Debian Codegraph @

src/gpu/ganesh/ops/StrokeRectOp.cpp

raw
1 /*
2 * Copyright 2018 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/StrokeRectOp.h"
8
9 #include "include/core/SkMatrix.h"
10 #include "include/core/SkPaint.h"
11 #include "include/core/SkRect.h"
12 #include "include/core/SkRefCnt.h"
13 #include "include/core/SkScalar.h"
14 #include "include/core/SkString.h"
15 #include "include/core/SkStrokeRec.h"
16 #include "include/gpu/ganesh/GrRecordingContext.h"
17 #include "include/private/base/SkAlignedStorage.h"
18 #include "include/private/base/SkAssert.h"
19 #include "include/private/base/SkDebug.h"
20 #include "include/private/base/SkOnce.h"
21 #include "include/private/base/SkPoint_impl.h"
22 #include "include/private/base/SkTArray.h"
23 #include "include/private/gpu/ganesh/GrTypesPriv.h"
24 #include "src/base/SkRandom.h"
25 #include "src/core/SkColorData.h"
26 #include "src/core/SkMatrixPriv.h"
27 #include "src/gpu/BufferWriter.h"
28 #include "src/gpu/ResourceKey.h"
29 #include "src/gpu/ganesh/GrAppliedClip.h"
30 #include "src/gpu/ganesh/GrBuffer.h"
31 #include "src/gpu/ganesh/GrCaps.h"
32 #include "src/gpu/ganesh/GrDefaultGeoProcFactory.h"
33 #include "src/gpu/ganesh/GrDrawOpTest.h"
34 #include "src/gpu/ganesh/GrGeometryProcessor.h"
35 #include "src/gpu/ganesh/GrMeshDrawTarget.h"
36 #include "src/gpu/ganesh/GrOpFlushState.h"
37 #include "src/gpu/ganesh/GrPaint.h"
38 #include "src/gpu/ganesh/GrProcessorAnalysis.h"
39 #include "src/gpu/ganesh/GrProcessorSet.h"
40 #include "src/gpu/ganesh/GrProgramInfo.h"
41 #include "src/gpu/ganesh/GrRecordingContextPriv.h"
42 #include "src/gpu/ganesh/GrResourceProvider.h"
43 #include "src/gpu/ganesh/GrSimpleMesh.h"
44 #include "src/gpu/ganesh/GrTestUtils.h"
45 #include "src/gpu/ganesh/geometry/GrQuad.h"
46 #include "src/gpu/ganesh/ops/FillRectOp.h"
47 #include "src/gpu/ganesh/ops/GrMeshDrawOp.h"
48 #include "src/gpu/ganesh/ops/GrSimpleMeshDrawOpHelper.h"
49
50 #include <algorithm>
51 #include <array>
52 #include <cstddef>
53 #include <cstdint>
54 #include <utility>
55
56 class GrDstProxyView;
57 class GrGpuBuffer;
58 class GrSurfaceProxyView;
59 class SkArenaAlloc;
60 enum class GrXferBarrierFlags;
61
62 namespace skgpu::ganesh {
63 class SurfaceDrawContext;
64 }
65
66 using namespace skia_private;
67
68 namespace skgpu::ganesh::StrokeRectOp {
69
70 namespace {
71
72 // This emits line primitives for hairlines, so only support hairlines if allowed by caps. Otherwise
73 // we support all hairlines, bevels, and miters, but not round joins. Also, check whether the miter
74 // limit makes a miter join effectively beveled. If the miter is effectively beveled, it is only
75 // supported when using an AA stroke.
76 inline bool allowed_stroke(const GrCaps* caps, const SkStrokeRec& stroke, GrAA aa, bool* isMiter) {
77 SkASSERT(stroke.getStyle() == SkStrokeRec::kStroke_Style ||
78 stroke.getStyle() == SkStrokeRec::kHairline_Style);
79 if (caps->avoidLineDraws() && stroke.isHairlineStyle()) {
80 return false;
81 }
82 // For hairlines, make bevel and round joins appear the same as mitered ones.
83 if (!stroke.getWidth()) {
84 *isMiter = true;
85 return true;
86 }
87 if (stroke.getJoin() == SkPaint::kBevel_Join) {
88 *isMiter = false;
89 return aa == GrAA::kYes; // bevel only supported with AA
90 }
91 if (stroke.getJoin() == SkPaint::kMiter_Join) {
92 *isMiter = stroke.getMiter() >= SK_ScalarSqrt2;
93 // Supported under non-AA only if it remains mitered
94 return aa == GrAA::kYes || *isMiter;
95 }
96 return false;
97 }
98
99
100 ///////////////////////////////////////////////////////////////////////////////////////////////////
101 // Non-AA Stroking
102 ///////////////////////////////////////////////////////////////////////////////////////////////////
103
104 /* create a triangle strip that strokes the specified rect. There are 8
105 unique vertices, but we repeat the last 2 to close up. Alternatively we
106 could use an indices array, and then only send 8 verts, but not sure that
107 would be faster.
108 */
109 void init_nonaa_stroke_rect_strip(SkPoint verts[10], const SkRect& rect, SkScalar width) {
110 const SkScalar rad = SkScalarHalf(width);
111
112 verts[0].set(rect.fLeft + rad, rect.fTop + rad);
113 verts[1].set(rect.fLeft - rad, rect.fTop - rad);
114 verts[2].set(rect.fRight - rad, rect.fTop + rad);
115 verts[3].set(rect.fRight + rad, rect.fTop - rad);
116 verts[4].set(rect.fRight - rad, rect.fBottom - rad);
117 verts[5].set(rect.fRight + rad, rect.fBottom + rad);
118 verts[6].set(rect.fLeft + rad, rect.fBottom - rad);
119 verts[7].set(rect.fLeft - rad, rect.fBottom + rad);
120 verts[8] = verts[0];
121 verts[9] = verts[1];
122
123 // TODO: we should be catching this higher up the call stack and just draw a single
124 // non-AA rect
125 if (2*rad >= rect.width()) {
126 verts[0].fX = verts[2].fX = verts[4].fX = verts[6].fX = verts[8].fX = rect.centerX();
127 }
128 if (2*rad >= rect.height()) {
129 verts[0].fY = verts[2].fY = verts[4].fY = verts[6].fY = verts[8].fY = rect.centerY();
130 }
131 }
132
133 class NonAAStrokeRectOp final : public GrMeshDrawOp {
134 private:
135 using Helper = GrSimpleMeshDrawOpHelper;
136
137 public:
138 DEFINE_OP_CLASS_ID
139
140 const char* name() const override { return "NonAAStrokeRectOp"; }
141
142 void visitProxies(const GrVisitProxyFunc& func) const override {
143 if (fProgramInfo) {
144 fProgramInfo->visitFPProxies(func);
145 } else {
146 fHelper.visitProxies(func);
147 }
148 }
149
150 static GrOp::Owner Make(GrRecordingContext* context,
151 GrPaint&& paint,
152 const SkMatrix& viewMatrix,
153 const SkRect& rect,
154 const SkStrokeRec& stroke,
155 GrAAType aaType) {
156 bool isMiter;
157 if (!allowed_stroke(context->priv().caps(), stroke, GrAA::kNo, &isMiter)) {
158 return nullptr;
159 }
160 Helper::InputFlags inputFlags = Helper::InputFlags::kNone;
161 // Depending on sub-pixel coordinates and the particular GPU, we may lose a corner of
162 // hairline rects. We jam all the vertices to pixel centers to avoid this, but not
163 // when MSAA is enabled because it can cause ugly artifacts.
164 if (stroke.getStyle() == SkStrokeRec::kHairline_Style && aaType != GrAAType::kMSAA) {
165 inputFlags |= Helper::InputFlags::kSnapVerticesToPixelCenters;
166 }
167 return Helper::FactoryHelper<NonAAStrokeRectOp>(context, std::move(paint), inputFlags,
168 viewMatrix, rect,
169 stroke, aaType);
170 }
171
172 NonAAStrokeRectOp(GrProcessorSet* processorSet, const SkPMColor4f& color,
173 Helper::InputFlags inputFlags, const SkMatrix& viewMatrix, const SkRect& rect,
174 const SkStrokeRec& stroke, GrAAType aaType)
175 : INHERITED(ClassID())
176 , fHelper(processorSet, aaType, inputFlags) {
177 fColor = color;
178 fViewMatrix = viewMatrix;
179 fRect = rect;
180 // Sort the rect for hairlines
181 fRect.sort();
182 fStrokeWidth = stroke.getWidth();
183
184 SkScalar rad = SkScalarHalf(fStrokeWidth);
185 SkRect bounds = rect;
186 bounds.outset(rad, rad);
187
188 // If our caller snaps to pixel centers then we have to round out the bounds
189 if (inputFlags & Helper::InputFlags::kSnapVerticesToPixelCenters) {
190 SkASSERT(!fStrokeWidth || aaType == GrAAType::kNone);
191 viewMatrix.mapRect(&bounds);
192 // We want to be consistent with how we snap non-aa lines. To match what we do in
193 // GrGLSLVertexShaderBuilder, we first floor all the vertex values and then add half a
194 // pixel to force us to pixel centers.
195 bounds.setLTRB(SkScalarFloorToScalar(bounds.fLeft),
196 SkScalarFloorToScalar(bounds.fTop),
197 SkScalarFloorToScalar(bounds.fRight),
198 SkScalarFloorToScalar(bounds.fBottom));
199 bounds.offset(0.5f, 0.5f);
200 this->setBounds(bounds, HasAABloat::kNo, IsHairline::kNo);
201 } else {
202 HasAABloat aaBloat = (aaType == GrAAType::kNone) ? HasAABloat ::kNo : HasAABloat::kYes;
203 this->setTransformedBounds(bounds, fViewMatrix, aaBloat,
204 fStrokeWidth ? IsHairline::kNo : IsHairline::kYes);
205 }
206 }
207
208 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
209
210 GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
211 GrClampType clampType) override {
212 // This Op uses uniform (not vertex) color, so doesn't need to track wide color.
213 return fHelper.finalizeProcessors(caps, clip, clampType, GrProcessorAnalysisCoverage::kNone,
214 &fColor, nullptr);
215 }
216
217 private:
218 GrProgramInfo* programInfo() override { return fProgramInfo; }
219
220 void onCreateProgramInfo(const GrCaps* caps,
221 SkArenaAlloc* arena,
222 const GrSurfaceProxyView& writeView,
223 bool usesMSAASurface,
224 GrAppliedClip&& clip,
225 const GrDstProxyView& dstProxyView,
226 GrXferBarrierFlags renderPassXferBarriers,
227 GrLoadOp colorLoadOp) override {
228 GrGeometryProcessor* gp;
229 {
230 using namespace GrDefaultGeoProcFactory;
231 Color color(fColor);
232 LocalCoords::Type localCoordsType = fHelper.usesLocalCoords()
233 ? LocalCoords::kUsePosition_Type
234 : LocalCoords::kUnused_Type;
235 gp = GrDefaultGeoProcFactory::Make(arena, color, Coverage::kSolid_Type, localCoordsType,
236 fViewMatrix);
237 }
238
239 GrPrimitiveType primType = (fStrokeWidth > 0) ? GrPrimitiveType::kTriangleStrip
240 : GrPrimitiveType::kLineStrip;
241
242 fProgramInfo = fHelper.createProgramInfo(caps, arena, writeView, usesMSAASurface,
243 std::move(clip), dstProxyView, gp, primType,
244 renderPassXferBarriers, colorLoadOp);
245 }
246
247 void onPrepareDraws(GrMeshDrawTarget* target) override {
248 if (!fProgramInfo) {
249 this->createProgramInfo(target);
250 }
251
252 size_t kVertexStride = fProgramInfo->geomProc().vertexStride();
253 int vertexCount = kVertsPerHairlineRect;
254 if (fStrokeWidth > 0) {
255 vertexCount = kVertsPerStrokeRect;
256 }
257
258 sk_sp<const GrBuffer> vertexBuffer;
259 int firstVertex;
260
261 void* verts =
262 target->makeVertexSpace(kVertexStride, vertexCount, &vertexBuffer, &firstVertex);
263
264 if (!verts) {
265 SkDebugf("Could not allocate vertices\n");
266 return;
267 }
268
269 SkPoint* vertex = reinterpret_cast<SkPoint*>(verts);
270
271 if (fStrokeWidth > 0) {
272 init_nonaa_stroke_rect_strip(vertex, fRect, fStrokeWidth);
273 } else {
274 // hairline
275 vertex[0].set(fRect.fLeft, fRect.fTop);
276 vertex[1].set(fRect.fRight, fRect.fTop);
277 vertex[2].set(fRect.fRight, fRect.fBottom);
278 vertex[3].set(fRect.fLeft, fRect.fBottom);
279 vertex[4].set(fRect.fLeft, fRect.fTop);
280 }
281
282 fMesh = target->allocMesh();
283 fMesh->set(std::move(vertexBuffer), vertexCount, firstVertex);
284 }
285
286 void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
287 if (!fMesh) {
288 return;
289 }
290
291 flushState->bindPipelineAndScissorClip(*fProgramInfo, chainBounds);
292 flushState->bindTextures(fProgramInfo->geomProc(), nullptr, fProgramInfo->pipeline());
293 flushState->drawMesh(*fMesh);
294 }
295
296 #if defined(GPU_TEST_UTILS)
297 SkString onDumpInfo() const override {
298 return SkStringPrintf("Color: 0x%08x, Rect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], "
299 "StrokeWidth: %.2f\n%s",
300 fColor.toBytes_RGBA(), fRect.fLeft, fRect.fTop, fRect.fRight,
301 fRect.fBottom, fStrokeWidth, fHelper.dumpInfo().c_str());
302 }
303 #endif
304
305 // TODO: override onCombineIfPossible
306
307 Helper fHelper;
308 SkPMColor4f fColor;
309 SkMatrix fViewMatrix;
310 SkRect fRect;
311 SkScalar fStrokeWidth;
312 GrSimpleMesh* fMesh = nullptr;
313 GrProgramInfo* fProgramInfo = nullptr;
314
315 const static int kVertsPerHairlineRect = 5;
316 const static int kVertsPerStrokeRect = 10;
317
318 using INHERITED = GrMeshDrawOp;
319 };
320
321 ///////////////////////////////////////////////////////////////////////////////////////////////////
322 // AA Stroking
323 ///////////////////////////////////////////////////////////////////////////////////////////////////
324
325 SKGPU_DECLARE_STATIC_UNIQUE_KEY(gMiterIndexBufferKey);
326 SKGPU_DECLARE_STATIC_UNIQUE_KEY(gBevelIndexBufferKey);
327
328 bool stroke_dev_half_size_supported(SkVector devHalfStrokeSize) {
329 // Since the horizontal and vertical strokes share internal corners, the coverage value at that
330 // corner needs to be equal for the horizontal and vertical strokes both.
331 //
332 // The inner coverage values will be equal if the horizontal and vertical stroke widths are
333 // equal (in which case innerCoverage is same for all sides of the rects) or if the horizontal
334 // and vertical stroke widths are both greater than 1 (in which case innerCoverage will always
335 // be 1). In actuality we allow them to be nearly-equal since differing by < 1/1000 will not be
336 // visually detectable when the shape is already less than 1px in thickness.
337 return SkScalarNearlyEqual(devHalfStrokeSize.fX, devHalfStrokeSize.fY) ||
338 std::min(devHalfStrokeSize.fX, devHalfStrokeSize.fY) >= .5f;
339 }
340
341 bool compute_aa_rects(const GrCaps& caps,
342 SkRect* devOutside,
343 SkRect* devOutsideAssist,
344 SkRect* devInside,
345 bool* isDegenerate,
346 const SkMatrix& viewMatrix,
347 const SkRect& rect,
348 SkScalar strokeWidth,
349 bool miterStroke,
350 SkVector* devHalfStrokeSize) {
351 SkVector devStrokeSize;
352 if (strokeWidth > 0) {
353 devStrokeSize = viewMatrix.mapVector({strokeWidth, strokeWidth});
354 devStrokeSize.setAbs(devStrokeSize);
355 } else {
356 devStrokeSize.set(SK_Scalar1, SK_Scalar1);
357 }
358
359 const SkScalar dx = devStrokeSize.fX;
360 const SkScalar dy = devStrokeSize.fY;
361 const SkScalar rx = SkScalarHalf(dx);
362 const SkScalar ry = SkScalarHalf(dy);
363
364 devHalfStrokeSize->fX = rx;
365 devHalfStrokeSize->fY = ry;
366
367 SkRect devRect;
368 viewMatrix.mapRect(&devRect, rect);
369
370 // Clip our draw rect 1 full stroke width plus bloat outside the viewport. This avoids
371 // interpolation precision issues with very large coordinates.
372 const float m = caps.maxRenderTargetSize();
373 const SkRect visibilityBounds = SkRect::MakeWH(m, m).makeOutset(dx + 1, dy + 1);
374 if (!devRect.intersect(visibilityBounds)) {
375 return false;
376 }
377
378 *devOutside = devRect;
379 *devOutsideAssist = devRect;
380 *devInside = devRect;
381
382 devOutside->outset(rx, ry);
383 devInside->inset(rx, ry);
384
385 // If we have a degenerate stroking rect(ie the stroke is larger than inner rect) then we
386 // make a degenerate inside rect to avoid double hitting. We will also jam all of the points
387 // together when we render these rects.
388 SkScalar spare;
389 {
390 SkScalar w = devRect.width() - dx;
391 SkScalar h = devRect.height() - dy;
392 spare = std::min(w, h);
393 }
394
395 *isDegenerate = spare <= 0;
396 if (*isDegenerate) {
397 devInside->fLeft = devInside->fRight = devRect.centerX();
398 devInside->fTop = devInside->fBottom = devRect.centerY();
399 }
400
401 // For bevel-stroke, use 2 SkRect instances(devOutside and devOutsideAssist)
402 // to draw the outside of the octagon. Because there are 8 vertices on the outer
403 // edge, while vertex number of inner edge is 4, the same as miter-stroke.
404 if (!miterStroke) {
405 devOutside->inset(0, ry);
406 devOutsideAssist->outset(0, ry);
407 }
408
409 return true;
410 }
411
412 GrGeometryProcessor* create_aa_stroke_rect_gp(SkArenaAlloc* arena,
413 bool usesMSAASurface,
414 bool tweakAlphaForCoverage,
415 const SkMatrix& viewMatrix,
416 bool usesLocalCoords,
417 bool wideColor) {
418 using namespace GrDefaultGeoProcFactory;
419
420 // When MSAA is enabled, we have to extend our AA bloats and interpolate coverage values outside
421 // 0..1. We tell the gp in this case that coverage is an unclamped attribute so it will call
422 // saturate(coverage) in the fragment shader.
423 Coverage::Type coverageType = usesMSAASurface ? Coverage::kAttributeUnclamped_Type
424 : (!tweakAlphaForCoverage ? Coverage::kAttribute_Type
425 : Coverage::kSolid_Type);
426 LocalCoords::Type localCoordsType =
427 usesLocalCoords ? LocalCoords::kUsePosition_Type : LocalCoords::kUnused_Type;
428 Color::Type colorType =
429 wideColor ? Color::kPremulWideColorAttribute_Type: Color::kPremulGrColorAttribute_Type;
430
431 return MakeForDeviceSpace(arena, colorType, coverageType, localCoordsType, viewMatrix);
432 }
433
434 class AAStrokeRectOp final : public GrMeshDrawOp {
435 private:
436 using Helper = GrSimpleMeshDrawOpHelper;
437
438 public:
439 DEFINE_OP_CLASS_ID
440
441 // TODO support AA rotated stroke rects by copying around view matrices
442 struct RectInfo {
443 SkPMColor4f fColor;
444 SkRect fDevOutside;
445 SkRect fDevOutsideAssist;
446 SkRect fDevInside;
447 SkVector fDevHalfStrokeSize;
448 bool fDegenerate;
449 };
450
451 static GrOp::Owner Make(GrRecordingContext* context,
452 GrPaint&& paint,
453 const SkMatrix& viewMatrix,
454 const SkRect& devOutside,
455 const SkRect& devInside,
456 const SkVector& devHalfStrokeSize) {
457 if (!viewMatrix.rectStaysRect()) {
458 // The AA op only supports axis-aligned rectangles
459 return nullptr;
460 }
461 if (!stroke_dev_half_size_supported(devHalfStrokeSize)) {
462 return nullptr;
463 }
464 return Helper::FactoryHelper<AAStrokeRectOp>(context, std::move(paint), viewMatrix,
465 devOutside, devInside, devHalfStrokeSize);
466 }
467
468 AAStrokeRectOp(GrProcessorSet* processorSet, const SkPMColor4f& color,
469 const SkMatrix& viewMatrix, const SkRect& devOutside, const SkRect& devInside,
470 const SkVector& devHalfStrokeSize)
471 : INHERITED(ClassID())
472 , fHelper(processorSet, GrAAType::kCoverage)
473 , fViewMatrix(viewMatrix) {
474 SkASSERT(!devOutside.isEmpty());
475 SkASSERT(!devInside.isEmpty());
476
477 fRects.emplace_back(RectInfo{color, devOutside, devOutside, devInside, devHalfStrokeSize, false});
478 this->setBounds(devOutside, HasAABloat::kYes, IsHairline::kNo);
479 fMiterStroke = true;
480 }
481
482 static GrOp::Owner Make(GrRecordingContext* context,
483 GrPaint&& paint,
484 const SkMatrix& viewMatrix,
485 const SkRect& rect,
486 const SkStrokeRec& stroke) {
487 if (!viewMatrix.rectStaysRect()) {
488 // The AA op only supports axis-aligned rectangles
489 return nullptr;
490 }
491 bool isMiter;
492 if (!allowed_stroke(context->priv().caps(), stroke, GrAA::kYes, &isMiter)) {
493 return nullptr;
494 }
495 RectInfo info;
496 if (!compute_aa_rects(*context->priv().caps(),
497 &info.fDevOutside,
498 &info.fDevOutsideAssist,
499 &info.fDevInside,
500 &info.fDegenerate,
501 viewMatrix,
502 rect,
503 stroke.getWidth(),
504 isMiter,
505 &info.fDevHalfStrokeSize)) {
506 return nullptr;
507 }
508 if (!stroke_dev_half_size_supported(info.fDevHalfStrokeSize)) {
509 return nullptr;
510 }
511 return Helper::FactoryHelper<AAStrokeRectOp>(context, std::move(paint), viewMatrix, info,
512 isMiter);
513 }
514
515 AAStrokeRectOp(GrProcessorSet* processorSet, const SkPMColor4f& color,
516 const SkMatrix& viewMatrix, const RectInfo& infoExceptColor, bool isMiter)
517 : INHERITED(ClassID())
518 , fHelper(processorSet, GrAAType::kCoverage)
519 , fViewMatrix(viewMatrix) {
520 fMiterStroke = isMiter;
521 RectInfo& info = fRects.push_back(infoExceptColor);
522 info.fColor = color;
523 if (isMiter) {
524 this->setBounds(info.fDevOutside, HasAABloat::kYes, IsHairline::kNo);
525 } else {
526 // The outer polygon of the bevel stroke is an octagon specified by the points of a
527 // pair of overlapping rectangles where one is wide and the other is narrow.
528 SkRect bounds = info.fDevOutside;
529 bounds.joinPossiblyEmptyRect(info.fDevOutsideAssist);
530 this->setBounds(bounds, HasAABloat::kYes, IsHairline::kNo);
531 }
532 }
533
534 const char* name() const override { return "AAStrokeRect"; }
535
536 void visitProxies(const GrVisitProxyFunc& func) const override {
537 if (fProgramInfo) {
538 fProgramInfo->visitFPProxies(func);
539 } else {
540 fHelper.visitProxies(func);
541 }
542 }
543
544 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
545
546 GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
547 GrClampType clampType) override {
548 return fHelper.finalizeProcessors(caps, clip, clampType,
549 GrProcessorAnalysisCoverage::kSingleChannel,
550 &fRects.back().fColor, &fWideColor);
551 }
552
553 private:
554 GrProgramInfo* programInfo() override { return fProgramInfo; }
555
556 bool compatibleWithCoverageAsAlpha(bool usesMSAASurface) const {
557 // When MSAA is enabled, we have to extend our AA bloats and interpolate coverage values
558 // outside 0..1. This makes us incompatible with coverage as alpha.
559 return !usesMSAASurface && fHelper.compatibleWithCoverageAsAlpha();
560 }
561
562 void onCreateProgramInfo(const GrCaps*,
563 SkArenaAlloc*,
564 const GrSurfaceProxyView& writeView,
565 bool usesMSAASurface,
566 GrAppliedClip&&,
567 const GrDstProxyView&,
568 GrXferBarrierFlags renderPassXferBarriers,
569 GrLoadOp colorLoadOp) override;
570
571 void onPrepareDraws(GrMeshDrawTarget*) override;
572 void onExecute(GrOpFlushState*, const SkRect& chainBounds) override;
573
574 #if defined(GPU_TEST_UTILS)
575 SkString onDumpInfo() const override {
576 SkString string;
577 for (const auto& info : fRects) {
578 string.appendf(
579 "Color: 0x%08x, ORect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], "
580 "AssistORect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], "
581 "IRect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], Degen: %d",
582 info.fColor.toBytes_RGBA(), info.fDevOutside.fLeft, info.fDevOutside.fTop,
583 info.fDevOutside.fRight, info.fDevOutside.fBottom, info.fDevOutsideAssist.fLeft,
584 info.fDevOutsideAssist.fTop, info.fDevOutsideAssist.fRight,
585 info.fDevOutsideAssist.fBottom, info.fDevInside.fLeft, info.fDevInside.fTop,
586 info.fDevInside.fRight, info.fDevInside.fBottom, info.fDegenerate);
587 }
588 string += fHelper.dumpInfo();
589 return string;
590 }
591 #endif
592
593 static const int kMiterIndexCnt = 3 * 24;
594 static const int kMiterVertexCnt = 16;
595 static const int kNumMiterRectsInIndexBuffer = 256;
596
597 static const int kBevelIndexCnt = 48 + 36 + 24;
598 static const int kBevelVertexCnt = 24;
599 static const int kNumBevelRectsInIndexBuffer = 256;
600
601 static sk_sp<const GrGpuBuffer> GetIndexBuffer(GrResourceProvider*, bool miterStroke);
602
603 const SkMatrix& viewMatrix() const { return fViewMatrix; }
604 bool miterStroke() const { return fMiterStroke; }
605
606 CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps&) override;
607
608 void generateAAStrokeRectGeometry(VertexWriter& vertices,
609 const SkPMColor4f& color,
610 bool wideColor,
611 const SkRect& devOutside,
612 const SkRect& devOutsideAssist,
613 const SkRect& devInside,
614 bool miterStroke,
615 bool degenerate,
616 const SkVector& devHalfStrokeSize,
617 bool usesMSAASurface) const;
618
619 Helper fHelper;
620 STArray<1, RectInfo, true> fRects;
621 SkMatrix fViewMatrix;
622 GrSimpleMesh* fMesh = nullptr;
623 GrProgramInfo* fProgramInfo = nullptr;
624 bool fMiterStroke;
625 bool fWideColor;
626
627 using INHERITED = GrMeshDrawOp;
628 };
629
630 void AAStrokeRectOp::onCreateProgramInfo(const GrCaps* caps,
631 SkArenaAlloc* arena,
632 const GrSurfaceProxyView& writeView,
633 bool usesMSAASurface,
634 GrAppliedClip&& appliedClip,
635 const GrDstProxyView& dstProxyView,
636 GrXferBarrierFlags renderPassXferBarriers,
637 GrLoadOp colorLoadOp) {
638
639 GrGeometryProcessor* gp = create_aa_stroke_rect_gp(
640 arena,
641 usesMSAASurface,
642 this->compatibleWithCoverageAsAlpha(usesMSAASurface),
643 this->viewMatrix(),
644 fHelper.usesLocalCoords(),
645 fWideColor);
646 if (!gp) {
647 SkDebugf("Couldn't create GrGeometryProcessor\n");
648 return;
649 }
650
651 fProgramInfo = fHelper.createProgramInfo(caps,
652 arena,
653 writeView,
654 usesMSAASurface,
655 std::move(appliedClip),
656 dstProxyView,
657 gp,
658 GrPrimitiveType::kTriangles,
659 renderPassXferBarriers,
660 colorLoadOp);
661 }
662
663 void AAStrokeRectOp::onPrepareDraws(GrMeshDrawTarget* target) {
664
665 if (!fProgramInfo) {
666 this->createProgramInfo(target);
667 if (!fProgramInfo) {
668 return;
669 }
670 }
671
672 int innerVertexNum = 4;
673 int outerVertexNum = this->miterStroke() ? 4 : 8;
674 int verticesPerInstance = (outerVertexNum + innerVertexNum) * 2;
675 int indicesPerInstance = this->miterStroke() ? kMiterIndexCnt : kBevelIndexCnt;
676 int instanceCount = fRects.size();
677 int maxQuads = this->miterStroke() ? kNumMiterRectsInIndexBuffer : kNumBevelRectsInIndexBuffer;
678
679 sk_sp<const GrGpuBuffer> indexBuffer =
680 GetIndexBuffer(target->resourceProvider(), this->miterStroke());
681 if (!indexBuffer) {
682 SkDebugf("Could not allocate indices\n");
683 return;
684 }
685 PatternHelper helper(target, GrPrimitiveType::kTriangles,
686 fProgramInfo->geomProc().vertexStride(), std::move(indexBuffer),
687 verticesPerInstance, indicesPerInstance, instanceCount, maxQuads);
688 VertexWriter vertices{ helper.vertices() };
689 if (!vertices) {
690 SkDebugf("Could not allocate vertices\n");
691 return;
692 }
693
694 for (int i = 0; i < instanceCount; i++) {
695 const RectInfo& info = fRects[i];
696 this->generateAAStrokeRectGeometry(vertices,
697 info.fColor,
698 fWideColor,
699 info.fDevOutside,
700 info.fDevOutsideAssist,
701 info.fDevInside,
702 fMiterStroke,
703 info.fDegenerate,
704 info.fDevHalfStrokeSize,
705 target->usesMSAASurface());
706 }
707 fMesh = helper.mesh();
708 }
709
710 void AAStrokeRectOp::onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) {
711 if (!fProgramInfo || !fMesh) {
712 return;
713 }
714
715 flushState->bindPipelineAndScissorClip(*fProgramInfo, chainBounds);
716 flushState->bindTextures(fProgramInfo->geomProc(), nullptr, fProgramInfo->pipeline());
717 flushState->drawMesh(*fMesh);
718 }
719
720 sk_sp<const GrGpuBuffer> AAStrokeRectOp::GetIndexBuffer(GrResourceProvider* resourceProvider,
721 bool miterStroke) {
722 if (miterStroke) {
723 // clang-format off
724 static const uint16_t gMiterIndices[] = {
725 0 + 0, 1 + 0, 5 + 0, 5 + 0, 4 + 0, 0 + 0,
726 1 + 0, 2 + 0, 6 + 0, 6 + 0, 5 + 0, 1 + 0,
727 2 + 0, 3 + 0, 7 + 0, 7 + 0, 6 + 0, 2 + 0,
728 3 + 0, 0 + 0, 4 + 0, 4 + 0, 7 + 0, 3 + 0,
729
730 0 + 4, 1 + 4, 5 + 4, 5 + 4, 4 + 4, 0 + 4,
731 1 + 4, 2 + 4, 6 + 4, 6 + 4, 5 + 4, 1 + 4,
732 2 + 4, 3 + 4, 7 + 4, 7 + 4, 6 + 4, 2 + 4,
733 3 + 4, 0 + 4, 4 + 4, 4 + 4, 7 + 4, 3 + 4,
734
735 0 + 8, 1 + 8, 5 + 8, 5 + 8, 4 + 8, 0 + 8,
736 1 + 8, 2 + 8, 6 + 8, 6 + 8, 5 + 8, 1 + 8,
737 2 + 8, 3 + 8, 7 + 8, 7 + 8, 6 + 8, 2 + 8,
738 3 + 8, 0 + 8, 4 + 8, 4 + 8, 7 + 8, 3 + 8,
739 };
740 // clang-format on
741 static_assert(std::size(gMiterIndices) == kMiterIndexCnt);
742 SKGPU_DEFINE_STATIC_UNIQUE_KEY(gMiterIndexBufferKey);
743 return resourceProvider->findOrCreatePatternedIndexBuffer(
744 gMiterIndices, kMiterIndexCnt, kNumMiterRectsInIndexBuffer, kMiterVertexCnt,
745 gMiterIndexBufferKey);
746 } else {
747 /**
748 * As in miter-stroke, index = a + b, and a is the current index, b is the shift
749 * from the first index. The index layout:
750 * outer AA line: 0~3, 4~7
751 * outer edge: 8~11, 12~15
752 * inner edge: 16~19
753 * inner AA line: 20~23
754 * Following comes a bevel-stroke rect and its indices:
755 *
756 * 4 7
757 * *********************************
758 * * ______________________________ *
759 * * / 12 15 \ *
760 * * / \ *
761 * 0 * |8 16_____________________19 11 | * 3
762 * * | | | | *
763 * * | | **************** | | *
764 * * | | * 20 23 * | | *
765 * * | | * * | | *
766 * * | | * 21 22 * | | *
767 * * | | **************** | | *
768 * * | |____________________| | *
769 * 1 * |9 17 18 10| * 2
770 * * \ / *
771 * * \13 __________________________14/ *
772 * * *
773 * **********************************
774 * 5 6
775 */
776 // clang-format off
777 static const uint16_t gBevelIndices[] = {
778 // Draw outer AA, from outer AA line to outer edge, shift is 0.
779 0 + 0, 1 + 0, 9 + 0, 9 + 0, 8 + 0, 0 + 0,
780 1 + 0, 5 + 0, 13 + 0, 13 + 0, 9 + 0, 1 + 0,
781 5 + 0, 6 + 0, 14 + 0, 14 + 0, 13 + 0, 5 + 0,
782 6 + 0, 2 + 0, 10 + 0, 10 + 0, 14 + 0, 6 + 0,
783 2 + 0, 3 + 0, 11 + 0, 11 + 0, 10 + 0, 2 + 0,
784 3 + 0, 7 + 0, 15 + 0, 15 + 0, 11 + 0, 3 + 0,
785 7 + 0, 4 + 0, 12 + 0, 12 + 0, 15 + 0, 7 + 0,
786 4 + 0, 0 + 0, 8 + 0, 8 + 0, 12 + 0, 4 + 0,
787
788 // Draw the stroke, from outer edge to inner edge, shift is 8.
789 0 + 8, 1 + 8, 9 + 8, 9 + 8, 8 + 8, 0 + 8,
790 1 + 8, 5 + 8, 9 + 8,
791 5 + 8, 6 + 8, 10 + 8, 10 + 8, 9 + 8, 5 + 8,
792 6 + 8, 2 + 8, 10 + 8,
793 2 + 8, 3 + 8, 11 + 8, 11 + 8, 10 + 8, 2 + 8,
794 3 + 8, 7 + 8, 11 + 8,
795 7 + 8, 4 + 8, 8 + 8, 8 + 8, 11 + 8, 7 + 8,
796 4 + 8, 0 + 8, 8 + 8,
797
798 // Draw the inner AA, from inner edge to inner AA line, shift is 16.
799 0 + 16, 1 + 16, 5 + 16, 5 + 16, 4 + 16, 0 + 16,
800 1 + 16, 2 + 16, 6 + 16, 6 + 16, 5 + 16, 1 + 16,
801 2 + 16, 3 + 16, 7 + 16, 7 + 16, 6 + 16, 2 + 16,
802 3 + 16, 0 + 16, 4 + 16, 4 + 16, 7 + 16, 3 + 16,
803 };
804 // clang-format on
805 static_assert(std::size(gBevelIndices) == kBevelIndexCnt);
806
807 SKGPU_DEFINE_STATIC_UNIQUE_KEY(gBevelIndexBufferKey);
808 return resourceProvider->findOrCreatePatternedIndexBuffer(
809 gBevelIndices, kBevelIndexCnt, kNumBevelRectsInIndexBuffer, kBevelVertexCnt,
810 gBevelIndexBufferKey);
811 }
812 }
813
814 GrOp::CombineResult AAStrokeRectOp::onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps)
815 {
816 AAStrokeRectOp* that = t->cast<AAStrokeRectOp>();
817
818 if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
819 return CombineResult::kCannotCombine;
820 }
821
822 // TODO combine across miterstroke changes
823 if (this->miterStroke() != that->miterStroke()) {
824 return CombineResult::kCannotCombine;
825 }
826
827 // We apply the viewmatrix to the rect points on the cpu. However, if the pipeline uses
828 // local coords then we won't be able to combine. TODO: Upload local coords as an attribute.
829 if (fHelper.usesLocalCoords() &&
830 !SkMatrixPriv::CheapEqual(this->viewMatrix(), that->viewMatrix()))
831 {
832 return CombineResult::kCannotCombine;
833 }
834
835 fRects.push_back_n(that->fRects.size(), that->fRects.begin());
836 fWideColor |= that->fWideColor;
837 return CombineResult::kMerged;
838 }
839
840 void AAStrokeRectOp::generateAAStrokeRectGeometry(VertexWriter& vertices,
841 const SkPMColor4f& color,
842 bool wideColor,
843 const SkRect& devOutside,
844 const SkRect& devOutsideAssist,
845 const SkRect& devInside,
846 bool miterStroke,
847 bool degenerate,
848 const SkVector& devHalfStrokeSize,
849 bool usesMSAASurface) const {
850 // We create vertices for four nested rectangles. There are two ramps from 0 to full
851 // coverage, one on the exterior of the stroke and the other on the interior.
852
853 // The following code only works if either devStrokeSize's fX and fY are
854 // equal (in which case innerCoverage is same for all sides of the rects) or
855 // if devStrokeSize's fX and fY are both greater than 1.0 (in which case
856 // innerCoverage will always be 1).
857 SkASSERT(stroke_dev_half_size_supported(devHalfStrokeSize));
858
859 auto inset_fan = [](const SkRect& r, SkScalar dx, SkScalar dy) {
860 return VertexWriter::TriFanFromRect(r.makeInset(dx, dy));
861 };
862
863 bool tweakAlphaForCoverage = this->compatibleWithCoverageAsAlpha(usesMSAASurface);
864
865 auto maybe_coverage = [tweakAlphaForCoverage](float coverage) {
866 return VertexWriter::If(!tweakAlphaForCoverage, coverage);
867 };
868
869 // How much do we inset toward the inside of the strokes?
870 float inset = std::min(0.5f, std::min(devHalfStrokeSize.fX, devHalfStrokeSize.fY));
871 float innerCoverage = 1;
872 if (inset < 0.5f) {
873 // Stroke is subpixel, so reduce the coverage to simulate the narrower strokes.
874 innerCoverage = 2 * inset / (inset + .5f);
875 }
876
877 // How much do we outset away from the outside of the strokes?
878 // We always want to keep the AA picture frame one pixel wide.
879 float outset = 1 - inset;
880 float outerCoverage = 0;
881
882 // How much do we outset away from the interior side of the stroke (toward the center)?
883 float interiorOutset = outset;
884 float interiorCoverage = outerCoverage;
885
886 if (usesMSAASurface) {
887 // Since we're using MSAA, extend our outsets to ensure any pixel with partial coverage has
888 // a full sample mask.
889 constexpr float msaaExtraBloat = SK_ScalarSqrt2 - .5f;
890 outset += msaaExtraBloat;
891 outerCoverage -= msaaExtraBloat;
892
893 float insetExtraBloat =
894 std::min(inset + msaaExtraBloat,
895 std::min(devHalfStrokeSize.fX, devHalfStrokeSize.fY)) - inset;
896 inset += insetExtraBloat;
897 innerCoverage += insetExtraBloat;
898
899 float interiorExtraBloat =
900 std::min(interiorOutset + msaaExtraBloat,
901 std::min(devInside.width(), devInside.height()) / 2) - interiorOutset;
902 interiorOutset += interiorExtraBloat;
903 interiorCoverage -= interiorExtraBloat;
904 }
905
906 VertexColor innerColor(tweakAlphaForCoverage ? color * innerCoverage : color, wideColor);
907 VertexColor outerColor(tweakAlphaForCoverage ? SK_PMColor4fTRANSPARENT : color, wideColor);
908
909 // Exterior outset rect (away from stroke).
910 vertices.writeQuad(inset_fan(devOutside, -outset, -outset),
911 outerColor,
912 maybe_coverage(outerCoverage));
913
914 if (!miterStroke) {
915 // Second exterior outset.
916 vertices.writeQuad(inset_fan(devOutsideAssist, -outset, -outset),
917 outerColor,
918 maybe_coverage(outerCoverage));
919 }
920
921 // Exterior inset rect (toward stroke).
922 vertices.writeQuad(inset_fan(devOutside, inset, inset),
923 innerColor,
924 maybe_coverage(innerCoverage));
925
926 if (!miterStroke) {
927 // Second exterior inset.
928 vertices.writeQuad(inset_fan(devOutsideAssist, inset, inset),
929 innerColor,
930 maybe_coverage(innerCoverage));
931 }
932
933 if (!degenerate) {
934 // Interior inset rect (toward stroke).
935 vertices.writeQuad(inset_fan(devInside, -inset, -inset),
936 innerColor,
937 maybe_coverage(innerCoverage));
938
939 // Interior outset rect (away from stroke, toward center of rect).
940 SkRect interiorAABoundary = devInside.makeInset(interiorOutset, interiorOutset);
941 float coverageBackset = 0; // Adds back coverage when the interior AA edges cross.
942 if (interiorAABoundary.fLeft > interiorAABoundary.fRight) {
943 coverageBackset =
944 (interiorAABoundary.fLeft - interiorAABoundary.fRight) / (interiorOutset * 2);
945 interiorAABoundary.fLeft = interiorAABoundary.fRight = interiorAABoundary.centerX();
946 }
947 if (interiorAABoundary.fTop > interiorAABoundary.fBottom) {
948 coverageBackset = std::max(
949 (interiorAABoundary.fTop - interiorAABoundary.fBottom) / (interiorOutset * 2),
950 coverageBackset);
951 interiorAABoundary.fTop = interiorAABoundary.fBottom = interiorAABoundary.centerY();
952 }
953 if (coverageBackset > 0) {
954 // The interior edges crossed. Lerp back toward innerCoverage, which is what this op
955 // will draw in the degenerate case. This gives a smooth transition into the degenerate
956 // case.
957 interiorCoverage += interiorCoverage * (1 - coverageBackset) +
958 innerCoverage * coverageBackset;
959 }
960 VertexColor interiorColor(tweakAlphaForCoverage ? color * interiorCoverage : color,
961 wideColor);
962 vertices.writeQuad(VertexWriter::TriFanFromRect(interiorAABoundary),
963 interiorColor,
964 maybe_coverage(interiorCoverage));
965 } else {
966 // When the interior rect has become degenerate we smoosh to a single point
967 SkASSERT(devInside.fLeft == devInside.fRight && devInside.fTop == devInside.fBottom);
968
969 vertices.writeQuad(VertexWriter::TriFanFromRect(devInside),
970 innerColor,
971 maybe_coverage(innerCoverage));
972
973 // ... unless we are degenerate, in which case we must apply the scaled coverage
974 vertices.writeQuad(VertexWriter::TriFanFromRect(devInside),
975 innerColor,
976 maybe_coverage(innerCoverage));
977 }
978 }
979
980 } // anonymous namespace
981
982 GrOp::Owner Make(GrRecordingContext* context,
983 GrPaint&& paint,
984 GrAAType aaType,
985 const SkMatrix& viewMatrix,
986 const SkRect& rect,
987 const SkStrokeRec& stroke) {
988 SkASSERT(!context->priv().caps()->reducedShaderMode());
989 if (aaType == GrAAType::kCoverage) {
990 return AAStrokeRectOp::Make(context, std::move(paint), viewMatrix, rect, stroke);
991 } else {
992 return NonAAStrokeRectOp::Make(context, std::move(paint), viewMatrix, rect, stroke, aaType);
993 }
994 }
995
996 GrOp::Owner MakeNested(GrRecordingContext* context,
997 GrPaint&& paint,
998 const SkMatrix& viewMatrix,
999 const SkRect rects[2]) {
1000 SkASSERT(viewMatrix.rectStaysRect());
1001 SkASSERT(!rects[0].isEmpty() && !rects[1].isEmpty());
1002
1003 SkRect devOutside = viewMatrix.mapRect(rects[0]);
1004 SkRect devInside = viewMatrix.mapRect(rects[1]);
1005 float dx = devOutside.fRight - devInside.fRight;
1006 float dy = devOutside.fBottom - devInside.fBottom;
1007
1008 // Clips our draw rects 1 full pixel outside the viewport. This avoids interpolation precision
1009 // issues with very large coordinates.
1010 const float m = context->priv().caps()->maxRenderTargetSize();
1011 const SkRect visibilityBounds = SkRect::MakeWH(m, m).makeOutset(1, 1);
1012
1013 if (!devOutside.intersect(visibilityBounds.makeOutset(dx, dy))) {
1014 return nullptr;
1015 }
1016
1017 if (devInside.isEmpty() || !devInside.intersect(visibilityBounds)) {
1018 if (devOutside.isEmpty()) {
1019 return nullptr;
1020 }
1021 DrawQuad quad{GrQuad::MakeFromRect(rects[0], viewMatrix), GrQuad(rects[0]),
1022 GrQuadAAFlags::kAll};
1023 return ganesh::FillRectOp::Make(context, std::move(paint), GrAAType::kCoverage, &quad);
1024 }
1025
1026 return AAStrokeRectOp::Make(context, std::move(paint), viewMatrix, devOutside,
1027 devInside, SkVector{dx, dy} * .5f);
1028 }
1029
1030 } // namespace skgpu::ganesh::StrokeRectOp
1031
1032 #if defined(GPU_TEST_UTILS)
1033
1034 GR_DRAW_OP_TEST_DEFINE(NonAAStrokeRectOp) {
1035 SkMatrix viewMatrix = GrTest::TestMatrix(random);
1036 SkRect rect = GrTest::TestRect(random);
1037 SkScalar strokeWidth = random->nextBool() ? 0.0f : 2.0f;
1038 SkPaint strokePaint;
1039 strokePaint.setStrokeWidth(strokeWidth);
1040 strokePaint.setStyle(SkPaint::kStroke_Style);
1041 strokePaint.setStrokeJoin(SkPaint::kMiter_Join);
1042 SkStrokeRec strokeRec(strokePaint);
1043 GrAAType aaType = GrAAType::kNone;
1044 if (numSamples > 1) {
1045 aaType = random->nextBool() ? GrAAType::kMSAA : GrAAType::kNone;
1046 }
1047 return skgpu::ganesh::StrokeRectOp::NonAAStrokeRectOp::Make(context, std::move(paint),
1048 viewMatrix, rect, strokeRec,
1049 aaType);
1050 }
1051
1052 GR_DRAW_OP_TEST_DEFINE(AAStrokeRectOp) {
1053 bool miterStroke = random->nextBool();
1054
1055 // Create either a empty rect or a non-empty rect.
1056 SkRect rect =
1057 random->nextBool() ? SkRect::MakeXYWH(10, 10, 50, 40) : SkRect::MakeXYWH(6, 7, 0, 0);
1058 SkScalar minDim = std::min(rect.width(), rect.height());
1059 SkScalar strokeWidth = random->nextUScalar1() * minDim;
1060
1061 SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);
1062 rec.setStrokeStyle(strokeWidth);
1063 rec.setStrokeParams(SkPaint::kButt_Cap,
1064 miterStroke ? SkPaint::kMiter_Join : SkPaint::kBevel_Join, 1.f);
1065 SkMatrix matrix = GrTest::TestMatrixRectStaysRect(random);
1066 return skgpu::ganesh::StrokeRectOp::AAStrokeRectOp::Make(context, std::move(paint), matrix,
1067 rect, rec);
1068 }
1069
1070 #endif