BsD3D11Texture.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsD3D11Texture.h"
  4. #include "BsD3D11Mappings.h"
  5. #include "BsD3D11Device.h"
  6. #include "BsD3D11RenderAPI.h"
  7. #include "BsD3D11TextureView.h"
  8. #include "CoreThread/BsCoreThread.h"
  9. #include "Error/BsException.h"
  10. #include "Threading/BsAsyncOp.h"
  11. #include "Profiling/BsRenderStats.h"
  12. #include "Math/BsMath.h"
  13. #include "BsD3D11CommandBuffer.h"
  14. namespace bs { namespace ct
  15. {
  16. D3D11Texture::D3D11Texture(const TEXTURE_DESC& desc, const SPtr<PixelData>& initialData,
  17. GpuDeviceFlags deviceMask)
  18. : Texture(desc, initialData, deviceMask),
  19. m1DTex(nullptr), m2DTex(nullptr), m3DTex(nullptr), mDXGIFormat(DXGI_FORMAT_UNKNOWN), mDXGIColorFormat(DXGI_FORMAT_UNKNOWN),
  20. mTex(nullptr), mInternalFormat(PF_UNKNOWN), mStagingBuffer(nullptr), mDXGIDepthStencilFormat(DXGI_FORMAT_UNKNOWN),
  21. mLockedSubresourceIdx(-1), mLockedForReading(false), mStaticBuffer(nullptr)
  22. {
  23. assert((deviceMask == GDF_DEFAULT || deviceMask == GDF_PRIMARY) && "Multiple GPUs not supported natively on DirectX 11.");
  24. }
  25. D3D11Texture::~D3D11Texture()
  26. {
  27. clearBufferViews();
  28. SAFE_RELEASE(mTex);
  29. SAFE_RELEASE(m1DTex);
  30. SAFE_RELEASE(m2DTex);
  31. SAFE_RELEASE(m3DTex);
  32. SAFE_RELEASE(mStagingBuffer);
  33. BS_INC_RENDER_STAT_CAT(ResDestroyed, RenderStatObject_Texture);
  34. }
  35. void D3D11Texture::initialize()
  36. {
  37. THROW_IF_NOT_CORE_THREAD;
  38. switch (mProperties.getTextureType())
  39. {
  40. case TEX_TYPE_1D:
  41. create1DTex();
  42. break;
  43. case TEX_TYPE_2D:
  44. case TEX_TYPE_CUBE_MAP:
  45. create2DTex();
  46. break;
  47. case TEX_TYPE_3D:
  48. create3DTex();
  49. break;
  50. default:
  51. BS_EXCEPT(RenderingAPIException, "Unknown texture type");
  52. }
  53. BS_INC_RENDER_STAT_CAT(ResCreated, RenderStatObject_Texture);
  54. Texture::initialize();
  55. }
  56. void D3D11Texture::copyImpl(const SPtr<Texture>& target, const TEXTURE_COPY_DESC& desc,
  57. const SPtr<CommandBuffer>& commandBuffer)
  58. {
  59. auto executeRef = [this](const SPtr<Texture>& target, const TEXTURE_COPY_DESC& desc)
  60. {
  61. D3D11Texture* other = static_cast<D3D11Texture*>(target.get());
  62. UINT32 srcResIdx = D3D11CalcSubresource(desc.srcMip, desc.srcFace, mProperties.getNumMipmaps() + 1);
  63. UINT32 destResIdx = D3D11CalcSubresource(desc.dstMip, desc.dstFace, target->getProperties().getNumMipmaps() + 1);
  64. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPI::instancePtr());
  65. D3D11Device& device = rs->getPrimaryDevice();
  66. bool srcHasMultisample = mProperties.getNumSamples() > 1;
  67. bool destHasMultisample = target->getProperties().getNumSamples() > 1;
  68. bool copyEntireSurface = desc.srcVolume.getWidth() == 0 ||
  69. desc.srcVolume.getHeight() == 0 ||
  70. desc.srcVolume.getDepth() == 0;
  71. if (srcHasMultisample && !destHasMultisample) // Resolving from MS to non-MS texture
  72. {
  73. if(copyEntireSurface)
  74. device.getImmediateContext()->ResolveSubresource(other->getDX11Resource(), destResIdx, mTex, srcResIdx, mDXGIFormat);
  75. else
  76. {
  77. // Need to first resolve to a temporary texture, then copy
  78. TEXTURE_DESC tempDesc;
  79. tempDesc.width = mProperties.getWidth();
  80. tempDesc.height = mProperties.getHeight();
  81. tempDesc.format = mProperties.getFormat();
  82. tempDesc.hwGamma = mProperties.isHardwareGammaEnabled();
  83. SPtr<D3D11Texture> temporary = std::static_pointer_cast<D3D11Texture>(Texture::create(tempDesc));
  84. device.getImmediateContext()->ResolveSubresource(temporary->getDX11Resource(), 0, mTex, srcResIdx, mDXGIFormat);
  85. TEXTURE_COPY_DESC tempCopyDesc;
  86. tempCopyDesc.dstMip = desc.dstMip;
  87. tempCopyDesc.dstFace = desc.dstFace;
  88. tempCopyDesc.dstPosition = desc.dstPosition;
  89. temporary->copy(target, tempCopyDesc);
  90. }
  91. }
  92. else
  93. {
  94. D3D11_BOX srcRegion;
  95. srcRegion.left = desc.srcVolume.left;
  96. srcRegion.right = desc.srcVolume.right;
  97. srcRegion.top = desc.srcVolume.top;
  98. srcRegion.bottom = desc.srcVolume.bottom;
  99. srcRegion.front = desc.srcVolume.front;
  100. srcRegion.back = desc.srcVolume.back;
  101. D3D11_BOX* srcRegionPtr = nullptr;
  102. if(!copyEntireSurface)
  103. srcRegionPtr = &srcRegion;
  104. device.getImmediateContext()->CopySubresourceRegion(
  105. other->getDX11Resource(),
  106. destResIdx,
  107. (UINT32)desc.dstPosition.x,
  108. (UINT32)desc.dstPosition.y,
  109. (UINT32)desc.dstPosition.z,
  110. mTex,
  111. srcResIdx,
  112. srcRegionPtr);
  113. if (device.hasError())
  114. {
  115. String errorDescription = device.getErrorDescription();
  116. BS_EXCEPT(RenderingAPIException, "D3D11 device cannot copy subresource\nError Description:" + errorDescription);
  117. }
  118. }
  119. };
  120. if (commandBuffer == nullptr)
  121. executeRef(target, desc);
  122. else
  123. {
  124. auto execute = [=]() { executeRef(target, desc); };
  125. SPtr<D3D11CommandBuffer> cb = std::static_pointer_cast<D3D11CommandBuffer>(commandBuffer);
  126. cb->queueCommand(execute);
  127. }
  128. }
  129. PixelData D3D11Texture::lockImpl(GpuLockOptions options, UINT32 mipLevel, UINT32 face, UINT32 deviceIdx,
  130. UINT32 queueIdx)
  131. {
  132. if (mProperties.getNumSamples() > 1)
  133. BS_EXCEPT(InvalidStateException, "Multisampled textures cannot be accessed from the CPU directly.");
  134. #if BS_PROFILING_ENABLED
  135. if (options == GBL_READ_ONLY || options == GBL_READ_WRITE)
  136. {
  137. BS_INC_RENDER_STAT_CAT(ResRead, RenderStatObject_Texture);
  138. }
  139. if (options == GBL_READ_WRITE || options == GBL_WRITE_ONLY || options == GBL_WRITE_ONLY_DISCARD || options == GBL_WRITE_ONLY_NO_OVERWRITE)
  140. {
  141. BS_INC_RENDER_STAT_CAT(ResWrite, RenderStatObject_Texture);
  142. }
  143. #endif
  144. UINT32 mipWidth = std::max(1u, mProperties.getWidth() >> mipLevel);
  145. UINT32 mipHeight = std::max(1u, mProperties.getHeight() >> mipLevel);
  146. UINT32 mipDepth = std::max(1u, mProperties.getDepth() >> mipLevel);
  147. PixelData lockedArea(mipWidth, mipHeight, mipDepth, mInternalFormat);
  148. D3D11_MAP flags = D3D11Mappings::getLockOptions(options);
  149. UINT32 rowPitch, slicePitch;
  150. if(flags == D3D11_MAP_READ || flags == D3D11_MAP_READ_WRITE)
  151. {
  152. UINT8* data = (UINT8*)mapstagingbuffer(flags, face, mipLevel, rowPitch, slicePitch);
  153. lockedArea.setExternalBuffer(data);
  154. if (PixelUtil::isCompressed(mProperties.getFormat()))
  155. {
  156. // Doesn't make sense to provide pitch values in pixels in this case
  157. lockedArea.setRowPitch(0);
  158. lockedArea.setSlicePitch(0);
  159. }
  160. else
  161. {
  162. UINT32 bytesPerPixel = PixelUtil::getNumElemBytes(mProperties.getFormat());
  163. lockedArea.setRowPitch(rowPitch / bytesPerPixel);
  164. lockedArea.setSlicePitch(slicePitch / bytesPerPixel);
  165. }
  166. mLockedForReading = true;
  167. }
  168. else
  169. {
  170. if ((mProperties.getUsage() & TU_DYNAMIC) != 0)
  171. {
  172. UINT8* data = (UINT8*)map(mTex, flags, face, mipLevel, rowPitch, slicePitch);
  173. lockedArea.setExternalBuffer(data);
  174. if (PixelUtil::isCompressed(mProperties.getFormat()))
  175. {
  176. // Doesn't make sense to provide pitch values in pixels in this case
  177. lockedArea.setRowPitch(0);
  178. lockedArea.setSlicePitch(0);
  179. }
  180. else
  181. {
  182. UINT32 bytesPerPixel = PixelUtil::getNumElemBytes(mProperties.getFormat());
  183. lockedArea.setRowPitch(rowPitch / bytesPerPixel);
  184. lockedArea.setSlicePitch(slicePitch / bytesPerPixel);
  185. }
  186. }
  187. else
  188. lockedArea.setExternalBuffer((UINT8*)mapstaticbuffer(lockedArea, mipLevel, face));
  189. mLockedForReading = false;
  190. }
  191. return lockedArea;
  192. }
  193. void D3D11Texture::unlockImpl()
  194. {
  195. if(mLockedForReading)
  196. unmapstagingbuffer();
  197. else
  198. {
  199. if ((mProperties.getUsage() & TU_DYNAMIC) != 0)
  200. unmap(mTex);
  201. else
  202. unmapstaticbuffer();
  203. }
  204. }
  205. void D3D11Texture::readDataImpl(PixelData& dest, UINT32 mipLevel, UINT32 face, UINT32 deviceIdx, UINT32 queueIdx)
  206. {
  207. if (mProperties.getNumSamples() > 1)
  208. {
  209. LOGERR("Multisampled textures cannot be accessed from the CPU directly.");
  210. return;
  211. }
  212. PixelData myData = lock(GBL_READ_ONLY, mipLevel, face, deviceIdx, queueIdx);
  213. PixelUtil::bulkPixelConversion(myData, dest);
  214. unlock();
  215. }
  216. void D3D11Texture::writeDataImpl(const PixelData& src, UINT32 mipLevel, UINT32 face, bool discardWholeBuffer,
  217. UINT32 queueIdx)
  218. {
  219. PixelFormat format = mProperties.getFormat();
  220. if (mProperties.getNumSamples() > 1)
  221. {
  222. LOGERR("Multisampled textures cannot be accessed from the CPU directly.");
  223. return;
  224. }
  225. mipLevel = Math::clamp(mipLevel, (UINT32)mipLevel, mProperties.getNumMipmaps());
  226. face = Math::clamp(face, (UINT32)0, mProperties.getNumFaces() - 1);
  227. if (face > 0 && mProperties.getTextureType() == TEX_TYPE_3D)
  228. {
  229. LOGERR("3D texture arrays are not supported.");
  230. return;
  231. }
  232. if ((mProperties.getUsage() & TU_DYNAMIC) != 0)
  233. {
  234. PixelData myData = lock(discardWholeBuffer ? GBL_WRITE_ONLY_DISCARD : GBL_WRITE_ONLY, mipLevel, face, 0, queueIdx);
  235. PixelUtil::bulkPixelConversion(src, myData);
  236. unlock();
  237. }
  238. else if ((mProperties.getUsage() & TU_DEPTHSTENCIL) == 0)
  239. {
  240. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPI::instancePtr());
  241. D3D11Device& device = rs->getPrimaryDevice();
  242. UINT subresourceIdx = D3D11CalcSubresource(mipLevel, face, mProperties.getNumMipmaps() + 1);
  243. UINT32 rowWidth = D3D11Mappings::getSizeInBytes(format, src.getWidth());
  244. UINT32 sliceWidth = D3D11Mappings::getSizeInBytes(format, src.getWidth(), src.getHeight());
  245. device.getImmediateContext()->UpdateSubresource(mTex, subresourceIdx, nullptr, src.getData(), rowWidth, sliceWidth);
  246. if (device.hasError())
  247. {
  248. String errorDescription = device.getErrorDescription();
  249. BS_EXCEPT(RenderingAPIException, "D3D11 device cannot map texture\nError Description:" + errorDescription);
  250. }
  251. BS_INC_RENDER_STAT_CAT(ResWrite, RenderStatObject_Texture);
  252. }
  253. else
  254. {
  255. BS_EXCEPT(RenderingAPIException, "Trying to write into a buffer with unsupported usage: " + toString(mProperties.getUsage()));
  256. }
  257. }
  258. void D3D11Texture::create1DTex()
  259. {
  260. UINT32 width = mProperties.getWidth();
  261. int usage = mProperties.getUsage();
  262. UINT32 numMips = mProperties.getNumMipmaps();
  263. PixelFormat format = mProperties.getFormat();
  264. bool hwGamma = mProperties.isHardwareGammaEnabled();
  265. PixelFormat closestFormat = D3D11Mappings::getClosestSupportedPF(format, TEX_TYPE_1D, usage);
  266. UINT32 numFaces = mProperties.getNumFaces();
  267. // We must have those defined here
  268. assert(width > 0);
  269. // Determine which D3D11 pixel format we'll use
  270. HRESULT hr;
  271. DXGI_FORMAT d3dPF = D3D11Mappings::getPF(closestFormat, hwGamma);
  272. if (format != closestFormat)
  273. {
  274. LOGWRN(StringUtil::format("Provided pixel format is not supported by the driver: {0}. Falling back on: {1}.",
  275. format, closestFormat));
  276. }
  277. mInternalFormat = closestFormat;
  278. mDXGIColorFormat = d3dPF;
  279. mDXGIDepthStencilFormat = d3dPF;
  280. // TODO - Consider making this a parameter eventually
  281. bool readableDepth = true;
  282. D3D11_TEXTURE1D_DESC desc;
  283. desc.Width = static_cast<UINT32>(width);
  284. desc.ArraySize = numFaces == 0 ? 1 : numFaces;
  285. desc.Format = d3dPF;
  286. desc.MiscFlags = 0;
  287. if((usage & TU_RENDERTARGET) != 0)
  288. {
  289. desc.Usage = D3D11_USAGE_DEFAULT;
  290. desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
  291. desc.CPUAccessFlags = 0;
  292. desc.MipLevels = 1;
  293. }
  294. else if ((usage & TU_DEPTHSTENCIL) != 0)
  295. {
  296. desc.Usage = D3D11_USAGE_DEFAULT;
  297. if(readableDepth)
  298. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
  299. else
  300. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  301. desc.CPUAccessFlags = 0;
  302. desc.MipLevels = 1;
  303. desc.Format = D3D11Mappings::getTypelessDepthStencilPF(closestFormat);
  304. mDXGIColorFormat = D3D11Mappings::getShaderResourceDepthStencilPF(closestFormat);
  305. mDXGIDepthStencilFormat = d3dPF;
  306. }
  307. else
  308. {
  309. desc.Usage = D3D11Mappings::getUsage((GpuBufferUsage)usage);
  310. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  311. desc.CPUAccessFlags = D3D11Mappings::getAccessFlags((GpuBufferUsage)usage);
  312. // Determine total number of mipmaps including main one (d3d11 convention)
  313. desc.MipLevels = (numMips == MIP_UNLIMITED || (1U << numMips) > width) ? 0 : numMips + 1;
  314. }
  315. if ((usage & TU_LOADSTORE) != 0)
  316. desc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS;
  317. // Create the texture
  318. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPI::instancePtr());
  319. D3D11Device& device = rs->getPrimaryDevice();
  320. hr = device.getD3D11Device()->CreateTexture1D(&desc, nullptr, &m1DTex);
  321. // Check result and except if failed
  322. if (FAILED(hr) || device.hasError())
  323. {
  324. String errorDescription = device.getErrorDescription();
  325. BS_EXCEPT(RenderingAPIException, "Error creating texture\nError Description:" + errorDescription);
  326. }
  327. hr = m1DTex->QueryInterface(__uuidof(ID3D11Resource), (void **)&mTex);
  328. if(FAILED(hr) || device.hasError())
  329. {
  330. String errorDescription = device.getErrorDescription();
  331. BS_EXCEPT(RenderingAPIException, "Can't get base texture\nError Description:" + errorDescription);
  332. }
  333. m1DTex->GetDesc(&desc);
  334. if(numMips != (desc.MipLevels - 1))
  335. {
  336. BS_EXCEPT(RenderingAPIException, "Driver returned different number of mip maps than requested. " \
  337. "Requested: " + toString(numMips) + ". Got: " + toString(desc.MipLevels - 1) + ".");
  338. }
  339. mDXGIFormat = desc.Format;
  340. // Create texture view
  341. if ((usage & TU_DEPTHSTENCIL) == 0 || readableDepth)
  342. {
  343. TEXTURE_VIEW_DESC viewDesc;
  344. viewDesc.mostDetailMip = 0;
  345. viewDesc.numMips = desc.MipLevels;
  346. viewDesc.firstArraySlice = 0;
  347. viewDesc.numArraySlices = desc.ArraySize;
  348. viewDesc.usage = GVU_DEFAULT;
  349. mShaderResourceView = bs_shared_ptr<D3D11TextureView>(new (bs_alloc<D3D11TextureView>()) D3D11TextureView(this, viewDesc));
  350. }
  351. }
  352. void D3D11Texture::create2DTex()
  353. {
  354. UINT32 width = mProperties.getWidth();
  355. UINT32 height = mProperties.getHeight();
  356. int usage = mProperties.getUsage();
  357. UINT32 numMips = mProperties.getNumMipmaps();
  358. PixelFormat format = mProperties.getFormat();
  359. bool hwGamma = mProperties.isHardwareGammaEnabled();
  360. UINT32 sampleCount = mProperties.getNumSamples();
  361. TextureType texType = mProperties.getTextureType();
  362. PixelFormat closestFormat = D3D11Mappings::getClosestSupportedPF(format, texType, usage);
  363. UINT32 numFaces = mProperties.getNumFaces();
  364. // TODO - Consider making this a parameter eventually
  365. bool readableDepth = true;
  366. // We must have those defined here
  367. assert(width > 0 || height > 0);
  368. // Determine which D3D11 pixel format we'll use
  369. HRESULT hr;
  370. DXGI_FORMAT d3dPF = D3D11Mappings::getPF(closestFormat, hwGamma);
  371. if (format != closestFormat)
  372. {
  373. LOGWRN(StringUtil::format("Provided pixel format is not supported by the driver: {0}. Falling back on: {1}.",
  374. format, closestFormat));
  375. }
  376. mInternalFormat = closestFormat;
  377. mDXGIColorFormat = d3dPF;
  378. mDXGIDepthStencilFormat = d3dPF;
  379. D3D11_TEXTURE2D_DESC desc;
  380. desc.Width = static_cast<UINT32>(width);
  381. desc.Height = static_cast<UINT32>(height);
  382. desc.ArraySize = numFaces == 0 ? 1 : numFaces;;
  383. desc.Format = d3dPF;
  384. desc.MiscFlags = 0;
  385. if((usage & TU_RENDERTARGET) != 0)
  386. {
  387. desc.Usage = D3D11_USAGE_DEFAULT;
  388. desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; // TODO - Add flags to allow RT be created without shader resource flags (might be more optimal)
  389. desc.CPUAccessFlags = 0;
  390. DXGI_SAMPLE_DESC sampleDesc;
  391. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPI::instancePtr());
  392. rs->determineMultisampleSettings(sampleCount, d3dPF, &sampleDesc);
  393. desc.SampleDesc = sampleDesc;
  394. }
  395. else if((usage & TU_DEPTHSTENCIL) != 0)
  396. {
  397. desc.Usage = D3D11_USAGE_DEFAULT;
  398. desc.CPUAccessFlags = 0;
  399. desc.Format = D3D11Mappings::getTypelessDepthStencilPF(closestFormat);
  400. if(readableDepth)
  401. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
  402. else
  403. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  404. DXGI_SAMPLE_DESC sampleDesc;
  405. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPI::instancePtr());
  406. rs->determineMultisampleSettings(sampleCount, d3dPF, &sampleDesc);
  407. desc.SampleDesc = sampleDesc;
  408. mDXGIColorFormat = D3D11Mappings::getShaderResourceDepthStencilPF(closestFormat);
  409. mDXGIDepthStencilFormat = d3dPF;
  410. }
  411. else
  412. {
  413. desc.Usage = D3D11Mappings::getUsage((GpuBufferUsage)usage);
  414. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  415. desc.CPUAccessFlags = D3D11Mappings::getAccessFlags((GpuBufferUsage)usage);
  416. DXGI_SAMPLE_DESC sampleDesc;
  417. sampleDesc.Count = 1;
  418. sampleDesc.Quality = 0;
  419. desc.SampleDesc = sampleDesc;
  420. }
  421. // Determine total number of mipmaps including main one (d3d11 convention)
  422. desc.MipLevels = (numMips == MIP_UNLIMITED || (1U << numMips) > width) ? 0 : numMips + 1;
  423. if (texType == TEX_TYPE_CUBE_MAP)
  424. desc.MiscFlags |= D3D11_RESOURCE_MISC_TEXTURECUBE;
  425. if ((usage & TU_LOADSTORE) != 0)
  426. {
  427. if(desc.SampleDesc.Count <= 1)
  428. desc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS;
  429. else
  430. {
  431. LOGWRN("Unable to create a load-store texture with multiple samples. This is not supported on DirectX 11. "
  432. "Ignoring load-store usage flag.");
  433. }
  434. }
  435. // Create the texture
  436. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPI::instancePtr());
  437. D3D11Device& device = rs->getPrimaryDevice();
  438. hr = device.getD3D11Device()->CreateTexture2D(&desc, nullptr, &m2DTex);
  439. // Check result and except if failed
  440. if (FAILED(hr) || device.hasError())
  441. {
  442. String errorDescription = device.getErrorDescription();
  443. BS_EXCEPT(RenderingAPIException, "Error creating texture\nError Description:" + errorDescription);
  444. }
  445. hr = m2DTex->QueryInterface(__uuidof(ID3D11Resource), (void **)&mTex);
  446. if(FAILED(hr) || device.hasError())
  447. {
  448. String errorDescription = device.getErrorDescription();
  449. BS_EXCEPT(RenderingAPIException, "Can't get base texture\nError Description:" + errorDescription);
  450. }
  451. m2DTex->GetDesc(&desc);
  452. if(numMips != (desc.MipLevels - 1))
  453. {
  454. BS_EXCEPT(RenderingAPIException, "Driver returned different number of mip maps than requested. " \
  455. "Requested: " + toString(numMips) + ". Got: " + toString(desc.MipLevels - 1) + ".");
  456. }
  457. mDXGIFormat = desc.Format;
  458. // Create shader texture view
  459. if((usage & TU_DEPTHSTENCIL) == 0 || readableDepth)
  460. {
  461. TEXTURE_VIEW_DESC viewDesc;
  462. viewDesc.mostDetailMip = 0;
  463. viewDesc.numMips = desc.MipLevels;
  464. viewDesc.firstArraySlice = 0;
  465. viewDesc.numArraySlices = desc.ArraySize;
  466. viewDesc.usage = GVU_DEFAULT;
  467. mShaderResourceView = bs_shared_ptr<D3D11TextureView>(new (bs_alloc<D3D11TextureView>()) D3D11TextureView(this, viewDesc));
  468. }
  469. }
  470. void D3D11Texture::create3DTex()
  471. {
  472. UINT32 width = mProperties.getWidth();
  473. UINT32 height = mProperties.getHeight();
  474. UINT32 depth = mProperties.getDepth();
  475. int usage = mProperties.getUsage();
  476. UINT32 numMips = mProperties.getNumMipmaps();
  477. PixelFormat format = mProperties.getFormat();
  478. bool hwGamma = mProperties.isHardwareGammaEnabled();
  479. PixelFormat closestFormat = D3D11Mappings::getClosestSupportedPF(format, TEX_TYPE_3D, usage);
  480. // TODO - Consider making this a parameter eventually
  481. bool readableDepth = true;
  482. // We must have those defined here
  483. assert(width > 0 && height > 0 && depth > 0);
  484. // Determine which D3D11 pixel format we'll use
  485. HRESULT hr;
  486. DXGI_FORMAT d3dPF = D3D11Mappings::getPF(closestFormat, hwGamma);
  487. if (format != closestFormat)
  488. {
  489. LOGWRN(StringUtil::format("Provided pixel format is not supported by the driver: {0}. Falling back on: {1}.",
  490. format, closestFormat));
  491. }
  492. mInternalFormat = closestFormat;
  493. mDXGIColorFormat = d3dPF;
  494. mDXGIDepthStencilFormat = d3dPF;
  495. D3D11_TEXTURE3D_DESC desc;
  496. desc.Width = static_cast<UINT32>(width);
  497. desc.Height = static_cast<UINT32>(height);
  498. desc.Depth = static_cast<UINT32>(depth);
  499. desc.Format = d3dPF;
  500. desc.MiscFlags = 0;
  501. if ((mProperties.getUsage() & TU_RENDERTARGET) != 0)
  502. {
  503. desc.Usage = D3D11_USAGE_DEFAULT;
  504. desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
  505. desc.CPUAccessFlags = 0;
  506. desc.MipLevels = 1;
  507. }
  508. else if ((mProperties.getUsage() & TU_DEPTHSTENCIL) != 0)
  509. {
  510. desc.Usage = D3D11_USAGE_DEFAULT;
  511. desc.CPUAccessFlags = 0;
  512. desc.MipLevels = 1;
  513. if (readableDepth)
  514. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
  515. else
  516. desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  517. mDXGIColorFormat = D3D11Mappings::getShaderResourceDepthStencilPF(closestFormat);
  518. mDXGIDepthStencilFormat = d3dPF;
  519. }
  520. else
  521. {
  522. desc.Usage = D3D11Mappings::getUsage((GpuBufferUsage)usage);
  523. desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  524. desc.CPUAccessFlags = D3D11Mappings::getAccessFlags((GpuBufferUsage)usage);
  525. // Determine total number of mipmaps including main one (d3d11 convention)
  526. desc.MipLevels = (numMips == MIP_UNLIMITED || (1U << numMips)
  527. > std::max(std::max(width, height), depth)) ? 0 : numMips + 1;
  528. }
  529. if ((usage & TU_LOADSTORE) != 0)
  530. desc.BindFlags |= D3D11_BIND_UNORDERED_ACCESS;
  531. // Create the texture
  532. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPI::instancePtr());
  533. D3D11Device& device = rs->getPrimaryDevice();
  534. hr = device.getD3D11Device()->CreateTexture3D(&desc, nullptr, &m3DTex);
  535. // Check result and except if failed
  536. if (FAILED(hr) || device.hasError())
  537. {
  538. String errorDescription = device.getErrorDescription();
  539. BS_EXCEPT(RenderingAPIException, "Error creating texture\nError Description:" + errorDescription);
  540. }
  541. hr = m3DTex->QueryInterface(__uuidof(ID3D11Resource), (void **)&mTex);
  542. if(FAILED(hr) || device.hasError())
  543. {
  544. String errorDescription = device.getErrorDescription();
  545. BS_EXCEPT(RenderingAPIException, "Can't get base texture\nError Description:" + errorDescription);
  546. }
  547. // Create texture view
  548. m3DTex->GetDesc(&desc);
  549. if (mProperties.getNumMipmaps() != (desc.MipLevels - 1))
  550. {
  551. BS_EXCEPT(RenderingAPIException, "Driver returned different number of mip maps than requested. " \
  552. "Requested: " + toString(mProperties.getNumMipmaps()) + ". Got: " + toString(desc.MipLevels - 1) + ".");
  553. }
  554. mDXGIFormat = desc.Format;
  555. if ((usage & TU_DEPTHSTENCIL) == 0 || readableDepth)
  556. {
  557. TEXTURE_VIEW_DESC viewDesc;
  558. viewDesc.mostDetailMip = 0;
  559. viewDesc.numMips = desc.MipLevels;
  560. viewDesc.firstArraySlice = 0;
  561. viewDesc.numArraySlices = 1;
  562. viewDesc.usage = GVU_DEFAULT;
  563. mShaderResourceView = bs_shared_ptr<D3D11TextureView>(new (bs_alloc<D3D11TextureView>()) D3D11TextureView(this, viewDesc));
  564. }
  565. }
  566. void* D3D11Texture::map(ID3D11Resource* res, D3D11_MAP flags, UINT32 mipLevel, UINT32 face, UINT32& rowPitch, UINT32& slicePitch)
  567. {
  568. D3D11_MAPPED_SUBRESOURCE pMappedResource;
  569. pMappedResource.pData = nullptr;
  570. mipLevel = Math::clamp(mipLevel, (UINT32)mipLevel, mProperties.getNumMipmaps());
  571. face = Math::clamp(face, (UINT32)0, mProperties.getNumFaces() - 1);
  572. if (mProperties.getTextureType() == TEX_TYPE_3D)
  573. face = 0;
  574. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPI::instancePtr());
  575. D3D11Device& device = rs->getPrimaryDevice();
  576. mLockedSubresourceIdx = D3D11CalcSubresource(mipLevel, face, mProperties.getNumMipmaps() + 1);
  577. device.getImmediateContext()->Map(res, mLockedSubresourceIdx, flags, 0, &pMappedResource);
  578. if (device.hasError())
  579. {
  580. String errorDescription = device.getErrorDescription();
  581. BS_EXCEPT(RenderingAPIException, "D3D11 device cannot map texture\nError Description:" + errorDescription);
  582. }
  583. rowPitch = pMappedResource.RowPitch;
  584. slicePitch = pMappedResource.DepthPitch;
  585. return pMappedResource.pData;
  586. }
  587. void D3D11Texture::unmap(ID3D11Resource* res)
  588. {
  589. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPI::instancePtr());
  590. D3D11Device& device = rs->getPrimaryDevice();
  591. device.getImmediateContext()->Unmap(res, mLockedSubresourceIdx);
  592. if (device.hasError())
  593. {
  594. String errorDescription = device.getErrorDescription();
  595. BS_EXCEPT(RenderingAPIException, "D3D11 device unmap resource\nError Description:" + errorDescription);
  596. }
  597. }
  598. void* D3D11Texture::mapstagingbuffer(D3D11_MAP flags, UINT32 mipLevel, UINT32 face, UINT32& rowPitch, UINT32& slicePitch)
  599. {
  600. // Note: I am creating and destroying a staging resource every time a texture is read.
  601. // Consider offering a flag on init that will keep this active all the time (at the cost of double memory).
  602. // Reading is slow operation anyway so I don't believe doing it as we are now will influence it much.
  603. if(!mStagingBuffer)
  604. createStagingBuffer();
  605. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPI::instancePtr());
  606. D3D11Device& device = rs->getPrimaryDevice();
  607. device.getImmediateContext()->CopyResource(mStagingBuffer, mTex);
  608. return map(mStagingBuffer, flags, face, mipLevel, rowPitch, slicePitch);
  609. }
  610. void D3D11Texture::unmapstagingbuffer()
  611. {
  612. unmap(mStagingBuffer);
  613. SAFE_RELEASE(mStagingBuffer);
  614. }
  615. void* D3D11Texture::mapstaticbuffer(PixelData lock, UINT32 mipLevel, UINT32 face)
  616. {
  617. UINT32 sizeOfImage = lock.getConsecutiveSize();
  618. mLockedSubresourceIdx = D3D11CalcSubresource(mipLevel, face, mProperties.getNumMipmaps()+1);
  619. mStaticBuffer = bs_new<PixelData>(lock.getWidth(), lock.getHeight(), lock.getDepth(), lock.getFormat());
  620. mStaticBuffer->allocateInternalBuffer();
  621. return mStaticBuffer->getData();
  622. }
  623. void D3D11Texture::unmapstaticbuffer()
  624. {
  625. UINT32 rowWidth = D3D11Mappings::getSizeInBytes(mStaticBuffer->getFormat(), mStaticBuffer->getWidth());
  626. UINT32 sliceWidth = D3D11Mappings::getSizeInBytes(mStaticBuffer->getFormat(), mStaticBuffer->getWidth(), mStaticBuffer->getHeight());
  627. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPI::instancePtr());
  628. D3D11Device& device = rs->getPrimaryDevice();
  629. device.getImmediateContext()->UpdateSubresource(mTex, mLockedSubresourceIdx, nullptr, mStaticBuffer->getData(), rowWidth, sliceWidth);
  630. if (device.hasError())
  631. {
  632. String errorDescription = device.getErrorDescription();
  633. BS_EXCEPT(RenderingAPIException, "D3D11 device cannot map texture\nError Description:" + errorDescription);
  634. }
  635. if(mStaticBuffer != nullptr)
  636. bs_delete(mStaticBuffer);
  637. }
  638. ID3D11ShaderResourceView* D3D11Texture::getSRV() const
  639. {
  640. return mShaderResourceView->getSRV();
  641. }
  642. void D3D11Texture::createStagingBuffer()
  643. {
  644. D3D11RenderAPI* rs = static_cast<D3D11RenderAPI*>(RenderAPI::instancePtr());
  645. D3D11Device& device = rs->getPrimaryDevice();
  646. switch (mProperties.getTextureType())
  647. {
  648. case TEX_TYPE_1D:
  649. {
  650. D3D11_TEXTURE1D_DESC desc;
  651. m1DTex->GetDesc(&desc);
  652. desc.BindFlags = 0;
  653. desc.MiscFlags = 0;
  654. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
  655. desc.Usage = D3D11_USAGE_STAGING;
  656. device.getD3D11Device()->CreateTexture1D(&desc, nullptr, (ID3D11Texture1D**)(&mStagingBuffer));
  657. }
  658. break;
  659. case TEX_TYPE_2D:
  660. case TEX_TYPE_CUBE_MAP:
  661. {
  662. D3D11_TEXTURE2D_DESC desc;
  663. m2DTex->GetDesc(&desc);
  664. desc.BindFlags = 0;
  665. desc.MiscFlags = 0;
  666. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
  667. desc.Usage = D3D11_USAGE_STAGING;
  668. device.getD3D11Device()->CreateTexture2D(&desc, nullptr, (ID3D11Texture2D**)(&mStagingBuffer));
  669. }
  670. break;
  671. case TEX_TYPE_3D:
  672. {
  673. D3D11_TEXTURE3D_DESC desc;
  674. m3DTex->GetDesc(&desc);
  675. desc.BindFlags = 0;
  676. desc.MiscFlags = 0;
  677. desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
  678. desc.Usage = D3D11_USAGE_STAGING;
  679. device.getD3D11Device()->CreateTexture3D(&desc, nullptr, (ID3D11Texture3D**)(&mStagingBuffer));
  680. }
  681. break;
  682. }
  683. }
  684. SPtr<TextureView> D3D11Texture::createView(const TEXTURE_VIEW_DESC& desc)
  685. {
  686. return bs_shared_ptr<D3D11TextureView>(new (bs_alloc<D3D11TextureView>()) D3D11TextureView(this, desc));
  687. }
  688. }}