BsTexture.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 "BsHardwareBuffer.h"
  7. #include "BsPixelUtil.h"
  8. #include "BsTextureView.h"
  9. namespace BansheeEngine
  10. {
  11. /** @addtogroup Resources
  12. * @{
  13. */
  14. /** Flags that describe how is a texture used. */
  15. enum TextureUsage
  16. {
  17. TU_STATIC = GBU_STATIC, /**< A regular texture that is not often or ever updated from the CPU. */
  18. TU_DYNAMIC = GBU_DYNAMIC, /**< A regular texture that is often updated by the CPU. */
  19. TU_RENDERTARGET = 0x200, /**< Texture that can be rendered to by the GPU. */
  20. TU_DEPTHSTENCIL = 0x400, /**< Texture used as a depth/stencil buffer by the GPU. */
  21. TU_LOADSTORE = 0x800, /**< Texture that allows load/store operations from the GPU program. */
  22. TU_CPUCACHED = 0x1000, /**< Ensures all texture data will also be cached in system memory. */
  23. TU_DEFAULT = TU_STATIC
  24. };
  25. /** Available texture types. */
  26. enum TextureType
  27. {
  28. TEX_TYPE_1D = 1, /**< One dimensional texture. Just a row of pixels. */
  29. TEX_TYPE_2D = 2, /**< Two dimensional texture. */
  30. TEX_TYPE_3D = 3, /**< Three dimensional texture. */
  31. TEX_TYPE_CUBE_MAP = 4 /**< Texture consisting out of six 2D textures describing an inside of a cube. Allows special sampling. */
  32. };
  33. /** Texture mipmap options. */
  34. enum TextureMipmap
  35. {
  36. MIP_UNLIMITED = 0x7FFFFFFF /**< Create all mip maps down to 1x1. */
  37. };
  38. /** Descriptor structure used for initialization of a Texture. */
  39. struct TEXTURE_DESC
  40. {
  41. /** Type of the texture. */
  42. TextureType type = TEX_TYPE_2D;
  43. /** Format of pixels in the texture. */
  44. PixelFormat format = PF_R8G8B8A8;
  45. /** Width of the texture in pixels. */
  46. UINT32 width = 1;
  47. /** Height of the texture in pixels. */
  48. UINT32 height = 1;
  49. /** Depth of the texture in pixels (Must be 1 for 2D textures). */
  50. UINT32 depth = 1;
  51. /** Number of mip-maps the texture has. This number excludes the full resolution map. */
  52. UINT32 numMips = 0;
  53. /** Describes how the caller plans on using the texture in the pipeline. */
  54. INT32 usage = TU_DEFAULT;
  55. /**
  56. * If true the texture data is assumed to have been gamma corrected and will be converted back to linear space when
  57. * sampled on GPU.
  58. */
  59. bool hwGamma = false;
  60. /** Number of samples per pixel. Set to 1 or 0 to use the default of a single sample per pixel. */
  61. UINT32 numSamples = 0;
  62. /** Number of texture slices to create if creating a texture array. Ignored for 3D textures. */
  63. UINT32 numArraySlices = 1;
  64. };
  65. /** Properties of a Texture. Shared between sim and core thread versions of a Texture. */
  66. class BS_CORE_EXPORT TextureProperties
  67. {
  68. public:
  69. TextureProperties();
  70. TextureProperties(const TEXTURE_DESC& desc);
  71. /** Gets the type of texture. */
  72. TextureType getTextureType() const { return mDesc.type; }
  73. /**
  74. * Gets the number of mipmaps to be used for this texture. This number excludes the top level map (which is always
  75. * assumed to be present).
  76. */
  77. UINT32 getNumMipmaps() const {return mDesc.numMips;}
  78. /** Gets whether this texture will be set up so that on sampling it, hardware gamma correction is applied. */
  79. bool isHardwareGammaEnabled() const { return mDesc.hwGamma; }
  80. /** Gets the number of samples used for multisampling (0 if multisampling is not used). */
  81. UINT32 getNumSamples() const { return mDesc.numSamples; }
  82. /** Returns the height of the texture. */
  83. UINT32 getHeight() const { return mDesc.height; }
  84. /** Returns the width of the texture. */
  85. UINT32 getWidth() const { return mDesc.width; }
  86. /** Returns the depth of the texture (only applicable for 3D textures). */
  87. UINT32 getDepth() const { return mDesc.depth; }
  88. /** Returns texture usage (TextureUsage) of this texture. */
  89. int getUsage() const { return mDesc.usage; }
  90. /** Returns the pixel format for the texture surface. */
  91. PixelFormat getFormat() const { return mDesc.format; }
  92. /** Returns true if the texture has an alpha layer. */
  93. bool hasAlpha() const;
  94. /** Returns the number of faces this texture has. */
  95. UINT32 getNumFaces() const;
  96. /** Returns the number of array slices of the texture (if the texture is an array texture). */
  97. UINT32 getNumArraySlices() const { return mDesc.numArraySlices; }
  98. /**
  99. * Maps a sub-resource index to an exact face and mip level. Sub-resource indexes are used when reading or writing
  100. * to the resource.
  101. *
  102. * @note
  103. * Sub-resource index is only valid for the instance it was created on. You cannot use a sub-resource index from a
  104. * different texture and expect to get valid result. Modifying the resource so the number of sub-resources changes
  105. * invalidates all sub-resource indexes.
  106. */
  107. void mapFromSubresourceIdx(UINT32 subresourceIdx, UINT32& face, UINT32& mip) const;
  108. /**
  109. * Map a face and a mip level to a sub-resource index you can use for updating or reading a specific sub-resource.
  110. *
  111. * @note
  112. * Generated sub-resource index is only valid for the instance it was created on. Modifying the resource so the
  113. * number of sub-resources changes, invalidates all sub-resource indexes.
  114. */
  115. UINT32 mapToSubresourceIdx(UINT32 face, UINT32 mip) const;
  116. /**
  117. * Allocates a buffer you may use for storage when reading or writing a sub-resource. You need to allocate such a
  118. * buffer if you are calling readSubresource().
  119. *
  120. * You can retrieve a sub-resource index by calling mapToSubresourceIdx().
  121. *
  122. * @note Thread safe.
  123. */
  124. SPtr<PixelData> allocateSubresourceBuffer(UINT32 subresourceIdx) const;
  125. protected:
  126. friend class TextureRTTI;
  127. friend class Texture;
  128. TEXTURE_DESC mDesc;
  129. };
  130. /**
  131. * Abstract class representing a texture. Specific render systems have their own Texture implementations. Internally
  132. * represented as one or more surfaces with pixels in a certain number of dimensions, backed by a hardware buffer.
  133. *
  134. * @note Sim thread.
  135. */
  136. class BS_CORE_EXPORT Texture : public Resource
  137. {
  138. public:
  139. /**
  140. * Updates the texture with new data. The actual write will be queued for later execution on the core thread.
  141. * Provided data buffer will be locked until the operation completes.
  142. *
  143. * @param[in] accessor Accessor to queue the operation on.
  144. * @param[in] subresourceIdx Index of the subresource to write. Retrieved from
  145. * TextureProperties::mapToSubresourceIdx().
  146. * @param[in] data Pixel data to write. User must ensure it is in format and size compatible with
  147. * the texture.
  148. * @param[in] discardEntireBuffer When true the existing contents of the resource you are updating will be
  149. * discarded. This can make the operation faster. Resources with certain buffer
  150. * types might require this flag to be in a specific state otherwise the operation
  151. * will fail.
  152. * @return Async operation object you can use to track operation completion.
  153. */
  154. AsyncOp writeSubresource(CoreAccessor& accessor, UINT32 subresourceIdx, const SPtr<PixelData>& data,
  155. bool discardEntireBuffer);
  156. /**
  157. * Reads internal texture data to the provided previously allocated buffer. The read is queued for execution on the
  158. * core thread and not executed immediately. Provided data buffer will be locked until the operation completes.
  159. *
  160. * @param[in] accessor Accessor to queue the operation on.
  161. * @param[in] subresourceIdx Index of the subresource to read. Retrieved from
  162. * TextureProperties::mapToSubresourceIdx().
  163. * @param[out] data Pre-allocated buffer of proper size and format where data will be read to. You
  164. * can use TextureProperties::allocateSubresourceBuffer() to allocate a valid
  165. * buffer.
  166. * @return Async operation object you can use to track operation completion.
  167. *
  168. * @see TextureCore::readSubresource
  169. */
  170. AsyncOp readSubresource(CoreAccessor& accessor, UINT32 subresourceIdx, const SPtr<PixelData>& data);
  171. /**
  172. * Reads data from the cached system memory texture buffer into the provided buffer.
  173. *
  174. * @param[out] dest Previously allocated buffer to read data into.
  175. * @param[in] mipLevel (optional) Mipmap level to read from.
  176. * @param[in] face (optional) Texture face to read from.
  177. *
  178. * @note
  179. * The data read is the cached texture data. Any data written to the texture from the GPU or core thread will not
  180. * be reflected in this data. Use readSubresource() if you require those changes.
  181. * @note
  182. * The texture must have been created with TU_CPUCACHED usage otherwise this method will not return any data.
  183. */
  184. void readData(PixelData& dest, UINT32 mipLevel = 0, UINT32 face = 0);
  185. /** Returns properties that contain information about the texture. */
  186. const TextureProperties& getProperties() const { return mProperties; }
  187. /** Retrieves a core implementation of a texture usable only from the core thread. */
  188. SPtr<TextureCore> getCore() const;
  189. /************************************************************************/
  190. /* STATICS */
  191. /************************************************************************/
  192. /**
  193. * Creates a new empty texture.
  194. *
  195. * @param[in] desc Description of the texture to create.
  196. */
  197. static HTexture create(const TEXTURE_DESC& desc);
  198. /**
  199. * Creates a new 2D or 3D texture initialized using the provided pixel data. Texture will not have any mipmaps.
  200. *
  201. * @param[in] pixelData Data to initialize the texture width.
  202. * @param[in] usage Describes planned texture use.
  203. * @param[in] hwGammaCorrection If true the texture data is assumed to have been gamma corrected and will be
  204. * converted back to linear space when sampled on GPU.
  205. */
  206. static HTexture create(const SPtr<PixelData>& pixelData, int usage = TU_DEFAULT, bool hwGammaCorrection = false);
  207. /** @name Internal
  208. * @{
  209. */
  210. /**
  211. * @copydoc create(const TEXTURE_DESC&)
  212. *
  213. * @note Internal method. Creates a texture pointer without a handle. Use create() for normal usage.
  214. */
  215. static SPtr<Texture> _createPtr(const TEXTURE_DESC& desc);
  216. /**
  217. * @copydoc create(const SPtr<PixelData>&, int, bool)
  218. *
  219. * @note Internal method. Creates a texture pointer without a handle. Use create() for normal usage.
  220. */
  221. static SPtr<Texture> _createPtr(const SPtr<PixelData>& pixelData, int usage = TU_DEFAULT,
  222. bool hwGammaCorrection = false);
  223. /** @} */
  224. protected:
  225. friend class TextureManager;
  226. Texture(const TEXTURE_DESC& desc);
  227. Texture(const TEXTURE_DESC& desc, const SPtr<PixelData>& pixelData);
  228. /** @copydoc Resource::initialize */
  229. void initialize() override;
  230. /** @copydoc CoreObject::createCore */
  231. SPtr<CoreObjectCore> createCore() const override;
  232. /** Calculates the size of the texture, in bytes. */
  233. UINT32 calculateSize() const;
  234. /**
  235. * Creates buffers used for caching of CPU texture data.
  236. *
  237. * @note Make sure to initialize all texture properties before calling this.
  238. */
  239. void createCPUBuffers();
  240. /** Updates the cached CPU buffers with new data. */
  241. void updateCPUBuffers(UINT32 subresourceIdx, const PixelData& data);
  242. protected:
  243. Vector<SPtr<PixelData>> mCPUSubresourceData;
  244. TextureProperties mProperties;
  245. mutable SPtr<PixelData> mInitData;
  246. /************************************************************************/
  247. /* SERIALIZATION */
  248. /************************************************************************/
  249. public:
  250. Texture(); // Serialization only
  251. friend class TextureRTTI;
  252. static RTTITypeBase* getRTTIStatic();
  253. RTTITypeBase* getRTTI() const override;
  254. };
  255. /** @} */
  256. /** @addtogroup Resources-Internal
  257. * @{
  258. */
  259. /**
  260. * Core thread version of a Texture.
  261. *
  262. * @note Core thread.
  263. */
  264. class BS_CORE_EXPORT TextureCore : public CoreObjectCore
  265. {
  266. public:
  267. TextureCore(const TEXTURE_DESC& desc, const SPtr<PixelData>& initData, GpuDeviceFlags deviceMask);
  268. virtual ~TextureCore() {}
  269. /** @copydoc CoreObjectCore::initialize */
  270. void initialize() override;
  271. /**
  272. * Updates a part of the texture with the provided data.
  273. *
  274. * @param[in] subresourceIdx Index of the subresource to update, if the texture has more than one.
  275. * @param[in] data Data to update the texture with.
  276. * @param[in] discardEntireBuffer When true the existing contents of the resource you are updating will be
  277. * discarded. This can make the operation faster. Resources with certain buffer
  278. * types might require this flag to be in a specific state otherwise the operation
  279. * will fail.
  280. */
  281. virtual void writeSubresource(UINT32 subresourceIdx, const PixelData& data, bool discardEntireBuffer);
  282. /**
  283. * Reads a part of the current resource into the provided @p data parameter. Data buffer needs to be pre-allocated.
  284. *
  285. * @param[in] subresourceIdx Index of the subresource to update, if the texture has more than one.
  286. * @param[out] data Buffer that will receive the data. Should be allocated with
  287. * allocateSubresourceBuffer() to ensure it is of valid type and size.
  288. */
  289. virtual void readSubresource(UINT32 subresourceIdx, PixelData& data);
  290. /**
  291. * Locks the buffer for reading or writing.
  292. *
  293. * @param[in] options Options for controlling what you may do with the locked data.
  294. * @param[in] mipLevel (optional) Mipmap level to lock.
  295. * @param[in] face (optional) Texture face to lock.
  296. * @return Pointer to the buffer data. Only valid until you call unlock().
  297. *
  298. * @note
  299. * If you are just reading or writing one block of data use readData()/writeData() methods as they can be much faster
  300. * in certain situations.
  301. */
  302. PixelData lock(GpuLockOptions options, UINT32 mipLevel = 0, UINT32 face = 0);
  303. /**
  304. * Unlocks a previously locked buffer. After the buffer is unlocked, any data returned by lock becomes invalid.
  305. *
  306. * @see lock()
  307. */
  308. void unlock();
  309. /**
  310. * Copies the contents a subresource in this texture to another texture. Texture format and size of the subresource
  311. * must match.
  312. *
  313. * You are allowed to copy from a multisampled to non-multisampled surface, which will resolve the multisampled
  314. * surface before copying.
  315. *
  316. * @param[in] srcSubresourceIdx Index of the subresource to copy from.
  317. * @param[in] destSubresourceIdx Index of the subresource to copy to.
  318. * @param[in] target Texture that contains the destination subresource.
  319. */
  320. void copy(UINT32 srcSubresourceIdx, UINT32 destSubresourceIdx, const SPtr<TextureCore>& target);
  321. /**
  322. * Reads data from the texture buffer into the provided buffer.
  323. *
  324. * @param[out] dest Previously allocated buffer to read data into.
  325. * @param[in] mipLevel (optional) Mipmap level to read from.
  326. * @param[in] face (optional) Texture face to read from.
  327. */
  328. virtual void readData(PixelData& dest, UINT32 mipLevel = 0, UINT32 face = 0) = 0;
  329. /**
  330. * Writes data from the provided buffer into the texture buffer.
  331. *
  332. * @param[in] src Buffer to retrieve the data from.
  333. * @param[in] mipLevel (optional) Mipmap level to write into.
  334. * @param[in] face (optional) Texture face to write into.
  335. * @param[in] discardWholeBuffer (optional) If true any existing texture data will be discard. This can improve
  336. * performance of the write operation.
  337. */
  338. virtual void writeData(const PixelData& src, UINT32 mipLevel = 0, UINT32 face = 0, bool discardWholeBuffer = false) = 0;
  339. /** Returns properties that contain information about the texture. */
  340. const TextureProperties& getProperties() const { return mProperties; }
  341. /************************************************************************/
  342. /* STATICS */
  343. /************************************************************************/
  344. /**
  345. * @copydoc Texture::create(const TEXTURE_DESC&)
  346. * @param[in] deviceMask Mask that determines on which GPU devices should the object be created on.
  347. */
  348. static SPtr<TextureCore> create(const TEXTURE_DESC& desc, GpuDeviceFlags deviceMask = GDF_DEFAULT);
  349. /**
  350. * @copydoc Texture::create(const SPtr<PixelData>&, int, bool)
  351. * @param[in] deviceMask Mask that determines on which GPU devices should the object be created on.
  352. */
  353. static SPtr<TextureCore> create(const SPtr<PixelData>& pixelData, int usage = TU_DEFAULT,
  354. bool hwGammaCorrection = false, GpuDeviceFlags deviceMask = GDF_DEFAULT);
  355. /************************************************************************/
  356. /* TEXTURE VIEW */
  357. /************************************************************************/
  358. /**
  359. * Requests a texture view for the specified mip and array ranges. Returns an existing view of one for the specified
  360. * ranges already exists, otherwise creates a new one. You must release all views by calling releaseView() when done.
  361. *
  362. * @note Core thread only.
  363. */
  364. static SPtr<TextureView> requestView(const SPtr<TextureCore>& texture, UINT32 mostDetailMip, UINT32 numMips,
  365. UINT32 firstArraySlice, UINT32 numArraySlices, GpuViewUsage usage);
  366. /**
  367. * Releases the view. View won't actually get destroyed until all references to it are released.
  368. *
  369. * @note Core thread only.
  370. */
  371. static void releaseView(const SPtr<TextureView>& view);
  372. /** Returns a plain white texture. */
  373. static SPtr<TextureCore> WHITE;
  374. /** Returns a plain black texture. */
  375. static SPtr<TextureCore> BLACK;
  376. /** Returns a plain normal map texture with normal pointing up (in Y direction). */
  377. static SPtr<TextureCore> NORMAL;
  378. protected:
  379. /** @copydoc lock */
  380. virtual PixelData lockImpl(GpuLockOptions options, UINT32 mipLevel = 0, UINT32 face = 0) = 0;
  381. /** @copydoc unlock */
  382. virtual void unlockImpl() = 0;
  383. /**
  384. * API specific implementation of copy().
  385. *
  386. * @param[in] srcFace Face index to copy from.
  387. * @param[in] srcMipLevel Mip level to copy from.
  388. * @param[in] destFace Face index to copy to.
  389. * @param[in] destMipLevel Mip level to copy to.
  390. * @param[in] target Texture to copy to.
  391. */
  392. virtual void copyImpl(UINT32 srcFace, UINT32 srcMipLevel, UINT32 destFace, UINT32 destMipLevel,
  393. const SPtr<TextureCore>& target) = 0;
  394. /************************************************************************/
  395. /* TEXTURE VIEW */
  396. /************************************************************************/
  397. /** Creates a new empty/undefined texture view. */
  398. virtual SPtr<TextureView> createView(const SPtr<TextureCore>& texture, const TEXTURE_VIEW_DESC& desc);
  399. /**
  400. * Releases all internal texture view references. Views won't get destroyed if there are external references still
  401. * held.
  402. */
  403. void clearBufferViews();
  404. /** Holds a single texture view with a usage reference count. */
  405. struct TextureViewReference
  406. {
  407. TextureViewReference(SPtr<TextureView> _view)
  408. :view(_view), refCount(0)
  409. { }
  410. SPtr<TextureView> view;
  411. UINT32 refCount;
  412. };
  413. UnorderedMap<TEXTURE_VIEW_DESC, TextureViewReference*, TextureView::HashFunction, TextureView::EqualFunction> mTextureViews;
  414. TextureProperties mProperties;
  415. SPtr<PixelData> mInitData;
  416. };
  417. /** @} */
  418. }