Material.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  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. 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. XMLElement renderOrderElem = source.GetChild("renderorder");
  342. if (renderOrderElem)
  343. SetRenderOrder((unsigned char)renderOrderElem.GetUInt("value"));
  344. RefreshShaderParameterHash();
  345. RefreshMemoryUse();
  346. CheckOcclusion();
  347. return true;
  348. }
  349. bool Material::Save(XMLElement& dest) const
  350. {
  351. if (dest.IsNull())
  352. {
  353. LOGERROR("Can not save material to null XML element");
  354. return false;
  355. }
  356. // Write techniques
  357. for (unsigned i = 0; i < techniques_.Size(); ++i)
  358. {
  359. const TechniqueEntry& entry = techniques_[i];
  360. if (!entry.technique_)
  361. continue;
  362. XMLElement techniqueElem = dest.CreateChild("technique");
  363. techniqueElem.SetString("name", entry.technique_->GetName());
  364. techniqueElem.SetInt("quality", entry.qualityLevel_);
  365. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  366. }
  367. // Write texture units
  368. for (unsigned j = 0; j < MAX_TEXTURE_UNITS; ++j)
  369. {
  370. Texture* texture = GetTexture((TextureUnit)j);
  371. if (texture)
  372. {
  373. XMLElement textureElem = dest.CreateChild("texture");
  374. textureElem.SetString("unit", textureUnitNames[j]);
  375. textureElem.SetString("name", texture->GetName());
  376. }
  377. }
  378. // Write shader parameters
  379. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin();
  380. j != shaderParameters_.End(); ++j)
  381. {
  382. XMLElement parameterElem = dest.CreateChild("parameter");
  383. parameterElem.SetString("name", j->second_.name_);
  384. parameterElem.SetVectorVariant("value", j->second_.value_);
  385. }
  386. // Write shader parameter animations
  387. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator j = shaderParameterAnimationInfos_.Begin();
  388. j != shaderParameterAnimationInfos_.End(); ++j)
  389. {
  390. ShaderParameterAnimationInfo* info = j->second_;
  391. XMLElement parameterAnimationElem = dest.CreateChild("parameteranimation");
  392. parameterAnimationElem.SetString("name", info->GetName());
  393. if (!info->GetAnimation()->SaveXML(parameterAnimationElem))
  394. return false;
  395. parameterAnimationElem.SetAttribute("wrapmode", wrapModeNames[info->GetWrapMode()]);
  396. parameterAnimationElem.SetFloat("speed", info->GetSpeed());
  397. }
  398. // Write culling modes
  399. XMLElement cullElem = dest.CreateChild("cull");
  400. cullElem.SetString("value", cullModeNames[cullMode_]);
  401. XMLElement shadowCullElem = dest.CreateChild("shadowcull");
  402. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  403. // Write fill mode
  404. XMLElement fillElem = dest.CreateChild("fill");
  405. fillElem.SetString("value", fillModeNames[fillMode_]);
  406. // Write depth bias
  407. XMLElement depthBiasElem = dest.CreateChild("depthbias");
  408. depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
  409. depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
  410. // Write render order
  411. XMLElement renderOrderElem = dest.CreateChild("renderorder");
  412. renderOrderElem.SetUInt("value", renderOrder_);
  413. return true;
  414. }
  415. void Material::SetNumTechniques(unsigned num)
  416. {
  417. if (!num)
  418. return;
  419. techniques_.Resize(num);
  420. RefreshMemoryUse();
  421. }
  422. void Material::SetTechnique(unsigned index, Technique* tech, unsigned qualityLevel, float lodDistance)
  423. {
  424. if (index >= techniques_.Size())
  425. return;
  426. techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
  427. CheckOcclusion();
  428. }
  429. void Material::SetShaderParameter(const String& name, const Variant& value)
  430. {
  431. MaterialShaderParameter newParam;
  432. newParam.name_ = name;
  433. newParam.value_ = value;
  434. StringHash nameHash(name);
  435. shaderParameters_[nameHash] = newParam;
  436. if (nameHash == PSP_MATSPECCOLOR)
  437. {
  438. VariantType type = value.GetType();
  439. if (type == VAR_VECTOR3)
  440. {
  441. const Vector3& vec = value.GetVector3();
  442. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  443. }
  444. else if (type == VAR_VECTOR4)
  445. {
  446. const Vector4& vec = value.GetVector4();
  447. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  448. }
  449. }
  450. if (!batchedParameterUpdate_)
  451. {
  452. RefreshShaderParameterHash();
  453. RefreshMemoryUse();
  454. }
  455. }
  456. void Material::SetShaderParameterAnimation(const String& name, ValueAnimation* animation, WrapMode wrapMode, float speed)
  457. {
  458. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  459. if (animation)
  460. {
  461. if (info && info->GetAnimation() == animation)
  462. {
  463. info->SetWrapMode(wrapMode);
  464. info->SetSpeed(speed);
  465. return;
  466. }
  467. if (shaderParameters_.Find(name) == shaderParameters_.End())
  468. {
  469. LOGERROR(GetName() + " has no shader parameter: " + name);
  470. return;
  471. }
  472. StringHash nameHash(name);
  473. shaderParameterAnimationInfos_[nameHash] = new ShaderParameterAnimationInfo(this, name, animation, wrapMode, speed);
  474. UpdateEventSubscription();
  475. }
  476. else
  477. {
  478. if (info)
  479. {
  480. StringHash nameHash(name);
  481. shaderParameterAnimationInfos_.Erase(nameHash);
  482. UpdateEventSubscription();
  483. }
  484. }
  485. }
  486. void Material::SetShaderParameterAnimationWrapMode(const String& name, WrapMode wrapMode)
  487. {
  488. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  489. if (info)
  490. info->SetWrapMode(wrapMode);
  491. }
  492. void Material::SetShaderParameterAnimationSpeed(const String& name, float speed)
  493. {
  494. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  495. if (info)
  496. info->SetSpeed(speed);
  497. }
  498. void Material::SetTexture(TextureUnit unit, Texture* texture)
  499. {
  500. if (unit < MAX_TEXTURE_UNITS)
  501. {
  502. if (texture)
  503. textures_[unit] = texture;
  504. else
  505. textures_.Erase(unit);
  506. }
  507. }
  508. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  509. {
  510. Matrix3x4 transform(Matrix3x4::IDENTITY);
  511. transform.m00_ = repeat.x_;
  512. transform.m11_ = repeat.y_;
  513. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  514. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  515. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  516. rotationMatrix.m00_ = Cos(rotation);
  517. rotationMatrix.m01_ = Sin(rotation);
  518. rotationMatrix.m10_ = -rotationMatrix.m01_;
  519. rotationMatrix.m11_ = rotationMatrix.m00_;
  520. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  521. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  522. transform = rotationMatrix * transform;
  523. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  524. offsetMatrix.m03_ = offset.x_;
  525. offsetMatrix.m13_ = offset.y_;
  526. transform = offsetMatrix * transform;
  527. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  528. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  529. }
  530. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  531. {
  532. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  533. }
  534. void Material::SetCullMode(CullMode mode)
  535. {
  536. cullMode_ = mode;
  537. }
  538. void Material::SetShadowCullMode(CullMode mode)
  539. {
  540. shadowCullMode_ = mode;
  541. }
  542. void Material::SetFillMode(FillMode mode)
  543. {
  544. fillMode_ = mode;
  545. }
  546. void Material::SetDepthBias(const BiasParameters& parameters)
  547. {
  548. depthBias_ = parameters;
  549. depthBias_.Validate();
  550. }
  551. void Material::SetRenderOrder(unsigned char order)
  552. {
  553. renderOrder_ = order;
  554. }
  555. void Material::SetScene(Scene* scene)
  556. {
  557. UnsubscribeFromEvent(E_UPDATE);
  558. UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
  559. subscribed_ = false;
  560. scene_ = scene;
  561. UpdateEventSubscription();
  562. }
  563. void Material::RemoveShaderParameter(const String& name)
  564. {
  565. StringHash nameHash(name);
  566. shaderParameters_.Erase(nameHash);
  567. if (nameHash == PSP_MATSPECCOLOR)
  568. specular_ = false;
  569. RefreshShaderParameterHash();
  570. RefreshMemoryUse();
  571. }
  572. void Material::ReleaseShaders()
  573. {
  574. for (unsigned i = 0; i < techniques_.Size(); ++i)
  575. {
  576. Technique* tech = techniques_[i].technique_;
  577. if (tech)
  578. tech->ReleaseShaders();
  579. }
  580. }
  581. SharedPtr<Material> Material::Clone(const String& cloneName) const
  582. {
  583. SharedPtr<Material> ret(new Material(context_));
  584. ret->SetName(cloneName);
  585. ret->techniques_ = techniques_;
  586. ret->shaderParameters_ = shaderParameters_;
  587. ret->textures_ = textures_;
  588. ret->occlusion_ = occlusion_;
  589. ret->specular_ = specular_;
  590. ret->cullMode_ = cullMode_;
  591. ret->shadowCullMode_ = shadowCullMode_;
  592. ret->fillMode_ = fillMode_;
  593. ret->renderOrder_ = renderOrder_;
  594. ret->RefreshMemoryUse();
  595. return ret;
  596. }
  597. void Material::SortTechniques()
  598. {
  599. Sort(techniques_.Begin(), techniques_.End(), CompareTechniqueEntries);
  600. }
  601. void Material::MarkForAuxView(unsigned frameNumber)
  602. {
  603. auxViewFrameNumber_ = frameNumber;
  604. }
  605. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  606. {
  607. return index < techniques_.Size() ? techniques_[index] : noEntry;
  608. }
  609. Technique* Material::GetTechnique(unsigned index) const
  610. {
  611. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  612. }
  613. Pass* Material::GetPass(unsigned index, const String& passName) const
  614. {
  615. Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  616. return tech ? tech->GetPass(passName) : 0;
  617. }
  618. Texture* Material::GetTexture(TextureUnit unit) const
  619. {
  620. HashMap<TextureUnit, SharedPtr<Texture> >::ConstIterator i = textures_.Find(unit);
  621. return i != textures_.End() ? i->second_.Get() : (Texture*)0;
  622. }
  623. const Variant& Material::GetShaderParameter(const String& name) const
  624. {
  625. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(name);
  626. return i != shaderParameters_.End() ? i->second_.value_ : Variant::EMPTY;
  627. }
  628. ValueAnimation* Material::GetShaderParameterAnimation(const String& name) const
  629. {
  630. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  631. return info == 0 ? 0 : info->GetAnimation();
  632. }
  633. WrapMode Material::GetShaderParameterAnimationWrapMode(const String& name) const
  634. {
  635. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  636. return info == 0 ? WM_LOOP : info->GetWrapMode();
  637. }
  638. float Material::GetShaderParameterAnimationSpeed(const String& name) const
  639. {
  640. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  641. return info == 0 ? 0 : info->GetSpeed();
  642. }
  643. Scene* Material::GetScene() const
  644. {
  645. return scene_;
  646. }
  647. String Material::GetTextureUnitName(TextureUnit unit)
  648. {
  649. return textureUnitNames[unit];
  650. }
  651. Variant Material::ParseShaderParameterValue(const String& value)
  652. {
  653. String valueTrimmed = value.Trimmed();
  654. if (valueTrimmed.Length() && IsAlpha((unsigned)valueTrimmed[0]))
  655. return Variant(ToBool(valueTrimmed));
  656. else
  657. return ToVectorVariant(valueTrimmed);
  658. }
  659. const char** Material::GetTextureUnitNames()
  660. {
  661. return textureUnitNames;
  662. }
  663. void Material::CheckOcclusion()
  664. {
  665. // Determine occlusion by checking the base pass of each technique
  666. occlusion_ = false;
  667. for (unsigned i = 0; i < techniques_.Size(); ++i)
  668. {
  669. Technique* tech = techniques_[i].technique_;
  670. if (tech)
  671. {
  672. Pass* pass = tech->GetPass("base");
  673. if (pass && pass->GetDepthWrite() && !pass->GetAlphaMask())
  674. occlusion_ = true;
  675. }
  676. }
  677. }
  678. void Material::ResetToDefaults()
  679. {
  680. // Needs to be a no-op when async loading, as this does a GetResource() which is not allowed from worker threads
  681. if (!Thread::IsMainThread())
  682. return;
  683. SetNumTechniques(1);
  684. SetTechnique(0, GetSubsystem<ResourceCache>()->GetResource<Technique>("Techniques/NoTexture.xml"));
  685. textures_.Clear();
  686. batchedParameterUpdate_ = true;
  687. shaderParameters_.Clear();
  688. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  689. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  690. SetShaderParameter("MatDiffColor", Vector4::ONE);
  691. SetShaderParameter("MatEmissiveColor", Vector3::ZERO);
  692. SetShaderParameter("MatEnvMapColor", Vector3::ONE);
  693. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  694. batchedParameterUpdate_ = false;
  695. cullMode_ = CULL_CCW;
  696. shadowCullMode_ = CULL_CCW;
  697. fillMode_ = FILL_SOLID;
  698. depthBias_ = BiasParameters(0.0f, 0.0f);
  699. renderOrder_ = DEFAULT_RENDER_ORDER;
  700. RefreshShaderParameterHash();
  701. RefreshMemoryUse();
  702. }
  703. void Material::RefreshShaderParameterHash()
  704. {
  705. VectorBuffer temp;
  706. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Begin();
  707. i != shaderParameters_.End(); ++i)
  708. {
  709. temp.WriteStringHash(i->first_);
  710. temp.WriteVariant(i->second_.value_);
  711. }
  712. shaderParameterHash_ = 0;
  713. const unsigned char* data = temp.GetData();
  714. unsigned dataSize = temp.GetSize();
  715. for (unsigned i = 0; i < dataSize; ++i)
  716. shaderParameterHash_ = SDBMHash(shaderParameterHash_, data[i]);
  717. }
  718. void Material::RefreshMemoryUse()
  719. {
  720. unsigned memoryUse = sizeof(Material);
  721. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  722. memoryUse += MAX_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
  723. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  724. SetMemoryUse(memoryUse);
  725. }
  726. ShaderParameterAnimationInfo* Material::GetShaderParameterAnimationInfo(const String& name) const
  727. {
  728. StringHash nameHash(name);
  729. HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Find(nameHash);
  730. if (i == shaderParameterAnimationInfos_.End())
  731. return 0;
  732. return i->second_;
  733. }
  734. void Material::UpdateEventSubscription()
  735. {
  736. if (shaderParameterAnimationInfos_.Size() && !subscribed_)
  737. {
  738. if (scene_)
  739. SubscribeToEvent(scene_, E_ATTRIBUTEANIMATIONUPDATE, HANDLER(Material, HandleAttributeAnimationUpdate));
  740. else
  741. SubscribeToEvent(E_UPDATE, HANDLER(Material, HandleAttributeAnimationUpdate));
  742. subscribed_ = true;
  743. }
  744. else if (subscribed_)
  745. {
  746. UnsubscribeFromEvent(E_UPDATE);
  747. UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
  748. subscribed_ = false;
  749. }
  750. }
  751. void Material::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  752. {
  753. // Timestep parameter is same no matter what event is being listened to
  754. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  755. Vector<String> finishedNames;
  756. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Begin();
  757. i != shaderParameterAnimationInfos_.End(); ++i)
  758. {
  759. if (i->second_->Update(timeStep))
  760. finishedNames.Push(i->second_->GetName());
  761. }
  762. // Remove finished animations
  763. for (unsigned i = 0; i < finishedNames.Size(); ++i)
  764. SetShaderParameterAnimation(finishedNames[i], 0);
  765. }
  766. }