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/core/SkTraceEvent.h"
13 #include "src/gpu/GrCaps.h"
14 #include "src/gpu/GrFragmentProcessor.h"
15 #include "src/gpu/GrGeometryProcessor.h"
16 #include "src/gpu/GrPipeline.h"
17 #include "src/gpu/GrRenderTarget.h"
18 #include "src/gpu/GrShaderCaps.h"
19 #include "src/gpu/GrTexture.h"
20 #include "src/gpu/GrXferProcessor.h"
21 #include "src/gpu/effects/GrTextureEffect.h"
22 #include "src/gpu/glsl/GrGLSLVarying.h"
23 #include "src/sksl/SkSLCompiler.h"
24 #include "src/sksl/dsl/priv/DSLFPs.h"
25 
26 const int GrGLSLProgramBuilder::kVarsPerBlock = 8;
27 
GrGLSLProgramBuilder(const GrProgramDesc& desc, const GrProgramInfo& programInfo)28 GrGLSLProgramBuilder::GrGLSLProgramBuilder(const GrProgramDesc& desc,
29                                            const GrProgramInfo& programInfo)
30         : fVS(this)
31         , fFS(this)
32         , fDesc(desc)
33         , fProgramInfo(programInfo)
34         , fNumFragmentSamplers(0) {}
35 
36 GrGLSLProgramBuilder::~GrGLSLProgramBuilder() = default;
37 
addFeature(GrShaderFlags shaders, uint32_t featureBit, const char* extensionName)38 void GrGLSLProgramBuilder::addFeature(GrShaderFlags shaders,
39                                       uint32_t featureBit,
40                                       const char* extensionName) {
41     if (shaders & kVertex_GrShaderFlag) {
42         fVS.addFeature(featureBit, extensionName);
43     }
44     if (shaders & kFragment_GrShaderFlag) {
45         fFS.addFeature(featureBit, extensionName);
46     }
47 }
48 
emitAndInstallProcs()49 bool GrGLSLProgramBuilder::emitAndInstallProcs() {
50     // First we loop over all of the installed processors and collect coord transforms.  These will
51     // be sent to the ProgramImpl in its emitCode function
52     SkSL::dsl::Start(this->shaderCompiler());
53     SkString inputColor;
54     SkString inputCoverage;
55     if (!this->emitAndInstallPrimProc(&inputColor, &inputCoverage)) {
56         return false;
57     }
58     if (!this->emitAndInstallDstTexture()) {
59         return false;
60     }
61     if (!this->emitAndInstallFragProcs(&inputColor, &inputCoverage)) {
62         return false;
63     }
64     if (!this->emitAndInstallXferProc(inputColor, inputCoverage)) {
65         return false;
66     }
67     fGPImpl->emitTransformCode(&fVS, this->uniformHandler());
68     SkSL::dsl::End();
69 
70     return this->checkSamplerCounts();
71 }
72 
emitAndInstallPrimProc(SkString* outputColor, SkString* outputCoverage)73 bool GrGLSLProgramBuilder::emitAndInstallPrimProc(SkString* outputColor, SkString* outputCoverage) {
74     const GrGeometryProcessor& geomProc = this->geometryProcessor();
75 
76     // Program builders have a bit of state we need to clear with each effect
77     this->advanceStage();
78     this->nameExpression(outputColor, "outputColor");
79     this->nameExpression(outputCoverage, "outputCoverage");
80 
81     SkASSERT(!fUniformHandles.fRTAdjustmentUni.isValid());
82     GrShaderFlags rtAdjustVisibility;
83     if (geomProc.willUseTessellationShaders()) {
84         rtAdjustVisibility = kTessEvaluation_GrShaderFlag;
85     } else {
86         rtAdjustVisibility = kVertex_GrShaderFlag;
87     }
88     fUniformHandles.fRTAdjustmentUni = this->uniformHandler()->addUniform(
89             nullptr, rtAdjustVisibility, kFloat4_GrSLType, SkSL::Compiler::RTADJUST_NAME);
90 
91     fFS.codeAppendf("// Stage %d, %s\n", fStageIndex, geomProc.name());
92     fVS.codeAppendf("// Primitive Processor %s\n", geomProc.name());
93 
94     HITRACE_OHOS_NAME_ALWAYS(geomProc.getShaderDfxInfo().c_str());
95     SkASSERT(!fGPImpl);
96     fGPImpl = geomProc.makeProgramImpl(*this->shaderCaps());
97 
98     SkAutoSTArray<4, SamplerHandle> texSamplers(geomProc.numTextureSamplers());
99     for (int i = 0; i < geomProc.numTextureSamplers(); ++i) {
100         SkString name;
101         name.printf("TextureSampler_%d", i);
102         const auto& sampler = geomProc.textureSampler(i);
103         texSamplers[i] = this->emitSampler(geomProc.textureSampler(i).backendFormat(),
104                                            sampler.samplerState(),
105                                            sampler.swizzle(),
106                                            name.c_str());
107         if (!texSamplers[i].isValid()) {
108             return false;
109         }
110     }
111 
112     GrGeometryProcessor::ProgramImpl::EmitArgs args(&fVS,
113                                                     &fFS,
114                                                     this->varyingHandler(),
115                                                     this->uniformHandler(),
116                                                     this->shaderCaps(),
117                                                     geomProc,
118                                                     outputColor->c_str(),
119                                                     outputCoverage->c_str(),
120                                                     texSamplers.get());
121     fFPCoordsMap = fGPImpl->emitCode(args, this->pipeline());
122 
123     // We have to check that effects and the code they emit are consistent, ie if an effect
124     // asks for dst color, then the emit code needs to follow suit
125     SkDEBUGCODE(verify(geomProc);)
126 
127     return true;
128 }
129 
emitAndInstallFragProcs(SkString* color, SkString* coverage)130 bool GrGLSLProgramBuilder::emitAndInstallFragProcs(SkString* color, SkString* coverage) {
131     int fpCount = this->pipeline().numFragmentProcessors();
132     SkASSERT(fFPImpls.empty());
133     fFPImpls.reserve(fpCount);
134     for (int i = 0; i < fpCount; ++i) {
135         SkString* inOut = this->pipeline().isColorFragmentProcessor(i) ? color : coverage;
136         SkString output;
137         const GrFragmentProcessor& fp = this->pipeline().getFragmentProcessor(i);
138         fFPImpls.push_back(fp.makeProgramImpl());
139         output = this->emitFragProc(fp, *fFPImpls.back(), *inOut, output);
140         if (output.isEmpty()) {
141             return false;
142         }
143         *inOut = std::move(output);
144     }
145     return true;
146 }
147 
emitFragProc(const GrFragmentProcessor& fp, GrFragmentProcessor::ProgramImpl& impl, const SkString& input, SkString output)148 SkString GrGLSLProgramBuilder::emitFragProc(const GrFragmentProcessor& fp,
149                                             GrFragmentProcessor::ProgramImpl& impl,
150                                             const SkString& input,
151                                             SkString output) {
152     SkASSERT(input.size());
153 
154     // Program builders have a bit of state we need to clear with each effect
155     this->advanceStage();
156     this->nameExpression(&output, "output");
157     fFS.codeAppendf("half4 %s;", output.c_str());
158     bool ok = true;
159     fp.visitWithImpls([&, samplerIdx = 0](const GrFragmentProcessor& fp,
160                                           GrFragmentProcessor::ProgramImpl& impl) mutable {
161         if (auto* te = fp.asTextureEffect()) {
162             SkString name;
163             name.printf("TextureSampler_%d", samplerIdx++);
164 
165             GrSamplerState samplerState = te->samplerState();
166             const GrBackendFormat& format = te->view().proxy()->backendFormat();
167             GrSwizzle swizzle = te->view().swizzle();
168             SamplerHandle handle = this->emitSampler(format, samplerState, swizzle, name.c_str());
169             if (!handle.isValid()) {
170                 ok = false;
171                 return;
172             }
173             static_cast<GrTextureEffect::Impl&>(impl).setSamplerHandle(handle);
174         }
175     }, impl);
176     if (!ok) {
177         return {};
178     }
179 
180     this->writeFPFunction(fp, impl);
181 
182     if (fp.isBlendFunction()) {
183         fFS.codeAppendf(
184                 "%s = %s(%s, half4(1));", output.c_str(), impl.functionName(), input.c_str());
185     } else {
186         fFS.codeAppendf("%s = %s(%s);", output.c_str(), impl.functionName(), input.c_str());
187     }
188 
189     // We have to check that effects and the code they emit are consistent, ie if an effect asks
190     // for dst color, then the emit code needs to follow suit
191     SkDEBUGCODE(verify(fp);)
192 
193     return output;
194 }
195 
writeChildFPFunctions(const GrFragmentProcessor& fp, GrFragmentProcessor::ProgramImpl& impl)196 void GrGLSLProgramBuilder::writeChildFPFunctions(const GrFragmentProcessor& fp,
197                                                  GrFragmentProcessor::ProgramImpl& impl) {
198     fSubstageIndices.push_back(0);
199     for (int i = 0; i < impl.numChildProcessors(); ++i) {
200         GrFragmentProcessor::ProgramImpl* childImpl = impl.childProcessor(i);
201         if (!childImpl) {
202             continue;
203         }
204 
205         const GrFragmentProcessor* childFP = fp.childProcessor(i);
206         SkASSERT(childFP);
207 
208         this->writeFPFunction(*childFP, *childImpl);
209         ++fSubstageIndices.back();
210     }
211     fSubstageIndices.pop_back();
212 }
213 
writeFPFunction(const GrFragmentProcessor& fp, GrFragmentProcessor::ProgramImpl& impl)214 void GrGLSLProgramBuilder::writeFPFunction(const GrFragmentProcessor& fp,
215                                            GrFragmentProcessor::ProgramImpl& impl) {
216     constexpr const char*       kDstColor    = "_dst";
217               const char* const inputColor   = fp.isBlendFunction() ? "_src" : "_input";
218               const char*       sampleCoords = "_coords";
219 
220     HITRACE_OHOS_NAME_ALWAYS(fp.getShaderDfxInfo().c_str());
221     fFS.nextStage();
222     // Conceptually, an FP is always sampled at a particular coordinate. However, if it is only
223     // sampled by a chain of uniform matrix expressions (or legacy coord transforms), the value that
224     // would have been passed to _coords is lifted to the vertex shader and
225     // varying. In that case it uses that variable and we do not pass a second argument for _coords.
226     GrShaderVar params[3];
227     int numParams = 0;
228 
229     params[numParams++] = GrShaderVar(inputColor, kHalf4_GrSLType);
230 
231     if (fp.isBlendFunction()) {
232         // Blend functions take a dest color as input.
233         params[numParams++] = GrShaderVar(kDstColor, kHalf4_GrSLType);
234     }
235 
236     if (this->fragmentProcessorHasCoordsParam(&fp)) {
237         params[numParams++] = GrShaderVar(sampleCoords, kFloat2_GrSLType);
238     } else {
239         // Either doesn't use coords at all or sampled through a chain of passthrough/matrix
240         // samples usages. In the latter case the coords are emitted in the vertex shader as a
241         // varying, so this only has to access it. Add a float2 _coords variable that maps to the
242         // associated varying and replaces the absent 2nd argument to the fp's function.
243         GrShaderVar varying = fFPCoordsMap[&fp].coordsVarying;
244 
245         switch (varying.getType()) {
246             case kVoid_GrSLType:
247                 SkASSERT(!fp.usesSampleCoordsDirectly());
248                 break;
249             case kFloat2_GrSLType:
250                 // Just point the local coords to the varying
251                 sampleCoords = varying.getName().c_str();
252                 break;
253             case kFloat3_GrSLType:
254                 // Must perform the perspective divide in the frag shader based on the
255                 // varying, and since we won't actually have a function parameter for local
256                 // coords, add it as a local variable.
257                 fFS.codeAppendf("float2 %s = %s.xy / %s.z;\n",
258                                 sampleCoords,
259                                 varying.getName().c_str(),
260                                 varying.getName().c_str());
261                 break;
262             default:
263                 SkDEBUGFAILF("Unexpected varying type for coord: %s %d\n",
264                              varying.getName().c_str(),
265                              (int)varying.getType());
266                 break;
267         }
268     }
269 
270     SkASSERT(numParams <= (int)SK_ARRAY_COUNT(params));
271 
272     // First, emit every child's function. This needs to happen (even for children that aren't
273     // sampled), so that all of the expected uniforms are registered.
274     this->writeChildFPFunctions(fp, impl);
275     GrFragmentProcessor::ProgramImpl::EmitArgs args(&fFS,
276                                                     this->uniformHandler(),
277                                                     this->shaderCaps(),
278                                                     fp,
279                                                     inputColor,
280                                                     kDstColor,
281                                                     sampleCoords);
282 
283     impl.emitCode(args);
284     impl.setFunctionName(fFS.getMangledFunctionName(args.fFp.name()));
285 
286     fFS.emitFunction(kHalf4_GrSLType,
287                      impl.functionName(),
288                      SkMakeSpan(params, numParams),
289                      fFS.code().c_str());
290     fFS.deleteStage();
291 }
292 
emitAndInstallDstTexture()293 bool GrGLSLProgramBuilder::emitAndInstallDstTexture() {
294     fDstTextureOrigin = kTopLeft_GrSurfaceOrigin;
295 
296     const GrSurfaceProxyView& dstView = this->pipeline().dstProxyView();
297     if (this->pipeline().usesDstTexture()) {
298         // Set up a sampler handle for the destination texture.
299         GrTextureProxy* dstTextureProxy = dstView.asTextureProxy();
300         SkASSERT(dstTextureProxy);
301         const GrSwizzle& swizzle = dstView.swizzle();
302         fDstTextureSamplerHandle = this->emitSampler(dstTextureProxy->backendFormat(),
303                                                     GrSamplerState(), swizzle, "DstTextureSampler");
304         if (!fDstTextureSamplerHandle.isValid()) {
305             return false;
306         }
307 
308         HITRACE_OHOS_NAME_ALWAYS("ShaderDfx emitAndInstallDstTexture usesDstTexture");
309         fDstTextureOrigin = dstView.origin();
310         SkASSERT(dstTextureProxy->textureType() != GrTextureType::kExternal);
311 
312         // Declare a _dstColor global variable which samples from the dest-texture sampler at the
313         // top of the fragment shader.
314         const char* dstTextureCoordsName;
315         fUniformHandles.fDstTextureCoordsUni = this->uniformHandler()->addUniform(
316                 /*owner=*/nullptr,
317                 kFragment_GrShaderFlag,
318                 kHalf4_GrSLType,
319                 "DstTextureCoords",
320                 &dstTextureCoordsName);
321         fFS.codeAppend("// Read color from copy of the destination\n");
322         fFS.codeAppendf("half2 _dstTexCoord = (half2(sk_FragCoord.xy) - %s.xy) * %s.zw;\n",
323                         dstTextureCoordsName, dstTextureCoordsName);
324         if (fDstTextureOrigin == kBottomLeft_GrSurfaceOrigin) {
325             fFS.codeAppend("_dstTexCoord.y = 1.0 - _dstTexCoord.y;\n");
326         }
327         const char* dstColor = fFS.dstColor();
328         SkString dstColorDecl = SkStringPrintf("half4 %s;", dstColor);
329         fFS.definitionAppend(dstColorDecl.c_str());
330         fFS.codeAppendf("%s = ", dstColor);
331         fFS.appendTextureLookup(fDstTextureSamplerHandle, "_dstTexCoord");
332         fFS.codeAppend(";\n");
333     } else if (this->pipeline().usesDstInputAttachment()) {
334         // Set up an input attachment for the destination texture.
335         const GrSwizzle& swizzle = dstView.swizzle();
336         fDstTextureSamplerHandle = this->emitInputSampler(swizzle, "DstTextureInput");
337         if (!fDstTextureSamplerHandle.isValid()) {
338             return false;
339         }
340 
341         HITRACE_OHOS_NAME_ALWAYS("ShaderDfx emitAndInstallDstTexture usesDstInputAttachment");
342         // Populate the _dstColor variable by loading from the input attachment at the top of the
343         // fragment shader.
344         fFS.codeAppend("// Read color from input attachment\n");
345         const char* dstColor = fFS.dstColor();
346         SkString dstColorDecl = SkStringPrintf("half4 %s;", dstColor);
347         fFS.definitionAppend(dstColorDecl.c_str());
348         fFS.codeAppendf("%s = ", dstColor);
349         fFS.appendInputLoad(fDstTextureSamplerHandle);
350         fFS.codeAppend(";\n");
351     }
352 
353     return true;
354 }
355 
emitAndInstallXferProc(const SkString& colorIn, const SkString& coverageIn)356 bool GrGLSLProgramBuilder::emitAndInstallXferProc(const SkString& colorIn,
357                                                   const SkString& coverageIn) {
358     // Program builders have a bit of state we need to clear with each effect
359     this->advanceStage();
360 
361     SkASSERT(!fXPImpl);
362     const GrXferProcessor& xp = this->pipeline().getXferProcessor();
363     fXPImpl = xp.makeProgramImpl();
364 
365     HITRACE_OHOS_NAME_ALWAYS(xp.getShaderDfxInfo().c_str());
366     // Enable dual source secondary output if we have one
367     if (xp.hasSecondaryOutput()) {
368         fFS.enableSecondaryOutput();
369     }
370 
371     if (this->shaderCaps()->mustDeclareFragmentShaderOutput()) {
372         fFS.enableCustomOutput();
373     }
374 
375     SkString openBrace;
376     openBrace.printf("{ // Xfer Processor: %s\n", xp.name());
377     fFS.codeAppend(openBrace.c_str());
378 
379     SkString finalInColor = colorIn.size() ? colorIn : SkString("float4(1)");
380 
381     GrXferProcessor::ProgramImpl::EmitArgs args(
382             &fFS,
383             this->uniformHandler(),
384             this->shaderCaps(),
385             xp,
386             finalInColor.c_str(),
387             coverageIn.size() ? coverageIn.c_str() : "float4(1)",
388             fFS.getPrimaryColorOutputName(),
389             fFS.getSecondaryColorOutputName(),
390             fDstTextureSamplerHandle,
391             fDstTextureOrigin,
392             this->pipeline().writeSwizzle());
393     fXPImpl->emitCode(args);
394 
395     // We have to check that effects and the code they emit are consistent, ie if an effect
396     // asks for dst color, then the emit code needs to follow suit
397     SkDEBUGCODE(verify(xp);)
398     fFS.codeAppend("}");
399     return true;
400 }
401 
emitSampler( const GrBackendFormat& backendFormat, GrSamplerState state, const GrSwizzle& swizzle, const char* name)402 GrGLSLProgramBuilder::SamplerHandle GrGLSLProgramBuilder::emitSampler(
403         const GrBackendFormat& backendFormat, GrSamplerState state, const GrSwizzle& swizzle,
404         const char* name) {
405     ++fNumFragmentSamplers;
406     return this->uniformHandler()->addSampler(backendFormat, state, swizzle, name,
407                                               this->shaderCaps());
408 }
409 
emitInputSampler(const GrSwizzle& swizzle, const char* name)410 GrGLSLProgramBuilder::SamplerHandle GrGLSLProgramBuilder::emitInputSampler(const GrSwizzle& swizzle,
411                                                                            const char* name) {
412     return this->uniformHandler()->addInputSampler(swizzle, name);
413 }
414 
checkSamplerCounts()415 bool GrGLSLProgramBuilder::checkSamplerCounts() {
416     const GrShaderCaps& shaderCaps = *this->shaderCaps();
417     if (fNumFragmentSamplers > shaderCaps.maxFragmentSamplers()) {
418         GrCapsDebugf(this->caps(), "Program would use too many fragment samplers\n");
419         return false;
420     }
421     return true;
422 }
423 
424 #ifdef SK_DEBUG
verify(const GrGeometryProcessor& geomProc)425 void GrGLSLProgramBuilder::verify(const GrGeometryProcessor& geomProc) {
426     SkASSERT(!fFS.fHasReadDstColorThisStage_DebugOnly);
427 }
428 
verify(const GrFragmentProcessor& fp)429 void GrGLSLProgramBuilder::verify(const GrFragmentProcessor& fp) {
430     SkASSERT(fp.willReadDstColor() == fFS.fHasReadDstColorThisStage_DebugOnly);
431 }
432 
verify(const GrXferProcessor& xp)433 void GrGLSLProgramBuilder::verify(const GrXferProcessor& xp) {
434     SkASSERT(xp.willReadDstColor() == fFS.fHasReadDstColorThisStage_DebugOnly);
435 }
436 #endif
437 
getMangleSuffix() const438 SkString GrGLSLProgramBuilder::getMangleSuffix() const {
439     SkASSERT(fStageIndex >= 0);
440     SkString suffix;
441     suffix.printf("_S%d", fStageIndex);
442     for (auto c : fSubstageIndices) {
443         suffix.appendf("_c%d", c);
444     }
445     return suffix;
446 }
447 
nameVariable(char prefix, const char* name, bool mangle)448 SkString GrGLSLProgramBuilder::nameVariable(char prefix, const char* name, bool mangle) {
449     SkString out;
450     if ('\0' == prefix) {
451         out = name;
452     } else {
453         out.printf("%c%s", prefix, name);
454     }
455     if (mangle) {
456         SkString suffix = this->getMangleSuffix();
457         // Names containing "__" are reserved; add "x" if needed to avoid consecutive underscores.
458         const char *underscoreSplitter = out.endsWith('_') ? "x" : "";
459         out.appendf("%s%s", underscoreSplitter, suffix.c_str());
460     }
461     return out;
462 }
463 
nameExpression(SkString* output, const char* baseName)464 void GrGLSLProgramBuilder::nameExpression(SkString* output, const char* baseName) {
465     // Name a variable to hold stage result. If we already have a valid output name, use that as-is;
466     // otherwise, create a new mangled one.
467     if (output->isEmpty()) {
468         *output = this->nameVariable(/*prefix=*/'\0', baseName);
469     }
470 }
471 
appendUniformDecls(GrShaderFlags visibility, SkString* out) const472 void GrGLSLProgramBuilder::appendUniformDecls(GrShaderFlags visibility, SkString* out) const {
473     this->uniformHandler()->appendUniformDecls(visibility, out);
474 }
475 
addRTFlipUniform(const char* name)476 void GrGLSLProgramBuilder::addRTFlipUniform(const char* name) {
477     SkASSERT(!fUniformHandles.fRTFlipUni.isValid());
478     GrGLSLUniformHandler* uniformHandler = this->uniformHandler();
479     fUniformHandles.fRTFlipUni =
480             uniformHandler->internalAddUniformArray(nullptr,
481                                                     kFragment_GrShaderFlag,
482                                                     kFloat2_GrSLType,
483                                                     name,
484                                                     false,
485                                                     0,
486                                                     nullptr);
487 }
488 
fragmentProcessorHasCoordsParam(const GrFragmentProcessor* fp)489 bool GrGLSLProgramBuilder::fragmentProcessorHasCoordsParam(const GrFragmentProcessor* fp) {
490     return fFPCoordsMap[fp].hasCoordsParam;
491 }
492 
finalizeShaders()493 void GrGLSLProgramBuilder::finalizeShaders() {
494     this->varyingHandler()->finalize();
495     fVS.finalize(kVertex_GrShaderFlag);
496     fFS.finalize(kFragment_GrShaderFlag);
497 }
498