BsD3D11Texture.cpp 27 KB

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