Material.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. //
  2. // Copyright (c) 2008-2013 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 "FileSystem.h"
  25. #include "Graphics.h"
  26. #include "Log.h"
  27. #include "Material.h"
  28. #include "Matrix3x4.h"
  29. #include "Profiler.h"
  30. #include "ResourceCache.h"
  31. #include "Technique.h"
  32. #include "Texture2D.h"
  33. #include "TextureCube.h"
  34. #include "XMLFile.h"
  35. #include "DebugNew.h"
  36. namespace Urho3D
  37. {
  38. static const char* textureUnitNames[] =
  39. {
  40. "diffuse",
  41. "normal",
  42. "specular",
  43. "emissive",
  44. "environment",
  45. "lightramp",
  46. "lightshape",
  47. "shadowmap",
  48. "faceselect",
  49. "indirection",
  50. "depth",
  51. "light",
  52. 0
  53. };
  54. static const char* cullModeNames[] =
  55. {
  56. "none",
  57. "ccw",
  58. "cw",
  59. 0
  60. };
  61. TextureUnit ParseTextureUnitName(const String& name)
  62. {
  63. TextureUnit unit = (TextureUnit)GetStringListIndex(name.CString(), textureUnitNames, MAX_TEXTURE_UNITS);
  64. if (name == "diff")
  65. unit = TU_DIFFUSE;
  66. else if (name == "albedo")
  67. unit = TU_DIFFUSE;
  68. else if (name == "norm")
  69. unit = TU_NORMAL;
  70. else if (name == "spec")
  71. unit = TU_SPECULAR;
  72. else if (name == "env")
  73. unit = TU_ENVIRONMENT;
  74. return unit;
  75. }
  76. static TechniqueEntry noEntry;
  77. bool CompareTechniqueEntries(const TechniqueEntry& lhs, const TechniqueEntry& rhs)
  78. {
  79. if (lhs.lodDistance_ != rhs.lodDistance_)
  80. return lhs.lodDistance_ > rhs.lodDistance_;
  81. else
  82. return lhs.qualityLevel_ > rhs.qualityLevel_;
  83. }
  84. TechniqueEntry::TechniqueEntry() :
  85. qualityLevel_(0),
  86. lodDistance_(0.0f)
  87. {
  88. }
  89. TechniqueEntry::TechniqueEntry(Technique* tech, unsigned qualityLevel, float lodDistance) :
  90. technique_(tech),
  91. qualityLevel_(qualityLevel),
  92. lodDistance_(lodDistance)
  93. {
  94. }
  95. TechniqueEntry::~TechniqueEntry()
  96. {
  97. }
  98. Material::Material(Context* context) :
  99. Resource(context),
  100. auxViewFrameNumber_(0),
  101. occlusion_(true),
  102. specular_(false)
  103. {
  104. SetNumTechniques(1);
  105. ResetToDefaults();
  106. }
  107. Material::~Material()
  108. {
  109. }
  110. void Material::RegisterObject(Context* context)
  111. {
  112. context->RegisterFactory<Material>();
  113. }
  114. bool Material::Load(Deserializer& source)
  115. {
  116. PROFILE(LoadMaterial);
  117. // In headless mode, do not actually load the material, just return success
  118. Graphics* graphics = GetSubsystem<Graphics>();
  119. if (!graphics)
  120. return true;
  121. SharedPtr<XMLFile> xml(new XMLFile(context_));
  122. if (!xml->Load(source))
  123. return false;
  124. XMLElement rootElem = xml->GetRoot();
  125. return Load(rootElem);
  126. }
  127. bool Material::Save(Serializer& dest) const
  128. {
  129. SharedPtr<XMLFile> xml(new XMLFile(context_));
  130. XMLElement materialElem = xml->CreateRoot("material");
  131. Save(materialElem);
  132. return xml->Save(dest);
  133. }
  134. bool Material::Load(const XMLElement& source)
  135. {
  136. ResetToDefaults();
  137. if (source.IsNull())
  138. {
  139. LOGERROR("Can not load material from null XML element");
  140. return false;
  141. }
  142. ResourceCache* cache = GetSubsystem<ResourceCache>();
  143. XMLElement techniqueElem = source.GetChild("technique");
  144. techniques_.Clear();
  145. while (techniqueElem)
  146. {
  147. Technique* tech = cache->GetResource<Technique>(techniqueElem.GetAttribute("name"));
  148. if (tech)
  149. {
  150. TechniqueEntry newTechnique;
  151. newTechnique.technique_ = tech;
  152. if (techniqueElem.HasAttribute("quality"))
  153. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  154. if (techniqueElem.HasAttribute("loddistance"))
  155. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  156. techniques_.Push(newTechnique);
  157. }
  158. techniqueElem = techniqueElem.GetNext("technique");
  159. }
  160. SortTechniques();
  161. XMLElement textureElem = source.GetChild("texture");
  162. while (textureElem)
  163. {
  164. TextureUnit unit = TU_DIFFUSE;
  165. if (textureElem.HasAttribute("unit"))
  166. {
  167. String unitName = textureElem.GetAttributeLower("unit");
  168. if (unitName.Length() > 1)
  169. {
  170. unit = ParseTextureUnitName(unitName);
  171. if (unit >= MAX_MATERIAL_TEXTURE_UNITS)
  172. LOGERROR("Unknown or illegal texture unit " + unitName);
  173. }
  174. else
  175. unit = (TextureUnit)Clamp(ToInt(unitName), 0, MAX_MATERIAL_TEXTURE_UNITS - 1);
  176. }
  177. if (unit != MAX_MATERIAL_TEXTURE_UNITS)
  178. {
  179. String name = textureElem.GetAttribute("name");
  180. // Detect cube maps by file extension: they are defined by an XML file
  181. if (GetExtension(name) == ".xml")
  182. SetTexture(unit, cache->GetResource<TextureCube>(name));
  183. else
  184. SetTexture(unit, cache->GetResource<Texture2D>(name));
  185. }
  186. textureElem = textureElem.GetNext("texture");
  187. }
  188. XMLElement parameterElem = source.GetChild("parameter");
  189. while (parameterElem)
  190. {
  191. String name = parameterElem.GetAttribute("name");
  192. SetShaderParameter(name, ParseShaderParameterValue(parameterElem.GetAttribute("value")));
  193. parameterElem = parameterElem.GetNext("parameter");
  194. }
  195. XMLElement cullElem = source.GetChild("cull");
  196. if (cullElem)
  197. SetCullMode((CullMode)GetStringListIndex(cullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  198. XMLElement shadowCullElem = source.GetChild("shadowcull");
  199. if (shadowCullElem)
  200. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  201. XMLElement depthBiasElem = source.GetChild("depthbias");
  202. if (depthBiasElem)
  203. SetDepthBias(BiasParameters(depthBiasElem.GetFloat("constant"), depthBiasElem.GetFloat("slopescaled")));
  204. // Calculate memory use
  205. unsigned memoryUse = sizeof(Material);
  206. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  207. memoryUse += MAX_MATERIAL_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
  208. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  209. SetMemoryUse(memoryUse);
  210. CheckOcclusion();
  211. return true;
  212. }
  213. bool Material::Save(XMLElement& dest) const
  214. {
  215. if (dest.IsNull())
  216. {
  217. LOGERROR("Can not save material to null XML element");
  218. return false;
  219. }
  220. // Write techniques
  221. for (unsigned i = 0; i < techniques_.Size(); ++i)
  222. {
  223. const TechniqueEntry& entry = techniques_[i];
  224. if (!entry.technique_)
  225. continue;
  226. XMLElement techniqueElem = dest.CreateChild("technique");
  227. techniqueElem.SetString("name", entry.technique_->GetName());
  228. techniqueElem.SetInt("quality", entry.qualityLevel_);
  229. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  230. }
  231. // Write texture units
  232. for (unsigned j = 0; j < MAX_MATERIAL_TEXTURE_UNITS; ++j)
  233. {
  234. Texture* texture = GetTexture((TextureUnit)j);
  235. if (texture)
  236. {
  237. XMLElement textureElem = dest.CreateChild("texture");
  238. textureElem.SetString("unit", textureUnitNames[j]);
  239. textureElem.SetString("name", texture->GetName());
  240. }
  241. }
  242. // Write shader parameters
  243. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin(); j != shaderParameters_.End(); ++j)
  244. {
  245. XMLElement parameterElem = dest.CreateChild("parameter");
  246. parameterElem.SetString("name", j->second_.name_);
  247. parameterElem.SetVectorVariant("value", j->second_.value_);
  248. }
  249. // Write culling modes
  250. XMLElement cullElem = dest.CreateChild("cull");
  251. cullElem.SetString("value", cullModeNames[cullMode_]);
  252. XMLElement shadowCullElem = dest.CreateChild("shadowcull");
  253. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  254. // Write depth bias
  255. XMLElement depthBiasElem = dest.CreateChild("depthbias");
  256. depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
  257. depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
  258. return true;
  259. }
  260. void Material::SetNumTechniques(unsigned num)
  261. {
  262. if (!num)
  263. return;
  264. techniques_.Resize(num);
  265. }
  266. void Material::SetTechnique(unsigned index, Technique* tech, unsigned qualityLevel, float lodDistance)
  267. {
  268. if (index >= techniques_.Size())
  269. return;
  270. techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
  271. CheckOcclusion();
  272. }
  273. void Material::SetShaderParameter(const String& name, const Variant& value)
  274. {
  275. MaterialShaderParameter newParam;
  276. newParam.name_ = name;
  277. newParam.value_ = value;
  278. StringHash nameHash(name);
  279. shaderParameters_[nameHash] = newParam;
  280. if (nameHash == PSP_MATSPECCOLOR)
  281. {
  282. VariantType type = value.GetType();
  283. if (type == VAR_VECTOR3)
  284. {
  285. const Vector3& vec = value.GetVector3();
  286. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  287. }
  288. else if (type == VAR_VECTOR4)
  289. {
  290. const Vector4& vec = value.GetVector4();
  291. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  292. }
  293. }
  294. }
  295. void Material::SetTexture(TextureUnit unit, Texture* texture)
  296. {
  297. if (unit < MAX_MATERIAL_TEXTURE_UNITS)
  298. textures_[unit] = texture;
  299. }
  300. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  301. {
  302. Matrix3x4 transform(Matrix3x4::IDENTITY);
  303. transform.m00_ = repeat.x_;
  304. transform.m11_ = repeat.y_;
  305. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  306. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  307. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  308. rotationMatrix.m00_ = Cos(rotation);
  309. rotationMatrix.m01_ = Sin(rotation);
  310. rotationMatrix.m10_ = -rotationMatrix.m01_;
  311. rotationMatrix.m11_ = rotationMatrix.m00_;
  312. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  313. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  314. transform = rotationMatrix * transform;
  315. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  316. offsetMatrix.m03_ = offset.x_;
  317. offsetMatrix.m13_ = offset.y_;
  318. transform = offsetMatrix * transform;
  319. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  320. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  321. }
  322. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  323. {
  324. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  325. }
  326. void Material::SetCullMode(CullMode mode)
  327. {
  328. cullMode_ = mode;
  329. }
  330. void Material::SetShadowCullMode(CullMode mode)
  331. {
  332. shadowCullMode_ = mode;
  333. }
  334. void Material::SetDepthBias(const BiasParameters& parameters)
  335. {
  336. depthBias_ = parameters;
  337. depthBias_.Validate();
  338. }
  339. void Material::RemoveShaderParameter(const String& name)
  340. {
  341. StringHash nameHash(name);
  342. shaderParameters_.Erase(nameHash);
  343. if (nameHash == PSP_MATSPECCOLOR)
  344. specular_ = false;
  345. }
  346. void Material::ReleaseShaders()
  347. {
  348. for (unsigned i = 0; i < techniques_.Size(); ++i)
  349. {
  350. Technique* tech = techniques_[i].technique_;
  351. if (tech)
  352. tech->ReleaseShaders();
  353. }
  354. }
  355. SharedPtr<Material> Material::Clone(const String& cloneName) const
  356. {
  357. SharedPtr<Material> ret(new Material(context_));
  358. ret->SetName(cloneName);
  359. ret->techniques_ = techniques_;
  360. ret->shaderParameters_ = shaderParameters_;
  361. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  362. ret->textures_[i] = textures_[i];
  363. ret->occlusion_ = occlusion_;
  364. ret->cullMode_ = cullMode_;
  365. ret->shadowCullMode_ = shadowCullMode_;
  366. return ret;
  367. }
  368. void Material::SortTechniques()
  369. {
  370. Sort(techniques_.Begin(), techniques_.End(), CompareTechniqueEntries);
  371. }
  372. void Material::MarkForAuxView(unsigned frameNumber)
  373. {
  374. auxViewFrameNumber_ = frameNumber;
  375. }
  376. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  377. {
  378. return index < techniques_.Size() ? techniques_[index] : noEntry;
  379. }
  380. Technique* Material::GetTechnique(unsigned index) const
  381. {
  382. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  383. }
  384. Pass* Material::GetPass(unsigned index, StringHash passType) const
  385. {
  386. Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  387. return tech ? tech->GetPass(passType) : 0;
  388. }
  389. Texture* Material::GetTexture(TextureUnit unit) const
  390. {
  391. return unit < MAX_MATERIAL_TEXTURE_UNITS ? textures_[unit] : (Texture*)0;
  392. }
  393. const Variant& Material::GetShaderParameter(const String& name) const
  394. {
  395. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(name);
  396. return i != shaderParameters_.End() ? i->second_.value_ : Variant::EMPTY;
  397. }
  398. String Material::GetTextureUnitName(TextureUnit unit)
  399. {
  400. return textureUnitNames[unit];
  401. }
  402. Variant Material::ParseShaderParameterValue(const String& value)
  403. {
  404. String valueTrimmed = value.Trimmed();
  405. if (valueTrimmed.Length() && IsAlpha(valueTrimmed[0]))
  406. return Variant(ToBool(valueTrimmed));
  407. else
  408. return ToVectorVariant(valueTrimmed);
  409. }
  410. void Material::CheckOcclusion()
  411. {
  412. // Determine occlusion by checking the base pass of each technique
  413. occlusion_ = false;
  414. for (unsigned i = 0; i < techniques_.Size(); ++i)
  415. {
  416. Technique* tech = techniques_[i].technique_;
  417. if (tech)
  418. {
  419. Pass* pass = tech->GetPass(PASS_BASE);
  420. if (pass && pass->GetDepthWrite() && !pass->GetAlphaMask())
  421. occlusion_ = true;
  422. }
  423. }
  424. }
  425. void Material::ResetToDefaults()
  426. {
  427. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  428. textures_[i] = 0;
  429. shaderParameters_.Clear();
  430. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  431. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  432. SetShaderParameter("MatDiffColor", Vector4::ONE);
  433. SetShaderParameter("MatEmissiveColor", Vector3::ZERO);
  434. SetShaderParameter("MatEnvMapColor", Vector3::ONE);
  435. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  436. cullMode_ = CULL_CCW;
  437. shadowCullMode_ = CULL_CCW;
  438. depthBias_ = BiasParameters(0.0f, 0.0f);
  439. }
  440. }