OGLTexture2DArray.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. //
  2. // Copyright (c) 2008-2016 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/Texture2DArray.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. #ifdef _MSC_VER
  36. #pragma warning(disable:4355)
  37. #endif
  38. namespace Urho3D
  39. {
  40. Texture2DArray::Texture2DArray(Context* context) :
  41. Texture(context),
  42. layers_(0)
  43. {
  44. #ifndef GL_ES_VERSION_2_0
  45. target_ = GL_TEXTURE_2D_ARRAY;
  46. #else
  47. target_ = 0;
  48. #endif
  49. }
  50. Texture2DArray::~Texture2DArray()
  51. {
  52. Release();
  53. }
  54. void Texture2DArray::RegisterObject(Context* context)
  55. {
  56. context->RegisterFactory<Texture2DArray>();
  57. }
  58. bool Texture2DArray::BeginLoad(Deserializer& source)
  59. {
  60. ResourceCache* cache = GetSubsystem<ResourceCache>();
  61. // In headless mode, do not actually load the texture, just return success
  62. if (!graphics_)
  63. return true;
  64. // If device is lost, retry later
  65. if (graphics_->IsDeviceLost())
  66. {
  67. URHO3D_LOGWARNING("Texture load while device is lost");
  68. dataPending_ = true;
  69. return true;
  70. }
  71. cache->ResetDependencies(this);
  72. String texPath, texName, texExt;
  73. SplitPath(GetName(), texPath, texName, texExt);
  74. loadParameters_ = (new XMLFile(context_));
  75. if (!loadParameters_->Load(source))
  76. {
  77. loadParameters_.Reset();
  78. return false;
  79. }
  80. loadImages_.Clear();
  81. XMLElement textureElem = loadParameters_->GetRoot();
  82. XMLElement layerElem = textureElem.GetChild("layer");
  83. while (layerElem)
  84. {
  85. String name = layerElem.GetAttribute("name");
  86. // If path is empty, add the XML file path
  87. if (GetPath(name).Empty())
  88. name = texPath + name;
  89. loadImages_.Push(cache->GetTempResource<Image>(name));
  90. cache->StoreResourceDependency(this, name);
  91. layerElem = layerElem.GetNext("layer");
  92. }
  93. // Precalculate mip levels if async loading
  94. if (GetAsyncLoadState() == ASYNC_LOADING)
  95. {
  96. for (unsigned i = 0; i < loadImages_.Size(); ++i)
  97. {
  98. if (loadImages_[i])
  99. loadImages_[i]->PrecalculateLevels();
  100. }
  101. }
  102. return true;
  103. }
  104. bool Texture2DArray::EndLoad()
  105. {
  106. // In headless mode, do not actually load the texture, just return success
  107. if (!graphics_ || graphics_->IsDeviceLost())
  108. return true;
  109. // If over the texture budget, see if materials can be freed to allow textures to be freed
  110. CheckTextureBudget(GetTypeStatic());
  111. SetParameters(loadParameters_);
  112. SetLayers(loadImages_.Size());
  113. for (unsigned i = 0; i < loadImages_.Size(); ++i)
  114. SetData(i, loadImages_[i]);
  115. loadImages_.Clear();
  116. loadParameters_.Reset();
  117. return true;
  118. }
  119. void Texture2DArray::OnDeviceLost()
  120. {
  121. GPUObject::OnDeviceLost();
  122. if (renderSurface_)
  123. renderSurface_->OnDeviceLost();
  124. }
  125. void Texture2DArray::OnDeviceReset()
  126. {
  127. if (!object_.name_ || dataPending_)
  128. {
  129. // If has a resource file, reload through the resource cache. Otherwise just recreate.
  130. ResourceCache* cache = GetSubsystem<ResourceCache>();
  131. if (cache->Exists(GetName()))
  132. dataLost_ = !cache->ReloadResource(this);
  133. if (!object_.name_)
  134. {
  135. Create();
  136. dataLost_ = true;
  137. }
  138. }
  139. dataPending_ = false;
  140. }
  141. void Texture2DArray::Release()
  142. {
  143. if (object_.name_)
  144. {
  145. if (!graphics_)
  146. return;
  147. if (!graphics_->IsDeviceLost())
  148. {
  149. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  150. {
  151. if (graphics_->GetTexture(i) == this)
  152. graphics_->SetTexture(i, 0);
  153. }
  154. glDeleteTextures(1, &object_.name_);
  155. }
  156. if (renderSurface_)
  157. renderSurface_->Release();
  158. object_.name_ = 0;
  159. }
  160. }
  161. void Texture2DArray::SetLayers(unsigned layers)
  162. {
  163. Release();
  164. layers_ = layers;
  165. }
  166. bool Texture2DArray::SetSize(unsigned layers, int width, int height, unsigned format, TextureUsage usage)
  167. {
  168. if (width <= 0 || height <= 0)
  169. {
  170. URHO3D_LOGERROR("Zero or negative texture array size");
  171. return false;
  172. }
  173. if (usage == TEXTURE_DEPTHSTENCIL)
  174. {
  175. URHO3D_LOGERROR("Depth-stencil usage not supported for texture arrays");
  176. return false;
  177. }
  178. // Delete the old rendersurface if any
  179. renderSurface_.Reset();
  180. usage_ = usage;
  181. if (usage == TEXTURE_RENDERTARGET)
  182. {
  183. renderSurface_ = new RenderSurface(this);
  184. // Nearest filtering and mipmaps disabled by default
  185. filterMode_ = FILTER_NEAREST;
  186. requestedLevels_ = 1;
  187. }
  188. if (usage == TEXTURE_RENDERTARGET)
  189. SubscribeToEvent(E_RENDERSURFACEUPDATE, URHO3D_HANDLER(Texture2DArray, HandleRenderSurfaceUpdate));
  190. else
  191. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  192. width_ = width;
  193. height_ = height;
  194. format_ = format;
  195. if (layers)
  196. layers_ = layers;
  197. layerMemoryUse_.Resize(layers_);
  198. for (unsigned i = 0; i < layers_; ++i)
  199. layerMemoryUse_[i] = 0;
  200. return Create();
  201. }
  202. bool Texture2DArray::SetData(unsigned layer, unsigned level, int x, int y, int width, int height, const void* data)
  203. {
  204. URHO3D_PROFILE(SetTextureData);
  205. if (!object_.name_ || !graphics_)
  206. {
  207. URHO3D_LOGERROR("Texture array not created, can not set data");
  208. return false;
  209. }
  210. if (!data)
  211. {
  212. URHO3D_LOGERROR("Null source for setting data");
  213. return false;
  214. }
  215. if (layer >= layers_)
  216. {
  217. URHO3D_LOGERROR("Illegal layer for setting data");
  218. return false;
  219. }
  220. if (level >= levels_)
  221. {
  222. URHO3D_LOGERROR("Illegal mip level for setting data");
  223. return false;
  224. }
  225. if (graphics_->IsDeviceLost())
  226. {
  227. URHO3D_LOGWARNING("Texture array data assignment while device is lost");
  228. dataPending_ = true;
  229. return true;
  230. }
  231. if (IsCompressed())
  232. {
  233. x &= ~3;
  234. y &= ~3;
  235. }
  236. int levelWidth = GetLevelWidth(level);
  237. int levelHeight = GetLevelHeight(level);
  238. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  239. {
  240. URHO3D_LOGERROR("Illegal dimensions for setting data");
  241. return false;
  242. }
  243. graphics_->SetTextureForUpdate(this);
  244. #ifndef GL_ES_VERSION_2_0
  245. bool wholeLevel = x == 0 && y == 0 && width == levelWidth && height == levelHeight && layer == 0;
  246. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  247. if (!IsCompressed())
  248. {
  249. if (wholeLevel)
  250. glTexImage3D(target_, level, format, width, height, layers_, 0, GetExternalFormat(format_),
  251. GetDataType(format_), 0);
  252. glTexSubImage3D(target_, level, x, y, layer, width, height, 1, GetExternalFormat(format_),
  253. GetDataType(format_), data);
  254. }
  255. else
  256. {
  257. if (wholeLevel)
  258. glCompressedTexImage3D(target_, level, format, width, height, layers_, 0,
  259. GetDataSize(width, height, layers_), 0);
  260. glCompressedTexSubImage3D(target_, level, x, y, layer, width, height, 1, format,
  261. GetDataSize(width, height), data);
  262. }
  263. #endif
  264. graphics_->SetTexture(0, 0);
  265. return true;
  266. }
  267. bool Texture2DArray::SetData(unsigned layer, Deserializer& source)
  268. {
  269. SharedPtr<Image> image(new Image(context_));
  270. if (!image->Load(source))
  271. return false;
  272. return SetData(layer, image);
  273. }
  274. bool Texture2DArray::SetData(unsigned layer, Image* image, bool useAlpha)
  275. {
  276. if (!image)
  277. {
  278. URHO3D_LOGERROR("Null image, can not set data");
  279. return false;
  280. }
  281. if (!layers_)
  282. {
  283. URHO3D_LOGERROR("Number of layers in the array must be set first");
  284. return false;
  285. }
  286. if (layer >= layers_)
  287. {
  288. URHO3D_LOGERROR("Illegal layer for setting data");
  289. return false;
  290. }
  291. // Use a shared ptr for managing the temporary mip images created during this function
  292. SharedPtr<Image> mipImage;
  293. unsigned memoryUse = 0;
  294. int quality = QUALITY_HIGH;
  295. Renderer* renderer = GetSubsystem<Renderer>();
  296. if (renderer)
  297. quality = renderer->GetTextureQuality();
  298. if (!image->IsCompressed())
  299. {
  300. // Convert unsuitable formats to RGBA
  301. unsigned components = image->GetComponents();
  302. if (Graphics::GetGL3Support() && ((components == 1 && !useAlpha) || components == 2))
  303. {
  304. mipImage = image->ConvertToRGBA(); image = mipImage;
  305. if (!image)
  306. return false;
  307. components = image->GetComponents();
  308. }
  309. unsigned char* levelData = image->GetData();
  310. int levelWidth = image->GetWidth();
  311. int levelHeight = image->GetHeight();
  312. unsigned format = 0;
  313. // Discard unnecessary mip levels
  314. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  315. {
  316. mipImage = image->GetNextLevel(); image = mipImage;
  317. levelData = image->GetData();
  318. levelWidth = image->GetWidth();
  319. levelHeight = image->GetHeight();
  320. }
  321. switch (components)
  322. {
  323. case 1:
  324. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  325. break;
  326. case 2:
  327. format = Graphics::GetLuminanceAlphaFormat();
  328. break;
  329. case 3:
  330. format = Graphics::GetRGBFormat();
  331. break;
  332. case 4:
  333. format = Graphics::GetRGBAFormat();
  334. break;
  335. default:
  336. assert(false); // Should not reach here
  337. break;
  338. }
  339. // Create the texture array when layer 0 is being loaded, check that rest of the layers are same size & format
  340. if (!layer)
  341. {
  342. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  343. if (IsCompressed() && requestedLevels_ > 1)
  344. requestedLevels_ = 0;
  345. // Create the texture array (the number of layers must have been already set)
  346. SetSize(0, levelWidth, levelHeight, format);
  347. }
  348. else
  349. {
  350. if (!object_.name_)
  351. {
  352. URHO3D_LOGERROR("Texture array layer 0 must be loaded first");
  353. return false;
  354. }
  355. if (levelWidth != width_ || levelHeight != height_ || format != format_)
  356. {
  357. URHO3D_LOGERROR("Texture array layer does not match size or format of layer 0");
  358. return false;
  359. }
  360. }
  361. for (unsigned i = 0; i < levels_; ++i)
  362. {
  363. SetData(layer, i, 0, 0, levelWidth, levelHeight, levelData);
  364. memoryUse += levelWidth * levelHeight * components;
  365. if (i < levels_ - 1)
  366. {
  367. mipImage = image->GetNextLevel(); image = mipImage;
  368. levelData = image->GetData();
  369. levelWidth = image->GetWidth();
  370. levelHeight = image->GetHeight();
  371. }
  372. }
  373. }
  374. else
  375. {
  376. int width = image->GetWidth();
  377. int height = image->GetHeight();
  378. unsigned levels = image->GetNumCompressedLevels();
  379. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  380. bool needDecompress = false;
  381. if (!format)
  382. {
  383. format = Graphics::GetRGBAFormat();
  384. needDecompress = true;
  385. }
  386. unsigned mipsToSkip = mipsToSkip_[quality];
  387. if (mipsToSkip >= levels)
  388. mipsToSkip = levels - 1;
  389. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4))
  390. --mipsToSkip;
  391. width /= (1 << mipsToSkip);
  392. height /= (1 << mipsToSkip);
  393. // Create the texture array when layer 0 is being loaded, assume rest of the layers are same size & format
  394. if (!layer)
  395. {
  396. SetNumLevels(Max((levels - mipsToSkip), 1U));
  397. SetSize(0, width, height, format);
  398. }
  399. else
  400. {
  401. if (!object_.name_)
  402. {
  403. URHO3D_LOGERROR("Texture array layer 0 must be loaded first");
  404. return false;
  405. }
  406. if (width != width_ || height != height_ || format != format_)
  407. {
  408. URHO3D_LOGERROR("Texture array layer does not match size or format of layer 0");
  409. return false;
  410. }
  411. }
  412. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  413. {
  414. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  415. if (!needDecompress)
  416. {
  417. SetData(layer, i, 0, 0, level.width_, level.height_, level.data_);
  418. memoryUse += level.rows_ * level.rowSize_;
  419. }
  420. else
  421. {
  422. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  423. level.Decompress(rgbaData);
  424. SetData(layer, i, 0, 0, level.width_, level.height_, rgbaData);
  425. memoryUse += level.width_ * level.height_ * 4;
  426. delete[] rgbaData;
  427. }
  428. }
  429. }
  430. layerMemoryUse_[layer] = memoryUse;
  431. unsigned totalMemoryUse = sizeof(Texture2DArray) + layerMemoryUse_.Capacity() * sizeof(unsigned);
  432. for (unsigned i = 0; i < layers_; ++i)
  433. totalMemoryUse += layerMemoryUse_[i];
  434. SetMemoryUse(totalMemoryUse);
  435. return true;
  436. }
  437. bool Texture2DArray::GetData(unsigned layer, unsigned level, void* dest) const
  438. {
  439. #ifndef GL_ES_VERSION_2_0
  440. if (!object_.name_ || !graphics_)
  441. {
  442. URHO3D_LOGERROR("Texture array not created, can not get data");
  443. return false;
  444. }
  445. if (!dest)
  446. {
  447. URHO3D_LOGERROR("Null destination for getting data");
  448. return false;
  449. }
  450. if (layer != 0)
  451. {
  452. URHO3D_LOGERROR("Only the full download of the array is supported, set layer=0");
  453. return false;
  454. }
  455. if (level >= levels_)
  456. {
  457. URHO3D_LOGERROR("Illegal mip level for getting data");
  458. return false;
  459. }
  460. if (graphics_->IsDeviceLost())
  461. {
  462. URHO3D_LOGWARNING("Getting texture data while device is lost");
  463. return false;
  464. }
  465. graphics_->SetTextureForUpdate(const_cast<Texture2DArray*>(this));
  466. if (!IsCompressed())
  467. glGetTexImage(target_, level, GetExternalFormat(format_), GetDataType(format_), dest);
  468. else
  469. glGetCompressedTexImage(target_, level, dest);
  470. graphics_->SetTexture(0, 0);
  471. return true;
  472. #else
  473. URHO3D_LOGERROR("Getting texture data not supported");
  474. return false;
  475. #endif
  476. }
  477. bool Texture2DArray::Create()
  478. {
  479. Release();
  480. #ifdef GL_ES_VERSION_2_0
  481. URHO3D_LOGERROR("Failed to create 2D array texture, currently unsupported on OpenGL ES 2");
  482. return false;
  483. #else
  484. if (!graphics_ || !width_ || !height_ || !layers_)
  485. return false;
  486. if (graphics_->IsDeviceLost())
  487. {
  488. URHO3D_LOGWARNING("Texture array creation while device is lost");
  489. return true;
  490. }
  491. glGenTextures(1, &object_.name_);
  492. // Ensure that our texture is bound to OpenGL texture unit 0
  493. graphics_->SetTextureForUpdate(this);
  494. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  495. unsigned externalFormat = GetExternalFormat(format_);
  496. unsigned dataType = GetDataType(format_);
  497. // If not compressed, create the initial level 0 texture with null data
  498. bool success = true;
  499. if (!IsCompressed())
  500. {
  501. glGetError();
  502. glTexImage3D(target_, 0, format, width_, height_, layers_, 0, externalFormat, dataType, 0);
  503. if (glGetError())
  504. success = false;
  505. }
  506. if (!success)
  507. URHO3D_LOGERROR("Failed to create texture array");
  508. // Set mipmapping
  509. levels_ = CheckMaxLevels(width_, height_, requestedLevels_);
  510. glTexParameteri(target_, GL_TEXTURE_BASE_LEVEL, 0);
  511. glTexParameteri(target_, GL_TEXTURE_MAX_LEVEL, levels_ - 1);
  512. // Set initial parameters, then unbind the texture
  513. UpdateParameters();
  514. graphics_->SetTexture(0, 0);
  515. return success;
  516. #endif
  517. }
  518. void Texture2DArray::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  519. {
  520. if (renderSurface_ && (renderSurface_->GetUpdateMode() == SURFACE_UPDATEALWAYS || renderSurface_->IsUpdateQueued()))
  521. {
  522. Renderer* renderer = GetSubsystem<Renderer>();
  523. if (renderer)
  524. renderer->QueueRenderSurface(renderSurface_);
  525. renderSurface_->ResetUpdateQueued();
  526. }
  527. }
  528. }