TextureManager.cc 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 GarageGames, LLC
  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
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell 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
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "graphics/TextureManager.h"
  23. #include "platform/platformAssert.h"
  24. #include "platform/platformGL.h"
  25. #include "platform/platform.h"
  26. #include "collection/vector.h"
  27. #include "io/resource/resourceManager.h"
  28. #include "graphics/gBitmap.h"
  29. #include "console/console.h"
  30. #include "console/consoleInternal.h"
  31. #include "console/consoleTypes.h"
  32. #include "memory/safeDelete.h"
  33. #include "math/mMath.h"
  34. #include "TextureManager_ScriptBinding.h"
  35. //---------------------------------------------------------------------------------------------------------------------
  36. S32 TextureManager::mMasterTextureKeyIndex = 0;
  37. TextureManager::ManagerState TextureManager::mManagerState = TextureManager::NotInitialized;
  38. bool TextureManager::mDGLRender = true;
  39. bool TextureManager::mForce16BitTexture = false;
  40. bool TextureManager::mAllowTextureCompression = false;
  41. bool TextureManager::mDisableTextureSubImageUpdates = false;
  42. GLenum TextureManager::mTextureCompressionHint = GL_FASTEST;
  43. S32 TextureManager::mBitmapResidentSize = 0;
  44. S32 TextureManager::mTextureResidentSize = 0;
  45. S32 TextureManager::mTextureResidentWasteSize = 0;
  46. S32 TextureManager::mTextureResidentCount = 0;
  47. //---------------------------------------------------------------------------------------------------------------------
  48. #ifdef TORQUE_OS_IOS
  49. #define EXT_ARRAY_SIZE 4
  50. static const char* extArray[EXT_ARRAY_SIZE] = { "", ".pvr", ".jpg", ".png"};
  51. #else
  52. struct Forced16BitMapping
  53. {
  54. GLenum wanted;
  55. GLenum forced;
  56. bool end;
  57. };
  58. Forced16BitMapping sg16BitMappings[] =
  59. {
  60. { GL_RGB, GL_RGB5, false },
  61. { GL_RGBA, GL_RGBA4, false },
  62. { 0, 0, true }
  63. };
  64. #define EXT_ARRAY_SIZE 3
  65. static const char* extArray[EXT_ARRAY_SIZE] = { "", ".jpg", ".png"};
  66. #endif
  67. //---------------------------------------------------------------------------------------------------------------------
  68. struct EventCallbackEntry
  69. {
  70. TextureManager::TextureEventCallback callback;
  71. void * userData;
  72. U32 key;
  73. };
  74. static U32 sgCurrCallbackKey = 0;
  75. static Vector<EventCallbackEntry> sgEventCallbacks(__FILE__, __LINE__);
  76. //--------------------------------------------------------------------------------------------------------------------
  77. U32 TextureManager::registerEventCallback(TextureEventCallback callback, void *userData)
  78. {
  79. sgEventCallbacks.increment();
  80. sgEventCallbacks.last().callback = callback;
  81. sgEventCallbacks.last().userData = userData;
  82. sgEventCallbacks.last().key = sgCurrCallbackKey++;
  83. return sgEventCallbacks.last().key;
  84. }
  85. //--------------------------------------------------------------------------------------------------------------------
  86. void TextureManager::unregisterEventCallback(const U32 callbackKey)
  87. {
  88. for (S32 i = 0; i < sgEventCallbacks.size(); i++)
  89. {
  90. if (sgEventCallbacks[i].key == callbackKey)
  91. {
  92. sgEventCallbacks.erase(i);
  93. return;
  94. }
  95. }
  96. }
  97. //--------------------------------------------------------------------------------------------------------------------
  98. void TextureManager::postTextureEvent(const TextureEventCode eventCode)
  99. {
  100. for (S32 i = 0; i < sgEventCallbacks.size(); i++)
  101. {
  102. (sgEventCallbacks[i].callback)(eventCode, sgEventCallbacks[i].userData);
  103. }
  104. }
  105. //--------------------------------------------------------------------------------------------------------------------
  106. U8 *getLuminanceAlphaBits(GBitmap *bmp)
  107. {
  108. U8 *data = new U8[bmp->getWidth() * bmp->getHeight() * 2];
  109. S32 w = bmp->getWidth();
  110. S32 h = bmp->getHeight();
  111. U8 *src = bmp->getAddress(0, 0);
  112. U8 *dest = data;
  113. for (int y=0; y<h; y++)
  114. {
  115. for (int x=0; x<w; x++)
  116. {
  117. *dest++ = 255;
  118. *dest++ = *src++;
  119. }
  120. }
  121. return data;
  122. }
  123. //--------------------------------------------------------------------------------------------------------------------
  124. void TextureManager::create()
  125. {
  126. AssertISV(mManagerState == NotInitialized, "TextureManager::create() - already created!");
  127. TextureDictionary::create();
  128. Con::addVariable("$pref::OpenGL::force16BitTexture", TypeBool, &TextureManager::mForce16BitTexture);
  129. Con::addVariable("$pref::OpenGL::allowTextureCompression", TypeBool, &TextureManager::mAllowTextureCompression);
  130. Con::addVariable("$pref::OpenGL::disableTextureSubImageUpdates", TypeBool, &TextureManager::mDisableTextureSubImageUpdates);
  131. // Flag as alive.
  132. mManagerState = Alive;
  133. }
  134. //--------------------------------------------------------------------------------------------------------------------
  135. void TextureManager::destroy()
  136. {
  137. AssertISV(mManagerState != NotInitialized, "TextureManager::destroy - nothing to destroy!");
  138. // Destroy the texture dictionary.
  139. TextureDictionary::destroy();
  140. // Reset state.
  141. mBitmapResidentSize = 0;
  142. mTextureResidentSize = 0;
  143. mTextureResidentWasteSize = 0;
  144. mTextureResidentCount = 0;
  145. mMasterTextureKeyIndex = 0;
  146. // Flag as not initialized.
  147. mManagerState = NotInitialized;
  148. }
  149. //--------------------------------------------------------------------------------------------------------------------
  150. void TextureManager::killManager()
  151. {
  152. // Finish if already dead.
  153. if ( mManagerState == Dead )
  154. return;
  155. // Flag as dead.
  156. mManagerState = Dead;
  157. // Post zombie event.
  158. postTextureEvent(BeginZombification);
  159. Vector<GLuint> deleteNames(4096);
  160. TextureObject* probe = TextureDictionary::TextureObjectChain;
  161. while (probe)
  162. {
  163. if (probe->mGLTextureName != 0)
  164. {
  165. deleteNames.push_back(probe->mGLTextureName);
  166. }
  167. probe->mGLTextureName = 0;
  168. // Adjust metrics.
  169. mTextureResidentCount--;
  170. mTextureResidentSize -= probe->mTextureResidentSize;
  171. probe->mTextureResidentSize = 0;
  172. mTextureResidentWasteSize -= probe->mTextureResidentWasteSize;
  173. probe->mTextureResidentWasteSize = 0;
  174. probe = probe->next;
  175. }
  176. // Delete all textures.
  177. glDeleteTextures(deleteNames.size(), deleteNames.address());
  178. }
  179. //--------------------------------------------------------------------------------------------------------------------
  180. void TextureManager::resurrectManager( void )
  181. {
  182. // Finish if not dead.
  183. if (mManagerState != Dead)
  184. return;
  185. // Flag as resurrecting.
  186. mManagerState = Resurrecting;
  187. // Post begin resurrection event.
  188. postTextureEvent(BeginResurrection);
  189. // Resurrect textures.
  190. TextureObject* probe = TextureDictionary::TextureObjectChain;
  191. while (probe)
  192. {
  193. switch( probe->mHandleType )
  194. {
  195. case TextureHandle::BitmapTexture:
  196. {
  197. // Sanity!
  198. AssertISV( probe->mTextureKey != NULL && probe->mTextureKey != StringTable->EmptyString, "Encountered a bitmap texture that didn't specify its bitmap." );
  199. // Load the bitmap.
  200. GBitmap* pBitmap = loadBitmap( probe->mTextureKey );
  201. // Sanity!
  202. AssertISV(pBitmap != NULL, "Error resurrecting the texture cache.\n""Possible cause: a bitmap was deleted during the course of gameplay.");
  203. // Register texture.
  204. TextureObject* pTextureObject;
  205. pTextureObject = registerTexture(probe->mTextureKey, pBitmap, probe->mHandleType, probe->mClamp);
  206. // Sanity!
  207. AssertFatal(pTextureObject == probe, "A new texture was returned during resurrection.");
  208. } break;
  209. case TextureHandle::BitmapKeepTexture:
  210. {
  211. // Sanity!
  212. AssertISV( probe->mpBitmap != NULL, "Encountered no bitmap for a texture that should keep it." );
  213. // Create texture.
  214. createGLName(probe);
  215. } break;
  216. default:
  217. // Sanity!
  218. AssertISV( false, "Unknown texture type encountered during texture resurrection." );
  219. }
  220. // Next texture.
  221. probe = probe->next;
  222. }
  223. // Post end resurrection event.
  224. postTextureEvent(EndResurrection);
  225. // Flag as alive.
  226. mManagerState = Alive;
  227. }
  228. //--------------------------------------------------------------------------------------------------------------------
  229. void TextureManager::flush()
  230. {
  231. killManager();
  232. resurrectManager();
  233. }
  234. //--------------------------------------------------------------------------------------------------------------------
  235. StringTableEntry TextureManager::getUniqueTextureKey( void )
  236. {
  237. char textureKeyBuffer[32];
  238. dSprintf( textureKeyBuffer, sizeof(textureKeyBuffer), "GeneratedKey_%d", mMasterTextureKeyIndex++ );
  239. return StringTable->insert( textureKeyBuffer );
  240. }
  241. //--------------------------------------------------------------------------------------------------------------------
  242. GBitmap* TextureManager::createPowerOfTwoBitmap(GBitmap* pBitmap)
  243. {
  244. // Sanity!
  245. AssertISV( pBitmap->getFormat() != GBitmap::Palettized, "Paletted bitmaps are not supported." );
  246. // Finish if already a power-of-two in dimension.
  247. if (isPow2(pBitmap->getWidth()) && isPow2(pBitmap->getHeight()))
  248. return pBitmap;
  249. U32 width = pBitmap->getWidth();
  250. U32 height = pBitmap->getHeight();
  251. U32 newWidth = getNextPow2(pBitmap->getWidth());
  252. U32 newHeight = getNextPow2(pBitmap->getHeight());
  253. GBitmap* pReturn = new GBitmap(newWidth, newHeight, false, pBitmap->getFormat());
  254. for (U32 i = 0; i < height; i++)
  255. {
  256. U8* pDest = (U8*)pReturn->getAddress(0, i);
  257. const U8* pSrc = (const U8*)pBitmap->getAddress(0, i);
  258. dMemcpy(pDest, pSrc, width * pBitmap->bytesPerPixel);
  259. pDest += width * pBitmap->bytesPerPixel;
  260. // set the src pixel to the last pixel in the row
  261. const U8 *pSrcPixel = pDest - pBitmap->bytesPerPixel;
  262. for(U32 j = width; j < newWidth; j++)
  263. for(U32 k = 0; k < pBitmap->bytesPerPixel; k++)
  264. *pDest++ = pSrcPixel[k];
  265. }
  266. for(U32 i = height; i < newHeight; i++)
  267. {
  268. U8* pDest = (U8*)pReturn->getAddress(0, i);
  269. U8* pSrc = (U8*)pReturn->getAddress(0, height-1);
  270. dMemcpy(pDest, pSrc, newWidth * pBitmap->bytesPerPixel);
  271. }
  272. return pReturn;
  273. }
  274. //---------------------------------------------------------------------------------------------------------------------
  275. void TextureManager::freeTexture( TextureObject* pTextureObject )
  276. {
  277. if((mDGLRender || mManagerState == Resurrecting) && pTextureObject->mGLTextureName)
  278. {
  279. glDeleteTextures(1, (const GLuint*)&pTextureObject->mGLTextureName);
  280. // Adjust metrics.
  281. mTextureResidentCount--;
  282. mTextureResidentSize -= pTextureObject->mTextureResidentSize;
  283. pTextureObject->mTextureResidentSize = 0;
  284. mTextureResidentWasteSize -= pTextureObject->mTextureResidentWasteSize;
  285. pTextureObject->mTextureResidentWasteSize = 0;
  286. }
  287. if ( pTextureObject->mpBitmap != NULL )
  288. {
  289. SAFE_DELETE( pTextureObject->mpBitmap );
  290. mBitmapResidentSize -= pTextureObject->mBitmapResidentSize;
  291. pTextureObject->mBitmapResidentSize = 0;
  292. }
  293. TextureDictionary::remove(pTextureObject);
  294. SAFE_DELETE( pTextureObject );
  295. }
  296. //---------------------------------------------------------------------------------------------------------------------
  297. void TextureManager::getSourceDestByteFormat(GBitmap *pBitmap, U32 *sourceFormat, U32 *destFormat, U32 *byteFormat, U32* texelSize )
  298. {
  299. *byteFormat = GL_UNSIGNED_BYTE;
  300. U32 byteSize = 1;
  301. #if defined(TORQUE_OS_IOS) || defined(TORQUE_OS_ANDROID) || defined(TORQUE_OS_EMSCRIPTEN)
  302. switch(pBitmap->getFormat())
  303. {
  304. case GBitmap::Intensity:
  305. AssertFatal( 0, "GBitmap::Intensity GL_INTENSITY format not supported" );
  306. break;
  307. case GBitmap::Palettized:
  308. AssertFatal( 0, "GBitmap::Palettized GL_COLOR_INDEX format not supported" );
  309. break;
  310. case GBitmap::Luminance:
  311. *sourceFormat = GL_LUMINANCE;
  312. break;
  313. case GBitmap::LuminanceAlpha:
  314. *sourceFormat = GL_LUMINANCE_ALPHA;
  315. byteSize = 2;
  316. break;
  317. case GBitmap::RGB:
  318. *sourceFormat = GL_RGB;
  319. break;
  320. case GBitmap::RGBA:
  321. *sourceFormat = GL_RGBA;
  322. break;
  323. case GBitmap::Alpha:
  324. *sourceFormat = GL_ALPHA;
  325. break;
  326. case GBitmap::RGB565:
  327. *sourceFormat = GL_RGB;
  328. *byteFormat = GL_UNSIGNED_SHORT_5_6_5;
  329. byteSize = 2;
  330. break;
  331. case GBitmap::RGB5551:
  332. *sourceFormat = GL_RGBA;
  333. *byteFormat = GL_UNSIGNED_SHORT_5_5_5_1;
  334. byteSize = 1; // Incorrect but assume worst case.
  335. break;
  336. #ifdef TORQUE_OS_IOS
  337. case GBitmap::PVR2:
  338. *sourceFormat = GL_RGB;
  339. *byteFormat = GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  340. byteSize = 1; // Incorrect but assume worst case.
  341. break;
  342. case GBitmap::PVR2A:
  343. *sourceFormat = GL_RGBA;
  344. *byteFormat = GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  345. byteSize = 1; // Incorrect but assume worst case.
  346. break;
  347. case GBitmap::PVR4:
  348. *sourceFormat = GL_RGB;
  349. *byteFormat = GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  350. byteSize = 1; // Incorrect but assume worst case.
  351. break;
  352. case GBitmap::PVR4A:
  353. *sourceFormat = GL_RGBA;
  354. *byteFormat = GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  355. byteSize = 1; // Incorrect but assume worst case.
  356. break;
  357. #endif
  358. }
  359. *destFormat = *sourceFormat;
  360. *texelSize = byteSize;
  361. return;
  362. #else
  363. switch(pBitmap->getFormat())
  364. {
  365. case GBitmap::Intensity:
  366. *sourceFormat = GL_INTENSITY;
  367. break;
  368. case GBitmap::Palettized:
  369. *sourceFormat = GL_COLOR_INDEX;
  370. break;
  371. case GBitmap::Luminance:
  372. *sourceFormat = GL_LUMINANCE;
  373. break;
  374. case GBitmap::LuminanceAlpha:
  375. *sourceFormat = GL_LUMINANCE_ALPHA;
  376. break;
  377. case GBitmap::RGB:
  378. *sourceFormat = GL_RGB;
  379. break;
  380. case GBitmap::RGBA:
  381. *sourceFormat = GL_RGBA;
  382. break;
  383. case GBitmap::Alpha:
  384. *sourceFormat = GL_ALPHA;
  385. break;
  386. case GBitmap::RGB565:
  387. case GBitmap::RGB5551:
  388. #if defined(TORQUE_BIG_ENDIAN)
  389. *sourceFormat = GL_BGRA_EXT;
  390. *byteFormat = GL_UNSIGNED_SHORT_1_5_5_5_REV;
  391. #else
  392. *sourceFormat = GL_RGBA;
  393. *byteFormat = GL_UNSIGNED_SHORT_5_5_5_1;
  394. #endif
  395. break;
  396. };
  397. if(*byteFormat == GL_UNSIGNED_BYTE)
  398. {
  399. if (*sourceFormat != GL_COLOR_INDEX)
  400. {
  401. *destFormat = *sourceFormat;
  402. }
  403. else
  404. {
  405. *destFormat = GL_COLOR_INDEX8_EXT;
  406. }
  407. byteSize = 1;
  408. *texelSize = byteSize;
  409. }
  410. else
  411. {
  412. *destFormat = GL_RGB5_A1;
  413. *texelSize = 2;
  414. }
  415. if (TextureManager::mForce16BitTexture)
  416. {
  417. for (U32 i = 0; sg16BitMappings[i].end != true; i++)
  418. {
  419. if (*destFormat == sg16BitMappings[i].wanted)
  420. {
  421. *destFormat = sg16BitMappings[i].forced;
  422. *texelSize = 2;
  423. return;
  424. }
  425. }
  426. }
  427. else
  428. {
  429. if(*destFormat == GL_RGB)
  430. {
  431. *destFormat = GL_RGB8;
  432. *texelSize = 3 * byteSize;
  433. }
  434. else if(*destFormat == GL_RGBA)
  435. {
  436. *destFormat = GL_RGBA8;
  437. *texelSize = 4 * byteSize;
  438. }
  439. }
  440. #endif // defined(TORQUE_OS_IOS)
  441. }
  442. //--------------------------------------------------------------------------------------------------------------------
  443. U16* TextureManager::create16BitBitmap( GBitmap *pDL, U8 *in_source8, GBitmap::BitmapFormat alpha_info, GLint *GLformat, GLint *GLdata_type, U32 width, U32 height )
  444. {
  445. //PUAP -Mat make 16 bit
  446. U16 *texture_data = new U16[width * height];
  447. U16 *dest = texture_data;
  448. U32 *source = (U32*)in_source8;
  449. //since the pointer is 4 bytes, multiply by the number of bytes per pixel over 4
  450. U32 spanInBytes = (U32)((width * height) * (pDL->bytesPerPixel / 4.0f));
  451. U32 *source_end = source + spanInBytes;
  452. switch (alpha_info) {
  453. case GBitmap::Alpha: //ALPHA_TRANSPARENT:
  454. while (source != source_end) {
  455. U32 color = *source++;
  456. *dest++ = ((color & 0xF8) << 8) | ((color & 0xF800) >> 5) | ((color & 0xF80000) >> 18) | (color >> 31);
  457. }
  458. *GLformat = GL_RGBA;
  459. *GLdata_type = GL_UNSIGNED_SHORT_5_5_5_1;
  460. break;
  461. case GBitmap::RGBA://ALPHA_BLEND
  462. while (source != source_end) {
  463. U32 color = *source++;
  464. *dest++ = ((color & 0xF0) << 8) | ((color & 0xF000) >> 4) | ((color & 0xF00000) >> 16) | ((color & 0xF0000000) >> 28);
  465. }
  466. *GLformat = GL_RGBA;
  467. *GLdata_type = GL_UNSIGNED_SHORT_4_4_4_4;
  468. break;
  469. default://ALPHA_NONE
  470. U8 *source8 = (U8*)source;
  471. //32 bytes per address, snce we are casting to U8 we need 4 times as many
  472. U8 *end8 = source8 + (U32)(spanInBytes*4);
  473. while (source8 < end8) {
  474. U16 red = (U16)*source8;
  475. source8++;
  476. U16 green = (U16)*source8;
  477. source8++;
  478. U16 blue = (U16)*source8;
  479. source8++;
  480. //now color should be == RR GG BB 00
  481. *dest = ((red & 0xF8) << 8) | ((green & 0xFC) << 3) | ((blue & 0xF8) >> 3);
  482. dest++;
  483. }
  484. *GLformat = GL_RGB;
  485. *GLdata_type = GL_UNSIGNED_SHORT_5_6_5;
  486. break;
  487. }
  488. return texture_data;
  489. }
  490. //-----------------------------------------------------------------------------
  491. void TextureManager::refresh( TextureObject* pTextureObject )
  492. {
  493. // Finish if refresh not appropriate.
  494. if (!(mDGLRender || mManagerState == Resurrecting))
  495. return;
  496. // Sanity!
  497. AssertISV( pTextureObject->mGLTextureName != 0, "Refreshing texture but no texture created." );
  498. AssertISV( pTextureObject->mpBitmap != 0, "Refreshing texture but no bitmap available." );
  499. // Fetch bitmaps.
  500. GBitmap* pSourceBitmap = pTextureObject->mpBitmap;
  501. GBitmap* pNewBitmap = createPowerOfTwoBitmap(pSourceBitmap);
  502. U8 *bits = (U8*)pNewBitmap->getBits();
  503. U8 *lumBits = NULL;
  504. // Fetch source/dest formats.
  505. U32 sourceFormat, destFormat, byteFormat, texelSize;
  506. #if defined(TORQUE_OS_EMSCRIPTEN)
  507. if (pSourceBitmap->getFormat() == GBitmap::Alpha)
  508. {
  509. // special case: alpha should be converted to luminancealpha
  510. bits = lumBits = getLuminanceAlphaBits(pNewBitmap);
  511. sourceFormat = destFormat = GL_LUMINANCE_ALPHA;
  512. byteFormat = GL_UNSIGNED_BYTE;
  513. texelSize = 2;
  514. }
  515. else
  516. #endif
  517. {
  518. getSourceDestByteFormat(pSourceBitmap, &sourceFormat, &destFormat, &byteFormat, &texelSize);
  519. }
  520. #if defined(TORQUE_OS_IOS)
  521. bool isCompressed = (pNewBitmap->getFormat() >= GBitmap::PVR2) && (pNewBitmap->getFormat() <= GBitmap::PVR4A);
  522. #endif
  523. #if defined(TORQUE_OS_IOS)
  524. if (isCompressed) {
  525. switch (pNewBitmap->getFormat()) {
  526. case GBitmap::PVR2:
  527. case GBitmap::PVR2A:
  528. glCompressedTexImage2D(GL_TEXTURE_2D, 0, byteFormat,
  529. pNewBitmap->getWidth(), pNewBitmap->getHeight(), 0, (getMax((int)pNewBitmap->getWidth(),16) * getMax((int)pNewBitmap->getHeight(), 8) * 2 + 7) / 8, pNewBitmap->getBits() );
  530. break;
  531. case GBitmap::PVR4:
  532. case GBitmap::PVR4A:
  533. glCompressedTexImage2D(GL_TEXTURE_2D, 0, byteFormat,
  534. pNewBitmap->getWidth(), pNewBitmap->getHeight(), 0, (getMax((int)pNewBitmap->getWidth(),8) * getMax((int)pNewBitmap->getHeight(), 8) * 4 + 7) / 8, pNewBitmap->getBits() );
  535. break;
  536. default:
  537. // already tested for range of values, so default is just to keep the compiler happy!
  538. break;
  539. }
  540. } else
  541. #endif
  542. // Bind texture.
  543. glBindTexture( GL_TEXTURE_2D, pTextureObject->mGLTextureName );
  544. // Are we forcing to 16-bit?
  545. if( pSourceBitmap->mForce16Bit )
  546. {
  547. // Yes, so generate a 16-bit texture.
  548. GLint GLformat;
  549. GLint GLdata_type;
  550. U16* pBitmap16 = create16BitBitmap( pNewBitmap, pNewBitmap->getWritableBits(), pNewBitmap->getFormat(),
  551. &GLformat, &GLdata_type,
  552. pNewBitmap->getWidth(), pNewBitmap->getHeight() );
  553. glTexImage2D(GL_TEXTURE_2D,
  554. 0,
  555. GLformat,
  556. pNewBitmap->getWidth(), pNewBitmap->getHeight(),
  557. 0,
  558. GLformat,
  559. GLdata_type,
  560. pBitmap16
  561. );
  562. //copy new texture_data into pBits
  563. delete [] pBitmap16;
  564. }
  565. else
  566. {
  567. // No, so upload as-is.
  568. glTexImage2D(GL_TEXTURE_2D,
  569. 0,
  570. destFormat,
  571. pNewBitmap->getWidth(), pNewBitmap->getHeight(),
  572. 0,
  573. sourceFormat,
  574. byteFormat,
  575. bits);
  576. }
  577. const GLuint filter = pTextureObject->getFilter();
  578. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);
  579. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter);
  580. GLenum glClamp;
  581. if ( pTextureObject->getClamp() )
  582. glClamp = dglDoesSupportEdgeClamp() ? GL_CLAMP_TO_EDGE : GL_CLAMP;
  583. else
  584. glClamp = GL_REPEAT;
  585. glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glClamp );
  586. glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glClamp );
  587. if(pNewBitmap != pSourceBitmap)
  588. {
  589. delete pNewBitmap;
  590. }
  591. if (lumBits)
  592. delete[] lumBits;
  593. }
  594. //--------------------------------------------------------------------------------------------------------------------
  595. void TextureManager::refresh( const char *textureName )
  596. {
  597. // Finish if no texture name specified.
  598. AssertFatal( textureName != NULL, "Texture Manager: Cannot refresh a NULL texture name." );
  599. // Find the texture object.
  600. TextureObject* pTextureObject = TextureDictionary::find( textureName );
  601. // Finish if no texture for this texture name.
  602. if ( pTextureObject == NULL )
  603. return;
  604. // Finish if the texture object is a kept bitmap.
  605. if ( pTextureObject->getHandleType() == TextureHandle::BitmapKeepTexture )
  606. return;
  607. // Load the bitmap.
  608. GBitmap* pBitmap = loadBitmap( pTextureObject->mTextureKey );
  609. // Finish if bitmap could not be loaded.
  610. if ( pBitmap == NULL )
  611. return;
  612. // Register texture.
  613. TextureObject* pNewTextureObject;
  614. pNewTextureObject = registerTexture(pTextureObject->mTextureKey, pBitmap, pTextureObject->mHandleType, pTextureObject->mClamp);
  615. // Sanity!
  616. AssertFatal(pNewTextureObject == pTextureObject, "A new texture was returned during refresh.");
  617. }
  618. //--------------------------------------------------------------------------------------------------------------------
  619. void TextureManager::createGLName( TextureObject* pTextureObject )
  620. {
  621. // Finish if not appropriate.
  622. if (!(mDGLRender || mManagerState == Resurrecting))
  623. return;
  624. // Sanity!
  625. AssertISV( pTextureObject->mHandleType != TextureHandle::InvalidTexture, "Invalid texture type." );
  626. AssertISV( pTextureObject->mpBitmap != NULL, "Bitmap cannot be NULL." );
  627. AssertISV( pTextureObject->mGLTextureName == 0, "GL texture name already exists." );
  628. // Generate texture name.
  629. glGenTextures(1, &pTextureObject->mGLTextureName);
  630. // Fetch source/dest formats.
  631. U32 sourceFormat, destFormat, byteFormat, texelSize;
  632. getSourceDestByteFormat(pTextureObject->mpBitmap, &sourceFormat, &destFormat, &byteFormat, &texelSize);
  633. // Adjust metrics.
  634. mTextureResidentCount++;
  635. pTextureObject->mTextureResidentSize = pTextureObject->mTextureWidth * pTextureObject->mTextureHeight * texelSize;
  636. mTextureResidentSize += pTextureObject->mTextureResidentSize;
  637. pTextureObject->mTextureResidentWasteSize = ((pTextureObject->mTextureWidth * pTextureObject->mTextureHeight)-(pTextureObject->mBitmapWidth * pTextureObject->mBitmapHeight)) * texelSize;
  638. mTextureResidentWasteSize += pTextureObject->mTextureResidentWasteSize;
  639. // Refresh the texture.
  640. refresh( pTextureObject );
  641. }
  642. //--------------------------------------------------------------------------------------------------------------------
  643. TextureObject* TextureManager::registerTexture(const char* pTextureKey, GBitmap* pNewBitmap, TextureHandle::TextureHandleType type, bool clampToEdge)
  644. {
  645. // Sanity!
  646. AssertISV( type != TextureHandle::InvalidTexture, "Invalid texture type." );
  647. TextureObject* pTextureObject = NULL;
  648. // Fetch texture key.
  649. StringTableEntry textureKey = StringTable->insert(pTextureKey);
  650. if(pTextureKey)
  651. {
  652. pTextureObject = TextureDictionary::find(textureKey, type, clampToEdge);
  653. }
  654. if( pTextureObject )
  655. {
  656. // Remove bitmap if we have a different existing one.
  657. if ( pTextureObject->mpBitmap != NULL && pTextureObject->mpBitmap != pNewBitmap)
  658. {
  659. delete pTextureObject->mpBitmap;
  660. pTextureObject->mpBitmap = NULL;
  661. // Adjust metrics.
  662. mBitmapResidentSize -= pTextureObject->mBitmapResidentSize;
  663. pTextureObject->mBitmapResidentSize = 0;
  664. }
  665. // Remove any texture name.
  666. if ( pTextureObject->mGLTextureName != 0 )
  667. {
  668. glDeleteTextures(1, (const GLuint*)&pTextureObject->mGLTextureName);
  669. pTextureObject->mGLTextureName = 0;
  670. // Adjust metrics.
  671. mTextureResidentCount--;
  672. mTextureResidentSize -= pTextureObject->mTextureResidentSize;
  673. pTextureObject->mTextureResidentSize = 0;
  674. mTextureResidentWasteSize -= pTextureObject->mTextureResidentWasteSize;
  675. pTextureObject->mTextureResidentWasteSize = 0;
  676. }
  677. }
  678. else
  679. {
  680. // Create new texture object.
  681. pTextureObject = new TextureObject();
  682. pTextureObject->mTextureKey = textureKey;
  683. pTextureObject->mHandleType = type;
  684. TextureDictionary::insert(pTextureObject);
  685. }
  686. if ( pTextureObject->mHandleType == TextureHandle::BitmapKeepTexture && pTextureObject->mpBitmap != pNewBitmap )
  687. {
  688. // Adjust metrics.
  689. pTextureObject->mBitmapResidentSize = pNewBitmap->byteSize;
  690. mBitmapResidentSize += pTextureObject->mBitmapResidentSize;
  691. }
  692. pTextureObject->mpBitmap = pNewBitmap;
  693. pTextureObject->mBitmapWidth = pNewBitmap->getWidth();
  694. pTextureObject->mBitmapHeight = pNewBitmap->getHeight();
  695. pTextureObject->mTextureWidth = getNextPow2(pNewBitmap->getWidth());
  696. pTextureObject->mTextureHeight = getNextPow2(pNewBitmap->getHeight());
  697. pTextureObject->mClamp = clampToEdge;
  698. // Generate a GL texture name if one is not ready.
  699. if( pTextureObject->mGLTextureName == 0)
  700. {
  701. createGLName(pTextureObject);
  702. }
  703. // Delete bitmap if we're not keeping it.
  704. if ( pTextureObject->mHandleType != TextureHandle::BitmapKeepTexture )
  705. {
  706. delete pTextureObject->mpBitmap;
  707. pTextureObject->mpBitmap = NULL;
  708. }
  709. return pTextureObject;
  710. }
  711. //--------------------------------------------------------------------------------------------------------------------
  712. TextureObject *TextureManager::loadTexture(const char* pTextureKey, TextureHandle::TextureHandleType type, bool clampToEdge, bool checkOnly, bool force16Bit )
  713. {
  714. // Sanity!
  715. AssertISV( type != TextureHandle::InvalidTexture, "Invalid texture type." );
  716. // Finish if texture key is invalid.
  717. if( pTextureKey == NULL || *pTextureKey == 0)
  718. return NULL;
  719. // Fetch texture key.
  720. StringTableEntry textureKey = StringTable->insert(pTextureKey);
  721. TextureObject *ret = TextureDictionary::find(textureKey, type, clampToEdge);
  722. GBitmap *bmp = NULL;
  723. if( ret == NULL )
  724. {
  725. // Ok, no hit - is it in the current dir? If so then let's grab it
  726. // and use it.
  727. bmp = loadBitmap(textureKey, false);
  728. if(bmp)
  729. {
  730. bmp->mForce16Bit = force16Bit;
  731. return registerTexture(textureKey, bmp, type, clampToEdge);
  732. }
  733. }
  734. if(ret)
  735. return ret;
  736. // If we're just checking, fail out so we eventually get around to
  737. // loading a real bitmap.
  738. if(checkOnly)
  739. return NULL;
  740. // Ok, no success so let's try actually loading a texture.
  741. bmp = loadBitmap(textureKey);
  742. if(!bmp)
  743. {
  744. Con::warnf("Could not locate texture: %s", textureKey);
  745. return NULL;
  746. }
  747. bmp->mForce16Bit = force16Bit;
  748. return registerTexture(textureKey, bmp, type, clampToEdge);
  749. }
  750. //--------------------------------------------------------------------------------------------------------------------
  751. GBitmap *TextureManager::loadBitmap( const char* pTextureKey, bool recurse, bool nocompression )
  752. {
  753. char fileNameBuffer[512];
  754. Con::expandPath( fileNameBuffer, sizeof(fileNameBuffer), pTextureKey );
  755. GBitmap *bmp = NULL;
  756. // Loop through the supported extensions to find the file.
  757. U32 len = dStrlen(fileNameBuffer);
  758. for (U32 i = 0; i < EXT_ARRAY_SIZE && bmp == NULL; i++)
  759. {
  760. #if defined(TORQUE_OS_IOS)
  761. // check to see if requested no-compression...
  762. if (nocompression && (dStrncmp( extArray[i], ".pvr", 4 ) == 0)) {
  763. continue;
  764. }
  765. #endif
  766. dStrcpy(fileNameBuffer + len, extArray[i]);
  767. bmp = (GBitmap*)ResourceManager->loadInstance(fileNameBuffer);
  768. if ( bmp != NULL && (bmp->getWidth() > MaximumProductSupportedTextureWidth || bmp->getHeight() > MaximumProductSupportedTextureHeight) )
  769. {
  770. Con::warnf( "TextureManager::loadBitmap() - Cannot load bitmap '%s' as its dimensions exceed the maximum product-supported texture dimension.", fileNameBuffer );
  771. delete bmp;
  772. return NULL;
  773. }
  774. }
  775. return bmp;
  776. }
  777. //--------------------------------------------------------------------------------------------------------------------
  778. void TextureManager::dumpMetrics( void )
  779. {
  780. S32 textureResidentCount = 0;
  781. S32 textureResidentSize = 0;
  782. S32 textureResidentWasteSize = 0;
  783. S32 bitmapResidentSize = 0;
  784. Con::printSeparator();
  785. Con::printBlankLine();
  786. Con::printf( "Dumping texture manager metrics:" );
  787. TextureObject* pProbe = TextureDictionary::TextureObjectChain;
  788. while (pProbe != NULL)
  789. {
  790. GLboolean isTextureResident = false;
  791. if ( pProbe->mGLTextureName != 0 )
  792. {
  793. textureResidentCount++;
  794. glAreTexturesResident( 1, &pProbe->mGLTextureName, &isTextureResident );
  795. }
  796. textureResidentSize += pProbe->mTextureResidentSize;
  797. bitmapResidentSize += pProbe->mBitmapResidentSize;
  798. textureResidentWasteSize += pProbe->mTextureResidentWasteSize;
  799. // Info.
  800. Con::printf( "BitmapArea: (%d-%d), BitmapMemory: %d, TextureArea: (%d-%d), TextureMemory: %d, TextureMemoryWaste=%d, Refs=%d, Resident=%s, Name=%s",
  801. pProbe->mBitmapWidth,pProbe->mBitmapHeight, pProbe->mBitmapResidentSize,
  802. pProbe->mTextureWidth, pProbe->mTextureHeight, pProbe->mTextureResidentSize, pProbe->mTextureResidentWasteSize,
  803. pProbe->mRefCount,
  804. isTextureResident == 0 ? "NO" : "YES",
  805. pProbe->mTextureKey );
  806. pProbe = pProbe->next;
  807. }
  808. // Validate metrics.
  809. const bool textureCountSame = textureResidentCount == mTextureResidentCount;
  810. const bool textureSizeSame = textureResidentSize == mTextureResidentSize;
  811. const bool textureWasteSizeSame = textureResidentWasteSize == mTextureResidentWasteSize;
  812. const bool bitmapSizeSame = bitmapResidentSize == mBitmapResidentSize;
  813. const bool allMetricsValid = textureCountSame && textureSizeSame && textureWasteSizeSame && bitmapSizeSame;
  814. // Error if metrics are invalid.
  815. if ( !allMetricsValid )
  816. Con::errorf( "Metrics appear to be invalid." );
  817. // Info.
  818. Con::printf( "Metrics Totals:" );
  819. Con::printf( "TextureCount: %d, TextureSize: %d, TextureWasteSize: %d, BitmapSize: %d, ResidentFraction: %g",
  820. mTextureResidentCount,
  821. mTextureResidentSize,
  822. mTextureResidentWasteSize,
  823. mBitmapResidentSize,
  824. getResidentFraction() );
  825. Con::printBlankLine();
  826. Con::printSeparator();
  827. Con::printf( "All texture manager metrics are valid." );
  828. Con::printSeparator();
  829. }
  830. //--------------------------------------------------------------------------------------------------------------------
  831. F32 TextureManager::getResidentFraction()
  832. {
  833. U32 resident = 0;
  834. U32 total = 0;
  835. Vector<GLuint> names;
  836. TextureObject* pProbe = TextureDictionary::TextureObjectChain;
  837. while (pProbe != NULL)
  838. {
  839. if (pProbe->mGLTextureName != 0)
  840. {
  841. total++;
  842. names.push_back(pProbe->mGLTextureName);
  843. }
  844. pProbe = pProbe->next;
  845. }
  846. if (total == 0)
  847. return 1.0f;
  848. Vector<GLboolean> isResident;
  849. isResident.setSize(names.size());
  850. glAreTexturesResident(names.size(), names.address(), isResident.address());
  851. for (U32 i = 0; i < (U32)names.size(); i++)
  852. if (isResident[i] == GL_TRUE)
  853. resident++;
  854. return (F32(resident) / F32(total));
  855. }