D3D11ShaderVariation.cpp 14 KB

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