OGLTexture2D.cpp 14 KB

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