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 "include/core/SkMatrix.h"
9 #include "include/core/SkPoint3.h"
10 #include "include/private/SkTPin.h"
11 #include "include/private/SkVx.h"
12 #include "src/core/SkGeometry.h"
13 #include "src/core/SkPointPriv.h"
21 using float2 = skvx::float2;
22 using float4 = skvx::float4;
24 SkVector to_vector(const float2& x) {
30 ////////////////////////////////////////////////////////////////////////
32 int is_not_monotonic(SkScalar a, SkScalar b, SkScalar c) {
38 return ab == 0 || bc < 0;
41 ////////////////////////////////////////////////////////////////////////
43 int valid_unit_divide(SkScalar numer, SkScalar denom, SkScalar* ratio) {
51 if (denom == 0 || numer == 0 || numer >= denom) {
55 SkScalar r = numer / denom;
56 if (SkScalarIsNaN(r)) {
59 SkASSERTF(r >= 0 && r < SK_Scalar1, "numer %f, denom %f, r %f", numer, denom, r);
60 if (r == 0) { // catch underflow if numer <<<< denom
67 // Just returns its argument, but makes it easy to set a break-point to know when
68 // SkFindUnitQuadRoots is going to return 0 (an error).
69 int return_check_zero(int value) {
78 /** From Numerical Recipes in C.
80 Q = -1/2 (B + sign(B) sqrt[B*B - 4*A*C])
84 int SkFindUnitQuadRoots(SkScalar A, SkScalar B, SkScalar C, SkScalar roots[2]) {
88 return return_check_zero(valid_unit_divide(-C, B, roots));
93 // use doubles so we don't overflow temporarily trying to compute R
94 double dr = (double)B * B - 4 * (double)A * C;
96 return return_check_zero(0);
99 SkScalar R = SkDoubleToScalar(dr);
100 if (!SkScalarIsFinite(R)) {
101 return return_check_zero(0);
104 SkScalar Q = (B < 0) ? -(B-R)/2 : -(B+R)/2;
105 r += valid_unit_divide(Q, A, r);
106 r += valid_unit_divide(C, Q, r);
107 if (r - roots == 2) {
108 if (roots[0] > roots[1]) {
110 swap(roots[0], roots[1]);
111 } else if (roots[0] == roots[1]) { // nearly-equal?
112 r -= 1; // skip the double root
115 return return_check_zero((int)(r - roots));
118 ///////////////////////////////////////////////////////////////////////////////
119 ///////////////////////////////////////////////////////////////////////////////
121 void SkEvalQuadAt(const SkPoint src[3], SkScalar t, SkPoint* pt, SkVector* tangent) {
123 SkASSERT(t >= 0 && t <= SK_Scalar1);
126 *pt = SkEvalQuadAt(src, t);
129 *tangent = SkEvalQuadTangentAt(src, t);
133 SkPoint SkEvalQuadAt(const SkPoint src[3], SkScalar t) {
134 return to_point(SkQuadCoeff(src).eval(t));
137 SkVector SkEvalQuadTangentAt(const SkPoint src[3], SkScalar t) {
138 // The derivative equation is 2(b - a +(a - 2b +c)t). This returns a
139 // zero tangent vector when t is 0 or 1, and the control point is equal
140 // to the end point. In this case, use the quad end points to compute the tangent.
141 if ((t == 0 && src[0] == src[1]) || (t == 1 && src[1] == src[2])) {
142 return src[2] - src[0];
145 SkASSERT(t >= 0 && t <= SK_Scalar1);
147 float2 P0 = from_point(src[0]);
148 float2 P1 = from_point(src[1]);
149 float2 P2 = from_point(src[2]);
152 float2 A = P2 - P1 - B;
153 float2 T = A * t + B;
155 return to_vector(T + T);
158 static inline float2 interp(const float2& v0,
161 return v0 + (v1 - v0) * t;
164 void SkChopQuadAt(const SkPoint src[3], SkPoint dst[5], SkScalar t) {
165 SkASSERT(t > 0 && t < SK_Scalar1);
167 float2 p0 = from_point(src[0]);
168 float2 p1 = from_point(src[1]);
169 float2 p2 = from_point(src[2]);
172 float2 p01 = interp(p0, p1, tt);
173 float2 p12 = interp(p1, p2, tt);
175 dst[0] = to_point(p0);
176 dst[1] = to_point(p01);
177 dst[2] = to_point(interp(p01, p12, tt));
178 dst[3] = to_point(p12);
179 dst[4] = to_point(p2);
182 void SkChopQuadAtHalf(const SkPoint src[3], SkPoint dst[5]) {
183 SkChopQuadAt(src, dst, 0.5f);
186 float SkMeasureAngleBetweenVectors(SkVector a, SkVector b) {
187 float cosTheta = sk_ieee_float_divide(a.dot(b), sqrtf(a.dot(a) * b.dot(b)));
188 // Pin cosTheta such that if it is NaN (e.g., if a or b was 0), then we return acos(1) = 0.
189 cosTheta = std::max(std::min(1.f, cosTheta), -1.f);
190 return acosf(cosTheta);
193 SkVector SkFindBisector(SkVector a, SkVector b) {
194 std::array<SkVector, 2> v;
196 // a,b are within +/-90 degrees apart.
198 } else if (a.cross(b) >= 0) {
199 // a,b are >90 degrees apart. Find the bisector of their interior normals instead. (Above 90
200 // degrees, the original vectors start cancelling each other out which eventually becomes
202 v[0].set(-a.fY, +a.fX);
203 v[1].set(+b.fY, -b.fX);
205 // a,b are <-90 degrees apart. Find the bisector of their interior normals instead. (Below
206 // -90 degrees, the original vectors start cancelling each other out which eventually
207 // becomes unstable.)
208 v[0].set(+a.fY, -a.fX);
209 v[1].set(-b.fY, +b.fX);
211 // Return "normalize(v[0]) + normalize(v[1])".
212 skvx::float2 x0_x1{v[0].fX, v[1].fX};
213 skvx::float2 y0_y1{v[0].fY, v[1].fY};
214 auto invLengths = 1.0f / sqrt(x0_x1 * x0_x1 + y0_y1 * y0_y1);
217 return SkPoint{x0_x1[0] + x0_x1[1], y0_y1[0] + y0_y1[1]};
220 float SkFindQuadMidTangent(const SkPoint src[3]) {
221 // Tangents point in the direction of increasing T, so tan0 and -tan1 both point toward the
222 // midtangent. The bisector of tan0 and -tan1 is orthogonal to the midtangent:
224 // n dot midtangent = 0
226 SkVector tan0 = src[1] - src[0];
227 SkVector tan1 = src[2] - src[1];
228 SkVector bisector = SkFindBisector(tan0, -tan1);
230 // The midtangent can be found where (F' dot bisector) = 0:
232 // 0 = (F'(T) dot bisector) = |2*T 1| * |p0 - 2*p1 + p2| * |bisector.x|
233 // |-2*p0 + 2*p1 | |bisector.y|
235 // = |2*T 1| * |tan1 - tan0| * |nx|
238 // = 2*T * ((tan1 - tan0) dot bisector) + (2*tan0 dot bisector)
240 // T = (tan0 dot bisector) / ((tan0 - tan1) dot bisector)
241 float T = sk_ieee_float_divide(tan0.dot(bisector), (tan0 - tan1).dot(bisector));
242 if (!(T > 0 && T < 1)) { // Use "!(positive_logic)" so T=nan will take this branch.
243 T = .5; // The quadratic was a line or near-line. Just chop at .5.
249 /** Quad'(t) = At + B, where
252 Solve for t, only if it fits between 0 < t < 1
254 int SkFindQuadExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar tValue[1]) {
258 return valid_unit_divide(a - b, a - b - b + c, tValue);
261 static inline void flatten_double_quad_extrema(SkScalar coords[14]) {
262 coords[2] = coords[6] = coords[4];
265 /* Returns 0 for 1 quad, and 1 for two quads, either way the answer is
266 stored in dst[]. Guarantees that the 1/2 quads will be monotonic.
268 int SkChopQuadAtYExtrema(const SkPoint src[3], SkPoint dst[5]) {
272 SkScalar a = src[0].fY;
273 SkScalar b = src[1].fY;
274 SkScalar c = src[2].fY;
276 if (is_not_monotonic(a, b, c)) {
278 if (valid_unit_divide(a - b, a - b - b + c, &tValue)) {
279 SkChopQuadAt(src, dst, tValue);
280 flatten_double_quad_extrema(&dst[0].fY);
283 // if we get here, we need to force dst to be monotonic, even though
284 // we couldn't compute a unit_divide value (probably underflow).
285 b = SkScalarAbs(a - b) < SkScalarAbs(b - c) ? a : c;
287 dst[0].set(src[0].fX, a);
288 dst[1].set(src[1].fX, b);
289 dst[2].set(src[2].fX, c);
293 /* Returns 0 for 1 quad, and 1 for two quads, either way the answer is
294 stored in dst[]. Guarantees that the 1/2 quads will be monotonic.
296 int SkChopQuadAtXExtrema(const SkPoint src[3], SkPoint dst[5]) {
300 SkScalar a = src[0].fX;
301 SkScalar b = src[1].fX;
302 SkScalar c = src[2].fX;
304 if (is_not_monotonic(a, b, c)) {
306 if (valid_unit_divide(a - b, a - b - b + c, &tValue)) {
307 SkChopQuadAt(src, dst, tValue);
308 flatten_double_quad_extrema(&dst[0].fX);
311 // if we get here, we need to force dst to be monotonic, even though
312 // we couldn't compute a unit_divide value (probably underflow).
313 b = SkScalarAbs(a - b) < SkScalarAbs(b - c) ? a : c;
315 dst[0].set(a, src[0].fY);
316 dst[1].set(b, src[1].fY);
317 dst[2].set(c, src[2].fY);
321 // F(t) = a (1 - t) ^ 2 + 2 b t (1 - t) + c t ^ 2
322 // F'(t) = 2 (b - a) + 2 (a - 2b + c) t
323 // F''(t) = 2 (a - 2b + c)
326 // B = 2 (a - 2b + c)
328 // Maximum curvature for a quadratic means solving
329 // Fx' Fx'' + Fy' Fy'' = 0
331 // t = - (Ax Bx + Ay By) / (Bx ^ 2 + By ^ 2)
333 SkScalar SkFindQuadMaxCurvature(const SkPoint src[3]) {
334 SkScalar Ax = src[1].fX - src[0].fX;
335 SkScalar Ay = src[1].fY - src[0].fY;
336 SkScalar Bx = src[0].fX - src[1].fX - src[1].fX + src[2].fX;
337 SkScalar By = src[0].fY - src[1].fY - src[1].fY + src[2].fY;
339 SkScalar numer = -(Ax * Bx + Ay * By);
340 SkScalar denom = Bx * Bx + By * By;
348 if (numer >= denom) { // Also catches denom=0.
351 SkScalar t = numer / denom;
352 SkASSERT((0 <= t && t < 1) || SkScalarIsNaN(t));
356 int SkChopQuadAtMaxCurvature(const SkPoint src[3], SkPoint dst[5]) {
357 SkScalar t = SkFindQuadMaxCurvature(src);
358 if (t > 0 && t < 1) {
359 SkChopQuadAt(src, dst, t);
362 memcpy(dst, src, 3 * sizeof(SkPoint));
367 void SkConvertQuadToCubic(const SkPoint src[3], SkPoint dst[4]) {
368 float2 scale(SkDoubleToScalar(2.0 / 3.0));
369 float2 s0 = from_point(src[0]);
370 float2 s1 = from_point(src[1]);
371 float2 s2 = from_point(src[2]);
373 dst[0] = to_point(s0);
374 dst[1] = to_point(s0 + (s1 - s0) * scale);
375 dst[2] = to_point(s2 + (s1 - s2) * scale);
376 dst[3] = to_point(s2);
379 //////////////////////////////////////////////////////////////////////////////
380 ///// CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS /////
381 //////////////////////////////////////////////////////////////////////////////
383 static SkVector eval_cubic_derivative(const SkPoint src[4], SkScalar t) {
385 float2 P0 = from_point(src[0]);
386 float2 P1 = from_point(src[1]);
387 float2 P2 = from_point(src[2]);
388 float2 P3 = from_point(src[3]);
390 coeff.fA = P3 + 3 * (P1 - P2) - P0;
391 coeff.fB = times_2(P2 - times_2(P1) + P0);
393 return to_vector(coeff.eval(t));
396 static SkVector eval_cubic_2ndDerivative(const SkPoint src[4], SkScalar t) {
397 float2 P0 = from_point(src[0]);
398 float2 P1 = from_point(src[1]);
399 float2 P2 = from_point(src[2]);
400 float2 P3 = from_point(src[3]);
401 float2 A = P3 + 3 * (P1 - P2) - P0;
402 float2 B = P2 - times_2(P1) + P0;
404 return to_vector(A * t + B);
407 void SkEvalCubicAt(const SkPoint src[4], SkScalar t, SkPoint* loc,
408 SkVector* tangent, SkVector* curvature) {
410 SkASSERT(t >= 0 && t <= SK_Scalar1);
413 *loc = to_point(SkCubicCoeff(src).eval(t));
416 // The derivative equation returns a zero tangent vector when t is 0 or 1, and the
417 // adjacent control point is equal to the end point. In this case, use the
418 // next control point or the end points to compute the tangent.
419 if ((t == 0 && src[0] == src[1]) || (t == 1 && src[2] == src[3])) {
421 *tangent = src[2] - src[0];
423 *tangent = src[3] - src[1];
425 if (!tangent->fX && !tangent->fY) {
426 *tangent = src[3] - src[0];
429 *tangent = eval_cubic_derivative(src, t);
433 *curvature = eval_cubic_2ndDerivative(src, t);
437 /** Cubic'(t) = At^2 + Bt + C, where
438 A = 3(-a + 3(b - c) + d)
441 Solve for t, keeping only those that fit betwee 0 < t < 1
443 int SkFindCubicExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar d,
444 SkScalar tValues[2]) {
445 // we divide A,B,C by 3 to simplify
446 SkScalar A = d - a + 3*(b - c);
447 SkScalar B = 2*(a - b - b + c);
450 return SkFindUnitQuadRoots(A, B, C, tValues);
453 // This does not return b when t==1, but it otherwise seems to get better precision than
454 // "a*(1 - t) + b*t" for things like chopping cubics on exact cusp points.
455 // The responsibility falls on the caller to check that t != 1 before calling.
456 template<int N, typename T>
457 inline static skvx::Vec<N,T> unchecked_mix(const skvx::Vec<N,T>& a, const skvx::Vec<N,T>& b,
458 const skvx::Vec<N,T>& t) {
459 return (b - a)*t + a;
462 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[7], SkScalar t) {
463 SkASSERT(0 <= t && t <= 1);
466 memcpy(dst, src, sizeof(SkPoint) * 4);
467 dst[4] = dst[5] = dst[6] = src[3];
471 float2 p0 = skvx::bit_pun<float2>(src[0]);
472 float2 p1 = skvx::bit_pun<float2>(src[1]);
473 float2 p2 = skvx::bit_pun<float2>(src[2]);
474 float2 p3 = skvx::bit_pun<float2>(src[3]);
477 float2 ab = unchecked_mix(p0, p1, T);
478 float2 bc = unchecked_mix(p1, p2, T);
479 float2 cd = unchecked_mix(p2, p3, T);
480 float2 abc = unchecked_mix(ab, bc, T);
481 float2 bcd = unchecked_mix(bc, cd, T);
482 float2 abcd = unchecked_mix(abc, bcd, T);
484 dst[0] = skvx::bit_pun<SkPoint>(p0);
485 dst[1] = skvx::bit_pun<SkPoint>(ab);
486 dst[2] = skvx::bit_pun<SkPoint>(abc);
487 dst[3] = skvx::bit_pun<SkPoint>(abcd);
488 dst[4] = skvx::bit_pun<SkPoint>(bcd);
489 dst[5] = skvx::bit_pun<SkPoint>(cd);
490 dst[6] = skvx::bit_pun<SkPoint>(p3);
493 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[10], float t0, float t1) {
494 SkASSERT(0 <= t0 && t0 <= t1 && t1 <= 1);
497 SkChopCubicAt(src, dst, t0);
498 dst[7] = dst[8] = dst[9] = src[3];
502 // Perform both chops in parallel using 4-lane SIMD.
503 float4 p00, p11, p22, p33, T;
504 p00.lo = p00.hi = skvx::bit_pun<float2>(src[0]);
505 p11.lo = p11.hi = skvx::bit_pun<float2>(src[1]);
506 p22.lo = p22.hi = skvx::bit_pun<float2>(src[2]);
507 p33.lo = p33.hi = skvx::bit_pun<float2>(src[3]);
511 float4 ab = unchecked_mix(p00, p11, T);
512 float4 bc = unchecked_mix(p11, p22, T);
513 float4 cd = unchecked_mix(p22, p33, T);
514 float4 abc = unchecked_mix(ab, bc, T);
515 float4 bcd = unchecked_mix(bc, cd, T);
516 float4 abcd = unchecked_mix(abc, bcd, T);
517 float4 middle = unchecked_mix(abc, bcd, skvx::shuffle<2,3,0,1>(T));
519 dst[0] = skvx::bit_pun<SkPoint>(p00.lo);
520 dst[1] = skvx::bit_pun<SkPoint>(ab.lo);
521 dst[2] = skvx::bit_pun<SkPoint>(abc.lo);
522 dst[3] = skvx::bit_pun<SkPoint>(abcd.lo);
523 middle.store(dst + 4);
524 dst[6] = skvx::bit_pun<SkPoint>(abcd.hi);
525 dst[7] = skvx::bit_pun<SkPoint>(bcd.hi);
526 dst[8] = skvx::bit_pun<SkPoint>(cd.hi);
527 dst[9] = skvx::bit_pun<SkPoint>(p33.hi);
530 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[],
531 const SkScalar tValues[], int tCount) {
532 SkASSERT(std::all_of(tValues, tValues + tCount, [](SkScalar t) { return t >= 0 && t <= 1; }));
533 SkASSERT(std::is_sorted(tValues, tValues + tCount));
536 if (tCount == 0) { // nothing to chop
537 memcpy(dst, src, 4*sizeof(SkPoint));
540 for (; i < tCount - 1; i += 2) {
541 // Do two chops at once.
542 float2 tt = float2::Load(tValues + i);
544 float lastT = tValues[i - 1];
545 tt = skvx::pin((tt - lastT) / (1 - lastT), float2(0), float2(1));
547 SkChopCubicAt(src, dst, tt[0], tt[1]);
551 // Chop the final cubic if there was an odd number of chops.
552 SkASSERT(i + 1 == tCount);
553 float t = tValues[i];
555 float lastT = tValues[i - 1];
556 t = SkTPin(sk_ieee_float_divide(t - lastT, 1 - lastT), 0.f, 1.f);
558 SkChopCubicAt(src, dst, t);
564 void SkChopCubicAtHalf(const SkPoint src[4], SkPoint dst[7]) {
565 SkChopCubicAt(src, dst, 0.5f);
568 float SkMeasureNonInflectCubicRotation(const SkPoint pts[4]) {
569 SkVector a = pts[1] - pts[0];
570 SkVector b = pts[2] - pts[1];
571 SkVector c = pts[3] - pts[2];
573 return SkMeasureAngleBetweenVectors(b, c);
576 return SkMeasureAngleBetweenVectors(a, c);
579 return SkMeasureAngleBetweenVectors(a, b);
581 // Postulate: When no points are colocated and there are no inflection points in T=0..1, the
582 // rotation is: 360 degrees, minus the angle [p0,p1,p2], minus the angle [p1,p2,p3].
583 return 2*SK_ScalarPI - SkMeasureAngleBetweenVectors(a,-b) - SkMeasureAngleBetweenVectors(b,-c);
586 static skvx::float4 fma(const skvx::float4& f, float m, const skvx::float4& a) {
587 return skvx::fma(f, skvx::float4(m), a);
590 // Finds the root nearest 0.5. Returns 0.5 if the roots are undefined or outside 0..1.
591 static float solve_quadratic_equation_for_midtangent(float a, float b, float c, float discr) {
592 // Quadratic formula from Numerical Recipes in C:
593 float q = -.5f * (b + copysignf(sqrtf(discr), b));
594 // The roots are q/a and c/q. Pick the midtangent closer to T=.5.
595 float _5qa = -.5f*q*a;
596 float T = fabsf(q*q + _5qa) < fabsf(a*c + _5qa) ? sk_ieee_float_divide(q,a)
597 : sk_ieee_float_divide(c,q);
598 if (!(T > 0 && T < 1)) { // Use "!(positive_logic)" so T=NaN will take this branch.
599 // Either the curve is a flat line with no rotation or FP precision failed us. Chop at .5.
605 static float solve_quadratic_equation_for_midtangent(float a, float b, float c) {
606 return solve_quadratic_equation_for_midtangent(a, b, c, b*b - 4*a*c);
609 float SkFindCubicMidTangent(const SkPoint src[4]) {
610 // Tangents point in the direction of increasing T, so tan0 and -tan1 both point toward the
611 // midtangent. The bisector of tan0 and -tan1 is orthogonal to the midtangent:
613 // bisector dot midtangent == 0
615 SkVector tan0 = (src[0] == src[1]) ? src[2] - src[0] : src[1] - src[0];
616 SkVector tan1 = (src[2] == src[3]) ? src[3] - src[1] : src[3] - src[2];
617 SkVector bisector = SkFindBisector(tan0, -tan1);
619 // Find the T value at the midtangent. This is a simple quadratic equation:
621 // midtangent dot bisector == 0, or using a tangent matrix C' in power basis form:
624 // |T^2 T 1| * |. . | * |bisector.x| == 0
625 // |. . | |bisector.y|
627 // The coeffs for the quadratic equation we need to solve are therefore: C' * bisector
628 static const skvx::float4 kM[4] = {skvx::float4(-1, 2, -1, 0),
629 skvx::float4( 3, -4, 1, 0),
630 skvx::float4(-3, 2, 0, 0)};
631 auto C_x = fma(kM[0], src[0].fX,
632 fma(kM[1], src[1].fX,
633 fma(kM[2], src[2].fX, skvx::float4(src[3].fX, 0,0,0))));
634 auto C_y = fma(kM[0], src[0].fY,
635 fma(kM[1], src[1].fY,
636 fma(kM[2], src[2].fY, skvx::float4(src[3].fY, 0,0,0))));
637 auto coeffs = C_x * bisector.x() + C_y * bisector.y();
639 // Now solve the quadratic for T.
641 float a=coeffs[0], b=coeffs[1], c=coeffs[2];
642 float discr = b*b - 4*a*c;
643 if (discr > 0) { // This will only be false if the curve is a line.
644 return solve_quadratic_equation_for_midtangent(a, b, c, discr);
646 // This is a 0- or 360-degree flat line. It doesn't have single points of midtangent.
647 // (tangent == midtangent at every point on the curve except the cusp points.)
648 // Chop in between both cusps instead, if any. There can be up to two cusps on a flat line,
649 // both where the tangent is perpendicular to the starting tangent:
651 // tangent dot tan0 == 0
653 coeffs = C_x * tan0.x() + C_y * tan0.y();
657 // We want the point in between both cusps. The midpoint of:
659 // (-b +/- sqrt(b^2 - 4*a*c)) / (2*a)
666 if (!(T > 0 && T < 1)) { // Use "!(positive_logic)" so T=NaN will take this branch.
667 // Either the curve is a flat line with no rotation or FP precision failed us. Chop at
675 static void flatten_double_cubic_extrema(SkScalar coords[14]) {
676 coords[4] = coords[8] = coords[6];
679 /** Given 4 points on a cubic bezier, chop it into 1, 2, 3 beziers such that
680 the resulting beziers are monotonic in Y. This is called by the scan
681 converter. Depending on what is returned, dst[] is treated as follows:
682 0 dst[0..3] is the original cubic
683 1 dst[0..3] and dst[3..6] are the two new cubics
684 2 dst[0..3], dst[3..6], dst[6..9] are the three new cubics
685 If dst == null, it is ignored and only the count is returned.
687 int SkChopCubicAtYExtrema(const SkPoint src[4], SkPoint dst[10]) {
689 int roots = SkFindCubicExtrema(src[0].fY, src[1].fY, src[2].fY,
692 SkChopCubicAt(src, dst, tValues, roots);
693 if (dst && roots > 0) {
694 // we do some cleanup to ensure our Y extrema are flat
695 flatten_double_cubic_extrema(&dst[0].fY);
697 flatten_double_cubic_extrema(&dst[3].fY);
703 int SkChopCubicAtXExtrema(const SkPoint src[4], SkPoint dst[10]) {
705 int roots = SkFindCubicExtrema(src[0].fX, src[1].fX, src[2].fX,
708 SkChopCubicAt(src, dst, tValues, roots);
709 if (dst && roots > 0) {
710 // we do some cleanup to ensure our Y extrema are flat
711 flatten_double_cubic_extrema(&dst[0].fX);
713 flatten_double_cubic_extrema(&dst[3].fX);
719 /** http://www.faculty.idc.ac.il/arik/quality/appendixA.html
721 Inflection means that curvature is zero.
722 Curvature is [F' x F''] / [F'^3]
723 So we solve F'x X F''y - F'y X F''y == 0
724 After some canceling of the cubic term, we get
728 (BxCy - ByCx)t^2 + (AxCy - AyCx)t + AxBy - AyBx == 0
730 int SkFindCubicInflections(const SkPoint src[4], SkScalar tValues[]) {
731 SkScalar Ax = src[1].fX - src[0].fX;
732 SkScalar Ay = src[1].fY - src[0].fY;
733 SkScalar Bx = src[2].fX - 2 * src[1].fX + src[0].fX;
734 SkScalar By = src[2].fY - 2 * src[1].fY + src[0].fY;
735 SkScalar Cx = src[3].fX + 3 * (src[1].fX - src[2].fX) - src[0].fX;
736 SkScalar Cy = src[3].fY + 3 * (src[1].fY - src[2].fY) - src[0].fY;
738 return SkFindUnitQuadRoots(Bx*Cy - By*Cx,
744 int SkChopCubicAtInflections(const SkPoint src[], SkPoint dst[10]) {
746 int count = SkFindCubicInflections(src, tValues);
750 memcpy(dst, src, 4 * sizeof(SkPoint));
752 SkChopCubicAt(src, dst, tValues, count);
758 // Assumes the third component of points is 1.
759 // Calcs p0 . (p1 x p2)
760 static double calc_dot_cross_cubic(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2) {
761 const double xComp = (double) p0.fX * ((double) p1.fY - (double) p2.fY);
762 const double yComp = (double) p0.fY * ((double) p2.fX - (double) p1.fX);
763 const double wComp = (double) p1.fX * (double) p2.fY - (double) p1.fY * (double) p2.fX;
764 return (xComp + yComp + wComp);
767 // Returns a positive power of 2 that, when multiplied by n, and excepting the two edge cases listed
768 // below, shifts the exponent of n to yield a magnitude somewhere inside [1..2).
769 // Returns 2^1023 if abs(n) < 2^-1022 (including 0).
770 // Returns NaN if n is Inf or NaN.
771 inline static double previous_inverse_pow2(double n) {
773 memcpy(&bits, &n, sizeof(double));
774 bits = ((1023llu*2 << 52) + ((1llu << 52) - 1)) - bits; // exp=-exp
775 bits &= (0x7ffllu) << 52; // mantissa=1.0, sign=0
776 memcpy(&n, &bits, sizeof(double));
780 inline static void write_cubic_inflection_roots(double t0, double s0, double t1, double s1,
781 double* t, double* s) {
785 // This copysign/abs business orients the implicit function so positive values are always on the
786 // "left" side of the curve.
787 t[1] = -copysign(t1, t1 * s1);
790 // Ensure t[0]/s[0] <= t[1]/s[1] (s[1] is negative from above).
791 if (copysign(s[1], s[0]) * t[0] > -fabs(s[0]) * t[1]) {
798 SkCubicType SkClassifyCubic(const SkPoint P[4], double t[2], double s[2], double d[4]) {
799 // Find the cubic's inflection function, I = [T^3 -3T^2 3T -1] dot D. (D0 will always be 0
800 // for integral cubics.)
802 // See "Resolution Independent Curve Rendering using Programmable Graphics Hardware",
803 // 4.2 Curve Categorization:
805 // https://www.microsoft.com/en-us/research/wp-content/uploads/2005/01/p1000-loop.pdf
806 double A1 = calc_dot_cross_cubic(P[0], P[3], P[2]);
807 double A2 = calc_dot_cross_cubic(P[1], P[0], P[3]);
808 double A3 = calc_dot_cross_cubic(P[2], P[1], P[0]);
812 double D1 = D2 - A2 + A1;
814 // Shift the exponents in D so the largest magnitude falls somewhere in 1..2. This protects us
815 // from overflow down the road while solving for roots and KLM functionals.
816 double Dmax = std::max(std::max(fabs(D1), fabs(D2)), fabs(D3));
817 double norm = previous_inverse_pow2(Dmax);
829 // Now use the inflection function to classify the cubic.
831 // See "Resolution Independent Curve Rendering using Programmable Graphics Hardware",
832 // 4.4 Integral Cubics:
834 // https://www.microsoft.com/en-us/research/wp-content/uploads/2005/01/p1000-loop.pdf
836 double discr = 3*D2*D2 - 4*D1*D3;
837 if (discr > 0) { // Serpentine.
839 double q = 3*D2 + copysign(sqrt(3*discr), D2);
840 write_cubic_inflection_roots(q, 6*D1, 2*D3, q, t, s);
842 return SkCubicType::kSerpentine;
843 } else if (discr < 0) { // Loop.
845 double q = D2 + copysign(sqrt(-discr), D2);
846 write_cubic_inflection_roots(q, 2*D1, 2*(D2*D2 - D3*D1), D1*q, t, s);
848 return SkCubicType::kLoop;
851 write_cubic_inflection_roots(D2, 2*D1, D2, 2*D1, t, s);
853 return SkCubicType::kLocalCusp;
856 if (0 != D2) { // Cusp at T=infinity.
858 write_cubic_inflection_roots(D3, 3*D2, 1, 0, t, s); // T1=infinity.
860 return SkCubicType::kCuspAtInfinity;
861 } else { // Degenerate.
863 write_cubic_inflection_roots(1, 0, 1, 0, t, s); // T0=T1=infinity.
865 return 0 != D3 ? SkCubicType::kQuadratic : SkCubicType::kLineOrPoint;
870 template <typename T> void bubble_sort(T array[], int count) {
871 for (int i = count - 1; i > 0; --i)
872 for (int j = i; j > 0; --j)
873 if (array[j] < array[j-1])
876 array[j] = array[j-1];
882 * Given an array and count, remove all pair-wise duplicates from the array,
883 * keeping the existing sorting, and return the new count
885 static int collaps_duplicates(SkScalar array[], int count) {
886 for (int n = count; n > 1; --n) {
887 if (array[0] == array[1]) {
888 for (int i = 1; i < n; ++i) {
889 array[i - 1] = array[i];
901 #define TEST_COLLAPS_ENTRY(array) array, SK_ARRAY_COUNT(array)
903 static void test_collaps_duplicates() {
905 if (gOnce) { return; }
907 const SkScalar src0[] = { 0 };
908 const SkScalar src1[] = { 0, 0 };
909 const SkScalar src2[] = { 0, 1 };
910 const SkScalar src3[] = { 0, 0, 0 };
911 const SkScalar src4[] = { 0, 0, 1 };
912 const SkScalar src5[] = { 0, 1, 1 };
913 const SkScalar src6[] = { 0, 1, 2 };
915 const SkScalar* fData;
919 { TEST_COLLAPS_ENTRY(src0), 1 },
920 { TEST_COLLAPS_ENTRY(src1), 1 },
921 { TEST_COLLAPS_ENTRY(src2), 2 },
922 { TEST_COLLAPS_ENTRY(src3), 1 },
923 { TEST_COLLAPS_ENTRY(src4), 2 },
924 { TEST_COLLAPS_ENTRY(src5), 2 },
925 { TEST_COLLAPS_ENTRY(src6), 3 },
927 for (size_t i = 0; i < SK_ARRAY_COUNT(data); ++i) {
929 memcpy(dst, data[i].fData, data[i].fCount * sizeof(dst[0]));
930 int count = collaps_duplicates(dst, data[i].fCount);
931 SkASSERT(data[i].fCollapsedCount == count);
932 for (int j = 1; j < count; ++j) {
933 SkASSERT(dst[j-1] < dst[j]);
939 static SkScalar SkScalarCubeRoot(SkScalar x) {
940 return SkScalarPow(x, 0.3333333f);
943 /* Solve coeff(t) == 0, returning the number of roots that
944 lie withing 0 < t < 1.
945 coeff[0]t^3 + coeff[1]t^2 + coeff[2]t + coeff[3]
947 Eliminates repeated roots (so that all tValues are distinct, and are always
950 static int solve_cubic_poly(const SkScalar coeff[4], SkScalar tValues[3]) {
951 if (SkScalarNearlyZero(coeff[0])) { // we're just a quadratic
952 return SkFindUnitQuadRoots(coeff[1], coeff[2], coeff[3], tValues);
955 SkScalar a, b, c, Q, R;
958 SkASSERT(coeff[0] != 0);
960 SkScalar inva = SkScalarInvert(coeff[0]);
966 R = (2*a*a*a - 9*a*b + 27*c) / 54;
968 SkScalar Q3 = Q * Q * Q;
969 SkScalar R2MinusQ3 = R * R - Q3;
970 SkScalar adiv3 = a / 3;
972 if (R2MinusQ3 < 0) { // we have 3 real roots
973 // the divide/root can, due to finite precisions, be slightly outside of -1...1
974 SkScalar theta = SkScalarACos(SkTPin(R / SkScalarSqrt(Q3), -1.0f, 1.0f));
975 SkScalar neg2RootQ = -2 * SkScalarSqrt(Q);
977 tValues[0] = SkTPin(neg2RootQ * SkScalarCos(theta/3) - adiv3, 0.0f, 1.0f);
978 tValues[1] = SkTPin(neg2RootQ * SkScalarCos((theta + 2*SK_ScalarPI)/3) - adiv3, 0.0f, 1.0f);
979 tValues[2] = SkTPin(neg2RootQ * SkScalarCos((theta - 2*SK_ScalarPI)/3) - adiv3, 0.0f, 1.0f);
980 SkDEBUGCODE(test_collaps_duplicates();)
982 // now sort the roots
983 bubble_sort(tValues, 3);
984 return collaps_duplicates(tValues, 3);
985 } else { // we have 1 real root
986 SkScalar A = SkScalarAbs(R) + SkScalarSqrt(R2MinusQ3);
987 A = SkScalarCubeRoot(A);
994 tValues[0] = SkTPin(A - adiv3, 0.0f, 1.0f);
999 /* Looking for F' dot F'' == 0
1005 F' = 3Ct^2 + 6Bt + 3A
1008 F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
1010 static void formulate_F1DotF2(const SkScalar src[], SkScalar coeff[4]) {
1011 SkScalar a = src[2] - src[0];
1012 SkScalar b = src[4] - 2 * src[2] + src[0];
1013 SkScalar c = src[6] + 3 * (src[2] - src[4]) - src[0];
1016 coeff[1] = 3 * b * c;
1017 coeff[2] = 2 * b * b + c * a;
1021 /* Looking for F' dot F'' == 0
1027 F' = 3Ct^2 + 6Bt + 3A
1030 F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
1032 int SkFindCubicMaxCurvature(const SkPoint src[4], SkScalar tValues[3]) {
1033 SkScalar coeffX[4], coeffY[4];
1036 formulate_F1DotF2(&src[0].fX, coeffX);
1037 formulate_F1DotF2(&src[0].fY, coeffY);
1039 for (i = 0; i < 4; i++) {
1040 coeffX[i] += coeffY[i];
1043 int numRoots = solve_cubic_poly(coeffX, tValues);
1044 // now remove extrema where the curvature is zero (mins)
1045 // !!!! need a test for this !!!!
1049 int SkChopCubicAtMaxCurvature(const SkPoint src[4], SkPoint dst[13],
1050 SkScalar tValues[3]) {
1051 SkScalar t_storage[3];
1053 if (tValues == nullptr) {
1054 tValues = t_storage;
1058 int rootCount = SkFindCubicMaxCurvature(src, roots);
1060 // Throw out values not inside 0..1.
1062 for (int i = 0; i < rootCount; ++i) {
1063 if (0 < roots[i] && roots[i] < 1) {
1064 tValues[count++] = roots[i];
1070 memcpy(dst, src, 4 * sizeof(SkPoint));
1072 SkChopCubicAt(src, dst, tValues, count);
1078 // Returns a constant proportional to the dimensions of the cubic.
1079 // Constant found through experimentation -- maybe there's a better way....
1080 static SkScalar calc_cubic_precision(const SkPoint src[4]) {
1081 return (SkPointPriv::DistanceToSqd(src[1], src[0]) + SkPointPriv::DistanceToSqd(src[2], src[1])
1082 + SkPointPriv::DistanceToSqd(src[3], src[2])) * 1e-8f;
1085 // Returns true if both points src[testIndex], src[testIndex+1] are in the same half plane defined
1086 // by the line segment src[lineIndex], src[lineIndex+1].
1087 static bool on_same_side(const SkPoint src[4], int testIndex, int lineIndex) {
1088 SkPoint origin = src[lineIndex];
1089 SkVector line = src[lineIndex + 1] - origin;
1090 SkScalar crosses[2];
1091 for (int index = 0; index < 2; ++index) {
1092 SkVector testLine = src[testIndex + index] - origin;
1093 crosses[index] = line.cross(testLine);
1095 return crosses[0] * crosses[1] >= 0;
1098 // Return location (in t) of cubic cusp, if there is one.
1099 // Note that classify cubic code does not reliably return all cusp'd cubics, so
1100 // it is not called here.
1101 SkScalar SkFindCubicCusp(const SkPoint src[4]) {
1102 // When the adjacent control point matches the end point, it behaves as if
1103 // the cubic has a cusp: there's a point of max curvature where the derivative
1104 // goes to zero. Ideally, this would be where t is zero or one, but math
1105 // error makes not so. It is not uncommon to create cubics this way; skip them.
1106 if (src[0] == src[1]) {
1109 if (src[2] == src[3]) {
1112 // Cubics only have a cusp if the line segments formed by the control and end points cross.
1113 // Detect crossing if line ends are on opposite sides of plane formed by the other line.
1114 if (on_same_side(src, 0, 2) || on_same_side(src, 2, 0)) {
1117 // Cubics may have multiple points of maximum curvature, although at most only
1119 SkScalar maxCurvature[3];
1120 int roots = SkFindCubicMaxCurvature(src, maxCurvature);
1121 for (int index = 0; index < roots; ++index) {
1122 SkScalar testT = maxCurvature[index];
1123 if (0 >= testT || testT >= 1) { // no need to consider max curvature on the end
1126 // A cusp is at the max curvature, and also has a derivative close to zero.
1127 // Choose the 'close to zero' meaning by comparing the derivative length
1128 // with the overall cubic size.
1129 SkVector dPt = eval_cubic_derivative(src, testT);
1130 SkScalar dPtMagnitude = SkPointPriv::LengthSqd(dPt);
1131 SkScalar precision = calc_cubic_precision(src);
1132 if (dPtMagnitude < precision) {
1133 // All three max curvature t values may be close to the cusp;
1134 // return the first one.
1141 #include "src/pathops/SkPathOpsCubic.h"
1143 typedef int (SkDCubic::*InterceptProc)(double intercept, double roots[3]) const;
1145 static bool cubic_dchop_at_intercept(const SkPoint src[4], SkScalar intercept, SkPoint dst[7],
1146 InterceptProc method) {
1149 int count = (cubic.set(src).*method)(intercept, roots);
1151 SkDCubicPair pair = cubic.chopAt(roots[0]);
1152 for (int i = 0; i < 7; ++i) {
1153 dst[i] = pair.pts[i].asSkPoint();
1160 bool SkChopMonoCubicAtY(SkPoint src[4], SkScalar y, SkPoint dst[7]) {
1161 return cubic_dchop_at_intercept(src, y, dst, &SkDCubic::horizontalIntersect);
1164 bool SkChopMonoCubicAtX(SkPoint src[4], SkScalar x, SkPoint dst[7]) {
1165 return cubic_dchop_at_intercept(src, x, dst, &SkDCubic::verticalIntersect);
1168 ///////////////////////////////////////////////////////////////////////////////
1170 // NURB representation for conics. Helpful explanations at:
1172 // http://citeseerx.ist.psu.edu/viewdoc/
1173 // download?doi=10.1.1.44.5740&rep=rep1&type=ps
1175 // http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/NURBS/RB-conics.html
1177 // F = (A (1 - t)^2 + C t^2 + 2 B (1 - t) t w)
1178 // ------------------------------------------
1179 // ((1 - t)^2 + t^2 + 2 (1 - t) t w)
1181 // = {t^2 (P0 + P2 - 2 P1 w), t (-2 P0 + 2 P1 w), P0}
1182 // ------------------------------------------------
1183 // {t^2 (2 - 2 w), t (-2 + 2 w), 1}
1186 // F' = 2 (C t (1 + t (-1 + w)) - A (-1 + t) (t (-1 + w) - w) + B (1 - 2 t) w)
1188 // t^2 : (2 P0 - 2 P2 - 2 P0 w + 2 P2 w)
1189 // t^1 : (-2 P0 + 2 P2 + 4 P0 w - 4 P1 w)
1190 // t^0 : -2 P0 w + 2 P1 w
1192 // We disregard magnitude, so we can freely ignore the denominator of F', and
1193 // divide the numerator by 2
1199 static void conic_deriv_coeff(const SkScalar src[],
1201 SkScalar coeff[3]) {
1202 const SkScalar P20 = src[4] - src[0];
1203 const SkScalar P10 = src[2] - src[0];
1204 const SkScalar wP10 = w * P10;
1205 coeff[0] = w * P20 - P20;
1206 coeff[1] = P20 - 2 * wP10;
1210 static bool conic_find_extrema(const SkScalar src[], SkScalar w, SkScalar* t) {
1212 conic_deriv_coeff(src, w, coeff);
1214 SkScalar tValues[2];
1215 int roots = SkFindUnitQuadRoots(coeff[0], coeff[1], coeff[2], tValues);
1216 SkASSERT(0 == roots || 1 == roots);
1225 // We only interpolate one dimension at a time (the first, at +0, +3, +6).
1226 static void p3d_interp(const SkScalar src[7], SkScalar dst[7], SkScalar t) {
1227 SkScalar ab = SkScalarInterp(src[0], src[3], t);
1228 SkScalar bc = SkScalarInterp(src[3], src[6], t);
1230 dst[3] = SkScalarInterp(ab, bc, t);
1234 static void ratquad_mapTo3D(const SkPoint src[3], SkScalar w, SkPoint3 dst[3]) {
1235 dst[0].set(src[0].fX * 1, src[0].fY * 1, 1);
1236 dst[1].set(src[1].fX * w, src[1].fY * w, w);
1237 dst[2].set(src[2].fX * 1, src[2].fY * 1, 1);
1240 static SkPoint project_down(const SkPoint3& src) {
1241 return {src.fX / src.fZ, src.fY / src.fZ};
1244 // return false if infinity or NaN is generated; caller must check
1245 bool SkConic::chopAt(SkScalar t, SkConic dst[2]) const {
1246 SkPoint3 tmp[3], tmp2[3];
1248 ratquad_mapTo3D(fPts, fW, tmp);
1250 p3d_interp(&tmp[0].fX, &tmp2[0].fX, t);
1251 p3d_interp(&tmp[0].fY, &tmp2[0].fY, t);
1252 p3d_interp(&tmp[0].fZ, &tmp2[0].fZ, t);
1254 dst[0].fPts[0] = fPts[0];
1255 dst[0].fPts[1] = project_down(tmp2[0]);
1256 dst[0].fPts[2] = project_down(tmp2[1]); dst[1].fPts[0] = dst[0].fPts[2];
1257 dst[1].fPts[1] = project_down(tmp2[2]);
1258 dst[1].fPts[2] = fPts[2];
1260 // to put in "standard form", where w0 and w2 are both 1, we compute the
1261 // new w1 as sqrt(w1*w1/w0*w2)
1263 // w1 /= sqrt(w0*w2)
1265 // However, in our case, we know that for dst[0]:
1266 // w0 == 1, and for dst[1], w2 == 1
1268 SkScalar root = SkScalarSqrt(tmp2[1].fZ);
1269 dst[0].fW = tmp2[0].fZ / root;
1270 dst[1].fW = tmp2[2].fZ / root;
1271 SkASSERT(sizeof(dst[0]) == sizeof(SkScalar) * 7);
1272 SkASSERT(0 == offsetof(SkConic, fPts[0].fX));
1273 return SkScalarsAreFinite(&dst[0].fPts[0].fX, 7 * 2);
1276 void SkConic::chopAt(SkScalar t1, SkScalar t2, SkConic* dst) const {
1277 if (0 == t1 || 1 == t2) {
1278 if (0 == t1 && 1 == t2) {
1283 if (this->chopAt(t1 ? t1 : t2, pair)) {
1284 *dst = pair[SkToBool(t1)];
1289 SkConicCoeff coeff(*this);
1291 float2 aXY = coeff.fNumer.eval(tt1);
1292 float2 aZZ = coeff.fDenom.eval(tt1);
1293 float2 midTT((t1 + t2) / 2);
1294 float2 dXY = coeff.fNumer.eval(midTT);
1295 float2 dZZ = coeff.fDenom.eval(midTT);
1297 float2 cXY = coeff.fNumer.eval(tt2);
1298 float2 cZZ = coeff.fDenom.eval(tt2);
1299 float2 bXY = times_2(dXY) - (aXY + cXY) * 0.5f;
1300 float2 bZZ = times_2(dZZ) - (aZZ + cZZ) * 0.5f;
1301 dst->fPts[0] = to_point(aXY / aZZ);
1302 dst->fPts[1] = to_point(bXY / bZZ);
1303 dst->fPts[2] = to_point(cXY / cZZ);
1304 float2 ww = bZZ / sqrt(aZZ * cZZ);
1308 SkPoint SkConic::evalAt(SkScalar t) const {
1309 return to_point(SkConicCoeff(*this).eval(t));
1312 SkVector SkConic::evalTangentAt(SkScalar t) const {
1313 // The derivative equation returns a zero tangent vector when t is 0 or 1,
1314 // and the control point is equal to the end point.
1315 // In this case, use the conic endpoints to compute the tangent.
1316 if ((t == 0 && fPts[0] == fPts[1]) || (t == 1 && fPts[1] == fPts[2])) {
1317 return fPts[2] - fPts[0];
1319 float2 p0 = from_point(fPts[0]);
1320 float2 p1 = from_point(fPts[1]);
1321 float2 p2 = from_point(fPts[2]);
1324 float2 p20 = p2 - p0;
1325 float2 p10 = p1 - p0;
1327 float2 C = ww * p10;
1328 float2 A = ww * p20 - p20;
1329 float2 B = p20 - C - C;
1331 return to_vector(SkQuadCoeff(A, B, C).eval(t));
1334 void SkConic::evalAt(SkScalar t, SkPoint* pt, SkVector* tangent) const {
1335 SkASSERT(t >= 0 && t <= SK_Scalar1);
1338 *pt = this->evalAt(t);
1341 *tangent = this->evalTangentAt(t);
1345 static SkScalar subdivide_w_value(SkScalar w) {
1346 return SkScalarSqrt(SK_ScalarHalf + w * SK_ScalarHalf);
1349 void SkConic::chop(SkConic * SK_RESTRICT dst) const {
1350 float2 scale = SkScalarInvert(SK_Scalar1 + fW);
1351 SkScalar newW = subdivide_w_value(fW);
1353 float2 p0 = from_point(fPts[0]);
1354 float2 p1 = from_point(fPts[1]);
1355 float2 p2 = from_point(fPts[2]);
1358 float2 wp1 = ww * p1;
1359 float2 m = (p0 + times_2(wp1) + p2) * scale * 0.5f;
1360 SkPoint mPt = to_point(m);
1361 if (!mPt.isFinite()) {
1363 double w_2 = w_d * 2;
1364 double scale_half = 1 / (1 + w_d) * 0.5;
1365 mPt.fX = SkDoubleToScalar((fPts[0].fX + w_2 * fPts[1].fX + fPts[2].fX) * scale_half);
1366 mPt.fY = SkDoubleToScalar((fPts[0].fY + w_2 * fPts[1].fY + fPts[2].fY) * scale_half);
1368 dst[0].fPts[0] = fPts[0];
1369 dst[0].fPts[1] = to_point((p0 + wp1) * scale);
1370 dst[0].fPts[2] = dst[1].fPts[0] = mPt;
1371 dst[1].fPts[1] = to_point((wp1 + p2) * scale);
1372 dst[1].fPts[2] = fPts[2];
1374 dst[0].fW = dst[1].fW = newW;
1378 * "High order approximation of conic sections by quadratic splines"
1379 * by Michael Floater, 1993
1381 #define AS_QUAD_ERROR_SETUP \
1382 SkScalar a = fW - 1; \
1383 SkScalar k = a / (4 * (2 + a)); \
1384 SkScalar x = k * (fPts[0].fX - 2 * fPts[1].fX + fPts[2].fX); \
1385 SkScalar y = k * (fPts[0].fY - 2 * fPts[1].fY + fPts[2].fY);
1387 void SkConic::computeAsQuadError(SkVector* err) const {
1392 bool SkConic::asQuadTol(SkScalar tol) const {
1394 return (x * x + y * y) <= tol * tol;
1397 // Limit the number of suggested quads to approximate a conic
1398 #define kMaxConicToQuadPOW2 5
1400 int SkConic::computeQuadPOW2(SkScalar tol) const {
1401 if (tol < 0 || !SkScalarIsFinite(tol) || !SkPointPriv::AreFinite(fPts, 3)) {
1407 SkScalar error = SkScalarSqrt(x * x + y * y);
1409 for (pow2 = 0; pow2 < kMaxConicToQuadPOW2; ++pow2) {
1415 // float version -- using ceil gives the same results as the above.
1417 SkScalar err = SkScalarSqrt(x * x + y * y);
1421 SkScalar tol2 = tol * tol;
1423 return kMaxConicToQuadPOW2;
1425 SkScalar fpow2 = SkScalarLog2((x * x + y * y) / tol2) * 0.25f;
1426 int altPow2 = SkScalarCeilToInt(fpow2);
1427 if (altPow2 != pow2) {
1428 SkDebugf("pow2 %d altPow2 %d fbits %g err %g tol %g\n", pow2, altPow2, fpow2, err, tol);
1435 // This was originally developed and tested for pathops: see SkOpTypes.h
1436 // returns true if (a <= b <= c) || (a >= b >= c)
1437 static bool between(SkScalar a, SkScalar b, SkScalar c) {
1438 return (a - b) * (c - b) <= 0;
1441 static SkPoint* subdivide(const SkConic& src, SkPoint pts[], int level) {
1442 SkASSERT(level >= 0);
1445 memcpy(pts, &src.fPts[1], 2 * sizeof(SkPoint));
1450 const SkScalar startY = src.fPts[0].fY;
1451 SkScalar endY = src.fPts[2].fY;
1452 if (between(startY, src.fPts[1].fY, endY)) {
1453 // If the input is monotonic and the output is not, the scan converter hangs.
1454 // Ensure that the chopped conics maintain their y-order.
1455 SkScalar midY = dst[0].fPts[2].fY;
1456 if (!between(startY, midY, endY)) {
1457 // If the computed midpoint is outside the ends, move it to the closer one.
1458 SkScalar closerY = SkTAbs(midY - startY) < SkTAbs(midY - endY) ? startY : endY;
1459 dst[0].fPts[2].fY = dst[1].fPts[0].fY = closerY;
1461 if (!between(startY, dst[0].fPts[1].fY, dst[0].fPts[2].fY)) {
1462 // If the 1st control is not between the start and end, put it at the start.
1463 // This also reduces the quad to a line.
1464 dst[0].fPts[1].fY = startY;
1466 if (!between(dst[1].fPts[0].fY, dst[1].fPts[1].fY, endY)) {
1467 // If the 2nd control is not between the start and end, put it at the end.
1468 // This also reduces the quad to a line.
1469 dst[1].fPts[1].fY = endY;
1471 // Verify that all five points are in order.
1472 SkASSERT(between(startY, dst[0].fPts[1].fY, dst[0].fPts[2].fY));
1473 SkASSERT(between(dst[0].fPts[1].fY, dst[0].fPts[2].fY, dst[1].fPts[1].fY));
1474 SkASSERT(between(dst[0].fPts[2].fY, dst[1].fPts[1].fY, endY));
1477 pts = subdivide(dst[0], pts, level);
1478 return subdivide(dst[1], pts, level);
1482 int SkConic::chopIntoQuadsPOW2(SkPoint pts[], int pow2) const {
1483 SkASSERT(pow2 >= 0);
1485 SkDEBUGCODE(SkPoint* endPts);
1486 if (pow2 == kMaxConicToQuadPOW2) { // If an extreme weight generates many quads ...
1489 // check to see if the first chop generates a pair of lines
1490 if (SkPointPriv::EqualsWithinTolerance(dst[0].fPts[1], dst[0].fPts[2]) &&
1491 SkPointPriv::EqualsWithinTolerance(dst[1].fPts[0], dst[1].fPts[1])) {
1492 pts[1] = pts[2] = pts[3] = dst[0].fPts[1]; // set ctrl == end to make lines
1493 pts[4] = dst[1].fPts[2];
1495 SkDEBUGCODE(endPts = &pts[5]);
1496 goto commonFinitePtCheck;
1499 SkDEBUGCODE(endPts = ) subdivide(*this, pts + 1, pow2);
1500 commonFinitePtCheck:
1501 const int quadCount = 1 << pow2;
1502 const int ptCount = 2 * quadCount + 1;
1503 SkASSERT(endPts - pts == ptCount);
1504 if (!SkPointPriv::AreFinite(pts, ptCount)) {
1505 // if we generated a non-finite, pin ourselves to the middle of the hull,
1506 // as our first and last are already on the first/last pts of the hull.
1507 for (int i = 1; i < ptCount - 1; ++i) {
1514 float SkConic::findMidTangent() const {
1515 // Tangents point in the direction of increasing T, so tan0 and -tan1 both point toward the
1516 // midtangent. The bisector of tan0 and -tan1 is orthogonal to the midtangent:
1518 // bisector dot midtangent = 0
1520 SkVector tan0 = fPts[1] - fPts[0];
1521 SkVector tan1 = fPts[2] - fPts[1];
1522 SkVector bisector = SkFindBisector(tan0, -tan1);
1524 // Start by finding the tangent function's power basis coefficients. These define a tangent
1525 // direction (scaled by some uniform value) as:
1527 // Tangent_Direction(T) = dx,dy = |A B C| * |T |
1530 // The derivative of a conic has a cumbersome order-4 denominator. However, this isn't necessary
1531 // if we are only interested in a vector in the same *direction* as a given tangent line. Since
1532 // the denominator scales dx and dy uniformly, we can throw it out completely after evaluating
1533 // the derivative with the standard quotient rule. This leaves us with a simpler quadratic
1534 // function that we use to find a tangent.
1535 SkVector A = (fPts[2] - fPts[0]) * (fW - 1);
1536 SkVector B = (fPts[2] - fPts[0]) - (fPts[1] - fPts[0]) * (fW*2);
1537 SkVector C = (fPts[1] - fPts[0]) * fW;
1539 // Now solve for "bisector dot midtangent = 0":
1542 // bisector * |A B C| * |T | = 0
1545 float a = bisector.dot(A);
1546 float b = bisector.dot(B);
1547 float c = bisector.dot(C);
1548 return solve_quadratic_equation_for_midtangent(a, b, c);
1551 bool SkConic::findXExtrema(SkScalar* t) const {
1552 return conic_find_extrema(&fPts[0].fX, fW, t);
1555 bool SkConic::findYExtrema(SkScalar* t) const {
1556 return conic_find_extrema(&fPts[0].fY, fW, t);
1559 bool SkConic::chopAtXExtrema(SkConic dst[2]) const {
1561 if (this->findXExtrema(&t)) {
1562 if (!this->chopAt(t, dst)) {
1563 // if chop can't return finite values, don't chop
1566 // now clean-up the middle, since we know t was meant to be at
1568 SkScalar value = dst[0].fPts[2].fX;
1569 dst[0].fPts[1].fX = value;
1570 dst[1].fPts[0].fX = value;
1571 dst[1].fPts[1].fX = value;
1577 bool SkConic::chopAtYExtrema(SkConic dst[2]) const {
1579 if (this->findYExtrema(&t)) {
1580 if (!this->chopAt(t, dst)) {
1581 // if chop can't return finite values, don't chop
1584 // now clean-up the middle, since we know t was meant to be at
1586 SkScalar value = dst[0].fPts[2].fY;
1587 dst[0].fPts[1].fY = value;
1588 dst[1].fPts[0].fY = value;
1589 dst[1].fPts[1].fY = value;
1595 void SkConic::computeTightBounds(SkRect* bounds) const {
1602 if (this->findXExtrema(&t)) {
1603 this->evalAt(t, &pts[count++]);
1605 if (this->findYExtrema(&t)) {
1606 this->evalAt(t, &pts[count++]);
1608 bounds->setBounds(pts, count);
1611 void SkConic::computeFastBounds(SkRect* bounds) const {
1612 bounds->setBounds(fPts, 3);
1615 #if 0 // unimplemented
1616 bool SkConic::findMaxCurvature(SkScalar* t) const {
1617 // TODO: Implement me
1622 SkScalar SkConic::TransformW(const SkPoint pts[], SkScalar w, const SkMatrix& matrix) {
1623 if (!matrix.hasPerspective()) {
1627 SkPoint3 src[3], dst[3];
1629 ratquad_mapTo3D(pts, w, src);
1631 matrix.mapHomogeneousPoints(dst, src, 3);
1633 // w' = sqrt(w1*w1/w0*w2)
1634 // use doubles temporarily, to handle small numer/denom
1635 double w0 = dst[0].fZ;
1636 double w1 = dst[1].fZ;
1637 double w2 = dst[2].fZ;
1638 return sk_double_to_float(sqrt(sk_ieee_double_divide(w1 * w1, w0 * w2)));
1641 int SkConic::BuildUnitArc(const SkVector& uStart, const SkVector& uStop, SkRotationDirection dir,
1642 const SkMatrix* userMatrix, SkConic dst[kMaxConicsForArc]) {
1643 // rotate by x,y so that uStart is (1.0)
1644 SkScalar x = SkPoint::DotProduct(uStart, uStop);
1645 SkScalar y = SkPoint::CrossProduct(uStart, uStop);
1647 SkScalar absY = SkScalarAbs(y);
1649 // check for (effectively) coincident vectors
1650 // this can happen if our angle is nearly 0 or nearly 180 (y == 0)
1651 // ... we use the dot-prod to distinguish between 0 and 180 (x > 0)
1652 if (absY <= SK_ScalarNearlyZero && x > 0 && ((y >= 0 && kCW_SkRotationDirection == dir) ||
1653 (y <= 0 && kCCW_SkRotationDirection == dir))) {
1657 if (dir == kCCW_SkRotationDirection) {
1661 // We decide to use 1-conic per quadrant of a circle. What quadrant does [xy] lie in?
1669 quadrant = 2; // 180
1670 SkASSERT(SkScalarAbs(x + SK_Scalar1) <= SK_ScalarNearlyZero);
1671 } else if (0 == x) {
1672 SkASSERT(absY - SK_Scalar1 <= SK_ScalarNearlyZero);
1673 quadrant = y > 0 ? 1 : 3; // 90 : 270
1678 if ((x < 0) != (y < 0)) {
1683 const SkPoint quadrantPts[] = {
1684 { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 }, { -1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 }
1686 const SkScalar quadrantWeight = SK_ScalarRoot2Over2;
1688 int conicCount = quadrant;
1689 for (int i = 0; i < conicCount; ++i) {
1690 dst[i].set(&quadrantPts[i * 2], quadrantWeight);
1693 // Now compute any remaing (sub-90-degree) arc for the last conic
1694 const SkPoint finalP = { x, y };
1695 const SkPoint& lastQ = quadrantPts[quadrant * 2]; // will already be a unit-vector
1696 const SkScalar dot = SkVector::DotProduct(lastQ, finalP);
1697 SkASSERT(0 <= dot && dot <= SK_Scalar1 + SK_ScalarNearlyZero);
1700 SkVector offCurve = { lastQ.x() + x, lastQ.y() + y };
1701 // compute the bisector vector, and then rescale to be the off-curve point.
1702 // we compute its length from cos(theta/2) = length / 1, using half-angle identity we get
1703 // length = sqrt(2 / (1 + cos(theta)). We already have cos() when to computed the dot.
1704 // This is nice, since our computed weight is cos(theta/2) as well!
1706 const SkScalar cosThetaOver2 = SkScalarSqrt((1 + dot) / 2);
1707 offCurve.setLength(SkScalarInvert(cosThetaOver2));
1708 if (!SkPointPriv::EqualsWithinTolerance(lastQ, offCurve)) {
1709 dst[conicCount].set(lastQ, offCurve, finalP, cosThetaOver2);
1714 // now handle counter-clockwise and the initial unitStart rotation
1716 matrix.setSinCos(uStart.fY, uStart.fX);
1717 if (dir == kCCW_SkRotationDirection) {
1718 matrix.preScale(SK_Scalar1, -SK_Scalar1);
1721 matrix.postConcat(*userMatrix);
1723 for (int i = 0; i < conicCount; ++i) {
1724 matrix.mapPoints(dst[i].fPts, 3);