OGLShaderProgram.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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 "Precompiled.h"
  23. #include "../../Graphics/ConstantBuffer.h"
  24. #include "../../Graphics/Graphics.h"
  25. #include "../../Graphics/GraphicsImpl.h"
  26. #include "../../Graphics/ShaderProgram.h"
  27. #include "../../Graphics/ShaderVariation.h"
  28. #include "../../IO/Log.h"
  29. #include "../../DebugNew.h"
  30. namespace Atomic
  31. {
  32. const char* shaderParameterGroups[] = {
  33. "frame",
  34. "camera",
  35. "zone",
  36. "light",
  37. "material",
  38. "object",
  39. "custom"
  40. };
  41. unsigned ShaderProgram::globalFrameNumber = 0;
  42. const void* ShaderProgram::globalParameterSources[MAX_SHADER_PARAMETER_GROUPS];
  43. ShaderProgram::ShaderProgram(Graphics* graphics, ShaderVariation* vertexShader, ShaderVariation* pixelShader) :
  44. GPUObject(graphics),
  45. vertexShader_(vertexShader),
  46. pixelShader_(pixelShader),
  47. frameNumber_(0)
  48. {
  49. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  50. useTextureUnit_[i] = false;
  51. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  52. parameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  53. }
  54. ShaderProgram::~ShaderProgram()
  55. {
  56. Release();
  57. }
  58. void ShaderProgram::OnDeviceLost()
  59. {
  60. GPUObject::OnDeviceLost();
  61. if (graphics_ && graphics_->GetShaderProgram() == this)
  62. graphics_->SetShaders(0, 0);
  63. linkerOutput_.Clear();
  64. }
  65. void ShaderProgram::Release()
  66. {
  67. if (object_)
  68. {
  69. if (!graphics_)
  70. return;
  71. if (!graphics_->IsDeviceLost())
  72. {
  73. if (graphics_->GetShaderProgram() == this)
  74. graphics_->SetShaders(0, 0);
  75. glDeleteProgram(object_);
  76. }
  77. object_ = 0;
  78. linkerOutput_.Clear();
  79. shaderParameters_.Clear();
  80. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  81. useTextureUnit_[i] = false;
  82. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  83. constantBuffers_[i].Reset();
  84. }
  85. }
  86. bool ShaderProgram::Link()
  87. {
  88. Release();
  89. if (!vertexShader_ || !pixelShader_ || !vertexShader_->GetGPUObject() || !pixelShader_->GetGPUObject())
  90. return false;
  91. object_ = glCreateProgram();
  92. if (!object_)
  93. {
  94. linkerOutput_ = "Could not create shader program";
  95. return false;
  96. }
  97. // Bind vertex attribute locations to ensure they are the same in all shaders
  98. // Note: this is not the same order as in VertexBuffer, instead a remapping is used to ensure everything except cube texture
  99. // coordinates fit to the first 8 for better GLES2 device compatibility
  100. glBindAttribLocation(object_, 0, "iPos");
  101. glBindAttribLocation(object_, 1, "iNormal");
  102. glBindAttribLocation(object_, 2, "iColor");
  103. glBindAttribLocation(object_, 3, "iTexCoord");
  104. glBindAttribLocation(object_, 4, "iTexCoord2");
  105. glBindAttribLocation(object_, 5, "iTangent");
  106. glBindAttribLocation(object_, 6, "iBlendWeights");
  107. glBindAttribLocation(object_, 7, "iBlendIndices");
  108. glBindAttribLocation(object_, 8, "iCubeTexCoord");
  109. glBindAttribLocation(object_, 9, "iCubeTexCoord2");
  110. #ifndef GL_ES_VERSION_2_0
  111. glBindAttribLocation(object_, 10, "iInstanceMatrix1");
  112. glBindAttribLocation(object_, 11, "iInstanceMatrix2");
  113. glBindAttribLocation(object_, 12, "iInstanceMatrix3");
  114. #endif
  115. glAttachShader(object_, vertexShader_->GetGPUObject());
  116. glAttachShader(object_, pixelShader_->GetGPUObject());
  117. glLinkProgram(object_);
  118. int linked, length;
  119. glGetProgramiv(object_, GL_LINK_STATUS, &linked);
  120. if (!linked)
  121. {
  122. glGetProgramiv(object_, GL_INFO_LOG_LENGTH, &length);
  123. linkerOutput_.Resize(length);
  124. int outLength;
  125. glGetProgramInfoLog(object_, length, &outLength, &linkerOutput_[0]);
  126. glDeleteProgram(object_);
  127. object_ = 0;
  128. }
  129. else
  130. linkerOutput_.Clear();
  131. if (!object_)
  132. return false;
  133. const int MAX_PARAMETER_NAME_LENGTH = 256;
  134. char uniformName[MAX_PARAMETER_NAME_LENGTH];
  135. int uniformCount;
  136. glUseProgram(object_);
  137. glGetProgramiv(object_, GL_ACTIVE_UNIFORMS, &uniformCount);
  138. // Check for constant buffers
  139. #ifndef GL_ES_VERSION_2_0
  140. HashMap<unsigned, unsigned> blockToBinding;
  141. if (Graphics::GetGL3Support())
  142. {
  143. int numUniformBlocks = 0;
  144. glGetProgramiv(object_, GL_ACTIVE_UNIFORM_BLOCKS, &numUniformBlocks);
  145. for (int i = 0; i < numUniformBlocks; ++i)
  146. {
  147. int nameLength;
  148. glGetActiveUniformBlockName(object_, i, MAX_PARAMETER_NAME_LENGTH, &nameLength, uniformName);
  149. String name(uniformName, nameLength);
  150. unsigned blockIndex = glGetUniformBlockIndex(object_, name.CString());
  151. unsigned group = M_MAX_UNSIGNED;
  152. // Try to recognize the use of the buffer from its name
  153. for (unsigned j = 0; j < MAX_SHADER_PARAMETER_GROUPS; ++j)
  154. {
  155. if (name.Contains(shaderParameterGroups[j], false))
  156. {
  157. group = j;
  158. break;
  159. }
  160. }
  161. // If name is not recognized, search for a digit in the name and use that as the group index
  162. if (group == M_MAX_UNSIGNED)
  163. {
  164. for (unsigned j = 1; j < name.Length(); ++j)
  165. {
  166. if (name[j] >= '0' && name[j] <= '5')
  167. {
  168. group = name[j] - '0';
  169. break;
  170. }
  171. }
  172. }
  173. if (group >= MAX_SHADER_PARAMETER_GROUPS)
  174. {
  175. LOGWARNING("Skipping unrecognized uniform block " + name + " in shader program " + vertexShader_->GetFullName() +
  176. " " + pixelShader_->GetFullName());
  177. continue;
  178. }
  179. // Find total constant buffer data size
  180. int dataSize;
  181. glGetActiveUniformBlockiv(object_, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE, &dataSize);
  182. if (!dataSize)
  183. continue;
  184. unsigned bindingIndex = group;
  185. // Vertex shader constant buffer bindings occupy slots starting from zero to maximum supported, pixel shader bindings
  186. // from that point onward
  187. if (name.Contains("PS", false))
  188. bindingIndex += MAX_SHADER_PARAMETER_GROUPS;
  189. glUniformBlockBinding(object_, blockIndex, bindingIndex);
  190. blockToBinding[blockIndex] = bindingIndex;
  191. constantBuffers_[bindingIndex] = graphics_->GetOrCreateConstantBuffer(bindingIndex, dataSize);
  192. }
  193. }
  194. #endif
  195. // Check for shader parameters and texture units
  196. for (int i = 0; i < uniformCount; ++i)
  197. {
  198. unsigned type;
  199. int count;
  200. glGetActiveUniform(object_, i, MAX_PARAMETER_NAME_LENGTH, 0, &count, &type, uniformName);
  201. int location = glGetUniformLocation(object_, uniformName);
  202. // Check for array index included in the name and strip it
  203. String name(uniformName);
  204. unsigned index = name.Find('[');
  205. if (index != String::NPOS)
  206. {
  207. // If not the first index, skip
  208. if (name.Find("[0]", index) == String::NPOS)
  209. continue;
  210. name = name.Substring(0, index);
  211. }
  212. if (name[0] == 'c')
  213. {
  214. // Store constant uniform
  215. String paramName = name.Substring(1);
  216. ShaderParameter newParam;
  217. newParam.type_ = type;
  218. newParam.location_ = location;
  219. #ifndef GL_ES_VERSION_2_0
  220. // If running OpenGL 3, the uniform may be inside a constant buffer
  221. if (newParam.location_ < 0 && Graphics::GetGL3Support())
  222. {
  223. int blockIndex, blockOffset;
  224. glGetActiveUniformsiv(object_, 1, (const GLuint*)&i, GL_UNIFORM_BLOCK_INDEX, &blockIndex);
  225. glGetActiveUniformsiv(object_, 1, (const GLuint*)&i, GL_UNIFORM_OFFSET, &blockOffset);
  226. if (blockIndex >= 0)
  227. {
  228. newParam.location_ = blockOffset;
  229. newParam.bufferPtr_ = constantBuffers_[blockToBinding[blockIndex]];
  230. }
  231. }
  232. #endif
  233. if (newParam.location_ >= 0)
  234. shaderParameters_[StringHash(paramName)] = newParam;
  235. }
  236. else if (location >= 0 && name[0] == 's')
  237. {
  238. // Set the samplers here so that they do not have to be set later
  239. int unit = graphics_->GetTextureUnit(name.Substring(1));
  240. if (unit >= MAX_TEXTURE_UNITS)
  241. {
  242. // If texture unit name is not recognized, search for a digit in the name and use that as the unit index
  243. for (unsigned j = 1; j < name.Length(); ++j)
  244. {
  245. if (name[j] >= '0' && name[j] <= '9')
  246. {
  247. unit = name[j] - '0';
  248. break;
  249. }
  250. }
  251. }
  252. if (unit < MAX_TEXTURE_UNITS)
  253. {
  254. useTextureUnit_[unit] = true;
  255. glUniform1iv(location, 1, &unit);
  256. }
  257. }
  258. }
  259. // Rehash the parameter map to ensure minimal load factor
  260. shaderParameters_.Rehash(NextPowerOfTwo(shaderParameters_.Size()));
  261. return true;
  262. }
  263. ShaderVariation* ShaderProgram::GetVertexShader() const
  264. {
  265. return vertexShader_;
  266. }
  267. ShaderVariation* ShaderProgram::GetPixelShader() const
  268. {
  269. return pixelShader_;
  270. }
  271. bool ShaderProgram::HasParameter(StringHash param) const
  272. {
  273. return shaderParameters_.Find(param) != shaderParameters_.End();
  274. }
  275. const ShaderParameter* ShaderProgram::GetParameter(StringHash param) const
  276. {
  277. HashMap<StringHash, ShaderParameter>::ConstIterator i = shaderParameters_.Find(param);
  278. if (i != shaderParameters_.End())
  279. return &i->second_;
  280. else
  281. return 0;
  282. }
  283. bool ShaderProgram::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  284. {
  285. // If global framenumber has changed, invalidate all per-program parameter sources now
  286. if (globalFrameNumber != frameNumber_)
  287. {
  288. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  289. parameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  290. frameNumber_ = globalFrameNumber;
  291. }
  292. // The shader program may use a mixture of constant buffers and individual uniforms even in the same group
  293. #ifndef GL_ES_VERSION_2_0
  294. bool useBuffer = constantBuffers_[group].Get() || constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  295. bool useIndividual = !constantBuffers_[group].Get() || !constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  296. bool needUpdate = false;
  297. if (useBuffer && globalParameterSources[group] != source)
  298. {
  299. globalParameterSources[group] = source;
  300. needUpdate = true;
  301. }
  302. if (useIndividual && parameterSources_[group] != source)
  303. {
  304. parameterSources_[group] = source;
  305. needUpdate = true;
  306. }
  307. return needUpdate;
  308. #else
  309. if (parameterSources_[group] != source)
  310. {
  311. parameterSources_[group] = source;
  312. return true;
  313. }
  314. else
  315. return false;
  316. #endif
  317. }
  318. void ShaderProgram::ClearParameterSource(ShaderParameterGroup group)
  319. {
  320. // The shader program may use a mixture of constant buffers and individual uniforms even in the same group
  321. #ifndef GL_ES_VERSION_2_0
  322. bool useBuffer = constantBuffers_[group].Get() || constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  323. bool useIndividual = !constantBuffers_[group].Get() || !constantBuffers_[group + MAX_SHADER_PARAMETER_GROUPS].Get();
  324. if (useBuffer)
  325. globalParameterSources[group] = (const void*)M_MAX_UNSIGNED;
  326. if (useIndividual)
  327. parameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  328. #else
  329. parameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  330. #endif
  331. }
  332. void ShaderProgram::ClearParameterSources()
  333. {
  334. ++globalFrameNumber;
  335. if (!globalFrameNumber)
  336. ++globalFrameNumber;
  337. #ifndef GL_ES_VERSION_2_0
  338. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  339. globalParameterSources[i] = (const void*)M_MAX_UNSIGNED;
  340. #endif
  341. }
  342. void ShaderProgram::ClearGlobalParameterSource(ShaderParameterGroup group)
  343. {
  344. globalParameterSources[group] = (const void*)M_MAX_UNSIGNED;
  345. }
  346. }