1 /*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "GrTessellator.h"
9
10 #include "GrDefaultGeoProcFactory.h"
11 #include "GrPathUtils.h"
12 #include "GrVertexWriter.h"
13
14 #include "SkArenaAlloc.h"
15 #include "SkGeometry.h"
16 #include "SkPath.h"
17 #include "SkPointPriv.h"
18 #include "SkTDPQueue.h"
19
20 #include <algorithm>
21 #include <cstdio>
22 #include <utility>
23
24 /*
25 * There are six stages to the basic algorithm:
26 *
27 * 1) Linearize the path contours into piecewise linear segments (path_to_contours()).
28 * 2) Build a mesh of edges connecting the vertices (build_edges()).
29 * 3) Sort the vertices in Y (and secondarily in X) (merge_sort()).
30 * 4) Simplify the mesh by inserting new vertices at intersecting edges (simplify()).
31 * 5) Tessellate the simplified mesh into monotone polygons (tessellate()).
32 * 6) Triangulate the monotone polygons directly into a vertex buffer (polys_to_triangles()).
33 *
34 * For screenspace antialiasing, the algorithm is modified as follows:
35 *
36 * Run steps 1-5 above to produce polygons.
37 * 5b) Apply fill rules to extract boundary contours from the polygons (extract_boundaries()).
38 * 5c) Simplify boundaries to remove "pointy" vertices that cause inversions (simplify_boundary()).
39 * 5d) Displace edges by half a pixel inward and outward along their normals. Intersect to find
40 * new vertices, and set zero alpha on the exterior and one alpha on the interior. Build a new
41 * antialiased mesh from those vertices (stroke_boundary()).
42 * Run steps 3-6 above on the new mesh, and produce antialiased triangles.
43 *
44 * The vertex sorting in step (3) is a merge sort, since it plays well with the linked list
45 * of vertices (and the necessity of inserting new vertices on intersection).
46 *
47 * Stages (4) and (5) use an active edge list -- a list of all edges for which the
48 * sweep line has crossed the top vertex, but not the bottom vertex. It's sorted
49 * left-to-right based on the point where both edges are active (when both top vertices
50 * have been seen, so the "lower" top vertex of the two). If the top vertices are equal
51 * (shared), it's sorted based on the last point where both edges are active, so the
52 * "upper" bottom vertex.
53 *
54 * The most complex step is the simplification (4). It's based on the Bentley-Ottman
55 * line-sweep algorithm, but due to floating point inaccuracy, the intersection points are
56 * not exact and may violate the mesh topology or active edge list ordering. We
57 * accommodate this by adjusting the topology of the mesh and AEL to match the intersection
58 * points. This occurs in two ways:
59 *
60 * A) Intersections may cause a shortened edge to no longer be ordered with respect to its
61 * neighbouring edges at the top or bottom vertex. This is handled by merging the
62 * edges (merge_collinear_edges()).
63 * B) Intersections may cause an edge to violate the left-to-right ordering of the
64 * active edge list. This is handled by detecting potential violations and rewinding
65 * the active edge list to the vertex before they occur (rewind() during merging,
66 * rewind_if_necessary() during splitting).
67 *
68 * The tessellation steps (5) and (6) are based on "Triangulating Simple Polygons and
69 * Equivalent Problems" (Fournier and Montuno); also a line-sweep algorithm. Note that it
70 * currently uses a linked list for the active edge list, rather than a 2-3 tree as the
71 * paper describes. The 2-3 tree gives O(lg N) lookups, but insertion and removal also
72 * become O(lg N). In all the test cases, it was found that the cost of frequent O(lg N)
73 * insertions and removals was greater than the cost of infrequent O(N) lookups with the
74 * linked list implementation. With the latter, all removals are O(1), and most insertions
75 * are O(1), since we know the adjacent edge in the active edge list based on the topology.
76 * Only type 2 vertices (see paper) require the O(N) lookups, and these are much less
77 * frequent. There may be other data structures worth investigating, however.
78 *
79 * Note that the orientation of the line sweep algorithms is determined by the aspect ratio of the
80 * path bounds. When the path is taller than it is wide, we sort vertices based on increasing Y
81 * coordinate, and secondarily by increasing X coordinate. When the path is wider than it is tall,
82 * we sort by increasing X coordinate, but secondarily by *decreasing* Y coordinate. This is so
83 * that the "left" and "right" orientation in the code remains correct (edges to the left are
84 * increasing in Y; edges to the right are decreasing in Y). That is, the setting rotates 90
85 * degrees counterclockwise, rather that transposing.
86 */
87
88 #define LOGGING_ENABLED 0
89
90 #if LOGGING_ENABLED
91 #define LOG printf
92 #else
93 #define LOG(...)
94 #endif
95
96 namespace {
97
98 const int kArenaChunkSize = 16 * 1024;
99 const float kCosMiterAngle = 0.97f; // Corresponds to an angle of ~14 degrees.
100
101 struct Vertex;
102 struct Edge;
103 struct Event;
104 struct Poly;
105
106 template <class T, T* T::*Prev, T* T::*Next>
list_insert(T * t,T * prev,T * next,T ** head,T ** tail)107 void list_insert(T* t, T* prev, T* next, T** head, T** tail) {
108 t->*Prev = prev;
109 t->*Next = next;
110 if (prev) {
111 prev->*Next = t;
112 } else if (head) {
113 *head = t;
114 }
115 if (next) {
116 next->*Prev = t;
117 } else if (tail) {
118 *tail = t;
119 }
120 }
121
122 template <class T, T* T::*Prev, T* T::*Next>
list_remove(T * t,T ** head,T ** tail)123 void list_remove(T* t, T** head, T** tail) {
124 if (t->*Prev) {
125 t->*Prev->*Next = t->*Next;
126 } else if (head) {
127 *head = t->*Next;
128 }
129 if (t->*Next) {
130 t->*Next->*Prev = t->*Prev;
131 } else if (tail) {
132 *tail = t->*Prev;
133 }
134 t->*Prev = t->*Next = nullptr;
135 }
136
137 /**
138 * Vertices are used in three ways: first, the path contours are converted into a
139 * circularly-linked list of Vertices for each contour. After edge construction, the same Vertices
140 * are re-ordered by the merge sort according to the sweep_lt comparator (usually, increasing
141 * in Y) using the same fPrev/fNext pointers that were used for the contours, to avoid
142 * reallocation. Finally, MonotonePolys are built containing a circularly-linked list of
143 * Vertices. (Currently, those Vertices are newly-allocated for the MonotonePolys, since
144 * an individual Vertex from the path mesh may belong to multiple
145 * MonotonePolys, so the original Vertices cannot be re-used.
146 */
147
148 struct Vertex {
Vertex__anon777eb59f0111::Vertex149 Vertex(const SkPoint& point, uint8_t alpha)
150 : fPoint(point), fPrev(nullptr), fNext(nullptr)
151 , fFirstEdgeAbove(nullptr), fLastEdgeAbove(nullptr)
152 , fFirstEdgeBelow(nullptr), fLastEdgeBelow(nullptr)
153 , fLeftEnclosingEdge(nullptr), fRightEnclosingEdge(nullptr)
154 , fPartner(nullptr)
155 , fAlpha(alpha)
156 #if LOGGING_ENABLED
157 , fID (-1.0f)
158 #endif
159 {}
160 SkPoint fPoint; // Vertex position
161 Vertex* fPrev; // Linked list of contours, then Y-sorted vertices.
162 Vertex* fNext; // "
163 Edge* fFirstEdgeAbove; // Linked list of edges above this vertex.
164 Edge* fLastEdgeAbove; // "
165 Edge* fFirstEdgeBelow; // Linked list of edges below this vertex.
166 Edge* fLastEdgeBelow; // "
167 Edge* fLeftEnclosingEdge; // Nearest edge in the AEL left of this vertex.
168 Edge* fRightEnclosingEdge; // Nearest edge in the AEL right of this vertex.
169 Vertex* fPartner; // Corresponding inner or outer vertex (for AA).
170 uint8_t fAlpha;
171 #if LOGGING_ENABLED
172 float fID; // Identifier used for logging.
173 #endif
174 };
175
176 /***************************************************************************************/
177
178 typedef bool (*CompareFunc)(const SkPoint& a, const SkPoint& b);
179
sweep_lt_horiz(const SkPoint & a,const SkPoint & b)180 bool sweep_lt_horiz(const SkPoint& a, const SkPoint& b) {
181 return a.fX < b.fX || (a.fX == b.fX && a.fY > b.fY);
182 }
183
sweep_lt_vert(const SkPoint & a,const SkPoint & b)184 bool sweep_lt_vert(const SkPoint& a, const SkPoint& b) {
185 return a.fY < b.fY || (a.fY == b.fY && a.fX < b.fX);
186 }
187
188 struct Comparator {
189 enum class Direction { kVertical, kHorizontal };
Comparator__anon777eb59f0111::Comparator190 Comparator(Direction direction) : fDirection(direction) {}
sweep_lt__anon777eb59f0111::Comparator191 bool sweep_lt(const SkPoint& a, const SkPoint& b) const {
192 return fDirection == Direction::kHorizontal ? sweep_lt_horiz(a, b) : sweep_lt_vert(a, b);
193 }
194 Direction fDirection;
195 };
196
emit_vertex(Vertex * v,bool emitCoverage,void * data)197 inline void* emit_vertex(Vertex* v, bool emitCoverage, void* data) {
198 GrVertexWriter verts{data};
199 verts.write(v->fPoint);
200
201 if (emitCoverage) {
202 verts.write(GrNormalizeByteToFloat(v->fAlpha));
203 }
204
205 return verts.fPtr;
206 }
207
emit_triangle(Vertex * v0,Vertex * v1,Vertex * v2,bool emitCoverage,void * data)208 void* emit_triangle(Vertex* v0, Vertex* v1, Vertex* v2, bool emitCoverage, void* data) {
209 LOG("emit_triangle %g (%g, %g) %d\n", v0->fID, v0->fPoint.fX, v0->fPoint.fY, v0->fAlpha);
210 LOG(" %g (%g, %g) %d\n", v1->fID, v1->fPoint.fX, v1->fPoint.fY, v1->fAlpha);
211 LOG(" %g (%g, %g) %d\n", v2->fID, v2->fPoint.fX, v2->fPoint.fY, v2->fAlpha);
212 #if TESSELLATOR_WIREFRAME
213 data = emit_vertex(v0, emitCoverage, data);
214 data = emit_vertex(v1, emitCoverage, data);
215 data = emit_vertex(v1, emitCoverage, data);
216 data = emit_vertex(v2, emitCoverage, data);
217 data = emit_vertex(v2, emitCoverage, data);
218 data = emit_vertex(v0, emitCoverage, data);
219 #else
220 data = emit_vertex(v0, emitCoverage, data);
221 data = emit_vertex(v1, emitCoverage, data);
222 data = emit_vertex(v2, emitCoverage, data);
223 #endif
224 return data;
225 }
226
227 struct VertexList {
VertexList__anon777eb59f0111::VertexList228 VertexList() : fHead(nullptr), fTail(nullptr) {}
VertexList__anon777eb59f0111::VertexList229 VertexList(Vertex* head, Vertex* tail) : fHead(head), fTail(tail) {}
230 Vertex* fHead;
231 Vertex* fTail;
insert__anon777eb59f0111::VertexList232 void insert(Vertex* v, Vertex* prev, Vertex* next) {
233 list_insert<Vertex, &Vertex::fPrev, &Vertex::fNext>(v, prev, next, &fHead, &fTail);
234 }
append__anon777eb59f0111::VertexList235 void append(Vertex* v) {
236 insert(v, fTail, nullptr);
237 }
append__anon777eb59f0111::VertexList238 void append(const VertexList& list) {
239 if (!list.fHead) {
240 return;
241 }
242 if (fTail) {
243 fTail->fNext = list.fHead;
244 list.fHead->fPrev = fTail;
245 } else {
246 fHead = list.fHead;
247 }
248 fTail = list.fTail;
249 }
prepend__anon777eb59f0111::VertexList250 void prepend(Vertex* v) {
251 insert(v, nullptr, fHead);
252 }
remove__anon777eb59f0111::VertexList253 void remove(Vertex* v) {
254 list_remove<Vertex, &Vertex::fPrev, &Vertex::fNext>(v, &fHead, &fTail);
255 }
close__anon777eb59f0111::VertexList256 void close() {
257 if (fHead && fTail) {
258 fTail->fNext = fHead;
259 fHead->fPrev = fTail;
260 }
261 }
262 };
263
264 // Round to nearest quarter-pixel. This is used for screenspace tessellation.
265
round(SkPoint * p)266 inline void round(SkPoint* p) {
267 p->fX = SkScalarRoundToScalar(p->fX * SkFloatToScalar(4.0f)) * SkFloatToScalar(0.25f);
268 p->fY = SkScalarRoundToScalar(p->fY * SkFloatToScalar(4.0f)) * SkFloatToScalar(0.25f);
269 }
270
double_to_clamped_scalar(double d)271 inline SkScalar double_to_clamped_scalar(double d) {
272 return SkDoubleToScalar(std::min((double) SK_ScalarMax, std::max(d, (double) -SK_ScalarMax)));
273 }
274
275 // A line equation in implicit form. fA * x + fB * y + fC = 0, for all points (x, y) on the line.
276 struct Line {
Line__anon777eb59f0111::Line277 Line(double a, double b, double c) : fA(a), fB(b), fC(c) {}
Line__anon777eb59f0111::Line278 Line(Vertex* p, Vertex* q) : Line(p->fPoint, q->fPoint) {}
Line__anon777eb59f0111::Line279 Line(const SkPoint& p, const SkPoint& q)
280 : fA(static_cast<double>(q.fY) - p.fY) // a = dY
281 , fB(static_cast<double>(p.fX) - q.fX) // b = -dX
282 , fC(static_cast<double>(p.fY) * q.fX - // c = cross(q, p)
283 static_cast<double>(p.fX) * q.fY) {}
dist__anon777eb59f0111::Line284 double dist(const SkPoint& p) const {
285 return fA * p.fX + fB * p.fY + fC;
286 }
operator *__anon777eb59f0111::Line287 Line operator*(double v) const {
288 return Line(fA * v, fB * v, fC * v);
289 }
magSq__anon777eb59f0111::Line290 double magSq() const {
291 return fA * fA + fB * fB;
292 }
normalize__anon777eb59f0111::Line293 void normalize() {
294 double len = sqrt(this->magSq());
295 if (len == 0.0) {
296 return;
297 }
298 double scale = 1.0f / len;
299 fA *= scale;
300 fB *= scale;
301 fC *= scale;
302 }
nearParallel__anon777eb59f0111::Line303 bool nearParallel(const Line& o) const {
304 return fabs(o.fA - fA) < 0.00001 && fabs(o.fB - fB) < 0.00001;
305 }
306
307 // Compute the intersection of two (infinite) Lines.
intersect__anon777eb59f0111::Line308 bool intersect(const Line& other, SkPoint* point) const {
309 double denom = fA * other.fB - fB * other.fA;
310 if (denom == 0.0) {
311 return false;
312 }
313 double scale = 1.0 / denom;
314 point->fX = double_to_clamped_scalar((fB * other.fC - other.fB * fC) * scale);
315 point->fY = double_to_clamped_scalar((other.fA * fC - fA * other.fC) * scale);
316 round(point);
317 return true;
318 }
319 double fA, fB, fC;
320 };
321
322 /**
323 * An Edge joins a top Vertex to a bottom Vertex. Edge ordering for the list of "edges above" and
324 * "edge below" a vertex as well as for the active edge list is handled by isLeftOf()/isRightOf().
325 * Note that an Edge will give occasionally dist() != 0 for its own endpoints (because floating
326 * point). For speed, that case is only tested by the callers that require it (e.g.,
327 * rewind_if_necessary()). Edges also handle checking for intersection with other edges.
328 * Currently, this converts the edges to the parametric form, in order to avoid doing a division
329 * until an intersection has been confirmed. This is slightly slower in the "found" case, but
330 * a lot faster in the "not found" case.
331 *
332 * The coefficients of the line equation stored in double precision to avoid catastrphic
333 * cancellation in the isLeftOf() and isRightOf() checks. Using doubles ensures that the result is
334 * correct in float, since it's a polynomial of degree 2. The intersect() function, being
335 * degree 5, is still subject to catastrophic cancellation. We deal with that by assuming its
336 * output may be incorrect, and adjusting the mesh topology to match (see comment at the top of
337 * this file).
338 */
339
340 struct Edge {
341 enum class Type { kInner, kOuter, kConnector };
Edge__anon777eb59f0111::Edge342 Edge(Vertex* top, Vertex* bottom, int winding, Type type)
343 : fWinding(winding)
344 , fTop(top)
345 , fBottom(bottom)
346 , fType(type)
347 , fLeft(nullptr)
348 , fRight(nullptr)
349 , fPrevEdgeAbove(nullptr)
350 , fNextEdgeAbove(nullptr)
351 , fPrevEdgeBelow(nullptr)
352 , fNextEdgeBelow(nullptr)
353 , fLeftPoly(nullptr)
354 , fRightPoly(nullptr)
355 , fEvent(nullptr)
356 , fLeftPolyPrev(nullptr)
357 , fLeftPolyNext(nullptr)
358 , fRightPolyPrev(nullptr)
359 , fRightPolyNext(nullptr)
360 , fOverlap(false)
361 , fUsedInLeftPoly(false)
362 , fUsedInRightPoly(false)
363 , fLine(top, bottom) {
364 }
365 int fWinding; // 1 == edge goes downward; -1 = edge goes upward.
366 Vertex* fTop; // The top vertex in vertex-sort-order (sweep_lt).
367 Vertex* fBottom; // The bottom vertex in vertex-sort-order.
368 Type fType;
369 Edge* fLeft; // The linked list of edges in the active edge list.
370 Edge* fRight; // "
371 Edge* fPrevEdgeAbove; // The linked list of edges in the bottom Vertex's "edges above".
372 Edge* fNextEdgeAbove; // "
373 Edge* fPrevEdgeBelow; // The linked list of edges in the top Vertex's "edges below".
374 Edge* fNextEdgeBelow; // "
375 Poly* fLeftPoly; // The Poly to the left of this edge, if any.
376 Poly* fRightPoly; // The Poly to the right of this edge, if any.
377 Event* fEvent;
378 Edge* fLeftPolyPrev;
379 Edge* fLeftPolyNext;
380 Edge* fRightPolyPrev;
381 Edge* fRightPolyNext;
382 bool fOverlap; // True if there's an overlap region adjacent to this edge.
383 bool fUsedInLeftPoly;
384 bool fUsedInRightPoly;
385 Line fLine;
dist__anon777eb59f0111::Edge386 double dist(const SkPoint& p) const {
387 return fLine.dist(p);
388 }
isRightOf__anon777eb59f0111::Edge389 bool isRightOf(Vertex* v) const {
390 return fLine.dist(v->fPoint) < 0.0;
391 }
isLeftOf__anon777eb59f0111::Edge392 bool isLeftOf(Vertex* v) const {
393 return fLine.dist(v->fPoint) > 0.0;
394 }
recompute__anon777eb59f0111::Edge395 void recompute() {
396 fLine = Line(fTop, fBottom);
397 }
intersect__anon777eb59f0111::Edge398 bool intersect(const Edge& other, SkPoint* p, uint8_t* alpha = nullptr) const {
399 LOG("intersecting %g -> %g with %g -> %g\n",
400 fTop->fID, fBottom->fID,
401 other.fTop->fID, other.fBottom->fID);
402 if (fTop == other.fTop || fBottom == other.fBottom) {
403 return false;
404 }
405 double denom = fLine.fA * other.fLine.fB - fLine.fB * other.fLine.fA;
406 if (denom == 0.0) {
407 return false;
408 }
409 double dx = static_cast<double>(other.fTop->fPoint.fX) - fTop->fPoint.fX;
410 double dy = static_cast<double>(other.fTop->fPoint.fY) - fTop->fPoint.fY;
411 double sNumer = dy * other.fLine.fB + dx * other.fLine.fA;
412 double tNumer = dy * fLine.fB + dx * fLine.fA;
413 // If (sNumer / denom) or (tNumer / denom) is not in [0..1], exit early.
414 // This saves us doing the divide below unless absolutely necessary.
415 if (denom > 0.0 ? (sNumer < 0.0 || sNumer > denom || tNumer < 0.0 || tNumer > denom)
416 : (sNumer > 0.0 || sNumer < denom || tNumer > 0.0 || tNumer < denom)) {
417 return false;
418 }
419 double s = sNumer / denom;
420 SkASSERT(s >= 0.0 && s <= 1.0);
421 p->fX = SkDoubleToScalar(fTop->fPoint.fX - s * fLine.fB);
422 p->fY = SkDoubleToScalar(fTop->fPoint.fY + s * fLine.fA);
423 if (alpha) {
424 if (fType == Type::kConnector) {
425 *alpha = (1.0 - s) * fTop->fAlpha + s * fBottom->fAlpha;
426 } else if (other.fType == Type::kConnector) {
427 double t = tNumer / denom;
428 *alpha = (1.0 - t) * other.fTop->fAlpha + t * other.fBottom->fAlpha;
429 } else if (fType == Type::kOuter && other.fType == Type::kOuter) {
430 *alpha = 0;
431 } else {
432 *alpha = 255;
433 }
434 }
435 return true;
436 }
437 };
438
439 struct EdgeList {
EdgeList__anon777eb59f0111::EdgeList440 EdgeList() : fHead(nullptr), fTail(nullptr) {}
441 Edge* fHead;
442 Edge* fTail;
insert__anon777eb59f0111::EdgeList443 void insert(Edge* edge, Edge* prev, Edge* next) {
444 list_insert<Edge, &Edge::fLeft, &Edge::fRight>(edge, prev, next, &fHead, &fTail);
445 }
append__anon777eb59f0111::EdgeList446 void append(Edge* e) {
447 insert(e, fTail, nullptr);
448 }
remove__anon777eb59f0111::EdgeList449 void remove(Edge* edge) {
450 list_remove<Edge, &Edge::fLeft, &Edge::fRight>(edge, &fHead, &fTail);
451 }
removeAll__anon777eb59f0111::EdgeList452 void removeAll() {
453 while (fHead) {
454 this->remove(fHead);
455 }
456 }
close__anon777eb59f0111::EdgeList457 void close() {
458 if (fHead && fTail) {
459 fTail->fRight = fHead;
460 fHead->fLeft = fTail;
461 }
462 }
contains__anon777eb59f0111::EdgeList463 bool contains(Edge* edge) const {
464 return edge->fLeft || edge->fRight || fHead == edge;
465 }
466 };
467
468 struct Event {
Event__anon777eb59f0111::Event469 Event(Edge* edge, bool isOuterBoundary, const SkPoint& point, uint8_t alpha)
470 : fEdge(edge), fIsOuterBoundary(isOuterBoundary), fPoint(point), fAlpha(alpha)
471 , fPrev(nullptr), fNext(nullptr) {
472 }
473 Edge* fEdge;
474 bool fIsOuterBoundary;
475 SkPoint fPoint;
476 uint8_t fAlpha;
477 Event* fPrev;
478 Event* fNext;
479 void apply(VertexList* mesh, Comparator& c, SkArenaAlloc& alloc);
480 };
481
compare(Event * const & e1,Event * const & e2)482 bool compare(Event* const& e1, Event* const& e2) {
483 return e1->fAlpha > e2->fAlpha;
484 }
485
486 struct EventList : public SkTDPQueue<Event*, &compare> {};
487
create_event(Edge * e,bool isOuterBoundary,EventList * events,SkArenaAlloc & alloc)488 void create_event(Edge* e, bool isOuterBoundary, EventList* events, SkArenaAlloc& alloc) {
489 Edge bisector1(e->fTop, e->fTop->fPartner, 1, Edge::Type::kConnector);
490 Edge bisector2(e->fBottom, e->fBottom->fPartner, 1, Edge::Type::kConnector);
491 SkPoint p;
492 uint8_t alpha;
493 if (bisector1.intersect(bisector2, &p, &alpha)) {
494 LOG("found overlap edge %g -> %g, will collapse to %g,%g alpha %d\n",
495 e->fTop->fID, e->fBottom->fID, p.fX, p.fY, alpha);
496 e->fEvent = alloc.make<Event>(e, isOuterBoundary, p, alpha);
497 events->insert(e->fEvent);
498 }
499 }
500
501 /***************************************************************************************/
502
503 struct Poly {
Poly__anon777eb59f0111::Poly504 Poly(Vertex* v, int winding)
505 : fFirstVertex(v)
506 , fWinding(winding)
507 , fHead(nullptr)
508 , fTail(nullptr)
509 , fNext(nullptr)
510 , fPartner(nullptr)
511 , fCount(0)
512 {
513 #if LOGGING_ENABLED
514 static int gID = 0;
515 fID = gID++;
516 LOG("*** created Poly %d\n", fID);
517 #endif
518 }
519 typedef enum { kLeft_Side, kRight_Side } Side;
520 struct MonotonePoly {
MonotonePoly__anon777eb59f0111::Poly::MonotonePoly521 MonotonePoly(Edge* edge, Side side)
522 : fSide(side)
523 , fFirstEdge(nullptr)
524 , fLastEdge(nullptr)
525 , fPrev(nullptr)
526 , fNext(nullptr) {
527 this->addEdge(edge);
528 }
529 Side fSide;
530 Edge* fFirstEdge;
531 Edge* fLastEdge;
532 MonotonePoly* fPrev;
533 MonotonePoly* fNext;
addEdge__anon777eb59f0111::Poly::MonotonePoly534 void addEdge(Edge* edge) {
535 if (fSide == kRight_Side) {
536 SkASSERT(!edge->fUsedInRightPoly);
537 list_insert<Edge, &Edge::fRightPolyPrev, &Edge::fRightPolyNext>(
538 edge, fLastEdge, nullptr, &fFirstEdge, &fLastEdge);
539 edge->fUsedInRightPoly = true;
540 } else {
541 SkASSERT(!edge->fUsedInLeftPoly);
542 list_insert<Edge, &Edge::fLeftPolyPrev, &Edge::fLeftPolyNext>(
543 edge, fLastEdge, nullptr, &fFirstEdge, &fLastEdge);
544 edge->fUsedInLeftPoly = true;
545 }
546 }
547
emit__anon777eb59f0111::Poly::MonotonePoly548 void* emit(bool emitCoverage, void* data) {
549 Edge* e = fFirstEdge;
550 VertexList vertices;
551 vertices.append(e->fTop);
552 int count = 1;
553 while (e != nullptr) {
554 if (kRight_Side == fSide) {
555 vertices.append(e->fBottom);
556 e = e->fRightPolyNext;
557 } else {
558 vertices.prepend(e->fBottom);
559 e = e->fLeftPolyNext;
560 }
561 count++;
562 }
563 Vertex* first = vertices.fHead;
564 Vertex* v = first->fNext;
565 while (v != vertices.fTail) {
566 SkASSERT(v && v->fPrev && v->fNext);
567 Vertex* prev = v->fPrev;
568 Vertex* curr = v;
569 Vertex* next = v->fNext;
570 if (count == 3) {
571 return emit_triangle(prev, curr, next, emitCoverage, data);
572 }
573 double ax = static_cast<double>(curr->fPoint.fX) - prev->fPoint.fX;
574 double ay = static_cast<double>(curr->fPoint.fY) - prev->fPoint.fY;
575 double bx = static_cast<double>(next->fPoint.fX) - curr->fPoint.fX;
576 double by = static_cast<double>(next->fPoint.fY) - curr->fPoint.fY;
577 if (ax * by - ay * bx >= 0.0) {
578 data = emit_triangle(prev, curr, next, emitCoverage, data);
579 v->fPrev->fNext = v->fNext;
580 v->fNext->fPrev = v->fPrev;
581 count--;
582 if (v->fPrev == first) {
583 v = v->fNext;
584 } else {
585 v = v->fPrev;
586 }
587 } else {
588 v = v->fNext;
589 }
590 }
591 return data;
592 }
593 };
addEdge__anon777eb59f0111::Poly594 Poly* addEdge(Edge* e, Side side, SkArenaAlloc& alloc) {
595 LOG("addEdge (%g -> %g) to poly %d, %s side\n",
596 e->fTop->fID, e->fBottom->fID, fID, side == kLeft_Side ? "left" : "right");
597 Poly* partner = fPartner;
598 Poly* poly = this;
599 if (side == kRight_Side) {
600 if (e->fUsedInRightPoly) {
601 return this;
602 }
603 } else {
604 if (e->fUsedInLeftPoly) {
605 return this;
606 }
607 }
608 if (partner) {
609 fPartner = partner->fPartner = nullptr;
610 }
611 if (!fTail) {
612 fHead = fTail = alloc.make<MonotonePoly>(e, side);
613 fCount += 2;
614 } else if (e->fBottom == fTail->fLastEdge->fBottom) {
615 return poly;
616 } else if (side == fTail->fSide) {
617 fTail->addEdge(e);
618 fCount++;
619 } else {
620 e = alloc.make<Edge>(fTail->fLastEdge->fBottom, e->fBottom, 1, Edge::Type::kInner);
621 fTail->addEdge(e);
622 fCount++;
623 if (partner) {
624 partner->addEdge(e, side, alloc);
625 poly = partner;
626 } else {
627 MonotonePoly* m = alloc.make<MonotonePoly>(e, side);
628 m->fPrev = fTail;
629 fTail->fNext = m;
630 fTail = m;
631 }
632 }
633 return poly;
634 }
emit__anon777eb59f0111::Poly635 void* emit(bool emitCoverage, void *data) {
636 if (fCount < 3) {
637 return data;
638 }
639 LOG("emit() %d, size %d\n", fID, fCount);
640 for (MonotonePoly* m = fHead; m != nullptr; m = m->fNext) {
641 data = m->emit(emitCoverage, data);
642 }
643 return data;
644 }
lastVertex__anon777eb59f0111::Poly645 Vertex* lastVertex() const { return fTail ? fTail->fLastEdge->fBottom : fFirstVertex; }
646 Vertex* fFirstVertex;
647 int fWinding;
648 MonotonePoly* fHead;
649 MonotonePoly* fTail;
650 Poly* fNext;
651 Poly* fPartner;
652 int fCount;
653 #if LOGGING_ENABLED
654 int fID;
655 #endif
656 };
657
658 /***************************************************************************************/
659
coincident(const SkPoint & a,const SkPoint & b)660 bool coincident(const SkPoint& a, const SkPoint& b) {
661 return a == b;
662 }
663
new_poly(Poly ** head,Vertex * v,int winding,SkArenaAlloc & alloc)664 Poly* new_poly(Poly** head, Vertex* v, int winding, SkArenaAlloc& alloc) {
665 Poly* poly = alloc.make<Poly>(v, winding);
666 poly->fNext = *head;
667 *head = poly;
668 return poly;
669 }
670
append_point_to_contour(const SkPoint & p,VertexList * contour,SkArenaAlloc & alloc)671 void append_point_to_contour(const SkPoint& p, VertexList* contour, SkArenaAlloc& alloc) {
672 Vertex* v = alloc.make<Vertex>(p, 255);
673 #if LOGGING_ENABLED
674 static float gID = 0.0f;
675 v->fID = gID++;
676 #endif
677 contour->append(v);
678 }
679
quad_error_at(const SkPoint pts[3],SkScalar t,SkScalar u)680 SkScalar quad_error_at(const SkPoint pts[3], SkScalar t, SkScalar u) {
681 SkQuadCoeff quad(pts);
682 SkPoint p0 = to_point(quad.eval(t - 0.5f * u));
683 SkPoint mid = to_point(quad.eval(t));
684 SkPoint p1 = to_point(quad.eval(t + 0.5f * u));
685 if (!p0.isFinite() || !mid.isFinite() || !p1.isFinite()) {
686 return 0;
687 }
688 return SkPointPriv::DistanceToLineSegmentBetweenSqd(mid, p0, p1);
689 }
690
append_quadratic_to_contour(const SkPoint pts[3],SkScalar toleranceSqd,VertexList * contour,SkArenaAlloc & alloc)691 void append_quadratic_to_contour(const SkPoint pts[3], SkScalar toleranceSqd, VertexList* contour,
692 SkArenaAlloc& alloc) {
693 SkQuadCoeff quad(pts);
694 Sk2s aa = quad.fA * quad.fA;
695 SkScalar denom = 2.0f * (aa[0] + aa[1]);
696 Sk2s ab = quad.fA * quad.fB;
697 SkScalar t = denom ? (-ab[0] - ab[1]) / denom : 0.0f;
698 int nPoints = 1;
699 SkScalar u = 1.0f;
700 // Test possible subdivision values only at the point of maximum curvature.
701 // If it passes the flatness metric there, it'll pass everywhere.
702 while (nPoints < GrPathUtils::kMaxPointsPerCurve) {
703 u = 1.0f / nPoints;
704 if (quad_error_at(pts, t, u) < toleranceSqd) {
705 break;
706 }
707 nPoints++;
708 }
709 for (int j = 1; j <= nPoints; j++) {
710 append_point_to_contour(to_point(quad.eval(j * u)), contour, alloc);
711 }
712 }
713
generate_cubic_points(const SkPoint & p0,const SkPoint & p1,const SkPoint & p2,const SkPoint & p3,SkScalar tolSqd,VertexList * contour,int pointsLeft,SkArenaAlloc & alloc)714 void generate_cubic_points(const SkPoint& p0,
715 const SkPoint& p1,
716 const SkPoint& p2,
717 const SkPoint& p3,
718 SkScalar tolSqd,
719 VertexList* contour,
720 int pointsLeft,
721 SkArenaAlloc& alloc) {
722 SkScalar d1 = SkPointPriv::DistanceToLineSegmentBetweenSqd(p1, p0, p3);
723 SkScalar d2 = SkPointPriv::DistanceToLineSegmentBetweenSqd(p2, p0, p3);
724 if (pointsLeft < 2 || (d1 < tolSqd && d2 < tolSqd) ||
725 !SkScalarIsFinite(d1) || !SkScalarIsFinite(d2)) {
726 append_point_to_contour(p3, contour, alloc);
727 return;
728 }
729 const SkPoint q[] = {
730 { SkScalarAve(p0.fX, p1.fX), SkScalarAve(p0.fY, p1.fY) },
731 { SkScalarAve(p1.fX, p2.fX), SkScalarAve(p1.fY, p2.fY) },
732 { SkScalarAve(p2.fX, p3.fX), SkScalarAve(p2.fY, p3.fY) }
733 };
734 const SkPoint r[] = {
735 { SkScalarAve(q[0].fX, q[1].fX), SkScalarAve(q[0].fY, q[1].fY) },
736 { SkScalarAve(q[1].fX, q[2].fX), SkScalarAve(q[1].fY, q[2].fY) }
737 };
738 const SkPoint s = { SkScalarAve(r[0].fX, r[1].fX), SkScalarAve(r[0].fY, r[1].fY) };
739 pointsLeft >>= 1;
740 generate_cubic_points(p0, q[0], r[0], s, tolSqd, contour, pointsLeft, alloc);
741 generate_cubic_points(s, r[1], q[2], p3, tolSqd, contour, pointsLeft, alloc);
742 }
743
744 // Stage 1: convert the input path to a set of linear contours (linked list of Vertices).
745
path_to_contours(const SkPath & path,SkScalar tolerance,const SkRect & clipBounds,VertexList * contours,SkArenaAlloc & alloc,bool * isLinear)746 void path_to_contours(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
747 VertexList* contours, SkArenaAlloc& alloc, bool *isLinear) {
748 SkScalar toleranceSqd = tolerance * tolerance;
749
750 SkPoint pts[4];
751 *isLinear = true;
752 VertexList* contour = contours;
753 SkPath::Iter iter(path, false);
754 if (path.isInverseFillType()) {
755 SkPoint quad[4];
756 clipBounds.toQuad(quad);
757 for (int i = 3; i >= 0; i--) {
758 append_point_to_contour(quad[i], contours, alloc);
759 }
760 contour++;
761 }
762 SkAutoConicToQuads converter;
763 SkPath::Verb verb;
764 while ((verb = iter.next(pts, false)) != SkPath::kDone_Verb) {
765 switch (verb) {
766 case SkPath::kConic_Verb: {
767 SkScalar weight = iter.conicWeight();
768 const SkPoint* quadPts = converter.computeQuads(pts, weight, toleranceSqd);
769 for (int i = 0; i < converter.countQuads(); ++i) {
770 append_quadratic_to_contour(quadPts, toleranceSqd, contour, alloc);
771 quadPts += 2;
772 }
773 *isLinear = false;
774 break;
775 }
776 case SkPath::kMove_Verb:
777 if (contour->fHead) {
778 contour++;
779 }
780 append_point_to_contour(pts[0], contour, alloc);
781 break;
782 case SkPath::kLine_Verb: {
783 append_point_to_contour(pts[1], contour, alloc);
784 break;
785 }
786 case SkPath::kQuad_Verb: {
787 append_quadratic_to_contour(pts, toleranceSqd, contour, alloc);
788 *isLinear = false;
789 break;
790 }
791 case SkPath::kCubic_Verb: {
792 int pointsLeft = GrPathUtils::cubicPointCount(pts, tolerance);
793 generate_cubic_points(pts[0], pts[1], pts[2], pts[3], toleranceSqd, contour,
794 pointsLeft, alloc);
795 *isLinear = false;
796 break;
797 }
798 case SkPath::kClose_Verb:
799 case SkPath::kDone_Verb:
800 break;
801 }
802 }
803 }
804
apply_fill_type(SkPath::FillType fillType,int winding)805 inline bool apply_fill_type(SkPath::FillType fillType, int winding) {
806 switch (fillType) {
807 case SkPath::kWinding_FillType:
808 return winding != 0;
809 case SkPath::kEvenOdd_FillType:
810 return (winding & 1) != 0;
811 case SkPath::kInverseWinding_FillType:
812 return winding == 1;
813 case SkPath::kInverseEvenOdd_FillType:
814 return (winding & 1) == 1;
815 default:
816 SkASSERT(false);
817 return false;
818 }
819 }
820
apply_fill_type(SkPath::FillType fillType,Poly * poly)821 inline bool apply_fill_type(SkPath::FillType fillType, Poly* poly) {
822 return poly && apply_fill_type(fillType, poly->fWinding);
823 }
824
new_edge(Vertex * prev,Vertex * next,Edge::Type type,Comparator & c,SkArenaAlloc & alloc)825 Edge* new_edge(Vertex* prev, Vertex* next, Edge::Type type, Comparator& c, SkArenaAlloc& alloc) {
826 int winding = c.sweep_lt(prev->fPoint, next->fPoint) ? 1 : -1;
827 Vertex* top = winding < 0 ? next : prev;
828 Vertex* bottom = winding < 0 ? prev : next;
829 return alloc.make<Edge>(top, bottom, winding, type);
830 }
831
remove_edge(Edge * edge,EdgeList * edges)832 void remove_edge(Edge* edge, EdgeList* edges) {
833 LOG("removing edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
834 SkASSERT(edges->contains(edge));
835 edges->remove(edge);
836 }
837
insert_edge(Edge * edge,Edge * prev,EdgeList * edges)838 void insert_edge(Edge* edge, Edge* prev, EdgeList* edges) {
839 LOG("inserting edge %g -> %g\n", edge->fTop->fID, edge->fBottom->fID);
840 SkASSERT(!edges->contains(edge));
841 Edge* next = prev ? prev->fRight : edges->fHead;
842 edges->insert(edge, prev, next);
843 }
844
find_enclosing_edges(Vertex * v,EdgeList * edges,Edge ** left,Edge ** right)845 void find_enclosing_edges(Vertex* v, EdgeList* edges, Edge** left, Edge** right) {
846 if (v->fFirstEdgeAbove && v->fLastEdgeAbove) {
847 *left = v->fFirstEdgeAbove->fLeft;
848 *right = v->fLastEdgeAbove->fRight;
849 return;
850 }
851 Edge* next = nullptr;
852 Edge* prev;
853 for (prev = edges->fTail; prev != nullptr; prev = prev->fLeft) {
854 if (prev->isLeftOf(v)) {
855 break;
856 }
857 next = prev;
858 }
859 *left = prev;
860 *right = next;
861 }
862
insert_edge_above(Edge * edge,Vertex * v,Comparator & c)863 void insert_edge_above(Edge* edge, Vertex* v, Comparator& c) {
864 if (edge->fTop->fPoint == edge->fBottom->fPoint ||
865 c.sweep_lt(edge->fBottom->fPoint, edge->fTop->fPoint)) {
866 return;
867 }
868 LOG("insert edge (%g -> %g) above vertex %g\n", edge->fTop->fID, edge->fBottom->fID, v->fID);
869 Edge* prev = nullptr;
870 Edge* next;
871 for (next = v->fFirstEdgeAbove; next; next = next->fNextEdgeAbove) {
872 if (next->isRightOf(edge->fTop)) {
873 break;
874 }
875 prev = next;
876 }
877 list_insert<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
878 edge, prev, next, &v->fFirstEdgeAbove, &v->fLastEdgeAbove);
879 }
880
insert_edge_below(Edge * edge,Vertex * v,Comparator & c)881 void insert_edge_below(Edge* edge, Vertex* v, Comparator& c) {
882 if (edge->fTop->fPoint == edge->fBottom->fPoint ||
883 c.sweep_lt(edge->fBottom->fPoint, edge->fTop->fPoint)) {
884 return;
885 }
886 LOG("insert edge (%g -> %g) below vertex %g\n", edge->fTop->fID, edge->fBottom->fID, v->fID);
887 Edge* prev = nullptr;
888 Edge* next;
889 for (next = v->fFirstEdgeBelow; next; next = next->fNextEdgeBelow) {
890 if (next->isRightOf(edge->fBottom)) {
891 break;
892 }
893 prev = next;
894 }
895 list_insert<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
896 edge, prev, next, &v->fFirstEdgeBelow, &v->fLastEdgeBelow);
897 }
898
remove_edge_above(Edge * edge)899 void remove_edge_above(Edge* edge) {
900 SkASSERT(edge->fTop && edge->fBottom);
901 LOG("removing edge (%g -> %g) above vertex %g\n", edge->fTop->fID, edge->fBottom->fID,
902 edge->fBottom->fID);
903 list_remove<Edge, &Edge::fPrevEdgeAbove, &Edge::fNextEdgeAbove>(
904 edge, &edge->fBottom->fFirstEdgeAbove, &edge->fBottom->fLastEdgeAbove);
905 }
906
remove_edge_below(Edge * edge)907 void remove_edge_below(Edge* edge) {
908 SkASSERT(edge->fTop && edge->fBottom);
909 LOG("removing edge (%g -> %g) below vertex %g\n", edge->fTop->fID, edge->fBottom->fID,
910 edge->fTop->fID);
911 list_remove<Edge, &Edge::fPrevEdgeBelow, &Edge::fNextEdgeBelow>(
912 edge, &edge->fTop->fFirstEdgeBelow, &edge->fTop->fLastEdgeBelow);
913 }
914
disconnect(Edge * edge)915 void disconnect(Edge* edge)
916 {
917 remove_edge_above(edge);
918 remove_edge_below(edge);
919 }
920
921 void merge_collinear_edges(Edge* edge, EdgeList* activeEdges, Vertex** current, Comparator& c);
922
rewind(EdgeList * activeEdges,Vertex ** current,Vertex * dst,Comparator & c)923 void rewind(EdgeList* activeEdges, Vertex** current, Vertex* dst, Comparator& c) {
924 if (!current || *current == dst || c.sweep_lt((*current)->fPoint, dst->fPoint)) {
925 return;
926 }
927 Vertex* v = *current;
928 LOG("rewinding active edges from vertex %g to vertex %g\n", v->fID, dst->fID);
929 while (v != dst) {
930 v = v->fPrev;
931 for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
932 remove_edge(e, activeEdges);
933 }
934 Edge* leftEdge = v->fLeftEnclosingEdge;
935 for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
936 insert_edge(e, leftEdge, activeEdges);
937 leftEdge = e;
938 }
939 }
940 *current = v;
941 }
942
rewind_if_necessary(Edge * edge,EdgeList * activeEdges,Vertex ** current,Comparator & c)943 void rewind_if_necessary(Edge* edge, EdgeList* activeEdges, Vertex** current, Comparator& c) {
944 if (!activeEdges || !current) {
945 return;
946 }
947 Vertex* top = edge->fTop;
948 Vertex* bottom = edge->fBottom;
949 if (edge->fLeft) {
950 Vertex* leftTop = edge->fLeft->fTop;
951 Vertex* leftBottom = edge->fLeft->fBottom;
952 if (c.sweep_lt(leftTop->fPoint, top->fPoint) && !edge->fLeft->isLeftOf(top)) {
953 rewind(activeEdges, current, leftTop, c);
954 } else if (c.sweep_lt(top->fPoint, leftTop->fPoint) && !edge->isRightOf(leftTop)) {
955 rewind(activeEdges, current, top, c);
956 } else if (c.sweep_lt(bottom->fPoint, leftBottom->fPoint) &&
957 !edge->fLeft->isLeftOf(bottom)) {
958 rewind(activeEdges, current, leftTop, c);
959 } else if (c.sweep_lt(leftBottom->fPoint, bottom->fPoint) && !edge->isRightOf(leftBottom)) {
960 rewind(activeEdges, current, top, c);
961 }
962 }
963 if (edge->fRight) {
964 Vertex* rightTop = edge->fRight->fTop;
965 Vertex* rightBottom = edge->fRight->fBottom;
966 if (c.sweep_lt(rightTop->fPoint, top->fPoint) && !edge->fRight->isRightOf(top)) {
967 rewind(activeEdges, current, rightTop, c);
968 } else if (c.sweep_lt(top->fPoint, rightTop->fPoint) && !edge->isLeftOf(rightTop)) {
969 rewind(activeEdges, current, top, c);
970 } else if (c.sweep_lt(bottom->fPoint, rightBottom->fPoint) &&
971 !edge->fRight->isRightOf(bottom)) {
972 rewind(activeEdges, current, rightTop, c);
973 } else if (c.sweep_lt(rightBottom->fPoint, bottom->fPoint) &&
974 !edge->isLeftOf(rightBottom)) {
975 rewind(activeEdges, current, top, c);
976 }
977 }
978 }
979
set_top(Edge * edge,Vertex * v,EdgeList * activeEdges,Vertex ** current,Comparator & c)980 void set_top(Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current, Comparator& c) {
981 remove_edge_below(edge);
982 edge->fTop = v;
983 edge->recompute();
984 insert_edge_below(edge, v, c);
985 rewind_if_necessary(edge, activeEdges, current, c);
986 merge_collinear_edges(edge, activeEdges, current, c);
987 }
988
set_bottom(Edge * edge,Vertex * v,EdgeList * activeEdges,Vertex ** current,Comparator & c)989 void set_bottom(Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current, Comparator& c) {
990 remove_edge_above(edge);
991 edge->fBottom = v;
992 edge->recompute();
993 insert_edge_above(edge, v, c);
994 rewind_if_necessary(edge, activeEdges, current, c);
995 merge_collinear_edges(edge, activeEdges, current, c);
996 }
997
merge_edges_above(Edge * edge,Edge * other,EdgeList * activeEdges,Vertex ** current,Comparator & c)998 void merge_edges_above(Edge* edge, Edge* other, EdgeList* activeEdges, Vertex** current,
999 Comparator& c) {
1000 if (coincident(edge->fTop->fPoint, other->fTop->fPoint)) {
1001 LOG("merging coincident above edges (%g, %g) -> (%g, %g)\n",
1002 edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
1003 edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
1004 rewind(activeEdges, current, edge->fTop, c);
1005 other->fWinding += edge->fWinding;
1006 disconnect(edge);
1007 edge->fTop = edge->fBottom = nullptr;
1008 } else if (c.sweep_lt(edge->fTop->fPoint, other->fTop->fPoint)) {
1009 rewind(activeEdges, current, edge->fTop, c);
1010 other->fWinding += edge->fWinding;
1011 set_bottom(edge, other->fTop, activeEdges, current, c);
1012 } else {
1013 rewind(activeEdges, current, other->fTop, c);
1014 edge->fWinding += other->fWinding;
1015 set_bottom(other, edge->fTop, activeEdges, current, c);
1016 }
1017 }
1018
merge_edges_below(Edge * edge,Edge * other,EdgeList * activeEdges,Vertex ** current,Comparator & c)1019 void merge_edges_below(Edge* edge, Edge* other, EdgeList* activeEdges, Vertex** current,
1020 Comparator& c) {
1021 if (coincident(edge->fBottom->fPoint, other->fBottom->fPoint)) {
1022 LOG("merging coincident below edges (%g, %g) -> (%g, %g)\n",
1023 edge->fTop->fPoint.fX, edge->fTop->fPoint.fY,
1024 edge->fBottom->fPoint.fX, edge->fBottom->fPoint.fY);
1025 rewind(activeEdges, current, edge->fTop, c);
1026 other->fWinding += edge->fWinding;
1027 disconnect(edge);
1028 edge->fTop = edge->fBottom = nullptr;
1029 } else if (c.sweep_lt(edge->fBottom->fPoint, other->fBottom->fPoint)) {
1030 rewind(activeEdges, current, other->fTop, c);
1031 edge->fWinding += other->fWinding;
1032 set_top(other, edge->fBottom, activeEdges, current, c);
1033 } else {
1034 rewind(activeEdges, current, edge->fTop, c);
1035 other->fWinding += edge->fWinding;
1036 set_top(edge, other->fBottom, activeEdges, current, c);
1037 }
1038 }
1039
top_collinear(Edge * left,Edge * right)1040 bool top_collinear(Edge* left, Edge* right) {
1041 if (!left || !right) {
1042 return false;
1043 }
1044 return left->fTop->fPoint == right->fTop->fPoint ||
1045 !left->isLeftOf(right->fTop) || !right->isRightOf(left->fTop);
1046 }
1047
bottom_collinear(Edge * left,Edge * right)1048 bool bottom_collinear(Edge* left, Edge* right) {
1049 if (!left || !right) {
1050 return false;
1051 }
1052 return left->fBottom->fPoint == right->fBottom->fPoint ||
1053 !left->isLeftOf(right->fBottom) || !right->isRightOf(left->fBottom);
1054 }
1055
merge_collinear_edges(Edge * edge,EdgeList * activeEdges,Vertex ** current,Comparator & c)1056 void merge_collinear_edges(Edge* edge, EdgeList* activeEdges, Vertex** current, Comparator& c) {
1057 for (;;) {
1058 if (top_collinear(edge->fPrevEdgeAbove, edge)) {
1059 merge_edges_above(edge->fPrevEdgeAbove, edge, activeEdges, current, c);
1060 } else if (top_collinear(edge, edge->fNextEdgeAbove)) {
1061 merge_edges_above(edge->fNextEdgeAbove, edge, activeEdges, current, c);
1062 } else if (bottom_collinear(edge->fPrevEdgeBelow, edge)) {
1063 merge_edges_below(edge->fPrevEdgeBelow, edge, activeEdges, current, c);
1064 } else if (bottom_collinear(edge, edge->fNextEdgeBelow)) {
1065 merge_edges_below(edge->fNextEdgeBelow, edge, activeEdges, current, c);
1066 } else {
1067 break;
1068 }
1069 }
1070 SkASSERT(!top_collinear(edge->fPrevEdgeAbove, edge));
1071 SkASSERT(!top_collinear(edge, edge->fNextEdgeAbove));
1072 SkASSERT(!bottom_collinear(edge->fPrevEdgeBelow, edge));
1073 SkASSERT(!bottom_collinear(edge, edge->fNextEdgeBelow));
1074 }
1075
split_edge(Edge * edge,Vertex * v,EdgeList * activeEdges,Vertex ** current,Comparator & c,SkArenaAlloc & alloc)1076 bool split_edge(Edge* edge, Vertex* v, EdgeList* activeEdges, Vertex** current, Comparator& c,
1077 SkArenaAlloc& alloc) {
1078 if (!edge->fTop || !edge->fBottom || v == edge->fTop || v == edge->fBottom) {
1079 return false;
1080 }
1081 LOG("splitting edge (%g -> %g) at vertex %g (%g, %g)\n",
1082 edge->fTop->fID, edge->fBottom->fID,
1083 v->fID, v->fPoint.fX, v->fPoint.fY);
1084 Vertex* top;
1085 Vertex* bottom;
1086 int winding = edge->fWinding;
1087 if (c.sweep_lt(v->fPoint, edge->fTop->fPoint)) {
1088 top = v;
1089 bottom = edge->fTop;
1090 set_top(edge, v, activeEdges, current, c);
1091 } else if (c.sweep_lt(edge->fBottom->fPoint, v->fPoint)) {
1092 top = edge->fBottom;
1093 bottom = v;
1094 set_bottom(edge, v, activeEdges, current, c);
1095 } else {
1096 top = v;
1097 bottom = edge->fBottom;
1098 set_bottom(edge, v, activeEdges, current, c);
1099 }
1100 Edge* newEdge = alloc.make<Edge>(top, bottom, winding, edge->fType);
1101 insert_edge_below(newEdge, top, c);
1102 insert_edge_above(newEdge, bottom, c);
1103 merge_collinear_edges(newEdge, activeEdges, current, c);
1104 return true;
1105 }
1106
intersect_edge_pair(Edge * left,Edge * right,EdgeList * activeEdges,Vertex ** current,Comparator & c,SkArenaAlloc & alloc)1107 bool intersect_edge_pair(Edge* left, Edge* right, EdgeList* activeEdges, Vertex** current, Comparator& c, SkArenaAlloc& alloc) {
1108 if (!left->fTop || !left->fBottom || !right->fTop || !right->fBottom) {
1109 return false;
1110 }
1111 if (left->fTop == right->fTop || left->fBottom == right->fBottom) {
1112 return false;
1113 }
1114 if (c.sweep_lt(left->fTop->fPoint, right->fTop->fPoint)) {
1115 if (!left->isLeftOf(right->fTop)) {
1116 rewind(activeEdges, current, right->fTop, c);
1117 return split_edge(left, right->fTop, activeEdges, current, c, alloc);
1118 }
1119 } else {
1120 if (!right->isRightOf(left->fTop)) {
1121 rewind(activeEdges, current, left->fTop, c);
1122 return split_edge(right, left->fTop, activeEdges, current, c, alloc);
1123 }
1124 }
1125 if (c.sweep_lt(right->fBottom->fPoint, left->fBottom->fPoint)) {
1126 if (!left->isLeftOf(right->fBottom)) {
1127 rewind(activeEdges, current, right->fBottom, c);
1128 return split_edge(left, right->fBottom, activeEdges, current, c, alloc);
1129 }
1130 } else {
1131 if (!right->isRightOf(left->fBottom)) {
1132 rewind(activeEdges, current, left->fBottom, c);
1133 return split_edge(right, left->fBottom, activeEdges, current, c, alloc);
1134 }
1135 }
1136 return false;
1137 }
1138
connect(Vertex * prev,Vertex * next,Edge::Type type,Comparator & c,SkArenaAlloc & alloc,int winding_scale=1)1139 Edge* connect(Vertex* prev, Vertex* next, Edge::Type type, Comparator& c, SkArenaAlloc& alloc,
1140 int winding_scale = 1) {
1141 if (!prev || !next || prev->fPoint == next->fPoint) {
1142 return nullptr;
1143 }
1144 Edge* edge = new_edge(prev, next, type, c, alloc);
1145 insert_edge_below(edge, edge->fTop, c);
1146 insert_edge_above(edge, edge->fBottom, c);
1147 edge->fWinding *= winding_scale;
1148 merge_collinear_edges(edge, nullptr, nullptr, c);
1149 return edge;
1150 }
1151
merge_vertices(Vertex * src,Vertex * dst,VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)1152 void merge_vertices(Vertex* src, Vertex* dst, VertexList* mesh, Comparator& c,
1153 SkArenaAlloc& alloc) {
1154 LOG("found coincident verts at %g, %g; merging %g into %g\n", src->fPoint.fX, src->fPoint.fY,
1155 src->fID, dst->fID);
1156 dst->fAlpha = SkTMax(src->fAlpha, dst->fAlpha);
1157 if (src->fPartner) {
1158 src->fPartner->fPartner = dst;
1159 }
1160 while (Edge* edge = src->fFirstEdgeAbove) {
1161 set_bottom(edge, dst, nullptr, nullptr, c);
1162 }
1163 while (Edge* edge = src->fFirstEdgeBelow) {
1164 set_top(edge, dst, nullptr, nullptr, c);
1165 }
1166 mesh->remove(src);
1167 }
1168
create_sorted_vertex(const SkPoint & p,uint8_t alpha,VertexList * mesh,Vertex * reference,Comparator & c,SkArenaAlloc & alloc)1169 Vertex* create_sorted_vertex(const SkPoint& p, uint8_t alpha, VertexList* mesh,
1170 Vertex* reference, Comparator& c, SkArenaAlloc& alloc) {
1171 Vertex* prevV = reference;
1172 while (prevV && c.sweep_lt(p, prevV->fPoint)) {
1173 prevV = prevV->fPrev;
1174 }
1175 Vertex* nextV = prevV ? prevV->fNext : mesh->fHead;
1176 while (nextV && c.sweep_lt(nextV->fPoint, p)) {
1177 prevV = nextV;
1178 nextV = nextV->fNext;
1179 }
1180 Vertex* v;
1181 if (prevV && coincident(prevV->fPoint, p)) {
1182 v = prevV;
1183 } else if (nextV && coincident(nextV->fPoint, p)) {
1184 v = nextV;
1185 } else {
1186 v = alloc.make<Vertex>(p, alpha);
1187 #if LOGGING_ENABLED
1188 if (!prevV) {
1189 v->fID = mesh->fHead->fID - 1.0f;
1190 } else if (!nextV) {
1191 v->fID = mesh->fTail->fID + 1.0f;
1192 } else {
1193 v->fID = (prevV->fID + nextV->fID) * 0.5f;
1194 }
1195 #endif
1196 mesh->insert(v, prevV, nextV);
1197 }
1198 return v;
1199 }
1200
1201 // If an edge's top and bottom points differ only by 1/2 machine epsilon in the primary
1202 // sort criterion, it may not be possible to split correctly, since there is no point which is
1203 // below the top and above the bottom. This function detects that case.
nearly_flat(Comparator & c,Edge * edge)1204 bool nearly_flat(Comparator& c, Edge* edge) {
1205 SkPoint diff = edge->fBottom->fPoint - edge->fTop->fPoint;
1206 float primaryDiff = c.fDirection == Comparator::Direction::kHorizontal ? diff.fX : diff.fY;
1207 return fabs(primaryDiff) < std::numeric_limits<float>::epsilon() && primaryDiff != 0.0f;
1208 }
1209
clamp(SkPoint p,SkPoint min,SkPoint max,Comparator & c)1210 SkPoint clamp(SkPoint p, SkPoint min, SkPoint max, Comparator& c) {
1211 if (c.sweep_lt(p, min)) {
1212 return min;
1213 } else if (c.sweep_lt(max, p)) {
1214 return max;
1215 } else {
1216 return p;
1217 }
1218 }
1219
check_for_intersection(Edge * left,Edge * right,EdgeList * activeEdges,Vertex ** current,VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)1220 bool check_for_intersection(Edge* left, Edge* right, EdgeList* activeEdges, Vertex** current,
1221 VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1222 if (!left || !right) {
1223 return false;
1224 }
1225 SkPoint p;
1226 uint8_t alpha;
1227 if (left->intersect(*right, &p, &alpha) && p.isFinite()) {
1228 Vertex* v;
1229 LOG("found intersection, pt is %g, %g\n", p.fX, p.fY);
1230 Vertex* top = *current;
1231 // If the intersection point is above the current vertex, rewind to the vertex above the
1232 // intersection.
1233 while (top && c.sweep_lt(p, top->fPoint)) {
1234 top = top->fPrev;
1235 }
1236 if (!nearly_flat(c, left)) {
1237 p = clamp(p, left->fTop->fPoint, left->fBottom->fPoint, c);
1238 }
1239 if (!nearly_flat(c, right)) {
1240 p = clamp(p, right->fTop->fPoint, right->fBottom->fPoint, c);
1241 }
1242 if (p == left->fTop->fPoint) {
1243 v = left->fTop;
1244 } else if (p == left->fBottom->fPoint) {
1245 v = left->fBottom;
1246 } else if (p == right->fTop->fPoint) {
1247 v = right->fTop;
1248 } else if (p == right->fBottom->fPoint) {
1249 v = right->fBottom;
1250 } else {
1251 v = create_sorted_vertex(p, alpha, mesh, top, c, alloc);
1252 if (left->fTop->fPartner) {
1253 Line line1 = left->fLine;
1254 Line line2 = right->fLine;
1255 int dir = left->fType == Edge::Type::kOuter ? -1 : 1;
1256 line1.fC += sqrt(left->fLine.magSq()) * (left->fWinding > 0 ? 1 : -1) * dir;
1257 line2.fC += sqrt(right->fLine.magSq()) * (right->fWinding > 0 ? 1 : -1) * dir;
1258 SkPoint p;
1259 if (line1.intersect(line2, &p)) {
1260 LOG("synthesizing partner (%g,%g) for intersection vertex %g\n",
1261 p.fX, p.fY, v->fID);
1262 v->fPartner = alloc.make<Vertex>(p, 255 - v->fAlpha);
1263 }
1264 }
1265 }
1266 rewind(activeEdges, current, top ? top : v, c);
1267 split_edge(left, v, activeEdges, current, c, alloc);
1268 split_edge(right, v, activeEdges, current, c, alloc);
1269 v->fAlpha = SkTMax(v->fAlpha, alpha);
1270 return true;
1271 }
1272 return intersect_edge_pair(left, right, activeEdges, current, c, alloc);
1273 }
1274
sanitize_contours(VertexList * contours,int contourCnt,bool approximate)1275 void sanitize_contours(VertexList* contours, int contourCnt, bool approximate) {
1276 for (VertexList* contour = contours; contourCnt > 0; --contourCnt, ++contour) {
1277 SkASSERT(contour->fHead);
1278 Vertex* prev = contour->fTail;
1279 if (approximate) {
1280 round(&prev->fPoint);
1281 }
1282 for (Vertex* v = contour->fHead; v;) {
1283 if (approximate) {
1284 round(&v->fPoint);
1285 }
1286 Vertex* next = v->fNext;
1287 Vertex* nextWrap = next ? next : contour->fHead;
1288 if (coincident(prev->fPoint, v->fPoint)) {
1289 LOG("vertex %g,%g coincident; removing\n", v->fPoint.fX, v->fPoint.fY);
1290 contour->remove(v);
1291 } else if (!v->fPoint.isFinite()) {
1292 LOG("vertex %g,%g non-finite; removing\n", v->fPoint.fX, v->fPoint.fY);
1293 contour->remove(v);
1294 } else if (Line(prev->fPoint, nextWrap->fPoint).dist(v->fPoint) == 0.0) {
1295 LOG("vertex %g,%g collinear; removing\n", v->fPoint.fX, v->fPoint.fY);
1296 contour->remove(v);
1297 } else {
1298 prev = v;
1299 }
1300 v = next;
1301 }
1302 }
1303 }
1304
merge_coincident_vertices(VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)1305 bool merge_coincident_vertices(VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1306 if (!mesh->fHead) {
1307 return false;
1308 }
1309 bool merged = false;
1310 for (Vertex* v = mesh->fHead->fNext; v;) {
1311 Vertex* next = v->fNext;
1312 if (c.sweep_lt(v->fPoint, v->fPrev->fPoint)) {
1313 v->fPoint = v->fPrev->fPoint;
1314 }
1315 if (coincident(v->fPrev->fPoint, v->fPoint)) {
1316 merge_vertices(v, v->fPrev, mesh, c, alloc);
1317 merged = true;
1318 }
1319 v = next;
1320 }
1321 return merged;
1322 }
1323
1324 // Stage 2: convert the contours to a mesh of edges connecting the vertices.
1325
build_edges(VertexList * contours,int contourCnt,VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)1326 void build_edges(VertexList* contours, int contourCnt, VertexList* mesh, Comparator& c,
1327 SkArenaAlloc& alloc) {
1328 for (VertexList* contour = contours; contourCnt > 0; --contourCnt, ++contour) {
1329 Vertex* prev = contour->fTail;
1330 for (Vertex* v = contour->fHead; v;) {
1331 Vertex* next = v->fNext;
1332 connect(prev, v, Edge::Type::kInner, c, alloc);
1333 mesh->append(v);
1334 prev = v;
1335 v = next;
1336 }
1337 }
1338 }
1339
connect_partners(VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)1340 void connect_partners(VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1341 for (Vertex* outer = mesh->fHead; outer; outer = outer->fNext) {
1342 if (Vertex* inner = outer->fPartner) {
1343 if ((inner->fPrev || inner->fNext) && (outer->fPrev || outer->fNext)) {
1344 // Connector edges get zero winding, since they're only structural (i.e., to ensure
1345 // no 0-0-0 alpha triangles are produced), and shouldn't affect the poly winding
1346 // number.
1347 connect(outer, inner, Edge::Type::kConnector, c, alloc, 0);
1348 inner->fPartner = outer->fPartner = nullptr;
1349 }
1350 }
1351 }
1352 }
1353
1354 template <CompareFunc sweep_lt>
sorted_merge(VertexList * front,VertexList * back,VertexList * result)1355 void sorted_merge(VertexList* front, VertexList* back, VertexList* result) {
1356 Vertex* a = front->fHead;
1357 Vertex* b = back->fHead;
1358 while (a && b) {
1359 if (sweep_lt(a->fPoint, b->fPoint)) {
1360 front->remove(a);
1361 result->append(a);
1362 a = front->fHead;
1363 } else {
1364 back->remove(b);
1365 result->append(b);
1366 b = back->fHead;
1367 }
1368 }
1369 result->append(*front);
1370 result->append(*back);
1371 }
1372
sorted_merge(VertexList * front,VertexList * back,VertexList * result,Comparator & c)1373 void sorted_merge(VertexList* front, VertexList* back, VertexList* result, Comparator& c) {
1374 if (c.fDirection == Comparator::Direction::kHorizontal) {
1375 sorted_merge<sweep_lt_horiz>(front, back, result);
1376 } else {
1377 sorted_merge<sweep_lt_vert>(front, back, result);
1378 }
1379 #if LOGGING_ENABLED
1380 float id = 0.0f;
1381 for (Vertex* v = result->fHead; v; v = v->fNext) {
1382 v->fID = id++;
1383 }
1384 #endif
1385 }
1386
1387 // Stage 3: sort the vertices by increasing sweep direction.
1388
1389 template <CompareFunc sweep_lt>
merge_sort(VertexList * vertices)1390 void merge_sort(VertexList* vertices) {
1391 Vertex* slow = vertices->fHead;
1392 if (!slow) {
1393 return;
1394 }
1395 Vertex* fast = slow->fNext;
1396 if (!fast) {
1397 return;
1398 }
1399 do {
1400 fast = fast->fNext;
1401 if (fast) {
1402 fast = fast->fNext;
1403 slow = slow->fNext;
1404 }
1405 } while (fast);
1406 VertexList front(vertices->fHead, slow);
1407 VertexList back(slow->fNext, vertices->fTail);
1408 front.fTail->fNext = back.fHead->fPrev = nullptr;
1409
1410 merge_sort<sweep_lt>(&front);
1411 merge_sort<sweep_lt>(&back);
1412
1413 vertices->fHead = vertices->fTail = nullptr;
1414 sorted_merge<sweep_lt>(&front, &back, vertices);
1415 }
1416
dump_mesh(const VertexList & mesh)1417 void dump_mesh(const VertexList& mesh) {
1418 #if LOGGING_ENABLED
1419 for (Vertex* v = mesh.fHead; v; v = v->fNext) {
1420 LOG("vertex %g (%g, %g) alpha %d", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1421 if (Vertex* p = v->fPartner) {
1422 LOG(", partner %g (%g, %g) alpha %d\n", p->fID, p->fPoint.fX, p->fPoint.fY, p->fAlpha);
1423 } else {
1424 LOG(", null partner\n");
1425 }
1426 for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1427 LOG(" edge %g -> %g, winding %d\n", e->fTop->fID, e->fBottom->fID, e->fWinding);
1428 }
1429 for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1430 LOG(" edge %g -> %g, winding %d\n", e->fTop->fID, e->fBottom->fID, e->fWinding);
1431 }
1432 }
1433 #endif
1434 }
1435
1436 #ifdef SK_DEBUG
validate_edge_pair(Edge * left,Edge * right,Comparator & c)1437 void validate_edge_pair(Edge* left, Edge* right, Comparator& c) {
1438 if (!left || !right) {
1439 return;
1440 }
1441 if (left->fTop == right->fTop) {
1442 SkASSERT(left->isLeftOf(right->fBottom));
1443 SkASSERT(right->isRightOf(left->fBottom));
1444 } else if (c.sweep_lt(left->fTop->fPoint, right->fTop->fPoint)) {
1445 SkASSERT(left->isLeftOf(right->fTop));
1446 } else {
1447 SkASSERT(right->isRightOf(left->fTop));
1448 }
1449 if (left->fBottom == right->fBottom) {
1450 SkASSERT(left->isLeftOf(right->fTop));
1451 SkASSERT(right->isRightOf(left->fTop));
1452 } else if (c.sweep_lt(right->fBottom->fPoint, left->fBottom->fPoint)) {
1453 SkASSERT(left->isLeftOf(right->fBottom));
1454 } else {
1455 SkASSERT(right->isRightOf(left->fBottom));
1456 }
1457 }
1458
validate_edge_list(EdgeList * edges,Comparator & c)1459 void validate_edge_list(EdgeList* edges, Comparator& c) {
1460 Edge* left = edges->fHead;
1461 if (!left) {
1462 return;
1463 }
1464 for (Edge* right = left->fRight; right; right = right->fRight) {
1465 validate_edge_pair(left, right, c);
1466 left = right;
1467 }
1468 }
1469 #endif
1470
1471 // Stage 4: Simplify the mesh by inserting new vertices at intersecting edges.
1472
simplify(VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)1473 bool simplify(VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1474 LOG("simplifying complex polygons\n");
1475 EdgeList activeEdges;
1476 bool found = false;
1477 for (Vertex* v = mesh->fHead; v != nullptr; v = v->fNext) {
1478 if (!v->fFirstEdgeAbove && !v->fFirstEdgeBelow) {
1479 continue;
1480 }
1481 Edge* leftEnclosingEdge;
1482 Edge* rightEnclosingEdge;
1483 bool restartChecks;
1484 do {
1485 LOG("\nvertex %g: (%g,%g), alpha %d\n", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1486 restartChecks = false;
1487 find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1488 v->fLeftEnclosingEdge = leftEnclosingEdge;
1489 v->fRightEnclosingEdge = rightEnclosingEdge;
1490 if (v->fFirstEdgeBelow) {
1491 for (Edge* edge = v->fFirstEdgeBelow; edge; edge = edge->fNextEdgeBelow) {
1492 if (check_for_intersection(leftEnclosingEdge, edge, &activeEdges, &v, mesh, c,
1493 alloc)) {
1494 restartChecks = true;
1495 break;
1496 }
1497 if (check_for_intersection(edge, rightEnclosingEdge, &activeEdges, &v, mesh, c,
1498 alloc)) {
1499 restartChecks = true;
1500 break;
1501 }
1502 }
1503 } else {
1504 if (check_for_intersection(leftEnclosingEdge, rightEnclosingEdge,
1505 &activeEdges, &v, mesh, c, alloc)) {
1506 restartChecks = true;
1507 }
1508
1509 }
1510 found = found || restartChecks;
1511 } while (restartChecks);
1512 #ifdef SK_DEBUG
1513 validate_edge_list(&activeEdges, c);
1514 #endif
1515 for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1516 remove_edge(e, &activeEdges);
1517 }
1518 Edge* leftEdge = leftEnclosingEdge;
1519 for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1520 insert_edge(e, leftEdge, &activeEdges);
1521 leftEdge = e;
1522 }
1523 }
1524 SkASSERT(!activeEdges.fHead && !activeEdges.fTail);
1525 return found;
1526 }
1527
1528 // Stage 5: Tessellate the simplified mesh into monotone polygons.
1529
tessellate(const VertexList & vertices,SkArenaAlloc & alloc)1530 Poly* tessellate(const VertexList& vertices, SkArenaAlloc& alloc) {
1531 LOG("\ntessellating simple polygons\n");
1532 EdgeList activeEdges;
1533 Poly* polys = nullptr;
1534 for (Vertex* v = vertices.fHead; v != nullptr; v = v->fNext) {
1535 if (!v->fFirstEdgeAbove && !v->fFirstEdgeBelow) {
1536 continue;
1537 }
1538 #if LOGGING_ENABLED
1539 LOG("\nvertex %g: (%g,%g), alpha %d\n", v->fID, v->fPoint.fX, v->fPoint.fY, v->fAlpha);
1540 #endif
1541 Edge* leftEnclosingEdge;
1542 Edge* rightEnclosingEdge;
1543 find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1544 Poly* leftPoly;
1545 Poly* rightPoly;
1546 if (v->fFirstEdgeAbove) {
1547 leftPoly = v->fFirstEdgeAbove->fLeftPoly;
1548 rightPoly = v->fLastEdgeAbove->fRightPoly;
1549 } else {
1550 leftPoly = leftEnclosingEdge ? leftEnclosingEdge->fRightPoly : nullptr;
1551 rightPoly = rightEnclosingEdge ? rightEnclosingEdge->fLeftPoly : nullptr;
1552 }
1553 #if LOGGING_ENABLED
1554 LOG("edges above:\n");
1555 for (Edge* e = v->fFirstEdgeAbove; e; e = e->fNextEdgeAbove) {
1556 LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1557 e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1558 }
1559 LOG("edges below:\n");
1560 for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1561 LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1562 e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1563 }
1564 #endif
1565 if (v->fFirstEdgeAbove) {
1566 if (leftPoly) {
1567 leftPoly = leftPoly->addEdge(v->fFirstEdgeAbove, Poly::kRight_Side, alloc);
1568 }
1569 if (rightPoly) {
1570 rightPoly = rightPoly->addEdge(v->fLastEdgeAbove, Poly::kLeft_Side, alloc);
1571 }
1572 for (Edge* e = v->fFirstEdgeAbove; e != v->fLastEdgeAbove; e = e->fNextEdgeAbove) {
1573 Edge* rightEdge = e->fNextEdgeAbove;
1574 remove_edge(e, &activeEdges);
1575 if (e->fRightPoly) {
1576 e->fRightPoly->addEdge(e, Poly::kLeft_Side, alloc);
1577 }
1578 if (rightEdge->fLeftPoly && rightEdge->fLeftPoly != e->fRightPoly) {
1579 rightEdge->fLeftPoly->addEdge(e, Poly::kRight_Side, alloc);
1580 }
1581 }
1582 remove_edge(v->fLastEdgeAbove, &activeEdges);
1583 if (!v->fFirstEdgeBelow) {
1584 if (leftPoly && rightPoly && leftPoly != rightPoly) {
1585 SkASSERT(leftPoly->fPartner == nullptr && rightPoly->fPartner == nullptr);
1586 rightPoly->fPartner = leftPoly;
1587 leftPoly->fPartner = rightPoly;
1588 }
1589 }
1590 }
1591 if (v->fFirstEdgeBelow) {
1592 if (!v->fFirstEdgeAbove) {
1593 if (leftPoly && rightPoly) {
1594 if (leftPoly == rightPoly) {
1595 if (leftPoly->fTail && leftPoly->fTail->fSide == Poly::kLeft_Side) {
1596 leftPoly = new_poly(&polys, leftPoly->lastVertex(),
1597 leftPoly->fWinding, alloc);
1598 leftEnclosingEdge->fRightPoly = leftPoly;
1599 } else {
1600 rightPoly = new_poly(&polys, rightPoly->lastVertex(),
1601 rightPoly->fWinding, alloc);
1602 rightEnclosingEdge->fLeftPoly = rightPoly;
1603 }
1604 }
1605 Edge* join = alloc.make<Edge>(leftPoly->lastVertex(), v, 1, Edge::Type::kInner);
1606 leftPoly = leftPoly->addEdge(join, Poly::kRight_Side, alloc);
1607 rightPoly = rightPoly->addEdge(join, Poly::kLeft_Side, alloc);
1608 }
1609 }
1610 Edge* leftEdge = v->fFirstEdgeBelow;
1611 leftEdge->fLeftPoly = leftPoly;
1612 insert_edge(leftEdge, leftEnclosingEdge, &activeEdges);
1613 for (Edge* rightEdge = leftEdge->fNextEdgeBelow; rightEdge;
1614 rightEdge = rightEdge->fNextEdgeBelow) {
1615 insert_edge(rightEdge, leftEdge, &activeEdges);
1616 int winding = leftEdge->fLeftPoly ? leftEdge->fLeftPoly->fWinding : 0;
1617 winding += leftEdge->fWinding;
1618 if (winding != 0) {
1619 Poly* poly = new_poly(&polys, v, winding, alloc);
1620 leftEdge->fRightPoly = rightEdge->fLeftPoly = poly;
1621 }
1622 leftEdge = rightEdge;
1623 }
1624 v->fLastEdgeBelow->fRightPoly = rightPoly;
1625 }
1626 #if LOGGING_ENABLED
1627 LOG("\nactive edges:\n");
1628 for (Edge* e = activeEdges.fHead; e != nullptr; e = e->fRight) {
1629 LOG("%g -> %g, lpoly %d, rpoly %d\n", e->fTop->fID, e->fBottom->fID,
1630 e->fLeftPoly ? e->fLeftPoly->fID : -1, e->fRightPoly ? e->fRightPoly->fID : -1);
1631 }
1632 #endif
1633 }
1634 return polys;
1635 }
1636
remove_non_boundary_edges(const VertexList & mesh,SkPath::FillType fillType,SkArenaAlloc & alloc)1637 void remove_non_boundary_edges(const VertexList& mesh, SkPath::FillType fillType,
1638 SkArenaAlloc& alloc) {
1639 LOG("removing non-boundary edges\n");
1640 EdgeList activeEdges;
1641 for (Vertex* v = mesh.fHead; v != nullptr; v = v->fNext) {
1642 if (!v->fFirstEdgeAbove && !v->fFirstEdgeBelow) {
1643 continue;
1644 }
1645 Edge* leftEnclosingEdge;
1646 Edge* rightEnclosingEdge;
1647 find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1648 bool prevFilled = leftEnclosingEdge &&
1649 apply_fill_type(fillType, leftEnclosingEdge->fWinding);
1650 for (Edge* e = v->fFirstEdgeAbove; e;) {
1651 Edge* next = e->fNextEdgeAbove;
1652 remove_edge(e, &activeEdges);
1653 bool filled = apply_fill_type(fillType, e->fWinding);
1654 if (filled == prevFilled) {
1655 disconnect(e);
1656 }
1657 prevFilled = filled;
1658 e = next;
1659 }
1660 Edge* prev = leftEnclosingEdge;
1661 for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1662 if (prev) {
1663 e->fWinding += prev->fWinding;
1664 }
1665 insert_edge(e, prev, &activeEdges);
1666 prev = e;
1667 }
1668 }
1669 }
1670
1671 // Note: this is the normal to the edge, but not necessarily unit length.
get_edge_normal(const Edge * e,SkVector * normal)1672 void get_edge_normal(const Edge* e, SkVector* normal) {
1673 normal->set(SkDoubleToScalar(e->fLine.fA),
1674 SkDoubleToScalar(e->fLine.fB));
1675 }
1676
reconnect(Edge * edge,Vertex * src,Vertex * dst,Comparator & c)1677 void reconnect(Edge* edge, Vertex* src, Vertex* dst, Comparator& c) {
1678 disconnect(edge);
1679 if (src == edge->fTop) {
1680 edge->fTop = dst;
1681 } else {
1682 SkASSERT(src == edge->fBottom);
1683 edge->fBottom = dst;
1684 }
1685 if (edge->fEvent) {
1686 edge->fEvent->fEdge = nullptr;
1687 }
1688 if (edge->fTop == edge->fBottom) {
1689 return;
1690 }
1691 if (c.sweep_lt(edge->fBottom->fPoint, edge->fTop->fPoint)) {
1692 using std::swap;
1693 swap(edge->fTop, edge->fBottom);
1694 edge->fWinding *= -1;
1695 }
1696 edge->recompute();
1697 insert_edge_below(edge, edge->fTop, c);
1698 insert_edge_above(edge, edge->fBottom, c);
1699 merge_collinear_edges(edge, nullptr, nullptr, c);
1700 }
1701
1702 // Stage 5c: detect and remove "pointy" vertices whose edge normals point in opposite directions
1703 // and whose adjacent vertices are less than a quarter pixel from an edge. These are guaranteed to
1704 // invert on stroking.
1705
simplify_boundary(EdgeList * boundary,Comparator & c,SkArenaAlloc & alloc)1706 void simplify_boundary(EdgeList* boundary, Comparator& c, SkArenaAlloc& alloc) {
1707 Edge* prevEdge = boundary->fTail;
1708 SkVector prevNormal;
1709 get_edge_normal(prevEdge, &prevNormal);
1710 for (Edge* e = boundary->fHead; e != nullptr;) {
1711 Vertex* prev = prevEdge->fWinding == 1 ? prevEdge->fTop : prevEdge->fBottom;
1712 Vertex* next = e->fWinding == 1 ? e->fBottom : e->fTop;
1713 double distPrev = e->dist(prev->fPoint);
1714 double distNext = prevEdge->dist(next->fPoint);
1715 SkVector normal;
1716 get_edge_normal(e, &normal);
1717 constexpr double kQuarterPixelSq = 0.25f * 0.25f;
1718 if (prev != next && prevNormal.dot(normal) < 0.0 &&
1719 (distPrev * distPrev <= kQuarterPixelSq || distNext * distNext <= kQuarterPixelSq)) {
1720 Edge* join = new_edge(prev, next, Edge::Type::kInner, c, alloc);
1721 if (prev->fPoint != next->fPoint) {
1722 join->fLine.normalize();
1723 join->fLine = join->fLine * join->fWinding;
1724 }
1725 insert_edge(join, e, boundary);
1726 remove_edge(prevEdge, boundary);
1727 remove_edge(e, boundary);
1728 if (join->fLeft && join->fRight) {
1729 prevEdge = join->fLeft;
1730 e = join;
1731 } else {
1732 prevEdge = boundary->fTail;
1733 e = boundary->fHead; // join->fLeft ? join->fLeft : join;
1734 }
1735 get_edge_normal(prevEdge, &prevNormal);
1736 } else {
1737 prevEdge = e;
1738 prevNormal = normal;
1739 e = e->fRight;
1740 }
1741 }
1742 }
1743
reconnect_all_overlap_edges(Vertex * src,Vertex * dst,Edge * current,Comparator & c)1744 void reconnect_all_overlap_edges(Vertex* src, Vertex* dst, Edge* current, Comparator& c) {
1745 if (src->fPartner) {
1746 src->fPartner->fPartner = dst;
1747 }
1748 for (Edge* e = src->fFirstEdgeAbove; e; ) {
1749 Edge* next = e->fNextEdgeAbove;
1750 if (e->fOverlap && e != current) {
1751 reconnect(e, src, dst, c);
1752 }
1753 e = next;
1754 }
1755 for (Edge* e = src->fFirstEdgeBelow; e; ) {
1756 Edge* next = e->fNextEdgeBelow;
1757 if (e->fOverlap && e != current) {
1758 reconnect(e, src, dst, c);
1759 }
1760 e = next;
1761 }
1762 }
1763
apply(VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)1764 void Event::apply(VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1765 if (!fEdge || !fEdge->fTop || !fEdge->fBottom) {
1766 return;
1767 }
1768 Vertex* top = fEdge->fTop;
1769 Vertex* bottom = fEdge->fBottom;
1770 Vertex* dest = create_sorted_vertex(fPoint, fAlpha, mesh, fEdge->fTop, c, alloc);
1771 LOG("collapsing edge %g -> %g to %g (%g, %g) alpha %d\n",
1772 top->fID, bottom->fID, dest->fID, fPoint.fX, fPoint.fY, fAlpha);
1773 reconnect_all_overlap_edges(top, dest, fEdge, c);
1774 reconnect_all_overlap_edges(bottom, dest, fEdge, c);
1775
1776 // Since the destination has multiple partners, give it none.
1777 dest->fPartner = nullptr;
1778
1779 // Disconnect all collapsed edges except outer boundaries.
1780 // Those are required to preserve shape coverage and winding correctness.
1781 if (!fIsOuterBoundary) {
1782 disconnect(fEdge);
1783 } else {
1784 LOG("edge %g -> %g is outer boundary; not disconnecting.\n",
1785 fEdge->fTop->fID, fEdge->fBottom->fID);
1786 fEdge->fWinding = fEdge->fWinding >= 0 ? 1 : -1;
1787 }
1788
1789 // If top still has some connected edges, set its partner to dest.
1790 top->fPartner = top->fFirstEdgeAbove || top->fFirstEdgeBelow ? dest : nullptr;
1791
1792 // If bottom still has some connected edges, set its partner to dest.
1793 bottom->fPartner = bottom->fFirstEdgeAbove || bottom->fFirstEdgeBelow ? dest : nullptr;
1794 }
1795
is_overlap_edge(Edge * e)1796 bool is_overlap_edge(Edge* e) {
1797 if (e->fType == Edge::Type::kOuter) {
1798 return e->fWinding != 0 && e->fWinding != 1;
1799 } else if (e->fType == Edge::Type::kInner) {
1800 return e->fWinding != 0 && e->fWinding != -2;
1801 } else {
1802 return false;
1803 }
1804 }
1805
1806 // This is a stripped-down version of tessellate() which computes edges which
1807 // join two filled regions, which represent overlap regions, and collapses them.
collapse_overlap_regions(VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)1808 bool collapse_overlap_regions(VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
1809 LOG("\nfinding overlap regions\n");
1810 EdgeList activeEdges;
1811 EventList events;
1812 for (Vertex* v = mesh->fHead; v != nullptr; v = v->fNext) {
1813 if (!v->fFirstEdgeAbove && !v->fFirstEdgeBelow) {
1814 continue;
1815 }
1816 Edge* leftEnclosingEdge;
1817 Edge* rightEnclosingEdge;
1818 find_enclosing_edges(v, &activeEdges, &leftEnclosingEdge, &rightEnclosingEdge);
1819 for (Edge* e = v->fLastEdgeAbove; e; e = e->fPrevEdgeAbove) {
1820 Edge* prev = e->fPrevEdgeAbove ? e->fPrevEdgeAbove : leftEnclosingEdge;
1821 remove_edge(e, &activeEdges);
1822 if (prev) {
1823 e->fWinding -= prev->fWinding;
1824 }
1825 }
1826 Edge* prev = leftEnclosingEdge;
1827 for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
1828 if (prev) {
1829 e->fWinding += prev->fWinding;
1830 e->fOverlap = e->fOverlap || is_overlap_edge(prev);
1831 }
1832 e->fOverlap = e->fOverlap || is_overlap_edge(e);
1833 if (e->fOverlap) {
1834 // If this edge borders a zero-winding area, it's a boundary; don't disconnect it.
1835 bool isOuterBoundary = e->fType == Edge::Type::kOuter &&
1836 (!prev || prev->fWinding == 0 || e->fWinding == 0);
1837 create_event(e, isOuterBoundary, &events, alloc);
1838 }
1839 insert_edge(e, prev, &activeEdges);
1840 prev = e;
1841 }
1842 }
1843 LOG("\ncollapsing overlap regions\n");
1844 if (events.count() == 0) {
1845 return false;
1846 }
1847 while (events.count() > 0) {
1848 Event* event = events.peek();
1849 events.pop();
1850 event->apply(mesh, c, alloc);
1851 }
1852 return true;
1853 }
1854
inversion(Vertex * prev,Vertex * next,Edge * origEdge,Comparator & c)1855 bool inversion(Vertex* prev, Vertex* next, Edge* origEdge, Comparator& c) {
1856 if (!prev || !next) {
1857 return true;
1858 }
1859 int winding = c.sweep_lt(prev->fPoint, next->fPoint) ? 1 : -1;
1860 return winding != origEdge->fWinding;
1861 }
1862
1863 // Stage 5d: Displace edges by half a pixel inward and outward along their normals. Intersect to
1864 // find new vertices, and set zero alpha on the exterior and one alpha on the interior. Build a
1865 // new antialiased mesh from those vertices.
1866
stroke_boundary(EdgeList * boundary,VertexList * innerMesh,VertexList * outerMesh,Comparator & c,SkArenaAlloc & alloc)1867 void stroke_boundary(EdgeList* boundary, VertexList* innerMesh, VertexList* outerMesh,
1868 Comparator& c, SkArenaAlloc& alloc) {
1869 LOG("\nstroking boundary\n");
1870 // A boundary with fewer than 3 edges is degenerate.
1871 if (!boundary->fHead || !boundary->fHead->fRight || !boundary->fHead->fRight->fRight) {
1872 return;
1873 }
1874 Edge* prevEdge = boundary->fTail;
1875 Vertex* prevV = prevEdge->fWinding > 0 ? prevEdge->fTop : prevEdge->fBottom;
1876 SkVector prevNormal;
1877 get_edge_normal(prevEdge, &prevNormal);
1878 double radius = 0.5;
1879 Line prevInner(prevEdge->fLine);
1880 prevInner.fC -= radius;
1881 Line prevOuter(prevEdge->fLine);
1882 prevOuter.fC += radius;
1883 VertexList innerVertices;
1884 VertexList outerVertices;
1885 bool innerInversion = true;
1886 bool outerInversion = true;
1887 for (Edge* e = boundary->fHead; e != nullptr; e = e->fRight) {
1888 Vertex* v = e->fWinding > 0 ? e->fTop : e->fBottom;
1889 SkVector normal;
1890 get_edge_normal(e, &normal);
1891 Line inner(e->fLine);
1892 inner.fC -= radius;
1893 Line outer(e->fLine);
1894 outer.fC += radius;
1895 SkPoint innerPoint, outerPoint;
1896 LOG("stroking vertex %g (%g, %g)\n", v->fID, v->fPoint.fX, v->fPoint.fY);
1897 if (!prevEdge->fLine.nearParallel(e->fLine) && prevInner.intersect(inner, &innerPoint) &&
1898 prevOuter.intersect(outer, &outerPoint)) {
1899 float cosAngle = normal.dot(prevNormal);
1900 if (cosAngle < -kCosMiterAngle) {
1901 Vertex* nextV = e->fWinding > 0 ? e->fBottom : e->fTop;
1902
1903 // This is a pointy vertex whose angle is smaller than the threshold; miter it.
1904 Line bisector(innerPoint, outerPoint);
1905 Line tangent(v->fPoint, v->fPoint + SkPoint::Make(bisector.fA, bisector.fB));
1906 if (tangent.fA == 0 && tangent.fB == 0) {
1907 continue;
1908 }
1909 tangent.normalize();
1910 Line innerTangent(tangent);
1911 Line outerTangent(tangent);
1912 innerTangent.fC -= 0.5;
1913 outerTangent.fC += 0.5;
1914 SkPoint innerPoint1, innerPoint2, outerPoint1, outerPoint2;
1915 if (prevNormal.cross(normal) > 0) {
1916 // Miter inner points
1917 if (!innerTangent.intersect(prevInner, &innerPoint1) ||
1918 !innerTangent.intersect(inner, &innerPoint2) ||
1919 !outerTangent.intersect(bisector, &outerPoint)) {
1920 continue;
1921 }
1922 Line prevTangent(prevV->fPoint,
1923 prevV->fPoint + SkVector::Make(prevOuter.fA, prevOuter.fB));
1924 Line nextTangent(nextV->fPoint,
1925 nextV->fPoint + SkVector::Make(outer.fA, outer.fB));
1926 if (prevTangent.dist(outerPoint) > 0) {
1927 bisector.intersect(prevTangent, &outerPoint);
1928 }
1929 if (nextTangent.dist(outerPoint) < 0) {
1930 bisector.intersect(nextTangent, &outerPoint);
1931 }
1932 outerPoint1 = outerPoint2 = outerPoint;
1933 } else {
1934 // Miter outer points
1935 if (!outerTangent.intersect(prevOuter, &outerPoint1) ||
1936 !outerTangent.intersect(outer, &outerPoint2)) {
1937 continue;
1938 }
1939 Line prevTangent(prevV->fPoint,
1940 prevV->fPoint + SkVector::Make(prevInner.fA, prevInner.fB));
1941 Line nextTangent(nextV->fPoint,
1942 nextV->fPoint + SkVector::Make(inner.fA, inner.fB));
1943 if (prevTangent.dist(innerPoint) > 0) {
1944 bisector.intersect(prevTangent, &innerPoint);
1945 }
1946 if (nextTangent.dist(innerPoint) < 0) {
1947 bisector.intersect(nextTangent, &innerPoint);
1948 }
1949 innerPoint1 = innerPoint2 = innerPoint;
1950 }
1951 if (!innerPoint1.isFinite() || !innerPoint2.isFinite() ||
1952 !outerPoint1.isFinite() || !outerPoint2.isFinite()) {
1953 continue;
1954 }
1955 LOG("inner (%g, %g), (%g, %g), ",
1956 innerPoint1.fX, innerPoint1.fY, innerPoint2.fX, innerPoint2.fY);
1957 LOG("outer (%g, %g), (%g, %g)\n",
1958 outerPoint1.fX, outerPoint1.fY, outerPoint2.fX, outerPoint2.fY);
1959 Vertex* innerVertex1 = alloc.make<Vertex>(innerPoint1, 255);
1960 Vertex* innerVertex2 = alloc.make<Vertex>(innerPoint2, 255);
1961 Vertex* outerVertex1 = alloc.make<Vertex>(outerPoint1, 0);
1962 Vertex* outerVertex2 = alloc.make<Vertex>(outerPoint2, 0);
1963 innerVertex1->fPartner = outerVertex1;
1964 innerVertex2->fPartner = outerVertex2;
1965 outerVertex1->fPartner = innerVertex1;
1966 outerVertex2->fPartner = innerVertex2;
1967 if (!inversion(innerVertices.fTail, innerVertex1, prevEdge, c)) {
1968 innerInversion = false;
1969 }
1970 if (!inversion(outerVertices.fTail, outerVertex1, prevEdge, c)) {
1971 outerInversion = false;
1972 }
1973 innerVertices.append(innerVertex1);
1974 innerVertices.append(innerVertex2);
1975 outerVertices.append(outerVertex1);
1976 outerVertices.append(outerVertex2);
1977 } else {
1978 LOG("inner (%g, %g), ", innerPoint.fX, innerPoint.fY);
1979 LOG("outer (%g, %g)\n", outerPoint.fX, outerPoint.fY);
1980 Vertex* innerVertex = alloc.make<Vertex>(innerPoint, 255);
1981 Vertex* outerVertex = alloc.make<Vertex>(outerPoint, 0);
1982 innerVertex->fPartner = outerVertex;
1983 outerVertex->fPartner = innerVertex;
1984 if (!inversion(innerVertices.fTail, innerVertex, prevEdge, c)) {
1985 innerInversion = false;
1986 }
1987 if (!inversion(outerVertices.fTail, outerVertex, prevEdge, c)) {
1988 outerInversion = false;
1989 }
1990 innerVertices.append(innerVertex);
1991 outerVertices.append(outerVertex);
1992 }
1993 }
1994 prevInner = inner;
1995 prevOuter = outer;
1996 prevV = v;
1997 prevEdge = e;
1998 prevNormal = normal;
1999 }
2000 if (!inversion(innerVertices.fTail, innerVertices.fHead, prevEdge, c)) {
2001 innerInversion = false;
2002 }
2003 if (!inversion(outerVertices.fTail, outerVertices.fHead, prevEdge, c)) {
2004 outerInversion = false;
2005 }
2006 // Outer edges get 1 winding, and inner edges get -2 winding. This ensures that the interior
2007 // is always filled (1 + -2 = -1 for normal cases, 1 + 2 = 3 for thin features where the
2008 // interior inverts).
2009 // For total inversion cases, the shape has now reversed handedness, so invert the winding
2010 // so it will be detected during collapse_overlap_regions().
2011 int innerWinding = innerInversion ? 2 : -2;
2012 int outerWinding = outerInversion ? -1 : 1;
2013 for (Vertex* v = innerVertices.fHead; v && v->fNext; v = v->fNext) {
2014 connect(v, v->fNext, Edge::Type::kInner, c, alloc, innerWinding);
2015 }
2016 connect(innerVertices.fTail, innerVertices.fHead, Edge::Type::kInner, c, alloc, innerWinding);
2017 for (Vertex* v = outerVertices.fHead; v && v->fNext; v = v->fNext) {
2018 connect(v, v->fNext, Edge::Type::kOuter, c, alloc, outerWinding);
2019 }
2020 connect(outerVertices.fTail, outerVertices.fHead, Edge::Type::kOuter, c, alloc, outerWinding);
2021 innerMesh->append(innerVertices);
2022 outerMesh->append(outerVertices);
2023 }
2024
extract_boundary(EdgeList * boundary,Edge * e,SkPath::FillType fillType,SkArenaAlloc & alloc)2025 void extract_boundary(EdgeList* boundary, Edge* e, SkPath::FillType fillType, SkArenaAlloc& alloc) {
2026 LOG("\nextracting boundary\n");
2027 bool down = apply_fill_type(fillType, e->fWinding);
2028 while (e) {
2029 e->fWinding = down ? 1 : -1;
2030 Edge* next;
2031 e->fLine.normalize();
2032 e->fLine = e->fLine * e->fWinding;
2033 boundary->append(e);
2034 if (down) {
2035 // Find outgoing edge, in clockwise order.
2036 if ((next = e->fNextEdgeAbove)) {
2037 down = false;
2038 } else if ((next = e->fBottom->fLastEdgeBelow)) {
2039 down = true;
2040 } else if ((next = e->fPrevEdgeAbove)) {
2041 down = false;
2042 }
2043 } else {
2044 // Find outgoing edge, in counter-clockwise order.
2045 if ((next = e->fPrevEdgeBelow)) {
2046 down = true;
2047 } else if ((next = e->fTop->fFirstEdgeAbove)) {
2048 down = false;
2049 } else if ((next = e->fNextEdgeBelow)) {
2050 down = true;
2051 }
2052 }
2053 disconnect(e);
2054 e = next;
2055 }
2056 }
2057
2058 // Stage 5b: Extract boundaries from mesh, simplify and stroke them into a new mesh.
2059
extract_boundaries(const VertexList & inMesh,VertexList * innerVertices,VertexList * outerVertices,SkPath::FillType fillType,Comparator & c,SkArenaAlloc & alloc)2060 void extract_boundaries(const VertexList& inMesh, VertexList* innerVertices,
2061 VertexList* outerVertices, SkPath::FillType fillType,
2062 Comparator& c, SkArenaAlloc& alloc) {
2063 remove_non_boundary_edges(inMesh, fillType, alloc);
2064 for (Vertex* v = inMesh.fHead; v; v = v->fNext) {
2065 while (v->fFirstEdgeBelow) {
2066 EdgeList boundary;
2067 extract_boundary(&boundary, v->fFirstEdgeBelow, fillType, alloc);
2068 simplify_boundary(&boundary, c, alloc);
2069 stroke_boundary(&boundary, innerVertices, outerVertices, c, alloc);
2070 }
2071 }
2072 }
2073
2074 // This is a driver function that calls stages 2-5 in turn.
2075
contours_to_mesh(VertexList * contours,int contourCnt,bool antialias,VertexList * mesh,Comparator & c,SkArenaAlloc & alloc)2076 void contours_to_mesh(VertexList* contours, int contourCnt, bool antialias,
2077 VertexList* mesh, Comparator& c, SkArenaAlloc& alloc) {
2078 #if LOGGING_ENABLED
2079 for (int i = 0; i < contourCnt; ++i) {
2080 Vertex* v = contours[i].fHead;
2081 SkASSERT(v);
2082 LOG("path.moveTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
2083 for (v = v->fNext; v; v = v->fNext) {
2084 LOG("path.lineTo(%20.20g, %20.20g);\n", v->fPoint.fX, v->fPoint.fY);
2085 }
2086 }
2087 #endif
2088 sanitize_contours(contours, contourCnt, antialias);
2089 build_edges(contours, contourCnt, mesh, c, alloc);
2090 }
2091
sort_mesh(VertexList * vertices,Comparator & c,SkArenaAlloc & alloc)2092 void sort_mesh(VertexList* vertices, Comparator& c, SkArenaAlloc& alloc) {
2093 if (!vertices || !vertices->fHead) {
2094 return;
2095 }
2096
2097 // Sort vertices in Y (secondarily in X).
2098 if (c.fDirection == Comparator::Direction::kHorizontal) {
2099 merge_sort<sweep_lt_horiz>(vertices);
2100 } else {
2101 merge_sort<sweep_lt_vert>(vertices);
2102 }
2103 #if LOGGING_ENABLED
2104 for (Vertex* v = vertices->fHead; v != nullptr; v = v->fNext) {
2105 static float gID = 0.0f;
2106 v->fID = gID++;
2107 }
2108 #endif
2109 }
2110
contours_to_polys(VertexList * contours,int contourCnt,SkPath::FillType fillType,const SkRect & pathBounds,bool antialias,VertexList * outerMesh,SkArenaAlloc & alloc)2111 Poly* contours_to_polys(VertexList* contours, int contourCnt, SkPath::FillType fillType,
2112 const SkRect& pathBounds, bool antialias, VertexList* outerMesh,
2113 SkArenaAlloc& alloc) {
2114 Comparator c(pathBounds.width() > pathBounds.height() ? Comparator::Direction::kHorizontal
2115 : Comparator::Direction::kVertical);
2116 VertexList mesh;
2117 contours_to_mesh(contours, contourCnt, antialias, &mesh, c, alloc);
2118 sort_mesh(&mesh, c, alloc);
2119 merge_coincident_vertices(&mesh, c, alloc);
2120 simplify(&mesh, c, alloc);
2121 if (antialias) {
2122 VertexList innerMesh;
2123 extract_boundaries(mesh, &innerMesh, outerMesh, fillType, c, alloc);
2124 sort_mesh(&innerMesh, c, alloc);
2125 sort_mesh(outerMesh, c, alloc);
2126 merge_coincident_vertices(&innerMesh, c, alloc);
2127 bool was_complex = merge_coincident_vertices(outerMesh, c, alloc);
2128 was_complex = simplify(&innerMesh, c, alloc) || was_complex;
2129 was_complex = simplify(outerMesh, c, alloc) || was_complex;
2130 LOG("\ninner mesh before:\n");
2131 dump_mesh(innerMesh);
2132 LOG("\nouter mesh before:\n");
2133 dump_mesh(*outerMesh);
2134 was_complex = collapse_overlap_regions(&innerMesh, c, alloc) || was_complex;
2135 was_complex = collapse_overlap_regions(outerMesh, c, alloc) || was_complex;
2136 if (was_complex) {
2137 LOG("found complex mesh; taking slow path\n");
2138 VertexList aaMesh;
2139 LOG("\ninner mesh after:\n");
2140 dump_mesh(innerMesh);
2141 LOG("\nouter mesh after:\n");
2142 dump_mesh(*outerMesh);
2143 connect_partners(outerMesh, c, alloc);
2144 connect_partners(&innerMesh, c, alloc);
2145 sorted_merge(&innerMesh, outerMesh, &aaMesh, c);
2146 merge_coincident_vertices(&aaMesh, c, alloc);
2147 simplify(&aaMesh, c, alloc);
2148 dump_mesh(aaMesh);
2149 outerMesh->fHead = outerMesh->fTail = nullptr;
2150 return tessellate(aaMesh, alloc);
2151 } else {
2152 LOG("no complex polygons; taking fast path\n");
2153 return tessellate(innerMesh, alloc);
2154 }
2155 } else {
2156 return tessellate(mesh, alloc);
2157 }
2158 }
2159
2160 // Stage 6: Triangulate the monotone polygons into a vertex buffer.
polys_to_triangles(Poly * polys,SkPath::FillType fillType,bool emitCoverage,void * data)2161 void* polys_to_triangles(Poly* polys, SkPath::FillType fillType, bool emitCoverage, void* data) {
2162 for (Poly* poly = polys; poly; poly = poly->fNext) {
2163 if (apply_fill_type(fillType, poly)) {
2164 data = poly->emit(emitCoverage, data);
2165 }
2166 }
2167 return data;
2168 }
2169
path_to_polys(const SkPath & path,SkScalar tolerance,const SkRect & clipBounds,int contourCnt,SkArenaAlloc & alloc,bool antialias,bool * isLinear,VertexList * outerMesh)2170 Poly* path_to_polys(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
2171 int contourCnt, SkArenaAlloc& alloc, bool antialias, bool* isLinear,
2172 VertexList* outerMesh) {
2173 SkPath::FillType fillType = path.getFillType();
2174 if (SkPath::IsInverseFillType(fillType)) {
2175 contourCnt++;
2176 }
2177 std::unique_ptr<VertexList[]> contours(new VertexList[contourCnt]);
2178
2179 path_to_contours(path, tolerance, clipBounds, contours.get(), alloc, isLinear);
2180 return contours_to_polys(contours.get(), contourCnt, path.getFillType(), path.getBounds(),
2181 antialias, outerMesh, alloc);
2182 }
2183
get_contour_count(const SkPath & path,SkScalar tolerance)2184 int get_contour_count(const SkPath& path, SkScalar tolerance) {
2185 int contourCnt;
2186 int maxPts = GrPathUtils::worstCasePointCount(path, &contourCnt, tolerance);
2187 if (maxPts <= 0) {
2188 return 0;
2189 }
2190 return contourCnt;
2191 }
2192
count_points(Poly * polys,SkPath::FillType fillType)2193 int64_t count_points(Poly* polys, SkPath::FillType fillType) {
2194 int64_t count = 0;
2195 for (Poly* poly = polys; poly; poly = poly->fNext) {
2196 if (apply_fill_type(fillType, poly) && poly->fCount >= 3) {
2197 count += (poly->fCount - 2) * (TESSELLATOR_WIREFRAME ? 6 : 3);
2198 }
2199 }
2200 return count;
2201 }
2202
count_outer_mesh_points(const VertexList & outerMesh)2203 int64_t count_outer_mesh_points(const VertexList& outerMesh) {
2204 int64_t count = 0;
2205 for (Vertex* v = outerMesh.fHead; v; v = v->fNext) {
2206 for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
2207 count += TESSELLATOR_WIREFRAME ? 12 : 6;
2208 }
2209 }
2210 return count;
2211 }
2212
outer_mesh_to_triangles(const VertexList & outerMesh,bool emitCoverage,void * data)2213 void* outer_mesh_to_triangles(const VertexList& outerMesh, bool emitCoverage, void* data) {
2214 for (Vertex* v = outerMesh.fHead; v; v = v->fNext) {
2215 for (Edge* e = v->fFirstEdgeBelow; e; e = e->fNextEdgeBelow) {
2216 Vertex* v0 = e->fTop;
2217 Vertex* v1 = e->fBottom;
2218 Vertex* v2 = e->fBottom->fPartner;
2219 Vertex* v3 = e->fTop->fPartner;
2220 data = emit_triangle(v0, v1, v2, emitCoverage, data);
2221 data = emit_triangle(v0, v2, v3, emitCoverage, data);
2222 }
2223 }
2224 return data;
2225 }
2226
2227 } // namespace
2228
2229 namespace GrTessellator {
2230
2231 // Stage 6: Triangulate the monotone polygons into a vertex buffer.
2232
PathToTriangles(const SkPath & path,SkScalar tolerance,const SkRect & clipBounds,VertexAllocator * vertexAllocator,bool antialias,bool * isLinear)2233 int PathToTriangles(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
2234 VertexAllocator* vertexAllocator, bool antialias, bool* isLinear) {
2235 int contourCnt = get_contour_count(path, tolerance);
2236 if (contourCnt <= 0) {
2237 *isLinear = true;
2238 return 0;
2239 }
2240 SkArenaAlloc alloc(kArenaChunkSize);
2241 VertexList outerMesh;
2242 Poly* polys = path_to_polys(path, tolerance, clipBounds, contourCnt, alloc, antialias,
2243 isLinear, &outerMesh);
2244 SkPath::FillType fillType = antialias ? SkPath::kWinding_FillType : path.getFillType();
2245 int64_t count64 = count_points(polys, fillType);
2246 if (antialias) {
2247 count64 += count_outer_mesh_points(outerMesh);
2248 }
2249 if (0 == count64 || count64 > SK_MaxS32) {
2250 return 0;
2251 }
2252 int count = count64;
2253
2254 void* verts = vertexAllocator->lock(count);
2255 if (!verts) {
2256 SkDebugf("Could not allocate vertices\n");
2257 return 0;
2258 }
2259
2260 LOG("emitting %d verts\n", count);
2261 void* end = polys_to_triangles(polys, fillType, antialias, verts);
2262 end = outer_mesh_to_triangles(outerMesh, true, end);
2263
2264 int actualCount = static_cast<int>((static_cast<uint8_t*>(end) - static_cast<uint8_t*>(verts))
2265 / vertexAllocator->stride());
2266 SkASSERT(actualCount <= count);
2267 vertexAllocator->unlock(actualCount);
2268 return actualCount;
2269 }
2270
PathToVertices(const SkPath & path,SkScalar tolerance,const SkRect & clipBounds,GrTessellator::WindingVertex ** verts)2271 int PathToVertices(const SkPath& path, SkScalar tolerance, const SkRect& clipBounds,
2272 GrTessellator::WindingVertex** verts) {
2273 int contourCnt = get_contour_count(path, tolerance);
2274 if (contourCnt <= 0) {
2275 *verts = nullptr;
2276 return 0;
2277 }
2278 SkArenaAlloc alloc(kArenaChunkSize);
2279 bool isLinear;
2280 Poly* polys = path_to_polys(path, tolerance, clipBounds, contourCnt, alloc, false, &isLinear,
2281 nullptr);
2282 SkPath::FillType fillType = path.getFillType();
2283 int64_t count64 = count_points(polys, fillType);
2284 if (0 == count64 || count64 > SK_MaxS32) {
2285 *verts = nullptr;
2286 return 0;
2287 }
2288 int count = count64;
2289
2290 *verts = new GrTessellator::WindingVertex[count];
2291 GrTessellator::WindingVertex* vertsEnd = *verts;
2292 SkPoint* points = new SkPoint[count];
2293 SkPoint* pointsEnd = points;
2294 for (Poly* poly = polys; poly; poly = poly->fNext) {
2295 if (apply_fill_type(fillType, poly)) {
2296 SkPoint* start = pointsEnd;
2297 pointsEnd = static_cast<SkPoint*>(poly->emit(false, pointsEnd));
2298 while (start != pointsEnd) {
2299 vertsEnd->fPos = *start;
2300 vertsEnd->fWinding = poly->fWinding;
2301 ++start;
2302 ++vertsEnd;
2303 }
2304 }
2305 }
2306 int actualCount = static_cast<int>(vertsEnd - *verts);
2307 SkASSERT(actualCount <= count);
2308 SkASSERT(pointsEnd - points == actualCount);
2309 delete[] points;
2310 return actualCount;
2311 }
2312
2313 } // namespace
2314