1 /*-------------------------------------------------------------------------
2 * drawElements Quality Program Random Shader Generator
3 * ----------------------------------------------------
5 * Copyright 2014 The Android Open Source Project
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
21 * \brief Shader generator.
22 *//*--------------------------------------------------------------------*/
24 #include "rsgShaderGenerator.hpp"
25 #include "rsgFunctionGenerator.hpp"
26 #include "rsgToken.hpp"
27 #include "rsgPrettyPrinter.hpp"
28 #include "rsgUtils.hpp"
39 ShaderGenerator::ShaderGenerator (GeneratorState& state)
41 , m_varManager (state.getNameAllocator())
43 state.setVariableManager(m_varManager);
46 ShaderGenerator::~ShaderGenerator (void)
53 const char* getFragColorName (const GeneratorState& state)
55 switch (state.getProgramParameters().version)
57 case VERSION_100: return "gl_FragColor";
58 case VERSION_300: return "dEQP_FragColor";
65 void createAssignment (BlockStatement& block, const Variable* dstVar, const Variable* srcVar)
67 VariableRead* varRead = new VariableRead(srcVar);
70 block.addChild(new AssignStatement( dstVar, varRead));
72 catch (const std::exception&)
79 const ValueEntry* findByName (VariableManager& varManager, const char* name)
81 AnyEntry::Iterator iter = varManager.getBegin<AnyEntry>();
82 AnyEntry::Iterator end = varManager.getEnd<AnyEntry>();
83 for (; iter != end; iter++)
85 const ValueEntry* entry = *iter;
86 if (deStringEqual(entry->getVariable()->getName(), name))
92 void genVertexPassthrough (GeneratorState& state, Shader& shader)
94 // Create copies from shader inputs to outputs
95 vector<const ValueEntry*> entries;
96 std::copy(state.getVariableManager().getBegin<AnyEntry>(), state.getVariableManager().getEnd<AnyEntry>(), std::inserter(entries, entries.begin()));
98 for (vector<const ValueEntry*>::const_iterator i = entries.begin(); i != entries.end(); i++)
100 const ValueEntry* entry = *i;
101 const Variable* outVar = entry->getVariable();
102 std::string inVarName;
104 if (outVar->getStorage() != Variable::STORAGE_SHADER_OUT)
107 // Name: a_[name], remove v_ -prefix if such exists
109 if (deStringBeginsWith(outVar->getName(), "v_"))
110 inVarName += (outVar->getName()+2);
112 inVarName += outVar->getName();
114 Variable* inVar = state.getVariableManager().allocate(outVar->getType(), Variable::STORAGE_SHADER_IN, inVarName.c_str());
116 // Update value range. This will be stored into shader input info.
117 state.getVariableManager().setValue(inVar, entry->getValueRange());
119 // Add assignment from input to output into main() body
120 createAssignment(shader.getMain().getBody(), entry->getVariable(), inVar);
124 void genFragmentPassthrough (GeneratorState& state, Shader& shader)
126 // Add simple gl_FragColor = v_color; assignment
127 const ValueEntry* fragColorEntry = findByName(state.getVariableManager(), getFragColorName(state));
128 TCU_CHECK(fragColorEntry);
130 Variable* inColorVariable = state.getVariableManager().allocate(fragColorEntry->getVariable()->getType(), Variable::STORAGE_SHADER_IN, "v_color");
132 state.getVariableManager().setValue(inColorVariable, fragColorEntry->getValueRange());
133 createAssignment(shader.getMain().getBody(), fragColorEntry->getVariable(), inColorVariable);
136 // Sets undefined (-inf..inf) components to some meaningful values. Used for sanitizing final shader input value ranges.
137 void fillUndefinedComponents (ValueRangeAccess valueRange)
139 VariableType::Type baseType = valueRange.getType().getBaseType();
140 TCU_CHECK(baseType == VariableType::TYPE_FLOAT ||
141 baseType == VariableType::TYPE_INT ||
142 baseType == VariableType::TYPE_BOOL);
144 for (int elemNdx = 0; elemNdx < valueRange.getType().getNumElements(); elemNdx++)
146 if (isUndefinedValueRange(valueRange.component(elemNdx)))
148 ValueAccess min = valueRange.component(elemNdx).getMin();
149 ValueAccess max = valueRange.component(elemNdx).getMax();
153 case VariableType::TYPE_FLOAT: min = 0.0f; max = 1.0f; break;
154 case VariableType::TYPE_INT: min = 0; max = 1; break;
155 case VariableType::TYPE_BOOL: min = false; max = true; break;
156 default: DE_ASSERT(DE_FALSE);
162 void fillUndefinedShaderInputs (vector<ShaderInput*>& inputs)
164 for (vector<ShaderInput*>::iterator i = inputs.begin(); i != inputs.end(); i++)
166 if (!(*i)->getVariable()->getType().isSampler()) // Samplers are assigned at program-level.
167 fillUndefinedComponents((*i)->getValueRange());
173 void ShaderGenerator::generate (const ShaderParameters& shaderParams, Shader& shader, const vector<ShaderInput*>& outputs)
176 VariableScope& globalVariableScope = shader.getGlobalScope();
177 ValueScope globalValueScope;
180 m_state.setShader(shaderParams, shader);
181 DE_ASSERT(m_state.getExpressionFlags() == 0);
183 // Reserve some scalars for gl_Position & dEQP_Position
184 ReservedScalars reservedScalars;
185 if (shader.getType() == Shader::TYPE_VERTEX)
186 m_state.getVariableManager().reserve(reservedScalars, 4*2);
188 // Push global scopes
189 m_varManager.pushVariableScope(globalVariableScope);
190 m_varManager.pushValueScope(globalValueScope);
192 // Init shader outputs.
194 for (vector<ShaderInput*>::const_iterator i = outputs.begin(); i != outputs.end(); i++)
196 const ShaderInput* input = *i;
197 Variable* variable = m_state.getVariableManager().allocate(input->getVariable()->getType(), Variable::STORAGE_SHADER_OUT, input->getVariable()->getName());
199 m_state.getVariableManager().setValue(variable, input->getValueRange());
202 if (shader.getType() == Shader::TYPE_FRAGMENT)
205 // \todo [2011-11-22 pyry] Multiple outputs from fragment shader!
206 Variable* fragColorVar = m_state.getVariableManager().allocate(VariableType(VariableType::TYPE_FLOAT, 4), Variable::STORAGE_SHADER_OUT, getFragColorName(m_state));
207 ValueRange valueRange(fragColorVar->getType());
209 valueRange.getMin() = tcu::Vec4(0.0f, 0.0f, 0.0f, 0.0f);
210 valueRange.getMax() = tcu::Vec4(1.0f, 1.0f, 1.0f, 1.0f);
212 fragColorVar->setLayoutLocation(0); // Bind color output to location 0 (applies to GLSL ES 3.0 onwards).
214 m_state.getVariableManager().setValue(fragColorVar, valueRange.asAccess());
218 // Construct shader code.
220 Function& main = shader.getMain();
221 main.setReturnType(VariableType(VariableType::TYPE_VOID));
223 if (shaderParams.randomize)
225 FunctionGenerator funcGen(m_state, main);
227 // Mandate assignment into to all shader outputs in main()
228 const vector<Variable*>& liveVars = globalVariableScope.getLiveVariables();
229 for (vector<Variable*>::const_iterator i = liveVars.begin(); i != liveVars.end(); i++)
231 Variable* variable = *i;
232 if (variable->getStorage() == Variable::STORAGE_SHADER_OUT)
233 funcGen.requireAssignment(variable);
240 if (shader.getType() == Shader::TYPE_VERTEX)
241 genVertexPassthrough(m_state, shader);
244 DE_ASSERT(shader.getType() == Shader::TYPE_FRAGMENT);
245 genFragmentPassthrough(m_state, shader);
249 if (shader.getType() == Shader::TYPE_VERTEX)
251 // Add gl_Position = dEQP_Position;
252 m_state.getVariableManager().release(reservedScalars);
254 Variable* glPosVariable = m_state.getVariableManager().allocate(VariableType(VariableType::TYPE_FLOAT, 4), Variable::STORAGE_SHADER_OUT, "gl_Position");
255 Variable* qpPosVariable = m_state.getVariableManager().allocate(VariableType(VariableType::TYPE_FLOAT, 4), Variable::STORAGE_SHADER_IN, "dEQP_Position");
257 ValueRange valueRange(glPosVariable->getType());
259 valueRange.getMin() = tcu::Vec4(-1.0f, -1.0f, 0.0f, 1.0f);
260 valueRange.getMax() = tcu::Vec4( 1.0f, 1.0f, 0.0f, 1.0f);
262 m_state.getVariableManager().setValue(qpPosVariable, valueRange.asAccess()); // \todo [2011-05-24 pyry] No expression should be able to use gl_Position or dEQP_Position..
264 createAssignment(main.getBody(), glPosVariable, qpPosVariable);
268 // Declare live global variables.
270 vector<Variable*> liveVariables;
271 std::copy(globalVariableScope.getLiveVariables().begin(), globalVariableScope.getLiveVariables().end(), std::inserter(liveVariables, liveVariables.begin()));
273 vector<Variable*> createDeclarationStatementVars;
275 for (vector<Variable*>::iterator i = liveVariables.begin(); i != liveVariables.end(); i++)
277 Variable* variable = *i;
278 const char* name = variable->getName();
279 bool declare = !deStringBeginsWith(name, "gl_"); // Do not declare built-in types.
281 // Create input entries (store value range) if necessary
282 vector<ShaderInput*>& inputs = shader.getInputs();
283 vector<ShaderInput*>& uniforms = shader.getUniforms();
285 switch (variable->getStorage())
287 case Variable::STORAGE_SHADER_IN:
289 const ValueEntry* value = m_state.getVariableManager().getValue(variable);
291 inputs.reserve(inputs.size()+1);
292 inputs.push_back(new ShaderInput(variable, value->getValueRange()));
296 case Variable::STORAGE_UNIFORM:
298 const ValueEntry* value = m_state.getVariableManager().getValue(variable);
300 uniforms.reserve(uniforms.size()+1);
301 uniforms.push_back(new ShaderInput(variable, value->getValueRange()));
310 createDeclarationStatementVars.push_back(variable);
313 // Just move to global scope without declaration statement.
314 m_state.getVariableManager().declareVariable(variable);
318 // All global initializers must be constant expressions, no variable allocation is allowed
319 DE_ASSERT(m_state.getExpressionFlags() == 0);
320 m_state.pushExpressionFlags(CONST_EXPR|NO_VAR_ALLOCATION);
322 // Create declaration statements
323 for (vector<Variable*>::iterator i = createDeclarationStatementVars.begin(); i != createDeclarationStatementVars.end(); i++)
325 shader.getGlobalStatements().reserve(shader.getGlobalStatements().size());
326 shader.getGlobalStatements().push_back(new DeclarationStatement(m_state, *i));
329 m_state.popExpressionFlags();
333 m_varManager.popVariableScope();
334 m_varManager.popValueScope();
336 // Fill undefined (unused) components in inputs with dummy values
337 fillUndefinedShaderInputs(shader.getInputs());
338 fillUndefinedShaderInputs(shader.getUniforms());
340 // Tokenize shader and write source
342 TokenStream tokenStr;
343 shader.tokenize(m_state, tokenStr);
345 std::ostringstream str;
346 PrettyPrinter printer(str);
348 // Append #version if necessary.
349 if (m_state.getProgramParameters().version == VERSION_300)
350 str << "#version 300 es\n";
352 printer.append(tokenStr);
353 shader.setSource(str.str().c_str());