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