50 #include "ShaderGenerator.hh" 57 #include <QTextStream> 65 std::vector<ShaderModifier*> ShaderProgGenerator::registeredModifiers_;
75 ShaderGenerator::Keywords::Keywords()
77 : macro_requestPosVS(
"#define SG_REQUEST_POSVS"),
78 macro_requestPosOS(
"#define SG_REQUEST_POSOS"),
79 macro_requestTexcoord(
"#define SG_REQUEST_TEXCOORD"),
80 macro_requestVertexColor(
"#define SG_REQUEST_VERTEXCOLOR"),
81 macro_requestNormalVS(
"#define SG_REQUEST_NORMALVS"),
82 macro_requestNormalOS(
"#define SG_REQUEST_NORMALOS"),
84 macro_requestRenormalize(
"#define SG_REQUEST_RENORMARLIZE"),
88 macro_inputPosVS(
"SG_INPUT_POSVS"),
89 macro_inputPosOS(
"SG_INPUT_POSOS"),
90 macro_inputPosCS(
"SG_INPUT_POSCS"),
91 macro_inputNormalVS(
"SG_INPUT_NORMALVS"),
92 macro_inputNormalOS(
"SG_INPUT_NORMALOS"),
93 macro_inputTexcoord(
"SG_INPUT_TEXCOORD"),
94 macro_inputVertexColor(
"SG_INPUT_VERTEXCOLOR"),
96 macro_outputPosVS(
"SG_OUTPUT_POSVS"),
97 macro_outputPosOS(
"SG_OUTPUT_POSOS"),
98 macro_outputPosCS(
"SG_OUTPUT_POSCS"),
99 macro_outputNormalVS(
"SG_OUTPUT_NORMALVS"),
100 macro_outputNormalOS(
"SG_OUTPUT_NORMALOS"),
101 macro_outputTexcoord(
"SG_OUTPUT_TEXCOORD"),
102 macro_outputVertexColor(
"SG_OUTPUT_VERTEXCOLOR"),
107 ioNormalVS(
"NormalVS"),
108 ioNormalOS(
"NormalOS"),
109 ioTexcoord(
"TexCoord"),
112 vs_inputPrefix(
"in"),
113 vs_outputPrefix(
"outVertex"),
114 tcs_outputPrefix(
"outTc"),
115 tes_outputPrefix(
"outTe"),
116 gs_outputPrefix(
"outGeometry"),
117 fs_outputPrefix(
"outFragment"),
119 vs_inputPosition(vs_inputPrefix +
"Position"),
120 vs_inputNormal(vs_inputPrefix +
"Normal"),
121 vs_inputTexCoord(vs_inputPrefix + ioTexcoord),
122 vs_inputColor(vs_inputPrefix + ioColor),
124 vs_outputPosCS(vs_outputPrefix + ioPosCS),
125 vs_outputPosVS(vs_outputPrefix + ioPosVS),
126 vs_outputPosOS(vs_outputPrefix + ioPosOS),
127 vs_outputTexCoord(vs_outputPrefix + ioTexcoord),
128 vs_outputNormalVS(vs_outputPrefix + ioNormalVS),
129 vs_outputNormalOS(vs_outputPrefix + ioNormalOS),
130 vs_outputVertexColor(vs_outputPrefix + ioColor),
131 fs_outputFragmentColor(fs_outputPrefix)
135 const ShaderGenerator::Keywords ShaderGenerator::keywords;
138 ShaderGenerator::ShaderGenerator()
139 : version_(150), inputArrays_(false), outputArrays_(false)
143 ShaderGenerator::~ShaderGenerator()
152 inputArrays_ =
false;
153 outputArrays_ =
false;
154 inputPrefix_ = keywords.vs_inputPrefix;
155 outputPrefix_ = keywords.vs_outputPrefix;
157 addInput(
"vec4", keywords.vs_inputPosition);
158 addOutput(
"vec4", keywords.vs_outputPosCS);
160 if (_iodesc->inputNormal_)
161 addInput(
"vec3", keywords.vs_inputNormal);
163 if (_desc->textured())
165 std::map<size_t,ShaderGenDesc::TextureType>::const_iterator iter = _desc->textureTypes().begin();
168 if (iter->second.type == GL_TEXTURE_3D) {
169 addInput(
"vec3", keywords.vs_inputTexCoord);
170 addOutput(
"vec3", keywords.vs_outputTexCoord);
172 addInput(
"vec2", keywords.vs_inputTexCoord);
173 addOutput(
"vec2", keywords.vs_outputTexCoord);
177 if (_iodesc->inputColor_)
178 addInput(
"vec4", keywords.vs_inputColor);
180 if (_iodesc->passNormalVS_)
181 addOutput(
"vec3", keywords.vs_outputNormalVS);
183 if (_iodesc->passNormalOS_)
184 addOutput(
"vec3", keywords.vs_outputNormalOS);
192 if (_desc->shadeMode == SG_SHADE_FLAT)
194 if (!_desc->geometryTemplateFile.isEmpty())
195 strColorOut = keywords.vs_outputVertexColor;
199 addStringToList(
"vec4 " + keywords.vs_outputVertexColor, &outputs_,
"flat out ",
"; ");
202 else if (_desc->shadeMode == SG_SHADE_GOURAUD || _desc->vertexColors || _iodesc->inputColor_)
203 strColorOut = keywords.vs_outputVertexColor;
205 if (strColorOut.size())
206 addOutput(
"vec4", strColorOut);
209 addStringToList(
"vec4 " + keywords.vs_outputVertexColor, &outputs_, _desc->vertexColorsInterpolator +
" out ",
";");
215 if (_iodesc->passPosVS_)
216 addOutput(
"vec4", keywords.vs_outputPosVS);
218 if (_iodesc->passPosOS_)
219 addOutput(
"vec4", keywords.vs_outputPosOS);
221 if (_iodesc->passTexCoord_ && !_desc->textured())
226 if (_desc->texGenMode && _desc->texGenDim > 0 && _desc->texGenDim <= 4 && !_desc->texGenPerFragment)
227 texdim = _desc->texGenDim;
229 QString texcoordType;
231 texcoordType.sprintf(
"vec%i", texdim);
233 texcoordType =
"float";
235 addInput(texcoordType, keywords.vs_inputTexCoord);
236 addOutput(texcoordType, keywords.vs_outputTexCoord);
240 defineIOAbstraction(_iodesc,
true,
false);
247 outputArrays_ =
true;
249 outputPrefix_ = keywords.tcs_outputPrefix;
251 matchInputs(_prevStage,
true, inputPrefix_, outputPrefix_);
253 defineIOAbstraction(_iodesc,
false,
false);
260 outputArrays_ =
false;
262 outputPrefix_ = keywords.tes_outputPrefix;
264 matchInputs(_prevStage,
true, inputPrefix_, outputPrefix_);
266 defineIOAbstraction(_iodesc,
false,
false);
273 outputArrays_ =
false;
275 outputPrefix_ = keywords.gs_outputPrefix;
277 matchInputs(_prevStage,
true, inputPrefix_, outputPrefix_);
279 defineIOAbstraction(_iodesc,
false,
false);
287 inputArrays_ =
false;
288 outputArrays_ =
false;
290 outputPrefix_ = keywords.fs_outputPrefix;
292 matchInputs(_prevStage,
false);
293 addOutput(
"vec4", keywords.fs_outputFragmentColor);
295 defineIOAbstraction(_iodesc,
false,
true);
305 addIODefine(keywords.macro_inputPosOS, keywords.vs_inputPosition);
308 addIODefine(keywords.macro_inputTexcoord, keywords.vs_inputTexCoord);
310 if (_iodesc->inputNormal_)
311 addIODefine(keywords.macro_inputNormalOS, keywords.vs_inputNormal);
313 if (_iodesc->inputColor_)
314 addIODefine(keywords.macro_inputVertexColor, keywords.vs_inputColor);
320 addIODefine(keywords.macro_outputPosCS, keywords.vs_outputPosCS);
323 addIODefine(keywords.macro_outputPosVS, keywords.vs_outputPosVS);
325 if (_iodesc->passPosOS_)
326 addIODefine(keywords.macro_outputPosOS, keywords.vs_outputPosOS);
328 if (_iodesc->passTexCoord_)
329 addIODefine(keywords.macro_outputTexcoord, keywords.vs_outputTexCoord);
331 if (_iodesc->passNormalVS_)
332 addIODefine(keywords.macro_outputNormalVS, keywords.vs_outputNormalVS);
334 if (_iodesc->passNormalOS_)
335 addIODefine(keywords.macro_outputNormalOS, keywords.vs_outputNormalOS);
337 if (_iodesc->passColor_)
338 addIODefine(keywords.macro_outputVertexColor, keywords.vs_outputVertexColor);
344 addIODefine(keywords.macro_inputPosVS, inputPrefix_ + keywords.ioPosVS);
346 addIODefine(keywords.macro_outputPosVS, outputPrefix_ + keywords.ioPosVS);
349 if (_iodesc->passPosOS_)
351 addIODefine(keywords.macro_inputPosOS, inputPrefix_ + keywords.ioPosOS);
353 addIODefine(keywords.macro_outputPosOS, outputPrefix_ + keywords.ioPosOS);
356 addIODefine(keywords.macro_inputPosCS, inputPrefix_ + keywords.ioPosCS);
358 addIODefine(keywords.macro_outputPosCS, outputPrefix_ + keywords.ioPosCS);
360 if (_iodesc->passNormalVS_)
362 addIODefine(keywords.macro_inputNormalVS, inputPrefix_ + keywords.ioNormalVS);
364 addIODefine(keywords.macro_outputNormalVS, outputPrefix_ + keywords.ioNormalVS);
367 if (_iodesc->passNormalOS_)
369 addIODefine(keywords.macro_inputNormalOS, inputPrefix_ + keywords.ioNormalOS);
371 addIODefine(keywords.macro_outputNormalOS, outputPrefix_ + keywords.ioNormalOS);
374 if (_iodesc->passTexCoord_)
376 addIODefine(keywords.macro_inputTexcoord, inputPrefix_ + keywords.ioTexcoord);
378 addIODefine(keywords.macro_outputTexcoord, outputPrefix_ + keywords.ioTexcoord);
381 if (_iodesc->passColor_)
383 addIODefine(keywords.macro_inputVertexColor, inputPrefix_ + keywords.ioColor);
385 addIODefine(keywords.macro_outputVertexColor, outputPrefix_ + keywords.ioColor);
396 addUniform(
"mat4 g_mWVP" ,
" // Projection * Modelview");
397 addUniform(
"mat4 g_mWV" ,
" // Modelview matrix");
398 addUniform(
"mat3 g_mWVIT" ,
" // Modelview inverse transposed");
399 addUniform(
"mat4 g_mP",
" // Projection matrix");
401 addUniform(
"vec3 g_vCamPos");
402 addUniform(
"vec3 g_vCamDir");
404 addUniform(
"vec3 g_cDiffuse");
405 addUniform(
"vec3 g_cAmbient");
406 addUniform(
"vec3 g_cEmissive");
407 addUniform(
"vec3 g_cSpecular");
408 addUniform(
"vec4 g_vMaterial");
409 addUniform(
"vec3 g_cLightModelAmbient");
413 #define ADDLIGHT(x) (sz.sprintf(x"_%d", lightIndex_), addUniform(sz)) 419 ADDLIGHT(
"vec3 g_cLightDiffuse");
420 ADDLIGHT(
"vec3 g_cLightAmbient");
421 ADDLIGHT(
"vec3 g_cLightSpecular");
423 if (_light == SG_LIGHT_POINT ||
424 _light == SG_LIGHT_SPOT)
426 ADDLIGHT(
"vec3 g_vLightPos");
427 ADDLIGHT(
"vec3 g_vLightAtten");
430 if (_light == SG_LIGHT_DIRECTIONAL ||
431 _light == SG_LIGHT_SPOT)
432 ADDLIGHT(
"vec3 g_vLightDir");
435 if (_light == SG_LIGHT_SPOT)
436 ADDLIGHT(
"vec2 g_vLightAngleExp");
449 if (!_str.startsWith(_prefix))
452 if (!_str.endsWith(_postfix))
457 tmp = tmp.simplified();
460 if (!_arr->contains(tmp))
461 _arr->push_back(tmp);
468 addStringToList(_input, &inputs_,
"in ",
";");
474 addStringToList(_output, &outputs_,
"out ",
";");
480 addStringToList(_def, &genDefines_,
"#define ");
486 addDefine(_macroName + QString(
" ") + _resolvedName);
494 typedef std::reverse_iterator<QStringList::const_iterator> QStringListReverseIterator;
495 QStringListReverseIterator rbegin( _macros.end() ), rend( _macros.begin() );
497 for (QStringListReverseIterator it = rbegin; it != rend; ++it)
498 genDefines_.push_front(*it);
503 if (genDefines_.contains(_define))
508 QString trimmedDef = _define.trimmed();
510 for (QStringList::const_iterator it = genDefines_.constBegin(); it != genDefines_.constEnd(); ++it)
512 QString trimmedRef = it->trimmed();
514 if (trimmedRef.startsWith(trimmedDef))
519 for (QStringList::const_iterator it = rawIO_.constBegin(); it != rawIO_.constEnd(); ++it)
521 QString trimmedRef = it->trimmed();
523 if (trimmedRef.startsWith(trimmedDef))
532 addStringToList(_def, &layouts_);
539 if (!_uniform.startsWith(
"uniform ") && !_uniform.contains(
" uniform "))
542 addStringToList(_uniform, &uniforms_, prefix,
"; " + _comment );
555 if (!it.contains(
";"))
556 code_.back().append(
";");
565 glslversion.sprintf(
"#version %d", version_);
567 code_.push_back(glslversion);
572 foreach(it, genDefines_)
576 foreach(it, layouts_)
580 addIOToCode(inputs_);
581 addIOToCode(outputs_);
582 addIOToCode(uniforms_);
585 bool requiresLightingCode =
false;
588 foreach(it, imports_)
590 if (it.contains(
"LitDirLight") || it.contains(
"LitPointLight") || it.contains(
"LitSpotLight"))
591 requiresLightingCode =
true;
594 if (requiresLightingCode)
596 foreach(it, _defaultLightingFunctions)
601 foreach(it, imports_)
607 if (!requiresLightingCode)
609 foreach(it, (*_pMainCode))
611 if (it.contains(
"LitDirLight") || it.contains(
"LitPointLight") || it.contains(
"LitSpotLight"))
612 requiresLightingCode =
true;
615 if (requiresLightingCode)
617 foreach(it, _defaultLightingFunctions)
624 code_.append(rawIO_);
628 foreach(it, (*_pMainCode))
636 QFile file(_fileName);
638 if (file.open(QIODevice::ReadOnly | QIODevice::Text))
640 QTextStream fileStream(&file);
644 imports_.push_back(
"// ==============================================================================");
645 imports_.push_back(QString(
"// ShaderGenerator - begin of imported file: ") + _fileName);
648 while (!fileStream.atEnd())
650 QString tmpLine = fileStream.readLine();
652 imports_.push_back(tmpLine.simplified());
658 imports_.push_back(QString(
"// ShaderGenerator - end of imported file #include \"") + _fileName);
659 imports_.push_back(
"// ==============================================================================");
669 QFile file(_fileName);
670 if (file.open(QIODevice::WriteOnly | QIODevice::Text))
672 QTextStream fileStream(&file);
676 fileStream << it <<
'\n';
693 bool _passToNextStage,
694 QString _inputPrefix,
695 QString _outputPrefix)
697 if (!_previousShaderStage)
699 std::cout <<
"error: ShaderGenerator::matchInputs called without providing input stage" << std::endl;
704 foreach(it, _previousShaderStage->outputs_)
708 QString outKeyword =
"out ";
709 QString inKeyword =
"in ";
712 input.replace(input.indexOf(outKeyword), outKeyword.size(), inKeyword);
718 QRegExp alphaNum(
"[a-zA-Z0-9]");
719 int lastNameChar = input.lastIndexOf(alphaNum);
720 input.insert(lastNameChar+1,
"[]");
726 addStringToList(input, &inputs_);
728 if (_passToNextStage)
732 QString output = input;
733 output.replace(output.indexOf(_inputPrefix), _inputPrefix.size(), _outputPrefix);
734 output.replace(output.indexOf(inKeyword), inKeyword.size(), outKeyword);
737 if (inputArrays_ && !outputArrays_)
739 int bracketStart = output.indexOf(
"[");
740 int bracketEnd = output.indexOf(
"]");
741 output.remove(bracketStart, bracketEnd-bracketStart+1);
743 else if (!inputArrays_ && outputArrays_)
745 QRegExp alphaNum(
"[a-zA-Z0-9]");
746 int lastNameChar = output.lastIndexOf(alphaNum);
747 output.insert(lastNameChar+1,
"[]");
753 addStringToList(output, &outputs_);
760 return outputs_.size();
765 QString output = outputs_.at(_id);
768 output.remove(
"out ");
770 int bracketStart = output.indexOf(
"[");
771 int bracketEnd = output.lastIndexOf(
"]");
773 if (bracketStart >= 0)
774 output.remove(bracketStart, bracketEnd-bracketStart+1);
777 QStringList decompOutput = output.split(
" ");
778 return decompOutput.last();
783 return inputs_.size();
788 QString input = inputs_.at(_id);
791 input.remove(
"out ");
793 int bracketStart = input.indexOf(
"[");
794 int bracketEnd = input.lastIndexOf(
"]");
796 if (bracketStart >= 0)
797 input.remove(bracketStart, bracketEnd-bracketStart+1);
800 QStringList decompInput = input.split(
" ");
801 return decompInput.last();
806 QString inputName = getInputName(_inId);
809 QString outputName = inputName;
810 outputName.replace(outputName.indexOf(inputPrefix_), inputPrefix_.size(), outputPrefix_);
816 ShaderGenerator::DefaultIODesc::DefaultIODesc()
817 : inputTexCoord_(
false),
820 passPosVS_(
false), passPosOS_(
false),
821 passTexCoord_(
false),
823 passNormalVS_(
false), passNormalOS_(
false)
830 QString ShaderProgGenerator::shaderDir_;
831 QStringList ShaderProgGenerator::lightingCode_;
835 : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0), renormalizeLighting_(false)
841 : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0),
renormalizeLighting_(false)
843 init(_desc, _modifierIDs, _numActiveMods);
847 : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0),
renormalizeLighting_(false)
849 init(_desc, _modifierIDs.empty() ? 0 : &_modifierIDs[0], (
unsigned int)_modifierIDs.size());
853 : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0),
renormalizeLighting_(false)
855 unsigned int numMods = !_modifierIDs || _modifierIDs->empty() ? 0 : (
unsigned int)_modifierIDs->size();
856 init(_desc, numMods ? &((*_modifierIDs)[0]) : 0, numMods);
860 : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0),
renormalizeLighting_(false)
862 init(_desc, _modifiers, _numActiveMods);
866 : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0),
renormalizeLighting_(false)
868 init(_desc, _modifierIDs.empty() ? 0 : &(_modifierIDs[0]), (
unsigned int)_modifierIDs.size());
872 : vertex_(0), tessControl_(0), tessEval_(0), geometry_(0), fragment_(0),
renormalizeLighting_(false)
874 unsigned int numMods = !_modifierIDs || _modifierIDs->empty() ? 0 : (
unsigned int)_modifierIDs->size();
875 init(_desc, numMods ? &((*_modifierIDs)[0]) : 0, numMods);
881 if (_modifierIDs && _numActiveMods)
883 activeMods_.resize(_numActiveMods);
885 for (
unsigned int i = 0; i < _numActiveMods; ++i)
886 activeMods_[i] = registeredModifiers_[ _modifierIDs[i] ];
897 size_t numDescMods = _desc->shaderMods.size();
898 size_t numTotalMods = _numActiveMods + numDescMods;
901 activeMods_.resize(numTotalMods);
903 for (
size_t i = 0; i < numDescMods; ++i)
905 unsigned int modID = _desc->shaderMods[i];
906 activeMods_[i] = registeredModifiers_[modID];
909 if (_modifiers && _numActiveMods)
911 for (
unsigned int i = 0; i < _numActiveMods; ++i)
912 activeMods_[i + numDescMods] = _modifiers[i];
919 if (shaderDir_.isEmpty())
920 std::cout <<
"error: call ShaderProgGenerator::setShaderDir() first!" << std::endl;
928 if (!desc_.geometryTemplateFile.isEmpty())
929 std::cerr <<
"Warning: removing geometry shader from ShaderDesc" << std::endl;
931 desc_.geometryTemplateFile.clear();
937 if (!desc_.tessControlTemplateFile.isEmpty() || !desc_.tessEvaluationTemplateFile.isEmpty())
938 std::cerr <<
"Warning: removing tessellation shader from ShaderDesc" << std::endl;
940 desc_.tessControlTemplateFile.clear();
941 desc_.tessEvaluationTemplateFile.clear();
946 if (!desc_.geometryTemplateFile.isEmpty())
947 desc_.version = std::max(desc_.version, 150);
949 if (!desc_.tessControlTemplateFile.isEmpty() || !desc_.tessEvaluationTemplateFile.isEmpty())
950 desc_.version = std::max(desc_.version, 400);
953 loadLightingFunctions();
960 ShaderProgGenerator::~ShaderProgGenerator(
void)
973 bool success =
false;
978 QFile file(absFilename);
980 if (file.open(QIODevice::ReadOnly | QIODevice::Text))
982 if (!file.isReadable())
983 std::cout <<
"error: unreadable file -> \"" << absFilename.toStdString() <<
"\"" << std::endl;
986 QTextStream filestream(&file);
988 while (!filestream.atEnd())
990 QString szLine = filestream.readLine();
991 _out->push_back(szLine.trimmed());
1000 std::cout <<
"error: " << file.errorString().toStdString() <<
" -> \"" << absFilename.toStdString() <<
"\"" << std::endl;
1006 void ShaderProgGenerator::loadLightingFunctions()
1008 if (lightingCode_.size())
return;
1010 static const QString lightingCodeFile =
"ShaderGen/SG_LIGHTING.GLSL";
1012 QString fileName = shaderDir_ + QDir::separator() + QString(lightingCodeFile);
1014 lightingCode_.push_back(
"// ==============================================================================");
1015 lightingCode_.push_back(QString(
"// ShaderGenerator - default lighting functions imported from file: ") + fileName);
1021 lightingCode_.push_back(QString(
"// ShaderGenerator - end of default lighting functions"));
1022 lightingCode_.push_back(
"// ==============================================================================");
1029 switch (desc_.shadeMode)
1031 case SG_SHADE_GOURAUD:
1035 case SG_SHADE_UNLIT:
1037 case SG_SHADE_PHONG:
1041 std::cout << __FUNCTION__ <<
" -> unknown shade mode: " << desc_.shadeMode << std::endl;
1044 if (desc_.textured())
1047 if (desc_.vertexColors)
1061 QString strNumLights;
1062 strNumLights.sprintf(
"SG_NUM_LIGHTS %d", desc_.numLights);
1066 const char* lightTypeNames[] = {
"SG_LIGHT_DIRECTIONAL",
1067 "SG_LIGHT_POINT",
"SG_LIGHT_SPOT"};
1069 for (
int i = 0; i < 3; ++i)
1073 for (
int i = 0; i < desc_.numLights; ++i)
1075 QString strLightType;
1076 strLightType.sprintf(
"SG_LIGHT_TYPE_%d %s", i, lightTypeNames[desc_.lightTypes[i]]);
1080 _gen->
addDefine(
"SG_ALPHA g_vMaterial.y");
1089 void ShaderProgGenerator::buildVertexShader()
1101 if (desc_.texGenDim && (desc_.texGenMode == GL_OBJECT_LINEAR || desc_.texGenMode == GL_EYE_LINEAR) && !desc_.texGenPerFragment)
1104 QString uniformDecl =
"vec4 g_vTexGenPlane";
1105 if (desc_.texGenDim > 1)
1106 uniformDecl +=
"[" + QString::number(desc_.texGenDim) +
"]";
1107 vertex_->
addUniform(uniformDecl,
" // texture projection planes");
1112 for (
size_t i = 0; i < activeMods_.size(); ++i)
1113 activeMods_[i]->modifyVertexIO(vertex_);
1123 if (desc_.shadeMode == SG_SHADE_GOURAUD ||
1124 desc_.shadeMode == SG_SHADE_FLAT)
1126 for (
int i = 0; i < desc_.numLights; ++i)
1127 vertex_->
addLight(i, desc_.lightTypes[i]);
1132 QStringList mainCode;
1134 if (!vertexTemplate_.size())
1136 mainCode.push_back(
"void main()");
1137 mainCode.push_back(
"{");
1139 addVertexBeginCode(&mainCode);
1140 addVertexEndCode(&mainCode);
1142 mainCode.push_back(
"}");
1150 foreach(it,vertexTemplate_)
1157 if (it.contains(
"SG_VERTEX_BEGIN"))
1158 addVertexBeginCode(&mainCode);
1161 if (it.contains(
"SG_VERTEX_END"))
1162 addVertexEndCode(&mainCode);
1166 mainCode.push_back(it);
1180 void ShaderProgGenerator::addVertexBeginCode(QStringList* _code)
1184 _code->push_back(QString(
"vec4 sg_vPosPS = g_mWVP * ") + ShaderGenerator::keywords.macro_inputPosOS + QString(
";"));
1185 _code->push_back(
"vec4 sg_vPosVS = g_mWV * inPosition;");
1186 _code->push_back(
"vec3 sg_vNormalVS = vec3(0.0, 1.0, 0.0);");
1187 _code->push_back(
"vec3 sg_vNormalOS = vec3(0.0, 1.0, 0.0);");
1189 if (desc_.vertexColors && (desc_.colorMaterialMode == GL_AMBIENT || desc_.colorMaterialMode == GL_AMBIENT_AND_DIFFUSE))
1190 _code->push_back(QString(
"vec4 sg_cColor = vec4(g_cEmissive + g_cLightModelAmbient * ") + ShaderGenerator::keywords.macro_inputVertexColor + QString(
".xyz, SG_ALPHA);"));
1192 _code->push_back(
"vec4 sg_cColor = vec4(g_cEmissive + g_cLightModelAmbient * g_cAmbient, SG_ALPHA);");
1196 _code->push_back(
"sg_vNormalVS = normalize(g_mWVIT * inNormal);");
1197 _code->push_back(
"sg_vNormalOS = normalize(inNormal);");
1200 if (
ioDesc_.inputColor_ && (desc_.shadeMode == SG_SHADE_UNLIT || desc_.colorMaterialMode == GL_EMISSION))
1201 _code->push_back(QString(
"sg_cColor = ") + ShaderGenerator::keywords.macro_inputVertexColor + QString(
";"));
1208 for (
size_t i = 0; i < activeMods_.size(); ++i)
1209 activeMods_[i]->modifyVertexBeginCode(_code);
1213 void ShaderProgGenerator::addVertexEndCode(QStringList* _code)
1215 if (desc_.shadeMode == SG_SHADE_GOURAUD ||
1216 desc_.shadeMode == SG_SHADE_FLAT)
1223 _code->push_back(
"gl_Position = sg_vPosPS;");
1224 _code->push_back(
"outVertexPosCS = sg_vPosPS;");
1227 _code->push_back(
"outVertexTexCoord = sg_vTexCoord;");
1230 _code->push_back(
"outVertexColor = sg_cColor;");
1233 _code->push_back(ShaderGenerator::keywords.macro_outputNormalVS + QString(
" = sg_vNormalVS;"));
1236 _code->push_back(ShaderGenerator::keywords.macro_outputNormalOS + QString(
" = sg_vNormalOS;"));
1239 _code->push_back(ShaderGenerator::keywords.macro_outputPosVS + QString(
" = sg_vPosVS;"));
1242 _code->push_back(ShaderGenerator::keywords.macro_outputPosOS + QString(
" = ") + ShaderGenerator::keywords.macro_inputPosOS + QString(
";"));
1247 for (
size_t i = 0; i < activeMods_.size(); ++i)
1248 activeMods_[i]->modifyVertexEndCode(_code);
1254 if (_str.contains(
"#include "))
1256 QString strIncludeFile = _str.remove(
"#include ").remove(
'\"').remove(
'<').remove(
'>').trimmed();
1258 if (strIncludeFile.isEmpty())
1259 std::cout <<
"wrong include syntax: " << _str.toStdString() << std::endl;
1262 QString fullPathToIncludeFile = _includePath + QDir::separator() + strIncludeFile;
1275 if (_str.contains(
"#include "))
1277 QString strIncludeFile = _str.remove(
"#include ").remove(
'\"').remove(
'<').remove(
'>').trimmed();
1279 if (strIncludeFile.isEmpty())
1280 std::cout <<
"wrong include syntax: " << _str.toStdString() << std::endl;
1283 QString fullPathToIncludeFile = _includePath + QDir::separator() + strIncludeFile;
1286 fullPathToIncludeFile.replace(
'\\',
'/');
1289 QString cleanFilepath = QDir::cleanPath(fullPathToIncludeFile);
1300 void ShaderProgGenerator::buildTessControlShader()
1303 if ( desc_.tessControlTemplateFile.isEmpty() )
1313 delete tessControl_;
1331 for (
size_t i = 0; i < activeMods_.size(); ++i)
1332 activeMods_[i]->modifyTessControlIO(tessControl_);
1339 QStringList mainCode;
1344 mainCode.push_back(
"void sg_MapIO(const int inIdx)");
1345 mainCode.push_back(
"{");
1348 mainCode.push_back(
"gl_out[gl_InvocationID].gl_Position = gl_in[inIdx].gl_Position;");
1356 QString outputAssignCode = outputName + QString(
"[gl_InvocationID] = ") + inputName + QString(
"[inIdx];");
1358 mainCode.push_back(outputAssignCode);
1361 mainCode.push_back(
"}");
1367 foreach(it,tessControlTemplate_)
1372 mainCode.push_back(it);
1379 void ShaderProgGenerator::buildTessEvalShader()
1382 if ( desc_.tessEvaluationTemplateFile.isEmpty() )
1403 prevStage = vertex_;
1410 foreach(itLayout, tessEvalLayout_)
1414 for (
size_t i = 0; i < activeMods_.size(); ++i)
1415 activeMods_[i]->modifyTessControlIO(tessEval_);
1421 QStringList mainCode;
1428 mainCode.push_back(
"void sg_MapIOBarycentric()");
1429 mainCode.push_back(
"{");
1432 mainCode.push_back(
"gl_Position = gl_TessCoord.x * gl_in[0].gl_Position + gl_TessCoord.y * gl_in[1].gl_Position + gl_TessCoord.z * gl_in[2].gl_Position;");
1440 QString outputAssignCode = outputName + QString(
" = ") +
1441 QString(
"gl_TessCoord.x*") + inputName + QString(
"[0] + ") +
1442 QString(
"gl_TessCoord.y*") + inputName + QString(
"[1] + ") +
1443 QString(
"gl_TessCoord.z*") + inputName + QString(
"[2];");
1445 mainCode.push_back(outputAssignCode);
1448 mainCode.push_back(
"}");
1453 mainCode.push_back(
"void sg_MapIOBilinear()");
1454 mainCode.push_back(
"{");
1457 mainCode.push_back(
"gl_Position = mix( mix(gl_in[0].gl_Position, gl_in[1].gl_Position, gl_TessCoord.x), mix(gl_in[2].gl_Position, gl_in[3].gl_Position, gl_TessCoord.x), gl_TessCoord.y);");
1465 QString outputAssignCode = outputName + QString(
" = mix( ") +
1466 QString(
"mix(") + inputName + QString(
"[0], ") + inputName + QString(
"[1], gl_TessCoord.x), ") +
1467 QString(
"mix(") + inputName + QString(
"[2], ") + inputName + QString(
"[3], gl_TessCoord.x), gl_TessCoord.y); ");
1469 mainCode.push_back(outputAssignCode);
1472 mainCode.push_back(
"}");
1478 QStringList::iterator it;
1479 for (it = tessEvalTemplate_.begin(); it != tessEvalTemplate_.end(); ++it)
1488 if (line.contains(
"SG_INPUT") || line.contains(
"SG_OUTPUT"))
1491 QStringList resolvedCode;
1493 resolvedCode.push_back(
"// ----------------------------------------");
1494 resolvedCode.push_back(
"// ShaderGen: resolve SG_OUTPUT = expression(SG_INPUT);");
1496 int numOccurrences = 0;
1504 QString resolvedLine = line;
1514 for (
int k = 0; k < 2; ++k)
1516 const QString stringToReplace = k ?
"SG_OUTPUT" :
"SG_INPUT";
1517 const int lenStringToReplace = stringToReplace.length();
1518 const QString replacementString = k ? outputName : inputName;
1520 int linePos = resolvedLine.indexOf(stringToReplace);
1522 while (linePos >= 0)
1524 bool replaceOcc =
true;
1526 int nextCharPos = linePos + lenStringToReplace;
1528 if (nextCharPos >= resolvedLine.size())
1531 if (nextCharPos > 0)
1533 QChar nextChar = resolvedLine.at(nextCharPos);
1535 if (nextChar ==
'_' || nextChar.isDigit() || nextChar.isLetter())
1539 linePos += lenStringToReplace;
1548 resolvedLine.replace(linePos, lenStringToReplace, replacementString);
1552 linePos = resolvedLine.indexOf(stringToReplace, linePos + 1);
1560 resolvedCode.push_back(resolvedLine);
1563 resolvedCode.push_back(
"// ----------------------------------------");
1566 mainCode.append(resolvedCode);
1568 mainCode.push_back(line);
1571 mainCode.push_back(line);
1577 void ShaderProgGenerator::buildGeometryShader()
1580 if ( desc_.geometryTemplateFile.isEmpty() )
1594 prevStage = vertex_;
1602 for (
size_t i = 0; i < activeMods_.size(); ++i)
1603 activeMods_[i]->modifyGeometryIO(geometry_);
1609 QStringList mainCode;
1614 mainCode.push_back(
"void sg_MapIO(const int inIdx)");
1615 mainCode.push_back(
"{");
1618 mainCode.push_back(
"gl_Position = gl_in[inIdx].gl_Position;");
1619 mainCode.push_back(
"gl_PrimitiveID = gl_PrimitiveIDIn;");
1627 QString outputAssignCode = outputName + QString(
" = ") + inputName + QString(
"[inIdx];");
1629 mainCode.push_back(outputAssignCode);
1632 mainCode.push_back(
"}");
1639 foreach(it,geometryTemplate_)
1644 mainCode.push_back(it);
1652 void ShaderProgGenerator::buildFragmentShader()
1663 prevStage = tessEval_;
1665 prevStage = tessControl_;
1667 prevStage = vertex_;
1672 if (desc_.texGenDim && (desc_.texGenMode == GL_OBJECT_LINEAR || desc_.texGenMode == GL_EYE_LINEAR) && desc_.texGenPerFragment)
1675 QString uniformDecl =
"vec4 g_vTexGenPlane";
1676 if (desc_.texGenDim > 1)
1677 uniformDecl +=
"[" + QString::number(desc_.texGenDim) +
"]";
1678 fragment_->
addUniform(uniformDecl,
" // texture projection planes");
1686 if (desc_.textured())
1688 for (std::map<size_t,ShaderGenDesc::TextureType>::const_iterator iter = desc_.textureTypes().begin();
1689 iter != desc_.textureTypes().end(); ++iter)
1691 QString name = QString(
"g_Texture%1").arg(iter->first);
1693 switch (iter->second.type)
1695 case GL_TEXTURE_1D: type =
"sampler1D";
break;
1696 case GL_TEXTURE_2D: type =
"sampler2D";
break;
1697 case GL_TEXTURE_3D: type =
"sampler3D";
break;
1698 case GL_TEXTURE_CUBE_MAP: type =
"samplerCube";
break;
1699 #ifdef GL_ARB_texture_rectangle //ARCH_DARWIN doesn't support all texture defines with all xcode version (xcode 5.0 seems to support all) 1700 case GL_TEXTURE_RECTANGLE_ARB: type =
"sampler2DRect";
break;
1702 #ifdef GL_ARB_texture_buffer_object 1703 case GL_TEXTURE_BUFFER_ARB: type =
"samplerBuffer";
break;
1705 #ifdef GL_EXT_texture_array 1706 case GL_TEXTURE_1D_ARRAY_EXT: type =
"sampler1DArray";
break;
1707 case GL_TEXTURE_2D_ARRAY_EXT: type =
"sampler2DArray";
break;
1709 #ifdef GL_ARB_texture_cube_map_array 1710 case GL_TEXTURE_CUBE_MAP_ARRAY_ARB: type =
"samplerCubeArray";
break;
1712 #ifdef GL_ARB_texture_multisample 1713 case GL_TEXTURE_2D_MULTISAMPLE: type =
"sampler2DMS";
break;
1714 case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: type =
"sampler2DMSArray";
break;
1716 default: std::cerr <<
"Texture Type not supported "<< iter->second.type << std::endl;
break;
1719 if (iter->second.shadow)
1726 for (
size_t i = 0; i < activeMods_.size(); ++i)
1727 activeMods_[i]->modifyFragmentIO(fragment_);
1737 if (desc_.shadeMode == SG_SHADE_PHONG)
1739 for (
int i = 0; i < desc_.numLights; ++i)
1740 fragment_->
addLight(i, desc_.lightTypes[i]);
1744 QStringList mainCode;
1746 if (!fragmentTemplate_.size())
1748 mainCode.push_back(
"void main()");
1749 mainCode.push_back(
"{");
1751 addFragmentBeginCode(&mainCode);
1752 addFragmentEndCode(&mainCode);
1754 mainCode.push_back(
"}");
1761 foreach(it,fragmentTemplate_)
1768 if (it.contains(
"SG_FRAGMENT_BEGIN"))
1769 addFragmentBeginCode(&mainCode);
1770 else if (it.contains(
"SG_FRAGMENT_END"))
1771 addFragmentEndCode(&mainCode);
1772 else if (it.contains(
"SG_FRAGMENT_LIGHTING"))
1775 mainCode.push_back(it);
1790 void ShaderProgGenerator::addFragmentBeginCode(QStringList* _code)
1793 _code->push_back(QString(
"vec4 sg_vPosCS = ") + ShaderGenerator::keywords.macro_inputPosCS + QString(
";"));
1794 _code->push_back(
"vec2 sg_vScreenPos = sg_vPosCS.xy / sg_vPosCS.w * 0.5 + vec2(0.5, 0.5);");
1796 _code->push_back(QString(
"#ifdef ") + ShaderGenerator::keywords.macro_inputPosVS);
1797 _code->push_back(QString(
"vec4 sg_vPosVS = ") + ShaderGenerator::keywords.macro_inputPosVS + QString(
";"));
1798 _code->push_back(
"#endif");
1800 _code->push_back(QString(
"#ifdef ") + ShaderGenerator::keywords.macro_inputNormalVS);
1801 _code->push_back(QString(
"vec3 sg_vNormalVS = ") + ShaderGenerator::keywords.macro_inputNormalVS + QString(
";"));
1803 _code->push_back(
"sg_vNormalVS = normalize(sg_vNormalVS);");
1804 _code->push_back(
"#endif");
1807 if (desc_.vertexColors && (desc_.colorMaterialMode == GL_AMBIENT || desc_.colorMaterialMode == GL_AMBIENT_AND_DIFFUSE))
1808 _code->push_back(QString(
"vec4 sg_cColor = vec4(g_cEmissive + g_cLightModelAmbient * ") + ShaderGenerator::keywords.macro_inputVertexColor + QString(
".xyz, SG_ALPHA);"));
1810 _code->push_back(
"vec4 sg_cColor = vec4(g_cEmissive + g_cLightModelAmbient * g_cAmbient, SG_ALPHA);");
1812 if (desc_.shadeMode == SG_SHADE_GOURAUD ||
1813 desc_.shadeMode == SG_SHADE_FLAT ||
1814 (
ioDesc_.passColor_ && (desc_.shadeMode == SG_SHADE_UNLIT || desc_.colorMaterialMode == GL_EMISSION)))
1815 _code->push_back(QString(
"sg_cColor = ") + ShaderGenerator::keywords.macro_inputVertexColor + QString(
";"));
1817 if (desc_.shadeMode == SG_SHADE_PHONG)
1823 if (desc_.textured())
1825 std::map<size_t,ShaderGenDesc::TextureType>::const_iterator iter = desc_.textureTypes().begin();
1826 _code->push_back(
"vec4 sg_cTex = texture(g_Texture"+QString::number(iter->first)+
", sg_vTexCoord);");
1828 for (++iter; iter != desc_.textureTypes().end(); ++iter)
1829 _code->push_back(
"sg_cTex += texture(g_Texture"+QString::number(iter->first)+
", sg_vTexCoord);");
1832 _code->push_back(
"sg_cTex = sg_cTex * 1.0/" + QString::number(desc_.textureTypes().size()) +
".0 ;");
1834 if (desc_.shadeMode == SG_SHADE_UNLIT)
1835 _code->push_back(
"sg_cColor += sg_cTex;");
1837 _code->push_back(
"sg_cColor *= sg_cTex;");
1842 for (
size_t i = 0; i < activeMods_.size(); ++i)
1843 activeMods_[i]->modifyFragmentBeginCode(_code);
1846 void ShaderProgGenerator::addFragmentEndCode(QStringList* _code)
1848 _code->push_back(ShaderGenerator::keywords.fs_outputFragmentColor + QString(
" = sg_cColor;"));
1851 for (
size_t i = 0; i < activeMods_.size(); ++i)
1852 activeMods_[i]->modifyFragmentEndCode(_code);
1863 for (
size_t i = 0; i < activeMods_.size() && !lightingModifier; ++i)
1865 if (activeMods_[i]->replaceDefaultLightingCode())
1866 lightingModifier = activeMods_[i];
1869 if (!lightingModifier)
1875 QString vertexColorString = (
ioDesc_.inputColor_ &&
ioDesc_.passColor_) ? (ShaderGenerator::keywords.macro_inputVertexColor + QString(
".xyz * ")) :
"";
1876 QString diffuseVertexColor = (desc_.colorMaterialMode == GL_DIFFUSE || desc_.colorMaterialMode == GL_AMBIENT_AND_DIFFUSE) ? vertexColorString :
"";
1877 QString ambientVertexColor = (desc_.colorMaterialMode == GL_AMBIENT || desc_.colorMaterialMode == GL_AMBIENT_AND_DIFFUSE) ? vertexColorString :
"";
1878 QString specularVertexColor = (desc_.colorMaterialMode == GL_SPECULAR) ? vertexColorString :
"";
1880 for (
int i = 0; i < desc_.numLights; ++i)
1882 ShaderGenLightType lgt = desc_.lightTypes[i];
1886 case SG_LIGHT_DIRECTIONAL:
1888 buf = QString(
"sg_cColor.xyz += LitDirLight(sg_vPosVS.xyz, sg_vNormalVS, g_vLightDir_%1, %2 g_cLightAmbient_%1, %3 g_cLightDiffuse_%1, %4 g_cLightSpecular_%1);").arg(QString::number(i), ambientVertexColor, diffuseVertexColor, specularVertexColor);
1891 case SG_LIGHT_POINT:
1893 buf = QString(
"sg_cColor.xyz += LitPointLight(sg_vPosVS.xyz, sg_vNormalVS, g_vLightPos_%1, %2 g_cLightAmbient_%1, %3 g_cLightDiffuse_%1, %4 g_cLightSpecular_%1, g_vLightAtten_%1);").arg(QString::number(i), ambientVertexColor, diffuseVertexColor, specularVertexColor);
1898 buf = QString(
"sg_cColor.xyz += LitSpotLight(sg_vPosVS.xyz, sg_vNormalVS, g_vLightPos_%1, g_vLightDir_%1, %2 g_cLightAmbient_%1, %3 g_cLightDiffuse_%1, %4 g_cLightSpecular_%1, g_vLightAtten_%1, g_vLightAngleExp_%1);").arg(QString::number(i), ambientVertexColor, diffuseVertexColor, specularVertexColor);
1904 _code->push_back(buf);
1909 for (
size_t i = 0; i < activeMods_.size(); ++i)
1920 for (
size_t i = 0; i < activeMods_.size(); ++i)
1922 if (lightingModifier != activeMods_[i])
1931 if (!_modifier)
return;
1933 for (
int i = 0; i < desc_.numLights; ++i)
1935 ShaderGenLightType lgt = desc_.lightTypes[i];
1945 foreach(it,lightingCode_)
1946 _code->push_back(it);
1953 int texcoordVarDim = 2;
1955 !desc_.textureTypes().empty() &&
1956 desc_.textureTypes().begin()->second.type == GL_TEXTURE_3D)
1959 bool generateTexCoord = desc_.texGenDim && desc_.texGenMode && (_fragmentShader == desc_.texGenPerFragment);
1960 if (generateTexCoord)
1961 texcoordVarDim = desc_.texGenDim;
1963 QString texcoordVarInit;
1964 if (texcoordVarDim == 1)
1965 texcoordVarInit =
"float sg_vTexCoord";
1967 texcoordVarInit.sprintf(
"vec%i sg_vTexCoord", texcoordVarDim);
1971 texcoordVarInit += QString(
"= ") + ShaderGenerator::keywords.macro_inputTexcoord + QString(
";");
1972 else if (0 <= texcoordVarDim && texcoordVarDim <= 4)
1974 QString zeroVecDefs[] =
1982 texcoordVarInit += zeroVecDefs[texcoordVarDim];
1985 _code->push_back(texcoordVarInit);
1990 if (generateTexCoord)
1993 const char* texGenCoordString[] = {
"x",
"y",
"z",
"w" };
1995 switch (desc_.texGenMode)
1997 case GL_OBJECT_LINEAR:
1999 for (
int i = 0; i < desc_.texGenDim; ++i)
2001 QString assignmentInstrString;
2002 assignmentInstrString =
"sg_vTexCoord";
2003 if (desc_.texGenDim > 1)
2005 assignmentInstrString +=
".";
2006 assignmentInstrString += texGenCoordString[i];
2008 assignmentInstrString +=
" = dot(";
2009 assignmentInstrString += ShaderGenerator::keywords.macro_inputPosOS;
2010 assignmentInstrString +=
", g_vTexGenPlane";
2011 if (desc_.texGenDim > 1)
2013 assignmentInstrString +=
"[";
2014 assignmentInstrString += QString::number(i);
2015 assignmentInstrString +=
"]";
2017 assignmentInstrString +=
");";
2018 _code->push_back(assignmentInstrString);
2024 for (
int i = 0; i < desc_.texGenDim; ++i)
2026 QString assignmentInstrString;
2027 assignmentInstrString =
"sg_vTexCoord";
2028 if (desc_.texGenDim > 1)
2030 assignmentInstrString +=
".";
2031 assignmentInstrString += texGenCoordString[i];
2033 assignmentInstrString +=
" = dot(sg_vPosVS, g_vTexGenPlane";
2034 if (desc_.texGenDim > 1)
2036 assignmentInstrString +=
"[";
2037 assignmentInstrString += QString::number(i);
2038 assignmentInstrString +=
"]";
2040 assignmentInstrString +=
");";
2041 _code->push_back(assignmentInstrString);
2048 _code->push_back(
"vec3 sg_vPosVS_unit = normalize(sg_vPosVS.xyz);");
2049 _code->push_back(
"vec3 sg_TexGenRefl = reflect(sg_vPosVS_unit, sg_vNormalVS);");
2050 _code->push_back(
"vec3 sg_TexGenRefl2 = sg_TexGenRefl; sg_TexGenRefl2.z += 1.0;");
2051 _code->push_back(
"float sg_TexGenMRcp = 0.5 * inversesqrt(dot(sg_TexGenRefl2, sg_TexGenRefl2));");
2052 for (
int i = 0; i < desc_.texGenDim; ++i)
2054 QString assignmentInstrString;
2055 assignmentInstrString.sprintf(
"sg_vTexCoord.%s = sg_TexGenRefl.%s * sg_TexGenMRcp + 0.5;", texGenCoordString[i], texGenCoordString[i]);
2056 _code->push_back(assignmentInstrString);
2062 for (
int i = 0; i < desc_.texGenDim; ++i)
2064 QString assignmentInstrString;
2065 assignmentInstrString.sprintf(
"sg_vTexCoord.%s = sg_vNormalVS.%s;", texGenCoordString[i], texGenCoordString[i]);
2066 _code->push_back(assignmentInstrString);
2070 case GL_REFLECTION_MAP:
2072 _code->push_back(
"vec3 sg_vPosVS_unit = normalize(sg_vPosVS.xyz);");
2073 _code->push_back(
"vec3 sg_TexGenRefl = reflect(sg_vPosVS_unit, sg_vNormalVS);");
2074 for (
int i = 0; i < desc_.texGenDim; ++i)
2076 QString assignmentInstrString;
2077 assignmentInstrString.sprintf(
"sg_vTexCoord.%s = sg_TexGenRefl.%s;", texGenCoordString[i], texGenCoordString[i]);
2078 _code->push_back(assignmentInstrString);
2095 if (desc_.shadeMode != SG_SHADE_UNLIT)
2098 if (desc_.textured())
2105 int maxTexGenDim = 4;
2107 switch (desc_.texGenMode)
2110 case GL_OBJECT_LINEAR: maxTexGenDim = 4;
break;
2112 case GL_SPHERE_MAP: maxTexGenDim = 2;
break;
2115 case GL_REFLECTION_MAP: maxTexGenDim = 3;
break;
2117 default: maxTexGenDim = 0;
break;
2120 desc_.texGenDim = std::max(std::min(desc_.texGenDim, maxTexGenDim), 0);
2123 if (desc_.texGenDim && desc_.texGenMode)
2126 if (!desc_.texGenPerFragment)
2130 if (desc_.texGenMode == GL_REFLECTION_MAP || desc_.texGenMode == GL_SPHERE_MAP || desc_.texGenMode == GL_NORMAL_MAP)
2134 if (desc_.texGenPerFragment)
2136 switch (desc_.texGenMode)
2138 case GL_OBJECT_LINEAR:
ioDesc_.passPosOS_ =
true;
break;
2141 case GL_NORMAL_MAP:
ioDesc_.passNormalVS_ =
true;
break;
2149 if (desc_.vertexColors)
2152 if (desc_.shadeMode == SG_SHADE_PHONG)
2158 if (desc_.shadeMode == SG_SHADE_FLAT || desc_.shadeMode == SG_SHADE_GOURAUD || desc_.vertexColors)
2166 for (
size_t i = 0; i < activeMods_.size(); ++i)
2178 if (dummy.
hasDefine(ShaderGenerator::keywords.macro_requestPosVS))
2180 if (dummy.
hasDefine(ShaderGenerator::keywords.macro_requestTexcoord))
2185 if (dummy.
hasDefine(ShaderGenerator::keywords.macro_requestVertexColor))
2190 if (dummy.
hasDefine(ShaderGenerator::keywords.macro_requestNormalVS))
2195 if (dummy.
hasDefine(ShaderGenerator::keywords.macro_requestNormalOS))
2200 if (dummy.
hasDefine(ShaderGenerator::keywords.macro_requestPosOS))
2203 if (dummy.
hasDefine(ShaderGenerator::keywords.macro_requestRenormalize))
2211 buildVertexShader();
2212 buildTessControlShader();
2213 buildTessEvalShader();
2214 buildGeometryShader();
2215 buildFragmentShader();
2245 void ShaderProgGenerator::saveVertexShToFile(
const char* _fileName)
2250 void ShaderProgGenerator::saveGeometryShToFile(
const char* _fileName)
2255 void ShaderProgGenerator::saveFragmentShToFile(
const char* _fileName)
2263 if (!desc_.vertexTemplateFile.isEmpty())
2268 if (!desc_.fragmentTemplateFile.isEmpty())
2273 if (!desc_.geometryTemplateFile.isEmpty())
2278 if (!desc_.tessControlTemplateFile.isEmpty())
2283 if (!desc_.tessEvaluationTemplateFile.isEmpty())
2286 scanShaderTemplate(tessEvalTemplate_, desc_.tessEvaluationTemplateFile, &tessEvalLayout_);
2291 tessControlShaderFile_ = desc_.tessControlTemplateFile;
2292 tessEvalShaderFile_ = desc_.tessEvaluationTemplateFile;
2293 geometryShaderFile_ = desc_.geometryTemplateFile;
2294 fragmentShaderFile_ = desc_.fragmentTemplateFile;
2302 QString filePath =
getPathName(_templateFilename);
2304 QStringList::iterator it;
2305 for (it = _templateSrc.begin(); it != _templateSrc.end(); ++it)
2314 it = _templateSrc.erase(it);
2316 int offset = it - _templateSrc.begin();
2321 foreach(importLine,
import)
2323 it = _templateSrc.insert(it, importLine);
2329 it = _templateSrc.begin() + offset;
2333 QString trimmedLine = it->trimmed();
2336 QByteArray lineBytes = trimmedLine.toUtf8();
2338 int templateVersion = 0;
2339 if (sscanf(lineBytes.constData(),
"#version %d", &templateVersion) == 1)
2341 desc_.version = std::max(templateVersion, desc_.version);
2344 it = _templateSrc.erase(it);
2347 else if (trimmedLine.startsWith(
"layout(") || trimmedLine.startsWith(
"layout ("))
2349 if (_outLayoutDirectives)
2351 _outLayoutDirectives->push_back(trimmedLine);
2354 it = _templateSrc.erase(it);
2361 if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestPosVS))
2363 else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestTexcoord))
2368 else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestVertexColor))
2373 else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestNormalVS))
2378 else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestNormalOS))
2383 else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestPosOS))
2385 else if (trimmedLine.startsWith(ShaderGenerator::keywords.macro_requestRenormalize))
2387 else if (trimmedLine.startsWith(
"SG_FRAGMENT_LIGHTING"))
2391 desc_.shadeMode = SG_SHADE_PHONG;
2403 return fileInfo.absolutePath();
2408 QString absFilename;
2409 if ( QDir(_strFileName).isRelative() )
2410 absFilename =
getShaderDir() + QDir::separator() + _strFileName;
2412 absFilename = _strFileName;
2414 return QDir::cleanPath(absFilename);
2424 return shaderDir_ + QString(
"/");
2430 if (!_modifier)
return 0;
2435 if (registeredModifiers_[i] == _modifier)
2438 return registeredModifiers_[i]->getID();
2442 _modifier->modifierID_ = (
unsigned int)(numRegisteredModifiers_++);
2444 registeredModifiers_.push_back(_modifier);
2445 return _modifier->modifierID_;
2450 if (_i >= 0 && _i <=
int(activeMods_.size()))
2451 return activeMods_[_i];
2459 return int(activeMods_.size());
2465 return !desc_.geometryTemplateFile.isEmpty();
2470 return !desc_.tessControlTemplateFile.isEmpty();
2475 return !desc_.tessEvaluationTemplateFile.isEmpty();
2481 ShaderModifier::ShaderModifier(
void )
2485 ShaderModifier::~ShaderModifier(
void )
2512 const QString& filename()
const {
return filename_;}
2513 const QDateTime& filetime()
const {
return filetime_;}
2514 void filetime(
const QDateTime& _newtime) {filetime_ = _newtime;}
2520 for (
int i = 0; i < 5; ++i)
2523 vertexBeginCode_.clear();
2524 vertexEndCode_.clear();
2525 fragmentBeginCode_.clear();
2526 fragmentEndCode_.clear();
2535 QDateTime lastmod = QFileInfo(absFilename).lastModified();
2538 QHash<QString, ShaderModifierFile>::iterator cacheEntry = fileCache_.find(_filename);
2540 bool reload =
false;
2541 bool firstLoad =
false;
2543 if (cacheEntry != fileCache_.end())
2546 res = &cacheEntry.value();
2548 if (lastmod != res->filetime())
2568 res = &fileCache_[_filename];
2570 res->loadBlocks(lines);
2571 res->filetime(lastmod);
2585 void loadBlocks(
const QStringList& _lines)
2587 static const char* markers [] =
2596 "FragmentBeginCode:",
2599 const int numMarkers =
sizeof(markers) /
sizeof(markers[0]);
2601 QStringList* blockTargets [] =
2610 &fragmentBeginCode_,
2614 assert(
sizeof(blockTargets) /
sizeof(blockTargets[0]) == numMarkers);
2618 QStringList* curBlock_ = 0;
2623 for (QStringList::const_iterator it = _lines.begin(); it != _lines.end(); ++it, ++curLine)
2629 if (version_ <= 0 && it->startsWith(
"#version "))
2631 const int offset = strlen(
"#version ");
2632 version_ = atoi(it->toLatin1().data() + offset);
2638 bool blockMarker =
false;
2640 for (
int i = 0; i < numMarkers && !blockMarker; ++i)
2642 if ( it->startsWith(markers[i]) )
2645 curBlock_ = blockTargets[i];
2653 curBlock_->push_back(*it);
2655 std::cerr <<
"ShaderModifierFile::loadBlocks - line belongs to unknown block in file " << filename_.toLatin1().data() <<
" at line " << curLine << std::endl;
2673 QDateTime filetime_;
2682 QStringList vertexBeginCode_,
2689 static QHash<QString, ShaderModifierFile> fileCache_;
2692 QHash<QString, ShaderModifierFile> ShaderModifierFile::fileCache_;
2697 return ShaderModifierFile::loadFromFile(_filename);
2707 const char* shadeModeString[] =
2716 QTextStream resStrm(&res);
2718 resStrm <<
"version: " << version;
2720 resStrm <<
"shaderDesc.numLights: " << numLights;
2724 resStrm <<
"\nshaderDesc.lightTypes[]: {";
2726 for (
int i = 0; i < numLights; ++i)
2728 switch (lightTypes[i])
2730 case SG_LIGHT_DIRECTIONAL: resStrm <<
"DIRECTIONAL";
break;
2731 case SG_LIGHT_POINT: resStrm <<
"POINT";
break;
2732 case SG_LIGHT_SPOT: resStrm <<
"SPOT";
break;
2733 default: resStrm <<
"UNDEFINED";
break;
2736 if (i + 1 < numLights)
2744 resStrm <<
"\nshaderDesc.shadeMode: " << shadeModeString[shadeMode];
2745 resStrm <<
"\nshaderDesc.vertexColors: " << vertexColors;
2746 resStrm <<
"\nshaderDesc.textured(): " << textured();
2747 for (std::map<size_t,TextureType>::const_iterator iter = textureTypes_.begin(); iter != textureTypes_.end();++iter)
2749 resStrm <<
"\nTexture stage: " << iter->first;
2750 resStrm <<
"\nTexture Type: ";
2751 switch (iter->second.type)
2753 case GL_TEXTURE_1D: resStrm <<
"GL_TEXTURE_1D";
break;
2754 case GL_TEXTURE_2D: resStrm <<
"GL_TEXTURE_2D";
break;
2755 case GL_TEXTURE_3D: resStrm <<
"GL_TEXTURE_3D";
break;
2756 case GL_TEXTURE_CUBE_MAP: resStrm <<
"GL_TEXTURE_CUBE_MAP";
break;
2757 #ifdef GL_ARB_texture_rectangle //ARCH_DARWIN doesn't support all texture defines with all xcode version (xcode 5.0 seems to support all) 2758 case GL_TEXTURE_RECTANGLE_ARB: resStrm <<
"GL_TEXTURE_RECTANGLE";
break;
2760 #ifdef GL_ARB_texture_buffer_object 2761 case GL_TEXTURE_BUFFER_ARB: resStrm <<
"GL_TEXTURE_BUFFER";
break;
2763 #ifdef GL_EXT_texture_array 2764 case GL_TEXTURE_1D_ARRAY_EXT: resStrm <<
"GL_TEXTURE_1D_ARRAY";
break;
2765 case GL_TEXTURE_2D_ARRAY_EXT: resStrm <<
"GL_TEXTURE_2D_ARRAY";
break;
2767 #ifdef GL_ARB_texture_cube_map_array 2768 case GL_TEXTURE_CUBE_MAP_ARRAY_ARB: resStrm <<
"GL_TEXTURE_CUBE_MAP_ARRAY";
break;
2770 #ifdef GL_ARB_texture_multisample 2771 case GL_TEXTURE_2D_MULTISAMPLE: resStrm <<
"GL_TEXTURE_2D_MULTISAMPLE";
break;
2772 case GL_TEXTURE_2D_MULTISAMPLE_ARRAY: resStrm <<
"GL_TEXTURE_2D_MULTISAMPLE_ARRAY";
break;
2774 default: std::cerr <<
"Texture Type with number "<< iter->second.type <<
" on stage "<< iter->first <<
" is not supported " << std::endl;
break;
2777 resStrm <<
"\nShadowTexture: " << iter->second.shadow;
2780 resStrm <<
"\nshaderDesc.texGenDim: " << texGenDim;
2784 case GL_OBJECT_LINEAR: resStrm <<
"\nshaderDesc.texGenMode: GL_OBJECT_LINEAR";
break;
2785 case GL_EYE_LINEAR: resStrm <<
"\nshaderDesc.texGenMode: GL_EYE_LINEAR";
break;
2786 case GL_SPHERE_MAP: resStrm <<
"\nshaderDesc.texGenMode: GL_SPHERE_MAP";
break;
2787 case GL_NORMAL_MAP: resStrm <<
"\nshaderDesc.texGenMode: GL_NORMAL_MAP";
break;
2788 case GL_REFLECTION_MAP: resStrm <<
"\nshaderDesc.texGenMode: GL_REFLECTION_MAP";
break;
2789 default: resStrm <<
"\nshaderDesc.texGenMode: unknown";
break;
2792 resStrm <<
"\nshaderDesc.texGenPerFragment: " << texGenPerFragment;
2794 if (!vertexTemplateFile.isEmpty())
2795 resStrm <<
"\nshaderDesc.vertexTemplateFile: " << vertexTemplateFile;
2797 if (!tessControlTemplateFile.isEmpty())
2798 resStrm <<
"\nshaderDesc.tessControlTemplateFile: " << tessControlTemplateFile;
2800 if (!tessEvaluationTemplateFile.isEmpty())
2801 resStrm <<
"\nshaderDesc.tessEvaluationTemplateFile: " << tessEvaluationTemplateFile;
2803 if (!geometryTemplateFile.isEmpty())
2804 resStrm <<
"\nshaderDesc.geometryTemplateFile: " << geometryTemplateFile;
2806 if (!fragmentTemplateFile.isEmpty())
2807 resStrm <<
"\nshaderDesc.fragmentTemplateFile: " << fragmentTemplateFile;
QString getInputName(int _id) const
get variable name of input
int getNumActiveModifiers() const
Get the number of active modifiers.
QString vertexColorsInterpolator
interpolation qualifier for input vertex colors: "flat", "smooth", "noperspective" ...
static void setShaderDir(QString _dir)
bool inputTexCoord_
default attributes that should be imported in vertex shader
QString vertexShaderFile_
path + filename to shader templates
bool hasDefine(QString _define) const
Check for define.
void modifyLightingCode(QStringList *_code, ShaderModifier *_modifier)
Calls lighting modifier for each light.
QString toString() const
convert ShaderGenDesc to string format for debugging
static QString getPathName(QString _strFileName)
returns path to _strFileName without last slash
virtual void modifyLightingCode(QStringList *_code, int _lightId, ShaderGenLightType _lightType)
Modify the default lighting code of the shader generator.
const QStringList & getShaderCode()
Get result of buildShaderCode.
void modifyFragmentIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the fragment shader.
void matchInputs(const ShaderGenerator *_previousShaderStage, bool _passToNextStage, QString _inputPrefix="outVertex", QString _outputPrefix="outGeometry")
Perform name matching of outputs and inputs between two shader stages.
void modifyGeometryIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the geometry shader.
void generateShaders()
Generates the shader code.
void loadShaderTemplateFromFile()
Loads external shader templates.
void addTexGenCode(QStringList *_code, bool _fragmentShader)
Add texture coordinate generation code.
void modifyFragmentBeginCode(QStringList *_code)
Append code the the fragment shader.
void modifyVertexIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the vertex shader.
void defineIOAbstraction(const DefaultIODesc *_iodesc, bool _vs, bool _fs)
Define abstract IO names via shader defines.
void addIODefine(const QString &_macroName, const QString &_resolvedName)
Assign an opaque name to the abstract macro.
const QStringList & getFragmentShaderCode()
Returns generated fragment shader code.
virtual void modifyTessEvalIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the tessellation evaluation shader.
void addLightingCode(QStringList *_code)
Adds lighting function calls to code.
void addLight(int lightIndex_, ShaderGenLightType _light)
Add a light description to shader:
bool renormalizeLighting_
renormalize before lighting, default false, can be activated via "#define SG_REQUEST_RENORMALIZE" ...
QString getOutputName(int _id) const
get variable name of output
void addRawIOBlock(QStringList _codeBlock)
Add a raw glsl IO code block.
void modifyTessControlIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the tessellation control shader.
bool hasGeometryShader() const
check whether there is a geometry shader present
static QString getShaderDir()
static QString getAbsFilePath(QString _fileName)
Convert a filename to an absolute filename.
void addIncludeFile(QString _fileName)
Imports another shader, same as #include.
static ShaderModifier * loadFromFile(QString _filename)
Load a modifier from file.
bool openGLVersion(const int _major, const int _minor)
static bool loadStringListFromFile(QString _fileName, QStringList *_out)
Load a text file as string list.
void addLayout(QString _layout)
Add a layout directive.
QString getIOMapName(int _inId) const
get corresponding output name of an input id
int getNumInputs() const
get number of inputs
ShaderProgGenerator(const ShaderGenDesc *_desc)
void initVertexShaderIO(const ShaderGenDesc *_desc, const DefaultIODesc *_iodesc)
Adds fitting vertex shader io for a given description.
void modifyVertexBeginCode(QStringList *_code)
Append code the the vertex shader.
ShaderModifier * getActiveModifier(int _i)
Get active modfiers for this program.
QString outputPrefix_
prefix of outputs of this shader
void initGenDefines(ShaderGenerator *_gen)
provide generated defines to shader
const QStringList & getGeometryShaderCode()
Returns generated tessellation evaluation shader code.
bool normalizeTexColors
Defines if the textureVariable is normalized or not, if multiple textures are used.
const QStringList & getVertexShaderCode()
Returns generated vertex shader code.
bool hasTessControlShader() const
check whether there is a tess-control shader present
void addInput(const QString &_input)
Add one GLSL input specifier.
int checkForIncludes(QString _str, ShaderGenerator *_gen, QString _includePath)
static int numRegisteredModifiers_
registered shader modifier
Namespace providing different geometric functions concerning angles.
bool passPosVS_
default attributes that should be passed down from vertex shader
void addLightingFunctions(QStringList *_code)
Adds lighting definition functions.
void initDefaultUniforms()
Adds frequently used uniform parameters.
const QStringList & getTessEvaluationShaderCode()
Returns generated tessellation control shader code.
virtual void modifyTessControlIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the tessellation control shader.
void addUniform(QString _uniform, QString _comment="")
Add one GLSL uniform specifier.
virtual void modifyVertexIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the vertex shader.
int getNumOutputs() const
get number of outputs
void addMacros(const QStringList &_macros)
Add a list of preprocessor macros.
virtual void modifyFragmentIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the fragment shader.
void initGeometryShaderIO(const ShaderGenDesc *_desc, ShaderGenerator *_prevStage, const DefaultIODesc *_iodesc)
Adds fitting geometry shader io for a given description.
void buildShaderCode(QStringList *_pMainCode, const QStringList &_defaultLightingFunctions)
Shader assembly function.
void setGLSLVersion(int _version)
Set glsl version.
void modifyTessEvalIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the tessellation evaluation shader.
const QStringList & getTessControlShaderCode()
Returns generated vertex shader code.
void addDefine(const QString &_define)
Add one define.
void saveToFile(const char *_fileName)
Save generated shader code to text file.
bool hasTessEvaluationShader() const
check whether there is a tess-evaluation shader present
bool outputArrays_
outputs of shader are arrays (tess-control)
void modifyFragmentEndCode(QStringList *_code)
Append code the the fragment shader.
void initTessControlShaderIO(const ShaderGenDesc *_desc, ShaderGenerator *_prevStage, const DefaultIODesc *_iodesc)
Adds fitting tess-control shader io for a given description.
void initFragmentShaderIO(const ShaderGenDesc *_desc, ShaderGenerator *_prevStage, const DefaultIODesc *_iodesc)
Adds fitting fragment shader io for a given description.
void init(const ShaderGenDesc *_desc, ShaderModifier *const *_modifiers, unsigned int _numActiveMods)
Called in constructor.
void addStringToList(QString _str, QStringList *_list, QString _prefix="", QString _postfix="")
virtual void modifyGeometryIO(ShaderGenerator *_shader)
Add your own inputs/outputs to the geometry shader.
void modifyVertexEndCode(QStringList *_code)
Append code the the vertex shader.
static unsigned int registerModifier(ShaderModifier *_modifier)
Shader modifiers have to be registered before they can be used. They also must remain allocated for t...
ShaderGenerator::DefaultIODesc ioDesc_
default IO descriptor for the vertex shader
void initTessEvalShaderIO(const ShaderGenDesc *_desc, ShaderGenerator *_prevStage, const DefaultIODesc *_iodesc)
Adds fitting tess-evaluation shader io for a given description.
void scanShaderTemplate(QStringList &_templateSrc, QString _templateFilename, QStringList *_outLayoutDirectives=0)
Scans loaded shader template for requested inputs, glsl version or includes.
void addIOToCode(const QStringList &_cmds)
void addOutput(const QString &_output)
Add one GLSL output specifier.
QStringList tessControlLayout_
layout() directives scanned from loaded templates