1 /*
2  * Copyright 2006 The Android Open Source Project
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "include/core/SkMatrix.h"
9 #include "include/core/SkPoint3.h"
10 #include "include/private/SkNx.h"
11 #include "include/private/SkTPin.h"
12 #include "include/private/SkVx.h"
13 #include "src/core/SkGeometry.h"
14 #include "src/core/SkPointPriv.h"
15 
16 #include <tuple>
17 #include <utility>
18 
to_vector(const Sk2s & x)19 static SkVector to_vector(const Sk2s& x) {
20     SkVector vector;
21     x.store(&vector);
22     return vector;
23 }
24 
25 ////////////////////////////////////////////////////////////////////////
26 
is_not_monotonic(SkScalar a,SkScalar b,SkScalar c)27 static int is_not_monotonic(SkScalar a, SkScalar b, SkScalar c) {
28     SkScalar ab = a - b;
29     SkScalar bc = b - c;
30     if (ab < 0) {
31         bc = -bc;
32     }
33     return ab == 0 || bc < 0;
34 }
35 
36 ////////////////////////////////////////////////////////////////////////
37 
valid_unit_divide(SkScalar numer,SkScalar denom,SkScalar * ratio)38 static int valid_unit_divide(SkScalar numer, SkScalar denom, SkScalar* ratio) {
39     SkASSERT(ratio);
40 
41     if (numer < 0) {
42         numer = -numer;
43         denom = -denom;
44     }
45 
46     if (denom == 0 || numer == 0 || numer >= denom) {
47         return 0;
48     }
49 
50     SkScalar r = numer / denom;
51     if (SkScalarIsNaN(r)) {
52         return 0;
53     }
54     SkASSERTF(r >= 0 && r < SK_Scalar1, "numer %f, denom %f, r %f", numer, denom, r);
55     if (r == 0) { // catch underflow if numer <<<< denom
56         return 0;
57     }
58     *ratio = r;
59     return 1;
60 }
61 
62 // Just returns its argument, but makes it easy to set a break-point to know when
63 // SkFindUnitQuadRoots is going to return 0 (an error).
return_check_zero(int value)64 static int return_check_zero(int value) {
65     if (value == 0) {
66         return 0;
67     }
68     return value;
69 }
70 
71 /** From Numerical Recipes in C.
72 
73     Q = -1/2 (B + sign(B) sqrt[B*B - 4*A*C])
74     x1 = Q / A
75     x2 = C / Q
76 */
SkFindUnitQuadRoots(SkScalar A,SkScalar B,SkScalar C,SkScalar roots[2])77 int SkFindUnitQuadRoots(SkScalar A, SkScalar B, SkScalar C, SkScalar roots[2]) {
78     SkASSERT(roots);
79 
80     if (A == 0) {
81         return return_check_zero(valid_unit_divide(-C, B, roots));
82     }
83 
84     SkScalar* r = roots;
85 
86     // use doubles so we don't overflow temporarily trying to compute R
87     double dr = (double)B * B - 4 * (double)A * C;
88     if (dr < 0) {
89         return return_check_zero(0);
90     }
91     dr = sqrt(dr);
92     SkScalar R = SkDoubleToScalar(dr);
93     if (!SkScalarIsFinite(R)) {
94         return return_check_zero(0);
95     }
96 
97     SkScalar Q = (B < 0) ? -(B-R)/2 : -(B+R)/2;
98     r += valid_unit_divide(Q, A, r);
99     r += valid_unit_divide(C, Q, r);
100     if (r - roots == 2) {
101         if (roots[0] > roots[1]) {
102             using std::swap;
103             swap(roots[0], roots[1]);
104         } else if (roots[0] == roots[1]) { // nearly-equal?
105             r -= 1; // skip the double root
106         }
107     }
108     return return_check_zero((int)(r - roots));
109 }
110 
111 ///////////////////////////////////////////////////////////////////////////////
112 ///////////////////////////////////////////////////////////////////////////////
113 
SkEvalQuadAt(const SkPoint src[3],SkScalar t,SkPoint * pt,SkVector * tangent)114 void SkEvalQuadAt(const SkPoint src[3], SkScalar t, SkPoint* pt, SkVector* tangent) {
115     SkASSERT(src);
116     SkASSERT(t >= 0 && t <= SK_Scalar1);
117 
118     if (pt) {
119         *pt = SkEvalQuadAt(src, t);
120     }
121     if (tangent) {
122         *tangent = SkEvalQuadTangentAt(src, t);
123     }
124 }
125 
SkEvalQuadAt(const SkPoint src[3],SkScalar t)126 SkPoint SkEvalQuadAt(const SkPoint src[3], SkScalar t) {
127     return to_point(SkQuadCoeff(src).eval(t));
128 }
129 
SkEvalQuadTangentAt(const SkPoint src[3],SkScalar t)130 SkVector SkEvalQuadTangentAt(const SkPoint src[3], SkScalar t) {
131     // The derivative equation is 2(b - a +(a - 2b +c)t). This returns a
132     // zero tangent vector when t is 0 or 1, and the control point is equal
133     // to the end point. In this case, use the quad end points to compute the tangent.
134     if ((t == 0 && src[0] == src[1]) || (t == 1 && src[1] == src[2])) {
135         return src[2] - src[0];
136     }
137     SkASSERT(src);
138     SkASSERT(t >= 0 && t <= SK_Scalar1);
139 
140     Sk2s P0 = from_point(src[0]);
141     Sk2s P1 = from_point(src[1]);
142     Sk2s P2 = from_point(src[2]);
143 
144     Sk2s B = P1 - P0;
145     Sk2s A = P2 - P1 - B;
146     Sk2s T = A * Sk2s(t) + B;
147 
148     return to_vector(T + T);
149 }
150 
interp(const Sk2s & v0,const Sk2s & v1,const Sk2s & t)151 static inline Sk2s interp(const Sk2s& v0, const Sk2s& v1, const Sk2s& t) {
152     return v0 + (v1 - v0) * t;
153 }
154 
SkChopQuadAt(const SkPoint src[3],SkPoint dst[5],SkScalar t)155 void SkChopQuadAt(const SkPoint src[3], SkPoint dst[5], SkScalar t) {
156     SkASSERT(t > 0 && t < SK_Scalar1);
157 
158     Sk2s p0 = from_point(src[0]);
159     Sk2s p1 = from_point(src[1]);
160     Sk2s p2 = from_point(src[2]);
161     Sk2s tt(t);
162 
163     Sk2s p01 = interp(p0, p1, tt);
164     Sk2s p12 = interp(p1, p2, tt);
165 
166     dst[0] = to_point(p0);
167     dst[1] = to_point(p01);
168     dst[2] = to_point(interp(p01, p12, tt));
169     dst[3] = to_point(p12);
170     dst[4] = to_point(p2);
171 }
172 
SkChopQuadAtHalf(const SkPoint src[3],SkPoint dst[5])173 void SkChopQuadAtHalf(const SkPoint src[3], SkPoint dst[5]) {
174     SkChopQuadAt(src, dst, 0.5f);
175 }
176 
SkMeasureAngleBetweenVectors(SkVector a,SkVector b)177 float SkMeasureAngleBetweenVectors(SkVector a, SkVector b) {
178     float cosTheta = sk_ieee_float_divide(a.dot(b), sqrtf(a.dot(a) * b.dot(b)));
179     // Pin cosTheta such that if it is NaN (e.g., if a or b was 0), then we return acos(1) = 0.
180     cosTheta = std::max(std::min(1.f, cosTheta), -1.f);
181     return acosf(cosTheta);
182 }
183 
SkFindBisector(SkVector a,SkVector b)184 SkVector SkFindBisector(SkVector a, SkVector b) {
185     std::array<SkVector, 2> v;
186     if (a.dot(b) >= 0) {
187         // a,b are within +/-90 degrees apart.
188         v = {a, b};
189     } else if (a.cross(b) >= 0) {
190         // a,b are >90 degrees apart. Find the bisector of their interior normals instead. (Above 90
191         // degrees, the original vectors start cancelling each other out which eventually becomes
192         // unstable.)
193         v[0].set(-a.fY, +a.fX);
194         v[1].set(+b.fY, -b.fX);
195     } else {
196         // a,b are <-90 degrees apart. Find the bisector of their interior normals instead. (Below
197         // -90 degrees, the original vectors start cancelling each other out which eventually
198         // becomes unstable.)
199         v[0].set(+a.fY, -a.fX);
200         v[1].set(-b.fY, +b.fX);
201     }
202     // Return "normalize(v[0]) + normalize(v[1])".
203     Sk2f x0_x1, y0_y1;
204     Sk2f::Load2(v.data(), &x0_x1, &y0_y1);
205     Sk2f invLengths = 1.0f / (x0_x1 * x0_x1 + y0_y1 * y0_y1).sqrt();
206     x0_x1 *= invLengths;
207     y0_y1 *= invLengths;
208     return SkPoint{x0_x1[0] + x0_x1[1], y0_y1[0] + y0_y1[1]};
209 }
210 
SkFindQuadMidTangent(const SkPoint src[3])211 float SkFindQuadMidTangent(const SkPoint src[3]) {
212     // Tangents point in the direction of increasing T, so tan0 and -tan1 both point toward the
213     // midtangent. The bisector of tan0 and -tan1 is orthogonal to the midtangent:
214     //
215     //     n dot midtangent = 0
216     //
217     SkVector tan0 = src[1] - src[0];
218     SkVector tan1 = src[2] - src[1];
219     SkVector bisector = SkFindBisector(tan0, -tan1);
220 
221     // The midtangent can be found where (F' dot bisector) = 0:
222     //
223     //   0 = (F'(T) dot bisector) = |2*T 1| * |p0 - 2*p1 + p2| * |bisector.x|
224     //                                        |-2*p0 + 2*p1  |   |bisector.y|
225     //
226     //                     = |2*T 1| * |tan1 - tan0| * |nx|
227     //                                 |2*tan0     |   |ny|
228     //
229     //                     = 2*T * ((tan1 - tan0) dot bisector) + (2*tan0 dot bisector)
230     //
231     //   T = (tan0 dot bisector) / ((tan0 - tan1) dot bisector)
232     float T = sk_ieee_float_divide(tan0.dot(bisector), (tan0 - tan1).dot(bisector));
233     if (!(T > 0 && T < 1)) {  // Use "!(positive_logic)" so T=nan will take this branch.
234         T = .5;  // The quadratic was a line or near-line. Just chop at .5.
235     }
236 
237     return T;
238 }
239 
240 /** Quad'(t) = At + B, where
241     A = 2(a - 2b + c)
242     B = 2(b - a)
243     Solve for t, only if it fits between 0 < t < 1
244 */
SkFindQuadExtrema(SkScalar a,SkScalar b,SkScalar c,SkScalar tValue[1])245 int SkFindQuadExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar tValue[1]) {
246     /*  At + B == 0
247         t = -B / A
248     */
249     return valid_unit_divide(a - b, a - b - b + c, tValue);
250 }
251 
flatten_double_quad_extrema(SkScalar coords[14])252 static inline void flatten_double_quad_extrema(SkScalar coords[14]) {
253     coords[2] = coords[6] = coords[4];
254 }
255 
256 /*  Returns 0 for 1 quad, and 1 for two quads, either way the answer is
257  stored in dst[]. Guarantees that the 1/2 quads will be monotonic.
258  */
SkChopQuadAtYExtrema(const SkPoint src[3],SkPoint dst[5])259 int SkChopQuadAtYExtrema(const SkPoint src[3], SkPoint dst[5]) {
260     SkASSERT(src);
261     SkASSERT(dst);
262 
263     SkScalar a = src[0].fY;
264     SkScalar b = src[1].fY;
265     SkScalar c = src[2].fY;
266 
267     if (is_not_monotonic(a, b, c)) {
268         SkScalar    tValue;
269         if (valid_unit_divide(a - b, a - b - b + c, &tValue)) {
270             SkChopQuadAt(src, dst, tValue);
271             flatten_double_quad_extrema(&dst[0].fY);
272             return 1;
273         }
274         // if we get here, we need to force dst to be monotonic, even though
275         // we couldn't compute a unit_divide value (probably underflow).
276         b = SkScalarAbs(a - b) < SkScalarAbs(b - c) ? a : c;
277     }
278     dst[0].set(src[0].fX, a);
279     dst[1].set(src[1].fX, b);
280     dst[2].set(src[2].fX, c);
281     return 0;
282 }
283 
284 /*  Returns 0 for 1 quad, and 1 for two quads, either way the answer is
285     stored in dst[]. Guarantees that the 1/2 quads will be monotonic.
286  */
SkChopQuadAtXExtrema(const SkPoint src[3],SkPoint dst[5])287 int SkChopQuadAtXExtrema(const SkPoint src[3], SkPoint dst[5]) {
288     SkASSERT(src);
289     SkASSERT(dst);
290 
291     SkScalar a = src[0].fX;
292     SkScalar b = src[1].fX;
293     SkScalar c = src[2].fX;
294 
295     if (is_not_monotonic(a, b, c)) {
296         SkScalar tValue;
297         if (valid_unit_divide(a - b, a - b - b + c, &tValue)) {
298             SkChopQuadAt(src, dst, tValue);
299             flatten_double_quad_extrema(&dst[0].fX);
300             return 1;
301         }
302         // if we get here, we need to force dst to be monotonic, even though
303         // we couldn't compute a unit_divide value (probably underflow).
304         b = SkScalarAbs(a - b) < SkScalarAbs(b - c) ? a : c;
305     }
306     dst[0].set(a, src[0].fY);
307     dst[1].set(b, src[1].fY);
308     dst[2].set(c, src[2].fY);
309     return 0;
310 }
311 
312 //  F(t)    = a (1 - t) ^ 2 + 2 b t (1 - t) + c t ^ 2
313 //  F'(t)   = 2 (b - a) + 2 (a - 2b + c) t
314 //  F''(t)  = 2 (a - 2b + c)
315 //
316 //  A = 2 (b - a)
317 //  B = 2 (a - 2b + c)
318 //
319 //  Maximum curvature for a quadratic means solving
320 //  Fx' Fx'' + Fy' Fy'' = 0
321 //
322 //  t = - (Ax Bx + Ay By) / (Bx ^ 2 + By ^ 2)
323 //
SkFindQuadMaxCurvature(const SkPoint src[3])324 SkScalar SkFindQuadMaxCurvature(const SkPoint src[3]) {
325     SkScalar    Ax = src[1].fX - src[0].fX;
326     SkScalar    Ay = src[1].fY - src[0].fY;
327     SkScalar    Bx = src[0].fX - src[1].fX - src[1].fX + src[2].fX;
328     SkScalar    By = src[0].fY - src[1].fY - src[1].fY + src[2].fY;
329 
330     SkScalar numer = -(Ax * Bx + Ay * By);
331     SkScalar denom = Bx * Bx + By * By;
332     if (denom < 0) {
333         numer = -numer;
334         denom = -denom;
335     }
336     if (numer <= 0) {
337         return 0;
338     }
339     if (numer >= denom) {  // Also catches denom=0.
340         return 1;
341     }
342     SkScalar t = numer / denom;
343     SkASSERT((0 <= t && t < 1) || SkScalarIsNaN(t));
344     return t;
345 }
346 
SkChopQuadAtMaxCurvature(const SkPoint src[3],SkPoint dst[5])347 int SkChopQuadAtMaxCurvature(const SkPoint src[3], SkPoint dst[5]) {
348     SkScalar t = SkFindQuadMaxCurvature(src);
349     if (t > 0 && t < 1) {
350         SkChopQuadAt(src, dst, t);
351         return 2;
352     } else {
353         memcpy(dst, src, 3 * sizeof(SkPoint));
354         return 1;
355     }
356 }
357 
SkConvertQuadToCubic(const SkPoint src[3],SkPoint dst[4])358 void SkConvertQuadToCubic(const SkPoint src[3], SkPoint dst[4]) {
359     Sk2s scale(SkDoubleToScalar(2.0 / 3.0));
360     Sk2s s0 = from_point(src[0]);
361     Sk2s s1 = from_point(src[1]);
362     Sk2s s2 = from_point(src[2]);
363 
364     dst[0] = to_point(s0);
365     dst[1] = to_point(s0 + (s1 - s0) * scale);
366     dst[2] = to_point(s2 + (s1 - s2) * scale);
367     dst[3] = to_point(s2);
368 }
369 
370 //////////////////////////////////////////////////////////////////////////////
371 ///// CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS /////
372 //////////////////////////////////////////////////////////////////////////////
373 
eval_cubic_derivative(const SkPoint src[4],SkScalar t)374 static SkVector eval_cubic_derivative(const SkPoint src[4], SkScalar t) {
375     SkQuadCoeff coeff;
376     Sk2s P0 = from_point(src[0]);
377     Sk2s P1 = from_point(src[1]);
378     Sk2s P2 = from_point(src[2]);
379     Sk2s P3 = from_point(src[3]);
380 
381     coeff.fA = P3 + Sk2s(3) * (P1 - P2) - P0;
382     coeff.fB = times_2(P2 - times_2(P1) + P0);
383     coeff.fC = P1 - P0;
384     return to_vector(coeff.eval(t));
385 }
386 
eval_cubic_2ndDerivative(const SkPoint src[4],SkScalar t)387 static SkVector eval_cubic_2ndDerivative(const SkPoint src[4], SkScalar t) {
388     Sk2s P0 = from_point(src[0]);
389     Sk2s P1 = from_point(src[1]);
390     Sk2s P2 = from_point(src[2]);
391     Sk2s P3 = from_point(src[3]);
392     Sk2s A = P3 + Sk2s(3) * (P1 - P2) - P0;
393     Sk2s B = P2 - times_2(P1) + P0;
394 
395     return to_vector(A * Sk2s(t) + B);
396 }
397 
SkEvalCubicAt(const SkPoint src[4],SkScalar t,SkPoint * loc,SkVector * tangent,SkVector * curvature)398 void SkEvalCubicAt(const SkPoint src[4], SkScalar t, SkPoint* loc,
399                    SkVector* tangent, SkVector* curvature) {
400     SkASSERT(src);
401     SkASSERT(t >= 0 && t <= SK_Scalar1);
402 
403     if (loc) {
404         *loc = to_point(SkCubicCoeff(src).eval(t));
405     }
406     if (tangent) {
407         // The derivative equation returns a zero tangent vector when t is 0 or 1, and the
408         // adjacent control point is equal to the end point. In this case, use the
409         // next control point or the end points to compute the tangent.
410         if ((t == 0 && src[0] == src[1]) || (t == 1 && src[2] == src[3])) {
411             if (t == 0) {
412                 *tangent = src[2] - src[0];
413             } else {
414                 *tangent = src[3] - src[1];
415             }
416             if (!tangent->fX && !tangent->fY) {
417                 *tangent = src[3] - src[0];
418             }
419         } else {
420             *tangent = eval_cubic_derivative(src, t);
421         }
422     }
423     if (curvature) {
424         *curvature = eval_cubic_2ndDerivative(src, t);
425     }
426 }
427 
428 /** Cubic'(t) = At^2 + Bt + C, where
429     A = 3(-a + 3(b - c) + d)
430     B = 6(a - 2b + c)
431     C = 3(b - a)
432     Solve for t, keeping only those that fit betwee 0 < t < 1
433 */
SkFindCubicExtrema(SkScalar a,SkScalar b,SkScalar c,SkScalar d,SkScalar tValues[2])434 int SkFindCubicExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar d,
435                        SkScalar tValues[2]) {
436     // we divide A,B,C by 3 to simplify
437     SkScalar A = d - a + 3*(b - c);
438     SkScalar B = 2*(a - b - b + c);
439     SkScalar C = b - a;
440 
441     return SkFindUnitQuadRoots(A, B, C, tValues);
442 }
443 
444 // This does not return b when t==1, but it otherwise seems to get better precision than
445 // "a*(1 - t) + b*t" for things like chopping cubics on exact cusp points.
446 // The responsibility falls on the caller to check that t != 1 before calling.
447 template<int N, typename T>
unchecked_mix(const skvx::Vec<N,T> & a,const skvx::Vec<N,T> & b,const skvx::Vec<N,T> & t)448 inline static skvx::Vec<N,T> unchecked_mix(const skvx::Vec<N,T>& a, const skvx::Vec<N,T>& b,
449                                            const skvx::Vec<N,T>& t) {
450     return (b - a)*t + a;
451 }
452 
SkChopCubicAt(const SkPoint src[4],SkPoint dst[7],SkScalar t)453 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[7], SkScalar t) {
454     using float2 = skvx::Vec<2,float>;
455     SkASSERT(0 <= t && t <= 1);
456 
457     if (t == 1) {
458         memcpy(dst, src, sizeof(SkPoint) * 4);
459         dst[4] = dst[5] = dst[6] = src[3];
460         return;
461     }
462 
463     float2 p0 = skvx::bit_pun<float2>(src[0]);
464     float2 p1 = skvx::bit_pun<float2>(src[1]);
465     float2 p2 = skvx::bit_pun<float2>(src[2]);
466     float2 p3 = skvx::bit_pun<float2>(src[3]);
467     float2 T = t;
468 
469     float2 ab = unchecked_mix(p0, p1, T);
470     float2 bc = unchecked_mix(p1, p2, T);
471     float2 cd = unchecked_mix(p2, p3, T);
472     float2 abc = unchecked_mix(ab, bc, T);
473     float2 bcd = unchecked_mix(bc, cd, T);
474     float2 abcd = unchecked_mix(abc, bcd, T);
475 
476     dst[0] = skvx::bit_pun<SkPoint>(p0);
477     dst[1] = skvx::bit_pun<SkPoint>(ab);
478     dst[2] = skvx::bit_pun<SkPoint>(abc);
479     dst[3] = skvx::bit_pun<SkPoint>(abcd);
480     dst[4] = skvx::bit_pun<SkPoint>(bcd);
481     dst[5] = skvx::bit_pun<SkPoint>(cd);
482     dst[6] = skvx::bit_pun<SkPoint>(p3);
483 }
484 
SkChopCubicAt(const SkPoint src[4],SkPoint dst[10],float t0,float t1)485 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[10], float t0, float t1) {
486     using float4 = skvx::Vec<4,float>;
487     using float2 = skvx::Vec<2,float>;
488     SkASSERT(0 <= t0 && t0 <= t1 && t1 <= 1);
489 
490     if (t1 == 1) {
491         SkChopCubicAt(src, dst, t0);
492         dst[7] = dst[8] = dst[9] = src[3];
493         return;
494     }
495 
496     // Perform both chops in parallel using 4-lane SIMD.
497     float4 p00, p11, p22, p33, T;
498     p00.lo = p00.hi = skvx::bit_pun<float2>(src[0]);
499     p11.lo = p11.hi = skvx::bit_pun<float2>(src[1]);
500     p22.lo = p22.hi = skvx::bit_pun<float2>(src[2]);
501     p33.lo = p33.hi = skvx::bit_pun<float2>(src[3]);
502     T.lo = t0;
503     T.hi = t1;
504 
505     float4 ab = unchecked_mix(p00, p11, T);
506     float4 bc = unchecked_mix(p11, p22, T);
507     float4 cd = unchecked_mix(p22, p33, T);
508     float4 abc = unchecked_mix(ab, bc, T);
509     float4 bcd = unchecked_mix(bc, cd, T);
510     float4 abcd = unchecked_mix(abc, bcd, T);
511     float4 middle = unchecked_mix(abc, bcd, skvx::shuffle<2,3,0,1>(T));
512 
513     dst[0] = skvx::bit_pun<SkPoint>(p00.lo);
514     dst[1] = skvx::bit_pun<SkPoint>(ab.lo);
515     dst[2] = skvx::bit_pun<SkPoint>(abc.lo);
516     dst[3] = skvx::bit_pun<SkPoint>(abcd.lo);
517     middle.store(dst + 4);
518     dst[6] = skvx::bit_pun<SkPoint>(abcd.hi);
519     dst[7] = skvx::bit_pun<SkPoint>(bcd.hi);
520     dst[8] = skvx::bit_pun<SkPoint>(cd.hi);
521     dst[9] = skvx::bit_pun<SkPoint>(p33.hi);
522 }
523 
SkChopCubicAt(const SkPoint src[4],SkPoint dst[],const SkScalar tValues[],int tCount)524 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[],
525                    const SkScalar tValues[], int tCount) {
526     using float2 = skvx::Vec<2,float>;
527 
528 #ifdef SK_DEBUG
529     float lastT = 0;
530     for (int i = 0; i < tCount; i++) {
531         SkASSERT(lastT <= tValues[i] && tValues[i] <= 1);
532         lastT = tValues[i];
533     }
534 #endif
535 
536     if (dst) {
537         if (tCount == 0) { // nothing to chop
538             memcpy(dst, src, 4*sizeof(SkPoint));
539         } else {
540             int i = 0;
541             for (; i < tCount - 1; i += 2) {
542                 // Do two chops at once.
543                 float2 tt = float2::Load(tValues + i);
544                 if (i != 0) {
545                     float lastT = tValues[i - 1];
546                     tt = skvx::pin((tt - lastT) / (1 - lastT), float2(0), float2(1));
547                 }
548                 SkChopCubicAt(src, dst, tt[0], tt[1]);
549                 src = dst = dst + 6;
550             }
551             if (i < tCount) {
552                 // Chop the final cubic if there was an odd number of chops.
553                 SkASSERT(i + 1 == tCount);
554                 float t = tValues[i];
555                 if (i != 0) {
556                     float lastT = tValues[i - 1];
557                     t = SkTPin(sk_ieee_float_divide(t - lastT, 1 - lastT), 0.f, 1.f);
558                 }
559                 SkChopCubicAt(src, dst, t);
560             }
561         }
562     }
563 }
564 
SkChopCubicAtHalf(const SkPoint src[4],SkPoint dst[7])565 void SkChopCubicAtHalf(const SkPoint src[4], SkPoint dst[7]) {
566     SkChopCubicAt(src, dst, 0.5f);
567 }
568 
SkMeasureNonInflectCubicRotation(const SkPoint pts[4])569 float SkMeasureNonInflectCubicRotation(const SkPoint pts[4]) {
570     SkVector a = pts[1] - pts[0];
571     SkVector b = pts[2] - pts[1];
572     SkVector c = pts[3] - pts[2];
573     if (a.isZero()) {
574         return SkMeasureAngleBetweenVectors(b, c);
575     }
576     if (b.isZero()) {
577         return SkMeasureAngleBetweenVectors(a, c);
578     }
579     if (c.isZero()) {
580         return SkMeasureAngleBetweenVectors(a, b);
581     }
582     // Postulate: When no points are colocated and there are no inflection points in T=0..1, the
583     // rotation is: 360 degrees, minus the angle [p0,p1,p2], minus the angle [p1,p2,p3].
584     return 2*SK_ScalarPI - SkMeasureAngleBetweenVectors(a,-b) - SkMeasureAngleBetweenVectors(b,-c);
585 }
586 
fma(const Sk4f & f,float m,const Sk4f & a)587 static Sk4f fma(const Sk4f& f, float m, const Sk4f& a) {
588     return SkNx_fma(f, Sk4f(m), a);
589 }
590 
591 // Finds the root nearest 0.5. Returns 0.5 if the roots are undefined or outside 0..1.
solve_quadratic_equation_for_midtangent(float a,float b,float c,float discr)592 static float solve_quadratic_equation_for_midtangent(float a, float b, float c, float discr) {
593     // Quadratic formula from Numerical Recipes in C:
594     float q = -.5f * (b + copysignf(sqrtf(discr), b));
595     // The roots are q/a and c/q. Pick the midtangent closer to T=.5.
596     float _5qa = -.5f*q*a;
597     float T = fabsf(q*q + _5qa) < fabsf(a*c + _5qa) ? sk_ieee_float_divide(q,a)
598                                                     : sk_ieee_float_divide(c,q);
599     if (!(T > 0 && T < 1)) {  // Use "!(positive_logic)" so T=NaN will take this branch.
600         // Either the curve is a flat line with no rotation or FP precision failed us. Chop at .5.
601         T = .5;
602     }
603     return T;
604 }
605 
solve_quadratic_equation_for_midtangent(float a,float b,float c)606 static float solve_quadratic_equation_for_midtangent(float a, float b, float c) {
607     return solve_quadratic_equation_for_midtangent(a, b, c, b*b - 4*a*c);
608 }
609 
SkFindCubicMidTangent(const SkPoint src[4])610 float SkFindCubicMidTangent(const SkPoint src[4]) {
611     // Tangents point in the direction of increasing T, so tan0 and -tan1 both point toward the
612     // midtangent. The bisector of tan0 and -tan1 is orthogonal to the midtangent:
613     //
614     //     bisector dot midtangent == 0
615     //
616     SkVector tan0 = (src[0] == src[1]) ? src[2] - src[0] : src[1] - src[0];
617     SkVector tan1 = (src[2] == src[3]) ? src[3] - src[1] : src[3] - src[2];
618     SkVector bisector = SkFindBisector(tan0, -tan1);
619 
620     // Find the T value at the midtangent. This is a simple quadratic equation:
621     //
622     //     midtangent dot bisector == 0, or using a tangent matrix C' in power basis form:
623     //
624     //                   |C'x  C'y|
625     //     |T^2  T  1| * |.    .  | * |bisector.x| == 0
626     //                   |.    .  |   |bisector.y|
627     //
628     // The coeffs for the quadratic equation we need to solve are therefore:  C' * bisector
629     static const Sk4f kM[4] = {Sk4f(-1,  2, -1,  0),
630                                Sk4f( 3, -4,  1,  0),
631                                Sk4f(-3,  2,  0,  0)};
632     Sk4f C_x = fma(kM[0], src[0].fX,
633                fma(kM[1], src[1].fX,
634                fma(kM[2], src[2].fX, Sk4f(src[3].fX, 0,0,0))));
635     Sk4f C_y = fma(kM[0], src[0].fY,
636                fma(kM[1], src[1].fY,
637                fma(kM[2], src[2].fY, Sk4f(src[3].fY, 0,0,0))));
638     Sk4f coeffs = C_x * bisector.x() + C_y * bisector.y();
639 
640     // Now solve the quadratic for T.
641     float T = 0;
642     float a=coeffs[0], b=coeffs[1], c=coeffs[2];
643     float discr = b*b - 4*a*c;
644     if (discr > 0) {  // This will only be false if the curve is a line.
645         return solve_quadratic_equation_for_midtangent(a, b, c, discr);
646     } else {
647         // This is a 0- or 360-degree flat line. It doesn't have single points of midtangent.
648         // (tangent == midtangent at every point on the curve except the cusp points.)
649         // Chop in between both cusps instead, if any. There can be up to two cusps on a flat line,
650         // both where the tangent is perpendicular to the starting tangent:
651         //
652         //     tangent dot tan0 == 0
653         //
654         coeffs = C_x * tan0.x() + C_y * tan0.y();
655         a = coeffs[0];
656         b = coeffs[1];
657         if (a != 0) {
658             // We want the point in between both cusps. The midpoint of:
659             //
660             //     (-b +/- sqrt(b^2 - 4*a*c)) / (2*a)
661             //
662             // Is equal to:
663             //
664             //     -b / (2*a)
665             T = -b / (2*a);
666         }
667         if (!(T > 0 && T < 1)) {  // Use "!(positive_logic)" so T=NaN will take this branch.
668             // Either the curve is a flat line with no rotation or FP precision failed us. Chop at
669             // .5.
670             T = .5;
671         }
672         return T;
673     }
674 }
675 
flatten_double_cubic_extrema(SkScalar coords[14])676 static void flatten_double_cubic_extrema(SkScalar coords[14]) {
677     coords[4] = coords[8] = coords[6];
678 }
679 
680 /** Given 4 points on a cubic bezier, chop it into 1, 2, 3 beziers such that
681     the resulting beziers are monotonic in Y. This is called by the scan
682     converter.  Depending on what is returned, dst[] is treated as follows:
683     0   dst[0..3] is the original cubic
684     1   dst[0..3] and dst[3..6] are the two new cubics
685     2   dst[0..3], dst[3..6], dst[6..9] are the three new cubics
686     If dst == null, it is ignored and only the count is returned.
687 */
SkChopCubicAtYExtrema(const SkPoint src[4],SkPoint dst[10])688 int SkChopCubicAtYExtrema(const SkPoint src[4], SkPoint dst[10]) {
689     SkScalar    tValues[2];
690     int         roots = SkFindCubicExtrema(src[0].fY, src[1].fY, src[2].fY,
691                                            src[3].fY, tValues);
692 
693     SkChopCubicAt(src, dst, tValues, roots);
694     if (dst && roots > 0) {
695         // we do some cleanup to ensure our Y extrema are flat
696         flatten_double_cubic_extrema(&dst[0].fY);
697         if (roots == 2) {
698             flatten_double_cubic_extrema(&dst[3].fY);
699         }
700     }
701     return roots;
702 }
703 
SkChopCubicAtXExtrema(const SkPoint src[4],SkPoint dst[10])704 int SkChopCubicAtXExtrema(const SkPoint src[4], SkPoint dst[10]) {
705     SkScalar    tValues[2];
706     int         roots = SkFindCubicExtrema(src[0].fX, src[1].fX, src[2].fX,
707                                            src[3].fX, tValues);
708 
709     SkChopCubicAt(src, dst, tValues, roots);
710     if (dst && roots > 0) {
711         // we do some cleanup to ensure our Y extrema are flat
712         flatten_double_cubic_extrema(&dst[0].fX);
713         if (roots == 2) {
714             flatten_double_cubic_extrema(&dst[3].fX);
715         }
716     }
717     return roots;
718 }
719 
720 /** http://www.faculty.idc.ac.il/arik/quality/appendixA.html
721 
722     Inflection means that curvature is zero.
723     Curvature is [F' x F''] / [F'^3]
724     So we solve F'x X F''y - F'y X F''y == 0
725     After some canceling of the cubic term, we get
726     A = b - a
727     B = c - 2b + a
728     C = d - 3c + 3b - a
729     (BxCy - ByCx)t^2 + (AxCy - AyCx)t + AxBy - AyBx == 0
730 */
SkFindCubicInflections(const SkPoint src[4],SkScalar tValues[])731 int SkFindCubicInflections(const SkPoint src[4], SkScalar tValues[]) {
732     SkScalar    Ax = src[1].fX - src[0].fX;
733     SkScalar    Ay = src[1].fY - src[0].fY;
734     SkScalar    Bx = src[2].fX - 2 * src[1].fX + src[0].fX;
735     SkScalar    By = src[2].fY - 2 * src[1].fY + src[0].fY;
736     SkScalar    Cx = src[3].fX + 3 * (src[1].fX - src[2].fX) - src[0].fX;
737     SkScalar    Cy = src[3].fY + 3 * (src[1].fY - src[2].fY) - src[0].fY;
738 
739     return SkFindUnitQuadRoots(Bx*Cy - By*Cx,
740                                Ax*Cy - Ay*Cx,
741                                Ax*By - Ay*Bx,
742                                tValues);
743 }
744 
SkChopCubicAtInflections(const SkPoint src[],SkPoint dst[10])745 int SkChopCubicAtInflections(const SkPoint src[], SkPoint dst[10]) {
746     SkScalar    tValues[2];
747     int         count = SkFindCubicInflections(src, tValues);
748 
749     if (dst) {
750         if (count == 0) {
751             memcpy(dst, src, 4 * sizeof(SkPoint));
752         } else {
753             SkChopCubicAt(src, dst, tValues, count);
754         }
755     }
756     return count + 1;
757 }
758 
759 // Assumes the third component of points is 1.
760 // Calcs p0 . (p1 x p2)
calc_dot_cross_cubic(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2)761 static double calc_dot_cross_cubic(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2) {
762     const double xComp = (double) p0.fX * ((double) p1.fY - (double) p2.fY);
763     const double yComp = (double) p0.fY * ((double) p2.fX - (double) p1.fX);
764     const double wComp = (double) p1.fX * (double) p2.fY - (double) p1.fY * (double) p2.fX;
765     return (xComp + yComp + wComp);
766 }
767 
768 // Returns a positive power of 2 that, when multiplied by n, and excepting the two edge cases listed
769 // below, shifts the exponent of n to yield a magnitude somewhere inside [1..2).
770 // Returns 2^1023 if abs(n) < 2^-1022 (including 0).
771 // Returns NaN if n is Inf or NaN.
previous_inverse_pow2(double n)772 inline static double previous_inverse_pow2(double n) {
773     uint64_t bits;
774     memcpy(&bits, &n, sizeof(double));
775     bits = ((1023llu*2 << 52) + ((1llu << 52) - 1)) - bits; // exp=-exp
776     bits &= (0x7ffllu) << 52; // mantissa=1.0, sign=0
777     memcpy(&n, &bits, sizeof(double));
778     return n;
779 }
780 
write_cubic_inflection_roots(double t0,double s0,double t1,double s1,double * t,double * s)781 inline static void write_cubic_inflection_roots(double t0, double s0, double t1, double s1,
782                                                 double* t, double* s) {
783     t[0] = t0;
784     s[0] = s0;
785 
786     // This copysign/abs business orients the implicit function so positive values are always on the
787     // "left" side of the curve.
788     t[1] = -copysign(t1, t1 * s1);
789     s[1] = -fabs(s1);
790 
791     // Ensure t[0]/s[0] <= t[1]/s[1] (s[1] is negative from above).
792     if (copysign(s[1], s[0]) * t[0] > -fabs(s[0]) * t[1]) {
793         using std::swap;
794         swap(t[0], t[1]);
795         swap(s[0], s[1]);
796     }
797 }
798 
SkClassifyCubic(const SkPoint P[4],double t[2],double s[2],double d[4])799 SkCubicType SkClassifyCubic(const SkPoint P[4], double t[2], double s[2], double d[4]) {
800     // Find the cubic's inflection function, I = [T^3  -3T^2  3T  -1] dot D. (D0 will always be 0
801     // for integral cubics.)
802     //
803     // See "Resolution Independent Curve Rendering using Programmable Graphics Hardware",
804     // 4.2 Curve Categorization:
805     //
806     // https://www.microsoft.com/en-us/research/wp-content/uploads/2005/01/p1000-loop.pdf
807     double A1 = calc_dot_cross_cubic(P[0], P[3], P[2]);
808     double A2 = calc_dot_cross_cubic(P[1], P[0], P[3]);
809     double A3 = calc_dot_cross_cubic(P[2], P[1], P[0]);
810 
811     double D3 = 3 * A3;
812     double D2 = D3 - A2;
813     double D1 = D2 - A2 + A1;
814 
815     // Shift the exponents in D so the largest magnitude falls somewhere in 1..2. This protects us
816     // from overflow down the road while solving for roots and KLM functionals.
817     double Dmax = std::max(std::max(fabs(D1), fabs(D2)), fabs(D3));
818     double norm = previous_inverse_pow2(Dmax);
819     D1 *= norm;
820     D2 *= norm;
821     D3 *= norm;
822 
823     if (d) {
824         d[3] = D3;
825         d[2] = D2;
826         d[1] = D1;
827         d[0] = 0;
828     }
829 
830     // Now use the inflection function to classify the cubic.
831     //
832     // See "Resolution Independent Curve Rendering using Programmable Graphics Hardware",
833     // 4.4 Integral Cubics:
834     //
835     // https://www.microsoft.com/en-us/research/wp-content/uploads/2005/01/p1000-loop.pdf
836     if (0 != D1) {
837         double discr = 3*D2*D2 - 4*D1*D3;
838         if (discr > 0) { // Serpentine.
839             if (t && s) {
840                 double q = 3*D2 + copysign(sqrt(3*discr), D2);
841                 write_cubic_inflection_roots(q, 6*D1, 2*D3, q, t, s);
842             }
843             return SkCubicType::kSerpentine;
844         } else if (discr < 0) { // Loop.
845             if (t && s) {
846                 double q = D2 + copysign(sqrt(-discr), D2);
847                 write_cubic_inflection_roots(q, 2*D1, 2*(D2*D2 - D3*D1), D1*q, t, s);
848             }
849             return SkCubicType::kLoop;
850         } else { // Cusp.
851             if (t && s) {
852                 write_cubic_inflection_roots(D2, 2*D1, D2, 2*D1, t, s);
853             }
854             return SkCubicType::kLocalCusp;
855         }
856     } else {
857         if (0 != D2) { // Cusp at T=infinity.
858             if (t && s) {
859                 write_cubic_inflection_roots(D3, 3*D2, 1, 0, t, s); // T1=infinity.
860             }
861             return SkCubicType::kCuspAtInfinity;
862         } else { // Degenerate.
863             if (t && s) {
864                 write_cubic_inflection_roots(1, 0, 1, 0, t, s); // T0=T1=infinity.
865             }
866             return 0 != D3 ? SkCubicType::kQuadratic : SkCubicType::kLineOrPoint;
867         }
868     }
869 }
870 
bubble_sort(T array[],int count)871 template <typename T> void bubble_sort(T array[], int count) {
872     for (int i = count - 1; i > 0; --i)
873         for (int j = i; j > 0; --j)
874             if (array[j] < array[j-1])
875             {
876                 T   tmp(array[j]);
877                 array[j] = array[j-1];
878                 array[j-1] = tmp;
879             }
880 }
881 
882 /**
883  *  Given an array and count, remove all pair-wise duplicates from the array,
884  *  keeping the existing sorting, and return the new count
885  */
collaps_duplicates(SkScalar array[],int count)886 static int collaps_duplicates(SkScalar array[], int count) {
887     for (int n = count; n > 1; --n) {
888         if (array[0] == array[1]) {
889             for (int i = 1; i < n; ++i) {
890                 array[i - 1] = array[i];
891             }
892             count -= 1;
893         } else {
894             array += 1;
895         }
896     }
897     return count;
898 }
899 
900 #ifdef SK_DEBUG
901 
902 #define TEST_COLLAPS_ENTRY(array)   array, SK_ARRAY_COUNT(array)
903 
test_collaps_duplicates()904 static void test_collaps_duplicates() {
905     static bool gOnce;
906     if (gOnce) { return; }
907     gOnce = true;
908     const SkScalar src0[] = { 0 };
909     const SkScalar src1[] = { 0, 0 };
910     const SkScalar src2[] = { 0, 1 };
911     const SkScalar src3[] = { 0, 0, 0 };
912     const SkScalar src4[] = { 0, 0, 1 };
913     const SkScalar src5[] = { 0, 1, 1 };
914     const SkScalar src6[] = { 0, 1, 2 };
915     const struct {
916         const SkScalar* fData;
917         int fCount;
918         int fCollapsedCount;
919     } data[] = {
920         { TEST_COLLAPS_ENTRY(src0), 1 },
921         { TEST_COLLAPS_ENTRY(src1), 1 },
922         { TEST_COLLAPS_ENTRY(src2), 2 },
923         { TEST_COLLAPS_ENTRY(src3), 1 },
924         { TEST_COLLAPS_ENTRY(src4), 2 },
925         { TEST_COLLAPS_ENTRY(src5), 2 },
926         { TEST_COLLAPS_ENTRY(src6), 3 },
927     };
928     for (size_t i = 0; i < SK_ARRAY_COUNT(data); ++i) {
929         SkScalar dst[3];
930         memcpy(dst, data[i].fData, data[i].fCount * sizeof(dst[0]));
931         int count = collaps_duplicates(dst, data[i].fCount);
932         SkASSERT(data[i].fCollapsedCount == count);
933         for (int j = 1; j < count; ++j) {
934             SkASSERT(dst[j-1] < dst[j]);
935         }
936     }
937 }
938 #endif
939 
SkScalarCubeRoot(SkScalar x)940 static SkScalar SkScalarCubeRoot(SkScalar x) {
941     return SkScalarPow(x, 0.3333333f);
942 }
943 
944 /*  Solve coeff(t) == 0, returning the number of roots that
945     lie withing 0 < t < 1.
946     coeff[0]t^3 + coeff[1]t^2 + coeff[2]t + coeff[3]
947 
948     Eliminates repeated roots (so that all tValues are distinct, and are always
949     in increasing order.
950 */
solve_cubic_poly(const SkScalar coeff[4],SkScalar tValues[3])951 static int solve_cubic_poly(const SkScalar coeff[4], SkScalar tValues[3]) {
952     if (SkScalarNearlyZero(coeff[0])) {  // we're just a quadratic
953         return SkFindUnitQuadRoots(coeff[1], coeff[2], coeff[3], tValues);
954     }
955 
956     SkScalar a, b, c, Q, R;
957 
958     {
959         SkASSERT(coeff[0] != 0);
960 
961         SkScalar inva = SkScalarInvert(coeff[0]);
962         a = coeff[1] * inva;
963         b = coeff[2] * inva;
964         c = coeff[3] * inva;
965     }
966     Q = (a*a - b*3) / 9;
967     R = (2*a*a*a - 9*a*b + 27*c) / 54;
968 
969     SkScalar Q3 = Q * Q * Q;
970     SkScalar R2MinusQ3 = R * R - Q3;
971     SkScalar adiv3 = a / 3;
972 
973     if (R2MinusQ3 < 0) { // we have 3 real roots
974         // the divide/root can, due to finite precisions, be slightly outside of -1...1
975         SkScalar theta = SkScalarACos(SkTPin(R / SkScalarSqrt(Q3), -1.0f, 1.0f));
976         SkScalar neg2RootQ = -2 * SkScalarSqrt(Q);
977 
978         tValues[0] = SkTPin(neg2RootQ * SkScalarCos(theta/3) - adiv3, 0.0f, 1.0f);
979         tValues[1] = SkTPin(neg2RootQ * SkScalarCos((theta + 2*SK_ScalarPI)/3) - adiv3, 0.0f, 1.0f);
980         tValues[2] = SkTPin(neg2RootQ * SkScalarCos((theta - 2*SK_ScalarPI)/3) - adiv3, 0.0f, 1.0f);
981         SkDEBUGCODE(test_collaps_duplicates();)
982 
983         // now sort the roots
984         bubble_sort(tValues, 3);
985         return collaps_duplicates(tValues, 3);
986     } else {              // we have 1 real root
987         SkScalar A = SkScalarAbs(R) + SkScalarSqrt(R2MinusQ3);
988         A = SkScalarCubeRoot(A);
989         if (R > 0) {
990             A = -A;
991         }
992         if (A != 0) {
993             A += Q / A;
994         }
995         tValues[0] = SkTPin(A - adiv3, 0.0f, 1.0f);
996         return 1;
997     }
998 }
999 
1000 /*  Looking for F' dot F'' == 0
1001 
1002     A = b - a
1003     B = c - 2b + a
1004     C = d - 3c + 3b - a
1005 
1006     F' = 3Ct^2 + 6Bt + 3A
1007     F'' = 6Ct + 6B
1008 
1009     F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
1010 */
formulate_F1DotF2(const SkScalar src[],SkScalar coeff[4])1011 static void formulate_F1DotF2(const SkScalar src[], SkScalar coeff[4]) {
1012     SkScalar    a = src[2] - src[0];
1013     SkScalar    b = src[4] - 2 * src[2] + src[0];
1014     SkScalar    c = src[6] + 3 * (src[2] - src[4]) - src[0];
1015 
1016     coeff[0] = c * c;
1017     coeff[1] = 3 * b * c;
1018     coeff[2] = 2 * b * b + c * a;
1019     coeff[3] = a * b;
1020 }
1021 
1022 /*  Looking for F' dot F'' == 0
1023 
1024     A = b - a
1025     B = c - 2b + a
1026     C = d - 3c + 3b - a
1027 
1028     F' = 3Ct^2 + 6Bt + 3A
1029     F'' = 6Ct + 6B
1030 
1031     F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
1032 */
SkFindCubicMaxCurvature(const SkPoint src[4],SkScalar tValues[3])1033 int SkFindCubicMaxCurvature(const SkPoint src[4], SkScalar tValues[3]) {
1034     SkScalar coeffX[4], coeffY[4];
1035     int      i;
1036 
1037     formulate_F1DotF2(&src[0].fX, coeffX);
1038     formulate_F1DotF2(&src[0].fY, coeffY);
1039 
1040     for (i = 0; i < 4; i++) {
1041         coeffX[i] += coeffY[i];
1042     }
1043 
1044     int numRoots = solve_cubic_poly(coeffX, tValues);
1045     // now remove extrema where the curvature is zero (mins)
1046     // !!!! need a test for this !!!!
1047     return numRoots;
1048 }
1049 
SkChopCubicAtMaxCurvature(const SkPoint src[4],SkPoint dst[13],SkScalar tValues[3])1050 int SkChopCubicAtMaxCurvature(const SkPoint src[4], SkPoint dst[13],
1051                               SkScalar tValues[3]) {
1052     SkScalar    t_storage[3];
1053 
1054     if (tValues == nullptr) {
1055         tValues = t_storage;
1056     }
1057 
1058     SkScalar roots[3];
1059     int rootCount = SkFindCubicMaxCurvature(src, roots);
1060 
1061     // Throw out values not inside 0..1.
1062     int count = 0;
1063     for (int i = 0; i < rootCount; ++i) {
1064         if (0 < roots[i] && roots[i] < 1) {
1065             tValues[count++] = roots[i];
1066         }
1067     }
1068 
1069     if (dst) {
1070         if (count == 0) {
1071             memcpy(dst, src, 4 * sizeof(SkPoint));
1072         } else {
1073             SkChopCubicAt(src, dst, tValues, count);
1074         }
1075     }
1076     return count + 1;
1077 }
1078 
1079 // Returns a constant proportional to the dimensions of the cubic.
1080 // Constant found through experimentation -- maybe there's a better way....
calc_cubic_precision(const SkPoint src[4])1081 static SkScalar calc_cubic_precision(const SkPoint src[4]) {
1082     return (SkPointPriv::DistanceToSqd(src[1], src[0]) + SkPointPriv::DistanceToSqd(src[2], src[1])
1083             + SkPointPriv::DistanceToSqd(src[3], src[2])) * 1e-8f;
1084 }
1085 
1086 // Returns true if both points src[testIndex], src[testIndex+1] are in the same half plane defined
1087 // by the line segment src[lineIndex], src[lineIndex+1].
on_same_side(const SkPoint src[4],int testIndex,int lineIndex)1088 static bool on_same_side(const SkPoint src[4], int testIndex, int lineIndex) {
1089     SkPoint origin = src[lineIndex];
1090     SkVector line = src[lineIndex + 1] - origin;
1091     SkScalar crosses[2];
1092     for (int index = 0; index < 2; ++index) {
1093         SkVector testLine = src[testIndex + index] - origin;
1094         crosses[index] = line.cross(testLine);
1095     }
1096     return crosses[0] * crosses[1] >= 0;
1097 }
1098 
1099 // Return location (in t) of cubic cusp, if there is one.
1100 // Note that classify cubic code does not reliably return all cusp'd cubics, so
1101 // it is not called here.
SkFindCubicCusp(const SkPoint src[4])1102 SkScalar SkFindCubicCusp(const SkPoint src[4]) {
1103     // When the adjacent control point matches the end point, it behaves as if
1104     // the cubic has a cusp: there's a point of max curvature where the derivative
1105     // goes to zero. Ideally, this would be where t is zero or one, but math
1106     // error makes not so. It is not uncommon to create cubics this way; skip them.
1107     if (src[0] == src[1]) {
1108         return -1;
1109     }
1110     if (src[2] == src[3]) {
1111         return -1;
1112     }
1113     // Cubics only have a cusp if the line segments formed by the control and end points cross.
1114     // Detect crossing if line ends are on opposite sides of plane formed by the other line.
1115     if (on_same_side(src, 0, 2) || on_same_side(src, 2, 0)) {
1116         return -1;
1117     }
1118     // Cubics may have multiple points of maximum curvature, although at most only
1119     // one is a cusp.
1120     SkScalar maxCurvature[3];
1121     int roots = SkFindCubicMaxCurvature(src, maxCurvature);
1122     for (int index = 0; index < roots; ++index) {
1123         SkScalar testT = maxCurvature[index];
1124         if (0 >= testT || testT >= 1) {  // no need to consider max curvature on the end
1125             continue;
1126         }
1127         // A cusp is at the max curvature, and also has a derivative close to zero.
1128         // Choose the 'close to zero' meaning by comparing the derivative length
1129         // with the overall cubic size.
1130         SkVector dPt = eval_cubic_derivative(src, testT);
1131         SkScalar dPtMagnitude = SkPointPriv::LengthSqd(dPt);
1132         SkScalar precision = calc_cubic_precision(src);
1133         if (dPtMagnitude < precision) {
1134             // All three max curvature t values may be close to the cusp;
1135             // return the first one.
1136             return testT;
1137         }
1138     }
1139     return -1;
1140 }
1141 
1142 #include "src/pathops/SkPathOpsCubic.h"
1143 
1144 typedef int (SkDCubic::*InterceptProc)(double intercept, double roots[3]) const;
1145 
cubic_dchop_at_intercept(const SkPoint src[4],SkScalar intercept,SkPoint dst[7],InterceptProc method)1146 static bool cubic_dchop_at_intercept(const SkPoint src[4], SkScalar intercept, SkPoint dst[7],
1147                                      InterceptProc method) {
1148     SkDCubic cubic;
1149     double roots[3];
1150     int count = (cubic.set(src).*method)(intercept, roots);
1151     if (count > 0) {
1152         SkDCubicPair pair = cubic.chopAt(roots[0]);
1153         for (int i = 0; i < 7; ++i) {
1154             dst[i] = pair.pts[i].asSkPoint();
1155         }
1156         return true;
1157     }
1158     return false;
1159 }
1160 
SkChopMonoCubicAtY(SkPoint src[4],SkScalar y,SkPoint dst[7])1161 bool SkChopMonoCubicAtY(SkPoint src[4], SkScalar y, SkPoint dst[7]) {
1162     return cubic_dchop_at_intercept(src, y, dst, &SkDCubic::horizontalIntersect);
1163 }
1164 
SkChopMonoCubicAtX(SkPoint src[4],SkScalar x,SkPoint dst[7])1165 bool SkChopMonoCubicAtX(SkPoint src[4], SkScalar x, SkPoint dst[7]) {
1166     return cubic_dchop_at_intercept(src, x, dst, &SkDCubic::verticalIntersect);
1167 }
1168 
1169 ///////////////////////////////////////////////////////////////////////////////
1170 //
1171 // NURB representation for conics.  Helpful explanations at:
1172 //
1173 // http://citeseerx.ist.psu.edu/viewdoc/
1174 //   download?doi=10.1.1.44.5740&rep=rep1&type=ps
1175 // and
1176 // http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/NURBS/RB-conics.html
1177 //
1178 // F = (A (1 - t)^2 + C t^2 + 2 B (1 - t) t w)
1179 //     ------------------------------------------
1180 //         ((1 - t)^2 + t^2 + 2 (1 - t) t w)
1181 //
1182 //   = {t^2 (P0 + P2 - 2 P1 w), t (-2 P0 + 2 P1 w), P0}
1183 //     ------------------------------------------------
1184 //             {t^2 (2 - 2 w), t (-2 + 2 w), 1}
1185 //
1186 
1187 // F' = 2 (C t (1 + t (-1 + w)) - A (-1 + t) (t (-1 + w) - w) + B (1 - 2 t) w)
1188 //
1189 //  t^2 : (2 P0 - 2 P2 - 2 P0 w + 2 P2 w)
1190 //  t^1 : (-2 P0 + 2 P2 + 4 P0 w - 4 P1 w)
1191 //  t^0 : -2 P0 w + 2 P1 w
1192 //
1193 //  We disregard magnitude, so we can freely ignore the denominator of F', and
1194 //  divide the numerator by 2
1195 //
1196 //    coeff[0] for t^2
1197 //    coeff[1] for t^1
1198 //    coeff[2] for t^0
1199 //
conic_deriv_coeff(const SkScalar src[],SkScalar w,SkScalar coeff[3])1200 static void conic_deriv_coeff(const SkScalar src[],
1201                               SkScalar w,
1202                               SkScalar coeff[3]) {
1203     const SkScalar P20 = src[4] - src[0];
1204     const SkScalar P10 = src[2] - src[0];
1205     const SkScalar wP10 = w * P10;
1206     coeff[0] = w * P20 - P20;
1207     coeff[1] = P20 - 2 * wP10;
1208     coeff[2] = wP10;
1209 }
1210 
conic_find_extrema(const SkScalar src[],SkScalar w,SkScalar * t)1211 static bool conic_find_extrema(const SkScalar src[], SkScalar w, SkScalar* t) {
1212     SkScalar coeff[3];
1213     conic_deriv_coeff(src, w, coeff);
1214 
1215     SkScalar tValues[2];
1216     int roots = SkFindUnitQuadRoots(coeff[0], coeff[1], coeff[2], tValues);
1217     SkASSERT(0 == roots || 1 == roots);
1218 
1219     if (1 == roots) {
1220         *t = tValues[0];
1221         return true;
1222     }
1223     return false;
1224 }
1225 
1226 // We only interpolate one dimension at a time (the first, at +0, +3, +6).
p3d_interp(const SkScalar src[7],SkScalar dst[7],SkScalar t)1227 static void p3d_interp(const SkScalar src[7], SkScalar dst[7], SkScalar t) {
1228     SkScalar ab = SkScalarInterp(src[0], src[3], t);
1229     SkScalar bc = SkScalarInterp(src[3], src[6], t);
1230     dst[0] = ab;
1231     dst[3] = SkScalarInterp(ab, bc, t);
1232     dst[6] = bc;
1233 }
1234 
ratquad_mapTo3D(const SkPoint src[3],SkScalar w,SkPoint3 dst[3])1235 static void ratquad_mapTo3D(const SkPoint src[3], SkScalar w, SkPoint3 dst[3]) {
1236     dst[0].set(src[0].fX * 1, src[0].fY * 1, 1);
1237     dst[1].set(src[1].fX * w, src[1].fY * w, w);
1238     dst[2].set(src[2].fX * 1, src[2].fY * 1, 1);
1239 }
1240 
project_down(const SkPoint3 & src)1241 static SkPoint project_down(const SkPoint3& src) {
1242     return {src.fX / src.fZ, src.fY / src.fZ};
1243 }
1244 
1245 // return false if infinity or NaN is generated; caller must check
chopAt(SkScalar t,SkConic dst[2]) const1246 bool SkConic::chopAt(SkScalar t, SkConic dst[2]) const {
1247     SkPoint3 tmp[3], tmp2[3];
1248 
1249     ratquad_mapTo3D(fPts, fW, tmp);
1250 
1251     p3d_interp(&tmp[0].fX, &tmp2[0].fX, t);
1252     p3d_interp(&tmp[0].fY, &tmp2[0].fY, t);
1253     p3d_interp(&tmp[0].fZ, &tmp2[0].fZ, t);
1254 
1255     dst[0].fPts[0] = fPts[0];
1256     dst[0].fPts[1] = project_down(tmp2[0]);
1257     dst[0].fPts[2] = project_down(tmp2[1]); dst[1].fPts[0] = dst[0].fPts[2];
1258     dst[1].fPts[1] = project_down(tmp2[2]);
1259     dst[1].fPts[2] = fPts[2];
1260 
1261     // to put in "standard form", where w0 and w2 are both 1, we compute the
1262     // new w1 as sqrt(w1*w1/w0*w2)
1263     // or
1264     // w1 /= sqrt(w0*w2)
1265     //
1266     // However, in our case, we know that for dst[0]:
1267     //     w0 == 1, and for dst[1], w2 == 1
1268     //
1269     SkScalar root = SkScalarSqrt(tmp2[1].fZ);
1270     dst[0].fW = tmp2[0].fZ / root;
1271     dst[1].fW = tmp2[2].fZ / root;
1272     SkASSERT(sizeof(dst[0]) == sizeof(SkScalar) * 7);
1273     SkASSERT(0 == offsetof(SkConic, fPts[0].fX));
1274     return SkScalarsAreFinite(&dst[0].fPts[0].fX, 7 * 2);
1275 }
1276 
chopAt(SkScalar t1,SkScalar t2,SkConic * dst) const1277 void SkConic::chopAt(SkScalar t1, SkScalar t2, SkConic* dst) const {
1278     if (0 == t1 || 1 == t2) {
1279         if (0 == t1 && 1 == t2) {
1280             *dst = *this;
1281             return;
1282         } else {
1283             SkConic pair[2];
1284             if (this->chopAt(t1 ? t1 : t2, pair)) {
1285                 *dst = pair[SkToBool(t1)];
1286                 return;
1287             }
1288         }
1289     }
1290     SkConicCoeff coeff(*this);
1291     Sk2s tt1(t1);
1292     Sk2s aXY = coeff.fNumer.eval(tt1);
1293     Sk2s aZZ = coeff.fDenom.eval(tt1);
1294     Sk2s midTT((t1 + t2) / 2);
1295     Sk2s dXY = coeff.fNumer.eval(midTT);
1296     Sk2s dZZ = coeff.fDenom.eval(midTT);
1297     Sk2s tt2(t2);
1298     Sk2s cXY = coeff.fNumer.eval(tt2);
1299     Sk2s cZZ = coeff.fDenom.eval(tt2);
1300     Sk2s bXY = times_2(dXY) - (aXY + cXY) * Sk2s(0.5f);
1301     Sk2s bZZ = times_2(dZZ) - (aZZ + cZZ) * Sk2s(0.5f);
1302     dst->fPts[0] = to_point(aXY / aZZ);
1303     dst->fPts[1] = to_point(bXY / bZZ);
1304     dst->fPts[2] = to_point(cXY / cZZ);
1305     Sk2s ww = bZZ / (aZZ * cZZ).sqrt();
1306     dst->fW = ww[0];
1307 }
1308 
evalAt(SkScalar t) const1309 SkPoint SkConic::evalAt(SkScalar t) const {
1310     return to_point(SkConicCoeff(*this).eval(t));
1311 }
1312 
evalTangentAt(SkScalar t) const1313 SkVector SkConic::evalTangentAt(SkScalar t) const {
1314     // The derivative equation returns a zero tangent vector when t is 0 or 1,
1315     // and the control point is equal to the end point.
1316     // In this case, use the conic endpoints to compute the tangent.
1317     if ((t == 0 && fPts[0] == fPts[1]) || (t == 1 && fPts[1] == fPts[2])) {
1318         return fPts[2] - fPts[0];
1319     }
1320     Sk2s p0 = from_point(fPts[0]);
1321     Sk2s p1 = from_point(fPts[1]);
1322     Sk2s p2 = from_point(fPts[2]);
1323     Sk2s ww(fW);
1324 
1325     Sk2s p20 = p2 - p0;
1326     Sk2s p10 = p1 - p0;
1327 
1328     Sk2s C = ww * p10;
1329     Sk2s A = ww * p20 - p20;
1330     Sk2s B = p20 - C - C;
1331 
1332     return to_vector(SkQuadCoeff(A, B, C).eval(t));
1333 }
1334 
evalAt(SkScalar t,SkPoint * pt,SkVector * tangent) const1335 void SkConic::evalAt(SkScalar t, SkPoint* pt, SkVector* tangent) const {
1336     SkASSERT(t >= 0 && t <= SK_Scalar1);
1337 
1338     if (pt) {
1339         *pt = this->evalAt(t);
1340     }
1341     if (tangent) {
1342         *tangent = this->evalTangentAt(t);
1343     }
1344 }
1345 
subdivide_w_value(SkScalar w)1346 static SkScalar subdivide_w_value(SkScalar w) {
1347     return SkScalarSqrt(SK_ScalarHalf + w * SK_ScalarHalf);
1348 }
1349 
chop(SkConic * SK_RESTRICT dst) const1350 void SkConic::chop(SkConic * SK_RESTRICT dst) const {
1351     Sk2s scale = Sk2s(SkScalarInvert(SK_Scalar1 + fW));
1352     SkScalar newW = subdivide_w_value(fW);
1353 
1354     Sk2s p0 = from_point(fPts[0]);
1355     Sk2s p1 = from_point(fPts[1]);
1356     Sk2s p2 = from_point(fPts[2]);
1357     Sk2s ww(fW);
1358 
1359     Sk2s wp1 = ww * p1;
1360     Sk2s m = (p0 + times_2(wp1) + p2) * scale * Sk2s(0.5f);
1361     SkPoint mPt = to_point(m);
1362     if (!mPt.isFinite()) {
1363         double w_d = fW;
1364         double w_2 = w_d * 2;
1365         double scale_half = 1 / (1 + w_d) * 0.5;
1366         mPt.fX = SkDoubleToScalar((fPts[0].fX + w_2 * fPts[1].fX + fPts[2].fX) * scale_half);
1367         mPt.fY = SkDoubleToScalar((fPts[0].fY + w_2 * fPts[1].fY + fPts[2].fY) * scale_half);
1368     }
1369     dst[0].fPts[0] = fPts[0];
1370     dst[0].fPts[1] = to_point((p0 + wp1) * scale);
1371     dst[0].fPts[2] = dst[1].fPts[0] = mPt;
1372     dst[1].fPts[1] = to_point((wp1 + p2) * scale);
1373     dst[1].fPts[2] = fPts[2];
1374 
1375     dst[0].fW = dst[1].fW = newW;
1376 }
1377 
1378 /*
1379  *  "High order approximation of conic sections by quadratic splines"
1380  *      by Michael Floater, 1993
1381  */
1382 #define AS_QUAD_ERROR_SETUP                                         \
1383     SkScalar a = fW - 1;                                            \
1384     SkScalar k = a / (4 * (2 + a));                                 \
1385     SkScalar x = k * (fPts[0].fX - 2 * fPts[1].fX + fPts[2].fX);    \
1386     SkScalar y = k * (fPts[0].fY - 2 * fPts[1].fY + fPts[2].fY);
1387 
computeAsQuadError(SkVector * err) const1388 void SkConic::computeAsQuadError(SkVector* err) const {
1389     AS_QUAD_ERROR_SETUP
1390     err->set(x, y);
1391 }
1392 
asQuadTol(SkScalar tol) const1393 bool SkConic::asQuadTol(SkScalar tol) const {
1394     AS_QUAD_ERROR_SETUP
1395     return (x * x + y * y) <= tol * tol;
1396 }
1397 
1398 // Limit the number of suggested quads to approximate a conic
1399 #define kMaxConicToQuadPOW2     5
1400 
computeQuadPOW2(SkScalar tol) const1401 int SkConic::computeQuadPOW2(SkScalar tol) const {
1402     if (tol < 0 || !SkScalarIsFinite(tol) || !SkPointPriv::AreFinite(fPts, 3)) {
1403         return 0;
1404     }
1405 
1406     AS_QUAD_ERROR_SETUP
1407 
1408     SkScalar error = SkScalarSqrt(x * x + y * y);
1409     int pow2;
1410     for (pow2 = 0; pow2 < kMaxConicToQuadPOW2; ++pow2) {
1411         if (error <= tol) {
1412             break;
1413         }
1414         error *= 0.25f;
1415     }
1416     // float version -- using ceil gives the same results as the above.
1417     if (false) {
1418         SkScalar err = SkScalarSqrt(x * x + y * y);
1419         if (err <= tol) {
1420             return 0;
1421         }
1422         SkScalar tol2 = tol * tol;
1423         if (tol2 == 0) {
1424             return kMaxConicToQuadPOW2;
1425         }
1426         SkScalar fpow2 = SkScalarLog2((x * x + y * y) / tol2) * 0.25f;
1427         int altPow2 = SkScalarCeilToInt(fpow2);
1428         if (altPow2 != pow2) {
1429             SkDebugf("pow2 %d altPow2 %d fbits %g err %g tol %g\n", pow2, altPow2, fpow2, err, tol);
1430         }
1431         pow2 = altPow2;
1432     }
1433     return pow2;
1434 }
1435 
1436 // This was originally developed and tested for pathops: see SkOpTypes.h
1437 // returns true if (a <= b <= c) || (a >= b >= c)
between(SkScalar a,SkScalar b,SkScalar c)1438 static bool between(SkScalar a, SkScalar b, SkScalar c) {
1439     return (a - b) * (c - b) <= 0;
1440 }
1441 
subdivide(const SkConic & src,SkPoint pts[],int level)1442 static SkPoint* subdivide(const SkConic& src, SkPoint pts[], int level) {
1443     SkASSERT(level >= 0);
1444 
1445     if (0 == level) {
1446         memcpy(pts, &src.fPts[1], 2 * sizeof(SkPoint));
1447         return pts + 2;
1448     } else {
1449         SkConic dst[2];
1450         src.chop(dst);
1451         const SkScalar startY = src.fPts[0].fY;
1452         SkScalar endY = src.fPts[2].fY;
1453         if (between(startY, src.fPts[1].fY, endY)) {
1454             // If the input is monotonic and the output is not, the scan converter hangs.
1455             // Ensure that the chopped conics maintain their y-order.
1456             SkScalar midY = dst[0].fPts[2].fY;
1457             if (!between(startY, midY, endY)) {
1458                 // If the computed midpoint is outside the ends, move it to the closer one.
1459                 SkScalar closerY = SkTAbs(midY - startY) < SkTAbs(midY - endY) ? startY : endY;
1460                 dst[0].fPts[2].fY = dst[1].fPts[0].fY = closerY;
1461             }
1462             if (!between(startY, dst[0].fPts[1].fY, dst[0].fPts[2].fY)) {
1463                 // If the 1st control is not between the start and end, put it at the start.
1464                 // This also reduces the quad to a line.
1465                 dst[0].fPts[1].fY = startY;
1466             }
1467             if (!between(dst[1].fPts[0].fY, dst[1].fPts[1].fY, endY)) {
1468                 // If the 2nd control is not between the start and end, put it at the end.
1469                 // This also reduces the quad to a line.
1470                 dst[1].fPts[1].fY = endY;
1471             }
1472             // Verify that all five points are in order.
1473             SkASSERT(between(startY, dst[0].fPts[1].fY, dst[0].fPts[2].fY));
1474             SkASSERT(between(dst[0].fPts[1].fY, dst[0].fPts[2].fY, dst[1].fPts[1].fY));
1475             SkASSERT(between(dst[0].fPts[2].fY, dst[1].fPts[1].fY, endY));
1476         }
1477         --level;
1478         pts = subdivide(dst[0], pts, level);
1479         return subdivide(dst[1], pts, level);
1480     }
1481 }
1482 
chopIntoQuadsPOW2(SkPoint pts[],int pow2) const1483 int SkConic::chopIntoQuadsPOW2(SkPoint pts[], int pow2) const {
1484     SkASSERT(pow2 >= 0);
1485     *pts = fPts[0];
1486     SkDEBUGCODE(SkPoint* endPts);
1487     if (pow2 == kMaxConicToQuadPOW2) {  // If an extreme weight generates many quads ...
1488         SkConic dst[2];
1489         this->chop(dst);
1490         // check to see if the first chop generates a pair of lines
1491         if (SkPointPriv::EqualsWithinTolerance(dst[0].fPts[1], dst[0].fPts[2]) &&
1492                 SkPointPriv::EqualsWithinTolerance(dst[1].fPts[0], dst[1].fPts[1])) {
1493             pts[1] = pts[2] = pts[3] = dst[0].fPts[1];  // set ctrl == end to make lines
1494             pts[4] = dst[1].fPts[2];
1495             pow2 = 1;
1496             SkDEBUGCODE(endPts = &pts[5]);
1497             goto commonFinitePtCheck;
1498         }
1499     }
1500     SkDEBUGCODE(endPts = ) subdivide(*this, pts + 1, pow2);
1501 commonFinitePtCheck:
1502     const int quadCount = 1 << pow2;
1503     const int ptCount = 2 * quadCount + 1;
1504     SkASSERT(endPts - pts == ptCount);
1505     if (!SkPointPriv::AreFinite(pts, ptCount)) {
1506         // if we generated a non-finite, pin ourselves to the middle of the hull,
1507         // as our first and last are already on the first/last pts of the hull.
1508         for (int i = 1; i < ptCount - 1; ++i) {
1509             pts[i] = fPts[1];
1510         }
1511     }
1512     return 1 << pow2;
1513 }
1514 
findMidTangent() const1515 float SkConic::findMidTangent() const {
1516     // Tangents point in the direction of increasing T, so tan0 and -tan1 both point toward the
1517     // midtangent. The bisector of tan0 and -tan1 is orthogonal to the midtangent:
1518     //
1519     //     bisector dot midtangent = 0
1520     //
1521     SkVector tan0 = fPts[1] - fPts[0];
1522     SkVector tan1 = fPts[2] - fPts[1];
1523     SkVector bisector = SkFindBisector(tan0, -tan1);
1524 
1525     // Start by finding the tangent function's power basis coefficients. These define a tangent
1526     // direction (scaled by some uniform value) as:
1527     //                                                |T^2|
1528     //     Tangent_Direction(T) = dx,dy = |A  B  C| * |T  |
1529     //                                    |.  .  .|   |1  |
1530     //
1531     // The derivative of a conic has a cumbersome order-4 denominator. However, this isn't necessary
1532     // if we are only interested in a vector in the same *direction* as a given tangent line. Since
1533     // the denominator scales dx and dy uniformly, we can throw it out completely after evaluating
1534     // the derivative with the standard quotient rule. This leaves us with a simpler quadratic
1535     // function that we use to find a tangent.
1536     SkVector A = (fPts[2] - fPts[0]) * (fW - 1);
1537     SkVector B = (fPts[2] - fPts[0]) - (fPts[1] - fPts[0]) * (fW*2);
1538     SkVector C = (fPts[1] - fPts[0]) * fW;
1539 
1540     // Now solve for "bisector dot midtangent = 0":
1541     //
1542     //                            |T^2|
1543     //     bisector * |A  B  C| * |T  | = 0
1544     //                |.  .  .|   |1  |
1545     //
1546     float a = bisector.dot(A);
1547     float b = bisector.dot(B);
1548     float c = bisector.dot(C);
1549     return solve_quadratic_equation_for_midtangent(a, b, c);
1550 }
1551 
findXExtrema(SkScalar * t) const1552 bool SkConic::findXExtrema(SkScalar* t) const {
1553     return conic_find_extrema(&fPts[0].fX, fW, t);
1554 }
1555 
findYExtrema(SkScalar * t) const1556 bool SkConic::findYExtrema(SkScalar* t) const {
1557     return conic_find_extrema(&fPts[0].fY, fW, t);
1558 }
1559 
chopAtXExtrema(SkConic dst[2]) const1560 bool SkConic::chopAtXExtrema(SkConic dst[2]) const {
1561     SkScalar t;
1562     if (this->findXExtrema(&t)) {
1563         if (!this->chopAt(t, dst)) {
1564             // if chop can't return finite values, don't chop
1565             return false;
1566         }
1567         // now clean-up the middle, since we know t was meant to be at
1568         // an X-extrema
1569         SkScalar value = dst[0].fPts[2].fX;
1570         dst[0].fPts[1].fX = value;
1571         dst[1].fPts[0].fX = value;
1572         dst[1].fPts[1].fX = value;
1573         return true;
1574     }
1575     return false;
1576 }
1577 
chopAtYExtrema(SkConic dst[2]) const1578 bool SkConic::chopAtYExtrema(SkConic dst[2]) const {
1579     SkScalar t;
1580     if (this->findYExtrema(&t)) {
1581         if (!this->chopAt(t, dst)) {
1582             // if chop can't return finite values, don't chop
1583             return false;
1584         }
1585         // now clean-up the middle, since we know t was meant to be at
1586         // an Y-extrema
1587         SkScalar value = dst[0].fPts[2].fY;
1588         dst[0].fPts[1].fY = value;
1589         dst[1].fPts[0].fY = value;
1590         dst[1].fPts[1].fY = value;
1591         return true;
1592     }
1593     return false;
1594 }
1595 
computeTightBounds(SkRect * bounds) const1596 void SkConic::computeTightBounds(SkRect* bounds) const {
1597     SkPoint pts[4];
1598     pts[0] = fPts[0];
1599     pts[1] = fPts[2];
1600     int count = 2;
1601 
1602     SkScalar t;
1603     if (this->findXExtrema(&t)) {
1604         this->evalAt(t, &pts[count++]);
1605     }
1606     if (this->findYExtrema(&t)) {
1607         this->evalAt(t, &pts[count++]);
1608     }
1609     bounds->setBounds(pts, count);
1610 }
1611 
computeFastBounds(SkRect * bounds) const1612 void SkConic::computeFastBounds(SkRect* bounds) const {
1613     bounds->setBounds(fPts, 3);
1614 }
1615 
1616 #if 0  // unimplemented
1617 bool SkConic::findMaxCurvature(SkScalar* t) const {
1618     // TODO: Implement me
1619     return false;
1620 }
1621 #endif
1622 
TransformW(const SkPoint pts[],SkScalar w,const SkMatrix & matrix)1623 SkScalar SkConic::TransformW(const SkPoint pts[], SkScalar w, const SkMatrix& matrix) {
1624     if (!matrix.hasPerspective()) {
1625         return w;
1626     }
1627 
1628     SkPoint3 src[3], dst[3];
1629 
1630     ratquad_mapTo3D(pts, w, src);
1631 
1632     matrix.mapHomogeneousPoints(dst, src, 3);
1633 
1634     // w' = sqrt(w1*w1/w0*w2)
1635     // use doubles temporarily, to handle small numer/denom
1636     double w0 = dst[0].fZ;
1637     double w1 = dst[1].fZ;
1638     double w2 = dst[2].fZ;
1639     return sk_double_to_float(sqrt(sk_ieee_double_divide(w1 * w1, w0 * w2)));
1640 }
1641 
BuildUnitArc(const SkVector & uStart,const SkVector & uStop,SkRotationDirection dir,const SkMatrix * userMatrix,SkConic dst[kMaxConicsForArc])1642 int SkConic::BuildUnitArc(const SkVector& uStart, const SkVector& uStop, SkRotationDirection dir,
1643                           const SkMatrix* userMatrix, SkConic dst[kMaxConicsForArc]) {
1644     // rotate by x,y so that uStart is (1.0)
1645     SkScalar x = SkPoint::DotProduct(uStart, uStop);
1646     SkScalar y = SkPoint::CrossProduct(uStart, uStop);
1647 
1648     SkScalar absY = SkScalarAbs(y);
1649 
1650     // check for (effectively) coincident vectors
1651     // this can happen if our angle is nearly 0 or nearly 180 (y == 0)
1652     // ... we use the dot-prod to distinguish between 0 and 180 (x > 0)
1653     if (absY <= SK_ScalarNearlyZero && x > 0 && ((y >= 0 && kCW_SkRotationDirection == dir) ||
1654                                                  (y <= 0 && kCCW_SkRotationDirection == dir))) {
1655         return 0;
1656     }
1657 
1658     if (dir == kCCW_SkRotationDirection) {
1659         y = -y;
1660     }
1661 
1662     // We decide to use 1-conic per quadrant of a circle. What quadrant does [xy] lie in?
1663     //      0 == [0  .. 90)
1664     //      1 == [90 ..180)
1665     //      2 == [180..270)
1666     //      3 == [270..360)
1667     //
1668     int quadrant = 0;
1669     if (0 == y) {
1670         quadrant = 2;        // 180
1671         SkASSERT(SkScalarAbs(x + SK_Scalar1) <= SK_ScalarNearlyZero);
1672     } else if (0 == x) {
1673         SkASSERT(absY - SK_Scalar1 <= SK_ScalarNearlyZero);
1674         quadrant = y > 0 ? 1 : 3; // 90 : 270
1675     } else {
1676         if (y < 0) {
1677             quadrant += 2;
1678         }
1679         if ((x < 0) != (y < 0)) {
1680             quadrant += 1;
1681         }
1682     }
1683 
1684     const SkPoint quadrantPts[] = {
1685         { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 }, { -1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 }
1686     };
1687     const SkScalar quadrantWeight = SK_ScalarRoot2Over2;
1688 
1689     int conicCount = quadrant;
1690     for (int i = 0; i < conicCount; ++i) {
1691         dst[i].set(&quadrantPts[i * 2], quadrantWeight);
1692     }
1693 
1694     // Now compute any remaing (sub-90-degree) arc for the last conic
1695     const SkPoint finalP = { x, y };
1696     const SkPoint& lastQ = quadrantPts[quadrant * 2];  // will already be a unit-vector
1697     const SkScalar dot = SkVector::DotProduct(lastQ, finalP);
1698     SkASSERT(0 <= dot && dot <= SK_Scalar1 + SK_ScalarNearlyZero);
1699 
1700     if (dot < 1) {
1701         SkVector offCurve = { lastQ.x() + x, lastQ.y() + y };
1702         // compute the bisector vector, and then rescale to be the off-curve point.
1703         // we compute its length from cos(theta/2) = length / 1, using half-angle identity we get
1704         // length = sqrt(2 / (1 + cos(theta)). We already have cos() when to computed the dot.
1705         // This is nice, since our computed weight is cos(theta/2) as well!
1706         //
1707         const SkScalar cosThetaOver2 = SkScalarSqrt((1 + dot) / 2);
1708         offCurve.setLength(SkScalarInvert(cosThetaOver2));
1709         if (!SkPointPriv::EqualsWithinTolerance(lastQ, offCurve)) {
1710             dst[conicCount].set(lastQ, offCurve, finalP, cosThetaOver2);
1711             conicCount += 1;
1712         }
1713     }
1714 
1715     // now handle counter-clockwise and the initial unitStart rotation
1716     SkMatrix    matrix;
1717     matrix.setSinCos(uStart.fY, uStart.fX);
1718     if (dir == kCCW_SkRotationDirection) {
1719         matrix.preScale(SK_Scalar1, -SK_Scalar1);
1720     }
1721     if (userMatrix) {
1722         matrix.postConcat(*userMatrix);
1723     }
1724     for (int i = 0; i < conicCount; ++i) {
1725         matrix.mapPoints(dst[i].fPts, 3);
1726     }
1727     return conicCount;
1728 }
1729