Material.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Context.h"
  25. #include "FileSystem.h"
  26. #include "Graphics.h"
  27. #include "Log.h"
  28. #include "Material.h"
  29. #include "Matrix4x3.h"
  30. #include "Profiler.h"
  31. #include "ResourceCache.h"
  32. #include "StringUtils.h"
  33. #include "Technique.h"
  34. #include "Texture2D.h"
  35. #include "TextureCube.h"
  36. #include "XMLFile.h"
  37. #include "DebugNew.h"
  38. static const String textureUnitNames[] =
  39. {
  40. "diffuse",
  41. "normal",
  42. "specular",
  43. "detail",
  44. "environment",
  45. "emissive",
  46. "lightramp", // Not defined by materials
  47. "lightspot" // Not defined by materials
  48. };
  49. static const String cullModeNames[] =
  50. {
  51. "none",
  52. "ccw",
  53. "cw"
  54. };
  55. TechniqueEntry::TechniqueEntry() :
  56. qualityLevel_(0),
  57. lodDistance_(0.0f)
  58. {
  59. }
  60. TechniqueEntry::TechniqueEntry(Technique* technique, unsigned qualityLevel, float lodDistance) :
  61. technique_(technique),
  62. qualityLevel_(qualityLevel),
  63. lodDistance_(lodDistance)
  64. {
  65. }
  66. TechniqueEntry::~TechniqueEntry()
  67. {
  68. }
  69. OBJECTTYPESTATIC(Material);
  70. Material::Material(Context* context) :
  71. Resource(context),
  72. cullMode_(CULL_CCW),
  73. shadowCullMode_(CULL_CCW),
  74. auxViewFrameNumber_(0),
  75. occlusion_(true)
  76. {
  77. SetNumTechniques(1);
  78. textures_.Resize(MAX_MATERIAL_TEXTURE_UNITS);
  79. // Setup often used default parameters
  80. vsParameters_[VSP_UOFFSET] = Vector4(1.0f, 0.0f, 0.0f, 0.0f);
  81. vsParameters_[VSP_VOFFSET] = Vector4(0.0f, 1.0f, 0.0f, 0.0f);
  82. psParameters_[PSP_MATDIFFCOLOR] = Vector4::UNITY;
  83. psParameters_[PSP_MATEMISSIVECOLOR] = Vector4::ZERO;
  84. psParameters_[PSP_MATSPECPROPERTIES] = Vector4::ZERO;
  85. }
  86. Material::~Material()
  87. {
  88. }
  89. void Material::RegisterObject(Context* context)
  90. {
  91. context->RegisterFactory<Material>();
  92. }
  93. bool Material::Load(Deserializer& source)
  94. {
  95. PROFILE(LoadMaterial);
  96. ResourceCache* cache = GetSubsystem<ResourceCache>();
  97. Graphics* graphics = GetSubsystem<Graphics>();
  98. if ((!cache) || (!graphics))
  99. return false;
  100. SharedPtr<XMLFile> xml(new XMLFile(context_));
  101. if (!xml->Load(source))
  102. return false;
  103. XMLElement rootElem = xml->GetRootElement();
  104. XMLElement techniqueElem = rootElem.GetChildElement("technique");
  105. techniques_.Clear();
  106. while (techniqueElem)
  107. {
  108. Technique* technique = cache->GetResource<Technique>(techniqueElem.GetString("name"));
  109. if (technique)
  110. {
  111. TechniqueEntry newTechnique;
  112. newTechnique.technique_ = technique;
  113. if (techniqueElem.HasAttribute("quality"))
  114. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  115. if (techniqueElem.HasAttribute("loddistance"))
  116. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  117. techniques_.Push(newTechnique);
  118. }
  119. techniqueElem = techniqueElem.GetNextElement("technique");
  120. }
  121. XMLElement textureElem = rootElem.GetChildElement("texture");
  122. while (textureElem)
  123. {
  124. TextureUnit unit = TU_DIFFUSE;
  125. if (textureElem.HasAttribute("unit"))
  126. {
  127. String unitName = textureElem.GetStringLower("unit");
  128. unit = (TextureUnit)GetStringListIndex(unitName, textureUnitNames, MAX_MATERIAL_TEXTURE_UNITS,
  129. MAX_MATERIAL_TEXTURE_UNITS);
  130. if (unitName == "diff")
  131. unit = TU_DIFFUSE;
  132. if (unitName == "norm")
  133. unit = TU_NORMAL;
  134. if (unitName == "spec")
  135. unit = TU_SPECULAR;
  136. if (unitName == "env")
  137. unit = TU_ENVIRONMENT;
  138. if (unit == MAX_MATERIAL_TEXTURE_UNITS)
  139. LOGERROR("Unknown texture unit " + unitName);
  140. }
  141. if (unit != MAX_MATERIAL_TEXTURE_UNITS)
  142. {
  143. String name = textureElem.GetString("name");
  144. // Detect cube maps by file extension: they are defined by an XML file
  145. if (GetExtension(name) == ".xml")
  146. SetTexture(unit, cache->GetResource<TextureCube>(name));
  147. else
  148. SetTexture(unit, cache->GetResource<Texture2D>(name));
  149. }
  150. textureElem = textureElem.GetNextElement("texture");
  151. }
  152. XMLElement parameterElem = rootElem.GetChildElement("parameter");
  153. while (parameterElem)
  154. {
  155. String name = parameterElem.GetString("name");
  156. Vector4 value = parameterElem.GetVector("value");
  157. VSParameter vsParam = graphics->GetVSParameter(name);
  158. if (vsParam != MAX_VS_PARAMETERS)
  159. SetVertexShaderParameter(vsParam, value);
  160. else
  161. {
  162. PSParameter psParam = graphics->GetPSParameter(name);
  163. if (psParam != MAX_PS_PARAMETERS)
  164. SetPixelShaderParameter(psParam, value);
  165. else
  166. LOGERROR("Unknown shader parameter " + name);
  167. }
  168. parameterElem = parameterElem.GetNextElement("parameter");
  169. }
  170. XMLElement cullElem = rootElem.GetChildElement("cull");
  171. if (cullElem)
  172. SetCullMode((CullMode)GetStringListIndex(cullElem.GetString("value"), cullModeNames, MAX_CULLMODES, CULL_CCW));
  173. XMLElement shadowCullElem = rootElem.GetChildElement("shadowcull");
  174. if (shadowCullElem)
  175. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetString("value"), cullModeNames, MAX_CULLMODES, CULL_CCW));
  176. // Calculate memory use
  177. unsigned memoryUse = 0;
  178. memoryUse += sizeof(Material);
  179. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  180. memoryUse += textures_.Size() * sizeof(SharedPtr<Texture>);
  181. memoryUse += vsParameters_.Size() * (sizeof(VSParameter) + sizeof(Vector4));
  182. memoryUse += psParameters_.Size() * (sizeof(PSParameter) + sizeof(Vector4));
  183. SetMemoryUse(memoryUse);
  184. Update();
  185. return true;
  186. }
  187. bool Material::Save(Serializer& dest)
  188. {
  189. Graphics* graphics = GetSubsystem<Graphics>();
  190. if (!graphics)
  191. return false;
  192. SharedPtr<XMLFile> xml(new XMLFile(context_));
  193. XMLElement materialElem = xml->CreateRootElement("material");
  194. // Write techniques
  195. for (unsigned i = 0; i < techniques_.Size(); ++i)
  196. {
  197. TechniqueEntry& entry = techniques_[i];
  198. if (!entry.technique_)
  199. continue;
  200. XMLElement techniqueElem = materialElem.CreateChildElement("technique");
  201. techniqueElem.SetString("name", entry.technique_->GetName());
  202. techniqueElem.SetInt("quality", entry.qualityLevel_);
  203. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  204. }
  205. // Write texture units
  206. for (unsigned j = 0; j < MAX_MATERIAL_TEXTURE_UNITS; ++j)
  207. {
  208. Texture* texture = GetTexture((TextureUnit)j);
  209. if (texture)
  210. {
  211. XMLElement textureElem = materialElem.CreateChildElement("texture");
  212. textureElem.SetString("unit", textureUnitNames[j]);
  213. textureElem.SetString("name", texture->GetName());
  214. }
  215. }
  216. // Write shader parameters
  217. for (Map<VSParameter, Vector4>::ConstIterator j = vsParameters_.Begin(); j != vsParameters_.End(); ++j)
  218. {
  219. XMLElement parameterElem = materialElem.CreateChildElement("parameter");
  220. parameterElem.SetString("name", graphics->GetVSParameterName(j->first_));
  221. parameterElem.SetVector4("value", j->second_);
  222. }
  223. for (Map<PSParameter, Vector4>::ConstIterator j = psParameters_.Begin(); j != psParameters_.End(); ++j)
  224. {
  225. XMLElement parameterElem = materialElem.CreateChildElement("parameter");
  226. parameterElem.SetString("name", graphics->GetPSParameterName(j->first_));
  227. parameterElem.SetVector4("value", j->second_);
  228. }
  229. return xml->Save(dest);
  230. }
  231. void Material::SetNumTechniques(unsigned num)
  232. {
  233. if (!num)
  234. return;
  235. techniques_.Resize(num);
  236. }
  237. void Material::SetTechnique(unsigned index, Technique* technique, unsigned qualityLevel, float lodDistance)
  238. {
  239. if (index >= techniques_.Size())
  240. return;
  241. techniques_[index] = TechniqueEntry(technique, qualityLevel, lodDistance);
  242. Update();
  243. }
  244. void Material::SetVertexShaderParameter(VSParameter parameter, const Vector4& value)
  245. {
  246. vsParameters_[parameter] = value;
  247. }
  248. void Material::SetPixelShaderParameter(PSParameter parameter, const Vector4& value)
  249. {
  250. psParameters_[parameter] = value;
  251. }
  252. void Material::SetTexture(TextureUnit unit, Texture* texture)
  253. {
  254. if (unit >= MAX_MATERIAL_TEXTURE_UNITS)
  255. return;
  256. textures_[unit] = texture;
  257. }
  258. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  259. {
  260. Matrix4x3 transform(Matrix4x3::IDENTITY);
  261. transform.m00_ = repeat.x_;
  262. transform.m11_ = repeat.y_;
  263. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  264. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  265. Matrix4x3 rotationMatrix(Matrix4x3::IDENTITY);
  266. float angleRad = rotation * M_DEGTORAD;
  267. rotationMatrix.m00_ = cosf(angleRad);
  268. rotationMatrix.m01_ = sinf(angleRad);
  269. rotationMatrix.m10_ = -rotationMatrix.m01_;
  270. rotationMatrix.m11_ = rotationMatrix.m00_;
  271. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  272. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  273. transform = rotationMatrix * transform;
  274. Matrix4x3 offsetMatrix = Matrix4x3::IDENTITY;
  275. offsetMatrix.m03_ = offset.x_;
  276. offsetMatrix.m13_ = offset.y_;
  277. transform = offsetMatrix * transform;
  278. Vector4& uOffset = vsParameters_[VSP_UOFFSET];
  279. Vector4& vOffset = vsParameters_[VSP_VOFFSET];
  280. uOffset.x_ = transform.m00_;
  281. uOffset.y_ = transform.m01_;
  282. uOffset.w_ = transform.m03_;
  283. vOffset.x_ = transform.m10_;
  284. vOffset.y_ = transform.m11_;
  285. vOffset.w_ = 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::ReleaseShaders()
  300. {
  301. for (unsigned i = 0; i < techniques_.Size(); ++i)
  302. {
  303. Technique* technique = techniques_[i].technique_;
  304. if (technique)
  305. technique->ReleaseShaders();
  306. }
  307. }
  308. SharedPtr<Material> Material::Clone(const String& cloneName) const
  309. {
  310. SharedPtr<Material> ret(new Material(context_));
  311. ret->SetName(cloneName);
  312. ret->techniques_ = techniques_;
  313. ret->vsParameters_ = vsParameters_;
  314. ret->psParameters_ = psParameters_;
  315. ret->textures_ = textures_;
  316. ret->occlusion_ = occlusion_;
  317. ret->cullMode_ = cullMode_;
  318. ret->shadowCullMode_ = shadowCullMode_;
  319. return ret;
  320. }
  321. void Material::MarkForAuxView(unsigned frameNumber)
  322. {
  323. auxViewFrameNumber_ = frameNumber;
  324. }
  325. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  326. {
  327. TechniqueEntry noEntry;
  328. return index < techniques_.Size() ? techniques_[index] : noEntry;
  329. }
  330. Technique* Material::GetTechnique(unsigned index) const
  331. {
  332. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  333. }
  334. Pass* Material::GetPass(unsigned index, PassType pass) const
  335. {
  336. Technique* technique = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  337. return technique ? technique->GetPass(pass) : 0;
  338. }
  339. Texture* Material::GetTexture(TextureUnit unit) const
  340. {
  341. return (unsigned)unit < textures_.Size() ? textures_[unit] : (Texture*)0;
  342. }
  343. const String& Material::GetTextureUnitName(TextureUnit unit)
  344. {
  345. return textureUnitNames[unit];
  346. }
  347. void Material::Update()
  348. {
  349. // Determine occlusion by checking the first pass of each technique
  350. occlusion_ = false;
  351. for (unsigned i = 0; i < techniques_.Size(); ++i)
  352. {
  353. Technique* technique = techniques_[i].technique_;
  354. if (!technique)
  355. continue;
  356. const Map<PassType, Pass>& passes = technique->GetPasses();
  357. if (!passes.Empty())
  358. {
  359. // If pass writes depth, enable occlusion
  360. const Pass& pass = passes.Begin()->second_;
  361. if (pass.GetDepthWrite())
  362. {
  363. occlusion_ = true;
  364. break;
  365. }
  366. }
  367. }
  368. }