blob: fc8b892bd0c88ff4eb43c45832dd76efa177e0e0 [file] [log] [blame]
joel.liang8cbb4242017-01-09 18:39:43 -08001/*
2 * Copyright 2017 ARM Ltd.
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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/core/SkDistanceFieldGen.h"
9#include "src/gpu/GrDistanceFieldGenFromVector.h"
Hal Canary95e3c052017-01-11 12:44:43 -050010
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "include/core/SkMatrix.h"
12#include "include/gpu/GrConfig.h"
13#include "include/pathops/SkPathOps.h"
Mike Klein8aa0edf2020-10-16 11:04:18 -050014#include "include/private/SkTPin.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050015#include "src/core/SkAutoMalloc.h"
16#include "src/core/SkGeometry.h"
17#include "src/core/SkPointPriv.h"
18#include "src/core/SkRectPriv.h"
Michael Ludwig663afe52019-06-03 16:46:19 -040019#include "src/gpu/geometry/GrPathUtils.h"
joel.liang8cbb4242017-01-09 18:39:43 -080020
Jim Van Verthde30e422019-12-19 10:13:23 -050021#include "src/pathops/SkPathOpsPoint.h"
22
joel.liang8cbb4242017-01-09 18:39:43 -080023/**
24 * If a scanline (a row of texel) cross from the kRight_SegSide
25 * of a segment to the kLeft_SegSide, the winding score should
26 * add 1.
27 * And winding score should subtract 1 if the scanline cross
28 * from kLeft_SegSide to kRight_SegSide.
29 * Always return kNA_SegSide if the scanline does not cross over
30 * the segment. Winding score should be zero in this case.
31 * You can get the winding number for each texel of the scanline
32 * by adding the winding score from left to right.
33 * Assuming we always start from outside, so the winding number
34 * should always start from zero.
35 * ________ ________
36 * | | | |
37 * ...R|L......L|R.....L|R......R|L..... <= Scanline & side of segment
38 * |+1 |-1 |-1 |+1 <= Winding score
39 * 0 | 1 ^ 0 ^ -1 |0 <= Winding number
40 * |________| |________|
41 *
42 * .......NA................NA..........
43 * 0 0
44 */
45enum SegSide {
46 kLeft_SegSide = -1,
47 kOn_SegSide = 0,
48 kRight_SegSide = 1,
49 kNA_SegSide = 2,
50};
51
52struct DFData {
53 float fDistSq; // distance squared to nearest (so far) edge
54 int fDeltaWindingScore; // +1 or -1 whenever a scanline cross over a segment
55};
56
57///////////////////////////////////////////////////////////////////////////////
58
59/*
Jim Van Verthde30e422019-12-19 10:13:23 -050060 * Type definition for double precision DAffineMatrix
joel.liang8cbb4242017-01-09 18:39:43 -080061 */
62
joel.liang8cbb4242017-01-09 18:39:43 -080063// Matrix with double precision for affine transformation.
64// We don't store row 3 because its always (0, 0, 1).
65class DAffineMatrix {
66public:
67 double operator[](int index) const {
68 SkASSERT((unsigned)index < 6);
69 return fMat[index];
70 }
71
72 double& operator[](int index) {
73 SkASSERT((unsigned)index < 6);
74 return fMat[index];
75 }
76
77 void setAffine(double m11, double m12, double m13,
78 double m21, double m22, double m23) {
79 fMat[0] = m11;
80 fMat[1] = m12;
81 fMat[2] = m13;
82 fMat[3] = m21;
83 fMat[4] = m22;
84 fMat[5] = m23;
85 }
86
87 /** Set the matrix to identity
88 */
89 void reset() {
90 fMat[0] = fMat[4] = 1.0;
91 fMat[1] = fMat[3] =
92 fMat[2] = fMat[5] = 0.0;
93 }
94
95 // alias for reset()
96 void setIdentity() { this->reset(); }
97
Jim Van Verthde30e422019-12-19 10:13:23 -050098 SkDPoint mapPoint(const SkPoint& src) const {
99 SkDPoint pt = {src.fX, src.fY};
joel.liang8cbb4242017-01-09 18:39:43 -0800100 return this->mapPoint(pt);
101 }
102
Jim Van Verthde30e422019-12-19 10:13:23 -0500103 SkDPoint mapPoint(const SkDPoint& src) const {
104 return { fMat[0] * src.fX + fMat[1] * src.fY + fMat[2],
105 fMat[3] * src.fX + fMat[4] * src.fY + fMat[5] };
joel.liang8cbb4242017-01-09 18:39:43 -0800106 }
107private:
108 double fMat[6];
109};
110
111///////////////////////////////////////////////////////////////////////////////
112
113static const double kClose = (SK_Scalar1 / 16.0);
Mike Reed8be952a2017-02-13 20:44:33 -0500114static const double kCloseSqd = kClose * kClose;
joel.liang8cbb4242017-01-09 18:39:43 -0800115static const double kNearlyZero = (SK_Scalar1 / (1 << 18));
116static const double kTangentTolerance = (SK_Scalar1 / (1 << 11));
117static const float kConicTolerance = 0.25f;
118
Jim Van Verthde30e422019-12-19 10:13:23 -0500119// returns true if a >= min(b,c) && a < max(b,c)
joel.liang8cbb4242017-01-09 18:39:43 -0800120static inline bool between_closed_open(double a, double b, double c,
121 double tolerance = 0.0,
122 bool xformToleranceToX = false) {
123 SkASSERT(tolerance >= 0.0);
124 double tolB = tolerance;
125 double tolC = tolerance;
126
127 if (xformToleranceToX) {
128 // Canonical space is y = x^2 and the derivative of x^2 is 2x.
129 // So the slope of the tangent line at point (x, x^2) is 2x.
130 //
131 // /|
132 // sqrt(2x * 2x + 1 * 1) / | 2x
133 // /__|
134 // 1
135 tolB = tolerance / sqrt(4.0 * b * b + 1.0);
136 tolC = tolerance / sqrt(4.0 * c * c + 1.0);
137 }
138 return b < c ? (a >= b - tolB && a < c - tolC) :
139 (a >= c - tolC && a < b - tolB);
140}
141
Jim Van Verthde30e422019-12-19 10:13:23 -0500142// returns true if a >= min(b,c) && a <= max(b,c)
joel.liang8cbb4242017-01-09 18:39:43 -0800143static inline bool between_closed(double a, double b, double c,
144 double tolerance = 0.0,
145 bool xformToleranceToX = false) {
146 SkASSERT(tolerance >= 0.0);
147 double tolB = tolerance;
148 double tolC = tolerance;
149
150 if (xformToleranceToX) {
151 tolB = tolerance / sqrt(4.0 * b * b + 1.0);
152 tolC = tolerance / sqrt(4.0 * c * c + 1.0);
153 }
154 return b < c ? (a >= b - tolB && a <= c + tolC) :
155 (a >= c - tolC && a <= b + tolB);
156}
157
158static inline bool nearly_zero(double x, double tolerance = kNearlyZero) {
159 SkASSERT(tolerance >= 0.0);
160 return fabs(x) <= tolerance;
161}
162
163static inline bool nearly_equal(double x, double y,
164 double tolerance = kNearlyZero,
165 bool xformToleranceToX = false) {
166 SkASSERT(tolerance >= 0.0);
167 if (xformToleranceToX) {
168 tolerance = tolerance / sqrt(4.0 * y * y + 1.0);
169 }
170 return fabs(x - y) <= tolerance;
171}
172
173static inline double sign_of(const double &val) {
Jim Van Verthde30e422019-12-19 10:13:23 -0500174 return std::copysign(1, val);
joel.liang8cbb4242017-01-09 18:39:43 -0800175}
176
177static bool is_colinear(const SkPoint pts[3]) {
Jim Van Verthde30e422019-12-19 10:13:23 -0500178 return nearly_zero((pts[1].fY - pts[0].fY) * (pts[1].fX - pts[2].fX) -
179 (pts[1].fY - pts[2].fY) * (pts[1].fX - pts[0].fX), kCloseSqd);
joel.liang8cbb4242017-01-09 18:39:43 -0800180}
181
182class PathSegment {
183public:
184 enum {
185 // These enum values are assumed in member functions below.
186 kLine = 0,
187 kQuad = 1,
188 } fType;
189
190 // line uses 2 pts, quad uses 3 pts
191 SkPoint fPts[3];
192
Jim Van Verthde30e422019-12-19 10:13:23 -0500193 SkDPoint fP0T, fP2T;
194 DAffineMatrix fXformMatrix; // transforms the segment into canonical space
joel.liang8cbb4242017-01-09 18:39:43 -0800195 double fScalingFactor;
196 double fScalingFactorSqd;
197 double fNearlyZeroScaled;
198 double fTangentTolScaledSqd;
199 SkRect fBoundingBox;
200
201 void init();
202
203 int countPoints() {
Brian Salomon4dea72a2019-12-18 10:43:10 -0500204 static_assert(0 == kLine && 1 == kQuad);
joel.liang8cbb4242017-01-09 18:39:43 -0800205 return fType + 2;
206 }
207
208 const SkPoint& endPt() const {
Brian Salomon4dea72a2019-12-18 10:43:10 -0500209 static_assert(0 == kLine && 1 == kQuad);
joel.liang8cbb4242017-01-09 18:39:43 -0800210 return fPts[fType + 1];
211 }
212};
213
214typedef SkTArray<PathSegment, true> PathSegmentArray;
215
216void PathSegment::init() {
Jim Van Verthde30e422019-12-19 10:13:23 -0500217 const SkDPoint p0 = { fPts[0].fX, fPts[0].fY };
218 const SkDPoint p2 = { this->endPt().fX, this->endPt().fY };
219 const double p0x = p0.fX;
220 const double p0y = p0.fY;
221 const double p2x = p2.fX;
222 const double p2y = p2.fY;
joel.liang8cbb4242017-01-09 18:39:43 -0800223
224 fBoundingBox.set(fPts[0], this->endPt());
225
226 if (fType == PathSegment::kLine) {
227 fScalingFactorSqd = fScalingFactor = 1.0;
Jim Van Verthde30e422019-12-19 10:13:23 -0500228 double hypotenuse = p0.distance(p2);
joel.liang8cbb4242017-01-09 18:39:43 -0800229
230 const double cosTheta = (p2x - p0x) / hypotenuse;
231 const double sinTheta = (p2y - p0y) / hypotenuse;
232
Jim Van Verthde30e422019-12-19 10:13:23 -0500233 // rotates the segment to the x-axis, with p0 at the origin
joel.liang8cbb4242017-01-09 18:39:43 -0800234 fXformMatrix.setAffine(
235 cosTheta, sinTheta, -(cosTheta * p0x) - (sinTheta * p0y),
236 -sinTheta, cosTheta, (sinTheta * p0x) - (cosTheta * p0y)
237 );
238 } else {
239 SkASSERT(fType == PathSegment::kQuad);
240
241 // Calculate bounding box
242 const SkPoint _P1mP0 = fPts[1] - fPts[0];
243 SkPoint t = _P1mP0 - fPts[2] + fPts[1];
Jim Van Verthde30e422019-12-19 10:13:23 -0500244 t.fX = _P1mP0.fX / t.fX;
245 t.fY = _P1mP0.fY / t.fY;
Brian Osmanaba642c2020-02-06 12:52:25 -0500246 t.fX = SkTPin(t.fX, 0.0f, 1.0f);
247 t.fY = SkTPin(t.fY, 0.0f, 1.0f);
Jim Van Verthde30e422019-12-19 10:13:23 -0500248 t.fX = _P1mP0.fX * t.fX;
249 t.fY = _P1mP0.fY * t.fY;
joel.liang8cbb4242017-01-09 18:39:43 -0800250 const SkPoint m = fPts[0] + t;
Mike Reed185ffe92018-01-08 17:09:54 -0500251 SkRectPriv::GrowToInclude(&fBoundingBox, m);
joel.liang8cbb4242017-01-09 18:39:43 -0800252
Jim Van Verthde30e422019-12-19 10:13:23 -0500253 const double p1x = fPts[1].fX;
254 const double p1y = fPts[1].fY;
joel.liang8cbb4242017-01-09 18:39:43 -0800255
256 const double p0xSqd = p0x * p0x;
257 const double p0ySqd = p0y * p0y;
258 const double p2xSqd = p2x * p2x;
259 const double p2ySqd = p2y * p2y;
260 const double p1xSqd = p1x * p1x;
261 const double p1ySqd = p1y * p1y;
262
263 const double p01xProd = p0x * p1x;
264 const double p02xProd = p0x * p2x;
265 const double b12xProd = p1x * p2x;
266 const double p01yProd = p0y * p1y;
267 const double p02yProd = p0y * p2y;
268 const double b12yProd = p1y * p2y;
269
Jim Van Verthde30e422019-12-19 10:13:23 -0500270 // calculate quadratic params
joel.liang8cbb4242017-01-09 18:39:43 -0800271 const double sqrtA = p0y - (2.0 * p1y) + p2y;
272 const double a = sqrtA * sqrtA;
273 const double h = -1.0 * (p0y - (2.0 * p1y) + p2y) * (p0x - (2.0 * p1x) + p2x);
274 const double sqrtB = p0x - (2.0 * p1x) + p2x;
275 const double b = sqrtB * sqrtB;
276 const double c = (p0xSqd * p2ySqd) - (4.0 * p01xProd * b12yProd)
277 - (2.0 * p02xProd * p02yProd) + (4.0 * p02xProd * p1ySqd)
278 + (4.0 * p1xSqd * p02yProd) - (4.0 * b12xProd * p01yProd)
279 + (p2xSqd * p0ySqd);
280 const double g = (p0x * p02yProd) - (2.0 * p0x * p1ySqd)
281 + (2.0 * p0x * b12yProd) - (p0x * p2ySqd)
282 + (2.0 * p1x * p01yProd) - (4.0 * p1x * p02yProd)
283 + (2.0 * p1x * b12yProd) - (p2x * p0ySqd)
284 + (2.0 * p2x * p01yProd) + (p2x * p02yProd)
285 - (2.0 * p2x * p1ySqd);
286 const double f = -((p0xSqd * p2y) - (2.0 * p01xProd * p1y)
287 - (2.0 * p01xProd * p2y) - (p02xProd * p0y)
288 + (4.0 * p02xProd * p1y) - (p02xProd * p2y)
289 + (2.0 * p1xSqd * p0y) + (2.0 * p1xSqd * p2y)
290 - (2.0 * b12xProd * p0y) - (2.0 * b12xProd * p1y)
291 + (p2xSqd * p0y));
292
293 const double cosTheta = sqrt(a / (a + b));
294 const double sinTheta = -1.0 * sign_of((a + b) * h) * sqrt(b / (a + b));
295
296 const double gDef = cosTheta * g - sinTheta * f;
297 const double fDef = sinTheta * g + cosTheta * f;
298
299
300 const double x0 = gDef / (a + b);
301 const double y0 = (1.0 / (2.0 * fDef)) * (c - (gDef * gDef / (a + b)));
302
303
304 const double lambda = -1.0 * ((a + b) / (2.0 * fDef));
305 fScalingFactor = fabs(1.0 / lambda);
306 fScalingFactorSqd = fScalingFactor * fScalingFactor;
307
308 const double lambda_cosTheta = lambda * cosTheta;
309 const double lambda_sinTheta = lambda * sinTheta;
310
Jim Van Verthde30e422019-12-19 10:13:23 -0500311 // transforms to lie on a canonical y = x^2 parabola
joel.liang8cbb4242017-01-09 18:39:43 -0800312 fXformMatrix.setAffine(
313 lambda_cosTheta, -lambda_sinTheta, lambda * x0,
314 lambda_sinTheta, lambda_cosTheta, lambda * y0
315 );
316 }
317
318 fNearlyZeroScaled = kNearlyZero / fScalingFactor;
319 fTangentTolScaledSqd = kTangentTolerance * kTangentTolerance / fScalingFactorSqd;
320
321 fP0T = fXformMatrix.mapPoint(p0);
322 fP2T = fXformMatrix.mapPoint(p2);
323}
324
325static void init_distances(DFData* data, int size) {
326 DFData* currData = data;
327
328 for (int i = 0; i < size; ++i) {
329 // init distance to "far away"
330 currData->fDistSq = SK_DistanceFieldMagnitude * SK_DistanceFieldMagnitude;
331 currData->fDeltaWindingScore = 0;
332 ++currData;
333 }
334}
335
Jim Van Verthde30e422019-12-19 10:13:23 -0500336static inline void add_line(const SkPoint pts[2], PathSegmentArray* segments) {
joel.liang8cbb4242017-01-09 18:39:43 -0800337 segments->push_back();
338 segments->back().fType = PathSegment::kLine;
339 segments->back().fPts[0] = pts[0];
340 segments->back().fPts[1] = pts[1];
341
342 segments->back().init();
343}
344
Jim Van Verthde30e422019-12-19 10:13:23 -0500345static inline void add_quad(const SkPoint pts[3], PathSegmentArray* segments) {
Cary Clarkdf429f32017-11-08 11:44:31 -0500346 if (SkPointPriv::DistanceToSqd(pts[0], pts[1]) < kCloseSqd ||
347 SkPointPriv::DistanceToSqd(pts[1], pts[2]) < kCloseSqd ||
joel.liang8cbb4242017-01-09 18:39:43 -0800348 is_colinear(pts)) {
349 if (pts[0] != pts[2]) {
350 SkPoint line_pts[2];
351 line_pts[0] = pts[0];
352 line_pts[1] = pts[2];
Jim Van Verthde30e422019-12-19 10:13:23 -0500353 add_line(line_pts, segments);
joel.liang8cbb4242017-01-09 18:39:43 -0800354 }
355 } else {
356 segments->push_back();
357 segments->back().fType = PathSegment::kQuad;
358 segments->back().fPts[0] = pts[0];
359 segments->back().fPts[1] = pts[1];
360 segments->back().fPts[2] = pts[2];
361
362 segments->back().init();
363 }
364}
365
Jim Van Verthde30e422019-12-19 10:13:23 -0500366static inline void add_cubic(const SkPoint pts[4],
367 PathSegmentArray* segments) {
joel.liang8cbb4242017-01-09 18:39:43 -0800368 SkSTArray<15, SkPoint, true> quads;
369 GrPathUtils::convertCubicToQuads(pts, SK_Scalar1, &quads);
370 int count = quads.count();
371 for (int q = 0; q < count; q += 3) {
Jim Van Verthde30e422019-12-19 10:13:23 -0500372 add_quad(&quads[q], segments);
joel.liang8cbb4242017-01-09 18:39:43 -0800373 }
374}
375
376static float calculate_nearest_point_for_quad(
377 const PathSegment& segment,
Jim Van Verthde30e422019-12-19 10:13:23 -0500378 const SkDPoint &xFormPt) {
joel.liang8cbb4242017-01-09 18:39:43 -0800379 static const float kThird = 0.33333333333f;
380 static const float kTwentySeventh = 0.037037037f;
381
Jim Van Verthde30e422019-12-19 10:13:23 -0500382 const float a = 0.5f - (float)xFormPt.fY;
383 const float b = -0.5f * (float)xFormPt.fX;
joel.liang8cbb4242017-01-09 18:39:43 -0800384
385 const float a3 = a * a * a;
386 const float b2 = b * b;
387
388 const float c = (b2 * 0.25f) + (a3 * kTwentySeventh);
389
390 if (c >= 0.f) {
391 const float sqrtC = sqrt(c);
392 const float result = (float)cbrt((-b * 0.5f) + sqrtC) + (float)cbrt((-b * 0.5f) - sqrtC);
393 return result;
394 } else {
395 const float cosPhi = (float)sqrt((b2 * 0.25f) * (-27.f / a3)) * ((b > 0) ? -1.f : 1.f);
396 const float phi = (float)acos(cosPhi);
397 float result;
Jim Van Verthde30e422019-12-19 10:13:23 -0500398 if (xFormPt.fX > 0.f) {
joel.liang8cbb4242017-01-09 18:39:43 -0800399 result = 2.f * (float)sqrt(-a * kThird) * (float)cos(phi * kThird);
Jim Van Verthde30e422019-12-19 10:13:23 -0500400 if (!between_closed(result, segment.fP0T.fX, segment.fP2T.fX)) {
joel.liang8cbb4242017-01-09 18:39:43 -0800401 result = 2.f * (float)sqrt(-a * kThird) * (float)cos((phi * kThird) + (SK_ScalarPI * 2.f * kThird));
402 }
403 } else {
404 result = 2.f * (float)sqrt(-a * kThird) * (float)cos((phi * kThird) + (SK_ScalarPI * 2.f * kThird));
Jim Van Verthde30e422019-12-19 10:13:23 -0500405 if (!between_closed(result, segment.fP0T.fX, segment.fP2T.fX)) {
joel.liang8cbb4242017-01-09 18:39:43 -0800406 result = 2.f * (float)sqrt(-a * kThird) * (float)cos(phi * kThird);
407 }
408 }
409 return result;
410 }
411}
412
413// This structure contains some intermediate values shared by the same row.
414// It is used to calculate segment side of a quadratic bezier.
415struct RowData {
416 // The intersection type of a scanline and y = x * x parabola in canonical space.
417 enum IntersectionType {
418 kNoIntersection,
419 kVerticalLine,
420 kTangentLine,
421 kTwoPointsIntersect
422 } fIntersectionType;
423
424 // The direction of the quadratic segment/scanline in the canonical space.
425 // 1: The quadratic segment/scanline going from negative x-axis to positive x-axis.
426 // 0: The scanline is a vertical line in the canonical space.
427 // -1: The quadratic segment/scanline going from positive x-axis to negative x-axis.
428 int fQuadXDirection;
429 int fScanlineXDirection;
430
431 // The y-value(equal to x*x) of intersection point for the kVerticalLine intersection type.
432 double fYAtIntersection;
433
434 // The x-value for two intersection points.
435 double fXAtIntersection1;
436 double fXAtIntersection2;
437};
438
Jim Van Verthde30e422019-12-19 10:13:23 -0500439void precomputation_for_row(RowData *rowData, const PathSegment& segment,
440 const SkPoint& pointLeft, const SkPoint& pointRight) {
joel.liang8cbb4242017-01-09 18:39:43 -0800441 if (segment.fType != PathSegment::kQuad) {
442 return;
443 }
444
Jim Van Verthde30e422019-12-19 10:13:23 -0500445 const SkDPoint& xFormPtLeft = segment.fXformMatrix.mapPoint(pointLeft);
446 const SkDPoint& xFormPtRight = segment.fXformMatrix.mapPoint(pointRight);
joel.liang8cbb4242017-01-09 18:39:43 -0800447
Jim Van Verthde30e422019-12-19 10:13:23 -0500448 rowData->fQuadXDirection = (int)sign_of(segment.fP2T.fX - segment.fP0T.fX);
449 rowData->fScanlineXDirection = (int)sign_of(xFormPtRight.fX - xFormPtLeft.fX);
joel.liang8cbb4242017-01-09 18:39:43 -0800450
Jim Van Verthde30e422019-12-19 10:13:23 -0500451 const double x1 = xFormPtLeft.fX;
452 const double y1 = xFormPtLeft.fY;
453 const double x2 = xFormPtRight.fX;
454 const double y2 = xFormPtRight.fY;
joel.liang8cbb4242017-01-09 18:39:43 -0800455
456 if (nearly_equal(x1, x2, segment.fNearlyZeroScaled, true)) {
457 rowData->fIntersectionType = RowData::kVerticalLine;
458 rowData->fYAtIntersection = x1 * x1;
459 rowData->fScanlineXDirection = 0;
460 return;
461 }
462
463 // Line y = mx + b
464 const double m = (y2 - y1) / (x2 - x1);
465 const double b = -m * x1 + y1;
466
467 const double m2 = m * m;
468 const double c = m2 + 4.0 * b;
469
470 const double tol = 4.0 * segment.fTangentTolScaledSqd / (m2 + 1.0);
471
472 // Check if the scanline is the tangent line of the curve,
473 // and the curve start or end at the same y-coordinate of the scanline
474 if ((rowData->fScanlineXDirection == 1 &&
Jim Van Verthde30e422019-12-19 10:13:23 -0500475 (segment.fPts[0].fY == pointLeft.fY ||
476 segment.fPts[2].fY == pointLeft.fY)) &&
joel.liang8cbb4242017-01-09 18:39:43 -0800477 nearly_zero(c, tol)) {
478 rowData->fIntersectionType = RowData::kTangentLine;
479 rowData->fXAtIntersection1 = m / 2.0;
480 rowData->fXAtIntersection2 = m / 2.0;
481 } else if (c <= 0.0) {
482 rowData->fIntersectionType = RowData::kNoIntersection;
483 return;
484 } else {
485 rowData->fIntersectionType = RowData::kTwoPointsIntersect;
486 const double d = sqrt(c);
487 rowData->fXAtIntersection1 = (m + d) / 2.0;
488 rowData->fXAtIntersection2 = (m - d) / 2.0;
489 }
490}
491
492SegSide calculate_side_of_quad(
493 const PathSegment& segment,
494 const SkPoint& point,
Jim Van Verthde30e422019-12-19 10:13:23 -0500495 const SkDPoint& xFormPt,
joel.liang8cbb4242017-01-09 18:39:43 -0800496 const RowData& rowData) {
497 SegSide side = kNA_SegSide;
498
499 if (RowData::kVerticalLine == rowData.fIntersectionType) {
Jim Van Verthde30e422019-12-19 10:13:23 -0500500 side = (SegSide)(int)(sign_of(xFormPt.fY - rowData.fYAtIntersection) * rowData.fQuadXDirection);
joel.liang8cbb4242017-01-09 18:39:43 -0800501 }
502 else if (RowData::kTwoPointsIntersect == rowData.fIntersectionType) {
503 const double p1 = rowData.fXAtIntersection1;
504 const double p2 = rowData.fXAtIntersection2;
505
Jim Van Verthde30e422019-12-19 10:13:23 -0500506 int signP1 = (int)sign_of(p1 - xFormPt.fX);
joel.liang8cbb4242017-01-09 18:39:43 -0800507 bool includeP1 = true;
508 bool includeP2 = true;
509
510 if (rowData.fScanlineXDirection == 1) {
Jim Van Verthde30e422019-12-19 10:13:23 -0500511 if ((rowData.fQuadXDirection == -1 && segment.fPts[0].fY <= point.fY &&
512 nearly_equal(segment.fP0T.fX, p1, segment.fNearlyZeroScaled, true)) ||
513 (rowData.fQuadXDirection == 1 && segment.fPts[2].fY <= point.fY &&
514 nearly_equal(segment.fP2T.fX, p1, segment.fNearlyZeroScaled, true))) {
joel.liang8cbb4242017-01-09 18:39:43 -0800515 includeP1 = false;
516 }
Jim Van Verthde30e422019-12-19 10:13:23 -0500517 if ((rowData.fQuadXDirection == -1 && segment.fPts[2].fY <= point.fY &&
518 nearly_equal(segment.fP2T.fX, p2, segment.fNearlyZeroScaled, true)) ||
519 (rowData.fQuadXDirection == 1 && segment.fPts[0].fY <= point.fY &&
520 nearly_equal(segment.fP0T.fX, p2, segment.fNearlyZeroScaled, true))) {
joel.liang8cbb4242017-01-09 18:39:43 -0800521 includeP2 = false;
522 }
523 }
524
Jim Van Verthde30e422019-12-19 10:13:23 -0500525 if (includeP1 && between_closed(p1, segment.fP0T.fX, segment.fP2T.fX,
joel.liang8cbb4242017-01-09 18:39:43 -0800526 segment.fNearlyZeroScaled, true)) {
527 side = (SegSide)(signP1 * rowData.fQuadXDirection);
528 }
Jim Van Verthde30e422019-12-19 10:13:23 -0500529 if (includeP2 && between_closed(p2, segment.fP0T.fX, segment.fP2T.fX,
joel.liang8cbb4242017-01-09 18:39:43 -0800530 segment.fNearlyZeroScaled, true)) {
Jim Van Verthde30e422019-12-19 10:13:23 -0500531 int signP2 = (int)sign_of(p2 - xFormPt.fX);
joel.liang8cbb4242017-01-09 18:39:43 -0800532 if (side == kNA_SegSide || signP2 == 1) {
533 side = (SegSide)(-signP2 * rowData.fQuadXDirection);
534 }
535 }
536 } else if (RowData::kTangentLine == rowData.fIntersectionType) {
537 // The scanline is the tangent line of current quadratic segment.
538
539 const double p = rowData.fXAtIntersection1;
Jim Van Verthde30e422019-12-19 10:13:23 -0500540 int signP = (int)sign_of(p - xFormPt.fX);
joel.liang8cbb4242017-01-09 18:39:43 -0800541 if (rowData.fScanlineXDirection == 1) {
542 // The path start or end at the tangent point.
Jim Van Verthde30e422019-12-19 10:13:23 -0500543 if (segment.fPts[0].fY == point.fY) {
joel.liang8cbb4242017-01-09 18:39:43 -0800544 side = (SegSide)(signP);
Jim Van Verthde30e422019-12-19 10:13:23 -0500545 } else if (segment.fPts[2].fY == point.fY) {
joel.liang8cbb4242017-01-09 18:39:43 -0800546 side = (SegSide)(-signP);
547 }
548 }
549 }
550
551 return side;
552}
553
554static float distance_to_segment(const SkPoint& point,
555 const PathSegment& segment,
556 const RowData& rowData,
557 SegSide* side) {
558 SkASSERT(side);
559
Jim Van Verthde30e422019-12-19 10:13:23 -0500560 const SkDPoint xformPt = segment.fXformMatrix.mapPoint(point);
joel.liang8cbb4242017-01-09 18:39:43 -0800561
562 if (segment.fType == PathSegment::kLine) {
563 float result = SK_DistanceFieldPad * SK_DistanceFieldPad;
564
Jim Van Verthde30e422019-12-19 10:13:23 -0500565 if (between_closed(xformPt.fX, segment.fP0T.fX, segment.fP2T.fX)) {
566 result = (float)(xformPt.fY * xformPt.fY);
567 } else if (xformPt.fX < segment.fP0T.fX) {
568 result = (float)(xformPt.fX * xformPt.fX + xformPt.fY * xformPt.fY);
joel.liang8cbb4242017-01-09 18:39:43 -0800569 } else {
Jim Van Verthde30e422019-12-19 10:13:23 -0500570 result = (float)((xformPt.fX - segment.fP2T.fX) * (xformPt.fX - segment.fP2T.fX)
571 + xformPt.fY * xformPt.fY);
joel.liang8cbb4242017-01-09 18:39:43 -0800572 }
573
Jim Van Verthde30e422019-12-19 10:13:23 -0500574 if (between_closed_open(point.fY, segment.fBoundingBox.fTop,
575 segment.fBoundingBox.fBottom)) {
576 *side = (SegSide)(int)sign_of(xformPt.fY);
joel.liang8cbb4242017-01-09 18:39:43 -0800577 } else {
578 *side = kNA_SegSide;
579 }
580 return result;
581 } else {
582 SkASSERT(segment.fType == PathSegment::kQuad);
583
584 const float nearestPoint = calculate_nearest_point_for_quad(segment, xformPt);
585
586 float dist;
587
Jim Van Verthde30e422019-12-19 10:13:23 -0500588 if (between_closed(nearestPoint, segment.fP0T.fX, segment.fP2T.fX)) {
589 SkDPoint x = { nearestPoint, nearestPoint * nearestPoint };
590 dist = (float)xformPt.distanceSquared(x);
joel.liang8cbb4242017-01-09 18:39:43 -0800591 } else {
Jim Van Verthde30e422019-12-19 10:13:23 -0500592 const float distToB0T = (float)xformPt.distanceSquared(segment.fP0T);
593 const float distToB2T = (float)xformPt.distanceSquared(segment.fP2T);
joel.liang8cbb4242017-01-09 18:39:43 -0800594
595 if (distToB0T < distToB2T) {
596 dist = distToB0T;
597 } else {
598 dist = distToB2T;
599 }
600 }
601
Jim Van Verthde30e422019-12-19 10:13:23 -0500602 if (between_closed_open(point.fY, segment.fBoundingBox.fTop,
603 segment.fBoundingBox.fBottom)) {
joel.liang8cbb4242017-01-09 18:39:43 -0800604 *side = calculate_side_of_quad(segment, point, xformPt, rowData);
605 } else {
606 *side = kNA_SegSide;
607 }
608
609 return (float)(dist * segment.fScalingFactorSqd);
610 }
611}
612
613static void calculate_distance_field_data(PathSegmentArray* segments,
614 DFData* dataPtr,
615 int width, int height) {
616 int count = segments->count();
Jim Van Verthde30e422019-12-19 10:13:23 -0500617 // for each segment
joel.liang8cbb4242017-01-09 18:39:43 -0800618 for (int a = 0; a < count; ++a) {
619 PathSegment& segment = (*segments)[a];
Jim Van Verthde30e422019-12-19 10:13:23 -0500620 const SkRect& segBB = segment.fBoundingBox;
621 // get the bounding box, outset by distance field pad, and clip to total bounds
622 const SkRect& paddedBB = segBB.makeOutset(SK_DistanceFieldPad, SK_DistanceFieldPad);
623 int startColumn = (int)paddedBB.fLeft;
624 int endColumn = SkScalarCeilToInt(paddedBB.fRight);
joel.liang8cbb4242017-01-09 18:39:43 -0800625
Jim Van Verthde30e422019-12-19 10:13:23 -0500626 int startRow = (int)paddedBB.fTop;
627 int endRow = SkScalarCeilToInt(paddedBB.fBottom);
joel.liang8cbb4242017-01-09 18:39:43 -0800628
629 SkASSERT((startColumn >= 0) && "StartColumn < 0!");
630 SkASSERT((endColumn <= width) && "endColumn > width!");
631 SkASSERT((startRow >= 0) && "StartRow < 0!");
632 SkASSERT((endRow <= height) && "EndRow > height!");
633
634 // Clip inside the distance field to avoid overflow
Brian Osman788b9162020-02-07 10:36:46 -0500635 startColumn = std::max(startColumn, 0);
636 endColumn = std::min(endColumn, width);
637 startRow = std::max(startRow, 0);
638 endRow = std::min(endRow, height);
joel.liang8cbb4242017-01-09 18:39:43 -0800639
Jim Van Verthde30e422019-12-19 10:13:23 -0500640 // for each row in the padded bounding box
joel.liang8cbb4242017-01-09 18:39:43 -0800641 for (int row = startRow; row < endRow; ++row) {
Jim Van Verthde30e422019-12-19 10:13:23 -0500642 SegSide prevSide = kNA_SegSide; // track side for winding count
643 const float pY = row + 0.5f; // offset by 1/2? why?
joel.liang8cbb4242017-01-09 18:39:43 -0800644 RowData rowData;
645
646 const SkPoint pointLeft = SkPoint::Make((SkScalar)startColumn, pY);
647 const SkPoint pointRight = SkPoint::Make((SkScalar)endColumn, pY);
648
Jim Van Verthde30e422019-12-19 10:13:23 -0500649 // if this is a row inside the original segment bounding box
650 if (between_closed_open(pY, segBB.fTop, segBB.fBottom)) {
651 // compute intersections with the row
joel.liang8cbb4242017-01-09 18:39:43 -0800652 precomputation_for_row(&rowData, segment, pointLeft, pointRight);
653 }
654
Jim Van Verthde30e422019-12-19 10:13:23 -0500655 // adjust distances and windings in each column based on the row calculation
joel.liang8cbb4242017-01-09 18:39:43 -0800656 for (int col = startColumn; col < endColumn; ++col) {
657 int idx = (row * width) + col;
658
659 const float pX = col + 0.5f;
660 const SkPoint point = SkPoint::Make(pX, pY);
661
662 const float distSq = dataPtr[idx].fDistSq;
joel.liang8cbb4242017-01-09 18:39:43 -0800663
Jim Van Verthde30e422019-12-19 10:13:23 -0500664 // Optimization for not calculating some points.
665 int dilation = distSq < 1.5f * 1.5f ? 1 :
666 distSq < 2.5f * 2.5f ? 2 :
667 distSq < 3.5f * 3.5f ? 3 : SK_DistanceFieldPad;
668 if (dilation < SK_DistanceFieldPad &&
669 !segBB.roundOut().makeOutset(dilation, dilation).contains(col, row)) {
joel.liang8cbb4242017-01-09 18:39:43 -0800670 continue;
671 }
672
673 SegSide side = kNA_SegSide;
674 int deltaWindingScore = 0;
675 float currDistSq = distance_to_segment(point, segment, rowData, &side);
676 if (prevSide == kLeft_SegSide && side == kRight_SegSide) {
677 deltaWindingScore = -1;
678 } else if (prevSide == kRight_SegSide && side == kLeft_SegSide) {
679 deltaWindingScore = 1;
680 }
681
682 prevSide = side;
683
684 if (currDistSq < distSq) {
685 dataPtr[idx].fDistSq = currDistSq;
686 }
687
688 dataPtr[idx].fDeltaWindingScore += deltaWindingScore;
689 }
690 }
691 }
692}
693
694template <int distanceMagnitude>
695static unsigned char pack_distance_field_val(float dist) {
696 // The distance field is constructed as unsigned char values, so that the zero value is at 128,
697 // Beside 128, we have 128 values in range [0, 128), but only 127 values in range (128, 255].
698 // So we multiply distanceMagnitude by 127/128 at the latter range to avoid overflow.
Brian Osmanaba642c2020-02-06 12:52:25 -0500699 dist = SkTPin<float>(-dist, -distanceMagnitude, distanceMagnitude * 127.0f / 128.0f);
joel.liang8cbb4242017-01-09 18:39:43 -0800700
701 // Scale into the positive range for unsigned distance.
702 dist += distanceMagnitude;
703
704 // Scale into unsigned char range.
705 // Round to place negative and positive values as equally as possible around 128
706 // (which represents zero).
707 return (unsigned char)SkScalarRoundToInt(dist / (2 * distanceMagnitude) * 256.0f);
708}
709
710bool GrGenerateDistanceFieldFromPath(unsigned char* distanceField,
711 const SkPath& path, const SkMatrix& drawMatrix,
712 int width, int height, size_t rowBytes) {
713 SkASSERT(distanceField);
714
Jim Van Verthde30e422019-12-19 10:13:23 -0500715 // transform to device space, then:
716 // translate path to offset (SK_DistanceFieldPad, SK_DistanceFieldPad)
717 SkMatrix dfMatrix(drawMatrix);
718 dfMatrix.postTranslate(SK_DistanceFieldPad, SK_DistanceFieldPad);
719
Brian Salomon23356442018-11-30 15:33:19 -0500720#ifdef SK_DEBUG
721 SkPath xformPath;
Jim Van Verthde30e422019-12-19 10:13:23 -0500722 path.transform(dfMatrix, &xformPath);
Brian Salomon23356442018-11-30 15:33:19 -0500723 SkIRect pathBounds = xformPath.getBounds().roundOut();
Jim Van Verthde30e422019-12-19 10:13:23 -0500724 SkIRect expectPathBounds = SkIRect::MakeWH(width, height);
Brian Salomon23356442018-11-30 15:33:19 -0500725#endif
726
joel.liang8cbb4242017-01-09 18:39:43 -0800727 SkASSERT(expectPathBounds.isEmpty() ||
Jim Van Verthde30e422019-12-19 10:13:23 -0500728 expectPathBounds.contains(pathBounds.fLeft, pathBounds.fTop));
joel.liang8cbb4242017-01-09 18:39:43 -0800729 SkASSERT(expectPathBounds.isEmpty() || pathBounds.isEmpty() ||
730 expectPathBounds.contains(pathBounds));
731
Jim Van Verthde30e422019-12-19 10:13:23 -0500732// TODO: restore when Simplify() is working correctly
733// see https://bugs.chromium.org/p/skia/issues/detail?id=9732
734// SkPath simplifiedPath;
joel.liang8cbb4242017-01-09 18:39:43 -0800735 SkPath workingPath;
Jim Van Verthde30e422019-12-19 10:13:23 -0500736// if (Simplify(path, &simplifiedPath)) {
737// workingPath = simplifiedPath;
738// } else {
joel.liang8cbb4242017-01-09 18:39:43 -0800739 workingPath = path;
Jim Van Verthde30e422019-12-19 10:13:23 -0500740// }
741 // only even-odd and inverse even-odd supported
Mike Reedcf0e3c62019-12-03 16:26:15 -0500742 if (!IsDistanceFieldSupportedFillType(workingPath.getFillType())) {
joel.liang8cbb4242017-01-09 18:39:43 -0800743 return false;
744 }
745
Jim Van Verthde30e422019-12-19 10:13:23 -0500746 // transform to device space + SDF offset
747 workingPath.transform(dfMatrix);
joel.liang8cbb4242017-01-09 18:39:43 -0800748
749 SkDEBUGCODE(pathBounds = workingPath.getBounds().roundOut());
750 SkASSERT(expectPathBounds.isEmpty() ||
Jim Van Verthde30e422019-12-19 10:13:23 -0500751 expectPathBounds.contains(pathBounds.fLeft, pathBounds.fTop));
joel.liang8cbb4242017-01-09 18:39:43 -0800752 SkASSERT(expectPathBounds.isEmpty() || pathBounds.isEmpty() ||
753 expectPathBounds.contains(pathBounds));
754
joel.liang8cbb4242017-01-09 18:39:43 -0800755 // create temp data
756 size_t dataSize = width * height * sizeof(DFData);
757 SkAutoSMalloc<1024> dfStorage(dataSize);
758 DFData* dataPtr = (DFData*) dfStorage.get();
759
Jim Van Verthde30e422019-12-19 10:13:23 -0500760 // create initial distance data (init to "far away")
joel.liang8cbb4242017-01-09 18:39:43 -0800761 init_distances(dataPtr, width * height);
762
Jim Van Verthde30e422019-12-19 10:13:23 -0500763 // polygonize path into line and quad segments
Mike Reed5f152f02019-08-19 14:40:16 -0400764 SkPathEdgeIter iter(workingPath);
joel.liang8cbb4242017-01-09 18:39:43 -0800765 SkSTArray<15, PathSegment, true> segments;
Mike Reed5f152f02019-08-19 14:40:16 -0400766 while (auto e = iter.next()) {
767 switch (e.fEdge) {
768 case SkPathEdgeIter::Edge::kLine: {
Jim Van Verthde30e422019-12-19 10:13:23 -0500769 add_line(e.fPts, &segments);
joel.liang8cbb4242017-01-09 18:39:43 -0800770 break;
771 }
Mike Reed5f152f02019-08-19 14:40:16 -0400772 case SkPathEdgeIter::Edge::kQuad:
Jim Van Verthde30e422019-12-19 10:13:23 -0500773 add_quad(e.fPts, &segments);
joel.liang8cbb4242017-01-09 18:39:43 -0800774 break;
Mike Reed5f152f02019-08-19 14:40:16 -0400775 case SkPathEdgeIter::Edge::kConic: {
joel.liang8cbb4242017-01-09 18:39:43 -0800776 SkScalar weight = iter.conicWeight();
777 SkAutoConicToQuads converter;
Mike Reed5f152f02019-08-19 14:40:16 -0400778 const SkPoint* quadPts = converter.computeQuads(e.fPts, weight, kConicTolerance);
joel.liang8cbb4242017-01-09 18:39:43 -0800779 for (int i = 0; i < converter.countQuads(); ++i) {
Jim Van Verthde30e422019-12-19 10:13:23 -0500780 add_quad(quadPts + 2*i, &segments);
joel.liang8cbb4242017-01-09 18:39:43 -0800781 }
782 break;
783 }
Mike Reed5f152f02019-08-19 14:40:16 -0400784 case SkPathEdgeIter::Edge::kCubic: {
Jim Van Verthde30e422019-12-19 10:13:23 -0500785 add_cubic(e.fPts, &segments);
joel.liang8cbb4242017-01-09 18:39:43 -0800786 break;
Brian Salomon23356442018-11-30 15:33:19 -0500787 }
joel.liang8cbb4242017-01-09 18:39:43 -0800788 }
789 }
790
Jim Van Verthde30e422019-12-19 10:13:23 -0500791 // do all the work
joel.liang8cbb4242017-01-09 18:39:43 -0800792 calculate_distance_field_data(&segments, dataPtr, width, height);
793
Jim Van Verthde30e422019-12-19 10:13:23 -0500794 // adjust distance based on winding
joel.liang8cbb4242017-01-09 18:39:43 -0800795 for (int row = 0; row < height; ++row) {
796 int windingNumber = 0; // Winding number start from zero for each scanline
797 for (int col = 0; col < width; ++col) {
798 int idx = (row * width) + col;
799 windingNumber += dataPtr[idx].fDeltaWindingScore;
800
801 enum DFSign {
802 kInside = -1,
803 kOutside = 1
804 } dfSign;
805
Mike Reedcf0e3c62019-12-03 16:26:15 -0500806 switch (workingPath.getFillType()) {
Mike Reed7d34dc72019-11-26 12:17:17 -0500807 case SkPathFillType::kWinding:
808 dfSign = windingNumber ? kInside : kOutside;
809 break;
810 case SkPathFillType::kInverseWinding:
811 dfSign = windingNumber ? kOutside : kInside;
812 break;
813 case SkPathFillType::kEvenOdd:
814 dfSign = (windingNumber % 2) ? kInside : kOutside;
815 break;
816 case SkPathFillType::kInverseEvenOdd:
817 dfSign = (windingNumber % 2) ? kOutside : kInside;
818 break;
joel.liang8cbb4242017-01-09 18:39:43 -0800819 }
820
821 // The winding number at the end of a scanline should be zero.
822 SkASSERT(((col != width - 1) || (windingNumber == 0)) &&
823 "Winding number should be zero at the end of a scan line.");
824 // Fallback to use SkPath::contains to determine the sign of pixel in release build.
825 if (col == width - 1 && windingNumber != 0) {
826 for (int col = 0; col < width; ++col) {
827 int idx = (row * width) + col;
828 dfSign = workingPath.contains(col + 0.5, row + 0.5) ? kInside : kOutside;
829 const float miniDist = sqrt(dataPtr[idx].fDistSq);
830 const float dist = dfSign * miniDist;
831
832 unsigned char pixelVal = pack_distance_field_val<SK_DistanceFieldMagnitude>(dist);
833
834 distanceField[(row * rowBytes) + col] = pixelVal;
835 }
836 continue;
837 }
838
839 const float miniDist = sqrt(dataPtr[idx].fDistSq);
840 const float dist = dfSign * miniDist;
841
842 unsigned char pixelVal = pack_distance_field_val<SK_DistanceFieldMagnitude>(dist);
843
844 distanceField[(row * rowBytes) + col] = pixelVal;
845 }
846 }
847 return true;
848}