Debian Codegraph @

src/core/SkPathData.cpp

raw
1 /*
2 * Copyright 2025 Google LLC.
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/SkPathTypes.h"
9 #include "include/core/SkRRect.h"
10 #include "include/core/SkSpan.h"
11 #include "include/private/base/SkFloatingPoint.h"
12 #include "include/private/base/SkMalloc.h"
13 #include "include/private/base/SkTo.h"
14 #include "src/base/SkSafeMath.h"
15 #include "src/core/SkPathData.h"
16 #include "src/core/SkPathEnums.h"
17 #include "src/core/SkPathPriv.h"
18 #include "src/core/SkPathRawShapes.h"
19 #include "src/core/SkSpanPriv.h"
20
21 #include <new>
22 #include <optional>
23 #include <type_traits>
24
25 SkPathData* SkPathData::PeekEmptySingleton() {
26 static SkPathData* gEmpty = SkPathData::MakeNoCheck({}, {}, {}, {}, {}).release();
27 return gEmpty;
28 }
29
30 static uint32_t next_pathdata_unique_id() {
31 constexpr int kHighBitsToMakeRoomForFillType = 2;
32
33 static std::atomic<int32_t> nextID{1};
34
35 uint32_t id;
36 do {
37 id = nextID.fetch_add(1, std::memory_order_relaxed);
38 // clear the high bits to make room for filltype
39 id <<= kHighBitsToMakeRoomForFillType;
40 id >>= kHighBitsToMakeRoomForFillType;
41 } while (id == 0);
42 return id;
43 }
44
45 class SkSafeAccumulator {
46 public:
47 SkSafeAccumulator(size_t n = 0) : fTotal(n) {}
48
49 bool ok() const { return fSafe.ok(); }
50 explicit operator bool() const { return fSafe.ok(); }
51
52 SkSafeAccumulator& add(size_t n) {
53 fTotal = fSafe.add(fTotal, n);
54 return *this;
55 }
56
57 SkSafeAccumulator& addMul(size_t a, size_t b) {
58 fTotal = fSafe.add(fTotal, fSafe.mul(a, b));
59 return *this;
60 }
61
62 std::optional<size_t> total() const {
63 if (fSafe.ok()) {
64 return fTotal;
65 }
66 return {};
67 }
68 private:
69 SkSafeMath fSafe;
70 size_t fTotal;
71 };
72
73 const uint8_t gPtsPerVerb[] = {
74 1, 1, 2, 2, 3, 0, // move, line, quad, conic, cubic, close
75 };
76
77 static inline bool valid_conic_weight(float w) {
78 return w >= 0 && SkIsFinite(w);
79 }
80
81 static bool valid_path_data(SkSpan<const SkPoint> pts,
82 SkSpan<const SkPathVerb> vbs,
83 SkSpan<const float> conics) {
84 if (vbs.empty()) {
85 return pts.empty() && conics.empty();
86 }
87
88 // We must begin with a Move (unless we're empty)
89 if (vbs.front() != SkPathVerb::kMove) {
90 return false;
91 }
92 SkPathVerb prev = SkPathVerb::kMove;
93 size_t point_count = 1,
94 conic_count = 0;
95
96 // Check that we have a valid sequence.
97 for (size_t i = 1; i < vbs.size(); ++i) {
98 SkPathVerb curr = vbs[i];
99
100 if (static_cast<unsigned>(curr) > static_cast<unsigned>(SkPathVerb::kLast_Verb)) {
101 return false;
102 }
103
104 // Previous verb Valid next verb
105 // -----------------------------------------
106 // Move --> not Move
107 // Line/Quad/Conic/Cubic --> *
108 // Close --> Move
109 //
110 if (prev == SkPathVerb::kMove && curr == SkPathVerb::kMove) {
111 return false;
112 }
113 if (prev == SkPathVerb::kClose && curr != SkPathVerb::kMove) {
114 return false;
115 }
116
117 point_count += gPtsPerVerb[SkToSizeT(curr)];
118 conic_count += (curr == SkPathVerb::kConic);
119
120 prev = curr;
121 }
122
123 if (pts.size() != point_count || conics.size() != conic_count){
124 return false;
125 }
126
127 for (auto w : conics) {
128 if (!valid_conic_weight(w)) {
129 return false;
130 }
131 }
132
133 return true;
134 }
135
136 // Handing in debugging, to set a break-point here if you want to know why we
137 // failed to create a pathdta
138 //
139 static void report_pathdata_make_failure(const char reason[]) {
140 // ` SkDEBUGF("SkPathData::Make failed: %s\n", reason);
141 }
142
143 // This just sets-up the spans to point inside our allocation
144 //
145 SkPathData::SkPathData(size_t npts, size_t nvbs, size_t ncns)
146 : fUniqueID(next_pathdata_unique_id())
147 , fConvexity((uint8_t)SkPathConvexity::kUnknown)
148 , fType(SkPathIsAType::kGeneral)
149 {
150 SkASSERT((npts == 0 && nvbs == 0 && ncns == 0) ||
151 (npts != 0 && nvbs != 0));
152
153 #ifdef SK_DEBUG
154 {
155 SkSafeAccumulator accum(sizeof(*this));
156 accum.addMul(npts, sizeof(SkPoint))
157 .addMul(ncns, sizeof(float))
158 .addMul(nvbs, sizeof(SkPathVerb));
159 SkASSERT(accum.ok());
160 }
161 #endif
162
163 if (nvbs == 0) {
164 SkASSERT(fPoints.empty());
165 SkASSERT(fVerbs.empty());
166 SkASSERT(fConics.empty());
167 } else {
168 auto data = reinterpret_cast<std::byte*>(this + 1);
169
170 fPoints = {reinterpret_cast<SkPoint*>(data), npts};
171 data += fPoints.size_bytes();
172
173 fConics = {reinterpret_cast<float*>(data), ncns};
174 data += fConics.size_bytes();
175
176 fVerbs = {reinterpret_cast<SkPathVerb*>(data), nvbs};
177 }
178
179 // fBounds is initialized in finishInit()
180 }
181
182 SkPathData::~SkPathData() {
183 // We will implicitly call our IDChangeList here, notifying them that we are
184 // being dstroyed.
185 SkDEBUGCODE(fUniqueID = 0xEEEEEEEE;)
186 }
187
188 void SkPathData::operator delete(void* p) {
189 ::operator delete(p);
190 }
191
192 void SkPathData::addGenIDChangeListener(sk_sp<SkIDChangeListener> listener) const {
193 // our empty singleton is never deleted, so we don't want to add any listeners to it.
194 if (this != SkPathData::PeekEmptySingleton()) {
195 // this method on the list is thread-safe
196 fGenIDChangeListeners.add(std::move(listener));
197 }
198 }
199
200 //////////////////////////////////////////////////////////////////////////////////////////////
201
202 // NOTE: This only allocates and initializes the span pointers (points, verbs),
203 // it does NOT set the other fields
204 sk_sp<SkPathData> SkPathData::Alloc(size_t npts, size_t nvbs, size_t ncns) {
205 SkSafeAccumulator accum(sizeof(SkPathData));
206
207 accum.addMul(npts, sizeof(SkPoint))
208 .addMul(ncns, sizeof(float))
209 .addMul(nvbs, sizeof(SkPathVerb));
210
211 if (auto size = accum.total()) {
212 // This trick allows us to just make one allocation, for us and our buffer
213 // rather than allocating us and also allocating the buffer (via malloc or new[])
214 // We have the corresponding operator delete() specified as well.
215 void* storage = ::operator new (*size);
216 sk_sp<SkPathData> path(new (storage) SkPathData(npts, nvbs, ncns));
217
218 return path;
219 }
220 return nullptr;
221 }
222
223 bool SkPathData::finishInit(std::optional<SkRect> bounds, std::optional<uint8_t> segmentMask) {
224 if (fPoints.empty()) {
225 fBounds = SkRect::MakeEmpty();
226 fSegmentMask = 0;
227 return true;
228 }
229
230 if (segmentMask.has_value()) {
231 fSegmentMask = segmentMask.value();
232 } else {
233 fSegmentMask = SkPathPriv::ComputeSegmentMask(fVerbs);
234 }
235
236 if (bounds.has_value()) {
237 fBounds = bounds.value().makeSorted();
238 SkASSERT(SkIsFinite(&fPoints.data()->fX, fPoints.size() * 2));
239 } else {
240 if (auto r = SkPathPriv::TrimmedBounds(fPoints, fVerbs)) {
241 fBounds = r.value();
242 } else {
243 report_pathdata_make_failure("non-finite bounds");
244 return false;
245 }
246 }
247
248 SkASSERT(fBounds.isSorted());
249 return true;
250 }
251
252 sk_sp<SkPathData> SkPathData::MakeTransform(const SkPathRaw& src, const SkMatrix& mx) {
253 if (src.empty()) {
254 return SkPathData::Empty();
255 }
256
257 if (mx.hasPerspective()) {
258 SkPathBuilder bu;
259 bu.addRaw(src);
260 bu.transform(mx);
261 return bu.detachData();
262 }
263
264 // Allocate our result, so we can map the new points directly into it
265 auto result = Alloc(src.points().size(), src.verbs().size(), src.conics().size());
266 mx.mapPoints(result->fPoints, src.points());
267 SkSpanPriv::Copy(result->fConics, src.conics());
268 SkSpanPriv::Copy(result->fVerbs, src.verbs());
269
270 std::optional<SkRect> transformedBounds;
271 if (mx.rectStaysRect()) {
272 // safe us from having to compute our transformed bounds in finishInit()
273 transformedBounds = mx.mapRect(src.bounds());
274 if (!transformedBounds.value().isFinite()) {
275 report_pathdata_make_failure("transform created non-finite bounds");
276 return nullptr;
277 }
278 }
279
280 if (!result->finishInit(transformedBounds, src.fSegmentMask)) {
281 return nullptr;
282 }
283
284 result->setConvexity(SkPathPriv::TransformConvexity(mx, src.fPoints, src.fConvexity));
285
286 return result;
287 }
288
289 sk_sp<SkPathData> SkPathData::makeTransform(const SkMatrix& mx) const {
290 if (mx.isIdentity()) {
291 return sk_ref_sp(this);
292 }
293
294 // not important for transform, just need a value
295 const SkPathFillType ft = SkPathFillType::kDefault;
296
297 if (auto result = MakeTransform(this->raw(ft, SkResolveConvexity::kNo), mx)) {
298 // See if we can maintian our IsA status ...
299 if ((fType == SkPathIsAType::kOval || fType == SkPathIsAType::kRRect) &&
300 mx.rectStaysRect() && SkPathPriv::IsAxisAligned(fPoints))
301 {
302 auto [dir, start] =
303 SkPathPriv::TransformDirAndStart(mx, fType == SkPathIsAType::kRRect,
304 fIsA.fDirection, fIsA.fStartIndex);
305 result->setupIsA(fType, dir, start);
306 }
307 return result;
308 }
309 return nullptr;
310 }
311
312 sk_sp<SkPathData> SkPathData::makeOffset(SkVector v) const {
313 return this->makeTransform(SkMatrix::Translate(v));
314 }
315
316 bool operator==(const SkPathData& a, const SkPathData& b) {
317 if (&a == &b) {
318 return true;
319 }
320
321 return SkSpanPriv::EQ(a.fPoints, b.fPoints) &&
322 SkSpanPriv::EQ(a.fConics, b.fConics) &&
323 SkSpanPriv::EQ(a.fVerbs, b.fVerbs);
324 }
325
326 /////////////////////////////////////
327
328 sk_sp<SkPathData> SkPathData::MakeNoCheck(SkSpan<const SkPoint> pts,
329 SkSpan<const SkPathVerb> vbs,
330 SkSpan<const float> conics,
331 std::optional<SkRect> bounds,
332 std::optional<unsigned> segmentMask) {
333 SkASSERT(valid_path_data(pts, vbs, conics));
334
335 auto path = Alloc(pts.size(), vbs.size(), conics.size());
336
337 SkSpanPriv::Copy(path->fPoints, pts);
338 SkSpanPriv::Copy(path->fConics, conics);
339 SkSpanPriv::Copy(path->fVerbs, vbs);
340
341 return path->finishInit(bounds, segmentMask) ? path : nullptr;
342 }
343
344 sk_sp<SkPathData> SkPathData::MakeNoCheck(const SkPathRaw& raw) {
345 return MakeNoCheck(raw.points(), raw.verbs(), raw.conics(), raw.fBounds, raw.fSegmentMask);
346 }
347
348 sk_sp<SkPathData> SkPathData::Empty() {
349 return sk_ref_sp(PeekEmptySingleton());
350 }
351
352 void SkPathData::setupIsA(SkPathIsAType type, SkPathDirection dir, unsigned index) {
353 this->setConvexity(SkPathDirection_ToConvexity(dir));
354
355 SkASSERT(type == SkPathIsAType::kOval || type == SkPathIsAType::kRRect);
356 fType = type;
357
358 SkASSERT((type == SkPathIsAType::kOval && index < 4) ||
359 (type == SkPathIsAType::kRRect && index < 8));
360
361 fIsA.fDirection = dir;
362 fIsA.fStartIndex = SkTo<uint8_t>(index);
363 }
364
365 sk_sp<SkPathData> SkPathData::Rect(const SkRect& r, SkPathDirection dir, unsigned index) {
366 if (!r.isFinite()) {
367 return nullptr;
368 }
369 SkPathRawShapes::Rect raw(r, dir, index);
370 return MakeNoCheck(raw.points(), raw.verbs(), raw.conics(), raw.fBounds, raw.fSegmentMask);
371 }
372
373 sk_sp<SkPathData> SkPathData::Oval(const SkRect& r, SkPathDirection dir, unsigned index) {
374 if (!r.isFinite()) {
375 return nullptr;
376 }
377 SkPathRawShapes::Oval raw(r, dir, index);
378 auto path = MakeNoCheck(raw.points(), raw.verbs(), raw.conics(), raw.fBounds, raw.fSegmentMask);
379
380 path->setupIsA(SkPathIsAType::kOval, dir, index);
381 return path;
382 }
383
384 sk_sp<SkPathData> SkPathData::RRect(const SkRRect& r, SkPathDirection dir, unsigned index) {
385 if (!r.isValid()) {
386 return nullptr;
387 }
388 SkPathRawShapes::RRect raw(r, dir, index);
389 // we use Make, not MakeNoCheck, to confirm all points an conics are finite
390 if (auto path = Make(raw.points(), raw.verbs(), raw.conics())) {
391 path->setupIsA(SkPathIsAType::kRRect, dir, index);
392 return path;
393 }
394 return nullptr;
395 }
396
397 sk_sp<SkPathData> SkPathData::Polygon(SkSpan<const SkPoint> pts, bool isClosed) {
398 if (pts.size() == 0 || (pts.size() == 1 && !isClosed)) {
399 return Empty();
400 }
401
402 const size_t nverbs = pts.size() + isClosed; // +1 for the kClose verb
403 const size_t nconics = 0;
404 auto path = Alloc(pts.size(), nverbs, nconics);
405
406 SkSpanPriv::Copy(path->fPoints, pts);
407
408 path->fVerbs[0] = SkPathVerb::kMove;
409 for (size_t i = 1; i < pts.size(); ++i) {
410 path->fVerbs[i] = SkPathVerb::kLine;
411 }
412 if (isClosed) {
413 path->fVerbs.back() = SkPathVerb::kClose;
414 }
415
416 return path->finishInit({}, kLine_SkPathSegmentMask) ? path : nullptr;
417 }
418
419 /////////////////////////////////////
420
421 SkPathConvexity SkPathData::getConvexityOrUnknown() const {
422 return static_cast<SkPathConvexity>(fConvexity.load(std::memory_order_relaxed));
423 }
424
425 SkPathConvexity SkPathData::getResolvedConvexity() const {
426 auto convexity = this->getConvexityOrUnknown();
427 if (convexity == SkPathConvexity::kUnknown) {
428 convexity = SkPathPriv::ComputeConvexity(fPoints, fVerbs, fConics);
429 this->setConvexity(convexity);
430 }
431 return convexity;
432 }
433
434 void SkPathData::setConvexity(SkPathConvexity convexity) const {
435 fConvexity.store((uint8_t)convexity, std::memory_order_relaxed);
436 }
437
438 bool SkPathData::isConvex() const {
439 return SkPathConvexity_IsConvex(this->getResolvedConvexity());
440 }
441
442 SkRect SkPathData::computeTightBounds() const {
443 return SkPathPriv::ComputeTightBounds(this->points(), this->verbs(), this->conics());
444 }
445
446 SkPathRaw SkPathData::raw(SkPathFillType ft, SkResolveConvexity rc) const {
447 return {
448 fPoints,
449 fVerbs,
450 fConics,
451 fBounds,
452 ft,
453 rc == SkResolveConvexity::kYes ? this->getResolvedConvexity()
454 : this->getConvexityOrUnknown(),
455 fSegmentMask,
456 };
457 }
458
459 std::optional<std::array<SkPoint, 2>> SkPathData::asLine() const {
460 if (fPoints.size() == 2 && fVerbs.size() == 2 && fConics.size() == 0 &&
461 fVerbs[1] == SkPathVerb::kLine)
462 {
463 SkASSERT(fVerbs[0] == SkPathVerb::kMove);
464 return {{ fPoints[0], fPoints[1] }};
465 }
466 return {};
467 }
468
469 std::optional<SkPathRectInfo> SkPathData::asRect() const {
470 if (auto rc = SkPathPriv::IsRectContour(fPoints, fVerbs, fSegmentMask, false)) {
471 SkASSERT(rc->fRect == fBounds);
472 return {{
473 fBounds,
474 rc->fDirection,
475 0, // start index???
476 }};
477 }
478 return {};
479 }
480
481 std::optional<SkPathOvalInfo> SkPathData::asOval() const {
482 if (fType == SkPathIsAType::kOval) {
483 return {{
484 fBounds,
485 fIsA.fDirection,
486 fIsA.fStartIndex,
487 }};
488 }
489 return {};
490 }
491
492 std::optional<SkPathRRectInfo> SkPathData::asRRect() const {
493 if (fType == SkPathIsAType::kRRect) {
494 return {{
495 SkPathPriv::DeduceRRectFromContour(fBounds, fPoints, fVerbs),
496 fIsA.fDirection,
497 fIsA.fStartIndex,
498 }};
499 }
500 return {};
501 }
502
503 bool SkPathData::contains(SkPoint p, SkPathFillType ft) const {
504 return SkPathPriv::Contains(this->raw(ft, SkResolveConvexity::kNo), p);
505 }
506
507 /////////////////
508
509 sk_sp<SkPathData> SkPathData::Make(SkSpan<const SkPoint> pts,
510 SkSpan<const SkPathVerb> vbs,
511 SkSpan<const float> conics) {
512 if (!valid_path_data(pts, vbs, conics)) {
513 report_pathdata_make_failure("invalid path data");
514 return nullptr;
515 }
516
517 // MakeNoCheck *does* compute/check bounds if we don't pass them in
518 return MakeNoCheck(pts, vbs, conics, {}, {});
519 }