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