materialManager.cpp 16 KB

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