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