D3D11ShaderVariation.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. //
  2. // Copyright (c) 2008-2017 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/Graphics.h"
  24. #include "../../Graphics/GraphicsImpl.h"
  25. #include "../../Graphics/Shader.h"
  26. #include "../../Graphics/VertexBuffer.h"
  27. #include "../../IO/File.h"
  28. #include "../../IO/FileSystem.h"
  29. #include "../../IO/Log.h"
  30. #include "../../Resource/ResourceCache.h"
  31. #include <d3dcompiler.h>
  32. #include "../../DebugNew.h"
  33. namespace Urho3D
  34. {
  35. const char* ShaderVariation::elementSemanticNames[] =
  36. {
  37. "POSITION",
  38. "NORMAL",
  39. "BINORMAL",
  40. "TANGENT",
  41. "TEXCOORD",
  42. "COLOR",
  43. "BLENDWEIGHT",
  44. "BLENDINDICES",
  45. "OBJECTINDEX"
  46. };
  47. void ShaderVariation::OnDeviceLost()
  48. {
  49. // No-op on Direct3D11
  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 = graphics_->GetShaderCacheDir() + 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. {
  81. HRESULT hr = device->CreateVertexShader(&byteCode_[0], byteCode_.Size(), nullptr, (ID3D11VertexShader**)&object_.ptr_);
  82. if (FAILED(hr))
  83. {
  84. URHO3D_SAFE_RELEASE(object_.ptr_);
  85. compilerOutput_ = "Could not create vertex shader (HRESULT " + ToStringHex((unsigned)hr) + ")";
  86. }
  87. }
  88. else
  89. compilerOutput_ = "Could not create vertex shader, empty bytecode";
  90. }
  91. else
  92. {
  93. if (device && byteCode_.Size())
  94. {
  95. HRESULT hr = device->CreatePixelShader(&byteCode_[0], byteCode_.Size(), nullptr, (ID3D11PixelShader**)&object_.ptr_);
  96. if (FAILED(hr))
  97. {
  98. URHO3D_SAFE_RELEASE(object_.ptr_);
  99. compilerOutput_ = "Could not create pixel shader (HRESULT " + ToStringHex((unsigned)hr) + ")";
  100. }
  101. }
  102. else
  103. compilerOutput_ = "Could not create pixel shader, empty bytecode";
  104. }
  105. return object_.ptr_ != nullptr;
  106. }
  107. void ShaderVariation::Release()
  108. {
  109. if (object_.ptr_)
  110. {
  111. if (!graphics_)
  112. return;
  113. graphics_->CleanupShaderPrograms(this);
  114. if (type_ == VS)
  115. {
  116. if (graphics_->GetVertexShader() == this)
  117. graphics_->SetShaders(nullptr, nullptr);
  118. }
  119. else
  120. {
  121. if (graphics_->GetPixelShader() == this)
  122. graphics_->SetShaders(nullptr, nullptr);
  123. }
  124. URHO3D_SAFE_RELEASE(object_.ptr_);
  125. }
  126. compilerOutput_.Clear();
  127. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  128. useTextureUnit_[i] = false;
  129. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  130. constantBufferSizes_[i] = 0;
  131. parameters_.Clear();
  132. byteCode_.Clear();
  133. elementHash_ = 0;
  134. }
  135. void ShaderVariation::SetDefines(const String& defines)
  136. {
  137. defines_ = defines;
  138. // Internal mechanism for appending the CLIPPLANE define, prevents runtime (every frame) string manipulation
  139. definesClipPlane_ = defines;
  140. if (!definesClipPlane_.EndsWith(" CLIPPLANE"))
  141. definesClipPlane_ += " CLIPPLANE";
  142. }
  143. bool ShaderVariation::LoadByteCode(const String& binaryShaderName)
  144. {
  145. ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
  146. if (!cache->Exists(binaryShaderName))
  147. return false;
  148. FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();
  149. unsigned sourceTimeStamp = owner_->GetTimeStamp();
  150. // If source code is loaded from a package, its timestamp will be zero. Else check that binary is not older
  151. // than source
  152. if (sourceTimeStamp && fileSystem->GetLastModifiedTime(cache->GetResourceFileName(binaryShaderName)) < sourceTimeStamp)
  153. return false;
  154. SharedPtr<File> file = cache->GetFile(binaryShaderName);
  155. if (!file || file->ReadFileID() != "USHD")
  156. {
  157. URHO3D_LOGERROR(binaryShaderName + " is not a valid shader bytecode file");
  158. return false;
  159. }
  160. /// \todo Check that shader type and model match
  161. /*unsigned short shaderType = */file->ReadUShort();
  162. /*unsigned short shaderModel = */file->ReadUShort();
  163. elementHash_ = file->ReadUInt();
  164. elementHash_ <<= 32;
  165. unsigned numParameters = file->ReadUInt();
  166. for (unsigned i = 0; i < numParameters; ++i)
  167. {
  168. String name = file->ReadString();
  169. unsigned buffer = file->ReadUByte();
  170. unsigned offset = file->ReadUInt();
  171. unsigned size = file->ReadUInt();
  172. ShaderParameter parameter;
  173. parameter.type_ = type_;
  174. parameter.name_ = name;
  175. parameter.buffer_ = buffer;
  176. parameter.offset_ = offset;
  177. parameter.size_ = size;
  178. parameters_[StringHash(name)] = parameter;
  179. }
  180. unsigned numTextureUnits = file->ReadUInt();
  181. for (unsigned i = 0; i < numTextureUnits; ++i)
  182. {
  183. /*String unitName = */file->ReadString();
  184. unsigned reg = file->ReadUByte();
  185. if (reg < MAX_TEXTURE_UNITS)
  186. useTextureUnit_[reg] = true;
  187. }
  188. unsigned byteCodeSize = file->ReadUInt();
  189. if (byteCodeSize)
  190. {
  191. byteCode_.Resize(byteCodeSize);
  192. file->Read(&byteCode_[0], byteCodeSize);
  193. if (type_ == VS)
  194. URHO3D_LOGDEBUG("Loaded cached vertex shader " + GetFullName());
  195. else
  196. URHO3D_LOGDEBUG("Loaded cached pixel shader " + GetFullName());
  197. CalculateConstantBufferSizes();
  198. return true;
  199. }
  200. else
  201. {
  202. URHO3D_LOGERROR(binaryShaderName + " has zero length bytecode");
  203. return false;
  204. }
  205. }
  206. bool ShaderVariation::Compile()
  207. {
  208. const String& sourceCode = owner_->GetSourceCode(type_);
  209. Vector<String> defines = defines_.Split(' ');
  210. // Set the entrypoint, profile and flags according to the shader being compiled
  211. const char* entryPoint = nullptr;
  212. const char* profile = nullptr;
  213. unsigned flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
  214. defines.Push("D3D11");
  215. if (type_ == VS)
  216. {
  217. entryPoint = "VS";
  218. defines.Push("COMPILEVS");
  219. profile = "vs_4_0";
  220. }
  221. else
  222. {
  223. entryPoint = "PS";
  224. defines.Push("COMPILEPS");
  225. profile = "ps_4_0";
  226. flags |= D3DCOMPILE_PREFER_FLOW_CONTROL;
  227. }
  228. defines.Push("MAXBONES=" + String(Graphics::GetMaxBones()));
  229. // Collect defines into macros
  230. Vector<String> defineValues;
  231. PODVector<D3D_SHADER_MACRO> macros;
  232. for (unsigned i = 0; i < defines.Size(); ++i)
  233. {
  234. unsigned equalsPos = defines[i].Find('=');
  235. if (equalsPos != String::NPOS)
  236. {
  237. defineValues.Push(defines[i].Substring(equalsPos + 1));
  238. defines[i].Resize(equalsPos);
  239. }
  240. else
  241. defineValues.Push("1");
  242. }
  243. for (unsigned i = 0; i < defines.Size(); ++i)
  244. {
  245. D3D_SHADER_MACRO macro;
  246. macro.Name = defines[i].CString();
  247. macro.Definition = defineValues[i].CString();
  248. macros.Push(macro);
  249. // In debug mode, check that all defines are referenced by the shader code
  250. #ifdef _DEBUG
  251. if (sourceCode.Find(defines[i]) == String::NPOS)
  252. URHO3D_LOGWARNING("Shader " + GetFullName() + " does not use the define " + defines[i]);
  253. #endif
  254. }
  255. D3D_SHADER_MACRO endMacro;
  256. endMacro.Name = nullptr;
  257. endMacro.Definition = nullptr;
  258. macros.Push(endMacro);
  259. // Compile using D3DCompile
  260. ID3DBlob* shaderCode = nullptr;
  261. ID3DBlob* errorMsgs = nullptr;
  262. HRESULT hr = D3DCompile(sourceCode.CString(), sourceCode.Length(), owner_->GetName().CString(), &macros.Front(), nullptr,
  263. entryPoint, profile, flags, 0, &shaderCode, &errorMsgs);
  264. if (FAILED(hr))
  265. {
  266. // Do not include end zero unnecessarily
  267. compilerOutput_ = String((const char*)errorMsgs->GetBufferPointer(), (unsigned)errorMsgs->GetBufferSize() - 1);
  268. }
  269. else
  270. {
  271. if (type_ == VS)
  272. URHO3D_LOGDEBUG("Compiled vertex shader " + GetFullName());
  273. else
  274. URHO3D_LOGDEBUG("Compiled pixel shader " + GetFullName());
  275. unsigned char* bufData = (unsigned char*)shaderCode->GetBufferPointer();
  276. unsigned bufSize = (unsigned)shaderCode->GetBufferSize();
  277. // Use the original bytecode to reflect the parameters
  278. ParseParameters(bufData, bufSize);
  279. CalculateConstantBufferSizes();
  280. // Then strip everything not necessary to use the shader
  281. ID3DBlob* strippedCode = nullptr;
  282. D3DStripShader(bufData, bufSize,
  283. D3DCOMPILER_STRIP_REFLECTION_DATA | D3DCOMPILER_STRIP_DEBUG_INFO | D3DCOMPILER_STRIP_TEST_BLOBS, &strippedCode);
  284. byteCode_.Resize((unsigned)strippedCode->GetBufferSize());
  285. memcpy(&byteCode_[0], strippedCode->GetBufferPointer(), byteCode_.Size());
  286. strippedCode->Release();
  287. }
  288. URHO3D_SAFE_RELEASE(shaderCode);
  289. URHO3D_SAFE_RELEASE(errorMsgs);
  290. return !byteCode_.Empty();
  291. }
  292. void ShaderVariation::ParseParameters(unsigned char* bufData, unsigned bufSize)
  293. {
  294. ID3D11ShaderReflection* reflection = nullptr;
  295. D3D11_SHADER_DESC shaderDesc;
  296. HRESULT hr = D3DReflect(bufData, bufSize, IID_ID3D11ShaderReflection, (void**)&reflection);
  297. if (FAILED(hr) || !reflection)
  298. {
  299. URHO3D_SAFE_RELEASE(reflection);
  300. URHO3D_LOGD3DERROR("Failed to reflect vertex shader's input signature", hr);
  301. return;
  302. }
  303. reflection->GetDesc(&shaderDesc);
  304. if (type_ == VS)
  305. {
  306. for (unsigned i = 0; i < shaderDesc.InputParameters; ++i)
  307. {
  308. D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
  309. reflection->GetInputParameterDesc((UINT)i, &paramDesc);
  310. VertexElementSemantic semantic = (VertexElementSemantic)GetStringListIndex(paramDesc.SemanticName, elementSemanticNames, MAX_VERTEX_ELEMENT_SEMANTICS, true);
  311. if (semantic != MAX_VERTEX_ELEMENT_SEMANTICS)
  312. {
  313. elementHash_ <<= 4;
  314. elementHash_ += ((int)semantic + 1) * (paramDesc.SemanticIndex + 1);
  315. }
  316. }
  317. elementHash_ <<= 32;
  318. }
  319. HashMap<String, unsigned> cbRegisterMap;
  320. for (unsigned i = 0; i < shaderDesc.BoundResources; ++i)
  321. {
  322. D3D11_SHADER_INPUT_BIND_DESC resourceDesc;
  323. reflection->GetResourceBindingDesc(i, &resourceDesc);
  324. String resourceName(resourceDesc.Name);
  325. if (resourceDesc.Type == D3D_SIT_CBUFFER)
  326. cbRegisterMap[resourceName] = resourceDesc.BindPoint;
  327. else if (resourceDesc.Type == D3D_SIT_SAMPLER && resourceDesc.BindPoint < MAX_TEXTURE_UNITS)
  328. useTextureUnit_[resourceDesc.BindPoint] = true;
  329. }
  330. for (unsigned i = 0; i < shaderDesc.ConstantBuffers; ++i)
  331. {
  332. ID3D11ShaderReflectionConstantBuffer* cb = reflection->GetConstantBufferByIndex(i);
  333. D3D11_SHADER_BUFFER_DESC cbDesc;
  334. cb->GetDesc(&cbDesc);
  335. unsigned cbRegister = cbRegisterMap[String(cbDesc.Name)];
  336. for (unsigned j = 0; j < cbDesc.Variables; ++j)
  337. {
  338. ID3D11ShaderReflectionVariable* var = cb->GetVariableByIndex(j);
  339. D3D11_SHADER_VARIABLE_DESC varDesc;
  340. var->GetDesc(&varDesc);
  341. String varName(varDesc.Name);
  342. if (varName[0] == 'c')
  343. {
  344. varName = varName.Substring(1); // Strip the c to follow Urho3D constant naming convention
  345. ShaderParameter parameter;
  346. parameter.type_ = type_;
  347. parameter.name_ = varName;
  348. parameter.buffer_ = cbRegister;
  349. parameter.offset_ = varDesc.StartOffset;
  350. parameter.size_ = varDesc.Size;
  351. parameters_[varName] = parameter;
  352. }
  353. }
  354. }
  355. reflection->Release();
  356. }
  357. void ShaderVariation::SaveByteCode(const String& binaryShaderName)
  358. {
  359. ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
  360. FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();
  361. // Filename may or may not be inside the resource system
  362. String fullName = binaryShaderName;
  363. if (!IsAbsolutePath(fullName))
  364. {
  365. // If not absolute, use the resource dir of the shader
  366. String shaderFileName = cache->GetResourceFileName(owner_->GetName());
  367. if (shaderFileName.Empty())
  368. return;
  369. fullName = shaderFileName.Substring(0, shaderFileName.Find(owner_->GetName())) + binaryShaderName;
  370. }
  371. String path = GetPath(fullName);
  372. if (!fileSystem->DirExists(path))
  373. fileSystem->CreateDir(path);
  374. SharedPtr<File> file(new File(owner_->GetContext(), fullName, FILE_WRITE));
  375. if (!file->IsOpen())
  376. return;
  377. file->WriteFileID("USHD");
  378. file->WriteShort((unsigned short)type_);
  379. file->WriteShort(4);
  380. file->WriteUInt(elementHash_ >> 32);
  381. file->WriteUInt(parameters_.Size());
  382. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters_.Begin(); i != parameters_.End(); ++i)
  383. {
  384. file->WriteString(i->second_.name_);
  385. file->WriteUByte((unsigned char)i->second_.buffer_);
  386. file->WriteUInt(i->second_.offset_);
  387. file->WriteUInt(i->second_.size_);
  388. }
  389. unsigned usedTextureUnits = 0;
  390. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  391. {
  392. if (useTextureUnit_[i])
  393. ++usedTextureUnits;
  394. }
  395. file->WriteUInt(usedTextureUnits);
  396. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  397. {
  398. if (useTextureUnit_[i])
  399. {
  400. file->WriteString(graphics_->GetTextureUnitName((TextureUnit)i));
  401. file->WriteUByte((unsigned char)i);
  402. }
  403. }
  404. file->WriteUInt(byteCode_.Size());
  405. if (byteCode_.Size())
  406. file->Write(&byteCode_[0], byteCode_.Size());
  407. }
  408. void ShaderVariation::CalculateConstantBufferSizes()
  409. {
  410. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  411. constantBufferSizes_[i] = 0;
  412. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters_.Begin(); i != parameters_.End(); ++i)
  413. {
  414. if (i->second_.buffer_ < MAX_SHADER_PARAMETER_GROUPS)
  415. {
  416. unsigned oldSize = constantBufferSizes_[i->second_.buffer_];
  417. unsigned paramEnd = i->second_.offset_ + i->second_.size_;
  418. if (paramEnd > oldSize)
  419. constantBufferSizes_[i->second_.buffer_] = paramEnd;
  420. }
  421. }
  422. }
  423. }