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/SkCanvas.h"
9 #include "include/core/SkPath.h"
10 #include "include/core/SkPoint.h"
11 #include "include/core/SkString.h"
12 #include "src/gpu/geometry/GrPathUtils.h"
13 #include "src/gpu/ops/GrAAConvexTessellator.h"
14
15 // Next steps:
16 // add an interactive sample app slide
17 // add debug check that all points are suitably far apart
18 // test more degenerate cases
19
20 // The tolerance for fusing vertices and eliminating colinear lines (It is in device space).
21 static const SkScalar kClose = (SK_Scalar1 / 16);
22 static const SkScalar kCloseSqd = kClose * kClose;
23
24 // tesselation tolerance values, in device space pixels
25 static const SkScalar kQuadTolerance = 0.2f;
26 static const SkScalar kCubicTolerance = 0.2f;
27 static const SkScalar kConicTolerance = 0.25f;
28
29 // dot product below which we use a round cap between curve segments
30 static const SkScalar kRoundCapThreshold = 0.8f;
31
32 // dot product above which we consider two adjacent curves to be part of the "same" curve
33 static const SkScalar kCurveConnectionThreshold = 0.8f;
34
intersect(const SkPoint & p0,const SkPoint & n0,const SkPoint & p1,const SkPoint & n1,SkScalar * t)35 static bool intersect(const SkPoint& p0, const SkPoint& n0,
36 const SkPoint& p1, const SkPoint& n1,
37 SkScalar* t) {
38 const SkPoint v = p1 - p0;
39 SkScalar perpDot = n0.fX * n1.fY - n0.fY * n1.fX;
40 if (SkScalarNearlyZero(perpDot)) {
41 return false;
42 }
43 *t = (v.fX * n1.fY - v.fY * n1.fX) / perpDot;
44 SkASSERT(SkScalarIsFinite(*t));
45 return true;
46 }
47
48 // This is a special case version of intersect where we have the vector
49 // perpendicular to the second line rather than the vector parallel to it.
perp_intersect(const SkPoint & p0,const SkPoint & n0,const SkPoint & p1,const SkPoint & perp)50 static SkScalar perp_intersect(const SkPoint& p0, const SkPoint& n0,
51 const SkPoint& p1, const SkPoint& perp) {
52 const SkPoint v = p1 - p0;
53 SkScalar perpDot = n0.dot(perp);
54 return v.dot(perp) / perpDot;
55 }
56
duplicate_pt(const SkPoint & p0,const SkPoint & p1)57 static bool duplicate_pt(const SkPoint& p0, const SkPoint& p1) {
58 SkScalar distSq = SkPointPriv::DistanceToSqd(p0, p1);
59 return distSq < kCloseSqd;
60 }
61
points_are_colinear_and_b_is_middle(const SkPoint & a,const SkPoint & b,const SkPoint & c)62 static bool points_are_colinear_and_b_is_middle(const SkPoint& a, const SkPoint& b,
63 const SkPoint& c) {
64 // 'area' is twice the area of the triangle with corners a, b, and c.
65 SkScalar area = a.fX * (b.fY - c.fY) + b.fX * (c.fY - a.fY) + c.fX * (a.fY - b.fY);
66 if (SkScalarAbs(area) >= 2 * kCloseSqd) {
67 return false;
68 }
69 return (a - b).dot(b - c) >= 0;
70 }
71
addPt(const SkPoint & pt,SkScalar depth,SkScalar coverage,bool movable,CurveState curve)72 int GrAAConvexTessellator::addPt(const SkPoint& pt,
73 SkScalar depth,
74 SkScalar coverage,
75 bool movable,
76 CurveState curve) {
77 SkASSERT(pt.isFinite());
78 this->validate();
79
80 int index = fPts.count();
81 *fPts.push() = pt;
82 *fCoverages.push() = coverage;
83 *fMovable.push() = movable;
84 *fCurveState.push() = curve;
85
86 this->validate();
87 return index;
88 }
89
popLastPt()90 void GrAAConvexTessellator::popLastPt() {
91 this->validate();
92
93 fPts.pop();
94 fCoverages.pop();
95 fMovable.pop();
96 fCurveState.pop();
97
98 this->validate();
99 }
100
popFirstPtShuffle()101 void GrAAConvexTessellator::popFirstPtShuffle() {
102 this->validate();
103
104 fPts.removeShuffle(0);
105 fCoverages.removeShuffle(0);
106 fMovable.removeShuffle(0);
107 fCurveState.removeShuffle(0);
108
109 this->validate();
110 }
111
updatePt(int index,const SkPoint & pt,SkScalar depth,SkScalar coverage)112 void GrAAConvexTessellator::updatePt(int index,
113 const SkPoint& pt,
114 SkScalar depth,
115 SkScalar coverage) {
116 this->validate();
117 SkASSERT(fMovable[index]);
118
119 fPts[index] = pt;
120 fCoverages[index] = coverage;
121 }
122
addTri(int i0,int i1,int i2)123 void GrAAConvexTessellator::addTri(int i0, int i1, int i2) {
124 if (i0 == i1 || i1 == i2 || i2 == i0) {
125 return;
126 }
127
128 *fIndices.push() = i0;
129 *fIndices.push() = i1;
130 *fIndices.push() = i2;
131 }
132
rewind()133 void GrAAConvexTessellator::rewind() {
134 fPts.rewind();
135 fCoverages.rewind();
136 fMovable.rewind();
137 fIndices.rewind();
138 fNorms.rewind();
139 fCurveState.rewind();
140 fInitialRing.rewind();
141 fCandidateVerts.rewind();
142 #if GR_AA_CONVEX_TESSELLATOR_VIZ
143 fRings.rewind(); // TODO: leak in this case!
144 #else
145 fRings[0].rewind();
146 fRings[1].rewind();
147 #endif
148 }
149
computeNormals()150 void GrAAConvexTessellator::computeNormals() {
151 auto normalToVector = [this](SkVector v) {
152 SkVector n = SkPointPriv::MakeOrthog(v, fSide);
153 SkAssertResult(n.normalize());
154 SkASSERT(SkScalarNearlyEqual(1.0f, n.length()));
155 return n;
156 };
157
158 // Check the cross product of the final trio
159 fNorms.append(fPts.count());
160 fNorms[0] = fPts[1] - fPts[0];
161 fNorms.top() = fPts[0] - fPts.top();
162 SkScalar cross = SkPoint::CrossProduct(fNorms[0], fNorms.top());
163 fSide = (cross > 0.0f) ? SkPointPriv::kRight_Side : SkPointPriv::kLeft_Side;
164 fNorms[0] = normalToVector(fNorms[0]);
165 for (int cur = 1; cur < fNorms.count() - 1; ++cur) {
166 fNorms[cur] = normalToVector(fPts[cur + 1] - fPts[cur]);
167 }
168 fNorms.top() = normalToVector(fNorms.top());
169 }
170
computeBisectors()171 void GrAAConvexTessellator::computeBisectors() {
172 fBisectors.setCount(fNorms.count());
173
174 int prev = fBisectors.count() - 1;
175 for (int cur = 0; cur < fBisectors.count(); prev = cur, ++cur) {
176 fBisectors[cur] = fNorms[cur] + fNorms[prev];
177 if (!fBisectors[cur].normalize()) {
178 fBisectors[cur] = SkPointPriv::MakeOrthog(fNorms[cur], (SkPointPriv::Side)-fSide) +
179 SkPointPriv::MakeOrthog(fNorms[prev], fSide);
180 SkAssertResult(fBisectors[cur].normalize());
181 } else {
182 fBisectors[cur].negate(); // make the bisector face in
183 }
184 if (fCurveState[prev] == kIndeterminate_CurveState) {
185 if (fCurveState[cur] == kSharp_CurveState) {
186 fCurveState[prev] = kSharp_CurveState;
187 } else {
188 if (SkScalarAbs(fNorms[cur].dot(fNorms[prev])) > kCurveConnectionThreshold) {
189 fCurveState[prev] = kCurve_CurveState;
190 fCurveState[cur] = kCurve_CurveState;
191 } else {
192 fCurveState[prev] = kSharp_CurveState;
193 fCurveState[cur] = kSharp_CurveState;
194 }
195 }
196 }
197
198 SkASSERT(SkScalarNearlyEqual(1.0f, fBisectors[cur].length()));
199 }
200 }
201
202 // Create as many rings as we need to (up to a predefined limit) to reach the specified target
203 // depth. If we are in fill mode, the final ring will automatically be fanned.
createInsetRings(Ring & previousRing,SkScalar initialDepth,SkScalar initialCoverage,SkScalar targetDepth,SkScalar targetCoverage,Ring ** finalRing)204 bool GrAAConvexTessellator::createInsetRings(Ring& previousRing, SkScalar initialDepth,
205 SkScalar initialCoverage, SkScalar targetDepth,
206 SkScalar targetCoverage, Ring** finalRing) {
207 static const int kMaxNumRings = 8;
208
209 if (previousRing.numPts() < 3) {
210 return false;
211 }
212 Ring* currentRing = &previousRing;
213 int i;
214 for (i = 0; i < kMaxNumRings; ++i) {
215 Ring* nextRing = this->getNextRing(currentRing);
216 SkASSERT(nextRing != currentRing);
217
218 bool done = this->createInsetRing(*currentRing, nextRing, initialDepth, initialCoverage,
219 targetDepth, targetCoverage, i == 0);
220 currentRing = nextRing;
221 if (done) {
222 break;
223 }
224 currentRing->init(*this);
225 }
226
227 if (kMaxNumRings == i) {
228 // Bail if we've exceeded the amount of time we want to throw at this.
229 this->terminate(*currentRing);
230 return false;
231 }
232 bool done = currentRing->numPts() >= 3;
233 if (done) {
234 currentRing->init(*this);
235 }
236 *finalRing = currentRing;
237 return done;
238 }
239
240 // The general idea here is to, conceptually, start with the original polygon and slide
241 // the vertices along the bisectors until the first intersection. At that
242 // point two of the edges collapse and the process repeats on the new polygon.
243 // The polygon state is captured in the Ring class while the GrAAConvexTessellator
244 // controls the iteration. The CandidateVerts holds the formative points for the
245 // next ring.
tessellate(const SkMatrix & m,const SkPath & path)246 bool GrAAConvexTessellator::tessellate(const SkMatrix& m, const SkPath& path) {
247 if (!this->extractFromPath(m, path)) {
248 return false;
249 }
250
251 SkScalar coverage = 1.0f;
252 SkScalar scaleFactor = 0.0f;
253
254 if (SkStrokeRec::kStrokeAndFill_Style == fStyle) {
255 SkASSERT(m.isSimilarity());
256 scaleFactor = m.getMaxScale(); // x and y scale are the same
257 SkScalar effectiveStrokeWidth = scaleFactor * fStrokeWidth;
258 Ring outerStrokeAndAARing;
259 this->createOuterRing(fInitialRing,
260 effectiveStrokeWidth / 2 + kAntialiasingRadius, 0.0,
261 &outerStrokeAndAARing);
262
263 // discard all the triangles added between the originating ring and the new outer ring
264 fIndices.rewind();
265
266 outerStrokeAndAARing.init(*this);
267
268 outerStrokeAndAARing.makeOriginalRing();
269
270 // Add the outer stroke ring's normals to the originating ring's normals
271 // so it can also act as an originating ring
272 fNorms.setCount(fNorms.count() + outerStrokeAndAARing.numPts());
273 for (int i = 0; i < outerStrokeAndAARing.numPts(); ++i) {
274 SkASSERT(outerStrokeAndAARing.index(i) < fNorms.count());
275 fNorms[outerStrokeAndAARing.index(i)] = outerStrokeAndAARing.norm(i);
276 }
277
278 // the bisectors are only needed for the computation of the outer ring
279 fBisectors.rewind();
280
281 Ring* insetAARing;
282 this->createInsetRings(outerStrokeAndAARing,
283 0.0f, 0.0f, 2*kAntialiasingRadius, 1.0f,
284 &insetAARing);
285
286 SkDEBUGCODE(this->validate();)
287 return true;
288 }
289
290 if (SkStrokeRec::kStroke_Style == fStyle) {
291 SkASSERT(fStrokeWidth >= 0.0f);
292 SkASSERT(m.isSimilarity());
293 scaleFactor = m.getMaxScale(); // x and y scale are the same
294 SkScalar effectiveStrokeWidth = scaleFactor * fStrokeWidth;
295 Ring outerStrokeRing;
296 this->createOuterRing(fInitialRing, effectiveStrokeWidth / 2 - kAntialiasingRadius,
297 coverage, &outerStrokeRing);
298 outerStrokeRing.init(*this);
299 Ring outerAARing;
300 this->createOuterRing(outerStrokeRing, kAntialiasingRadius * 2, 0.0f, &outerAARing);
301 } else {
302 Ring outerAARing;
303 this->createOuterRing(fInitialRing, kAntialiasingRadius, 0.0f, &outerAARing);
304 }
305
306 // the bisectors are only needed for the computation of the outer ring
307 fBisectors.rewind();
308 if (SkStrokeRec::kStroke_Style == fStyle && fInitialRing.numPts() > 2) {
309 SkASSERT(fStrokeWidth >= 0.0f);
310 SkScalar effectiveStrokeWidth = scaleFactor * fStrokeWidth;
311 Ring* insetStrokeRing;
312 SkScalar strokeDepth = effectiveStrokeWidth / 2 - kAntialiasingRadius;
313 if (this->createInsetRings(fInitialRing, 0.0f, coverage, strokeDepth, coverage,
314 &insetStrokeRing)) {
315 Ring* insetAARing;
316 this->createInsetRings(*insetStrokeRing, strokeDepth, coverage, strokeDepth +
317 kAntialiasingRadius * 2, 0.0f, &insetAARing);
318 }
319 } else {
320 Ring* insetAARing;
321 this->createInsetRings(fInitialRing, 0.0f, 0.5f, kAntialiasingRadius, 1.0f, &insetAARing);
322 }
323
324 SkDEBUGCODE(this->validate();)
325 return true;
326 }
327
computeDepthFromEdge(int edgeIdx,const SkPoint & p) const328 SkScalar GrAAConvexTessellator::computeDepthFromEdge(int edgeIdx, const SkPoint& p) const {
329 SkASSERT(edgeIdx < fNorms.count());
330
331 SkPoint v = p - fPts[edgeIdx];
332 SkScalar depth = -fNorms[edgeIdx].dot(v);
333 return depth;
334 }
335
336 // Find a point that is 'desiredDepth' away from the 'edgeIdx'-th edge and lies
337 // along the 'bisector' from the 'startIdx'-th point.
computePtAlongBisector(int startIdx,const SkVector & bisector,int edgeIdx,SkScalar desiredDepth,SkPoint * result) const338 bool GrAAConvexTessellator::computePtAlongBisector(int startIdx,
339 const SkVector& bisector,
340 int edgeIdx,
341 SkScalar desiredDepth,
342 SkPoint* result) const {
343 const SkPoint& norm = fNorms[edgeIdx];
344
345 // First find the point where the edge and the bisector intersect
346 SkPoint newP;
347
348 SkScalar t = perp_intersect(fPts[startIdx], bisector, fPts[edgeIdx], norm);
349 if (SkScalarNearlyEqual(t, 0.0f)) {
350 // the start point was one of the original ring points
351 SkASSERT(startIdx < fPts.count());
352 newP = fPts[startIdx];
353 } else if (t < 0.0f) {
354 newP = bisector;
355 newP.scale(t);
356 newP += fPts[startIdx];
357 } else {
358 return false;
359 }
360
361 // Then offset along the bisector from that point the correct distance
362 SkScalar dot = bisector.dot(norm);
363 t = -desiredDepth / dot;
364 *result = bisector;
365 result->scale(t);
366 *result += newP;
367
368 return true;
369 }
370
extractFromPath(const SkMatrix & m,const SkPath & path)371 bool GrAAConvexTessellator::extractFromPath(const SkMatrix& m, const SkPath& path) {
372 SkASSERT(SkPath::kConvex_Convexity == path.getConvexity());
373
374 SkRect bounds = path.getBounds();
375 m.mapRect(&bounds);
376 if (!bounds.isFinite()) {
377 // We could do something smarter here like clip the path based on the bounds of the dst.
378 // We'd have to be careful about strokes to ensure we don't draw something wrong.
379 return false;
380 }
381
382 // Outer ring: 3*numPts
383 // Middle ring: numPts
384 // Presumptive inner ring: numPts
385 this->reservePts(5*path.countPoints());
386 // Outer ring: 12*numPts
387 // Middle ring: 0
388 // Presumptive inner ring: 6*numPts + 6
389 fIndices.setReserve(18*path.countPoints() + 6);
390
391 // TODO: is there a faster way to extract the points from the path? Perhaps
392 // get all the points via a new entry point, transform them all in bulk
393 // and then walk them to find duplicates?
394 SkPath::Iter iter(path, true);
395 SkPoint pts[4];
396 SkPath::Verb verb;
397 while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
398 switch (verb) {
399 case SkPath::kLine_Verb:
400 if (!SkPathPriv::AllPointsEq(pts, 2)) {
401 this->lineTo(m, pts[1], kSharp_CurveState);
402 }
403 break;
404 case SkPath::kQuad_Verb:
405 if (!SkPathPriv::AllPointsEq(pts, 3)) {
406 this->quadTo(m, pts);
407 }
408 break;
409 case SkPath::kCubic_Verb:
410 if (!SkPathPriv::AllPointsEq(pts, 4)) {
411 this->cubicTo(m, pts);
412 }
413 break;
414 case SkPath::kConic_Verb:
415 if (!SkPathPriv::AllPointsEq(pts, 3)) {
416 this->conicTo(m, pts, iter.conicWeight());
417 }
418 break;
419 case SkPath::kMove_Verb:
420 case SkPath::kClose_Verb:
421 case SkPath::kDone_Verb:
422 break;
423 }
424 }
425
426 if (this->numPts() < 2) {
427 return false;
428 }
429
430 // check if last point is a duplicate of the first point. If so, remove it.
431 if (duplicate_pt(fPts[this->numPts()-1], fPts[0])) {
432 this->popLastPt();
433 }
434
435 // Remove any lingering colinear points where the path wraps around
436 bool noRemovalsToDo = false;
437 while (!noRemovalsToDo && this->numPts() >= 3) {
438 if (points_are_colinear_and_b_is_middle(fPts[fPts.count() - 2], fPts.top(), fPts[0])) {
439 this->popLastPt();
440 } else if (points_are_colinear_and_b_is_middle(fPts.top(), fPts[0], fPts[1])) {
441 this->popFirstPtShuffle();
442 } else {
443 noRemovalsToDo = true;
444 }
445 }
446
447 // Compute the normals and bisectors.
448 SkASSERT(fNorms.empty());
449 if (this->numPts() >= 3) {
450 this->computeNormals();
451 this->computeBisectors();
452 } else if (this->numPts() == 2) {
453 // We've got two points, so we're degenerate.
454 if (fStyle == SkStrokeRec::kFill_Style) {
455 // it's a fill, so we don't need to worry about degenerate paths
456 return false;
457 }
458 // For stroking, we still need to process the degenerate path, so fix it up
459 fSide = SkPointPriv::kLeft_Side;
460
461 fNorms.append(2);
462 fNorms[0] = SkPointPriv::MakeOrthog(fPts[1] - fPts[0], fSide);
463 fNorms[0].normalize();
464 fNorms[1] = -fNorms[0];
465 SkASSERT(SkScalarNearlyEqual(1.0f, fNorms[0].length()));
466 // we won't actually use the bisectors, so just push zeroes
467 fBisectors.push_back(SkPoint::Make(0.0, 0.0));
468 fBisectors.push_back(SkPoint::Make(0.0, 0.0));
469 } else {
470 return false;
471 }
472
473 fCandidateVerts.setReserve(this->numPts());
474 fInitialRing.setReserve(this->numPts());
475 for (int i = 0; i < this->numPts(); ++i) {
476 fInitialRing.addIdx(i, i);
477 }
478 fInitialRing.init(fNorms, fBisectors);
479
480 this->validate();
481 return true;
482 }
483
getNextRing(Ring * lastRing)484 GrAAConvexTessellator::Ring* GrAAConvexTessellator::getNextRing(Ring* lastRing) {
485 #if GR_AA_CONVEX_TESSELLATOR_VIZ
486 Ring* ring = *fRings.push() = new Ring;
487 ring->setReserve(fInitialRing.numPts());
488 ring->rewind();
489 return ring;
490 #else
491 // Flip flop back and forth between fRings[0] & fRings[1]
492 int nextRing = (lastRing == &fRings[0]) ? 1 : 0;
493 fRings[nextRing].setReserve(fInitialRing.numPts());
494 fRings[nextRing].rewind();
495 return &fRings[nextRing];
496 #endif
497 }
498
fanRing(const Ring & ring)499 void GrAAConvexTessellator::fanRing(const Ring& ring) {
500 // fan out from point 0
501 int startIdx = ring.index(0);
502 for (int cur = ring.numPts() - 2; cur >= 0; --cur) {
503 this->addTri(startIdx, ring.index(cur), ring.index(cur + 1));
504 }
505 }
506
createOuterRing(const Ring & previousRing,SkScalar outset,SkScalar coverage,Ring * nextRing)507 void GrAAConvexTessellator::createOuterRing(const Ring& previousRing, SkScalar outset,
508 SkScalar coverage, Ring* nextRing) {
509 const int numPts = previousRing.numPts();
510 if (numPts == 0) {
511 return;
512 }
513
514 int prev = numPts - 1;
515 int lastPerpIdx = -1, firstPerpIdx = -1;
516
517 const SkScalar outsetSq = outset * outset;
518 SkScalar miterLimitSq = outset * fMiterLimit;
519 miterLimitSq = miterLimitSq * miterLimitSq;
520 for (int cur = 0; cur < numPts; ++cur) {
521 int originalIdx = previousRing.index(cur);
522 // For each vertex of the original polygon we add at least two points to the
523 // outset polygon - one extending perpendicular to each impinging edge. Connecting these
524 // two points yields a bevel join. We need one additional point for a mitered join, and
525 // a round join requires one or more points depending upon curvature.
526
527 // The perpendicular point for the last edge
528 SkPoint normal1 = previousRing.norm(prev);
529 SkPoint perp1 = normal1;
530 perp1.scale(outset);
531 perp1 += this->point(originalIdx);
532
533 // The perpendicular point for the next edge.
534 SkPoint normal2 = previousRing.norm(cur);
535 SkPoint perp2 = normal2;
536 perp2.scale(outset);
537 perp2 += fPts[originalIdx];
538
539 CurveState curve = fCurveState[originalIdx];
540
541 // We know it isn't a duplicate of the prior point (since it and this
542 // one are just perpendicular offsets from the non-merged polygon points)
543 int perp1Idx = this->addPt(perp1, -outset, coverage, false, curve);
544 nextRing->addIdx(perp1Idx, originalIdx);
545
546 int perp2Idx;
547 // For very shallow angles all the corner points could fuse.
548 if (duplicate_pt(perp2, this->point(perp1Idx))) {
549 perp2Idx = perp1Idx;
550 } else {
551 perp2Idx = this->addPt(perp2, -outset, coverage, false, curve);
552 }
553
554 if (perp2Idx != perp1Idx) {
555 if (curve == kCurve_CurveState) {
556 // bevel or round depending upon curvature
557 SkScalar dotProd = normal1.dot(normal2);
558 if (dotProd < kRoundCapThreshold) {
559 // Currently we "round" by creating a single extra point, which produces
560 // good results for common cases. For thick strokes with high curvature, we will
561 // need to add more points; for the time being we simply fall back to software
562 // rendering for thick strokes.
563 SkPoint miter = previousRing.bisector(cur);
564 miter.setLength(-outset);
565 miter += fPts[originalIdx];
566
567 // For very shallow angles all the corner points could fuse
568 if (!duplicate_pt(miter, this->point(perp1Idx))) {
569 int miterIdx;
570 miterIdx = this->addPt(miter, -outset, coverage, false, kSharp_CurveState);
571 nextRing->addIdx(miterIdx, originalIdx);
572 // The two triangles for the corner
573 this->addTri(originalIdx, perp1Idx, miterIdx);
574 this->addTri(originalIdx, miterIdx, perp2Idx);
575 }
576 } else {
577 this->addTri(originalIdx, perp1Idx, perp2Idx);
578 }
579 } else {
580 switch (fJoin) {
581 case SkPaint::Join::kMiter_Join: {
582 // The bisector outset point
583 SkPoint miter = previousRing.bisector(cur);
584 SkScalar dotProd = normal1.dot(normal2);
585 // The max is because this could go slightly negative if precision causes
586 // us to become slightly concave.
587 SkScalar sinHalfAngleSq = SkTMax(SkScalarHalf(SK_Scalar1 + dotProd), 0.f);
588 SkScalar lengthSq = sk_ieee_float_divide(outsetSq, sinHalfAngleSq);
589 if (lengthSq > miterLimitSq) {
590 // just bevel it
591 this->addTri(originalIdx, perp1Idx, perp2Idx);
592 break;
593 }
594 miter.setLength(-SkScalarSqrt(lengthSq));
595 miter += fPts[originalIdx];
596
597 // For very shallow angles all the corner points could fuse
598 if (!duplicate_pt(miter, this->point(perp1Idx))) {
599 int miterIdx;
600 miterIdx = this->addPt(miter, -outset, coverage, false,
601 kSharp_CurveState);
602 nextRing->addIdx(miterIdx, originalIdx);
603 // The two triangles for the corner
604 this->addTri(originalIdx, perp1Idx, miterIdx);
605 this->addTri(originalIdx, miterIdx, perp2Idx);
606 } else {
607 // ignore the miter point as it's so close to perp1/perp2 and simply
608 // bevel.
609 this->addTri(originalIdx, perp1Idx, perp2Idx);
610 }
611 break;
612 }
613 case SkPaint::Join::kBevel_Join:
614 this->addTri(originalIdx, perp1Idx, perp2Idx);
615 break;
616 default:
617 // kRound_Join is unsupported for now. GrAALinearizingConvexPathRenderer is
618 // only willing to draw mitered or beveled, so we should never get here.
619 SkASSERT(false);
620 }
621 }
622
623 nextRing->addIdx(perp2Idx, originalIdx);
624 }
625
626 if (0 == cur) {
627 // Store the index of the first perpendicular point to finish up
628 firstPerpIdx = perp1Idx;
629 SkASSERT(-1 == lastPerpIdx);
630 } else {
631 // The triangles for the previous edge
632 int prevIdx = previousRing.index(prev);
633 this->addTri(prevIdx, perp1Idx, originalIdx);
634 this->addTri(prevIdx, lastPerpIdx, perp1Idx);
635 }
636
637 // Track the last perpendicular outset point so we can construct the
638 // trailing edge triangles.
639 lastPerpIdx = perp2Idx;
640 prev = cur;
641 }
642
643 // pick up the final edge rect
644 int lastIdx = previousRing.index(numPts - 1);
645 this->addTri(lastIdx, firstPerpIdx, previousRing.index(0));
646 this->addTri(lastIdx, lastPerpIdx, firstPerpIdx);
647
648 this->validate();
649 }
650
651 // Something went wrong in the creation of the next ring. If we're filling the shape, just go ahead
652 // and fan it.
terminate(const Ring & ring)653 void GrAAConvexTessellator::terminate(const Ring& ring) {
654 if (fStyle != SkStrokeRec::kStroke_Style && ring.numPts() > 0) {
655 this->fanRing(ring);
656 }
657 }
658
compute_coverage(SkScalar depth,SkScalar initialDepth,SkScalar initialCoverage,SkScalar targetDepth,SkScalar targetCoverage)659 static SkScalar compute_coverage(SkScalar depth, SkScalar initialDepth, SkScalar initialCoverage,
660 SkScalar targetDepth, SkScalar targetCoverage) {
661 if (SkScalarNearlyEqual(initialDepth, targetDepth)) {
662 return targetCoverage;
663 }
664 SkScalar result = (depth - initialDepth) / (targetDepth - initialDepth) *
665 (targetCoverage - initialCoverage) + initialCoverage;
666 return SkScalarClampMax(result, 1.0f);
667 }
668
669 // return true when processing is complete
createInsetRing(const Ring & lastRing,Ring * nextRing,SkScalar initialDepth,SkScalar initialCoverage,SkScalar targetDepth,SkScalar targetCoverage,bool forceNew)670 bool GrAAConvexTessellator::createInsetRing(const Ring& lastRing, Ring* nextRing,
671 SkScalar initialDepth, SkScalar initialCoverage,
672 SkScalar targetDepth, SkScalar targetCoverage,
673 bool forceNew) {
674 bool done = false;
675
676 fCandidateVerts.rewind();
677
678 // Loop through all the points in the ring and find the intersection with the smallest depth
679 SkScalar minDist = SK_ScalarMax, minT = 0.0f;
680 int minEdgeIdx = -1;
681
682 for (int cur = 0; cur < lastRing.numPts(); ++cur) {
683 int next = (cur + 1) % lastRing.numPts();
684
685 SkScalar t;
686 bool result = intersect(this->point(lastRing.index(cur)), lastRing.bisector(cur),
687 this->point(lastRing.index(next)), lastRing.bisector(next),
688 &t);
689 // The bisectors may be parallel (!result) or the previous ring may have become slightly
690 // concave due to accumulated error (t <= 0).
691 if (!result || t <= 0) {
692 continue;
693 }
694 SkScalar dist = -t * lastRing.norm(cur).dot(lastRing.bisector(cur));
695
696 if (minDist > dist) {
697 minDist = dist;
698 minT = t;
699 minEdgeIdx = cur;
700 }
701 }
702
703 if (minEdgeIdx == -1) {
704 return false;
705 }
706 SkPoint newPt = lastRing.bisector(minEdgeIdx);
707 newPt.scale(minT);
708 newPt += this->point(lastRing.index(minEdgeIdx));
709
710 SkScalar depth = this->computeDepthFromEdge(lastRing.origEdgeID(minEdgeIdx), newPt);
711 if (depth >= targetDepth) {
712 // None of the bisectors intersect before reaching the desired depth.
713 // Just step them all to the desired depth
714 depth = targetDepth;
715 done = true;
716 }
717
718 // 'dst' stores where each point in the last ring maps to/transforms into
719 // in the next ring.
720 SkTDArray<int> dst;
721 dst.setCount(lastRing.numPts());
722
723 // Create the first point (who compares with no one)
724 if (!this->computePtAlongBisector(lastRing.index(0),
725 lastRing.bisector(0),
726 lastRing.origEdgeID(0),
727 depth, &newPt)) {
728 this->terminate(lastRing);
729 return true;
730 }
731 dst[0] = fCandidateVerts.addNewPt(newPt,
732 lastRing.index(0), lastRing.origEdgeID(0),
733 !this->movable(lastRing.index(0)));
734
735 // Handle the middle points (who only compare with the prior point)
736 for (int cur = 1; cur < lastRing.numPts()-1; ++cur) {
737 if (!this->computePtAlongBisector(lastRing.index(cur),
738 lastRing.bisector(cur),
739 lastRing.origEdgeID(cur),
740 depth, &newPt)) {
741 this->terminate(lastRing);
742 return true;
743 }
744 if (!duplicate_pt(newPt, fCandidateVerts.lastPoint())) {
745 dst[cur] = fCandidateVerts.addNewPt(newPt,
746 lastRing.index(cur), lastRing.origEdgeID(cur),
747 !this->movable(lastRing.index(cur)));
748 } else {
749 dst[cur] = fCandidateVerts.fuseWithPrior(lastRing.origEdgeID(cur));
750 }
751 }
752
753 // Check on the last point (handling the wrap around)
754 int cur = lastRing.numPts()-1;
755 if (!this->computePtAlongBisector(lastRing.index(cur),
756 lastRing.bisector(cur),
757 lastRing.origEdgeID(cur),
758 depth, &newPt)) {
759 this->terminate(lastRing);
760 return true;
761 }
762 bool dupPrev = duplicate_pt(newPt, fCandidateVerts.lastPoint());
763 bool dupNext = duplicate_pt(newPt, fCandidateVerts.firstPoint());
764
765 if (!dupPrev && !dupNext) {
766 dst[cur] = fCandidateVerts.addNewPt(newPt,
767 lastRing.index(cur), lastRing.origEdgeID(cur),
768 !this->movable(lastRing.index(cur)));
769 } else if (dupPrev && !dupNext) {
770 dst[cur] = fCandidateVerts.fuseWithPrior(lastRing.origEdgeID(cur));
771 } else if (!dupPrev && dupNext) {
772 dst[cur] = fCandidateVerts.fuseWithNext();
773 } else {
774 bool dupPrevVsNext = duplicate_pt(fCandidateVerts.firstPoint(), fCandidateVerts.lastPoint());
775
776 if (!dupPrevVsNext) {
777 dst[cur] = fCandidateVerts.fuseWithPrior(lastRing.origEdgeID(cur));
778 } else {
779 const int fused = fCandidateVerts.fuseWithBoth();
780 dst[cur] = fused;
781 const int targetIdx = dst[cur - 1];
782 for (int i = cur - 1; i >= 0 && dst[i] == targetIdx; i--) {
783 dst[i] = fused;
784 }
785 }
786 }
787
788 // Fold the new ring's points into the global pool
789 for (int i = 0; i < fCandidateVerts.numPts(); ++i) {
790 int newIdx;
791 if (fCandidateVerts.needsToBeNew(i) || forceNew) {
792 // if the originating index is still valid then this point wasn't
793 // fused (and is thus movable)
794 SkScalar coverage = compute_coverage(depth, initialDepth, initialCoverage,
795 targetDepth, targetCoverage);
796 newIdx = this->addPt(fCandidateVerts.point(i), depth, coverage,
797 fCandidateVerts.originatingIdx(i) != -1, kSharp_CurveState);
798 } else {
799 SkASSERT(fCandidateVerts.originatingIdx(i) != -1);
800 this->updatePt(fCandidateVerts.originatingIdx(i), fCandidateVerts.point(i), depth,
801 targetCoverage);
802 newIdx = fCandidateVerts.originatingIdx(i);
803 }
804
805 nextRing->addIdx(newIdx, fCandidateVerts.origEdge(i));
806 }
807
808 // 'dst' currently has indices into the ring. Remap these to be indices
809 // into the global pool since the triangulation operates in that space.
810 for (int i = 0; i < dst.count(); ++i) {
811 dst[i] = nextRing->index(dst[i]);
812 }
813
814 for (int i = 0; i < lastRing.numPts(); ++i) {
815 int next = (i + 1) % lastRing.numPts();
816
817 this->addTri(lastRing.index(i), lastRing.index(next), dst[next]);
818 this->addTri(lastRing.index(i), dst[next], dst[i]);
819 }
820
821 if (done && fStyle != SkStrokeRec::kStroke_Style) {
822 // fill or stroke-and-fill
823 this->fanRing(*nextRing);
824 }
825
826 if (nextRing->numPts() < 3) {
827 done = true;
828 }
829 return done;
830 }
831
validate() const832 void GrAAConvexTessellator::validate() const {
833 SkASSERT(fPts.count() == fMovable.count());
834 SkASSERT(fPts.count() == fCoverages.count());
835 SkASSERT(fPts.count() == fCurveState.count());
836 SkASSERT(0 == (fIndices.count() % 3));
837 SkASSERT(!fBisectors.count() || fBisectors.count() == fNorms.count());
838 }
839
840 //////////////////////////////////////////////////////////////////////////////
init(const GrAAConvexTessellator & tess)841 void GrAAConvexTessellator::Ring::init(const GrAAConvexTessellator& tess) {
842 this->computeNormals(tess);
843 this->computeBisectors(tess);
844 }
845
init(const SkTDArray<SkVector> & norms,const SkTDArray<SkVector> & bisectors)846 void GrAAConvexTessellator::Ring::init(const SkTDArray<SkVector>& norms,
847 const SkTDArray<SkVector>& bisectors) {
848 for (int i = 0; i < fPts.count(); ++i) {
849 fPts[i].fNorm = norms[i];
850 fPts[i].fBisector = bisectors[i];
851 }
852 }
853
854 // Compute the outward facing normal at each vertex.
computeNormals(const GrAAConvexTessellator & tess)855 void GrAAConvexTessellator::Ring::computeNormals(const GrAAConvexTessellator& tess) {
856 for (int cur = 0; cur < fPts.count(); ++cur) {
857 int next = (cur + 1) % fPts.count();
858
859 fPts[cur].fNorm = tess.point(fPts[next].fIndex) - tess.point(fPts[cur].fIndex);
860 SkPoint::Normalize(&fPts[cur].fNorm);
861 fPts[cur].fNorm = SkPointPriv::MakeOrthog(fPts[cur].fNorm, tess.side());
862 }
863 }
864
computeBisectors(const GrAAConvexTessellator & tess)865 void GrAAConvexTessellator::Ring::computeBisectors(const GrAAConvexTessellator& tess) {
866 int prev = fPts.count() - 1;
867 for (int cur = 0; cur < fPts.count(); prev = cur, ++cur) {
868 fPts[cur].fBisector = fPts[cur].fNorm + fPts[prev].fNorm;
869 if (!fPts[cur].fBisector.normalize()) {
870 fPts[cur].fBisector =
871 SkPointPriv::MakeOrthog(fPts[cur].fNorm, (SkPointPriv::Side)-tess.side()) +
872 SkPointPriv::MakeOrthog(fPts[prev].fNorm, tess.side());
873 SkAssertResult(fPts[cur].fBisector.normalize());
874 } else {
875 fPts[cur].fBisector.negate(); // make the bisector face in
876 }
877 }
878 }
879
880 //////////////////////////////////////////////////////////////////////////////
881 #ifdef SK_DEBUG
882 // Is this ring convex?
isConvex(const GrAAConvexTessellator & tess) const883 bool GrAAConvexTessellator::Ring::isConvex(const GrAAConvexTessellator& tess) const {
884 if (fPts.count() < 3) {
885 return true;
886 }
887
888 SkPoint prev = tess.point(fPts[0].fIndex) - tess.point(fPts.top().fIndex);
889 SkPoint cur = tess.point(fPts[1].fIndex) - tess.point(fPts[0].fIndex);
890 SkScalar minDot = prev.fX * cur.fY - prev.fY * cur.fX;
891 SkScalar maxDot = minDot;
892
893 prev = cur;
894 for (int i = 1; i < fPts.count(); ++i) {
895 int next = (i + 1) % fPts.count();
896
897 cur = tess.point(fPts[next].fIndex) - tess.point(fPts[i].fIndex);
898 SkScalar dot = prev.fX * cur.fY - prev.fY * cur.fX;
899
900 minDot = SkMinScalar(minDot, dot);
901 maxDot = SkMaxScalar(maxDot, dot);
902
903 prev = cur;
904 }
905
906 if (SkScalarNearlyEqual(maxDot, 0.0f, 0.005f)) {
907 maxDot = 0;
908 }
909 if (SkScalarNearlyEqual(minDot, 0.0f, 0.005f)) {
910 minDot = 0;
911 }
912 return (maxDot >= 0.0f) == (minDot >= 0.0f);
913 }
914
915 #endif
916
lineTo(const SkPoint & p,CurveState curve)917 void GrAAConvexTessellator::lineTo(const SkPoint& p, CurveState curve) {
918 if (this->numPts() > 0 && duplicate_pt(p, this->lastPoint())) {
919 return;
920 }
921
922 if (this->numPts() >= 2 &&
923 points_are_colinear_and_b_is_middle(fPts[fPts.count() - 2], fPts.top(), p)) {
924 // The old last point is on the line from the second to last to the new point
925 this->popLastPt();
926 // double-check that the new last point is not a duplicate of the new point. In an ideal
927 // world this wouldn't be necessary (since it's only possible for non-convex paths), but
928 // floating point precision issues mean it can actually happen on paths that were
929 // determined to be convex.
930 if (duplicate_pt(p, this->lastPoint())) {
931 return;
932 }
933 }
934 SkScalar initialRingCoverage = (SkStrokeRec::kFill_Style == fStyle) ? 0.5f : 1.0f;
935 this->addPt(p, 0.0f, initialRingCoverage, false, curve);
936 }
937
lineTo(const SkMatrix & m,SkPoint p,CurveState curve)938 void GrAAConvexTessellator::lineTo(const SkMatrix& m, SkPoint p, CurveState curve) {
939 m.mapPoints(&p, 1);
940 this->lineTo(p, curve);
941 }
942
quadTo(const SkPoint pts[3])943 void GrAAConvexTessellator::quadTo(const SkPoint pts[3]) {
944 int maxCount = GrPathUtils::quadraticPointCount(pts, kQuadTolerance);
945 fPointBuffer.setCount(maxCount);
946 SkPoint* target = fPointBuffer.begin();
947 int count = GrPathUtils::generateQuadraticPoints(pts[0], pts[1], pts[2],
948 kQuadTolerance, &target, maxCount);
949 fPointBuffer.setCount(count);
950 for (int i = 0; i < count - 1; i++) {
951 this->lineTo(fPointBuffer[i], kCurve_CurveState);
952 }
953 this->lineTo(fPointBuffer[count - 1], kIndeterminate_CurveState);
954 }
955
quadTo(const SkMatrix & m,SkPoint pts[3])956 void GrAAConvexTessellator::quadTo(const SkMatrix& m, SkPoint pts[3]) {
957 m.mapPoints(pts, 3);
958 this->quadTo(pts);
959 }
960
cubicTo(const SkMatrix & m,SkPoint pts[4])961 void GrAAConvexTessellator::cubicTo(const SkMatrix& m, SkPoint pts[4]) {
962 m.mapPoints(pts, 4);
963 int maxCount = GrPathUtils::cubicPointCount(pts, kCubicTolerance);
964 fPointBuffer.setCount(maxCount);
965 SkPoint* target = fPointBuffer.begin();
966 int count = GrPathUtils::generateCubicPoints(pts[0], pts[1], pts[2], pts[3],
967 kCubicTolerance, &target, maxCount);
968 fPointBuffer.setCount(count);
969 for (int i = 0; i < count - 1; i++) {
970 this->lineTo(fPointBuffer[i], kCurve_CurveState);
971 }
972 this->lineTo(fPointBuffer[count - 1], kIndeterminate_CurveState);
973 }
974
975 // include down here to avoid compilation errors caused by "-" overload in SkGeometry.h
976 #include "src/core/SkGeometry.h"
977
conicTo(const SkMatrix & m,SkPoint pts[3],SkScalar w)978 void GrAAConvexTessellator::conicTo(const SkMatrix& m, SkPoint pts[3], SkScalar w) {
979 m.mapPoints(pts, 3);
980 SkAutoConicToQuads quadder;
981 const SkPoint* quads = quadder.computeQuads(pts, w, kConicTolerance);
982 SkPoint lastPoint = *(quads++);
983 int count = quadder.countQuads();
984 for (int i = 0; i < count; ++i) {
985 SkPoint quadPts[3];
986 quadPts[0] = lastPoint;
987 quadPts[1] = quads[0];
988 quadPts[2] = i == count - 1 ? pts[2] : quads[1];
989 this->quadTo(quadPts);
990 lastPoint = quadPts[2];
991 quads += 2;
992 }
993 }
994
995 //////////////////////////////////////////////////////////////////////////////
996 #if GR_AA_CONVEX_TESSELLATOR_VIZ
997 static const SkScalar kPointRadius = 0.02f;
998 static const SkScalar kArrowStrokeWidth = 0.0f;
999 static const SkScalar kArrowLength = 0.2f;
1000 static const SkScalar kEdgeTextSize = 0.1f;
1001 static const SkScalar kPointTextSize = 0.02f;
1002
draw_point(SkCanvas * canvas,const SkPoint & p,SkScalar paramValue,bool stroke)1003 static void draw_point(SkCanvas* canvas, const SkPoint& p, SkScalar paramValue, bool stroke) {
1004 SkPaint paint;
1005 SkASSERT(paramValue <= 1.0f);
1006 int gs = int(255*paramValue);
1007 paint.setARGB(255, gs, gs, gs);
1008
1009 canvas->drawCircle(p.fX, p.fY, kPointRadius, paint);
1010
1011 if (stroke) {
1012 SkPaint stroke;
1013 stroke.setColor(SK_ColorYELLOW);
1014 stroke.setStyle(SkPaint::kStroke_Style);
1015 stroke.setStrokeWidth(kPointRadius/3.0f);
1016 canvas->drawCircle(p.fX, p.fY, kPointRadius, stroke);
1017 }
1018 }
1019
draw_line(SkCanvas * canvas,const SkPoint & p0,const SkPoint & p1,SkColor color)1020 static void draw_line(SkCanvas* canvas, const SkPoint& p0, const SkPoint& p1, SkColor color) {
1021 SkPaint p;
1022 p.setColor(color);
1023
1024 canvas->drawLine(p0.fX, p0.fY, p1.fX, p1.fY, p);
1025 }
1026
draw_arrow(SkCanvas * canvas,const SkPoint & p,const SkPoint & n,SkScalar len,SkColor color)1027 static void draw_arrow(SkCanvas*canvas, const SkPoint& p, const SkPoint &n,
1028 SkScalar len, SkColor color) {
1029 SkPaint paint;
1030 paint.setColor(color);
1031 paint.setStrokeWidth(kArrowStrokeWidth);
1032 paint.setStyle(SkPaint::kStroke_Style);
1033
1034 canvas->drawLine(p.fX, p.fY,
1035 p.fX + len * n.fX, p.fY + len * n.fY,
1036 paint);
1037 }
1038
draw(SkCanvas * canvas,const GrAAConvexTessellator & tess) const1039 void GrAAConvexTessellator::Ring::draw(SkCanvas* canvas, const GrAAConvexTessellator& tess) const {
1040 SkPaint paint;
1041 paint.setTextSize(kEdgeTextSize);
1042
1043 for (int cur = 0; cur < fPts.count(); ++cur) {
1044 int next = (cur + 1) % fPts.count();
1045
1046 draw_line(canvas,
1047 tess.point(fPts[cur].fIndex),
1048 tess.point(fPts[next].fIndex),
1049 SK_ColorGREEN);
1050
1051 SkPoint mid = tess.point(fPts[cur].fIndex) + tess.point(fPts[next].fIndex);
1052 mid.scale(0.5f);
1053
1054 if (fPts.count()) {
1055 draw_arrow(canvas, mid, fPts[cur].fNorm, kArrowLength, SK_ColorRED);
1056 mid.fX += (kArrowLength/2) * fPts[cur].fNorm.fX;
1057 mid.fY += (kArrowLength/2) * fPts[cur].fNorm.fY;
1058 }
1059
1060 SkString num;
1061 num.printf("%d", this->origEdgeID(cur));
1062 canvas->drawString(num, mid.fX, mid.fY, paint);
1063
1064 if (fPts.count()) {
1065 draw_arrow(canvas, tess.point(fPts[cur].fIndex), fPts[cur].fBisector,
1066 kArrowLength, SK_ColorBLUE);
1067 }
1068 }
1069 }
1070
draw(SkCanvas * canvas) const1071 void GrAAConvexTessellator::draw(SkCanvas* canvas) const {
1072 for (int i = 0; i < fIndices.count(); i += 3) {
1073 SkASSERT(fIndices[i] < this->numPts()) ;
1074 SkASSERT(fIndices[i+1] < this->numPts()) ;
1075 SkASSERT(fIndices[i+2] < this->numPts()) ;
1076
1077 draw_line(canvas,
1078 this->point(this->fIndices[i]), this->point(this->fIndices[i+1]),
1079 SK_ColorBLACK);
1080 draw_line(canvas,
1081 this->point(this->fIndices[i+1]), this->point(this->fIndices[i+2]),
1082 SK_ColorBLACK);
1083 draw_line(canvas,
1084 this->point(this->fIndices[i+2]), this->point(this->fIndices[i]),
1085 SK_ColorBLACK);
1086 }
1087
1088 fInitialRing.draw(canvas, *this);
1089 for (int i = 0; i < fRings.count(); ++i) {
1090 fRings[i]->draw(canvas, *this);
1091 }
1092
1093 for (int i = 0; i < this->numPts(); ++i) {
1094 draw_point(canvas,
1095 this->point(i), 0.5f + (this->depth(i)/(2 * kAntialiasingRadius)),
1096 !this->movable(i));
1097
1098 SkPaint paint;
1099 paint.setTextSize(kPointTextSize);
1100 if (this->depth(i) <= -kAntialiasingRadius) {
1101 paint.setColor(SK_ColorWHITE);
1102 }
1103
1104 SkString num;
1105 num.printf("%d", i);
1106 canvas->drawString(num,
1107 this->point(i).fX, this->point(i).fY+(kPointRadius/2.0f),
1108 paint);
1109 }
1110 }
1111
1112 #endif
1113