D3D11TextureCube.cpp 18 KB

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