gfxTextureManager.cpp 48 KB

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