D3D11Texture3D.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. //
  2. // Copyright (c) 2008-2015 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 "../../Core/Context.h"
  23. #include "../../IO/FileSystem.h"
  24. #include "../../Graphics/Graphics.h"
  25. #include "../../Graphics/GraphicsEvents.h"
  26. #include "../../Graphics/GraphicsImpl.h"
  27. #include "../../IO/Log.h"
  28. #include "../../Graphics/Renderer.h"
  29. #include "../../Core/Profiler.h"
  30. #include "../../Resource/ResourceCache.h"
  31. #include "../../Graphics/Texture3D.h"
  32. #include "../../Resource/XMLFile.h"
  33. #include "../../DebugNew.h"
  34. namespace Urho3D
  35. {
  36. Texture3D::Texture3D(Context* context) :
  37. Texture(context)
  38. {
  39. }
  40. Texture3D::~Texture3D()
  41. {
  42. Release();
  43. }
  44. void Texture3D::RegisterObject(Context* context)
  45. {
  46. context->RegisterFactory<Texture3D>();
  47. }
  48. bool Texture3D::BeginLoad(Deserializer& source)
  49. {
  50. ResourceCache* cache = GetSubsystem<ResourceCache>();
  51. // In headless mode, do not actually load the texture, just return success
  52. if (!graphics_)
  53. return true;
  54. String texPath, texName, texExt;
  55. SplitPath(GetName(), texPath, texName, texExt);
  56. cache->ResetDependencies(this);
  57. loadParameters_ = new XMLFile(context_);
  58. if (!loadParameters_->Load(source))
  59. {
  60. loadParameters_.Reset();
  61. return false;
  62. }
  63. XMLElement textureElem = loadParameters_->GetRoot();
  64. XMLElement volumeElem = textureElem.GetChild("volume");
  65. XMLElement colorlutElem = textureElem.GetChild("colorlut");
  66. if (volumeElem)
  67. {
  68. String name = volumeElem.GetAttribute("name");
  69. String volumeTexPath, volumeTexName, volumeTexExt;
  70. SplitPath(name, volumeTexPath, volumeTexName, volumeTexExt);
  71. // If path is empty, add the XML file path
  72. if (volumeTexPath.Empty())
  73. name = texPath + name;
  74. loadImage_ = cache->GetTempResource<Image>(name);
  75. // Precalculate mip levels if async loading
  76. if (loadImage_ && GetAsyncLoadState() == ASYNC_LOADING)
  77. loadImage_->PrecalculateLevels();
  78. cache->StoreResourceDependency(this, name);
  79. return true;
  80. }
  81. else if (colorlutElem)
  82. {
  83. String name = colorlutElem.GetAttribute("name");
  84. String colorlutTexPath, colorlutTexName, colorlutTexExt;
  85. SplitPath(name, colorlutTexPath, colorlutTexName, colorlutTexExt);
  86. // If path is empty, add the XML file path
  87. if (colorlutTexPath.Empty())
  88. name = texPath + name;
  89. SharedPtr<File> file = GetSubsystem<ResourceCache>()->GetFile(name);
  90. loadImage_ = new Image(context_);
  91. if (!loadImage_->LoadColorLUT(*(file.Get())))
  92. {
  93. loadParameters_.Reset();
  94. loadImage_.Reset();
  95. return false;
  96. }
  97. // Precalculate mip levels if async loading
  98. if (loadImage_ && GetAsyncLoadState() == ASYNC_LOADING)
  99. loadImage_->PrecalculateLevels();
  100. cache->StoreResourceDependency(this, name);
  101. return true;
  102. }
  103. LOGERROR("Texture3D XML data for " + GetName() + " did not contain either volume or colorlut element");
  104. return false;
  105. }
  106. bool Texture3D::EndLoad()
  107. {
  108. // In headless mode, do not actually load the texture, just return success
  109. if (!graphics_)
  110. return true;
  111. // If over the texture budget, see if materials can be freed to allow textures to be freed
  112. CheckTextureBudget(GetTypeStatic());
  113. SetParameters(loadParameters_);
  114. bool success = SetData(loadImage_);
  115. loadImage_.Reset();
  116. loadParameters_.Reset();
  117. return success;
  118. }
  119. void Texture3D::Release()
  120. {
  121. if (object_)
  122. {
  123. if (!graphics_)
  124. return;
  125. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  126. {
  127. if (graphics_->GetTexture(i) == this)
  128. graphics_->SetTexture(i, 0);
  129. }
  130. if (renderSurface_)
  131. renderSurface_->Release();
  132. ((ID3D11Resource*)object_)->Release();
  133. object_ = 0;
  134. if (shaderResourceView_)
  135. {
  136. ((ID3D11ShaderResourceView*)shaderResourceView_)->Release();
  137. shaderResourceView_ = 0;
  138. }
  139. if (sampler_)
  140. {
  141. ((ID3D11SamplerState*)sampler_)->Release();
  142. sampler_ = 0;
  143. }
  144. }
  145. else
  146. {
  147. if (renderSurface_)
  148. renderSurface_->Release();
  149. }
  150. }
  151. bool Texture3D::SetSize(int width, int height, int depth, unsigned format, TextureUsage usage)
  152. {
  153. // Delete the old rendersurface if any
  154. renderSurface_.Reset();
  155. usage_ = usage;
  156. if (usage_ == TEXTURE_RENDERTARGET)
  157. {
  158. renderSurface_ = new RenderSurface(this);
  159. // Clamp mode addressing by default, nearest filtering, and mipmaps disabled
  160. addressMode_[COORD_U] = ADDRESS_CLAMP;
  161. addressMode_[COORD_V] = ADDRESS_CLAMP;
  162. filterMode_ = FILTER_NEAREST;
  163. requestedLevels_ = 1;
  164. }
  165. if (usage_ == TEXTURE_RENDERTARGET)
  166. SubscribeToEvent(E_RENDERSURFACEUPDATE, HANDLER(Texture3D, HandleRenderSurfaceUpdate));
  167. else
  168. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  169. width_ = width;
  170. height_ = height;
  171. depth_ = depth;
  172. format_ = format;
  173. return Create();
  174. }
  175. bool Texture3D::SetData(unsigned level, int x, int y, int z, int width, int height, int depth, const void* data)
  176. {
  177. PROFILE(SetTextureData);
  178. if (!object_)
  179. {
  180. LOGERROR("No texture created, can not set data");
  181. return false;
  182. }
  183. if (!data)
  184. {
  185. LOGERROR("Null source for setting data");
  186. return false;
  187. }
  188. if (level >= levels_)
  189. {
  190. LOGERROR("Illegal mip level for setting data");
  191. return false;
  192. }
  193. int levelWidth = GetLevelWidth(level);
  194. int levelHeight = GetLevelHeight(level);
  195. int levelDepth = GetLevelDepth(level);
  196. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || z < 0 || z + depth > levelDepth || width <= 0 || height <= 0 || depth <= 0)
  197. {
  198. LOGERROR("Illegal dimensions for setting data");
  199. return false;
  200. }
  201. // If compressed, align the update region on a block
  202. if (IsCompressed())
  203. {
  204. x &= ~3;
  205. y &= ~3;
  206. width += 3;
  207. width &= 0xfffffffc;
  208. height += 3;
  209. height &= 0xfffffffc;
  210. }
  211. unsigned char* src = (unsigned char*)data;
  212. unsigned rowSize = GetRowDataSize(width);
  213. unsigned rowStart = GetRowDataSize(x);
  214. unsigned subResource = D3D11CalcSubresource(level, 0, levels_);
  215. if (usage_ == TEXTURE_DYNAMIC)
  216. {
  217. if (IsCompressed())
  218. {
  219. height = (height + 3) >> 2;
  220. y >>= 2;
  221. }
  222. D3D11_MAPPED_SUBRESOURCE mappedData;
  223. mappedData.pData = 0;
  224. graphics_->GetImpl()->GetDeviceContext()->Map((ID3D11Resource*)object_, subResource, D3D11_MAP_WRITE_DISCARD, 0,
  225. &mappedData);
  226. if (mappedData.pData)
  227. {
  228. for (int page = 0; page < depth; ++page)
  229. {
  230. for (int row = 0; row < height; ++row)
  231. {
  232. memcpy((unsigned char*)mappedData.pData + (page + z) * mappedData.DepthPitch + (row + y) * mappedData.RowPitch
  233. + rowStart, src + row * rowSize, rowSize);
  234. }
  235. }
  236. graphics_->GetImpl()->GetDeviceContext()->Unmap((ID3D11Resource*)object_, subResource);
  237. }
  238. else
  239. {
  240. LOGERROR("Failed to map texture for update");
  241. return false;
  242. }
  243. }
  244. else
  245. {
  246. if (IsCompressed())
  247. levelHeight = (levelHeight + 3) >> 2;
  248. D3D11_BOX destBox;
  249. destBox.left = x;
  250. destBox.right = x + width;
  251. destBox.top = y;
  252. destBox.bottom = y + height;
  253. destBox.front = z;
  254. destBox.back = z + depth;
  255. graphics_->GetImpl()->GetDeviceContext()->UpdateSubresource((ID3D11Resource*)object_, subResource, &destBox, data,
  256. rowSize, levelHeight * rowSize);
  257. }
  258. return true;
  259. }
  260. bool Texture3D::SetData(SharedPtr<Image> image, bool useAlpha)
  261. {
  262. if (!image)
  263. {
  264. LOGERROR("Null image, can not load texture");
  265. return false;
  266. }
  267. unsigned memoryUse = sizeof(Texture3D);
  268. int quality = QUALITY_HIGH;
  269. Renderer* renderer = GetSubsystem<Renderer>();
  270. if (renderer)
  271. quality = renderer->GetTextureQuality();
  272. if (!image->IsCompressed())
  273. {
  274. // Convert unsuitable formats to RGBA
  275. unsigned components = image->GetComponents();
  276. if ((components == 1 && !useAlpha) || components == 2 || components == 3)
  277. {
  278. image = image->ConvertToRGBA();
  279. if (!image)
  280. return false;
  281. components = image->GetComponents();
  282. }
  283. unsigned char* levelData = image->GetData();
  284. int levelWidth = image->GetWidth();
  285. int levelHeight = image->GetHeight();
  286. int levelDepth = image->GetDepth();
  287. unsigned format = 0;
  288. // Discard unnecessary mip levels
  289. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  290. {
  291. image = image->GetNextLevel();
  292. levelData = image->GetData();
  293. levelWidth = image->GetWidth();
  294. levelHeight = image->GetHeight();
  295. levelDepth = image->GetDepth();
  296. }
  297. switch (components)
  298. {
  299. case 1:
  300. format = Graphics::GetAlphaFormat();
  301. break;
  302. case 4:
  303. format = Graphics::GetRGBAFormat();
  304. break;
  305. }
  306. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  307. if (IsCompressed() && requestedLevels_ > 1)
  308. requestedLevels_ = 0;
  309. SetSize(levelWidth, levelHeight, levelDepth, format);
  310. for (unsigned i = 0; i < levels_; ++i)
  311. {
  312. SetData(i, 0, 0, 0, levelWidth, levelHeight, levelDepth, levelData);
  313. memoryUse += levelWidth * levelHeight * levelDepth * components;
  314. if (i < levels_ - 1)
  315. {
  316. image = image->GetNextLevel();
  317. levelData = image->GetData();
  318. levelWidth = image->GetWidth();
  319. levelHeight = image->GetHeight();
  320. levelDepth = image->GetDepth();
  321. }
  322. }
  323. }
  324. else
  325. {
  326. int width = image->GetWidth();
  327. int height = image->GetHeight();
  328. int depth = image->GetDepth();
  329. unsigned levels = image->GetNumCompressedLevels();
  330. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  331. bool needDecompress = false;
  332. if (!format)
  333. {
  334. format = Graphics::GetRGBAFormat();
  335. needDecompress = true;
  336. }
  337. unsigned mipsToSkip = mipsToSkip_[quality];
  338. if (mipsToSkip >= levels)
  339. mipsToSkip = levels - 1;
  340. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4 || depth / (1 << mipsToSkip) < 4))
  341. --mipsToSkip;
  342. width /= (1 << mipsToSkip);
  343. height /= (1 << mipsToSkip);
  344. depth /= (1 << mipsToSkip);
  345. SetNumLevels(Max((int)(levels - mipsToSkip), 1));
  346. SetSize(width, height, depth, format);
  347. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  348. {
  349. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  350. if (!needDecompress)
  351. {
  352. SetData(i, 0, 0, 0, level.width_, level.height_, level.depth_, level.data_);
  353. memoryUse += level.depth_ * level.rows_ * level.rowSize_;
  354. }
  355. else
  356. {
  357. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * level.depth_ * 4];
  358. level.Decompress(rgbaData);
  359. SetData(i, 0, 0, 0, level.width_, level.height_, level.depth_, rgbaData);
  360. memoryUse += level.width_ * level.height_ * level.depth_ * 4;
  361. delete[] rgbaData;
  362. }
  363. }
  364. }
  365. SetMemoryUse(memoryUse);
  366. return true;
  367. }
  368. bool Texture3D::GetData(unsigned level, void* dest) const
  369. {
  370. if (!object_)
  371. {
  372. LOGERROR("No texture created, can not get data");
  373. return false;
  374. }
  375. if (!dest)
  376. {
  377. LOGERROR("Null destination for getting data");
  378. return false;
  379. }
  380. if (level >= levels_)
  381. {
  382. LOGERROR("Illegal mip level for getting data");
  383. return false;
  384. }
  385. int levelWidth = GetLevelWidth(level);
  386. int levelHeight = GetLevelHeight(level);
  387. int levelDepth = GetLevelDepth(level);
  388. D3D11_TEXTURE3D_DESC textureDesc;
  389. memset(&textureDesc, 0, sizeof textureDesc);
  390. textureDesc.Width = levelWidth;
  391. textureDesc.Height = levelHeight;
  392. textureDesc.Depth = levelDepth;
  393. textureDesc.MipLevels = 1;
  394. textureDesc.Format = (DXGI_FORMAT)format_;
  395. textureDesc.Usage = D3D11_USAGE_STAGING;
  396. textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  397. ID3D11Texture3D* stagingTexture = 0;
  398. graphics_->GetImpl()->GetDevice()->CreateTexture3D(&textureDesc, 0, &stagingTexture);
  399. if (!stagingTexture)
  400. {
  401. LOGERROR("Failed to create staging texture for GetData");
  402. return false;
  403. }
  404. unsigned srcSubResource = D3D11CalcSubresource(level, 0, levels_);
  405. D3D11_BOX srcBox;
  406. srcBox.left = 0;
  407. srcBox.right = levelWidth;
  408. srcBox.top = 0;
  409. srcBox.bottom = levelHeight;
  410. srcBox.front = 0;
  411. srcBox.back = levelDepth;
  412. graphics_->GetImpl()->GetDeviceContext()->CopySubresourceRegion(stagingTexture, 0, 0, 0, 0, (ID3D11Resource*)object_,
  413. srcSubResource, &srcBox);
  414. D3D11_MAPPED_SUBRESOURCE mappedData;
  415. mappedData.pData = 0;
  416. unsigned rowSize = GetRowDataSize(levelWidth);
  417. unsigned numRows = IsCompressed() ? (levelHeight + 3) >> 2 : levelHeight;
  418. graphics_->GetImpl()->GetDeviceContext()->Map((ID3D11Resource*)stagingTexture, 0, D3D11_MAP_READ, 0, &mappedData);
  419. if (mappedData.pData)
  420. {
  421. for (int page = 0; page < levelDepth; ++page)
  422. {
  423. for (unsigned row = 0; row < numRows; ++row)
  424. {
  425. memcpy((unsigned char*)dest + (page * numRows + row) * rowSize, (unsigned char*)mappedData.pData + page *
  426. mappedData.DepthPitch + row * mappedData.RowPitch, rowSize);
  427. }
  428. }
  429. graphics_->GetImpl()->GetDeviceContext()->Unmap((ID3D11Resource*)stagingTexture, 0);
  430. stagingTexture->Release();
  431. return true;
  432. }
  433. else
  434. {
  435. LOGERROR("Failed to map staging texture for GetData");
  436. stagingTexture->Release();
  437. return false;
  438. }
  439. }
  440. bool Texture3D::Create()
  441. {
  442. Release();
  443. if (!graphics_ || !width_ || !height_ || !depth_)
  444. return false;
  445. levels_ = CheckMaxLevels(width_, height_, depth_, requestedLevels_);
  446. D3D11_TEXTURE3D_DESC textureDesc;
  447. memset(&textureDesc, 0, sizeof textureDesc);
  448. textureDesc.Width = width_;
  449. textureDesc.Height = height_;
  450. textureDesc.Depth = depth_;
  451. textureDesc.MipLevels = levels_;
  452. textureDesc.Format = (DXGI_FORMAT)(sRGB_ ? GetSRGBFormat(format_) : format_);
  453. textureDesc.Usage = usage_ == TEXTURE_DYNAMIC ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
  454. textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  455. textureDesc.CPUAccessFlags = usage_ == TEXTURE_DYNAMIC ? D3D11_CPU_ACCESS_WRITE : 0;
  456. graphics_->GetImpl()->GetDevice()->CreateTexture3D(&textureDesc, 0, (ID3D11Texture3D**)&object_);
  457. if (!object_)
  458. {
  459. LOGERROR("Failed to create texture");
  460. return false;
  461. }
  462. D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
  463. memset(&resourceViewDesc, 0, sizeof resourceViewDesc);
  464. resourceViewDesc.Format = (DXGI_FORMAT)GetSRVFormat(textureDesc.Format);
  465. resourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D;
  466. resourceViewDesc.Texture3D.MipLevels = (unsigned)levels_;
  467. graphics_->GetImpl()->GetDevice()->CreateShaderResourceView((ID3D11Resource*)object_, &resourceViewDesc,
  468. (ID3D11ShaderResourceView**)&shaderResourceView_);
  469. if (!shaderResourceView_)
  470. {
  471. LOGERROR("Failed to create shader resource view for texture");
  472. return false;
  473. }
  474. return true;
  475. }
  476. void Texture3D::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  477. {
  478. if (renderSurface_ && renderSurface_->GetUpdateMode() == SURFACE_UPDATEALWAYS)
  479. renderSurface_->QueueUpdate();
  480. }
  481. }