• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2015 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #ifndef GrTriangulator_DEFINED
9 #define GrTriangulator_DEFINED
10 
11 #include "include/core/SkPath.h"
12 #include "include/core/SkPoint.h"
13 #include "include/private/SkColorData.h"
14 #include "src/core/SkArenaAlloc.h"
15 #include "src/gpu/GrColor.h"
16 
17 class GrEagerVertexAllocator;
18 struct SkRect;
19 
20 #define TRIANGULATOR_LOGGING 0
21 #define TRIANGULATOR_WIREFRAME 0
22 
23 /**
24  * Provides utility functions for converting paths to a collection of triangles.
25  */
26 class SK_API GrTriangulator {
27 public:
28     constexpr static int kArenaDefaultChunkSize = 16 * 1024;
29 
PathToTriangles(const SkPath & path,SkScalar tolerance,const SkRect & clipBounds,GrEagerVertexAllocator * vertexAllocator,bool * isLinear)30     static int PathToTriangles(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
31                                GrEagerVertexAllocator* vertexAllocator, bool* isLinear) {
32         if (!path.isFinite()) {
33             return 0;
34         }
35         SkArenaAlloc alloc(kArenaDefaultChunkSize);
36         GrTriangulator triangulator(path, &alloc);
37         auto [ polys, success ] = triangulator.pathToPolys(tolerance, clipBounds, isLinear);
38         if (!success) {
39             return 0;
40         }
41         int count = triangulator.polysToTriangles(polys, vertexAllocator);
42         return count;
43     }
44 
45     // Enums used by GrTriangulator internals.
46     typedef enum { kLeft_Side, kRight_Side } Side;
47     enum class EdgeType { kInner, kOuter, kConnector };
48 
49     // Structs used by GrTriangulator internals.
50     struct Vertex;
51     struct VertexList;
52     struct Line;
53     struct Edge;
54     struct EdgeList;
55     struct MonotonePoly;
56     struct Poly;
57     struct Comparator;
58 
59 protected:
GrTriangulator(const SkPath & path,SkArenaAlloc * alloc)60     GrTriangulator(const SkPath& path, SkArenaAlloc* alloc) : fPath(path), fAlloc(alloc) {}
~GrTriangulator()61     virtual ~GrTriangulator() {}
62 
63     // There are six stages to the basic algorithm:
64     //
65     // 1) Linearize the path contours into piecewise linear segments:
66     void pathToContours(float tolerance, const SkRect& clipBounds, VertexList* contours,
67                         bool* isLinear) const;
68 
69     // 2) Build a mesh of edges connecting the vertices:
70     void contoursToMesh(VertexList* contours, int contourCnt, VertexList* mesh,
71                         const Comparator&);
72 
73     // 3) Sort the vertices in Y (and secondarily in X):
74     static void SortedMerge(VertexList* front, VertexList* back, VertexList* result,
75                             const Comparator&);
76     static void SortMesh(VertexList* vertices, const Comparator&);
77 
78     // 4) Simplify the mesh by inserting new vertices at intersecting edges:
79     enum class SimplifyResult {
80         kFailed,
81         kAlreadySimple,
82         kFoundSelfIntersection
83     };
84 
85     SimplifyResult SK_WARN_UNUSED_RESULT simplify(VertexList* mesh, const Comparator&);
86 
87     // 5) Tessellate the simplified mesh into monotone polygons:
88     virtual std::tuple<Poly*, bool> tessellate(const VertexList& vertices, const Comparator&);
89 
90     // 6) Triangulate the monotone polygons directly into a vertex buffer:
91     void* polysToTriangles(Poly* polys, void* data, SkPathFillType overrideFillType) const;
92 
93     // The vertex sorting in step (3) is a merge sort, since it plays well with the linked list
94     // of vertices (and the necessity of inserting new vertices on intersection).
95     //
96     // Stages (4) and (5) use an active edge list -- a list of all edges for which the
97     // sweep line has crossed the top vertex, but not the bottom vertex.  It's sorted
98     // left-to-right based on the point where both edges are active (when both top vertices
99     // have been seen, so the "lower" top vertex of the two). If the top vertices are equal
100     // (shared), it's sorted based on the last point where both edges are active, so the
101     // "upper" bottom vertex.
102     //
103     // The most complex step is the simplification (4). It's based on the Bentley-Ottman
104     // line-sweep algorithm, but due to floating point inaccuracy, the intersection points are
105     // not exact and may violate the mesh topology or active edge list ordering. We
106     // accommodate this by adjusting the topology of the mesh and AEL to match the intersection
107     // points. This occurs in two ways:
108     //
109     // A) Intersections may cause a shortened edge to no longer be ordered with respect to its
110     //    neighbouring edges at the top or bottom vertex. This is handled by merging the
111     //    edges (mergeCollinearVertices()).
112     // B) Intersections may cause an edge to violate the left-to-right ordering of the
113     //    active edge list. This is handled by detecting potential violations and rewinding
114     //    the active edge list to the vertex before they occur (rewind() during merging,
115     //    rewind_if_necessary() during splitting).
116     //
117     // The tessellation steps (5) and (6) are based on "Triangulating Simple Polygons and
118     // Equivalent Problems" (Fournier and Montuno); also a line-sweep algorithm. Note that it
119     // currently uses a linked list for the active edge list, rather than a 2-3 tree as the
120     // paper describes. The 2-3 tree gives O(lg N) lookups, but insertion and removal also
121     // become O(lg N). In all the test cases, it was found that the cost of frequent O(lg N)
122     // insertions and removals was greater than the cost of infrequent O(N) lookups with the
123     // linked list implementation. With the latter, all removals are O(1), and most insertions
124     // are O(1), since we know the adjacent edge in the active edge list based on the topology.
125     // Only type 2 vertices (see paper) require the O(N) lookups, and these are much less
126     // frequent. There may be other data structures worth investigating, however.
127     //
128     // Note that the orientation of the line sweep algorithms is determined by the aspect ratio of
129     // the path bounds. When the path is taller than it is wide, we sort vertices based on
130     // increasing Y coordinate, and secondarily by increasing X coordinate. When the path is wider
131     // than it is tall, we sort by increasing X coordinate, but secondarily by *decreasing* Y
132     // coordinate. This is so that the "left" and "right" orientation in the code remains correct
133     // (edges to the left are increasing in Y; edges to the right are decreasing in Y). That is, the
134     // setting rotates 90 degrees counterclockwise, rather that transposing.
135 
136     // Additional helpers and driver functions.
137     void* emitMonotonePoly(const MonotonePoly*, void* data) const;
138     void* emitTriangle(Vertex* prev, Vertex* curr, Vertex* next, int winding, void* data) const;
139     void* emitPoly(const Poly*, void *data) const;
140     Poly* makePoly(Poly** head, Vertex* v, int winding) const;
141     void appendPointToContour(const SkPoint& p, VertexList* contour) const;
142     void appendQuadraticToContour(const SkPoint[3], SkScalar toleranceSqd,
143                                   VertexList* contour) const;
144     void generateCubicPoints(const SkPoint&, const SkPoint&, const SkPoint&, const SkPoint&,
145                              SkScalar tolSqd, VertexList* contour, int pointsLeft) const;
146     bool applyFillType(int winding) const;
147     MonotonePoly* allocateMonotonePoly(Edge* edge, Side side, int winding);
148     Edge* allocateEdge(Vertex* top, Vertex* bottom, int winding, EdgeType type);
149     Edge* makeEdge(Vertex* prev, Vertex* next, EdgeType type, const Comparator&);
150     void setTop(Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current,
151                 const Comparator&) const;
152     void setBottom(Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current,
153                    const Comparator&) const;
154     void mergeEdgesAbove(Edge* edge, Edge* other, EdgeList* activeEdges, Vertex** current,
155                          const Comparator&) const;
156     void mergeEdgesBelow(Edge* edge, Edge* other, EdgeList* activeEdges, Vertex** current,
157                          const Comparator&) const;
158     Edge* makeConnectingEdge(Vertex* prev, Vertex* next, EdgeType, const Comparator&,
159                              int windingScale = 1);
160     void mergeVertices(Vertex* src, Vertex* dst, VertexList* mesh, const Comparator&) const;
161     static void FindEnclosingEdges(Vertex* v, EdgeList* edges, Edge** left, Edge** right);
162     void mergeCollinearEdges(Edge* edge, EdgeList* activeEdges, Vertex** current,
163                              const Comparator&) const;
164     bool splitEdge(Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current,
165                    const Comparator&);
166     bool intersectEdgePair(Edge* left, Edge* right, EdgeList* activeEdges, Vertex** current,
167                            const Comparator&);
168     Vertex* makeSortedVertex(const SkPoint&, uint8_t alpha, VertexList* mesh, Vertex* reference,
169                              const Comparator&) const;
170     void computeBisector(Edge* edge1, Edge* edge2, Vertex*) const;
171     bool checkForIntersection(Edge* left, Edge* right, EdgeList* activeEdges, Vertex** current,
172                               VertexList* mesh, const Comparator&);
173     void sanitizeContours(VertexList* contours, int contourCnt) const;
174     bool mergeCoincidentVertices(VertexList* mesh, const Comparator&) const;
175     void buildEdges(VertexList* contours, int contourCnt, VertexList* mesh,
176                     const Comparator&);
177     std::tuple<Poly*, bool> contoursToPolys(VertexList* contours, int contourCnt);
178     std::tuple<Poly*, bool> pathToPolys(float tolerance, const SkRect& clipBounds,
179                       bool* isLinear);
180     static int64_t CountPoints(Poly* polys, SkPathFillType overrideFillType);
181     int polysToTriangles(Poly*, GrEagerVertexAllocator*) const;
182 
183     // FIXME: fPath should be plumbed through function parameters instead.
184     const SkPath fPath;
185     SkArenaAlloc* const fAlloc;
186     int fNumMonotonePolys = 0;
187     int fNumEdges = 0;
188 
189     // Internal control knobs.
190     bool fRoundVerticesToQuarterPixel = false;
191     bool fEmitCoverage = false;
192     bool fPreserveCollinearVertices = false;
193     bool fCollectBreadcrumbTriangles = false;
194 
195     // The breadcrumb triangles serve as a glue that erases T-junctions between a path's outer
196     // curves and its inner polygon triangulation. Drawing a path's outer curves, breadcrumb
197     // triangles, and inner polygon triangulation all together into the stencil buffer has the same
198     // identical rasterized effect as stenciling a classic Redbook fan.
199     //
200     // The breadcrumb triangles track all the edge splits that led from the original inner polygon
201     // edges to the final triangulation. Every time an edge splits, we emit a razor-thin breadcrumb
202     // triangle consisting of the edge's original endpoints and the split point. (We also add
203     // supplemental breadcrumb triangles to areas where abs(winding) > 1.)
204     //
205     //                a
206     //               /
207     //              /
208     //             /
209     //            x  <- Edge splits at x. New breadcrumb triangle is: [a, b, x].
210     //           /
211     //          /
212     //         b
213     //
214     // The opposite-direction shared edges between the triangulation and breadcrumb triangles should
215     // all cancel out, leaving just the set of edges from the original polygon.
216     class BreadcrumbTriangleList {
217     public:
218         struct Node {
NodeNode219             Node(SkPoint a, SkPoint b, SkPoint c) : fPts{a, b, c} {}
220             SkPoint fPts[3];
221             Node* fNext = nullptr;
222         };
head()223         const Node* head() const { return fHead; }
count()224         int count() const { return fCount; }
225 
append(SkArenaAlloc * alloc,SkPoint a,SkPoint b,SkPoint c,int winding)226         void append(SkArenaAlloc* alloc, SkPoint a, SkPoint b, SkPoint c, int winding) {
227             if (a == b || a == c || b == c || winding == 0) {
228                 return;
229             }
230             if (winding < 0) {
231                 std::swap(a, b);
232                 winding = -winding;
233             }
234             for (int i = 0; i < winding; ++i) {
235                 SkASSERT(fTail && !(*fTail));
236                 *fTail = alloc->make<Node>(a, b, c);
237                 fTail = &(*fTail)->fNext;
238             }
239             fCount += winding;
240         }
241 
concat(BreadcrumbTriangleList && list)242         void concat(BreadcrumbTriangleList&& list) {
243             SkASSERT(fTail && !(*fTail));
244             if (list.fHead) {
245                 *fTail = list.fHead;
246                 fTail = list.fTail;
247                 fCount += list.fCount;
248                 list.fHead = nullptr;
249                 list.fTail = &list.fHead;
250                 list.fCount = 0;
251             }
252         }
253 
254     private:
255         Node* fHead = nullptr;
256         Node** fTail = &fHead;
257         int fCount = 0;
258     };
259 
260     mutable BreadcrumbTriangleList fBreadcrumbList;
261 };
262 
263 /**
264  * Vertices are used in three ways: first, the path contours are converted into a
265  * circularly-linked list of Vertices for each contour. After edge construction, the same Vertices
266  * are re-ordered by the merge sort according to the sweep_lt comparator (usually, increasing
267  * in Y) using the same fPrev/fNext pointers that were used for the contours, to avoid
268  * reallocation. Finally, MonotonePolys are built containing a circularly-linked list of
269  * Vertices. (Currently, those Vertices are newly-allocated for the MonotonePolys, since
270  * an individual Vertex from the path mesh may belong to multiple
271  * MonotonePolys, so the original Vertices cannot be re-used.
272  */
273 
274 struct GrTriangulator::Vertex {
VertexVertex275   Vertex(const SkPoint& point, uint8_t alpha)
276     : fPoint(point), fPrev(nullptr), fNext(nullptr)
277     , fFirstEdgeAbove(nullptr), fLastEdgeAbove(nullptr)
278     , fFirstEdgeBelow(nullptr), fLastEdgeBelow(nullptr)
279     , fLeftEnclosingEdge(nullptr), fRightEnclosingEdge(nullptr)
280     , fPartner(nullptr)
281     , fAlpha(alpha)
282     , fSynthetic(false)
283 #if TRIANGULATOR_LOGGING
284     , fID (-1.0f)
285 #endif
286     {}
287     SkPoint fPoint;               // Vertex position
288     Vertex* fPrev;                // Linked list of contours, then Y-sorted vertices.
289     Vertex* fNext;                // "
290     Edge*   fFirstEdgeAbove;      // Linked list of edges above this vertex.
291     Edge*   fLastEdgeAbove;       // "
292     Edge*   fFirstEdgeBelow;      // Linked list of edges below this vertex.
293     Edge*   fLastEdgeBelow;       // "
294     Edge*   fLeftEnclosingEdge;   // Nearest edge in the AEL left of this vertex.
295     Edge*   fRightEnclosingEdge;  // Nearest edge in the AEL right of this vertex.
296     Vertex* fPartner;             // Corresponding inner or outer vertex (for AA).
297     uint8_t fAlpha;
298     bool    fSynthetic;           // Is this a synthetic vertex?
299 #if TRIANGULATOR_LOGGING
300     float   fID;                  // Identifier used for logging.
301 #endif
isConnectedVertex302     bool isConnected() const { return this->fFirstEdgeAbove || this->fFirstEdgeBelow; }
303 };
304 
305 struct GrTriangulator::VertexList {
VertexListVertexList306     VertexList() : fHead(nullptr), fTail(nullptr) {}
VertexListVertexList307     VertexList(Vertex* head, Vertex* tail) : fHead(head), fTail(tail) {}
308     Vertex* fHead;
309     Vertex* fTail;
310     void insert(Vertex* v, Vertex* prev, Vertex* next);
appendVertexList311     void append(Vertex* v) { insert(v, fTail, nullptr); }
appendVertexList312     void append(const VertexList& list) {
313         if (!list.fHead) {
314             return;
315         }
316         if (fTail) {
317             fTail->fNext = list.fHead;
318             list.fHead->fPrev = fTail;
319         } else {
320             fHead = list.fHead;
321         }
322         fTail = list.fTail;
323     }
prependVertexList324     void prepend(Vertex* v) { insert(v, nullptr, fHead); }
325     void remove(Vertex* v);
closeVertexList326     void close() {
327         if (fHead && fTail) {
328             fTail->fNext = fHead;
329             fHead->fPrev = fTail;
330         }
331     }
332 #if TRIANGULATOR_LOGGING
333     void dump() const;
334 #endif
335 };
336 
337 // A line equation in implicit form. fA * x + fB * y + fC = 0, for all points (x, y) on the line.
338 struct GrTriangulator::Line {
LineLine339     Line(double a, double b, double c) : fA(a), fB(b), fC(c) {}
LineLine340     Line(Vertex* p, Vertex* q) : Line(p->fPoint, q->fPoint) {}
LineLine341     Line(const SkPoint& p, const SkPoint& q)
342         : fA(static_cast<double>(q.fY) - p.fY)      // a = dY
343         , fB(static_cast<double>(p.fX) - q.fX)      // b = -dX
344         , fC(static_cast<double>(p.fY) * q.fX -     // c = cross(q, p)
345              static_cast<double>(p.fX) * q.fY) {}
distLine346     double dist(const SkPoint& p) const { return fA * p.fX + fB * p.fY + fC; }
347     Line operator*(double v) const { return Line(fA * v, fB * v, fC * v); }
magSqLine348     double magSq() const { return fA * fA + fB * fB; }
normalizeLine349     void normalize() {
350         double len = sqrt(this->magSq());
351         if (len == 0.0) {
352             return;
353         }
354         double scale = 1.0f / len;
355         fA *= scale;
356         fB *= scale;
357         fC *= scale;
358     }
nearParallelLine359     bool nearParallel(const Line& o) const {
360         return fabs(o.fA - fA) < 0.00001 && fabs(o.fB - fB) < 0.00001;
361     }
362 
363     // Compute the intersection of two (infinite) Lines.
364     bool intersect(const Line& other, SkPoint* point) const;
365     double fA, fB, fC;
366 };
367 
368 /**
369  * An Edge joins a top Vertex to a bottom Vertex. Edge ordering for the list of "edges above" and
370  * "edge below" a vertex as well as for the active edge list is handled by isLeftOf()/isRightOf().
371  * Note that an Edge will give occasionally dist() != 0 for its own endpoints (because floating
372  * point). For speed, that case is only tested by the callers that require it (e.g.,
373  * rewind_if_necessary()). Edges also handle checking for intersection with other edges.
374  * Currently, this converts the edges to the parametric form, in order to avoid doing a division
375  * until an intersection has been confirmed. This is slightly slower in the "found" case, but
376  * a lot faster in the "not found" case.
377  *
378  * The coefficients of the line equation stored in double precision to avoid catastrophic
379  * cancellation in the isLeftOf() and isRightOf() checks. Using doubles ensures that the result is
380  * correct in float, since it's a polynomial of degree 2. The intersect() function, being
381  * degree 5, is still subject to catastrophic cancellation. We deal with that by assuming its
382  * output may be incorrect, and adjusting the mesh topology to match (see comment at the top of
383  * this file).
384  */
385 
386 struct GrTriangulator::Edge {
EdgeEdge387     Edge(Vertex* top, Vertex* bottom, int winding, EdgeType type)
388         : fWinding(winding)
389         , fTop(top)
390         , fBottom(bottom)
391         , fType(type)
392         , fLeft(nullptr)
393         , fRight(nullptr)
394         , fPrevEdgeAbove(nullptr)
395         , fNextEdgeAbove(nullptr)
396         , fPrevEdgeBelow(nullptr)
397         , fNextEdgeBelow(nullptr)
398         , fLeftPoly(nullptr)
399         , fRightPoly(nullptr)
400         , fLeftPolyPrev(nullptr)
401         , fLeftPolyNext(nullptr)
402         , fRightPolyPrev(nullptr)
403         , fRightPolyNext(nullptr)
404         , fUsedInLeftPoly(false)
405         , fUsedInRightPoly(false)
406         , fLine(top, bottom) {
407         }
408     int      fWinding;          // 1 == edge goes downward; -1 = edge goes upward.
409     Vertex*  fTop;              // The top vertex in vertex-sort-order (sweep_lt).
410     Vertex*  fBottom;           // The bottom vertex in vertex-sort-order.
411     EdgeType fType;
412     Edge*    fLeft;             // The linked list of edges in the active edge list.
413     Edge*    fRight;            // "
414     Edge*    fPrevEdgeAbove;    // The linked list of edges in the bottom Vertex's "edges above".
415     Edge*    fNextEdgeAbove;    // "
416     Edge*    fPrevEdgeBelow;    // The linked list of edges in the top Vertex's "edges below".
417     Edge*    fNextEdgeBelow;    // "
418     Poly*    fLeftPoly;         // The Poly to the left of this edge, if any.
419     Poly*    fRightPoly;        // The Poly to the right of this edge, if any.
420     Edge*    fLeftPolyPrev;
421     Edge*    fLeftPolyNext;
422     Edge*    fRightPolyPrev;
423     Edge*    fRightPolyNext;
424     bool     fUsedInLeftPoly;
425     bool     fUsedInRightPoly;
426     Line     fLine;
427 
distEdge428     double dist(const SkPoint& p) const {
429         // Coerce points coincident with the vertices to have dist = 0, since converting from
430         // a double intersection point back to float storage might construct a point that's no
431         // longer on the ideal line.
432         return (p == fTop->fPoint || p == fBottom->fPoint) ? 0.0 : fLine.dist(p);
433     }
isRightOfEdge434     bool isRightOf(Vertex* v) const { return this->dist(v->fPoint) < 0.0; }
isLeftOfEdge435     bool isLeftOf(Vertex* v) const { return this->dist(v->fPoint) > 0.0; }
recomputeEdge436     void recompute() { fLine = Line(fTop, fBottom); }
437     void insertAbove(Vertex*, const Comparator&);
438     void insertBelow(Vertex*, const Comparator&);
439     void disconnect();
440     bool intersect(const Edge& other, SkPoint* p, uint8_t* alpha = nullptr) const;
441 };
442 
443 struct GrTriangulator::EdgeList {
EdgeListEdgeList444     EdgeList() : fHead(nullptr), fTail(nullptr) {}
445     Edge* fHead;
446     Edge* fTail;
447     void insert(Edge* edge, Edge* prev, Edge* next);
448     void insert(Edge* edge, Edge* prev);
appendEdgeList449     void append(Edge* e) { insert(e, fTail, nullptr); }
450     void remove(Edge* edge);
removeAllEdgeList451     void removeAll() {
452         while (fHead) {
453             this->remove(fHead);
454         }
455     }
closeEdgeList456     void close() {
457         if (fHead && fTail) {
458             fTail->fRight = fHead;
459             fHead->fLeft = fTail;
460         }
461     }
containsEdgeList462     bool contains(Edge* edge) const { return edge->fLeft || edge->fRight || fHead == edge; }
463 };
464 
465 struct GrTriangulator::MonotonePoly {
MonotonePolyMonotonePoly466     MonotonePoly(Edge* edge, Side side, int winding)
467         : fSide(side)
468         , fFirstEdge(nullptr)
469         , fLastEdge(nullptr)
470         , fPrev(nullptr)
471         , fNext(nullptr)
472         , fWinding(winding) {
473         this->addEdge(edge);
474     }
475     Side          fSide;
476     Edge*         fFirstEdge;
477     Edge*         fLastEdge;
478     MonotonePoly* fPrev;
479     MonotonePoly* fNext;
480     int fWinding;
481     void addEdge(Edge*);
482 };
483 
484 struct GrTriangulator::Poly {
485     Poly(Vertex* v, int winding);
486 
487     Poly* addEdge(Edge* e, Side side, GrTriangulator*);
lastVertexPoly488     Vertex* lastVertex() const { return fTail ? fTail->fLastEdge->fBottom : fFirstVertex; }
489     Vertex* fFirstVertex;
490     int fWinding;
491     MonotonePoly* fHead;
492     MonotonePoly* fTail;
493     Poly* fNext;
494     Poly* fPartner;
495     int fCount;
496 #if TRIANGULATOR_LOGGING
497     int fID;
498 #endif
499 };
500 
501 struct GrTriangulator::Comparator {
502     enum class Direction { kVertical, kHorizontal };
ComparatorComparator503     Comparator(Direction direction) : fDirection(direction) {}
504     bool sweep_lt(const SkPoint& a, const SkPoint& b) const;
505     Direction fDirection;
506 };
507 
508 #endif
509