D3D9Texture2D.cpp 16 KB

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