D3D11Texture2D.cpp 16 KB

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