gfxTextureManager.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  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/imageUtils.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(Con::getVariable("$Core::MissingTexturePath"));
  39. String GFXTextureManager::smUnavailableTexturePath(Con::getVariable("$Core::UnAvailableTexturePath"));
  40. String GFXTextureManager::smWarningTexturePath(Con::getVariable("$Core::WarningTexturePath"));
  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. //compare just the profile flags and not the entire profile, names could be different but otherwise identical flags
  204. if (ret && (ret->mProfile->compareFlags(*profile)))
  205. return ret;
  206. else if (ret)
  207. Con::warnf("GFXTextureManager::_lookupTexture: Cached texture %s has a different profile flag", hashName);
  208. return NULL;
  209. }
  210. GFXTextureObject *GFXTextureManager::_lookupTexture( const DDSFile *ddsFile, const GFXTextureProfile *profile )
  211. {
  212. if( ddsFile->getTextureCacheString().isNotEmpty() )
  213. {
  214. // Call _lookupTexture()
  215. return _lookupTexture( ddsFile->getTextureCacheString(), profile );
  216. }
  217. return NULL;
  218. }
  219. GFXTextureObject *GFXTextureManager::createTexture( GBitmap *bmp, const String &resourceName, GFXTextureProfile *profile, bool deleteBmp )
  220. {
  221. AssertFatal(bmp, "GFXTextureManager::createTexture() - Got NULL bitmap!");
  222. GFXTextureObject *cacheHit = _lookupTexture( resourceName, profile );
  223. if( cacheHit != NULL)
  224. {
  225. // Con::errorf("Cached texture '%s'", (resourceName.isNotEmpty() ? resourceName.c_str() : "unknown"));
  226. if (deleteBmp)
  227. delete bmp;
  228. return cacheHit;
  229. }
  230. return _createTexture( bmp, resourceName, profile, deleteBmp, NULL );
  231. }
  232. GFXTextureObject *GFXTextureManager::_createTexture( GBitmap *bmp,
  233. const String &resourceName,
  234. GFXTextureProfile *profile,
  235. bool deleteBmp,
  236. GFXTextureObject *inObj )
  237. {
  238. PROFILE_SCOPE( GFXTextureManager_CreateTexture_Bitmap );
  239. #ifdef DEBUG_SPEW
  240. Platform::outputDebugString( "[GFXTextureManager] _createTexture (GBitmap) '%s'",
  241. resourceName.c_str()
  242. );
  243. #endif
  244. // Massage the bitmap based on any resize rules.
  245. U32 scalePower = getTextureDownscalePower( profile );
  246. GBitmap *realBmp = bmp;
  247. U32 realWidth = bmp->getWidth();
  248. U32 realHeight = bmp->getHeight();
  249. if ( scalePower &&
  250. isPow2(bmp->getWidth()) &&
  251. isPow2(bmp->getHeight()) &&
  252. profile->canDownscale() )
  253. {
  254. // We only work with power of 2 textures for now, so we
  255. // don't have to worry about padding.
  256. // We downscale the bitmap on the CPU... this is the reason
  257. // you should be using DDS which already has good looking mips.
  258. GBitmap *padBmp = bmp;
  259. padBmp->extrudeMipLevels();
  260. scalePower = getMin( scalePower, padBmp->getNumMipLevels() - 1 );
  261. realWidth = getMax( (U32)1, padBmp->getWidth() >> scalePower );
  262. realHeight = getMax( (U32)1, padBmp->getHeight() >> scalePower );
  263. realBmp = new GBitmap( realWidth, realHeight, false, bmp->getFormat() );
  264. // Copy to the new bitmap...
  265. dMemcpy( realBmp->getWritableBits(),
  266. padBmp->getBits(scalePower),
  267. padBmp->getBytesPerPixel() * realWidth * realHeight );
  268. // This line is commented out because createPaddedBitmap is commented out.
  269. // If that line is added back in, this line should be added back in.
  270. // delete padBmp;
  271. }
  272. // Call the internal create... (use the real* variables now, as they
  273. // reflect the reality of the texture we are creating.)
  274. U32 numMips = 0;
  275. GFXFormat realFmt = realBmp->getFormat();
  276. _validateTexParams( realWidth, realHeight, profile, numMips, realFmt );
  277. GFXTextureObject *ret;
  278. if ( inObj )
  279. {
  280. // If the texture has changed in dimensions
  281. // then we need to recreate it.
  282. if ( inObj->getWidth() != realWidth ||
  283. inObj->getHeight() != realHeight ||
  284. inObj->getFormat() != realFmt )
  285. ret = _createTextureObject( realHeight, realWidth, 0, realFmt, profile, numMips, false, 0, inObj );
  286. else
  287. ret = inObj;
  288. }
  289. else
  290. ret = _createTextureObject(realHeight, realWidth, 0, realFmt, profile, numMips );
  291. if(!ret)
  292. {
  293. Con::errorf("GFXTextureManager - failed to create texture (1) for '%s'", (resourceName.isNotEmpty() ? resourceName.c_str() : "unknown"));
  294. return NULL;
  295. }
  296. // Extrude mip levels
  297. // Don't do this for fonts!
  298. if( ret->mMipLevels > 1 && ( realBmp->getNumMipLevels() == 1 ) && ( realBmp->getFormat() != GFXFormatA8 ) &&
  299. isPow2( realBmp->getHeight() ) && isPow2( realBmp->getWidth() ) && !profile->noMip() )
  300. {
  301. // NOTE: This should really be done by extruding mips INTO a DDS file instead
  302. // of modifying the gbitmap
  303. realBmp->extrudeMipLevels(false);
  304. }
  305. // If _validateTexParams kicked back a different format, than there needs to be
  306. // a conversion unless it's a sRGB format
  307. DDSFile *bmpDDS = NULL;
  308. if( realBmp->getFormat() != realFmt && !profile->isSRGB() )
  309. {
  310. const GFXFormat oldFmt = realBmp->getFormat();
  311. // TODO: Set it up so that ALL format conversions use DDSFile. Rip format
  312. // switching out of GBitmap entirely.
  313. if( !realBmp->setFormat( realFmt ) )
  314. {
  315. // This is not the ideal implementation...
  316. bmpDDS = DDSFile::createDDSFileFromGBitmap( realBmp );
  317. bool convSuccess = false;
  318. if( bmpDDS != NULL )
  319. {
  320. // This shouldn't live here, I don't think
  321. switch( realFmt )
  322. {
  323. case GFXFormatBC1:
  324. case GFXFormatBC2:
  325. case GFXFormatBC3:
  326. // If this is a Normal Map profile, than the data needs to be conditioned
  327. // to use the swizzle trick
  328. if( ret->mProfile->getType() == GFXTextureProfile::NormalMap )
  329. {
  330. PROFILE_START(DXT_DXTNMSwizzle);
  331. static DXT5nmSwizzle sDXT5nmSwizzle;
  332. ImageUtil::swizzleDDS( bmpDDS, sDXT5nmSwizzle );
  333. PROFILE_END();
  334. }
  335. convSuccess = ImageUtil::ddsCompress( bmpDDS, realFmt );
  336. break;
  337. default:
  338. AssertFatal(false, "Attempting to convert to a non-DXT format");
  339. break;
  340. }
  341. }
  342. if( !convSuccess )
  343. {
  344. Con::errorf( "[GFXTextureManager]: Failed to change source format from %s to %s. Cannot create texture.",
  345. GFXStringTextureFormat[oldFmt], GFXStringTextureFormat[realFmt] );
  346. delete bmpDDS;
  347. return NULL;
  348. }
  349. }
  350. #ifdef TORQUE_DEBUG
  351. else
  352. {
  353. //Con::warnf( "[GFXTextureManager]: Changed bitmap format from %s to %s.",
  354. // GFXStringTextureFormat[oldFmt], GFXStringTextureFormat[realFmt] );
  355. }
  356. #endif
  357. }
  358. // Call the internal load...
  359. if( ( bmpDDS == NULL && !_loadTexture( ret, realBmp ) ) || // If we aren't doing a DDS format change, use bitmap load
  360. ( bmpDDS != NULL && !_loadTexture( ret, bmpDDS ) ) ) // If there is a DDS, than load that instead. A format change took place.
  361. {
  362. Con::errorf("GFXTextureManager - failed to load GBitmap for '%s'", (resourceName.isNotEmpty() ? resourceName.c_str() : "unknown"));
  363. return NULL;
  364. }
  365. // Do statistics and book-keeping...
  366. // - info for the texture...
  367. ret->mTextureLookupName = resourceName;
  368. ret->mBitmapSize.set(realWidth, realHeight,0);
  369. #ifdef TORQUE_DEBUG
  370. if (resourceName.isNotEmpty())
  371. ret->mDebugDescription = resourceName;
  372. else
  373. ret->mDebugDescription = "Anonymous Texture Object";
  374. #endif
  375. if(profile->doStoreBitmap())
  376. {
  377. // NOTE: may store a downscaled copy!
  378. SAFE_DELETE( ret->mBitmap );
  379. SAFE_DELETE( ret->mDDS );
  380. if( bmpDDS == NULL )
  381. ret->mBitmap = new GBitmap( *realBmp );
  382. else
  383. ret->mDDS = bmpDDS;
  384. }
  385. else
  386. {
  387. // Delete the DDS if we made one
  388. SAFE_DELETE( bmpDDS );
  389. }
  390. if ( !inObj )
  391. _linkTexture( ret );
  392. // - output debug info?
  393. // Save texture for debug purpose
  394. // static int texId = 0;
  395. // char buff[256];
  396. // dSprintf(buff, sizeof(buff), "tex_%d", texId++);
  397. // bmp->writePNGDebug(buff);
  398. // texId++;
  399. // Before we delete the bitmap save our transparency flag
  400. ret->mHasTransparency = realBmp->getHasTransparency();
  401. // Some final cleanup...
  402. if(realBmp != bmp)
  403. SAFE_DELETE(realBmp);
  404. if (deleteBmp)
  405. SAFE_DELETE(bmp);
  406. // Return the new texture!
  407. return ret;
  408. }
  409. GFXTextureObject *GFXTextureManager::createTexture( DDSFile *dds, GFXTextureProfile *profile, bool deleteDDS )
  410. {
  411. AssertFatal(dds, "GFXTextureManager::createTexture() - Got NULL dds!");
  412. // Check the cache first...
  413. GFXTextureObject *cacheHit = _lookupTexture( dds, profile );
  414. if ( cacheHit )
  415. {
  416. // Con::errorf("Cached texture '%s'", (fileName.isNotEmpty() ? fileName.c_str() : "unknown"));
  417. if( deleteDDS )
  418. delete dds;
  419. return cacheHit;
  420. }
  421. return _createTexture( dds, profile, deleteDDS, NULL );
  422. }
  423. GFXTextureObject *GFXTextureManager::_createTexture( DDSFile *dds,
  424. GFXTextureProfile *profile,
  425. bool deleteDDS,
  426. GFXTextureObject *inObj )
  427. {
  428. PROFILE_SCOPE( GFXTextureManager_CreateTexture_DDS );
  429. const char *fileName = dds->getTextureCacheString();
  430. if( !fileName )
  431. fileName = "unknown";
  432. #ifdef DEBUG_SPEW
  433. Platform::outputDebugString( "[GFXTextureManager] _createTexture (DDS) '%s'",
  434. fileName
  435. );
  436. #endif
  437. // Ignore padding from the profile.
  438. U32 numMips = dds->mMipMapCount;
  439. GFXFormat fmt = dds->mFormat;
  440. _validateTexParams( dds->getHeight(), dds->getWidth(), profile, numMips, fmt );
  441. if( fmt != dds->mFormat && !profile->isSRGB())
  442. {
  443. Con::errorf( "GFXTextureManager - failed to validate texture parameters for DDS file '%s'", fileName );
  444. return NULL;
  445. }
  446. // Call the internal create... (use the real* variables now, as they
  447. // reflect the reality of the texture we are creating.)
  448. GFXTextureObject *ret;
  449. if ( inObj )
  450. {
  451. // If the texture has changed in dimensions
  452. // then we need to recreate it.
  453. if ( inObj->getWidth() != dds->getWidth() ||
  454. inObj->getHeight() != dds->getHeight() ||
  455. inObj->getFormat() != fmt ||
  456. inObj->getMipLevels() != numMips )
  457. ret = _createTextureObject( dds->getHeight(), dds->getWidth(), 0,
  458. fmt, profile, numMips,
  459. true, 0, inObj );
  460. else
  461. ret = inObj;
  462. }
  463. else
  464. ret = _createTextureObject( dds->getHeight(), dds->getWidth(), 0,
  465. fmt, profile, numMips, true );
  466. if(!ret)
  467. {
  468. Con::errorf("GFXTextureManager - failed to create texture (1) for '%s' DDSFile.", fileName);
  469. return NULL;
  470. }
  471. // Call the internal load...
  472. if(!_loadTexture(ret, dds))
  473. {
  474. Con::errorf("GFXTextureManager - failed to load DDS for '%s'", fileName);
  475. return NULL;
  476. }
  477. // Do statistics and book-keeping...
  478. // - info for the texture...
  479. ret->mTextureLookupName = dds->getTextureCacheString();
  480. ret->mBitmapSize.set( dds->mWidth, dds->mHeight, 0 );
  481. #ifdef TORQUE_DEBUG
  482. ret->mDebugDescription = fileName;
  483. #endif
  484. if(profile->doStoreBitmap())
  485. {
  486. // NOTE: may store a downscaled copy!
  487. SAFE_DELETE( ret->mBitmap );
  488. SAFE_DELETE( ret->mDDS );
  489. ret->mDDS = new DDSFile( *dds );
  490. }
  491. if ( !inObj )
  492. _linkTexture( ret );
  493. // - output debug info?
  494. // Save texture for debug purpose
  495. // static int texId = 0;
  496. // char buff[256];
  497. // dSprintf(buff, sizeof(buff), "tex_%d", texId++);
  498. // bmp->writePNGDebug(buff);
  499. // texId++;
  500. // Save our transparency flag
  501. ret->mHasTransparency = dds->getHasTransparency();
  502. if( deleteDDS )
  503. delete dds;
  504. // Return the new texture!
  505. return ret;
  506. }
  507. GFXTextureObject *GFXTextureManager::createTexture( const Torque::Path &path, GFXTextureProfile *profile )
  508. {
  509. PROFILE_SCOPE( GFXTextureManager_createTexture );
  510. // Resource handles used for loading. Hold on to them
  511. // throughout this function so that change notifications
  512. // don't get added, then removed, and then re-added.
  513. Resource< DDSFile > dds;
  514. Resource< GBitmap > bitmap;
  515. // We need to handle path's that have had "incorrect"
  516. // extensions parsed out of the file name
  517. Torque::Path correctPath = validatePath(path);
  518. // Check the cache first...
  519. String pathNoExt = Torque::Path::Join( correctPath.getRoot(), ':', correctPath.getPath() );
  520. pathNoExt = Torque::Path::Join( pathNoExt, '/', correctPath.getFileName() );
  521. GFXTextureObject *retTexObj = _lookupTexture( pathNoExt, profile );
  522. if( retTexObj )
  523. return retTexObj;
  524. const U32 scalePower = getTextureDownscalePower( profile );
  525. // If this is a valid file (has an extension) than load it
  526. Path realPath;
  527. if( Torque::FS::IsFile( correctPath ) )
  528. {
  529. // Check for DDS
  530. if( sDDSExt.equal(correctPath.getExtension(), String::NoCase ) )
  531. {
  532. dds = DDSFile::load( correctPath, scalePower );
  533. if( dds != NULL )
  534. {
  535. realPath = dds.getPath();
  536. retTexObj = createTexture( dds, profile, false );
  537. }
  538. }
  539. else // Let GBitmap take care of it
  540. {
  541. bitmap = GBitmap::load( correctPath );
  542. if( bitmap != NULL )
  543. {
  544. realPath = bitmap.getPath();
  545. retTexObj = createTexture( bitmap, pathNoExt, profile, false );
  546. }
  547. }
  548. }
  549. else
  550. {
  551. // NOTE -- We should probably remove the code from GBitmap that tries different
  552. // extensions for things GBitmap loads, and move it here. I think it should
  553. // be a bit more involved than just a list of extensions. Some kind of
  554. // extension registration thing, maybe.
  555. // Check to see if there is a .DDS file with this name (if no extension is provided)
  556. Torque::Path tryDDSPath = pathNoExt;
  557. if( tryDDSPath.getExtension().isNotEmpty() )
  558. tryDDSPath.setFileName( tryDDSPath.getFullFileName() );
  559. tryDDSPath.setExtension( sDDSExt );
  560. if( Torque::FS::IsFile( tryDDSPath ) )
  561. {
  562. dds = DDSFile::load( tryDDSPath, scalePower );
  563. if( dds != NULL )
  564. {
  565. realPath = dds.getPath();
  566. retTexObj = createTexture( dds, profile, false );
  567. }
  568. }
  569. // Otherwise, retTexObj stays NULL, and fall through to the generic GBitmap
  570. // load.
  571. }
  572. // If we still don't have a texture object yet, feed the correctPath to GBitmap and
  573. // it will try a bunch of extensions
  574. if( retTexObj == NULL )
  575. {
  576. // Find and load the texture.
  577. bitmap = GBitmap::load( correctPath );
  578. if ( bitmap != NULL )
  579. {
  580. realPath = bitmap.getPath();
  581. retTexObj = createTexture( bitmap, pathNoExt, profile, false );
  582. }
  583. }
  584. if ( retTexObj )
  585. {
  586. // Store the path for later use.
  587. retTexObj->mPath = realPath;
  588. // Register the texture file for change notifications.
  589. FS::AddChangeNotification( retTexObj->getPath(), this, &GFXTextureManager::_onFileChanged );
  590. }
  591. // Could put in a final check for 'retTexObj == NULL' here as an error message.
  592. return retTexObj;
  593. }
  594. GFXTextureObject *GFXTextureManager::createTexture( U32 width, U32 height, void *pixels, GFXFormat format, GFXTextureProfile *profile )
  595. {
  596. // For now, stuff everything into a GBitmap and pass it off... This may need to be revisited -- BJG
  597. GBitmap *bmp = new GBitmap(width, height, 0, format);
  598. dMemcpy(bmp->getWritableBits(), pixels, width * height * bmp->getBytesPerPixel());
  599. return createTexture( bmp, String::EmptyString, profile, true );
  600. }
  601. GFXTextureObject *GFXTextureManager::createTexture( U32 width, U32 height, GFXFormat format, GFXTextureProfile *profile, U32 numMipLevels, S32 antialiasLevel )
  602. {
  603. // Deal with sizing issues...
  604. U32 localWidth = width;
  605. U32 localHeight = height;
  606. // TODO: Format check HERE! -patw
  607. validateTextureQuality(profile, localWidth, localHeight);
  608. U32 numMips = numMipLevels;
  609. GFXFormat checkFmt = format;
  610. _validateTexParams( localWidth, localHeight, profile, numMips, checkFmt );
  611. // AssertFatal( checkFmt == format, "Anonymous texture didn't get the format it wanted." );
  612. GFXTextureObject *outTex = NULL;
  613. // If this is a pooled profile then look there first.
  614. if ( profile->isPooled() )
  615. {
  616. outTex = _findPooledTexure( localWidth, localHeight, checkFmt,
  617. profile, numMips, antialiasLevel );
  618. // If we got a pooled texture then its
  619. // already setup... just return it.
  620. if ( outTex )
  621. return outTex;
  622. }
  623. // Create the texture if we didn't get one from the pool.
  624. if ( !outTex )
  625. {
  626. outTex = _createTextureObject( localHeight, localWidth, 0, format, profile, numMips, false, antialiasLevel );
  627. // Make sure we add it to the pool.
  628. if ( outTex && profile->isPooled() )
  629. mTexturePool.insertEqual( profile, outTex );
  630. }
  631. if ( !outTex )
  632. {
  633. Con::errorf("GFXTextureManager - failed to create anonymous texture.");
  634. return NULL;
  635. }
  636. // And do book-keeping...
  637. // - texture info
  638. outTex->mBitmapSize.set(localWidth, localHeight, 0);
  639. outTex->mAntialiasLevel = antialiasLevel;
  640. // PWTODO: Need to assign this a lookup name before _linkTexture() is called
  641. // otherwise it won't get a hash insert call
  642. _linkTexture( outTex );
  643. return outTex;
  644. }
  645. GFXTextureObject *GFXTextureManager::createTexture( U32 width,
  646. U32 height,
  647. U32 depth,
  648. void *pixels,
  649. GFXFormat format,
  650. GFXTextureProfile *profile,
  651. U32 numMipLevels)
  652. {
  653. PROFILE_SCOPE( GFXTextureManager_CreateTexture_3D );
  654. // Create texture...
  655. GFXTextureObject *ret = _createTextureObject( height, width, depth, format, profile, numMipLevels );
  656. if(!ret)
  657. {
  658. Con::errorf("GFXTextureManager - failed to create anonymous texture.");
  659. return NULL;
  660. }
  661. // Call the internal load...
  662. if( !_loadTexture( ret, pixels ) )
  663. {
  664. Con::errorf("GFXTextureManager - failed to load volume texture" );
  665. return NULL;
  666. }
  667. // And do book-keeping...
  668. // - texture info
  669. ret->mBitmapSize.set( width, height, depth );
  670. _linkTexture( ret );
  671. // Return the new texture!
  672. return ret;
  673. }
  674. Torque::Path GFXTextureManager::validatePath(const Torque::Path &path)
  675. {
  676. // We need to handle path's that have had "incorrect"
  677. // extensions parsed out of the file name
  678. Torque::Path correctPath = path;
  679. bool textureExt = false;
  680. // Easiest case to handle is when there isn't an extension
  681. if (path.getExtension().isEmpty())
  682. textureExt = true;
  683. // Since "dds" isn't registered with GBitmap currently we
  684. // have to test it separately
  685. if (sDDSExt.equal(path.getExtension(), String::NoCase))
  686. textureExt = true;
  687. // Now loop through the rest of the GBitmap extensions
  688. // to see if we have any matches
  689. for (U32 i = 0; i < GBitmap::sRegistrations.size(); i++)
  690. {
  691. // If we have gotten a match (either in this loop or before)
  692. // then we can exit
  693. if (textureExt)
  694. break;
  695. const GBitmap::Registration &reg = GBitmap::sRegistrations[i];
  696. const Vector<String> &extensions = reg.extensions;
  697. for (U32 j = 0; j < extensions.size(); ++j)
  698. {
  699. if (extensions[j].equal(path.getExtension(), String::NoCase))
  700. {
  701. // Found a valid texture extension
  702. textureExt = true;
  703. break;
  704. }
  705. }
  706. }
  707. // If we didn't find a valid texture extension then assume that
  708. // the parsed out "extension" was actually intended to be part of
  709. // the texture name so add it back
  710. if (!textureExt)
  711. {
  712. correctPath.setFileName(Torque::Path::Join(path.getFileName(), '.', path.getExtension()));
  713. correctPath.setExtension(String::EmptyString);
  714. }
  715. return correctPath;
  716. }
  717. GBitmap *GFXTextureManager::loadUncompressedTexture(const Torque::Path &path, GFXTextureProfile *profile)
  718. {
  719. PROFILE_SCOPE(GFXTextureManager_loadUncompressedTexture);
  720. GBitmap *retBitmap = NULL;
  721. // Resource handles used for loading. Hold on to them
  722. // throughout this function so that change notifications
  723. // don't get added, then removed, and then re-added.
  724. Resource< DDSFile > dds;
  725. Resource< GBitmap > bitmap;
  726. // We need to handle path's that have had "incorrect"
  727. // extensions parsed out of the file name
  728. Torque::Path correctPath = validatePath(path);
  729. U32 scalePower = profile ? getTextureDownscalePower(profile) : 0;
  730. // Check the cache first...
  731. String pathNoExt = Torque::Path::Join(correctPath.getRoot(), ':', correctPath.getPath());
  732. pathNoExt = Torque::Path::Join(pathNoExt, '/', correctPath.getFileName());
  733. // If this is a valid file (has an extension) than load it
  734. Path realPath;
  735. if (Torque::FS::IsFile(correctPath))
  736. {
  737. PROFILE_SCOPE(GFXTextureManager_loadUncompressedTexture_INNNER1)
  738. // Check for DDS
  739. if (sDDSExt.equal(correctPath.getExtension(), String::NoCase))
  740. {
  741. dds = DDSFile::load(correctPath, scalePower);
  742. if (dds != NULL)
  743. {
  744. realPath = dds.getPath();
  745. retBitmap = new GBitmap();
  746. if (!dds->decompressToGBitmap(retBitmap))
  747. {
  748. delete retBitmap;
  749. retBitmap = NULL;
  750. }
  751. }
  752. }
  753. else // Let GBitmap take care of it
  754. {
  755. bitmap = GBitmap::load(correctPath);
  756. if (bitmap != NULL)
  757. {
  758. realPath = bitmap.getPath();
  759. retBitmap = new GBitmap(*bitmap);
  760. if (scalePower &&
  761. isPow2(retBitmap->getWidth()) &&
  762. isPow2(retBitmap->getHeight()) &&
  763. profile->canDownscale())
  764. {
  765. retBitmap->extrudeMipLevels();
  766. retBitmap->chopTopMips(scalePower);
  767. }
  768. }
  769. }
  770. }
  771. else
  772. {
  773. PROFILE_SCOPE(GFXTextureManager_loadUncompressedTexture_INNNER2)
  774. // NOTE -- We should probably remove the code from GBitmap that tries different
  775. // extensions for things GBitmap loads, and move it here. I think it should
  776. // be a bit more involved than just a list of extensions. Some kind of
  777. // extension registration thing, maybe.
  778. // Check to see if there is a .DDS file with this name (if no extension is provided)
  779. Torque::Path tryDDSPath = pathNoExt;
  780. if (tryDDSPath.getExtension().isNotEmpty())
  781. tryDDSPath.setFileName(tryDDSPath.getFullFileName());
  782. tryDDSPath.setExtension(sDDSExt);
  783. if (Torque::FS::IsFile(tryDDSPath))
  784. {
  785. dds = DDSFile::load(tryDDSPath, scalePower);
  786. if (dds != NULL)
  787. {
  788. realPath = dds.getPath();
  789. // Decompress dds into the GBitmap
  790. retBitmap = new GBitmap();
  791. if (!dds->decompressToGBitmap(retBitmap))
  792. {
  793. delete retBitmap;
  794. retBitmap = NULL;
  795. }
  796. }
  797. }
  798. // Otherwise, retTexObj stays NULL, and fall through to the generic GBitmap
  799. // load.
  800. }
  801. // If we still don't have a texture object yet, feed the correctPath to GBitmap and
  802. // it will try a bunch of extensions
  803. if (retBitmap == NULL)
  804. {
  805. PROFILE_SCOPE(GFXTextureManager_loadUncompressedTexture_INNNER3)
  806. // Find and load the texture.
  807. bitmap = GBitmap::load(correctPath);
  808. if (bitmap != NULL)
  809. {
  810. retBitmap = new GBitmap(*bitmap);
  811. if (scalePower &&
  812. isPow2(retBitmap->getWidth()) &&
  813. isPow2(retBitmap->getHeight()) &&
  814. profile->canDownscale())
  815. {
  816. retBitmap->extrudeMipLevels();
  817. retBitmap->chopTopMips(scalePower);
  818. }
  819. }
  820. }
  821. return retBitmap;
  822. }
  823. GFXTextureObject *GFXTextureManager::createCompositeTexture(const Torque::Path &pathR, const Torque::Path &pathG, const Torque::Path &pathB, const Torque::Path &pathA, U32 inputKey[4],
  824. GFXTextureProfile *profile)
  825. {
  826. PROFILE_SCOPE(GFXTextureManager_createCompositeTexture);
  827. String inputKeyStr = String::ToString("%d%d%d%d", inputKey[0], inputKey[1], inputKey[2], inputKey[3]);
  828. String resourceTag = pathR.getFileName() + pathG.getFileName() + pathB.getFileName() + pathA.getFileName() + inputKeyStr; //associate texture object with a key combo
  829. GFXTextureObject *cacheHit = _lookupTexture(resourceTag, profile);
  830. if (cacheHit != NULL) return cacheHit;
  831. GBitmap*bitmap[4];
  832. bitmap[0] = loadUncompressedTexture(pathR, profile);
  833. if (!pathG.isEmpty())
  834. bitmap[1] = loadUncompressedTexture(pathG, profile);
  835. else
  836. bitmap[1] = NULL;
  837. if (!pathB.isEmpty())
  838. bitmap[2] = loadUncompressedTexture(pathB, profile);
  839. else
  840. bitmap[2] = NULL;
  841. if (!pathA.isEmpty())
  842. bitmap[3] = loadUncompressedTexture(pathA, profile);
  843. else
  844. bitmap[3] = NULL;
  845. Path realPath;
  846. GFXTextureObject *retTexObj = NULL;
  847. realPath = validatePath(pathR); //associate path with r channel texture in.
  848. retTexObj = createCompositeTexture(bitmap, inputKey, resourceTag, profile, false);
  849. if (retTexObj)
  850. {
  851. // Store the path for later use.
  852. retTexObj->mPath = resourceTag;
  853. // Register the texture file for change notifications.
  854. FS::AddChangeNotification(retTexObj->getPath(), this, &GFXTextureManager::_onFileChanged);
  855. }
  856. // Could put in a final check for 'retTexObj == NULL' here as an error message.
  857. for (U32 i = 0; i < 4; i++)
  858. {
  859. if (bitmap[i])
  860. {
  861. bitmap[i]->deleteImage();
  862. delete bitmap[i];
  863. }
  864. }
  865. return retTexObj;
  866. }
  867. void GFXTextureManager::saveCompositeTexture(const Torque::Path &pathR, const Torque::Path &pathG, const Torque::Path &pathB, const Torque::Path &pathA, U32 inputKey[4],
  868. const Torque::Path &saveAs,GFXTextureProfile *profile)
  869. {
  870. PROFILE_SCOPE(GFXTextureManager_saveCompositeTexture);
  871. String inputKeyStr = String::ToString("%d%d%d%d", inputKey[0], inputKey[1], inputKey[2], inputKey[3]);
  872. String resourceTag = pathR.getFileName() + pathG.getFileName() + pathB.getFileName() + pathA.getFileName() + inputKeyStr; //associate texture object with a key combo
  873. GFXTextureObject *cacheHit = _lookupTexture(resourceTag, profile);
  874. if (cacheHit != NULL)
  875. {
  876. cacheHit->dumpToDisk("png", saveAs.getFullPath());
  877. return;
  878. }
  879. GBitmap*bitmap[4];
  880. bitmap[0] = loadUncompressedTexture(pathR, profile);
  881. if (!pathG.isEmpty())
  882. bitmap[1] = loadUncompressedTexture(pathG, profile);
  883. else
  884. bitmap[1] = NULL;
  885. if (!pathB.isEmpty())
  886. bitmap[2] = loadUncompressedTexture(pathB, profile);
  887. else
  888. bitmap[2] = NULL;
  889. if (!pathA.isEmpty())
  890. bitmap[3] = loadUncompressedTexture(pathA, profile);
  891. else
  892. bitmap[3] = NULL;
  893. Path realPath;
  894. GFXTextureObject *retTexObj = NULL;
  895. realPath = validatePath(pathR); //associate path with r channel texture in.
  896. retTexObj = createCompositeTexture(bitmap, inputKey, resourceTag, profile, false);
  897. if (retTexObj != NULL)
  898. retTexObj->dumpToDisk("png", saveAs.getFullPath());
  899. return;
  900. }
  901. DefineEngineFunction(saveCompositeTexture, void, (const char* pathR, const char* pathG, const char* pathB, const char* pathA,
  902. const char * inputKeyString, const char* saveAs),
  903. ("", "", "", "", "", ""), "File1,file2,file3,file4,[chanels for r g b and a locations],saveAs")
  904. {
  905. U32 inputKey[4] = {0,0,0,0};
  906. if (dStrcmp(inputKeyString, "") != 0)
  907. {
  908. dSscanf(inputKeyString, "%i %i %i %i", &inputKey[0], &inputKey[1], &inputKey[2], &inputKey[3]);
  909. }
  910. GFX->getTextureManager()->saveCompositeTexture(pathR, pathG, pathB, pathA, inputKey, saveAs, &GFXTexturePersistentProfile);
  911. }
  912. GFXTextureObject *GFXTextureManager::createCompositeTexture(GBitmap*bmp[4], U32 inputKey[4],
  913. const String &resourceName, GFXTextureProfile *profile, bool deleteBmp)
  914. {
  915. if (!bmp[0])
  916. {
  917. Con::errorf(ConsoleLogEntry::General, "GFXTextureManager::createCompositeTexture() - Got NULL bitmap(R)!");
  918. return NULL;
  919. }
  920. U8 rChan, gChan, bChan, aChan;
  921. GBitmap *outBitmap = new GBitmap();
  922. outBitmap->allocateBitmap(bmp[0]->getWidth(), bmp[0]->getHeight(),false, GFXFormatR8G8B8A8);
  923. //pack additional bitmaps into the origional
  924. for (U32 x = 0; x < bmp[0]->getWidth(); x++)
  925. {
  926. for (U32 y = 0; y < bmp[0]->getHeight(); y++)
  927. {
  928. rChan = bmp[0]->getChanelValueAt(x, y, inputKey[0]);
  929. if (bmp[1])
  930. gChan = bmp[1]->getChanelValueAt(x, y, inputKey[1]);
  931. else
  932. gChan = 255;
  933. if (bmp[2])
  934. bChan = bmp[2]->getChanelValueAt(x, y, inputKey[2]);
  935. else
  936. bChan = 255;
  937. if (bmp[3])
  938. aChan = bmp[3]->getChanelValueAt(x, y, inputKey[3]);
  939. else
  940. aChan = 255;
  941. outBitmap->setColor(x, y, ColorI(rChan, gChan, bChan, aChan));
  942. }
  943. }
  944. GFXTextureObject *cacheHit = _lookupTexture(resourceName, profile);
  945. if (cacheHit != NULL)
  946. {
  947. // Con::errorf("Cached texture '%s'", (resourceName.isNotEmpty() ? resourceName.c_str() : "unknown"));
  948. if (deleteBmp)
  949. {
  950. delete outBitmap;
  951. delete[] bmp;
  952. }
  953. return cacheHit;
  954. }
  955. return _createTexture(outBitmap, resourceName, profile, deleteBmp, NULL);
  956. }
  957. GFXTextureObject* GFXTextureManager::_findPooledTexure( U32 width,
  958. U32 height,
  959. GFXFormat format,
  960. GFXTextureProfile *profile,
  961. U32 numMipLevels,
  962. S32 antialiasLevel )
  963. {
  964. PROFILE_SCOPE( GFXTextureManager_FindPooledTexure );
  965. GFXTextureObject *outTex;
  966. // First see if we have a free one in the pool.
  967. TexturePoolMap::Iterator iter = mTexturePool.find( profile );
  968. for ( ; iter != mTexturePool.end() && iter->key == profile; iter++ )
  969. {
  970. outTex = iter->value;
  971. // If the reference count is 1 then we're the only
  972. // ones holding on to this texture and we can hand
  973. // it out if the size matches... else its in use.
  974. if ( outTex->getRefCount() != 1 )
  975. continue;
  976. // Check for a match... if so return it. The assignment
  977. // to a GFXTexHandle will take care of incrementing the
  978. // reference count and keeping it from being handed out
  979. // to anyone else.
  980. if ( outTex->getFormat() == format &&
  981. outTex->getWidth() == width &&
  982. outTex->getHeight() == height &&
  983. outTex->getMipLevels() == numMipLevels &&
  984. outTex->mAntialiasLevel == antialiasLevel )
  985. return outTex;
  986. }
  987. return NULL;
  988. }
  989. void GFXTextureManager::hashInsert( GFXTextureObject *object )
  990. {
  991. if ( object->mTextureLookupName.isEmpty() )
  992. return;
  993. U32 key = object->mTextureLookupName.getHashCaseInsensitive() % mHashCount;
  994. object->mHashNext = mHashTable[key];
  995. mHashTable[key] = object;
  996. }
  997. void GFXTextureManager::hashRemove( GFXTextureObject *object )
  998. {
  999. if ( object->mTextureLookupName.isEmpty() )
  1000. return;
  1001. U32 key = object->mTextureLookupName.getHashCaseInsensitive() % mHashCount;
  1002. GFXTextureObject **walk = &mHashTable[key];
  1003. while(*walk)
  1004. {
  1005. if(*walk == object)
  1006. {
  1007. *walk = object->mHashNext;
  1008. break;
  1009. }
  1010. walk = &((*walk)->mHashNext);
  1011. }
  1012. }
  1013. GFXTextureObject* GFXTextureManager::hashFind( const String &name )
  1014. {
  1015. if ( name.isEmpty() )
  1016. return NULL;
  1017. U32 key = name.getHashCaseInsensitive() % mHashCount;
  1018. GFXTextureObject *walk = mHashTable[key];
  1019. for(; walk; walk = walk->mHashNext)
  1020. {
  1021. if( walk->mTextureLookupName.equal( name, String::NoCase ) )
  1022. break;
  1023. }
  1024. return walk;
  1025. }
  1026. void GFXTextureManager::freeTexture(GFXTextureObject *texture, bool zombify)
  1027. {
  1028. // Ok, let the backend deal with it.
  1029. _freeTexture(texture, zombify);
  1030. }
  1031. void GFXTextureManager::refreshTexture(GFXTextureObject *texture)
  1032. {
  1033. _refreshTexture(texture);
  1034. }
  1035. void GFXTextureManager::_linkTexture( GFXTextureObject *obj )
  1036. {
  1037. // info for the profile
  1038. GFXTextureProfile::updateStatsForCreation(obj);
  1039. // info for the cache
  1040. hashInsert(obj);
  1041. // info for the master list
  1042. if( mListHead == NULL )
  1043. mListHead = obj;
  1044. if( mListTail != NULL )
  1045. mListTail->mNext = obj;
  1046. obj->mPrev = mListTail;
  1047. mListTail = obj;
  1048. }
  1049. void GFXTextureManager::deleteTexture( GFXTextureObject *texture )
  1050. {
  1051. if ( mTextureManagerState == GFXTextureManager::Dead )
  1052. return;
  1053. #ifdef DEBUG_SPEW
  1054. Platform::outputDebugString( "[GFXTextureManager] deleteTexture '%s'",
  1055. texture->mTextureLookupName.c_str()
  1056. );
  1057. #endif
  1058. if( mListHead == texture )
  1059. mListHead = texture->mNext;
  1060. if( mListTail == texture )
  1061. mListTail = texture->mPrev;
  1062. hashRemove( texture );
  1063. // If we have a path for the texture then
  1064. // remove change notifications for it.
  1065. Path texPath = texture->getPath();
  1066. if ( !texPath.isEmpty() )
  1067. FS::RemoveChangeNotification( texPath, this, &GFXTextureManager::_onFileChanged );
  1068. GFXTextureProfile::updateStatsForDeletion(texture);
  1069. freeTexture( texture );
  1070. }
  1071. void GFXTextureManager::_validateTexParams( const U32 width, const U32 height,
  1072. const GFXTextureProfile *profile,
  1073. U32 &inOutNumMips, GFXFormat &inOutFormat )
  1074. {
  1075. // Validate mipmap parameter. If this profile requests no mips, set mips to 1.
  1076. if( profile->noMip() )
  1077. {
  1078. inOutNumMips = 1;
  1079. }
  1080. else if( !isPow2( width ) || !isPow2( height ) )
  1081. {
  1082. // If a texture is not power-of-2 in size for both dimensions, it must
  1083. // have only 1 mip level.
  1084. inOutNumMips = 1;
  1085. }
  1086. // Check format, and compatibility with texture profile requirements
  1087. bool autoGenSupp = ( inOutNumMips == 0 );
  1088. // If the format is non-compressed, and the profile requests a compressed format
  1089. // than change the format.
  1090. GFXFormat testingFormat = inOutFormat;
  1091. if( profile->getCompression() != GFXTextureProfile::NONE )
  1092. {
  1093. const S32 offset = profile->getCompression() - GFXTextureProfile::BC1;
  1094. testingFormat = GFXFormat( GFXFormatBC1 + offset );
  1095. // No auto-gen mips on compressed textures
  1096. autoGenSupp = false;
  1097. }
  1098. if (profile->isSRGB())
  1099. testingFormat = ImageUtil::toSRGBFormat(testingFormat);
  1100. // inOutFormat is not modified by this method
  1101. GFXCardProfiler* cardProfiler = GFX->getCardProfiler();
  1102. bool chekFmt = cardProfiler->checkFormat(testingFormat, profile, autoGenSupp);
  1103. if( !chekFmt )
  1104. {
  1105. // It tested for a compressed format, and didn't like it
  1106. if( testingFormat != inOutFormat && profile->getCompression() )
  1107. testingFormat = inOutFormat; // Reset to requested format, and try again
  1108. // Trying again here, so reset autogen mip
  1109. autoGenSupp = ( inOutNumMips == 0 );
  1110. // Wow more weak sauce. There should be a better way to do this.
  1111. switch( inOutFormat )
  1112. {
  1113. case GFXFormatR8G8B8:
  1114. testingFormat = GFXFormatR8G8B8X8;
  1115. chekFmt = cardProfiler->checkFormat(testingFormat, profile, autoGenSupp);
  1116. break;
  1117. case GFXFormatA8:
  1118. testingFormat = GFXFormatR8G8B8A8;
  1119. chekFmt = cardProfiler->checkFormat(testingFormat, profile, autoGenSupp);
  1120. break;
  1121. default:
  1122. chekFmt = cardProfiler->checkFormat(testingFormat, profile, autoGenSupp);
  1123. break;
  1124. }
  1125. }
  1126. // Write back num mips that need to be generated by GBitmap
  1127. if( !chekFmt )
  1128. Con::errorf( "Format %s not supported with specified profile.", GFXStringTextureFormat[inOutFormat] );
  1129. else
  1130. {
  1131. inOutFormat = testingFormat;
  1132. // If auto gen mipmaps were requested, and they aren't supported for whatever
  1133. // reason, than write out the number of mips that need to be generated.
  1134. //
  1135. // NOTE: Does this belong here?
  1136. if( inOutNumMips == 0 && !autoGenSupp )
  1137. {
  1138. inOutNumMips = mFloor(mLog2(mMax(width, height))) + 1;
  1139. }
  1140. }
  1141. }
  1142. GFXCubemap* GFXTextureManager::createCubemap( const Torque::Path &path )
  1143. {
  1144. // Very first thing... check the cache.
  1145. CubemapTable::Iterator iter = mCubemapTable.find( path.getFullPath() );
  1146. if ( iter != mCubemapTable.end() )
  1147. return iter->value;
  1148. // Not in the cache... we have to load it ourselves.
  1149. // First check for a DDS file.
  1150. if ( !sDDSExt.equal( path.getExtension(), String::NoCase ) )
  1151. {
  1152. // At the moment we only support DDS cubemaps.
  1153. return NULL;
  1154. }
  1155. const U32 scalePower = getTextureDownscalePower( NULL );
  1156. // Ok... load the DDS file then.
  1157. Resource<DDSFile> dds = DDSFile::load( path, scalePower );
  1158. if ( !dds || !dds->isCubemap() )
  1159. {
  1160. // This wasn't a cubemap... give up too.
  1161. return NULL;
  1162. }
  1163. // We loaded the cubemap dds, so now we create the GFXCubemap from it.
  1164. GFXCubemap *cubemap = GFX->createCubemap();
  1165. cubemap->initStatic( dds );
  1166. cubemap->_setPath( path.getFullPath() );
  1167. // Store the cubemap into the cache.
  1168. mCubemapTable.insertUnique( path.getFullPath(), cubemap );
  1169. return cubemap;
  1170. }
  1171. void GFXTextureManager::releaseCubemap( GFXCubemap *cubemap )
  1172. {
  1173. if ( mTextureManagerState == GFXTextureManager::Dead )
  1174. return;
  1175. const String &path = cubemap->getPath();
  1176. CubemapTable::Iterator iter = mCubemapTable.find( path );
  1177. if ( iter != mCubemapTable.end() && iter->value == cubemap )
  1178. mCubemapTable.erase( iter );
  1179. // If we have a path for the texture then
  1180. // remove change notifications for it.
  1181. //Path texPath = texture->getPath();
  1182. //if ( !texPath.isEmpty() )
  1183. //FS::RemoveChangeNotification( texPath, this, &GFXTextureManager::_onFileChanged );
  1184. }
  1185. void GFXTextureManager::_onFileChanged( const Torque::Path &path )
  1186. {
  1187. String pathNoExt = Torque::Path::Join( path.getRoot(), ':', path.getPath() );
  1188. pathNoExt = Torque::Path::Join( pathNoExt, '/', path.getFileName() );
  1189. // See if we've got it loaded.
  1190. GFXTextureObject *obj = hashFind( pathNoExt );
  1191. if ( !obj || path != obj->getPath() )
  1192. return;
  1193. Con::errorf( "[GFXTextureManager::_onFileChanged] : File changed [%s]", path.getFullPath().c_str() );
  1194. const U32 scalePower = getTextureDownscalePower( obj->mProfile );
  1195. if ( sDDSExt.equal( path.getExtension(), String::NoCase) )
  1196. {
  1197. Resource<DDSFile> dds = DDSFile::load( path, scalePower );
  1198. if ( dds )
  1199. _createTexture( dds, obj->mProfile, false, obj );
  1200. }
  1201. else
  1202. {
  1203. Resource<GBitmap> bmp = GBitmap::load( path );
  1204. if( bmp )
  1205. _createTexture( bmp, obj->mTextureLookupName, obj->mProfile, false, obj );
  1206. }
  1207. }
  1208. void GFXTextureManager::reloadTextures()
  1209. {
  1210. GFXTextureObject *tex = mListHead;
  1211. while ( tex != NULL )
  1212. {
  1213. const Torque::Path path( tex->mPath );
  1214. if ( !path.isEmpty() )
  1215. {
  1216. const U32 scalePower = getTextureDownscalePower( tex->mProfile );
  1217. if ( sDDSExt.equal( path.getExtension(), String::NoCase ) )
  1218. {
  1219. Resource<DDSFile> dds = DDSFile::load( path, scalePower );
  1220. if ( dds )
  1221. _createTexture( dds, tex->mProfile, false, tex );
  1222. }
  1223. else
  1224. {
  1225. Resource<GBitmap> bmp = GBitmap::load( path );
  1226. if( bmp )
  1227. _createTexture( bmp, tex->mTextureLookupName, tex->mProfile, false, tex );
  1228. }
  1229. }
  1230. tex = tex->mNext;
  1231. }
  1232. }
  1233. DefineEngineFunction( flushTextureCache, void, (),,
  1234. "Releases all textures and resurrects the texture manager.\n"
  1235. "@ingroup GFX\n" )
  1236. {
  1237. if ( !GFX || !TEXMGR )
  1238. return;
  1239. TEXMGR->zombify();
  1240. TEXMGR->resurrect();
  1241. }
  1242. DefineEngineFunction( cleanupTexturePool, void, (),,
  1243. "Release the unused pooled textures in texture manager freeing up video memory.\n"
  1244. "@ingroup GFX\n" )
  1245. {
  1246. if ( !GFX || !TEXMGR )
  1247. return;
  1248. TEXMGR->cleanupPool();
  1249. }
  1250. DefineEngineFunction( reloadTextures, void, (),,
  1251. "Reload all the textures from disk.\n"
  1252. "@ingroup GFX\n" )
  1253. {
  1254. if ( !GFX || !TEXMGR )
  1255. return;
  1256. TEXMGR->reloadTextures();
  1257. }