Material.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. //
  2. // Copyright (c) 2008-2017 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. #pragma once
  23. #include "../Graphics/GraphicsDefs.h"
  24. #include "../Graphics/Light.h"
  25. #include "../Math/Vector4.h"
  26. #include "../Resource/Resource.h"
  27. #include "../Scene/ValueAnimationInfo.h"
  28. namespace Atomic
  29. {
  30. class Material;
  31. class Pass;
  32. class Scene;
  33. class Technique;
  34. class Texture;
  35. class Texture2D;
  36. class TextureCube;
  37. class ValueAnimationInfo;
  38. class JSONFile;
  39. static const unsigned char DEFAULT_RENDER_ORDER = 128;
  40. /// %Material's shader parameter definition.
  41. struct MaterialShaderParameter
  42. {
  43. /// Name.
  44. String name_;
  45. /// Value.
  46. Variant value_;
  47. };
  48. /// %Material's technique list entry.
  49. struct TechniqueEntry
  50. {
  51. /// Construct with defaults.
  52. TechniqueEntry();
  53. /// Construct with parameters.
  54. TechniqueEntry(Technique* tech, unsigned qualityLevel, float lodDistance);
  55. /// Destruct.
  56. ~TechniqueEntry();
  57. /// Technique.
  58. SharedPtr<Technique> technique_;
  59. /// Original technique, in case the material adds shader compilation defines. The modified clones are requested from it.
  60. SharedPtr<Technique> original_;
  61. /// Quality level.
  62. int qualityLevel_;
  63. /// LOD distance.
  64. float lodDistance_;
  65. };
  66. /// Material's shader parameter animation instance.
  67. class ShaderParameterAnimationInfo : public ValueAnimationInfo
  68. {
  69. public:
  70. /// Construct.
  71. ShaderParameterAnimationInfo
  72. (Material* material, const String& name, ValueAnimation* attributeAnimation, WrapMode wrapMode, float speed);
  73. /// Copy construct.
  74. ShaderParameterAnimationInfo(const ShaderParameterAnimationInfo& other);
  75. /// Destruct.
  76. ~ShaderParameterAnimationInfo();
  77. /// Return shader parameter name.
  78. const String& GetName() const { return name_; }
  79. protected:
  80. /// Apply new animation value to the target object. Called by Update().
  81. virtual void ApplyValue(const Variant& newValue);
  82. private:
  83. /// Shader parameter name.
  84. String name_;
  85. };
  86. /// TextureUnit hash function.
  87. template <> inline unsigned MakeHash(const TextureUnit& value)
  88. {
  89. return (unsigned)value;
  90. }
  91. /// Describes how to render 3D geometries.
  92. class ATOMIC_API Material : public Resource
  93. {
  94. ATOMIC_OBJECT(Material, Resource);
  95. public:
  96. /// Construct.
  97. Material(Context* context);
  98. /// Destruct.
  99. ~Material();
  100. /// Register object factory.
  101. static void RegisterObject(Context* context);
  102. /// Load resource from stream. May be called from a worker thread. Return true if successful.
  103. virtual bool BeginLoad(Deserializer& source);
  104. /// Finish resource loading. Always called from the main thread. Return true if successful.
  105. virtual bool EndLoad();
  106. /// Save resource. Return true if successful.
  107. virtual bool Save(Serializer& dest) const;
  108. /// Load from an XML element. Return true if successful.
  109. bool Load(const XMLElement& source);
  110. /// Save to an XML element. Return true if successful.
  111. bool Save(XMLElement& dest) const;
  112. /// Load from a JSON value. Return true if successful.
  113. bool Load(const JSONValue& source);
  114. /// Save to a JSON value. Return true if successful.
  115. bool Save(JSONValue& dest) const;
  116. /// Set number of techniques.
  117. void SetNumTechniques(unsigned num);
  118. /// Set technique.
  119. void SetTechnique(unsigned index, Technique* tech, unsigned qualityLevel = 0, float lodDistance = 0.0f);
  120. /// Set additional vertex shader defines. Separate multiple defines with spaces. Setting defines at the material level causes technique(s) to be cloned as necessary.
  121. void SetVertexShaderDefines(const String& defines);
  122. /// Set additional pixel shader defines. Separate multiple defines with spaces. Setting defines at the material level causes technique(s) to be cloned as necessary.
  123. void SetPixelShaderDefines(const String& defines);
  124. /// Set shader parameter.
  125. void SetShaderParameter(const String& name, const Variant& value);
  126. /// Set shader parameter animation.
  127. void
  128. SetShaderParameterAnimation(const String& name, ValueAnimation* animation, WrapMode wrapMode = WM_LOOP, float speed = 1.0f);
  129. /// Set shader parameter animation wrap mode.
  130. void SetShaderParameterAnimationWrapMode(const String& name, WrapMode wrapMode);
  131. /// Set shader parameter animation speed.
  132. void SetShaderParameterAnimationSpeed(const String& name, float speed);
  133. /// Set texture.
  134. void SetTexture(TextureUnit unit, Texture* texture);
  135. /// Set texture coordinate transform.
  136. void SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat);
  137. /// Set texture coordinate transform.
  138. void SetUVTransform(const Vector2& offset, float rotation, float repeat);
  139. /// Set culling mode.
  140. void SetCullMode(CullMode mode);
  141. /// Set culling mode for shadows.
  142. void SetShadowCullMode(CullMode mode);
  143. /// Set polygon fill mode. Interacts with the camera's fill mode setting so that the "least filled" mode will be used.
  144. void SetFillMode(FillMode mode);
  145. /// Set depth bias parameters for depth write and compare. Note that the normal offset parameter is not used and will not be saved, as it affects only shadow map sampling during light rendering.
  146. void SetDepthBias(const BiasParameters& parameters);
  147. /// Set alpha-to-coverage mode on all passes.
  148. void SetAlphaToCoverage(bool enable);
  149. /// Set line antialiasing on/off. Has effect only on models that consist of line lists.
  150. void SetLineAntiAlias(bool enable);
  151. /// Set 8-bit render order within pass. Default 128. Lower values will render earlier and higher values later, taking precedence over e.g. state and distance sorting.
  152. void SetRenderOrder(unsigned char order);
  153. /// Set whether to use in occlusion rendering. Default true.
  154. void SetOcclusion(bool enable);
  155. /// Associate the material with a scene to ensure that shader parameter animation happens in sync with scene update, respecting the scene time scale. If no scene is set, the global update events will be used.
  156. void SetScene(Scene* scene);
  157. /// Remove shader parameter.
  158. void RemoveShaderParameter(const String& name);
  159. /// Reset all shader pointers.
  160. void ReleaseShaders();
  161. /// Clone the material.
  162. SharedPtr<Material> Clone(const String& cloneName = String::EMPTY) const;
  163. /// Ensure that material techniques are listed in correct order.
  164. void SortTechniques();
  165. /// Mark material for auxiliary view rendering.
  166. void MarkForAuxView(unsigned frameNumber);
  167. /// Return number of techniques.
  168. unsigned GetNumTechniques() const { return techniques_.Size(); }
  169. /// Return all techniques.
  170. const Vector<TechniqueEntry>& GetTechniques() const { return techniques_; }
  171. /// Return technique entry by index.
  172. const TechniqueEntry& GetTechniqueEntry(unsigned index) const;
  173. /// Return technique by index.
  174. Technique* GetTechnique(unsigned index) const;
  175. /// Return pass by technique index and pass name.
  176. Pass* GetPass(unsigned index, const String& passName) const;
  177. /// Return texture by unit.
  178. Texture* GetTexture(TextureUnit unit) const;
  179. /// Return all textures.
  180. const HashMap<TextureUnit, SharedPtr<Texture> >& GetTextures() const { return textures_; }
  181. /// Return additional vertex shader defines.
  182. const String& GetVertexShaderDefines() const { return vertexShaderDefines_; }
  183. /// Return additional pixel shader defines.
  184. const String& GetPixelShaderDefines() const { return pixelShaderDefines_; }
  185. /// Return shader parameter.
  186. const Variant& GetShaderParameter(const String& name) const;
  187. /// Return shader parameter animation.
  188. ValueAnimation* GetShaderParameterAnimation(const String& name) const;
  189. /// Return shader parameter animation wrap mode.
  190. WrapMode GetShaderParameterAnimationWrapMode(const String& name) const;
  191. /// Return shader parameter animation speed.
  192. float GetShaderParameterAnimationSpeed(const String& name) const;
  193. /// Return all shader parameters.
  194. const HashMap<StringHash, MaterialShaderParameter>& GetShaderParameters() const { return shaderParameters_; }
  195. /// Return normal culling mode.
  196. CullMode GetCullMode() const { return cullMode_; }
  197. /// Return culling mode for shadows.
  198. CullMode GetShadowCullMode() const { return shadowCullMode_; }
  199. /// Return polygon fill mode.
  200. FillMode GetFillMode() const { return fillMode_; }
  201. /// Return depth bias.
  202. const BiasParameters& GetDepthBias() const { return depthBias_; }
  203. /// Return alpha-to-coverage mode.
  204. bool GetAlphaToCoverage() const { return alphaToCoverage_; }
  205. /// Return whether line antialiasing is enabled.
  206. bool GetLineAntiAlias() const { return lineAntiAlias_; }
  207. /// Return render order.
  208. unsigned char GetRenderOrder() const { return renderOrder_; }
  209. /// Return last auxiliary view rendered frame number.
  210. unsigned GetAuxViewFrameNumber() const { return auxViewFrameNumber_; }
  211. /// Return whether should render occlusion.
  212. bool GetOcclusion() const { return occlusion_; }
  213. /// Return whether should render specular.
  214. bool GetSpecular() const { return specular_; }
  215. /// Return the scene associated with the material for shader parameter animation updates.
  216. Scene* GetScene() const;
  217. /// Return shader parameter hash value. Used as an optimization to avoid setting shader parameters unnecessarily.
  218. unsigned GetShaderParameterHash() const { return shaderParameterHash_; }
  219. /// Return name for texture unit.
  220. static String GetTextureUnitName(TextureUnit unit);
  221. /// Parse a shader parameter value from a string. Retunrs either a bool, a float, or a 2 to 4-component vector.
  222. static Variant ParseShaderParameterValue(const String& value);
  223. // ATOMIC BEGIN
  224. /// Return the names of supported texture units, with null sentinel on list
  225. static const char** GetTextureUnitNames();
  226. // ATOMIC END
  227. private:
  228. /// Helper function for loading JSON files.
  229. bool BeginLoadJSON(Deserializer& source);
  230. /// Helper function for loading XML files.
  231. bool BeginLoadXML(Deserializer& source);
  232. /// Reset to defaults.
  233. void ResetToDefaults();
  234. /// Recalculate shader parameter hash.
  235. void RefreshShaderParameterHash();
  236. /// Recalculate the memory used by the material.
  237. void RefreshMemoryUse();
  238. /// Reapply shader defines to technique index. By default reapply all.
  239. void ApplyShaderDefines(unsigned index = M_MAX_UNSIGNED);
  240. /// Return shader parameter animation info.
  241. ShaderParameterAnimationInfo* GetShaderParameterAnimationInfo(const String& name) const;
  242. /// Update whether should be subscribed to scene or global update events for shader parameter animation.
  243. void UpdateEventSubscription();
  244. /// Update shader parameter animations.
  245. void HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData);
  246. /// Techniques.
  247. Vector<TechniqueEntry> techniques_;
  248. /// Textures.
  249. HashMap<TextureUnit, SharedPtr<Texture> > textures_;
  250. /// %Shader parameters.
  251. HashMap<StringHash, MaterialShaderParameter> shaderParameters_;
  252. /// %Shader parameters animation infos.
  253. HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> > shaderParameterAnimationInfos_;
  254. /// Vertex shader defines.
  255. String vertexShaderDefines_;
  256. /// Pixel shader defines.
  257. String pixelShaderDefines_;
  258. /// Normal culling mode.
  259. CullMode cullMode_;
  260. /// Culling mode for shadow rendering.
  261. CullMode shadowCullMode_;
  262. /// Polygon fill mode.
  263. FillMode fillMode_;
  264. /// Depth bias parameters.
  265. BiasParameters depthBias_;
  266. /// Render order value.
  267. unsigned char renderOrder_;
  268. /// Last auxiliary view rendered frame number.
  269. unsigned auxViewFrameNumber_;
  270. /// Shader parameter hash value.
  271. unsigned shaderParameterHash_;
  272. /// Alpha-to-coverage flag.
  273. bool alphaToCoverage_;
  274. /// Line antialiasing flag.
  275. bool lineAntiAlias_;
  276. /// Render occlusion flag.
  277. bool occlusion_;
  278. /// Specular lighting flag.
  279. bool specular_;
  280. /// Flag for whether is subscribed to animation updates.
  281. bool subscribed_;
  282. /// Flag to suppress parameter hash and memory use recalculation when setting multiple shader parameters (loading or resetting the material.)
  283. bool batchedParameterUpdate_;
  284. /// XML file used while loading.
  285. SharedPtr<XMLFile> loadXMLFile_;
  286. /// JSON file used while loading.
  287. SharedPtr<JSONFile> loadJSONFile_;
  288. /// Associated scene for shader parameter animation updates.
  289. WeakPtr<Scene> scene_;
  290. };
  291. }