BsTexture.cpp 17 KB

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