BsShader.h 20 KB

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