OGLTexture2D.cpp 15 KB

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