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