Material.cpp 15 KB

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