• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "SkGeometry.h"
9 #include "SkMatrix.h"
10 #include "SkNx.h"
11 
to_vector(const Sk2s & x)12 static SkVector to_vector(const Sk2s& x) {
13     SkVector vector;
14     x.store(&vector);
15     return vector;
16 }
17 
18 ////////////////////////////////////////////////////////////////////////
19 
is_not_monotonic(SkScalar a,SkScalar b,SkScalar c)20 static int is_not_monotonic(SkScalar a, SkScalar b, SkScalar c) {
21     SkScalar ab = a - b;
22     SkScalar bc = b - c;
23     if (ab < 0) {
24         bc = -bc;
25     }
26     return ab == 0 || bc < 0;
27 }
28 
29 ////////////////////////////////////////////////////////////////////////
30 
is_unit_interval(SkScalar x)31 static bool is_unit_interval(SkScalar x) {
32     return x > 0 && x < SK_Scalar1;
33 }
34 
valid_unit_divide(SkScalar numer,SkScalar denom,SkScalar * ratio)35 static int valid_unit_divide(SkScalar numer, SkScalar denom, SkScalar* ratio) {
36     SkASSERT(ratio);
37 
38     if (numer < 0) {
39         numer = -numer;
40         denom = -denom;
41     }
42 
43     if (denom == 0 || numer == 0 || numer >= denom) {
44         return 0;
45     }
46 
47     SkScalar r = numer / denom;
48     if (SkScalarIsNaN(r)) {
49         return 0;
50     }
51     SkASSERTF(r >= 0 && r < SK_Scalar1, "numer %f, denom %f, r %f", numer, denom, r);
52     if (r == 0) { // catch underflow if numer <<<< denom
53         return 0;
54     }
55     *ratio = r;
56     return 1;
57 }
58 
59 /** From Numerical Recipes in C.
60 
61     Q = -1/2 (B + sign(B) sqrt[B*B - 4*A*C])
62     x1 = Q / A
63     x2 = C / Q
64 */
SkFindUnitQuadRoots(SkScalar A,SkScalar B,SkScalar C,SkScalar roots[2])65 int SkFindUnitQuadRoots(SkScalar A, SkScalar B, SkScalar C, SkScalar roots[2]) {
66     SkASSERT(roots);
67 
68     if (A == 0) {
69         return valid_unit_divide(-C, B, roots);
70     }
71 
72     SkScalar* r = roots;
73 
74     SkScalar R = B*B - 4*A*C;
75     if (R < 0 || !SkScalarIsFinite(R)) {  // complex roots
76         // if R is infinite, it's possible that it may still produce
77         // useful results if the operation was repeated in doubles
78         // the flipside is determining if the more precise answer
79         // isn't useful because surrounding machinery (e.g., subtracting
80         // the axis offset from C) already discards the extra precision
81         // more investigation and unit tests required...
82         return 0;
83     }
84     R = SkScalarSqrt(R);
85 
86     SkScalar Q = (B < 0) ? -(B-R)/2 : -(B+R)/2;
87     r += valid_unit_divide(Q, A, r);
88     r += valid_unit_divide(C, Q, r);
89     if (r - roots == 2) {
90         if (roots[0] > roots[1])
91             SkTSwap<SkScalar>(roots[0], roots[1]);
92         else if (roots[0] == roots[1])  // nearly-equal?
93             r -= 1; // skip the double root
94     }
95     return (int)(r - roots);
96 }
97 
98 ///////////////////////////////////////////////////////////////////////////////
99 ///////////////////////////////////////////////////////////////////////////////
100 
SkEvalQuadAt(const SkPoint src[3],SkScalar t,SkPoint * pt,SkVector * tangent)101 void SkEvalQuadAt(const SkPoint src[3], SkScalar t, SkPoint* pt, SkVector* tangent) {
102     SkASSERT(src);
103     SkASSERT(t >= 0 && t <= SK_Scalar1);
104 
105     if (pt) {
106         *pt = SkEvalQuadAt(src, t);
107     }
108     if (tangent) {
109         *tangent = SkEvalQuadTangentAt(src, t);
110     }
111 }
112 
SkEvalQuadAt(const SkPoint src[3],SkScalar t)113 SkPoint SkEvalQuadAt(const SkPoint src[3], SkScalar t) {
114     return to_point(SkQuadCoeff(src).eval(t));
115 }
116 
SkEvalQuadTangentAt(const SkPoint src[3],SkScalar t)117 SkVector SkEvalQuadTangentAt(const SkPoint src[3], SkScalar t) {
118     // The derivative equation is 2(b - a +(a - 2b +c)t). This returns a
119     // zero tangent vector when t is 0 or 1, and the control point is equal
120     // to the end point. In this case, use the quad end points to compute the tangent.
121     if ((t == 0 && src[0] == src[1]) || (t == 1 && src[1] == src[2])) {
122         return src[2] - src[0];
123     }
124     SkASSERT(src);
125     SkASSERT(t >= 0 && t <= SK_Scalar1);
126 
127     Sk2s P0 = from_point(src[0]);
128     Sk2s P1 = from_point(src[1]);
129     Sk2s P2 = from_point(src[2]);
130 
131     Sk2s B = P1 - P0;
132     Sk2s A = P2 - P1 - B;
133     Sk2s T = A * Sk2s(t) + B;
134 
135     return to_vector(T + T);
136 }
137 
interp(const Sk2s & v0,const Sk2s & v1,const Sk2s & t)138 static inline Sk2s interp(const Sk2s& v0, const Sk2s& v1, const Sk2s& t) {
139     return v0 + (v1 - v0) * t;
140 }
141 
SkChopQuadAt(const SkPoint src[3],SkPoint dst[5],SkScalar t)142 void SkChopQuadAt(const SkPoint src[3], SkPoint dst[5], SkScalar t) {
143     SkASSERT(t > 0 && t < SK_Scalar1);
144 
145     Sk2s p0 = from_point(src[0]);
146     Sk2s p1 = from_point(src[1]);
147     Sk2s p2 = from_point(src[2]);
148     Sk2s tt(t);
149 
150     Sk2s p01 = interp(p0, p1, tt);
151     Sk2s p12 = interp(p1, p2, tt);
152 
153     dst[0] = to_point(p0);
154     dst[1] = to_point(p01);
155     dst[2] = to_point(interp(p01, p12, tt));
156     dst[3] = to_point(p12);
157     dst[4] = to_point(p2);
158 }
159 
SkChopQuadAtHalf(const SkPoint src[3],SkPoint dst[5])160 void SkChopQuadAtHalf(const SkPoint src[3], SkPoint dst[5]) {
161     SkChopQuadAt(src, dst, 0.5f);
162 }
163 
164 /** Quad'(t) = At + B, where
165     A = 2(a - 2b + c)
166     B = 2(b - a)
167     Solve for t, only if it fits between 0 < t < 1
168 */
SkFindQuadExtrema(SkScalar a,SkScalar b,SkScalar c,SkScalar tValue[1])169 int SkFindQuadExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar tValue[1]) {
170     /*  At + B == 0
171         t = -B / A
172     */
173     return valid_unit_divide(a - b, a - b - b + c, tValue);
174 }
175 
flatten_double_quad_extrema(SkScalar coords[14])176 static inline void flatten_double_quad_extrema(SkScalar coords[14]) {
177     coords[2] = coords[6] = coords[4];
178 }
179 
180 /*  Returns 0 for 1 quad, and 1 for two quads, either way the answer is
181  stored in dst[]. Guarantees that the 1/2 quads will be monotonic.
182  */
SkChopQuadAtYExtrema(const SkPoint src[3],SkPoint dst[5])183 int SkChopQuadAtYExtrema(const SkPoint src[3], SkPoint dst[5]) {
184     SkASSERT(src);
185     SkASSERT(dst);
186 
187     SkScalar a = src[0].fY;
188     SkScalar b = src[1].fY;
189     SkScalar c = src[2].fY;
190 
191     if (is_not_monotonic(a, b, c)) {
192         SkScalar    tValue;
193         if (valid_unit_divide(a - b, a - b - b + c, &tValue)) {
194             SkChopQuadAt(src, dst, tValue);
195             flatten_double_quad_extrema(&dst[0].fY);
196             return 1;
197         }
198         // if we get here, we need to force dst to be monotonic, even though
199         // we couldn't compute a unit_divide value (probably underflow).
200         b = SkScalarAbs(a - b) < SkScalarAbs(b - c) ? a : c;
201     }
202     dst[0].set(src[0].fX, a);
203     dst[1].set(src[1].fX, b);
204     dst[2].set(src[2].fX, c);
205     return 0;
206 }
207 
208 /*  Returns 0 for 1 quad, and 1 for two quads, either way the answer is
209     stored in dst[]. Guarantees that the 1/2 quads will be monotonic.
210  */
SkChopQuadAtXExtrema(const SkPoint src[3],SkPoint dst[5])211 int SkChopQuadAtXExtrema(const SkPoint src[3], SkPoint dst[5]) {
212     SkASSERT(src);
213     SkASSERT(dst);
214 
215     SkScalar a = src[0].fX;
216     SkScalar b = src[1].fX;
217     SkScalar c = src[2].fX;
218 
219     if (is_not_monotonic(a, b, c)) {
220         SkScalar tValue;
221         if (valid_unit_divide(a - b, a - b - b + c, &tValue)) {
222             SkChopQuadAt(src, dst, tValue);
223             flatten_double_quad_extrema(&dst[0].fX);
224             return 1;
225         }
226         // if we get here, we need to force dst to be monotonic, even though
227         // we couldn't compute a unit_divide value (probably underflow).
228         b = SkScalarAbs(a - b) < SkScalarAbs(b - c) ? a : c;
229     }
230     dst[0].set(a, src[0].fY);
231     dst[1].set(b, src[1].fY);
232     dst[2].set(c, src[2].fY);
233     return 0;
234 }
235 
236 //  F(t)    = a (1 - t) ^ 2 + 2 b t (1 - t) + c t ^ 2
237 //  F'(t)   = 2 (b - a) + 2 (a - 2b + c) t
238 //  F''(t)  = 2 (a - 2b + c)
239 //
240 //  A = 2 (b - a)
241 //  B = 2 (a - 2b + c)
242 //
243 //  Maximum curvature for a quadratic means solving
244 //  Fx' Fx'' + Fy' Fy'' = 0
245 //
246 //  t = - (Ax Bx + Ay By) / (Bx ^ 2 + By ^ 2)
247 //
SkFindQuadMaxCurvature(const SkPoint src[3])248 SkScalar SkFindQuadMaxCurvature(const SkPoint src[3]) {
249     SkScalar    Ax = src[1].fX - src[0].fX;
250     SkScalar    Ay = src[1].fY - src[0].fY;
251     SkScalar    Bx = src[0].fX - src[1].fX - src[1].fX + src[2].fX;
252     SkScalar    By = src[0].fY - src[1].fY - src[1].fY + src[2].fY;
253     SkScalar    t = 0;  // 0 means don't chop
254 
255     (void)valid_unit_divide(-(Ax * Bx + Ay * By), Bx * Bx + By * By, &t);
256     return t;
257 }
258 
SkChopQuadAtMaxCurvature(const SkPoint src[3],SkPoint dst[5])259 int SkChopQuadAtMaxCurvature(const SkPoint src[3], SkPoint dst[5]) {
260     SkScalar t = SkFindQuadMaxCurvature(src);
261     if (t == 0) {
262         memcpy(dst, src, 3 * sizeof(SkPoint));
263         return 1;
264     } else {
265         SkChopQuadAt(src, dst, t);
266         return 2;
267     }
268 }
269 
SkConvertQuadToCubic(const SkPoint src[3],SkPoint dst[4])270 void SkConvertQuadToCubic(const SkPoint src[3], SkPoint dst[4]) {
271     Sk2s scale(SkDoubleToScalar(2.0 / 3.0));
272     Sk2s s0 = from_point(src[0]);
273     Sk2s s1 = from_point(src[1]);
274     Sk2s s2 = from_point(src[2]);
275 
276     dst[0] = src[0];
277     dst[1] = to_point(s0 + (s1 - s0) * scale);
278     dst[2] = to_point(s2 + (s1 - s2) * scale);
279     dst[3] = src[2];
280 }
281 
282 //////////////////////////////////////////////////////////////////////////////
283 ///// CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS /////
284 //////////////////////////////////////////////////////////////////////////////
285 
eval_cubic_derivative(const SkPoint src[4],SkScalar t)286 static SkVector eval_cubic_derivative(const SkPoint src[4], SkScalar t) {
287     SkQuadCoeff coeff;
288     Sk2s P0 = from_point(src[0]);
289     Sk2s P1 = from_point(src[1]);
290     Sk2s P2 = from_point(src[2]);
291     Sk2s P3 = from_point(src[3]);
292 
293     coeff.fA = P3 + Sk2s(3) * (P1 - P2) - P0;
294     coeff.fB = times_2(P2 - times_2(P1) + P0);
295     coeff.fC = P1 - P0;
296     return to_vector(coeff.eval(t));
297 }
298 
eval_cubic_2ndDerivative(const SkPoint src[4],SkScalar t)299 static SkVector eval_cubic_2ndDerivative(const SkPoint src[4], SkScalar t) {
300     Sk2s P0 = from_point(src[0]);
301     Sk2s P1 = from_point(src[1]);
302     Sk2s P2 = from_point(src[2]);
303     Sk2s P3 = from_point(src[3]);
304     Sk2s A = P3 + Sk2s(3) * (P1 - P2) - P0;
305     Sk2s B = P2 - times_2(P1) + P0;
306 
307     return to_vector(A * Sk2s(t) + B);
308 }
309 
SkEvalCubicAt(const SkPoint src[4],SkScalar t,SkPoint * loc,SkVector * tangent,SkVector * curvature)310 void SkEvalCubicAt(const SkPoint src[4], SkScalar t, SkPoint* loc,
311                    SkVector* tangent, SkVector* curvature) {
312     SkASSERT(src);
313     SkASSERT(t >= 0 && t <= SK_Scalar1);
314 
315     if (loc) {
316         *loc = to_point(SkCubicCoeff(src).eval(t));
317     }
318     if (tangent) {
319         // The derivative equation returns a zero tangent vector when t is 0 or 1, and the
320         // adjacent control point is equal to the end point. In this case, use the
321         // next control point or the end points to compute the tangent.
322         if ((t == 0 && src[0] == src[1]) || (t == 1 && src[2] == src[3])) {
323             if (t == 0) {
324                 *tangent = src[2] - src[0];
325             } else {
326                 *tangent = src[3] - src[1];
327             }
328             if (!tangent->fX && !tangent->fY) {
329                 *tangent = src[3] - src[0];
330             }
331         } else {
332             *tangent = eval_cubic_derivative(src, t);
333         }
334     }
335     if (curvature) {
336         *curvature = eval_cubic_2ndDerivative(src, t);
337     }
338 }
339 
340 /** Cubic'(t) = At^2 + Bt + C, where
341     A = 3(-a + 3(b - c) + d)
342     B = 6(a - 2b + c)
343     C = 3(b - a)
344     Solve for t, keeping only those that fit betwee 0 < t < 1
345 */
SkFindCubicExtrema(SkScalar a,SkScalar b,SkScalar c,SkScalar d,SkScalar tValues[2])346 int SkFindCubicExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar d,
347                        SkScalar tValues[2]) {
348     // we divide A,B,C by 3 to simplify
349     SkScalar A = d - a + 3*(b - c);
350     SkScalar B = 2*(a - b - b + c);
351     SkScalar C = b - a;
352 
353     return SkFindUnitQuadRoots(A, B, C, tValues);
354 }
355 
SkChopCubicAt(const SkPoint src[4],SkPoint dst[7],SkScalar t)356 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[7], SkScalar t) {
357     SkASSERT(t > 0 && t < SK_Scalar1);
358 
359     Sk2s    p0 = from_point(src[0]);
360     Sk2s    p1 = from_point(src[1]);
361     Sk2s    p2 = from_point(src[2]);
362     Sk2s    p3 = from_point(src[3]);
363     Sk2s    tt(t);
364 
365     Sk2s    ab = interp(p0, p1, tt);
366     Sk2s    bc = interp(p1, p2, tt);
367     Sk2s    cd = interp(p2, p3, tt);
368     Sk2s    abc = interp(ab, bc, tt);
369     Sk2s    bcd = interp(bc, cd, tt);
370     Sk2s    abcd = interp(abc, bcd, tt);
371 
372     dst[0] = src[0];
373     dst[1] = to_point(ab);
374     dst[2] = to_point(abc);
375     dst[3] = to_point(abcd);
376     dst[4] = to_point(bcd);
377     dst[5] = to_point(cd);
378     dst[6] = src[3];
379 }
380 
381 /*  http://code.google.com/p/skia/issues/detail?id=32
382 
383     This test code would fail when we didn't check the return result of
384     valid_unit_divide in SkChopCubicAt(... tValues[], int roots). The reason is
385     that after the first chop, the parameters to valid_unit_divide are equal
386     (thanks to finite float precision and rounding in the subtracts). Thus
387     even though the 2nd tValue looks < 1.0, after we renormalize it, we end
388     up with 1.0, hence the need to check and just return the last cubic as
389     a degenerate clump of 4 points in the sampe place.
390 
391     static void test_cubic() {
392         SkPoint src[4] = {
393             { 556.25000, 523.03003 },
394             { 556.23999, 522.96002 },
395             { 556.21997, 522.89001 },
396             { 556.21997, 522.82001 }
397         };
398         SkPoint dst[10];
399         SkScalar tval[] = { 0.33333334f, 0.99999994f };
400         SkChopCubicAt(src, dst, tval, 2);
401     }
402  */
403 
SkChopCubicAt(const SkPoint src[4],SkPoint dst[],const SkScalar tValues[],int roots)404 void SkChopCubicAt(const SkPoint src[4], SkPoint dst[],
405                    const SkScalar tValues[], int roots) {
406 #ifdef SK_DEBUG
407     {
408         for (int i = 0; i < roots - 1; i++)
409         {
410             SkASSERT(is_unit_interval(tValues[i]));
411             SkASSERT(is_unit_interval(tValues[i+1]));
412             SkASSERT(tValues[i] < tValues[i+1]);
413         }
414     }
415 #endif
416 
417     if (dst) {
418         if (roots == 0) { // nothing to chop
419             memcpy(dst, src, 4*sizeof(SkPoint));
420         } else {
421             SkScalar    t = tValues[0];
422             SkPoint     tmp[4];
423 
424             for (int i = 0; i < roots; i++) {
425                 SkChopCubicAt(src, dst, t);
426                 if (i == roots - 1) {
427                     break;
428                 }
429 
430                 dst += 3;
431                 // have src point to the remaining cubic (after the chop)
432                 memcpy(tmp, dst, 4 * sizeof(SkPoint));
433                 src = tmp;
434 
435                 // watch out in case the renormalized t isn't in range
436                 if (!valid_unit_divide(tValues[i+1] - tValues[i],
437                                        SK_Scalar1 - tValues[i], &t)) {
438                     // if we can't, just create a degenerate cubic
439                     dst[4] = dst[5] = dst[6] = src[3];
440                     break;
441                 }
442             }
443         }
444     }
445 }
446 
SkChopCubicAtHalf(const SkPoint src[4],SkPoint dst[7])447 void SkChopCubicAtHalf(const SkPoint src[4], SkPoint dst[7]) {
448     SkChopCubicAt(src, dst, 0.5f);
449 }
450 
flatten_double_cubic_extrema(SkScalar coords[14])451 static void flatten_double_cubic_extrema(SkScalar coords[14]) {
452     coords[4] = coords[8] = coords[6];
453 }
454 
455 /** Given 4 points on a cubic bezier, chop it into 1, 2, 3 beziers such that
456     the resulting beziers are monotonic in Y. This is called by the scan
457     converter.  Depending on what is returned, dst[] is treated as follows:
458     0   dst[0..3] is the original cubic
459     1   dst[0..3] and dst[3..6] are the two new cubics
460     2   dst[0..3], dst[3..6], dst[6..9] are the three new cubics
461     If dst == null, it is ignored and only the count is returned.
462 */
SkChopCubicAtYExtrema(const SkPoint src[4],SkPoint dst[10])463 int SkChopCubicAtYExtrema(const SkPoint src[4], SkPoint dst[10]) {
464     SkScalar    tValues[2];
465     int         roots = SkFindCubicExtrema(src[0].fY, src[1].fY, src[2].fY,
466                                            src[3].fY, tValues);
467 
468     SkChopCubicAt(src, dst, tValues, roots);
469     if (dst && roots > 0) {
470         // we do some cleanup to ensure our Y extrema are flat
471         flatten_double_cubic_extrema(&dst[0].fY);
472         if (roots == 2) {
473             flatten_double_cubic_extrema(&dst[3].fY);
474         }
475     }
476     return roots;
477 }
478 
SkChopCubicAtXExtrema(const SkPoint src[4],SkPoint dst[10])479 int SkChopCubicAtXExtrema(const SkPoint src[4], SkPoint dst[10]) {
480     SkScalar    tValues[2];
481     int         roots = SkFindCubicExtrema(src[0].fX, src[1].fX, src[2].fX,
482                                            src[3].fX, tValues);
483 
484     SkChopCubicAt(src, dst, tValues, roots);
485     if (dst && roots > 0) {
486         // we do some cleanup to ensure our Y extrema are flat
487         flatten_double_cubic_extrema(&dst[0].fX);
488         if (roots == 2) {
489             flatten_double_cubic_extrema(&dst[3].fX);
490         }
491     }
492     return roots;
493 }
494 
495 /** http://www.faculty.idc.ac.il/arik/quality/appendixA.html
496 
497     Inflection means that curvature is zero.
498     Curvature is [F' x F''] / [F'^3]
499     So we solve F'x X F''y - F'y X F''y == 0
500     After some canceling of the cubic term, we get
501     A = b - a
502     B = c - 2b + a
503     C = d - 3c + 3b - a
504     (BxCy - ByCx)t^2 + (AxCy - AyCx)t + AxBy - AyBx == 0
505 */
SkFindCubicInflections(const SkPoint src[4],SkScalar tValues[])506 int SkFindCubicInflections(const SkPoint src[4], SkScalar tValues[]) {
507     SkScalar    Ax = src[1].fX - src[0].fX;
508     SkScalar    Ay = src[1].fY - src[0].fY;
509     SkScalar    Bx = src[2].fX - 2 * src[1].fX + src[0].fX;
510     SkScalar    By = src[2].fY - 2 * src[1].fY + src[0].fY;
511     SkScalar    Cx = src[3].fX + 3 * (src[1].fX - src[2].fX) - src[0].fX;
512     SkScalar    Cy = src[3].fY + 3 * (src[1].fY - src[2].fY) - src[0].fY;
513 
514     return SkFindUnitQuadRoots(Bx*Cy - By*Cx,
515                                Ax*Cy - Ay*Cx,
516                                Ax*By - Ay*Bx,
517                                tValues);
518 }
519 
SkChopCubicAtInflections(const SkPoint src[],SkPoint dst[10])520 int SkChopCubicAtInflections(const SkPoint src[], SkPoint dst[10]) {
521     SkScalar    tValues[2];
522     int         count = SkFindCubicInflections(src, tValues);
523 
524     if (dst) {
525         if (count == 0) {
526             memcpy(dst, src, 4 * sizeof(SkPoint));
527         } else {
528             SkChopCubicAt(src, dst, tValues, count);
529         }
530     }
531     return count + 1;
532 }
533 
534 // Assumes the third component of points is 1.
535 // Calcs p0 . (p1 x p2)
calc_dot_cross_cubic(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2)536 static double calc_dot_cross_cubic(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2) {
537     const double xComp = (double) p0.fX * (double) (p1.fY - p2.fY);
538     const double yComp = (double) p0.fY * (double) (p2.fX - p1.fX);
539     const double wComp = (double) p1.fX * (double) p2.fY - (double) p1.fY * (double) p2.fX;
540     return (xComp + yComp + wComp);
541 }
542 
543 // Calc coefficients of I(s,t) where roots of I are inflection points of curve
544 // I(s,t) = t*(3*d0*s^2 - 3*d1*s*t + d2*t^2)
545 // d0 = a1 - 2*a2+3*a3
546 // d1 = -a2 + 3*a3
547 // d2 = 3*a3
548 // a1 = p0 . (p3 x p2)
549 // a2 = p1 . (p0 x p3)
550 // a3 = p2 . (p1 x p0)
551 // Places the values of d1, d2, d3 in array d passed in
calc_cubic_inflection_func(const SkPoint p[4],double d[4])552 static void calc_cubic_inflection_func(const SkPoint p[4], double d[4]) {
553     const double a1 = calc_dot_cross_cubic(p[0], p[3], p[2]);
554     const double a2 = calc_dot_cross_cubic(p[1], p[0], p[3]);
555     const double a3 = calc_dot_cross_cubic(p[2], p[1], p[0]);
556 
557     d[3] = 3 * a3;
558     d[2] = d[3] - a2;
559     d[1] = d[2] - a2 + a1;
560     d[0] = 0;
561 }
562 
normalize_t_s(double t[],double s[],int count)563 static void normalize_t_s(double t[], double s[], int count) {
564     // Keep the exponents at or below zero to avoid overflow down the road.
565     for (int i = 0; i < count; ++i) {
566         SkASSERT(0 != s[i]);
567         union { double value; int64_t bits; } tt, ss, norm;
568         tt.value = t[i];
569         ss.value = s[i];
570         int64_t expT = ((tt.bits >> 52) & 0x7ff) - 1023,
571                 expS = ((ss.bits >> 52) & 0x7ff) - 1023;
572         int64_t expNorm = -SkTMax(expT, expS) + 1023;
573         SkASSERT(expNorm > 0 && expNorm < 2047); // ensure we have a valid non-zero exponent.
574         norm.bits = expNorm << 52;
575         t[i] *= norm.value;
576         s[i] *= norm.value;
577     }
578 }
579 
sort_and_orient_t_s(double t[2],double s[2])580 static void sort_and_orient_t_s(double t[2], double s[2]) {
581     // This copysign/abs business orients the implicit function so positive values are always on the
582     // "left" side of the curve.
583     t[1] = -copysign(t[1], t[1] * s[1]);
584     s[1] = -fabs(s[1]);
585 
586     // Ensure t[0]/s[0] <= t[1]/s[1] (s[1] is negative from above).
587     if (copysign(s[1], s[0]) * t[0] > -fabs(s[0]) * t[1]) {
588         std::swap(t[0], t[1]);
589         std::swap(s[0], s[1]);
590     }
591 }
592 
593 // See "Resolution Independent Curve Rendering using Programmable Graphics Hardware"
594 // https://www.microsoft.com/en-us/research/wp-content/uploads/2005/01/p1000-loop.pdf
595 // discr(I) = 3*d2^2 - 4*d1*d3
596 // Classification:
597 // d1 != 0, discr(I) > 0        Serpentine
598 // d1 != 0, discr(I) < 0        Loop
599 // d1 != 0, discr(I) = 0        Cusp (with inflection at infinity)
600 // d1 = 0, d2 != 0              Cusp (with cusp at infinity)
601 // d1 = d2 = 0, d3 != 0         Quadratic
602 // d1 = d2 = d3 = 0             Line or Point
classify_cubic(const double d[4],double t[2],double s[2])603 static SkCubicType classify_cubic(const double d[4], double t[2], double s[2]) {
604     // Check for degenerate cubics (quadratics, lines, and points).
605     // This also attempts to detect near-quadratics in a resolution independent fashion, however it
606     // is still up to the caller to check for almost-linear curves if needed.
607     if (fabs(d[1]) + fabs(d[2]) <= fabs(d[3]) * 1e-3) {
608         if (t && s) {
609             t[0] = t[1] = 1;
610             s[0] = s[1] = 0; // infinity
611         }
612         return 0 == d[3] ? SkCubicType::kLineOrPoint : SkCubicType::kQuadratic;
613     }
614 
615     if (0 == d[1]) {
616         SkASSERT(0 != d[2]); // captured in check for degeneracy above.
617         if (t && s) {
618             t[0] = d[3];
619             s[0] = 3 * d[2];
620             normalize_t_s(t, s, 1);
621             t[1] = 1;
622             s[1] = 0; // infinity
623         }
624         return SkCubicType::kCuspAtInfinity;
625     }
626 
627     const double discr = 3 * d[2] * d[2] - 4 * d[1] * d[3];
628     if (discr > 0) {
629         if (t && s) {
630             const double q = 3 * d[2] + copysign(sqrt(3 * discr), d[2]);
631             t[0] = q;
632             s[0] = 6 * d[1];
633             t[1] = 2 * d[3];
634             s[1] = q;
635             normalize_t_s(t, s, 2);
636             sort_and_orient_t_s(t, s);
637         }
638         return SkCubicType::kSerpentine;
639     } else if (discr < 0) {
640         if (t && s) {
641             const double q = d[2] + copysign(sqrt(-discr), d[2]);
642             t[0] = q;
643             s[0] = 2 * d[1];
644             t[1] = 2 * (d[2] * d[2] - d[3] * d[1]);
645             s[1] = d[1] * q;
646             normalize_t_s(t, s, 2);
647             sort_and_orient_t_s(t, s);
648         }
649         return SkCubicType::kLoop;
650     } else {
651         SkASSERT(0 == discr); // Detect NaN.
652         if (t && s) {
653             t[0] = d[2];
654             s[0] = 2 * d[1];
655             normalize_t_s(t, s, 1);
656             t[1] = t[0];
657             s[1] = s[0];
658             sort_and_orient_t_s(t, s);
659         }
660         return SkCubicType::kLocalCusp;
661     }
662 }
663 
SkClassifyCubic(const SkPoint src[4],double t[2],double s[2],double d[4])664 SkCubicType SkClassifyCubic(const SkPoint src[4], double t[2], double s[2], double d[4]) {
665     double localD[4];
666     double* dd = d ? d : localD;
667     calc_cubic_inflection_func(src, dd);
668     return classify_cubic(dd, t, s);
669 }
670 
bubble_sort(T array[],int count)671 template <typename T> void bubble_sort(T array[], int count) {
672     for (int i = count - 1; i > 0; --i)
673         for (int j = i; j > 0; --j)
674             if (array[j] < array[j-1])
675             {
676                 T   tmp(array[j]);
677                 array[j] = array[j-1];
678                 array[j-1] = tmp;
679             }
680 }
681 
682 /**
683  *  Given an array and count, remove all pair-wise duplicates from the array,
684  *  keeping the existing sorting, and return the new count
685  */
collaps_duplicates(SkScalar array[],int count)686 static int collaps_duplicates(SkScalar array[], int count) {
687     for (int n = count; n > 1; --n) {
688         if (array[0] == array[1]) {
689             for (int i = 1; i < n; ++i) {
690                 array[i - 1] = array[i];
691             }
692             count -= 1;
693         } else {
694             array += 1;
695         }
696     }
697     return count;
698 }
699 
700 #ifdef SK_DEBUG
701 
702 #define TEST_COLLAPS_ENTRY(array)   array, SK_ARRAY_COUNT(array)
703 
test_collaps_duplicates()704 static void test_collaps_duplicates() {
705     static bool gOnce;
706     if (gOnce) { return; }
707     gOnce = true;
708     const SkScalar src0[] = { 0 };
709     const SkScalar src1[] = { 0, 0 };
710     const SkScalar src2[] = { 0, 1 };
711     const SkScalar src3[] = { 0, 0, 0 };
712     const SkScalar src4[] = { 0, 0, 1 };
713     const SkScalar src5[] = { 0, 1, 1 };
714     const SkScalar src6[] = { 0, 1, 2 };
715     const struct {
716         const SkScalar* fData;
717         int fCount;
718         int fCollapsedCount;
719     } data[] = {
720         { TEST_COLLAPS_ENTRY(src0), 1 },
721         { TEST_COLLAPS_ENTRY(src1), 1 },
722         { TEST_COLLAPS_ENTRY(src2), 2 },
723         { TEST_COLLAPS_ENTRY(src3), 1 },
724         { TEST_COLLAPS_ENTRY(src4), 2 },
725         { TEST_COLLAPS_ENTRY(src5), 2 },
726         { TEST_COLLAPS_ENTRY(src6), 3 },
727     };
728     for (size_t i = 0; i < SK_ARRAY_COUNT(data); ++i) {
729         SkScalar dst[3];
730         memcpy(dst, data[i].fData, data[i].fCount * sizeof(dst[0]));
731         int count = collaps_duplicates(dst, data[i].fCount);
732         SkASSERT(data[i].fCollapsedCount == count);
733         for (int j = 1; j < count; ++j) {
734             SkASSERT(dst[j-1] < dst[j]);
735         }
736     }
737 }
738 #endif
739 
SkScalarCubeRoot(SkScalar x)740 static SkScalar SkScalarCubeRoot(SkScalar x) {
741     return SkScalarPow(x, 0.3333333f);
742 }
743 
744 /*  Solve coeff(t) == 0, returning the number of roots that
745     lie withing 0 < t < 1.
746     coeff[0]t^3 + coeff[1]t^2 + coeff[2]t + coeff[3]
747 
748     Eliminates repeated roots (so that all tValues are distinct, and are always
749     in increasing order.
750 */
solve_cubic_poly(const SkScalar coeff[4],SkScalar tValues[3])751 static int solve_cubic_poly(const SkScalar coeff[4], SkScalar tValues[3]) {
752     if (SkScalarNearlyZero(coeff[0])) {  // we're just a quadratic
753         return SkFindUnitQuadRoots(coeff[1], coeff[2], coeff[3], tValues);
754     }
755 
756     SkScalar a, b, c, Q, R;
757 
758     {
759         SkASSERT(coeff[0] != 0);
760 
761         SkScalar inva = SkScalarInvert(coeff[0]);
762         a = coeff[1] * inva;
763         b = coeff[2] * inva;
764         c = coeff[3] * inva;
765     }
766     Q = (a*a - b*3) / 9;
767     R = (2*a*a*a - 9*a*b + 27*c) / 54;
768 
769     SkScalar Q3 = Q * Q * Q;
770     SkScalar R2MinusQ3 = R * R - Q3;
771     SkScalar adiv3 = a / 3;
772 
773     SkScalar*   roots = tValues;
774     SkScalar    r;
775 
776     if (R2MinusQ3 < 0) { // we have 3 real roots
777         // the divide/root can, due to finite precisions, be slightly outside of -1...1
778         SkScalar theta = SkScalarACos(SkScalarPin(R / SkScalarSqrt(Q3), -1, 1));
779         SkScalar neg2RootQ = -2 * SkScalarSqrt(Q);
780 
781         r = neg2RootQ * SkScalarCos(theta/3) - adiv3;
782         if (is_unit_interval(r)) {
783             *roots++ = r;
784         }
785         r = neg2RootQ * SkScalarCos((theta + 2*SK_ScalarPI)/3) - adiv3;
786         if (is_unit_interval(r)) {
787             *roots++ = r;
788         }
789         r = neg2RootQ * SkScalarCos((theta - 2*SK_ScalarPI)/3) - adiv3;
790         if (is_unit_interval(r)) {
791             *roots++ = r;
792         }
793         SkDEBUGCODE(test_collaps_duplicates();)
794 
795         // now sort the roots
796         int count = (int)(roots - tValues);
797         SkASSERT((unsigned)count <= 3);
798         bubble_sort(tValues, count);
799         count = collaps_duplicates(tValues, count);
800         roots = tValues + count;    // so we compute the proper count below
801     } else {              // we have 1 real root
802         SkScalar A = SkScalarAbs(R) + SkScalarSqrt(R2MinusQ3);
803         A = SkScalarCubeRoot(A);
804         if (R > 0) {
805             A = -A;
806         }
807         if (A != 0) {
808             A += Q / A;
809         }
810         r = A - adiv3;
811         if (is_unit_interval(r)) {
812             *roots++ = r;
813         }
814     }
815 
816     return (int)(roots - tValues);
817 }
818 
819 /*  Looking for F' dot F'' == 0
820 
821     A = b - a
822     B = c - 2b + a
823     C = d - 3c + 3b - a
824 
825     F' = 3Ct^2 + 6Bt + 3A
826     F'' = 6Ct + 6B
827 
828     F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
829 */
formulate_F1DotF2(const SkScalar src[],SkScalar coeff[4])830 static void formulate_F1DotF2(const SkScalar src[], SkScalar coeff[4]) {
831     SkScalar    a = src[2] - src[0];
832     SkScalar    b = src[4] - 2 * src[2] + src[0];
833     SkScalar    c = src[6] + 3 * (src[2] - src[4]) - src[0];
834 
835     coeff[0] = c * c;
836     coeff[1] = 3 * b * c;
837     coeff[2] = 2 * b * b + c * a;
838     coeff[3] = a * b;
839 }
840 
841 /*  Looking for F' dot F'' == 0
842 
843     A = b - a
844     B = c - 2b + a
845     C = d - 3c + 3b - a
846 
847     F' = 3Ct^2 + 6Bt + 3A
848     F'' = 6Ct + 6B
849 
850     F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
851 */
SkFindCubicMaxCurvature(const SkPoint src[4],SkScalar tValues[3])852 int SkFindCubicMaxCurvature(const SkPoint src[4], SkScalar tValues[3]) {
853     SkScalar coeffX[4], coeffY[4];
854     int      i;
855 
856     formulate_F1DotF2(&src[0].fX, coeffX);
857     formulate_F1DotF2(&src[0].fY, coeffY);
858 
859     for (i = 0; i < 4; i++) {
860         coeffX[i] += coeffY[i];
861     }
862 
863     SkScalar    t[3];
864     int         count = solve_cubic_poly(coeffX, t);
865     int         maxCount = 0;
866 
867     // now remove extrema where the curvature is zero (mins)
868     // !!!! need a test for this !!!!
869     for (i = 0; i < count; i++) {
870         // if (not_min_curvature())
871         if (t[i] > 0 && t[i] < SK_Scalar1) {
872             tValues[maxCount++] = t[i];
873         }
874     }
875     return maxCount;
876 }
877 
SkChopCubicAtMaxCurvature(const SkPoint src[4],SkPoint dst[13],SkScalar tValues[3])878 int SkChopCubicAtMaxCurvature(const SkPoint src[4], SkPoint dst[13],
879                               SkScalar tValues[3]) {
880     SkScalar    t_storage[3];
881 
882     if (tValues == nullptr) {
883         tValues = t_storage;
884     }
885 
886     int count = SkFindCubicMaxCurvature(src, tValues);
887 
888     if (dst) {
889         if (count == 0) {
890             memcpy(dst, src, 4 * sizeof(SkPoint));
891         } else {
892             SkChopCubicAt(src, dst, tValues, count);
893         }
894     }
895     return count + 1;
896 }
897 
898 #include "../pathops/SkPathOpsCubic.h"
899 
900 typedef int (SkDCubic::*InterceptProc)(double intercept, double roots[3]) const;
901 
cubic_dchop_at_intercept(const SkPoint src[4],SkScalar intercept,SkPoint dst[7],InterceptProc method)902 static bool cubic_dchop_at_intercept(const SkPoint src[4], SkScalar intercept, SkPoint dst[7],
903                                      InterceptProc method) {
904     SkDCubic cubic;
905     double roots[3];
906     int count = (cubic.set(src).*method)(intercept, roots);
907     if (count > 0) {
908         SkDCubicPair pair = cubic.chopAt(roots[0]);
909         for (int i = 0; i < 7; ++i) {
910             dst[i] = pair.pts[i].asSkPoint();
911         }
912         return true;
913     }
914     return false;
915 }
916 
SkChopMonoCubicAtY(SkPoint src[4],SkScalar y,SkPoint dst[7])917 bool SkChopMonoCubicAtY(SkPoint src[4], SkScalar y, SkPoint dst[7]) {
918     return cubic_dchop_at_intercept(src, y, dst, &SkDCubic::horizontalIntersect);
919 }
920 
SkChopMonoCubicAtX(SkPoint src[4],SkScalar x,SkPoint dst[7])921 bool SkChopMonoCubicAtX(SkPoint src[4], SkScalar x, SkPoint dst[7]) {
922     return cubic_dchop_at_intercept(src, x, dst, &SkDCubic::verticalIntersect);
923 }
924 
925 ///////////////////////////////////////////////////////////////////////////////
926 //
927 // NURB representation for conics.  Helpful explanations at:
928 //
929 // http://citeseerx.ist.psu.edu/viewdoc/
930 //   download?doi=10.1.1.44.5740&rep=rep1&type=ps
931 // and
932 // http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/NURBS/RB-conics.html
933 //
934 // F = (A (1 - t)^2 + C t^2 + 2 B (1 - t) t w)
935 //     ------------------------------------------
936 //         ((1 - t)^2 + t^2 + 2 (1 - t) t w)
937 //
938 //   = {t^2 (P0 + P2 - 2 P1 w), t (-2 P0 + 2 P1 w), P0}
939 //     ------------------------------------------------
940 //             {t^2 (2 - 2 w), t (-2 + 2 w), 1}
941 //
942 
943 // F' = 2 (C t (1 + t (-1 + w)) - A (-1 + t) (t (-1 + w) - w) + B (1 - 2 t) w)
944 //
945 //  t^2 : (2 P0 - 2 P2 - 2 P0 w + 2 P2 w)
946 //  t^1 : (-2 P0 + 2 P2 + 4 P0 w - 4 P1 w)
947 //  t^0 : -2 P0 w + 2 P1 w
948 //
949 //  We disregard magnitude, so we can freely ignore the denominator of F', and
950 //  divide the numerator by 2
951 //
952 //    coeff[0] for t^2
953 //    coeff[1] for t^1
954 //    coeff[2] for t^0
955 //
conic_deriv_coeff(const SkScalar src[],SkScalar w,SkScalar coeff[3])956 static void conic_deriv_coeff(const SkScalar src[],
957                               SkScalar w,
958                               SkScalar coeff[3]) {
959     const SkScalar P20 = src[4] - src[0];
960     const SkScalar P10 = src[2] - src[0];
961     const SkScalar wP10 = w * P10;
962     coeff[0] = w * P20 - P20;
963     coeff[1] = P20 - 2 * wP10;
964     coeff[2] = wP10;
965 }
966 
conic_find_extrema(const SkScalar src[],SkScalar w,SkScalar * t)967 static bool conic_find_extrema(const SkScalar src[], SkScalar w, SkScalar* t) {
968     SkScalar coeff[3];
969     conic_deriv_coeff(src, w, coeff);
970 
971     SkScalar tValues[2];
972     int roots = SkFindUnitQuadRoots(coeff[0], coeff[1], coeff[2], tValues);
973     SkASSERT(0 == roots || 1 == roots);
974 
975     if (1 == roots) {
976         *t = tValues[0];
977         return true;
978     }
979     return false;
980 }
981 
982 struct SkP3D {
983     SkScalar fX, fY, fZ;
984 
setSkP3D985     void set(SkScalar x, SkScalar y, SkScalar z) {
986         fX = x; fY = y; fZ = z;
987     }
988 
projectDownSkP3D989     void projectDown(SkPoint* dst) const {
990         dst->set(fX / fZ, fY / fZ);
991     }
992 };
993 
994 // 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)995 static void p3d_interp(const SkScalar src[7], SkScalar dst[7], SkScalar t) {
996     SkScalar ab = SkScalarInterp(src[0], src[3], t);
997     SkScalar bc = SkScalarInterp(src[3], src[6], t);
998     dst[0] = ab;
999     dst[3] = SkScalarInterp(ab, bc, t);
1000     dst[6] = bc;
1001 }
1002 
ratquad_mapTo3D(const SkPoint src[3],SkScalar w,SkP3D dst[])1003 static void ratquad_mapTo3D(const SkPoint src[3], SkScalar w, SkP3D dst[]) {
1004     dst[0].set(src[0].fX * 1, src[0].fY * 1, 1);
1005     dst[1].set(src[1].fX * w, src[1].fY * w, w);
1006     dst[2].set(src[2].fX * 1, src[2].fY * 1, 1);
1007 }
1008 
1009 // return false if infinity or NaN is generated; caller must check
chopAt(SkScalar t,SkConic dst[2]) const1010 bool SkConic::chopAt(SkScalar t, SkConic dst[2]) const {
1011     SkP3D tmp[3], tmp2[3];
1012 
1013     ratquad_mapTo3D(fPts, fW, tmp);
1014 
1015     p3d_interp(&tmp[0].fX, &tmp2[0].fX, t);
1016     p3d_interp(&tmp[0].fY, &tmp2[0].fY, t);
1017     p3d_interp(&tmp[0].fZ, &tmp2[0].fZ, t);
1018 
1019     dst[0].fPts[0] = fPts[0];
1020     tmp2[0].projectDown(&dst[0].fPts[1]);
1021     tmp2[1].projectDown(&dst[0].fPts[2]); dst[1].fPts[0] = dst[0].fPts[2];
1022     tmp2[2].projectDown(&dst[1].fPts[1]);
1023     dst[1].fPts[2] = fPts[2];
1024 
1025     // to put in "standard form", where w0 and w2 are both 1, we compute the
1026     // new w1 as sqrt(w1*w1/w0*w2)
1027     // or
1028     // w1 /= sqrt(w0*w2)
1029     //
1030     // However, in our case, we know that for dst[0]:
1031     //     w0 == 1, and for dst[1], w2 == 1
1032     //
1033     SkScalar root = SkScalarSqrt(tmp2[1].fZ);
1034     dst[0].fW = tmp2[0].fZ / root;
1035     dst[1].fW = tmp2[2].fZ / root;
1036     SkASSERT(sizeof(dst[0]) == sizeof(SkScalar) * 7);
1037     SkASSERT(0 == offsetof(SkConic, fPts[0].fX));
1038     return SkScalarsAreFinite(&dst[0].fPts[0].fX, 7 * 2);
1039 }
1040 
chopAt(SkScalar t1,SkScalar t2,SkConic * dst) const1041 void SkConic::chopAt(SkScalar t1, SkScalar t2, SkConic* dst) const {
1042     if (0 == t1 || 1 == t2) {
1043         if (0 == t1 && 1 == t2) {
1044             *dst = *this;
1045             return;
1046         } else {
1047             SkConic pair[2];
1048             if (this->chopAt(t1 ? t1 : t2, pair)) {
1049                 *dst = pair[SkToBool(t1)];
1050                 return;
1051             }
1052         }
1053     }
1054     SkConicCoeff coeff(*this);
1055     Sk2s tt1(t1);
1056     Sk2s aXY = coeff.fNumer.eval(tt1);
1057     Sk2s aZZ = coeff.fDenom.eval(tt1);
1058     Sk2s midTT((t1 + t2) / 2);
1059     Sk2s dXY = coeff.fNumer.eval(midTT);
1060     Sk2s dZZ = coeff.fDenom.eval(midTT);
1061     Sk2s tt2(t2);
1062     Sk2s cXY = coeff.fNumer.eval(tt2);
1063     Sk2s cZZ = coeff.fDenom.eval(tt2);
1064     Sk2s bXY = times_2(dXY) - (aXY + cXY) * Sk2s(0.5f);
1065     Sk2s bZZ = times_2(dZZ) - (aZZ + cZZ) * Sk2s(0.5f);
1066     dst->fPts[0] = to_point(aXY / aZZ);
1067     dst->fPts[1] = to_point(bXY / bZZ);
1068     dst->fPts[2] = to_point(cXY / cZZ);
1069     Sk2s ww = bZZ / (aZZ * cZZ).sqrt();
1070     dst->fW = ww[0];
1071 }
1072 
evalAt(SkScalar t) const1073 SkPoint SkConic::evalAt(SkScalar t) const {
1074     return to_point(SkConicCoeff(*this).eval(t));
1075 }
1076 
evalTangentAt(SkScalar t) const1077 SkVector SkConic::evalTangentAt(SkScalar t) const {
1078     // The derivative equation returns a zero tangent vector when t is 0 or 1,
1079     // and the control point is equal to the end point.
1080     // In this case, use the conic endpoints to compute the tangent.
1081     if ((t == 0 && fPts[0] == fPts[1]) || (t == 1 && fPts[1] == fPts[2])) {
1082         return fPts[2] - fPts[0];
1083     }
1084     Sk2s p0 = from_point(fPts[0]);
1085     Sk2s p1 = from_point(fPts[1]);
1086     Sk2s p2 = from_point(fPts[2]);
1087     Sk2s ww(fW);
1088 
1089     Sk2s p20 = p2 - p0;
1090     Sk2s p10 = p1 - p0;
1091 
1092     Sk2s C = ww * p10;
1093     Sk2s A = ww * p20 - p20;
1094     Sk2s B = p20 - C - C;
1095 
1096     return to_vector(SkQuadCoeff(A, B, C).eval(t));
1097 }
1098 
evalAt(SkScalar t,SkPoint * pt,SkVector * tangent) const1099 void SkConic::evalAt(SkScalar t, SkPoint* pt, SkVector* tangent) const {
1100     SkASSERT(t >= 0 && t <= SK_Scalar1);
1101 
1102     if (pt) {
1103         *pt = this->evalAt(t);
1104     }
1105     if (tangent) {
1106         *tangent = this->evalTangentAt(t);
1107     }
1108 }
1109 
subdivide_w_value(SkScalar w)1110 static SkScalar subdivide_w_value(SkScalar w) {
1111     return SkScalarSqrt(SK_ScalarHalf + w * SK_ScalarHalf);
1112 }
1113 
chop(SkConic * SK_RESTRICT dst) const1114 void SkConic::chop(SkConic * SK_RESTRICT dst) const {
1115     Sk2s scale = Sk2s(SkScalarInvert(SK_Scalar1 + fW));
1116     SkScalar newW = subdivide_w_value(fW);
1117 
1118     Sk2s p0 = from_point(fPts[0]);
1119     Sk2s p1 = from_point(fPts[1]);
1120     Sk2s p2 = from_point(fPts[2]);
1121     Sk2s ww(fW);
1122 
1123     Sk2s wp1 = ww * p1;
1124     Sk2s m = (p0 + times_2(wp1) + p2) * scale * Sk2s(0.5f);
1125 
1126     dst[0].fPts[0] = fPts[0];
1127     dst[0].fPts[1] = to_point((p0 + wp1) * scale);
1128     dst[0].fPts[2] = dst[1].fPts[0] = to_point(m);
1129     dst[1].fPts[1] = to_point((wp1 + p2) * scale);
1130     dst[1].fPts[2] = fPts[2];
1131 
1132     dst[0].fW = dst[1].fW = newW;
1133 }
1134 
1135 /*
1136  *  "High order approximation of conic sections by quadratic splines"
1137  *      by Michael Floater, 1993
1138  */
1139 #define AS_QUAD_ERROR_SETUP                                         \
1140     SkScalar a = fW - 1;                                            \
1141     SkScalar k = a / (4 * (2 + a));                                 \
1142     SkScalar x = k * (fPts[0].fX - 2 * fPts[1].fX + fPts[2].fX);    \
1143     SkScalar y = k * (fPts[0].fY - 2 * fPts[1].fY + fPts[2].fY);
1144 
computeAsQuadError(SkVector * err) const1145 void SkConic::computeAsQuadError(SkVector* err) const {
1146     AS_QUAD_ERROR_SETUP
1147     err->set(x, y);
1148 }
1149 
asQuadTol(SkScalar tol) const1150 bool SkConic::asQuadTol(SkScalar tol) const {
1151     AS_QUAD_ERROR_SETUP
1152     return (x * x + y * y) <= tol * tol;
1153 }
1154 
1155 // Limit the number of suggested quads to approximate a conic
1156 #define kMaxConicToQuadPOW2     5
1157 
computeQuadPOW2(SkScalar tol) const1158 int SkConic::computeQuadPOW2(SkScalar tol) const {
1159     if (tol < 0 || !SkScalarIsFinite(tol)) {
1160         return 0;
1161     }
1162 
1163     AS_QUAD_ERROR_SETUP
1164 
1165     SkScalar error = SkScalarSqrt(x * x + y * y);
1166     int pow2;
1167     for (pow2 = 0; pow2 < kMaxConicToQuadPOW2; ++pow2) {
1168         if (error <= tol) {
1169             break;
1170         }
1171         error *= 0.25f;
1172     }
1173     // float version -- using ceil gives the same results as the above.
1174     if (false) {
1175         SkScalar err = SkScalarSqrt(x * x + y * y);
1176         if (err <= tol) {
1177             return 0;
1178         }
1179         SkScalar tol2 = tol * tol;
1180         if (tol2 == 0) {
1181             return kMaxConicToQuadPOW2;
1182         }
1183         SkScalar fpow2 = SkScalarLog2((x * x + y * y) / tol2) * 0.25f;
1184         int altPow2 = SkScalarCeilToInt(fpow2);
1185         if (altPow2 != pow2) {
1186             SkDebugf("pow2 %d altPow2 %d fbits %g err %g tol %g\n", pow2, altPow2, fpow2, err, tol);
1187         }
1188         pow2 = altPow2;
1189     }
1190     return pow2;
1191 }
1192 
1193 // This was originally developed and tested for pathops: see SkOpTypes.h
1194 // returns true if (a <= b <= c) || (a >= b >= c)
between(SkScalar a,SkScalar b,SkScalar c)1195 static bool between(SkScalar a, SkScalar b, SkScalar c) {
1196     return (a - b) * (c - b) <= 0;
1197 }
1198 
subdivide(const SkConic & src,SkPoint pts[],int level)1199 static SkPoint* subdivide(const SkConic& src, SkPoint pts[], int level) {
1200     SkASSERT(level >= 0);
1201 
1202     if (0 == level) {
1203         memcpy(pts, &src.fPts[1], 2 * sizeof(SkPoint));
1204         return pts + 2;
1205     } else {
1206         SkConic dst[2];
1207         src.chop(dst);
1208         const SkScalar startY = src.fPts[0].fY;
1209         const SkScalar endY = src.fPts[2].fY;
1210         if (between(startY, src.fPts[1].fY, endY)) {
1211             // If the input is monotonic and the output is not, the scan converter hangs.
1212             // Ensure that the chopped conics maintain their y-order.
1213             SkScalar midY = dst[0].fPts[2].fY;
1214             if (!between(startY, midY, endY)) {
1215                 // If the computed midpoint is outside the ends, move it to the closer one.
1216                 SkScalar closerY = SkTAbs(midY - startY) < SkTAbs(midY - endY) ? startY : endY;
1217                 dst[0].fPts[2].fY = dst[1].fPts[0].fY = closerY;
1218             }
1219             if (!between(startY, dst[0].fPts[1].fY, dst[0].fPts[2].fY)) {
1220                 // If the 1st control is not between the start and end, put it at the start.
1221                 // This also reduces the quad to a line.
1222                 dst[0].fPts[1].fY = startY;
1223             }
1224             if (!between(dst[1].fPts[0].fY, dst[1].fPts[1].fY, endY)) {
1225                 // If the 2nd control is not between the start and end, put it at the end.
1226                 // This also reduces the quad to a line.
1227                 dst[1].fPts[1].fY = endY;
1228             }
1229             // Verify that all five points are in order.
1230             SkASSERT(between(startY, dst[0].fPts[1].fY, dst[0].fPts[2].fY));
1231             SkASSERT(between(dst[0].fPts[1].fY, dst[0].fPts[2].fY, dst[1].fPts[1].fY));
1232             SkASSERT(between(dst[0].fPts[2].fY, dst[1].fPts[1].fY, endY));
1233         }
1234         --level;
1235         pts = subdivide(dst[0], pts, level);
1236         return subdivide(dst[1], pts, level);
1237     }
1238 }
1239 
chopIntoQuadsPOW2(SkPoint pts[],int pow2) const1240 int SkConic::chopIntoQuadsPOW2(SkPoint pts[], int pow2) const {
1241     SkASSERT(pow2 >= 0);
1242     *pts = fPts[0];
1243     SkDEBUGCODE(SkPoint* endPts);
1244     if (pow2 == kMaxConicToQuadPOW2) {  // If an extreme weight generates many quads ...
1245         SkConic dst[2];
1246         this->chop(dst);
1247         // check to see if the first chop generates a pair of lines
1248         if (dst[0].fPts[1].equalsWithinTolerance(dst[0].fPts[2])
1249                 && dst[1].fPts[0].equalsWithinTolerance(dst[1].fPts[1])) {
1250             pts[1] = pts[2] = pts[3] = dst[0].fPts[1];  // set ctrl == end to make lines
1251             pts[4] = dst[1].fPts[2];
1252             pow2 = 1;
1253             SkDEBUGCODE(endPts = &pts[5]);
1254             goto commonFinitePtCheck;
1255         }
1256     }
1257     SkDEBUGCODE(endPts = ) subdivide(*this, pts + 1, pow2);
1258 commonFinitePtCheck:
1259     const int quadCount = 1 << pow2;
1260     const int ptCount = 2 * quadCount + 1;
1261     SkASSERT(endPts - pts == ptCount);
1262     if (!SkPointsAreFinite(pts, ptCount)) {
1263         // if we generated a non-finite, pin ourselves to the middle of the hull,
1264         // as our first and last are already on the first/last pts of the hull.
1265         for (int i = 1; i < ptCount - 1; ++i) {
1266             pts[i] = fPts[1];
1267         }
1268     }
1269     return 1 << pow2;
1270 }
1271 
findXExtrema(SkScalar * t) const1272 bool SkConic::findXExtrema(SkScalar* t) const {
1273     return conic_find_extrema(&fPts[0].fX, fW, t);
1274 }
1275 
findYExtrema(SkScalar * t) const1276 bool SkConic::findYExtrema(SkScalar* t) const {
1277     return conic_find_extrema(&fPts[0].fY, fW, t);
1278 }
1279 
chopAtXExtrema(SkConic dst[2]) const1280 bool SkConic::chopAtXExtrema(SkConic dst[2]) const {
1281     SkScalar t;
1282     if (this->findXExtrema(&t)) {
1283         if (!this->chopAt(t, dst)) {
1284             // if chop can't return finite values, don't chop
1285             return false;
1286         }
1287         // now clean-up the middle, since we know t was meant to be at
1288         // an X-extrema
1289         SkScalar value = dst[0].fPts[2].fX;
1290         dst[0].fPts[1].fX = value;
1291         dst[1].fPts[0].fX = value;
1292         dst[1].fPts[1].fX = value;
1293         return true;
1294     }
1295     return false;
1296 }
1297 
chopAtYExtrema(SkConic dst[2]) const1298 bool SkConic::chopAtYExtrema(SkConic dst[2]) const {
1299     SkScalar t;
1300     if (this->findYExtrema(&t)) {
1301         if (!this->chopAt(t, dst)) {
1302             // if chop can't return finite values, don't chop
1303             return false;
1304         }
1305         // now clean-up the middle, since we know t was meant to be at
1306         // an Y-extrema
1307         SkScalar value = dst[0].fPts[2].fY;
1308         dst[0].fPts[1].fY = value;
1309         dst[1].fPts[0].fY = value;
1310         dst[1].fPts[1].fY = value;
1311         return true;
1312     }
1313     return false;
1314 }
1315 
computeTightBounds(SkRect * bounds) const1316 void SkConic::computeTightBounds(SkRect* bounds) const {
1317     SkPoint pts[4];
1318     pts[0] = fPts[0];
1319     pts[1] = fPts[2];
1320     int count = 2;
1321 
1322     SkScalar t;
1323     if (this->findXExtrema(&t)) {
1324         this->evalAt(t, &pts[count++]);
1325     }
1326     if (this->findYExtrema(&t)) {
1327         this->evalAt(t, &pts[count++]);
1328     }
1329     bounds->set(pts, count);
1330 }
1331 
computeFastBounds(SkRect * bounds) const1332 void SkConic::computeFastBounds(SkRect* bounds) const {
1333     bounds->set(fPts, 3);
1334 }
1335 
1336 #if 0  // unimplemented
1337 bool SkConic::findMaxCurvature(SkScalar* t) const {
1338     // TODO: Implement me
1339     return false;
1340 }
1341 #endif
1342 
TransformW(const SkPoint pts[],SkScalar w,const SkMatrix & matrix)1343 SkScalar SkConic::TransformW(const SkPoint pts[], SkScalar w,
1344                              const SkMatrix& matrix) {
1345     if (!matrix.hasPerspective()) {
1346         return w;
1347     }
1348 
1349     SkP3D src[3], dst[3];
1350 
1351     ratquad_mapTo3D(pts, w, src);
1352 
1353     matrix.mapHomogeneousPoints(&dst[0].fX, &src[0].fX, 3);
1354 
1355     // w' = sqrt(w1*w1/w0*w2)
1356     SkScalar w0 = dst[0].fZ;
1357     SkScalar w1 = dst[1].fZ;
1358     SkScalar w2 = dst[2].fZ;
1359     w = SkScalarSqrt((w1 * w1) / (w0 * w2));
1360     return w;
1361 }
1362 
BuildUnitArc(const SkVector & uStart,const SkVector & uStop,SkRotationDirection dir,const SkMatrix * userMatrix,SkConic dst[kMaxConicsForArc])1363 int SkConic::BuildUnitArc(const SkVector& uStart, const SkVector& uStop, SkRotationDirection dir,
1364                           const SkMatrix* userMatrix, SkConic dst[kMaxConicsForArc]) {
1365     // rotate by x,y so that uStart is (1.0)
1366     SkScalar x = SkPoint::DotProduct(uStart, uStop);
1367     SkScalar y = SkPoint::CrossProduct(uStart, uStop);
1368 
1369     SkScalar absY = SkScalarAbs(y);
1370 
1371     // check for (effectively) coincident vectors
1372     // this can happen if our angle is nearly 0 or nearly 180 (y == 0)
1373     // ... we use the dot-prod to distinguish between 0 and 180 (x > 0)
1374     if (absY <= SK_ScalarNearlyZero && x > 0 && ((y >= 0 && kCW_SkRotationDirection == dir) ||
1375                                                  (y <= 0 && kCCW_SkRotationDirection == dir))) {
1376         return 0;
1377     }
1378 
1379     if (dir == kCCW_SkRotationDirection) {
1380         y = -y;
1381     }
1382 
1383     // We decide to use 1-conic per quadrant of a circle. What quadrant does [xy] lie in?
1384     //      0 == [0  .. 90)
1385     //      1 == [90 ..180)
1386     //      2 == [180..270)
1387     //      3 == [270..360)
1388     //
1389     int quadrant = 0;
1390     if (0 == y) {
1391         quadrant = 2;        // 180
1392         SkASSERT(SkScalarAbs(x + SK_Scalar1) <= SK_ScalarNearlyZero);
1393     } else if (0 == x) {
1394         SkASSERT(absY - SK_Scalar1 <= SK_ScalarNearlyZero);
1395         quadrant = y > 0 ? 1 : 3; // 90 : 270
1396     } else {
1397         if (y < 0) {
1398             quadrant += 2;
1399         }
1400         if ((x < 0) != (y < 0)) {
1401             quadrant += 1;
1402         }
1403     }
1404 
1405     const SkPoint quadrantPts[] = {
1406         { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 }, { -1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 }
1407     };
1408     const SkScalar quadrantWeight = SK_ScalarRoot2Over2;
1409 
1410     int conicCount = quadrant;
1411     for (int i = 0; i < conicCount; ++i) {
1412         dst[i].set(&quadrantPts[i * 2], quadrantWeight);
1413     }
1414 
1415     // Now compute any remaing (sub-90-degree) arc for the last conic
1416     const SkPoint finalP = { x, y };
1417     const SkPoint& lastQ = quadrantPts[quadrant * 2];  // will already be a unit-vector
1418     const SkScalar dot = SkVector::DotProduct(lastQ, finalP);
1419     SkASSERT(0 <= dot && dot <= SK_Scalar1 + SK_ScalarNearlyZero);
1420 
1421     if (dot < 1) {
1422         SkVector offCurve = { lastQ.x() + x, lastQ.y() + y };
1423         // compute the bisector vector, and then rescale to be the off-curve point.
1424         // we compute its length from cos(theta/2) = length / 1, using half-angle identity we get
1425         // length = sqrt(2 / (1 + cos(theta)). We already have cos() when to computed the dot.
1426         // This is nice, since our computed weight is cos(theta/2) as well!
1427         //
1428         const SkScalar cosThetaOver2 = SkScalarSqrt((1 + dot) / 2);
1429         offCurve.setLength(SkScalarInvert(cosThetaOver2));
1430         if (!lastQ.equalsWithinTolerance(offCurve)) {
1431             dst[conicCount].set(lastQ, offCurve, finalP, cosThetaOver2);
1432             conicCount += 1;
1433         }
1434     }
1435 
1436     // now handle counter-clockwise and the initial unitStart rotation
1437     SkMatrix    matrix;
1438     matrix.setSinCos(uStart.fY, uStart.fX);
1439     if (dir == kCCW_SkRotationDirection) {
1440         matrix.preScale(SK_Scalar1, -SK_Scalar1);
1441     }
1442     if (userMatrix) {
1443         matrix.postConcat(*userMatrix);
1444     }
1445     for (int i = 0; i < conicCount; ++i) {
1446         matrix.mapPoints(dst[i].fPts, 3);
1447     }
1448     return conicCount;
1449 }
1450