D3D11ShaderVariation.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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 "../../IO/File.h"
  23. #include "../../IO/FileSystem.h"
  24. #include "../../Graphics/Graphics.h"
  25. #include "../../Graphics/GraphicsImpl.h"
  26. #include "../../IO/Log.h"
  27. #include "../../Resource/ResourceCache.h"
  28. #include "../../Graphics/Shader.h"
  29. #include "../../Graphics/ShaderVariation.h"
  30. #include "../../Graphics/VertexBuffer.h"
  31. #include <windows.h>
  32. #include <d3dcompiler.h>
  33. #include "../../DebugNew.h"
  34. namespace Urho3D
  35. {
  36. ShaderVariation::ShaderVariation(Shader* owner, ShaderType type) :
  37. GPUObject(owner->GetSubsystem<Graphics>()),
  38. owner_(owner),
  39. type_(type),
  40. elementMask_(0)
  41. {
  42. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  43. useTextureUnit_[i] = false;
  44. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  45. constantBufferSizes_[i] = 0;
  46. }
  47. ShaderVariation::~ShaderVariation()
  48. {
  49. Release();
  50. }
  51. bool ShaderVariation::Create()
  52. {
  53. Release();
  54. if (!graphics_)
  55. return false;
  56. if (!owner_)
  57. {
  58. compilerOutput_ = "Owner shader has expired";
  59. return false;
  60. }
  61. // Check for up-to-date bytecode on disk
  62. String path, name, extension;
  63. SplitPath(owner_->GetName(), path, name, extension);
  64. extension = type_ == VS ? ".vs4" : ".ps4";
  65. String binaryShaderName = path + "Cache/" + name + "_" + StringHash(defines_).ToString() + extension;
  66. if (!LoadByteCode(binaryShaderName))
  67. {
  68. // Compile shader if don't have valid bytecode
  69. if (!Compile())
  70. return false;
  71. // Save the bytecode after successful compile, but not if the source is from a package
  72. if (owner_->GetTimeStamp())
  73. SaveByteCode(binaryShaderName);
  74. }
  75. // Then create shader from the bytecode
  76. ID3D11Device* device = graphics_->GetImpl()->GetDevice();
  77. if (type_ == VS)
  78. {
  79. if (device && byteCode_.Size())
  80. device->CreateVertexShader(&byteCode_[0], byteCode_.Size(), 0, (ID3D11VertexShader**)&object_);
  81. if (!object_)
  82. compilerOutput_ = "Could not create vertex shader";
  83. }
  84. else
  85. {
  86. if (device && byteCode_.Size())
  87. device->CreatePixelShader(&byteCode_[0], byteCode_.Size(), 0, (ID3D11PixelShader**)&object_);
  88. if (!object_)
  89. compilerOutput_ = "Could not create pixel shader";
  90. }
  91. return object_ != 0;
  92. }
  93. void ShaderVariation::Release()
  94. {
  95. if (object_)
  96. {
  97. if (!graphics_)
  98. return;
  99. graphics_->CleanUpShaderPrograms(this);
  100. if (type_ == VS)
  101. {
  102. if (graphics_->GetVertexShader() == this)
  103. graphics_->SetShaders(0, 0);
  104. ((ID3D11VertexShader*)object_)->Release();
  105. }
  106. else
  107. {
  108. if (graphics_->GetPixelShader() == this)
  109. graphics_->SetShaders(0, 0);
  110. ((ID3D11PixelShader*)object_)->Release();
  111. }
  112. object_ = 0;
  113. }
  114. compilerOutput_.Clear();
  115. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  116. useTextureUnit_[i] = false;
  117. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  118. constantBufferSizes_[i] = 0;
  119. parameters_.Clear();
  120. byteCode_.Clear();
  121. elementMask_ = 0;
  122. }
  123. void ShaderVariation::SetName(const String& name)
  124. {
  125. name_ = name;
  126. }
  127. void ShaderVariation::SetDefines(const String& defines)
  128. {
  129. defines_ = defines;
  130. }
  131. Shader* ShaderVariation::GetOwner() const
  132. {
  133. return owner_;
  134. }
  135. bool ShaderVariation::LoadByteCode(const String& binaryShaderName)
  136. {
  137. ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
  138. if (!cache->Exists(binaryShaderName))
  139. return false;
  140. FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();
  141. unsigned sourceTimeStamp = owner_->GetTimeStamp();
  142. // If source code is loaded from a package, its timestamp will be zero. Else check that binary is not older
  143. // than source
  144. if (sourceTimeStamp && fileSystem->GetLastModifiedTime(cache->GetResourceFileName(binaryShaderName)) <
  145. sourceTimeStamp)
  146. return false;
  147. SharedPtr<File> file = cache->GetFile(binaryShaderName);
  148. if (!file || file->ReadFileID() != "USHD")
  149. {
  150. LOGERROR(binaryShaderName + " is not a valid shader bytecode file");
  151. return false;
  152. }
  153. /// \todo Check that shader type and model match
  154. unsigned short shaderType = file->ReadUShort();
  155. unsigned short shaderModel = file->ReadUShort();
  156. elementMask_ = file->ReadUInt();
  157. unsigned numParameters = file->ReadUInt();
  158. for (unsigned i = 0; i < numParameters; ++i)
  159. {
  160. String name = file->ReadString();
  161. unsigned buffer = file->ReadUByte();
  162. unsigned offset = file->ReadUInt();
  163. unsigned size = file->ReadUInt();
  164. ShaderParameter parameter(type_, name_, buffer, offset, size);
  165. parameters_[StringHash(name)] = parameter;
  166. }
  167. unsigned numTextureUnits = file->ReadUInt();
  168. for (unsigned i = 0; i < numTextureUnits; ++i)
  169. {
  170. String unitName = file->ReadString();
  171. unsigned reg = file->ReadUByte();
  172. if (reg < MAX_TEXTURE_UNITS)
  173. useTextureUnit_[reg] = true;
  174. }
  175. unsigned byteCodeSize = file->ReadUInt();
  176. if (byteCodeSize)
  177. {
  178. byteCode_.Resize(byteCodeSize);
  179. file->Read(&byteCode_[0], byteCodeSize);
  180. if (type_ == VS)
  181. LOGDEBUG("Loaded cached vertex shader " + GetFullName());
  182. else
  183. LOGDEBUG("Loaded cached pixel shader " + GetFullName());
  184. CalculateConstantBufferSizes();
  185. return true;
  186. }
  187. else
  188. {
  189. LOGERROR(binaryShaderName + " has zero length bytecode");
  190. return false;
  191. }
  192. }
  193. bool ShaderVariation::Compile()
  194. {
  195. const String& sourceCode = owner_->GetSourceCode(type_);
  196. Vector<String> defines = defines_.Split(' ');
  197. // Set the entrypoint, profile and flags according to the shader being compiled
  198. const char* entryPoint = 0;
  199. const char* profile = 0;
  200. unsigned flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
  201. defines.Push("D3D11");
  202. if (type_ == VS)
  203. {
  204. entryPoint = "VS";
  205. defines.Push("COMPILEVS");
  206. profile = "vs_4_0";
  207. }
  208. else
  209. {
  210. entryPoint = "PS";
  211. defines.Push("COMPILEPS");
  212. profile = "ps_4_0";
  213. flags |= D3DCOMPILE_PREFER_FLOW_CONTROL;
  214. }
  215. defines.Push("MAXBONES=" + String(Graphics::GetMaxBones()));
  216. // Collect defines into macros
  217. Vector<String> defineValues;
  218. PODVector<D3D_SHADER_MACRO> macros;
  219. for (unsigned i = 0; i < defines.Size(); ++i)
  220. {
  221. unsigned equalsPos = defines[i].Find('=');
  222. if (equalsPos != String::NPOS)
  223. {
  224. defineValues.Push(defines[i].Substring(equalsPos + 1));
  225. defines[i].Resize(equalsPos);
  226. }
  227. else
  228. defineValues.Push("1");
  229. }
  230. for (unsigned i = 0; i < defines.Size(); ++i)
  231. {
  232. D3D_SHADER_MACRO macro;
  233. macro.Name = defines[i].CString();
  234. macro.Definition = defineValues[i].CString();
  235. macros.Push(macro);
  236. // In debug mode, check that all defines are referenced by the shader code
  237. #ifdef _DEBUG
  238. if (sourceCode.Find(defines[i]) == String::NPOS)
  239. LOGWARNING("Shader " + GetFullName() + " does not use the define " + defines[i]);
  240. #endif
  241. }
  242. D3D_SHADER_MACRO endMacro;
  243. endMacro.Name = 0;
  244. endMacro.Definition = 0;
  245. macros.Push(endMacro);
  246. // Compile using D3DCompile
  247. ID3DBlob* shaderCode = 0;
  248. ID3DBlob* errorMsgs = 0;
  249. if (FAILED(D3DCompile(sourceCode.CString(), sourceCode.Length(), owner_->GetName().CString(), &macros.Front(), 0,
  250. entryPoint, profile, flags, 0, &shaderCode, &errorMsgs)))
  251. compilerOutput_ = String((const char*)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize());
  252. else
  253. {
  254. if (type_ == VS)
  255. LOGDEBUG("Compiled vertex shader " + GetFullName());
  256. else
  257. LOGDEBUG("Compiled pixel shader " + GetFullName());
  258. unsigned char* bufData = (unsigned char*)shaderCode->GetBufferPointer();
  259. unsigned bufSize = shaderCode->GetBufferSize();
  260. // Use the original bytecode to reflect the parameters
  261. ParseParameters(bufData, bufSize);
  262. CalculateConstantBufferSizes();
  263. // Then strip everything not necessary to use the shader
  264. ID3DBlob* strippedCode = 0;
  265. D3DStripShader(bufData, bufSize, D3DCOMPILER_STRIP_REFLECTION_DATA | D3DCOMPILER_STRIP_DEBUG_INFO |
  266. D3DCOMPILER_STRIP_TEST_BLOBS, &strippedCode);
  267. byteCode_.Resize(strippedCode->GetBufferSize());
  268. memcpy(&byteCode_[0], strippedCode->GetBufferPointer(), byteCode_.Size());
  269. strippedCode->Release();
  270. }
  271. if (shaderCode)
  272. shaderCode->Release();
  273. if (errorMsgs)
  274. errorMsgs->Release();
  275. return !byteCode_.Empty();
  276. }
  277. void ShaderVariation::ParseParameters(unsigned char* bufData, unsigned bufSize)
  278. {
  279. ID3D11ShaderReflection* reflection = 0;
  280. D3D11_SHADER_DESC shaderDesc;
  281. D3DReflect(bufData, bufSize, IID_ID3D11ShaderReflection, (void**)&reflection);
  282. if (!reflection)
  283. {
  284. LOGERROR("Failed to reflect vertex shader's input signature");
  285. return;
  286. }
  287. reflection->GetDesc(&shaderDesc);
  288. if (type_ == VS)
  289. {
  290. for (unsigned i = 0; i < shaderDesc.InputParameters; ++i)
  291. {
  292. D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
  293. reflection->GetInputParameterDesc((unsigned)i, &paramDesc);
  294. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  295. {
  296. if (!String::Compare(paramDesc.SemanticName, VertexBuffer::elementSemantics[j], true) && paramDesc.SemanticIndex ==
  297. VertexBuffer::elementSemanticIndices[j])
  298. {
  299. elementMask_ |= (1 << j);
  300. break;
  301. }
  302. }
  303. }
  304. }
  305. HashMap<String, unsigned> cbRegisterMap;
  306. for (unsigned i = 0; i < shaderDesc.BoundResources; ++i)
  307. {
  308. D3D11_SHADER_INPUT_BIND_DESC resourceDesc;
  309. reflection->GetResourceBindingDesc(i, &resourceDesc);
  310. String resourceName(resourceDesc.Name);
  311. if (resourceDesc.Type == D3D_SIT_CBUFFER)
  312. cbRegisterMap[resourceName] = resourceDesc.BindPoint;
  313. else if (type_ == PS && resourceDesc.Type == D3D_SIT_SAMPLER && resourceDesc.BindPoint < MAX_TEXTURE_UNITS)
  314. useTextureUnit_[resourceDesc.BindPoint] = true;
  315. }
  316. for (unsigned i = 0; i < shaderDesc.ConstantBuffers; ++i)
  317. {
  318. ID3D11ShaderReflectionConstantBuffer* cb = reflection->GetConstantBufferByIndex(i);
  319. D3D11_SHADER_BUFFER_DESC cbDesc;
  320. cb->GetDesc(&cbDesc);
  321. unsigned cbRegister = cbRegisterMap[String(cbDesc.Name)];
  322. for (unsigned j = 0; j < cbDesc.Variables; ++j)
  323. {
  324. ID3D11ShaderReflectionVariable* var = cb->GetVariableByIndex(j);
  325. D3D11_SHADER_VARIABLE_DESC varDesc;
  326. var->GetDesc(&varDesc);
  327. String varName(varDesc.Name);
  328. if (varName[0] == 'c')
  329. {
  330. varName = varName.Substring(1); // Strip the c to follow Urho3D constant naming convention
  331. parameters_[varName] = ShaderParameter(type_, varName, cbRegister, varDesc.StartOffset, varDesc.Size);
  332. }
  333. }
  334. }
  335. reflection->Release();
  336. }
  337. void ShaderVariation::SaveByteCode(const String& binaryShaderName)
  338. {
  339. ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
  340. FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();
  341. String path = GetPath(cache->GetResourceFileName(owner_->GetName())) + "Cache/";
  342. String fullName = path + GetFileNameAndExtension(binaryShaderName);
  343. if (!fileSystem->DirExists(path))
  344. fileSystem->CreateDir(path);
  345. SharedPtr<File> file(new File(owner_->GetContext(), fullName, FILE_WRITE));
  346. if (!file->IsOpen())
  347. return;
  348. file->WriteFileID("USHD");
  349. file->WriteShort((unsigned short)type_);
  350. file->WriteShort(4);
  351. file->WriteUInt(elementMask_);
  352. file->WriteUInt(parameters_.Size());
  353. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters_.Begin(); i != parameters_.End(); ++i)
  354. {
  355. file->WriteString(i->second_.name_);
  356. file->WriteUByte((unsigned char)i->second_.buffer_);
  357. file->WriteUInt(i->second_.offset_);
  358. file->WriteUInt(i->second_.size_);
  359. }
  360. unsigned usedTextureUnits = 0;
  361. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  362. {
  363. if (useTextureUnit_[i])
  364. ++usedTextureUnits;
  365. }
  366. file->WriteUInt(usedTextureUnits);
  367. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  368. {
  369. if (useTextureUnit_[i])
  370. {
  371. file->WriteString(graphics_->GetTextureUnitName((TextureUnit)i));
  372. file->WriteUByte(i);
  373. }
  374. }
  375. file->WriteUInt(byteCode_.Size());
  376. if (byteCode_.Size())
  377. file->Write(&byteCode_[0], byteCode_.Size());
  378. }
  379. void ShaderVariation::CalculateConstantBufferSizes()
  380. {
  381. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  382. constantBufferSizes_[i] = 0;
  383. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters_.Begin(); i != parameters_.End(); ++i)
  384. {
  385. if (i->second_.buffer_ < MAX_SHADER_PARAMETER_GROUPS)
  386. {
  387. unsigned oldSize = constantBufferSizes_[i->second_.buffer_];
  388. unsigned paramEnd = i->second_.offset_ + i->second_.size_;
  389. if (paramEnd > oldSize)
  390. constantBufferSizes_[i->second_.buffer_] = paramEnd;
  391. }
  392. }
  393. }
  394. }