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