OGLTexture2DArray.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. //
  2. // Copyright (c) 2008-2020 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. void Texture2DArray::OnDeviceLost()
  41. {
  42. if (object_.name_ && !graphics_->IsDeviceLost())
  43. glDeleteTextures(1, &object_.name_);
  44. GPUObject::OnDeviceLost();
  45. if (renderSurface_)
  46. renderSurface_->OnDeviceLost();
  47. }
  48. void Texture2DArray::OnDeviceReset()
  49. {
  50. if (!object_.name_ || dataPending_)
  51. {
  52. // If has a resource file, reload through the resource cache. Otherwise just recreate.
  53. auto* cache = GetSubsystem<ResourceCache>();
  54. if (cache->Exists(GetName()))
  55. dataLost_ = !cache->ReloadResource(this);
  56. if (!object_.name_)
  57. {
  58. Create();
  59. dataLost_ = true;
  60. }
  61. }
  62. dataPending_ = false;
  63. }
  64. void Texture2DArray::Release()
  65. {
  66. if (object_.name_)
  67. {
  68. if (!graphics_)
  69. return;
  70. if (!graphics_->IsDeviceLost())
  71. {
  72. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  73. {
  74. if (graphics_->GetTexture(i) == this)
  75. graphics_->SetTexture(i, nullptr);
  76. }
  77. glDeleteTextures(1, &object_.name_);
  78. }
  79. if (renderSurface_)
  80. renderSurface_->Release();
  81. object_.name_ = 0;
  82. }
  83. levelsDirty_ = false;
  84. }
  85. bool Texture2DArray::SetData(unsigned layer, unsigned level, int x, int y, int width, int height, const void* data)
  86. {
  87. URHO3D_PROFILE(SetTextureData);
  88. if (!object_.name_ || !graphics_)
  89. {
  90. URHO3D_LOGERROR("Texture array not created, can not set data");
  91. return false;
  92. }
  93. if (!data)
  94. {
  95. URHO3D_LOGERROR("Null source for setting data");
  96. return false;
  97. }
  98. if (layer >= layers_)
  99. {
  100. URHO3D_LOGERROR("Illegal layer for setting data");
  101. return false;
  102. }
  103. if (level >= levels_)
  104. {
  105. URHO3D_LOGERROR("Illegal mip level for setting data");
  106. return false;
  107. }
  108. if (graphics_->IsDeviceLost())
  109. {
  110. URHO3D_LOGWARNING("Texture array data assignment while device is lost");
  111. dataPending_ = true;
  112. return true;
  113. }
  114. if (IsCompressed())
  115. {
  116. x &= ~3u;
  117. y &= ~3u;
  118. }
  119. int levelWidth = GetLevelWidth(level);
  120. int levelHeight = GetLevelHeight(level);
  121. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  122. {
  123. URHO3D_LOGERROR("Illegal dimensions for setting data");
  124. return false;
  125. }
  126. graphics_->SetTextureForUpdate(this);
  127. #ifndef GL_ES_VERSION_2_0
  128. bool wholeLevel = x == 0 && y == 0 && width == levelWidth && height == levelHeight && layer == 0;
  129. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  130. if (!IsCompressed())
  131. {
  132. if (wholeLevel)
  133. glTexImage3D(target_, level, format, width, height, layers_, 0, GetExternalFormat(format_),
  134. GetDataType(format_), nullptr);
  135. glTexSubImage3D(target_, level, x, y, layer, width, height, 1, GetExternalFormat(format_),
  136. GetDataType(format_), data);
  137. }
  138. else
  139. {
  140. if (wholeLevel)
  141. glCompressedTexImage3D(target_, level, format, width, height, layers_, 0,
  142. GetDataSize(width, height, layers_), nullptr);
  143. glCompressedTexSubImage3D(target_, level, x, y, layer, width, height, 1, format,
  144. GetDataSize(width, height), data);
  145. }
  146. #endif
  147. graphics_->SetTexture(0, nullptr);
  148. return true;
  149. }
  150. bool Texture2DArray::SetData(unsigned layer, Deserializer& source)
  151. {
  152. SharedPtr<Image> image(new Image(context_));
  153. if (!image->Load(source))
  154. return false;
  155. return SetData(layer, image);
  156. }
  157. bool Texture2DArray::SetData(unsigned layer, Image* image, bool useAlpha)
  158. {
  159. if (!image)
  160. {
  161. URHO3D_LOGERROR("Null image, can not set data");
  162. return false;
  163. }
  164. if (!layers_)
  165. {
  166. URHO3D_LOGERROR("Number of layers in the array must be set first");
  167. return false;
  168. }
  169. if (layer >= layers_)
  170. {
  171. URHO3D_LOGERROR("Illegal layer for setting data");
  172. return false;
  173. }
  174. // Use a shared ptr for managing the temporary mip images created during this function
  175. SharedPtr<Image> mipImage;
  176. unsigned memoryUse = 0;
  177. MaterialQuality quality = QUALITY_HIGH;
  178. auto* renderer = GetSubsystem<Renderer>();
  179. if (renderer)
  180. quality = renderer->GetTextureQuality();
  181. if (!image->IsCompressed())
  182. {
  183. // Convert unsuitable formats to RGBA
  184. unsigned components = image->GetComponents();
  185. if (Graphics::GetGL3Support() && ((components == 1 && !useAlpha) || components == 2))
  186. {
  187. mipImage = image->ConvertToRGBA(); image = mipImage;
  188. if (!image)
  189. return false;
  190. components = image->GetComponents();
  191. }
  192. unsigned char* levelData = image->GetData();
  193. int levelWidth = image->GetWidth();
  194. int levelHeight = image->GetHeight();
  195. unsigned format = 0;
  196. // Discard unnecessary mip levels
  197. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  198. {
  199. mipImage = image->GetNextLevel(); image = mipImage;
  200. levelData = image->GetData();
  201. levelWidth = image->GetWidth();
  202. levelHeight = image->GetHeight();
  203. }
  204. switch (components)
  205. {
  206. case 1:
  207. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  208. break;
  209. case 2:
  210. format = Graphics::GetLuminanceAlphaFormat();
  211. break;
  212. case 3:
  213. format = Graphics::GetRGBFormat();
  214. break;
  215. case 4:
  216. format = Graphics::GetRGBAFormat();
  217. break;
  218. default:
  219. assert(false); // Should not reach here
  220. break;
  221. }
  222. // Create the texture array when layer 0 is being loaded, check that rest of the layers are same size & format
  223. if (!layer)
  224. {
  225. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  226. if (IsCompressed() && requestedLevels_ > 1)
  227. requestedLevels_ = 0;
  228. // Create the texture array (the number of layers must have been already set)
  229. SetSize(0, levelWidth, levelHeight, format);
  230. }
  231. else
  232. {
  233. if (!object_.name_)
  234. {
  235. URHO3D_LOGERROR("Texture array layer 0 must be loaded first");
  236. return false;
  237. }
  238. if (levelWidth != width_ || levelHeight != height_ || format != format_)
  239. {
  240. URHO3D_LOGERROR("Texture array layer does not match size or format of layer 0");
  241. return false;
  242. }
  243. }
  244. for (unsigned i = 0; i < levels_; ++i)
  245. {
  246. SetData(layer, i, 0, 0, levelWidth, levelHeight, levelData);
  247. memoryUse += levelWidth * levelHeight * components;
  248. if (i < levels_ - 1)
  249. {
  250. mipImage = image->GetNextLevel(); image = mipImage;
  251. levelData = image->GetData();
  252. levelWidth = image->GetWidth();
  253. levelHeight = image->GetHeight();
  254. }
  255. }
  256. }
  257. else
  258. {
  259. int width = image->GetWidth();
  260. int height = image->GetHeight();
  261. unsigned levels = image->GetNumCompressedLevels();
  262. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  263. bool needDecompress = false;
  264. if (!format)
  265. {
  266. format = Graphics::GetRGBAFormat();
  267. needDecompress = true;
  268. }
  269. unsigned mipsToSkip = mipsToSkip_[quality];
  270. if (mipsToSkip >= levels)
  271. mipsToSkip = levels - 1;
  272. while (mipsToSkip && (width / (1u << mipsToSkip) < 4 || height / (1u << mipsToSkip) < 4))
  273. --mipsToSkip;
  274. width /= (1u << mipsToSkip);
  275. height /= (1u << mipsToSkip);
  276. // Create the texture array when layer 0 is being loaded, assume rest of the layers are same size & format
  277. if (!layer)
  278. {
  279. SetNumLevels(Max((levels - mipsToSkip), 1U));
  280. SetSize(0, width, height, format);
  281. }
  282. else
  283. {
  284. if (!object_.name_)
  285. {
  286. URHO3D_LOGERROR("Texture array layer 0 must be loaded first");
  287. return false;
  288. }
  289. if (width != width_ || height != height_ || format != format_)
  290. {
  291. URHO3D_LOGERROR("Texture array layer does not match size or format of layer 0");
  292. return false;
  293. }
  294. }
  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(layer, i, 0, 0, level.width_, level.height_, level.data_);
  301. memoryUse += level.rows_ * level.rowSize_;
  302. }
  303. else
  304. {
  305. auto* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  306. level.Decompress(rgbaData);
  307. SetData(layer, i, 0, 0, level.width_, level.height_, rgbaData);
  308. memoryUse += level.width_ * level.height_ * 4;
  309. delete[] rgbaData;
  310. }
  311. }
  312. }
  313. layerMemoryUse_[layer] = memoryUse;
  314. unsigned totalMemoryUse = sizeof(Texture2DArray) + layerMemoryUse_.Capacity() * sizeof(unsigned);
  315. for (unsigned i = 0; i < layers_; ++i)
  316. totalMemoryUse += layerMemoryUse_[i];
  317. SetMemoryUse(totalMemoryUse);
  318. return true;
  319. }
  320. bool Texture2DArray::GetData(unsigned layer, unsigned level, void* dest) const
  321. {
  322. #ifndef GL_ES_VERSION_2_0
  323. if (!object_.name_ || !graphics_)
  324. {
  325. URHO3D_LOGERROR("Texture array not created, can not get data");
  326. return false;
  327. }
  328. if (!dest)
  329. {
  330. URHO3D_LOGERROR("Null destination for getting data");
  331. return false;
  332. }
  333. if (layer != 0)
  334. {
  335. URHO3D_LOGERROR("Only the full download of the array is supported, set layer=0");
  336. return false;
  337. }
  338. if (level >= levels_)
  339. {
  340. URHO3D_LOGERROR("Illegal mip level for getting data");
  341. return false;
  342. }
  343. if (graphics_->IsDeviceLost())
  344. {
  345. URHO3D_LOGWARNING("Getting texture data while device is lost");
  346. return false;
  347. }
  348. graphics_->SetTextureForUpdate(const_cast<Texture2DArray*>(this));
  349. if (!IsCompressed())
  350. glGetTexImage(target_, level, GetExternalFormat(format_), GetDataType(format_), dest);
  351. else
  352. glGetCompressedTexImage(target_, level, dest);
  353. graphics_->SetTexture(0, nullptr);
  354. return true;
  355. #else
  356. URHO3D_LOGERROR("Getting texture data not supported");
  357. return false;
  358. #endif
  359. }
  360. bool Texture2DArray::Create()
  361. {
  362. Release();
  363. #ifdef GL_ES_VERSION_2_0
  364. URHO3D_LOGERROR("Failed to create 2D array texture, currently unsupported on OpenGL ES 2");
  365. return false;
  366. #else
  367. if (!graphics_ || !width_ || !height_ || !layers_)
  368. return false;
  369. if (graphics_->IsDeviceLost())
  370. {
  371. URHO3D_LOGWARNING("Texture array creation while device is lost");
  372. return true;
  373. }
  374. glGenTextures(1, &object_.name_);
  375. // Ensure that our texture is bound to OpenGL texture unit 0
  376. graphics_->SetTextureForUpdate(this);
  377. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  378. unsigned externalFormat = GetExternalFormat(format_);
  379. unsigned dataType = GetDataType(format_);
  380. // If not compressed, create the initial level 0 texture with null data
  381. bool success = true;
  382. if (!IsCompressed())
  383. {
  384. glGetError();
  385. glTexImage3D(target_, 0, format, width_, height_, layers_, 0, externalFormat, dataType, nullptr);
  386. if (glGetError())
  387. success = false;
  388. }
  389. if (!success)
  390. URHO3D_LOGERROR("Failed to create texture array");
  391. // Set mipmapping
  392. if (usage_ == TEXTURE_DEPTHSTENCIL || usage_ == TEXTURE_DYNAMIC)
  393. requestedLevels_ = 1;
  394. else if (usage_ == TEXTURE_RENDERTARGET)
  395. {
  396. #ifdef __EMSCRIPTEN__
  397. // glGenerateMipmap appears to not be working on WebGL, disable rendertarget mipmaps for now
  398. requestedLevels_ = 1;
  399. #else
  400. if (requestedLevels_ != 1)
  401. {
  402. // Generate levels for the first time now
  403. RegenerateLevels();
  404. // Determine max. levels automatically
  405. requestedLevels_ = 0;
  406. }
  407. #endif
  408. }
  409. levels_ = CheckMaxLevels(width_, height_, requestedLevels_);
  410. glTexParameteri(target_, GL_TEXTURE_BASE_LEVEL, 0);
  411. glTexParameteri(target_, GL_TEXTURE_MAX_LEVEL, levels_ - 1);
  412. // Set initial parameters, then unbind the texture
  413. UpdateParameters();
  414. graphics_->SetTexture(0, nullptr);
  415. return success;
  416. #endif
  417. }
  418. }