D3D9Texture2D.cpp 16 KB

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