Debian Codegraph @

src/core/SkPathPriv.h

raw
1 /*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #ifndef SkPathPriv_DEFINED
9 #define SkPathPriv_DEFINED
10
11 #include "include/core/SkArc.h"
12 #include "include/core/SkPath.h"
13 #include "include/core/SkPathBuilder.h"
14 #include "include/core/SkPathTypes.h"
15 #include "include/core/SkPoint.h"
16 #include "include/core/SkRect.h"
17 #include "include/core/SkRefCnt.h"
18 #include "include/core/SkScalar.h"
19 #include "include/core/SkSpan.h"
20 #include "include/core/SkTypes.h"
21 #include "include/private/SkIDChangeListener.h"
22 #include "include/private/SkPathRef.h"
23 #include "include/private/base/SkDebug.h"
24 #include "src/core/SkPathData.h"
25 #include "src/core/SkPathEnums.h"
26 #include "src/core/SkPathRaw.h"
27
28 #include <cstddef>
29 #include <cstdint>
30 #include <iterator>
31 #include <optional>
32 #include <utility>
33
34 class SkMatrix;
35 class SkRRect;
36
37 static_assert(0 == static_cast<int>(SkPathFillType::kWinding), "fill_type_mismatch");
38 static_assert(1 == static_cast<int>(SkPathFillType::kEvenOdd), "fill_type_mismatch");
39 static_assert(2 == static_cast<int>(SkPathFillType::kInverseWinding), "fill_type_mismatch");
40 static_assert(3 == static_cast<int>(SkPathFillType::kInverseEvenOdd), "fill_type_mismatch");
41
42 class SkPathPriv {
43 public:
44 enum class RRectAsEnum {
45 kRect, kOval, kRRect,
46 };
47 static std::pair<RRectAsEnum, unsigned> SimplifyRRect(const SkRRect& rr, unsigned startIndex) {
48 if (rr.isRect() || rr.isEmpty()) {
49 return { RRectAsEnum::kRect, (startIndex + 1) / 2 };
50 }
51 if (rr.isOval()) {
52 return { RRectAsEnum::kOval, startIndex / 2 };
53 }
54 return { RRectAsEnum::kRRect, startIndex };
55 }
56
57 static SkPathConvexity ComputeConvexity(SkSpan<const SkPoint> pts,
58 SkSpan<const SkPathVerb> verbs,
59 SkSpan<const float> conicWeights);
60
61 static SkPathConvexity TransformConvexity(const SkMatrix&, SkSpan<const SkPoint>,
62 SkPathConvexity);
63
64 static uint8_t ComputeSegmentMask(SkSpan<const SkPathVerb>);
65
66 /* Note: does NOT use convexity in the raw, so it need not be resolved,
67 * if converting from builder or path.
68 */
69 static bool Contains(const SkPathRaw&, SkPoint);
70
71 // skbug.com/40041027: Not a perfect solution for W plane clipping, but 1/16384 is a
72 // reasonable limit (roughly 5e-5)
73 inline static constexpr SkScalar kW0PlaneDistance = 1.f / (1 << 14);
74
75 static SkPathFirstDirection AsFirstDirection(SkPathDirection dir) {
76 // since we agree numerically for the values in Direction, we can just cast.
77 return (SkPathFirstDirection)dir;
78 }
79
80 /**
81 * Return the opposite of the specified direction. kUnknown is its own
82 * opposite.
83 */
84 static SkPathFirstDirection OppositeFirstDirection(SkPathFirstDirection dir) {
85 static const SkPathFirstDirection gOppositeDir[] = {
86 SkPathFirstDirection::kCCW, SkPathFirstDirection::kCW, SkPathFirstDirection::kUnknown,
87 };
88 return gOppositeDir[(unsigned)dir];
89 }
90
91 /**
92 * Tries to compute the direction of the outer-most non-degenerate
93 * contour. If it can be computed, return that direction. If it cannot be determined,
94 * or the contour is known to be convex, return kUnknown. If the direction was determined,
95 * it is cached to make subsequent calls return quickly.
96 */
97 static SkPathFirstDirection ComputeFirstDirection(const SkPathRaw&);
98 static SkPathFirstDirection ComputeFirstDirection(const SkPath&);
99
100 static bool IsClosedSingleContour(SkSpan<const SkPathVerb> verbs) {
101 if (verbs.empty()) {
102 return false;
103 }
104
105 int moveCount = 0;
106 for (const auto& verb : verbs) {
107 switch (verb) {
108 case SkPathVerb::kMove:
109 if (++moveCount > 1) {
110 return false;
111 }
112 break;
113 case SkPathVerb::kClose:
114 return &verb == &verbs.back();
115 default:
116 break;
117 }
118 }
119 return false;
120 }
121
122 static bool IsClosedSingleContour(const SkPath& path) {
123 return IsClosedSingleContour(path.verbs());
124 }
125
126 /*
127 * Returns the index of the last moveTo() point, based on the verbs.
128 * If verbs is empty / ptCount == 0, then this returns -1.
129 */
130 static int FindLastMoveToIndex(SkSpan<const SkPathVerb> verbs, const size_t ptCount);
131
132 /*
133 * If we're transforming a known shape (oval or rrect), this computes what happens to its
134 * - winding direction
135 * - start index
136 */
137 static std::pair<SkPathDirection, unsigned>
138 TransformDirAndStart(const SkMatrix&, bool isRRect, SkPathDirection dir, unsigned start);
139
140 static void AddGenIDChangeListener(const SkPath&, sk_sp<SkIDChangeListener>);
141
142 /**
143 * This returns the info for a rect that has a move followed by 3 or 4 lines and a close. If
144 * 'isSimpleFill' is true, an uncloseed rect will also be accepted as long as it starts and
145 * ends at the same corner. This does not permit degenerate line or point rectangles.
146 */
147 static std::optional<SkPathRectInfo> IsSimpleRect(const SkPath& path, bool isSimpleFill);
148
149 // Asserts the path contour was built from RRect, so it does not return
150 // an optional. This exists so path's can have a flag that they are really
151 // a RRect, without having to actually store the 4 radii... since those can
152 // be deduced from the contour itself.
153 //
154 static SkRRect DeduceRRectFromContour(const SkRect& bounds,
155 SkSpan<const SkPoint>, SkSpan<const SkPathVerb>);
156
157 /**
158 * Creates a path from arc params using the semantics of SkCanvas::drawArc. This function
159 * assumes empty ovals and zero sweeps have already been filtered out.
160 */
161 static SkPath CreateDrawArcPath(const SkArc& arc, bool isFillNoPathEffect);
162
163 /**
164 * Determines whether an arc produced by CreateDrawArcPath will be convex. Assumes a non-empty
165 * oval.
166 */
167 static bool DrawArcIsConvex(SkScalar sweepAngle, SkArc::Type arcType, bool isFillNoPathEffect);
168
169 /**
170 * Iterates through a raw range of path verbs, points, and conics. All values are returned
171 * unaltered.
172 *
173 * NOTE: This class's definition will be moved into SkPathPriv once RangeIter is removed.
174 */
175 using RangeIter = SkPath::RangeIter;
176
177 /**
178 * Iterable object for traversing verbs, points, and conic weights in a path:
179 *
180 * for (auto [verb, pts, weights] : SkPathPriv::Iterate(skPath)) {
181 * ...
182 * }
183 */
184 struct Iterate {
185 public:
186 Iterate(SkPath&&) = delete;
187 Iterate(const SkPath& path)
188 : Iterate(path.verbs(), path.points().data(), path.conicWeights().data())
189 {
190 // Don't allow iteration through non-finite points.
191 if (!path.isFinite()) {
192 fVerbsBegin = fVerbsEnd;
193 }
194 }
195 Iterate(SkSpan<const SkPathVerb> verbs, const SkPoint* points, const SkScalar* weights)
196 : fVerbsBegin(verbs.data())
197 , fVerbsEnd(verbs.data() + verbs.size())
198 , fPoints(points)
199 , fWeights(weights)
200 {}
201 SkPath::RangeIter begin() { return {fVerbsBegin, fPoints, fWeights}; }
202 SkPath::RangeIter end() { return {fVerbsEnd, nullptr, nullptr}; }
203 private:
204 const SkPathVerb* fVerbsBegin;
205 const SkPathVerb* fVerbsEnd;
206 const SkPoint* fPoints;
207 const SkScalar* fWeights;
208 };
209
210 // returns Empty() if there are no points
211 static SkRect ComputeTightBounds(SkSpan<const SkPoint> points,
212 SkSpan<const SkPathVerb> verbs,
213 SkSpan<const float> conicWeights);
214
215 /** Returns the oval info if this path was created as an oval or circle, else returns {}.
216 */
217 static std::optional<SkPathOvalInfo> IsOval(const SkPath& path) {
218 return path.getOvalInfo();
219 }
220
221 /** Returns the rrect info if this path was created as one, else returns {}.
222 */
223 static std::optional<SkPathRRectInfo> IsRRect(const SkPath& path) {
224 return path.getRRectInfo();
225 }
226
227 /**
228 * Sometimes in the drawing pipeline, we have to perform math on path coordinates, even after
229 * the path is in device-coordinates. Tessellation and clipping are two examples. Usually this
230 * is pretty modest, but it can involve subtracting/adding coordinates, or multiplying by
231 * small constants (e.g. 2,3,4). To try to preflight issues where these optionations could turn
232 * finite path values into infinities (or NaNs), we allow the upper drawing code to reject
233 * the path if its bounds (in device coordinates) is too close to max float.
234 */
235 static bool TooBigForMath(const SkRect& bounds) {
236 // This value is just a guess. smaller is safer, but we don't want to reject largish paths
237 // that we don't have to.
238 constexpr SkScalar scale_down_to_allow_for_small_multiplies = 0.25f;
239 constexpr SkScalar max = SK_ScalarMax * scale_down_to_allow_for_small_multiplies;
240
241 // use ! expression so we return true if bounds contains NaN
242 return !(bounds.fLeft >= -max && bounds.fTop >= -max &&
243 bounds.fRight <= max && bounds.fBottom <= max);
244 }
245
246 // Returns number of valid points for each SkPath::Iter verb
247 static int PtsInIter(unsigned verb) {
248 static const uint8_t gPtsInVerb[] = {
249 1, // kMove pts[0]
250 2, // kLine pts[0..1]
251 3, // kQuad pts[0..2]
252 3, // kConic pts[0..2]
253 4, // kCubic pts[0..3]
254 0, // kClose
255 0 // kDone
256 };
257
258 SkASSERT(verb < std::size(gPtsInVerb));
259 return gPtsInVerb[verb];
260 }
261
262 static int PtsInIter(SkPathVerb verb) { return PtsInIter((unsigned)verb); }
263
264 // Returns number of valid points for each verb, not including the "starter"
265 // point that the Iterator adds for line/quad/conic/cubic
266 static int PtsInVerb(unsigned verb) {
267 static const uint8_t gPtsInVerb[] = {
268 1, // kMove pts[0]
269 1, // kLine pts[0..1]
270 2, // kQuad pts[0..2]
271 2, // kConic pts[0..2]
272 3, // kCubic pts[0..3]
273 0, // kClose
274 0 // kDone
275 };
276
277 SkASSERT(verb < std::size(gPtsInVerb));
278 return gPtsInVerb[verb];
279 }
280
281 static int PtsInVerb(SkPathVerb verb) { return PtsInVerb((unsigned)verb); }
282
283 static bool IsAxisAligned(SkSpan<const SkPoint>);
284
285 static bool AllPointsEq(SkSpan<const SkPoint> pts) {
286 for (size_t i = 1; i < pts.size(); ++i) {
287 if (pts[0] != pts[i]) {
288 return false;
289 }
290 }
291 return true;
292 }
293
294 struct RectContour {
295 SkRect fRect;
296 bool fIsClosed;
297 SkPathDirection fDirection;
298 size_t fPointsConsumed,
299 fVerbsConsumed;
300 };
301 static std::optional<RectContour> IsRectContour(SkSpan<const SkPoint> ptSpan,
302 SkSpan<const SkPathVerb> vbSpan,
303 uint32_t segmentMask,
304 bool allowPartial);
305
306 /** Returns true if SkPath is equivalent to nested SkRect pair when filled.
307 If false, rect and dirs are unchanged.
308 If true, rect and dirs are written to if not nullptr:
309 setting rect[0] to outer SkRect, and rect[1] to inner SkRect;
310 setting dirs[0] to SkPathDirection of outer SkRect, and dirs[1] to SkPathDirection of
311 inner SkRect.
312
313 @param rect storage for SkRect pair; may be nullptr
314 @param dirs storage for SkPathDirection pair; may be nullptr
315 @return true if SkPath contains nested SkRect pair
316 */
317 static bool IsNestedFillRects(const SkPathRaw&, SkRect rect[2],
318 SkPathDirection dirs[2] = nullptr);
319
320 static bool IsNestedFillRects(const SkPath& path, SkRect rect[2],
321 SkPathDirection dirs[2] = nullptr) {
322 auto raw = Raw(path, SkResolveConvexity::kNo);
323 return raw.has_value() && IsNestedFillRects(*raw, rect, dirs);
324 }
325
326
327 static bool IsInverseFillType(SkPathFillType fill) {
328 return (static_cast<int>(fill) & 2) != 0;
329 }
330
331 /**
332 * If needed (to not blow-up under a perspective matrix), clip the path, returning the
333 * answer in "result", and return true.
334 *
335 * Note result might be empty (if the path was completely clipped out).
336 *
337 * If no clipping is needed, returns false and "result" is left unchanged.
338 */
339 static bool PerspectiveClip(const SkPath& src, const SkMatrix&, SkPath* result);
340
341 /**
342 * Gets the number of GenIDChangeListeners. If another thread has access to this path then
343 * this may be stale before return and only indicates that the count was the return value
344 * at some point during the execution of the function.
345 */
346 static int GenIDChangeListenersCount(const SkPath&);
347
348 static SkPathConvexity GetConvexity(const SkPath& path) {
349 return path.getConvexity();
350 }
351 static SkPathConvexity GetConvexityOrUnknown(const SkPath& path) {
352 return path.getConvexityOrUnknown();
353 }
354 static void SetConvexity(const SkPath& path, SkPathConvexity c) {
355 path.setConvexity(c);
356 }
357 static void ForceComputeConvexity(const SkPath& path) {
358 path.setConvexity(SkPathConvexity::kUnknown);
359 (void)path.isConvex();
360 }
361
362 static SkPathConvexity GetConvexityOrUnknown(const SkPathData& pdata) {
363 return pdata.getConvexityOrUnknown();
364 }
365
366 static void ReverseAddPath(SkPathBuilder* builder, const SkPath& reverseMe) {
367 builder->privateReverseAddPath(reverseMe);
368 }
369
370 static void ReversePathTo(SkPathBuilder* builder, const SkPath& reverseMe) {
371 builder->privateReversePathTo(reverseMe);
372 }
373
374 static SkPath ReversePath(const SkPath& reverseMe) {
375 SkPathBuilder bu;
376 bu.privateReverseAddPath(reverseMe);
377 return bu.detach();
378 }
379
380 static SkSpan<const SkPathVerb> GetVerbs(const SkPathBuilder& builder) {
381 return builder.fVerbs;
382 }
383
384 static int CountVerbs(const SkPathBuilder& builder) {
385 return builder.fVerbs.size();
386 }
387
388 static std::optional<SkPathRaw> Raw(const SkPath& path, SkResolveConvexity rc) {
389 return path.raw(rc);
390 }
391
392 static std::optional<SkPathRaw> Raw(const SkPathBuilder& builder, SkResolveConvexity rc) {
393 const auto bounds = builder.computeFiniteBounds();
394 if (!bounds) {
395 return {};
396 }
397
398 SkPathConvexity convexity = builder.fConvexity;
399 if (convexity == SkPathConvexity::kUnknown && rc == SkResolveConvexity::kYes) {
400 convexity = SkPathPriv::ComputeConvexity(builder.fPts,
401 builder.fVerbs,
402 builder.fConicWeights);
403 }
404
405 return SkPathRaw{
406 builder.points(),
407 builder.verbs(),
408 builder.conicWeights(),
409 *bounds,
410 builder.fillType(),
411 convexity,
412 SkTo<uint8_t>(builder.fSegmentMask),
413 };
414 }
415
416 // Returns Empty if there are no points
417 // Returns {} if the bounds are not finite
418 static std::optional<SkRect> TrimmedBounds(SkSpan<const SkPoint> pts,
419 SkSpan<const SkPathVerb> vbs) {
420 // Does a trailing kMove verb contribute to the bounds?
421 // - only if it is the only verb in the path
422 // - otherwise we ignore it when computing bounds
423 if (vbs.size() > 1 && vbs.back() == SkPathVerb::kMove) {
424 SkASSERT(pts.size() > 0);
425 // While trailing moves do not contribute to the bounds, we still reject them.
426 if (!pts.back().isFinite()) {
427 return {};
428 }
429 pts = pts.subspan(0, pts.size() - 1);
430 }
431 return SkRect::Bounds(pts);
432 }
433 };
434
435 // Lightweight variant of SkPath::Iter that only returns segments (e.g. lines/conics).
436 // Does not return kMove or kClose.
437 // Always "auto-closes" each contour.
438 // Roughly the same as SkPath::Iter(path, true), but does not return moves or closes
439 //
440 class SkPathEdgeIter {
441 const SkPathVerb* fVerbs;
442 const SkPathVerb* fVerbsStop;
443 const SkPoint* fPts;
444 const SkPoint* fMoveToPtr;
445 const SkScalar* fConicWeights;
446 SkPoint fScratch[2]; // for auto-close lines
447 bool fNeedsCloseLine;
448 bool fNextIsNewContour;
449 SkDEBUGCODE(bool fIsConic;)
450
451 public:
452 SkPathEdgeIter(const SkPath& path);
453 SkPathEdgeIter(const SkPathRaw&);
454
455 SkScalar conicWeight() const {
456 SkASSERT(fIsConic);
457 return *fConicWeights;
458 }
459
460 enum class Edge {
461 kLine = (int)SkPathVerb::kLine,
462 kQuad = (int)SkPathVerb::kQuad,
463 kConic = (int)SkPathVerb::kConic,
464 kCubic = (int)SkPathVerb::kCubic,
465 // kInvalid = 99,
466 };
467
468 static SkPathVerb EdgeToVerb(Edge e) {
469 return SkPathVerb(e);
470 }
471
472 // todo: return as optional? fPts become span?
473 struct Result {
474 const SkPoint* fPts; // points for the segment, or null if done
475 Edge fEdge;
476 bool fIsNewContour;
477
478 // Returns true when it holds an Edge, false when the path is done.
479 explicit operator bool() { return fPts != nullptr; }
480 };
481
482 Result next() {
483 auto closeline = [&]() {
484 fScratch[0] = fPts[-1];
485 fScratch[1] = *fMoveToPtr;
486 fNeedsCloseLine = false;
487 fNextIsNewContour = true;
488 return Result{ fScratch, Edge::kLine, false };
489 };
490
491 for (;;) {
492 SkASSERT(fVerbs <= fVerbsStop);
493 if (fVerbs == fVerbsStop) {
494 return fNeedsCloseLine ? closeline() : Result{nullptr, Edge::kLine, false};
495 }
496
497 SkDEBUGCODE(fIsConic = false;)
498
499 const auto verb = *fVerbs++;
500 switch (verb) {
501 case SkPathVerb::kMove: {
502 if (fNeedsCloseLine) {
503 auto res = closeline();
504 fMoveToPtr = fPts++;
505 return res;
506 }
507 fMoveToPtr = fPts++;
508 fNextIsNewContour = true;
509 } break;
510 case SkPathVerb::kClose:
511 if (fNeedsCloseLine) return closeline();
512 break;
513 default: {
514 unsigned v = static_cast<unsigned>(verb);
515 // Actual edge.
516 const int pts_count = (v+2) / 2,
517 cws_count = (v & (v-1)) / 2;
518 SkASSERT(pts_count == SkPathPriv::PtsInIter(v) - 1);
519
520 fNeedsCloseLine = true;
521 fPts += pts_count;
522 fConicWeights += cws_count;
523
524 SkDEBUGCODE(fIsConic = (verb == SkPathVerb::kConic);)
525 SkASSERT(fIsConic == (cws_count > 0));
526
527 bool isNewContour = fNextIsNewContour;
528 fNextIsNewContour = false;
529 return { &fPts[-(pts_count + 1)], Edge(v), isNewContour };
530 }
531 }
532 }
533 }
534 };
535
536 #endif