OGLShaderProgram.cpp 14 KB

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