Shader.cpp 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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 "../Core/Context.h"
  24. #include "../Graphics/Graphics.h"
  25. #include "../Graphics/Shader.h"
  26. #include "../Graphics/ShaderVariation.h"
  27. #include "../IO/Deserializer.h"
  28. #include "../IO/FileSystem.h"
  29. #include "../IO/Log.h"
  30. #include "../Resource/ResourceCache.h"
  31. #include "../DebugNew.h"
  32. namespace Atomic
  33. {
  34. void CommentOutFunction(String& code, const String& signature)
  35. {
  36. unsigned startPos = code.Find(signature);
  37. unsigned braceLevel = 0;
  38. if (startPos == String::NPOS)
  39. return;
  40. code.Insert(startPos, "/*");
  41. for (unsigned i = startPos + 2 + signature.Length(); i < code.Length(); ++i)
  42. {
  43. if (code[i] == '{')
  44. ++braceLevel;
  45. else if (code[i] == '}')
  46. {
  47. --braceLevel;
  48. if (braceLevel == 0)
  49. {
  50. code.Insert(i + 1, "*/");
  51. return;
  52. }
  53. }
  54. }
  55. }
  56. Shader::Shader(Context* context) :
  57. Resource(context),
  58. timeStamp_(0),
  59. numVariations_(0)
  60. {
  61. RefreshMemoryUse();
  62. }
  63. Shader::~Shader()
  64. {
  65. ResourceCache* cache = GetSubsystem<ResourceCache>();
  66. cache->ResetDependencies(this);
  67. }
  68. void Shader::RegisterObject(Context* context)
  69. {
  70. context->RegisterFactory<Shader>();
  71. }
  72. bool Shader::BeginLoad(Deserializer& source)
  73. {
  74. Graphics* graphics = GetSubsystem<Graphics>();
  75. if (!graphics)
  76. return false;
  77. // Load the shader source code and resolve any includes
  78. timeStamp_ = 0;
  79. String shaderCode;
  80. if (!ProcessSource(shaderCode, source))
  81. return false;
  82. // Comment out the unneeded shader function
  83. vsSourceCode_ = shaderCode;
  84. psSourceCode_ = shaderCode;
  85. CommentOutFunction(vsSourceCode_, "void PS(");
  86. CommentOutFunction(psSourceCode_, "void VS(");
  87. // OpenGL: rename either VS() or PS() to main()
  88. #ifdef ATOMIC_OPENGL
  89. vsSourceCode_.Replace("void VS(", "void main(");
  90. psSourceCode_.Replace("void PS(", "void main(");
  91. #endif
  92. RefreshMemoryUse();
  93. return true;
  94. }
  95. bool Shader::EndLoad()
  96. {
  97. // If variations had already been created, release them and require recompile
  98. for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = vsVariations_.Begin(); i != vsVariations_.End(); ++i)
  99. i->second_->Release();
  100. for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = psVariations_.Begin(); i != psVariations_.End(); ++i)
  101. i->second_->Release();
  102. return true;
  103. }
  104. ShaderVariation* Shader::GetVariation(ShaderType type, const String& defines)
  105. {
  106. return GetVariation(type, defines.CString());
  107. }
  108. ShaderVariation* Shader::GetVariation(ShaderType type, const char* defines)
  109. {
  110. StringHash definesHash(defines);
  111. HashMap<StringHash, SharedPtr<ShaderVariation> >& variations(type == VS ? vsVariations_ : psVariations_);
  112. HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = variations.Find(definesHash);
  113. if (i == variations.End())
  114. {
  115. // If shader not found, normalize the defines (to prevent duplicates) and check again. In that case make an alias
  116. // so that further queries are faster
  117. String normalizedDefines = NormalizeDefines(defines);
  118. StringHash normalizedHash(normalizedDefines);
  119. i = variations.Find(normalizedHash);
  120. if (i != variations.End())
  121. variations.Insert(MakePair(definesHash, i->second_));
  122. else
  123. {
  124. // No shader variation found. Create new
  125. i = variations.Insert(MakePair(normalizedHash, SharedPtr<ShaderVariation>(new ShaderVariation(this, type))));
  126. if (definesHash != normalizedHash)
  127. variations.Insert(MakePair(definesHash, i->second_));
  128. i->second_->SetName(GetFileName(GetName()));
  129. i->second_->SetDefines(normalizedDefines);
  130. ++numVariations_;
  131. RefreshMemoryUse();
  132. }
  133. }
  134. return i->second_;
  135. }
  136. bool Shader::ProcessSource(String& code, Deserializer& source)
  137. {
  138. ResourceCache* cache = GetSubsystem<ResourceCache>();
  139. // If the source if a non-packaged file, store the timestamp
  140. File* file = dynamic_cast<File*>(&source);
  141. if (file && !file->IsPackaged())
  142. {
  143. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  144. String fullName = cache->GetResourceFileName(file->GetName());
  145. unsigned fileTimeStamp = fileSystem->GetLastModifiedTime(fullName);
  146. if (fileTimeStamp > timeStamp_)
  147. timeStamp_ = fileTimeStamp;
  148. }
  149. // Store resource dependencies for includes so that we know to reload if any of them changes
  150. if (source.GetName() != GetName())
  151. cache->StoreResourceDependency(this, source.GetName());
  152. while (!source.IsEof())
  153. {
  154. String line = source.ReadLine();
  155. if (line.StartsWith("#include"))
  156. {
  157. String includeFileName = GetPath(source.GetName()) + line.Substring(9).Replaced("\"", "").Trimmed();
  158. SharedPtr<File> includeFile = cache->GetFile(includeFileName);
  159. if (!includeFile)
  160. return false;
  161. // Add the include file into the current code recursively
  162. if (!ProcessSource(code, *includeFile))
  163. return false;
  164. }
  165. else
  166. {
  167. code += line;
  168. code += "\n";
  169. }
  170. }
  171. // Finally insert an empty line to mark the space between files
  172. code += "\n";
  173. return true;
  174. }
  175. String Shader::NormalizeDefines(const String& defines)
  176. {
  177. Vector<String> definesVec = defines.ToUpper().Split(' ');
  178. Sort(definesVec.Begin(), definesVec.End());
  179. return String::Joined(definesVec, " ");
  180. }
  181. void Shader::RefreshMemoryUse()
  182. {
  183. SetMemoryUse(
  184. (unsigned)(sizeof(Shader) + vsSourceCode_.Length() + psSourceCode_.Length() + numVariations_ * sizeof(ShaderVariation)));
  185. }
  186. }