D3D9Texture2D.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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 "Renderer.h"
  30. #include "Profiler.h"
  31. #include "ResourceCache.h"
  32. #include "Texture2D.h"
  33. #include "XMLFile.h"
  34. #include "DebugNew.h"
  35. namespace Urho3D
  36. {
  37. Texture2D::Texture2D(Context* context) :
  38. Texture(context)
  39. {
  40. }
  41. Texture2D::~Texture2D()
  42. {
  43. Release();
  44. }
  45. void Texture2D::RegisterObject(Context* context)
  46. {
  47. context->RegisterFactory<Texture2D>();
  48. }
  49. bool Texture2D::BeginLoad(Deserializer& source)
  50. {
  51. // In headless mode, do not actually load the texture, just return success
  52. if (!graphics_)
  53. return true;
  54. // If device is lost, retry later
  55. if (graphics_->IsDeviceLost())
  56. {
  57. LOGWARNING("Texture load while device is lost");
  58. dataPending_ = true;
  59. return true;
  60. }
  61. // Load the image data for EndLoad()
  62. loadImage_ = new Image(context_);
  63. if (!loadImage_->Load(source))
  64. {
  65. loadImage_.Reset();
  66. return false;
  67. }
  68. // Precalculate mip levels if async loading
  69. if (GetAsyncLoadState() == ASYNC_LOADING)
  70. loadImage_->PrecalculateLevels();
  71. // Load the optional parameters file
  72. ResourceCache* cache = GetSubsystem<ResourceCache>();
  73. String xmlName = ReplaceExtension(GetName(), ".xml");
  74. loadParameters_ = cache->GetTempResource<XMLFile>(xmlName, false);
  75. return true;
  76. }
  77. bool Texture2D::EndLoad()
  78. {
  79. // In headless mode, do not actually load the texture, just return success
  80. if (!graphics_ || graphics_->IsDeviceLost())
  81. return true;
  82. // If over the texture budget, see if materials can be freed to allow textures to be freed
  83. CheckTextureBudget(GetTypeStatic());
  84. SetParameters(loadParameters_);
  85. bool success = SetData(loadImage_);
  86. loadImage_.Reset();
  87. loadParameters_.Reset();
  88. return success;
  89. }
  90. void Texture2D::OnDeviceLost()
  91. {
  92. if (pool_ == D3DPOOL_DEFAULT)
  93. Release();
  94. }
  95. void Texture2D::OnDeviceReset()
  96. {
  97. if (pool_ == D3DPOOL_DEFAULT || !object_ || dataPending_)
  98. {
  99. // If has a resource file, reload through the resource cache. Otherwise just recreate.
  100. ResourceCache* cache = GetSubsystem<ResourceCache>();
  101. if (cache->Exists(GetName()))
  102. dataLost_ = !cache->ReloadResource(this);
  103. if (!object_)
  104. {
  105. Create();
  106. dataLost_ = true;
  107. }
  108. }
  109. dataPending_ = false;
  110. }
  111. void Texture2D::Release()
  112. {
  113. if (object_)
  114. {
  115. if (!graphics_)
  116. return;
  117. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  118. {
  119. if (graphics_->GetTexture(i) == this)
  120. graphics_->SetTexture(i, 0);
  121. }
  122. if (renderSurface_)
  123. renderSurface_->Release();
  124. ((IDirect3DTexture9*)object_)->Release();
  125. object_ = 0;
  126. }
  127. else
  128. {
  129. if (renderSurface_)
  130. renderSurface_->Release();
  131. }
  132. }
  133. bool Texture2D::SetSize(int width, int height, unsigned format, TextureUsage usage)
  134. {
  135. // Delete the old rendersurface if any
  136. renderSurface_.Reset();
  137. pool_ = D3DPOOL_MANAGED;
  138. usage_ = 0;
  139. if (usage == TEXTURE_RENDERTARGET || usage == TEXTURE_DEPTHSTENCIL)
  140. {
  141. renderSurface_ = new RenderSurface(this);
  142. if (usage == TEXTURE_RENDERTARGET)
  143. usage_ |= D3DUSAGE_RENDERTARGET;
  144. else
  145. usage_ |= D3DUSAGE_DEPTHSTENCIL;
  146. pool_ = D3DPOOL_DEFAULT;
  147. // Clamp mode addressing by default, nearest filtering, and mipmaps disabled
  148. addressMode_[COORD_U] = ADDRESS_CLAMP;
  149. addressMode_[COORD_V] = ADDRESS_CLAMP;
  150. filterMode_ = FILTER_NEAREST;
  151. requestedLevels_ = 1;
  152. }
  153. else if (usage == TEXTURE_DYNAMIC)
  154. {
  155. usage_ |= D3DUSAGE_DYNAMIC;
  156. pool_ = D3DPOOL_DEFAULT;
  157. }
  158. if (usage == TEXTURE_RENDERTARGET)
  159. SubscribeToEvent(E_RENDERSURFACEUPDATE, HANDLER(Texture2D, HandleRenderSurfaceUpdate));
  160. else
  161. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  162. width_ = width;
  163. height_ = height;
  164. format_ = format;
  165. return Create();
  166. }
  167. bool Texture2D::SetData(unsigned level, int x, int y, int width, int height, const void* data)
  168. {
  169. PROFILE(SetTextureData);
  170. if (!object_)
  171. {
  172. LOGERROR("No texture created, can not set data");
  173. return false;
  174. }
  175. if (!data)
  176. {
  177. LOGERROR("Null source for setting data");
  178. return false;
  179. }
  180. if (level >= levels_)
  181. {
  182. LOGERROR("Illegal mip level for setting data");
  183. return false;
  184. }
  185. if (graphics_->IsDeviceLost())
  186. {
  187. LOGWARNING("Texture data assignment while device is lost");
  188. dataPending_ = true;
  189. return true;
  190. }
  191. if (IsCompressed())
  192. {
  193. x &= ~3;
  194. y &= ~3;
  195. }
  196. int levelWidth = GetLevelWidth(level);
  197. int levelHeight = GetLevelHeight(level);
  198. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  199. {
  200. LOGERROR("Illegal dimensions for setting data");
  201. return false;
  202. }
  203. D3DLOCKED_RECT d3dLockedRect;
  204. RECT d3dRect;
  205. d3dRect.left = x;
  206. d3dRect.top = y;
  207. d3dRect.right = x + width;
  208. d3dRect.bottom = y + height;
  209. DWORD flags = 0;
  210. if (level == 0 && x == 0 && y == 0 && width == levelWidth && height == levelHeight && pool_ == D3DPOOL_DEFAULT)
  211. flags |= D3DLOCK_DISCARD;
  212. if (FAILED(((IDirect3DTexture9*)object_)->LockRect(level, &d3dLockedRect, (flags & D3DLOCK_DISCARD) ? 0 : &d3dRect, flags)))
  213. {
  214. LOGERROR("Could not lock texture");
  215. return false;
  216. }
  217. if (IsCompressed())
  218. {
  219. height = (height + 3) >> 2;
  220. y >>= 2;
  221. }
  222. unsigned char* src = (unsigned char*)data;
  223. unsigned rowSize = GetRowDataSize(width);
  224. // GetRowDataSize() returns CPU-side (source) data size, so need to convert for X8R8G8B8
  225. if (format_ == D3DFMT_X8R8G8B8)
  226. rowSize = rowSize / 3 * 4;
  227. // Perform conversion from RGB / RGBA as necessary
  228. switch (format_)
  229. {
  230. default:
  231. for (int i = 0; i < height; ++i)
  232. {
  233. unsigned char* dest = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  234. memcpy(dest, src, rowSize);
  235. src += rowSize;
  236. }
  237. break;
  238. case D3DFMT_X8R8G8B8:
  239. for (int i = 0; i < height; ++i)
  240. {
  241. unsigned char* dest = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  242. for (int j = 0; j < width; ++j)
  243. {
  244. *dest++ = src[2]; *dest++ = src[1]; *dest++ = src[0]; *dest++ = 255;
  245. src += 3;
  246. }
  247. }
  248. break;
  249. case D3DFMT_A8R8G8B8:
  250. for (int i = 0; i < height; ++i)
  251. {
  252. unsigned char* dest = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  253. for (int j = 0; j < width; ++j)
  254. {
  255. *dest++ = src[2]; *dest++ = src[1]; *dest++ = src[0]; *dest++ = src[3];
  256. src += 4;
  257. }
  258. }
  259. break;
  260. }
  261. ((IDirect3DTexture9*)object_)->UnlockRect(level);
  262. return true;
  263. }
  264. bool Texture2D::SetData(SharedPtr<Image> image, bool useAlpha)
  265. {
  266. if (!image)
  267. {
  268. LOGERROR("Null image, can not load texture");
  269. return false;
  270. }
  271. unsigned memoryUse = sizeof(Texture2D);
  272. int quality = QUALITY_HIGH;
  273. Renderer* renderer = GetSubsystem<Renderer>();
  274. if (renderer)
  275. quality = renderer->GetTextureQuality();
  276. if (!image->IsCompressed())
  277. {
  278. unsigned char* levelData = image->GetData();
  279. int levelWidth = image->GetWidth();
  280. int levelHeight = image->GetHeight();
  281. unsigned components = image->GetComponents();
  282. unsigned format = 0;
  283. // Discard unnecessary mip levels
  284. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  285. {
  286. image = image->GetNextLevel();
  287. levelData = image->GetData();
  288. levelWidth = image->GetWidth();
  289. levelHeight = image->GetHeight();
  290. }
  291. switch (components)
  292. {
  293. case 1:
  294. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  295. break;
  296. case 2:
  297. format = Graphics::GetLuminanceAlphaFormat();
  298. break;
  299. case 3:
  300. format = Graphics::GetRGBFormat();
  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, format);
  310. for (unsigned i = 0; i < levels_; ++i)
  311. {
  312. SetData(i, 0, 0, levelWidth, levelHeight, levelData);
  313. memoryUse += levelWidth * levelHeight * components;
  314. if (i < levels_ - 1)
  315. {
  316. image = image->GetNextLevel();
  317. levelData = image->GetData();
  318. levelWidth = image->GetWidth();
  319. levelHeight = image->GetHeight();
  320. }
  321. }
  322. }
  323. else
  324. {
  325. int width = image->GetWidth();
  326. int height = image->GetHeight();
  327. unsigned levels = image->GetNumCompressedLevels();
  328. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  329. bool needDecompress = false;
  330. if (!format)
  331. {
  332. format = Graphics::GetRGBAFormat();
  333. needDecompress = true;
  334. }
  335. unsigned mipsToSkip = mipsToSkip_[quality];
  336. if (mipsToSkip >= levels)
  337. mipsToSkip = levels - 1;
  338. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4))
  339. --mipsToSkip;
  340. width /= (1 << mipsToSkip);
  341. height /= (1 << mipsToSkip);
  342. SetNumLevels(Max((int)(levels - mipsToSkip), 1));
  343. SetSize(width, height, format);
  344. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  345. {
  346. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  347. if (!needDecompress)
  348. {
  349. SetData(i, 0, 0, level.width_, level.height_, level.data_);
  350. memoryUse += level.rows_ * level.rowSize_;
  351. }
  352. else
  353. {
  354. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  355. level.Decompress(rgbaData);
  356. SetData(i, 0, 0, level.width_, level.height_, rgbaData);
  357. memoryUse += level.width_ * level.height_ * 4;
  358. delete[] rgbaData;
  359. }
  360. }
  361. }
  362. SetMemoryUse(memoryUse);
  363. return true;
  364. }
  365. bool Texture2D::GetData(unsigned level, void* dest) const
  366. {
  367. if (!object_)
  368. {
  369. LOGERROR("No texture created, can not get data");
  370. return false;
  371. }
  372. if (!dest)
  373. {
  374. LOGERROR("Null destination for getting data");
  375. return false;
  376. }
  377. if (level >= levels_)
  378. {
  379. LOGERROR("Illegal mip level for getting data");
  380. return false;
  381. }
  382. if (graphics_->IsDeviceLost())
  383. {
  384. LOGWARNING("Getting texture data while device is lost");
  385. return false;
  386. }
  387. int levelWidth = GetLevelWidth(level);
  388. int levelHeight = GetLevelHeight(level);
  389. D3DLOCKED_RECT d3dLockedRect;
  390. RECT d3dRect;
  391. d3dRect.left = 0;
  392. d3dRect.top = 0;
  393. d3dRect.right = levelWidth;
  394. d3dRect.bottom = levelHeight;
  395. if (FAILED(((IDirect3DTexture9*)object_)->LockRect(level, &d3dLockedRect, &d3dRect, D3DLOCK_READONLY)))
  396. {
  397. LOGERROR("Could not lock texture");
  398. return false;
  399. }
  400. int height = levelHeight;
  401. if (IsCompressed())
  402. height = (height + 3) >> 2;
  403. unsigned char* destPtr = (unsigned char*)dest;
  404. unsigned rowSize = GetRowDataSize(levelWidth);
  405. // GetRowDataSize() returns CPU-side (destination) data size, so need to convert for X8R8G8B8
  406. if (format_ == D3DFMT_X8R8G8B8)
  407. rowSize = rowSize / 3 * 4;
  408. // Perform conversion to RGB / RGBA as necessary
  409. switch (format_)
  410. {
  411. default:
  412. for (int i = 0; i < height; ++i)
  413. {
  414. unsigned char* src = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  415. memcpy(destPtr, src, rowSize);
  416. destPtr += rowSize;
  417. }
  418. break;
  419. case D3DFMT_X8R8G8B8:
  420. for (int i = 0; i < height; ++i)
  421. {
  422. unsigned char* src = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  423. for (int j = 0; j < levelWidth; ++j)
  424. {
  425. destPtr[2] = *src++; destPtr[1] = *src++; destPtr[0] = *src++; ++src;
  426. destPtr += 3;
  427. }
  428. }
  429. break;
  430. case D3DFMT_A8R8G8B8:
  431. for (int i = 0; i < height; ++i)
  432. {
  433. unsigned char* src = (unsigned char*)d3dLockedRect.pBits + i * d3dLockedRect.Pitch;
  434. for (int j = 0; j < levelWidth; ++j)
  435. {
  436. destPtr[2] = *src++; destPtr[1] = *src++; destPtr[0] = *src++; destPtr[3] = *src++;
  437. destPtr += 4;
  438. }
  439. }
  440. break;
  441. }
  442. ((IDirect3DTexture9*)object_)->UnlockRect(level);
  443. return true;
  444. }
  445. bool Texture2D::Create()
  446. {
  447. Release();
  448. if (!graphics_ || !width_ || !height_)
  449. return false;
  450. if (graphics_->IsDeviceLost())
  451. {
  452. LOGWARNING("Texture creation while device is lost");
  453. return true;
  454. }
  455. IDirect3DDevice9* device = graphics_->GetImpl()->GetDevice();
  456. // If creating a depth-stencil texture, and it is not supported, create a depth-stencil surface instead
  457. if (usage_ & D3DUSAGE_DEPTHSTENCIL && !graphics_->GetImpl()->CheckFormatSupport((D3DFORMAT)format_, usage_, D3DRTYPE_TEXTURE))
  458. {
  459. if (!device || FAILED(device->CreateDepthStencilSurface(
  460. width_,
  461. height_,
  462. (D3DFORMAT)format_,
  463. D3DMULTISAMPLE_NONE,
  464. 0,
  465. FALSE,
  466. (IDirect3DSurface9**)&renderSurface_->surface_,
  467. 0)))
  468. {
  469. LOGERROR("Could not create depth-stencil surface");
  470. return false;
  471. }
  472. levels_ = 1;
  473. }
  474. else
  475. {
  476. if (!device || FAILED(graphics_->GetImpl()->GetDevice()->CreateTexture(
  477. width_,
  478. height_,
  479. requestedLevels_,
  480. usage_,
  481. (D3DFORMAT)format_,
  482. (D3DPOOL)pool_,
  483. (IDirect3DTexture9**)&object_,
  484. 0)))
  485. {
  486. LOGERROR("Could not create texture");
  487. return false;
  488. }
  489. levels_ = ((IDirect3DTexture9*)object_)->GetLevelCount();
  490. if (usage_ & (D3DUSAGE_RENDERTARGET | D3DUSAGE_DEPTHSTENCIL))
  491. ((IDirect3DTexture9*)object_)->GetSurfaceLevel(0, (IDirect3DSurface9**)&renderSurface_->surface_);
  492. }
  493. return true;
  494. }
  495. void Texture2D::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  496. {
  497. if (renderSurface_ && renderSurface_->GetUpdateMode() == SURFACE_UPDATEALWAYS)
  498. renderSurface_->QueueUpdate();
  499. }
  500. }