1 /*
2  * Copyright 2017 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/ccpr/GrCCPathProcessor.h"
9 
10 #include "include/gpu/GrTexture.h"
11 #include "src/gpu/GrOnFlushResourceProvider.h"
12 #include "src/gpu/GrOpsRenderPass.h"
13 #include "src/gpu/GrTexturePriv.h"
14 #include "src/gpu/ccpr/GrCCPerFlushResources.h"
15 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
16 #include "src/gpu/glsl/GrGLSLGeometryProcessor.h"
17 #include "src/gpu/glsl/GrGLSLProgramBuilder.h"
18 #include "src/gpu/glsl/GrGLSLVarying.h"
19 
20 // Paths are drawn as octagons. Each point on the octagon is the intersection of two lines: one edge
21 // from the path's bounding box and one edge from its 45-degree bounding box. The selectors
22 // below indicate one corner from the bounding box, paired with a corner from the 45-degree bounding
23 // box. The octagon vertex is the point that lies between these two corners, found by intersecting
24 // their edges.
25 static constexpr float kOctoEdgeNorms[8*4] = {
26     // bbox   // bbox45
27     0,0,      0,0,
28     0,0,      1,0,
29     1,0,      1,0,
30     1,0,      1,1,
31     1,1,      1,1,
32     1,1,      0,1,
33     0,1,      0,1,
34     0,1,      0,0,
35 };
36 
37 GR_DECLARE_STATIC_UNIQUE_KEY(gVertexBufferKey);
38 
FindVertexBuffer(GrOnFlushResourceProvider * onFlushRP)39 sk_sp<const GrGpuBuffer> GrCCPathProcessor::FindVertexBuffer(GrOnFlushResourceProvider* onFlushRP) {
40     GR_DEFINE_STATIC_UNIQUE_KEY(gVertexBufferKey);
41     return onFlushRP->findOrMakeStaticBuffer(GrGpuBufferType::kVertex, sizeof(kOctoEdgeNorms),
42                                              kOctoEdgeNorms, gVertexBufferKey);
43 }
44 
45 static constexpr uint16_t kRestartStrip = 0xffff;
46 
47 static constexpr uint16_t kOctoIndicesAsStrips[] = {
48     3, 4, 2, 0, 1, kRestartStrip,  // First half.
49     7, 0, 6, 4, 5  // Second half.
50 };
51 
52 static constexpr uint16_t kOctoIndicesAsTris[] = {
53     // First half.
54     3, 4, 2,
55     4, 0, 2,
56     2, 0, 1,
57 
58     // Second half.
59     7, 0, 6,
60     0, 4, 6,
61     6, 4, 5,
62 };
63 
64 GR_DECLARE_STATIC_UNIQUE_KEY(gIndexBufferKey);
65 
66 constexpr GrPrimitiveProcessor::Attribute GrCCPathProcessor::kInstanceAttribs[];
67 constexpr GrPrimitiveProcessor::Attribute GrCCPathProcessor::kCornersAttrib;
68 
FindIndexBuffer(GrOnFlushResourceProvider * onFlushRP)69 sk_sp<const GrGpuBuffer> GrCCPathProcessor::FindIndexBuffer(GrOnFlushResourceProvider* onFlushRP) {
70     GR_DEFINE_STATIC_UNIQUE_KEY(gIndexBufferKey);
71     if (onFlushRP->caps()->usePrimitiveRestart()) {
72         return onFlushRP->findOrMakeStaticBuffer(GrGpuBufferType::kIndex,
73                                                  sizeof(kOctoIndicesAsStrips), kOctoIndicesAsStrips,
74                                                  gIndexBufferKey);
75     } else {
76         return onFlushRP->findOrMakeStaticBuffer(GrGpuBufferType::kIndex,
77                                                  sizeof(kOctoIndicesAsTris), kOctoIndicesAsTris,
78                                                  gIndexBufferKey);
79     }
80 }
81 
GrCCPathProcessor(CoverageMode coverageMode,const GrTexture * atlasTexture,const GrSwizzle & swizzle,GrSurfaceOrigin atlasOrigin,const SkMatrix & viewMatrixIfUsingLocalCoords)82 GrCCPathProcessor::GrCCPathProcessor(CoverageMode coverageMode, const GrTexture* atlasTexture,
83                                      const GrSwizzle& swizzle, GrSurfaceOrigin atlasOrigin,
84                                      const SkMatrix& viewMatrixIfUsingLocalCoords)
85         : INHERITED(kGrCCPathProcessor_ClassID)
86         , fCoverageMode(coverageMode)
87         , fAtlasAccess(atlasTexture->texturePriv().textureType(), GrSamplerState::ClampNearest(),
88                        swizzle)
89         , fAtlasSize(SkISize::Make(atlasTexture->width(), atlasTexture->height()))
90         , fAtlasOrigin(atlasOrigin) {
91     // TODO: Can we just assert that atlas has GrCCAtlas::kTextureOrigin and remove fAtlasOrigin?
92     this->setInstanceAttributes(kInstanceAttribs, SK_ARRAY_COUNT(kInstanceAttribs));
93     SkASSERT(this->instanceStride() == sizeof(Instance));
94 
95     this->setVertexAttributes(&kCornersAttrib, 1);
96     this->setTextureSamplerCnt(1);
97 
98     if (!viewMatrixIfUsingLocalCoords.invert(&fLocalMatrix)) {
99         fLocalMatrix.setIdentity();
100     }
101 }
102 
103 class GrCCPathProcessor::Impl : public GrGLSLGeometryProcessor {
104 public:
105     void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override;
106 
107 private:
setData(const GrGLSLProgramDataManager & pdman,const GrPrimitiveProcessor & primProc,FPCoordTransformIter && transformIter)108     void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor& primProc,
109                  FPCoordTransformIter&& transformIter) override {
110         const auto& proc = primProc.cast<GrCCPathProcessor>();
111         pdman.set2f(
112                 fAtlasAdjustUniform, 1.0f / proc.fAtlasSize.fWidth, 1.0f / proc.fAtlasSize.fHeight);
113         this->setTransformDataHelper(proc.fLocalMatrix, pdman, &transformIter);
114     }
115 
116     GrGLSLUniformHandler::UniformHandle fAtlasAdjustUniform;
117 
118     typedef GrGLSLGeometryProcessor INHERITED;
119 };
120 
createGLSLInstance(const GrShaderCaps &) const121 GrGLSLPrimitiveProcessor* GrCCPathProcessor::createGLSLInstance(const GrShaderCaps&) const {
122     return new Impl();
123 }
124 
drawPaths(GrOpFlushState * flushState,const GrPipeline & pipeline,const GrPipeline::FixedDynamicState * fixedDynamicState,const GrCCPerFlushResources & resources,int baseInstance,int endInstance,const SkRect & bounds) const125 void GrCCPathProcessor::drawPaths(GrOpFlushState* flushState, const GrPipeline& pipeline,
126                                   const GrPipeline::FixedDynamicState* fixedDynamicState,
127                                   const GrCCPerFlushResources& resources, int baseInstance,
128                                   int endInstance, const SkRect& bounds) const {
129     const GrCaps& caps = flushState->caps();
130     GrPrimitiveType primitiveType = caps.usePrimitiveRestart()
131                                             ? GrPrimitiveType::kTriangleStrip
132                                             : GrPrimitiveType::kTriangles;
133     int numIndicesPerInstance = caps.usePrimitiveRestart()
134                                         ? SK_ARRAY_COUNT(kOctoIndicesAsStrips)
135                                         : SK_ARRAY_COUNT(kOctoIndicesAsTris);
136     GrMesh mesh(primitiveType);
137     auto enablePrimitiveRestart = GrPrimitiveRestart(flushState->caps().usePrimitiveRestart());
138 
139     mesh.setIndexedInstanced(resources.refIndexBuffer(), numIndicesPerInstance,
140                              resources.refInstanceBuffer(), endInstance - baseInstance,
141                              baseInstance, enablePrimitiveRestart);
142     mesh.setVertexData(resources.refVertexBuffer());
143 
144     GrProgramInfo programInfo(flushState->drawOpArgs().numSamples(),
145                               flushState->drawOpArgs().origin(),
146                               pipeline,
147                               *this,
148                               fixedDynamicState,
149                               nullptr, 0);
150 
151     flushState->opsRenderPass()->draw(programInfo, &mesh, 1, bounds);
152 }
153 
onEmitCode(EmitArgs & args,GrGPArgs * gpArgs)154 void GrCCPathProcessor::Impl::onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) {
155     using Interpolation = GrGLSLVaryingHandler::Interpolation;
156 
157     const GrCCPathProcessor& proc = args.fGP.cast<GrCCPathProcessor>();
158     GrGLSLUniformHandler* uniHandler = args.fUniformHandler;
159     GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
160     bool isCoverageCount = (CoverageMode::kCoverageCount == proc.fCoverageMode);
161 
162     const char* atlasAdjust;
163     fAtlasAdjustUniform = uniHandler->addUniform(
164             kVertex_GrShaderFlag, kFloat2_GrSLType, "atlas_adjust", &atlasAdjust);
165 
166     varyingHandler->emitAttributes(proc);
167 
168     GrGLSLVarying texcoord((isCoverageCount) ? kFloat3_GrSLType : kFloat2_GrSLType);
169     varyingHandler->addVarying("texcoord", &texcoord);
170 
171     GrGLSLVarying color(kHalf4_GrSLType);
172     varyingHandler->addPassThroughAttribute(
173             kInstanceAttribs[kColorAttribIdx], args.fOutputColor, Interpolation::kCanBeFlat);
174 
175     // The vertex shader bloats and intersects the devBounds and devBounds45 rectangles, in order to
176     // find an octagon that circumscribes the (bloated) path.
177     GrGLSLVertexBuilder* v = args.fVertBuilder;
178 
179     // Are we clockwise? (Positive wind => nonzero fill rule.)
180     // Or counter-clockwise? (negative wind => even/odd fill rule.)
181     v->codeAppendf("float wind = sign(devbounds.z - devbounds.x);");
182 
183     // Find our reference corner from the device-space bounding box.
184     v->codeAppendf("float2 refpt = mix(devbounds.xy, devbounds.zw, corners.xy);");
185 
186     // Find our reference corner from the 45-degree bounding box.
187     v->codeAppendf("float2 refpt45 = mix(devbounds45.xy, devbounds45.zw, corners.zw);");
188     // Transform back to device space.
189     v->codeAppendf("refpt45 *= float2x2(+1, +1, -wind, +wind) * .5;");
190 
191     // Find the normals to each edge, then intersect them to find our octagon vertex.
192     v->codeAppendf("float2x2 N = float2x2("
193                            "corners.z + corners.w - 1, corners.w - corners.z, "
194                            "corners.xy*2 - 1);");
195     v->codeAppendf("N = float2x2(wind, 0, 0, 1) * N;");
196     v->codeAppendf("float2 K = float2(dot(N[0], refpt), dot(N[1], refpt45));");
197     v->codeAppendf("float2 octocoord = K * inverse(N);");
198 
199     // Round the octagon out to ensure we rasterize every pixel the path might touch. (Positive
200     // bloatdir means we should take the "ceil" and negative means to take the "floor".)
201     //
202     // NOTE: If we were just drawing a rect, ceil/floor would be enough. But since there are also
203     // diagonals in the octagon that cross through pixel centers, we need to outset by another
204     // quarter px to ensure those pixels get rasterized.
205     v->codeAppendf("float2 bloatdir = (0 != N[0].x) "
206                            "? float2(N[0].x, N[1].y)"
207                            ": float2(N[1].x, N[0].y);");
208     v->codeAppendf("octocoord = (ceil(octocoord * bloatdir - 1e-4) + 0.25) * bloatdir;");
209     v->codeAppendf("float2 atlascoord = octocoord + float2(dev_to_atlas_offset);");
210 
211     // Convert to atlas coordinates in order to do our texture lookup.
212     if (kTopLeft_GrSurfaceOrigin == proc.fAtlasOrigin) {
213         v->codeAppendf("%s.xy = atlascoord * %s;", texcoord.vsOut(), atlasAdjust);
214     } else {
215         SkASSERT(kBottomLeft_GrSurfaceOrigin == proc.fAtlasOrigin);
216         v->codeAppendf("%s.xy = float2(atlascoord.x * %s.x, 1 - atlascoord.y * %s.y);",
217                        texcoord.vsOut(), atlasAdjust, atlasAdjust);
218     }
219     if (isCoverageCount) {
220         v->codeAppendf("%s.z = wind * .5;", texcoord.vsOut());
221     }
222 
223     gpArgs->fPositionVar.set(kFloat2_GrSLType, "octocoord");
224     this->emitTransforms(v, varyingHandler, uniHandler, gpArgs->fPositionVar, proc.fLocalMatrix,
225                          args.fFPCoordTransformHandler);
226 
227     // Fragment shader.
228     GrGLSLFPFragmentBuilder* f = args.fFragBuilder;
229 
230     // Look up coverage in the atlas.
231     f->codeAppendf("half coverage = ");
232     f->appendTextureLookup(args.fTexSamplers[0], SkStringPrintf("%s.xy", texcoord.fsIn()).c_str(),
233                            kFloat2_GrSLType);
234     f->codeAppendf(".a;");
235 
236     if (isCoverageCount) {
237         f->codeAppendf("coverage = abs(coverage);");
238 
239         // Scale coverage count by .5. Make it negative for even-odd paths and positive for
240         // winding ones. Clamp winding coverage counts at 1.0 (i.e. min(coverage/2, .5)).
241         f->codeAppendf("coverage = min(abs(coverage) * half(%s.z), .5);", texcoord.fsIn());
242 
243         // For negative values, this finishes the even-odd sawtooth function. Since positive
244         // (winding) values were clamped at "coverage/2 = .5", this only undoes the previous
245         // multiply by .5.
246         f->codeAppend ("coverage = 1 - abs(fract(coverage) * 2 - 1);");
247     }
248 
249     f->codeAppendf("%s = half4(coverage);", args.fOutputCoverage);
250 }
251