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