1 /*
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
8 #include "src/core/SkDistanceFieldGen.h"
9 #include "src/gpu/GrDistanceFieldGenFromVector.h"
10
11 #include "include/core/SkMatrix.h"
12 #include "include/gpu/GrConfig.h"
13 #include "include/private/SkTPin.h"
14 #include "src/core/SkAutoMalloc.h"
15 #include "src/core/SkGeometry.h"
16 #include "src/core/SkPointPriv.h"
17 #include "src/core/SkRectPriv.h"
18 #include "src/gpu/geometry/GrPathUtils.h"
19
20 namespace {
21 // TODO: should we make this real (i.e. src/core) and distinguish it from
22 // pathops SkDPoint?
23 struct DPoint {
24 double fX, fY;
25
distanceSquared__anonad6b75b20111::DPoint26 double distanceSquared(DPoint p) const {
27 double dx = fX - p.fX;
28 double dy = fY - p.fY;
29 return dx*dx + dy*dy;
30 }
31
distance__anonad6b75b20111::DPoint32 double distance(DPoint p) const { return sqrt(this->distanceSquared(p)); }
33 };
34 }
35
36 /**
37 * If a scanline (a row of texel) cross from the kRight_SegSide
38 * of a segment to the kLeft_SegSide, the winding score should
39 * add 1.
40 * And winding score should subtract 1 if the scanline cross
41 * from kLeft_SegSide to kRight_SegSide.
42 * Always return kNA_SegSide if the scanline does not cross over
43 * the segment. Winding score should be zero in this case.
44 * You can get the winding number for each texel of the scanline
45 * by adding the winding score from left to right.
46 * Assuming we always start from outside, so the winding number
47 * should always start from zero.
48 * ________ ________
49 * | | | |
50 * ...R|L......L|R.....L|R......R|L..... <= Scanline & side of segment
51 * |+1 |-1 |-1 |+1 <= Winding score
52 * 0 | 1 ^ 0 ^ -1 |0 <= Winding number
53 * |________| |________|
54 *
55 * .......NA................NA..........
56 * 0 0
57 */
58 enum SegSide {
59 kLeft_SegSide = -1,
60 kOn_SegSide = 0,
61 kRight_SegSide = 1,
62 kNA_SegSide = 2,
63 };
64
65 struct DFData {
66 float fDistSq; // distance squared to nearest (so far) edge
67 int fDeltaWindingScore; // +1 or -1 whenever a scanline cross over a segment
68 };
69
70 ///////////////////////////////////////////////////////////////////////////////
71
72 /*
73 * Type definition for double precision DAffineMatrix
74 */
75
76 // Matrix with double precision for affine transformation.
77 // We don't store row 3 because its always (0, 0, 1).
78 class DAffineMatrix {
79 public:
operator [](int index) const80 double operator[](int index) const {
81 SkASSERT((unsigned)index < 6);
82 return fMat[index];
83 }
84
operator [](int index)85 double& operator[](int index) {
86 SkASSERT((unsigned)index < 6);
87 return fMat[index];
88 }
89
setAffine(double m11,double m12,double m13,double m21,double m22,double m23)90 void setAffine(double m11, double m12, double m13,
91 double m21, double m22, double m23) {
92 fMat[0] = m11;
93 fMat[1] = m12;
94 fMat[2] = m13;
95 fMat[3] = m21;
96 fMat[4] = m22;
97 fMat[5] = m23;
98 }
99
100 /** Set the matrix to identity
101 */
reset()102 void reset() {
103 fMat[0] = fMat[4] = 1.0;
104 fMat[1] = fMat[3] =
105 fMat[2] = fMat[5] = 0.0;
106 }
107
108 // alias for reset()
setIdentity()109 void setIdentity() { this->reset(); }
110
mapPoint(const SkPoint & src) const111 DPoint mapPoint(const SkPoint& src) const {
112 DPoint pt = {src.fX, src.fY};
113 return this->mapPoint(pt);
114 }
115
mapPoint(const DPoint & src) const116 DPoint mapPoint(const DPoint& src) const {
117 return { fMat[0] * src.fX + fMat[1] * src.fY + fMat[2],
118 fMat[3] * src.fX + fMat[4] * src.fY + fMat[5] };
119 }
120 private:
121 double fMat[6];
122 };
123
124 ///////////////////////////////////////////////////////////////////////////////
125
126 static const double kClose = (SK_Scalar1 / 16.0);
127 static const double kCloseSqd = kClose * kClose;
128 static const double kNearlyZero = (SK_Scalar1 / (1 << 18));
129 static const double kTangentTolerance = (SK_Scalar1 / (1 << 11));
130 static const float kConicTolerance = 0.25f;
131
132 // returns true if a >= min(b,c) && a < max(b,c)
between_closed_open(double a,double b,double c,double tolerance=0.0,bool xformToleranceToX=false)133 static inline bool between_closed_open(double a, double b, double c,
134 double tolerance = 0.0,
135 bool xformToleranceToX = false) {
136 SkASSERT(tolerance >= 0.0);
137 double tolB = tolerance;
138 double tolC = tolerance;
139
140 if (xformToleranceToX) {
141 // Canonical space is y = x^2 and the derivative of x^2 is 2x.
142 // So the slope of the tangent line at point (x, x^2) is 2x.
143 //
144 // /|
145 // sqrt(2x * 2x + 1 * 1) / | 2x
146 // /__|
147 // 1
148 tolB = tolerance / sqrt(4.0 * b * b + 1.0);
149 tolC = tolerance / sqrt(4.0 * c * c + 1.0);
150 }
151 return b < c ? (a >= b - tolB && a < c - tolC) :
152 (a >= c - tolC && a < b - tolB);
153 }
154
155 // returns true if a >= min(b,c) && a <= max(b,c)
between_closed(double a,double b,double c,double tolerance=0.0,bool xformToleranceToX=false)156 static inline bool between_closed(double a, double b, double c,
157 double tolerance = 0.0,
158 bool xformToleranceToX = false) {
159 SkASSERT(tolerance >= 0.0);
160 double tolB = tolerance;
161 double tolC = tolerance;
162
163 if (xformToleranceToX) {
164 tolB = tolerance / sqrt(4.0 * b * b + 1.0);
165 tolC = tolerance / sqrt(4.0 * c * c + 1.0);
166 }
167 return b < c ? (a >= b - tolB && a <= c + tolC) :
168 (a >= c - tolC && a <= b + tolB);
169 }
170
nearly_zero(double x,double tolerance=kNearlyZero)171 static inline bool nearly_zero(double x, double tolerance = kNearlyZero) {
172 SkASSERT(tolerance >= 0.0);
173 return fabs(x) <= tolerance;
174 }
175
nearly_equal(double x,double y,double tolerance=kNearlyZero,bool xformToleranceToX=false)176 static inline bool nearly_equal(double x, double y,
177 double tolerance = kNearlyZero,
178 bool xformToleranceToX = false) {
179 SkASSERT(tolerance >= 0.0);
180 if (xformToleranceToX) {
181 tolerance = tolerance / sqrt(4.0 * y * y + 1.0);
182 }
183 return fabs(x - y) <= tolerance;
184 }
185
sign_of(const double & val)186 static inline double sign_of(const double &val) {
187 return std::copysign(1, val);
188 }
189
is_colinear(const SkPoint pts[3])190 static bool is_colinear(const SkPoint pts[3]) {
191 return nearly_zero((pts[1].fY - pts[0].fY) * (pts[1].fX - pts[2].fX) -
192 (pts[1].fY - pts[2].fY) * (pts[1].fX - pts[0].fX), kCloseSqd);
193 }
194
195 class PathSegment {
196 public:
197 enum {
198 // These enum values are assumed in member functions below.
199 kLine = 0,
200 kQuad = 1,
201 } fType;
202
203 // line uses 2 pts, quad uses 3 pts
204 SkPoint fPts[3];
205
206 DPoint fP0T, fP2T;
207 DAffineMatrix fXformMatrix; // transforms the segment into canonical space
208 double fScalingFactor;
209 double fScalingFactorSqd;
210 double fNearlyZeroScaled;
211 double fTangentTolScaledSqd;
212 SkRect fBoundingBox;
213
214 void init();
215
countPoints()216 int countPoints() {
217 static_assert(0 == kLine && 1 == kQuad);
218 return fType + 2;
219 }
220
endPt() const221 const SkPoint& endPt() const {
222 static_assert(0 == kLine && 1 == kQuad);
223 return fPts[fType + 1];
224 }
225 };
226
227 typedef SkTArray<PathSegment, true> PathSegmentArray;
228
init()229 void PathSegment::init() {
230 const DPoint p0 = { fPts[0].fX, fPts[0].fY };
231 const DPoint p2 = { this->endPt().fX, this->endPt().fY };
232 const double p0x = p0.fX;
233 const double p0y = p0.fY;
234 const double p2x = p2.fX;
235 const double p2y = p2.fY;
236
237 fBoundingBox.set(fPts[0], this->endPt());
238
239 if (fType == PathSegment::kLine) {
240 fScalingFactorSqd = fScalingFactor = 1.0;
241 double hypotenuse = p0.distance(p2);
242
243 const double cosTheta = (p2x - p0x) / hypotenuse;
244 const double sinTheta = (p2y - p0y) / hypotenuse;
245
246 // rotates the segment to the x-axis, with p0 at the origin
247 fXformMatrix.setAffine(
248 cosTheta, sinTheta, -(cosTheta * p0x) - (sinTheta * p0y),
249 -sinTheta, cosTheta, (sinTheta * p0x) - (cosTheta * p0y)
250 );
251 } else {
252 SkASSERT(fType == PathSegment::kQuad);
253
254 // Calculate bounding box
255 const SkPoint _P1mP0 = fPts[1] - fPts[0];
256 SkPoint t = _P1mP0 - fPts[2] + fPts[1];
257 t.fX = _P1mP0.fX / t.fX;
258 t.fY = _P1mP0.fY / t.fY;
259 t.fX = SkTPin(t.fX, 0.0f, 1.0f);
260 t.fY = SkTPin(t.fY, 0.0f, 1.0f);
261 t.fX = _P1mP0.fX * t.fX;
262 t.fY = _P1mP0.fY * t.fY;
263 const SkPoint m = fPts[0] + t;
264 SkRectPriv::GrowToInclude(&fBoundingBox, m);
265
266 const double p1x = fPts[1].fX;
267 const double p1y = fPts[1].fY;
268
269 const double p0xSqd = p0x * p0x;
270 const double p0ySqd = p0y * p0y;
271 const double p2xSqd = p2x * p2x;
272 const double p2ySqd = p2y * p2y;
273 const double p1xSqd = p1x * p1x;
274 const double p1ySqd = p1y * p1y;
275
276 const double p01xProd = p0x * p1x;
277 const double p02xProd = p0x * p2x;
278 const double b12xProd = p1x * p2x;
279 const double p01yProd = p0y * p1y;
280 const double p02yProd = p0y * p2y;
281 const double b12yProd = p1y * p2y;
282
283 // calculate quadratic params
284 const double sqrtA = p0y - (2.0 * p1y) + p2y;
285 const double a = sqrtA * sqrtA;
286 const double h = -1.0 * (p0y - (2.0 * p1y) + p2y) * (p0x - (2.0 * p1x) + p2x);
287 const double sqrtB = p0x - (2.0 * p1x) + p2x;
288 const double b = sqrtB * sqrtB;
289 const double c = (p0xSqd * p2ySqd) - (4.0 * p01xProd * b12yProd)
290 - (2.0 * p02xProd * p02yProd) + (4.0 * p02xProd * p1ySqd)
291 + (4.0 * p1xSqd * p02yProd) - (4.0 * b12xProd * p01yProd)
292 + (p2xSqd * p0ySqd);
293 const double g = (p0x * p02yProd) - (2.0 * p0x * p1ySqd)
294 + (2.0 * p0x * b12yProd) - (p0x * p2ySqd)
295 + (2.0 * p1x * p01yProd) - (4.0 * p1x * p02yProd)
296 + (2.0 * p1x * b12yProd) - (p2x * p0ySqd)
297 + (2.0 * p2x * p01yProd) + (p2x * p02yProd)
298 - (2.0 * p2x * p1ySqd);
299 const double f = -((p0xSqd * p2y) - (2.0 * p01xProd * p1y)
300 - (2.0 * p01xProd * p2y) - (p02xProd * p0y)
301 + (4.0 * p02xProd * p1y) - (p02xProd * p2y)
302 + (2.0 * p1xSqd * p0y) + (2.0 * p1xSqd * p2y)
303 - (2.0 * b12xProd * p0y) - (2.0 * b12xProd * p1y)
304 + (p2xSqd * p0y));
305
306 const double cosTheta = sqrt(a / (a + b));
307 const double sinTheta = -1.0 * sign_of((a + b) * h) * sqrt(b / (a + b));
308
309 const double gDef = cosTheta * g - sinTheta * f;
310 const double fDef = sinTheta * g + cosTheta * f;
311
312
313 const double x0 = gDef / (a + b);
314 const double y0 = (1.0 / (2.0 * fDef)) * (c - (gDef * gDef / (a + b)));
315
316
317 const double lambda = -1.0 * ((a + b) / (2.0 * fDef));
318 fScalingFactor = fabs(1.0 / lambda);
319 fScalingFactorSqd = fScalingFactor * fScalingFactor;
320
321 const double lambda_cosTheta = lambda * cosTheta;
322 const double lambda_sinTheta = lambda * sinTheta;
323
324 // transforms to lie on a canonical y = x^2 parabola
325 fXformMatrix.setAffine(
326 lambda_cosTheta, -lambda_sinTheta, lambda * x0,
327 lambda_sinTheta, lambda_cosTheta, lambda * y0
328 );
329 }
330
331 fNearlyZeroScaled = kNearlyZero / fScalingFactor;
332 fTangentTolScaledSqd = kTangentTolerance * kTangentTolerance / fScalingFactorSqd;
333
334 fP0T = fXformMatrix.mapPoint(p0);
335 fP2T = fXformMatrix.mapPoint(p2);
336 }
337
init_distances(DFData * data,int size)338 static void init_distances(DFData* data, int size) {
339 DFData* currData = data;
340
341 for (int i = 0; i < size; ++i) {
342 // init distance to "far away"
343 currData->fDistSq = SK_DistanceFieldMagnitude * SK_DistanceFieldMagnitude;
344 currData->fDeltaWindingScore = 0;
345 ++currData;
346 }
347 }
348
add_line(const SkPoint pts[2],PathSegmentArray * segments)349 static inline void add_line(const SkPoint pts[2], PathSegmentArray* segments) {
350 segments->push_back();
351 segments->back().fType = PathSegment::kLine;
352 segments->back().fPts[0] = pts[0];
353 segments->back().fPts[1] = pts[1];
354
355 segments->back().init();
356 }
357
add_quad(const SkPoint pts[3],PathSegmentArray * segments)358 static inline void add_quad(const SkPoint pts[3], PathSegmentArray* segments) {
359 if (SkPointPriv::DistanceToSqd(pts[0], pts[1]) < kCloseSqd ||
360 SkPointPriv::DistanceToSqd(pts[1], pts[2]) < kCloseSqd ||
361 is_colinear(pts)) {
362 if (pts[0] != pts[2]) {
363 SkPoint line_pts[2];
364 line_pts[0] = pts[0];
365 line_pts[1] = pts[2];
366 add_line(line_pts, segments);
367 }
368 } else {
369 segments->push_back();
370 segments->back().fType = PathSegment::kQuad;
371 segments->back().fPts[0] = pts[0];
372 segments->back().fPts[1] = pts[1];
373 segments->back().fPts[2] = pts[2];
374
375 segments->back().init();
376 }
377 }
378
add_cubic(const SkPoint pts[4],PathSegmentArray * segments)379 static inline void add_cubic(const SkPoint pts[4],
380 PathSegmentArray* segments) {
381 SkSTArray<15, SkPoint, true> quads;
382 GrPathUtils::convertCubicToQuads(pts, SK_Scalar1, &quads);
383 int count = quads.count();
384 for (int q = 0; q < count; q += 3) {
385 add_quad(&quads[q], segments);
386 }
387 }
388
calculate_nearest_point_for_quad(const PathSegment & segment,const DPoint & xFormPt)389 static float calculate_nearest_point_for_quad(
390 const PathSegment& segment,
391 const DPoint &xFormPt) {
392 static const float kThird = 0.33333333333f;
393 static const float kTwentySeventh = 0.037037037f;
394
395 const float a = 0.5f - (float)xFormPt.fY;
396 const float b = -0.5f * (float)xFormPt.fX;
397
398 const float a3 = a * a * a;
399 const float b2 = b * b;
400
401 const float c = (b2 * 0.25f) + (a3 * kTwentySeventh);
402
403 if (c >= 0.f) {
404 const float sqrtC = sqrt(c);
405 const float result = (float)cbrt((-b * 0.5f) + sqrtC) + (float)cbrt((-b * 0.5f) - sqrtC);
406 return result;
407 } else {
408 const float cosPhi = (float)sqrt((b2 * 0.25f) * (-27.f / a3)) * ((b > 0) ? -1.f : 1.f);
409 const float phi = (float)acos(cosPhi);
410 float result;
411 if (xFormPt.fX > 0.f) {
412 result = 2.f * (float)sqrt(-a * kThird) * (float)cos(phi * kThird);
413 if (!between_closed(result, segment.fP0T.fX, segment.fP2T.fX)) {
414 result = 2.f * (float)sqrt(-a * kThird) * (float)cos((phi * kThird) + (SK_ScalarPI * 2.f * kThird));
415 }
416 } else {
417 result = 2.f * (float)sqrt(-a * kThird) * (float)cos((phi * kThird) + (SK_ScalarPI * 2.f * kThird));
418 if (!between_closed(result, segment.fP0T.fX, segment.fP2T.fX)) {
419 result = 2.f * (float)sqrt(-a * kThird) * (float)cos(phi * kThird);
420 }
421 }
422 return result;
423 }
424 }
425
426 // This structure contains some intermediate values shared by the same row.
427 // It is used to calculate segment side of a quadratic bezier.
428 struct RowData {
429 // The intersection type of a scanline and y = x * x parabola in canonical space.
430 enum IntersectionType {
431 kNoIntersection,
432 kVerticalLine,
433 kTangentLine,
434 kTwoPointsIntersect
435 } fIntersectionType;
436
437 // The direction of the quadratic segment/scanline in the canonical space.
438 // 1: The quadratic segment/scanline going from negative x-axis to positive x-axis.
439 // 0: The scanline is a vertical line in the canonical space.
440 // -1: The quadratic segment/scanline going from positive x-axis to negative x-axis.
441 int fQuadXDirection;
442 int fScanlineXDirection;
443
444 // The y-value(equal to x*x) of intersection point for the kVerticalLine intersection type.
445 double fYAtIntersection;
446
447 // The x-value for two intersection points.
448 double fXAtIntersection1;
449 double fXAtIntersection2;
450 };
451
precomputation_for_row(RowData * rowData,const PathSegment & segment,const SkPoint & pointLeft,const SkPoint & pointRight)452 void precomputation_for_row(RowData *rowData, const PathSegment& segment,
453 const SkPoint& pointLeft, const SkPoint& pointRight) {
454 if (segment.fType != PathSegment::kQuad) {
455 return;
456 }
457
458 const DPoint& xFormPtLeft = segment.fXformMatrix.mapPoint(pointLeft);
459 const DPoint& xFormPtRight = segment.fXformMatrix.mapPoint(pointRight);
460
461 rowData->fQuadXDirection = (int)sign_of(segment.fP2T.fX - segment.fP0T.fX);
462 rowData->fScanlineXDirection = (int)sign_of(xFormPtRight.fX - xFormPtLeft.fX);
463
464 const double x1 = xFormPtLeft.fX;
465 const double y1 = xFormPtLeft.fY;
466 const double x2 = xFormPtRight.fX;
467 const double y2 = xFormPtRight.fY;
468
469 if (nearly_equal(x1, x2, segment.fNearlyZeroScaled, true)) {
470 rowData->fIntersectionType = RowData::kVerticalLine;
471 rowData->fYAtIntersection = x1 * x1;
472 rowData->fScanlineXDirection = 0;
473 return;
474 }
475
476 // Line y = mx + b
477 const double m = (y2 - y1) / (x2 - x1);
478 const double b = -m * x1 + y1;
479
480 const double m2 = m * m;
481 const double c = m2 + 4.0 * b;
482
483 const double tol = 4.0 * segment.fTangentTolScaledSqd / (m2 + 1.0);
484
485 // Check if the scanline is the tangent line of the curve,
486 // and the curve start or end at the same y-coordinate of the scanline
487 if ((rowData->fScanlineXDirection == 1 &&
488 (segment.fPts[0].fY == pointLeft.fY ||
489 segment.fPts[2].fY == pointLeft.fY)) &&
490 nearly_zero(c, tol)) {
491 rowData->fIntersectionType = RowData::kTangentLine;
492 rowData->fXAtIntersection1 = m / 2.0;
493 rowData->fXAtIntersection2 = m / 2.0;
494 } else if (c <= 0.0) {
495 rowData->fIntersectionType = RowData::kNoIntersection;
496 return;
497 } else {
498 rowData->fIntersectionType = RowData::kTwoPointsIntersect;
499 const double d = sqrt(c);
500 rowData->fXAtIntersection1 = (m + d) / 2.0;
501 rowData->fXAtIntersection2 = (m - d) / 2.0;
502 }
503 }
504
calculate_side_of_quad(const PathSegment & segment,const SkPoint & point,const DPoint & xFormPt,const RowData & rowData)505 SegSide calculate_side_of_quad(
506 const PathSegment& segment,
507 const SkPoint& point,
508 const DPoint& xFormPt,
509 const RowData& rowData) {
510 SegSide side = kNA_SegSide;
511
512 if (RowData::kVerticalLine == rowData.fIntersectionType) {
513 side = (SegSide)(int)(sign_of(xFormPt.fY - rowData.fYAtIntersection) * rowData.fQuadXDirection);
514 }
515 else if (RowData::kTwoPointsIntersect == rowData.fIntersectionType) {
516 const double p1 = rowData.fXAtIntersection1;
517 const double p2 = rowData.fXAtIntersection2;
518
519 int signP1 = (int)sign_of(p1 - xFormPt.fX);
520 bool includeP1 = true;
521 bool includeP2 = true;
522
523 if (rowData.fScanlineXDirection == 1) {
524 if ((rowData.fQuadXDirection == -1 && segment.fPts[0].fY <= point.fY &&
525 nearly_equal(segment.fP0T.fX, p1, segment.fNearlyZeroScaled, true)) ||
526 (rowData.fQuadXDirection == 1 && segment.fPts[2].fY <= point.fY &&
527 nearly_equal(segment.fP2T.fX, p1, segment.fNearlyZeroScaled, true))) {
528 includeP1 = false;
529 }
530 if ((rowData.fQuadXDirection == -1 && segment.fPts[2].fY <= point.fY &&
531 nearly_equal(segment.fP2T.fX, p2, segment.fNearlyZeroScaled, true)) ||
532 (rowData.fQuadXDirection == 1 && segment.fPts[0].fY <= point.fY &&
533 nearly_equal(segment.fP0T.fX, p2, segment.fNearlyZeroScaled, true))) {
534 includeP2 = false;
535 }
536 }
537
538 if (includeP1 && between_closed(p1, segment.fP0T.fX, segment.fP2T.fX,
539 segment.fNearlyZeroScaled, true)) {
540 side = (SegSide)(signP1 * rowData.fQuadXDirection);
541 }
542 if (includeP2 && between_closed(p2, segment.fP0T.fX, segment.fP2T.fX,
543 segment.fNearlyZeroScaled, true)) {
544 int signP2 = (int)sign_of(p2 - xFormPt.fX);
545 if (side == kNA_SegSide || signP2 == 1) {
546 side = (SegSide)(-signP2 * rowData.fQuadXDirection);
547 }
548 }
549 } else if (RowData::kTangentLine == rowData.fIntersectionType) {
550 // The scanline is the tangent line of current quadratic segment.
551
552 const double p = rowData.fXAtIntersection1;
553 int signP = (int)sign_of(p - xFormPt.fX);
554 if (rowData.fScanlineXDirection == 1) {
555 // The path start or end at the tangent point.
556 if (segment.fPts[0].fY == point.fY) {
557 side = (SegSide)(signP);
558 } else if (segment.fPts[2].fY == point.fY) {
559 side = (SegSide)(-signP);
560 }
561 }
562 }
563
564 return side;
565 }
566
distance_to_segment(const SkPoint & point,const PathSegment & segment,const RowData & rowData,SegSide * side)567 static float distance_to_segment(const SkPoint& point,
568 const PathSegment& segment,
569 const RowData& rowData,
570 SegSide* side) {
571 SkASSERT(side);
572
573 const DPoint xformPt = segment.fXformMatrix.mapPoint(point);
574
575 if (segment.fType == PathSegment::kLine) {
576 float result = SK_DistanceFieldPad * SK_DistanceFieldPad;
577
578 if (between_closed(xformPt.fX, segment.fP0T.fX, segment.fP2T.fX)) {
579 result = (float)(xformPt.fY * xformPt.fY);
580 } else if (xformPt.fX < segment.fP0T.fX) {
581 result = (float)(xformPt.fX * xformPt.fX + xformPt.fY * xformPt.fY);
582 } else {
583 result = (float)((xformPt.fX - segment.fP2T.fX) * (xformPt.fX - segment.fP2T.fX)
584 + xformPt.fY * xformPt.fY);
585 }
586
587 if (between_closed_open(point.fY, segment.fBoundingBox.fTop,
588 segment.fBoundingBox.fBottom)) {
589 *side = (SegSide)(int)sign_of(xformPt.fY);
590 } else {
591 *side = kNA_SegSide;
592 }
593 return result;
594 } else {
595 SkASSERT(segment.fType == PathSegment::kQuad);
596
597 const float nearestPoint = calculate_nearest_point_for_quad(segment, xformPt);
598
599 float dist;
600
601 if (between_closed(nearestPoint, segment.fP0T.fX, segment.fP2T.fX)) {
602 DPoint x = { nearestPoint, nearestPoint * nearestPoint };
603 dist = (float)xformPt.distanceSquared(x);
604 } else {
605 const float distToB0T = (float)xformPt.distanceSquared(segment.fP0T);
606 const float distToB2T = (float)xformPt.distanceSquared(segment.fP2T);
607
608 if (distToB0T < distToB2T) {
609 dist = distToB0T;
610 } else {
611 dist = distToB2T;
612 }
613 }
614
615 if (between_closed_open(point.fY, segment.fBoundingBox.fTop,
616 segment.fBoundingBox.fBottom)) {
617 *side = calculate_side_of_quad(segment, point, xformPt, rowData);
618 } else {
619 *side = kNA_SegSide;
620 }
621
622 return (float)(dist * segment.fScalingFactorSqd);
623 }
624 }
625
calculate_distance_field_data(PathSegmentArray * segments,DFData * dataPtr,int width,int height)626 static void calculate_distance_field_data(PathSegmentArray* segments,
627 DFData* dataPtr,
628 int width, int height) {
629 int count = segments->count();
630 // for each segment
631 for (int a = 0; a < count; ++a) {
632 PathSegment& segment = (*segments)[a];
633 const SkRect& segBB = segment.fBoundingBox;
634 // get the bounding box, outset by distance field pad, and clip to total bounds
635 const SkRect& paddedBB = segBB.makeOutset(SK_DistanceFieldPad, SK_DistanceFieldPad);
636 int startColumn = (int)paddedBB.fLeft;
637 int endColumn = SkScalarCeilToInt(paddedBB.fRight);
638
639 int startRow = (int)paddedBB.fTop;
640 int endRow = SkScalarCeilToInt(paddedBB.fBottom);
641
642 SkASSERT((startColumn >= 0) && "StartColumn < 0!");
643 SkASSERT((endColumn <= width) && "endColumn > width!");
644 SkASSERT((startRow >= 0) && "StartRow < 0!");
645 SkASSERT((endRow <= height) && "EndRow > height!");
646
647 // Clip inside the distance field to avoid overflow
648 startColumn = std::max(startColumn, 0);
649 endColumn = std::min(endColumn, width);
650 startRow = std::max(startRow, 0);
651 endRow = std::min(endRow, height);
652
653 // for each row in the padded bounding box
654 for (int row = startRow; row < endRow; ++row) {
655 SegSide prevSide = kNA_SegSide; // track side for winding count
656 const float pY = row + 0.5f; // offset by 1/2? why?
657 RowData rowData;
658
659 const SkPoint pointLeft = SkPoint::Make((SkScalar)startColumn, pY);
660 const SkPoint pointRight = SkPoint::Make((SkScalar)endColumn, pY);
661
662 // if this is a row inside the original segment bounding box
663 if (between_closed_open(pY, segBB.fTop, segBB.fBottom)) {
664 // compute intersections with the row
665 precomputation_for_row(&rowData, segment, pointLeft, pointRight);
666 }
667
668 // adjust distances and windings in each column based on the row calculation
669 for (int col = startColumn; col < endColumn; ++col) {
670 int idx = (row * width) + col;
671
672 const float pX = col + 0.5f;
673 const SkPoint point = SkPoint::Make(pX, pY);
674
675 const float distSq = dataPtr[idx].fDistSq;
676
677 // Optimization for not calculating some points.
678 int dilation = distSq < 1.5f * 1.5f ? 1 :
679 distSq < 2.5f * 2.5f ? 2 :
680 distSq < 3.5f * 3.5f ? 3 : SK_DistanceFieldPad;
681 if (dilation < SK_DistanceFieldPad &&
682 !segBB.roundOut().makeOutset(dilation, dilation).contains(col, row)) {
683 continue;
684 }
685
686 SegSide side = kNA_SegSide;
687 int deltaWindingScore = 0;
688 float currDistSq = distance_to_segment(point, segment, rowData, &side);
689 if (prevSide == kLeft_SegSide && side == kRight_SegSide) {
690 deltaWindingScore = -1;
691 } else if (prevSide == kRight_SegSide && side == kLeft_SegSide) {
692 deltaWindingScore = 1;
693 }
694
695 prevSide = side;
696
697 if (currDistSq < distSq) {
698 dataPtr[idx].fDistSq = currDistSq;
699 }
700
701 dataPtr[idx].fDeltaWindingScore += deltaWindingScore;
702 }
703 }
704 }
705 }
706
707 template <int distanceMagnitude>
pack_distance_field_val(float dist)708 static unsigned char pack_distance_field_val(float dist) {
709 // The distance field is constructed as unsigned char values, so that the zero value is at 128,
710 // Beside 128, we have 128 values in range [0, 128), but only 127 values in range (128, 255].
711 // So we multiply distanceMagnitude by 127/128 at the latter range to avoid overflow.
712 dist = SkTPin<float>(-dist, -distanceMagnitude, distanceMagnitude * 127.0f / 128.0f);
713
714 // Scale into the positive range for unsigned distance.
715 dist += distanceMagnitude;
716
717 // Scale into unsigned char range.
718 // Round to place negative and positive values as equally as possible around 128
719 // (which represents zero).
720 return (unsigned char)SkScalarRoundToInt(dist / (2 * distanceMagnitude) * 256.0f);
721 }
722
GrGenerateDistanceFieldFromPath(unsigned char * distanceField,const SkPath & path,const SkMatrix & drawMatrix,int width,int height,size_t rowBytes)723 bool GrGenerateDistanceFieldFromPath(unsigned char* distanceField,
724 const SkPath& path, const SkMatrix& drawMatrix,
725 int width, int height, size_t rowBytes) {
726 SkASSERT(distanceField);
727
728 // transform to device space, then:
729 // translate path to offset (SK_DistanceFieldPad, SK_DistanceFieldPad)
730 SkMatrix dfMatrix(drawMatrix);
731 dfMatrix.postTranslate(SK_DistanceFieldPad, SK_DistanceFieldPad);
732
733 #ifdef SK_DEBUG
734 SkPath xformPath;
735 path.transform(dfMatrix, &xformPath);
736 SkIRect pathBounds = xformPath.getBounds().roundOut();
737 SkIRect expectPathBounds = SkIRect::MakeWH(width, height);
738 #endif
739
740 SkASSERT(expectPathBounds.isEmpty() ||
741 expectPathBounds.contains(pathBounds.fLeft, pathBounds.fTop));
742 SkASSERT(expectPathBounds.isEmpty() || pathBounds.isEmpty() ||
743 expectPathBounds.contains(pathBounds));
744
745 // TODO: restore when Simplify() is working correctly
746 // see https://bugs.chromium.org/p/skia/issues/detail?id=9732
747 // SkPath simplifiedPath;
748 SkPath workingPath;
749 // if (Simplify(path, &simplifiedPath)) {
750 // workingPath = simplifiedPath;
751 // } else {
752 workingPath = path;
753 // }
754 // only even-odd and inverse even-odd supported
755 if (!IsDistanceFieldSupportedFillType(workingPath.getFillType())) {
756 return false;
757 }
758
759 // transform to device space + SDF offset
760 workingPath.transform(dfMatrix);
761
762 SkDEBUGCODE(pathBounds = workingPath.getBounds().roundOut());
763 SkASSERT(expectPathBounds.isEmpty() ||
764 expectPathBounds.contains(pathBounds.fLeft, pathBounds.fTop));
765 SkASSERT(expectPathBounds.isEmpty() || pathBounds.isEmpty() ||
766 expectPathBounds.contains(pathBounds));
767
768 // create temp data
769 size_t dataSize = width * height * sizeof(DFData);
770 SkAutoSMalloc<1024> dfStorage(dataSize);
771 DFData* dataPtr = (DFData*) dfStorage.get();
772
773 // create initial distance data (init to "far away")
774 init_distances(dataPtr, width * height);
775
776 // polygonize path into line and quad segments
777 SkPathEdgeIter iter(workingPath);
778 SkSTArray<15, PathSegment, true> segments;
779 while (auto e = iter.next()) {
780 switch (e.fEdge) {
781 case SkPathEdgeIter::Edge::kLine: {
782 add_line(e.fPts, &segments);
783 break;
784 }
785 case SkPathEdgeIter::Edge::kQuad:
786 add_quad(e.fPts, &segments);
787 break;
788 case SkPathEdgeIter::Edge::kConic: {
789 SkScalar weight = iter.conicWeight();
790 SkAutoConicToQuads converter;
791 const SkPoint* quadPts = converter.computeQuads(e.fPts, weight, kConicTolerance);
792 for (int i = 0; i < converter.countQuads(); ++i) {
793 add_quad(quadPts + 2*i, &segments);
794 }
795 break;
796 }
797 case SkPathEdgeIter::Edge::kCubic: {
798 add_cubic(e.fPts, &segments);
799 break;
800 }
801 }
802 }
803
804 // do all the work
805 calculate_distance_field_data(&segments, dataPtr, width, height);
806
807 // adjust distance based on winding
808 for (int row = 0; row < height; ++row) {
809 enum DFSign {
810 kInside = -1,
811 kOutside = 1
812 };
813 int windingNumber = 0; // Winding number start from zero for each scanline
814 for (int col = 0; col < width; ++col) {
815 int idx = (row * width) + col;
816 windingNumber += dataPtr[idx].fDeltaWindingScore;
817
818 DFSign dfSign;
819 switch (workingPath.getFillType()) {
820 case SkPathFillType::kWinding:
821 dfSign = windingNumber ? kInside : kOutside;
822 break;
823 case SkPathFillType::kInverseWinding:
824 dfSign = windingNumber ? kOutside : kInside;
825 break;
826 case SkPathFillType::kEvenOdd:
827 dfSign = (windingNumber % 2) ? kInside : kOutside;
828 break;
829 case SkPathFillType::kInverseEvenOdd:
830 dfSign = (windingNumber % 2) ? kOutside : kInside;
831 break;
832 }
833
834 const float miniDist = sqrt(dataPtr[idx].fDistSq);
835 const float dist = dfSign * miniDist;
836
837 unsigned char pixelVal = pack_distance_field_val<SK_DistanceFieldMagnitude>(dist);
838
839 distanceField[(row * rowBytes) + col] = pixelVal;
840 }
841
842 // The winding number at the end of a scanline should be zero.
843 if (windingNumber != 0) {
844 SkDEBUGFAIL("Winding number should be zero at the end of a scan line.");
845 // Fallback to use SkPath::contains to determine the sign of pixel in release build.
846 for (int col = 0; col < width; ++col) {
847 int idx = (row * width) + col;
848 DFSign dfSign = workingPath.contains(col + 0.5, row + 0.5) ? kInside : kOutside;
849 const float miniDist = sqrt(dataPtr[idx].fDistSq);
850 const float dist = dfSign * miniDist;
851
852 unsigned char pixelVal = pack_distance_field_val<SK_DistanceFieldMagnitude>(dist);
853
854 distanceField[(row * rowBytes) + col] = pixelVal;
855 }
856 continue;
857 }
858 }
859 return true;
860 }
861