Skip to main content

font_shape/
stroke.rs

1//! Stroke expansion: a stroke becomes an outline, then gets filled.
2//!
3//! Rasterizing a stroke directly means solving "distance to the path" per
4//! pixel, which is exact and slow. Expanding the stroke into the *region* it
5//! covers — one closed quad per segment, plus joins and caps — and filling
6//! that with the same scanline filler is the standard robust approach: one
7//! rasterizer, one set of edge cases, and correct behaviour with overlapping
8//! self-intersections under the non-zero rule.
9//!
10//! # What is expanded
11//!
12//! | Part | Contribution |
13//! |---|---|
14//! | segment | a quad from the two offset lines, both sides |
15//! | join ([`LineJoin::Miter`]) | a miter wedge, falling back to a bevel past the limit |
16//! | join ([`LineJoin::Round`]) | a fan around the vertex |
17//! | join ([`LineJoin::Bevel`]) | the triangle between the two offsets |
18//! | cap ([`LineCap::Butt`]) | nothing |
19//! | cap ([`LineCap::Square`]) | a quad extending `width / 2` past the endpoint |
20//! | cap ([`LineCap::Round`]) | a fan at the endpoint |
21//!
22//! Every emitted contour runs in the same rotational direction, so filling
23//! the union with [`FillRule::NonZero`](crate::FillRule::NonZero) is a union —
24//! which is exactly what a stroke is.
25
26use alloc::vec;
27use alloc::vec::Vec;
28
29use crate::path::{Path2D, PathCommand};
30
31/// How the ends of an open subpath are finished.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
33pub enum LineCap {
34    /// Stop exactly at the endpoint. The default, matching SVG.
35    #[default]
36    Butt,
37    /// Extend by half the stroke width, squared off.
38    Square,
39    /// Extend by half the stroke width, rounded.
40    Round,
41}
42
43/// How the corners between two segments are finished.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
45pub enum LineJoin {
46    /// Extend both sides until they meet, or bevel past the miter limit. The
47    /// default, matching SVG.
48    #[default]
49    Miter,
50    /// Cut the corner off with a straight edge.
51    Bevel,
52    /// Round the corner with an arc.
53    Round,
54}
55
56/// The default miter limit: a miter longer than this many stroke widths is
57/// beveled instead. Matches SVG's `stroke-miterlimit` default.
58pub const DEFAULT_MITER_LIMIT: f32 = 4.0;
59
60/// How much arc a round join or cap approximates its true circle with.
61const ARC_STEPS: usize = 12;
62
63/// A stroke's width, caps, joins, and miter limit.
64#[derive(Debug, Clone, Copy, PartialEq)]
65pub struct StrokeStyle {
66    /// The stroke width. A zero or negative width yields an empty path: there
67    /// is no region to fill.
68    pub width: f32,
69    /// The end treatment.
70    pub cap: LineCap,
71    /// The corner treatment.
72    pub join: LineJoin,
73    /// The longest miter, as a multiple of the stroke width.
74    pub miter_limit: f32,
75}
76
77impl Default for StrokeStyle {
78    fn default() -> Self {
79        StrokeStyle {
80            width: 1.0,
81            cap: LineCap::Butt,
82            join: LineJoin::Miter,
83            miter_limit: DEFAULT_MITER_LIMIT,
84        }
85    }
86}
87
88impl StrokeStyle {
89    /// A style with the given width and the default cap and join.
90    #[must_use]
91    pub const fn new(width: f32) -> Self {
92        StrokeStyle {
93            width,
94            cap: LineCap::Butt,
95            join: LineJoin::Miter,
96            miter_limit: DEFAULT_MITER_LIMIT,
97        }
98    }
99
100    /// Set the cap.
101    #[must_use]
102    pub const fn with_cap(mut self, cap: LineCap) -> Self {
103        self.cap = cap;
104        self
105    }
106
107    /// Set the join.
108    #[must_use]
109    pub const fn with_join(mut self, join: LineJoin) -> Self {
110        self.join = join;
111        self
112    }
113
114    /// Set the miter limit.
115    #[must_use]
116    pub const fn with_miter_limit(mut self, limit: f32) -> Self {
117        self.miter_limit = limit;
118        self
119    }
120}
121
122/// Expand a stroke into the outline of the region it covers.
123///
124/// ```
125/// use font_shape::{stroke_path, LineCap, PathBuilder, StrokeStyle};
126///
127/// let mut b = PathBuilder::new();
128/// b.move_to(0.0, 0.0);
129/// b.line_to(100.0, 0.0);
130/// let path = b.build();
131///
132/// // A butt-capped 10-wide horizontal stroke is a 100 x 10 rectangle.
133/// let s = stroke_path(&path, 10.0, StrokeStyle::new(10.0));
134/// let bbox = s.bbox().expect("bbox");
135/// assert_eq!(bbox.width(), 100.0);
136/// assert_eq!(bbox.height(), 10.0);
137///
138/// // A square cap extends each end by half the width.
139/// let c = stroke_path(&path, 10.0, StrokeStyle::new(10.0).with_cap(LineCap::Square));
140/// assert_eq!(c.bbox().expect("bbox").width(), 110.0);
141///
142/// // A zero width has no region at all.
143/// assert!(stroke_path(&path, 0.0, StrokeStyle::new(0.0)).is_empty());
144/// ```
145#[must_use]
146pub fn stroke_path(path: &Path2D, width: f32, style: StrokeStyle) -> Path2D {
147    let mut out = Path2D::new();
148    let hw = width * 0.5;
149    // A zero, negative, or non-finite width has no region to fill. SVG says a
150    // zero-width stroke renders as a hairline; that is a rasterisation
151    // convention, and this function expands geometry, so it reports the truth:
152    // nothing.
153    if !hw.is_finite() || hw <= 0.0 {
154        return out;
155    }
156    // Flatten once. A stroke's joins depend on the polygon's vertices, and the
157    // tolerance here is a fiftieth of the stroke's own half-width — far finer
158    // than any cap or join needs.
159    //
160    // The closedness comes from the *source* subpath, not from the flattened
161    // points: `flatten` appends an implicit closing point to open subpaths too,
162    // and treating that as a `Close` would put a join where a cap belongs.
163    for poly in path.flatten_polylines(hw * 0.05) {
164        // Both branches drop the repeated closing point. For a closed subpath
165        // that is bookkeeping; for an open one the implicit closing segment is
166        // *not* part of the stroke, and keeping it is what would put a join
167        // where a cap belongs.
168        let pts: Vec<(f32, f32)> = match poly.points.split_last() {
169            Some((last, head)) if head.len() > 1 && poly.points.first() == Some(last) => {
170                head.to_vec()
171            }
172            _ => poly.points,
173        };
174        if pts.len() < 2 {
175            continue;
176        }
177        let mut seg = StrokeEmitter {
178            out: &mut out,
179            hw,
180            style,
181        };
182        seg.emit(&pts, poly.closed);
183    }
184    out
185}
186
187/// Emits the quads, joins, and caps of one polyline.
188struct StrokeEmitter<'a> {
189    out: &'a mut Path2D,
190    hw: f32,
191    style: StrokeStyle,
192}
193
194impl StrokeEmitter<'_> {
195    /// One quad per segment, plus joins between them and caps at the ends.
196    fn emit(&mut self, pts: &[(f32, f32)], closed: bool) {
197        let n = pts.len();
198        let last = if closed { n } else { n - 1 };
199        let at = |i: usize| -> Option<(f32, f32)> { pts.get(i % n).copied() };
200        for i in 0..last {
201            let (Some(a), Some(b)) = (at(i), at(i + 1)) else {
202                continue;
203            };
204            if a == b {
205                // A zero-length segment contributes no region, and no join.
206                continue;
207            }
208            let (na, nb) = (normal(a, b, self.hw), normal(a, b, -self.hw));
209            self.quad(
210                (a.0 + na.0, a.1 + na.1),
211                (b.0 + na.0, b.1 + na.1),
212                (b.0 + nb.0, b.1 + nb.1),
213                (a.0 + nb.0, a.1 + nb.1),
214            );
215        }
216        // Joins. A closed subpath has one at every vertex; an open one only at its
217        // *interior* vertices, since its two ends get caps instead. Joining at
218        // an open end is not cosmetic: the "previous" vertex would wrap around
219        // to the far end of the polyline, filling a wedge nowhere near the cap.
220        let first_join = if closed { 0 } else { 1 };
221        let last_join = if closed { n } else { n - 1 };
222        for i in first_join..last_join {
223            let (Some(prev), Some(here), Some(next)) = (at(i + n - 1), at(i), at(i + 1)) else {
224                continue;
225            };
226            self.join(prev, here, next);
227        }
228        if !closed {
229            match self.style.cap {
230                LineCap::Butt => {}
231                LineCap::Square | LineCap::Round => {
232                    let round = matches!(self.style.cap, LineCap::Round);
233                    let (Some(first), Some(second)) = (pts.first().copied(), pts.get(1).copied())
234                    else {
235                        return;
236                    };
237                    let (Some(last), Some(prev)) = (pts.last().copied(), pts.get(n - 2).copied())
238                    else {
239                        return;
240                    };
241                    if round {
242                        self.cap_round(first, second);
243                        self.cap_round(last, prev);
244                    } else {
245                        self.cap_square(first, second);
246                        self.cap_square(last, prev);
247                    }
248                }
249            }
250        }
251    }
252
253    /// A closed quad, emitted in a consistent rotational direction.
254    fn quad(&mut self, a: (f32, f32), b: (f32, f32), c: (f32, f32), d: (f32, f32)) {
255        self.out.push(PathCommand::MoveTo(a.0, a.1));
256        self.out.push(PathCommand::LineTo(b.0, b.1));
257        self.out.push(PathCommand::LineTo(c.0, c.1));
258        self.out.push(PathCommand::LineTo(d.0, d.1));
259        self.out.push(PathCommand::Close);
260    }
261
262    /// A closed triangle.
263    fn triangle(&mut self, a: (f32, f32), b: (f32, f32), c: (f32, f32)) {
264        self.out.push(PathCommand::MoveTo(a.0, a.1));
265        self.out.push(PathCommand::LineTo(b.0, b.1));
266        self.out.push(PathCommand::LineTo(c.0, c.1));
267        self.out.push(PathCommand::Close);
268    }
269
270    /// The join at `here`, between the segment arriving from `prev` and the one
271    /// leaving toward `next`.
272    fn join(&mut self, prev: (f32, f32), here: (f32, f32), next: (f32, f32)) {
273        let (Some(in_dir), Some(out_dir)) = (
274            norm((here.0 - prev.0, here.1 - prev.1)),
275            norm((next.0 - here.0, next.1 - here.1)),
276        ) else {
277            return;
278        };
279        // The cross product's sign says which way the path turns; the normal
280        // offsets then cross over or splay apart.
281        let cross = in_dir.0 * out_dir.1 - in_dir.1 * out_dir.0;
282        if cross.abs() < 1e-9 {
283            // Collinear: the two quads already meet, nothing to fill.
284            return;
285        }
286        let n_in = (in_dir.1 * self.hw, -in_dir.0 * self.hw);
287        let n_out = (out_dir.1 * self.hw, -out_dir.0 * self.hw);
288        let side_in = (here.0 + n_in.0, here.1 + n_in.1);
289        let side_out = (here.0 + n_out.0, here.1 + n_out.1);
290        match self.style.join {
291            LineJoin::Bevel => self.triangle(here, side_in, side_out),
292            LineJoin::Round => self.fan(here, side_in, side_out, cross),
293            LineJoin::Miter => {
294                // The miter length is `hw / cos(θ/2)`, so the limit compares
295                // the miter's length against `hw / miter_limit`.
296                let dot = in_dir.0 * out_dir.0 + in_dir.1 * out_dir.1;
297                let half_cos = libm::sqrtf((1.0 + dot) * 0.5).max(1e-6);
298                let ratio = 1.0 / half_cos;
299                if ratio > self.style.miter_limit.max(1.0) {
300                    // Past the limit: SVG's fallback is a bevel.
301                    self.triangle(here, side_in, side_out);
302                } else {
303                    // The miter point is where the two *offset lines* meet, so
304                    // it lies along the bisector of the two normals — not of
305                    // the two directions, which points into the corner's
306                    // interior and would produce a zero-area wedge.
307                    let Some(n) = norm((n_in.0 + n_out.0, n_in.1 + n_out.1)) else {
308                        self.triangle(here, side_in, side_out);
309                        return;
310                    };
311                    let miter = (
312                        here.0 + n.0 * self.hw * ratio,
313                        here.1 + n.1 * self.hw * ratio,
314                    );
315                    self.quad(here, side_in, miter, side_out);
316                }
317            }
318        }
319    }
320
321    /// A round fan from `from` to `to` around `centre`.
322    fn fan(&mut self, centre: (f32, f32), from: (f32, f32), to: (f32, f32), sign: f32) {
323        let a0 = libm::atan2f(from.1 - centre.1, from.0 - centre.0);
324        let a1 = libm::atan2f(to.1 - centre.1, to.0 - centre.0);
325        // Sweep the short way round, in the direction `sign` names.
326        let mut delta = a1 - a0;
327        while delta <= -core::f32::consts::PI {
328            delta += 2.0 * core::f32::consts::PI;
329        }
330        while delta > core::f32::consts::PI {
331            delta -= 2.0 * core::f32::consts::PI;
332        }
333        let steps = ARC_STEPS.max(2);
334        self.out.push(PathCommand::MoveTo(centre.0, centre.1));
335        for i in 0..=steps {
336            let t = a0 + delta * (i as f32) / (steps as f32);
337            let (s, c) = (libm::sinf(t), libm::cosf(t));
338            let p = (centre.0 + c * self.hw, centre.1 + s * self.hw);
339            self.out.push(PathCommand::LineTo(p.0, p.1));
340        }
341        self.out.push(PathCommand::Close);
342        let _ = sign;
343    }
344
345    /// A square cap at `end`, extending half a width along the segment.
346    fn cap_square(&mut self, end: (f32, f32), toward: (f32, f32)) {
347        let Some(d) = norm((end.0 - toward.0, end.1 - toward.1)) else {
348            return;
349        };
350        // The cap is a rectangle `hw` past the endpoint, `width` wide: two of its
351        // corners are the endpoint's own offsets and two the same offsets
352        // pushed out along `d`. `d` points *away* from the path at both ends,
353        // so the same corner order winds the same way at both — which is what
354        // makes the non-zero union correct.
355        let n = (d.1 * self.hw, -d.0 * self.hw);
356        let a = (end.0 + n.0, end.1 + n.1);
357        let b = (end.0 - n.0, end.1 - n.1);
358        let far_a = (a.0 + d.0 * self.hw, a.1 + d.1 * self.hw);
359        let far_b = (b.0 + d.0 * self.hw, b.1 + d.1 * self.hw);
360        self.quad(a, far_a, far_b, b);
361    }
362
363    /// A round cap at `end`: a half-disc.
364    fn cap_round(&mut self, end: (f32, f32), toward: (f32, f32)) {
365        let Some(d) = norm((end.0 - toward.0, end.1 - toward.1)) else {
366            return;
367        };
368        let n = (d.1 * self.hw, -d.0 * self.hw);
369        let a = (end.0 + n.0, end.1 + n.1);
370        let b = (end.0 - n.0, end.1 - n.1);
371        // `d` points away from the path at both ends, so sweeping from `a` to
372        // `b` the positive way round always goes through the outer half — the
373        // same direction at both ends, which keeps the union non-zero.
374        self.arc(end, a, b);
375    }
376
377    /// A fan from `from` to `to` around `centre`, swept counter-clockwise.
378    fn arc(&mut self, centre: (f32, f32), from: (f32, f32), to: (f32, f32)) {
379        let a0 = libm::atan2f(from.1 - centre.1, from.0 - centre.0);
380        let a1 = libm::atan2f(to.1 - centre.1, to.0 - centre.0);
381        let mut delta = a1 - a0;
382        // Normalise into (0, 2π]: a fan that swept the short way would put the
383        // wrong half of the disc on the stroke.
384        while delta <= 0.0 {
385            delta += 2.0 * core::f32::consts::PI;
386        }
387        while delta > 2.0 * core::f32::consts::PI {
388            delta -= 2.0 * core::f32::consts::PI;
389        }
390        let steps = ARC_STEPS.max(2);
391        self.out.push(PathCommand::MoveTo(centre.0, centre.1));
392        for i in 0..=steps {
393            let t = a0 + delta * (i as f32) / (steps as f32);
394            let (s, c) = (libm::sinf(t), libm::cosf(t));
395            let p = (centre.0 + c * self.hw, centre.1 + s * self.hw);
396            self.out.push(PathCommand::LineTo(p.0, p.1));
397        }
398        self.out.push(PathCommand::Close);
399    }
400}
401
402/// The unit normal to the direction `d`, scaled by `hw`, on one side.
403///
404/// `side` is `+hw` or `-hw`, giving the two offset lines of a segment.
405fn normal(from: (f32, f32), to: (f32, f32), side: f32) -> (f32, f32) {
406    let dx = to.0 - from.0;
407    let dy = to.1 - from.1;
408    let len = libm::sqrtf(dx * dx + dy * dy);
409    if len <= 1e-9 {
410        return (0.0, 0.0);
411    }
412    let ux = dx / len;
413    let uy = dy / len;
414    (uy * side, -ux * side)
415}
416
417/// A unit vector along `d`, `None` for a zero-length direction.
418fn norm(d: (f32, f32)) -> Option<(f32, f32)> {
419    let len = libm::sqrtf(d.0 * d.0 + d.1 * d.1);
420    if len <= 1e-9 || !len.is_finite() {
421        return None;
422    }
423    Some((d.0 / len, d.1 / len))
424}
425
426/// Reverse every subpath of a command list, keeping the geometry.
427///
428/// Used by [`Path2D::reverse`](crate::Path2D::reverse) and shared with the
429/// tests: a segment's reversal swaps its endpoints and reverses its controls,
430/// and a subpath's segments come out in the opposite order.
431#[must_use]
432pub(crate) fn reverse_commands(commands: &[PathCommand]) -> Vec<PathCommand> {
433    /// One segment: its kind, its control points, and its on-curve endpoint.
434    struct Seg {
435        kind: u8,
436        c1: (f32, f32),
437        c2: (f32, f32),
438        to: (f32, f32),
439    }
440    /// A subpath under construction: on-curve points, segments, and whether
441    /// it was explicitly closed.
442    type Sub = (Vec<(f32, f32)>, Vec<Seg>, bool);
443    /// The same, minus the closed flag, which is only known at `Close`.
444    type Open = (Vec<(f32, f32)>, Vec<Seg>);
445
446    let mut out: Vec<PathCommand> = Vec::with_capacity(commands.len());
447    let mut subs: Vec<Sub> = Vec::new();
448    let mut cur: Option<Open> = None;
449    for cmd in commands {
450        match *cmd {
451            PathCommand::MoveTo(x, y) => {
452                if let Some(sp) = cur.take() {
453                    subs.push((sp.0, sp.1, false));
454                }
455                cur = Some((vec![(x, y)], Vec::new()));
456            }
457            PathCommand::LineTo(x, y) => {
458                if let Some(sp) = cur.as_mut() {
459                    sp.1.push(Seg {
460                        kind: 1,
461                        c1: (0.0, 0.0),
462                        c2: (0.0, 0.0),
463                        to: (x, y),
464                    });
465                    sp.0.push((x, y));
466                }
467            }
468            PathCommand::QuadTo(cx, cy, x, y) => {
469                if let Some(sp) = cur.as_mut() {
470                    sp.1.push(Seg {
471                        kind: 2,
472                        c1: (cx, cy),
473                        c2: (0.0, 0.0),
474                        to: (x, y),
475                    });
476                    sp.0.push((x, y));
477                }
478            }
479            PathCommand::CubicTo(c1x, c1y, c2x, c2y, x, y) => {
480                if let Some(sp) = cur.as_mut() {
481                    sp.1.push(Seg {
482                        kind: 3,
483                        c1: (c1x, c1y),
484                        c2: (c2x, c2y),
485                        to: (x, y),
486                    });
487                    sp.0.push((x, y));
488                }
489            }
490            PathCommand::Close => {
491                if let Some(sp) = cur.take() {
492                    subs.push((sp.0, sp.1, true));
493                }
494            }
495        }
496    }
497    if let Some(sp) = cur.take() {
498        subs.push((sp.0, sp.1, false));
499    }
500    for (points, segs, closed) in subs {
501        let Some(first) = points.first().copied() else {
502            continue;
503        };
504        if segs.is_empty() {
505            // A subpath with no segments — a lone `MoveTo`, which is a point
506            // with no extent. It has no direction to flip, but it is still a
507            // point the path's bounding box covers, so dropping it would make
508            // reversal change the geometry.
509            out.push(PathCommand::MoveTo(first.0, first.1));
510            if closed {
511                out.push(PathCommand::Close);
512            }
513            continue;
514        }
515        let begin = segs.last().map_or(first, |s| s.to);
516        out.push(PathCommand::MoveTo(begin.0, begin.1));
517        for (i, s) in segs.iter().enumerate().rev() {
518            let to = match i.checked_sub(1).and_then(|k| segs.get(k)) {
519                Some(prev) => prev.to,
520                None => first,
521            };
522            match s.kind {
523                1 => out.push(PathCommand::LineTo(to.0, to.1)),
524                2 => out.push(PathCommand::QuadTo(s.c1.0, s.c1.1, to.0, to.1)),
525                _ => out.push(PathCommand::CubicTo(
526                    s.c2.0, s.c2.1, s.c1.0, s.c1.1, to.0, to.1,
527                )),
528            }
529        }
530        if closed {
531            out.push(PathCommand::Close);
532        }
533    }
534    out
535}
536
537#[cfg(test)]
538mod tests {
539    #![allow(
540        clippy::unwrap_used,
541        clippy::expect_used,
542        clippy::panic,
543        clippy::indexing_slicing,
544        clippy::float_cmp
545    )]
546    use super::{stroke_path, LineCap, LineJoin, StrokeStyle};
547    use crate::path::{PathBuilder, PathCommand};
548    use crate::FillRule;
549
550    // Test harness: assertions legitimately panic; the lib target stays
551    // lint-clean.
552
553    fn close(a: f32, b: f32) -> bool {
554        (a - b).abs() < 1e-3
555    }
556
557    /// Total coverage of a stroke, as a fraction of full ink.
558    fn ink(path: &crate::Path2D, size: u32) -> f32 {
559        let mask = crate::fill_path(path, FillRule::NonZero, size, size).expect("fills");
560        mask.iter().map(|&v| f32::from(v)).sum::<f32>() / (255.0 * (size * size) as f32)
561    }
562
563    fn line(from: (f32, f32), to: (f32, f32)) -> crate::Path2D {
564        let mut b = PathBuilder::new();
565        b.move_to(from.0, from.1);
566        b.line_to(to.0, to.1);
567        b.build()
568    }
569
570    #[test]
571    fn zero_width_stroke_has_no_region() {
572        let p = line((10.0, 10.0), (50.0, 10.0));
573        for w in [0.0, -1.0, -0.001] {
574            let s = stroke_path(&p, w, StrokeStyle::new(w));
575            assert!(s.is_empty(), "width {w} produced {} commands", s.len());
576        }
577        // A non-finite width likewise.
578        assert!(stroke_path(&p, f32::NAN, StrokeStyle::default()).is_empty());
579        assert!(stroke_path(&p, f32::INFINITY, StrokeStyle::default()).is_empty());
580    }
581
582    #[test]
583    fn hairline_is_a_thin_but_nonzero_region() {
584        // A 0.01-wide stroke is the practical "hairline": a real region, so
585        // the difference from zero is visible.
586        let p = line((10.0, 10.0), (50.0, 10.0));
587        let s = stroke_path(&p, 0.01, StrokeStyle::new(0.01));
588        assert!(!s.is_empty());
589        let b = s.bbox().expect("bbox");
590        assert!(close(b.height(), 0.01), "height {}", b.height());
591        assert!(close(b.width(), 40.0));
592    }
593
594    #[test]
595    fn butt_cap_stops_at_the_endpoint() {
596        let p = line((20.0, 50.0), (80.0, 50.0));
597        let s = stroke_path(&p, 10.0, StrokeStyle::new(10.0).with_cap(LineCap::Butt));
598        let b = s.bbox().expect("bbox");
599        assert_eq!(b.min_x, 20.0);
600        assert_eq!(b.max_x, 80.0);
601        assert_eq!(b.min_y, 45.0);
602        assert_eq!(b.max_y, 55.0);
603    }
604
605    #[test]
606    fn square_cap_extends_by_half_the_width() {
607        let p = line((20.0, 50.0), (80.0, 50.0));
608        let s = stroke_path(&p, 10.0, StrokeStyle::new(10.0).with_cap(LineCap::Square));
609        let b = s.bbox().expect("bbox");
610        assert_eq!(b.min_x, 15.0);
611        assert_eq!(b.max_x, 85.0);
612        // Still the same thickness across the body.
613        assert_eq!(b.height(), 10.0);
614    }
615
616    #[test]
617    fn round_cap_extends_by_exactly_half_the_width() {
618        let p = line((30.0, 50.0), (70.0, 50.0));
619        let s = stroke_path(&p, 10.0, StrokeStyle::new(10.0).with_cap(LineCap::Round));
620        let b = s.bbox().expect("bbox");
621        // The cap is an `ARC_STEPS`-gon inscribed in the true half-disc, so it
622        // reaches exactly `hw` along the segment's axis — the first and last
623        // arc steps lie on the axis — and falls short of `hw` by the diagonal.
624        assert!(close(b.min_x, 25.0), "min_x {}", b.min_x);
625        assert!(close(b.max_x, 75.0), "max_x {}", b.max_x);
626        assert_eq!(b.height(), 10.0, "the cap is as wide as the stroke");
627        // A square cap is the same length, so the two agree at the extremes.
628        let sq = stroke_path(&p, 10.0, StrokeStyle::new(10.0).with_cap(LineCap::Square));
629        assert_eq!(sq.bbox(), Some(b));
630    }
631
632    #[test]
633    fn diagonal_stroke_thickness_is_the_width() {
634        // A butt-capped 45-degree stroke of width w is bounded by the segment's
635        // endpoints offset by the half-width perpendicular, which at 45° is
636        // hw·cos(45°) = w / (2√2) in each axis.
637        let p = line((0.0, 0.0), (100.0, 100.0));
638        let s = stroke_path(&p, 10.0, StrokeStyle::new(10.0));
639        let b = s.bbox().expect("bbox");
640        let expected = 5.0 / core::f32::consts::SQRT_2;
641        assert!(
642            close(b.min_x, -expected) && close(b.min_y, -expected),
643            "{b:?}"
644        );
645        assert!(close(b.max_x, 100.0 + expected), "{b:?}");
646        assert!(close(b.max_y, 100.0 + expected), "{b:?}");
647    }
648
649    #[test]
650    fn miter_join_extends_a_right_angle_to_the_miter_limit() {
651        // An L: the miter at the corner reaches hw·sqrt(2) for a 90° turn.
652        let mut b = PathBuilder::new();
653        b.move_to(0.0, 0.0);
654        b.line_to(50.0, 0.0);
655        b.line_to(50.0, 50.0);
656        let p = b.build();
657        let s = stroke_path(&p, 10.0, StrokeStyle::new(10.0).with_join(LineJoin::Miter));
658        let bb = s.bbox().expect("bbox");
659        // The miter point is where the two offset lines meet: `hw·sqrt(2)`
660        // beyond the corner along the bisector, which at a right angle lands
661        // at (55, -5).
662        assert!(close(bb.max_x, 55.0), "{bb:?}");
663        assert!(close(bb.min_y, -5.0), "{bb:?}");
664        assert!(close(bb.min_x, 0.0) && close(bb.max_y, 50.0), "{bb:?}");
665        // A bevel stops at the offset endpoints instead: it cuts the corner
666        // off, so it covers strictly less area. That difference is the
667        // miter's whole point.
668        let bevel = stroke_path(&p, 10.0, StrokeStyle::new(10.0).with_join(LineJoin::Bevel));
669        let bvb = bevel.bbox().expect("bbox");
670        assert!(close(bvb.max_x, 55.0) && close(bvb.min_y, -5.0), "{bvb:?}");
671        let miter_area = s.polygon_area();
672        let bevel_area = bevel.polygon_area();
673        assert!(
674            miter_area > bevel_area,
675            "miter {miter_area} vs bevel {bevel_area}"
676        );
677        // The gap is the right triangle between the bevel's chord and the
678        // miter's point: `hw² − hw² / √2` ≈ 12.5.
679        assert!(
680            (miter_area - bevel_area - 12.5).abs() < 0.5,
681            "gap {}",
682            miter_area - bevel_area
683        );
684    }
685
686    #[test]
687    fn miter_limit_exceeded_falls_back_to_a_bevel() {
688        // A very sharp spike: the miter would be enormous, so the bevel is used.
689        let mut b = PathBuilder::new();
690        b.move_to(0.0, 0.0);
691        b.line_to(100.0, 0.0);
692        b.line_to(50.0, 1.0); // a near-180° reversal
693        let p = b.build();
694
695        let bevel = stroke_path(&p, 4.0, StrokeStyle::new(4.0).with_join(LineJoin::Bevel));
696        let tight = stroke_path(
697            &p,
698            4.0,
699            StrokeStyle::new(4.0)
700                .with_join(LineJoin::Miter)
701                .with_miter_limit(1.5),
702        );
703        // Past the limit the miter join *is* the bevel join.
704        assert_eq!(
705            tight.commands(),
706            bevel.commands(),
707            "a 1.5 limit bevels this spike"
708        );
709        // With a generous limit the two differ.
710        let loose = stroke_path(&p, 4.0, StrokeStyle::new(4.0).with_miter_limit(1000.0));
711        assert_ne!(loose.commands(), bevel.commands());
712    }
713
714    #[test]
715    fn bevel_join_matches_miter_below_the_limit() {
716        // A gentle turn: both produce the same region, since the miter is
717        // within the default limit.
718        let mut b = PathBuilder::new();
719        b.move_to(0.0, 0.0);
720        b.line_to(50.0, 0.0);
721        b.line_to(100.0, 20.0);
722        let p = b.build();
723        let miter = stroke_path(&p, 6.0, StrokeStyle::new(6.0).with_join(LineJoin::Miter));
724        let bevel = stroke_path(&p, 6.0, StrokeStyle::new(6.0).with_join(LineJoin::Bevel));
725        // Same coverage to within a fraction of a percent.
726        let a = ink(&miter, 128);
727        let c = ink(&bevel, 128);
728        assert!((a - c).abs() < 0.005, "miter {a} vs bevel {c}");
729    }
730
731    #[test]
732    fn joins_cover_different_amounts_at_a_corner() {
733        // The corner is placed well inside the raster: a stroke's bounding box
734        // extends past the path, and ink measured on a path that hangs off the
735        // edge is clipped, which would hide the very differences under test.
736        let mut b = PathBuilder::new();
737        b.move_to(30.0, 30.0);
738        b.line_to(80.0, 30.0);
739        b.line_to(80.0, 80.0);
740        let p = b.build();
741        let miter = stroke_path(&p, 10.0, StrokeStyle::new(10.0).with_join(LineJoin::Miter));
742        let round = stroke_path(&p, 10.0, StrokeStyle::new(10.0).with_join(LineJoin::Round));
743        let bevel = stroke_path(&p, 10.0, StrokeStyle::new(10.0).with_join(LineJoin::Bevel));
744
745        // A quarter-disc is π·hw²/4 ≈ 19.6; the bevel's triangle is hw²/2 = 12.5;
746        // the miter's wedge is hw² − hw²/√2 ≈ 12.5 as well but in a different
747        // place. The bevel is the smallest of the three.
748        assert!(ink(&round, 256) > ink(&bevel, 256), "round vs bevel");
749        assert!(ink(&miter, 256) > ink(&bevel, 256), "miter vs bevel");
750        // Round and miter differ by a few square units out of ~1000, which at
751        // a 256² raster is well under a tenth of a percent of the frame — so
752        // compare the areas, not the frame-normalised ink.
753        let miter_area = miter.polygon_area();
754        assert!(
755            (round.polygon_area() - miter_area).abs() > 1.0,
756            "round and miter differ"
757        );
758        // The two segment quads contribute 2 · 50 · 10 = 1000, so what is left
759        // is the join itself. A round join's fan covers a quarter-disc, less
760        // the triangle its two chords already share with the quads — and the
761        // fan's twelve chords make it slightly smaller again, which is what
762        // pins ARC_STEPS.
763        let round_join = round.polygon_area() - 1000.0;
764        let quarter_disc = core::f32::consts::FRAC_PI_4 * 25.0;
765        assert!(
766            (round_join - quarter_disc).abs() < 0.5,
767            "round join area {round_join} vs quarter-disc {quarter_disc}"
768        );
769        // And the bevel's is the triangle, which is smaller.
770        let bevel_join = bevel.polygon_area() - 1000.0;
771        assert!(
772            (bevel_join - 12.5).abs() < 0.5,
773            "bevel join area {bevel_join} vs triangle 12.5"
774        );
775    }
776
777    #[test]
778    fn collinear_join_adds_nothing() {
779        let mut b = PathBuilder::new();
780        b.move_to(0.0, 0.0);
781        b.line_to(50.0, 0.0);
782        b.line_to(100.0, 0.0);
783        let p = b.build();
784        let s = stroke_path(&p, 10.0, StrokeStyle::new(10.0));
785        let bb = s.bbox().expect("bbox");
786        assert_eq!(bb.min_y, -5.0);
787        assert_eq!(bb.max_y, 5.0);
788    }
789
790    #[test]
791    fn closed_subpath_strokes_the_whole_ring() {
792        let mut b = PathBuilder::new();
793        b.rect(20.0, 20.0, 60.0, 60.0);
794        let p = b.build();
795        let s = stroke_path(&p, 6.0, StrokeStyle::new(6.0));
796        let bb = s.bbox().expect("bbox");
797        // Outward by half the width on every side, plus the mitered corners.
798        assert!(bb.min_x <= 17.0 && bb.max_x >= 83.0, "{bb:?}");
799        // A closed ring has no caps, so it does not extend past the miter.
800        let round = stroke_path(&p, 6.0, StrokeStyle::new(6.0).with_join(LineJoin::Round));
801        let rb = round.bbox().expect("bbox");
802        assert!(close(rb.min_x, 17.0) && close(rb.max_x, 83.0), "{rb:?}");
803    }
804
805    #[test]
806    fn stroke_ink_is_length_times_width() {
807        // A 100-long, 10-wide horizontal stroke covers 1000 square units.
808        let p = line((20.0, 50.0), (120.0, 50.0));
809        let s = stroke_path(&p, 10.0, StrokeStyle::new(10.0));
810        let area = s.polygon_area();
811        assert!((area - 1000.0).abs() < 2.0, "polygon area {area} vs 1000");
812        // The rendered mask agrees to within a percent at a fine resolution.
813        let mut b = PathBuilder::new();
814        b.extend(&s.translated(0.0, 0.0));
815        let total = ink(&b.build(), 512);
816        let expect = 1000.0 / (512.0 * 512.0);
817        assert!(
818            (total - expect).abs() < expect * 0.01,
819            "mask ink {total} vs {expect}"
820        );
821    }
822
823    #[test]
824    fn zero_length_segment_contributes_nothing() {
825        let mut b = PathBuilder::new();
826        b.move_to(10.0, 10.0);
827        b.line_to(10.0, 10.0);
828        b.line_to(50.0, 10.0);
829        let p = b.build();
830        let s = stroke_path(&p, 10.0, StrokeStyle::new(10.0));
831        let bb = s.bbox().expect("bbox");
832        assert_eq!(bb.min_x, 10.0, "the zero segment adds no cap");
833        assert_eq!(bb.max_x, 50.0);
834    }
835
836    #[test]
837    fn degenerate_paths_do_not_panic() {
838        // An empty path.
839        assert!(stroke_path(&crate::Path2D::new(), 5.0, StrokeStyle::default()).is_empty());
840        // A lone point.
841        let mut b = PathBuilder::new();
842        b.move_to(5.0, 5.0);
843        let p = b.build();
844        assert!(stroke_path(&p, 5.0, StrokeStyle::default()).is_empty());
845        // Two identical points.
846        let mut b = PathBuilder::new();
847        b.move_to(5.0, 5.0);
848        b.line_to(5.0, 5.0);
849        b.close();
850        assert!(stroke_path(&b.build(), 5.0, StrokeStyle::default()).is_empty());
851    }
852
853    #[test]
854    fn style_builders() {
855        let s = StrokeStyle::default();
856        assert_eq!(s.width, 1.0);
857        assert_eq!(s.cap, LineCap::Butt);
858        assert_eq!(s.join, LineJoin::Miter);
859        assert_eq!(s.miter_limit, super::DEFAULT_MITER_LIMIT);
860        let s = StrokeStyle::new(3.0)
861            .with_cap(LineCap::Round)
862            .with_join(LineJoin::Round)
863            .with_miter_limit(2.0);
864        assert_eq!(s.width, 3.0);
865        assert_eq!(s.cap, LineCap::Round);
866        assert_eq!(s.join, LineJoin::Round);
867        assert_eq!(s.miter_limit, 2.0);
868    }
869
870    #[test]
871    fn reverse_commands_helper() {
872        let mut b = PathBuilder::new();
873        b.move_to(0.0, 0.0);
874        b.line_to(10.0, 0.0);
875        b.line_to(10.0, 10.0);
876        b.close();
877        let before = b.build();
878        let reversed = super::reverse_commands(before.commands());
879        let mut after = before.clone();
880        after.reverse();
881        assert_eq!(reversed, after.commands());
882        // Reversing an empty list is empty.
883        assert!(super::reverse_commands(&[]).is_empty());
884    }
885
886    #[test]
887    fn emitted_contours_all_close() {
888        // Every subpath a stroke emits is closed, which is what makes the
889        // non-zero union correct.
890        let mut b = PathBuilder::new();
891        b.move_to(10.0, 10.0);
892        b.line_to(50.0, 10.0);
893        b.line_to(50.0, 50.0);
894        let s = stroke_path(&b.build(), 8.0, StrokeStyle::new(8.0));
895        assert!(!s.commands().is_empty());
896        assert!(
897            matches!(s.commands().last(), Some(PathCommand::Close)),
898            "last command {:?}",
899            s.commands().last()
900        );
901        let mut starts = 0usize;
902        let mut closes = 0usize;
903        for c in s.commands() {
904            match c {
905                PathCommand::MoveTo(..) => starts += 1,
906                PathCommand::Close => closes += 1,
907                _ => {}
908            }
909        }
910        assert_eq!(starts, closes, "every MoveTo has a Close");
911    }
912
913    #[test]
914    fn many_segment_path_strokes_without_panicking() {
915        let mut b = PathBuilder::new();
916        b.move_to(0.0, 0.0);
917        for i in 1..200 {
918            b.line_to(
919                f32::from(i as u16) * 0.5,
920                if i % 3 == 0 { 5.0 } else { 0.0 },
921            );
922        }
923        let s = stroke_path(&b.build(), 2.0, StrokeStyle::new(2.0));
924        assert!(!s.is_empty());
925        assert!(s.bbox().is_some());
926    }
927
928    #[test]
929    fn non_finite_coordinates_do_not_panic() {
930        let mut b = PathBuilder::new();
931        b.move_to(0.0, 0.0);
932        b.line_to(f32::NAN, 10.0);
933        b.line_to(50.0, 10.0);
934        let s = stroke_path(&b.build(), 4.0, StrokeStyle::new(4.0));
935        // Whatever it produced, it produced something finite.
936        if let Some(bb) = s.bbox() {
937            assert!(bb.min_x.is_finite() || bb.min_x == f32::INFINITY);
938        }
939    }
940}