Material.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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 "Matrix3x4.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. "emissive",
  44. "detail",
  45. "environment",
  46. ""
  47. };
  48. static const String cullModeNames[] =
  49. {
  50. "none",
  51. "ccw",
  52. "cw",
  53. ""
  54. };
  55. TechniqueEntry::TechniqueEntry() :
  56. qualityLevel_(0),
  57. lodDistance_(0.0f)
  58. {
  59. }
  60. TechniqueEntry::TechniqueEntry(Technique* technique, unsigned qualityLevel, float lodDistance) :
  61. technique_(technique),
  62. qualityLevel_(qualityLevel),
  63. lodDistance_(lodDistance)
  64. {
  65. }
  66. TechniqueEntry::~TechniqueEntry()
  67. {
  68. }
  69. OBJECTTYPESTATIC(Material);
  70. Material::Material(Context* context) :
  71. Resource(context),
  72. auxViewFrameNumber_(0),
  73. cullMode_(CULL_CCW),
  74. shadowCullMode_(CULL_CCW),
  75. occlusion_(true)
  76. {
  77. SetNumTechniques(1);
  78. textures_.Resize(MAX_MATERIAL_TEXTURE_UNITS);
  79. // Setup often used default parameters
  80. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  81. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  82. SetShaderParameter("MatDiffColor", Vector4::ONE);
  83. SetShaderParameter("MatEmissiveColor", Vector4::ZERO);
  84. SetShaderParameter("MatSpecProperties", Vector4::ZERO);
  85. CheckSpecular();
  86. }
  87. Material::~Material()
  88. {
  89. }
  90. void Material::RegisterObject(Context* context)
  91. {
  92. context->RegisterFactory<Material>();
  93. }
  94. bool Material::Load(Deserializer& source)
  95. {
  96. PROFILE(LoadMaterial);
  97. // In headless mode, do not actually load the material, just return success
  98. Graphics* graphics = GetSubsystem<Graphics>();
  99. if (!graphics)
  100. return true;
  101. ResourceCache* cache = GetSubsystem<ResourceCache>();
  102. SharedPtr<XMLFile> xml(new XMLFile(context_));
  103. if (!xml->Load(source))
  104. return false;
  105. XMLElement rootElem = xml->GetRoot();
  106. XMLElement techniqueElem = rootElem.GetChild("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.GetNext("technique");
  122. }
  123. XMLElement textureElem = rootElem.GetChild("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.GetNext("texture");
  152. }
  153. XMLElement parameterElem = rootElem.GetChild("parameter");
  154. while (parameterElem)
  155. {
  156. String name = parameterElem.GetString("name");
  157. Vector4 value = parameterElem.GetVector("value");
  158. SetShaderParameter(name, value);
  159. parameterElem = parameterElem.GetNext("parameter");
  160. }
  161. XMLElement cullElem = rootElem.GetChild("cull");
  162. if (cullElem)
  163. SetCullMode((CullMode)GetStringListIndex(cullElem.GetString("value"), cullModeNames, CULL_CCW));
  164. XMLElement shadowCullElem = rootElem.GetChild("shadowcull");
  165. if (shadowCullElem)
  166. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetString("value"), cullModeNames, CULL_CCW));
  167. // Calculate memory use
  168. unsigned memoryUse = sizeof(Material);
  169. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  170. memoryUse += textures_.Size() * sizeof(SharedPtr<Texture>);
  171. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  172. SetMemoryUse(memoryUse);
  173. CheckOcclusion();
  174. CheckSpecular();
  175. return true;
  176. }
  177. bool Material::Save(Serializer& dest)
  178. {
  179. SharedPtr<XMLFile> xml(new XMLFile(context_));
  180. XMLElement materialElem = xml->CreateRoot("material");
  181. // Write techniques
  182. for (unsigned i = 0; i < techniques_.Size(); ++i)
  183. {
  184. TechniqueEntry& entry = techniques_[i];
  185. if (!entry.technique_)
  186. continue;
  187. XMLElement techniqueElem = materialElem.CreateChild("technique");
  188. techniqueElem.SetString("name", entry.technique_->GetName());
  189. techniqueElem.SetInt("quality", entry.qualityLevel_);
  190. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  191. }
  192. // Write texture units
  193. for (unsigned j = 0; j < MAX_MATERIAL_TEXTURE_UNITS; ++j)
  194. {
  195. Texture* texture = GetTexture((TextureUnit)j);
  196. if (texture)
  197. {
  198. XMLElement textureElem = materialElem.CreateChild("texture");
  199. textureElem.SetString("unit", textureUnitNames[j]);
  200. textureElem.SetString("name", texture->GetName());
  201. }
  202. }
  203. // Write shader parameters
  204. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin(); j != shaderParameters_.End(); ++j)
  205. {
  206. XMLElement parameterElem = materialElem.CreateChild("parameter");
  207. parameterElem.SetString("name", j->second_.name_);
  208. parameterElem.SetVector4("value", j->second_.value_);
  209. }
  210. // Write culling modes
  211. XMLElement cullElem = materialElem.CreateChild("cull");
  212. cullElem.SetString("value", cullModeNames[cullMode_]);
  213. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  214. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  215. return xml->Save(dest);
  216. }
  217. void Material::SetNumTechniques(unsigned num)
  218. {
  219. if (!num)
  220. return;
  221. techniques_.Resize(num);
  222. }
  223. void Material::SetTechnique(unsigned index, Technique* technique, unsigned qualityLevel, float lodDistance)
  224. {
  225. if (index >= techniques_.Size())
  226. return;
  227. techniques_[index] = TechniqueEntry(technique, qualityLevel, lodDistance);
  228. CheckOcclusion();
  229. }
  230. void Material::SetShaderParameter(const String& name, const Vector4& value)
  231. {
  232. MaterialShaderParameter newParam;
  233. newParam.name_ = name;
  234. newParam.value_ = value;
  235. shaderParameters_[StringHash(name)] = newParam;
  236. CheckSpecular();
  237. }
  238. void Material::SetTexture(TextureUnit unit, Texture* texture)
  239. {
  240. if (unit >= MAX_MATERIAL_TEXTURE_UNITS)
  241. return;
  242. textures_[unit] = texture;
  243. }
  244. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  245. {
  246. Matrix3x4 transform(Matrix3x4::IDENTITY);
  247. transform.m00_ = repeat.x_;
  248. transform.m11_ = repeat.y_;
  249. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  250. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  251. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  252. float angleRad = rotation * M_DEGTORAD;
  253. rotationMatrix.m00_ = cosf(angleRad);
  254. rotationMatrix.m01_ = sinf(angleRad);
  255. rotationMatrix.m10_ = -rotationMatrix.m01_;
  256. rotationMatrix.m11_ = rotationMatrix.m00_;
  257. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  258. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  259. transform = rotationMatrix * transform;
  260. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  261. offsetMatrix.m03_ = offset.x_;
  262. offsetMatrix.m13_ = offset.y_;
  263. transform = offsetMatrix * transform;
  264. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  265. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  266. }
  267. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  268. {
  269. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  270. }
  271. void Material::SetCullMode(CullMode mode)
  272. {
  273. cullMode_ = mode;
  274. }
  275. void Material::SetShadowCullMode(CullMode mode)
  276. {
  277. shadowCullMode_ = mode;
  278. }
  279. void Material::RemoveShaderParameter(const String& name)
  280. {
  281. shaderParameters_.Erase(StringHash(name));
  282. CheckSpecular();
  283. }
  284. void Material::ReleaseShaders()
  285. {
  286. for (unsigned i = 0; i < techniques_.Size(); ++i)
  287. {
  288. Technique* technique = techniques_[i].technique_;
  289. if (technique)
  290. technique->ReleaseShaders();
  291. }
  292. }
  293. SharedPtr<Material> Material::Clone(const String& cloneName) const
  294. {
  295. SharedPtr<Material> ret(new Material(context_));
  296. ret->SetName(cloneName);
  297. ret->techniques_ = techniques_;
  298. ret->shaderParameters_ = shaderParameters_;
  299. ret->textures_ = textures_;
  300. ret->occlusion_ = occlusion_;
  301. ret->cullMode_ = cullMode_;
  302. ret->shadowCullMode_ = shadowCullMode_;
  303. return ret;
  304. }
  305. void Material::MarkForAuxView(unsigned frameNumber)
  306. {
  307. auxViewFrameNumber_ = frameNumber;
  308. }
  309. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  310. {
  311. TechniqueEntry noEntry;
  312. return index < techniques_.Size() ? techniques_[index] : noEntry;
  313. }
  314. Technique* Material::GetTechnique(unsigned index) const
  315. {
  316. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  317. }
  318. Pass* Material::GetPass(unsigned index, PassType pass) const
  319. {
  320. Technique* technique = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  321. return technique ? technique->GetPass(pass) : 0;
  322. }
  323. Texture* Material::GetTexture(TextureUnit unit) const
  324. {
  325. return (unsigned)unit < textures_.Size() ? textures_[unit] : (Texture*)0;
  326. }
  327. const String& Material::GetTextureUnitName(TextureUnit unit)
  328. {
  329. return textureUnitNames[unit];
  330. }
  331. void Material::CheckOcclusion()
  332. {
  333. // Determine occlusion by checking the first pass of each technique
  334. occlusion_ = false;
  335. for (unsigned i = 0; i < techniques_.Size(); ++i)
  336. {
  337. Technique* technique = techniques_[i].technique_;
  338. if (technique)
  339. {
  340. Pass* pass = technique->GetPass(PASS_BASE);
  341. if (pass && pass->GetDepthWrite())
  342. occlusion_ = true;
  343. }
  344. }
  345. }
  346. void Material::CheckSpecular()
  347. {
  348. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(PSP_MATSPECPROPERTIES);
  349. if (i != shaderParameters_.End())
  350. specular_ = i->second_.value_.x_ > 0.0f;
  351. else
  352. specular_ = false;
  353. }