renderDeferredMgr.cpp 41 KB

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