OGLTexture2D.cpp 14 KB

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