D3D11Texture2D.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. //
  2. // Copyright (c) 2008-2015 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 "../../Core/Context.h"
  23. #include "../../IO/FileSystem.h"
  24. #include "../../Graphics/Graphics.h"
  25. #include "../../Graphics/GraphicsEvents.h"
  26. #include "../../Graphics/GraphicsImpl.h"
  27. #include "../../IO/Log.h"
  28. #include "../../Graphics/Renderer.h"
  29. #include "../../Core/Profiler.h"
  30. #include "../../Resource/ResourceCache.h"
  31. #include "../../Graphics/Texture2D.h"
  32. #include "../../Resource/XMLFile.h"
  33. #include "../../DebugNew.h"
  34. namespace Urho3D
  35. {
  36. Texture2D::Texture2D(Context* context) :
  37. Texture(context)
  38. {
  39. }
  40. Texture2D::~Texture2D()
  41. {
  42. Release();
  43. }
  44. void Texture2D::RegisterObject(Context* context)
  45. {
  46. context->RegisterFactory<Texture2D>();
  47. }
  48. bool Texture2D::BeginLoad(Deserializer& source)
  49. {
  50. // In headless mode, do not actually load the texture, just return success
  51. if (!graphics_)
  52. return true;
  53. // Load the image data for EndLoad()
  54. loadImage_ = new Image(context_);
  55. if (!loadImage_->Load(source))
  56. {
  57. loadImage_.Reset();
  58. return false;
  59. }
  60. // Precalculate mip levels if async loading
  61. if (GetAsyncLoadState() == ASYNC_LOADING)
  62. loadImage_->PrecalculateLevels();
  63. // Load the optional parameters file
  64. ResourceCache* cache = GetSubsystem<ResourceCache>();
  65. String xmlName = ReplaceExtension(GetName(), ".xml");
  66. loadParameters_ = cache->GetTempResource<XMLFile>(xmlName, false);
  67. return true;
  68. }
  69. bool Texture2D::EndLoad()
  70. {
  71. // In headless mode, do not actually load the texture, just return success
  72. if (!graphics_)
  73. return true;
  74. // If over the texture budget, see if materials can be freed to allow textures to be freed
  75. CheckTextureBudget(GetTypeStatic());
  76. SetParameters(loadParameters_);
  77. bool success = SetData(loadImage_);
  78. loadImage_.Reset();
  79. loadParameters_.Reset();
  80. return success;
  81. }
  82. void Texture2D::Release()
  83. {
  84. if (object_)
  85. {
  86. if (!graphics_)
  87. return;
  88. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  89. {
  90. if (graphics_->GetTexture(i) == this)
  91. graphics_->SetTexture(i, 0);
  92. }
  93. if (renderSurface_)
  94. renderSurface_->Release();
  95. ((ID3D11Resource*)object_)->Release();
  96. object_ = 0;
  97. if (shaderResourceView_)
  98. {
  99. ((ID3D11ShaderResourceView*)shaderResourceView_)->Release();
  100. shaderResourceView_ = 0;
  101. }
  102. if (sampler_)
  103. {
  104. ((ID3D11SamplerState*)sampler_)->Release();
  105. sampler_ = 0;
  106. }
  107. }
  108. else
  109. {
  110. if (renderSurface_)
  111. renderSurface_->Release();
  112. }
  113. }
  114. bool Texture2D::SetSize(int width, int height, unsigned format, TextureUsage usage)
  115. {
  116. // Delete the old rendersurface if any
  117. renderSurface_.Reset();
  118. usage_ = usage;
  119. if (usage_ == TEXTURE_RENDERTARGET || usage_ == TEXTURE_DEPTHSTENCIL)
  120. {
  121. renderSurface_ = new RenderSurface(this);
  122. // Clamp mode addressing by default, nearest filtering, and mipmaps disabled
  123. addressMode_[COORD_U] = ADDRESS_CLAMP;
  124. addressMode_[COORD_V] = ADDRESS_CLAMP;
  125. filterMode_ = FILTER_NEAREST;
  126. requestedLevels_ = 1;
  127. }
  128. if (usage_ == TEXTURE_RENDERTARGET)
  129. SubscribeToEvent(E_RENDERSURFACEUPDATE, HANDLER(Texture2D, HandleRenderSurfaceUpdate));
  130. else
  131. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  132. width_ = width;
  133. height_ = height;
  134. format_ = format;
  135. return Create();
  136. }
  137. bool Texture2D::SetData(unsigned level, int x, int y, int width, int height, const void* data)
  138. {
  139. PROFILE(SetTextureData);
  140. if (!object_)
  141. {
  142. LOGERROR("No texture created, can not set data");
  143. return false;
  144. }
  145. if (!data)
  146. {
  147. LOGERROR("Null source for setting data");
  148. return false;
  149. }
  150. if (level >= levels_)
  151. {
  152. LOGERROR("Illegal mip level for setting data");
  153. return false;
  154. }
  155. int levelWidth = GetLevelWidth(level);
  156. int levelHeight = GetLevelHeight(level);
  157. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  158. {
  159. LOGERROR("Illegal dimensions for setting data");
  160. return false;
  161. }
  162. // If compressed, align the update region on a block
  163. if (IsCompressed())
  164. {
  165. x &= ~3;
  166. y &= ~3;
  167. width += 3;
  168. width &= 0xfffffffc;
  169. height += 3;
  170. height &= 0xfffffffc;
  171. }
  172. unsigned char* src = (unsigned char*)data;
  173. unsigned rowSize = GetRowDataSize(width);
  174. unsigned rowStart = GetRowDataSize(x);
  175. unsigned subResource = D3D11CalcSubresource(level, 0, levels_);
  176. if (usage_ == TEXTURE_DYNAMIC)
  177. {
  178. if (IsCompressed())
  179. {
  180. height = (height + 3) >> 2;
  181. y >>= 2;
  182. }
  183. D3D11_MAPPED_SUBRESOURCE mappedData;
  184. mappedData.pData = 0;
  185. graphics_->GetImpl()->GetDeviceContext()->Map((ID3D11Resource*)object_, subResource, D3D11_MAP_WRITE_DISCARD, 0,
  186. &mappedData);
  187. if (mappedData.pData)
  188. {
  189. for (int row = 0; row < height; ++row)
  190. memcpy((unsigned char*)mappedData.pData + (row + y) * mappedData.RowPitch + rowStart, src + row * rowSize, rowSize);
  191. graphics_->GetImpl()->GetDeviceContext()->Unmap((ID3D11Resource*)object_, subResource);
  192. }
  193. else
  194. {
  195. LOGERROR("Failed to map texture for update");
  196. return false;
  197. }
  198. }
  199. else
  200. {
  201. D3D11_BOX destBox;
  202. destBox.left = x;
  203. destBox.right = x + width;
  204. destBox.top = y;
  205. destBox.bottom = y + height;
  206. destBox.front = 0;
  207. destBox.back = 1;
  208. graphics_->GetImpl()->GetDeviceContext()->UpdateSubresource((ID3D11Resource*)object_, subResource, &destBox, data,
  209. rowSize, 0);
  210. }
  211. return true;
  212. }
  213. bool Texture2D::SetData(SharedPtr<Image> image, bool useAlpha)
  214. {
  215. if (!image)
  216. {
  217. LOGERROR("Null image, can not load texture");
  218. return false;
  219. }
  220. unsigned memoryUse = sizeof(Texture2D);
  221. int quality = QUALITY_HIGH;
  222. Renderer* renderer = GetSubsystem<Renderer>();
  223. if (renderer)
  224. quality = renderer->GetTextureQuality();
  225. if (!image->IsCompressed())
  226. {
  227. // Convert unsuitable formats to RGBA
  228. unsigned components = image->GetComponents();
  229. if ((components == 1 && !useAlpha) || components == 2 || components == 3)
  230. {
  231. image = image->ConvertToRGBA();
  232. if (!image)
  233. return false;
  234. components = image->GetComponents();
  235. }
  236. unsigned char* levelData = image->GetData();
  237. int levelWidth = image->GetWidth();
  238. int levelHeight = image->GetHeight();
  239. unsigned format = 0;
  240. // Discard unnecessary mip levels
  241. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  242. {
  243. image = image->GetNextLevel();
  244. levelData = image->GetData();
  245. levelWidth = image->GetWidth();
  246. levelHeight = image->GetHeight();
  247. }
  248. switch (components)
  249. {
  250. case 1:
  251. format = Graphics::GetAlphaFormat();
  252. break;
  253. case 4:
  254. format = Graphics::GetRGBAFormat();
  255. break;
  256. }
  257. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  258. if (IsCompressed() && requestedLevels_ > 1)
  259. requestedLevels_ = 0;
  260. SetSize(levelWidth, levelHeight, format);
  261. for (unsigned i = 0; i < levels_; ++i)
  262. {
  263. SetData(i, 0, 0, levelWidth, levelHeight, levelData);
  264. memoryUse += levelWidth * levelHeight * components;
  265. if (i < levels_ - 1)
  266. {
  267. image = image->GetNextLevel();
  268. levelData = image->GetData();
  269. levelWidth = image->GetWidth();
  270. levelHeight = image->GetHeight();
  271. }
  272. }
  273. }
  274. else
  275. {
  276. int width = image->GetWidth();
  277. int height = image->GetHeight();
  278. unsigned levels = image->GetNumCompressedLevels();
  279. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  280. bool needDecompress = false;
  281. if (!format)
  282. {
  283. format = Graphics::GetRGBAFormat();
  284. needDecompress = true;
  285. }
  286. unsigned mipsToSkip = mipsToSkip_[quality];
  287. if (mipsToSkip >= levels)
  288. mipsToSkip = levels - 1;
  289. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4))
  290. --mipsToSkip;
  291. width /= (1 << mipsToSkip);
  292. height /= (1 << mipsToSkip);
  293. SetNumLevels(Max((int)(levels - mipsToSkip), 1));
  294. SetSize(width, height, format);
  295. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  296. {
  297. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  298. if (!needDecompress)
  299. {
  300. SetData(i, 0, 0, level.width_, level.height_, level.data_);
  301. memoryUse += level.rows_ * level.rowSize_;
  302. }
  303. else
  304. {
  305. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  306. level.Decompress(rgbaData);
  307. SetData(i, 0, 0, level.width_, level.height_, rgbaData);
  308. memoryUse += level.width_ * level.height_ * 4;
  309. delete[] rgbaData;
  310. }
  311. }
  312. }
  313. SetMemoryUse(memoryUse);
  314. return true;
  315. }
  316. bool Texture2D::GetData(unsigned level, void* dest) const
  317. {
  318. if (!object_)
  319. {
  320. LOGERROR("No texture created, can not get data");
  321. return false;
  322. }
  323. if (!dest)
  324. {
  325. LOGERROR("Null destination for getting data");
  326. return false;
  327. }
  328. if (level >= levels_)
  329. {
  330. LOGERROR("Illegal mip level for getting data");
  331. return false;
  332. }
  333. int levelWidth = GetLevelWidth(level);
  334. int levelHeight = GetLevelHeight(level);
  335. D3D11_TEXTURE2D_DESC textureDesc;
  336. memset(&textureDesc, 0, sizeof textureDesc);
  337. textureDesc.Width = levelWidth;
  338. textureDesc.Height = levelHeight;
  339. textureDesc.MipLevels = 1;
  340. textureDesc.ArraySize = 1;
  341. textureDesc.Format = (DXGI_FORMAT)format_;
  342. textureDesc.SampleDesc.Count = 1;
  343. textureDesc.SampleDesc.Quality = 0;
  344. textureDesc.Usage = D3D11_USAGE_STAGING;
  345. textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  346. ID3D11Texture2D* stagingTexture = 0;
  347. graphics_->GetImpl()->GetDevice()->CreateTexture2D(&textureDesc, 0, &stagingTexture);
  348. if (!stagingTexture)
  349. {
  350. LOGERROR("Failed to create staging texture for GetData");
  351. return false;
  352. }
  353. unsigned srcSubResource = D3D11CalcSubresource(level, 0, levels_);
  354. D3D11_BOX srcBox;
  355. srcBox.left = 0;
  356. srcBox.right = levelWidth;
  357. srcBox.top = 0;
  358. srcBox.bottom = levelHeight;
  359. srcBox.front = 0;
  360. srcBox.back = 1;
  361. graphics_->GetImpl()->GetDeviceContext()->CopySubresourceRegion(stagingTexture, 0, 0, 0, 0, (ID3D11Resource*)object_,
  362. srcSubResource, &srcBox);
  363. D3D11_MAPPED_SUBRESOURCE mappedData;
  364. mappedData.pData = 0;
  365. unsigned rowSize = GetRowDataSize(levelWidth);
  366. unsigned numRows = IsCompressed() ? (levelHeight + 3) >> 2 : levelHeight;
  367. graphics_->GetImpl()->GetDeviceContext()->Map((ID3D11Resource*)stagingTexture, 0, D3D11_MAP_READ, 0, &mappedData);
  368. if (mappedData.pData)
  369. {
  370. for (unsigned row = 0; row < numRows; ++row)
  371. memcpy((unsigned char*)dest + row * rowSize, (unsigned char*)mappedData.pData + row * mappedData.RowPitch, rowSize);
  372. graphics_->GetImpl()->GetDeviceContext()->Unmap((ID3D11Resource*)stagingTexture, 0);
  373. stagingTexture->Release();
  374. return true;
  375. }
  376. else
  377. {
  378. LOGERROR("Failed to map staging texture for GetData");
  379. stagingTexture->Release();
  380. return false;
  381. }
  382. }
  383. bool Texture2D::Create()
  384. {
  385. Release();
  386. if (!graphics_ || !width_ || !height_)
  387. return false;
  388. levels_ = CheckMaxLevels(width_, height_, requestedLevels_);
  389. D3D11_TEXTURE2D_DESC textureDesc;
  390. memset(&textureDesc, 0, sizeof textureDesc);
  391. textureDesc.Width = width_;
  392. textureDesc.Height = height_;
  393. textureDesc.MipLevels = levels_;
  394. textureDesc.ArraySize = 1;
  395. textureDesc.Format = (DXGI_FORMAT)(sRGB_ ? GetSRGBFormat(format_) : format_);
  396. textureDesc.SampleDesc.Count = 1;
  397. textureDesc.SampleDesc.Quality = 0;
  398. textureDesc.Usage = usage_ == TEXTURE_DYNAMIC ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT;
  399. textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  400. if (usage_ == TEXTURE_RENDERTARGET)
  401. textureDesc.BindFlags |= D3D11_BIND_RENDER_TARGET;
  402. else if (usage_ == TEXTURE_DEPTHSTENCIL)
  403. textureDesc.BindFlags |= D3D11_BIND_DEPTH_STENCIL;
  404. textureDesc.CPUAccessFlags = usage_ == TEXTURE_DYNAMIC ? D3D11_CPU_ACCESS_WRITE : 0;
  405. graphics_->GetImpl()->GetDevice()->CreateTexture2D(&textureDesc, 0, (ID3D11Texture2D**)&object_);
  406. if (!object_)
  407. {
  408. LOGERROR("Failed to create texture");
  409. return false;
  410. }
  411. D3D11_SHADER_RESOURCE_VIEW_DESC resourceViewDesc;
  412. memset(&resourceViewDesc, 0, sizeof resourceViewDesc);
  413. resourceViewDesc.Format = (DXGI_FORMAT)GetSRVFormat(textureDesc.Format);
  414. resourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
  415. resourceViewDesc.Texture2D.MipLevels = (unsigned)levels_;
  416. graphics_->GetImpl()->GetDevice()->CreateShaderResourceView((ID3D11Resource*)object_, &resourceViewDesc,
  417. (ID3D11ShaderResourceView**)&shaderResourceView_);
  418. if (!shaderResourceView_)
  419. {
  420. LOGERROR("Failed to create shader resource view for texture");
  421. return false;
  422. }
  423. if (usage_ == TEXTURE_RENDERTARGET)
  424. {
  425. renderSurface_ = new RenderSurface(this);
  426. D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc;
  427. memset(&renderTargetViewDesc, 0, sizeof renderTargetViewDesc);
  428. renderTargetViewDesc.Format = textureDesc.Format;
  429. renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  430. graphics_->GetImpl()->GetDevice()->CreateRenderTargetView((ID3D11Resource*)object_, &renderTargetViewDesc,
  431. (ID3D11RenderTargetView**)&renderSurface_->renderTargetView_);
  432. if (!renderSurface_->renderTargetView_)
  433. {
  434. LOGERROR("Failed to create rendertarget view for texture");
  435. return false;
  436. }
  437. }
  438. else if (usage_ == TEXTURE_DEPTHSTENCIL)
  439. {
  440. renderSurface_ = new RenderSurface(this);
  441. D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
  442. memset(&depthStencilViewDesc, 0, sizeof depthStencilViewDesc);
  443. depthStencilViewDesc.Format = (DXGI_FORMAT)GetDSVFormat(textureDesc.Format);
  444. depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
  445. graphics_->GetImpl()->GetDevice()->CreateDepthStencilView((ID3D11Resource*)object_, &depthStencilViewDesc,
  446. (ID3D11DepthStencilView**)&renderSurface_->renderTargetView_);
  447. if (!renderSurface_->renderTargetView_)
  448. {
  449. LOGERROR("Failed to create depth-stencil view for texture");
  450. return false;
  451. }
  452. }
  453. return true;
  454. }
  455. void Texture2D::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  456. {
  457. if (renderSurface_ && renderSurface_->GetUpdateMode() == SURFACE_UPDATEALWAYS)
  458. renderSurface_->QueueUpdate();
  459. }
  460. }