xref: /aosp_15_r20/external/skia/src/utils/SkDashPath.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2014 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 "src/utils/SkDashPathPriv.h"
9 
10 #include "include/core/SkPaint.h"
11 #include "include/core/SkPath.h"
12 #include "include/core/SkPathMeasure.h"
13 #include "include/core/SkPoint.h"
14 #include "include/core/SkRect.h"
15 #include "include/core/SkScalar.h"
16 #include "include/core/SkStrokeRec.h"
17 #include "include/core/SkTypes.h"
18 #include "include/private/base/SkAlign.h"
19 #include "include/private/base/SkFloatingPoint.h"
20 #include "include/private/base/SkTo.h"
21 #include "src/core/SkPathEffectBase.h"
22 #include "src/core/SkPathEnums.h"
23 #include "src/core/SkPathPriv.h"
24 #include "src/core/SkPointPriv.h"
25 
26 #include <algorithm>
27 #include <cmath>
28 #include <cstdint>
29 #include <iterator>
30 
is_even(int x)31 static inline int is_even(int x) {
32     return !(x & 1);
33 }
34 
find_first_interval(const SkScalar intervals[],SkScalar phase,int32_t * index,int count)35 static SkScalar find_first_interval(const SkScalar intervals[], SkScalar phase,
36                                     int32_t* index, int count) {
37     for (int i = 0; i < count; ++i) {
38         SkScalar gap = intervals[i];
39         if (phase > gap || (phase == gap && gap)) {
40             phase -= gap;
41         } else {
42             *index = i;
43             return gap - phase;
44         }
45     }
46     // If we get here, phase "appears" to be larger than our length. This
47     // shouldn't happen with perfect precision, but we can accumulate errors
48     // during the initial length computation (rounding can make our sum be too
49     // big or too small. In that event, we just have to eat the error here.
50     *index = 0;
51     return intervals[0];
52 }
53 
CalcDashParameters(SkScalar phase,const SkScalar intervals[],int32_t count,SkScalar * initialDashLength,int32_t * initialDashIndex,SkScalar * intervalLength,SkScalar * adjustedPhase)54 void SkDashPath::CalcDashParameters(SkScalar phase, const SkScalar intervals[], int32_t count,
55                                     SkScalar* initialDashLength, int32_t* initialDashIndex,
56                                     SkScalar* intervalLength, SkScalar* adjustedPhase) {
57     SkScalar len = 0;
58     for (int i = 0; i < count; i++) {
59         len += intervals[i];
60     }
61     *intervalLength = len;
62     // Adjust phase to be between 0 and len, "flipping" phase if negative.
63     // e.g., if len is 100, then phase of -20 (or -120) is equivalent to 80
64     if (adjustedPhase) {
65         if (phase < 0) {
66             phase = -phase;
67             if (phase > len) {
68                 phase = SkScalarMod(phase, len);
69             }
70             phase = len - phase;
71 
72             // Due to finite precision, it's possible that phase == len,
73             // even after the subtract (if len >>> phase), so fix that here.
74             // This fixes http://crbug.com/124652 .
75             SkASSERT(phase <= len);
76             if (phase == len) {
77                 phase = 0;
78             }
79         } else if (phase >= len) {
80             phase = SkScalarMod(phase, len);
81         }
82         *adjustedPhase = phase;
83     }
84     SkASSERT(phase >= 0 && phase < len);
85 
86     *initialDashLength = find_first_interval(intervals, phase,
87                                             initialDashIndex, count);
88 
89     SkASSERT(*initialDashLength >= 0);
90     SkASSERT(*initialDashIndex >= 0 && *initialDashIndex < count);
91 }
92 
outset_for_stroke(SkRect * rect,const SkStrokeRec & rec)93 static void outset_for_stroke(SkRect* rect, const SkStrokeRec& rec) {
94     SkScalar radius = SkScalarHalf(rec.getWidth());
95     if (0 == radius) {
96         radius = SK_Scalar1;    // hairlines
97     }
98     if (SkPaint::kMiter_Join == rec.getJoin()) {
99         radius *= rec.getMiter();
100     }
101     rect->outset(radius, radius);
102 }
103 
104 // If line is zero-length, bump out the end by a tiny amount
105 // to draw endcaps. The bump factor is sized so that
106 // SkPoint::Distance() computes a non-zero length.
107 // Offsets SK_ScalarNearlyZero or smaller create empty paths when Iter measures length.
108 // Large values are scaled by SK_ScalarNearlyZero so significant bits change.
adjust_zero_length_line(SkPoint pts[2])109 static void adjust_zero_length_line(SkPoint pts[2]) {
110     SkASSERT(pts[0] == pts[1]);
111     pts[1].fX += std::max(1.001f, pts[1].fX) * SK_ScalarNearlyZero;
112 }
113 
clip_line(SkPoint pts[2],const SkRect & bounds,SkScalar intervalLength,SkScalar priorPhase)114 static bool clip_line(SkPoint pts[2], const SkRect& bounds, SkScalar intervalLength,
115                       SkScalar priorPhase) {
116     SkVector dxy = pts[1] - pts[0];
117 
118     // only horizontal or vertical lines
119     if (dxy.fX && dxy.fY) {
120         return false;
121     }
122     int xyOffset = SkToBool(dxy.fY);  // 0 to adjust horizontal, 1 to adjust vertical
123 
124     SkScalar minXY = (&pts[0].fX)[xyOffset];
125     SkScalar maxXY = (&pts[1].fX)[xyOffset];
126     bool swapped = maxXY < minXY;
127     if (swapped) {
128         using std::swap;
129         swap(minXY, maxXY);
130     }
131 
132     SkASSERT(minXY <= maxXY);
133     SkScalar leftTop = (&bounds.fLeft)[xyOffset];
134     SkScalar rightBottom = (&bounds.fRight)[xyOffset];
135     if (maxXY < leftTop || minXY > rightBottom) {
136         return false;
137     }
138 
139     // Now we actually perform the chop, removing the excess to the left/top and
140     // right/bottom of the bounds (keeping our new line "in phase" with the dash,
141     // hence the (mod intervalLength).
142 
143     if (minXY < leftTop) {
144         minXY = leftTop - SkScalarMod(leftTop - minXY, intervalLength);
145         if (!swapped) {
146             minXY -= priorPhase;  // for rectangles, adjust by prior phase
147         }
148     }
149     if (maxXY > rightBottom) {
150         maxXY = rightBottom + SkScalarMod(maxXY - rightBottom, intervalLength);
151         if (swapped) {
152             maxXY += priorPhase;  // for rectangles, adjust by prior phase
153         }
154     }
155 
156     SkASSERT(maxXY >= minXY);
157     if (swapped) {
158         using std::swap;
159         swap(minXY, maxXY);
160     }
161     (&pts[0].fX)[xyOffset] = minXY;
162     (&pts[1].fX)[xyOffset] = maxXY;
163 
164     if (minXY == maxXY) {
165         adjust_zero_length_line(pts);
166     }
167     return true;
168 }
169 
170 // Handles only lines and rects.
171 // If cull_path() returns true, dstPath is the new smaller path,
172 // otherwise dstPath may have been changed but you should ignore it.
cull_path(const SkPath & srcPath,const SkStrokeRec & rec,const SkRect * cullRect,SkScalar intervalLength,SkPath * dstPath)173 static bool cull_path(const SkPath& srcPath, const SkStrokeRec& rec,
174                       const SkRect* cullRect, SkScalar intervalLength, SkPath* dstPath) {
175     if (!cullRect) {
176         SkPoint pts[2];
177         if (srcPath.isLine(pts) && pts[0] == pts[1]) {
178             adjust_zero_length_line(pts);
179             dstPath->moveTo(pts[0]);
180             dstPath->lineTo(pts[1]);
181             return true;
182         }
183         return false;
184     }
185 
186     SkRect bounds;
187     bounds = *cullRect;
188     outset_for_stroke(&bounds, rec);
189 
190     {
191         SkPoint pts[2];
192         if (srcPath.isLine(pts)) {
193             if (clip_line(pts, bounds, intervalLength, 0)) {
194                 dstPath->moveTo(pts[0]);
195                 dstPath->lineTo(pts[1]);
196                 return true;
197             }
198             return false;
199         }
200     }
201 
202     if (srcPath.isRect(nullptr)) {
203         // We'll break the rect into four lines, culling each separately.
204         SkPath::Iter iter(srcPath, false);
205 
206         SkPoint pts[4];  // Rects are all moveTo and lineTo, so we'll only use pts[0] and pts[1].
207         SkAssertResult(SkPath::kMove_Verb == iter.next(pts));
208 
209         double accum = 0;  // Sum of unculled edge lengths to keep the phase correct.
210                            // Intentionally a double to minimize the risk of overflow and drift.
211         while (iter.next(pts) == SkPath::kLine_Verb) {
212             // Notice this vector v and accum work with the original unclipped length.
213             SkVector v = pts[1] - pts[0];
214 
215             if (clip_line(pts, bounds, intervalLength, std::fmod(accum, intervalLength))) {
216                 // pts[0] may have just been changed by clip_line().
217                 // If that's not where we ended the previous lineTo(), we need to moveTo() there.
218                 SkPoint last;
219                 if (!dstPath->getLastPt(&last) || last != pts[0]) {
220                     dstPath->moveTo(pts[0]);
221                 }
222                 dstPath->lineTo(pts[1]);
223             }
224 
225             // We either just traveled v.fX horizontally or v.fY vertically.
226             SkASSERT(v.fX == 0 || v.fY == 0);
227             accum += SkScalarAbs(v.fX + v.fY);
228         }
229         return !dstPath->isEmpty();
230     }
231 
232     return false;
233 }
234 
235 class SpecialLineRec {
236 public:
init(const SkPath & src,SkPath * dst,SkStrokeRec * rec,int intervalCount,SkScalar intervalLength)237     bool init(const SkPath& src, SkPath* dst, SkStrokeRec* rec,
238               int intervalCount, SkScalar intervalLength) {
239         if (rec->isHairlineStyle() || !src.isLine(fPts)) {
240             return false;
241         }
242 
243         // can relax this in the future, if we handle square and round caps
244         if (SkPaint::kButt_Cap != rec->getCap()) {
245             return false;
246         }
247 
248         SkScalar pathLength = SkPoint::Distance(fPts[0], fPts[1]);
249 
250         fTangent = fPts[1] - fPts[0];
251         if (fTangent.isZero()) {
252             return false;
253         }
254 
255         fPathLength = pathLength;
256         fTangent.scale(sk_ieee_float_divide(1.0f, pathLength));
257         if (!SkIsFinite(fTangent.fX, fTangent.fY)) {
258             return false;
259         }
260         SkPointPriv::RotateCCW(fTangent, &fNormal);
261         fNormal.scale(SkScalarHalf(rec->getWidth()));
262 
263         // now estimate how many quads will be added to the path
264         //     resulting segments = pathLen * intervalCount / intervalLen
265         //     resulting points = 4 * segments
266 
267         SkScalar ptCount = pathLength * intervalCount / (float)intervalLength;
268         ptCount = std::min(ptCount, SkDashPath::kMaxDashCount);
269         if (SkIsNaN(ptCount)) {
270             return false;
271         }
272         int n = SkScalarCeilToInt(ptCount) << 2;
273         dst->incReserve(n);
274 
275         // we will take care of the stroking
276         rec->setFillStyle();
277         return true;
278     }
279 
addSegment(SkScalar d0,SkScalar d1,SkPath * path) const280     void addSegment(SkScalar d0, SkScalar d1, SkPath* path) const {
281         SkASSERT(d0 <= fPathLength);
282         // clamp the segment to our length
283         if (d1 > fPathLength) {
284             d1 = fPathLength;
285         }
286 
287         SkScalar x0 = fPts[0].fX + fTangent.fX * d0;
288         SkScalar x1 = fPts[0].fX + fTangent.fX * d1;
289         SkScalar y0 = fPts[0].fY + fTangent.fY * d0;
290         SkScalar y1 = fPts[0].fY + fTangent.fY * d1;
291 
292         SkPoint pts[4];
293         pts[0].set(x0 + fNormal.fX, y0 + fNormal.fY);   // moveTo
294         pts[1].set(x1 + fNormal.fX, y1 + fNormal.fY);   // lineTo
295         pts[2].set(x1 - fNormal.fX, y1 - fNormal.fY);   // lineTo
296         pts[3].set(x0 - fNormal.fX, y0 - fNormal.fY);   // lineTo
297 
298         path->addPoly(pts, std::size(pts), false);
299     }
300 
301 private:
302     SkPoint fPts[2];
303     SkVector fTangent;
304     SkVector fNormal;
305     SkScalar fPathLength;
306 };
307 
308 
InternalFilter(SkPath * dst,const SkPath & src,SkStrokeRec * rec,const SkRect * cullRect,const SkScalar aIntervals[],int32_t count,SkScalar initialDashLength,int32_t initialDashIndex,SkScalar intervalLength,SkScalar startPhase,StrokeRecApplication strokeRecApplication)309 bool SkDashPath::InternalFilter(SkPath* dst, const SkPath& src, SkStrokeRec* rec,
310                                 const SkRect* cullRect, const SkScalar aIntervals[],
311                                 int32_t count, SkScalar initialDashLength, int32_t initialDashIndex,
312                                 SkScalar intervalLength, SkScalar startPhase,
313                                 StrokeRecApplication strokeRecApplication) {
314     // we must always have an even number of intervals
315     SkASSERT(is_even(count));
316 
317     // we do nothing if the src wants to be filled
318     SkStrokeRec::Style style = rec->getStyle();
319     if (SkStrokeRec::kFill_Style == style || SkStrokeRec::kStrokeAndFill_Style == style) {
320         return false;
321     }
322 
323     const SkScalar* intervals = aIntervals;
324     SkScalar        dashCount = 0;
325     int             segCount = 0;
326 
327     SkPath cullPathStorage;
328     const SkPath* srcPtr = &src;
329     if (cull_path(src, *rec, cullRect, intervalLength, &cullPathStorage)) {
330         // if rect is closed, starts in a dash, and ends in a dash, add the initial join
331         // potentially a better fix is described here: bug.skia.org/7445
332         if (src.isRect(nullptr) && src.isLastContourClosed() && is_even(initialDashIndex)) {
333             SkScalar pathLength = SkPathMeasure(src, false, rec->getResScale()).getLength();
334             SkScalar endPhase = SkScalarMod(pathLength + startPhase, intervalLength);
335             int index = 0;
336             while (endPhase > intervals[index]) {
337                 endPhase -= intervals[index++];
338                 SkASSERT(index <= count);
339                 if (index == count) {
340                     // We have run out of intervals. endPhase "should" never get to this point,
341                     // but it could if the subtracts underflowed. Hence we will pin it as if it
342                     // perfectly ran through the intervals.
343                     // See crbug.com/875494 (and skbug.com/8274)
344                     endPhase = 0;
345                     break;
346                 }
347             }
348             // if dash ends inside "on", or ends at beginning of "off"
349             if (is_even(index) == (endPhase > 0)) {
350                 SkPoint midPoint = src.getPoint(0);
351                 // get vector at end of rect
352                 int last = src.countPoints() - 1;
353                 while (midPoint == src.getPoint(last)) {
354                     --last;
355                     SkASSERT(last >= 0);
356                 }
357                 // get vector at start of rect
358                 int next = 1;
359                 while (midPoint == src.getPoint(next)) {
360                     ++next;
361                     SkASSERT(next < last);
362                 }
363                 SkVector v = midPoint - src.getPoint(last);
364                 const SkScalar kTinyOffset = SK_ScalarNearlyZero;
365                 // scale vector to make start of tiny right angle
366                 v *= kTinyOffset;
367                 cullPathStorage.moveTo(midPoint - v);
368                 cullPathStorage.lineTo(midPoint);
369                 v = midPoint - src.getPoint(next);
370                 // scale vector to make end of tiny right angle
371                 v *= kTinyOffset;
372                 cullPathStorage.lineTo(midPoint - v);
373             }
374         }
375         srcPtr = &cullPathStorage;
376     }
377 
378     SpecialLineRec lineRec;
379     bool specialLine = (StrokeRecApplication::kAllow == strokeRecApplication) &&
380                        lineRec.init(*srcPtr, dst, rec, count >> 1, intervalLength);
381 
382     SkPathMeasure   meas(*srcPtr, false, rec->getResScale());
383 
384     do {
385         bool        skipFirstSegment = meas.isClosed();
386         bool        addedSegment = false;
387         SkScalar    length = meas.getLength();
388         int         index = initialDashIndex;
389 
390         // Since the path length / dash length ratio may be arbitrarily large, we can exert
391         // significant memory pressure while attempting to build the filtered path. To avoid this,
392         // we simply give up dashing beyond a certain threshold.
393         //
394         // The original bug report (http://crbug.com/165432) is based on a path yielding more than
395         // 90 million dash segments and crashing the memory allocator. A limit of 1 million
396         // segments seems reasonable: at 2 verbs per segment * 9 bytes per verb, this caps the
397         // maximum dash memory overhead at roughly 17MB per path.
398         dashCount += length * (count >> 1) / intervalLength;
399         if (dashCount > kMaxDashCount) {
400             dst->reset();
401             return false;
402         }
403 
404         // Using double precision to avoid looping indefinitely due to single precision rounding
405         // (for extreme path_length/dash_length ratios). See test_infinite_dash() unittest.
406         double  distance = 0;
407         double  dlen = initialDashLength;
408 
409         while (distance < length) {
410             SkASSERT(dlen >= 0);
411             addedSegment = false;
412             if (is_even(index) && !skipFirstSegment) {
413                 addedSegment = true;
414                 ++segCount;
415 
416                 if (specialLine) {
417                     lineRec.addSegment(SkDoubleToScalar(distance),
418                                        SkDoubleToScalar(distance + dlen),
419                                        dst);
420                 } else {
421                     meas.getSegment(SkDoubleToScalar(distance),
422                                     SkDoubleToScalar(distance + dlen),
423                                     dst, true);
424                 }
425             }
426             distance += dlen;
427 
428             // clear this so we only respect it the first time around
429             skipFirstSegment = false;
430 
431             // wrap around our intervals array if necessary
432             index += 1;
433             SkASSERT(index <= count);
434             if (index == count) {
435                 index = 0;
436             }
437 
438             // fetch our next dlen
439             dlen = intervals[index];
440         }
441 
442         // extend if we ended on a segment and we need to join up with the (skipped) initial segment
443         if (meas.isClosed() && is_even(initialDashIndex) &&
444             initialDashLength >= 0) {
445             meas.getSegment(0, initialDashLength, dst, !addedSegment);
446             ++segCount;
447         }
448     } while (meas.nextContour());
449 
450     // TODO: do we still need this?
451     if (segCount > 1) {
452         SkPathPriv::SetConvexity(*dst, SkPathConvexity::kConcave);
453     }
454 
455     return true;
456 }
457 
FilterDashPath(SkPath * dst,const SkPath & src,SkStrokeRec * rec,const SkRect * cullRect,const SkPathEffectBase::DashInfo & info)458 bool SkDashPath::FilterDashPath(SkPath* dst, const SkPath& src, SkStrokeRec* rec,
459                                 const SkRect* cullRect, const SkPathEffectBase::DashInfo& info) {
460     if (!ValidDashPath(info.fPhase, info.fIntervals, info.fCount)) {
461         return false;
462     }
463     SkScalar initialDashLength = 0;
464     int32_t initialDashIndex = 0;
465     SkScalar intervalLength = 0;
466     CalcDashParameters(info.fPhase, info.fIntervals, info.fCount,
467                        &initialDashLength, &initialDashIndex, &intervalLength);
468     return InternalFilter(dst, src, rec, cullRect, info.fIntervals, info.fCount, initialDashLength,
469                           initialDashIndex, intervalLength, info.fPhase);
470 }
471 
ValidDashPath(SkScalar phase,const SkScalar intervals[],int32_t count)472 bool SkDashPath::ValidDashPath(SkScalar phase, const SkScalar intervals[], int32_t count) {
473     if (count < 2 || !SkIsAlign2(count)) {
474         return false;
475     }
476     SkScalar length = 0;
477     for (int i = 0; i < count; i++) {
478         if (intervals[i] < 0) {
479             return false;
480         }
481         length += intervals[i];
482     }
483     // watch out for values that might make us go out of bounds
484     return length > 0 && SkIsFinite(phase, length);
485 }
486