Material.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  1. //
  2. // Copyright (c) 2008-2016 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 "../Core/Profiler.h"
  26. #include "../Graphics/Graphics.h"
  27. #include "../Graphics/Material.h"
  28. #include "../Graphics/Renderer.h"
  29. #include "../Graphics/Technique.h"
  30. #include "../Graphics/Texture2D.h"
  31. #include "../Graphics/Texture2DArray.h"
  32. #include "../Graphics/Texture3D.h"
  33. #include "../Graphics/TextureCube.h"
  34. #include "../IO/FileSystem.h"
  35. #include "../IO/Log.h"
  36. #include "../IO/VectorBuffer.h"
  37. #include "../Resource/ResourceCache.h"
  38. #include "../Resource/XMLFile.h"
  39. #include "../Resource/JSONFile.h"
  40. #include "../Scene/Scene.h"
  41. #include "../Scene/SceneEvents.h"
  42. #include "../Scene/ValueAnimation.h"
  43. #include "../DebugNew.h"
  44. namespace Urho3D
  45. {
  46. extern const char* wrapModeNames[];
  47. static const char* textureUnitNames[] =
  48. {
  49. "diffuse",
  50. "normal",
  51. "specular",
  52. "emissive",
  53. "environment",
  54. #ifdef DESKTOP_GRAPHICS
  55. "volume",
  56. "custom1",
  57. "custom2",
  58. "lightramp",
  59. "lightshape",
  60. "shadowmap",
  61. "faceselect",
  62. "indirection",
  63. "depth",
  64. "light",
  65. "zone",
  66. 0
  67. #else
  68. "lightramp",
  69. "lightshape",
  70. "shadowmap",
  71. 0
  72. #endif
  73. };
  74. static const char* cullModeNames[] =
  75. {
  76. "none",
  77. "ccw",
  78. "cw",
  79. 0
  80. };
  81. static const char* fillModeNames[] =
  82. {
  83. "solid",
  84. "wireframe",
  85. "point",
  86. 0
  87. };
  88. TextureUnit ParseTextureUnitName(String name)
  89. {
  90. name = name.ToLower().Trimmed();
  91. TextureUnit unit = (TextureUnit)GetStringListIndex(name.CString(), textureUnitNames, MAX_TEXTURE_UNITS);
  92. if (unit == MAX_TEXTURE_UNITS)
  93. {
  94. // Check also for shorthand names
  95. if (name == "diff")
  96. unit = TU_DIFFUSE;
  97. else if (name == "albedo")
  98. unit = TU_DIFFUSE;
  99. else if (name == "norm")
  100. unit = TU_NORMAL;
  101. else if (name == "spec")
  102. unit = TU_SPECULAR;
  103. else if (name == "env")
  104. unit = TU_ENVIRONMENT;
  105. // Finally check for specifying the texture unit directly as a number
  106. else if (name.Length() < 3)
  107. unit = (TextureUnit)Clamp(ToInt(name), 0, MAX_TEXTURE_UNITS - 1);
  108. }
  109. if (unit == MAX_TEXTURE_UNITS)
  110. URHO3D_LOGERROR("Unknown texture unit name " + name);
  111. return unit;
  112. }
  113. StringHash ParseTextureTypeName(String name)
  114. {
  115. name = name.ToLower().Trimmed();
  116. if (name == "texture")
  117. return Texture2D::GetTypeStatic();
  118. else if (name == "cubemap")
  119. return TextureCube::GetTypeStatic();
  120. else if (name == "texture3d")
  121. return Texture3D::GetTypeStatic();
  122. else if (name == "texturearray")
  123. return Texture2DArray::GetTypeStatic();
  124. return 0;
  125. }
  126. StringHash ParseTextureTypeXml(ResourceCache* cache, String filename)
  127. {
  128. StringHash type = 0;
  129. if (!cache)
  130. return type;
  131. SharedPtr<File> texXmlFile = cache->GetFile(filename, false);
  132. if (texXmlFile.NotNull())
  133. {
  134. SharedPtr<XMLFile> texXml(new XMLFile(cache->GetContext()));
  135. if (texXml->Load(*texXmlFile))
  136. type = ParseTextureTypeName(texXml->GetRoot().GetName());
  137. }
  138. return type;
  139. }
  140. static TechniqueEntry noEntry;
  141. bool CompareTechniqueEntries(const TechniqueEntry& lhs, const TechniqueEntry& rhs)
  142. {
  143. if (lhs.lodDistance_ != rhs.lodDistance_)
  144. return lhs.lodDistance_ > rhs.lodDistance_;
  145. else
  146. return lhs.qualityLevel_ > rhs.qualityLevel_;
  147. }
  148. TechniqueEntry::TechniqueEntry() :
  149. qualityLevel_(0),
  150. lodDistance_(0.0f)
  151. {
  152. }
  153. TechniqueEntry::TechniqueEntry(Technique* tech, unsigned qualityLevel, float lodDistance) :
  154. technique_(tech),
  155. qualityLevel_(qualityLevel),
  156. lodDistance_(lodDistance)
  157. {
  158. }
  159. TechniqueEntry::~TechniqueEntry()
  160. {
  161. }
  162. ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(Material* target, const String& name, ValueAnimation* attributeAnimation,
  163. WrapMode wrapMode, float speed) :
  164. ValueAnimationInfo(target, attributeAnimation, wrapMode, speed),
  165. name_(name)
  166. {
  167. }
  168. ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(const ShaderParameterAnimationInfo& other) :
  169. ValueAnimationInfo(other),
  170. name_(other.name_)
  171. {
  172. }
  173. ShaderParameterAnimationInfo::~ShaderParameterAnimationInfo()
  174. {
  175. }
  176. void ShaderParameterAnimationInfo::ApplyValue(const Variant& newValue)
  177. {
  178. static_cast<Material*>(target_.Get())->SetShaderParameter(name_, newValue);
  179. }
  180. Material::Material(Context* context) :
  181. Resource(context),
  182. auxViewFrameNumber_(0),
  183. shaderParameterHash_(0),
  184. occlusion_(true),
  185. specular_(false),
  186. subscribed_(false),
  187. batchedParameterUpdate_(false)
  188. {
  189. ResetToDefaults();
  190. }
  191. Material::~Material()
  192. {
  193. }
  194. void Material::RegisterObject(Context* context)
  195. {
  196. context->RegisterFactory<Material>();
  197. }
  198. bool Material::BeginLoad(Deserializer& source)
  199. {
  200. // In headless mode, do not actually load the material, just return success
  201. Graphics* graphics = GetSubsystem<Graphics>();
  202. if (!graphics)
  203. return true;
  204. String extension = GetExtension(source.GetName());
  205. bool success = false;
  206. if (extension == ".xml")
  207. {
  208. success = BeginLoadXML(source);
  209. if (!success)
  210. success = BeginLoadJSON(source);
  211. if (success)
  212. return true;
  213. }
  214. else // Load JSON file
  215. {
  216. success = BeginLoadJSON(source);
  217. if (!success)
  218. success = BeginLoadXML(source);
  219. if (success)
  220. return true;
  221. }
  222. // All loading failed
  223. ResetToDefaults();
  224. loadJSONFile_.Reset();
  225. return false;
  226. }
  227. bool Material::EndLoad()
  228. {
  229. // In headless mode, do not actually load the material, just return success
  230. Graphics* graphics = GetSubsystem<Graphics>();
  231. if (!graphics)
  232. return true;
  233. bool success = false;
  234. if (loadXMLFile_)
  235. {
  236. // If async loading, get the techniques / textures which should be ready now
  237. XMLElement rootElem = loadXMLFile_->GetRoot();
  238. success = Load(rootElem);
  239. }
  240. if (loadJSONFile_)
  241. {
  242. JSONValue rootVal = loadJSONFile_->GetRoot();
  243. success = Load(rootVal);
  244. }
  245. loadXMLFile_.Reset();
  246. loadJSONFile_.Reset();
  247. return success;
  248. }
  249. bool Material::BeginLoadXML(Deserializer& source)
  250. {
  251. ResetToDefaults();
  252. loadXMLFile_ = new XMLFile(context_);
  253. if (loadXMLFile_->Load(source))
  254. {
  255. // If async loading, scan the XML content beforehand for technique & texture resources
  256. // and request them to also be loaded. Can not do anything else at this point
  257. if (GetAsyncLoadState() == ASYNC_LOADING)
  258. {
  259. ResourceCache* cache = GetSubsystem<ResourceCache>();
  260. XMLElement rootElem = loadXMLFile_->GetRoot();
  261. XMLElement techniqueElem = rootElem.GetChild("technique");
  262. while (techniqueElem)
  263. {
  264. cache->BackgroundLoadResource<Technique>(techniqueElem.GetAttribute("name"), true, this);
  265. techniqueElem = techniqueElem.GetNext("technique");
  266. }
  267. XMLElement textureElem = rootElem.GetChild("texture");
  268. while (textureElem)
  269. {
  270. String name = textureElem.GetAttribute("name");
  271. // Detect cube maps and arrays by file extension: they are defined by an XML file
  272. if (GetExtension(name) == ".xml")
  273. {
  274. #ifdef DESKTOP_GRAPHICS
  275. StringHash type = ParseTextureTypeXml(cache, name);
  276. if (!type && textureElem.HasAttribute("unit"))
  277. {
  278. TextureUnit unit = ParseTextureUnitName(textureElem.GetAttribute("unit"));
  279. if (unit == TU_VOLUMEMAP)
  280. type = Texture3D::GetTypeStatic();
  281. }
  282. if (type == Texture3D::GetTypeStatic())
  283. cache->BackgroundLoadResource<Texture3D>(name, true, this);
  284. else if (type == Texture2DArray::GetTypeStatic())
  285. cache->BackgroundLoadResource<Texture2DArray>(name, true, this);
  286. else
  287. #endif
  288. cache->BackgroundLoadResource<TextureCube>(name, true, this);
  289. }
  290. else
  291. cache->BackgroundLoadResource<Texture2D>(name, true, this);
  292. textureElem = textureElem.GetNext("texture");
  293. }
  294. }
  295. return true;
  296. }
  297. return false;
  298. }
  299. bool Material::BeginLoadJSON(Deserializer& source)
  300. {
  301. // Attempt to load a JSON file
  302. ResetToDefaults();
  303. loadXMLFile_.Reset();
  304. // Attempt to load from JSON file instead
  305. loadJSONFile_ = new JSONFile(context_);
  306. if (loadJSONFile_->Load(source))
  307. {
  308. // If async loading, scan the XML content beforehand for technique & texture resources
  309. // and request them to also be loaded. Can not do anything else at this point
  310. if (GetAsyncLoadState() == ASYNC_LOADING)
  311. {
  312. ResourceCache* cache = GetSubsystem<ResourceCache>();
  313. const JSONValue& rootVal = loadJSONFile_->GetRoot();
  314. JSONArray techniqueArray = rootVal.Get("techniques").GetArray();
  315. for (unsigned i = 0; i < techniqueArray.Size(); i++)
  316. {
  317. const JSONValue& techVal = techniqueArray[i];
  318. cache->BackgroundLoadResource<Technique>(techVal.Get("name").GetString(), true, this);
  319. }
  320. JSONObject textureObject = rootVal.Get("textures").GetObject();
  321. for (JSONObject::ConstIterator it = textureObject.Begin(); it != textureObject.End(); it++)
  322. {
  323. String unitString = it->first_;
  324. String name = it->second_.GetString();
  325. // Detect cube maps and arrays by file extension: they are defined by an XML file
  326. if (GetExtension(name) == ".xml")
  327. {
  328. #ifdef DESKTOP_GRAPHICS
  329. StringHash type = ParseTextureTypeXml(cache, name);
  330. if (!type && !unitString.Empty())
  331. {
  332. TextureUnit unit = ParseTextureUnitName(unitString);
  333. if (unit == TU_VOLUMEMAP)
  334. type = Texture3D::GetTypeStatic();
  335. }
  336. if (type == Texture3D::GetTypeStatic())
  337. cache->BackgroundLoadResource<Texture3D>(name, true, this);
  338. else if (type == Texture2DArray::GetTypeStatic())
  339. cache->BackgroundLoadResource<Texture2DArray>(name, true, this);
  340. else
  341. #endif
  342. cache->BackgroundLoadResource<TextureCube>(name, true, this);
  343. }
  344. else
  345. cache->BackgroundLoadResource<Texture2D>(name, true, this);
  346. }
  347. }
  348. // JSON material was successfully loaded
  349. return true;
  350. }
  351. return false;
  352. }
  353. bool Material::Save(Serializer& dest) const
  354. {
  355. SharedPtr<XMLFile> xml(new XMLFile(context_));
  356. XMLElement materialElem = xml->CreateRoot("material");
  357. Save(materialElem);
  358. return xml->Save(dest);
  359. }
  360. bool Material::Load(const XMLElement& source)
  361. {
  362. ResetToDefaults();
  363. if (source.IsNull())
  364. {
  365. URHO3D_LOGERROR("Can not load material from null XML element");
  366. return false;
  367. }
  368. ResourceCache* cache = GetSubsystem<ResourceCache>();
  369. XMLElement techniqueElem = source.GetChild("technique");
  370. techniques_.Clear();
  371. while (techniqueElem)
  372. {
  373. Technique* tech = cache->GetResource<Technique>(techniqueElem.GetAttribute("name"));
  374. if (tech)
  375. {
  376. TechniqueEntry newTechnique;
  377. newTechnique.technique_ = tech;
  378. if (techniqueElem.HasAttribute("quality"))
  379. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  380. if (techniqueElem.HasAttribute("loddistance"))
  381. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  382. techniques_.Push(newTechnique);
  383. }
  384. techniqueElem = techniqueElem.GetNext("technique");
  385. }
  386. SortTechniques();
  387. XMLElement textureElem = source.GetChild("texture");
  388. while (textureElem)
  389. {
  390. TextureUnit unit = TU_DIFFUSE;
  391. if (textureElem.HasAttribute("unit"))
  392. unit = ParseTextureUnitName(textureElem.GetAttribute("unit"));
  393. if (unit < MAX_TEXTURE_UNITS)
  394. {
  395. String name = textureElem.GetAttribute("name");
  396. // Detect cube maps and arrays by file extension: they are defined by an XML file
  397. if (GetExtension(name) == ".xml")
  398. {
  399. #ifdef DESKTOP_GRAPHICS
  400. StringHash type = ParseTextureTypeXml(cache, name);
  401. if (!type && unit == TU_VOLUMEMAP)
  402. type = Texture3D::GetTypeStatic();
  403. if (type == Texture3D::GetTypeStatic())
  404. SetTexture(unit, cache->GetResource<Texture3D>(name));
  405. else if (type == Texture2DArray::GetTypeStatic())
  406. SetTexture(unit, cache->GetResource<Texture2DArray>(name));
  407. else
  408. #endif
  409. SetTexture(unit, cache->GetResource<TextureCube>(name));
  410. }
  411. else
  412. SetTexture(unit, cache->GetResource<Texture2D>(name));
  413. }
  414. textureElem = textureElem.GetNext("texture");
  415. }
  416. batchedParameterUpdate_ = true;
  417. XMLElement parameterElem = source.GetChild("parameter");
  418. while (parameterElem)
  419. {
  420. String name = parameterElem.GetAttribute("name");
  421. if (!parameterElem.HasAttribute("type"))
  422. SetShaderParameter(name, ParseShaderParameterValue(parameterElem.GetAttribute("value")));
  423. else
  424. SetShaderParameter(name, Variant(parameterElem.GetAttribute("type"), parameterElem.GetAttribute("value")));
  425. parameterElem = parameterElem.GetNext("parameter");
  426. }
  427. batchedParameterUpdate_ = false;
  428. XMLElement parameterAnimationElem = source.GetChild("parameteranimation");
  429. while (parameterAnimationElem)
  430. {
  431. String name = parameterAnimationElem.GetAttribute("name");
  432. SharedPtr<ValueAnimation> animation(new ValueAnimation(context_));
  433. if (!animation->LoadXML(parameterAnimationElem))
  434. {
  435. URHO3D_LOGERROR("Could not load parameter animation");
  436. return false;
  437. }
  438. String wrapModeString = parameterAnimationElem.GetAttribute("wrapmode");
  439. WrapMode wrapMode = WM_LOOP;
  440. for (int i = 0; i <= WM_CLAMP; ++i)
  441. {
  442. if (wrapModeString == wrapModeNames[i])
  443. {
  444. wrapMode = (WrapMode)i;
  445. break;
  446. }
  447. }
  448. float speed = parameterAnimationElem.GetFloat("speed");
  449. SetShaderParameterAnimation(name, animation, wrapMode, speed);
  450. parameterAnimationElem = parameterAnimationElem.GetNext("parameteranimation");
  451. }
  452. XMLElement cullElem = source.GetChild("cull");
  453. if (cullElem)
  454. SetCullMode((CullMode)GetStringListIndex(cullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  455. XMLElement shadowCullElem = source.GetChild("shadowcull");
  456. if (shadowCullElem)
  457. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  458. XMLElement fillElem = source.GetChild("fill");
  459. if (fillElem)
  460. SetFillMode((FillMode)GetStringListIndex(fillElem.GetAttribute("value").CString(), fillModeNames, FILL_SOLID));
  461. XMLElement depthBiasElem = source.GetChild("depthbias");
  462. if (depthBiasElem)
  463. SetDepthBias(BiasParameters(depthBiasElem.GetFloat("constant"), depthBiasElem.GetFloat("slopescaled")));
  464. XMLElement renderOrderElem = source.GetChild("renderorder");
  465. if (renderOrderElem)
  466. SetRenderOrder((unsigned char)renderOrderElem.GetUInt("value"));
  467. RefreshShaderParameterHash();
  468. RefreshMemoryUse();
  469. CheckOcclusion();
  470. return true;
  471. }
  472. bool Material::Load(const JSONValue& source)
  473. {
  474. ResetToDefaults();
  475. if (source.IsNull())
  476. {
  477. URHO3D_LOGERROR("Can not load material from null JSON element");
  478. return false;
  479. }
  480. ResourceCache* cache = GetSubsystem<ResourceCache>();
  481. // Load techniques
  482. JSONArray techniquesArray = source.Get("techniques").GetArray();
  483. techniques_.Clear();
  484. techniques_.Reserve(techniquesArray.Size());
  485. for (unsigned i = 0; i < techniquesArray.Size(); i++)
  486. {
  487. const JSONValue& techVal = techniquesArray[i];
  488. Technique* tech = cache->GetResource<Technique>(techVal.Get("name").GetString());
  489. if (tech)
  490. {
  491. TechniqueEntry newTechnique;
  492. newTechnique.technique_ = tech;
  493. JSONValue qualityVal = techVal.Get("quality");
  494. if (!qualityVal.IsNull())
  495. newTechnique.qualityLevel_ = qualityVal.GetInt();
  496. JSONValue lodDistanceVal = techVal.Get("loddistance");
  497. if (!lodDistanceVal.IsNull())
  498. newTechnique.lodDistance_ = lodDistanceVal.GetFloat();
  499. techniques_.Push(newTechnique);
  500. }
  501. }
  502. SortTechniques();
  503. // Load textures
  504. JSONObject textureObject = source.Get("textures").GetObject();
  505. for (JSONObject::ConstIterator it = textureObject.Begin(); it != textureObject.End(); it++)
  506. {
  507. String textureUnit = it->first_;
  508. String textureName = it->second_.GetString();
  509. TextureUnit unit = TU_DIFFUSE;
  510. unit = ParseTextureUnitName(textureUnit);
  511. if (unit < MAX_TEXTURE_UNITS)
  512. {
  513. // Detect cube maps and arrays by file extension: they are defined by an XML file
  514. if (GetExtension(textureName) == ".xml")
  515. {
  516. #ifdef DESKTOP_GRAPHICS
  517. StringHash type = ParseTextureTypeXml(cache, textureName);
  518. if (!type && unit == TU_VOLUMEMAP)
  519. type = Texture3D::GetTypeStatic();
  520. if (type == Texture3D::GetTypeStatic())
  521. SetTexture(unit, cache->GetResource<Texture3D>(textureName));
  522. else if (type == Texture2DArray::GetTypeStatic())
  523. SetTexture(unit, cache->GetResource<Texture2DArray>(textureName));
  524. else
  525. #endif
  526. SetTexture(unit, cache->GetResource<TextureCube>(textureName));
  527. }
  528. else
  529. SetTexture(unit, cache->GetResource<Texture2D>(textureName));
  530. }
  531. }
  532. // Get shader parameters
  533. batchedParameterUpdate_ = true;
  534. JSONObject parameterObject = source.Get("shaderParameters").GetObject();
  535. for (JSONObject::ConstIterator it = parameterObject.Begin(); it != parameterObject.End(); it++)
  536. {
  537. String name = it->first_;
  538. if (it->second_.IsString())
  539. SetShaderParameter(name, ParseShaderParameterValue(it->second_.GetString()));
  540. else if (it->second_.IsObject())
  541. {
  542. JSONObject valueObj = it->second_.GetObject();
  543. SetShaderParameter(name, Variant(valueObj["type"].GetString(), valueObj["value"].GetString()));
  544. }
  545. }
  546. batchedParameterUpdate_ = false;
  547. // Load shader parameter animationss
  548. JSONObject paramAnimationsObject = source.Get("shaderParameterAnimations").GetObject();
  549. for (JSONObject::ConstIterator it = paramAnimationsObject.Begin(); it != paramAnimationsObject.End(); it++)
  550. {
  551. String name = it->first_;
  552. JSONValue paramAnimVal = it->second_;
  553. SharedPtr<ValueAnimation> animation(new ValueAnimation(context_));
  554. if (!animation->LoadJSON(paramAnimVal))
  555. {
  556. URHO3D_LOGERROR("Could not load parameter animation");
  557. return false;
  558. }
  559. String wrapModeString = paramAnimVal.Get("wrapmode").GetString();
  560. WrapMode wrapMode = WM_LOOP;
  561. for (int i = 0; i <= WM_CLAMP; ++i)
  562. {
  563. if (wrapModeString == wrapModeNames[i])
  564. {
  565. wrapMode = (WrapMode)i;
  566. break;
  567. }
  568. }
  569. float speed = paramAnimVal.Get("speed").GetFloat();
  570. SetShaderParameterAnimation(name, animation, wrapMode, speed);
  571. }
  572. JSONValue cullVal = source.Get("cull");
  573. if (!cullVal.IsNull())
  574. SetCullMode((CullMode)GetStringListIndex(cullVal.GetString().CString(), cullModeNames, CULL_CCW));
  575. JSONValue shadowCullVal = source.Get("shadowcull");
  576. if (!shadowCullVal.IsNull())
  577. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullVal.GetString().CString(), cullModeNames, CULL_CCW));
  578. JSONValue fillVal = source.Get("fill");
  579. if (!fillVal.IsNull())
  580. SetFillMode((FillMode)GetStringListIndex(fillVal.GetString().CString(), fillModeNames, FILL_SOLID));
  581. JSONValue depthBiasVal = source.Get("depthbias");
  582. if (!depthBiasVal.IsNull())
  583. SetDepthBias(BiasParameters(depthBiasVal.Get("constant").GetFloat(), depthBiasVal.Get("slopescaled").GetFloat()));
  584. JSONValue renderOrderVal = source.Get("renderorder");
  585. if (!renderOrderVal.IsNull())
  586. SetRenderOrder((unsigned char)renderOrderVal.Get("value").GetUInt());
  587. RefreshShaderParameterHash();
  588. RefreshMemoryUse();
  589. CheckOcclusion();
  590. return true;
  591. }
  592. bool Material::Save(XMLElement& dest) const
  593. {
  594. if (dest.IsNull())
  595. {
  596. URHO3D_LOGERROR("Can not save material to null XML element");
  597. return false;
  598. }
  599. // Write techniques
  600. for (unsigned i = 0; i < techniques_.Size(); ++i)
  601. {
  602. const TechniqueEntry& entry = techniques_[i];
  603. if (!entry.technique_)
  604. continue;
  605. XMLElement techniqueElem = dest.CreateChild("technique");
  606. techniqueElem.SetString("name", entry.technique_->GetName());
  607. techniqueElem.SetInt("quality", entry.qualityLevel_);
  608. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  609. }
  610. // Write texture units
  611. for (unsigned j = 0; j < MAX_TEXTURE_UNITS; ++j)
  612. {
  613. Texture* texture = GetTexture((TextureUnit)j);
  614. if (texture)
  615. {
  616. XMLElement textureElem = dest.CreateChild("texture");
  617. textureElem.SetString("unit", textureUnitNames[j]);
  618. textureElem.SetString("name", texture->GetName());
  619. }
  620. }
  621. // Write shader parameters
  622. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin();
  623. j != shaderParameters_.End(); ++j)
  624. {
  625. XMLElement parameterElem = dest.CreateChild("parameter");
  626. parameterElem.SetString("name", j->second_.name_);
  627. if (j->second_.value_.GetType() != VAR_BUFFER)
  628. parameterElem.SetVectorVariant("value", j->second_.value_);
  629. else
  630. {
  631. parameterElem.SetAttribute("type", j->second_.value_.GetTypeName());
  632. parameterElem.SetAttribute("value", j->second_.value_.ToString());
  633. }
  634. }
  635. // Write shader parameter animations
  636. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator j = shaderParameterAnimationInfos_.Begin();
  637. j != shaderParameterAnimationInfos_.End(); ++j)
  638. {
  639. ShaderParameterAnimationInfo* info = j->second_;
  640. XMLElement parameterAnimationElem = dest.CreateChild("parameteranimation");
  641. parameterAnimationElem.SetString("name", info->GetName());
  642. if (!info->GetAnimation()->SaveXML(parameterAnimationElem))
  643. return false;
  644. parameterAnimationElem.SetAttribute("wrapmode", wrapModeNames[info->GetWrapMode()]);
  645. parameterAnimationElem.SetFloat("speed", info->GetSpeed());
  646. }
  647. // Write culling modes
  648. XMLElement cullElem = dest.CreateChild("cull");
  649. cullElem.SetString("value", cullModeNames[cullMode_]);
  650. XMLElement shadowCullElem = dest.CreateChild("shadowcull");
  651. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  652. // Write fill mode
  653. XMLElement fillElem = dest.CreateChild("fill");
  654. fillElem.SetString("value", fillModeNames[fillMode_]);
  655. // Write depth bias
  656. XMLElement depthBiasElem = dest.CreateChild("depthbias");
  657. depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
  658. depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
  659. // Write render order
  660. XMLElement renderOrderElem = dest.CreateChild("renderorder");
  661. renderOrderElem.SetUInt("value", renderOrder_);
  662. return true;
  663. }
  664. bool Material::Save(JSONValue& dest) const
  665. {
  666. // Write techniques
  667. JSONArray techniquesArray;
  668. techniquesArray.Reserve(techniques_.Size());
  669. for (unsigned i = 0; i < techniques_.Size(); ++i)
  670. {
  671. const TechniqueEntry& entry = techniques_[i];
  672. if (!entry.technique_)
  673. continue;
  674. JSONValue techniqueVal;
  675. techniqueVal.Set("name", entry.technique_->GetName());
  676. techniqueVal.Set("quality", (int) entry.qualityLevel_);
  677. techniqueVal.Set("loddistance", entry.lodDistance_);
  678. techniquesArray.Push(techniqueVal);
  679. }
  680. dest.Set("techniques", techniquesArray);
  681. // Write texture units
  682. JSONValue texturesValue;
  683. for (unsigned j = 0; j < MAX_TEXTURE_UNITS; ++j)
  684. {
  685. Texture* texture = GetTexture((TextureUnit)j);
  686. if (texture)
  687. texturesValue.Set(textureUnitNames[j], texture->GetName());
  688. }
  689. dest.Set("textures", texturesValue);
  690. // Write shader parameters
  691. JSONValue shaderParamsVal;
  692. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin();
  693. j != shaderParameters_.End(); ++j)
  694. {
  695. if (j->second_.value_.GetType() != VAR_BUFFER)
  696. shaderParamsVal.Set(j->second_.name_, j->second_.value_.ToString());
  697. else
  698. {
  699. JSONObject valueObj;
  700. valueObj["type"] = j->second_.value_.GetTypeName();
  701. valueObj["value"] = j->second_.value_.ToString();
  702. shaderParamsVal.Set(j->second_.name_, valueObj);
  703. }
  704. }
  705. dest.Set("shaderParameters", shaderParamsVal);
  706. // Write shader parameter animations
  707. JSONValue shaderParamAnimationsVal;
  708. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator j = shaderParameterAnimationInfos_.Begin();
  709. j != shaderParameterAnimationInfos_.End(); ++j)
  710. {
  711. ShaderParameterAnimationInfo* info = j->second_;
  712. JSONValue paramAnimationVal;
  713. if (!info->GetAnimation()->SaveJSON(paramAnimationVal))
  714. return false;
  715. paramAnimationVal.Set("wrapmode", wrapModeNames[info->GetWrapMode()]);
  716. paramAnimationVal.Set("speed", info->GetSpeed());
  717. shaderParamAnimationsVal.Set(info->GetName(), paramAnimationVal);
  718. }
  719. dest.Set("shaderParameterAnimations", shaderParamAnimationsVal);
  720. // Write culling modes
  721. dest.Set("cull", cullModeNames[cullMode_]);
  722. dest.Set("shadowcull", cullModeNames[shadowCullMode_]);
  723. // Write fill mode
  724. dest.Set("fill", fillModeNames[fillMode_]);
  725. // Write depth bias
  726. JSONValue depthBiasValue;
  727. depthBiasValue.Set("constant", depthBias_.constantBias_);
  728. depthBiasValue.Set("slopescaled", depthBias_.slopeScaledBias_);
  729. // Write render order
  730. dest.Set("renderorder", (unsigned) renderOrder_);
  731. return true;
  732. }
  733. void Material::SetNumTechniques(unsigned num)
  734. {
  735. if (!num)
  736. return;
  737. techniques_.Resize(num);
  738. RefreshMemoryUse();
  739. }
  740. void Material::SetTechnique(unsigned index, Technique* tech, unsigned qualityLevel, float lodDistance)
  741. {
  742. if (index >= techniques_.Size())
  743. return;
  744. techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
  745. CheckOcclusion();
  746. }
  747. void Material::SetShaderParameter(const String& name, const Variant& value)
  748. {
  749. MaterialShaderParameter newParam;
  750. newParam.name_ = name;
  751. newParam.value_ = value;
  752. StringHash nameHash(name);
  753. shaderParameters_[nameHash] = newParam;
  754. if (nameHash == PSP_MATSPECCOLOR)
  755. {
  756. VariantType type = value.GetType();
  757. if (type == VAR_VECTOR3)
  758. {
  759. const Vector3& vec = value.GetVector3();
  760. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  761. }
  762. else if (type == VAR_VECTOR4)
  763. {
  764. const Vector4& vec = value.GetVector4();
  765. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  766. }
  767. }
  768. if (!batchedParameterUpdate_)
  769. {
  770. RefreshShaderParameterHash();
  771. RefreshMemoryUse();
  772. }
  773. }
  774. void Material::SetShaderParameterAnimation(const String& name, ValueAnimation* animation, WrapMode wrapMode, float speed)
  775. {
  776. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  777. if (animation)
  778. {
  779. if (info && info->GetAnimation() == animation)
  780. {
  781. info->SetWrapMode(wrapMode);
  782. info->SetSpeed(speed);
  783. return;
  784. }
  785. if (shaderParameters_.Find(name) == shaderParameters_.End())
  786. {
  787. URHO3D_LOGERROR(GetName() + " has no shader parameter: " + name);
  788. return;
  789. }
  790. StringHash nameHash(name);
  791. shaderParameterAnimationInfos_[nameHash] = new ShaderParameterAnimationInfo(this, name, animation, wrapMode, speed);
  792. UpdateEventSubscription();
  793. }
  794. else
  795. {
  796. if (info)
  797. {
  798. StringHash nameHash(name);
  799. shaderParameterAnimationInfos_.Erase(nameHash);
  800. UpdateEventSubscription();
  801. }
  802. }
  803. }
  804. void Material::SetShaderParameterAnimationWrapMode(const String& name, WrapMode wrapMode)
  805. {
  806. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  807. if (info)
  808. info->SetWrapMode(wrapMode);
  809. }
  810. void Material::SetShaderParameterAnimationSpeed(const String& name, float speed)
  811. {
  812. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  813. if (info)
  814. info->SetSpeed(speed);
  815. }
  816. void Material::SetTexture(TextureUnit unit, Texture* texture)
  817. {
  818. if (unit < MAX_TEXTURE_UNITS)
  819. {
  820. if (texture)
  821. textures_[unit] = texture;
  822. else
  823. textures_.Erase(unit);
  824. }
  825. }
  826. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  827. {
  828. Matrix3x4 transform(Matrix3x4::IDENTITY);
  829. transform.m00_ = repeat.x_;
  830. transform.m11_ = repeat.y_;
  831. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  832. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  833. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  834. rotationMatrix.m00_ = Cos(rotation);
  835. rotationMatrix.m01_ = Sin(rotation);
  836. rotationMatrix.m10_ = -rotationMatrix.m01_;
  837. rotationMatrix.m11_ = rotationMatrix.m00_;
  838. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  839. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  840. transform = rotationMatrix * transform;
  841. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  842. offsetMatrix.m03_ = offset.x_;
  843. offsetMatrix.m13_ = offset.y_;
  844. transform = offsetMatrix * transform;
  845. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  846. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  847. }
  848. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  849. {
  850. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  851. }
  852. void Material::SetCullMode(CullMode mode)
  853. {
  854. cullMode_ = mode;
  855. }
  856. void Material::SetShadowCullMode(CullMode mode)
  857. {
  858. shadowCullMode_ = mode;
  859. }
  860. void Material::SetFillMode(FillMode mode)
  861. {
  862. fillMode_ = mode;
  863. }
  864. void Material::SetDepthBias(const BiasParameters& parameters)
  865. {
  866. depthBias_ = parameters;
  867. depthBias_.Validate();
  868. }
  869. void Material::SetRenderOrder(unsigned char order)
  870. {
  871. renderOrder_ = order;
  872. }
  873. void Material::SetScene(Scene* scene)
  874. {
  875. UnsubscribeFromEvent(E_UPDATE);
  876. UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
  877. subscribed_ = false;
  878. scene_ = scene;
  879. UpdateEventSubscription();
  880. }
  881. void Material::RemoveShaderParameter(const String& name)
  882. {
  883. StringHash nameHash(name);
  884. shaderParameters_.Erase(nameHash);
  885. if (nameHash == PSP_MATSPECCOLOR)
  886. specular_ = false;
  887. RefreshShaderParameterHash();
  888. RefreshMemoryUse();
  889. }
  890. void Material::ReleaseShaders()
  891. {
  892. for (unsigned i = 0; i < techniques_.Size(); ++i)
  893. {
  894. Technique* tech = techniques_[i].technique_;
  895. if (tech)
  896. tech->ReleaseShaders();
  897. }
  898. }
  899. SharedPtr<Material> Material::Clone(const String& cloneName) const
  900. {
  901. SharedPtr<Material> ret(new Material(context_));
  902. ret->SetName(cloneName);
  903. ret->techniques_ = techniques_;
  904. ret->shaderParameters_ = shaderParameters_;
  905. ret->shaderParameterHash_ = shaderParameterHash_;
  906. ret->textures_ = textures_;
  907. ret->occlusion_ = occlusion_;
  908. ret->specular_ = specular_;
  909. ret->cullMode_ = cullMode_;
  910. ret->shadowCullMode_ = shadowCullMode_;
  911. ret->fillMode_ = fillMode_;
  912. ret->renderOrder_ = renderOrder_;
  913. ret->RefreshMemoryUse();
  914. return ret;
  915. }
  916. void Material::SortTechniques()
  917. {
  918. Sort(techniques_.Begin(), techniques_.End(), CompareTechniqueEntries);
  919. }
  920. void Material::MarkForAuxView(unsigned frameNumber)
  921. {
  922. auxViewFrameNumber_ = frameNumber;
  923. }
  924. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  925. {
  926. return index < techniques_.Size() ? techniques_[index] : noEntry;
  927. }
  928. Technique* Material::GetTechnique(unsigned index) const
  929. {
  930. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  931. }
  932. Pass* Material::GetPass(unsigned index, const String& passName) const
  933. {
  934. Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  935. return tech ? tech->GetPass(passName) : 0;
  936. }
  937. Texture* Material::GetTexture(TextureUnit unit) const
  938. {
  939. HashMap<TextureUnit, SharedPtr<Texture> >::ConstIterator i = textures_.Find(unit);
  940. return i != textures_.End() ? i->second_.Get() : (Texture*)0;
  941. }
  942. const Variant& Material::GetShaderParameter(const String& name) const
  943. {
  944. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(name);
  945. return i != shaderParameters_.End() ? i->second_.value_ : Variant::EMPTY;
  946. }
  947. ValueAnimation* Material::GetShaderParameterAnimation(const String& name) const
  948. {
  949. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  950. return info == 0 ? 0 : info->GetAnimation();
  951. }
  952. WrapMode Material::GetShaderParameterAnimationWrapMode(const String& name) const
  953. {
  954. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  955. return info == 0 ? WM_LOOP : info->GetWrapMode();
  956. }
  957. float Material::GetShaderParameterAnimationSpeed(const String& name) const
  958. {
  959. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  960. return info == 0 ? 0 : info->GetSpeed();
  961. }
  962. Scene* Material::GetScene() const
  963. {
  964. return scene_;
  965. }
  966. String Material::GetTextureUnitName(TextureUnit unit)
  967. {
  968. return textureUnitNames[unit];
  969. }
  970. Variant Material::ParseShaderParameterValue(const String& value)
  971. {
  972. String valueTrimmed = value.Trimmed();
  973. if (valueTrimmed.Length() && IsAlpha((unsigned)valueTrimmed[0]))
  974. return Variant(ToBool(valueTrimmed));
  975. else
  976. return ToVectorVariant(valueTrimmed);
  977. }
  978. void Material::CheckOcclusion()
  979. {
  980. // Determine occlusion by checking the base pass of each technique
  981. occlusion_ = false;
  982. for (unsigned i = 0; i < techniques_.Size(); ++i)
  983. {
  984. Technique* tech = techniques_[i].technique_;
  985. if (tech)
  986. {
  987. Pass* pass = tech->GetPass("base");
  988. if (pass && pass->GetDepthWrite() && !pass->GetAlphaMask())
  989. occlusion_ = true;
  990. }
  991. }
  992. }
  993. void Material::ResetToDefaults()
  994. {
  995. // Needs to be a no-op when async loading, as this does a GetResource() which is not allowed from worker threads
  996. if (!Thread::IsMainThread())
  997. return;
  998. SetNumTechniques(1);
  999. Renderer* renderer = GetSubsystem<Renderer>();
  1000. SetTechnique(0, renderer ? renderer->GetDefaultTechnique() :
  1001. GetSubsystem<ResourceCache>()->GetResource<Technique>("Techniques/NoTexture.xml"));
  1002. textures_.Clear();
  1003. batchedParameterUpdate_ = true;
  1004. shaderParameters_.Clear();
  1005. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  1006. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  1007. SetShaderParameter("MatDiffColor", Vector4::ONE);
  1008. SetShaderParameter("MatEmissiveColor", Vector3::ZERO);
  1009. SetShaderParameter("MatEnvMapColor", Vector3::ONE);
  1010. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  1011. SetShaderParameter("RoughnessPS", 0.5f);
  1012. SetShaderParameter("MetallicPS", 0.0f);
  1013. batchedParameterUpdate_ = false;
  1014. cullMode_ = CULL_CCW;
  1015. shadowCullMode_ = CULL_CCW;
  1016. fillMode_ = FILL_SOLID;
  1017. depthBias_ = BiasParameters(0.0f, 0.0f);
  1018. renderOrder_ = DEFAULT_RENDER_ORDER;
  1019. RefreshShaderParameterHash();
  1020. RefreshMemoryUse();
  1021. }
  1022. void Material::RefreshShaderParameterHash()
  1023. {
  1024. VectorBuffer temp;
  1025. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Begin();
  1026. i != shaderParameters_.End(); ++i)
  1027. {
  1028. temp.WriteStringHash(i->first_);
  1029. temp.WriteVariant(i->second_.value_);
  1030. }
  1031. shaderParameterHash_ = 0;
  1032. const unsigned char* data = temp.GetData();
  1033. unsigned dataSize = temp.GetSize();
  1034. for (unsigned i = 0; i < dataSize; ++i)
  1035. shaderParameterHash_ = SDBMHash(shaderParameterHash_, data[i]);
  1036. }
  1037. void Material::RefreshMemoryUse()
  1038. {
  1039. unsigned memoryUse = sizeof(Material);
  1040. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  1041. memoryUse += MAX_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
  1042. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  1043. SetMemoryUse(memoryUse);
  1044. }
  1045. ShaderParameterAnimationInfo* Material::GetShaderParameterAnimationInfo(const String& name) const
  1046. {
  1047. StringHash nameHash(name);
  1048. HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Find(nameHash);
  1049. if (i == shaderParameterAnimationInfos_.End())
  1050. return 0;
  1051. return i->second_;
  1052. }
  1053. void Material::UpdateEventSubscription()
  1054. {
  1055. if (shaderParameterAnimationInfos_.Size() && !subscribed_)
  1056. {
  1057. if (scene_)
  1058. SubscribeToEvent(scene_, E_ATTRIBUTEANIMATIONUPDATE, URHO3D_HANDLER(Material, HandleAttributeAnimationUpdate));
  1059. else
  1060. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Material, HandleAttributeAnimationUpdate));
  1061. subscribed_ = true;
  1062. }
  1063. else if (subscribed_ && shaderParameterAnimationInfos_.Empty())
  1064. {
  1065. UnsubscribeFromEvent(E_UPDATE);
  1066. UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
  1067. subscribed_ = false;
  1068. }
  1069. }
  1070. void Material::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  1071. {
  1072. // Timestep parameter is same no matter what event is being listened to
  1073. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  1074. Vector<String> finishedNames;
  1075. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Begin();
  1076. i != shaderParameterAnimationInfos_.End(); ++i)
  1077. {
  1078. if (i->second_->Update(timeStep))
  1079. finishedNames.Push(i->second_->GetName());
  1080. }
  1081. // Remove finished animations
  1082. for (unsigned i = 0; i < finishedNames.Size(); ++i)
  1083. SetShaderParameterAnimation(finishedNames[i], 0);
  1084. }
  1085. }