D3D9ShaderVariation.cpp 13 KB

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