BsTexture.cpp 18 KB

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