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/GrRenderTarget.h"
9 #include "src/gpu/GrShaderCaps.h"
10 #include "src/gpu/gl/GrGLGpu.h"
11 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
12 #include "src/gpu/glsl/GrGLSLProgramBuilder.h"
13 #include "src/gpu/glsl/GrGLSLUniformHandler.h"
14 #include "src/gpu/glsl/GrGLSLVarying.h"
15 
16 const char* GrGLSLFragmentShaderBuilder::kDstColorName = "_dstColor";
17 
KeyForSurfaceOrigin(GrSurfaceOrigin origin)18 uint8_t GrGLSLFragmentShaderBuilder::KeyForSurfaceOrigin(GrSurfaceOrigin origin) {
19     SkASSERT(kTopLeft_GrSurfaceOrigin == origin || kBottomLeft_GrSurfaceOrigin == origin);
20     return origin + 1;
21 
22     static_assert(0 == kTopLeft_GrSurfaceOrigin);
23     static_assert(1 == kBottomLeft_GrSurfaceOrigin);
24 }
25 
GrGLSLFragmentShaderBuilder(GrGLSLProgramBuilder * program)26 GrGLSLFragmentShaderBuilder::GrGLSLFragmentShaderBuilder(GrGLSLProgramBuilder* program)
27         : GrGLSLShaderBuilder(program) {
28     fSubstageIndices.push_back(0);
29 }
30 
writeProcessorFunction(GrGLSLFragmentProcessor * fp,GrGLSLFragmentProcessor::EmitArgs & args)31 SkString GrGLSLFPFragmentBuilder::writeProcessorFunction(GrGLSLFragmentProcessor* fp,
32                                                          GrGLSLFragmentProcessor::EmitArgs& args) {
33     this->onBeforeChildProcEmitCode();
34     this->nextStage();
35 
36     // An FP's function signature is theoretically always main(half4 color, float2 _coords).
37     // However, if it is only sampled by a chain of uniform matrix expressions (or legacy coord
38     // transforms), the value that would have been passed to _coords is lifted to the vertex shader
39     // and stored in a unique varying. In that case it uses that variable and does not have a
40     // second actual argument for _coords.
41     // FIXME: An alternative would be to have all FP functions have a float2 argument, and the
42     // parent FP invokes it with the varying reference when it's been lifted to the vertex shader.
43     size_t paramCount = 2;
44     GrShaderVar params[] = { GrShaderVar(args.fInputColor, kHalf4_GrSLType),
45                              GrShaderVar(args.fSampleCoord, kFloat2_GrSLType) };
46 
47     if (!args.fFp.isSampledWithExplicitCoords()) {
48         // Sampled with a uniform matrix expression and/or a legacy coord transform. The actual
49         // transformation code is emitted in the vertex shader, so this only has to access it.
50         // Add a float2 _coords variable that maps to the associated varying and replaces the
51         // absent 2nd argument to the fp's function.
52         paramCount = 1;
53 
54         if (args.fFp.referencesSampleCoords()) {
55             const GrShaderVar& varying = args.fTransformedCoords[0];
56             switch(varying.getType()) {
57                 case kFloat2_GrSLType:
58                     // Just point the local coords to the varying
59                     args.fSampleCoord = varying.getName().c_str();
60                     break;
61                 case kFloat3_GrSLType:
62                     // Must perform the perspective divide in the frag shader based on the varying,
63                     // and since we won't actually have a function parameter for local coords, add
64                     // it as a local variable.
65                     this->codeAppendf("float2 %s = %s.xy / %s.z;\n", args.fSampleCoord,
66                                       varying.getName().c_str(), varying.getName().c_str());
67                     break;
68                 default:
69                     SkDEBUGFAILF("Unexpected varying type for coord: %s %d\n",
70                                  varying.getName().c_str(), (int) varying.getType());
71                     break;
72             }
73         }
74     } // else the function keeps its two arguments
75 
76     fp->emitCode(args);
77 
78     SkString funcName = this->getMangledFunctionName(args.fFp.name());
79     this->emitFunction(kHalf4_GrSLType, funcName.c_str(), {params, paramCount},
80                        this->code().c_str());
81     this->deleteStage();
82     this->onAfterChildProcEmitCode();
83     return funcName;
84 }
85 
dstColor()86 const char* GrGLSLFragmentShaderBuilder::dstColor() {
87     SkDEBUGCODE(fHasReadDstColorThisStage_DebugOnly = true;)
88 
89     const GrShaderCaps* shaderCaps = fProgramBuilder->shaderCaps();
90     if (shaderCaps->fbFetchSupport()) {
91         this->addFeature(1 << kFramebufferFetch_GLSLPrivateFeature,
92                          shaderCaps->fbFetchExtensionString());
93 
94         // Some versions of this extension string require declaring custom color output on ES 3.0+
95         const char* fbFetchColorName = "sk_LastFragColor";
96         if (shaderCaps->fbFetchNeedsCustomOutput()) {
97             this->enableCustomOutput();
98             fCustomColorOutput->setTypeModifier(GrShaderVar::TypeModifier::InOut);
99             fbFetchColorName = DeclaredColorOutputName();
100             // Set the dstColor to an intermediate variable so we don't override it with the output
101             this->codeAppendf("half4 %s = %s;", kDstColorName, fbFetchColorName);
102         } else {
103             return fbFetchColorName;
104         }
105     }
106     return kDstColorName;
107 }
108 
enableAdvancedBlendEquationIfNeeded(GrBlendEquation equation)109 void GrGLSLFragmentShaderBuilder::enableAdvancedBlendEquationIfNeeded(GrBlendEquation equation) {
110     SkASSERT(GrBlendEquationIsAdvanced(equation));
111 
112     if (fProgramBuilder->shaderCaps()->mustEnableAdvBlendEqs()) {
113         this->addFeature(1 << kBlendEquationAdvanced_GLSLPrivateFeature,
114                          "GL_KHR_blend_equation_advanced");
115         this->addLayoutQualifier("blend_support_all_equations", kOut_InterfaceQualifier);
116     }
117 }
118 
enableCustomOutput()119 void GrGLSLFragmentShaderBuilder::enableCustomOutput() {
120     if (!fCustomColorOutput) {
121         fCustomColorOutput = &fOutputs.emplace_back(DeclaredColorOutputName(), kHalf4_GrSLType,
122                                                     GrShaderVar::TypeModifier::Out);
123         fProgramBuilder->finalizeFragmentOutputColor(fOutputs.back());
124     }
125 }
126 
enableSecondaryOutput()127 void GrGLSLFragmentShaderBuilder::enableSecondaryOutput() {
128     SkASSERT(!fHasSecondaryOutput);
129     fHasSecondaryOutput = true;
130     const GrShaderCaps& caps = *fProgramBuilder->shaderCaps();
131     if (const char* extension = caps.secondaryOutputExtensionString()) {
132         this->addFeature(1 << kBlendFuncExtended_GLSLPrivateFeature, extension);
133     }
134 
135     // If the primary output is declared, we must declare also the secondary output
136     // and vice versa, since it is not allowed to use a built-in gl_FragColor and a custom
137     // output. The condition also co-incides with the condition in which GLES SL 2.0
138     // requires the built-in gl_SecondaryFragColorEXT, where as 3.0 requires a custom output.
139     if (caps.mustDeclareFragmentShaderOutput()) {
140         fOutputs.emplace_back(DeclaredSecondaryColorOutputName(), kHalf4_GrSLType,
141                               GrShaderVar::TypeModifier::Out);
142         fProgramBuilder->finalizeFragmentSecondaryColor(fOutputs.back());
143     }
144 }
145 
getPrimaryColorOutputName() const146 const char* GrGLSLFragmentShaderBuilder::getPrimaryColorOutputName() const {
147     return this->hasCustomColorOutput() ? DeclaredColorOutputName() : "sk_FragColor";
148 }
149 
primaryColorOutputIsInOut() const150 bool GrGLSLFragmentShaderBuilder::primaryColorOutputIsInOut() const {
151     return fCustomColorOutput &&
152            fCustomColorOutput->getTypeModifier() == GrShaderVar::TypeModifier::InOut;
153 }
154 
getSecondaryColorOutputName() const155 const char* GrGLSLFragmentShaderBuilder::getSecondaryColorOutputName() const {
156     if (this->hasSecondaryOutput()) {
157         return (fProgramBuilder->shaderCaps()->mustDeclareFragmentShaderOutput())
158                 ? DeclaredSecondaryColorOutputName()
159                 : "gl_SecondaryFragColorEXT";
160     }
161     return nullptr;
162 }
163 
getSurfaceOrigin() const164 GrSurfaceOrigin GrGLSLFragmentShaderBuilder::getSurfaceOrigin() const {
165     return fProgramBuilder->origin();
166 }
167 
onFinalize()168 void GrGLSLFragmentShaderBuilder::onFinalize() {
169     SkASSERT(fProgramBuilder->processorFeatures() == fUsedProcessorFeaturesAllStages_DebugOnly);
170 
171     fProgramBuilder->varyingHandler()->getFragDecls(&this->inputs(), &this->outputs());
172 }
173 
onBeforeChildProcEmitCode()174 void GrGLSLFragmentShaderBuilder::onBeforeChildProcEmitCode() {
175     SkASSERT(fSubstageIndices.count() >= 1);
176     fSubstageIndices.push_back(0);
177     // second-to-last value in the fSubstageIndices stack is the index of the child proc
178     // at that level which is currently emitting code.
179     fMangleString.appendf("_c%d", fSubstageIndices[fSubstageIndices.count() - 2]);
180 }
181 
onAfterChildProcEmitCode()182 void GrGLSLFragmentShaderBuilder::onAfterChildProcEmitCode() {
183     SkASSERT(fSubstageIndices.count() >= 2);
184     fSubstageIndices.pop_back();
185     fSubstageIndices.back()++;
186     int removeAt = fMangleString.findLastOf('_');
187     fMangleString.remove(removeAt, fMangleString.size() - removeAt);
188 }
189