D3D9ShaderVariation.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. //
  2. // Copyright (c) 2008-2014 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.h"
  24. #include "GraphicsImpl.h"
  25. #include "Shader.h"
  26. #include "ShaderVariation.h"
  27. #include <windows.h>
  28. #include <d3dcompiler.h>
  29. #include <mojoshader.h>
  30. #include "DebugNew.h"
  31. namespace Urho3D
  32. {
  33. ShaderVariation::ShaderVariation(Shader* owner, ShaderType type) :
  34. GPUObject(owner->GetSubsystem<Graphics>()),
  35. owner_(owner),
  36. type_(type),
  37. compiled_(false)
  38. {
  39. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  40. useTextureUnit_[i] = false;
  41. }
  42. ShaderVariation::~ShaderVariation()
  43. {
  44. Release();
  45. }
  46. bool ShaderVariation::Create()
  47. {
  48. Release();
  49. if (!graphics_)
  50. return false;
  51. // Compile shader if don't have loadable bytecode
  52. PODVector<unsigned> byteCode;
  53. if (byteCode.Empty())
  54. {
  55. Vector<String> defines = defines_.Split(' ');
  56. // Set the entrypoint, profile and flags according to the shader being compiled
  57. const char* entryPoint = 0;
  58. const char* profile = 0;
  59. unsigned flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
  60. bool useSM3 = graphics_->GetSM3Support();
  61. if (type_ == VS)
  62. {
  63. entryPoint = "VS";
  64. defines.Push("COMPILEVS");
  65. if (!useSM3)
  66. profile = "vs_2_0";
  67. else
  68. profile = "vs_3_0";
  69. }
  70. else
  71. {
  72. entryPoint = "PS";
  73. defines.Push("COMPILEPS");
  74. if (!useSM3)
  75. profile = "ps_2_0";
  76. else
  77. {
  78. profile = "ps_3_0";
  79. flags |= D3DCOMPILE_PREFER_FLOW_CONTROL;
  80. }
  81. }
  82. if (useSM3)
  83. defines.Push("SM3");
  84. // Collect defines into macros
  85. Vector<String> defineValues;
  86. PODVector<D3D_SHADER_MACRO> macros;
  87. for (unsigned i = 0; i < defines.Size(); ++i)
  88. {
  89. unsigned equalsPos = defines[i].Find('=');
  90. if (equalsPos != String::NPOS)
  91. {
  92. defineValues.Push(defines[i].Substring(equalsPos + 1));
  93. defines[i].Resize(equalsPos);
  94. }
  95. else
  96. defineValues.Push("1");
  97. }
  98. for (unsigned i = 0; i < defines.Size(); ++i)
  99. {
  100. D3D_SHADER_MACRO macro;
  101. macro.Name = defines[i].CString();
  102. macro.Definition = defineValues[i].CString();
  103. macros.Push(macro);
  104. }
  105. D3D_SHADER_MACRO endMacro;
  106. endMacro.Name = 0;
  107. endMacro.Definition = 0;
  108. macros.Push(endMacro);
  109. // Compile using D3DCompile
  110. const String& sourceCode = owner_->GetSourceCode(type_);
  111. LPD3DBLOB shaderCode = 0;
  112. LPD3DBLOB errorMsgs = 0;
  113. if (FAILED(D3DCompile(sourceCode.CString(), sourceCode.Length(), owner_->GetName().CString(), &macros.Front(), 0,
  114. entryPoint, profile, flags, 0, &shaderCode, &errorMsgs)))
  115. compilerOutput_ = String((const char*)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize());
  116. else
  117. {
  118. // Inspect the produced bytecode using MojoShader, then strip and store it
  119. unsigned char* bufData = (unsigned char*)shaderCode->GetBufferPointer();
  120. unsigned bufSize = shaderCode->GetBufferSize();
  121. ParseParameters(bufData, bufSize);
  122. CopyStrippedCode(byteCode, bufData, bufSize);
  123. }
  124. if (shaderCode)
  125. shaderCode->Release();
  126. if (errorMsgs)
  127. errorMsgs->Release();
  128. if (byteCode.Empty())
  129. return false;
  130. }
  131. // Then create shader from the bytecode
  132. IDirect3DDevice9* device = graphics_->GetImpl()->GetDevice();
  133. if (type_ == VS)
  134. {
  135. if (!device || FAILED(device->CreateVertexShader(
  136. (const DWORD*)&byteCode[0],
  137. (IDirect3DVertexShader9**)&object_)))
  138. compilerOutput_ = "Could not create vertex shader";
  139. else
  140. compiled_ = true;
  141. }
  142. else
  143. {
  144. if (!device || FAILED(device->CreatePixelShader(
  145. (const DWORD*)&byteCode[0],
  146. (IDirect3DPixelShader9**)&object_)))
  147. compilerOutput_ = "Could not create pixel shader";
  148. else
  149. compiled_ = true;
  150. }
  151. return compiled_;
  152. }
  153. void ShaderVariation::Release()
  154. {
  155. if (object_)
  156. {
  157. if (!graphics_)
  158. return;
  159. if (type_ == VS)
  160. {
  161. if (graphics_->GetVertexShader() == this)
  162. graphics_->SetShaders(0, 0);
  163. ((IDirect3DVertexShader9*)object_)->Release();
  164. }
  165. else
  166. {
  167. if (graphics_->GetPixelShader() == this)
  168. graphics_->SetShaders(0, 0);
  169. ((IDirect3DPixelShader9*)object_)->Release();
  170. }
  171. object_ = 0;
  172. compiled_ = false;
  173. compilerOutput_.Clear();
  174. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  175. useTextureUnit_[i] = false;
  176. parameters_.Clear();
  177. }
  178. }
  179. void ShaderVariation::SetName(const String& name)
  180. {
  181. name_ = name.Trimmed().Replaced(' ', '_');
  182. }
  183. void ShaderVariation::SetDefines(const String& defines)
  184. {
  185. defines_ = defines;
  186. }
  187. void ShaderVariation::ParseParameters(unsigned char* bufData, unsigned bufSize)
  188. {
  189. MOJOSHADER_parseData const *parseData = MOJOSHADER_parse("bytecode", bufData, bufSize, 0, 0, 0, 0, 0, 0, 0);
  190. for (int i = 0; i < parseData->symbol_count; i++)
  191. {
  192. MOJOSHADER_symbol const& symbol = parseData->symbols[i];
  193. String name(symbol.name);
  194. unsigned reg = symbol.register_index;
  195. unsigned regCount = symbol.register_count;
  196. // Check if the parameter is a constant or a texture sampler
  197. bool isSampler = (name[0] == 's');
  198. name = name.Substring(1);
  199. if (isSampler)
  200. {
  201. // Skip if it's a G-buffer sampler, which are aliases for the standard texture units
  202. if (reg < MAX_TEXTURE_UNITS)
  203. {
  204. if (name != "AlbedoBuffer" && name != "NormalBuffer" && name != "DepthBuffer" && name != "LightBuffer")
  205. useTextureUnit_[reg] = true;
  206. }
  207. }
  208. else
  209. {
  210. ShaderParameter newParam(type_, reg, regCount);
  211. HashMap<StringHash, ShaderParameter>::Iterator i = parameters_.Insert(MakePair(StringHash(name), newParam));
  212. graphics_->RegisterShaderParameter(i->first_, i->second_);
  213. }
  214. }
  215. MOJOSHADER_freeParseData(parseData);
  216. // Optimize shader parameter lookup by rehashing to next power of two
  217. parameters_.Rehash(NextPowerOfTwo(parameters_.Size()));
  218. }
  219. void ShaderVariation::CopyStrippedCode(PODVector<unsigned>& dest, unsigned char* bufData, unsigned bufSize)
  220. {
  221. unsigned const D3DSIO_COMMENT = 0xFFFE;
  222. unsigned* srcWords = (unsigned*)bufData;
  223. unsigned srcWordSize = bufSize >> 2;
  224. dest.Clear();
  225. for (unsigned i = 0; i < srcWordSize; ++i)
  226. {
  227. unsigned opcode = srcWords[i] & 0xffff;
  228. unsigned paramLength = (srcWords[i] & 0x0f000000) >> 24;
  229. unsigned commentLength = srcWords[i] >> 16;
  230. // For now, skip comment only at fixed position to prevent false positives
  231. if (i == 1 && opcode == D3DSIO_COMMENT)
  232. {
  233. // Skip the comment
  234. i += commentLength;
  235. }
  236. else
  237. {
  238. // Not a comment, copy the data
  239. dest.Push(srcWords[i]);
  240. }
  241. }
  242. }
  243. }