renderPrePassMgr.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  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 "renderInstance/renderPrePassMgr.h"
  24. #include "gfx/gfxTransformSaver.h"
  25. #include "materials/sceneData.h"
  26. #include "materials/materialManager.h"
  27. #include "materials/materialFeatureTypes.h"
  28. #include "core/util/safeDelete.h"
  29. #include "shaderGen/featureMgr.h"
  30. #include "shaderGen/HLSL/depthHLSL.h"
  31. #include "shaderGen/GLSL/depthGLSL.h"
  32. #include "shaderGen/conditionerFeature.h"
  33. #include "shaderGen/shaderGenVars.h"
  34. #include "scene/sceneRenderState.h"
  35. #include "gfx/gfxStringEnumTranslate.h"
  36. #include "gfx/gfxDebugEvent.h"
  37. #include "materials/customMaterialDefinition.h"
  38. #include "lighting/advanced/advancedLightManager.h"
  39. #include "lighting/advanced/advancedLightBinManager.h"
  40. #include "terrain/terrCell.h"
  41. #include "renderInstance/renderTerrainMgr.h"
  42. #include "terrain/terrCellMaterial.h"
  43. #include "math/mathUtils.h"
  44. #include "math/util/matrixSet.h"
  45. const MatInstanceHookType PrePassMatInstanceHook::Type( "PrePass" );
  46. const String RenderPrePassMgr::BufferName("prepass");
  47. const RenderInstType RenderPrePassMgr::RIT_PrePass("PrePass");
  48. IMPLEMENT_CONOBJECT(RenderPrePassMgr);
  49. ConsoleDocClass( RenderPrePassMgr,
  50. "@brief The render bin which performs a z+normals prepass used in Advanced Lighting.\n\n"
  51. "This render bin is used in Advanced Lighting to gather all opaque mesh render instances "
  52. "and render them to the g-buffer for use in lighting the scene and doing effects.\n\n"
  53. "PostEffect and other shaders can access the output of this bin by using the #prepass "
  54. "texture target name. See the edge anti-aliasing post effect for an example.\n\n"
  55. "@see game/core/scripts/client/postFx/edgeAA.cs\n"
  56. "@ingroup RenderBin\n" );
  57. RenderPrePassMgr::RenderSignal& RenderPrePassMgr::getRenderSignal()
  58. {
  59. static RenderSignal theSignal;
  60. return theSignal;
  61. }
  62. RenderPrePassMgr::RenderPrePassMgr( bool gatherDepth,
  63. GFXFormat format )
  64. : Parent( RIT_PrePass,
  65. 0.01f,
  66. 0.01f,
  67. format,
  68. Point2I( Parent::DefaultTargetSize, Parent::DefaultTargetSize),
  69. gatherDepth ? Parent::DefaultTargetChainLength : 0 ),
  70. mPrePassMatInstance( NULL )
  71. {
  72. notifyType( RenderPassManager::RIT_Decal );
  73. notifyType( RenderPassManager::RIT_Mesh );
  74. notifyType( RenderPassManager::RIT_Interior );
  75. notifyType( RenderPassManager::RIT_Terrain );
  76. notifyType( RenderPassManager::RIT_Object );
  77. // We want a full-resolution buffer
  78. mTargetSizeType = RenderTexTargetBinManager::WindowSize;
  79. if(getTargetChainLength() > 0)
  80. GFXShader::addGlobalMacro( "TORQUE_LINEAR_DEPTH" );
  81. mNamedTarget.registerWithName( BufferName );
  82. _registerFeatures();
  83. }
  84. RenderPrePassMgr::~RenderPrePassMgr()
  85. {
  86. GFXShader::removeGlobalMacro( "TORQUE_LINEAR_DEPTH" );
  87. _unregisterFeatures();
  88. SAFE_DELETE( mPrePassMatInstance );
  89. }
  90. void RenderPrePassMgr::_registerFeatures()
  91. {
  92. ConditionerFeature *cond = new LinearEyeDepthConditioner( getTargetFormat() );
  93. FEATUREMGR->registerFeature( MFT_PrePassConditioner, cond );
  94. mNamedTarget.setConditioner( cond );
  95. }
  96. void RenderPrePassMgr::_unregisterFeatures()
  97. {
  98. mNamedTarget.setConditioner( NULL );
  99. FEATUREMGR->unregisterFeature(MFT_PrePassConditioner);
  100. }
  101. bool RenderPrePassMgr::setTargetSize(const Point2I &newTargetSize)
  102. {
  103. bool ret = Parent::setTargetSize( newTargetSize );
  104. mNamedTarget.setViewport( GFX->getViewport() );
  105. return ret;
  106. }
  107. bool RenderPrePassMgr::_updateTargets()
  108. {
  109. PROFILE_SCOPE(RenderPrePassMgr_updateTargets);
  110. bool ret = Parent::_updateTargets();
  111. // check for an output conditioner, and update it's format
  112. ConditionerFeature *outputConditioner = dynamic_cast<ConditionerFeature *>(FEATUREMGR->getByType(MFT_PrePassConditioner));
  113. if( outputConditioner && outputConditioner->setBufferFormat(mTargetFormat) )
  114. {
  115. // reload materials, the conditioner needs to alter the generated shaders
  116. }
  117. // Attach the light info buffer as a second render target, if there is
  118. // lightmapped geometry in the scene.
  119. AdvancedLightBinManager *lightBin;
  120. if ( Sim::findObject( "AL_LightBinMgr", lightBin ) &&
  121. lightBin->MRTLightmapsDuringPrePass() &&
  122. lightBin->isProperlyAdded() )
  123. {
  124. // Update the size of the light bin target here. This will call _updateTargets
  125. // on the light bin
  126. ret &= lightBin->setTargetSize( mTargetSize );
  127. if ( ret )
  128. {
  129. // Sanity check
  130. AssertFatal(lightBin->getTargetChainLength() == mTargetChainLength, "Target chain length mismatch");
  131. // Attach light info buffer to Color1 for each target in the chain
  132. for ( U32 i = 0; i < mTargetChainLength; i++ )
  133. {
  134. GFXTexHandle lightInfoTex = lightBin->getTargetTexture(0, i);
  135. mTargetChain[i]->attachTexture(GFXTextureTarget::Color1, lightInfoTex);
  136. }
  137. }
  138. }
  139. return ret;
  140. }
  141. void RenderPrePassMgr::_createPrePassMaterial()
  142. {
  143. SAFE_DELETE(mPrePassMatInstance);
  144. const GFXVertexFormat *vertexFormat = getGFXVertexFormat<GFXVertexPNTTB>();
  145. MatInstance* prepassMat = static_cast<MatInstance*>(MATMGR->createMatInstance("AL_DefaultPrePassMaterial", vertexFormat));
  146. AssertFatal( prepassMat, "TODO: Handle this better." );
  147. mPrePassMatInstance = new PrePassMatInstance(prepassMat, this);
  148. mPrePassMatInstance->init( MATMGR->getDefaultFeatures(), vertexFormat);
  149. delete prepassMat;
  150. }
  151. void RenderPrePassMgr::setPrePassMaterial( PrePassMatInstance *mat )
  152. {
  153. SAFE_DELETE(mPrePassMatInstance);
  154. mPrePassMatInstance = mat;
  155. }
  156. void RenderPrePassMgr::addElement( RenderInst *inst )
  157. {
  158. PROFILE_SCOPE( RenderPrePassMgr_addElement )
  159. // Skip out if this bin is disabled.
  160. if ( gClientSceneGraph->getCurrentRenderState() &&
  161. gClientSceneGraph->getCurrentRenderState()->disableAdvancedLightingBins() )
  162. return;
  163. // First what type of render instance is it?
  164. const bool isDecalMeshInst = inst->type == RenderPassManager::RIT_Decal;
  165. const bool isMeshInst = inst->type == RenderPassManager::RIT_Mesh ||
  166. inst->type == RenderPassManager::RIT_Interior;
  167. const bool isTerrainInst = inst->type == RenderPassManager::RIT_Terrain;
  168. // Get the material if its a mesh.
  169. BaseMatInstance* matInst = NULL;
  170. if ( isMeshInst || isDecalMeshInst )
  171. matInst = static_cast<MeshRenderInst*>(inst)->matInst;
  172. // Skip decals if they don't have normal maps.
  173. if ( isDecalMeshInst && !matInst->hasNormalMap() )
  174. return;
  175. // If its a custom material and it refracts... skip it.
  176. if ( matInst &&
  177. matInst->isCustomMaterial() &&
  178. static_cast<CustomMaterial*>( matInst->getMaterial() )->mRefract )
  179. return;
  180. // Make sure we got a prepass material.
  181. if ( matInst )
  182. {
  183. matInst = getPrePassMaterial( matInst );
  184. if ( !matInst || !matInst->isValid() )
  185. return;
  186. }
  187. // We're gonna add it to the bin... get the right element list.
  188. Vector< MainSortElem > *elementList;
  189. if ( isMeshInst || isDecalMeshInst )
  190. elementList = &mElementList;
  191. else if ( isTerrainInst )
  192. elementList = &mTerrainElementList;
  193. else
  194. elementList = &mObjectElementList;
  195. elementList->increment();
  196. MainSortElem &elem = elementList->last();
  197. elem.inst = inst;
  198. // Store the original key... we might need it.
  199. U32 originalKey = elem.key;
  200. // Sort front-to-back first to get the most fillrate savings.
  201. const F32 invSortDistSq = F32_MAX - inst->sortDistSq;
  202. elem.key = *((U32*)&invSortDistSq);
  203. // Next sort by pre-pass material if its a mesh... use the original sort key.
  204. if ( isMeshInst )
  205. elem.key2 = matInst->getStateHint();
  206. else
  207. elem.key2 = originalKey;
  208. }
  209. void RenderPrePassMgr::sort()
  210. {
  211. PROFILE_SCOPE( RenderPrePassMgr_sort );
  212. Parent::sort();
  213. dQsort( mTerrainElementList.address(), mTerrainElementList.size(), sizeof(MainSortElem), cmpKeyFunc);
  214. dQsort( mObjectElementList.address(), mObjectElementList.size(), sizeof(MainSortElem), cmpKeyFunc);
  215. }
  216. void RenderPrePassMgr::clear()
  217. {
  218. Parent::clear();
  219. mTerrainElementList.clear();
  220. mObjectElementList.clear();
  221. }
  222. void RenderPrePassMgr::render( SceneRenderState *state )
  223. {
  224. PROFILE_SCOPE(RenderPrePassMgr_render);
  225. // Take a look at the SceneRenderState and see if we should skip drawing the pre-pass
  226. if ( state->disableAdvancedLightingBins() )
  227. return;
  228. // NOTE: We don't early out here when the element list is
  229. // zero because we need the prepass to be cleared.
  230. // Automagically save & restore our viewport and transforms.
  231. GFXTransformSaver saver;
  232. GFXDEBUGEVENT_SCOPE( RenderPrePassMgr_Render, ColorI::RED );
  233. // Tell the superclass we're about to render
  234. const bool isRenderingToTarget = _onPreRender(state);
  235. // Clear all the buffers to white so that the
  236. // default depth is to the far plane.
  237. GFX->clear( GFXClearTarget | GFXClearZBuffer | GFXClearStencil, ColorI::WHITE, 1.0f, 0);
  238. // Restore transforms
  239. MatrixSet &matrixSet = getRenderPass()->getMatrixSet();
  240. matrixSet.restoreSceneViewProjection();
  241. const MatrixF worldViewXfm = GFX->getWorldMatrix();
  242. // Setup the default prepass material for object instances.
  243. if ( !mPrePassMatInstance )
  244. _createPrePassMaterial();
  245. if ( mPrePassMatInstance )
  246. {
  247. matrixSet.setWorld(MatrixF::Identity);
  248. mPrePassMatInstance->setTransforms(matrixSet, state);
  249. }
  250. // Signal start of pre-pass
  251. getRenderSignal().trigger( state, this, true );
  252. // First do a loop and render all the terrain... these are
  253. // usually the big blockers in a scene and will save us fillrate
  254. // on the smaller meshes and objects.
  255. // The terrain doesn't need any scene graph data
  256. // in the the prepass... so just clear it.
  257. SceneData sgData;
  258. sgData.init( state, SceneData::PrePassBin );
  259. Vector< MainSortElem >::const_iterator itr = mTerrainElementList.begin();
  260. for ( ; itr != mTerrainElementList.end(); itr++ )
  261. {
  262. TerrainRenderInst *ri = static_cast<TerrainRenderInst*>( itr->inst );
  263. TerrainCellMaterial *mat = ri->cellMat->getPrePassMat();
  264. GFX->setPrimitiveBuffer( ri->primBuff );
  265. GFX->setVertexBuffer( ri->vertBuff );
  266. mat->setTransformAndEye( *ri->objectToWorldXfm,
  267. worldViewXfm,
  268. GFX->getProjectionMatrix(),
  269. state->getFarPlane() );
  270. while ( mat->setupPass( state, sgData ) )
  271. GFX->drawPrimitive( ri->prim );
  272. }
  273. // Next render all the meshes.
  274. itr = mElementList.begin();
  275. for ( ; itr != mElementList.end(); )
  276. {
  277. MeshRenderInst *ri = static_cast<MeshRenderInst*>( itr->inst );
  278. // Get the prepass material.
  279. BaseMatInstance *mat = getPrePassMaterial( ri->matInst );
  280. // Set up SG data proper like and flag it
  281. // as a pre-pass render
  282. setupSGData( ri, sgData );
  283. Vector< MainSortElem >::const_iterator meshItr, endOfBatchItr = itr;
  284. while ( mat->setupPass( state, sgData ) )
  285. {
  286. meshItr = itr;
  287. for ( ; meshItr != mElementList.end(); meshItr++ )
  288. {
  289. MeshRenderInst *passRI = static_cast<MeshRenderInst*>( meshItr->inst );
  290. // Check to see if we need to break this batch.
  291. //
  292. // NOTE: We're comparing the non-prepass materials
  293. // here so we don't incur the cost of looking up the
  294. // prepass hook on each inst.
  295. //
  296. if ( newPassNeeded( ri, passRI ) )
  297. break;
  298. // Set up SG data for this instance.
  299. setupSGData( passRI, sgData );
  300. matrixSet.setWorld(*passRI->objectToWorld);
  301. matrixSet.setView(*passRI->worldToCamera);
  302. matrixSet.setProjection(*passRI->projection);
  303. mat->setSceneInfo(state, sgData);
  304. mat->setTransforms(matrixSet, state);
  305. // If we're instanced then don't render yet.
  306. if ( mat->isInstanced() )
  307. {
  308. // Let the material increment the instance buffer, but
  309. // break the batch if it runs out of room for more.
  310. if ( !mat->stepInstance() )
  311. {
  312. meshItr++;
  313. break;
  314. }
  315. continue;
  316. }
  317. // Setup the vertex and index buffers.
  318. mat->setBuffers( passRI->vertBuff, passRI->primBuff );
  319. // Render this sucker.
  320. if ( passRI->prim )
  321. GFX->drawPrimitive( *passRI->prim );
  322. else
  323. GFX->drawPrimitive( passRI->primBuffIndex );
  324. }
  325. // Draw the instanced batch.
  326. if ( mat->isInstanced() )
  327. {
  328. // Sets the buffers including the instancing stream.
  329. mat->setBuffers( ri->vertBuff, ri->primBuff );
  330. if ( ri->prim )
  331. GFX->drawPrimitive( *ri->prim );
  332. else
  333. GFX->drawPrimitive( ri->primBuffIndex );
  334. }
  335. endOfBatchItr = meshItr;
  336. } // while( mat->setupPass(state, sgData) )
  337. // Force the increment if none happened, otherwise go to end of batch.
  338. itr = ( itr == endOfBatchItr ) ? itr + 1 : endOfBatchItr;
  339. }
  340. // The final loop is for object render instances.
  341. itr = mObjectElementList.begin();
  342. for ( ; itr != mObjectElementList.end(); itr++ )
  343. {
  344. ObjectRenderInst *ri = static_cast<ObjectRenderInst*>( itr->inst );
  345. if ( ri->renderDelegate )
  346. ri->renderDelegate( ri, state, mPrePassMatInstance );
  347. }
  348. // Signal end of pre-pass
  349. getRenderSignal().trigger( state, this, false );
  350. if(isRenderingToTarget)
  351. _onPostRender();
  352. }
  353. const GFXStateBlockDesc & RenderPrePassMgr::getOpaqueStenciWriteDesc( bool lightmappedGeometry /*= true*/ )
  354. {
  355. static bool sbInit = false;
  356. static GFXStateBlockDesc sOpaqueStaticLitStencilWriteDesc;
  357. static GFXStateBlockDesc sOpaqueDynamicLitStencilWriteDesc;
  358. if(!sbInit)
  359. {
  360. sbInit = true;
  361. // Build the static opaque stencil write/test state block descriptions
  362. sOpaqueStaticLitStencilWriteDesc.stencilDefined = true;
  363. sOpaqueStaticLitStencilWriteDesc.stencilEnable = true;
  364. sOpaqueStaticLitStencilWriteDesc.stencilWriteMask = 0x03;
  365. sOpaqueStaticLitStencilWriteDesc.stencilMask = 0x03;
  366. sOpaqueStaticLitStencilWriteDesc.stencilRef = RenderPrePassMgr::OpaqueStaticLitMask;
  367. sOpaqueStaticLitStencilWriteDesc.stencilPassOp = GFXStencilOpReplace;
  368. sOpaqueStaticLitStencilWriteDesc.stencilFailOp = GFXStencilOpKeep;
  369. sOpaqueStaticLitStencilWriteDesc.stencilZFailOp = GFXStencilOpKeep;
  370. sOpaqueStaticLitStencilWriteDesc.stencilFunc = GFXCmpAlways;
  371. // Same only dynamic
  372. sOpaqueDynamicLitStencilWriteDesc = sOpaqueStaticLitStencilWriteDesc;
  373. sOpaqueDynamicLitStencilWriteDesc.stencilRef = RenderPrePassMgr::OpaqueDynamicLitMask;
  374. }
  375. return (lightmappedGeometry ? sOpaqueStaticLitStencilWriteDesc : sOpaqueDynamicLitStencilWriteDesc);
  376. }
  377. const GFXStateBlockDesc & RenderPrePassMgr::getOpaqueStencilTestDesc()
  378. {
  379. static bool sbInit = false;
  380. static GFXStateBlockDesc sOpaqueStencilTestDesc;
  381. if(!sbInit)
  382. {
  383. // Build opaque test
  384. sbInit = true;
  385. sOpaqueStencilTestDesc.stencilDefined = true;
  386. sOpaqueStencilTestDesc.stencilEnable = true;
  387. sOpaqueStencilTestDesc.stencilWriteMask = 0xFE;
  388. sOpaqueStencilTestDesc.stencilMask = 0x03;
  389. sOpaqueStencilTestDesc.stencilRef = 0;
  390. sOpaqueStencilTestDesc.stencilPassOp = GFXStencilOpKeep;
  391. sOpaqueStencilTestDesc.stencilFailOp = GFXStencilOpKeep;
  392. sOpaqueStencilTestDesc.stencilZFailOp = GFXStencilOpKeep;
  393. sOpaqueStencilTestDesc.stencilFunc = GFXCmpLess;
  394. }
  395. return sOpaqueStencilTestDesc;
  396. }
  397. //------------------------------------------------------------------------------
  398. //------------------------------------------------------------------------------
  399. ProcessedPrePassMaterial::ProcessedPrePassMaterial( Material& mat, const RenderPrePassMgr *prePassMgr )
  400. : Parent(mat), mPrePassMgr(prePassMgr)
  401. {
  402. }
  403. void ProcessedPrePassMaterial::_determineFeatures( U32 stageNum,
  404. MaterialFeatureData &fd,
  405. const FeatureSet &features )
  406. {
  407. Parent::_determineFeatures( stageNum, fd, features );
  408. // Find this for use down below...
  409. bool bEnableMRTLightmap = false;
  410. AdvancedLightBinManager *lightBin;
  411. if ( Sim::findObject( "AL_LightBinMgr", lightBin ) )
  412. bEnableMRTLightmap = lightBin->MRTLightmapsDuringPrePass();
  413. // If this material has a lightmap or tonemap (texture or baked vertex color),
  414. // it must be static. Otherwise it is dynamic.
  415. mIsLightmappedGeometry = ( fd.features.hasFeature( MFT_ToneMap ) ||
  416. fd.features.hasFeature( MFT_LightMap ) ||
  417. fd.features.hasFeature( MFT_VertLit ) ||
  418. ( bEnableMRTLightmap && fd.features.hasFeature( MFT_IsTranslucent ) ||
  419. fd.features.hasFeature( MFT_ForwardShading ) ||
  420. fd.features.hasFeature( MFT_IsTranslucentZWrite ) ) );
  421. // Integrate proper opaque stencil write state
  422. mUserDefined.addDesc( mPrePassMgr->getOpaqueStenciWriteDesc( mIsLightmappedGeometry ) );
  423. FeatureSet newFeatures;
  424. // These are always on for prepass.
  425. newFeatures.addFeature( MFT_EyeSpaceDepthOut );
  426. newFeatures.addFeature( MFT_PrePassConditioner );
  427. #ifndef TORQUE_DEDICATED
  428. for ( U32 i=0; i < fd.features.getCount(); i++ )
  429. {
  430. const FeatureType &type = fd.features.getAt( i );
  431. // Turn on the diffuse texture only if we
  432. // have alpha test.
  433. if ( type == MFT_AlphaTest )
  434. {
  435. newFeatures.addFeature( MFT_AlphaTest );
  436. newFeatures.addFeature( MFT_DiffuseMap );
  437. }
  438. else if ( type == MFT_IsTranslucentZWrite )
  439. {
  440. newFeatures.addFeature( MFT_IsTranslucentZWrite );
  441. newFeatures.addFeature( MFT_DiffuseMap );
  442. }
  443. // Always allow these.
  444. else if ( type == MFT_IsDXTnm ||
  445. type == MFT_TexAnim ||
  446. type == MFT_NormalMap ||
  447. type == MFT_DetailNormalMap ||
  448. type == MFT_AlphaTest ||
  449. type == MFT_Parallax ||
  450. type == MFT_InterlacedPrePass ||
  451. type == MFT_Visibility ||
  452. type == MFT_UseInstancing ||
  453. type == MFT_DiffuseVertColor )
  454. newFeatures.addFeature( type );
  455. // Add any transform features.
  456. else if ( type.getGroup() == MFG_PreTransform ||
  457. type.getGroup() == MFG_Transform ||
  458. type.getGroup() == MFG_PostTransform )
  459. newFeatures.addFeature( type );
  460. }
  461. // If there is lightmapped geometry support, add the MRT light buffer features
  462. if(bEnableMRTLightmap)
  463. {
  464. // If this material has a lightmap, pass it through, and flag it to
  465. // send it's output to RenderTarget1
  466. if( fd.features.hasFeature( MFT_ToneMap ) )
  467. {
  468. newFeatures.addFeature( MFT_ToneMap );
  469. newFeatures.addFeature( MFT_LightbufferMRT );
  470. }
  471. else if( fd.features.hasFeature( MFT_LightMap ) )
  472. {
  473. newFeatures.addFeature( MFT_LightMap );
  474. newFeatures.addFeature( MFT_LightbufferMRT );
  475. }
  476. else if( fd.features.hasFeature( MFT_VertLit ) )
  477. {
  478. // Flag un-tone-map if necesasary
  479. if( fd.features.hasFeature( MFT_DiffuseMap ) )
  480. newFeatures.addFeature( MFT_VertLitTone );
  481. newFeatures.addFeature( MFT_VertLit );
  482. newFeatures.addFeature( MFT_LightbufferMRT );
  483. }
  484. else
  485. {
  486. // If this object isn't lightmapped, add a zero-output feature to it
  487. newFeatures.addFeature( MFT_RenderTarget1_Zero );
  488. }
  489. }
  490. #endif
  491. // Set the new features.
  492. fd.features = newFeatures;
  493. }
  494. U32 ProcessedPrePassMaterial::getNumStages()
  495. {
  496. // Return 1 stage so this material gets processed for sure
  497. return 1;
  498. }
  499. void ProcessedPrePassMaterial::addStateBlockDesc(const GFXStateBlockDesc& desc)
  500. {
  501. GFXStateBlockDesc prePassStateBlock = desc;
  502. // Adjust color writes if this is a pure z-fill pass
  503. const bool pixelOutEnabled = mPrePassMgr->getTargetChainLength() > 0;
  504. if ( !pixelOutEnabled )
  505. {
  506. prePassStateBlock.colorWriteDefined = true;
  507. prePassStateBlock.colorWriteRed = pixelOutEnabled;
  508. prePassStateBlock.colorWriteGreen = pixelOutEnabled;
  509. prePassStateBlock.colorWriteBlue = pixelOutEnabled;
  510. prePassStateBlock.colorWriteAlpha = pixelOutEnabled;
  511. }
  512. // Never allow the alpha test state when rendering
  513. // the prepass as we use the alpha channel for the
  514. // depth information... MFT_AlphaTest will handle it.
  515. prePassStateBlock.alphaDefined = true;
  516. prePassStateBlock.alphaTestEnable = false;
  517. // If we're translucent then we're doing prepass blending
  518. // which never writes to the depth channels.
  519. const bool isTranslucent = getMaterial()->isTranslucent();
  520. if ( isTranslucent )
  521. {
  522. prePassStateBlock.setBlend( true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha );
  523. prePassStateBlock.setColorWrites( true, true, false, false );
  524. }
  525. // Enable z reads, but only enable zwrites if we're not translucent.
  526. prePassStateBlock.setZReadWrite( true, isTranslucent ? false : true );
  527. // Pass to parent
  528. Parent::addStateBlockDesc(prePassStateBlock);
  529. }
  530. PrePassMatInstance::PrePassMatInstance(MatInstance* root, const RenderPrePassMgr *prePassMgr)
  531. : Parent(*root->getMaterial()), mPrePassMgr(prePassMgr)
  532. {
  533. mFeatureList = root->getRequestedFeatures();
  534. mVertexFormat = root->getVertexFormat();
  535. mUserObject = root->getUserObject();
  536. }
  537. PrePassMatInstance::~PrePassMatInstance()
  538. {
  539. }
  540. ProcessedMaterial* PrePassMatInstance::getShaderMaterial()
  541. {
  542. return new ProcessedPrePassMaterial(*mMaterial, mPrePassMgr);
  543. }
  544. bool PrePassMatInstance::init( const FeatureSet &features,
  545. const GFXVertexFormat *vertexFormat )
  546. {
  547. return Parent::init( features, vertexFormat );
  548. }
  549. PrePassMatInstanceHook::PrePassMatInstanceHook( MatInstance *baseMatInst,
  550. const RenderPrePassMgr *prePassMgr )
  551. : mHookedPrePassMatInst(NULL), mPrePassManager(prePassMgr)
  552. {
  553. // If the material is a custom material then
  554. // hope that using DefaultPrePassMaterial gives
  555. // them a good prepass.
  556. if ( baseMatInst->isCustomMaterial() )
  557. {
  558. MatInstance* dummyInst = static_cast<MatInstance*>( MATMGR->createMatInstance( "AL_DefaultPrePassMaterial", baseMatInst->getVertexFormat() ) );
  559. mHookedPrePassMatInst = new PrePassMatInstance( dummyInst, prePassMgr );
  560. mHookedPrePassMatInst->init( dummyInst->getRequestedFeatures(), baseMatInst->getVertexFormat());
  561. delete dummyInst;
  562. return;
  563. }
  564. // Create the prepass material instance.
  565. mHookedPrePassMatInst = new PrePassMatInstance(baseMatInst, prePassMgr);
  566. mHookedPrePassMatInst->getFeaturesDelegate() = baseMatInst->getFeaturesDelegate();
  567. // Get the features, but remove the instancing feature if the
  568. // original material didn't end up using it.
  569. FeatureSet features = baseMatInst->getRequestedFeatures();
  570. if ( !baseMatInst->isInstanced() )
  571. features.removeFeature( MFT_UseInstancing );
  572. // Initialize the material.
  573. mHookedPrePassMatInst->init(features, baseMatInst->getVertexFormat());
  574. }
  575. PrePassMatInstanceHook::~PrePassMatInstanceHook()
  576. {
  577. SAFE_DELETE(mHookedPrePassMatInst);
  578. }
  579. //------------------------------------------------------------------------------
  580. //------------------------------------------------------------------------------
  581. void LinearEyeDepthConditioner::processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd )
  582. {
  583. // find depth
  584. ShaderFeature *depthFeat = FEATUREMGR->getByType( MFT_EyeSpaceDepthOut );
  585. AssertFatal( depthFeat != NULL, "No eye space depth feature found!" );
  586. Var *depth = (Var*) LangElement::find(depthFeat->getOutputVarName());
  587. AssertFatal( depth, "Something went bad with ShaderGen. The depth should be already generated by the EyeSpaceDepthOut feature." );
  588. MultiLine *meta = new MultiLine;
  589. meta->addStatement( assignOutput( depth ) );
  590. output = meta;
  591. }
  592. Var *LinearEyeDepthConditioner::_conditionOutput( Var *unconditionedOutput, MultiLine *meta )
  593. {
  594. Var *retVar = NULL;
  595. String fracMethodName = (GFX->getAdapterType() == OpenGL) ? "fract" : "frac";
  596. switch(getBufferFormat())
  597. {
  598. case GFXFormatR8G8B8A8:
  599. retVar = new Var;
  600. retVar->setType("float4");
  601. retVar->setName("_ppDepth");
  602. meta->addStatement( new GenOp( " // depth conditioner: packing to rgba\r\n" ) );
  603. meta->addStatement( new GenOp(
  604. avar( " @ = %s(@ * (255.0/256) * float4(1, 255, 255 * 255, 255 * 255 * 255));\r\n", fracMethodName.c_str() ),
  605. new DecOp(retVar), unconditionedOutput ) );
  606. break;
  607. default:
  608. retVar = unconditionedOutput;
  609. meta->addStatement( new GenOp( " // depth conditioner: no conditioning\r\n" ) );
  610. break;
  611. }
  612. AssertFatal( retVar != NULL, avar( "Cannot condition output to buffer format: %s", GFXStringTextureFormat[getBufferFormat()] ) );
  613. return retVar;
  614. }
  615. Var *LinearEyeDepthConditioner::_unconditionInput( Var *conditionedInput, MultiLine *meta )
  616. {
  617. String float4Typename = (GFX->getAdapterType() == OpenGL) ? "vec4" : "float4";
  618. Var *retVar = conditionedInput;
  619. if(getBufferFormat() != GFXFormat_COUNT)
  620. {
  621. retVar = new Var;
  622. retVar->setType(float4Typename.c_str());
  623. retVar->setName("_ppDepth");
  624. meta->addStatement( new GenOp( avar( " @ = %s(0, 0, 1, 1);\r\n", float4Typename.c_str() ), new DecOp(retVar) ) );
  625. switch(getBufferFormat())
  626. {
  627. case GFXFormatR32F:
  628. case GFXFormatR16F:
  629. meta->addStatement( new GenOp( " // depth conditioner: float texture\r\n" ) );
  630. meta->addStatement( new GenOp( " @.w = @.r;\r\n", retVar, conditionedInput ) );
  631. break;
  632. case GFXFormatR8G8B8A8:
  633. meta->addStatement( new GenOp( " // depth conditioner: unpacking from rgba\r\n" ) );
  634. meta->addStatement( new GenOp(
  635. avar( " @.w = dot(@ * (256.0/255), %s(1, 1 / 255, 1 / (255 * 255), 1 / (255 * 255 * 255)));\r\n", float4Typename.c_str() )
  636. , retVar, conditionedInput ) );
  637. break;
  638. default:
  639. AssertFatal(false, "LinearEyeDepthConditioner::_unconditionInput - Unrecognized buffer format");
  640. }
  641. }
  642. return retVar;
  643. }
  644. Var* LinearEyeDepthConditioner::printMethodHeader( MethodType methodType, const String &methodName, Stream &stream, MultiLine *meta )
  645. {
  646. const bool isCondition = ( methodType == ConditionerFeature::ConditionMethod );
  647. Var *retVal = NULL;
  648. // The uncondition method inputs are changed
  649. if( isCondition )
  650. retVal = Parent::printMethodHeader( methodType, methodName, stream, meta );
  651. else
  652. {
  653. Var *methodVar = new Var;
  654. methodVar->setName(methodName);
  655. if (GFX->getAdapterType() == OpenGL)
  656. methodVar->setType("vec4");
  657. else
  658. methodVar->setType("inline float4");
  659. DecOp *methodDecl = new DecOp(methodVar);
  660. Var *prepassSampler = new Var;
  661. prepassSampler->setName("prepassSamplerVar");
  662. prepassSampler->setType("sampler2D");
  663. DecOp *prepassSamplerDecl = new DecOp(prepassSampler);
  664. Var *screenUV = new Var;
  665. screenUV->setName("screenUVVar");
  666. if (GFX->getAdapterType() == OpenGL)
  667. screenUV->setType("vec2");
  668. else
  669. screenUV->setType("float2");
  670. DecOp *screenUVDecl = new DecOp(screenUV);
  671. Var *bufferSample = new Var;
  672. bufferSample->setName("bufferSample");
  673. if (GFX->getAdapterType() == OpenGL)
  674. bufferSample->setType("vec4");
  675. else
  676. bufferSample->setType("float4");
  677. DecOp *bufferSampleDecl = new DecOp(bufferSample);
  678. meta->addStatement( new GenOp( "@(@, @)\r\n", methodDecl, prepassSamplerDecl, screenUVDecl ) );
  679. meta->addStatement( new GenOp( "{\r\n" ) );
  680. meta->addStatement( new GenOp( " // Sampler g-buffer\r\n" ) );
  681. // The linear depth target has no mipmaps, so use tex2dlod when
  682. // possible so that the shader compiler can optimize.
  683. meta->addStatement( new GenOp( " #if TORQUE_SM >= 30\r\n" ) );
  684. if (GFX->getAdapterType() == OpenGL)
  685. meta->addStatement( new GenOp( " @ = texture2DLod(@, @, 0); \r\n", bufferSampleDecl, prepassSampler, screenUV) );
  686. else
  687. meta->addStatement( new GenOp( " @ = tex2Dlod(@, float4(@,0,0));\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
  688. meta->addStatement( new GenOp( " #else\r\n" ) );
  689. if (GFX->getAdapterType() == OpenGL)
  690. meta->addStatement( new GenOp( " @ = texture2D(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV) );
  691. else
  692. meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
  693. meta->addStatement( new GenOp( " #endif\r\n\r\n" ) );
  694. // We don't use this way of passing var's around, so this should cause a crash
  695. // if something uses this improperly
  696. retVal = bufferSample;
  697. }
  698. return retVal;
  699. }