materialManager.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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 "materials/materialManager.h"
  24. #include "materials/matInstance.h"
  25. #include "materials/materialFeatureTypes.h"
  26. #include "lighting/lightManager.h"
  27. #include "core/util/safeDelete.h"
  28. #include "shaderGen/shaderGen.h"
  29. #include "core/module.h"
  30. #include "console/consoleTypes.h"
  31. #include "console/engineAPI.h"
  32. MODULE_BEGIN( MaterialManager )
  33. MODULE_INIT_BEFORE( GFX )
  34. MODULE_SHUTDOWN_BEFORE( GFX )
  35. MODULE_INIT
  36. {
  37. MaterialManager::createSingleton();
  38. }
  39. MODULE_SHUTDOWN
  40. {
  41. MaterialManager::deleteSingleton();
  42. }
  43. MODULE_END;
  44. MaterialManager::MaterialManager()
  45. {
  46. VECTOR_SET_ASSOCIATION( mMatInstanceList );
  47. mDt = 0.0f;
  48. mAccumTime = 0.0f;
  49. mLastTime = 0;
  50. mWarningInst = NULL;
  51. GFXDevice::getDeviceEventSignal().notify( this, &MaterialManager::_handleGFXEvent );
  52. // Make sure we get activation signals
  53. // and that we're the last to get them.
  54. LightManager::smActivateSignal.notify( this, &MaterialManager::_onLMActivate, 9999 );
  55. mMaterialSet = NULL;
  56. mUsingPrePass = false;
  57. mFlushAndReInit = false;
  58. mDefaultAnisotropy = 1;
  59. Con::addVariable( "$pref::Video::defaultAnisotropy", TypeS32, &mDefaultAnisotropy,
  60. "@brief Global variable defining the default anisotropy value.\n\n"
  61. "Controls the default anisotropic texture filtering level for all materials, including the terrain. "
  62. "This value can be changed at runtime to see its affect without reloading.\n\n "
  63. "@ingroup Materials");
  64. Con::NotifyDelegate callabck( this, &MaterialManager::_updateDefaultAnisotropy );
  65. Con::addVariableNotify( "$pref::Video::defaultAnisotropy", callabck );
  66. Con::NotifyDelegate callabck2( this, &MaterialManager::_onDisableMaterialFeature );
  67. Con::setVariable( "$pref::Video::disableNormalMapping", "false" );
  68. Con::addVariableNotify( "$pref::Video::disableNormalMapping", callabck2 );
  69. Con::setVariable( "$pref::Video::disablePixSpecular", "false" );
  70. Con::addVariableNotify( "$pref::Video::disablePixSpecular", callabck2 );
  71. Con::setVariable( "$pref::Video::disableCubemapping", "false" );
  72. Con::addVariableNotify( "$pref::Video::disableCubemapping", callabck2 );
  73. Con::setVariable( "$pref::Video::disableParallaxMapping", "false" );
  74. Con::addVariableNotify( "$pref::Video::disableParallaxMapping", callabck2 );
  75. }
  76. MaterialManager::~MaterialManager()
  77. {
  78. GFXDevice::getDeviceEventSignal().remove( this, &MaterialManager::_handleGFXEvent );
  79. LightManager::smActivateSignal.remove( this, &MaterialManager::_onLMActivate );
  80. SAFE_DELETE( mWarningInst );
  81. #ifndef TORQUE_SHIPPING
  82. DebugMaterialMap::Iterator itr = mMeshDebugMaterialInsts.begin();
  83. for ( ; itr != mMeshDebugMaterialInsts.end(); itr++ )
  84. delete itr->value;
  85. #endif
  86. }
  87. void MaterialManager::_onLMActivate( const char *lm, bool activate )
  88. {
  89. if ( !activate )
  90. return;
  91. // Since the light manager usually swaps shadergen features
  92. // and changes system wide shader defines we need to completely
  93. // flush and rebuild all the material instances.
  94. mFlushAndReInit = true;
  95. }
  96. void MaterialManager::_updateDefaultAnisotropy()
  97. {
  98. // Update all the materials.
  99. Vector<BaseMatInstance*>::iterator iter = mMatInstanceList.begin();
  100. for ( ; iter != mMatInstanceList.end(); iter++ )
  101. (*iter)->updateStateBlocks();
  102. }
  103. Material * MaterialManager::allocateAndRegister(const String &objectName, const String &mapToName)
  104. {
  105. Material *newMat = new Material();
  106. if ( mapToName.isNotEmpty() )
  107. newMat->mMapTo = mapToName;
  108. bool registered = newMat->registerObject(objectName );
  109. AssertFatal( registered, "Unable to register material" );
  110. if (registered)
  111. Sim::getRootGroup()->addObject( newMat );
  112. else
  113. {
  114. delete newMat;
  115. newMat = NULL;
  116. }
  117. return newMat;
  118. }
  119. Material * MaterialManager::getMaterialDefinitionByName(const String &matName)
  120. {
  121. // Get the material
  122. Material * foundMat;
  123. if(!Sim::findObject(matName, foundMat))
  124. {
  125. Con::errorf("MaterialManager: Unable to find material '%s'", matName.c_str());
  126. return NULL;
  127. }
  128. return foundMat;
  129. }
  130. BaseMatInstance* MaterialManager::createMatInstance(const String &matName)
  131. {
  132. BaseMaterialDefinition* mat = NULL;
  133. if (Sim::findObject(matName, mat))
  134. return mat->createMatInstance();
  135. return NULL;
  136. }
  137. BaseMatInstance* MaterialManager::createMatInstance( const String &matName,
  138. const GFXVertexFormat *vertexFormat )
  139. {
  140. return createMatInstance( matName, getDefaultFeatures(), vertexFormat );
  141. }
  142. BaseMatInstance* MaterialManager::createMatInstance( const String &matName,
  143. const FeatureSet& features,
  144. const GFXVertexFormat *vertexFormat )
  145. {
  146. BaseMatInstance* mat = createMatInstance(matName);
  147. if (mat)
  148. {
  149. mat->init( features, vertexFormat );
  150. return mat;
  151. }
  152. return NULL;
  153. }
  154. BaseMatInstance * MaterialManager::createWarningMatInstance()
  155. {
  156. Material *warnMat = static_cast<Material*>(Sim::findObject("WarningMaterial"));
  157. BaseMatInstance *warnMatInstance = NULL;
  158. if( warnMat != NULL )
  159. {
  160. warnMatInstance = warnMat->createMatInstance();
  161. GFXStateBlockDesc desc;
  162. desc.setCullMode(GFXCullNone);
  163. warnMatInstance->addStateBlockDesc(desc);
  164. warnMatInstance->init( getDefaultFeatures(),
  165. getGFXVertexFormat<GFXVertexPNTTB>() );
  166. }
  167. return warnMatInstance;
  168. }
  169. // Gets the global warning material instance, callers should not free this copy
  170. BaseMatInstance * MaterialManager::getWarningMatInstance()
  171. {
  172. if (!mWarningInst)
  173. mWarningInst = createWarningMatInstance();
  174. return mWarningInst;
  175. }
  176. #ifndef TORQUE_SHIPPING
  177. BaseMatInstance * MaterialManager::createMeshDebugMatInstance(const ColorF &meshColor)
  178. {
  179. String meshDebugStr = String::ToString( "Torque_MeshDebug_%d", meshColor.getRGBAPack() );
  180. Material *debugMat;
  181. if (!Sim::findObject(meshDebugStr,debugMat))
  182. {
  183. debugMat = allocateAndRegister( meshDebugStr );
  184. debugMat->mDiffuse[0] = meshColor;
  185. debugMat->mEmissive[0] = true;
  186. }
  187. BaseMatInstance *debugMatInstance = NULL;
  188. if( debugMat != NULL )
  189. {
  190. debugMatInstance = debugMat->createMatInstance();
  191. GFXStateBlockDesc desc;
  192. desc.setCullMode(GFXCullNone);
  193. desc.fillMode = GFXFillWireframe;
  194. debugMatInstance->addStateBlockDesc(desc);
  195. // Disable fog and other stuff.
  196. FeatureSet debugFeatures;
  197. debugFeatures.addFeature( MFT_DiffuseColor );
  198. debugMatInstance->init( debugFeatures, getGFXVertexFormat<GFXVertexPCN>() );
  199. }
  200. return debugMatInstance;
  201. }
  202. // Gets the global material instance for a given color, callers should not free this copy
  203. BaseMatInstance *MaterialManager::getMeshDebugMatInstance(const ColorF &meshColor)
  204. {
  205. DebugMaterialMap::Iterator itr = mMeshDebugMaterialInsts.find( meshColor.getRGBAPack() );
  206. BaseMatInstance *inst = NULL;
  207. if ( itr == mMeshDebugMaterialInsts.end() )
  208. inst = createMeshDebugMatInstance( meshColor );
  209. else
  210. inst = itr->value;
  211. mMeshDebugMaterialInsts.insert( meshColor.getRGBAPack(), inst );
  212. return inst;
  213. }
  214. #endif
  215. void MaterialManager::mapMaterial(const String & textureName, const String & materialName)
  216. {
  217. if (getMapEntry(textureName).isNotEmpty())
  218. {
  219. if (!textureName.equal("unmapped_mat", String::NoCase))
  220. Con::warnf(ConsoleLogEntry::General, "Warning, overwriting material for: %s", textureName.c_str());
  221. }
  222. mMaterialMap[String::ToLower(textureName)] = materialName;
  223. }
  224. String MaterialManager::getMapEntry(const String & textureName) const
  225. {
  226. MaterialMap::ConstIterator iter = mMaterialMap.find(String::ToLower(textureName));
  227. if ( iter == mMaterialMap.end() )
  228. return String();
  229. return iter->value;
  230. }
  231. void MaterialManager::flushAndReInitInstances()
  232. {
  233. // Clear the flag if its set.
  234. mFlushAndReInit = false;
  235. // Check to see if any shader preferences have changed.
  236. recalcFeaturesFromPrefs();
  237. // First we flush all the shader gen shaders which will
  238. // invalidate all GFXShader* to them.
  239. SHADERGEN->flushProceduralShaders();
  240. mFlushSignal.trigger();
  241. // First do a pass deleting all hooks as they can contain
  242. // materials themselves. This means we have to restart the
  243. // loop every time we delete any hooks... lame.
  244. Vector<BaseMatInstance*>::iterator iter = mMatInstanceList.begin();
  245. while ( iter != mMatInstanceList.end() )
  246. {
  247. if ( (*iter)->deleteAllHooks() != 0 )
  248. {
  249. // Restart the loop.
  250. iter = mMatInstanceList.begin();
  251. continue;
  252. }
  253. iter++;
  254. }
  255. // Now do a pass re-initializing materials.
  256. iter = mMatInstanceList.begin();
  257. for ( ; iter != mMatInstanceList.end(); iter++ )
  258. (*iter)->reInit();
  259. }
  260. // Used in the materialEditor. This flushes the material preview object so it can be reloaded easily.
  261. void MaterialManager::flushInstance( BaseMaterialDefinition *target )
  262. {
  263. Vector<BaseMatInstance*>::iterator iter = mMatInstanceList.begin();
  264. while ( iter != mMatInstanceList.end() )
  265. {
  266. if ( (*iter)->getMaterial() == target )
  267. {
  268. (*iter)->deleteAllHooks();
  269. return;
  270. }
  271. iter++;
  272. }
  273. }
  274. void MaterialManager::reInitInstance( BaseMaterialDefinition *target )
  275. {
  276. Vector<BaseMatInstance*>::iterator iter = mMatInstanceList.begin();
  277. for ( ; iter != mMatInstanceList.end(); iter++ )
  278. {
  279. if ( (*iter)->getMaterial() == target )
  280. (*iter)->reInit();
  281. }
  282. }
  283. void MaterialManager::updateTime()
  284. {
  285. U32 curTime = Sim::getCurrentTime();
  286. if(curTime > mLastTime)
  287. {
  288. mDt = (curTime - mLastTime) / 1000.0f;
  289. mLastTime = curTime;
  290. mAccumTime += mDt;
  291. }
  292. else
  293. mDt = 0.0f;
  294. }
  295. SimSet * MaterialManager::getMaterialSet()
  296. {
  297. if(!mMaterialSet)
  298. mMaterialSet = static_cast<SimSet*>( Sim::findObject( "MaterialSet" ) );
  299. AssertFatal( mMaterialSet, "MaterialSet not found" );
  300. return mMaterialSet;
  301. }
  302. void MaterialManager::dumpMaterialInstances( BaseMaterialDefinition *target ) const
  303. {
  304. if ( !mMatInstanceList.size() )
  305. return;
  306. if ( target )
  307. Con::printf( "--------------------- %s MatInstances ---------------------", target->getName() );
  308. else
  309. Con::printf( "--------------------- MatInstances %d ---------------------", mMatInstanceList.size() );
  310. for( U32 i=0; i<mMatInstanceList.size(); i++ )
  311. {
  312. BaseMatInstance *inst = mMatInstanceList[i];
  313. if ( target && inst->getMaterial() != target )
  314. continue;
  315. inst->dumpShaderInfo();
  316. Con::printf( "" );
  317. }
  318. Con::printf( "---------------------- Dump complete ----------------------");
  319. }
  320. void MaterialManager::_track( MatInstance *matInstance )
  321. {
  322. mMatInstanceList.push_back( matInstance );
  323. }
  324. void MaterialManager::_untrack( MatInstance *matInstance )
  325. {
  326. mMatInstanceList.remove( matInstance );
  327. }
  328. void MaterialManager::recalcFeaturesFromPrefs()
  329. {
  330. mDefaultFeatures.clear();
  331. FeatureType::addDefaultTypes( &mDefaultFeatures );
  332. mExclusionFeatures.setFeature( MFT_NormalMap,
  333. Con::getBoolVariable( "$pref::Video::disableNormalMapping", false ) );
  334. mExclusionFeatures.setFeature( MFT_SpecularMap,
  335. Con::getBoolVariable( "$pref::Video::disablePixSpecular", false ) );
  336. mExclusionFeatures.setFeature( MFT_PixSpecular,
  337. Con::getBoolVariable( "$pref::Video::disablePixSpecular", false ) );
  338. mExclusionFeatures.setFeature( MFT_CubeMap,
  339. Con::getBoolVariable( "$pref::Video::disableCubemapping", false ) );
  340. mExclusionFeatures.setFeature( MFT_Parallax,
  341. Con::getBoolVariable( "$pref::Video::disableParallaxMapping", false ) );
  342. }
  343. bool MaterialManager::_handleGFXEvent( GFXDevice::GFXDeviceEventType event_ )
  344. {
  345. switch ( event_ )
  346. {
  347. case GFXDevice::deInit:
  348. recalcFeaturesFromPrefs();
  349. break;
  350. case GFXDevice::deDestroy :
  351. SAFE_DELETE( mWarningInst );
  352. break;
  353. case GFXDevice::deStartOfFrame:
  354. if ( mFlushAndReInit )
  355. flushAndReInitInstances();
  356. break;
  357. default:
  358. break;
  359. }
  360. return true;
  361. }
  362. DefineConsoleFunction( reInitMaterials, void, (),,
  363. "@brief Flushes all procedural shaders and re-initializes all active material instances.\n\n"
  364. "@ingroup Materials")
  365. {
  366. MATMGR->flushAndReInitInstances();
  367. }
  368. DefineConsoleFunction( addMaterialMapping, void, (const char * texName, const char * matName), , "(string texName, string matName)\n"
  369. "@brief Maps the given texture to the given material.\n\n"
  370. "Generates a console warning before overwriting.\n\n"
  371. "Material maps are used by terrain and interiors for triggering "
  372. "effects when an object moves onto a terrain "
  373. "block or interior surface using the associated texture.\n\n"
  374. "@ingroup Materials")
  375. {
  376. MATMGR->mapMaterial(texName, matName);
  377. }
  378. DefineConsoleFunction( getMaterialMapping, const char*, (const char * texName), , "(string texName)\n"
  379. "@brief Returns the name of the material mapped to this texture.\n\n"
  380. "If no materials are found, an empty string is returned.\n\n"
  381. "@param texName Name of the texture\n\n"
  382. "@ingroup Materials")
  383. {
  384. return MATMGR->getMapEntry(texName).c_str();
  385. }
  386. DefineConsoleFunction( dumpMaterialInstances, void, (), ,
  387. "@brief Dumps a formatted list of currently allocated material instances to the console.\n\n"
  388. "@ingroup Materials")
  389. {
  390. MATMGR->dumpMaterialInstances();
  391. }
  392. DefineConsoleFunction( getMapEntry, const char*, (const char * texName), ,
  393. "@hide")
  394. {
  395. return MATMGR->getMapEntry( String(texName) );
  396. }