1use std::sync::Arc;
2
3use crate::{Matrix, Point, Rect};
4
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8pub enum FillRule {
9 #[default]
11 NonZero,
12 EvenOdd,
14}
15
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
22#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
23pub enum Winding {
24 #[default]
26 Clockwise,
27 CounterClockwise,
29}
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35#[cfg_attr(feature = "serde", derive(serde::Serialize))]
36enum Verb {
37 Move,
38 Line,
39 Quad,
40 Conic,
44 Cubic,
45 Close,
46}
47
48#[derive(Clone, Debug, PartialEq)]
54pub struct Contour {
55 pub points: Vec<Point>,
57 pub closed: bool,
59 pub has_segments: bool,
63}
64
65#[derive(Clone, Copy, Debug, PartialEq)]
70pub enum PathElement {
71 MoveTo(Point),
72 LineTo(Point),
73 QuadTo(Point, Point),
74 ConicTo(Point, Point, f32),
75 CubicTo(Point, Point, Point),
76 Close,
77}
78
79#[derive(Clone, Debug, PartialEq)]
84#[cfg_attr(feature = "serde", derive(serde::Serialize))]
85pub struct Path {
86 verbs: Vec<Verb>,
87 points: Vec<Point>,
88 weights: Vec<f32>,
91 bounds: Rect,
94 shape: BuiltShape,
97}
98
99#[derive(Clone, Copy, Debug, Default, PartialEq)]
104#[cfg_attr(feature = "serde", derive(serde::Serialize))]
105enum BuiltShape {
106 #[default]
107 General,
108 Oval(Rect),
110 RoundRect { rect: Rect, radii: [[f32; 2]; 4] },
113}
114
115impl BuiltShape {
116 fn of_round_rect(rect: Rect, radii: [[f32; 2]; 4]) -> Self {
122 let halves = [rect.width * 0.5, rect.height * 0.5];
123 if radii.iter().all(|corner| *corner == [0.0; 2]) {
124 BuiltShape::General
125 } else if radii.iter().all(|corner| *corner == halves) {
126 BuiltShape::Oval(rect)
127 } else {
128 BuiltShape::RoundRect { rect, radii }
129 }
130 }
131
132 fn transformed(self, transform: &Matrix) -> Self {
140 if !transform.rect_stays_rect() {
141 return BuiltShape::General;
142 }
143 match self {
144 BuiltShape::General => BuiltShape::General,
145 BuiltShape::Oval(rect) => BuiltShape::Oval(transform.map_rect(&rect)),
146 BuiltShape::RoundRect { rect, radii } => BuiltShape::of_round_rect(
147 transform.map_rect(&rect),
148 transformed_radii(&rect, radii, transform),
149 ),
150 }
151 }
152}
153
154fn transformed_radii(rect: &Rect, radii: [[f32; 2]; 4], transform: &Matrix) -> [[f32; 2]; 4] {
160 let [a, b, c, d, ..] = transform.to_affine();
161 let quarter_turn = a == 0.0 && d == 0.0;
162 let mapped = transform.map_rect(rect);
163 let centre = Point::new(
164 mapped.x + mapped.width * 0.5,
165 mapped.y + mapped.height * 0.5,
166 );
167 let corners = [
168 Point::new(rect.x, rect.y),
169 Point::new(rect.right(), rect.y),
170 Point::new(rect.right(), rect.bottom()),
171 Point::new(rect.x, rect.bottom()),
172 ];
173 let mut moved = [[0.0; 2]; 4];
174 for (corner, [x, y]) in corners.into_iter().zip(radii) {
175 let landed = transform.map_point(corner);
176 let index = match (landed.x < centre.x, landed.y < centre.y) {
177 (true, true) => 0,
178 (false, true) => 1,
179 (false, false) => 2,
180 (true, false) => 3,
181 };
182 moved[index] = if quarter_turn {
183 [y * c.abs(), x * b.abs()]
184 } else {
185 [x * a.abs(), y * d.abs()]
186 };
187 }
188 moved
189}
190
191impl Path {
192 pub fn as_oval(&self) -> Option<Rect> {
197 match self.shape {
198 BuiltShape::Oval(rect) => Some(rect),
199 _ => None,
200 }
201 }
202
203 pub fn as_round_rect(&self) -> Option<(Rect, [[f32; 2]; 4])> {
210 match self.shape {
211 BuiltShape::RoundRect { rect, radii } => Some((rect, radii)),
212 _ => None,
213 }
214 }
215
216 pub fn transformed(&self, transform: &Matrix) -> Arc<Path> {
228 let points: Vec<Point> = self
229 .points
230 .iter()
231 .map(|point| transform.map_point(*point))
232 .collect();
233 Arc::new(Path {
234 verbs: self.verbs.clone(),
235 bounds: control_point_bounds(&points),
236 points,
237 weights: self.weights.clone(),
238 shape: self.shape.transformed(transform),
239 })
240 }
241
242 pub fn elements(&self) -> impl Iterator<Item = PathElement> + '_ {
245 let mut point = 0;
246 let mut weight = 0;
247 self.verbs.iter().map(move |verb| {
248 let element = match verb {
249 Verb::Move => PathElement::MoveTo(self.points[point]),
250 Verb::Line => PathElement::LineTo(self.points[point]),
251 Verb::Quad => PathElement::QuadTo(self.points[point], self.points[point + 1]),
252 Verb::Conic => {
253 let element = PathElement::ConicTo(
254 self.points[point],
255 self.points[point + 1],
256 self.weights[weight],
257 );
258 weight += 1;
259 element
260 }
261 Verb::Cubic => PathElement::CubicTo(
262 self.points[point],
263 self.points[point + 1],
264 self.points[point + 2],
265 ),
266 Verb::Close => PathElement::Close,
267 };
268 point += match verb {
269 Verb::Move | Verb::Line => 1,
270 Verb::Quad | Verb::Conic => 2,
271 Verb::Cubic => 3,
272 Verb::Close => 0,
273 };
274 element
275 })
276 }
277
278 pub fn bounds(&self) -> Rect {
280 self.bounds
281 }
282
283 pub fn tight_bounds(&self) -> Rect {
285 let mut bounds = TightBounds::default();
286 let mut point_index = 0usize;
287 let mut weight_index = 0usize;
288 let mut cursor = Point::ZERO;
289 let mut contour_start = Point::ZERO;
290 for verb in &self.verbs {
291 match verb {
292 Verb::Move => {
293 cursor = self.points[point_index];
294 contour_start = cursor;
295 point_index += 1;
296 bounds.include(cursor);
297 }
298 Verb::Line => {
299 cursor = self.points[point_index];
300 point_index += 1;
301 bounds.include(cursor);
302 }
303 Verb::Quad => {
304 let control = self.points[point_index];
305 let end = self.points[point_index + 1];
306 point_index += 2;
307 include_quadratic_extrema(&mut bounds, cursor, control, end);
308 cursor = end;
309 }
310 Verb::Conic => {
311 let control = self.points[point_index];
312 let end = self.points[point_index + 1];
313 let weight = self.weights[weight_index];
314 point_index += 2;
315 weight_index += 1;
316 include_conic_extrema(&mut bounds, cursor, control, end, weight);
317 cursor = end;
318 }
319 Verb::Cubic => {
320 let first = self.points[point_index];
321 let second = self.points[point_index + 1];
322 let end = self.points[point_index + 2];
323 point_index += 3;
324 include_cubic_extrema(&mut bounds, cursor, first, second, end);
325 cursor = end;
326 }
327 Verb::Close => {
328 cursor = contour_start;
329 bounds.include(cursor);
330 }
331 }
332 }
333 bounds.rect()
334 }
335
336 pub fn is_empty(&self) -> bool {
338 self.verbs.is_empty()
339 }
340
341 pub fn heap_bytes(&self) -> usize {
343 self.points.len() * std::mem::size_of::<Point>()
344 + self.weights.len() * std::mem::size_of::<f32>()
345 + self.verbs.len()
346 }
347
348 pub fn contains(&self, point: Point, fill_rule: FillRule) -> bool {
353 if !self.bounds.contains_inclusive(point) {
354 return false;
355 }
356 let crossings = self.walk_crossings(point);
357 match fill_rule {
358 FillRule::NonZero => crossings.is_inside_non_zero(),
359 FillRule::EvenOdd => crossings.is_inside_even_odd(),
360 }
361 }
362
363 fn walk_crossings(&self, point: Point) -> crate::winding::Crossings {
365 let mut crossings = crate::winding::Crossings::default();
366 let mut index = 0usize;
367 let mut weight_index = 0usize;
368 let mut cursor = Point::ZERO;
369 let mut contour_start = Point::ZERO;
370 let mut contour_open = false;
371 for verb in &self.verbs {
372 match verb {
373 Verb::Move => {
374 if contour_open {
377 crossings.line(cursor, contour_start, point);
378 }
379 contour_open = true;
380 contour_start = self.points[index];
381 cursor = contour_start;
382 index += 1;
383 }
384 Verb::Line => {
385 crossings.line(cursor, self.points[index], point);
386 cursor = self.points[index];
387 index += 1;
388 }
389 Verb::Quad => {
390 crossings.quad(cursor, self.points[index], self.points[index + 1], point);
391 cursor = self.points[index + 1];
392 index += 2;
393 }
394 Verb::Conic => {
395 crossings.conic(
396 cursor,
397 self.points[index],
398 self.points[index + 1],
399 self.weights[weight_index],
400 point,
401 );
402 cursor = self.points[index + 1];
403 index += 2;
404 weight_index += 1;
405 }
406 Verb::Cubic => {
407 crossings.cubic(
408 cursor,
409 self.points[index],
410 self.points[index + 1],
411 self.points[index + 2],
412 point,
413 );
414 cursor = self.points[index + 2];
415 index += 3;
416 }
417 Verb::Close => {
418 crossings.line(cursor, contour_start, point);
419 cursor = contour_start;
420 contour_open = false;
421 }
422 }
423 }
424 if contour_open {
425 crossings.line(cursor, contour_start, point);
426 }
427 crossings
428 }
429
430 pub fn measure(&self, tolerance: f32) -> Vec<crate::ContourMeasure> {
434 self.flatten(tolerance)
435 .iter()
436 .filter_map(crate::ContourMeasure::of)
437 .collect()
438 }
439
440 pub fn flatten(&self, tolerance: f32) -> Vec<Contour> {
446 let mut out = Flattener::new(tolerance.max(1e-4));
447 let mut i = 0usize;
448 let mut weight_index = 0usize;
449 for verb in &self.verbs {
450 match verb {
451 Verb::Move => {
452 out.move_to(self.points[i]);
453 i += 1;
454 }
455 Verb::Line => {
456 out.line_to(self.points[i]);
457 i += 1;
458 }
459 Verb::Quad => {
460 out.quad_to(self.points[i], self.points[i + 1]);
461 i += 2;
462 }
463 Verb::Conic => {
464 out.conic_to(
465 self.points[i],
466 self.points[i + 1],
467 self.weights[weight_index],
468 );
469 i += 2;
470 weight_index += 1;
471 }
472 Verb::Cubic => {
473 out.cubic_to(self.points[i], self.points[i + 1], self.points[i + 2]);
474 i += 3;
475 }
476 Verb::Close => out.close(),
477 }
478 }
479 out.finish()
480 }
481}
482
483#[derive(Default)]
484struct TightBounds(Option<(f32, f32, f32, f32)>);
485
486impl TightBounds {
487 fn include(&mut self, point: Point) {
488 self.0 = Some(match self.0 {
489 Some((left, top, right, bottom)) => (
490 left.min(point.x),
491 top.min(point.y),
492 right.max(point.x),
493 bottom.max(point.y),
494 ),
495 None => (point.x, point.y, point.x, point.y),
496 });
497 }
498
499 fn rect(self) -> Rect {
500 self.0
501 .map_or_else(Rect::default, |(left, top, right, bottom)| {
502 Rect::from_ltrb(left, top, right, bottom)
503 })
504 }
505}
506
507fn include_quadratic_extrema(bounds: &mut TightBounds, start: Point, control: Point, end: Point) {
508 bounds.include(start);
509 bounds.include(end);
510 for (start_axis, control_axis, end_axis) in
511 [(start.x, control.x, end.x), (start.y, control.y, end.y)]
512 {
513 let denominator = start_axis as f64 - 2.0 * control_axis as f64 + end_axis as f64;
514 if denominator == 0.0 {
515 continue;
516 }
517 let parameter = ((start_axis as f64 - control_axis as f64) / denominator) as f32;
518 if parameter > 0.0 && parameter < 1.0 {
519 bounds.include(eval_quad(start, control, end, parameter));
520 }
521 }
522}
523
524fn include_cubic_extrema(
525 bounds: &mut TightBounds,
526 start: Point,
527 first: Point,
528 second: Point,
529 end: Point,
530) {
531 bounds.include(start);
532 bounds.include(end);
533 for (start_axis, first_axis, second_axis, end_axis) in [
534 (start.x, first.x, second.x, end.x),
535 (start.y, first.y, second.y, end.y),
536 ] {
537 for parameter in cubic_extrema(start_axis, first_axis, second_axis, end_axis)
538 .into_iter()
539 .flatten()
540 {
541 if parameter > 0.0 && parameter < 1.0 {
542 bounds.include(eval_cubic(start, first, second, end, parameter));
543 }
544 }
545 }
546}
547
548fn include_conic_extrema(
549 bounds: &mut TightBounds,
550 start: Point,
551 control: Point,
552 end: Point,
553 weight: f32,
554) {
555 bounds.include(start);
556 bounds.include(end);
557 for (start_axis, control_axis, end_axis) in
558 [(start.x, control.x, end.x), (start.y, control.y, end.y)]
559 {
560 for parameter in conic_derivative_roots(start_axis, control_axis, end_axis, weight) {
561 let p = eval_conic(start, control, end, weight, parameter);
562 let clamp = |v: f32, a: f32, b: f32, c: f32| v.clamp(a.min(b).min(c), a.max(b).max(c));
566 bounds.include(Point::new(
567 clamp(p.x, start.x, control.x, end.x),
568 clamp(p.y, start.y, control.y, end.y),
569 ));
570 }
571 }
572}
573
574pub(crate) fn conic_derivative_roots(
580 start: f32,
581 control: f32,
582 end: f32,
583 weight: f32,
584) -> impl Iterator<Item = f32> {
585 let w = weight as f64;
592 let p10 = control as f64 - start as f64;
593 let p20 = end as f64 - start as f64;
594 let quadratic = (w - 1.0) * p20;
595 let linear = p20 - 2.0 * w * p10;
596 let constant = w * p10;
597
598 let mut roots = [None, None];
599 if quadratic == 0.0 {
600 roots[0] = unit_root(-constant, linear);
601 } else {
602 let discriminant = linear * linear - 4.0 * quadratic * constant;
603 if discriminant >= 0.0 && discriminant.is_finite() {
604 let root = discriminant.sqrt();
607 let q = -0.5 * (linear + root.copysign(linear));
608 roots[0] = unit_root(q, quadratic);
609 roots[1] = unit_root(constant, q).filter(|value| roots[0] != Some(*value));
610 }
611 }
612 roots.into_iter().flatten()
613}
614
615pub(crate) fn eval_conic(start: Point, control: Point, end: Point, weight: f32, t: f32) -> Point {
617 let u = 1.0 - t;
618 let b0 = u * u;
619 let b1 = 2.0 * weight * u * t;
620 let b2 = t * t;
621 let d = b0 + b1 + b2;
622 Point::new(
623 (b0 * start.x + b1 * control.x + b2 * end.x) / d,
624 (b0 * start.y + b1 * control.y + b2 * end.y) / d,
625 )
626}
627
628fn cubic_extrema(start: f32, first: f32, second: f32, end: f32) -> [Option<f32>; 2] {
629 let start = start as f64;
630 let first = first as f64;
631 let second = second as f64;
632 let end = end as f64;
633 let quadratic = -start + 3.0 * first - 3.0 * second + end;
634 let linear = 2.0 * (start - 2.0 * first + second);
635 let constant = first - start;
636 if quadratic == 0.0 {
637 return [unit_root(-constant, linear), None];
638 }
639 let discriminant = linear * linear - 4.0 * quadratic * constant;
640 if discriminant < 0.0 || !discriminant.is_finite() {
641 return [None, None];
642 }
643
644 let root = discriminant.sqrt();
647 let q = -0.5 * (linear + root.copysign(linear));
648 let first_root = unit_root(q, quadratic);
649 let second_root = unit_root(constant, q).filter(|value| Some(*value) != first_root);
650 [first_root, second_root]
651}
652
653fn unit_root(numerator: f64, denominator: f64) -> Option<f32> {
654 if denominator == 0.0 {
655 return None;
656 }
657 let value = numerator / denominator;
658 (value.is_finite() && value > 0.0 && value < 1.0).then_some(value as f32)
659}
660
661#[derive(Clone, Default)]
663pub struct PathBuilder {
664 verbs: Vec<Verb>,
665 points: Vec<Point>,
666 weights: Vec<f32>,
667 bounds: Option<Rect>,
668 resume_point: Option<Point>,
683 contour_open: bool,
684 shape: BuiltShape,
688}
689
690impl PathBuilder {
691 pub fn new() -> Self {
693 Self::default()
694 }
695
696 pub fn move_to(&mut self, p: impl Into<Point>) -> &mut Self {
698 let p = p.into();
699 self.verbs.push(Verb::Move);
700 self.push_point(p);
701 self.resume_point = Some(p);
702 self.contour_open = true;
703 self
704 }
705
706 pub fn line_to(&mut self, p: impl Into<Point>) -> &mut Self {
708 let p = p.into();
709 self.ensure_contour(p);
710 self.verbs.push(Verb::Line);
711 self.push_point(p);
712 self
713 }
714
715 pub fn quad_to(&mut self, c: impl Into<Point>, p: impl Into<Point>) -> &mut Self {
717 let (c, p) = (c.into(), p.into());
718 self.ensure_contour(c);
719 self.verbs.push(Verb::Quad);
720 self.push_point(c);
721 self.push_point(p);
722 self
723 }
724
725 pub fn conic_to(&mut self, c: impl Into<Point>, p: impl Into<Point>, weight: f32) -> &mut Self {
738 let (c, p) = (c.into(), p.into());
739 if !weight.is_finite() {
740 return self.line_to(c).line_to(p);
741 }
742 if weight <= 0.0 {
743 return self.line_to(p);
744 }
745 if weight == 1.0 {
746 return self.quad_to(c, p);
747 }
748 self.ensure_contour(c);
749 self.verbs.push(Verb::Conic);
750 self.push_point(c);
751 self.push_point(p);
752 self.weights.push(weight);
753 self
754 }
755
756 pub fn cubic_to(
758 &mut self,
759 c1: impl Into<Point>,
760 c2: impl Into<Point>,
761 p: impl Into<Point>,
762 ) -> &mut Self {
763 let (c1, c2, p) = (c1.into(), c2.into(), p.into());
764 self.ensure_contour(c1);
765 self.verbs.push(Verb::Cubic);
766 self.push_point(c1);
767 self.push_point(c2);
768 self.push_point(p);
769 self
770 }
771
772 pub fn close(&mut self) -> &mut Self {
776 if self.contour_open {
777 self.verbs.push(Verb::Close);
778 self.contour_open = false;
779 }
780 self
781 }
782
783 pub fn rect(&mut self, r: Rect) -> &mut Self {
787 self.move_to((r.x, r.y))
788 .line_to((r.right(), r.y))
789 .line_to((r.right(), r.bottom()))
790 .line_to((r.x, r.bottom()))
791 .close();
792 self.resume_point = Some(Point::new(r.x, r.y));
796 self
797 }
798
799 pub fn rrect(&mut self, r: Rect, radius: f32) -> &mut Self {
801 self.rrect_radii(r, [radius; 4])
802 }
803
804 pub fn rrect_radii(&mut self, r: Rect, radii: [f32; 4]) -> &mut Self {
808 self.rrect_radii_elliptical(r, radii.map(|radius| [radius; 2]))
809 }
810
811 pub fn rrect_radii_elliptical(
816 &mut self,
817 r: impl Into<Rect>,
818 radii: [[f32; 2]; 4],
819 ) -> &mut Self {
820 self.rrect_radii_elliptical_wound(r, radii, Winding::Clockwise)
821 }
822
823 pub fn rrect_radii_elliptical_wound(
828 &mut self,
829 r: impl Into<Rect>,
830 radii: [[f32; 2]; 4],
831 winding: Winding,
832 ) -> &mut Self {
833 let r = r.into();
834 let [tl, tr, br, bl] = constrain_radii_elliptical(&r, radii);
835 let built_alone = self.has_no_segment();
836 self.trace_rrect(r, [tl, tr, br, bl], winding);
837 if built_alone {
838 self.shape = BuiltShape::of_round_rect(r, [tl, tr, br, bl]);
839 }
840 self
841 }
842
843 fn trace_rrect(&mut self, r: Rect, radii: [[f32; 2]; 4], winding: Winding) {
846 let [tl, tr, br, bl] = radii;
847 let (l, t, rr, b) = (r.x, r.y, r.right(), r.bottom());
848 if [tl, tr, br, bl].iter().all(|[x, y]| *x == 0.0 && *y == 0.0) {
849 match winding {
850 Winding::Clockwise => self.rect(r),
851 Winding::CounterClockwise => self
852 .move_to((l, t))
853 .line_to((l, b))
854 .line_to((rr, b))
855 .line_to((rr, t))
856 .close(),
857 };
858 self.resume_point = Some(Point::new(l, t));
859 return;
860 }
861 let w = std::f32::consts::FRAC_1_SQRT_2;
865 match winding {
866 Winding::Clockwise => self
867 .move_to((l + tl[0], t))
868 .line_to((rr - tr[0], t))
869 .conic_to((rr, t), (rr, t + tr[1]), w)
870 .line_to((rr, b - br[1]))
871 .conic_to((rr, b), (rr - br[0], b), w)
872 .line_to((l + bl[0], b))
873 .conic_to((l, b), (l, b - bl[1]), w)
874 .line_to((l, t + tl[1]))
875 .conic_to((l, t), (l + tl[0], t), w)
876 .close(),
877 Winding::CounterClockwise => self
881 .move_to((l + tl[0], t))
882 .conic_to((l, t), (l, t + tl[1]), w)
883 .line_to((l, b - bl[1]))
884 .conic_to((l, b), (l + bl[0], b), w)
885 .line_to((rr - br[0], b))
886 .conic_to((rr, b), (rr, b - br[1]), w)
887 .line_to((rr, t + tr[1]))
888 .conic_to((rr, t), (rr - tr[0], t), w)
889 .line_to((l + tl[0], t))
890 .close(),
891 };
892 self.resume_point = Some(Point::new(l, t));
905 }
906
907 pub fn rsuperellipse(&mut self, r: Rect, radius: f32) -> &mut Self {
913 self.rsuperellipse_radii(r, [[radius; 2]; 4])
914 }
915
916 pub fn rsuperellipse_radii(&mut self, r: Rect, radii: [[f32; 2]; 4]) -> &mut Self {
922 crate::superellipse::RoundSuperellipse::new(r, radii).emit(self);
923 self.resume_point = Some(Point::new(r.x, r.y));
924 self
925 }
926
927 pub fn arc(
932 &mut self,
933 center: impl Into<Point>,
934 radius: f32,
935 start_angle: f32,
936 sweep_angle: f32,
937 ) -> &mut Self {
938 self.ellipse(center, [radius; 2], 0.0, start_angle, sweep_angle)
939 }
940
941 pub fn ellipse(
950 &mut self,
951 center: impl Into<Point>,
952 radii: [f32; 2],
953 x_axis_rotation: f32,
954 start_angle: f32,
955 sweep_angle: f32,
956 ) -> &mut Self {
957 let center = center.into();
958 let [radius_x, radius_y] = radii;
959 let finite = center.x.is_finite()
964 && center.y.is_finite()
965 && radius_x.is_finite()
966 && radius_y.is_finite()
967 && x_axis_rotation.is_finite()
968 && start_angle.is_finite()
969 && sweep_angle.is_finite();
970 debug_assert!(
971 radius_x >= 0.0 && radius_y >= 0.0,
972 "negative radii draw nothing; Canvas2D throws here"
973 );
974 if !finite || radius_x < 0.0 || radius_y < 0.0 {
975 return self;
976 }
977
978 let full_turn = std::f32::consts::TAU;
983 let sweep_angle = sweep_angle.clamp(-full_turn, full_turn);
984
985 let unit_circle_to_ellipse = unit_circle_map(center, radii, x_axis_rotation);
986 let first = unit_circle_to_ellipse.map_point(unit_circle_point(start_angle));
987 if self.contour_open || self.resume_point.is_some() {
993 self.ensure_contour(first);
994 self.line_to(first);
995 } else {
996 self.move_to(first);
997 }
998 if sweep_angle != 0.0 {
999 self.push_arc_conics(&unit_circle_to_ellipse, start_angle, sweep_angle);
1000 }
1001 if sweep_angle.abs() >= full_turn {
1004 self.close();
1005 }
1006 self
1007 }
1008
1009 pub fn arc_to(
1014 &mut self,
1015 corner: impl Into<Point>,
1016 next: impl Into<Point>,
1017 radius: f32,
1018 ) -> &mut Self {
1019 let (corner, next) = (corner.into(), next.into());
1020 self.ensure_contour(corner);
1021 let start = *self.points.last().expect("ensure_contour opened a contour");
1022
1023 let incoming = normalize(
1027 corner.x as f64 - start.x as f64,
1028 corner.y as f64 - start.y as f64,
1029 );
1030 let outgoing = normalize(
1031 next.x as f64 - corner.x as f64,
1032 next.y as f64 - corner.y as f64,
1033 );
1034 let (Some(incoming), Some(outgoing)) = (incoming, outgoing) else {
1035 return self.line_to(corner);
1036 };
1037 let cosine = incoming.0 * outgoing.0 + incoming.1 * outgoing.1;
1038 let sine = incoming.0 * outgoing.1 - incoming.1 * outgoing.0;
1039 if radius <= 0.0 || !radius.is_finite() || sine.abs() < 1.0 / (1 << 12) as f64 {
1040 return self.line_to(corner);
1041 }
1042
1043 let tangent_length = (radius as f64 * (1.0 - cosine) / sine).abs();
1044 let entry = Point::new(
1045 corner.x - (tangent_length * incoming.0) as f32,
1046 corner.y - (tangent_length * incoming.1) as f32,
1047 );
1048 let turn = sine.signum() as f32;
1050 let center = Point::new(
1051 entry.x + radius * turn * -(incoming.1 as f32),
1052 entry.y + radius * turn * incoming.0 as f32,
1053 );
1054 let exit = Point::new(
1055 corner.x + (tangent_length * outgoing.0) as f32,
1056 corner.y + (tangent_length * outgoing.1) as f32,
1057 );
1058
1059 let start_angle = (entry.y - center.y).atan2(entry.x - center.x);
1060 let end_angle = (exit.y - center.y).atan2(exit.x - center.x);
1061 let sweep = shortest_sweep(start_angle, end_angle, turn);
1062
1063 self.line_to(entry);
1064 let map = unit_circle_map(center, [radius; 2], 0.0);
1065 self.push_arc_conics(&map, start_angle, sweep);
1066 self
1067 }
1068
1069 pub fn circle(&mut self, center: impl Into<Point>, radius: f32) -> &mut Self {
1074 let c = center.into();
1075 let r = radius;
1076 let w = std::f32::consts::FRAC_1_SQRT_2;
1077 let built_alone = self.has_no_segment();
1078 self.move_to((c.x + r, c.y))
1079 .conic_to((c.x + r, c.y + r), (c.x, c.y + r), w)
1080 .conic_to((c.x - r, c.y + r), (c.x - r, c.y), w)
1081 .conic_to((c.x - r, c.y - r), (c.x, c.y - r), w)
1082 .conic_to((c.x + r, c.y - r), (c.x + r, c.y), w)
1083 .close();
1084 if built_alone && r > 0.0 {
1085 self.shape = BuiltShape::Oval(Rect::new(c.x - r, c.y - r, 2.0 * r, 2.0 * r));
1086 }
1087 self
1088 }
1089
1090 pub fn append(&mut self, path: &Path, transform: &Matrix) -> &mut Self {
1095 if path.verbs.is_empty() {
1096 return self;
1099 }
1100 let mut point = path.points.iter();
1101 let mut weight = path.weights.iter();
1102 let mut cursor = Point::ZERO;
1103 let mut contour_start = Point::ZERO;
1104 for verb in &path.verbs {
1105 let count = match verb {
1106 Verb::Move | Verb::Line => 1,
1107 Verb::Quad | Verb::Conic => 2,
1108 Verb::Cubic => 3,
1109 Verb::Close => 0,
1110 };
1111 self.verbs.push(*verb);
1112 for _ in 0..count {
1113 let Some(&p) = point.next() else {
1114 return self;
1115 };
1116 cursor = transform.map_point(p);
1117 self.push_point(cursor);
1118 }
1119 if matches!(verb, Verb::Conic) {
1120 let Some(&w) = weight.next() else {
1125 return self;
1126 };
1127 self.weights.push(w);
1128 }
1129 match verb {
1130 Verb::Move => contour_start = cursor,
1131 Verb::Close => cursor = contour_start,
1132 _ => {}
1133 }
1134 }
1135 if matches!(path.verbs.last(), Some(Verb::Close)) {
1146 self.move_to(cursor);
1147 } else {
1148 self.resume_point = Some(contour_start);
1152 self.contour_open = true;
1153 }
1154 self
1155 }
1156
1157 pub fn build(self) -> Arc<Path> {
1159 Arc::new(Path {
1160 verbs: self.verbs,
1161 points: self.points,
1162 weights: self.weights,
1163 bounds: self.bounds.unwrap_or_default(),
1164 shape: self.shape,
1165 })
1166 }
1167
1168 fn push_arc_conics(&mut self, map: &Matrix, start_angle: f32, sweep_angle: f32) {
1176 let piece_count = (sweep_angle.abs() / std::f32::consts::FRAC_PI_2)
1177 .ceil()
1178 .max(1.0);
1179 let step = sweep_angle / piece_count;
1180 let weight = (step / 2.0).cos();
1181
1182 let mut angle = start_angle;
1183 for _ in 0..piece_count as u32 {
1184 let mid = unit_circle_point(angle + step / 2.0);
1185 let control = Point::new(mid.x / weight, mid.y / weight);
1186 let to = unit_circle_point(angle + step);
1187 self.conic_to(map.map_point(control), map.map_point(to), weight);
1188 angle += step;
1189 }
1190 }
1191
1192 fn ensure_contour(&mut self, p: Point) {
1202 if self.contour_open {
1203 return;
1204 }
1205 self.move_to(self.resume_point.unwrap_or(p));
1206 }
1207
1208 fn has_no_segment(&self) -> bool {
1211 self.verbs.iter().all(|verb| matches!(verb, Verb::Move))
1212 }
1213
1214 fn push_point(&mut self, p: Point) {
1215 self.shape = BuiltShape::General;
1216 self.points.push(p);
1217 self.bounds = Some(grown_bounds(self.bounds, p));
1218 }
1219}
1220
1221fn grown_bounds(bounds: Option<Rect>, p: Point) -> Rect {
1226 match bounds {
1227 Some(b) => Rect::from_ltrb(
1228 b.x.min(p.x),
1229 b.y.min(p.y),
1230 b.right().max(p.x),
1231 b.bottom().max(p.y),
1232 ),
1233 None => Rect::new(p.x, p.y, 0.0, 0.0),
1234 }
1235}
1236
1237fn control_point_bounds(points: &[Point]) -> Rect {
1240 points
1241 .iter()
1242 .fold(None, |bounds, point| Some(grown_bounds(bounds, *point)))
1243 .unwrap_or_default()
1244}
1245
1246fn unit_circle_point(angle: f32) -> Point {
1248 let (sine, cosine) = angle.sin_cos();
1249 Point::new(cosine, sine)
1250}
1251
1252fn unit_circle_map(center: Point, radii: [f32; 2], rotation: f32) -> Matrix {
1254 let [radius_x, radius_y] = radii;
1255 let (sine, cosine) = rotation.sin_cos();
1256 Matrix::from_affine(
1257 radius_x * cosine,
1258 radius_x * sine,
1259 -radius_y * sine,
1260 radius_y * cosine,
1261 center.x,
1262 center.y,
1263 )
1264}
1265
1266fn shortest_sweep(start: f32, end: f32, direction: f32) -> f32 {
1268 let mut sweep = end - start;
1269 let turn = std::f32::consts::TAU;
1270 while sweep > 0.0 && direction < 0.0 {
1271 sweep -= turn;
1272 }
1273 while sweep < 0.0 && direction > 0.0 {
1274 sweep += turn;
1275 }
1276 sweep
1277}
1278
1279fn normalize(x: f64, y: f64) -> Option<(f64, f64)> {
1281 let length = (x * x + y * y).sqrt();
1282 (length.is_finite() && length > 0.0).then(|| (x / length, y / length))
1283}
1284
1285pub fn constrain_radii(r: &Rect, radii: [f32; 4]) -> [f32; 4] {
1289 constrain_radii_elliptical(r, radii.map(|v| [v; 2])).map(|[x, _]| x)
1290}
1291
1292pub fn constrain_radii_elliptical(r: &Rect, radii: [[f32; 2]; 4]) -> [[f32; 2]; 4] {
1297 let [tl, tr, br, bl] = radii.map(|[x, y]| [x.max(0.0), y.max(0.0)]);
1298 let fit = |side: f32, a: f32, b: f32| if a + b <= side { 1.0 } else { side / (a + b) };
1299 let f = fit(r.width, tl[0], tr[0])
1300 .min(fit(r.width, bl[0], br[0]))
1301 .min(fit(r.height, tl[1], bl[1]))
1302 .min(fit(r.height, tr[1], br[1]));
1303 [tl, tr, br, bl].map(|[x, y]| [x * f, y * f])
1304}
1305
1306struct Flattener {
1308 tolerance: f32,
1309 contours: Vec<Contour>,
1310 current: Vec<Point>,
1311 has_segments: bool,
1313}
1314
1315impl Flattener {
1316 fn new(tolerance: f32) -> Self {
1317 Self {
1318 tolerance,
1319 contours: Vec::new(),
1320 current: Vec::new(),
1321 has_segments: false,
1322 }
1323 }
1324
1325 fn move_to(&mut self, p: Point) {
1326 self.flush(false);
1327 self.current.push(p);
1328 self.has_segments = false;
1329 }
1330
1331 fn line_to(&mut self, p: Point) {
1332 self.current.push(p);
1333 self.has_segments = true;
1334 }
1335
1336 fn quad_to(&mut self, c: Point, p: Point) {
1337 let Some(&start) = self.current.last() else {
1338 return;
1339 };
1340 self.has_segments = true;
1341 let dev = second_difference(start, c, p);
1342 let n = segment_count((dev / (8.0 * self.tolerance)).sqrt());
1343 for i in 1..=n {
1344 let t = i as f32 / n as f32;
1345 self.current.push(eval_quad(start, c, p, t));
1346 }
1347 }
1348
1349 fn conic_to(&mut self, c: Point, p: Point, w: f32) {
1350 let Some(&start) = self.current.last() else {
1351 return;
1352 };
1353 self.has_segments = true;
1354 let n = segment_count(conic_segment_estimate(start, c, p, w, self.tolerance));
1355 for i in 1..=n {
1356 let t = i as f32 / n as f32;
1357 self.current.push(eval_conic(start, c, p, w, t));
1358 }
1359 }
1360
1361 fn cubic_to(&mut self, c1: Point, c2: Point, p: Point) {
1362 let Some(&start) = self.current.last() else {
1363 return;
1364 };
1365 self.has_segments = true;
1366 let dev = second_difference(start, c1, c2).max(second_difference(c1, c2, p));
1367 let n = segment_count((3.0 * dev / (4.0 * self.tolerance)).sqrt());
1368 for i in 1..=n {
1369 let t = i as f32 / n as f32;
1370 self.current.push(eval_cubic(start, c1, c2, p, t));
1371 }
1372 }
1373
1374 fn close(&mut self) {
1375 if let (Some(&first), Some(&last)) = (self.current.first(), self.current.last()) {
1378 if self.current.len() >= 2 && (first.x, first.y) != (last.x, last.y) {
1379 self.current.push(first);
1380 }
1381 }
1382 if !self.current.is_empty() {
1388 self.has_segments = true;
1389 }
1390 self.flush(true);
1391 }
1392
1393 fn finish(mut self) -> Vec<Contour> {
1394 self.flush(false);
1395 self.contours
1396 }
1397
1398 fn flush(&mut self, closed: bool) {
1405 if !self.current.is_empty() {
1406 self.contours.push(Contour {
1407 points: std::mem::take(&mut self.current),
1408 closed,
1409 has_segments: self.has_segments,
1410 });
1411 }
1412 self.has_segments = false;
1413 }
1414}
1415
1416fn conic_segment_estimate(start: Point, control: Point, end: Point, w: f32, tolerance: f32) -> f32 {
1420 let precision = 1.0 / tolerance;
1421 let cx = 0.5 * (start.x.min(control.x).min(end.x) + start.x.max(control.x).max(end.x));
1423 let cy = 0.5 * (start.y.min(control.y).min(end.y) + start.y.max(control.y).max(end.y));
1424 let (p0x, p0y) = (start.x - cx, start.y - cy);
1425 let (p1x, p1y) = (control.x - cx, control.y - cy);
1426 let (p2x, p2y) = (end.x - cx, end.y - cy);
1427 let max_len_sq = (p0x * p0x + p0y * p0y)
1428 .max(p1x * p1x + p1y * p1y)
1429 .max(p2x * p2x + p2y * p2y);
1430 let (dpx, dpy) = (p0x - 2.0 * w * p1x + p2x, p0y - 2.0 * w * p1y + p2y);
1431 let dw = (2.0 - 2.0 * w).abs();
1432 let rp_minus_1 = (max_len_sq.sqrt() * precision - 1.0).max(0.0);
1433 let numer = (dpx * dpx + dpy * dpy).sqrt() * precision + rp_minus_1 * dw;
1434 let denom = 4.0 * w.min(1.0);
1435 (numer / denom).sqrt()
1436}
1437
1438fn second_difference(a: Point, b: Point, c: Point) -> f32 {
1439 let dx = a.x - 2.0 * b.x + c.x;
1440 let dy = a.y - 2.0 * b.y + c.y;
1441 (dx * dx + dy * dy).sqrt()
1442}
1443
1444fn segment_count(estimate: f32) -> u32 {
1445 (estimate.ceil() as u32).clamp(1, 64)
1446}
1447
1448fn eval_quad(p0: Point, c: Point, p1: Point, t: f32) -> Point {
1449 let u = 1.0 - t;
1450 Point::new(
1451 u * u * p0.x + 2.0 * u * t * c.x + t * t * p1.x,
1452 u * u * p0.y + 2.0 * u * t * c.y + t * t * p1.y,
1453 )
1454}
1455
1456fn eval_cubic(p0: Point, c1: Point, c2: Point, p1: Point, t: f32) -> Point {
1457 let u = 1.0 - t;
1458 let (uu, tt) = (u * u, t * t);
1459 Point::new(
1460 u * uu * p0.x + 3.0 * uu * t * c1.x + 3.0 * u * tt * c2.x + t * tt * p1.x,
1461 u * uu * p0.y + 3.0 * uu * t * c1.y + 3.0 * u * tt * c2.y + t * tt * p1.y,
1462 )
1463}
1464
1465pub fn local_tolerance(transform: &Matrix) -> f32 {
1467 0.25 / transform.max_scale().max(1e-3)
1468}
1469
1470#[cfg(test)]
1471mod tests {
1472 #[test]
1476 fn a_path_built_as_an_oval_or_a_rounded_rect_knows_it() {
1477 let built = |build: &dyn Fn(&mut PathBuilder)| {
1478 let mut path = PathBuilder::new();
1479 build(&mut path);
1480 path.build()
1481 };
1482 let r = Rect::new(10.0, 10.0, 40.0, 20.0);
1483
1484 let rounded = built(&|p| {
1485 p.rrect_radii(r, [4.0, 6.0, 0.0, 2.0]);
1486 });
1487 let radii = [[4.0; 2], [6.0; 2], [0.0; 2], [2.0; 2]];
1488 assert_eq!(rounded.as_round_rect(), Some((r, radii)));
1489 assert_eq!(rounded.as_oval(), None);
1490
1491 let circle = built(&|p| {
1492 p.circle((5.0, 5.0), 5.0);
1493 });
1494 assert_eq!(circle.as_oval(), Some(Rect::new(0.0, 0.0, 10.0, 10.0)));
1495 let filled = built(&|p| {
1496 p.rrect_radii_elliptical(r, [[20.0, 10.0]; 4]);
1497 });
1498 assert_eq!(filled.as_oval(), Some(r));
1499 assert_eq!(filled.as_round_rect(), None);
1500
1501 for general in [
1502 built(&|p| {
1503 p.rect(r);
1504 }),
1505 built(&|p| {
1506 p.rrect(r, 0.0);
1507 }),
1508 built(&|p| {
1509 p.rect(r);
1510 p.rrect(r, 4.0);
1511 }),
1512 built(&|p| {
1513 p.circle((5.0, 5.0), 5.0);
1514 p.line_to((20.0, 20.0));
1515 }),
1516 ] {
1517 assert_eq!((general.as_oval(), general.as_round_rect()), (None, None));
1518 }
1519
1520 let after_a_move = built(&|p| {
1521 p.move_to((0.0, 0.0));
1522 p.rrect(r, 4.0);
1523 });
1524 assert!(
1525 after_a_move.as_round_rect().is_some(),
1526 "a move adds no segment"
1527 );
1528 }
1529
1530 fn round_rect_path(r: Rect, radii: [[f32; 2]; 4]) -> Arc<Path> {
1531 let mut path = PathBuilder::new();
1532 path.rrect_radii_elliptical(r, radii);
1533 path.build()
1534 }
1535
1536 const ROUND_RECT: Rect = Rect {
1537 x: 10.0,
1538 y: 20.0,
1539 width: 40.0,
1540 height: 30.0,
1541 };
1542 const RADII: [[f32; 2]; 4] = [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]];
1543
1544 #[test]
1547 fn a_translated_round_rect_or_oval_keeps_its_shape() {
1548 let moved = round_rect_path(ROUND_RECT, RADII).transformed(&Matrix::translation(5.0, -3.0));
1549 assert_eq!(
1550 moved.as_round_rect(),
1551 Some((Rect::new(15.0, 17.0, 40.0, 30.0), RADII))
1552 );
1553 assert_eq!(moved.bounds(), Rect::new(15.0, 17.0, 40.0, 30.0));
1554
1555 let mut circle = PathBuilder::new();
1556 circle.circle((5.0, 5.0), 5.0);
1557 let moved = circle.build().transformed(&Matrix::translation(10.0, 0.0));
1558 assert_eq!(moved.as_oval(), Some(Rect::new(10.0, 0.0, 10.0, 10.0)));
1559 }
1560
1561 #[test]
1565 fn a_rect_staying_transform_moves_the_corners_with_their_radii() {
1566 let path = round_rect_path(ROUND_RECT, RADII);
1567 let scaled = path.transformed(&Matrix::scale(2.0, 0.5));
1568 assert_eq!(
1569 scaled.as_round_rect(),
1570 Some((
1571 Rect::new(20.0, 10.0, 80.0, 15.0),
1572 [[2.0, 1.0], [6.0, 2.0], [10.0, 3.0], [14.0, 4.0]]
1573 ))
1574 );
1575 let mirrored = path.transformed(&Matrix::scale(-1.0, 1.0));
1576 assert_eq!(
1577 mirrored.as_round_rect(),
1578 Some((
1579 Rect::new(-50.0, 20.0, 40.0, 30.0),
1580 [RADII[1], RADII[0], RADII[3], RADII[2]]
1581 ))
1582 );
1583 let turned = path.transformed(&Matrix::from_affine(0.0, 1.0, -1.0, 0.0, 0.0, 0.0));
1586 let swapped = RADII.map(|[x, y]| [y, x]);
1587 assert_eq!(
1588 turned.as_round_rect(),
1589 Some((
1590 Rect::new(-50.0, 10.0, 30.0, 40.0),
1591 [swapped[3], swapped[0], swapped[1], swapped[2]]
1592 ))
1593 );
1594 }
1595
1596 #[test]
1599 fn any_other_transform_or_an_append_makes_a_general_path() {
1600 let path = round_rect_path(ROUND_RECT, RADII);
1601 let mut perspective = Matrix::IDENTITY.to_flutter_array();
1602 perspective[3] = 0.001;
1603 for transform in [
1604 Matrix::rotation(0.3),
1605 Matrix::from_affine(1.0, 0.0, 0.5, 1.0, 0.0, 0.0),
1606 Matrix::from_flutter_array(&perspective),
1607 Matrix::scale(0.0, 1.0),
1608 ] {
1609 let moved = path.transformed(&transform);
1610 assert_eq!((moved.as_oval(), moved.as_round_rect()), (None, None));
1611 }
1612 let mut appended = PathBuilder::new();
1613 appended.append(&path, &Matrix::translation(5.0, 0.0));
1614 assert_eq!(appended.build().as_round_rect(), None);
1615 }
1616
1617 #[test]
1621 fn a_transformed_path_maps_every_point() {
1622 let mut built = PathBuilder::new();
1623 built
1624 .move_to((0.0, 0.0))
1625 .line_to((10.0, 0.0))
1626 .conic_to((10.0, 10.0), (0.0, 10.0), 0.5)
1627 .close();
1628 let path = built.build();
1629 let transform = Matrix::rotation(0.4).then(&Matrix::scale(2.0, 3.0));
1630 let mut appended = PathBuilder::new();
1631 appended.append(&path, &transform);
1632 let appended = appended.build();
1633 let transformed = path.transformed(&transform);
1634 let elements: Vec<PathElement> = transformed.elements().collect();
1635 let appended_elements: Vec<PathElement> = appended.elements().collect();
1636 assert_eq!(elements, appended_elements[..elements.len()]);
1637 assert_eq!(transformed.bounds(), appended.bounds());
1638 }
1639
1640 use super::*;
1641
1642 #[test]
1649 fn opposed_windings_cancel_under_the_non_zero_rule() {
1650 let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
1651 let radii = [[12.0, 12.0]; 4];
1652 let inside = Point::new(50.0, 50.0);
1653
1654 let mut opposed = PathBuilder::new();
1655 opposed.rrect_radii_elliptical_wound(rect, radii, Winding::Clockwise);
1656 opposed.rrect_radii_elliptical_wound(rect, radii, Winding::CounterClockwise);
1657 assert!(
1658 !opposed.build().contains(inside, FillRule::NonZero),
1659 "opposed windings must cancel"
1660 );
1661
1662 let mut agreeing = PathBuilder::new();
1663 agreeing.rrect_radii_elliptical_wound(rect, radii, Winding::Clockwise);
1664 agreeing.rrect_radii_elliptical_wound(rect, radii, Winding::Clockwise);
1665 assert!(
1666 agreeing.build().contains(inside, FillRule::NonZero),
1667 "agreeing windings must reinforce"
1668 );
1669 }
1670
1671 #[test]
1675 fn winding_reverses_the_walk_without_moving_the_outline() {
1676 let rect = Rect::new(10.0, 20.0, 80.0, 60.0);
1677 let radii = [[8.0, 14.0], [4.0, 4.0], [20.0, 6.0], [0.0, 0.0]];
1678 let wound = |winding| {
1679 let mut path = PathBuilder::new();
1680 path.rrect_radii_elliptical_wound(rect, radii, winding);
1681 path.build()
1682 };
1683 let clockwise = wound(Winding::Clockwise);
1684 let counter = wound(Winding::CounterClockwise);
1685 assert_eq!(clockwise.tight_bounds(), counter.tight_bounds());
1686 for point in [
1689 Point::new(50.0, 50.0),
1690 Point::new(14.0, 30.0),
1691 Point::new(86.0, 24.0),
1692 Point::new(74.0, 76.0),
1693 Point::new(12.0, 78.0),
1694 Point::new(5.0, 15.0),
1695 Point::new(95.0, 85.0),
1696 ] {
1697 assert_eq!(
1698 clockwise.contains(point, FillRule::NonZero),
1699 counter.contains(point, FillRule::NonZero),
1700 "the two directions disagree about {point:?}"
1701 );
1702 }
1703 }
1704
1705 #[test]
1713 fn a_segment_after_close_resumes_at_the_contour_origin() {
1714 let mut path = PathBuilder::new();
1715 path.move_to((10.0, 10.0));
1716 path.line_to((30.0, 10.0));
1717 path.close();
1718 path.line_to((30.0, 30.0));
1719 let path = path.build();
1720
1721 let contours = path.flatten(0.05);
1723 let resumed = contours.last().expect("the path continues after the close");
1724 assert_eq!(
1725 resumed.points.first().copied(),
1726 Some(Point::new(10.0, 10.0)),
1727 "the segment after close must start at the contour origin, not its own end"
1728 );
1729 assert!(crate::stroke_contains(
1730 &contours,
1731 &crate::Stroke::new(6.0),
1732 0.05,
1733 Point::new(20.0, 20.0)
1734 ));
1735 }
1736
1737 #[test]
1745 fn a_segment_after_a_shape_helper_resumes_at_the_box_corner() {
1746 let box_corner = Point::new(10.0, 10.0);
1747 for corner in [0.0f32, 8.0] {
1748 let mut path = PathBuilder::new();
1749 if corner == 0.0 {
1750 path.rect(Rect::new(10.0, 10.0, 40.0, 40.0));
1751 } else {
1752 path.rrect_radii_elliptical(Rect::new(10.0, 10.0, 40.0, 40.0), [[corner; 2]; 4]);
1753 }
1754 path.line_to((90.0, 90.0));
1755
1756 let contours = path.build().flatten(0.05);
1757 let resumed = contours.last().expect("the path continues after the shape");
1758 assert_eq!(
1759 resumed.points.first().copied(),
1760 Some(box_corner),
1761 "corner radius {corner}: the trailing segment starts at (x, y)"
1762 );
1763 }
1764
1765 let mut path = PathBuilder::new();
1769 path.rrect_radii_elliptical(Rect::new(10.0, 10.0, 40.0, 40.0), [[8.0; 2]; 4]);
1770 path.line_to((90.0, 90.0));
1771 let contours = path.build().flatten(0.05);
1772 let stroke = crate::Stroke::new(4.0);
1773 assert!(
1774 crate::stroke_contains(&contours, &stroke, 0.05, Point::new(50.0, 50.0)),
1775 "the diagonal from (10,10) must be stroked"
1776 );
1777 assert!(
1778 !crate::stroke_contains(&contours, &stroke, 0.05, Point::new(54.0, 50.0)),
1779 "the diagonal from the tangent (18,10) must not be"
1780 );
1781 }
1782
1783 #[test]
1786 fn close_still_resumes_at_the_contour_origin() {
1787 let mut path = PathBuilder::new();
1788 path.move_to((10.0, 10.0));
1789 path.line_to((30.0, 10.0));
1790 path.line_to((30.0, 30.0));
1791 path.close();
1792 path.line_to((90.0, 90.0));
1793 let contours = path.build().flatten(0.05);
1794 assert_eq!(
1795 contours
1796 .last()
1797 .and_then(|contour| contour.points.first())
1798 .copied(),
1799 Some(Point::new(10.0, 10.0)),
1800 "close resumes where the contour began, not at any box corner"
1801 );
1802 }
1803
1804 #[test]
1807 fn a_first_segment_with_no_contour_starts_at_its_own_point() {
1808 let mut path = PathBuilder::new();
1809 path.line_to((30.0, 30.0));
1810 assert_eq!(
1811 path.build().bounds(),
1812 Rect::from_ltrb(30.0, 30.0, 30.0, 30.0)
1813 );
1814 }
1815
1816 #[test]
1817 fn append_carries_verbs_through_the_transform() {
1818 let mut source = PathBuilder::new();
1819 source.rect(Rect::new(0.0, 0.0, 10.0, 10.0));
1820 let source = source.build();
1821
1822 let mut target = PathBuilder::new();
1823 target.rect(Rect::new(0.0, 0.0, 4.0, 4.0));
1824 target.append(&source, &Matrix::translation(100.0, 50.0));
1825 let target = target.build();
1826
1827 assert_eq!(target.bounds(), Rect::from_ltrb(0.0, 0.0, 110.0, 60.0));
1828 assert!(target.contains(Point::new(105.0, 55.0), FillRule::NonZero));
1829 assert!(!target.contains(Point::new(5.0, 5.0), FillRule::NonZero));
1830 }
1831
1832 #[test]
1836 fn appending_a_closed_contour_reopens_at_its_seam() {
1837 let mut source = PathBuilder::new();
1838 source.move_to((10.0, 10.0));
1839 source.line_to((20.0, 10.0));
1840 source.close();
1841 let source = source.build();
1842
1843 let mut target = PathBuilder::new();
1844 target.append(&source, &Matrix::IDENTITY);
1845 target.line_to((10.0, 40.0));
1846 let built = target.build();
1847
1848 assert_eq!(built.bounds(), Rect::from_ltrb(10.0, 10.0, 20.0, 40.0));
1850 assert!(built.contains(Point::new(10.0, 25.0), FillRule::NonZero));
1851 }
1852
1853 #[test]
1857 fn appending_an_open_contour_hands_over_its_origin() {
1858 let mut source = PathBuilder::new();
1859 source.move_to((50.0, 50.0));
1860 source.line_to((60.0, 50.0));
1861 let source = source.build();
1862
1863 let mut target = PathBuilder::new();
1864 target.move_to((0.0, 0.0));
1865 target.line_to((10.0, 0.0));
1866 target.append(&source, &Matrix::IDENTITY);
1867 target.close();
1868 target.line_to((90.0, 90.0));
1869
1870 let contours = target.build().flatten(0.05);
1871 let resumed = contours.last().expect("the path continues after the close");
1872 assert_eq!(
1873 resumed.points.first().copied(),
1874 Some(Point::new(50.0, 50.0)),
1875 "the resumed segment must start at the APPENDED contour's origin"
1876 );
1877 }
1878
1879 #[test]
1880 fn appending_nothing_leaves_an_open_contour_open() {
1881 let empty = PathBuilder::new().build();
1882 let mut target = PathBuilder::new();
1883 target.move_to((0.0, 0.0));
1884 target.line_to((10.0, 0.0));
1885 target.append(&empty, &Matrix::IDENTITY);
1886 target.line_to((10.0, 10.0));
1887 assert_eq!(
1888 target.build().bounds(),
1889 Rect::from_ltrb(0.0, 0.0, 10.0, 10.0)
1890 );
1891 }
1892
1893 #[test]
1894 fn appending_an_open_contour_leaves_it_open() {
1895 let mut source = PathBuilder::new();
1896 source.move_to((0.0, 0.0));
1897 source.line_to((10.0, 0.0));
1898 let source = source.build();
1899
1900 let mut target = PathBuilder::new();
1901 target.append(&source, &Matrix::IDENTITY);
1902 target.line_to((10.0, 10.0));
1905 assert_eq!(
1906 target.build().bounds(),
1907 Rect::from_ltrb(0.0, 0.0, 10.0, 10.0)
1908 );
1909 }
1910
1911 #[test]
1912 fn tight_bounds_use_curve_extrema_not_control_points() {
1913 let mut path = PathBuilder::new();
1914 path.move_to((0.0, 0.0));
1915 path.quad_to((100.0, 100.0), (200.0, 0.0));
1916 let path = path.build();
1917 assert_eq!(path.bounds(), Rect::new(0.0, 0.0, 200.0, 100.0));
1918 assert_eq!(path.tight_bounds(), Rect::new(0.0, 0.0, 200.0, 50.0));
1919 }
1920
1921 #[test]
1922 fn tight_bounds_keep_extrema_below_f32_epsilon() {
1923 let mut path = PathBuilder::new();
1924 path.move_to((0.0, 0.0));
1925 path.quad_to((0.0, 1.0e-8), (0.0, 0.0));
1926 let bounds = path.build().tight_bounds();
1927 assert!((bounds.height - 5.0e-9).abs() < 1.0e-12);
1928 }
1929
1930 #[test]
1931 fn cubic_extrema_preserve_the_small_root() {
1932 let roots = cubic_extrema(0.0, 1.0e-8, -0.5, -0.5);
1933 assert!(roots
1934 .into_iter()
1935 .flatten()
1936 .any(|root| (root - 1.0e-8).abs() < 1.0e-10));
1937 }
1938
1939 #[test]
1940 fn radii_constrain_together() {
1941 let r = Rect::new(0.0, 0.0, 100.0, 40.0);
1942 let out = constrain_radii(&r, [40.0, 10.0, 10.0, 40.0]);
1944 assert_eq!(out, [20.0, 5.0, 5.0, 20.0]);
1945 assert_eq!(constrain_radii(&r, [8.0, 8.0, 8.0, 8.0]), [8.0; 4]);
1947 }
1948
1949 #[test]
1950 fn per_corner_rrect_stays_in_rect() {
1951 let r = Rect::new(10.0, 10.0, 100.0, 60.0);
1952 let mut b = PathBuilder::new();
1953 b.rrect_radii(r, [30.0, 0.0, 16.0, 8.0]);
1954 assert_eq!(b.build().bounds(), r);
1955 }
1956
1957 #[test]
1958 fn bounds_cover_control_points() {
1959 let mut b = PathBuilder::new();
1960 b.move_to((10.0, 10.0)).quad_to((50.0, -20.0), (90.0, 10.0));
1961 let p = b.build();
1962 assert_eq!(p.bounds(), Rect::from_ltrb(10.0, -20.0, 90.0, 10.0));
1963 }
1964
1965 #[test]
1966 fn circle_flattens_to_radius() {
1967 let mut b = PathBuilder::new();
1968 b.circle((0.0, 0.0), 100.0);
1969 let contours = b.build().flatten(0.1);
1970 assert_eq!(contours.len(), 1);
1971 assert!(contours[0].closed, "circle closes its contour");
1972 for p in &contours[0].points {
1973 let r = (p.x * p.x + p.y * p.y).sqrt();
1974 assert!((r - 100.0).abs() < 0.5, "point off circle: r={r}");
1975 }
1976 }
1977
1978 #[test]
1979 fn finer_tolerance_means_more_segments() {
1980 let path = {
1981 let mut b = PathBuilder::new();
1982 b.circle((0.0, 0.0), 100.0);
1983 b.build()
1984 };
1985 let coarse = path.flatten(2.0)[0].points.len();
1986 let fine = path.flatten(0.05)[0].points.len();
1987 assert!(fine > coarse, "fine {fine} vs coarse {coarse}");
1988 }
1989
1990 #[test]
1991 fn small_contours_survive_for_the_stroker() {
1992 let mut b = PathBuilder::new();
1993 b.move_to((0.0, 0.0)).line_to((10.0, 0.0)); b.move_to((50.0, 50.0)); let contours = b.build().flatten(0.1);
1996 assert_eq!(contours.len(), 2);
1997 assert_eq!(contours[0].points.len(), 2);
1998 assert!(!contours[0].closed);
1999 assert_eq!(contours[1].points.len(), 1);
2000 }
2001
2002 #[test]
2003 fn close_emits_the_closing_edge_and_marks_the_contour() {
2004 let mut b = PathBuilder::new();
2005 b.move_to((0.0, 0.0))
2006 .line_to((10.0, 0.0))
2007 .line_to((10.0, 10.0))
2008 .close();
2009 let contours = b.build().flatten(0.1);
2010 assert!(contours[0].closed);
2011 assert_eq!(contours[0].points.len(), 4, "closing edge in the polyline");
2012 assert_eq!(contours[0].points[3], Point::new(0.0, 0.0));
2013 }
2014
2015 #[test]
2016 fn bounds_keep_a_first_point_at_the_origin() {
2017 let mut b = PathBuilder::new();
2018 b.move_to((0.0, 0.0)).line_to((50.0, 80.0));
2019 assert_eq!(b.build().bounds(), Rect::from_ltrb(0.0, 0.0, 50.0, 80.0));
2020
2021 let mut b = PathBuilder::new();
2022 b.move_to((0.0, 0.0)).line_to((100.0, 0.0)); assert_eq!(b.build().bounds(), Rect::from_ltrb(0.0, 0.0, 100.0, 0.0));
2024 }
2025
2026 #[test]
2027 fn curve_without_move_starts_contour() {
2028 let mut b = PathBuilder::new();
2029 b.line_to((10.0, 0.0))
2030 .line_to((10.0, 10.0))
2031 .line_to((0.0, 10.0));
2032 let contours = b.build().flatten(0.1);
2033 assert_eq!(contours.len(), 1);
2034 assert_eq!(contours[0].points.len(), 4);
2035 }
2036
2037 #[test]
2041 fn circular_rrect_is_the_equal_axes_elliptical_case() {
2042 let r = Rect::new(10.0, 20.0, 120.0, 80.0);
2043 let radii = [24.0, 8.0, 30.0, 0.0];
2044 let mut circular = PathBuilder::new();
2045 circular.rrect_radii(r, radii);
2046 let mut elliptical = PathBuilder::new();
2047 elliptical.rrect_radii_elliptical(r, radii.map(|v| [v; 2]));
2048 assert_eq!(
2049 circular.build().flatten(0.1)[0].points,
2050 elliptical.build().flatten(0.1)[0].points,
2051 );
2052 }
2053
2054 #[test]
2055 fn elliptical_radii_constrain_per_axis() {
2056 let r = Rect::new(0.0, 0.0, 100.0, 40.0);
2059 let out = constrain_radii_elliptical(
2060 &r,
2061 [[10.0, 20.0], [10.0, 20.0], [10.0, 30.0], [10.0, 30.0]],
2062 );
2063 assert_eq!(out[0], [8.0, 16.0]);
2064 assert_eq!(out[2], [8.0, 24.0]);
2065 let out = constrain_radii_elliptical(&r, [[-5.0, 10.0], [0.0; 2], [0.0; 2], [0.0; 2]]);
2067 assert_eq!(out[0], [0.0, 10.0]);
2068 }
2069
2070 #[test]
2071 fn elliptical_corner_lands_on_axis_extremes() {
2072 let r = Rect::new(0.0, 0.0, 200.0, 100.0);
2075 let mut b = PathBuilder::new();
2076 b.rrect_radii_elliptical(r, [[0.0; 2], [40.0, 10.0], [0.0; 2], [0.0; 2]]);
2077 let points = &b.build().flatten(0.05)[0].points;
2078 assert!(points
2081 .iter()
2082 .any(|p| (p.x - 160.0).abs() < 0.5 && p.y.abs() < 0.5));
2083 assert!(points
2084 .iter()
2085 .any(|p| (p.x - 200.0).abs() < 0.5 && (p.y - 10.0).abs() < 0.5));
2086 }
2087
2088 #[test]
2093 fn swept_arc_stays_on_its_circle() {
2094 let (center, radius) = (Point::new(50.0, 60.0), 40.0);
2095 let mut b = PathBuilder::new();
2096 b.arc(center, radius, 0.0, std::f32::consts::TAU);
2097 for point in &b.build().flatten(0.01)[0].points {
2098 let offset = (point.x - center.x).hypot(point.y - center.y);
2099 assert!(
2100 (offset - radius).abs() < 0.05,
2101 "point {point:?} is {offset} from the centre, not {radius}"
2102 );
2103 }
2104 }
2105
2106 #[test]
2108 fn quarter_arc_ends_where_it_should() {
2109 let mut b = PathBuilder::new();
2110 b.arc((0.0, 0.0), 100.0, 0.0, std::f32::consts::FRAC_PI_2);
2111 let points = &b.build().flatten(0.01)[0].points;
2112 let (first, last) = (points[0], *points.last().unwrap());
2113 assert!(
2114 (first.x - 100.0).abs() < 0.01 && first.y.abs() < 0.01,
2115 "{first:?}"
2116 );
2117 assert!(
2118 last.x.abs() < 0.05 && (last.y - 100.0).abs() < 0.05,
2119 "{last:?}"
2120 );
2121 }
2122
2123 #[test]
2125 fn ellipse_reaches_both_radii() {
2126 let mut b = PathBuilder::new();
2127 b.ellipse((0.0, 0.0), [80.0, 20.0], 0.0, 0.0, std::f32::consts::TAU);
2128 let points = &b.build().flatten(0.01)[0].points;
2129 let widest = points.iter().fold(0.0f32, |m, p| m.max(p.x.abs()));
2130 let tallest = points.iter().fold(0.0f32, |m, p| m.max(p.y.abs()));
2131 assert!((widest - 80.0).abs() < 0.1, "widest {widest}");
2132 assert!((tallest - 20.0).abs() < 0.1, "tallest {tallest}");
2133 }
2134
2135 #[test]
2137 fn ellipse_rotation_swaps_the_axes() {
2138 let mut b = PathBuilder::new();
2139 b.ellipse(
2140 (0.0, 0.0),
2141 [80.0, 20.0],
2142 std::f32::consts::FRAC_PI_2,
2143 0.0,
2144 std::f32::consts::TAU,
2145 );
2146 let points = &b.build().flatten(0.01)[0].points;
2147 let widest = points.iter().fold(0.0f32, |m, p| m.max(p.x.abs()));
2148 let tallest = points.iter().fold(0.0f32, |m, p| m.max(p.y.abs()));
2149 assert!((widest - 20.0).abs() < 0.1, "widest {widest}");
2150 assert!((tallest - 80.0).abs() < 0.1, "tallest {tallest}");
2151 }
2152
2153 #[test]
2157 fn arc_to_rounds_a_right_angle() {
2158 let radius = 20.0f32;
2159 let mut b = PathBuilder::new();
2160 b.move_to((0.0, 0.0))
2161 .arc_to((100.0, 0.0), (100.0, 100.0), radius);
2162 let points = &b.build().flatten(0.01)[0].points;
2163
2164 let entry = Point::new(100.0 - radius, 0.0);
2165 let exit = Point::new(100.0, radius);
2166 assert!(points
2167 .iter()
2168 .any(|p| (p.x - entry.x).abs() < 0.1 && (p.y - entry.y).abs() < 0.1));
2169 assert!(points
2170 .iter()
2171 .any(|p| (p.x - exit.x).abs() < 0.1 && (p.y - exit.y).abs() < 0.1));
2172
2173 let center = Point::new(100.0 - radius, radius);
2174 for point in points.iter().filter(|p| p.x > entry.x - 0.01) {
2175 let offset = (point.x - center.x).hypot(point.y - center.y);
2176 assert!(
2177 (offset - radius).abs() < 0.1,
2178 "{point:?} is {offset} from the centre"
2179 );
2180 }
2181 }
2182
2183 #[test]
2186 fn degenerate_arc_to_falls_back_to_a_line() {
2187 for (corner, next, radius) in [
2188 ((50.0, 0.0), (100.0, 0.0), 20.0), ((50.0, 0.0), (50.0, 50.0), 0.0), ] {
2191 let mut b = PathBuilder::new();
2192 b.move_to((0.0, 0.0)).arc_to(corner, next, radius);
2193 let points = &b.build().flatten(0.01)[0].points;
2194 assert_eq!(points.len(), 2, "expected a bare line, got {points:?}");
2195 assert!((points[1].x - corner.0).abs() < 0.01 && (points[1].y - corner.1).abs() < 0.01);
2196 }
2197 }
2198
2199 #[test]
2202 fn rect_contains_what_it_covers() {
2203 let mut b = PathBuilder::new();
2204 b.rect(Rect::new(10.0, 10.0, 80.0, 60.0));
2205 let path = b.build();
2206 assert!(path.contains(Point::new(50.0, 40.0), FillRule::NonZero));
2207 assert!(!path.contains(Point::new(5.0, 40.0), FillRule::NonZero));
2208 assert!(!path.contains(Point::new(50.0, 80.0), FillRule::NonZero));
2209 for on_outline in [
2212 Point::new(10.0, 40.0), Point::new(50.0, 10.0), Point::new(90.0, 40.0), Point::new(50.0, 70.0), Point::new(90.0, 70.0), ] {
2218 assert!(
2219 path.contains(on_outline, FillRule::NonZero),
2220 "{on_outline:?} is on the outline and must count as inside"
2221 );
2222 }
2223 }
2224
2225 #[test]
2229 fn an_enormous_sweep_stays_one_turn() {
2230 let mut b = PathBuilder::new();
2231 b.arc((0.0, 0.0), 50.0, 0.0, 1e20);
2232 let path = b.build();
2233 let contours = path.flatten(0.1);
2234 assert_eq!(contours.len(), 1);
2235 assert!(
2237 contours[0].points.len() < 1_000,
2238 "a clamped turn should stay small, got {}",
2239 contours[0].points.len()
2240 );
2241 assert!(contours[0].closed, "a full turn closes its contour");
2242 }
2243
2244 #[test]
2245 fn a_negative_sweep_turns_the_other_way() {
2246 let quarter = std::f32::consts::FRAC_PI_2;
2247 let mut clockwise = PathBuilder::new();
2248 clockwise.arc((0.0, 0.0), 50.0, 0.0, quarter);
2249 let mut anticlockwise = PathBuilder::new();
2250 anticlockwise.arc((0.0, 0.0), 50.0, 0.0, -quarter);
2251
2252 let forward = clockwise.build().bounds();
2255 let backward = anticlockwise.build().bounds();
2256 assert!(forward.bottom() > 40.0, "positive sweep reaches +y");
2257 assert!(backward.y < -40.0, "negative sweep reaches -y");
2258 }
2259
2260 #[test]
2263 fn circle_containment_is_exact_all_the_way_round() {
2264 let (center, radius) = (Point::new(0.0, 0.0), 100.0f32);
2265 let mut b = PathBuilder::new();
2266 b.circle(center, radius);
2267 let path = b.build();
2268 for step in 0..64 {
2269 let angle = step as f32 / 64.0 * std::f32::consts::TAU;
2270 let (sine, cosine) = angle.sin_cos();
2271 let inside = Point::new(cosine * radius * 0.99, sine * radius * 0.99);
2272 let outside = Point::new(cosine * radius * 1.01, sine * radius * 1.01);
2273 assert!(
2274 path.contains(inside, FillRule::NonZero),
2275 "{inside:?} should be in"
2276 );
2277 assert!(
2278 !path.contains(outside, FillRule::NonZero),
2279 "{outside:?} should be out"
2280 );
2281 }
2282 }
2283
2284 #[test]
2288 fn fill_rules_disagree_about_a_same_wound_hole() {
2289 let mut b = PathBuilder::new();
2290 b.rect(Rect::new(0.0, 0.0, 100.0, 100.0));
2291 b.rect(Rect::new(25.0, 25.0, 50.0, 50.0));
2292 let path = b.build();
2293 let middle = Point::new(50.0, 50.0);
2294 assert!(path.contains(middle, FillRule::NonZero));
2295 assert!(!path.contains(middle, FillRule::EvenOdd));
2296 let ring = Point::new(10.0, 50.0);
2298 assert!(path.contains(ring, FillRule::NonZero));
2299 assert!(path.contains(ring, FillRule::EvenOdd));
2300 }
2301
2302 #[test]
2304 fn open_contour_closes_implicitly() {
2305 let mut b = PathBuilder::new();
2306 b.move_to((0.0, 0.0))
2307 .line_to((100.0, 0.0))
2308 .line_to((100.0, 100.0));
2309 let path = b.build();
2310 assert!(path.contains(Point::new(80.0, 40.0), FillRule::NonZero));
2311 assert!(!path.contains(Point::new(20.0, 60.0), FillRule::NonZero));
2312 }
2313
2314 #[test]
2316 fn containment_handles_curves_that_double_back() {
2317 let mut b = PathBuilder::new();
2318 b.move_to((0.0, 0.0))
2319 .cubic_to((120.0, 120.0), (-20.0, 120.0), (100.0, 0.0))
2320 .close();
2321 let path = b.build();
2322 assert!(path.contains(Point::new(50.0, 40.0), FillRule::NonZero));
2323 assert!(!path.contains(Point::new(50.0, -10.0), FillRule::NonZero));
2324 assert!(!path.contains(Point::new(-30.0, 40.0), FillRule::NonZero));
2325 }
2326
2327 #[test]
2334 fn circle_flattens_onto_the_exact_circle() {
2335 let mut b = PathBuilder::new();
2336 b.circle((10.0, -20.0), 100.0);
2337 let contours = b.build().flatten(0.1);
2338 let points: Vec<Point> = contours.iter().flat_map(|c| c.points.clone()).collect();
2339 assert!(points.len() > 20);
2340 for p in &points {
2341 let distance = (p.x - 10.0).hypot(p.y + 20.0);
2342 assert!(
2343 (distance - 100.0).abs() < 2e-3,
2344 "{p:?} is off the circle by {}",
2345 (distance - 100.0).abs()
2346 );
2347 }
2348 }
2349
2350 #[test]
2353 fn ellipse_arc_flattens_onto_the_exact_ellipse() {
2354 let mut b = PathBuilder::new();
2355 let rotation = 0.5f32;
2356 b.ellipse((5.0, 7.0), [80.0, 30.0], rotation, 0.3, 4.0);
2357 let contours = b.build().flatten(0.05);
2358 let (sin_r, cos_r) = rotation.sin_cos();
2359 for p in contours.iter().flat_map(|c| &c.points) {
2360 let (dx, dy) = (p.x - 5.0, p.y - 7.0);
2361 let (ux, uy) = (dx * cos_r + dy * sin_r, -dx * sin_r + dy * cos_r);
2363 let value = (ux / 80.0).powi(2) + (uy / 30.0).powi(2);
2364 assert!((value - 1.0).abs() < 1e-3, "{p:?} deviates: {value}");
2365 }
2366 }
2367
2368 #[test]
2372 fn conic_circle_tight_bounds_are_exact() {
2373 let mut b = PathBuilder::new();
2374 b.circle((0.0, 0.0), 50.0);
2375 let tight = b.build().tight_bounds();
2376 for (got, want) in [
2377 (tight.x, -50.0),
2378 (tight.y, -50.0),
2379 (tight.right(), 50.0),
2380 (tight.bottom(), 50.0),
2381 ] {
2382 assert!((got - want).abs() < 1e-3, "bound {got} should be {want}");
2383 }
2384 let mut arc = PathBuilder::new();
2387 arc.arc((0.0, 0.0), 50.0, -3.0, 2.5);
2388 let tight = arc.build().tight_bounds();
2389 assert!((tight.y + 50.0).abs() < 1e-3, "arc top: {}", tight.y);
2390 }
2391
2392 #[test]
2395 fn conic_containment_is_exact_on_the_curve() {
2396 let mut b = PathBuilder::new();
2397 b.circle((0.0, 0.0), 100.0);
2398 let path = b.build();
2399 for i in 0..64 {
2400 let angle = i as f32 / 64.0 * std::f32::consts::TAU;
2401 let (s, c) = angle.sin_cos();
2402 let inside = Point::new(c * 99.95, s * 99.95);
2403 let outside = Point::new(c * 100.05, s * 100.05);
2404 assert!(
2405 path.contains(inside, FillRule::NonZero),
2406 "{inside:?} at angle {i} should be inside"
2407 );
2408 assert!(
2409 !path.contains(outside, FillRule::NonZero),
2410 "{outside:?} at angle {i} should be outside"
2411 );
2412 }
2413 }
2414
2415 #[test]
2418 fn conic_windings_cancel_under_the_non_zero_rule() {
2419 let mut b = PathBuilder::new();
2420 b.circle((0.0, 0.0), 100.0);
2421 let w = std::f32::consts::FRAC_1_SQRT_2;
2424 b.move_to((60.0, 0.0))
2425 .conic_to((60.0, -60.0), (0.0, -60.0), w)
2426 .conic_to((-60.0, -60.0), (-60.0, 0.0), w)
2427 .conic_to((-60.0, 60.0), (0.0, 60.0), w)
2428 .conic_to((60.0, 60.0), (60.0, 0.0), w)
2429 .close();
2430 let path = b.build();
2431 assert!(!path.contains(Point::new(0.0, 0.0), FillRule::NonZero));
2432 assert!(path.contains(Point::new(80.0, 0.0), FillRule::NonZero));
2433 }
2434
2435 #[test]
2438 fn append_preserves_conic_weights() {
2439 let mut source = PathBuilder::new();
2440 source.circle((0.0, 0.0), 40.0);
2441 let source = source.build();
2442 let mut b = PathBuilder::new();
2443 b.append(&source, &Matrix::rotation(0.7));
2444 for p in b.build().flatten(0.05).iter().flat_map(|c| &c.points) {
2445 let distance = p.x.hypot(p.y);
2446 assert!((distance - 40.0).abs() < 1e-3, "{p:?} off by {distance}");
2447 }
2448 }
2449
2450 #[test]
2453 fn degenerate_conic_weights_lower_to_simpler_verbs() {
2454 let mut zero = PathBuilder::new();
2455 zero.move_to((0.0, 0.0))
2456 .conic_to((50.0, 50.0), (100.0, 0.0), 0.0);
2457 let contour = &zero.build().flatten(0.1)[0];
2458 assert_eq!(contour.points.len(), 2, "weight 0 must be a straight line");
2459
2460 let mut quad = PathBuilder::new();
2461 quad.move_to((0.0, 0.0))
2462 .conic_to((50.0, 50.0), (100.0, 0.0), 1.0);
2463 let mut plain = PathBuilder::new();
2464 plain
2465 .move_to((0.0, 0.0))
2466 .quad_to((50.0, 50.0), (100.0, 0.0));
2467 assert_eq!(
2468 quad.build().flatten(0.1),
2469 plain.build().flatten(0.1),
2470 "weight 1 must match the plain quadratic"
2471 );
2472
2473 let mut infinite = PathBuilder::new();
2474 infinite
2475 .move_to((0.0, 0.0))
2476 .conic_to((50.0, 50.0), (100.0, 0.0), f32::INFINITY);
2477 let contour = &infinite.build().flatten(0.1)[0];
2478 assert_eq!(
2479 contour.points,
2480 vec![
2481 Point::new(0.0, 0.0),
2482 Point::new(50.0, 50.0),
2483 Point::new(100.0, 0.0)
2484 ],
2485 "an unbounded weight collapses onto the control polygon"
2486 );
2487 }
2488
2489 #[test]
2495 fn conic_extrema_survive_large_coordinates() {
2496 let p0 = Point::new(0.0, 442_027.38);
2497 let c = Point::new(50.0, 442_028.47);
2498 let p2 = Point::new(100.0, 442_027.03);
2499 let w = 20.189_045;
2500 let mut b = PathBuilder::new();
2501 b.move_to(p0).conic_to(c, p2, w).close();
2502 let path = b.build();
2503 let bottom = path.tight_bounds().bottom();
2504 assert!(
2505 (bottom - 442_028.4).abs() < 0.05,
2506 "tight bottom {bottom} should reach the true maximum ~442028.41"
2507 );
2508 assert!(
2509 path.contains(Point::new(49.660_536, 442_028.0), FillRule::NonZero),
2510 "an interior point above the chord must be inside"
2511 );
2512 }
2513
2514 #[test]
2519 fn conic_flattening_respects_tolerance_for_large_weights() {
2520 let (p0, c, p2, w) = (
2521 Point::new(0.0, 100.0),
2522 Point::new(35.0, 100.0),
2523 Point::new(40.0, 90.0),
2524 8.3f32,
2525 );
2526 let tolerance = 0.05f32;
2527 let mut b = PathBuilder::new();
2528 b.move_to(p0).conic_to(c, p2, w);
2529 let contour = &b.build().flatten(tolerance)[0];
2530 let reference: Vec<Point> = (0..=4096)
2532 .map(|i| eval_conic(p0, c, p2, w, i as f32 / 4096.0))
2533 .collect();
2534 for pair in contour.points.windows(2) {
2535 let mid = Point::new((pair[0].x + pair[1].x) / 2.0, (pair[0].y + pair[1].y) / 2.0);
2536 let distance = reference
2537 .iter()
2538 .map(|r| (r.x - mid.x).hypot(r.y - mid.y))
2539 .fold(f32::MAX, f32::min);
2540 assert!(
2541 distance <= tolerance * 1.1,
2542 "chord midpoint {mid:?} is {distance} off the curve"
2543 );
2544 }
2545 }
2546}
2547
2548#[cfg(test)]
2549mod element_tests {
2550 use super::*;
2551
2552 #[test]
2553 fn elements_rebuild_an_equal_path() {
2554 let mut builder = PathBuilder::new();
2555 builder
2556 .move_to((0.0, 0.0))
2557 .line_to((10.0, 0.0))
2558 .quad_to((10.0, 5.0), (10.0, 10.0))
2559 .conic_to((5.0, 10.0), (0.0, 10.0), 0.7)
2560 .cubic_to((0.0, 7.0), (0.0, 3.0), (0.0, 0.0))
2561 .close();
2562 let path = builder.build();
2563 let mut rebuilt = PathBuilder::new();
2564 for element in path.elements() {
2565 match element {
2566 PathElement::MoveTo(p) => rebuilt.move_to(p),
2567 PathElement::LineTo(p) => rebuilt.line_to(p),
2568 PathElement::QuadTo(c, p) => rebuilt.quad_to(c, p),
2569 PathElement::ConicTo(c, p, w) => rebuilt.conic_to(c, p, w),
2570 PathElement::CubicTo(a, b, p) => rebuilt.cubic_to(a, b, p),
2571 PathElement::Close => rebuilt.close(),
2572 };
2573 }
2574 let rebuilt = rebuilt.build();
2575 assert_eq!(path.elements().count(), 6);
2576 assert_eq!(rebuilt.bounds(), path.bounds());
2577 assert!(path.elements().eq(rebuilt.elements()));
2578 }
2579}