D3D9ShaderVariation.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. //
  2. // Copyright (c) 2008-2016 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/ShaderVariation.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 <MojoShader/mojoshader.h>
  33. #include "../../DebugNew.h"
  34. namespace Atomic
  35. {
  36. void CopyStrippedCode(PODVector<unsigned char>& byteCode, unsigned char* bufData, unsigned bufSize)
  37. {
  38. unsigned const D3DSIO_COMMENT = 0xFFFE;
  39. unsigned* srcWords = (unsigned*)bufData;
  40. unsigned srcWordSize = bufSize >> 2;
  41. byteCode.Clear();
  42. for (unsigned i = 0; i < srcWordSize; ++i)
  43. {
  44. unsigned opcode = srcWords[i] & 0xffff;
  45. // unsigned paramLength = (srcWords[i] & 0x0f000000) >> 24;
  46. unsigned commentLength = srcWords[i] >> 16;
  47. // For now, skip comment only at fixed position to prevent false positives
  48. if (i == 1 && opcode == D3DSIO_COMMENT)
  49. {
  50. // Skip the comment
  51. i += commentLength;
  52. }
  53. else
  54. {
  55. // Not a comment, copy the data
  56. unsigned destPos = byteCode.Size();
  57. byteCode.Resize(destPos + sizeof(unsigned));
  58. unsigned* dest = (unsigned*)&byteCode[destPos];
  59. *dest = srcWords[i];
  60. }
  61. }
  62. }
  63. void ShaderVariation::OnDeviceLost()
  64. {
  65. // No-op on Direct3D9, shaders are preserved through a device loss & reset
  66. }
  67. bool ShaderVariation::Create()
  68. {
  69. Release();
  70. if (!graphics_)
  71. return false;
  72. if (!owner_)
  73. {
  74. compilerOutput_ = "Owner shader has expired";
  75. return false;
  76. }
  77. // Check for up-to-date bytecode on disk
  78. String path, name, extension;
  79. SplitPath(owner_->GetName(), path, name, extension);
  80. extension = type_ == VS ? ".vs3" : ".ps3";
  81. String binaryShaderName = path + "Cache/" + name + "_" + StringHash(defines_).ToString() + extension;
  82. if (!LoadByteCode(binaryShaderName))
  83. {
  84. // Compile shader if don't have valid bytecode
  85. if (!Compile())
  86. return false;
  87. // Save the bytecode after successful compile, but not if the source is from a package
  88. if (owner_->GetTimeStamp())
  89. SaveByteCode(binaryShaderName);
  90. }
  91. // Then create shader from the bytecode
  92. IDirect3DDevice9* device = graphics_->GetImpl()->GetDevice();
  93. if (type_ == VS)
  94. {
  95. HRESULT hr = device->CreateVertexShader(
  96. (const DWORD*)&byteCode_[0],
  97. (IDirect3DVertexShader9**)&object_.ptr_);
  98. if (FAILED(hr))
  99. {
  100. ATOMIC_SAFE_RELEASE(object_.ptr_);
  101. compilerOutput_ = "Could not create vertex shader (HRESULT " + ToStringHex((unsigned)hr) + ")";
  102. }
  103. }
  104. else
  105. {
  106. HRESULT hr = device->CreatePixelShader(
  107. (const DWORD*)&byteCode_[0],
  108. (IDirect3DPixelShader9**)&object_.ptr_);
  109. if (FAILED(hr))
  110. {
  111. ATOMIC_SAFE_RELEASE(object_.ptr_);
  112. compilerOutput_ = "Could not create pixel shader (HRESULT " + ToStringHex((unsigned)hr) + ")";
  113. }
  114. }
  115. // The bytecode is not needed on Direct3D9 after creation, so delete it to save memory
  116. byteCode_.Clear();
  117. byteCode_.Reserve(0);
  118. return object_.ptr_ != 0;
  119. }
  120. void ShaderVariation::Release()
  121. {
  122. if (object_.ptr_ && graphics_)
  123. {
  124. graphics_->CleanupShaderPrograms(this);
  125. if (type_ == VS)
  126. {
  127. if (graphics_->GetVertexShader() == this)
  128. graphics_->SetShaders(0, 0);
  129. }
  130. else
  131. {
  132. if (graphics_->GetPixelShader() == this)
  133. graphics_->SetShaders(0, 0);
  134. }
  135. }
  136. ATOMIC_SAFE_RELEASE(object_.ptr_);
  137. compilerOutput_.Clear();
  138. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  139. useTextureUnit_[i] = false;
  140. parameters_.Clear();
  141. }
  142. void ShaderVariation::SetDefines(const String& defines)
  143. {
  144. defines_ = defines;
  145. }
  146. bool ShaderVariation::LoadByteCode(const String& binaryShaderName)
  147. {
  148. // ATOMIC BEGIN
  149. // ATOMIC: Disable shader cache until we can bring in configuration updates for writeable paths:
  150. // https://github.com/urho3d/Urho3D/commit/a1e2bc9bd3fe0966bb1aae1e911b96b006d155ce
  151. #ifndef ATOMIC_DEV_BUILD
  152. return false;
  153. #endif
  154. // ATOMIC END
  155. ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
  156. if (!cache->Exists(binaryShaderName))
  157. return false;
  158. FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();
  159. unsigned sourceTimeStamp = owner_->GetTimeStamp();
  160. // If source code is loaded from a package, its timestamp will be zero. Else check that binary is not older
  161. // than source
  162. if (sourceTimeStamp && fileSystem->GetLastModifiedTime(cache->GetResourceFileName(binaryShaderName)) < sourceTimeStamp)
  163. return false;
  164. SharedPtr<File> file = cache->GetFile(binaryShaderName);
  165. if (!file || file->ReadFileID() != "USHD")
  166. {
  167. ATOMIC_LOGERROR(binaryShaderName + " is not a valid shader bytecode file");
  168. return false;
  169. }
  170. /// \todo Check that shader type and model match
  171. /*unsigned short shaderType = */file->ReadUShort();
  172. /*unsigned short shaderModel = */file->ReadUShort();
  173. unsigned numParameters = file->ReadUInt();
  174. for (unsigned i = 0; i < numParameters; ++i)
  175. {
  176. String name = file->ReadString();
  177. unsigned reg = file->ReadUByte();
  178. unsigned regCount = file->ReadUByte();
  179. ShaderParameter parameter;
  180. parameter.type_ = type_;
  181. parameter.name_ = name;
  182. parameter.register_ = reg;
  183. parameter.regCount_ = regCount;
  184. parameters_[StringHash(name)] = parameter;
  185. }
  186. unsigned numTextureUnits = file->ReadUInt();
  187. for (unsigned i = 0; i < numTextureUnits; ++i)
  188. {
  189. /*String unitName = */file->ReadString();
  190. unsigned reg = file->ReadUByte();
  191. if (reg < MAX_TEXTURE_UNITS)
  192. useTextureUnit_[reg] = true;
  193. }
  194. unsigned byteCodeSize = file->ReadUInt();
  195. if (byteCodeSize)
  196. {
  197. byteCode_.Resize(byteCodeSize);
  198. file->Read(&byteCode_[0], byteCodeSize);
  199. if (type_ == VS)
  200. ATOMIC_LOGDEBUG("Loaded cached vertex shader " + GetFullName());
  201. else
  202. ATOMIC_LOGDEBUG("Loaded cached pixel shader " + GetFullName());
  203. return true;
  204. }
  205. else
  206. {
  207. ATOMIC_LOGERROR(binaryShaderName + " has zero length bytecode");
  208. return false;
  209. }
  210. }
  211. bool ShaderVariation::Compile()
  212. {
  213. const String& sourceCode = owner_->GetSourceCode(type_);
  214. Vector<String> defines = defines_.Split(' ');
  215. // Set the entrypoint, profile and flags according to the shader being compiled
  216. const char* entryPoint = 0;
  217. const char* profile = 0;
  218. unsigned flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
  219. if (type_ == VS)
  220. {
  221. entryPoint = "VS";
  222. defines.Push("COMPILEVS");
  223. profile = "vs_3_0";
  224. }
  225. else
  226. {
  227. entryPoint = "PS";
  228. defines.Push("COMPILEPS");
  229. profile = "ps_3_0";
  230. flags |= D3DCOMPILE_PREFER_FLOW_CONTROL;
  231. }
  232. defines.Push("MAXBONES=" + String(Graphics::GetMaxBones()));
  233. // Collect defines into macros
  234. Vector<String> defineValues;
  235. PODVector<D3D_SHADER_MACRO> macros;
  236. for (unsigned i = 0; i < defines.Size(); ++i)
  237. {
  238. unsigned equalsPos = defines[i].Find('=');
  239. if (equalsPos != String::NPOS)
  240. {
  241. defineValues.Push(defines[i].Substring(equalsPos + 1));
  242. defines[i].Resize(equalsPos);
  243. }
  244. else
  245. defineValues.Push("1");
  246. }
  247. for (unsigned i = 0; i < defines.Size(); ++i)
  248. {
  249. D3D_SHADER_MACRO macro;
  250. macro.Name = defines[i].CString();
  251. macro.Definition = defineValues[i].CString();
  252. macros.Push(macro);
  253. // In debug mode, check that all defines are referenced by the shader code
  254. #ifdef _DEBUG
  255. if (sourceCode.Find(defines[i]) == String::NPOS)
  256. ATOMIC_LOGWARNING("Shader " + GetFullName() + " does not use the define " + defines[i]);
  257. #endif
  258. }
  259. D3D_SHADER_MACRO endMacro;
  260. endMacro.Name = 0;
  261. endMacro.Definition = 0;
  262. macros.Push(endMacro);
  263. // Compile using D3DCompile
  264. ID3DBlob* shaderCode = 0;
  265. ID3DBlob* errorMsgs = 0;
  266. HRESULT hr = D3DCompile(sourceCode.CString(), sourceCode.Length(), owner_->GetName().CString(), &macros.Front(), 0,
  267. entryPoint, profile, flags, 0, &shaderCode, &errorMsgs);
  268. if (FAILED(hr))
  269. {
  270. // Do not include end zero unnecessarily
  271. compilerOutput_ = String((const char*)errorMsgs->GetBufferPointer(), (unsigned)errorMsgs->GetBufferSize() - 1);
  272. }
  273. else
  274. {
  275. if (type_ == VS)
  276. ATOMIC_LOGDEBUG("Compiled vertex shader " + GetFullName());
  277. else
  278. ATOMIC_LOGDEBUG("Compiled pixel shader " + GetFullName());
  279. // Inspect the produced bytecode using MojoShader, then strip and store it
  280. unsigned char* bufData = (unsigned char*)shaderCode->GetBufferPointer();
  281. unsigned bufSize = (unsigned)shaderCode->GetBufferSize();
  282. ParseParameters(bufData, bufSize);
  283. CopyStrippedCode(byteCode_, bufData, bufSize);
  284. }
  285. ATOMIC_SAFE_RELEASE(shaderCode);
  286. ATOMIC_SAFE_RELEASE(errorMsgs);
  287. return !byteCode_.Empty();
  288. }
  289. void ShaderVariation::ParseParameters(unsigned char* bufData, unsigned bufSize)
  290. {
  291. MOJOSHADER_parseData const* parseData = MOJOSHADER_parse("bytecode", bufData, bufSize, 0, 0, 0, 0, 0, 0, 0);
  292. for (int i = 0; i < parseData->symbol_count; i++)
  293. {
  294. MOJOSHADER_symbol const& symbol = parseData->symbols[i];
  295. String name(symbol.name);
  296. unsigned reg = symbol.register_index;
  297. unsigned regCount = symbol.register_count;
  298. // Check if the parameter is a constant or a texture sampler
  299. bool isSampler = (name[0] == 's');
  300. name = name.Substring(1);
  301. if (isSampler)
  302. {
  303. // Skip if it's a G-buffer sampler, which are aliases for the standard texture units
  304. if (reg < MAX_TEXTURE_UNITS)
  305. {
  306. if (name != "AlbedoBuffer" && name != "NormalBuffer" && name != "DepthBuffer" && name != "LightBuffer")
  307. useTextureUnit_[reg] = true;
  308. }
  309. }
  310. else
  311. {
  312. ShaderParameter parameter;
  313. parameter.type_ = type_;
  314. parameter.name_ = name;
  315. parameter.register_ = reg;
  316. parameter.regCount_ = regCount;
  317. parameters_[StringHash(name)] = parameter;
  318. }
  319. }
  320. MOJOSHADER_freeParseData(parseData);
  321. }
  322. void ShaderVariation::SaveByteCode(const String& binaryShaderName)
  323. {
  324. // ATOMIC BEGIN
  325. // ATOMIC: Disable shader cache until we can bring in configuration updates for writeable paths:
  326. // https://github.com/urho3d/Urho3D/commit/a1e2bc9bd3fe0966bb1aae1e911b96b006d155ce
  327. #ifndef ATOMIC_DEV_BUILD
  328. return;
  329. #endif
  330. // ATOMIC END
  331. ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
  332. FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();
  333. String path = GetPath(cache->GetResourceFileName(owner_->GetName())) + "Cache/";
  334. String fullName = path + GetFileNameAndExtension(binaryShaderName);
  335. if (!fileSystem->DirExists(path))
  336. fileSystem->CreateDir(path);
  337. SharedPtr<File> file(new File(owner_->GetContext(), fullName, FILE_WRITE));
  338. if (!file->IsOpen())
  339. return;
  340. file->WriteFileID("USHD");
  341. file->WriteShort((unsigned short)type_);
  342. file->WriteShort(3);
  343. file->WriteUInt(parameters_.Size());
  344. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters_.Begin(); i != parameters_.End(); ++i)
  345. {
  346. file->WriteString(i->second_.name_);
  347. file->WriteUByte((unsigned char)i->second_.register_);
  348. file->WriteUByte((unsigned char)i->second_.regCount_);
  349. }
  350. unsigned usedTextureUnits = 0;
  351. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  352. {
  353. if (useTextureUnit_[i])
  354. ++usedTextureUnits;
  355. }
  356. file->WriteUInt(usedTextureUnits);
  357. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  358. {
  359. if (useTextureUnit_[i])
  360. {
  361. file->WriteString(graphics_->GetTextureUnitName((TextureUnit)i));
  362. file->WriteUByte((unsigned char)i);
  363. }
  364. }
  365. unsigned dataSize = byteCode_.Size();
  366. file->WriteUInt(dataSize);
  367. if (dataSize)
  368. file->Write(&byteCode_[0], dataSize);
  369. }
  370. }