Debian Codegraph @

src/core/SkRegion_path.cpp

raw
1 /*
2 * Copyright 2006 The Android Open Source Project
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 "include/core/SkColor.h"
9 #include "include/core/SkMatrix.h"
10 #include "include/core/SkPath.h"
11 #include "include/core/SkPathBuilder.h"
12 #include "include/core/SkRect.h"
13 #include "include/core/SkRegion.h"
14 #include "include/core/SkScalar.h"
15 #include "include/core/SkTypes.h"
16 #include "include/private/base/SkDebug.h"
17 #include "include/private/base/SkMalloc.h"
18 #include "include/private/base/SkMath.h"
19 #include "include/private/base/SkPoint_impl.h"
20 #include "include/private/base/SkTDArray.h"
21 #include "include/private/base/SkTFitsIn.h"
22 #include "include/private/base/SkTo.h"
23 #include "src/base/SkSafeMath.h"
24 #include "src/base/SkTSort.h"
25 #include "src/core/SkBlitter.h"
26 #include "src/core/SkPathPriv.h"
27 #include "src/core/SkRegionPriv.h"
28 #include "src/core/SkScan.h"
29
30 #include <algorithm>
31 #include <cstdint>
32 #include <cstring>
33 #include <iterator>
34
35 // The rgnbuilder caller *seems* to pass short counts, possible often seens early failure, so
36 // we may not want to promote this to a "std" routine just yet.
37 static bool sk_memeq32(const int32_t* SK_RESTRICT a, const int32_t* SK_RESTRICT b, int count) {
38 for (int i = 0; i < count; ++i) {
39 if (a[i] != b[i]) {
40 return false;
41 }
42 }
43 return true;
44 }
45
46 class SkRgnBuilder : public SkBlitter {
47 public:
48 SkRgnBuilder();
49 ~SkRgnBuilder() override;
50
51 // returns true if it could allocate the working storage needed
52 bool init(int maxHeight, int maxTransitions, bool pathIsInverse);
53
54 void done() {
55 if (fCurrScanline != nullptr) {
56 fCurrScanline->fXCount = (SkRegion::RunType)((int)(fCurrXPtr - fCurrScanline->firstX()));
57 if (!this->collapsWithPrev()) { // flush the last line
58 fCurrScanline = fCurrScanline->nextScanline();
59 }
60 }
61 }
62
63 int computeRunCount() const;
64 void copyToRect(SkIRect*) const;
65 void copyToRgn(SkRegion::RunType runs[]) const;
66
67 void blitH(int x, int y, int width) override;
68 void blitAntiH(int x, int y, const SkAlpha antialias[], const int16_t runs[]) override {
69 SkDEBUGFAIL("blitAntiH not implemented");
70 }
71
72 #ifdef SK_DEBUG
73 void dump() const {
74 SkDebugf("SkRgnBuilder: Top = %d\n", fTop);
75 Scanline* line = (Scanline*)fStorage;
76 while (line < fCurrScanline) {
77 SkDebugf("SkRgnBuilder::Scanline: LastY=%d, fXCount=%d", line->fLastY, line->fXCount);
78 for (int i = 0; i < line->fXCount; i++) {
79 SkDebugf(" %d", line->firstX()[i]);
80 }
81 SkDebugf("\n");
82
83 line = line->nextScanline();
84 }
85 }
86 #endif
87 private:
88 /*
89 * Scanline mimics a row in the region, nearly. A row in a region is:
90 * [Bottom IntervalCount [L R]... Sentinel]
91 * while a Scanline is
92 * [LastY XCount [L R]... uninitialized]
93 * The two are the same length (which is good), but we have to transmute
94 * the scanline a little when we convert it to a region-row.
95 *
96 * Potentially we could recode this to exactly match the row format, in
97 * which case copyToRgn() could be a single memcpy. Not sure that is worth
98 * the effort.
99 */
100 struct Scanline {
101 SkRegion::RunType fLastY;
102 SkRegion::RunType fXCount;
103
104 SkRegion::RunType* firstX() { return (SkRegion::RunType*)(this + 1); }
105 Scanline* nextScanline() {
106 // add final +1 for the x-sentinel
107 return (Scanline*)((SkRegion::RunType*)(this + 1) + fXCount + 1);
108 }
109 };
110 SkRegion::RunType* fStorage;
111 Scanline* fCurrScanline;
112 Scanline* fPrevScanline;
113 // points at next avialable x[] in fCurrScanline
114 SkRegion::RunType* fCurrXPtr;
115 SkRegion::RunType fTop; // first Y value
116
117 int fStorageCount;
118
119 bool collapsWithPrev() {
120 if (fPrevScanline != nullptr &&
121 fPrevScanline->fLastY + 1 == fCurrScanline->fLastY &&
122 fPrevScanline->fXCount == fCurrScanline->fXCount &&
123 sk_memeq32(fPrevScanline->firstX(), fCurrScanline->firstX(), fCurrScanline->fXCount))
124 {
125 // update the height of fPrevScanline
126 fPrevScanline->fLastY = fCurrScanline->fLastY;
127 return true;
128 }
129 return false;
130 }
131 };
132
133 SkRgnBuilder::SkRgnBuilder()
134 : fStorage(nullptr) {
135 }
136
137 SkRgnBuilder::~SkRgnBuilder() {
138 sk_free(fStorage);
139 }
140
141 bool SkRgnBuilder::init(int maxHeight, int maxTransitions, bool pathIsInverse) {
142 if ((maxHeight | maxTransitions) < 0) {
143 return false;
144 }
145
146 SkSafeMath safe;
147
148 if (pathIsInverse) {
149 // allow for additional X transitions to "invert" each scanline
150 // [ L' ... normal transitions ... R' ]
151 //
152 maxTransitions = safe.addInt(maxTransitions, 2);
153 }
154
155 // compute the count with +1 and +3 slop for the working buffer
156 size_t count = safe.mul(safe.addInt(maxHeight, 1), safe.addInt(3, maxTransitions));
157
158 if (pathIsInverse) {
159 // allow for two "empty" rows for the top and bottom
160 // [ Y, 1, L, R, S] == 5 (*2 for top and bottom)
161 count = safe.add(count, 10);
162 }
163
164 if (!safe || !SkTFitsIn<int32_t>(count)) {
165 return false;
166 }
167 fStorageCount = SkToS32(count);
168
169 fStorage = (SkRegion::RunType*)sk_malloc_canfail(fStorageCount, sizeof(SkRegion::RunType));
170 if (nullptr == fStorage) {
171 return false;
172 }
173
174 fCurrScanline = nullptr; // signal empty collection
175 fPrevScanline = nullptr; // signal first scanline
176 return true;
177 }
178
179 void SkRgnBuilder::blitH(int x, int y, int width) {
180 if (fCurrScanline == nullptr) { // first time
181 fTop = (SkRegion::RunType)(y);
182 fCurrScanline = (Scanline*)fStorage;
183 fCurrScanline->fLastY = (SkRegion::RunType)(y);
184 fCurrXPtr = fCurrScanline->firstX();
185 } else {
186 SkASSERT(y >= fCurrScanline->fLastY);
187
188 if (y > fCurrScanline->fLastY) {
189 // if we get here, we're done with fCurrScanline
190 fCurrScanline->fXCount = (SkRegion::RunType)((int)(fCurrXPtr - fCurrScanline->firstX()));
191
192 int prevLastY = fCurrScanline->fLastY;
193 if (!this->collapsWithPrev()) {
194 fPrevScanline = fCurrScanline;
195 fCurrScanline = fCurrScanline->nextScanline();
196
197 }
198 if (y - 1 > prevLastY) { // insert empty run
199 fCurrScanline->fLastY = (SkRegion::RunType)(y - 1);
200 fCurrScanline->fXCount = 0;
201 fCurrScanline = fCurrScanline->nextScanline();
202 }
203 // setup for the new curr line
204 fCurrScanline->fLastY = (SkRegion::RunType)(y);
205 fCurrXPtr = fCurrScanline->firstX();
206 }
207 }
208 // check if we should extend the current run, or add a new one
209 if (fCurrXPtr > fCurrScanline->firstX() && fCurrXPtr[-1] == x) {
210 fCurrXPtr[-1] = (SkRegion::RunType)(x + width);
211 } else {
212 fCurrXPtr[0] = (SkRegion::RunType)(x);
213 fCurrXPtr[1] = (SkRegion::RunType)(x + width);
214 fCurrXPtr += 2;
215 }
216 SkASSERT(fCurrXPtr - fStorage < fStorageCount);
217 }
218
219 int SkRgnBuilder::computeRunCount() const {
220 if (fCurrScanline == nullptr) {
221 return 0;
222 }
223
224 const SkRegion::RunType* line = fStorage;
225 const SkRegion::RunType* stop = (const SkRegion::RunType*)fCurrScanline;
226
227 return 2 + (int)(stop - line);
228 }
229
230 void SkRgnBuilder::copyToRect(SkIRect* r) const {
231 SkASSERT(fCurrScanline != nullptr);
232 // A rect's scanline is [bottom intervals left right sentinel] == 5
233 SkASSERT((const SkRegion::RunType*)fCurrScanline - fStorage == 5);
234
235 Scanline* line = (Scanline*)fStorage;
236 SkASSERT(line->fXCount == 2);
237
238 r->setLTRB(line->firstX()[0], fTop, line->firstX()[1], line->fLastY + 1);
239 }
240
241 void SkRgnBuilder::copyToRgn(SkRegion::RunType runs[]) const {
242 SkASSERT(fCurrScanline != nullptr);
243 SkASSERT((const SkRegion::RunType*)fCurrScanline - fStorage > 4);
244
245 Scanline* line = (Scanline*)fStorage;
246 const Scanline* stop = fCurrScanline;
247
248 *runs++ = fTop;
249 do {
250 *runs++ = (SkRegion::RunType)(line->fLastY + 1);
251 int count = line->fXCount;
252 *runs++ = count >> 1; // intervalCount
253 if (count) {
254 memcpy(runs, line->firstX(), count * sizeof(SkRegion::RunType));
255 runs += count;
256 }
257 *runs++ = SkRegion_kRunTypeSentinel;
258 line = line->nextScanline();
259 } while (line < stop);
260 SkASSERT(line == stop);
261 *runs = SkRegion_kRunTypeSentinel;
262 }
263
264 static unsigned verb_to_initial_last_index(SkPathVerb verb) {
265 static const uint8_t gPathVerbToInitialLastIndex[] = {
266 0, // kMove_Verb
267 1, // kLine_Verb
268 2, // kQuad_Verb
269 2, // kConic_Verb
270 3, // kCubic_Verb
271 0, // kClose_Verb
272 };
273 const unsigned index = static_cast<unsigned>(verb);
274 SkASSERT(index < std::size(gPathVerbToInitialLastIndex));
275 return gPathVerbToInitialLastIndex[index];
276 }
277
278 static unsigned verb_to_max_edges(SkPathVerb verb) {
279 static const uint8_t gPathVerbToMaxEdges[] = {
280 0, // kMove_Verb
281 1, // kLine_Verb
282 2, // kQuad_VerbB
283 2, // kConic_VerbB
284 3, // kCubic_Verb
285 0, // kClose_Verb
286 };
287 const unsigned index = static_cast<unsigned>(verb);
288 SkASSERT(index < std::size(gPathVerbToMaxEdges));
289 return gPathVerbToMaxEdges[index];
290 }
291
292 // If returns 0, ignore itop and ibot
293 static int count_path_runtype_values(const SkPath& path, int* itop, int* ibot) {
294 int maxEdges = 0;
295 SkScalar top = SkIntToScalar(SK_MaxS16);
296 SkScalar bot = SkIntToScalar(SK_MinS16);
297
298 SkPath::Iter iter(path, true);
299 while (auto rec = iter.next()) {
300 const SkPathVerb verb = rec->fVerb;
301 const SkSpan<const SkPoint> pts = rec->fPoints;
302
303 maxEdges += verb_to_max_edges(verb);
304
305 int lastIndex = verb_to_initial_last_index(verb);
306 if (lastIndex > 0) {
307 for (int i = 1; i <= lastIndex; i++) {
308 if (top > pts[i].fY) {
309 top = pts[i].fY;
310 } else if (bot < pts[i].fY) {
311 bot = pts[i].fY;
312 }
313 }
314 } else if (SkPathVerb::kMove == verb) {
315 if (top > pts[0].fY) {
316 top = pts[0].fY;
317 } else if (bot < pts[0].fY) {
318 bot = pts[0].fY;
319 }
320 }
321 }
322 if (0 == maxEdges) {
323 return 0; // we have only moves+closes
324 }
325
326 SkASSERT(top <= bot);
327 *itop = SkScalarRoundToInt(top);
328 *ibot = SkScalarRoundToInt(bot);
329 return maxEdges;
330 }
331
332 static bool check_inverse_on_empty_return(SkRegion* dst, const SkPath& path, const SkRegion& clip) {
333 if (path.isInverseFillType()) {
334 return dst->set(clip);
335 } else {
336 return dst->setEmpty();
337 }
338 }
339
340 bool SkRegion::setPath(const SkPath& path, const SkRegion& clip) {
341 SkDEBUGCODE(SkRegionPriv::Validate(*this));
342
343 const auto raw = SkPathPriv::Raw(path, SkResolveConvexity::kYes);
344
345 if (clip.isEmpty() || !raw.has_value() || path.isEmpty()) {
346 // This treats non-finite paths (no raw) as empty as well, so this returns empty or 'clip'
347 // if it's inverse-filled. If clip is also empty, path's fill type doesn't really matter
348 // and this region ends up empty.
349 return check_inverse_on_empty_return(this, path, clip);
350 }
351
352 // Our builder is very fragile, and can't be called with spans/rects out of Y->X order.
353 // To ensure this, we only "fill" clipped to a rect (the clip's bounds), and if the
354 // clip is more complex than that, we just post-intersect the result with the clip.
355 const SkIRect clipBounds = clip.getBounds();
356 if (clip.isComplex()) {
357 if (!this->setPath(path, SkRegion(clipBounds))) {
358 return false;
359 }
360 return this->op(clip, kIntersect_Op);
361 }
362
363 // SkScan::FillPath has limits on the coordinate range of the clipping SkRegion. If it's too
364 // big, tile the clip bounds and union the pieces back together.
365 if (SkScan::PathRequiresTiling(clipBounds)) {
366 static constexpr int kTileSize = 32767 >> 1; // Limit so coords can fit into SkFixed (16.16)
367 const SkIRect pathBounds = path.getBounds().roundOut();
368
369 this->setEmpty();
370
371 // Note: With large integers some intermediate calculations can overflow, but the
372 // end results will still be in integer range. Using int64_t for the intermediate
373 // values will handle this situation.
374 for (int64_t top = clipBounds.fTop; top < clipBounds.fBottom; top += kTileSize) {
375 int64_t bot = std::min(top + kTileSize, (int64_t)clipBounds.fBottom);
376 for (int64_t left = clipBounds.fLeft; left < clipBounds.fRight; left += kTileSize) {
377 int64_t right = std::min(left + kTileSize, (int64_t)clipBounds.fRight);
378
379 SkIRect tileClipBounds = {(int)left, (int)top, (int)right, (int)bot};
380 if (!SkIRect::Intersects(pathBounds, tileClipBounds)) {
381 continue;
382 }
383
384 // Shift coordinates so the top left is (0,0) during scan conversion and then
385 // translate the SkRegion afterwards.
386 tileClipBounds.offset(-left, -top);
387 SkASSERT(!SkScan::PathRequiresTiling(tileClipBounds));
388 SkRegion tile;
389 if (auto newpath = path.tryMakeOffset(-left, -top)) {
390 tile.setPath(*newpath, SkRegion(tileClipBounds));
391 tile.translate(left, top);
392 this->op(tile, kUnion_Op);
393 } else {
394 return false;
395 }
396 }
397 }
398 // During tiling we only applied the bounds of the tile, now that we have a full SkRegion,
399 // apply the original clip.
400 return this->op(clip, kIntersect_Op);
401 }
402
403 // compute worst-case rgn-size for the path
404 int pathTop, pathBot;
405 int pathTransitions = count_path_runtype_values(path, &pathTop, &pathBot);
406 if (0 == pathTransitions) {
407 return check_inverse_on_empty_return(this, path, clip);
408 }
409
410 int clipTop, clipBot;
411 int clipTransitions = clip.count_runtype_values(&clipTop, &clipBot);
412
413 int top = std::max(pathTop, clipTop);
414 int bot = std::min(pathBot, clipBot);
415 if (top >= bot) {
416 return check_inverse_on_empty_return(this, path, clip);
417 }
418
419 SkRgnBuilder builder;
420
421 if (!builder.init(bot - top,
422 std::max(pathTransitions, clipTransitions),
423 path.isInverseFillType())) {
424 // can't allocate working space, so return false
425 return this->setEmpty();
426 }
427
428 SkScan::FillPath(*raw, clip, &builder);
429 builder.done();
430
431 int count = builder.computeRunCount();
432 if (count == 0) {
433 return this->setEmpty();
434 } else if (count == kRectRegionRuns) {
435 builder.copyToRect(&fBounds);
436 this->setRect(fBounds);
437 } else {
438 SkRegion tmp;
439
440 tmp.fRunHead = RunHead::Alloc(count);
441 builder.copyToRgn(tmp.fRunHead->writable_runs());
442 tmp.fRunHead->computeRunBounds(&tmp.fBounds);
443 this->swap(tmp);
444 }
445 SkDEBUGCODE(SkRegionPriv::Validate(*this));
446 return true;
447 }
448
449 /////////////////////////////////////////////////////////////////////////////////////////////////
450 /////////////////////////////////////////////////////////////////////////////////////////////////
451
452 struct Edge {
453 enum {
454 kY0Link = 0x01,
455 kY1Link = 0x02,
456
457 kCompleteLink = (kY0Link | kY1Link)
458 };
459
460 SkRegionPriv::RunType fX;
461 SkRegionPriv::RunType fY0, fY1;
462 uint8_t fFlags;
463 Edge* fNext;
464
465 void set(int x, int y0, int y1) {
466 SkASSERT(y0 != y1);
467
468 fX = (SkRegionPriv::RunType)(x);
469 fY0 = (SkRegionPriv::RunType)(y0);
470 fY1 = (SkRegionPriv::RunType)(y1);
471 fFlags = 0;
472 SkDEBUGCODE(fNext = nullptr;)
473 }
474
475 int top() const {
476 return std::min(fY0, fY1);
477 }
478 };
479
480 static void find_link(Edge* base, Edge* stop) {
481 SkASSERT(base < stop);
482
483 if (base->fFlags == Edge::kCompleteLink) {
484 SkASSERT(base->fNext);
485 return;
486 }
487
488 SkASSERT(base + 1 < stop);
489
490 int y0 = base->fY0;
491 int y1 = base->fY1;
492
493 Edge* e = base;
494 if ((base->fFlags & Edge::kY0Link) == 0) {
495 for (;;) {
496 e += 1;
497 if ((e->fFlags & Edge::kY1Link) == 0 && y0 == e->fY1) {
498 SkASSERT(nullptr == e->fNext);
499 e->fNext = base;
500 e->fFlags = SkToU8(e->fFlags | Edge::kY1Link);
501 break;
502 }
503 }
504 }
505
506 e = base;
507 if ((base->fFlags & Edge::kY1Link) == 0) {
508 for (;;) {
509 e += 1;
510 if ((e->fFlags & Edge::kY0Link) == 0 && y1 == e->fY0) {
511 SkASSERT(nullptr == base->fNext);
512 base->fNext = e;
513 e->fFlags = SkToU8(e->fFlags | Edge::kY0Link);
514 break;
515 }
516 }
517 }
518
519 base->fFlags = Edge::kCompleteLink;
520 }
521
522 static int extract_path(Edge* edge, Edge* stop, SkPathBuilder* builder) {
523 while (0 == edge->fFlags) {
524 edge++; // skip over "used" edges
525 }
526
527 SkASSERT(edge < stop);
528
529 Edge* base = edge;
530 Edge* prev = edge;
531 edge = edge->fNext;
532 SkASSERT(edge != base);
533
534 int count = 1;
535 builder->moveTo(SkIntToScalar(prev->fX), SkIntToScalar(prev->fY0));
536 prev->fFlags = 0;
537 do {
538 if (prev->fX != edge->fX || prev->fY1 != edge->fY0) { // skip collinear
539 builder->lineTo(SkIntToScalar(prev->fX), SkIntToScalar(prev->fY1)); // V
540 builder->lineTo(SkIntToScalar(edge->fX), SkIntToScalar(edge->fY0)); // H
541 }
542 prev = edge;
543 edge = edge->fNext;
544 count += 1;
545 prev->fFlags = 0;
546 } while (edge != base);
547 builder->lineTo(SkIntToScalar(prev->fX), SkIntToScalar(prev->fY1)); // V
548 builder->close();
549 return count;
550 }
551
552 struct EdgeLT {
553 bool operator()(const Edge& a, const Edge& b) const {
554 return (a.fX == b.fX) ? a.top() < b.top() : a.fX < b.fX;
555 }
556 };
557
558 bool SkRegion::addBoundaryPath(SkPathBuilder* builder) const {
559 // path could safely be nullptr if we're empty, but the caller shouldn't
560 // *know* that
561 SkASSERT(builder);
562
563 if (this->isEmpty()) {
564 return false;
565 }
566
567 const SkIRect& bounds = this->getBounds();
568
569 if (this->isRect()) {
570 SkRect r;
571 r.set(bounds); // this converts the ints to scalars
572 builder->addRect(r);
573 return true;
574 }
575
576 SkRegion::Iterator iter(*this);
577 SkTDArray<Edge> edges;
578
579 for (const SkIRect& r = iter.rect(); !iter.done(); iter.next()) {
580 Edge* edge = edges.append(2);
581 edge[0].set(r.fLeft, r.fBottom, r.fTop);
582 edge[1].set(r.fRight, r.fTop, r.fBottom);
583 }
584
585 int count = edges.size();
586 Edge* start = edges.begin();
587 Edge* stop = start + count;
588 SkTQSort<Edge>(start, stop, EdgeLT());
589
590 Edge* e;
591 for (e = start; e != stop; e++) {
592 find_link(e, stop);
593 }
594
595 #ifdef SK_DEBUG
596 for (e = start; e != stop; e++) {
597 SkASSERT(e->fNext != nullptr);
598 SkASSERT(e->fFlags == Edge::kCompleteLink);
599 }
600 #endif
601
602 builder->incReserve(count << 1);
603 do {
604 SkASSERT(count > 1);
605 count -= extract_path(start, stop, builder);
606 } while (count > 0);
607
608 return true;
609 }
610
611 SkPath SkRegion::getBoundaryPath() const {
612 SkPathBuilder builder;
613 (void)this->addBoundaryPath(&builder);
614 return builder.detach();
615 }