BsTexture.h 19 KB

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