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