OGLTexture2D.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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 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 Urho3D
  36. {
  37. Texture2D::Texture2D(Context* context) :
  38. Texture(context)
  39. {
  40. target_ = GL_TEXTURE_2D;
  41. }
  42. Texture2D::~Texture2D()
  43. {
  44. Release();
  45. }
  46. void Texture2D::RegisterObject(Context* context)
  47. {
  48. context->RegisterFactory<Texture2D>();
  49. }
  50. bool Texture2D::BeginLoad(Deserializer& source)
  51. {
  52. // In headless mode, do not actually load the texture, just return success
  53. if (!graphics_)
  54. return true;
  55. // If device is lost, retry later
  56. if (graphics_->IsDeviceLost())
  57. {
  58. LOGWARNING("Texture load while device is lost");
  59. dataPending_ = true;
  60. return true;
  61. }
  62. // Load the image data for EndLoad()
  63. loadImage_ = new Image(context_);
  64. if (!loadImage_->Load(source))
  65. {
  66. loadImage_.Reset();
  67. return false;
  68. }
  69. // Precalculate mip levels if async loading
  70. if (GetAsyncLoadState() == ASYNC_LOADING)
  71. loadImage_->PrecalculateLevels();
  72. // Load the optional parameters file
  73. ResourceCache* cache = GetSubsystem<ResourceCache>();
  74. String xmlName = ReplaceExtension(GetName(), ".xml");
  75. loadParameters_ = cache->GetTempResource<XMLFile>(xmlName, false);
  76. return true;
  77. }
  78. bool Texture2D::EndLoad()
  79. {
  80. // In headless mode, do not actually load the texture, just return success
  81. if (!graphics_ || graphics_->IsDeviceLost())
  82. return true;
  83. // If over the texture budget, see if materials can be freed to allow textures to be freed
  84. CheckTextureBudget(GetTypeStatic());
  85. SetParameters(loadParameters_);
  86. bool success = SetData(loadImage_);
  87. loadImage_.Reset();
  88. loadParameters_.Reset();
  89. return success;
  90. }
  91. void Texture2D::OnDeviceLost()
  92. {
  93. GPUObject::OnDeviceLost();
  94. if (renderSurface_)
  95. renderSurface_->OnDeviceLost();
  96. }
  97. void Texture2D::OnDeviceReset()
  98. {
  99. if (!object_ || dataPending_)
  100. {
  101. // If has a resource file, reload through the resource cache. Otherwise just recreate.
  102. ResourceCache* cache = GetSubsystem<ResourceCache>();
  103. if (cache->Exists(GetName()))
  104. dataLost_ = !cache->ReloadResource(this);
  105. if (!object_)
  106. {
  107. Create();
  108. dataLost_ = true;
  109. }
  110. }
  111. dataPending_ = false;
  112. }
  113. void Texture2D::Release()
  114. {
  115. if (object_)
  116. {
  117. if (!graphics_)
  118. return;
  119. if (!graphics_->IsDeviceLost())
  120. {
  121. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  122. {
  123. if (graphics_->GetTexture(i) == this)
  124. graphics_->SetTexture(i, 0);
  125. }
  126. glDeleteTextures(1, &object_);
  127. }
  128. if (renderSurface_)
  129. renderSurface_->Release();
  130. object_ = 0;
  131. }
  132. else
  133. {
  134. if (renderSurface_)
  135. renderSurface_->Release();
  136. }
  137. }
  138. bool Texture2D::SetSize(int width, int height, unsigned format, TextureUsage usage)
  139. {
  140. // Delete the old rendersurface if any
  141. renderSurface_.Reset();
  142. usage_ = usage;
  143. if (usage >= TEXTURE_RENDERTARGET)
  144. {
  145. renderSurface_ = new RenderSurface(this);
  146. // Clamp mode addressing by default, nearest filtering, and mipmaps disabled
  147. addressMode_[COORD_U] = ADDRESS_CLAMP;
  148. addressMode_[COORD_V] = ADDRESS_CLAMP;
  149. filterMode_ = FILTER_NEAREST;
  150. requestedLevels_ = 1;
  151. }
  152. if (usage == TEXTURE_RENDERTARGET)
  153. SubscribeToEvent(E_RENDERSURFACEUPDATE, URHO3D_HANDLER(Texture2D, HandleRenderSurfaceUpdate));
  154. else
  155. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  156. width_ = width;
  157. height_ = height;
  158. format_ = format;
  159. return Create();
  160. }
  161. bool Texture2D::SetData(unsigned level, int x, int y, int width, int height, const void* data)
  162. {
  163. PROFILE(SetTextureData);
  164. if (!object_ || !graphics_)
  165. {
  166. LOGERROR("No texture created, can not set data");
  167. return false;
  168. }
  169. if (!data)
  170. {
  171. LOGERROR("Null source for setting data");
  172. return false;
  173. }
  174. if (level >= levels_)
  175. {
  176. LOGERROR("Illegal mip level for setting data");
  177. return false;
  178. }
  179. if (graphics_->IsDeviceLost())
  180. {
  181. LOGWARNING("Texture data assignment while device is lost");
  182. dataPending_ = true;
  183. return true;
  184. }
  185. if (IsCompressed())
  186. {
  187. x &= ~3;
  188. y &= ~3;
  189. }
  190. int levelWidth = GetLevelWidth(level);
  191. int levelHeight = GetLevelHeight(level);
  192. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  193. {
  194. LOGERROR("Illegal dimensions for setting data");
  195. return false;
  196. }
  197. graphics_->SetTextureForUpdate(this);
  198. bool wholeLevel = x == 0 && y == 0 && width == levelWidth && height == levelHeight;
  199. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  200. if (!IsCompressed())
  201. {
  202. if (wholeLevel)
  203. glTexImage2D(target_, level, format, width, height, 0, GetExternalFormat(format_), GetDataType(format_), data);
  204. else
  205. glTexSubImage2D(target_, level, x, y, width, height, GetExternalFormat(format_), GetDataType(format_), data);
  206. }
  207. else
  208. {
  209. if (wholeLevel)
  210. glCompressedTexImage2D(target_, level, format, width, height, 0, GetDataSize(width, height), data);
  211. else
  212. glCompressedTexSubImage2D(target_, level, x, y, width, height, format, GetDataSize(width, height), data);
  213. }
  214. graphics_->SetTexture(0, 0);
  215. return true;
  216. }
  217. bool Texture2D::SetData(SharedPtr<Image> image, bool useAlpha)
  218. {
  219. if (!image)
  220. {
  221. LOGERROR("Null image, can not set data");
  222. return false;
  223. }
  224. unsigned memoryUse = sizeof(Texture2D);
  225. int quality = QUALITY_HIGH;
  226. Renderer* renderer = GetSubsystem<Renderer>();
  227. if (renderer)
  228. quality = renderer->GetTextureQuality();
  229. if (!image->IsCompressed())
  230. {
  231. // Convert unsuitable formats to RGBA
  232. unsigned components = image->GetComponents();
  233. if (Graphics::GetGL3Support() && ((components == 1 && !useAlpha) || components == 2))
  234. {
  235. image = image->ConvertToRGBA();
  236. if (!image)
  237. return false;
  238. components = image->GetComponents();
  239. }
  240. unsigned char* levelData = image->GetData();
  241. int levelWidth = image->GetWidth();
  242. int levelHeight = image->GetHeight();
  243. unsigned format = 0;
  244. // Discard unnecessary mip levels
  245. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  246. {
  247. image = image->GetNextLevel();
  248. levelData = image->GetData();
  249. levelWidth = image->GetWidth();
  250. levelHeight = image->GetHeight();
  251. }
  252. switch (components)
  253. {
  254. case 1:
  255. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  256. break;
  257. case 2:
  258. format = Graphics::GetLuminanceAlphaFormat();
  259. break;
  260. case 3:
  261. format = Graphics::GetRGBFormat();
  262. break;
  263. case 4:
  264. format = Graphics::GetRGBAFormat();
  265. break;
  266. default:
  267. assert(false); // Should not reach here
  268. break;
  269. }
  270. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  271. if (IsCompressed() && requestedLevels_ > 1)
  272. requestedLevels_ = 0;
  273. SetSize(levelWidth, levelHeight, format);
  274. if (!object_)
  275. return false;
  276. for (unsigned i = 0; i < levels_; ++i)
  277. {
  278. SetData(i, 0, 0, levelWidth, levelHeight, levelData);
  279. memoryUse += levelWidth * levelHeight * components;
  280. if (i < levels_ - 1)
  281. {
  282. image = image->GetNextLevel();
  283. levelData = image->GetData();
  284. levelWidth = image->GetWidth();
  285. levelHeight = image->GetHeight();
  286. }
  287. }
  288. }
  289. else
  290. {
  291. int width = image->GetWidth();
  292. int height = image->GetHeight();
  293. unsigned levels = image->GetNumCompressedLevels();
  294. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  295. bool needDecompress = false;
  296. if (!format)
  297. {
  298. format = Graphics::GetRGBAFormat();
  299. needDecompress = true;
  300. }
  301. unsigned mipsToSkip = mipsToSkip_[quality];
  302. if (mipsToSkip >= levels)
  303. mipsToSkip = levels - 1;
  304. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4))
  305. --mipsToSkip;
  306. width /= (1 << mipsToSkip);
  307. height /= (1 << mipsToSkip);
  308. SetNumLevels((unsigned)Max((int)(levels - mipsToSkip), 1));
  309. SetSize(width, height, format);
  310. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  311. {
  312. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  313. if (!needDecompress)
  314. {
  315. SetData(i, 0, 0, level.width_, level.height_, level.data_);
  316. memoryUse += level.rows_ * level.rowSize_;
  317. }
  318. else
  319. {
  320. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  321. level.Decompress(rgbaData);
  322. SetData(i, 0, 0, level.width_, level.height_, rgbaData);
  323. memoryUse += level.width_ * level.height_ * 4;
  324. delete[] rgbaData;
  325. }
  326. }
  327. }
  328. SetMemoryUse(memoryUse);
  329. return true;
  330. }
  331. bool Texture2D::GetData(unsigned level, void* dest) const
  332. {
  333. #ifndef GL_ES_VERSION_2_0
  334. if (!object_ || !graphics_)
  335. {
  336. LOGERROR("No texture created, can not get data");
  337. return false;
  338. }
  339. if (!dest)
  340. {
  341. LOGERROR("Null destination for getting data");
  342. return false;
  343. }
  344. if (level >= levels_)
  345. {
  346. LOGERROR("Illegal mip level for getting data");
  347. return false;
  348. }
  349. if (graphics_->IsDeviceLost())
  350. {
  351. LOGWARNING("Getting texture data while device is lost");
  352. return false;
  353. }
  354. graphics_->SetTextureForUpdate(const_cast<Texture2D*>(this));
  355. if (!IsCompressed())
  356. glGetTexImage(target_, level, GetExternalFormat(format_), GetDataType(format_), dest);
  357. else
  358. glGetCompressedTexImage(target_, level, dest);
  359. graphics_->SetTexture(0, 0);
  360. return true;
  361. #else
  362. LOGERROR("Getting texture data not supported");
  363. return false;
  364. #endif
  365. }
  366. bool Texture2D::Create()
  367. {
  368. Release();
  369. if (!graphics_ || !width_ || !height_)
  370. return false;
  371. if (graphics_->IsDeviceLost())
  372. {
  373. LOGWARNING("Texture creation while device is lost");
  374. return true;
  375. }
  376. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  377. unsigned externalFormat = GetExternalFormat(format_);
  378. unsigned dataType = GetDataType(format_);
  379. // Create a renderbuffer instead of a texture if depth texture is not properly supported, or if this will be a packed
  380. // depth stencil texture
  381. #ifndef GL_ES_VERSION_2_0
  382. if (format == Graphics::GetDepthStencilFormat())
  383. #else
  384. if (format == GL_DEPTH_COMPONENT16 || format == GL_DEPTH_COMPONENT24_OES || format == GL_DEPTH24_STENCIL8_OES ||
  385. (format == GL_DEPTH_COMPONENT && !graphics_->GetShadowMapFormat()))
  386. #endif
  387. {
  388. if (renderSurface_)
  389. {
  390. renderSurface_->CreateRenderBuffer(width_, height_, format);
  391. return true;
  392. }
  393. else
  394. return false;
  395. }
  396. glGenTextures(1, &object_);
  397. // Ensure that our texture is bound to OpenGL texture unit 0
  398. graphics_->SetTextureForUpdate(this);
  399. // If not compressed, create the initial level 0 texture with null data
  400. bool success = true;
  401. if (!IsCompressed())
  402. {
  403. glGetError();
  404. glTexImage2D(target_, 0, format, width_, height_, 0, externalFormat, dataType, 0);
  405. if (glGetError())
  406. {
  407. LOGERROR("Failed to create texture");
  408. success = false;
  409. }
  410. }
  411. // Set mipmapping
  412. levels_ = requestedLevels_;
  413. if (!levels_)
  414. {
  415. unsigned maxSize = Max((int)width_, (int)height_);
  416. while (maxSize)
  417. {
  418. maxSize >>= 1;
  419. ++levels_;
  420. }
  421. }
  422. #ifndef GL_ES_VERSION_2_0
  423. glTexParameteri(target_, GL_TEXTURE_BASE_LEVEL, 0);
  424. glTexParameteri(target_, GL_TEXTURE_MAX_LEVEL, levels_ - 1);
  425. #endif
  426. // Set initial parameters, then unbind the texture
  427. UpdateParameters();
  428. graphics_->SetTexture(0, 0);
  429. return success;
  430. }
  431. void Texture2D::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  432. {
  433. if (renderSurface_ && renderSurface_->GetUpdateMode() == SURFACE_UPDATEALWAYS)
  434. renderSurface_->QueueUpdate();
  435. }
  436. }