strata-gpu-path 0.1.0

Slug and Vello-tier analytical GPU Bézier curve and vector path engine for Project Strata
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Analytical GPU Font Curve Shaders and In-VRAM Text Rasterization (Slug / Loop-Blinn algorithm).
//!
//! Provides hardware-accelerated resolution-independent vector font rendering by evaluating
//! quadratic Bézier curves and winding numbers directly in fragment shaders.

use crate::curve::{QuadraticBezier, Rect2D};
use crate::font_cache::AnalyticGlyph;

/// Embedded WGSL shader for Slug / Loop-Blinn analytical GPU font curve rasterization.
pub const WGSL_SLUG_FONT_SHADER: &str = r#"
struct VertexInput {
    @location(0) position: vec2<f32>, // Unit quad [0, 0] to [1, 1]
};

struct InstanceInput {
    @location(1) bounds: vec4<f32>,      // [x, y, width, height] in screen pixels
    @location(2) color: vec4<f32>,       // Text color RGBA
    @location(3) curve_range: vec2<u32>, // [start_index, count] in glyph curve storage buffer
    @location(4) clip_rect: vec4<f32>,   // Scissor clipping rectangle
    @location(5) glyph_bounds: vec4<f32>,// Normalized [min_x, min_y, max_x, max_y] of glyph design space
};

struct VertexOutput {
    @builtin(position) clip_position: vec4<f32>,
    @location(0) pixel_pos: vec2<f32>,
    @location(1) glyph_coord: vec2<f32>,
    @location(2) color: vec4<f32>,
    @location(3) @interpolate(flat) curve_range: vec2<u32>,
    @location(4) clip_rect: vec4<f32>,
    @location(5) @interpolate(flat) pixel_to_glyph_scale: f32,
};

struct Uniforms {
    viewport_size: vec2<f32>,
    dpr: f32,
    _pad: f32,
};

struct GpuGlyphCurve {
    p0: vec2<f32>,
    p1: vec2<f32>,
    p2: vec2<f32>,
    _pad: vec2<f32>,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<storage, read> glyph_curves: array<GpuGlyphCurve>;

@vertex
fn vs_main(model: VertexInput, instance: InstanceInput) -> VertexOutput {
    var out: VertexOutput;

    let pixel_coords = instance.bounds.xy + model.position * instance.bounds.zw;
    let ndc_x = (pixel_coords.x / uniforms.viewport_size.x) * 2.0 - 1.0;
    let ndc_y = 1.0 - (pixel_coords.y / uniforms.viewport_size.y) * 2.0;

    out.clip_position = vec4<f32>(ndc_x, ndc_y, 0.0, 1.0);
    out.pixel_pos = pixel_coords;

    // Map unit quad to normalized glyph design coordinates
    let glyph_size = instance.glyph_bounds.zw - instance.glyph_bounds.xy;
    out.glyph_coord = instance.glyph_bounds.xy + model.position * glyph_size;

    out.color = instance.color;
    out.curve_range = instance.curve_range;
    out.clip_rect = instance.clip_rect;
    out.pixel_to_glyph_scale = glyph_size.y / max(instance.bounds.w, 1.0);

    return out;
}

// Solves quadratic equation A*t^2 + B*t + C = 0 returning number of valid roots in [0, 1]
fn solve_quadratic_roots(a: f32, b: f32, c: f32) -> vec2<f32> {
    if (abs(a) < 1e-6) {
        if (abs(b) < 1e-6) {
            return vec2<f32>(-1.0, -1.0);
        }
        let t = -c / b;
        if (t >= 0.0 && t <= 1.0) {
            return vec2<f32>(t, -1.0);
        }
        return vec2<f32>(-1.0, -1.0);
    }

    let discr = b * b - 4.0 * a * c;
    if (discr < 0.0) {
        return vec2<f32>(-1.0, -1.0);
    }

    let sqrt_d = sqrt(discr);
    let t1 = (-b - sqrt_d) / (2.0 * a);
    let t2 = (-b + sqrt_d) / (2.0 * a);

    var r1 = -1.0;
    var r2 = -1.0;
    if (t1 >= 0.0 && t1 <= 1.0) {
        r1 = t1;
    }
    if (t2 >= 0.0 && t2 <= 1.0) {
        r2 = t2;
    }
    return vec2<f32>(r1, r2);
}

// Distance from point P to quadratic segment
fn dist_to_segment(p: vec2<f32>, p0: vec2<f32>, p2: vec2<f32>) -> f32 {
    let v = p2 - p0;
    let w = p - p0;
    let c1 = dot(w, v);
    let c2 = dot(v, v);
    let t = clamp(c1 / max(c2, 1e-6), 0.0, 1.0);
    let proj = p0 + t * v;
    return length(p - proj);
}

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    // 1. Scissor clipping
    if (in.pixel_pos.x < in.clip_rect.x || in.pixel_pos.x > in.clip_rect.x + in.clip_rect.z ||
        in.pixel_pos.y < in.clip_rect.y || in.pixel_pos.y > in.clip_rect.y + in.clip_rect.w) {
        discard;
    }

