renderPrePassMgr.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  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 "gfx/gfxCardProfile.h"
  38. #include "materials/customMaterialDefinition.h"
  39. #include "lighting/advanced/advancedLightManager.h"
  40. #include "lighting/advanced/advancedLightBinManager.h"
  41. #include "terrain/terrCell.h"
  42. #include "renderInstance/renderTerrainMgr.h"
  43. #include "terrain/terrCellMaterial.h"
  44. #include "math/mathUtils.h"
  45. #include "math/util/matrixSet.h"
  46. #include "gfx/gfxTextureManager.h"
  47. #include "gfx/primBuilder.h"
  48. #include "gfx/gfxDrawUtil.h"
  49. #include "materials/shaderData.h"
  50. #include "gfx/sim/cubemapData.h"
  51. const MatInstanceHookType PrePassMatInstanceHook::Type( "PrePass" );
  52. const String RenderPrePassMgr::BufferName("prepass");
  53. const RenderInstType RenderPrePassMgr::RIT_PrePass("PrePass");
  54. const String RenderPrePassMgr::ColorBufferName("color");
  55. const String RenderPrePassMgr::MatInfoBufferName("matinfo");
  56. IMPLEMENT_CONOBJECT(RenderPrePassMgr);
  57. ConsoleDocClass( RenderPrePassMgr,
  58. "@brief The render bin which performs a z+normals prepass used in Advanced Lighting.\n\n"
  59. "This render bin is used in Advanced Lighting to gather all opaque mesh render instances "
  60. "and render them to the g-buffer for use in lighting the scene and doing effects.\n\n"
  61. "PostEffect and other shaders can access the output of this bin by using the #prepass "
  62. "texture target name. See the edge anti-aliasing post effect for an example.\n\n"
  63. "@see game/core/scripts/client/postFx/edgeAA.cs\n"
  64. "@ingroup RenderBin\n" );
  65. RenderPrePassMgr::RenderSignal& RenderPrePassMgr::getRenderSignal()
  66. {
  67. static RenderSignal theSignal;
  68. return theSignal;
  69. }
  70. RenderPrePassMgr::RenderPrePassMgr( bool gatherDepth,
  71. GFXFormat format )
  72. : Parent( RIT_PrePass,
  73. 0.01f,
  74. 0.01f,
  75. format,
  76. Point2I( Parent::DefaultTargetSize, Parent::DefaultTargetSize),
  77. gatherDepth ? Parent::DefaultTargetChainLength : 0 ),
  78. mPrePassMatInstance( NULL )
  79. {
  80. notifyType( RenderPassManager::RIT_Decal );
  81. notifyType( RenderPassManager::RIT_DecalRoad );
  82. notifyType( RenderPassManager::RIT_Mesh );
  83. notifyType( RenderPassManager::RIT_Terrain );
  84. notifyType( RenderPassManager::RIT_Object );
  85. // We want a full-resolution buffer
  86. mTargetSizeType = RenderTexTargetBinManager::WindowSize;
  87. if(getTargetChainLength() > 0)
  88. GFXShader::addGlobalMacro( "TORQUE_LINEAR_DEPTH" );
  89. mNamedTarget.registerWithName( BufferName );
  90. mColorTarget.registerWithName( ColorBufferName );
  91. mMatInfoTarget.registerWithName( MatInfoBufferName );
  92. mClearGBufferShader = NULL;
  93. _registerFeatures();
  94. }
  95. RenderPrePassMgr::~RenderPrePassMgr()
  96. {
  97. GFXShader::removeGlobalMacro( "TORQUE_LINEAR_DEPTH" );
  98. mColorTarget.release();
  99. mMatInfoTarget.release();
  100. _unregisterFeatures();
  101. SAFE_DELETE( mPrePassMatInstance );
  102. }
  103. void RenderPrePassMgr::_registerFeatures()
  104. {
  105. ConditionerFeature *cond = new LinearEyeDepthConditioner( getTargetFormat() );
  106. FEATUREMGR->registerFeature( MFT_PrePassConditioner, cond );
  107. mNamedTarget.setConditioner( cond );
  108. }
  109. void RenderPrePassMgr::_unregisterFeatures()
  110. {
  111. mNamedTarget.setConditioner( NULL );
  112. FEATUREMGR->unregisterFeature(MFT_PrePassConditioner);
  113. }
  114. bool RenderPrePassMgr::setTargetSize(const Point2I &newTargetSize)
  115. {
  116. bool ret = Parent::setTargetSize( newTargetSize );
  117. mNamedTarget.setViewport( GFX->getViewport() );
  118. mColorTarget.setViewport( GFX->getViewport() );
  119. mMatInfoTarget.setViewport( GFX->getViewport() );
  120. return ret;
  121. }
  122. bool RenderPrePassMgr::_updateTargets()
  123. {
  124. PROFILE_SCOPE(RenderPrePassMgr_updateTargets);
  125. bool ret = Parent::_updateTargets();
  126. // check for an output conditioner, and update it's format
  127. ConditionerFeature *outputConditioner = dynamic_cast<ConditionerFeature *>(FEATUREMGR->getByType(MFT_PrePassConditioner));
  128. if( outputConditioner && outputConditioner->setBufferFormat(mTargetFormat) )
  129. {
  130. // reload materials, the conditioner needs to alter the generated shaders
  131. }
  132. GFXFormat colorFormat = mTargetFormat;
  133. bool independentMrtBitDepth = GFX->getCardProfiler()->queryProfile("independentMrtBitDepth", false);
  134. //If independent bit depth on a MRT is supported than just use 8bit channels for the albedo color.
  135. if(independentMrtBitDepth)
  136. colorFormat = GFXFormatR8G8B8A8;
  137. // andrewmac: Deferred Shading Color Buffer
  138. if (mColorTex.getFormat() != colorFormat || mColorTex.getWidthHeight() != mTargetSize || GFX->recentlyReset())
  139. {
  140. mColorTarget.release();
  141. mColorTex.set(mTargetSize.x, mTargetSize.y, colorFormat,
  142. &GFXDefaultRenderTargetProfile, avar("%s() - (line %d)", __FUNCTION__, __LINE__),
  143. 1, GFXTextureManager::AA_MATCH_BACKBUFFER);
  144. mColorTarget.setTexture(mColorTex);
  145. for (U32 i = 0; i < mTargetChainLength; i++)
  146. mTargetChain[i]->attachTexture(GFXTextureTarget::Color1, mColorTarget.getTexture());
  147. }
  148. // andrewmac: Deferred Shading Material Info Buffer
  149. if (mMatInfoTex.getFormat() != colorFormat || mMatInfoTex.getWidthHeight() != mTargetSize || GFX->recentlyReset())
  150. {
  151. mMatInfoTarget.release();
  152. mMatInfoTex.set(mTargetSize.x, mTargetSize.y, colorFormat,
  153. &GFXDefaultRenderTargetProfile, avar("%s() - (line %d)", __FUNCTION__, __LINE__),
  154. 1, GFXTextureManager::AA_MATCH_BACKBUFFER);
  155. mMatInfoTarget.setTexture(mMatInfoTex);
  156. for (U32 i = 0; i < mTargetChainLength; i++)
  157. mTargetChain[i]->attachTexture(GFXTextureTarget::Color2, mMatInfoTarget.getTexture());
  158. }
  159. GFX->finalizeReset();
  160. // Attach the light info buffer as a second render target, if there is
  161. // lightmapped geometry in the scene.
  162. AdvancedLightBinManager *lightBin;
  163. if ( Sim::findObject( "AL_LightBinMgr", lightBin ) &&
  164. lightBin->MRTLightmapsDuringPrePass() &&
  165. lightBin->isProperlyAdded() )
  166. {
  167. // Update the size of the light bin target here. This will call _updateTargets
  168. // on the light bin
  169. ret &= lightBin->setTargetSize( mTargetSize );
  170. if ( ret )
  171. {
  172. // Sanity check
  173. AssertFatal(lightBin->getTargetChainLength() == mTargetChainLength, "Target chain length mismatch");
  174. // Attach light info buffer to Color1 for each target in the chain
  175. for ( U32 i = 0; i < mTargetChainLength; i++ )
  176. {
  177. GFXTexHandle lightInfoTex = lightBin->getTargetTexture(0, i);
  178. mTargetChain[i]->attachTexture(GFXTextureTarget::Color3, lightInfoTex);
  179. }
  180. }
  181. }
  182. _initShaders();
  183. return ret;
  184. }
  185. void RenderPrePassMgr::_createPrePassMaterial()
  186. {
  187. SAFE_DELETE(mPrePassMatInstance);
  188. const GFXVertexFormat *vertexFormat = getGFXVertexFormat<GFXVertexPNTTB>();
  189. MatInstance* prepassMat = static_cast<MatInstance*>(MATMGR->createMatInstance("AL_DefaultPrePassMaterial", vertexFormat));
  190. AssertFatal( prepassMat, "TODO: Handle this better." );
  191. mPrePassMatInstance = new PrePassMatInstance(prepassMat, this);
  192. mPrePassMatInstance->init( MATMGR->getDefaultFeatures(), vertexFormat);
  193. delete prepassMat;
  194. }
  195. void RenderPrePassMgr::setPrePassMaterial( PrePassMatInstance *mat )
  196. {
  197. SAFE_DELETE(mPrePassMatInstance);
  198. mPrePassMatInstance = mat;
  199. }
  200. void RenderPrePassMgr::addElement( RenderInst *inst )
  201. {
  202. PROFILE_SCOPE( RenderPrePassMgr_addElement )
  203. // Skip out if this bin is disabled.
  204. if ( gClientSceneGraph->getCurrentRenderState() &&
  205. gClientSceneGraph->getCurrentRenderState()->disableAdvancedLightingBins() )
  206. return;
  207. // First what type of render instance is it?
  208. const bool isDecalMeshInst = ((inst->type == RenderPassManager::RIT_Decal)||(inst->type == RenderPassManager::RIT_DecalRoad));
  209. const bool isMeshInst = inst->type == RenderPassManager::RIT_Mesh;
  210. const bool isTerrainInst = inst->type == RenderPassManager::RIT_Terrain;
  211. // Get the material if its a mesh.
  212. BaseMatInstance* matInst = NULL;
  213. if ( isMeshInst || isDecalMeshInst )
  214. matInst = static_cast<MeshRenderInst*>(inst)->matInst;
  215. if (matInst)
  216. {
  217. // Skip decals if they don't have normal maps.
  218. if (isDecalMeshInst && !matInst->hasNormalMap())
  219. return;
  220. // If its a custom material and it refracts... skip it.
  221. if (matInst->isCustomMaterial() &&
  222. static_cast<CustomMaterial*>(matInst->getMaterial())->mRefract)
  223. return;
  224. // Make sure we got a prepass material.
  225. matInst = getPrePassMaterial(matInst);
  226. if (!matInst || !matInst->isValid())
  227. return;
  228. }
  229. // We're gonna add it to the bin... get the right element list.
  230. Vector< MainSortElem > *elementList;
  231. if ( isMeshInst || isDecalMeshInst )
  232. elementList = &mElementList;
  233. else if ( isTerrainInst )
  234. elementList = &mTerrainElementList;
  235. else
  236. elementList = &mObjectElementList;
  237. elementList->increment();
  238. MainSortElem &elem = elementList->last();
  239. elem.inst = inst;
  240. // Store the original key... we might need it.
  241. U32 originalKey = elem.key;
  242. // Sort front-to-back first to get the most fillrate savings.
  243. const F32 invSortDistSq = F32_MAX - inst->sortDistSq;
  244. elem.key = *((U32*)&invSortDistSq);
  245. // Next sort by pre-pass material if its a mesh... use the original sort key.
  246. if (isMeshInst && matInst)
  247. elem.key2 = matInst->getStateHint();
  248. else
  249. elem.key2 = originalKey;
  250. }
  251. void RenderPrePassMgr::sort()
  252. {
  253. PROFILE_SCOPE( RenderPrePassMgr_sort );
  254. Parent::sort();
  255. dQsort( mTerrainElementList.address(), mTerrainElementList.size(), sizeof(MainSortElem), cmpKeyFunc);
  256. dQsort( mObjectElementList.address(), mObjectElementList.size(), sizeof(MainSortElem), cmpKeyFunc);
  257. }
  258. void RenderPrePassMgr::clear()
  259. {
  260. Parent::clear();
  261. mTerrainElementList.clear();
  262. mObjectElementList.clear();
  263. }
  264. void RenderPrePassMgr::render( SceneRenderState *state )
  265. {
  266. PROFILE_SCOPE(RenderPrePassMgr_render);
  267. // Take a look at the SceneRenderState and see if we should skip drawing the pre-pass
  268. if ( state->disableAdvancedLightingBins() )
  269. return;
  270. // NOTE: We don't early out here when the element list is
  271. // zero because we need the prepass to be cleared.
  272. // Automagically save & restore our viewport and transforms.
  273. GFXTransformSaver saver;
  274. GFXDEBUGEVENT_SCOPE( RenderPrePassMgr_Render, ColorI::RED );
  275. // Tell the superclass we're about to render
  276. const bool isRenderingToTarget = _onPreRender(state);
  277. // Clear all z-buffer, and g-buffer.
  278. clearBuffers();
  279. // Restore transforms
  280. MatrixSet &matrixSet = getRenderPass()->getMatrixSet();
  281. matrixSet.restoreSceneViewProjection();
  282. const MatrixF worldViewXfm = GFX->getWorldMatrix();
  283. // Setup the default prepass material for object instances.
  284. if ( !mPrePassMatInstance )
  285. _createPrePassMaterial();
  286. if ( mPrePassMatInstance )
  287. {
  288. matrixSet.setWorld(MatrixF::Identity);
  289. mPrePassMatInstance->setTransforms(matrixSet, state);
  290. }
  291. // Signal start of pre-pass
  292. getRenderSignal().trigger( state, this, true );
  293. // First do a loop and render all the terrain... these are
  294. // usually the big blockers in a scene and will save us fillrate
  295. // on the smaller meshes and objects.
  296. // The terrain doesn't need any scene graph data
  297. // in the the prepass... so just clear it.
  298. SceneData sgData;
  299. sgData.init( state, SceneData::PrePassBin );
  300. Vector< MainSortElem >::const_iterator itr = mTerrainElementList.begin();
  301. for ( ; itr != mTerrainElementList.end(); itr++ )
  302. {
  303. TerrainRenderInst *ri = static_cast<TerrainRenderInst*>( itr->inst );
  304. TerrainCellMaterial *mat = ri->cellMat->getPrePassMat();
  305. GFX->setPrimitiveBuffer( ri->primBuff );
  306. GFX->setVertexBuffer( ri->vertBuff );
  307. mat->setTransformAndEye( *ri->objectToWorldXfm,
  308. worldViewXfm,
  309. GFX->getProjectionMatrix(),
  310. state->getFarPlane() );
  311. while ( mat->setupPass( state, sgData ) )
  312. GFX->drawPrimitive( ri->prim );
  313. }
  314. // init loop data
  315. GFXTextureObject *lastLM = NULL;
  316. GFXCubemap *lastCubemap = NULL;
  317. GFXTextureObject *lastReflectTex = NULL;
  318. GFXTextureObject *lastMiscTex = NULL;
  319. GFXTextureObject *lastAccuTex = NULL;
  320. // Next render all the meshes.
  321. itr = mElementList.begin();
  322. for ( ; itr != mElementList.end(); )
  323. {
  324. MeshRenderInst *ri = static_cast<MeshRenderInst*>( itr->inst );
  325. // Get the prepass material.
  326. BaseMatInstance *mat = getPrePassMaterial( ri->matInst );
  327. // Set up SG data proper like and flag it
  328. // as a pre-pass render
  329. setupSGData( ri, sgData );
  330. Vector< MainSortElem >::const_iterator meshItr, endOfBatchItr = itr;
  331. while ( mat->setupPass( state, sgData ) )
  332. {
  333. meshItr = itr;
  334. for ( ; meshItr != mElementList.end(); meshItr++ )
  335. {
  336. MeshRenderInst *passRI = static_cast<MeshRenderInst*>( meshItr->inst );
  337. // Check to see if we need to break this batch.
  338. //
  339. // NOTE: We're comparing the non-prepass materials
  340. // here so we don't incur the cost of looking up the
  341. // prepass hook on each inst.
  342. //
  343. if ( newPassNeeded( ri, passRI ) )
  344. break;
  345. // Set up SG data for this instance.
  346. setupSGData( passRI, sgData );
  347. mat->setSceneInfo(state, sgData);
  348. matrixSet.setWorld(*passRI->objectToWorld);
  349. matrixSet.setView(*passRI->worldToCamera);
  350. matrixSet.setProjection(*passRI->projection);
  351. mat->setTransforms(matrixSet, state);
  352. // If we're instanced then don't render yet.
  353. if ( mat->isInstanced() )
  354. {
  355. // Let the material increment the instance buffer, but
  356. // break the batch if it runs out of room for more.
  357. if ( !mat->stepInstance() )
  358. {
  359. meshItr++;
  360. break;
  361. }
  362. continue;
  363. }
  364. bool dirty = false;
  365. // set the lightmaps if different
  366. if( passRI->lightmap && passRI->lightmap != lastLM )
  367. {
  368. sgData.lightmap = passRI->lightmap;
  369. lastLM = passRI->lightmap;
  370. dirty = true;
  371. }
  372. // set the cubemap if different.
  373. if ( passRI->cubemap != lastCubemap )
  374. {
  375. sgData.cubemap = passRI->cubemap;
  376. lastCubemap = passRI->cubemap;
  377. dirty = true;
  378. }
  379. if ( passRI->reflectTex != lastReflectTex )
  380. {
  381. sgData.reflectTex = passRI->reflectTex;
  382. lastReflectTex = passRI->reflectTex;
  383. dirty = true;
  384. }
  385. // Update accumulation texture if it changed.
  386. // Note: accumulation texture can be NULL, and must be updated.
  387. if (passRI->accuTex != lastAccuTex)
  388. {
  389. sgData.accuTex = passRI->accuTex;
  390. lastAccuTex = lastAccuTex;
  391. dirty = true;
  392. }
  393. if ( dirty )
  394. mat->setTextureStages( state, sgData );
  395. // Setup the vertex and index buffers.
  396. mat->setBuffers( passRI->vertBuff, passRI->primBuff );
  397. // Render this sucker.
  398. if ( passRI->prim )
  399. GFX->drawPrimitive( *passRI->prim );
  400. else
  401. GFX->drawPrimitive( passRI->primBuffIndex );
  402. }
  403. // Draw the instanced batch.
  404. if ( mat->isInstanced() )
  405. {
  406. // Sets the buffers including the instancing stream.
  407. mat->setBuffers( ri->vertBuff, ri->primBuff );
  408. if ( ri->prim )
  409. GFX->drawPrimitive( *ri->prim );
  410. else
  411. GFX->drawPrimitive( ri->primBuffIndex );
  412. }
  413. endOfBatchItr = meshItr;
  414. } // while( mat->setupPass(state, sgData) )
  415. // Force the increment if none happened, otherwise go to end of batch.
  416. itr = ( itr == endOfBatchItr ) ? itr + 1 : endOfBatchItr;
  417. }
  418. // The final loop is for object render instances.
  419. itr = mObjectElementList.begin();
  420. for ( ; itr != mObjectElementList.end(); itr++ )
  421. {
  422. ObjectRenderInst *ri = static_cast<ObjectRenderInst*>( itr->inst );
  423. if ( ri->renderDelegate )
  424. ri->renderDelegate( ri, state, mPrePassMatInstance );
  425. }
  426. // Signal end of pre-pass
  427. getRenderSignal().trigger( state, this, false );
  428. if(isRenderingToTarget)
  429. _onPostRender();
  430. }
  431. const GFXStateBlockDesc & RenderPrePassMgr::getOpaqueStenciWriteDesc( bool lightmappedGeometry /*= true*/ )
  432. {
  433. static bool sbInit = false;
  434. static GFXStateBlockDesc sOpaqueStaticLitStencilWriteDesc;
  435. static GFXStateBlockDesc sOpaqueDynamicLitStencilWriteDesc;
  436. if(!sbInit)
  437. {
  438. sbInit = true;
  439. // Build the static opaque stencil write/test state block descriptions
  440. sOpaqueStaticLitStencilWriteDesc.stencilDefined = true;
  441. sOpaqueStaticLitStencilWriteDesc.stencilEnable = true;
  442. sOpaqueStaticLitStencilWriteDesc.stencilWriteMask = 0x03;
  443. sOpaqueStaticLitStencilWriteDesc.stencilMask = 0x03;
  444. sOpaqueStaticLitStencilWriteDesc.stencilRef = RenderPrePassMgr::OpaqueStaticLitMask;
  445. sOpaqueStaticLitStencilWriteDesc.stencilPassOp = GFXStencilOpReplace;
  446. sOpaqueStaticLitStencilWriteDesc.stencilFailOp = GFXStencilOpKeep;
  447. sOpaqueStaticLitStencilWriteDesc.stencilZFailOp = GFXStencilOpKeep;
  448. sOpaqueStaticLitStencilWriteDesc.stencilFunc = GFXCmpAlways;
  449. // Same only dynamic
  450. sOpaqueDynamicLitStencilWriteDesc = sOpaqueStaticLitStencilWriteDesc;
  451. sOpaqueDynamicLitStencilWriteDesc.stencilRef = RenderPrePassMgr::OpaqueDynamicLitMask;
  452. }
  453. return (lightmappedGeometry ? sOpaqueStaticLitStencilWriteDesc : sOpaqueDynamicLitStencilWriteDesc);
  454. }
  455. const GFXStateBlockDesc & RenderPrePassMgr::getOpaqueStencilTestDesc()
  456. {
  457. static bool sbInit = false;
  458. static GFXStateBlockDesc sOpaqueStencilTestDesc;
  459. if(!sbInit)
  460. {
  461. // Build opaque test
  462. sbInit = true;
  463. sOpaqueStencilTestDesc.stencilDefined = true;
  464. sOpaqueStencilTestDesc.stencilEnable = true;
  465. sOpaqueStencilTestDesc.stencilWriteMask = 0xFE;
  466. sOpaqueStencilTestDesc.stencilMask = 0x03;
  467. sOpaqueStencilTestDesc.stencilRef = 0;
  468. sOpaqueStencilTestDesc.stencilPassOp = GFXStencilOpKeep;
  469. sOpaqueStencilTestDesc.stencilFailOp = GFXStencilOpKeep;
  470. sOpaqueStencilTestDesc.stencilZFailOp = GFXStencilOpKeep;
  471. sOpaqueStencilTestDesc.stencilFunc = GFXCmpLess;
  472. }
  473. return sOpaqueStencilTestDesc;
  474. }
  475. //------------------------------------------------------------------------------
  476. //------------------------------------------------------------------------------
  477. ProcessedPrePassMaterial::ProcessedPrePassMaterial( Material& mat, const RenderPrePassMgr *prePassMgr )
  478. : Parent(mat), mPrePassMgr(prePassMgr)
  479. {
  480. }
  481. void ProcessedPrePassMaterial::_determineFeatures( U32 stageNum,
  482. MaterialFeatureData &fd,
  483. const FeatureSet &features )
  484. {
  485. Parent::_determineFeatures( stageNum, fd, features );
  486. // Find this for use down below...
  487. bool bEnableMRTLightmap = false;
  488. AdvancedLightBinManager *lightBin;
  489. if ( Sim::findObject( "AL_LightBinMgr", lightBin ) )
  490. bEnableMRTLightmap = lightBin->MRTLightmapsDuringPrePass();
  491. // If this material has a lightmap or tonemap (texture or baked vertex color),
  492. // it must be static. Otherwise it is dynamic.
  493. mIsLightmappedGeometry = ( fd.features.hasFeature( MFT_ToneMap ) ||
  494. fd.features.hasFeature( MFT_LightMap ) ||
  495. fd.features.hasFeature( MFT_VertLit ) ||
  496. ( bEnableMRTLightmap && fd.features.hasFeature( MFT_IsTranslucent ) ||
  497. fd.features.hasFeature( MFT_ForwardShading ) ||
  498. fd.features.hasFeature( MFT_IsTranslucentZWrite ) ) );
  499. // Integrate proper opaque stencil write state
  500. mUserDefined.addDesc( mPrePassMgr->getOpaqueStenciWriteDesc( mIsLightmappedGeometry ) );
  501. FeatureSet newFeatures;
  502. // These are always on for prepass.
  503. newFeatures.addFeature( MFT_EyeSpaceDepthOut );
  504. newFeatures.addFeature( MFT_PrePassConditioner );
  505. #ifndef TORQUE_DEDICATED
  506. //tag all materials running through prepass as deferred
  507. newFeatures.addFeature(MFT_isDeferred);
  508. // Deferred Shading : Diffuse
  509. if (mStages[stageNum].getTex( MFT_DiffuseMap ))
  510. {
  511. newFeatures.addFeature(MFT_DiffuseMap);
  512. }
  513. newFeatures.addFeature( MFT_DiffuseColor );
  514. // Deferred Shading : Specular
  515. if( mStages[stageNum].getTex( MFT_SpecularMap ) )
  516. {
  517. newFeatures.addFeature( MFT_DeferredSpecMap );
  518. }
  519. else if ( mMaterial->mPixelSpecular[stageNum] )
  520. {
  521. newFeatures.addFeature( MFT_DeferredSpecVars );
  522. }
  523. else
  524. newFeatures.addFeature(MFT_DeferredEmptySpec);
  525. // Deferred Shading : Material Info Flags
  526. newFeatures.addFeature( MFT_DeferredMatInfoFlags );
  527. for ( U32 i=0; i < fd.features.getCount(); i++ )
  528. {
  529. const FeatureType &type = fd.features.getAt( i );
  530. // Turn on the diffuse texture only if we
  531. // have alpha test.
  532. if ( type == MFT_AlphaTest )
  533. {
  534. newFeatures.addFeature( MFT_AlphaTest );
  535. newFeatures.addFeature( MFT_DiffuseMap );
  536. }
  537. else if ( type == MFT_IsTranslucentZWrite )
  538. {
  539. newFeatures.addFeature( MFT_IsTranslucentZWrite );
  540. newFeatures.addFeature( MFT_DiffuseMap );
  541. }
  542. // Always allow these.
  543. else if ( type == MFT_IsDXTnm ||
  544. type == MFT_TexAnim ||
  545. type == MFT_NormalMap ||
  546. type == MFT_DetailNormalMap ||
  547. type == MFT_AlphaTest ||
  548. type == MFT_Parallax ||
  549. type == MFT_InterlacedPrePass ||
  550. type == MFT_Visibility ||
  551. type == MFT_UseInstancing ||
  552. type == MFT_DiffuseVertColor ||
  553. type == MFT_DetailMap ||
  554. type == MFT_DetailNormalMap ||
  555. type == MFT_DiffuseMapAtlas)
  556. newFeatures.addFeature( type );
  557. // Add any transform features.
  558. else if ( type.getGroup() == MFG_PreTransform ||
  559. type.getGroup() == MFG_Transform ||
  560. type.getGroup() == MFG_PostTransform )
  561. newFeatures.addFeature( type );
  562. }
  563. if (mMaterial->mAccuEnabled[stageNum])
  564. {
  565. newFeatures.addFeature(MFT_AccuMap);
  566. mHasAccumulation = true;
  567. }
  568. // we need both diffuse and normal maps + sm3 to have an accu map
  569. if (newFeatures[MFT_AccuMap] &&
  570. (!newFeatures[MFT_DiffuseMap] ||
  571. !newFeatures[MFT_NormalMap] ||
  572. GFX->getPixelShaderVersion() < 3.0f)) {
  573. AssertWarn(false, "SAHARA: Using an Accu Map requires SM 3.0 and a normal map.");
  574. newFeatures.removeFeature(MFT_AccuMap);
  575. mHasAccumulation = false;
  576. }
  577. // if we still have the AccuMap feature, we add all accu constant features
  578. if (newFeatures[MFT_AccuMap]) {
  579. // add the dependencies of the accu map
  580. newFeatures.addFeature(MFT_AccuScale);
  581. newFeatures.addFeature(MFT_AccuDirection);
  582. newFeatures.addFeature(MFT_AccuStrength);
  583. newFeatures.addFeature(MFT_AccuCoverage);
  584. newFeatures.addFeature(MFT_AccuSpecular);
  585. // now remove some features that are not compatible with this
  586. newFeatures.removeFeature(MFT_UseInstancing);
  587. }
  588. // If there is lightmapped geometry support, add the MRT light buffer features
  589. if(bEnableMRTLightmap)
  590. {
  591. // If this material has a lightmap, pass it through, and flag it to
  592. // send it's output to RenderTarget3
  593. if( fd.features.hasFeature( MFT_ToneMap ) )
  594. {
  595. newFeatures.addFeature( MFT_ToneMap );
  596. newFeatures.addFeature( MFT_LightbufferMRT );
  597. }
  598. else if( fd.features.hasFeature( MFT_LightMap ) )
  599. {
  600. newFeatures.addFeature( MFT_LightMap );
  601. newFeatures.addFeature( MFT_LightbufferMRT );
  602. }
  603. else if( fd.features.hasFeature( MFT_VertLit ) )
  604. {
  605. // Flag un-tone-map if necesasary
  606. if( fd.features.hasFeature( MFT_DiffuseMap ) )
  607. newFeatures.addFeature( MFT_VertLitTone );
  608. newFeatures.addFeature( MFT_VertLit );
  609. newFeatures.addFeature( MFT_LightbufferMRT );
  610. }
  611. else
  612. {
  613. // If this object isn't lightmapped, add a zero-output feature to it
  614. newFeatures.addFeature( MFT_RenderTarget3_Zero );
  615. }
  616. }
  617. // cubemaps only available on stage 0 for now - bramage
  618. if ( stageNum < 1 &&
  619. ( ( mMaterial->mCubemapData && mMaterial->mCubemapData->mCubemap ) ||
  620. mMaterial->mDynamicCubemap ) )
  621. newFeatures.addFeature( MFT_CubeMap );
  622. #endif
  623. // Set the new features.
  624. fd.features = newFeatures;
  625. }
  626. U32 ProcessedPrePassMaterial::getNumStages()
  627. {
  628. // Loops through all stages to determine how many
  629. // stages we actually use.
  630. //
  631. // The first stage is always active else we shouldn't be
  632. // creating the material to begin with.
  633. U32 numStages = 1;
  634. U32 i;
  635. for( i=1; i<Material::MAX_STAGES; i++ )
  636. {
  637. // Assume stage is inactive
  638. bool stageActive = false;
  639. // Cubemaps only on first stage
  640. if( i == 0 )
  641. {
  642. // If we have a cubemap the stage is active
  643. if( mMaterial->mCubemapData || mMaterial->mDynamicCubemap )
  644. {
  645. numStages++;
  646. continue;
  647. }
  648. }
  649. // If we have a texture for the a feature the
  650. // stage is active.
  651. if ( mStages[i].hasValidTex() )
  652. stageActive = true;
  653. // If this stage has specular lighting, it's active
  654. if ( mMaterial->mPixelSpecular[i] )
  655. stageActive = true;
  656. // If this stage has diffuse color, it's active
  657. if ( mMaterial->mDiffuse[i].alpha > 0 &&
  658. mMaterial->mDiffuse[i] != ColorF::WHITE )
  659. stageActive = true;
  660. // If we have a Material that is vertex lit
  661. // then it may not have a texture
  662. if( mMaterial->mVertLit[i] )
  663. stageActive = true;
  664. // Increment the number of active stages
  665. numStages += stageActive;
  666. }
  667. return numStages;
  668. }
  669. void ProcessedPrePassMaterial::addStateBlockDesc(const GFXStateBlockDesc& desc)
  670. {
  671. GFXStateBlockDesc prePassStateBlock = desc;
  672. // Adjust color writes if this is a pure z-fill pass
  673. const bool pixelOutEnabled = mPrePassMgr->getTargetChainLength() > 0;
  674. if ( !pixelOutEnabled )
  675. {
  676. prePassStateBlock.colorWriteDefined = true;
  677. prePassStateBlock.colorWriteRed = pixelOutEnabled;
  678. prePassStateBlock.colorWriteGreen = pixelOutEnabled;
  679. prePassStateBlock.colorWriteBlue = pixelOutEnabled;
  680. prePassStateBlock.colorWriteAlpha = pixelOutEnabled;
  681. }
  682. // Never allow the alpha test state when rendering
  683. // the prepass as we use the alpha channel for the
  684. // depth information... MFT_AlphaTest will handle it.
  685. prePassStateBlock.alphaDefined = true;
  686. prePassStateBlock.alphaTestEnable = false;
  687. // If we're translucent then we're doing prepass blending
  688. // which never writes to the depth channels.
  689. const bool isTranslucent = getMaterial()->isTranslucent();
  690. if ( isTranslucent )
  691. {
  692. prePassStateBlock.setBlend( true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha );
  693. prePassStateBlock.setColorWrites(false, false, false, true);
  694. }
  695. // Enable z reads, but only enable zwrites if we're not translucent.
  696. prePassStateBlock.setZReadWrite( true, isTranslucent ? false : true );
  697. // Pass to parent
  698. Parent::addStateBlockDesc(prePassStateBlock);
  699. }
  700. PrePassMatInstance::PrePassMatInstance(MatInstance* root, const RenderPrePassMgr *prePassMgr)
  701. : Parent(*root->getMaterial()), mPrePassMgr(prePassMgr)
  702. {
  703. mFeatureList = root->getRequestedFeatures();
  704. mVertexFormat = root->getVertexFormat();
  705. mUserObject = root->getUserObject();
  706. }
  707. PrePassMatInstance::~PrePassMatInstance()
  708. {
  709. }
  710. ProcessedMaterial* PrePassMatInstance::getShaderMaterial()
  711. {
  712. return new ProcessedPrePassMaterial(*mMaterial, mPrePassMgr);
  713. }
  714. bool PrePassMatInstance::init( const FeatureSet &features,
  715. const GFXVertexFormat *vertexFormat )
  716. {
  717. bool vaild = Parent::init(features, vertexFormat);
  718. if (mMaterial && mMaterial->mDiffuseMapFilename[0].isNotEmpty() && mMaterial->mDiffuseMapFilename[0].substr(0, 1).equal("#"))
  719. {
  720. String texTargetBufferName = mMaterial->mDiffuseMapFilename[0].substr(1, mMaterial->mDiffuseMapFilename[0].length() - 1);
  721. NamedTexTarget *texTarget = NamedTexTarget::find(texTargetBufferName);
  722. RenderPassData* rpd = getPass(0);
  723. if (rpd)
  724. {
  725. rpd->mTexSlot[0].texTarget = texTarget;
  726. rpd->mTexType[0] = Material::TexTarget;
  727. rpd->mSamplerNames[0] = "diffuseMap";
  728. }
  729. }
  730. return vaild;
  731. }
  732. PrePassMatInstanceHook::PrePassMatInstanceHook( MatInstance *baseMatInst,
  733. const RenderPrePassMgr *prePassMgr )
  734. : mHookedPrePassMatInst(NULL), mPrePassManager(prePassMgr)
  735. {
  736. // If the material is a custom material then
  737. // hope that using DefaultPrePassMaterial gives
  738. // them a good prepass.
  739. if ( baseMatInst->isCustomMaterial() )
  740. {
  741. MatInstance* dummyInst = static_cast<MatInstance*>( MATMGR->createMatInstance( "AL_DefaultPrePassMaterial", baseMatInst->getVertexFormat() ) );
  742. mHookedPrePassMatInst = new PrePassMatInstance( dummyInst, prePassMgr );
  743. mHookedPrePassMatInst->init( dummyInst->getRequestedFeatures(), baseMatInst->getVertexFormat());
  744. delete dummyInst;
  745. return;
  746. }
  747. // Create the prepass material instance.
  748. mHookedPrePassMatInst = new PrePassMatInstance(baseMatInst, prePassMgr);
  749. mHookedPrePassMatInst->getFeaturesDelegate() = baseMatInst->getFeaturesDelegate();
  750. // Get the features, but remove the instancing feature if the
  751. // original material didn't end up using it.
  752. FeatureSet features = baseMatInst->getRequestedFeatures();
  753. if ( !baseMatInst->isInstanced() )
  754. features.removeFeature( MFT_UseInstancing );
  755. // Initialize the material.
  756. mHookedPrePassMatInst->init(features, baseMatInst->getVertexFormat());
  757. }
  758. PrePassMatInstanceHook::~PrePassMatInstanceHook()
  759. {
  760. SAFE_DELETE(mHookedPrePassMatInst);
  761. }
  762. //------------------------------------------------------------------------------
  763. //------------------------------------------------------------------------------
  764. void LinearEyeDepthConditioner::processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd )
  765. {
  766. // find depth
  767. ShaderFeature *depthFeat = FEATUREMGR->getByType( MFT_EyeSpaceDepthOut );
  768. AssertFatal( depthFeat != NULL, "No eye space depth feature found!" );
  769. Var *depth = (Var*) LangElement::find(depthFeat->getOutputVarName());
  770. AssertFatal( depth, "Something went bad with ShaderGen. The depth should be already generated by the EyeSpaceDepthOut feature." );
  771. MultiLine *meta = new MultiLine;
  772. meta->addStatement( assignOutput( depth ) );
  773. output = meta;
  774. }
  775. Var *LinearEyeDepthConditioner::_conditionOutput( Var *unconditionedOutput, MultiLine *meta )
  776. {
  777. Var *retVar = NULL;
  778. String fracMethodName = (GFX->getAdapterType() == OpenGL) ? "fract" : "frac";
  779. switch(getBufferFormat())
  780. {
  781. case GFXFormatR8G8B8A8:
  782. retVar = new Var;
  783. retVar->setType("float4");
  784. retVar->setName("_ppDepth");
  785. meta->addStatement( new GenOp( " // depth conditioner: packing to rgba\r\n" ) );
  786. meta->addStatement( new GenOp(
  787. avar( " @ = %s(@ * (255.0/256) * float4(1, 255, 255 * 255, 255 * 255 * 255));\r\n", fracMethodName.c_str() ),
  788. new DecOp(retVar), unconditionedOutput ) );
  789. break;
  790. default:
  791. retVar = unconditionedOutput;
  792. meta->addStatement( new GenOp( " // depth conditioner: no conditioning\r\n" ) );
  793. break;
  794. }
  795. AssertFatal( retVar != NULL, avar( "Cannot condition output to buffer format: %s", GFXStringTextureFormat[getBufferFormat()] ) );
  796. return retVar;
  797. }
  798. Var *LinearEyeDepthConditioner::_unconditionInput( Var *conditionedInput, MultiLine *meta )
  799. {
  800. String float4Typename = (GFX->getAdapterType() == OpenGL) ? "vec4" : "float4";
  801. Var *retVar = conditionedInput;
  802. if(getBufferFormat() != GFXFormat_COUNT)
  803. {
  804. retVar = new Var;
  805. retVar->setType(float4Typename.c_str());
  806. retVar->setName("_ppDepth");
  807. meta->addStatement( new GenOp( avar( " @ = %s(0, 0, 1, 1);\r\n", float4Typename.c_str() ), new DecOp(retVar) ) );
  808. switch(getBufferFormat())
  809. {
  810. case GFXFormatR32F:
  811. case GFXFormatR16F:
  812. meta->addStatement( new GenOp( " // depth conditioner: float texture\r\n" ) );
  813. meta->addStatement( new GenOp( " @.w = @.r;\r\n", retVar, conditionedInput ) );
  814. break;
  815. case GFXFormatR8G8B8A8:
  816. meta->addStatement( new GenOp( " // depth conditioner: unpacking from rgba\r\n" ) );
  817. meta->addStatement( new GenOp(
  818. avar( " @.w = dot(@ * (256.0/255), %s(1, 1 / 255, 1 / (255 * 255), 1 / (255 * 255 * 255)));\r\n", float4Typename.c_str() )
  819. , retVar, conditionedInput ) );
  820. break;
  821. default:
  822. AssertFatal(false, "LinearEyeDepthConditioner::_unconditionInput - Unrecognized buffer format");
  823. }
  824. }
  825. return retVar;
  826. }
  827. Var* LinearEyeDepthConditioner::printMethodHeader( MethodType methodType, const String &methodName, Stream &stream, MultiLine *meta )
  828. {
  829. const bool isCondition = ( methodType == ConditionerFeature::ConditionMethod );
  830. Var *retVal = NULL;
  831. // The uncondition method inputs are changed
  832. if( isCondition )
  833. retVal = Parent::printMethodHeader( methodType, methodName, stream, meta );
  834. else
  835. {
  836. Var *methodVar = new Var;
  837. methodVar->setName(methodName);
  838. if (GFX->getAdapterType() == OpenGL)
  839. methodVar->setType("vec4");
  840. else
  841. methodVar->setType("inline float4");
  842. DecOp *methodDecl = new DecOp(methodVar);
  843. Var *prepassSampler = new Var;
  844. prepassSampler->setName("prepassSamplerVar");
  845. prepassSampler->setType("sampler2D");
  846. DecOp *prepassSamplerDecl = new DecOp(prepassSampler);
  847. Var *screenUV = new Var;
  848. screenUV->setName("screenUVVar");
  849. if (GFX->getAdapterType() == OpenGL)
  850. screenUV->setType("vec2");
  851. else
  852. screenUV->setType("float2");
  853. DecOp *screenUVDecl = new DecOp(screenUV);
  854. Var *bufferSample = new Var;
  855. bufferSample->setName("bufferSample");
  856. if (GFX->getAdapterType() == OpenGL)
  857. bufferSample->setType("vec4");
  858. else
  859. bufferSample->setType("float4");
  860. DecOp *bufferSampleDecl = new DecOp(bufferSample);
  861. meta->addStatement( new GenOp( "@(@, @)\r\n", methodDecl, prepassSamplerDecl, screenUVDecl ) );
  862. meta->addStatement( new GenOp( "{\r\n" ) );
  863. meta->addStatement( new GenOp( " // Sampler g-buffer\r\n" ) );
  864. // The linear depth target has no mipmaps, so use tex2dlod when
  865. // possible so that the shader compiler can optimize.
  866. meta->addStatement( new GenOp( " #if TORQUE_SM >= 30\r\n" ) );
  867. if (GFX->getAdapterType() == OpenGL)
  868. meta->addStatement( new GenOp( " @ = textureLod(@, @, 0); \r\n", bufferSampleDecl, prepassSampler, screenUV) );
  869. else
  870. meta->addStatement( new GenOp( " @ = tex2Dlod(@, float4(@,0,0));\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
  871. meta->addStatement( new GenOp( " #else\r\n" ) );
  872. if (GFX->getAdapterType() == OpenGL)
  873. meta->addStatement( new GenOp( " @ = texture(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV) );
  874. else
  875. meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
  876. meta->addStatement( new GenOp( " #endif\r\n\r\n" ) );
  877. // We don't use this way of passing var's around, so this should cause a crash
  878. // if something uses this improperly
  879. retVal = bufferSample;
  880. }
  881. return retVal;
  882. }
  883. void RenderPrePassMgr::_initShaders()
  884. {
  885. if ( mClearGBufferShader ) return;
  886. // Find ShaderData
  887. ShaderData *shaderData;
  888. mClearGBufferShader = Sim::findObject( "ClearGBufferShader", shaderData ) ? shaderData->getShader() : NULL;
  889. if ( !mClearGBufferShader )
  890. Con::errorf( "RenderPrePassMgr::_initShaders - could not find ClearGBufferShader" );
  891. // Create StateBlocks
  892. GFXStateBlockDesc desc;
  893. desc.setCullMode( GFXCullNone );
  894. desc.setBlend( true );
  895. desc.setZReadWrite( false, false );
  896. desc.samplersDefined = true;
  897. desc.samplers[0].addressModeU = GFXAddressWrap;
  898. desc.samplers[0].addressModeV = GFXAddressWrap;
  899. desc.samplers[0].addressModeW = GFXAddressWrap;
  900. desc.samplers[0].magFilter = GFXTextureFilterLinear;
  901. desc.samplers[0].minFilter = GFXTextureFilterLinear;
  902. desc.samplers[0].mipFilter = GFXTextureFilterLinear;
  903. desc.samplers[0].textureColorOp = GFXTOPModulate;
  904. mStateblock = GFX->createStateBlock( desc );
  905. // Set up shader constants.
  906. mShaderConsts = mClearGBufferShader->allocConstBuffer();
  907. mSpecularStrengthSC = mClearGBufferShader->getShaderConstHandle( "$specularStrength" );
  908. mSpecularPowerSC = mClearGBufferShader->getShaderConstHandle( "$specularPower" );
  909. }
  910. void RenderPrePassMgr::clearBuffers()
  911. {
  912. // Clear z-buffer.
  913. GFX->clear( GFXClearTarget | GFXClearZBuffer | GFXClearStencil, ColorI::ZERO, 1.0f, 0);
  914. if ( !mClearGBufferShader )
  915. return;
  916. GFXTransformSaver saver;
  917. // Clear the g-buffer.
  918. RectI box(-1, -1, 3, 3);
  919. GFX->setWorldMatrix( MatrixF::Identity );
  920. GFX->setViewMatrix( MatrixF::Identity );
  921. GFX->setProjectionMatrix( MatrixF::Identity );
  922. GFX->setShader(mClearGBufferShader);
  923. GFX->setStateBlock(mStateblock);
  924. Point2F nw(-0.5,-0.5);
  925. Point2F ne(0.5,-0.5);
  926. GFXVertexBufferHandle<GFXVertexPC> verts(GFX, 4, GFXBufferTypeVolatile);
  927. verts.lock();
  928. F32 ulOffset = 0.5f - GFX->getFillConventionOffset();
  929. Point2F upperLeft(-1.0, -1.0);
  930. Point2F lowerRight(1.0, 1.0);
  931. verts[0].point.set( upperLeft.x+nw.x+ulOffset, upperLeft.y+nw.y+ulOffset, 0.0f );
  932. verts[1].point.set( lowerRight.x+ne.x, upperLeft.y+ne.y+ulOffset, 0.0f );
  933. verts[2].point.set( upperLeft.x-ne.x+ulOffset, lowerRight.y-ne.y, 0.0f );
  934. verts[3].point.set( lowerRight.x-nw.x, lowerRight.y-nw.y, 0.0f );
  935. verts.unlock();
  936. GFX->setVertexBuffer( verts );
  937. GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
  938. GFX->setShader(NULL);
  939. }