D3D9Shader.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. //
  2. // Copyright (c) 2008-2013 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 "Context.h"
  24. #include "Deserializer.h"
  25. #include "File.h"
  26. #include "FileSystem.h"
  27. #include "Graphics.h"
  28. #include "GraphicsImpl.h"
  29. #include "Log.h"
  30. #include "Profiler.h"
  31. #include "ResourceCache.h"
  32. #include "Shader.h"
  33. #include "ShaderVariation.h"
  34. #include "XMLFile.h"
  35. #include "DebugNew.h"
  36. namespace Urho3D
  37. {
  38. OBJECTTYPESTATIC(Shader);
  39. Shader::Shader(Context* context) :
  40. Resource(context),
  41. sourceModifiedTime_(0)
  42. {
  43. }
  44. Shader::~Shader()
  45. {
  46. ResourceCache* cache = GetSubsystem<ResourceCache>();
  47. if (cache)
  48. cache->ResetDependencies(this);
  49. }
  50. void Shader::RegisterObject(Context* context)
  51. {
  52. context->RegisterFactory<Shader>();
  53. }
  54. bool Shader::Load(Deserializer& source)
  55. {
  56. PROFILE(LoadShader);
  57. ResourceCache* cache = GetSubsystem<ResourceCache>();
  58. cache->ResetDependencies(this);
  59. Graphics* graphics = GetSubsystem<Graphics>();
  60. if (!graphics)
  61. return false;
  62. if (graphics->GetSM3Support())
  63. {
  64. vsExtension_ = ".vs3";
  65. psExtension_ = ".ps3";
  66. subDir_ = "SM3/";
  67. }
  68. else
  69. {
  70. vsExtension_ = ".vs2";
  71. psExtension_ = ".ps2";
  72. subDir_ = "SM2/";
  73. }
  74. // Get absolute file name of the shader in case we need to invoke ShaderCompiler. This only works if the shader was not
  75. // loaded from a package file
  76. fullFileName_.Clear();
  77. sourceModifiedTime_ = 0;
  78. File* sourceFile = dynamic_cast<File*>(&source);
  79. if (sourceFile && !sourceFile->IsPackaged())
  80. {
  81. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  82. if (fileSystem && !fileSystem->HasRegisteredPaths())
  83. {
  84. fullFileName_ = cache->GetResourceFileName(GetName());
  85. if (!fullFileName_.Empty())
  86. {
  87. // Get last modified time of the main HLSL source file
  88. String path, fileName, extension;
  89. SplitPath(fullFileName_, path, fileName, extension);
  90. String hlslFileName = path + fileName + ".hlsl";
  91. sourceModifiedTime_ = fileSystem->GetLastModifiedTime(hlslFileName);
  92. String resourcePath = GetPath(GetName());
  93. cache->StoreResourceDependency(this, resourcePath + fileName + ".hlsl");
  94. // Check also timestamps of any included files and the shader description file
  95. if (sourceModifiedTime_)
  96. {
  97. SharedPtr<File> file(new File(context_, hlslFileName));
  98. while (file->IsOpen() && !file->IsEof())
  99. {
  100. String line = file->ReadLine();
  101. if (line.StartsWith("#include"))
  102. {
  103. String includeName = line.Substring(9).Replaced("\"", "").Trimmed();
  104. String includeFullName = path + includeName;
  105. cache->StoreResourceDependency(this, resourcePath + includeName);
  106. unsigned includeFileTime = fileSystem->GetLastModifiedTime(includeFullName);
  107. if (includeFileTime > sourceModifiedTime_)
  108. sourceModifiedTime_ = includeFileTime;
  109. }
  110. }
  111. unsigned descriptionFileTime = fileSystem->GetLastModifiedTime(fullFileName_);
  112. if (descriptionFileTime > sourceModifiedTime_)
  113. sourceModifiedTime_ = descriptionFileTime;
  114. }
  115. else
  116. {
  117. // If the HLSL file was not found, do not attempt to compile shaders
  118. fullFileName_.Clear();
  119. }
  120. }
  121. }
  122. }
  123. SharedPtr<XMLFile> xml(new XMLFile(context_));
  124. if (!xml->Load(source))
  125. return false;
  126. Vector<String> globalDefines;
  127. Vector<String> globalDefineValues;
  128. if (graphics->GetSM3Support())
  129. {
  130. globalDefines.Push("SM3");
  131. globalDefineValues.Push("1");
  132. }
  133. if (!vsParser_.Parse(VS, xml->GetRoot("shaders"), globalDefines, globalDefineValues))
  134. {
  135. LOGERROR("VS: " + vsParser_.GetErrorMessage());
  136. return false;
  137. }
  138. if (!psParser_.Parse(PS, xml->GetRoot("shaders"), globalDefines, globalDefineValues))
  139. {
  140. LOGERROR("PS: " + psParser_.GetErrorMessage());
  141. return false;
  142. }
  143. // If variations had already been created, clear their bytecode
  144. for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = vsVariations_.Begin(); i != vsVariations_.End(); ++i)
  145. {
  146. i->second_->Release();
  147. i->second_->SetByteCode(SharedArrayPtr<unsigned char>());
  148. }
  149. for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = psVariations_.Begin(); i != psVariations_.End(); ++i)
  150. {
  151. i->second_->Release();
  152. i->second_->SetByteCode(SharedArrayPtr<unsigned char>());
  153. }
  154. SetMemoryUse(sizeof(Shader) + 2 * sizeof(ShaderParser) + (vsVariations_.Size() + psVariations_.Size()) *
  155. sizeof(ShaderVariation));
  156. return true;
  157. }
  158. ShaderVariation* Shader::GetVariation(ShaderType type, const String& name)
  159. {
  160. Graphics* graphics = GetSubsystem<Graphics>();
  161. if (!graphics)
  162. return 0;
  163. StringHash nameHash(name);
  164. ShaderParser& parser = type == VS ? vsParser_ : psParser_;
  165. HashMap<StringHash, SharedPtr<ShaderVariation> >& variations = type == VS ? vsVariations_ : psVariations_;
  166. if (parser.HasCombination(name))
  167. {
  168. HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = variations.Find(nameHash);
  169. // Create the shader variation now if not created yet
  170. if (i == variations.End())
  171. {
  172. String path, fileName, extension;
  173. SplitPath(GetName(), path, fileName, extension);
  174. String compiledShaderName = path + subDir_ + fileName;
  175. if (!name.Empty())
  176. compiledShaderName += "_" + name;
  177. compiledShaderName += type == VS ? vsExtension_ : psExtension_;
  178. i = variations.Insert(MakePair(nameHash, SharedPtr<ShaderVariation>(new ShaderVariation(this, type))));
  179. i->second_->SetName(compiledShaderName);
  180. SetMemoryUse(GetMemoryUse() + sizeof(ShaderVariation));
  181. }
  182. return i->second_;
  183. }
  184. else
  185. return 0;
  186. }
  187. bool Shader::PrepareVariation(ShaderVariation* variation)
  188. {
  189. if (!variation)
  190. return false;
  191. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  192. Graphics* graphics = GetSubsystem<Graphics>();
  193. ResourceCache* cache = GetSubsystem<ResourceCache>();
  194. if (!fileSystem || !graphics || !cache)
  195. return false;
  196. String shaderName = variation->GetName();
  197. String variationName = GetFileName(shaderName);
  198. unsigned pos = variationName.Find('_');
  199. if (pos != String::NPOS)
  200. variationName = variationName.Substring(pos + 1);
  201. else
  202. variationName.Clear();
  203. if (!fullFileName_.Empty())
  204. {
  205. if (fileSystem->GetLastModifiedTime(cache->GetResourceFileName(shaderName)) < sourceModifiedTime_)
  206. {
  207. PROFILE(CompileShader);
  208. LOGINFO("Compiling shader " + shaderName);
  209. Vector<String> arguments;
  210. arguments.Push("\"" + fullFileName_ + "\"");
  211. arguments.Push("\"" + GetPath(fullFileName_) + subDir_ + "\"");
  212. arguments.Push(variation->GetShaderType() == VS ? "-tVS" : "-tPS");
  213. arguments.Push("-v" + variationName);
  214. if (graphics->GetSM3Support())
  215. arguments.Push("-dSM3");
  216. if (fileSystem->SystemRun(fileSystem->GetProgramDir() + "ShaderCompiler", arguments) != 0)
  217. {
  218. LOGERROR("Failed to compile shader " + shaderName);
  219. return false;
  220. }
  221. }
  222. }
  223. SharedPtr<File> file(cache->GetFile(shaderName));
  224. if (!file)
  225. return false;
  226. if (file->ReadFileID() != "USHD")
  227. {
  228. LOGERROR(shaderName + " is not a valid shader bytecode file");
  229. return false;
  230. }
  231. /// \todo Check that shader type and model match
  232. unsigned short shaderType = file->ReadUShort();
  233. unsigned short shaderModel = file->ReadUShort();
  234. unsigned numParameters = file->ReadUInt();
  235. for (unsigned i = 0; i < numParameters; ++i)
  236. {
  237. String paramName = file->ReadString();
  238. unsigned reg = file->ReadUByte();
  239. unsigned regCount = file->ReadUByte();
  240. StringHash nameHash(paramName);
  241. ShaderParameter parameter(variation->GetShaderType(), reg, regCount);
  242. variation->AddParameter(nameHash, parameter);
  243. // Register the parameter globally
  244. graphics->RegisterShaderParameter(nameHash, parameter);
  245. }
  246. unsigned numTextureUnits = file->ReadUInt();
  247. for (unsigned i = 0; i < numTextureUnits; ++i)
  248. {
  249. String unitName = file->ReadString();
  250. unsigned sampler = file->ReadUByte();
  251. TextureUnit tuIndex = graphics->GetTextureUnit(unitName);
  252. if (tuIndex < MAX_TEXTURE_UNITS)
  253. variation->AddTextureUnit(tuIndex);
  254. else if (sampler < MAX_TEXTURE_UNITS)
  255. variation->AddTextureUnit((TextureUnit)sampler);
  256. }
  257. unsigned byteCodeSize = file->ReadUInt();
  258. if (byteCodeSize)
  259. {
  260. SharedArrayPtr<unsigned char> byteCode(new unsigned char[byteCodeSize]);
  261. file->Read(byteCode.Get(), byteCodeSize);
  262. variation->SetByteCode(byteCode);
  263. SetMemoryUse(GetMemoryUse() + byteCodeSize);
  264. return true;
  265. }
  266. else
  267. {
  268. LOGERROR("Shader " + shaderName + " has zero length bytecode");
  269. return false;
  270. }
  271. }
  272. }