    let p = in.glyph_coord;
    var winding: i32 = 0;
    var min_dist: f32 = 1e6;

    let start = in.curve_range.x;
    let count = in.curve_range.y;
    let total_curves = arrayLength(&glyph_curves);

    for (var i = 0u; i < count; i = i + 1u) {
        let curve_idx = start + i;
        if (curve_idx >= total_curves) {
            break;
        }
        let curve = glyph_curves[curve_idx];

        let p0 = curve.p0;
        let p1 = curve.p1;
        let p2 = curve.p2;

        // Quadratic coefficients for y(t) = P.y
        // y(t) = (1-t)^2 y0 + 2t(1-t) y1 + t^2 y2
        //      = (y0 - 2y1 + y2) t^2 + 2(y1 - y0) t + (y0 - P.y)
        let a = p0.y - 2.0 * p1.y + p2.y;
        let b = 2.0 * (p1.y - p0.y);
        let c = p0.y - p.y;

        let roots = solve_quadratic_roots(a, b, c);

        // Process root 1
        if (roots.x >= 0.0) {
            let t = roots.x;
            let u = 1.0 - t;
            let x = u * u * p0.x + 2.0 * u * t * p1.x + t * t * p2.x;
            if (x > p.x) {
                let dy = 2.0 * a * t + b;
                if (dy > 0.0) {
                    winding = winding + 1;
                } else if (dy < 0.0) {
                    winding = winding - 1;
                }
            }
        }

        // Process root 2
        if (roots.y >= 0.0) {
            let t = roots.y;
            let u = 1.0 - t;
            let x = u * u * p0.x + 2.0 * u * t * p1.x + t * t * p2.x;
            if (x > p.x) {
                let dy = 2.0 * a * t + b;
                if (dy > 0.0) {
                    winding = winding + 1;
                } else if (dy < 0.0) {
                    winding = winding - 1;
                }
            }
        }

        // Compute approximate minimum distance to curve for anti-aliasing
        let d = dist_to_segment(p, p0, p2);
        min_dist = min(min_dist, d);
    }

    // Convert glyph-space distance to screen pixels
    let pixel_dist = min_dist / max(in.pixel_to_glyph_scale, 1e-4);

    let inside = (winding != 0);
    var alpha: f32 = 0.0;
    if (inside) {
        alpha = clamp(0.5 + pixel_dist, 0.0, 1.0);
    } else {
        alpha = clamp(0.5 - pixel_dist, 0.0, 1.0);
    }

    if (alpha <= 0.001) {
        discard;
    }

    return vec4<f32>(in.color.rgb, in.color.a * alpha);
}
"#;

