Material.cpp 13 KB

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