BsShader.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsCorePrerequisites.h"
  5. #include "BsResource.h"
  6. #include "BsStringID.h"
  7. #include "BsResourceMetaData.h"
  8. namespace BansheeEngine
  9. {
  10. /** @addtogroup Material
  11. * @{
  12. */
  13. /**
  14. * Describes a single data (int, Vector2, etc.) shader parameter.
  15. *
  16. * @see Shader::addParameter().
  17. */
  18. struct SHADER_DATA_PARAM_DESC
  19. {
  20. String name;
  21. String gpuVariableName;
  22. GpuParamDataType type;
  23. StringID rendererSemantic;
  24. UINT32 arraySize;
  25. UINT32 elementSize;
  26. UINT32 defaultValueIdx;
  27. };
  28. /**
  29. * Describes a single object (texture, sampler state, etc.) shader parameter.
  30. *
  31. * @see Shader::addParameter().
  32. */
  33. struct SHADER_OBJECT_PARAM_DESC
  34. {
  35. String name;
  36. Vector<String> gpuVariableNames;
  37. StringID rendererSemantic;
  38. GpuParamObjectType type;
  39. UINT32 defaultValueIdx;
  40. };
  41. /** Describes a shader parameter block. */
  42. struct SHADER_PARAM_BLOCK_DESC
  43. {
  44. String name;
  45. bool shared;
  46. StringID rendererSemantic;
  47. GpuParamBlockUsage usage;
  48. };
  49. /** @} */
  50. /** @addtogroup Implementation
  51. * @{
  52. */
  53. /** Structure used for initializing a shader. */
  54. template<bool Core>
  55. struct BS_CORE_EXPORT TSHADER_DESC
  56. {
  57. template<bool Core> struct TTextureType {};
  58. template<> struct TTextureType < false > { typedef HTexture Type; };
  59. template<> struct TTextureType < true > { typedef SPtr<TextureCore> Type; };
  60. template<bool Core> struct TSamplerStateType {};
  61. template<> struct TSamplerStateType < false > { typedef SamplerStatePtr Type; };
  62. template<> struct TSamplerStateType < true > { typedef SPtr<SamplerStateCore> Type; };
  63. typedef typename TTextureType<Core>::Type TextureType;
  64. typedef typename TSamplerStateType<Core>::Type SamplerStateType;
  65. TSHADER_DESC();
  66. /**
  67. * Registers a new data (int, Vector2, etc.) parameter you that you may then use via Material by providing the
  68. * parameter name. All parameters internally map to variables defined in GPU programs.
  69. *
  70. * @param[in] name The name of the parameter. Name must be unique between all data and object parameters.
  71. * @param[in] gpuVariableName Name of the GPU variable in the GpuProgram that the parameter corresponds with.
  72. * @param[in] type The type of the parameter, must be the same as the type in GpuProgram.
  73. * @param[in] rendererSemantic (optional) Semantic that allows you to specify the use of this parameter in the
  74. * renderer. The actual value of the semantic depends on the current Renderer and
  75. * its supported list of semantics. Elements with renderer semantics should not be
  76. * updated by the user, and will be updated by the renderer. These semantics will
  77. * also be used to determine if a shader is compatible with a specific renderer
  78. * or not. Value of 0 signifies the parameter is not used by the renderer.
  79. * @param[in] arraySize (optional) If the parameter is an array, the number of elements in the array.
  80. * Size of 1 means its not an array.
  81. * @param[in] elementSize (optional) Size of an individual element in the array, in bytes. You only need
  82. * to set this if you are setting variable length parameters, like structs.
  83. * @param[in] defaultValue (optional) Pointer to the buffer containing the default value for this parameter
  84. * (initial value that will be set when a material is initialized with this shader).
  85. * The provided buffer must be of the correct size (depending on the element type
  86. * and array size).
  87. *
  88. * @note If multiple parameters are given with the same name but different types behavior is undefined.
  89. */
  90. void addParameter(const String& name, const String& gpuVariableName, GpuParamDataType type, StringID rendererSemantic = StringID::NONE,
  91. UINT32 arraySize = 1, UINT32 elementSize = 0, UINT8* defaultValue = nullptr);
  92. /**
  93. * Registers a new object (texture, sampler state, etc.) parameter you that you may then use via Material by
  94. * providing the parameter name. All parameters internally map to variables defined in GPU programs. Multiple GPU
  95. * variables may be mapped to a single parameter in which case the first variable actually found in the program will
  96. * be used while others will be ignored.
  97. *
  98. * @param[in] name The name of the parameter. Name must be unique between all data and object parameters.
  99. * @param[in] gpuVariableName Name of the GPU variable in the GpuProgram that the parameter corresponds with.
  100. * @param[in] type The type of the parameter, must be the same as the type in GpuProgram.
  101. * @param[in] rendererSemantic (optional) Semantic that allows you to specify the use of this parameter in the
  102. * renderer. The actual value of the semantic depends on the current Renderer and
  103. * its supported list of semantics. Elements with renderer semantics should not be
  104. * updated by the user, and will be updated by the renderer. These semantics will
  105. * also be used to determine if a shader is compatible with a specific renderer or
  106. * not. Value of 0 signifies the parameter is not used by the renderer.
  107. *
  108. * @note
  109. * If multiple parameters are given with the same name but different types behavior is undefined. You are allowed
  110. * to call this method multiple times in order to map multiple GPU variable names to a single parameter, but the
  111. * default value (if any) will only be recognized on the first call. Mapping multiple GPU variables to a single
  112. * parameter is useful when you are defining a shader that supports techniques across different render systems
  113. * where GPU variable names for the same parameters might differ.
  114. */
  115. void addParameter(const String& name, const String& gpuVariableName, GpuParamObjectType type, StringID rendererSemantic = StringID::NONE);
  116. /**
  117. * @see SHADER_DESC::addParameter(const String&, const String&, GpuParamObjectType, StringID)
  118. *
  119. * @note
  120. * Specialized version of addParameter that accepts a default sampler value that will be used for initializing the
  121. * object parameter upon Material creation. Default sampler value is only valid if the object type is one of the
  122. * sampler types.
  123. */
  124. void addParameter(const String& name, const String& gpuVariableName, GpuParamObjectType type,
  125. const SamplerStateType& defaultValue, StringID rendererSemantic = StringID::NONE);
  126. /**
  127. * @see SHADER_DESC::addParameter(const String&, const String&, GpuParamObjectType, StringID)
  128. *
  129. * @note
  130. * Specialized version of addParameter that accepts a default texture value that will be used for initializing the
  131. * object parameter upon Material creation. Default texture value is only valid if the object type is one of the
  132. * texture types.
  133. */
  134. void addParameter(const String& name, const String& gpuVariableName, GpuParamObjectType type,
  135. const TextureType& defaultValue, StringID rendererSemantic = StringID::NONE);
  136. /**
  137. * Changes parameters of a parameter block with the specified name.
  138. *
  139. * @param[in] name Name of the parameter block. This should correspond with the name specified in
  140. * the GPU program code.
  141. * @param[in] shared If parameter block is marked as shared it will not be automatically created by
  142. * the Material. You will need to create it elsewhere and then assign it manually.
  143. * @param[in] usage Specified how often do we plan on modifying the buffer, which determines how is
  144. * the buffer internally stored for best performance.
  145. * @param[in] rendererSemantic (optional) Semantic that allows you to specify the use of this parameter block
  146. * in the renderer. The actual value of the semantic depends on the current
  147. * Renderer and its supported list of semantics. Elements with a renderer semantic
  148. * will not have their parameter block automatically created (similar to "shared"
  149. * argument), but instead a Renderer will create an assign it instead. Be aware
  150. * that renderers have strict policies on what and how are parameters stored in the
  151. * buffer and you will need to respect them. If you don't respect them your shader
  152. * will be deemed incompatible and won't be used. Value of 0 signifies the parameter
  153. * block is not used by the renderer.
  154. */
  155. void setParamBlockAttribs(const String& name, bool shared, GpuParamBlockUsage usage, StringID rendererSemantic = StringID::NONE);
  156. /**
  157. * Sorting type to use when performing sort in the render queue. Default value is sort front to back which causes
  158. * least overdraw and is preferable. Transparent objects need to be sorted back to front. You may also specify no
  159. * sorting and the elements will be rendered in the order they were added to the render queue.
  160. */
  161. QueueSortType queueSortType;
  162. /**
  163. * Priority that allows you to control in what order are your shaders rendered. See QueuePriority for a list of
  164. * initial values. Shaders with higher priority will be rendered before shaders with lower priority, and
  165. * additionally render queue will only sort elements within the same priority group.
  166. *
  167. * @note
  168. * This is useful when you want all your opaque objects to be rendered before you start drawing your transparent
  169. * ones. Or to render your overlays after everything else. Values provided in QueuePriority are just for general
  170. * guidance and feel free to increase them or decrease them for finer tuning. (for example QueuePriority::Opaque +
  171. * 1).
  172. */
  173. INT32 queuePriority;
  174. /**
  175. * Enables or disables separable passes. When separable passes are disabled all shader passes will be executed in a
  176. * sequence one after another. If it is disabled the renderer is free to mix and match passes from different
  177. * objects to achieve best performance. (They will still be executed in sequence, but some other object may be
  178. * rendered in-between passes)
  179. *
  180. * @note Shaders with transparency generally can't be separable, while opaque can.
  181. */
  182. bool separablePasses;
  183. /** Flags that let the renderer know how should it interpret the shader. */
  184. UINT32 flags;
  185. Map<String, SHADER_DATA_PARAM_DESC> dataParams;
  186. Map<String, SHADER_OBJECT_PARAM_DESC> textureParams;
  187. Map<String, SHADER_OBJECT_PARAM_DESC> bufferParams;
  188. Map<String, SHADER_OBJECT_PARAM_DESC> samplerParams;
  189. Map<String, SHADER_PARAM_BLOCK_DESC> paramBlocks;
  190. Vector<UINT8> dataDefaultValues;
  191. Vector<SamplerStateType> samplerDefaultValues;
  192. Vector<TextureType> textureDefaultValues;
  193. private:
  194. /**
  195. * @copydoc addParameter(const String&, const String&, GpuParamObjectType, StringID)
  196. *
  197. * @note Common method shared by different addParameter overloads.
  198. */
  199. void addParameterInternal(const String& name, const String& gpuVariableName, GpuParamObjectType type, StringID rendererSemantic, UINT32 defaultValueIdx);
  200. };
  201. /**
  202. * Shader represents a collection of techniques. They are used in Materials, which can be considered as instances of a
  203. * Shader. Multiple materials may share the same shader but provide different parameters to it.
  204. *
  205. * Shader will always choose the first supported technique based on the current render system, render manager and other
  206. * properties. So make sure to add most important techniques first so you make sure they are used if they are supported.
  207. *
  208. * @note Templated version of Shader used for implementing both sim and core thread variants.
  209. */
  210. template<bool Core>
  211. class BS_CORE_EXPORT TShader
  212. {
  213. public:
  214. template<bool Core> struct TTechniqueType {};
  215. template<> struct TTechniqueType < false > { typedef Technique Type; };
  216. template<> struct TTechniqueType < true > { typedef TechniqueCore Type; };
  217. typedef typename TTechniqueType<Core>::Type TechniqueType;
  218. typedef typename TSHADER_DESC<Core>::TextureType TextureType;
  219. typedef typename TSHADER_DESC<Core>::SamplerStateType SamplerStateType;
  220. TShader() { }
  221. TShader(const String& name, const TSHADER_DESC<Core>& desc, const Vector<SPtr<TechniqueType>>& techniques, UINT32 id);
  222. virtual ~TShader();
  223. /** Returns the total number of techniques in this shader. */
  224. UINT32 getNumTechniques() const { return (UINT32)mTechniques.size(); }
  225. /**
  226. * Gets the best supported technique based on current render and other systems. Returns null if not a single
  227. * technique is supported.
  228. */
  229. SPtr<TechniqueType> getBestTechnique() const;
  230. /**
  231. * Returns currently active queue sort type.
  232. *
  233. * @see SHADER_DESC::queueSortType
  234. */
  235. QueueSortType getQueueSortType() const { return mDesc.queueSortType; }
  236. /**
  237. * Returns currently active queue priority.
  238. *
  239. * @see SHADER_DESC::queuePriority
  240. */
  241. INT32 getQueuePriority() const { return mDesc.queuePriority; }
  242. /**
  243. * Returns if separable passes are allowed.
  244. *
  245. * @see SHADER_DESC::separablePasses
  246. */
  247. bool getAllowSeparablePasses() const { return mDesc.separablePasses; }
  248. /**
  249. * Returns flags that control how the renderer interprets the shader. Actual interpretation of the flags depends on
  250. * the active renderer.
  251. */
  252. UINT32 getFlags() const { return mDesc.flags; }
  253. /** Returns type of the parameter with the specified name. Throws exception if the parameter doesn't exist. */
  254. GpuParamType getParamType(const String& name) const;
  255. /**
  256. * Returns description for a data parameter with the specified name. Throws exception if the parameter doesn't exist.
  257. */
  258. const SHADER_DATA_PARAM_DESC& getDataParamDesc(const String& name) const;
  259. /**
  260. * Returns description for a texture parameter with the specified name. Throws exception if the parameter doesn't
  261. * exist.
  262. */
  263. const SHADER_OBJECT_PARAM_DESC& getTextureParamDesc(const String& name) const;
  264. /**
  265. * Returns description for a sampler parameter with the specified name. Throws exception if the parameter doesn't
  266. * exist.
  267. */
  268. const SHADER_OBJECT_PARAM_DESC& getSamplerParamDesc(const String& name) const;
  269. /**
  270. * Returns description for a buffer parameter with the specified name. Throws exception if the parameter doesn't
  271. * exist.
  272. */
  273. const SHADER_OBJECT_PARAM_DESC& getBufferParamDesc(const String& name) const;
  274. /** Checks if the parameter with the specified name exists, and is a data parameter. */
  275. bool hasDataParam(const String& name) const;
  276. /** Checks if the parameter with the specified name exists, and is a texture parameter. */
  277. bool hasTextureParam(const String& name) const;
  278. /** Checks if the parameter with the specified name exists, and is a sampler parameter. */
  279. bool hasSamplerParam(const String& name) const;
  280. /** Checks if the parameter with the specified name exists, and is a buffer parameter. */
  281. bool hasBufferParam(const String& name) const;
  282. /** Returns a map of all data parameters in the shader. */
  283. const Map<String, SHADER_DATA_PARAM_DESC>& getDataParams() const { return mDesc.dataParams; }
  284. /** Returns a map of all texture parameters in the shader. */
  285. const Map<String, SHADER_OBJECT_PARAM_DESC>& getTextureParams() const { return mDesc.textureParams; }
  286. /** Returns a map of all buffer parameters in the shader. */
  287. const Map<String, SHADER_OBJECT_PARAM_DESC>& getBufferParams() const { return mDesc.bufferParams; }
  288. /** Returns a map of all sampler parameters in the shader. */
  289. const Map<String, SHADER_OBJECT_PARAM_DESC>& getSamplerParams() const { return mDesc.samplerParams; }
  290. /** Returns a map of all parameter blocks. */
  291. const Map<String, SHADER_PARAM_BLOCK_DESC>& getParamBlocks() const { return mDesc.paramBlocks; }
  292. /**
  293. * Returns a default texture for a parameter that has the specified default value index (retrieved from the
  294. * parameters descriptor).
  295. */
  296. TextureType getDefaultTexture(UINT32 index) const;
  297. /**
  298. * Returns a default sampler state for a parameter that has the specified default value index (retrieved from the
  299. * parameters descriptor).
  300. */
  301. SamplerStateType getDefaultSampler(UINT32 index) const;
  302. /**
  303. * Returns a pointer to the internal buffer containing the default value for a data parameter that has the
  304. * specified default value index (retrieved from the parameters descriptor).
  305. */
  306. UINT8* getDefaultValue(UINT32 index) const;
  307. /** Returns the unique shader ID. */
  308. UINT32 getId() const { return mId; }
  309. protected:
  310. String mName;
  311. TSHADER_DESC<Core> mDesc;
  312. Vector<SPtr<TechniqueType>> mTechniques;
  313. UINT32 mId;
  314. };
  315. /** @} */
  316. /** @addtogroup Material-Internal
  317. * @{
  318. */
  319. typedef TSHADER_DESC<true> SHADER_DESC_CORE;
  320. /** @copydoc TShader */
  321. class BS_CORE_EXPORT ShaderCore : public CoreObjectCore, public TShader<true>
  322. {
  323. public:
  324. /** @copydoc Shader::create */
  325. static SPtr<ShaderCore> create(const String& name, const SHADER_DESC_CORE& desc, const Vector<SPtr<TechniqueCore>>& techniques);
  326. protected:
  327. friend class Shader;
  328. ShaderCore(const String& name, const SHADER_DESC_CORE& desc, const Vector<SPtr<TechniqueCore>>& techniques, UINT32 id);
  329. static std::atomic<UINT32> mNextShaderId;
  330. };
  331. /** @} */
  332. /** @addtogroup Material
  333. * @{
  334. */
  335. typedef TSHADER_DESC<false> SHADER_DESC;
  336. /** @copydoc TShader */
  337. class BS_CORE_EXPORT Shader : public Resource, public TShader<false>
  338. {
  339. public:
  340. /** Retrieves an implementation of a shader usable only from the core thread. */
  341. SPtr<ShaderCore> getCore() const;
  342. /**
  343. * Sets a list include file paths that are referenced by this shader.
  344. *
  345. * @note
  346. * This is not used directly by the shader as includes are expected to be processed during GPU program and state
  347. * creation, but it may be referenced by higher layers for various purposes.
  348. */
  349. void setIncludeFiles(const Vector<String>& includes);
  350. /** Checks is the provided object type a sampler. */
  351. static bool isSampler(GpuParamObjectType type);
  352. /** Checks is the provided object type a texture. */
  353. static bool isTexture(GpuParamObjectType type);
  354. /** Checks is the provided object type a buffer. */
  355. static bool isBuffer(GpuParamObjectType type);
  356. /**
  357. * Returns the size in bytes for a specific data type.
  358. *
  359. * @note Returns 0 for variable size types like structures.
  360. */
  361. static UINT32 getDataParamSize(GpuParamDataType type);
  362. /** Creates a new shader resource using the provided descriptor and techniques. */
  363. static HShader create(const String& name, const SHADER_DESC& desc, const Vector<SPtr<Technique>>& techniques);
  364. /** Returns a shader object but doesn't initialize it. */
  365. static ShaderPtr createEmpty();
  366. public: // ***** INTERNAL ******
  367. /** @name Internal
  368. * @{
  369. */
  370. /**
  371. * Creates a new shader object using the provided descriptor and techniques.
  372. *
  373. * @note Internal method.
  374. */
  375. static ShaderPtr _createPtr(const String& name, const SHADER_DESC& desc, const Vector<SPtr<Technique>>& techniques);
  376. /** @} */
  377. private:
  378. Shader(const String& name, const SHADER_DESC& desc, const Vector<SPtr<Technique>>& techniques, UINT32 id);
  379. /** @copydoc CoreObject::getCoreDependencies */
  380. void getCoreDependencies(Vector<CoreObject*>& dependencies) override;
  381. /** @copydoc CoreObject::createCore */
  382. SPtr<CoreObjectCore> createCore() const override;
  383. /** Converts a sim thread version of the shader descriptor to a core thread version. */
  384. SHADER_DESC_CORE convertDesc(const SHADER_DESC& desc) const;
  385. private:
  386. /************************************************************************/
  387. /* RTTI */
  388. /************************************************************************/
  389. Shader() { }
  390. public:
  391. friend class ShaderRTTI;
  392. static RTTITypeBase* getRTTIStatic();
  393. virtual RTTITypeBase* getRTTI() const override;
  394. };
  395. /** @} */
  396. /** @addtogroup Material
  397. * @{
  398. */
  399. /** Shader specific resource meta-data containing information about referenced include files. */
  400. class BS_CORE_EXPORT ShaderMetaData : public ResourceMetaData
  401. {
  402. public:
  403. Vector<String> includes;
  404. /************************************************************************/
  405. /* SERIALIZATION */
  406. /************************************************************************/
  407. public:
  408. friend class ShaderMetaDataRTTI;
  409. static RTTITypeBase* getRTTIStatic();
  410. virtual RTTITypeBase* getRTTI() const override;
  411. };
  412. /** @} */
  413. }