Debian Codegraph @

src/gpu/ganesh/ops/AAConvexPathRenderer.cpp

raw
1 /*
2 * Copyright 2012 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/AAConvexPathRenderer.h"
8
9 #include "include/core/SkMatrix.h"
10 #include "include/core/SkPath.h"
11 #include "include/core/SkPoint.h"
12 #include "include/core/SkRefCnt.h"
13 #include "include/core/SkScalar.h"
14 #include "include/core/SkString.h"
15 #include "include/core/SkTypes.h"
16 #include "include/gpu/ganesh/GrRecordingContext.h"
17 #include "include/private/base/SkDebug.h"
18 #include "include/private/base/SkFloatingPoint.h"
19 #include "include/private/base/SkMath.h"
20 #include "include/private/base/SkTArray.h"
21 #include "include/private/base/SkTDArray.h"
22 #include "include/private/gpu/ganesh/GrTypesPriv.h"
23 #include "src/base/SkArenaAlloc.h"
24 #include "src/core/SkColorData.h"
25 #include "src/core/SkGeometry.h"
26 #include "src/core/SkMatrixPriv.h"
27 #include "src/core/SkPathEnums.h"
28 #include "src/core/SkPathPriv.h"
29 #include "src/core/SkPointPriv.h"
30 #include "src/core/SkSLTypeShared.h"
31 #include "src/gpu/BufferWriter.h"
32 #include "src/gpu/KeyBuilder.h"
33 #include "src/gpu/ganesh/GrAppliedClip.h"
34 #include "src/gpu/ganesh/GrAuditTrail.h"
35 #include "src/gpu/ganesh/GrBuffer.h"
36 #include "src/gpu/ganesh/GrCaps.h"
37 #include "src/gpu/ganesh/GrDrawOpTest.h"
38 #include "src/gpu/ganesh/GrGeometryProcessor.h"
39 #include "src/gpu/ganesh/GrMeshDrawTarget.h"
40 #include "src/gpu/ganesh/GrOpFlushState.h"
41 #include "src/gpu/ganesh/GrPaint.h"
42 #include "src/gpu/ganesh/GrProcessorAnalysis.h"
43 #include "src/gpu/ganesh/GrProcessorSet.h"
44 #include "src/gpu/ganesh/GrProcessorUnitTest.h"
45 #include "src/gpu/ganesh/GrProgramInfo.h"
46 #include "src/gpu/ganesh/GrRecordingContextPriv.h"
47 #include "src/gpu/ganesh/GrShaderCaps.h"
48 #include "src/gpu/ganesh/GrSimpleMesh.h"
49 #include "src/gpu/ganesh/GrStyle.h"
50 #include "src/gpu/ganesh/SurfaceDrawContext.h"
51 #include "src/gpu/ganesh/geometry/GrPathUtils.h"
52 #include "src/gpu/ganesh/geometry/GrStyledShape.h"
53 #include "src/gpu/ganesh/glsl/GrGLSLFragmentShaderBuilder.h"
54 #include "src/gpu/ganesh/glsl/GrGLSLVarying.h"
55 #include "src/gpu/ganesh/glsl/GrGLSLVertexGeoBuilder.h"
56 #include "src/gpu/ganesh/ops/GrMeshDrawOp.h"
57 #include "src/gpu/ganesh/ops/GrOp.h"
58 #include "src/gpu/ganesh/ops/GrSimpleMeshDrawOpHelperWithStencil.h"
59
60 #if defined(GPU_TEST_UTILS)
61 #include "src/base/SkRandom.h"
62 #include "src/gpu/ganesh/GrTestUtils.h"
63 #endif
64
65 #include <cstddef>
66 #include <cstdint>
67 #include <memory>
68 #include <utility>
69
70 class GrDstProxyView;
71 class GrGLSLProgramDataManager;
72 class GrGLSLUniformHandler;
73 class GrSurfaceProxyView;
74 enum class GrXferBarrierFlags;
75 struct GrUserStencilSettings;
76 struct SkRect;
77
78 using namespace skia_private;
79
80 namespace skgpu::ganesh {
81
82 namespace {
83
84 struct Segment {
85 enum {
86 kLine = 0,
87 kQuad = 1,
88 } fType;
89 // These enum values are assumed in member functions below.
90 static_assert(0 == kLine && 1 == kQuad);
91
92 // line uses one pt, quad uses 2 pts
93 SkPoint fPts[2];
94 // normal to edge ending at each pt
95 SkVector fNorms[2];
96 // is the corner where the previous segment meets this segment
97 // sharp. If so, fMid is a normalized bisector facing outward.
98 SkVector fMid;
99
100 int countPoints() const {
101 SkASSERT(fType == kLine || fType == kQuad);
102 return fType + 1;
103 }
104 const SkPoint& endPt() const {
105 SkASSERT(fType == kLine || fType == kQuad);
106 return fPts[fType];
107 }
108 const SkPoint& endNorm() const {
109 SkASSERT(fType == kLine || fType == kQuad);
110 return fNorms[fType];
111 }
112 };
113
114 typedef TArray<Segment, true> SegmentArray;
115
116 bool center_of_mass(const SegmentArray& segments, SkPoint* c) {
117 SkScalar area = 0;
118 SkPoint center = {0, 0};
119 int count = segments.size();
120 if (count <= 0) {
121 return false;
122 }
123 SkPoint p0 = {0, 0};
124 if (count > 2) {
125 // We translate the polygon so that the first point is at the origin.
126 // This avoids some precision issues with small area polygons far away
127 // from the origin.
128 p0 = segments[0].endPt();
129 SkPoint pi;
130 SkPoint pj;
131 // the first and last iteration of the below loop would compute
132 // zeros since the starting / ending point is (0,0). So instead we start
133 // at i=1 and make the last iteration i=count-2.
134 pj = segments[1].endPt() - p0;
135 for (int i = 1; i < count - 1; ++i) {
136 pi = pj;
137 pj = segments[i + 1].endPt() - p0;
138
139 SkScalar t = SkPoint::CrossProduct(pi, pj);
140 area += t;
141 center.fX += (pi.fX + pj.fX) * t;
142 center.fY += (pi.fY + pj.fY) * t;
143 }
144 }
145
146 // If the poly has no area then we instead return the average of
147 // its points.
148 if (SkScalarNearlyZero(area)) {
149 SkPoint avg;
150 avg.set(0, 0);
151 for (int i = 0; i < count; ++i) {
152 const SkPoint& pt = segments[i].endPt();
153 avg.fX += pt.fX;
154 avg.fY += pt.fY;
155 }
156 SkScalar denom = SK_Scalar1 / count;
157 avg.scale(denom);
158 *c = avg;
159 } else {
160 area *= 3;
161 area = SkScalarInvert(area);
162 center.scale(area);
163 // undo the translate of p0 to the origin.
164 *c = center + p0;
165 }
166 return !SkIsNaN(c->fX) && !SkIsNaN(c->fY) && c->isFinite();
167 }
168
169 bool compute_vectors(SegmentArray* segments,
170 SkPoint* fanPt,
171 SkPathFirstDirection dir,
172 int* vCount,
173 int* iCount) {
174 if (!center_of_mass(*segments, fanPt)) {
175 return false;
176 }
177 int count = segments->size();
178
179 // Make the normals point towards the outside
180 SkPointPriv::Side normSide;
181 if (dir == SkPathFirstDirection::kCCW) {
182 normSide = SkPointPriv::kRight_Side;
183 } else {
184 normSide = SkPointPriv::kLeft_Side;
185 }
186
187 int64_t vCount64 = 0;
188 int64_t iCount64 = 0;
189 // compute normals at all points
190 for (int a = 0; a < count; ++a) {
191 Segment& sega = (*segments)[a];
192 int b = (a + 1) % count;
193 Segment& segb = (*segments)[b];
194
195 const SkPoint* prevPt = &sega.endPt();
196 int n = segb.countPoints();
197 for (int p = 0; p < n; ++p) {
198 segb.fNorms[p] = segb.fPts[p] - *prevPt;
199 segb.fNorms[p].normalize();
200 segb.fNorms[p] = SkPointPriv::MakeOrthog(segb.fNorms[p], normSide);
201 prevPt = &segb.fPts[p];
202 }
203 if (Segment::kLine == segb.fType) {
204 vCount64 += 5;
205 iCount64 += 9;
206 } else {
207 vCount64 += 6;
208 iCount64 += 12;
209 }
210 }
211
212 // compute mid-vectors where segments meet. TODO: Detect shallow corners
213 // and leave out the wedges and close gaps by stitching segments together.
214 for (int a = 0; a < count; ++a) {
215 const Segment& sega = (*segments)[a];
216 int b = (a + 1) % count;
217 Segment& segb = (*segments)[b];
218 segb.fMid = segb.fNorms[0] + sega.endNorm();
219 segb.fMid.normalize();
220 // corner wedges
221 vCount64 += 4;
222 iCount64 += 6;
223 }
224 if (vCount64 > SK_MaxS32 || iCount64 > SK_MaxS32) {
225 return false;
226 }
227 *vCount = vCount64;
228 *iCount = iCount64;
229 return true;
230 }
231
232 struct DegenerateTestData {
233 bool isDegenerate() const { return Stage::kNonDegenerate != fStage; }
234 enum class Stage {
235 kInitial,
236 kPoint,
237 kLine,
238 kNonDegenerate,
239 };
240 Stage fStage = Stage::kInitial;
241 SkPoint fFirstPoint;
242 SkVector fLineNormal;
243 SkScalar fLineC;
244 };
245
246 static const SkScalar kClose = (SK_Scalar1 / 16);
247 static const SkScalar kCloseSqd = kClose * kClose;
248
249 void update_degenerate_test(DegenerateTestData* data, const SkPoint& pt) {
250 switch (data->fStage) {
251 case DegenerateTestData::Stage::kInitial:
252 data->fFirstPoint = pt;
253 data->fStage = DegenerateTestData::Stage::kPoint;
254 break;
255 case DegenerateTestData::Stage::kPoint:
256 if (SkPointPriv::DistanceToSqd(pt, data->fFirstPoint) > kCloseSqd) {
257 data->fLineNormal = pt - data->fFirstPoint;
258 data->fLineNormal.normalize();
259 data->fLineNormal = SkPointPriv::MakeOrthog(data->fLineNormal);
260 data->fLineC = -data->fLineNormal.dot(data->fFirstPoint);
261 data->fStage = DegenerateTestData::Stage::kLine;
262 }
263 break;
264 case DegenerateTestData::Stage::kLine:
265 if (SkScalarAbs(data->fLineNormal.dot(pt) + data->fLineC) > kClose) {
266 data->fStage = DegenerateTestData::Stage::kNonDegenerate;
267 }
268 break;
269 case DegenerateTestData::Stage::kNonDegenerate:
270 break;
271 default:
272 SK_ABORT("Unexpected degenerate test stage.");
273 }
274 }
275
276 inline bool get_direction(const SkPath& path, const SkMatrix& m, SkPathFirstDirection* dir) {
277 // At this point, we've already returned true from canDraw(), which checked that the path's
278 // direction could be determined, so this should just be fetching the cached direction.
279 // However, if perspective is involved, we're operating on a transformed path, which may no
280 // longer have a computable direction.
281 *dir = SkPathPriv::ComputeFirstDirection(path);
282 if (*dir == SkPathFirstDirection::kUnknown) {
283 return false;
284 }
285
286 // check whether m reverses the orientation
287 SkASSERT(!m.hasPerspective());
288 SkScalar det2x2 = m.get(SkMatrix::kMScaleX) * m.get(SkMatrix::kMScaleY) -
289 m.get(SkMatrix::kMSkewX) * m.get(SkMatrix::kMSkewY);
290 if (det2x2 < 0) {
291 *dir = SkPathPriv::OppositeFirstDirection(*dir);
292 }
293
294 return true;
295 }
296
297 inline void add_line_to_segment(const SkPoint& pt, SegmentArray* segments) {
298 segments->push_back();
299 segments->back().fType = Segment::kLine;
300 segments->back().fPts[0] = pt;
301 }
302
303 inline void add_quad_segment(const SkPoint pts[3], SegmentArray* segments) {
304 if (SkPointPriv::DistanceToLineSegmentBetweenSqd(pts[1], pts[0], pts[2]) < kCloseSqd) {
305 if (pts[0] != pts[2]) {
306 add_line_to_segment(pts[2], segments);
307 }
308 } else {
309 segments->push_back();
310 segments->back().fType = Segment::kQuad;
311 segments->back().fPts[0] = pts[1];
312 segments->back().fPts[1] = pts[2];
313 }
314 }
315
316 inline void add_cubic_segments(const SkPoint pts[4],
317 SkPathFirstDirection dir,
318 SegmentArray* segments) {
319 STArray<15, SkPoint, true> quads;
320 GrPathUtils::convertCubicToQuadsConstrainToTangents(pts, SK_Scalar1, dir, &quads);
321 int count = quads.size();
322 for (int q = 0; q < count; q += 3) {
323 add_quad_segment(&quads[q], segments);
324 }
325 }
326
327 bool get_segments(const SkPath& path,
328 const SkMatrix& m,
329 SegmentArray* segments,
330 SkPoint* fanPt,
331 int* vCount,
332 int* iCount) {
333 // This renderer over-emphasizes very thin path regions. We use the distance
334 // to the path from the sample to compute coverage. Every pixel intersected
335 // by the path will be hit and the maximum distance is sqrt(2)/2. We don't
336 // notice that the sample may be close to a very thin area of the path and
337 // thus should be very light. This is particularly egregious for degenerate
338 // line paths. We detect paths that are very close to a line (zero area) and
339 // draw nothing.
340 DegenerateTestData degenerateData;
341 SkPathFirstDirection dir;
342 if (!get_direction(path, m, &dir)) {
343 return false;
344 }
345
346 SkPath::Iter iter(path, true);
347 while (auto rec = iter.next()) {
348 SkSpan<const SkPoint> src = rec->fPoints;
349 switch (rec->fVerb) {
350 case SkPathVerb::kMove:
351 update_degenerate_test(&degenerateData, m.mapPoint(src[0]));
352 break;
353 case SkPathVerb::kLine: {
354 if (!SkPathPriv::AllPointsEq(src)) {
355 SkPoint dst = m.mapPoint(src[1]);
356 update_degenerate_test(&degenerateData, dst);
357 add_line_to_segment(dst, segments);
358 }
359 break;
360 }
361 case SkPathVerb::kQuad:
362 if (!SkPathPriv::AllPointsEq(src)) {
363 SkPoint dst[3];
364 m.mapPoints(dst, src);
365 update_degenerate_test(&degenerateData, dst[1]);
366 update_degenerate_test(&degenerateData, dst[2]);
367 add_quad_segment(dst, segments);
368 }
369 break;
370 case SkPathVerb::kConic: {
371 if (!SkPathPriv::AllPointsEq(src)) {
372 SkPoint dst[3];
373 m.mapPoints(dst, src);
374 SkAutoConicToQuads converter;
375 const SkPoint* quadPts = converter.computeQuads(dst, rec->conicWeight(), 0.25f);
376 for (int i = 0; i < converter.countQuads(); ++i) {
377 update_degenerate_test(&degenerateData, quadPts[2*i + 1]);
378 update_degenerate_test(&degenerateData, quadPts[2*i + 2]);
379 add_quad_segment(quadPts + 2*i, segments);
380 }
381 }
382 break;
383 }
384 case SkPathVerb::kCubic: {
385 if (!SkPathPriv::AllPointsEq(src)) {
386 SkPoint dst[4];
387 m.mapPoints(dst, src);
388 update_degenerate_test(&degenerateData, dst[1]);
389 update_degenerate_test(&degenerateData, dst[2]);
390 update_degenerate_test(&degenerateData, dst[3]);
391 add_cubic_segments(dst, dir, segments);
392 }
393 break;
394 }
395 case SkPathVerb::kClose:
396 break;
397 }
398 }
399
400 if (degenerateData.isDegenerate()) {
401 return false;
402 } else {
403 return compute_vectors(segments, fanPt, dir, vCount, iCount);
404 }
405 }
406
407 struct Draw {
408 Draw() : fVertexCnt(0), fIndexCnt(0) {}
409 int fVertexCnt;
410 int fIndexCnt;
411 };
412
413 typedef TArray<Draw, true> DrawArray;
414
415 void create_vertices(const SegmentArray& segments,
416 const SkPoint& fanPt,
417 const VertexColor& color,
418 DrawArray* draws,
419 VertexWriter& verts,
420 uint16_t* idxs,
421 size_t vertexStride) {
422 Draw* draw = &draws->push_back();
423 // alias just to make vert/index assignments easier to read.
424 int* v = &draw->fVertexCnt;
425 int* i = &draw->fIndexCnt;
426
427 int count = segments.size();
428 for (int a = 0; a < count; ++a) {
429 const Segment& sega = segments[a];
430 int b = (a + 1) % count;
431 const Segment& segb = segments[b];
432
433 // Check whether adding the verts for this segment to the current draw would cause index
434 // values to overflow.
435 int vCount = 4;
436 if (Segment::kLine == segb.fType) {
437 vCount += 5;
438 } else {
439 vCount += 6;
440 }
441 if (draw->fVertexCnt + vCount > (1 << 16)) {
442 idxs += *i;
443 draw = &draws->push_back();
444 v = &draw->fVertexCnt;
445 i = &draw->fIndexCnt;
446 }
447
448 const SkScalar negOneDists[2] = { -SK_Scalar1, -SK_Scalar1 };
449
450 // FIXME: These tris are inset in the 1 unit arc around the corner
451 SkPoint p0 = sega.endPt();
452 // Position, Color, UV, D0, D1
453 verts << p0 << color << SkPoint{0, 0} << negOneDists;
454 verts << (p0 + sega.endNorm()) << color << SkPoint{0, -SK_Scalar1} << negOneDists;
455 verts << (p0 + segb.fMid) << color << SkPoint{0, -SK_Scalar1} << negOneDists;
456 verts << (p0 + segb.fNorms[0]) << color << SkPoint{0, -SK_Scalar1} << negOneDists;
457
458 idxs[*i + 0] = *v + 0;
459 idxs[*i + 1] = *v + 2;
460 idxs[*i + 2] = *v + 1;
461 idxs[*i + 3] = *v + 0;
462 idxs[*i + 4] = *v + 3;
463 idxs[*i + 5] = *v + 2;
464
465 *v += 4;
466 *i += 6;
467
468 if (Segment::kLine == segb.fType) {
469 // we draw the line edge as a degenerate quad (u is 0, v is the
470 // signed distance to the edge)
471 SkPoint v1Pos = sega.endPt();
472 SkPoint v2Pos = segb.fPts[0];
473 SkScalar dist = SkPointPriv::DistanceToLineBetween(fanPt, v1Pos, v2Pos);
474
475 verts << fanPt << color << SkPoint{0, dist} << negOneDists;
476 verts << v1Pos << color << SkPoint{0, 0} << negOneDists;
477 verts << v2Pos << color << SkPoint{0, 0} << negOneDists;
478 verts << (v1Pos + segb.fNorms[0]) << color << SkPoint{0, -SK_Scalar1} << negOneDists;
479 verts << (v2Pos + segb.fNorms[0]) << color << SkPoint{0, -SK_Scalar1} << negOneDists;
480
481 idxs[*i + 0] = *v + 3;
482 idxs[*i + 1] = *v + 1;
483 idxs[*i + 2] = *v + 2;
484
485 idxs[*i + 3] = *v + 4;
486 idxs[*i + 4] = *v + 3;
487 idxs[*i + 5] = *v + 2;
488
489 *i += 6;
490
491 // Draw the interior fan if it exists.
492 // TODO: Detect and combine colinear segments. This will ensure we catch every case
493 // with no interior, and that the resulting shared edge uses the same endpoints.
494 if (count >= 3) {
495 idxs[*i + 0] = *v + 0;
496 idxs[*i + 1] = *v + 2;
497 idxs[*i + 2] = *v + 1;
498
499 *i += 3;
500 }
501
502 *v += 5;
503 } else {
504 SkPoint qpts[] = {sega.endPt(), segb.fPts[0], segb.fPts[1]};
505
506 SkScalar c0 = segb.fNorms[0].dot(qpts[0]);
507 SkScalar c1 = segb.fNorms[1].dot(qpts[2]);
508
509 // We must transform the positions into UV in cpu memory and then copy them to the gpu
510 // buffer. If we write the position first into the gpu buffer then calculate the UVs, it
511 // will cause us to read from the GPU buffer which can be very slow.
512 struct PosAndUV {
513 SkPoint fPos;
514 SkPoint fUV;
515 };
516 PosAndUV posAndUVPoints[6];
517 posAndUVPoints[0].fPos = fanPt;
518 posAndUVPoints[1].fPos = qpts[0];
519 posAndUVPoints[2].fPos = qpts[2];
520 posAndUVPoints[3].fPos = qpts[0] + segb.fNorms[0];
521 posAndUVPoints[4].fPos = qpts[2] + segb.fNorms[1];
522 SkVector midVec = segb.fNorms[0] + segb.fNorms[1];
523 midVec.normalize();
524 posAndUVPoints[5].fPos = qpts[1] + midVec;
525
526 GrPathUtils::QuadUVMatrix toUV(qpts);
527 toUV.apply(posAndUVPoints, 6, sizeof(PosAndUV), sizeof(SkPoint));
528
529 verts << posAndUVPoints[0].fPos << color << posAndUVPoints[0].fUV
530 << (-segb.fNorms[0].dot(fanPt) + c0)
531 << (-segb.fNorms[1].dot(fanPt) + c1);
532
533 verts << posAndUVPoints[1].fPos << color << posAndUVPoints[1].fUV
534 << 0.0f
535 << (-segb.fNorms[1].dot(qpts[0]) + c1);
536
537 verts << posAndUVPoints[2].fPos << color << posAndUVPoints[2].fUV
538 << (-segb.fNorms[0].dot(qpts[2]) + c0)
539 << 0.0f;
540 // We need a negative value that is very large that it won't effect results if it is
541 // interpolated with. However, the value can't be too large of a negative that it
542 // effects numerical precision on less powerful GPUs.
543 static const SkScalar kStableLargeNegativeValue = -SK_ScalarMax/1000000;
544 verts << posAndUVPoints[3].fPos << color << posAndUVPoints[3].fUV
545 << kStableLargeNegativeValue
546 << kStableLargeNegativeValue;
547
548 verts << posAndUVPoints[4].fPos << color << posAndUVPoints[4].fUV
549 << kStableLargeNegativeValue
550 << kStableLargeNegativeValue;
551
552 verts << posAndUVPoints[5].fPos << color << posAndUVPoints[5].fUV
553 << kStableLargeNegativeValue
554 << kStableLargeNegativeValue;
555
556 idxs[*i + 0] = *v + 3;
557 idxs[*i + 1] = *v + 1;
558 idxs[*i + 2] = *v + 2;
559 idxs[*i + 3] = *v + 4;
560 idxs[*i + 4] = *v + 3;
561 idxs[*i + 5] = *v + 2;
562
563 idxs[*i + 6] = *v + 5;
564 idxs[*i + 7] = *v + 3;
565 idxs[*i + 8] = *v + 4;
566
567 *i += 9;
568
569 // Draw the interior fan if it exists.
570 // TODO: Detect and combine colinear segments. This will ensure we catch every case
571 // with no interior, and that the resulting shared edge uses the same endpoints.
572 if (count >= 3) {
573 idxs[*i + 0] = *v + 0;
574 idxs[*i + 1] = *v + 2;
575 idxs[*i + 2] = *v + 1;
576
577 *i += 3;
578 }
579
580 *v += 6;
581 }
582 }
583 }
584
585 ///////////////////////////////////////////////////////////////////////////////
586
587 /*
588 * Quadratic specified by 0=u^2-v canonical coords. u and v are the first
589 * two components of the vertex attribute. Coverage is based on signed
590 * distance with negative being inside, positive outside. The edge is specified in
591 * window space (y-down). If either the third or fourth component of the interpolated
592 * vertex coord is > 0 then the pixel is considered outside the edge. This is used to
593 * attempt to trim to a portion of the infinite quad.
594 * Requires shader derivative instruction support.
595 */
596
597 class QuadEdgeEffect : public GrGeometryProcessor {
598 public:
599 static GrGeometryProcessor* Make(SkArenaAlloc* arena,
600 const SkMatrix& localMatrix,
601 bool usesLocalCoords,
602 bool wideColor) {
603 return arena->make([&](void* ptr) {
604 return new (ptr) QuadEdgeEffect(localMatrix, usesLocalCoords, wideColor);
605 });
606 }
607
608 ~QuadEdgeEffect() override {}
609
610 const char* name() const override { return "QuadEdge"; }
611
612 void addToKey(const GrShaderCaps& caps, KeyBuilder* b) const override {
613 b->addBool(fUsesLocalCoords, "usesLocalCoords");
614 b->addBits(ProgramImpl::kMatrixKeyBits,
615 ProgramImpl::ComputeMatrixKey(caps, fLocalMatrix),
616 "localMatrixType");
617 }
618
619 std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const override;
620
621 private:
622 QuadEdgeEffect(const SkMatrix& localMatrix, bool usesLocalCoords, bool wideColor)
623 : INHERITED(kQuadEdgeEffect_ClassID)
624 , fLocalMatrix(localMatrix)
625 , fUsesLocalCoords(usesLocalCoords) {
626 fInPosition = {"inPosition", kFloat2_GrVertexAttribType, SkSLType::kFloat2};
627 fInColor = MakeColorAttribute("inColor", wideColor);
628 // GL on iOS 14 needs more precision for the quadedge attributes
629 fInQuadEdge = {"inQuadEdge", kFloat4_GrVertexAttribType, SkSLType::kFloat4};
630 this->setVertexAttributesWithImplicitOffsets(&fInPosition, 3);
631 }
632
633 Attribute fInPosition;
634 Attribute fInColor;
635 Attribute fInQuadEdge;
636
637 SkMatrix fLocalMatrix;
638 bool fUsesLocalCoords;
639
640 GR_DECLARE_GEOMETRY_PROCESSOR_TEST
641
642 using INHERITED = GrGeometryProcessor;
643 };
644
645 std::unique_ptr<GrGeometryProcessor::ProgramImpl> QuadEdgeEffect::makeProgramImpl(
646 const GrShaderCaps&) const {
647 class Impl : public ProgramImpl {
648 public:
649 void setData(const GrGLSLProgramDataManager& pdman,
650 const GrShaderCaps& shaderCaps,
651 const GrGeometryProcessor& geomProc) override {
652 const QuadEdgeEffect& qe = geomProc.cast<QuadEdgeEffect>();
653 SetTransform(pdman, shaderCaps, fLocalMatrixUniform, qe.fLocalMatrix, &fLocalMatrix);
654 }
655
656 private:
657 void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override {
658 const QuadEdgeEffect& qe = args.fGeomProc.cast<QuadEdgeEffect>();
659 GrGLSLVertexBuilder* vertBuilder = args.fVertBuilder;
660 GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
661 GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
662 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
663
664 // emit attributes
665 varyingHandler->emitAttributes(qe);
666
667 // GL on iOS 14 needs more precision for the quadedge attributes
668 // We might as well enable it everywhere
669 GrGLSLVarying v(SkSLType::kFloat4);
670 varyingHandler->addVarying("QuadEdge", &v);
671 vertBuilder->codeAppendf("%s = %s;", v.vsOut(), qe.fInQuadEdge.name());
672
673 // Setup pass through color
674 fragBuilder->codeAppendf("half4 %s;", args.fOutputColor);
675 varyingHandler->addPassThroughAttribute(qe.fInColor.asShaderVar(), args.fOutputColor);
676
677 // Setup position
678 WriteOutputPosition(vertBuilder, gpArgs, qe.fInPosition.name());
679 if (qe.fUsesLocalCoords) {
680 WriteLocalCoord(vertBuilder,
681 uniformHandler,
682 *args.fShaderCaps,
683 gpArgs,
684 qe.fInPosition.asShaderVar(),
685 qe.fLocalMatrix,
686 &fLocalMatrixUniform);
687 }
688
689 fragBuilder->codeAppendf("half edgeAlpha;");
690
691 // keep the derivative instructions outside the conditional
692 fragBuilder->codeAppendf("half2 duvdx = half2(dFdx(%s.xy));", v.fsIn());
693 fragBuilder->codeAppendf("half2 duvdy = half2(dFdy(%s.xy));", v.fsIn());
694 fragBuilder->codeAppendf("if (%s.z > 0.0 && %s.w > 0.0) {", v.fsIn(), v.fsIn());
695 // today we know z and w are in device space. We could use derivatives
696 fragBuilder->codeAppendf("edgeAlpha = half(min(min(%s.z, %s.w) + 0.5, 1.0));", v.fsIn(),
697 v.fsIn());
698 fragBuilder->codeAppendf ("} else {");
699 fragBuilder->codeAppendf("half2 gF = half2(half(2.0*%s.x*duvdx.x - duvdx.y),"
700 " half(2.0*%s.x*duvdy.x - duvdy.y));",
701 v.fsIn(), v.fsIn());
702 fragBuilder->codeAppendf("edgeAlpha = half(%s.x*%s.x - %s.y);", v.fsIn(), v.fsIn(),
703 v.fsIn());
704 fragBuilder->codeAppendf("edgeAlpha = "
705 "saturate(0.5 - edgeAlpha / max(length(gF), 1e-6));}");
706
707 fragBuilder->codeAppendf("half4 %s = half4(edgeAlpha);", args.fOutputCoverage);
708 }
709
710 private:
711 SkMatrix fLocalMatrix = SkMatrix::InvalidMatrix();
712
713 UniformHandle fLocalMatrixUniform;
714 };
715
716 return std::make_unique<Impl>();
717 }
718
719 GR_DEFINE_GEOMETRY_PROCESSOR_TEST(QuadEdgeEffect)
720
721 #if defined(GPU_TEST_UTILS)
722 GrGeometryProcessor* QuadEdgeEffect::TestCreate(GrProcessorTestData* d) {
723 SkMatrix localMatrix = GrTest::TestMatrix(d->fRandom);
724 bool usesLocalCoords = d->fRandom->nextBool();
725 bool wideColor = d->fRandom->nextBool();
726 // Doesn't work without derivative instructions.
727 return d->caps()->shaderCaps()->fShaderDerivativeSupport
728 ? QuadEdgeEffect::Make(d->allocator(), localMatrix, usesLocalCoords, wideColor)
729 : nullptr;
730 }
731 #endif
732
733 class AAConvexPathOp final : public GrMeshDrawOp {
734 private:
735 using Helper = GrSimpleMeshDrawOpHelperWithStencil;
736
737 public:
738 DEFINE_OP_CLASS_ID
739
740 static GrOp::Owner Make(GrRecordingContext* context,
741 GrPaint&& paint,
742 const SkMatrix& viewMatrix,
743 const SkPath& path,
744 const GrUserStencilSettings* stencilSettings) {
745 return Helper::FactoryHelper<AAConvexPathOp>(context, std::move(paint), viewMatrix, path,
746 stencilSettings);
747 }
748
749 AAConvexPathOp(GrProcessorSet* processorSet, const SkPMColor4f& color,
750 const SkMatrix& viewMatrix, const SkPath& path,
751 const GrUserStencilSettings* stencilSettings)
752 : INHERITED(ClassID()), fHelper(processorSet, GrAAType::kCoverage, stencilSettings) {
753 fPaths.emplace_back(PathData{viewMatrix, path, color});
754 this->setTransformedBounds(path.getBounds(), viewMatrix, HasAABloat::kYes,
755 IsHairline::kNo);
756 }
757
758 const char* name() const override { return "AAConvexPathOp"; }
759
760 void visitProxies(const GrVisitProxyFunc& func) const override {
761 if (fProgramInfo) {
762 fProgramInfo->visitFPProxies(func);
763 } else {
764 fHelper.visitProxies(func);
765 }
766 }
767
768 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
769
770 GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
771 GrClampType clampType) override {
772 return fHelper.finalizeProcessors(
773 caps, clip, clampType, GrProcessorAnalysisCoverage::kSingleChannel,
774 &fPaths.back().fColor, &fWideColor);
775 }
776
777 private:
778 GrProgramInfo* programInfo() override { return fProgramInfo; }
779
780 void onCreateProgramInfo(const GrCaps* caps,
781 SkArenaAlloc* arena,
782 const GrSurfaceProxyView& writeView,
783 bool usesMSAASurface,
784 GrAppliedClip&& appliedClip,
785 const GrDstProxyView& dstProxyView,
786 GrXferBarrierFlags renderPassXferBarriers,
787 GrLoadOp colorLoadOp) override {
788 SkMatrix invert;
789 if (fHelper.usesLocalCoords()) {
790 if (auto inv = fPaths.back().fViewMatrix.invert()) {
791 invert = *inv;
792 } else {
793 return;
794 }
795 }
796
797 GrGeometryProcessor* quadProcessor = QuadEdgeEffect::Make(arena, invert,
798 fHelper.usesLocalCoords(),
799 fWideColor);
800
801 fProgramInfo = fHelper.createProgramInfoWithStencil(caps, arena, writeView, usesMSAASurface,
802 std::move(appliedClip),
803 dstProxyView, quadProcessor,
804 GrPrimitiveType::kTriangles,
805 renderPassXferBarriers, colorLoadOp);
806 }
807
808 void onPrepareDraws(GrMeshDrawTarget* target) override {
809 int instanceCount = fPaths.size();
810
811 if (!fProgramInfo) {
812 this->createProgramInfo(target);
813 if (!fProgramInfo) {
814 return;
815 }
816 }
817
818 const size_t kVertexStride = fProgramInfo->geomProc().vertexStride();
819
820 fDraws.reserve(instanceCount);
821
822 // TODO generate all segments for all paths and use one vertex buffer
823 for (int i = 0; i < instanceCount; i++) {
824 const PathData& args = fPaths[i];
825
826 // We use the fact that SkPath::transform path does subdivision based on
827 // perspective. Otherwise, we apply the view matrix when copying to the
828 // segment representation.
829 const SkMatrix* viewMatrix = &args.fViewMatrix;
830
831 // We avoid initializing the path unless we have to
832 const SkPath* pathPtr = &args.fPath;
833 std::optional<SkPath> tmpPath;
834 if (viewMatrix->hasPerspective()) {
835 tmpPath.emplace(pathPtr->makeTransform(*viewMatrix));
836 tmpPath->setIsVolatile(true);
837 pathPtr = &tmpPath.value();
838 viewMatrix = &SkMatrix::I();
839 }
840
841 int vertexCount;
842 int indexCount;
843 static constexpr size_t kPreallocSegmentCnt = 512 / sizeof(Segment);
844 static constexpr size_t kPreallocDrawCnt = 4;
845
846 STArray<kPreallocSegmentCnt, Segment, true> segments;
847 SkPoint fanPt;
848
849 if (!get_segments(*pathPtr, *viewMatrix, &segments, &fanPt, &vertexCount,
850 &indexCount)) {
851 continue;
852 }
853
854 sk_sp<const GrBuffer> vertexBuffer;
855 int firstVertex;
856
857 VertexWriter verts = target->makeVertexWriter(kVertexStride,
858 vertexCount,
859 &vertexBuffer,
860 &firstVertex);
861
862 if (!verts) SK_UNLIKELY {
863 SkDebugf("Could not allocate vertices\n");
864 return;
865 }
866
867 sk_sp<const GrBuffer> indexBuffer;
868 int firstIndex;
869
870 uint16_t *idxs = target->makeIndexSpace(indexCount, &indexBuffer, &firstIndex);
871 if (!idxs) SK_UNLIKELY {
872 SkDebugf("Could not allocate indices\n");
873 return;
874 }
875
876 STArray<kPreallocDrawCnt, Draw, true> draws;
877 VertexColor color(args.fColor, fWideColor);
878 create_vertices(segments, fanPt, color, &draws, verts, idxs, kVertexStride);
879
880 GrSimpleMesh* meshes = target->allocMeshes(draws.size());
881 for (int j = 0; j < draws.size(); ++j) {
882 const Draw& draw = draws[j];
883 meshes[j].setIndexed(indexBuffer, draw.fIndexCnt, firstIndex, 0,
884 draw.fVertexCnt - 1, GrPrimitiveRestart::kNo, vertexBuffer,
885 firstVertex);
886 firstIndex += draw.fIndexCnt;
887 firstVertex += draw.fVertexCnt;
888 }
889
890 fDraws.push_back({ meshes, draws.size() });
891 }
892 }
893
894 void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
895 if (!fProgramInfo || fDraws.empty()) {
896 return;
897 }
898
899 flushState->bindPipelineAndScissorClip(*fProgramInfo, chainBounds);
900 flushState->bindTextures(fProgramInfo->geomProc(), nullptr, fProgramInfo->pipeline());
901 for (int i = 0; i < fDraws.size(); ++i) {
902 for (int j = 0; j < fDraws[i].fMeshCount; ++j) {
903 flushState->drawMesh(fDraws[i].fMeshes[j]);
904 }
905 }
906 }
907
908 CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps) override {
909 AAConvexPathOp* that = t->cast<AAConvexPathOp>();
910 if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
911 return CombineResult::kCannotCombine;
912 }
913 if (fHelper.usesLocalCoords() &&
914 !SkMatrixPriv::CheapEqual(fPaths[0].fViewMatrix, that->fPaths[0].fViewMatrix)) {
915 return CombineResult::kCannotCombine;
916 }
917
918 fPaths.push_back_n(that->fPaths.size(), that->fPaths.begin());
919 fWideColor |= that->fWideColor;
920 return CombineResult::kMerged;
921 }
922
923 #if defined(GPU_TEST_UTILS)
924 SkString onDumpInfo() const override {
925 return SkStringPrintf("Count: %d\n%s", fPaths.size(), fHelper.dumpInfo().c_str());
926 }
927 #endif
928
929 struct PathData {
930 SkMatrix fViewMatrix;
931 SkPath fPath;
932 SkPMColor4f fColor;
933 };
934
935 Helper fHelper;
936 STArray<1, PathData, true> fPaths;
937 bool fWideColor;
938
939 struct MeshDraw {
940 GrSimpleMesh* fMeshes;
941 int fMeshCount;
942 };
943
944 SkTDArray<MeshDraw> fDraws;
945 GrProgramInfo* fProgramInfo = nullptr;
946
947 using INHERITED = GrMeshDrawOp;
948 };
949
950 } // anonymous namespace
951
952 ///////////////////////////////////////////////////////////////////////////////
953
954 PathRenderer::CanDrawPath AAConvexPathRenderer::onCanDrawPath(const CanDrawPathArgs& args) const {
955 // This check requires convexity and known direction, since the direction is used to build
956 // the geometry segments. Degenerate convex paths will fall through to some other path renderer.
957 if (args.fCaps->shaderCaps()->fShaderDerivativeSupport &&
958 (GrAAType::kCoverage == args.fAAType) && args.fShape->style().isSimpleFill() &&
959 !args.fShape->inverseFilled() && args.fShape->knownToBeConvex() &&
960 args.fShape->knownDirection()) {
961 return CanDrawPath::kYes;
962 }
963 return CanDrawPath::kNo;
964 }
965
966 bool AAConvexPathRenderer::onDrawPath(const DrawPathArgs& args) {
967 GR_AUDIT_TRAIL_AUTO_FRAME(args.fContext->priv().auditTrail(),
968 "AAConvexPathRenderer::onDrawPath");
969 SkASSERT(args.fSurfaceDrawContext->numSamples() <= 1);
970 SkASSERT(!args.fShape->isEmpty());
971
972 SkPath path = args.fShape->asPath();
973
974 GrOp::Owner op = AAConvexPathOp::Make(args.fContext, std::move(args.fPaint),
975 *args.fViewMatrix,
976 path, args.fUserStencilSettings);
977 args.fSurfaceDrawContext->addDrawOp(args.fClip, std::move(op));
978 return true;
979 }
980
981 } // namespace skgpu::ganesh
982
983 #if defined(GPU_TEST_UTILS)
984
985 GR_DRAW_OP_TEST_DEFINE(AAConvexPathOp) {
986 SkMatrix viewMatrix = GrTest::TestMatrixInvertible(random);
987 const SkPath& path = GrTest::TestPathConvex(random);
988 const GrUserStencilSettings* stencilSettings = GrGetRandomStencil(random, context);
989 return skgpu::ganesh::AAConvexPathOp::Make(
990 context, std::move(paint), viewMatrix, path, stencilSettings);
991 }
992
993 #endif