gfxTextureManager.cpp 47 KB

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