1/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "src/gpu/geometry/GrTriangulator.h"
9
10#include "src/gpu/BufferWriter.h"
11#include "src/gpu/GrEagerVertexAllocator.h"
12#include "src/gpu/geometry/GrPathUtils.h"
13
14#include "src/core/SkGeometry.h"
15#include "src/core/SkPointPriv.h"
16
17#include <algorithm>
18
19
20#if TRIANGULATOR_LOGGING
21#define TESS_LOG printf
22#define DUMP_MESH(M) (M).dump()
23#else
24#define TESS_LOG(...)
25#define DUMP_MESH(M)
26#endif
27
28using EdgeType = GrTriangulator::EdgeType;
29using Vertex = GrTriangulator::Vertex;
30using VertexList = GrTriangulator::VertexList;
31using Line = GrTriangulator::Line;
32using Edge = GrTriangulator::Edge;
33using EdgeList = GrTriangulator::EdgeList;
34using Poly = GrTriangulator::Poly;
35using MonotonePoly = GrTriangulator::MonotonePoly;
36using Comparator = GrTriangulator::Comparator;
37
38template <class T, T* T::*Prev, T* T::*Next>
39static void list_insert(T* t, T* prev, T* next, T** head, T** tail) {
40    t->*Prev = prev;
41    t->*Next = next;
42    if (prev) {
43        prev->*Next = t;
44    } else if (head) {
45        *head = t;
46    }
47    if (next) {
48        next->*Prev = t;
49    } else if (tail) {
50        *tail = t;
51    }
52}
53
54template <class T, T* T::*Prev, T* T::*Next>
55static void list_remove(T* t, T** head, T** tail) {
56    if (t->*Prev) {
57        t->*Prev->*Next = t->*Next;
58    } else if (head) {
59        *head = t->*Next;
60    }
61    if (t->*Next) {
62        t->*Next->*Prev = t->*Prev;
63    } else if (tail) {
64        *tail = t->*Prev;
65    }
66    t->*Prev = t->*Next = nullptr;
67}
68
69typedef bool (*CompareFunc)(const SkPoint& a, const SkPoint& b);
70
71static bool sweep_lt_horiz(const SkPoint& a, const SkPoint& b) {
72    return a.fX < b.fX || (a.fX == b.fX && a.fY > b.fY);
73}
74
75static bool sweep_lt_vert(const SkPoint& a, const SkPoint& b) {
76    return a.fY < b.fY || (a.fY == b.fY && a.fX < b.fX);
77}
78
79bool GrTriangulator::Comparator::sweep_lt(const SkPoint& a, const SkPoint& b) const {
80    return fDirection == Direction::kHorizontal ? sweep_lt_horiz(a, b) : sweep_lt_vert(a, b);
81}
82
83static inline void* emit_vertex(Vertex* v, bool emitCoverage, void* data) {
84    skgpu::VertexWriter verts{data};
85    verts << v->fPoint;
86
87    if (emitCoverage) {
88        verts << GrNormalizeByteToFloat(v->fAlpha);
89    }
90
91    return verts.ptr();
92}
93
94static void* emit_triangle(Vertex* v0, Vertex* v1, Vertex* v2, bool emitCoverage, void* data) {
95    TESS_LOG("emit_triangle %g (%g, %g) %d\n", v0->fID, v0->fPoint.fX, v0->fPoint.fY, v0->fAlpha);
96    TESS_LOG("              %g (%g, %g) %d\n", v1->fID, v1->fPoint.fX, v1->fPoint.fY, v1->fAlpha);
97    TESS_LOG("              %g (%g, %g) %d\n", v2->fID, v2->fPoint.fX, v2->fPoint.fY, v2->fAlpha);
98#if TESSELLATOR_WIREFRAME
99    data = emit_vertex(v0, emitCoverage, data);
100    data = emit_vertex(v1, emitCoverage, data);
101    data = emit_vertex(v1, emitCoverage, data);
102    data = emit_vertex(v2, emitCoverage, data);
103    data = emit_vertex(v2, emitCoverage, data);
104    data = emit_vertex(v0, emitCoverage, data);
105#else
106    data = emit_vertex(v0, emitCoverage, data);
107    data = emit_vertex(v1, emitCoverage, data);
108    data = emit_vertex(v2, emitCoverage, data);
109#endif
110    return data;
111}
112
113void GrTriangulator::VertexList::insert(Vertex* v, Vertex* prev, Vertex* next) {
114    list_insert<Vertex, &Vertex::fPrev, &Vertex::fNext>(v, prev, next, &fHead, &fTail);
115}
116
117void GrTriangulator::VertexList::remove(Vertex* v) {
118    list_remove<Vertex, &Vertex::fPrev, &Vertex::fNext>(v, &fHead, &fTail);
119}
120
121// Round to nearest quarter-pixel. This is used for screenspace tessellation.
122
123static inline void round(SkPoint* p) {
124    p->fX = SkScalarRoundToScalar(p->fX * SkFloatToScalar(4.0f)) * SkFloatToScalar(0.25f);
125    p->fY = SkScalarRoundToScalar(p->fY * SkFloatToScalar(4.0f)) * SkFloatToScalar(0.25f);
126}
127
128static inline SkScalar double_to_clamped_scalar(double d) {
129    // Clamps large values to what's finitely representable when cast back to a float.
130    static const double kMaxLimit = (double) SK_ScalarMax;
131    // It's not perfect, but a using a value larger than float_min helps protect from denormalized
132    // values and ill-conditions in intermediate calculations on coordinates.
133    static const double kNearZeroLimit = 16 * (double) std::numeric_limits<float>::min();
134    if (std::abs(d) < kNearZeroLimit) {
135        d = 0.f;
136    }
137    return SkDoubleToScalar(std::max(-kMaxLimit, std::min(d, kMaxLimit)));
138}
139
140bool GrTriangulator::Line::intersect(const Line& other, SkPoint* point) const {
141    double denom = fA * other.fB - fB * other.fA;
142    if (denom == 0.0) {
143        return false;
144    }
145    double scale = 1.0 / denom;
146    point->fX = double_to_clamped_scalar((fB * other.fC - other.fB * fC) * scale);
147    point->fY = double_to_clamped_scalar((other.fA * fC - fA * other.fC) * scale);
148     round(point);
149    return point->isFinite();
150}
151
152// If the edge's vertices differ by many orders of magnitude, the computed line equation can have
153// significant error in its distance and intersection tests. To avoid this, we recursively subdivide
154// long edges and effectively perform a binary search to perform a more accurate intersection test.
155static bool edge_line_needs_recursion(const SkPoint& p0, const SkPoint& p1) {
156    // ilogbf(0) returns an implementation-defined constant, but we are choosing to saturate
157    // negative exponents to 0 for comparisons sake. We're only trying to recurse on lines with
158    // very large coordinates.
159    int expDiffX = std::abs((std::abs(p0.fX) < 1.f ? 0 : std::ilogbf(p0.fX)) -
160                            (std::abs(p1.fX) < 1.f ? 0 : std::ilogbf(p1.fX)));
161    int expDiffY = std::abs((std::abs(p0.fY) < 1.f ? 0 : std::ilogbf(p0.fY)) -
162                            (std::abs(p1.fY) < 1.f ? 0 : std::ilogbf(p1.fY)));
163    // Differ by more than 2^20, or roughly a factor of one million.
164    return expDiffX > 20 || expDiffY > 20;
165}
166
167static bool recursive_edge_intersect(const Line& u, SkPoint u0, SkPoint u1,
168                                     const Line& v, SkPoint v0, SkPoint v1,
169                                     SkPoint* p, double* s, double* t) {
170    // First check if the bounding boxes of [u0,u1] intersects [v0,v1]. If they do not, then the
171    // two line segments cannot intersect in their domain (even if the lines themselves might).
172    // - don't use SkRect::intersect since the vertices aren't sorted and horiz/vertical lines
173    //   appear as empty rects, which then never "intersect" according to SkRect.
174    if (std::min(u0.fX, u1.fX) > std::max(v0.fX, v1.fX) ||
175        std::max(u0.fX, u1.fX) < std::min(v0.fX, v1.fX) ||
176        std::min(u0.fY, u1.fY) > std::max(v0.fY, v1.fY) ||
177        std::max(u0.fY, u1.fY) < std::min(v0.fY, v1.fY)) {
178        return false;
179    }
180
181    // Compute intersection based on current segment vertices; if an intersection is found but the
182    // vertices differ too much in magnitude, we recurse using the midpoint of the segment to
183    // reject false positives. We don't currently try to avoid false negatives (e.g. large magnitude
184    // line reports no intersection but there is one).
185    double denom = u.fA * v.fB - u.fB * v.fA;
186    if (denom == 0.0) {
187        return false;
188    }
189    double dx = static_cast<double>(v0.fX) - u0.fX;
190    double dy = static_cast<double>(v0.fY) - u0.fY;
191    double sNumer = dy * v.fB + dx * v.fA;
192    double tNumer = dy * u.fB + dx * u.fA;
193    // If (sNumer / denom) or (tNumer / denom) is not in [0..1], exit early.
194    // This saves us doing the divide below unless absolutely necessary.
195    if (denom > 0.0 ? (sNumer < 0.0 || sNumer > denom || tNumer < 0.0 || tNumer > denom)
196                    : (sNumer > 0.0 || sNumer < denom || tNumer > 0.0 || tNumer < denom)) {
197        return false;
198    }
199
200    *s = sNumer / denom;
201    *t = tNumer / denom;
202    SkASSERT(*s >= 0.0 && *s <= 1.0 && *t >= 0.0 && *t <= 1.0);
203
204    const bool uNeedsSplit = edge_line_needs_recursion(u0, u1);
205    const bool vNeedsSplit = edge_line_needs_recursion(v0, v1);
206    if (!uNeedsSplit && !vNeedsSplit) {
207        p->fX = double_to_clamped_scalar(u0.fX - (*s) * u.fB);
208        p->fY = double_to_clamped_scalar(u0.fY + (*s) * u.fA);
209        return true;
210    } else {
211        double sScale = 1.0, sShift = 0.0;
212        double tScale = 1.0, tShift = 0.0;
213
214        if (uNeedsSplit) {
215            SkPoint uM = {(float) (0.5 * u0.fX + 0.5 * u1.fX),
216                          (float) (0.5 * u0.fY + 0.5 * u1.fY)};
217            sScale = 0.5;
218            if (*s >= 0.5) {
219                u1 = uM;
220                sShift = 0.5;
221            } else {
222                u0 = uM;
223            }
224        }
225        if (vNeedsSplit) {
226            SkPoint vM = {(float) (0.5 * v0.fX + 0.5 * v1.fX),
227                          (float) (0.5 * v0.fY + 0.5 * v1.fY)};
228            tScale = 0.5;
229            if (*t >= 0.5) {
230                v1 = vM;
231                tShift = 0.5;
232            } else {
233                v0 = vM;
234            }
235        }
236
237        // Just recompute both lines, even if only one was split; we're already in a slow path.
238        if (recursive_edge_intersect(Line(u0, u1), u0, u1, Line(v0, v1), v0, v1, p, s, t)) {
239            // Adjust s and t back to full range
240            *s = sScale * (*s) + sShift;
241            *t = tScale * (*t) + tShift;
242            return true;
243        } else {
244            // False positive
245            return false;
246        }
247    }
248}
249
250bool GrTriangulator::Edge::intersect(const Edge& other, SkPoint* p, uint8_t* alpha) const {
251    TESS_LOG("intersecting %g -> %g with %g -> %g\n",
252             fTop->fID, fBottom->fID, other.fTop->fID, other.fBottom->fID);
253    if (fTop == other.fTop || fBottom == other.fBottom ||
254        fTop == other.fBottom || fBottom == other.fTop) {
255        // If the two edges share a vertex by construction, they have already been split and
256        // shouldn't be considered "intersecting" anymore.
257        return false;
258    }
259
260    double s, t; // needed to interpolate vertex alpha
261    const bool intersects = recursive_edge_intersect(
262            fLine, fTop->fPoint, fBottom->fPoint,
263            other.fLine, other.fTop->fPoint, other.fBottom->fPoint,
264            p, &s, &t);
265    if (!intersects) {
266        return false;
267    }
268
269    if (alpha) {
270        if (fType == EdgeType::kInner || other.fType == EdgeType::kInner) {
271            // If the intersection is on any interior edge, it needs to stay fully opaque or later
272            // triangulation could leech transparency into the inner fill region.
273            *alpha = 255;
274        } else if (fType == EdgeType::kOuter && other.fType == EdgeType::kOuter) {
275            // Trivially, the intersection will be fully transparent since since it is by
276            // construction on the outer edge.
277            *alpha = 0;
278        } else {
279            // Could be two connectors crossing, or a connector crossing an outer edge.
280            // Take the max interpolated alpha
281            SkASSERT(fType == EdgeType::kConnector || other.fType == EdgeType::kConnector);
282            *alpha = std::max((1.0 - s) * fTop->fAlpha + s * fBottom->fAlpha,
283                              (1.0 - t) * other.fTop->fAlpha + t * other.fBottom->fAlpha);
284        }
285    }
286    return true;
287}
288
289void GrTriangulator::EdgeList::insert(Edge* edge, Edge* prev, Edge* next) {
290    list_insert<Edge, &Edge::fLeft, &Edge::fRight>(edge, prev, next, &fHead, &fTail);
291}
292
293void GrTriangulator::EdgeList::remove(Edge* edge) {
294    TESS_LOG("removing edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
295    SkASSERT(this->contains(edge));
296    list_remove<Edge, &Edge::fLeft, &Edge::fRight>(edge, &fHead, &fTail);
297}
298
299void GrTriangulator::MonotonePoly::addEdge(Edge* edge) {
300    if (fSide == kRight_Side) {
301        SkASSERT(!edge->fUsedInRightPoly);
302        list_insert<Edge, &Edge::fRightPolyPrev, &Edge::fRightPolyNext>(
303            edge, fLastEdge, nullptr, &fFirstEdge, &fLastEdge);
304        edge->fUsedInRightPoly = true;
305    } else {
306        SkASSERT(!edge->fUsedInLeftPoly);
307        list_insert<Edge, &Edge::fLeftPolyPrev, &Edge::fLeftPolyNext>(
308            edge, fLastEdge, nullptr, &fFirstEdge, &fLastEdge);
309        edge->fUsedInLeftPoly = true;
310    }
311}
312
313void* GrTriangulator::emitMonotonePoly(const MonotonePoly* monotonePoly, void* data) const {
314    SkASSERT(monotonePoly->fWinding != 0);
315    Edge* e = monotonePoly->fFirstEdge;
316    VertexList vertices;
317    vertices.append(e->fTop);
318    int count = 1;
319    while (e != nullptr) {
320        if (kRight_Side == monotonePoly->fSide) {
321            vertices.append(e->fBottom);
322            e = e->fRightPolyNext;
323        } else {
324            vertices.prepend(e->fBottom);
325            e = e->fLeftPolyNext;
326        }
327        count++;
328    }
329    Vertex* first = vertices.fHead;
330    Vertex* v = first->fNext;
331    while (v != vertices.fTail) {
332        SkASSERT(v && v->fPrev && v->fNext);
333        Vertex* prev = v->fPrev;
334        Vertex* curr = v;
335        Vertex* next = v->fNext;
336        if (count == 3) {
337            return this->emitTriangle(prev, curr, next, monotonePoly->fWinding, data);
338        }
339        double ax = static_cast<double>(curr->fPoint.fX) - prev->fPoint.fX;
340        double ay = static_cast<double>(curr->fPoint.fY) - prev->fPoint.fY;
341        double bx = static_cast<double>(next->fPoint.fX) - curr->fPoint.fX;
342        double by = static_cast<double>(next->fPoint.fY) - curr->fPoint.fY;
343        if (ax * by - ay * bx >= 0.0) {
344            data = this->emitTriangle(prev, curr, next, monotonePoly->fWinding, data);
345            v->fPrev->fNext = v->fNext;
346            v->fNext->fPrev = v->fPrev;
347            count--;
348            if (v->fPrev == first) {
349                v = v->fNext;
350            } else {
351                v = v->fPrev;
352            }
353        } else {
354            v = v->fNext;
355        }
356    }
357    return data;
358}
359
360void* GrTriangulator::emitTriangle(Vertex* prev, Vertex* curr, Vertex* next, int winding,
361                                   void* data) const {
362    if (winding > 0) {
363        // Ensure our triangles always wind in the same direction as if the path had been
364        // triangulated as a simple fan (a la red book).
365        std::swap(prev, next);
366    }
367    if (fCollectBreadcrumbTriangles && abs(winding) > 1 &&
368        fPath.getFillType() == SkPathFillType::kWinding) {
369        // The first winding count will come from the actual triangle we emit. The remaining counts
370        // come from the breadcrumb triangle.
371        fBreadcrumbList.append(fAlloc, prev->fPoint, curr->fPoint, next->fPoint, abs(winding) - 1);
372    }
373    return emit_triangle(prev, curr, next, fEmitCoverage, data);
374}
375
376GrTriangulator::Poly::Poly(Vertex* v, int winding)
377        : fFirstVertex(v)
378        , fWinding(winding)
379        , fHead(nullptr)
380        , fTail(nullptr)
381        , fNext(nullptr)
382        , fPartner(nullptr)
383        , fCount(0)
384{
385#if TRIANGULATOR_LOGGING
386    static int gID = 0;
387    fID = gID++;
388    TESS_LOG("*** created Poly %d\n", fID);
389#endif
390}
391
392Poly* GrTriangulator::Poly::addEdge(Edge* e, Side side, SkArenaAlloc* alloc) {
393    TESS_LOG("addEdge (%g -> %g) to poly %d, %s side\n",
394             e->fTop->fID, e->fBottom->fID, fID, side == kLeft_Side ? "left" : "right");
395    Poly* partner = fPartner;
396    Poly* poly = this;
397    if (side == kRight_Side) {
398        if (e->fUsedInRightPoly) {
399            return this;
400        }
401    } else {
402        if (e->fUsedInLeftPoly) {
403            return this;
404        }
405    }
406    if (partner) {
407        fPartner = partner->fPartner = nullptr;
408    }
409    if (!fTail) {
410        fHead = fTail = alloc->make<MonotonePoly>(e, side, fWinding);
411        fCount += 2;
412    } else if (e->fBottom == fTail->fLastEdge->fBottom) {
413        return poly;
414    } else if (side == fTail->fSide) {
415        fTail->addEdge(e);
416        fCount++;
417    } else {
418        e = alloc->make<Edge>(fTail->fLastEdge->fBottom, e->fBottom, 1, EdgeType::kInner);
419        fTail->addEdge(e);
420        fCount++;
421        if (partner) {
422            partner->addEdge(e, side, alloc);
423            poly = partner;
424        } else {
425            MonotonePoly* m = alloc->make<MonotonePoly>(e, side, fWinding);
426            m->fPrev = fTail;
427            fTail->fNext = m;
428            fTail = m;
429        }
430    }
431    return poly;
432}
433void* GrTriangulator::emitPoly(const Poly* poly, void *data) const {
434    if (poly->fCount < 3) {
435        return data;
436    }
437    TESS_LOG("emit() %d, size %d\n", poly->fID, poly->fCount);
438    for (MonotonePoly* m = poly->fHead; m != nullptr; m = m->fNext) {
439        data = this->emitMonotonePoly(m, data);
440    }
441    return data;
442}
443
444static bool coincident(const SkPoint& a, const SkPoint& b) {
445    return a == b;
446}
447
448Poly* GrTriangulator::makePoly(Poly** head, Vertex* v, int winding) const {
449    Poly* poly = fAlloc->make<Poly>(v, winding);
450    poly->fNext = *head;
451    *head = poly;
452    return poly;
453}
454
455void GrTriangulator::appendPointToContour(const SkPoint& p, VertexList* contour) const {
456    Vertex* v = fAlloc->make<Vertex>(p, 255);
457#if TRIANGULATOR_LOGGING
458    static float gID = 0.0f;
459    v->fID = gID++;
460#endif
461    contour->append(v);
462}
463
464static SkScalar quad_error_at(const SkPoint pts[3], SkScalar t, SkScalar u) {
465    SkQuadCoeff quad(pts);
466    SkPoint p0 = to_point(quad.eval(t - 0.5f * u));
467    SkPoint mid = to_point(quad.eval(t));
468    SkPoint p1 = to_point(quad.eval(t + 0.5f * u));
469    if (!p0.isFinite() || !mid.isFinite() || !p1.isFinite()) {
470        return 0;
471    }
472    return SkPointPriv::DistanceToLineSegmentBetweenSqd(mid, p0, p1);
473}
474
475void GrTriangulator::appendQuadraticToContour(const SkPoint pts[3], SkScalar toleranceSqd,
476                                              VertexList* contour) const {
477    SkQuadCoeff quad(pts);
478    Sk2s aa = quad.fA * quad.fA;
479    SkScalar denom = 2.0f * (aa[0] + aa[1]);
480    Sk2s ab = quad.fA * quad.fB;
481    SkScalar t = denom ? (-ab[0] - ab[1]) / denom : 0.0f;
482    int nPoints = 1;
483    SkScalar u = 1.0f;
484    // Test possible subdivision values only at the point of maximum curvature.
485    // If it passes the flatness metric there, it'll pass everywhere.
486    while (nPoints < GrPathUtils::kMaxPointsPerCurve) {
487        u = 1.0f / nPoints;
488        if (quad_error_at(pts, t, u) < toleranceSqd) {
489            break;
490        }
491        nPoints++;
492    }
493    for (int j = 1; j <= nPoints; j++) {
494        this->appendPointToContour(to_point(quad.eval(j * u)), contour);
495    }
496}
497
498void GrTriangulator::generateCubicPoints(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2,
499                                         const SkPoint& p3, SkScalar tolSqd, VertexList* contour,
500                                         int pointsLeft) const {
501    SkScalar d1 = SkPointPriv::DistanceToLineSegmentBetweenSqd(p1, p0, p3);
502    SkScalar d2 = SkPointPriv::DistanceToLineSegmentBetweenSqd(p2, p0, p3);
503    if (pointsLeft < 2 || (d1 < tolSqd && d2 < tolSqd) ||
504        !SkScalarIsFinite(d1) || !SkScalarIsFinite(d2)) {
505        this->appendPointToContour(p3, contour);
506        return;
507    }
508    const SkPoint q[] = {
509        { SkScalarAve(p0.fX, p1.fX), SkScalarAve(p0.fY, p1.fY) },
510        { SkScalarAve(p1.fX, p2.fX), SkScalarAve(p1.fY, p2.fY) },
511        { SkScalarAve(p2.fX, p3.fX), SkScalarAve(p2.fY, p3.fY) }
512    };
513    const SkPoint r[] = {
514        { SkScalarAve(q[0].fX, q[1].fX), SkScalarAve(q[0].fY, q[1].fY) },
515        { SkScalarAve(q[1].fX, q[2].fX), SkScalarAve(q[1].fY, q[2].fY) }
516    };
517    const SkPoint s = { SkScalarAve(r[0].fX, r[1].fX), SkScalarAve(r[0].fY, r[1].fY) };
518    pointsLeft >>= 1;
519    this->generateCubicPoints(p0, q[0], r[0], s, tolSqd, contour, pointsLeft);
520    this->generateCubicPoints(s, r[1], q[2], p3, tolSqd, contour, pointsLeft);
521}
522
523// Stage 1: convert the input path to a set of linear contours (linked list of Vertices).
524
525void GrTriangulator::pathToContours(float tolerance, const SkRect& clipBounds,
526                                    VertexList* contours, bool* isLinear) const {
527    SkScalar toleranceSqd = tolerance * tolerance;
528    SkPoint pts[4];
529    *isLinear = true;
530    VertexList* contour = contours;
531    SkPath::Iter iter(fPath, false);
532    if (fPath.isInverseFillType()) {
533        SkPoint quad[4];
534        clipBounds.toQuad(quad);
535        for (int i = 3; i >= 0; i--) {
536            this->appendPointToContour(quad[i], contours);
537        }
538        contour++;
539    }
540    SkAutoConicToQuads converter;
541    SkPath::Verb verb;
542    while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
543        switch (verb) {
544            case SkPath::kConic_Verb: {
545                *isLinear = false;
546                if (toleranceSqd == 0) {
547                    this->appendPointToContour(pts[2], contour);
548                    break;
549                }
550                SkScalar weight = iter.conicWeight();
551                const SkPoint* quadPts = converter.computeQuads(pts, weight, toleranceSqd);
552                for (int i = 0; i < converter.countQuads(); ++i) {
553                    this->appendQuadraticToContour(quadPts, toleranceSqd, contour);
554                    quadPts += 2;
555                }
556                break;
557            }
558            case SkPath::kMove_Verb:
559                if (contour->fHead) {
560                    contour++;
561                }
562                this->appendPointToContour(pts[0], contour);
563                break;
564            case SkPath::kLine_Verb: {
565                this->appendPointToContour(pts[1], contour);
566                break;
567            }
568            case SkPath::kQuad_Verb: {
569                *isLinear = false;
570                if (toleranceSqd == 0) {
571                    this->appendPointToContour(pts[2], contour);
572                    break;
573                }
574                this->appendQuadraticToContour(pts, toleranceSqd, contour);
575                break;
576            }
577            case SkPath::kCubic_Verb: {
578                *isLinear = false;
579                if (toleranceSqd == 0) {
580                    this->appendPointToContour(pts[3], contour);
581                    break;
582                }
583                int pointsLeft = GrPathUtils::cubicPointCount(pts, tolerance);
584                this->generateCubicPoints(pts[0], pts[1], pts[2], pts[3], toleranceSqd, contour,
585                                          pointsLeft);
586                break;
587            }
588            case SkPath::kClose_Verb:
589            case SkPath::kDone_Verb:
590                break;
591        }
592    }
593}
594
595static inline bool apply_fill_type(SkPathFillType fillType, int winding) {
596    switch (fillType) {
597        case SkPathFillType::kWinding:
598            return winding != 0;
599        case SkPathFillType::kEvenOdd:
600            return (winding & 1) != 0;
601        case SkPathFillType::kInverseWinding:
602            return winding == 1;
603        case SkPathFillType::kInverseEvenOdd:
604            return (winding & 1) == 1;
605        default:
606            SkASSERT(false);
607            return false;
608    }
609}
610
611bool GrTriangulator::applyFillType(int winding) const {
612    return apply_fill_type(fPath.getFillType(), winding);
613}
614
615static inline bool apply_fill_type(SkPathFillType fillType, Poly* poly) {
616    return poly && apply_fill_type(fillType, poly->fWinding);
617}
618
619Edge* GrTriangulator::makeEdge(Vertex* prev, Vertex* next, EdgeType type,
620                               const Comparator& c) const {
621    SkASSERT(prev->fPoint != next->fPoint);
622    int winding = c.sweep_lt(prev->fPoint, next->fPoint) ? 1 : -1;
623    Vertex* top = winding < 0 ? next : prev;
624    Vertex* bottom = winding < 0 ? prev : next;
625    return fAlloc->make<Edge>(top, bottom, winding, type);
626}
627
628void EdgeList::insert(Edge* edge, Edge* prev) {
629    TESS_LOG("inserting edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
630    SkASSERT(!this->contains(edge));
631    Edge* next = prev ? prev->fRight : fHead;
632    this->insert(edge, prev, next);
633}
634
635void GrTriangulator::FindEnclosingEdges(Vertex* v, EdgeList* edges, Edge** left, Edge** right) {
636    if (v->fFirstEdgeAbove && v->fLastEdgeAbove) {
637        *left = v->fFirstEdgeAbove->fLeft;
638        *right = v->fLastEdgeAbove->fRight;
639        return;
640    }
641    Edge* next = nullptr;
642    Edge* prev;
643    for (prev = edges->fTail; prev != nullptr; prev = prev->fLeft) {
644        if (prev->isLeftOf(v)) {
645            break;
646        }
647        next = prev;
648    }
649    *left = prev;
650    *right = next;
651}
652
653void GrTriangulator::Edge::insertAbove(Vertex* v, const Comparator& c) {
654    if (fTop->fPoint == fBottom->fPoint ||
655        c.sweep_lt(fBottom->fPoint, fTop->fPoint)) {
656        return;
657    }
658    TESS_LOG("insert edge (%g -> %g) above vertex %g\n", fTop->fID, fBottom->fID, v->fID);
659    Edge* prev = nullptr;
660    Edge* next;
661    for (next = v->fFirstEdgeAbove; next; next = next->fNextEdgeAbove) {
662        if (next->isRightOf(fTop)) {
663            break;
664        }
665        prev = next;
666    }
667    list_insert<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
668        this, prev, next, &v->fFirstEdgeAbove, &v->fLastEdgeAbove);
669}
670
671void GrTriangulator::Edge::insertBelow(Vertex* v, const Comparator& c) {
672    if (fTop->fPoint == fBottom->fPoint ||
673        c.sweep_lt(fBottom->fPoint, fTop->fPoint)) {
674        return;
675    }
676    TESS_LOG("insert edge (%g -> %g) below vertex %g\n", fTop->fID, fBottom->fID, v->fID);
677    Edge* prev = nullptr;
678    Edge* next;
679    for (next = v->fFirstEdgeBelow; next; next = next->fNextEdgeBelow) {
680        if (next->isRightOf(fBottom)) {
681            break;
682        }
683        prev = next;
684    }
685    list_insert<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
686        this, prev, next, &v->fFirstEdgeBelow, &v->fLastEdgeBelow);
687}
688
689static void remove_edge_above(Edge* edge) {
690    SkASSERT(edge->fTop && edge->fBottom);
691    TESS_LOG("removing edge (%g -> %g) above vertex %g\n", edge->fTop->fID, edge->fBottom->fID,
692             edge->fBottom->fID);
693    list_remove<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
694        edge, &edge->fBottom->fFirstEdgeAbove, &edge->fBottom->fLastEdgeAbove);
695}
696
697static void remove_edge_below(Edge* edge) {
698    SkASSERT(edge->fTop && edge->fBottom);
699    TESS_LOG("removing edge (%g -> %g) below vertex %g\n",
700             edge->fTop->fID, edge->fBottom->fID, edge->fTop->fID);
701    list_remove<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
702        edge, &edge->fTop->fFirstEdgeBelow, &edge->fTop->fLastEdgeBelow);
703}
704
705void GrTriangulator::Edge::disconnect() {
706    remove_edge_above(this);
707    remove_edge_below(this);
708}
709
710static void rewind(EdgeList* activeEdges, Vertex** current, Vertex* dst, const Comparator& c) {
711    if (!current || *current == dst || c.sweep_lt((*current)->fPoint, dst->fPoint)) {
712        return;
713    }
714    Vertex* v = *current;
715    TESS_LOG("rewinding active edges from vertex %g to vertex %g\n", v->fID, dst->fID);
716    while (v != dst) {
717        v = v->fPrev;
718        for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
719            activeEdges->remove(e);
720        }
721        Edge* leftEdge = v->fLeftEnclosingEdge;
722        for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
723            activeEdges->insert(e, leftEdge);
724            leftEdge = e;
725            Vertex* top = e->fTop;
726            if (c.sweep_lt(top->fPoint, dst->fPoint) &&
727                ((top->fLeftEnclosingEdge && !top->fLeftEnclosingEdge->isLeftOf(e->fTop)) ||
728                 (top->fRightEnclosingEdge && !top->fRightEnclosingEdge->isRightOf(e->fTop)))) {
729                dst = top;
730            }
731        }
732    }
733    *current = v;
734}
735
736static void rewind_if_necessary(Edge* edge, EdgeList* activeEdges, Vertex** current,
737                                const Comparator& c) {
738    if (!activeEdges || !current) {
739        return;
740    }
741    Vertex* top = edge->fTop;
742    Vertex* bottom = edge->fBottom;
743    if (edge->fLeft) {
744        Vertex* leftTop = edge->fLeft->fTop;
745        Vertex* leftBottom = edge->fLeft->fBottom;
746        if (c.sweep_lt(leftTop->fPoint, top->fPoint) && !edge->fLeft->isLeftOf(top)) {
747            rewind(activeEdges, current, leftTop, c);
748        } else if (c.sweep_lt(top->fPoint, leftTop->fPoint) && !edge->isRightOf(leftTop)) {
749            rewind(activeEdges, current, top, c);
750        } else if (c.sweep_lt(bottom->fPoint, leftBottom->fPoint) &&
751                   !edge->fLeft->isLeftOf(bottom)) {
752            rewind(activeEdges, current, leftTop, c);
753        } else if (c.sweep_lt(leftBottom->fPoint, bottom->fPoint) && !edge->isRightOf(leftBottom)) {
754            rewind(activeEdges, current, top, c);
755        }
756    }
757    if (edge->fRight) {
758        Vertex* rightTop = edge->fRight->fTop;
759        Vertex* rightBottom = edge->fRight->fBottom;
760        if (c.sweep_lt(rightTop->fPoint, top->fPoint) && !edge->fRight->isRightOf(top)) {
761            rewind(activeEdges, current, rightTop, c);
762        } else if (c.sweep_lt(top->fPoint, rightTop->fPoint) && !edge->isLeftOf(rightTop)) {
763            rewind(activeEdges, current, top, c);
764        } else if (c.sweep_lt(bottom->fPoint, rightBottom->fPoint) &&
765                   !edge->fRight->isRightOf(bottom)) {
766            rewind(activeEdges, current, rightTop, c);
767        } else if (c.sweep_lt(rightBottom->fPoint, bottom->fPoint) &&
768                   !edge->isLeftOf(rightBottom)) {
769            rewind(activeEdges, current, top, c);
770        }
771    }
772}
773
774void GrTriangulator::setTop(Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current,
775                            const Comparator& c) const {
776    remove_edge_below(edge);
777    if (fCollectBreadcrumbTriangles) {
778        fBreadcrumbList.append(fAlloc, edge->fTop->fPoint, edge->fBottom->fPoint, v->fPoint,
779                               edge->fWinding);
780    }
781    edge->fTop = v;
782    edge->recompute();
783    edge->insertBelow(v, c);
784    rewind_if_necessary(edge, activeEdges, current, c);
785    this->mergeCollinearEdges(edge, activeEdges, current, c);
786}
787
788void GrTriangulator::setBottom(Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current,
789                               const Comparator& c) const {
790    remove_edge_above(edge);
791    if (fCollectBreadcrumbTriangles) {
792        fBreadcrumbList.append(fAlloc, edge->fTop->fPoint, edge->fBottom->fPoint, v->fPoint,
793                               edge->fWinding);
794    }
795    edge->fBottom = v;
796    edge->recompute();
797    edge->insertAbove(v, c);
798    rewind_if_necessary(edge, activeEdges, current, c);
799    this->mergeCollinearEdges(edge, activeEdges, current, c);
800}
801
802void GrTriangulator::mergeEdgesAbove(Edge* edge, Edge* other, EdgeList* activeEdges,
803                                     Vertex** current, const Comparator& c) const {
804    if (coincident(edge->fTop->fPoint, other->fTop->fPoint)) {
805        TESS_LOG("merging coincident above edges (%g, %g) -> (%g, %g)\n",
806                 edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
807                 edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
808        rewind(activeEdges, current, edge->fTop, c);
809        other->fWinding += edge->fWinding;
810        edge->disconnect();
811        edge->fTop = edge->fBottom = nullptr;
812    } else if (c.sweep_lt(edge->fTop->fPoint, other->fTop->fPoint)) {
813        rewind(activeEdges, current, edge->fTop, c);
814        other->fWinding += edge->fWinding;
815        this->setBottom(edge, other->fTop, activeEdges, current, c);
816    } else {
817        rewind(activeEdges, current, other->fTop, c);
818        edge->fWinding += other->fWinding;
819        this->setBottom(other, edge->fTop, activeEdges, current, c);
820    }
821}
822
823void GrTriangulator::mergeEdgesBelow(Edge* edge, Edge* other, EdgeList* activeEdges,
824                                     Vertex** current, const Comparator& c) const {
825    if (coincident(edge->fBottom->fPoint, other->fBottom->fPoint)) {
826        TESS_LOG("merging coincident below edges (%g, %g) -> (%g, %g)\n",
827                 edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
828                 edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
829        rewind(activeEdges, current, edge->fTop, c);
830        other->fWinding += edge->fWinding;
831        edge->disconnect();
832        edge->fTop = edge->fBottom = nullptr;
833    } else if (c.sweep_lt(edge->fBottom->fPoint, other->fBottom->fPoint)) {
834        rewind(activeEdges, current, other->fTop, c);
835        edge->fWinding += other->fWinding;
836        this->setTop(other, edge->fBottom, activeEdges, current, c);
837    } else {
838        rewind(activeEdges, current, edge->fTop, c);
839        other->fWinding += edge->fWinding;
840        this->setTop(edge, other->fBottom, activeEdges, current, c);
841    }
842}
843
844static bool top_collinear(Edge* left, Edge* right) {
845    if (!left || !right) {
846        return false;
847    }
848    return left->fTop->fPoint == right->fTop->fPoint ||
849           !left->isLeftOf(right->fTop) || !right->isRightOf(left->fTop);
850}
851
852static bool bottom_collinear(Edge* left, Edge* right) {
853    if (!left || !right) {
854        return false;
855    }
856    return left->fBottom->fPoint == right->fBottom->fPoint ||
857           !left->isLeftOf(right->fBottom) || !right->isRightOf(left->fBottom);
858}
859
860void GrTriangulator::mergeCollinearEdges(Edge* edge, EdgeList* activeEdges, Vertex** current,
861                                         const Comparator& c) const {
862    for (;;) {
863        if (top_collinear(edge->fPrevEdgeAbove, edge)) {
864            this->mergeEdgesAbove(edge->fPrevEdgeAbove, edge, activeEdges, current, c);
865        } else if (top_collinear(edge, edge->fNextEdgeAbove)) {
866            this->mergeEdgesAbove(edge->fNextEdgeAbove, edge, activeEdges, current, c);
867        } else if (bottom_collinear(edge->fPrevEdgeBelow, edge)) {
868            this->mergeEdgesBelow(edge->fPrevEdgeBelow, edge, activeEdges, current, c);
869        } else if (bottom_collinear(edge, edge->fNextEdgeBelow)) {
870            this->mergeEdgesBelow(edge->fNextEdgeBelow, edge, activeEdges, current, c);
871        } else {
872            break;
873        }
874    }
875    SkASSERT(!top_collinear(edge->fPrevEdgeAbove, edge));
876    SkASSERT(!top_collinear(edge, edge->fNextEdgeAbove));
877    SkASSERT(!bottom_collinear(edge->fPrevEdgeBelow, edge));
878    SkASSERT(!bottom_collinear(edge, edge->fNextEdgeBelow));
879}
880
881bool GrTriangulator::splitEdge(Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current,
882                               const Comparator& c) const {
883    if (!edge->fTop || !edge->fBottom || v == edge->fTop || v == edge->fBottom) {
884        return false;
885    }
886    TESS_LOG("splitting edge (%g -> %g) at vertex %g (%g, %g)\n",
887             edge->fTop->fID, edge->fBottom->fID, v->fID, v->fPoint.fX, v->fPoint.fY);
888    Vertex* top;
889    Vertex* bottom;
890    int winding = edge->fWinding;
891    // Theoretically, and ideally, the edge betwee p0 and p1 is being split by v, and v is "between"
892    // the segment end points according to c. This is equivalent to p0 < v < p1.  Unfortunately, if
893    // v was clamped/rounded this relation doesn't always hold.
894    if (c.sweep_lt(v->fPoint, edge->fTop->fPoint)) {
895        // Actually "v < p0 < p1": update 'edge' to be v->p1 and add v->p0. We flip the winding on
896        // the new edge so that it winds as if it were p0->v.
897        top = v;
898        bottom = edge->fTop;
899        winding *= -1;
900        this->setTop(edge, v, activeEdges, current, c);
901    } else if (c.sweep_lt(edge->fBottom->fPoint, v->fPoint)) {
902        // Actually "p0 < p1 < v": update 'edge' to be p0->v and add p1->v. We flip the winding on
903        // the new edge so that it winds as if it were v->p1.
904        top = edge->fBottom;
905        bottom = v;
906        winding *= -1;
907        this->setBottom(edge, v, activeEdges, current, c);
908    } else {
909        // The ideal case, "p0 < v < p1": update 'edge' to be p0->v and add v->p1. Original winding
910        // is valid for both edges.
911        top = v;
912        bottom = edge->fBottom;
913        this->setBottom(edge, v, activeEdges, current, c);
914    }
915    Edge* newEdge = fAlloc->make<Edge>(top, bottom, winding, edge->fType);
916    newEdge->insertBelow(top, c);
917    newEdge->insertAbove(bottom, c);
918    this->mergeCollinearEdges(newEdge, activeEdges, current, c);
919    return true;
920}
921
922bool GrTriangulator::intersectEdgePair(Edge* left, Edge* right, EdgeList* activeEdges,
923                                       Vertex** current, const Comparator& c) const {
924    if (!left->fTop || !left->fBottom || !right->fTop || !right->fBottom) {
925        return false;
926    }
927    if (left->fTop == right->fTop || left->fBottom == right->fBottom) {
928        return false;
929    }
930    if (c.sweep_lt(left->fTop->fPoint, right->fTop->fPoint)) {
931        if (!left->isLeftOf(right->fTop)) {
932            rewind(activeEdges, current, right->fTop, c);
933            return this->splitEdge(left, right->fTop, activeEdges, current, c);
934        }
935    } else {
936        if (!right->isRightOf(left->fTop)) {
937            rewind(activeEdges, current, left->fTop, c);
938            return this->splitEdge(right, left->fTop, activeEdges, current, c);
939        }
940    }
941    if (c.sweep_lt(right->fBottom->fPoint, left->fBottom->fPoint)) {
942        if (!left->isLeftOf(right->fBottom)) {
943            rewind(activeEdges, current, right->fBottom, c);
944            return this->splitEdge(left, right->fBottom, activeEdges, current, c);
945        }
946    } else {
947        if (!right->isRightOf(left->fBottom)) {
948            rewind(activeEdges, current, left->fBottom, c);
949            return this->splitEdge(right, left->fBottom, activeEdges, current, c);
950        }
951    }
952    return false;
953}
954
955Edge* GrTriangulator::makeConnectingEdge(Vertex* prev, Vertex* next, EdgeType type,
956                                         const Comparator& c, int windingScale) const {
957    if (!prev || !next || prev->fPoint == next->fPoint) {
958        return nullptr;
959    }
960    Edge* edge = this->makeEdge(prev, next, type, c);
961    edge->insertBelow(edge->fTop, c);
962    edge->insertAbove(edge->fBottom, c);
963    edge->fWinding *= windingScale;
964    this->mergeCollinearEdges(edge, nullptr, nullptr, c);
965    return edge;
966}
967
968void GrTriangulator::mergeVertices(Vertex* src, Vertex* dst, VertexList* mesh,
969                                   const Comparator& c) const {
970    TESS_LOG("found coincident verts at %g, %g; merging %g into %g\n",
971             src->fPoint.fX, src->fPoint.fY, src->fID, dst->fID);
972    dst->fAlpha = std::max(src->fAlpha, dst->fAlpha);
973    if (src->fPartner) {
974        src->fPartner->fPartner = dst;
975    }
976    while (Edge* edge = src->fFirstEdgeAbove) {
977        this->setBottom(edge, dst, nullptr, nullptr, c);
978    }
979    while (Edge* edge = src->fFirstEdgeBelow) {
980        this->setTop(edge, dst, nullptr, nullptr, c);
981    }
982    mesh->remove(src);
983    dst->fSynthetic = true;
984}
985
986Vertex* GrTriangulator::makeSortedVertex(const SkPoint& p, uint8_t alpha, VertexList* mesh,
987                                         Vertex* reference, const Comparator& c) const {
988    Vertex* prevV = reference;
989    while (prevV && c.sweep_lt(p, prevV->fPoint)) {
990        prevV = prevV->fPrev;
991    }
992    Vertex* nextV = prevV ? prevV->fNext : mesh->fHead;
993    while (nextV && c.sweep_lt(nextV->fPoint, p)) {
994        prevV = nextV;
995        nextV = nextV->fNext;
996    }
997    Vertex* v;
998    if (prevV && coincident(prevV->fPoint, p)) {
999        v = prevV;
1000    } else if (nextV && coincident(nextV->fPoint, p)) {
1001        v = nextV;
1002    } else {
1003        v = fAlloc->make<Vertex>(p, alpha);
1004#if TRIANGULATOR_LOGGING
1005        if (!prevV) {
1006            v->fID = mesh->fHead->fID - 1.0f;
1007        } else if (!nextV) {
1008            v->fID = mesh->fTail->fID + 1.0f;
1009        } else {
1010            v->fID = (prevV->fID + nextV->fID) * 0.5f;
1011        }
1012#endif
1013        mesh->insert(v, prevV, nextV);
1014    }
1015    return v;
1016}
1017
1018// Clamps x and y coordinates independently, so the returned point will lie within the bounding
1019// box formed by the corners of 'min' and 'max' (although min/max here refer to the ordering
1020// imposed by 'c').
1021static SkPoint clamp(SkPoint p, SkPoint min, SkPoint max, const Comparator& c) {
1022    if (c.fDirection == Comparator::Direction::kHorizontal) {
1023        // With horizontal sorting, we know min.x <= max.x, but there's no relation between
1024        // Y components unless min.x == max.x.
1025        return {SkTPin(p.fX, min.fX, max.fX),
1026                min.fY < max.fY ? SkTPin(p.fY, min.fY, max.fY)
1027                                : SkTPin(p.fY, max.fY, min.fY)};
1028    } else {
1029        // And with vertical sorting, we know Y's relation but not necessarily X's.
1030        return {min.fX < max.fX ? SkTPin(p.fX, min.fX, max.fX)
1031                                : SkTPin(p.fX, max.fX, min.fX),
1032                SkTPin(p.fY, min.fY, max.fY)};
1033    }
1034}
1035
1036void GrTriangulator::computeBisector(Edge* edge1, Edge* edge2, Vertex* v) const {
1037    SkASSERT(fEmitCoverage);  // Edge-AA only!
1038    Line line1 = edge1->fLine;
1039    Line line2 = edge2->fLine;
1040    line1.normalize();
1041    line2.normalize();
1042    double cosAngle = line1.fA * line2.fA + line1.fB * line2.fB;
1043    if (cosAngle > 0.999) {
1044        return;
1045    }
1046    line1.fC += edge1->fWinding > 0 ? -1 : 1;
1047    line2.fC += edge2->fWinding > 0 ? -1 : 1;
1048    SkPoint p;
1049    if (line1.intersect(line2, &p)) {
1050        uint8_t alpha = edge1->fType == EdgeType::kOuter ? 255 : 0;
1051        v->fPartner = fAlloc->make<Vertex>(p, alpha);
1052        TESS_LOG("computed bisector (%g,%g) alpha %d for vertex %g\n", p.fX, p.fY, alpha, v->fID);
1053    }
1054}
1055
1056bool GrTriangulator::checkForIntersection(Edge* left, Edge* right, EdgeList* activeEdges,
1057                                          Vertex** current, VertexList* mesh,
1058                                          const Comparator& c) const {
1059    if (!left || !right) {
1060        return false;
1061    }
1062    SkPoint p;
1063    uint8_t alpha;
1064    if (left->intersect(*right, &p, &alpha) && p.isFinite()) {
1065        Vertex* v;
1066        TESS_LOG("found intersection, pt is %g, %g\n", p.fX, p.fY);
1067        Vertex* top = *current;
1068        // If the intersection point is above the current vertex, rewind to the vertex above the
1069        // intersection.
1070        while (top && c.sweep_lt(p, top->fPoint)) {
1071            top = top->fPrev;
1072        }
1073
1074        // Always clamp the intersection to lie between the vertices of each segment, since
1075        // in theory that's where the intersection is, but in reality, floating point error may
1076        // have computed an intersection beyond a vertex's component(s).
1077        p = clamp(p, left->fTop->fPoint, left->fBottom->fPoint, c);
1078        p = clamp(p, right->fTop->fPoint, right->fBottom->fPoint, c);
1079
1080        if (coincident(p, left->fTop->fPoint)) {
1081            v = left->fTop;
1082        } else if (coincident(p, left->fBottom->fPoint)) {
1083            v = left->fBottom;
1084        } else if (coincident(p, right->fTop->fPoint)) {
1085            v = right->fTop;
1086        } else if (coincident(p, right->fBottom->fPoint)) {
1087            v = right->fBottom;
1088        } else {
1089            v = this->makeSortedVertex(p, alpha, mesh, top, c);
1090            if (left->fTop->fPartner) {
1091                SkASSERT(fEmitCoverage);  // Edge-AA only!
1092                v->fSynthetic = true;
1093                this->computeBisector(left, right, v);
1094            }
1095        }
1096        rewind(activeEdges, current, top ? top : v, c);
1097        this->splitEdge(left, v, activeEdges, current, c);
1098        this->splitEdge(right, v, activeEdges, current, c);
1099        v->fAlpha = std::max(v->fAlpha, alpha);
1100        return true;
1101    }
1102    return this->intersectEdgePair(left, right, activeEdges, current, c);
1103}
1104
1105void GrTriangulator::sanitizeContours(VertexList* contours, int contourCnt) const {
1106    for (VertexList* contour = contours; contourCnt > 0; --contourCnt, ++contour) {
1107        SkASSERT(contour->fHead);
1108        Vertex* prev = contour->fTail;
1109        prev->fPoint.fX = double_to_clamped_scalar((double) prev->fPoint.fX);
1110        prev->fPoint.fY = double_to_clamped_scalar((double) prev->fPoint.fY);
1111        if (fRoundVerticesToQuarterPixel) {
1112            round(&prev->fPoint);
1113        }
1114        for (Vertex* v = contour->fHead; v;) {
1115            v->fPoint.fX = double_to_clamped_scalar((double) v->fPoint.fX);
1116            v->fPoint.fY = double_to_clamped_scalar((double) v->fPoint.fY);
1117            if (fRoundVerticesToQuarterPixel) {
1118                round(&v->fPoint);
1119            }
1120            Vertex* next = v->fNext;
1121            Vertex* nextWrap = next ? next : contour->fHead;
1122            if (coincident(prev->fPoint, v->fPoint)) {
1123                TESS_LOG("vertex %g,%g coincident; removing\n", v->fPoint.fX, v->fPoint.fY);
1124                contour->remove(v);
1125            } else if (!v->fPoint.isFinite()) {
1126                TESS_LOG("vertex %g,%g non-finite; removing\n", v->fPoint.fX, v->fPoint.fY);
1127                contour->remove(v);
1128            } else if (!fPreserveCollinearVertices &&
1129                       Line(prev->fPoint, nextWrap->fPoint).dist(v->fPoint) == 0.0) {
1130                TESS_LOG("vertex %g,%g collinear; removing\n", v->fPoint.fX, v->fPoint.fY);
1131                contour->remove(v);
1132            } else {
1133                prev = v;
1134            }
1135            v = next;
1136        }
1137    }
1138}
1139
1140bool GrTriangulator::mergeCoincidentVertices(VertexList* mesh, const Comparator& c) const {
1141    if (!mesh->fHead) {
1142        return false;
1143    }
1144    bool merged = false;
1145    for (Vertex* v = mesh->fHead->fNext; v;) {
1146        Vertex* next = v->fNext;
1147        if (c.sweep_lt(v->fPoint, v->fPrev->fPoint)) {
1148            v->fPoint = v->fPrev->fPoint;
1149        }
1150        if (coincident(v->fPrev->fPoint, v->fPoint)) {
1151            this->mergeVertices(v, v->fPrev, mesh, c);
1152            merged = true;
1153        }
1154        v = next;
1155    }
1156    return merged;
1157}
1158
1159// Stage 2: convert the contours to a mesh of edges connecting the vertices.
1160
1161void GrTriangulator::buildEdges(VertexList* contours, int contourCnt, VertexList* mesh,
1162                                const Comparator& c) const {
1163    for (VertexList* contour = contours; contourCnt > 0; --contourCnt, ++contour) {
1164        Vertex* prev = contour->fTail;
1165        for (Vertex* v = contour->fHead; v;) {
1166            Vertex* next = v->fNext;
1167            this->makeConnectingEdge(prev, v, EdgeType::kInner, c);
1168            mesh->append(v);
1169            prev = v;
1170            v = next;
1171        }
1172    }
1173}
1174
1175template <CompareFunc sweep_lt>
1176static void sorted_merge(VertexList* front, VertexList* back, VertexList* result) {
1177    Vertex* a = front->fHead;
1178    Vertex* b = back->fHead;
1179    while (a && b) {
1180        if (sweep_lt(a->fPoint, b->fPoint)) {
1181            front->remove(a);
1182            result->append(a);
1183            a = front->fHead;
1184        } else {
1185            back->remove(b);
1186            result->append(b);
1187            b = back->fHead;
1188        }
1189    }
1190    result->append(*front);
1191    result->append(*back);
1192}
1193
1194void GrTriangulator::SortedMerge(VertexList* front, VertexList* back, VertexList* result,
1195                                 const Comparator& c) {
1196    if (c.fDirection == Comparator::Direction::kHorizontal) {
1197        sorted_merge<sweep_lt_horiz>(front, back, result);
1198    } else {
1199        sorted_merge<sweep_lt_vert>(front, back, result);
1200    }
1201#if TRIANGULATOR_LOGGING
1202    float id = 0.0f;
1203    for (Vertex* v = result->fHead; v; v = v->fNext) {
1204        v->fID = id++;
1205    }
1206#endif
1207}
1208
1209// Stage 3: sort the vertices by increasing sweep direction.
1210
1211template <CompareFunc sweep_lt>
1212static void merge_sort(VertexList* vertices) {
1213    Vertex* slow = vertices->fHead;
1214    if (!slow) {
1215        return;
1216    }
1217    Vertex* fast = slow->fNext;
1218    if (!fast) {
1219        return;
1220    }
1221    do {
1222        fast = fast->fNext;
1223        if (fast) {
1224            fast = fast->fNext;
1225            slow = slow->fNext;
1226        }
1227    } while (fast);
1228    VertexList front(vertices->fHead, slow);
1229    VertexList back(slow->fNext, vertices->fTail);
1230    front.fTail->fNext = back.fHead->fPrev = nullptr;
1231
1232    merge_sort<sweep_lt>(&front);
1233    merge_sort<sweep_lt>(&back);
1234
1235    vertices->fHead = vertices->fTail = nullptr;
1236    sorted_merge<sweep_lt>(&front, &back, vertices);
1237}
1238
1239#if TRIANGULATOR_LOGGING
1240void VertexList::dump() const {
1241    for (Vertex* v = fHead; v; v = v->fNext) {
1242        TESS_LOG("vertex %g (%g, %g) alpha %d", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1243        if (Vertex* p = v->fPartner) {
1244            TESS_LOG(", partner %g (%g, %g) alpha %d\n",
1245                    p->fID, p->fPoint.fX, p->fPoint.fY, p->fAlpha);
1246        } else {
1247            TESS_LOG(", null partner\n");
1248        }
1249        for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1250            TESS_LOG("  edge %g -> %g, winding %d\n", e->fTop->fID, e->fBottom->fID, e->fWinding);
1251        }
1252        for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1253            TESS_LOG("  edge %g -> %g, winding %d\n", e->fTop->fID, e->fBottom->fID, e->fWinding);
1254        }
1255    }
1256}
1257#endif
1258
1259#ifdef SK_DEBUG
1260static void validate_edge_pair(Edge* left, Edge* right, const Comparator& c) {
1261    if (!left || !right) {
1262        return;
1263    }
1264    if (left->fTop == right->fTop) {
1265        SkASSERT(left->isLeftOf(right->fBottom));
1266        SkASSERT(right->isRightOf(left->fBottom));
1267    } else if (c.sweep_lt(left->fTop->fPoint, right->fTop->fPoint)) {
1268        SkASSERT(left->isLeftOf(right->fTop));
1269    } else {
1270        SkASSERT(right->isRightOf(left->fTop));
1271    }
1272    if (left->fBottom == right->fBottom) {
1273        SkASSERT(left->isLeftOf(right->fTop));
1274        SkASSERT(right->isRightOf(left->fTop));
1275    } else if (c.sweep_lt(right->fBottom->fPoint, left->fBottom->fPoint)) {
1276        SkASSERT(left->isLeftOf(right->fBottom));
1277    } else {
1278        SkASSERT(right->isRightOf(left->fBottom));
1279    }
1280}
1281
1282static void validate_edge_list(EdgeList* edges, const Comparator& c) {
1283    Edge* left = edges->fHead;
1284    if (!left) {
1285        return;
1286    }
1287    for (Edge* right = left->fRight; right; right = right->fRight) {
1288        validate_edge_pair(left, right, c);
1289        left = right;
1290    }
1291}
1292#endif
1293
1294// Stage 4: Simplify the mesh by inserting new vertices at intersecting edges.
1295
1296GrTriangulator::SimplifyResult GrTriangulator::simplify(VertexList* mesh,
1297                                                        const Comparator& c) const {
1298    TESS_LOG("simplifying complex polygons\n");
1299    EdgeList activeEdges;
1300    auto result = SimplifyResult::kAlreadySimple;
1301    for (Vertex* v = mesh->fHead; v != nullptr; v = v->fNext) {
1302        if (!v->isConnected()) {
1303            continue;
1304        }
1305        Edge* leftEnclosingEdge;
1306        Edge* rightEnclosingEdge;
1307        bool restartChecks;
1308        do {
1309            TESS_LOG("\nvertex %g: (%g,%g), alpha %d\n",
1310                     v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1311            restartChecks = false;
1312            FindEnclosingEdges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1313            v->fLeftEnclosingEdge = leftEnclosingEdge;
1314            v->fRightEnclosingEdge = rightEnclosingEdge;
1315            if (v->fFirstEdgeBelow) {
1316                for (Edge* edge = v->fFirstEdgeBelow; edge; edge = edge->fNextEdgeBelow) {
1317                    if (this->checkForIntersection(
1318                            leftEnclosingEdge, edge, &activeEdges, &v, mesh, c) ||
1319                        this->checkForIntersection(
1320                            edge, rightEnclosingEdge, &activeEdges, &v, mesh, c)) {
1321                        result = SimplifyResult::kFoundSelfIntersection;
1322                        restartChecks = true;
1323                        break;
1324                    }
1325                }
1326            } else {
1327                if (this->checkForIntersection(leftEnclosingEdge, rightEnclosingEdge, &activeEdges,
1328                                               &v, mesh, c)) {
1329                    result = SimplifyResult::kFoundSelfIntersection;
1330                    restartChecks = true;
1331                }
1332
1333            }
1334        } while (restartChecks);
1335#ifdef SK_DEBUG
1336        validate_edge_list(&activeEdges, c);
1337#endif
1338        for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1339            activeEdges.remove(e);
1340        }
1341        Edge* leftEdge = leftEnclosingEdge;
1342        for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1343            activeEdges.insert(e, leftEdge);
1344            leftEdge = e;
1345        }
1346    }
1347    SkASSERT(!activeEdges.fHead && !activeEdges.fTail);
1348    return result;
1349}
1350
1351// Stage 5: Tessellate the simplified mesh into monotone polygons.
1352
1353Poly* GrTriangulator::tessellate(const VertexList& vertices, const Comparator&) const {
1354    TESS_LOG("\ntessellating simple polygons\n");
1355    EdgeList activeEdges;
1356    Poly* polys = nullptr;
1357    for (Vertex* v = vertices.fHead; v != nullptr; v = v->fNext) {
1358        if (!v->isConnected()) {
1359            continue;
1360        }
1361#if TRIANGULATOR_LOGGING
1362        TESS_LOG("\nvertex %g: (%g,%g), alpha %d\n", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1363#endif
1364        Edge* leftEnclosingEdge;
1365        Edge* rightEnclosingEdge;
1366        FindEnclosingEdges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1367        Poly* leftPoly;
1368        Poly* rightPoly;
1369        if (v->fFirstEdgeAbove) {
1370            leftPoly = v->fFirstEdgeAbove->fLeftPoly;
1371            rightPoly = v->fLastEdgeAbove->fRightPoly;
1372        } else {
1373            leftPoly = leftEnclosingEdge ? leftEnclosingEdge->fRightPoly : nullptr;
1374            rightPoly = rightEnclosingEdge ? rightEnclosingEdge->fLeftPoly : nullptr;
1375        }
1376#if TRIANGULATOR_LOGGING
1377        TESS_LOG("edges above:\n");
1378        for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1379            TESS_LOG("%g -> %g, lpoly %d, rpoly %d\n",
1380                     e->fTop->fID, e->fBottom->fID,
1381                     e->fLeftPoly ? e->fLeftPoly->fID : -1,
1382                     e->fRightPoly ? e->fRightPoly->fID : -1);
1383        }
1384        TESS_LOG("edges below:\n");
1385        for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1386            TESS_LOG("%g -> %g, lpoly %d, rpoly %d\n",
1387                     e->fTop->fID, e->fBottom->fID,
1388                     e->fLeftPoly ? e->fLeftPoly->fID : -1,
1389                     e->fRightPoly ? e->fRightPoly->fID : -1);
1390        }
1391#endif
1392        if (v->fFirstEdgeAbove) {
1393            if (leftPoly) {
1394                leftPoly = leftPoly->addEdge(v->fFirstEdgeAbove, kRight_Side, fAlloc);
1395            }
1396            if (rightPoly) {
1397                rightPoly = rightPoly->addEdge(v->fLastEdgeAbove, kLeft_Side, fAlloc);
1398            }
1399            for (Edge* e = v->fFirstEdgeAbove; e != v->fLastEdgeAbove; e = e->fNextEdgeAbove) {
1400                Edge* rightEdge = e->fNextEdgeAbove;
1401                activeEdges.remove(e);
1402                if (e->fRightPoly) {
1403                    e->fRightPoly->addEdge(e, kLeft_Side, fAlloc);
1404                }
1405                if (rightEdge->fLeftPoly && rightEdge->fLeftPoly != e->fRightPoly) {
1406                    rightEdge->fLeftPoly->addEdge(e, kRight_Side, fAlloc);
1407                }
1408            }
1409            activeEdges.remove(v->fLastEdgeAbove);
1410            if (!v->fFirstEdgeBelow) {
1411                if (leftPoly && rightPoly && leftPoly != rightPoly) {
1412                    SkASSERT(leftPoly->fPartner == nullptr && rightPoly->fPartner == nullptr);
1413                    rightPoly->fPartner = leftPoly;
1414                    leftPoly->fPartner = rightPoly;
1415                }
1416            }
1417        }
1418        if (v->fFirstEdgeBelow) {
1419            if (!v->fFirstEdgeAbove) {
1420                if (leftPoly && rightPoly) {
1421                    if (leftPoly == rightPoly) {
1422                        if (leftPoly->fTail && leftPoly->fTail->fSide == kLeft_Side) {
1423                            leftPoly = this->makePoly(&polys, leftPoly->lastVertex(),
1424                                                      leftPoly->fWinding);
1425                            leftEnclosingEdge->fRightPoly = leftPoly;
1426                        } else {
1427                            rightPoly = this->makePoly(&polys, rightPoly->lastVertex(),
1428                                                       rightPoly->fWinding);
1429                            rightEnclosingEdge->fLeftPoly = rightPoly;
1430                        }
1431                    }
1432                    Edge* join = fAlloc->make<Edge>(leftPoly->lastVertex(), v, 1,
1433                                                   EdgeType::kInner);
1434                    leftPoly = leftPoly->addEdge(join, kRight_Side, fAlloc);
1435                    rightPoly = rightPoly->addEdge(join, kLeft_Side, fAlloc);
1436                }
1437            }
1438            Edge* leftEdge = v->fFirstEdgeBelow;
1439            leftEdge->fLeftPoly = leftPoly;
1440            activeEdges.insert(leftEdge, leftEnclosingEdge);
1441            for (Edge* rightEdge = leftEdge->fNextEdgeBelow; rightEdge;
1442                 rightEdge = rightEdge->fNextEdgeBelow) {
1443                activeEdges.insert(rightEdge, leftEdge);
1444                int winding = leftEdge->fLeftPoly ? leftEdge->fLeftPoly->fWinding : 0;
1445                winding += leftEdge->fWinding;
1446                if (winding != 0) {
1447                    Poly* poly = this->makePoly(&polys, v, winding);
1448                    leftEdge->fRightPoly = rightEdge->fLeftPoly = poly;
1449                }
1450                leftEdge = rightEdge;
1451            }
1452            v->fLastEdgeBelow->fRightPoly = rightPoly;
1453        }
1454#if TRIANGULATOR_LOGGING
1455        TESS_LOG("\nactive edges:\n");
1456        for (Edge* e = activeEdges.fHead; e != nullptr; e = e->fRight) {
1457            TESS_LOG("%g -> %g, lpoly %d, rpoly %d\n",
1458                     e->fTop->fID, e->fBottom->fID,
1459                     e->fLeftPoly ? e->fLeftPoly->fID : -1,
1460                     e->fRightPoly ? e->fRightPoly->fID : -1);
1461        }
1462#endif
1463    }
1464    return polys;
1465}
1466
1467// This is a driver function that calls stages 2-5 in turn.
1468
1469void GrTriangulator::contoursToMesh(VertexList* contours, int contourCnt, VertexList* mesh,
1470                                    const Comparator& c) const {
1471#if TRIANGULATOR_LOGGING
1472    for (int i = 0; i < contourCnt; ++i) {
1473        Vertex* v = contours[i].fHead;
1474        SkASSERT(v);
1475        TESS_LOG("path.moveTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
1476        for (v = v->fNext; v; v = v->fNext) {
1477            TESS_LOG("path.lineTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
1478        }
1479    }
1480#endif
1481    this->sanitizeContours(contours, contourCnt);
1482    this->buildEdges(contours, contourCnt, mesh, c);
1483}
1484
1485void GrTriangulator::SortMesh(VertexList* vertices, const Comparator& c) {
1486    if (!vertices || !vertices->fHead) {
1487        return;
1488    }
1489
1490    // Sort vertices in Y (secondarily in X).
1491    if (c.fDirection == Comparator::Direction::kHorizontal) {
1492        merge_sort<sweep_lt_horiz>(vertices);
1493    } else {
1494        merge_sort<sweep_lt_vert>(vertices);
1495    }
1496#if TRIANGULATOR_LOGGING
1497    for (Vertex* v = vertices->fHead; v != nullptr; v = v->fNext) {
1498        static float gID = 0.0f;
1499        v->fID = gID++;
1500    }
1501#endif
1502}
1503
1504Poly* GrTriangulator::contoursToPolys(VertexList* contours, int contourCnt) const {
1505    const SkRect& pathBounds = fPath.getBounds();
1506    Comparator c(pathBounds.width() > pathBounds.height() ? Comparator::Direction::kHorizontal
1507                                                          : Comparator::Direction::kVertical);
1508    VertexList mesh;
1509    this->contoursToMesh(contours, contourCnt, &mesh, c);
1510    TESS_LOG("\ninitial mesh:\n");
1511    DUMP_MESH(mesh);
1512    SortMesh(&mesh, c);
1513    TESS_LOG("\nsorted mesh:\n");
1514    DUMP_MESH(mesh);
1515    this->mergeCoincidentVertices(&mesh, c);
1516    TESS_LOG("\nsorted+merged mesh:\n");
1517    DUMP_MESH(mesh);
1518    this->simplify(&mesh, c);
1519    TESS_LOG("\nsimplified mesh:\n");
1520    DUMP_MESH(mesh);
1521    return this->tessellate(mesh, c);
1522}
1523
1524// Stage 6: Triangulate the monotone polygons into a vertex buffer.
1525void* GrTriangulator::polysToTriangles(Poly* polys, void* data,
1526                                       SkPathFillType overrideFillType) const {
1527    for (Poly* poly = polys; poly; poly = poly->fNext) {
1528        if (apply_fill_type(overrideFillType, poly)) {
1529            data = this->emitPoly(poly, data);
1530        }
1531    }
1532    return data;
1533}
1534
1535static int get_contour_count(const SkPath& path, SkScalar tolerance) {
1536    // We could theoretically be more aggressive about not counting empty contours, but we need to
1537    // actually match the exact number of contour linked lists the tessellator will create later on.
1538    int contourCnt = 1;
1539    bool hasPoints = false;
1540
1541    SkPath::Iter iter(path, false);
1542    SkPath::Verb verb;
1543    SkPoint pts[4];
1544    bool first = true;
1545    while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
1546        switch (verb) {
1547            case SkPath::kMove_Verb:
1548                if (!first) {
1549                    ++contourCnt;
1550                }
1551                [[fallthrough]];
1552            case SkPath::kLine_Verb:
1553            case SkPath::kConic_Verb:
1554            case SkPath::kQuad_Verb:
1555            case SkPath::kCubic_Verb:
1556                hasPoints = true;
1557                break;
1558            default:
1559                break;
1560        }
1561        first = false;
1562    }
1563    if (!hasPoints) {
1564        return 0;
1565    }
1566    return contourCnt;
1567}
1568
1569Poly* GrTriangulator::pathToPolys(float tolerance, const SkRect& clipBounds, bool* isLinear) const {
1570    int contourCnt = get_contour_count(fPath, tolerance);
1571    if (contourCnt <= 0) {
1572        *isLinear = true;
1573        return nullptr;
1574    }
1575
1576    if (SkPathFillType_IsInverse(fPath.getFillType())) {
1577        contourCnt++;
1578    }
1579    std::unique_ptr<VertexList[]> contours(new VertexList[contourCnt]);
1580
1581    this->pathToContours(tolerance, clipBounds, contours.get(), isLinear);
1582    return this->contoursToPolys(contours.get(), contourCnt);
1583}
1584
1585int64_t GrTriangulator::CountPoints(Poly* polys, SkPathFillType overrideFillType) {
1586    int64_t count = 0;
1587    for (Poly* poly = polys; poly; poly = poly->fNext) {
1588        if (apply_fill_type(overrideFillType, poly) && poly->fCount >= 3) {
1589            count += (poly->fCount - 2) * (TRIANGULATOR_WIREFRAME ? 6 : 3);
1590        }
1591    }
1592    return count;
1593}
1594
1595// Stage 6: Triangulate the monotone polygons into a vertex buffer.
1596
1597int GrTriangulator::polysToTriangles(Poly* polys, GrEagerVertexAllocator* vertexAllocator) const {
1598    int64_t count64 = CountPoints(polys, fPath.getFillType());
1599    if (0 == count64 || count64 > SK_MaxS32) {
1600        return 0;
1601    }
1602    int count = count64;
1603
1604    size_t vertexStride = sizeof(SkPoint);
1605    if (fEmitCoverage) {
1606        vertexStride += sizeof(float);
1607    }
1608    void* verts = vertexAllocator->lock(vertexStride, count);
1609    if (!verts) {
1610        SkDebugf("Could not allocate vertices\n");
1611        return 0;
1612    }
1613
1614    TESS_LOG("emitting %d verts\n", count);
1615    void* end = this->polysToTriangles(polys, verts, fPath.getFillType());
1616
1617    int actualCount = static_cast<int>((static_cast<uint8_t*>(end) - static_cast<uint8_t*>(verts))
1618                                       / vertexStride);
1619    SkASSERT(actualCount <= count);
1620    vertexAllocator->unlock(actualCount);
1621    return actualCount;
1622}
1623