Material.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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 "FileSystem.h"
  26. #include "Graphics.h"
  27. #include "Log.h"
  28. #include "Material.h"
  29. #include "Matrix4x3.h"
  30. #include "Profiler.h"
  31. #include "ResourceCache.h"
  32. #include "StringUtils.h"
  33. #include "Technique.h"
  34. #include "Texture2D.h"
  35. #include "TextureCube.h"
  36. #include "XMLFile.h"
  37. #include "DebugNew.h"
  38. static const String textureUnitNames[] =
  39. {
  40. "diffuse",
  41. "normal",
  42. "specular",
  43. "detail",
  44. "environment",
  45. "emissive",
  46. "lightramp", // Not defined by materials
  47. "lightspot", // Not defined by materials
  48. ""
  49. };
  50. static const String cullModeNames[] =
  51. {
  52. "none",
  53. "ccw",
  54. "cw",
  55. ""
  56. };
  57. TechniqueEntry::TechniqueEntry() :
  58. qualityLevel_(0),
  59. lodDistance_(0.0f)
  60. {
  61. }
  62. TechniqueEntry::TechniqueEntry(Technique* technique, unsigned qualityLevel, float lodDistance) :
  63. technique_(technique),
  64. qualityLevel_(qualityLevel),
  65. lodDistance_(lodDistance)
  66. {
  67. }
  68. TechniqueEntry::~TechniqueEntry()
  69. {
  70. }
  71. OBJECTTYPESTATIC(Material);
  72. Material::Material(Context* context) :
  73. Resource(context),
  74. cullMode_(CULL_CCW),
  75. shadowCullMode_(CULL_CCW),
  76. auxViewFrameNumber_(0),
  77. occlusion_(true)
  78. {
  79. SetNumTechniques(1);
  80. textures_.Resize(MAX_MATERIAL_TEXTURE_UNITS);
  81. // Setup often used default parameters
  82. vsParameters_[VSP_UOFFSET] = Vector4(1.0f, 0.0f, 0.0f, 0.0f);
  83. vsParameters_[VSP_VOFFSET] = Vector4(0.0f, 1.0f, 0.0f, 0.0f);
  84. psParameters_[PSP_MATDIFFCOLOR] = Vector4::UNITY;
  85. psParameters_[PSP_MATEMISSIVECOLOR] = Vector4::ZERO;
  86. psParameters_[PSP_MATSPECPROPERTIES] = Vector4::ZERO;
  87. }
  88. Material::~Material()
  89. {
  90. }
  91. void Material::RegisterObject(Context* context)
  92. {
  93. context->RegisterFactory<Material>();
  94. }
  95. bool Material::Load(Deserializer& source)
  96. {
  97. PROFILE(LoadMaterial);
  98. ResourceCache* cache = GetSubsystem<ResourceCache>();
  99. Graphics* graphics = GetSubsystem<Graphics>();
  100. if ((!cache) || (!graphics))
  101. return false;
  102. SharedPtr<XMLFile> xml(new XMLFile(context_));
  103. if (!xml->Load(source))
  104. return false;
  105. XMLElement rootElem = xml->GetRootElement();
  106. XMLElement techniqueElem = rootElem.GetChildElement("technique");
  107. techniques_.Clear();
  108. while (techniqueElem)
  109. {
  110. Technique* technique = cache->GetResource<Technique>(techniqueElem.GetString("name"));
  111. if (technique)
  112. {
  113. TechniqueEntry newTechnique;
  114. newTechnique.technique_ = technique;
  115. if (techniqueElem.HasAttribute("quality"))
  116. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  117. if (techniqueElem.HasAttribute("loddistance"))
  118. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  119. techniques_.Push(newTechnique);
  120. }
  121. techniqueElem = techniqueElem.GetNextElement("technique");
  122. }
  123. XMLElement textureElem = rootElem.GetChildElement("texture");
  124. while (textureElem)
  125. {
  126. TextureUnit unit = TU_DIFFUSE;
  127. if (textureElem.HasAttribute("unit"))
  128. {
  129. String unitName = textureElem.GetStringLower("unit");
  130. unit = (TextureUnit)GetStringListIndex(unitName, textureUnitNames, MAX_MATERIAL_TEXTURE_UNITS);
  131. if (unitName == "diff")
  132. unit = TU_DIFFUSE;
  133. if (unitName == "norm")
  134. unit = TU_NORMAL;
  135. if (unitName == "spec")
  136. unit = TU_SPECULAR;
  137. if (unitName == "env")
  138. unit = TU_ENVIRONMENT;
  139. if (unit == MAX_MATERIAL_TEXTURE_UNITS)
  140. LOGERROR("Unknown texture unit " + unitName);
  141. }
  142. if (unit != MAX_MATERIAL_TEXTURE_UNITS)
  143. {
  144. String name = textureElem.GetString("name");
  145. // Detect cube maps by file extension: they are defined by an XML file
  146. if (GetExtension(name) == ".xml")
  147. SetTexture(unit, cache->GetResource<TextureCube>(name));
  148. else
  149. SetTexture(unit, cache->GetResource<Texture2D>(name));
  150. }
  151. textureElem = textureElem.GetNextElement("texture");
  152. }
  153. XMLElement parameterElem = rootElem.GetChildElement("parameter");
  154. while (parameterElem)
  155. {
  156. String name = parameterElem.GetString("name");
  157. Vector4 value = parameterElem.GetVector("value");
  158. ShaderParameter param = graphics->GetShaderParameter(name);
  159. // Check whether a VS or PS parameter
  160. if (param < PSP_AMBIENTCOLOR)
  161. SetVertexShaderParameter(param, value);
  162. else if (param != MAX_SHADER_PARAMETERS)
  163. SetPixelShaderParameter(param, value);
  164. else
  165. LOGERROR("Unknown shader parameter " + name);
  166. parameterElem = parameterElem.GetNextElement("parameter");
  167. }
  168. XMLElement cullElem = rootElem.GetChildElement("cull");
  169. if (cullElem)
  170. SetCullMode((CullMode)GetStringListIndex(cullElem.GetString("value"), cullModeNames, CULL_CCW));
  171. XMLElement shadowCullElem = rootElem.GetChildElement("shadowcull");
  172. if (shadowCullElem)
  173. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetString("value"), cullModeNames, CULL_CCW));
  174. // Calculate memory use
  175. unsigned memoryUse = 0;
  176. memoryUse += sizeof(Material);
  177. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  178. memoryUse += textures_.Size() * sizeof(SharedPtr<Texture>);
  179. memoryUse += vsParameters_.Size() * (sizeof(ShaderParameter) + sizeof(Vector4));
  180. memoryUse += psParameters_.Size() * (sizeof(ShaderParameter) + sizeof(Vector4));
  181. SetMemoryUse(memoryUse);
  182. Update();
  183. return true;
  184. }
  185. bool Material::Save(Serializer& dest)
  186. {
  187. Graphics* graphics = GetSubsystem<Graphics>();
  188. if (!graphics)
  189. return false;
  190. SharedPtr<XMLFile> xml(new XMLFile(context_));
  191. XMLElement materialElem = xml->CreateRootElement("material");
  192. // Write techniques
  193. for (unsigned i = 0; i < techniques_.Size(); ++i)
  194. {
  195. TechniqueEntry& entry = techniques_[i];
  196. if (!entry.technique_)
  197. continue;
  198. XMLElement techniqueElem = materialElem.CreateChildElement("technique");
  199. techniqueElem.SetString("name", entry.technique_->GetName());
  200. techniqueElem.SetInt("quality", entry.qualityLevel_);
  201. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  202. }
  203. // Write texture units
  204. for (unsigned j = 0; j < MAX_MATERIAL_TEXTURE_UNITS; ++j)
  205. {
  206. Texture* texture = GetTexture((TextureUnit)j);
  207. if (texture)
  208. {
  209. XMLElement textureElem = materialElem.CreateChildElement("texture");
  210. textureElem.SetString("unit", textureUnitNames[j]);
  211. textureElem.SetString("name", texture->GetName());
  212. }
  213. }
  214. // Write shader parameters
  215. for (Map<ShaderParameter, Vector4>::ConstIterator j = vsParameters_.Begin(); j != vsParameters_.End(); ++j)
  216. {
  217. XMLElement parameterElem = materialElem.CreateChildElement("parameter");
  218. parameterElem.SetString("name", graphics->GetShaderParameterName(j->first_));
  219. parameterElem.SetVector4("value", j->second_);
  220. }
  221. for (Map<ShaderParameter, Vector4>::ConstIterator j = psParameters_.Begin(); j != psParameters_.End(); ++j)
  222. {
  223. XMLElement parameterElem = materialElem.CreateChildElement("parameter");
  224. parameterElem.SetString("name", graphics->GetShaderParameterName(j->first_));
  225. parameterElem.SetVector4("value", j->second_);
  226. }
  227. return xml->Save(dest);
  228. }
  229. void Material::SetNumTechniques(unsigned num)
  230. {
  231. if (!num)
  232. return;
  233. techniques_.Resize(num);
  234. }
  235. void Material::SetTechnique(unsigned index, Technique* technique, unsigned qualityLevel, float lodDistance)
  236. {
  237. if (index >= techniques_.Size())
  238. return;
  239. techniques_[index] = TechniqueEntry(technique, qualityLevel, lodDistance);
  240. Update();
  241. }
  242. void Material::SetVertexShaderParameter(ShaderParameter parameter, const Vector4& value)
  243. {
  244. vsParameters_[parameter] = value;
  245. }
  246. void Material::SetPixelShaderParameter(ShaderParameter parameter, const Vector4& value)
  247. {
  248. psParameters_[parameter] = value;
  249. }
  250. void Material::SetTexture(TextureUnit unit, Texture* texture)
  251. {
  252. if (unit >= MAX_MATERIAL_TEXTURE_UNITS)
  253. return;
  254. textures_[unit] = texture;
  255. }
  256. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  257. {
  258. Matrix4x3 transform(Matrix4x3::IDENTITY);
  259. transform.m00_ = repeat.x_;
  260. transform.m11_ = repeat.y_;
  261. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  262. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  263. Matrix4x3 rotationMatrix(Matrix4x3::IDENTITY);
  264. float angleRad = rotation * M_DEGTORAD;
  265. rotationMatrix.m00_ = cosf(angleRad);
  266. rotationMatrix.m01_ = sinf(angleRad);
  267. rotationMatrix.m10_ = -rotationMatrix.m01_;
  268. rotationMatrix.m11_ = rotationMatrix.m00_;
  269. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  270. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  271. transform = rotationMatrix * transform;
  272. Matrix4x3 offsetMatrix = Matrix4x3::IDENTITY;
  273. offsetMatrix.m03_ = offset.x_;
  274. offsetMatrix.m13_ = offset.y_;
  275. transform = offsetMatrix * transform;
  276. Vector4& uOffset = vsParameters_[VSP_UOFFSET];
  277. Vector4& vOffset = vsParameters_[VSP_VOFFSET];
  278. uOffset.x_ = transform.m00_;
  279. uOffset.y_ = transform.m01_;
  280. uOffset.w_ = transform.m03_;
  281. vOffset.x_ = transform.m10_;
  282. vOffset.y_ = transform.m11_;
  283. vOffset.w_ = transform.m13_;
  284. }
  285. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  286. {
  287. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  288. }
  289. void Material::SetCullMode(CullMode mode)
  290. {
  291. cullMode_ = mode;
  292. }
  293. void Material::SetShadowCullMode(CullMode mode)
  294. {
  295. shadowCullMode_ = mode;
  296. }
  297. void Material::ReleaseShaders()
  298. {
  299. for (unsigned i = 0; i < techniques_.Size(); ++i)
  300. {
  301. Technique* technique = techniques_[i].technique_;
  302. if (technique)
  303. technique->ReleaseShaders();
  304. }
  305. }
  306. SharedPtr<Material> Material::Clone(const String& cloneName) const
  307. {
  308. SharedPtr<Material> ret(new Material(context_));
  309. ret->SetName(cloneName);
  310. ret->techniques_ = techniques_;
  311. ret->vsParameters_ = vsParameters_;
  312. ret->psParameters_ = psParameters_;
  313. ret->textures_ = textures_;
  314. ret->occlusion_ = occlusion_;
  315. ret->cullMode_ = cullMode_;
  316. ret->shadowCullMode_ = shadowCullMode_;
  317. return ret;
  318. }
  319. void Material::MarkForAuxView(unsigned frameNumber)
  320. {
  321. auxViewFrameNumber_ = frameNumber;
  322. }
  323. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  324. {
  325. TechniqueEntry noEntry;
  326. return index < techniques_.Size() ? techniques_[index] : noEntry;
  327. }
  328. Technique* Material::GetTechnique(unsigned index) const
  329. {
  330. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  331. }
  332. Pass* Material::GetPass(unsigned index, PassType pass) const
  333. {
  334. Technique* technique = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  335. return technique ? technique->GetPass(pass) : 0;
  336. }
  337. Texture* Material::GetTexture(TextureUnit unit) const
  338. {
  339. return (unsigned)unit < textures_.Size() ? textures_[unit] : (Texture*)0;
  340. }
  341. const String& Material::GetTextureUnitName(TextureUnit unit)
  342. {
  343. return textureUnitNames[unit];
  344. }
  345. void Material::Update()
  346. {
  347. // Determine occlusion by checking the first pass of each technique
  348. occlusion_ = false;
  349. for (unsigned i = 0; i < techniques_.Size(); ++i)
  350. {
  351. Technique* technique = techniques_[i].technique_;
  352. if (!technique)
  353. continue;
  354. const Map<PassType, Pass>& passes = technique->GetPasses();
  355. if (!passes.Empty())
  356. {
  357. // If pass writes depth, enable occlusion
  358. const Pass& pass = passes.Begin()->second_;
  359. if (pass.GetDepthWrite())
  360. {
  361. occlusion_ = true;
  362. break;
  363. }
  364. }
  365. }
  366. }