Material.cpp 44 KB

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