2
0

BsTexture.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "Image/BsTexture.h"
  4. #include "RTTI/BsTextureRTTI.h"
  5. #include "FileSystem/BsDataStream.h"
  6. #include "Error/BsException.h"
  7. #include "Debug/BsDebug.h"
  8. #include "CoreThread/BsCoreThread.h"
  9. #include "Threading/BsAsyncOp.h"
  10. #include "Resources/BsResources.h"
  11. #include "Image/BsPixelUtil.h"
  12. namespace bs
  13. {
  14. TextureProperties::TextureProperties()
  15. { }
  16. TextureProperties::TextureProperties(const TEXTURE_DESC& desc)
  17. :mDesc(desc)
  18. {
  19. }
  20. bool TextureProperties::hasAlpha() const
  21. {
  22. return PixelUtil::hasAlpha(mDesc.format);
  23. }
  24. UINT32 TextureProperties::getNumFaces() const
  25. {
  26. UINT32 facesPerSlice = getTextureType() == TEX_TYPE_CUBE_MAP ? 6 : 1;
  27. return facesPerSlice * mDesc.numArraySlices;
  28. }
  29. void TextureProperties::mapFromSubresourceIdx(UINT32 subresourceIdx, UINT32& face, UINT32& mip) const
  30. {
  31. UINT32 numMipmaps = getNumMipmaps() + 1;
  32. face = Math::floorToInt((subresourceIdx) / (float)numMipmaps);
  33. mip = subresourceIdx % numMipmaps;
  34. }
  35. UINT32 TextureProperties::mapToSubresourceIdx(UINT32 face, UINT32 mip) const
  36. {
  37. return face * (getNumMipmaps() + 1) + mip;
  38. }
  39. SPtr<PixelData> TextureProperties::allocBuffer(UINT32 face, UINT32 mipLevel) const
  40. {
  41. UINT32 width = getWidth();
  42. UINT32 height = getHeight();
  43. UINT32 depth = getDepth();
  44. UINT32 totalSize = PixelUtil::getMemorySize(width, height, depth, getFormat());
  45. for (UINT32 j = 0; j < mipLevel; j++)
  46. {
  47. totalSize = PixelUtil::getMemorySize(width, height, depth, getFormat());
  48. if (width != 1) width /= 2;
  49. if (height != 1) height /= 2;
  50. if (depth != 1) depth /= 2;
  51. }
  52. SPtr<PixelData> dst = bs_shared_ptr_new<PixelData>(width, height, depth, getFormat());
  53. dst->allocateInternalBuffer();
  54. return dst;
  55. }
  56. Texture::Texture()
  57. {
  58. }
  59. Texture::Texture(const TEXTURE_DESC& desc)
  60. :mProperties(desc)
  61. {
  62. }
  63. Texture::Texture(const TEXTURE_DESC& desc, const SPtr<PixelData>& pixelData)
  64. : mProperties(desc), mInitData(pixelData)
  65. {
  66. if (mInitData != nullptr)
  67. mInitData->_lock();
  68. }
  69. void Texture::initialize()
  70. {
  71. mSize = calculateSize();
  72. // Allocate CPU buffers if needed
  73. if ((mProperties.getUsage() & TU_CPUCACHED) != 0)
  74. {
  75. createCPUBuffers();
  76. if (mInitData != nullptr)
  77. updateCPUBuffers(0, *mInitData);
  78. }
  79. Resource::initialize();
  80. }
  81. SPtr<ct::CoreObject> Texture::createCore() const
  82. {
  83. const TextureProperties& props = getProperties();
  84. SPtr<ct::CoreObject> coreObj = ct::TextureManager::instance().createTextureInternal(props.mDesc, mInitData);
  85. if ((mProperties.getUsage() & TU_CPUCACHED) == 0)
  86. mInitData = nullptr;
  87. return coreObj;
  88. }
  89. AsyncOp Texture::writeData(const SPtr<PixelData>& data, UINT32 face, UINT32 mipLevel, bool discardEntireBuffer)
  90. {
  91. UINT32 subresourceIdx = mProperties.mapToSubresourceIdx(face, mipLevel);
  92. updateCPUBuffers(subresourceIdx, *data);
  93. data->_lock();
  94. std::function<void(const SPtr<ct::Texture>&, UINT32, UINT32, const SPtr<PixelData>&, bool, AsyncOp&)> func =
  95. [&](const SPtr<ct::Texture>& texture, UINT32 _face, UINT32 _mipLevel, const SPtr<PixelData>& _pixData,
  96. bool _discardEntireBuffer, AsyncOp& asyncOp)
  97. {
  98. texture->writeData(*_pixData, _mipLevel, _face, _discardEntireBuffer);
  99. _pixData->_unlock();
  100. asyncOp._completeOperation();
  101. };
  102. return gCoreThread().queueReturnCommand(std::bind(func, getCore(), face, mipLevel,
  103. data, discardEntireBuffer, std::placeholders::_1));
  104. }
  105. AsyncOp Texture::readData(const SPtr<PixelData>& data, UINT32 face, UINT32 mipLevel)
  106. {
  107. data->_lock();
  108. std::function<void(const SPtr<ct::Texture>&, UINT32, UINT32, const SPtr<PixelData>&, AsyncOp&)> func =
  109. [&](const SPtr<ct::Texture>& texture, UINT32 _face, UINT32 _mipLevel, const SPtr<PixelData>& _pixData,
  110. AsyncOp& asyncOp)
  111. {
  112. // Make sure any queued command start executing before reading
  113. ct::RenderAPI::instance().submitCommandBuffer(nullptr);
  114. texture->readData(*_pixData, _mipLevel, _face);
  115. _pixData->_unlock();
  116. asyncOp._completeOperation();
  117. };
  118. return gCoreThread().queueReturnCommand(std::bind(func, getCore(), face, mipLevel,
  119. data, std::placeholders::_1));
  120. }
  121. UINT32 Texture::calculateSize() const
  122. {
  123. return mProperties.getNumFaces() * PixelUtil::getMemorySize(mProperties.getWidth(),
  124. mProperties.getHeight(), mProperties.getDepth(), mProperties.getFormat());
  125. }
  126. void Texture::updateCPUBuffers(UINT32 subresourceIdx, const PixelData& pixelData)
  127. {
  128. if ((mProperties.getUsage() & TU_CPUCACHED) == 0)
  129. return;
  130. if (subresourceIdx >= (UINT32)mCPUSubresourceData.size())
  131. {
  132. LOGERR("Invalid subresource index: " + toString(subresourceIdx) + ". Supported range: 0 .. " + toString((UINT32)mCPUSubresourceData.size()));
  133. return;
  134. }
  135. UINT32 mipLevel;
  136. UINT32 face;
  137. mProperties.mapFromSubresourceIdx(subresourceIdx, face, mipLevel);
  138. UINT32 mipWidth, mipHeight, mipDepth;
  139. PixelUtil::getSizeForMipLevel(mProperties.getWidth(), mProperties.getHeight(), mProperties.getDepth(),
  140. mipLevel, mipWidth, mipHeight, mipDepth);
  141. if (pixelData.getWidth() != mipWidth || pixelData.getHeight() != mipHeight ||
  142. pixelData.getDepth() != mipDepth || pixelData.getFormat() != mProperties.getFormat())
  143. {
  144. LOGERR("Provided buffer is not of valid dimensions or format in order to update this texture.");
  145. return;
  146. }
  147. if (mCPUSubresourceData[subresourceIdx]->getSize() != pixelData.getSize())
  148. BS_EXCEPT(InternalErrorException, "Buffer sizes don't match.");
  149. UINT8* dest = mCPUSubresourceData[subresourceIdx]->getData();
  150. UINT8* src = pixelData.getData();
  151. memcpy(dest, src, pixelData.getSize());
  152. }
  153. void Texture::readCachedData(PixelData& dest, UINT32 face, UINT32 mipLevel)
  154. {
  155. if ((mProperties.getUsage() & TU_CPUCACHED) == 0)
  156. {
  157. LOGERR("Attempting to read CPU data from a texture that is created without CPU caching.");
  158. return;
  159. }
  160. UINT32 mipWidth, mipHeight, mipDepth;
  161. PixelUtil::getSizeForMipLevel(mProperties.getWidth(), mProperties.getHeight(), mProperties.getDepth(),
  162. mipLevel, mipWidth, mipHeight, mipDepth);
  163. if (dest.getWidth() != mipWidth || dest.getHeight() != mipHeight ||
  164. dest.getDepth() != mipDepth || dest.getFormat() != mProperties.getFormat())
  165. {
  166. LOGERR("Provided buffer is not of valid dimensions or format in order to read from this texture.");
  167. return;
  168. }
  169. UINT32 subresourceIdx = mProperties.mapToSubresourceIdx(face, mipLevel);
  170. if (subresourceIdx >= (UINT32)mCPUSubresourceData.size())
  171. {
  172. LOGERR("Invalid subresource index: " + toString(subresourceIdx) + ". Supported range: 0 .. " + toString((UINT32)mCPUSubresourceData.size()));
  173. return;
  174. }
  175. if (mCPUSubresourceData[subresourceIdx]->getSize() != dest.getSize())
  176. BS_EXCEPT(InternalErrorException, "Buffer sizes don't match.");
  177. UINT8* srcPtr = mCPUSubresourceData[subresourceIdx]->getData();
  178. UINT8* destPtr = dest.getData();
  179. memcpy(destPtr, srcPtr, dest.getSize());
  180. }
  181. void Texture::createCPUBuffers()
  182. {
  183. UINT32 numFaces = mProperties.getNumFaces();
  184. UINT32 numMips = mProperties.getNumMipmaps() + 1;
  185. UINT32 numSubresources = numFaces * numMips;
  186. mCPUSubresourceData.resize(numSubresources);
  187. for (UINT32 i = 0; i < numFaces; i++)
  188. {
  189. UINT32 curWidth = mProperties.getWidth();
  190. UINT32 curHeight = mProperties.getHeight();
  191. UINT32 curDepth = mProperties.getDepth();
  192. for (UINT32 j = 0; j < numMips; j++)
  193. {
  194. UINT32 subresourceIdx = mProperties.mapToSubresourceIdx(i, j);
  195. mCPUSubresourceData[subresourceIdx] = bs_shared_ptr_new<PixelData>(curWidth, curHeight, curDepth, mProperties.getFormat());
  196. mCPUSubresourceData[subresourceIdx]->allocateInternalBuffer();
  197. if (curWidth > 1)
  198. curWidth = curWidth / 2;
  199. if (curHeight > 1)
  200. curHeight = curHeight / 2;
  201. if (curDepth > 1)
  202. curDepth = curDepth / 2;
  203. }
  204. }
  205. }
  206. SPtr<ct::Texture> Texture::getCore() const
  207. {
  208. return std::static_pointer_cast<ct::Texture>(mCoreSpecific);
  209. }
  210. /************************************************************************/
  211. /* SERIALIZATION */
  212. /************************************************************************/
  213. RTTITypeBase* Texture::getRTTIStatic()
  214. {
  215. return TextureRTTI::instance();
  216. }
  217. RTTITypeBase* Texture::getRTTI() const
  218. {
  219. return Texture::getRTTIStatic();
  220. }
  221. /************************************************************************/
  222. /* STATICS */
  223. /************************************************************************/
  224. HTexture Texture::create(const TEXTURE_DESC& desc)
  225. {
  226. SPtr<Texture> texturePtr = _createPtr(desc);
  227. return static_resource_cast<Texture>(gResources()._createResourceHandle(texturePtr));
  228. }
  229. HTexture Texture::create(const SPtr<PixelData>& pixelData, int usage, bool hwGammaCorrection)
  230. {
  231. SPtr<Texture> texturePtr = _createPtr(pixelData, usage, hwGammaCorrection);
  232. return static_resource_cast<Texture>(gResources()._createResourceHandle(texturePtr));
  233. }
  234. SPtr<Texture> Texture::_createPtr(const TEXTURE_DESC& desc)
  235. {
  236. return TextureManager::instance().createTexture(desc);
  237. }
  238. SPtr<Texture> Texture::_createPtr(const SPtr<PixelData>& pixelData, int usage, bool hwGammaCorrection)
  239. {
  240. TEXTURE_DESC desc;
  241. desc.type = pixelData->getDepth() > 1 ? TEX_TYPE_3D : TEX_TYPE_2D;
  242. desc.width = pixelData->getWidth();
  243. desc.height = pixelData->getHeight();
  244. desc.depth = pixelData->getDepth();
  245. desc.format = pixelData->getFormat();
  246. desc.usage = usage;
  247. desc.hwGamma = hwGammaCorrection;
  248. return TextureManager::instance().createTexture(desc, pixelData);
  249. }
  250. namespace ct
  251. {
  252. SPtr<Texture> Texture::WHITE;
  253. SPtr<Texture> Texture::BLACK;
  254. SPtr<Texture> Texture::NORMAL;
  255. Texture::Texture(const TEXTURE_DESC& desc, const SPtr<PixelData>& initData, GpuDeviceFlags deviceMask)
  256. :mProperties(desc), mInitData(initData)
  257. { }
  258. void Texture::initialize()
  259. {
  260. if (mInitData != nullptr)
  261. {
  262. writeData(*mInitData, 0, 0, true);
  263. mInitData->_unlock();
  264. mInitData = nullptr;
  265. }
  266. CoreObject::initialize();
  267. }
  268. void Texture::writeData(const PixelData& src, UINT32 mipLevel, UINT32 face, bool discardEntireBuffer,
  269. UINT32 queueIdx)
  270. {
  271. THROW_IF_NOT_CORE_THREAD;
  272. if(discardEntireBuffer)
  273. {
  274. if((mProperties.getUsage() & TU_DYNAMIC) == 0)
  275. {
  276. // Buffer discard is enabled but buffer was not created as dynamic. Disabling discard.
  277. discardEntireBuffer = false;
  278. }
  279. }
  280. writeDataImpl(src, mipLevel, face, discardEntireBuffer, queueIdx);
  281. }
  282. void Texture::readData(PixelData& dest, UINT32 mipLevel, UINT32 face, UINT32 deviceIdx, UINT32 queueIdx)
  283. {
  284. THROW_IF_NOT_CORE_THREAD;
  285. PixelData& pixelData = static_cast<PixelData&>(dest);
  286. UINT32 mipWidth, mipHeight, mipDepth;
  287. PixelUtil::getSizeForMipLevel(mProperties.getWidth(), mProperties.getHeight(), mProperties.getDepth(),
  288. mipLevel, mipWidth, mipHeight, mipDepth);
  289. if (pixelData.getWidth() != mipWidth || pixelData.getHeight() != mipHeight ||
  290. pixelData.getDepth() != mipDepth || pixelData.getFormat() != mProperties.getFormat())
  291. {
  292. LOGERR("Provided buffer is not of valid dimensions or format in order to read from this texture.");
  293. return;
  294. }
  295. readDataImpl(pixelData, mipLevel, face, deviceIdx, queueIdx);
  296. }
  297. PixelData Texture::lock(GpuLockOptions options, UINT32 mipLevel, UINT32 face, UINT32 deviceIdx, UINT32 queueIdx)
  298. {
  299. THROW_IF_NOT_CORE_THREAD;
  300. if (mipLevel > mProperties.getNumMipmaps())
  301. {
  302. LOGERR("Invalid mip level: " + toString(mipLevel) + ". Min is 0, max is " + toString(mProperties.getNumMipmaps()));
  303. return PixelData(0, 0, 0, PF_UNKNOWN);
  304. }
  305. if (face >= mProperties.getNumFaces())
  306. {
  307. LOGERR("Invalid face index: " + toString(face) + ". Min is 0, max is " + toString(mProperties.getNumFaces()));
  308. return PixelData(0, 0, 0, PF_UNKNOWN);
  309. }
  310. return lockImpl(options, mipLevel, face, deviceIdx, queueIdx);
  311. }
  312. void Texture::unlock()
  313. {
  314. THROW_IF_NOT_CORE_THREAD;
  315. unlockImpl();
  316. }
  317. void Texture::copy(const SPtr<Texture>& target, UINT32 srcFace, UINT32 srcMipLevel, UINT32 dstFace,
  318. UINT32 dstMipLevel, const SPtr<CommandBuffer>& commandBuffer)
  319. {
  320. THROW_IF_NOT_CORE_THREAD;
  321. if (target->mProperties.getTextureType() != mProperties.getTextureType())
  322. {
  323. LOGERR("Source and destination textures must be of same type and must have the same usage and type.");
  324. return;
  325. }
  326. if (mProperties.getFormat() != target->mProperties.getFormat()) // Note: It might be okay to use different formats of the same size
  327. {
  328. LOGERR("Source and destination texture formats must match.");
  329. return;
  330. }
  331. if (target->mProperties.getNumSamples() > 0 && mProperties.getNumSamples() != target->mProperties.getNumSamples())
  332. {
  333. LOGERR("When copying to a multisampled texture, source texture must have the same number of samples.");
  334. return;
  335. }
  336. if (dstFace >= mProperties.getNumFaces())
  337. {
  338. LOGERR("Invalid destination face index");
  339. return;
  340. }
  341. if (srcFace >= target->mProperties.getNumFaces())
  342. {
  343. LOGERR("Invalid destination face index");
  344. return;
  345. }
  346. if (srcMipLevel > mProperties.getNumMipmaps())
  347. {
  348. LOGERR("Source mip level out of range. Valid range is [0, " + toString(mProperties.getNumMipmaps()) + "]");
  349. return;
  350. }
  351. if (dstMipLevel > target->mProperties.getNumMipmaps())
  352. {
  353. LOGERR("Destination mip level out of range. Valid range is [0, " + toString(target->mProperties.getNumMipmaps()) + "]");
  354. return;
  355. }
  356. UINT32 srcMipWidth = mProperties.getWidth() >> srcMipLevel;
  357. UINT32 srcMipHeight = mProperties.getHeight() >> srcMipLevel;
  358. UINT32 srcMipDepth = mProperties.getDepth() >> srcMipLevel;
  359. UINT32 dstMipWidth = target->mProperties.getWidth() >> dstMipLevel;
  360. UINT32 dstMipHeight = target->mProperties.getHeight() >> dstMipLevel;
  361. UINT32 dstMipDepth = target->mProperties.getDepth() >> dstMipLevel;
  362. if (srcMipWidth != dstMipWidth || srcMipHeight != dstMipHeight || srcMipDepth != dstMipDepth)
  363. {
  364. LOGERR("Source and destination sizes must match");
  365. return;
  366. }
  367. copyImpl(srcFace, srcMipLevel, dstFace, dstMipLevel, target, commandBuffer);
  368. }
  369. /************************************************************************/
  370. /* TEXTURE VIEW */
  371. /************************************************************************/
  372. SPtr<TextureView> Texture::createView(const TEXTURE_VIEW_DESC& desc)
  373. {
  374. return bs_shared_ptr<TextureView>(new (bs_alloc<TextureView>()) TextureView(desc));
  375. }
  376. void Texture::clearBufferViews()
  377. {
  378. mTextureViews.clear();
  379. }
  380. SPtr<TextureView> Texture::requestView(UINT32 mostDetailMip, UINT32 numMips, UINT32 firstArraySlice,
  381. UINT32 numArraySlices, GpuViewUsage usage)
  382. {
  383. THROW_IF_NOT_CORE_THREAD;
  384. const TextureProperties& texProps = getProperties();
  385. TEXTURE_VIEW_DESC key;
  386. key.mostDetailMip = mostDetailMip;
  387. key.numMips = numMips == 0 ? (texProps.getNumMipmaps() + 1) : numMips;
  388. key.firstArraySlice = firstArraySlice;
  389. key.numArraySlices = numArraySlices == 0 ? texProps.getNumFaces() : numArraySlices;
  390. key.usage = usage;
  391. auto iterFind = mTextureViews.find(key);
  392. if (iterFind == mTextureViews.end())
  393. {
  394. SPtr<TextureView> newView =
  395. mTextureViews[key] = createView(key);
  396. iterFind = mTextureViews.find(key);
  397. }
  398. return iterFind->second;
  399. }
  400. /************************************************************************/
  401. /* STATICS */
  402. /************************************************************************/
  403. SPtr<Texture> Texture::create(const TEXTURE_DESC& desc, GpuDeviceFlags deviceMask)
  404. {
  405. return TextureManager::instance().createTexture(desc, deviceMask);
  406. }
  407. SPtr<Texture> Texture::create(const SPtr<PixelData>& pixelData, int usage, bool hwGammaCorrection,
  408. GpuDeviceFlags deviceMask)
  409. {
  410. TEXTURE_DESC desc;
  411. desc.type = pixelData->getDepth() > 1 ? TEX_TYPE_3D : TEX_TYPE_2D;
  412. desc.width = pixelData->getWidth();
  413. desc.height = pixelData->getHeight();
  414. desc.depth = pixelData->getDepth();
  415. desc.format = pixelData->getFormat();
  416. desc.usage = usage;
  417. desc.hwGamma = hwGammaCorrection;
  418. SPtr<Texture> newTex = TextureManager::instance().createTextureInternal(desc, pixelData, deviceMask);
  419. newTex->initialize();
  420. return newTex;
  421. }
  422. }
  423. }