Material.cpp 45 KB

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