Material.cpp 27 KB

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