D3D9TextureCube.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. //
  2. // Copyright (c) 2008-2014 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 "Context.h"
  24. #include "FileSystem.h"
  25. #include "Graphics.h"
  26. #include "GraphicsEvents.h"
  27. #include "GraphicsImpl.h"
  28. #include "Log.h"
  29. #include "Profiler.h"
  30. #include "Renderer.h"
  31. #include "ResourceCache.h"
  32. #include "TextureCube.h"
  33. #include "XMLFile.h"
  34. #include "DebugNew.h"
  35. #ifdef _MSC_VER
  36. #pragma warning(disable:4355)
  37. #endif
  38. namespace Urho3D
  39. {
  40. TextureCube::TextureCube(Context* context) :
  41. Texture(context),
  42. lockedLevel_(-1)
  43. {
  44. // Default to clamp mode addressing
  45. addressMode_[COORD_U] = ADDRESS_CLAMP;
  46. addressMode_[COORD_V] = ADDRESS_CLAMP;
  47. addressMode_[COORD_W] = ADDRESS_CLAMP;
  48. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  49. faceMemoryUse_[i] = 0;
  50. }
  51. TextureCube::~TextureCube()
  52. {
  53. Release();
  54. }
  55. void TextureCube::RegisterObject(Context* context)
  56. {
  57. context->RegisterFactory<TextureCube>();
  58. }
  59. bool TextureCube::BeginLoad(Deserializer& source)
  60. {
  61. ResourceCache* cache = GetSubsystem<ResourceCache>();
  62. // In headless mode, do not actually load the texture, just return success
  63. if (!graphics_)
  64. return true;
  65. // If device is lost, retry later
  66. if (graphics_->IsDeviceLost())
  67. {
  68. LOGWARNING("Texture load while device is lost");
  69. dataPending_ = true;
  70. return true;
  71. }
  72. cache->ResetDependencies(this);
  73. String texPath, texName, texExt;
  74. SplitPath(GetName(), texPath, texName, texExt);
  75. loadParameters_ = (new XMLFile(context_));
  76. if (!loadParameters_->Load(source))
  77. {
  78. loadParameters_.Reset();
  79. return false;
  80. }
  81. loadImages_.Clear();
  82. XMLElement textureElem = loadParameters_->GetRoot();
  83. XMLElement faceElem = textureElem.GetChild("face");
  84. while (faceElem)
  85. {
  86. String name = faceElem.GetAttribute("name");
  87. String faceTexPath, faceTexName, faceTexExt;
  88. SplitPath(name, faceTexPath, faceTexName, faceTexExt);
  89. // If path is empty, add the XML file path
  90. if (faceTexPath.Empty())
  91. name = texPath + name;
  92. loadImages_.Push(cache->GetTempResource<Image>(name));
  93. cache->StoreResourceDependency(this, name);
  94. faceElem = faceElem.GetNext("face");
  95. }
  96. // Precalculate mip levels if async loading
  97. if (GetAsyncLoadState() == ASYNC_LOADING)
  98. {
  99. for (unsigned i = 0; i < loadImages_.Size(); ++i)
  100. {
  101. if (loadImages_[i])
  102. loadImages_[i]->PrecalculateLevels();
  103. }
  104. }
  105. return true;
  106. }
  107. bool TextureCube::EndLoad()
  108. {
  109. // In headless mode, do not actually load the texture, just return success
  110. if (!graphics_ || graphics_->IsDeviceLost())
  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. for (unsigned i = 0; i < loadImages_.Size() && i < MAX_CUBEMAP_FACES; ++i)
  116. SetData((CubeMapFace)i, loadImages_[i]);
  117. loadImages_.Clear();
  118. loadParameters_.Reset();
  119. return true;
  120. }
  121. void TextureCube::OnDeviceLost()
  122. {
  123. if (pool_ == D3DPOOL_DEFAULT)
  124. Release();
  125. }
  126. void TextureCube::OnDeviceReset()
  127. {
  128. if (pool_ == D3DPOOL_DEFAULT || !object_ || dataPending_)
  129. {
  130. // If has a resource file, reload through the resource cache. Otherwise just recreate.
  131. ResourceCache* cache = GetSubsystem<ResourceCache>();
  132. if (cache->Exists(GetName()))
  133. dataLost_ = !cache->ReloadResource(this);
  134. if (!object_)
  135. {
  136. Create();
  137. dataLost_ = true;
  138. }
  139. }
  140. dataPending_ = false;
  141. }
  142. void TextureCube::Release()
  143. {
  144. if (object_)
  145. {
  146. if (!graphics_)
  147. return;
  148. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  149. {
  150. if (graphics_->GetTexture(i) == this)
  151. graphics_->SetTexture(i, 0);
  152. }
  153. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  154. {
  155. if (renderSurfaces_[i])
  156. renderSurfaces_[i]->Release();
  157. }
  158. ((IDirect3DCubeTexture9*)object_)->Release();
  159. object_ = 0;
  160. }
  161. }
  162. bool TextureCube::SetSize(int size, unsigned format, TextureUsage usage)
  163. {
  164. if (size <= 0)
  165. {
  166. LOGERROR("Zero or negative cube texture size");
  167. return false;
  168. }
  169. if (usage == TEXTURE_DEPTHSTENCIL)
  170. {
  171. LOGERROR("Depth-stencil usage not supported for cube maps");
  172. return false;
  173. }
  174. // Delete the old rendersurfaces if any
  175. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  176. {
  177. renderSurfaces_[i].Reset();
  178. faceMemoryUse_[i] = 0;
  179. }
  180. pool_ = D3DPOOL_MANAGED;
  181. usage_ = 0;
  182. if (usage == TEXTURE_RENDERTARGET)
  183. {
  184. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  185. renderSurfaces_[i] = new RenderSurface(this);
  186. usage_ |= D3DUSAGE_RENDERTARGET;
  187. pool_ = D3DPOOL_DEFAULT;
  188. // Nearest filtering and mipmaps disabled by default
  189. filterMode_ = FILTER_NEAREST;
  190. requestedLevels_ = 1;
  191. }
  192. else if (usage == TEXTURE_DYNAMIC)
  193. {
  194. usage_ |= D3DUSAGE_DYNAMIC;
  195. pool_ = D3DPOOL_DEFAULT;
  196. }
  197. if (usage == TEXTURE_RENDERTARGET)
  198. SubscribeToEvent(E_RENDERSURFACEUPDATE, HANDLER(TextureCube, HandleRenderSurfaceUpdate));
  199. else
  200. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  201. width_ = size;
  202. height_ = size;
  203. format_ = format;
  204. return Create();
  205. }
  206. bool TextureCube::SetData(CubeMapFace face, unsigned level, int x, int y, int width, int height, const void* data)
  207. {
  208. PROFILE(SetTextureData);
  209. if (!object_)
  210. {
  211. LOGERROR("No texture created, can not set data");
  212. return false;
  213. }
  214. if (!data)
  215. {
  216. LOGERROR("Null source for setting data");
  217. return false;
  218. }
  219. if (level >= levels_)
  220. {
  221. LOGERROR("Illegal mip level for setting data");
  222. return false;
  223. }
  224. if (graphics_->IsDeviceLost())
  225. {
  226. LOGWARNING("Texture data assignment while device is lost");
  227. dataPending_ = true;
  228. return true;
  229. }
  230. if (IsCompressed())
  231. {
  232. x &= ~3;
  233. y &= ~3;
  234. }
  235. int levelWidth = GetLevelWidth(level);
  236. int levelHeight = GetLevelHeight(level);
  237. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  238. {
  239. LOGERROR("Illegal dimensions for setting data");
  240. return false;
  241. }
  242. D3DLOCKED_RECT d3dLockedRect;
  243. RECT d3dRect;
  244. d3dRect.left = x;
  245. d3dRect.top = y;
  246. d3dRect.right = x + width;
  247. d3dRect.bottom = y + height;
  248. DWORD flags = 0;
  249. if (level == 0 && x == 0 && y == 0 && width == levelWidth && height == levelHeight && pool_ == D3DPOOL_DEFAULT)
  250. flags |= D3DLOCK_DISCARD;
  251. if (FAILED(((IDirect3DCubeTexture9*)object_)->LockRect((D3DCUBEMAP_FACES)face, level, &d3dLockedRect, (flags &
  252. D3DLOCK_DISCARD) ? 0 : &d3dRect, 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 i = 0; i < height; ++i)
  272. {
  273. unsigned char* dest = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  274. memcpy(dest, src, rowSize);
  275. src += rowSize;
  276. }
  277. break;
  278. case D3DFMT_X8R8G8B8:
  279. for (int i = 0; i < height; ++i)
  280. {
  281. unsigned char* dest = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  282. for (int j = 0; j < width; ++j)
  283. {
  284. *dest++ = src[2]; *dest++ = src[1]; *dest++ = src[0]; *dest++ = 255;
  285. src += 3;
  286. }
  287. }
  288. break;
  289. case D3DFMT_A8R8G8B8:
  290. for (int i = 0; i < height; ++i)
  291. {
  292. unsigned char* dest = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  293. for (int j = 0; j < width; ++j)
  294. {
  295. *dest++ = src[2]; *dest++ = src[1]; *dest++ = src[0]; *dest++ = src[3];
  296. src += 4;
  297. }
  298. }
  299. break;
  300. }
  301. ((IDirect3DCubeTexture9*)object_)->UnlockRect((D3DCUBEMAP_FACES)face, level);
  302. return true;
  303. }
  304. bool TextureCube::SetData(CubeMapFace face, Deserializer& source)
  305. {
  306. SharedPtr<Image> image(new Image(context_));
  307. if (!image->Load(source))
  308. return false;
  309. return SetData(face, image);
  310. }
  311. bool TextureCube::SetData(CubeMapFace face, SharedPtr<Image> image, bool useAlpha)
  312. {
  313. if (!image)
  314. {
  315. LOGERROR("Null image, can not load texture");
  316. return false;
  317. }
  318. unsigned memoryUse = 0;
  319. int quality = QUALITY_HIGH;
  320. Renderer* renderer = GetSubsystem<Renderer>();
  321. if (renderer)
  322. quality = renderer->GetTextureQuality();
  323. if (!image->IsCompressed())
  324. {
  325. unsigned char* levelData = image->GetData();
  326. int levelWidth = image->GetWidth();
  327. int levelHeight = image->GetHeight();
  328. unsigned components = image->GetComponents();
  329. unsigned format = 0;
  330. if (levelWidth != levelHeight)
  331. {
  332. LOGERROR("Cube texture width not equal to height");
  333. return false;
  334. }
  335. // Discard unnecessary mip levels
  336. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  337. {
  338. image = image->GetNextLevel();
  339. levelData = image->GetData();
  340. levelWidth = image->GetWidth();
  341. levelHeight = image->GetHeight();
  342. }
  343. switch (components)
  344. {
  345. case 1:
  346. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  347. break;
  348. case 2:
  349. format = Graphics::GetLuminanceAlphaFormat();
  350. break;
  351. case 3:
  352. format = Graphics::GetRGBFormat();
  353. break;
  354. case 4:
  355. format = Graphics::GetRGBAFormat();
  356. break;
  357. }
  358. // Create the texture when face 0 is being loaded, check that rest of the faces are same size & format
  359. if (!face)
  360. {
  361. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  362. if (IsCompressed() && requestedLevels_ > 1)
  363. requestedLevels_ = 0;
  364. SetSize(levelWidth, format);
  365. }
  366. else
  367. {
  368. if (!object_)
  369. {
  370. LOGERROR("Cube texture face 0 must be loaded first");
  371. return false;
  372. }
  373. if (levelWidth != width_ || format != format_)
  374. {
  375. LOGERROR("Cube texture face does not match size or format of face 0");
  376. return false;
  377. }
  378. }
  379. for (unsigned i = 0; i < levels_; ++i)
  380. {
  381. SetData(face, i, 0, 0, levelWidth, levelHeight, levelData);
  382. memoryUse += levelWidth * levelHeight * components;
  383. if (i < levels_ - 1)
  384. {
  385. image = image->GetNextLevel();
  386. levelData = image->GetData();
  387. levelWidth = image->GetWidth();
  388. levelHeight = image->GetHeight();
  389. }
  390. }
  391. }
  392. else
  393. {
  394. int width = image->GetWidth();
  395. int height = image->GetHeight();
  396. unsigned levels = image->GetNumCompressedLevels();
  397. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  398. bool needDecompress = false;
  399. if (width != height)
  400. {
  401. LOGERROR("Cube texture width not equal to height");
  402. return false;
  403. }
  404. if (!format)
  405. {
  406. format = Graphics::GetRGBAFormat();
  407. needDecompress = true;
  408. }
  409. unsigned mipsToSkip = mipsToSkip_[quality];
  410. if (mipsToSkip >= levels)
  411. mipsToSkip = levels - 1;
  412. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4))
  413. --mipsToSkip;
  414. width /= (1 << mipsToSkip);
  415. height /= (1 << mipsToSkip);
  416. // Create the texture when face 0 is being loaded, assume rest of the faces are same size & format
  417. if (!face)
  418. {
  419. SetNumLevels(Max((int)(levels - mipsToSkip), 1));
  420. SetSize(width, format);
  421. }
  422. else
  423. {
  424. if (!object_)
  425. {
  426. LOGERROR("Cube texture face 0 must be loaded first");
  427. return false;
  428. }
  429. if (width != width_ || format != format_)
  430. {
  431. LOGERROR("Cube texture face does not match size or format of face 0");
  432. return false;
  433. }
  434. }
  435. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  436. {
  437. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  438. if (!needDecompress)
  439. {
  440. SetData(face, i, 0, 0, level.width_, level.height_, level.data_);
  441. memoryUse += level.rows_ * level.rowSize_;
  442. }
  443. else
  444. {
  445. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  446. level.Decompress(rgbaData);
  447. SetData(face, i, 0, 0, level.width_, level.height_, rgbaData);
  448. memoryUse += level.width_ * level.height_ * 4;
  449. delete[] rgbaData;
  450. }
  451. }
  452. }
  453. faceMemoryUse_[face] = memoryUse;
  454. unsigned totalMemoryUse = sizeof(TextureCube);
  455. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  456. totalMemoryUse += faceMemoryUse_[i];
  457. SetMemoryUse(totalMemoryUse);
  458. return true;
  459. }
  460. bool TextureCube::GetData(CubeMapFace face, unsigned level, void* dest) const
  461. {
  462. if (!object_)
  463. {
  464. LOGERROR("No texture created, can not get data");
  465. return false;
  466. }
  467. if (!dest)
  468. {
  469. LOGERROR("Null destination for getting data");
  470. return false;
  471. }
  472. if (level >= levels_)
  473. {
  474. LOGERROR("Illegal mip level for getting data");
  475. return false;
  476. }
  477. if (graphics_->IsDeviceLost())
  478. {
  479. LOGWARNING("Getting texture data while device is lost");
  480. return false;
  481. }
  482. int levelWidth = GetLevelWidth(level);
  483. int levelHeight = GetLevelHeight(level);
  484. D3DLOCKED_RECT d3dLockedRect;
  485. RECT d3dRect;
  486. d3dRect.left = 0;
  487. d3dRect.top = 0;
  488. d3dRect.right = levelWidth;
  489. d3dRect.bottom = levelHeight;
  490. if (FAILED(((IDirect3DCubeTexture9*)object_)->LockRect((D3DCUBEMAP_FACES)face, level, &d3dLockedRect, &d3dRect, D3DLOCK_READONLY)))
  491. {
  492. LOGERROR("Could not lock texture");
  493. return false;
  494. }
  495. int height = levelHeight;
  496. if (IsCompressed())
  497. height = (height + 3) >> 2;
  498. unsigned char* destPtr = (unsigned char*)dest;
  499. unsigned rowSize = GetRowDataSize(levelWidth);
  500. // GetRowDataSize() returns CPU-side (destination) data size, so need to convert for X8R8G8B8
  501. if (format_ == D3DFMT_X8R8G8B8)
  502. rowSize = rowSize / 3 * 4;
  503. // Perform conversion to RGB / RGBA as necessary
  504. switch (format_)
  505. {
  506. default:
  507. for (int i = 0; i < height; ++i)
  508. {
  509. unsigned char* src = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  510. memcpy(destPtr, src, rowSize);
  511. destPtr += rowSize;
  512. }
  513. break;
  514. case D3DFMT_X8R8G8B8:
  515. for (int i = 0; i < height; ++i)
  516. {
  517. unsigned char* src = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  518. for (int j = 0; j < levelWidth; ++j)
  519. {
  520. destPtr[2] = *src++; destPtr[1] = *src++; destPtr[0] = *src++; ++src;
  521. destPtr += 3;
  522. }
  523. }
  524. break;
  525. case D3DFMT_A8R8G8B8:
  526. for (int i = 0; i < height; ++i)
  527. {
  528. unsigned char* src = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  529. for (int j = 0; j < levelWidth; ++j)
  530. {
  531. destPtr[2] = *src++; destPtr[1] = *src++; destPtr[0] = *src++; destPtr[3] = *src++;
  532. destPtr += 4;
  533. }
  534. }
  535. break;
  536. }
  537. ((IDirect3DCubeTexture9*)object_)->UnlockRect((D3DCUBEMAP_FACES)face, level);
  538. return true;
  539. }
  540. bool TextureCube::Create()
  541. {
  542. Release();
  543. if (!graphics_ || !width_ || !height_)
  544. return false;
  545. if (graphics_->IsDeviceLost())
  546. {
  547. LOGWARNING("Texture creation while device is lost");
  548. return true;
  549. }
  550. IDirect3DDevice9* device = graphics_->GetImpl()->GetDevice();
  551. if (!device || FAILED(device->CreateCubeTexture(
  552. width_,
  553. requestedLevels_,
  554. usage_,
  555. (D3DFORMAT)format_,
  556. (D3DPOOL)pool_,
  557. (IDirect3DCubeTexture9**)&object_,
  558. 0)))
  559. {
  560. LOGERROR("Could not create cube texture");
  561. return false;
  562. }
  563. levels_ = ((IDirect3DCubeTexture9*)object_)->GetLevelCount();
  564. if (usage_ & D3DUSAGE_RENDERTARGET)
  565. {
  566. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  567. {
  568. ((IDirect3DCubeTexture9*)object_)->GetCubeMapSurface((D3DCUBEMAP_FACES)i, 0,
  569. (IDirect3DSurface9**)&renderSurfaces_[i]->surface_);
  570. }
  571. }
  572. return true;
  573. }
  574. void TextureCube::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  575. {
  576. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  577. {
  578. if (renderSurfaces_[i] && renderSurfaces_[i]->GetUpdateMode() == SURFACE_UPDATEALWAYS)
  579. renderSurfaces_[i]->QueueUpdate();
  580. }
  581. }
  582. }