blob: b335a25f0a9eaf8ff57722e807770046dfaf8423 [file] [log] [blame]
Brian Salomonab664fa2017-03-24 16:07:20 +00001/*
2 * Copyright 2017 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
Jim Van Verth41964ed2018-03-28 10:10:30 -04008#include "SkOffsetPolygon.h"
Brian Salomonab664fa2017-03-24 16:07:20 +00009
Cary Clarkdf429f32017-11-08 11:44:31 -050010#include "SkPointPriv.h"
Jim Van Verth4db18ed2018-04-03 10:00:37 -040011#include "SkTArray.h"
Brian Salomonab664fa2017-03-24 16:07:20 +000012#include "SkTemplates.h"
Jim Van Verth4db18ed2018-04-03 10:00:37 -040013#include "SkTDPQueue.h"
Brian Salomonab664fa2017-03-24 16:07:20 +000014
Jim Van Verth4db18ed2018-04-03 10:00:37 -040015struct OffsetSegment {
Brian Salomonab664fa2017-03-24 16:07:20 +000016 SkPoint fP0;
17 SkPoint fP1;
18};
19
20// Computes perpDot for point compared to segment.
21// A positive value means the point is to the left of the segment,
22// negative is to the right, 0 is collinear.
23static int compute_side(const SkPoint& s0, const SkPoint& s1, const SkPoint& p) {
24 SkVector v0 = s1 - s0;
25 SkVector v1 = p - s0;
26 SkScalar perpDot = v0.cross(v1);
27 if (!SkScalarNearlyZero(perpDot)) {
28 return ((perpDot > 0) ? 1 : -1);
29 }
30
31 return 0;
32}
33
34// returns 1 for ccw, -1 for cw and 0 if degenerate
35static int get_winding(const SkPoint* polygonVerts, int polygonSize) {
36 SkPoint p0 = polygonVerts[0];
37 SkPoint p1 = polygonVerts[1];
38
39 for (int i = 2; i < polygonSize; ++i) {
40 SkPoint p2 = polygonVerts[i];
41
42 // determine if cw or ccw
43 int side = compute_side(p0, p1, p2);
44 if (0 != side) {
45 return ((side > 0) ? 1 : -1);
46 }
47
48 // if nearly collinear, treat as straight line and continue
49 p1 = p2;
50 }
51
52 return 0;
53}
54
Jim Van Verthbdde4282018-06-14 09:09:18 -040055// Helper function to compute the individual vector for non-equal offsets
56inline void compute_offset(SkScalar d, const SkPoint& polyPoint, int side,
57 const SkPoint& outerTangentIntersect, SkVector* v) {
58 SkScalar dsq = d * d;
59 SkVector dP = outerTangentIntersect - polyPoint;
60 SkScalar dPlenSq = SkPointPriv::LengthSqd(dP);
61 if (SkScalarNearlyZero(dPlenSq)) {
62 v->set(0, 0);
63 } else {
64 SkScalar discrim = SkScalarSqrt(dPlenSq - dsq);
65 v->fX = (dsq*dP.fX - side * d*dP.fY*discrim) / dPlenSq;
66 v->fY = (dsq*dP.fY + side * d*dP.fX*discrim) / dPlenSq;
67 }
68}
69
70// Compute difference vector to offset p0-p1 'd0' and 'd1' units in direction specified by 'side'
71bool compute_offset_vectors(const SkPoint& p0, const SkPoint& p1, SkScalar d0, SkScalar d1,
72 int side, SkPoint* vector0, SkPoint* vector1) {
Jim Van Verthda965502017-04-11 15:29:14 -040073 SkASSERT(side == -1 || side == 1);
Jim Van Verthda965502017-04-11 15:29:14 -040074 if (SkScalarNearlyEqual(d0, d1)) {
75 // if distances are equal, can just outset by the perpendicular
Jim Van Verthbdde4282018-06-14 09:09:18 -040076 SkVector perp = SkVector::Make(p0.fY - p1.fY, p1.fX - p0.fX);
Jim Van Verthda965502017-04-11 15:29:14 -040077 perp.setLength(d0*side);
Jim Van Verthbdde4282018-06-14 09:09:18 -040078 *vector0 = perp;
79 *vector1 = perp;
Jim Van Verthda965502017-04-11 15:29:14 -040080 } else {
Jim Van Verthbdde4282018-06-14 09:09:18 -040081 SkScalar d0abs = SkTAbs(d0);
82 SkScalar d1abs = SkTAbs(d1);
Jim Van Verthda965502017-04-11 15:29:14 -040083 // Otherwise we need to compute the outer tangent.
84 // See: http://www.ambrsoft.com/TrigoCalc/Circles2/Circles2Tangent_.htm
Jim Van Verthbdde4282018-06-14 09:09:18 -040085 if (d0abs < d1abs) {
Jim Van Verthda965502017-04-11 15:29:14 -040086 side = -side;
87 }
Jim Van Verthbdde4282018-06-14 09:09:18 -040088 SkScalar dD = d0abs - d1abs;
Jim Van Verthda965502017-04-11 15:29:14 -040089 // if one circle is inside another, we can't compute an offset
Cary Clarkdf429f32017-11-08 11:44:31 -050090 if (dD*dD >= SkPointPriv::DistanceToSqd(p0, p1)) {
Jim Van Verthda965502017-04-11 15:29:14 -040091 return false;
92 }
Jim Van Verthbdde4282018-06-14 09:09:18 -040093 SkPoint outerTangentIntersect = SkPoint::Make((p1.fX*d0abs - p0.fX*d1abs) / dD,
94 (p1.fY*d0abs - p0.fY*d1abs) / dD);
Jim Van Verthda965502017-04-11 15:29:14 -040095
Jim Van Verthbdde4282018-06-14 09:09:18 -040096 compute_offset(d0, p0, side, outerTangentIntersect, vector0);
97 compute_offset(d1, p1, side, outerTangentIntersect, vector1);
Jim Van Verthda965502017-04-11 15:29:14 -040098 }
99
100 return true;
Brian Salomonab664fa2017-03-24 16:07:20 +0000101}
102
Jim Van Verthbdde4282018-06-14 09:09:18 -0400103// Offset line segment p0-p1 'd0' and 'd1' units in the direction specified by 'side'
104bool SkOffsetSegment(const SkPoint& p0, const SkPoint& p1, SkScalar d0, SkScalar d1,
105 int side, SkPoint* offset0, SkPoint* offset1) {
106 SkVector v0, v1;
107 if (!compute_offset_vectors(p0, p1, d0, d1, side, &v0, &v1)) {
108 return false;
109 }
110 *offset0 = p0 + v0;
111 *offset1 = p1 + v1;
112
113 return true;
114}
115
Brian Salomonab664fa2017-03-24 16:07:20 +0000116// Compute the intersection 'p' between segments s0 and s1, if any.
117// 's' is the parametric value for the intersection along 's0' & 't' is the same for 's1'.
118// Returns false if there is no intersection.
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400119static bool compute_intersection(const OffsetSegment& s0, const OffsetSegment& s1,
Brian Salomonab664fa2017-03-24 16:07:20 +0000120 SkPoint* p, SkScalar* s, SkScalar* t) {
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400121 // Common cases for polygon chains -- check if endpoints are touching
122 if (SkPointPriv::EqualsWithinTolerance(s0.fP1, s1.fP0)) {
123 *p = s0.fP1;
124 *s = SK_Scalar1;
125 *t = 0;
126 return true;
127 }
128 if (SkPointPriv::EqualsWithinTolerance(s1.fP1, s0.fP0)) {
129 *p = s1.fP1;
130 *s = 0;
131 *t = SK_Scalar1;
132 return true;
133 }
134
Brian Salomonab664fa2017-03-24 16:07:20 +0000135 SkVector v0 = s0.fP1 - s0.fP0;
136 SkVector v1 = s1.fP1 - s1.fP0;
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400137 // We should have culled coincident points before this
138 SkASSERT(!SkPointPriv::EqualsWithinTolerance(s0.fP0, s0.fP1));
139 SkASSERT(!SkPointPriv::EqualsWithinTolerance(s1.fP0, s1.fP1));
Brian Salomonab664fa2017-03-24 16:07:20 +0000140
141 SkVector d = s1.fP0 - s0.fP0;
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400142 SkScalar perpDot = v0.cross(v1);
143 SkScalar localS, localT;
144 if (SkScalarNearlyZero(perpDot)) {
145 // segments are parallel, but not collinear
146 if (!SkScalarNearlyZero(d.dot(d), SK_ScalarNearlyZero*SK_ScalarNearlyZero)) {
147 return false;
148 }
149
150 // project segment1's endpoints onto segment0
151 localS = d.fX / v0.fX;
152 localT = 0;
153 if (localS < 0 || localS > SK_Scalar1) {
154 // the first endpoint doesn't lie on segment0, try the other one
155 SkScalar oldLocalS = localS;
156 localS = (s1.fP1.fX - s0.fP0.fX) / v0.fX;
157 localT = SK_Scalar1;
158 if (localS < 0 || localS > SK_Scalar1) {
159 // it's possible that segment1's interval surrounds segment0
160 // this is false if the params have the same signs, and in that case no collision
161 if (localS*oldLocalS > 0) {
162 return false;
163 }
164 // otherwise project segment0's endpoint onto segment1 instead
165 localS = 0;
166 localT = -d.fX / v1.fX;
167 }
168 }
169 } else {
170 localS = d.cross(v1) / perpDot;
171 if (localS < 0 || localS > SK_Scalar1) {
172 return false;
173 }
174 localT = d.cross(v0) / perpDot;
175 if (localT < 0 || localT > SK_Scalar1) {
176 return false;
177 }
Brian Salomonab664fa2017-03-24 16:07:20 +0000178 }
179
180 v0 *= localS;
181 *p = s0.fP0 + v0;
182 *s = localS;
183 *t = localT;
184
185 return true;
186}
187
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400188// computes the line intersection and then the distance to s0's endpoint
189static SkScalar compute_crossing_distance(const OffsetSegment& s0, const OffsetSegment& s1) {
190 SkVector v0 = s0.fP1 - s0.fP0;
191 SkVector v1 = s1.fP1 - s1.fP0;
192
193 SkScalar perpDot = v0.cross(v1);
194 if (SkScalarNearlyZero(perpDot)) {
195 // segments are parallel
196 return SK_ScalarMax;
197 }
198
199 SkVector d = s1.fP0 - s0.fP0;
200 SkScalar localS = d.cross(v1) / perpDot;
201 if (localS < 0) {
202 localS = -localS;
203 } else {
204 localS -= SK_Scalar1;
205 }
206
207 localS *= v0.length();
208
209 return localS;
210}
211
Jim Van Verth0513f142017-03-24 14:28:57 -0400212static bool is_convex(const SkTDArray<SkPoint>& poly) {
213 if (poly.count() <= 3) {
214 return true;
215 }
216
217 SkVector v0 = poly[0] - poly[poly.count() - 1];
218 SkVector v1 = poly[1] - poly[poly.count() - 1];
219 SkScalar winding = v0.cross(v1);
220
221 for (int i = 0; i < poly.count() - 1; ++i) {
222 int j = i + 1;
223 int k = (i + 2) % poly.count();
224
225 SkVector v0 = poly[j] - poly[i];
226 SkVector v1 = poly[k] - poly[i];
227 SkScalar perpDot = v0.cross(v1);
Jim Van Verth291932e2017-03-29 14:37:28 -0400228 if (winding*perpDot < 0) {
Jim Van Verth0513f142017-03-24 14:28:57 -0400229 return false;
230 }
231 }
232
233 return true;
234}
Jim Van Verth0513f142017-03-24 14:28:57 -0400235
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400236struct EdgeData {
237 OffsetSegment fInset;
238 SkPoint fIntersection;
239 SkScalar fTValue;
Jim Van Verth872da6b2018-04-10 11:24:11 -0400240 uint16_t fStart;
241 uint16_t fEnd;
242 uint16_t fIndex;
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400243 bool fValid;
244
245 void init() {
246 fIntersection = fInset.fP0;
247 fTValue = SK_ScalarMin;
Jim Van Verth872da6b2018-04-10 11:24:11 -0400248 fStart = 0;
249 fEnd = 0;
250 fIndex = 0;
251 fValid = true;
252 }
253
254 void init(uint16_t start, uint16_t end) {
255 fIntersection = fInset.fP0;
256 fTValue = SK_ScalarMin;
257 fStart = start;
258 fEnd = end;
259 fIndex = start;
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400260 fValid = true;
261 }
262};
263
Brian Salomonab664fa2017-03-24 16:07:20 +0000264// The objective here is to inset all of the edges by the given distance, and then
265// remove any invalid inset edges by detecting right-hand turns. In a ccw polygon,
266// we should only be making left-hand turns (for cw polygons, we use the winding
267// parameter to reverse this). We detect this by checking whether the second intersection
268// on an edge is closer to its tail than the first one.
269//
270// We might also have the case that there is no intersection between two neighboring inset edges.
271// In this case, one edge will lie to the right of the other and should be discarded along with
272// its previous intersection (if any).
273//
274// Note: the assumption is that inputPolygon is convex and has no coincident points.
275//
276bool SkInsetConvexPolygon(const SkPoint* inputPolygonVerts, int inputPolygonSize,
Jim Van Verthbdde4282018-06-14 09:09:18 -0400277 std::function<SkScalar(const SkPoint&)> insetDistanceFunc,
Jim Van Verthda965502017-04-11 15:29:14 -0400278 SkTDArray<SkPoint>* insetPolygon) {
Brian Salomonab664fa2017-03-24 16:07:20 +0000279 if (inputPolygonSize < 3) {
280 return false;
281 }
282
283 int winding = get_winding(inputPolygonVerts, inputPolygonSize);
284 if (0 == winding) {
285 return false;
286 }
287
288 // set up
Brian Salomonab664fa2017-03-24 16:07:20 +0000289 SkAutoSTMalloc<64, EdgeData> edgeData(inputPolygonSize);
290 for (int i = 0; i < inputPolygonSize; ++i) {
Brian Salomonab664fa2017-03-24 16:07:20 +0000291 int j = (i + 1) % inputPolygonSize;
Jim Van Verthb55eb282017-07-18 14:13:45 -0400292 int k = (i + 2) % inputPolygonSize;
293 // check for convexity just to be sure
294 if (compute_side(inputPolygonVerts[i], inputPolygonVerts[j],
295 inputPolygonVerts[k])*winding < 0) {
296 return false;
297 }
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400298 if (!SkOffsetSegment(inputPolygonVerts[i], inputPolygonVerts[j],
Jim Van Verthbdde4282018-06-14 09:09:18 -0400299 insetDistanceFunc(inputPolygonVerts[i]),
300 insetDistanceFunc(inputPolygonVerts[j]),
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400301 winding,
302 &edgeData[i].fInset.fP0, &edgeData[i].fInset.fP1)) {
303 return false;
304 }
305 edgeData[i].init();
Brian Salomonab664fa2017-03-24 16:07:20 +0000306 }
307
308 int prevIndex = inputPolygonSize - 1;
309 int currIndex = 0;
310 int insetVertexCount = inputPolygonSize;
311 while (prevIndex != currIndex) {
312 if (!edgeData[prevIndex].fValid) {
313 prevIndex = (prevIndex + inputPolygonSize - 1) % inputPolygonSize;
314 continue;
315 }
316
317 SkScalar s, t;
318 SkPoint intersection;
319 if (compute_intersection(edgeData[prevIndex].fInset, edgeData[currIndex].fInset,
320 &intersection, &s, &t)) {
321 // if new intersection is further back on previous inset from the prior intersection
322 if (s < edgeData[prevIndex].fTValue) {
323 // no point in considering this one again
324 edgeData[prevIndex].fValid = false;
325 --insetVertexCount;
326 // go back one segment
327 prevIndex = (prevIndex + inputPolygonSize - 1) % inputPolygonSize;
328 // we've already considered this intersection, we're done
329 } else if (edgeData[currIndex].fTValue > SK_ScalarMin &&
Cary Clarkdf429f32017-11-08 11:44:31 -0500330 SkPointPriv::EqualsWithinTolerance(intersection,
331 edgeData[currIndex].fIntersection,
Brian Salomonab664fa2017-03-24 16:07:20 +0000332 1.0e-6f)) {
333 break;
334 } else {
335 // add intersection
336 edgeData[currIndex].fIntersection = intersection;
337 edgeData[currIndex].fTValue = t;
338
339 // go to next segment
340 prevIndex = currIndex;
341 currIndex = (currIndex + 1) % inputPolygonSize;
342 }
343 } else {
344 // if prev to right side of curr
345 int side = winding*compute_side(edgeData[currIndex].fInset.fP0,
346 edgeData[currIndex].fInset.fP1,
347 edgeData[prevIndex].fInset.fP1);
348 if (side < 0 && side == winding*compute_side(edgeData[currIndex].fInset.fP0,
349 edgeData[currIndex].fInset.fP1,
350 edgeData[prevIndex].fInset.fP0)) {
351 // no point in considering this one again
352 edgeData[prevIndex].fValid = false;
353 --insetVertexCount;
354 // go back one segment
355 prevIndex = (prevIndex + inputPolygonSize - 1) % inputPolygonSize;
356 } else {
357 // move to next segment
358 edgeData[currIndex].fValid = false;
359 --insetVertexCount;
360 currIndex = (currIndex + 1) % inputPolygonSize;
361 }
362 }
363 }
364
Jim Van Verthda965502017-04-11 15:29:14 -0400365 // store all the valid intersections that aren't nearly coincident
366 // TODO: look at the main algorithm and see if we can detect these better
367 static constexpr SkScalar kCleanupTolerance = 0.01f;
368
Brian Salomonab664fa2017-03-24 16:07:20 +0000369 insetPolygon->reset();
Mike Klein23e45442018-04-19 09:29:02 -0400370 if (insetVertexCount >= 0) {
371 insetPolygon->setReserve(insetVertexCount);
372 }
Jim Van Verthda965502017-04-11 15:29:14 -0400373 currIndex = -1;
Brian Salomonab664fa2017-03-24 16:07:20 +0000374 for (int i = 0; i < inputPolygonSize; ++i) {
Jim Van Verthda965502017-04-11 15:29:14 -0400375 if (edgeData[i].fValid && (currIndex == -1 ||
Cary Clarkdf429f32017-11-08 11:44:31 -0500376 !SkPointPriv::EqualsWithinTolerance(edgeData[i].fIntersection,
377 (*insetPolygon)[currIndex],
378 kCleanupTolerance))) {
Brian Salomonab664fa2017-03-24 16:07:20 +0000379 *insetPolygon->push() = edgeData[i].fIntersection;
Jim Van Verthda965502017-04-11 15:29:14 -0400380 currIndex++;
Brian Salomonab664fa2017-03-24 16:07:20 +0000381 }
382 }
Jim Van Verthda965502017-04-11 15:29:14 -0400383 // make sure the first and last points aren't coincident
384 if (currIndex >= 1 &&
Cary Clarkdf429f32017-11-08 11:44:31 -0500385 SkPointPriv::EqualsWithinTolerance((*insetPolygon)[0], (*insetPolygon)[currIndex],
386 kCleanupTolerance)) {
Jim Van Verthda965502017-04-11 15:29:14 -0400387 insetPolygon->pop();
388 }
Brian Salomonab664fa2017-03-24 16:07:20 +0000389
Jim Van Verthb55eb282017-07-18 14:13:45 -0400390 return (insetPolygon->count() >= 3 && is_convex(*insetPolygon));
Brian Salomonab664fa2017-03-24 16:07:20 +0000391}
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400392
393// compute the number of points needed for a circular join when offsetting a reflex vertex
394static void compute_radial_steps(const SkVector& v1, const SkVector& v2, SkScalar r,
395 SkScalar* rotSin, SkScalar* rotCos, int* n) {
396 const SkScalar kRecipPixelsPerArcSegment = 0.25f;
397
398 SkScalar rCos = v1.dot(v2);
399 SkScalar rSin = v1.cross(v2);
400 SkScalar theta = SkScalarATan2(rSin, rCos);
401
402 int steps = SkScalarRoundToInt(SkScalarAbs(r*theta*kRecipPixelsPerArcSegment));
403
404 SkScalar dTheta = theta / steps;
405 *rotSin = SkScalarSinCos(dTheta, rotCos);
406 *n = steps;
407}
408
409// tolerant less-than comparison
410static inline bool nearly_lt(SkScalar a, SkScalar b, SkScalar tolerance = SK_ScalarNearlyZero) {
411 return a < b - tolerance;
412}
413
414// a point is "left" to another if its x coordinate is less, or if equal, its y coordinate
415static bool left(const SkPoint& p0, const SkPoint& p1) {
416 return nearly_lt(p0.fX, p1.fX) ||
417 (SkScalarNearlyEqual(p0.fX, p1.fX) && nearly_lt(p0.fY, p1.fY));
418}
419
420struct Vertex {
421 static bool Left(const Vertex& qv0, const Vertex& qv1) {
422 return left(qv0.fPosition, qv1.fPosition);
423 }
424 // packed to fit into 16 bytes (one cache line)
425 SkPoint fPosition;
426 uint16_t fIndex; // index in unsorted polygon
427 uint16_t fPrevIndex; // indices for previous and next vertex in unsorted polygon
428 uint16_t fNextIndex;
429 uint16_t fFlags;
430};
431
432enum VertexFlags {
433 kPrevLeft_VertexFlag = 0x1,
434 kNextLeft_VertexFlag = 0x2,
435};
436
437struct Edge {
438 // returns true if "this" is above "that"
439 bool above(const Edge& that, SkScalar tolerance = SK_ScalarNearlyZero) {
440 SkASSERT(nearly_lt(this->fSegment.fP0.fX, that.fSegment.fP0.fX, tolerance) ||
441 SkScalarNearlyEqual(this->fSegment.fP0.fX, that.fSegment.fP0.fX, tolerance));
442 // The idea here is that if the vector between the origins of the two segments (dv)
443 // rotates counterclockwise up to the vector representing the "this" segment (u),
444 // then we know that "this" is above that. If the result is clockwise we say it's below.
445 SkVector dv = that.fSegment.fP0 - this->fSegment.fP0;
446 SkVector u = this->fSegment.fP1 - this->fSegment.fP0;
447 SkScalar cross = dv.cross(u);
448 if (cross > tolerance) {
449 return true;
450 } else if (cross < -tolerance) {
451 return false;
452 }
453 // If the result is 0 then either the two origins are equal or the origin of "that"
454 // lies on dv. So then we try the same for the vector from the tail of "this"
455 // to the head of "that". Again, ccw means "this" is above "that".
456 dv = that.fSegment.fP1 - this->fSegment.fP0;
457 return (dv.cross(u) > tolerance);
458 }
459
460 bool intersect(const Edge& that) const {
461 SkPoint intersection;
462 SkScalar s, t;
463 // check first to see if these edges are neighbors in the polygon
464 if (this->fIndex0 == that.fIndex0 || this->fIndex1 == that.fIndex0 ||
465 this->fIndex0 == that.fIndex1 || this->fIndex1 == that.fIndex1) {
466 return false;
467 }
468 return compute_intersection(this->fSegment, that.fSegment, &intersection, &s, &t);
469 }
470
471 bool operator==(const Edge& that) const {
472 return (this->fIndex0 == that.fIndex0 && this->fIndex1 == that.fIndex1);
473 }
474
475 bool operator!=(const Edge& that) const {
476 return !operator==(that);
477 }
478
479 OffsetSegment fSegment;
480 int32_t fIndex0; // indices for previous and next vertex
481 int32_t fIndex1;
482};
483
484class EdgeList {
485public:
486 void reserve(int count) { fEdges.reserve(count); }
487
488 bool insert(const Edge& newEdge) {
489 // linear search for now (expected case is very few active edges)
490 int insertIndex = 0;
491 while (insertIndex < fEdges.count() && fEdges[insertIndex].above(newEdge)) {
492 ++insertIndex;
493 }
494 // if we intersect with the existing edge above or below us
495 // then we know this polygon is not simple, so don't insert, just fail
496 if (insertIndex > 0 && newEdge.intersect(fEdges[insertIndex - 1])) {
497 return false;
498 }
499 if (insertIndex < fEdges.count() && newEdge.intersect(fEdges[insertIndex])) {
500 return false;
501 }
502
503 fEdges.push_back();
504 for (int i = fEdges.count() - 1; i > insertIndex; --i) {
505 fEdges[i] = fEdges[i - 1];
506 }
507 fEdges[insertIndex] = newEdge;
508
509 return true;
510 }
511
512 bool remove(const Edge& edge) {
513 SkASSERT(fEdges.count() > 0);
514
515 // linear search for now (expected case is very few active edges)
516 int removeIndex = 0;
517 while (removeIndex < fEdges.count() && fEdges[removeIndex] != edge) {
518 ++removeIndex;
519 }
520 // we'd better find it or something is wrong
521 SkASSERT(removeIndex < fEdges.count());
522
523 // if we intersect with the edge above or below us
524 // then we know this polygon is not simple, so don't remove, just fail
525 if (removeIndex > 0 && fEdges[removeIndex].intersect(fEdges[removeIndex-1])) {
526 return false;
527 }
528 if (removeIndex < fEdges.count()-1) {
529 if (fEdges[removeIndex].intersect(fEdges[removeIndex + 1])) {
530 return false;
531 }
532 // copy over the old entry
533 memmove(&fEdges[removeIndex], &fEdges[removeIndex + 1],
534 sizeof(Edge)*(fEdges.count() - removeIndex - 1));
535 }
536
537 fEdges.pop_back();
538 return true;
539 }
540
541private:
542 SkSTArray<1, Edge> fEdges;
543};
544
545// Here we implement a sweep line algorithm to determine whether the provided points
546// represent a simple polygon, i.e., the polygon is non-self-intersecting.
547// We first insert the vertices into a priority queue sorting horizontally from left to right.
548// Then as we pop the vertices from the queue we generate events which indicate that an edge
549// should be added or removed from an edge list. If any intersections are detected in the edge
550// list, then we know the polygon is self-intersecting and hence not simple.
551static bool is_simple_polygon(const SkPoint* polygon, int polygonSize) {
552 SkTDPQueue <Vertex, Vertex::Left> vertexQueue;
553 EdgeList sweepLine;
554
555 sweepLine.reserve(polygonSize);
556 for (int i = 0; i < polygonSize; ++i) {
557 Vertex newVertex;
558 newVertex.fPosition = polygon[i];
559 newVertex.fIndex = i;
560 newVertex.fPrevIndex = (i - 1 + polygonSize) % polygonSize;
561 newVertex.fNextIndex = (i + 1) % polygonSize;
562 newVertex.fFlags = 0;
563 if (left(polygon[newVertex.fPrevIndex], polygon[i])) {
564 newVertex.fFlags |= kPrevLeft_VertexFlag;
565 }
566 if (left(polygon[newVertex.fNextIndex], polygon[i])) {
567 newVertex.fFlags |= kNextLeft_VertexFlag;
568 }
569 vertexQueue.insert(newVertex);
570 }
571
572 // pop each vertex from the queue and generate events depending on
573 // where it lies relative to its neighboring edges
574 while (vertexQueue.count() > 0) {
575 const Vertex& v = vertexQueue.peek();
576
577 // check edge to previous vertex
578 if (v.fFlags & kPrevLeft_VertexFlag) {
579 Edge edge{ { polygon[v.fPrevIndex], v.fPosition }, v.fPrevIndex, v.fIndex };
580 if (!sweepLine.remove(edge)) {
581 break;
582 }
583 } else {
584 Edge edge{ { v.fPosition, polygon[v.fPrevIndex] }, v.fIndex, v.fPrevIndex };
585 if (!sweepLine.insert(edge)) {
586 break;
587 }
588 }
589
590 // check edge to next vertex
591 if (v.fFlags & kNextLeft_VertexFlag) {
592 Edge edge{ { polygon[v.fNextIndex], v.fPosition }, v.fNextIndex, v.fIndex };
593 if (!sweepLine.remove(edge)) {
594 break;
595 }
596 } else {
597 Edge edge{ { v.fPosition, polygon[v.fNextIndex] }, v.fIndex, v.fNextIndex };
598 if (!sweepLine.insert(edge)) {
599 break;
600 }
601 }
602
603 vertexQueue.pop();
604 }
605
606 return (vertexQueue.count() == 0);
607}
608
609// TODO: assuming a constant offset here -- do we want to support variable offset?
610bool SkOffsetSimplePolygon(const SkPoint* inputPolygonVerts, int inputPolygonSize,
Jim Van Verthbdde4282018-06-14 09:09:18 -0400611 std::function<SkScalar(const SkPoint&)> offsetDistanceFunc,
612 SkTDArray<SkPoint>* offsetPolygon, SkTDArray<int>* polygonIndices) {
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400613 if (inputPolygonSize < 3) {
614 return false;
615 }
616
617 if (!is_simple_polygon(inputPolygonVerts, inputPolygonSize)) {
618 return false;
619 }
620
621 // compute area and use sign to determine winding
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400622 SkScalar quadArea = 0;
623 for (int curr = 0; curr < inputPolygonSize; ++curr) {
624 int next = (curr + 1) % inputPolygonSize;
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400625 quadArea += inputPolygonVerts[curr].cross(inputPolygonVerts[next]);
626 }
Jim Van Verthbdde4282018-06-14 09:09:18 -0400627 if (SkScalarNearlyZero(quadArea)) {
628 return false;
629 }
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400630 // 1 == ccw, -1 == cw
631 int winding = (quadArea > 0) ? 1 : -1;
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400632
Jim Van Verthbdde4282018-06-14 09:09:18 -0400633 // build normals
634 SkAutoSTMalloc<64, SkVector> normal0(inputPolygonSize);
635 SkAutoSTMalloc<64, SkVector> normal1(inputPolygonSize);
636 SkScalar currOffset = offsetDistanceFunc(inputPolygonVerts[0]);
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400637 for (int curr = 0; curr < inputPolygonSize; ++curr) {
Jim Van Verthbdde4282018-06-14 09:09:18 -0400638 int next = (curr + 1) % inputPolygonSize;
639 SkScalar nextOffset = offsetDistanceFunc(inputPolygonVerts[next]);
640 if (!compute_offset_vectors(inputPolygonVerts[curr], inputPolygonVerts[next],
641 currOffset, nextOffset, winding,
642 &normal0[curr], &normal1[next])) {
643 return false;
644 }
645 currOffset = nextOffset;
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400646 }
647
648 // build initial offset edge list
649 SkSTArray<64, EdgeData> edgeData(inputPolygonSize);
650 int prevIndex = inputPolygonSize - 1;
651 int currIndex = 0;
652 int nextIndex = 1;
653 while (currIndex < inputPolygonSize) {
654 int side = compute_side(inputPolygonVerts[prevIndex],
655 inputPolygonVerts[currIndex],
656 inputPolygonVerts[nextIndex]);
Jim Van Verthbdde4282018-06-14 09:09:18 -0400657 SkScalar offset = offsetDistanceFunc(inputPolygonVerts[currIndex]);
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400658 // if reflex point, fill in curve
659 if (side*winding*offset < 0) {
660 SkScalar rotSin, rotCos;
661 int numSteps;
Jim Van Verthbdde4282018-06-14 09:09:18 -0400662 SkVector prevNormal = normal1[currIndex];
663 compute_radial_steps(prevNormal, normal0[currIndex], SkScalarAbs(offset),
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400664 &rotSin, &rotCos, &numSteps);
665 for (int i = 0; i < numSteps - 1; ++i) {
666 SkVector currNormal = SkVector::Make(prevNormal.fX*rotCos - prevNormal.fY*rotSin,
667 prevNormal.fY*rotCos + prevNormal.fX*rotSin);
668 EdgeData& edge = edgeData.push_back();
669 edge.fInset.fP0 = inputPolygonVerts[currIndex] + prevNormal;
670 edge.fInset.fP1 = inputPolygonVerts[currIndex] + currNormal;
Jim Van Verth872da6b2018-04-10 11:24:11 -0400671 edge.init(currIndex, currIndex);
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400672 prevNormal = currNormal;
673 }
674 EdgeData& edge = edgeData.push_back();
675 edge.fInset.fP0 = inputPolygonVerts[currIndex] + prevNormal;
Jim Van Verthbdde4282018-06-14 09:09:18 -0400676 edge.fInset.fP1 = inputPolygonVerts[currIndex] + normal0[currIndex];
Jim Van Verth872da6b2018-04-10 11:24:11 -0400677 edge.init(currIndex, currIndex);
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400678 }
679
680 // Add the edge
681 EdgeData& edge = edgeData.push_back();
Jim Van Verthbdde4282018-06-14 09:09:18 -0400682 edge.fInset.fP0 = inputPolygonVerts[currIndex] + normal0[currIndex];
683 edge.fInset.fP1 = inputPolygonVerts[nextIndex] + normal1[nextIndex];
Jim Van Verth872da6b2018-04-10 11:24:11 -0400684 edge.init(currIndex, nextIndex);
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400685
686 prevIndex = currIndex;
687 currIndex++;
688 nextIndex = (nextIndex + 1) % inputPolygonSize;
689 }
690
691 int edgeDataSize = edgeData.count();
692 prevIndex = edgeDataSize - 1;
693 currIndex = 0;
694 int insetVertexCount = edgeDataSize;
695 while (prevIndex != currIndex) {
696 if (!edgeData[prevIndex].fValid) {
697 prevIndex = (prevIndex + edgeDataSize - 1) % edgeDataSize;
698 continue;
699 }
Jim Van Verth872da6b2018-04-10 11:24:11 -0400700 if (!edgeData[currIndex].fValid) {
701 currIndex = (currIndex + 1) % edgeDataSize;
702 continue;
703 }
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400704
705 SkScalar s, t;
706 SkPoint intersection;
707 if (compute_intersection(edgeData[prevIndex].fInset, edgeData[currIndex].fInset,
708 &intersection, &s, &t)) {
709 // if new intersection is further back on previous inset from the prior intersection
710 if (s < edgeData[prevIndex].fTValue) {
711 // no point in considering this one again
712 edgeData[prevIndex].fValid = false;
713 --insetVertexCount;
714 // go back one segment
715 prevIndex = (prevIndex + edgeDataSize - 1) % edgeDataSize;
716 // we've already considered this intersection, we're done
717 } else if (edgeData[currIndex].fTValue > SK_ScalarMin &&
718 SkPointPriv::EqualsWithinTolerance(intersection,
719 edgeData[currIndex].fIntersection,
720 1.0e-6f)) {
721 break;
722 } else {
723 // add intersection
724 edgeData[currIndex].fIntersection = intersection;
725 edgeData[currIndex].fTValue = t;
Jim Van Verth872da6b2018-04-10 11:24:11 -0400726 edgeData[currIndex].fIndex = edgeData[prevIndex].fEnd;
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400727
728 // go to next segment
729 prevIndex = currIndex;
730 currIndex = (currIndex + 1) % edgeDataSize;
731 }
732 } else {
733 // If there is no intersection, we want to minimize the distance between
734 // the point where the segment lines cross and the segments themselves.
735 SkScalar prevPrevIndex = (prevIndex + edgeDataSize - 1) % edgeDataSize;
736 SkScalar currNextIndex = (currIndex + 1) % edgeDataSize;
737 SkScalar dist0 = compute_crossing_distance(edgeData[currIndex].fInset,
738 edgeData[prevPrevIndex].fInset);
739 SkScalar dist1 = compute_crossing_distance(edgeData[prevIndex].fInset,
740 edgeData[currNextIndex].fInset);
741 if (dist0 < dist1) {
742 edgeData[prevIndex].fValid = false;
743 prevIndex = prevPrevIndex;
744 } else {
745 edgeData[currIndex].fValid = false;
746 currIndex = currNextIndex;
747 }
748 --insetVertexCount;
749 }
750 }
751
752 // store all the valid intersections that aren't nearly coincident
753 // TODO: look at the main algorithm and see if we can detect these better
754 static constexpr SkScalar kCleanupTolerance = 0.01f;
755
756 offsetPolygon->reset();
757 offsetPolygon->setReserve(insetVertexCount);
758 currIndex = -1;
759 for (int i = 0; i < edgeData.count(); ++i) {
760 if (edgeData[i].fValid && (currIndex == -1 ||
761 !SkPointPriv::EqualsWithinTolerance(edgeData[i].fIntersection,
762 (*offsetPolygon)[currIndex],
763 kCleanupTolerance))) {
764 *offsetPolygon->push() = edgeData[i].fIntersection;
Jim Van Verth872da6b2018-04-10 11:24:11 -0400765 if (polygonIndices) {
766 *polygonIndices->push() = edgeData[i].fIndex;
767 }
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400768 currIndex++;
769 }
770 }
771 // make sure the first and last points aren't coincident
772 if (currIndex >= 1 &&
773 SkPointPriv::EqualsWithinTolerance((*offsetPolygon)[0], (*offsetPolygon)[currIndex],
774 kCleanupTolerance)) {
775 offsetPolygon->pop();
Jim Van Verth872da6b2018-04-10 11:24:11 -0400776 if (polygonIndices) {
777 polygonIndices->pop();
778 }
Jim Van Verth4db18ed2018-04-03 10:00:37 -0400779 }
780
781 // compute signed area to check winding (it should be same as the original polygon)
782 quadArea = 0;
783 for (int curr = 0; curr < offsetPolygon->count(); ++curr) {
784 int next = (curr + 1) % offsetPolygon->count();
785 quadArea += (*offsetPolygon)[curr].cross((*offsetPolygon)[next]);
786 }
787
788 return (winding*quadArea > 0 &&
789 is_simple_polygon(offsetPolygon->begin(), offsetPolygon->count()));
790}
791