Material.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. //
  2. // Copyright (c) 2008-2013 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 "Context.h"
  24. #include "FileSystem.h"
  25. #include "Graphics.h"
  26. #include "Log.h"
  27. #include "Material.h"
  28. #include "Matrix3x4.h"
  29. #include "Profiler.h"
  30. #include "ResourceCache.h"
  31. #include "StringUtils.h"
  32. #include "Technique.h"
  33. #include "Texture2D.h"
  34. #include "TextureCube.h"
  35. #include "XMLFile.h"
  36. #include "DebugNew.h"
  37. namespace Urho3D
  38. {
  39. static const char* textureUnitNames[] =
  40. {
  41. "diffuse",
  42. "normal",
  43. "specular",
  44. "emissive",
  45. "environment",
  46. "lightramp",
  47. "lightshape",
  48. "shadowmap",
  49. "faceselect",
  50. "indirection",
  51. "depth",
  52. "light",
  53. 0
  54. };
  55. static const char* cullModeNames[] =
  56. {
  57. "none",
  58. "ccw",
  59. "cw",
  60. 0
  61. };
  62. TextureUnit ParseTextureUnitName(const String& name)
  63. {
  64. TextureUnit unit = (TextureUnit)GetStringListIndex(name.CString(), textureUnitNames, MAX_TEXTURE_UNITS);
  65. if (name == "diff")
  66. unit = TU_DIFFUSE;
  67. else if (name == "albedo")
  68. unit = TU_DIFFUSE;
  69. else if (name == "norm")
  70. unit = TU_NORMAL;
  71. else if (name == "spec")
  72. unit = TU_SPECULAR;
  73. else if (name == "env")
  74. unit = TU_ENVIRONMENT;
  75. return unit;
  76. }
  77. static TechniqueEntry noEntry;
  78. TechniqueEntry::TechniqueEntry() :
  79. qualityLevel_(0),
  80. lodDistance_(0.0f)
  81. {
  82. }
  83. TechniqueEntry::TechniqueEntry(Technique* tech, unsigned qualityLevel, float lodDistance) :
  84. technique_(tech),
  85. qualityLevel_(qualityLevel),
  86. lodDistance_(lodDistance)
  87. {
  88. }
  89. TechniqueEntry::~TechniqueEntry()
  90. {
  91. }
  92. OBJECTTYPESTATIC(Material);
  93. Material::Material(Context* context) :
  94. Resource(context),
  95. auxViewFrameNumber_(0),
  96. occlusion_(true),
  97. specular_(false)
  98. {
  99. SetNumTechniques(1);
  100. ResetToDefaults();
  101. }
  102. Material::~Material()
  103. {
  104. }
  105. void Material::RegisterObject(Context* context)
  106. {
  107. context->RegisterFactory<Material>();
  108. }
  109. bool Material::Load(Deserializer& source)
  110. {
  111. PROFILE(LoadMaterial);
  112. // In headless mode, do not actually load the material, just return success
  113. Graphics* graphics = GetSubsystem<Graphics>();
  114. if (!graphics)
  115. return true;
  116. ResetToDefaults();
  117. ResourceCache* cache = GetSubsystem<ResourceCache>();
  118. SharedPtr<XMLFile> xml(new XMLFile(context_));
  119. if (!xml->Load(source))
  120. return false;
  121. XMLElement rootElem = xml->GetRoot();
  122. XMLElement techniqueElem = rootElem.GetChild("technique");
  123. techniques_.Clear();
  124. while (techniqueElem)
  125. {
  126. Technique* tech = cache->GetResource<Technique>(techniqueElem.GetAttribute("name"));
  127. if (tech)
  128. {
  129. TechniqueEntry newTechnique;
  130. newTechnique.technique_ = tech;
  131. if (techniqueElem.HasAttribute("quality"))
  132. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  133. if (techniqueElem.HasAttribute("loddistance"))
  134. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  135. techniques_.Push(newTechnique);
  136. }
  137. techniqueElem = techniqueElem.GetNext("technique");
  138. }
  139. XMLElement textureElem = rootElem.GetChild("texture");
  140. while (textureElem)
  141. {
  142. TextureUnit unit = TU_DIFFUSE;
  143. if (textureElem.HasAttribute("unit"))
  144. {
  145. String unitName = textureElem.GetAttributeLower("unit");
  146. if (unitName.Length() > 1)
  147. {
  148. unit = ParseTextureUnitName(unitName);
  149. if (unit >= MAX_MATERIAL_TEXTURE_UNITS)
  150. LOGERROR("Unknown or illegal texture unit " + unitName);
  151. }
  152. else
  153. unit = (TextureUnit)Clamp(ToInt(unitName), 0, MAX_MATERIAL_TEXTURE_UNITS - 1);
  154. }
  155. if (unit != MAX_MATERIAL_TEXTURE_UNITS)
  156. {
  157. String name = textureElem.GetAttribute("name");
  158. // Detect cube maps by file extension: they are defined by an XML file
  159. if (GetExtension(name) == ".xml")
  160. SetTexture(unit, cache->GetResource<TextureCube>(name));
  161. else
  162. SetTexture(unit, cache->GetResource<Texture2D>(name));
  163. }
  164. textureElem = textureElem.GetNext("texture");
  165. }
  166. XMLElement parameterElem = rootElem.GetChild("parameter");
  167. while (parameterElem)
  168. {
  169. String name = parameterElem.GetAttribute("name");
  170. Vector4 value = parameterElem.GetVector("value");
  171. SetShaderParameter(name, value);
  172. parameterElem = parameterElem.GetNext("parameter");
  173. }
  174. XMLElement cullElem = rootElem.GetChild("cull");
  175. if (cullElem)
  176. SetCullMode((CullMode)GetStringListIndex(cullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  177. XMLElement shadowCullElem = rootElem.GetChild("shadowcull");
  178. if (shadowCullElem)
  179. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  180. XMLElement depthBiasElem = rootElem.GetChild("depthbias");
  181. if (depthBiasElem)
  182. SetDepthBias(BiasParameters(depthBiasElem.GetFloat("constant"), depthBiasElem.GetFloat("slopescaled")));
  183. // Calculate memory use
  184. unsigned memoryUse = sizeof(Material);
  185. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  186. memoryUse += MAX_MATERIAL_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
  187. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  188. SetMemoryUse(memoryUse);
  189. CheckOcclusion();
  190. return true;
  191. }
  192. bool Material::Save(Serializer& dest) const
  193. {
  194. SharedPtr<XMLFile> xml(new XMLFile(context_));
  195. XMLElement materialElem = xml->CreateRoot("material");
  196. // Write techniques
  197. for (unsigned i = 0; i < techniques_.Size(); ++i)
  198. {
  199. const TechniqueEntry& entry = techniques_[i];
  200. if (!entry.technique_)
  201. continue;
  202. XMLElement techniqueElem = materialElem.CreateChild("technique");
  203. techniqueElem.SetString("name", entry.technique_->GetName());
  204. techniqueElem.SetInt("quality", entry.qualityLevel_);
  205. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  206. }
  207. // Write texture units
  208. for (unsigned j = 0; j < MAX_MATERIAL_TEXTURE_UNITS; ++j)
  209. {
  210. Texture* texture = GetTexture((TextureUnit)j);
  211. if (texture)
  212. {
  213. XMLElement textureElem = materialElem.CreateChild("texture");
  214. textureElem.SetString("unit", textureUnitNames[j]);
  215. textureElem.SetString("name", texture->GetName());
  216. }
  217. }
  218. // Write shader parameters
  219. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin(); j != shaderParameters_.End(); ++j)
  220. {
  221. XMLElement parameterElem = materialElem.CreateChild("parameter");
  222. parameterElem.SetString("name", j->second_.name_);
  223. parameterElem.SetVector4("value", j->second_.value_);
  224. }
  225. // Write culling modes
  226. XMLElement cullElem = materialElem.CreateChild("cull");
  227. cullElem.SetString("value", cullModeNames[cullMode_]);
  228. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  229. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  230. // Write depth bias
  231. XMLElement depthBiasElem = materialElem.CreateChild("depthbias");
  232. depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
  233. depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
  234. return xml->Save(dest);
  235. }
  236. void Material::SetNumTechniques(unsigned num)
  237. {
  238. if (!num)
  239. return;
  240. techniques_.Resize(num);
  241. }
  242. void Material::SetTechnique(unsigned index, Technique* tech, unsigned qualityLevel, float lodDistance)
  243. {
  244. if (index >= techniques_.Size())
  245. return;
  246. techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
  247. CheckOcclusion();
  248. }
  249. void Material::SetShaderParameter(const String& name, const Vector4& value)
  250. {
  251. MaterialShaderParameter newParam;
  252. newParam.name_ = name;
  253. newParam.value_ = value;
  254. StringHash nameHash(name);
  255. shaderParameters_[nameHash] = newParam;
  256. if (nameHash == PSP_MATSPECCOLOR)
  257. specular_ = value.x_ > 0.0f || value.y_ > 0.0f || value.z_ > 0.0f;
  258. }
  259. void Material::SetTexture(TextureUnit unit, Texture* texture)
  260. {
  261. if (unit < MAX_MATERIAL_TEXTURE_UNITS)
  262. textures_[unit] = texture;
  263. }
  264. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  265. {
  266. Matrix3x4 transform(Matrix3x4::IDENTITY);
  267. transform.m00_ = repeat.x_;
  268. transform.m11_ = repeat.y_;
  269. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  270. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  271. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  272. float angleRad = rotation * M_DEGTORAD;
  273. rotationMatrix.m00_ = cosf(angleRad);
  274. rotationMatrix.m01_ = sinf(angleRad);
  275. rotationMatrix.m10_ = -rotationMatrix.m01_;
  276. rotationMatrix.m11_ = rotationMatrix.m00_;
  277. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  278. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  279. transform = rotationMatrix * transform;
  280. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  281. offsetMatrix.m03_ = offset.x_;
  282. offsetMatrix.m13_ = offset.y_;
  283. transform = offsetMatrix * transform;
  284. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  285. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  286. }
  287. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  288. {
  289. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  290. }
  291. void Material::SetCullMode(CullMode mode)
  292. {
  293. cullMode_ = mode;
  294. }
  295. void Material::SetShadowCullMode(CullMode mode)
  296. {
  297. shadowCullMode_ = mode;
  298. }
  299. void Material::SetDepthBias(const BiasParameters& parameters)
  300. {
  301. depthBias_ = parameters;
  302. depthBias_.Validate();
  303. }
  304. void Material::RemoveShaderParameter(const String& name)
  305. {
  306. StringHash nameHash(name);
  307. shaderParameters_.Erase(nameHash);
  308. if (nameHash == PSP_MATSPECCOLOR)
  309. specular_ = false;
  310. }
  311. void Material::ReleaseShaders()
  312. {
  313. for (unsigned i = 0; i < techniques_.Size(); ++i)
  314. {
  315. Technique* tech = techniques_[i].technique_;
  316. if (tech)
  317. tech->ReleaseShaders();
  318. }
  319. }
  320. SharedPtr<Material> Material::Clone(const String& cloneName) const
  321. {
  322. SharedPtr<Material> ret(new Material(context_));
  323. ret->SetName(cloneName);
  324. ret->techniques_ = techniques_;
  325. ret->shaderParameters_ = shaderParameters_;
  326. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  327. ret->textures_[i] = textures_[i];
  328. ret->occlusion_ = occlusion_;
  329. ret->cullMode_ = cullMode_;
  330. ret->shadowCullMode_ = shadowCullMode_;
  331. return ret;
  332. }
  333. void Material::MarkForAuxView(unsigned frameNumber)
  334. {
  335. auxViewFrameNumber_ = frameNumber;
  336. }
  337. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  338. {
  339. return index < techniques_.Size() ? techniques_[index] : noEntry;
  340. }
  341. Technique* Material::GetTechnique(unsigned index) const
  342. {
  343. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  344. }
  345. Pass* Material::GetPass(unsigned index, StringHash passType) const
  346. {
  347. Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  348. return tech ? tech->GetPass(passType) : 0;
  349. }
  350. Texture* Material::GetTexture(TextureUnit unit) const
  351. {
  352. return unit < MAX_MATERIAL_TEXTURE_UNITS ? textures_[unit] : (Texture*)0;
  353. }
  354. const Vector4& Material::GetShaderParameter(const String& name) const
  355. {
  356. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(name);
  357. return i != shaderParameters_.End() ? i->second_.value_ : Vector4::ZERO;
  358. }
  359. String Material::GetTextureUnitName(TextureUnit unit)
  360. {
  361. return textureUnitNames[unit];
  362. }
  363. void Material::CheckOcclusion()
  364. {
  365. // Determine occlusion by checking the base pass of each technique
  366. occlusion_ = false;
  367. for (unsigned i = 0; i < techniques_.Size(); ++i)
  368. {
  369. Technique* tech = techniques_[i].technique_;
  370. if (tech)
  371. {
  372. Pass* pass = tech->GetPass(PASS_BASE);
  373. if (pass && pass->GetDepthWrite() && !pass->GetAlphaMask())
  374. occlusion_ = true;
  375. }
  376. }
  377. }
  378. void Material::ResetToDefaults()
  379. {
  380. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  381. textures_[i] = 0;
  382. shaderParameters_.Clear();
  383. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  384. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  385. SetShaderParameter("MatDiffColor", Vector4::ONE);
  386. SetShaderParameter("MatEmissiveColor", Vector4::ZERO);
  387. SetShaderParameter("MatEnvMapColor", Vector4::ONE);
  388. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  389. cullMode_ = CULL_CCW;
  390. shadowCullMode_ = CULL_CCW;
  391. depthBias_ = BiasParameters(0.0f, 0.0f);
  392. }
  393. }