Debian Codegraph @

src/pathops/SkPathOpsAsWinding.cpp

raw
1 /*
2 * Copyright 2018 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 #include "include/core/SkPath.h"
8 #include "include/core/SkPathBuilder.h"
9 #include "include/core/SkPathTypes.h"
10 #include "include/core/SkPoint.h"
11 #include "include/core/SkRect.h"
12 #include "include/core/SkScalar.h"
13 #include "include/core/SkTypes.h"
14 #include "include/pathops/SkPathOps.h"
15 #include "include/private/base/SkMacros.h"
16 #include "src/core/SkPathPriv.h"
17 #include "src/pathops/SkPathOpsConic.h"
18 #include "src/pathops/SkPathOpsCubic.h"
19 #include "src/pathops/SkPathOpsCurve.h"
20 #include "src/pathops/SkPathOpsPoint.h"
21 #include "src/pathops/SkPathOpsQuad.h"
22 #include "src/pathops/SkPathOpsTypes.h"
23
24 #include <algorithm>
25 #include <vector>
26
27 using std::vector;
28
29 struct Contour {
30 enum class Direction { // SkPathDirection doesn't have 'none' state
31 kCCW = -1,
32 kNone,
33 kCW,
34 };
35
36 Contour(const SkRect& bounds, int lastStart, int verbStart)
37 : fBounds(bounds)
38 , fVerbStart(lastStart)
39 , fVerbEnd(verbStart) {
40 }
41
42 vector<Contour*> fChildren;
43 const SkRect fBounds;
44 SkPoint fMinXY{SK_ScalarMax, SK_ScalarMax};
45 const int fVerbStart;
46 const int fVerbEnd;
47 Direction fDirection{Direction::kNone};
48 bool fContained{false};
49 bool fReverse{false};
50 };
51
52 static unsigned VerbPtCount(SkPathVerb verb) {
53 static const uint8_t kPtCount[] = { 1, 1, 2, 2, 3, 0 };
54 unsigned index = static_cast<unsigned>(verb);
55 SkASSERT(index < std::size(kPtCount));
56 return kPtCount[index];
57 }
58
59 static int VerbPtIndex(SkPathVerb verb) {
60 static const int kPtIndex[] = { 0, 1, 1, 1, 1, 0 };
61 unsigned index = static_cast<unsigned>(verb);
62 SkASSERT(index < std::size(kPtIndex));
63 return kPtIndex[index];
64 }
65
66 static Contour::Direction to_direction(SkScalar dy) {
67 return dy > 0 ? Contour::Direction::kCCW : dy < 0 ? Contour::Direction::kCW :
68 Contour::Direction::kNone;
69 }
70
71 static int contains_edge(const SkPoint pts[4], SkPathVerb verb, SkScalar weight, const SkPoint& edge) {
72 SkRect bounds = SkRect::BoundsOrEmpty({pts, VerbPtCount(verb) + 1});
73 if (bounds.fTop > edge.fY) {
74 return 0;
75 }
76 if (bounds.fBottom <= edge.fY) { // check to see if y is at line end to avoid double counting
77 return 0;
78 }
79 if (bounds.fLeft >= edge.fX) {
80 return 0;
81 }
82 int winding = 0;
83 double tVals[3];
84 Contour::Direction directions[3];
85 // must intersect horz ray with curve in case it intersects more than once
86 int count = (*CurveIntercept[(int)verb * 2])(pts, weight, edge.fY, tVals);
87 SkASSERT(between(0, count, 3));
88 // remove results to the right of edge
89 for (int index = 0; index < count; ) {
90 SkScalar intersectX = (*CurvePointAtT[(int)verb])(pts, weight, tVals[index]).fX;
91 if (intersectX < edge.fX) {
92 ++index;
93 continue;
94 }
95 if (intersectX > edge.fX) {
96 tVals[index] = tVals[--count];
97 continue;
98 }
99 // if intersect x equals edge x, we need to determine if pts is to the left or right of edge
100 if (pts[0].fX < edge.fX && pts[VerbPtCount(verb)].fX < edge.fX) {
101 ++index;
102 continue;
103 }
104 // TODO : other cases need discriminating. need op angle code to figure it out
105 // example: edge ends 45 degree diagonal going up. If pts is to the left of edge, keep.
106 // if pts is to the right of edge, discard. With code as is, can't distiguish the two cases.
107 tVals[index] = tVals[--count];
108 }
109 // use first derivative to determine if intersection is contributing +1 or -1 to winding
110 for (int index = 0; index < count; ++index) {
111 directions[index] = to_direction((*CurveSlopeAtT[(int)verb])(pts, weight, tVals[index]).fY);
112 }
113 for (int index = 0; index < count; ++index) {
114 // skip intersections that end at edge and go up
115 if (zero_or_one(tVals[index]) && Contour::Direction::kCCW != directions[index]) {
116 continue;
117 }
118 winding += (int) directions[index];
119 }
120 return winding; // note winding indicates containership, not contour direction
121 }
122
123 static float conic_weight(const SkPath::IterRec& rec) {
124 return rec.fVerb == SkPathVerb::kConic ? rec.conicWeight() : 1;
125 }
126
127 static SkPoint left_edge(const SkPoint pts[4], SkPathVerb verb, SkScalar weight) {
128 SkASSERT(SkPathVerb::kLine <= verb && verb <= SkPathVerb::kCubic);
129 SkPoint result;
130 double t SK_INIT_TO_AVOID_WARNING;
131 int roots = 0;
132 if (SkPathVerb::kLine == verb) {
133 result = pts[0].fX < pts[1].fX ? pts[0] : pts[1];
134 } else if (SkPathVerb::kQuad == verb) {
135 SkDQuad quad;
136 quad.set(pts);
137 if (!quad.monotonicInX()) {
138 roots = SkDQuad::FindExtrema(&quad[0].fX, &t);
139 }
140 if (roots) {
141 result = quad.ptAtT(t).asSkPoint();
142 } else {
143 result = pts[0].fX < pts[2].fX ? pts[0] : pts[2];
144 }
145 } else if (SkPathVerb::kConic == verb) {
146 SkDConic conic;
147 conic.set(pts, weight);
148 if (!conic.monotonicInX()) {
149 roots = SkDConic::FindExtrema(&conic[0].fX, weight, &t);
150 }
151 if (roots) {
152 result = conic.ptAtT(t).asSkPoint();
153 } else {
154 result = pts[0].fX < pts[2].fX ? pts[0] : pts[2];
155 }
156 } else {
157 SkASSERT(SkPathVerb::kCubic == verb);
158 SkDCubic cubic;
159 cubic.set(pts);
160 if (!cubic.monotonicInX()) {
161 double tValues[2];
162 roots = SkDCubic::FindExtrema(&cubic[0].fX, tValues);
163 SkASSERT(roots <= 2);
164 for (int index = 0; index < roots; ++index) {
165 SkPoint temp = cubic.ptAtT(tValues[index]).asSkPoint();
166 if (0 == index || result.fX > temp.fX) {
167 result = temp;
168 }
169 }
170 }
171 if (roots) {
172 result = cubic.ptAtT(t).asSkPoint();
173 } else {
174 result = pts[0].fX < pts[3].fX ? pts[0] : pts[3];
175 }
176 }
177 return result;
178 }
179
180 class OpAsWinding {
181 public:
182 enum class Edge {
183 kInitial,
184 kCompare,
185 };
186
187 OpAsWinding(const SkPath& path)
188 : fPath(path) {
189 }
190
191 void contourBounds(vector<Contour>* containers) {
192 SkRect bounds;
193 bounds.setEmpty();
194 int lastStart = 0;
195 int verbStart = 0;
196 for (auto [verb, pts, w] : SkPathPriv::Iterate(fPath)) {
197 if (SkPathVerb::kMove == verb) {
198 if (!bounds.isEmpty()) {
199 containers->emplace_back(bounds, lastStart, verbStart);
200 lastStart = verbStart;
201 }
202 bounds.setBounds({&pts[VerbPtIndex(SkPathVerb::kMove)],
203 VerbPtCount(SkPathVerb::kMove)});
204 }
205 if (SkPathVerb::kLine <= verb && verb <= SkPathVerb::kCubic) {
206 SkRect verbBounds;
207 verbBounds.setBounds({&pts[VerbPtIndex(verb)], VerbPtCount(verb)});
208 bounds.joinPossiblyEmptyRect(verbBounds);
209 }
210 ++verbStart;
211 }
212 if (!bounds.isEmpty()) {
213 containers->emplace_back(bounds, lastStart, ++verbStart);
214 }
215 }
216
217 Contour::Direction getDirection(Contour& contour) {
218 SkPath::Iter iter(fPath, true);
219 int verbCount = -1;
220
221 SkScalar total_signed_area = 0;
222 while (auto rec = iter.next()) {
223 if (++verbCount < contour.fVerbStart) {
224 continue;
225 }
226 if (verbCount >= contour.fVerbEnd) {
227 continue;
228 }
229 if (SkPathVerb::kLine > rec->fVerb || rec->fVerb > SkPathVerb::kCubic) {
230 continue;
231 }
232
233 SkSpan<const SkPoint> pts = rec->fPoints;
234 switch (rec->fVerb) {
235 case SkPathVerb::kLine:
236 total_signed_area += (pts[0].fY - pts[1].fY) * (pts[0].fX + pts[1].fX);
237 break;
238 case SkPathVerb::kQuad:
239 case SkPathVerb::kConic:
240 total_signed_area += (pts[0].fY - pts[2].fY) * (pts[0].fX + pts[2].fX);
241 break;
242 case SkPathVerb::kCubic:
243 total_signed_area += (pts[0].fY - pts[3].fY) * (pts[0].fX + pts[3].fX);
244 break;
245 default:
246 break;
247 }
248 }
249
250 return total_signed_area < 0 ? Contour::Direction::kCCW: Contour::Direction::kCW;
251 }
252
253 int nextEdge(Contour& contour, Edge edge) {
254 SkPath::Iter iter(fPath, true);
255 int verbCount = -1;
256 int winding = 0;
257 while (auto rec = iter.next()) {
258 const SkPathVerb verb = rec->fVerb;
259 if (++verbCount < contour.fVerbStart) {
260 continue;
261 }
262 if (verbCount >= contour.fVerbEnd) {
263 continue;
264 }
265 if (SkPathVerb::kLine > verb || verb > SkPathVerb::kCubic) {
266 continue;
267 }
268
269 SkSpan<const SkPoint> pts = rec->fPoints;
270 bool horizontal = true;
271 for (size_t index = 1; index <= VerbPtCount(verb); ++index) {
272 if (pts[0].fY != pts[index].fY) {
273 horizontal = false;
274 break;
275 }
276 }
277 if (horizontal) {
278 continue;
279 }
280 if (edge == Edge::kCompare) {
281 winding += contains_edge(pts.data(), verb, conic_weight(*rec),
282 contour.fMinXY);
283 continue;
284 }
285 SkASSERT(edge == Edge::kInitial);
286 SkPoint minXY = left_edge(pts.data(), verb, conic_weight(*rec));
287 if (minXY.fX > contour.fMinXY.fX) {
288 continue;
289 }
290 if (minXY.fX == contour.fMinXY.fX) {
291 if (minXY.fY != contour.fMinXY.fY) {
292 continue;
293 }
294 }
295 contour.fMinXY = minXY;
296 }
297 return winding;
298 }
299
300 bool containerContains(Contour& contour, Contour& test) {
301 // find outside point on lesser contour
302 // arbitrarily, choose non-horizontal edge where point <= bounds left
303 // note that if leftmost point is control point, may need tight bounds
304 // to find edge with minimum-x
305 if (SK_ScalarMax == test.fMinXY.fX) {
306 this->nextEdge(test, Edge::kInitial);
307 }
308 // find all edges on greater equal or to the left of one on lesser
309 contour.fMinXY = test.fMinXY;
310 int winding = this->nextEdge(contour, Edge::kCompare);
311 // if edge is up, mark contour cw, otherwise, ccw
312 // sum of greater edges direction should be cw, 0, ccw
313 test.fContained = winding != 0;
314 return -1 <= winding && winding <= 1;
315 }
316
317 void inParent(Contour& contour, Contour& parent) {
318 // move contour into sibling list contained by parent
319 for (auto test : parent.fChildren) {
320 if (test->fBounds.contains(contour.fBounds)) {
321 inParent(contour, *test);
322 return;
323 }
324 }
325 // move parent's children into contour's children if contained by contour
326 for (auto iter = parent.fChildren.begin(); iter != parent.fChildren.end(); ) {
327 if (contour.fBounds.contains((*iter)->fBounds)) {
328 contour.fChildren.push_back(*iter);
329 iter = parent.fChildren.erase(iter);
330 continue;
331 }
332 ++iter;
333 }
334 parent.fChildren.push_back(&contour);
335 }
336
337 bool checkContainerChildren(Contour* parent, Contour* child) {
338 for (auto grandChild : child->fChildren) {
339 if (!checkContainerChildren(child, grandChild)) {
340 return false;
341 }
342 }
343 if (parent) {
344 if (!containerContains(*parent, *child)) {
345 return false;
346 }
347 }
348 return true;
349 }
350
351 bool markReverse(Contour* parent, Contour* child) {
352 bool reversed = false;
353 for (auto grandChild : child->fChildren) {
354 reversed |= markReverse(grandChild->fContained ? child : parent, grandChild);
355 }
356
357 child->fDirection = getDirection(*child);
358 if (parent && parent->fDirection == child->fDirection) {
359 child->fReverse = true;
360 child->fDirection = (Contour::Direction) -(int) child->fDirection;
361 return true;
362 }
363 return reversed;
364 }
365
366 SkPath reverseMarkedContours(vector<Contour>& contours, SkPathFillType fillType) {
367 SkPathPriv::Iterate iterate(fPath);
368 auto iter = iterate.begin();
369 int verbCount = 0;
370
371 SkPathBuilder result;
372 result.setFillType(fillType);
373 for (const Contour& contour : contours) {
374 SkPathBuilder reverse;
375 SkPathBuilder* temp = contour.fReverse ? &reverse : &result;
376 for (; iter != iterate.end() && verbCount < contour.fVerbEnd; ++iter, ++verbCount) {
377 auto [verb, pts, w] = *iter;
378 switch (verb) {
379 case SkPathVerb::kMove:
380 temp->moveTo(pts[0]);
381 break;
382 case SkPathVerb::kLine:
383 temp->lineTo(pts[1]);
384 break;
385 case SkPathVerb::kQuad:
386 temp->quadTo(pts[1], pts[2]);
387 break;
388 case SkPathVerb::kConic:
389 temp->conicTo(pts[1], pts[2], *w);
390 break;
391 case SkPathVerb::kCubic:
392 temp->cubicTo(pts[1], pts[2], pts[3]);
393 break;
394 case SkPathVerb::kClose:
395 temp->close();
396 break;
397 }
398 }
399 if (contour.fReverse) {
400 SkASSERT(temp == &reverse);
401 SkPathPriv::ReverseAddPath(&result, reverse.detach());
402 }
403 }
404 return result.detach();
405 }
406
407 private:
408 const SkPath& fPath;
409 };
410
411 std::optional<SkPath> AsWinding(const SkPath& path) {
412 if (!path.isFinite()) {
413 return {};
414 }
415 SkPathFillType fillType = path.getFillType();
416 if (fillType == SkPathFillType::kWinding
417 || fillType == SkPathFillType::kInverseWinding ) {
418 return path;
419 }
420 fillType = path.isInverseFillType() ? SkPathFillType::kInverseWinding :
421 SkPathFillType::kWinding;
422 if (path.isEmpty() || path.isConvex()) {
423 return path.makeFillType(fillType);
424 }
425 // count contours
426 vector<Contour> contours; // one per contour
427 OpAsWinding winder(path);
428 winder.contourBounds(&contours);
429 if (contours.size() <= 1) {
430 return path.makeFillType(fillType);
431 }
432 // create contour bounding box tree
433 Contour sorted(SkRect(), 0, 0);
434 for (auto& contour : contours) {
435 winder.inParent(contour, sorted);
436 }
437 // if sorted has no grandchildren, no child has to fix its children's winding
438 if (std::all_of(sorted.fChildren.begin(), sorted.fChildren.end(),
439 [](const Contour* contour) -> bool { return contour->fChildren.empty(); } )) {
440 return path.makeFillType(fillType);
441 }
442 // starting with outermost and moving inward, see if one path contains another
443 for (auto contour : sorted.fChildren) {
444 winder.nextEdge(*contour, OpAsWinding::Edge::kInitial);
445 contour->fDirection = winder.getDirection(*contour);
446 if (!winder.checkContainerChildren(nullptr, contour)) {
447 return {};
448 }
449 }
450 // starting with outermost and moving inward, mark paths to reverse
451 bool reversed = false;
452 for (auto contour : sorted.fChildren) {
453 reversed |= winder.markReverse(nullptr, contour);
454 }
455 if (!reversed) {
456 return path.makeFillType(fillType);
457 }
458 return winder.reverseMarkedContours(contours, fillType);
459 }