OGLTextureCube.cpp 16 KB

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