D3D9Shader.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Context.h"
  25. #include "Deserializer.h"
  26. #include "File.h"
  27. #include "FileSystem.h"
  28. #include "Graphics.h"
  29. #include "GraphicsImpl.h"
  30. #include "Log.h"
  31. #include "Profiler.h"
  32. #include "ResourceCache.h"
  33. #include "Shader.h"
  34. #include "ShaderVariation.h"
  35. #include "XMLFile.h"
  36. #include "DebugNew.h"
  37. OBJECTTYPESTATIC(Shader);
  38. Shader::Shader(Context* context) :
  39. Resource(context),
  40. sourceModifiedTime_(0)
  41. {
  42. }
  43. Shader::~Shader()
  44. {
  45. }
  46. void Shader::RegisterObject(Context* context)
  47. {
  48. context->RegisterFactory<Shader>();
  49. }
  50. bool Shader::Load(Deserializer& source)
  51. {
  52. PROFILE(LoadShader);
  53. Graphics* graphics = GetSubsystem<Graphics>();
  54. if (!graphics)
  55. return false;
  56. if (graphics->GetSM3Support())
  57. {
  58. vsExtension_ = ".vs3";
  59. psExtension_ = ".ps3";
  60. subDir_ = "SM3/";
  61. }
  62. else
  63. {
  64. vsExtension_ = ".vs2";
  65. psExtension_ = ".ps2";
  66. subDir_ = "SM2/";
  67. }
  68. // Get absolute file name of the shader in case we need to invoke ShaderCompiler. This only works if the shader was not
  69. // loaded from a package file
  70. fullFileName_.Clear();
  71. sourceModifiedTime_ = 0;
  72. File* sourceFile = dynamic_cast<File*>(&source);
  73. if (sourceFile && !sourceFile->IsPackaged())
  74. {
  75. ResourceCache* cache = GetSubsystem<ResourceCache>();
  76. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  77. if (cache && fileSystem && !fileSystem->HasRegisteredPaths())
  78. {
  79. fullFileName_ = cache->GetResourceFileName(GetName());
  80. if (!fullFileName_.Empty())
  81. {
  82. // Get last modified time of the main HLSL source file
  83. String path, fileName, extension;
  84. SplitPath(fullFileName_, path, fileName, extension);
  85. String hlslFileName = path + fileName + ".hlsl";
  86. sourceModifiedTime_ = fileSystem->GetLastModifiedTime(hlslFileName);
  87. // Check also timestamps of any included files and the shader description file
  88. if (sourceModifiedTime_)
  89. {
  90. SharedPtr<File> file(new File(context_, hlslFileName));
  91. while (file->IsOpen() && !file->IsEof())
  92. {
  93. String line = file->ReadLine();
  94. if (line.StartsWith("#include"))
  95. {
  96. String includeFileName = path + line.Substring(9).Replaced("\"", "").Trimmed();
  97. unsigned includeFileTime = fileSystem->GetLastModifiedTime(includeFileName);
  98. if (includeFileTime > sourceModifiedTime_)
  99. sourceModifiedTime_ = includeFileTime;
  100. }
  101. }
  102. unsigned descriptionFileTime = fileSystem->GetLastModifiedTime(fullFileName_);
  103. if (descriptionFileTime > sourceModifiedTime_)
  104. sourceModifiedTime_ = descriptionFileTime;
  105. }
  106. else
  107. {
  108. // If the HLSL file was not found, do not attempt to compile shaders
  109. fullFileName_.Clear();
  110. }
  111. }
  112. }
  113. }
  114. SharedPtr<XMLFile> xml(new XMLFile(context_));
  115. if (!xml->Load(source))
  116. return false;
  117. Vector<String> globalDefines;
  118. Vector<String> globalDefineValues;
  119. if (graphics->GetSM3Support())
  120. {
  121. globalDefines.Push("SM3");
  122. globalDefineValues.Push("1");
  123. }
  124. if (!vsParser_.Parse(VS, xml->GetRoot("shaders"), globalDefines, globalDefineValues))
  125. {
  126. LOGERROR("VS: " + vsParser_.GetErrorMessage());
  127. return false;
  128. }
  129. if (!psParser_.Parse(PS, xml->GetRoot("shaders"), globalDefines, globalDefineValues))
  130. {
  131. LOGERROR("PS: " + psParser_.GetErrorMessage());
  132. return false;
  133. }
  134. // If variations had already been created, clear their bytecode
  135. for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = vsVariations_.Begin(); i != vsVariations_.End(); ++i)
  136. {
  137. i->second_->Release();
  138. i->second_->SetByteCode(SharedArrayPtr<unsigned char>());
  139. }
  140. for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = psVariations_.Begin(); i != psVariations_.End(); ++i)
  141. {
  142. i->second_->Release();
  143. i->second_->SetByteCode(SharedArrayPtr<unsigned char>());
  144. }
  145. SetMemoryUse(sizeof(Shader) + 2 * sizeof(ShaderParser) + (vsVariations_.Size() + psVariations_.Size()) *
  146. sizeof(ShaderVariation));
  147. return true;
  148. }
  149. ShaderVariation* Shader::GetVariation(ShaderType type, const String& name)
  150. {
  151. Graphics* graphics = GetSubsystem<Graphics>();
  152. if (!graphics)
  153. return 0;
  154. StringHash nameHash(name);
  155. ShaderParser& parser = type == VS ? vsParser_ : psParser_;
  156. HashMap<StringHash, SharedPtr<ShaderVariation> >& variations = type == VS ? vsVariations_ : psVariations_;
  157. if (parser.HasCombination(name))
  158. {
  159. HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = variations.Find(nameHash);
  160. // Create the shader variation now if not created yet
  161. if (i == variations.End())
  162. {
  163. String path, fileName, extension;
  164. SplitPath(GetName(), path, fileName, extension);
  165. String compiledShaderName = path + subDir_ + fileName;
  166. if (!name.Empty())
  167. compiledShaderName += "_" + name;
  168. compiledShaderName += type == VS ? vsExtension_ : psExtension_;
  169. i = variations.Insert(MakePair(nameHash, SharedPtr<ShaderVariation>(new ShaderVariation(this, type))));
  170. i->second_->SetName(compiledShaderName);
  171. SetMemoryUse(GetMemoryUse() + sizeof(ShaderVariation));
  172. }
  173. return i->second_;
  174. }
  175. else
  176. return 0;
  177. }
  178. bool Shader::PrepareVariation(ShaderVariation* variation)
  179. {
  180. if (!variation)
  181. return false;
  182. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  183. Graphics* graphics = GetSubsystem<Graphics>();
  184. ResourceCache* cache = GetSubsystem<ResourceCache>();
  185. if (!fileSystem || !graphics || !cache)
  186. return false;
  187. String shaderName = variation->GetName();
  188. String variationName = GetFileName(shaderName);
  189. unsigned pos = variationName.Find('_');
  190. if (pos != String::NPOS)
  191. variationName = variationName.Substring(pos + 1);
  192. else
  193. variationName.Clear();
  194. if (!fullFileName_.Empty())
  195. {
  196. if (fileSystem->GetLastModifiedTime(cache->GetResourceFileName(shaderName)) < sourceModifiedTime_)
  197. {
  198. PROFILE(CompileShader);
  199. LOGINFO("Compiling shader " + shaderName);
  200. Vector<String> arguments;
  201. arguments.Push(fullFileName_);
  202. arguments.Push(GetPath(fullFileName_) + subDir_);
  203. arguments.Push(variation->GetShaderType() == VS ? "-tVS" : "-tPS");
  204. arguments.Push("-v" + variationName);
  205. if (graphics->GetSM3Support())
  206. arguments.Push("-dSM3");
  207. if (fileSystem->SystemRun(fileSystem->GetProgramDir() + "ShaderCompiler", arguments) != 0)
  208. {
  209. LOGERROR("Failed to compile shader " + shaderName);
  210. return false;
  211. }
  212. }
  213. }
  214. SharedPtr<File> file(cache->GetFile(shaderName));
  215. if (!file)
  216. return false;
  217. if (file->ReadFileID() != "USHD")
  218. {
  219. LOGERROR(shaderName + " is not a valid shader bytecode file");
  220. return false;
  221. }
  222. /// \todo Check that shader type and model match
  223. unsigned short shaderType = file->ReadUShort();
  224. unsigned short shaderModel = file->ReadUShort();
  225. unsigned numParameters = file->ReadUInt();
  226. for (unsigned i = 0; i < numParameters; ++i)
  227. {
  228. String paramName = file->ReadString();
  229. unsigned reg = file->ReadUByte();
  230. unsigned regCount = file->ReadUByte();
  231. StringHash nameHash(paramName);
  232. ShaderParameter parameter(variation->GetShaderType(), reg, regCount);
  233. variation->AddParameter(nameHash, parameter);
  234. // Register the parameter globally
  235. graphics->RegisterShaderParameter(nameHash, parameter);
  236. }
  237. unsigned numTextureUnits = file->ReadUInt();
  238. for (unsigned i = 0; i < numTextureUnits; ++i)
  239. {
  240. String unitName = file->ReadString();
  241. unsigned sampler = file->ReadUByte();
  242. TextureUnit tuIndex = graphics->GetTextureUnit(unitName);
  243. if (tuIndex != MAX_TEXTURE_UNITS)
  244. variation->AddTextureUnit(tuIndex);
  245. else if (sampler < MAX_TEXTURE_UNITS)
  246. variation->AddTextureUnit((TextureUnit)sampler);
  247. }
  248. unsigned byteCodeSize = file->ReadUInt();
  249. if (byteCodeSize)
  250. {
  251. SharedArrayPtr<unsigned char> byteCode(new unsigned char[byteCodeSize]);
  252. file->Read(byteCode.Get(), byteCodeSize);
  253. variation->SetByteCode(byteCode);
  254. SetMemoryUse(GetMemoryUse() + byteCodeSize);
  255. return true;
  256. }
  257. else
  258. {
  259. LOGERROR("Shader " + shaderName + " has zero length bytecode");
  260. return false;
  261. }
  262. }