Update rive-cpp to 2.0 version
[platform/core/uifw/rive-tizen.git] / submodule / skia / src / core / SkGeometry.cpp
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/SkTPin.h"
11 #include "include/private/SkVx.h"
12 #include "src/core/SkGeometry.h"
13 #include "src/core/SkPointPriv.h"
14
15 #include <algorithm>
16 #include <tuple>
17 #include <utility>
18
19 namespace {
20
21 using float2 = skvx::float2;
22 using float4 = skvx::float4;
23
24 SkVector to_vector(const float2& x) {
25     SkVector vector;
26     x.store(&vector);
27     return vector;
28 }
29
30 ////////////////////////////////////////////////////////////////////////
31
32 int is_not_monotonic(SkScalar a, SkScalar b, SkScalar c) {
33     SkScalar ab = a - b;
34     SkScalar bc = b - c;
35     if (ab < 0) {
36         bc = -bc;
37     }
38     return ab == 0 || bc < 0;
39 }
40
41 ////////////////////////////////////////////////////////////////////////
42
43 int valid_unit_divide(SkScalar numer, SkScalar denom, SkScalar* ratio) {
44     SkASSERT(ratio);
45
46     if (numer < 0) {
47         numer = -numer;
48         denom = -denom;
49     }
50
51     if (denom == 0 || numer == 0 || numer >= denom) {
52         return 0;
53     }
54
55     SkScalar r = numer / denom;
56     if (SkScalarIsNaN(r)) {
57         return 0;
58     }
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
61         return 0;
62     }
63     *ratio = r;
64     return 1;
65 }
66
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) {
70     if (value == 0) {
71         return 0;
72     }
73     return value;
74 }
75
76 } // namespace
77
78 /** From Numerical Recipes in C.
79
80     Q = -1/2 (B + sign(B) sqrt[B*B - 4*A*C])
81     x1 = Q / A
82     x2 = C / Q
83 */
84 int SkFindUnitQuadRoots(SkScalar A, SkScalar B, SkScalar C, SkScalar roots[2]) {
85     SkASSERT(roots);
86
87     if (A == 0) {
88         return return_check_zero(valid_unit_divide(-C, B, roots));
89     }
90
91     SkScalar* r = roots;
92
93     // use doubles so we don't overflow temporarily trying to compute R
94     double dr = (double)B * B - 4 * (double)A * C;
95     if (dr < 0) {
96         return return_check_zero(0);
97     }
98     dr = sqrt(dr);
99     SkScalar R = SkDoubleToScalar(dr);
100     if (!SkScalarIsFinite(R)) {
101         return return_check_zero(0);
102     }
103
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]) {
109             using std::swap;
110             swap(roots[0], roots[1]);
111         } else if (roots[0] == roots[1]) { // nearly-equal?
112             r -= 1; // skip the double root
113         }
114     }
115     return return_check_zero((int)(r - roots));
116 }
117
118 ///////////////////////////////////////////////////////////////////////////////
119 ///////////////////////////////////////////////////////////////////////////////
120
121 void SkEvalQuadAt(const SkPoint src[3], SkScalar t, SkPoint* pt, SkVector* tangent) {
122     SkASSERT(src);
123     SkASSERT(t >= 0 && t <= SK_Scalar1);
124
125     if (pt) {
126         *pt = SkEvalQuadAt(src, t);
127     }
128     if (tangent) {
129         *tangent = SkEvalQuadTangentAt(src, t);
130     }
131 }
132
133 SkPoint SkEvalQuadAt(const SkPoint src[3], SkScalar t) {
134     return to_point(SkQuadCoeff(src).eval(t));
135 }
136
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];
143     }
144     SkASSERT(src);
145     SkASSERT(t >= 0 && t <= SK_Scalar1);
146
147     float2 P0 = from_point(src[0]);
148     float2 P1 = from_point(src[1]);
149     float2 P2 = from_point(src[2]);
150
151     float2 B = P1 - P0;
152     float2 A = P2 - P1 - B;
153     float2 T = A * t + B;
154
155     return to_vector(T + T);
156 }
157
158 static inline float2 interp(const float2& v0,
159                             const float2& v1,
160                             const float2& t) {
161     return v0 + (v1 - v0) * t;
162 }
163
164 void SkChopQuadAt(const SkPoint src[3], SkPoint dst[5], SkScalar t) {
165     SkASSERT(t > 0 && t < SK_Scalar1);
166
167     float2 p0 = from_point(src[0]);
168     float2 p1 = from_point(src[1]);
169     float2 p2 = from_point(src[2]);
170     float2 tt(t);
171
172     float2 p01 = interp(p0, p1, tt);
173     float2 p12 = interp(p1, p2, tt);
174
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);
180 }
181
182 void SkChopQuadAtHalf(const SkPoint src[3], SkPoint dst[5]) {
183     SkChopQuadAt(src, dst, 0.5f);
184 }
185
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);
191 }
192
193 SkVector SkFindBisector(SkVector a, SkVector b) {
194     std::array<SkVector, 2> v;
195     if (a.dot(b) >= 0) {
196         // a,b are within +/-90 degrees apart.
197         v = {a, b};
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
201         // unstable.)
202         v[0].set(-a.fY, +a.fX);
203         v[1].set(+b.fY, -b.fX);
204     } else {
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);
210     }
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);
215     x0_x1 *= invLengths;
216     y0_y1 *= invLengths;
217     return SkPoint{x0_x1[0] + x0_x1[1], y0_y1[0] + y0_y1[1]};
218 }
219
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:
223     //
224     //     n dot midtangent = 0
225     //
226     SkVector tan0 = src[1] - src[0];
227     SkVector tan1 = src[2] - src[1];
228     SkVector bisector = SkFindBisector(tan0, -tan1);
229
230     // The midtangent can be found where (F' dot bisector) = 0:
231     //
232     //   0 = (F'(T) dot bisector) = |2*T 1| * |p0 - 2*p1 + p2| * |bisector.x|
233     //                                        |-2*p0 + 2*p1  |   |bisector.y|
234     //
235     //                     = |2*T 1| * |tan1 - tan0| * |nx|
236     //                                 |2*tan0     |   |ny|
237     //
238     //                     = 2*T * ((tan1 - tan0) dot bisector) + (2*tan0 dot bisector)
239     //
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.
244     }
245
246     return T;
247 }
248
249 /** Quad'(t) = At + B, where
250     A = 2(a - 2b + c)
251     B = 2(b - a)
252     Solve for t, only if it fits between 0 < t < 1
253 */
254 int SkFindQuadExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar tValue[1]) {
255     /*  At + B == 0
256         t = -B / A
257     */
258     return valid_unit_divide(a - b, a - b - b + c, tValue);
259 }
260
261 static inline void flatten_double_quad_extrema(SkScalar coords[14]) {
262     coords[2] = coords[6] = coords[4];
263 }
264
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.
267  */
268 int SkChopQuadAtYExtrema(const SkPoint src[3], SkPoint dst[5]) {
269     SkASSERT(src);
270     SkASSERT(dst);
271
272     SkScalar a = src[0].fY;
273     SkScalar b = src[1].fY;
274     SkScalar c = src[2].fY;
275
276     if (is_not_monotonic(a, b, c)) {
277         SkScalar    tValue;
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);
281             return 1;
282         }
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;
286     }
287     dst[0].set(src[0].fX, a);
288     dst[1].set(src[1].fX, b);
289     dst[2].set(src[2].fX, c);
290     return 0;
291 }
292
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.
295  */
296 int SkChopQuadAtXExtrema(const SkPoint src[3], SkPoint dst[5]) {
297     SkASSERT(src);
298     SkASSERT(dst);
299
300     SkScalar a = src[0].fX;
301     SkScalar b = src[1].fX;
302     SkScalar c = src[2].fX;
303
304     if (is_not_monotonic(a, b, c)) {
305         SkScalar tValue;
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);
309             return 1;
310         }
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;
314     }
315     dst[0].set(a, src[0].fY);
316     dst[1].set(b, src[1].fY);
317     dst[2].set(c, src[2].fY);
318     return 0;
319 }
320
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)
324 //
325 //  A = 2 (b - a)
326 //  B = 2 (a - 2b + c)
327 //
328 //  Maximum curvature for a quadratic means solving
329 //  Fx' Fx'' + Fy' Fy'' = 0
330 //
331 //  t = - (Ax Bx + Ay By) / (Bx ^ 2 + By ^ 2)
332 //
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;
338
339     SkScalar numer = -(Ax * Bx + Ay * By);
340     SkScalar denom = Bx * Bx + By * By;
341     if (denom < 0) {
342         numer = -numer;
343         denom = -denom;
344     }
345     if (numer <= 0) {
346         return 0;
347     }
348     if (numer >= denom) {  // Also catches denom=0.
349         return 1;
350     }
351     SkScalar t = numer / denom;
352     SkASSERT((0 <= t && t < 1) || SkScalarIsNaN(t));
353     return t;
354 }
355
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);
360         return 2;
361     } else {
362         memcpy(dst, src, 3 * sizeof(SkPoint));
363         return 1;
364     }
365 }
366
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]);
372
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);
377 }
378
379 //////////////////////////////////////////////////////////////////////////////
380 ///// CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS /////
381 //////////////////////////////////////////////////////////////////////////////
382
383 static SkVector eval_cubic_derivative(const SkPoint src[4], SkScalar t) {
384     SkQuadCoeff coeff;
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]);
389
390     coeff.fA = P3 + 3 * (P1 - P2) - P0;
391     coeff.fB = times_2(P2 - times_2(P1) + P0);
392     coeff.fC = P1 - P0;
393     return to_vector(coeff.eval(t));
394 }
395
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;
403
404     return to_vector(A * t + B);
405 }
406
407 void SkEvalCubicAt(const SkPoint src[4], SkScalar t, SkPoint* loc,
408                    SkVector* tangent, SkVector* curvature) {
409     SkASSERT(src);
410     SkASSERT(t >= 0 && t <= SK_Scalar1);
411
412     if (loc) {
413         *loc = to_point(SkCubicCoeff(src).eval(t));
414     }
415     if (tangent) {
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])) {
420             if (t == 0) {
421                 *tangent = src[2] - src[0];
422             } else {
423                 *tangent = src[3] - src[1];
424             }
425             if (!tangent->fX && !tangent->fY) {
426                 *tangent = src[3] - src[0];
427             }
428         } else {
429             *tangent = eval_cubic_derivative(src, t);
430         }
431     }
432     if (curvature) {
433         *curvature = eval_cubic_2ndDerivative(src, t);
434     }
435 }
436
437 /** Cubic'(t) = At^2 + Bt + C, where
438     A = 3(-a + 3(b - c) + d)
439     B = 6(a - 2b + c)
440     C = 3(b - a)
441     Solve for t, keeping only those that fit betwee 0 < t < 1
442 */
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);
448     SkScalar C = b - a;
449
450     return SkFindUnitQuadRoots(A, B, C, tValues);
451 }
452
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;
460 }
461
462 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[7], SkScalar t) {
463     SkASSERT(0 <= t && t <= 1);
464
465     if (t == 1) {
466         memcpy(dst, src, sizeof(SkPoint) * 4);
467         dst[4] = dst[5] = dst[6] = src[3];
468         return;
469     }
470
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]);
475     float2 T = t;
476
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);
483
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);
491 }
492
493 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[10], float t0, float t1) {
494     SkASSERT(0 <= t0 && t0 <= t1 && t1 <= 1);
495
496     if (t1 == 1) {
497         SkChopCubicAt(src, dst, t0);
498         dst[7] = dst[8] = dst[9] = src[3];
499         return;
500     }
501
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]);
508     T.lo = t0;
509     T.hi = t1;
510
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));
518
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);
528 }
529
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));
534
535     if (dst) {
536         if (tCount == 0) { // nothing to chop
537             memcpy(dst, src, 4*sizeof(SkPoint));
538         } else {
539             int i = 0;
540             for (; i < tCount - 1; i += 2) {
541                 // Do two chops at once.
542                 float2 tt = float2::Load(tValues + i);
543                 if (i != 0) {
544                     float lastT = tValues[i - 1];
545                     tt = skvx::pin((tt - lastT) / (1 - lastT), float2(0), float2(1));
546                 }
547                 SkChopCubicAt(src, dst, tt[0], tt[1]);
548                 src = dst = dst + 6;
549             }
550             if (i < tCount) {
551                 // Chop the final cubic if there was an odd number of chops.
552                 SkASSERT(i + 1 == tCount);
553                 float t = tValues[i];
554                 if (i != 0) {
555                     float lastT = tValues[i - 1];
556                     t = SkTPin(sk_ieee_float_divide(t - lastT, 1 - lastT), 0.f, 1.f);
557                 }
558                 SkChopCubicAt(src, dst, t);
559             }
560         }
561     }
562 }
563
564 void SkChopCubicAtHalf(const SkPoint src[4], SkPoint dst[7]) {
565     SkChopCubicAt(src, dst, 0.5f);
566 }
567
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];
572     if (a.isZero()) {
573         return SkMeasureAngleBetweenVectors(b, c);
574     }
575     if (b.isZero()) {
576         return SkMeasureAngleBetweenVectors(a, c);
577     }
578     if (c.isZero()) {
579         return SkMeasureAngleBetweenVectors(a, b);
580     }
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);
584 }
585
586 static skvx::float4 fma(const skvx::float4& f, float m, const skvx::float4& a) {
587     return skvx::fma(f, skvx::float4(m), a);
588 }
589
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.
600         T = .5;
601     }
602     return T;
603 }
604
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);
607 }
608
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:
612     //
613     //     bisector dot midtangent == 0
614     //
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);
618
619     // Find the T value at the midtangent. This is a simple quadratic equation:
620     //
621     //     midtangent dot bisector == 0, or using a tangent matrix C' in power basis form:
622     //
623     //                   |C'x  C'y|
624     //     |T^2  T  1| * |.    .  | * |bisector.x| == 0
625     //                   |.    .  |   |bisector.y|
626     //
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();
638
639     // Now solve the quadratic for T.
640     float T = 0;
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);
645     } else {
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:
650         //
651         //     tangent dot tan0 == 0
652         //
653         coeffs = C_x * tan0.x() + C_y * tan0.y();
654         a = coeffs[0];
655         b = coeffs[1];
656         if (a != 0) {
657             // We want the point in between both cusps. The midpoint of:
658             //
659             //     (-b +/- sqrt(b^2 - 4*a*c)) / (2*a)
660             //
661             // Is equal to:
662             //
663             //     -b / (2*a)
664             T = -b / (2*a);
665         }
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
668             // .5.
669             T = .5;
670         }
671         return T;
672     }
673 }
674
675 static void flatten_double_cubic_extrema(SkScalar coords[14]) {
676     coords[4] = coords[8] = coords[6];
677 }
678
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.
686 */
687 int SkChopCubicAtYExtrema(const SkPoint src[4], SkPoint dst[10]) {
688     SkScalar    tValues[2];
689     int         roots = SkFindCubicExtrema(src[0].fY, src[1].fY, src[2].fY,
690                                            src[3].fY, tValues);
691
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);
696         if (roots == 2) {
697             flatten_double_cubic_extrema(&dst[3].fY);
698         }
699     }
700     return roots;
701 }
702
703 int SkChopCubicAtXExtrema(const SkPoint src[4], SkPoint dst[10]) {
704     SkScalar    tValues[2];
705     int         roots = SkFindCubicExtrema(src[0].fX, src[1].fX, src[2].fX,
706                                            src[3].fX, tValues);
707
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);
712         if (roots == 2) {
713             flatten_double_cubic_extrema(&dst[3].fX);
714         }
715     }
716     return roots;
717 }
718
719 /** http://www.faculty.idc.ac.il/arik/quality/appendixA.html
720
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
725     A = b - a
726     B = c - 2b + a
727     C = d - 3c + 3b - a
728     (BxCy - ByCx)t^2 + (AxCy - AyCx)t + AxBy - AyBx == 0
729 */
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;
737
738     return SkFindUnitQuadRoots(Bx*Cy - By*Cx,
739                                Ax*Cy - Ay*Cx,
740                                Ax*By - Ay*Bx,
741                                tValues);
742 }
743
744 int SkChopCubicAtInflections(const SkPoint src[], SkPoint dst[10]) {
745     SkScalar    tValues[2];
746     int         count = SkFindCubicInflections(src, tValues);
747
748     if (dst) {
749         if (count == 0) {
750             memcpy(dst, src, 4 * sizeof(SkPoint));
751         } else {
752             SkChopCubicAt(src, dst, tValues, count);
753         }
754     }
755     return count + 1;
756 }
757
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);
765 }
766
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) {
772     uint64_t bits;
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));
777     return n;
778 }
779
780 inline static void write_cubic_inflection_roots(double t0, double s0, double t1, double s1,
781                                                 double* t, double* s) {
782     t[0] = t0;
783     s[0] = s0;
784
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);
788     s[1] = -fabs(s1);
789
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]) {
792         using std::swap;
793         swap(t[0], t[1]);
794         swap(s[0], s[1]);
795     }
796 }
797
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.)
801     //
802     // See "Resolution Independent Curve Rendering using Programmable Graphics Hardware",
803     // 4.2 Curve Categorization:
804     //
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]);
809
810     double D3 = 3 * A3;
811     double D2 = D3 - A2;
812     double D1 = D2 - A2 + A1;
813
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);
818     D1 *= norm;
819     D2 *= norm;
820     D3 *= norm;
821
822     if (d) {
823         d[3] = D3;
824         d[2] = D2;
825         d[1] = D1;
826         d[0] = 0;
827     }
828
829     // Now use the inflection function to classify the cubic.
830     //
831     // See "Resolution Independent Curve Rendering using Programmable Graphics Hardware",
832     // 4.4 Integral Cubics:
833     //
834     // https://www.microsoft.com/en-us/research/wp-content/uploads/2005/01/p1000-loop.pdf
835     if (0 != D1) {
836         double discr = 3*D2*D2 - 4*D1*D3;
837         if (discr > 0) { // Serpentine.
838             if (t && s) {
839                 double q = 3*D2 + copysign(sqrt(3*discr), D2);
840                 write_cubic_inflection_roots(q, 6*D1, 2*D3, q, t, s);
841             }
842             return SkCubicType::kSerpentine;
843         } else if (discr < 0) { // Loop.
844             if (t && s) {
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);
847             }
848             return SkCubicType::kLoop;
849         } else { // Cusp.
850             if (t && s) {
851                 write_cubic_inflection_roots(D2, 2*D1, D2, 2*D1, t, s);
852             }
853             return SkCubicType::kLocalCusp;
854         }
855     } else {
856         if (0 != D2) { // Cusp at T=infinity.
857             if (t && s) {
858                 write_cubic_inflection_roots(D3, 3*D2, 1, 0, t, s); // T1=infinity.
859             }
860             return SkCubicType::kCuspAtInfinity;
861         } else { // Degenerate.
862             if (t && s) {
863                 write_cubic_inflection_roots(1, 0, 1, 0, t, s); // T0=T1=infinity.
864             }
865             return 0 != D3 ? SkCubicType::kQuadratic : SkCubicType::kLineOrPoint;
866         }
867     }
868 }
869
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])
874             {
875                 T   tmp(array[j]);
876                 array[j] = array[j-1];
877                 array[j-1] = tmp;
878             }
879 }
880
881 /**
882  *  Given an array and count, remove all pair-wise duplicates from the array,
883  *  keeping the existing sorting, and return the new count
884  */
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];
890             }
891             count -= 1;
892         } else {
893             array += 1;
894         }
895     }
896     return count;
897 }
898
899 #ifdef SK_DEBUG
900
901 #define TEST_COLLAPS_ENTRY(array)   array, SK_ARRAY_COUNT(array)
902
903 static void test_collaps_duplicates() {
904     static bool gOnce;
905     if (gOnce) { return; }
906     gOnce = true;
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 };
914     const struct {
915         const SkScalar* fData;
916         int fCount;
917         int fCollapsedCount;
918     } data[] = {
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 },
926     };
927     for (size_t i = 0; i < SK_ARRAY_COUNT(data); ++i) {
928         SkScalar dst[3];
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]);
934         }
935     }
936 }
937 #endif
938
939 static SkScalar SkScalarCubeRoot(SkScalar x) {
940     return SkScalarPow(x, 0.3333333f);
941 }
942
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]
946
947     Eliminates repeated roots (so that all tValues are distinct, and are always
948     in increasing order.
949 */
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);
953     }
954
955     SkScalar a, b, c, Q, R;
956
957     {
958         SkASSERT(coeff[0] != 0);
959
960         SkScalar inva = SkScalarInvert(coeff[0]);
961         a = coeff[1] * inva;
962         b = coeff[2] * inva;
963         c = coeff[3] * inva;
964     }
965     Q = (a*a - b*3) / 9;
966     R = (2*a*a*a - 9*a*b + 27*c) / 54;
967
968     SkScalar Q3 = Q * Q * Q;
969     SkScalar R2MinusQ3 = R * R - Q3;
970     SkScalar adiv3 = a / 3;
971
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);
976
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();)
981
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);
988         if (R > 0) {
989             A = -A;
990         }
991         if (A != 0) {
992             A += Q / A;
993         }
994         tValues[0] = SkTPin(A - adiv3, 0.0f, 1.0f);
995         return 1;
996     }
997 }
998
999 /*  Looking for F' dot F'' == 0
1000
1001     A = b - a
1002     B = c - 2b + a
1003     C = d - 3c + 3b - a
1004
1005     F' = 3Ct^2 + 6Bt + 3A
1006     F'' = 6Ct + 6B
1007
1008     F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
1009 */
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];
1014
1015     coeff[0] = c * c;
1016     coeff[1] = 3 * b * c;
1017     coeff[2] = 2 * b * b + c * a;
1018     coeff[3] = a * b;
1019 }
1020
1021 /*  Looking for F' dot F'' == 0
1022
1023     A = b - a
1024     B = c - 2b + a
1025     C = d - 3c + 3b - a
1026
1027     F' = 3Ct^2 + 6Bt + 3A
1028     F'' = 6Ct + 6B
1029
1030     F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
1031 */
1032 int SkFindCubicMaxCurvature(const SkPoint src[4], SkScalar tValues[3]) {
1033     SkScalar coeffX[4], coeffY[4];
1034     int      i;
1035
1036     formulate_F1DotF2(&src[0].fX, coeffX);
1037     formulate_F1DotF2(&src[0].fY, coeffY);
1038
1039     for (i = 0; i < 4; i++) {
1040         coeffX[i] += coeffY[i];
1041     }
1042
1043     int numRoots = solve_cubic_poly(coeffX, tValues);
1044     // now remove extrema where the curvature is zero (mins)
1045     // !!!! need a test for this !!!!
1046     return numRoots;
1047 }
1048
1049 int SkChopCubicAtMaxCurvature(const SkPoint src[4], SkPoint dst[13],
1050                               SkScalar tValues[3]) {
1051     SkScalar    t_storage[3];
1052
1053     if (tValues == nullptr) {
1054         tValues = t_storage;
1055     }
1056
1057     SkScalar roots[3];
1058     int rootCount = SkFindCubicMaxCurvature(src, roots);
1059
1060     // Throw out values not inside 0..1.
1061     int count = 0;
1062     for (int i = 0; i < rootCount; ++i) {
1063         if (0 < roots[i] && roots[i] < 1) {
1064             tValues[count++] = roots[i];
1065         }
1066     }
1067
1068     if (dst) {
1069         if (count == 0) {
1070             memcpy(dst, src, 4 * sizeof(SkPoint));
1071         } else {
1072             SkChopCubicAt(src, dst, tValues, count);
1073         }
1074     }
1075     return count + 1;
1076 }
1077
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;
1083 }
1084
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);
1094     }
1095     return crosses[0] * crosses[1] >= 0;
1096 }
1097
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]) {
1107         return -1;
1108     }
1109     if (src[2] == src[3]) {
1110         return -1;
1111     }
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)) {
1115         return -1;
1116     }
1117     // Cubics may have multiple points of maximum curvature, although at most only
1118     // one is a cusp.
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
1124             continue;
1125         }
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.
1135             return testT;
1136         }
1137     }
1138     return -1;
1139 }
1140
1141 #include "src/pathops/SkPathOpsCubic.h"
1142
1143 typedef int (SkDCubic::*InterceptProc)(double intercept, double roots[3]) const;
1144
1145 static bool cubic_dchop_at_intercept(const SkPoint src[4], SkScalar intercept, SkPoint dst[7],
1146                                      InterceptProc method) {
1147     SkDCubic cubic;
1148     double roots[3];
1149     int count = (cubic.set(src).*method)(intercept, roots);
1150     if (count > 0) {
1151         SkDCubicPair pair = cubic.chopAt(roots[0]);
1152         for (int i = 0; i < 7; ++i) {
1153             dst[i] = pair.pts[i].asSkPoint();
1154         }
1155         return true;
1156     }
1157     return false;
1158 }
1159
1160 bool SkChopMonoCubicAtY(SkPoint src[4], SkScalar y, SkPoint dst[7]) {
1161     return cubic_dchop_at_intercept(src, y, dst, &SkDCubic::horizontalIntersect);
1162 }
1163
1164 bool SkChopMonoCubicAtX(SkPoint src[4], SkScalar x, SkPoint dst[7]) {
1165     return cubic_dchop_at_intercept(src, x, dst, &SkDCubic::verticalIntersect);
1166 }
1167
1168 ///////////////////////////////////////////////////////////////////////////////
1169 //
1170 // NURB representation for conics.  Helpful explanations at:
1171 //
1172 // http://citeseerx.ist.psu.edu/viewdoc/
1173 //   download?doi=10.1.1.44.5740&rep=rep1&type=ps
1174 // and
1175 // http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/NURBS/RB-conics.html
1176 //
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)
1180 //
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}
1184 //
1185
1186 // F' = 2 (C t (1 + t (-1 + w)) - A (-1 + t) (t (-1 + w) - w) + B (1 - 2 t) w)
1187 //
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
1191 //
1192 //  We disregard magnitude, so we can freely ignore the denominator of F', and
1193 //  divide the numerator by 2
1194 //
1195 //    coeff[0] for t^2
1196 //    coeff[1] for t^1
1197 //    coeff[2] for t^0
1198 //
1199 static void conic_deriv_coeff(const SkScalar src[],
1200                               SkScalar w,
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;
1207     coeff[2] = wP10;
1208 }
1209
1210 static bool conic_find_extrema(const SkScalar src[], SkScalar w, SkScalar* t) {
1211     SkScalar coeff[3];
1212     conic_deriv_coeff(src, w, coeff);
1213
1214     SkScalar tValues[2];
1215     int roots = SkFindUnitQuadRoots(coeff[0], coeff[1], coeff[2], tValues);
1216     SkASSERT(0 == roots || 1 == roots);
1217
1218     if (1 == roots) {
1219         *t = tValues[0];
1220         return true;
1221     }
1222     return false;
1223 }
1224
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);
1229     dst[0] = ab;
1230     dst[3] = SkScalarInterp(ab, bc, t);
1231     dst[6] = bc;
1232 }
1233
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);
1238 }
1239
1240 static SkPoint project_down(const SkPoint3& src) {
1241     return {src.fX / src.fZ, src.fY / src.fZ};
1242 }
1243
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];
1247
1248     ratquad_mapTo3D(fPts, fW, tmp);
1249
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);
1253
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];
1259
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)
1262     // or
1263     // w1 /= sqrt(w0*w2)
1264     //
1265     // However, in our case, we know that for dst[0]:
1266     //     w0 == 1, and for dst[1], w2 == 1
1267     //
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);
1274 }
1275
1276 void SkConic::chopAt(SkScalar t1, SkScalar t2, SkConic* dst) const {
1277     if (0 == t1 || 1 == t2) {
1278         if (0 == t1 && 1 == t2) {
1279             *dst = *this;
1280             return;
1281         } else {
1282             SkConic pair[2];
1283             if (this->chopAt(t1 ? t1 : t2, pair)) {
1284                 *dst = pair[SkToBool(t1)];
1285                 return;
1286             }
1287         }
1288     }
1289     SkConicCoeff coeff(*this);
1290     float2 tt1(t1);
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);
1296     float2 tt2(t2);
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);
1305     dst->fW = ww[0];
1306 }
1307
1308 SkPoint SkConic::evalAt(SkScalar t) const {
1309     return to_point(SkConicCoeff(*this).eval(t));
1310 }
1311
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];
1318     }
1319     float2 p0 = from_point(fPts[0]);
1320     float2 p1 = from_point(fPts[1]);
1321     float2 p2 = from_point(fPts[2]);
1322     float2 ww(fW);
1323
1324     float2 p20 = p2 - p0;
1325     float2 p10 = p1 - p0;
1326
1327     float2 C = ww * p10;
1328     float2 A = ww * p20 - p20;
1329     float2 B = p20 - C - C;
1330
1331     return to_vector(SkQuadCoeff(A, B, C).eval(t));
1332 }
1333
1334 void SkConic::evalAt(SkScalar t, SkPoint* pt, SkVector* tangent) const {
1335     SkASSERT(t >= 0 && t <= SK_Scalar1);
1336
1337     if (pt) {
1338         *pt = this->evalAt(t);
1339     }
1340     if (tangent) {
1341         *tangent = this->evalTangentAt(t);
1342     }
1343 }
1344
1345 static SkScalar subdivide_w_value(SkScalar w) {
1346     return SkScalarSqrt(SK_ScalarHalf + w * SK_ScalarHalf);
1347 }
1348
1349 void SkConic::chop(SkConic * SK_RESTRICT dst) const {
1350     float2 scale = SkScalarInvert(SK_Scalar1 + fW);
1351     SkScalar newW = subdivide_w_value(fW);
1352
1353     float2 p0 = from_point(fPts[0]);
1354     float2 p1 = from_point(fPts[1]);
1355     float2 p2 = from_point(fPts[2]);
1356     float2 ww(fW);
1357
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()) {
1362         double w_d = fW;
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);
1367     }
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];
1373
1374     dst[0].fW = dst[1].fW = newW;
1375 }
1376
1377 /*
1378  *  "High order approximation of conic sections by quadratic splines"
1379  *      by Michael Floater, 1993
1380  */
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);
1386
1387 void SkConic::computeAsQuadError(SkVector* err) const {
1388     AS_QUAD_ERROR_SETUP
1389     err->set(x, y);
1390 }
1391
1392 bool SkConic::asQuadTol(SkScalar tol) const {
1393     AS_QUAD_ERROR_SETUP
1394     return (x * x + y * y) <= tol * tol;
1395 }
1396
1397 // Limit the number of suggested quads to approximate a conic
1398 #define kMaxConicToQuadPOW2     5
1399
1400 int SkConic::computeQuadPOW2(SkScalar tol) const {
1401     if (tol < 0 || !SkScalarIsFinite(tol) || !SkPointPriv::AreFinite(fPts, 3)) {
1402         return 0;
1403     }
1404
1405     AS_QUAD_ERROR_SETUP
1406
1407     SkScalar error = SkScalarSqrt(x * x + y * y);
1408     int pow2;
1409     for (pow2 = 0; pow2 < kMaxConicToQuadPOW2; ++pow2) {
1410         if (error <= tol) {
1411             break;
1412         }
1413         error *= 0.25f;
1414     }
1415     // float version -- using ceil gives the same results as the above.
1416     if ((false)) {
1417         SkScalar err = SkScalarSqrt(x * x + y * y);
1418         if (err <= tol) {
1419             return 0;
1420         }
1421         SkScalar tol2 = tol * tol;
1422         if (tol2 == 0) {
1423             return kMaxConicToQuadPOW2;
1424         }
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);
1429         }
1430         pow2 = altPow2;
1431     }
1432     return pow2;
1433 }
1434
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;
1439 }
1440
1441 static SkPoint* subdivide(const SkConic& src, SkPoint pts[], int level) {
1442     SkASSERT(level >= 0);
1443
1444     if (0 == level) {
1445         memcpy(pts, &src.fPts[1], 2 * sizeof(SkPoint));
1446         return pts + 2;
1447     } else {
1448         SkConic dst[2];
1449         src.chop(dst);
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;
1460             }
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;
1465             }
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;
1470             }
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));
1475         }
1476         --level;
1477         pts = subdivide(dst[0], pts, level);
1478         return subdivide(dst[1], pts, level);
1479     }
1480 }
1481
1482 int SkConic::chopIntoQuadsPOW2(SkPoint pts[], int pow2) const {
1483     SkASSERT(pow2 >= 0);
1484     *pts = fPts[0];
1485     SkDEBUGCODE(SkPoint* endPts);
1486     if (pow2 == kMaxConicToQuadPOW2) {  // If an extreme weight generates many quads ...
1487         SkConic dst[2];
1488         this->chop(dst);
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];
1494             pow2 = 1;
1495             SkDEBUGCODE(endPts = &pts[5]);
1496             goto commonFinitePtCheck;
1497         }
1498     }
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) {
1508             pts[i] = fPts[1];
1509         }
1510     }
1511     return 1 << pow2;
1512 }
1513
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:
1517     //
1518     //     bisector dot midtangent = 0
1519     //
1520     SkVector tan0 = fPts[1] - fPts[0];
1521     SkVector tan1 = fPts[2] - fPts[1];
1522     SkVector bisector = SkFindBisector(tan0, -tan1);
1523
1524     // Start by finding the tangent function's power basis coefficients. These define a tangent
1525     // direction (scaled by some uniform value) as:
1526     //                                                |T^2|
1527     //     Tangent_Direction(T) = dx,dy = |A  B  C| * |T  |
1528     //                                    |.  .  .|   |1  |
1529     //
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;
1538
1539     // Now solve for "bisector dot midtangent = 0":
1540     //
1541     //                            |T^2|
1542     //     bisector * |A  B  C| * |T  | = 0
1543     //                |.  .  .|   |1  |
1544     //
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);
1549 }
1550
1551 bool SkConic::findXExtrema(SkScalar* t) const {
1552     return conic_find_extrema(&fPts[0].fX, fW, t);
1553 }
1554
1555 bool SkConic::findYExtrema(SkScalar* t) const {
1556     return conic_find_extrema(&fPts[0].fY, fW, t);
1557 }
1558
1559 bool SkConic::chopAtXExtrema(SkConic dst[2]) const {
1560     SkScalar t;
1561     if (this->findXExtrema(&t)) {
1562         if (!this->chopAt(t, dst)) {
1563             // if chop can't return finite values, don't chop
1564             return false;
1565         }
1566         // now clean-up the middle, since we know t was meant to be at
1567         // an X-extrema
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;
1572         return true;
1573     }
1574     return false;
1575 }
1576
1577 bool SkConic::chopAtYExtrema(SkConic dst[2]) const {
1578     SkScalar t;
1579     if (this->findYExtrema(&t)) {
1580         if (!this->chopAt(t, dst)) {
1581             // if chop can't return finite values, don't chop
1582             return false;
1583         }
1584         // now clean-up the middle, since we know t was meant to be at
1585         // an Y-extrema
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;
1590         return true;
1591     }
1592     return false;
1593 }
1594
1595 void SkConic::computeTightBounds(SkRect* bounds) const {
1596     SkPoint pts[4];
1597     pts[0] = fPts[0];
1598     pts[1] = fPts[2];
1599     int count = 2;
1600
1601     SkScalar t;
1602     if (this->findXExtrema(&t)) {
1603         this->evalAt(t, &pts[count++]);
1604     }
1605     if (this->findYExtrema(&t)) {
1606         this->evalAt(t, &pts[count++]);
1607     }
1608     bounds->setBounds(pts, count);
1609 }
1610
1611 void SkConic::computeFastBounds(SkRect* bounds) const {
1612     bounds->setBounds(fPts, 3);
1613 }
1614
1615 #if 0  // unimplemented
1616 bool SkConic::findMaxCurvature(SkScalar* t) const {
1617     // TODO: Implement me
1618     return false;
1619 }
1620 #endif
1621
1622 SkScalar SkConic::TransformW(const SkPoint pts[], SkScalar w, const SkMatrix& matrix) {
1623     if (!matrix.hasPerspective()) {
1624         return w;
1625     }
1626
1627     SkPoint3 src[3], dst[3];
1628
1629     ratquad_mapTo3D(pts, w, src);
1630
1631     matrix.mapHomogeneousPoints(dst, src, 3);
1632
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)));
1639 }
1640
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);
1646
1647     SkScalar absY = SkScalarAbs(y);
1648
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))) {
1654         return 0;
1655     }
1656
1657     if (dir == kCCW_SkRotationDirection) {
1658         y = -y;
1659     }
1660
1661     // We decide to use 1-conic per quadrant of a circle. What quadrant does [xy] lie in?
1662     //      0 == [0  .. 90)
1663     //      1 == [90 ..180)
1664     //      2 == [180..270)
1665     //      3 == [270..360)
1666     //
1667     int quadrant = 0;
1668     if (0 == y) {
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
1674     } else {
1675         if (y < 0) {
1676             quadrant += 2;
1677         }
1678         if ((x < 0) != (y < 0)) {
1679             quadrant += 1;
1680         }
1681     }
1682
1683     const SkPoint quadrantPts[] = {
1684         { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 }, { -1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 }
1685     };
1686     const SkScalar quadrantWeight = SK_ScalarRoot2Over2;
1687
1688     int conicCount = quadrant;
1689     for (int i = 0; i < conicCount; ++i) {
1690         dst[i].set(&quadrantPts[i * 2], quadrantWeight);
1691     }
1692
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);
1698
1699     if (dot < 1) {
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!
1705         //
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);
1710             conicCount += 1;
1711         }
1712     }
1713
1714     // now handle counter-clockwise and the initial unitStart rotation
1715     SkMatrix    matrix;
1716     matrix.setSinCos(uStart.fY, uStart.fX);
1717     if (dir == kCCW_SkRotationDirection) {
1718         matrix.preScale(SK_Scalar1, -SK_Scalar1);
1719     }
1720     if (userMatrix) {
1721         matrix.postConcat(*userMatrix);
1722     }
1723     for (int i = 0; i < conicCount; ++i) {
1724         matrix.mapPoints(dst[i].fPts, 3);
1725     }
1726     return conicCount;
1727 }