D3D9ShaderVariation.cpp 13 KB

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