2
0

Material.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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("MatEnvMapColor", Vector4::ONE);
  85. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  86. CheckSpecular();
  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. // In headless mode, do not actually load the material, just return success
  99. Graphics* graphics = GetSubsystem<Graphics>();
  100. if (!graphics)
  101. return true;
  102. ResourceCache* cache = GetSubsystem<ResourceCache>();
  103. SharedPtr<XMLFile> xml(new XMLFile(context_));
  104. if (!xml->Load(source))
  105. return false;
  106. XMLElement rootElem = xml->GetRoot();
  107. XMLElement techniqueElem = rootElem.GetChild("technique");
  108. techniques_.Clear();
  109. while (techniqueElem)
  110. {
  111. Technique* technique = cache->GetResource<Technique>(techniqueElem.GetString("name"));
  112. if (technique)
  113. {
  114. TechniqueEntry newTechnique;
  115. newTechnique.technique_ = technique;
  116. if (techniqueElem.HasAttribute("quality"))
  117. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  118. if (techniqueElem.HasAttribute("loddistance"))
  119. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  120. techniques_.Push(newTechnique);
  121. }
  122. techniqueElem = techniqueElem.GetNext("technique");
  123. }
  124. XMLElement textureElem = rootElem.GetChild("texture");
  125. while (textureElem)
  126. {
  127. TextureUnit unit = TU_DIFFUSE;
  128. if (textureElem.HasAttribute("unit"))
  129. {
  130. String unitName = textureElem.GetStringLower("unit");
  131. unit = (TextureUnit)GetStringListIndex(unitName, textureUnitNames, MAX_MATERIAL_TEXTURE_UNITS);
  132. if (unitName == "diff")
  133. unit = TU_DIFFUSE;
  134. if (unitName == "norm")
  135. unit = TU_NORMAL;
  136. if (unitName == "spec")
  137. unit = TU_SPECULAR;
  138. if (unitName == "env")
  139. unit = TU_ENVIRONMENT;
  140. if (unit == MAX_MATERIAL_TEXTURE_UNITS)
  141. LOGERROR("Unknown texture unit " + unitName);
  142. }
  143. if (unit != MAX_MATERIAL_TEXTURE_UNITS)
  144. {
  145. String name = textureElem.GetString("name");
  146. // Detect cube maps by file extension: they are defined by an XML file
  147. if (GetExtension(name) == ".xml")
  148. SetTexture(unit, cache->GetResource<TextureCube>(name));
  149. else
  150. SetTexture(unit, cache->GetResource<Texture2D>(name));
  151. }
  152. textureElem = textureElem.GetNext("texture");
  153. }
  154. XMLElement parameterElem = rootElem.GetChild("parameter");
  155. while (parameterElem)
  156. {
  157. String name = parameterElem.GetString("name");
  158. Vector4 value = parameterElem.GetVector("value");
  159. SetShaderParameter(name, value);
  160. parameterElem = parameterElem.GetNext("parameter");
  161. }
  162. XMLElement cullElem = rootElem.GetChild("cull");
  163. if (cullElem)
  164. SetCullMode((CullMode)GetStringListIndex(cullElem.GetString("value"), cullModeNames, CULL_CCW));
  165. XMLElement shadowCullElem = rootElem.GetChild("shadowcull");
  166. if (shadowCullElem)
  167. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetString("value"), cullModeNames, CULL_CCW));
  168. // Calculate memory use
  169. unsigned memoryUse = sizeof(Material);
  170. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  171. memoryUse += textures_.Size() * sizeof(SharedPtr<Texture>);
  172. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  173. SetMemoryUse(memoryUse);
  174. CheckOcclusion();
  175. CheckSpecular();
  176. return true;
  177. }
  178. bool Material::Save(Serializer& dest)
  179. {
  180. SharedPtr<XMLFile> xml(new XMLFile(context_));
  181. XMLElement materialElem = xml->CreateRoot("material");
  182. // Write techniques
  183. for (unsigned i = 0; i < techniques_.Size(); ++i)
  184. {
  185. TechniqueEntry& entry = techniques_[i];
  186. if (!entry.technique_)
  187. continue;
  188. XMLElement techniqueElem = materialElem.CreateChild("technique");
  189. techniqueElem.SetString("name", entry.technique_->GetName());
  190. techniqueElem.SetInt("quality", entry.qualityLevel_);
  191. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  192. }
  193. // Write texture units
  194. for (unsigned j = 0; j < MAX_MATERIAL_TEXTURE_UNITS; ++j)
  195. {
  196. Texture* texture = GetTexture((TextureUnit)j);
  197. if (texture)
  198. {
  199. XMLElement textureElem = materialElem.CreateChild("texture");
  200. textureElem.SetString("unit", textureUnitNames[j]);
  201. textureElem.SetString("name", texture->GetName());
  202. }
  203. }
  204. // Write shader parameters
  205. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin(); j != shaderParameters_.End(); ++j)
  206. {
  207. XMLElement parameterElem = materialElem.CreateChild("parameter");
  208. parameterElem.SetString("name", j->second_.name_);
  209. parameterElem.SetVector4("value", j->second_.value_);
  210. }
  211. // Write culling modes
  212. XMLElement cullElem = materialElem.CreateChild("cull");
  213. cullElem.SetString("value", cullModeNames[cullMode_]);
  214. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  215. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  216. return xml->Save(dest);
  217. }
  218. void Material::SetNumTechniques(unsigned num)
  219. {
  220. if (!num)
  221. return;
  222. techniques_.Resize(num);
  223. }
  224. void Material::SetTechnique(unsigned index, Technique* technique, unsigned qualityLevel, float lodDistance)
  225. {
  226. if (index >= techniques_.Size())
  227. return;
  228. techniques_[index] = TechniqueEntry(technique, qualityLevel, lodDistance);
  229. CheckOcclusion();
  230. }
  231. void Material::SetShaderParameter(const String& name, const Vector4& value)
  232. {
  233. MaterialShaderParameter newParam;
  234. newParam.name_ = name;
  235. newParam.value_ = value;
  236. shaderParameters_[StringHash(name)] = newParam;
  237. CheckSpecular();
  238. }
  239. void Material::SetTexture(TextureUnit unit, Texture* texture)
  240. {
  241. if (unit >= MAX_MATERIAL_TEXTURE_UNITS)
  242. return;
  243. textures_[unit] = texture;
  244. }
  245. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  246. {
  247. Matrix3x4 transform(Matrix3x4::IDENTITY);
  248. transform.m00_ = repeat.x_;
  249. transform.m11_ = repeat.y_;
  250. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  251. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  252. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  253. float angleRad = rotation * M_DEGTORAD;
  254. rotationMatrix.m00_ = cosf(angleRad);
  255. rotationMatrix.m01_ = sinf(angleRad);
  256. rotationMatrix.m10_ = -rotationMatrix.m01_;
  257. rotationMatrix.m11_ = rotationMatrix.m00_;
  258. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  259. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  260. transform = rotationMatrix * transform;
  261. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  262. offsetMatrix.m03_ = offset.x_;
  263. offsetMatrix.m13_ = offset.y_;
  264. transform = offsetMatrix * transform;
  265. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  266. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  267. }
  268. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  269. {
  270. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  271. }
  272. void Material::SetCullMode(CullMode mode)
  273. {
  274. cullMode_ = mode;
  275. }
  276. void Material::SetShadowCullMode(CullMode mode)
  277. {
  278. shadowCullMode_ = mode;
  279. }
  280. void Material::RemoveShaderParameter(const String& name)
  281. {
  282. shaderParameters_.Erase(StringHash(name));
  283. CheckSpecular();
  284. }
  285. void Material::ReleaseShaders()
  286. {
  287. for (unsigned i = 0; i < techniques_.Size(); ++i)
  288. {
  289. Technique* technique = techniques_[i].technique_;
  290. if (technique)
  291. technique->ReleaseShaders();
  292. }
  293. }
  294. SharedPtr<Material> Material::Clone(const String& cloneName) const
  295. {
  296. SharedPtr<Material> ret(new Material(context_));
  297. ret->SetName(cloneName);
  298. ret->techniques_ = techniques_;
  299. ret->shaderParameters_ = shaderParameters_;
  300. ret->textures_ = textures_;
  301. ret->occlusion_ = occlusion_;
  302. ret->cullMode_ = cullMode_;
  303. ret->shadowCullMode_ = shadowCullMode_;
  304. return ret;
  305. }
  306. void Material::MarkForAuxView(unsigned frameNumber)
  307. {
  308. auxViewFrameNumber_ = frameNumber;
  309. }
  310. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  311. {
  312. TechniqueEntry noEntry;
  313. return index < techniques_.Size() ? techniques_[index] : noEntry;
  314. }
  315. Technique* Material::GetTechnique(unsigned index) const
  316. {
  317. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  318. }
  319. Pass* Material::GetPass(unsigned index, PassType pass) const
  320. {
  321. Technique* technique = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  322. return technique ? technique->GetPass(pass) : 0;
  323. }
  324. Texture* Material::GetTexture(TextureUnit unit) const
  325. {
  326. return (unsigned)unit < textures_.Size() ? textures_[unit] : (Texture*)0;
  327. }
  328. const String& Material::GetTextureUnitName(TextureUnit unit)
  329. {
  330. return textureUnitNames[unit];
  331. }
  332. void Material::CheckOcclusion()
  333. {
  334. // Determine occlusion by checking the first pass of each technique
  335. occlusion_ = false;
  336. for (unsigned i = 0; i < techniques_.Size(); ++i)
  337. {
  338. Technique* technique = techniques_[i].technique_;
  339. if (technique)
  340. {
  341. Pass* pass = technique->GetPass(PASS_BASE);
  342. if (pass && pass->GetDepthWrite())
  343. occlusion_ = true;
  344. }
  345. }
  346. }
  347. void Material::CheckSpecular()
  348. {
  349. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(PSP_MATSPECCOLOR);
  350. if (i != shaderParameters_.End())
  351. specular_ = i->second_.value_.x_ > 0.0f || i->second_.value_.y_ > 0.0f || i->second_.value_.z_ > 0.0f;
  352. else
  353. specular_ = false;
  354. }