• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2015 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/gpu/GrTessellator.h"
9 
10 #include "src/gpu/GrDefaultGeoProcFactory.h"
11 #include "src/gpu/GrVertexWriter.h"
12 #include "src/gpu/geometry/GrPathUtils.h"
13 
14 #include "include/core/SkPath.h"
15 #include "src/core/SkArenaAlloc.h"
16 #include "src/core/SkGeometry.h"
17 #include "src/core/SkPointPriv.h"
18 
19 #include <algorithm>
20 #include <cstdio>
21 #include <queue>
22 #include <unordered_map>
23 #include <utility>
24 
25 /*
26  * There are six stages to the basic algorithm:
27  *
28  * 1) Linearize the path contours into piecewise linear segments (path_to_contours()).
29  * 2) Build a mesh of edges connecting the vertices (build_edges()).
30  * 3) Sort the vertices in Y (and secondarily in X) (merge_sort()).
31  * 4) Simplify the mesh by inserting new vertices at intersecting edges (simplify()).
32  * 5) Tessellate the simplified mesh into monotone polygons (tessellate()).
33  * 6) Triangulate the monotone polygons directly into a vertex buffer (polys_to_triangles()).
34  *
35  * For screenspace antialiasing, the algorithm is modified as follows:
36  *
37  * Run steps 1-5 above to produce polygons.
38  * 5b) Apply fill rules to extract boundary contours from the polygons (extract_boundaries()).
39  * 5c) Simplify boundaries to remove "pointy" vertices that cause inversions (simplify_boundary()).
40  * 5d) Displace edges by half a pixel inward and outward along their normals. Intersect to find
41  *     new vertices, and set zero alpha on the exterior and one alpha on the interior. Build a new
42  *     antialiased mesh from those vertices (stroke_boundary()).
43  * Run steps 3-6 above on the new mesh, and produce antialiased triangles.
44  *
45  * The vertex sorting in step (3) is a merge sort, since it plays well with the linked list
46  * of vertices (and the necessity of inserting new vertices on intersection).
47  *
48  * Stages (4) and (5) use an active edge list -- a list of all edges for which the
49  * sweep line has crossed the top vertex, but not the bottom vertex.  It's sorted
50  * left-to-right based on the point where both edges are active (when both top vertices
51  * have been seen, so the "lower" top vertex of the two). If the top vertices are equal
52  * (shared), it's sorted based on the last point where both edges are active, so the
53  * "upper" bottom vertex.
54  *
55  * The most complex step is the simplification (4). It's based on the Bentley-Ottman
56  * line-sweep algorithm, but due to floating point inaccuracy, the intersection points are
57  * not exact and may violate the mesh topology or active edge list ordering. We
58  * accommodate this by adjusting the topology of the mesh and AEL to match the intersection
59  * points. This occurs in two ways:
60  *
61  * A) Intersections may cause a shortened edge to no longer be ordered with respect to its
62  *    neighbouring edges at the top or bottom vertex. This is handled by merging the
63  *    edges (merge_collinear_edges()).
64  * B) Intersections may cause an edge to violate the left-to-right ordering of the
65  *    active edge list. This is handled during merging or splitting by rewind()ing the
66  *    active edge list to the vertex before potential violations occur.
67  *
68  * The tessellation steps (5) and (6) are based on "Triangulating Simple Polygons and
69  * Equivalent Problems" (Fournier and Montuno); also a line-sweep algorithm. Note that it
70  * currently uses a linked list for the active edge list, rather than a 2-3 tree as the
71  * paper describes. The 2-3 tree gives O(lg N) lookups, but insertion and removal also
72  * become O(lg N). In all the test cases, it was found that the cost of frequent O(lg N)
73  * insertions and removals was greater than the cost of infrequent O(N) lookups with the
74  * linked list implementation. With the latter, all removals are O(1), and most insertions
75  * are O(1), since we know the adjacent edge in the active edge list based on the topology.
76  * Only type 2 vertices (see paper) require the O(N) lookups, and these are much less
77  * frequent. There may be other data structures worth investigating, however.
78  *
79  * Note that the orientation of the line sweep algorithms is determined by the aspect ratio of the
80  * path bounds. When the path is taller than it is wide, we sort vertices based on increasing Y
81  * coordinate, and secondarily by increasing X coordinate. When the path is wider than it is tall,
82  * we sort by increasing X coordinate, but secondarily by *decreasing* Y coordinate. This is so
83  * that the "left" and "right" orientation in the code remains correct (edges to the left are
84  * increasing in Y; edges to the right are decreasing in Y). That is, the setting rotates 90
85  * degrees counterclockwise, rather that transposing.
86  */
87 
88 #define LOGGING_ENABLED 0
89 
90 #if LOGGING_ENABLED
91 #define LOG printf
92 #else
93 #define LOG(...)
94 #endif
95 
96 namespace {
97 
98 const int kArenaChunkSize = 16 * 1024;
99 const float kCosMiterAngle = 0.97f; // Corresponds to an angle of ~14 degrees.
100 
101 struct Vertex;
102 struct Edge;
103 struct Event;
104 struct Poly;
105 
106 template <class T, T* T::*Prev, T* T::*Next>
list_insert(T * t,T * prev,T * next,T ** head,T ** tail)107 void list_insert(T* t, T* prev, T* next, T** head, T** tail) {
108     t->*Prev = prev;
109     t->*Next = next;
110     if (prev) {
111         prev->*Next = t;
112     } else if (head) {
113         *head = t;
114     }
115     if (next) {
116         next->*Prev = t;
117     } else if (tail) {
118         *tail = t;
119     }
120 }
121 
122 template <class T, T* T::*Prev, T* T::*Next>
list_remove(T * t,T ** head,T ** tail)123 void list_remove(T* t, T** head, T** tail) {
124     if (t->*Prev) {
125         t->*Prev->*Next = t->*Next;
126     } else if (head) {
127         *head = t->*Next;
128     }
129     if (t->*Next) {
130         t->*Next->*Prev = t->*Prev;
131     } else if (tail) {
132         *tail = t->*Prev;
133     }
134     t->*Prev = t->*Next = nullptr;
135 }
136 
137 /**
138  * Vertices are used in three ways: first, the path contours are converted into a
139  * circularly-linked list of Vertices for each contour. After edge construction, the same Vertices
140  * are re-ordered by the merge sort according to the sweep_lt comparator (usually, increasing
141  * in Y) using the same fPrev/fNext pointers that were used for the contours, to avoid
142  * reallocation. Finally, MonotonePolys are built containing a circularly-linked list of
143  * Vertices. (Currently, those Vertices are newly-allocated for the MonotonePolys, since
144  * an individual Vertex from the path mesh may belong to multiple
145  * MonotonePolys, so the original Vertices cannot be re-used.
146  */
147 
148 struct Vertex {
Vertex__anonbcd5ee210111::Vertex149   Vertex(const SkPoint& point, uint8_t alpha)
150     : fPoint(point), fPrev(nullptr), fNext(nullptr)
151     , fFirstEdgeAbove(nullptr), fLastEdgeAbove(nullptr)
152     , fFirstEdgeBelow(nullptr), fLastEdgeBelow(nullptr)
153     , fLeftEnclosingEdge(nullptr), fRightEnclosingEdge(nullptr)
154     , fPartner(nullptr)
155     , fAlpha(alpha)
156     , fSynthetic(false)
157 #if LOGGING_ENABLED
158     , fID (-1.0f)
159 #endif
160     {}
161     SkPoint fPoint;               // Vertex position
162     Vertex* fPrev;                // Linked list of contours, then Y-sorted vertices.
163     Vertex* fNext;                // "
164     Edge*   fFirstEdgeAbove;      // Linked list of edges above this vertex.
165     Edge*   fLastEdgeAbove;       // "
166     Edge*   fFirstEdgeBelow;      // Linked list of edges below this vertex.
167     Edge*   fLastEdgeBelow;       // "
168     Edge*   fLeftEnclosingEdge;   // Nearest edge in the AEL left of this vertex.
169     Edge*   fRightEnclosingEdge;  // Nearest edge in the AEL right of this vertex.
170     Vertex* fPartner;             // Corresponding inner or outer vertex (for AA).
171     uint8_t fAlpha;
172     bool    fSynthetic;           // Is this a synthetic vertex?
173 #if LOGGING_ENABLED
174     float   fID;                  // Identifier used for logging.
175 #endif
176 };
177 
178 /***************************************************************************************/
179 
180 typedef bool (*CompareFunc)(const SkPoint& a, const SkPoint& b);
181 
sweep_lt_horiz(const SkPoint & a,const SkPoint & b)182 bool sweep_lt_horiz(const SkPoint& a, const SkPoint& b) {
183     return a.fX < b.fX || (a.fX == b.fX && a.fY > b.fY);
184 }
185 
sweep_lt_vert(const SkPoint & a,const SkPoint & b)186 bool sweep_lt_vert(const SkPoint& a, const SkPoint& b) {
187     return a.fY < b.fY || (a.fY == b.fY && a.fX < b.fX);
188 }
189 
190 struct Comparator {
191     enum class Direction { kVertical, kHorizontal };
Comparator__anonbcd5ee210111::Comparator192     Comparator(Direction direction) : fDirection(direction) {}
sweep_lt__anonbcd5ee210111::Comparator193     bool sweep_lt(const SkPoint& a, const SkPoint& b) const {
194         return fDirection == Direction::kHorizontal ? sweep_lt_horiz(a, b) : sweep_lt_vert(a, b);
195     }
196     Direction fDirection;
197 };
198 
emit_vertex(Vertex * v,bool emitCoverage,void * data)199 inline void* emit_vertex(Vertex* v, bool emitCoverage, void* data) {
200     GrVertexWriter verts{data};
201     verts.write(v->fPoint);
202 
203     if (emitCoverage) {
204         verts.write(GrNormalizeByteToFloat(v->fAlpha));
205     }
206 
207     return verts.fPtr;
208 }
209 
emit_triangle(Vertex * v0,Vertex * v1,Vertex * v2,bool emitCoverage,void * data)210 void* emit_triangle(Vertex* v0, Vertex* v1, Vertex* v2, bool emitCoverage, void* data) {
211     LOG("emit_triangle %g (%g, %g) %d\n", v0->fID, v0->fPoint.fX, v0->fPoint.fY, v0->fAlpha);
212     LOG("              %g (%g, %g) %d\n", v1->fID, v1->fPoint.fX, v1->fPoint.fY, v1->fAlpha);
213     LOG("              %g (%g, %g) %d\n", v2->fID, v2->fPoint.fX, v2->fPoint.fY, v2->fAlpha);
214 #if TESSELLATOR_WIREFRAME
215     data = emit_vertex(v0, emitCoverage, data);
216     data = emit_vertex(v1, emitCoverage, data);
217     data = emit_vertex(v1, emitCoverage, data);
218     data = emit_vertex(v2, emitCoverage, data);
219     data = emit_vertex(v2, emitCoverage, data);
220     data = emit_vertex(v0, emitCoverage, data);
221 #else
222     data = emit_vertex(v0, emitCoverage, data);
223     data = emit_vertex(v1, emitCoverage, data);
224     data = emit_vertex(v2, emitCoverage, data);
225 #endif
226     return data;
227 }
228 
229 struct VertexList {
VertexList__anonbcd5ee210111::VertexList230     VertexList() : fHead(nullptr), fTail(nullptr) {}
VertexList__anonbcd5ee210111::VertexList231     VertexList(Vertex* head, Vertex* tail) : fHead(head), fTail(tail) {}
232     Vertex* fHead;
233     Vertex* fTail;
insert__anonbcd5ee210111::VertexList234     void insert(Vertex* v, Vertex* prev, Vertex* next) {
235         list_insert<Vertex, &Vertex::fPrev, &Vertex::fNext>(v, prev, next, &fHead, &fTail);
236     }
append__anonbcd5ee210111::VertexList237     void append(Vertex* v) {
238         insert(v, fTail, nullptr);
239     }
append__anonbcd5ee210111::VertexList240     void append(const VertexList& list) {
241         if (!list.fHead) {
242             return;
243         }
244         if (fTail) {
245             fTail->fNext = list.fHead;
246             list.fHead->fPrev = fTail;
247         } else {
248             fHead = list.fHead;
249         }
250         fTail = list.fTail;
251     }
prepend__anonbcd5ee210111::VertexList252     void prepend(Vertex* v) {
253         insert(v, nullptr, fHead);
254     }
remove__anonbcd5ee210111::VertexList255     void remove(Vertex* v) {
256         list_remove<Vertex, &Vertex::fPrev, &Vertex::fNext>(v, &fHead, &fTail);
257     }
close__anonbcd5ee210111::VertexList258     void close() {
259         if (fHead && fTail) {
260             fTail->fNext = fHead;
261             fHead->fPrev = fTail;
262         }
263     }
264 };
265 
266 // Round to nearest quarter-pixel. This is used for screenspace tessellation.
267 
round(SkPoint * p)268 inline void round(SkPoint* p) {
269     p->fX = SkScalarRoundToScalar(p->fX * SkFloatToScalar(4.0f)) * SkFloatToScalar(0.25f);
270     p->fY = SkScalarRoundToScalar(p->fY * SkFloatToScalar(4.0f)) * SkFloatToScalar(0.25f);
271 }
272 
double_to_clamped_scalar(double d)273 inline SkScalar double_to_clamped_scalar(double d) {
274     return SkDoubleToScalar(std::min((double) SK_ScalarMax, std::max(d, (double) -SK_ScalarMax)));
275 }
276 
277 // A line equation in implicit form. fA * x + fB * y + fC = 0, for all points (x, y) on the line.
278 struct Line {
Line__anonbcd5ee210111::Line279     Line(double a, double b, double c) : fA(a), fB(b), fC(c) {}
Line__anonbcd5ee210111::Line280     Line(Vertex* p, Vertex* q) : Line(p->fPoint, q->fPoint) {}
Line__anonbcd5ee210111::Line281     Line(const SkPoint& p, const SkPoint& q)
282         : fA(static_cast<double>(q.fY) - p.fY)      // a = dY
283         , fB(static_cast<double>(p.fX) - q.fX)      // b = -dX
284         , fC(static_cast<double>(p.fY) * q.fX -     // c = cross(q, p)
285              static_cast<double>(p.fX) * q.fY) {}
dist__anonbcd5ee210111::Line286     double dist(const SkPoint& p) const {
287         return fA * p.fX + fB * p.fY + fC;
288     }
operator *__anonbcd5ee210111::Line289     Line operator*(double v) const {
290         return Line(fA * v, fB * v, fC * v);
291     }
magSq__anonbcd5ee210111::Line292     double magSq() const {
293         return fA * fA + fB * fB;
294     }
normalize__anonbcd5ee210111::Line295     void normalize() {
296         double len = sqrt(this->magSq());
297         if (len == 0.0) {
298             return;
299         }
300         double scale = 1.0f / len;
301         fA *= scale;
302         fB *= scale;
303         fC *= scale;
304     }
nearParallel__anonbcd5ee210111::Line305     bool nearParallel(const Line& o) const {
306         return fabs(o.fA - fA) < 0.00001 && fabs(o.fB - fB) < 0.00001;
307     }
308 
309     // Compute the intersection of two (infinite) Lines.
intersect__anonbcd5ee210111::Line310     bool intersect(const Line& other, SkPoint* point) const {
311         double denom = fA * other.fB - fB * other.fA;
312         if (denom == 0.0) {
313             return false;
314         }
315         double scale = 1.0 / denom;
316         point->fX = double_to_clamped_scalar((fB * other.fC - other.fB * fC) * scale);
317         point->fY = double_to_clamped_scalar((other.fA * fC - fA * other.fC) * scale);
318         round(point);
319         return point->isFinite();
320     }
321     double fA, fB, fC;
322 };
323 
324 /**
325  * An Edge joins a top Vertex to a bottom Vertex. Edge ordering for the list of "edges above" and
326  * "edge below" a vertex as well as for the active edge list is handled by isLeftOf()/isRightOf().
327  * Note that an Edge will give occasionally dist() != 0 for its own endpoints (because floating
328  * point). For speed, that case is only tested by the callers that require it. Edges also handle
329  * checking for intersection with other edges.  Currently, this converts the edges to the
330  * parametric form, in order to avoid doing a division until an intersection has been confirmed.
331  * This is slightly slower in the "found" case, but a lot faster in the "not found" case.
332  *
333  * The coefficients of the line equation stored in double precision to avoid catastrphic
334  * cancellation in the isLeftOf() and isRightOf() checks. Using doubles ensures that the result is
335  * correct in float, since it's a polynomial of degree 2. The intersect() function, being
336  * degree 5, is still subject to catastrophic cancellation. We deal with that by assuming its
337  * output may be incorrect, and adjusting the mesh topology to match (see comment at the top of
338  * this file).
339  */
340 
341 struct Edge {
342     enum class Type { kInner, kOuter, kConnector };
Edge__anonbcd5ee210111::Edge343     Edge(Vertex* top, Vertex* bottom, int winding, Type type)
344         : fWinding(winding)
345         , fTop(top)
346         , fBottom(bottom)
347         , fType(type)
348         , fLeft(nullptr)
349         , fRight(nullptr)
350         , fPrevEdgeAbove(nullptr)
351         , fNextEdgeAbove(nullptr)
352         , fPrevEdgeBelow(nullptr)
353         , fNextEdgeBelow(nullptr)
354         , fLeftPoly(nullptr)
355         , fRightPoly(nullptr)
356         , fLeftPolyPrev(nullptr)
357         , fLeftPolyNext(nullptr)
358         , fRightPolyPrev(nullptr)
359         , fRightPolyNext(nullptr)
360         , fUsedInLeftPoly(false)
361         , fUsedInRightPoly(false)
362         , fLine(top, bottom) {
363         }
364     int      fWinding;          // 1 == edge goes downward; -1 = edge goes upward.
365     Vertex*  fTop;              // The top vertex in vertex-sort-order (sweep_lt).
366     Vertex*  fBottom;           // The bottom vertex in vertex-sort-order.
367     Type     fType;
368     Edge*    fLeft;             // The linked list of edges in the active edge list.
369     Edge*    fRight;            // "
370     Edge*    fPrevEdgeAbove;    // The linked list of edges in the bottom Vertex's "edges above".
371     Edge*    fNextEdgeAbove;    // "
372     Edge*    fPrevEdgeBelow;    // The linked list of edges in the top Vertex's "edges below".
373     Edge*    fNextEdgeBelow;    // "
374     Poly*    fLeftPoly;         // The Poly to the left of this edge, if any.
375     Poly*    fRightPoly;        // The Poly to the right of this edge, if any.
376     Edge*    fLeftPolyPrev;
377     Edge*    fLeftPolyNext;
378     Edge*    fRightPolyPrev;
379     Edge*    fRightPolyNext;
380     bool     fUsedInLeftPoly;
381     bool     fUsedInRightPoly;
382     Line     fLine;
dist__anonbcd5ee210111::Edge383     double dist(const SkPoint& p) const {
384         return fLine.dist(p);
385     }
isRightOf__anonbcd5ee210111::Edge386     bool isRightOf(Vertex* v) const {
387         return fLine.dist(v->fPoint) < 0.0;
388     }
isLeftOf__anonbcd5ee210111::Edge389     bool isLeftOf(Vertex* v) const {
390         return fLine.dist(v->fPoint) > 0.0;
391     }
recompute__anonbcd5ee210111::Edge392     void recompute() {
393         fLine = Line(fTop, fBottom);
394     }
intersect__anonbcd5ee210111::Edge395     bool intersect(const Edge& other, SkPoint* p, uint8_t* alpha = nullptr) const {
396         LOG("intersecting %g -> %g with %g -> %g\n",
397                fTop->fID, fBottom->fID,
398                other.fTop->fID, other.fBottom->fID);
399         if (fTop == other.fTop || fBottom == other.fBottom) {
400             return false;
401         }
402         double denom = fLine.fA * other.fLine.fB - fLine.fB * other.fLine.fA;
403         if (denom == 0.0) {
404             return false;
405         }
406         double dx = static_cast<double>(other.fTop->fPoint.fX) - fTop->fPoint.fX;
407         double dy = static_cast<double>(other.fTop->fPoint.fY) - fTop->fPoint.fY;
408         double sNumer = dy * other.fLine.fB + dx * other.fLine.fA;
409         double tNumer = dy * fLine.fB + dx * fLine.fA;
410         // If (sNumer / denom) or (tNumer / denom) is not in [0..1], exit early.
411         // This saves us doing the divide below unless absolutely necessary.
412         if (denom > 0.0 ? (sNumer < 0.0 || sNumer > denom || tNumer < 0.0 || tNumer > denom)
413                         : (sNumer > 0.0 || sNumer < denom || tNumer > 0.0 || tNumer < denom)) {
414             return false;
415         }
416         double s = sNumer / denom;
417         SkASSERT(s >= 0.0 && s <= 1.0);
418         p->fX = SkDoubleToScalar(fTop->fPoint.fX - s * fLine.fB);
419         p->fY = SkDoubleToScalar(fTop->fPoint.fY + s * fLine.fA);
420         if (alpha) {
421             if (fType == Type::kConnector) {
422                 *alpha = (1.0 - s) * fTop->fAlpha + s * fBottom->fAlpha;
423             } else if (other.fType == Type::kConnector) {
424                 double t = tNumer / denom;
425                 *alpha = (1.0 - t) * other.fTop->fAlpha + t * other.fBottom->fAlpha;
426             } else if (fType == Type::kOuter && other.fType == Type::kOuter) {
427                 *alpha = 0;
428             } else {
429                 *alpha = 255;
430             }
431         }
432         return true;
433     }
434 };
435 
436 struct SSEdge;
437 
438 struct SSVertex {
SSVertex__anonbcd5ee210111::SSVertex439     SSVertex(Vertex* v) : fVertex(v), fPrev(nullptr), fNext(nullptr) {}
440     Vertex* fVertex;
441     SSEdge* fPrev;
442     SSEdge* fNext;
443 };
444 
445 struct SSEdge {
SSEdge__anonbcd5ee210111::SSEdge446     SSEdge(Edge* edge, SSVertex* prev, SSVertex* next)
447       : fEdge(edge), fEvent(nullptr), fPrev(prev), fNext(next) {
448     }
449     Edge*     fEdge;
450     Event*    fEvent;
451     SSVertex* fPrev;
452     SSVertex* fNext;
453 };
454 
455 typedef std::unordered_map<Vertex*, SSVertex*> SSVertexMap;
456 typedef std::vector<SSEdge*> SSEdgeList;
457 
458 struct EdgeList {
EdgeList__anonbcd5ee210111::EdgeList459     EdgeList() : fHead(nullptr), fTail(nullptr) {}
460     Edge* fHead;
461     Edge* fTail;
insert__anonbcd5ee210111::EdgeList462     void insert(Edge* edge, Edge* prev, Edge* next) {
463         list_insert<Edge, &Edge::fLeft, &Edge::fRight>(edge, prev, next, &fHead, &fTail);
464     }
append__anonbcd5ee210111::EdgeList465     void append(Edge* e) {
466         insert(e, fTail, nullptr);
467     }
remove__anonbcd5ee210111::EdgeList468     void remove(Edge* edge) {
469         list_remove<Edge, &Edge::fLeft, &Edge::fRight>(edge, &fHead, &fTail);
470     }
removeAll__anonbcd5ee210111::EdgeList471     void removeAll() {
472         while (fHead) {
473             this->remove(fHead);
474         }
475     }
close__anonbcd5ee210111::EdgeList476     void close() {
477         if (fHead && fTail) {
478             fTail->fRight = fHead;
479             fHead->fLeft = fTail;
480         }
481     }
contains__anonbcd5ee210111::EdgeList482     bool contains(Edge* edge) const {
483         return edge->fLeft || edge->fRight || fHead == edge;
484     }
485 };
486 
487 struct EventList;
488 
489 struct Event {
Event__anonbcd5ee210111::Event490     Event(SSEdge* edge, const SkPoint& point, uint8_t alpha)
491       : fEdge(edge), fPoint(point), fAlpha(alpha) {
492     }
493     SSEdge* fEdge;
494     SkPoint fPoint;
495     uint8_t fAlpha;
496     void apply(VertexList* mesh, Comparator& c, EventList* events, SkArenaAlloc& alloc);
497 };
498 
499 struct EventComparator {
500     enum class Op { kLessThan, kGreaterThan };
EventComparator__anonbcd5ee210111::EventComparator501     EventComparator(Op op) : fOp(op) {}
operator ()__anonbcd5ee210111::EventComparator502     bool operator() (Event* const &e1, Event* const &e2) {
503         return fOp == Op::kLessThan ? e1->fAlpha < e2->fAlpha
504                                     : e1->fAlpha > e2->fAlpha;
505     }
506     Op fOp;
507 };
508 
509 typedef  std::priority_queue<Event*, std::vector<Event*>, EventComparator> EventPQ;
510 
511 struct EventList : EventPQ {
EventList__anonbcd5ee210111::EventList512     EventList(EventComparator comparison) : EventPQ(comparison) {
513     }
514 };
515 
create_event(SSEdge * e,EventList * events,SkArenaAlloc & alloc)516 void create_event(SSEdge* e, EventList* events, SkArenaAlloc& alloc) {
517     Vertex* prev = e->fPrev->fVertex;
518     Vertex* next = e->fNext->fVertex;
519     if (prev == next || !prev->fPartner || !next->fPartner) {
520         return;
521     }
522     Edge bisector1(prev, prev->fPartner, 1, Edge::Type::kConnector);
523     Edge bisector2(next, next->fPartner, 1, Edge::Type::kConnector);
524     SkPoint p;
525     uint8_t alpha;
526     if (bisector1.intersect(bisector2, &p, &alpha)) {
527         LOG("found edge event for %g, %g (original %g -> %g), will collapse to %g,%g alpha %d\n",
528             prev->fID, next->fID, e->fEdge->fTop->fID, e->fEdge->fBottom->fID, p.fX, p.fY, alpha);
529         e->fEvent = alloc.make<Event>(e, p, alpha);
530         events->push(e->fEvent);
531     }
532 }
533 
create_event(SSEdge * edge,Vertex * v,SSEdge * other,Vertex * dest,EventList * events,Comparator & c,SkArenaAlloc & alloc)534 void create_event(SSEdge* edge, Vertex* v, SSEdge* other, Vertex* dest, EventList* events,
535                   Comparator& c, SkArenaAlloc& alloc) {
536     if (!v->fPartner) {
537         return;
538     }
539     Vertex* top = edge->fEdge->fTop;
540     Vertex* bottom = edge->fEdge->fBottom;
541     if (!top || !bottom ) {
542         return;
543     }
544     Line line = edge->fEdge->fLine;
545     line.fC = -(dest->fPoint.fX * line.fA  + dest->fPoint.fY * line.fB);
546     Edge bisector(v, v->fPartner, 1, Edge::Type::kConnector);
547     SkPoint p;
548     uint8_t alpha = dest->fAlpha;
549     if (line.intersect(bisector.fLine, &p) && !c.sweep_lt(p, top->fPoint) &&
550                                                c.sweep_lt(p, bottom->fPoint)) {
551         LOG("found p edge event for %g, %g (original %g -> %g), will collapse to %g,%g alpha %d\n",
552             dest->fID, v->fID, top->fID, bottom->fID, p.fX, p.fY, alpha);
553         edge->fEvent = alloc.make<Event>(edge, p, alpha);
554         events->push(edge->fEvent);
555     }
556 }
557 
558 /***************************************************************************************/
559 
560 struct Poly {
Poly__anonbcd5ee210111::Poly561     Poly(Vertex* v, int winding)
562         : fFirstVertex(v)
563         , fWinding(winding)
564         , fHead(nullptr)
565         , fTail(nullptr)
566         , fNext(nullptr)
567         , fPartner(nullptr)
568         , fCount(0)
569     {
570 #if LOGGING_ENABLED
571         static int gID = 0;
572         fID = gID++;
573         LOG("*** created Poly %d\n", fID);
574 #endif
575     }
576     typedef enum { kLeft_Side, kRight_Side } Side;
577     struct MonotonePoly {
MonotonePoly__anonbcd5ee210111::Poly::MonotonePoly578         MonotonePoly(Edge* edge, Side side)
579             : fSide(side)
580             , fFirstEdge(nullptr)
581             , fLastEdge(nullptr)
582             , fPrev(nullptr)
583             , fNext(nullptr) {
584             this->addEdge(edge);
585         }
586         Side          fSide;
587         Edge*         fFirstEdge;
588         Edge*         fLastEdge;
589         MonotonePoly* fPrev;
590         MonotonePoly* fNext;
addEdge__anonbcd5ee210111::Poly::MonotonePoly591         void addEdge(Edge* edge) {
592             if (fSide == kRight_Side) {
593                 SkASSERT(!edge->fUsedInRightPoly);
594                 list_insert<Edge, &Edge::fRightPolyPrev, &Edge::fRightPolyNext>(
595                     edge, fLastEdge, nullptr, &fFirstEdge, &fLastEdge);
596                 edge->fUsedInRightPoly = true;
597             } else {
598                 SkASSERT(!edge->fUsedInLeftPoly);
599                 list_insert<Edge, &Edge::fLeftPolyPrev, &Edge::fLeftPolyNext>(
600                     edge, fLastEdge, nullptr, &fFirstEdge, &fLastEdge);
601                 edge->fUsedInLeftPoly = true;
602             }
603         }
604 
emit__anonbcd5ee210111::Poly::MonotonePoly605         void* emit(bool emitCoverage, void* data) {
606             Edge* e = fFirstEdge;
607             VertexList vertices;
608             vertices.append(e->fTop);
609             int count = 1;
610             while (e != nullptr) {
611                 if (kRight_Side == fSide) {
612                     vertices.append(e->fBottom);
613                     e = e->fRightPolyNext;
614                 } else {
615                     vertices.prepend(e->fBottom);
616                     e = e->fLeftPolyNext;
617                 }
618                 count++;
619             }
620             Vertex* first = vertices.fHead;
621             Vertex* v = first->fNext;
622             while (v != vertices.fTail) {
623                 SkASSERT(v && v->fPrev && v->fNext);
624                 Vertex* prev = v->fPrev;
625                 Vertex* curr = v;
626                 Vertex* next = v->fNext;
627                 if (count == 3) {
628                     return emit_triangle(prev, curr, next, emitCoverage, data);
629                 }
630                 double ax = static_cast<double>(curr->fPoint.fX) - prev->fPoint.fX;
631                 double ay = static_cast<double>(curr->fPoint.fY) - prev->fPoint.fY;
632                 double bx = static_cast<double>(next->fPoint.fX) - curr->fPoint.fX;
633                 double by = static_cast<double>(next->fPoint.fY) - curr->fPoint.fY;
634                 if (ax * by - ay * bx >= 0.0) {
635                     data = emit_triangle(prev, curr, next, emitCoverage, data);
636                     v->fPrev->fNext = v->fNext;
637                     v->fNext->fPrev = v->fPrev;
638                     count--;
639                     if (v->fPrev == first) {
640                         v = v->fNext;
641                     } else {
642                         v = v->fPrev;
643                     }
644                 } else {
645                     v = v->fNext;
646                 }
647             }
648             return data;
649         }
650     };
addEdge__anonbcd5ee210111::Poly651     Poly* addEdge(Edge* e, Side side, SkArenaAlloc& alloc) {
652         LOG("addEdge (%g -> %g) to poly %d, %s side\n",
653                e->fTop->fID, e->fBottom->fID, fID, side == kLeft_Side ? "left" : "right");
654         Poly* partner = fPartner;
655         Poly* poly = this;
656         if (side == kRight_Side) {
657             if (e->fUsedInRightPoly) {
658                 return this;
659             }
660         } else {
661             if (e->fUsedInLeftPoly) {
662                 return this;
663             }
664         }
665         if (partner) {
666             fPartner = partner->fPartner = nullptr;
667         }
668         if (!fTail) {
669             fHead = fTail = alloc.make<MonotonePoly>(e, side);
670             fCount += 2;
671         } else if (e->fBottom == fTail->fLastEdge->fBottom) {
672             return poly;
673         } else if (side == fTail->fSide) {
674             fTail->addEdge(e);
675             fCount++;
676         } else {
677             e = alloc.make<Edge>(fTail->fLastEdge->fBottom, e->fBottom, 1, Edge::Type::kInner);
678             fTail->addEdge(e);
679             fCount++;
680             if (partner) {
681                 partner->addEdge(e, side, alloc);
682                 poly = partner;
683             } else {
684                 MonotonePoly* m = alloc.make<MonotonePoly>(e, side);
685                 m->fPrev = fTail;
686                 fTail->fNext = m;
687                 fTail = m;
688             }
689         }
690         return poly;
691     }
emit__anonbcd5ee210111::Poly692     void* emit(bool emitCoverage, void *data) {
693         if (fCount < 3) {
694             return data;
695         }
696         LOG("emit() %d, size %d\n", fID, fCount);
697         for (MonotonePoly* m = fHead; m != nullptr; m = m->fNext) {
698             data = m->emit(emitCoverage, data);
699         }
700         return data;
701     }
lastVertex__anonbcd5ee210111::Poly702     Vertex* lastVertex() const { return fTail ? fTail->fLastEdge->fBottom : fFirstVertex; }
703     Vertex* fFirstVertex;
704     int fWinding;
705     MonotonePoly* fHead;
706     MonotonePoly* fTail;
707     Poly* fNext;
708     Poly* fPartner;
709     int fCount;
710 #if LOGGING_ENABLED
711     int fID;
712 #endif
713 };
714 
715 /***************************************************************************************/
716 
coincident(const SkPoint & a,const SkPoint & b)717 bool coincident(const SkPoint& a, const SkPoint& b) {
718     return a == b;
719 }
720 
new_poly(Poly ** head,Vertex * v,int winding,SkArenaAlloc & alloc)721 Poly* new_poly(Poly** head, Vertex* v, int winding, SkArenaAlloc& alloc) {
722     Poly* poly = alloc.make<Poly>(v, winding);
723     poly->fNext = *head;
724     *head = poly;
725     return poly;
726 }
727 
append_point_to_contour(const SkPoint & p,VertexList * contour,SkArenaAlloc & alloc)728 void append_point_to_contour(const SkPoint& p, VertexList* contour, SkArenaAlloc& alloc) {
729     Vertex* v = alloc.make<Vertex>(p, 255);
730 #if LOGGING_ENABLED
731     static float gID = 0.0f;
732     v->fID = gID++;
733 #endif
734     contour->append(v);
735 }
736 
quad_error_at(const SkPoint pts[3],SkScalar t,SkScalar u)737 SkScalar quad_error_at(const SkPoint pts[3], SkScalar t, SkScalar u) {
738     SkQuadCoeff quad(pts);
739     SkPoint p0 = to_point(quad.eval(t - 0.5f * u));
740     SkPoint mid = to_point(quad.eval(t));
741     SkPoint p1 = to_point(quad.eval(t + 0.5f * u));
742     if (!p0.isFinite() || !mid.isFinite() || !p1.isFinite()) {
743         return 0;
744     }
745     return SkPointPriv::DistanceToLineSegmentBetweenSqd(mid, p0, p1);
746 }
747 
append_quadratic_to_contour(const SkPoint pts[3],SkScalar toleranceSqd,VertexList * contour,SkArenaAlloc & alloc)748 void append_quadratic_to_contour(const SkPoint pts[3], SkScalar toleranceSqd, VertexList* contour,
749                                  SkArenaAlloc& alloc) {
750     SkQuadCoeff quad(pts);
751     Sk2s aa = quad.fA * quad.fA;
752     SkScalar denom = 2.0f * (aa[0] + aa[1]);
753     Sk2s ab = quad.fA * quad.fB;
754     SkScalar t = denom ? (-ab[0] - ab[1]) / denom : 0.0f;
755     int nPoints = 1;
756     SkScalar u = 1.0f;
757     // Test possible subdivision values only at the point of maximum curvature.
758     // If it passes the flatness metric there, it'll pass everywhere.
759     while (nPoints < GrPathUtils::kMaxPointsPerCurve) {
760         u = 1.0f / nPoints;
761         if (quad_error_at(pts, t, u) < toleranceSqd) {
762             break;
763         }
764         nPoints++;
765     }
766     for (int j = 1; j <= nPoints; j++) {
767         append_point_to_contour(to_point(quad.eval(j * u)), contour, alloc);
768     }
769 }
770 
generate_cubic_points(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2,const SkPoint & p3,SkScalar tolSqd,VertexList * contour,int pointsLeft,SkArenaAlloc & alloc)771 void generate_cubic_points(const SkPoint& p0,
772                            const SkPoint& p1,
773                            const SkPoint& p2,
774                            const SkPoint& p3,
775                            SkScalar tolSqd,
776                            VertexList* contour,
777                            int pointsLeft,
778                            SkArenaAlloc& alloc) {
779     SkScalar d1 = SkPointPriv::DistanceToLineSegmentBetweenSqd(p1, p0, p3);
780     SkScalar d2 = SkPointPriv::DistanceToLineSegmentBetweenSqd(p2, p0, p3);
781     if (pointsLeft < 2 || (d1 < tolSqd && d2 < tolSqd) ||
782         !SkScalarIsFinite(d1) || !SkScalarIsFinite(d2)) {
783         append_point_to_contour(p3, contour, alloc);
784         return;
785     }
786     const SkPoint q[] = {
787         { SkScalarAve(p0.fX, p1.fX), SkScalarAve(p0.fY, p1.fY) },
788         { SkScalarAve(p1.fX, p2.fX), SkScalarAve(p1.fY, p2.fY) },
789         { SkScalarAve(p2.fX, p3.fX), SkScalarAve(p2.fY, p3.fY) }
790     };
791     const SkPoint r[] = {
792         { SkScalarAve(q[0].fX, q[1].fX), SkScalarAve(q[0].fY, q[1].fY) },
793         { SkScalarAve(q[1].fX, q[2].fX), SkScalarAve(q[1].fY, q[2].fY) }
794     };
795     const SkPoint s = { SkScalarAve(r[0].fX, r[1].fX), SkScalarAve(r[0].fY, r[1].fY) };
796     pointsLeft >>= 1;
797     generate_cubic_points(p0, q[0], r[0], s, tolSqd, contour, pointsLeft, alloc);
798     generate_cubic_points(s, r[1], q[2], p3, tolSqd, contour, pointsLeft, alloc);
799 }
800 
801 // Stage 1: convert the input path to a set of linear contours (linked list of Vertices).
802 
path_to_contours(const SkPath & path,SkScalar tolerance,const SkRect & clipBounds,VertexList * contours,SkArenaAlloc & alloc,bool * isLinear)803 void path_to_contours(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
804                       VertexList* contours, SkArenaAlloc& alloc, bool *isLinear) {
805     SkScalar toleranceSqd = tolerance * tolerance;
806 
807     SkPoint pts[4];
808     *isLinear = true;
809     VertexList* contour = contours;
810     SkPath::Iter iter(path, false);
811     if (path.isInverseFillType()) {
812         SkPoint quad[4];
813         clipBounds.toQuad(quad);
814         for (int i = 3; i >= 0; i--) {
815             append_point_to_contour(quad[i], contours, alloc);
816         }
817         contour++;
818     }
819     SkAutoConicToQuads converter;
820     SkPath::Verb verb;
821     while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
822         switch (verb) {
823             case SkPath::kConic_Verb: {
824                 SkScalar weight = iter.conicWeight();
825                 const SkPoint* quadPts = converter.computeQuads(pts, weight, toleranceSqd);
826                 for (int i = 0; i < converter.countQuads(); ++i) {
827                     append_quadratic_to_contour(quadPts, toleranceSqd, contour, alloc);
828                     quadPts += 2;
829                 }
830                 *isLinear = false;
831                 break;
832             }
833             case SkPath::kMove_Verb:
834                 if (contour->fHead) {
835                     contour++;
836                 }
837                 append_point_to_contour(pts[0], contour, alloc);
838                 break;
839             case SkPath::kLine_Verb: {
840                 append_point_to_contour(pts[1], contour, alloc);
841                 break;
842             }
843             case SkPath::kQuad_Verb: {
844                 append_quadratic_to_contour(pts, toleranceSqd, contour, alloc);
845                 *isLinear = false;
846                 break;
847             }
848             case SkPath::kCubic_Verb: {
849                 int pointsLeft = GrPathUtils::cubicPointCount(pts, tolerance);
850                 generate_cubic_points(pts[0], pts[1], pts[2], pts[3], toleranceSqd, contour,
851                                       pointsLeft, alloc);
852                 *isLinear = false;
853                 break;
854             }
855             case SkPath::kClose_Verb:
856             case SkPath::kDone_Verb:
857                 break;
858         }
859     }
860 }
861 
apply_fill_type(SkPath::FillType fillType,int winding)862 inline bool apply_fill_type(SkPath::FillType fillType, int winding) {
863     switch (fillType) {
864         case SkPath::kWinding_FillType:
865             return winding != 0;
866         case SkPath::kEvenOdd_FillType:
867             return (winding & 1) != 0;
868         case SkPath::kInverseWinding_FillType:
869             return winding == 1;
870         case SkPath::kInverseEvenOdd_FillType:
871             return (winding & 1) == 1;
872         default:
873             SkASSERT(false);
874             return false;
875     }
876 }
877 
apply_fill_type(SkPath::FillType fillType,Poly * poly)878 inline bool apply_fill_type(SkPath::FillType fillType, Poly* poly) {
879     return poly && apply_fill_type(fillType, poly->fWinding);
880 }
881 
new_edge(Vertex * prev,Vertex * next,Edge::Type type,Comparator & c,SkArenaAlloc & alloc)882 Edge* new_edge(Vertex* prev, Vertex* next, Edge::Type type, Comparator& c, SkArenaAlloc& alloc) {
883     int winding = c.sweep_lt(prev->fPoint, next->fPoint) ? 1 : -1;
884     Vertex* top = winding < 0 ? next : prev;
885     Vertex* bottom = winding < 0 ? prev : next;
886     return alloc.make<Edge>(top, bottom, winding, type);
887 }
888 
remove_edge(Edge * edge,EdgeList * edges)889 void remove_edge(Edge* edge, EdgeList* edges) {
890     LOG("removing edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
891     SkASSERT(edges->contains(edge));
892     edges->remove(edge);
893 }
894 
insert_edge(Edge * edge,Edge * prev,EdgeList * edges)895 void insert_edge(Edge* edge, Edge* prev, EdgeList* edges) {
896     LOG("inserting edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
897     SkASSERT(!edges->contains(edge));
898     Edge* next = prev ? prev->fRight : edges->fHead;
899     edges->insert(edge, prev, next);
900 }
901 
find_enclosing_edges(Vertex * v,EdgeList * edges,Edge ** left,Edge ** right)902 void find_enclosing_edges(Vertex* v, EdgeList* edges, Edge** left, Edge** right) {
903     if (v->fFirstEdgeAbove && v->fLastEdgeAbove) {
904         *left = v->fFirstEdgeAbove->fLeft;
905         *right = v->fLastEdgeAbove->fRight;
906         return;
907     }
908     Edge* next = nullptr;
909     Edge* prev;
910     for (prev = edges->fTail; prev != nullptr; prev = prev->fLeft) {
911         if (prev->isLeftOf(v)) {
912             break;
913         }
914         next = prev;
915     }
916     *left = prev;
917     *right = next;
918 }
919 
insert_edge_above(Edge * edge,Vertex * v,Comparator & c)920 void insert_edge_above(Edge* edge, Vertex* v, Comparator& c) {
921     if (edge->fTop->fPoint == edge->fBottom->fPoint ||
922         c.sweep_lt(edge->fBottom->fPoint, edge->fTop->fPoint)) {
923         return;
924     }
925     LOG("insert edge (%g -> %g) above vertex %g\n", edge->fTop->fID, edge->fBottom->fID, v->fID);
926     Edge* prev = nullptr;
927     Edge* next;
928     for (next = v->fFirstEdgeAbove; next; next = next->fNextEdgeAbove) {
929         if (next->isRightOf(edge->fTop)) {
930             break;
931         }
932         prev = next;
933     }
934     list_insert<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
935         edge, prev, next, &v->fFirstEdgeAbove, &v->fLastEdgeAbove);
936 }
937 
insert_edge_below(Edge * edge,Vertex * v,Comparator & c)938 void insert_edge_below(Edge* edge, Vertex* v, Comparator& c) {
939     if (edge->fTop->fPoint == edge->fBottom->fPoint ||
940         c.sweep_lt(edge->fBottom->fPoint, edge->fTop->fPoint)) {
941         return;
942     }
943     LOG("insert edge (%g -> %g) below vertex %g\n", edge->fTop->fID, edge->fBottom->fID, v->fID);
944     Edge* prev = nullptr;
945     Edge* next;
946     for (next = v->fFirstEdgeBelow; next; next = next->fNextEdgeBelow) {
947         if (next->isRightOf(edge->fBottom)) {
948             break;
949         }
950         prev = next;
951     }
952     list_insert<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
953         edge, prev, next, &v->fFirstEdgeBelow, &v->fLastEdgeBelow);
954 }
955 
remove_edge_above(Edge * edge)956 void remove_edge_above(Edge* edge) {
957     SkASSERT(edge->fTop && edge->fBottom);
958     LOG("removing edge (%g -> %g) above vertex %g\n", edge->fTop->fID, edge->fBottom->fID,
959         edge->fBottom->fID);
960     list_remove<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
961         edge, &edge->fBottom->fFirstEdgeAbove, &edge->fBottom->fLastEdgeAbove);
962 }
963 
remove_edge_below(Edge * edge)964 void remove_edge_below(Edge* edge) {
965     SkASSERT(edge->fTop && edge->fBottom);
966     LOG("removing edge (%g -> %g) below vertex %g\n", edge->fTop->fID, edge->fBottom->fID,
967         edge->fTop->fID);
968     list_remove<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
969         edge, &edge->fTop->fFirstEdgeBelow, &edge->fTop->fLastEdgeBelow);
970 }
971 
disconnect(Edge * edge)972 void disconnect(Edge* edge)
973 {
974     remove_edge_above(edge);
975     remove_edge_below(edge);
976 }
977 
978 void merge_collinear_edges(Edge* edge, EdgeList* activeEdges, Vertex** current, Comparator& c);
979 
rewind(EdgeList * activeEdges,Vertex ** current,Vertex * dst,Comparator & c)980 void rewind(EdgeList* activeEdges, Vertex** current, Vertex* dst, Comparator& c) {
981     if (!current || *current == dst || c.sweep_lt((*current)->fPoint, dst->fPoint)) {
982         return;
983     }
984     Vertex* v = *current;
985     LOG("rewinding active edges from vertex %g to vertex %g\n", v->fID, dst->fID);
986     while (v != dst) {
987         v = v->fPrev;
988         for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
989             remove_edge(e, activeEdges);
990         }
991         Edge* leftEdge = v->fLeftEnclosingEdge;
992         for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
993             insert_edge(e, leftEdge, activeEdges);
994             leftEdge = e;
995         }
996     }
997     *current = v;
998 }
999 
set_top(Edge * edge,Vertex * v,EdgeList * activeEdges,Vertex ** current,Comparator & c)1000 void set_top(Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current, Comparator& c) {
1001     remove_edge_below(edge);
1002     edge->fTop = v;
1003     edge->recompute();
1004     insert_edge_below(edge, v, c);
1005     rewind(activeEdges, current, edge->fTop, c);
1006     merge_collinear_edges(edge, activeEdges, current, c);
1007 }
1008 
set_bottom(Edge * edge,Vertex * v,EdgeList * activeEdges,Vertex ** current,Comparator & c)1009 void set_bottom(Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current, Comparator& c) {
1010     remove_edge_above(edge);
1011     edge->fBottom = v;
1012     edge->recompute();
1013     insert_edge_above(edge, v, c);
1014     rewind(activeEdges, current, edge->fTop, c);
1015     merge_collinear_edges(edge, activeEdges, current, c);
1016 }
1017 
merge_edges_above(Edge * edge,Edge * other,EdgeList * activeEdges,Vertex ** current,Comparator & c)1018 void merge_edges_above(Edge* edge, Edge* other, EdgeList* activeEdges, Vertex** current,
1019                        Comparator& c) {
1020     if (coincident(edge->fTop->fPoint, other->fTop->fPoint)) {
1021         LOG("merging coincident above edges (%g, %g) -> (%g, %g)\n",
1022             edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
1023             edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
1024         rewind(activeEdges, current, edge->fTop, c);
1025         other->fWinding += edge->fWinding;
1026         disconnect(edge);
1027         edge->fTop = edge->fBottom = nullptr;
1028     } else if (c.sweep_lt(edge->fTop->fPoint, other->fTop->fPoint)) {
1029         rewind(activeEdges, current, edge->fTop, c);
1030         other->fWinding += edge->fWinding;
1031         set_bottom(edge, other->fTop, activeEdges, current, c);
1032     } else {
1033         rewind(activeEdges, current, other->fTop, c);
1034         edge->fWinding += other->fWinding;
1035         set_bottom(other, edge->fTop, activeEdges, current, c);
1036     }
1037 }
1038 
merge_edges_below(Edge * edge,Edge * other,EdgeList * activeEdges,Vertex ** current,Comparator & c)1039 void merge_edges_below(Edge* edge, Edge* other, EdgeList* activeEdges, Vertex** current,
1040                        Comparator& c) {
1041     if (coincident(edge->fBottom->fPoint, other->fBottom->fPoint)) {
1042         LOG("merging coincident below edges (%g, %g) -> (%g, %g)\n",
1043             edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
1044             edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
1045         rewind(activeEdges, current, edge->fTop, c);
1046         other->fWinding += edge->fWinding;
1047         disconnect(edge);
1048         edge->fTop = edge->fBottom = nullptr;
1049     } else if (c.sweep_lt(edge->fBottom->fPoint, other->fBottom->fPoint)) {
1050         rewind(activeEdges, current, other->fTop, c);
1051         edge->fWinding += other->fWinding;
1052         set_top(other, edge->fBottom, activeEdges, current, c);
1053     } else {
1054         rewind(activeEdges, current, edge->fTop, c);
1055         other->fWinding += edge->fWinding;
1056         set_top(edge, other->fBottom, activeEdges, current, c);
1057     }
1058 }
1059 
top_collinear(Edge * left,Edge * right)1060 bool top_collinear(Edge* left, Edge* right) {
1061     if (!left || !right) {
1062         return false;
1063     }
1064     return left->fTop->fPoint == right->fTop->fPoint ||
1065            !left->isLeftOf(right->fTop) || !right->isRightOf(left->fTop);
1066 }
1067 
bottom_collinear(Edge * left,Edge * right)1068 bool bottom_collinear(Edge* left, Edge* right) {
1069     if (!left || !right) {
1070         return false;
1071     }
1072     return left->fBottom->fPoint == right->fBottom->fPoint ||
1073            !left->isLeftOf(right->fBottom) || !right->isRightOf(left->fBottom);
1074 }
1075 
merge_collinear_edges(Edge * edge,EdgeList * activeEdges,Vertex ** current,Comparator & c)1076 void merge_collinear_edges(Edge* edge, EdgeList* activeEdges, Vertex** current, Comparator& c) {
1077     for (;;) {
1078         if (top_collinear(edge->fPrevEdgeAbove, edge)) {
1079             merge_edges_above(edge->fPrevEdgeAbove, edge, activeEdges, current, c);
1080         } else if (top_collinear(edge, edge->fNextEdgeAbove)) {
1081             merge_edges_above(edge->fNextEdgeAbove, edge, activeEdges, current, c);
1082         } else if (bottom_collinear(edge->fPrevEdgeBelow, edge)) {
1083             merge_edges_below(edge->fPrevEdgeBelow, edge, activeEdges, current, c);
1084         } else if (bottom_collinear(edge, edge->fNextEdgeBelow)) {
1085             merge_edges_below(edge->fNextEdgeBelow, edge, activeEdges, current, c);
1086         } else {
1087             break;
1088         }
1089     }
1090     SkASSERT(!top_collinear(edge->fPrevEdgeAbove, edge));
1091     SkASSERT(!top_collinear(edge, edge->fNextEdgeAbove));
1092     SkASSERT(!bottom_collinear(edge->fPrevEdgeBelow, edge));
1093     SkASSERT(!bottom_collinear(edge, edge->fNextEdgeBelow));
1094 }
1095 
split_edge(Edge * edge,Vertex * v,EdgeList * activeEdges,Vertex ** current,Comparator & c,SkArenaAlloc & alloc)1096 bool split_edge(Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current, Comparator& c,
1097                 SkArenaAlloc& alloc) {
1098     if (!edge->fTop || !edge->fBottom || v == edge->fTop || v == edge->fBottom) {
1099         return false;
1100     }
1101     LOG("splitting edge (%g -> %g) at vertex %g (%g, %g)\n",
1102         edge->fTop->fID, edge->fBottom->fID,
1103         v->fID, v->fPoint.fX, v->fPoint.fY);
1104     Vertex* top;
1105     Vertex* bottom;
1106     int winding = edge->fWinding;
1107     if (c.sweep_lt(v->fPoint, edge->fTop->fPoint)) {
1108         top = v;
1109         bottom = edge->fTop;
1110         set_top(edge, v, activeEdges, current, c);
1111     } else if (c.sweep_lt(edge->fBottom->fPoint, v->fPoint)) {
1112         top = edge->fBottom;
1113         bottom = v;
1114         set_bottom(edge, v, activeEdges, current, c);
1115     } else {
1116         top = v;
1117         bottom = edge->fBottom;
1118         set_bottom(edge, v, activeEdges, current, c);
1119     }
1120     Edge* newEdge = alloc.make<Edge>(top, bottom, winding, edge->fType);
1121     insert_edge_below(newEdge, top, c);
1122     insert_edge_above(newEdge, bottom, c);
1123     merge_collinear_edges(newEdge, activeEdges, current, c);
1124     return true;
1125 }
1126 
intersect_edge_pair(Edge * left,Edge * right,EdgeList * activeEdges,Vertex ** current,Comparator & c,SkArenaAlloc & alloc)1127 bool intersect_edge_pair(Edge* left, Edge* right, EdgeList* activeEdges, Vertex** current, Comparator& c, SkArenaAlloc& alloc) {
1128     if (!left->fTop || !left->fBottom || !right->fTop || !right->fBottom) {
1129         return false;
1130     }
1131     if (left->fTop == right->fTop || left->fBottom == right->fBottom) {
1132         return false;
1133     }
1134     if (c.sweep_lt(left->fTop->fPoint, right->fTop->fPoint)) {
1135         if (!left->isLeftOf(right->fTop)) {
1136             rewind(activeEdges, current, right->fTop, c);
1137             return split_edge(left, right->fTop, activeEdges, current, c, alloc);
1138         }
1139     } else {
1140         if (!right->isRightOf(left->fTop)) {
1141             rewind(activeEdges, current, left->fTop, c);
1142             return split_edge(right, left->fTop, activeEdges, current, c, alloc);
1143         }
1144     }
1145     if (c.sweep_lt(right->fBottom->fPoint, left->fBottom->fPoint)) {
1146         if (!left->isLeftOf(right->fBottom)) {
1147             rewind(activeEdges, current, right->fBottom, c);
1148             return split_edge(left, right->fBottom, activeEdges, current, c, alloc);
1149         }
1150     } else {
1151         if (!right->isRightOf(left->fBottom)) {
1152             rewind(activeEdges, current, left->fBottom, c);
1153             return split_edge(right, left->fBottom, activeEdges, current, c, alloc);
1154         }
1155     }
1156     return false;
1157 }
1158 
connect(Vertex * prev,Vertex * next,Edge::Type type,Comparator & c,SkArenaAlloc & alloc,int winding_scale=1)1159 Edge* connect(Vertex* prev, Vertex* next, Edge::Type type, Comparator& c, SkArenaAlloc& alloc,
1160               int winding_scale = 1) {
1161     if (!prev || !next || prev->fPoint == next->fPoint) {
1162         return nullptr;
1163     }
1164     Edge* edge = new_edge(prev, next, type, c, alloc);
1165     insert_edge_below(edge, edge->fTop, c);
1166     insert_edge_above(edge, edge->fBottom, c);
1167     edge->fWinding *= winding_scale;
1168     merge_collinear_edges(edge, nullptr, nullptr, c);
1169     return edge;
1170 }
1171 
merge_vertices(Vertex * src,Vertex * dst,VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)1172 void merge_vertices(Vertex* src, Vertex* dst, VertexList* mesh, Comparator& c,
1173                     SkArenaAlloc& alloc) {
1174     LOG("found coincident verts at %g, %g; merging %g into %g\n", src->fPoint.fX, src->fPoint.fY,
1175         src->fID, dst->fID);
1176     dst->fAlpha = SkTMax(src->fAlpha, dst->fAlpha);
1177     if (src->fPartner) {
1178         src->fPartner->fPartner = dst;
1179     }
1180     while (Edge* edge = src->fFirstEdgeAbove) {
1181         set_bottom(edge, dst, nullptr, nullptr, c);
1182     }
1183     while (Edge* edge = src->fFirstEdgeBelow) {
1184         set_top(edge, dst, nullptr, nullptr, c);
1185     }
1186     mesh->remove(src);
1187     dst->fSynthetic = true;
1188 }
1189 
create_sorted_vertex(const SkPoint & p,uint8_t alpha,VertexList * mesh,Vertex * reference,Comparator & c,SkArenaAlloc & alloc)1190 Vertex* create_sorted_vertex(const SkPoint& p, uint8_t alpha, VertexList* mesh,
1191                              Vertex* reference, Comparator& c, SkArenaAlloc& alloc) {
1192     Vertex* prevV = reference;
1193     while (prevV && c.sweep_lt(p, prevV->fPoint)) {
1194         prevV = prevV->fPrev;
1195     }
1196     Vertex* nextV = prevV ? prevV->fNext : mesh->fHead;
1197     while (nextV && c.sweep_lt(nextV->fPoint, p)) {
1198         prevV = nextV;
1199         nextV = nextV->fNext;
1200     }
1201     Vertex* v;
1202     if (prevV && coincident(prevV->fPoint, p)) {
1203         v = prevV;
1204     } else if (nextV && coincident(nextV->fPoint, p)) {
1205         v = nextV;
1206     } else {
1207         v = alloc.make<Vertex>(p, alpha);
1208 #if LOGGING_ENABLED
1209         if (!prevV) {
1210             v->fID = mesh->fHead->fID - 1.0f;
1211         } else if (!nextV) {
1212             v->fID = mesh->fTail->fID + 1.0f;
1213         } else {
1214             v->fID = (prevV->fID + nextV->fID) * 0.5f;
1215         }
1216 #endif
1217         mesh->insert(v, prevV, nextV);
1218     }
1219     return v;
1220 }
1221 
1222 // If an edge's top and bottom points differ only by 1/2 machine epsilon in the primary
1223 // sort criterion, it may not be possible to split correctly, since there is no point which is
1224 // below the top and above the bottom. This function detects that case.
nearly_flat(Comparator & c,Edge * edge)1225 bool nearly_flat(Comparator& c, Edge* edge) {
1226     SkPoint diff = edge->fBottom->fPoint - edge->fTop->fPoint;
1227     float primaryDiff = c.fDirection == Comparator::Direction::kHorizontal ? diff.fX : diff.fY;
1228     return fabs(primaryDiff) < std::numeric_limits<float>::epsilon() && primaryDiff != 0.0f;
1229 }
1230 
clamp(SkPoint p,SkPoint min,SkPoint max,Comparator & c)1231 SkPoint clamp(SkPoint p, SkPoint min, SkPoint max, Comparator& c) {
1232     if (c.sweep_lt(p, min)) {
1233         return min;
1234     } else if (c.sweep_lt(max, p)) {
1235         return max;
1236     } else {
1237         return p;
1238     }
1239 }
1240 
compute_bisector(Edge * edge1,Edge * edge2,Vertex * v,SkArenaAlloc & alloc)1241 void compute_bisector(Edge* edge1, Edge* edge2, Vertex* v, SkArenaAlloc& alloc) {
1242     Line line1 = edge1->fLine;
1243     Line line2 = edge2->fLine;
1244     line1.normalize();
1245     line2.normalize();
1246     double cosAngle = line1.fA * line2.fA + line1.fB * line2.fB;
1247     if (cosAngle > 0.999) {
1248         return;
1249     }
1250     line1.fC += edge1->fWinding > 0 ? -1 : 1;
1251     line2.fC += edge2->fWinding > 0 ? -1 : 1;
1252     SkPoint p;
1253     if (line1.intersect(line2, &p)) {
1254         uint8_t alpha = edge1->fType == Edge::Type::kOuter ? 255 : 0;
1255         v->fPartner = alloc.make<Vertex>(p, alpha);
1256         LOG("computed bisector (%g,%g) alpha %d for vertex %g\n", p.fX, p.fY, alpha, v->fID);
1257     }
1258 }
1259 
check_for_intersection(Edge * left,Edge * right,EdgeList * activeEdges,Vertex ** current,VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)1260 bool check_for_intersection(Edge* left, Edge* right, EdgeList* activeEdges, Vertex** current,
1261                             VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1262     if (!left || !right) {
1263         return false;
1264     }
1265     SkPoint p;
1266     uint8_t alpha;
1267     if (left->intersect(*right, &p, &alpha) && p.isFinite()) {
1268         Vertex* v;
1269         LOG("found intersection, pt is %g, %g\n", p.fX, p.fY);
1270         Vertex* top = *current;
1271         // If the intersection point is above the current vertex, rewind to the vertex above the
1272         // intersection.
1273         while (top && c.sweep_lt(p, top->fPoint)) {
1274             top = top->fPrev;
1275         }
1276         if (!nearly_flat(c, left)) {
1277             p = clamp(p, left->fTop->fPoint, left->fBottom->fPoint, c);
1278         }
1279         if (!nearly_flat(c, right)) {
1280             p = clamp(p, right->fTop->fPoint, right->fBottom->fPoint, c);
1281         }
1282         if (p == left->fTop->fPoint) {
1283             v = left->fTop;
1284         } else if (p == left->fBottom->fPoint) {
1285             v = left->fBottom;
1286         } else if (p == right->fTop->fPoint) {
1287             v = right->fTop;
1288         } else if (p == right->fBottom->fPoint) {
1289             v = right->fBottom;
1290         } else {
1291             v = create_sorted_vertex(p, alpha, mesh, top, c, alloc);
1292             if (left->fTop->fPartner) {
1293                 v->fSynthetic = true;
1294                 compute_bisector(left, right, v, alloc);
1295             }
1296         }
1297         rewind(activeEdges, current, top ? top : v, c);
1298         split_edge(left, v, activeEdges, current, c, alloc);
1299         split_edge(right, v, activeEdges, current, c, alloc);
1300         v->fAlpha = SkTMax(v->fAlpha, alpha);
1301         return true;
1302     }
1303     return intersect_edge_pair(left, right, activeEdges, current, c, alloc);
1304 }
1305 
sanitize_contours(VertexList * contours,int contourCnt,bool approximate)1306 void sanitize_contours(VertexList* contours, int contourCnt, bool approximate) {
1307     for (VertexList* contour = contours; contourCnt > 0; --contourCnt, ++contour) {
1308         SkASSERT(contour->fHead);
1309         Vertex* prev = contour->fTail;
1310         if (approximate) {
1311             round(&prev->fPoint);
1312         }
1313         for (Vertex* v = contour->fHead; v;) {
1314             if (approximate) {
1315                 round(&v->fPoint);
1316             }
1317             Vertex* next = v->fNext;
1318             Vertex* nextWrap = next ? next : contour->fHead;
1319             if (coincident(prev->fPoint, v->fPoint)) {
1320                 LOG("vertex %g,%g coincident; removing\n", v->fPoint.fX, v->fPoint.fY);
1321                 contour->remove(v);
1322             } else if (!v->fPoint.isFinite()) {
1323                 LOG("vertex %g,%g non-finite; removing\n", v->fPoint.fX, v->fPoint.fY);
1324                 contour->remove(v);
1325             } else if (Line(prev->fPoint, nextWrap->fPoint).dist(v->fPoint) == 0.0) {
1326                 LOG("vertex %g,%g collinear; removing\n", v->fPoint.fX, v->fPoint.fY);
1327                 contour->remove(v);
1328             } else {
1329                 prev = v;
1330             }
1331             v = next;
1332         }
1333     }
1334 }
1335 
merge_coincident_vertices(VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)1336 bool merge_coincident_vertices(VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1337     if (!mesh->fHead) {
1338         return false;
1339     }
1340     bool merged = false;
1341     for (Vertex* v = mesh->fHead->fNext; v;) {
1342         Vertex* next = v->fNext;
1343         if (c.sweep_lt(v->fPoint, v->fPrev->fPoint)) {
1344             v->fPoint = v->fPrev->fPoint;
1345         }
1346         if (coincident(v->fPrev->fPoint, v->fPoint)) {
1347             merge_vertices(v, v->fPrev, mesh, c, alloc);
1348             merged = true;
1349         }
1350         v = next;
1351     }
1352     return merged;
1353 }
1354 
1355 // Stage 2: convert the contours to a mesh of edges connecting the vertices.
1356 
build_edges(VertexList * contours,int contourCnt,VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)1357 void build_edges(VertexList* contours, int contourCnt, VertexList* mesh, Comparator& c,
1358                  SkArenaAlloc& alloc) {
1359     for (VertexList* contour = contours; contourCnt > 0; --contourCnt, ++contour) {
1360         Vertex* prev = contour->fTail;
1361         for (Vertex* v = contour->fHead; v;) {
1362             Vertex* next = v->fNext;
1363             connect(prev, v, Edge::Type::kInner, c, alloc);
1364             mesh->append(v);
1365             prev = v;
1366             v = next;
1367         }
1368     }
1369 }
1370 
connect_partners(VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)1371 void connect_partners(VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1372     for (Vertex* outer = mesh->fHead; outer; outer = outer->fNext) {
1373         if (Vertex* inner = outer->fPartner) {
1374             if ((inner->fPrev || inner->fNext) && (outer->fPrev || outer->fNext)) {
1375                 // Connector edges get zero winding, since they're only structural (i.e., to ensure
1376                 // no 0-0-0 alpha triangles are produced), and shouldn't affect the poly winding
1377                 // number.
1378                 connect(outer, inner, Edge::Type::kConnector, c, alloc, 0);
1379                 inner->fPartner = outer->fPartner = nullptr;
1380             }
1381         }
1382     }
1383 }
1384 
1385 template <CompareFunc sweep_lt>
sorted_merge(VertexList * front,VertexList * back,VertexList * result)1386 void sorted_merge(VertexList* front, VertexList* back, VertexList* result) {
1387     Vertex* a = front->fHead;
1388     Vertex* b = back->fHead;
1389     while (a && b) {
1390         if (sweep_lt(a->fPoint, b->fPoint)) {
1391             front->remove(a);
1392             result->append(a);
1393             a = front->fHead;
1394         } else {
1395             back->remove(b);
1396             result->append(b);
1397             b = back->fHead;
1398         }
1399     }
1400     result->append(*front);
1401     result->append(*back);
1402 }
1403 
sorted_merge(VertexList * front,VertexList * back,VertexList * result,Comparator & c)1404 void sorted_merge(VertexList* front, VertexList* back, VertexList* result, Comparator& c) {
1405     if (c.fDirection == Comparator::Direction::kHorizontal) {
1406         sorted_merge<sweep_lt_horiz>(front, back, result);
1407     } else {
1408         sorted_merge<sweep_lt_vert>(front, back, result);
1409     }
1410 #if LOGGING_ENABLED
1411     float id = 0.0f;
1412     for (Vertex* v = result->fHead; v; v = v->fNext) {
1413         v->fID = id++;
1414     }
1415 #endif
1416 }
1417 
1418 // Stage 3: sort the vertices by increasing sweep direction.
1419 
1420 template <CompareFunc sweep_lt>
merge_sort(VertexList * vertices)1421 void merge_sort(VertexList* vertices) {
1422     Vertex* slow = vertices->fHead;
1423     if (!slow) {
1424         return;
1425     }
1426     Vertex* fast = slow->fNext;
1427     if (!fast) {
1428         return;
1429     }
1430     do {
1431         fast = fast->fNext;
1432         if (fast) {
1433             fast = fast->fNext;
1434             slow = slow->fNext;
1435         }
1436     } while (fast);
1437     VertexList front(vertices->fHead, slow);
1438     VertexList back(slow->fNext, vertices->fTail);
1439     front.fTail->fNext = back.fHead->fPrev = nullptr;
1440 
1441     merge_sort<sweep_lt>(&front);
1442     merge_sort<sweep_lt>(&back);
1443 
1444     vertices->fHead = vertices->fTail = nullptr;
1445     sorted_merge<sweep_lt>(&front, &back, vertices);
1446 }
1447 
dump_mesh(const VertexList & mesh)1448 void dump_mesh(const VertexList& mesh) {
1449 #if LOGGING_ENABLED
1450     for (Vertex* v = mesh.fHead; v; v = v->fNext) {
1451         LOG("vertex %g (%g, %g) alpha %d", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1452         if (Vertex* p = v->fPartner) {
1453             LOG(", partner %g (%g, %g) alpha %d\n", p->fID, p->fPoint.fX, p->fPoint.fY, p->fAlpha);
1454         } else {
1455             LOG(", null partner\n");
1456         }
1457         for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1458             LOG("  edge %g -> %g, winding %d\n", e->fTop->fID, e->fBottom->fID, e->fWinding);
1459         }
1460         for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1461             LOG("  edge %g -> %g, winding %d\n", e->fTop->fID, e->fBottom->fID, e->fWinding);
1462         }
1463     }
1464 #endif
1465 }
1466 
dump_skel(const SSEdgeList & ssEdges)1467 void dump_skel(const SSEdgeList& ssEdges) {
1468 #if LOGGING_ENABLED
1469     for (SSEdge* edge : ssEdges) {
1470         if (edge->fEdge) {
1471             LOG("skel edge %g -> %g",
1472                 edge->fPrev->fVertex->fID,
1473                 edge->fNext->fVertex->fID);
1474             if (edge->fEdge->fTop && edge->fEdge->fBottom) {
1475                 LOG(" (original %g -> %g)\n",
1476                     edge->fEdge->fTop->fID,
1477                     edge->fEdge->fBottom->fID);
1478             } else {
1479                 LOG("\n");
1480             }
1481         }
1482     }
1483 #endif
1484 }
1485 
1486 #ifdef SK_DEBUG
validate_edge_pair(Edge * left,Edge * right,Comparator & c)1487 void validate_edge_pair(Edge* left, Edge* right, Comparator& c) {
1488     if (!left || !right) {
1489         return;
1490     }
1491     if (left->fTop == right->fTop) {
1492         SkASSERT(left->isLeftOf(right->fBottom));
1493         SkASSERT(right->isRightOf(left->fBottom));
1494     } else if (c.sweep_lt(left->fTop->fPoint, right->fTop->fPoint)) {
1495         SkASSERT(left->isLeftOf(right->fTop));
1496     } else {
1497         SkASSERT(right->isRightOf(left->fTop));
1498     }
1499     if (left->fBottom == right->fBottom) {
1500         SkASSERT(left->isLeftOf(right->fTop));
1501         SkASSERT(right->isRightOf(left->fTop));
1502     } else if (c.sweep_lt(right->fBottom->fPoint, left->fBottom->fPoint)) {
1503         SkASSERT(left->isLeftOf(right->fBottom));
1504     } else {
1505         SkASSERT(right->isRightOf(left->fBottom));
1506     }
1507 }
1508 
validate_edge_list(EdgeList * edges,Comparator & c)1509 void validate_edge_list(EdgeList* edges, Comparator& c) {
1510     Edge* left = edges->fHead;
1511     if (!left) {
1512         return;
1513     }
1514     for (Edge* right = left->fRight; right; right = right->fRight) {
1515         validate_edge_pair(left, right, c);
1516         left = right;
1517     }
1518 }
1519 #endif
1520 
1521 // Stage 4: Simplify the mesh by inserting new vertices at intersecting edges.
1522 
connected(Vertex * v)1523 bool connected(Vertex* v) {
1524     return v->fFirstEdgeAbove || v->fFirstEdgeBelow;
1525 }
1526 
simplify(VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)1527 bool simplify(VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1528     LOG("simplifying complex polygons\n");
1529     EdgeList activeEdges;
1530     bool found = false;
1531     for (Vertex* v = mesh->fHead; v != nullptr; v = v->fNext) {
1532         if (!connected(v)) {
1533             continue;
1534         }
1535         Edge* leftEnclosingEdge;
1536         Edge* rightEnclosingEdge;
1537         bool restartChecks;
1538         do {
1539             LOG("\nvertex %g: (%g,%g), alpha %d\n", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1540             restartChecks = false;
1541             find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1542             v->fLeftEnclosingEdge = leftEnclosingEdge;
1543             v->fRightEnclosingEdge = rightEnclosingEdge;
1544             if (v->fFirstEdgeBelow) {
1545                 for (Edge* edge = v->fFirstEdgeBelow; edge; edge = edge->fNextEdgeBelow) {
1546                     if (check_for_intersection(leftEnclosingEdge, edge, &activeEdges, &v, mesh, c,
1547                                                alloc)) {
1548                         restartChecks = true;
1549                         break;
1550                     }
1551                     if (check_for_intersection(edge, rightEnclosingEdge, &activeEdges, &v, mesh, c,
1552                                                alloc)) {
1553                         restartChecks = true;
1554                         break;
1555                     }
1556                 }
1557             } else {
1558                 if (check_for_intersection(leftEnclosingEdge, rightEnclosingEdge,
1559                                            &activeEdges, &v, mesh, c, alloc)) {
1560                     restartChecks = true;
1561                 }
1562 
1563             }
1564             found = found || restartChecks;
1565         } while (restartChecks);
1566 #ifdef SK_DEBUG
1567         validate_edge_list(&activeEdges, c);
1568 #endif
1569         for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1570             remove_edge(e, &activeEdges);
1571         }
1572         Edge* leftEdge = leftEnclosingEdge;
1573         for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1574             insert_edge(e, leftEdge, &activeEdges);
1575             leftEdge = e;
1576         }
1577     }
1578     SkASSERT(!activeEdges.fHead && !activeEdges.fTail);
1579     return found;
1580 }
1581 
1582 // Stage 5: Tessellate the simplified mesh into monotone polygons.
1583 
tessellate(const VertexList & vertices,SkArenaAlloc & alloc)1584 Poly* tessellate(const VertexList& vertices, SkArenaAlloc& alloc) {
1585     LOG("\ntessellating simple polygons\n");
1586     EdgeList activeEdges;
1587     Poly* polys = nullptr;
1588     for (Vertex* v = vertices.fHead; v != nullptr; v = v->fNext) {
1589         if (!connected(v)) {
1590             continue;
1591         }
1592 #if LOGGING_ENABLED
1593         LOG("\nvertex %g: (%g,%g), alpha %d\n", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1594 #endif
1595         Edge* leftEnclosingEdge;
1596         Edge* rightEnclosingEdge;
1597         find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1598         Poly* leftPoly;
1599         Poly* rightPoly;
1600         if (v->fFirstEdgeAbove) {
1601             leftPoly = v->fFirstEdgeAbove->fLeftPoly;
1602             rightPoly = v->fLastEdgeAbove->fRightPoly;
1603         } else {
1604             leftPoly = leftEnclosingEdge ? leftEnclosingEdge->fRightPoly : nullptr;
1605             rightPoly = rightEnclosingEdge ? rightEnclosingEdge->fLeftPoly : nullptr;
1606         }
1607 #if LOGGING_ENABLED
1608         LOG("edges above:\n");
1609         for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1610             LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1611                 e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1612         }
1613         LOG("edges below:\n");
1614         for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1615             LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1616                 e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1617         }
1618 #endif
1619         if (v->fFirstEdgeAbove) {
1620             if (leftPoly) {
1621                 leftPoly = leftPoly->addEdge(v->fFirstEdgeAbove, Poly::kRight_Side, alloc);
1622             }
1623             if (rightPoly) {
1624                 rightPoly = rightPoly->addEdge(v->fLastEdgeAbove, Poly::kLeft_Side, alloc);
1625             }
1626             for (Edge* e = v->fFirstEdgeAbove; e != v->fLastEdgeAbove; e = e->fNextEdgeAbove) {
1627                 Edge* rightEdge = e->fNextEdgeAbove;
1628                 remove_edge(e, &activeEdges);
1629                 if (e->fRightPoly) {
1630                     e->fRightPoly->addEdge(e, Poly::kLeft_Side, alloc);
1631                 }
1632                 if (rightEdge->fLeftPoly && rightEdge->fLeftPoly != e->fRightPoly) {
1633                     rightEdge->fLeftPoly->addEdge(e, Poly::kRight_Side, alloc);
1634                 }
1635             }
1636             remove_edge(v->fLastEdgeAbove, &activeEdges);
1637             if (!v->fFirstEdgeBelow) {
1638                 if (leftPoly && rightPoly && leftPoly != rightPoly) {
1639                     SkASSERT(leftPoly->fPartner == nullptr && rightPoly->fPartner == nullptr);
1640                     rightPoly->fPartner = leftPoly;
1641                     leftPoly->fPartner = rightPoly;
1642                 }
1643             }
1644         }
1645         if (v->fFirstEdgeBelow) {
1646             if (!v->fFirstEdgeAbove) {
1647                 if (leftPoly && rightPoly) {
1648                     if (leftPoly == rightPoly) {
1649                         if (leftPoly->fTail && leftPoly->fTail->fSide == Poly::kLeft_Side) {
1650                             leftPoly = new_poly(&polys, leftPoly->lastVertex(),
1651                                                  leftPoly->fWinding, alloc);
1652                             leftEnclosingEdge->fRightPoly = leftPoly;
1653                         } else {
1654                             rightPoly = new_poly(&polys, rightPoly->lastVertex(),
1655                                                  rightPoly->fWinding, alloc);
1656                             rightEnclosingEdge->fLeftPoly = rightPoly;
1657                         }
1658                     }
1659                     Edge* join = alloc.make<Edge>(leftPoly->lastVertex(), v, 1, Edge::Type::kInner);
1660                     leftPoly = leftPoly->addEdge(join, Poly::kRight_Side, alloc);
1661                     rightPoly = rightPoly->addEdge(join, Poly::kLeft_Side, alloc);
1662                 }
1663             }
1664             Edge* leftEdge = v->fFirstEdgeBelow;
1665             leftEdge->fLeftPoly = leftPoly;
1666             insert_edge(leftEdge, leftEnclosingEdge, &activeEdges);
1667             for (Edge* rightEdge = leftEdge->fNextEdgeBelow; rightEdge;
1668                  rightEdge = rightEdge->fNextEdgeBelow) {
1669                 insert_edge(rightEdge, leftEdge, &activeEdges);
1670                 int winding = leftEdge->fLeftPoly ? leftEdge->fLeftPoly->fWinding : 0;
1671                 winding += leftEdge->fWinding;
1672                 if (winding != 0) {
1673                     Poly* poly = new_poly(&polys, v, winding, alloc);
1674                     leftEdge->fRightPoly = rightEdge->fLeftPoly = poly;
1675                 }
1676                 leftEdge = rightEdge;
1677             }
1678             v->fLastEdgeBelow->fRightPoly = rightPoly;
1679         }
1680 #if LOGGING_ENABLED
1681         LOG("\nactive edges:\n");
1682         for (Edge* e = activeEdges.fHead; e != nullptr; e = e->fRight) {
1683             LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1684                 e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1685         }
1686 #endif
1687     }
1688     return polys;
1689 }
1690 
remove_non_boundary_edges(const VertexList & mesh,SkPath::FillType fillType,SkArenaAlloc & alloc)1691 void remove_non_boundary_edges(const VertexList& mesh, SkPath::FillType fillType,
1692                                SkArenaAlloc& alloc) {
1693     LOG("removing non-boundary edges\n");
1694     EdgeList activeEdges;
1695     for (Vertex* v = mesh.fHead; v != nullptr; v = v->fNext) {
1696         if (!connected(v)) {
1697             continue;
1698         }
1699         Edge* leftEnclosingEdge;
1700         Edge* rightEnclosingEdge;
1701         find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1702         bool prevFilled = leftEnclosingEdge &&
1703                           apply_fill_type(fillType, leftEnclosingEdge->fWinding);
1704         for (Edge* e = v->fFirstEdgeAbove; e;) {
1705             Edge* next = e->fNextEdgeAbove;
1706             remove_edge(e, &activeEdges);
1707             bool filled = apply_fill_type(fillType, e->fWinding);
1708             if (filled == prevFilled) {
1709                 disconnect(e);
1710             }
1711             prevFilled = filled;
1712             e = next;
1713         }
1714         Edge* prev = leftEnclosingEdge;
1715         for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1716             if (prev) {
1717                 e->fWinding += prev->fWinding;
1718             }
1719             insert_edge(e, prev, &activeEdges);
1720             prev = e;
1721         }
1722     }
1723 }
1724 
1725 // Note: this is the normal to the edge, but not necessarily unit length.
get_edge_normal(const Edge * e,SkVector * normal)1726 void get_edge_normal(const Edge* e, SkVector* normal) {
1727     normal->set(SkDoubleToScalar(e->fLine.fA),
1728                 SkDoubleToScalar(e->fLine.fB));
1729 }
1730 
1731 // Stage 5c: detect and remove "pointy" vertices whose edge normals point in opposite directions
1732 // and whose adjacent vertices are less than a quarter pixel from an edge. These are guaranteed to
1733 // invert on stroking.
1734 
simplify_boundary(EdgeList * boundary,Comparator & c,SkArenaAlloc & alloc)1735 void simplify_boundary(EdgeList* boundary, Comparator& c, SkArenaAlloc& alloc) {
1736     Edge* prevEdge = boundary->fTail;
1737     SkVector prevNormal;
1738     get_edge_normal(prevEdge, &prevNormal);
1739     for (Edge* e = boundary->fHead; e != nullptr;) {
1740         Vertex* prev = prevEdge->fWinding == 1 ? prevEdge->fTop : prevEdge->fBottom;
1741         Vertex* next = e->fWinding == 1 ? e->fBottom : e->fTop;
1742         double distPrev = e->dist(prev->fPoint);
1743         double distNext = prevEdge->dist(next->fPoint);
1744         SkVector normal;
1745         get_edge_normal(e, &normal);
1746         constexpr double kQuarterPixelSq = 0.25f * 0.25f;
1747         if (prev == next) {
1748             remove_edge(prevEdge, boundary);
1749             remove_edge(e, boundary);
1750             prevEdge = boundary->fTail;
1751             e = boundary->fHead;
1752             if (prevEdge) {
1753                 get_edge_normal(prevEdge, &prevNormal);
1754             }
1755         } else if (prevNormal.dot(normal) < 0.0 &&
1756             (distPrev * distPrev <= kQuarterPixelSq || distNext * distNext <= kQuarterPixelSq)) {
1757             Edge* join = new_edge(prev, next, Edge::Type::kInner, c, alloc);
1758             if (prev->fPoint != next->fPoint) {
1759                 join->fLine.normalize();
1760                 join->fLine = join->fLine * join->fWinding;
1761             }
1762             insert_edge(join, e, boundary);
1763             remove_edge(prevEdge, boundary);
1764             remove_edge(e, boundary);
1765             if (join->fLeft && join->fRight) {
1766                 prevEdge = join->fLeft;
1767                 e = join;
1768             } else {
1769                 prevEdge = boundary->fTail;
1770                 e = boundary->fHead; // join->fLeft ? join->fLeft : join;
1771             }
1772             get_edge_normal(prevEdge, &prevNormal);
1773         } else {
1774             prevEdge = e;
1775             prevNormal = normal;
1776             e = e->fRight;
1777         }
1778     }
1779 }
1780 
ss_connect(Vertex * v,Vertex * dest,Comparator & c,SkArenaAlloc & alloc)1781 void ss_connect(Vertex* v, Vertex* dest, Comparator& c, SkArenaAlloc& alloc) {
1782     if (v == dest) {
1783         return;
1784     }
1785     LOG("ss_connecting vertex %g to vertex %g\n", v->fID, dest->fID);
1786     if (v->fSynthetic) {
1787         connect(v, dest, Edge::Type::kConnector, c, alloc, 0);
1788     } else if (v->fPartner) {
1789         LOG("setting %g's partner to %g ", v->fPartner->fID, dest->fID);
1790         LOG("and %g's partner to null\n", v->fID);
1791         v->fPartner->fPartner = dest;
1792         v->fPartner = nullptr;
1793     }
1794 }
1795 
apply(VertexList * mesh,Comparator & c,EventList * events,SkArenaAlloc & alloc)1796 void Event::apply(VertexList* mesh, Comparator& c, EventList* events, SkArenaAlloc& alloc) {
1797     if (!fEdge) {
1798         return;
1799     }
1800     Vertex* prev = fEdge->fPrev->fVertex;
1801     Vertex* next = fEdge->fNext->fVertex;
1802     SSEdge* prevEdge = fEdge->fPrev->fPrev;
1803     SSEdge* nextEdge = fEdge->fNext->fNext;
1804     if (!prevEdge || !nextEdge || !prevEdge->fEdge || !nextEdge->fEdge) {
1805         return;
1806     }
1807     Vertex* dest = create_sorted_vertex(fPoint, fAlpha, mesh, prev, c, alloc);
1808     dest->fSynthetic = true;
1809     SSVertex* ssv = alloc.make<SSVertex>(dest);
1810     LOG("collapsing %g, %g (original edge %g -> %g) to %g (%g, %g) alpha %d\n",
1811         prev->fID, next->fID, fEdge->fEdge->fTop->fID, fEdge->fEdge->fBottom->fID,
1812         dest->fID, fPoint.fX, fPoint.fY, fAlpha);
1813     fEdge->fEdge = nullptr;
1814 
1815     ss_connect(prev, dest, c, alloc);
1816     ss_connect(next, dest, c, alloc);
1817 
1818     prevEdge->fNext = nextEdge->fPrev = ssv;
1819     ssv->fPrev = prevEdge;
1820     ssv->fNext = nextEdge;
1821     if (!prevEdge->fEdge || !nextEdge->fEdge) {
1822         return;
1823     }
1824     if (prevEdge->fEvent) {
1825         prevEdge->fEvent->fEdge = nullptr;
1826     }
1827     if (nextEdge->fEvent) {
1828         nextEdge->fEvent->fEdge = nullptr;
1829     }
1830     if (prevEdge->fPrev == nextEdge->fNext) {
1831         ss_connect(prevEdge->fPrev->fVertex, dest, c, alloc);
1832         prevEdge->fEdge = nextEdge->fEdge = nullptr;
1833     } else {
1834         compute_bisector(prevEdge->fEdge, nextEdge->fEdge, dest, alloc);
1835         SkASSERT(prevEdge != fEdge && nextEdge != fEdge);
1836         if (dest->fPartner) {
1837             create_event(prevEdge, events, alloc);
1838             create_event(nextEdge, events, alloc);
1839         } else {
1840             create_event(prevEdge, prevEdge->fPrev->fVertex, nextEdge, dest, events, c, alloc);
1841             create_event(nextEdge, nextEdge->fNext->fVertex, prevEdge, dest, events, c, alloc);
1842         }
1843     }
1844 }
1845 
is_overlap_edge(Edge * e)1846 bool is_overlap_edge(Edge* e) {
1847     if (e->fType == Edge::Type::kOuter) {
1848         return e->fWinding != 0 && e->fWinding != 1;
1849     } else if (e->fType == Edge::Type::kInner) {
1850         return e->fWinding != 0 && e->fWinding != -2;
1851     } else {
1852         return false;
1853     }
1854 }
1855 
1856 // This is a stripped-down version of tessellate() which computes edges which
1857 // join two filled regions, which represent overlap regions, and collapses them.
collapse_overlap_regions(VertexList * mesh,Comparator & c,SkArenaAlloc & alloc,EventComparator comp)1858 bool collapse_overlap_regions(VertexList* mesh, Comparator& c, SkArenaAlloc& alloc,
1859                               EventComparator comp) {
1860     LOG("\nfinding overlap regions\n");
1861     EdgeList activeEdges;
1862     EventList events(comp);
1863     SSVertexMap ssVertices;
1864     SSEdgeList ssEdges;
1865     for (Vertex* v = mesh->fHead; v != nullptr; v = v->fNext) {
1866         if (!connected(v)) {
1867             continue;
1868         }
1869         Edge* leftEnclosingEdge;
1870         Edge* rightEnclosingEdge;
1871         find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1872         for (Edge* e = v->fLastEdgeAbove; e && e != leftEnclosingEdge;) {
1873             Edge* prev = e->fPrevEdgeAbove ? e->fPrevEdgeAbove : leftEnclosingEdge;
1874             remove_edge(e, &activeEdges);
1875             bool leftOverlap = prev && is_overlap_edge(prev);
1876             bool rightOverlap = is_overlap_edge(e);
1877             bool isOuterBoundary = e->fType == Edge::Type::kOuter &&
1878                                    (!prev || prev->fWinding == 0 || e->fWinding == 0);
1879             if (prev) {
1880                 e->fWinding -= prev->fWinding;
1881             }
1882             if (leftOverlap && rightOverlap) {
1883                 LOG("found interior overlap edge %g -> %g, disconnecting\n",
1884                     e->fTop->fID, e->fBottom->fID);
1885                 disconnect(e);
1886             } else if (leftOverlap || rightOverlap) {
1887                 LOG("found overlap edge %g -> %g%s\n", e->fTop->fID, e->fBottom->fID,
1888                     isOuterBoundary ? ", is outer boundary" : "");
1889                 Vertex* prevVertex = e->fWinding < 0 ? e->fBottom : e->fTop;
1890                 Vertex* nextVertex = e->fWinding < 0 ? e->fTop : e->fBottom;
1891                 SSVertex* ssPrev = ssVertices[prevVertex];
1892                 if (!ssPrev) {
1893                     ssPrev = ssVertices[prevVertex] = alloc.make<SSVertex>(prevVertex);
1894                 }
1895                 SSVertex* ssNext = ssVertices[nextVertex];
1896                 if (!ssNext) {
1897                     ssNext = ssVertices[nextVertex] = alloc.make<SSVertex>(nextVertex);
1898                 }
1899                 SSEdge* ssEdge = alloc.make<SSEdge>(e, ssPrev, ssNext);
1900                 ssEdges.push_back(ssEdge);
1901 //                SkASSERT(!ssPrev->fNext && !ssNext->fPrev);
1902                 ssPrev->fNext = ssNext->fPrev = ssEdge;
1903                 create_event(ssEdge, &events, alloc);
1904                 if (!isOuterBoundary) {
1905                     disconnect(e);
1906                 }
1907             }
1908             e = prev;
1909         }
1910         Edge* prev = leftEnclosingEdge;
1911         for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1912             if (prev) {
1913                 e->fWinding += prev->fWinding;
1914             }
1915             insert_edge(e, prev, &activeEdges);
1916             prev = e;
1917         }
1918     }
1919     bool complex = events.size() > 0;
1920 
1921     LOG("\ncollapsing overlap regions\n");
1922     LOG("skeleton before:\n");
1923     dump_skel(ssEdges);
1924     while (events.size() > 0) {
1925         Event* event = events.top();
1926         events.pop();
1927         event->apply(mesh, c, &events, alloc);
1928     }
1929     LOG("skeleton after:\n");
1930     dump_skel(ssEdges);
1931     for (SSEdge* edge : ssEdges) {
1932         if (Edge* e = edge->fEdge) {
1933             connect(edge->fPrev->fVertex, edge->fNext->fVertex, e->fType, c, alloc, 0);
1934         }
1935     }
1936     return complex;
1937 }
1938 
inversion(Vertex * prev,Vertex * next,Edge * origEdge,Comparator & c)1939 bool inversion(Vertex* prev, Vertex* next, Edge* origEdge, Comparator& c) {
1940     if (!prev || !next) {
1941         return true;
1942     }
1943     int winding = c.sweep_lt(prev->fPoint, next->fPoint) ? 1 : -1;
1944     return winding != origEdge->fWinding;
1945 }
1946 
1947 // Stage 5d: Displace edges by half a pixel inward and outward along their normals. Intersect to
1948 // find new vertices, and set zero alpha on the exterior and one alpha on the interior. Build a
1949 // new antialiased mesh from those vertices.
1950 
stroke_boundary(EdgeList * boundary,VertexList * innerMesh,VertexList * outerMesh,Comparator & c,SkArenaAlloc & alloc)1951 void stroke_boundary(EdgeList* boundary, VertexList* innerMesh, VertexList* outerMesh,
1952                      Comparator& c, SkArenaAlloc& alloc) {
1953     LOG("\nstroking boundary\n");
1954     // A boundary with fewer than 3 edges is degenerate.
1955     if (!boundary->fHead || !boundary->fHead->fRight || !boundary->fHead->fRight->fRight) {
1956         return;
1957     }
1958     Edge* prevEdge = boundary->fTail;
1959     Vertex* prevV = prevEdge->fWinding > 0 ? prevEdge->fTop : prevEdge->fBottom;
1960     SkVector prevNormal;
1961     get_edge_normal(prevEdge, &prevNormal);
1962     double radius = 0.5;
1963     Line prevInner(prevEdge->fLine);
1964     prevInner.fC -= radius;
1965     Line prevOuter(prevEdge->fLine);
1966     prevOuter.fC += radius;
1967     VertexList innerVertices;
1968     VertexList outerVertices;
1969     bool innerInversion = true;
1970     bool outerInversion = true;
1971     for (Edge* e = boundary->fHead; e != nullptr; e = e->fRight) {
1972         Vertex* v = e->fWinding > 0 ? e->fTop : e->fBottom;
1973         SkVector normal;
1974         get_edge_normal(e, &normal);
1975         Line inner(e->fLine);
1976         inner.fC -= radius;
1977         Line outer(e->fLine);
1978         outer.fC += radius;
1979         SkPoint innerPoint, outerPoint;
1980         LOG("stroking vertex %g (%g, %g)\n", v->fID, v->fPoint.fX, v->fPoint.fY);
1981         if (!prevEdge->fLine.nearParallel(e->fLine) && prevInner.intersect(inner, &innerPoint) &&
1982             prevOuter.intersect(outer, &outerPoint)) {
1983             float cosAngle = normal.dot(prevNormal);
1984             if (cosAngle < -kCosMiterAngle) {
1985                 Vertex* nextV = e->fWinding > 0 ? e->fBottom : e->fTop;
1986 
1987                 // This is a pointy vertex whose angle is smaller than the threshold; miter it.
1988                 Line bisector(innerPoint, outerPoint);
1989                 Line tangent(v->fPoint, v->fPoint + SkPoint::Make(bisector.fA, bisector.fB));
1990                 if (tangent.fA == 0 && tangent.fB == 0) {
1991                     continue;
1992                 }
1993                 tangent.normalize();
1994                 Line innerTangent(tangent);
1995                 Line outerTangent(tangent);
1996                 innerTangent.fC -= 0.5;
1997                 outerTangent.fC += 0.5;
1998                 SkPoint innerPoint1, innerPoint2, outerPoint1, outerPoint2;
1999                 if (prevNormal.cross(normal) > 0) {
2000                     // Miter inner points
2001                     if (!innerTangent.intersect(prevInner, &innerPoint1) ||
2002                         !innerTangent.intersect(inner, &innerPoint2) ||
2003                         !outerTangent.intersect(bisector, &outerPoint)) {
2004                         continue;
2005                     }
2006                     Line prevTangent(prevV->fPoint,
2007                                      prevV->fPoint + SkVector::Make(prevOuter.fA, prevOuter.fB));
2008                     Line nextTangent(nextV->fPoint,
2009                                      nextV->fPoint + SkVector::Make(outer.fA, outer.fB));
2010                     if (prevTangent.dist(outerPoint) > 0) {
2011                         bisector.intersect(prevTangent, &outerPoint);
2012                     }
2013                     if (nextTangent.dist(outerPoint) < 0) {
2014                         bisector.intersect(nextTangent, &outerPoint);
2015                     }
2016                     outerPoint1 = outerPoint2 = outerPoint;
2017                 } else {
2018                     // Miter outer points
2019                     if (!outerTangent.intersect(prevOuter, &outerPoint1) ||
2020                         !outerTangent.intersect(outer, &outerPoint2)) {
2021                         continue;
2022                     }
2023                     Line prevTangent(prevV->fPoint,
2024                                      prevV->fPoint + SkVector::Make(prevInner.fA, prevInner.fB));
2025                     Line nextTangent(nextV->fPoint,
2026                                      nextV->fPoint + SkVector::Make(inner.fA, inner.fB));
2027                     if (prevTangent.dist(innerPoint) > 0) {
2028                         bisector.intersect(prevTangent, &innerPoint);
2029                     }
2030                     if (nextTangent.dist(innerPoint) < 0) {
2031                         bisector.intersect(nextTangent, &innerPoint);
2032                     }
2033                     innerPoint1 = innerPoint2 = innerPoint;
2034                 }
2035                 if (!innerPoint1.isFinite() || !innerPoint2.isFinite() ||
2036                     !outerPoint1.isFinite() || !outerPoint2.isFinite()) {
2037                     continue;
2038                 }
2039                 LOG("inner (%g, %g), (%g, %g), ",
2040                     innerPoint1.fX, innerPoint1.fY, innerPoint2.fX, innerPoint2.fY);
2041                 LOG("outer (%g, %g), (%g, %g)\n",
2042                     outerPoint1.fX, outerPoint1.fY, outerPoint2.fX, outerPoint2.fY);
2043                 Vertex* innerVertex1 = alloc.make<Vertex>(innerPoint1, 255);
2044                 Vertex* innerVertex2 = alloc.make<Vertex>(innerPoint2, 255);
2045                 Vertex* outerVertex1 = alloc.make<Vertex>(outerPoint1, 0);
2046                 Vertex* outerVertex2 = alloc.make<Vertex>(outerPoint2, 0);
2047                 innerVertex1->fPartner = outerVertex1;
2048                 innerVertex2->fPartner = outerVertex2;
2049                 outerVertex1->fPartner = innerVertex1;
2050                 outerVertex2->fPartner = innerVertex2;
2051                 if (!inversion(innerVertices.fTail, innerVertex1, prevEdge, c)) {
2052                     innerInversion = false;
2053                 }
2054                 if (!inversion(outerVertices.fTail, outerVertex1, prevEdge, c)) {
2055                     outerInversion = false;
2056                 }
2057                 innerVertices.append(innerVertex1);
2058                 innerVertices.append(innerVertex2);
2059                 outerVertices.append(outerVertex1);
2060                 outerVertices.append(outerVertex2);
2061             } else {
2062                 LOG("inner (%g, %g), ", innerPoint.fX, innerPoint.fY);
2063                 LOG("outer (%g, %g)\n", outerPoint.fX, outerPoint.fY);
2064                 Vertex* innerVertex = alloc.make<Vertex>(innerPoint, 255);
2065                 Vertex* outerVertex = alloc.make<Vertex>(outerPoint, 0);
2066                 innerVertex->fPartner = outerVertex;
2067                 outerVertex->fPartner = innerVertex;
2068                 if (!inversion(innerVertices.fTail, innerVertex, prevEdge, c)) {
2069                     innerInversion = false;
2070                 }
2071                 if (!inversion(outerVertices.fTail, outerVertex, prevEdge, c)) {
2072                     outerInversion = false;
2073                 }
2074                 innerVertices.append(innerVertex);
2075                 outerVertices.append(outerVertex);
2076             }
2077         }
2078         prevInner = inner;
2079         prevOuter = outer;
2080         prevV = v;
2081         prevEdge = e;
2082         prevNormal = normal;
2083     }
2084     if (!inversion(innerVertices.fTail, innerVertices.fHead, prevEdge, c)) {
2085         innerInversion = false;
2086     }
2087     if (!inversion(outerVertices.fTail, outerVertices.fHead, prevEdge, c)) {
2088         outerInversion = false;
2089     }
2090     // Outer edges get 1 winding, and inner edges get -2 winding. This ensures that the interior
2091     // is always filled (1 + -2 = -1 for normal cases, 1 + 2 = 3 for thin features where the
2092     // interior inverts).
2093     // For total inversion cases, the shape has now reversed handedness, so invert the winding
2094     // so it will be detected during collapse_overlap_regions().
2095     int innerWinding = innerInversion ? 2 : -2;
2096     int outerWinding = outerInversion ? -1 : 1;
2097     for (Vertex* v = innerVertices.fHead; v && v->fNext; v = v->fNext) {
2098         connect(v, v->fNext, Edge::Type::kInner, c, alloc, innerWinding);
2099     }
2100     connect(innerVertices.fTail, innerVertices.fHead, Edge::Type::kInner, c, alloc, innerWinding);
2101     for (Vertex* v = outerVertices.fHead; v && v->fNext; v = v->fNext) {
2102         connect(v, v->fNext, Edge::Type::kOuter, c, alloc, outerWinding);
2103     }
2104     connect(outerVertices.fTail, outerVertices.fHead, Edge::Type::kOuter, c, alloc, outerWinding);
2105     innerMesh->append(innerVertices);
2106     outerMesh->append(outerVertices);
2107 }
2108 
extract_boundary(EdgeList * boundary,Edge * e,SkPath::FillType fillType,SkArenaAlloc & alloc)2109 void extract_boundary(EdgeList* boundary, Edge* e, SkPath::FillType fillType, SkArenaAlloc& alloc) {
2110     LOG("\nextracting boundary\n");
2111     bool down = apply_fill_type(fillType, e->fWinding);
2112     Vertex* start = down ? e->fTop : e->fBottom;
2113     do {
2114         e->fWinding = down ? 1 : -1;
2115         Edge* next;
2116         e->fLine.normalize();
2117         e->fLine = e->fLine * e->fWinding;
2118         boundary->append(e);
2119         if (down) {
2120             // Find outgoing edge, in clockwise order.
2121             if ((next = e->fNextEdgeAbove)) {
2122                 down = false;
2123             } else if ((next = e->fBottom->fLastEdgeBelow)) {
2124                 down = true;
2125             } else if ((next = e->fPrevEdgeAbove)) {
2126                 down = false;
2127             }
2128         } else {
2129             // Find outgoing edge, in counter-clockwise order.
2130             if ((next = e->fPrevEdgeBelow)) {
2131                 down = true;
2132             } else if ((next = e->fTop->fFirstEdgeAbove)) {
2133                 down = false;
2134             } else if ((next = e->fNextEdgeBelow)) {
2135                 down = true;
2136             }
2137         }
2138         disconnect(e);
2139         e = next;
2140     } while (e && (down ? e->fTop : e->fBottom) != start);
2141 }
2142 
2143 // Stage 5b: Extract boundaries from mesh, simplify and stroke them into a new mesh.
2144 
extract_boundaries(const VertexList & inMesh,VertexList * innerVertices,VertexList * outerVertices,SkPath::FillType fillType,Comparator & c,SkArenaAlloc & alloc)2145 void extract_boundaries(const VertexList& inMesh, VertexList* innerVertices,
2146                         VertexList* outerVertices, SkPath::FillType fillType,
2147                         Comparator& c, SkArenaAlloc& alloc) {
2148     remove_non_boundary_edges(inMesh, fillType, alloc);
2149     for (Vertex* v = inMesh.fHead; v; v = v->fNext) {
2150         while (v->fFirstEdgeBelow) {
2151             EdgeList boundary;
2152             extract_boundary(&boundary, v->fFirstEdgeBelow, fillType, alloc);
2153             simplify_boundary(&boundary, c, alloc);
2154             stroke_boundary(&boundary, innerVertices, outerVertices, c, alloc);
2155         }
2156     }
2157 }
2158 
2159 // This is a driver function that calls stages 2-5 in turn.
2160 
contours_to_mesh(VertexList * contours,int contourCnt,bool antialias,VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)2161 void contours_to_mesh(VertexList* contours, int contourCnt, bool antialias,
2162                       VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
2163 #if LOGGING_ENABLED
2164     for (int i = 0; i < contourCnt; ++i) {
2165         Vertex* v = contours[i].fHead;
2166         SkASSERT(v);
2167         LOG("path.moveTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
2168         for (v = v->fNext; v; v = v->fNext) {
2169             LOG("path.lineTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
2170         }
2171     }
2172 #endif
2173     sanitize_contours(contours, contourCnt, antialias);
2174     build_edges(contours, contourCnt, mesh, c, alloc);
2175 }
2176 
sort_mesh(VertexList * vertices,Comparator & c,SkArenaAlloc & alloc)2177 void sort_mesh(VertexList* vertices, Comparator& c, SkArenaAlloc& alloc) {
2178     if (!vertices || !vertices->fHead) {
2179         return;
2180     }
2181 
2182     // Sort vertices in Y (secondarily in X).
2183     if (c.fDirection == Comparator::Direction::kHorizontal) {
2184         merge_sort<sweep_lt_horiz>(vertices);
2185     } else {
2186         merge_sort<sweep_lt_vert>(vertices);
2187     }
2188 #if LOGGING_ENABLED
2189     for (Vertex* v = vertices->fHead; v != nullptr; v = v->fNext) {
2190         static float gID = 0.0f;
2191         v->fID = gID++;
2192     }
2193 #endif
2194 }
2195 
contours_to_polys(VertexList * contours,int contourCnt,SkPath::FillType fillType,const SkRect & pathBounds,bool antialias,VertexList * outerMesh,SkArenaAlloc & alloc)2196 Poly* contours_to_polys(VertexList* contours, int contourCnt, SkPath::FillType fillType,
2197                         const SkRect& pathBounds, bool antialias, VertexList* outerMesh,
2198                         SkArenaAlloc& alloc) {
2199     Comparator c(pathBounds.width() > pathBounds.height() ? Comparator::Direction::kHorizontal
2200                                                           : Comparator::Direction::kVertical);
2201     VertexList mesh;
2202     contours_to_mesh(contours, contourCnt, antialias, &mesh, c, alloc);
2203     sort_mesh(&mesh, c, alloc);
2204     merge_coincident_vertices(&mesh, c, alloc);
2205     simplify(&mesh, c, alloc);
2206     LOG("\nsimplified mesh:\n");
2207     dump_mesh(mesh);
2208     if (antialias) {
2209         VertexList innerMesh;
2210         extract_boundaries(mesh, &innerMesh, outerMesh, fillType, c, alloc);
2211         sort_mesh(&innerMesh, c, alloc);
2212         sort_mesh(outerMesh, c, alloc);
2213         merge_coincident_vertices(&innerMesh, c, alloc);
2214         bool was_complex = merge_coincident_vertices(outerMesh, c, alloc);
2215         was_complex = simplify(&innerMesh, c, alloc) || was_complex;
2216         was_complex = simplify(outerMesh, c, alloc) || was_complex;
2217         LOG("\ninner mesh before:\n");
2218         dump_mesh(innerMesh);
2219         LOG("\nouter mesh before:\n");
2220         dump_mesh(*outerMesh);
2221         EventComparator eventLT(EventComparator::Op::kLessThan);
2222         EventComparator eventGT(EventComparator::Op::kGreaterThan);
2223         was_complex = collapse_overlap_regions(&innerMesh, c, alloc, eventLT) || was_complex;
2224         was_complex = collapse_overlap_regions(outerMesh, c, alloc, eventGT) || was_complex;
2225         if (was_complex) {
2226             LOG("found complex mesh; taking slow path\n");
2227             VertexList aaMesh;
2228             LOG("\ninner mesh after:\n");
2229             dump_mesh(innerMesh);
2230             LOG("\nouter mesh after:\n");
2231             dump_mesh(*outerMesh);
2232             connect_partners(outerMesh, c, alloc);
2233             connect_partners(&innerMesh, c, alloc);
2234             sorted_merge(&innerMesh, outerMesh, &aaMesh, c);
2235             merge_coincident_vertices(&aaMesh, c, alloc);
2236             simplify(&aaMesh, c, alloc);
2237             LOG("combined and simplified mesh:\n");
2238             dump_mesh(aaMesh);
2239             outerMesh->fHead = outerMesh->fTail = nullptr;
2240             return tessellate(aaMesh, alloc);
2241         } else {
2242             LOG("no complex polygons; taking fast path\n");
2243             return tessellate(innerMesh, alloc);
2244         }
2245     } else {
2246         return tessellate(mesh, alloc);
2247     }
2248 }
2249 
2250 // Stage 6: Triangulate the monotone polygons into a vertex buffer.
polys_to_triangles(Poly * polys,SkPath::FillType fillType,bool emitCoverage,void * data)2251 void* polys_to_triangles(Poly* polys, SkPath::FillType fillType, bool emitCoverage, void* data) {
2252     for (Poly* poly = polys; poly; poly = poly->fNext) {
2253         if (apply_fill_type(fillType, poly)) {
2254             data = poly->emit(emitCoverage, data);
2255         }
2256     }
2257     return data;
2258 }
2259 
path_to_polys(const SkPath & path,SkScalar tolerance,const SkRect & clipBounds,int contourCnt,SkArenaAlloc & alloc,bool antialias,bool * isLinear,VertexList * outerMesh)2260 Poly* path_to_polys(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
2261                     int contourCnt, SkArenaAlloc& alloc, bool antialias, bool* isLinear,
2262                     VertexList* outerMesh) {
2263     SkPath::FillType fillType = path.getFillType();
2264     if (SkPath::IsInverseFillType(fillType)) {
2265         contourCnt++;
2266     }
2267     std::unique_ptr<VertexList[]> contours(new VertexList[contourCnt]);
2268 
2269     path_to_contours(path, tolerance, clipBounds, contours.get(), alloc, isLinear);
2270     return contours_to_polys(contours.get(), contourCnt, path.getFillType(), path.getBounds(),
2271                              antialias, outerMesh, alloc);
2272 }
2273 
get_contour_count(const SkPath & path,SkScalar tolerance)2274 int get_contour_count(const SkPath& path, SkScalar tolerance) {
2275     int contourCnt;
2276     int maxPts = GrPathUtils::worstCasePointCount(path, &contourCnt, tolerance);
2277     if (maxPts <= 0) {
2278         return 0;
2279     }
2280     return contourCnt;
2281 }
2282 
count_points(Poly * polys,SkPath::FillType fillType)2283 int64_t count_points(Poly* polys, SkPath::FillType fillType) {
2284     int64_t count = 0;
2285     for (Poly* poly = polys; poly; poly = poly->fNext) {
2286         if (apply_fill_type(fillType, poly) && poly->fCount >= 3) {
2287             count += (poly->fCount - 2) * (TESSELLATOR_WIREFRAME ? 6 : 3);
2288         }
2289     }
2290     return count;
2291 }
2292 
count_outer_mesh_points(const VertexList & outerMesh)2293 int64_t count_outer_mesh_points(const VertexList& outerMesh) {
2294     int64_t count = 0;
2295     for (Vertex* v = outerMesh.fHead; v; v = v->fNext) {
2296         for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
2297             count += TESSELLATOR_WIREFRAME ? 12 : 6;
2298         }
2299     }
2300     return count;
2301 }
2302 
outer_mesh_to_triangles(const VertexList & outerMesh,bool emitCoverage,void * data)2303 void* outer_mesh_to_triangles(const VertexList& outerMesh, bool emitCoverage, void* data) {
2304     for (Vertex* v = outerMesh.fHead; v; v = v->fNext) {
2305         for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
2306             Vertex* v0 = e->fTop;
2307             Vertex* v1 = e->fBottom;
2308             Vertex* v2 = e->fBottom->fPartner;
2309             Vertex* v3 = e->fTop->fPartner;
2310             data = emit_triangle(v0, v1, v2, emitCoverage, data);
2311             data = emit_triangle(v0, v2, v3, emitCoverage, data);
2312         }
2313     }
2314     return data;
2315 }
2316 
2317 } // namespace
2318 
2319 namespace GrTessellator {
2320 
2321 // Stage 6: Triangulate the monotone polygons into a vertex buffer.
2322 
PathToTriangles(const SkPath & path,SkScalar tolerance,const SkRect & clipBounds,VertexAllocator * vertexAllocator,bool antialias,bool * isLinear)2323 int PathToTriangles(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
2324                     VertexAllocator* vertexAllocator, bool antialias, bool* isLinear) {
2325     int contourCnt = get_contour_count(path, tolerance);
2326     if (contourCnt <= 0) {
2327         *isLinear = true;
2328         return 0;
2329     }
2330     SkArenaAlloc alloc(kArenaChunkSize);
2331     VertexList outerMesh;
2332     Poly* polys = path_to_polys(path, tolerance, clipBounds, contourCnt, alloc, antialias,
2333                                 isLinear, &outerMesh);
2334     SkPath::FillType fillType = antialias ? SkPath::kWinding_FillType : path.getFillType();
2335     int64_t count64 = count_points(polys, fillType);
2336     if (antialias) {
2337         count64 += count_outer_mesh_points(outerMesh);
2338     }
2339     if (0 == count64 || count64 > SK_MaxS32) {
2340         return 0;
2341     }
2342     int count = count64;
2343 
2344     void* verts = vertexAllocator->lock(count);
2345     if (!verts) {
2346         SkDebugf("Could not allocate vertices\n");
2347         return 0;
2348     }
2349 
2350     LOG("emitting %d verts\n", count);
2351     void* end = polys_to_triangles(polys, fillType, antialias, verts);
2352     end = outer_mesh_to_triangles(outerMesh, true, end);
2353 
2354     int actualCount = static_cast<int>((static_cast<uint8_t*>(end) - static_cast<uint8_t*>(verts))
2355                                        / vertexAllocator->stride());
2356     SkASSERT(actualCount <= count);
2357     vertexAllocator->unlock(actualCount);
2358     return actualCount;
2359 }
2360 
PathToVertices(const SkPath & path,SkScalar tolerance,const SkRect & clipBounds,GrTessellator::WindingVertex ** verts)2361 int PathToVertices(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
2362                    GrTessellator::WindingVertex** verts) {
2363     int contourCnt = get_contour_count(path, tolerance);
2364     if (contourCnt <= 0) {
2365         *verts = nullptr;
2366         return 0;
2367     }
2368     SkArenaAlloc alloc(kArenaChunkSize);
2369     bool isLinear;
2370     Poly* polys = path_to_polys(path, tolerance, clipBounds, contourCnt, alloc, false, &isLinear,
2371                                 nullptr);
2372     SkPath::FillType fillType = path.getFillType();
2373     int64_t count64 = count_points(polys, fillType);
2374     if (0 == count64 || count64 > SK_MaxS32) {
2375         *verts = nullptr;
2376         return 0;
2377     }
2378     int count = count64;
2379 
2380     *verts = new GrTessellator::WindingVertex[count];
2381     GrTessellator::WindingVertex* vertsEnd = *verts;
2382     SkPoint* points = new SkPoint[count];
2383     SkPoint* pointsEnd = points;
2384     for (Poly* poly = polys; poly; poly = poly->fNext) {
2385         if (apply_fill_type(fillType, poly)) {
2386             SkPoint* start = pointsEnd;
2387             pointsEnd = static_cast<SkPoint*>(poly->emit(false, pointsEnd));
2388             while (start != pointsEnd) {
2389                 vertsEnd->fPos = *start;
2390                 vertsEnd->fWinding = poly->fWinding;
2391                 ++start;
2392                 ++vertsEnd;
2393             }
2394         }
2395     }
2396     int actualCount = static_cast<int>(vertsEnd - *verts);
2397     SkASSERT(actualCount <= count);
2398     SkASSERT(pointsEnd - points == actualCount);
2399     delete[] points;
2400     return actualCount;
2401 }
2402 
2403 } // namespace
2404