OGLTexture3D.cpp 16 KB

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