OGLTextureCube.cpp 16 KB

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