OGLShaderProgram.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../../Graphics/ConstantBuffer.h"
  23. #include "../../Graphics/Graphics.h"
  24. #include "../../Graphics/GraphicsImpl.h"
  25. #include "../../Graphics/ShaderProgram.h"
  26. #include "../../Graphics/ShaderVariation.h"
  27. #include "../../IO/Log.h"
  28. #include "../../DebugNew.h"
  29. namespace Urho3D
  30. {
  31. const char* shaderParameterGroups[] = {
  32. "frame",
  33. "camera",
  34. "zone",
  35. "light",
  36. "material",
  37. "object",
  38. "custom"
  39. };
  40. ShaderProgram::ShaderProgram(Graphics* graphics, ShaderVariation* vertexShader, ShaderVariation* pixelShader) :
  41. GPUObject(graphics),
  42. vertexShader_(vertexShader),
  43. pixelShader_(pixelShader)
  44. {
  45. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  46. useTextureUnit_[i] = false;
  47. }
  48. ShaderProgram::~ShaderProgram()
  49. {
  50. Release();
  51. }
  52. void ShaderProgram::OnDeviceLost()
  53. {
  54. GPUObject::OnDeviceLost();
  55. if (graphics_ && graphics_->GetShaderProgram() == this)
  56. graphics_->SetShaders(0, 0);
  57. linkerOutput_.Clear();
  58. }
  59. void ShaderProgram::Release()
  60. {
  61. if (object_)
  62. {
  63. if (!graphics_)
  64. return;
  65. if (!graphics_->IsDeviceLost())
  66. {
  67. if (graphics_->GetShaderProgram() == this)
  68. graphics_->SetShaders(0, 0);
  69. glDeleteProgram(object_);
  70. }
  71. object_ = 0;
  72. linkerOutput_.Clear();
  73. shaderParameters_.Clear();
  74. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  75. useTextureUnit_[i] = false;
  76. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  77. constantBuffers_[i].Reset();
  78. }
  79. }
  80. bool ShaderProgram::Link()
  81. {
  82. Release();
  83. if (!vertexShader_ || !pixelShader_ || !vertexShader_->GetGPUObject() || !pixelShader_->GetGPUObject())
  84. return false;
  85. object_ = glCreateProgram();
  86. if (!object_)
  87. {
  88. linkerOutput_ = "Could not create shader program";
  89. return false;
  90. }
  91. // Bind vertex attribute locations to ensure they are the same in all shaders
  92. // Note: this is not the same order as in VertexBuffer, instead a remapping is used to ensure everything except cube texture
  93. // coordinates fit to the first 8 for better GLES2 device compatibility
  94. glBindAttribLocation(object_, 0, "iPos");
  95. glBindAttribLocation(object_, 1, "iNormal");
  96. glBindAttribLocation(object_, 2, "iColor");
  97. glBindAttribLocation(object_, 3, "iTexCoord");
  98. glBindAttribLocation(object_, 4, "iTexCoord2");
  99. glBindAttribLocation(object_, 5, "iTangent");
  100. glBindAttribLocation(object_, 6, "iBlendWeights");
  101. glBindAttribLocation(object_, 7, "iBlendIndices");
  102. glBindAttribLocation(object_, 8, "iCubeTexCoord");
  103. glBindAttribLocation(object_, 9, "iCubeTexCoord2");
  104. #ifndef GL_ES_VERSION_2_0
  105. glBindAttribLocation(object_, 10, "iInstanceMatrix1");
  106. glBindAttribLocation(object_, 11, "iInstanceMatrix2");
  107. glBindAttribLocation(object_, 12, "iInstanceMatrix3");
  108. #endif
  109. glAttachShader(object_, vertexShader_->GetGPUObject());
  110. glAttachShader(object_, pixelShader_->GetGPUObject());
  111. glLinkProgram(object_);
  112. int linked, length;
  113. glGetProgramiv(object_, GL_LINK_STATUS, &linked);
  114. if (!linked)
  115. {
  116. glGetProgramiv(object_, GL_INFO_LOG_LENGTH, &length);
  117. linkerOutput_.Resize(length);
  118. int outLength;
  119. glGetProgramInfoLog(object_, length, &outLength, &linkerOutput_[0]);
  120. glDeleteProgram(object_);
  121. object_ = 0;
  122. }
  123. else
  124. linkerOutput_.Clear();
  125. if (!object_)
  126. return false;
  127. const int MAX_PARAMETER_NAME_LENGTH = 256;
  128. char uniformName[MAX_PARAMETER_NAME_LENGTH];
  129. int uniformCount;
  130. glUseProgram(object_);
  131. glGetProgramiv(object_, GL_ACTIVE_UNIFORMS, &uniformCount);
  132. // Check for constant buffers
  133. #ifndef GL_ES_VERSION_2_0
  134. HashMap<unsigned, unsigned> blockToBinding;
  135. if (Graphics::GetGL3Support())
  136. {
  137. int numUniformBlocks = 0;
  138. glGetProgramiv(object_, GL_ACTIVE_UNIFORM_BLOCKS, &numUniformBlocks);
  139. for (int i = 0; i < numUniformBlocks; ++i)
  140. {
  141. int nameLength;
  142. glGetActiveUniformBlockName(object_, i, MAX_PARAMETER_NAME_LENGTH, &nameLength, uniformName);
  143. String name(uniformName, nameLength);
  144. unsigned blockIndex = glGetUniformBlockIndex(object_, name.CString());
  145. unsigned group = M_MAX_UNSIGNED;
  146. // Try to recognize the use of the buffer from its name
  147. for (unsigned j = 0; j < MAX_SHADER_PARAMETER_GROUPS; ++j)
  148. {
  149. if (name.Contains(shaderParameterGroups[j], false))
  150. {
  151. group = j;
  152. break;
  153. }
  154. }
  155. // If name is not recognized, search for a digit in the name and use that as the group index
  156. if (group == M_MAX_UNSIGNED)
  157. {
  158. for (unsigned j = 1; j < name.Length(); ++j)
  159. {
  160. if (name[j] >= '0' && name[j] <= '5')
  161. {
  162. group = name[j] - '0';
  163. break;
  164. }
  165. }
  166. }
  167. if (group >= MAX_SHADER_PARAMETER_GROUPS)
  168. {
  169. LOGWARNING("Skipping unrecognized uniform block " + name + " in shader program " + vertexShader_->GetFullName() +
  170. " " + pixelShader_->GetFullName());
  171. continue;
  172. }
  173. // Find total constant buffer data size
  174. int dataSize;
  175. glGetActiveUniformBlockiv(object_, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize);
  176. if (!dataSize)
  177. return 0;
  178. unsigned bindingIndex = group;
  179. // Vertex shader constant buffer bindings occupy slots starting from zero to maximum supported, pixel shader bindings
  180. // from that point onward
  181. if (name.Contains("PS", false))
  182. bindingIndex += MAX_SHADER_PARAMETER_GROUPS;
  183. glUniformBlockBinding(object_, blockIndex, bindingIndex);
  184. blockToBinding[blockIndex] = bindingIndex;
  185. constantBuffers_[bindingIndex] = graphics_->GetOrCreateConstantBuffer(bindingIndex, dataSize);
  186. }
  187. }
  188. #endif
  189. // Check for shader parameters and texture units
  190. for (int i = 0; i < uniformCount; ++i)
  191. {
  192. unsigned type;
  193. int count;
  194. glGetActiveUniform(object_, i, MAX_PARAMETER_NAME_LENGTH, 0, &count, &type, uniformName);
  195. int location = glGetUniformLocation(object_, uniformName);
  196. // Check for array index included in the name and strip it
  197. String name(uniformName);
  198. unsigned index = name.Find('[');
  199. if (index != String::NPOS)
  200. {
  201. // If not the first index, skip
  202. if (name.Find("[0]", index) == String::NPOS)
  203. continue;
  204. name = name.Substring(0, index);
  205. }
  206. if (name[0] == 'c')
  207. {
  208. // Store constant uniform
  209. String paramName = name.Substring(1);
  210. ShaderParameter newParam;
  211. newParam.type_ = type;
  212. newParam.location_ = location;
  213. #ifndef GL_ES_VERSION_2_0
  214. // If running OpenGL 3, the uniform may be inside a constant buffer
  215. if (newParam.location_ < 0 && Graphics::GetGL3Support())
  216. {
  217. int blockIndex, blockOffset;
  218. glGetActiveUniformsiv(object_, 1, (const GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &blockIndex);
  219. glGetActiveUniformsiv(object_, 1, (const GLuint*)&i, GL_UNIFORM_OFFSET, &blockOffset);
  220. if (blockIndex >= 0)
  221. {
  222. newParam.location_ = blockOffset;
  223. newParam.buffer_ = blockToBinding[blockIndex];
  224. newParam.bufferPtr_ = constantBuffers_[newParam.buffer_];
  225. }
  226. }
  227. #endif
  228. if (newParam.location_ >= 0)
  229. shaderParameters_[StringHash(paramName)] = newParam;
  230. }
  231. else if (location >= 0 && name[0] == 's')
  232. {
  233. // Set the samplers here so that they do not have to be set later
  234. int unit = graphics_->GetTextureUnit(name.Substring(1));
  235. if (unit >= MAX_TEXTURE_UNITS)
  236. {
  237. // If texture unit name is not recognized, search for a digit in the name and use that as the unit index
  238. for (unsigned j = 1; j < name.Length(); ++j)
  239. {
  240. if (name[j] >= '0' && name[j] <= '9')
  241. {
  242. unit = name[j] - '0';
  243. break;
  244. }
  245. }
  246. }
  247. if (unit < MAX_TEXTURE_UNITS)
  248. {
  249. useTextureUnit_[unit] = true;
  250. glUniform1iv(location, 1, &unit);
  251. }
  252. }
  253. }
  254. // Rehash the parameter map to ensure minimal load factor
  255. shaderParameters_.Rehash(NextPowerOfTwo(shaderParameters_.Size()));
  256. return true;
  257. }
  258. ShaderVariation* ShaderProgram::GetVertexShader() const
  259. {
  260. return vertexShader_;
  261. }
  262. ShaderVariation* ShaderProgram::GetPixelShader() const
  263. {
  264. return pixelShader_;
  265. }
  266. bool ShaderProgram::HasParameter(StringHash param) const
  267. {
  268. return shaderParameters_.Find(param) != shaderParameters_.End();
  269. }
  270. const ShaderParameter* ShaderProgram::GetParameter(StringHash param) const
  271. {
  272. HashMap<StringHash, ShaderParameter>::ConstIterator i = shaderParameters_.Find(param);
  273. if (i != shaderParameters_.End())
  274. return &i->second_;
  275. else
  276. return 0;
  277. }
  278. }