D3D11Texture3D.cpp 17 KB

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