Material.cpp 26 KB

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