renderDeferredMgr.cpp 40 KB

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