renderPrePassMgr.cpp 30 KB

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