D3D9ShaderVariation.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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/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 = graphics_->GetShaderCacheDir() + 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. ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
  149. if (!cache->Exists(binaryShaderName))
  150. return false;
  151. FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();
  152. unsigned sourceTimeStamp = owner_->GetTimeStamp();
  153. // If source code is loaded from a package, its timestamp will be zero. Else check that binary is not older
  154. // than source
  155. if (sourceTimeStamp && fileSystem->GetLastModifiedTime(cache->GetResourceFileName(binaryShaderName)) < sourceTimeStamp)
  156. return false;
  157. SharedPtr<File> file = cache->GetFile(binaryShaderName);
  158. if (!file || file->ReadFileID() != "USHD")
  159. {
  160. ATOMIC_LOGERROR(binaryShaderName + " is not a valid shader bytecode file");
  161. return false;
  162. }
  163. /// \todo Check that shader type and model match
  164. /*unsigned short shaderType = */file->ReadUShort();
  165. /*unsigned short shaderModel = */file->ReadUShort();
  166. unsigned numParameters = file->ReadUInt();
  167. for (unsigned i = 0; i < numParameters; ++i)
  168. {
  169. String name = file->ReadString();
  170. unsigned reg = file->ReadUByte();
  171. unsigned regCount = file->ReadUByte();
  172. ShaderParameter parameter;
  173. parameter.type_ = type_;
  174. parameter.name_ = name;
  175. parameter.register_ = reg;
  176. parameter.regCount_ = regCount;
  177. parameters_[StringHash(name)] = parameter;
  178. }
  179. unsigned numTextureUnits = file->ReadUInt();
  180. for (unsigned i = 0; i < numTextureUnits; ++i)
  181. {
  182. /*String unitName = */file->ReadString();
  183. unsigned reg = file->ReadUByte();
  184. if (reg < MAX_TEXTURE_UNITS)
  185. useTextureUnit_[reg] = true;
  186. }
  187. unsigned byteCodeSize = file->ReadUInt();
  188. if (byteCodeSize)
  189. {
  190. byteCode_.Resize(byteCodeSize);
  191. file->Read(&byteCode_[0], byteCodeSize);
  192. if (type_ == VS)
  193. ATOMIC_LOGDEBUG("Loaded cached vertex shader " + GetFullName());
  194. else
  195. ATOMIC_LOGDEBUG("Loaded cached pixel shader " + GetFullName());
  196. return true;
  197. }
  198. else
  199. {
  200. ATOMIC_LOGERROR(binaryShaderName + " has zero length bytecode");
  201. return false;
  202. }
  203. }
  204. bool ShaderVariation::Compile()
  205. {
  206. const String& sourceCode = owner_->GetSourceCode(type_);
  207. Vector<String> defines = defines_.Split(' ');
  208. // Set the entrypoint, profile and flags according to the shader being compiled
  209. const char* entryPoint = 0;
  210. const char* profile = 0;
  211. unsigned flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
  212. if (type_ == VS)
  213. {
  214. entryPoint = "VS";
  215. defines.Push("COMPILEVS");
  216. profile = "vs_3_0";
  217. }
  218. else
  219. {
  220. entryPoint = "PS";
  221. defines.Push("COMPILEPS");
  222. profile = "ps_3_0";
  223. flags |= D3DCOMPILE_PREFER_FLOW_CONTROL;
  224. }
  225. defines.Push("MAXBONES=" + String(Graphics::GetMaxBones()));
  226. // Collect defines into macros
  227. Vector<String> defineValues;
  228. PODVector<D3D_SHADER_MACRO> macros;
  229. for (unsigned i = 0; i < defines.Size(); ++i)
  230. {
  231. unsigned equalsPos = defines[i].Find('=');
  232. if (equalsPos != String::NPOS)
  233. {
  234. defineValues.Push(defines[i].Substring(equalsPos + 1));
  235. defines[i].Resize(equalsPos);
  236. }
  237. else
  238. defineValues.Push("1");
  239. }
  240. for (unsigned i = 0; i < defines.Size(); ++i)
  241. {
  242. D3D_SHADER_MACRO macro;
  243. macro.Name = defines[i].CString();
  244. macro.Definition = defineValues[i].CString();
  245. macros.Push(macro);
  246. // In debug mode, check that all defines are referenced by the shader code
  247. #ifdef _DEBUG
  248. if (sourceCode.Find(defines[i]) == String::NPOS)
  249. ATOMIC_LOGWARNING("Shader " + GetFullName() + " does not use the define " + defines[i]);
  250. #endif
  251. }
  252. D3D_SHADER_MACRO endMacro;
  253. endMacro.Name = 0;
  254. endMacro.Definition = 0;
  255. macros.Push(endMacro);
  256. // Compile using D3DCompile
  257. ID3DBlob* shaderCode = 0;
  258. ID3DBlob* errorMsgs = 0;
  259. HRESULT hr = D3DCompile(sourceCode.CString(), sourceCode.Length(), owner_->GetName().CString(), &macros.Front(), 0,
  260. entryPoint, profile, flags, 0, &shaderCode, &errorMsgs);
  261. if (FAILED(hr))
  262. {
  263. // Do not include end zero unnecessarily
  264. compilerOutput_ = String((const char*)errorMsgs->GetBufferPointer(), (unsigned)errorMsgs->GetBufferSize() - 1);
  265. }
  266. else
  267. {
  268. if (type_ == VS)
  269. ATOMIC_LOGDEBUG("Compiled vertex shader " + GetFullName());
  270. else
  271. ATOMIC_LOGDEBUG("Compiled pixel shader " + GetFullName());
  272. // Inspect the produced bytecode using MojoShader, then strip and store it
  273. unsigned char* bufData = (unsigned char*)shaderCode->GetBufferPointer();
  274. unsigned bufSize = (unsigned)shaderCode->GetBufferSize();
  275. ParseParameters(bufData, bufSize);
  276. CopyStrippedCode(byteCode_, bufData, bufSize);
  277. }
  278. ATOMIC_SAFE_RELEASE(shaderCode);
  279. ATOMIC_SAFE_RELEASE(errorMsgs);
  280. return !byteCode_.Empty();
  281. }
  282. void ShaderVariation::ParseParameters(unsigned char* bufData, unsigned bufSize)
  283. {
  284. MOJOSHADER_parseData const* parseData = MOJOSHADER_parse("bytecode", bufData, bufSize, 0, 0, 0, 0, 0, 0, 0);
  285. for (int i = 0; i < parseData->symbol_count; i++)
  286. {
  287. MOJOSHADER_symbol const& symbol = parseData->symbols[i];
  288. String name(symbol.name);
  289. unsigned reg = symbol.register_index;
  290. unsigned regCount = symbol.register_count;
  291. // Check if the parameter is a constant or a texture sampler
  292. bool isSampler = (name[0] == 's');
  293. name = name.Substring(1);
  294. if (isSampler)
  295. {
  296. // Skip if it's a G-buffer sampler, which are aliases for the standard texture units
  297. if (reg < MAX_TEXTURE_UNITS)
  298. {
  299. if (name != "AlbedoBuffer" && name != "NormalBuffer" && name != "DepthBuffer" && name != "LightBuffer")
  300. useTextureUnit_[reg] = true;
  301. }
  302. }
  303. else
  304. {
  305. ShaderParameter parameter;
  306. parameter.type_ = type_;
  307. parameter.name_ = name;
  308. parameter.register_ = reg;
  309. parameter.regCount_ = regCount;
  310. parameters_[StringHash(name)] = parameter;
  311. }
  312. }
  313. MOJOSHADER_freeParseData(parseData);
  314. }
  315. void ShaderVariation::SaveByteCode(const String& binaryShaderName)
  316. {
  317. ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
  318. FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();
  319. // Filename may or may not be inside the resource system
  320. String fullName = binaryShaderName;
  321. if (!IsAbsolutePath(fullName))
  322. {
  323. // If not absolute, use the resource dir of the shader
  324. String shaderFileName = cache->GetResourceFileName(owner_->GetName());
  325. if (shaderFileName.Empty())
  326. return;
  327. fullName = shaderFileName.Substring(0, shaderFileName.Find(owner_->GetName())) + binaryShaderName;
  328. }
  329. String path = GetPath(fullName);
  330. if (!fileSystem->DirExists(path))
  331. fileSystem->CreateDir(path);
  332. SharedPtr<File> file(new File(owner_->GetContext(), fullName, FILE_WRITE));
  333. if (!file->IsOpen())
  334. return;
  335. file->WriteFileID("USHD");
  336. file->WriteShort((unsigned short)type_);
  337. file->WriteShort(3);
  338. file->WriteUInt(parameters_.Size());
  339. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters_.Begin(); i != parameters_.End(); ++i)
  340. {
  341. file->WriteString(i->second_.name_);
  342. file->WriteUByte((unsigned char)i->second_.register_);
  343. file->WriteUByte((unsigned char)i->second_.regCount_);
  344. }
  345. unsigned usedTextureUnits = 0;
  346. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  347. {
  348. if (useTextureUnit_[i])
  349. ++usedTextureUnits;
  350. }
  351. file->WriteUInt(usedTextureUnits);
  352. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  353. {
  354. if (useTextureUnit_[i])
  355. {
  356. file->WriteString(graphics_->GetTextureUnitName((TextureUnit)i));
  357. file->WriteUByte((unsigned char)i);
  358. }
  359. }
  360. unsigned dataSize = byteCode_.Size();
  361. file->WriteUInt(dataSize);
  362. if (dataSize)
  363. file->Write(&byteCode_[0], dataSize);
  364. }
  365. }