Skip to main content

strata_render/
gpu_pipeline.rs

1//! GPU Quad and Rounded Rectangle Presentation Pipeline.
2//!
3//! Provides instanced GPU memory representations (`GpuQuadInstance`, `GpuUniforms`, `GpuBatch`)
4//! and analytical Signed Distance Field (SDF) WGSL shaders for zero-CPU hardware rendering.
5
6use crate::compositor::{DisplayList, DrawCommand};
7use strata_layout::Rect;
8use strata_primitives::geom::EdgeInsets;
9use strata_style::types::{BorderRadius, Color};
10
11/// Embedded WGSL shader for instanced quad rendering with analytical SDF anti-aliased corners and borders.
12pub 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    let out_a = in.color.a * coverage;
112    return vec4<f32>(in.color.rgb * out_a, out_a);
113}
114"#;
115
116/// 2D Vertex coordinates for rendering unit instanced quads.
117#[repr(C)]
118#[derive(Debug, Clone, Copy, PartialEq)]
119pub struct GpuVertex {
120    pub position: [f32; 2],
121}
122
123impl GpuVertex {
124    pub const fn new(x: f32, y: f32) -> Self {
125        Self { position: [x, y] }
126    }
127}
128
129/// Six vertices composing two triangles for a unit rectangle [0, 0] to [1, 1].
130pub const QUAD_VERTICES: [GpuVertex; 6] = [
131    GpuVertex::new(0.0, 0.0),
132    GpuVertex::new(1.0, 0.0),
133    GpuVertex::new(0.0, 1.0),
134    GpuVertex::new(0.0, 1.0),
135    GpuVertex::new(1.0, 0.0),
136    GpuVertex::new(1.0, 1.0),
137];
138
139/// Six vertices composing two triangles for a signed unit quad `[-1, -1]` to `[1, 1]`,
140/// matching [`strata_gpu_path::WGSL_ANALYTICAL_PATH_RASTER_SHADER`].
141pub const SIGNED_QUAD_VERTICES: [GpuVertex; 6] = [
142    GpuVertex::new(-1.0, -1.0),
143    GpuVertex::new(1.0, -1.0),
144    GpuVertex::new(-1.0, 1.0),
145    GpuVertex::new(-1.0, 1.0),
146    GpuVertex::new(1.0, -1.0),
147    GpuVertex::new(1.0, 1.0),
148];
149
150/// Exact 96-byte GPU memory instance representation for an instanced quad or rounded rectangle.
151#[repr(C)]
152#[derive(Debug, Clone, Copy, PartialEq)]
153pub struct GpuQuadInstance {
154    pub bounds: [f32; 4],        // [x, y, width, height]
155    pub color: [f32; 4],         // [r, g, b, a]
156    pub border_radius: [f32; 4], // [top_left, top_right, bottom_right, bottom_left]
157    pub border_width: [f32; 4],  // [top, right, bottom, left]
158    pub border_color: [f32; 4],  // [r, g, b, a]
159    pub clip_rect: [f32; 4],     // [clip_x, clip_y, clip_w, clip_h]
160}
161
162impl GpuQuadInstance {
163    pub const BYTE_SIZE: usize = std::mem::size_of::<Self>();
164
165    /// Constructs a simple solid colored quad instance.
166    pub fn from_rect(bounds: Rect, color: Color, clip: Rect) -> Self {
167        let (r, g, b, a) = color.to_f32();
168        Self {
169            bounds: [bounds.x, bounds.y, bounds.width, bounds.height],
170            color: [r, g, b, a],
171            border_radius: [0.0; 4],
172            border_width: [0.0; 4],
173            border_color: [0.0; 4],
174            clip_rect: [clip.x, clip.y, clip.width, clip.height],
175        }
176    }
177
178    /// Constructs a rounded rectangle with border widths and border colors.
179    pub fn from_rounded_rect(
180        bounds: Rect,
181        color: Color,
182        radius: BorderRadius,
183        widths: EdgeInsets<f32>,
184        border_color: Option<Color>,
185        clip: Rect,
186    ) -> Self {
187        let (r, g, b, a) = color.to_f32();
188        let (br, bg, bb, ba) = border_color
189            .map(|c| c.to_f32())
190            .unwrap_or((0.0, 0.0, 0.0, 0.0));
191
192        Self {
193            bounds: [bounds.x, bounds.y, bounds.width, bounds.height],
194            color: [r, g, b, a],
195            border_radius: [
196                radius.top_left,
197                radius.top_right,
198                radius.bottom_right,
199                radius.bottom_left,
200            ],
201            border_width: [widths.top, widths.right, widths.bottom, widths.left],
202            border_color: [br, bg, bb, ba],
203            clip_rect: [clip.x, clip.y, clip.width, clip.height],
204        }
205    }
206
207    /// Safe zero-copy byte slice view of this quad instance.
208    #[inline]
209    pub fn as_bytes(&self) -> &[u8] {
210        unsafe { std::slice::from_raw_parts((self as *const Self) as *const u8, Self::BYTE_SIZE) }
211    }
212
213    /// Safe zero-copy byte slice view of a contiguous slice of quad instances.
214    #[inline]
215    pub fn slice_to_bytes(slice: &[Self]) -> &[u8] {
216        unsafe {
217            std::slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len() * Self::BYTE_SIZE)
218        }
219    }
220}
221
222/// 16-byte aligned Uniform Buffer object for viewport projection.
223#[repr(C)]
224#[derive(Debug, Clone, Copy, PartialEq)]
225pub struct GpuUniforms {
226    pub viewport_size: [f32; 2],
227    pub _padding: [f32; 2],
228}
229
230impl GpuUniforms {
231    pub const BYTE_SIZE: usize = std::mem::size_of::<Self>();
232
233    pub fn new(width: f32, height: f32) -> Self {
234        Self {
235            viewport_size: [width, height],
236            _padding: [0.0, 0.0],
237        }
238    }
239
240    #[inline]
241    pub fn as_bytes(&self) -> &[u8] {
242        unsafe { std::slice::from_raw_parts((self as *const Self) as *const u8, Self::BYTE_SIZE) }
243    }
244}
245
246/// Embedded WGSL shader for non-rectangular polygonal clip stencil masks.
247pub const WGSL_STENCIL_CLIP_SHADER: &str = r#"
248struct VertexInput {
249    @location(0) position: vec2<f32>,
250};
251
252struct Uniforms {
253    viewport_size: vec2<f32>,
254    _padding: vec2<f32>,
255};
256
257@group(0) @binding(0) var<uniform> uniforms: Uniforms;
258
259@vertex
260fn vs_main(model: VertexInput) -> @builtin(position) vec4<f32> {
261    let ndc_x = (model.position.x / uniforms.viewport_size.x) * 2.0 - 1.0;
262    let ndc_y = 1.0 - (model.position.y / uniforms.viewport_size.y) * 2.0;
263    return vec4<f32>(ndc_x, ndc_y, 0.0, 1.0);
264}
265
266@fragment
267fn fs_main() -> @location(0) vec4<f32> {
268    // Stencil clip passes disable color writes and update the stencil attachment directly.
269    return vec4<f32>(0.0, 0.0, 0.0, 0.0);
270}
271"#;
272
273/// 2D vertex coordinate for triangulated GPU stencil clip mask geometry.
274#[repr(C)]
275#[derive(Debug, Clone, Copy, PartialEq)]
276pub struct GpuClipVertex {
277    pub position: [f32; 2],
278}
279
280impl GpuClipVertex {
281    pub const BYTE_SIZE: usize = std::mem::size_of::<Self>();
282
283    #[inline]
284    pub const fn new(x: f32, y: f32) -> Self {
285        Self { position: [x, y] }
286    }
287
288    #[inline]
289    pub fn slice_to_bytes(slice: &[Self]) -> &[u8] {
290        unsafe {
291            std::slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len() * Self::BYTE_SIZE)
292        }
293    }
294}
295
296/// Spatial containment relation of a primitive or quad against an active polygonal clip stack.
297#[derive(Debug, Clone, Copy, PartialEq, Eq)]
298pub enum ClipContainment {
299    /// Primitive lies completely outside at least one clip layer (cullable).
300    Outside,
301    /// Primitive crosses a non-rectangular clip boundary (requires stencil masking).
302    Partial,
303    /// Primitive lies strictly inside every active clip layer (no stencil needed).
304    Inside,
305}
306
307/// Compiled polygonal/stencil clip mask for circular, rounded, or arbitrary CAD clip paths.
308#[derive(Debug, Clone, PartialEq)]
309pub struct GpuClipMask {
310    /// Conservative axis-aligned bounding box of the intersected clip region.
311    pub bounds: Rect,
312    /// Active non-rectangular clip layers; each layer contains closed/open subpaths evaluated even-odd.
313    pub layers: Vec<Vec<Vec<(f32, f32)>>>,
314    /// Triangulated vertex triplets per clip layer (3 vertices per triangle) for GPU stencil passes.
315    pub stencil_layers: Vec<Vec<GpuClipVertex>>,
316}
317
318impl GpuClipMask {
319    /// Constructs and triangulates a stencil clip mask from a stack of subpath layers.
320    pub fn from_layers(bounds: Rect, layers: Vec<Vec<Vec<(f32, f32)>>>) -> Self {
321        let stencil_layers = layers
322            .iter()
323            .map(|subpaths| {
324                let mut verts = Vec::new();
325                for sub in subpaths {
326                    verts.extend(triangulate_subpath_pts(sub));
327                }
328                verts
329            })
330            .collect();
331        Self {
332            bounds,
333            layers,
334            stencil_layers,
335        }
336    }
337
338    /// Returns `true` if `(x, y)` passes the intersected AABB and all even-odd polygon layers.
339    #[inline]
340    pub fn contains_point(&self, x: f32, y: f32) -> bool {
341        if x < self.bounds.x
342            || x >= self.bounds.max_x()
343            || y < self.bounds.y
344            || y >= self.bounds.max_y()
345        {
346            return false;
347        }
348        self.layers
349            .iter()
350            .all(|poly| crate::canvas2d::point_in_subpaths_even_odd(poly, x, y))
351    }
352
353    /// Evaluates containment of `rect` against all clip layers in this mask.
354    #[inline]
355    pub fn rect_containment(&self, rect: Rect) -> ClipContainment {
356        if self.bounds.intersect(rect).is_none() {
357            return ClipContainment::Outside;
358        }
359        rect_relation_to_clip_polys(rect, &self.layers)
360    }
361
362    /// Total number of stencil triangle vertices across all active clip layers.
363    #[inline]
364    pub fn total_stencil_vertices(&self) -> usize {
365        self.stencil_layers.iter().map(|v| v.len()).sum()
366    }
367}
368
369/// Maps a contiguous slice `[start..end)` of batched GPU primitives to an optional [`GpuClipMask`].
370#[derive(Debug, Clone, Copy, PartialEq, Eq)]
371pub struct GpuClipSpan {
372    pub start: usize,
373    pub end: usize,
374    pub clip_mask: Option<usize>,
375}
376
377#[inline]
378fn orient2d(a: (f32, f32), b: (f32, f32), c: (f32, f32)) -> f32 {
379    (b.0 - a.0) * (c.1 - a.1) - (b.1 - a.1) * (c.0 - a.0)
380}
381
382#[inline]
383fn on_segment_bbox(a: (f32, f32), b: (f32, f32), p: (f32, f32)) -> bool {
384    p.0 >= a.0.min(b.0) - 1e-4
385        && p.0 <= a.0.max(b.0) + 1e-4
386        && p.1 >= a.1.min(b.1) - 1e-4
387        && p.1 <= a.1.max(b.1) + 1e-4
388}
389
390fn segments_intersect_2d(
391    a0: (f32, f32),
392    a1: (f32, f32),
393    b0: (f32, f32),
394    b1: (f32, f32),
395) -> bool {
396    let o1 = orient2d(a0, a1, b0);
397    let o2 = orient2d(a0, a1, b1);
398    let o3 = orient2d(b0, b1, a0);
399    let o4 = orient2d(b0, b1, a1);
400    if ((o1 > 1e-4 && o2 < -1e-4) || (o1 < -1e-4 && o2 > 1e-4))
401        && ((o3 > 1e-4 && o4 < -1e-4) || (o3 < -1e-4 && o4 > 1e-4))
402    {
403        return true;
404    }
405    (o1.abs() <= 1e-4 && on_segment_bbox(a0, a1, b0))
406        || (o2.abs() <= 1e-4 && on_segment_bbox(a0, a1, b1))
407        || (o3.abs() <= 1e-4 && on_segment_bbox(b0, b1, a0))
408        || (o4.abs() <= 1e-4 && on_segment_bbox(b0, b1, a1))
409}
410
411fn subpaths_are_axis_aligned_rect(subpaths: &[Vec<(f32, f32)>]) -> bool {
412    if subpaths.len() != 1 {
413        return false;
414    }
415    let raw = &subpaths[0];
416    let mut pts: Vec<(f32, f32)> = Vec::with_capacity(raw.len());
417    for &p in raw {
418        if pts
419            .last()
420            .is_none_or(|&prev| (p.0 - prev.0).hypot(p.1 - prev.1) > 1e-3)
421        {
422            pts.push(p);
423        }
424    }
425    if pts.len() >= 2 {
426        let first = pts[0];
427        let last = *pts.last().unwrap();
428        if (first.0 - last.0).hypot(first.1 - last.1) <= 1e-3 {
429            pts.pop();
430        }
431    }
432    if pts.len() != 4 {
433        return false;
434    }
435    let mut prev_horiz: Option<bool> = None;
436    for i in 0..4 {
437        let a = pts[i];
438        let b = pts[(i + 1) % 4];
439        let dx = (b.0 - a.0).abs();
440        let dy = (b.1 - a.1).abs();
441        let is_horiz = if dy <= 1e-3 && dx > 1e-3 {
442            true
443        } else if dx <= 1e-3 && dy > 1e-3 {
444            false
445        } else {
446            return false;
447        };
448        if prev_horiz == Some(is_horiz) {
449            return false;
450        }
451        prev_horiz = Some(is_horiz);
452    }
453    true
454}
455
456#[inline]
457fn point_in_triangle_ccw(p: (f32, f32), a: (f32, f32), b: (f32, f32), c: (f32, f32)) -> bool {
458    orient2d(a, b, p) >= -1e-4 && orient2d(b, c, p) >= -1e-4 && orient2d(c, a, p) >= -1e-4
459}
460
461fn triangulate_subpath_pts(raw_pts: &[(f32, f32)]) -> Vec<GpuClipVertex> {
462    let mut pts: Vec<(f32, f32)> = Vec::with_capacity(raw_pts.len());
463    for &p in raw_pts {
464        if pts
465            .last()
466            .is_none_or(|&prev| (p.0 - prev.0).hypot(p.1 - prev.1) > 1e-4)
467        {
468            pts.push(p);
469        }
470    }
471    if pts.len() >= 2 {
472        let first = pts[0];
473        let last = *pts.last().unwrap();
474        if (first.0 - last.0).hypot(first.1 - last.1) <= 1e-4 {
475            pts.pop();
476        }
477    }
478    let n = pts.len();
479    if n < 3 {
480        return Vec::new();
481    }
482
483    let mut area2 = 0.0_f32;
484    for i in 0..n {
485        let a = pts[i];
486        let b = pts[(i + 1) % n];
487        area2 += a.0 * b.1 - b.0 * a.1;
488    }
489    if area2.abs() <= 1e-4 {
490        return Vec::new();
491    }
492    if area2 < 0.0 {
493        pts.reverse();
494    }
495
496    let mut out = Vec::with_capacity((n - 2) * 3);
497    let mut indices: Vec<usize> = (0..n).collect();
498    let mut guard = 0usize;
499    let max_iters = n * n;
500
501    while indices.len() > 3 && guard < max_iters {
502        guard += 1;
503        let m = indices.len();
504        let mut clipped = false;
505        for i in 0..m {
506            let i_prev = indices[(i + m - 1) % m];
507            let i_curr = indices[i];
508            let i_next = indices[(i + 1) % m];
509            let a = pts[i_prev];
510            let b = pts[i_curr];
511            let c = pts[i_next];
512            if orient2d(a, b, c) <= 1e-5 {
513                continue;
514            }
515            let mut empty = true;
516            for (k_idx, &idx) in indices.iter().enumerate() {
517                if k_idx == (i + m - 1) % m || k_idx == i || k_idx == (i + 1) % m {
518                    continue;
519                }
520                if point_in_triangle_ccw(pts[idx], a, b, c) {
521                    empty = false;
522                    break;
523                }
524            }
525            if empty {
526                out.push(GpuClipVertex::new(a.0, a.1));
527                out.push(GpuClipVertex::new(b.0, b.1));
528                out.push(GpuClipVertex::new(c.0, c.1));
529                indices.remove(i);
530                clipped = true;
531                break;
532            }
533        }
534        if !clipped {
535            // Self-intersecting subpath fallback: centroid fan pairs cleanly with Invert even-odd stencil.
536            out.clear();
537            let inv = 1.0 / (n as f32);
538            let mut cx = 0.0_f32;
539            let mut cy = 0.0_f32;
540            for &(px, py) in &pts {
541                cx += px;
542                cy += py;
543            }
544            cx *= inv;
545            cy *= inv;
546            for i in 0..n {
547                let a = pts[i];
548                let b = pts[(i + 1) % n];
549                out.push(GpuClipVertex::new(cx, cy));
550                out.push(GpuClipVertex::new(a.0, a.1));
551                out.push(GpuClipVertex::new(b.0, b.1));
552            }
553            return out;
554        }
555    }
556
557    if indices.len() == 3 {
558        let a = pts[indices[0]];
559        let b = pts[indices[1]];
560        let c = pts[indices[2]];
561        out.push(GpuClipVertex::new(a.0, a.1));
562        out.push(GpuClipVertex::new(b.0, b.1));
563        out.push(GpuClipVertex::new(c.0, c.1));
564    }
565    out
566}
567
568/// Evaluates whether axis-aligned `r` is completely outside, partially clipped by, or strictly
569/// inside a stack of non-rectangular clip subpath layers (`even-odd` fill per layer).
570pub fn rect_relation_to_clip_polys(
571    r: Rect,
572    clip_polys: &[Vec<Vec<(f32, f32)>>],
573) -> ClipContainment {
574    if clip_polys.is_empty() {
575        return ClipContainment::Inside;
576    }
577    if r.width <= 0.0 || r.height <= 0.0 {
578        return ClipContainment::Outside;
579    }
580
581    let x0 = r.x;
582    let y0 = r.y;
583    let x1 = r.max_x();
584    let y1 = r.max_y();
585    let rect_edges = [
586        ((x0, y0), (x1, y0)),
587        ((x1, y0), (x1, y1)),
588        ((x1, y1), (x0, y1)),
589        ((x0, y1), (x0, y0)),
590    ];
591    let samples = [
592        (x0, y0),
593        (x1, y0),
594        (x1, y1),
595        (x0, y1),
596        ((x0 + x1) * 0.5, (y0 + y1) * 0.5),
597    ];
598
599    let mut all_inside = true;
600    for poly in clip_polys {
601        let mut any_vertex_in_rect = false;
602        let mut any_edge_cross = false;
603
604        'poly_scan: for sub in poly {
605            if sub.len() < 2 {
606                continue;
607            }
608            for &v in sub {
609                if v.0 > x0 + 1e-4 && v.0 < x1 - 1e-4 && v.1 > y0 + 1e-4 && v.1 < y1 - 1e-4 {
610                    any_vertex_in_rect = true;
611                    break 'poly_scan;
612                }
613            }
614            let closed_sub = sub.len() >= 3;
615            let edge_count = if closed_sub { sub.len() } else { sub.len() - 1 };
616            for i in 0..edge_count {
617                let a = sub[i];
618                let b = sub[(i + 1) % sub.len()];
619                for &(e0, e1) in &rect_edges {
620                    if segments_intersect_2d(a, b, e0, e1) {
621                        any_edge_cross = true;
622                        break 'poly_scan;
623                    }
624                }
625            }
626        }
627
628        if any_vertex_in_rect || any_edge_cross {
629            all_inside = false;
630            continue;
631        }
632
633        let mut inside_count = 0usize;
634        for &(sx, sy) in &samples {
635            if crate::canvas2d::point_in_subpaths_even_odd(poly, sx, sy) {
636                inside_count += 1;
637            }
638        }
639        if inside_count == 0 {
640            return ClipContainment::Outside;
641        }
642        if inside_count < samples.len() {
643            all_inside = false;
644        }
645    }
646
647    if all_inside {
648        ClipContainment::Inside
649    } else {
650        ClipContainment::Partial
651    }
652}
653
654fn push_clip_span(spans: &mut Vec<GpuClipSpan>, count: usize, index: usize, mask: Option<usize>) {
655    if let Some(last) = spans.last_mut() {
656        if last.end == index && last.clip_mask == mask {
657            last.end = index + count;
658            return;
659        }
660    }
661    spans.push(GpuClipSpan {
662        start: index,
663        end: index + count,
664        clip_mask: mask,
665    });
666}
667
668fn resolve_or_push_clip_mask(
669    masks: &mut Vec<GpuClipMask>,
670    active_clip: Option<Rect>,
671    clip_polys: &[Vec<Vec<(f32, f32)>>],
672) -> Option<usize> {
673    if clip_polys.is_empty() {
674        return None;
675    }
676    let bounds = active_clip?;
677    if let Some((idx, _)) = masks
678        .iter()
679        .enumerate()
680        .find(|(_, m)| m.bounds == bounds && m.layers == clip_polys)
681    {
682        Some(idx)
683    } else {
684        let idx = masks.len();
685        masks.push(GpuClipMask::from_layers(bounds, clip_polys.to_vec()));
686        Some(idx)
687    }
688}
689
690#[inline]
691fn apply_color_opacity(c: Color, alpha_mul: f32) -> Color {
692    if (alpha_mul - 1.0).abs() <= 1e-4 {
693        return c;
694    }
695    let (r, g, b, a) = c.to_f32();
696    Color::from_f32(r, g, b, (a * alpha_mul).clamp(0.0, 1.0))
697}
698
699fn rounded_rect_subpath(bounds: Rect, radius: BorderRadius) -> Vec<(f32, f32)> {
700    let hw = bounds.width * 0.5;
701    let hh = bounds.height * 0.5;
702    let max_r = hw.min(hh).max(0.0);
703    let r_tl = radius.top_left.clamp(0.0, max_r);
704    let r_tr = radius.top_right.clamp(0.0, max_r);
705    let r_br = radius.bottom_right.clamp(0.0, max_r);
706    let r_bl = radius.bottom_left.clamp(0.0, max_r);
707
708    let mut pts = Vec::with_capacity(32);
709    let corners = [
710        (
711            bounds.x + bounds.width - r_tr,
712            bounds.y + r_tr,
713            r_tr,
714            -std::f32::consts::FRAC_PI_2,
715            0.0,
716        ),
717        (
718            bounds.x + bounds.width - r_br,
719            bounds.y + bounds.height - r_br,
720            r_br,
721            0.0,
722            std::f32::consts::FRAC_PI_2,
723        ),
724        (
725            bounds.x + r_bl,
726            bounds.y + bounds.height - r_bl,
727            r_bl,
728            std::f32::consts::FRAC_PI_2,
729            std::f32::consts::PI,
730        ),
731        (
732            bounds.x + r_tl,
733            bounds.y + r_tl,
734            r_tl,
735            std::f32::consts::PI,
736            std::f32::consts::PI * 1.5,
737        ),
738    ];
739    for (cx, cy, r, a0, a1) in corners {
740        if r <= 0.25 {
741            pts.push((cx, cy));
742        } else {
743            let steps = 6usize;
744            for i in 0..=steps {
745                let a = a0 + (a1 - a0) * (i as f32 / steps as f32);
746                pts.push((cx + r * a.cos(), cy + r * a.sin()));
747            }
748        }
749    }
750    pts
751}
752
753fn compute_dashed_stroke_rect_segments(
754    r: Rect,
755    lw: f32,
756    line_dash: &[f32],
757    dash_offset: f32,
758) -> Vec<Rect> {
759    let mut out = Vec::new();
760    let period: f32 = line_dash.iter().copied().sum();
761    if line_dash.is_empty() || period <= 1e-4 || lw <= 0.0 || r.width <= 0.0 || r.height <= 0.0 {
762        return out;
763    }
764    let half = lw * 0.5;
765    let mut phase = dash_offset.rem_euclid(period);
766    let mut dash_idx = 0usize;
767    while dash_idx < line_dash.len() && phase >= line_dash[dash_idx] {
768        phase -= line_dash[dash_idx];
769        dash_idx = (dash_idx + 1) % line_dash.len();
770    }
771    let mut rem = (line_dash[dash_idx] - phase).max(0.0);
772
773    // Edges clockwise matching Cairo/framebuffer: Top, Right, Bottom, Left
774    let edges = [
775        (0u8, r.width),
776        (1u8, r.height),
777        (2u8, r.width),
778        (3u8, r.height),
779    ];
780    for (edge_id, edge_len) in edges {
781        if edge_len <= 1e-4 {
782            continue;
783        }
784        let mut cursor = 0.0_f32;
785        while cursor < edge_len {
786            if rem <= 1e-4 {
787                dash_idx = (dash_idx + 1) % line_dash.len();
788                rem = line_dash[dash_idx];
789                if rem <= 1e-4 {
790                    break;
791                }
792            }
793            let step = rem.min(edge_len - cursor);
794            if dash_idx.is_multiple_of(2) && step > 1e-4 {
795                let s0 = cursor;
796                let s1 = cursor + step;
797                let seg_rect = match edge_id {
798                    0 => Rect::new(r.x + s0, r.y - half, s1 - s0, lw),
799                    1 => Rect::new(r.x + r.width - half, r.y + s0, lw, s1 - s0),
800                    2 => Rect::new(r.x + r.width - s1, r.y + r.height - half, s1 - s0, lw),
801                    _ => Rect::new(r.x - half, r.y + r.height - s1, lw, s1 - s0),
802                };
803                out.push(seg_rect);
804            }
805            cursor += step;
806            rem -= step;
807        }
808    }
809    out
810}
811
812/// Batch collection of GPU instanced quads ready for upload to GPU buffers.
813#[derive(Debug, Default, Clone, PartialEq)]
814pub struct GpuBatch {
815    pub instances: Vec<GpuQuadInstance>,
816    /// Compiled non-rectangular/stencil clip masks referenced by [`Self::clip_spans`].
817    pub clip_masks: Vec<GpuClipMask>,
818    /// Contiguous instance ranges mapped to their active optional stencil clip mask index.
819    pub clip_spans: Vec<GpuClipSpan>,
820}
821
822impl GpuBatch {
823    pub fn new() -> Self {
824        Self::default()
825    }
826
827    pub fn with_capacity(capacity: usize) -> Self {
828        Self {
829            instances: Vec::with_capacity(capacity),
830            clip_masks: Vec::new(),
831            clip_spans: Vec::new(),
832        }
833    }
834
835    #[inline]
836    pub fn push(&mut self, instance: GpuQuadInstance) {
837        self.push_with_clip(instance, None);
838    }
839
840    /// Pushes a quad instance associated with an optional non-rectangular stencil clip mask index.
841    #[inline]
842    pub fn push_with_clip(&mut self, instance: GpuQuadInstance, clip_mask: Option<usize>) {
843        let idx = self.instances.len();
844        self.instances.push(instance);
845        if clip_mask.is_some() || !self.clip_spans.is_empty() {
846            push_clip_span(&mut self.clip_spans, 1, idx, clip_mask);
847        }
848    }
849
850    #[inline]
851    pub fn has_stencil_clips(&self) -> bool {
852        !self.clip_masks.is_empty()
853    }
854
855    /// Returns the stencil clip mask governing `instance_index`, if any.
856    pub fn clip_mask_for_instance(&self, instance_index: usize) -> Option<&GpuClipMask> {
857        let span = self
858            .clip_spans
859            .iter()
860            .find(|s| instance_index >= s.start && instance_index < s.end)?;
861        span.clip_mask.and_then(|id| self.clip_masks.get(id))
862    }
863
864    #[inline]
865    pub fn clear(&mut self) {
866        self.instances.clear();
867        self.clip_masks.clear();
868        self.clip_spans.clear();
869    }
870
871    #[inline]
872    pub fn len(&self) -> usize {
873        self.instances.len()
874    }
875
876    #[inline]
877    pub fn is_empty(&self) -> bool {
878        self.instances.is_empty()
879    }
880
881    #[inline]
882    pub fn as_bytes(&self) -> &[u8] {
883        GpuQuadInstance::slice_to_bytes(&self.instances)
884    }
885
886    /// Compiles a DisplayList into GPU quad instances for the given viewport.
887    pub fn from_display_list(
888        list: &DisplayList,
889        viewport_width: f32,
890        viewport_height: f32,
891    ) -> Self {
892        Self::from_display_list_damaged(list, None, viewport_width, viewport_height)
893    }
894
895    /// Compiles a DisplayList into GPU quad instances, scissoring to the optional damage rectangle.
896    pub fn from_display_list_damaged(
897        list: &DisplayList,
898        damage: Option<Rect>,
899        viewport_width: f32,
900        viewport_height: f32,
901    ) -> Self {
902        let mut batch = Self::with_capacity(list.len());
903        let mut clip_stack: Vec<Rect> = Vec::new();
904        let mut transform_stack: Vec<strata_primitives::geom::Matrix4x4> = Vec::new();
905        let default_clip = damage.unwrap_or(Rect::new(0.0, 0.0, viewport_width, viewport_height));
906
907        for cmd in list.commands() {
908            if let DrawCommand::PushClip { bounds, .. } = cmd {
909                let combined = match clip_stack.last() {
910                    Some(prev) => prev.intersect(*bounds).unwrap_or(Rect::zero()),
911                    None => *bounds,
912                };
913                clip_stack.push(combined);
914                continue;
915            } else if let DrawCommand::PopClip = cmd {
916                clip_stack.pop();
917                continue;
918            } else if let DrawCommand::PushTransform { matrix } = cmd {
919                let combined = match transform_stack.last() {
920                    Some(prev) => prev.multiply(matrix),
921                    None => *matrix,
922                };
923                transform_stack.push(combined);
924                continue;
925            } else if let DrawCommand::PopTransform = cmd {
926                transform_stack.pop();
927                continue;
928            }
929
930            let current_clip = match clip_stack.last() {
931                Some(prev) => match prev.intersect(default_clip) {
932                    Some(c) => c,
933                    None => continue, // Clipped away completely
934                },
935                None => default_clip,
936            };
937
938            let active_matrix = transform_stack.last();
939            let transform_rect_fn = |r: Rect| -> Rect {
940                if let Some(mat) = active_matrix {
941                    if !mat.is_identity() {
942                        let (x, y, w, h) = mat.transform_bounds(r.x, r.y, r.width, r.height);
943                        return Rect::new(x, y, w, h);
944                    }
945                }
946                r
947            };
948
949            // Fast AABB intersection check
950            let transformed_bounds = cmd.bounds().map(transform_rect_fn);
951            if let Some(cmd_bounds) = transformed_bounds {
952                if cmd_bounds.intersect(current_clip).is_none() {
953                    continue;
954                }
955            }
956
957            match cmd {
958                DrawCommand::DrawRect { bounds, color } => {
959                    batch.push(GpuQuadInstance::from_rect(
960                        transform_rect_fn(*bounds),
961                        *color,
962                        current_clip,
963                    ));
964                }
965                DrawCommand::DrawRoundedRect {
966                    bounds,
967                    color,
968                    border_radius,
969                    border_width,
970                    border_color,
971                } => {
972                    batch.push(GpuQuadInstance::from_rounded_rect(
973                        transform_rect_fn(*bounds),
974                        *color,
975                        *border_radius,
976                        *border_width,
977                        *border_color,
978                        current_clip,
979                    ));
980                }
981                DrawCommand::DrawBorder {
982                    bounds,
983                    widths,
984                    color,
985                    border_radius,
986                    ..
987                } => {
988                    batch.push(GpuQuadInstance::from_rounded_rect(
989                        transform_rect_fn(*bounds),
990                        Color::TRANSPARENT,
991                        *border_radius,
992                        *widths,
993                        Some(*color),
994                        current_clip,
995                    ));
996                }
997                DrawCommand::DrawCanvas2D { bounds, commands } => {
998                    if let Some(base_clip) = transform_rect_fn(*bounds).intersect(current_clip) {
999                        let mut active_clip = Some(base_clip);
1000                        let mut line_dash: Vec<f32> = Vec::new();
1001                        let mut dash_offset: f32 = 0.0;
1002                        let mut clip_polys: Vec<Vec<Vec<(f32, f32)>>> = Vec::new();
1003                        let mut clip_mask_id: Option<usize> = None;
1004                        #[allow(clippy::type_complexity)]
1005                        let mut state_stack: Vec<(
1006                            Option<Rect>,
1007                            Vec<f32>,
1008                            f32,
1009                            Vec<Vec<Vec<(f32, f32)>>>,
1010                            Option<usize>,
1011                        )> = Vec::new();
1012
1013                        let transform_subpaths = |subs: Vec<Vec<(f32, f32)>>| -> Vec<Vec<(f32, f32)>> {
1014                            if let Some(mat) = active_matrix {
1015                                if !mat.is_identity() {
1016                                    return subs
1017                                        .into_iter()
1018                                        .map(|sub| {
1019                                            sub.into_iter()
1020                                                .map(|(x, y)| mat.transform_point(x, y))
1021                                                .collect()
1022                                        })
1023                                        .collect();
1024                                }
1025                            }
1026                            subs
1027                        };
1028
1029                        for ccmd in commands {
1030                            match ccmd {
1031                                crate::canvas2d::CanvasCommand::Save => {
1032                                    state_stack.push((
1033                                        active_clip,
1034                                        line_dash.clone(),
1035                                        dash_offset,
1036                                        clip_polys.clone(),
1037                                        clip_mask_id,
1038                                    ));
1039                                }
1040                                crate::canvas2d::CanvasCommand::Restore => {
1041                                    if let Some((
1042                                        prev_clip,
1043                                        prev_dash,
1044                                        prev_offset,
1045                                        prev_polys,
1046                                        prev_mask,
1047                                    )) = state_stack.pop()
1048                                    {
1049                                        active_clip = prev_clip;
1050                                        line_dash = prev_dash;
1051                                        dash_offset = prev_offset;
1052                                        clip_polys = prev_polys;
1053                                        clip_mask_id = prev_mask;
1054                                    }
1055                                }
1056                                crate::canvas2d::CanvasCommand::SetLineDash {
1057                                    segments,
1058                                    offset,
1059                                } => {
1060                                    line_dash = segments
1061                                        .iter()
1062                                        .copied()
1063                                        .filter(|d| d.is_finite() && *d >= 0.0)
1064                                        .collect();
1065                                    if line_dash.len() % 2 == 1 {
1066                                        let dup = line_dash.clone();
1067                                        line_dash.extend(dup);
1068                                    }
1069                                    dash_offset = if offset.is_finite() { *offset } else { 0.0 };
1070                                }
1071                                crate::canvas2d::CanvasCommand::ClipPath { verbs } => {
1072                                    let subpaths = transform_subpaths(
1073                                        crate::canvas2d::flatten_canvas_verbs(
1074                                            verbs, bounds.x, bounds.y,
1075                                        ),
1076                                    );
1077                                    if !subpaths.is_empty() {
1078                                        let mut min_x = f32::INFINITY;
1079                                        let mut min_y = f32::INFINITY;
1080                                        let mut max_x = f32::NEG_INFINITY;
1081                                        let mut max_y = f32::NEG_INFINITY;
1082                                        for sub in &subpaths {
1083                                            for &(x, y) in sub {
1084                                                min_x = min_x.min(x);
1085                                                min_y = min_y.min(y);
1086                                                max_x = max_x.max(x);
1087                                                max_y = max_y.max(y);
1088                                            }
1089                                        }
1090                                        if min_x.is_finite()
1091                                            && min_y.is_finite()
1092                                            && max_x >= min_x
1093                                            && max_y >= min_y
1094                                        {
1095                                            let tb = Rect::new(
1096                                                min_x,
1097                                                min_y,
1098                                                max_x - min_x,
1099                                                max_y - min_y,
1100                                            );
1101                                            active_clip =
1102                                                active_clip.and_then(|c| c.intersect(tb));
1103                                        }
1104                                        if !subpaths_are_axis_aligned_rect(&subpaths) {
1105                                            clip_polys.push(subpaths);
1106                                            clip_mask_id = resolve_or_push_clip_mask(
1107                                                &mut batch.clip_masks,
1108                                                active_clip,
1109                                                &clip_polys,
1110                                            );
1111                                        }
1112                                    }
1113                                }
1114                                crate::canvas2d::CanvasCommand::FillRect {
1115                                    bounds: rb,
1116                                    color,
1117                                } => {
1118                                    if let Some(canvas_clip) = active_clip {
1119                                        let r = transform_rect_fn(Rect::new(
1120                                            bounds.x + rb.x,
1121                                            bounds.y + rb.y,
1122                                            rb.width,
1123                                            rb.height,
1124                                        ));
1125                                        if r.intersect(canvas_clip).is_none() {
1126                                            continue;
1127                                        }
1128                                        let (emit, mask) = if clip_polys.is_empty() {
1129                                            (true, None)
1130                                        } else {
1131                                            match rect_relation_to_clip_polys(r, &clip_polys) {
1132                                                ClipContainment::Outside => (false, None),
1133                                                ClipContainment::Inside => (true, None),
1134                                                ClipContainment::Partial => (true, clip_mask_id),
1135                                            }
1136                                        };
1137                                        if emit {
1138                                            batch.push_with_clip(
1139                                                GpuQuadInstance::from_rect(r, *color, canvas_clip),
1140                                                mask,
1141                                            );
1142                                        }
1143                                    }
1144                                }
1145                                crate::canvas2d::CanvasCommand::StrokeRect {
1146                                    bounds: rb,
1147                                    color,
1148                                    line_width,
1149                                } => {
1150                                    if let Some(canvas_clip) = active_clip {
1151                                        let r = Rect::new(
1152                                            bounds.x + rb.x,
1153                                            bounds.y + rb.y,
1154                                            rb.width,
1155                                            rb.height,
1156                                        );
1157                                        let period: f32 = line_dash.iter().copied().sum();
1158                                        if line_dash.is_empty() || period <= 1e-4 {
1159                                            let tr = transform_rect_fn(r);
1160                                            let lw = *line_width;
1161                                            let (emit, mask) = if clip_polys.is_empty() {
1162                                                (tr.intersect(canvas_clip).is_some(), None)
1163                                            } else {
1164                                                let half = lw * 0.5;
1165                                                let edge_rects = [
1166                                                    Rect::new(tr.x, tr.y - half, tr.width, lw),
1167                                                    Rect::new(
1168                                                        tr.x + tr.width - half,
1169                                                        tr.y,
1170                                                        lw,
1171                                                        tr.height,
1172                                                    ),
1173                                                    Rect::new(
1174                                                        tr.x,
1175                                                        tr.y + tr.height - half,
1176                                                        tr.width,
1177                                                        lw,
1178                                                    ),
1179                                                    Rect::new(tr.x - half, tr.y, lw, tr.height),
1180                                                ];
1181                                                let mut any_in = false;
1182                                                let mut all_strictly_in = true;
1183                                                for er in edge_rects {
1184                                                    match rect_relation_to_clip_polys(
1185                                                        er,
1186                                                        &clip_polys,
1187                                                    ) {
1188                                                        ClipContainment::Outside => {
1189                                                            all_strictly_in = false;
1190                                                        }
1191                                                        ClipContainment::Inside => {
1192                                                            any_in = true;
1193                                                        }
1194                                                        ClipContainment::Partial => {
1195                                                            any_in = true;
1196                                                            all_strictly_in = false;
1197                                                        }
1198                                                    }
1199                                                }
1200                                                if !any_in {
1201                                                    (false, None)
1202                                                } else if all_strictly_in {
1203                                                    (true, None)
1204                                                } else {
1205                                                    (true, clip_mask_id)
1206                                                }
1207                                            };
1208                                            if emit {
1209                                                batch.push_with_clip(
1210                                                    GpuQuadInstance::from_rounded_rect(
1211                                                        tr,
1212                                                        Color::TRANSPARENT,
1213                                                        BorderRadius::default(),
1214                                                        EdgeInsets::all(lw),
1215                                                        Some(*color),
1216                                                        canvas_clip,
1217                                                    ),
1218                                                    mask,
1219                                                );
1220                                            }
1221                                        } else if *line_width > 0.0 && r.width > 0.0 && r.height > 0.0
1222                                        {
1223                                            for seg_rect in compute_dashed_stroke_rect_segments(
1224                                                r,
1225                                                *line_width,
1226                                                &line_dash,
1227                                                dash_offset,
1228                                            ) {
1229                                                let t_seg = transform_rect_fn(seg_rect);
1230                                                if t_seg.intersect(canvas_clip).is_some() {
1231                                                    let (emit, mask) = if clip_polys.is_empty() {
1232                                                        (true, None)
1233                                                    } else {
1234                                                        match rect_relation_to_clip_polys(
1235                                                            t_seg,
1236                                                            &clip_polys,
1237                                                        ) {
1238                                                            ClipContainment::Outside => {
1239                                                                (false, None)
1240                                                            }
1241                                                            ClipContainment::Inside => (true, None),
1242                                                            ClipContainment::Partial => {
1243                                                                (true, clip_mask_id)
1244                                                            }
1245                                                        }
1246                                                    };
1247                                                    if emit {
1248                                                        batch.push_with_clip(
1249                                                            GpuQuadInstance::from_rect(
1250                                                                t_seg,
1251                                                                *color,
1252                                                                canvas_clip,
1253                                                            ),
1254                                                            mask,
1255                                                        );
1256                                                    }
1257                                                }
1258                                            }
1259                                        }
1260                                    }
1261                                }
1262                                _ => {}
1263                            }
1264                        }
1265                    }
1266                }
1267                _ => {}
1268            }
1269        }
1270
1271        batch
1272    }
1273}
1274
1275/// Slug-tier analytical GPU text compilation pipeline.
1276///
1277/// Compiles DisplayList text commands (`DrawText`, `DrawTextFragments`) into analytical
1278/// quadratic Bézier glyph instances and curve contours for hardware shader evaluation.
1279#[derive(Debug, Clone)]
1280pub struct GpuSlugTextPipeline {
1281    pub glyph_cache: strata_gpu_path::AnalyticGlyphCache,
1282    pub buffer: strata_gpu_path::SlugGlyphBuffer,
1283    pub total_glyphs: usize,
1284    pub total_curves: usize,
1285}
1286
1287impl Default for GpuSlugTextPipeline {
1288    fn default() -> Self {
1289        Self::new()
1290    }
1291}
1292
1293impl GpuSlugTextPipeline {
1294    pub fn new() -> Self {
1295        Self {
1296            glyph_cache: strata_gpu_path::AnalyticGlyphCache::with_standard_ascii(),
1297            buffer: strata_gpu_path::SlugGlyphBuffer::new(),
1298            total_glyphs: 0,
1299            total_curves: 0,
1300        }
1301    }
1302
1303    pub fn clear(&mut self) {
1304        self.buffer.clear();
1305        self.total_glyphs = 0;
1306        self.total_curves = 0;
1307    }
1308
1309    /// Advances and returns the hardware synchronization fence.
1310    pub fn sync_barrier(&self) -> u64 {
1311        self.buffer.sync_barrier()
1312    }
1313
1314    /// Checks if a hardware synchronization fence has been signaled.
1315    pub fn is_fence_synchronized(&self, fence: u64) -> bool {
1316        self.buffer.is_fence_synchronized(fence)
1317    }
1318
1319    #[allow(clippy::too_many_arguments)]
1320    fn push_text_run(
1321        &mut self,
1322        text: &str,
1323        start_x: f32,
1324        start_y: f32,
1325        font_size: f32,
1326        x_squeeze: f32,
1327        color: Color,
1328        clip_rect: Rect,
1329    ) -> usize {
1330        self.push_text_run_with_bounds(
1331            text,
1332            start_x,
1333            start_y,
1334            None,
1335            None,
1336            font_size,
1337            1.2,
1338            strata_style::TextAlign::Left,
1339            x_squeeze,
1340            color,
1341            clip_rect,
1342        )
1343        .0
1344    }
1345
1346    #[allow(clippy::too_many_arguments)]
1347    fn push_text_run_with_bounds(
1348        &mut self,
1349        text: &str,
1350        start_x: f32,
1351        start_y: f32,
1352        bounds_width: Option<f32>,
1353        bounds_height: Option<f32>,
1354        font_size: f32,
1355        line_height: f32,
1356        text_align: strata_style::TextAlign,
1357        x_squeeze: f32,
1358        color: Color,
1359        clip_rect: Rect,
1360    ) -> (usize, Rect) {
1361        let (r, g, b, a) = color.to_f32();
1362        let color_f32 = [r, g, b, a];
1363        let clip_r = strata_gpu_path::Rect2D::new(
1364            clip_rect.x,
1365            clip_rect.y,
1366            clip_rect.x + clip_rect.width,
1367            clip_rect.y + clip_rect.height,
1368        );
1369        let step_y = crate::compositor::effective_draw_text_line_height(font_size, line_height);
1370        let glyph_cache = &self.glyph_cache;
1371        let (lines, start_y_off) = crate::compositor::layout_draw_text_lines(
1372            text,
1373            bounds_width,
1374            bounds_height,
1375            font_size,
1376            line_height,
1377            text_align,
1378            |ch| {
1379                glyph_cache
1380                    .get(ch)
1381                    .map(|glyph| glyph.advance_width * font_size * x_squeeze)
1382                    .unwrap_or(font_size * 0.5 * x_squeeze)
1383            },
1384        );
1385        let mut pushed = 0usize;
1386        let mut max_end_x = start_x;
1387        let mut min_start_x = start_x;
1388        let base_y = start_y + start_y_off;
1389
1390        for (line_idx, (line_ox, line_str)) in lines.iter().enumerate() {
1391            let mut cursor_x = start_x + line_ox;
1392            min_start_x = min_start_x.min(cursor_x);
1393            let cursor_y = base_y + line_idx as f32 * step_y;
1394            for ch in line_str.chars() {
1395                if let Some(glyph) = self.glyph_cache.get(ch) {
1396                    let glyph_w = glyph.advance_width * font_size * x_squeeze;
1397                    let glyph_h = font_size;
1398                    let screen_bounds = strata_gpu_path::Rect2D::new(
1399                        cursor_x,
1400                        cursor_y,
1401                        cursor_x + glyph_w,
1402                        cursor_y + glyph_h,
1403                    );
1404                    if clip_rect
1405                        .intersect(Rect::new(cursor_x, cursor_y, glyph_w, glyph_h))
1406                        .is_some()
1407                        && self
1408                            .buffer
1409                            .push_glyph(glyph, screen_bounds, color_f32, clip_r)
1410                    {
1411                        self.total_glyphs += 1;
1412                        pushed += 1;
1413                    }
1414                    cursor_x += glyph_w;
1415                } else {
1416                    cursor_x += font_size * 0.5 * x_squeeze;
1417                }
1418            }
1419            max_end_x = max_end_x.max(cursor_x);
1420        }
1421        let total_h = (lines.len().max(1) as f32 * step_y).max(font_size).max(1.0);
1422        let run_rect = Rect::new(
1423            min_start_x,
1424            base_y,
1425            (max_end_x - min_start_x).max(1.0),
1426            total_h,
1427        );
1428        (pushed, run_rect)
1429    }
1430
1431    #[allow(clippy::too_many_arguments)]
1432    fn push_canvas_text(
1433        &mut self,
1434        bounds: Rect,
1435        text: &str,
1436        x: f32,
1437        y: f32,
1438        color: Color,
1439        font_size: f32,
1440        text_align: crate::canvas2d::CanvasTextAlign,
1441        text_baseline: crate::canvas2d::CanvasTextBaseline,
1442        max_width: Option<f32>,
1443        canvas_clip: Rect,
1444    ) -> (usize, Rect) {
1445        let scale = font_size;
1446        let raw_w: f32 = text
1447            .chars()
1448            .map(|ch| {
1449                self.glyph_cache
1450                    .get(ch)
1451                    .map(|g| g.advance_width * scale)
1452                    .unwrap_or(scale * 0.5)
1453            })
1454            .sum();
1455        let x_squeeze = match max_width {
1456            Some(mw) if mw > 0.0 && raw_w > mw => mw / raw_w,
1457            _ => 1.0,
1458        };
1459        let total_w = raw_w * x_squeeze;
1460        let cursor_x = bounds.x
1461            + match text_align {
1462                crate::canvas2d::CanvasTextAlign::Left | crate::canvas2d::CanvasTextAlign::Start => {
1463                    x
1464                }
1465                crate::canvas2d::CanvasTextAlign::Center => x - total_w * 0.5,
1466                crate::canvas2d::CanvasTextAlign::Right | crate::canvas2d::CanvasTextAlign::End => {
1467                    x - total_w
1468                }
1469            };
1470        let cursor_y = bounds.y
1471            + match text_baseline {
1472                crate::canvas2d::CanvasTextBaseline::Top
1473                | crate::canvas2d::CanvasTextBaseline::Hanging => y,
1474                crate::canvas2d::CanvasTextBaseline::Middle => y - scale * 0.5,
1475                crate::canvas2d::CanvasTextBaseline::Bottom
1476                | crate::canvas2d::CanvasTextBaseline::Ideographic => y - scale,
1477                crate::canvas2d::CanvasTextBaseline::Alphabetic => y - scale * 0.8,
1478            };
1479        let run_rect = Rect::new(cursor_x, cursor_y, total_w.max(1.0), scale.max(1.0));
1480        let pushed = self.push_text_run(
1481            text,
1482            cursor_x,
1483            cursor_y,
1484            scale,
1485            x_squeeze,
1486            color,
1487            canvas_clip,
1488        );
1489        (pushed, run_rect)
1490    }
1491
1492    /// Compiles all DrawText commands in a DisplayList into the Slug GPU buffer.
1493    pub fn compile_display_list(
1494        &mut self,
1495        list: &DisplayList,
1496        viewport_width: f32,
1497        viewport_height: f32,
1498        damage: Option<Rect>,
1499    ) -> usize {
1500        self.clear();
1501        let default_clip = damage.unwrap_or(Rect::new(0.0, 0.0, viewport_width, viewport_height));
1502
1503        for cmd in list.commands() {
1504            match cmd {
1505                DrawCommand::DrawText {
1506                    origin,
1507                    bounds_width,
1508                    bounds_height,
1509                    text_align,
1510                    text,
1511                    font_size,
1512                    line_height,
1513                    color,
1514                    ..
1515                } => {
1516                    self.push_text_run_with_bounds(
1517                        text,
1518                        origin.0,
1519                        origin.1,
1520                        *bounds_width,
1521                        *bounds_height,
1522                        *font_size,
1523                        *line_height,
1524                        *text_align,
1525                        1.0,
1526                        *color,
1527                        default_clip,
1528                    );
1529                }
1530                DrawCommand::DrawTextFragments { fragments } => {
1531                    for frag in fragments {
1532                        self.push_text_run(
1533                            &frag.text,
1534                            frag.bounds.x,
1535                            frag.bounds.y,
1536                            frag.style.font_size,
1537                            1.0,
1538                            frag.style.color,
1539                            default_clip,
1540                        );
1541                    }
1542                }
1543                DrawCommand::DrawCanvas2D { bounds, commands } => {
1544                    let Some(base_clip) = bounds.intersect(default_clip) else {
1545                        continue;
1546                    };
1547                    let mut active_clip = Some(base_clip);
1548                    let mut clip_stack: Vec<Option<Rect>> = Vec::new();
1549
1550                    for ccmd in commands {
1551                        match ccmd {
1552                            crate::canvas2d::CanvasCommand::Save => {
1553                                clip_stack.push(active_clip);
1554                            }
1555                            crate::canvas2d::CanvasCommand::Restore => {
1556                                if let Some(prev) = clip_stack.pop() {
1557                                    active_clip = prev;
1558                                }
1559                            }
1560                            crate::canvas2d::CanvasCommand::ClipPath { verbs } => {
1561                                if let Some(vbbox) =
1562                                    crate::canvas2d::canvas_verbs_bounds(verbs, bounds.x, bounds.y)
1563                                {
1564                                    active_clip = active_clip.and_then(|c| c.intersect(vbbox));
1565                                }
1566                            }
1567                            crate::canvas2d::CanvasCommand::FillText {
1568                                text,
1569                                x,
1570                                y,
1571                                color,
1572                                font_size,
1573                                text_align,
1574                                text_baseline,
1575                                max_width,
1576                                ..
1577                            }
1578                            | crate::canvas2d::CanvasCommand::StrokeText {
1579                                text,
1580                                x,
1581                                y,
1582                                color,
1583                                font_size,
1584                                text_align,
1585                                text_baseline,
1586                                max_width,
1587                                ..
1588                            } => {
1589                                let Some(canvas_clip) = active_clip else {
1590                                    continue;
1591                                };
1592                                self.push_canvas_text(
1593                                    *bounds,
1594                                    text,
1595                                    *x,
1596                                    *y,
1597                                    *color,
1598                                    *font_size,
1599                                    *text_align,
1600                                    *text_baseline,
1601                                    *max_width,
1602                                    canvas_clip,
1603                                );
1604                            }
1605                            _ => {}
1606                        }
1607                    }
1608                }
1609                _ => {}
1610            }
1611        }
1612
1613        self.total_curves = self.buffer.curves.len();
1614        self.total_glyphs
1615    }
1616
1617    #[inline]
1618    pub fn instance_bytes(&self) -> &[u8] {
1619        self.buffer.instances_as_bytes()
1620    }
1621
1622    #[inline]
1623    pub fn curve_bytes(&self) -> &[u8] {
1624        self.buffer.curves_as_bytes()
1625    }
1626}
1627
1628/// High-level orchestration pipeline for compiling display lists into GPU instance buffers.
1629#[derive(Debug, Clone)]
1630pub struct GpuPresentationPipeline {
1631    pub viewport_width: f32,
1632    pub viewport_height: f32,
1633    pub uniforms: GpuUniforms,
1634    pub batch: GpuBatch,
1635    pub text_pipeline: GpuSlugTextPipeline,
1636    pub total_uploaded_bytes: usize,
1637    pub compiled_frames: u64,
1638}
1639
1640impl GpuPresentationPipeline {
1641    pub fn new(viewport_width: f32, viewport_height: f32) -> Self {
1642        Self {
1643            viewport_width,
1644            viewport_height,
1645            uniforms: GpuUniforms::new(viewport_width, viewport_height),
1646            batch: GpuBatch::new(),
1647            text_pipeline: GpuSlugTextPipeline::new(),
1648            total_uploaded_bytes: 0,
1649            compiled_frames: 0,
1650        }
1651    }
1652
1653    pub fn resize(&mut self, width: f32, height: f32) {
1654        self.viewport_width = width;
1655        self.viewport_height = height;
1656        self.uniforms = GpuUniforms::new(width, height);
1657    }
1658
1659    /// Compiles a frame from a DisplayList and optional damage rectangle into internal buffers.
1660    /// Returns the total number of primitives (quads + text glyphs) emitted.
1661    pub fn compile_frame(&mut self, list: &DisplayList, damage: Option<Rect>) -> usize {
1662        self.batch = GpuBatch::from_display_list_damaged(
1663            list,
1664            damage,
1665            self.viewport_width,
1666            self.viewport_height,
1667        );
1668
1669        let glyph_count = self.text_pipeline.compile_display_list(
1670            list,
1671            self.viewport_width,
1672            self.viewport_height,
1673            damage,
1674        );
1675
1676        let byte_count = self.batch.as_bytes().len()
1677            + self.uniforms.as_bytes().len()
1678            + self.text_pipeline.instance_bytes().len()
1679            + self.text_pipeline.curve_bytes().len();
1680        self.total_uploaded_bytes += byte_count;
1681        self.compiled_frames += 1;
1682
1683        self.batch.len() + glyph_count
1684    }
1685
1686    #[inline]
1687    pub fn instance_bytes(&self) -> &[u8] {
1688        self.batch.as_bytes()
1689    }
1690
1691    #[inline]
1692    pub fn uniform_bytes(&self) -> &[u8] {
1693        self.uniforms.as_bytes()
1694    }
1695}
1696
1697#[inline]
1698fn layout_cap_to_gpu(cap: strata_layout::StrokeLineCap) -> strata_gpu_path::LineCap {
1699    match cap {
1700        strata_layout::StrokeLineCap::Butt => strata_gpu_path::LineCap::Butt,
1701        strata_layout::StrokeLineCap::Round => strata_gpu_path::LineCap::Round,
1702        strata_layout::StrokeLineCap::Square => strata_gpu_path::LineCap::Square,
1703    }
1704}
1705
1706#[inline]
1707fn layout_join_to_gpu(join: strata_layout::StrokeLineJoin) -> strata_gpu_path::LineJoin {
1708    match join {
1709        strata_layout::StrokeLineJoin::Miter => strata_gpu_path::LineJoin::Miter,
1710        strata_layout::StrokeLineJoin::Round => strata_gpu_path::LineJoin::Round,
1711        strata_layout::StrokeLineJoin::Bevel => strata_gpu_path::LineJoin::Bevel,
1712    }
1713}
1714
1715#[inline]
1716fn quad_world_bounds(q: &strata_gpu_path::QuadraticBezier, pad: f32) -> Rect {
1717    let min_x = q.p0.x.min(q.p1.x).min(q.p2.x) - pad;
1718    let max_x = q.p0.x.max(q.p1.x).max(q.p2.x) + pad;
1719    let min_y = q.p0.y.min(q.p1.y).min(q.p2.y) - pad;
1720    let max_y = q.p0.y.max(q.p1.y).max(q.p2.y) + pad;
1721    Rect::new(
1722        min_x,
1723        min_y,
1724        (max_x - min_x).max(1.0),
1725        (max_y - min_y).max(1.0),
1726    )
1727}
1728
1729#[inline]
1730fn subpaths_from_path_verbs(
1731    verbs: &[strata_gpu_path::PathVerb],
1732    ox: f32,
1733    oy: f32,
1734    sx: f32,
1735    sy: f32,
1736    tolerance: f32,
1737) -> Vec<(Vec<strata_gpu_path::QuadraticBezier>, bool)> {
1738    let mut result = Vec::new();
1739    let mut cur_sub = Vec::new();
1740    let mut cur = strata_gpu_path::Point2D::new(ox, oy);
1741    let mut start = cur;
1742
1743    let map_pt = |p: strata_gpu_path::Point2D| {
1744        strata_gpu_path::Point2D::new(ox + p.x * sx, oy + p.y * sy)
1745    };
1746
1747    for &v in verbs {
1748        match v {
1749            strata_gpu_path::PathVerb::MoveTo(p) => {
1750                if !cur_sub.is_empty() {
1751                    result.push((std::mem::take(&mut cur_sub), false));
1752                }
1753                cur = map_pt(p);
1754                start = cur;
1755            }
1756            strata_gpu_path::PathVerb::LineTo(p) => {
1757                let next = map_pt(p);
1758                cur_sub.push(strata_gpu_path::QuadraticBezier::new(
1759                    cur,
1760                    cur.lerp(next, 0.5),
1761                    next,
1762                ));
1763                cur = next;
1764            }
1765            strata_gpu_path::PathVerb::QuadTo(p1, p2) => {
1766                let cp = map_pt(p1);
1767                let next = map_pt(p2);
1768                cur_sub.push(strata_gpu_path::QuadraticBezier::new(cur, cp, next));
1769                cur = next;
1770            }
1771            strata_gpu_path::PathVerb::CubicTo(p1, p2, p3) => {
1772                let cubic =
1773                    strata_gpu_path::CubicBezier::new(cur, map_pt(p1), map_pt(p2), map_pt(p3));
1774                cur_sub.extend(cubic.to_quadratics(tolerance));
1775                cur = map_pt(p3);
1776            }
1777            strata_gpu_path::PathVerb::Close => {
1778                if cur.distance_squared(start) > 1e-4 {
1779                    cur_sub.push(strata_gpu_path::QuadraticBezier::new(
1780                        cur,
1781                        cur.lerp(start, 0.5),
1782                        start,
1783                    ));
1784                    cur = start;
1785                }
1786                if !cur_sub.is_empty() {
1787                    result.push((std::mem::take(&mut cur_sub), true));
1788                }
1789            }
1790        }
1791    }
1792    if !cur_sub.is_empty() {
1793        result.push((cur_sub, false));
1794    }
1795    result
1796}
1797
1798fn circle_to_quads(cx: f32, cy: f32, r: f32) -> Vec<strata_gpu_path::QuadraticBezier> {
1799    let segs = 8usize;
1800    let mut circle_quads = Vec::with_capacity(segs);
1801    for i in 0..segs {
1802        let a0 = (i as f32 / segs as f32) * std::f32::consts::TAU;
1803        let a1 = ((i + 1) as f32 / segs as f32) * std::f32::consts::TAU;
1804        let am = (a0 + a1) * 0.5;
1805        let cos_half = ((a1 - a0) * 0.5).cos().max(0.1);
1806        let p0 = strata_gpu_path::Point2D::new(cx + r * a0.cos(), cy + r * a0.sin());
1807        let p2 = strata_gpu_path::Point2D::new(cx + r * a1.cos(), cy + r * a1.sin());
1808        let p1 = strata_gpu_path::Point2D::new(
1809            cx + (r / cos_half) * am.cos(),
1810            cy + (r / cos_half) * am.sin(),
1811        );
1812        circle_quads.push(strata_gpu_path::QuadraticBezier::new(p0, p1, p2));
1813    }
1814    circle_quads
1815}
1816
1817fn canvas_path_verbs_to_quad_subpaths(
1818    verbs: &[crate::canvas2d::CanvasPathVerb],
1819    ox: f32,
1820    oy: f32,
1821) -> Vec<(Vec<strata_gpu_path::QuadraticBezier>, bool)> {
1822    let mut subpaths: Vec<(Vec<strata_gpu_path::QuadraticBezier>, bool)> = Vec::new();
1823    let mut cur_sub = Vec::new();
1824    let mut start = strata_gpu_path::Point2D::new(ox, oy);
1825    let mut cur = start;
1826    let mut has_current = false;
1827    for v in verbs {
1828        match *v {
1829            crate::canvas2d::CanvasPathVerb::MoveTo(x, y) => {
1830                if !cur_sub.is_empty() {
1831                    subpaths.push((std::mem::take(&mut cur_sub), false));
1832                }
1833                cur = strata_gpu_path::Point2D::new(ox + x, oy + y);
1834                start = cur;
1835                has_current = true;
1836            }
1837            crate::canvas2d::CanvasPathVerb::LineTo(x, y) => {
1838                let next = strata_gpu_path::Point2D::new(ox + x, oy + y);
1839                cur_sub.push(strata_gpu_path::QuadraticBezier::new(
1840                    cur,
1841                    cur.lerp(next, 0.5),
1842                    next,
1843                ));
1844                cur = next;
1845                has_current = true;
1846            }
1847            crate::canvas2d::CanvasPathVerb::QuadraticCurveTo { cpx, cpy, x, y } => {
1848                let cp = strata_gpu_path::Point2D::new(ox + cpx, oy + cpy);
1849                let next = strata_gpu_path::Point2D::new(ox + x, oy + y);
1850                cur_sub.push(strata_gpu_path::QuadraticBezier::new(cur, cp, next));
1851                cur = next;
1852                has_current = true;
1853            }
1854            crate::canvas2d::CanvasPathVerb::BezierCurveTo {
1855                cp1x,
1856                cp1y,
1857                cp2x,
1858                cp2y,
1859                x,
1860                y,
1861            } => {
1862                let cp1 = strata_gpu_path::Point2D::new(ox + cp1x, oy + cp1y);
1863                let cp2 = strata_gpu_path::Point2D::new(ox + cp2x, oy + cp2y);
1864                let next = strata_gpu_path::Point2D::new(ox + x, oy + y);
1865                let cubic = strata_gpu_path::CubicBezier::new(cur, cp1, cp2, next);
1866                cur_sub.extend(cubic.to_quadratics(0.25));
1867                cur = next;
1868                has_current = true;
1869            }
1870            crate::canvas2d::CanvasPathVerb::Arc {
1871                cx,
1872                cy,
1873                radius,
1874                start_angle,
1875                end_angle,
1876                counter_clockwise,
1877            } => {
1878                let acx = ox + cx;
1879                let acy = oy + cy;
1880                let mut sweep = end_angle - start_angle;
1881                if counter_clockwise && sweep > 0.0 {
1882                    sweep -= std::f32::consts::TAU;
1883                } else if !counter_clockwise && sweep < 0.0 {
1884                    sweep += std::f32::consts::TAU;
1885                }
1886                let arc_start = strata_gpu_path::Point2D::new(
1887                    acx + radius * start_angle.cos(),
1888                    acy + radius * start_angle.sin(),
1889                );
1890                if !has_current {
1891                    start = arc_start;
1892                    cur = arc_start;
1893                    has_current = true;
1894                } else if cur.distance_squared(arc_start) > 1e-4 {
1895                    cur_sub.push(strata_gpu_path::QuadraticBezier::new(
1896                        cur,
1897                        cur.lerp(arc_start, 0.5),
1898                        arc_start,
1899                    ));
1900                    cur = arc_start;
1901                }
1902                let steps = ((sweep.abs() / std::f32::consts::FRAC_PI_4).ceil() as usize)
1903                    .clamp(4, 16);
1904                for i in 0..steps {
1905                    let t0 = start_angle + sweep * (i as f32 / steps as f32);
1906                    let t1 = start_angle + sweep * ((i + 1) as f32 / steps as f32);
1907                    let tm = (t0 + t1) * 0.5;
1908                    let cos_h = ((t1 - t0) * 0.5).cos().max(0.1);
1909                    let p0 = strata_gpu_path::Point2D::new(
1910                        acx + radius * t0.cos(),
1911                        acy + radius * t0.sin(),
1912                    );
1913                    let p2 = strata_gpu_path::Point2D::new(
1914                        acx + radius * t1.cos(),
1915                        acy + radius * t1.sin(),
1916                    );
1917                    let p1 = strata_gpu_path::Point2D::new(
1918                        acx + (radius / cos_h) * tm.cos(),
1919                        acy + (radius / cos_h) * tm.sin(),
1920                    );
1921                    cur_sub.push(strata_gpu_path::QuadraticBezier::new(p0, p1, p2));
1922                    cur = p2;
1923                }
1924            }
1925            crate::canvas2d::CanvasPathVerb::Close => {
1926                if has_current && cur.distance_squared(start) > 1e-4 {
1927                    cur_sub.push(strata_gpu_path::QuadraticBezier::new(
1928                        cur,
1929                        cur.lerp(start, 0.5),
1930                        start,
1931                    ));
1932                    cur = start;
1933                }
1934                if !cur_sub.is_empty() {
1935                    subpaths.push((std::mem::take(&mut cur_sub), true));
1936                }
1937            }
1938        }
1939    }
1940    if !cur_sub.is_empty() {
1941        subpaths.push((cur_sub, false));
1942    }
1943    subpaths
1944}
1945
1946fn flatten_quad_subpaths(
1947    subpaths: &[(Vec<strata_gpu_path::QuadraticBezier>, bool)],
1948    steps_per_curve: usize,
1949) -> Vec<Vec<(f32, f32)>> {
1950    let steps = steps_per_curve.max(1);
1951    let mut polys = Vec::with_capacity(subpaths.len());
1952    for (quads, _) in subpaths {
1953        if quads.is_empty() {
1954            continue;
1955        }
1956        let mut pts = Vec::with_capacity(quads.len() * steps + 1);
1957        for (qi, q) in quads.iter().enumerate() {
1958            let a = (q.p0.x - 2.0 * q.p1.x + q.p2.x).hypot(q.p0.y - 2.0 * q.p1.y + q.p2.y);
1959            let seg_steps = if a <= 1e-3 { 1 } else { steps };
1960            let start_step = if qi == 0 { 0 } else { 1 };
1961            for s in start_step..=seg_steps {
1962                let t = s as f32 / seg_steps as f32;
1963                let u = 1.0 - t;
1964                let px = u * u * q.p0.x + 2.0 * u * t * q.p1.x + t * t * q.p2.x;
1965                let py = u * u * q.p0.y + 2.0 * u * t * q.p1.y + t * t * q.p2.y;
1966                pts.push((px, py));
1967            }
1968        }
1969        if pts.len() >= 3 {
1970            polys.push(pts);
1971        }
1972    }
1973    polys
1974}
1975
1976fn poly_layers_bbox(subpaths: &[Vec<(f32, f32)>]) -> Option<Rect> {
1977    let mut min_x = f32::INFINITY;
1978    let mut min_y = f32::INFINITY;
1979    let mut max_x = f32::NEG_INFINITY;
1980    let mut max_y = f32::NEG_INFINITY;
1981    for sub in subpaths {
1982        for &(x, y) in sub {
1983            min_x = min_x.min(x);
1984            min_y = min_y.min(y);
1985            max_x = max_x.max(x);
1986            max_y = max_y.max(y);
1987        }
1988    }
1989    if min_x.is_finite() && min_y.is_finite() && max_x > min_x && max_y > min_y {
1990        Some(Rect::new(min_x, min_y, max_x - min_x, max_y - min_y))
1991    } else {
1992        None
1993    }
1994}
1995
1996/// Batch collection of GPU instanced path segments ready for upload to storage/vertex buffers.
1997#[derive(Debug, Default, Clone, PartialEq)]
1998pub struct GpuPathBatch {
1999    pub segments: Vec<strata_gpu_path::GpuPathSegment>,
2000    /// Compiled non-rectangular/stencil clip masks referenced by [`Self::clip_spans`].
2001    pub clip_masks: Vec<GpuClipMask>,
2002    /// Contiguous segment ranges mapped to their active optional stencil clip mask index.
2003    pub clip_spans: Vec<GpuClipSpan>,
2004}
2005
2006impl GpuPathBatch {
2007    pub fn new() -> Self {
2008        Self::default()
2009    }
2010
2011    pub fn with_capacity(capacity: usize) -> Self {
2012        Self {
2013            segments: Vec::with_capacity(capacity),
2014            clip_masks: Vec::new(),
2015            clip_spans: Vec::new(),
2016        }
2017    }
2018
2019    #[inline]
2020    pub fn push(&mut self, segment: strata_gpu_path::GpuPathSegment) {
2021        self.push_with_clip(segment, None);
2022    }
2023
2024    /// Pushes a path segment associated with an optional non-rectangular stencil clip mask index.
2025    #[inline]
2026    pub fn push_with_clip(
2027        &mut self,
2028        segment: strata_gpu_path::GpuPathSegment,
2029        clip_mask: Option<usize>,
2030    ) {
2031        let idx = self.segments.len();
2032        self.segments.push(segment);
2033        if clip_mask.is_some() || !self.clip_spans.is_empty() {
2034            push_clip_span(&mut self.clip_spans, 1, idx, clip_mask);
2035        }
2036    }
2037
2038    #[inline]
2039    pub fn has_stencil_clips(&self) -> bool {
2040        !self.clip_masks.is_empty()
2041    }
2042
2043    /// Returns the stencil clip mask governing `segment_index`, if any.
2044    pub fn clip_mask_for_segment(&self, segment_index: usize) -> Option<&GpuClipMask> {
2045        let span = self
2046            .clip_spans
2047            .iter()
2048            .find(|s| segment_index >= s.start && segment_index < s.end)?;
2049        span.clip_mask.and_then(|id| self.clip_masks.get(id))
2050    }
2051
2052    #[inline]
2053    pub fn clear(&mut self) {
2054        self.segments.clear();
2055        self.clip_masks.clear();
2056        self.clip_spans.clear();
2057    }
2058
2059    #[inline]
2060    pub fn len(&self) -> usize {
2061        self.segments.len()
2062    }
2063
2064    #[inline]
2065    pub fn is_empty(&self) -> bool {
2066        self.segments.is_empty()
2067    }
2068
2069    #[inline]
2070    pub fn as_bytes(&self) -> &[u8] {
2071        strata_gpu_path::GpuPathSegment::slice_to_bytes(&self.segments)
2072    }
2073
2074    fn emit_clipped_segment(
2075        &mut self,
2076        seg: strata_gpu_path::GpuPathSegment,
2077        q_bbox: Rect,
2078        clip: Rect,
2079        clip_polys: &[Vec<Vec<(f32, f32)>>],
2080        clip_mask_id: Option<usize>,
2081    ) {
2082        if q_bbox.intersect(clip).is_none() {
2083            return;
2084        }
2085        let (emit, mask) = if clip_polys.is_empty() {
2086            (true, None)
2087        } else {
2088            match rect_relation_to_clip_polys(q_bbox, clip_polys) {
2089                ClipContainment::Outside => (false, None),
2090                ClipContainment::Inside => (true, None),
2091                ClipContainment::Partial => (true, clip_mask_id),
2092            }
2093        };
2094        if emit {
2095            self.push_with_clip(seg, mask);
2096        }
2097    }
2098
2099    #[allow(clippy::too_many_arguments)]
2100    fn emit_corner_join(
2101        &mut self,
2102        q0: &strata_gpu_path::QuadraticBezier,
2103        q1: &strata_gpu_path::QuadraticBezier,
2104        sw: f32,
2105        c: [f32; 4],
2106        join: strata_gpu_path::LineJoin,
2107        miter_limit: f32,
2108        extra_flags: u32,
2109        clip: Rect,
2110        clip_polys: &[Vec<Vec<(f32, f32)>>],
2111        clip_mask_id: Option<usize>,
2112    ) {
2113        let j = q0.p2;
2114        let raw_t0 = q0.tangent(1.0);
2115        let raw_t0 = if raw_t0.x * raw_t0.x + raw_t0.y * raw_t0.y > 1e-6 {
2116            raw_t0
2117        } else {
2118            strata_gpu_path::Point2D::new(q0.p2.x - q0.p0.x, q0.p2.y - q0.p0.y)
2119        };
2120        let len0 = (raw_t0.x * raw_t0.x + raw_t0.y * raw_t0.y).sqrt();
2121        let raw_t1 = q1.tangent(0.0);
2122        let raw_t1 = if raw_t1.x * raw_t1.x + raw_t1.y * raw_t1.y > 1e-6 {
2123            raw_t1
2124        } else {
2125            strata_gpu_path::Point2D::new(q1.p2.x - q1.p0.x, q1.p2.y - q1.p0.y)
2126        };
2127        let len1 = (raw_t1.x * raw_t1.x + raw_t1.y * raw_t1.y).sqrt();
2128        if len0 <= 1e-5 || len1 <= 1e-5 {
2129            return;
2130        }
2131        let t0 = strata_gpu_path::Point2D::new(raw_t0.x / len0, raw_t0.y / len0);
2132        let t1 = strata_gpu_path::Point2D::new(raw_t1.x / len1, raw_t1.y / len1);
2133        let dot_t = t0.x * t1.x + t0.y * t1.y;
2134        if dot_t > 0.995 {
2135            return;
2136        }
2137
2138        let half_w = sw * 0.5;
2139        let join_bbox = Rect::new(
2140            j.x - half_w * miter_limit.max(1.0) - 2.0,
2141            j.y - half_w * miter_limit.max(1.0) - 2.0,
2142            (half_w * miter_limit.max(1.0) + 2.0) * 2.0,
2143            (half_w * miter_limit.max(1.0) + 2.0) * 2.0,
2144        );
2145
2146        let join_flag_bit = match join {
2147            strata_gpu_path::LineJoin::Miter => 0,
2148            strata_gpu_path::LineJoin::Round => strata_gpu_path::FLAG_JOIN_ROUND,
2149            strata_gpu_path::LineJoin::Bevel => strata_gpu_path::FLAG_JOIN_BEVEL,
2150        };
2151
2152        if join == strata_gpu_path::LineJoin::Round {
2153            let deg = strata_gpu_path::QuadraticBezier::new(j, j, j);
2154            let seg = strata_gpu_path::GpuPathSegment::from_quadratic(
2155                &deg,
2156                sw,
2157                strata_gpu_path::FLAG_STROKE
2158                    | strata_gpu_path::FLAG_CAP_ROUND
2159                    | strata_gpu_path::FLAG_START_OPEN
2160                    | strata_gpu_path::FLAG_END_OPEN
2161                    | join_flag_bit
2162                    | extra_flags,
2163                c,
2164                0.0,
2165            );
2166            self.emit_clipped_segment(seg, join_bbox, clip, clip_polys, clip_mask_id);
2167            return;
2168        }
2169
2170        let cross = t0.x * t1.y - t0.y * t1.x;
2171        if cross.abs() < 1e-4 {
2172            return;
2173        }
2174        let sign = if cross > 0.0 { -1.0 } else { 1.0 };
2175        let n0x = sign * (-t0.y);
2176        let n0y = sign * t0.x;
2177        let n1x = sign * (-t1.y);
2178        let n1y = sign * t1.x;
2179        let a = strata_gpu_path::Point2D::new(j.x + n0x * half_w, j.y + n0y * half_w);
2180        let b = strata_gpu_path::Point2D::new(j.x + n1x * half_w, j.y + n1y * half_w);
2181        if a.distance_squared(b) <= 0.04 {
2182            return;
2183        }
2184
2185        let sum_x = n0x + n1x;
2186        let sum_y = n0y + n1y;
2187        let sum_len = sum_x.hypot(sum_y);
2188        if sum_len <= 1e-5 {
2189            return;
2190        }
2191        let miter_ratio = 2.0 / sum_len;
2192        if join == strata_gpu_path::LineJoin::Miter && miter_ratio <= miter_limit.max(1.0) {
2193            let denom = 1.0 + n0x * n1x + n0y * n1y;
2194            if denom > 1e-4 {
2195                let m_scale = half_w / denom;
2196                let m = strata_gpu_path::Point2D::new(j.x + sum_x * m_scale, j.y + sum_y * m_scale);
2197                let q_a = strata_gpu_path::QuadraticBezier::new(j, a, m);
2198                let q_b = strata_gpu_path::QuadraticBezier::new(j, m, b);
2199                let flags = strata_gpu_path::FLAG_FILL | strata_gpu_path::FLAG_TRIANGLE | extra_flags;
2200                self.emit_clipped_segment(
2201                    strata_gpu_path::GpuPathSegment::from_quadratic(&q_a, sw, flags, c, 0.0),
2202                    quad_world_bounds(&q_a, 2.0),
2203                    clip,
2204                    clip_polys,
2205                    clip_mask_id,
2206                );
2207                self.emit_clipped_segment(
2208                    strata_gpu_path::GpuPathSegment::from_quadratic(&q_b, sw, flags, c, 0.0),
2209                    quad_world_bounds(&q_b, 2.0),
2210                    clip,
2211                    clip_polys,
2212                    clip_mask_id,
2213                );
2214                return;
2215            }
2216        }
2217
2218        let q_bev = strata_gpu_path::QuadraticBezier::new(j, a, b);
2219        let flags = strata_gpu_path::FLAG_FILL
2220            | strata_gpu_path::FLAG_JOIN_BEVEL
2221            | strata_gpu_path::FLAG_TRIANGLE
2222            | extra_flags;
2223        self.emit_clipped_segment(
2224            strata_gpu_path::GpuPathSegment::from_quadratic(&q_bev, sw, flags, c, 0.0),
2225            quad_world_bounds(&q_bev, 2.0),
2226            clip,
2227            clip_polys,
2228            clip_mask_id,
2229        );
2230    }
2231
2232    #[allow(clippy::too_many_arguments)]
2233    fn emit_subpath_strokes(
2234        &mut self,
2235        quads: &[strata_gpu_path::QuadraticBezier],
2236        closed: bool,
2237        sw: f32,
2238        col: Color,
2239        cap: strata_gpu_path::LineCap,
2240        join: strata_gpu_path::LineJoin,
2241        miter_limit: f32,
2242        dash: &[f32],
2243        dash_offset: f32,
2244        extra_flags: u32,
2245        clip_opt: Option<Rect>,
2246        clip_polys: &[Vec<Vec<(f32, f32)>>],
2247        clip_mask_id: Option<usize>,
2248    ) {
2249        let Some(clip) = clip_opt else {
2250            return;
2251        };
2252        if quads.is_empty() {
2253            return;
2254        }
2255        let (cr, cg, cb, ca) = col.to_f32();
2256        let c = [cr, cg, cb, ca];
2257        let pad = sw * 1.5 + 2.0;
2258
2259        let dash_period: f32 = dash.iter().copied().filter(|&d| d >= 0.0 && d.is_finite()).sum();
2260        if dash.iter().any(|&d| d > 0.0) && dash_period > 1e-4 {
2261            for dash_sub in strata_gpu_path::dash_quadratics_with_offset(quads, dash, dash_offset) {
2262                let n = dash_sub.len();
2263                if n == 0 {
2264                    continue;
2265                }
2266                for (i, q) in dash_sub.iter().enumerate() {
2267                    let flags = strata_gpu_path::stroke_style_flags(
2268                        cap,
2269                        join,
2270                        false,
2271                        i == 0,
2272                        i + 1 == n,
2273                    ) | extra_flags;
2274                    let seg = strata_gpu_path::GpuPathSegment::from_quadratic(q, sw, flags, c, 0.0);
2275                    self.emit_clipped_segment(
2276                        seg,
2277                        quad_world_bounds(q, pad),
2278                        clip,
2279                        clip_polys,
2280                        clip_mask_id,
2281                    );
2282                }
2283                for i in 0..n.saturating_sub(1) {
2284                    self.emit_corner_join(
2285                        &dash_sub[i],
2286                        &dash_sub[i + 1],
2287                        sw,
2288                        c,
2289                        join,
2290                        miter_limit,
2291                        extra_flags,
2292                        clip,
2293                        clip_polys,
2294                        clip_mask_id,
2295                    );
2296                }
2297            }
2298            return;
2299        }
2300
2301        // Split into connected runs cleanly in case `quads` holds multiple disconnected subpaths.
2302        let mut run_start = 0usize;
2303        for idx in 1..=quads.len() {
2304            let disconnected = idx == quads.len()
2305                || quads[idx - 1]
2306                    .p2
2307                    .distance_squared(quads[idx].p0)
2308                    > 1e-3;
2309            if disconnected {
2310                let run = &quads[run_start..idx];
2311                let n = run.len();
2312                let is_loop = closed
2313                    && n >= 2
2314                    && run.last().unwrap().p2.distance_squared(run[0].p0) <= 1e-3;
2315                for (i, q) in run.iter().enumerate() {
2316                    let start_open = !is_loop && i == 0;
2317                    let end_open = !is_loop && i + 1 == n;
2318                    let flags = strata_gpu_path::stroke_style_flags(
2319                        cap,
2320                        join,
2321                        is_loop,
2322                        start_open,
2323                        end_open,
2324                    ) | extra_flags;
2325                    let seg = strata_gpu_path::GpuPathSegment::from_quadratic(q, sw, flags, c, 0.0);
2326                    self.emit_clipped_segment(
2327                        seg,
2328                        quad_world_bounds(q, pad),
2329                        clip,
2330                        clip_polys,
2331                        clip_mask_id,
2332                    );
2333                }
2334                for i in 0..n.saturating_sub(1) {
2335                    self.emit_corner_join(
2336                        &run[i],
2337                        &run[i + 1],
2338                        sw,
2339                        c,
2340                        join,
2341                        miter_limit,
2342                        extra_flags,
2343                        clip,
2344                        clip_polys,
2345                        clip_mask_id,
2346                    );
2347                }
2348                if is_loop {
2349                    self.emit_corner_join(
2350                        &run[n - 1],
2351                        &run[0],
2352                        sw,
2353                        c,
2354                        join,
2355                        miter_limit,
2356                        extra_flags,
2357                        clip,
2358                        clip_polys,
2359                        clip_mask_id,
2360                    );
2361                }
2362                run_start = idx;
2363            }
2364        }
2365    }
2366
2367    #[allow(clippy::too_many_arguments)]
2368    fn emit_fill_quads(
2369        &mut self,
2370        quads: &[strata_gpu_path::QuadraticBezier],
2371        sw: f32,
2372        col: Color,
2373        extra_flags: u32,
2374        clip_opt: Option<Rect>,
2375        clip_polys: &[Vec<Vec<(f32, f32)>>],
2376        clip_mask_id: Option<usize>,
2377    ) {
2378        let Some(clip) = clip_opt else {
2379            return;
2380        };
2381        let (cr, cg, cb, ca) = col.to_f32();
2382        let c = [cr, cg, cb, ca];
2383        for q in quads {
2384            let seg = strata_gpu_path::GpuPathSegment::from_quadratic(
2385                q,
2386                sw,
2387                strata_gpu_path::FLAG_FILL | extra_flags,
2388                c,
2389                0.0,
2390            );
2391            self.emit_clipped_segment(seg, quad_world_bounds(q, 2.0), clip, clip_polys, clip_mask_id);
2392        }
2393    }
2394
2395    /// Compiles vector paths from a DisplayList into GPU path segments.
2396    pub fn from_display_list(
2397        list: &DisplayList,
2398        viewport_width: f32,
2399        viewport_height: f32,
2400    ) -> Self {
2401        Self::from_display_list_damaged(list, None, viewport_width, viewport_height)
2402    }
2403
2404    /// Compiles vector paths from a DisplayList into GPU path segments with optional damage scissoring.
2405    pub fn from_display_list_damaged(
2406        list: &DisplayList,
2407        damage: Option<Rect>,
2408        viewport_width: f32,
2409        viewport_height: f32,
2410    ) -> Self {
2411        let mut batch = Self::new();
2412        let mut clip_stack: Vec<Rect> = Vec::new();
2413        let default_clip = damage.unwrap_or(Rect::new(0.0, 0.0, viewport_width, viewport_height));
2414
2415        for cmd in list.commands() {
2416            if let DrawCommand::PushClip { bounds, .. } = cmd {
2417                let combined = match clip_stack.last() {
2418                    Some(prev) => prev.intersect(*bounds).unwrap_or(Rect::zero()),
2419                    None => *bounds,
2420                };
2421                clip_stack.push(combined);
2422                continue;
2423            } else if let DrawCommand::PopClip = cmd {
2424                clip_stack.pop();
2425                continue;
2426            }
2427
2428            let current_clip = match clip_stack.last() {
2429                Some(prev) => match prev.intersect(default_clip) {
2430                    Some(c) => c,
2431                    None => continue,
2432                },
2433                None => default_clip,
2434            };
2435
2436            match cmd {
2437                DrawCommand::DrawGpuPath {
2438                    bounds,
2439                    path,
2440                    stroke,
2441                    fill_color,
2442                    stroke_color,
2443                    transform: _,
2444                } => {
2445                    if bounds.intersect(current_clip).is_none() {
2446                        continue;
2447                    }
2448                    let even_odd = if path.fill_rule == Some(strata_gpu_path::FillRule::EvenOdd) {
2449                        strata_gpu_path::FLAG_EVEN_ODD
2450                    } else {
2451                        0
2452                    };
2453                    let subpaths = subpaths_from_path_verbs(&path.verbs, 0.0, 0.0, 1.0, 1.0, 0.25);
2454                    let stroke_w = stroke.map(|s| s.width).unwrap_or(1.0);
2455                    let cap = stroke.map(|s| s.cap).unwrap_or_default();
2456                    let join = stroke.map(|s| s.join).unwrap_or_default();
2457                    let miter_limit = stroke.map(|s| s.miter_limit).unwrap_or(4.0);
2458
2459                    if let Some(fc) = fill_color {
2460                        for (sub, closed) in &subpaths {
2461                            let closed_flag = if *closed {
2462                                strata_gpu_path::FLAG_CLOSED
2463                            } else {
2464                                0
2465                            };
2466                            batch.emit_fill_quads(
2467                                sub,
2468                                stroke_w,
2469                                *fc,
2470                                even_odd | closed_flag,
2471                                Some(current_clip),
2472                                &[],
2473                                None,
2474                            );
2475                        }
2476                    }
2477
2478                    if let Some(sc) = stroke_color {
2479                        for (sub, closed) in &subpaths {
2480                            batch.emit_subpath_strokes(
2481                                sub,
2482                                *closed,
2483                                stroke_w,
2484                                *sc,
2485                                cap,
2486                                join,
2487                                miter_limit,
2488                                &[],
2489                                0.0,
2490                                even_odd,
2491                                Some(current_clip),
2492                                &[],
2493                                None,
2494                            );
2495                        }
2496                    }
2497                }
2498                DrawCommand::DrawSvgPath {
2499                    bounds,
2500                    path_data,
2501                    stroke_color,
2502                    fill_color,
2503                    stroke_width,
2504                    stroke_linecap,
2505                    stroke_linejoin,
2506                    stroke_dasharray,
2507                    fill_rule,
2508                    view_box,
2509                } => {
2510                    if bounds.intersect(current_clip).is_none() {
2511                        continue;
2512                    }
2513                    let scale_x = if view_box.0 > 0.0 {
2514                        bounds.width / view_box.0
2515                    } else {
2516                        1.0
2517                    };
2518                    let scale_y = if view_box.1 > 0.0 {
2519                        bounds.height / view_box.1
2520                    } else {
2521                        1.0
2522                    };
2523                    let avg_scale = ((scale_x + scale_y) * 0.5).max(0.001);
2524                    let parsed = strata_gpu_path::PathBuilder::from_svg(path_data);
2525                    let subpaths = subpaths_from_path_verbs(
2526                        &parsed.verbs,
2527                        bounds.x,
2528                        bounds.y,
2529                        scale_x,
2530                        scale_y,
2531                        0.25,
2532                    );
2533
2534                    let even_odd = if *fill_rule == strata_layout::FillRule::EvenOdd {
2535                        strata_gpu_path::FLAG_EVEN_ODD
2536                    } else {
2537                        0
2538                    };
2539                    let sw = *stroke_width * avg_scale;
2540                    let cap = layout_cap_to_gpu(*stroke_linecap);
2541                    let join = layout_join_to_gpu(*stroke_linejoin);
2542
2543                    if let Some(fc) = fill_color {
2544                        for (sub, closed) in &subpaths {
2545                            let closed_flag = if *closed {
2546                                strata_gpu_path::FLAG_CLOSED
2547                            } else {
2548                                0
2549                            };
2550                            batch.emit_fill_quads(
2551                                sub,
2552                                sw,
2553                                *fc,
2554                                even_odd | closed_flag,
2555                                Some(current_clip),
2556                                &[],
2557                                None,
2558                            );
2559                        }
2560                    }
2561
2562                    if let Some(sc) = stroke_color {
2563                        let scaled_dashes: Vec<f32> =
2564                            stroke_dasharray.iter().map(|&d| d * avg_scale).collect();
2565                        for (sub, closed) in &subpaths {
2566                            batch.emit_subpath_strokes(
2567                                sub,
2568                                *closed,
2569                                sw,
2570                                *sc,
2571                                cap,
2572                                join,
2573                                4.0,
2574                                &scaled_dashes,
2575                                0.0,
2576                                even_odd,
2577                                Some(current_clip),
2578                                &[],
2579                                None,
2580                            );
2581                        }
2582                    }
2583                }
2584                DrawCommand::DrawCanvas2D { bounds, commands } => {
2585                    let Some(base_clip) = bounds.intersect(current_clip) else {
2586                        continue;
2587                    };
2588                    let ox = bounds.x;
2589                    let oy = bounds.y;
2590                    let mut active_clip = Some(base_clip);
2591                    let mut line_dash: Vec<f32> = Vec::new();
2592                    let mut dash_offset: f32 = 0.0;
2593                    let mut line_cap = strata_gpu_path::LineCap::Butt;
2594                    let mut line_join = strata_gpu_path::LineJoin::Miter;
2595                    let mut clip_polys: Vec<Vec<Vec<(f32, f32)>>> = Vec::new();
2596                    let mut clip_mask_id: Option<usize> = None;
2597                    #[allow(clippy::type_complexity)]
2598                    let mut state_stack: Vec<(
2599                        Option<Rect>,
2600                        Vec<f32>,
2601                        f32,
2602                        strata_gpu_path::LineCap,
2603                        strata_gpu_path::LineJoin,
2604                        Vec<Vec<Vec<(f32, f32)>>>,
2605                        Option<usize>,
2606                    )> = Vec::new();
2607
2608                    let rect_quads = |r: Rect| -> [strata_gpu_path::QuadraticBezier; 4] {
2609                        let p0 = strata_gpu_path::Point2D::new(ox + r.x, oy + r.y);
2610                        let p1 = strata_gpu_path::Point2D::new(ox + r.x + r.width, oy + r.y);
2611                        let p2 =
2612                            strata_gpu_path::Point2D::new(ox + r.x + r.width, oy + r.y + r.height);
2613                        let p3 = strata_gpu_path::Point2D::new(ox + r.x, oy + r.y + r.height);
2614                        [
2615                            strata_gpu_path::QuadraticBezier::new(p0, p0.lerp(p1, 0.5), p1),
2616                            strata_gpu_path::QuadraticBezier::new(p1, p1.lerp(p2, 0.5), p2),
2617                            strata_gpu_path::QuadraticBezier::new(p2, p2.lerp(p3, 0.5), p3),
2618                            strata_gpu_path::QuadraticBezier::new(p3, p3.lerp(p0, 0.5), p0),
2619                        ]
2620                    };
2621
2622                    for ccmd in commands {
2623                        match ccmd {
2624                            crate::canvas2d::CanvasCommand::Save => {
2625                                state_stack.push((
2626                                    active_clip,
2627                                    line_dash.clone(),
2628                                    dash_offset,
2629                                    line_cap,
2630                                    line_join,
2631                                    clip_polys.clone(),
2632                                    clip_mask_id,
2633                                ));
2634                            }
2635                            crate::canvas2d::CanvasCommand::Restore => {
2636                                if let Some((
2637                                    prev_clip,
2638                                    prev_dash,
2639                                    prev_offset,
2640                                    prev_cap,
2641                                    prev_join,
2642                                    prev_polys,
2643                                    prev_mask,
2644                                )) = state_stack.pop()
2645                                {
2646                                    active_clip = prev_clip;
2647                                    line_dash = prev_dash;
2648                                    dash_offset = prev_offset;
2649                                    line_cap = prev_cap;
2650                                    line_join = prev_join;
2651                                    clip_polys = prev_polys;
2652                                    clip_mask_id = prev_mask;
2653                                }
2654                            }
2655                            crate::canvas2d::CanvasCommand::SetLineDash { segments, offset } => {
2656                                line_dash = segments.clone();
2657                                dash_offset = *offset;
2658                            }
2659                            crate::canvas2d::CanvasCommand::SetLineCap(cap) => {
2660                                line_cap = layout_cap_to_gpu(*cap);
2661                            }
2662                            crate::canvas2d::CanvasCommand::SetLineJoin(join) => {
2663                                line_join = layout_join_to_gpu(*join);
2664                            }
2665                            crate::canvas2d::CanvasCommand::ClipPath { verbs } => {
2666                                let subpaths = crate::canvas2d::flatten_canvas_verbs(verbs, ox, oy);
2667                                if !subpaths.is_empty() {
2668                                    if let Some(vbbox) =
2669                                        crate::canvas2d::canvas_verbs_bounds(verbs, ox, oy)
2670                                    {
2671                                        active_clip = active_clip.and_then(|c| c.intersect(vbbox));
2672                                    }
2673                                    if !subpaths_are_axis_aligned_rect(&subpaths) {
2674                                        clip_polys.push(subpaths);
2675                                        clip_mask_id = resolve_or_push_clip_mask(
2676                                            &mut batch.clip_masks,
2677                                            active_clip,
2678                                            &clip_polys,
2679                                        );
2680                                    }
2681                                }
2682                            }
2683                            crate::canvas2d::CanvasCommand::FillRect {
2684                                bounds: rb,
2685                                color,
2686                            } => {
2687                                let world_rect =
2688                                    Rect::new(ox + rb.x, oy + rb.y, rb.width, rb.height);
2689                                if active_clip
2690                                    .and_then(|c| c.intersect(world_rect))
2691                                    .is_some()
2692                                {
2693                                    let quads = rect_quads(*rb);
2694                                    batch.emit_fill_quads(
2695                                        &quads,
2696                                        1.0,
2697                                        *color,
2698                                        strata_gpu_path::FLAG_CLOSED,
2699                                        active_clip,
2700                                        &clip_polys,
2701                                        clip_mask_id,
2702                                    );
2703                                }
2704                            }
2705                            crate::canvas2d::CanvasCommand::StrokeRect {
2706                                bounds: rb,
2707                                color,
2708                                line_width,
2709                            } => {
2710                                let quads = rect_quads(*rb);
2711                                batch.emit_subpath_strokes(
2712                                    &quads,
2713                                    true,
2714                                    *line_width,
2715                                    *color,
2716                                    line_cap,
2717                                    line_join,
2718                                    10.0,
2719                                    &line_dash,
2720                                    dash_offset,
2721                                    0,
2722                                    active_clip,
2723                                    &clip_polys,
2724                                    clip_mask_id,
2725                                );
2726                            }
2727                            crate::canvas2d::CanvasCommand::DrawLine {
2728                                p0,
2729                                p1,
2730                                color,
2731                                line_width,
2732                            } => {
2733                                let a = strata_gpu_path::Point2D::new(ox + p0.0, oy + p0.1);
2734                                let b = strata_gpu_path::Point2D::new(ox + p1.0, oy + p1.1);
2735                                let q = strata_gpu_path::QuadraticBezier::new(a, a.lerp(b, 0.5), b);
2736                                batch.emit_subpath_strokes(
2737                                    &[q],
2738                                    false,
2739                                    *line_width,
2740                                    *color,
2741                                    line_cap,
2742                                    line_join,
2743                                    10.0,
2744                                    &line_dash,
2745                                    dash_offset,
2746                                    0,
2747                                    active_clip,
2748                                    &clip_polys,
2749                                    clip_mask_id,
2750                                );
2751                            }
2752                            crate::canvas2d::CanvasCommand::DrawCircle {
2753                                center,
2754                                radius,
2755                                fill_color,
2756                                stroke_color,
2757                                line_width,
2758                            } => {
2759                                let circle_quads =
2760                                    circle_to_quads(ox + center.0, oy + center.1, *radius);
2761                                if let Some(fc) = fill_color {
2762                                    batch.emit_fill_quads(
2763                                        &circle_quads,
2764                                        *line_width,
2765                                        *fc,
2766                                        strata_gpu_path::FLAG_CLOSED,
2767                                        active_clip,
2768                                        &clip_polys,
2769                                        clip_mask_id,
2770                                    );
2771                                }
2772                                if let Some(sc) = stroke_color {
2773                                    batch.emit_subpath_strokes(
2774                                        &circle_quads,
2775                                        true,
2776                                        *line_width,
2777                                        *sc,
2778                                        line_cap,
2779                                        line_join,
2780                                        10.0,
2781                                        &line_dash,
2782                                        dash_offset,
2783                                        0,
2784                                        active_clip,
2785                                        &clip_polys,
2786                                        clip_mask_id,
2787                                    );
2788                                }
2789                            }
2790                            crate::canvas2d::CanvasCommand::DrawPath {
2791                                verbs,
2792                                fill_color,
2793                                stroke_color,
2794                                line_width,
2795                            } => {
2796                                let subpaths = canvas_path_verbs_to_quad_subpaths(verbs, ox, oy);
2797
2798                                if let Some(fc) = fill_color {
2799                                    for (sub, closed) in &subpaths {
2800                                        let closed_flag = if *closed {
2801                                            strata_gpu_path::FLAG_CLOSED
2802                                        } else {
2803                                            0
2804                                        };
2805                                        batch.emit_fill_quads(
2806                                            sub,
2807                                            *line_width,
2808                                            *fc,
2809                                            closed_flag,
2810                                            active_clip,
2811                                            &clip_polys,
2812                                            clip_mask_id,
2813                                        );
2814                                    }
2815                                }
2816                                if let Some(sc) = stroke_color {
2817                                    for (sub, closed) in &subpaths {
2818                                        batch.emit_subpath_strokes(
2819                                            sub,
2820                                            *closed,
2821                                            *line_width,
2822                                            *sc,
2823                                            line_cap,
2824                                            line_join,
2825                                            10.0,
2826                                            &line_dash,
2827                                            dash_offset,
2828                                            0,
2829                                            active_clip,
2830                                            &clip_polys,
2831                                            clip_mask_id,
2832                                        );
2833                                    }
2834                                }
2835                            }
2836                            crate::canvas2d::CanvasCommand::ClearRect { .. }
2837                            | crate::canvas2d::CanvasCommand::FillText { .. }
2838                            | crate::canvas2d::CanvasCommand::StrokeText { .. } => {}
2839                        }
2840                    }
2841                }
2842                _ => {}
2843            }
2844        }
2845
2846        batch
2847    }
2848}
2849
2850/// High-level orchestration pipeline for compiling vector paths into GPU compute/render buffers.
2851#[derive(Debug, Clone)]
2852pub struct GpuPathPipeline {
2853    pub viewport_width: f32,
2854    pub viewport_height: f32,
2855    pub uniforms: strata_gpu_path::GpuPathUniforms,
2856    pub batch: GpuPathBatch,
2857    pub total_uploaded_bytes: usize,
2858    pub compiled_frames: u64,
2859}
2860
2861impl GpuPathPipeline {
2862    pub fn new(viewport_width: f32, viewport_height: f32) -> Self {
2863        Self {
2864            viewport_width,
2865            viewport_height,
2866            uniforms: strata_gpu_path::GpuPathUniforms::new(
2867                viewport_width,
2868                viewport_height,
2869                0.25,
2870                0,
2871            ),
2872            batch: GpuPathBatch::new(),
2873            total_uploaded_bytes: 0,
2874            compiled_frames: 0,
2875        }
2876    }
2877
2878    pub fn resize(&mut self, width: f32, height: f32) {
2879        self.viewport_width = width;
2880        self.viewport_height = height;
2881        self.uniforms =
2882            strata_gpu_path::GpuPathUniforms::new(width, height, 0.25, self.batch.len() as u32);
2883    }
2884
2885    /// Compiles a frame from a DisplayList and optional damage rectangle into the internal path batch buffer.
2886    pub fn compile_frame(&mut self, list: &DisplayList, damage: Option<Rect>) -> usize {
2887        // Most frames contain no vector paths; avoid walking clips and
2888        // rebuilding an empty batch when nothing needs compiling.
2889        let has_paths = list.commands().iter().any(|cmd| {
2890            matches!(
2891                cmd,
2892                DrawCommand::DrawGpuPath { .. }
2893                    | DrawCommand::DrawSvgPath { .. }
2894                    | DrawCommand::DrawCanvas2D { .. }
2895            )
2896        });
2897        if !has_paths {
2898            if !self.batch.is_empty() {
2899                self.batch.clear();
2900                self.uniforms.curve_count = 0;
2901            }
2902            return 0;
2903        }
2904        self.batch = GpuPathBatch::from_display_list_damaged(
2905            list,
2906            damage,
2907            self.viewport_width,
2908            self.viewport_height,
2909        );
2910
2911        self.uniforms.curve_count = self.batch.len() as u32;
2912        let byte_count = self.batch.as_bytes().len() + self.uniforms.as_bytes().len();
2913        self.total_uploaded_bytes += byte_count;
2914        self.compiled_frames += 1;
2915
2916        self.batch.len()
2917    }
2918
2919    #[inline]
2920    pub fn segment_bytes(&self) -> &[u8] {
2921        self.batch.as_bytes()
2922    }
2923
2924    #[inline]
2925    pub fn uniform_bytes(&self) -> &[u8] {
2926        self.uniforms.as_bytes()
2927    }
2928}
2929
2930/// Parsed and compiled WGSL shader module with verified reflection data.
2931#[derive(Debug, Clone, PartialEq)]
2932pub struct GpuShaderModule {
2933    pub source: String,
2934    pub has_vertex_entry: bool,
2935    pub has_fragment_entry: bool,
2936    pub vertex_entry: String,
2937    pub fragment_entry: String,
2938    pub uniforms_declared: Vec<String>,
2939    pub bind_groups_declared: usize,
2940}
2941
2942/// Compiler and validator for WGSL shaders ensuring runtime hardware compatibility.
2943#[derive(Debug, Default, Clone)]
2944pub struct GpuShaderCompiler;
2945
2946impl GpuShaderCompiler {
2947    pub fn new() -> Self {
2948        Self
2949    }
2950
2951    /// Compiles and validates a WGSL source string, returning a `GpuShaderModule` or an error.
2952    pub fn compile(&self, source: &str) -> Result<GpuShaderModule, String> {
2953        let has_vertex_entry = source.contains("@vertex");
2954        let has_fragment_entry = source.contains("@fragment");
2955
2956        if !has_vertex_entry && !has_fragment_entry && !source.contains("@compute") {
2957            return Err(
2958                "WGSL shader missing @vertex, @fragment, or @compute entry point".to_string(),
2959            );
2960        }
2961
2962        let mut vertex_entry = "vs_main".to_string();
2963        let mut fragment_entry = "fs_main".to_string();
2964
2965        for line in source.lines() {
2966            let trimmed = line.trim();
2967            if trimmed.starts_with("fn ") {
2968                let name = trimmed
2969                    .trim_start_matches("fn ")
2970                    .split('(')
2971                    .next()
2972                    .unwrap_or("")
2973                    .trim();
2974                if source.contains(&format!("@vertex\nfn {}", name))
2975                    || source.contains(&format!("@vertex fn {}", name))
2976                {
2977                    vertex_entry = name.to_string();
2978                }
2979                if source.contains(&format!("@fragment\nfn {}", name))
2980                    || source.contains(&format!("@fragment fn {}", name))
2981                {
2982                    fragment_entry = name.to_string();
2983                }
2984            }
2985        }
2986
2987        let mut uniforms = Vec::new();
2988        for line in source.lines() {
2989            if line.contains("var<uniform>") {
2990                if let Some(name) = line.split("var<uniform>").nth(1) {
2991                    let u_name = name.split(':').next().unwrap_or("").trim();
2992                    if !u_name.is_empty() {
2993                        uniforms.push(u_name.to_string());
2994                    }
2995                }
2996            }
2997        }
2998
2999        let bind_groups = source.matches("@group(").count();
3000
3001        Ok(GpuShaderModule {
3002            source: source.to_string(),
3003            has_vertex_entry,
3004            has_fragment_entry,
3005            vertex_entry,
3006            fragment_entry,
3007            uniforms_declared: uniforms,
3008            bind_groups_declared: bind_groups,
3009        })
3010    }
3011}
3012
3013/// Vertex attribute data format.
3014#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3015pub enum GpuVertexFormat {
3016    Float32x2,
3017    Float32x3,
3018    Float32x4,
3019    Uint32x2,
3020    Uint32x4,
3021}
3022
3023impl GpuVertexFormat {
3024    pub const fn byte_size(&self) -> usize {
3025        match self {
3026            Self::Float32x2 | Self::Uint32x2 => 8,
3027            Self::Float32x3 => 12,
3028            Self::Float32x4 | Self::Uint32x4 => 16,
3029        }
3030    }
3031}
3032
3033/// Individual vertex attribute descriptor.
3034#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3035pub struct GpuVertexAttribute {
3036    pub format: GpuVertexFormat,
3037    pub offset: u64,
3038    pub shader_location: u32,
3039}
3040
3041/// Step mode for vertex buffer stepping.
3042#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
3043pub enum GpuVertexStepMode {
3044    #[default]
3045    Vertex,
3046    Instance,
3047}
3048
3049/// Vertex buffer layout specifying stride and attributes.
3050#[derive(Debug, Clone, PartialEq)]
3051pub struct GpuVertexBufferLayout {
3052    pub array_stride: u64,
3053    pub step_mode: GpuVertexStepMode,
3054    pub attributes: Vec<GpuVertexAttribute>,
3055}
3056
3057/// Primitive topology for rasterization.
3058#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
3059pub enum GpuPrimitiveTopology {
3060    PointList,
3061    LineList,
3062    LineStrip,
3063    #[default]
3064    TriangleList,
3065    TriangleStrip,
3066}
3067
3068/// Depth comparison function for early-Z culling and depth bounds testing.
3069#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
3070pub enum GpuCompareFunction {
3071    Never,
3072    #[default]
3073    Less,
3074    Equal,
3075    LessEqual,
3076    Greater,
3077    NotEqual,
3078    GreaterEqual,
3079    Always,
3080}
3081
3082/// Depth/stencil state for hardware depth attachment.
3083#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3084pub struct GpuDepthStencilState {
3085    pub format: crate::swapchain::SwapchainFormat,
3086    pub depth_write_enabled: bool,
3087    pub depth_compare: GpuCompareFunction,
3088}
3089
3090impl Default for GpuDepthStencilState {
3091    fn default() -> Self {
3092        Self {
3093            format: crate::swapchain::SwapchainFormat::Depth32Float,
3094            depth_write_enabled: true,
3095            depth_compare: GpuCompareFunction::LessEqual,
3096        }
3097    }
3098}
3099
3100impl GpuDepthStencilState {
3101    /// Evaluates early-Z depth comparison between current depth buffer value and incoming fragment depth.
3102    pub fn passes_test(&self, current_depth: f32, new_depth: f32) -> bool {
3103        match self.depth_compare {
3104            GpuCompareFunction::Never => false,
3105            GpuCompareFunction::Less => new_depth < current_depth,
3106            GpuCompareFunction::Equal => (new_depth - current_depth).abs() < 1e-6,
3107            GpuCompareFunction::LessEqual => new_depth <= current_depth + 1e-6,
3108            GpuCompareFunction::Greater => new_depth > current_depth,
3109            GpuCompareFunction::NotEqual => (new_depth - current_depth).abs() >= 1e-6,
3110            GpuCompareFunction::GreaterEqual => new_depth >= current_depth - 1e-6,
3111            GpuCompareFunction::Always => true,
3112        }
3113    }
3114}
3115
3116/// Hardware-accelerated GPU render pipeline configuration.
3117#[derive(Debug, Clone)]
3118pub struct GpuRenderPipeline {
3119    pub shader_module: GpuShaderModule,
3120    pub vertex_layout: GpuVertexBufferLayout,
3121    pub instance_layout: Option<GpuVertexBufferLayout>,
3122    pub primitive_topology: GpuPrimitiveTopology,
3123    pub depth_stencil: Option<GpuDepthStencilState>,
3124}
3125
3126impl GpuRenderPipeline {
3127    /// Constructs an authentic instanced UI quad render pipeline binding WGSL_ANALYTICAL_QUAD_SHADER.
3128    pub fn new_instanced_quad_pipeline(
3129        viewport_width: f32,
3130        viewport_height: f32,
3131    ) -> Result<Self, String> {
3132        let _ = (viewport_width, viewport_height);
3133        let compiler = GpuShaderCompiler::new();
3134        let shader_module = compiler.compile(WGSL_ANALYTICAL_QUAD_SHADER)?;
3135
3136        let vertex_layout = GpuVertexBufferLayout {
3137            array_stride: 8,
3138            step_mode: GpuVertexStepMode::Vertex,
3139            attributes: vec![GpuVertexAttribute {
3140                format: GpuVertexFormat::Float32x2,
3141                offset: 0,
3142                shader_location: 0,
3143            }],
3144        };
3145
3146        let instance_layout = GpuVertexBufferLayout {
3147            array_stride: 96,
3148            step_mode: GpuVertexStepMode::Instance,
3149            attributes: vec![
3150                GpuVertexAttribute {
3151                    format: GpuVertexFormat::Float32x4,
3152                    offset: 0,
3153                    shader_location: 1,
3154                },
3155                GpuVertexAttribute {
3156                    format: GpuVertexFormat::Float32x4,
3157                    offset: 16,
3158                    shader_location: 2,
3159                },
3160                GpuVertexAttribute {
3161                    format: GpuVertexFormat::Float32x4,
3162                    offset: 32,
3163                    shader_location: 3,
3164                },
3165                GpuVertexAttribute {
3166                    format: GpuVertexFormat::Float32x4,
3167                    offset: 48,
3168                    shader_location: 4,
3169                },
3170                GpuVertexAttribute {
3171                    format: GpuVertexFormat::Float32x4,
3172                    offset: 64,
3173                    shader_location: 5,
3174                },
3175                GpuVertexAttribute {
3176                    format: GpuVertexFormat::Float32x4,
3177                    offset: 80,
3178                    shader_location: 6,
3179                },
3180            ],
3181        };
3182
3183        Ok(Self {
3184            shader_module,
3185            vertex_layout,
3186            instance_layout: Some(instance_layout),
3187            primitive_topology: GpuPrimitiveTopology::TriangleList,
3188            depth_stencil: Some(GpuDepthStencilState {
3189                format: crate::swapchain::SwapchainFormat::Depth32Float,
3190                depth_write_enabled: true,
3191                depth_compare: GpuCompareFunction::LessEqual,
3192            }),
3193        })
3194    }
3195
3196    /// Constructs a hardware stencil clip pipeline binding `WGSL_STENCIL_CLIP_SHADER`.
3197    pub fn new_stencil_clip_pipeline(
3198        viewport_width: f32,
3199        viewport_height: f32,
3200    ) -> Result<Self, String> {
3201        let _ = (viewport_width, viewport_height);
3202        let compiler = GpuShaderCompiler::new();
3203        let shader_module = compiler.compile(WGSL_STENCIL_CLIP_SHADER)?;
3204
3205        let vertex_layout = GpuVertexBufferLayout {
3206            array_stride: GpuClipVertex::BYTE_SIZE as u64,
3207            step_mode: GpuVertexStepMode::Vertex,
3208            attributes: vec![GpuVertexAttribute {
3209                format: GpuVertexFormat::Float32x2,
3210                offset: 0,
3211                shader_location: 0,
3212            }],
3213        };
3214
3215        Ok(Self {
3216            shader_module,
3217            vertex_layout,
3218            instance_layout: None,
3219            primitive_topology: GpuPrimitiveTopology::TriangleList,
3220            depth_stencil: Some(GpuDepthStencilState {
3221                format: crate::swapchain::SwapchainFormat::Depth32Float,
3222                depth_write_enabled: false,
3223                depth_compare: GpuCompareFunction::Always,
3224            }),
3225        })
3226    }
3227
3228    /// Records an instanced draw command onto a command encoder.
3229    pub fn draw_instanced(
3230        &self,
3231        encoder: &mut crate::gpu_context::GpuCommandEncoder,
3232        vertex_count: usize,
3233        instance_count: usize,
3234    ) {
3235        encoder.draw_instanced(vertex_count, instance_count);
3236    }
3237}
3238
3239/// Statistics and primitive breakdown for batched GPU dispatches.
3240#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3241pub struct GpuBatchSummary {
3242    pub total_commands: usize,
3243    pub quad_instances: usize,
3244    pub slug_glyphs: usize,
3245    pub path_segments: usize,
3246    pub total_draw_calls: usize,
3247}
3248
3249/// Instanced UI Draw Call Batch Collector for complex layouts (Goal 07).
3250///
3251/// Batches heterogeneous display lists with 10,000+ commands into <= 5 GPU draw calls.
3252#[derive(Debug, Clone)]
3253pub struct GpuBatchCollector {
3254    pub viewport_width: f32,
3255    pub viewport_height: f32,
3256    pub quad_batch: GpuBatch,
3257    pub text_pipeline: GpuSlugTextPipeline,
3258    pub path_batch: GpuPathBatch,
3259    pub summary: GpuBatchSummary,
3260}
3261
3262impl GpuBatchCollector {
3263    pub fn new(viewport_width: f32, viewport_height: f32) -> Self {
3264        Self {
3265            viewport_width,
3266            viewport_height,
3267            quad_batch: GpuBatch::new(),
3268            text_pipeline: GpuSlugTextPipeline::new(),
3269            path_batch: GpuPathBatch::new(),
3270            summary: GpuBatchSummary::default(),
3271        }
3272    }
3273
3274    fn count_span_draw_calls(
3275        total_items: usize,
3276        spans: &[GpuClipSpan],
3277        masks: &[GpuClipMask],
3278    ) -> usize {
3279        if total_items == 0 {
3280            return 0;
3281        }
3282        if spans.is_empty() || masks.is_empty() {
3283            return 1;
3284        }
3285        let mut calls = 0usize;
3286        for span in spans {
3287            if span.end <= span.start {
3288                continue;
3289            }
3290            if let Some(mask_id) = span.clip_mask {
3291                if let Some(mask) = masks.get(mask_id) {
3292                    calls += mask
3293                        .stencil_layers
3294                        .iter()
3295                        .filter(|layer| !layer.is_empty())
3296                        .count();
3297                }
3298            }
3299            calls += 1;
3300        }
3301        calls.max(1)
3302    }
3303
3304    /// Collects and batches all compatible primitives from a DisplayList.
3305    pub fn collect(&mut self, list: &DisplayList, damage: Option<Rect>) -> GpuBatchSummary {
3306        self.quad_batch = GpuBatch::from_display_list_damaged(
3307            list,
3308            damage,
3309            self.viewport_width,
3310            self.viewport_height,
3311        );
3312
3313        let glyph_count = self.text_pipeline.compile_display_list(
3314            list,
3315            self.viewport_width,
3316            self.viewport_height,
3317            damage,
3318        );
3319
3320        self.path_batch = GpuPathBatch::from_display_list_damaged(
3321            list,
3322            damage,
3323            self.viewport_width,
3324            self.viewport_height,
3325        );
3326
3327        let mut draw_calls = 0;
3328        draw_calls += Self::count_span_draw_calls(
3329            self.quad_batch.len(),
3330            &self.quad_batch.clip_spans,
3331            &self.quad_batch.clip_masks,
3332        );
3333        if glyph_count > 0 {
3334            draw_calls += 1;
3335        }
3336        draw_calls += Self::count_span_draw_calls(
3337            self.path_batch.len(),
3338            &self.path_batch.clip_spans,
3339            &self.path_batch.clip_masks,
3340        );
3341
3342        self.summary = GpuBatchSummary {
3343            total_commands: list.len(),
3344            quad_instances: self.quad_batch.len(),
3345            slug_glyphs: glyph_count,
3346            path_segments: self.path_batch.len(),
3347            total_draw_calls: draw_calls,
3348        };
3349
3350        self.summary
3351    }
3352
3353    fn dispatch_masked_spans(
3354        encoder: &mut crate::gpu_context::GpuCommandEncoder,
3355        total_items: usize,
3356        spans: &[GpuClipSpan],
3357        masks: &[GpuClipMask],
3358    ) {
3359        if total_items == 0 {
3360            return;
3361        }
3362        if spans.is_empty() || masks.is_empty() {
3363            encoder.draw_instanced(6, total_items);
3364            return;
3365        }
3366        for span in spans {
3367            let count = span.end.saturating_sub(span.start);
3368            if count == 0 {
3369                continue;
3370            }
3371            if let Some(mask_id) = span.clip_mask {
3372                if let Some(mask) = masks.get(mask_id) {
3373                    for layer in &mask.stencil_layers {
3374                        if !layer.is_empty() {
3375                            encoder.draw_instanced(layer.len(), 1);
3376                        }
3377                    }
3378                }
3379            }
3380            encoder.draw_instanced(6, count);
3381        }
3382    }
3383
3384    /// Dispatches all collected batches onto the GPU device in unified passes.
3385    pub fn dispatch(
3386        &self,
3387        device: &mut crate::gpu_context::GpuDevice,
3388        damage: Option<Rect>,
3389    ) -> Result<GpuBatchSummary, crate::swapchain::PresentError> {
3390        let mut encoder = device.create_command_encoder();
3391        let pass = crate::gpu_context::GpuRenderPassDescriptor {
3392            color_texture_id: device.swapchain_texture.id,
3393            depth_texture_id: Some(device.depth_texture.id),
3394            clear_color: Some([0.0, 0.0, 0.0, 1.0]),
3395            clear_depth: Some(1.0),
3396            scissor_rect: damage,
3397        };
3398        encoder.begin_render_pass(pass);
3399
3400        Self::dispatch_masked_spans(
3401            &mut encoder,
3402            self.quad_batch.len(),
3403            &self.quad_batch.clip_spans,
3404            &self.quad_batch.clip_masks,
3405        );
3406        if self.summary.slug_glyphs > 0 {
3407            encoder.draw_instanced(6, self.summary.slug_glyphs);
3408        }
3409        Self::dispatch_masked_spans(
3410            &mut encoder,
3411            self.path_batch.len(),
3412            &self.path_batch.clip_spans,
3413            &self.path_batch.clip_masks,
3414        );
3415
3416        encoder.end_render_pass();
3417        device.submit(encoder);
3418
3419        Ok(self.summary)
3420    }
3421
3422    /// Updates viewport dimensions for subsequent batch compilations.
3423    pub fn resize(&mut self, viewport_width: f32, viewport_height: f32) {
3424        self.viewport_width = viewport_width;
3425        self.viewport_height = viewport_height;
3426    }
3427
3428    /// Compiles a `DisplayList` into coalesced painter's-order hardware GPU batches
3429    /// (`GpuBatch`, `GpuPathBatch`, `GpuSlugTextPipeline`, `GpuClipMask`s, and `DrawViewport3D` split points),
3430    /// eliminating duplicate `FillRect`/`StrokeRect` emission and triangulating/stencil-filling closed vector shapes.
3431    pub fn collect_hardware_frame(
3432        &mut self,
3433        list: &DisplayList,
3434        damage: Option<Rect>,
3435    ) -> Hardware2DFrame {
3436        self.quad_batch.clear();
3437        self.path_batch.clear();
3438        self.text_pipeline.clear();
3439
3440        let glyph_cache = std::mem::take(&mut self.text_pipeline.glyph_cache);
3441        let text = GpuSlugTextPipeline {
3442            glyph_cache,
3443            buffer: strata_gpu_path::SlugGlyphBuffer::new(),
3444            total_glyphs: 0,
3445            total_curves: 0,
3446        };
3447        let mut frame = Hardware2DFrame {
3448            quads: GpuBatch::with_capacity(list.len()),
3449            paths: GpuPathBatch::new(),
3450            text,
3451            items: Vec::with_capacity(list.len().min(64)),
3452            clip_masks: Vec::new(),
3453            summary: GpuBatchSummary::default(),
3454        };
3455
3456        let viewport_rect = Rect::new(0.0, 0.0, self.viewport_width, self.viewport_height);
3457        let default_clip = damage.unwrap_or(viewport_rect);
3458        let mut builder = HardwareFrameBuilder {
3459            frame: &mut frame,
3460            viewport_rect,
3461            default_clip,
3462            clip_stack: Vec::new(),
3463            poly_clip_stack: Vec::new(),
3464            poly_mask_id: None,
3465            transform_stack: Vec::new(),
3466            opacity_stack: Vec::new(),
3467            cur_alpha: 1.0,
3468        };
3469        builder.compile_list(list);
3470
3471        frame.text.total_curves = frame.text.buffer.curves.len();
3472        let draw_calls = frame.count_draw_calls();
3473        frame.summary = GpuBatchSummary {
3474            total_commands: list.len(),
3475            quad_instances: frame.quads.len(),
3476            slug_glyphs: frame.text.total_glyphs,
3477            path_segments: frame.paths.len(),
3478            total_draw_calls: draw_calls,
3479        };
3480
3481        // Keep legacy collector state in sync without cloning large vector buffers.
3482        self.text_pipeline.glyph_cache = frame.text.glyph_cache.clone();
3483        self.summary = frame.summary;
3484        frame
3485    }
3486}
3487
3488/// Alias matching hardware swapchain batch collection across `strata_render` and `strata_platform`.
3489pub type UnifiedGpuCollector = GpuBatchCollector;
3490
3491/// GPU primitive kind for a coalesced hardware draw call inside [`Hardware2DFrame`].
3492#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3493pub enum HardwareDrawOpKind {
3494    Quads,
3495    Paths,
3496    Text,
3497}
3498
3499/// Contiguous range `[start..end)` of batched GPU instances/segments sharing clip mask and scissor.
3500#[derive(Debug, Clone, Copy, PartialEq)]
3501pub struct HardwareDrawOp {
3502    pub kind: HardwareDrawOpKind,
3503    pub start: usize,
3504    pub end: usize,
3505    pub clip_mask: Option<usize>,
3506    pub scissor_rect: Option<Rect>,
3507}
3508
3509/// Ordered hardware render step preserving exact Z-order across 2D GPU batches and 3D viewports.
3510#[derive(Debug, Clone)]
3511pub enum HardwareRenderItem {
3512    Batch(HardwareDrawOp),
3513    Viewport3D {
3514        bounds: Rect,
3515        scene: std::sync::Arc<crate::scene3d::Scene3D>,
3516    },
3517}
3518
3519/// Complete compiled hardware 2D/3D frame ready for live `wgpu` swapchain or offscreen execution.
3520#[derive(Debug, Clone, Default)]
3521pub struct Hardware2DFrame {
3522    pub quads: GpuBatch,
3523    pub paths: GpuPathBatch,
3524    pub text: GpuSlugTextPipeline,
3525    pub items: Vec<HardwareRenderItem>,
3526    pub clip_masks: Vec<GpuClipMask>,
3527    pub summary: GpuBatchSummary,
3528}
3529
3530impl Hardware2DFrame {
3531    /// Counts hardware draw calls including stencil clip mask passes and batched content spans.
3532    pub fn count_draw_calls(&self) -> usize {
3533        let mut calls = 0usize;
3534        let mut active_mask: Option<usize> = None;
3535        for item in &self.items {
3536            match item {
3537                HardwareRenderItem::Batch(op) => {
3538                    if let Some(mask_id) = op.clip_mask {
3539                        if active_mask != Some(mask_id) {
3540                            if let Some(mask) = self.clip_masks.get(mask_id) {
3541                                calls += mask
3542                                    .stencil_layers
3543                                    .iter()
3544                                    .filter(|l| !l.is_empty())
3545                                    .count();
3546                            }
3547                            active_mask = Some(mask_id);
3548                        }
3549                    }
3550                    calls += 1;
3551                }
3552                HardwareRenderItem::Viewport3D { .. } => {
3553                    calls += 1;
3554                    active_mask = None;
3555                }
3556            }
3557        }
3558        calls
3559    }
3560}
3561
3562struct HardwareFrameBuilder<'a> {
3563    frame: &'a mut Hardware2DFrame,
3564    viewport_rect: Rect,
3565    default_clip: Rect,
3566    clip_stack: Vec<(Rect, bool)>,
3567    poly_clip_stack: Vec<Vec<Vec<(f32, f32)>>>,
3568    poly_mask_id: Option<usize>,
3569    transform_stack: Vec<strata_primitives::geom::Matrix4x4>,
3570    opacity_stack: Vec<f32>,
3571    cur_alpha: f32,
3572}
3573
3574impl<'a> HardwareFrameBuilder<'a> {
3575    #[inline]
3576    fn current_clip(&self) -> Option<Rect> {
3577        match self.clip_stack.last() {
3578            Some((r, _)) => r.intersect(self.default_clip),
3579            None => Some(self.default_clip),
3580        }
3581    }
3582
3583    #[inline]
3584    fn transform_rect(&self, r: Rect) -> Rect {
3585        if let Some(mat) = self.transform_stack.last() {
3586            if !mat.is_identity() {
3587                let (x, y, w, h) = mat.transform_bounds(r.x, r.y, r.width, r.height);
3588                return Rect::new(x, y, w, h);
3589            }
3590        }
3591        r
3592    }
3593
3594    fn transform_subpaths(&self, subs: Vec<Vec<(f32, f32)>>) -> Vec<Vec<(f32, f32)>> {
3595        if let Some(mat) = self.transform_stack.last() {
3596            if !mat.is_identity() {
3597                return subs
3598                    .into_iter()
3599                    .map(|sub| {
3600                        sub.into_iter()
3601                            .map(|(x, y)| mat.transform_point(x, y))
3602                            .collect()
3603                    })
3604                    .collect();
3605            }
3606        }
3607        subs
3608    }
3609
3610    fn record_op(
3611        &mut self,
3612        kind: HardwareDrawOpKind,
3613        start: usize,
3614        end: usize,
3615        clip_mask: Option<usize>,
3616        scissor_rect: Option<Rect>,
3617    ) {
3618        if end <= start {
3619            return;
3620        }
3621        if let Some(HardwareRenderItem::Batch(prev)) = self.frame.items.last_mut() {
3622            if prev.kind == kind
3623                && prev.clip_mask == clip_mask
3624                && prev.scissor_rect == scissor_rect
3625                && prev.end == start
3626            {
3627                prev.end = end;
3628                return;
3629            }
3630        }
3631        self.frame.items.push(HardwareRenderItem::Batch(HardwareDrawOp {
3632            kind,
3633            start,
3634            end,
3635            clip_mask,
3636            scissor_rect,
3637        }));
3638    }
3639
3640    #[inline]
3641    fn scissor_for(&self, clip: Rect) -> Option<Rect> {
3642        if clip == self.viewport_rect {
3643            None
3644        } else {
3645            Some(clip)
3646        }
3647    }
3648
3649    fn push_clipped_quad(
3650        &mut self,
3651        instance: GpuQuadInstance,
3652        rect: Rect,
3653        clip_polys: &[Vec<Vec<(f32, f32)>>],
3654        clip_mask_id: Option<usize>,
3655    ) {
3656        let mask = if clip_polys.is_empty() {
3657            None
3658        } else {
3659            match rect_relation_to_clip_polys(rect, clip_polys) {
3660                ClipContainment::Outside => return,
3661                ClipContainment::Inside => None,
3662                ClipContainment::Partial => clip_mask_id,
3663            }
3664        };
3665        let start = self.frame.quads.len();
3666        self.frame.quads.push_with_clip(instance, mask);
3667        let end = self.frame.quads.len();
3668        self.record_op(HardwareDrawOpKind::Quads, start, end, mask, None);
3669    }
3670
3671    fn emit_stencil_fill(
3672        &mut self,
3673        fill_polys: Vec<Vec<(f32, f32)>>,
3674        fill_color: Color,
3675        active_clip: Rect,
3676        parent_clip_polys: &[Vec<Vec<(f32, f32)>>],
3677    ) {
3678        let Some(poly_bbox) = poly_layers_bbox(&fill_polys) else {
3679            return;
3680        };
3681        let Some(clipped_bbox) = poly_bbox.intersect(active_clip) else {
3682            return;
3683        };
3684        if !parent_clip_polys.is_empty()
3685            && rect_relation_to_clip_polys(clipped_bbox, parent_clip_polys)
3686                == ClipContainment::Outside
3687        {
3688            return;
3689        }
3690        let mut layers = Vec::with_capacity(parent_clip_polys.len() + 1);
3691        layers.extend_from_slice(parent_clip_polys);
3692        layers.push(fill_polys);
3693        let Some(mask_id) =
3694            resolve_or_push_clip_mask(&mut self.frame.clip_masks, Some(clipped_bbox), &layers)
3695        else {
3696            return;
3697        };
3698        let col = apply_color_opacity(fill_color, self.cur_alpha);
3699        let start = self.frame.quads.len();
3700        self.frame
3701            .quads
3702            .push_with_clip(GpuQuadInstance::from_rect(clipped_bbox, col, active_clip), Some(mask_id));
3703        let end = self.frame.quads.len();
3704        self.record_op(HardwareDrawOpKind::Quads, start, end, Some(mask_id), None);
3705    }
3706
3707    #[allow(clippy::too_many_arguments)]
3708    fn emit_paths_with_op(
3709        &mut self,
3710        quads: &[strata_gpu_path::QuadraticBezier],
3711        closed: bool,
3712        sw: f32,
3713        color: Color,
3714        cap: strata_gpu_path::LineCap,
3715        join: strata_gpu_path::LineJoin,
3716        miter_limit: f32,
3717        dashes: &[f32],
3718        dash_offset: f32,
3719        extra_flags: u32,
3720        active_clip: Rect,
3721        clip_polys: &[Vec<Vec<(f32, f32)>>],
3722        clip_mask_id: Option<usize>,
3723    ) {
3724        let start = self.frame.paths.len();
3725        let before_spans = self.frame.paths.clip_spans.len();
3726        let col = apply_color_opacity(color, self.cur_alpha);
3727        self.frame.paths.emit_subpath_strokes(
3728            quads,
3729            closed,
3730            sw,
3731            col,
3732            cap,
3733            join,
3734            miter_limit,
3735            dashes,
3736            dash_offset,
3737            extra_flags,
3738            Some(active_clip),
3739            clip_polys,
3740            clip_mask_id,
3741        );
3742        let end = self.frame.paths.len();
3743        if end <= start {
3744            return;
3745        }
3746        let scissor = self.scissor_for(active_clip);
3747        let spans = &self.frame.paths.clip_spans;
3748        if !spans.is_empty() {
3749            let scan_from = before_spans.saturating_sub(1);
3750            let mut local_ops: Vec<(usize, usize, Option<usize>)> = Vec::new();
3751            for span in &spans[scan_from..] {
3752                if span.end <= start || span.start >= end {
3753                    continue;
3754                }
3755                local_ops.push((span.start.max(start), span.end.min(end), span.clip_mask));
3756            }
3757            for (s0, s1, mask) in local_ops {
3758                self.record_op(HardwareDrawOpKind::Paths, s0, s1, mask, scissor);
3759            }
3760        } else {
3761            self.record_op(HardwareDrawOpKind::Paths, start, end, None, scissor);
3762        }
3763    }
3764
3765    fn emit_text_with_clip(
3766        &mut self,
3767        start: usize,
3768        end: usize,
3769        run_bounds: Rect,
3770        active_clip: Rect,
3771        clip_polys: &[Vec<Vec<(f32, f32)>>],
3772        clip_mask_id: Option<usize>,
3773    ) {
3774        if end <= start {
3775            return;
3776        }
3777        let mask = if clip_polys.is_empty() {
3778            None
3779        } else {
3780            match rect_relation_to_clip_polys(run_bounds, clip_polys) {
3781                ClipContainment::Outside => {
3782                    self.frame.text.buffer.instances.truncate(start);
3783                    self.frame.text.total_glyphs = self.frame.text.buffer.instances.len();
3784                    return;
3785                }
3786                ClipContainment::Inside => None,
3787                ClipContainment::Partial => clip_mask_id,
3788            }
3789        };
3790        let scissor = self.scissor_for(active_clip);
3791        self.record_op(HardwareDrawOpKind::Text, start, end, mask, scissor);
3792    }
3793
3794    fn compile_list(&mut self, list: &DisplayList) {
3795        for cmd in list.commands() {
3796            match cmd {
3797                DrawCommand::PushClip { bounds, radius } => {
3798                    let tb = self.transform_rect(*bounds);
3799                    let combined = match self.clip_stack.last() {
3800                        Some((prev, _)) => prev.intersect(tb).unwrap_or(Rect::zero()),
3801                        None => tb,
3802                    };
3803                    let has_radius = radius.top_left > 0.5
3804                        || radius.top_right > 0.5
3805                        || radius.bottom_right > 0.5
3806                        || radius.bottom_left > 0.5;
3807                    if has_radius && tb.width > 0.0 && tb.height > 0.0 {
3808                        self.poly_clip_stack.push(vec![rounded_rect_subpath(tb, *radius)]);
3809                        self.poly_mask_id = resolve_or_push_clip_mask(
3810                            &mut self.frame.clip_masks,
3811                            combined.intersect(self.default_clip),
3812                            &self.poly_clip_stack,
3813                        );
3814                    }
3815                    self.clip_stack.push((combined, has_radius));
3816                    continue;
3817                }
3818                DrawCommand::PopClip => {
3819                    if let Some((_, had_poly)) = self.clip_stack.pop() {
3820                        if had_poly {
3821                            self.poly_clip_stack.pop();
3822                            let active = self.current_clip();
3823                            self.poly_mask_id = resolve_or_push_clip_mask(
3824                                &mut self.frame.clip_masks,
3825                                active,
3826                                &self.poly_clip_stack,
3827                            );
3828                        }
3829                    }
3830                    continue;
3831                }
3832                DrawCommand::PushTransform { matrix } => {
3833                    let combined = match self.transform_stack.last() {
3834                        Some(prev) => prev.multiply(matrix),
3835                        None => *matrix,
3836                    };
3837                    self.transform_stack.push(combined);
3838                    continue;
3839                }
3840                DrawCommand::PopTransform => {
3841                    self.transform_stack.pop();
3842                    continue;
3843                }
3844                DrawCommand::PushOpacity { alpha } => {
3845                    self.opacity_stack.push(self.cur_alpha);
3846                    self.cur_alpha = (self.cur_alpha * alpha).clamp(0.0, 1.0);
3847                    continue;
3848                }
3849                DrawCommand::PopOpacity => {
3850                    if let Some(prev) = self.opacity_stack.pop() {
3851                        self.cur_alpha = prev;
3852                    }
3853                    continue;
3854                }
3855                DrawCommand::DrawViewport3D { bounds, scene } => {
3856                    if bounds.width > 0.0 && bounds.height > 0.0 {
3857                        self.frame.items.push(HardwareRenderItem::Viewport3D {
3858                            bounds: self.transform_rect(*bounds),
3859                            scene: std::sync::Arc::clone(scene),
3860                        });
3861                    }
3862                    continue;
3863                }
3864                _ => {}
3865            }
3866
3867            let Some(current_clip) = self.current_clip() else {
3868                continue;
3869            };
3870            if let Some(b) = cmd.bounds() {
3871                if self.transform_rect(b).intersect(current_clip).is_none() {
3872                    continue;
3873                }
3874            }
3875
3876            let root_polys = self.poly_clip_stack.clone();
3877            let root_mask = self.poly_mask_id;
3878            match cmd {
3879                DrawCommand::DrawRect { bounds, color } => {
3880                    let tr = self.transform_rect(*bounds);
3881                    let col = apply_color_opacity(*color, self.cur_alpha);
3882                    self.push_clipped_quad(
3883                        GpuQuadInstance::from_rect(tr, col, current_clip),
3884                        tr,
3885                        &root_polys,
3886                        root_mask,
3887                    );
3888                }
3889                DrawCommand::DrawRoundedRect {
3890                    bounds,
3891                    color,
3892                    border_radius,
3893                    border_width,
3894                    border_color,
3895                } => {
3896                    let tr = self.transform_rect(*bounds);
3897                    let col = apply_color_opacity(*color, self.cur_alpha);
3898                    let bcol = border_color.map(|c| apply_color_opacity(c, self.cur_alpha));
3899                    self.push_clipped_quad(
3900                        GpuQuadInstance::from_rounded_rect(
3901                            tr,
3902                            col,
3903                            *border_radius,
3904                            *border_width,
3905                            bcol,
3906                            current_clip,
3907                        ),
3908                        tr,
3909                        &root_polys,
3910                        root_mask,
3911                    );
3912                }
3913                DrawCommand::DrawBorder {
3914                    bounds,
3915                    widths,
3916                    color,
3917                    border_radius,
3918                    ..
3919                } => {
3920                    let tr = self.transform_rect(*bounds);
3921                    let bcol = apply_color_opacity(*color, self.cur_alpha);
3922                    self.push_clipped_quad(
3923                        GpuQuadInstance::from_rounded_rect(
3924                            tr,
3925                            Color::TRANSPARENT,
3926                            *border_radius,
3927                            *widths,
3928                            Some(bcol),
3929                            current_clip,
3930                        ),
3931                        tr,
3932                        &root_polys,
3933                        root_mask,
3934                    );
3935                }
3936                DrawCommand::DrawText {
3937                    origin,
3938                    bounds_width,
3939                    bounds_height,
3940                    text_align,
3941                    text,
3942                    font_size,
3943                    line_height,
3944                    color,
3945                    ..
3946                } => {
3947                    let col = apply_color_opacity(*color, self.cur_alpha);
3948                    let start = self.frame.text.buffer.instances.len();
3949                    let (_, run_rect) = self.frame.text.push_text_run_with_bounds(
3950                        text,
3951                        origin.0,
3952                        origin.1,
3953                        *bounds_width,
3954                        *bounds_height,
3955                        *font_size,
3956                        *line_height,
3957                        *text_align,
3958                        1.0,
3959                        col,
3960                        current_clip,
3961                    );
3962                    let end = self.frame.text.buffer.instances.len();
3963                    self.emit_text_with_clip(
3964                        start,
3965                        end,
3966                        run_rect,
3967                        current_clip,
3968                        &root_polys,
3969                        root_mask,
3970                    );
3971                }
3972                DrawCommand::DrawTextFragments { fragments } => {
3973                    for frag in fragments {
3974                        let col = apply_color_opacity(frag.style.color, self.cur_alpha);
3975                        let start = self.frame.text.buffer.instances.len();
3976                        self.frame.text.push_text_run(
3977                            &frag.text,
3978                            frag.bounds.x,
3979                            frag.bounds.y,
3980                            frag.style.font_size,
3981                            1.0,
3982                            col,
3983                            current_clip,
3984                        );
3985                        let end = self.frame.text.buffer.instances.len();
3986                        self.emit_text_with_clip(
3987                            start,
3988                            end,
3989                            frag.bounds,
3990                            current_clip,
3991                            &root_polys,
3992                            root_mask,
3993                        );
3994                    }
3995                }
3996                DrawCommand::DrawGpuPath {
3997                    path,
3998                    stroke,
3999                    fill_color,
4000                    stroke_color,
4001                    ..
4002                } => {
4003                    let subpaths = subpaths_from_path_verbs(&path.verbs, 0.0, 0.0, 1.0, 1.0, 0.25);
4004                    if let Some(fc) = fill_color {
4005                        let polys = flatten_quad_subpaths(&subpaths, 6);
4006                        self.emit_stencil_fill(polys, *fc, current_clip, &root_polys);
4007                    }
4008                    if let Some(sc) = stroke_color {
4009                        let sw = stroke.map(|s| s.width).unwrap_or(1.0);
4010                        let cap = stroke.map(|s| s.cap).unwrap_or_default();
4011                        let join = stroke.map(|s| s.join).unwrap_or_default();
4012                        let miter = stroke.map(|s| s.miter_limit).unwrap_or(4.0);
4013                        let even_odd =
4014                            if path.fill_rule == Some(strata_gpu_path::FillRule::EvenOdd) {
4015                                strata_gpu_path::FLAG_EVEN_ODD
4016                            } else {
4017                                0
4018                            };
4019                        for (sub, closed) in &subpaths {
4020                            self.emit_paths_with_op(
4021                                sub,
4022                                *closed,
4023                                sw,
4024                                *sc,
4025                                cap,
4026                                join,
4027                                miter,
4028                                &[],
4029                                0.0,
4030                                even_odd,
4031                                current_clip,
4032                                &root_polys,
4033                                root_mask,
4034                            );
4035                        }
4036                    }
4037                }
4038                DrawCommand::DrawSvgPath {
4039                    bounds,
4040                    path_data,
4041                    stroke_color,
4042                    fill_color,
4043                    stroke_width,
4044                    stroke_linecap,
4045                    stroke_linejoin,
4046                    stroke_dasharray,
4047                    fill_rule,
4048                    view_box,
4049                } => {
4050                    let sx = if view_box.0 > 0.0 {
4051                        bounds.width / view_box.0
4052                    } else {
4053                        1.0
4054                    };
4055                    let sy = if view_box.1 > 0.0 {
4056                        bounds.height / view_box.1
4057                    } else {
4058                        1.0
4059                    };
4060                    let avg_scale = ((sx + sy) * 0.5).max(0.001);
4061                    let parsed = strata_gpu_path::PathBuilder::from_svg(path_data);
4062                    let subpaths = subpaths_from_path_verbs(
4063                        &parsed.verbs,
4064                        bounds.x,
4065                        bounds.y,
4066                        sx,
4067                        sy,
4068                        0.25,
4069                    );
4070                    if let Some(fc) = fill_color {
4071                        let polys = flatten_quad_subpaths(&subpaths, 6);
4072                        self.emit_stencil_fill(polys, *fc, current_clip, &root_polys);
4073                    }
4074                    if let Some(sc) = stroke_color {
4075                        let sw = *stroke_width * avg_scale;
4076                        let cap = layout_cap_to_gpu(*stroke_linecap);
4077                        let join = layout_join_to_gpu(*stroke_linejoin);
4078                        let even_odd = if *fill_rule == strata_layout::FillRule::EvenOdd {
4079                            strata_gpu_path::FLAG_EVEN_ODD
4080                        } else {
4081                            0
4082                        };
4083                        let scaled_dashes: Vec<f32> =
4084                            stroke_dasharray.iter().map(|&d| d * avg_scale).collect();
4085                        for (sub, closed) in &subpaths {
4086                            self.emit_paths_with_op(
4087                                sub,
4088                                *closed,
4089                                sw,
4090                                *sc,
4091                                cap,
4092                                join,
4093                                4.0,
4094                                &scaled_dashes,
4095                                0.0,
4096                                even_odd,
4097                                current_clip,
4098                                &root_polys,
4099                                root_mask,
4100                            );
4101                        }
4102                    }
4103                }
4104                DrawCommand::DrawCanvas2D { bounds, commands } => {
4105                    if let Some(base_clip) = self.transform_rect(*bounds).intersect(current_clip) {
4106                        self.compile_canvas_commands(bounds, commands, base_clip);
4107                    }
4108                }
4109                _ => {}
4110            }
4111        }
4112    }
4113
4114    fn compile_canvas_commands(
4115        &mut self,
4116        bounds: &Rect,
4117        commands: &[crate::canvas2d::CanvasCommand],
4118        base_clip: Rect,
4119    ) {
4120        let ox = bounds.x;
4121        let oy = bounds.y;
4122        let mut active_clip = Some(base_clip);
4123        let mut line_dash: Vec<f32> = Vec::new();
4124        let mut dash_offset: f32 = 0.0;
4125        let mut line_cap = strata_gpu_path::LineCap::Butt;
4126        let mut line_join = strata_gpu_path::LineJoin::Miter;
4127        let mut clip_polys = self.poly_clip_stack.clone();
4128        let mut clip_mask_id = resolve_or_push_clip_mask(
4129            &mut self.frame.clip_masks,
4130            active_clip,
4131            &clip_polys,
4132        );
4133        #[allow(clippy::type_complexity)]
4134        let mut state_stack: Vec<(
4135            Option<Rect>,
4136            Vec<f32>,
4137            f32,
4138            strata_gpu_path::LineCap,
4139            strata_gpu_path::LineJoin,
4140            Vec<Vec<Vec<(f32, f32)>>>,
4141            Option<usize>,
4142        )> = Vec::new();
4143
4144        for ccmd in commands {
4145            match ccmd {
4146                crate::canvas2d::CanvasCommand::Save => {
4147                    state_stack.push((
4148                        active_clip,
4149                        line_dash.clone(),
4150                        dash_offset,
4151                        line_cap,
4152                        line_join,
4153                        clip_polys.clone(),
4154                        clip_mask_id,
4155                    ));
4156                }
4157                crate::canvas2d::CanvasCommand::Restore => {
4158                    if let Some((
4159                        prev_clip,
4160                        prev_dash,
4161                        prev_offset,
4162                        prev_cap,
4163                        prev_join,
4164                        prev_polys,
4165                        prev_mask,
4166                    )) = state_stack.pop()
4167                    {
4168                        active_clip = prev_clip;
4169                        line_dash = prev_dash;
4170                        dash_offset = prev_offset;
4171                        line_cap = prev_cap;
4172                        line_join = prev_join;
4173                        clip_polys = prev_polys;
4174                        clip_mask_id = prev_mask;
4175                    }
4176                }
4177                crate::canvas2d::CanvasCommand::SetLineDash { segments, offset } => {
4178                    line_dash = segments
4179                        .iter()
4180                        .copied()
4181                        .filter(|d| d.is_finite() && *d >= 0.0)
4182                        .collect();
4183                    if line_dash.len() % 2 == 1 {
4184                        let dup = line_dash.clone();
4185                        line_dash.extend(dup);
4186                    }
4187                    dash_offset = if offset.is_finite() { *offset } else { 0.0 };
4188                }
4189                crate::canvas2d::CanvasCommand::SetLineCap(cap) => {
4190                    line_cap = layout_cap_to_gpu(*cap);
4191                }
4192                crate::canvas2d::CanvasCommand::SetLineJoin(join) => {
4193                    line_join = layout_join_to_gpu(*join);
4194                }
4195                crate::canvas2d::CanvasCommand::ClipPath { verbs } => {
4196                    let subpaths = self.transform_subpaths(
4197                        crate::canvas2d::flatten_canvas_verbs(verbs, ox, oy),
4198                    );
4199                    if !subpaths.is_empty() {
4200                        if let Some(tb) = poly_layers_bbox(&subpaths) {
4201                            active_clip = active_clip.and_then(|c| c.intersect(tb));
4202                        }
4203                        if !subpaths_are_axis_aligned_rect(&subpaths) {
4204                            clip_polys.push(subpaths);
4205                            clip_mask_id = resolve_or_push_clip_mask(
4206                                &mut self.frame.clip_masks,
4207                                active_clip,
4208                                &clip_polys,
4209                            );
4210                        }
4211                    }
4212                }
4213                crate::canvas2d::CanvasCommand::FillRect { bounds: rb, color } => {
4214                    let Some(canvas_clip) = active_clip else {
4215                        continue;
4216                    };
4217                    let tr = self.transform_rect(Rect::new(
4218                        ox + rb.x,
4219                        oy + rb.y,
4220                        rb.width,
4221                        rb.height,
4222                    ));
4223                    if tr.intersect(canvas_clip).is_none() {
4224                        continue;
4225                    }
4226                    let col = apply_color_opacity(*color, self.cur_alpha);
4227                    self.push_clipped_quad(
4228                        GpuQuadInstance::from_rect(tr, col, canvas_clip),
4229                        tr,
4230                        &clip_polys,
4231                        clip_mask_id,
4232                    );
4233                }
4234                crate::canvas2d::CanvasCommand::StrokeRect {
4235                    bounds: rb,
4236                    color,
4237                    line_width,
4238                } => {
4239                    let Some(canvas_clip) = active_clip else {
4240                        continue;
4241                    };
4242                    let r = Rect::new(ox + rb.x, oy + rb.y, rb.width, rb.height);
4243                    let period: f32 = line_dash.iter().copied().sum();
4244                    if line_cap == strata_gpu_path::LineCap::Butt
4245                        && line_join == strata_gpu_path::LineJoin::Miter
4246                    {
4247                        if line_dash.is_empty() || period <= 1e-4 {
4248                            let tr = self.transform_rect(r);
4249                            if tr.intersect(canvas_clip).is_some() {
4250                                let col = apply_color_opacity(*color, self.cur_alpha);
4251                                self.push_clipped_quad(
4252                                    GpuQuadInstance::from_rounded_rect(
4253                                        tr,
4254                                        Color::TRANSPARENT,
4255                                        BorderRadius::default(),
4256                                        EdgeInsets::all(*line_width),
4257                                        Some(col),
4258                                        canvas_clip,
4259                                    ),
4260                                    tr,
4261                                    &clip_polys,
4262                                    clip_mask_id,
4263                                );
4264                            }
4265                        } else {
4266                            let col = apply_color_opacity(*color, self.cur_alpha);
4267                            for seg_rect in compute_dashed_stroke_rect_segments(
4268                                r,
4269                                *line_width,
4270                                &line_dash,
4271                                dash_offset,
4272                            ) {
4273                                let t_seg = self.transform_rect(seg_rect);
4274                                if t_seg.intersect(canvas_clip).is_some() {
4275                                    self.push_clipped_quad(
4276                                        GpuQuadInstance::from_rect(t_seg, col, canvas_clip),
4277                                        t_seg,
4278                                        &clip_polys,
4279                                        clip_mask_id,
4280                                    );
4281                                }
4282                            }
4283                        }
4284                    } else {
4285                        let p0 = strata_gpu_path::Point2D::new(r.x, r.y);
4286                        let p1 = strata_gpu_path::Point2D::new(r.x + r.width, r.y);
4287                        let p2 = strata_gpu_path::Point2D::new(r.x + r.width, r.y + r.height);
4288                        let p3 = strata_gpu_path::Point2D::new(r.x, r.y + r.height);
4289                        let rect_quads = [
4290                            strata_gpu_path::QuadraticBezier::new(p0, p0.lerp(p1, 0.5), p1),
4291                            strata_gpu_path::QuadraticBezier::new(p1, p1.lerp(p2, 0.5), p2),
4292                            strata_gpu_path::QuadraticBezier::new(p2, p2.lerp(p3, 0.5), p3),
4293                            strata_gpu_path::QuadraticBezier::new(p3, p3.lerp(p0, 0.5), p0),
4294                        ];
4295                        self.emit_paths_with_op(
4296                            &rect_quads,
4297                            true,
4298                            *line_width,
4299                            *color,
4300                            line_cap,
4301                            line_join,
4302                            10.0,
4303                            &line_dash,
4304                            dash_offset,
4305                            0,
4306                            canvas_clip,
4307                            &clip_polys,
4308                            clip_mask_id,
4309                        );
4310                    }
4311                }
4312                crate::canvas2d::CanvasCommand::DrawLine {
4313                    p0,
4314                    p1,
4315                    color,
4316                    line_width,
4317                } => {
4318                    let Some(canvas_clip) = active_clip else {
4319                        continue;
4320                    };
4321                    let a = strata_gpu_path::Point2D::new(ox + p0.0, oy + p0.1);
4322                    let b = strata_gpu_path::Point2D::new(ox + p1.0, oy + p1.1);
4323                    let q = strata_gpu_path::QuadraticBezier::new(a, a.lerp(b, 0.5), b);
4324                    self.emit_paths_with_op(
4325                        &[q],
4326                        false,
4327                        *line_width,
4328                        *color,
4329                        line_cap,
4330                        line_join,
4331                        10.0,
4332                        &line_dash,
4333                        dash_offset,
4334                        0,
4335                        canvas_clip,
4336                        &clip_polys,
4337                        clip_mask_id,
4338                    );
4339                }
4340                crate::canvas2d::CanvasCommand::DrawCircle {
4341                    center,
4342                    radius,
4343                    fill_color,
4344                    stroke_color,
4345                    line_width,
4346                } => {
4347                    let Some(canvas_clip) = active_clip else {
4348                        continue;
4349                    };
4350                    let circle_quads = circle_to_quads(ox + center.0, oy + center.1, *radius);
4351                    if let Some(fc) = fill_color {
4352                        let polys = flatten_quad_subpaths(&[(circle_quads.clone(), true)], 4);
4353                        self.emit_stencil_fill(polys, *fc, canvas_clip, &clip_polys);
4354                    }
4355                    if let Some(sc) = stroke_color {
4356                        self.emit_paths_with_op(
4357                            &circle_quads,
4358                            true,
4359                            *line_width,
4360                            *sc,
4361                            line_cap,
4362                            line_join,
4363                            10.0,
4364                            &line_dash,
4365                            dash_offset,
4366                            0,
4367                            canvas_clip,
4368                            &clip_polys,
4369                            clip_mask_id,
4370                        );
4371                    }
4372                }
4373                crate::canvas2d::CanvasCommand::DrawPath {
4374                    verbs,
4375                    fill_color,
4376                    stroke_color,
4377                    line_width,
4378                } => {
4379                    let Some(canvas_clip) = active_clip else {
4380                        continue;
4381                    };
4382                    let subpaths = canvas_path_verbs_to_quad_subpaths(verbs, ox, oy);
4383                    if let Some(fc) = fill_color {
4384                        let polys = flatten_quad_subpaths(&subpaths, 6);
4385                        self.emit_stencil_fill(polys, *fc, canvas_clip, &clip_polys);
4386                    }
4387                    if let Some(sc) = stroke_color {
4388                        for (sub, closed) in &subpaths {
4389                            self.emit_paths_with_op(
4390                                sub,
4391                                *closed,
4392                                *line_width,
4393                                *sc,
4394                                line_cap,
4395                                line_join,
4396                                10.0,
4397                                &line_dash,
4398                                dash_offset,
4399                                0,
4400                                canvas_clip,
4401                                &clip_polys,
4402                                clip_mask_id,
4403                            );
4404                        }
4405                    }
4406                }
4407                crate::canvas2d::CanvasCommand::FillText {
4408                    text,
4409                    x,
4410                    y,
4411                    color,
4412                    font_size,
4413                    text_align,
4414                    text_baseline,
4415                    max_width,
4416                    ..
4417                }
4418                | crate::canvas2d::CanvasCommand::StrokeText {
4419                    text,
4420                    x,
4421                    y,
4422                    color,
4423                    font_size,
4424                    text_align,
4425                    text_baseline,
4426                    max_width,
4427                    ..
4428                } => {
4429                    let Some(canvas_clip) = active_clip else {
4430                        continue;
4431                    };
4432                    let col = apply_color_opacity(*color, self.cur_alpha);
4433                    let start = self.frame.text.buffer.instances.len();
4434                    let (_, run_rect) = self.frame.text.push_canvas_text(
4435                        *bounds,
4436                        text,
4437                        *x,
4438                        *y,
4439                        col,
4440                        *font_size,
4441                        *text_align,
4442                        *text_baseline,
4443                        *max_width,
4444                        canvas_clip,
4445                    );
4446                    let end = self.frame.text.buffer.instances.len();
4447                    self.emit_text_with_clip(
4448                        start,
4449                        end,
4450                        run_rect,
4451                        canvas_clip,
4452                        &clip_polys,
4453                        clip_mask_id,
4454                    );
4455                }
4456                crate::canvas2d::CanvasCommand::ClearRect { .. } => {}
4457            }
4458        }
4459    }
4460}
4461
4462#[cfg(feature = "wgpu-backend")]
4463pub use crate::wgpu_2d::{GpuStencilClipPipeline, Wgpu2DRenderer};
4464
4465#[cfg(test)]
4466mod tests {
4467    use super::*;
4468
4469    #[test]
4470    fn test_gpu_quad_memory_layout() {
4471        assert_eq!(GpuQuadInstance::BYTE_SIZE, 96);
4472        assert_eq!(GpuUniforms::BYTE_SIZE, 16);
4473        assert_eq!(QUAD_VERTICES.len(), 6);
4474
4475        let quad = GpuQuadInstance::from_rect(
4476            Rect::new(10.0, 20.0, 100.0, 50.0),
4477            Color::rgb(255, 0, 0),
4478            Rect::new(0.0, 0.0, 1920.0, 1080.0),
4479        );
4480
4481        let bytes = quad.as_bytes();
4482        assert_eq!(bytes.len(), 96);
4483
4484        // Verify bounds at byte offset 0: 10.0, 20.0, 100.0, 50.0
4485        let b0 = f32::from_ne_bytes(bytes[0..4].try_into().unwrap());
4486        let b1 = f32::from_ne_bytes(bytes[4..8].try_into().unwrap());
4487        let b2 = f32::from_ne_bytes(bytes[8..12].try_into().unwrap());
4488        let b3 = f32::from_ne_bytes(bytes[12..16].try_into().unwrap());
4489        assert_eq!(b0, 10.0);
4490        assert_eq!(b1, 20.0);
4491        assert_eq!(b2, 100.0);
4492        assert_eq!(b3, 50.0);
4493    }
4494
4495    #[test]
4496    fn test_gpu_batch_compilation_and_scissoring() {
4497        let mut dl = DisplayList::new();
4498
4499        // 1. Root background (1920x1080)
4500        dl.push(DrawCommand::DrawRect {
4501            bounds: Rect::new(0.0, 0.0, 1920.0, 1080.0),
4502            color: Color::rgb(10, 10, 15),
4503        });
4504
4505        // 2. Button in top-left (20, 20, 120, 36)
4506        dl.push(DrawCommand::DrawRoundedRect {
4507            bounds: Rect::new(20.0, 20.0, 120.0, 36.0),
4508            color: Color::rgb(59, 130, 246),
4509            border_radius: BorderRadius::all(6.0),
4510            border_width: EdgeInsets::ZERO,
4511            border_color: None,
4512        });
4513
4514        // 3. Card in bottom-right (1500, 800, 300, 200)
4515        dl.push(DrawCommand::DrawRect {
4516            bounds: Rect::new(1500.0, 800.0, 300.0, 200.0),
4517            color: Color::rgb(30, 41, 59),
4518        });
4519
4520        // Full compilation
4521        let full_batch = GpuBatch::from_display_list(&dl, 1920.0, 1080.0);
4522        assert_eq!(full_batch.len(), 3);
4523        assert_eq!(full_batch.as_bytes().len(), 3 * 96);
4524
4525        // Damaged compilation targeting only the button in top-left
4526        let damage = Rect::new(10.0, 10.0, 140.0, 60.0);
4527        let damaged_batch = GpuBatch::from_display_list_damaged(&dl, Some(damage), 1920.0, 1080.0);
4528
4529        // Background (intersects damage) and Button (intersects damage) are included.
4530        // Card (at 1500, 800) does not intersect damage and is skipped!
4531        assert_eq!(damaged_batch.len(), 2);
4532    }
4533
4534    #[test]
4535    fn test_presentation_pipeline_compilation() {
4536        let mut pipeline = GpuPresentationPipeline::new(1920.0, 1080.0);
4537
4538        let mut dl = DisplayList::new();
4539        dl.push(DrawCommand::DrawRect {
4540            bounds: Rect::new(50.0, 50.0, 200.0, 100.0),
4541            color: Color::rgb(255, 255, 255),
4542        });
4543
4544        let count = pipeline.compile_frame(&dl, None);
4545        assert_eq!(count, 1);
4546        assert_eq!(pipeline.compiled_frames, 1);
4547        assert_eq!(pipeline.instance_bytes().len(), 96);
4548        assert_eq!(pipeline.uniform_bytes().len(), 16);
4549    }
4550
4551    #[test]
4552    fn test_gpu_path_batch_and_pipeline() {
4553        let mut path_pipeline = GpuPathPipeline::new(1920.0, 1080.0);
4554
4555        let mut dl = DisplayList::new();
4556        // Add DrawGpuPath
4557        let path = strata_gpu_path::PathBuilder::from_svg("M 0 0 L 100 100 Q 150 50 200 0 Z")
4558            .with_fill(strata_gpu_path::FillRule::NonZero);
4559
4560        dl.push(DrawCommand::DrawGpuPath {
4561            bounds: Rect::new(0.0, 0.0, 200.0, 100.0),
4562            path,
4563            stroke: Some(strata_gpu_path::StrokeOptions::new(2.0)),
4564            fill_color: Some(Color::rgb(16, 185, 129)),
4565            stroke_color: Some(Color::rgb(5, 150, 105)),
4566            transform: None,
4567        });
4568
4569        // Add DrawSvgPath
4570        dl.push(DrawCommand::DrawSvgPath {
4571            bounds: Rect::new(300.0, 300.0, 50.0, 50.0),
4572            path_data: "M 0 0 L 50 50 Z".to_string(),
4573            stroke_color: Some(Color::rgb(255, 255, 255)),
4574            fill_color: None,
4575            stroke_width: 1.5,
4576            stroke_linecap: strata_layout::StrokeLineCap::Round,
4577            stroke_linejoin: strata_layout::StrokeLineJoin::Round,
4578            stroke_dasharray: Vec::new(),
4579            fill_rule: strata_layout::FillRule::NonZero,
4580            view_box: (50.0, 50.0),
4581        });
4582
4583        let seg_count = path_pipeline.compile_frame(&dl, None);
4584        assert!(
4585            seg_count >= 4,
4586            "Should emit multiple quadratic segments for path + svg"
4587        );
4588        assert_eq!(path_pipeline.compiled_frames, 1);
4589        assert_eq!(path_pipeline.segment_bytes().len(), seg_count * 64);
4590        assert_eq!(path_pipeline.uniform_bytes().len(), 16);
4591
4592        // Test damage scissoring: scissoring away the second path
4593        let damage = Rect::new(0.0, 0.0, 220.0, 120.0);
4594        let damaged_count = path_pipeline.compile_frame(&dl, Some(damage));
4595        assert!(
4596            damaged_count < seg_count,
4597            "Damaged compilation should skip path outside damage rect"
4598        );
4599    }
4600
4601    #[test]
4602    fn test_gpu_batch_dashed_stroke_rect() {
4603        let mut ctx = crate::canvas2d::Canvas2DContext::new(200.0, 200.0);
4604        ctx.set_stroke_style(Color::rgb(255, 255, 255));
4605        ctx.set_line_width(2.0);
4606        ctx.save();
4607        ctx.set_line_dash(&[10.0, 10.0]);
4608        // 100x40 perimeter = 280 -> should emit multiple dash quads
4609        ctx.stroke_rect(10.0, 10.0, 100.0, 40.0);
4610        ctx.restore();
4611        // After restore, dash is cleared -> single solid bordered StrokeRect quad
4612        ctx.stroke_rect(10.0, 70.0, 100.0, 40.0);
4613
4614        let mut dl = DisplayList::new();
4615        dl.push(DrawCommand::DrawCanvas2D {
4616            bounds: Rect::new(0.0, 0.0, 200.0, 200.0),
4617            commands: ctx.commands().to_vec(),
4618        });
4619
4620        let batch = GpuBatch::from_display_list(&dl, 200.0, 200.0);
4621        // Perimeter 280 with 10 on / 10 off produces 14 dash instances, plus 1 solid instance after restore = 15
4622        assert_eq!(batch.instances.len(), 15);
4623        // Solid last instance carries non-zero border_width
4624        let last = batch.instances.last().unwrap();
4625        assert!(last.border_width[0] > 1.5);
4626        // Dash instances are solid fill rects with border_width == 0
4627        assert_eq!(batch.instances[0].border_width, [0.0; 4]);
4628    }
4629
4630    #[test]
4631    fn test_gpu_path_pipeline_set_line_cap_and_set_line_join() {
4632        let build_corner = |cap: crate::canvas2d::CanvasLineCap, join: crate::canvas2d::CanvasLineJoin| {
4633            let mut ctx = crate::canvas2d::Canvas2DContext::new(200.0, 200.0);
4634            ctx.set_stroke_style(Color::rgb(0, 255, 128));
4635            ctx.set_line_width(10.0);
4636            ctx.save();
4637            ctx.set_line_cap(cap);
4638            ctx.set_line_join(join);
4639            ctx.begin_path();
4640            ctx.move_to(10.0, 30.0);
4641            ctx.line_to(50.0, 30.0);
4642            ctx.line_to(50.0, 70.0);
4643            ctx.stroke();
4644            ctx.restore();
4645            // After restore, caps/joins revert to Butt / Miter
4646            ctx.begin_path();
4647            ctx.move_to(10.0, 100.0);
4648            ctx.line_to(80.0, 100.0);
4649            ctx.stroke();
4650
4651            let mut dl = DisplayList::new();
4652            dl.push(DrawCommand::DrawCanvas2D {
4653                bounds: Rect::new(0.0, 0.0, 200.0, 200.0),
4654                commands: ctx.commands().to_vec(),
4655            });
4656            let mut pipe = GpuPathPipeline::new(200.0, 200.0);
4657            pipe.compile_frame(&dl, None);
4658            pipe.batch.segments
4659        };
4660
4661        let segs_butt_miter =
4662            build_corner(crate::canvas2d::CanvasLineCap::Butt, crate::canvas2d::CanvasLineJoin::Miter);
4663        let segs_round_bevel =
4664            build_corner(crate::canvas2d::CanvasLineCap::Round, crate::canvas2d::CanvasLineJoin::Bevel);
4665        let segs_square_round =
4666            build_corner(crate::canvas2d::CanvasLineCap::Square, crate::canvas2d::CanvasLineJoin::Round);
4667
4668        // Butt vs Round vs Square open cap flags on first segment of the polyline
4669        assert_eq!(segs_butt_miter[0].flags & strata_gpu_path::FLAG_CAP_ROUND, 0);
4670        assert_eq!(segs_butt_miter[0].flags & strata_gpu_path::FLAG_CAP_SQUARE, 0);
4671        assert_ne!(segs_butt_miter[0].flags & strata_gpu_path::FLAG_START_OPEN, 0);
4672
4673        assert_ne!(segs_round_bevel[0].flags & strata_gpu_path::FLAG_CAP_ROUND, 0);
4674        assert_ne!(segs_round_bevel[0].flags & strata_gpu_path::FLAG_JOIN_BEVEL, 0);
4675        assert_ne!(segs_square_round[0].flags & strata_gpu_path::FLAG_CAP_SQUARE, 0);
4676        assert_ne!(segs_square_round[0].flags & strata_gpu_path::FLAG_JOIN_ROUND, 0);
4677
4678        // Miter emits 2 FLAG_TRIANGLE corner wedges reaching apex (55, 25); Bevel emits 1 triangle; Round emits 1 disk
4679        let miter_tris: Vec<_> = segs_butt_miter
4680            .iter()
4681            .filter(|s| (s.flags & strata_gpu_path::FLAG_TRIANGLE) != 0)
4682            .collect();
4683        assert_eq!(miter_tris.len(), 2);
4684        assert!(miter_tris.iter().any(|s| s.p2 == [55.0, 25.0] || s.p1 == [55.0, 25.0]));
4685
4686        let bevel_tris: Vec<_> = segs_round_bevel
4687            .iter()
4688            .filter(|s| (s.flags & strata_gpu_path::FLAG_TRIANGLE) != 0)
4689            .collect();
4690        assert_eq!(bevel_tris.len(), 1);
4691        assert_ne!(bevel_tris[0].flags & strata_gpu_path::FLAG_JOIN_BEVEL, 0);
4692
4693        let round_joins: Vec<_> = segs_square_round
4694            .iter()
4695            .filter(|s| s.p0 == [50.0, 30.0] && s.p2 == [50.0, 30.0])
4696            .collect();
4697        assert_eq!(round_joins.len(), 1);
4698        assert_ne!(round_joins[0].flags & strata_gpu_path::FLAG_CAP_ROUND, 0);
4699
4700        // Restored final line segment must revert to Butt (no Round/Square cap flags)
4701        let last_line_round_ctx = segs_round_bevel.last().unwrap();
4702        assert_eq!(last_line_round_ctx.flags & strata_gpu_path::FLAG_CAP_ROUND, 0);
4703        assert_eq!(last_line_round_ctx.flags & strata_gpu_path::FLAG_CAP_SQUARE, 0);
4704    }
4705
4706    #[test]
4707    fn test_gpu_non_rectangular_clip_path_parity_for_quads_and_paths() {
4708        // 1. Diagonal triangle clip (0,0) -> (100,0) -> (0,100)
4709        // AABB is [0,0,100,100], yet any rect with x+y > 100 lies outside the diagonal clip!
4710        let mut ctx = crate::canvas2d::Canvas2DContext::new(200.0, 200.0);
4711        ctx.save();
4712        ctx.begin_path();
4713        ctx.move_to(0.0, 0.0);
4714        ctx.line_to(100.0, 0.0);
4715        ctx.line_to(0.0, 100.0);
4716        ctx.close_path();
4717        ctx.clip();
4718
4719        // Inside AABB [0..100, 0..100], strictly OUTSIDE diagonal triangle -> must be culled!
4720        ctx.set_fill_style(Color::rgb(255, 0, 0));
4721        ctx.fill_rect(60.0, 60.0, 30.0, 30.0);
4722
4723        // Strictly INSIDE diagonal triangle ((5..25) -> max x+y = 50 < 100) -> no stencil mask needed
4724        ctx.set_fill_style(Color::rgb(0, 255, 0));
4725        ctx.fill_rect(5.0, 5.0, 20.0, 20.0);
4726
4727        // Crosses diagonal boundary -> requires triangulated stencil mask
4728        ctx.set_fill_style(Color::rgb(0, 0, 255));
4729        ctx.fill_rect(0.0, 0.0, 100.0, 100.0);
4730
4731        // Line strictly outside triangle -> culled by GpuPathBatch too
4732        ctx.set_stroke_style(Color::rgb(255, 255, 0));
4733        ctx.set_line_width(2.0);
4734        ctx.begin_path();
4735        ctx.move_to(65.0, 65.0);
4736        ctx.line_to(90.0, 90.0);
4737        ctx.stroke();
4738
4739        // Line inside/crossing triangle -> emitted with clip mask on partial span
4740        ctx.begin_path();
4741        ctx.move_to(10.0, 10.0);
4742        ctx.line_to(80.0, 80.0);
4743        ctx.stroke();
4744        ctx.restore();
4745
4746        // Rectangular clip must NOT allocate stencil masks
4747        ctx.save();
4748        ctx.begin_path();
4749        ctx.rect(110.0, 10.0, 50.0, 50.0);
4750        ctx.clip();
4751        ctx.fill_rect(115.0, 15.0, 20.0, 20.0);
4752        ctx.restore();
4753
4754        // Circular aperture clip
4755        ctx.save();
4756        ctx.begin_path();
4757        ctx.arc(150.0, 150.0, 30.0, 0.0, std::f32::consts::TAU, false);
4758        ctx.clip();
4759        // Corner of circle's AABB [120..180, 120..180] outside radius 30: dist from (150,150) to (122..126) is > 33!
4760        ctx.fill_rect(121.0, 121.0, 4.0, 4.0);
4761        // Crossing circle center
4762        ctx.fill_rect(120.0, 120.0, 60.0, 60.0);
4763        ctx.restore();
4764
4765        let mut dl = DisplayList::new();
4766        dl.push(DrawCommand::DrawCanvas2D {
4767            bounds: Rect::new(0.0, 0.0, 200.0, 200.0),
4768            commands: ctx.commands().to_vec(),
4769        });
4770
4771        let batch = GpuBatch::from_display_list(&dl, 200.0, 200.0);
4772        assert!(batch.has_stencil_clips());
4773        // Red (60,60) and corner-outside-circle (121,121) were culled -> 4 quads remain!
4774        assert_eq!(batch.instances.len(), 4);
4775        // Green (5,5) is strictly inside triangle -> no stencil mask
4776        assert!(batch.clip_mask_for_instance(0).is_none());
4777        // Blue (0,0,100,100) crosses diagonal -> stencil mask has vertices and accurate point test
4778        let diag_mask = batch
4779            .clip_mask_for_instance(1)
4780            .expect("crossing quad should have diagonal stencil clip mask");
4781        assert!(diag_mask.total_stencil_vertices() >= 3);
4782        assert_eq!(diag_mask.total_stencil_vertices() % 3, 0);
4783        assert!(diag_mask.contains_point(20.0, 20.0));
4784        assert!(!diag_mask.contains_point(75.0, 75.0));
4785
4786        // Rect clip (instance 2) must be unmasked after restore()
4787        assert!(batch.clip_mask_for_instance(2).is_none());
4788
4789        // Circular clip (instance 3)
4790        let circle_mask = batch
4791            .clip_mask_for_instance(3)
4792            .expect("circle aperture should bind stencil mask");
4793        assert!(circle_mask.contains_point(150.0, 150.0));
4794        assert!(!circle_mask.contains_point(122.0, 122.0));
4795
4796        // GpuPathBatch also culls outside diagonal & circle clips and compiles stencil shader
4797        let mut collector = GpuBatchCollector::new(200.0, 200.0);
4798        let summary = collector.collect(&dl, None);
4799        assert!(collector.path_batch.has_stencil_clips());
4800        let mut dev = crate::gpu_context::GpuDevice::new(
4801            200,
4802            200,
4803            crate::swapchain::SwapchainFormat::Rgba8Unorm,
4804        );
4805        let dispatched = collector.dispatch(&mut dev, None).expect("dispatch");
4806        assert_eq!(dispatched.total_draw_calls, summary.total_draw_calls);
4807        assert!(GpuRenderPipeline::new_stencil_clip_pipeline(200.0, 200.0).is_ok());
4808    }
4809
4810    #[test]
4811    fn test_unified_gpu_collector_hardware_frame_ordering_and_stencil_masks() {
4812        let mut collector = UnifiedGpuCollector::new(240.0, 240.0);
4813
4814        let mut canvas = crate::canvas2d::Canvas2DContext::new(240.0, 240.0);
4815        canvas.set_fill_style(Color::rgb(20, 40, 80));
4816        canvas.fill_rect(0.0, 0.0, 240.0, 240.0);
4817        canvas.save();
4818        canvas.set_stroke_style(Color::rgb(255, 200, 0));
4819        canvas.set_line_width(6.0);
4820        canvas.set_line_cap(crate::canvas2d::CanvasLineCap::Round);
4821        canvas.set_line_join(crate::canvas2d::CanvasLineJoin::Bevel);
4822        canvas.begin_path();
4823        canvas.move_to(20.0, 40.0);
4824        canvas.line_to(100.0, 40.0);
4825        canvas.line_to(100.0, 120.0);
4826        canvas.stroke();
4827        canvas.restore();
4828        canvas.set_fill_style(Color::rgb(12, 12, 16));
4829        canvas.fill_rect(60.0, 30.0, 60.0, 24.0);
4830        canvas.set_fill_style(Color::WHITE);
4831        canvas.fill_text("A", 70.0, 46.0);
4832
4833        let scene = crate::scene3d::Scene3D::new();
4834        let mut dl = DisplayList::new();
4835        dl.push(DrawCommand::DrawRect {
4836            bounds: Rect::new(0.0, 0.0, 240.0, 240.0),
4837            color: Color::rgb(10, 12, 18),
4838        });
4839        dl.push(DrawCommand::DrawViewport3D {
4840            bounds: Rect::new(120.0, 20.0, 100.0, 100.0),
4841            scene: std::sync::Arc::new(scene),
4842        });
4843        dl.push(DrawCommand::DrawCanvas2D {
4844            bounds: Rect::new(0.0, 0.0, 240.0, 240.0),
4845            commands: canvas.commands().to_vec(),
4846        });
4847
4848        let frame = collector.collect_hardware_frame(&dl, None);
4849        // Order: bg DrawRect (Quads) -> Viewport3D -> FillRect (Quads) -> Path stroke (Paths) -> badge FillRect (Quads) -> FillText (Text)
4850        assert!(frame.items.len() >= 6);
4851        assert!(matches!(
4852            frame.items[0],
4853            HardwareRenderItem::Batch(HardwareDrawOp {
4854                kind: HardwareDrawOpKind::Quads,
4855                ..
4856            })
4857        ));
4858        assert!(matches!(
4859            frame.items[1],
4860            HardwareRenderItem::Viewport3D { .. }
4861        ));
4862        // Capped path stroke is preserved strictly between FillRect #1 and badge FillRect #2!
4863        let path_pos = frame
4864            .items
4865            .iter()
4866            .position(|it| {
4867                matches!(
4868                    it,
4869                    HardwareRenderItem::Batch(HardwareDrawOp {
4870                        kind: HardwareDrawOpKind::Paths,
4871                        ..
4872                    })
4873                )
4874            })
4875            .expect("path stroke op");
4876        let text_pos = frame
4877            .items
4878            .iter()
4879            .position(|it| {
4880                matches!(
4881                    it,
4882                    HardwareRenderItem::Batch(HardwareDrawOp {
4883                        kind: HardwareDrawOpKind::Text,
4884                        ..
4885                    })
4886                )
4887            })
4888            .expect("slug text op");
4889        assert!(path_pos < text_pos);
4890        // Canvas FillRect must NOT emit duplicate segments in paths batch
4891        assert!(!frame.paths.segments.is_empty());
4892        assert_eq!(
4893            frame.quads.len(),
4894            3,
4895            "bg rect + canvas FillRect + badge FillRect"
4896        );
4897    }
4898
4899    #[cfg(feature = "wgpu-backend")]
4900    #[test]
4901    fn test_wgpu_2d_renderer_stencil_clip_dashed_stroke_caps_joins_and_slug_pixels() {
4902        let instance = wgpu::Instance::default();
4903        let Ok((_adapter, device, queue)) = crate::gpu_wgpu::request_working_adapter_and_device(
4904            &instance,
4905            None,
4906            "strata_render_2d_test_device",
4907        ) else {
4908            return;
4909        };
4910
4911        let mut renderer = Wgpu2DRenderer::from_device(
4912            std::sync::Arc::new(device),
4913            std::sync::Arc::new(queue),
4914            wgpu::TextureFormat::Rgba8Unorm,
4915        );
4916        let mut collector = UnifiedGpuCollector::new(240.0, 240.0);
4917
4918        let mut ctx = crate::canvas2d::Canvas2DContext::new(240.0, 240.0);
4919        // 1. Diagonal triangle clip (0,0)-(100,0)-(0,100) + crossing blue FillRect
4920        ctx.save();
4921        ctx.begin_path();
4922        ctx.move_to(0.0, 0.0);
4923        ctx.line_to(100.0, 0.0);
4924        ctx.line_to(0.0, 100.0);
4925        ctx.close_path();
4926        ctx.clip();
4927        ctx.set_fill_style(Color::rgb(0, 120, 255));
4928        ctx.fill_rect(0.0, 0.0, 100.0, 100.0);
4929        ctx.restore();
4930
4931        // 2. Circular clip aperture at (170, 55), radius 30 + full AABB green FillRect
4932        ctx.save();
4933        ctx.begin_path();
4934        ctx.arc(170.0, 55.0, 30.0, 0.0, std::f32::consts::TAU, false);
4935        ctx.clip();
4936        ctx.set_fill_style(Color::rgb(0, 220, 80));
4937        ctx.fill_rect(140.0, 25.0, 60.0, 60.0);
4938        ctx.restore();
4939
4940        // 3. Dashed StrokeRect [12, 12] from x=20..120 at y=140, width=4 (dash on [20..32], gap on [36..42])
4941        ctx.save();
4942        ctx.set_stroke_style(Color::rgb(255, 60, 60));
4943        ctx.set_line_width(4.0);
4944        ctx.set_line_dash(&[12.0, 12.0]);
4945        ctx.stroke_rect(20.0, 140.0, 100.0, 30.0);
4946        ctx.restore();
4947
4948        // 4. Straight horizontal+vertical stroke with Round cap + Miter join
4949        ctx.save();
4950        ctx.set_stroke_style(Color::rgb(255, 220, 0));
4951        ctx.set_line_width(10.0);
4952        ctx.set_line_cap(crate::canvas2d::CanvasLineCap::Round);
4953        ctx.set_line_join(crate::canvas2d::CanvasLineJoin::Miter);
4954        ctx.begin_path();
4955        ctx.move_to(150.0, 150.0);
4956        ctx.line_to(200.0, 150.0);
4957        ctx.line_to(200.0, 200.0);
4958        ctx.stroke();
4959        ctx.restore();
4960
4961        // 5. Slug glyph "H" rendered in bright cyan
4962        let mut dl = DisplayList::new();
4963        dl.push(DrawCommand::DrawCanvas2D {
4964            bounds: Rect::new(0.0, 0.0, 240.0, 240.0),
4965            commands: ctx.commands().to_vec(),
4966        });
4967        dl.push(DrawCommand::DrawText {
4968            origin: (20.0, 195.0),
4969            bounds_width: None,
4970            bounds_height: None,
4971            text_align: strata_style::TextAlign::Left,
4972            text: "H".to_string(),
4973            font_size: 24.0,
4974            line_height: 1.2,
4975            font_weight: strata_style::FontWeight::Bold,
4976            color: Color::rgb(0, 240, 240),
4977            is_monospace: false,
4978            font_family: strata_primitives::atom::AtomId::NULL,
4979        });
4980
4981        let (summary, pixels) = renderer
4982            .render_display_list_offscreen(
4983                &mut collector,
4984                &dl,
4985                240,
4986                240,
4987                1.0,
4988                [0.0, 0.0, 0.0, 1.0],
4989                None,
4990                true,
4991            )
4992            .expect("wgpu 2D offscreen render");
4993        assert!(summary.quad_instances >= 10);
4994        assert!(summary.path_segments > 0);
4995        assert!(summary.slug_glyphs > 0);
4996
4997        let px = |x: usize, y: usize| -> [u8; 4] {
4998            let idx = (y * 240 + x) * 4;
4999            [pixels[idx], pixels[idx + 1], pixels[idx + 2], pixels[idx + 3]]
5000        };
5001
5002        // Diagonal triangle clip: (20,20) inside (blue), (75,75) inside AABB but outside diagonal (black!)
5003        let diag_in = px(20, 20);
5004        assert!(
5005            diag_in[2] > 200 && diag_in[0] < 20,
5006            "inside diagonal clip should be blue: {:?}",
5007            diag_in
5008        );
5009        let diag_out = px(75, 75);
5010        assert_eq!(
5011            diag_out,
5012            [0, 0, 0, 255],
5013            "outside diagonal clip must remain cleared background via stencil"
5014        );
5015
5016        // Circular clip: (170,55) inside (green), (143,28) in circle AABB corner outside radius 30 (black!)
5017        let circ_in = px(170, 55);
5018        assert!(
5019            circ_in[1] > 180 && circ_in[0] < 20,
5020            "inside circular clip should be green: {:?}",
5021            circ_in
5022        );
5023        let circ_corner = px(143, 28);
5024        assert_eq!(
5025            circ_corner,
5026            [0, 0, 0, 255],
5027            "outside circular clip must remain black via stencil"
5028        );
5029
5030        // Dashed StrokeRect: dash on [20..32] at (25, 140) is red; gap [32..44] at (38, 140) is black
5031        let dash_on = px(25, 140);
5032        assert!(
5033            dash_on[0] > 200 && dash_on[1] < 80,
5034            "dash segment should be red: {:?}",
5035            dash_on
5036        );
5037        assert_eq!(px(38, 140), [0, 0, 0, 255], "dash gap must stay background");
5038
5039        // Round cap + Miter join stroke: midpoint (175, 150) & miter apex (203, 147) & round cap tail (147, 150)
5040        assert!(
5041            px(175, 150)[0] > 200 && px(175, 150)[1] > 180,
5042            "straight segment midpoint must be filled"
5043        );
5044        assert!(
5045            px(147, 150)[0] > 150,
5046            "Round cap extends past x=150: {:?}",
5047            px(147, 150)
5048        );
5049        assert!(
5050            px(203, 147)[0] > 150,
5051            "Miter outer corner reaches outside corner apex: {:?}",
5052            px(203, 147)
5053        );
5054
5055        // Slug glyph "H" should light up at least one cyan pixel inside [20..44, 195..220]
5056        let mut lit_glyph = false;
5057        for y in 195..220 {
5058            for x in 20..44 {
5059                let p = px(x, y);
5060                if p[1] > 150 && p[2] > 150 {
5061                    lit_glyph = true;
5062                    break;
5063                }
5064            }
5065        }
5066        assert!(lit_glyph, "Slug font shader should rasterize visible glyph pixels");
5067    }
5068}