• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2011 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "src/gpu/ops/AAHairLinePathRenderer.h"
9 
10 #include "include/core/SkPoint3.h"
11 #include "include/private/SkTemplates.h"
12 #include "src/core/SkGeometry.h"
13 #include "src/core/SkMatrixPriv.h"
14 #include "src/core/SkPointPriv.h"
15 #include "src/core/SkRectPriv.h"
16 #include "src/core/SkStroke.h"
17 #include "src/gpu/GrAuditTrail.h"
18 #include "src/gpu/GrBuffer.h"
19 #include "src/gpu/GrCaps.h"
20 #include "src/gpu/GrDefaultGeoProcFactory.h"
21 #include "src/gpu/GrDrawOpTest.h"
22 #include "src/gpu/GrOpFlushState.h"
23 #include "src/gpu/GrProcessor.h"
24 #include "src/gpu/GrProgramInfo.h"
25 #include "src/gpu/GrResourceProvider.h"
26 #include "src/gpu/GrStyle.h"
27 #include "src/gpu/GrUtil.h"
28 #include "src/gpu/effects/GrBezierEffect.h"
29 #include "src/gpu/geometry/GrPathUtils.h"
30 #include "src/gpu/geometry/GrStyledShape.h"
31 #include "src/gpu/ops/GrMeshDrawOp.h"
32 #include "src/gpu/ops/GrSimpleMeshDrawOpHelperWithStencil.h"
33 #include "src/gpu/v1/SurfaceDrawContext_v1.h"
34 
35 #define PREALLOC_PTARRAY(N) SkSTArray<(N),SkPoint, true>
36 
37 using PtArray = SkTArray<SkPoint, true>;
38 using IntArray = SkTArray<int, true>;
39 using FloatArray = SkTArray<float, true>;
40 
41 namespace {
42 
43 // quadratics are rendered as 5-sided polys in order to bound the
44 // AA stroke around the center-curve. See comments in push_quad_index_buffer and
45 // bloat_quad. Quadratics and conics share an index buffer
46 
47 // lines are rendered as:
48 //      *______________*
49 //      |\ -_______   /|
50 //      | \        \ / |
51 //      |  *--------*  |
52 //      | /  ______/ \ |
53 //      */_-__________\*
54 // For: 6 vertices and 18 indices (for 6 triangles)
55 
56 // Each quadratic is rendered as a five sided polygon. This poly bounds
57 // the quadratic's bounding triangle but has been expanded so that the
58 // 1-pixel wide area around the curve is inside the poly.
59 // If a,b,c are the original control points then the poly a0,b0,c0,c1,a1
60 // that is rendered would look like this:
61 //              b0
62 //              b
63 //
64 //     a0              c0
65 //      a            c
66 //       a1       c1
67 // Each is drawn as three triangles ((a0,a1,b0), (b0,c1,c0), (a1,c1,b0))
68 // specified by these 9 indices:
69 static const uint16_t kQuadIdxBufPattern[] = {
70     0, 1, 2,
71     2, 4, 3,
72     1, 4, 2
73 };
74 
75 static const int kIdxsPerQuad = SK_ARRAY_COUNT(kQuadIdxBufPattern);
76 static const int kQuadNumVertices = 5;
77 static const int kQuadsNumInIdxBuffer = 256;
78 SKGPU_DECLARE_STATIC_UNIQUE_KEY(gQuadsIndexBufferKey);
79 
get_quads_index_buffer(GrResourceProvider * resourceProvider)80 sk_sp<const GrBuffer> get_quads_index_buffer(GrResourceProvider* resourceProvider) {
81     SKGPU_DEFINE_STATIC_UNIQUE_KEY(gQuadsIndexBufferKey);
82     return resourceProvider->findOrCreatePatternedIndexBuffer(
83         kQuadIdxBufPattern, kIdxsPerQuad, kQuadsNumInIdxBuffer, kQuadNumVertices,
84         gQuadsIndexBufferKey);
85 }
86 
87 
88 // Each line segment is rendered as two quads and two triangles.
89 // p0 and p1 have alpha = 1 while all other points have alpha = 0.
90 // The four external points are offset 1 pixel perpendicular to the
91 // line and half a pixel parallel to the line.
92 //
93 // p4                  p5
94 //      p0         p1
95 // p2                  p3
96 //
97 // Each is drawn as six triangles specified by these 18 indices:
98 
99 static const uint16_t kLineSegIdxBufPattern[] = {
100     0, 1, 3,
101     0, 3, 2,
102     0, 4, 5,
103     0, 5, 1,
104     0, 2, 4,
105     1, 5, 3
106 };
107 
108 static const int kIdxsPerLineSeg = SK_ARRAY_COUNT(kLineSegIdxBufPattern);
109 static const int kLineSegNumVertices = 6;
110 static const int kLineSegsNumInIdxBuffer = 256;
111 
112 SKGPU_DECLARE_STATIC_UNIQUE_KEY(gLinesIndexBufferKey);
113 
get_lines_index_buffer(GrResourceProvider * resourceProvider)114 sk_sp<const GrBuffer> get_lines_index_buffer(GrResourceProvider* resourceProvider) {
115     SKGPU_DEFINE_STATIC_UNIQUE_KEY(gLinesIndexBufferKey);
116     return resourceProvider->findOrCreatePatternedIndexBuffer(
117         kLineSegIdxBufPattern, kIdxsPerLineSeg,  kLineSegsNumInIdxBuffer, kLineSegNumVertices,
118         gLinesIndexBufferKey);
119 }
120 
121 // Takes 178th time of logf on Z600 / VC2010
get_float_exp(float x)122 int get_float_exp(float x) {
123     static_assert(sizeof(int) == sizeof(float));
124 #ifdef SK_DEBUG
125     static bool tested;
126     if (!tested) {
127         tested = true;
128         SkASSERT(get_float_exp(0.25f) == -2);
129         SkASSERT(get_float_exp(0.3f) == -2);
130         SkASSERT(get_float_exp(0.5f) == -1);
131         SkASSERT(get_float_exp(1.f) == 0);
132         SkASSERT(get_float_exp(2.f) == 1);
133         SkASSERT(get_float_exp(2.5f) == 1);
134         SkASSERT(get_float_exp(8.f) == 3);
135         SkASSERT(get_float_exp(100.f) == 6);
136         SkASSERT(get_float_exp(1000.f) == 9);
137         SkASSERT(get_float_exp(1024.f) == 10);
138         SkASSERT(get_float_exp(3000000.f) == 21);
139     }
140 #endif
141     const int* iptr = (const int*)&x;
142     return (((*iptr) & 0x7f800000) >> 23) - 127;
143 }
144 
145 // Uses the max curvature function for quads to estimate
146 // where to chop the conic. If the max curvature is not
147 // found along the curve segment it will return 1 and
148 // dst[0] is the original conic. If it returns 2 the dst[0]
149 // and dst[1] are the two new conics.
split_conic(const SkPoint src[3],SkConic dst[2],const SkScalar weight)150 int split_conic(const SkPoint src[3], SkConic dst[2], const SkScalar weight) {
151     SkScalar t = SkFindQuadMaxCurvature(src);
152     if (t == 0 || t == 1) {
153         if (dst) {
154             dst[0].set(src, weight);
155         }
156         return 1;
157     } else {
158         if (dst) {
159             SkConic conic;
160             conic.set(src, weight);
161             if (!conic.chopAt(t, dst)) {
162                 dst[0].set(src, weight);
163                 return 1;
164             }
165         }
166         return 2;
167     }
168 }
169 
170 // Calls split_conic on the entire conic and then once more on each subsection.
171 // Most cases will result in either 1 conic (chop point is not within t range)
172 // or 3 points (split once and then one subsection is split again).
chop_conic(const SkPoint src[3],SkConic dst[4],const SkScalar weight)173 int chop_conic(const SkPoint src[3], SkConic dst[4], const SkScalar weight) {
174     SkConic dstTemp[2];
175     int conicCnt = split_conic(src, dstTemp, weight);
176     if (2 == conicCnt) {
177         int conicCnt2 = split_conic(dstTemp[0].fPts, dst, dstTemp[0].fW);
178         conicCnt = conicCnt2 + split_conic(dstTemp[1].fPts, &dst[conicCnt2], dstTemp[1].fW);
179     } else {
180         dst[0] = dstTemp[0];
181     }
182     return conicCnt;
183 }
184 
185 // returns 0 if quad/conic is degen or close to it
186 // in this case approx the path with lines
187 // otherwise returns 1
is_degen_quad_or_conic(const SkPoint p[3],SkScalar * dsqd)188 int is_degen_quad_or_conic(const SkPoint p[3], SkScalar* dsqd) {
189     static const SkScalar gDegenerateToLineTol = GrPathUtils::kDefaultTolerance;
190     static const SkScalar gDegenerateToLineTolSqd =
191         gDegenerateToLineTol * gDegenerateToLineTol;
192 
193     if (SkPointPriv::DistanceToSqd(p[0], p[1]) < gDegenerateToLineTolSqd ||
194         SkPointPriv::DistanceToSqd(p[1], p[2]) < gDegenerateToLineTolSqd) {
195         return 1;
196     }
197 
198     *dsqd = SkPointPriv::DistanceToLineBetweenSqd(p[1], p[0], p[2]);
199     if (*dsqd < gDegenerateToLineTolSqd) {
200         return 1;
201     }
202 
203     if (SkPointPriv::DistanceToLineBetweenSqd(p[2], p[1], p[0]) < gDegenerateToLineTolSqd) {
204         return 1;
205     }
206     return 0;
207 }
208 
is_degen_quad_or_conic(const SkPoint p[3])209 int is_degen_quad_or_conic(const SkPoint p[3]) {
210     SkScalar dsqd;
211     return is_degen_quad_or_conic(p, &dsqd);
212 }
213 
214 // we subdivide the quads to avoid huge overfill
215 // if it returns -1 then should be drawn as lines
num_quad_subdivs(const SkPoint p[3])216 int num_quad_subdivs(const SkPoint p[3]) {
217     SkScalar dsqd;
218     if (is_degen_quad_or_conic(p, &dsqd)) {
219         return -1;
220     }
221 
222     // tolerance of triangle height in pixels
223     // tuned on windows  Quadro FX 380 / Z600
224     // trade off of fill vs cpu time on verts
225     // maybe different when do this using gpu (geo or tess shaders)
226     static const SkScalar gSubdivTol = 175 * SK_Scalar1;
227 
228     if (dsqd <= gSubdivTol * gSubdivTol) {
229         return 0;
230     } else {
231         static const int kMaxSub = 4;
232         // subdividing the quad reduces d by 4. so we want x = log4(d/tol)
233         // = log4(d*d/tol*tol)/2
234         // = log2(d*d/tol*tol)
235 
236         // +1 since we're ignoring the mantissa contribution.
237         int log = get_float_exp(dsqd/(gSubdivTol*gSubdivTol)) + 1;
238         log = std::min(std::max(0, log), kMaxSub);
239         return log;
240     }
241 }
242 
243 /**
244  * Generates the lines and quads to be rendered. Lines are always recorded in
245  * device space. We will do a device space bloat to account for the 1pixel
246  * thickness.
247  * Quads are recorded in device space unless m contains
248  * perspective, then in they are in src space. We do this because we will
249  * subdivide large quads to reduce over-fill. This subdivision has to be
250  * performed before applying the perspective matrix.
251  */
gather_lines_and_quads(const SkPath & path,const SkMatrix & m,const SkIRect & devClipBounds,SkScalar capLength,bool convertConicsToQuads,PtArray * lines,PtArray * quads,PtArray * conics,IntArray * quadSubdivCnts,FloatArray * conicWeights)252 int gather_lines_and_quads(const SkPath& path,
253                            const SkMatrix& m,
254                            const SkIRect& devClipBounds,
255                            SkScalar capLength,
256                            bool convertConicsToQuads,
257                            PtArray* lines,
258                            PtArray* quads,
259                            PtArray* conics,
260                            IntArray* quadSubdivCnts,
261                            FloatArray* conicWeights) {
262     SkPath::Iter iter(path, false);
263 
264     int totalQuadCount = 0;
265     SkRect bounds;
266     SkIRect ibounds;
267 
268     bool persp = m.hasPerspective();
269 
270     // Whenever a degenerate, zero-length contour is encountered, this code will insert a
271     // 'capLength' x-aligned line segment. Since this is rendering hairlines it is hoped this will
272     // suffice for AA square & circle capping.
273     int verbsInContour = 0; // Does not count moves
274     bool seenZeroLengthVerb = false;
275     SkPoint zeroVerbPt;
276 
277     // Adds a quad that has already been chopped to the list and checks for quads that are close to
278     // lines. Also does a bounding box check. It takes points that are in src space and device
279     // space. The src points are only required if the view matrix has perspective.
280     auto addChoppedQuad = [&](const SkPoint srcPts[3], const SkPoint devPts[4],
281                               bool isContourStart) {
282         SkRect bounds;
283         SkIRect ibounds;
284         bounds.setBounds(devPts, 3);
285         bounds.outset(SK_Scalar1, SK_Scalar1);
286         bounds.roundOut(&ibounds);
287         // We only need the src space space pts when not in perspective.
288         SkASSERT(srcPts || !persp);
289         if (SkIRect::Intersects(devClipBounds, ibounds)) {
290             int subdiv = num_quad_subdivs(devPts);
291             SkASSERT(subdiv >= -1);
292             if (-1 == subdiv) {
293                 SkPoint* pts = lines->push_back_n(4);
294                 pts[0] = devPts[0];
295                 pts[1] = devPts[1];
296                 pts[2] = devPts[1];
297                 pts[3] = devPts[2];
298                 if (isContourStart && pts[0] == pts[1] && pts[2] == pts[3]) {
299                     seenZeroLengthVerb = true;
300                     zeroVerbPt = pts[0];
301                 }
302             } else {
303                 // when in perspective keep quads in src space
304                 const SkPoint* qPts = persp ? srcPts : devPts;
305                 SkPoint* pts = quads->push_back_n(3);
306                 pts[0] = qPts[0];
307                 pts[1] = qPts[1];
308                 pts[2] = qPts[2];
309                 quadSubdivCnts->push_back() = subdiv;
310                 totalQuadCount += 1 << subdiv;
311             }
312         }
313     };
314 
315     // Applies the view matrix to quad src points and calls the above helper.
316     auto addSrcChoppedQuad = [&](const SkPoint srcSpaceQuadPts[3], bool isContourStart) {
317         SkPoint devPts[3];
318         m.mapPoints(devPts, srcSpaceQuadPts, 3);
319         addChoppedQuad(srcSpaceQuadPts, devPts, isContourStart);
320     };
321 
322     for (;;) {
323         SkPoint pathPts[4];
324         SkPath::Verb verb = iter.next(pathPts);
325         switch (verb) {
326             case SkPath::kConic_Verb:
327                 if (convertConicsToQuads) {
328                     SkScalar weight = iter.conicWeight();
329                     SkAutoConicToQuads converter;
330                     const SkPoint* quadPts = converter.computeQuads(pathPts, weight, 0.25f);
331                     for (int i = 0; i < converter.countQuads(); ++i) {
332                         addSrcChoppedQuad(quadPts + 2 * i, !verbsInContour && 0 == i);
333                     }
334                 } else {
335                     SkConic dst[4];
336                     // We chop the conics to create tighter clipping to hide error
337                     // that appears near max curvature of very thin conics. Thin
338                     // hyperbolas with high weight still show error.
339                     int conicCnt = chop_conic(pathPts, dst, iter.conicWeight());
340                     for (int i = 0; i < conicCnt; ++i) {
341                         SkPoint devPts[4];
342                         SkPoint* chopPnts = dst[i].fPts;
343                         m.mapPoints(devPts, chopPnts, 3);
344                         bounds.setBounds(devPts, 3);
345                         bounds.outset(SK_Scalar1, SK_Scalar1);
346                         bounds.roundOut(&ibounds);
347                         if (SkIRect::Intersects(devClipBounds, ibounds)) {
348                             if (is_degen_quad_or_conic(devPts)) {
349                                 SkPoint* pts = lines->push_back_n(4);
350                                 pts[0] = devPts[0];
351                                 pts[1] = devPts[1];
352                                 pts[2] = devPts[1];
353                                 pts[3] = devPts[2];
354                                 if (verbsInContour == 0 && i == 0 && pts[0] == pts[1] &&
355                                     pts[2] == pts[3]) {
356                                     seenZeroLengthVerb = true;
357                                     zeroVerbPt = pts[0];
358                                 }
359                             } else {
360                                 // when in perspective keep conics in src space
361                                 SkPoint* cPts = persp ? chopPnts : devPts;
362                                 SkPoint* pts = conics->push_back_n(3);
363                                 pts[0] = cPts[0];
364                                 pts[1] = cPts[1];
365                                 pts[2] = cPts[2];
366                                 conicWeights->push_back() = dst[i].fW;
367                             }
368                         }
369                     }
370                 }
371                 verbsInContour++;
372                 break;
373             case SkPath::kMove_Verb:
374                 // New contour (and last one was unclosed). If it was just a zero length drawing
375                 // operation, and we're supposed to draw caps, then add a tiny line.
376                 if (seenZeroLengthVerb && verbsInContour == 1 && capLength > 0) {
377                     SkPoint* pts = lines->push_back_n(2);
378                     pts[0] = SkPoint::Make(zeroVerbPt.fX - capLength, zeroVerbPt.fY);
379                     pts[1] = SkPoint::Make(zeroVerbPt.fX + capLength, zeroVerbPt.fY);
380                 }
381                 verbsInContour = 0;
382                 seenZeroLengthVerb = false;
383                 break;
384             case SkPath::kLine_Verb: {
385                 SkPoint devPts[2];
386                 m.mapPoints(devPts, pathPts, 2);
387                 bounds.setBounds(devPts, 2);
388                 bounds.outset(SK_Scalar1, SK_Scalar1);
389                 bounds.roundOut(&ibounds);
390                 if (SkIRect::Intersects(devClipBounds, ibounds)) {
391                     SkPoint* pts = lines->push_back_n(2);
392                     pts[0] = devPts[0];
393                     pts[1] = devPts[1];
394                     if (verbsInContour == 0 && pts[0] == pts[1]) {
395                         seenZeroLengthVerb = true;
396                         zeroVerbPt = pts[0];
397                     }
398                 }
399                 verbsInContour++;
400                 break;
401             }
402             case SkPath::kQuad_Verb: {
403                 SkPoint choppedPts[5];
404                 // Chopping the quad helps when the quad is either degenerate or nearly degenerate.
405                 // When it is degenerate it allows the approximation with lines to work since the
406                 // chop point (if there is one) will be at the parabola's vertex. In the nearly
407                 // degenerate the QuadUVMatrix computed for the points is almost singular which
408                 // can cause rendering artifacts.
409                 int n = SkChopQuadAtMaxCurvature(pathPts, choppedPts);
410                 for (int i = 0; i < n; ++i) {
411                     addSrcChoppedQuad(choppedPts + i * 2, !verbsInContour && 0 == i);
412                 }
413                 verbsInContour++;
414                 break;
415             }
416             case SkPath::kCubic_Verb: {
417                 SkPoint devPts[4];
418                 m.mapPoints(devPts, pathPts, 4);
419                 bounds.setBounds(devPts, 4);
420                 bounds.outset(SK_Scalar1, SK_Scalar1);
421                 bounds.roundOut(&ibounds);
422                 if (SkIRect::Intersects(devClipBounds, ibounds)) {
423                     PREALLOC_PTARRAY(32) q;
424                     // We convert cubics to quadratics (for now).
425                     // In perspective have to do conversion in src space.
426                     if (persp) {
427                         SkScalar tolScale =
428                             GrPathUtils::scaleToleranceToSrc(SK_Scalar1, m, path.getBounds());
429                         GrPathUtils::convertCubicToQuads(pathPts, tolScale, &q);
430                     } else {
431                         GrPathUtils::convertCubicToQuads(devPts, SK_Scalar1, &q);
432                     }
433                     for (int i = 0; i < q.count(); i += 3) {
434                         if (persp) {
435                             addSrcChoppedQuad(&q[i], !verbsInContour && 0 == i);
436                         } else {
437                             addChoppedQuad(nullptr, &q[i], !verbsInContour && 0 == i);
438                         }
439                     }
440                 }
441                 verbsInContour++;
442                 break;
443             }
444             case SkPath::kClose_Verb:
445                 // Contour is closed, so we don't need to grow the starting line, unless it's
446                 // *just* a zero length subpath. (SVG Spec 11.4, 'stroke').
447                 if (capLength > 0) {
448                     if (seenZeroLengthVerb && verbsInContour == 1) {
449                         SkPoint* pts = lines->push_back_n(2);
450                         pts[0] = SkPoint::Make(zeroVerbPt.fX - capLength, zeroVerbPt.fY);
451                         pts[1] = SkPoint::Make(zeroVerbPt.fX + capLength, zeroVerbPt.fY);
452                     } else if (verbsInContour == 0) {
453                         // Contour was (moveTo, close). Add a line.
454                         SkPoint devPts[2];
455                         m.mapPoints(devPts, pathPts, 1);
456                         devPts[1] = devPts[0];
457                         bounds.setBounds(devPts, 2);
458                         bounds.outset(SK_Scalar1, SK_Scalar1);
459                         bounds.roundOut(&ibounds);
460                         if (SkIRect::Intersects(devClipBounds, ibounds)) {
461                             SkPoint* pts = lines->push_back_n(2);
462                             pts[0] = SkPoint::Make(devPts[0].fX - capLength, devPts[0].fY);
463                             pts[1] = SkPoint::Make(devPts[1].fX + capLength, devPts[1].fY);
464                         }
465                     }
466                 }
467                 break;
468             case SkPath::kDone_Verb:
469                 if (seenZeroLengthVerb && verbsInContour == 1 && capLength > 0) {
470                     // Path ended with a dangling (moveTo, line|quad|etc). If the final verb is
471                     // degenerate, we need to draw a line.
472                     SkPoint* pts = lines->push_back_n(2);
473                     pts[0] = SkPoint::Make(zeroVerbPt.fX - capLength, zeroVerbPt.fY);
474                     pts[1] = SkPoint::Make(zeroVerbPt.fX + capLength, zeroVerbPt.fY);
475                 }
476                 return totalQuadCount;
477         }
478     }
479 }
480 
481 struct LineVertex {
482     SkPoint fPos;
483     float fCoverage;
484 };
485 
486 struct BezierVertex {
487     SkPoint fPos;
488     union {
489         struct {
490             SkScalar fKLM[3];
491         } fConic;
492         SkVector   fQuadCoord;
493         struct {
494             SkScalar fBogus[4];
495         };
496     };
497 };
498 
499 static_assert(sizeof(BezierVertex) == 3 * sizeof(SkPoint));
500 
intersect_lines(const SkPoint & ptA,const SkVector & normA,const SkPoint & ptB,const SkVector & normB,SkPoint * result)501 void intersect_lines(const SkPoint& ptA, const SkVector& normA,
502                      const SkPoint& ptB, const SkVector& normB,
503                      SkPoint* result) {
504 
505     SkScalar lineAW = -normA.dot(ptA);
506     SkScalar lineBW = -normB.dot(ptB);
507 
508     SkScalar wInv = normA.fX * normB.fY - normA.fY * normB.fX;
509     wInv = SkScalarInvert(wInv);
510     if (!SkScalarIsFinite(wInv)) {
511         // lines are parallel, pick the point in between
512         *result = (ptA + ptB)*SK_ScalarHalf;
513         *result += normA;
514     } else {
515         result->fX = normA.fY * lineBW - lineAW * normB.fY;
516         result->fX *= wInv;
517 
518         result->fY = lineAW * normB.fX - normA.fX * lineBW;
519         result->fY *= wInv;
520     }
521 }
522 
set_uv_quad(const SkPoint qpts[3],BezierVertex verts[kQuadNumVertices])523 void set_uv_quad(const SkPoint qpts[3], BezierVertex verts[kQuadNumVertices]) {
524     // this should be in the src space, not dev coords, when we have perspective
525     GrPathUtils::QuadUVMatrix DevToUV(qpts);
526     DevToUV.apply(verts, kQuadNumVertices, sizeof(BezierVertex), sizeof(SkPoint));
527 }
528 
bloat_quad(const SkPoint qpts[3],const SkMatrix * toDevice,const SkMatrix * toSrc,BezierVertex verts[kQuadNumVertices])529 bool bloat_quad(const SkPoint qpts[3],
530                 const SkMatrix* toDevice,
531                 const SkMatrix* toSrc,
532                 BezierVertex verts[kQuadNumVertices]) {
533     SkASSERT(!toDevice == !toSrc);
534     // original quad is specified by tri a,b,c
535     SkPoint a = qpts[0];
536     SkPoint b = qpts[1];
537     SkPoint c = qpts[2];
538 
539     if (toDevice) {
540         toDevice->mapPoints(&a, 1);
541         toDevice->mapPoints(&b, 1);
542         toDevice->mapPoints(&c, 1);
543     }
544     // make a new poly where we replace a and c by a 1-pixel wide edges orthog
545     // to edges ab and bc:
546     //
547     //   before       |        after
548     //                |              b0
549     //         b      |
550     //                |
551     //                |     a0            c0
552     // a         c    |        a1       c1
553     //
554     // edges a0->b0 and b0->c0 are parallel to original edges a->b and b->c,
555     // respectively.
556     BezierVertex& a0 = verts[0];
557     BezierVertex& a1 = verts[1];
558     BezierVertex& b0 = verts[2];
559     BezierVertex& c0 = verts[3];
560     BezierVertex& c1 = verts[4];
561 
562     SkVector ab = b;
563     ab -= a;
564     SkVector ac = c;
565     ac -= a;
566     SkVector cb = b;
567     cb -= c;
568 
569     // After the transform (or due to floating point math) we might have a line,
570     // try to do something reasonable
571 
572     bool abNormalized = ab.normalize();
573     bool cbNormalized = cb.normalize();
574 
575     if (!abNormalized) {
576         if (!cbNormalized) {
577             return false;          // Quad is degenerate so we won't add it.
578         }
579 
580         ab = cb;
581     }
582 
583     if (!cbNormalized) {
584         cb = ab;
585     }
586 
587     // We should have already handled degenerates
588     SkASSERT(ab.length() > 0 && cb.length() > 0);
589 
590     SkVector abN = SkPointPriv::MakeOrthog(ab, SkPointPriv::kLeft_Side);
591     if (abN.dot(ac) > 0) {
592         abN.negate();
593     }
594 
595     SkVector cbN = SkPointPriv::MakeOrthog(cb, SkPointPriv::kLeft_Side);
596     if (cbN.dot(ac) < 0) {
597         cbN.negate();
598     }
599 
600     a0.fPos = a;
601     a0.fPos += abN;
602     a1.fPos = a;
603     a1.fPos -= abN;
604 
605     if (toDevice && SkPointPriv::LengthSqd(ac) <= SK_ScalarNearlyZero*SK_ScalarNearlyZero) {
606         c = b;
607     }
608     c0.fPos = c;
609     c0.fPos += cbN;
610     c1.fPos = c;
611     c1.fPos -= cbN;
612 
613     intersect_lines(a0.fPos, abN, c0.fPos, cbN, &b0.fPos);
614 
615     if (toSrc) {
616         SkMatrixPriv::MapPointsWithStride(*toSrc, &verts[0].fPos, sizeof(BezierVertex),
617                                           kQuadNumVertices);
618     }
619 
620     return true;
621 }
622 
623 // Equations based off of Loop-Blinn Quadratic GPU Rendering
624 // Input Parametric:
625 // P(t) = (P0*(1-t)^2 + 2*w*P1*t*(1-t) + P2*t^2) / (1-t)^2 + 2*w*t*(1-t) + t^2)
626 // Output Implicit:
627 // f(x, y, w) = f(P) = K^2 - LM
628 // K = dot(k, P), L = dot(l, P), M = dot(m, P)
629 // k, l, m are calculated in function GrPathUtils::getConicKLM
set_conic_coeffs(const SkPoint p[3],BezierVertex verts[kQuadNumVertices],const SkScalar weight)630 void set_conic_coeffs(const SkPoint p[3],
631                       BezierVertex verts[kQuadNumVertices],
632                       const SkScalar weight) {
633     SkMatrix klm;
634 
635     GrPathUtils::getConicKLM(p, weight, &klm);
636 
637     for (int i = 0; i < kQuadNumVertices; ++i) {
638         const SkPoint3 pt3 = {verts[i].fPos.x(), verts[i].fPos.y(), 1.f};
639         klm.mapHomogeneousPoints((SkPoint3* ) verts[i].fConic.fKLM, &pt3, 1);
640     }
641 }
642 
add_conics(const SkPoint p[3],const SkScalar weight,const SkMatrix * toDevice,const SkMatrix * toSrc,BezierVertex ** vert)643 void add_conics(const SkPoint p[3],
644                 const SkScalar weight,
645                 const SkMatrix* toDevice,
646                 const SkMatrix* toSrc,
647                 BezierVertex** vert) {
648     if (bloat_quad(p, toDevice, toSrc, *vert)) {
649         set_conic_coeffs(p, *vert, weight);
650         *vert += kQuadNumVertices;
651     }
652 }
653 
add_quads(const SkPoint p[3],int subdiv,const SkMatrix * toDevice,const SkMatrix * toSrc,BezierVertex ** vert)654 void add_quads(const SkPoint p[3],
655                int subdiv,
656                const SkMatrix* toDevice,
657                const SkMatrix* toSrc,
658                BezierVertex** vert) {
659     SkASSERT(subdiv >= 0);
660     // temporary vertex storage to avoid reading the vertex buffer
661     BezierVertex outVerts[kQuadNumVertices] = {};
662 
663     // storage for the chopped quad
664     // pts 0,1,2 are the first quad, and 2,3,4 the second quad
665     SkPoint choppedQuadPts[5];
666     // start off with our original curve in the second quad slot
667     memcpy(&choppedQuadPts[2], p, 3*sizeof(SkPoint));
668 
669     int stepCount = 1 << subdiv;
670     while (stepCount > 1) {
671         // The general idea is:
672         // * chop the quad using pts 2,3,4 as the input
673         // * write out verts using pts 0,1,2
674         // * now 2,3,4 is the remainder of the curve, chop again until all subdivisions are done
675         SkScalar h = 1.f / stepCount;
676         SkChopQuadAt(&choppedQuadPts[2], choppedQuadPts, h);
677 
678         if (bloat_quad(choppedQuadPts, toDevice, toSrc, outVerts)) {
679             set_uv_quad(choppedQuadPts, outVerts);
680             memcpy(*vert, outVerts, kQuadNumVertices * sizeof(BezierVertex));
681             *vert += kQuadNumVertices;
682         }
683         --stepCount;
684     }
685 
686     // finish up, write out the final quad
687     if (bloat_quad(&choppedQuadPts[2], toDevice, toSrc, outVerts)) {
688         set_uv_quad(&choppedQuadPts[2], outVerts);
689         memcpy(*vert, outVerts, kQuadNumVertices * sizeof(BezierVertex));
690         *vert += kQuadNumVertices;
691     }
692 }
693 
add_line(const SkPoint p[2],const SkMatrix * toSrc,uint8_t coverage,LineVertex ** vert)694 void add_line(const SkPoint p[2],
695               const SkMatrix* toSrc,
696               uint8_t coverage,
697               LineVertex** vert) {
698     const SkPoint& a = p[0];
699     const SkPoint& b = p[1];
700 
701     SkVector ortho, vec = b;
702     vec -= a;
703 
704     SkScalar lengthSqd = SkPointPriv::LengthSqd(vec);
705 
706     if (vec.setLength(SK_ScalarHalf)) {
707         // Create a vector orthogonal to 'vec' and of unit length
708         ortho.fX = 2.0f * vec.fY;
709         ortho.fY = -2.0f * vec.fX;
710 
711         float floatCoverage = GrNormalizeByteToFloat(coverage);
712 
713         if (lengthSqd >= 1.0f) {
714             // Relative to points a and b:
715             // The inner vertices are inset half a pixel along the line a,b
716             (*vert)[0].fPos = a + vec;
717             (*vert)[0].fCoverage = floatCoverage;
718             (*vert)[1].fPos = b - vec;
719             (*vert)[1].fCoverage = floatCoverage;
720         } else {
721             // The inner vertices are inset a distance of length(a,b) from the outer edge of
722             // geometry. For the "a" inset this is the same as insetting from b by half a pixel.
723             // The coverage is then modulated by the length. This gives us the correct
724             // coverage for rects shorter than a pixel as they get translated subpixel amounts
725             // inside of a pixel.
726             SkScalar length = SkScalarSqrt(lengthSqd);
727             (*vert)[0].fPos = b - vec;
728             (*vert)[0].fCoverage = floatCoverage * length;
729             (*vert)[1].fPos = a + vec;
730             (*vert)[1].fCoverage = floatCoverage * length;
731         }
732         // Relative to points a and b:
733         // The outer vertices are outset half a pixel along the line a,b and then a whole pixel
734         // orthogonally.
735         (*vert)[2].fPos = a - vec + ortho;
736         (*vert)[2].fCoverage = 0;
737         (*vert)[3].fPos = b + vec + ortho;
738         (*vert)[3].fCoverage = 0;
739         (*vert)[4].fPos = a - vec - ortho;
740         (*vert)[4].fCoverage = 0;
741         (*vert)[5].fPos = b + vec - ortho;
742         (*vert)[5].fCoverage = 0;
743 
744         if (toSrc) {
745             SkMatrixPriv::MapPointsWithStride(*toSrc, &(*vert)->fPos, sizeof(LineVertex),
746                                               kLineSegNumVertices);
747         }
748     } else {
749         // just make it degenerate and likely offscreen
750         for (int i = 0; i < kLineSegNumVertices; ++i) {
751             (*vert)[i].fPos.set(SK_ScalarMax, SK_ScalarMax);
752         }
753     }
754 
755     *vert += kLineSegNumVertices;
756 }
757 
758 ///////////////////////////////////////////////////////////////////////////////
759 
760 class AAHairlineOp final : public GrMeshDrawOp {
761 private:
762     using Helper = GrSimpleMeshDrawOpHelperWithStencil;
763 
764 public:
765     DEFINE_OP_CLASS_ID
766 
Make(GrRecordingContext * context,GrPaint && paint,const SkMatrix & viewMatrix,const SkPath & path,const GrStyle & style,const SkIRect & devClipBounds,const GrUserStencilSettings * stencilSettings)767     static GrOp::Owner Make(GrRecordingContext* context,
768                             GrPaint&& paint,
769                             const SkMatrix& viewMatrix,
770                             const SkPath& path,
771                             const GrStyle& style,
772                             const SkIRect& devClipBounds,
773                             const GrUserStencilSettings* stencilSettings) {
774         SkScalar hairlineCoverage;
775         uint8_t newCoverage = 0xff;
776         if (GrIsStrokeHairlineOrEquivalent(style, viewMatrix, &hairlineCoverage)) {
777             newCoverage = SkScalarRoundToInt(hairlineCoverage * 0xff);
778         }
779 
780         const SkStrokeRec& stroke = style.strokeRec();
781         SkScalar capLength = SkPaint::kButt_Cap != stroke.getCap() ? hairlineCoverage * 0.5f : 0.0f;
782 
783         return Helper::FactoryHelper<AAHairlineOp>(context, std::move(paint), newCoverage,
784                                                    viewMatrix, path,
785                                                    devClipBounds, capLength, stencilSettings);
786     }
787 
AAHairlineOp(GrProcessorSet * processorSet,const SkPMColor4f & color,uint8_t coverage,const SkMatrix & viewMatrix,const SkPath & path,SkIRect devClipBounds,SkScalar capLength,const GrUserStencilSettings * stencilSettings)788     AAHairlineOp(GrProcessorSet* processorSet,
789                  const SkPMColor4f& color,
790                  uint8_t coverage,
791                  const SkMatrix& viewMatrix,
792                  const SkPath& path,
793                  SkIRect devClipBounds,
794                  SkScalar capLength,
795                  const GrUserStencilSettings* stencilSettings)
796             : INHERITED(ClassID())
797             , fHelper(processorSet, GrAAType::kCoverage, stencilSettings)
798             , fColor(color)
799             , fCoverage(coverage) {
800         fPaths.emplace_back(PathData{viewMatrix, path, devClipBounds, capLength});
801 
802         this->setTransformedBounds(path.getBounds(), viewMatrix, HasAABloat::kYes,
803                                    IsHairline::kYes);
804     }
805 
name() const806     const char* name() const override { return "AAHairlineOp"; }
807 
visitProxies(const GrVisitProxyFunc & func) const808     void visitProxies(const GrVisitProxyFunc& func) const override {
809 
810         bool visited = false;
811         for (int i = 0; i < 3; ++i) {
812             if (fProgramInfos[i]) {
813                 fProgramInfos[i]->visitFPProxies(func);
814                 visited = true;
815             }
816         }
817 
818         if (!visited) {
819             fHelper.visitProxies(func);
820         }
821     }
822 
fixedFunctionFlags() const823     FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
824 
finalize(const GrCaps & caps,const GrAppliedClip * clip,GrClampType clampType)825     GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
826                                       GrClampType clampType) override {
827         // This Op uses uniform (not vertex) color, so doesn't need to track wide color.
828         return fHelper.finalizeProcessors(caps, clip, clampType,
829                                           GrProcessorAnalysisCoverage::kSingleChannel, &fColor,
830                                           nullptr);
831     }
832 
833     enum class Program : uint8_t {
834         kNone  = 0x0,
835         kLine  = 0x1,
836         kQuad  = 0x2,
837         kConic = 0x4,
838     };
839 
840 private:
841     void makeLineProgramInfo(const GrCaps&, SkArenaAlloc*, const GrPipeline*,
842                              const GrSurfaceProxyView& writeView,
843                              bool usesMSAASurface,
844                              const SkMatrix* geometryProcessorViewM,
845                              const SkMatrix* geometryProcessorLocalM,
846                              GrXferBarrierFlags renderPassXferBarriers,
847                              GrLoadOp colorLoadOp);
848     void makeQuadProgramInfo(const GrCaps&, SkArenaAlloc*, const GrPipeline*,
849                              const GrSurfaceProxyView& writeView,
850                              bool usesMSAASurface,
851                              const SkMatrix* geometryProcessorViewM,
852                              const SkMatrix* geometryProcessorLocalM,
853                              GrXferBarrierFlags renderPassXferBarriers,
854                              GrLoadOp colorLoadOp);
855     void makeConicProgramInfo(const GrCaps&, SkArenaAlloc*, const GrPipeline*,
856                               const GrSurfaceProxyView& writeView,
857                               bool usesMSAASurface,
858                               const SkMatrix* geometryProcessorViewM,
859                               const SkMatrix* geometryProcessorLocalM,
860                               GrXferBarrierFlags renderPassXferBarriers,
861                               GrLoadOp colorLoadOp);
862 
programInfo()863     GrProgramInfo* programInfo() override {
864         // This Op has 3 programInfos and implements its own onPrePrepareDraws so this entry point
865         // should really never be called.
866         SkASSERT(0);
867         return nullptr;
868     }
869 
870     Program predictPrograms(const GrCaps*) const;
871 
872     void onCreateProgramInfo(const GrCaps*,
873                              SkArenaAlloc*,
874                              const GrSurfaceProxyView& writeView,
875                              bool usesMSAASurface,
876                              GrAppliedClip&&,
877                              const GrDstProxyView&,
878                              GrXferBarrierFlags renderPassXferBarriers,
879                              GrLoadOp colorLoadOp) override;
880 
881     void onPrePrepareDraws(GrRecordingContext*,
882                            const GrSurfaceProxyView& writeView,
883                            GrAppliedClip*,
884                            const GrDstProxyView&,
885                            GrXferBarrierFlags renderPassXferBarriers,
886                            GrLoadOp colorLoadOp) override;
887 
888     void onPrepareDraws(GrMeshDrawTarget*) override;
889     void onExecute(GrOpFlushState*, const SkRect& chainBounds) override;
890 
onCombineIfPossible(GrOp * t,SkArenaAlloc *,const GrCaps & caps)891     CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps) override {
892         AAHairlineOp* that = t->cast<AAHairlineOp>();
893 
894         if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
895             return CombineResult::kCannotCombine;
896         }
897 
898         if (this->viewMatrix().hasPerspective() != that->viewMatrix().hasPerspective()) {
899             return CombineResult::kCannotCombine;
900         }
901 
902         // We go to identity if we don't have perspective
903         if (this->viewMatrix().hasPerspective() &&
904             !SkMatrixPriv::CheapEqual(this->viewMatrix(), that->viewMatrix())) {
905             return CombineResult::kCannotCombine;
906         }
907 
908         // TODO we can actually combine hairlines if they are the same color in a kind of bulk
909         // method but we haven't implemented this yet
910         // TODO investigate going to vertex color and coverage?
911         if (this->coverage() != that->coverage()) {
912             return CombineResult::kCannotCombine;
913         }
914 
915         if (this->color() != that->color()) {
916             return CombineResult::kCannotCombine;
917         }
918 
919         if (fHelper.usesLocalCoords() && !SkMatrixPriv::CheapEqual(this->viewMatrix(),
920                                                                    that->viewMatrix())) {
921             return CombineResult::kCannotCombine;
922         }
923 
924         fPaths.push_back_n(that->fPaths.count(), that->fPaths.begin());
925         return CombineResult::kMerged;
926     }
927 
928 #if GR_TEST_UTILS
onDumpInfo() const929     SkString onDumpInfo() const override {
930         return SkStringPrintf("Color: 0x%08x Coverage: 0x%02x, Count: %d\n%s",
931                               fColor.toBytes_RGBA(), fCoverage, fPaths.count(),
932                               fHelper.dumpInfo().c_str());
933     }
934 #endif
935 
color() const936     const SkPMColor4f& color() const { return fColor; }
coverage() const937     uint8_t coverage() const { return fCoverage; }
viewMatrix() const938     const SkMatrix& viewMatrix() const { return fPaths[0].fViewMatrix; }
939 
940     struct PathData {
941         SkMatrix fViewMatrix;
942         SkPath fPath;
943         SkIRect fDevClipBounds;
944         SkScalar fCapLength;
945     };
946 
947     SkSTArray<1, PathData, true> fPaths;
948     Helper fHelper;
949     SkPMColor4f fColor;
950     uint8_t fCoverage;
951 
952     Program        fCharacterization = Program::kNone;       // holds a mask of required programs
953     GrSimpleMesh*  fMeshes[3] = { nullptr };
954     GrProgramInfo* fProgramInfos[3] = { nullptr };
955 
956     using INHERITED = GrMeshDrawOp;
957 };
958 
GR_MAKE_BITFIELD_CLASS_OPS(AAHairlineOp::Program)959 GR_MAKE_BITFIELD_CLASS_OPS(AAHairlineOp::Program)
960 
961 void AAHairlineOp::makeLineProgramInfo(const GrCaps& caps, SkArenaAlloc* arena,
962                                        const GrPipeline* pipeline,
963                                        const GrSurfaceProxyView& writeView,
964                                        bool usesMSAASurface,
965                                        const SkMatrix* geometryProcessorViewM,
966                                        const SkMatrix* geometryProcessorLocalM,
967                                        GrXferBarrierFlags renderPassXferBarriers,
968                                        GrLoadOp colorLoadOp) {
969     if (fProgramInfos[0]) {
970         return;
971     }
972 
973     GrGeometryProcessor* lineGP;
974     {
975         using namespace GrDefaultGeoProcFactory;
976 
977         Color color(this->color());
978         LocalCoords localCoords(fHelper.usesLocalCoords() ? LocalCoords::kUsePosition_Type
979                                                           : LocalCoords::kUnused_Type);
980         localCoords.fMatrix = geometryProcessorLocalM;
981 
982         lineGP = GrDefaultGeoProcFactory::Make(arena,
983                                                color,
984                                                Coverage::kAttribute_Type,
985                                                localCoords,
986                                                *geometryProcessorViewM);
987         SkASSERT(sizeof(LineVertex) == lineGP->vertexStride());
988     }
989 
990     fProgramInfos[0] = GrSimpleMeshDrawOpHelper::CreateProgramInfo(
991             &caps, arena, pipeline, writeView, usesMSAASurface, lineGP, GrPrimitiveType::kTriangles,
992             renderPassXferBarriers, colorLoadOp, fHelper.stencilSettings());
993 }
994 
makeQuadProgramInfo(const GrCaps & caps,SkArenaAlloc * arena,const GrPipeline * pipeline,const GrSurfaceProxyView & writeView,bool usesMSAASurface,const SkMatrix * geometryProcessorViewM,const SkMatrix * geometryProcessorLocalM,GrXferBarrierFlags renderPassXferBarriers,GrLoadOp colorLoadOp)995 void AAHairlineOp::makeQuadProgramInfo(const GrCaps& caps, SkArenaAlloc* arena,
996                                        const GrPipeline* pipeline,
997                                        const GrSurfaceProxyView& writeView,
998                                        bool usesMSAASurface,
999                                        const SkMatrix* geometryProcessorViewM,
1000                                        const SkMatrix* geometryProcessorLocalM,
1001                                        GrXferBarrierFlags renderPassXferBarriers,
1002                                        GrLoadOp colorLoadOp) {
1003     if (fProgramInfos[1]) {
1004         return;
1005     }
1006 
1007     GrGeometryProcessor* quadGP = GrQuadEffect::Make(arena,
1008                                                      this->color(),
1009                                                      *geometryProcessorViewM,
1010                                                      caps,
1011                                                      *geometryProcessorLocalM,
1012                                                      fHelper.usesLocalCoords(),
1013                                                      this->coverage());
1014     SkASSERT(sizeof(BezierVertex) == quadGP->vertexStride());
1015 
1016     fProgramInfos[1] = GrSimpleMeshDrawOpHelper::CreateProgramInfo(
1017             &caps, arena, pipeline, writeView, usesMSAASurface, quadGP, GrPrimitiveType::kTriangles,
1018             renderPassXferBarriers, colorLoadOp, fHelper.stencilSettings());
1019 }
1020 
makeConicProgramInfo(const GrCaps & caps,SkArenaAlloc * arena,const GrPipeline * pipeline,const GrSurfaceProxyView & writeView,bool usesMSAASurface,const SkMatrix * geometryProcessorViewM,const SkMatrix * geometryProcessorLocalM,GrXferBarrierFlags renderPassXferBarriers,GrLoadOp colorLoadOp)1021 void AAHairlineOp::makeConicProgramInfo(const GrCaps& caps, SkArenaAlloc* arena,
1022                                         const GrPipeline* pipeline,
1023                                         const GrSurfaceProxyView& writeView,
1024                                         bool usesMSAASurface,
1025                                         const SkMatrix* geometryProcessorViewM,
1026                                         const SkMatrix* geometryProcessorLocalM,
1027                                         GrXferBarrierFlags renderPassXferBarriers,
1028                                         GrLoadOp colorLoadOp) {
1029     if (fProgramInfos[2]) {
1030         return;
1031     }
1032 
1033     GrGeometryProcessor* conicGP = GrConicEffect::Make(arena,
1034                                                        this->color(),
1035                                                        *geometryProcessorViewM,
1036                                                        caps,
1037                                                        *geometryProcessorLocalM,
1038                                                        fHelper.usesLocalCoords(),
1039                                                        this->coverage());
1040     SkASSERT(sizeof(BezierVertex) == conicGP->vertexStride());
1041 
1042     fProgramInfos[2] = GrSimpleMeshDrawOpHelper::CreateProgramInfo(
1043             &caps, arena, pipeline, writeView, usesMSAASurface, conicGP,
1044             GrPrimitiveType::kTriangles, renderPassXferBarriers, colorLoadOp,
1045             fHelper.stencilSettings());
1046 }
1047 
predictPrograms(const GrCaps * caps) const1048 AAHairlineOp::Program AAHairlineOp::predictPrograms(const GrCaps* caps) const {
1049     bool convertConicsToQuads = !caps->shaderCaps()->floatIs32Bits();
1050 
1051     // When predicting the programs we always include the lineProgram bc it is used as a fallback
1052     // for quads and conics. In non-DDL mode there are cases where it sometimes isn't needed for a
1053     // given path.
1054     Program neededPrograms = Program::kLine;
1055 
1056     for (int i = 0; i < fPaths.count(); i++) {
1057         uint32_t mask = fPaths[i].fPath.getSegmentMasks();
1058 
1059         if (mask & (SkPath::kQuad_SegmentMask | SkPath::kCubic_SegmentMask)) {
1060             neededPrograms |= Program::kQuad;
1061         }
1062         if (mask & SkPath::kConic_SegmentMask) {
1063             if (convertConicsToQuads) {
1064                 neededPrograms |= Program::kQuad;
1065             } else {
1066                 neededPrograms |= Program::kConic;
1067             }
1068         }
1069     }
1070 
1071     return neededPrograms;
1072 }
1073 
onCreateProgramInfo(const GrCaps * caps,SkArenaAlloc * arena,const GrSurfaceProxyView & writeView,bool usesMSAASurface,GrAppliedClip && appliedClip,const GrDstProxyView & dstProxyView,GrXferBarrierFlags renderPassXferBarriers,GrLoadOp colorLoadOp)1074 void AAHairlineOp::onCreateProgramInfo(const GrCaps* caps,
1075                                        SkArenaAlloc* arena,
1076                                        const GrSurfaceProxyView& writeView,
1077                                        bool usesMSAASurface,
1078                                        GrAppliedClip&& appliedClip,
1079                                        const GrDstProxyView& dstProxyView,
1080                                        GrXferBarrierFlags renderPassXferBarriers,
1081                                        GrLoadOp colorLoadOp) {
1082     // Setup the viewmatrix and localmatrix for the GrGeometryProcessor.
1083     SkMatrix invert;
1084     if (!this->viewMatrix().invert(&invert)) {
1085         return;
1086     }
1087 
1088     // we will transform to identity space if the viewmatrix does not have perspective
1089     bool hasPerspective = this->viewMatrix().hasPerspective();
1090     const SkMatrix* geometryProcessorViewM = &SkMatrix::I();
1091     const SkMatrix* geometryProcessorLocalM = &invert;
1092     if (hasPerspective) {
1093         geometryProcessorViewM = &this->viewMatrix();
1094         geometryProcessorLocalM = &SkMatrix::I();
1095     }
1096 
1097     auto pipeline = fHelper.createPipeline(caps, arena, writeView.swizzle(),
1098                                            std::move(appliedClip), dstProxyView);
1099 
1100     if (fCharacterization & Program::kLine) {
1101         this->makeLineProgramInfo(*caps, arena, pipeline, writeView, usesMSAASurface,
1102                                   geometryProcessorViewM, geometryProcessorLocalM,
1103                                   renderPassXferBarriers, colorLoadOp);
1104     }
1105     if (fCharacterization & Program::kQuad) {
1106         this->makeQuadProgramInfo(*caps, arena, pipeline, writeView, usesMSAASurface,
1107                                   geometryProcessorViewM, geometryProcessorLocalM,
1108                                   renderPassXferBarriers, colorLoadOp);
1109     }
1110     if (fCharacterization & Program::kConic) {
1111         this->makeConicProgramInfo(*caps, arena, pipeline, writeView, usesMSAASurface,
1112                                    geometryProcessorViewM, geometryProcessorLocalM,
1113                                    renderPassXferBarriers, colorLoadOp);
1114 
1115     }
1116 }
1117 
onPrePrepareDraws(GrRecordingContext * context,const GrSurfaceProxyView & writeView,GrAppliedClip * clip,const GrDstProxyView & dstProxyView,GrXferBarrierFlags renderPassXferBarriers,GrLoadOp colorLoadOp)1118 void AAHairlineOp::onPrePrepareDraws(GrRecordingContext* context,
1119                                      const GrSurfaceProxyView& writeView,
1120                                      GrAppliedClip* clip,
1121                                      const GrDstProxyView& dstProxyView,
1122                                      GrXferBarrierFlags renderPassXferBarriers,
1123                                      GrLoadOp colorLoadOp) {
1124     SkArenaAlloc* arena = context->priv().recordTimeAllocator();
1125     const GrCaps* caps = context->priv().caps();
1126 
1127     // http://skbug.com/12201 -- DDL does not yet support DMSAA.
1128     bool usesMSAASurface = writeView.asRenderTargetProxy()->numSamples() > 1;
1129 
1130     // This is equivalent to a GrOpFlushState::detachAppliedClip
1131     GrAppliedClip appliedClip = clip ? std::move(*clip) : GrAppliedClip::Disabled();
1132 
1133     // Conservatively predict which programs will be required
1134     fCharacterization = this->predictPrograms(caps);
1135 
1136     this->createProgramInfo(caps, arena, writeView, usesMSAASurface, std::move(appliedClip),
1137                             dstProxyView, renderPassXferBarriers, colorLoadOp);
1138 
1139     context->priv().recordProgramInfo(fProgramInfos[0]);
1140     context->priv().recordProgramInfo(fProgramInfos[1]);
1141     context->priv().recordProgramInfo(fProgramInfos[2]);
1142 }
1143 
onPrepareDraws(GrMeshDrawTarget * target)1144 void AAHairlineOp::onPrepareDraws(GrMeshDrawTarget* target) {
1145     // Setup the viewmatrix and localmatrix for the GrGeometryProcessor.
1146     SkMatrix invert;
1147     if (!this->viewMatrix().invert(&invert)) {
1148         return;
1149     }
1150 
1151     // we will transform to identity space if the viewmatrix does not have perspective
1152     const SkMatrix* toDevice = nullptr;
1153     const SkMatrix* toSrc = nullptr;
1154     if (this->viewMatrix().hasPerspective()) {
1155         toDevice = &this->viewMatrix();
1156         toSrc = &invert;
1157     }
1158 
1159     SkDEBUGCODE(Program predictedPrograms = this->predictPrograms(&target->caps()));
1160     Program actualPrograms = Program::kNone;
1161 
1162     // This is hand inlined for maximum performance.
1163     PREALLOC_PTARRAY(128) lines;
1164     PREALLOC_PTARRAY(128) quads;
1165     PREALLOC_PTARRAY(128) conics;
1166     IntArray qSubdivs;
1167     FloatArray cWeights;
1168     int quadCount = 0;
1169 
1170     int instanceCount = fPaths.count();
1171     bool convertConicsToQuads = !target->caps().shaderCaps()->floatIs32Bits();
1172     for (int i = 0; i < instanceCount; i++) {
1173         const PathData& args = fPaths[i];
1174         quadCount += gather_lines_and_quads(args.fPath, args.fViewMatrix, args.fDevClipBounds,
1175                                             args.fCapLength, convertConicsToQuads, &lines, &quads,
1176                                             &conics, &qSubdivs, &cWeights);
1177     }
1178 
1179     int lineCount = lines.count() / 2;
1180     int conicCount = conics.count() / 3;
1181     int quadAndConicCount = conicCount + quadCount;
1182 
1183     static constexpr int kMaxLines = SK_MaxS32 / kLineSegNumVertices;
1184     static constexpr int kMaxQuadsAndConics = SK_MaxS32 / kQuadNumVertices;
1185     if (lineCount > kMaxLines || quadAndConicCount > kMaxQuadsAndConics) {
1186         return;
1187     }
1188 
1189     // do lines first
1190     if (lineCount) {
1191         SkASSERT(predictedPrograms & Program::kLine);
1192         actualPrograms |= Program::kLine;
1193 
1194         sk_sp<const GrBuffer> linesIndexBuffer = get_lines_index_buffer(target->resourceProvider());
1195 
1196         GrMeshDrawOp::PatternHelper helper(target, GrPrimitiveType::kTriangles, sizeof(LineVertex),
1197                                            std::move(linesIndexBuffer), kLineSegNumVertices,
1198                                            kIdxsPerLineSeg, lineCount, kLineSegsNumInIdxBuffer);
1199 
1200         LineVertex* verts = reinterpret_cast<LineVertex*>(helper.vertices());
1201         if (!verts) {
1202             SkDebugf("Could not allocate vertices\n");
1203             return;
1204         }
1205 
1206         for (int i = 0; i < lineCount; ++i) {
1207             add_line(&lines[2*i], toSrc, this->coverage(), &verts);
1208         }
1209 
1210         fMeshes[0] = helper.mesh();
1211     }
1212 
1213     if (quadCount || conicCount) {
1214         sk_sp<const GrBuffer> vertexBuffer;
1215         int firstVertex;
1216 
1217         sk_sp<const GrBuffer> quadsIndexBuffer = get_quads_index_buffer(target->resourceProvider());
1218 
1219         int vertexCount = kQuadNumVertices * quadAndConicCount;
1220         void* vertices = target->makeVertexSpace(sizeof(BezierVertex), vertexCount, &vertexBuffer,
1221                                                  &firstVertex);
1222 
1223         if (!vertices || !quadsIndexBuffer) {
1224             SkDebugf("Could not allocate vertices\n");
1225             return;
1226         }
1227 
1228         // Setup vertices
1229         BezierVertex* bezVerts = reinterpret_cast<BezierVertex*>(vertices);
1230 
1231         int unsubdivQuadCnt = quads.count() / 3;
1232         for (int i = 0; i < unsubdivQuadCnt; ++i) {
1233             SkASSERT(qSubdivs[i] >= 0);
1234             if (!quads[3*i].isFinite() || !quads[3*i+1].isFinite() || !quads[3*i+2].isFinite()) {
1235                 return;
1236             }
1237             add_quads(&quads[3*i], qSubdivs[i], toDevice, toSrc, &bezVerts);
1238         }
1239 
1240         // Start Conics
1241         for (int i = 0; i < conicCount; ++i) {
1242             add_conics(&conics[3*i], cWeights[i], toDevice, toSrc, &bezVerts);
1243         }
1244 
1245         if (quadCount > 0) {
1246             SkASSERT(predictedPrograms & Program::kQuad);
1247             actualPrograms |= Program::kQuad;
1248 
1249             fMeshes[1] = target->allocMesh();
1250             fMeshes[1]->setIndexedPatterned(quadsIndexBuffer, kIdxsPerQuad, quadCount,
1251                                             kQuadsNumInIdxBuffer, vertexBuffer, kQuadNumVertices,
1252                                             firstVertex);
1253             firstVertex += quadCount * kQuadNumVertices;
1254         }
1255 
1256         if (conicCount > 0) {
1257             SkASSERT(predictedPrograms & Program::kConic);
1258             actualPrograms |= Program::kConic;
1259 
1260             fMeshes[2] = target->allocMesh();
1261             fMeshes[2]->setIndexedPatterned(std::move(quadsIndexBuffer), kIdxsPerQuad, conicCount,
1262                                             kQuadsNumInIdxBuffer, std::move(vertexBuffer),
1263                                             kQuadNumVertices, firstVertex);
1264         }
1265     }
1266 
1267     // In DDL mode this will replace the predicted program requirements with the actual ones.
1268     // However, we will already have surfaced the predicted programs to the DDL.
1269     fCharacterization = actualPrograms;
1270 }
1271 
onExecute(GrOpFlushState * flushState,const SkRect & chainBounds)1272 void AAHairlineOp::onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) {
1273     this->createProgramInfo(flushState);
1274 
1275     for (int i = 0; i < 3; ++i) {
1276         if (fProgramInfos[i] && fMeshes[i]) {
1277             flushState->bindPipelineAndScissorClip(*fProgramInfos[i], chainBounds);
1278             flushState->bindTextures(fProgramInfos[i]->geomProc(), nullptr,
1279                                      fProgramInfos[i]->pipeline());
1280             flushState->drawMesh(*fMeshes[i]);
1281         }
1282     }
1283 }
1284 
1285 } // anonymous namespace
1286 
1287 ///////////////////////////////////////////////////////////////////////////////////////////////////
1288 
1289 #if GR_TEST_UTILS
1290 
GR_DRAW_OP_TEST_DEFINE(AAHairlineOp)1291 GR_DRAW_OP_TEST_DEFINE(AAHairlineOp) {
1292     SkMatrix viewMatrix = GrTest::TestMatrix(random);
1293     const SkPath& path = GrTest::TestPath(random);
1294     SkIRect devClipBounds;
1295     devClipBounds.setEmpty();
1296     return AAHairlineOp::Make(context, std::move(paint), viewMatrix, path,
1297                               GrStyle::SimpleHairline(), devClipBounds,
1298                               GrGetRandomStencil(random, context));
1299 }
1300 
1301 #endif
1302 
1303 ///////////////////////////////////////////////////////////////////////////////////////////////////
1304 
1305 namespace skgpu::v1 {
1306 
onCanDrawPath(const CanDrawPathArgs & args) const1307 PathRenderer::CanDrawPath AAHairLinePathRenderer::onCanDrawPath(const CanDrawPathArgs& args) const {
1308     if (GrAAType::kCoverage != args.fAAType) {
1309         return CanDrawPath::kNo;
1310     }
1311 
1312     if (!GrIsStrokeHairlineOrEquivalent(args.fShape->style(), *args.fViewMatrix, nullptr)) {
1313         return CanDrawPath::kNo;
1314     }
1315 
1316     // We don't currently handle dashing in this class though perhaps we should.
1317     if (args.fShape->style().pathEffect()) {
1318         return CanDrawPath::kNo;
1319     }
1320 
1321     if (SkPath::kLine_SegmentMask == args.fShape->segmentMask() ||
1322         args.fCaps->shaderCaps()->shaderDerivativeSupport()) {
1323         return CanDrawPath::kYes;
1324     }
1325 
1326     return CanDrawPath::kNo;
1327 }
1328 
1329 
onDrawPath(const DrawPathArgs & args)1330 bool AAHairLinePathRenderer::onDrawPath(const DrawPathArgs& args) {
1331     GR_AUDIT_TRAIL_AUTO_FRAME(args.fContext->priv().auditTrail(),
1332                               "AAHairlinePathRenderer::onDrawPath");
1333     SkASSERT(args.fSurfaceDrawContext->numSamples() <= 1);
1334 
1335     SkPath path;
1336     args.fShape->asPath(&path);
1337     GrOp::Owner op =
1338             AAHairlineOp::Make(args.fContext, std::move(args.fPaint), *args.fViewMatrix, path,
1339                                args.fShape->style(), *args.fClipConservativeBounds,
1340                                args.fUserStencilSettings);
1341     args.fSurfaceDrawContext->addDrawOp(args.fClip, std::move(op));
1342     return true;
1343 }
1344 
1345 } // namespace skgpu::v1
1346 
1347