OGLTexture3D.cpp 16 KB

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