Material.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Graphics/Graphics.h"
  27. #include "../Graphics/Material.h"
  28. #include "../Graphics/Technique.h"
  29. #include "../Graphics/Texture2D.h"
  30. #include "../Graphics/Texture3D.h"
  31. #include "../Graphics/TextureCube.h"
  32. #include "../IO/FileSystem.h"
  33. #include "../IO/Log.h"
  34. #include "../IO/VectorBuffer.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../Resource/XMLFile.h"
  37. #include "../Scene/Scene.h"
  38. #include "../Scene/SceneEvents.h"
  39. #include "../Scene/ValueAnimation.h"
  40. #include "../DebugNew.h"
  41. namespace Atomic
  42. {
  43. extern const char* wrapModeNames[];
  44. static const char* textureUnitNames[] =
  45. {
  46. "diffuse",
  47. "normal",
  48. "specular",
  49. "emissive",
  50. "environment",
  51. #ifdef DESKTOP_GRAPHICS
  52. "volume",
  53. "custom1",
  54. "custom2",
  55. "lightramp",
  56. "lightshape",
  57. "shadowmap",
  58. "faceselect",
  59. "indirection",
  60. "depth",
  61. "light",
  62. "zone",
  63. 0
  64. #else
  65. "lightramp",
  66. "lightshape",
  67. "shadowmap",
  68. 0
  69. #endif
  70. };
  71. static const char* cullModeNames[] =
  72. {
  73. "none",
  74. "ccw",
  75. "cw",
  76. 0
  77. };
  78. static const char* fillModeNames[] =
  79. {
  80. "solid",
  81. "wireframe",
  82. "point",
  83. 0
  84. };
  85. TextureUnit ParseTextureUnitName(String name)
  86. {
  87. name = name.ToLower().Trimmed();
  88. TextureUnit unit = (TextureUnit)GetStringListIndex(name.CString(), textureUnitNames, MAX_TEXTURE_UNITS);
  89. if (unit == MAX_TEXTURE_UNITS)
  90. {
  91. // Check also for shorthand names
  92. if (name == "diff")
  93. unit = TU_DIFFUSE;
  94. else if (name == "albedo")
  95. unit = TU_DIFFUSE;
  96. else if (name == "norm")
  97. unit = TU_NORMAL;
  98. else if (name == "spec")
  99. unit = TU_SPECULAR;
  100. else if (name == "env")
  101. unit = TU_ENVIRONMENT;
  102. // Finally check for specifying the texture unit directly as a number
  103. else if (name.Length() < 3)
  104. unit = (TextureUnit)Clamp(ToInt(name), 0, MAX_TEXTURE_UNITS - 1);
  105. }
  106. if (unit == MAX_TEXTURE_UNITS)
  107. LOGERROR("Unknown texture unit name " + name);
  108. return unit;
  109. }
  110. static TechniqueEntry noEntry;
  111. bool CompareTechniqueEntries(const TechniqueEntry& lhs, const TechniqueEntry& rhs)
  112. {
  113. if (lhs.lodDistance_ != rhs.lodDistance_)
  114. return lhs.lodDistance_ > rhs.lodDistance_;
  115. else
  116. return lhs.qualityLevel_ > rhs.qualityLevel_;
  117. }
  118. TechniqueEntry::TechniqueEntry() :
  119. qualityLevel_(0),
  120. lodDistance_(0.0f)
  121. {
  122. }
  123. TechniqueEntry::TechniqueEntry(Technique* tech, unsigned qualityLevel, float lodDistance) :
  124. technique_(tech),
  125. qualityLevel_(qualityLevel),
  126. lodDistance_(lodDistance)
  127. {
  128. }
  129. TechniqueEntry::~TechniqueEntry()
  130. {
  131. }
  132. ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(Material* target, const String& name, ValueAnimation* attributeAnimation,
  133. 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();
  377. j != shaderParameters_.End(); ++j)
  378. {
  379. XMLElement parameterElem = dest.CreateChild("parameter");
  380. parameterElem.SetString("name", j->second_.name_);
  381. parameterElem.SetVectorVariant("value", j->second_.value_);
  382. }
  383. // Write shader parameter animations
  384. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator j = shaderParameterAnimationInfos_.Begin();
  385. j != shaderParameterAnimationInfos_.End(); ++j)
  386. {
  387. ShaderParameterAnimationInfo* info = j->second_;
  388. XMLElement parameterAnimationElem = dest.CreateChild("parameteranimation");
  389. parameterAnimationElem.SetString("name", info->GetName());
  390. if (!info->GetAnimation()->SaveXML(parameterAnimationElem))
  391. return false;
  392. parameterAnimationElem.SetAttribute("wrapmode", wrapModeNames[info->GetWrapMode()]);
  393. parameterAnimationElem.SetFloat("speed", info->GetSpeed());
  394. }
  395. // Write culling modes
  396. XMLElement cullElem = dest.CreateChild("cull");
  397. cullElem.SetString("value", cullModeNames[cullMode_]);
  398. XMLElement shadowCullElem = dest.CreateChild("shadowcull");
  399. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  400. // Write fill mode
  401. XMLElement fillElem = dest.CreateChild("fill");
  402. fillElem.SetString("value", fillModeNames[fillMode_]);
  403. // Write depth bias
  404. XMLElement depthBiasElem = dest.CreateChild("depthbias");
  405. depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
  406. depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
  407. return true;
  408. }
  409. void Material::SetNumTechniques(unsigned num)
  410. {
  411. if (!num)
  412. return;
  413. techniques_.Resize(num);
  414. RefreshMemoryUse();
  415. }
  416. void Material::SetTechnique(unsigned index, Technique* tech, unsigned qualityLevel, float lodDistance)
  417. {
  418. if (index >= techniques_.Size())
  419. return;
  420. techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
  421. CheckOcclusion();
  422. }
  423. void Material::SetShaderParameter(const String& name, const Variant& value)
  424. {
  425. MaterialShaderParameter newParam;
  426. newParam.name_ = name;
  427. newParam.value_ = value;
  428. StringHash nameHash(name);
  429. shaderParameters_[nameHash] = newParam;
  430. if (nameHash == PSP_MATSPECCOLOR)
  431. {
  432. VariantType type = value.GetType();
  433. if (type == VAR_VECTOR3)
  434. {
  435. const Vector3& vec = value.GetVector3();
  436. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  437. }
  438. else if (type == VAR_VECTOR4)
  439. {
  440. const Vector4& vec = value.GetVector4();
  441. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  442. }
  443. }
  444. if (!batchedParameterUpdate_)
  445. {
  446. RefreshShaderParameterHash();
  447. RefreshMemoryUse();
  448. }
  449. }
  450. void Material::SetShaderParameterAnimation(const String& name, ValueAnimation* animation, WrapMode wrapMode, float speed)
  451. {
  452. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  453. if (animation)
  454. {
  455. if (info && info->GetAnimation() == animation)
  456. {
  457. info->SetWrapMode(wrapMode);
  458. info->SetSpeed(speed);
  459. return;
  460. }
  461. if (shaderParameters_.Find(name) == shaderParameters_.End())
  462. {
  463. LOGERROR(GetName() + " has no shader parameter: " + name);
  464. return;
  465. }
  466. StringHash nameHash(name);
  467. shaderParameterAnimationInfos_[nameHash] = new ShaderParameterAnimationInfo(this, name, animation, wrapMode, speed);
  468. UpdateEventSubscription();
  469. }
  470. else
  471. {
  472. if (info)
  473. {
  474. StringHash nameHash(name);
  475. shaderParameterAnimationInfos_.Erase(nameHash);
  476. UpdateEventSubscription();
  477. }
  478. }
  479. }
  480. void Material::SetShaderParameterAnimationWrapMode(const String& name, WrapMode wrapMode)
  481. {
  482. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  483. if (info)
  484. info->SetWrapMode(wrapMode);
  485. }
  486. void Material::SetShaderParameterAnimationSpeed(const String& name, float speed)
  487. {
  488. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  489. if (info)
  490. info->SetSpeed(speed);
  491. }
  492. void Material::SetTexture(TextureUnit unit, Texture* texture)
  493. {
  494. if (unit < MAX_TEXTURE_UNITS)
  495. {
  496. if (texture)
  497. textures_[unit] = texture;
  498. else
  499. textures_.Erase(unit);
  500. }
  501. }
  502. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  503. {
  504. Matrix3x4 transform(Matrix3x4::IDENTITY);
  505. transform.m00_ = repeat.x_;
  506. transform.m11_ = repeat.y_;
  507. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  508. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  509. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  510. rotationMatrix.m00_ = Cos(rotation);
  511. rotationMatrix.m01_ = Sin(rotation);
  512. rotationMatrix.m10_ = -rotationMatrix.m01_;
  513. rotationMatrix.m11_ = rotationMatrix.m00_;
  514. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  515. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  516. transform = rotationMatrix * transform;
  517. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  518. offsetMatrix.m03_ = offset.x_;
  519. offsetMatrix.m13_ = offset.y_;
  520. transform = offsetMatrix * transform;
  521. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  522. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  523. }
  524. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  525. {
  526. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  527. }
  528. void Material::SetCullMode(CullMode mode)
  529. {
  530. cullMode_ = mode;
  531. }
  532. void Material::SetShadowCullMode(CullMode mode)
  533. {
  534. shadowCullMode_ = mode;
  535. }
  536. void Material::SetFillMode(FillMode mode)
  537. {
  538. fillMode_ = mode;
  539. }
  540. void Material::SetDepthBias(const BiasParameters& parameters)
  541. {
  542. depthBias_ = parameters;
  543. depthBias_.Validate();
  544. }
  545. void Material::SetScene(Scene* scene)
  546. {
  547. UnsubscribeFromEvent(E_UPDATE);
  548. UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
  549. subscribed_ = false;
  550. scene_ = scene;
  551. UpdateEventSubscription();
  552. }
  553. void Material::RemoveShaderParameter(const String& name)
  554. {
  555. StringHash nameHash(name);
  556. shaderParameters_.Erase(nameHash);
  557. if (nameHash == PSP_MATSPECCOLOR)
  558. specular_ = false;
  559. RefreshShaderParameterHash();
  560. RefreshMemoryUse();
  561. }
  562. void Material::ReleaseShaders()
  563. {
  564. for (unsigned i = 0; i < techniques_.Size(); ++i)
  565. {
  566. Technique* tech = techniques_[i].technique_;
  567. if (tech)
  568. tech->ReleaseShaders();
  569. }
  570. }
  571. SharedPtr<Material> Material::Clone(const String& cloneName) const
  572. {
  573. SharedPtr<Material> ret(new Material(context_));
  574. ret->SetName(cloneName);
  575. ret->techniques_ = techniques_;
  576. ret->shaderParameters_ = shaderParameters_;
  577. ret->textures_ = textures_;
  578. ret->occlusion_ = occlusion_;
  579. ret->specular_ = specular_;
  580. ret->cullMode_ = cullMode_;
  581. ret->shadowCullMode_ = shadowCullMode_;
  582. ret->fillMode_ = fillMode_;
  583. ret->RefreshMemoryUse();
  584. return ret;
  585. }
  586. void Material::SortTechniques()
  587. {
  588. Sort(techniques_.Begin(), techniques_.End(), CompareTechniqueEntries);
  589. }
  590. void Material::MarkForAuxView(unsigned frameNumber)
  591. {
  592. auxViewFrameNumber_ = frameNumber;
  593. }
  594. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  595. {
  596. return index < techniques_.Size() ? techniques_[index] : noEntry;
  597. }
  598. Technique* Material::GetTechnique(unsigned index) const
  599. {
  600. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  601. }
  602. Pass* Material::GetPass(unsigned index, const String& passName) const
  603. {
  604. Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  605. return tech ? tech->GetPass(passName) : 0;
  606. }
  607. Texture* Material::GetTexture(TextureUnit unit) const
  608. {
  609. HashMap<TextureUnit, SharedPtr<Texture> >::ConstIterator i = textures_.Find(unit);
  610. return i != textures_.End() ? i->second_.Get() : (Texture*)0;
  611. }
  612. const Variant& Material::GetShaderParameter(const String& name) const
  613. {
  614. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(name);
  615. return i != shaderParameters_.End() ? i->second_.value_ : Variant::EMPTY;
  616. }
  617. ValueAnimation* Material::GetShaderParameterAnimation(const String& name) const
  618. {
  619. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  620. return info == 0 ? 0 : info->GetAnimation();
  621. }
  622. WrapMode Material::GetShaderParameterAnimationWrapMode(const String& name) const
  623. {
  624. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  625. return info == 0 ? WM_LOOP : info->GetWrapMode();
  626. }
  627. float Material::GetShaderParameterAnimationSpeed(const String& name) const
  628. {
  629. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  630. return info == 0 ? 0 : info->GetSpeed();
  631. }
  632. Scene* Material::GetScene() const
  633. {
  634. return scene_;
  635. }
  636. String Material::GetTextureUnitName(TextureUnit unit)
  637. {
  638. return textureUnitNames[unit];
  639. }
  640. Variant Material::ParseShaderParameterValue(const String& value)
  641. {
  642. String valueTrimmed = value.Trimmed();
  643. if (valueTrimmed.Length() && IsAlpha((unsigned)valueTrimmed[0]))
  644. return Variant(ToBool(valueTrimmed));
  645. else
  646. return ToVectorVariant(valueTrimmed);
  647. }
  648. void Material::CheckOcclusion()
  649. {
  650. // Determine occlusion by checking the base pass of each technique
  651. occlusion_ = false;
  652. for (unsigned i = 0; i < techniques_.Size(); ++i)
  653. {
  654. Technique* tech = techniques_[i].technique_;
  655. if (tech)
  656. {
  657. Pass* pass = tech->GetPass("base");
  658. if (pass && pass->GetDepthWrite() && !pass->GetAlphaMask())
  659. occlusion_ = true;
  660. }
  661. }
  662. }
  663. void Material::ResetToDefaults()
  664. {
  665. // Needs to be a no-op when async loading, as this does a GetResource() which is not allowed from worker threads
  666. if (!Thread::IsMainThread())
  667. return;
  668. SetNumTechniques(1);
  669. SetTechnique(0, GetSubsystem<ResourceCache>()->GetResource<Technique>("Techniques/NoTexture.xml"));
  670. textures_.Clear();
  671. batchedParameterUpdate_ = true;
  672. shaderParameters_.Clear();
  673. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  674. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  675. SetShaderParameter("MatDiffColor", Vector4::ONE);
  676. SetShaderParameter("MatEmissiveColor", Vector3::ZERO);
  677. SetShaderParameter("MatEnvMapColor", Vector3::ONE);
  678. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  679. batchedParameterUpdate_ = false;
  680. cullMode_ = CULL_CCW;
  681. shadowCullMode_ = CULL_CCW;
  682. fillMode_ = FILL_SOLID;
  683. depthBias_ = BiasParameters(0.0f, 0.0f);
  684. RefreshShaderParameterHash();
  685. RefreshMemoryUse();
  686. }
  687. void Material::RefreshShaderParameterHash()
  688. {
  689. VectorBuffer temp;
  690. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Begin();
  691. i != shaderParameters_.End(); ++i)
  692. {
  693. temp.WriteStringHash(i->first_);
  694. temp.WriteVariant(i->second_.value_);
  695. }
  696. shaderParameterHash_ = 0;
  697. const unsigned char* data = temp.GetData();
  698. unsigned dataSize = temp.GetSize();
  699. for (unsigned i = 0; i < dataSize; ++i)
  700. shaderParameterHash_ = SDBMHash(shaderParameterHash_, data[i]);
  701. }
  702. void Material::RefreshMemoryUse()
  703. {
  704. unsigned memoryUse = sizeof(Material);
  705. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  706. memoryUse += MAX_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
  707. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  708. SetMemoryUse(memoryUse);
  709. }
  710. ShaderParameterAnimationInfo* Material::GetShaderParameterAnimationInfo(const String& name) const
  711. {
  712. StringHash nameHash(name);
  713. HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Find(nameHash);
  714. if (i == shaderParameterAnimationInfos_.End())
  715. return 0;
  716. return i->second_;
  717. }
  718. void Material::UpdateEventSubscription()
  719. {
  720. if (shaderParameterAnimationInfos_.Size() && !subscribed_)
  721. {
  722. if (scene_)
  723. SubscribeToEvent(scene_, E_ATTRIBUTEANIMATIONUPDATE, HANDLER(Material, HandleAttributeAnimationUpdate));
  724. else
  725. SubscribeToEvent(E_UPDATE, HANDLER(Material, HandleAttributeAnimationUpdate));
  726. subscribed_ = true;
  727. }
  728. else if (subscribed_)
  729. {
  730. UnsubscribeFromEvent(E_UPDATE);
  731. UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
  732. subscribed_ = false;
  733. }
  734. }
  735. void Material::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  736. {
  737. // Timestep parameter is same no matter what event is being listened to
  738. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  739. Vector<String> finishedNames;
  740. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Begin();
  741. i != shaderParameterAnimationInfos_.End(); ++i)
  742. {
  743. if (i->second_->Update(timeStep))
  744. finishedNames.Push(i->second_->GetName());
  745. }
  746. // Remove finished animations
  747. for (unsigned i = 0; i < finishedNames.Size(); ++i)
  748. SetShaderParameterAnimation(finishedNames[i], 0);
  749. }
  750. }