1 | /* |
2 | * Copyright 2015 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/glsl/GrGLSLProgramBuilder.h" |
9 | |
10 | #include <memory> |
11 | |
12 | #include "src/gpu/GrCaps.h" |
13 | #include "src/gpu/GrPipeline.h" |
14 | #include "src/gpu/GrRenderTarget.h" |
15 | #include "src/gpu/GrShaderCaps.h" |
16 | #include "src/gpu/GrTexture.h" |
17 | #include "src/gpu/glsl/GrGLSLFragmentProcessor.h" |
18 | #include "src/gpu/glsl/GrGLSLGeometryProcessor.h" |
19 | #include "src/gpu/glsl/GrGLSLVarying.h" |
20 | #include "src/gpu/glsl/GrGLSLXferProcessor.h" |
21 | #include "src/sksl/SkSLCompiler.h" |
22 | |
23 | const int GrGLSLProgramBuilder::kVarsPerBlock = 8; |
24 | |
25 | GrGLSLProgramBuilder::GrGLSLProgramBuilder(GrRenderTarget* renderTarget, |
26 | const GrProgramDesc& desc, |
27 | const GrProgramInfo& programInfo) |
28 | : fVS(this) |
29 | , fGS(this) |
30 | , fFS(this) |
31 | , fStageIndex(-1) |
32 | , fRenderTarget(renderTarget) |
33 | , fDesc(desc) |
34 | , fProgramInfo(programInfo) |
35 | , fGeometryProcessor(nullptr) |
36 | , fXferProcessor(nullptr) |
37 | , fNumFragmentSamplers(0) {} |
38 | |
39 | void GrGLSLProgramBuilder::addFeature(GrShaderFlags shaders, |
40 | uint32_t featureBit, |
41 | const char* extensionName) { |
42 | if (shaders & kVertex_GrShaderFlag) { |
43 | fVS.addFeature(featureBit, extensionName); |
44 | } |
45 | if (shaders & kGeometry_GrShaderFlag) { |
46 | SkASSERT(this->primitiveProcessor().willUseGeoShader()); |
47 | fGS.addFeature(featureBit, extensionName); |
48 | } |
49 | if (shaders & kFragment_GrShaderFlag) { |
50 | fFS.addFeature(featureBit, extensionName); |
51 | } |
52 | } |
53 | |
54 | bool GrGLSLProgramBuilder::emitAndInstallProcs() { |
55 | // First we loop over all of the installed processors and collect coord transforms. These will |
56 | // be sent to the GrGLSLPrimitiveProcessor in its emitCode function |
57 | SkString inputColor; |
58 | SkString inputCoverage; |
59 | this->emitAndInstallPrimProc(&inputColor, &inputCoverage); |
60 | this->emitAndInstallFragProcs(&inputColor, &inputCoverage); |
61 | this->emitAndInstallXferProc(inputColor, inputCoverage); |
62 | fGeometryProcessor->emitTransformCode(&fVS, this->uniformHandler()); |
63 | |
64 | return this->checkSamplerCounts(); |
65 | } |
66 | |
67 | void GrGLSLProgramBuilder::emitAndInstallPrimProc(SkString* outputColor, SkString* outputCoverage) { |
68 | const GrPrimitiveProcessor& proc = this->primitiveProcessor(); |
69 | |
70 | // Program builders have a bit of state we need to clear with each effect |
71 | AutoStageAdvance adv(this); |
72 | this->nameExpression(outputColor, "outputColor" ); |
73 | this->nameExpression(outputCoverage, "outputCoverage" ); |
74 | |
75 | SkASSERT(!fUniformHandles.fRTAdjustmentUni.isValid()); |
76 | GrShaderFlags rtAdjustVisibility; |
77 | if (proc.willUseGeoShader()) { |
78 | rtAdjustVisibility = kGeometry_GrShaderFlag; |
79 | } else if (proc.willUseTessellationShaders()) { |
80 | rtAdjustVisibility = kTessEvaluation_GrShaderFlag; |
81 | } else { |
82 | rtAdjustVisibility = kVertex_GrShaderFlag; |
83 | } |
84 | fUniformHandles.fRTAdjustmentUni = this->uniformHandler()->addUniform( |
85 | nullptr, rtAdjustVisibility, kFloat4_GrSLType, SkSL::Compiler::RTADJUST_NAME); |
86 | const char* rtAdjustName = |
87 | this->uniformHandler()->getUniformCStr(fUniformHandles.fRTAdjustmentUni); |
88 | |
89 | // Enclose custom code in a block to avoid namespace conflicts |
90 | SkString openBrace; |
91 | openBrace.printf("{ // Stage %d, %s\n" , fStageIndex, proc.name()); |
92 | fFS.codeAppend(openBrace.c_str()); |
93 | fVS.codeAppendf("// Primitive Processor %s\n" , proc.name()); |
94 | |
95 | SkASSERT(!fGeometryProcessor); |
96 | fGeometryProcessor.reset(proc.createGLSLInstance(*this->shaderCaps())); |
97 | |
98 | SkAutoSTMalloc<4, SamplerHandle> texSamplers(proc.numTextureSamplers()); |
99 | for (int i = 0; i < proc.numTextureSamplers(); ++i) { |
100 | SkString name; |
101 | name.printf("TextureSampler_%d" , i); |
102 | const auto& sampler = proc.textureSampler(i); |
103 | texSamplers[i] = this->emitSampler(proc.textureSampler(i).backendFormat(), |
104 | sampler.samplerState(), |
105 | sampler.swizzle(), |
106 | name.c_str()); |
107 | } |
108 | |
109 | GrGLSLPrimitiveProcessor::FPCoordTransformHandler transformHandler(this->pipeline(), |
110 | &fTransformedCoordVars); |
111 | GrGLSLGeometryProcessor::EmitArgs args(&fVS, |
112 | proc.willUseGeoShader() ? &fGS : nullptr, |
113 | &fFS, |
114 | this->varyingHandler(), |
115 | this->uniformHandler(), |
116 | this->shaderCaps(), |
117 | proc, |
118 | outputColor->c_str(), |
119 | outputCoverage->c_str(), |
120 | rtAdjustName, |
121 | texSamplers.get(), |
122 | &transformHandler); |
123 | fGeometryProcessor->emitCode(args); |
124 | |
125 | // We have to check that effects and the code they emit are consistent, ie if an effect |
126 | // asks for dst color, then the emit code needs to follow suit |
127 | SkDEBUGCODE(verify(proc);) |
128 | |
129 | fFS.codeAppend("}" ); |
130 | } |
131 | |
132 | void GrGLSLProgramBuilder::emitAndInstallFragProcs(SkString* color, SkString* coverage) { |
133 | int transformedCoordVarsIdx = 0; |
134 | int fpCount = this->pipeline().numFragmentProcessors(); |
135 | fFragmentProcessors = std::make_unique<std::unique_ptr<GrGLSLFragmentProcessor>[]>(fpCount); |
136 | for (int i = 0; i < fpCount; ++i) { |
137 | SkString* inOut = this->pipeline().isColorFragmentProcessor(i) ? color : coverage; |
138 | SkString output; |
139 | const GrFragmentProcessor& fp = this->pipeline().getFragmentProcessor(i); |
140 | fFragmentProcessors[i] = std::unique_ptr<GrGLSLFragmentProcessor>(fp.createGLSLInstance()); |
141 | output = this->emitFragProc(fp, *fFragmentProcessors[i], transformedCoordVarsIdx, *inOut, |
142 | output); |
143 | for (const auto& subFP : GrFragmentProcessor::FPRange(fp)) { |
144 | transformedCoordVarsIdx += subFP.numVaryingCoordsUsed(); |
145 | } |
146 | *inOut = std::move(output); |
147 | } |
148 | } |
149 | |
150 | // TODO Processors cannot output zeros because an empty string is all 1s |
151 | // the fix is to allow effects to take the SkString directly |
152 | SkString GrGLSLProgramBuilder::emitFragProc(const GrFragmentProcessor& fp, |
153 | GrGLSLFragmentProcessor& glslFP, |
154 | int transformedCoordVarsIdx, |
155 | const SkString& input, |
156 | SkString output) { |
157 | SkASSERT(input.size()); |
158 | // Program builders have a bit of state we need to clear with each effect |
159 | AutoStageAdvance adv(this); |
160 | this->nameExpression(&output, "output" ); |
161 | |
162 | // Enclose custom code in a block to avoid namespace conflicts |
163 | SkString openBrace; |
164 | openBrace.printf("{ // Stage %d, %s\n" , fStageIndex, fp.name()); |
165 | fFS.codeAppend(openBrace.c_str()); |
166 | |
167 | int samplerIdx = 0; |
168 | for (auto [subFP, subGLSLFP] : GrGLSLFragmentProcessor::ParallelRange(fp, glslFP)) { |
169 | if (auto* te = subFP.asTextureEffect()) { |
170 | SkString name; |
171 | name.printf("TextureSampler_%d" , samplerIdx++); |
172 | |
173 | GrSamplerState samplerState = te->samplerState(); |
174 | const GrBackendFormat& format = te->view().proxy()->backendFormat(); |
175 | GrSwizzle swizzle = te->view().swizzle(); |
176 | SamplerHandle handle = this->emitSampler(format, samplerState, swizzle, name.c_str()); |
177 | static_cast<GrTextureEffect::Impl&>(subGLSLFP).setSamplerHandle(handle); |
178 | } |
179 | } |
180 | const GrShaderVar* coordVars = fTransformedCoordVars.begin() + transformedCoordVarsIdx; |
181 | GrGLSLFragmentProcessor::TransformedCoordVars coords(&fp, coordVars); |
182 | GrGLSLFragmentProcessor::EmitArgs args(&fFS, |
183 | this->uniformHandler(), |
184 | this->shaderCaps(), |
185 | fp, |
186 | output.c_str(), |
187 | input.c_str(), |
188 | "_coords" , |
189 | coords); |
190 | |
191 | if (fp.referencesSampleCoords()) { |
192 | // The fp's generated code expects a _coords variable, but we're at the root so _coords |
193 | // is just the local coordinates produced by the primitive processor. |
194 | SkASSERT(fp.usesVaryingCoordsDirectly()); |
195 | |
196 | const GrShaderVar& varying = coordVars[0]; |
197 | switch(varying.getType()) { |
198 | case kFloat2_GrSLType: |
199 | fFS.codeAppendf("float2 %s = %s.xy;\n" , |
200 | args.fSampleCoord, varying.getName().c_str()); |
201 | break; |
202 | case kFloat3_GrSLType: |
203 | fFS.codeAppendf("float2 %s = %s.xy / %s.z;\n" , |
204 | args.fSampleCoord, |
205 | varying.getName().c_str(), |
206 | varying.getName().c_str()); |
207 | break; |
208 | default: |
209 | SkDEBUGFAILF("Unexpected type for varying: %d named %s\n" , |
210 | (int) varying.getType(), varying.getName().c_str()); |
211 | break; |
212 | } |
213 | } |
214 | |
215 | glslFP.emitCode(args); |
216 | |
217 | // We have to check that effects and the code they emit are consistent, ie if an effect |
218 | // asks for dst color, then the emit code needs to follow suit |
219 | SkDEBUGCODE(verify(fp);) |
220 | |
221 | fFS.codeAppend("}" ); |
222 | return output; |
223 | } |
224 | |
225 | void GrGLSLProgramBuilder::emitAndInstallXferProc(const SkString& colorIn, |
226 | const SkString& coverageIn) { |
227 | // Program builders have a bit of state we need to clear with each effect |
228 | AutoStageAdvance adv(this); |
229 | |
230 | SkASSERT(!fXferProcessor); |
231 | const GrXferProcessor& xp = this->pipeline().getXferProcessor(); |
232 | fXferProcessor.reset(xp.createGLSLInstance()); |
233 | |
234 | // Enable dual source secondary output if we have one |
235 | if (xp.hasSecondaryOutput()) { |
236 | fFS.enableSecondaryOutput(); |
237 | } |
238 | |
239 | if (this->shaderCaps()->mustDeclareFragmentShaderOutput()) { |
240 | fFS.enableCustomOutput(); |
241 | } |
242 | |
243 | SkString openBrace; |
244 | openBrace.printf("{ // Xfer Processor: %s\n" , xp.name()); |
245 | fFS.codeAppend(openBrace.c_str()); |
246 | |
247 | SamplerHandle dstTextureSamplerHandle; |
248 | GrSurfaceOrigin dstTextureOrigin = kTopLeft_GrSurfaceOrigin; |
249 | |
250 | const GrSurfaceProxyView& dstView = this->pipeline().dstProxyView(); |
251 | if (GrTextureProxy* dstTextureProxy = dstView.asTextureProxy()) { |
252 | // GrProcessor::TextureSampler sampler(dstTexture); |
253 | const GrSwizzle& swizzle = dstView.swizzle(); |
254 | dstTextureSamplerHandle = this->emitSampler(dstTextureProxy->backendFormat(), |
255 | GrSamplerState(), swizzle, "DstTextureSampler" ); |
256 | dstTextureOrigin = dstView.origin(); |
257 | SkASSERT(dstTextureProxy->textureType() != GrTextureType::kExternal); |
258 | } |
259 | |
260 | SkString finalInColor = colorIn.size() ? colorIn : SkString("float4(1)" ); |
261 | |
262 | GrGLSLXferProcessor::EmitArgs args(&fFS, |
263 | this->uniformHandler(), |
264 | this->shaderCaps(), |
265 | xp, |
266 | finalInColor.c_str(), |
267 | coverageIn.size() ? coverageIn.c_str() : "float4(1)" , |
268 | fFS.getPrimaryColorOutputName(), |
269 | fFS.getSecondaryColorOutputName(), |
270 | dstTextureSamplerHandle, |
271 | dstTextureOrigin, |
272 | this->pipeline().writeSwizzle()); |
273 | fXferProcessor->emitCode(args); |
274 | |
275 | // We have to check that effects and the code they emit are consistent, ie if an effect |
276 | // asks for dst color, then the emit code needs to follow suit |
277 | SkDEBUGCODE(verify(xp);) |
278 | fFS.codeAppend("}" ); |
279 | } |
280 | |
281 | GrGLSLProgramBuilder::SamplerHandle GrGLSLProgramBuilder::emitSampler( |
282 | const GrBackendFormat& backendFormat, GrSamplerState state, const GrSwizzle& swizzle, |
283 | const char* name) { |
284 | ++fNumFragmentSamplers; |
285 | return this->uniformHandler()->addSampler(backendFormat, state, swizzle, name, |
286 | this->shaderCaps()); |
287 | } |
288 | |
289 | bool GrGLSLProgramBuilder::checkSamplerCounts() { |
290 | const GrShaderCaps& shaderCaps = *this->shaderCaps(); |
291 | if (fNumFragmentSamplers > shaderCaps.maxFragmentSamplers()) { |
292 | GrCapsDebugf(this->caps(), "Program would use too many fragment samplers\n" ); |
293 | return false; |
294 | } |
295 | return true; |
296 | } |
297 | |
298 | #ifdef SK_DEBUG |
299 | void GrGLSLProgramBuilder::verify(const GrPrimitiveProcessor& gp) { |
300 | SkASSERT(!fFS.fHasReadDstColorThisStage_DebugOnly); |
301 | SkASSERT(fFS.fUsedProcessorFeaturesThisStage_DebugOnly == gp.requestedFeatures()); |
302 | } |
303 | |
304 | void GrGLSLProgramBuilder::verify(const GrFragmentProcessor& fp) { |
305 | SkASSERT(!fFS.fHasReadDstColorThisStage_DebugOnly); |
306 | SkASSERT(fFS.fUsedProcessorFeaturesThisStage_DebugOnly == fp.requestedFeatures()); |
307 | } |
308 | |
309 | void GrGLSLProgramBuilder::verify(const GrXferProcessor& xp) { |
310 | SkASSERT(xp.willReadDstColor() == fFS.fHasReadDstColorThisStage_DebugOnly); |
311 | SkASSERT(fFS.fUsedProcessorFeaturesThisStage_DebugOnly == xp.requestedFeatures()); |
312 | } |
313 | #endif |
314 | |
315 | void GrGLSLProgramBuilder::nameVariable(SkString* out, char prefix, const char* name, bool mangle) { |
316 | if ('\0' == prefix) { |
317 | *out = name; |
318 | } else { |
319 | out->printf("%c%s" , prefix, name); |
320 | } |
321 | if (mangle) { |
322 | if (out->endsWith('_')) { |
323 | // Names containing "__" are reserved. |
324 | out->append("x" ); |
325 | } |
326 | out->appendf("_Stage%d%s" , fStageIndex, fFS.getMangleString().c_str()); |
327 | } |
328 | } |
329 | |
330 | void GrGLSLProgramBuilder::nameExpression(SkString* output, const char* baseName) { |
331 | // create var to hold stage result. If we already have a valid output name, just use that |
332 | // otherwise create a new mangled one. This name is only valid if we are reordering stages |
333 | // and have to tell stage exactly where to put its output. |
334 | SkString outName; |
335 | if (output->size()) { |
336 | outName = output->c_str(); |
337 | } else { |
338 | this->nameVariable(&outName, '\0', baseName); |
339 | } |
340 | fFS.codeAppendf("half4 %s;" , outName.c_str()); |
341 | *output = outName; |
342 | } |
343 | |
344 | void GrGLSLProgramBuilder::appendUniformDecls(GrShaderFlags visibility, SkString* out) const { |
345 | this->uniformHandler()->appendUniformDecls(visibility, out); |
346 | } |
347 | |
348 | void GrGLSLProgramBuilder::addRTWidthUniform(const char* name) { |
349 | SkASSERT(!fUniformHandles.fRTWidthUni.isValid()); |
350 | GrGLSLUniformHandler* uniformHandler = this->uniformHandler(); |
351 | fUniformHandles.fRTWidthUni = |
352 | uniformHandler->internalAddUniformArray(nullptr, kFragment_GrShaderFlag, kHalf_GrSLType, |
353 | name, false, 0, nullptr); |
354 | } |
355 | |
356 | void GrGLSLProgramBuilder::addRTHeightUniform(const char* name) { |
357 | SkASSERT(!fUniformHandles.fRTHeightUni.isValid()); |
358 | GrGLSLUniformHandler* uniformHandler = this->uniformHandler(); |
359 | fUniformHandles.fRTHeightUni = |
360 | uniformHandler->internalAddUniformArray(nullptr, kFragment_GrShaderFlag, kHalf_GrSLType, |
361 | name, false, 0, nullptr); |
362 | } |
363 | |
364 | void GrGLSLProgramBuilder::finalizeShaders() { |
365 | this->varyingHandler()->finalize(); |
366 | fVS.finalize(kVertex_GrShaderFlag); |
367 | if (this->primitiveProcessor().willUseGeoShader()) { |
368 | SkASSERT(this->shaderCaps()->geometryShaderSupport()); |
369 | fGS.finalize(kGeometry_GrShaderFlag); |
370 | } |
371 | fFS.finalize(kFragment_GrShaderFlag); |
372 | } |
373 | |