gfxTextureManager.cpp 50 KB

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