GrTessellator.cpp revision 16a40cb65adeb4d94b84479f9946c360ed73e1bb
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 "GrTessellator.h"
9
10#include "GrDefaultGeoProcFactory.h"
11#include "GrPathUtils.h"
12
13#include "SkArenaAlloc.h"
14#include "SkGeometry.h"
15#include "SkPath.h"
16
17#include <stdio.h>
18
19/*
20 * There are six stages to the basic algorithm:
21 *
22 * 1) Linearize the path contours into piecewise linear segments (path_to_contours()).
23 * 2) Build a mesh of edges connecting the vertices (build_edges()).
24 * 3) Sort the vertices in Y (and secondarily in X) (merge_sort()).
25 * 4) Simplify the mesh by inserting new vertices at intersecting edges (simplify()).
26 * 5) Tessellate the simplified mesh into monotone polygons (tessellate()).
27 * 6) Triangulate the monotone polygons directly into a vertex buffer (polys_to_triangles()).
28 *
29 * For screenspace antialiasing, the algorithm is modified as follows:
30 *
31 * Run steps 1-5 above to produce polygons.
32 * 5b) Apply fill rules to extract boundary contours from the polygons (extract_boundaries()).
33 * 5c) Simplify boundaries to remove "pointy" vertices which cause inversions (simplify_boundary()).
34 * 5d) Displace edges by half a pixel inward and outward along their normals. Intersect to find
35 *     new vertices, and set zero alpha on the exterior and one alpha on the interior. Build a new
36 *     antialiased mesh from those vertices (boundary_to_aa_mesh()).
37 * Run steps 3-6 above on the new mesh, and produce antialiased triangles.
38 *
39 * The vertex sorting in step (3) is a merge sort, since it plays well with the linked list
40 * of vertices (and the necessity of inserting new vertices on intersection).
41 *
42 * Stages (4) and (5) use an active edge list, which a list of all edges for which the
43 * sweep line has crossed the top vertex, but not the bottom vertex.  It's sorted
44 * left-to-right based on the point where both edges are active (when both top vertices
45 * have been seen, so the "lower" top vertex of the two). If the top vertices are equal
46 * (shared), it's sorted based on the last point where both edges are active, so the
47 * "upper" bottom vertex.
48 *
49 * The most complex step is the simplification (4). It's based on the Bentley-Ottman
50 * line-sweep algorithm, but due to floating point inaccuracy, the intersection points are
51 * not exact and may violate the mesh topology or active edge list ordering. We
52 * accommodate this by adjusting the topology of the mesh and AEL to match the intersection
53 * points. This occurs in three ways:
54 *
55 * A) Intersections may cause a shortened edge to no longer be ordered with respect to its
56 *    neighbouring edges at the top or bottom vertex. This is handled by merging the
57 *    edges (merge_collinear_edges()).
58 * B) Intersections may cause an edge to violate the left-to-right ordering of the
59 *    active edge list. This is handled by splitting the neighbour edge on the
60 *    intersected vertex (cleanup_active_edges()).
61 * C) Shortening an edge may cause an active edge to become inactive or an inactive edge
62 *    to become active. This is handled by removing or inserting the edge in the active
63 *    edge list (fix_active_state()).
64 *
65 * The tessellation steps (5) and (6) are based on "Triangulating Simple Polygons and
66 * Equivalent Problems" (Fournier and Montuno); also a line-sweep algorithm. Note that it
67 * currently uses a linked list for the active edge list, rather than a 2-3 tree as the
68 * paper describes. The 2-3 tree gives O(lg N) lookups, but insertion and removal also
69 * become O(lg N). In all the test cases, it was found that the cost of frequent O(lg N)
70 * insertions and removals was greater than the cost of infrequent O(N) lookups with the
71 * linked list implementation. With the latter, all removals are O(1), and most insertions
72 * are O(1), since we know the adjacent edge in the active edge list based on the topology.
73 * Only type 2 vertices (see paper) require the O(N) lookups, and these are much less
74 * frequent. There may be other data structures worth investigating, however.
75 *
76 * Note that the orientation of the line sweep algorithms is determined by the aspect ratio of the
77 * path bounds. When the path is taller than it is wide, we sort vertices based on increasing Y
78 * coordinate, and secondarily by increasing X coordinate. When the path is wider than it is tall,
79 * we sort by increasing X coordinate, but secondarily by *decreasing* Y coordinate. This is so
80 * that the "left" and "right" orientation in the code remains correct (edges to the left are
81 * increasing in Y; edges to the right are decreasing in Y). That is, the setting rotates 90
82 * degrees counterclockwise, rather that transposing.
83 */
84
85#define LOGGING_ENABLED 0
86
87#if LOGGING_ENABLED
88#define LOG printf
89#else
90#define LOG(...)
91#endif
92
93namespace {
94
95const int kArenaChunkSize = 16 * 1024;
96
97struct Vertex;
98struct Edge;
99struct Poly;
100
101template <class T, T* T::*Prev, T* T::*Next>
102void list_insert(T* t, T* prev, T* next, T** head, T** tail) {
103    t->*Prev = prev;
104    t->*Next = next;
105    if (prev) {
106        prev->*Next = t;
107    } else if (head) {
108        *head = t;
109    }
110    if (next) {
111        next->*Prev = t;
112    } else if (tail) {
113        *tail = t;
114    }
115}
116
117template <class T, T* T::*Prev, T* T::*Next>
118void list_remove(T* t, T** head, T** tail) {
119    if (t->*Prev) {
120        t->*Prev->*Next = t->*Next;
121    } else if (head) {
122        *head = t->*Next;
123    }
124    if (t->*Next) {
125        t->*Next->*Prev = t->*Prev;
126    } else if (tail) {
127        *tail = t->*Prev;
128    }
129    t->*Prev = t->*Next = nullptr;
130}
131
132/**
133 * Vertices are used in three ways: first, the path contours are converted into a
134 * circularly-linked list of Vertices for each contour. After edge construction, the same Vertices
135 * are re-ordered by the merge sort according to the sweep_lt comparator (usually, increasing
136 * in Y) using the same fPrev/fNext pointers that were used for the contours, to avoid
137 * reallocation. Finally, MonotonePolys are built containing a circularly-linked list of
138 * Vertices. (Currently, those Vertices are newly-allocated for the MonotonePolys, since
139 * an individual Vertex from the path mesh may belong to multiple
140 * MonotonePolys, so the original Vertices cannot be re-used.
141 */
142
143struct Vertex {
144  Vertex(const SkPoint& point, uint8_t alpha)
145    : fPoint(point), fPrev(nullptr), fNext(nullptr)
146    , fFirstEdgeAbove(nullptr), fLastEdgeAbove(nullptr)
147    , fFirstEdgeBelow(nullptr), fLastEdgeBelow(nullptr)
148    , fProcessed(false)
149    , fAlpha(alpha)
150#if LOGGING_ENABLED
151    , fID (-1.0f)
152#endif
153    {}
154    SkPoint fPoint;           // Vertex position
155    Vertex* fPrev;            // Linked list of contours, then Y-sorted vertices.
156    Vertex* fNext;            // "
157    Edge*   fFirstEdgeAbove;  // Linked list of edges above this vertex.
158    Edge*   fLastEdgeAbove;   // "
159    Edge*   fFirstEdgeBelow;  // Linked list of edges below this vertex.
160    Edge*   fLastEdgeBelow;   // "
161    bool    fProcessed;       // Has this vertex been seen in simplify()?
162    uint8_t fAlpha;
163#if LOGGING_ENABLED
164    float   fID;              // Identifier used for logging.
165#endif
166};
167
168/***************************************************************************************/
169
170struct AAParams {
171    bool fTweakAlpha;
172    GrColor fColor;
173};
174
175typedef bool (*CompareFunc)(const SkPoint& a, const SkPoint& b);
176
177bool sweep_lt_horiz(const SkPoint& a, const SkPoint& b) {
178    return a.fX < b.fX || (a.fX == b.fX && a.fY > b.fY);
179}
180
181bool sweep_lt_vert(const SkPoint& a, const SkPoint& b) {
182    return a.fY < b.fY || (a.fY == b.fY && a.fX < b.fX);
183}
184
185bool sweep_gt_horiz(const SkPoint& a, const SkPoint& b) {
186    return a.fX > b.fX || (a.fX == b.fX && a.fY < b.fY);
187}
188
189bool sweep_gt_vert(const SkPoint& a, const SkPoint& b) {
190    return a.fY > b.fY || (a.fY == b.fY && a.fX > b.fX);
191}
192
193struct Comparator {
194    enum class Direction { kVertical, kHorizontal };
195    Comparator(Direction direction) : fDirection(direction) {}
196    bool sweep_lt(const SkPoint& a, const SkPoint& b) const {
197        return fDirection == Direction::kHorizontal ? sweep_lt_horiz(a, b) : sweep_lt_vert(a, b);
198    }
199    bool sweep_gt(const SkPoint& a, const SkPoint& b) const {
200        return fDirection == Direction::kHorizontal ? sweep_gt_horiz(a, b) : sweep_gt_vert(a, b);
201    }
202    Direction fDirection;
203};
204
205inline void* emit_vertex(Vertex* v, const AAParams* aaParams, void* data) {
206    if (!aaParams) {
207        SkPoint* d = static_cast<SkPoint*>(data);
208        *d++ = v->fPoint;
209        return d;
210    }
211    if (aaParams->fTweakAlpha) {
212        auto d = static_cast<GrDefaultGeoProcFactory::PositionColorAttr*>(data);
213        d->fPosition = v->fPoint;
214        d->fColor = SkAlphaMulQ(aaParams->fColor, SkAlpha255To256(v->fAlpha));
215        d++;
216        return d;
217    }
218    auto d = static_cast<GrDefaultGeoProcFactory::PositionColorCoverageAttr*>(data);
219    d->fPosition = v->fPoint;
220    d->fColor = aaParams->fColor;
221    d->fCoverage = GrNormalizeByteToFloat(v->fAlpha);
222    d++;
223    return d;
224}
225
226void* emit_triangle(Vertex* v0, Vertex* v1, Vertex* v2, const AAParams* aaParams, void* data) {
227    LOG("emit_triangle (%g, %g) %d\n", v0->fPoint.fX, v0->fPoint.fY, v0->fAlpha);
228    LOG("              (%g, %g) %d\n", v1->fPoint.fX, v1->fPoint.fY, v1->fAlpha);
229    LOG("              (%g, %g) %d\n", v2->fPoint.fX, v2->fPoint.fY, v2->fAlpha);
230#if TESSELLATOR_WIREFRAME
231    data = emit_vertex(v0, aaParams, data);
232    data = emit_vertex(v1, aaParams, data);
233    data = emit_vertex(v1, aaParams, data);
234    data = emit_vertex(v2, aaParams, data);
235    data = emit_vertex(v2, aaParams, data);
236    data = emit_vertex(v0, aaParams, data);
237#else
238    data = emit_vertex(v0, aaParams, data);
239    data = emit_vertex(v1, aaParams, data);
240    data = emit_vertex(v2, aaParams, data);
241#endif
242    return data;
243}
244
245struct VertexList {
246    VertexList() : fHead(nullptr), fTail(nullptr) {}
247    VertexList(Vertex* head, Vertex* tail) : fHead(head), fTail(tail) {}
248    Vertex* fHead;
249    Vertex* fTail;
250    void insert(Vertex* v, Vertex* prev, Vertex* next) {
251        list_insert<Vertex, &Vertex::fPrev, &Vertex::fNext>(v, prev, next, &fHead, &fTail);
252    }
253    void append(Vertex* v) {
254        insert(v, fTail, nullptr);
255    }
256    void prepend(Vertex* v) {
257        insert(v, nullptr, fHead);
258    }
259    void remove(Vertex* v) {
260        list_remove<Vertex, &Vertex::fPrev, &Vertex::fNext>(v, &fHead, &fTail);
261    }
262    void close() {
263        if (fHead && fTail) {
264            fTail->fNext = fHead;
265            fHead->fPrev = fTail;
266        }
267    }
268};
269
270// Round to nearest quarter-pixel. This is used for screenspace tessellation.
271
272inline void round(SkPoint* p) {
273    p->fX = SkScalarRoundToScalar(p->fX * SkFloatToScalar(4.0f)) * SkFloatToScalar(0.25f);
274    p->fY = SkScalarRoundToScalar(p->fY * SkFloatToScalar(4.0f)) * SkFloatToScalar(0.25f);
275}
276
277// A line equation in implicit form. fA * x + fB * y + fC = 0, for all points (x, y) on the line.
278struct Line {
279    Line(Vertex* p, Vertex* q) : Line(p->fPoint, q->fPoint) {}
280    Line(const SkPoint& p, const SkPoint& q)
281        : fA(static_cast<double>(q.fY) - p.fY)      // a = dY
282        , fB(static_cast<double>(p.fX) - q.fX)      // b = -dX
283        , fC(static_cast<double>(p.fY) * q.fX -     // c = cross(q, p)
284             static_cast<double>(p.fX) * q.fY) {}
285    double dist(const SkPoint& p) const {
286        return fA * p.fX + fB * p.fY + fC;
287    }
288    double magSq() const {
289        return fA * fA + fB * fB;
290    }
291
292    // Compute the intersection of two (infinite) Lines.
293    bool intersect(const Line& other, SkPoint* point) {
294        double denom = fA * other.fB - fB * other.fA;
295        if (denom == 0.0) {
296            return false;
297        }
298        double scale = 1.0f / denom;
299        point->fX = SkDoubleToScalar((fB * other.fC - other.fB * fC) * scale);
300        point->fY = SkDoubleToScalar((other.fA * fC - fA * other.fC) * scale);
301        return true;
302    }
303    double fA, fB, fC;
304};
305
306/**
307 * An Edge joins a top Vertex to a bottom Vertex. Edge ordering for the list of "edges above" and
308 * "edge below" a vertex as well as for the active edge list is handled by isLeftOf()/isRightOf().
309 * Note that an Edge will give occasionally dist() != 0 for its own endpoints (because floating
310 * point). For speed, that case is only tested by the callers which require it (e.g.,
311 * cleanup_active_edges()). Edges also handle checking for intersection with other edges.
312 * Currently, this converts the edges to the parametric form, in order to avoid doing a division
313 * until an intersection has been confirmed. This is slightly slower in the "found" case, but
314 * a lot faster in the "not found" case.
315 *
316 * The coefficients of the line equation stored in double precision to avoid catastrphic
317 * cancellation in the isLeftOf() and isRightOf() checks. Using doubles ensures that the result is
318 * correct in float, since it's a polynomial of degree 2. The intersect() function, being
319 * degree 5, is still subject to catastrophic cancellation. We deal with that by assuming its
320 * output may be incorrect, and adjusting the mesh topology to match (see comment at the top of
321 * this file).
322 */
323
324struct Edge {
325    enum class Type { kInner, kOuter, kConnector };
326    Edge(Vertex* top, Vertex* bottom, int winding, Type type)
327        : fWinding(winding)
328        , fTop(top)
329        , fBottom(bottom)
330        , fType(type)
331        , fLeft(nullptr)
332        , fRight(nullptr)
333        , fPrevEdgeAbove(nullptr)
334        , fNextEdgeAbove(nullptr)
335        , fPrevEdgeBelow(nullptr)
336        , fNextEdgeBelow(nullptr)
337        , fLeftPoly(nullptr)
338        , fRightPoly(nullptr)
339        , fLeftPolyPrev(nullptr)
340        , fLeftPolyNext(nullptr)
341        , fRightPolyPrev(nullptr)
342        , fRightPolyNext(nullptr)
343        , fUsedInLeftPoly(false)
344        , fUsedInRightPoly(false)
345        , fLine(top, bottom) {
346        }
347    int      fWinding;          // 1 == edge goes downward; -1 = edge goes upward.
348    Vertex*  fTop;              // The top vertex in vertex-sort-order (sweep_lt).
349    Vertex*  fBottom;           // The bottom vertex in vertex-sort-order.
350    Type     fType;
351    Edge*    fLeft;             // The linked list of edges in the active edge list.
352    Edge*    fRight;            // "
353    Edge*    fPrevEdgeAbove;    // The linked list of edges in the bottom Vertex's "edges above".
354    Edge*    fNextEdgeAbove;    // "
355    Edge*    fPrevEdgeBelow;    // The linked list of edges in the top Vertex's "edges below".
356    Edge*    fNextEdgeBelow;    // "
357    Poly*    fLeftPoly;         // The Poly to the left of this edge, if any.
358    Poly*    fRightPoly;        // The Poly to the right of this edge, if any.
359    Edge*    fLeftPolyPrev;
360    Edge*    fLeftPolyNext;
361    Edge*    fRightPolyPrev;
362    Edge*    fRightPolyNext;
363    bool     fUsedInLeftPoly;
364    bool     fUsedInRightPoly;
365    Line     fLine;
366    double dist(const SkPoint& p) const {
367        return fLine.dist(p);
368    }
369    bool isRightOf(Vertex* v) const {
370        return fLine.dist(v->fPoint) < 0.0;
371    }
372    bool isLeftOf(Vertex* v) const {
373        return fLine.dist(v->fPoint) > 0.0;
374    }
375    void recompute() {
376        fLine = Line(fTop, fBottom);
377    }
378    bool intersect(const Edge& other, SkPoint* p, uint8_t* alpha = nullptr) {
379        LOG("intersecting %g -> %g with %g -> %g\n",
380               fTop->fID, fBottom->fID,
381               other.fTop->fID, other.fBottom->fID);
382        if (fTop == other.fTop || fBottom == other.fBottom) {
383            return false;
384        }
385        double denom = fLine.fA * other.fLine.fB - fLine.fB * other.fLine.fA;
386        if (denom == 0.0) {
387            return false;
388        }
389        double dx = static_cast<double>(other.fTop->fPoint.fX) - fTop->fPoint.fX;
390        double dy = static_cast<double>(other.fTop->fPoint.fY) - fTop->fPoint.fY;
391        double sNumer = dy * other.fLine.fB + dx * other.fLine.fA;
392        double tNumer = dy * fLine.fB + dx * fLine.fA;
393        // If (sNumer / denom) or (tNumer / denom) is not in [0..1], exit early.
394        // This saves us doing the divide below unless absolutely necessary.
395        if (denom > 0.0 ? (sNumer < 0.0 || sNumer > denom || tNumer < 0.0 || tNumer > denom)
396                        : (sNumer > 0.0 || sNumer < denom || tNumer > 0.0 || tNumer < denom)) {
397            return false;
398        }
399        double s = sNumer / denom;
400        SkASSERT(s >= 0.0 && s <= 1.0);
401        p->fX = SkDoubleToScalar(fTop->fPoint.fX - s * fLine.fB);
402        p->fY = SkDoubleToScalar(fTop->fPoint.fY + s * fLine.fA);
403        if (alpha) {
404            if (fType == Type::kConnector) {
405                *alpha = (1.0 - s) * fTop->fAlpha + s * fBottom->fAlpha;
406            } else if (other.fType == Type::kConnector) {
407                double t = tNumer / denom;
408                *alpha = (1.0 - t) * other.fTop->fAlpha + t * other.fBottom->fAlpha;
409            } else if (fType == Type::kOuter && other.fType == Type::kOuter) {
410                *alpha = 0;
411            } else {
412                *alpha = 255;
413            }
414        }
415        return true;
416    }
417};
418
419struct EdgeList {
420    EdgeList() : fHead(nullptr), fTail(nullptr), fNext(nullptr) {}
421    Edge* fHead;
422    Edge* fTail;
423    EdgeList* fNext;
424    void insert(Edge* edge, Edge* prev, Edge* next) {
425        list_insert<Edge, &Edge::fLeft, &Edge::fRight>(edge, prev, next, &fHead, &fTail);
426    }
427    void append(Edge* e) {
428        insert(e, fTail, nullptr);
429    }
430    void remove(Edge* edge) {
431        list_remove<Edge, &Edge::fLeft, &Edge::fRight>(edge, &fHead, &fTail);
432    }
433    void close() {
434        if (fHead && fTail) {
435            fTail->fRight = fHead;
436            fHead->fLeft = fTail;
437        }
438    }
439    bool contains(Edge* edge) const {
440        return edge->fLeft || edge->fRight || fHead == edge;
441    }
442};
443
444/***************************************************************************************/
445
446struct Poly {
447    Poly(Vertex* v, int winding)
448        : fFirstVertex(v)
449        , fWinding(winding)
450        , fHead(nullptr)
451        , fTail(nullptr)
452        , fNext(nullptr)
453        , fPartner(nullptr)
454        , fCount(0)
455    {
456#if LOGGING_ENABLED
457        static int gID = 0;
458        fID = gID++;
459        LOG("*** created Poly %d\n", fID);
460#endif
461    }
462    typedef enum { kLeft_Side, kRight_Side } Side;
463    struct MonotonePoly {
464        MonotonePoly(Edge* edge, Side side)
465            : fSide(side)
466            , fFirstEdge(nullptr)
467            , fLastEdge(nullptr)
468            , fPrev(nullptr)
469            , fNext(nullptr) {
470            this->addEdge(edge);
471        }
472        Side          fSide;
473        Edge*         fFirstEdge;
474        Edge*         fLastEdge;
475        MonotonePoly* fPrev;
476        MonotonePoly* fNext;
477        void addEdge(Edge* edge) {
478            if (fSide == kRight_Side) {
479                SkASSERT(!edge->fUsedInRightPoly);
480                list_insert<Edge, &Edge::fRightPolyPrev, &Edge::fRightPolyNext>(
481                    edge, fLastEdge, nullptr, &fFirstEdge, &fLastEdge);
482                edge->fUsedInRightPoly = true;
483            } else {
484                SkASSERT(!edge->fUsedInLeftPoly);
485                list_insert<Edge, &Edge::fLeftPolyPrev, &Edge::fLeftPolyNext>(
486                    edge, fLastEdge, nullptr, &fFirstEdge, &fLastEdge);
487                edge->fUsedInLeftPoly = true;
488            }
489        }
490
491        void* emit(const AAParams* aaParams, void* data) {
492            Edge* e = fFirstEdge;
493            e->fTop->fPrev = e->fTop->fNext = nullptr;
494            VertexList vertices;
495            vertices.append(e->fTop);
496            while (e != nullptr) {
497                e->fBottom->fPrev = e->fBottom->fNext = nullptr;
498                if (kRight_Side == fSide) {
499                    vertices.append(e->fBottom);
500                    e = e->fRightPolyNext;
501                } else {
502                    vertices.prepend(e->fBottom);
503                    e = e->fLeftPolyNext;
504                }
505            }
506            Vertex* first = vertices.fHead;
507            Vertex* v = first->fNext;
508            while (v != vertices.fTail) {
509                SkASSERT(v && v->fPrev && v->fNext);
510                Vertex* prev = v->fPrev;
511                Vertex* curr = v;
512                Vertex* next = v->fNext;
513                double ax = static_cast<double>(curr->fPoint.fX) - prev->fPoint.fX;
514                double ay = static_cast<double>(curr->fPoint.fY) - prev->fPoint.fY;
515                double bx = static_cast<double>(next->fPoint.fX) - curr->fPoint.fX;
516                double by = static_cast<double>(next->fPoint.fY) - curr->fPoint.fY;
517                if (ax * by - ay * bx >= 0.0) {
518                    data = emit_triangle(prev, curr, next, aaParams, data);
519                    v->fPrev->fNext = v->fNext;
520                    v->fNext->fPrev = v->fPrev;
521                    if (v->fPrev == first) {
522                        v = v->fNext;
523                    } else {
524                        v = v->fPrev;
525                    }
526                } else {
527                    v = v->fNext;
528                }
529            }
530            return data;
531        }
532    };
533    Poly* addEdge(Edge* e, Side side, SkArenaAlloc& alloc) {
534        LOG("addEdge (%g -> %g) to poly %d, %s side\n",
535               e->fTop->fID, e->fBottom->fID, fID, side == kLeft_Side ? "left" : "right");
536        Poly* partner = fPartner;
537        Poly* poly = this;
538        if (side == kRight_Side) {
539            if (e->fUsedInRightPoly) {
540                return this;
541            }
542        } else {
543            if (e->fUsedInLeftPoly) {
544                return this;
545            }
546        }
547        if (partner) {
548            fPartner = partner->fPartner = nullptr;
549        }
550        if (!fTail) {
551            fHead = fTail = alloc.make<MonotonePoly>(e, side);
552            fCount += 2;
553        } else if (e->fBottom == fTail->fLastEdge->fBottom) {
554            return poly;
555        } else if (side == fTail->fSide) {
556            fTail->addEdge(e);
557            fCount++;
558        } else {
559            e = alloc.make<Edge>(fTail->fLastEdge->fBottom, e->fBottom, 1, Edge::Type::kInner);
560            fTail->addEdge(e);
561            fCount++;
562            if (partner) {
563                partner->addEdge(e, side, alloc);
564                poly = partner;
565            } else {
566                MonotonePoly* m = alloc.make<MonotonePoly>(e, side);
567                m->fPrev = fTail;
568                fTail->fNext = m;
569                fTail = m;
570            }
571        }
572        return poly;
573    }
574    void* emit(const AAParams* aaParams, void *data) {
575        if (fCount < 3) {
576            return data;
577        }
578        LOG("emit() %d, size %d\n", fID, fCount);
579        for (MonotonePoly* m = fHead; m != nullptr; m = m->fNext) {
580            data = m->emit(aaParams, data);
581        }
582        return data;
583    }
584    Vertex* lastVertex() const { return fTail ? fTail->fLastEdge->fBottom : fFirstVertex; }
585    Vertex* fFirstVertex;
586    int fWinding;
587    MonotonePoly* fHead;
588    MonotonePoly* fTail;
589    Poly* fNext;
590    Poly* fPartner;
591    int fCount;
592#if LOGGING_ENABLED
593    int fID;
594#endif
595};
596
597/***************************************************************************************/
598
599bool coincident(const SkPoint& a, const SkPoint& b) {
600    return a == b;
601}
602
603Poly* new_poly(Poly** head, Vertex* v, int winding, SkArenaAlloc& alloc) {
604    Poly* poly = alloc.make<Poly>(v, winding);
605    poly->fNext = *head;
606    *head = poly;
607    return poly;
608}
609
610EdgeList* new_contour(EdgeList** head, SkArenaAlloc& alloc) {
611    EdgeList* contour = alloc.make<EdgeList>();
612    contour->fNext = *head;
613    *head = contour;
614    return contour;
615}
616
617Vertex* append_point_to_contour(const SkPoint& p, Vertex* prev, Vertex** head,
618                                SkArenaAlloc& alloc) {
619    Vertex* v = alloc.make<Vertex>(p, 255);
620#if LOGGING_ENABLED
621    static float gID = 0.0f;
622    v->fID = gID++;
623#endif
624    if (prev) {
625        prev->fNext = v;
626        v->fPrev = prev;
627    } else {
628        *head = v;
629    }
630    return v;
631}
632
633Vertex* generate_quadratic_points(const SkPoint& p0,
634                                  const SkPoint& p1,
635                                  const SkPoint& p2,
636                                  SkScalar tolSqd,
637                                  Vertex* prev,
638                                  Vertex** head,
639                                  int pointsLeft,
640                                  SkArenaAlloc& alloc) {
641    SkScalar d = p1.distanceToLineSegmentBetweenSqd(p0, p2);
642    if (pointsLeft < 2 || d < tolSqd || !SkScalarIsFinite(d)) {
643        return append_point_to_contour(p2, prev, head, alloc);
644    }
645
646    const SkPoint q[] = {
647        { SkScalarAve(p0.fX, p1.fX), SkScalarAve(p0.fY, p1.fY) },
648        { SkScalarAve(p1.fX, p2.fX), SkScalarAve(p1.fY, p2.fY) },
649    };
650    const SkPoint r = { SkScalarAve(q[0].fX, q[1].fX), SkScalarAve(q[0].fY, q[1].fY) };
651
652    pointsLeft >>= 1;
653    prev = generate_quadratic_points(p0, q[0], r, tolSqd, prev, head, pointsLeft, alloc);
654    prev = generate_quadratic_points(r, q[1], p2, tolSqd, prev, head, pointsLeft, alloc);
655    return prev;
656}
657
658Vertex* generate_cubic_points(const SkPoint& p0,
659                              const SkPoint& p1,
660                              const SkPoint& p2,
661                              const SkPoint& p3,
662                              SkScalar tolSqd,
663                              Vertex* prev,
664                              Vertex** head,
665                              int pointsLeft,
666                              SkArenaAlloc& alloc) {
667    SkScalar d1 = p1.distanceToLineSegmentBetweenSqd(p0, p3);
668    SkScalar d2 = p2.distanceToLineSegmentBetweenSqd(p0, p3);
669    if (pointsLeft < 2 || (d1 < tolSqd && d2 < tolSqd) ||
670        !SkScalarIsFinite(d1) || !SkScalarIsFinite(d2)) {
671        return append_point_to_contour(p3, prev, head, alloc);
672    }
673    const SkPoint q[] = {
674        { SkScalarAve(p0.fX, p1.fX), SkScalarAve(p0.fY, p1.fY) },
675        { SkScalarAve(p1.fX, p2.fX), SkScalarAve(p1.fY, p2.fY) },
676        { SkScalarAve(p2.fX, p3.fX), SkScalarAve(p2.fY, p3.fY) }
677    };
678    const SkPoint r[] = {
679        { SkScalarAve(q[0].fX, q[1].fX), SkScalarAve(q[0].fY, q[1].fY) },
680        { SkScalarAve(q[1].fX, q[2].fX), SkScalarAve(q[1].fY, q[2].fY) }
681    };
682    const SkPoint s = { SkScalarAve(r[0].fX, r[1].fX), SkScalarAve(r[0].fY, r[1].fY) };
683    pointsLeft >>= 1;
684    prev = generate_cubic_points(p0, q[0], r[0], s, tolSqd, prev, head, pointsLeft, alloc);
685    prev = generate_cubic_points(s, r[1], q[2], p3, tolSqd, prev, head, pointsLeft, alloc);
686    return prev;
687}
688
689// Stage 1: convert the input path to a set of linear contours (linked list of Vertices).
690
691void path_to_contours(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
692                      Vertex** contours, SkArenaAlloc& alloc, bool *isLinear) {
693    SkScalar toleranceSqd = tolerance * tolerance;
694
695    SkPoint pts[4];
696    bool done = false;
697    *isLinear = true;
698    SkPath::Iter iter(path, false);
699    Vertex* prev = nullptr;
700    Vertex* head = nullptr;
701    if (path.isInverseFillType()) {
702        SkPoint quad[4];
703        clipBounds.toQuad(quad);
704        for (int i = 3; i >= 0; i--) {
705            prev = append_point_to_contour(quad[i], prev, &head, alloc);
706        }
707        head->fPrev = prev;
708        prev->fNext = head;
709        *contours++ = head;
710        head = prev = nullptr;
711    }
712    SkAutoConicToQuads converter;
713    while (!done) {
714        SkPath::Verb verb = iter.next(pts);
715        switch (verb) {
716            case SkPath::kConic_Verb: {
717                SkScalar weight = iter.conicWeight();
718                const SkPoint* quadPts = converter.computeQuads(pts, weight, toleranceSqd);
719                for (int i = 0; i < converter.countQuads(); ++i) {
720                    int pointsLeft = GrPathUtils::quadraticPointCount(quadPts, tolerance);
721                    prev = generate_quadratic_points(quadPts[0], quadPts[1], quadPts[2],
722                                                     toleranceSqd, prev, &head, pointsLeft, alloc);
723                    quadPts += 2;
724                }
725                *isLinear = false;
726                break;
727            }
728            case SkPath::kMove_Verb:
729                if (head) {
730                    head->fPrev = prev;
731                    prev->fNext = head;
732                    *contours++ = head;
733                }
734                head = prev = nullptr;
735                prev = append_point_to_contour(pts[0], prev, &head, alloc);
736                break;
737            case SkPath::kLine_Verb: {
738                prev = append_point_to_contour(pts[1], prev, &head, alloc);
739                break;
740            }
741            case SkPath::kQuad_Verb: {
742                int pointsLeft = GrPathUtils::quadraticPointCount(pts, tolerance);
743                prev = generate_quadratic_points(pts[0], pts[1], pts[2], toleranceSqd, prev,
744                                                 &head, pointsLeft, alloc);
745                *isLinear = false;
746                break;
747            }
748            case SkPath::kCubic_Verb: {
749                int pointsLeft = GrPathUtils::cubicPointCount(pts, tolerance);
750                prev = generate_cubic_points(pts[0], pts[1], pts[2], pts[3],
751                                toleranceSqd, prev, &head, pointsLeft, alloc);
752                *isLinear = false;
753                break;
754            }
755            case SkPath::kClose_Verb:
756                if (head) {
757                    head->fPrev = prev;
758                    prev->fNext = head;
759                    *contours++ = head;
760                }
761                head = prev = nullptr;
762                break;
763            case SkPath::kDone_Verb:
764                if (head) {
765                    head->fPrev = prev;
766                    prev->fNext = head;
767                    *contours++ = head;
768                }
769                done = true;
770                break;
771        }
772    }
773}
774
775inline bool apply_fill_type(SkPath::FillType fillType, int winding) {
776    switch (fillType) {
777        case SkPath::kWinding_FillType:
778            return winding != 0;
779        case SkPath::kEvenOdd_FillType:
780            return (winding & 1) != 0;
781        case SkPath::kInverseWinding_FillType:
782            return winding == 1;
783        case SkPath::kInverseEvenOdd_FillType:
784            return (winding & 1) == 1;
785        default:
786            SkASSERT(false);
787            return false;
788    }
789}
790
791inline bool apply_fill_type(SkPath::FillType fillType, Poly* poly) {
792    return poly && apply_fill_type(fillType, poly->fWinding);
793}
794
795Edge* new_edge(Vertex* prev, Vertex* next, Edge::Type type, Comparator& c, SkArenaAlloc& alloc) {
796    int winding = c.sweep_lt(prev->fPoint, next->fPoint) ? 1 : -1;
797    Vertex* top = winding < 0 ? next : prev;
798    Vertex* bottom = winding < 0 ? prev : next;
799    return alloc.make<Edge>(top, bottom, winding, type);
800}
801
802void remove_edge(Edge* edge, EdgeList* edges) {
803    LOG("removing edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
804    SkASSERT(edges->contains(edge));
805    edges->remove(edge);
806}
807
808void insert_edge(Edge* edge, Edge* prev, EdgeList* edges) {
809    LOG("inserting edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
810    SkASSERT(!edges->contains(edge));
811    Edge* next = prev ? prev->fRight : edges->fHead;
812    edges->insert(edge, prev, next);
813}
814
815void find_enclosing_edges(Vertex* v, EdgeList* edges, Edge** left, Edge** right) {
816    if (v->fFirstEdgeAbove) {
817        *left = v->fFirstEdgeAbove->fLeft;
818        *right = v->fLastEdgeAbove->fRight;
819        return;
820    }
821    Edge* next = nullptr;
822    Edge* prev;
823    for (prev = edges->fTail; prev != nullptr; prev = prev->fLeft) {
824        if (prev->isLeftOf(v)) {
825            break;
826        }
827        next = prev;
828    }
829    *left = prev;
830    *right = next;
831}
832
833void find_enclosing_edges(Edge* edge, EdgeList* edges, Comparator& c, Edge** left, Edge** right) {
834    Edge* prev = nullptr;
835    Edge* next;
836    for (next = edges->fHead; next != nullptr; next = next->fRight) {
837        if ((c.sweep_gt(edge->fTop->fPoint, next->fTop->fPoint) && next->isRightOf(edge->fTop)) ||
838            (c.sweep_gt(next->fTop->fPoint, edge->fTop->fPoint) && edge->isLeftOf(next->fTop)) ||
839            (c.sweep_lt(edge->fBottom->fPoint, next->fBottom->fPoint) &&
840             next->isRightOf(edge->fBottom)) ||
841            (c.sweep_lt(next->fBottom->fPoint, edge->fBottom->fPoint) &&
842             edge->isLeftOf(next->fBottom))) {
843            break;
844        }
845        prev = next;
846    }
847    *left = prev;
848    *right = next;
849}
850
851void fix_active_state(Edge* edge, EdgeList* activeEdges, Comparator& c) {
852    if (!activeEdges) {
853        return;
854    }
855    if (activeEdges->contains(edge)) {
856        if (edge->fBottom->fProcessed || !edge->fTop->fProcessed) {
857            remove_edge(edge, activeEdges);
858        }
859    } else if (edge->fTop->fProcessed && !edge->fBottom->fProcessed) {
860        Edge* left;
861        Edge* right;
862        find_enclosing_edges(edge, activeEdges, c, &left, &right);
863        insert_edge(edge, left, activeEdges);
864    }
865}
866
867void insert_edge_above(Edge* edge, Vertex* v, Comparator& c) {
868    if (edge->fTop->fPoint == edge->fBottom->fPoint ||
869        c.sweep_gt(edge->fTop->fPoint, edge->fBottom->fPoint)) {
870        return;
871    }
872    LOG("insert edge (%g -> %g) above vertex %g\n", edge->fTop->fID, edge->fBottom->fID, v->fID);
873    Edge* prev = nullptr;
874    Edge* next;
875    for (next = v->fFirstEdgeAbove; next; next = next->fNextEdgeAbove) {
876        if (next->isRightOf(edge->fTop)) {
877            break;
878        }
879        prev = next;
880    }
881    list_insert<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
882        edge, prev, next, &v->fFirstEdgeAbove, &v->fLastEdgeAbove);
883}
884
885void insert_edge_below(Edge* edge, Vertex* v, Comparator& c) {
886    if (edge->fTop->fPoint == edge->fBottom->fPoint ||
887        c.sweep_gt(edge->fTop->fPoint, edge->fBottom->fPoint)) {
888        return;
889    }
890    LOG("insert edge (%g -> %g) below vertex %g\n", edge->fTop->fID, edge->fBottom->fID, v->fID);
891    Edge* prev = nullptr;
892    Edge* next;
893    for (next = v->fFirstEdgeBelow; next; next = next->fNextEdgeBelow) {
894        if (next->isRightOf(edge->fBottom)) {
895            break;
896        }
897        prev = next;
898    }
899    list_insert<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
900        edge, prev, next, &v->fFirstEdgeBelow, &v->fLastEdgeBelow);
901}
902
903void remove_edge_above(Edge* edge) {
904    LOG("removing edge (%g -> %g) above vertex %g\n", edge->fTop->fID, edge->fBottom->fID,
905        edge->fBottom->fID);
906    list_remove<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
907        edge, &edge->fBottom->fFirstEdgeAbove, &edge->fBottom->fLastEdgeAbove);
908}
909
910void remove_edge_below(Edge* edge) {
911    LOG("removing edge (%g -> %g) below vertex %g\n", edge->fTop->fID, edge->fBottom->fID,
912        edge->fTop->fID);
913    list_remove<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
914        edge, &edge->fTop->fFirstEdgeBelow, &edge->fTop->fLastEdgeBelow);
915}
916
917void disconnect(Edge* edge)
918{
919    remove_edge_above(edge);
920    remove_edge_below(edge);
921}
922
923void erase_edge(Edge* edge, EdgeList* edges) {
924    LOG("erasing edge (%g -> %g)\n", edge->fTop->fID, edge->fBottom->fID);
925    disconnect(edge);
926    if (edges && edges->contains(edge)) {
927        remove_edge(edge, edges);
928    }
929}
930
931void merge_collinear_edges(Edge* edge, EdgeList* activeEdges, Comparator& c);
932
933void set_top(Edge* edge, Vertex* v, EdgeList* activeEdges, Comparator& c) {
934    remove_edge_below(edge);
935    edge->fTop = v;
936    edge->recompute();
937    insert_edge_below(edge, v, c);
938    fix_active_state(edge, activeEdges, c);
939    merge_collinear_edges(edge, activeEdges, c);
940}
941
942void set_bottom(Edge* edge, Vertex* v, EdgeList* activeEdges, Comparator& c) {
943    remove_edge_above(edge);
944    edge->fBottom = v;
945    edge->recompute();
946    insert_edge_above(edge, v, c);
947    fix_active_state(edge, activeEdges, c);
948    merge_collinear_edges(edge, activeEdges, c);
949}
950
951void merge_edges_above(Edge* edge, Edge* other, EdgeList* activeEdges, Comparator& c) {
952    if (coincident(edge->fTop->fPoint, other->fTop->fPoint)) {
953        LOG("merging coincident above edges (%g, %g) -> (%g, %g)\n",
954            edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
955            edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
956        other->fWinding += edge->fWinding;
957        erase_edge(edge, activeEdges);
958    } else if (c.sweep_lt(edge->fTop->fPoint, other->fTop->fPoint)) {
959        other->fWinding += edge->fWinding;
960        set_bottom(edge, other->fTop, activeEdges, c);
961    } else {
962        edge->fWinding += other->fWinding;
963        set_bottom(other, edge->fTop, activeEdges, c);
964    }
965}
966
967void merge_edges_below(Edge* edge, Edge* other, EdgeList* activeEdges, Comparator& c) {
968    if (coincident(edge->fBottom->fPoint, other->fBottom->fPoint)) {
969        LOG("merging coincident below edges (%g, %g) -> (%g, %g)\n",
970            edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
971            edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
972        other->fWinding += edge->fWinding;
973        erase_edge(edge, activeEdges);
974    } else if (c.sweep_lt(edge->fBottom->fPoint, other->fBottom->fPoint)) {
975        edge->fWinding += other->fWinding;
976        set_top(other, edge->fBottom, activeEdges, c);
977    } else {
978        other->fWinding += edge->fWinding;
979        set_top(edge, other->fBottom, activeEdges, c);
980    }
981}
982
983void merge_collinear_edges(Edge* edge, EdgeList* activeEdges, Comparator& c) {
984    if (edge->fPrevEdgeAbove && (edge->fTop == edge->fPrevEdgeAbove->fTop ||
985                                 !edge->fPrevEdgeAbove->isLeftOf(edge->fTop))) {
986        merge_edges_above(edge, edge->fPrevEdgeAbove, activeEdges, c);
987    } else if (edge->fNextEdgeAbove && (edge->fTop == edge->fNextEdgeAbove->fTop ||
988                                        !edge->isLeftOf(edge->fNextEdgeAbove->fTop))) {
989        merge_edges_above(edge, edge->fNextEdgeAbove, activeEdges, c);
990    }
991    if (edge->fPrevEdgeBelow && (edge->fBottom == edge->fPrevEdgeBelow->fBottom ||
992                                 !edge->fPrevEdgeBelow->isLeftOf(edge->fBottom))) {
993        merge_edges_below(edge, edge->fPrevEdgeBelow, activeEdges, c);
994    } else if (edge->fNextEdgeBelow && (edge->fBottom == edge->fNextEdgeBelow->fBottom ||
995                                        !edge->isLeftOf(edge->fNextEdgeBelow->fBottom))) {
996        merge_edges_below(edge, edge->fNextEdgeBelow, activeEdges, c);
997    }
998}
999
1000void split_edge(Edge* edge, Vertex* v, EdgeList* activeEdges, Comparator& c, SkArenaAlloc& alloc);
1001
1002void cleanup_active_edges(Edge* edge, EdgeList* activeEdges, Comparator& c, SkArenaAlloc& alloc) {
1003    Vertex* top = edge->fTop;
1004    Vertex* bottom = edge->fBottom;
1005    if (edge->fLeft) {
1006        Vertex* leftTop = edge->fLeft->fTop;
1007        Vertex* leftBottom = edge->fLeft->fBottom;
1008        if (c.sweep_gt(top->fPoint, leftTop->fPoint) && !edge->fLeft->isLeftOf(top)) {
1009            split_edge(edge->fLeft, edge->fTop, activeEdges, c, alloc);
1010        } else if (c.sweep_gt(leftTop->fPoint, top->fPoint) && !edge->isRightOf(leftTop)) {
1011            split_edge(edge, leftTop, activeEdges, c, alloc);
1012        } else if (c.sweep_lt(bottom->fPoint, leftBottom->fPoint) &&
1013                   !edge->fLeft->isLeftOf(bottom)) {
1014            split_edge(edge->fLeft, bottom, activeEdges, c, alloc);
1015        } else if (c.sweep_lt(leftBottom->fPoint, bottom->fPoint) && !edge->isRightOf(leftBottom)) {
1016            split_edge(edge, leftBottom, activeEdges, c, alloc);
1017        }
1018    }
1019    if (edge->fRight) {
1020        Vertex* rightTop = edge->fRight->fTop;
1021        Vertex* rightBottom = edge->fRight->fBottom;
1022        if (c.sweep_gt(top->fPoint, rightTop->fPoint) && !edge->fRight->isRightOf(top)) {
1023            split_edge(edge->fRight, top, activeEdges, c, alloc);
1024        } else if (c.sweep_gt(rightTop->fPoint, top->fPoint) && !edge->isLeftOf(rightTop)) {
1025            split_edge(edge, rightTop, activeEdges, c, alloc);
1026        } else if (c.sweep_lt(bottom->fPoint, rightBottom->fPoint) &&
1027                   !edge->fRight->isRightOf(bottom)) {
1028            split_edge(edge->fRight, bottom, activeEdges, c, alloc);
1029        } else if (c.sweep_lt(rightBottom->fPoint, bottom->fPoint) &&
1030                   !edge->isLeftOf(rightBottom)) {
1031            split_edge(edge, rightBottom, activeEdges, c, alloc);
1032        }
1033    }
1034}
1035
1036void split_edge(Edge* edge, Vertex* v, EdgeList* activeEdges, Comparator& c, SkArenaAlloc& alloc) {
1037    LOG("splitting edge (%g -> %g) at vertex %g (%g, %g)\n",
1038        edge->fTop->fID, edge->fBottom->fID,
1039        v->fID, v->fPoint.fX, v->fPoint.fY);
1040    if (c.sweep_lt(v->fPoint, edge->fTop->fPoint)) {
1041        set_top(edge, v, activeEdges, c);
1042    } else if (c.sweep_gt(v->fPoint, edge->fBottom->fPoint)) {
1043        set_bottom(edge, v, activeEdges, c);
1044    } else {
1045        Edge* newEdge = alloc.make<Edge>(v, edge->fBottom, edge->fWinding, edge->fType);
1046        insert_edge_below(newEdge, v, c);
1047        insert_edge_above(newEdge, edge->fBottom, c);
1048        set_bottom(edge, v, activeEdges, c);
1049        cleanup_active_edges(edge, activeEdges, c, alloc);
1050        fix_active_state(newEdge, activeEdges, c);
1051        merge_collinear_edges(newEdge, activeEdges, c);
1052    }
1053}
1054
1055Edge* connect(Vertex* prev, Vertex* next, Edge::Type type, Comparator& c, SkArenaAlloc& alloc,
1056              int winding_scale = 1) {
1057    Edge* edge = new_edge(prev, next, type, c, alloc);
1058    insert_edge_below(edge, edge->fTop, c);
1059    insert_edge_above(edge, edge->fBottom, c);
1060    edge->fWinding *= winding_scale;
1061    merge_collinear_edges(edge, nullptr, c);
1062    return edge;
1063}
1064
1065void merge_vertices(Vertex* src, Vertex* dst, VertexList* mesh, Comparator& c,
1066                    SkArenaAlloc& alloc) {
1067    LOG("found coincident verts at %g, %g; merging %g into %g\n", src->fPoint.fX, src->fPoint.fY,
1068        src->fID, dst->fID);
1069    dst->fAlpha = SkTMax(src->fAlpha, dst->fAlpha);
1070    for (Edge* edge = src->fFirstEdgeAbove; edge;) {
1071        Edge* next = edge->fNextEdgeAbove;
1072        set_bottom(edge, dst, nullptr, c);
1073        edge = next;
1074    }
1075    for (Edge* edge = src->fFirstEdgeBelow; edge;) {
1076        Edge* next = edge->fNextEdgeBelow;
1077        set_top(edge, dst, nullptr, c);
1078        edge = next;
1079    }
1080    mesh->remove(src);
1081}
1082
1083uint8_t max_edge_alpha(Edge* a, Edge* b) {
1084    if (a->fType == Edge::Type::kInner || b->fType == Edge::Type::kInner) {
1085        return 255;
1086    } else if (a->fType == Edge::Type::kOuter && b->fType == Edge::Type::kOuter) {
1087        return 0;
1088    } else {
1089        return SkTMax(SkTMax(a->fTop->fAlpha, a->fBottom->fAlpha),
1090                      SkTMax(b->fTop->fAlpha, b->fBottom->fAlpha));
1091    }
1092}
1093
1094Vertex* check_for_intersection(Edge* edge, Edge* other, EdgeList* activeEdges, Comparator& c,
1095                               SkArenaAlloc& alloc) {
1096    if (!edge || !other) {
1097        return nullptr;
1098    }
1099    SkPoint p;
1100    uint8_t alpha;
1101    if (edge->intersect(*other, &p, &alpha)) {
1102        Vertex* v;
1103        LOG("found intersection, pt is %g, %g\n", p.fX, p.fY);
1104        if (p == edge->fTop->fPoint || c.sweep_lt(p, edge->fTop->fPoint)) {
1105            split_edge(other, edge->fTop, activeEdges, c, alloc);
1106            v = edge->fTop;
1107        } else if (p == edge->fBottom->fPoint || c.sweep_gt(p, edge->fBottom->fPoint)) {
1108            split_edge(other, edge->fBottom, activeEdges, c, alloc);
1109            v = edge->fBottom;
1110        } else if (p == other->fTop->fPoint || c.sweep_lt(p, other->fTop->fPoint)) {
1111            split_edge(edge, other->fTop, activeEdges, c, alloc);
1112            v = other->fTop;
1113        } else if (p == other->fBottom->fPoint || c.sweep_gt(p, other->fBottom->fPoint)) {
1114            split_edge(edge, other->fBottom, activeEdges, c, alloc);
1115            v = other->fBottom;
1116        } else {
1117            Vertex* nextV = edge->fTop;
1118            while (c.sweep_lt(p, nextV->fPoint)) {
1119                nextV = nextV->fPrev;
1120            }
1121            while (c.sweep_lt(nextV->fPoint, p)) {
1122                nextV = nextV->fNext;
1123            }
1124            Vertex* prevV = nextV->fPrev;
1125            if (coincident(prevV->fPoint, p)) {
1126                v = prevV;
1127            } else if (coincident(nextV->fPoint, p)) {
1128                v = nextV;
1129            } else {
1130                v = alloc.make<Vertex>(p, alpha);
1131                LOG("inserting between %g (%g, %g) and %g (%g, %g)\n",
1132                    prevV->fID, prevV->fPoint.fX, prevV->fPoint.fY,
1133                    nextV->fID, nextV->fPoint.fX, nextV->fPoint.fY);
1134#if LOGGING_ENABLED
1135                v->fID = (nextV->fID + prevV->fID) * 0.5f;
1136#endif
1137                v->fPrev = prevV;
1138                v->fNext = nextV;
1139                prevV->fNext = v;
1140                nextV->fPrev = v;
1141            }
1142            split_edge(edge, v, activeEdges, c, alloc);
1143            split_edge(other, v, activeEdges, c, alloc);
1144        }
1145        v->fAlpha = SkTMax(v->fAlpha, alpha);
1146        return v;
1147    }
1148    return nullptr;
1149}
1150
1151void sanitize_contours(Vertex** contours, int contourCnt, bool approximate) {
1152    for (int i = 0; i < contourCnt; ++i) {
1153        SkASSERT(contours[i]);
1154        if (approximate) {
1155            round(&contours[i]->fPrev->fPoint);
1156        }
1157        for (Vertex* v = contours[i];;) {
1158            if (approximate) {
1159                round(&v->fPoint);
1160            }
1161            if (coincident(v->fPrev->fPoint, v->fPoint)) {
1162                LOG("vertex %g,%g coincident; removing\n", v->fPoint.fX, v->fPoint.fY);
1163                if (v->fPrev == v) {
1164                    contours[i] = nullptr;
1165                    break;
1166                }
1167                v->fPrev->fNext = v->fNext;
1168                v->fNext->fPrev = v->fPrev;
1169                if (contours[i] == v) {
1170                    contours[i] = v->fPrev;
1171                }
1172                v = v->fPrev;
1173            } else {
1174                v = v->fNext;
1175                if (v == contours[i]) break;
1176            }
1177        }
1178    }
1179}
1180
1181void merge_coincident_vertices(VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1182    for (Vertex* v = mesh->fHead->fNext; v != nullptr; v = v->fNext) {
1183        if (c.sweep_lt(v->fPoint, v->fPrev->fPoint)) {
1184            v->fPoint = v->fPrev->fPoint;
1185        }
1186        if (coincident(v->fPrev->fPoint, v->fPoint)) {
1187            merge_vertices(v->fPrev, v, mesh, c, alloc);
1188        }
1189    }
1190}
1191
1192// Stage 2: convert the contours to a mesh of edges connecting the vertices.
1193
1194void build_edges(Vertex** contours, int contourCnt, VertexList* mesh, Comparator& c,
1195                 SkArenaAlloc& alloc) {
1196    Vertex* prev = nullptr;
1197    for (int i = 0; i < contourCnt; ++i) {
1198        for (Vertex* v = contours[i]; v != nullptr;) {
1199            Vertex* vNext = v->fNext;
1200            connect(v->fPrev, v, Edge::Type::kInner, c, alloc);
1201            if (prev) {
1202                prev->fNext = v;
1203                v->fPrev = prev;
1204            } else {
1205                mesh->fHead = v;
1206            }
1207            prev = v;
1208            v = vNext;
1209            if (v == contours[i]) break;
1210        }
1211    }
1212    if (prev) {
1213        prev->fNext = mesh->fHead->fPrev = nullptr;
1214    }
1215    mesh->fTail = prev;
1216}
1217
1218// Stage 3: sort the vertices by increasing sweep direction.
1219
1220template <CompareFunc sweep_lt>
1221void merge_sort(VertexList* vertices) {
1222    Vertex* slow = vertices->fHead;
1223    if (!slow) {
1224        return;
1225    }
1226    Vertex* fast = slow->fNext;
1227    if (!fast) {
1228        return;
1229    }
1230    do {
1231        fast = fast->fNext;
1232        if (fast) {
1233            fast = fast->fNext;
1234            slow = slow->fNext;
1235        }
1236    } while (fast);
1237    VertexList front(vertices->fHead, slow);
1238    VertexList back(slow->fNext, vertices->fTail);
1239    front.fTail->fNext = back.fHead->fPrev = nullptr;
1240
1241    merge_sort<sweep_lt>(&front);
1242    merge_sort<sweep_lt>(&back);
1243
1244    vertices->fHead = vertices->fTail = nullptr;
1245    Vertex* a = front.fHead;
1246    Vertex* b = back.fHead;
1247    while (a && b) {
1248        if (sweep_lt(a->fPoint, b->fPoint)) {
1249            Vertex* next = a->fNext;
1250            vertices->append(a);
1251            a = next;
1252        } else {
1253            Vertex* next = b->fNext;
1254            vertices->append(b);
1255            b = next;
1256        }
1257    }
1258    if (a) {
1259        vertices->insert(a, vertices->fTail, a->fNext);
1260    }
1261    if (b) {
1262        vertices->insert(b, vertices->fTail, b->fNext);
1263    }
1264}
1265
1266// Stage 4: Simplify the mesh by inserting new vertices at intersecting edges.
1267
1268void simplify(const VertexList& vertices, Comparator& c, SkArenaAlloc& alloc) {
1269    LOG("simplifying complex polygons\n");
1270    EdgeList activeEdges;
1271    for (Vertex* v = vertices.fHead; v != nullptr; v = v->fNext) {
1272        if (!v->fFirstEdgeAbove && !v->fFirstEdgeBelow) {
1273            continue;
1274        }
1275#if LOGGING_ENABLED
1276        LOG("\nvertex %g: (%g,%g), alpha %d\n", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1277#endif
1278        Edge* leftEnclosingEdge;
1279        Edge* rightEnclosingEdge;
1280        bool restartChecks;
1281        do {
1282            restartChecks = false;
1283            find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1284            if (v->fFirstEdgeBelow) {
1285                for (Edge* edge = v->fFirstEdgeBelow; edge; edge = edge->fNextEdgeBelow) {
1286                    if (check_for_intersection(edge, leftEnclosingEdge, &activeEdges, c, alloc)) {
1287                        restartChecks = true;
1288                        break;
1289                    }
1290                    if (check_for_intersection(edge, rightEnclosingEdge, &activeEdges, c, alloc)) {
1291                        restartChecks = true;
1292                        break;
1293                    }
1294                }
1295            } else {
1296                if (Vertex* pv = check_for_intersection(leftEnclosingEdge, rightEnclosingEdge,
1297                                                        &activeEdges, c, alloc)) {
1298                    if (c.sweep_lt(pv->fPoint, v->fPoint)) {
1299                        v = pv;
1300                    }
1301                    restartChecks = true;
1302                }
1303
1304            }
1305        } while (restartChecks);
1306        if (v->fAlpha == 0) {
1307            if ((leftEnclosingEdge && leftEnclosingEdge->fWinding < 0) &&
1308                (rightEnclosingEdge && rightEnclosingEdge->fWinding > 0)) {
1309                v->fAlpha = max_edge_alpha(leftEnclosingEdge, rightEnclosingEdge);
1310            }
1311        }
1312        for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1313            remove_edge(e, &activeEdges);
1314        }
1315        Edge* leftEdge = leftEnclosingEdge;
1316        for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1317            insert_edge(e, leftEdge, &activeEdges);
1318            leftEdge = e;
1319        }
1320        v->fProcessed = true;
1321    }
1322}
1323
1324// Stage 5: Tessellate the simplified mesh into monotone polygons.
1325
1326Poly* tessellate(const VertexList& vertices, SkArenaAlloc& alloc) {
1327    LOG("tessellating simple polygons\n");
1328    EdgeList activeEdges;
1329    Poly* polys = nullptr;
1330    for (Vertex* v = vertices.fHead; v != nullptr; v = v->fNext) {
1331        if (!v->fFirstEdgeAbove && !v->fFirstEdgeBelow) {
1332            continue;
1333        }
1334#if LOGGING_ENABLED
1335        LOG("\nvertex %g: (%g,%g), alpha %d\n", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1336#endif
1337        Edge* leftEnclosingEdge;
1338        Edge* rightEnclosingEdge;
1339        find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1340        Poly* leftPoly;
1341        Poly* rightPoly;
1342        if (v->fFirstEdgeAbove) {
1343            leftPoly = v->fFirstEdgeAbove->fLeftPoly;
1344            rightPoly = v->fLastEdgeAbove->fRightPoly;
1345        } else {
1346            leftPoly = leftEnclosingEdge ? leftEnclosingEdge->fRightPoly : nullptr;
1347            rightPoly = rightEnclosingEdge ? rightEnclosingEdge->fLeftPoly : nullptr;
1348        }
1349#if LOGGING_ENABLED
1350        LOG("edges above:\n");
1351        for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1352            LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1353                e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1354        }
1355        LOG("edges below:\n");
1356        for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1357            LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1358                e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1359        }
1360#endif
1361        if (v->fFirstEdgeAbove) {
1362            if (leftPoly) {
1363                leftPoly = leftPoly->addEdge(v->fFirstEdgeAbove, Poly::kRight_Side, alloc);
1364            }
1365            if (rightPoly) {
1366                rightPoly = rightPoly->addEdge(v->fLastEdgeAbove, Poly::kLeft_Side, alloc);
1367            }
1368            for (Edge* e = v->fFirstEdgeAbove; e != v->fLastEdgeAbove; e = e->fNextEdgeAbove) {
1369                Edge* rightEdge = e->fNextEdgeAbove;
1370                SkASSERT(rightEdge->isRightOf(e->fTop));
1371                remove_edge(e, &activeEdges);
1372                if (e->fRightPoly) {
1373                    e->fRightPoly->addEdge(e, Poly::kLeft_Side, alloc);
1374                }
1375                if (rightEdge->fLeftPoly && rightEdge->fLeftPoly != e->fRightPoly) {
1376                    rightEdge->fLeftPoly->addEdge(e, Poly::kRight_Side, alloc);
1377                }
1378            }
1379            remove_edge(v->fLastEdgeAbove, &activeEdges);
1380            if (!v->fFirstEdgeBelow) {
1381                if (leftPoly && rightPoly && leftPoly != rightPoly) {
1382                    SkASSERT(leftPoly->fPartner == nullptr && rightPoly->fPartner == nullptr);
1383                    rightPoly->fPartner = leftPoly;
1384                    leftPoly->fPartner = rightPoly;
1385                }
1386            }
1387        }
1388        if (v->fFirstEdgeBelow) {
1389            if (!v->fFirstEdgeAbove) {
1390                if (leftPoly && rightPoly) {
1391                    if (leftPoly == rightPoly) {
1392                        if (leftPoly->fTail && leftPoly->fTail->fSide == Poly::kLeft_Side) {
1393                            leftPoly = new_poly(&polys, leftPoly->lastVertex(),
1394                                                 leftPoly->fWinding, alloc);
1395                            leftEnclosingEdge->fRightPoly = leftPoly;
1396                        } else {
1397                            rightPoly = new_poly(&polys, rightPoly->lastVertex(),
1398                                                 rightPoly->fWinding, alloc);
1399                            rightEnclosingEdge->fLeftPoly = rightPoly;
1400                        }
1401                    }
1402                    Edge* join = alloc.make<Edge>(leftPoly->lastVertex(), v, 1, Edge::Type::kInner);
1403                    leftPoly = leftPoly->addEdge(join, Poly::kRight_Side, alloc);
1404                    rightPoly = rightPoly->addEdge(join, Poly::kLeft_Side, alloc);
1405                }
1406            }
1407            Edge* leftEdge = v->fFirstEdgeBelow;
1408            leftEdge->fLeftPoly = leftPoly;
1409            insert_edge(leftEdge, leftEnclosingEdge, &activeEdges);
1410            for (Edge* rightEdge = leftEdge->fNextEdgeBelow; rightEdge;
1411                 rightEdge = rightEdge->fNextEdgeBelow) {
1412                insert_edge(rightEdge, leftEdge, &activeEdges);
1413                int winding = leftEdge->fLeftPoly ? leftEdge->fLeftPoly->fWinding : 0;
1414                winding += leftEdge->fWinding;
1415                if (winding != 0) {
1416                    Poly* poly = new_poly(&polys, v, winding, alloc);
1417                    leftEdge->fRightPoly = rightEdge->fLeftPoly = poly;
1418                }
1419                leftEdge = rightEdge;
1420            }
1421            v->fLastEdgeBelow->fRightPoly = rightPoly;
1422        }
1423#if LOGGING_ENABLED
1424        LOG("\nactive edges:\n");
1425        for (Edge* e = activeEdges.fHead; e != nullptr; e = e->fRight) {
1426            LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1427                e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1428        }
1429#endif
1430    }
1431    return polys;
1432}
1433
1434void remove_non_boundary_edges(const VertexList& mesh, SkPath::FillType fillType,
1435                               SkArenaAlloc& alloc) {
1436    LOG("removing non-boundary edges\n");
1437    EdgeList activeEdges;
1438    for (Vertex* v = mesh.fHead; v != nullptr; v = v->fNext) {
1439        if (!v->fFirstEdgeAbove && !v->fFirstEdgeBelow) {
1440            continue;
1441        }
1442        Edge* leftEnclosingEdge;
1443        Edge* rightEnclosingEdge;
1444        find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1445        bool prevFilled = leftEnclosingEdge &&
1446                          apply_fill_type(fillType, leftEnclosingEdge->fWinding);
1447        for (Edge* e = v->fFirstEdgeAbove; e;) {
1448            Edge* next = e->fNextEdgeAbove;
1449            remove_edge(e, &activeEdges);
1450            bool filled = apply_fill_type(fillType, e->fWinding);
1451            if (filled == prevFilled) {
1452                disconnect(e);
1453            }
1454            prevFilled = filled;
1455            e = next;
1456        }
1457        Edge* prev = leftEnclosingEdge;
1458        for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1459            if (prev) {
1460                e->fWinding += prev->fWinding;
1461            }
1462            insert_edge(e, prev, &activeEdges);
1463            prev = e;
1464        }
1465    }
1466}
1467
1468void get_edge_normal(const Edge* e, SkVector* normal) {
1469    normal->setNormalize(SkDoubleToScalar(e->fLine.fA) * e->fWinding,
1470                         SkDoubleToScalar(e->fLine.fB) * e->fWinding);
1471}
1472
1473// Stage 5c: detect and remove "pointy" vertices whose edge normals point in opposite directions
1474// and whose adjacent vertices are less than a quarter pixel from an edge. These are guaranteed to
1475// invert on stroking.
1476
1477void simplify_boundary(EdgeList* boundary, Comparator& c, SkArenaAlloc& alloc) {
1478    Edge* prevEdge = boundary->fTail;
1479    SkVector prevNormal;
1480    get_edge_normal(prevEdge, &prevNormal);
1481    for (Edge* e = boundary->fHead; e != nullptr;) {
1482        Vertex* prev = prevEdge->fWinding == 1 ? prevEdge->fTop : prevEdge->fBottom;
1483        Vertex* next = e->fWinding == 1 ? e->fBottom : e->fTop;
1484        double dist = e->dist(prev->fPoint);
1485        SkVector normal;
1486        get_edge_normal(e, &normal);
1487        float denom = 0.0625f * static_cast<float>(e->fLine.magSq());
1488        if (prevNormal.dot(normal) < 0.0 && (dist * dist) <= denom) {
1489            Edge* join = new_edge(prev, next, Edge::Type::kInner, c, alloc);
1490            insert_edge(join, e, boundary);
1491            remove_edge(prevEdge, boundary);
1492            remove_edge(e, boundary);
1493            if (join->fLeft && join->fRight) {
1494                prevEdge = join->fLeft;
1495                e = join;
1496            } else {
1497                prevEdge = boundary->fTail;
1498                e = boundary->fHead; // join->fLeft ? join->fLeft : join;
1499            }
1500            get_edge_normal(prevEdge, &prevNormal);
1501        } else {
1502            prevEdge = e;
1503            prevNormal = normal;
1504            e = e->fRight;
1505        }
1506    }
1507}
1508
1509void fix_inversions(Vertex* prev, Vertex* next, Edge* prevBisector, Edge* nextBisector,
1510                    Edge* prevEdge, Comparator& c) {
1511    if (!prev || !next) {
1512        return;
1513    }
1514    int winding = c.sweep_lt(prev->fPoint, next->fPoint) ? 1 : -1;
1515    SkPoint p;
1516    uint8_t alpha;
1517    if (winding != prevEdge->fWinding && prevBisector->intersect(*nextBisector, &p, &alpha)) {
1518        prev->fPoint = next->fPoint = p;
1519        prev->fAlpha = next->fAlpha = alpha;
1520    }
1521}
1522
1523// Stage 5d: Displace edges by half a pixel inward and outward along their normals. Intersect to
1524// find new vertices, and set zero alpha on the exterior and one alpha on the interior. Build a
1525// new antialiased mesh from those vertices.
1526
1527void boundary_to_aa_mesh(EdgeList* boundary, VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1528    // A boundary with fewer than 3 edges is degenerate.
1529    if (!boundary->fHead || !boundary->fHead->fRight || !boundary->fHead->fRight->fRight) {
1530        return;
1531    }
1532    Edge* prevEdge = boundary->fTail;
1533    float radius = 0.5f;
1534    double offset = radius * sqrt(prevEdge->fLine.magSq()) * prevEdge->fWinding;
1535    Line prevInner(prevEdge->fTop, prevEdge->fBottom);
1536    prevInner.fC -= offset;
1537    Line prevOuter(prevEdge->fTop, prevEdge->fBottom);
1538    prevOuter.fC += offset;
1539    VertexList innerVertices;
1540    VertexList outerVertices;
1541    Edge* prevBisector = nullptr;
1542    for (Edge* e = boundary->fHead; e != nullptr; e = e->fRight) {
1543        double offset = radius * sqrt(e->fLine.magSq()) * e->fWinding;
1544        Line inner(e->fTop, e->fBottom);
1545        inner.fC -= offset;
1546        Line outer(e->fTop, e->fBottom);
1547        outer.fC += offset;
1548        SkPoint innerPoint, outerPoint;
1549        if (prevInner.intersect(inner, &innerPoint) &&
1550            prevOuter.intersect(outer, &outerPoint)) {
1551            Vertex* innerVertex = alloc.make<Vertex>(innerPoint, 255);
1552            Vertex* outerVertex = alloc.make<Vertex>(outerPoint, 0);
1553            Edge* bisector = new_edge(outerVertex, innerVertex, Edge::Type::kConnector, c, alloc);
1554            fix_inversions(innerVertices.fTail, innerVertex, prevBisector, bisector, prevEdge, c);
1555            fix_inversions(outerVertices.fTail, outerVertex, prevBisector, bisector, prevEdge, c);
1556            innerVertices.append(innerVertex);
1557            outerVertices.append(outerVertex);
1558            prevBisector = bisector;
1559        }
1560        prevInner = inner;
1561        prevOuter = outer;
1562        prevEdge = e;
1563    }
1564    innerVertices.close();
1565    outerVertices.close();
1566
1567    Vertex* innerVertex = innerVertices.fHead;
1568    Vertex* outerVertex = outerVertices.fHead;
1569    if (!innerVertex || !outerVertex) {
1570        return;
1571    }
1572    Edge* bisector = new_edge(outerVertices.fHead, innerVertices.fHead, Edge::Type::kConnector, c,
1573                              alloc);
1574    fix_inversions(innerVertices.fTail, innerVertices.fHead, prevBisector, bisector, prevEdge, c);
1575    fix_inversions(outerVertices.fTail, outerVertices.fHead, prevBisector, bisector, prevEdge, c);
1576    do {
1577        // Connect vertices into a quad mesh. Outer edges get default (1) winding.
1578        // Inner edges get -2 winding. This ensures that the interior is always filled
1579        // (-1 winding number for normal cases, 3 for thin features where the interior inverts).
1580        // Connector edges get zero winding, since they're only structural (i.e., to ensure
1581        // no 0-0-0 alpha triangles are produced), and shouldn't affect the poly winding number.
1582        connect(outerVertex->fPrev, outerVertex, Edge::Type::kOuter, c, alloc);
1583        connect(innerVertex->fPrev, innerVertex, Edge::Type::kInner, c, alloc, -2);
1584        connect(outerVertex, innerVertex, Edge::Type::kConnector, c, alloc, 0);
1585        Vertex* innerNext = innerVertex->fNext;
1586        Vertex* outerNext = outerVertex->fNext;
1587        mesh->append(innerVertex);
1588        mesh->append(outerVertex);
1589        innerVertex = innerNext;
1590        outerVertex = outerNext;
1591    } while (innerVertex != innerVertices.fHead && outerVertex != outerVertices.fHead);
1592}
1593
1594void extract_boundary(EdgeList* boundary, Edge* e, SkPath::FillType fillType, SkArenaAlloc& alloc) {
1595    bool down = apply_fill_type(fillType, e->fWinding);
1596    while (e) {
1597        e->fWinding = down ? 1 : -1;
1598        Edge* next;
1599        boundary->append(e);
1600        if (down) {
1601            // Find outgoing edge, in clockwise order.
1602            if ((next = e->fNextEdgeAbove)) {
1603                down = false;
1604            } else if ((next = e->fBottom->fLastEdgeBelow)) {
1605                down = true;
1606            } else if ((next = e->fPrevEdgeAbove)) {
1607                down = false;
1608            }
1609        } else {
1610            // Find outgoing edge, in counter-clockwise order.
1611            if ((next = e->fPrevEdgeBelow)) {
1612                down = true;
1613            } else if ((next = e->fTop->fFirstEdgeAbove)) {
1614                down = false;
1615            } else if ((next = e->fNextEdgeBelow)) {
1616                down = true;
1617            }
1618        }
1619        disconnect(e);
1620        e = next;
1621    }
1622}
1623
1624// Stage 5b: Extract boundary edges.
1625
1626EdgeList* extract_boundaries(const VertexList& mesh, SkPath::FillType fillType,
1627                             SkArenaAlloc& alloc) {
1628    LOG("extracting boundaries\n");
1629    remove_non_boundary_edges(mesh, fillType, alloc);
1630    EdgeList* boundaries = nullptr;
1631    for (Vertex* v = mesh.fHead; v != nullptr; v = v->fNext) {
1632        while (v->fFirstEdgeBelow) {
1633            EdgeList* boundary = new_contour(&boundaries, alloc);
1634            extract_boundary(boundary, v->fFirstEdgeBelow, fillType, alloc);
1635        }
1636    }
1637    return boundaries;
1638}
1639
1640// This is a driver function which calls stages 2-5 in turn.
1641
1642void contours_to_mesh(Vertex** contours, int contourCnt, bool antialias,
1643                      VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1644#if LOGGING_ENABLED
1645    for (int i = 0; i < contourCnt; ++i) {
1646        Vertex* v = contours[i];
1647        SkASSERT(v);
1648        LOG("path.moveTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
1649        for (v = v->fNext; v != contours[i]; v = v->fNext) {
1650            LOG("path.lineTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
1651        }
1652    }
1653#endif
1654    sanitize_contours(contours, contourCnt, antialias);
1655    build_edges(contours, contourCnt, mesh, c, alloc);
1656}
1657
1658void sort_and_simplify(VertexList* vertices, Comparator& c, SkArenaAlloc& alloc) {
1659    if (!vertices || !vertices->fHead) {
1660        return;
1661    }
1662
1663    // Sort vertices in Y (secondarily in X).
1664    if (c.fDirection == Comparator::Direction::kHorizontal) {
1665        merge_sort<sweep_lt_horiz>(vertices);
1666    } else {
1667        merge_sort<sweep_lt_vert>(vertices);
1668    }
1669    merge_coincident_vertices(vertices, c, alloc);
1670#if LOGGING_ENABLED
1671    for (Vertex* v = vertices->fHead; v != nullptr; v = v->fNext) {
1672        static float gID = 0.0f;
1673        v->fID = gID++;
1674    }
1675#endif
1676    simplify(*vertices, c, alloc);
1677}
1678
1679Poly* contours_to_polys(Vertex** contours, int contourCnt, SkPath::FillType fillType,
1680                        const SkRect& pathBounds, bool antialias,
1681                        SkArenaAlloc& alloc) {
1682    Comparator c(pathBounds.width() > pathBounds.height() ? Comparator::Direction::kHorizontal
1683                                                          : Comparator::Direction::kVertical);
1684    VertexList mesh;
1685    contours_to_mesh(contours, contourCnt, antialias, &mesh, c, alloc);
1686    sort_and_simplify(&mesh, c, alloc);
1687    if (antialias) {
1688        EdgeList* boundaries = extract_boundaries(mesh, fillType, alloc);
1689        VertexList aaMesh;
1690        for (EdgeList* boundary = boundaries; boundary != nullptr; boundary = boundary->fNext) {
1691            simplify_boundary(boundary, c, alloc);
1692            boundary_to_aa_mesh(boundary, &aaMesh, c, alloc);
1693        }
1694        sort_and_simplify(&aaMesh, c, alloc);
1695        return tessellate(aaMesh, alloc);
1696    } else {
1697        return tessellate(mesh, alloc);
1698    }
1699}
1700
1701// Stage 6: Triangulate the monotone polygons into a vertex buffer.
1702void* polys_to_triangles(Poly* polys, SkPath::FillType fillType, const AAParams* aaParams,
1703                         void* data) {
1704    for (Poly* poly = polys; poly; poly = poly->fNext) {
1705        if (apply_fill_type(fillType, poly)) {
1706            data = poly->emit(aaParams, data);
1707        }
1708    }
1709    return data;
1710}
1711
1712Poly* path_to_polys(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
1713                    int contourCnt, SkArenaAlloc& alloc, bool antialias, bool* isLinear) {
1714    SkPath::FillType fillType = path.getFillType();
1715    if (SkPath::IsInverseFillType(fillType)) {
1716        contourCnt++;
1717    }
1718    std::unique_ptr<Vertex*[]> contours(new Vertex* [contourCnt]);
1719
1720    path_to_contours(path, tolerance, clipBounds, contours.get(), alloc, isLinear);
1721    return contours_to_polys(contours.get(), contourCnt, path.getFillType(), path.getBounds(),
1722                             antialias, alloc);
1723}
1724
1725int get_contour_count(const SkPath& path, SkScalar tolerance) {
1726    int contourCnt;
1727    int maxPts = GrPathUtils::worstCasePointCount(path, &contourCnt, tolerance);
1728    if (maxPts <= 0) {
1729        return 0;
1730    }
1731    if (maxPts > ((int)SK_MaxU16 + 1)) {
1732        SkDebugf("Path not rendered, too many verts (%d)\n", maxPts);
1733        return 0;
1734    }
1735    return contourCnt;
1736}
1737
1738int count_points(Poly* polys, SkPath::FillType fillType) {
1739    int count = 0;
1740    for (Poly* poly = polys; poly; poly = poly->fNext) {
1741        if (apply_fill_type(fillType, poly) && poly->fCount >= 3) {
1742            count += (poly->fCount - 2) * (TESSELLATOR_WIREFRAME ? 6 : 3);
1743        }
1744    }
1745    return count;
1746}
1747
1748} // namespace
1749
1750namespace GrTessellator {
1751
1752// Stage 6: Triangulate the monotone polygons into a vertex buffer.
1753
1754int PathToTriangles(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
1755                    VertexAllocator* vertexAllocator, bool antialias, const GrColor& color,
1756                    bool canTweakAlphaForCoverage, bool* isLinear) {
1757    int contourCnt = get_contour_count(path, tolerance);
1758    if (contourCnt <= 0) {
1759        *isLinear = true;
1760        return 0;
1761    }
1762    SkArenaAlloc alloc(kArenaChunkSize);
1763    Poly* polys = path_to_polys(path, tolerance, clipBounds, contourCnt, alloc, antialias,
1764                                isLinear);
1765    SkPath::FillType fillType = antialias ? SkPath::kWinding_FillType : path.getFillType();
1766    int count = count_points(polys, fillType);
1767    if (0 == count) {
1768        return 0;
1769    }
1770
1771    void* verts = vertexAllocator->lock(count);
1772    if (!verts) {
1773        SkDebugf("Could not allocate vertices\n");
1774        return 0;
1775    }
1776
1777    LOG("emitting %d verts\n", count);
1778    AAParams aaParams;
1779    aaParams.fTweakAlpha = canTweakAlphaForCoverage;
1780    aaParams.fColor = color;
1781
1782    void* end = polys_to_triangles(polys, fillType, antialias ? &aaParams : nullptr, verts);
1783    int actualCount = static_cast<int>((static_cast<uint8_t*>(end) - static_cast<uint8_t*>(verts))
1784                                       / vertexAllocator->stride());
1785    SkASSERT(actualCount <= count);
1786    vertexAllocator->unlock(actualCount);
1787    return actualCount;
1788}
1789
1790int PathToVertices(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
1791                   GrTessellator::WindingVertex** verts) {
1792    int contourCnt = get_contour_count(path, tolerance);
1793    if (contourCnt <= 0) {
1794        return 0;
1795    }
1796    SkArenaAlloc alloc(kArenaChunkSize);
1797    bool isLinear;
1798    Poly* polys = path_to_polys(path, tolerance, clipBounds, contourCnt, alloc, false, &isLinear);
1799    SkPath::FillType fillType = path.getFillType();
1800    int count = count_points(polys, fillType);
1801    if (0 == count) {
1802        *verts = nullptr;
1803        return 0;
1804    }
1805
1806    *verts = new GrTessellator::WindingVertex[count];
1807    GrTessellator::WindingVertex* vertsEnd = *verts;
1808    SkPoint* points = new SkPoint[count];
1809    SkPoint* pointsEnd = points;
1810    for (Poly* poly = polys; poly; poly = poly->fNext) {
1811        if (apply_fill_type(fillType, poly)) {
1812            SkPoint* start = pointsEnd;
1813            pointsEnd = static_cast<SkPoint*>(poly->emit(nullptr, pointsEnd));
1814            while (start != pointsEnd) {
1815                vertsEnd->fPos = *start;
1816                vertsEnd->fWinding = poly->fWinding;
1817                ++start;
1818                ++vertsEnd;
1819            }
1820        }
1821    }
1822    int actualCount = static_cast<int>(vertsEnd - *verts);
1823    SkASSERT(actualCount <= count);
1824    SkASSERT(pointsEnd - points == actualCount);
1825    delete[] points;
1826    return actualCount;
1827}
1828
1829} // namespace
1830