Debian Codegraph @

src/core/SkPathBuilder.cpp

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