D3D11Texture2DArray.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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/Texture2DArray.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. #ifdef _MSC_VER
  36. #pragma warning(disable:4355)
  37. #endif
  38. namespace Urho3D
  39. {
  40. void Texture2DArray::OnDeviceLost()
  41. {
  42. // No-op on Direct3D11
  43. }
  44. void Texture2DArray::OnDeviceReset()
  45. {
  46. // No-op on Direct3D11
  47. }
  48. void Texture2DArray::Release()
  49. {
  50. if (graphics_)
  51. {
  52. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  53. {
  54. if (graphics_->GetTexture(i) == this)
  55. graphics_->SetTexture(i, nullptr);
  56. }
  57. }
  58. if (renderSurface_)
  59. renderSurface_->Release();
  60. URHO3D_SAFE_RELEASE(object_.ptr_);
  61. URHO3D_SAFE_RELEASE(shaderResourceView_);
  62. URHO3D_SAFE_RELEASE(sampler_);
  63. levelsDirty_ = false;
  64. }
  65. bool Texture2DArray::SetData(unsigned layer, unsigned level, int x, int y, int width, int height, const void* data)
  66. {
  67. URHO3D_PROFILE(SetTextureData);
  68. if (!object_.ptr_)
  69. {
  70. URHO3D_LOGERROR("Texture array not created, can not set data");
  71. return false;
  72. }
  73. if (!data)
  74. {
  75. URHO3D_LOGERROR("Null source for setting data");
  76. return false;
  77. }
  78. if (layer >= layers_)
  79. {
  80. URHO3D_LOGERROR("Illegal layer for setting data");
  81. return false;
  82. }
  83. if (level >= levels_)
  84. {
  85. URHO3D_LOGERROR("Illegal mip level for setting data");
  86. return false;
  87. }
  88. int levelWidth = GetLevelWidth(level);
  89. int levelHeight = GetLevelHeight(level);
  90. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  91. {
  92. URHO3D_LOGERROR("Illegal dimensions for setting data");
  93. return false;
  94. }
  95. // If compressed, align the update region on a block
  96. if (IsCompressed())
  97. {
  98. x &= ~3;
  99. y &= ~3;
  100. width += 3;
  101. width &= 0xfffffffc;
  102. height += 3;
  103. height &= 0xfffffffc;
  104. }
  105. unsigned char* src = (unsigned char*)data;
  106. unsigned rowSize = GetRowDataSize(width);
  107. unsigned rowStart = GetRowDataSize(x);
  108. unsigned subResource = D3D11CalcSubresource(level, layer, levels_);
  109. if (usage_ == TEXTURE_DYNAMIC)
  110. {
  111. if (IsCompressed())
  112. {
  113. height = (height + 3) >> 2;
  114. y >>= 2;
  115. }
  116. D3D11_MAPPED_SUBRESOURCE mappedData;
  117. mappedData.pData = nullptr;
  118. HRESULT hr = graphics_->GetImpl()->GetDeviceContext()->Map((ID3D11Resource*)object_.ptr_, subResource, D3D11_MAP_WRITE_DISCARD, 0,
  119. &mappedData);
  120. if (FAILED(hr) || !mappedData.pData)
  121. {
  122. URHO3D_LOGD3DERROR("Failed to map texture for update", hr);
  123. return false;
  124. }
  125. else
  126. {
  127. for (int row = 0; row < height; ++row)
  128. memcpy((unsigned char*)mappedData.pData + (row + y) * mappedData.RowPitch + rowStart, src + row * rowSize, rowSize);
  129. graphics_->GetImpl()->GetDeviceContext()->Unmap((ID3D11Resource*)object_.ptr_, subResource);
  130. }
  131. }
  132. else
  133. {
  134. D3D11_BOX destBox;
  135. destBox.left = (UINT)x;
  136. destBox.right = (UINT)(x + width);
  137. destBox.top = (UINT)y;
  138. destBox.bottom = (UINT)(y + height);
  139. destBox.front = 0;
  140. destBox.back = 1;
  141. graphics_->GetImpl()->GetDeviceContext()->UpdateSubresource((ID3D11Resource*)object_.ptr_, subResource, &destBox, data,
  142. rowSize, 0);
  143. }
  144. return true;
  145. }
  146. bool Texture2DArray::SetData(unsigned layer, Deserializer& source)
  147. {
  148. SharedPtr<Image> image(new Image(context_));
  149. if (!image->Load(source))
  150. return false;
  151. return SetData(layer, image);
  152. }
  153. bool Texture2DArray::SetData(unsigned layer, Image* image, bool useAlpha)
  154. {
  155. if (!image)
  156. {
  157. URHO3D_LOGERROR("Null image, can not set data");
  158. return false;
  159. }
  160. if (!layers_)
  161. {
  162. URHO3D_LOGERROR("Number of layers in the array must be set first");
  163. return false;
  164. }
  165. if (layer >= layers_)
  166. {
  167. URHO3D_LOGERROR("Illegal layer for setting data");
  168. return false;
  169. }
  170. // Use a shared ptr for managing the temporary mip images created during this function
  171. SharedPtr<Image> mipImage;
  172. unsigned memoryUse = 0;
  173. int quality = QUALITY_HIGH;
  174. Renderer* renderer = GetSubsystem<Renderer>();
  175. if (renderer)
  176. quality = renderer->GetTextureQuality();
  177. if (!image->IsCompressed())
  178. {
  179. // Convert unsuitable formats to RGBA
  180. unsigned components = image->GetComponents();
  181. if ((components == 1 && !useAlpha) || components == 2 || components == 3)
  182. {
  183. mipImage = image->ConvertToRGBA(); image = mipImage;
  184. if (!image)
  185. return false;
  186. components = image->GetComponents();
  187. }
  188. unsigned char* levelData = image->GetData();
  189. int levelWidth = image->GetWidth();
  190. int levelHeight = image->GetHeight();
  191. unsigned format = 0;
  192. // Discard unnecessary mip levels
  193. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  194. {
  195. mipImage = image->GetNextLevel(); image = mipImage;
  196. levelData = image->GetData();
  197. levelWidth = image->GetWidth();
  198. levelHeight = image->GetHeight();
  199. }
  200. switch (components)
  201. {
  202. case 1:
  203. format = Graphics::GetAlphaFormat();
  204. break;
  205. case 4:
  206. format = Graphics::GetRGBAFormat();
  207. break;
  208. default: break;
  209. }
  210. // Create the texture array when layer 0 is being loaded, check that rest of the layers are same size & format
  211. if (!layer)
  212. {
  213. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  214. if (IsCompressed() && requestedLevels_ > 1)
  215. requestedLevels_ = 0;
  216. // Create the texture array (the number of layers must have been already set)
  217. SetSize(0, levelWidth, levelHeight, format);
  218. }
  219. else
  220. {
  221. if (!object_.ptr_)
  222. {
  223. URHO3D_LOGERROR("Texture array layer 0 must be loaded first");
  224. return false;
  225. }
  226. if (levelWidth != width_ || levelHeight != height_ || format != format_)
  227. {
  228. URHO3D_LOGERROR("Texture array layer does not match size or format of layer 0");
  229. return false;
  230. }
  231. }
  232. for (unsigned i = 0; i < levels_; ++i)
  233. {
  234. SetData(layer, i, 0, 0, levelWidth, levelHeight, levelData);
  235. memoryUse += levelWidth * levelHeight * components;
  236. if (i < levels_ - 1)
  237. {
  238. mipImage = image->GetNextLevel(); image = mipImage;
  239. levelData = image->GetData();
  240. levelWidth = image->GetWidth();
  241. levelHeight = image->GetHeight();
  242. }
  243. }
  244. }
  245. else
  246. {
  247. int width = image->GetWidth();
  248. int height = image->GetHeight();
  249. unsigned levels = image->GetNumCompressedLevels();
  250. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  251. bool needDecompress = false;
  252. if (!format)
  253. {
  254. format = Graphics::GetRGBAFormat();
  255. needDecompress = true;
  256. }
  257. unsigned mipsToSkip = mipsToSkip_[quality];
  258. if (mipsToSkip >= levels)
  259. mipsToSkip = levels - 1;
  260. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4))
  261. --mipsToSkip;
  262. width /= (1 << mipsToSkip);
  263. height /= (1 << mipsToSkip);
  264. // Create the texture array when layer 0 is being loaded, assume rest of the layers are same size & format
  265. if (!layer)
  266. {
  267. SetNumLevels(Max((levels - mipsToSkip), 1U));
  268. SetSize(0, width, height, format);
  269. }
  270. else
  271. {
  272. if (!object_.ptr_)
  273. {
  274. URHO3D_LOGERROR("Texture array layer 0 must be loaded first");
  275. return false;
  276. }
  277. if (width != width_ || height != height_ || format != format_)
  278. {
  279. URHO3D_LOGERROR("Texture array layer does not match size or format of layer 0");
  280. return false;
  281. }
  282. }
  283. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  284. {
  285. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  286. if (!needDecompress)
  287. {
  288. SetData(layer, i, 0, 0, level.width_, level.height_, level.data_);
  289. memoryUse += level.rows_ * level.rowSize_;
  290. }
  291. else
  292. {
  293. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  294. level.Decompress(rgbaData);
  295. SetData(layer, i, 0, 0, level.width_, level.height_, rgbaData);
  296. memoryUse += level.width_ * level.height_ * 4;
  297. delete[] rgbaData;
  298. }
  299. }
  300. }
  301. layerMemoryUse_[layer] = memoryUse;
  302. unsigned totalMemoryUse = sizeof(Texture2DArray) + layerMemoryUse_.Capacity() * sizeof(unsigned);
  303. for (unsigned i = 0; i < layers_; ++i)
  304. totalMemoryUse += layerMemoryUse_[i];
  305. SetMemoryUse(totalMemoryUse);
  306. return true;
  307. }
  308. bool Texture2DArray::GetData(unsigned layer, unsigned level, void* dest) const
  309. {
  310. if (!object_.ptr_)
  311. {
  312. URHO3D_LOGERROR("Texture array not created, can not get data");
  313. return false;
  314. }
  315. if (!dest)
  316. {
  317. URHO3D_LOGERROR("Null destination for getting data");
  318. return false;
  319. }
  320. if (layer >= layers_)
  321. {
  322. URHO3D_LOGERROR("Illegal layer for getting data");
  323. return false;
  324. }
  325. if (level >= levels_)
  326. {
  327. URHO3D_LOGERROR("Illegal mip level for getting data");
  328. return false;
  329. }
  330. int levelWidth = GetLevelWidth(level);
  331. int levelHeight = GetLevelHeight(level);
  332. D3D11_TEXTURE2D_DESC textureDesc;
  333. memset(&textureDesc, 0, sizeof textureDesc);
  334. textureDesc.Width = (UINT)levelWidth;
  335. textureDesc.Height = (UINT)levelHeight;
  336. textureDesc.MipLevels = 1;
  337. textureDesc.ArraySize = 1;
  338. textureDesc.Format = (DXGI_FORMAT)format_;
  339. textureDesc.SampleDesc.Count = 1;
  340. textureDesc.SampleDesc.Quality = 0;
  341. textureDesc.Usage = D3D11_USAGE_STAGING;
  342. textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  343. ID3D11Texture2D* stagingTexture = nullptr;
  344. HRESULT hr = graphics_->GetImpl()->GetDevice()->CreateTexture2D(&textureDesc, nullptr, &stagingTexture);
  345. if (FAILED(hr))
  346. {
  347. URHO3D_LOGD3DERROR("Failed to create staging texture for GetData", hr);
  348. URHO3D_SAFE_RELEASE(stagingTexture);
  349. return false;
  350. }
  351. unsigned srcSubResource = D3D11CalcSubresource(level, layer, levels_);
  352. D3D11_BOX srcBox;
  353. srcBox.left = 0;
  354. srcBox.right = (UINT)levelWidth;
  355. srcBox.top = 0;
  356. srcBox.bottom = (UINT)levelHeight;
  357. srcBox.front = 0;
  358. srcBox.back = 1;
  359. graphics_->GetImpl()->GetDeviceContext()->CopySubresourceRegion(stagingTexture, 0, 0, 0, 0, (ID3D11Resource*)object_.ptr_,
  360. srcSubResource, &srcBox);
  361. D3D11_MAPPED_SUBRESOURCE mappedData;
  362. mappedData.pData = nullptr;
  363. unsigned rowSize = GetRowDataSize(levelWidth);
  364. unsigned numRows = (unsigned)(IsCompressed() ? (levelHeight + 3) >> 2 : levelHeight);
  365. hr = graphics_->GetImpl()->GetDeviceContext()->Map((ID3D11Resource*)stagingTexture, 0, D3D11_MAP_READ, 0, &mappedData);
  366. if (FAILED(hr) || !mappedData.pData)
  367. {
  368. URHO3D_LOGD3DERROR("Failed to map staging texture for GetData", hr);
  369. URHO3D_SAFE_RELEASE(stagingTexture);
  370. return false;
  371. }
  372. else
  373. {
  374. for (unsigned row = 0; row < numRows; ++row)
  375. memcpy((unsigned char*)dest + row * rowSize, (unsigned char*)mappedData.pData + row * mappedData.RowPitch, rowSize);
  376. graphics_->GetImpl()->GetDeviceContext()->Unmap((ID3D11Resource*)stagingTexture, 0);
  377. URHO3D_SAFE_RELEASE(stagingTexture);
  378. return true;
  379. }
  380. }
  381. bool Texture2DArray::Create()
  382. {
  383. Release();
  384. if (!graphics_ || !width_ || !height_ || !layers_)
  385. return false;
  386. levels_ = CheckMaxLevels(width_, height_, requestedLevels_);
  387. D3D11_TEXTURE2D_DESC textureDesc;
  388. memset(&textureDesc, 0, sizeof textureDesc);
  389. // Set mipmapping
  390. if (usage_ == TEXTURE_RENDERTARGET && levels_ != 1)
  391. textureDesc.MiscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS;
  392. textureDesc.Width = (UINT)width_;
  393. textureDesc.Height = (UINT)height_;
  394. textureDesc.MipLevels = levels_;
  395. textureDesc.ArraySize = layers_;
  396. textureDesc.Format = (DXGI_FORMAT)(sRGB_ ? GetSRGBFormat(format_) : format_);
  397. textureDesc.SampleDesc.Count = 1;
  398. textureDesc.SampleDesc.Quality = 0;
  399. textureDesc.Usage = usage_ == TEXTURE_DYNAMIC ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
  400. textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  401. if (usage_ == TEXTURE_RENDERTARGET)
  402. textureDesc.BindFlags |= D3D11_BIND_RENDER_TARGET;
  403. else if (usage_ == TEXTURE_DEPTHSTENCIL)
  404. textureDesc.BindFlags |= D3D11_BIND_DEPTH_STENCIL;
  405. textureDesc.CPUAccessFlags = usage_ == TEXTURE_DYNAMIC ? D3D11_CPU_ACCESS_WRITE : 0;
  406. HRESULT hr = graphics_->GetImpl()->GetDevice()->CreateTexture2D(&textureDesc, nullptr, (ID3D11Texture2D**)&object_);
  407. if (FAILED(hr))
  408. {
  409. URHO3D_LOGD3DERROR("Failed to create texture array", hr);
  410. URHO3D_SAFE_RELEASE(object_.ptr_);
  411. return false;
  412. }
  413. D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
  414. memset(&srvDesc, 0, sizeof srvDesc);
  415. srvDesc.Format = (DXGI_FORMAT)GetSRVFormat(textureDesc.Format);
  416. if (layers_ == 1)
  417. {
  418. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  419. srvDesc.Texture2D.MipLevels = (UINT)levels_;
  420. srvDesc.Texture2D.MostDetailedMip = 0;
  421. }
  422. else
  423. {
  424. srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
  425. srvDesc.Texture2DArray.MipLevels = (UINT)levels_;
  426. srvDesc.Texture2DArray.ArraySize = layers_;
  427. srvDesc.Texture2DArray.FirstArraySlice = 0;
  428. srvDesc.Texture2DArray.MostDetailedMip = 0;
  429. }
  430. hr = graphics_->GetImpl()->GetDevice()->CreateShaderResourceView((ID3D11Resource*)object_.ptr_, &srvDesc,
  431. (ID3D11ShaderResourceView**)&shaderResourceView_);
  432. if (FAILED(hr))
  433. {
  434. URHO3D_LOGD3DERROR("Failed to create shader resource view for texture array", hr);
  435. URHO3D_SAFE_RELEASE(shaderResourceView_);
  436. return false;
  437. }
  438. if (usage_ == TEXTURE_RENDERTARGET)
  439. {
  440. D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
  441. memset(&renderTargetViewDesc, 0, sizeof renderTargetViewDesc);
  442. renderTargetViewDesc.Format = textureDesc.Format;
  443. if (layers_ == 1)
  444. {
  445. renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  446. renderTargetViewDesc.Texture2D.MipSlice = 0;
  447. }
  448. else
  449. {
  450. renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
  451. renderTargetViewDesc.Texture2DArray.MipSlice = 0;
  452. renderTargetViewDesc.Texture2DArray.ArraySize = layers_;
  453. renderTargetViewDesc.Texture2DArray.FirstArraySlice = 0;
  454. }
  455. hr = graphics_->GetImpl()->GetDevice()->CreateRenderTargetView((ID3D11Resource*)object_.ptr_, &renderTargetViewDesc,
  456. (ID3D11RenderTargetView**)&renderSurface_->renderTargetView_);
  457. if (FAILED(hr))
  458. {
  459. URHO3D_LOGD3DERROR("Failed to create rendertarget view for texture array", hr);
  460. URHO3D_SAFE_RELEASE(renderSurface_->renderTargetView_);
  461. return false;
  462. }
  463. }
  464. return true;
  465. }
  466. }