terrCellMaterial.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  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 "terrain/terrCellMaterial.h"
  24. #include "terrain/terrData.h"
  25. #include "terrain/terrCell.h"
  26. #include "materials/materialFeatureTypes.h"
  27. #include "materials/materialManager.h"
  28. #include "terrain/terrFeatureTypes.h"
  29. #include "terrain/terrMaterial.h"
  30. #include "renderInstance/renderDeferredMgr.h"
  31. #include "shaderGen/shaderGen.h"
  32. #include "shaderGen/featureMgr.h"
  33. #include "scene/sceneRenderState.h"
  34. #include "materials/sceneData.h"
  35. #include "gfx/util/screenspace.h"
  36. #include "lighting/advanced/advancedLightBinManager.h"
  37. S32 sgMaxTerrainMaterialsPerPass = 3;
  38. AFTER_MODULE_INIT( MaterialManager )
  39. {
  40. Con::NotifyDelegate callabck( &TerrainCellMaterial::_updateDefaultAnisotropy );
  41. Con::addVariableNotify( "$pref::Video::defaultAnisotropy", callabck );
  42. }
  43. Vector<TerrainCellMaterial*> TerrainCellMaterial::smAllMaterials;
  44. Vector<String> _initSamplerNames()
  45. {
  46. Vector<String> samplerNames;
  47. samplerNames.push_back("$baseTexMap");
  48. samplerNames.push_back("$layerTex");
  49. samplerNames.push_back("$macrolayerTex");
  50. samplerNames.push_back("$lightMapTex");
  51. samplerNames.push_back("$lightInfoBuffer");
  52. for(int i = 0; i < 3; ++i)
  53. {
  54. samplerNames.push_back(avar("$normalMap%d",i));
  55. samplerNames.push_back(avar("$detailMap%d",i));
  56. samplerNames.push_back(avar("$macroMap%d",i));
  57. }
  58. return samplerNames;
  59. }
  60. const Vector<String> TerrainCellMaterial::mSamplerNames = _initSamplerNames();
  61. TerrainCellMaterial::TerrainCellMaterial()
  62. : mTerrain( NULL ),
  63. mCurrPass( 0 ),
  64. mDeferredMat( NULL ),
  65. mReflectMat( NULL )
  66. {
  67. smAllMaterials.push_back( this );
  68. }
  69. TerrainCellMaterial::~TerrainCellMaterial()
  70. {
  71. SAFE_DELETE( mDeferredMat );
  72. SAFE_DELETE( mReflectMat );
  73. smAllMaterials.remove( this );
  74. }
  75. void TerrainCellMaterial::_updateDefaultAnisotropy()
  76. {
  77. // TODO: We need to split the stateblock initialization
  78. // from the shader constant lookup and pass setup in a
  79. // future version of terrain materials.
  80. //
  81. // For now use some custom code in a horrible loop to
  82. // change the anisotropy directly and fast.
  83. //
  84. const U32 maxAnisotropy = MATMGR->getDefaultAnisotropy();
  85. Vector<TerrainCellMaterial*>::iterator iter = smAllMaterials.begin();
  86. for ( ; iter != smAllMaterials.end(); iter++ )
  87. {
  88. for ( U32 p=0; p < (*iter)->mPasses.size(); p++ )
  89. {
  90. Pass &pass = (*iter)->mPasses[p];
  91. // Start from the existing state block.
  92. GFXStateBlockDesc desc = pass.stateBlock->getDesc();
  93. for ( U32 m=0; m < pass.materials.size(); m++ )
  94. {
  95. const MaterialInfo *matInfo = pass.materials[m];
  96. if ( matInfo->detailTexConst->isValid() )
  97. {
  98. const S32 sampler = matInfo->detailTexConst->getSamplerRegister();
  99. if ( maxAnisotropy > 1 )
  100. {
  101. desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
  102. desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
  103. }
  104. else
  105. desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
  106. }
  107. if ( matInfo->macroTexConst->isValid() )
  108. {
  109. const S32 sampler = matInfo->macroTexConst->getSamplerRegister();
  110. if ( maxAnisotropy > 1 )
  111. {
  112. desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
  113. desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
  114. }
  115. else
  116. desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
  117. }
  118. if ( matInfo->normalTexConst->isValid() )
  119. {
  120. const S32 sampler = matInfo->normalTexConst->getSamplerRegister();
  121. if ( maxAnisotropy > 1 )
  122. {
  123. desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
  124. desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
  125. }
  126. else
  127. desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
  128. }
  129. } // for ( U32 m=0; m < pass.materials.size(); m++ )
  130. // Set the updated stateblock.
  131. desc.setCullMode( GFXCullCCW );
  132. pass.stateBlock = GFX->createStateBlock( desc );
  133. //reflection
  134. desc.setCullMode( GFXCullCW );
  135. pass.reflectionStateBlock = GFX->createStateBlock(desc);
  136. // Create the wireframe state blocks.
  137. GFXStateBlockDesc wireframe( desc );
  138. wireframe.fillMode = GFXFillWireframe;
  139. wireframe.setCullMode( GFXCullCCW );
  140. pass.wireframeStateBlock = GFX->createStateBlock( wireframe );
  141. } // for ( U32 p=0; i < (*iter)->mPasses.size(); p++ )
  142. }
  143. }
  144. void TerrainCellMaterial::setTransformAndEye( const MatrixF &modelXfm,
  145. const MatrixF &viewXfm,
  146. const MatrixF &projectXfm,
  147. F32 farPlane )
  148. {
  149. PROFILE_SCOPE( TerrainCellMaterial_SetTransformAndEye );
  150. MatrixF modelViewProj = projectXfm * viewXfm * modelXfm;
  151. MatrixF invViewXfm( viewXfm );
  152. invViewXfm.inverse();
  153. Point3F eyePos = invViewXfm.getPosition();
  154. MatrixF invModelXfm( modelXfm );
  155. invModelXfm.inverse();
  156. Point3F objEyePos = eyePos;
  157. invModelXfm.mulP( objEyePos );
  158. VectorF vEye = invViewXfm.getForwardVector();
  159. vEye.normalize( 1.0f / farPlane );
  160. for ( U32 i=0; i < mPasses.size(); i++ )
  161. {
  162. Pass &pass = mPasses[i];
  163. pass.consts->setSafe( pass.modelViewProjConst, modelViewProj );
  164. if( pass.viewToObj->isValid() || pass.worldViewOnly->isValid() )
  165. {
  166. MatrixF worldViewOnly = viewXfm * modelXfm;
  167. pass.consts->setSafe( pass.worldViewOnly, worldViewOnly );
  168. if( pass.viewToObj->isValid() )
  169. {
  170. worldViewOnly.affineInverse();
  171. pass.consts->set( pass.viewToObj, worldViewOnly);
  172. }
  173. }
  174. pass.consts->setSafe( pass.eyePosWorldConst, eyePos );
  175. pass.consts->setSafe( pass.eyePosConst, objEyePos );
  176. pass.consts->setSafe( pass.objTransConst, modelXfm );
  177. pass.consts->setSafe( pass.worldToObjConst, invModelXfm );
  178. pass.consts->setSafe( pass.vEyeConst, vEye );
  179. }
  180. }
  181. TerrainCellMaterial* TerrainCellMaterial::getDeferredMat()
  182. {
  183. if ( !mDeferredMat )
  184. {
  185. mDeferredMat = new TerrainCellMaterial();
  186. mDeferredMat->init( mTerrain, mMaterials, true, false, mMaterials == 0 );
  187. }
  188. return mDeferredMat;
  189. }
  190. TerrainCellMaterial* TerrainCellMaterial::getReflectMat()
  191. {
  192. if ( !mReflectMat )
  193. {
  194. mReflectMat = new TerrainCellMaterial();
  195. mReflectMat->init( mTerrain, mMaterials, false, true, true );
  196. }
  197. return mReflectMat;
  198. }
  199. void TerrainCellMaterial::init( TerrainBlock *block,
  200. U64 activeMaterials,
  201. bool deferredMat,
  202. bool reflectMat,
  203. bool baseOnly )
  204. {
  205. // This isn't allowed for now.
  206. AssertFatal( !( deferredMat && reflectMat ), "TerrainCellMaterial::init - We shouldn't get deferred and reflection in the same material!" );
  207. mTerrain = block;
  208. mMaterials = activeMaterials;
  209. Vector<MaterialInfo*> materials;
  210. for ( U32 i = 0; i < 64; i++ )
  211. {
  212. if ( !( mMaterials & ((U64)1 << i ) ) )
  213. continue;
  214. TerrainMaterial *mat = block->getMaterial( i );
  215. MaterialInfo *info = new MaterialInfo();
  216. info->layerId = i;
  217. info->mat = mat;
  218. materials.push_back( info );
  219. }
  220. mCurrPass = 0;
  221. mPasses.clear();
  222. // Ok... loop till we successfully generate all
  223. // the shader passes for the materials.
  224. while ( materials.size() > 0 || baseOnly )
  225. {
  226. mPasses.increment();
  227. if ( !_createPass( &materials,
  228. &mPasses.last(),
  229. mPasses.size() == 1,
  230. deferredMat,
  231. reflectMat,
  232. baseOnly ) )
  233. {
  234. Con::errorf( "TerrainCellMaterial::init - Failed to create pass!" );
  235. // The pass failed to be generated... give up.
  236. mPasses.last().materials.clear();
  237. mPasses.clear();
  238. T3D::for_each( materials.begin(), materials.end(), T3D::delete_pointer() );
  239. return;
  240. }
  241. if ( baseOnly )
  242. break;
  243. }
  244. // Cleanup any remaining matinfo.
  245. T3D::for_each( materials.begin(), materials.end(), T3D::delete_pointer() );
  246. // If we have attached mats then update them too.
  247. if ( mDeferredMat )
  248. mDeferredMat->init( mTerrain, mMaterials, true, false, baseOnly );
  249. if ( mReflectMat )
  250. mReflectMat->init( mTerrain, mMaterials, false, true, baseOnly );
  251. }
  252. bool TerrainCellMaterial::_createPass( Vector<MaterialInfo*> *materials,
  253. Pass *pass,
  254. bool firstPass,
  255. bool deferredMat,
  256. bool reflectMat,
  257. bool baseOnly )
  258. {
  259. if ( GFX->getPixelShaderVersion() < 3.0f )
  260. baseOnly = true;
  261. // NOTE: At maximum we only try to combine sgMaxTerrainMaterialsPerPass materials
  262. // into a single pass. This is sub-optimal for the simplest
  263. // cases, but the most common case results in much fewer
  264. // shader generation failures and permutations leading to
  265. // faster load time and less hiccups during gameplay.
  266. U32 matCount = getMin( sgMaxTerrainMaterialsPerPass, materials->size() );
  267. Vector<GFXTexHandle> normalMaps;
  268. // See if we're currently running under the
  269. // basic lighting manager.
  270. //
  271. // TODO: This seems ugly... we should trigger
  272. // features like this differently in the future.
  273. //
  274. bool useBLM = dStrcmp( LIGHTMGR->getId(), "BLM" ) == 0;
  275. // Do we need to disable normal mapping?
  276. const bool disableNormalMaps = MATMGR->getExclusionFeatures().hasFeature( MFT_NormalMap ) || useBLM;
  277. // How about parallax?
  278. const bool disableParallaxMaps = GFX->getPixelShaderVersion() < 3.0f ||
  279. MATMGR->getExclusionFeatures().hasFeature( MFT_Parallax );
  280. // Has advanced lightmap support been enabled for deferred.
  281. bool advancedLightmapSupport = false;
  282. if ( deferredMat )
  283. {
  284. // This sucks... but it works.
  285. AdvancedLightBinManager *lightBin;
  286. if ( Sim::findObject( "AL_LightBinMgr", lightBin ) )
  287. advancedLightmapSupport = lightBin->MRTLightmapsDuringDeferred();
  288. }
  289. // Loop till we create a valid shader!
  290. while( true )
  291. {
  292. FeatureSet features;
  293. features.addFeature( MFT_VertTransform );
  294. if ( deferredMat )
  295. {
  296. features.addFeature( MFT_EyeSpaceDepthOut );
  297. features.addFeature( MFT_DeferredConditioner );
  298. features.addFeature( MFT_DeferredTerrainBaseMap );
  299. features.addFeature(MFT_isDeferred);
  300. if ( advancedLightmapSupport )
  301. features.addFeature( MFT_RenderTarget3_Zero );
  302. }
  303. else
  304. {
  305. features.addFeature( MFT_TerrainBaseMap );
  306. features.addFeature( MFT_RTLighting );
  307. // The HDR feature is always added... it will compile out
  308. // if HDR is not enabled in the engine.
  309. features.addFeature( MFT_HDROut );
  310. }
  311. features.addFeature(MFT_DeferredTerrainBlankInfoMap);
  312. // Enable lightmaps and fogging if we're in BL.
  313. if ( reflectMat || useBLM )
  314. {
  315. features.addFeature( MFT_Fog );
  316. features.addFeature( MFT_ForwardShading );
  317. }
  318. if ( useBLM )
  319. features.addFeature( MFT_TerrainLightMap );
  320. // The additional passes need to be lerp blended into the
  321. // target to maintain the results of the previous passes.
  322. if ( !firstPass )
  323. features.addFeature( MFT_TerrainAdditive );
  324. normalMaps.clear();
  325. pass->materials.clear();
  326. // Now add all the material layer features.
  327. for ( U32 i=0; i < matCount && !baseOnly; i++ )
  328. {
  329. TerrainMaterial *mat = (*materials)[i]->mat;
  330. if ( mat == NULL )
  331. continue;
  332. // We only include materials that
  333. // have more than a base texture.
  334. if ( mat->getDetailSize() <= 0 ||
  335. mat->getDetailDistance() <= 0 ||
  336. mat->getDetailMap().isEmpty() )
  337. continue;
  338. S32 featureIndex = pass->materials.size();
  339. // check for macro detail texture
  340. if ( !(mat->getMacroSize() <= 0 || mat->getMacroDistance() <= 0 || mat->getMacroMap().isEmpty() ) )
  341. {
  342. if(deferredMat)
  343. features.addFeature( MFT_DeferredTerrainMacroMap, featureIndex );
  344. else
  345. features.addFeature( MFT_TerrainMacroMap, featureIndex );
  346. }
  347. if(deferredMat)
  348. features.addFeature( MFT_DeferredTerrainDetailMap, featureIndex );
  349. else
  350. features.addFeature( MFT_TerrainDetailMap, featureIndex );
  351. pass->materials.push_back( (*materials)[i] );
  352. normalMaps.increment();
  353. // Skip normal maps if we need to.
  354. if ( !disableNormalMaps && mat->getNormalMap().isNotEmpty() )
  355. {
  356. features.addFeature( MFT_TerrainNormalMap, featureIndex );
  357. normalMaps.last().set( mat->getNormalMap(),
  358. &GFXNormalMapProfile, "TerrainCellMaterial::_createPass() - NormalMap" );
  359. GFXFormat normalFmt = normalMaps.last().getFormat();
  360. if ( normalFmt == GFXFormatBC3 )
  361. features.addFeature( MFT_IsBC3nm, featureIndex );
  362. else if ( normalFmt == GFXFormatBC5)
  363. features.addFeature( MFT_IsBC5nm, featureIndex);
  364. // Do we need and can we do parallax mapping?
  365. if ( !disableParallaxMaps &&
  366. mat->getParallaxScale() > 0.0f &&
  367. !mat->useSideProjection() )
  368. features.addFeature( MFT_TerrainParallaxMap, featureIndex );
  369. }
  370. // Is this layer got side projection?
  371. if ( mat->useSideProjection() )
  372. features.addFeature( MFT_TerrainSideProject, featureIndex );
  373. }
  374. MaterialFeatureData featureData;
  375. featureData.features = features;
  376. featureData.materialFeatures = features;
  377. // Check to see how many vertex shader output
  378. // registers we're gonna need.
  379. U32 numTex = 0;
  380. U32 numTexReg = 0;
  381. for ( U32 i=0; i < features.getCount(); i++ )
  382. {
  383. S32 index;
  384. const FeatureType &type = features.getAt( i, &index );
  385. ShaderFeature* sf = FEATUREMGR->getByType( type );
  386. if ( !sf )
  387. continue;
  388. sf->setProcessIndex( index );
  389. ShaderFeature::Resources res = sf->getResources( featureData );
  390. numTex += res.numTex;
  391. numTexReg += res.numTexReg;
  392. }
  393. // Can we build the shader?
  394. //
  395. // NOTE: The 10 is sort of an abitrary SM 3.0
  396. // limit. Its really supposed to be 11, but that
  397. // always fails to compile so far.
  398. //
  399. if ( numTex < GFX->getNumSamplers() &&
  400. numTexReg <= 10 )
  401. {
  402. // NOTE: We really shouldn't be getting errors building the shaders,
  403. // but we can generate more instructions than the ps_2_x will allow.
  404. //
  405. // There is no way to deal with this case that i know of other than
  406. // letting the compile fail then recovering by trying to build it
  407. // with fewer materials.
  408. //
  409. // We normally disable the shader error logging so that the user
  410. // isn't fooled into thinking there is a real bug. That is until
  411. // we get down to a single material. If a single material case
  412. // fails it means it cannot generate any passes at all!
  413. const bool logErrors = matCount == 1;
  414. GFXShader::setLogging( logErrors, true );
  415. pass->shader = SHADERGEN->getShader( featureData, getGFXVertexFormat<TerrVertex>(), NULL, mSamplerNames );
  416. }
  417. // If we got a shader then we can continue.
  418. if ( pass->shader )
  419. break;
  420. // If the material count is already 1 then this
  421. // is a real shader error... give up!
  422. if ( matCount <= 1 )
  423. return false;
  424. // If we failed we next try half the input materials
  425. // so that we can more quickly arrive at a valid shader.
  426. matCount -= matCount / 2;
  427. }
  428. // Setup the constant buffer.
  429. pass->consts = pass->shader->allocConstBuffer();
  430. // Prepare the basic constants.
  431. pass->modelViewProjConst = pass->shader->getShaderConstHandle( "$modelview" );
  432. pass->worldViewOnly = pass->shader->getShaderConstHandle( "$worldViewOnly" );
  433. pass->viewToObj = pass->shader->getShaderConstHandle( "$viewToObj" );
  434. pass->eyePosWorldConst = pass->shader->getShaderConstHandle( "$eyePosWorld" );
  435. pass->eyePosConst = pass->shader->getShaderConstHandle( "$eyePos" );
  436. pass->vEyeConst = pass->shader->getShaderConstHandle( "$vEye" );
  437. pass->layerSizeConst = pass->shader->getShaderConstHandle( "$layerSize" );
  438. pass->objTransConst = pass->shader->getShaderConstHandle( "$objTrans" );
  439. pass->worldToObjConst = pass->shader->getShaderConstHandle( "$worldToObj" );
  440. pass->lightInfoBufferConst = pass->shader->getShaderConstHandle( "$lightInfoBuffer" );
  441. pass->baseTexMapConst = pass->shader->getShaderConstHandle( "$baseTexMap" );
  442. pass->layerTexConst = pass->shader->getShaderConstHandle( "$layerTex" );
  443. pass->fogDataConst = pass->shader->getShaderConstHandle( "$fogData" );
  444. pass->fogColorConst = pass->shader->getShaderConstHandle( "$fogColor" );
  445. pass->lightMapTexConst = pass->shader->getShaderConstHandle( "$lightMapTex" );
  446. pass->oneOverTerrainSize = pass->shader->getShaderConstHandle( "$oneOverTerrainSize" );
  447. pass->squareSize = pass->shader->getShaderConstHandle( "$squareSize" );
  448. pass->lightParamsConst = pass->shader->getShaderConstHandle( "$rtParamslightInfoBuffer" );
  449. // Now prepare the basic stateblock.
  450. GFXStateBlockDesc desc;
  451. if ( !firstPass )
  452. {
  453. desc.setBlend( true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha );
  454. // If this is the deferred then we don't want to
  455. // write to the last two color channels (where
  456. // depth is usually encoded).
  457. //
  458. // This trick works in combination with the
  459. // MFT_TerrainAdditive feature to lerp the
  460. // output normal with the previous pass.
  461. //
  462. if ( deferredMat )
  463. desc.setColorWrites( true, true, true, false );
  464. }
  465. // We write to the zbuffer if this is a deferred
  466. // material or if the deferred is disabled.
  467. desc.setZReadWrite( true, !MATMGR->getDeferredEnabled() ||
  468. deferredMat ||
  469. reflectMat );
  470. desc.samplersDefined = true;
  471. if ( pass->baseTexMapConst->isValid() )
  472. desc.samplers[pass->baseTexMapConst->getSamplerRegister()] = GFXSamplerStateDesc::getWrapLinear();
  473. if ( pass->layerTexConst->isValid() )
  474. desc.samplers[pass->layerTexConst->getSamplerRegister()] = GFXSamplerStateDesc::getClampPoint();
  475. if ( pass->lightInfoBufferConst->isValid() )
  476. desc.samplers[pass->lightInfoBufferConst->getSamplerRegister()] = GFXSamplerStateDesc::getClampPoint();
  477. if ( pass->lightMapTexConst->isValid() )
  478. desc.samplers[pass->lightMapTexConst->getSamplerRegister()] = GFXSamplerStateDesc::getWrapLinear();
  479. const U32 maxAnisotropy = MATMGR->getDefaultAnisotropy();
  480. // Finally setup the material specific shader
  481. // constants and stateblock state.
  482. //
  483. // NOTE: If this changes be sure to check TerrainCellMaterial::_updateDefaultAnisotropy
  484. // to see if it needs the same changes.
  485. //
  486. for ( U32 i=0; i < pass->materials.size(); i++ )
  487. {
  488. MaterialInfo *matInfo = pass->materials[i];
  489. matInfo->detailInfoVConst = pass->shader->getShaderConstHandle( avar( "$detailScaleAndFade%d", i ) );
  490. matInfo->detailInfoPConst = pass->shader->getShaderConstHandle( avar( "$detailIdStrengthParallax%d", i ) );
  491. matInfo->detailTexConst = pass->shader->getShaderConstHandle( avar( "$detailMap%d", i ) );
  492. if ( matInfo->detailTexConst->isValid() )
  493. {
  494. const S32 sampler = matInfo->detailTexConst->getSamplerRegister();
  495. desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
  496. desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
  497. desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
  498. if ( maxAnisotropy > 1 )
  499. {
  500. desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
  501. desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
  502. }
  503. else
  504. desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
  505. matInfo->detailTex.set( matInfo->mat->getDetailMap(),
  506. &GFXStaticTextureProfile, "TerrainCellMaterial::_createPass() - DetailMap" );
  507. }
  508. matInfo->macroInfoVConst = pass->shader->getShaderConstHandle( avar( "$macroScaleAndFade%d", i ) );
  509. matInfo->macroInfoPConst = pass->shader->getShaderConstHandle( avar( "$macroIdStrengthParallax%d", i ) );
  510. matInfo->macroTexConst = pass->shader->getShaderConstHandle( avar( "$macroMap%d", i ) );
  511. if ( matInfo->macroTexConst->isValid() )
  512. {
  513. const S32 sampler = matInfo->macroTexConst->getSamplerRegister();
  514. desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
  515. desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
  516. desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
  517. if ( maxAnisotropy > 1 )
  518. {
  519. desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
  520. desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
  521. }
  522. else
  523. desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
  524. matInfo->macroTex.set( matInfo->mat->getMacroMap(),
  525. &GFXStaticTextureProfile, "TerrainCellMaterial::_createPass() - MacroMap" );
  526. }
  527. //end macro texture
  528. matInfo->normalTexConst = pass->shader->getShaderConstHandle( avar( "$normalMap%d", i ) );
  529. if ( matInfo->normalTexConst->isValid() )
  530. {
  531. const S32 sampler = matInfo->normalTexConst->getSamplerRegister();
  532. desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
  533. desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
  534. desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
  535. if ( maxAnisotropy > 1 )
  536. {
  537. desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
  538. desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
  539. }
  540. else
  541. desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
  542. matInfo->normalTex = normalMaps[i];
  543. }
  544. }
  545. // Remove the materials we processed and leave the
  546. // ones that remain for the next pass.
  547. for ( U32 i=0; i < matCount; i++ )
  548. {
  549. MaterialInfo *matInfo = materials->first();
  550. if ( baseOnly || pass->materials.find_next( matInfo ) == -1 )
  551. delete matInfo;
  552. materials->pop_front();
  553. }
  554. // If we're doing deferred it requires some
  555. // special stencil settings for it to work.
  556. if ( deferredMat )
  557. desc.addDesc( RenderDeferredMgr::getOpaqueStenciWriteDesc( false ) );
  558. desc.setCullMode( GFXCullCCW );
  559. pass->stateBlock = GFX->createStateBlock(desc);
  560. //reflection stateblock
  561. desc.setCullMode( GFXCullCW );
  562. pass->reflectionStateBlock = GFX->createStateBlock(desc);
  563. // Create the wireframe state blocks.
  564. GFXStateBlockDesc wireframe( desc );
  565. wireframe.fillMode = GFXFillWireframe;
  566. wireframe.setCullMode( GFXCullCCW );
  567. pass->wireframeStateBlock = GFX->createStateBlock( wireframe );
  568. return true;
  569. }
  570. void TerrainCellMaterial::_updateMaterialConsts( Pass *pass )
  571. {
  572. PROFILE_SCOPE( TerrainCellMaterial_UpdateMaterialConsts );
  573. for ( U32 j=0; j < pass->materials.size(); j++ )
  574. {
  575. MaterialInfo *matInfo = pass->materials[j];
  576. F32 detailSize = matInfo->mat->getDetailSize();
  577. F32 detailScale = 1.0f;
  578. if ( !mIsZero( detailSize ) )
  579. detailScale = mTerrain->getWorldBlockSize() / detailSize;
  580. // Scale the distance by the global scalar.
  581. const F32 distance = mTerrain->smDetailScale * matInfo->mat->getDetailDistance();
  582. // NOTE: The negation of the y scale is to make up for
  583. // my mistake early in development and passing the wrong
  584. // y texture coord into the system.
  585. //
  586. // This negation fixes detail, normal, and parallax mapping
  587. // without harming the layer id blending code.
  588. //
  589. // Eventually we should rework this to correct this little
  590. // mistake, but there isn't really a hurry to.
  591. //
  592. Point4F detailScaleAndFade( detailScale,
  593. -detailScale,
  594. distance,
  595. 0 );
  596. if ( !mIsZero( distance ) )
  597. detailScaleAndFade.w = 1.0f / distance;
  598. Point3F detailIdStrengthParallax( matInfo->layerId,
  599. matInfo->mat->getDetailStrength(),
  600. matInfo->mat->getParallaxScale() );
  601. pass->consts->setSafe( matInfo->detailInfoVConst, detailScaleAndFade );
  602. pass->consts->setSafe( matInfo->detailInfoPConst, detailIdStrengthParallax );
  603. // macro texture info
  604. F32 macroSize = matInfo->mat->getMacroSize();
  605. F32 macroScale = 1.0f;
  606. if ( !mIsZero( macroSize ) )
  607. macroScale = mTerrain->getWorldBlockSize() / macroSize;
  608. // Scale the distance by the global scalar.
  609. const F32 macroDistance = mTerrain->smDetailScale * matInfo->mat->getMacroDistance();
  610. Point4F macroScaleAndFade( macroScale,
  611. -macroScale,
  612. macroDistance,
  613. 0 );
  614. if ( !mIsZero( macroDistance ) )
  615. macroScaleAndFade.w = 1.0f / macroDistance;
  616. Point3F macroIdStrengthParallax( matInfo->layerId,
  617. matInfo->mat->getMacroStrength(),
  618. 0 );
  619. pass->consts->setSafe( matInfo->macroInfoVConst, macroScaleAndFade );
  620. pass->consts->setSafe( matInfo->macroInfoPConst, macroIdStrengthParallax );
  621. }
  622. }
  623. bool TerrainCellMaterial::setupPass( const SceneRenderState *state,
  624. const SceneData &sceneData )
  625. {
  626. PROFILE_SCOPE( TerrainCellMaterial_SetupPass );
  627. if ( mCurrPass >= mPasses.size() )
  628. {
  629. mCurrPass = 0;
  630. return false;
  631. }
  632. Pass &pass = mPasses[mCurrPass];
  633. _updateMaterialConsts( &pass );
  634. if ( pass.baseTexMapConst->isValid() )
  635. GFX->setTexture( pass.baseTexMapConst->getSamplerRegister(), mTerrain->mBaseTex.getPointer() );
  636. if ( pass.layerTexConst->isValid() )
  637. GFX->setTexture( pass.layerTexConst->getSamplerRegister(), mTerrain->mLayerTex.getPointer() );
  638. if ( pass.lightMapTexConst->isValid() )
  639. GFX->setTexture( pass.lightMapTexConst->getSamplerRegister(), mTerrain->getLightMapTex() );
  640. if ( sceneData.wireframe )
  641. GFX->setStateBlock( pass.wireframeStateBlock );
  642. else if ( state->isReflectPass( ))
  643. GFX->setStateBlock( pass.reflectionStateBlock );
  644. else
  645. GFX->setStateBlock( pass.stateBlock );
  646. GFX->setShader( pass.shader );
  647. GFX->setShaderConstBuffer( pass.consts );
  648. // Let the light manager prepare any light stuff it needs.
  649. LIGHTMGR->setLightInfo( NULL,
  650. NULL,
  651. sceneData,
  652. state,
  653. mCurrPass,
  654. pass.consts );
  655. for ( U32 i=0; i < pass.materials.size(); i++ )
  656. {
  657. MaterialInfo *matInfo = pass.materials[i];
  658. if ( matInfo->detailTexConst->isValid() )
  659. GFX->setTexture( matInfo->detailTexConst->getSamplerRegister(), matInfo->detailTex );
  660. if ( matInfo->macroTexConst->isValid() )
  661. GFX->setTexture( matInfo->macroTexConst->getSamplerRegister(), matInfo->macroTex );
  662. if ( matInfo->normalTexConst->isValid() )
  663. GFX->setTexture( matInfo->normalTexConst->getSamplerRegister(), matInfo->normalTex );
  664. }
  665. pass.consts->setSafe( pass.layerSizeConst, (F32)mTerrain->mLayerTex.getWidth() );
  666. if ( pass.oneOverTerrainSize->isValid() )
  667. {
  668. F32 oneOverTerrainSize = 1.0f / mTerrain->getWorldBlockSize();
  669. pass.consts->set( pass.oneOverTerrainSize, oneOverTerrainSize );
  670. }
  671. pass.consts->setSafe( pass.squareSize, mTerrain->getSquareSize() );
  672. if ( pass.fogDataConst->isValid() )
  673. {
  674. Point3F fogData;
  675. fogData.x = sceneData.fogDensity;
  676. fogData.y = sceneData.fogDensityOffset;
  677. fogData.z = sceneData.fogHeightFalloff;
  678. pass.consts->set( pass.fogDataConst, fogData );
  679. }
  680. pass.consts->setSafe( pass.fogColorConst, sceneData.fogColor );
  681. if ( pass.lightInfoBufferConst->isValid() &&
  682. pass.lightParamsConst->isValid() )
  683. {
  684. if ( !mLightInfoTarget )
  685. mLightInfoTarget = NamedTexTarget::find( "lightinfo" );
  686. GFXTextureObject *texObject = mLightInfoTarget->getTexture();
  687. // TODO: Sometimes during reset of the light manager we get a
  688. // NULL texture here. This is corrected on the next frame, but
  689. // we should still investigate why that happens.
  690. if ( texObject )
  691. {
  692. GFX->setTexture( pass.lightInfoBufferConst->getSamplerRegister(), texObject );
  693. const Point3I &targetSz = texObject->getSize();
  694. const RectI &targetVp = mLightInfoTarget->getViewport();
  695. Point4F rtParams;
  696. ScreenSpace::RenderTargetParameters(targetSz, targetVp, rtParams);
  697. pass.consts->setSafe( pass.lightParamsConst, rtParams );
  698. }
  699. }
  700. ++mCurrPass;
  701. return true;
  702. }
  703. BaseMatInstance* TerrainCellMaterial::getShadowMat()
  704. {
  705. // Find our material which has some settings
  706. // defined on it in script.
  707. Material *mat = MATMGR->getMaterialDefinitionByName( "AL_DefaultShadowMaterial" );
  708. // Create the material instance adding the feature which
  709. // handles rendering terrain cut outs.
  710. FeatureSet features = MATMGR->getDefaultFeatures();
  711. BaseMatInstance *matInst = mat->createMatInstance();
  712. if ( !matInst->init( features, getGFXVertexFormat<TerrVertex>() ) )
  713. {
  714. delete matInst;
  715. matInst = NULL;
  716. }
  717. return matInst;
  718. }