2
0

Material.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. //
  2. // Copyright (c) 2008-2014 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. "volume",
  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. RefreshMemoryUse();
  108. }
  109. Material::~Material()
  110. {
  111. }
  112. void Material::RegisterObject(Context* context)
  113. {
  114. context->RegisterFactory<Material>();
  115. }
  116. bool Material::Load(Deserializer& source)
  117. {
  118. PROFILE(LoadMaterial);
  119. // In headless mode, do not actually load the material, just return success
  120. Graphics* graphics = GetSubsystem<Graphics>();
  121. if (!graphics)
  122. return true;
  123. SharedPtr<XMLFile> xml(new XMLFile(context_));
  124. if (!xml->Load(source))
  125. return false;
  126. XMLElement rootElem = xml->GetRoot();
  127. return Load(rootElem);
  128. }
  129. bool Material::Save(Serializer& dest) const
  130. {
  131. SharedPtr<XMLFile> xml(new XMLFile(context_));
  132. XMLElement materialElem = xml->CreateRoot("material");
  133. Save(materialElem);
  134. return xml->Save(dest);
  135. }
  136. bool Material::Load(const XMLElement& source)
  137. {
  138. ResetToDefaults();
  139. if (source.IsNull())
  140. {
  141. LOGERROR("Can not load material from null XML element");
  142. return false;
  143. }
  144. ResourceCache* cache = GetSubsystem<ResourceCache>();
  145. XMLElement techniqueElem = source.GetChild("technique");
  146. techniques_.Clear();
  147. while (techniqueElem)
  148. {
  149. Technique* tech = cache->GetResource<Technique>(techniqueElem.GetAttribute("name"));
  150. if (tech)
  151. {
  152. TechniqueEntry newTechnique;
  153. newTechnique.technique_ = tech;
  154. if (techniqueElem.HasAttribute("quality"))
  155. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  156. if (techniqueElem.HasAttribute("loddistance"))
  157. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  158. techniques_.Push(newTechnique);
  159. }
  160. techniqueElem = techniqueElem.GetNext("technique");
  161. }
  162. SortTechniques();
  163. XMLElement textureElem = source.GetChild("texture");
  164. while (textureElem)
  165. {
  166. TextureUnit unit = TU_DIFFUSE;
  167. if (textureElem.HasAttribute("unit"))
  168. {
  169. String unitName = textureElem.GetAttributeLower("unit");
  170. if (unitName.Length() > 1)
  171. {
  172. unit = ParseTextureUnitName(unitName);
  173. if (unit >= MAX_MATERIAL_TEXTURE_UNITS)
  174. LOGERROR("Unknown or illegal texture unit " + unitName);
  175. }
  176. else
  177. unit = (TextureUnit)Clamp(ToInt(unitName), 0, MAX_MATERIAL_TEXTURE_UNITS - 1);
  178. }
  179. if (unit != MAX_MATERIAL_TEXTURE_UNITS)
  180. {
  181. String name = textureElem.GetAttribute("name");
  182. // Detect cube maps by file extension: they are defined by an XML file
  183. if (GetExtension(name) == ".xml")
  184. SetTexture(unit, cache->GetResource<TextureCube>(name));
  185. else
  186. SetTexture(unit, cache->GetResource<Texture2D>(name));
  187. }
  188. textureElem = textureElem.GetNext("texture");
  189. }
  190. XMLElement parameterElem = source.GetChild("parameter");
  191. while (parameterElem)
  192. {
  193. String name = parameterElem.GetAttribute("name");
  194. SetShaderParameter(name, ParseShaderParameterValue(parameterElem.GetAttribute("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. RefreshMemoryUse();
  208. CheckOcclusion();
  209. return true;
  210. }
  211. bool Material::Save(XMLElement& dest) const
  212. {
  213. if (dest.IsNull())
  214. {
  215. LOGERROR("Can not save material to null XML element");
  216. return false;
  217. }
  218. // Write techniques
  219. for (unsigned i = 0; i < techniques_.Size(); ++i)
  220. {
  221. const TechniqueEntry& entry = techniques_[i];
  222. if (!entry.technique_)
  223. continue;
  224. XMLElement techniqueElem = dest.CreateChild("technique");
  225. techniqueElem.SetString("name", entry.technique_->GetName());
  226. techniqueElem.SetInt("quality", entry.qualityLevel_);
  227. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  228. }
  229. // Write texture units
  230. for (unsigned j = 0; j < MAX_MATERIAL_TEXTURE_UNITS; ++j)
  231. {
  232. Texture* texture = GetTexture((TextureUnit)j);
  233. if (texture)
  234. {
  235. XMLElement textureElem = dest.CreateChild("texture");
  236. textureElem.SetString("unit", textureUnitNames[j]);
  237. textureElem.SetString("name", texture->GetName());
  238. }
  239. }
  240. // Write shader parameters
  241. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin(); j != shaderParameters_.End(); ++j)
  242. {
  243. XMLElement parameterElem = dest.CreateChild("parameter");
  244. parameterElem.SetString("name", j->second_.name_);
  245. parameterElem.SetVectorVariant("value", j->second_.value_);
  246. }
  247. // Write culling modes
  248. XMLElement cullElem = dest.CreateChild("cull");
  249. cullElem.SetString("value", cullModeNames[cullMode_]);
  250. XMLElement shadowCullElem = dest.CreateChild("shadowcull");
  251. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  252. // Write depth bias
  253. XMLElement depthBiasElem = dest.CreateChild("depthbias");
  254. depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
  255. depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
  256. return true;
  257. }
  258. void Material::SetNumTechniques(unsigned num)
  259. {
  260. if (!num)
  261. return;
  262. techniques_.Resize(num);
  263. RefreshMemoryUse();
  264. }
  265. void Material::SetTechnique(unsigned index, Technique* tech, unsigned qualityLevel, float lodDistance)
  266. {
  267. if (index >= techniques_.Size())
  268. return;
  269. techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
  270. CheckOcclusion();
  271. }
  272. void Material::SetShaderParameter(const String& name, const Variant& value)
  273. {
  274. MaterialShaderParameter newParam;
  275. newParam.name_ = name;
  276. newParam.value_ = value;
  277. StringHash nameHash(name);
  278. shaderParameters_[nameHash] = newParam;
  279. if (nameHash == PSP_MATSPECCOLOR)
  280. {
  281. VariantType type = value.GetType();
  282. if (type == VAR_VECTOR3)
  283. {
  284. const Vector3& vec = value.GetVector3();
  285. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  286. }
  287. else if (type == VAR_VECTOR4)
  288. {
  289. const Vector4& vec = value.GetVector4();
  290. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  291. }
  292. }
  293. RefreshMemoryUse();
  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. RefreshMemoryUse();
  346. }
  347. void Material::ReleaseShaders()
  348. {
  349. for (unsigned i = 0; i < techniques_.Size(); ++i)
  350. {
  351. Technique* tech = techniques_[i].technique_;
  352. if (tech)
  353. tech->ReleaseShaders();
  354. }
  355. }
  356. SharedPtr<Material> Material::Clone(const String& cloneName) const
  357. {
  358. SharedPtr<Material> ret(new Material(context_));
  359. ret->SetName(cloneName);
  360. ret->techniques_ = techniques_;
  361. ret->shaderParameters_ = shaderParameters_;
  362. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  363. ret->textures_[i] = textures_[i];
  364. ret->occlusion_ = occlusion_;
  365. ret->specular_ = specular_;
  366. ret->cullMode_ = cullMode_;
  367. ret->shadowCullMode_ = shadowCullMode_;
  368. ret->RefreshMemoryUse();
  369. return ret;
  370. }
  371. void Material::SortTechniques()
  372. {
  373. Sort(techniques_.Begin(), techniques_.End(), CompareTechniqueEntries);
  374. }
  375. void Material::MarkForAuxView(unsigned frameNumber)
  376. {
  377. auxViewFrameNumber_ = frameNumber;
  378. }
  379. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  380. {
  381. return index < techniques_.Size() ? techniques_[index] : noEntry;
  382. }
  383. Technique* Material::GetTechnique(unsigned index) const
  384. {
  385. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  386. }
  387. Pass* Material::GetPass(unsigned index, StringHash passType) const
  388. {
  389. Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  390. return tech ? tech->GetPass(passType) : 0;
  391. }
  392. Texture* Material::GetTexture(TextureUnit unit) const
  393. {
  394. return unit < MAX_MATERIAL_TEXTURE_UNITS ? textures_[unit] : (Texture*)0;
  395. }
  396. const Variant& Material::GetShaderParameter(const String& name) const
  397. {
  398. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(name);
  399. return i != shaderParameters_.End() ? i->second_.value_ : Variant::EMPTY;
  400. }
  401. String Material::GetTextureUnitName(TextureUnit unit)
  402. {
  403. return textureUnitNames[unit];
  404. }
  405. Variant Material::ParseShaderParameterValue(const String& value)
  406. {
  407. String valueTrimmed = value.Trimmed();
  408. if (valueTrimmed.Length() && IsAlpha(valueTrimmed[0]))
  409. return Variant(ToBool(valueTrimmed));
  410. else
  411. return ToVectorVariant(valueTrimmed);
  412. }
  413. void Material::CheckOcclusion()
  414. {
  415. // Determine occlusion by checking the base pass of each technique
  416. occlusion_ = false;
  417. for (unsigned i = 0; i < techniques_.Size(); ++i)
  418. {
  419. Technique* tech = techniques_[i].technique_;
  420. if (tech)
  421. {
  422. Pass* pass = tech->GetPass(PASS_BASE);
  423. if (pass && pass->GetDepthWrite() && !pass->GetAlphaMask())
  424. occlusion_ = true;
  425. }
  426. }
  427. }
  428. void Material::ResetToDefaults()
  429. {
  430. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  431. textures_[i] = 0;
  432. shaderParameters_.Clear();
  433. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  434. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  435. SetShaderParameter("MatDiffColor", Vector4::ONE);
  436. SetShaderParameter("MatEmissiveColor", Vector3::ZERO);
  437. SetShaderParameter("MatEnvMapColor", Vector3::ONE);
  438. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  439. cullMode_ = CULL_CCW;
  440. shadowCullMode_ = CULL_CCW;
  441. depthBias_ = BiasParameters(0.0f, 0.0f);
  442. }
  443. void Material::RefreshMemoryUse()
  444. {
  445. unsigned memoryUse = sizeof(Material);
  446. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  447. memoryUse += MAX_MATERIAL_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
  448. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  449. SetMemoryUse(memoryUse);
  450. }
  451. }