/// GPU representation of a glyph quad instance.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GpuGlyphInstance {
    pub bounds: [f32; 4],       // [x, y, width, height] in screen pixels
    pub color: [f32; 4],        // RGBA
    pub curve_range: [u32; 2],  // [start_index, count] in curve storage buffer
    pub clip_rect: [f32; 4],    // [x, y, width, height]
    pub glyph_bounds: [f32; 4], // [min_x, min_y, max_x, max_y] design space
}

/// GPU representation of a packed quadratic Bézier curve contour.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GpuGlyphCurve {
    pub p0: [f32; 2],
    pub p1: [f32; 2],
    pub p2: [f32; 2],
    pub _pad: [f32; 2],
}

impl GpuGlyphCurve {
    /// Constructs a packed GPU curve from a `QuadraticBezier`.
    pub fn from_quadratic(curve: &QuadraticBezier) -> Self {
        Self {
            p0: [curve.p0.x, curve.p0.y],
            p1: [curve.p1.x, curve.p1.y],
            p2: [curve.p2.x, curve.p2.y],
            _pad: [0.0, 0.0],
        }
    }
}

/// Maximum number of quadratic Bézier curve segments permissible in a single GPU draw batch.
pub const MAX_GLYPH_CURVES: usize = 1_048_576;
/// Maximum number of glyph instances permissible in a single GPU draw batch.
pub const MAX_GLYPH_INSTANCES: usize = 65_536;

/// VRAM-ready batch buffer packing analytical glyph instances and curves.
#[derive(Debug, Default)]
pub struct SlugGlyphBuffer {
    pub instances: Vec<GpuGlyphInstance>,
    pub curves: Vec<GpuGlyphCurve>,
    current_fence: std::sync::atomic::AtomicU64,
}

impl Clone for SlugGlyphBuffer {
    fn clone(&self) -> Self {
        Self {
            instances: self.instances.clone(),
            curves: self.curves.clone(),
            current_fence: std::sync::atomic::AtomicU64::new(
                self.current_fence
                    .load(std::sync::atomic::Ordering::Relaxed),
            ),
        }
    }
}

impl SlugGlyphBuffer {
    /// Creates a new empty glyph buffer.
    pub fn new() -> Self {
        Self::default()
    }

    /// Clears both instance and curve buffers for the next frame.
    pub fn clear(&mut self) {
        self.instances.clear();
        self.curves.clear();
    }

    /// Advances and returns the hardware synchronization fence.
    pub fn sync_barrier(&self) -> u64 {
        self.current_fence
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
            + 1
    }

    /// Verifies whether the hardware fence has been signaled.
    pub fn is_fence_synchronized(&self, fence: u64) -> bool {
        self.current_fence.load(std::sync::atomic::Ordering::SeqCst) >= fence
    }

    /// Appends an analytical glyph to the draw batch with buffer bounds validation.
    pub fn push_glyph(
        &mut self,
        glyph: &AnalyticGlyph,
        screen_bounds: Rect2D,
        color: [f32; 4],
        clip_rect: Rect2D,
    ) -> bool {
        if self.instances.len() >= MAX_GLYPH_INSTANCES
            || self.curves.len() + glyph.curves.len() > MAX_GLYPH_CURVES
        {
            return false;
        }

        let start_index = self.curves.len() as u32;
        let count = glyph.curves.len() as u32;

        for c in &glyph.curves {
            self.curves.push(GpuGlyphCurve::from_quadratic(c));
        }

        let instance = GpuGlyphInstance {
            bounds: [
                screen_bounds.min_x,
                screen_bounds.min_y,
                screen_bounds.width(),
                screen_bounds.height(),
            ],
            color,
            curve_range: [start_index, count],
            clip_rect: [
                clip_rect.min_x,
                clip_rect.min_y,
                clip_rect.width(),
                clip_rect.height(),
            ],
            glyph_bounds: [
                glyph.bounds.min_x,
                glyph.bounds.min_y,
                glyph.bounds.max_x,
                glyph.bounds.max_y,
            ],
        };

        self.instances.push(instance);
        true
    }

