Skip to main content

strata_gpu_path/
compute.rs

1//! GPU Compute Buffer Layouts, Raw Curve Representations, and Compute Dispatchers.
2
3use crate::curve::{CubicBezier, Point2D, QuadraticBezier};
4
5/// Flag indicating that the path segment belongs to a filled polygon / region.
6pub const FLAG_FILL: u32 = 1 << 0;
7/// Flag indicating that the path segment is stroked with a line width.
8pub const FLAG_STROKE: u32 = 1 << 1;
9/// Flag indicating Even-Odd fill rule (default is Non-Zero winding rule).
10pub const FLAG_EVEN_ODD: u32 = 1 << 2;
11/// Flag indicating that the path segment is closed.
12pub const FLAG_CLOSED: u32 = 1 << 3;
13/// Flag indicating round stroke end caps (when paired with `FLAG_START_OPEN` / `FLAG_END_OPEN`).
14pub const FLAG_CAP_ROUND: u32 = 1 << 4;
15/// Flag indicating square stroke end caps (when paired with `FLAG_START_OPEN` / `FLAG_END_OPEN`).
16pub const FLAG_CAP_SQUARE: u32 = 1 << 5;
17/// Flag indicating round corner joins.
18pub const FLAG_JOIN_ROUND: u32 = 1 << 6;
19/// Flag indicating bevel corner joins (both `FLAG_JOIN_ROUND` and `FLAG_JOIN_BEVEL` clear = miter).
20pub const FLAG_JOIN_BEVEL: u32 = 1 << 7;
21/// Flag indicating this segment's start endpoint (`p0`) is an open subpath/dash cap.
22pub const FLAG_START_OPEN: u32 = 1 << 8;
23/// Flag indicating this segment's end endpoint (`p2`) is an open subpath/dash cap.
24pub const FLAG_END_OPEN: u32 = 1 << 9;
25/// Flag indicating `(p0, p1, p2)` encodes a filled 2D triangle (e.g. bevel/miter join wedge or clip).
26pub const FLAG_TRIANGLE: u32 = 1 << 10;
27
28/// Encodes `LineCap`, `LineJoin`, closure, and open-endpoint bits into a `GpuPathSegment::flags` bitmask.
29#[inline]
30pub fn stroke_style_flags(
31    cap: crate::stroke::LineCap,
32    join: crate::stroke::LineJoin,
33    closed: bool,
34    start_open: bool,
35    end_open: bool,
36) -> u32 {
37    let mut flags = FLAG_STROKE;
38    if closed {
39        flags |= FLAG_CLOSED;
40    }
41    match cap {
42        crate::stroke::LineCap::Butt => {}
43        crate::stroke::LineCap::Round => flags |= FLAG_CAP_ROUND,
44        crate::stroke::LineCap::Square => flags |= FLAG_CAP_SQUARE,
45    }
46    match join {
47        crate::stroke::LineJoin::Miter => {}
48        crate::stroke::LineJoin::Round => flags |= FLAG_JOIN_ROUND,
49        crate::stroke::LineJoin::Bevel => flags |= FLAG_JOIN_BEVEL,
50    }
51    if start_open {
52        flags |= FLAG_START_OPEN;
53    }
54    if end_open {
55        flags |= FLAG_END_OPEN;
56    }
57    flags
58}
59
60/// 64-byte aligned raw cubic curve input data fed into WebGPU compute pipelines.
61#[repr(C)]
62#[derive(Debug, Clone, Copy, PartialEq)]
63pub struct RawCurveInput {
64    pub p0: [f32; 2],
65    pub p1: [f32; 2],
66    pub p2: [f32; 2],
67    pub p3: [f32; 2],
68    pub stroke_width: f32,
69    pub flags: u32,
70    pub z_index: f32,
71    pub _pad: f32,
72    pub color: [f32; 4],
73}
74
75impl RawCurveInput {
76    pub const BYTE_SIZE: usize = std::mem::size_of::<Self>();
77
78    pub fn new_cubic(
79        cubic: &CubicBezier,
80        stroke_width: f32,
81        flags: u32,
82        color: [f32; 4],
83        z_index: f32,
84    ) -> Self {
85        Self {
86            p0: [cubic.p0.x, cubic.p0.y],
87            p1: [cubic.p1.x, cubic.p1.y],
88            p2: [cubic.p2.x, cubic.p2.y],
89            p3: [cubic.p3.x, cubic.p3.y],
90            stroke_width,
91            flags,
92            z_index,
93            _pad: 0.0,
94            color,
95        }
96    }
97
98    pub fn new_quadratic(
99        quad: &QuadraticBezier,
100        stroke_width: f32,
101        flags: u32,
102        color: [f32; 4],
103        z_index: f32,
104    ) -> Self {
105        // Degree elevate or replicate control point for compute pipeline uniformity
106        Self {
107            p0: [quad.p0.x, quad.p0.y],
108            p1: [quad.p1.x, quad.p1.y],
109            p2: [quad.p1.x, quad.p1.y],
110            p3: [quad.p2.x, quad.p2.y],
111            stroke_width,
112            flags,
113            z_index,
114            _pad: 0.0,
115            color,
116        }
117    }
118
119    pub fn new_line(
120        p0: Point2D,
121        p1: Point2D,
122        stroke_width: f32,
123        flags: u32,
124        color: [f32; 4],
125        z_index: f32,
126    ) -> Self {
127        let mid = p0.lerp(p1, 0.5);
128        Self {
129            p0: [p0.x, p0.y],
130            p1: [mid.x, mid.y],
131            p2: [mid.x, mid.y],
132            p3: [p1.x, p1.y],
133            stroke_width,
134            flags,
135            z_index,
136            _pad: 0.0,
137            color,
138        }
139    }
140
141    #[inline]
142    pub fn as_bytes(&self) -> &[u8] {
143        unsafe { std::slice::from_raw_parts((self as *const Self) as *const u8, Self::BYTE_SIZE) }
144    }
145
146    #[inline]
147    pub fn slice_to_bytes(slice: &[Self]) -> &[u8] {
148        unsafe {
149            std::slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len() * Self::BYTE_SIZE)
150        }
151    }
152}
153
154/// 64-byte aligned output quadratic segment produced by compute shaders or CPU fallback.
155#[repr(C)]
156#[derive(Debug, Clone, Copy, PartialEq)]
157pub struct GpuPathSegment {
158    pub p0: [f32; 2],
159    pub p1: [f32; 2],
160    pub p2: [f32; 2],
161    pub stroke_width: f32,
162    pub flags: u32,
163    pub color: [f32; 4],
164    pub z_index: f32,
165    pub _pad0: f32,
166    pub _pad1: f32,
167    pub _pad2: f32,
168}
169
170impl GpuPathSegment {
171    pub const BYTE_SIZE: usize = std::mem::size_of::<Self>();
172
173    pub fn from_quadratic(
174        quad: &QuadraticBezier,
175        stroke_width: f32,
176        flags: u32,
177        color: [f32; 4],
178        z_index: f32,
179    ) -> Self {
180        Self {
181            p0: [quad.p0.x, quad.p0.y],
182            p1: [quad.p1.x, quad.p1.y],
183            p2: [quad.p2.x, quad.p2.y],
184            stroke_width,
185            flags,
186            color,
187            z_index,
188            _pad0: 0.0,
189            _pad1: 0.0,
190            _pad2: 0.0,
191        }
192    }
193
194    #[inline]
195    pub fn as_bytes(&self) -> &[u8] {
196        unsafe { std::slice::from_raw_parts((self as *const Self) as *const u8, Self::BYTE_SIZE) }
197    }
198
199    #[inline]
200    pub fn slice_to_bytes(slice: &[Self]) -> &[u8] {
201        unsafe {
202            std::slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len() * Self::BYTE_SIZE)
203        }
204    }
205}
206
207/// 16-byte aligned Uniform Buffer object for path compute operations.
208#[repr(C)]
209#[derive(Debug, Clone, Copy, PartialEq)]
210pub struct GpuPathUniforms {
211    pub viewport_size: [f32; 2],
212    pub tolerance: f32,
213    pub curve_count: u32,
214}
215
216impl GpuPathUniforms {
217    pub const BYTE_SIZE: usize = std::mem::size_of::<Self>();
218
219    pub fn new(
220        viewport_width: f32,
221        viewport_height: f32,
222        tolerance: f32,
223        curve_count: u32,
224    ) -> Self {
225        Self {
226            viewport_size: [viewport_width, viewport_height],
227            tolerance,
228            curve_count,
229        }
230    }
231
232    #[inline]
233    pub fn as_bytes(&self) -> &[u8] {
234        unsafe { std::slice::from_raw_parts((self as *const Self) as *const u8, Self::BYTE_SIZE) }
235    }
236}
237
238/// High-performance CPU dispatcher and simulator matching the WGSL compute pipeline layout.
239#[derive(Debug, Clone, Default)]
240pub struct CurveComputeDispatcher {
241    pub input_curves: Vec<RawCurveInput>,
242    pub tolerance: f32,
243}
244
245impl CurveComputeDispatcher {
246    pub fn new(tolerance: f32) -> Self {
247        Self {
248            input_curves: Vec::new(),
249            tolerance: if tolerance <= 0.0 { 0.25 } else { tolerance },
250        }
251    }
252
253    pub fn push_cubic(
254        &mut self,
255        cubic: &CubicBezier,
256        stroke_width: f32,
257        flags: u32,
258        color: [f32; 4],
259        z_index: f32,
260    ) {
261        self.input_curves.push(RawCurveInput::new_cubic(
262            cubic,
263            stroke_width,
264            flags,
265            color,
266            z_index,
267        ));
268    }
269
270    pub fn push_quadratic(
271        &mut self,
272        quad: &QuadraticBezier,
273        stroke_width: f32,
274        flags: u32,
275        color: [f32; 4],
276        z_index: f32,
277    ) {
278        self.input_curves.push(RawCurveInput::new_quadratic(
279            quad,
280            stroke_width,
281            flags,
282            color,
283            z_index,
284        ));
285    }
286
287    pub fn push_line(
288        &mut self,
289        p0: Point2D,
290        p1: Point2D,
291        stroke_width: f32,
292        flags: u32,
293        color: [f32; 4],
294        z_index: f32,
295    ) {
296        self.input_curves.push(RawCurveInput::new_line(
297            p0,
298            p1,
299            stroke_width,
300            flags,
301            color,
302            z_index,
303        ));
304    }
305
306    pub fn clear(&mut self) {
307        self.input_curves.clear();
308    }
309
310    pub fn len(&self) -> usize {
311        self.input_curves.len()
312    }
313
314    pub fn is_empty(&self) -> bool {
315        self.input_curves.is_empty()
316    }
317
318    pub fn input_bytes(&self) -> &[u8] {
319        RawCurveInput::slice_to_bytes(&self.input_curves)
320    }
321
322    /// Simulates the WGSL compute pass on CPU, adaptively decomposing cubics into quadratics.
323    pub fn dispatch_compute(&self) -> Vec<GpuPathSegment> {
324        let mut output = Vec::with_capacity(self.input_curves.len());
325
326        for raw in &self.input_curves {
327            let p0 = Point2D::new(raw.p0[0], raw.p0[1]);
328            let p1 = Point2D::new(raw.p1[0], raw.p1[1]);
329            let p2 = Point2D::new(raw.p2[0], raw.p2[1]);
330            let p3 = Point2D::new(raw.p3[0], raw.p3[1]);
331
332            let cubic = CubicBezier::new(p0, p1, p2, p3);
333            let quads = cubic.to_quadratics(self.tolerance);
334
335            for q in quads {
336                output.push(GpuPathSegment::from_quadratic(
337                    &q,
338                    raw.stroke_width,
339                    raw.flags,
340                    raw.color,
341                    raw.z_index,
342                ));
343            }
344        }
345
346        output
347    }
348}