• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/glsl/GrGLSLShaderBuilder.h"
9 
10 #include "include/sksl/DSL.h"
11 #include "src/gpu/GrShaderCaps.h"
12 #include "src/gpu/GrShaderVar.h"
13 #include "src/gpu/GrSwizzle.h"
14 #include "src/gpu/glsl/GrGLSLBlend.h"
15 #include "src/gpu/glsl/GrGLSLColorSpaceXformHelper.h"
16 #include "src/gpu/glsl/GrGLSLProgramBuilder.h"
17 #include "src/sksl/dsl/priv/DSLWriter.h"
18 #include "src/sksl/ir/SkSLVarDeclarations.h"
19 
GrGLSLShaderBuilder(GrGLSLProgramBuilder * program)20 GrGLSLShaderBuilder::GrGLSLShaderBuilder(GrGLSLProgramBuilder* program)
21     : fProgramBuilder(program)
22     , fInputs(GrGLSLProgramBuilder::kVarsPerBlock)
23     , fOutputs(GrGLSLProgramBuilder::kVarsPerBlock)
24     , fFeaturesAddedMask(0)
25     , fCodeIndex(kCode)
26     , fFinalized(false)
27     , fTmpVariableCounter(0) {
28     // We push back some dummy pointers which will later become our header
29     for (int i = 0; i <= kCode; i++) {
30         fShaderStrings.push_back();
31     }
32 
33     this->main() = "void main() {";
34 }
35 
declAppend(const GrShaderVar & var)36 void GrGLSLShaderBuilder::declAppend(const GrShaderVar& var) {
37     SkString tempDecl;
38     var.appendDecl(fProgramBuilder->shaderCaps(), &tempDecl);
39     this->codeAppendf("%s;", tempDecl.c_str());
40 }
41 
declareGlobal(const GrShaderVar & v)42 void GrGLSLShaderBuilder::declareGlobal(const GrShaderVar& v) {
43     v.appendDecl(this->getProgramBuilder()->shaderCaps(), &this->definitions());
44     this->definitions().append(";");
45 }
46 
getMangledFunctionName(const char * baseName)47 SkString GrGLSLShaderBuilder::getMangledFunctionName(const char* baseName) {
48     return fProgramBuilder->nameVariable(/*prefix=*/'\0', baseName);
49 }
50 
appendFunctionDecl(GrSLType returnType,const char * mangledName,SkSpan<const GrShaderVar> args)51 void GrGLSLShaderBuilder::appendFunctionDecl(GrSLType returnType,
52                                              const char* mangledName,
53                                              SkSpan<const GrShaderVar> args) {
54     this->functions().appendf("%s %s(", GrGLSLTypeString(returnType), mangledName);
55     for (size_t i = 0; i < args.size(); ++i) {
56         if (i > 0) {
57             this->functions().append(", ");
58         }
59         args[i].appendDecl(fProgramBuilder->shaderCaps(), &this->functions());
60     }
61 
62     this->functions().append(")");
63 }
64 
emitFunction(GrSLType returnType,const char * mangledName,SkSpan<const GrShaderVar> args,const char * body)65 void GrGLSLShaderBuilder::emitFunction(GrSLType returnType,
66                                        const char* mangledName,
67                                        SkSpan<const GrShaderVar> args,
68                                        const char* body) {
69     this->appendFunctionDecl(returnType, mangledName, args);
70     this->functions().appendf(" {\n"
71                               "%s"
72                               "}\n\n", body);
73 }
74 
emitFunction(const char * declaration,const char * body)75 void GrGLSLShaderBuilder::emitFunction(const char* declaration, const char* body) {
76     this->functions().appendf("%s {\n"
77                               "%s"
78                               "}\n\n", declaration, body);
79 }
80 
emitFunctionPrototype(GrSLType returnType,const char * mangledName,SkSpan<const GrShaderVar> args)81 void GrGLSLShaderBuilder::emitFunctionPrototype(GrSLType returnType,
82                                                 const char* mangledName,
83                                                 SkSpan<const GrShaderVar> args) {
84     this->appendFunctionDecl(returnType, mangledName, args);
85     this->functions().append(";\n");
86 }
87 
codeAppend(std::unique_ptr<SkSL::Statement> stmt)88 void GrGLSLShaderBuilder::codeAppend(std::unique_ptr<SkSL::Statement> stmt) {
89     SkASSERT(SkSL::dsl::DSLWriter::CurrentProcessor());
90     SkASSERT(stmt);
91     this->codeAppend(stmt->description().c_str());
92     if (stmt->is<SkSL::VarDeclaration>()) {
93         fDeclarations.push_back(std::move(stmt));
94     }
95 }
96 
append_texture_swizzle(SkString * out,GrSwizzle swizzle)97 static inline void append_texture_swizzle(SkString* out, GrSwizzle swizzle) {
98     if (swizzle != GrSwizzle::RGBA()) {
99         out->appendf(".%s", swizzle.asString().c_str());
100     }
101 }
102 
appendTextureLookup(SkString * out,SamplerHandle samplerHandle,const char * coordName) const103 void GrGLSLShaderBuilder::appendTextureLookup(SkString* out,
104                                               SamplerHandle samplerHandle,
105                                               const char* coordName) const {
106     const char* sampler = fProgramBuilder->samplerVariable(samplerHandle);
107     out->appendf("sample(%s, %s)", sampler, coordName);
108     append_texture_swizzle(out, fProgramBuilder->samplerSwizzle(samplerHandle));
109 }
110 
appendTextureLookup(SamplerHandle samplerHandle,const char * coordName,GrGLSLColorSpaceXformHelper * colorXformHelper)111 void GrGLSLShaderBuilder::appendTextureLookup(SamplerHandle samplerHandle,
112                                               const char* coordName,
113                                               GrGLSLColorSpaceXformHelper* colorXformHelper) {
114     SkString lookup;
115     this->appendTextureLookup(&lookup, samplerHandle, coordName);
116     this->appendColorGamutXform(lookup.c_str(), colorXformHelper);
117 }
118 
appendTextureLookupAndBlend(const char * dst,SkBlendMode mode,SamplerHandle samplerHandle,const char * coordName,GrGLSLColorSpaceXformHelper * colorXformHelper)119 void GrGLSLShaderBuilder::appendTextureLookupAndBlend(
120         const char* dst,
121         SkBlendMode mode,
122         SamplerHandle samplerHandle,
123         const char* coordName,
124         GrGLSLColorSpaceXformHelper* colorXformHelper) {
125     if (!dst) {
126         dst = "half4(1)";
127     }
128     SkString lookup;
129     // This works around an issue in SwiftShader where the texture lookup is messed up
130     // if we use blend_modulate instead of simply operator * on dst and the sampled result.
131     // At this time it's unknown if the same problem exists for other modes.
132     if (mode == SkBlendMode::kModulate) {
133         this->codeAppend("(");
134         this->appendTextureLookup(&lookup, samplerHandle, coordName);
135         this->appendColorGamutXform(lookup.c_str(), colorXformHelper);
136         this->codeAppendf(" * %s)", dst);
137     } else {
138         this->codeAppendf("%s(", GrGLSLBlend::BlendFuncName(mode));
139         this->appendTextureLookup(&lookup, samplerHandle, coordName);
140         this->appendColorGamutXform(lookup.c_str(), colorXformHelper);
141         this->codeAppendf(", %s)", dst);
142     }
143 }
144 
appendInputLoad(SamplerHandle samplerHandle)145 void GrGLSLShaderBuilder::appendInputLoad(SamplerHandle samplerHandle) {
146     const char* input = fProgramBuilder->inputSamplerVariable(samplerHandle);
147     SkString load;
148     load.appendf("subpassLoad(%s)", input);
149     append_texture_swizzle(&load, fProgramBuilder->inputSamplerSwizzle(samplerHandle));
150     this->codeAppend(load.c_str());
151 }
152 
appendColorGamutXform(SkString * out,const char * srcColor,GrGLSLColorSpaceXformHelper * colorXformHelper)153 void GrGLSLShaderBuilder::appendColorGamutXform(SkString* out,
154                                                 const char* srcColor,
155                                                 GrGLSLColorSpaceXformHelper* colorXformHelper) {
156     if (!colorXformHelper || colorXformHelper->isNoop()) {
157         *out = srcColor;
158         return;
159     }
160 
161     GrGLSLUniformHandler* uniformHandler = fProgramBuilder->uniformHandler();
162 
163     // We define up to three helper functions, to keep things clearer. One for the source transfer
164     // function, one for the (inverse) destination transfer function, and one for the gamut xform.
165     // Any combination of these may be present, although some configurations are much more likely.
166 
167     auto emitTFFunc = [=](const char* name, GrGLSLProgramDataManager::UniformHandle uniform,
168                           TFKind kind) {
169         const GrShaderVar gTFArgs[] = { GrShaderVar("x", kHalf_GrSLType) };
170         const char* coeffs = uniformHandler->getUniformCStr(uniform);
171         SkString body;
172         // Temporaries to make evaluation line readable. We always use the sRGBish names, so the
173         // PQ and HLG math is confusing.
174         body.appendf("half G = %s[0];", coeffs);
175         body.appendf("half A = %s[1];", coeffs);
176         body.appendf("half B = %s[2];", coeffs);
177         body.appendf("half C = %s[3];", coeffs);
178         body.appendf("half D = %s[4];", coeffs);
179         body.appendf("half E = %s[5];", coeffs);
180         body.appendf("half F = %s[6];", coeffs);
181         body.append("half s = sign(x);");
182         body.append("x = abs(x);");
183         switch (kind) {
184             case TFKind::sRGBish_TF:
185                 body.append("x = (x < D) ? (C * x) + F : pow(A * x + B, G) + E;");
186                 break;
187             case TFKind::PQish_TF:
188                 body.append("x = pow(max(A + B * pow(x, C), 0) / (D + E * pow(x, C)), F);");
189                 break;
190             case TFKind::HLGish_TF:
191                 body.append("x = (x*A <= 1) ? pow(x*A, B) : exp((x-E)*C) + D; x *= (F+1);");
192                 break;
193             case TFKind::HLGinvish_TF:
194                 body.append("x /= (F+1); x = (x <= 1) ? A * pow(x, B) : C * log(x - D) + E;");
195                 break;
196             default:
197                 SkASSERT(false);
198                 break;
199         }
200         body.append("return s * x;");
201         SkString funcName = this->getMangledFunctionName(name);
202         this->emitFunction(kHalf_GrSLType, funcName.c_str(), {gTFArgs, SK_ARRAY_COUNT(gTFArgs)},
203                            body.c_str());
204         return funcName;
205     };
206 
207     SkString srcTFFuncName;
208     if (colorXformHelper->applySrcTF()) {
209         srcTFFuncName = emitTFFunc("src_tf", colorXformHelper->srcTFUniform(),
210                                    colorXformHelper->srcTFKind());
211     }
212 
213     SkString dstTFFuncName;
214     if (colorXformHelper->applyDstTF()) {
215         dstTFFuncName = emitTFFunc("dst_tf", colorXformHelper->dstTFUniform(),
216                                    colorXformHelper->dstTFKind());
217     }
218 
219     SkString gamutXformFuncName;
220     if (colorXformHelper->applyGamutXform()) {
221         const GrShaderVar gGamutXformArgs[] = { GrShaderVar("color", kHalf4_GrSLType) };
222         const char* xform = uniformHandler->getUniformCStr(colorXformHelper->gamutXformUniform());
223         SkString body;
224         body.appendf("color.rgb = (%s * color.rgb);", xform);
225         body.append("return color;");
226         gamutXformFuncName = this->getMangledFunctionName("gamut_xform");
227         this->emitFunction(kHalf4_GrSLType, gamutXformFuncName.c_str(),
228                            {gGamutXformArgs, SK_ARRAY_COUNT(gGamutXformArgs)}, body.c_str());
229     }
230 
231     // Now define a wrapper function that applies all the intermediate steps
232     {
233         // Some GPUs require full float to get results that are as accurate as expected/required.
234         // Most GPUs work just fine with half float. Strangely, the GPUs that have this bug
235         // (Mali G series) only require us to promote the type of a few temporaries here --
236         // the helper functions above can always be written to use half.
237         bool useFloat = fProgramBuilder->shaderCaps()->colorSpaceMathNeedsFloat();
238 
239         const GrShaderVar gColorXformArgs[] = {
240                 GrShaderVar("color", useFloat ? kFloat4_GrSLType : kHalf4_GrSLType)};
241         SkString body;
242         if (colorXformHelper->applyUnpremul()) {
243             body.append("color = unpremul(color);");
244         }
245         if (colorXformHelper->applySrcTF()) {
246             body.appendf("color.r = %s(half(color.r));", srcTFFuncName.c_str());
247             body.appendf("color.g = %s(half(color.g));", srcTFFuncName.c_str());
248             body.appendf("color.b = %s(half(color.b));", srcTFFuncName.c_str());
249         }
250         if (colorXformHelper->applyGamutXform()) {
251             body.appendf("color = %s(half4(color));", gamutXformFuncName.c_str());
252         }
253         if (colorXformHelper->applyDstTF()) {
254             body.appendf("color.r = %s(half(color.r));", dstTFFuncName.c_str());
255             body.appendf("color.g = %s(half(color.g));", dstTFFuncName.c_str());
256             body.appendf("color.b = %s(half(color.b));", dstTFFuncName.c_str());
257         }
258         if (colorXformHelper->applyPremul()) {
259             body.append("color.rgb *= color.a;");
260         }
261         body.append("return half4(color);");
262         SkString colorXformFuncName = this->getMangledFunctionName("color_xform");
263         this->emitFunction(kHalf4_GrSLType, colorXformFuncName.c_str(),
264                            {gColorXformArgs, SK_ARRAY_COUNT(gColorXformArgs)}, body.c_str());
265         out->appendf("%s(%s)", colorXformFuncName.c_str(), srcColor);
266     }
267 }
268 
appendColorGamutXform(const char * srcColor,GrGLSLColorSpaceXformHelper * colorXformHelper)269 void GrGLSLShaderBuilder::appendColorGamutXform(const char* srcColor,
270                                                 GrGLSLColorSpaceXformHelper* colorXformHelper) {
271     SkString xform;
272     this->appendColorGamutXform(&xform, srcColor, colorXformHelper);
273     this->codeAppend(xform.c_str());
274 }
275 
addFeature(uint32_t featureBit,const char * extensionName)276 bool GrGLSLShaderBuilder::addFeature(uint32_t featureBit, const char* extensionName) {
277     if (featureBit & fFeaturesAddedMask) {
278         return false;
279     }
280     this->extensions().appendf("#extension %s: require\n", extensionName);
281     fFeaturesAddedMask |= featureBit;
282     return true;
283 }
284 
appendDecls(const VarArray & vars,SkString * out) const285 void GrGLSLShaderBuilder::appendDecls(const VarArray& vars, SkString* out) const {
286     for (const auto& v : vars.items()) {
287         v.appendDecl(fProgramBuilder->shaderCaps(), out);
288         out->append(";\n");
289     }
290 }
291 
addLayoutQualifier(const char * param,InterfaceQualifier interface)292 void GrGLSLShaderBuilder::addLayoutQualifier(const char* param, InterfaceQualifier interface) {
293     SkASSERT(fProgramBuilder->shaderCaps()->generation() >= k330_GrGLSLGeneration ||
294              fProgramBuilder->shaderCaps()->mustEnableAdvBlendEqs());
295     fLayoutParams[interface].push_back() = param;
296 }
297 
compileAndAppendLayoutQualifiers()298 void GrGLSLShaderBuilder::compileAndAppendLayoutQualifiers() {
299     static const char* interfaceQualifierNames[] = {
300         "in",
301         "out"
302     };
303 
304     for (int interface = 0; interface <= kLastInterfaceQualifier; ++interface) {
305         const SkTArray<SkString>& params = fLayoutParams[interface];
306         if (params.empty()) {
307             continue;
308         }
309         this->layoutQualifiers().appendf("layout(%s", params[0].c_str());
310         for (int i = 1; i < params.count(); ++i) {
311             this->layoutQualifiers().appendf(", %s", params[i].c_str());
312         }
313         this->layoutQualifiers().appendf(") %s;\n", interfaceQualifierNames[interface]);
314     }
315 
316     static_assert(0 == GrGLSLShaderBuilder::kIn_InterfaceQualifier);
317     static_assert(1 == GrGLSLShaderBuilder::kOut_InterfaceQualifier);
318     static_assert(SK_ARRAY_COUNT(interfaceQualifierNames) == kLastInterfaceQualifier + 1);
319 }
320 
finalize(uint32_t visibility)321 void GrGLSLShaderBuilder::finalize(uint32_t visibility) {
322     SkASSERT(!fFinalized);
323     this->compileAndAppendLayoutQualifiers();
324     SkASSERT(visibility);
325     fProgramBuilder->appendUniformDecls((GrShaderFlags) visibility, &this->uniforms());
326     this->appendDecls(fInputs, &this->inputs());
327     this->appendDecls(fOutputs, &this->outputs());
328     this->onFinalize();
329     // append the 'footer' to code
330     this->code().append("}");
331 
332     for (int i = 0; i <= fCodeIndex; i++) {
333         fCompilerString.append(fShaderStrings[i].c_str(), fShaderStrings[i].size());
334     }
335 
336     fFinalized = true;
337 }
338