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        // Miter/bevel keep a square corner square; an already-rounded corner
50        // has no join and keeps the true parallel offset.
51        for (out, r) in outer_radii.iter_mut().zip(radii.iter()) {
52            if *r < 0.0001 {
53                *out = 0.0;
54            }
55        }
56    }
57    let inner_radii = [
58        (radii[0] - hw).max(0.0),
59        (radii[1] - hw).max(0.0),
60        (radii[2] - hw).max(0.0),
61        (radii[3] - hw).max(0.0),
62    ];
63
64    let outer = sdf_rounded_rect(p, (geom.0 + hw, geom.1 + hw), outer_radii);
65    let inner = sdf_rounded_rect(
66        p,
67        ((geom.0 - hw).max(0.0), (geom.1 - hw).max(0.0)),
68        inner_radii,
69    );
70    let mut dist = outer.max(-inner);
71
72    if join == StrokeJoin::Bevel {
73        let chamfer = (p.x.abs() + p.y.abs() - (geom.0 + geom.1 + hw)) * INV_SQRT2;
74        dist = dist.max(chamfer);
75    }
76    dist
77}
78
79/// Signed distance to a circular band limited to an angular sweep — the shape
80/// behind both stroked arcs and filled annular sectors.
81pub fn sdf_arc_band(p: Point, arc: &ArcGeometry) -> f32 {
82    let ra = arc.mid_radius();
83    let rb = arc.half_thickness().max(0.0);
84    let sweep = arc.sweep_angle.clamp(0.0, cranpose_ui_graphics::TAU);
85    let half_sweep = sweep * 0.5;
86    let mid = arc.start_angle + half_sweep;
87
88    let (sm, cm) = mid.sin_cos();
89    let dx = p.x - arc.center.x;
90    let dy = p.y - arc.center.y;
91    // Rotate into the frame the analytic arc SDF expects: band straddling +Y.
92    let qx = (-sm * dx + cm * dy).abs();
93    let qy = cm * dx + sm * dy;
94
95    // sin() of a half sweep in [0, PI] is non-negative in exact math; the max()
96    // pins a full turn to exactly (0, -1) so a closed ring has no seam.
97    let sc = (half_sweep.sin().max(0.0), half_sweep.cos());
98
99    let mut dist = if sc.1 * qx > sc.0 * qy {
100        ((qx - sc.0 * ra).powi(2) + (qy - sc.1 * ra).powi(2)).sqrt() - rb
101    } else {
102        ((qx * qx + qy * qy).sqrt() - ra).abs() - rb
103    };
104
105    // Distance to the radial boundary plane, positive outside the wedge.
106    let plane = sc.1 * qx - sc.0 * qy;
107    match arc.cap {
108        StrokeCap::Butt => dist = dist.max(plane),
109        StrokeCap::Square => dist = dist.max(plane - rb),
110        StrokeCap::Round => {}
111    }
112    dist
113}
114
115/// Antialiased coverage for a signed distance, matching the shader's
116/// `1.0 - smoothstep(-0.5, 0.5, d)`.
117pub fn coverage_for_distance(distance: f32) -> f32 {
118    if !distance.is_finite() {
119        return 0.0;
120    }
121    let t = ((distance + 0.5).clamp(0.0, 1.0)) as f64;
122    let smooth = t * t * (3.0 - 2.0 * t);
123    (1.0 - smooth) as f32
124}
125
126/// Coverage of `point` by a stroked rect/round-rect whose (already inflated)
127/// bounds are `rect`.
128pub fn stroked_rect_coverage(
129    point: Point,
130    rect: Rect,
131    radii: Option<CornerRadii>,
132    half_width: f32,
133    join: StrokeJoin,
134) -> f32 {
135    let half_size = (rect.width * 0.5, rect.height * 0.5);
136    let local = Point::new(
137        point.x - (rect.x + half_size.0),
138        point.y - (rect.y + half_size.1),
139    );
140    let radii = radii.unwrap_or_default();
141    let distance = sdf_stroked_rounded_rect(
142        local,
143        half_size,
144        [
145            radii.top_left,
146            radii.top_right,
147            radii.bottom_left,
148            radii.bottom_right,
149        ],
150        half_width,
151        join,
152    );
153    coverage_for_distance(distance)
154}
155
156/// Coverage of `point` by an arc band.
157pub fn arc_coverage(point: Point, arc: &ArcGeometry) -> f32 {
158    coverage_for_distance(sdf_arc_band(point, arc))
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164    use cranpose_ui_graphics::TAU;
165    use std::f32::consts::{FRAC_PI_2, PI};
166
167    fn arc(inner: f32, outer: f32, start: f32, sweep: f32, cap: StrokeCap) -> ArcGeometry {
168        ArcGeometry::new(Point::ZERO, inner, outer, start, sweep, cap)
169    }
170
171    #[test]
172    fn rounded_rect_sdf_matches_known_distances() {
173        // A 20x20 box, no radii: the center is 10 inside, a point 5 to the
174        // right of the right edge is 5 outside.
175        let d_center = sdf_rounded_rect(Point::ZERO, (10.0, 10.0), [0.0; 4]);
176        assert!((d_center + 10.0).abs() < 1e-4, "{d_center}");
177        let d_outside = sdf_rounded_rect(Point::new(15.0, 0.0), (10.0, 10.0), [0.0; 4]);
178        assert!((d_outside - 5.0).abs() < 1e-4, "{d_outside}");
179    }
180
181    #[test]
182    fn stroked_rect_covers_only_the_band_around_the_edge() {
183        // Geometry is 20x20 (half 10), stroke width 4 => inflated half 12.
184        let half = (12.0, 12.0);
185        let on_edge = sdf_stroked_rounded_rect(
186            Point::new(10.0, 0.0),
187            half,
188            [0.0; 4],
189            2.0,
190            StrokeJoin::Miter,
191        );
192        assert!(on_edge < 0.0, "the edge itself must be inside the stroke");
193        let inside =
194            sdf_stroked_rounded_rect(Point::new(4.0, 0.0), half, [0.0; 4], 2.0, StrokeJoin::Miter);
195        assert!(inside > 0.0, "the interior must be empty for a stroke");
196        let outside = sdf_stroked_rounded_rect(
197            Point::new(16.0, 0.0),
198            half,
199            [0.0; 4],
200            2.0,
201            StrokeJoin::Miter,
202        );
203        assert!(outside > 0.0, "well outside must be empty");
204    }
205
206    #[test]
207    fn miter_join_keeps_a_square_corner_round_join_does_not() {
208        // Geometry 20x20 (half 10), width 4 (hw 2) => inflated half 12.
209        // The outer miter corner is exactly (12, 12).
210        let corner = Point::new(11.9, 11.9);
211        let miter =
212            sdf_stroked_rounded_rect(corner, (12.0, 12.0), [0.0; 4], 2.0, StrokeJoin::Miter);
213        let round =
214            sdf_stroked_rounded_rect(corner, (12.0, 12.0), [0.0; 4], 2.0, StrokeJoin::Round);
215        let bevel =
216            sdf_stroked_rounded_rect(corner, (12.0, 12.0), [0.0; 4], 2.0, StrokeJoin::Bevel);
217        assert!(miter < 0.0, "miter fills the corner point: {miter}");
218        assert!(round > 0.0, "round cuts the corner off: {round}");
219        assert!(bevel > 0.0, "bevel cuts the corner off: {bevel}");
220        // The bevel is the chord between the two arc endpoints, so along the
221        // diagonal it sits *inside* the round join's arc and cuts more.
222        assert!(
223            bevel > round,
224            "the bevel chord must cut deeper than the round arc: \
225             bevel={bevel} round={round}"
226        );
227    }
228
229    #[test]
230    fn full_ring_has_no_seam_at_the_wrap_point() {
231        let ring = arc(8.0, 12.0, 0.0, TAU, StrokeCap::Butt);
232        // Sample all the way round, including exactly at the wrap angle.
233        for step in 0..64 {
234            let angle = step as f32 / 64.0 * TAU;
235            let (sin, cos) = angle.sin_cos();
236            let p = Point::new(cos * 10.0, sin * 10.0);
237            let d = sdf_arc_band(p, &ring);
238            assert!(
239                d < 0.0,
240                "the ring centerline must be covered at angle {angle}: d={d}"
241            );
242        }
243    }
244
245    #[test]
246    fn butt_caps_cut_the_band_at_the_radial_ends() {
247        // 0 -> 90 degrees, band 8..12.
248        let band = arc(8.0, 12.0, 0.0, FRAC_PI_2, StrokeCap::Butt);
249        // Just inside the sweep at 45 degrees, on the centerline.
250        let inside = Point::new(10.0 * INV_SQRT2, 10.0 * INV_SQRT2);
251        assert!(sdf_arc_band(inside, &band) < 0.0);
252        // Just past the end cap (angle slightly > 90 degrees) must be empty.
253        let past_end = Point::new(-1.0, 10.0);
254        assert!(
255            sdf_arc_band(past_end, &band) > 0.0,
256            "butt cap must not bulge past the radial end"
257        );
258        // Just before the start cap likewise.
259        let before_start = Point::new(10.0, -1.0);
260        assert!(sdf_arc_band(before_start, &band) > 0.0);
261    }
262
263    #[test]
264    fn round_caps_bulge_past_the_radial_ends_and_square_caps_project() {
265        let round = arc(8.0, 12.0, 0.0, FRAC_PI_2, StrokeCap::Round);
266        let square = arc(8.0, 12.0, 0.0, FRAC_PI_2, StrokeCap::Square);
267        // 1 unit before the start angle, on the centerline (radius 10).
268        let before_start = Point::new(10.0, -1.0);
269        assert!(
270            sdf_arc_band(before_start, &round) < 0.0,
271            "round cap must cover the semicircle past the end"
272        );
273        assert!(
274            sdf_arc_band(before_start, &square) < 0.0,
275            "square cap must cover the projection past the end"
276        );
277        // 3 units before the start is past both caps (rb = 2).
278        let far = Point::new(10.0, -3.0);
279        assert!(sdf_arc_band(far, &round) > 0.0);
280        assert!(sdf_arc_band(far, &square) > 0.0);
281    }
282
283    #[test]
284    fn annular_sector_has_flat_radial_edges() {
285        // The defining property: at the start angle the boundary is a straight
286        // radial line, so points at the same angle but different radii are all
287        // exactly on the edge.
288        let sector = arc(6.0, 12.0, 0.0, PI, StrokeCap::Butt);
289        for radius in [6.5, 8.0, 10.0, 11.5] {
290            // Just inside the sweep.
291            let p = Point::new(radius * (0.01f32).cos(), radius * (0.01f32).sin());
292            assert!(
293                sdf_arc_band(p, &sector) < 0.0,
294                "radius {radius} just inside the sweep must be covered"
295            );
296            // Just outside the sweep (negative angle).
297            let q = Point::new(radius * (-0.2f32).cos(), radius * (-0.2f32).sin());
298            assert!(
299                sdf_arc_band(q, &sector) > 0.0,
300                "radius {radius} just outside the sweep must be empty"
301            );
302        }
303    }
304
305    #[test]
306    fn wedge_with_zero_inner_radius_reaches_the_center() {
307        let wedge = arc(0.0, 10.0, 0.0, FRAC_PI_2, StrokeCap::Butt);
308        assert!(sdf_arc_band(Point::new(0.5, 0.5), &wedge) < 0.0);
309        assert!(sdf_arc_band(Point::new(-0.5, -0.5), &wedge) > 0.0);
310    }
311
312    #[test]
313    fn degenerate_arcs_never_produce_nan_coverage() {
314        for geometry in [
315            arc(0.0, 0.0, 0.0, 0.0, StrokeCap::Butt),
316            arc(5.0, 5.0, 0.0, 1.0, StrokeCap::Round),
317            arc(0.0, 10.0, 0.0, 0.0, StrokeCap::Square),
318            ArcGeometry::new(Point::ZERO, f32::NAN, 1.0, 0.0, 1.0, StrokeCap::Butt),
319        ] {
320            for p in [Point::ZERO, Point::new(3.0, -4.0), Point::new(-9.0, 9.0)] {
321                let value = arc_coverage(p, &geometry);
322                assert!(value.is_finite(), "coverage must stay finite: {value}");
323                assert!((0.0..=1.0).contains(&value), "{value}");
324            }
325        }
326    }
327
328    #[test]
329    fn coverage_saturates_and_antialiases() {
330        assert_eq!(coverage_for_distance(-5.0), 1.0);
331        assert_eq!(coverage_for_distance(5.0), 0.0);
332        assert!((coverage_for_distance(0.0) - 0.5).abs() < 1e-5);
333        assert_eq!(coverage_for_distance(f32::NAN), 0.0);
334    }
335
336    #[test]
337    fn stroked_rect_coverage_uses_the_inflated_bounds() {
338        // Geometry (10,10)-(30,30) stroked at width 4 => bounds (8,8)-(32,32).
339        let bounds = Rect {
340            x: 8.0,
341            y: 8.0,
342            width: 24.0,
343            height: 24.0,
344        };
345        let on_edge =
346            stroked_rect_coverage(Point::new(10.0, 20.0), bounds, None, 2.0, StrokeJoin::Miter);
347        assert!(on_edge > 0.9, "the stroked edge must be opaque: {on_edge}");
348        let interior =
349            stroked_rect_coverage(Point::new(20.0, 20.0), bounds, None, 2.0, StrokeJoin::Miter);
350        assert_eq!(interior, 0.0, "a stroke must not fill its interior");
351    }
352}