Skip to main content

strata_gpu_path/
font_shader.rs

1//! Analytical GPU Font Curve Shaders and In-VRAM Text Rasterization (Slug / Loop-Blinn algorithm).
2//!
3//! Provides hardware-accelerated resolution-independent vector font rendering by evaluating
4//! quadratic Bézier curves and winding numbers directly in fragment shaders.
5
6use crate::curve::{QuadraticBezier, Rect2D};
7use crate::font_cache::AnalyticGlyph;
8
9/// Embedded WGSL shader for Slug / Loop-Blinn analytical GPU font curve rasterization.
10pub const WGSL_SLUG_FONT_SHADER: &str = r#"
11struct VertexInput {
12    @location(0) position: vec2<f32>, // Unit quad [0, 0] to [1, 1]
13};
14
15struct InstanceInput {
16    @location(1) bounds: vec4<f32>,      // [x, y, width, height] in screen pixels
17    @location(2) color: vec4<f32>,       // Text color RGBA
18    @location(3) curve_range: vec2<u32>, // [start_index, count] in glyph curve storage buffer
19    @location(4) clip_rect: vec4<f32>,   // Scissor clipping rectangle
20    @location(5) glyph_bounds: vec4<f32>,// Normalized [min_x, min_y, max_x, max_y] of glyph design space
21};
22
23struct VertexOutput {
24    @builtin(position) clip_position: vec4<f32>,
25    @location(0) pixel_pos: vec2<f32>,
26    @location(1) glyph_coord: vec2<f32>,
27    @location(2) color: vec4<f32>,
28    @location(3) @interpolate(flat) curve_range: vec2<u32>,
29    @location(4) clip_rect: vec4<f32>,
30    @location(5) @interpolate(flat) pixel_to_glyph_scale: f32,
31};
32
33struct Uniforms {
34    viewport_size: vec2<f32>,
35    dpr: f32,
36    _pad: f32,
37};
38
39struct GpuGlyphCurve {
40    p0: vec2<f32>,
41    p1: vec2<f32>,
42    p2: vec2<f32>,
43    _pad: vec2<f32>,
44};
45
46@group(0) @binding(0) var<uniform> uniforms: Uniforms;
47@group(0) @binding(1) var<storage, read> glyph_curves: array<GpuGlyphCurve>;
48
49@vertex
50fn vs_main(model: VertexInput, instance: InstanceInput) -> VertexOutput {
51    var out: VertexOutput;
52
53    let pixel_coords = instance.bounds.xy + model.position * instance.bounds.zw;
54    let ndc_x = (pixel_coords.x / uniforms.viewport_size.x) * 2.0 - 1.0;
55    let ndc_y = 1.0 - (pixel_coords.y / uniforms.viewport_size.y) * 2.0;
56
57    out.clip_position = vec4<f32>(ndc_x, ndc_y, 0.0, 1.0);
58    out.pixel_pos = pixel_coords;
59
60    // Map unit quad to normalized glyph design coordinates
61    let glyph_size = instance.glyph_bounds.zw - instance.glyph_bounds.xy;
62    out.glyph_coord = instance.glyph_bounds.xy + model.position * glyph_size;
63
64    out.color = instance.color;
65    out.curve_range = instance.curve_range;
66    out.clip_rect = instance.clip_rect;
67    out.pixel_to_glyph_scale = glyph_size.y / max(instance.bounds.w, 1.0);
68
69    return out;
70}
71
72// Solves quadratic equation A*t^2 + B*t + C = 0 returning number of valid roots in [0, 1]
73fn solve_quadratic_roots(a: f32, b: f32, c: f32) -> vec2<f32> {
74    if (abs(a) < 1e-6) {
75        if (abs(b) < 1e-6) {
76            return vec2<f32>(-1.0, -1.0);
77        }
78        let t = -c / b;
79        if (t >= 0.0 && t <= 1.0) {
80            return vec2<f32>(t, -1.0);
81        }
82        return vec2<f32>(-1.0, -1.0);
83    }
84
85    let discr = b * b - 4.0 * a * c;
86    if (discr < 0.0) {
87        return vec2<f32>(-1.0, -1.0);
88    }
89
90    let sqrt_d = sqrt(discr);
91    let t1 = (-b - sqrt_d) / (2.0 * a);
92    let t2 = (-b + sqrt_d) / (2.0 * a);
93
94    var r1 = -1.0;
95    var r2 = -1.0;
96    if (t1 >= 0.0 && t1 <= 1.0) {
97        r1 = t1;
98    }
99    if (t2 >= 0.0 && t2 <= 1.0) {
100        r2 = t2;
101    }
102    return vec2<f32>(r1, r2);
103}
104
105// Distance from point P to quadratic segment
106fn dist_to_segment(p: vec2<f32>, p0: vec2<f32>, p2: vec2<f32>) -> f32 {
107    let v = p2 - p0;
108    let w = p - p0;
109    let c1 = dot(w, v);
110    let c2 = dot(v, v);
111    let t = clamp(c1 / max(c2, 1e-6), 0.0, 1.0);
112    let proj = p0 + t * v;
113    return length(p - proj);
114}
115
116@fragment
117fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
118    // 1. Scissor clipping
119    if (in.pixel_pos.x < in.clip_rect.x || in.pixel_pos.x > in.clip_rect.x + in.clip_rect.z ||
120        in.pixel_pos.y < in.clip_rect.y || in.pixel_pos.y > in.clip_rect.y + in.clip_rect.w) {
121        discard;
122    }
123
124    let p = in.glyph_coord;
125    var winding: i32 = 0;
126    var min_dist: f32 = 1e6;
127
128    let start = in.curve_range.x;
129    let count = in.curve_range.y;
130    let total_curves = arrayLength(&glyph_curves);
131
132    for (var i = 0u; i < count; i = i + 1u) {
133        let curve_idx = start + i;
134        if (curve_idx >= total_curves) {
135            break;
136        }
137        let curve = glyph_curves[curve_idx];
138
139        let p0 = curve.p0;
140        let p1 = curve.p1;
141        let p2 = curve.p2;
142
143        // Quadratic coefficients for y(t) = P.y
144        // y(t) = (1-t)^2 y0 + 2t(1-t) y1 + t^2 y2
145        //      = (y0 - 2y1 + y2) t^2 + 2(y1 - y0) t + (y0 - P.y)
146        let a = p0.y - 2.0 * p1.y + p2.y;
147        let b = 2.0 * (p1.y - p0.y);
148        let c = p0.y - p.y;
149
150        let roots = solve_quadratic_roots(a, b, c);
151
152        // Process root 1
153        if (roots.x >= 0.0) {
154            let t = roots.x;
155            let u = 1.0 - t;
156            let x = u * u * p0.x + 2.0 * u * t * p1.x + t * t * p2.x;
157            if (x > p.x) {
158                let dy = 2.0 * a * t + b;
159                if (dy > 0.0) {
160                    winding = winding + 1;
161                } else if (dy < 0.0) {
162                    winding = winding - 1;
163                }
164            }
165        }
166
167        // Process root 2
168        if (roots.y >= 0.0) {
169            let t = roots.y;
170            let u = 1.0 - t;
171            let x = u * u * p0.x + 2.0 * u * t * p1.x + t * t * p2.x;
172            if (x > p.x) {
173                let dy = 2.0 * a * t + b;
174                if (dy > 0.0) {
175                    winding = winding + 1;
176                } else if (dy < 0.0) {
177                    winding = winding - 1;
178                }
179            }
180        }
181
182        // Compute approximate minimum distance to curve for anti-aliasing
183        let d = dist_to_segment(p, p0, p2);
184        min_dist = min(min_dist, d);
185    }
186
187    // Convert glyph-space distance to screen pixels
188    let pixel_dist = min_dist / max(in.pixel_to_glyph_scale, 1e-4);
189
190    let inside = (winding != 0);
191    var alpha: f32 = 0.0;
192    if (inside) {
193        alpha = clamp(0.5 + pixel_dist, 0.0, 1.0);
194    } else {
195        alpha = clamp(0.5 - pixel_dist, 0.0, 1.0);
196    }
197
198    if (alpha <= 0.001) {
199        discard;
200    }
201
202    return vec4<f32>(in.color.rgb, in.color.a * alpha);
203}
204"#;
205
206/// GPU representation of a glyph quad instance.
207#[repr(C)]
208#[derive(Debug, Clone, Copy, PartialEq)]
209pub struct GpuGlyphInstance {
210    pub bounds: [f32; 4],       // [x, y, width, height] in screen pixels
211    pub color: [f32; 4],        // RGBA
212    pub curve_range: [u32; 2],  // [start_index, count] in curve storage buffer
213    pub clip_rect: [f32; 4],    // [x, y, width, height]
214    pub glyph_bounds: [f32; 4], // [min_x, min_y, max_x, max_y] design space
215}
216
217/// GPU representation of a packed quadratic Bézier curve contour.
218#[repr(C)]
219#[derive(Debug, Clone, Copy, PartialEq)]
220pub struct GpuGlyphCurve {
221    pub p0: [f32; 2],
222    pub p1: [f32; 2],
223    pub p2: [f32; 2],
224    pub _pad: [f32; 2],
225}
226
227impl GpuGlyphCurve {
228    /// Constructs a packed GPU curve from a `QuadraticBezier`.
229    pub fn from_quadratic(curve: &QuadraticBezier) -> Self {
230        Self {
231            p0: [curve.p0.x, curve.p0.y],
232            p1: [curve.p1.x, curve.p1.y],
233            p2: [curve.p2.x, curve.p2.y],
234            _pad: [0.0, 0.0],
235        }
236    }
237}
238
239/// Maximum number of quadratic Bézier curve segments permissible in a single GPU draw batch.
240pub const MAX_GLYPH_CURVES: usize = 1_048_576;
241/// Maximum number of glyph instances permissible in a single GPU draw batch.
242pub const MAX_GLYPH_INSTANCES: usize = 65_536;
243
244/// VRAM-ready batch buffer packing analytical glyph instances and curves.
245#[derive(Debug, Default)]
246pub struct SlugGlyphBuffer {
247    pub instances: Vec<GpuGlyphInstance>,
248    pub curves: Vec<GpuGlyphCurve>,
249    current_fence: std::sync::atomic::AtomicU64,
250}
251
252impl Clone for SlugGlyphBuffer {
253    fn clone(&self) -> Self {
254        Self {
255            instances: self.instances.clone(),
256            curves: self.curves.clone(),
257            current_fence: std::sync::atomic::AtomicU64::new(
258                self.current_fence
259                    .load(std::sync::atomic::Ordering::Relaxed),
260            ),
261        }
262    }
263}
264
265impl SlugGlyphBuffer {
266    /// Creates a new empty glyph buffer.
267    pub fn new() -> Self {
268        Self::default()
269    }
270
271    /// Clears both instance and curve buffers for the next frame.
272    pub fn clear(&mut self) {
273        self.instances.clear();
274        self.curves.clear();
275    }
276
277    /// Advances and returns the hardware synchronization fence.
278    pub fn sync_barrier(&self) -> u64 {
279        self.current_fence
280            .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
281            + 1
282    }
283
284    /// Verifies whether the hardware fence has been signaled.
285    pub fn is_fence_synchronized(&self, fence: u64) -> bool {
286        self.current_fence.load(std::sync::atomic::Ordering::SeqCst) >= fence
287    }
288
289    /// Appends an analytical glyph to the draw batch with buffer bounds validation.
290    pub fn push_glyph(
291        &mut self,
292        glyph: &AnalyticGlyph,
293        screen_bounds: Rect2D,
294        color: [f32; 4],
295        clip_rect: Rect2D,
296    ) -> bool {
297        if self.instances.len() >= MAX_GLYPH_INSTANCES
298            || self.curves.len() + glyph.curves.len() > MAX_GLYPH_CURVES
299        {
300            return false;
301        }
302
303        let start_index = self.curves.len() as u32;
304        let count = glyph.curves.len() as u32;
305
306        for c in &glyph.curves {
307            self.curves.push(GpuGlyphCurve::from_quadratic(c));
308        }
309
310        let instance = GpuGlyphInstance {
311            bounds: [
312                screen_bounds.min_x,
313                screen_bounds.min_y,
314                screen_bounds.width(),
315                screen_bounds.height(),
316            ],
317            color,
318            curve_range: [start_index, count],
319            clip_rect: [
320                clip_rect.min_x,
321                clip_rect.min_y,
322                clip_rect.width(),
323                clip_rect.height(),
324            ],
325            glyph_bounds: [
326                glyph.bounds.min_x,
327                glyph.bounds.min_y,
328                glyph.bounds.max_x,
329                glyph.bounds.max_y,
330            ],
331        };
332
333        self.instances.push(instance);
334        true
335    }
336
337    /// Returns byte slice of instance buffer for direct GPU upload.
338    pub fn instances_as_bytes(&self) -> &[u8] {
339        unsafe {
340            std::slice::from_raw_parts(
341                self.instances.as_ptr() as *const u8,
342                self.instances.len() * std::mem::size_of::<GpuGlyphInstance>(),
343            )
344        }
345    }
346
347    /// Returns byte slice of curve storage buffer for direct GPU upload.
348    pub fn curves_as_bytes(&self) -> &[u8] {
349        unsafe {
350            std::slice::from_raw_parts(
351                self.curves.as_ptr() as *const u8,
352                self.curves.len() * std::mem::size_of::<GpuGlyphCurve>(),
353            )
354        }
355    }
356}
357
358/// Solves quadratic equation A*t^2 + B*t + C = 0 returning valid roots in [0, 1].
359pub fn solve_quadratic_roots_f32(a: f32, b: f32, c: f32) -> (Option<f32>, Option<f32>) {
360    if a.abs() < 1e-6 {
361        if b.abs() < 1e-6 {
362            return (None, None);
363        }
364        let t = -c / b;
365        if (0.0..=1.0).contains(&t) {
366            return (Some(t), None);
367        }
368        return (None, None);
369    }
370
371    let discr = b * b - 4.0 * a * c;
372    if discr < 0.0 {
373        return (None, None);
374    }
375
376    let sqrt_d = discr.sqrt();
377    let t1 = (-b - sqrt_d) / (2.0 * a);
378    let t2 = (-b + sqrt_d) / (2.0 * a);
379
380    let r1 = if (0.0..=1.0).contains(&t1) {
381        Some(t1)
382    } else {
383        None
384    };
385    let r2 = if (0.0..=1.0).contains(&t2) {
386        Some(t2)
387    } else {
388        None
389    };
390    (r1, r2)
391}
392
393/// Evaluates Slug-tier analytical subpixel glyph coverage at a given design/glyph point.
394///
395/// Returns subpixel coverage alpha in [0.0, 1.0] without polygon tessellation at any zoom scale.
396pub fn evaluate_slug_analytical_coverage(
397    glyph: &AnalyticGlyph,
398    p: [f32; 2],
399    pixel_scale: f32,
400) -> f32 {
401    let mut winding: i32 = 0;
402    let mut min_dist: f32 = 1e6;
403
404    for curve in &glyph.curves {
405        let p0 = [curve.p0.x, curve.p0.y];
406        let p1 = [curve.p1.x, curve.p1.y];
407        let p2 = [curve.p2.x, curve.p2.y];
408
409        let a = p0[1] - 2.0 * p1[1] + p2[1];
410        let b = 2.0 * (p1[1] - p0[1]);
411        let c = p0[1] - p[1];
412
413        let (r1, r2) = solve_quadratic_roots_f32(a, b, c);
414
415        for t in [r1, r2].into_iter().flatten() {
416            let u = 1.0 - t;
417            let x = u * u * p0[0] + 2.0 * u * t * p1[0] + t * t * p2[0];
418            if x > p[0] {
419                let dy = 2.0 * a * t + b;
420                if dy > 0.0 {
421                    winding += 1;
422                } else if dy < 0.0 {
423                    winding -= 1;
424                }
425            }
426        }
427
428        // Segment distance
429        let v = [p2[0] - p0[0], p2[1] - p0[1]];
430        let w = [p[0] - p0[0], p[1] - p0[1]];
431        let c1 = w[0] * v[0] + w[1] * v[1];
432        let c2 = v[0] * v[0] + v[1] * v[1];
433        let t = (c1 / c2.max(1e-6)).clamp(0.0, 1.0);
434        let proj = [p0[0] + t * v[0], p0[1] + t * v[1]];
435        let d = ((p[0] - proj[0]).powi(2) + (p[1] - proj[1]).powi(2)).sqrt();
436        min_dist = min_dist.min(d);
437    }
438
439    let pixel_dist = min_dist / pixel_scale.max(1e-4);
440    let inside = winding != 0;
441    if inside {
442        (0.5 + pixel_dist).clamp(0.0, 1.0)
443    } else {
444        (0.5 - pixel_dist).clamp(0.0, 1.0)
445    }
446}