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 
8 #include "src/gpu/ops/GrStrokeRectOp.h"
9 
10 #include "include/core/SkStrokeRec.h"
11 #include "include/private/GrResourceKey.h"
12 #include "include/utils/SkRandom.h"
13 #include "src/gpu/GrCaps.h"
14 #include "src/gpu/GrColor.h"
15 #include "src/gpu/GrDefaultGeoProcFactory.h"
16 #include "src/gpu/GrDrawOpTest.h"
17 #include "src/gpu/GrOpFlushState.h"
18 #include "src/gpu/GrResourceProvider.h"
19 #include "src/gpu/GrVertexWriter.h"
20 #include "src/gpu/ops/GrFillRectOp.h"
21 #include "src/gpu/ops/GrMeshDrawOp.h"
22 #include "src/gpu/ops/GrSimpleMeshDrawOpHelper.h"
23 
24 namespace {
25 
26 // We support all hairlines, bevels, and miters, but not round joins. Also, check whether the miter
27 // limit makes a miter join effectively beveled. If the miter is effectively beveled, it is only
28 // supported when using an AA stroke.
allowed_stroke(const SkStrokeRec & stroke,GrAA aa,bool * isMiter)29 inline static bool allowed_stroke(const SkStrokeRec& stroke, GrAA aa, bool* isMiter) {
30     SkASSERT(stroke.getStyle() == SkStrokeRec::kStroke_Style ||
31              stroke.getStyle() == SkStrokeRec::kHairline_Style);
32     // For hairlines, make bevel and round joins appear the same as mitered ones.
33     if (!stroke.getWidth()) {
34         *isMiter = true;
35         return true;
36     }
37     if (stroke.getJoin() == SkPaint::kBevel_Join) {
38         *isMiter = false;
39         return aa == GrAA::kYes; // bevel only supported with AA
40     }
41     if (stroke.getJoin() == SkPaint::kMiter_Join) {
42         *isMiter = stroke.getMiter() >= SK_ScalarSqrt2;
43         // Supported under non-AA only if it remains mitered
44         return aa == GrAA::kYes || *isMiter;
45     }
46     return false;
47 }
48 
49 
50 ///////////////////////////////////////////////////////////////////////////////////////////////////
51 // Non-AA Stroking
52 ///////////////////////////////////////////////////////////////////////////////////////////////////
53 
54 /*  create a triangle strip that strokes the specified rect. There are 8
55     unique vertices, but we repeat the last 2 to close up. Alternatively we
56     could use an indices array, and then only send 8 verts, but not sure that
57     would be faster.
58     */
init_nonaa_stroke_rect_strip(SkPoint verts[10],const SkRect & rect,SkScalar width)59 static void init_nonaa_stroke_rect_strip(SkPoint verts[10], const SkRect& rect, SkScalar width) {
60     const SkScalar rad = SkScalarHalf(width);
61 
62     verts[0].set(rect.fLeft + rad, rect.fTop + rad);
63     verts[1].set(rect.fLeft - rad, rect.fTop - rad);
64     verts[2].set(rect.fRight - rad, rect.fTop + rad);
65     verts[3].set(rect.fRight + rad, rect.fTop - rad);
66     verts[4].set(rect.fRight - rad, rect.fBottom - rad);
67     verts[5].set(rect.fRight + rad, rect.fBottom + rad);
68     verts[6].set(rect.fLeft + rad, rect.fBottom - rad);
69     verts[7].set(rect.fLeft - rad, rect.fBottom + rad);
70     verts[8] = verts[0];
71     verts[9] = verts[1];
72 
73     // TODO: we should be catching this higher up the call stack and just draw a single
74     // non-AA rect
75     if (2*rad >= rect.width()) {
76         verts[0].fX = verts[2].fX = verts[4].fX = verts[6].fX = verts[8].fX = rect.centerX();
77     }
78     if (2*rad >= rect.height()) {
79         verts[0].fY = verts[2].fY = verts[4].fY = verts[6].fY = verts[8].fY = rect.centerY();
80     }
81 }
82 
83 class NonAAStrokeRectOp final : public GrMeshDrawOp {
84 private:
85     using Helper = GrSimpleMeshDrawOpHelper;
86 
87 public:
88     DEFINE_OP_CLASS_ID
89 
name() const90     const char* name() const override { return "NonAAStrokeRectOp"; }
91 
visitProxies(const VisitProxyFunc & func) const92     void visitProxies(const VisitProxyFunc& func) const override {
93         fHelper.visitProxies(func);
94     }
95 
96 #ifdef SK_DEBUG
dumpInfo() const97     SkString dumpInfo() const override {
98         SkString string;
99         string.appendf(
100                 "Color: 0x%08x, Rect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], "
101                 "StrokeWidth: %.2f\n",
102                 fColor.toBytes_RGBA(), fRect.fLeft, fRect.fTop, fRect.fRight, fRect.fBottom,
103                 fStrokeWidth);
104         string += fHelper.dumpInfo();
105         string += INHERITED::dumpInfo();
106         return string;
107     }
108 #endif
109 
Make(GrRecordingContext * context,GrPaint && paint,const SkMatrix & viewMatrix,const SkRect & rect,const SkStrokeRec & stroke,GrAAType aaType)110     static std::unique_ptr<GrDrawOp> Make(GrRecordingContext* context,
111                                           GrPaint&& paint,
112                                           const SkMatrix& viewMatrix,
113                                           const SkRect& rect,
114                                           const SkStrokeRec& stroke,
115                                           GrAAType aaType) {
116         bool isMiter;
117         if (!allowed_stroke(stroke, GrAA::kNo, &isMiter)) {
118             return nullptr;
119         }
120         Helper::InputFlags inputFlags = Helper::InputFlags::kNone;
121         // Depending on sub-pixel coordinates and the particular GPU, we may lose a corner of
122         // hairline rects. We jam all the vertices to pixel centers to avoid this, but not
123         // when MSAA is enabled because it can cause ugly artifacts.
124         if (stroke.getStyle() == SkStrokeRec::kHairline_Style && aaType != GrAAType::kMSAA) {
125             inputFlags |= Helper::InputFlags::kSnapVerticesToPixelCenters;
126         }
127         return Helper::FactoryHelper<NonAAStrokeRectOp>(context, std::move(paint), inputFlags,
128                                                         viewMatrix, rect,
129                                                         stroke, aaType);
130     }
131 
NonAAStrokeRectOp(const Helper::MakeArgs & helperArgs,const SkPMColor4f & color,Helper::InputFlags inputFlags,const SkMatrix & viewMatrix,const SkRect & rect,const SkStrokeRec & stroke,GrAAType aaType)132     NonAAStrokeRectOp(const Helper::MakeArgs& helperArgs, const SkPMColor4f& color,
133                       Helper::InputFlags inputFlags, const SkMatrix& viewMatrix, const SkRect& rect,
134                       const SkStrokeRec& stroke, GrAAType aaType)
135             : INHERITED(ClassID()), fHelper(helperArgs, aaType, inputFlags) {
136         fColor = color;
137         fViewMatrix = viewMatrix;
138         fRect = rect;
139         // Sort the rect for hairlines
140         fRect.sort();
141         fStrokeWidth = stroke.getWidth();
142 
143         SkScalar rad = SkScalarHalf(fStrokeWidth);
144         SkRect bounds = rect;
145         bounds.outset(rad, rad);
146 
147         // If our caller snaps to pixel centers then we have to round out the bounds
148         if (inputFlags & Helper::InputFlags::kSnapVerticesToPixelCenters) {
149             SkASSERT(!fStrokeWidth || aaType == GrAAType::kNone);
150             viewMatrix.mapRect(&bounds);
151             // We want to be consistent with how we snap non-aa lines. To match what we do in
152             // GrGLSLVertexShaderBuilder, we first floor all the vertex values and then add half a
153             // pixel to force us to pixel centers.
154             bounds.setLTRB(SkScalarFloorToScalar(bounds.fLeft),
155                            SkScalarFloorToScalar(bounds.fTop),
156                            SkScalarFloorToScalar(bounds.fRight),
157                            SkScalarFloorToScalar(bounds.fBottom));
158             bounds.offset(0.5f, 0.5f);
159             this->setBounds(bounds, HasAABloat::kNo, IsHairline::kNo);
160         } else {
161             HasAABloat aaBloat = (aaType == GrAAType::kNone) ? HasAABloat ::kNo : HasAABloat::kYes;
162             this->setTransformedBounds(bounds, fViewMatrix, aaBloat,
163                                        fStrokeWidth ? IsHairline::kNo : IsHairline::kYes);
164         }
165     }
166 
fixedFunctionFlags() const167     FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
168 
finalize(const GrCaps & caps,const GrAppliedClip * clip,bool hasMixedSampledCoverage,GrClampType clampType)169     GrProcessorSet::Analysis finalize(
170             const GrCaps& caps, const GrAppliedClip* clip, bool hasMixedSampledCoverage,
171             GrClampType clampType) override {
172         // This Op uses uniform (not vertex) color, so doesn't need to track wide color.
173         return fHelper.finalizeProcessors(caps, clip, hasMixedSampledCoverage, clampType,
174                                           GrProcessorAnalysisCoverage::kNone, &fColor, nullptr);
175     }
176 
177 private:
onPrepareDraws(Target * target)178     void onPrepareDraws(Target* target) override {
179         sk_sp<GrGeometryProcessor> gp;
180         {
181             using namespace GrDefaultGeoProcFactory;
182             Color color(fColor);
183             LocalCoords::Type localCoordsType = fHelper.usesLocalCoords()
184                                                         ? LocalCoords::kUsePosition_Type
185                                                         : LocalCoords::kUnused_Type;
186             gp = GrDefaultGeoProcFactory::Make(target->caps().shaderCaps(), color,
187                                                Coverage::kSolid_Type, localCoordsType,
188                                                fViewMatrix);
189         }
190 
191         size_t kVertexStride = gp->vertexStride();
192         int vertexCount = kVertsPerHairlineRect;
193         if (fStrokeWidth > 0) {
194             vertexCount = kVertsPerStrokeRect;
195         }
196 
197         sk_sp<const GrBuffer> vertexBuffer;
198         int firstVertex;
199 
200         void* verts =
201                 target->makeVertexSpace(kVertexStride, vertexCount, &vertexBuffer, &firstVertex);
202 
203         if (!verts) {
204             SkDebugf("Could not allocate vertices\n");
205             return;
206         }
207 
208         SkPoint* vertex = reinterpret_cast<SkPoint*>(verts);
209 
210         GrPrimitiveType primType;
211         if (fStrokeWidth > 0) {
212             primType = GrPrimitiveType::kTriangleStrip;
213             init_nonaa_stroke_rect_strip(vertex, fRect, fStrokeWidth);
214         } else {
215             // hairline
216             primType = GrPrimitiveType::kLineStrip;
217             vertex[0].set(fRect.fLeft, fRect.fTop);
218             vertex[1].set(fRect.fRight, fRect.fTop);
219             vertex[2].set(fRect.fRight, fRect.fBottom);
220             vertex[3].set(fRect.fLeft, fRect.fBottom);
221             vertex[4].set(fRect.fLeft, fRect.fTop);
222         }
223 
224         GrMesh* mesh = target->allocMesh(primType);
225         mesh->setNonIndexedNonInstanced(vertexCount);
226         mesh->setVertexData(std::move(vertexBuffer), firstVertex);
227         target->recordDraw(std::move(gp), mesh);
228     }
229 
onExecute(GrOpFlushState * flushState,const SkRect & chainBounds)230     void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
231         fHelper.executeDrawsAndUploads(this, flushState, chainBounds);
232     }
233 
234     // TODO: override onCombineIfPossible
235 
236     Helper fHelper;
237     SkPMColor4f fColor;
238     SkMatrix fViewMatrix;
239     SkRect fRect;
240     SkScalar fStrokeWidth;
241 
242     const static int kVertsPerHairlineRect = 5;
243     const static int kVertsPerStrokeRect = 10;
244 
245     typedef GrMeshDrawOp INHERITED;
246 };
247 
248 ///////////////////////////////////////////////////////////////////////////////////////////////////
249 // AA Stroking
250 ///////////////////////////////////////////////////////////////////////////////////////////////////
251 
252 GR_DECLARE_STATIC_UNIQUE_KEY(gMiterIndexBufferKey);
253 GR_DECLARE_STATIC_UNIQUE_KEY(gBevelIndexBufferKey);
254 
compute_aa_rects(SkRect * devOutside,SkRect * devOutsideAssist,SkRect * devInside,bool * isDegenerate,const SkMatrix & viewMatrix,const SkRect & rect,SkScalar strokeWidth,bool miterStroke)255 static void compute_aa_rects(SkRect* devOutside, SkRect* devOutsideAssist, SkRect* devInside,
256                              bool* isDegenerate, const SkMatrix& viewMatrix, const SkRect& rect,
257                              SkScalar strokeWidth, bool miterStroke) {
258     SkRect devRect;
259     viewMatrix.mapRect(&devRect, rect);
260 
261     SkVector devStrokeSize;
262     if (strokeWidth > 0) {
263         devStrokeSize.set(strokeWidth, strokeWidth);
264         viewMatrix.mapVectors(&devStrokeSize, 1);
265         devStrokeSize.setAbs(devStrokeSize);
266     } else {
267         devStrokeSize.set(SK_Scalar1, SK_Scalar1);
268     }
269 
270     const SkScalar dx = devStrokeSize.fX;
271     const SkScalar dy = devStrokeSize.fY;
272     const SkScalar rx = SkScalarHalf(dx);
273     const SkScalar ry = SkScalarHalf(dy);
274 
275     *devOutside = devRect;
276     *devOutsideAssist = devRect;
277     *devInside = devRect;
278 
279     devOutside->outset(rx, ry);
280     devInside->inset(rx, ry);
281 
282     // If we have a degenerate stroking rect(ie the stroke is larger than inner rect) then we
283     // make a degenerate inside rect to avoid double hitting.  We will also jam all of the points
284     // together when we render these rects.
285     SkScalar spare;
286     {
287         SkScalar w = devRect.width() - dx;
288         SkScalar h = devRect.height() - dy;
289         spare = SkTMin(w, h);
290     }
291 
292     *isDegenerate = spare <= 0;
293     if (*isDegenerate) {
294         devInside->fLeft = devInside->fRight = devRect.centerX();
295         devInside->fTop = devInside->fBottom = devRect.centerY();
296     }
297 
298     // For bevel-stroke, use 2 SkRect instances(devOutside and devOutsideAssist)
299     // to draw the outside of the octagon. Because there are 8 vertices on the outer
300     // edge, while vertex number of inner edge is 4, the same as miter-stroke.
301     if (!miterStroke) {
302         devOutside->inset(0, ry);
303         devOutsideAssist->outset(0, ry);
304     }
305 }
306 
create_aa_stroke_rect_gp(const GrShaderCaps * shaderCaps,bool tweakAlphaForCoverage,const SkMatrix & viewMatrix,bool usesLocalCoords,bool wideColor)307 static sk_sp<GrGeometryProcessor> create_aa_stroke_rect_gp(const GrShaderCaps* shaderCaps,
308                                                            bool tweakAlphaForCoverage,
309                                                            const SkMatrix& viewMatrix,
310                                                            bool usesLocalCoords,
311                                                            bool wideColor) {
312     using namespace GrDefaultGeoProcFactory;
313 
314     Coverage::Type coverageType =
315         tweakAlphaForCoverage ? Coverage::kSolid_Type : Coverage::kAttribute_Type;
316     LocalCoords::Type localCoordsType =
317         usesLocalCoords ? LocalCoords::kUsePosition_Type : LocalCoords::kUnused_Type;
318     Color::Type colorType =
319         wideColor ? Color::kPremulWideColorAttribute_Type: Color::kPremulGrColorAttribute_Type;
320 
321     return MakeForDeviceSpace(shaderCaps, colorType, coverageType, localCoordsType, viewMatrix);
322 }
323 
324 class AAStrokeRectOp final : public GrMeshDrawOp {
325 private:
326     using Helper = GrSimpleMeshDrawOpHelper;
327 
328 public:
329     DEFINE_OP_CLASS_ID
330 
Make(GrRecordingContext * context,GrPaint && paint,const SkMatrix & viewMatrix,const SkRect & devOutside,const SkRect & devInside)331     static std::unique_ptr<GrDrawOp> Make(GrRecordingContext* context,
332                                           GrPaint&& paint,
333                                           const SkMatrix& viewMatrix,
334                                           const SkRect& devOutside,
335                                           const SkRect& devInside) {
336         return Helper::FactoryHelper<AAStrokeRectOp>(context, std::move(paint), viewMatrix,
337                                                      devOutside, devInside);
338     }
339 
AAStrokeRectOp(const Helper::MakeArgs & helperArgs,const SkPMColor4f & color,const SkMatrix & viewMatrix,const SkRect & devOutside,const SkRect & devInside)340     AAStrokeRectOp(const Helper::MakeArgs& helperArgs, const SkPMColor4f& color,
341                    const SkMatrix& viewMatrix, const SkRect& devOutside, const SkRect& devInside)
342             : INHERITED(ClassID())
343             , fHelper(helperArgs, GrAAType::kCoverage)
344             , fViewMatrix(viewMatrix) {
345         SkASSERT(!devOutside.isEmpty());
346         SkASSERT(!devInside.isEmpty());
347 
348         fRects.emplace_back(RectInfo{color, devOutside, devOutside, devInside, false});
349         this->setBounds(devOutside, HasAABloat::kYes, IsHairline::kNo);
350         fMiterStroke = true;
351     }
352 
Make(GrRecordingContext * context,GrPaint && paint,const SkMatrix & viewMatrix,const SkRect & rect,const SkStrokeRec & stroke)353     static std::unique_ptr<GrDrawOp> Make(GrRecordingContext* context,
354                                           GrPaint&& paint,
355                                           const SkMatrix& viewMatrix,
356                                           const SkRect& rect,
357                                           const SkStrokeRec& stroke) {
358         bool isMiter;
359         if (!allowed_stroke(stroke, GrAA::kYes, &isMiter)) {
360             return nullptr;
361         }
362         return Helper::FactoryHelper<AAStrokeRectOp>(context, std::move(paint), viewMatrix, rect,
363                                                      stroke, isMiter);
364     }
365 
AAStrokeRectOp(const Helper::MakeArgs & helperArgs,const SkPMColor4f & color,const SkMatrix & viewMatrix,const SkRect & rect,const SkStrokeRec & stroke,bool isMiter)366     AAStrokeRectOp(const Helper::MakeArgs& helperArgs, const SkPMColor4f& color,
367                    const SkMatrix& viewMatrix, const SkRect& rect, const SkStrokeRec& stroke,
368                    bool isMiter)
369             : INHERITED(ClassID())
370             , fHelper(helperArgs, GrAAType::kCoverage)
371             , fViewMatrix(viewMatrix) {
372         fMiterStroke = isMiter;
373         RectInfo& info = fRects.push_back();
374         compute_aa_rects(&info.fDevOutside, &info.fDevOutsideAssist, &info.fDevInside,
375                          &info.fDegenerate, viewMatrix, rect, stroke.getWidth(), isMiter);
376         info.fColor = color;
377         if (isMiter) {
378             this->setBounds(info.fDevOutside, HasAABloat::kYes, IsHairline::kNo);
379         } else {
380             // The outer polygon of the bevel stroke is an octagon specified by the points of a
381             // pair of overlapping rectangles where one is wide and the other is narrow.
382             SkRect bounds = info.fDevOutside;
383             bounds.joinPossiblyEmptyRect(info.fDevOutsideAssist);
384             this->setBounds(bounds, HasAABloat::kYes, IsHairline::kNo);
385         }
386     }
387 
name() const388     const char* name() const override { return "AAStrokeRect"; }
389 
visitProxies(const VisitProxyFunc & func) const390     void visitProxies(const VisitProxyFunc& func) const override {
391         fHelper.visitProxies(func);
392     }
393 
394 #ifdef SK_DEBUG
dumpInfo() const395     SkString dumpInfo() const override {
396         SkString string;
397         for (const auto& info : fRects) {
398             string.appendf(
399                     "Color: 0x%08x, ORect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], "
400                     "AssistORect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], "
401                     "IRect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], Degen: %d",
402                     info.fColor.toBytes_RGBA(), info.fDevOutside.fLeft, info.fDevOutside.fTop,
403                     info.fDevOutside.fRight, info.fDevOutside.fBottom, info.fDevOutsideAssist.fLeft,
404                     info.fDevOutsideAssist.fTop, info.fDevOutsideAssist.fRight,
405                     info.fDevOutsideAssist.fBottom, info.fDevInside.fLeft, info.fDevInside.fTop,
406                     info.fDevInside.fRight, info.fDevInside.fBottom, info.fDegenerate);
407         }
408         string += fHelper.dumpInfo();
409         string += INHERITED::dumpInfo();
410         return string;
411     }
412 #endif
413 
fixedFunctionFlags() const414     FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
415 
finalize(const GrCaps & caps,const GrAppliedClip * clip,bool hasMixedSampledCoverage,GrClampType clampType)416     GrProcessorSet::Analysis finalize(
417             const GrCaps& caps, const GrAppliedClip* clip, bool hasMixedSampledCoverage,
418             GrClampType clampType) override {
419         return fHelper.finalizeProcessors(
420                 caps, clip, hasMixedSampledCoverage, clampType,
421                 GrProcessorAnalysisCoverage::kSingleChannel, &fRects.back().fColor, &fWideColor);
422     }
423 
424 private:
425     void onPrepareDraws(Target*) override;
426     void onExecute(GrOpFlushState*, const SkRect& chainBounds) override;
427 
428     static const int kMiterIndexCnt = 3 * 24;
429     static const int kMiterVertexCnt = 16;
430     static const int kNumMiterRectsInIndexBuffer = 256;
431 
432     static const int kBevelIndexCnt = 48 + 36 + 24;
433     static const int kBevelVertexCnt = 24;
434     static const int kNumBevelRectsInIndexBuffer = 256;
435 
436     static sk_sp<const GrGpuBuffer> GetIndexBuffer(GrResourceProvider*, bool miterStroke);
437 
viewMatrix() const438     const SkMatrix& viewMatrix() const { return fViewMatrix; }
miterStroke() const439     bool miterStroke() const { return fMiterStroke; }
440 
441     CombineResult onCombineIfPossible(GrOp* t, const GrCaps&) override;
442 
443     void generateAAStrokeRectGeometry(GrVertexWriter& vertices,
444                                       const SkPMColor4f& color,
445                                       bool wideColor,
446                                       const SkRect& devOutside,
447                                       const SkRect& devOutsideAssist,
448                                       const SkRect& devInside,
449                                       bool miterStroke,
450                                       bool degenerate,
451                                       bool tweakAlphaForCoverage) const;
452 
453     // TODO support AA rotated stroke rects by copying around view matrices
454     struct RectInfo {
455         SkPMColor4f fColor;
456         SkRect fDevOutside;
457         SkRect fDevOutsideAssist;
458         SkRect fDevInside;
459         bool fDegenerate;
460     };
461 
462     Helper fHelper;
463     SkSTArray<1, RectInfo, true> fRects;
464     SkMatrix fViewMatrix;
465     bool fMiterStroke;
466     bool fWideColor;
467 
468     typedef GrMeshDrawOp INHERITED;
469 };
470 
onPrepareDraws(Target * target)471 void AAStrokeRectOp::onPrepareDraws(Target* target) {
472     sk_sp<GrGeometryProcessor> gp(create_aa_stroke_rect_gp(target->caps().shaderCaps(),
473                                                            fHelper.compatibleWithCoverageAsAlpha(),
474                                                            this->viewMatrix(),
475                                                            fHelper.usesLocalCoords(),
476                                                            fWideColor));
477     if (!gp) {
478         SkDebugf("Couldn't create GrGeometryProcessor\n");
479         return;
480     }
481 
482     int innerVertexNum = 4;
483     int outerVertexNum = this->miterStroke() ? 4 : 8;
484     int verticesPerInstance = (outerVertexNum + innerVertexNum) * 2;
485     int indicesPerInstance = this->miterStroke() ? kMiterIndexCnt : kBevelIndexCnt;
486     int instanceCount = fRects.count();
487 
488     sk_sp<const GrGpuBuffer> indexBuffer =
489             GetIndexBuffer(target->resourceProvider(), this->miterStroke());
490     if (!indexBuffer) {
491         SkDebugf("Could not allocate indices\n");
492         return;
493     }
494     PatternHelper helper(target, GrPrimitiveType::kTriangles, gp->vertexStride(),
495                          std::move(indexBuffer), verticesPerInstance, indicesPerInstance,
496                          instanceCount);
497     GrVertexWriter vertices{ helper.vertices() };
498     if (!vertices.fPtr) {
499         SkDebugf("Could not allocate vertices\n");
500         return;
501     }
502 
503     for (int i = 0; i < instanceCount; i++) {
504         const RectInfo& info = fRects[i];
505         this->generateAAStrokeRectGeometry(vertices,
506                                            info.fColor,
507                                            fWideColor,
508                                            info.fDevOutside,
509                                            info.fDevOutsideAssist,
510                                            info.fDevInside,
511                                            fMiterStroke,
512                                            info.fDegenerate,
513                                            fHelper.compatibleWithCoverageAsAlpha());
514     }
515     helper.recordDraw(target, std::move(gp));
516 }
517 
onExecute(GrOpFlushState * flushState,const SkRect & chainBounds)518 void AAStrokeRectOp::onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) {
519     fHelper.executeDrawsAndUploads(this, flushState, chainBounds);
520 }
521 
GetIndexBuffer(GrResourceProvider * resourceProvider,bool miterStroke)522 sk_sp<const GrGpuBuffer> AAStrokeRectOp::GetIndexBuffer(GrResourceProvider* resourceProvider,
523                                                         bool miterStroke) {
524     if (miterStroke) {
525         // clang-format off
526         static const uint16_t gMiterIndices[] = {
527             0 + 0, 1 + 0, 5 + 0, 5 + 0, 4 + 0, 0 + 0,
528             1 + 0, 2 + 0, 6 + 0, 6 + 0, 5 + 0, 1 + 0,
529             2 + 0, 3 + 0, 7 + 0, 7 + 0, 6 + 0, 2 + 0,
530             3 + 0, 0 + 0, 4 + 0, 4 + 0, 7 + 0, 3 + 0,
531 
532             0 + 4, 1 + 4, 5 + 4, 5 + 4, 4 + 4, 0 + 4,
533             1 + 4, 2 + 4, 6 + 4, 6 + 4, 5 + 4, 1 + 4,
534             2 + 4, 3 + 4, 7 + 4, 7 + 4, 6 + 4, 2 + 4,
535             3 + 4, 0 + 4, 4 + 4, 4 + 4, 7 + 4, 3 + 4,
536 
537             0 + 8, 1 + 8, 5 + 8, 5 + 8, 4 + 8, 0 + 8,
538             1 + 8, 2 + 8, 6 + 8, 6 + 8, 5 + 8, 1 + 8,
539             2 + 8, 3 + 8, 7 + 8, 7 + 8, 6 + 8, 2 + 8,
540             3 + 8, 0 + 8, 4 + 8, 4 + 8, 7 + 8, 3 + 8,
541         };
542         // clang-format on
543         GR_STATIC_ASSERT(SK_ARRAY_COUNT(gMiterIndices) == kMiterIndexCnt);
544         GR_DEFINE_STATIC_UNIQUE_KEY(gMiterIndexBufferKey);
545         return resourceProvider->findOrCreatePatternedIndexBuffer(
546                 gMiterIndices, kMiterIndexCnt, kNumMiterRectsInIndexBuffer, kMiterVertexCnt,
547                 gMiterIndexBufferKey);
548     } else {
549         /**
550          * As in miter-stroke, index = a + b, and a is the current index, b is the shift
551          * from the first index. The index layout:
552          * outer AA line: 0~3, 4~7
553          * outer edge:    8~11, 12~15
554          * inner edge:    16~19
555          * inner AA line: 20~23
556          * Following comes a bevel-stroke rect and its indices:
557          *
558          *           4                                 7
559          *            *********************************
560          *          *   ______________________________  *
561          *         *  / 12                          15 \  *
562          *        *  /                                  \  *
563          *     0 *  |8     16_____________________19  11 |  * 3
564          *       *  |       |                    |       |  *
565          *       *  |       |  ****************  |       |  *
566          *       *  |       |  * 20        23 *  |       |  *
567          *       *  |       |  *              *  |       |  *
568          *       *  |       |  * 21        22 *  |       |  *
569          *       *  |       |  ****************  |       |  *
570          *       *  |       |____________________|       |  *
571          *     1 *  |9    17                      18   10|  * 2
572          *        *  \                                  /  *
573          *         *  \13 __________________________14/  *
574          *          *                                   *
575          *           **********************************
576          *          5                                  6
577          */
578         // clang-format off
579         static const uint16_t gBevelIndices[] = {
580             // Draw outer AA, from outer AA line to outer edge, shift is 0.
581             0 + 0, 1 + 0,  9 + 0,  9 + 0,  8 + 0, 0 + 0,
582             1 + 0, 5 + 0, 13 + 0, 13 + 0,  9 + 0, 1 + 0,
583             5 + 0, 6 + 0, 14 + 0, 14 + 0, 13 + 0, 5 + 0,
584             6 + 0, 2 + 0, 10 + 0, 10 + 0, 14 + 0, 6 + 0,
585             2 + 0, 3 + 0, 11 + 0, 11 + 0, 10 + 0, 2 + 0,
586             3 + 0, 7 + 0, 15 + 0, 15 + 0, 11 + 0, 3 + 0,
587             7 + 0, 4 + 0, 12 + 0, 12 + 0, 15 + 0, 7 + 0,
588             4 + 0, 0 + 0,  8 + 0,  8 + 0, 12 + 0, 4 + 0,
589 
590             // Draw the stroke, from outer edge to inner edge, shift is 8.
591             0 + 8, 1 + 8, 9 + 8, 9 + 8, 8 + 8, 0 + 8,
592             1 + 8, 5 + 8, 9 + 8,
593             5 + 8, 6 + 8, 10 + 8, 10 + 8, 9 + 8, 5 + 8,
594             6 + 8, 2 + 8, 10 + 8,
595             2 + 8, 3 + 8, 11 + 8, 11 + 8, 10 + 8, 2 + 8,
596             3 + 8, 7 + 8, 11 + 8,
597             7 + 8, 4 + 8, 8 + 8, 8 + 8, 11 + 8, 7 + 8,
598             4 + 8, 0 + 8, 8 + 8,
599 
600             // Draw the inner AA, from inner edge to inner AA line, shift is 16.
601             0 + 16, 1 + 16, 5 + 16, 5 + 16, 4 + 16, 0 + 16,
602             1 + 16, 2 + 16, 6 + 16, 6 + 16, 5 + 16, 1 + 16,
603             2 + 16, 3 + 16, 7 + 16, 7 + 16, 6 + 16, 2 + 16,
604             3 + 16, 0 + 16, 4 + 16, 4 + 16, 7 + 16, 3 + 16,
605         };
606         // clang-format on
607         GR_STATIC_ASSERT(SK_ARRAY_COUNT(gBevelIndices) == kBevelIndexCnt);
608 
609         GR_DEFINE_STATIC_UNIQUE_KEY(gBevelIndexBufferKey);
610         return resourceProvider->findOrCreatePatternedIndexBuffer(
611                 gBevelIndices, kBevelIndexCnt, kNumBevelRectsInIndexBuffer, kBevelVertexCnt,
612                 gBevelIndexBufferKey);
613     }
614 }
615 
onCombineIfPossible(GrOp * t,const GrCaps & caps)616 GrOp::CombineResult AAStrokeRectOp::onCombineIfPossible(GrOp* t, const GrCaps& caps) {
617     AAStrokeRectOp* that = t->cast<AAStrokeRectOp>();
618 
619     if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
620         return CombineResult::kCannotCombine;
621     }
622 
623     // TODO combine across miterstroke changes
624     if (this->miterStroke() != that->miterStroke()) {
625         return CombineResult::kCannotCombine;
626     }
627 
628     // We apply the viewmatrix to the rect points on the cpu.  However, if the pipeline uses
629     // local coords then we won't be able to combine. TODO: Upload local coords as an attribute.
630     if (fHelper.usesLocalCoords() && !this->viewMatrix().cheapEqualTo(that->viewMatrix())) {
631         return CombineResult::kCannotCombine;
632     }
633 
634     fRects.push_back_n(that->fRects.count(), that->fRects.begin());
635     fWideColor |= that->fWideColor;
636     return CombineResult::kMerged;
637 }
638 
setup_scale(int * scale,SkScalar inset)639 static void setup_scale(int* scale, SkScalar inset) {
640     if (inset < SK_ScalarHalf) {
641         *scale = SkScalarFloorToInt(512.0f * inset / (inset + SK_ScalarHalf));
642         SkASSERT(*scale >= 0 && *scale <= 255);
643     } else {
644         *scale = 0xff;
645     }
646 }
647 
generateAAStrokeRectGeometry(GrVertexWriter & vertices,const SkPMColor4f & color,bool wideColor,const SkRect & devOutside,const SkRect & devOutsideAssist,const SkRect & devInside,bool miterStroke,bool degenerate,bool tweakAlphaForCoverage) const648 void AAStrokeRectOp::generateAAStrokeRectGeometry(GrVertexWriter& vertices,
649                                                   const SkPMColor4f& color,
650                                                   bool wideColor,
651                                                   const SkRect& devOutside,
652                                                   const SkRect& devOutsideAssist,
653                                                   const SkRect& devInside,
654                                                   bool miterStroke,
655                                                   bool degenerate,
656                                                   bool tweakAlphaForCoverage) const {
657     // We create vertices for four nested rectangles. There are two ramps from 0 to full
658     // coverage, one on the exterior of the stroke and the other on the interior.
659 
660     // TODO: this only really works if the X & Y margins are the same all around
661     // the rect (or if they are all >= 1.0).
662     SkScalar inset;
663     if (!degenerate) {
664         inset = SkMinScalar(SK_Scalar1, devOutside.fRight - devInside.fRight);
665         inset = SkMinScalar(inset, devInside.fLeft - devOutside.fLeft);
666         inset = SkMinScalar(inset, devInside.fTop - devOutside.fTop);
667         if (miterStroke) {
668             inset = SK_ScalarHalf * SkMinScalar(inset, devOutside.fBottom - devInside.fBottom);
669         } else {
670             inset = SK_ScalarHalf *
671                     SkMinScalar(inset, devOutsideAssist.fBottom - devInside.fBottom);
672         }
673         SkASSERT(inset >= 0);
674     } else {
675         // TODO use real devRect here
676         inset = SkMinScalar(devOutside.width(), SK_Scalar1);
677         inset = SK_ScalarHalf *
678                 SkMinScalar(inset, SkTMax(devOutside.height(), devOutsideAssist.height()));
679     }
680 
681     auto inset_fan = [](const SkRect& r, SkScalar dx, SkScalar dy) {
682         return GrVertexWriter::TriFanFromRect(r.makeInset(dx, dy));
683     };
684 
685     auto maybe_coverage = [tweakAlphaForCoverage](float coverage) {
686         return GrVertexWriter::If(!tweakAlphaForCoverage, coverage);
687     };
688 
689     GrVertexColor outerColor(tweakAlphaForCoverage ? SK_PMColor4fTRANSPARENT : color, wideColor);
690 
691     // Outermost rect
692     vertices.writeQuad(inset_fan(devOutside, -SK_ScalarHalf, -SK_ScalarHalf),
693                        outerColor,
694                        maybe_coverage(0.0f));
695 
696     if (!miterStroke) {
697         // Second outermost
698         vertices.writeQuad(inset_fan(devOutsideAssist, -SK_ScalarHalf, -SK_ScalarHalf),
699                            outerColor,
700                            maybe_coverage(0.0f));
701     }
702 
703     // scale is the coverage for the the inner two rects.
704     int scale;
705     setup_scale(&scale, inset);
706 
707     float innerCoverage = GrNormalizeByteToFloat(scale);
708     SkPMColor4f scaledColor = color * innerCoverage;
709     GrVertexColor innerColor(tweakAlphaForCoverage ? scaledColor : color, wideColor);
710 
711     // Inner rect
712     vertices.writeQuad(inset_fan(devOutside, inset, inset),
713                        innerColor,
714                        maybe_coverage(innerCoverage));
715 
716     if (!miterStroke) {
717         // Second inner
718         vertices.writeQuad(inset_fan(devOutsideAssist, inset, inset),
719                            innerColor,
720                            maybe_coverage(innerCoverage));
721     }
722 
723     if (!degenerate) {
724         vertices.writeQuad(inset_fan(devInside, -inset, -inset),
725                            innerColor,
726                            maybe_coverage(innerCoverage));
727 
728         // The innermost rect has 0 coverage...
729         vertices.writeQuad(inset_fan(devInside, SK_ScalarHalf, SK_ScalarHalf),
730                            outerColor,
731                            maybe_coverage(0.0f));
732     } else {
733         // When the interior rect has become degenerate we smoosh to a single point
734         SkASSERT(devInside.fLeft == devInside.fRight && devInside.fTop == devInside.fBottom);
735 
736         vertices.writeQuad(GrVertexWriter::TriFanFromRect(devInside),
737                            innerColor,
738                            maybe_coverage(innerCoverage));
739 
740         // ... unless we are degenerate, in which case we must apply the scaled coverage
741         vertices.writeQuad(GrVertexWriter::TriFanFromRect(devInside),
742                            innerColor,
743                            maybe_coverage(innerCoverage));
744     }
745 }
746 
747 }  // anonymous namespace
748 
749 namespace GrStrokeRectOp {
750 
Make(GrRecordingContext * context,GrPaint && paint,GrAAType aaType,const SkMatrix & viewMatrix,const SkRect & rect,const SkStrokeRec & stroke)751 std::unique_ptr<GrDrawOp> Make(GrRecordingContext* context,
752                                GrPaint&& paint,
753                                GrAAType aaType,
754                                const SkMatrix& viewMatrix,
755                                const SkRect& rect,
756                                const SkStrokeRec& stroke) {
757     if (aaType == GrAAType::kCoverage) {
758         // The AA op only supports axis-aligned rectangles
759         if (!viewMatrix.rectStaysRect()) {
760             return nullptr;
761         }
762         return AAStrokeRectOp::Make(context, std::move(paint), viewMatrix, rect, stroke);
763     } else {
764         return NonAAStrokeRectOp::Make(context, std::move(paint), viewMatrix, rect, stroke, aaType);
765     }
766 }
767 
MakeNested(GrRecordingContext * context,GrPaint && paint,const SkMatrix & viewMatrix,const SkRect rects[2])768 std::unique_ptr<GrDrawOp> MakeNested(GrRecordingContext* context,
769                                      GrPaint&& paint,
770                                      const SkMatrix& viewMatrix,
771                                      const SkRect rects[2]) {
772     SkASSERT(viewMatrix.rectStaysRect());
773     SkASSERT(!rects[0].isEmpty() && !rects[1].isEmpty());
774 
775     SkRect devOutside, devInside;
776     viewMatrix.mapRect(&devOutside, rects[0]);
777     viewMatrix.mapRect(&devInside, rects[1]);
778     if (devInside.isEmpty()) {
779         if (devOutside.isEmpty()) {
780             return nullptr;
781         }
782         return GrFillRectOp::Make(context, std::move(paint), GrAAType::kCoverage,
783                                   GrQuadAAFlags::kAll,
784                                   GrQuad::MakeFromRect(rects[0], viewMatrix),
785                                   GrQuad(rects[0]));
786     }
787 
788     return AAStrokeRectOp::Make(context, std::move(paint), viewMatrix, devOutside, devInside);
789 }
790 
791 }  // namespace GrStrokeRectOp
792 
793 #if GR_TEST_UTILS
794 
795 #include "src/gpu/GrDrawOpTest.h"
796 
GR_DRAW_OP_TEST_DEFINE(NonAAStrokeRectOp)797 GR_DRAW_OP_TEST_DEFINE(NonAAStrokeRectOp) {
798     SkMatrix viewMatrix = GrTest::TestMatrix(random);
799     SkRect rect = GrTest::TestRect(random);
800     SkScalar strokeWidth = random->nextBool() ? 0.0f : 2.0f;
801     SkPaint strokePaint;
802     strokePaint.setStrokeWidth(strokeWidth);
803     strokePaint.setStyle(SkPaint::kStroke_Style);
804     strokePaint.setStrokeJoin(SkPaint::kMiter_Join);
805     SkStrokeRec strokeRec(strokePaint);
806     GrAAType aaType = GrAAType::kNone;
807     if (numSamples > 1) {
808         aaType = random->nextBool() ? GrAAType::kMSAA : GrAAType::kNone;
809     }
810     return NonAAStrokeRectOp::Make(context, std::move(paint), viewMatrix, rect, strokeRec, aaType);
811 }
812 
GR_DRAW_OP_TEST_DEFINE(AAStrokeRectOp)813 GR_DRAW_OP_TEST_DEFINE(AAStrokeRectOp) {
814     bool miterStroke = random->nextBool();
815 
816     // Create either a empty rect or a non-empty rect.
817     SkRect rect =
818             random->nextBool() ? SkRect::MakeXYWH(10, 10, 50, 40) : SkRect::MakeXYWH(6, 7, 0, 0);
819     SkScalar minDim = SkMinScalar(rect.width(), rect.height());
820     SkScalar strokeWidth = random->nextUScalar1() * minDim;
821 
822     SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);
823     rec.setStrokeStyle(strokeWidth);
824     rec.setStrokeParams(SkPaint::kButt_Cap,
825                         miterStroke ? SkPaint::kMiter_Join : SkPaint::kBevel_Join, 1.f);
826     SkMatrix matrix = GrTest::TestMatrixRectStaysRect(random);
827     return AAStrokeRectOp::Make(context, std::move(paint), matrix, rect, rec);
828 }
829 
830 #endif
831