1use crate::compositor::{DisplayList, DrawCommand};
7use strata_layout::Rect;
8use strata_primitives::geom::EdgeInsets;
9use strata_style::types::{BorderRadius, Color};
10
11pub const WGSL_ANALYTICAL_QUAD_SHADER: &str = r#"
13struct VertexInput {
14 @location(0) position: vec2<f32>,
15};
16
17struct InstanceInput {
18 @location(1) bounds: vec4<f32>,
19 @location(2) color: vec4<f32>,
20 @location(3) border_radius: vec4<f32>,
21 @location(4) border_width: vec4<f32>,
22 @location(5) border_color: vec4<f32>,
23 @location(6) clip_rect: vec4<f32>,
24};
25
26struct VertexOutput {
27 @builtin(position) clip_position: vec4<f32>,
28 @location(0) pixel_pos: vec2<f32>,
29 @location(1) bounds: vec4<f32>,
30 @location(2) color: vec4<f32>,
31 @location(3) border_radius: vec4<f32>,
32 @location(4) border_width: vec4<f32>,
33 @location(5) border_color: vec4<f32>,
34 @location(6) clip_rect: vec4<f32>,
35};
36
37struct Uniforms {
38 viewport_size: vec2<f32>,
39 _padding: vec2<f32>,
40};
41
42@group(0) @binding(0) var<uniform> uniforms: Uniforms;
43
44@vertex
45fn vs_main(model: VertexInput, instance: InstanceInput) -> VertexOutput {
46 var out: VertexOutput;
47 let pixel_coords = instance.bounds.xy + model.position * instance.bounds.zw;
48
49 let ndc_x = (pixel_coords.x / uniforms.viewport_size.x) * 2.0 - 1.0;
50 let ndc_y = 1.0 - (pixel_coords.y / uniforms.viewport_size.y) * 2.0;
51
52 out.clip_position = vec4<f32>(ndc_x, ndc_y, 0.0, 1.0);
53 out.pixel_pos = pixel_coords;
54 out.bounds = instance.bounds;
55 out.color = instance.color;
56 out.border_radius = instance.border_radius;
57 out.border_width = instance.border_width;
58 out.border_color = instance.border_color;
59 out.clip_rect = instance.clip_rect;
60 return out;
61}
62
63fn sd_rounded_rect(p: vec2<f32>, b: vec2<f32>, r: f32) -> f32 {
64 let q = abs(p) - b + vec2<f32>(r, r);
65 return length(max(q, vec2<f32>(0.0, 0.0))) + min(max(q.x, q.y), 0.0) - r;
66}
67
68@fragment
69fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
70 // Scissor clipping test
71 if (in.pixel_pos.x < in.clip_rect.x || in.pixel_pos.x > in.clip_rect.x + in.clip_rect.z ||
72 in.pixel_pos.y < in.clip_rect.y || in.pixel_pos.y > in.clip_rect.y + in.clip_rect.w) {
73 discard;
74 }
75
76 let center = in.bounds.xy + in.bounds.zw * 0.5;
77 let half_extents = in.bounds.zw * 0.5;
78 let p = in.pixel_pos - center;
79
80 // Corner radius selection per quadrant: [top_left, top_right, bottom_right, bottom_left]
81 var r: f32 = in.border_radius.x;
82 if (p.x >= 0.0 && p.y < 0.0) {
83 r = in.border_radius.y;
84 } else if (p.x >= 0.0 && p.y >= 0.0) {
85 r = in.border_radius.z;
86 } else if (p.x < 0.0 && p.y >= 0.0) {
87 r = in.border_radius.w;
88 }
89 r = min(r, min(half_extents.x, half_extents.y));
90
91 let dist = sd_rounded_rect(p, half_extents, r);
92 let coverage = clamp(0.5 - dist, 0.0, 1.0);
93
94 if (coverage <= 0.0) {
95 discard;
96 }
97
98 let bw = in.border_width.x;
99 if (bw > 0.0 && in.border_color.a > 0.0) {
100 let inner_dist = dist + bw;
101 let inner_cov = clamp(0.5 - inner_dist, 0.0, 1.0);
102
103 let border_alpha = in.border_color.a * coverage * (1.0 - inner_cov);
104 let fill_alpha = in.color.a * inner_cov;
105
106 let out_rgb = in.border_color.rgb * border_alpha + in.color.rgb * fill_alpha;
107 let out_a = border_alpha + fill_alpha;
108 return vec4<f32>(out_rgb, out_a);
109 }
110
111 return vec4<f32>(in.color.rgb, in.color.a * coverage);
112}
113"#;
114
115#[repr(C)]
117#[derive(Debug, Clone, Copy, PartialEq)]
118pub struct GpuVertex {
119 pub position: [f32; 2],
120}
121
122impl GpuVertex {
123 pub const fn new(x: f32, y: f32) -> Self {
124 Self { position: [x, y] }
125 }
126}
127
128pub const QUAD_VERTICES: [GpuVertex; 6] = [
130 GpuVertex::new(0.0, 0.0),
131 GpuVertex::new(1.0, 0.0),
132 GpuVertex::new(0.0, 1.0),
133 GpuVertex::new(0.0, 1.0),
134 GpuVertex::new(1.0, 0.0),
135 GpuVertex::new(1.0, 1.0),
136];
137
138#[repr(C)]
140#[derive(Debug, Clone, Copy, PartialEq)]
141pub struct GpuQuadInstance {
142 pub bounds: [f32; 4], pub color: [f32; 4], pub border_radius: [f32; 4], pub border_width: [f32; 4], pub border_color: [f32; 4], pub clip_rect: [f32; 4], }
149
150impl GpuQuadInstance {
151 pub const BYTE_SIZE: usize = std::mem::size_of::<Self>();
152
153 pub fn from_rect(bounds: Rect, color: Color, clip: Rect) -> Self {
155 let (r, g, b, a) = color.to_f32();
156 Self {
157 bounds: [bounds.x, bounds.y, bounds.width, bounds.height],
158 color: [r, g, b, a],
159 border_radius: [0.0; 4],
160 border_width: [0.0; 4],
161 border_color: [0.0; 4],
162 clip_rect: [clip.x, clip.y, clip.width, clip.height],
163 }
164 }
165
166 pub fn from_rounded_rect(
168 bounds: Rect,
169 color: Color,
170 radius: BorderRadius,
171 widths: EdgeInsets<f32>,
172 border_color: Option<Color>,
173 clip: Rect,
174 ) -> Self {
175 let (r, g, b, a) = color.to_f32();
176 let (br, bg, bb, ba) = border_color
177 .map(|c| c.to_f32())
178 .unwrap_or((0.0, 0.0, 0.0, 0.0));
179
180 Self {
181 bounds: [bounds.x, bounds.y, bounds.width, bounds.height],
182 color: [r, g, b, a],
183 border_radius: [
184 radius.top_left,
185 radius.top_right,
186 radius.bottom_right,
187 radius.bottom_left,
188 ],
189 border_width: [widths.top, widths.right, widths.bottom, widths.left],
190 border_color: [br, bg, bb, ba],
191 clip_rect: [clip.x, clip.y, clip.width, clip.height],
192 }
193 }
194
195 #[inline]
197 pub fn as_bytes(&self) -> &[u8] {
198 unsafe { std::slice::from_raw_parts((self as *const Self) as *const u8, Self::BYTE_SIZE) }
199 }
200
201 #[inline]
203 pub fn slice_to_bytes(slice: &[Self]) -> &[u8] {
204 unsafe {
205 std::slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len() * Self::BYTE_SIZE)
206 }
207 }
208}
209
210#[repr(C)]
212#[derive(Debug, Clone, Copy, PartialEq)]
213pub struct GpuUniforms {
214 pub viewport_size: [f32; 2],
215 pub _padding: [f32; 2],
216}
217
218impl GpuUniforms {
219 pub const BYTE_SIZE: usize = std::mem::size_of::<Self>();
220
221 pub fn new(width: f32, height: f32) -> Self {
222 Self {
223 viewport_size: [width, height],
224 _padding: [0.0, 0.0],
225 }
226 }
227
228 #[inline]
229 pub fn as_bytes(&self) -> &[u8] {
230 unsafe { std::slice::from_raw_parts((self as *const Self) as *const u8, Self::BYTE_SIZE) }
231 }
232}
233
234#[derive(Debug, Default, Clone, PartialEq)]
236pub struct GpuBatch {
237 pub instances: Vec<GpuQuadInstance>,
238}
239
240impl GpuBatch {
241 pub fn new() -> Self {
242 Self::default()
243 }
244
245 pub fn with_capacity(capacity: usize) -> Self {
246 Self {
247 instances: Vec::with_capacity(capacity),
248 }
249 }
250
251 #[inline]
252 pub fn push(&mut self, instance: GpuQuadInstance) {
253 self.instances.push(instance);
254 }
255
256 #[inline]
257 pub fn clear(&mut self) {
258 self.instances.clear();
259 }
260
261 #[inline]
262 pub fn len(&self) -> usize {
263 self.instances.len()
264 }
265
266 #[inline]
267 pub fn is_empty(&self) -> bool {
268 self.instances.is_empty()
269 }
270
271 #[inline]
272 pub fn as_bytes(&self) -> &[u8] {
273 GpuQuadInstance::slice_to_bytes(&self.instances)
274 }
275
276 pub fn from_display_list(
278 list: &DisplayList,
279 viewport_width: f32,
280 viewport_height: f32,
281 ) -> Self {
282 Self::from_display_list_damaged(list, None, viewport_width, viewport_height)
283 }
284
285 pub fn from_display_list_damaged(
287 list: &DisplayList,
288 damage: Option<Rect>,
289 viewport_width: f32,
290 viewport_height: f32,
291 ) -> Self {
292 let mut batch = Self::with_capacity(list.len());
293 let mut clip_stack: Vec<Rect> = Vec::new();
294 let mut transform_stack: Vec<strata_primitives::geom::Matrix4x4> = Vec::new();
295 let default_clip = damage.unwrap_or(Rect::new(0.0, 0.0, viewport_width, viewport_height));
296
297 for cmd in list.commands() {
298 if let DrawCommand::PushClip { bounds, .. } = cmd {
299 let combined = match clip_stack.last() {
300 Some(prev) => prev.intersect(*bounds).unwrap_or(Rect::zero()),
301 None => *bounds,
302 };
303 clip_stack.push(combined);
304 continue;
305 } else if let DrawCommand::PopClip = cmd {
306 clip_stack.pop();
307 continue;
308 } else if let DrawCommand::PushTransform { matrix } = cmd {
309 let combined = match transform_stack.last() {
310 Some(prev) => prev.multiply(matrix),
311 None => *matrix,
312 };
313 transform_stack.push(combined);
314 continue;
315 } else if let DrawCommand::PopTransform = cmd {
316 transform_stack.pop();
317 continue;
318 }
319
320 let current_clip = match clip_stack.last() {
321 Some(prev) => match prev.intersect(default_clip) {
322 Some(c) => c,
323 None => continue, },
325 None => default_clip,
326 };
327
328 let active_matrix = transform_stack.last();
329 let transform_rect_fn = |r: Rect| -> Rect {
330 if let Some(mat) = active_matrix {
331 if !mat.is_identity() {
332 let (x, y, w, h) = mat.transform_bounds(r.x, r.y, r.width, r.height);
333 return Rect::new(x, y, w, h);
334 }
335 }
336 r
337 };
338
339 let transformed_bounds = cmd.bounds().map(transform_rect_fn);
341 if let Some(cmd_bounds) = transformed_bounds {
342 if cmd_bounds.intersect(current_clip).is_none() {
343 continue;
344 }
345 }
346
347 match cmd {
348 DrawCommand::DrawRect { bounds, color } => {
349 batch.push(GpuQuadInstance::from_rect(
350 transform_rect_fn(*bounds),
351 *color,
352 current_clip,
353 ));
354 }
355 DrawCommand::DrawRoundedRect {
356 bounds,
357 color,
358 border_radius,
359 border_width,
360 border_color,
361 } => {
362 batch.push(GpuQuadInstance::from_rounded_rect(
363 transform_rect_fn(*bounds),
364 *color,
365 *border_radius,
366 *border_width,
367 *border_color,
368 current_clip,
369 ));
370 }
371 DrawCommand::DrawBorder {
372 bounds,
373 widths,
374 color,
375 border_radius,
376 ..
377 } => {
378 batch.push(GpuQuadInstance::from_rounded_rect(
379 transform_rect_fn(*bounds),
380 Color::TRANSPARENT,
381 *border_radius,
382 *widths,
383 Some(*color),
384 current_clip,
385 ));
386 }
387 DrawCommand::DrawCanvas2D { bounds, commands } => {
388 if let Some(base_clip) = transform_rect_fn(*bounds).intersect(current_clip) {
389 let mut active_clip = Some(base_clip);
390 let mut clip_stack: Vec<Option<Rect>> = Vec::new();
391 for ccmd in commands {
392 match ccmd {
393 crate::canvas2d::CanvasCommand::Save => {
394 clip_stack.push(active_clip);
395 }
396 crate::canvas2d::CanvasCommand::Restore => {
397 if let Some(prev) = clip_stack.pop() {
398 active_clip = prev;
399 }
400 }
401 crate::canvas2d::CanvasCommand::ClipPath { verbs } => {
402 if let Some(vbbox) =
403 crate::canvas2d::canvas_verbs_bounds(verbs, bounds.x, bounds.y)
404 {
405 let tb = transform_rect_fn(vbbox);
406 active_clip = active_clip.and_then(|c| c.intersect(tb));
407 }
408 }
409 crate::canvas2d::CanvasCommand::FillRect {
410 bounds: rb,
411 color,
412 } => {
413 if let Some(canvas_clip) = active_clip {
414 let r = Rect::new(
415 bounds.x + rb.x,
416 bounds.y + rb.y,
417 rb.width,
418 rb.height,
419 );
420 batch.push(GpuQuadInstance::from_rect(
421 transform_rect_fn(r),
422 *color,
423 canvas_clip,
424 ));
425 }
426 }
427 crate::canvas2d::CanvasCommand::StrokeRect {
428 bounds: rb,
429 color,
430 line_width,
431 } => {
432 if let Some(canvas_clip) = active_clip {
433 let r = Rect::new(
434 bounds.x + rb.x,
435 bounds.y + rb.y,
436 rb.width,
437 rb.height,
438 );
439 batch.push(GpuQuadInstance::from_rounded_rect(
440 transform_rect_fn(r),
441 Color::TRANSPARENT,
442 BorderRadius::default(),
443 EdgeInsets::all(*line_width),
444 Some(*color),
445 canvas_clip,
446 ));
447 }
448 }
449 _ => {}
450 }
451 }
452 }
453 }
454 _ => {}
455 }
456 }
457
458 batch
459 }
460}
461
462#[derive(Debug, Clone)]
467pub struct GpuSlugTextPipeline {
468 pub glyph_cache: strata_gpu_path::AnalyticGlyphCache,
469 pub buffer: strata_gpu_path::SlugGlyphBuffer,
470 pub total_glyphs: usize,
471 pub total_curves: usize,
472}
473
474impl Default for GpuSlugTextPipeline {
475 fn default() -> Self {
476 Self::new()
477 }
478}
479
480impl GpuSlugTextPipeline {
481 pub fn new() -> Self {
482 Self {
483 glyph_cache: strata_gpu_path::AnalyticGlyphCache::with_standard_ascii(),
484 buffer: strata_gpu_path::SlugGlyphBuffer::new(),
485 total_glyphs: 0,
486 total_curves: 0,
487 }
488 }
489
490 pub fn clear(&mut self) {
491 self.buffer.clear();
492 self.total_glyphs = 0;
493 self.total_curves = 0;
494 }
495
496 pub fn sync_barrier(&self) -> u64 {
498 self.buffer.sync_barrier()
499 }
500
501 pub fn is_fence_synchronized(&self, fence: u64) -> bool {
503 self.buffer.is_fence_synchronized(fence)
504 }
505
506 pub fn compile_display_list(
508 &mut self,
509 list: &DisplayList,
510 viewport_width: f32,
511 viewport_height: f32,
512 damage: Option<Rect>,
513 ) -> usize {
514 self.clear();
515 let default_clip = damage.unwrap_or(Rect::new(0.0, 0.0, viewport_width, viewport_height));
516
517 for cmd in list.commands() {
518 match cmd {
519 DrawCommand::DrawText {
520 origin,
521 text,
522 font_size,
523 color,
524 ..
525 } => {
526 let (r, g, b, a) = color.to_f32();
527 let color_f32 = [r, g, b, a];
528 let mut cursor_x = origin.0;
529 let cursor_y = origin.1;
530
531 for ch in text.chars() {
532 if let Some(glyph) = self.glyph_cache.get(ch) {
533 let scale = *font_size;
534 let glyph_w = glyph.advance_width * scale;
535 let glyph_h = scale;
536 let screen_bounds = strata_gpu_path::Rect2D::new(
537 cursor_x,
538 cursor_y,
539 cursor_x + glyph_w,
540 cursor_y + glyph_h,
541 );
542
543 let clip_r = strata_gpu_path::Rect2D::new(
544 default_clip.x,
545 default_clip.y,
546 default_clip.x + default_clip.width,
547 default_clip.y + default_clip.height,
548 );
549
550 if default_clip
551 .intersect(Rect::new(cursor_x, cursor_y, glyph_w, glyph_h))
552 .is_some()
553 {
554 self.buffer
555 .push_glyph(glyph, screen_bounds, color_f32, clip_r);
556 self.total_glyphs += 1;
557 }
558 cursor_x += glyph_w;
559 } else {
560 cursor_x += *font_size * 0.5;
561 }
562 }
563 }
564 DrawCommand::DrawTextFragments { fragments } => {
565 for frag in fragments {
566 let (r, g, b, a) = frag.style.color.to_f32();
567 let color_f32 = [r, g, b, a];
568 let mut cursor_x = frag.bounds.x;
569 let cursor_y = frag.bounds.y;
570
571 for ch in frag.text.chars() {
572 if let Some(glyph) = self.glyph_cache.get(ch) {
573 let scale = frag.style.font_size;
574 let glyph_w = glyph.advance_width * scale;
575 let glyph_h = scale;
576 let screen_bounds = strata_gpu_path::Rect2D::new(
577 cursor_x,
578 cursor_y,
579 cursor_x + glyph_w,
580 cursor_y + glyph_h,
581 );
582
583 let clip_r = strata_gpu_path::Rect2D::new(
584 default_clip.x,
585 default_clip.y,
586 default_clip.x + default_clip.width,
587 default_clip.y + default_clip.height,
588 );
589
590 if default_clip
591 .intersect(Rect::new(cursor_x, cursor_y, glyph_w, glyph_h))
592 .is_some()
593 {
594 self.buffer
595 .push_glyph(glyph, screen_bounds, color_f32, clip_r);
596 self.total_glyphs += 1;
597 }
598 cursor_x += glyph_w;
599 } else {
600 cursor_x += frag.style.font_size * 0.5;
601 }
602 }
603 }
604 }
605 DrawCommand::DrawCanvas2D { bounds, commands } => {
606 let Some(base_clip) = bounds.intersect(default_clip) else {
607 continue;
608 };
609 let mut active_clip = Some(base_clip);
610 let mut clip_stack: Vec<Option<Rect>> = Vec::new();
611
612 for ccmd in commands {
613 match ccmd {
614 crate::canvas2d::CanvasCommand::Save => {
615 clip_stack.push(active_clip);
616 }
617 crate::canvas2d::CanvasCommand::Restore => {
618 if let Some(prev) = clip_stack.pop() {
619 active_clip = prev;
620 }
621 }
622 crate::canvas2d::CanvasCommand::ClipPath { verbs } => {
623 if let Some(vbbox) =
624 crate::canvas2d::canvas_verbs_bounds(verbs, bounds.x, bounds.y)
625 {
626 active_clip = active_clip.and_then(|c| c.intersect(vbbox));
627 }
628 }
629 crate::canvas2d::CanvasCommand::FillText {
630 text,
631 x,
632 y,
633 color,
634 font_size,
635 text_align,
636 text_baseline,
637 max_width,
638 ..
639 }
640 | crate::canvas2d::CanvasCommand::StrokeText {
641 text,
642 x,
643 y,
644 color,
645 font_size,
646 text_align,
647 text_baseline,
648 max_width,
649 ..
650 } => {
651 let Some(canvas_clip) = active_clip else {
652 continue;
653 };
654 let scale = *font_size;
655 let raw_w: f32 = text
656 .chars()
657 .map(|ch| {
658 self.glyph_cache
659 .get(ch)
660 .map(|g| g.advance_width * scale)
661 .unwrap_or(scale * 0.5)
662 })
663 .sum();
664 let x_squeeze = match max_width {
665 Some(mw) if *mw > 0.0 && raw_w > *mw => *mw / raw_w,
666 _ => 1.0,
667 };
668 let total_w = raw_w * x_squeeze;
669 let mut cursor_x = bounds.x
670 + match text_align {
671 crate::canvas2d::CanvasTextAlign::Left
672 | crate::canvas2d::CanvasTextAlign::Start => *x,
673 crate::canvas2d::CanvasTextAlign::Center => {
674 *x - total_w * 0.5
675 }
676 crate::canvas2d::CanvasTextAlign::Right
677 | crate::canvas2d::CanvasTextAlign::End => *x - total_w,
678 };
679 let cursor_y = bounds.y
680 + match text_baseline {
681 crate::canvas2d::CanvasTextBaseline::Top
682 | crate::canvas2d::CanvasTextBaseline::Hanging => *y,
683 crate::canvas2d::CanvasTextBaseline::Middle => {
684 *y - scale * 0.5
685 }
686 crate::canvas2d::CanvasTextBaseline::Bottom
687 | crate::canvas2d::CanvasTextBaseline::Ideographic => {
688 *y - scale
689 }
690 crate::canvas2d::CanvasTextBaseline::Alphabetic => {
691 *y - scale * 0.8
692 }
693 };
694
695 let (r, g, b, a) = color.to_f32();
696 let color_f32 = [r, g, b, a];
697 let clip_r = strata_gpu_path::Rect2D::new(
698 canvas_clip.x,
699 canvas_clip.y,
700 canvas_clip.x + canvas_clip.width,
701 canvas_clip.y + canvas_clip.height,
702 );
703
704 for ch in text.chars() {
705 if let Some(glyph) = self.glyph_cache.get(ch) {
706 let glyph_w = glyph.advance_width * scale * x_squeeze;
707 let glyph_h = scale;
708 let screen_bounds = strata_gpu_path::Rect2D::new(
709 cursor_x,
710 cursor_y,
711 cursor_x + glyph_w,
712 cursor_y + glyph_h,
713 );
714 if canvas_clip
715 .intersect(Rect::new(
716 cursor_x, cursor_y, glyph_w, glyph_h,
717 ))
718 .is_some()
719 {
720 self.buffer.push_glyph(
721 glyph,
722 screen_bounds,
723 color_f32,
724 clip_r,
725 );
726 self.total_glyphs += 1;
727 }
728 cursor_x += glyph_w;
729 } else {
730 cursor_x += scale * 0.5 * x_squeeze;
731 }
732 }
733 }
734 _ => {}
735 }
736 }
737 }
738 _ => {}
739 }
740 }
741
742 self.total_curves = self.buffer.curves.len();
743 self.total_glyphs
744 }
745
746 #[inline]
747 pub fn instance_bytes(&self) -> &[u8] {
748 self.buffer.instances_as_bytes()
749 }
750
751 #[inline]
752 pub fn curve_bytes(&self) -> &[u8] {
753 self.buffer.curves_as_bytes()
754 }
755}
756
757#[derive(Debug, Clone)]
759pub struct GpuPresentationPipeline {
760 pub viewport_width: f32,
761 pub viewport_height: f32,
762 pub uniforms: GpuUniforms,
763 pub batch: GpuBatch,
764 pub text_pipeline: GpuSlugTextPipeline,
765 pub total_uploaded_bytes: usize,
766 pub compiled_frames: u64,
767}
768
769impl GpuPresentationPipeline {
770 pub fn new(viewport_width: f32, viewport_height: f32) -> Self {
771 Self {
772 viewport_width,
773 viewport_height,
774 uniforms: GpuUniforms::new(viewport_width, viewport_height),
775 batch: GpuBatch::new(),
776 text_pipeline: GpuSlugTextPipeline::new(),
777 total_uploaded_bytes: 0,
778 compiled_frames: 0,
779 }
780 }
781
782 pub fn resize(&mut self, width: f32, height: f32) {
783 self.viewport_width = width;
784 self.viewport_height = height;
785 self.uniforms = GpuUniforms::new(width, height);
786 }
787
788 pub fn compile_frame(&mut self, list: &DisplayList, damage: Option<Rect>) -> usize {
791 self.batch = GpuBatch::from_display_list_damaged(
792 list,
793 damage,
794 self.viewport_width,
795 self.viewport_height,
796 );
797
798 let glyph_count = self.text_pipeline.compile_display_list(
799 list,
800 self.viewport_width,
801 self.viewport_height,
802 damage,
803 );
804
805 let byte_count = self.batch.as_bytes().len()
806 + self.uniforms.as_bytes().len()
807 + self.text_pipeline.instance_bytes().len()
808 + self.text_pipeline.curve_bytes().len();
809 self.total_uploaded_bytes += byte_count;
810 self.compiled_frames += 1;
811
812 self.batch.len() + glyph_count
813 }
814
815 #[inline]
816 pub fn instance_bytes(&self) -> &[u8] {
817 self.batch.as_bytes()
818 }
819
820 #[inline]
821 pub fn uniform_bytes(&self) -> &[u8] {
822 self.uniforms.as_bytes()
823 }
824}
825
826#[derive(Debug, Default, Clone, PartialEq)]
828pub struct GpuPathBatch {
829 pub segments: Vec<strata_gpu_path::GpuPathSegment>,
830}
831
832impl GpuPathBatch {
833 pub fn new() -> Self {
834 Self::default()
835 }
836
837 pub fn with_capacity(capacity: usize) -> Self {
838 Self {
839 segments: Vec::with_capacity(capacity),
840 }
841 }
842
843 #[inline]
844 pub fn push(&mut self, segment: strata_gpu_path::GpuPathSegment) {
845 self.segments.push(segment);
846 }
847
848 #[inline]
849 pub fn clear(&mut self) {
850 self.segments.clear();
851 }
852
853 #[inline]
854 pub fn len(&self) -> usize {
855 self.segments.len()
856 }
857
858 #[inline]
859 pub fn is_empty(&self) -> bool {
860 self.segments.is_empty()
861 }
862
863 #[inline]
864 pub fn as_bytes(&self) -> &[u8] {
865 strata_gpu_path::GpuPathSegment::slice_to_bytes(&self.segments)
866 }
867
868 pub fn from_display_list(
870 list: &DisplayList,
871 viewport_width: f32,
872 viewport_height: f32,
873 ) -> Self {
874 Self::from_display_list_damaged(list, None, viewport_width, viewport_height)
875 }
876
877 pub fn from_display_list_damaged(
879 list: &DisplayList,
880 damage: Option<Rect>,
881 viewport_width: f32,
882 viewport_height: f32,
883 ) -> Self {
884 let mut batch = Self::new();
885 let mut clip_stack: Vec<Rect> = Vec::new();
886 let default_clip = damage.unwrap_or(Rect::new(0.0, 0.0, viewport_width, viewport_height));
887
888 for cmd in list.commands() {
889 if let DrawCommand::PushClip { bounds, .. } = cmd {
890 let combined = match clip_stack.last() {
891 Some(prev) => prev.intersect(*bounds).unwrap_or(Rect::zero()),
892 None => *bounds,
893 };
894 clip_stack.push(combined);
895 continue;
896 } else if let DrawCommand::PopClip = cmd {
897 clip_stack.pop();
898 continue;
899 }
900
901 let current_clip = match clip_stack.last() {
902 Some(prev) => match prev.intersect(default_clip) {
903 Some(c) => c,
904 None => continue,
905 },
906 None => default_clip,
907 };
908
909 match cmd {
910 DrawCommand::DrawGpuPath {
911 bounds,
912 path,
913 stroke,
914 fill_color,
915 stroke_color,
916 transform: _,
917 } => {
918 if bounds.intersect(current_clip).is_none() {
919 continue;
920 }
921
922 let quads = path.to_quadratics(0.25);
923 let mut flags = 0;
924 if fill_color.is_some() {
925 flags |= strata_gpu_path::FLAG_FILL;
926 }
927 if stroke_color.is_some() {
928 flags |= strata_gpu_path::FLAG_STROKE;
929 }
930 if path.fill_rule == Some(strata_gpu_path::FillRule::EvenOdd) {
931 flags |= strata_gpu_path::FLAG_EVEN_ODD;
932 }
933
934 let color_f32 = if let Some(fc) = fill_color {
935 let (r, g, b, a) = fc.to_f32();
936 [r, g, b, a]
937 } else if let Some(sc) = stroke_color {
938 let (r, g, b, a) = sc.to_f32();
939 [r, g, b, a]
940 } else {
941 [1.0, 1.0, 1.0, 1.0]
942 };
943
944 let stroke_w = stroke.map(|s| s.width).unwrap_or(1.0);
945
946 for q in quads {
947 batch.push(strata_gpu_path::GpuPathSegment::from_quadratic(
948 &q, stroke_w, flags, color_f32, 0.0,
949 ));
950 }
951 }
952 DrawCommand::DrawSvgPath {
953 bounds,
954 path_data,
955 stroke_color,
956 fill_color,
957 stroke_width,
958 stroke_dasharray,
959 fill_rule,
960 view_box,
961 ..
962 } => {
963 if bounds.intersect(current_clip).is_none() {
964 continue;
965 }
966 let scale_x = if view_box.0 > 0.0 {
967 bounds.width / view_box.0
968 } else {
969 1.0
970 };
971 let scale_y = if view_box.1 > 0.0 {
972 bounds.height / view_box.1
973 } else {
974 1.0
975 };
976 let avg_scale = ((scale_x + scale_y) * 0.5).max(0.001);
977 let parsed = strata_gpu_path::PathBuilder::from_svg(path_data);
978 let quads: Vec<strata_gpu_path::QuadraticBezier> = parsed
979 .to_quadratics(0.25)
980 .into_iter()
981 .map(|q| {
982 strata_gpu_path::QuadraticBezier::new(
983 strata_gpu_path::Point2D::new(
984 bounds.x + q.p0.x * scale_x,
985 bounds.y + q.p0.y * scale_y,
986 ),
987 strata_gpu_path::Point2D::new(
988 bounds.x + q.p1.x * scale_x,
989 bounds.y + q.p1.y * scale_y,
990 ),
991 strata_gpu_path::Point2D::new(
992 bounds.x + q.p2.x * scale_x,
993 bounds.y + q.p2.y * scale_y,
994 ),
995 )
996 })
997 .collect();
998
999 let even_odd = if *fill_rule == strata_layout::FillRule::EvenOdd {
1000 strata_gpu_path::FLAG_EVEN_ODD
1001 } else {
1002 0
1003 };
1004
1005 if let Some(fc) = fill_color {
1006 let (r, g, b, a) = fc.to_f32();
1007 let flags = strata_gpu_path::FLAG_FILL | even_odd;
1008 for q in &quads {
1009 batch.push(strata_gpu_path::GpuPathSegment::from_quadratic(
1010 q,
1011 *stroke_width * avg_scale,
1012 flags,
1013 [r, g, b, a],
1014 0.0,
1015 ));
1016 }
1017 }
1018
1019 if let Some(sc) = stroke_color {
1020 let (r, g, b, a) = sc.to_f32();
1021 let flags = strata_gpu_path::FLAG_STROKE | even_odd;
1022 let sw = *stroke_width * avg_scale;
1023 let has_dashes = stroke_dasharray.iter().any(|&d| d > 0.0);
1024 if has_dashes {
1025 let scaled_dashes: Vec<f32> =
1026 stroke_dasharray.iter().map(|&d| d * avg_scale).collect();
1027 for dash_sub in
1028 strata_gpu_path::dash_quadratics(&quads, &scaled_dashes)
1029 {
1030 for q in &dash_sub {
1031 batch.push(strata_gpu_path::GpuPathSegment::from_quadratic(
1032 q,
1033 sw,
1034 flags,
1035 [r, g, b, a],
1036 0.0,
1037 ));
1038 }
1039 }
1040 } else {
1041 for q in &quads {
1042 batch.push(strata_gpu_path::GpuPathSegment::from_quadratic(
1043 q,
1044 sw,
1045 flags,
1046 [r, g, b, a],
1047 0.0,
1048 ));
1049 }
1050 }
1051 }
1052 }
1053 DrawCommand::DrawCanvas2D { bounds, commands } => {
1054 let Some(base_clip) = bounds.intersect(current_clip) else {
1055 continue;
1056 };
1057 let ox = bounds.x;
1058 let oy = bounds.y;
1059 let mut active_clip = Some(base_clip);
1060 let mut line_dash: Vec<f32> = Vec::new();
1061 let mut state_stack: Vec<(Option<Rect>, Vec<f32>)> = Vec::new();
1062
1063 let quad_intersects_clip = |q: &strata_gpu_path::QuadraticBezier,
1064 clip: Rect,
1065 pad: f32|
1066 -> bool {
1067 let min_x = q.p0.x.min(q.p1.x).min(q.p2.x) - pad;
1068 let max_x = q.p0.x.max(q.p1.x).max(q.p2.x) + pad;
1069 let min_y = q.p0.y.min(q.p1.y).min(q.p2.y) - pad;
1070 let max_y = q.p0.y.max(q.p1.y).max(q.p2.y) + pad;
1071 clip.intersect(Rect::new(
1072 min_x,
1073 min_y,
1074 (max_x - min_x).max(1.0),
1075 (max_y - min_y).max(1.0),
1076 ))
1077 .is_some()
1078 };
1079
1080 let push_stroke_quads = |batch: &mut Self,
1081 quads: &[strata_gpu_path::QuadraticBezier],
1082 sw: f32,
1083 col: Color,
1084 dash: &[f32],
1085 clip_opt: Option<Rect>| {
1086 let Some(clip) = clip_opt else {
1087 return;
1088 };
1089 let (cr, cg, cb, ca) = col.to_f32();
1090 let c = [cr, cg, cb, ca];
1091 let pad = sw.max(1.0);
1092 let has_dashes = dash.iter().any(|&d| d > 0.0);
1093 if has_dashes {
1094 for dash_sub in strata_gpu_path::dash_quadratics(quads, dash) {
1095 for q in &dash_sub {
1096 if quad_intersects_clip(q, clip, pad) {
1097 batch.push(
1098 strata_gpu_path::GpuPathSegment::from_quadratic(
1099 q,
1100 sw,
1101 strata_gpu_path::FLAG_STROKE,
1102 c,
1103 0.0,
1104 ),
1105 );
1106 }
1107 }
1108 }
1109 } else {
1110 for q in quads {
1111 if quad_intersects_clip(q, clip, pad) {
1112 batch.push(strata_gpu_path::GpuPathSegment::from_quadratic(
1113 q,
1114 sw,
1115 strata_gpu_path::FLAG_STROKE,
1116 c,
1117 0.0,
1118 ));
1119 }
1120 }
1121 }
1122 };
1123
1124 let push_fill_quads = |batch: &mut Self,
1125 quads: &[strata_gpu_path::QuadraticBezier],
1126 sw: f32,
1127 col: Color,
1128 clip_opt: Option<Rect>| {
1129 if clip_opt.is_none() {
1130 return;
1131 }
1132 let (cr, cg, cb, ca) = col.to_f32();
1133 let c = [cr, cg, cb, ca];
1134 for q in quads {
1135 batch.push(strata_gpu_path::GpuPathSegment::from_quadratic(
1136 q,
1137 sw,
1138 strata_gpu_path::FLAG_FILL,
1139 c,
1140 0.0,
1141 ));
1142 }
1143 };
1144
1145 let rect_quads = |r: Rect| -> [strata_gpu_path::QuadraticBezier; 4] {
1146 let p0 = strata_gpu_path::Point2D::new(ox + r.x, oy + r.y);
1147 let p1 = strata_gpu_path::Point2D::new(ox + r.x + r.width, oy + r.y);
1148 let p2 =
1149 strata_gpu_path::Point2D::new(ox + r.x + r.width, oy + r.y + r.height);
1150 let p3 = strata_gpu_path::Point2D::new(ox + r.x, oy + r.y + r.height);
1151 [
1152 strata_gpu_path::QuadraticBezier::new(p0, p0.lerp(p1, 0.5), p1),
1153 strata_gpu_path::QuadraticBezier::new(p1, p1.lerp(p2, 0.5), p2),
1154 strata_gpu_path::QuadraticBezier::new(p2, p2.lerp(p3, 0.5), p3),
1155 strata_gpu_path::QuadraticBezier::new(p3, p3.lerp(p0, 0.5), p0),
1156 ]
1157 };
1158
1159 for ccmd in commands {
1160 match ccmd {
1161 crate::canvas2d::CanvasCommand::Save => {
1162 state_stack.push((active_clip, line_dash.clone()));
1163 }
1164 crate::canvas2d::CanvasCommand::Restore => {
1165 if let Some((prev_clip, prev_dash)) = state_stack.pop() {
1166 active_clip = prev_clip;
1167 line_dash = prev_dash;
1168 }
1169 }
1170 crate::canvas2d::CanvasCommand::SetLineDash { segments, .. } => {
1171 line_dash = segments.clone();
1172 }
1173 crate::canvas2d::CanvasCommand::ClipPath { verbs } => {
1174 if let Some(vbbox) =
1175 crate::canvas2d::canvas_verbs_bounds(verbs, ox, oy)
1176 {
1177 active_clip = active_clip.and_then(|c| c.intersect(vbbox));
1178 }
1179 }
1180 crate::canvas2d::CanvasCommand::FillRect {
1181 bounds: rb,
1182 color,
1183 } => {
1184 let world_rect =
1185 Rect::new(ox + rb.x, oy + rb.y, rb.width, rb.height);
1186 if active_clip
1187 .and_then(|c| c.intersect(world_rect))
1188 .is_some()
1189 {
1190 let quads = rect_quads(*rb);
1191 push_fill_quads(&mut batch, &quads, 1.0, *color, active_clip);
1192 }
1193 }
1194 crate::canvas2d::CanvasCommand::StrokeRect {
1195 bounds: rb,
1196 color,
1197 line_width,
1198 } => {
1199 let quads = rect_quads(*rb);
1200 push_stroke_quads(
1201 &mut batch,
1202 &quads,
1203 *line_width,
1204 *color,
1205 &line_dash,
1206 active_clip,
1207 );
1208 }
1209 crate::canvas2d::CanvasCommand::DrawLine {
1210 p0,
1211 p1,
1212 color,
1213 line_width,
1214 } => {
1215 let a = strata_gpu_path::Point2D::new(ox + p0.0, oy + p0.1);
1216 let b = strata_gpu_path::Point2D::new(ox + p1.0, oy + p1.1);
1217 let q = strata_gpu_path::QuadraticBezier::new(a, a.lerp(b, 0.5), b);
1218 push_stroke_quads(
1219 &mut batch,
1220 &[q],
1221 *line_width,
1222 *color,
1223 &line_dash,
1224 active_clip,
1225 );
1226 }
1227 crate::canvas2d::CanvasCommand::DrawCircle {
1228 center,
1229 radius,
1230 fill_color,
1231 stroke_color,
1232 line_width,
1233 } => {
1234 let cx = ox + center.0;
1235 let cy = oy + center.1;
1236 let r = *radius;
1237 let segs = 8usize;
1238 let mut circle_quads = Vec::with_capacity(segs);
1239 for i in 0..segs {
1240 let a0 = (i as f32 / segs as f32) * std::f32::consts::TAU;
1241 let a1 =
1242 ((i + 1) as f32 / segs as f32) * std::f32::consts::TAU;
1243 let am = (a0 + a1) * 0.5;
1244 let cos_half = ((a1 - a0) * 0.5).cos().max(0.1);
1245 let p0 = strata_gpu_path::Point2D::new(
1246 cx + r * a0.cos(),
1247 cy + r * a0.sin(),
1248 );
1249 let p2 = strata_gpu_path::Point2D::new(
1250 cx + r * a1.cos(),
1251 cy + r * a1.sin(),
1252 );
1253 let p1 = strata_gpu_path::Point2D::new(
1254 cx + (r / cos_half) * am.cos(),
1255 cy + (r / cos_half) * am.sin(),
1256 );
1257 circle_quads
1258 .push(strata_gpu_path::QuadraticBezier::new(p0, p1, p2));
1259 }
1260 if let Some(fc) = fill_color {
1261 push_fill_quads(
1262 &mut batch,
1263 &circle_quads,
1264 *line_width,
1265 *fc,
1266 active_clip,
1267 );
1268 }
1269 if let Some(sc) = stroke_color {
1270 push_stroke_quads(
1271 &mut batch,
1272 &circle_quads,
1273 *line_width,
1274 *sc,
1275 &line_dash,
1276 active_clip,
1277 );
1278 }
1279 }
1280 crate::canvas2d::CanvasCommand::DrawPath {
1281 verbs,
1282 fill_color,
1283 stroke_color,
1284 line_width,
1285 } => {
1286 let mut start = strata_gpu_path::Point2D::new(ox, oy);
1287 let mut cur = start;
1288 let mut path_quads = Vec::new();
1289 for v in verbs {
1290 match *v {
1291 crate::canvas2d::CanvasPathVerb::MoveTo(x, y) => {
1292 cur = strata_gpu_path::Point2D::new(ox + x, oy + y);
1293 start = cur;
1294 }
1295 crate::canvas2d::CanvasPathVerb::LineTo(x, y) => {
1296 let next =
1297 strata_gpu_path::Point2D::new(ox + x, oy + y);
1298 path_quads.push(strata_gpu_path::QuadraticBezier::new(
1299 cur,
1300 cur.lerp(next, 0.5),
1301 next,
1302 ));
1303 cur = next;
1304 }
1305 crate::canvas2d::CanvasPathVerb::QuadraticCurveTo {
1306 cpx,
1307 cpy,
1308 x,
1309 y,
1310 } => {
1311 let cp =
1312 strata_gpu_path::Point2D::new(ox + cpx, oy + cpy);
1313 let next =
1314 strata_gpu_path::Point2D::new(ox + x, oy + y);
1315 path_quads.push(strata_gpu_path::QuadraticBezier::new(
1316 cur, cp, next,
1317 ));
1318 cur = next;
1319 }
1320 crate::canvas2d::CanvasPathVerb::BezierCurveTo {
1321 cp1x,
1322 cp1y,
1323 cp2x,
1324 cp2y,
1325 x,
1326 y,
1327 } => {
1328 let cp1 = strata_gpu_path::Point2D::new(
1329 ox + cp1x,
1330 oy + cp1y,
1331 );
1332 let cp2 = strata_gpu_path::Point2D::new(
1333 ox + cp2x,
1334 oy + cp2y,
1335 );
1336 let next =
1337 strata_gpu_path::Point2D::new(ox + x, oy + y);
1338 let cubic = strata_gpu_path::CubicBezier::new(
1339 cur, cp1, cp2, next,
1340 );
1341 path_quads.extend(cubic.to_quadratics(0.25));
1342 cur = next;
1343 }
1344 crate::canvas2d::CanvasPathVerb::Arc {
1345 cx,
1346 cy,
1347 radius,
1348 start_angle,
1349 end_angle,
1350 counter_clockwise,
1351 } => {
1352 let acx = ox + cx;
1353 let acy = oy + cy;
1354 let mut sweep = end_angle - start_angle;
1355 if counter_clockwise && sweep > 0.0 {
1356 sweep -= std::f32::consts::TAU;
1357 } else if !counter_clockwise && sweep < 0.0 {
1358 sweep += std::f32::consts::TAU;
1359 }
1360 let steps = 8usize;
1361 for i in 0..steps {
1362 let t0 =
1363 start_angle + sweep * (i as f32 / steps as f32);
1364 let t1 = start_angle
1365 + sweep * ((i + 1) as f32 / steps as f32);
1366 let p0 = strata_gpu_path::Point2D::new(
1367 acx + radius * t0.cos(),
1368 acy + radius * t0.sin(),
1369 );
1370 let p2 = strata_gpu_path::Point2D::new(
1371 acx + radius * t1.cos(),
1372 acy + radius * t1.sin(),
1373 );
1374 path_quads.push(
1375 strata_gpu_path::QuadraticBezier::new(
1376 p0,
1377 p0.lerp(p2, 0.5),
1378 p2,
1379 ),
1380 );
1381 cur = p2;
1382 }
1383 }
1384 crate::canvas2d::CanvasPathVerb::Close => {
1385 if cur.distance_squared(start) > 1e-4 {
1386 path_quads.push(
1387 strata_gpu_path::QuadraticBezier::new(
1388 cur,
1389 cur.lerp(start, 0.5),
1390 start,
1391 ),
1392 );
1393 cur = start;
1394 }
1395 }
1396 }
1397 }
1398 if let Some(fc) = fill_color {
1399 push_fill_quads(
1400 &mut batch,
1401 &path_quads,
1402 *line_width,
1403 *fc,
1404 active_clip,
1405 );
1406 }
1407 if let Some(sc) = stroke_color {
1408 push_stroke_quads(
1409 &mut batch,
1410 &path_quads,
1411 *line_width,
1412 *sc,
1413 &line_dash,
1414 active_clip,
1415 );
1416 }
1417 }
1418 crate::canvas2d::CanvasCommand::ClearRect { .. }
1419 | crate::canvas2d::CanvasCommand::FillText { .. }
1420 | crate::canvas2d::CanvasCommand::StrokeText { .. } => {}
1421 }
1422 }
1423 }
1424 _ => {}
1425 }
1426 }
1427
1428 batch
1429 }
1430}
1431
1432#[derive(Debug, Clone)]
1434pub struct GpuPathPipeline {
1435 pub viewport_width: f32,
1436 pub viewport_height: f32,
1437 pub uniforms: strata_gpu_path::GpuPathUniforms,
1438 pub batch: GpuPathBatch,
1439 pub total_uploaded_bytes: usize,
1440 pub compiled_frames: u64,
1441}
1442
1443impl GpuPathPipeline {
1444 pub fn new(viewport_width: f32, viewport_height: f32) -> Self {
1445 Self {
1446 viewport_width,
1447 viewport_height,
1448 uniforms: strata_gpu_path::GpuPathUniforms::new(
1449 viewport_width,
1450 viewport_height,
1451 0.25,
1452 0,
1453 ),
1454 batch: GpuPathBatch::new(),
1455 total_uploaded_bytes: 0,
1456 compiled_frames: 0,
1457 }
1458 }
1459
1460 pub fn resize(&mut self, width: f32, height: f32) {
1461 self.viewport_width = width;
1462 self.viewport_height = height;
1463 self.uniforms =
1464 strata_gpu_path::GpuPathUniforms::new(width, height, 0.25, self.batch.len() as u32);
1465 }
1466
1467 pub fn compile_frame(&mut self, list: &DisplayList, damage: Option<Rect>) -> usize {
1469 let has_paths = list.commands().iter().any(|cmd| {
1472 matches!(
1473 cmd,
1474 DrawCommand::DrawGpuPath { .. }
1475 | DrawCommand::DrawSvgPath { .. }
1476 | DrawCommand::DrawCanvas2D { .. }
1477 )
1478 });
1479 if !has_paths {
1480 if !self.batch.is_empty() {
1481 self.batch.clear();
1482 self.uniforms.curve_count = 0;
1483 }
1484 return 0;
1485 }
1486 self.batch = GpuPathBatch::from_display_list_damaged(
1487 list,
1488 damage,
1489 self.viewport_width,
1490 self.viewport_height,
1491 );
1492
1493 self.uniforms.curve_count = self.batch.len() as u32;
1494 let byte_count = self.batch.as_bytes().len() + self.uniforms.as_bytes().len();
1495 self.total_uploaded_bytes += byte_count;
1496 self.compiled_frames += 1;
1497
1498 self.batch.len()
1499 }
1500
1501 #[inline]
1502 pub fn segment_bytes(&self) -> &[u8] {
1503 self.batch.as_bytes()
1504 }
1505
1506 #[inline]
1507 pub fn uniform_bytes(&self) -> &[u8] {
1508 self.uniforms.as_bytes()
1509 }
1510}
1511
1512#[derive(Debug, Clone, PartialEq)]
1514pub struct GpuShaderModule {
1515 pub source: String,
1516 pub has_vertex_entry: bool,
1517 pub has_fragment_entry: bool,
1518 pub vertex_entry: String,
1519 pub fragment_entry: String,
1520 pub uniforms_declared: Vec<String>,
1521 pub bind_groups_declared: usize,
1522}
1523
1524#[derive(Debug, Default, Clone)]
1526pub struct GpuShaderCompiler;
1527
1528impl GpuShaderCompiler {
1529 pub fn new() -> Self {
1530 Self
1531 }
1532
1533 pub fn compile(&self, source: &str) -> Result<GpuShaderModule, String> {
1535 let has_vertex_entry = source.contains("@vertex");
1536 let has_fragment_entry = source.contains("@fragment");
1537
1538 if !has_vertex_entry && !has_fragment_entry && !source.contains("@compute") {
1539 return Err(
1540 "WGSL shader missing @vertex, @fragment, or @compute entry point".to_string(),
1541 );
1542 }
1543
1544 let mut vertex_entry = "vs_main".to_string();
1545 let mut fragment_entry = "fs_main".to_string();
1546
1547 for line in source.lines() {
1548 let trimmed = line.trim();
1549 if trimmed.starts_with("fn ") {
1550 let name = trimmed
1551 .trim_start_matches("fn ")
1552 .split('(')
1553 .next()
1554 .unwrap_or("")
1555 .trim();
1556 if source.contains(&format!("@vertex\nfn {}", name))
1557 || source.contains(&format!("@vertex fn {}", name))
1558 {
1559 vertex_entry = name.to_string();
1560 }
1561 if source.contains(&format!("@fragment\nfn {}", name))
1562 || source.contains(&format!("@fragment fn {}", name))
1563 {
1564 fragment_entry = name.to_string();
1565 }
1566 }
1567 }
1568
1569 let mut uniforms = Vec::new();
1570 for line in source.lines() {
1571 if line.contains("var<uniform>") {
1572 if let Some(name) = line.split("var<uniform>").nth(1) {
1573 let u_name = name.split(':').next().unwrap_or("").trim();
1574 if !u_name.is_empty() {
1575 uniforms.push(u_name.to_string());
1576 }
1577 }
1578 }
1579 }
1580
1581 let bind_groups = source.matches("@group(").count();
1582
1583 Ok(GpuShaderModule {
1584 source: source.to_string(),
1585 has_vertex_entry,
1586 has_fragment_entry,
1587 vertex_entry,
1588 fragment_entry,
1589 uniforms_declared: uniforms,
1590 bind_groups_declared: bind_groups,
1591 })
1592 }
1593}
1594
1595#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1597pub enum GpuVertexFormat {
1598 Float32x2,
1599 Float32x3,
1600 Float32x4,
1601 Uint32x2,
1602 Uint32x4,
1603}
1604
1605impl GpuVertexFormat {
1606 pub const fn byte_size(&self) -> usize {
1607 match self {
1608 Self::Float32x2 | Self::Uint32x2 => 8,
1609 Self::Float32x3 => 12,
1610 Self::Float32x4 | Self::Uint32x4 => 16,
1611 }
1612 }
1613}
1614
1615#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1617pub struct GpuVertexAttribute {
1618 pub format: GpuVertexFormat,
1619 pub offset: u64,
1620 pub shader_location: u32,
1621}
1622
1623#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1625pub enum GpuVertexStepMode {
1626 #[default]
1627 Vertex,
1628 Instance,
1629}
1630
1631#[derive(Debug, Clone, PartialEq)]
1633pub struct GpuVertexBufferLayout {
1634 pub array_stride: u64,
1635 pub step_mode: GpuVertexStepMode,
1636 pub attributes: Vec<GpuVertexAttribute>,
1637}
1638
1639#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1641pub enum GpuPrimitiveTopology {
1642 PointList,
1643 LineList,
1644 LineStrip,
1645 #[default]
1646 TriangleList,
1647 TriangleStrip,
1648}
1649
1650#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1652pub enum GpuCompareFunction {
1653 Never,
1654 #[default]
1655 Less,
1656 Equal,
1657 LessEqual,
1658 Greater,
1659 NotEqual,
1660 GreaterEqual,
1661 Always,
1662}
1663
1664#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1666pub struct GpuDepthStencilState {
1667 pub format: crate::swapchain::SwapchainFormat,
1668 pub depth_write_enabled: bool,
1669 pub depth_compare: GpuCompareFunction,
1670}
1671
1672impl Default for GpuDepthStencilState {
1673 fn default() -> Self {
1674 Self {
1675 format: crate::swapchain::SwapchainFormat::Depth32Float,
1676 depth_write_enabled: true,
1677 depth_compare: GpuCompareFunction::LessEqual,
1678 }
1679 }
1680}
1681
1682impl GpuDepthStencilState {
1683 pub fn passes_test(&self, current_depth: f32, new_depth: f32) -> bool {
1685 match self.depth_compare {
1686 GpuCompareFunction::Never => false,
1687 GpuCompareFunction::Less => new_depth < current_depth,
1688 GpuCompareFunction::Equal => (new_depth - current_depth).abs() < 1e-6,
1689 GpuCompareFunction::LessEqual => new_depth <= current_depth + 1e-6,
1690 GpuCompareFunction::Greater => new_depth > current_depth,
1691 GpuCompareFunction::NotEqual => (new_depth - current_depth).abs() >= 1e-6,
1692 GpuCompareFunction::GreaterEqual => new_depth >= current_depth - 1e-6,
1693 GpuCompareFunction::Always => true,
1694 }
1695 }
1696}
1697
1698#[derive(Debug, Clone)]
1700pub struct GpuRenderPipeline {
1701 pub shader_module: GpuShaderModule,
1702 pub vertex_layout: GpuVertexBufferLayout,
1703 pub instance_layout: Option<GpuVertexBufferLayout>,
1704 pub primitive_topology: GpuPrimitiveTopology,
1705 pub depth_stencil: Option<GpuDepthStencilState>,
1706}
1707
1708impl GpuRenderPipeline {
1709 pub fn new_instanced_quad_pipeline(
1711 viewport_width: f32,
1712 viewport_height: f32,
1713 ) -> Result<Self, String> {
1714 let _ = (viewport_width, viewport_height);
1715 let compiler = GpuShaderCompiler::new();
1716 let shader_module = compiler.compile(WGSL_ANALYTICAL_QUAD_SHADER)?;
1717
1718 let vertex_layout = GpuVertexBufferLayout {
1719 array_stride: 8,
1720 step_mode: GpuVertexStepMode::Vertex,
1721 attributes: vec![GpuVertexAttribute {
1722 format: GpuVertexFormat::Float32x2,
1723 offset: 0,
1724 shader_location: 0,
1725 }],
1726 };
1727
1728 let instance_layout = GpuVertexBufferLayout {
1729 array_stride: 96,
1730 step_mode: GpuVertexStepMode::Instance,
1731 attributes: vec![
1732 GpuVertexAttribute {
1733 format: GpuVertexFormat::Float32x4,
1734 offset: 0,
1735 shader_location: 1,
1736 },
1737 GpuVertexAttribute {
1738 format: GpuVertexFormat::Float32x4,
1739 offset: 16,
1740 shader_location: 2,
1741 },
1742 GpuVertexAttribute {
1743 format: GpuVertexFormat::Float32x4,
1744 offset: 32,
1745 shader_location: 3,
1746 },
1747 GpuVertexAttribute {
1748 format: GpuVertexFormat::Float32x4,
1749 offset: 48,
1750 shader_location: 4,
1751 },
1752 GpuVertexAttribute {
1753 format: GpuVertexFormat::Float32x4,
1754 offset: 64,
1755 shader_location: 5,
1756 },
1757 GpuVertexAttribute {
1758 format: GpuVertexFormat::Float32x4,
1759 offset: 80,
1760 shader_location: 6,
1761 },
1762 ],
1763 };
1764
1765 Ok(Self {
1766 shader_module,
1767 vertex_layout,
1768 instance_layout: Some(instance_layout),
1769 primitive_topology: GpuPrimitiveTopology::TriangleList,
1770 depth_stencil: Some(GpuDepthStencilState {
1771 format: crate::swapchain::SwapchainFormat::Depth32Float,
1772 depth_write_enabled: true,
1773 depth_compare: GpuCompareFunction::LessEqual,
1774 }),
1775 })
1776 }
1777
1778 pub fn draw_instanced(
1780 &self,
1781 encoder: &mut crate::gpu_context::GpuCommandEncoder,
1782 vertex_count: usize,
1783 instance_count: usize,
1784 ) {
1785 encoder.draw_instanced(vertex_count, instance_count);
1786 }
1787}
1788
1789#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1791pub struct GpuBatchSummary {
1792 pub total_commands: usize,
1793 pub quad_instances: usize,
1794 pub slug_glyphs: usize,
1795 pub path_segments: usize,
1796 pub total_draw_calls: usize,
1797}
1798
1799#[derive(Debug, Clone)]
1803pub struct GpuBatchCollector {
1804 pub viewport_width: f32,
1805 pub viewport_height: f32,
1806 pub quad_batch: GpuBatch,
1807 pub text_pipeline: GpuSlugTextPipeline,
1808 pub path_batch: GpuPathBatch,
1809 pub summary: GpuBatchSummary,
1810}
1811
1812impl GpuBatchCollector {
1813 pub fn new(viewport_width: f32, viewport_height: f32) -> Self {
1814 Self {
1815 viewport_width,
1816 viewport_height,
1817 quad_batch: GpuBatch::new(),
1818 text_pipeline: GpuSlugTextPipeline::new(),
1819 path_batch: GpuPathBatch::new(),
1820 summary: GpuBatchSummary::default(),
1821 }
1822 }
1823
1824 pub fn collect(&mut self, list: &DisplayList, damage: Option<Rect>) -> GpuBatchSummary {
1826 self.quad_batch = GpuBatch::from_display_list_damaged(
1827 list,
1828 damage,
1829 self.viewport_width,
1830 self.viewport_height,
1831 );
1832
1833 let glyph_count = self.text_pipeline.compile_display_list(
1834 list,
1835 self.viewport_width,
1836 self.viewport_height,
1837 damage,
1838 );
1839
1840 self.path_batch = GpuPathBatch::from_display_list_damaged(
1841 list,
1842 damage,
1843 self.viewport_width,
1844 self.viewport_height,
1845 );
1846
1847 let mut draw_calls = 0;
1848 if !self.quad_batch.is_empty() {
1849 draw_calls += 1;
1850 }
1851 if glyph_count > 0 {
1852 draw_calls += 1;
1853 }
1854 if !self.path_batch.is_empty() {
1855 draw_calls += 1;
1856 }
1857
1858 self.summary = GpuBatchSummary {
1859 total_commands: list.len(),
1860 quad_instances: self.quad_batch.len(),
1861 slug_glyphs: glyph_count,
1862 path_segments: self.path_batch.len(),
1863 total_draw_calls: draw_calls,
1864 };
1865
1866 self.summary
1867 }
1868
1869 pub fn dispatch(
1871 &self,
1872 device: &mut crate::gpu_context::GpuDevice,
1873 damage: Option<Rect>,
1874 ) -> Result<GpuBatchSummary, crate::swapchain::PresentError> {
1875 let mut encoder = device.create_command_encoder();
1876 let pass = crate::gpu_context::GpuRenderPassDescriptor {
1877 color_texture_id: device.swapchain_texture.id,
1878 depth_texture_id: Some(device.depth_texture.id),
1879 clear_color: Some([0.0, 0.0, 0.0, 1.0]),
1880 clear_depth: Some(1.0),
1881 scissor_rect: damage,
1882 };
1883 encoder.begin_render_pass(pass);
1884
1885 if !self.quad_batch.is_empty() {
1886 encoder.draw_instanced(6, self.quad_batch.len());
1887 }
1888 if self.summary.slug_glyphs > 0 {
1889 encoder.draw_instanced(6, self.summary.slug_glyphs);
1890 }
1891 if !self.path_batch.is_empty() {
1892 encoder.draw_instanced(6, self.path_batch.len());
1893 }
1894
1895 encoder.end_render_pass();
1896 device.submit(encoder);
1897
1898 Ok(self.summary)
1899 }
1900}
1901
1902#[cfg(test)]
1903mod tests {
1904 use super::*;
1905
1906 #[test]
1907 fn test_gpu_quad_memory_layout() {
1908 assert_eq!(GpuQuadInstance::BYTE_SIZE, 96);
1909 assert_eq!(GpuUniforms::BYTE_SIZE, 16);
1910 assert_eq!(QUAD_VERTICES.len(), 6);
1911
1912 let quad = GpuQuadInstance::from_rect(
1913 Rect::new(10.0, 20.0, 100.0, 50.0),
1914 Color::rgb(255, 0, 0),
1915 Rect::new(0.0, 0.0, 1920.0, 1080.0),
1916 );
1917
1918 let bytes = quad.as_bytes();
1919 assert_eq!(bytes.len(), 96);
1920
1921 let b0 = f32::from_ne_bytes(bytes[0..4].try_into().unwrap());
1923 let b1 = f32::from_ne_bytes(bytes[4..8].try_into().unwrap());
1924 let b2 = f32::from_ne_bytes(bytes[8..12].try_into().unwrap());
1925 let b3 = f32::from_ne_bytes(bytes[12..16].try_into().unwrap());
1926 assert_eq!(b0, 10.0);
1927 assert_eq!(b1, 20.0);
1928 assert_eq!(b2, 100.0);
1929 assert_eq!(b3, 50.0);
1930 }
1931
1932 #[test]
1933 fn test_gpu_batch_compilation_and_scissoring() {
1934 let mut dl = DisplayList::new();
1935
1936 dl.push(DrawCommand::DrawRect {
1938 bounds: Rect::new(0.0, 0.0, 1920.0, 1080.0),
1939 color: Color::rgb(10, 10, 15),
1940 });
1941
1942 dl.push(DrawCommand::DrawRoundedRect {
1944 bounds: Rect::new(20.0, 20.0, 120.0, 36.0),
1945 color: Color::rgb(59, 130, 246),
1946 border_radius: BorderRadius::all(6.0),
1947 border_width: EdgeInsets::ZERO,
1948 border_color: None,
1949 });
1950
1951 dl.push(DrawCommand::DrawRect {
1953 bounds: Rect::new(1500.0, 800.0, 300.0, 200.0),
1954 color: Color::rgb(30, 41, 59),
1955 });
1956
1957 let full_batch = GpuBatch::from_display_list(&dl, 1920.0, 1080.0);
1959 assert_eq!(full_batch.len(), 3);
1960 assert_eq!(full_batch.as_bytes().len(), 3 * 96);
1961
1962 let damage = Rect::new(10.0, 10.0, 140.0, 60.0);
1964 let damaged_batch = GpuBatch::from_display_list_damaged(&dl, Some(damage), 1920.0, 1080.0);
1965
1966 assert_eq!(damaged_batch.len(), 2);
1969 }
1970
1971 #[test]
1972 fn test_presentation_pipeline_compilation() {
1973 let mut pipeline = GpuPresentationPipeline::new(1920.0, 1080.0);
1974
1975 let mut dl = DisplayList::new();
1976 dl.push(DrawCommand::DrawRect {
1977 bounds: Rect::new(50.0, 50.0, 200.0, 100.0),
1978 color: Color::rgb(255, 255, 255),
1979 });
1980
1981 let count = pipeline.compile_frame(&dl, None);
1982 assert_eq!(count, 1);
1983 assert_eq!(pipeline.compiled_frames, 1);
1984 assert_eq!(pipeline.instance_bytes().len(), 96);
1985 assert_eq!(pipeline.uniform_bytes().len(), 16);
1986 }
1987
1988 #[test]
1989 fn test_gpu_path_batch_and_pipeline() {
1990 let mut path_pipeline = GpuPathPipeline::new(1920.0, 1080.0);
1991
1992 let mut dl = DisplayList::new();
1993 let path = strata_gpu_path::PathBuilder::from_svg("M 0 0 L 100 100 Q 150 50 200 0 Z")
1995 .with_fill(strata_gpu_path::FillRule::NonZero);
1996
1997 dl.push(DrawCommand::DrawGpuPath {
1998 bounds: Rect::new(0.0, 0.0, 200.0, 100.0),
1999 path,
2000 stroke: Some(strata_gpu_path::StrokeOptions::new(2.0)),
2001 fill_color: Some(Color::rgb(16, 185, 129)),
2002 stroke_color: Some(Color::rgb(5, 150, 105)),
2003 transform: None,
2004 });
2005
2006 dl.push(DrawCommand::DrawSvgPath {
2008 bounds: Rect::new(300.0, 300.0, 50.0, 50.0),
2009 path_data: "M 0 0 L 50 50 Z".to_string(),
2010 stroke_color: Some(Color::rgb(255, 255, 255)),
2011 fill_color: None,
2012 stroke_width: 1.5,
2013 stroke_linecap: strata_layout::StrokeLineCap::Round,
2014 stroke_linejoin: strata_layout::StrokeLineJoin::Round,
2015 stroke_dasharray: Vec::new(),
2016 fill_rule: strata_layout::FillRule::NonZero,
2017 view_box: (50.0, 50.0),
2018 });
2019
2020 let seg_count = path_pipeline.compile_frame(&dl, None);
2021 assert!(
2022 seg_count >= 4,
2023 "Should emit multiple quadratic segments for path + svg"
2024 );
2025 assert_eq!(path_pipeline.compiled_frames, 1);
2026 assert_eq!(path_pipeline.segment_bytes().len(), seg_count * 64);
2027 assert_eq!(path_pipeline.uniform_bytes().len(), 16);
2028
2029 let damage = Rect::new(0.0, 0.0, 220.0, 120.0);
2031 let damaged_count = path_pipeline.compile_frame(&dl, Some(damage));
2032 assert!(
2033 damaged_count < seg_count,
2034 "Damaged compilation should skip path outside damage rect"
2035 );
2036 }
2037}