Skip to main content

cranpose_render_common/
shape_sdf.rs

1//! CPU mirror of the signed-distance functions in `shaders/shape.wgsl`.
2//!
3//! The software (pixels) renderer rasterizes the *same* shapes as the GPU. Both
4//! evaluate these formulas, so a stroked rect or an arc looks the same on either
5//! backend instead of the CPU path quietly degrading to a filled box.
6//!
7//! Angle convention (shared with `cranpose_ui_graphics::stroke`): radians, `0`
8//! along +X, increasing clockwise on screen (y-down device space).
9
10use cranpose_ui_graphics::{ArcGeometry, CornerRadii, Point, Rect, StrokeCap, StrokeJoin};
11
12const INV_SQRT2: f32 = std::f32::consts::FRAC_1_SQRT_2;
13
14/// Signed distance to a rounded box centered at the origin.
15///
16/// `radii` is ordered exactly like the WGSL `vec4`: top-left, top-right,
17/// bottom-left, bottom-right.
18pub fn sdf_rounded_rect(p: Point, half_size: (f32, f32), radii: [f32; 4]) -> f32 {
19    let radius = match (p.x > 0.0, p.y > 0.0) {
20        (false, false) => radii[0],
21        (true, false) => radii[1],
22        (false, true) => radii[2],
23        (true, true) => radii[3],
24    };
25    let qx = p.x.abs() - half_size.0 + radius;
26    let qy = p.y.abs() - half_size.1 + radius;
27    let inside = qx.max(qy).min(0.0);
28    let outside = (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt();
29    inside + outside - radius
30}
31
32/// Signed distance to the outline of a rounded box stroked with a centered
33/// stroke of width `2 * half_width`.
34///
35/// `half_size` is the **inflated** box (geometry plus `half_width` on every
36/// side), matching what the renderer hands the shader.
37pub fn sdf_stroked_rounded_rect(
38    p: Point,
39    half_size: (f32, f32),
40    radii: [f32; 4],
41    half_width: f32,
42    join: StrokeJoin,
43) -> f32 {
44    let hw = half_width.max(0.0);
45    let geom = ((half_size.0 - hw).max(0.0), (half_size.1 - hw).max(0.0));
46
47    let mut outer_radii = [radii[0] + hw, radii[1] + hw, radii[2] + hw, radii[3] + hw];
48    if join != StrokeJoin::Round {
49        for (out, r) in outer_radii.iter_mut().zip(radii.iter()) {
50            if *r < 0.0001 {
51                *out = 0.0;
52            }
53        }
54    }
55    let inner_radii = [
56        (radii[0] - hw).max(0.0),
57        (radii[1] - hw).max(0.0),
58        (radii[2] - hw).max(0.0),
59        (radii[3] - hw).max(0.0),
60    ];
61
62    let outer = sdf_rounded_rect(p, (geom.0 + hw, geom.1 + hw), outer_radii);
63    let inner = sdf_rounded_rect(
64        p,
65        ((geom.0 - hw).max(0.0), (geom.1 - hw).max(0.0)),
66        inner_radii,
67    );
68    let mut dist = outer.max(-inner);
69
70    if join == StrokeJoin::Bevel {
71        let chamfer = (p.x.abs() + p.y.abs() - (geom.0 + geom.1 + hw)) * INV_SQRT2;
72        dist = dist.max(chamfer);
73    }
74    dist
75}
76
77/// Signed distance to a circular band limited to an angular sweep — the shape
78/// behind both stroked arcs and filled annular sectors.
79pub fn sdf_arc_band(p: Point, arc: &ArcGeometry) -> f32 {
80    let ra = arc.mid_radius();
81    let rb = arc.half_thickness().max(0.0);
82    let sweep = arc.sweep_angle.clamp(0.0, cranpose_ui_graphics::TAU);
83    let half_sweep = sweep * 0.5;
84    let mid = arc.start_angle + half_sweep;
85
86    let (sm, cm) = mid.sin_cos();
87    let dx = p.x - arc.center.x;
88    let dy = p.y - arc.center.y;
89    let qx = (-sm * dx + cm * dy).abs();
90    let qy = cm * dx + sm * dy;
91
92    let sc = (half_sweep.sin().max(0.0), half_sweep.cos());
93
94    let mut dist = if sc.1 * qx > sc.0 * qy {
95        ((qx - sc.0 * ra).powi(2) + (qy - sc.1 * ra).powi(2)).sqrt() - rb
96    } else {
97        ((qx * qx + qy * qy).sqrt() - ra).abs() - rb
98    };
99
100    let plane = sc.1 * qx - sc.0 * qy;
101    match arc.cap {
102        StrokeCap::Butt => dist = dist.max(plane),
103        StrokeCap::Square => dist = dist.max(plane - rb),
104        StrokeCap::Round => {}
105    }
106    dist
107}
108
109/// Antialiased coverage for a signed distance, matching the shader's
110/// `1.0 - smoothstep(-0.5, 0.5, d)`.
111pub fn coverage_for_distance(distance: f32) -> f32 {
112    if !distance.is_finite() {
113        return 0.0;
114    }
115    let t = ((distance + 0.5).clamp(0.0, 1.0)) as f64;
116    let smooth = t * t * (3.0 - 2.0 * t);
117    (1.0 - smooth) as f32
118}
119
120/// Coverage of `point` by a stroked rect/round-rect whose (already inflated)
121/// bounds are `rect`.
122pub fn stroked_rect_coverage(
123    point: Point,
124    rect: Rect,
125    radii: Option<CornerRadii>,
126    half_width: f32,
127    join: StrokeJoin,
128) -> f32 {
129    let half_size = (rect.width * 0.5, rect.height * 0.5);
130    let local = Point::new(
131        point.x - (rect.x + half_size.0),
132        point.y - (rect.y + half_size.1),
133    );
134    let radii = radii.unwrap_or_default();
135    let distance = sdf_stroked_rounded_rect(
136        local,
137        half_size,
138        [
139            radii.top_left,
140            radii.top_right,
141            radii.bottom_left,
142            radii.bottom_right,
143        ],
144        half_width,
145        join,
146    );
147    coverage_for_distance(distance)
148}
149
150/// Coverage of `point` by an arc band.
151pub fn arc_coverage(point: Point, arc: &ArcGeometry) -> f32 {
152    coverage_for_distance(sdf_arc_band(point, arc))
153}
154
155#[cfg(test)]
156mod tests {
157    use std::f32::consts::{FRAC_PI_2, PI};
158
159    use cranpose_ui_graphics::TAU;
160
161    use super::*;
162
163    fn arc(inner: f32, outer: f32, start: f32, sweep: f32, cap: StrokeCap) -> ArcGeometry {
164        ArcGeometry::new(Point::ZERO, inner, outer, start, sweep, cap)
165    }
166
167    #[test]
168    fn rounded_rect_sdf_matches_known_distances() {
169        let d_center = sdf_rounded_rect(Point::ZERO, (10.0, 10.0), [0.0; 4]);
170        assert!((d_center + 10.0).abs() < 1e-4, "{d_center}");
171        let d_outside = sdf_rounded_rect(Point::new(15.0, 0.0), (10.0, 10.0), [0.0; 4]);
172        assert!((d_outside - 5.0).abs() < 1e-4, "{d_outside}");
173    }
174
175    #[test]
176    fn stroked_rect_covers_only_the_band_around_the_edge() {
177        let half = (12.0, 12.0);
178        let on_edge = sdf_stroked_rounded_rect(
179            Point::new(10.0, 0.0),
180            half,
181            [0.0; 4],
182            2.0,
183            StrokeJoin::Miter,
184        );
185        assert!(on_edge < 0.0, "the edge itself must be inside the stroke");
186        let inside =
187            sdf_stroked_rounded_rect(Point::new(4.0, 0.0), half, [0.0; 4], 2.0, StrokeJoin::Miter);
188        assert!(inside > 0.0, "the interior must be empty for a stroke");
189        let outside = sdf_stroked_rounded_rect(
190            Point::new(16.0, 0.0),
191            half,
192            [0.0; 4],
193            2.0,
194            StrokeJoin::Miter,
195        );
196        assert!(outside > 0.0, "well outside must be empty");
197    }
198
199    #[test]
200    fn miter_join_keeps_a_square_corner_round_join_does_not() {
201        let corner = Point::new(11.9, 11.9);
202        let miter =
203            sdf_stroked_rounded_rect(corner, (12.0, 12.0), [0.0; 4], 2.0, StrokeJoin::Miter);
204        let round =
205            sdf_stroked_rounded_rect(corner, (12.0, 12.0), [0.0; 4], 2.0, StrokeJoin::Round);
206        let bevel =
207            sdf_stroked_rounded_rect(corner, (12.0, 12.0), [0.0; 4], 2.0, StrokeJoin::Bevel);
208        assert!(miter < 0.0, "miter fills the corner point: {miter}");
209        assert!(round > 0.0, "round cuts the corner off: {round}");
210        assert!(bevel > 0.0, "bevel cuts the corner off: {bevel}");
211        assert!(
212            bevel > round,
213            "the bevel chord must cut deeper than the round arc: \
214             bevel={bevel} round={round}"
215        );
216    }
217
218    #[test]
219    fn full_ring_has_no_seam_at_the_wrap_point() {
220        let ring = arc(8.0, 12.0, 0.0, TAU, StrokeCap::Butt);
221        for step in 0..64 {
222            let angle = step as f32 / 64.0 * TAU;
223            let (sin, cos) = angle.sin_cos();
224            let p = Point::new(cos * 10.0, sin * 10.0);
225            let d = sdf_arc_band(p, &ring);
226            assert!(
227                d < 0.0,
228                "the ring centerline must be covered at angle {angle}: d={d}"
229            );
230        }
231    }
232
233    #[test]
234    fn butt_caps_cut_the_band_at_the_radial_ends() {
235        let band = arc(8.0, 12.0, 0.0, FRAC_PI_2, StrokeCap::Butt);
236        let inside = Point::new(10.0 * INV_SQRT2, 10.0 * INV_SQRT2);
237        assert!(sdf_arc_band(inside, &band) < 0.0);
238        let past_end = Point::new(-1.0, 10.0);
239        assert!(
240            sdf_arc_band(past_end, &band) > 0.0,
241            "butt cap must not bulge past the radial end"
242        );
243        let before_start = Point::new(10.0, -1.0);
244        assert!(sdf_arc_band(before_start, &band) > 0.0);
245    }
246
247    #[test]
248    fn round_caps_bulge_past_the_radial_ends_and_square_caps_project() {
249        let round = arc(8.0, 12.0, 0.0, FRAC_PI_2, StrokeCap::Round);
250        let square = arc(8.0, 12.0, 0.0, FRAC_PI_2, StrokeCap::Square);
251        let before_start = Point::new(10.0, -1.0);
252        assert!(
253            sdf_arc_band(before_start, &round) < 0.0,
254            "round cap must cover the semicircle past the end"
255        );
256        assert!(
257            sdf_arc_band(before_start, &square) < 0.0,
258            "square cap must cover the projection past the end"
259        );
260        let far = Point::new(10.0, -3.0);
261        assert!(sdf_arc_band(far, &round) > 0.0);
262        assert!(sdf_arc_band(far, &square) > 0.0);
263    }
264
265    #[test]
266    fn annular_sector_has_flat_radial_edges() {
267        let sector = arc(6.0, 12.0, 0.0, PI, StrokeCap::Butt);
268        for radius in [6.5, 8.0, 10.0, 11.5] {
269            let p = Point::new(radius * (0.01f32).cos(), radius * (0.01f32).sin());
270            assert!(
271                sdf_arc_band(p, &sector) < 0.0,
272                "radius {radius} just inside the sweep must be covered"
273            );
274            let q = Point::new(radius * (-0.2f32).cos(), radius * (-0.2f32).sin());
275            assert!(
276                sdf_arc_band(q, &sector) > 0.0,
277                "radius {radius} just outside the sweep must be empty"
278            );
279        }
280    }
281
282    #[test]
283    fn wedge_with_zero_inner_radius_reaches_the_center() {
284        let wedge = arc(0.0, 10.0, 0.0, FRAC_PI_2, StrokeCap::Butt);
285        assert!(sdf_arc_band(Point::new(0.5, 0.5), &wedge) < 0.0);
286        assert!(sdf_arc_band(Point::new(-0.5, -0.5), &wedge) > 0.0);
287    }
288
289    #[test]
290    fn degenerate_arcs_never_produce_nan_coverage() {
291        for geometry in [
292            arc(0.0, 0.0, 0.0, 0.0, StrokeCap::Butt),
293            arc(5.0, 5.0, 0.0, 1.0, StrokeCap::Round),
294            arc(0.0, 10.0, 0.0, 0.0, StrokeCap::Square),
295            ArcGeometry::new(Point::ZERO, f32::NAN, 1.0, 0.0, 1.0, StrokeCap::Butt),
296        ] {
297            for p in [Point::ZERO, Point::new(3.0, -4.0), Point::new(-9.0, 9.0)] {
298                let value = arc_coverage(p, &geometry);
299                assert!(value.is_finite(), "coverage must stay finite: {value}");
300                assert!((0.0..=1.0).contains(&value), "{value}");
301            }
302        }
303    }
304
305    #[test]
306    fn coverage_saturates_and_antialiases() {
307        assert_eq!(coverage_for_distance(-5.0), 1.0);
308        assert_eq!(coverage_for_distance(5.0), 0.0);
309        assert!((coverage_for_distance(0.0) - 0.5).abs() < 1e-5);
310        assert_eq!(coverage_for_distance(f32::NAN), 0.0);
311    }
312
313    #[test]
314    fn stroked_rect_coverage_uses_the_inflated_bounds() {
315        let bounds = Rect {
316            x: 8.0,
317            y: 8.0,
318            width: 24.0,
319            height: 24.0,
320        };
321        let on_edge =
322            stroked_rect_coverage(Point::new(10.0, 20.0), bounds, None, 2.0, StrokeJoin::Miter);
323        assert!(on_edge > 0.9, "the stroked edge must be opaque: {on_edge}");
324        let interior =
325            stroked_rect_coverage(Point::new(20.0, 20.0), bounds, None, 2.0, StrokeJoin::Miter);
326        assert_eq!(interior, 0.0, "a stroke must not fill its interior");
327    }
328}