Debian Codegraph @

src/gpu/ganesh/ops/AAHairLinePathRenderer.cpp

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