1use alloc::vec;
27use alloc::vec::Vec;
28
29use crate::path::{Path2D, PathCommand};
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
33pub enum LineCap {
34 #[default]
36 Butt,
37 Square,
39 Round,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
45pub enum LineJoin {
46 #[default]
49 Miter,
50 Bevel,
52 Round,
54}
55
56pub const DEFAULT_MITER_LIMIT: f32 = 4.0;
59
60const ARC_STEPS: usize = 12;
62
63#[derive(Debug, Clone, Copy, PartialEq)]
65pub struct StrokeStyle {
66 pub width: f32,
69 pub cap: LineCap,
71 pub join: LineJoin,
73 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 #[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 #[must_use]
102 pub const fn with_cap(mut self, cap: LineCap) -> Self {
103 self.cap = cap;
104 self
105 }
106
107 #[must_use]
109 pub const fn with_join(mut self, join: LineJoin) -> Self {
110 self.join = join;
111 self
112 }
113
114 #[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#[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 if !hw.is_finite() || hw <= 0.0 {
154 return out;
155 }
156 for poly in path.flatten_polylines(hw * 0.05) {
164 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
187struct StrokeEmitter<'a> {
189 out: &'a mut Path2D,
190 hw: f32,
191 style: StrokeStyle,
192}
193
194impl StrokeEmitter<'_> {
195 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 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 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 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 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 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 let cross = in_dir.0 * out_dir.1 - in_dir.1 * out_dir.0;
282 if cross.abs() < 1e-9 {
283 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 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 self.triangle(here, side_in, side_out);
302 } else {
303 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 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 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 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 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 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 self.arc(end, a, b);
375 }
376
377 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 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
402fn 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
417fn 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#[must_use]
432pub(crate) fn reverse_commands(commands: &[PathCommand]) -> Vec<PathCommand> {
433 struct Seg {
435 kind: u8,
436 c1: (f32, f32),
437 c2: (f32, f32),
438 to: (f32, f32),
439 }
440 type Sub = (Vec<(f32, f32)>, Vec<Seg>, bool);
443 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 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 fn close(a: f32, b: f32) -> bool {
554 (a - b).abs() < 1e-3
555 }
556
557 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 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 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 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 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 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 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 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 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 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 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 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); 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 assert_eq!(
705 tight.commands(),
706 bevel.commands(),
707 "a 1.5 limit bevels this spike"
708 );
709 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 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 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 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 assert!(ink(&round, 256) > ink(&bevel, 256), "round vs bevel");
749 assert!(ink(&miter, 256) > ink(&bevel, 256), "miter vs bevel");
750 let miter_area = miter.polygon_area();
754 assert!(
755 (round.polygon_area() - miter_area).abs() > 1.0,
756 "round and miter differ"
757 );
758 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 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 assert!(bb.min_x <= 17.0 && bb.max_x >= 83.0, "{bb:?}");
799 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 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 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 assert!(stroke_path(&crate::Path2D::new(), 5.0, StrokeStyle::default()).is_empty());
840 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 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 assert!(super::reverse_commands(&[]).is_empty());
884 }
885
886 #[test]
887 fn emitted_contours_all_close() {
888 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 if let Some(bb) = s.bbox() {
937 assert!(bb.min_x.is_finite() || bb.min_x == f32::INFINITY);
938 }
939 }
940}