BsD3D11Texture.cpp 26 KB

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