OGLTextureCube.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Context.h"
  25. #include "FileSystem.h"
  26. #include "Graphics.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. OBJECTTYPESTATIC(TextureCube);
  39. TextureCube::TextureCube(Context* context) :
  40. Texture(context)
  41. {
  42. target_ = GL_TEXTURE_CUBE_MAP;
  43. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  44. faceMemoryUse_[i] = 0;
  45. }
  46. TextureCube::~TextureCube()
  47. {
  48. Release();
  49. }
  50. void TextureCube::RegisterObject(Context* context)
  51. {
  52. context->RegisterFactory<TextureCube>();
  53. }
  54. void TextureCube::OnDeviceLost()
  55. {
  56. savedLevels_.Clear();
  57. // Check if save data is supported, in that case save data of each face and mip level
  58. if (GetDataSize(width_, height_))
  59. {
  60. for (unsigned i = 0; i < levels_; ++i)
  61. {
  62. for (unsigned face = FACE_POSITIVE_X; face < MAX_CUBEMAP_FACES; ++face)
  63. {
  64. int levelWidth = GetLevelWidth(i);
  65. int levelHeight = GetLevelHeight(i);
  66. SharedArrayPtr<unsigned char> savedLevel(new unsigned char[GetDataSize(levelWidth, levelHeight)]);
  67. GetData((CubeMapFace)face, i, savedLevel.Get());
  68. savedLevels_.Push(savedLevel);
  69. }
  70. }
  71. }
  72. Release();
  73. }
  74. void TextureCube::OnDeviceReset()
  75. {
  76. if (!object_)
  77. {
  78. Create();
  79. // Restore texture from save data if it exists
  80. if (savedLevels_.Size())
  81. {
  82. for (unsigned i = 0; i < savedLevels_.Size(); ++i)
  83. {
  84. CubeMapFace face = (CubeMapFace)(i % 6);
  85. unsigned level = i / 6;
  86. int levelWidth = GetLevelWidth(level);
  87. int levelHeight = GetLevelHeight(level);
  88. SetData(face, level, 0, 0, levelWidth, levelHeight, savedLevels_[i].Get());
  89. }
  90. savedLevels_.Clear();
  91. }
  92. }
  93. }
  94. void TextureCube::Release()
  95. {
  96. if (object_)
  97. {
  98. if (!graphics_)
  99. return;
  100. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  101. {
  102. if (graphics_->GetTexture(i) == this)
  103. graphics_->SetTexture(i, 0);
  104. }
  105. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  106. {
  107. if (renderSurfaces_[i])
  108. renderSurfaces_[i]->Release();
  109. }
  110. glDeleteTextures(1, &object_);
  111. object_ = 0;
  112. }
  113. }
  114. bool TextureCube::SetSize(int size, unsigned format, TextureUsage usage)
  115. {
  116. if (size <= 0)
  117. {
  118. LOGERROR("Zero or negative cube texture size");
  119. return false;
  120. }
  121. if (usage == TEXTURE_DEPTHSTENCIL)
  122. {
  123. LOGERROR("Depth-stencil usage not supported for cube maps");
  124. return false;
  125. }
  126. // Delete the old rendersurfaces if any
  127. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  128. {
  129. renderSurfaces_[i].Reset();
  130. faceMemoryUse_[i] = 0;
  131. }
  132. if (usage == TEXTURE_RENDERTARGET)
  133. {
  134. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  135. renderSurfaces_[i] = new RenderSurface(this, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i);
  136. // Clamp mode addressing by default, nearest filtering, and mipmaps disabled
  137. addressMode_[COORD_U] = ADDRESS_CLAMP;
  138. addressMode_[COORD_V] = ADDRESS_CLAMP;
  139. addressMode_[COORD_W] = ADDRESS_CLAMP;
  140. filterMode_ = FILTER_NEAREST;
  141. requestedLevels_ = 1;
  142. dynamic_ = true;
  143. }
  144. else if (usage == TEXTURE_DYNAMIC)
  145. dynamic_ = true;
  146. else
  147. dynamic_ = false;
  148. width_ = size;
  149. height_ = size;
  150. format_ = format;
  151. return Create();
  152. }
  153. bool TextureCube::SetData(CubeMapFace face, unsigned level, int x, int y, int width, int height, const void* data)
  154. {
  155. if (!object_ || !graphics_)
  156. {
  157. LOGERROR("No texture created, can not set data");
  158. return false;
  159. }
  160. if (!data)
  161. {
  162. LOGERROR("Null source for setting data");
  163. return false;
  164. }
  165. if (level >= levels_)
  166. {
  167. LOGERROR("Illegal mip level for setting data");
  168. return false;
  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(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, format_, width, height, 0, GetExternalFormat(format_),
  190. GetDataType(format_), data);
  191. else
  192. glTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, x, y, width, height, GetExternalFormat(format_),
  193. GetDataType(format_), data);
  194. }
  195. else
  196. {
  197. if (wholeLevel)
  198. glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, format_, width, height, 0,
  199. GetDataSize(width, height), data);
  200. else
  201. glCompressedTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, x, y, width, height, format_,
  202. GetDataSize(width, height), data);
  203. }
  204. graphics_->SetTexture(0, 0);
  205. return true;
  206. }
  207. bool TextureCube::Load(Deserializer& source)
  208. {
  209. PROFILE(LoadTextureCube);
  210. ResourceCache* cache = GetSubsystem<ResourceCache>();
  211. // In headless mode, do not actually load the texture, just return success
  212. Graphics* graphics = GetSubsystem<Graphics>();
  213. if (!graphics)
  214. return true;
  215. // If over the texture budget, see if materials can be freed to allow textures to be freed
  216. CheckTextureBudget(GetTypeStatic());
  217. String texPath, texName, texExt;
  218. SplitPath(GetName(), texPath, texName, texExt);
  219. SharedPtr<XMLFile> xml(new XMLFile(context_));
  220. if (!xml->Load(source))
  221. return false;
  222. LoadParameters(xml);
  223. XMLElement textureElem = xml->GetRoot();
  224. XMLElement faceElem = textureElem.GetChild("face");
  225. unsigned faces = 0;
  226. while (faceElem && faces < MAX_CUBEMAP_FACES)
  227. {
  228. String name = faceElem.GetAttribute("name");
  229. String faceTexPath, faceTexName, faceTexExt;
  230. SplitPath(name, faceTexPath, faceTexName, faceTexExt);
  231. // If path is empty, add the XML file path
  232. if (faceTexPath.Empty())
  233. name = texPath + name;
  234. SharedPtr<Image> image(cache->GetResource<Image>(name));
  235. Load((CubeMapFace)faces, image);
  236. faces++;
  237. faceElem = faceElem.GetNext("face");
  238. }
  239. return true;
  240. }
  241. bool TextureCube::Load(CubeMapFace face, Deserializer& source)
  242. {
  243. PROFILE(LoadTextureCube);
  244. SharedPtr<Image> image(new Image(context_));
  245. if (!image->Load(source))
  246. return false;
  247. return Load(face, image);
  248. }
  249. bool TextureCube::Load(CubeMapFace face, SharedPtr<Image> image, bool useAlpha)
  250. {
  251. if (!image)
  252. {
  253. LOGERROR("Null image, can not load texture");
  254. return false;
  255. }
  256. unsigned memoryUse = 0;
  257. int quality = QUALITY_HIGH;
  258. Renderer* renderer = GetSubsystem<Renderer>();
  259. if (renderer)
  260. quality = renderer->GetTextureQuality();
  261. if (!image->IsCompressed())
  262. {
  263. unsigned char* levelData = image->GetData();
  264. int levelWidth = image->GetWidth();
  265. int levelHeight = image->GetHeight();
  266. unsigned components = image->GetComponents();
  267. unsigned format = 0;
  268. if (levelWidth != levelHeight)
  269. {
  270. LOGERROR("Cube texture width not equal to height");
  271. return false;
  272. }
  273. // Discard unnecessary mip levels
  274. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  275. {
  276. image = image->GetNextLevel();
  277. levelWidth = image->GetWidth();
  278. levelHeight = image->GetHeight();
  279. }
  280. switch (components)
  281. {
  282. case 1:
  283. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  284. break;
  285. case 2:
  286. format = Graphics::GetLuminanceAlphaFormat();
  287. break;
  288. case 3:
  289. format = Graphics::GetRGBFormat();
  290. break;
  291. case 4:
  292. format = Graphics::GetRGBAFormat();
  293. break;
  294. }
  295. // Create the texture when face 0 is being loaded, check that rest of the faces are same size & format
  296. if (!face)
  297. SetSize(levelWidth, format);
  298. else
  299. {
  300. if (!object_)
  301. {
  302. LOGERROR("Cube texture face 0 must be loaded first");
  303. return false;
  304. }
  305. if (levelWidth != width_ || format != format_)
  306. {
  307. LOGERROR("Cube texture face does not match size or format of face 0");
  308. return false;
  309. }
  310. }
  311. for (unsigned i = 0; i < levels_; ++i)
  312. {
  313. SetData(face, i, 0, 0, levelWidth, levelHeight, levelData);
  314. memoryUse += levelWidth * levelHeight * components;
  315. if (i < levels_ - 1)
  316. {
  317. image = image->GetNextLevel();
  318. levelData = image->GetData();
  319. levelWidth = image->GetWidth();
  320. levelHeight = image->GetHeight();
  321. }
  322. }
  323. }
  324. else
  325. {
  326. int width = image->GetWidth();
  327. int height = image->GetHeight();
  328. unsigned levels = image->GetNumCompressedLevels();
  329. unsigned format = GetDXTFormat(image->GetCompressedFormat());
  330. bool needDecompress = false;
  331. if (width != height)
  332. {
  333. LOGERROR("Cube texture width not equal to height");
  334. return false;
  335. }
  336. if (!graphics_->GetCompressedTextureSupport() || !format)
  337. {
  338. format = Graphics::GetRGBAFormat();
  339. needDecompress = true;
  340. }
  341. unsigned mipsToSkip = mipsToSkip_[quality];
  342. if (mipsToSkip >= levels)
  343. mipsToSkip = levels - 1;
  344. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4))
  345. --mipsToSkip;
  346. width /= (1 << mipsToSkip);
  347. height /= (1 << mipsToSkip);
  348. // Create the texture when face 0 is being loaded, assume rest of the faces are same size & format
  349. if (!face)
  350. {
  351. SetNumLevels(Max((int)(levels - mipsToSkip), 1));
  352. SetSize(width, format);
  353. }
  354. else
  355. {
  356. if (!object_)
  357. {
  358. LOGERROR("Cube texture face 0 must be loaded first");
  359. return false;
  360. }
  361. if (width != width_ || format != format_)
  362. {
  363. LOGERROR("Cube texture face does not match size or format of face 0");
  364. return false;
  365. }
  366. }
  367. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  368. {
  369. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  370. if (!needDecompress)
  371. {
  372. SetData(face, i, 0, 0, level.width_, level.height_, level.data_);
  373. memoryUse += level.rows_ * level.rowSize_;
  374. }
  375. else
  376. {
  377. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  378. level.Decompress(rgbaData);
  379. SetData(face, i, 0, 0, level.width_, level.height_, rgbaData);
  380. memoryUse += level.width_ * level.height_ * 4;
  381. delete[] rgbaData;
  382. }
  383. }
  384. }
  385. faceMemoryUse_[face] = memoryUse;
  386. unsigned totalMemoryUse = sizeof(TextureCube);
  387. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  388. totalMemoryUse += faceMemoryUse_[i];
  389. SetMemoryUse(totalMemoryUse);
  390. return true;
  391. }
  392. bool TextureCube::GetData(CubeMapFace face, unsigned level, void* dest) const
  393. {
  394. #ifndef GL_ES_VERSION_2_0
  395. if (!object_ || !graphics_)
  396. {
  397. LOGERROR("No texture created, can not get data");
  398. return false;
  399. }
  400. if (!dest)
  401. {
  402. LOGERROR("Null destination for getting data");
  403. return false;
  404. }
  405. if (level >= levels_)
  406. {
  407. LOGERROR("Illegal mip level for getting data");
  408. return false;
  409. }
  410. graphics_->SetTextureForUpdate(const_cast<TextureCube*>(this));
  411. if (!IsCompressed())
  412. glGetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, GetExternalFormat(format_), GetDataType(format_), dest);
  413. else
  414. glGetCompressedTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, dest);
  415. graphics_->SetTexture(0, 0);
  416. return true;
  417. #else
  418. LOGERROR("Get texture data not supported");
  419. return false;
  420. #endif
  421. }
  422. bool TextureCube::Create()
  423. {
  424. Release();
  425. if (!graphics_)
  426. return false;
  427. if (!width_ || !height_)
  428. return false;
  429. glGenTextures(1, &object_);
  430. // Ensure that our texture is bound to OpenGL texture unit 0
  431. graphics_->SetTextureForUpdate(this);
  432. // If not compressed, create the initial level 0 texture with null data
  433. unsigned externalFormat = GetExternalFormat(format_);
  434. unsigned dataType = GetDataType(format_);
  435. bool success = true;
  436. if (!IsCompressed())
  437. {
  438. glGetError();
  439. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  440. {
  441. glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, format_, width_, height_, 0, externalFormat, dataType, 0);
  442. if (glGetError())
  443. success = false;
  444. }
  445. }
  446. if (!success)
  447. LOGERROR("Failed to create texture");
  448. // Set mipmapping
  449. levels_ = requestedLevels_;
  450. if (!levels_)
  451. {
  452. unsigned maxSize = Max((int)width_, (int)height_);
  453. while (maxSize)
  454. {
  455. maxSize >>= 1;
  456. ++levels_;
  457. }
  458. }
  459. #ifndef GL_ES_VERSION_2_0
  460. glTexParameteri(target_, GL_TEXTURE_BASE_LEVEL, 0);
  461. glTexParameteri(target_, GL_TEXTURE_MAX_LEVEL, levels_ - 1);
  462. #endif
  463. // Set initial parameters, then unbind the texture
  464. UpdateParameters();
  465. graphics_->SetTexture(0, 0);
  466. return success;
  467. }