D3D11Texture2D.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../../Precompiled.h"
  23. #include "../../Core/Context.h"
  24. #include "../../Core/Profiler.h"
  25. #include "../../Graphics/Graphics.h"
  26. #include "../../Graphics/GraphicsEvents.h"
  27. #include "../../Graphics/GraphicsImpl.h"
  28. #include "../../Graphics/Renderer.h"
  29. #include "../../Graphics/Texture2D.h"
  30. #include "../../IO/FileSystem.h"
  31. #include "../../IO/Log.h"
  32. #include "../../Resource/ResourceCache.h"
  33. #include "../../Resource/XMLFile.h"
  34. #include "../../DebugNew.h"
  35. namespace Atomic
  36. {
  37. void Texture2D::OnDeviceLost()
  38. {
  39. // No-op on Direct3D11
  40. }
  41. void Texture2D::OnDeviceReset()
  42. {
  43. // No-op on Direct3D11
  44. }
  45. void Texture2D::Release()
  46. {
  47. if (graphics_ && object_.ptr_)
  48. {
  49. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  50. {
  51. if (graphics_->GetTexture(i) == this)
  52. graphics_->SetTexture(i, 0);
  53. }
  54. }
  55. if (renderSurface_)
  56. renderSurface_->Release();
  57. ATOMIC_SAFE_RELEASE(object_.ptr_);
  58. ATOMIC_SAFE_RELEASE(resolveTexture_);
  59. ATOMIC_SAFE_RELEASE(shaderResourceView_);
  60. ATOMIC_SAFE_RELEASE(sampler_);
  61. }
  62. bool Texture2D::SetData(unsigned level, int x, int y, int width, int height, const void* data)
  63. {
  64. ATOMIC_PROFILE(SetTextureData);
  65. if (!object_.ptr_)
  66. {
  67. ATOMIC_LOGERROR("No texture created, can not set data");
  68. return false;
  69. }
  70. if (!data)
  71. {
  72. ATOMIC_LOGERROR("Null source for setting data");
  73. return false;
  74. }
  75. if (level >= levels_)
  76. {
  77. ATOMIC_LOGERROR("Illegal mip level for setting data");
  78. return false;
  79. }
  80. int levelWidth = GetLevelWidth(level);
  81. int levelHeight = GetLevelHeight(level);
  82. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  83. {
  84. ATOMIC_LOGERROR("Illegal dimensions for setting data");
  85. return false;
  86. }
  87. // If compressed, align the update region on a block
  88. if (IsCompressed())
  89. {
  90. x &= ~3;
  91. y &= ~3;
  92. width += 3;
  93. width &= 0xfffffffc;
  94. height += 3;
  95. height &= 0xfffffffc;
  96. }
  97. unsigned char* src = (unsigned char*)data;
  98. unsigned rowSize = GetRowDataSize(width);
  99. unsigned rowStart = GetRowDataSize(x);
  100. unsigned subResource = D3D11CalcSubresource(level, 0, levels_);
  101. if (usage_ == TEXTURE_DYNAMIC)
  102. {
  103. if (IsCompressed())
  104. {
  105. height = (height + 3) >> 2;
  106. y >>= 2;
  107. }
  108. D3D11_MAPPED_SUBRESOURCE mappedData;
  109. mappedData.pData = 0;
  110. HRESULT hr = graphics_->GetImpl()->GetDeviceContext()->Map((ID3D11Resource*)object_.ptr_, subResource, D3D11_MAP_WRITE_DISCARD, 0,
  111. &mappedData);
  112. if (FAILED(hr) || !mappedData.pData)
  113. {
  114. ATOMIC_LOGD3DERROR("Failed to map texture for update", hr);
  115. return false;
  116. }
  117. else
  118. {
  119. for (int row = 0; row < height; ++row)
  120. memcpy((unsigned char*)mappedData.pData + (row + y) * mappedData.RowPitch + rowStart, src + row * rowSize, rowSize);
  121. graphics_->GetImpl()->GetDeviceContext()->Unmap((ID3D11Resource*)object_.ptr_, subResource);
  122. }
  123. }
  124. else
  125. {
  126. D3D11_BOX destBox;
  127. destBox.left = (UINT)x;
  128. destBox.right = (UINT)(x + width);
  129. destBox.top = (UINT)y;
  130. destBox.bottom = (UINT)(y + height);
  131. destBox.front = 0;
  132. destBox.back = 1;
  133. graphics_->GetImpl()->GetDeviceContext()->UpdateSubresource((ID3D11Resource*)object_.ptr_, subResource, &destBox, data,
  134. rowSize, 0);
  135. }
  136. return true;
  137. }
  138. bool Texture2D::SetData(Image* image, bool useAlpha)
  139. {
  140. if (!image)
  141. {
  142. ATOMIC_LOGERROR("Null image, can not load texture");
  143. return false;
  144. }
  145. // Use a shared ptr for managing the temporary mip images created during this function
  146. SharedPtr<Image> mipImage;
  147. unsigned memoryUse = sizeof(Texture2D);
  148. int quality = QUALITY_HIGH;
  149. Renderer* renderer = GetSubsystem<Renderer>();
  150. if (renderer)
  151. quality = renderer->GetTextureQuality();
  152. if (!image->IsCompressed())
  153. {
  154. // Convert unsuitable formats to RGBA
  155. unsigned components = image->GetComponents();
  156. if ((components == 1 && !useAlpha) || components == 2 || components == 3)
  157. {
  158. mipImage = image->ConvertToRGBA(); image = mipImage;
  159. if (!image)
  160. return false;
  161. components = image->GetComponents();
  162. }
  163. unsigned char* levelData = image->GetData();
  164. int levelWidth = image->GetWidth();
  165. int levelHeight = image->GetHeight();
  166. unsigned format = 0;
  167. // Discard unnecessary mip levels
  168. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  169. {
  170. mipImage = image->GetNextLevel(); image = mipImage;
  171. levelData = image->GetData();
  172. levelWidth = image->GetWidth();
  173. levelHeight = image->GetHeight();
  174. }
  175. switch (components)
  176. {
  177. case 1:
  178. format = Graphics::GetAlphaFormat();
  179. break;
  180. case 4:
  181. format = Graphics::GetRGBAFormat();
  182. break;
  183. default: break;
  184. }
  185. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  186. if (IsCompressed() && requestedLevels_ > 1)
  187. requestedLevels_ = 0;
  188. SetSize(levelWidth, levelHeight, format);
  189. for (unsigned i = 0; i < levels_; ++i)
  190. {
  191. SetData(i, 0, 0, levelWidth, levelHeight, levelData);
  192. memoryUse += levelWidth * levelHeight * components;
  193. if (i < levels_ - 1)
  194. {
  195. mipImage = image->GetNextLevel(); image = mipImage;
  196. levelData = image->GetData();
  197. levelWidth = image->GetWidth();
  198. levelHeight = image->GetHeight();
  199. }
  200. }
  201. }
  202. else
  203. {
  204. int width = image->GetWidth();
  205. int height = image->GetHeight();
  206. unsigned levels = image->GetNumCompressedLevels();
  207. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  208. bool needDecompress = false;
  209. if (!format)
  210. {
  211. format = Graphics::GetRGBAFormat();
  212. needDecompress = true;
  213. }
  214. unsigned mipsToSkip = mipsToSkip_[quality];
  215. if (mipsToSkip >= levels)
  216. mipsToSkip = levels - 1;
  217. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4))
  218. --mipsToSkip;
  219. width /= (1 << mipsToSkip);
  220. height /= (1 << mipsToSkip);
  221. SetNumLevels(Max((levels - mipsToSkip), 1U));
  222. SetSize(width, height, format);
  223. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  224. {
  225. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  226. if (!needDecompress)
  227. {
  228. SetData(i, 0, 0, level.width_, level.height_, level.data_);
  229. memoryUse += level.rows_ * level.rowSize_;
  230. }
  231. else
  232. {
  233. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  234. level.Decompress(rgbaData);
  235. SetData(i, 0, 0, level.width_, level.height_, rgbaData);
  236. memoryUse += level.width_ * level.height_ * 4;
  237. delete[] rgbaData;
  238. }
  239. }
  240. }
  241. SetMemoryUse(memoryUse);
  242. return true;
  243. }
  244. bool Texture2D::GetData(unsigned level, void* dest) const
  245. {
  246. if (!object_.ptr_)
  247. {
  248. ATOMIC_LOGERROR("No texture created, can not get data");
  249. return false;
  250. }
  251. if (!dest)
  252. {
  253. ATOMIC_LOGERROR("Null destination for getting data");
  254. return false;
  255. }
  256. if (level >= levels_)
  257. {
  258. ATOMIC_LOGERROR("Illegal mip level for getting data");
  259. return false;
  260. }
  261. if (multiSample_ > 1 && !autoResolve_)
  262. {
  263. ATOMIC_LOGERROR("Can not get data from multisampled texture without autoresolve");
  264. return false;
  265. }
  266. if (resolveDirty_)
  267. graphics_->ResolveToTexture(const_cast<Texture2D*>(this));
  268. int levelWidth = GetLevelWidth(level);
  269. int levelHeight = GetLevelHeight(level);
  270. D3D11_TEXTURE2D_DESC textureDesc;
  271. memset(&textureDesc, 0, sizeof textureDesc);
  272. textureDesc.Width = (UINT)levelWidth;
  273. textureDesc.Height = (UINT)levelHeight;
  274. textureDesc.MipLevels = 1;
  275. textureDesc.ArraySize = 1;
  276. textureDesc.Format = (DXGI_FORMAT)format_;
  277. textureDesc.SampleDesc.Count = 1;
  278. textureDesc.SampleDesc.Quality = 0;
  279. textureDesc.Usage = D3D11_USAGE_STAGING;
  280. textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  281. ID3D11Texture2D* stagingTexture = 0;
  282. HRESULT hr = graphics_->GetImpl()->GetDevice()->CreateTexture2D(&textureDesc, 0, &stagingTexture);
  283. if (FAILED(hr))
  284. {
  285. ATOMIC_LOGD3DERROR("Failed to create staging texture for GetData", hr);
  286. ATOMIC_SAFE_RELEASE(stagingTexture);
  287. return false;
  288. }
  289. ID3D11Resource* srcResource = (ID3D11Resource*)(resolveTexture_ ? resolveTexture_ : object_.ptr_);
  290. unsigned srcSubResource = D3D11CalcSubresource(level, 0, levels_);
  291. D3D11_BOX srcBox;
  292. srcBox.left = 0;
  293. srcBox.right = (UINT)levelWidth;
  294. srcBox.top = 0;
  295. srcBox.bottom = (UINT)levelHeight;
  296. srcBox.front = 0;
  297. srcBox.back = 1;
  298. graphics_->GetImpl()->GetDeviceContext()->CopySubresourceRegion(stagingTexture, 0, 0, 0, 0, srcResource,
  299. srcSubResource, &srcBox);
  300. D3D11_MAPPED_SUBRESOURCE mappedData;
  301. mappedData.pData = 0;
  302. unsigned rowSize = GetRowDataSize(levelWidth);
  303. unsigned numRows = (unsigned)(IsCompressed() ? (levelHeight + 3) >> 2 : levelHeight);
  304. hr = graphics_->GetImpl()->GetDeviceContext()->Map((ID3D11Resource*)stagingTexture, 0, D3D11_MAP_READ, 0, &mappedData);
  305. if (FAILED(hr) || !mappedData.pData)
  306. {
  307. ATOMIC_LOGD3DERROR("Failed to map staging texture for GetData", hr);
  308. ATOMIC_SAFE_RELEASE(stagingTexture);
  309. return false;
  310. }
  311. else
  312. {
  313. for (unsigned row = 0; row < numRows; ++row)
  314. memcpy((unsigned char*)dest + row * rowSize, (unsigned char*)mappedData.pData + row * mappedData.RowPitch, rowSize);
  315. graphics_->GetImpl()->GetDeviceContext()->Unmap((ID3D11Resource*)stagingTexture, 0);
  316. ATOMIC_SAFE_RELEASE(stagingTexture);
  317. return true;
  318. }
  319. }
  320. bool Texture2D::Create()
  321. {
  322. Release();
  323. if (!graphics_ || !width_ || !height_)
  324. return false;
  325. levels_ = CheckMaxLevels(width_, height_, requestedLevels_);
  326. D3D11_TEXTURE2D_DESC textureDesc;
  327. memset(&textureDesc, 0, sizeof textureDesc);
  328. textureDesc.Format = (DXGI_FORMAT)(sRGB_ ? GetSRGBFormat(format_) : format_);
  329. // Disable multisampling if not supported
  330. if (multiSample_ > 1 && !graphics_->GetImpl()->CheckMultiSampleSupport(textureDesc.Format, multiSample_))
  331. {
  332. multiSample_ = 1;
  333. autoResolve_ = false;
  334. }
  335. // Set mipmapping
  336. if (usage_ == TEXTURE_DEPTHSTENCIL)
  337. levels_ = 1;
  338. else if (usage_ == TEXTURE_RENDERTARGET && levels_ != 1 && multiSample_ == 1)
  339. textureDesc.MiscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
  340. textureDesc.Width = (UINT)width_;
  341. textureDesc.Height = (UINT)height_;
  342. // Disable mip levels from the multisample texture. Rather create them to the resolve texture
  343. textureDesc.MipLevels = multiSample_ == 1 ? levels_ : 1;
  344. textureDesc.ArraySize = 1;
  345. textureDesc.SampleDesc.Count = (UINT)multiSample_;
  346. textureDesc.SampleDesc.Quality = graphics_->GetImpl()->GetMultiSampleQuality(textureDesc.Format, multiSample_);
  347. textureDesc.Usage = usage_ == TEXTURE_DYNAMIC ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
  348. textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  349. if (usage_ == TEXTURE_RENDERTARGET)
  350. textureDesc.BindFlags |= D3D11_BIND_RENDER_TARGET;
  351. else if (usage_ == TEXTURE_DEPTHSTENCIL)
  352. textureDesc.BindFlags |= D3D11_BIND_DEPTH_STENCIL;
  353. textureDesc.CPUAccessFlags = usage_ == TEXTURE_DYNAMIC ? D3D11_CPU_ACCESS_WRITE : 0;
  354. // D3D feature level 10.0 or below does not support readable depth when multisampled
  355. if (usage_ == TEXTURE_DEPTHSTENCIL && multiSample_ > 1 && graphics_->GetImpl()->GetDevice()->GetFeatureLevel() < D3D_FEATURE_LEVEL_10_1)
  356. textureDesc.BindFlags &= ~D3D11_BIND_SHADER_RESOURCE;
  357. HRESULT hr = graphics_->GetImpl()->GetDevice()->CreateTexture2D(&textureDesc, 0, (ID3D11Texture2D**)&object_);
  358. if (FAILED(hr))
  359. {
  360. ATOMIC_LOGD3DERROR("Failed to create texture", hr);
  361. ATOMIC_SAFE_RELEASE(object_.ptr_);
  362. return false;
  363. }
  364. // Create resolve texture for multisampling if necessary
  365. if (multiSample_ > 1 && autoResolve_)
  366. {
  367. textureDesc.MipLevels = levels_;
  368. textureDesc.SampleDesc.Count = 1;
  369. textureDesc.SampleDesc.Quality = 0;
  370. if (levels_ != 1)
  371. textureDesc.MiscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
  372. HRESULT hr = graphics_->GetImpl()->GetDevice()->CreateTexture2D(&textureDesc, 0, (ID3D11Texture2D**)&resolveTexture_);
  373. if (FAILED(hr))
  374. {
  375. ATOMIC_LOGD3DERROR("Failed to create resolve texture", hr);
  376. ATOMIC_SAFE_RELEASE(resolveTexture_);
  377. return false;
  378. }
  379. }
  380. if (textureDesc.BindFlags & D3D11_BIND_SHADER_RESOURCE)
  381. {
  382. D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
  383. memset(&resourceViewDesc, 0, sizeof resourceViewDesc);
  384. resourceViewDesc.Format = (DXGI_FORMAT)GetSRVFormat(textureDesc.Format);
  385. resourceViewDesc.ViewDimension = (multiSample_ > 1 && !autoResolve_) ? D3D11_SRV_DIMENSION_TEXTURE2DMS :
  386. D3D11_SRV_DIMENSION_TEXTURE2D;
  387. resourceViewDesc.Texture2D.MipLevels = (UINT)levels_;
  388. // Sample the resolve texture if created, otherwise the original
  389. ID3D11Resource* viewObject = resolveTexture_ ? (ID3D11Resource*)resolveTexture_ : (ID3D11Resource*)object_.ptr_;
  390. hr = graphics_->GetImpl()->GetDevice()->CreateShaderResourceView(viewObject, &resourceViewDesc,
  391. (ID3D11ShaderResourceView**)&shaderResourceView_);
  392. if (FAILED(hr))
  393. {
  394. ATOMIC_LOGD3DERROR("Failed to create shader resource view for texture", hr);
  395. ATOMIC_SAFE_RELEASE(shaderResourceView_);
  396. return false;
  397. }
  398. }
  399. if (usage_ == TEXTURE_RENDERTARGET)
  400. {
  401. D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
  402. memset(&renderTargetViewDesc, 0, sizeof renderTargetViewDesc);
  403. renderTargetViewDesc.Format = textureDesc.Format;
  404. renderTargetViewDesc.ViewDimension = multiSample_ > 1 ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D;
  405. hr = graphics_->GetImpl()->GetDevice()->CreateRenderTargetView((ID3D11Resource*)object_.ptr_, &renderTargetViewDesc,
  406. (ID3D11RenderTargetView**)&renderSurface_->renderTargetView_);
  407. if (FAILED(hr))
  408. {
  409. ATOMIC_LOGD3DERROR("Failed to create rendertarget view for texture", hr);
  410. ATOMIC_SAFE_RELEASE(renderSurface_->renderTargetView_);
  411. return false;
  412. }
  413. }
  414. else if (usage_ == TEXTURE_DEPTHSTENCIL)
  415. {
  416. D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
  417. memset(&depthStencilViewDesc, 0, sizeof depthStencilViewDesc);
  418. depthStencilViewDesc.Format = (DXGI_FORMAT)GetDSVFormat(textureDesc.Format);
  419. depthStencilViewDesc.ViewDimension = multiSample_ > 1 ? D3D11_DSV_DIMENSION_TEXTURE2DMS : D3D11_DSV_DIMENSION_TEXTURE2D;
  420. hr = graphics_->GetImpl()->GetDevice()->CreateDepthStencilView((ID3D11Resource*)object_.ptr_, &depthStencilViewDesc,
  421. (ID3D11DepthStencilView**)&renderSurface_->renderTargetView_);
  422. if (FAILED(hr))
  423. {
  424. ATOMIC_LOGD3DERROR("Failed to create depth-stencil view for texture", hr);
  425. ATOMIC_SAFE_RELEASE(renderSurface_->renderTargetView_);
  426. return false;
  427. }
  428. // Create also a read-only version of the view for simultaneous depth testing and sampling in shader
  429. // Requires feature level 11
  430. if (graphics_->GetImpl()->GetDevice()->GetFeatureLevel() >= D3D_FEATURE_LEVEL_11_0)
  431. {
  432. depthStencilViewDesc.Flags = D3D11_DSV_READ_ONLY_DEPTH;
  433. hr = graphics_->GetImpl()->GetDevice()->CreateDepthStencilView((ID3D11Resource*)object_.ptr_, &depthStencilViewDesc,
  434. (ID3D11DepthStencilView**)&renderSurface_->readOnlyView_);
  435. if (FAILED(hr))
  436. {
  437. ATOMIC_LOGD3DERROR("Failed to create read-only depth-stencil view for texture", hr);
  438. ATOMIC_SAFE_RELEASE(renderSurface_->readOnlyView_);
  439. }
  440. }
  441. }
  442. return true;
  443. }
  444. }