• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017 Google Inc.
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 "src/utils/SkPolyUtils.h"
9 
10 #include <limits>
11 
12 #include "include/private/SkNx.h"
13 #include "include/private/SkTArray.h"
14 #include "include/private/SkTemplates.h"
15 #include "src/core/SkPointPriv.h"
16 #include "src/core/SkTDPQueue.h"
17 #include "src/core/SkTInternalLList.h"
18 
19 //////////////////////////////////////////////////////////////////////////////////
20 // Helper data structures and functions
21 
22 struct OffsetSegment {
23     SkPoint fP0;
24     SkVector fV;
25 };
26 
27 constexpr SkScalar kCrossTolerance = SK_ScalarNearlyZero * SK_ScalarNearlyZero;
28 
29 // Computes perpDot for point p compared to segment defined by origin p0 and vector v.
30 // A positive value means the point is to the left of the segment,
31 // negative is to the right, 0 is collinear.
compute_side(const SkPoint & p0,const SkVector & v,const SkPoint & p)32 static int compute_side(const SkPoint& p0, const SkVector& v, const SkPoint& p) {
33     SkVector w = p - p0;
34     SkScalar perpDot = v.cross(w);
35     if (!SkScalarNearlyZero(perpDot, kCrossTolerance)) {
36         return ((perpDot > 0) ? 1 : -1);
37     }
38 
39     return 0;
40 }
41 
42 // Returns 1 for cw, -1 for ccw and 0 if zero signed area (either degenerate or self-intersecting)
SkGetPolygonWinding(const SkPoint * polygonVerts,int polygonSize)43 int SkGetPolygonWinding(const SkPoint* polygonVerts, int polygonSize) {
44     if (polygonSize < 3) {
45         return 0;
46     }
47 
48     // compute area and use sign to determine winding
49     SkScalar quadArea = 0;
50     SkVector v0 = polygonVerts[1] - polygonVerts[0];
51     for (int curr = 2; curr < polygonSize; ++curr) {
52         SkVector v1 = polygonVerts[curr] - polygonVerts[0];
53         quadArea += v0.cross(v1);
54         v0 = v1;
55     }
56     if (SkScalarNearlyZero(quadArea, kCrossTolerance)) {
57         return 0;
58     }
59     // 1 == ccw, -1 == cw
60     return (quadArea > 0) ? 1 : -1;
61 }
62 
63 // Compute difference vector to offset p0-p1 'offset' units in direction specified by 'side'
compute_offset_vector(const SkPoint & p0,const SkPoint & p1,SkScalar offset,int side,SkPoint * vector)64 bool compute_offset_vector(const SkPoint& p0, const SkPoint& p1, SkScalar offset, int side,
65                            SkPoint* vector) {
66     SkASSERT(side == -1 || side == 1);
67     // if distances are equal, can just outset by the perpendicular
68     SkVector perp = SkVector::Make(p0.fY - p1.fY, p1.fX - p0.fX);
69     if (!perp.setLength(offset*side)) {
70         return false;
71     }
72     *vector = perp;
73     return true;
74 }
75 
76 // check interval to see if intersection is in segment
outside_interval(SkScalar numer,SkScalar denom,bool denomPositive)77 static inline bool outside_interval(SkScalar numer, SkScalar denom, bool denomPositive) {
78     return (denomPositive && (numer < 0 || numer > denom)) ||
79            (!denomPositive && (numer > 0 || numer < denom));
80 }
81 
82 // special zero-length test when we're using vdotv as a denominator
zero_length(const SkPoint & v,SkScalar vdotv)83 static inline bool zero_length(const SkPoint& v, SkScalar vdotv) {
84     return !(SkScalarsAreFinite(v.fX, v.fY) && vdotv);
85 }
86 
87 // Compute the intersection 'p' between segments s0 and s1, if any.
88 // 's' is the parametric value for the intersection along 's0' & 't' is the same for 's1'.
89 // Returns false if there is no intersection.
90 // If the length squared of a segment is 0, then we treat the segment as degenerate
91 // and use only the first endpoint for tests.
compute_intersection(const OffsetSegment & s0,const OffsetSegment & s1,SkPoint * p,SkScalar * s,SkScalar * t)92 static bool compute_intersection(const OffsetSegment& s0, const OffsetSegment& s1,
93                                  SkPoint* p, SkScalar* s, SkScalar* t) {
94     const SkVector& v0 = s0.fV;
95     const SkVector& v1 = s1.fV;
96     SkVector w = s1.fP0 - s0.fP0;
97     SkScalar denom = v0.cross(v1);
98     bool denomPositive = (denom > 0);
99     SkScalar sNumer, tNumer;
100     if (SkScalarNearlyZero(denom, kCrossTolerance)) {
101         // segments are parallel, but not collinear
102         if (!SkScalarNearlyZero(w.cross(v0), kCrossTolerance) ||
103             !SkScalarNearlyZero(w.cross(v1), kCrossTolerance)) {
104             return false;
105         }
106 
107         // Check for zero-length segments
108         SkScalar v0dotv0 = v0.dot(v0);
109         if (zero_length(v0, v0dotv0)) {
110             // Both are zero-length
111             SkScalar v1dotv1 = v1.dot(v1);
112             if (zero_length(v1, v1dotv1)) {
113                 // Check if they're the same point
114                 if (!SkPointPriv::CanNormalize(w.fX, w.fY)) {
115                     *p = s0.fP0;
116                     *s = 0;
117                     *t = 0;
118                     return true;
119                 } else {
120                     // Intersection is indeterminate
121                     return false;
122                 }
123             }
124             // Otherwise project segment0's origin onto segment1
125             tNumer = v1.dot(-w);
126             denom = v1dotv1;
127             if (outside_interval(tNumer, denom, true)) {
128                 return false;
129             }
130             sNumer = 0;
131         } else {
132             // Project segment1's endpoints onto segment0
133             sNumer = v0.dot(w);
134             denom = v0dotv0;
135             tNumer = 0;
136             if (outside_interval(sNumer, denom, true)) {
137                 // The first endpoint doesn't lie on segment0
138                 // If segment1 is degenerate, then there's no collision
139                 SkScalar v1dotv1 = v1.dot(v1);
140                 if (zero_length(v1, v1dotv1)) {
141                     return false;
142                 }
143 
144                 // Otherwise try the other one
145                 SkScalar oldSNumer = sNumer;
146                 sNumer = v0.dot(w + v1);
147                 tNumer = denom;
148                 if (outside_interval(sNumer, denom, true)) {
149                     // it's possible that segment1's interval surrounds segment0
150                     // this is false if params have the same signs, and in that case no collision
151                     if (sNumer*oldSNumer > 0) {
152                         return false;
153                     }
154                     // otherwise project segment0's endpoint onto segment1 instead
155                     sNumer = 0;
156                     tNumer = v1.dot(-w);
157                     denom = v1dotv1;
158                 }
159             }
160         }
161     } else {
162         sNumer = w.cross(v1);
163         if (outside_interval(sNumer, denom, denomPositive)) {
164             return false;
165         }
166         tNumer = w.cross(v0);
167         if (outside_interval(tNumer, denom, denomPositive)) {
168             return false;
169         }
170     }
171 
172     SkScalar localS = sNumer/denom;
173     SkScalar localT = tNumer/denom;
174 
175     *p = s0.fP0 + v0*localS;
176     *s = localS;
177     *t = localT;
178 
179     return true;
180 }
181 
SkIsConvexPolygon(const SkPoint * polygonVerts,int polygonSize)182 bool SkIsConvexPolygon(const SkPoint* polygonVerts, int polygonSize) {
183     if (polygonSize < 3) {
184         return false;
185     }
186 
187     SkScalar lastArea = 0;
188     SkScalar lastPerpDot = 0;
189 
190     int prevIndex = polygonSize - 1;
191     int currIndex = 0;
192     int nextIndex = 1;
193     SkPoint origin = polygonVerts[0];
194     SkVector v0 = polygonVerts[currIndex] - polygonVerts[prevIndex];
195     SkVector v1 = polygonVerts[nextIndex] - polygonVerts[currIndex];
196     SkVector w0 = polygonVerts[currIndex] - origin;
197     SkVector w1 = polygonVerts[nextIndex] - origin;
198     for (int i = 0; i < polygonSize; ++i) {
199         if (!polygonVerts[i].isFinite()) {
200             return false;
201         }
202 
203         // Check that winding direction is always the same (otherwise we have a reflex vertex)
204         SkScalar perpDot = v0.cross(v1);
205         if (lastPerpDot*perpDot < 0) {
206             return false;
207         }
208         if (0 != perpDot) {
209             lastPerpDot = perpDot;
210         }
211 
212         // If the signed area ever flips it's concave
213         // TODO: see if we can verify convexity only with signed area
214         SkScalar quadArea = w0.cross(w1);
215         if (quadArea*lastArea < 0) {
216             return false;
217         }
218         if (0 != quadArea) {
219             lastArea = quadArea;
220         }
221 
222         prevIndex = currIndex;
223         currIndex = nextIndex;
224         nextIndex = (currIndex + 1) % polygonSize;
225         v0 = v1;
226         v1 = polygonVerts[nextIndex] - polygonVerts[currIndex];
227         w0 = w1;
228         w1 = polygonVerts[nextIndex] - origin;
229     }
230 
231     return true;
232 }
233 
234 struct OffsetEdge {
235     OffsetEdge*   fPrev;
236     OffsetEdge*   fNext;
237     OffsetSegment fOffset;
238     SkPoint       fIntersection;
239     SkScalar      fTValue;
240     uint16_t      fIndex;
241     uint16_t      fEnd;
242 
initOffsetEdge243     void init(uint16_t start = 0, uint16_t end = 0) {
244         fIntersection = fOffset.fP0;
245         fTValue = SK_ScalarMin;
246         fIndex = start;
247         fEnd = end;
248     }
249 
250     // special intersection check that looks for endpoint intersection
checkIntersectionOffsetEdge251     bool checkIntersection(const OffsetEdge* that,
252                            SkPoint* p, SkScalar* s, SkScalar* t) {
253         if (this->fEnd == that->fIndex) {
254             SkPoint p1 = this->fOffset.fP0 + this->fOffset.fV;
255             if (SkPointPriv::EqualsWithinTolerance(p1, that->fOffset.fP0)) {
256                 *p = p1;
257                 *s = SK_Scalar1;
258                 *t = 0;
259                 return true;
260             }
261         }
262 
263         return compute_intersection(this->fOffset, that->fOffset, p, s, t);
264     }
265 
266     // computes the line intersection and then the "distance" from that to this
267     // this is really a signed squared distance, where negative means that
268     // the intersection lies inside this->fOffset
computeCrossingDistanceOffsetEdge269     SkScalar computeCrossingDistance(const OffsetEdge* that) {
270         const OffsetSegment& s0 = this->fOffset;
271         const OffsetSegment& s1 = that->fOffset;
272         const SkVector& v0 = s0.fV;
273         const SkVector& v1 = s1.fV;
274 
275         SkScalar denom = v0.cross(v1);
276         if (SkScalarNearlyZero(denom, kCrossTolerance)) {
277             // segments are parallel
278             return SK_ScalarMax;
279         }
280 
281         SkVector w = s1.fP0 - s0.fP0;
282         SkScalar localS = w.cross(v1) / denom;
283         if (localS < 0) {
284             localS = -localS;
285         } else {
286             localS -= SK_Scalar1;
287         }
288 
289         localS *= SkScalarAbs(localS);
290         localS *= v0.dot(v0);
291 
292         return localS;
293     }
294 
295 };
296 
remove_node(const OffsetEdge * node,OffsetEdge ** head)297 static void remove_node(const OffsetEdge* node, OffsetEdge** head) {
298     // remove from linked list
299     node->fPrev->fNext = node->fNext;
300     node->fNext->fPrev = node->fPrev;
301     if (node == *head) {
302         *head = (node->fNext == node) ? nullptr : node->fNext;
303     }
304 }
305 
306 //////////////////////////////////////////////////////////////////////////////////
307 
308 // The objective here is to inset all of the edges by the given distance, and then
309 // remove any invalid inset edges by detecting right-hand turns. In a ccw polygon,
310 // we should only be making left-hand turns (for cw polygons, we use the winding
311 // parameter to reverse this). We detect this by checking whether the second intersection
312 // on an edge is closer to its tail than the first one.
313 //
314 // We might also have the case that there is no intersection between two neighboring inset edges.
315 // In this case, one edge will lie to the right of the other and should be discarded along with
316 // its previous intersection (if any).
317 //
318 // Note: the assumption is that inputPolygon is convex and has no coincident points.
319 //
SkInsetConvexPolygon(const SkPoint * inputPolygonVerts,int inputPolygonSize,SkScalar inset,SkTDArray<SkPoint> * insetPolygon)320 bool SkInsetConvexPolygon(const SkPoint* inputPolygonVerts, int inputPolygonSize,
321                           SkScalar inset, SkTDArray<SkPoint>* insetPolygon) {
322     if (inputPolygonSize < 3) {
323         return false;
324     }
325 
326     // restrict this to match other routines
327     // practically we don't want anything bigger than this anyway
328     if (inputPolygonSize > std::numeric_limits<uint16_t>::max()) {
329         return false;
330     }
331 
332     // can't inset by a negative or non-finite amount
333     if (inset < -SK_ScalarNearlyZero || !SkScalarIsFinite(inset)) {
334         return false;
335     }
336 
337     // insetting close to zero just returns the original poly
338     if (inset <= SK_ScalarNearlyZero) {
339         for (int i = 0; i < inputPolygonSize; ++i) {
340             *insetPolygon->push() = inputPolygonVerts[i];
341         }
342         return true;
343     }
344 
345     // get winding direction
346     int winding = SkGetPolygonWinding(inputPolygonVerts, inputPolygonSize);
347     if (0 == winding) {
348         return false;
349     }
350 
351     // set up
352     SkAutoSTMalloc<64, OffsetEdge> edgeData(inputPolygonSize);
353     int prev = inputPolygonSize - 1;
354     for (int curr = 0; curr < inputPolygonSize; prev = curr, ++curr) {
355         int next = (curr + 1) % inputPolygonSize;
356         if (!inputPolygonVerts[curr].isFinite()) {
357             return false;
358         }
359         // check for convexity just to be sure
360         if (compute_side(inputPolygonVerts[prev], inputPolygonVerts[curr] - inputPolygonVerts[prev],
361                          inputPolygonVerts[next])*winding < 0) {
362             return false;
363         }
364         SkVector v = inputPolygonVerts[next] - inputPolygonVerts[curr];
365         SkVector perp = SkVector::Make(-v.fY, v.fX);
366         perp.setLength(inset*winding);
367         edgeData[curr].fPrev = &edgeData[prev];
368         edgeData[curr].fNext = &edgeData[next];
369         edgeData[curr].fOffset.fP0 = inputPolygonVerts[curr] + perp;
370         edgeData[curr].fOffset.fV = v;
371         edgeData[curr].init();
372     }
373 
374     OffsetEdge* head = &edgeData[0];
375     OffsetEdge* currEdge = head;
376     OffsetEdge* prevEdge = currEdge->fPrev;
377     int insetVertexCount = inputPolygonSize;
378     unsigned int iterations = 0;
379     unsigned int maxIterations = inputPolygonSize * inputPolygonSize;
380     while (head && prevEdge != currEdge) {
381         ++iterations;
382         // we should check each edge against each other edge at most once
383         if (iterations > maxIterations) {
384             return false;
385         }
386 
387         SkScalar s, t;
388         SkPoint intersection;
389         if (compute_intersection(prevEdge->fOffset, currEdge->fOffset,
390                                  &intersection, &s, &t)) {
391             // if new intersection is further back on previous inset from the prior intersection
392             if (s < prevEdge->fTValue) {
393                 // no point in considering this one again
394                 remove_node(prevEdge, &head);
395                 --insetVertexCount;
396                 // go back one segment
397                 prevEdge = prevEdge->fPrev;
398             // we've already considered this intersection, we're done
399             } else if (currEdge->fTValue > SK_ScalarMin &&
400                        SkPointPriv::EqualsWithinTolerance(intersection,
401                                                           currEdge->fIntersection,
402                                                           1.0e-6f)) {
403                 break;
404             } else {
405                 // add intersection
406                 currEdge->fIntersection = intersection;
407                 currEdge->fTValue = t;
408 
409                 // go to next segment
410                 prevEdge = currEdge;
411                 currEdge = currEdge->fNext;
412             }
413         } else {
414             // if prev to right side of curr
415             int side = winding*compute_side(currEdge->fOffset.fP0,
416                                             currEdge->fOffset.fV,
417                                             prevEdge->fOffset.fP0);
418             if (side < 0 &&
419                 side == winding*compute_side(currEdge->fOffset.fP0,
420                                              currEdge->fOffset.fV,
421                                              prevEdge->fOffset.fP0 + prevEdge->fOffset.fV)) {
422                 // no point in considering this one again
423                 remove_node(prevEdge, &head);
424                 --insetVertexCount;
425                 // go back one segment
426                 prevEdge = prevEdge->fPrev;
427             } else {
428                 // move to next segment
429                 remove_node(currEdge, &head);
430                 --insetVertexCount;
431                 currEdge = currEdge->fNext;
432             }
433         }
434     }
435 
436     // store all the valid intersections that aren't nearly coincident
437     // TODO: look at the main algorithm and see if we can detect these better
438     insetPolygon->reset();
439     if (!head) {
440         return false;
441     }
442 
443     static constexpr SkScalar kCleanupTolerance = 0.01f;
444     if (insetVertexCount >= 0) {
445         insetPolygon->setReserve(insetVertexCount);
446     }
447     int currIndex = 0;
448     *insetPolygon->push() = head->fIntersection;
449     currEdge = head->fNext;
450     while (currEdge != head) {
451         if (!SkPointPriv::EqualsWithinTolerance(currEdge->fIntersection,
452                                                 (*insetPolygon)[currIndex],
453                                                 kCleanupTolerance)) {
454             *insetPolygon->push() = currEdge->fIntersection;
455             currIndex++;
456         }
457         currEdge = currEdge->fNext;
458     }
459     // make sure the first and last points aren't coincident
460     if (currIndex >= 1 &&
461         SkPointPriv::EqualsWithinTolerance((*insetPolygon)[0], (*insetPolygon)[currIndex],
462                                             kCleanupTolerance)) {
463         insetPolygon->pop();
464     }
465 
466     return SkIsConvexPolygon(insetPolygon->begin(), insetPolygon->count());
467 }
468 
469 ///////////////////////////////////////////////////////////////////////////////////////////
470 
471 // compute the number of points needed for a circular join when offsetting a reflex vertex
SkComputeRadialSteps(const SkVector & v1,const SkVector & v2,SkScalar offset,SkScalar * rotSin,SkScalar * rotCos,int * n)472 bool SkComputeRadialSteps(const SkVector& v1, const SkVector& v2, SkScalar offset,
473                           SkScalar* rotSin, SkScalar* rotCos, int* n) {
474     const SkScalar kRecipPixelsPerArcSegment = 0.25f;
475 
476     SkScalar rCos = v1.dot(v2);
477     if (!SkScalarIsFinite(rCos)) {
478         return false;
479     }
480     SkScalar rSin = v1.cross(v2);
481     if (!SkScalarIsFinite(rSin)) {
482         return false;
483     }
484     SkScalar theta = SkScalarATan2(rSin, rCos);
485 
486     SkScalar floatSteps = SkScalarAbs(offset*theta*kRecipPixelsPerArcSegment);
487     // limit the number of steps to at most max uint16_t (that's all we can index)
488     // knock one value off the top to account for rounding
489     if (floatSteps >= std::numeric_limits<uint16_t>::max()) {
490         return false;
491     }
492     int steps = SkScalarRoundToInt(floatSteps);
493 
494     SkScalar dTheta = steps > 0 ? theta / steps : 0;
495     *rotSin = SkScalarSin(dTheta);
496     *rotCos = SkScalarCos(dTheta);
497     // Our offset may be so large that we end up with a tiny dTheta, in which case we
498     // lose precision when computing rotSin and rotCos.
499     if (steps > 0 && (*rotSin == 0 || *rotCos == 1)) {
500         return false;
501     }
502     *n = steps;
503     return true;
504 }
505 
506 ///////////////////////////////////////////////////////////////////////////////////////////
507 
508 // a point is "left" to another if its x-coord is less, or if equal, its y-coord is greater
left(const SkPoint & p0,const SkPoint & p1)509 static bool left(const SkPoint& p0, const SkPoint& p1) {
510     return p0.fX < p1.fX || (!(p0.fX > p1.fX) && p0.fY > p1.fY);
511 }
512 
513 // a point is "right" to another if its x-coord is greater, or if equal, its y-coord is less
right(const SkPoint & p0,const SkPoint & p1)514 static bool right(const SkPoint& p0, const SkPoint& p1) {
515     return p0.fX > p1.fX || (!(p0.fX < p1.fX) && p0.fY < p1.fY);
516 }
517 
518 struct Vertex {
LeftVertex519     static bool Left(const Vertex& qv0, const Vertex& qv1) {
520         return left(qv0.fPosition, qv1.fPosition);
521     }
522 
523     // packed to fit into 16 bytes (one cache line)
524     SkPoint  fPosition;
525     uint16_t fIndex;       // index in unsorted polygon
526     uint16_t fPrevIndex;   // indices for previous and next vertex in unsorted polygon
527     uint16_t fNextIndex;
528     uint16_t fFlags;
529 };
530 
531 enum VertexFlags {
532     kPrevLeft_VertexFlag = 0x1,
533     kNextLeft_VertexFlag = 0x2,
534 };
535 
536 struct ActiveEdge {
ActiveEdgeActiveEdge537     ActiveEdge() : fChild{ nullptr, nullptr }, fAbove(nullptr), fBelow(nullptr), fRed(false) {}
ActiveEdgeActiveEdge538     ActiveEdge(const SkPoint& p0, const SkVector& v, uint16_t index0, uint16_t index1)
539         : fSegment({ p0, v })
540         , fIndex0(index0)
541         , fIndex1(index1)
542         , fAbove(nullptr)
543         , fBelow(nullptr)
544         , fRed(true) {
545         fChild[0] = nullptr;
546         fChild[1] = nullptr;
547     }
548 
549     // Returns true if "this" is above "that", assuming this->p0 is to the left of that->p0
550     // This is only used to verify the edgelist -- the actual test for insertion/deletion is much
551     // simpler because we can make certain assumptions then.
aboveIfLeftActiveEdge552     bool aboveIfLeft(const ActiveEdge* that) const {
553         const SkPoint& p0 = this->fSegment.fP0;
554         const SkPoint& q0 = that->fSegment.fP0;
555         SkASSERT(p0.fX <= q0.fX);
556         SkVector d = q0 - p0;
557         const SkVector& v = this->fSegment.fV;
558         const SkVector& w = that->fSegment.fV;
559         // The idea here is that if the vector between the origins of the two segments (d)
560         // rotates counterclockwise up to the vector representing the "this" segment (v),
561         // then we know that "this" is above "that". If the result is clockwise we say it's below.
562         if (this->fIndex0 != that->fIndex0) {
563             SkScalar cross = d.cross(v);
564             if (cross > kCrossTolerance) {
565                 return true;
566             } else if (cross < -kCrossTolerance) {
567                 return false;
568             }
569         } else if (this->fIndex1 == that->fIndex1) {
570             return false;
571         }
572         // At this point either the two origins are nearly equal or the origin of "that"
573         // lies on dv. So then we try the same for the vector from the tail of "this"
574         // to the head of "that". Again, ccw means "this" is above "that".
575         // d = that.P1 - this.P0
576         //   = that.fP0 + that.fV - this.fP0
577         //   = that.fP0 - this.fP0 + that.fV
578         //   = old_d + that.fV
579         d += w;
580         SkScalar cross = d.cross(v);
581         if (cross > kCrossTolerance) {
582             return true;
583         } else if (cross < -kCrossTolerance) {
584             return false;
585         }
586         // If the previous check fails, the two segments are nearly collinear
587         // First check y-coord of first endpoints
588         if (p0.fX < q0.fX) {
589             return (p0.fY >= q0.fY);
590         } else if (p0.fY > q0.fY) {
591             return true;
592         } else if (p0.fY < q0.fY) {
593             return false;
594         }
595         // The first endpoints are the same, so check the other endpoint
596         SkPoint p1 = p0 + v;
597         SkPoint q1 = q0 + w;
598         if (p1.fX < q1.fX) {
599             return (p1.fY >= q1.fY);
600         } else {
601             return (p1.fY > q1.fY);
602         }
603     }
604 
605     // same as leftAndAbove(), but generalized
aboveActiveEdge606     bool above(const ActiveEdge* that) const {
607         const SkPoint& p0 = this->fSegment.fP0;
608         const SkPoint& q0 = that->fSegment.fP0;
609         if (right(p0, q0)) {
610             return !that->aboveIfLeft(this);
611         } else {
612             return this->aboveIfLeft(that);
613         }
614     }
615 
intersectActiveEdge616     bool intersect(const SkPoint& q0, const SkVector& w, uint16_t index0, uint16_t index1) const {
617         // check first to see if these edges are neighbors in the polygon
618         if (this->fIndex0 == index0 || this->fIndex1 == index0 ||
619             this->fIndex0 == index1 || this->fIndex1 == index1) {
620             return false;
621         }
622 
623         // We don't need the exact intersection point so we can do a simpler test here.
624         const SkPoint& p0 = this->fSegment.fP0;
625         const SkVector& v = this->fSegment.fV;
626         SkPoint p1 = p0 + v;
627         SkPoint q1 = q0 + w;
628 
629         // We assume some x-overlap due to how the edgelist works
630         // This allows us to simplify our test
631         // We need some slop here because storing the vector and recomputing the second endpoint
632         // doesn't necessary give us the original result in floating point.
633         // TODO: Store vector as double? Store endpoint as well?
634         SkASSERT(q0.fX <= p1.fX + SK_ScalarNearlyZero);
635 
636         // if each segment straddles the other (i.e., the endpoints have different sides)
637         // then they intersect
638         bool result;
639         if (p0.fX < q0.fX) {
640             if (q1.fX < p1.fX) {
641                 result = (compute_side(p0, v, q0)*compute_side(p0, v, q1) < 0);
642             } else {
643                 result = (compute_side(p0, v, q0)*compute_side(q0, w, p1) > 0);
644             }
645         } else {
646             if (p1.fX < q1.fX) {
647                 result = (compute_side(q0, w, p0)*compute_side(q0, w, p1) < 0);
648             } else {
649                 result = (compute_side(q0, w, p0)*compute_side(p0, v, q1) > 0);
650             }
651         }
652         return result;
653     }
654 
intersectActiveEdge655     bool intersect(const ActiveEdge* edge) {
656         return this->intersect(edge->fSegment.fP0, edge->fSegment.fV, edge->fIndex0, edge->fIndex1);
657     }
658 
lessThanActiveEdge659     bool lessThan(const ActiveEdge* that) const {
660         SkASSERT(!this->above(this));
661         SkASSERT(!that->above(that));
662         SkASSERT(!(this->above(that) && that->above(this)));
663         return this->above(that);
664     }
665 
equalsActiveEdge666     bool equals(uint16_t index0, uint16_t index1) const {
667         return (this->fIndex0 == index0 && this->fIndex1 == index1);
668     }
669 
670     OffsetSegment fSegment;
671     uint16_t fIndex0;   // indices for previous and next vertex in polygon
672     uint16_t fIndex1;
673     ActiveEdge* fChild[2];
674     ActiveEdge* fAbove;
675     ActiveEdge* fBelow;
676     int32_t  fRed;
677 };
678 
679 class ActiveEdgeList {
680 public:
ActiveEdgeList(int maxEdges)681     ActiveEdgeList(int maxEdges) {
682         fAllocation = (char*) sk_malloc_throw(sizeof(ActiveEdge)*maxEdges);
683         fCurrFree = 0;
684         fMaxFree = maxEdges;
685     }
~ActiveEdgeList()686     ~ActiveEdgeList() {
687         fTreeHead.fChild[1] = nullptr;
688         sk_free(fAllocation);
689     }
690 
insert(const SkPoint & p0,const SkPoint & p1,uint16_t index0,uint16_t index1)691     bool insert(const SkPoint& p0, const SkPoint& p1, uint16_t index0, uint16_t index1) {
692         SkVector v = p1 - p0;
693         if (!v.isFinite()) {
694             return false;
695         }
696         // empty tree case -- easy
697         if (!fTreeHead.fChild[1]) {
698             ActiveEdge* root = fTreeHead.fChild[1] = this->allocate(p0, v, index0, index1);
699             SkASSERT(root);
700             if (!root) {
701                 return false;
702             }
703             root->fRed = false;
704             return true;
705         }
706 
707         // set up helpers
708         ActiveEdge* top = &fTreeHead;
709         ActiveEdge *grandparent = nullptr;
710         ActiveEdge *parent = nullptr;
711         ActiveEdge *curr = top->fChild[1];
712         int dir = 0;
713         int last = 0; // ?
714         // predecessor and successor, for intersection check
715         ActiveEdge* pred = nullptr;
716         ActiveEdge* succ = nullptr;
717 
718         // search down the tree
719         while (true) {
720             if (!curr) {
721                 // check for intersection with predecessor and successor
722                 if ((pred && pred->intersect(p0, v, index0, index1)) ||
723                     (succ && succ->intersect(p0, v, index0, index1))) {
724                     return false;
725                 }
726                 // insert new node at bottom
727                 parent->fChild[dir] = curr = this->allocate(p0, v, index0, index1);
728                 SkASSERT(curr);
729                 if (!curr) {
730                     return false;
731                 }
732                 curr->fAbove = pred;
733                 curr->fBelow = succ;
734                 if (pred) {
735                     pred->fBelow = curr;
736                 }
737                 if (succ) {
738                     succ->fAbove = curr;
739                 }
740                 if (IsRed(parent)) {
741                     int dir2 = (top->fChild[1] == grandparent);
742                     if (curr == parent->fChild[last]) {
743                         top->fChild[dir2] = SingleRotation(grandparent, !last);
744                     } else {
745                         top->fChild[dir2] = DoubleRotation(grandparent, !last);
746                     }
747                 }
748                 break;
749             } else if (IsRed(curr->fChild[0]) && IsRed(curr->fChild[1])) {
750                 // color flip
751                 curr->fRed = true;
752                 curr->fChild[0]->fRed = false;
753                 curr->fChild[1]->fRed = false;
754                 if (IsRed(parent)) {
755                     int dir2 = (top->fChild[1] == grandparent);
756                     if (curr == parent->fChild[last]) {
757                         top->fChild[dir2] = SingleRotation(grandparent, !last);
758                     } else {
759                         top->fChild[dir2] = DoubleRotation(grandparent, !last);
760                     }
761                 }
762             }
763 
764             last = dir;
765             int side;
766             // check to see if segment is above or below
767             if (curr->fIndex0 == index0) {
768                 side = compute_side(curr->fSegment.fP0, curr->fSegment.fV, p1);
769             } else {
770                 side = compute_side(curr->fSegment.fP0, curr->fSegment.fV, p0);
771             }
772             if (0 == side) {
773                 return false;
774             }
775             dir = (side < 0);
776 
777             if (0 == dir) {
778                 succ = curr;
779             } else {
780                 pred = curr;
781             }
782 
783             // update helpers
784             if (grandparent) {
785                 top = grandparent;
786             }
787             grandparent = parent;
788             parent = curr;
789             curr = curr->fChild[dir];
790         }
791 
792         // update root and make it black
793         fTreeHead.fChild[1]->fRed = false;
794 
795         SkDEBUGCODE(VerifyTree(fTreeHead.fChild[1]));
796 
797         return true;
798     }
799 
800     // replaces edge p0p1 with p1p2
replace(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2,uint16_t index0,uint16_t index1,uint16_t index2)801     bool replace(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2,
802                  uint16_t index0, uint16_t index1, uint16_t index2) {
803         if (!fTreeHead.fChild[1]) {
804             return false;
805         }
806 
807         SkVector v = p2 - p1;
808         ActiveEdge* curr = &fTreeHead;
809         ActiveEdge* found = nullptr;
810         int dir = 1;
811 
812         // search
813         while (curr->fChild[dir] != nullptr) {
814             // update helpers
815             curr = curr->fChild[dir];
816             // save found node
817             if (curr->equals(index0, index1)) {
818                 found = curr;
819                 break;
820             } else {
821                 // check to see if segment is above or below
822                 int side;
823                 if (curr->fIndex1 == index1) {
824                     side = compute_side(curr->fSegment.fP0, curr->fSegment.fV, p0);
825                 } else {
826                     side = compute_side(curr->fSegment.fP0, curr->fSegment.fV, p1);
827                 }
828                 if (0 == side) {
829                     return false;
830                 }
831                 dir = (side < 0);
832             }
833         }
834 
835         if (!found) {
836             return false;
837         }
838 
839         // replace if found
840         ActiveEdge* pred = found->fAbove;
841         ActiveEdge* succ = found->fBelow;
842         // check deletion and insert intersection cases
843         if (pred && (pred->intersect(found) || pred->intersect(p1, v, index1, index2))) {
844             return false;
845         }
846         if (succ && (succ->intersect(found) || succ->intersect(p1, v, index1, index2))) {
847             return false;
848         }
849         found->fSegment.fP0 = p1;
850         found->fSegment.fV = v;
851         found->fIndex0 = index1;
852         found->fIndex1 = index2;
853         // above and below should stay the same
854 
855         SkDEBUGCODE(VerifyTree(fTreeHead.fChild[1]));
856 
857         return true;
858     }
859 
remove(const SkPoint & p0,const SkPoint & p1,uint16_t index0,uint16_t index1)860     bool remove(const SkPoint& p0, const SkPoint& p1, uint16_t index0, uint16_t index1) {
861         if (!fTreeHead.fChild[1]) {
862             return false;
863         }
864 
865         ActiveEdge* curr = &fTreeHead;
866         ActiveEdge* parent = nullptr;
867         ActiveEdge* grandparent = nullptr;
868         ActiveEdge* found = nullptr;
869         int dir = 1;
870 
871         // search and push a red node down
872         while (curr->fChild[dir] != nullptr) {
873             int last = dir;
874 
875             // update helpers
876             grandparent = parent;
877             parent = curr;
878             curr = curr->fChild[dir];
879             // save found node
880             if (curr->equals(index0, index1)) {
881                 found = curr;
882                 dir = 0;
883             } else {
884                 // check to see if segment is above or below
885                 int side;
886                 if (curr->fIndex1 == index1) {
887                     side = compute_side(curr->fSegment.fP0, curr->fSegment.fV, p0);
888                 } else {
889                     side = compute_side(curr->fSegment.fP0, curr->fSegment.fV, p1);
890                 }
891                 if (0 == side) {
892                     return false;
893                 }
894                 dir = (side < 0);
895             }
896 
897             // push the red node down
898             if (!IsRed(curr) && !IsRed(curr->fChild[dir])) {
899                 if (IsRed(curr->fChild[!dir])) {
900                     parent = parent->fChild[last] = SingleRotation(curr, dir);
901                 } else {
902                     ActiveEdge *s = parent->fChild[!last];
903 
904                     if (s != nullptr) {
905                         if (!IsRed(s->fChild[!last]) && !IsRed(s->fChild[last])) {
906                             // color flip
907                             parent->fRed = false;
908                             s->fRed = true;
909                             curr->fRed = true;
910                         } else {
911                             int dir2 = (grandparent->fChild[1] == parent);
912 
913                             if (IsRed(s->fChild[last])) {
914                                 grandparent->fChild[dir2] = DoubleRotation(parent, last);
915                             } else if (IsRed(s->fChild[!last])) {
916                                 grandparent->fChild[dir2] = SingleRotation(parent, last);
917                             }
918 
919                             // ensure correct coloring
920                             curr->fRed = grandparent->fChild[dir2]->fRed = true;
921                             grandparent->fChild[dir2]->fChild[0]->fRed = false;
922                             grandparent->fChild[dir2]->fChild[1]->fRed = false;
923                         }
924                     }
925                 }
926             }
927         }
928 
929         // replace and remove if found
930         if (found) {
931             ActiveEdge* pred = found->fAbove;
932             ActiveEdge* succ = found->fBelow;
933             if ((pred && pred->intersect(found)) || (succ && succ->intersect(found))) {
934                 return false;
935             }
936             if (found != curr) {
937                 found->fSegment = curr->fSegment;
938                 found->fIndex0 = curr->fIndex0;
939                 found->fIndex1 = curr->fIndex1;
940                 found->fAbove = curr->fAbove;
941                 pred = found->fAbove;
942                 // we don't need to set found->fBelow here
943             } else {
944                 if (succ) {
945                     succ->fAbove = pred;
946                 }
947             }
948             if (pred) {
949                 pred->fBelow = curr->fBelow;
950             }
951             parent->fChild[parent->fChild[1] == curr] = curr->fChild[!curr->fChild[0]];
952 
953             // no need to delete
954             curr->fAbove = reinterpret_cast<ActiveEdge*>(0xdeadbeefll);
955             curr->fBelow = reinterpret_cast<ActiveEdge*>(0xdeadbeefll);
956             if (fTreeHead.fChild[1]) {
957                 fTreeHead.fChild[1]->fRed = false;
958             }
959         }
960 
961         // update root and make it black
962         if (fTreeHead.fChild[1]) {
963             fTreeHead.fChild[1]->fRed = false;
964         }
965 
966         SkDEBUGCODE(VerifyTree(fTreeHead.fChild[1]));
967 
968         return true;
969     }
970 
971 private:
972     // allocator
allocate(const SkPoint & p0,const SkPoint & p1,uint16_t index0,uint16_t index1)973     ActiveEdge * allocate(const SkPoint& p0, const SkPoint& p1, uint16_t index0, uint16_t index1) {
974         if (fCurrFree >= fMaxFree) {
975             return nullptr;
976         }
977         char* bytes = fAllocation + sizeof(ActiveEdge)*fCurrFree;
978         ++fCurrFree;
979         return new(bytes) ActiveEdge(p0, p1, index0, index1);
980     }
981 
982     ///////////////////////////////////////////////////////////////////////////////////
983     // Red-black tree methods
984     ///////////////////////////////////////////////////////////////////////////////////
IsRed(const ActiveEdge * node)985     static bool IsRed(const ActiveEdge* node) {
986         return node && node->fRed;
987     }
988 
SingleRotation(ActiveEdge * node,int dir)989     static ActiveEdge* SingleRotation(ActiveEdge* node, int dir) {
990         ActiveEdge* tmp = node->fChild[!dir];
991 
992         node->fChild[!dir] = tmp->fChild[dir];
993         tmp->fChild[dir] = node;
994 
995         node->fRed = true;
996         tmp->fRed = false;
997 
998         return tmp;
999     }
1000 
DoubleRotation(ActiveEdge * node,int dir)1001     static ActiveEdge* DoubleRotation(ActiveEdge* node, int dir) {
1002         node->fChild[!dir] = SingleRotation(node->fChild[!dir], !dir);
1003 
1004         return SingleRotation(node, dir);
1005     }
1006 
1007     // returns black link count
VerifyTree(const ActiveEdge * tree)1008     static int VerifyTree(const ActiveEdge* tree) {
1009         if (!tree) {
1010             return 1;
1011         }
1012 
1013         const ActiveEdge* left = tree->fChild[0];
1014         const ActiveEdge* right = tree->fChild[1];
1015 
1016         // no consecutive red links
1017         if (IsRed(tree) && (IsRed(left) || IsRed(right))) {
1018             SkASSERT(false);
1019             return 0;
1020         }
1021 
1022         // check secondary links
1023         if (tree->fAbove) {
1024             SkASSERT(tree->fAbove->fBelow == tree);
1025             SkASSERT(tree->fAbove->lessThan(tree));
1026         }
1027         if (tree->fBelow) {
1028             SkASSERT(tree->fBelow->fAbove == tree);
1029             SkASSERT(tree->lessThan(tree->fBelow));
1030         }
1031 
1032         // violates binary tree order
1033         if ((left && tree->lessThan(left)) || (right && right->lessThan(tree))) {
1034             SkASSERT(false);
1035             return 0;
1036         }
1037 
1038         int leftCount = VerifyTree(left);
1039         int rightCount = VerifyTree(right);
1040 
1041         // return black link count
1042         if (leftCount != 0 && rightCount != 0) {
1043             // black height mismatch
1044             if (leftCount != rightCount) {
1045                 SkASSERT(false);
1046                 return 0;
1047             }
1048             return IsRed(tree) ? leftCount : leftCount + 1;
1049         } else {
1050             return 0;
1051         }
1052     }
1053 
1054     ActiveEdge fTreeHead;
1055     char*      fAllocation;
1056     int        fCurrFree;
1057     int        fMaxFree;
1058 };
1059 
1060 // Here we implement a sweep line algorithm to determine whether the provided points
1061 // represent a simple polygon, i.e., the polygon is non-self-intersecting.
1062 // We first insert the vertices into a priority queue sorting horizontally from left to right.
1063 // Then as we pop the vertices from the queue we generate events which indicate that an edge
1064 // should be added or removed from an edge list. If any intersections are detected in the edge
1065 // list, then we know the polygon is self-intersecting and hence not simple.
SkIsSimplePolygon(const SkPoint * polygon,int polygonSize)1066 bool SkIsSimplePolygon(const SkPoint* polygon, int polygonSize) {
1067     if (polygonSize < 3) {
1068         return false;
1069     }
1070 
1071     // If it's convex, it's simple
1072     if (SkIsConvexPolygon(polygon, polygonSize)) {
1073         return true;
1074     }
1075 
1076     // practically speaking, it takes too long to process large polygons
1077     if (polygonSize > 2048) {
1078         return false;
1079     }
1080 
1081     SkTDPQueue <Vertex, Vertex::Left> vertexQueue(polygonSize);
1082     for (int i = 0; i < polygonSize; ++i) {
1083         Vertex newVertex;
1084         if (!polygon[i].isFinite()) {
1085             return false;
1086         }
1087         newVertex.fPosition = polygon[i];
1088         newVertex.fIndex = i;
1089         newVertex.fPrevIndex = (i - 1 + polygonSize) % polygonSize;
1090         newVertex.fNextIndex = (i + 1) % polygonSize;
1091         newVertex.fFlags = 0;
1092         if (left(polygon[newVertex.fPrevIndex], polygon[i])) {
1093             newVertex.fFlags |= kPrevLeft_VertexFlag;
1094         }
1095         if (left(polygon[newVertex.fNextIndex], polygon[i])) {
1096             newVertex.fFlags |= kNextLeft_VertexFlag;
1097         }
1098         vertexQueue.insert(newVertex);
1099     }
1100 
1101     // pop each vertex from the queue and generate events depending on
1102     // where it lies relative to its neighboring edges
1103     ActiveEdgeList sweepLine(polygonSize);
1104     while (vertexQueue.count() > 0) {
1105         const Vertex& v = vertexQueue.peek();
1106 
1107         // both to the right -- insert both
1108         if (v.fFlags == 0) {
1109             if (!sweepLine.insert(v.fPosition, polygon[v.fPrevIndex], v.fIndex, v.fPrevIndex)) {
1110                 break;
1111             }
1112             if (!sweepLine.insert(v.fPosition, polygon[v.fNextIndex], v.fIndex, v.fNextIndex)) {
1113                 break;
1114             }
1115         // both to the left -- remove both
1116         } else if (v.fFlags == (kPrevLeft_VertexFlag | kNextLeft_VertexFlag)) {
1117             if (!sweepLine.remove(polygon[v.fPrevIndex], v.fPosition, v.fPrevIndex, v.fIndex)) {
1118                 break;
1119             }
1120             if (!sweepLine.remove(polygon[v.fNextIndex], v.fPosition, v.fNextIndex, v.fIndex)) {
1121                 break;
1122             }
1123         // one to left and right -- replace one with another
1124         } else {
1125             if (v.fFlags & kPrevLeft_VertexFlag) {
1126                 if (!sweepLine.replace(polygon[v.fPrevIndex], v.fPosition, polygon[v.fNextIndex],
1127                                        v.fPrevIndex, v.fIndex, v.fNextIndex)) {
1128                     break;
1129                 }
1130             } else {
1131                 SkASSERT(v.fFlags & kNextLeft_VertexFlag);
1132                 if (!sweepLine.replace(polygon[v.fNextIndex], v.fPosition, polygon[v.fPrevIndex],
1133                                        v.fNextIndex, v.fIndex, v.fPrevIndex)) {
1134                     break;
1135                 }
1136             }
1137         }
1138 
1139         vertexQueue.pop();
1140     }
1141 
1142     return (vertexQueue.count() == 0);
1143 }
1144 
1145 ///////////////////////////////////////////////////////////////////////////////////////////
1146 
1147 // helper function for SkOffsetSimplePolygon
setup_offset_edge(OffsetEdge * currEdge,const SkPoint & endpoint0,const SkPoint & endpoint1,uint16_t startIndex,uint16_t endIndex)1148 static void setup_offset_edge(OffsetEdge* currEdge,
1149                               const SkPoint& endpoint0, const SkPoint& endpoint1,
1150                               uint16_t startIndex, uint16_t endIndex) {
1151     currEdge->fOffset.fP0 = endpoint0;
1152     currEdge->fOffset.fV = endpoint1 - endpoint0;
1153     currEdge->init(startIndex, endIndex);
1154 }
1155 
is_reflex_vertex(const SkPoint * inputPolygonVerts,int winding,SkScalar offset,uint16_t prevIndex,uint16_t currIndex,uint16_t nextIndex)1156 static bool is_reflex_vertex(const SkPoint* inputPolygonVerts, int winding, SkScalar offset,
1157                              uint16_t prevIndex, uint16_t currIndex, uint16_t nextIndex) {
1158     int side = compute_side(inputPolygonVerts[prevIndex],
1159                             inputPolygonVerts[currIndex] - inputPolygonVerts[prevIndex],
1160                             inputPolygonVerts[nextIndex]);
1161     // if reflex point, we need to add extra edges
1162     return (side*winding*offset < 0);
1163 }
1164 
SkOffsetSimplePolygon(const SkPoint * inputPolygonVerts,int inputPolygonSize,const SkRect & bounds,SkScalar offset,SkTDArray<SkPoint> * offsetPolygon,SkTDArray<int> * polygonIndices)1165 bool SkOffsetSimplePolygon(const SkPoint* inputPolygonVerts, int inputPolygonSize,
1166                            const SkRect& bounds, SkScalar offset,
1167                            SkTDArray<SkPoint>* offsetPolygon, SkTDArray<int>* polygonIndices) {
1168     if (inputPolygonSize < 3) {
1169         return false;
1170     }
1171 
1172     // need to be able to represent all the vertices in the 16-bit indices
1173     if (inputPolygonSize >= std::numeric_limits<uint16_t>::max()) {
1174         return false;
1175     }
1176 
1177     if (!SkScalarIsFinite(offset)) {
1178         return false;
1179     }
1180 
1181     // can't inset more than the half bounds of the polygon
1182     if (offset > std::min(SkTAbs(SK_ScalarHalf*bounds.width()),
1183                         SkTAbs(SK_ScalarHalf*bounds.height()))) {
1184         return false;
1185     }
1186 
1187     // offsetting close to zero just returns the original poly
1188     if (SkScalarNearlyZero(offset)) {
1189         for (int i = 0; i < inputPolygonSize; ++i) {
1190             *offsetPolygon->push() = inputPolygonVerts[i];
1191             if (polygonIndices) {
1192                 *polygonIndices->push() = i;
1193             }
1194         }
1195         return true;
1196     }
1197 
1198     // get winding direction
1199     int winding = SkGetPolygonWinding(inputPolygonVerts, inputPolygonSize);
1200     if (0 == winding) {
1201         return false;
1202     }
1203 
1204     // build normals
1205     SkAutoSTMalloc<64, SkVector> normals(inputPolygonSize);
1206     unsigned int numEdges = 0;
1207     for (int currIndex = 0, prevIndex = inputPolygonSize - 1;
1208          currIndex < inputPolygonSize;
1209          prevIndex = currIndex, ++currIndex) {
1210         if (!inputPolygonVerts[currIndex].isFinite()) {
1211             return false;
1212         }
1213         int nextIndex = (currIndex + 1) % inputPolygonSize;
1214         if (!compute_offset_vector(inputPolygonVerts[currIndex], inputPolygonVerts[nextIndex],
1215                                    offset, winding, &normals[currIndex])) {
1216             return false;
1217         }
1218         if (currIndex > 0) {
1219             // if reflex point, we need to add extra edges
1220             if (is_reflex_vertex(inputPolygonVerts, winding, offset,
1221                                  prevIndex, currIndex, nextIndex)) {
1222                 SkScalar rotSin, rotCos;
1223                 int numSteps;
1224                 if (!SkComputeRadialSteps(normals[prevIndex], normals[currIndex], offset,
1225                                           &rotSin, &rotCos, &numSteps)) {
1226                     return false;
1227                 }
1228                 numEdges += std::max(numSteps, 1);
1229             }
1230         }
1231         numEdges++;
1232     }
1233     // finish up the edge counting
1234     if (is_reflex_vertex(inputPolygonVerts, winding, offset, inputPolygonSize-1, 0, 1)) {
1235         SkScalar rotSin, rotCos;
1236         int numSteps;
1237         if (!SkComputeRadialSteps(normals[inputPolygonSize-1], normals[0], offset,
1238                                   &rotSin, &rotCos, &numSteps)) {
1239             return false;
1240         }
1241         numEdges += std::max(numSteps, 1);
1242     }
1243 
1244     // Make sure we don't overflow the max array count.
1245     // We shouldn't overflow numEdges, as SkComputeRadialSteps returns a max of 2^16-1,
1246     // and we have a max of 2^16-1 original vertices.
1247     if (numEdges > (unsigned int)std::numeric_limits<int32_t>::max()) {
1248         return false;
1249     }
1250 
1251     // build initial offset edge list
1252     SkSTArray<64, OffsetEdge> edgeData(numEdges);
1253     OffsetEdge* prevEdge = nullptr;
1254     for (int currIndex = 0, prevIndex = inputPolygonSize - 1;
1255          currIndex < inputPolygonSize;
1256          prevIndex = currIndex, ++currIndex) {
1257         int nextIndex = (currIndex + 1) % inputPolygonSize;
1258         // if reflex point, fill in curve
1259         if (is_reflex_vertex(inputPolygonVerts, winding, offset,
1260                              prevIndex, currIndex, nextIndex)) {
1261             SkScalar rotSin, rotCos;
1262             int numSteps;
1263             SkVector prevNormal = normals[prevIndex];
1264             if (!SkComputeRadialSteps(prevNormal, normals[currIndex], offset,
1265                                       &rotSin, &rotCos, &numSteps)) {
1266                 return false;
1267             }
1268             auto currEdge = edgeData.push_back_n(std::max(numSteps, 1));
1269             for (int i = 0; i < numSteps - 1; ++i) {
1270                 SkVector currNormal = SkVector::Make(prevNormal.fX*rotCos - prevNormal.fY*rotSin,
1271                                                      prevNormal.fY*rotCos + prevNormal.fX*rotSin);
1272                 setup_offset_edge(currEdge,
1273                                   inputPolygonVerts[currIndex] + prevNormal,
1274                                   inputPolygonVerts[currIndex] + currNormal,
1275                                   currIndex, currIndex);
1276                 prevNormal = currNormal;
1277                 currEdge->fPrev = prevEdge;
1278                 if (prevEdge) {
1279                     prevEdge->fNext = currEdge;
1280                 }
1281                 prevEdge = currEdge;
1282                 ++currEdge;
1283             }
1284             setup_offset_edge(currEdge,
1285                               inputPolygonVerts[currIndex] + prevNormal,
1286                               inputPolygonVerts[currIndex] + normals[currIndex],
1287                               currIndex, currIndex);
1288             currEdge->fPrev = prevEdge;
1289             if (prevEdge) {
1290                 prevEdge->fNext = currEdge;
1291             }
1292             prevEdge = currEdge;
1293         }
1294 
1295         // Add the edge
1296         auto currEdge = edgeData.push_back_n(1);
1297         setup_offset_edge(currEdge,
1298                           inputPolygonVerts[currIndex] + normals[currIndex],
1299                           inputPolygonVerts[nextIndex] + normals[currIndex],
1300                           currIndex, nextIndex);
1301         currEdge->fPrev = prevEdge;
1302         if (prevEdge) {
1303             prevEdge->fNext = currEdge;
1304         }
1305         prevEdge = currEdge;
1306     }
1307     // close up the linked list
1308     SkASSERT(prevEdge);
1309     prevEdge->fNext = &edgeData[0];
1310     edgeData[0].fPrev = prevEdge;
1311 
1312     // now clip edges
1313     SkASSERT(edgeData.count() == (int)numEdges);
1314     auto head = &edgeData[0];
1315     auto currEdge = head;
1316     unsigned int offsetVertexCount = numEdges;
1317     unsigned long long iterations = 0;
1318     unsigned long long maxIterations = (unsigned long long)(numEdges) * numEdges;
1319     while (head && prevEdge != currEdge && offsetVertexCount > 0) {
1320         ++iterations;
1321         // we should check each edge against each other edge at most once
1322         if (iterations > maxIterations) {
1323             return false;
1324         }
1325 
1326         SkScalar s, t;
1327         SkPoint intersection;
1328         if (prevEdge->checkIntersection(currEdge, &intersection, &s, &t)) {
1329             // if new intersection is further back on previous inset from the prior intersection
1330             if (s < prevEdge->fTValue) {
1331                 // no point in considering this one again
1332                 remove_node(prevEdge, &head);
1333                 --offsetVertexCount;
1334                 // go back one segment
1335                 prevEdge = prevEdge->fPrev;
1336                 // we've already considered this intersection, we're done
1337             } else if (currEdge->fTValue > SK_ScalarMin &&
1338                        SkPointPriv::EqualsWithinTolerance(intersection,
1339                                                           currEdge->fIntersection,
1340                                                           1.0e-6f)) {
1341                 break;
1342             } else {
1343                 // add intersection
1344                 currEdge->fIntersection = intersection;
1345                 currEdge->fTValue = t;
1346                 currEdge->fIndex = prevEdge->fEnd;
1347 
1348                 // go to next segment
1349                 prevEdge = currEdge;
1350                 currEdge = currEdge->fNext;
1351             }
1352         } else {
1353             // If there is no intersection, we want to minimize the distance between
1354             // the point where the segment lines cross and the segments themselves.
1355             OffsetEdge* prevPrevEdge = prevEdge->fPrev;
1356             OffsetEdge* currNextEdge = currEdge->fNext;
1357             SkScalar dist0 = currEdge->computeCrossingDistance(prevPrevEdge);
1358             SkScalar dist1 = prevEdge->computeCrossingDistance(currNextEdge);
1359             // if both lead to direct collision
1360             if (dist0 < 0 && dist1 < 0) {
1361                 // check first to see if either represent parts of one contour
1362                 SkPoint p1 = prevPrevEdge->fOffset.fP0 + prevPrevEdge->fOffset.fV;
1363                 bool prevSameContour = SkPointPriv::EqualsWithinTolerance(p1,
1364                                                                           prevEdge->fOffset.fP0);
1365                 p1 = currEdge->fOffset.fP0 + currEdge->fOffset.fV;
1366                 bool currSameContour = SkPointPriv::EqualsWithinTolerance(p1,
1367                                                                          currNextEdge->fOffset.fP0);
1368 
1369                 // want to step along contour to find intersections rather than jump to new one
1370                 if (currSameContour && !prevSameContour) {
1371                     remove_node(currEdge, &head);
1372                     currEdge = currNextEdge;
1373                     --offsetVertexCount;
1374                     continue;
1375                 } else if (prevSameContour && !currSameContour) {
1376                     remove_node(prevEdge, &head);
1377                     prevEdge = prevPrevEdge;
1378                     --offsetVertexCount;
1379                     continue;
1380                 }
1381             }
1382 
1383             // otherwise minimize collision distance along segment
1384             if (dist0 < dist1) {
1385                 remove_node(prevEdge, &head);
1386                 prevEdge = prevPrevEdge;
1387             } else {
1388                 remove_node(currEdge, &head);
1389                 currEdge = currNextEdge;
1390             }
1391             --offsetVertexCount;
1392         }
1393     }
1394 
1395     // store all the valid intersections that aren't nearly coincident
1396     // TODO: look at the main algorithm and see if we can detect these better
1397     offsetPolygon->reset();
1398     if (!head || offsetVertexCount == 0 ||
1399         offsetVertexCount >= std::numeric_limits<uint16_t>::max()) {
1400         return false;
1401     }
1402 
1403     static constexpr SkScalar kCleanupTolerance = 0.01f;
1404     offsetPolygon->setReserve(offsetVertexCount);
1405     int currIndex = 0;
1406     *offsetPolygon->push() = head->fIntersection;
1407     if (polygonIndices) {
1408         *polygonIndices->push() = head->fIndex;
1409     }
1410     currEdge = head->fNext;
1411     while (currEdge != head) {
1412         if (!SkPointPriv::EqualsWithinTolerance(currEdge->fIntersection,
1413                                                 (*offsetPolygon)[currIndex],
1414                                                 kCleanupTolerance)) {
1415             *offsetPolygon->push() = currEdge->fIntersection;
1416             if (polygonIndices) {
1417                 *polygonIndices->push() = currEdge->fIndex;
1418             }
1419             currIndex++;
1420         }
1421         currEdge = currEdge->fNext;
1422     }
1423     // make sure the first and last points aren't coincident
1424     if (currIndex >= 1 &&
1425         SkPointPriv::EqualsWithinTolerance((*offsetPolygon)[0], (*offsetPolygon)[currIndex],
1426                                             kCleanupTolerance)) {
1427         offsetPolygon->pop();
1428         if (polygonIndices) {
1429             polygonIndices->pop();
1430         }
1431     }
1432 
1433     // check winding of offset polygon (it should be same as the original polygon)
1434     SkScalar offsetWinding = SkGetPolygonWinding(offsetPolygon->begin(), offsetPolygon->count());
1435 
1436     return (winding*offsetWinding > 0 &&
1437             SkIsSimplePolygon(offsetPolygon->begin(), offsetPolygon->count()));
1438 }
1439 
1440 //////////////////////////////////////////////////////////////////////////////////////////
1441 
1442 struct TriangulationVertex {
1443     SK_DECLARE_INTERNAL_LLIST_INTERFACE(TriangulationVertex);
1444 
1445     enum class VertexType { kConvex, kReflex };
1446 
1447     SkPoint    fPosition;
1448     VertexType fVertexType;
1449     uint16_t   fIndex;
1450     uint16_t   fPrevIndex;
1451     uint16_t   fNextIndex;
1452 };
1453 
compute_triangle_bounds(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2,SkRect * bounds)1454 static void compute_triangle_bounds(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2,
1455                                     SkRect* bounds) {
1456     Sk4s min, max;
1457     min = max = Sk4s(p0.fX, p0.fY, p0.fX, p0.fY);
1458     Sk4s xy(p1.fX, p1.fY, p2.fX, p2.fY);
1459     min = Sk4s::Min(min, xy);
1460     max = Sk4s::Max(max, xy);
1461     bounds->setLTRB(std::min(min[0], min[2]), std::min(min[1], min[3]),
1462                     std::max(max[0], max[2]), std::max(max[1], max[3]));
1463 }
1464 
1465 // test to see if point p is in triangle p0p1p2.
1466 // for now assuming strictly inside -- if on the edge it's outside
point_in_triangle(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2,const SkPoint & p)1467 static bool point_in_triangle(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2,
1468                               const SkPoint& p) {
1469     SkVector v0 = p1 - p0;
1470     SkVector v1 = p2 - p1;
1471     SkScalar n = v0.cross(v1);
1472 
1473     SkVector w0 = p - p0;
1474     if (n*v0.cross(w0) < SK_ScalarNearlyZero) {
1475         return false;
1476     }
1477 
1478     SkVector w1 = p - p1;
1479     if (n*v1.cross(w1) < SK_ScalarNearlyZero) {
1480         return false;
1481     }
1482 
1483     SkVector v2 = p0 - p2;
1484     SkVector w2 = p - p2;
1485     if (n*v2.cross(w2) < SK_ScalarNearlyZero) {
1486         return false;
1487     }
1488 
1489     return true;
1490 }
1491 
1492 // Data structure to track reflex vertices and check whether any are inside a given triangle
1493 class ReflexHash {
1494 public:
init(const SkRect & bounds,int vertexCount)1495     bool init(const SkRect& bounds, int vertexCount) {
1496         fBounds = bounds;
1497         fNumVerts = 0;
1498         SkScalar width = bounds.width();
1499         SkScalar height = bounds.height();
1500         if (!SkScalarIsFinite(width) || !SkScalarIsFinite(height)) {
1501             return false;
1502         }
1503 
1504         // We want vertexCount grid cells, roughly distributed to match the bounds ratio
1505         SkScalar hCount = SkScalarSqrt(sk_ieee_float_divide(vertexCount*width, height));
1506         if (!SkScalarIsFinite(hCount)) {
1507             return false;
1508         }
1509         fHCount = std::max(std::min(SkScalarRoundToInt(hCount), vertexCount), 1);
1510         fVCount = vertexCount/fHCount;
1511         fGridConversion.set(sk_ieee_float_divide(fHCount - 0.001f, width),
1512                             sk_ieee_float_divide(fVCount - 0.001f, height));
1513         if (!fGridConversion.isFinite()) {
1514             return false;
1515         }
1516 
1517         fGrid.setCount(fHCount*fVCount);
1518         for (int i = 0; i < fGrid.count(); ++i) {
1519             fGrid[i].reset();
1520         }
1521 
1522         return true;
1523     }
1524 
add(TriangulationVertex * v)1525     void add(TriangulationVertex* v) {
1526         int index = hash(v);
1527         fGrid[index].addToTail(v);
1528         ++fNumVerts;
1529     }
1530 
remove(TriangulationVertex * v)1531     void remove(TriangulationVertex* v) {
1532         int index = hash(v);
1533         fGrid[index].remove(v);
1534         --fNumVerts;
1535     }
1536 
checkTriangle(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2,uint16_t ignoreIndex0,uint16_t ignoreIndex1) const1537     bool checkTriangle(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2,
1538                        uint16_t ignoreIndex0, uint16_t ignoreIndex1) const {
1539         if (!fNumVerts) {
1540             return false;
1541         }
1542 
1543         SkRect triBounds;
1544         compute_triangle_bounds(p0, p1, p2, &triBounds);
1545         int h0 = (triBounds.fLeft - fBounds.fLeft)*fGridConversion.fX;
1546         int h1 = (triBounds.fRight - fBounds.fLeft)*fGridConversion.fX;
1547         int v0 = (triBounds.fTop - fBounds.fTop)*fGridConversion.fY;
1548         int v1 = (triBounds.fBottom - fBounds.fTop)*fGridConversion.fY;
1549 
1550         for (int v = v0; v <= v1; ++v) {
1551             for (int h = h0; h <= h1; ++h) {
1552                 int i = v * fHCount + h;
1553                 for (SkTInternalLList<TriangulationVertex>::Iter reflexIter = fGrid[i].begin();
1554                      reflexIter != fGrid[i].end(); ++reflexIter) {
1555                     TriangulationVertex* reflexVertex = *reflexIter;
1556                     if (reflexVertex->fIndex != ignoreIndex0 &&
1557                         reflexVertex->fIndex != ignoreIndex1 &&
1558                         point_in_triangle(p0, p1, p2, reflexVertex->fPosition)) {
1559                         return true;
1560                     }
1561                 }
1562 
1563             }
1564         }
1565 
1566         return false;
1567     }
1568 
1569 private:
hash(TriangulationVertex * vert) const1570     int hash(TriangulationVertex* vert) const {
1571         int h = (vert->fPosition.fX - fBounds.fLeft)*fGridConversion.fX;
1572         int v = (vert->fPosition.fY - fBounds.fTop)*fGridConversion.fY;
1573         SkASSERT(v*fHCount + h >= 0);
1574         return v*fHCount + h;
1575     }
1576 
1577     SkRect fBounds;
1578     int fHCount;
1579     int fVCount;
1580     int fNumVerts;
1581     // converts distance from the origin to a grid location (when cast to int)
1582     SkVector fGridConversion;
1583     SkTDArray<SkTInternalLList<TriangulationVertex>> fGrid;
1584 };
1585 
1586 // Check to see if a reflex vertex has become a convex vertex after clipping an ear
reclassify_vertex(TriangulationVertex * p,const SkPoint * polygonVerts,int winding,ReflexHash * reflexHash,SkTInternalLList<TriangulationVertex> * convexList)1587 static void reclassify_vertex(TriangulationVertex* p, const SkPoint* polygonVerts,
1588                               int winding, ReflexHash* reflexHash,
1589                               SkTInternalLList<TriangulationVertex>* convexList) {
1590     if (TriangulationVertex::VertexType::kReflex == p->fVertexType) {
1591         SkVector v0 = p->fPosition - polygonVerts[p->fPrevIndex];
1592         SkVector v1 = polygonVerts[p->fNextIndex] - p->fPosition;
1593         if (winding*v0.cross(v1) > SK_ScalarNearlyZero*SK_ScalarNearlyZero) {
1594             p->fVertexType = TriangulationVertex::VertexType::kConvex;
1595             reflexHash->remove(p);
1596             p->fPrev = p->fNext = nullptr;
1597             convexList->addToTail(p);
1598         }
1599     }
1600 }
1601 
SkTriangulateSimplePolygon(const SkPoint * polygonVerts,uint16_t * indexMap,int polygonSize,SkTDArray<uint16_t> * triangleIndices)1602 bool SkTriangulateSimplePolygon(const SkPoint* polygonVerts, uint16_t* indexMap, int polygonSize,
1603                                 SkTDArray<uint16_t>* triangleIndices) {
1604     if (polygonSize < 3) {
1605         return false;
1606     }
1607     // need to be able to represent all the vertices in the 16-bit indices
1608     if (polygonSize >= std::numeric_limits<uint16_t>::max()) {
1609         return false;
1610     }
1611 
1612     // get bounds
1613     SkRect bounds;
1614     if (!bounds.setBoundsCheck(polygonVerts, polygonSize)) {
1615         return false;
1616     }
1617     // get winding direction
1618     // TODO: we do this for all the polygon routines -- might be better to have the client
1619     // compute it and pass it in
1620     int winding = SkGetPolygonWinding(polygonVerts, polygonSize);
1621     if (0 == winding) {
1622         return false;
1623     }
1624 
1625     // Set up vertices
1626     SkAutoSTArray<64, TriangulationVertex> triangulationVertices(polygonSize);
1627     int prevIndex = polygonSize - 1;
1628     SkVector v0 = polygonVerts[0] - polygonVerts[prevIndex];
1629     for (int currIndex = 0; currIndex < polygonSize; ++currIndex) {
1630         int nextIndex = (currIndex + 1) % polygonSize;
1631 
1632         triangulationVertices[currIndex] = TriangulationVertex{};
1633         triangulationVertices[currIndex].fPosition = polygonVerts[currIndex];
1634         triangulationVertices[currIndex].fIndex = currIndex;
1635         triangulationVertices[currIndex].fPrevIndex = prevIndex;
1636         triangulationVertices[currIndex].fNextIndex = nextIndex;
1637         SkVector v1 = polygonVerts[nextIndex] - polygonVerts[currIndex];
1638         if (winding*v0.cross(v1) > SK_ScalarNearlyZero*SK_ScalarNearlyZero) {
1639             triangulationVertices[currIndex].fVertexType = TriangulationVertex::VertexType::kConvex;
1640         } else {
1641             triangulationVertices[currIndex].fVertexType = TriangulationVertex::VertexType::kReflex;
1642         }
1643 
1644         prevIndex = currIndex;
1645         v0 = v1;
1646     }
1647 
1648     // Classify initial vertices into a list of convex vertices and a hash of reflex vertices
1649     // TODO: possibly sort the convexList in some way to get better triangles
1650     SkTInternalLList<TriangulationVertex> convexList;
1651     ReflexHash reflexHash;
1652     if (!reflexHash.init(bounds, polygonSize)) {
1653         return false;
1654     }
1655     prevIndex = polygonSize - 1;
1656     for (int currIndex = 0; currIndex < polygonSize; prevIndex = currIndex, ++currIndex) {
1657         TriangulationVertex::VertexType currType = triangulationVertices[currIndex].fVertexType;
1658         if (TriangulationVertex::VertexType::kConvex == currType) {
1659             int nextIndex = (currIndex + 1) % polygonSize;
1660             TriangulationVertex::VertexType prevType = triangulationVertices[prevIndex].fVertexType;
1661             TriangulationVertex::VertexType nextType = triangulationVertices[nextIndex].fVertexType;
1662             // We prioritize clipping vertices with neighboring reflex vertices.
1663             // The intent here is that it will cull reflex vertices more quickly.
1664             if (TriangulationVertex::VertexType::kReflex == prevType ||
1665                 TriangulationVertex::VertexType::kReflex == nextType) {
1666                 convexList.addToHead(&triangulationVertices[currIndex]);
1667             } else {
1668                 convexList.addToTail(&triangulationVertices[currIndex]);
1669             }
1670         } else {
1671             // We treat near collinear vertices as reflex
1672             reflexHash.add(&triangulationVertices[currIndex]);
1673         }
1674     }
1675 
1676     // The general concept: We are trying to find three neighboring vertices where
1677     // no other vertex lies inside the triangle (an "ear"). If we find one, we clip
1678     // that ear off, and then repeat on the new polygon. Once we get down to three vertices
1679     // we have triangulated the entire polygon.
1680     // In the worst case this is an n^2 algorithm. We can cut down the search space somewhat by
1681     // noting that only convex vertices can be potential ears, and we only need to check whether
1682     // any reflex vertices lie inside the ear.
1683     triangleIndices->setReserve(triangleIndices->count() + 3 * (polygonSize - 2));
1684     int vertexCount = polygonSize;
1685     while (vertexCount > 3) {
1686         bool success = false;
1687         TriangulationVertex* earVertex = nullptr;
1688         TriangulationVertex* p0 = nullptr;
1689         TriangulationVertex* p2 = nullptr;
1690         // find a convex vertex to clip
1691         for (SkTInternalLList<TriangulationVertex>::Iter convexIter = convexList.begin();
1692              convexIter != convexList.end(); ++convexIter) {
1693             earVertex = *convexIter;
1694             SkASSERT(TriangulationVertex::VertexType::kReflex != earVertex->fVertexType);
1695 
1696             p0 = &triangulationVertices[earVertex->fPrevIndex];
1697             p2 = &triangulationVertices[earVertex->fNextIndex];
1698 
1699             // see if any reflex vertices are inside the ear
1700             bool failed = reflexHash.checkTriangle(p0->fPosition, earVertex->fPosition,
1701                                                    p2->fPosition, p0->fIndex, p2->fIndex);
1702             if (failed) {
1703                 continue;
1704             }
1705 
1706             // found one we can clip
1707             success = true;
1708             break;
1709         }
1710         // If we can't find any ears to clip, this probably isn't a simple polygon
1711         if (!success) {
1712             return false;
1713         }
1714 
1715         // add indices
1716         auto indices = triangleIndices->append(3);
1717         indices[0] = indexMap[p0->fIndex];
1718         indices[1] = indexMap[earVertex->fIndex];
1719         indices[2] = indexMap[p2->fIndex];
1720 
1721         // clip the ear
1722         convexList.remove(earVertex);
1723         --vertexCount;
1724 
1725         // reclassify reflex verts
1726         p0->fNextIndex = earVertex->fNextIndex;
1727         reclassify_vertex(p0, polygonVerts, winding, &reflexHash, &convexList);
1728 
1729         p2->fPrevIndex = earVertex->fPrevIndex;
1730         reclassify_vertex(p2, polygonVerts, winding, &reflexHash, &convexList);
1731     }
1732 
1733     // output indices
1734     for (SkTInternalLList<TriangulationVertex>::Iter vertexIter = convexList.begin();
1735          vertexIter != convexList.end(); ++vertexIter) {
1736         TriangulationVertex* vertex = *vertexIter;
1737         *triangleIndices->push() = indexMap[vertex->fIndex];
1738     }
1739 
1740     return true;
1741 }
1742 
1743 ///////////
1744 
crs(SkVector a,SkVector b)1745 static double crs(SkVector a, SkVector b) {
1746     return a.fX * b.fY - a.fY * b.fX;
1747 }
1748 
sign(SkScalar v)1749 static int sign(SkScalar v) {
1750     return v < 0 ? -1 : (v > 0);
1751 }
1752 
1753 struct SignTracker {
1754     int fSign;
1755     int fSignChanges;
1756 
resetSignTracker1757     void reset() {
1758         fSign = 0;
1759         fSignChanges = 0;
1760     }
1761 
initSignTracker1762     void init(int s) {
1763         SkASSERT(fSignChanges == 0);
1764         SkASSERT(s == 1 || s == -1 || s == 0);
1765         fSign = s;
1766         fSignChanges = 1;
1767     }
1768 
updateSignTracker1769     void update(int s) {
1770         if (s) {
1771             if (fSign != s) {
1772                 fSignChanges += 1;
1773                 fSign = s;
1774             }
1775         }
1776     }
1777 };
1778 
1779 struct ConvexTracker {
1780     SkVector    fFirst, fPrev;
1781     SignTracker fDSign, fCSign;
1782     int         fVecCounter;
1783     bool        fIsConcave;
1784 
ConvexTrackerConvexTracker1785     ConvexTracker() { this->reset(); }
1786 
resetConvexTracker1787     void reset() {
1788         fPrev = {0, 0};
1789         fDSign.reset();
1790         fCSign.reset();
1791         fVecCounter = 0;
1792         fIsConcave = false;
1793     }
1794 
addVecConvexTracker1795     void addVec(SkPoint p1, SkPoint p0) {
1796         this->addVec(p1 - p0);
1797     }
addVecConvexTracker1798     void addVec(SkVector v) {
1799         if (v.fX == 0 && v.fY == 0) {
1800             return;
1801         }
1802 
1803         fVecCounter += 1;
1804         if (fVecCounter == 1) {
1805             fFirst = fPrev = v;
1806             fDSign.update(sign(v.fX));
1807             return;
1808         }
1809 
1810         SkScalar d = v.fX;
1811         SkScalar c = crs(fPrev, v);
1812         int sign_c;
1813         if (c) {
1814             sign_c = sign(c);
1815         } else {
1816             if (d >= 0) {
1817                 sign_c = fCSign.fSign;
1818             } else {
1819                 sign_c = -fCSign.fSign;
1820             }
1821         }
1822 
1823         fDSign.update(sign(d));
1824         fCSign.update(sign_c);
1825         fPrev = v;
1826 
1827         if (fDSign.fSignChanges > 3 || fCSign.fSignChanges > 1) {
1828             fIsConcave = true;
1829         }
1830     }
1831 
finalCrossConvexTracker1832     void finalCross() {
1833         this->addVec(fFirst);
1834     }
1835 };
1836 
SkIsPolyConvex_experimental(const SkPoint pts[],int count)1837 bool SkIsPolyConvex_experimental(const SkPoint pts[], int count) {
1838     if (count <= 3) {
1839         return true;
1840     }
1841 
1842     ConvexTracker tracker;
1843 
1844     for (int i = 0; i < count - 1; ++i) {
1845         tracker.addVec(pts[i + 1], pts[i]);
1846         if (tracker.fIsConcave) {
1847             return false;
1848         }
1849     }
1850     tracker.addVec(pts[0], pts[count - 1]);
1851     tracker.finalCross();
1852     return !tracker.fIsConcave;
1853 }
1854 
1855