gfxTextureManager.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 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 "platform/platform.h"
  23. #include "gfx/gfxTextureManager.h"
  24. #include "gfx/gfxDevice.h"
  25. #include "gfx/gfxCardProfile.h"
  26. #include "gfx/gfxStringEnumTranslate.h"
  27. #include "gfx/bitmap/ddsUtils.h"
  28. #include "core/strings/stringFunctions.h"
  29. #include "core/util/safeDelete.h"
  30. #include "core/resourceManager.h"
  31. #include "core/volume.h"
  32. #include "core/util/dxt5nmSwizzle.h"
  33. #include "console/consoleTypes.h"
  34. #include "console/engineAPI.h"
  35. using namespace Torque;
  36. //#define DEBUG_SPEW
  37. S32 GFXTextureManager::smTextureReductionLevel = 0;
  38. String GFXTextureManager::smMissingTexturePath("core/art/missingTexture");
  39. String GFXTextureManager::smUnavailableTexturePath("core/art/unavailable");
  40. String GFXTextureManager::smWarningTexturePath("core/art/warnmat");
  41. GFXTextureManager::EventSignal GFXTextureManager::smEventSignal;
  42. static const String sDDSExt( "dds" );
  43. void GFXTextureManager::init()
  44. {
  45. Con::addVariable( "$pref::Video::textureReductionLevel", TypeS32, &smTextureReductionLevel,
  46. "The number of mipmap levels to drop on loaded textures to reduce "
  47. "video memory usage. It will skip any textures that have been defined "
  48. "as not allowing down scaling.\n"
  49. "@ingroup GFX\n" );
  50. Con::addVariable( "$pref::Video::missingTexturePath", TypeRealString, &smMissingTexturePath,
  51. "The file path of the texture to display when the requested texture is missing.\n"
  52. "@ingroup GFX\n" );
  53. Con::addVariable( "$pref::Video::unavailableTexturePath", TypeRealString, &smUnavailableTexturePath,
  54. "@brief The file path of the texture to display when the requested texture is unavailable.\n\n"
  55. "Often this texture is used by GUI controls to indicate that the request image is unavailable.\n"
  56. "@ingroup GFX\n" );
  57. Con::addVariable( "$pref::Video::warningTexturePath", TypeRealString, &smWarningTexturePath,
  58. "The file path of the texture used to warn the developer.\n"
  59. "@ingroup GFX\n" );
  60. }
  61. GFXTextureManager::GFXTextureManager()
  62. {
  63. mListHead = mListTail = NULL;
  64. mTextureManagerState = GFXTextureManager::Living;
  65. // Set up the hash table
  66. mHashCount = 1023;
  67. mHashTable = new GFXTextureObject *[mHashCount];
  68. for(U32 i = 0; i < mHashCount; i++)
  69. mHashTable[i] = NULL;
  70. }
  71. GFXTextureManager::~GFXTextureManager()
  72. {
  73. if( mHashTable )
  74. SAFE_DELETE_ARRAY( mHashTable );
  75. mCubemapTable.clear();
  76. }
  77. U32 GFXTextureManager::getTextureDownscalePower( GFXTextureProfile *profile )
  78. {
  79. if ( !profile || profile->canDownscale() )
  80. return smTextureReductionLevel;
  81. return 0;
  82. }
  83. bool GFXTextureManager::validateTextureQuality( GFXTextureProfile *profile, U32 &width, U32 &height )
  84. {
  85. U32 scaleFactor = getTextureDownscalePower( profile );
  86. if ( scaleFactor == 0 )
  87. return true;
  88. // Otherwise apply the appropriate scale...
  89. width >>= scaleFactor;
  90. height >>= scaleFactor;
  91. return true;
  92. }
  93. void GFXTextureManager::kill()
  94. {
  95. AssertFatal( mTextureManagerState != GFXTextureManager::Dead, "Texture Manager already killed!" );
  96. // Release everything in the cache we can
  97. // so we don't leak any textures.
  98. cleanupCache();
  99. GFXTextureObject *curr = mListHead;
  100. GFXTextureObject *temp;
  101. // Actually delete all the textures we know about.
  102. while( curr != NULL )
  103. {
  104. temp = curr->mNext;
  105. curr->kill();
  106. curr = temp;
  107. }
  108. mCubemapTable.clear();
  109. mTextureManagerState = GFXTextureManager::Dead;
  110. }
  111. void GFXTextureManager::zombify()
  112. {
  113. AssertFatal( mTextureManagerState != GFXTextureManager::Zombie, "Texture Manager already a zombie!" );
  114. // Notify everyone that cares about the zombification!
  115. smEventSignal.trigger( GFXZombify );
  116. // Release unused pool textures.
  117. cleanupPool();
  118. // Release everything in the cache we can.
  119. cleanupCache();
  120. // Free all the device copies of the textures.
  121. GFXTextureObject *temp = mListHead;
  122. while( temp != NULL )
  123. {
  124. freeTexture( temp, true );
  125. temp = temp->mNext;
  126. }
  127. // Finally, note our state.
  128. mTextureManagerState = GFXTextureManager::Zombie;
  129. }
  130. void GFXTextureManager::resurrect()
  131. {
  132. // Reupload all the device copies of the textures.
  133. GFXTextureObject *temp = mListHead;
  134. while( temp != NULL )
  135. {
  136. refreshTexture( temp );
  137. temp = temp->mNext;
  138. }
  139. // Notify callback registries.
  140. smEventSignal.trigger( GFXResurrect );
  141. // Update our state.
  142. mTextureManagerState = GFXTextureManager::Living;
  143. }
  144. void GFXTextureManager::cleanupPool()
  145. {
  146. PROFILE_SCOPE( GFXTextureManager_CleanupPool );
  147. TexturePoolMap::Iterator iter = mTexturePool.begin();
  148. for ( ; iter != mTexturePool.end(); )
  149. {
  150. if ( iter->value->getRefCount() == 1 )
  151. {
  152. // This texture is unreferenced, so take the time
  153. // now to completely remove it from the pool.
  154. TexturePoolMap::Iterator unref = iter;
  155. ++iter;
  156. unref->value = NULL;
  157. mTexturePool.erase( unref );
  158. continue;
  159. }
  160. ++iter;
  161. }
  162. }
  163. void GFXTextureManager::requestDeleteTexture( GFXTextureObject *texture )
  164. {
  165. // If this is a non-cached texture then just really delete it.
  166. if ( texture->mTextureLookupName.isEmpty() )
  167. {
  168. delete texture;
  169. return;
  170. }
  171. // Set the time and store it.
  172. texture->mDeleteTime = Platform::getTime();
  173. mToDelete.push_back_unique( texture );
  174. }
  175. void GFXTextureManager::cleanupCache( U32 secondsToLive )
  176. {
  177. PROFILE_SCOPE( GFXTextureManager_CleanupCache );
  178. U32 killTime = Platform::getTime() - secondsToLive;
  179. for ( U32 i=0; i < mToDelete.size(); )
  180. {
  181. GFXTextureObject *tex = mToDelete[i];
  182. // If the texture was picked back up by a user
  183. // then just remove it from the list.
  184. if ( tex->getRefCount() != 0 )
  185. {
  186. mToDelete.erase_fast( i );
  187. continue;
  188. }
  189. // If its time has expired delete it for real.
  190. if ( tex->mDeleteTime <= killTime )
  191. {
  192. //Con::errorf( "Killed texture: %s", tex->mTextureLookupName.c_str() );
  193. delete tex;
  194. mToDelete.erase_fast( i );
  195. continue;
  196. }
  197. i++;
  198. }
  199. }
  200. GFXTextureObject *GFXTextureManager::_lookupTexture( const char *hashName, const GFXTextureProfile *profile )
  201. {
  202. GFXTextureObject *ret = hashFind( hashName );
  203. // TODO: Profile checking HERE
  204. return ret;
  205. }
  206. GFXTextureObject *GFXTextureManager::_lookupTexture( const DDSFile *ddsFile, const GFXTextureProfile *profile )
  207. {
  208. if( ddsFile->getTextureCacheString().isNotEmpty() )
  209. {
  210. // Call _lookupTexture()
  211. return _lookupTexture( ddsFile->getTextureCacheString(), profile );
  212. }
  213. return NULL;
  214. }
  215. GFXTextureObject *GFXTextureManager::createTexture( GBitmap *bmp, const String &resourceName, GFXTextureProfile *profile, bool deleteBmp )
  216. {
  217. AssertFatal(bmp, "GFXTextureManager::createTexture() - Got NULL bitmap!");
  218. GFXTextureObject *cacheHit = _lookupTexture( resourceName, profile );
  219. if( cacheHit != NULL)
  220. {
  221. // Con::errorf("Cached texture '%s'", (resourceName.isNotEmpty() ? resourceName.c_str() : "unknown"));
  222. if (deleteBmp)
  223. delete bmp;
  224. return cacheHit;
  225. }
  226. return _createTexture( bmp, resourceName, profile, deleteBmp, NULL );
  227. }
  228. GFXTextureObject *GFXTextureManager::_createTexture( GBitmap *bmp,
  229. const String &resourceName,
  230. GFXTextureProfile *profile,
  231. bool deleteBmp,
  232. GFXTextureObject *inObj )
  233. {
  234. PROFILE_SCOPE( GFXTextureManager_CreateTexture_Bitmap );
  235. #ifdef DEBUG_SPEW
  236. Platform::outputDebugString( "[GFXTextureManager] _createTexture (GBitmap) '%s'",
  237. resourceName.c_str()
  238. );
  239. #endif
  240. // Massage the bitmap based on any resize rules.
  241. U32 scalePower = getTextureDownscalePower( profile );
  242. GBitmap *realBmp = bmp;
  243. U32 realWidth = bmp->getWidth();
  244. U32 realHeight = bmp->getHeight();
  245. if ( scalePower &&
  246. isPow2(bmp->getWidth()) &&
  247. isPow2(bmp->getHeight()) &&
  248. profile->canDownscale() )
  249. {
  250. // We only work with power of 2 textures for now, so we
  251. // don't have to worry about padding.
  252. // We downscale the bitmap on the CPU... this is the reason
  253. // you should be using DDS which already has good looking mips.
  254. GBitmap *padBmp = bmp;
  255. padBmp->extrudeMipLevels();
  256. scalePower = getMin( scalePower, padBmp->getNumMipLevels() - 1 );
  257. realWidth = getMax( (U32)1, padBmp->getWidth() >> scalePower );
  258. realHeight = getMax( (U32)1, padBmp->getHeight() >> scalePower );
  259. realBmp = new GBitmap( realWidth, realHeight, false, bmp->getFormat() );
  260. // Copy to the new bitmap...
  261. dMemcpy( realBmp->getWritableBits(),
  262. padBmp->getBits(scalePower),
  263. padBmp->getBytesPerPixel() * realWidth * realHeight );
  264. // This line is commented out because createPaddedBitmap is commented out.
  265. // If that line is added back in, this line should be added back in.
  266. // delete padBmp;
  267. }
  268. // Call the internal create... (use the real* variables now, as they
  269. // reflect the reality of the texture we are creating.)
  270. U32 numMips = 0;
  271. GFXFormat realFmt = realBmp->getFormat();
  272. _validateTexParams( realWidth, realHeight, profile, numMips, realFmt );
  273. GFXTextureObject *ret;
  274. if ( inObj )
  275. {
  276. // If the texture has changed in dimensions
  277. // then we need to recreate it.
  278. if ( inObj->getWidth() != realWidth ||
  279. inObj->getHeight() != realHeight ||
  280. inObj->getFormat() != realFmt )
  281. ret = _createTextureObject( realHeight, realWidth, 0, realFmt, profile, numMips, false, 0, inObj );
  282. else
  283. ret = inObj;
  284. }
  285. else
  286. ret = _createTextureObject(realHeight, realWidth, 0, realFmt, profile, numMips );
  287. if(!ret)
  288. {
  289. Con::errorf("GFXTextureManager - failed to create texture (1) for '%s'", (resourceName.isNotEmpty() ? resourceName.c_str() : "unknown"));
  290. return NULL;
  291. }
  292. // Extrude mip levels
  293. // Don't do this for fonts!
  294. if( ret->mMipLevels > 1 && ( realBmp->getNumMipLevels() == 1 ) && ( realBmp->getFormat() != GFXFormatA8 ) &&
  295. isPow2( realBmp->getHeight() ) && isPow2( realBmp->getWidth() ) && !profile->noMip() )
  296. {
  297. // NOTE: This should really be done by extruding mips INTO a DDS file instead
  298. // of modifying the gbitmap
  299. realBmp->extrudeMipLevels(false);
  300. }
  301. // If _validateTexParams kicked back a different format, than there needs to be
  302. // a conversion
  303. DDSFile *bmpDDS = NULL;
  304. if( realBmp->getFormat() != realFmt )
  305. {
  306. const GFXFormat oldFmt = realBmp->getFormat();
  307. // TODO: Set it up so that ALL format conversions use DDSFile. Rip format
  308. // switching out of GBitmap entirely.
  309. if( !realBmp->setFormat( realFmt ) )
  310. {
  311. // This is not the ideal implementation...
  312. bmpDDS = DDSFile::createDDSFileFromGBitmap( realBmp );
  313. bool convSuccess = false;
  314. if( bmpDDS != NULL )
  315. {
  316. // This shouldn't live here, I don't think
  317. switch( realFmt )
  318. {
  319. case GFXFormatDXT1:
  320. case GFXFormatDXT2:
  321. case GFXFormatDXT3:
  322. case GFXFormatDXT4:
  323. case GFXFormatDXT5:
  324. // If this is a Normal Map profile, than the data needs to be conditioned
  325. // to use the swizzle trick
  326. if( ret->mProfile->getType() == GFXTextureProfile::NormalMap )
  327. {
  328. PROFILE_START(DXT_DXTNMSwizzle);
  329. static DXT5nmSwizzle sDXT5nmSwizzle;
  330. DDSUtil::swizzleDDS( bmpDDS, sDXT5nmSwizzle );
  331. PROFILE_END();
  332. }
  333. convSuccess = DDSUtil::squishDDS( bmpDDS, realFmt );
  334. break;
  335. default:
  336. AssertFatal(false, "Attempting to convert to a non-DXT format");
  337. break;
  338. }
  339. }
  340. if( !convSuccess )
  341. {
  342. Con::errorf( "[GFXTextureManager]: Failed to change source format from %s to %s. Cannot create texture.",
  343. GFXStringTextureFormat[oldFmt], GFXStringTextureFormat[realFmt] );
  344. delete bmpDDS;
  345. return NULL;
  346. }
  347. }
  348. #ifdef TORQUE_DEBUG
  349. else
  350. {
  351. //Con::warnf( "[GFXTextureManager]: Changed bitmap format from %s to %s.",
  352. // GFXStringTextureFormat[oldFmt], GFXStringTextureFormat[realFmt] );
  353. }
  354. #endif
  355. }
  356. // Call the internal load...
  357. if( ( bmpDDS == NULL && !_loadTexture( ret, realBmp ) ) || // If we aren't doing a DDS format change, use bitmap load
  358. ( bmpDDS != NULL && !_loadTexture( ret, bmpDDS ) ) ) // If there is a DDS, than load that instead. A format change took place.
  359. {
  360. Con::errorf("GFXTextureManager - failed to load GBitmap for '%s'", (resourceName.isNotEmpty() ? resourceName.c_str() : "unknown"));
  361. return NULL;
  362. }
  363. // Do statistics and book-keeping...
  364. // - info for the texture...
  365. ret->mTextureLookupName = resourceName;
  366. ret->mBitmapSize.set(realWidth, realHeight,0);
  367. #ifdef TORQUE_DEBUG
  368. if (resourceName.isNotEmpty())
  369. ret->mDebugDescription = resourceName;
  370. else
  371. ret->mDebugDescription = "Anonymous Texture Object";
  372. #endif
  373. if(profile->doStoreBitmap())
  374. {
  375. // NOTE: may store a downscaled copy!
  376. SAFE_DELETE( ret->mBitmap );
  377. SAFE_DELETE( ret->mDDS );
  378. if( bmpDDS == NULL )
  379. ret->mBitmap = new GBitmap( *realBmp );
  380. else
  381. ret->mDDS = bmpDDS;
  382. }
  383. else
  384. {
  385. // Delete the DDS if we made one
  386. SAFE_DELETE( bmpDDS );
  387. }
  388. if ( !inObj )
  389. _linkTexture( ret );
  390. // - output debug info?
  391. // Save texture for debug purpose
  392. // static int texId = 0;
  393. // char buff[256];
  394. // dSprintf(buff, sizeof(buff), "tex_%d", texId++);
  395. // bmp->writePNGDebug(buff);
  396. // texId++;
  397. // Before we delete the bitmap save our transparency flag
  398. ret->mHasTransparency = realBmp->getHasTransparency();
  399. // Some final cleanup...
  400. if(realBmp != bmp)
  401. SAFE_DELETE(realBmp);
  402. if (deleteBmp)
  403. SAFE_DELETE(bmp);
  404. // Return the new texture!
  405. return ret;
  406. }
  407. GFXTextureObject *GFXTextureManager::createTexture( DDSFile *dds, GFXTextureProfile *profile, bool deleteDDS )
  408. {
  409. AssertFatal(dds, "GFXTextureManager::createTexture() - Got NULL dds!");
  410. // Check the cache first...
  411. GFXTextureObject *cacheHit = _lookupTexture( dds, profile );
  412. if ( cacheHit )
  413. {
  414. // Con::errorf("Cached texture '%s'", (fileName.isNotEmpty() ? fileName.c_str() : "unknown"));
  415. if( deleteDDS )
  416. delete dds;
  417. return cacheHit;
  418. }
  419. return _createTexture( dds, profile, deleteDDS, NULL );
  420. }
  421. GFXTextureObject *GFXTextureManager::_createTexture( DDSFile *dds,
  422. GFXTextureProfile *profile,
  423. bool deleteDDS,
  424. GFXTextureObject *inObj )
  425. {
  426. PROFILE_SCOPE( GFXTextureManager_CreateTexture_DDS );
  427. const char *fileName = dds->getTextureCacheString();
  428. if( !fileName )
  429. fileName = "unknown";
  430. #ifdef DEBUG_SPEW
  431. Platform::outputDebugString( "[GFXTextureManager] _createTexture (DDS) '%s'",
  432. fileName
  433. );
  434. #endif
  435. // Ignore padding from the profile.
  436. U32 numMips = dds->mMipMapCount;
  437. GFXFormat fmt = dds->mFormat;
  438. _validateTexParams( dds->getHeight(), dds->getWidth(), profile, numMips, fmt );
  439. if( fmt != dds->mFormat )
  440. {
  441. Con::errorf( "GFXTextureManager - failed to validate texture parameters for DDS file '%s'", fileName );
  442. return NULL;
  443. }
  444. // Call the internal create... (use the real* variables now, as they
  445. // reflect the reality of the texture we are creating.)
  446. GFXTextureObject *ret;
  447. if ( inObj )
  448. {
  449. // If the texture has changed in dimensions
  450. // then we need to recreate it.
  451. if ( inObj->getWidth() != dds->getWidth() ||
  452. inObj->getHeight() != dds->getHeight() ||
  453. inObj->getFormat() != fmt ||
  454. inObj->getMipLevels() != numMips )
  455. ret = _createTextureObject( dds->getHeight(), dds->getWidth(), 0,
  456. fmt, profile, numMips,
  457. true, 0, inObj );
  458. else
  459. ret = inObj;
  460. }
  461. else
  462. ret = _createTextureObject( dds->getHeight(), dds->getWidth(), 0,
  463. fmt, profile, numMips, true );
  464. if(!ret)
  465. {
  466. Con::errorf("GFXTextureManager - failed to create texture (1) for '%s' DDSFile.", fileName);
  467. return NULL;
  468. }
  469. // Call the internal load...
  470. if(!_loadTexture(ret, dds))
  471. {
  472. Con::errorf("GFXTextureManager - failed to load DDS for '%s'", fileName);
  473. return NULL;
  474. }
  475. // Do statistics and book-keeping...
  476. // - info for the texture...
  477. ret->mTextureLookupName = dds->getTextureCacheString();
  478. ret->mBitmapSize.set( dds->mWidth, dds->mHeight, 0 );
  479. #ifdef TORQUE_DEBUG
  480. ret->mDebugDescription = fileName;
  481. #endif
  482. if(profile->doStoreBitmap())
  483. {
  484. // NOTE: may store a downscaled copy!
  485. SAFE_DELETE( ret->mBitmap );
  486. SAFE_DELETE( ret->mDDS );
  487. ret->mDDS = new DDSFile( *dds );
  488. }
  489. if ( !inObj )
  490. _linkTexture( ret );
  491. // - output debug info?
  492. // Save texture for debug purpose
  493. // static int texId = 0;
  494. // char buff[256];
  495. // dSprintf(buff, sizeof(buff), "tex_%d", texId++);
  496. // bmp->writePNGDebug(buff);
  497. // texId++;
  498. // Save our transparency flag
  499. ret->mHasTransparency = dds->getHasTransparency();
  500. if( deleteDDS )
  501. delete dds;
  502. // Return the new texture!
  503. return ret;
  504. }
  505. GFXTextureObject *GFXTextureManager::createTexture( const Torque::Path &path, GFXTextureProfile *profile )
  506. {
  507. PROFILE_SCOPE( GFXTextureManager_createTexture );
  508. // Resource handles used for loading. Hold on to them
  509. // throughout this function so that change notifications
  510. // don't get added, then removed, and then re-added.
  511. Resource< DDSFile > dds;
  512. Resource< GBitmap > bitmap;
  513. // We need to handle path's that have had "incorrect"
  514. // extensions parsed out of the file name
  515. Torque::Path correctPath = path;
  516. bool textureExt = false;
  517. // Easiest case to handle is when there isn't an extension
  518. if (path.getExtension().isEmpty())
  519. textureExt = true;
  520. // Since "dds" isn't registered with GBitmap currently we
  521. // have to test it separately
  522. if (sDDSExt.equal( path.getExtension(), String::NoCase ) )
  523. textureExt = true;
  524. // Now loop through the rest of the GBitmap extensions
  525. // to see if we have any matches
  526. for ( U32 i = 0; i < GBitmap::sRegistrations.size(); i++ )
  527. {
  528. // If we have gotten a match (either in this loop or before)
  529. // then we can exit
  530. if (textureExt)
  531. break;
  532. const GBitmap::Registration &reg = GBitmap::sRegistrations[i];
  533. const Vector<String> &extensions = reg.extensions;
  534. for ( U32 j = 0; j < extensions.size(); ++j )
  535. {
  536. if ( extensions[j].equal( path.getExtension(), String::NoCase ) )
  537. {
  538. // Found a valid texture extension
  539. textureExt = true;
  540. break;
  541. }
  542. }
  543. }
  544. // If we didn't find a valid texture extension then assume that
  545. // the parsed out "extension" was actually intended to be part of
  546. // the texture name so add it back
  547. if (!textureExt)
  548. {
  549. correctPath.setFileName( Torque::Path::Join( path.getFileName(), '.', path.getExtension() ) );
  550. correctPath.setExtension( String::EmptyString );
  551. }
  552. // Check the cache first...
  553. String pathNoExt = Torque::Path::Join( correctPath.getRoot(), ':', correctPath.getPath() );
  554. pathNoExt = Torque::Path::Join( pathNoExt, '/', correctPath.getFileName() );
  555. GFXTextureObject *retTexObj = _lookupTexture( pathNoExt, profile );
  556. if( retTexObj )
  557. return retTexObj;
  558. const U32 scalePower = getTextureDownscalePower( profile );
  559. // If this is a valid file (has an extension) than load it
  560. Path realPath;
  561. if( Torque::FS::IsFile( correctPath ) )
  562. {
  563. // Check for DDS
  564. if( sDDSExt.equal(correctPath.getExtension(), String::NoCase ) )
  565. {
  566. dds = DDSFile::load( correctPath, scalePower );
  567. if( dds != NULL )
  568. {
  569. realPath = dds.getPath();
  570. retTexObj = createTexture( dds, profile, false );
  571. }
  572. }
  573. else // Let GBitmap take care of it
  574. {
  575. bitmap = GBitmap::load( correctPath );
  576. if( bitmap != NULL )
  577. {
  578. realPath = bitmap.getPath();
  579. retTexObj = createTexture( bitmap, pathNoExt, profile, false );
  580. }
  581. }
  582. }
  583. else
  584. {
  585. // NOTE -- We should probably remove the code from GBitmap that tries different
  586. // extensions for things GBitmap loads, and move it here. I think it should
  587. // be a bit more involved than just a list of extensions. Some kind of
  588. // extension registration thing, maybe.
  589. // Check to see if there is a .DDS file with this name (if no extension is provided)
  590. Torque::Path tryDDSPath = pathNoExt;
  591. if( tryDDSPath.getExtension().isNotEmpty() )
  592. tryDDSPath.setFileName( tryDDSPath.getFullFileName() );
  593. tryDDSPath.setExtension( sDDSExt );
  594. if( Torque::FS::IsFile( tryDDSPath ) )
  595. {
  596. dds = DDSFile::load( tryDDSPath, scalePower );
  597. if( dds != NULL )
  598. {
  599. realPath = dds.getPath();
  600. retTexObj = createTexture( dds, profile, false );
  601. }
  602. }
  603. // Otherwise, retTexObj stays NULL, and fall through to the generic GBitmap
  604. // load.
  605. }
  606. // If we still don't have a texture object yet, feed the correctPath to GBitmap and
  607. // it will try a bunch of extensions
  608. if( retTexObj == NULL )
  609. {
  610. // Find and load the texture.
  611. bitmap = GBitmap::load( correctPath );
  612. if ( bitmap != NULL )
  613. {
  614. realPath = bitmap.getPath();
  615. retTexObj = createTexture( bitmap, pathNoExt, profile, false );
  616. }
  617. }
  618. if ( retTexObj )
  619. {
  620. // Store the path for later use.
  621. retTexObj->mPath = realPath;
  622. // Register the texture file for change notifications.
  623. FS::AddChangeNotification( retTexObj->getPath(), this, &GFXTextureManager::_onFileChanged );
  624. }
  625. // Could put in a final check for 'retTexObj == NULL' here as an error message.
  626. return retTexObj;
  627. }
  628. GFXTextureObject *GFXTextureManager::createTexture( U32 width, U32 height, void *pixels, GFXFormat format, GFXTextureProfile *profile )
  629. {
  630. // For now, stuff everything into a GBitmap and pass it off... This may need to be revisited -- BJG
  631. GBitmap *bmp = new GBitmap(width, height, 0, format);
  632. dMemcpy(bmp->getWritableBits(), pixels, width * height * bmp->getBytesPerPixel());
  633. return createTexture( bmp, String::EmptyString, profile, true );
  634. }
  635. GFXTextureObject *GFXTextureManager::createTexture( U32 width, U32 height, GFXFormat format, GFXTextureProfile *profile, U32 numMipLevels, S32 antialiasLevel )
  636. {
  637. // Deal with sizing issues...
  638. U32 localWidth = width;
  639. U32 localHeight = height;
  640. // TODO: Format check HERE! -patw
  641. validateTextureQuality(profile, localWidth, localHeight);
  642. U32 numMips = numMipLevels;
  643. GFXFormat checkFmt = format;
  644. _validateTexParams( localWidth, localHeight, profile, numMips, checkFmt );
  645. AssertFatal( checkFmt == format, "Anonymous texture didn't get the format it wanted." );
  646. GFXTextureObject *outTex = NULL;
  647. // If this is a pooled profile then look there first.
  648. if ( profile->isPooled() )
  649. {
  650. outTex = _findPooledTexure( localWidth, localHeight, checkFmt,
  651. profile, numMips, antialiasLevel );
  652. // If we got a pooled texture then its
  653. // already setup... just return it.
  654. if ( outTex )
  655. return outTex;
  656. }
  657. // Create the texture if we didn't get one from the pool.
  658. if ( !outTex )
  659. {
  660. outTex = _createTextureObject( localHeight, localWidth, 0, format, profile, numMips, false, antialiasLevel );
  661. // Make sure we add it to the pool.
  662. if ( outTex && profile->isPooled() )
  663. mTexturePool.insertEqual( profile, outTex );
  664. }
  665. if ( !outTex )
  666. {
  667. Con::errorf("GFXTextureManager - failed to create anonymous texture.");
  668. return NULL;
  669. }
  670. // And do book-keeping...
  671. // - texture info
  672. outTex->mBitmapSize.set(localWidth, localHeight, 0);
  673. outTex->mAntialiasLevel = antialiasLevel;
  674. // PWTODO: Need to assign this a lookup name before _linkTexture() is called
  675. // otherwise it won't get a hash insert call
  676. _linkTexture( outTex );
  677. return outTex;
  678. }
  679. GFXTextureObject *GFXTextureManager::createTexture( U32 width,
  680. U32 height,
  681. U32 depth,
  682. void *pixels,
  683. GFXFormat format,
  684. GFXTextureProfile *profile )
  685. {
  686. PROFILE_SCOPE( GFXTextureManager_CreateTexture_3D );
  687. // Create texture...
  688. GFXTextureObject *ret = _createTextureObject( height, width, depth, format, profile, 1 );
  689. if(!ret)
  690. {
  691. Con::errorf("GFXTextureManager - failed to create anonymous texture.");
  692. return NULL;
  693. }
  694. // Call the internal load...
  695. if( !_loadTexture( ret, pixels ) )
  696. {
  697. Con::errorf("GFXTextureManager - failed to load volume texture" );
  698. return NULL;
  699. }
  700. // And do book-keeping...
  701. // - texture info
  702. ret->mBitmapSize.set( width, height, depth );
  703. _linkTexture( ret );
  704. // Return the new texture!
  705. return ret;
  706. }
  707. GFXTextureObject* GFXTextureManager::_findPooledTexure( U32 width,
  708. U32 height,
  709. GFXFormat format,
  710. GFXTextureProfile *profile,
  711. U32 numMipLevels,
  712. S32 antialiasLevel )
  713. {
  714. PROFILE_SCOPE( GFXTextureManager_FindPooledTexure );
  715. GFXTextureObject *outTex;
  716. // First see if we have a free one in the pool.
  717. TexturePoolMap::Iterator iter = mTexturePool.find( profile );
  718. for ( ; iter != mTexturePool.end() && iter->key == profile; iter++ )
  719. {
  720. outTex = iter->value;
  721. // If the reference count is 1 then we're the only
  722. // ones holding on to this texture and we can hand
  723. // it out if the size matches... else its in use.
  724. if ( outTex->getRefCount() != 1 )
  725. continue;
  726. // Check for a match... if so return it. The assignment
  727. // to a GFXTexHandle will take care of incrementing the
  728. // reference count and keeping it from being handed out
  729. // to anyone else.
  730. if ( outTex->getFormat() == format &&
  731. outTex->getWidth() == width &&
  732. outTex->getHeight() == height &&
  733. outTex->getMipLevels() == numMipLevels &&
  734. outTex->mAntialiasLevel == antialiasLevel )
  735. return outTex;
  736. }
  737. return NULL;
  738. }
  739. void GFXTextureManager::hashInsert( GFXTextureObject *object )
  740. {
  741. if ( object->mTextureLookupName.isEmpty() )
  742. return;
  743. U32 key = object->mTextureLookupName.getHashCaseInsensitive() % mHashCount;
  744. object->mHashNext = mHashTable[key];
  745. mHashTable[key] = object;
  746. }
  747. void GFXTextureManager::hashRemove( GFXTextureObject *object )
  748. {
  749. if ( object->mTextureLookupName.isEmpty() )
  750. return;
  751. U32 key = object->mTextureLookupName.getHashCaseInsensitive() % mHashCount;
  752. GFXTextureObject **walk = &mHashTable[key];
  753. while(*walk)
  754. {
  755. if(*walk == object)
  756. {
  757. *walk = object->mHashNext;
  758. break;
  759. }
  760. walk = &((*walk)->mHashNext);
  761. }
  762. }
  763. GFXTextureObject* GFXTextureManager::hashFind( const String &name )
  764. {
  765. if ( name.isEmpty() )
  766. return NULL;
  767. U32 key = name.getHashCaseInsensitive() % mHashCount;
  768. GFXTextureObject *walk = mHashTable[key];
  769. for(; walk; walk = walk->mHashNext)
  770. {
  771. if( walk->mTextureLookupName.equal( name, String::NoCase ) )
  772. break;
  773. }
  774. return walk;
  775. }
  776. void GFXTextureManager::freeTexture(GFXTextureObject *texture, bool zombify)
  777. {
  778. // Ok, let the backend deal with it.
  779. _freeTexture(texture, zombify);
  780. }
  781. void GFXTextureManager::refreshTexture(GFXTextureObject *texture)
  782. {
  783. _refreshTexture(texture);
  784. }
  785. void GFXTextureManager::_linkTexture( GFXTextureObject *obj )
  786. {
  787. // info for the profile
  788. GFXTextureProfile::updateStatsForCreation(obj);
  789. // info for the cache
  790. hashInsert(obj);
  791. // info for the master list
  792. if( mListHead == NULL )
  793. mListHead = obj;
  794. if( mListTail != NULL )
  795. mListTail->mNext = obj;
  796. obj->mPrev = mListTail;
  797. mListTail = obj;
  798. }
  799. void GFXTextureManager::deleteTexture( GFXTextureObject *texture )
  800. {
  801. if ( mTextureManagerState == GFXTextureManager::Dead )
  802. return;
  803. #ifdef DEBUG_SPEW
  804. Platform::outputDebugString( "[GFXTextureManager] deleteTexture '%s'",
  805. texture->mTextureLookupName.c_str()
  806. );
  807. #endif
  808. if( mListHead == texture )
  809. mListHead = texture->mNext;
  810. if( mListTail == texture )
  811. mListTail = texture->mPrev;
  812. hashRemove( texture );
  813. // If we have a path for the texture then
  814. // remove change notifications for it.
  815. Path texPath = texture->getPath();
  816. if ( !texPath.isEmpty() )
  817. FS::RemoveChangeNotification( texPath, this, &GFXTextureManager::_onFileChanged );
  818. GFXTextureProfile::updateStatsForDeletion(texture);
  819. freeTexture( texture );
  820. }
  821. void GFXTextureManager::_validateTexParams( const U32 width, const U32 height,
  822. const GFXTextureProfile *profile,
  823. U32 &inOutNumMips, GFXFormat &inOutFormat )
  824. {
  825. // Validate mipmap parameter. If this profile requests no mips, set mips to 1.
  826. if( profile->noMip() )
  827. {
  828. inOutNumMips = 1;
  829. }
  830. else if( !isPow2( width ) || !isPow2( height ) )
  831. {
  832. // If a texture is not power-of-2 in size for both dimensions, it must
  833. // have only 1 mip level.
  834. inOutNumMips = 1;
  835. }
  836. // Check format, and compatibility with texture profile requirements
  837. bool autoGenSupp = ( inOutNumMips == 0 );
  838. // If the format is non-compressed, and the profile requests a compressed format
  839. // than change the format.
  840. GFXFormat testingFormat = inOutFormat;
  841. if( profile->getCompression() != GFXTextureProfile::NONE )
  842. {
  843. const S32 offset = profile->getCompression() - GFXTextureProfile::DXT1;
  844. testingFormat = GFXFormat( GFXFormatDXT1 + offset );
  845. // No auto-gen mips on compressed textures
  846. autoGenSupp = false;
  847. }
  848. // inOutFormat is not modified by this method
  849. GFXCardProfiler* cardProfiler = GFX->getCardProfiler();
  850. bool chekFmt = cardProfiler->checkFormat(testingFormat, profile, autoGenSupp);
  851. if( !chekFmt )
  852. {
  853. // It tested for a compressed format, and didn't like it
  854. if( testingFormat != inOutFormat && profile->getCompression() )
  855. testingFormat = inOutFormat; // Reset to requested format, and try again
  856. // Trying again here, so reset autogen mip
  857. autoGenSupp = ( inOutNumMips == 0 );
  858. // Wow more weak sauce. There should be a better way to do this.
  859. switch( inOutFormat )
  860. {
  861. case GFXFormatR8G8B8:
  862. testingFormat = GFXFormatR8G8B8X8;
  863. chekFmt = cardProfiler->checkFormat(testingFormat, profile, autoGenSupp);
  864. break;
  865. case GFXFormatA8:
  866. testingFormat = GFXFormatR8G8B8A8;
  867. chekFmt = cardProfiler->checkFormat(testingFormat, profile, autoGenSupp);
  868. break;
  869. default:
  870. chekFmt = cardProfiler->checkFormat(testingFormat, profile, autoGenSupp);
  871. break;
  872. }
  873. }
  874. // Write back num mips that need to be generated by GBitmap
  875. if( !chekFmt )
  876. Con::errorf( "Format %s not supported with specified profile.", GFXStringTextureFormat[inOutFormat] );
  877. else
  878. {
  879. inOutFormat = testingFormat;
  880. // If auto gen mipmaps were requested, and they aren't supported for whatever
  881. // reason, than write out the number of mips that need to be generated.
  882. //
  883. // NOTE: Does this belong here?
  884. if( inOutNumMips == 0 && !autoGenSupp )
  885. {
  886. inOutNumMips = mFloor(mLog2(mMax(width, height))) + 1;
  887. }
  888. }
  889. }
  890. GFXCubemap* GFXTextureManager::createCubemap( const Torque::Path &path )
  891. {
  892. // Very first thing... check the cache.
  893. CubemapTable::Iterator iter = mCubemapTable.find( path.getFullPath() );
  894. if ( iter != mCubemapTable.end() )
  895. return iter->value;
  896. // Not in the cache... we have to load it ourselves.
  897. // First check for a DDS file.
  898. if ( !sDDSExt.equal( path.getExtension(), String::NoCase ) )
  899. {
  900. // At the moment we only support DDS cubemaps.
  901. return NULL;
  902. }
  903. const U32 scalePower = getTextureDownscalePower( NULL );
  904. // Ok... load the DDS file then.
  905. Resource<DDSFile> dds = DDSFile::load( path, scalePower );
  906. if ( !dds || !dds->isCubemap() )
  907. {
  908. // This wasn't a cubemap... give up too.
  909. return NULL;
  910. }
  911. // We loaded the cubemap dds, so now we create the GFXCubemap from it.
  912. GFXCubemap *cubemap = GFX->createCubemap();
  913. cubemap->initStatic( dds );
  914. cubemap->_setPath( path.getFullPath() );
  915. // Store the cubemap into the cache.
  916. mCubemapTable.insertUnique( path.getFullPath(), cubemap );
  917. return cubemap;
  918. }
  919. void GFXTextureManager::releaseCubemap( GFXCubemap *cubemap )
  920. {
  921. if ( mTextureManagerState == GFXTextureManager::Dead )
  922. return;
  923. const String &path = cubemap->getPath();
  924. CubemapTable::Iterator iter = mCubemapTable.find( path );
  925. if ( iter != mCubemapTable.end() && iter->value == cubemap )
  926. mCubemapTable.erase( iter );
  927. // If we have a path for the texture then
  928. // remove change notifications for it.
  929. //Path texPath = texture->getPath();
  930. //if ( !texPath.isEmpty() )
  931. //FS::RemoveChangeNotification( texPath, this, &GFXTextureManager::_onFileChanged );
  932. }
  933. void GFXTextureManager::_onFileChanged( const Torque::Path &path )
  934. {
  935. String pathNoExt = Torque::Path::Join( path.getRoot(), ':', path.getPath() );
  936. pathNoExt = Torque::Path::Join( pathNoExt, '/', path.getFileName() );
  937. // See if we've got it loaded.
  938. GFXTextureObject *obj = hashFind( pathNoExt );
  939. if ( !obj || path != obj->getPath() )
  940. return;
  941. Con::errorf( "[GFXTextureManager::_onFileChanged] : File changed [%s]", path.getFullPath().c_str() );
  942. const U32 scalePower = getTextureDownscalePower( obj->mProfile );
  943. if ( sDDSExt.equal( path.getExtension(), String::NoCase) )
  944. {
  945. Resource<DDSFile> dds = DDSFile::load( path, scalePower );
  946. if ( dds )
  947. _createTexture( dds, obj->mProfile, false, obj );
  948. }
  949. else
  950. {
  951. Resource<GBitmap> bmp = GBitmap::load( path );
  952. if( bmp )
  953. _createTexture( bmp, obj->mTextureLookupName, obj->mProfile, false, obj );
  954. }
  955. }
  956. void GFXTextureManager::reloadTextures()
  957. {
  958. GFXTextureObject *tex = mListHead;
  959. while ( tex != NULL )
  960. {
  961. const Torque::Path path( tex->mPath );
  962. if ( !path.isEmpty() )
  963. {
  964. const U32 scalePower = getTextureDownscalePower( tex->mProfile );
  965. if ( sDDSExt.equal( path.getExtension(), String::NoCase ) )
  966. {
  967. Resource<DDSFile> dds = DDSFile::load( path, scalePower );
  968. if ( dds )
  969. _createTexture( dds, tex->mProfile, false, tex );
  970. }
  971. else
  972. {
  973. Resource<GBitmap> bmp = GBitmap::load( path );
  974. if( bmp )
  975. _createTexture( bmp, tex->mTextureLookupName, tex->mProfile, false, tex );
  976. }
  977. }
  978. tex = tex->mNext;
  979. }
  980. }
  981. DefineEngineFunction( flushTextureCache, void, (),,
  982. "Releases all textures and resurrects the texture manager.\n"
  983. "@ingroup GFX\n" )
  984. {
  985. if ( !GFX || !TEXMGR )
  986. return;
  987. TEXMGR->zombify();
  988. TEXMGR->resurrect();
  989. }
  990. DefineEngineFunction( cleanupTexturePool, void, (),,
  991. "Release the unused pooled textures in texture manager freeing up video memory.\n"
  992. "@ingroup GFX\n" )
  993. {
  994. if ( !GFX || !TEXMGR )
  995. return;
  996. TEXMGR->cleanupPool();
  997. }
  998. DefineEngineFunction( reloadTextures, void, (),,
  999. "Reload all the textures from disk.\n"
  1000. "@ingroup GFX\n" )
  1001. {
  1002. if ( !GFX || !TEXMGR )
  1003. return;
  1004. TEXMGR->reloadTextures();
  1005. }