BsD3D11Texture.cpp 27 KB

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