D3D9Texture3D.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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 Urho3D
  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. // If device is lost, retry later
  56. if (graphics_->IsDeviceLost())
  57. {
  58. LOGWARNING("Texture load while device is lost");
  59. dataPending_ = true;
  60. return true;
  61. }
  62. String texPath, texName, texExt;
  63. SplitPath(GetName(), texPath, texName, texExt);
  64. cache->ResetDependencies(this);
  65. loadParameters_ = new XMLFile(context_);
  66. if (!loadParameters_->Load(source))
  67. {
  68. loadParameters_.Reset();
  69. return false;
  70. }
  71. XMLElement textureElem = loadParameters_->GetRoot();
  72. XMLElement volumeElem = textureElem.GetChild("volume");
  73. XMLElement colorlutElem = textureElem.GetChild("colorlut");
  74. if (volumeElem)
  75. {
  76. String name = volumeElem.GetAttribute("name");
  77. String volumeTexPath, volumeTexName, volumeTexExt;
  78. SplitPath(name, volumeTexPath, volumeTexName, volumeTexExt);
  79. // If path is empty, add the XML file path
  80. if (volumeTexPath.Empty())
  81. name = texPath + name;
  82. loadImage_ = cache->GetTempResource<Image>(name);
  83. // Precalculate mip levels if async loading
  84. if (loadImage_ && GetAsyncLoadState() == ASYNC_LOADING)
  85. loadImage_->PrecalculateLevels();
  86. cache->StoreResourceDependency(this, name);
  87. return true;
  88. }
  89. else if (colorlutElem)
  90. {
  91. String name = colorlutElem.GetAttribute("name");
  92. String colorlutTexPath, colorlutTexName, colorlutTexExt;
  93. SplitPath(name, colorlutTexPath, colorlutTexName, colorlutTexExt);
  94. // If path is empty, add the XML file path
  95. if (colorlutTexPath.Empty())
  96. name = texPath + name;
  97. SharedPtr<File> file = GetSubsystem<ResourceCache>()->GetFile(name);
  98. loadImage_ = new Image(context_);
  99. if (!loadImage_->LoadColorLUT(*(file.Get())))
  100. {
  101. loadParameters_.Reset();
  102. loadImage_.Reset();
  103. return false;
  104. }
  105. // Precalculate mip levels if async loading
  106. if (loadImage_ && GetAsyncLoadState() == ASYNC_LOADING)
  107. loadImage_->PrecalculateLevels();
  108. cache->StoreResourceDependency(this, name);
  109. return true;
  110. }
  111. LOGERROR("Texture3D XML data for " + GetName() + " did not contain either volume or colorlut element");
  112. return false;
  113. }
  114. bool Texture3D::EndLoad()
  115. {
  116. // In headless mode, do not actually load the texture, just return success
  117. if (!graphics_ || graphics_->IsDeviceLost())
  118. return true;
  119. // If over the texture budget, see if materials can be freed to allow textures to be freed
  120. CheckTextureBudget(GetTypeStatic());
  121. SetParameters(loadParameters_);
  122. bool success = SetData(loadImage_);
  123. loadImage_.Reset();
  124. loadParameters_.Reset();
  125. return success;
  126. }
  127. void Texture3D::OnDeviceLost()
  128. {
  129. if (pool_ == D3DPOOL_DEFAULT)
  130. Release();
  131. }
  132. void Texture3D::OnDeviceReset()
  133. {
  134. if (pool_ == D3DPOOL_DEFAULT || !object_ || dataPending_)
  135. {
  136. // If has a resource file, reload through the resource cache. Otherwise just recreate.
  137. ResourceCache* cache = GetSubsystem<ResourceCache>();
  138. if (cache->Exists(GetName()))
  139. dataLost_ = !cache->ReloadResource(this);
  140. if (!object_)
  141. {
  142. Create();
  143. dataLost_ = true;
  144. }
  145. }
  146. dataPending_ = false;
  147. }
  148. void Texture3D::Release()
  149. {
  150. if (object_)
  151. {
  152. if (!graphics_)
  153. return;
  154. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  155. {
  156. if (graphics_->GetTexture(i) == this)
  157. graphics_->SetTexture(i, 0);
  158. }
  159. if (renderSurface_)
  160. renderSurface_->Release();
  161. ((IDirect3DVolumeTexture9*)object_)->Release();
  162. object_ = 0;
  163. }
  164. else
  165. {
  166. if (renderSurface_)
  167. renderSurface_->Release();
  168. }
  169. }
  170. bool Texture3D::SetSize(int width, int height, int depth, unsigned format, TextureUsage usage)
  171. {
  172. // Delete the old rendersurface if any
  173. renderSurface_.Reset();
  174. pool_ = D3DPOOL_MANAGED;
  175. usage_ = 0;
  176. if (usage == TEXTURE_RENDERTARGET)
  177. {
  178. renderSurface_ = new RenderSurface(this);
  179. usage_ |= D3DUSAGE_RENDERTARGET;
  180. pool_ = D3DPOOL_DEFAULT;
  181. // Clamp mode addressing by default, nearest filtering, and mipmaps disabled
  182. addressMode_[COORD_U] = ADDRESS_CLAMP;
  183. addressMode_[COORD_V] = ADDRESS_CLAMP;
  184. filterMode_ = FILTER_NEAREST;
  185. requestedLevels_ = 1;
  186. }
  187. else if (usage == TEXTURE_DYNAMIC)
  188. {
  189. usage_ |= D3DUSAGE_DYNAMIC;
  190. pool_ = D3DPOOL_DEFAULT;
  191. }
  192. if (usage == TEXTURE_RENDERTARGET)
  193. SubscribeToEvent(E_RENDERSURFACEUPDATE, URHO3D_HANDLER(Texture3D, HandleRenderSurfaceUpdate));
  194. else
  195. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  196. width_ = width;
  197. height_ = height;
  198. depth_ = depth;
  199. format_ = format;
  200. return Create();
  201. }
  202. bool Texture3D::SetData(unsigned level, int x, int y, int z, int width, int height, int depth, const void* data)
  203. {
  204. PROFILE(SetTextureData);
  205. if (!object_)
  206. {
  207. LOGERROR("No texture created, can not set data");
  208. return false;
  209. }
  210. if (!data)
  211. {
  212. LOGERROR("Null source for setting data");
  213. return false;
  214. }
  215. if (level >= levels_)
  216. {
  217. LOGERROR("Illegal mip level for setting data");
  218. return false;
  219. }
  220. if (graphics_->IsDeviceLost())
  221. {
  222. LOGWARNING("Texture data assignment while device is lost");
  223. dataPending_ = true;
  224. return true;
  225. }
  226. if (IsCompressed())
  227. {
  228. x &= ~3;
  229. y &= ~3;
  230. }
  231. int levelWidth = GetLevelWidth(level);
  232. int levelHeight = GetLevelHeight(level);
  233. int levelDepth = GetLevelDepth(level);
  234. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || z < 0 || z + depth > levelDepth || width <= 0 ||
  235. height <= 0 || depth <= 0)
  236. {
  237. LOGERROR("Illegal dimensions for setting data");
  238. return false;
  239. }
  240. D3DLOCKED_BOX d3dLockedBox;
  241. D3DBOX d3dBox;
  242. d3dBox.Left = (UINT)x;
  243. d3dBox.Top = (UINT)y;
  244. d3dBox.Front = (UINT)z;
  245. d3dBox.Right = (UINT)(x + width);
  246. d3dBox.Bottom = (UINT)(y + height);
  247. d3dBox.Back = (UINT)(z + depth);
  248. DWORD flags = 0;
  249. if (level == 0 && x == 0 && y == 0 && z == 0 && width == levelWidth && height == levelHeight && depth == levelDepth &&
  250. pool_ == D3DPOOL_DEFAULT)
  251. flags |= D3DLOCK_DISCARD;
  252. if (FAILED(((IDirect3DVolumeTexture9*)object_)->LockBox(level, &d3dLockedBox, (flags & D3DLOCK_DISCARD) ? 0 : &d3dBox, flags)))
  253. {
  254. LOGERROR("Could not lock texture");
  255. return false;
  256. }
  257. if (IsCompressed())
  258. {
  259. height = (height + 3) >> 2;
  260. y >>= 2;
  261. }
  262. unsigned char* src = (unsigned char*)data;
  263. unsigned rowSize = GetRowDataSize(width);
  264. // GetRowDataSize() returns CPU-side (source) data size, so need to convert for X8R8G8B8
  265. if (format_ == D3DFMT_X8R8G8B8)
  266. rowSize = rowSize / 3 * 4;
  267. // Perform conversion from RGB / RGBA as necessary
  268. switch (format_)
  269. {
  270. default:
  271. for (int k = 0; k < levelDepth; ++k)
  272. {
  273. for (int i = 0; i < height; ++i)
  274. {
  275. unsigned char
  276. * dest = (unsigned char*)d3dLockedBox.pBits + (k * d3dLockedBox.SlicePitch) + i * d3dLockedBox.RowPitch;
  277. memcpy(dest, src, rowSize);
  278. src += rowSize;
  279. }
  280. }
  281. break;
  282. case D3DFMT_X8R8G8B8:
  283. for (int k = 0; k < levelDepth; ++k)
  284. {
  285. for (int i = 0; i < height; ++i)
  286. {
  287. unsigned char
  288. * dest = (unsigned char*)d3dLockedBox.pBits + (k * d3dLockedBox.SlicePitch) + i * d3dLockedBox.RowPitch;
  289. for (int j = 0; j < width; ++j)
  290. {
  291. *dest++ = src[2];
  292. *dest++ = src[1];
  293. *dest++ = src[0];
  294. *dest++ = 255;
  295. src += 3;
  296. }
  297. }
  298. }
  299. break;
  300. case D3DFMT_A8R8G8B8:
  301. for (int k = 0; k < levelDepth; ++k)
  302. {
  303. for (int i = 0; i < height; ++i)
  304. {
  305. unsigned char
  306. * dest = (unsigned char*)d3dLockedBox.pBits + (k * d3dLockedBox.SlicePitch) + i * d3dLockedBox.RowPitch;
  307. for (int j = 0; j < width; ++j)
  308. {
  309. *dest++ = src[2];
  310. *dest++ = src[1];
  311. *dest++ = src[0];
  312. *dest++ = src[3];
  313. src += 4;
  314. }
  315. }
  316. }
  317. break;
  318. }
  319. ((IDirect3DVolumeTexture9*)object_)->UnlockBox(level);
  320. return true;
  321. }
  322. bool Texture3D::SetData(SharedPtr<Image> image, bool useAlpha)
  323. {
  324. if (!image)
  325. {
  326. LOGERROR("Null image, can not load texture");
  327. return false;
  328. }
  329. unsigned memoryUse = sizeof(Texture3D);
  330. int quality = QUALITY_HIGH;
  331. Renderer* renderer = GetSubsystem<Renderer>();
  332. if (renderer)
  333. quality = renderer->GetTextureQuality();
  334. if (!image->IsCompressed())
  335. {
  336. unsigned char* levelData = image->GetData();
  337. int levelWidth = image->GetWidth();
  338. int levelHeight = image->GetHeight();
  339. int levelDepth = image->GetDepth();
  340. unsigned components = image->GetComponents();
  341. unsigned format = 0;
  342. // Discard unnecessary mip levels
  343. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  344. {
  345. image = image->GetNextLevel();
  346. levelData = image->GetData();
  347. levelWidth = image->GetWidth();
  348. levelHeight = image->GetHeight();
  349. levelDepth = image->GetDepth();
  350. }
  351. switch (components)
  352. {
  353. case 1:
  354. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  355. break;
  356. case 2:
  357. format = Graphics::GetLuminanceAlphaFormat();
  358. break;
  359. case 3:
  360. format = Graphics::GetRGBFormat();
  361. break;
  362. case 4:
  363. format = Graphics::GetRGBAFormat();
  364. break;
  365. default:
  366. assert(false); // Should never reach here
  367. break;
  368. }
  369. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  370. if (IsCompressed() && requestedLevels_ > 1)
  371. requestedLevels_ = 0;
  372. SetSize(levelWidth, levelHeight, levelDepth, format);
  373. for (unsigned i = 0; i < levels_; ++i)
  374. {
  375. SetData(i, 0, 0, 0, levelWidth, levelHeight, levelDepth, levelData);
  376. memoryUse += levelWidth * levelHeight * levelDepth * components;
  377. if (i < levels_ - 1)
  378. {
  379. image = image->GetNextLevel();
  380. levelData = image->GetData();
  381. levelWidth = image->GetWidth();
  382. levelHeight = image->GetHeight();
  383. levelDepth = image->GetDepth();
  384. }
  385. }
  386. }
  387. else
  388. {
  389. int width = image->GetWidth();
  390. int height = image->GetHeight();
  391. int depth = image->GetDepth();
  392. unsigned levels = image->GetNumCompressedLevels();
  393. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  394. bool needDecompress = false;
  395. if (!format)
  396. {
  397. format = Graphics::GetRGBAFormat();
  398. needDecompress = true;
  399. }
  400. unsigned mipsToSkip = mipsToSkip_[quality];
  401. if (mipsToSkip >= levels)
  402. mipsToSkip = levels - 1;
  403. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4 || depth / (1 << mipsToSkip) < 4))
  404. --mipsToSkip;
  405. width /= (1 << mipsToSkip);
  406. height /= (1 << mipsToSkip);
  407. depth /= (1 << mipsToSkip);
  408. SetNumLevels((unsigned)Max((int)(levels - mipsToSkip), 1));
  409. SetSize(width, height, depth, format);
  410. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  411. {
  412. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  413. if (!needDecompress)
  414. {
  415. SetData(i, 0, 0, 0, level.width_, level.height_, level.depth_, level.data_);
  416. memoryUse += level.depth_ * level.rows_ * level.rowSize_;
  417. }
  418. else
  419. {
  420. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * level.depth_ * 4];
  421. level.Decompress(rgbaData);
  422. SetData(i, 0, 0, 0, level.width_, level.height_, level.depth_, rgbaData);
  423. memoryUse += level.width_ * level.height_ * level.depth_ * 4;
  424. delete[] rgbaData;
  425. }
  426. }
  427. }
  428. SetMemoryUse(memoryUse);
  429. return true;
  430. }
  431. bool Texture3D::GetData(unsigned level, void* dest) const
  432. {
  433. if (!object_)
  434. {
  435. LOGERROR("No texture created, can not get data");
  436. return false;
  437. }
  438. if (!dest)
  439. {
  440. LOGERROR("Null destination for getting data");
  441. return false;
  442. }
  443. if (level >= levels_)
  444. {
  445. LOGERROR("Illegal mip level for getting data");
  446. return false;
  447. }
  448. if (graphics_->IsDeviceLost())
  449. {
  450. LOGWARNING("Getting texture data while device is lost");
  451. return false;
  452. }
  453. int levelWidth = GetLevelWidth(level);
  454. int levelHeight = GetLevelHeight(level);
  455. int levelDepth = GetLevelDepth(level);
  456. D3DLOCKED_BOX d3dLockedBox;
  457. D3DBOX d3dBox;
  458. d3dBox.Left = 0;
  459. d3dBox.Top = 0;
  460. d3dBox.Front = 0;
  461. d3dBox.Right = (UINT)levelWidth;
  462. d3dBox.Bottom = (UINT)levelHeight;
  463. d3dBox.Back = (UINT)levelDepth;
  464. if (FAILED(((IDirect3DVolumeTexture9*)object_)->LockBox(level, &d3dLockedBox, &d3dBox, D3DLOCK_READONLY)))
  465. {
  466. LOGERROR("Could not lock texture");
  467. return false;
  468. }
  469. int height = levelHeight;
  470. if (IsCompressed())
  471. height = (height + 3) >> 2;
  472. unsigned char* destPtr = (unsigned char*)dest;
  473. unsigned rowSize = GetRowDataSize(levelWidth);
  474. // GetRowDataSize() returns CPU-side (destination) data size, so need to convert for X8R8G8B8
  475. if (format_ == D3DFMT_X8R8G8B8)
  476. rowSize = rowSize / 3 * 4;
  477. // Perform conversion to RGB / RGBA as necessary
  478. switch (format_)
  479. {
  480. default:
  481. for (int k = 0; k < levelDepth; ++k)
  482. {
  483. for (int i = 0; i < height; ++i)
  484. {
  485. unsigned char* src = (unsigned char*)d3dLockedBox.pBits + (k * d3dLockedBox.SlicePitch) + i * d3dLockedBox.RowPitch;
  486. memcpy(destPtr, src, rowSize);
  487. destPtr += rowSize;
  488. }
  489. }
  490. break;
  491. case D3DFMT_X8R8G8B8:
  492. for (int k = 0; k < levelDepth; ++k)
  493. {
  494. for (int i = 0; i < height; ++i)
  495. {
  496. unsigned char* src = (unsigned char*)d3dLockedBox.pBits + (k * d3dLockedBox.SlicePitch) + i * d3dLockedBox.RowPitch;
  497. for (int j = 0; j < levelWidth; ++j)
  498. {
  499. destPtr[2] = *src++;
  500. destPtr[1] = *src++;
  501. destPtr[0] = *src++;
  502. ++src;
  503. destPtr += 3;
  504. }
  505. }
  506. }
  507. break;
  508. case D3DFMT_A8R8G8B8:
  509. for (int k = 0; k < levelDepth; ++k)
  510. {
  511. for (int i = 0; i < height; ++i)
  512. {
  513. unsigned char* src = (unsigned char*)d3dLockedBox.pBits + (k * d3dLockedBox.SlicePitch) + i * d3dLockedBox.RowPitch;
  514. for (int j = 0; j < levelWidth; ++j)
  515. {
  516. destPtr[2] = *src++;
  517. destPtr[1] = *src++;
  518. destPtr[0] = *src++;
  519. destPtr[3] = *src++;
  520. destPtr += 4;
  521. }
  522. }
  523. }
  524. break;
  525. }
  526. ((IDirect3DVolumeTexture9*)object_)->UnlockBox(level);
  527. return true;
  528. }
  529. bool Texture3D::Create()
  530. {
  531. Release();
  532. if (!graphics_ || !width_ || !height_)
  533. return false;
  534. if (graphics_->IsDeviceLost())
  535. {
  536. LOGWARNING("Texture creation while device is lost");
  537. return true;
  538. }
  539. IDirect3DDevice9* device = graphics_->GetImpl()->GetDevice();
  540. if (!device || FAILED(graphics_->GetImpl()->GetDevice()->CreateVolumeTexture(
  541. (UINT)width_,
  542. (UINT)height_,
  543. (UINT)depth_,
  544. requestedLevels_,
  545. usage_,
  546. (D3DFORMAT)format_,
  547. (D3DPOOL)pool_,
  548. (IDirect3DVolumeTexture9**)&object_,
  549. 0)))
  550. {
  551. LOGERROR("Could not create texture");
  552. return false;
  553. }
  554. levels_ = ((IDirect3DVolumeTexture9*)object_)->GetLevelCount();
  555. return true;
  556. }
  557. void Texture3D::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  558. {
  559. if (renderSurface_ && renderSurface_->GetUpdateMode() == SURFACE_UPDATEALWAYS)
  560. renderSurface_->QueueUpdate();
  561. }
  562. }