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