gfxTextureManager.cpp 49 KB

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