D3D9Texture2D.cpp 16 KB

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