2 * Copyright 2006 The Android Open Source Project
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "SkGeometry.h"
12 static SkVector to_vector(const Sk2s& x) {
18 /** If defined, this makes eval_quad and eval_cubic do more setup (sometimes
19 involving integer multiplies by 2 or 3, but fewer calls to SkScalarMul.
20 May also introduce overflow of fixed when we compute our setup.
22 // #define DIRECT_EVAL_OF_POLYNOMIALS
24 ////////////////////////////////////////////////////////////////////////
26 static int is_not_monotonic(SkScalar a, SkScalar b, SkScalar c) {
32 return ab == 0 || bc < 0;
35 ////////////////////////////////////////////////////////////////////////
37 static bool is_unit_interval(SkScalar x) {
38 return x > 0 && x < SK_Scalar1;
41 static int valid_unit_divide(SkScalar numer, SkScalar denom, SkScalar* ratio) {
49 if (denom == 0 || numer == 0 || numer >= denom) {
53 SkScalar r = numer / denom;
54 if (SkScalarIsNaN(r)) {
57 SkASSERTF(r >= 0 && r < SK_Scalar1, "numer %f, denom %f, r %f", numer, denom, r);
58 if (r == 0) { // catch underflow if numer <<<< denom
65 /** From Numerical Recipes in C.
67 Q = -1/2 (B + sign(B) sqrt[B*B - 4*A*C])
71 int SkFindUnitQuadRoots(SkScalar A, SkScalar B, SkScalar C, SkScalar roots[2]) {
75 return valid_unit_divide(-C, B, roots);
80 SkScalar R = B*B - 4*A*C;
81 if (R < 0 || !SkScalarIsFinite(R)) { // complex roots
82 // if R is infinite, it's possible that it may still produce
83 // useful results if the operation was repeated in doubles
84 // the flipside is determining if the more precise answer
85 // isn't useful because surrounding machinery (e.g., subtracting
86 // the axis offset from C) already discards the extra precision
87 // more investigation and unit tests required...
92 SkScalar Q = (B < 0) ? -(B-R)/2 : -(B+R)/2;
93 r += valid_unit_divide(Q, A, r);
94 r += valid_unit_divide(C, Q, r);
96 if (roots[0] > roots[1])
97 SkTSwap<SkScalar>(roots[0], roots[1]);
98 else if (roots[0] == roots[1]) // nearly-equal?
99 r -= 1; // skip the double root
101 return (int)(r - roots);
104 ///////////////////////////////////////////////////////////////////////////////
105 ///////////////////////////////////////////////////////////////////////////////
107 void SkEvalQuadAt(const SkPoint src[3], SkScalar t, SkPoint* pt, SkVector* tangent) {
109 SkASSERT(t >= 0 && t <= SK_Scalar1);
112 *pt = SkEvalQuadAt(src, t);
115 *tangent = SkEvalQuadTangentAt(src, t);
119 SkPoint SkEvalQuadAt(const SkPoint src[3], SkScalar t) {
120 return to_point(SkQuadCoeff(src).eval(t));
123 SkVector SkEvalQuadTangentAt(const SkPoint src[3], SkScalar t) {
124 // The derivative equation is 2(b - a +(a - 2b +c)t). This returns a
125 // zero tangent vector when t is 0 or 1, and the control point is equal
126 // to the end point. In this case, use the quad end points to compute the tangent.
127 if ((t == 0 && src[0] == src[1]) || (t == 1 && src[1] == src[2])) {
128 return src[2] - src[0];
131 SkASSERT(t >= 0 && t <= SK_Scalar1);
133 Sk2s P0 = from_point(src[0]);
134 Sk2s P1 = from_point(src[1]);
135 Sk2s P2 = from_point(src[2]);
138 Sk2s A = P2 - P1 - B;
139 Sk2s T = A * Sk2s(t) + B;
141 return to_vector(T + T);
144 static inline Sk2s interp(const Sk2s& v0, const Sk2s& v1, const Sk2s& t) {
145 return v0 + (v1 - v0) * t;
148 void SkChopQuadAt(const SkPoint src[3], SkPoint dst[5], SkScalar t) {
149 SkASSERT(t > 0 && t < SK_Scalar1);
151 Sk2s p0 = from_point(src[0]);
152 Sk2s p1 = from_point(src[1]);
153 Sk2s p2 = from_point(src[2]);
156 Sk2s p01 = interp(p0, p1, tt);
157 Sk2s p12 = interp(p1, p2, tt);
159 dst[0] = to_point(p0);
160 dst[1] = to_point(p01);
161 dst[2] = to_point(interp(p01, p12, tt));
162 dst[3] = to_point(p12);
163 dst[4] = to_point(p2);
166 void SkChopQuadAtHalf(const SkPoint src[3], SkPoint dst[5]) {
167 SkChopQuadAt(src, dst, 0.5f);
170 /** Quad'(t) = At + B, where
173 Solve for t, only if it fits between 0 < t < 1
175 int SkFindQuadExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar tValue[1]) {
179 return valid_unit_divide(a - b, a - b - b + c, tValue);
182 static inline void flatten_double_quad_extrema(SkScalar coords[14]) {
183 coords[2] = coords[6] = coords[4];
186 /* Returns 0 for 1 quad, and 1 for two quads, either way the answer is
187 stored in dst[]. Guarantees that the 1/2 quads will be monotonic.
189 int SkChopQuadAtYExtrema(const SkPoint src[3], SkPoint dst[5]) {
193 SkScalar a = src[0].fY;
194 SkScalar b = src[1].fY;
195 SkScalar c = src[2].fY;
197 if (is_not_monotonic(a, b, c)) {
199 if (valid_unit_divide(a - b, a - b - b + c, &tValue)) {
200 SkChopQuadAt(src, dst, tValue);
201 flatten_double_quad_extrema(&dst[0].fY);
204 // if we get here, we need to force dst to be monotonic, even though
205 // we couldn't compute a unit_divide value (probably underflow).
206 b = SkScalarAbs(a - b) < SkScalarAbs(b - c) ? a : c;
208 dst[0].set(src[0].fX, a);
209 dst[1].set(src[1].fX, b);
210 dst[2].set(src[2].fX, c);
214 /* Returns 0 for 1 quad, and 1 for two quads, either way the answer is
215 stored in dst[]. Guarantees that the 1/2 quads will be monotonic.
217 int SkChopQuadAtXExtrema(const SkPoint src[3], SkPoint dst[5]) {
221 SkScalar a = src[0].fX;
222 SkScalar b = src[1].fX;
223 SkScalar c = src[2].fX;
225 if (is_not_monotonic(a, b, c)) {
227 if (valid_unit_divide(a - b, a - b - b + c, &tValue)) {
228 SkChopQuadAt(src, dst, tValue);
229 flatten_double_quad_extrema(&dst[0].fX);
232 // if we get here, we need to force dst to be monotonic, even though
233 // we couldn't compute a unit_divide value (probably underflow).
234 b = SkScalarAbs(a - b) < SkScalarAbs(b - c) ? a : c;
236 dst[0].set(a, src[0].fY);
237 dst[1].set(b, src[1].fY);
238 dst[2].set(c, src[2].fY);
242 // F(t) = a (1 - t) ^ 2 + 2 b t (1 - t) + c t ^ 2
243 // F'(t) = 2 (b - a) + 2 (a - 2b + c) t
244 // F''(t) = 2 (a - 2b + c)
247 // B = 2 (a - 2b + c)
249 // Maximum curvature for a quadratic means solving
250 // Fx' Fx'' + Fy' Fy'' = 0
252 // t = - (Ax Bx + Ay By) / (Bx ^ 2 + By ^ 2)
254 SkScalar SkFindQuadMaxCurvature(const SkPoint src[3]) {
255 SkScalar Ax = src[1].fX - src[0].fX;
256 SkScalar Ay = src[1].fY - src[0].fY;
257 SkScalar Bx = src[0].fX - src[1].fX - src[1].fX + src[2].fX;
258 SkScalar By = src[0].fY - src[1].fY - src[1].fY + src[2].fY;
259 SkScalar t = 0; // 0 means don't chop
261 (void)valid_unit_divide(-(Ax * Bx + Ay * By), Bx * Bx + By * By, &t);
265 int SkChopQuadAtMaxCurvature(const SkPoint src[3], SkPoint dst[5]) {
266 SkScalar t = SkFindQuadMaxCurvature(src);
268 memcpy(dst, src, 3 * sizeof(SkPoint));
271 SkChopQuadAt(src, dst, t);
276 void SkConvertQuadToCubic(const SkPoint src[3], SkPoint dst[4]) {
277 Sk2s scale(SkDoubleToScalar(2.0 / 3.0));
278 Sk2s s0 = from_point(src[0]);
279 Sk2s s1 = from_point(src[1]);
280 Sk2s s2 = from_point(src[2]);
283 dst[1] = to_point(s0 + (s1 - s0) * scale);
284 dst[2] = to_point(s2 + (s1 - s2) * scale);
288 //////////////////////////////////////////////////////////////////////////////
289 ///// CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS /////
290 //////////////////////////////////////////////////////////////////////////////
292 #ifdef SK_SUPPORT_LEGACY_EVAL_CUBIC
293 static SkScalar eval_cubic(const SkScalar src[], SkScalar t) {
295 SkASSERT(t >= 0 && t <= SK_Scalar1);
301 #ifdef DIRECT_EVAL_OF_POLYNOMIALS
303 SkScalar A = src[6] + 3*(src[2] - src[4]) - D;
304 SkScalar B = 3*(src[4] - src[2] - src[2] + D);
305 SkScalar C = 3*(src[2] - D);
307 return SkScalarMulAdd(SkScalarMulAdd(SkScalarMulAdd(A, t, B), t, C), t, D);
309 SkScalar ab = SkScalarInterp(src[0], src[2], t);
310 SkScalar bc = SkScalarInterp(src[2], src[4], t);
311 SkScalar cd = SkScalarInterp(src[4], src[6], t);
312 SkScalar abc = SkScalarInterp(ab, bc, t);
313 SkScalar bcd = SkScalarInterp(bc, cd, t);
314 return SkScalarInterp(abc, bcd, t);
319 static SkVector eval_cubic_derivative(const SkPoint src[4], SkScalar t) {
321 Sk2s P0 = from_point(src[0]);
322 Sk2s P1 = from_point(src[1]);
323 Sk2s P2 = from_point(src[2]);
324 Sk2s P3 = from_point(src[3]);
326 coeff.fA = P3 + Sk2s(3) * (P1 - P2) - P0;
327 coeff.fB = times_2(P2 - times_2(P1) + P0);
329 return to_vector(coeff.eval(t));
332 static SkVector eval_cubic_2ndDerivative(const SkPoint src[4], SkScalar t) {
333 Sk2s P0 = from_point(src[0]);
334 Sk2s P1 = from_point(src[1]);
335 Sk2s P2 = from_point(src[2]);
336 Sk2s P3 = from_point(src[3]);
337 Sk2s A = P3 + Sk2s(3) * (P1 - P2) - P0;
338 Sk2s B = P2 - times_2(P1) + P0;
340 return to_vector(A * Sk2s(t) + B);
343 void SkEvalCubicAt(const SkPoint src[4], SkScalar t, SkPoint* loc,
344 SkVector* tangent, SkVector* curvature) {
346 SkASSERT(t >= 0 && t <= SK_Scalar1);
349 #ifdef SK_SUPPORT_LEGACY_EVAL_CUBIC
350 loc->set(eval_cubic(&src[0].fX, t), eval_cubic(&src[0].fY, t));
352 *loc = to_point(SkCubicCoeff(src).eval(t));
356 // The derivative equation returns a zero tangent vector when t is 0 or 1, and the
357 // adjacent control point is equal to the end point. In this case, use the
358 // next control point or the end points to compute the tangent.
359 if ((t == 0 && src[0] == src[1]) || (t == 1 && src[2] == src[3])) {
361 *tangent = src[2] - src[0];
363 *tangent = src[3] - src[1];
365 if (!tangent->fX && !tangent->fY) {
366 *tangent = src[3] - src[0];
369 *tangent = eval_cubic_derivative(src, t);
373 *curvature = eval_cubic_2ndDerivative(src, t);
377 /** Cubic'(t) = At^2 + Bt + C, where
378 A = 3(-a + 3(b - c) + d)
381 Solve for t, keeping only those that fit betwee 0 < t < 1
383 int SkFindCubicExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar d,
384 SkScalar tValues[2]) {
385 // we divide A,B,C by 3 to simplify
386 SkScalar A = d - a + 3*(b - c);
387 SkScalar B = 2*(a - b - b + c);
390 return SkFindUnitQuadRoots(A, B, C, tValues);
393 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[7], SkScalar t) {
394 SkASSERT(t > 0 && t < SK_Scalar1);
396 Sk2s p0 = from_point(src[0]);
397 Sk2s p1 = from_point(src[1]);
398 Sk2s p2 = from_point(src[2]);
399 Sk2s p3 = from_point(src[3]);
402 Sk2s ab = interp(p0, p1, tt);
403 Sk2s bc = interp(p1, p2, tt);
404 Sk2s cd = interp(p2, p3, tt);
405 Sk2s abc = interp(ab, bc, tt);
406 Sk2s bcd = interp(bc, cd, tt);
407 Sk2s abcd = interp(abc, bcd, tt);
410 dst[1] = to_point(ab);
411 dst[2] = to_point(abc);
412 dst[3] = to_point(abcd);
413 dst[4] = to_point(bcd);
414 dst[5] = to_point(cd);
418 /* http://code.google.com/p/skia/issues/detail?id=32
420 This test code would fail when we didn't check the return result of
421 valid_unit_divide in SkChopCubicAt(... tValues[], int roots). The reason is
422 that after the first chop, the parameters to valid_unit_divide are equal
423 (thanks to finite float precision and rounding in the subtracts). Thus
424 even though the 2nd tValue looks < 1.0, after we renormalize it, we end
425 up with 1.0, hence the need to check and just return the last cubic as
426 a degenerate clump of 4 points in the sampe place.
428 static void test_cubic() {
430 { 556.25000, 523.03003 },
431 { 556.23999, 522.96002 },
432 { 556.21997, 522.89001 },
433 { 556.21997, 522.82001 }
436 SkScalar tval[] = { 0.33333334f, 0.99999994f };
437 SkChopCubicAt(src, dst, tval, 2);
441 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[],
442 const SkScalar tValues[], int roots) {
445 for (int i = 0; i < roots - 1; i++)
447 SkASSERT(is_unit_interval(tValues[i]));
448 SkASSERT(is_unit_interval(tValues[i+1]));
449 SkASSERT(tValues[i] < tValues[i+1]);
455 if (roots == 0) { // nothing to chop
456 memcpy(dst, src, 4*sizeof(SkPoint));
458 SkScalar t = tValues[0];
461 for (int i = 0; i < roots; i++) {
462 SkChopCubicAt(src, dst, t);
463 if (i == roots - 1) {
468 // have src point to the remaining cubic (after the chop)
469 memcpy(tmp, dst, 4 * sizeof(SkPoint));
472 // watch out in case the renormalized t isn't in range
473 if (!valid_unit_divide(tValues[i+1] - tValues[i],
474 SK_Scalar1 - tValues[i], &t)) {
475 // if we can't, just create a degenerate cubic
476 dst[4] = dst[5] = dst[6] = src[3];
484 void SkChopCubicAtHalf(const SkPoint src[4], SkPoint dst[7]) {
485 SkChopCubicAt(src, dst, 0.5f);
488 static void flatten_double_cubic_extrema(SkScalar coords[14]) {
489 coords[4] = coords[8] = coords[6];
492 /** Given 4 points on a cubic bezier, chop it into 1, 2, 3 beziers such that
493 the resulting beziers are monotonic in Y. This is called by the scan
494 converter. Depending on what is returned, dst[] is treated as follows:
495 0 dst[0..3] is the original cubic
496 1 dst[0..3] and dst[3..6] are the two new cubics
497 2 dst[0..3], dst[3..6], dst[6..9] are the three new cubics
498 If dst == null, it is ignored and only the count is returned.
500 int SkChopCubicAtYExtrema(const SkPoint src[4], SkPoint dst[10]) {
502 int roots = SkFindCubicExtrema(src[0].fY, src[1].fY, src[2].fY,
505 SkChopCubicAt(src, dst, tValues, roots);
506 if (dst && roots > 0) {
507 // we do some cleanup to ensure our Y extrema are flat
508 flatten_double_cubic_extrema(&dst[0].fY);
510 flatten_double_cubic_extrema(&dst[3].fY);
516 int SkChopCubicAtXExtrema(const SkPoint src[4], SkPoint dst[10]) {
518 int roots = SkFindCubicExtrema(src[0].fX, src[1].fX, src[2].fX,
521 SkChopCubicAt(src, dst, tValues, roots);
522 if (dst && roots > 0) {
523 // we do some cleanup to ensure our Y extrema are flat
524 flatten_double_cubic_extrema(&dst[0].fX);
526 flatten_double_cubic_extrema(&dst[3].fX);
532 /** http://www.faculty.idc.ac.il/arik/quality/appendixA.html
534 Inflection means that curvature is zero.
535 Curvature is [F' x F''] / [F'^3]
536 So we solve F'x X F''y - F'y X F''y == 0
537 After some canceling of the cubic term, we get
541 (BxCy - ByCx)t^2 + (AxCy - AyCx)t + AxBy - AyBx == 0
543 int SkFindCubicInflections(const SkPoint src[4], SkScalar tValues[]) {
544 SkScalar Ax = src[1].fX - src[0].fX;
545 SkScalar Ay = src[1].fY - src[0].fY;
546 SkScalar Bx = src[2].fX - 2 * src[1].fX + src[0].fX;
547 SkScalar By = src[2].fY - 2 * src[1].fY + src[0].fY;
548 SkScalar Cx = src[3].fX + 3 * (src[1].fX - src[2].fX) - src[0].fX;
549 SkScalar Cy = src[3].fY + 3 * (src[1].fY - src[2].fY) - src[0].fY;
551 return SkFindUnitQuadRoots(Bx*Cy - By*Cx,
557 int SkChopCubicAtInflections(const SkPoint src[], SkPoint dst[10]) {
559 int count = SkFindCubicInflections(src, tValues);
563 memcpy(dst, src, 4 * sizeof(SkPoint));
565 SkChopCubicAt(src, dst, tValues, count);
571 // See http://http.developer.nvidia.com/GPUGems3/gpugems3_ch25.html (from the book GPU Gems 3)
572 // discr(I) = d0^2 * (3*d1^2 - 4*d0*d2)
574 // discr(I) > 0 Serpentine
577 // d0 = d1 = 0 Quadratic
578 // d0 = d1 = d2 = 0 Line
579 // p0 = p1 = p2 = p3 Point
580 static SkCubicType classify_cubic(const SkPoint p[4], const SkScalar d[3]) {
581 if (p[0] == p[1] && p[0] == p[2] && p[0] == p[3]) {
582 return kPoint_SkCubicType;
584 const SkScalar discr = d[0] * d[0] * (3.f * d[1] * d[1] - 4.f * d[0] * d[2]);
585 if (discr > SK_ScalarNearlyZero) {
586 return kSerpentine_SkCubicType;
587 } else if (discr < -SK_ScalarNearlyZero) {
588 return kLoop_SkCubicType;
590 if (0.f == d[0] && 0.f == d[1]) {
591 return (0.f == d[2] ? kLine_SkCubicType : kQuadratic_SkCubicType);
593 return kCusp_SkCubicType;
598 // Assumes the third component of points is 1.
599 // Calcs p0 . (p1 x p2)
600 static SkScalar calc_dot_cross_cubic(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2) {
601 const SkScalar xComp = p0.fX * (p1.fY - p2.fY);
602 const SkScalar yComp = p0.fY * (p2.fX - p1.fX);
603 const SkScalar wComp = p1.fX * p2.fY - p1.fY * p2.fX;
604 return (xComp + yComp + wComp);
607 // Calc coefficients of I(s,t) where roots of I are inflection points of curve
608 // I(s,t) = t*(3*d0*s^2 - 3*d1*s*t + d2*t^2)
609 // d0 = a1 - 2*a2+3*a3
612 // a1 = p0 . (p3 x p2)
613 // a2 = p1 . (p0 x p3)
614 // a3 = p2 . (p1 x p0)
615 // Places the values of d1, d2, d3 in array d passed in
616 static void calc_cubic_inflection_func(const SkPoint p[4], SkScalar d[3]) {
617 SkScalar a1 = calc_dot_cross_cubic(p[0], p[3], p[2]);
618 SkScalar a2 = calc_dot_cross_cubic(p[1], p[0], p[3]);
619 SkScalar a3 = calc_dot_cross_cubic(p[2], p[1], p[0]);
621 // need to scale a's or values in later calculations will grow to high
622 SkScalar max = SkScalarAbs(a1);
623 max = SkMaxScalar(max, SkScalarAbs(a2));
624 max = SkMaxScalar(max, SkScalarAbs(a3));
632 d[0] = d[1] - a2 + a1;
635 SkCubicType SkClassifyCubic(const SkPoint src[4], SkScalar d[3]) {
636 calc_cubic_inflection_func(src, d);
637 return classify_cubic(src, d);
640 template <typename T> void bubble_sort(T array[], int count) {
641 for (int i = count - 1; i > 0; --i)
642 for (int j = i; j > 0; --j)
643 if (array[j] < array[j-1])
646 array[j] = array[j-1];
652 * Given an array and count, remove all pair-wise duplicates from the array,
653 * keeping the existing sorting, and return the new count
655 static int collaps_duplicates(SkScalar array[], int count) {
656 for (int n = count; n > 1; --n) {
657 if (array[0] == array[1]) {
658 for (int i = 1; i < n; ++i) {
659 array[i - 1] = array[i];
671 #define TEST_COLLAPS_ENTRY(array) array, SK_ARRAY_COUNT(array)
673 static void test_collaps_duplicates() {
675 if (gOnce) { return; }
677 const SkScalar src0[] = { 0 };
678 const SkScalar src1[] = { 0, 0 };
679 const SkScalar src2[] = { 0, 1 };
680 const SkScalar src3[] = { 0, 0, 0 };
681 const SkScalar src4[] = { 0, 0, 1 };
682 const SkScalar src5[] = { 0, 1, 1 };
683 const SkScalar src6[] = { 0, 1, 2 };
685 const SkScalar* fData;
689 { TEST_COLLAPS_ENTRY(src0), 1 },
690 { TEST_COLLAPS_ENTRY(src1), 1 },
691 { TEST_COLLAPS_ENTRY(src2), 2 },
692 { TEST_COLLAPS_ENTRY(src3), 1 },
693 { TEST_COLLAPS_ENTRY(src4), 2 },
694 { TEST_COLLAPS_ENTRY(src5), 2 },
695 { TEST_COLLAPS_ENTRY(src6), 3 },
697 for (size_t i = 0; i < SK_ARRAY_COUNT(data); ++i) {
699 memcpy(dst, data[i].fData, data[i].fCount * sizeof(dst[0]));
700 int count = collaps_duplicates(dst, data[i].fCount);
701 SkASSERT(data[i].fCollapsedCount == count);
702 for (int j = 1; j < count; ++j) {
703 SkASSERT(dst[j-1] < dst[j]);
709 static SkScalar SkScalarCubeRoot(SkScalar x) {
710 return SkScalarPow(x, 0.3333333f);
713 /* Solve coeff(t) == 0, returning the number of roots that
714 lie withing 0 < t < 1.
715 coeff[0]t^3 + coeff[1]t^2 + coeff[2]t + coeff[3]
717 Eliminates repeated roots (so that all tValues are distinct, and are always
720 static int solve_cubic_poly(const SkScalar coeff[4], SkScalar tValues[3]) {
721 if (SkScalarNearlyZero(coeff[0])) { // we're just a quadratic
722 return SkFindUnitQuadRoots(coeff[1], coeff[2], coeff[3], tValues);
725 SkScalar a, b, c, Q, R;
728 SkASSERT(coeff[0] != 0);
730 SkScalar inva = SkScalarInvert(coeff[0]);
736 R = (2*a*a*a - 9*a*b + 27*c) / 54;
738 SkScalar Q3 = Q * Q * Q;
739 SkScalar R2MinusQ3 = R * R - Q3;
740 SkScalar adiv3 = a / 3;
742 SkScalar* roots = tValues;
745 if (R2MinusQ3 < 0) { // we have 3 real roots
746 // the divide/root can, due to finite precisions, be slightly outside of -1...1
747 SkScalar theta = SkScalarACos(SkScalarPin(R / SkScalarSqrt(Q3), -1, 1));
748 SkScalar neg2RootQ = -2 * SkScalarSqrt(Q);
750 r = neg2RootQ * SkScalarCos(theta/3) - adiv3;
751 if (is_unit_interval(r)) {
754 r = neg2RootQ * SkScalarCos((theta + 2*SK_ScalarPI)/3) - adiv3;
755 if (is_unit_interval(r)) {
758 r = neg2RootQ * SkScalarCos((theta - 2*SK_ScalarPI)/3) - adiv3;
759 if (is_unit_interval(r)) {
762 SkDEBUGCODE(test_collaps_duplicates();)
764 // now sort the roots
765 int count = (int)(roots - tValues);
766 SkASSERT((unsigned)count <= 3);
767 bubble_sort(tValues, count);
768 count = collaps_duplicates(tValues, count);
769 roots = tValues + count; // so we compute the proper count below
770 } else { // we have 1 real root
771 SkScalar A = SkScalarAbs(R) + SkScalarSqrt(R2MinusQ3);
772 A = SkScalarCubeRoot(A);
780 if (is_unit_interval(r)) {
785 return (int)(roots - tValues);
788 /* Looking for F' dot F'' == 0
794 F' = 3Ct^2 + 6Bt + 3A
797 F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
799 static void formulate_F1DotF2(const SkScalar src[], SkScalar coeff[4]) {
800 SkScalar a = src[2] - src[0];
801 SkScalar b = src[4] - 2 * src[2] + src[0];
802 SkScalar c = src[6] + 3 * (src[2] - src[4]) - src[0];
805 coeff[1] = 3 * b * c;
806 coeff[2] = 2 * b * b + c * a;
810 /* Looking for F' dot F'' == 0
816 F' = 3Ct^2 + 6Bt + 3A
819 F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
821 int SkFindCubicMaxCurvature(const SkPoint src[4], SkScalar tValues[3]) {
822 SkScalar coeffX[4], coeffY[4];
825 formulate_F1DotF2(&src[0].fX, coeffX);
826 formulate_F1DotF2(&src[0].fY, coeffY);
828 for (i = 0; i < 4; i++) {
829 coeffX[i] += coeffY[i];
833 int count = solve_cubic_poly(coeffX, t);
836 // now remove extrema where the curvature is zero (mins)
837 // !!!! need a test for this !!!!
838 for (i = 0; i < count; i++) {
839 // if (not_min_curvature())
840 if (t[i] > 0 && t[i] < SK_Scalar1) {
841 tValues[maxCount++] = t[i];
847 int SkChopCubicAtMaxCurvature(const SkPoint src[4], SkPoint dst[13],
848 SkScalar tValues[3]) {
849 SkScalar t_storage[3];
851 if (tValues == nullptr) {
855 int count = SkFindCubicMaxCurvature(src, tValues);
859 memcpy(dst, src, 4 * sizeof(SkPoint));
861 SkChopCubicAt(src, dst, tValues, count);
867 #include "../pathops/SkPathOpsCubic.h"
869 typedef int (SkDCubic::*InterceptProc)(double intercept, double roots[3]) const;
871 static bool cubic_dchop_at_intercept(const SkPoint src[4], SkScalar intercept, SkPoint dst[7],
872 InterceptProc method) {
875 int count = (cubic.set(src).*method)(intercept, roots);
877 SkDCubicPair pair = cubic.chopAt(roots[0]);
878 for (int i = 0; i < 7; ++i) {
879 dst[i] = pair.pts[i].asSkPoint();
886 bool SkChopMonoCubicAtY(SkPoint src[4], SkScalar y, SkPoint dst[7]) {
887 return cubic_dchop_at_intercept(src, y, dst, &SkDCubic::horizontalIntersect);
890 bool SkChopMonoCubicAtX(SkPoint src[4], SkScalar x, SkPoint dst[7]) {
891 return cubic_dchop_at_intercept(src, x, dst, &SkDCubic::verticalIntersect);
894 ///////////////////////////////////////////////////////////////////////////////
896 // NURB representation for conics. Helpful explanations at:
898 // http://citeseerx.ist.psu.edu/viewdoc/
899 // download?doi=10.1.1.44.5740&rep=rep1&type=ps
901 // http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/NURBS/RB-conics.html
903 // F = (A (1 - t)^2 + C t^2 + 2 B (1 - t) t w)
904 // ------------------------------------------
905 // ((1 - t)^2 + t^2 + 2 (1 - t) t w)
907 // = {t^2 (P0 + P2 - 2 P1 w), t (-2 P0 + 2 P1 w), P0}
908 // ------------------------------------------------
909 // {t^2 (2 - 2 w), t (-2 + 2 w), 1}
912 // F' = 2 (C t (1 + t (-1 + w)) - A (-1 + t) (t (-1 + w) - w) + B (1 - 2 t) w)
914 // t^2 : (2 P0 - 2 P2 - 2 P0 w + 2 P2 w)
915 // t^1 : (-2 P0 + 2 P2 + 4 P0 w - 4 P1 w)
916 // t^0 : -2 P0 w + 2 P1 w
918 // We disregard magnitude, so we can freely ignore the denominator of F', and
919 // divide the numerator by 2
925 static void conic_deriv_coeff(const SkScalar src[],
928 const SkScalar P20 = src[4] - src[0];
929 const SkScalar P10 = src[2] - src[0];
930 const SkScalar wP10 = w * P10;
931 coeff[0] = w * P20 - P20;
932 coeff[1] = P20 - 2 * wP10;
936 static bool conic_find_extrema(const SkScalar src[], SkScalar w, SkScalar* t) {
938 conic_deriv_coeff(src, w, coeff);
941 int roots = SkFindUnitQuadRoots(coeff[0], coeff[1], coeff[2], tValues);
942 SkASSERT(0 == roots || 1 == roots);
954 void set(SkScalar x, SkScalar y, SkScalar z) {
955 fX = x; fY = y; fZ = z;
958 void projectDown(SkPoint* dst) const {
959 dst->set(fX / fZ, fY / fZ);
963 // We only interpolate one dimension at a time (the first, at +0, +3, +6).
964 static void p3d_interp(const SkScalar src[7], SkScalar dst[7], SkScalar t) {
965 SkScalar ab = SkScalarInterp(src[0], src[3], t);
966 SkScalar bc = SkScalarInterp(src[3], src[6], t);
968 dst[3] = SkScalarInterp(ab, bc, t);
972 static void ratquad_mapTo3D(const SkPoint src[3], SkScalar w, SkP3D dst[]) {
973 dst[0].set(src[0].fX * 1, src[0].fY * 1, 1);
974 dst[1].set(src[1].fX * w, src[1].fY * w, w);
975 dst[2].set(src[2].fX * 1, src[2].fY * 1, 1);
978 void SkConic::chopAt(SkScalar t, SkConic dst[2]) const {
979 SkP3D tmp[3], tmp2[3];
981 ratquad_mapTo3D(fPts, fW, tmp);
983 p3d_interp(&tmp[0].fX, &tmp2[0].fX, t);
984 p3d_interp(&tmp[0].fY, &tmp2[0].fY, t);
985 p3d_interp(&tmp[0].fZ, &tmp2[0].fZ, t);
987 dst[0].fPts[0] = fPts[0];
988 tmp2[0].projectDown(&dst[0].fPts[1]);
989 tmp2[1].projectDown(&dst[0].fPts[2]); dst[1].fPts[0] = dst[0].fPts[2];
990 tmp2[2].projectDown(&dst[1].fPts[1]);
991 dst[1].fPts[2] = fPts[2];
993 // to put in "standard form", where w0 and w2 are both 1, we compute the
994 // new w1 as sqrt(w1*w1/w0*w2)
998 // However, in our case, we know that for dst[0]:
999 // w0 == 1, and for dst[1], w2 == 1
1001 SkScalar root = SkScalarSqrt(tmp2[1].fZ);
1002 dst[0].fW = tmp2[0].fZ / root;
1003 dst[1].fW = tmp2[2].fZ / root;
1006 void SkConic::chopAt(SkScalar t1, SkScalar t2, SkConic* dst) const {
1007 if (0 == t1 || 1 == t2) {
1008 if (0 == t1 && 1 == t2) {
1012 this->chopAt(t1 ? t1 : t2, pair);
1013 *dst = pair[SkToBool(t1)];
1017 SkConicCoeff coeff(*this);
1019 Sk2s aXY = coeff.fNumer.eval(tt1);
1020 Sk2s aZZ = coeff.fDenom.eval(tt1);
1021 Sk2s midTT((t1 + t2) / 2);
1022 Sk2s dXY = coeff.fNumer.eval(midTT);
1023 Sk2s dZZ = coeff.fDenom.eval(midTT);
1025 Sk2s cXY = coeff.fNumer.eval(tt2);
1026 Sk2s cZZ = coeff.fDenom.eval(tt2);
1027 Sk2s bXY = times_2(dXY) - (aXY + cXY) * Sk2s(0.5f);
1028 Sk2s bZZ = times_2(dZZ) - (aZZ + cZZ) * Sk2s(0.5f);
1029 dst->fPts[0] = to_point(aXY / aZZ);
1030 dst->fPts[1] = to_point(bXY / bZZ);
1031 dst->fPts[2] = to_point(cXY / cZZ);
1032 Sk2s ww = bZZ / (aZZ * cZZ).sqrt();
1036 SkPoint SkConic::evalAt(SkScalar t) const {
1037 return to_point(SkConicCoeff(*this).eval(t));
1040 SkVector SkConic::evalTangentAt(SkScalar t) const {
1041 // The derivative equation returns a zero tangent vector when t is 0 or 1,
1042 // and the control point is equal to the end point.
1043 // In this case, use the conic endpoints to compute the tangent.
1044 if ((t == 0 && fPts[0] == fPts[1]) || (t == 1 && fPts[1] == fPts[2])) {
1045 return fPts[2] - fPts[0];
1047 Sk2s p0 = from_point(fPts[0]);
1048 Sk2s p1 = from_point(fPts[1]);
1049 Sk2s p2 = from_point(fPts[2]);
1056 Sk2s A = ww * p20 - p20;
1057 Sk2s B = p20 - C - C;
1059 return to_vector(SkQuadCoeff(A, B, C).eval(t));
1062 void SkConic::evalAt(SkScalar t, SkPoint* pt, SkVector* tangent) const {
1063 SkASSERT(t >= 0 && t <= SK_Scalar1);
1066 *pt = this->evalAt(t);
1069 *tangent = this->evalTangentAt(t);
1073 static SkScalar subdivide_w_value(SkScalar w) {
1074 return SkScalarSqrt(SK_ScalarHalf + w * SK_ScalarHalf);
1077 void SkConic::chop(SkConic * SK_RESTRICT dst) const {
1078 Sk2s scale = Sk2s(SkScalarInvert(SK_Scalar1 + fW));
1079 SkScalar newW = subdivide_w_value(fW);
1081 Sk2s p0 = from_point(fPts[0]);
1082 Sk2s p1 = from_point(fPts[1]);
1083 Sk2s p2 = from_point(fPts[2]);
1087 Sk2s m = (p0 + times_2(wp1) + p2) * scale * Sk2s(0.5f);
1089 dst[0].fPts[0] = fPts[0];
1090 dst[0].fPts[1] = to_point((p0 + wp1) * scale);
1091 dst[0].fPts[2] = dst[1].fPts[0] = to_point(m);
1092 dst[1].fPts[1] = to_point((wp1 + p2) * scale);
1093 dst[1].fPts[2] = fPts[2];
1095 dst[0].fW = dst[1].fW = newW;
1099 * "High order approximation of conic sections by quadratic splines"
1100 * by Michael Floater, 1993
1102 #define AS_QUAD_ERROR_SETUP \
1103 SkScalar a = fW - 1; \
1104 SkScalar k = a / (4 * (2 + a)); \
1105 SkScalar x = k * (fPts[0].fX - 2 * fPts[1].fX + fPts[2].fX); \
1106 SkScalar y = k * (fPts[0].fY - 2 * fPts[1].fY + fPts[2].fY);
1108 void SkConic::computeAsQuadError(SkVector* err) const {
1113 bool SkConic::asQuadTol(SkScalar tol) const {
1115 return (x * x + y * y) <= tol * tol;
1118 // Limit the number of suggested quads to approximate a conic
1119 #define kMaxConicToQuadPOW2 5
1121 int SkConic::computeQuadPOW2(SkScalar tol) const {
1122 if (tol < 0 || !SkScalarIsFinite(tol)) {
1128 SkScalar error = SkScalarSqrt(x * x + y * y);
1130 for (pow2 = 0; pow2 < kMaxConicToQuadPOW2; ++pow2) {
1136 // float version -- using ceil gives the same results as the above.
1138 SkScalar err = SkScalarSqrt(x * x + y * y);
1142 SkScalar tol2 = tol * tol;
1144 return kMaxConicToQuadPOW2;
1146 SkScalar fpow2 = SkScalarLog2((x * x + y * y) / tol2) * 0.25f;
1147 int altPow2 = SkScalarCeilToInt(fpow2);
1148 if (altPow2 != pow2) {
1149 SkDebugf("pow2 %d altPow2 %d fbits %g err %g tol %g\n", pow2, altPow2, fpow2, err, tol);
1156 static SkPoint* subdivide(const SkConic& src, SkPoint pts[], int level) {
1157 SkASSERT(level >= 0);
1160 memcpy(pts, &src.fPts[1], 2 * sizeof(SkPoint));
1166 pts = subdivide(dst[0], pts, level);
1167 return subdivide(dst[1], pts, level);
1171 int SkConic::chopIntoQuadsPOW2(SkPoint pts[], int pow2) const {
1172 SkASSERT(pow2 >= 0);
1174 SkDEBUGCODE(SkPoint* endPts);
1175 if (pow2 == kMaxConicToQuadPOW2) { // If an extreme weight generates many quads ...
1178 // check to see if the first chop generates a pair of lines
1179 if (dst[0].fPts[1].equalsWithinTolerance(dst[0].fPts[2])
1180 && dst[1].fPts[0].equalsWithinTolerance(dst[1].fPts[1])) {
1181 pts[1] = pts[2] = pts[3] = dst[0].fPts[1]; // set ctrl == end to make lines
1182 pts[4] = dst[1].fPts[2];
1184 SkDEBUGCODE(endPts = &pts[5]);
1185 goto commonFinitePtCheck;
1188 SkDEBUGCODE(endPts = ) subdivide(*this, pts + 1, pow2);
1189 commonFinitePtCheck:
1190 const int quadCount = 1 << pow2;
1191 const int ptCount = 2 * quadCount + 1;
1192 SkASSERT(endPts - pts == ptCount);
1193 if (!SkPointsAreFinite(pts, ptCount)) {
1194 // if we generated a non-finite, pin ourselves to the middle of the hull,
1195 // as our first and last are already on the first/last pts of the hull.
1196 for (int i = 1; i < ptCount - 1; ++i) {
1203 bool SkConic::findXExtrema(SkScalar* t) const {
1204 return conic_find_extrema(&fPts[0].fX, fW, t);
1207 bool SkConic::findYExtrema(SkScalar* t) const {
1208 return conic_find_extrema(&fPts[0].fY, fW, t);
1211 bool SkConic::chopAtXExtrema(SkConic dst[2]) const {
1213 if (this->findXExtrema(&t)) {
1214 this->chopAt(t, dst);
1215 // now clean-up the middle, since we know t was meant to be at
1217 SkScalar value = dst[0].fPts[2].fX;
1218 dst[0].fPts[1].fX = value;
1219 dst[1].fPts[0].fX = value;
1220 dst[1].fPts[1].fX = value;
1226 bool SkConic::chopAtYExtrema(SkConic dst[2]) const {
1228 if (this->findYExtrema(&t)) {
1229 this->chopAt(t, dst);
1230 // now clean-up the middle, since we know t was meant to be at
1232 SkScalar value = dst[0].fPts[2].fY;
1233 dst[0].fPts[1].fY = value;
1234 dst[1].fPts[0].fY = value;
1235 dst[1].fPts[1].fY = value;
1241 void SkConic::computeTightBounds(SkRect* bounds) const {
1248 if (this->findXExtrema(&t)) {
1249 this->evalAt(t, &pts[count++]);
1251 if (this->findYExtrema(&t)) {
1252 this->evalAt(t, &pts[count++]);
1254 bounds->set(pts, count);
1257 void SkConic::computeFastBounds(SkRect* bounds) const {
1258 bounds->set(fPts, 3);
1261 #if 0 // unimplemented
1262 bool SkConic::findMaxCurvature(SkScalar* t) const {
1263 // TODO: Implement me
1268 SkScalar SkConic::TransformW(const SkPoint pts[], SkScalar w,
1269 const SkMatrix& matrix) {
1270 if (!matrix.hasPerspective()) {
1274 SkP3D src[3], dst[3];
1276 ratquad_mapTo3D(pts, w, src);
1278 matrix.mapHomogeneousPoints(&dst[0].fX, &src[0].fX, 3);
1280 // w' = sqrt(w1*w1/w0*w2)
1281 SkScalar w0 = dst[0].fZ;
1282 SkScalar w1 = dst[1].fZ;
1283 SkScalar w2 = dst[2].fZ;
1284 w = SkScalarSqrt((w1 * w1) / (w0 * w2));
1288 int SkConic::BuildUnitArc(const SkVector& uStart, const SkVector& uStop, SkRotationDirection dir,
1289 const SkMatrix* userMatrix, SkConic dst[kMaxConicsForArc]) {
1290 // rotate by x,y so that uStart is (1.0)
1291 SkScalar x = SkPoint::DotProduct(uStart, uStop);
1292 SkScalar y = SkPoint::CrossProduct(uStart, uStop);
1294 SkScalar absY = SkScalarAbs(y);
1296 // check for (effectively) coincident vectors
1297 // this can happen if our angle is nearly 0 or nearly 180 (y == 0)
1298 // ... we use the dot-prod to distinguish between 0 and 180 (x > 0)
1299 if (absY <= SK_ScalarNearlyZero && x > 0 && ((y >= 0 && kCW_SkRotationDirection == dir) ||
1300 (y <= 0 && kCCW_SkRotationDirection == dir))) {
1304 if (dir == kCCW_SkRotationDirection) {
1308 // We decide to use 1-conic per quadrant of a circle. What quadrant does [xy] lie in?
1316 quadrant = 2; // 180
1317 SkASSERT(SkScalarAbs(x + SK_Scalar1) <= SK_ScalarNearlyZero);
1318 } else if (0 == x) {
1319 SkASSERT(absY - SK_Scalar1 <= SK_ScalarNearlyZero);
1320 quadrant = y > 0 ? 1 : 3; // 90 : 270
1325 if ((x < 0) != (y < 0)) {
1330 const SkPoint quadrantPts[] = {
1331 { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 }, { -1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 }
1333 const SkScalar quadrantWeight = SK_ScalarRoot2Over2;
1335 int conicCount = quadrant;
1336 for (int i = 0; i < conicCount; ++i) {
1337 dst[i].set(&quadrantPts[i * 2], quadrantWeight);
1340 // Now compute any remaing (sub-90-degree) arc for the last conic
1341 const SkPoint finalP = { x, y };
1342 const SkPoint& lastQ = quadrantPts[quadrant * 2]; // will already be a unit-vector
1343 const SkScalar dot = SkVector::DotProduct(lastQ, finalP);
1344 SkASSERT(0 <= dot && dot <= SK_Scalar1 + SK_ScalarNearlyZero);
1347 SkVector offCurve = { lastQ.x() + x, lastQ.y() + y };
1348 // compute the bisector vector, and then rescale to be the off-curve point.
1349 // we compute its length from cos(theta/2) = length / 1, using half-angle identity we get
1350 // length = sqrt(2 / (1 + cos(theta)). We already have cos() when to computed the dot.
1351 // This is nice, since our computed weight is cos(theta/2) as well!
1353 const SkScalar cosThetaOver2 = SkScalarSqrt((1 + dot) / 2);
1354 offCurve.setLength(SkScalarInvert(cosThetaOver2));
1355 dst[conicCount].set(lastQ, offCurve, finalP, cosThetaOver2);
1359 // now handle counter-clockwise and the initial unitStart rotation
1361 matrix.setSinCos(uStart.fY, uStart.fX);
1362 if (dir == kCCW_SkRotationDirection) {
1363 matrix.preScale(SK_Scalar1, -SK_Scalar1);
1366 matrix.postConcat(*userMatrix);
1368 for (int i = 0; i < conicCount; ++i) {
1369 matrix.mapPoints(dst[i].fPts, 3);