OGLShaderProgram.cpp 14 KB

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