Material.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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 "CoreEvents.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 "Scene.h"
  33. #include "SceneEvents.h"
  34. #include "Technique.h"
  35. #include "Texture2D.h"
  36. #include "TextureCube.h"
  37. #include "ValueAnimation.h"
  38. #include "XMLFile.h"
  39. #include "DebugNew.h"
  40. namespace Urho3D
  41. {
  42. extern const char* wrapModeNames[];
  43. static const char* textureUnitNames[] =
  44. {
  45. "diffuse",
  46. "normal",
  47. "specular",
  48. "emissive",
  49. "environment",
  50. "lightramp",
  51. "lightshape",
  52. "shadowmap",
  53. "faceselect",
  54. "indirection",
  55. "depth",
  56. "light",
  57. "volume",
  58. "zone",
  59. 0
  60. };
  61. static const char* cullModeNames[] =
  62. {
  63. "none",
  64. "ccw",
  65. "cw",
  66. 0
  67. };
  68. TextureUnit ParseTextureUnitName(String name)
  69. {
  70. name = name.ToLower().Trimmed();
  71. TextureUnit unit = (TextureUnit)GetStringListIndex(name.CString(), textureUnitNames, MAX_TEXTURE_UNITS);
  72. if (unit == MAX_TEXTURE_UNITS)
  73. {
  74. // Check also for shorthand names
  75. if (name == "diff")
  76. unit = TU_DIFFUSE;
  77. else if (name == "albedo")
  78. unit = TU_DIFFUSE;
  79. else if (name == "norm")
  80. unit = TU_NORMAL;
  81. else if (name == "spec")
  82. unit = TU_SPECULAR;
  83. else if (name == "env")
  84. unit = TU_ENVIRONMENT;
  85. // Finally check for specifying the texture unit directly as a number
  86. else if (name.Length() < 3)
  87. unit = (TextureUnit)Clamp(ToInt(name), 0, MAX_TEXTURE_UNITS);
  88. }
  89. if (unit == MAX_TEXTURE_UNITS)
  90. LOGERROR("Unknown texture unit name " + name);
  91. return unit;
  92. }
  93. static TechniqueEntry noEntry;
  94. bool CompareTechniqueEntries(const TechniqueEntry& lhs, const TechniqueEntry& rhs)
  95. {
  96. if (lhs.lodDistance_ != rhs.lodDistance_)
  97. return lhs.lodDistance_ > rhs.lodDistance_;
  98. else
  99. return lhs.qualityLevel_ > rhs.qualityLevel_;
  100. }
  101. TechniqueEntry::TechniqueEntry() :
  102. qualityLevel_(0),
  103. lodDistance_(0.0f)
  104. {
  105. }
  106. TechniqueEntry::TechniqueEntry(Technique* tech, unsigned qualityLevel, float lodDistance) :
  107. technique_(tech),
  108. qualityLevel_(qualityLevel),
  109. lodDistance_(lodDistance)
  110. {
  111. }
  112. TechniqueEntry::~TechniqueEntry()
  113. {
  114. }
  115. ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(Material* target, const String& name, ValueAnimation* attributeAnimation, WrapMode wrapMode, float speed) :
  116. ValueAnimationInfo(target, attributeAnimation, wrapMode, speed),
  117. name_(name)
  118. {
  119. }
  120. ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(const ShaderParameterAnimationInfo& other) :
  121. ValueAnimationInfo(other),
  122. name_(other.name_)
  123. {
  124. }
  125. ShaderParameterAnimationInfo::~ShaderParameterAnimationInfo()
  126. {
  127. }
  128. void ShaderParameterAnimationInfo::ApplyValue(const Variant& newValue)
  129. {
  130. static_cast<Material*>(target_.Get())->SetShaderParameter(name_, newValue);
  131. }
  132. Material::Material(Context* context) :
  133. Resource(context),
  134. auxViewFrameNumber_(0),
  135. occlusion_(true),
  136. specular_(false),
  137. subscribed_(false)
  138. {
  139. ResetToDefaults();
  140. }
  141. Material::~Material()
  142. {
  143. }
  144. void Material::RegisterObject(Context* context)
  145. {
  146. context->RegisterFactory<Material>();
  147. }
  148. bool Material::BeginLoad(Deserializer& source)
  149. {
  150. // In headless mode, do not actually load the material, just return success
  151. Graphics* graphics = GetSubsystem<Graphics>();
  152. if (!graphics)
  153. return true;
  154. loadXMLFile_ = new XMLFile(context_);
  155. if (loadXMLFile_->Load(source))
  156. {
  157. // If async loading, scan the XML content beforehand for technique & texture resources
  158. // and request them to also be loaded. Can not do anything else at this point
  159. if (GetAsyncLoadState() == ASYNC_LOADING)
  160. {
  161. ResourceCache* cache = GetSubsystem<ResourceCache>();
  162. XMLElement rootElem = loadXMLFile_->GetRoot();
  163. XMLElement techniqueElem = rootElem.GetChild("technique");
  164. while (techniqueElem)
  165. {
  166. cache->BackgroundLoadResource<Technique>(techniqueElem.GetAttribute("name"), true, this);
  167. techniqueElem = techniqueElem.GetNext("technique");
  168. }
  169. XMLElement textureElem = rootElem.GetChild("texture");
  170. while (textureElem)
  171. {
  172. String name = textureElem.GetAttribute("name");
  173. // Detect cube maps by file extension: they are defined by an XML file
  174. /// \todo Differentiate with 3D textures by actually reading the XML content
  175. if (GetExtension(name) == ".xml")
  176. cache->BackgroundLoadResource<TextureCube>(name, true, this);
  177. else
  178. cache->BackgroundLoadResource<Texture2D>(name, true, this);
  179. textureElem = textureElem.GetNext("texture");
  180. }
  181. }
  182. return true;
  183. }
  184. else
  185. {
  186. ResetToDefaults();
  187. loadXMLFile_.Reset();
  188. return false;
  189. }
  190. }
  191. bool Material::EndLoad()
  192. {
  193. // In headless mode, do not actually load the material, just return success
  194. Graphics* graphics = GetSubsystem<Graphics>();
  195. if (!graphics)
  196. return true;
  197. bool success = false;
  198. if (loadXMLFile_)
  199. {
  200. // If async loading, get the techniques / textures which should be ready now
  201. XMLElement rootElem = loadXMLFile_->GetRoot();
  202. success = Load(rootElem);
  203. }
  204. loadXMLFile_.Reset();
  205. return success;
  206. }
  207. bool Material::Save(Serializer& dest) const
  208. {
  209. SharedPtr<XMLFile> xml(new XMLFile(context_));
  210. XMLElement materialElem = xml->CreateRoot("material");
  211. Save(materialElem);
  212. return xml->Save(dest);
  213. }
  214. bool Material::Load(const XMLElement& source)
  215. {
  216. ResetToDefaults();
  217. if (source.IsNull())
  218. {
  219. LOGERROR("Can not load material from null XML element");
  220. return false;
  221. }
  222. ResourceCache* cache = GetSubsystem<ResourceCache>();
  223. XMLElement techniqueElem = source.GetChild("technique");
  224. techniques_.Clear();
  225. while (techniqueElem)
  226. {
  227. Technique* tech = cache->GetResource<Technique>(techniqueElem.GetAttribute("name"));
  228. if (tech)
  229. {
  230. TechniqueEntry newTechnique;
  231. newTechnique.technique_ = tech;
  232. if (techniqueElem.HasAttribute("quality"))
  233. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  234. if (techniqueElem.HasAttribute("loddistance"))
  235. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  236. techniques_.Push(newTechnique);
  237. }
  238. techniqueElem = techniqueElem.GetNext("technique");
  239. }
  240. SortTechniques();
  241. XMLElement textureElem = source.GetChild("texture");
  242. while (textureElem)
  243. {
  244. TextureUnit unit = TU_DIFFUSE;
  245. if (textureElem.HasAttribute("unit"))
  246. unit = ParseTextureUnitName(textureElem.GetAttribute("unit"));
  247. if (unit < MAX_MATERIAL_TEXTURE_UNITS)
  248. {
  249. String name = textureElem.GetAttribute("name");
  250. // Detect cube maps by file extension: they are defined by an XML file
  251. /// \todo Differentiate with 3D textures by actually reading the XML content
  252. if (GetExtension(name) == ".xml")
  253. SetTexture(unit, cache->GetResource<TextureCube>(name));
  254. else
  255. SetTexture(unit, cache->GetResource<Texture2D>(name));
  256. }
  257. textureElem = textureElem.GetNext("texture");
  258. }
  259. XMLElement parameterElem = source.GetChild("parameter");
  260. while (parameterElem)
  261. {
  262. String name = parameterElem.GetAttribute("name");
  263. SetShaderParameter(name, ParseShaderParameterValue(parameterElem.GetAttribute("value")));
  264. parameterElem = parameterElem.GetNext("parameter");
  265. }
  266. XMLElement parameterAnimationElem = source.GetChild("parameteranimation");
  267. while (parameterAnimationElem)
  268. {
  269. String name = parameterAnimationElem.GetAttribute("name");
  270. SharedPtr<ValueAnimation> animation(new ValueAnimation(context_));
  271. if (!animation->LoadXML(parameterAnimationElem))
  272. {
  273. LOGERROR("Could not load parameter animation");
  274. return false;
  275. }
  276. String wrapModeString = parameterAnimationElem.GetAttribute("wrapmode");
  277. WrapMode wrapMode = WM_LOOP;
  278. for (int i = 0; i <= WM_CLAMP; ++i)
  279. {
  280. if (wrapModeString == wrapModeNames[i])
  281. {
  282. wrapMode = (WrapMode)i;
  283. break;
  284. }
  285. }
  286. float speed = parameterAnimationElem.GetFloat("speed");
  287. SetShaderParameterAnimation(name, animation, wrapMode, speed);
  288. parameterAnimationElem = parameterAnimationElem.GetNext("parameteranimation");
  289. }
  290. XMLElement cullElem = source.GetChild("cull");
  291. if (cullElem)
  292. SetCullMode((CullMode)GetStringListIndex(cullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  293. XMLElement shadowCullElem = source.GetChild("shadowcull");
  294. if (shadowCullElem)
  295. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  296. XMLElement depthBiasElem = source.GetChild("depthbias");
  297. if (depthBiasElem)
  298. SetDepthBias(BiasParameters(depthBiasElem.GetFloat("constant"), depthBiasElem.GetFloat("slopescaled")));
  299. RefreshMemoryUse();
  300. CheckOcclusion();
  301. return true;
  302. }
  303. bool Material::Save(XMLElement& dest) const
  304. {
  305. if (dest.IsNull())
  306. {
  307. LOGERROR("Can not save material to null XML element");
  308. return false;
  309. }
  310. // Write techniques
  311. for (unsigned i = 0; i < techniques_.Size(); ++i)
  312. {
  313. const TechniqueEntry& entry = techniques_[i];
  314. if (!entry.technique_)
  315. continue;
  316. XMLElement techniqueElem = dest.CreateChild("technique");
  317. techniqueElem.SetString("name", entry.technique_->GetName());
  318. techniqueElem.SetInt("quality", entry.qualityLevel_);
  319. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  320. }
  321. // Write texture units
  322. for (unsigned j = 0; j < MAX_MATERIAL_TEXTURE_UNITS; ++j)
  323. {
  324. Texture* texture = GetTexture((TextureUnit)j);
  325. if (texture)
  326. {
  327. XMLElement textureElem = dest.CreateChild("texture");
  328. textureElem.SetString("unit", textureUnitNames[j]);
  329. textureElem.SetString("name", texture->GetName());
  330. }
  331. }
  332. // Write shader parameters
  333. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin(); j != shaderParameters_.End(); ++j)
  334. {
  335. XMLElement parameterElem = dest.CreateChild("parameter");
  336. parameterElem.SetString("name", j->second_.name_);
  337. parameterElem.SetVectorVariant("value", j->second_.value_);
  338. }
  339. // Write shader parameter animations
  340. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator j = shaderParameterAnimationInfos_.Begin(); j != shaderParameterAnimationInfos_.End(); ++j)
  341. {
  342. ShaderParameterAnimationInfo* info = j->second_;
  343. XMLElement parameterAnimationElem = dest.CreateChild("parameteranimation");
  344. parameterAnimationElem.SetString("name", info->GetName());
  345. if (!info->GetAnimation()->SaveXML(parameterAnimationElem))
  346. return false;
  347. parameterAnimationElem.SetAttribute("wrapmode", wrapModeNames[info->GetWrapMode()]);
  348. parameterAnimationElem.SetFloat("speed", info->GetSpeed());
  349. }
  350. // Write culling modes
  351. XMLElement cullElem = dest.CreateChild("cull");
  352. cullElem.SetString("value", cullModeNames[cullMode_]);
  353. XMLElement shadowCullElem = dest.CreateChild("shadowcull");
  354. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  355. // Write depth bias
  356. XMLElement depthBiasElem = dest.CreateChild("depthbias");
  357. depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
  358. depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
  359. return true;
  360. }
  361. void Material::SetNumTechniques(unsigned num)
  362. {
  363. if (!num)
  364. return;
  365. techniques_.Resize(num);
  366. RefreshMemoryUse();
  367. }
  368. void Material::SetTechnique(unsigned index, Technique* tech, unsigned qualityLevel, float lodDistance)
  369. {
  370. if (index >= techniques_.Size())
  371. return;
  372. techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
  373. CheckOcclusion();
  374. }
  375. void Material::SetShaderParameter(const String& name, const Variant& value)
  376. {
  377. MaterialShaderParameter newParam;
  378. newParam.name_ = name;
  379. newParam.value_ = value;
  380. StringHash nameHash(name);
  381. shaderParameters_[nameHash] = newParam;
  382. if (nameHash == PSP_MATSPECCOLOR)
  383. {
  384. VariantType type = value.GetType();
  385. if (type == VAR_VECTOR3)
  386. {
  387. const Vector3& vec = value.GetVector3();
  388. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  389. }
  390. else if (type == VAR_VECTOR4)
  391. {
  392. const Vector4& vec = value.GetVector4();
  393. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  394. }
  395. }
  396. RefreshMemoryUse();
  397. }
  398. void Material::SetShaderParameterAnimation(const String& name, ValueAnimation* animation, WrapMode wrapMode, float speed)
  399. {
  400. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  401. if (animation)
  402. {
  403. if (info && info->GetAnimation() == animation)
  404. {
  405. info->SetWrapMode(wrapMode);
  406. info->SetSpeed(speed);
  407. return;
  408. }
  409. if (shaderParameters_.Find(name) == shaderParameters_.End())
  410. {
  411. LOGERROR(GetName() + " has no shader parameter: " + name);
  412. return;
  413. }
  414. StringHash nameHash(name);
  415. shaderParameterAnimationInfos_[nameHash] = new ShaderParameterAnimationInfo(this, name, animation, wrapMode, speed);
  416. UpdateEventSubscription();
  417. }
  418. else
  419. {
  420. if (info)
  421. {
  422. StringHash nameHash(name);
  423. shaderParameterAnimationInfos_.Erase(nameHash);
  424. UpdateEventSubscription();
  425. }
  426. }
  427. }
  428. void Material::SetShaderParameterAnimationWrapMode(const String& name, WrapMode wrapMode)
  429. {
  430. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  431. if (info)
  432. info->SetWrapMode(wrapMode);
  433. }
  434. void Material::SetShaderParameterAnimationSpeed(const String& name, float speed)
  435. {
  436. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  437. if (info)
  438. info->SetSpeed(speed);
  439. }
  440. void Material::SetTexture(TextureUnit unit, Texture* texture)
  441. {
  442. if (unit < MAX_MATERIAL_TEXTURE_UNITS)
  443. textures_[unit] = texture;
  444. }
  445. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  446. {
  447. Matrix3x4 transform(Matrix3x4::IDENTITY);
  448. transform.m00_ = repeat.x_;
  449. transform.m11_ = repeat.y_;
  450. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  451. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  452. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  453. rotationMatrix.m00_ = Cos(rotation);
  454. rotationMatrix.m01_ = Sin(rotation);
  455. rotationMatrix.m10_ = -rotationMatrix.m01_;
  456. rotationMatrix.m11_ = rotationMatrix.m00_;
  457. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  458. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  459. transform = rotationMatrix * transform;
  460. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  461. offsetMatrix.m03_ = offset.x_;
  462. offsetMatrix.m13_ = offset.y_;
  463. transform = offsetMatrix * transform;
  464. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  465. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  466. }
  467. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  468. {
  469. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  470. }
  471. void Material::SetCullMode(CullMode mode)
  472. {
  473. cullMode_ = mode;
  474. }
  475. void Material::SetShadowCullMode(CullMode mode)
  476. {
  477. shadowCullMode_ = mode;
  478. }
  479. void Material::SetDepthBias(const BiasParameters& parameters)
  480. {
  481. depthBias_ = parameters;
  482. depthBias_.Validate();
  483. }
  484. void Material::SetScene(Scene* scene)
  485. {
  486. UnsubscribeFromEvent(E_UPDATE);
  487. UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
  488. subscribed_ = false;
  489. scene_ = scene;
  490. UpdateEventSubscription();
  491. }
  492. void Material::RemoveShaderParameter(const String& name)
  493. {
  494. StringHash nameHash(name);
  495. shaderParameters_.Erase(nameHash);
  496. if (nameHash == PSP_MATSPECCOLOR)
  497. specular_ = false;
  498. RefreshMemoryUse();
  499. }
  500. void Material::ReleaseShaders()
  501. {
  502. for (unsigned i = 0; i < techniques_.Size(); ++i)
  503. {
  504. Technique* tech = techniques_[i].technique_;
  505. if (tech)
  506. tech->ReleaseShaders();
  507. }
  508. }
  509. SharedPtr<Material> Material::Clone(const String& cloneName) const
  510. {
  511. SharedPtr<Material> ret(new Material(context_));
  512. ret->SetName(cloneName);
  513. ret->techniques_ = techniques_;
  514. ret->shaderParameters_ = shaderParameters_;
  515. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  516. ret->textures_[i] = textures_[i];
  517. ret->occlusion_ = occlusion_;
  518. ret->specular_ = specular_;
  519. ret->cullMode_ = cullMode_;
  520. ret->shadowCullMode_ = shadowCullMode_;
  521. ret->RefreshMemoryUse();
  522. return ret;
  523. }
  524. void Material::SortTechniques()
  525. {
  526. Sort(techniques_.Begin(), techniques_.End(), CompareTechniqueEntries);
  527. }
  528. void Material::MarkForAuxView(unsigned frameNumber)
  529. {
  530. auxViewFrameNumber_ = frameNumber;
  531. }
  532. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  533. {
  534. return index < techniques_.Size() ? techniques_[index] : noEntry;
  535. }
  536. Technique* Material::GetTechnique(unsigned index) const
  537. {
  538. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  539. }
  540. Pass* Material::GetPass(unsigned index, StringHash passType) const
  541. {
  542. Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  543. return tech ? tech->GetPass(passType) : 0;
  544. }
  545. Texture* Material::GetTexture(TextureUnit unit) const
  546. {
  547. return unit < MAX_MATERIAL_TEXTURE_UNITS ? textures_[unit] : (Texture*)0;
  548. }
  549. const Variant& Material::GetShaderParameter(const String& name) const
  550. {
  551. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(name);
  552. return i != shaderParameters_.End() ? i->second_.value_ : Variant::EMPTY;
  553. }
  554. ValueAnimation* Material::GetShaderParameterAnimation(const String& name) const
  555. {
  556. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  557. return info == 0 ? 0 : info->GetAnimation();
  558. }
  559. WrapMode Material::GetShaderParameterAnimationWrapMode(const String& name) const
  560. {
  561. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  562. return info == 0 ? WM_LOOP : info->GetWrapMode();
  563. }
  564. float Material::GetShaderParameterAnimationSpeed(const String& name) const
  565. {
  566. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  567. return info == 0 ? 0 : info->GetSpeed();
  568. }
  569. Scene* Material::GetScene() const
  570. {
  571. return scene_;
  572. }
  573. String Material::GetTextureUnitName(TextureUnit unit)
  574. {
  575. return textureUnitNames[unit];
  576. }
  577. Variant Material::ParseShaderParameterValue(const String& value)
  578. {
  579. String valueTrimmed = value.Trimmed();
  580. if (valueTrimmed.Length() && IsAlpha(valueTrimmed[0]))
  581. return Variant(ToBool(valueTrimmed));
  582. else
  583. return ToVectorVariant(valueTrimmed);
  584. }
  585. void Material::CheckOcclusion()
  586. {
  587. // Determine occlusion by checking the base pass of each technique
  588. occlusion_ = false;
  589. for (unsigned i = 0; i < techniques_.Size(); ++i)
  590. {
  591. Technique* tech = techniques_[i].technique_;
  592. if (tech)
  593. {
  594. Pass* pass = tech->GetPass(PASS_BASE);
  595. if (pass && pass->GetDepthWrite() && !pass->GetAlphaMask())
  596. occlusion_ = true;
  597. }
  598. }
  599. }
  600. void Material::ResetToDefaults()
  601. {
  602. // Needs to be a no-op when async loading, as this does a GetResource() which is not allowed from worker threads
  603. if (!Thread::IsMainThread())
  604. return;
  605. SetNumTechniques(1);
  606. SetTechnique(0, GetSubsystem<ResourceCache>()->GetResource<Technique>("Techniques/NoTexture.xml"));
  607. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  608. textures_[i] = 0;
  609. shaderParameters_.Clear();
  610. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  611. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  612. SetShaderParameter("MatDiffColor", Vector4::ONE);
  613. SetShaderParameter("MatEmissiveColor", Vector3::ZERO);
  614. SetShaderParameter("MatEnvMapColor", Vector3::ONE);
  615. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  616. cullMode_ = CULL_CCW;
  617. shadowCullMode_ = CULL_CCW;
  618. depthBias_ = BiasParameters(0.0f, 0.0f);
  619. RefreshMemoryUse();
  620. }
  621. void Material::RefreshMemoryUse()
  622. {
  623. unsigned memoryUse = sizeof(Material);
  624. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  625. memoryUse += MAX_MATERIAL_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
  626. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  627. SetMemoryUse(memoryUse);
  628. }
  629. ShaderParameterAnimationInfo* Material::GetShaderParameterAnimationInfo(const String& name) const
  630. {
  631. StringHash nameHash(name);
  632. HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Find(nameHash);
  633. if (i == shaderParameterAnimationInfos_.End())
  634. return 0;
  635. return i->second_;
  636. }
  637. void Material::UpdateEventSubscription()
  638. {
  639. if (shaderParameterAnimationInfos_.Size() && !subscribed_)
  640. {
  641. if (scene_)
  642. SubscribeToEvent(scene_, E_ATTRIBUTEANIMATIONUPDATE, HANDLER(Material, HandleAttributeAnimationUpdate));
  643. else
  644. SubscribeToEvent(E_UPDATE, HANDLER(Material, HandleAttributeAnimationUpdate));
  645. subscribed_ = true;
  646. }
  647. else if (subscribed_)
  648. {
  649. UnsubscribeFromEvent(E_UPDATE);
  650. UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
  651. subscribed_ = false;
  652. }
  653. }
  654. void Material::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  655. {
  656. // Timestep parameter is same no matter what event is being listened to
  657. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  658. Vector<String> finishedNames;
  659. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Begin(); i != shaderParameterAnimationInfos_.End(); ++i)
  660. {
  661. if (i->second_->Update(timeStep))
  662. finishedNames.Push(i->second_->GetName());
  663. }
  664. // Remove finished animations
  665. for (unsigned i = 0; i < finishedNames.Size(); ++i)
  666. SetShaderParameterAnimation(finishedNames[i], 0);
  667. }
  668. }