• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 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/ganesh/ops/DashOp.h"
9 
10 #include "include/gpu/GrRecordingContext.h"
11 #include "src/core/SkMatrixPriv.h"
12 #include "src/core/SkPointPriv.h"
13 #include "src/gpu/BufferWriter.h"
14 #include "src/gpu/KeyBuilder.h"
15 #include "src/gpu/ganesh/GrAppliedClip.h"
16 #include "src/gpu/ganesh/GrCaps.h"
17 #include "src/gpu/ganesh/GrDefaultGeoProcFactory.h"
18 #include "src/gpu/ganesh/GrGeometryProcessor.h"
19 #include "src/gpu/ganesh/GrMemoryPool.h"
20 #include "src/gpu/ganesh/GrOpFlushState.h"
21 #include "src/gpu/ganesh/GrProcessor.h"
22 #include "src/gpu/ganesh/GrProcessorUnitTest.h"
23 #include "src/gpu/ganesh/GrProgramInfo.h"
24 #include "src/gpu/ganesh/GrRecordingContextPriv.h"
25 #include "src/gpu/ganesh/GrStyle.h"
26 #include "src/gpu/ganesh/SkGr.h"
27 #include "src/gpu/ganesh/geometry/GrQuad.h"
28 #include "src/gpu/ganesh/glsl/GrGLSLFragmentShaderBuilder.h"
29 #include "src/gpu/ganesh/glsl/GrGLSLProgramDataManager.h"
30 #include "src/gpu/ganesh/glsl/GrGLSLUniformHandler.h"
31 #include "src/gpu/ganesh/glsl/GrGLSLVarying.h"
32 #include "src/gpu/ganesh/glsl/GrGLSLVertexGeoBuilder.h"
33 #include "src/gpu/ganesh/ops/GrMeshDrawOp.h"
34 #include "src/gpu/ganesh/ops/GrSimpleMeshDrawOpHelper.h"
35 
36 using namespace skia_private;
37 
38 using AAMode = skgpu::ganesh::DashOp::AAMode;
39 
40 #if defined(GR_TEST_UTILS)
41 constexpr int kAAModeCnt = static_cast<int>(skgpu::ganesh::DashOp::AAMode::kCoverageWithMSAA) + 1;
42 #endif
43 
44 namespace skgpu::ganesh::DashOp {
45 
46 namespace {
47 
calc_dash_scaling(SkScalar * parallelScale,SkScalar * perpScale,const SkMatrix & viewMatrix,const SkPoint pts[2])48 void calc_dash_scaling(SkScalar* parallelScale, SkScalar* perpScale,
49                        const SkMatrix& viewMatrix, const SkPoint pts[2]) {
50     SkVector vecSrc = pts[1] - pts[0];
51     if (pts[1] == pts[0]) {
52         vecSrc.set(1.0, 0.0);
53     }
54     SkScalar magSrc = vecSrc.length();
55     SkScalar invSrc = magSrc ? SkScalarInvert(magSrc) : 0;
56     vecSrc.scale(invSrc);
57 
58     SkVector vecSrcPerp;
59     SkPointPriv::RotateCW(vecSrc, &vecSrcPerp);
60     viewMatrix.mapVectors(&vecSrc, 1);
61     viewMatrix.mapVectors(&vecSrcPerp, 1);
62 
63     // parallelScale tells how much to scale along the line parallel to the dash line
64     // perpScale tells how much to scale in the direction perpendicular to the dash line
65     *parallelScale = vecSrc.length();
66     *perpScale = vecSrcPerp.length();
67 }
68 
69 // calculates the rotation needed to aligned pts to the x axis with pts[0] < pts[1]
70 // Stores the rotation matrix in rotMatrix, and the mapped points in ptsRot
align_to_x_axis(const SkPoint pts[2],SkMatrix * rotMatrix,SkPoint ptsRot[2]=nullptr)71 void align_to_x_axis(const SkPoint pts[2], SkMatrix* rotMatrix, SkPoint ptsRot[2] = nullptr) {
72     SkVector vec = pts[1] - pts[0];
73     if (pts[1] == pts[0]) {
74         vec.set(1.0, 0.0);
75     }
76     SkScalar mag = vec.length();
77     SkScalar inv = mag ? SkScalarInvert(mag) : 0;
78 
79     vec.scale(inv);
80     rotMatrix->setSinCos(-vec.fY, vec.fX, pts[0].fX, pts[0].fY);
81     if (ptsRot) {
82         rotMatrix->mapPoints(ptsRot, pts, 2);
83         // correction for numerical issues if map doesn't make ptsRot exactly horizontal
84         ptsRot[1].fY = pts[0].fY;
85     }
86 }
87 
88 // Assumes phase < sum of all intervals
calc_start_adjustment(const SkScalar intervals[2],SkScalar phase)89 SkScalar calc_start_adjustment(const SkScalar intervals[2], SkScalar phase) {
90     SkASSERT(phase < intervals[0] + intervals[1]);
91     if (phase >= intervals[0] && phase != 0) {
92         SkScalar srcIntervalLen = intervals[0] + intervals[1];
93         return srcIntervalLen - phase;
94     }
95     return 0;
96 }
97 
calc_end_adjustment(const SkScalar intervals[2],const SkPoint pts[2],SkScalar phase,SkScalar * endingInt)98 SkScalar calc_end_adjustment(const SkScalar intervals[2], const SkPoint pts[2],
99                              SkScalar phase, SkScalar* endingInt) {
100     if (pts[1].fX <= pts[0].fX) {
101         return 0;
102     }
103     SkScalar srcIntervalLen = intervals[0] + intervals[1];
104     SkScalar totalLen = pts[1].fX - pts[0].fX;
105     SkScalar temp = totalLen / srcIntervalLen;
106     SkScalar numFullIntervals = SkScalarFloorToScalar(temp);
107     *endingInt = totalLen - numFullIntervals * srcIntervalLen + phase;
108     temp = *endingInt / srcIntervalLen;
109     *endingInt = *endingInt - SkScalarFloorToScalar(temp) * srcIntervalLen;
110     if (0 == *endingInt) {
111         *endingInt = srcIntervalLen;
112     }
113     if (*endingInt > intervals[0]) {
114         return *endingInt - intervals[0];
115     }
116     return 0;
117 }
118 
119 enum DashCap {
120     kRound_DashCap,
121     kNonRound_DashCap,
122 };
123 
setup_dashed_rect(const SkRect & rect,VertexWriter & vertices,const SkMatrix & matrix,SkScalar offset,SkScalar bloatX,SkScalar len,SkScalar startInterval,SkScalar endInterval,SkScalar strokeWidth,SkScalar perpScale,DashCap cap)124 void setup_dashed_rect(const SkRect& rect,
125                        VertexWriter& vertices,
126                        const SkMatrix& matrix,
127                        SkScalar offset,
128                        SkScalar bloatX,
129                        SkScalar len,
130                        SkScalar startInterval,
131                        SkScalar endInterval,
132                        SkScalar strokeWidth,
133                        SkScalar perpScale,
134                        DashCap cap) {
135     SkScalar intervalLength = startInterval + endInterval;
136     // 'dashRect' gets interpolated over the rendered 'rect'. For y we want the perpendicular signed
137     // distance from the stroke center line in device space. 'perpScale' is the scale factor applied
138     // to the y dimension of 'rect' isolated from 'matrix'.
139     SkScalar halfDevRectHeight = rect.height() * perpScale / 2.f;
140     SkRect dashRect = { offset       - bloatX, -halfDevRectHeight,
141                         offset + len + bloatX,  halfDevRectHeight };
142 
143     if (kRound_DashCap == cap) {
144         SkScalar radius = SkScalarHalf(strokeWidth) - 0.5f;
145         SkScalar centerX = SkScalarHalf(endInterval);
146 
147         vertices.writeQuad(GrQuad::MakeFromRect(rect, matrix),
148                            VertexWriter::TriStripFromRect(dashRect),
149                            intervalLength,
150                            radius,
151                            centerX);
152     } else {
153         SkASSERT(kNonRound_DashCap == cap);
154         SkScalar halfOffLen = SkScalarHalf(endInterval);
155         SkScalar halfStroke = SkScalarHalf(strokeWidth);
156         SkRect rectParam;
157         rectParam.setLTRB(halfOffLen                 + 0.5f, -halfStroke + 0.5f,
158                           halfOffLen + startInterval - 0.5f,  halfStroke - 0.5f);
159 
160         vertices.writeQuad(GrQuad::MakeFromRect(rect, matrix),
161                            VertexWriter::TriStripFromRect(dashRect),
162                            intervalLength,
163                            rectParam);
164     }
165 }
166 
167 /**
168  * An GrGeometryProcessor that renders a dashed line.
169  * This GrGeometryProcessor is meant for dashed lines that only have a single on/off interval pair.
170  * Bounding geometry is rendered and the effect computes coverage based on the fragment's
171  * position relative to the dashed line.
172  */
173 GrGeometryProcessor* make_dash_gp(SkArenaAlloc* arena,
174                                   const SkPMColor4f&,
175                                   AAMode aaMode,
176                                   DashCap cap,
177                                   const SkMatrix& localMatrix,
178                                   bool usesLocalCoords);
179 
180 class DashOpImpl final : public GrMeshDrawOp {
181 public:
182     DEFINE_OP_CLASS_ID
183 
184     struct LineData {
185         SkMatrix fViewMatrix;
186         SkMatrix fSrcRotInv;
187         SkPoint fPtsRot[2];
188         SkScalar fSrcStrokeWidth;
189         SkScalar fPhase;
190         SkScalar fIntervals[2];
191         SkScalar fParallelScale;
192         SkScalar fPerpendicularScale;
193     };
194 
Make(GrRecordingContext * context,GrPaint && paint,const LineData & geometry,SkPaint::Cap cap,AAMode aaMode,bool fullDash,const GrUserStencilSettings * stencilSettings)195     static GrOp::Owner Make(GrRecordingContext* context,
196                             GrPaint&& paint,
197                             const LineData& geometry,
198                             SkPaint::Cap cap,
199                             AAMode aaMode, bool fullDash,
200                             const GrUserStencilSettings* stencilSettings) {
201         return GrOp::Make<DashOpImpl>(context, std::move(paint), geometry, cap,
202                                       aaMode, fullDash, stencilSettings);
203     }
204 
name() const205     const char* name() const override { return "DashOp"; }
206 
visitProxies(const GrVisitProxyFunc & func) const207     void visitProxies(const GrVisitProxyFunc& func) const override {
208         if (fProgramInfo) {
209             fProgramInfo->visitFPProxies(func);
210         } else {
211             fProcessorSet.visitProxies(func);
212         }
213     }
214 
fixedFunctionFlags() const215     FixedFunctionFlags fixedFunctionFlags() const override {
216         FixedFunctionFlags flags = FixedFunctionFlags::kNone;
217         if (AAMode::kCoverageWithMSAA == fAAMode) {
218             flags |= FixedFunctionFlags::kUsesHWAA;
219         }
220         if (fStencilSettings != &GrUserStencilSettings::kUnused) {
221             flags |= FixedFunctionFlags::kUsesStencil;
222         }
223         return flags;
224     }
225 
finalize(const GrCaps & caps,const GrAppliedClip * clip,GrClampType clampType)226     GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
227                                       GrClampType clampType) override {
228         GrProcessorAnalysisCoverage coverage = GrProcessorAnalysisCoverage::kSingleChannel;
229         auto analysis = fProcessorSet.finalize(fColor, coverage, clip, fStencilSettings, caps,
230                                                clampType, &fColor);
231         fUsesLocalCoords = analysis.usesLocalCoords();
232         return analysis;
233     }
234 
235 private:
236     friend class GrOp; // for ctor
237 
DashOpImpl(GrPaint && paint,const LineData & geometry,SkPaint::Cap cap,AAMode aaMode,bool fullDash,const GrUserStencilSettings * stencilSettings)238     DashOpImpl(GrPaint&& paint, const LineData& geometry, SkPaint::Cap cap, AAMode aaMode,
239                bool fullDash, const GrUserStencilSettings* stencilSettings)
240             : INHERITED(ClassID())
241             , fColor(paint.getColor4f())
242             , fFullDash(fullDash)
243             , fCap(cap)
244             , fAAMode(aaMode)
245             , fProcessorSet(std::move(paint))
246             , fStencilSettings(stencilSettings) {
247         fLines.push_back(geometry);
248 
249         // compute bounds
250         SkScalar halfStrokeWidth = 0.5f * geometry.fSrcStrokeWidth;
251         SkScalar xBloat = SkPaint::kButt_Cap == cap ? 0 : halfStrokeWidth;
252         SkRect bounds;
253         bounds.set(geometry.fPtsRot[0], geometry.fPtsRot[1]);
254         bounds.outset(xBloat, halfStrokeWidth);
255 
256         // Note, we actually create the combined matrix here, and save the work
257         SkMatrix& combinedMatrix = fLines[0].fSrcRotInv;
258         combinedMatrix.postConcat(geometry.fViewMatrix);
259 
260         IsHairline zeroArea = geometry.fSrcStrokeWidth ? IsHairline::kNo : IsHairline::kYes;
261         HasAABloat aaBloat = (aaMode == AAMode::kNone) ? HasAABloat::kNo : HasAABloat::kYes;
262         this->setTransformedBounds(bounds, combinedMatrix, aaBloat, zeroArea);
263     }
264 
265     struct DashDraw {
DashDrawskgpu::ganesh::DashOp::__anonbbeec1240111::DashOpImpl::DashDraw266         DashDraw(const LineData& geo) {
267             memcpy(fPtsRot, geo.fPtsRot, sizeof(geo.fPtsRot));
268             memcpy(fIntervals, geo.fIntervals, sizeof(geo.fIntervals));
269             fPhase = geo.fPhase;
270         }
271         SkPoint fPtsRot[2];
272         SkScalar fIntervals[2];
273         SkScalar fPhase;
274         SkScalar fStartOffset;
275         SkScalar fStrokeWidth;
276         SkScalar fLineLength;
277         SkScalar fDevBloatX;
278         SkScalar fPerpendicularScale;
279         bool fLineDone;
280         bool fHasStartRect;
281         bool fHasEndRect;
282     };
283 
programInfo()284     GrProgramInfo* programInfo() override { return fProgramInfo; }
285 
onCreateProgramInfo(const GrCaps * caps,SkArenaAlloc * arena,const GrSurfaceProxyView & writeView,bool usesMSAASurface,GrAppliedClip && appliedClip,const GrDstProxyView & dstProxyView,GrXferBarrierFlags renderPassXferBarriers,GrLoadOp colorLoadOp)286     void onCreateProgramInfo(const GrCaps* caps,
287                              SkArenaAlloc* arena,
288                              const GrSurfaceProxyView& writeView,
289                              bool usesMSAASurface,
290                              GrAppliedClip&& appliedClip,
291                              const GrDstProxyView& dstProxyView,
292                              GrXferBarrierFlags renderPassXferBarriers,
293                              GrLoadOp colorLoadOp) override {
294 
295         DashCap capType = (this->cap() == SkPaint::kRound_Cap) ? kRound_DashCap : kNonRound_DashCap;
296 
297         GrGeometryProcessor* gp;
298         if (this->fullDash()) {
299             gp = make_dash_gp(arena, this->color(), this->aaMode(), capType,
300                               this->viewMatrix(), fUsesLocalCoords);
301         } else {
302             // Set up the vertex data for the line and start/end dashes
303             using namespace GrDefaultGeoProcFactory;
304             Color color(this->color());
305             LocalCoords::Type localCoordsType =
306                     fUsesLocalCoords ? LocalCoords::kUsePosition_Type : LocalCoords::kUnused_Type;
307             gp = MakeForDeviceSpace(arena,
308                                     color,
309                                     Coverage::kSolid_Type,
310                                     localCoordsType,
311                                     this->viewMatrix());
312         }
313 
314         if (!gp) {
315             SkDebugf("Could not create GrGeometryProcessor\n");
316             return;
317         }
318 
319         fProgramInfo = GrSimpleMeshDrawOpHelper::CreateProgramInfo(caps,
320                                                                    arena,
321                                                                    writeView,
322                                                                    usesMSAASurface,
323                                                                    std::move(appliedClip),
324                                                                    dstProxyView,
325                                                                    gp,
326                                                                    std::move(fProcessorSet),
327                                                                    GrPrimitiveType::kTriangles,
328                                                                    renderPassXferBarriers,
329                                                                    colorLoadOp,
330                                                                    GrPipeline::InputFlags::kNone,
331                                                                    fStencilSettings);
332     }
333 
onPrepareDraws(GrMeshDrawTarget * target)334     void onPrepareDraws(GrMeshDrawTarget* target) override {
335         int instanceCount = fLines.size();
336         SkPaint::Cap cap = this->cap();
337         DashCap capType = (SkPaint::kRound_Cap == cap) ? kRound_DashCap : kNonRound_DashCap;
338 
339         if (!fProgramInfo) {
340             this->createProgramInfo(target);
341             if (!fProgramInfo) {
342                 return;
343             }
344         }
345 
346         // useAA here means Edge AA or MSAA
347         bool useAA = this->aaMode() != AAMode::kNone;
348         bool fullDash = this->fullDash();
349 
350         // We do two passes over all of the dashes.  First we setup the start, end, and bounds,
351         // rectangles.  We preserve all of this work in the rects / draws arrays below.  Then we
352         // iterate again over these decomposed dashes to generate vertices
353         static const int kNumStackDashes = 128;
354         STArray<kNumStackDashes, SkRect, true> rects;
355         STArray<kNumStackDashes, DashDraw, true> draws;
356 
357         int totalRectCount = 0;
358         int rectOffset = 0;
359         rects.push_back_n(3 * instanceCount);
360         for (int i = 0; i < instanceCount; i++) {
361             const LineData& args = fLines[i];
362 
363             DashDraw& draw = draws.push_back(args);
364 
365             bool hasCap = SkPaint::kButt_Cap != cap;
366 
367             SkScalar halfSrcStroke = args.fSrcStrokeWidth * 0.5f;
368             if (halfSrcStroke == 0.0f || this->aaMode() != AAMode::kCoverageWithMSAA) {
369                 // In the non-MSAA case, we always want to at least stroke out half a pixel on each
370                 // side in device space. 0.5f / fPerpendicularScale gives us this min in src space.
371                 // This is also necessary when the stroke width is zero, to allow hairlines to draw.
372                 halfSrcStroke = std::max(halfSrcStroke, 0.5f / args.fPerpendicularScale);
373             }
374 
375             SkScalar strokeAdj = hasCap ? halfSrcStroke : 0.0f;
376             SkScalar startAdj = 0;
377 
378             bool lineDone = false;
379 
380             // Too simplify the algorithm, we always push back rects for start and end rect.
381             // Otherwise we'd have to track start / end rects for each individual geometry
382             SkRect& bounds = rects[rectOffset++];
383             SkRect& startRect = rects[rectOffset++];
384             SkRect& endRect = rects[rectOffset++];
385 
386             bool hasStartRect = false;
387             // If we are using AA, check to see if we are drawing a partial dash at the start. If so
388             // draw it separately here and adjust our start point accordingly
389             if (useAA) {
390                 if (draw.fPhase > 0 && draw.fPhase < draw.fIntervals[0]) {
391                     SkPoint startPts[2];
392                     startPts[0] = draw.fPtsRot[0];
393                     startPts[1].fY = startPts[0].fY;
394                     startPts[1].fX = std::min(startPts[0].fX + draw.fIntervals[0] - draw.fPhase,
395                                               draw.fPtsRot[1].fX);
396                     startRect.setBounds(startPts, 2);
397                     startRect.outset(strokeAdj, halfSrcStroke);
398 
399                     hasStartRect = true;
400                     startAdj = draw.fIntervals[0] + draw.fIntervals[1] - draw.fPhase;
401                 }
402             }
403 
404             // adjustments for start and end of bounding rect so we only draw dash intervals
405             // contained in the original line segment.
406             startAdj += calc_start_adjustment(draw.fIntervals, draw.fPhase);
407             if (startAdj != 0) {
408                 draw.fPtsRot[0].fX += startAdj;
409                 draw.fPhase = 0;
410             }
411             SkScalar endingInterval = 0;
412             SkScalar endAdj = calc_end_adjustment(draw.fIntervals, draw.fPtsRot, draw.fPhase,
413                                                   &endingInterval);
414             draw.fPtsRot[1].fX -= endAdj;
415             if (draw.fPtsRot[0].fX >= draw.fPtsRot[1].fX) {
416                 lineDone = true;
417             }
418 
419             bool hasEndRect = false;
420             // If we are using AA, check to see if we are drawing a partial dash at then end. If so
421             // draw it separately here and adjust our end point accordingly
422             if (useAA && !lineDone) {
423                 // If we adjusted the end then we will not be drawing a partial dash at the end.
424                 // If we didn't adjust the end point then we just need to make sure the ending
425                 // dash isn't a full dash
426                 if (0 == endAdj && endingInterval != draw.fIntervals[0]) {
427                     SkPoint endPts[2];
428                     endPts[1] = draw.fPtsRot[1];
429                     endPts[0].fY = endPts[1].fY;
430                     endPts[0].fX = endPts[1].fX - endingInterval;
431 
432                     endRect.setBounds(endPts, 2);
433                     endRect.outset(strokeAdj, halfSrcStroke);
434 
435                     hasEndRect = true;
436                     endAdj = endingInterval + draw.fIntervals[1];
437 
438                     draw.fPtsRot[1].fX -= endAdj;
439                     if (draw.fPtsRot[0].fX >= draw.fPtsRot[1].fX) {
440                         lineDone = true;
441                     }
442                 }
443             }
444 
445             if (draw.fPtsRot[0].fX == draw.fPtsRot[1].fX &&
446                 (0 != endAdj || 0 == startAdj) &&
447                 hasCap) {
448                 // At this point the fPtsRot[0]/[1] represent the start and end of the inner rect of
449                 // dashes that we want to draw. The only way they can be equal is if the on interval
450                 // is zero (or an edge case if the end of line ends at a full off interval, but this
451                 // is handled as well). Thus if the on interval is zero then we need to draw a cap
452                 // at this position if the stroke has caps. The spec says we only draw this point if
453                 // point lies between [start of line, end of line). Thus we check if we are at the
454                 // end (but not the start), and if so we don't draw the cap.
455                 lineDone = false;
456             }
457 
458             if (startAdj != 0) {
459                 draw.fPhase = 0;
460             }
461 
462             // Change the dashing info from src space into device space
463             SkScalar* devIntervals = draw.fIntervals;
464             devIntervals[0] = draw.fIntervals[0] * args.fParallelScale;
465             devIntervals[1] = draw.fIntervals[1] * args.fParallelScale;
466             SkScalar devPhase = draw.fPhase * args.fParallelScale;
467             SkScalar strokeWidth = args.fSrcStrokeWidth * args.fPerpendicularScale;
468 
469             if ((strokeWidth < 1.f && !useAA) || 0.f == strokeWidth) {
470                 strokeWidth = 1.f;
471             }
472 
473             SkScalar halfDevStroke = strokeWidth * 0.5f;
474 
475             if (SkPaint::kSquare_Cap == cap) {
476                 // add cap to on interval and remove from off interval
477                 devIntervals[0] += strokeWidth;
478                 devIntervals[1] -= strokeWidth;
479             }
480             SkScalar startOffset = devIntervals[1] * 0.5f + devPhase;
481 
482             SkScalar devBloatX = 0.0f;
483             SkScalar devBloatY = 0.0f;
484             switch (this->aaMode()) {
485                 case AAMode::kNone:
486                     break;
487                 case AAMode::kCoverage:
488                     // For EdgeAA, we bloat in X & Y for both square and round caps.
489                     devBloatX = 0.5f;
490                     devBloatY = 0.5f;
491                     break;
492                 case AAMode::kCoverageWithMSAA:
493                     // For MSAA, we only bloat in Y for round caps.
494                     devBloatY = (cap == SkPaint::kRound_Cap) ? 0.5f : 0.0f;
495                     break;
496             }
497 
498             SkScalar bloatX = devBloatX / args.fParallelScale;
499             SkScalar bloatY = devBloatY / args.fPerpendicularScale;
500 
501             if (devIntervals[1] <= 0.f && useAA) {
502                 // Case when we end up drawing a solid AA rect
503                 // Reset the start rect to draw this single solid rect
504                 // but it requires to upload a new intervals uniform so we can mimic
505                 // one giant dash
506                 draw.fPtsRot[0].fX -= hasStartRect ? startAdj : 0;
507                 draw.fPtsRot[1].fX += hasEndRect ? endAdj : 0;
508                 startRect.setBounds(draw.fPtsRot, 2);
509                 startRect.outset(strokeAdj, halfSrcStroke);
510                 hasStartRect = true;
511                 hasEndRect = false;
512                 lineDone = true;
513 
514                 SkPoint devicePts[2];
515                 args.fSrcRotInv.mapPoints(devicePts, draw.fPtsRot, 2);
516                 SkScalar lineLength = SkPoint::Distance(devicePts[0], devicePts[1]);
517                 if (hasCap) {
518                     lineLength += 2.f * halfDevStroke;
519                 }
520                 devIntervals[0] = lineLength;
521             }
522 
523             totalRectCount += !lineDone ? 1 : 0;
524             totalRectCount += hasStartRect ? 1 : 0;
525             totalRectCount += hasEndRect ? 1 : 0;
526 
527             if (SkPaint::kRound_Cap == cap && 0 != args.fSrcStrokeWidth) {
528                 // need to adjust this for round caps to correctly set the dashPos attrib on
529                 // vertices
530                 startOffset -= halfDevStroke;
531             }
532 
533             if (!lineDone) {
534                 SkPoint devicePts[2];
535                 args.fSrcRotInv.mapPoints(devicePts, draw.fPtsRot, 2);
536                 draw.fLineLength = SkPoint::Distance(devicePts[0], devicePts[1]);
537                 if (hasCap) {
538                     draw.fLineLength += 2.f * halfDevStroke;
539                 }
540 
541                 bounds.setLTRB(draw.fPtsRot[0].fX, draw.fPtsRot[0].fY,
542                                draw.fPtsRot[1].fX, draw.fPtsRot[1].fY);
543                 bounds.outset(bloatX + strokeAdj, bloatY + halfSrcStroke);
544             }
545 
546             if (hasStartRect) {
547                 SkASSERT(useAA);  // so that we know bloatX and bloatY have been set
548                 startRect.outset(bloatX, bloatY);
549             }
550 
551             if (hasEndRect) {
552                 SkASSERT(useAA);  // so that we know bloatX and bloatY have been set
553                 endRect.outset(bloatX, bloatY);
554             }
555 
556             draw.fStartOffset = startOffset;
557             draw.fDevBloatX = devBloatX;
558             draw.fPerpendicularScale = args.fPerpendicularScale;
559             draw.fStrokeWidth = strokeWidth;
560             draw.fHasStartRect = hasStartRect;
561             draw.fLineDone = lineDone;
562             draw.fHasEndRect = hasEndRect;
563         }
564 
565         if (!totalRectCount) {
566             return;
567         }
568 
569         QuadHelper helper(target, fProgramInfo->geomProc().vertexStride(), totalRectCount);
570         VertexWriter vertices{ helper.vertices() };
571         if (!vertices) {
572             return;
573         }
574 
575         int rectIndex = 0;
576         for (int i = 0; i < instanceCount; i++) {
577             const LineData& geom = fLines[i];
578 
579             if (!draws[i].fLineDone) {
580                 if (fullDash) {
581                     setup_dashed_rect(rects[rectIndex], vertices, geom.fSrcRotInv,
582                                       draws[i].fStartOffset, draws[i].fDevBloatX,
583                                       draws[i].fLineLength, draws[i].fIntervals[0],
584                                       draws[i].fIntervals[1], draws[i].fStrokeWidth,
585                                       draws[i].fPerpendicularScale,
586                                       capType);
587                 } else {
588                     vertices.writeQuad(GrQuad::MakeFromRect(rects[rectIndex], geom.fSrcRotInv));
589                 }
590             }
591             rectIndex++;
592 
593             if (draws[i].fHasStartRect) {
594                 if (fullDash) {
595                     setup_dashed_rect(rects[rectIndex], vertices, geom.fSrcRotInv,
596                                       draws[i].fStartOffset, draws[i].fDevBloatX,
597                                       draws[i].fIntervals[0], draws[i].fIntervals[0],
598                                       draws[i].fIntervals[1], draws[i].fStrokeWidth,
599                                       draws[i].fPerpendicularScale, capType);
600                 } else {
601                     vertices.writeQuad(GrQuad::MakeFromRect(rects[rectIndex], geom.fSrcRotInv));
602                 }
603             }
604             rectIndex++;
605 
606             if (draws[i].fHasEndRect) {
607                 if (fullDash) {
608                     setup_dashed_rect(rects[rectIndex], vertices, geom.fSrcRotInv,
609                                       draws[i].fStartOffset, draws[i].fDevBloatX,
610                                       draws[i].fIntervals[0], draws[i].fIntervals[0],
611                                       draws[i].fIntervals[1], draws[i].fStrokeWidth,
612                                       draws[i].fPerpendicularScale, capType);
613                 } else {
614                     vertices.writeQuad(GrQuad::MakeFromRect(rects[rectIndex], geom.fSrcRotInv));
615                 }
616             }
617             rectIndex++;
618         }
619 
620         fMesh = helper.mesh();
621     }
622 
onExecute(GrOpFlushState * flushState,const SkRect & chainBounds)623     void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
624         if (!fProgramInfo || !fMesh) {
625             return;
626         }
627 
628         flushState->bindPipelineAndScissorClip(*fProgramInfo, chainBounds);
629         flushState->bindTextures(fProgramInfo->geomProc(), nullptr, fProgramInfo->pipeline());
630         flushState->drawMesh(*fMesh);
631     }
632 
onCombineIfPossible(GrOp * t,SkArenaAlloc *,const GrCaps & caps)633     CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps) override {
634         auto that = t->cast<DashOpImpl>();
635         if (fProcessorSet != that->fProcessorSet) {
636             return CombineResult::kCannotCombine;
637         }
638 
639         if (this->aaMode() != that->aaMode()) {
640             return CombineResult::kCannotCombine;
641         }
642 
643         if (this->fullDash() != that->fullDash()) {
644             return CombineResult::kCannotCombine;
645         }
646 
647         if (this->cap() != that->cap()) {
648             return CombineResult::kCannotCombine;
649         }
650 
651         // TODO vertex color
652         if (this->color() != that->color()) {
653             return CombineResult::kCannotCombine;
654         }
655 
656         if (fUsesLocalCoords && !SkMatrixPriv::CheapEqual(this->viewMatrix(), that->viewMatrix())) {
657             return CombineResult::kCannotCombine;
658         }
659 
660         fLines.push_back_n(that->fLines.size(), that->fLines.begin());
661         return CombineResult::kMerged;
662     }
663 
664 #if defined(GR_TEST_UTILS)
onDumpInfo() const665     SkString onDumpInfo() const override {
666         SkString string;
667         for (const auto& geo : fLines) {
668             string.appendf("Pt0: [%.2f, %.2f], Pt1: [%.2f, %.2f], Width: %.2f, Ival0: %.2f, "
669                            "Ival1 : %.2f, Phase: %.2f\n",
670                            geo.fPtsRot[0].fX, geo.fPtsRot[0].fY,
671                            geo.fPtsRot[1].fX, geo.fPtsRot[1].fY,
672                            geo.fSrcStrokeWidth,
673                            geo.fIntervals[0],
674                            geo.fIntervals[1],
675                            geo.fPhase);
676         }
677         string += fProcessorSet.dumpProcessors();
678         return string;
679     }
680 #endif
681 
color() const682     const SkPMColor4f& color() const { return fColor; }
viewMatrix() const683     const SkMatrix& viewMatrix() const { return fLines[0].fViewMatrix; }
aaMode() const684     AAMode aaMode() const { return fAAMode; }
fullDash() const685     bool fullDash() const { return fFullDash; }
cap() const686     SkPaint::Cap cap() const { return fCap; }
687 
688     STArray<1, LineData, true> fLines;
689     SkPMColor4f fColor;
690     bool fUsesLocalCoords : 1;
691     bool fFullDash : 1;
692     // We use 3 bits for this 3-value enum because MSVS makes the underlying types signed.
693     SkPaint::Cap fCap : 3;
694     AAMode fAAMode;
695     GrProcessorSet fProcessorSet;
696     const GrUserStencilSettings* fStencilSettings;
697 
698     GrSimpleMesh*  fMesh = nullptr;
699     GrProgramInfo* fProgramInfo = nullptr;
700 
701     using INHERITED = GrMeshDrawOp;
702 };
703 
704 /*
705  * This effect will draw a dotted line (defined as a dashed lined with round caps and no on
706  * interval). The radius of the dots is given by the strokeWidth and the spacing by the DashInfo.
707  * Both of the previous two parameters are in device space. This effect also requires the setting of
708  * a float2 vertex attribute for the the four corners of the bounding rect. This attribute is the
709  * "dash position" of each vertex. In other words it is the vertex coords (in device space) if we
710  * transform the line to be horizontal, with the start of line at the origin then shifted to the
711  * right by half the off interval. The line then goes in the positive x direction.
712  */
713 class DashingCircleEffect : public GrGeometryProcessor {
714 public:
715     typedef SkPathEffect::DashInfo DashInfo;
716 
717     static GrGeometryProcessor* Make(SkArenaAlloc* arena,
718                                      const SkPMColor4f&,
719                                      AAMode aaMode,
720                                      const SkMatrix& localMatrix,
721                                      bool usesLocalCoords);
722 
name() const723     const char* name() const override { return "DashingCircleEffect"; }
724 
725     void addToKey(const GrShaderCaps&, KeyBuilder*) const override;
726 
727     std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const override;
728 
729 private:
730     class Impl;
731 
732     DashingCircleEffect(const SkPMColor4f&, AAMode aaMode, const SkMatrix& localMatrix,
733                         bool usesLocalCoords);
734 
735     SkPMColor4f fColor;
736     SkMatrix    fLocalMatrix;
737     bool        fUsesLocalCoords;
738     AAMode      fAAMode;
739 
740     Attribute   fInPosition;
741     Attribute   fInDashParams;
742     Attribute   fInCircleParams;
743 
744     GR_DECLARE_GEOMETRY_PROCESSOR_TEST
745 
746     using INHERITED = GrGeometryProcessor;
747 };
748 
749 //////////////////////////////////////////////////////////////////////////////
750 
751 class DashingCircleEffect::Impl : public ProgramImpl {
752 public:
753     void setData(const GrGLSLProgramDataManager&,
754                  const GrShaderCaps&,
755                  const GrGeometryProcessor&) override;
756 
757 private:
758     void onEmitCode(EmitArgs&, GrGPArgs*) override;
759 
760     SkMatrix    fLocalMatrix         = SkMatrix::InvalidMatrix();
761     SkPMColor4f fColor               = SK_PMColor4fILLEGAL;
762 
763     UniformHandle fParamUniform;
764     UniformHandle fColorUniform;
765     UniformHandle fLocalMatrixUniform;
766 };
767 
onEmitCode(EmitArgs & args,GrGPArgs * gpArgs)768 void DashingCircleEffect::Impl::onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) {
769     const DashingCircleEffect& dce = args.fGeomProc.cast<DashingCircleEffect>();
770     GrGLSLVertexBuilder* vertBuilder = args.fVertBuilder;
771     GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
772     GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
773 
774     // emit attributes
775     varyingHandler->emitAttributes(dce);
776 
777     // XY are dashPos, Z is dashInterval
778     GrGLSLVarying dashParams(SkSLType::kHalf3);
779     varyingHandler->addVarying("DashParam", &dashParams);
780     vertBuilder->codeAppendf("%s = %s;", dashParams.vsOut(), dce.fInDashParams.name());
781 
782     // x refers to circle radius - 0.5, y refers to cicle's center x coord
783     GrGLSLVarying circleParams(SkSLType::kHalf2);
784     varyingHandler->addVarying("CircleParams", &circleParams);
785     vertBuilder->codeAppendf("%s = %s;", circleParams.vsOut(), dce.fInCircleParams.name());
786 
787     GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
788     // Setup pass through color
789     fragBuilder->codeAppendf("half4 %s;", args.fOutputColor);
790     this->setupUniformColor(fragBuilder, uniformHandler, args.fOutputColor, &fColorUniform);
791 
792     // Setup position
793     WriteOutputPosition(vertBuilder, gpArgs, dce.fInPosition.name());
794     if (dce.fUsesLocalCoords) {
795         WriteLocalCoord(vertBuilder,
796                         uniformHandler,
797                         *args.fShaderCaps,
798                         gpArgs,
799                         dce.fInPosition.asShaderVar(),
800                         dce.fLocalMatrix,
801                         &fLocalMatrixUniform);
802     }
803 
804     // transforms all points so that we can compare them to our test circle
805     fragBuilder->codeAppendf("half xShifted = half(%s.x - floor(%s.x / %s.z) * %s.z);",
806                              dashParams.fsIn(), dashParams.fsIn(), dashParams.fsIn(),
807                              dashParams.fsIn());
808     fragBuilder->codeAppendf("half2 fragPosShifted = half2(xShifted, half(%s.y));",
809                              dashParams.fsIn());
810     fragBuilder->codeAppendf("half2 center = half2(%s.y, 0.0);", circleParams.fsIn());
811     fragBuilder->codeAppend("half dist = length(center - fragPosShifted);");
812     if (dce.fAAMode != AAMode::kNone) {
813         fragBuilder->codeAppendf("half diff = dist - %s.x;", circleParams.fsIn());
814         fragBuilder->codeAppend("diff = 1.0 - diff;");
815         fragBuilder->codeAppend("half alpha = saturate(diff);");
816     } else {
817         fragBuilder->codeAppendf("half alpha = 1.0;");
818         fragBuilder->codeAppendf("alpha *=  dist < %s.x + 0.5 ? 1.0 : 0.0;", circleParams.fsIn());
819     }
820     fragBuilder->codeAppendf("half4 %s = half4(alpha);", args.fOutputCoverage);
821 }
822 
setData(const GrGLSLProgramDataManager & pdman,const GrShaderCaps & shaderCaps,const GrGeometryProcessor & geomProc)823 void DashingCircleEffect::Impl::setData(const GrGLSLProgramDataManager& pdman,
824                                         const GrShaderCaps& shaderCaps,
825                                         const GrGeometryProcessor& geomProc) {
826     const DashingCircleEffect& dce = geomProc.cast<DashingCircleEffect>();
827     if (dce.fColor != fColor) {
828         pdman.set4fv(fColorUniform, 1, dce.fColor.vec());
829         fColor = dce.fColor;
830     }
831     SetTransform(pdman, shaderCaps, fLocalMatrixUniform, dce.fLocalMatrix, &fLocalMatrix);
832 }
833 
834 //////////////////////////////////////////////////////////////////////////////
835 
Make(SkArenaAlloc * arena,const SkPMColor4f & color,AAMode aaMode,const SkMatrix & localMatrix,bool usesLocalCoords)836 GrGeometryProcessor* DashingCircleEffect::Make(SkArenaAlloc* arena,
837                                                const SkPMColor4f& color,
838                                                AAMode aaMode,
839                                                const SkMatrix& localMatrix,
840                                                bool usesLocalCoords) {
841     return arena->make([&](void* ptr) {
842         return new (ptr) DashingCircleEffect(color, aaMode, localMatrix, usesLocalCoords);
843     });
844 }
845 
addToKey(const GrShaderCaps & caps,KeyBuilder * b) const846 void DashingCircleEffect::addToKey(const GrShaderCaps& caps, KeyBuilder* b) const {
847     uint32_t key = 0;
848     key |= fUsesLocalCoords ? 0x1 : 0x0;
849     key |= static_cast<uint32_t>(fAAMode) << 1;
850     key |= ProgramImpl::ComputeMatrixKey(caps, fLocalMatrix) << 3;
851     b->add32(key);
852 }
853 
makeProgramImpl(const GrShaderCaps &) const854 std::unique_ptr<GrGeometryProcessor::ProgramImpl> DashingCircleEffect::makeProgramImpl(
855         const GrShaderCaps&) const {
856     return std::make_unique<Impl>();
857 }
858 
DashingCircleEffect(const SkPMColor4f & color,AAMode aaMode,const SkMatrix & localMatrix,bool usesLocalCoords)859 DashingCircleEffect::DashingCircleEffect(const SkPMColor4f& color,
860                                          AAMode aaMode,
861                                          const SkMatrix& localMatrix,
862                                          bool usesLocalCoords)
863         : INHERITED(kDashingCircleEffect_ClassID)
864         , fColor(color)
865         , fLocalMatrix(localMatrix)
866         , fUsesLocalCoords(usesLocalCoords)
867         , fAAMode(aaMode) {
868     fInPosition = {"inPosition", kFloat2_GrVertexAttribType, SkSLType::kFloat2};
869     fInDashParams = {"inDashParams", kFloat3_GrVertexAttribType, SkSLType::kHalf3};
870     fInCircleParams = {"inCircleParams", kFloat2_GrVertexAttribType, SkSLType::kHalf2};
871     this->setVertexAttributesWithImplicitOffsets(&fInPosition, 3);
872 }
873 
GR_DEFINE_GEOMETRY_PROCESSOR_TEST(DashingCircleEffect)874 GR_DEFINE_GEOMETRY_PROCESSOR_TEST(DashingCircleEffect)
875 
876 #if defined(GR_TEST_UTILS)
877 GrGeometryProcessor* DashingCircleEffect::TestCreate(GrProcessorTestData* d) {
878     AAMode aaMode = static_cast<AAMode>(d->fRandom->nextULessThan(kAAModeCnt));
879     GrColor color = GrTest::RandomColor(d->fRandom);
880     SkMatrix matrix = GrTest::TestMatrix(d->fRandom);
881     return DashingCircleEffect::Make(d->allocator(),
882                                      SkPMColor4f::FromBytes_RGBA(color),
883                                      aaMode,
884                                      matrix,
885                                      d->fRandom->nextBool());
886 }
887 #endif
888 
889 //////////////////////////////////////////////////////////////////////////////
890 
891 /*
892  * This effect will draw a dashed line. The width of the dash is given by the strokeWidth and the
893  * length and spacing by the DashInfo. Both of the previous two parameters are in device space.
894  * This effect also requires the setting of a float2 vertex attribute for the the four corners of the
895  * bounding rect. This attribute is the "dash position" of each vertex. In other words it is the
896  * vertex coords (in device space) if we transform the line to be horizontal, with the start of
897  * line at the origin then shifted to the right by half the off interval. The line then goes in the
898  * positive x direction.
899  */
900 class DashingLineEffect : public GrGeometryProcessor {
901 public:
902     typedef SkPathEffect::DashInfo DashInfo;
903 
904     static GrGeometryProcessor* Make(SkArenaAlloc* arena,
905                                      const SkPMColor4f&,
906                                      AAMode aaMode,
907                                      const SkMatrix& localMatrix,
908                                      bool usesLocalCoords);
909 
name() const910     const char* name() const override { return "DashingEffect"; }
911 
usesLocalCoords() const912     bool usesLocalCoords() const { return fUsesLocalCoords; }
913 
914     void addToKey(const GrShaderCaps&, KeyBuilder*) const override;
915 
916     std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const override;
917 
918 private:
919     class Impl;
920 
921     DashingLineEffect(const SkPMColor4f&, AAMode aaMode, const SkMatrix& localMatrix,
922                       bool usesLocalCoords);
923 
924     SkPMColor4f fColor;
925     SkMatrix    fLocalMatrix;
926     bool        fUsesLocalCoords;
927     AAMode      fAAMode;
928 
929     Attribute   fInPosition;
930     Attribute   fInDashParams;
931     Attribute   fInRect;
932 
933     GR_DECLARE_GEOMETRY_PROCESSOR_TEST
934 
935     using INHERITED = GrGeometryProcessor;
936 };
937 
938 //////////////////////////////////////////////////////////////////////////////
939 
940 class DashingLineEffect::Impl : public ProgramImpl {
941 public:
942     void setData(const GrGLSLProgramDataManager&,
943                  const GrShaderCaps&,
944                  const GrGeometryProcessor&) override;
945 
946 private:
947     void onEmitCode(EmitArgs&, GrGPArgs*) override;
948 
949     SkPMColor4f fColor       = SK_PMColor4fILLEGAL;
950     SkMatrix    fLocalMatrix = SkMatrix::InvalidMatrix();
951 
952     UniformHandle fLocalMatrixUniform;
953     UniformHandle fColorUniform;
954 };
955 
onEmitCode(EmitArgs & args,GrGPArgs * gpArgs)956 void DashingLineEffect::Impl::onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) {
957     const DashingLineEffect& de = args.fGeomProc.cast<DashingLineEffect>();
958 
959     GrGLSLVertexBuilder* vertBuilder = args.fVertBuilder;
960     GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
961     GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
962 
963     // emit attributes
964     varyingHandler->emitAttributes(de);
965 
966     // XY refers to dashPos, Z is the dash interval length
967     GrGLSLVarying inDashParams(SkSLType::kFloat3);
968     varyingHandler->addVarying("DashParams", &inDashParams);
969     vertBuilder->codeAppendf("%s = %s;", inDashParams.vsOut(), de.fInDashParams.name());
970 
971     // The rect uniform's xyzw refer to (left + 0.5, top + 0.5, right - 0.5, bottom - 0.5),
972     // respectively.
973     GrGLSLVarying inRectParams(SkSLType::kFloat4);
974     varyingHandler->addVarying("RectParams", &inRectParams);
975     vertBuilder->codeAppendf("%s = %s;", inRectParams.vsOut(), de.fInRect.name());
976 
977     GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
978     // Setup pass through color
979     fragBuilder->codeAppendf("half4 %s;", args.fOutputColor);
980     this->setupUniformColor(fragBuilder, uniformHandler, args.fOutputColor, &fColorUniform);
981 
982     // Setup position
983     WriteOutputPosition(vertBuilder, gpArgs, de.fInPosition.name());
984     if (de.usesLocalCoords()) {
985         WriteLocalCoord(vertBuilder,
986                         uniformHandler,
987                         *args.fShaderCaps,
988                         gpArgs,
989                         de.fInPosition.asShaderVar(),
990                         de.fLocalMatrix,
991                         &fLocalMatrixUniform);
992     }
993 
994     // transforms all points so that we can compare them to our test rect
995     fragBuilder->codeAppendf("half xShifted = half(%s.x - floor(%s.x / %s.z) * %s.z);",
996                              inDashParams.fsIn(), inDashParams.fsIn(), inDashParams.fsIn(),
997                              inDashParams.fsIn());
998     fragBuilder->codeAppendf("half2 fragPosShifted = half2(xShifted, half(%s.y));",
999                              inDashParams.fsIn());
1000     if (de.fAAMode == AAMode::kCoverage) {
1001         // The amount of coverage removed in x and y by the edges is computed as a pair of negative
1002         // numbers, xSub and ySub.
1003         fragBuilder->codeAppend("half xSub, ySub;");
1004         fragBuilder->codeAppendf("xSub = half(min(fragPosShifted.x - %s.x, 0.0));",
1005                                  inRectParams.fsIn());
1006         fragBuilder->codeAppendf("xSub += half(min(%s.z - fragPosShifted.x, 0.0));",
1007                                  inRectParams.fsIn());
1008         fragBuilder->codeAppendf("ySub = half(min(fragPosShifted.y - %s.y, 0.0));",
1009                                  inRectParams.fsIn());
1010         fragBuilder->codeAppendf("ySub += half(min(%s.w - fragPosShifted.y, 0.0));",
1011                                  inRectParams.fsIn());
1012         // Now compute coverage in x and y and multiply them to get the fraction of the pixel
1013         // covered.
1014         fragBuilder->codeAppendf(
1015             "half alpha = (1.0 + max(xSub, -1.0)) * (1.0 + max(ySub, -1.0));");
1016     } else if (de.fAAMode == AAMode::kCoverageWithMSAA) {
1017         // For MSAA, we don't modulate the alpha by the Y distance, since MSAA coverage will handle
1018         // AA on the the top and bottom edges. The shader is only responsible for intra-dash alpha.
1019         fragBuilder->codeAppend("half xSub;");
1020         fragBuilder->codeAppendf("xSub = half(min(fragPosShifted.x - %s.x, 0.0));",
1021                                  inRectParams.fsIn());
1022         fragBuilder->codeAppendf("xSub += half(min(%s.z - fragPosShifted.x, 0.0));",
1023                                  inRectParams.fsIn());
1024         // Now compute coverage in x to get the fraction of the pixel covered.
1025         fragBuilder->codeAppendf("half alpha = (1.0 + max(xSub, -1.0));");
1026     } else {
1027         // Assuming the bounding geometry is tight so no need to check y values
1028         fragBuilder->codeAppendf("half alpha = 1.0;");
1029         fragBuilder->codeAppendf("alpha *= (fragPosShifted.x - %s.x) > -0.5 ? 1.0 : 0.0;",
1030                                  inRectParams.fsIn());
1031         fragBuilder->codeAppendf("alpha *= (%s.z - fragPosShifted.x) >= -0.5 ? 1.0 : 0.0;",
1032                                  inRectParams.fsIn());
1033     }
1034     fragBuilder->codeAppendf("half4 %s = half4(alpha);", args.fOutputCoverage);
1035 }
1036 
setData(const GrGLSLProgramDataManager & pdman,const GrShaderCaps & shaderCaps,const GrGeometryProcessor & geomProc)1037 void DashingLineEffect::Impl::setData(const GrGLSLProgramDataManager& pdman,
1038                                       const GrShaderCaps& shaderCaps,
1039                                       const GrGeometryProcessor& geomProc) {
1040     const DashingLineEffect& de = geomProc.cast<DashingLineEffect>();
1041     if (de.fColor != fColor) {
1042         pdman.set4fv(fColorUniform, 1, de.fColor.vec());
1043         fColor = de.fColor;
1044     }
1045     SetTransform(pdman, shaderCaps, fLocalMatrixUniform, de.fLocalMatrix, &fLocalMatrix);
1046 }
1047 
1048 //////////////////////////////////////////////////////////////////////////////
1049 
Make(SkArenaAlloc * arena,const SkPMColor4f & color,AAMode aaMode,const SkMatrix & localMatrix,bool usesLocalCoords)1050 GrGeometryProcessor* DashingLineEffect::Make(SkArenaAlloc* arena,
1051                                              const SkPMColor4f& color,
1052                                              AAMode aaMode,
1053                                              const SkMatrix& localMatrix,
1054                                              bool usesLocalCoords) {
1055     return arena->make([&](void* ptr) {
1056         return new (ptr) DashingLineEffect(color, aaMode, localMatrix, usesLocalCoords);
1057     });
1058 }
1059 
addToKey(const GrShaderCaps & caps,KeyBuilder * b) const1060 void DashingLineEffect::addToKey(const GrShaderCaps& caps, KeyBuilder* b) const {
1061     uint32_t key = 0;
1062     key |= fUsesLocalCoords ? 0x1 : 0x0;
1063     key |= static_cast<int>(fAAMode) << 1;
1064     key |= ProgramImpl::ComputeMatrixKey(caps, fLocalMatrix) << 3;
1065     b->add32(key);
1066 }
1067 
makeProgramImpl(const GrShaderCaps &) const1068 std::unique_ptr<GrGeometryProcessor::ProgramImpl> DashingLineEffect::makeProgramImpl(
1069         const GrShaderCaps&) const {
1070     return std::make_unique<Impl>();
1071 }
1072 
DashingLineEffect(const SkPMColor4f & color,AAMode aaMode,const SkMatrix & localMatrix,bool usesLocalCoords)1073 DashingLineEffect::DashingLineEffect(const SkPMColor4f& color,
1074                                      AAMode aaMode,
1075                                      const SkMatrix& localMatrix,
1076                                      bool usesLocalCoords)
1077         : INHERITED(kDashingLineEffect_ClassID)
1078         , fColor(color)
1079         , fLocalMatrix(localMatrix)
1080         , fUsesLocalCoords(usesLocalCoords)
1081         , fAAMode(aaMode) {
1082     fInPosition = {"inPosition", kFloat2_GrVertexAttribType, SkSLType::kFloat2};
1083     fInDashParams = {"inDashParams", kFloat3_GrVertexAttribType, SkSLType::kHalf3};
1084     fInRect = {"inRect", kFloat4_GrVertexAttribType, SkSLType::kHalf4};
1085     this->setVertexAttributesWithImplicitOffsets(&fInPosition, 3);
1086 }
1087 
GR_DEFINE_GEOMETRY_PROCESSOR_TEST(DashingLineEffect)1088 GR_DEFINE_GEOMETRY_PROCESSOR_TEST(DashingLineEffect)
1089 
1090 #if defined(GR_TEST_UTILS)
1091 GrGeometryProcessor* DashingLineEffect::TestCreate(GrProcessorTestData* d) {
1092     AAMode aaMode = static_cast<AAMode>(d->fRandom->nextULessThan(kAAModeCnt));
1093     GrColor color = GrTest::RandomColor(d->fRandom);
1094     SkMatrix matrix = GrTest::TestMatrix(d->fRandom);
1095     return DashingLineEffect::Make(d->allocator(),
1096                                    SkPMColor4f::FromBytes_RGBA(color),
1097                                    aaMode,
1098                                    matrix,
1099                                    d->fRandom->nextBool());
1100 }
1101 
1102 #endif
1103 //////////////////////////////////////////////////////////////////////////////
1104 
make_dash_gp(SkArenaAlloc * arena,const SkPMColor4f & color,AAMode aaMode,DashCap cap,const SkMatrix & viewMatrix,bool usesLocalCoords)1105 GrGeometryProcessor* make_dash_gp(SkArenaAlloc* arena,
1106                                   const SkPMColor4f& color,
1107                                   AAMode aaMode,
1108                                   DashCap cap,
1109                                   const SkMatrix& viewMatrix,
1110                                   bool usesLocalCoords) {
1111     SkMatrix invert;
1112     if (usesLocalCoords && !viewMatrix.invert(&invert)) {
1113         SkDebugf("Failed to invert\n");
1114         return nullptr;
1115     }
1116 
1117     switch (cap) {
1118         case kRound_DashCap:
1119             return DashingCircleEffect::Make(arena, color, aaMode, invert, usesLocalCoords);
1120         case kNonRound_DashCap:
1121             return DashingLineEffect::Make(arena, color, aaMode, invert, usesLocalCoords);
1122     }
1123     return nullptr;
1124 }
1125 
1126 } // anonymous namespace
1127 
1128 /////////////////////////////////////////////////////////////////////////////////////////////////
1129 
MakeDashLineOp(GrRecordingContext * context,GrPaint && paint,const SkMatrix & viewMatrix,const SkPoint pts[2],AAMode aaMode,const GrStyle & style,const GrUserStencilSettings * stencilSettings)1130 GrOp::Owner MakeDashLineOp(GrRecordingContext* context,
1131                            GrPaint&& paint,
1132                            const SkMatrix& viewMatrix,
1133                            const SkPoint pts[2],
1134                            AAMode aaMode,
1135                            const GrStyle& style,
1136                            const GrUserStencilSettings* stencilSettings) {
1137     SkASSERT(CanDrawDashLine(pts, style, viewMatrix));
1138     const SkScalar* intervals = style.dashIntervals();
1139     SkScalar phase = style.dashPhase();
1140 
1141     SkPaint::Cap cap = style.strokeRec().getCap();
1142 
1143     DashOpImpl::LineData lineData;
1144     lineData.fSrcStrokeWidth = style.strokeRec().getWidth();
1145 
1146     // the phase should be normalized to be [0, sum of all intervals)
1147     SkASSERT(phase >= 0 && phase < intervals[0] + intervals[1]);
1148 
1149     // Rotate the src pts so they are aligned horizontally with pts[0].fX < pts[1].fX
1150     if (pts[0].fY != pts[1].fY || pts[0].fX > pts[1].fX) {
1151         SkMatrix rotMatrix;
1152         align_to_x_axis(pts, &rotMatrix, lineData.fPtsRot);
1153         if (!rotMatrix.invert(&lineData.fSrcRotInv)) {
1154             SkDebugf("Failed to create invertible rotation matrix!\n");
1155             return nullptr;
1156         }
1157     } else {
1158         lineData.fSrcRotInv.reset();
1159         memcpy(lineData.fPtsRot, pts, 2 * sizeof(SkPoint));
1160     }
1161 
1162     // Scale corrections of intervals and stroke from view matrix
1163     calc_dash_scaling(&lineData.fParallelScale, &lineData.fPerpendicularScale, viewMatrix, pts);
1164     if (SkScalarNearlyZero(lineData.fParallelScale) ||
1165         SkScalarNearlyZero(lineData.fPerpendicularScale)) {
1166         return nullptr;
1167     }
1168 
1169     SkScalar offInterval = intervals[1] * lineData.fParallelScale;
1170     SkScalar strokeWidth = lineData.fSrcStrokeWidth * lineData.fPerpendicularScale;
1171 
1172     if (SkPaint::kSquare_Cap == cap && 0 != lineData.fSrcStrokeWidth) {
1173         // add cap to on interval and remove from off interval
1174         offInterval -= strokeWidth;
1175     }
1176 
1177     // TODO we can do a real rect call if not using fulldash(ie no off interval, not using AA)
1178     bool fullDash = offInterval > 0.f || aaMode != AAMode::kNone;
1179 
1180     lineData.fViewMatrix = viewMatrix;
1181     lineData.fPhase = phase;
1182     lineData.fIntervals[0] = intervals[0];
1183     lineData.fIntervals[1] = intervals[1];
1184 
1185     return DashOpImpl::Make(context, std::move(paint), lineData, cap, aaMode, fullDash,
1186                             stencilSettings);
1187 }
1188 
1189 // Returns whether or not the gpu can fast path the dash line effect.
CanDrawDashLine(const SkPoint pts[2],const GrStyle & style,const SkMatrix & viewMatrix)1190 bool CanDrawDashLine(const SkPoint pts[2], const GrStyle& style, const SkMatrix& viewMatrix) {
1191     // Pts must be either horizontal or vertical in src space
1192     if (pts[0].fX != pts[1].fX && pts[0].fY != pts[1].fY) {
1193         return false;
1194     }
1195 
1196     // May be able to relax this to include skew. As of now cannot do perspective
1197     // because of the non uniform scaling of bloating a rect
1198     if (!viewMatrix.preservesRightAngles()) {
1199         return false;
1200     }
1201 
1202     if (!style.isDashed() || 2 != style.dashIntervalCnt()) {
1203         return false;
1204     }
1205 
1206     const SkScalar* intervals = style.dashIntervals();
1207     if (0 == intervals[0] && 0 == intervals[1]) {
1208         return false;
1209     }
1210 
1211     SkPaint::Cap cap = style.strokeRec().getCap();
1212     if (SkPaint::kRound_Cap == cap) {
1213         // Current we don't support round caps unless the on interval is zero
1214         if (intervals[0] != 0.f) {
1215             return false;
1216         }
1217         // If the width of the circle caps in greater than the off interval we will pick up unwanted
1218         // segments of circles at the start and end of the dash line.
1219         if (style.strokeRec().getWidth() > intervals[1]) {
1220             return false;
1221         }
1222     }
1223 
1224     return true;
1225 }
1226 
1227 } // namespace skgpu::ganesh::DashOp
1228 
1229 #if defined(GR_TEST_UTILS)
1230 
1231 #include "src/gpu/ganesh/GrDrawOpTest.h"
1232 
GR_DRAW_OP_TEST_DEFINE(DashOpImpl)1233 GR_DRAW_OP_TEST_DEFINE(DashOpImpl) {
1234     SkMatrix viewMatrix = GrTest::TestMatrixPreservesRightAngles(random);
1235     AAMode aaMode;
1236     do {
1237         aaMode = static_cast<AAMode>(random->nextULessThan(kAAModeCnt));
1238     } while (AAMode::kCoverageWithMSAA == aaMode && numSamples <= 1);
1239 
1240     // We can only dash either horizontal or vertical lines
1241     SkPoint pts[2];
1242     if (random->nextBool()) {
1243         // vertical
1244         pts[0].fX = 1.f;
1245         pts[0].fY = random->nextF() * 10.f;
1246         pts[1].fX = 1.f;
1247         pts[1].fY = random->nextF() * 10.f;
1248     } else {
1249         // horizontal
1250         pts[0].fX = random->nextF() * 10.f;
1251         pts[0].fY = 1.f;
1252         pts[1].fX = random->nextF() * 10.f;
1253         pts[1].fY = 1.f;
1254     }
1255 
1256     // pick random cap
1257     SkPaint::Cap cap = SkPaint::Cap(random->nextULessThan(SkPaint::kCapCount));
1258 
1259     SkScalar intervals[2];
1260 
1261     // We can only dash with the following intervals
1262     enum Intervals {
1263         kOpenOpen_Intervals ,
1264         kOpenClose_Intervals,
1265         kCloseOpen_Intervals,
1266     };
1267 
1268     Intervals intervalType = SkPaint::kRound_Cap == cap ?
1269                              kOpenClose_Intervals :
1270                              Intervals(random->nextULessThan(kCloseOpen_Intervals + 1));
1271     static const SkScalar kIntervalMin = 0.1f;
1272     static const SkScalar kIntervalMinCircles = 1.f; // Must be >= to stroke width
1273     static const SkScalar kIntervalMax = 10.f;
1274     switch (intervalType) {
1275         case kOpenOpen_Intervals:
1276             intervals[0] = random->nextRangeScalar(kIntervalMin, kIntervalMax);
1277             intervals[1] = random->nextRangeScalar(kIntervalMin, kIntervalMax);
1278             break;
1279         case kOpenClose_Intervals: {
1280             intervals[0] = 0.f;
1281             SkScalar min = SkPaint::kRound_Cap == cap ? kIntervalMinCircles : kIntervalMin;
1282             intervals[1] = random->nextRangeScalar(min, kIntervalMax);
1283             break;
1284         }
1285         case kCloseOpen_Intervals:
1286             intervals[0] = random->nextRangeScalar(kIntervalMin, kIntervalMax);
1287             intervals[1] = 0.f;
1288             break;
1289 
1290     }
1291 
1292     // phase is 0 < sum (i0, i1)
1293     SkScalar phase = random->nextRangeScalar(0, intervals[0] + intervals[1]);
1294 
1295     SkPaint p;
1296     p.setStyle(SkPaint::kStroke_Style);
1297     p.setStrokeWidth(SkIntToScalar(1));
1298     p.setStrokeCap(cap);
1299     p.setPathEffect(GrTest::TestDashPathEffect::Make(intervals, 2, phase));
1300 
1301     GrStyle style(p);
1302 
1303     return skgpu::ganesh::DashOp::MakeDashLineOp(context, std::move(paint), viewMatrix, pts, aaMode,
1304                                                  style, GrGetRandomStencil(random, context));
1305 }
1306 
1307 #endif // defined(GR_TEST_UTILS)
1308