Shader.cpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. //
  2. // Copyright (c) 2008-2014 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 "FileSystem.h"
  26. #include "Graphics.h"
  27. #include "Log.h"
  28. #include "Profiler.h"
  29. #include "ResourceCache.h"
  30. #include "Shader.h"
  31. #include "ShaderVariation.h"
  32. #include "XMLFile.h"
  33. #include "DebugNew.h"
  34. namespace Urho3D
  35. {
  36. void CommentOutFunction(String& code, const String& signature)
  37. {
  38. unsigned startPos = code.Find(signature);
  39. unsigned braceLevel = 0;
  40. if (startPos == String::NPOS)
  41. return;
  42. code.Insert(startPos, "/*");
  43. for (unsigned i = startPos + 2 + signature.Length(); i < code.Length(); ++i)
  44. {
  45. if (code[i] == '{')
  46. ++braceLevel;
  47. else if (code[i] == '}')
  48. {
  49. --braceLevel;
  50. if (braceLevel == 0)
  51. {
  52. code.Insert(i + 1, "*/");
  53. return;
  54. }
  55. }
  56. }
  57. }
  58. Shader::Shader(Context* context) :
  59. Resource(context),
  60. timeStamp_(0)
  61. {
  62. }
  63. Shader::~Shader()
  64. {
  65. ResourceCache* cache = GetSubsystem<ResourceCache>();
  66. if (cache)
  67. cache->ResetDependencies(this);
  68. }
  69. void Shader::RegisterObject(Context* context)
  70. {
  71. context->RegisterFactory<Shader>();
  72. }
  73. bool Shader::Load(Deserializer& source)
  74. {
  75. PROFILE(LoadShader);
  76. Graphics* graphics = GetSubsystem<Graphics>();
  77. if (!graphics)
  78. return false;
  79. // Load the shader source code and resolve any includes
  80. timeStamp_ = 0;
  81. String shaderCode;
  82. if (!ProcessSource(shaderCode, source))
  83. return false;
  84. // OpenGL: customize the vertex & pixel shader source code to not include the unnecessary shader,
  85. // and rename either VS() or PS() to main()
  86. #ifdef USE_OPENGL
  87. vsSourceCode_ = shaderCode;
  88. vsSourceCode_.Replace("uniform sampler", "// uniform sampler");
  89. vsSourceCode_.Replace("void VS(", "void main(");
  90. CommentOutFunction(vsSourceCode_, "void PS(");
  91. psSourceCode_ = shaderCode;
  92. psSourceCode_.Replace("attribute ", "// attribute ");
  93. psSourceCode_.Replace("void PS(", "void main(");
  94. CommentOutFunction(psSourceCode_, "void VS(");
  95. #else
  96. vsSourceCode_ = shaderCode;
  97. psSourceCode_ = shaderCode;
  98. #endif
  99. // If variations had already been created, release them and require recompile
  100. for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = vsVariations_.Begin(); i != vsVariations_.End(); ++i)
  101. i->second_->Release();
  102. for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = psVariations_.Begin(); i != psVariations_.End(); ++i)
  103. i->second_->Release();
  104. SetMemoryUse(sizeof(Shader) + vsSourceCode_.Length() + psSourceCode_.Length() + (vsVariations_.Size() + psVariations_.Size()) *
  105. sizeof(ShaderVariation));
  106. return true;
  107. }
  108. ShaderVariation* Shader::GetVariation(ShaderType type, const String& defines)
  109. {
  110. return GetVariation(type, defines.CString());
  111. }
  112. ShaderVariation* Shader::GetVariation(ShaderType type, const char* defines)
  113. {
  114. StringHash definesHash(defines);
  115. if (type == VS)
  116. {
  117. HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = vsVariations_.Find(definesHash);
  118. // Create the shader variation now if not created yet
  119. if (i == vsVariations_.End())
  120. {
  121. i = vsVariations_.Insert(MakePair(definesHash, SharedPtr<ShaderVariation>(new ShaderVariation(this, VS))));
  122. i->second_->SetName(GetFileName(GetName()) + " " + defines);
  123. i->second_->SetDefines(defines);
  124. SetMemoryUse(GetMemoryUse() + sizeof(ShaderVariation));
  125. }
  126. return i->second_;
  127. }
  128. else
  129. {
  130. HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = psVariations_.Find(definesHash);
  131. // Create the shader variation now if not created yet
  132. if (i == psVariations_.End())
  133. {
  134. i = psVariations_.Insert(MakePair(definesHash, SharedPtr<ShaderVariation>(new ShaderVariation(this, PS))));
  135. i->second_->SetName(GetFileName(GetName()) + " " + defines);
  136. i->second_->SetDefines(defines);
  137. SetMemoryUse(GetMemoryUse() + sizeof(ShaderVariation));
  138. }
  139. return i->second_;
  140. }
  141. }
  142. String Shader::SanitateDefines(const String& definesIn)
  143. {
  144. String ret;
  145. ret.Reserve(definesIn.Length());
  146. unsigned numSpaces = 0;
  147. for (unsigned i = 0; i < definesIn.Length(); ++i)
  148. {
  149. // Ensure only one space in a row
  150. if (definesIn[i] == ' ')
  151. ++numSpaces;
  152. else
  153. numSpaces = 0;
  154. if (numSpaces <= 1)
  155. ret += definesIn[i];
  156. }
  157. return ret.Trimmed();
  158. }
  159. bool Shader::ProcessSource(String& code, Deserializer& source)
  160. {
  161. ResourceCache* cache = GetSubsystem<ResourceCache>();
  162. if (!cache)
  163. return false;
  164. // If the source if a non-packaged file, store the timestamp
  165. File* file = dynamic_cast<File*>(&source);
  166. if (file && !file->IsPackaged())
  167. {
  168. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  169. if (fileSystem)
  170. {
  171. String fullName = cache->GetResourceFileName(file->GetName());
  172. unsigned fileTimeStamp = fileSystem->GetLastModifiedTime(fullName);
  173. if (fileTimeStamp > timeStamp_)
  174. timeStamp_ = fileTimeStamp;
  175. }
  176. }
  177. // Store resource dependencies for includes so that we know to reload if any of them changes
  178. if (source.GetName() != GetName())
  179. cache->StoreResourceDependency(this, source.GetName());
  180. while (!source.IsEof())
  181. {
  182. String line = source.ReadLine();
  183. if (line.StartsWith("#include"))
  184. {
  185. String includeFileName = GetPath(source.GetName()) + line.Substring(9).Replaced("\"", "").Trimmed();
  186. SharedPtr<File> includeFile = cache->GetFile(includeFileName);
  187. if (!includeFile)
  188. return false;
  189. // Add the include file into the current code recursively
  190. if (!ProcessSource(code, *includeFile))
  191. return false;
  192. }
  193. else
  194. {
  195. code += line;
  196. code += "\n";
  197. }
  198. }
  199. // Finally insert an empty line to mark the space between files
  200. code += "\n";
  201. return true;
  202. }
  203. }