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