1use core::ops::{Mul, Range};
7
8use arrayvec::ArrayVec;
9
10use crate::common::solve_cubic;
11use crate::MAX_EXTREMA;
12use crate::{
13 Affine, CubicBez, Line, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea,
14 ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, PathEl, Point,
15 Rect, Shape,
16};
17
18#[cfg(not(feature = "std"))]
19use crate::common::FloatFuncs;
20
21#[derive(Clone, Copy, Debug, PartialEq)]
23#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
24#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
25#[allow(missing_docs)]
26pub struct QuadBez {
27 pub p0: Point,
28 pub p1: Point,
29 pub p2: Point,
30}
31
32impl QuadBez {
33 #[inline]
35 pub fn new<V: Into<Point>>(p0: V, p1: V, p2: V) -> QuadBez {
36 QuadBez {
37 p0: p0.into(),
38 p1: p1.into(),
39 p2: p2.into(),
40 }
41 }
42
43 #[inline]
47 pub fn raise(&self) -> CubicBez {
48 CubicBez::new(
49 self.p0,
50 self.p0 + (2.0 / 3.0) * (self.p1 - self.p0),
51 self.p2 + (2.0 / 3.0) * (self.p1 - self.p2),
52 self.p2,
53 )
54 }
55
56 pub(crate) fn estimate_subdiv(&self, sqrt_tol: f64) -> FlattenParams {
58 let d01 = self.p1 - self.p0;
60 let d12 = self.p2 - self.p1;
61 let dd = d01 - d12;
62 let cross = (self.p2 - self.p0).cross(dd);
63 let x0 = d01.dot(dd) * cross.recip();
64 let x2 = d12.dot(dd) * cross.recip();
65 let scale = (cross / (dd.hypot() * (x2 - x0))).abs();
66
67 let a0 = approx_parabola_integral(x0);
69 let a2 = approx_parabola_integral(x2);
70 let val = if scale.is_finite() {
71 let da = (a2 - a0).abs();
72 let sqrt_scale = scale.sqrt();
73 if x0.signum() == x2.signum() {
74 da * sqrt_scale
75 } else {
76 let xmin = sqrt_tol / sqrt_scale;
78 sqrt_tol * da / approx_parabola_integral(xmin)
79 }
80 } else {
81 0.0
82 };
83 let u0 = approx_parabola_inv_integral(a0);
84 let u2 = approx_parabola_inv_integral(a2);
85 let uscale = (u2 - u0).recip();
86 FlattenParams {
87 a0,
88 a2,
89 u0,
90 uscale,
91 val,
92 }
93 }
94
95 pub(crate) fn determine_subdiv_t(&self, params: &FlattenParams, x: f64) -> f64 {
97 let a = params.a0 + (params.a2 - params.a0) * x;
98 let u = approx_parabola_inv_integral(a);
99 (u - params.u0) * params.uscale
100 }
101
102 #[inline]
104 pub const fn is_finite(&self) -> bool {
105 self.p0.is_finite() && self.p1.is_finite() && self.p2.is_finite()
106 }
107
108 #[inline]
110 pub const fn is_nan(&self) -> bool {
111 self.p0.is_nan() || self.p1.is_nan() || self.p2.is_nan()
112 }
113}
114
115pub struct QuadBezIter {
117 quad: QuadBez,
118 ix: usize,
119}
120
121impl Shape for QuadBez {
122 type PathElementsIter<'iter> = QuadBezIter;
123
124 #[inline]
125 fn path_elements(&self, _tolerance: f64) -> QuadBezIter {
126 QuadBezIter { quad: *self, ix: 0 }
127 }
128
129 fn area(&self) -> f64 {
130 0.0
131 }
132
133 #[inline]
134 fn perimeter(&self, accuracy: f64) -> f64 {
135 self.arclen(accuracy)
136 }
137
138 fn winding(&self, _pt: Point) -> i32 {
139 0
140 }
141
142 #[inline]
143 fn bounding_box(&self) -> Rect {
144 ParamCurveExtrema::bounding_box(self)
145 }
146}
147
148impl Iterator for QuadBezIter {
149 type Item = PathEl;
150
151 fn next(&mut self) -> Option<PathEl> {
152 self.ix += 1;
153 match self.ix {
154 1 => Some(PathEl::MoveTo(self.quad.p0)),
155 2 => Some(PathEl::QuadTo(self.quad.p1, self.quad.p2)),
156 _ => None,
157 }
158 }
159}
160
161pub(crate) struct FlattenParams {
162 a0: f64,
163 a2: f64,
164 u0: f64,
165 uscale: f64,
166 pub(crate) val: f64,
168}
169
170fn approx_parabola_integral(x: f64) -> f64 {
174 const D: f64 = 0.67;
175 x / (1.0 - D + (D.powi(4) + 0.25 * x * x).sqrt().sqrt())
176}
177
178fn approx_parabola_inv_integral(x: f64) -> f64 {
180 const B: f64 = 0.39;
181 x * (1.0 - B + (B * B + 0.25 * x * x).sqrt())
182}
183
184impl ParamCurve for QuadBez {
185 #[inline]
186 fn eval(&self, t: f64) -> Point {
187 let mt = 1.0 - t;
188 (self.p0.to_vec2() * (mt * mt)
189 + (self.p1.to_vec2() * (mt * 2.0) + self.p2.to_vec2() * t) * t)
190 .to_point()
191 }
192
193 fn subsegment(&self, range: Range<f64>) -> QuadBez {
194 let (t0, t1) = (range.start, range.end);
195 let p0 = self.eval(t0);
196 let p2 = self.eval(t1);
197 let p1 = p0 + (self.p1 - self.p0).lerp(self.p2 - self.p1, t0) * (t1 - t0);
198 QuadBez { p0, p1, p2 }
199 }
200
201 #[inline]
203 fn subdivide(&self) -> (QuadBez, QuadBez) {
204 let pm = self.eval(0.5);
205 (
206 QuadBez::new(self.p0, self.p0.midpoint(self.p1), pm),
207 QuadBez::new(pm, self.p1.midpoint(self.p2), self.p2),
208 )
209 }
210
211 #[inline]
212 fn start(&self) -> Point {
213 self.p0
214 }
215
216 #[inline]
217 fn end(&self) -> Point {
218 self.p2
219 }
220}
221
222impl ParamCurveDeriv for QuadBez {
223 type DerivResult = Line;
224
225 #[inline]
226 fn deriv(&self) -> Line {
227 Line::new(
228 (2.0 * (self.p1.to_vec2() - self.p0.to_vec2())).to_point(),
229 (2.0 * (self.p2.to_vec2() - self.p1.to_vec2())).to_point(),
230 )
231 }
232}
233
234impl ParamCurveArclen for QuadBez {
235 fn arclen(&self, _accuracy: f64) -> f64 {
246 let d2 = self.p0.to_vec2() - 2.0 * self.p1.to_vec2() + self.p2.to_vec2();
247 let a = d2.hypot2();
248 let d1 = self.p1 - self.p0;
249 let c = d1.hypot2();
250 if a < 5e-4 * c {
251 let v0 = (-0.492943519233745 * self.p0.to_vec2()
256 + 0.430331482911935 * self.p1.to_vec2()
257 + 0.0626120363218102 * self.p2.to_vec2())
258 .hypot();
259 let v1 = ((self.p2 - self.p0) * 0.4444444444444444).hypot();
260 let v2 = (-0.0626120363218102 * self.p0.to_vec2()
261 - 0.430331482911935 * self.p1.to_vec2()
262 + 0.492943519233745 * self.p2.to_vec2())
263 .hypot();
264 return v0 + v1 + v2;
265 }
266 let b = 2.0 * d2.dot(d1);
267
268 let sabc = (a + b + c).sqrt();
269 let a2 = a.powf(-0.5);
270 let a32 = a2.powi(3);
271 let c2 = 2.0 * c.sqrt();
272 let ba_c2 = b * a2 + c2;
273
274 let v0 = 0.25 * a2 * a2 * b * (2.0 * sabc - c2) + sabc;
275 if ba_c2 * a2 < 1e-13 {
282 v0
284 } else {
285 v0 + 0.25
286 * a32
287 * (4.0 * c * a - b * b)
288 * (((2.0 * a + b) * a2 + 2.0 * sabc) / ba_c2).ln()
289 }
290 }
291}
292
293impl ParamCurveArea for QuadBez {
294 #[inline]
295 fn signed_area(&self) -> f64 {
296 (self.p0.x * (2.0 * self.p1.y + self.p2.y) + 2.0 * self.p1.x * (self.p2.y - self.p0.y)
297 - self.p2.x * (self.p0.y + 2.0 * self.p1.y))
298 * (1.0 / 6.0)
299 }
300}
301
302impl ParamCurveNearest for QuadBez {
303 fn nearest(&self, p: Point, _accuracy: f64) -> Nearest {
305 fn eval_t(p: Point, t_best: &mut f64, r_best: &mut Option<f64>, t: f64, p0: Point) {
306 let r = (p0 - p).hypot2();
307 if r_best.map(|r_best| r < r_best).unwrap_or(true) {
308 *r_best = Some(r);
309 *t_best = t;
310 }
311 }
312 fn try_t(
313 q: &QuadBez,
314 p: Point,
315 t_best: &mut f64,
316 r_best: &mut Option<f64>,
317 t: f64,
318 ) -> bool {
319 if !(0.0..=1.0).contains(&t) {
320 return true;
321 }
322 eval_t(p, t_best, r_best, t, q.eval(t));
323 false
324 }
325 let d0 = self.p1 - self.p0;
326 let d1 = self.p0.to_vec2() + self.p2.to_vec2() - 2.0 * self.p1.to_vec2();
327 let d = self.p0 - p;
328 let c0 = d.dot(d0);
329 let c1 = 2.0 * d0.hypot2() + d.dot(d1);
330 let c2 = 3.0 * d1.dot(d0);
331 let c3 = d1.hypot2();
332 let roots = solve_cubic(c0, c1, c2, c3);
333 let mut r_best = None;
334 let mut t_best = 0.0;
335 let mut need_ends = false;
336 if roots.is_empty() {
337 need_ends = true;
338 }
339 for &t in &roots {
340 need_ends |= try_t(self, p, &mut t_best, &mut r_best, t);
341 }
342 if need_ends {
343 eval_t(p, &mut t_best, &mut r_best, 0.0, self.p0);
344 eval_t(p, &mut t_best, &mut r_best, 1.0, self.p2);
345 }
346
347 Nearest {
348 t: t_best,
349 distance_sq: r_best.unwrap(),
350 }
351 }
352}
353
354impl ParamCurveCurvature for QuadBez {}
355
356impl ParamCurveExtrema for QuadBez {
357 fn extrema(&self) -> ArrayVec<f64, MAX_EXTREMA> {
358 let mut result = ArrayVec::new();
359 let d0 = self.p1 - self.p0;
360 let d1 = self.p2 - self.p1;
361 let dd = d1 - d0;
362 if dd.x != 0.0 {
363 let t = -d0.x / dd.x;
364 if t > 0.0 && t < 1.0 {
365 result.push(t);
366 }
367 }
368 if dd.y != 0.0 {
369 let t = -d0.y / dd.y;
370 if t > 0.0 && t < 1.0 {
371 result.push(t);
372 if result.len() == 2 && result[0] > t {
373 result.swap(0, 1);
374 }
375 }
376 }
377 result
378 }
379}
380
381impl Mul<QuadBez> for Affine {
382 type Output = QuadBez;
383
384 #[inline]
385 fn mul(self, other: QuadBez) -> QuadBez {
386 QuadBez {
387 p0: self * other.p0,
388 p1: self * other.p1,
389 p2: self * other.p2,
390 }
391 }
392}
393
394#[cfg(test)]
395mod tests {
396 use crate::{
397 Affine, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveDeriv,
398 ParamCurveExtrema, ParamCurveNearest, Point, QuadBez,
399 };
400
401 fn assert_near(p0: Point, p1: Point, epsilon: f64) {
402 assert!((p1 - p0).hypot() < epsilon, "{p0:?} != {p1:?}");
403 }
404
405 #[test]
406 fn quadbez_deriv() {
407 let q = QuadBez::new((0.0, 0.0), (0.0, 0.5), (1.0, 1.0));
408 let deriv = q.deriv();
409
410 let n = 10;
411 for i in 0..=n {
412 let t = (i as f64) * (n as f64).recip();
413 let delta = 1e-6;
414 let p = q.eval(t);
415 let p1 = q.eval(t + delta);
416 let d_approx = (p1 - p) * delta.recip();
417 let d = deriv.eval(t).to_vec2();
418 assert!((d - d_approx).hypot() < delta * 2.0);
419 }
420 }
421
422 #[test]
423 fn quadbez_arclen() {
424 let q = QuadBez::new((0.0, 0.0), (0.0, 0.5), (1.0, 1.0));
425 let true_arclen = 0.5 * 5.0f64.sqrt() + 0.25 * (2.0 + 5.0f64.sqrt()).ln();
426 for i in 0..12 {
427 let accuracy = 0.1f64.powi(i);
428 let est = q.arclen(accuracy);
429 let error = est - true_arclen;
430 assert!(error.abs() < accuracy, "{est} != {true_arclen}");
431 }
432 }
433
434 #[test]
435 fn quadbez_arclen_pathological() {
436 let q = QuadBez::new((-1.0, 0.0), (1.03, 0.0), (1.0, 0.0));
437 let true_arclen = 2.0008737864167325; let accuracy = 1e-11;
439 let est = q.arclen(accuracy);
440 assert!(
441 (est - true_arclen).abs() < accuracy,
442 "{est} != {true_arclen}"
443 );
444 }
445
446 #[test]
447 fn quadbez_subsegment() {
448 let q = QuadBez::new((3.1, 4.1), (5.9, 2.6), (5.3, 5.8));
449 let t0 = 0.1;
450 let t1 = 0.8;
451 let qs = q.subsegment(t0..t1);
452 let epsilon = 1e-12;
453 let n = 10;
454 for i in 0..=n {
455 let t = (i as f64) * (n as f64).recip();
456 let ts = t0 + t * (t1 - t0);
457 assert_near(q.eval(ts), qs.eval(t), epsilon);
458 }
459 }
460
461 #[test]
462 fn quadbez_raise() {
463 let q = QuadBez::new((3.1, 4.1), (5.9, 2.6), (5.3, 5.8));
464 let c = q.raise();
465 let qd = q.deriv();
466 let cd = c.deriv();
467 let epsilon = 1e-12;
468 let n = 10;
469 for i in 0..=n {
470 let t = (i as f64) * (n as f64).recip();
471 assert_near(q.eval(t), c.eval(t), epsilon);
472 assert_near(qd.eval(t), cd.eval(t), epsilon);
473 }
474 }
475
476 #[test]
477 fn quadbez_signed_area() {
478 let q = QuadBez::new((1.0, 0.0), (0.5, 1.0), (0.0, 1.0));
480 let epsilon = 1e-12;
481 assert!((q.signed_area() - 2.0 / 3.0).abs() < epsilon);
482 assert!(((Affine::rotate(0.5) * q).signed_area() - 2.0 / 3.0).abs() < epsilon);
483 assert!(((Affine::translate((0.0, 1.0)) * q).signed_area() - 3.5 / 3.0).abs() < epsilon);
484 assert!(((Affine::translate((1.0, 0.0)) * q).signed_area() - 3.5 / 3.0).abs() < epsilon);
485 }
486
487 fn verify(result: Nearest, expected: f64) {
488 assert!(
489 (result.t - expected).abs() < 1e-6,
490 "got {result:?} expected {expected}"
491 );
492 }
493
494 #[test]
495 fn quadbez_nearest() {
496 let q = QuadBez::new((-1.0, 1.0), (0.0, -1.0), (1.0, 1.0));
498 verify(q.nearest((0.0, 0.0).into(), 1e-3), 0.5);
499 verify(q.nearest((0.0, 0.1).into(), 1e-3), 0.5);
500 verify(q.nearest((0.0, -0.1).into(), 1e-3), 0.5);
501 verify(q.nearest((0.5, 0.25).into(), 1e-3), 0.75);
502 verify(q.nearest((1.0, 1.0).into(), 1e-3), 1.0);
503 verify(q.nearest((1.1, 1.1).into(), 1e-3), 1.0);
504 verify(q.nearest((-1.1, 1.1).into(), 1e-3), 0.0);
505 let a = Affine::rotate(0.5);
506 verify((a * q).nearest(a * Point::new(0.5, 0.25), 1e-3), 0.75);
507 }
508
509 #[test]
512 fn quadbez_nearest_low_order() {
513 let q = QuadBez::new((-1.0, 0.0), (0.0, 0.0), (1.0, 0.0));
514
515 verify(q.nearest((0.0, 0.0).into(), 1e-3), 0.5);
516 verify(q.nearest((0.0, 1.0).into(), 1e-3), 0.5);
517 }
518
519 #[test]
520 fn quadbez_nearest_rounding_panic() {
521 let quad = QuadBez::new(
522 (-1.0394736842105263, 0.0),
523 (0.8210526315789474, -1.511111111111111),
524 (0.0, 1.9333333333333333),
525 );
526 let test = Point::new(-1.7976931348623157e308, 0.8571428571428571);
527 let _res = quad.nearest(test, 1e-6);
529 }
531
532 #[test]
533 fn quadbez_extrema() {
534 let q = QuadBez::new((-1.0, 1.0), (0.0, -1.0), (1.0, 1.0));
536 let extrema = q.extrema();
537 assert_eq!(extrema.len(), 1);
538 assert!((extrema[0] - 0.5).abs() < 1e-6);
539
540 let q = QuadBez::new((0.0, 0.5), (1.0, 1.0), (0.5, 0.0));
541 let extrema = q.extrema();
542 assert_eq!(extrema.len(), 2);
543 assert!((extrema[0] - 1.0 / 3.0).abs() < 1e-6);
544 assert!((extrema[1] - 2.0 / 3.0).abs() < 1e-6);
545
546 let q = QuadBez::new((0.5, 0.0), (1.0, 1.0), (0.0, 0.5));
548 let extrema = q.extrema();
549 assert_eq!(extrema.len(), 2);
550 assert!((extrema[0] - 1.0 / 3.0).abs() < 1e-6);
551 assert!((extrema[1] - 2.0 / 3.0).abs() < 1e-6);
552 }
553
554 #[test]
557 fn perimeter_not_nan() {
558 let q = QuadBez::new((2685., -1251.), (2253., -1303.), (2253., -1303.));
559
560 let len = q.arclen(crate::DEFAULT_ACCURACY);
561 assert!(len.is_finite());
562 }
563}