OGLTextureCube.cpp 17 KB

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