Debian Codegraph @

src/core/SkPathBuilder.cpp

raw ◀ ▶
1 Debian patch touch this file
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 #include "include/core/SkPathBuilder.h"
9
10 #include "include/core/SkMatrix.h"
11 #include "include/core/SkPath.h"
12 #include "include/core/SkPathTypes.h"
13 #include "include/core/SkRRect.h"
14 #include "include/core/SkTypes.h"
15 #include "include/private/SkPathRef.h"
16 #include "include/private/base/SkAssert.h" // IWYU pragma: keep
17 #include "include/private/base/SkFloatingPoint.h"
18 #include "include/private/base/SkSafe32.h"
19 #include "include/private/base/SkTArray.h"
20 #include "include/private/base/SkTo.h"
21 #include "src/base/SkVx.h"
22 #include "src/core/SkGeometry.h"
23 #include "src/core/SkMatrixPriv.h"
24 #include "src/core/SkPathData.h"
25 #include "src/core/SkPathEnums.h"
26 #include "src/core/SkPathPriv.h"
27 #include "src/core/SkPathRawShapes.h"
28
29 #include <algorithm>
30 #include <cmath>
31 #include <cstdint>
32 #include <cstring>
33 #include <utility>
34
35 namespace {
36
37 void subdivide_cubic_to(SkPathBuilder* path, const SkPoint pts[4], int level = 2) {
38 if (--level >= 0) {
39 SkPoint tmp[7];
40
41 SkChopCubicAtHalf(pts, tmp);
42 subdivide_cubic_to(path, &tmp[0], level);
43 subdivide_cubic_to(path, &tmp[3], level);
44 } else {
45 path->cubicTo(pts[1], pts[2], pts[3]);
46 }
47 }
48
49 } // namespace
50
51 SkPathBuilder::SkPathBuilder() {
52 this->reset();
53 }
54
55 SkPathBuilder::SkPathBuilder(const SkPathBuilder&) = default;
56 SkPathBuilder& SkPathBuilder::operator=(const SkPathBuilder&) = default;
57 SkPathBuilder::SkPathBuilder(SkPathBuilder&&) = default;
58 SkPathBuilder& SkPathBuilder::operator=(SkPathBuilder&&) = default;
59 SkPathBuilder::~SkPathBuilder() = default;
60
61 SkPathBuilder::SkPathBuilder(SkPathFillType ft) {
62 this->reset();
63 fFillType = ft;
64 }
65
66 SkPathBuilder::SkPathBuilder(const SkPath& src) {
67 *this = src;
68 }
69
70 SkPathBuilder& SkPathBuilder::operator=(const SkPath& src) {
71 this->reset().setFillType(src.getFillType());
72 this->setIsVolatile(src.isVolatile());
73
74 if (src.isEmpty()) {
75 return *this;
76 }
77
78 this->addRaw(src.fPathData->raw(src.getFillType(), SkResolveConvexity::kYes));
79
80 // These are not part of SkPathRaw, so we set them separately
81 fLastMoveIndex = SkPathPriv::FindLastMoveToIndex(fVerbs, fPts.size());
82 SkASSERT(fLastMoveIndex < fPts.size());
83 fType = src.fPathData->fType;
84 fIsA = src.fPathData->fIsA;
85
86 return *this;
87 }
88
89 SkPathBuilder& SkPathBuilder::reset() {
90 fPts.clear();
91 fVerbs.clear();
92 fConicWeights.clear();
93 fFillType = SkPathFillType::kDefault;
94 fIsVolatile = false;
95
96 // these are internal state
97
98 fSegmentMask = 0;
99 fLastMoveIndex = -1; // illegal
100
101 fType = SkPathIsAType::kGeneral;
102 fConvexity = SkPathConvexity::kUnknown;
103
104 return *this;
105 }
106
107 bool SkPathBuilder::operator==(const SkPathBuilder& o) const {
108 // quick-accept
109 if (this == &o) {
110 return true;
111 }
112 // quick-reject
113 if (fSegmentMask != o.fSegmentMask || fFillType != o.fFillType) {
114 return false;
115 }
116 // deep compare
117 return fVerbs == o.fVerbs && fPts == o.fPts && fConicWeights == o.fConicWeights;
118 }
119
120 void SkPathBuilder::incReserve(int extraPtCount, int extraVbCount, int extraCnCount) {
121 fPts.reserve_exact(Sk32_sat_add(fPts.size(), extraPtCount));
122 fVerbs.reserve_exact(Sk32_sat_add(fVerbs.size(), extraVbCount));
123 fConicWeights.reserve_exact(Sk32_sat_add(fConicWeights.size(), extraCnCount));
124 }
125
126 std::tuple<SkPoint*, SkScalar*> SkPathBuilder::growForVerbsInPath(const SkPath& path) {
127 fSegmentMask |= path.getSegmentMasks();
128
129 const SkSpan<const SkPathVerb> verbs = path.verbs();
130 if (!verbs.empty()) {
131 // TODO(borenet): If the current builder is empty or JustMoves, we can use the type of the
132 // path. If the path is empty, we can keep the current type.
133 fType = SkPathIsAType::kGeneral;
134 fVerbs.push_back_n(verbs.size(), verbs.data());
135 }
136
137 SkPoint* pts = nullptr;
138 if (int numPts = path.countPoints()) {
139 pts = fPts.push_back_n(numPts);
140 }
141
142 SkScalar* weights = nullptr;
143 if (int numConics = path.conicWeights().size()) {
144 weights = fConicWeights.push_back_n(numConics);
145 }
146
147 return {pts, weights};
148 }
149
150 /*
151 * Some old behavior in SkPath -- should we keep it?
152 *
153 * After each edit (i.e. adding a verb)
154 this->setConvexityType(SkPathConvexity::kUnknown);
155 this->setFirstDirection(SkPathPriv::kUnknown_FirstDirection);
156 */
157
158 SkPathBuilder& SkPathBuilder::moveTo(SkPoint pt) {
159 if (!fVerbs.empty() && fVerbs.back() == SkPathVerb::kMove) {
160 fPts.back() = pt;
161
162 SkASSERT(fType != SkPathIsAType::kOval && fType != SkPathIsAType::kRRect);
163 SkASSERT(fConvexity == SkPathConvexity::kUnknown);
164 SkASSERT(fLastMoveIndex == SkToInt(fPts.size()) - 1);
165 } else {
166 fLastMoveIndex = SkToInt(fPts.size());
167
168 fPts.push_back(pt);
169 fVerbs.push_back(SkPathVerb::kMove);
170
171 if (fType == SkPathIsAType::kOval || fType == SkPathIsAType::kRRect) {
172 fType = SkPathIsAType::kGeneral;
173 }
174 fConvexity = SkPathConvexity::kUnknown;
175 }
176
177 return *this;
178 }
179
180 SkPathBuilder& SkPathBuilder::lineTo(SkPoint pt) {
181 this->ensureMove();
182
183 fPts.push_back(pt);
184 fVerbs.push_back(SkPathVerb::kLine);
185
186 fSegmentMask |= kLine_SkPathSegmentMask;
187 return *this;
188 }
189
190 SkPathBuilder& SkPathBuilder::quadTo(SkPoint pt1, SkPoint pt2) {
191 this->ensureMove();
192
193 SkPoint* p = fPts.push_back_n(2);
194 p[0] = pt1;
195 p[1] = pt2;
196 fVerbs.push_back(SkPathVerb::kQuad);
197
198 fSegmentMask |= kQuad_SkPathSegmentMask;
199 return *this;
200 }
201
202 SkPathBuilder& SkPathBuilder::conicTo(SkPoint pt1, SkPoint pt2, SkScalar w) {
203 this->ensureMove();
204
•205 if (w <= 0) {
206 return this->lineTo(pt2);
207 }
208 SkPoint* p = fPts.push_back_n(2);
209 p[0] = pt1;
210 p[1] = pt2;
211 if (w == 1) {
212 fVerbs.push_back(SkPathVerb::kQuad);
213 fSegmentMask |= kQuad_SkPathSegmentMask;
214 } else {
215 fVerbs.push_back(SkPathVerb::kConic);
216 fConicWeights.push_back(w);
217 fSegmentMask |= kConic_SkPathSegmentMask;
218 }
219
220 return *this;
221 }
222
223 SkPathBuilder& SkPathBuilder::cubicTo(SkPoint pt1, SkPoint pt2, SkPoint pt3) {
224 this->ensureMove();
225
226 SkPoint* p = fPts.push_back_n(3);
227 p[0] = pt1;
228 p[1] = pt2;
229 p[2] = pt3;
230 fVerbs.push_back(SkPathVerb::kCubic);
231
232 fSegmentMask |= kCubic_SkPathSegmentMask;
233 return *this;
234 }
235
236 SkPathBuilder& SkPathBuilder::close() {
237 // If this is a 2nd 'close', we just ignore it
238 if (!fVerbs.empty() && fVerbs.back() != SkPathVerb::kClose) {
239 this->ensureMove();
240 fVerbs.push_back(SkPathVerb::kClose);
241 }
242 return *this;
243 }
244
245 ///////////////////////////////////////////////////////////////////////////////////////////
246
247 SkPathBuilder& SkPathBuilder::rMoveTo(SkVector pt) {
248 SkPoint lastPt = {0,0}; // in case we're empty
249 if (!fPts.empty()) {
250 SkASSERT(fLastMoveIndex >= 0);
251 if (fVerbs.back() == SkPathVerb::kClose) {
252 lastPt = fPts[fLastMoveIndex];
253 } else {
254 lastPt = fPts.back();
255 }
256 }
257 return this->moveTo(lastPt + pt);
258 }
259
260 SkPathBuilder& SkPathBuilder::rLineTo(SkVector p1) {
261 this->ensureMove();
262 return this->lineTo(fPts.back() + p1);
263 }
264
265 SkPathBuilder& SkPathBuilder::rQuadTo(SkVector p1, SkVector p2) {
266 this->ensureMove();
267 SkPoint base = fPts.back();
268 return this->quadTo(base + p1, base + p2);
269 }
270
271 SkPathBuilder& SkPathBuilder::rConicTo(SkVector p1, SkVector p2, SkScalar w) {
272 this->ensureMove();
273 SkPoint base = fPts.back();
274 return this->conicTo(base + p1, base + p2, w);
275 }
276
277 SkPathBuilder& SkPathBuilder::rCubicTo(SkVector p1, SkVector p2, SkVector p3) {
278 this->ensureMove();
279 SkPoint base = fPts.back();
280 return this->cubicTo(base + p1, base + p2, base + p3);
281 }
282
283 ///////////////////////////////////////////////////////////////////////////////////////////
284
285 SkPath SkPathBuilder::snapshot(const SkMatrix* mx) const {
286 if (!mx) {
287 mx = &SkMatrix::I();
288 }
289
290 sk_sp<SkPathData> pdata;
291 if (auto raw = SkPathPriv::Raw(*this, SkResolveConvexity::kNo)) {
292 pdata = SkPathData::MakeTransform(*raw, *mx);
293 }
294 if (pdata && fType != SkPathIsAType::kGeneral) {
295 pdata->setupIsA(fType, fIsA.fDirection, fIsA.fStartIndex);
296 }
297 return SkPath::MakeNullCheck(std::move(pdata), fFillType, fIsVolatile);
298 }
299
300 SkPath SkPathBuilder::detach(const SkMatrix* mx) {
301 auto path = this->snapshot(mx);
302 this->reset();
303 return path;
304 }
305
306 ///////////////////////////////////////////////////////////////////////////////////////////////////
307
308 sk_sp<SkPathData> SkPathBuilder::snapshotData() const {
309 if (fVerbs.size() <= 1) {
310 return SkPathData::Empty();
311 }
312
313 switch (fType) {
314 case SkPathIsAType::kGeneral:
315 break;
316 case SkPathIsAType::kOval:
317 if (auto r = SkRect::Bounds(fPts)) {
318 return SkPathData::Oval(*r, fIsA.fDirection, fIsA.fStartIndex);
319 }
320 return nullptr;
321 case SkPathIsAType::kRRect:
322 if (auto r = SkRect::Bounds(fPts)) {
323 return SkPathData::RRect(SkPathPriv::DeduceRRectFromContour(*r, fPts, fVerbs),
324 fIsA.fDirection, fIsA.fStartIndex);
325 }
326 return nullptr;
327 }
328 SkASSERT(fType == SkPathIsAType::kGeneral);
329
330 return SkPathData::Make(fPts, fVerbs, fConicWeights);
331 }
332
333 sk_sp<SkPathData> SkPathBuilder::detachData() {
334 auto data = this->snapshotData();
335 this->reset();
336 return data;
337 }
338
339 ///////////////////////////////////////////////////////////////////////////////////////////////////
340
341 static bool arc_is_lone_point(const SkRect& oval, SkScalar startAngle, SkScalar sweepAngle,
342 SkPoint* pt) {
343 if (0 == sweepAngle && (0 == startAngle || SkIntToScalar(360) == startAngle)) {
344 // Chrome uses this path to move into and out of ovals. If not
345 // treated as a special case the moves can distort the oval's
346 // bounding box (and break the circle special case).
347 pt->set(oval.fRight, oval.centerY());
348 return true;
349 } else if (0 == oval.width() && 0 == oval.height()) {
350 // Chrome will sometimes create 0 radius round rects. Having degenerate
351 // quad segments in the path prevents the path from being recognized as
352 // a rect.
353 // TODO: optimizing the case where only one of width or height is zero
354 // should also be considered. This case, however, doesn't seem to be
355 // as common as the single point case.
356 pt->set(oval.fRight, oval.fTop);
357 return true;
358 }
359 return false;
360 }
361
362 // Return the unit vectors pointing at the start/stop points for the given start/sweep angles
363 //
364 static void angles_to_unit_vectors(SkScalar startAngle, SkScalar sweepAngle,
365 SkVector* startV, SkVector* stopV, SkPathDirection* dir) {
366 SkScalar startRad = SkDegreesToRadians(startAngle),
367 stopRad = SkDegreesToRadians(startAngle + sweepAngle);
368
369 startV->fY = SkScalarSinSnapToZero(startRad);
370 startV->fX = SkScalarCosSnapToZero(startRad);
371 stopV->fY = SkScalarSinSnapToZero(stopRad);
372 stopV->fX = SkScalarCosSnapToZero(stopRad);
373
374 /* If the sweep angle is nearly (but less than) 360, then due to precision
375 loss in radians-conversion and/or sin/cos, we may end up with coincident
376 vectors, which will fool SkBuildQuadArc into doing nothing (bad) instead
377 of drawing a nearly complete circle (good).
378 e.g. canvas.drawArc(0, 359.99, ...)
379 -vs- canvas.drawArc(0, 359.9, ...)
380 We try to detect this edge case, and tweak the stop vector
381 */
382 if (*startV == *stopV) {
383 SkScalar sw = SkScalarAbs(sweepAngle);
384 if (sw < SkIntToScalar(360) && sw > SkIntToScalar(359)) {
385 // make a guess at a tiny angle (in radians) to tweak by
386 SkScalar deltaRad = SkScalarCopySign(SK_Scalar1/512, sweepAngle);
387 // not sure how much will be enough, so we use a loop
388 do {
389 stopRad -= deltaRad;
390 stopV->fY = SkScalarSinSnapToZero(stopRad);
391 stopV->fX = SkScalarCosSnapToZero(stopRad);
392 } while (*startV == *stopV);
393 }
394 }
395 *dir = sweepAngle > 0 ? SkPathDirection::kCW : SkPathDirection::kCCW;
396 }
397
398 /**
399 * If this returns 0, then the caller should just line-to the singlePt, else it should
400 * ignore singlePt and append the specified number of conics.
401 */
402 static int build_arc_conics(const SkRect& oval, const SkVector& start, const SkVector& stop,
403 SkPathDirection dir, SkConic conics[SkConic::kMaxConicsForArc],
404 SkPoint* singlePt) {
405 SkMatrix matrix;
406
407 matrix.setScale(SkScalarHalf(oval.width()), SkScalarHalf(oval.height()));
408 matrix.postTranslate(oval.centerX(), oval.centerY());
409
410 int count = SkConic::BuildUnitArc(start, stop, dir, &matrix, conics);
411 if (0 == count) {
412 *singlePt = matrix.mapPoint(stop);
413 }
414 return count;
415 }
416
417 static bool nearly_equal(const SkPoint& a, const SkPoint& b) {
418 return SkScalarNearlyEqual(a.fX, b.fX)
419 && SkScalarNearlyEqual(a.fY, b.fY);
420 }
421
422 SkPathBuilder& SkPathBuilder::arcTo(const SkRect& oval, SkScalar startAngle, SkScalar sweepAngle,
423 bool forceMoveTo) {
424 if (oval.width() < 0 || oval.height() < 0) {
425 return *this;
426 }
427
428 startAngle = SkScalarMod(startAngle, 360.0f);
429
430 if (fVerbs.empty()) {
431 forceMoveTo = true;
432 }
433
434 SkPoint lonePt;
435 if (arc_is_lone_point(oval, startAngle, sweepAngle, &lonePt)) {
436 return forceMoveTo ? this->moveTo(lonePt) : this->lineTo(lonePt);
437 }
438
439 SkVector startV, stopV;
440 SkPathDirection dir;
441 angles_to_unit_vectors(startAngle, sweepAngle, &startV, &stopV, &dir);
442
443 SkPoint singlePt;
444
445 // Adds a move-to to 'pt' if forceMoveTo is true. Otherwise a lineTo unless we're sufficiently
446 // close to 'pt' currently. This prevents spurious lineTos when adding a series of contiguous
447 // arcs from the same oval.
448 auto addPt = [forceMoveTo, this](const SkPoint& pt) {
449 if (forceMoveTo) {
450 this->moveTo(pt);
451 } else if (!nearly_equal(fPts.back(), pt)) {
452 this->lineTo(pt);
453 }
454 };
455
456 // At this point, we know that the arc is not a lone point, but startV == stopV
457 // indicates that the sweepAngle is too small such that angles_to_unit_vectors
458 // cannot handle it.
459 if (startV == stopV) {
460 SkScalar endAngle = SkDegreesToRadians(startAngle + sweepAngle);
461 SkScalar radiusX = oval.width() / 2;
462 SkScalar radiusY = oval.height() / 2;
463 // We do not use SkScalar[Sin|Cos]SnapToZero here. When sin(startAngle) is 0 and sweepAngle
464 // is very small and radius is huge, the expected behavior here is to draw a line. But
465 // calling SkScalarSinSnapToZero will make sin(endAngle) be 0 which will then draw a dot.
466 singlePt.set(oval.centerX() + radiusX * SkScalarCos(endAngle),
467 oval.centerY() + radiusY * SkScalarSin(endAngle));
468 addPt(singlePt);
469 return *this;
470 }
471
472 SkConic conics[SkConic::kMaxConicsForArc];
473 int count = build_arc_conics(oval, startV, stopV, dir, conics, &singlePt);
474 if (count) {
475 this->incReserve(count * 2 + 1);
476 const SkPoint& pt = conics[0].fPts[0];
477 addPt(pt);
478 for (int i = 0; i < count; ++i) {
479 this->conicTo(conics[i].fPts[1], conics[i].fPts[2], conics[i].fW);
480 }
481 } else {
482 addPt(singlePt);
483 }
484 return *this;
485 }
486
487 SkPathBuilder& SkPathBuilder::rArcTo(SkPoint r, SkScalar xAxisRotate, ArcSize largeArc,
488 SkPathDirection sweep, SkVector dxdy) {
489 const SkPoint currentPoint = this->getLastPt().value_or(SkPoint{0, 0});
490 return this->arcTo(r, xAxisRotate, largeArc, sweep, currentPoint + dxdy);
491 }
492
493 SkPathBuilder& SkPathBuilder::addArc(const SkRect& oval, SkScalar startAngle, SkScalar sweepAngle) {
494 if (oval.isEmpty() || 0 == sweepAngle) {
495 return *this;
496 }
497
498 const SkScalar kFullCircleAngle = SkIntToScalar(360);
499
500 if (sweepAngle >= kFullCircleAngle || sweepAngle <= -kFullCircleAngle) {
501 // We can treat the arc as an oval if it begins at one of our legal starting positions.
502 // See SkPath::addOval() docs.
503 SkScalar startOver90 = startAngle / 90.f;
504 SkScalar startOver90I = SkScalarRoundToScalar(startOver90);
505 SkScalar error = startOver90 - startOver90I;
506 if (SkScalarNearlyEqual(error, 0)) {
507 // Index 1 is at startAngle == 0.
508 SkScalar startIndex = std::fmod(startOver90I + 1.f, 4.f);
509 startIndex = startIndex < 0 ? startIndex + 4.f : startIndex;
510 return this->addOval(oval, sweepAngle > 0 ? SkPathDirection::kCW : SkPathDirection::kCCW,
511 (unsigned) startIndex);
512 }
513 }
514 return this->arcTo(oval, startAngle, sweepAngle, true);
515 }
516
517 SkPathBuilder& SkPathBuilder::arcTo(SkPoint p1, SkPoint p2, SkScalar radius) {
518 this->ensureMove();
519
520 if (radius == 0) {
521 return this->lineTo(p1);
522 }
523
524 // need to know our prev pt so we can construct tangent vectors
525 SkPoint start = fPts.back();
526
527 // need double precision for these calcs.
528 skvx::double2 befored = normalize(skvx::double2{p1.fX - start.fX, p1.fY - start.fY});
529 skvx::double2 afterd = normalize(skvx::double2{p2.fX - p1.fX, p2.fY - p1.fY});
530 double cosh = dot(befored, afterd);
531 double sinh = cross(befored, afterd);
532
533 // If the previous point equals the first point, befored will be denormalized.
534 // If the two points equal, afterd will be denormalized.
535 // If the second point equals the first point, sinh will be zero.
536 // In all these cases, we cannot construct an arc, so we construct a line to the first point.
537 if (!isfinite(befored) || !isfinite(afterd) || SkScalarNearlyZero(SkDoubleToScalar(sinh))) {
538 return this->lineTo(p1);
539 }
540
541 // safe to convert back to floats now
542 SkScalar dist = SkScalarAbs(SkDoubleToScalar(radius * (1 - cosh) / sinh));
543 SkScalar xx = p1.fX - dist * befored[0];
544 SkScalar yy = p1.fY - dist * befored[1];
545
546 SkVector after = SkVector::Make(afterd[0], afterd[1]);
547 after.setLength(dist);
548 this->lineTo(xx, yy);
549 SkScalar weight = SkScalarSqrt(SkDoubleToScalar(SK_ScalarHalf + cosh * 0.5));
550 return this->conicTo(p1, p1 + after, weight);
551 }
552
553 // This converts the SVG arc to conics.
554 // Partly adapted from Niko's code in kdelibs/kdecore/svgicons.
555 // Then transcribed from webkit/chrome's SVGPathNormalizer::decomposeArcToCubic()
556 // See also SVG implementation notes:
557 // http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
558 // Note that arcSweep bool value is flipped from the original implementation.
559 SkPathBuilder& SkPathBuilder::arcTo(SkPoint rad, SkScalar angle, SkPathBuilder::ArcSize arcLarge,
560 SkPathDirection arcSweep, SkPoint endPt) {
561 this->ensureMove();
562
563 const SkPoint srcPts[2] = { fPts.back(), endPt };
564
565 // If rx = 0 or ry = 0 then this arc is treated as a straight line segment (a "lineto")
566 // joining the endpoints.
567 // http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters
568 if (!rad.fX || !rad.fY) {
569 return this->lineTo(endPt);
570 }
571 // If the current point and target point for the arc are identical, it should be treated as a
572 // zero length path. This ensures continuity in animations.
573 if (srcPts[0] == srcPts[1]) {
574 return this->lineTo(endPt);
575 }
576 SkScalar rx = SkScalarAbs(rad.fX);
577 SkScalar ry = SkScalarAbs(rad.fY);
578 SkVector midPointDistance = srcPts[0] - srcPts[1];
579 midPointDistance *= 0.5f;
580
581 SkMatrix pointTransform;
582 pointTransform.setRotate(-angle);
583
584 SkPoint transformedMidPoint = pointTransform.mapPoint(midPointDistance);
585 SkScalar squareRx = rx * rx;
586 SkScalar squareRy = ry * ry;
587 SkScalar squareX = transformedMidPoint.fX * transformedMidPoint.fX;
588 SkScalar squareY = transformedMidPoint.fY * transformedMidPoint.fY;
589
590 // Check if the radii are big enough to draw the arc, scale radii if not.
591 // http://www.w3.org/TR/SVG/implnote.html#ArcCorrectionOutOfRangeRadii
592 SkScalar radiiScale = squareX / squareRx + squareY / squareRy;
593 if (radiiScale > 1) {
594 radiiScale = SkScalarSqrt(radiiScale);
595 rx *= radiiScale;
596 ry *= radiiScale;
597 }
598
599 pointTransform.setScale(1 / rx, 1 / ry);
600 pointTransform.preRotate(-angle);
601
602 SkPoint unitPts[2];
603 pointTransform.mapPoints(unitPts, srcPts);
604 SkVector delta = unitPts[1] - unitPts[0];
605
606 SkScalar d = delta.fX * delta.fX + delta.fY * delta.fY;
607 SkScalar scaleFactorSquared = std::max(1 / d - 0.25f, 0.f);
608
609 SkScalar scaleFactor = SkScalarSqrt(scaleFactorSquared);
610 if ((arcSweep == SkPathDirection::kCCW) != SkToBool(arcLarge)) { // flipped from the original implementation
611 scaleFactor = -scaleFactor;
612 }
613 delta.scale(scaleFactor);
614 SkPoint centerPoint = unitPts[0] + unitPts[1];
615 centerPoint *= 0.5f;
616 centerPoint.offset(-delta.fY, delta.fX);
617 unitPts[0] -= centerPoint;
618 unitPts[1] -= centerPoint;
619 SkScalar theta1 = SkScalarATan2(unitPts[0].fY, unitPts[0].fX);
620 SkScalar theta2 = SkScalarATan2(unitPts[1].fY, unitPts[1].fX);
621 SkScalar thetaArc = theta2 - theta1;
622 if (thetaArc < 0 && (arcSweep == SkPathDirection::kCW)) { // arcSweep flipped from the original implementation
623 thetaArc += SK_ScalarPI * 2;
624 } else if (thetaArc > 0 && (arcSweep != SkPathDirection::kCW)) { // arcSweep flipped from the original implementation
625 thetaArc -= SK_ScalarPI * 2;
626 }
627
628 // Very tiny angles cause our subsequent math to go wonky (skbug.com/40040578)
629 // so we do a quick check here. The precise tolerance amount is just made up.
630 // PI/million happens to fix the bug in 9272, but a larger value is probably
631 // ok too.
632 if (SkScalarAbs(thetaArc) < (SK_ScalarPI / (1000 * 1000))) {
633 return this->lineTo(endPt);
634 }
635
636 pointTransform.setRotate(angle);
637 pointTransform.preScale(rx, ry);
638
639 // the arc may be slightly bigger than 1/4 circle, so allow up to 1/3rd
640 int segments = SkScalarCeilToInt(SkScalarAbs(thetaArc / (2 * SK_ScalarPI / 3)));
641 SkScalar thetaWidth = thetaArc / segments;
642 SkScalar t = SkScalarTan(0.5f * thetaWidth);
643 if (!SkIsFinite(t)) {
644 return *this;
645 }
646 SkScalar startTheta = theta1;
647 SkScalar w = SkScalarSqrt(SK_ScalarHalf + SkScalarCos(thetaWidth) * SK_ScalarHalf);
648 auto scalar_is_integer = [](SkScalar scalar) -> bool {
649 return scalar == SkScalarFloorToScalar(scalar);
650 };
651 bool expectIntegers = SkScalarNearlyZero(SK_ScalarPI/2 - SkScalarAbs(thetaWidth)) &&
652 scalar_is_integer(rx) && scalar_is_integer(ry) &&
653 scalar_is_integer(endPt.fX) && scalar_is_integer(endPt.fY);
654
655 for (int i = 0; i < segments; ++i) {
656 SkScalar endTheta = startTheta + thetaWidth,
657 sinEndTheta = SkScalarSinSnapToZero(endTheta),
658 cosEndTheta = SkScalarCosSnapToZero(endTheta);
659
660 unitPts[1].set(cosEndTheta, sinEndTheta);
661 unitPts[1] += centerPoint;
662 unitPts[0] = unitPts[1];
663 unitPts[0].offset(t * sinEndTheta, -t * cosEndTheta);
664 SkPoint mapped[2];
665 pointTransform.mapPoints(mapped, unitPts);
666 /*
667 Computing the arc width introduces rounding errors that cause arcs to start
668 outside their marks. A round rect may lose convexity as a result. If the input
669 values are on integers, place the conic on integers as well.
670 */
671 if (expectIntegers) {
672 for (SkPoint& point : mapped) {
673 point.fX = SkScalarRoundToScalar(point.fX);
674 point.fY = SkScalarRoundToScalar(point.fY);
675 }
676 }
677 this->conicTo(mapped[0], mapped[1], w);
678 startTheta = endTheta;
679 }
680
681 // The final point should match the input point (by definition); replace it to
682 // ensure that rounding errors in the above math don't cause any problems.
683 fPts.back() = endPt;
684 return *this;
685 }
686
687 ///////////////////////////////////////////////////////////////////////////////////////////
688
689 SkPathIter SkPathBuilder::iter() const {
690 return SkPathIter(fPts, fVerbs, fConicWeights);
691 }
692
693 SkPathBuilder& SkPathBuilder::addRaw(const SkPathRaw& raw) {
694 this->incReserve(raw.points().size(), raw.verbs().size(), raw.conics().size());
695
696 for (auto iter = raw.iter(); auto rec = iter.next();) {
697 const auto pts = rec->fPoints;
698 switch (rec->fVerb) {
699 case SkPathVerb::kMove: this->moveTo( pts[0]); break;
700 case SkPathVerb::kLine: this->lineTo( pts[1]); break;
701 case SkPathVerb::kQuad: this->quadTo( pts[1], pts[2]); break;
702 case SkPathVerb::kConic: this->conicTo(pts[1], pts[2], rec->fConicWeight); break;
703 case SkPathVerb::kCubic: this->cubicTo(pts[1], pts[2], pts[3]); break;
704 case SkPathVerb::kClose: this->close(); break;
705 }
706 }
707
708 auto has_trailing_move = [](SkSpan<const SkPathVerb> vbs) {
709 return vbs.size() > 0 && vbs.back() == SkPathVerb::kMove;
710 };
711
712 // if the iterator 'trimmed' off a trialing move, we restore it here
713 if (has_trailing_move(raw.verbs()) && !has_trailing_move(this->verbs())) {
714 this->moveTo(raw.points().back());
715 }
716
717 return *this;
718 }
719
720 SkPathBuilder& SkPathBuilder::addRect(const SkRect& rect, SkPathDirection dir, unsigned index) {
721 const bool wasEmpty = (fSegmentMask == 0);
722
723 this->addRaw(SkPathRawShapes::Rect(rect, dir, index));
724
725 if (wasEmpty) {
726 // now we're a rect
727 fConvexity = SkPathDirection_ToConvexity(dir);
728 }
729 return *this;
730 }
731
732 SkPathBuilder& SkPathBuilder::addOval(const SkRect& oval, SkPathDirection dir, unsigned index) {
733 const bool wasEmpty = (fSegmentMask == 0);
734
735 this->addRaw(SkPathRawShapes::Oval(oval, dir, index));
736
737 if (wasEmpty) {
738 fType = SkPathIsAType::kOval;
739 fIsA.fDirection = dir;
740 fIsA.fStartIndex = index % 4;
741 fConvexity = SkPathDirection_ToConvexity(dir);
742 }
743
744 return *this;
745 }
746
747 SkPathBuilder& SkPathBuilder::addRRect(const SkRRect& rrect, SkPathDirection dir, unsigned index) {
748 const SkRect& bounds = rrect.getBounds();
749
750 auto [asType, newIndex] = SkPathPriv::SimplifyRRect(rrect, index);
751 switch (asType) {
752 case SkPathPriv::RRectAsEnum::kRect:
753 return this->addRect(bounds, dir, newIndex);
754 case SkPathPriv::RRectAsEnum::kOval:
755 return this->addOval(bounds, dir, newIndex);
756 case SkPathPriv::RRectAsEnum::kRRect:
757 // fall through ...
758 break;
759 }
760
761 const bool wasEmpty = (fSegmentMask == 0);
762
763 this->addRaw(SkPathRawShapes::RRect(rrect, dir, index));
764
765 if (wasEmpty) {
766 fType = SkPathIsAType::kRRect;
767 fIsA.fDirection = dir;
768 fIsA.fStartIndex = index % 8;
769 fConvexity = SkPathDirection_ToConvexity(dir);
770 }
771 return *this;
772 }
773
774 SkPathBuilder& SkPathBuilder::addCircle(SkPoint center, float r, SkPathDirection dir) {
775 if (r >= 0) {
776 this->addOval(SkRect::MakeLTRB(center.fX - r, center.fY - r, center.fX + r, center.fY + r),
777 dir);
778 }
779 return *this;
780 }
781
782 SkPathBuilder& SkPathBuilder::addPolygon(SkSpan<const SkPoint> pts, bool isClosed) {
783 if (pts.empty()) {
784 return *this;
785 }
786
787 this->moveTo(pts[0]);
788 this->polylineTo(pts.last(pts.size() - 1));
789 if (isClosed) {
790 this->close();
791 }
792 return *this;
793 }
794
795 SkPathBuilder& SkPathBuilder::polylineTo(SkSpan<const SkPoint> pts) {
796 if (!pts.empty()) {
797 this->ensureMove();
798
799 const auto count = pts.size();
800 this->incReserve(count, count, 0);
801 memcpy(fPts.push_back_n(count), pts.data(), count * sizeof(SkPoint));
802 memset(fVerbs.push_back_n(count), (uint8_t)SkPathVerb::kLine, count);
803 fSegmentMask |= kLine_SkPathSegmentMask;
804 }
805 return *this;
806 }
807
808 //////////////////////////////////////////////////////////////////////////////////////////////////
809
810 SkPathBuilder& SkPathBuilder::offset(SkScalar dx, SkScalar dy) {
811 for (auto& p : fPts) {
812 p += {dx, dy};
813 }
814 return *this;
815 }
816
817 SkPathBuilder& SkPathBuilder::addPath(const SkPath& path, SkScalar dx, SkScalar dy,
818 SkPath::AddPathMode mode) {
819 SkMatrix matrix = SkMatrix::Translate(dx, dy);
820 return this->addPath(path, matrix, mode);
821 }
822
823 SkPathBuilder& SkPathBuilder::addPath(const SkPath& src, const SkMatrix& matrix,
824 SkPath::AddPathMode mode) {
825 if (src.isEmpty()) {
826 return *this;
827 }
828
829 const bool canReplaceThis = (mode == SkPath::AddPathMode::kAppend_AddPathMode &&
830 this->verbs().size() <= 1)
831 || this->verbs().empty();
832 if (canReplaceThis && matrix.isIdentity()) {
833 const SkPathFillType fillType = fFillType;
834 *this = src;
835 fFillType = fillType;
836 return *this;
837 }
838
839 // We're about to append - clear convexity.
840 fConvexity = SkPathConvexity::kUnknown;
841
842 if (SkPath::AddPathMode::kAppend_AddPathMode == mode && !matrix.hasPerspective()) {
843 const int lastMoveToIndex = SkPathPriv::FindLastMoveToIndex(src.verbs(), src.points().size());
844 SkASSERT(lastMoveToIndex >= 0);
845 fLastMoveIndex = lastMoveToIndex + this->countPoints();
846
847 auto [newPts, newWeights] = this->growForVerbsInPath(src);
848 const size_t count = src.points().size();
849 matrix.mapPoints({newPts, count}, src.points());
850 if (auto conics = src.conicWeights(); !conics.empty()) {
851 memcpy(newWeights, conics.data(), conics.size_bytes());
852 }
853 return *this;
854 }
855
856 SkMatrixPriv::MapPtsProc mapPtsProc = SkMatrixPriv::GetMapPtsProc(matrix);
857 bool firstVerb = true;
858 for (auto [verb, pts, w] : SkPathPriv::Iterate(src)) {
859 SkPoint mappedPts[3];
860 switch (verb) {
861 case SkPathVerb::kMove:
862 mapPtsProc(matrix, mappedPts, &pts[0], 1);
863 if (firstVerb && mode == SkPath::kExtend_AddPathMode && !isEmpty()) {
864 this->ensureMove(); // In case last contour is closed
865 std::optional<SkPoint> lastPt = this->getLastPt();
866 // don't add lineTo if it is degenerate
867 if (!lastPt.has_value() || lastPt.value() != mappedPts[0]) {
868 this->lineTo(mappedPts[0]);
869 }
870 } else {
871 this->moveTo(mappedPts[0]);
872 }
873 break;
874 case SkPathVerb::kLine:
875 mapPtsProc(matrix, mappedPts, &pts[1], 1);
876 this->lineTo(mappedPts[0]);
877 break;
878 case SkPathVerb::kQuad:
879 mapPtsProc(matrix, mappedPts, &pts[1], 2);
880 this->quadTo(mappedPts[0], mappedPts[1]);
881 break;
882 case SkPathVerb::kConic:
883 mapPtsProc(matrix, mappedPts, &pts[1], 2);
884 this->conicTo(mappedPts[0], mappedPts[1], *w);
885 break;
886 case SkPathVerb::kCubic:
887 mapPtsProc(matrix, mappedPts, &pts[1], 3);
888 this->cubicTo(mappedPts[0], mappedPts[1], mappedPts[2]);
889 break;
890 case SkPathVerb::kClose:
891 this->close();
892 break;
893 }
894 firstVerb = false;
895 }
896 return *this;
897 }
898
899 // ignore the last point of the 1st contour
900 SkPathBuilder& SkPathBuilder::privateReversePathTo(const SkPath& path) {
901 auto verbSpan = path.verbs();
902 if (verbSpan.empty()) {
903 return *this;
904 }
905
906 auto verbs = verbSpan.end();
907 auto verbsBegin = verbSpan.begin();
908 auto pts = path.points().end() - 1;
909 auto conicWeights = path.conicWeights().end();
910
911 while (verbs > verbsBegin) {
912 SkPathVerb v = *--verbs;
913 pts -= SkPathPriv::PtsInVerb(v);
914 switch (v) {
915 case SkPathVerb::kMove:
916 // if the path has multiple contours, stop after reversing the last
917 return *this;
918 case SkPathVerb::kLine:
919 this->lineTo(pts[0]);
920 break;
921 case SkPathVerb::kQuad:
922 this->quadTo(pts[1], pts[0]);
923 break;
924 case SkPathVerb::kConic:
925 this->conicTo(pts[1], pts[0], *--conicWeights);
926 break;
927 case SkPathVerb::kCubic:
928 this->cubicTo(pts[2], pts[1], pts[0]);
929 break;
930 case SkPathVerb::kClose:
931 break;
932 }
933 }
934 return *this;
935 }
936
937 SkPathBuilder& SkPathBuilder::privateReverseAddPath(const SkPath& src) {
938 auto verbSpan = src.verbs();
939 if (verbSpan.empty()) {
940 return *this;
941 }
942
943 auto verbs = verbSpan.end();
944 auto verbsBegin = verbSpan.begin();
945 auto pts = src.points().end();
946 auto conicWeights = src.conicWeights().end();
947
948 bool needMove = true;
949 bool needClose = false;
950 while (verbs > verbsBegin) {
951 SkPathVerb v = *--verbs;
952 int n = SkPathPriv::PtsInVerb(v);
953
954 if (needMove) {
955 --pts;
956 this->moveTo(pts->fX, pts->fY);
957 needMove = false;
958 }
959 pts -= n;
960 switch ((SkPathVerb)v) {
961 case SkPathVerb::kMove:
962 if (needClose) {
963 this->close();
964 needClose = false;
965 }
966 needMove = true;
967 pts += 1; // so we see the point in "if (needMove)" above
968 break;
969 case SkPathVerb::kLine:
970 this->lineTo(pts[0]);
971 break;
972 case SkPathVerb::kQuad:
973 this->quadTo(pts[1], pts[0]);
974 break;
975 case SkPathVerb::kConic:
976 this->conicTo(pts[1], pts[0], *--conicWeights);
977 break;
978 case SkPathVerb::kCubic:
979 this->cubicTo(pts[2], pts[1], pts[0]);
980 break;
981 case SkPathVerb::kClose:
982 needClose = true;
983 break;
984 }
985 }
986 return *this;
987 }
988
989 std::optional<SkPoint> SkPathBuilder::getLastPt() const {
990 size_t count = this->fPts.size();
991 if (count > 0) {
992 return this->fPts.at(count - 1);
993 }
994 return std::nullopt;
995 }
996
997 #ifdef SK_SUPPORT_LEGACY_PATHBUILDER_SETLASTPT
998 void SkPathBuilder::setLastPt(SkPoint pt) {
999 size_t count = fPts.size();
1000 if (count == 0) {
1001 this->moveTo(pt);
1002 } else {
1003 this->setPoint(count - 1, pt);
1004 }
1005 }
1006 #endif
1007
1008 void SkPathBuilder::setPoint(size_t index, SkPoint p) {
1009 if (index < (size_t)fPts.size()) {
1010 fPts[index] = p;
1011 fType = SkPathIsAType::kGeneral;
1012 }
1013 }
1014
1015 SkPathBuilder& SkPathBuilder::transform(const SkMatrix& matrix) {
1016 if (matrix.isIdentity() || this->isEmpty()) {
1017 return *this;
1018 }
1019
1020 if (matrix.hasPerspective()) {
1021 SkPath src = this->detach();
1022
1023 // remember this from before the detach()
1024 this->setFillType(src.getFillType());
1025
1026 SkPath clipped;
1027 if (SkPathPriv::PerspectiveClip(src, matrix, &clipped)) {
1028 src = std::move(clipped);
1029 }
1030
1031 for (auto [verb, pts, wt] : SkPathPriv::Iterate(src)) {
1032 switch (verb) {
1033 case SkPathVerb::kMove:
1034 this->moveTo(pts[0]);
1035 break;
1036 case SkPathVerb::kLine:
1037 this->lineTo(pts[1]);
1038 break;
1039 case SkPathVerb::kQuad:
1040 // promote the quad to a conic
1041 this->conicTo(pts[1], pts[2], SkConic::TransformW(pts, SK_Scalar1, matrix));
1042 break;
1043 case SkPathVerb::kConic:
1044 this->conicTo(pts[1], pts[2], SkConic::TransformW(pts, wt[0], matrix));
1045 break;
1046 case SkPathVerb::kCubic:
1047 subdivide_cubic_to(this, pts);
1048 break;
1049 case SkPathVerb::kClose:
1050 this->close();
1051 break;
1052 }
1053 }
1054 } else {
1055
1056 // Can we maintain our special case shape?
1057 if (!matrix.rectStaysRect() || !SkPathPriv::IsAxisAligned(fPts)) {
1058 fType = SkPathIsAType::kGeneral;
1059 // lose convexity (just to be numerically safe)
1060 if (SkPathConvexity_IsConvex(fConvexity)) {
1061 fConvexity = SkPathConvexity::kUnknown;
1062 }
1063 }
1064
1065 // If we're still a special case, check if we need to reverse our winding
1066 if (fType == SkPathIsAType::kOval || fType == SkPathIsAType::kRRect) {
1067 auto [dir, start] =
1068 SkPathPriv::TransformDirAndStart(matrix, fType == SkPathIsAType::kRRect,
1069 fIsA.fDirection, fIsA.fStartIndex);
1070 fIsA.fDirection = dir;
1071 fIsA.fStartIndex = start;
1072 }
1073
1074 }
1075 matrix.mapPoints(fPts);
1076
1077 return *this;
1078 }
1079
1080 std::optional<SkRect> SkPathBuilder::computeFiniteBounds() const {
1081 return SkPathPriv::TrimmedBounds(this->points(), this->verbs());
1082 }
1083
1084 std::optional<SkRect> SkPathBuilder::computeTightBounds() const {
1085 if (!this->isFinite()) {
1086 return {};
1087 }
1088 return SkPathPriv::ComputeTightBounds(this->points(), this->verbs(), this->conicWeights());
1089 }
1090
1091 bool SkPathBuilder::isFinite() const {
1092 for (auto p : fPts) {
1093 if (!p.isFinite()) {
1094 return false;
1095 }
1096 }
1097 return true;
1098 }
1099
1100 bool SkPathBuilder::isZeroLengthSincePoint(int startPtIndex) const {
1101 int count = fPts.size() - startPtIndex;
1102 if (count < 2) {
1103 return true;
1104 }
1105 const SkPoint* pts = fPts.begin() + startPtIndex;
1106 const SkPoint& first = *pts;
1107 for (int index = 1; index < count; ++index) {
1108 if (first != pts[index]) {
1109 return false;
1110 }
1111 }
1112 return true;
1113 }
1114
1115 bool SkPathBuilder::contains(SkPoint p) const {
1116 const auto raw = SkPathPriv::Raw(*this, SkResolveConvexity::kNo);
1117 return raw.has_value() && SkPathPriv::Contains(*raw, p);
1118 }