OGLTextureCube.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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 "FileSystem.h"
  25. #include "Graphics.h"
  26. #include "GraphicsEvents.h"
  27. #include "GraphicsImpl.h"
  28. #include "Log.h"
  29. #include "Profiler.h"
  30. #include "Renderer.h"
  31. #include "ResourceCache.h"
  32. #include "TextureCube.h"
  33. #include "XMLFile.h"
  34. #include "DebugNew.h"
  35. #ifdef _MSC_VER
  36. #pragma warning(disable:4355)
  37. #endif
  38. namespace Urho3D
  39. {
  40. TextureCube::TextureCube(Context* context) :
  41. Texture(context)
  42. {
  43. target_ = GL_TEXTURE_CUBE_MAP;
  44. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  45. faceMemoryUse_[i] = 0;
  46. }
  47. TextureCube::~TextureCube()
  48. {
  49. Release();
  50. }
  51. void TextureCube::RegisterObject(Context* context)
  52. {
  53. context->RegisterFactory<TextureCube>();
  54. }
  55. void TextureCube::OnDeviceLost()
  56. {
  57. GPUObject::OnDeviceLost();
  58. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  59. {
  60. if (renderSurfaces_[i])
  61. renderSurfaces_[i]->OnDeviceLost();
  62. }
  63. }
  64. void TextureCube::OnDeviceReset()
  65. {
  66. // If has a file name, reload through the resource cache. Otherwise just recreate.
  67. if (!object_)
  68. {
  69. if (!GetName().Trimmed().Empty())
  70. dataLost_ = !GetSubsystem<ResourceCache>()->ReloadResource(this);
  71. else
  72. {
  73. Create();
  74. dataLost_ = true;
  75. }
  76. }
  77. else if (dataPending_)
  78. {
  79. if (!GetName().Trimmed().Empty())
  80. dataLost_ = !GetSubsystem<ResourceCache>()->ReloadResource(this);
  81. else
  82. dataLost_ = true;
  83. }
  84. dataPending_ = false;
  85. }
  86. void TextureCube::Release()
  87. {
  88. if (object_)
  89. {
  90. if (!graphics_ || graphics_->IsDeviceLost())
  91. return;
  92. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  93. {
  94. if (graphics_->GetTexture(i) == this)
  95. graphics_->SetTexture(i, 0);
  96. }
  97. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  98. {
  99. if (renderSurfaces_[i])
  100. renderSurfaces_[i]->Release();
  101. }
  102. glDeleteTextures(1, &object_);
  103. object_ = 0;
  104. }
  105. }
  106. bool TextureCube::SetSize(int size, unsigned format, TextureUsage usage)
  107. {
  108. if (size <= 0)
  109. {
  110. LOGERROR("Zero or negative cube texture size");
  111. return false;
  112. }
  113. if (usage == TEXTURE_DEPTHSTENCIL)
  114. {
  115. LOGERROR("Depth-stencil usage not supported for cube maps");
  116. return false;
  117. }
  118. // Delete the old rendersurfaces if any
  119. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  120. {
  121. renderSurfaces_[i].Reset();
  122. faceMemoryUse_[i] = 0;
  123. }
  124. usage_ = usage;
  125. if (usage == TEXTURE_RENDERTARGET)
  126. {
  127. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  128. renderSurfaces_[i] = new RenderSurface(this, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i);
  129. // Clamp mode addressing by default, nearest filtering, and mipmaps disabled
  130. addressMode_[COORD_U] = ADDRESS_CLAMP;
  131. addressMode_[COORD_V] = ADDRESS_CLAMP;
  132. addressMode_[COORD_W] = ADDRESS_CLAMP;
  133. filterMode_ = FILTER_NEAREST;
  134. requestedLevels_ = 1;
  135. }
  136. if (usage == TEXTURE_RENDERTARGET)
  137. SubscribeToEvent(E_RENDERSURFACEUPDATE, HANDLER(TextureCube, HandleRenderSurfaceUpdate));
  138. else
  139. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  140. width_ = size;
  141. height_ = size;
  142. format_ = format;
  143. return Create();
  144. }
  145. bool TextureCube::SetData(CubeMapFace face, unsigned level, int x, int y, int width, int height, const void* data)
  146. {
  147. if (!object_ || !graphics_)
  148. {
  149. LOGERROR("No texture created, can not set data");
  150. return false;
  151. }
  152. if (!data)
  153. {
  154. LOGERROR("Null source for setting data");
  155. return false;
  156. }
  157. if (level >= levels_)
  158. {
  159. LOGERROR("Illegal mip level for setting data");
  160. return false;
  161. }
  162. if (graphics_->IsDeviceLost())
  163. {
  164. LOGWARNING("Texture data assignment while device is lost");
  165. dataPending_ = true;
  166. return true;
  167. }
  168. if (IsCompressed())
  169. {
  170. x &= ~3;
  171. y &= ~3;
  172. }
  173. int levelWidth = GetLevelWidth(level);
  174. int levelHeight = GetLevelHeight(level);
  175. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  176. {
  177. LOGERROR("Illegal dimensions for setting data");
  178. return false;
  179. }
  180. bool wholeLevel = x == 0 && y == 0 && width == levelWidth && height == levelHeight;
  181. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  182. y = levelHeight - (y + height);
  183. graphics_->SetTextureForUpdate(this);
  184. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  185. if (!IsCompressed())
  186. {
  187. if (wholeLevel)
  188. glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, format, width, height, 0, GetExternalFormat(format_),
  189. GetDataType(format_), data);
  190. else
  191. glTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, x, y, width, height, GetExternalFormat(format_),
  192. GetDataType(format_), data);
  193. }
  194. else
  195. {
  196. if (wholeLevel)
  197. glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, format, width, height, 0,
  198. GetDataSize(width, height), data);
  199. else
  200. glCompressedTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, x, y, width, height, format,
  201. GetDataSize(width, height), data);
  202. }
  203. graphics_->SetTexture(0, 0);
  204. return true;
  205. }
  206. bool TextureCube::Load(Deserializer& source)
  207. {
  208. PROFILE(LoadTextureCube);
  209. ResourceCache* cache = GetSubsystem<ResourceCache>();
  210. // In headless mode, do not actually load the texture, just return success
  211. Graphics* graphics = GetSubsystem<Graphics>();
  212. if (!graphics)
  213. return true;
  214. // If device is lost, retry later
  215. if (graphics_->IsDeviceLost())
  216. {
  217. LOGWARNING("Texture load while device is lost");
  218. dataPending_ = true;
  219. return true;
  220. }
  221. // If over the texture budget, see if materials can be freed to allow textures to be freed
  222. CheckTextureBudget(GetTypeStatic());
  223. String texPath, texName, texExt;
  224. SplitPath(GetName(), texPath, texName, texExt);
  225. SharedPtr<XMLFile> xml(new XMLFile(context_));
  226. if (!xml->Load(source))
  227. return false;
  228. LoadParameters(xml);
  229. XMLElement textureElem = xml->GetRoot();
  230. XMLElement faceElem = textureElem.GetChild("face");
  231. unsigned faces = 0;
  232. while (faceElem && faces < MAX_CUBEMAP_FACES)
  233. {
  234. String name = faceElem.GetAttribute("name");
  235. String faceTexPath, faceTexName, faceTexExt;
  236. SplitPath(name, faceTexPath, faceTexName, faceTexExt);
  237. // If path is empty, add the XML file path
  238. if (faceTexPath.Empty())
  239. name = texPath + name;
  240. SharedPtr<Image> image(cache->GetResource<Image>(name));
  241. Load((CubeMapFace)faces, image);
  242. ++faces;
  243. faceElem = faceElem.GetNext("face");
  244. }
  245. return true;
  246. }
  247. bool TextureCube::Load(CubeMapFace face, Deserializer& source)
  248. {
  249. PROFILE(LoadTextureCube);
  250. SharedPtr<Image> image(new Image(context_));
  251. if (!image->Load(source))
  252. return false;
  253. return Load(face, image);
  254. }
  255. bool TextureCube::Load(CubeMapFace face, SharedPtr<Image> image, bool useAlpha)
  256. {
  257. if (!image)
  258. {
  259. LOGERROR("Null image, can not load texture");
  260. return false;
  261. }
  262. unsigned memoryUse = 0;
  263. int quality = QUALITY_HIGH;
  264. Renderer* renderer = GetSubsystem<Renderer>();
  265. if (renderer)
  266. quality = renderer->GetTextureQuality();
  267. if (!image->IsCompressed())
  268. {
  269. unsigned char* levelData = image->GetData();
  270. int levelWidth = image->GetWidth();
  271. int levelHeight = image->GetHeight();
  272. unsigned components = image->GetComponents();
  273. unsigned format = 0;
  274. if (levelWidth != levelHeight)
  275. {
  276. LOGERROR("Cube texture width not equal to height");
  277. return false;
  278. }
  279. // Discard unnecessary mip levels
  280. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  281. {
  282. image = image->GetNextLevel();
  283. levelData = image->GetData();
  284. levelWidth = image->GetWidth();
  285. levelHeight = image->GetHeight();
  286. }
  287. switch (components)
  288. {
  289. case 1:
  290. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  291. break;
  292. case 2:
  293. format = Graphics::GetLuminanceAlphaFormat();
  294. break;
  295. case 3:
  296. format = Graphics::GetRGBFormat();
  297. break;
  298. case 4:
  299. format = Graphics::GetRGBAFormat();
  300. break;
  301. }
  302. // Create the texture when face 0 is being loaded, check that rest of the faces are same size & format
  303. if (!face)
  304. SetSize(levelWidth, format);
  305. else
  306. {
  307. if (!object_)
  308. {
  309. LOGERROR("Cube texture face 0 must be loaded first");
  310. return false;
  311. }
  312. if (levelWidth != width_ || format != format_)
  313. {
  314. LOGERROR("Cube texture face does not match size or format of face 0");
  315. return false;
  316. }
  317. }
  318. for (unsigned i = 0; i < levels_; ++i)
  319. {
  320. SetData(face, i, 0, 0, levelWidth, levelHeight, levelData);
  321. memoryUse += levelWidth * levelHeight * components;
  322. if (i < levels_ - 1)
  323. {
  324. image = image->GetNextLevel();
  325. levelData = image->GetData();
  326. levelWidth = image->GetWidth();
  327. levelHeight = image->GetHeight();
  328. }
  329. }
  330. }
  331. else
  332. {
  333. int width = image->GetWidth();
  334. int height = image->GetHeight();
  335. unsigned levels = image->GetNumCompressedLevels();
  336. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  337. bool needDecompress = false;
  338. if (width != height)
  339. {
  340. LOGERROR("Cube texture width not equal to height");
  341. return false;
  342. }
  343. if (!format)
  344. {
  345. format = Graphics::GetRGBAFormat();
  346. needDecompress = true;
  347. }
  348. unsigned mipsToSkip = mipsToSkip_[quality];
  349. if (mipsToSkip >= levels)
  350. mipsToSkip = levels - 1;
  351. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4))
  352. --mipsToSkip;
  353. width /= (1 << mipsToSkip);
  354. height /= (1 << mipsToSkip);
  355. // Create the texture when face 0 is being loaded, assume rest of the faces are same size & format
  356. if (!face)
  357. {
  358. SetNumLevels(Max((int)(levels - mipsToSkip), 1));
  359. SetSize(width, format);
  360. }
  361. else
  362. {
  363. if (!object_)
  364. {
  365. LOGERROR("Cube texture face 0 must be loaded first");
  366. return false;
  367. }
  368. if (width != width_ || format != format_)
  369. {
  370. LOGERROR("Cube texture face does not match size or format of face 0");
  371. return false;
  372. }
  373. }
  374. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  375. {
  376. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  377. if (!needDecompress)
  378. {
  379. SetData(face, i, 0, 0, level.width_, level.height_, level.data_);
  380. memoryUse += level.rows_ * level.rowSize_;
  381. }
  382. else
  383. {
  384. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  385. level.Decompress(rgbaData);
  386. SetData(face, i, 0, 0, level.width_, level.height_, rgbaData);
  387. memoryUse += level.width_ * level.height_ * 4;
  388. delete[] rgbaData;
  389. }
  390. }
  391. }
  392. faceMemoryUse_[face] = memoryUse;
  393. unsigned totalMemoryUse = sizeof(TextureCube);
  394. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  395. totalMemoryUse += faceMemoryUse_[i];
  396. SetMemoryUse(totalMemoryUse);
  397. return true;
  398. }
  399. bool TextureCube::GetData(CubeMapFace face, unsigned level, void* dest) const
  400. {
  401. #ifndef GL_ES_VERSION_2_0
  402. if (!object_ || !graphics_)
  403. {
  404. LOGERROR("No texture created, can not get data");
  405. return false;
  406. }
  407. if (!dest)
  408. {
  409. LOGERROR("Null destination for getting data");
  410. return false;
  411. }
  412. if (level >= levels_)
  413. {
  414. LOGERROR("Illegal mip level for getting data");
  415. return false;
  416. }
  417. if (graphics_->IsDeviceLost())
  418. {
  419. LOGWARNING("Getting texture data while device is lost");
  420. return false;
  421. }
  422. graphics_->SetTextureForUpdate(const_cast<TextureCube*>(this));
  423. if (!IsCompressed())
  424. glGetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, GetExternalFormat(format_), GetDataType(format_), dest);
  425. else
  426. glGetCompressedTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, dest);
  427. graphics_->SetTexture(0, 0);
  428. return true;
  429. #else
  430. LOGERROR("Getting texture data not supported");
  431. return false;
  432. #endif
  433. }
  434. bool TextureCube::Create()
  435. {
  436. Release();
  437. if (!graphics_ || !width_ || !height_)
  438. return false;
  439. if (graphics_->IsDeviceLost())
  440. {
  441. LOGWARNING("Texture creation while device is lost");
  442. return true;
  443. }
  444. glGenTextures(1, &object_);
  445. // Ensure that our texture is bound to OpenGL texture unit 0
  446. graphics_->SetTextureForUpdate(this);
  447. // If not compressed, create the initial level 0 texture with null data
  448. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  449. unsigned externalFormat = GetExternalFormat(format_);
  450. unsigned dataType = GetDataType(format_);
  451. bool success = true;
  452. if (!IsCompressed())
  453. {
  454. glGetError();
  455. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  456. {
  457. glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, format, width_, height_, 0, externalFormat, dataType, 0);
  458. if (glGetError())
  459. success = false;
  460. }
  461. }
  462. if (!success)
  463. LOGERROR("Failed to create texture");
  464. // Set mipmapping
  465. levels_ = requestedLevels_;
  466. if (!levels_)
  467. {
  468. unsigned maxSize = Max((int)width_, (int)height_);
  469. while (maxSize)
  470. {
  471. maxSize >>= 1;
  472. ++levels_;
  473. }
  474. }
  475. #ifndef GL_ES_VERSION_2_0
  476. glTexParameteri(target_, GL_TEXTURE_BASE_LEVEL, 0);
  477. glTexParameteri(target_, GL_TEXTURE_MAX_LEVEL, levels_ - 1);
  478. #endif
  479. // Set initial parameters, then unbind the texture
  480. UpdateParameters();
  481. graphics_->SetTexture(0, 0);
  482. return success;
  483. }
  484. void TextureCube::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  485. {
  486. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  487. {
  488. if (renderSurfaces_[i] && renderSurfaces_[i]->GetUpdateMode() == SURFACE_UPDATEALWAYS)
  489. renderSurfaces_[i]->QueueUpdate();
  490. }
  491. }
  492. }