gfxTextureManager.cpp 49 KB

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