    /// Returns byte slice of instance buffer for direct GPU upload.
    pub fn instances_as_bytes(&self) -> &[u8] {
        unsafe {
            std::slice::from_raw_parts(
                self.instances.as_ptr() as *const u8,
                self.instances.len() * std::mem::size_of::<GpuGlyphInstance>(),
            )
        }
    }

    /// Returns byte slice of curve storage buffer for direct GPU upload.
    pub fn curves_as_bytes(&self) -> &[u8] {
        unsafe {
            std::slice::from_raw_parts(
                self.curves.as_ptr() as *const u8,
                self.curves.len() * std::mem::size_of::<GpuGlyphCurve>(),
            )
        }
    }
}

/// Solves quadratic equation A*t^2 + B*t + C = 0 returning valid roots in [0, 1].
pub fn solve_quadratic_roots_f32(a: f32, b: f32, c: f32) -> (Option<f32>, Option<f32>) {
    if a.abs() < 1e-6 {
        if b.abs() < 1e-6 {
            return (None, None);
        }
        let t = -c / b;
        if (0.0..=1.0).contains(&t) {
            return (Some(t), None);
        }
        return (None, None);
    }

    let discr = b * b - 4.0 * a * c;
    if discr < 0.0 {
        return (None, None);
    }

    let sqrt_d = discr.sqrt();
    let t1 = (-b - sqrt_d) / (2.0 * a);
    let t2 = (-b + sqrt_d) / (2.0 * a);

    let r1 = if (0.0..=1.0).contains(&t1) {
        Some(t1)
    } else {
        None
    };
    let r2 = if (0.0..=1.0).contains(&t2) {
        Some(t2)
    } else {
        None
    };
    (r1, r2)
}

/// Evaluates Slug-tier analytical subpixel glyph coverage at a given design/glyph point.
///
/// Returns subpixel coverage alpha in [0.0, 1.0] without polygon tessellation at any zoom scale.
pub fn evaluate_slug_analytical_coverage(
    glyph: &AnalyticGlyph,
    p: [f32; 2],
    pixel_scale: f32,
) -> f32 {
    let mut winding: i32 = 0;
    let mut min_dist: f32 = 1e6;

    for curve in &glyph.curves {
        let p0 = [curve.p0.x, curve.p0.y];
        let p1 = [curve.p1.x, curve.p1.y];
        let p2 = [curve.p2.x, curve.p2.y];

        let a = p0[1] - 2.0 * p1[1] + p2[1];
        let b = 2.0 * (p1[1] - p0[1]);
        let c = p0[1] - p[1];

        let (r1, r2) = solve_quadratic_roots_f32(a, b, c);

        for t in [r1, r2].into_iter().flatten() {
            let u = 1.0 - t;
            let x = u * u * p0[0] + 2.0 * u * t * p1[0] + t * t * p2[0];
            if x > p[0] {
                let dy = 2.0 * a * t + b;
                if dy > 0.0 {
                    winding += 1;
                } else if dy < 0.0 {
                    winding -= 1;
                }
            }
        }

        // Segment distance
        let v = [p2[0] - p0[0], p2[1] - p0[1]];
        let w = [p[0] - p0[0], p[1] - p0[1]];
        let c1 = w[0] * v[0] + w[1] * v[1];
        let c2 = v[0] * v[0] + v[1] * v[1];
        let t = (c1 / c2.max(1e-6)).clamp(0.0, 1.0);
        let proj = [p0[0] + t * v[0], p0[1] + t * v[1]];
        let d = ((p[0] - proj[0]).powi(2) + (p[1] - proj[1]).powi(2)).sqrt();
        min_dist = min_dist.min(d);
    }

    let pixel_dist = min_dist / pixel_scale.max(1e-4);
    let inside = winding != 0;
    if inside {
        (0.5 + pixel_dist).clamp(0.0, 1.0)
    } else {
        (0.5 - pixel_dist).clamp(0.0, 1.0)
    }
}