BsTexture.h 19 KB

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