renderPrePassMgr.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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 *lastAccuTex = NULL;
  319. // Next render all the meshes.
  320. itr = mElementList.begin();
  321. for ( ; itr != mElementList.end(); )
  322. {
  323. MeshRenderInst *ri = static_cast<MeshRenderInst*>( itr->inst );
  324. // Get the prepass material.
  325. BaseMatInstance *mat = getPrePassMaterial( ri->matInst );
  326. // Set up SG data proper like and flag it
  327. // as a pre-pass render
  328. setupSGData( ri, sgData );
  329. Vector< MainSortElem >::const_iterator meshItr, endOfBatchItr = itr;
  330. while ( mat->setupPass( state, sgData ) )
  331. {
  332. meshItr = itr;
  333. for ( ; meshItr != mElementList.end(); meshItr++ )
  334. {
  335. MeshRenderInst *passRI = static_cast<MeshRenderInst*>( meshItr->inst );
  336. // Check to see if we need to break this batch.
  337. //
  338. // NOTE: We're comparing the non-prepass materials
  339. // here so we don't incur the cost of looking up the
  340. // prepass hook on each inst.
  341. //
  342. if ( newPassNeeded( ri, passRI ) )
  343. break;
  344. // Set up SG data for this instance.
  345. setupSGData( passRI, sgData );
  346. mat->setSceneInfo(state, sgData);
  347. matrixSet.setWorld(*passRI->objectToWorld);
  348. matrixSet.setView(*passRI->worldToCamera);
  349. matrixSet.setProjection(*passRI->projection);
  350. mat->setTransforms(matrixSet, state);
  351. // If we're instanced then don't render yet.
  352. if ( mat->isInstanced() )
  353. {
  354. // Let the material increment the instance buffer, but
  355. // break the batch if it runs out of room for more.
  356. if ( !mat->stepInstance() )
  357. {
  358. meshItr++;
  359. break;
  360. }
  361. continue;
  362. }
  363. bool dirty = false;
  364. // set the lightmaps if different
  365. if( passRI->lightmap && passRI->lightmap != lastLM )
  366. {
  367. sgData.lightmap = passRI->lightmap;
  368. lastLM = passRI->lightmap;
  369. dirty = true;
  370. }
  371. // set the cubemap if different.
  372. if ( passRI->cubemap != lastCubemap )
  373. {
  374. sgData.cubemap = passRI->cubemap;
  375. lastCubemap = passRI->cubemap;
  376. dirty = true;
  377. }
  378. if ( passRI->reflectTex != lastReflectTex )
  379. {
  380. sgData.reflectTex = passRI->reflectTex;
  381. lastReflectTex = passRI->reflectTex;
  382. dirty = true;
  383. }
  384. // Update accumulation texture if it changed.
  385. // Note: accumulation texture can be NULL, and must be updated.
  386. if (passRI->accuTex != lastAccuTex)
  387. {
  388. sgData.accuTex = passRI->accuTex;
  389. lastAccuTex = lastAccuTex;
  390. dirty = true;
  391. }
  392. if ( dirty )
  393. mat->setTextureStages( state, sgData );
  394. // Setup the vertex and index buffers.
  395. mat->setBuffers( passRI->vertBuff, passRI->primBuff );
  396. // Render this sucker.
  397. if ( passRI->prim )
  398. GFX->drawPrimitive( *passRI->prim );
  399. else
  400. GFX->drawPrimitive( passRI->primBuffIndex );
  401. }
  402. // Draw the instanced batch.
  403. if ( mat->isInstanced() )
  404. {
  405. // Sets the buffers including the instancing stream.
  406. mat->setBuffers( ri->vertBuff, ri->primBuff );
  407. if ( ri->prim )
  408. GFX->drawPrimitive( *ri->prim );
  409. else
  410. GFX->drawPrimitive( ri->primBuffIndex );
  411. }
  412. endOfBatchItr = meshItr;
  413. } // while( mat->setupPass(state, sgData) )
  414. // Force the increment if none happened, otherwise go to end of batch.
  415. itr = ( itr == endOfBatchItr ) ? itr + 1 : endOfBatchItr;
  416. }
  417. // The final loop is for object render instances.
  418. itr = mObjectElementList.begin();
  419. for ( ; itr != mObjectElementList.end(); itr++ )
  420. {
  421. ObjectRenderInst *ri = static_cast<ObjectRenderInst*>( itr->inst );
  422. if ( ri->renderDelegate )
  423. ri->renderDelegate( ri, state, mPrePassMatInstance );
  424. }
  425. // Signal end of pre-pass
  426. getRenderSignal().trigger( state, this, false );
  427. if(isRenderingToTarget)
  428. _onPostRender();
  429. }
  430. const GFXStateBlockDesc & RenderPrePassMgr::getOpaqueStenciWriteDesc( bool lightmappedGeometry /*= true*/ )
  431. {
  432. static bool sbInit = false;
  433. static GFXStateBlockDesc sOpaqueStaticLitStencilWriteDesc;
  434. static GFXStateBlockDesc sOpaqueDynamicLitStencilWriteDesc;
  435. if(!sbInit)
  436. {
  437. sbInit = true;
  438. // Build the static opaque stencil write/test state block descriptions
  439. sOpaqueStaticLitStencilWriteDesc.stencilDefined = true;
  440. sOpaqueStaticLitStencilWriteDesc.stencilEnable = true;
  441. sOpaqueStaticLitStencilWriteDesc.stencilWriteMask = 0x03;
  442. sOpaqueStaticLitStencilWriteDesc.stencilMask = 0x03;
  443. sOpaqueStaticLitStencilWriteDesc.stencilRef = RenderPrePassMgr::OpaqueStaticLitMask;
  444. sOpaqueStaticLitStencilWriteDesc.stencilPassOp = GFXStencilOpReplace;
  445. sOpaqueStaticLitStencilWriteDesc.stencilFailOp = GFXStencilOpKeep;
  446. sOpaqueStaticLitStencilWriteDesc.stencilZFailOp = GFXStencilOpKeep;
  447. sOpaqueStaticLitStencilWriteDesc.stencilFunc = GFXCmpAlways;
  448. // Same only dynamic
  449. sOpaqueDynamicLitStencilWriteDesc = sOpaqueStaticLitStencilWriteDesc;
  450. sOpaqueDynamicLitStencilWriteDesc.stencilRef = RenderPrePassMgr::OpaqueDynamicLitMask;
  451. }
  452. return (lightmappedGeometry ? sOpaqueStaticLitStencilWriteDesc : sOpaqueDynamicLitStencilWriteDesc);
  453. }
  454. const GFXStateBlockDesc & RenderPrePassMgr::getOpaqueStencilTestDesc()
  455. {
  456. static bool sbInit = false;
  457. static GFXStateBlockDesc sOpaqueStencilTestDesc;
  458. if(!sbInit)
  459. {
  460. // Build opaque test
  461. sbInit = true;
  462. sOpaqueStencilTestDesc.stencilDefined = true;
  463. sOpaqueStencilTestDesc.stencilEnable = true;
  464. sOpaqueStencilTestDesc.stencilWriteMask = 0xFE;
  465. sOpaqueStencilTestDesc.stencilMask = 0x03;
  466. sOpaqueStencilTestDesc.stencilRef = 0;
  467. sOpaqueStencilTestDesc.stencilPassOp = GFXStencilOpKeep;
  468. sOpaqueStencilTestDesc.stencilFailOp = GFXStencilOpKeep;
  469. sOpaqueStencilTestDesc.stencilZFailOp = GFXStencilOpKeep;
  470. sOpaqueStencilTestDesc.stencilFunc = GFXCmpLess;
  471. }
  472. return sOpaqueStencilTestDesc;
  473. }
  474. //------------------------------------------------------------------------------
  475. //------------------------------------------------------------------------------
  476. ProcessedPrePassMaterial::ProcessedPrePassMaterial( Material& mat, const RenderPrePassMgr *prePassMgr )
  477. : Parent(mat), mPrePassMgr(prePassMgr)
  478. {
  479. }
  480. void ProcessedPrePassMaterial::_determineFeatures( U32 stageNum,
  481. MaterialFeatureData &fd,
  482. const FeatureSet &features )
  483. {
  484. Parent::_determineFeatures( stageNum, fd, features );
  485. // Find this for use down below...
  486. bool bEnableMRTLightmap = false;
  487. AdvancedLightBinManager *lightBin;
  488. if ( Sim::findObject( "AL_LightBinMgr", lightBin ) )
  489. bEnableMRTLightmap = lightBin->MRTLightmapsDuringPrePass();
  490. // If this material has a lightmap or tonemap (texture or baked vertex color),
  491. // it must be static. Otherwise it is dynamic.
  492. mIsLightmappedGeometry = ( fd.features.hasFeature( MFT_ToneMap ) ||
  493. fd.features.hasFeature( MFT_LightMap ) ||
  494. fd.features.hasFeature( MFT_VertLit ) ||
  495. ( bEnableMRTLightmap && fd.features.hasFeature( MFT_IsTranslucent ) ||
  496. fd.features.hasFeature( MFT_ForwardShading ) ||
  497. fd.features.hasFeature( MFT_IsTranslucentZWrite ) ) );
  498. // Integrate proper opaque stencil write state
  499. mUserDefined.addDesc( mPrePassMgr->getOpaqueStenciWriteDesc( mIsLightmappedGeometry ) );
  500. FeatureSet newFeatures;
  501. // These are always on for prepass.
  502. newFeatures.addFeature( MFT_EyeSpaceDepthOut );
  503. newFeatures.addFeature( MFT_PrePassConditioner );
  504. #ifndef TORQUE_DEDICATED
  505. //tag all materials running through prepass as deferred
  506. newFeatures.addFeature(MFT_isDeferred);
  507. // Deferred Shading : Diffuse
  508. if (mStages[stageNum].getTex( MFT_DiffuseMap ))
  509. {
  510. newFeatures.addFeature(MFT_DiffuseMap);
  511. }
  512. newFeatures.addFeature( MFT_DiffuseColor );
  513. // Deferred Shading : Specular
  514. if( mStages[stageNum].getTex( MFT_SpecularMap ) )
  515. {
  516. newFeatures.addFeature( MFT_DeferredSpecMap );
  517. }
  518. else if ( mMaterial->mPixelSpecular[stageNum] )
  519. {
  520. newFeatures.addFeature( MFT_DeferredSpecVars );
  521. }
  522. else
  523. newFeatures.addFeature(MFT_DeferredEmptySpec);
  524. // Deferred Shading : Material Info Flags
  525. newFeatures.addFeature( MFT_DeferredMatInfoFlags );
  526. for ( U32 i=0; i < fd.features.getCount(); i++ )
  527. {
  528. const FeatureType &type = fd.features.getAt( i );
  529. // Turn on the diffuse texture only if we
  530. // have alpha test.
  531. if ( type == MFT_AlphaTest )
  532. {
  533. newFeatures.addFeature( MFT_AlphaTest );
  534. newFeatures.addFeature( MFT_DiffuseMap );
  535. }
  536. else if ( type == MFT_IsTranslucentZWrite )
  537. {
  538. newFeatures.addFeature( MFT_IsTranslucentZWrite );
  539. newFeatures.addFeature( MFT_DiffuseMap );
  540. }
  541. // Always allow these.
  542. else if ( type == MFT_IsDXTnm ||
  543. type == MFT_TexAnim ||
  544. type == MFT_NormalMap ||
  545. type == MFT_DetailNormalMap ||
  546. type == MFT_AlphaTest ||
  547. type == MFT_Parallax ||
  548. type == MFT_InterlacedPrePass ||
  549. type == MFT_Visibility ||
  550. type == MFT_UseInstancing ||
  551. type == MFT_DiffuseVertColor ||
  552. type == MFT_DetailMap ||
  553. type == MFT_DetailNormalMap ||
  554. type == MFT_DiffuseMapAtlas)
  555. newFeatures.addFeature( type );
  556. // Add any transform features.
  557. else if ( type.getGroup() == MFG_PreTransform ||
  558. type.getGroup() == MFG_Transform ||
  559. type.getGroup() == MFG_PostTransform )
  560. newFeatures.addFeature( type );
  561. }
  562. if (mMaterial->mAccuEnabled[stageNum])
  563. {
  564. newFeatures.addFeature(MFT_AccuMap);
  565. mHasAccumulation = true;
  566. }
  567. // we need both diffuse and normal maps + sm3 to have an accu map
  568. if (newFeatures[MFT_AccuMap] &&
  569. (!newFeatures[MFT_DiffuseMap] ||
  570. !newFeatures[MFT_NormalMap] ||
  571. GFX->getPixelShaderVersion() < 3.0f)) {
  572. AssertWarn(false, "SAHARA: Using an Accu Map requires SM 3.0 and a normal map.");
  573. newFeatures.removeFeature(MFT_AccuMap);
  574. mHasAccumulation = false;
  575. }
  576. // if we still have the AccuMap feature, we add all accu constant features
  577. if (newFeatures[MFT_AccuMap]) {
  578. // add the dependencies of the accu map
  579. newFeatures.addFeature(MFT_AccuScale);
  580. newFeatures.addFeature(MFT_AccuDirection);
  581. newFeatures.addFeature(MFT_AccuStrength);
  582. newFeatures.addFeature(MFT_AccuCoverage);
  583. newFeatures.addFeature(MFT_AccuSpecular);
  584. // now remove some features that are not compatible with this
  585. newFeatures.removeFeature(MFT_UseInstancing);
  586. }
  587. // If there is lightmapped geometry support, add the MRT light buffer features
  588. if(bEnableMRTLightmap)
  589. {
  590. // If this material has a lightmap, pass it through, and flag it to
  591. // send it's output to RenderTarget3
  592. if( fd.features.hasFeature( MFT_ToneMap ) )
  593. {
  594. newFeatures.addFeature( MFT_ToneMap );
  595. newFeatures.addFeature( MFT_LightbufferMRT );
  596. }
  597. else if( fd.features.hasFeature( MFT_LightMap ) )
  598. {
  599. newFeatures.addFeature( MFT_LightMap );
  600. newFeatures.addFeature( MFT_LightbufferMRT );
  601. }
  602. else if( fd.features.hasFeature( MFT_VertLit ) )
  603. {
  604. // Flag un-tone-map if necesasary
  605. if( fd.features.hasFeature( MFT_DiffuseMap ) )
  606. newFeatures.addFeature( MFT_VertLitTone );
  607. newFeatures.addFeature( MFT_VertLit );
  608. newFeatures.addFeature( MFT_LightbufferMRT );
  609. }
  610. else
  611. {
  612. // If this object isn't lightmapped, add a zero-output feature to it
  613. newFeatures.addFeature( MFT_RenderTarget3_Zero );
  614. }
  615. }
  616. // cubemaps only available on stage 0 for now - bramage
  617. if ( stageNum < 1 &&
  618. ( ( mMaterial->mCubemapData && mMaterial->mCubemapData->mCubemap ) ||
  619. mMaterial->mDynamicCubemap ) )
  620. newFeatures.addFeature( MFT_CubeMap );
  621. #endif
  622. // Set the new features.
  623. fd.features = newFeatures;
  624. }
  625. U32 ProcessedPrePassMaterial::getNumStages()
  626. {
  627. // Loops through all stages to determine how many
  628. // stages we actually use.
  629. //
  630. // The first stage is always active else we shouldn't be
  631. // creating the material to begin with.
  632. U32 numStages = 1;
  633. U32 i;
  634. for( i=1; i<Material::MAX_STAGES; i++ )
  635. {
  636. // Assume stage is inactive
  637. bool stageActive = false;
  638. // Cubemaps only on first stage
  639. if( i == 0 )
  640. {
  641. // If we have a cubemap the stage is active
  642. if( mMaterial->mCubemapData || mMaterial->mDynamicCubemap )
  643. {
  644. numStages++;
  645. continue;
  646. }
  647. }
  648. // If we have a texture for the a feature the
  649. // stage is active.
  650. if ( mStages[i].hasValidTex() )
  651. stageActive = true;
  652. // If this stage has specular lighting, it's active
  653. if ( mMaterial->mPixelSpecular[i] )
  654. stageActive = true;
  655. // If this stage has diffuse color, it's active
  656. if ( mMaterial->mDiffuse[i].alpha > 0 &&
  657. mMaterial->mDiffuse[i] != ColorF::WHITE )
  658. stageActive = true;
  659. // If we have a Material that is vertex lit
  660. // then it may not have a texture
  661. if( mMaterial->mVertLit[i] )
  662. stageActive = true;
  663. // Increment the number of active stages
  664. numStages += stageActive;
  665. }
  666. return numStages;
  667. }
  668. void ProcessedPrePassMaterial::addStateBlockDesc(const GFXStateBlockDesc& desc)
  669. {
  670. GFXStateBlockDesc prePassStateBlock = desc;
  671. // Adjust color writes if this is a pure z-fill pass
  672. const bool pixelOutEnabled = mPrePassMgr->getTargetChainLength() > 0;
  673. if ( !pixelOutEnabled )
  674. {
  675. prePassStateBlock.colorWriteDefined = true;
  676. prePassStateBlock.colorWriteRed = pixelOutEnabled;
  677. prePassStateBlock.colorWriteGreen = pixelOutEnabled;
  678. prePassStateBlock.colorWriteBlue = pixelOutEnabled;
  679. prePassStateBlock.colorWriteAlpha = pixelOutEnabled;
  680. }
  681. // Never allow the alpha test state when rendering
  682. // the prepass as we use the alpha channel for the
  683. // depth information... MFT_AlphaTest will handle it.
  684. prePassStateBlock.alphaDefined = true;
  685. prePassStateBlock.alphaTestEnable = false;
  686. // If we're translucent then we're doing prepass blending
  687. // which never writes to the depth channels.
  688. const bool isTranslucent = getMaterial()->isTranslucent();
  689. if ( isTranslucent )
  690. {
  691. prePassStateBlock.setBlend( true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha );
  692. prePassStateBlock.setColorWrites(false, false, false, true);
  693. }
  694. // Enable z reads, but only enable zwrites if we're not translucent.
  695. prePassStateBlock.setZReadWrite( true, isTranslucent ? false : true );
  696. // Pass to parent
  697. Parent::addStateBlockDesc(prePassStateBlock);
  698. }
  699. PrePassMatInstance::PrePassMatInstance(MatInstance* root, const RenderPrePassMgr *prePassMgr)
  700. : Parent(*root->getMaterial()), mPrePassMgr(prePassMgr)
  701. {
  702. mFeatureList = root->getRequestedFeatures();
  703. mVertexFormat = root->getVertexFormat();
  704. mUserObject = root->getUserObject();
  705. }
  706. PrePassMatInstance::~PrePassMatInstance()
  707. {
  708. }
  709. ProcessedMaterial* PrePassMatInstance::getShaderMaterial()
  710. {
  711. return new ProcessedPrePassMaterial(*mMaterial, mPrePassMgr);
  712. }
  713. bool PrePassMatInstance::init( const FeatureSet &features,
  714. const GFXVertexFormat *vertexFormat )
  715. {
  716. bool vaild = Parent::init(features, vertexFormat);
  717. if (mMaterial && mMaterial->mDiffuseMapFilename[0].isNotEmpty() && mMaterial->mDiffuseMapFilename[0].substr(0, 1).equal("#"))
  718. {
  719. String texTargetBufferName = mMaterial->mDiffuseMapFilename[0].substr(1, mMaterial->mDiffuseMapFilename[0].length() - 1);
  720. NamedTexTarget *texTarget = NamedTexTarget::find(texTargetBufferName);
  721. RenderPassData* rpd = getPass(0);
  722. if (rpd)
  723. {
  724. rpd->mTexSlot[0].texTarget = texTarget;
  725. rpd->mTexType[0] = Material::TexTarget;
  726. rpd->mSamplerNames[0] = "diffuseMap";
  727. }
  728. }
  729. return vaild;
  730. }
  731. PrePassMatInstanceHook::PrePassMatInstanceHook( MatInstance *baseMatInst,
  732. const RenderPrePassMgr *prePassMgr )
  733. : mHookedPrePassMatInst(NULL), mPrePassManager(prePassMgr)
  734. {
  735. // If the material is a custom material then
  736. // hope that using DefaultPrePassMaterial gives
  737. // them a good prepass.
  738. if ( baseMatInst->isCustomMaterial() )
  739. {
  740. MatInstance* dummyInst = static_cast<MatInstance*>( MATMGR->createMatInstance( "AL_DefaultPrePassMaterial", baseMatInst->getVertexFormat() ) );
  741. mHookedPrePassMatInst = new PrePassMatInstance( dummyInst, prePassMgr );
  742. mHookedPrePassMatInst->init( dummyInst->getRequestedFeatures(), baseMatInst->getVertexFormat());
  743. delete dummyInst;
  744. return;
  745. }
  746. // Create the prepass material instance.
  747. mHookedPrePassMatInst = new PrePassMatInstance(baseMatInst, prePassMgr);
  748. mHookedPrePassMatInst->getFeaturesDelegate() = baseMatInst->getFeaturesDelegate();
  749. // Get the features, but remove the instancing feature if the
  750. // original material didn't end up using it.
  751. FeatureSet features = baseMatInst->getRequestedFeatures();
  752. if ( !baseMatInst->isInstanced() )
  753. features.removeFeature( MFT_UseInstancing );
  754. // Initialize the material.
  755. mHookedPrePassMatInst->init(features, baseMatInst->getVertexFormat());
  756. }
  757. PrePassMatInstanceHook::~PrePassMatInstanceHook()
  758. {
  759. SAFE_DELETE(mHookedPrePassMatInst);
  760. }
  761. //------------------------------------------------------------------------------
  762. //------------------------------------------------------------------------------
  763. void LinearEyeDepthConditioner::processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd )
  764. {
  765. // find depth
  766. ShaderFeature *depthFeat = FEATUREMGR->getByType( MFT_EyeSpaceDepthOut );
  767. AssertFatal( depthFeat != NULL, "No eye space depth feature found!" );
  768. Var *depth = (Var*) LangElement::find(depthFeat->getOutputVarName());
  769. AssertFatal( depth, "Something went bad with ShaderGen. The depth should be already generated by the EyeSpaceDepthOut feature." );
  770. MultiLine *meta = new MultiLine;
  771. meta->addStatement( assignOutput( depth ) );
  772. output = meta;
  773. }
  774. Var *LinearEyeDepthConditioner::_conditionOutput( Var *unconditionedOutput, MultiLine *meta )
  775. {
  776. Var *retVar = NULL;
  777. String fracMethodName = (GFX->getAdapterType() == OpenGL) ? "fract" : "frac";
  778. switch(getBufferFormat())
  779. {
  780. case GFXFormatR8G8B8A8:
  781. retVar = new Var;
  782. retVar->setType("float4");
  783. retVar->setName("_ppDepth");
  784. meta->addStatement( new GenOp( " // depth conditioner: packing to rgba\r\n" ) );
  785. meta->addStatement( new GenOp(
  786. avar( " @ = %s(@ * (255.0/256) * float4(1, 255, 255 * 255, 255 * 255 * 255));\r\n", fracMethodName.c_str() ),
  787. new DecOp(retVar), unconditionedOutput ) );
  788. break;
  789. default:
  790. retVar = unconditionedOutput;
  791. meta->addStatement( new GenOp( " // depth conditioner: no conditioning\r\n" ) );
  792. break;
  793. }
  794. AssertFatal( retVar != NULL, avar( "Cannot condition output to buffer format: %s", GFXStringTextureFormat[getBufferFormat()] ) );
  795. return retVar;
  796. }
  797. Var *LinearEyeDepthConditioner::_unconditionInput( Var *conditionedInput, MultiLine *meta )
  798. {
  799. String float4Typename = (GFX->getAdapterType() == OpenGL) ? "vec4" : "float4";
  800. Var *retVar = conditionedInput;
  801. if(getBufferFormat() != GFXFormat_COUNT)
  802. {
  803. retVar = new Var;
  804. retVar->setType(float4Typename.c_str());
  805. retVar->setName("_ppDepth");
  806. meta->addStatement( new GenOp( avar( " @ = %s(0, 0, 1, 1);\r\n", float4Typename.c_str() ), new DecOp(retVar) ) );
  807. switch(getBufferFormat())
  808. {
  809. case GFXFormatR32F:
  810. case GFXFormatR16F:
  811. meta->addStatement( new GenOp( " // depth conditioner: float texture\r\n" ) );
  812. meta->addStatement( new GenOp( " @.w = @.r;\r\n", retVar, conditionedInput ) );
  813. break;
  814. case GFXFormatR8G8B8A8:
  815. meta->addStatement( new GenOp( " // depth conditioner: unpacking from rgba\r\n" ) );
  816. meta->addStatement( new GenOp(
  817. avar( " @.w = dot(@ * (256.0/255), %s(1, 1 / 255, 1 / (255 * 255), 1 / (255 * 255 * 255)));\r\n", float4Typename.c_str() )
  818. , retVar, conditionedInput ) );
  819. break;
  820. default:
  821. AssertFatal(false, "LinearEyeDepthConditioner::_unconditionInput - Unrecognized buffer format");
  822. }
  823. }
  824. return retVar;
  825. }
  826. Var* LinearEyeDepthConditioner::printMethodHeader( MethodType methodType, const String &methodName, Stream &stream, MultiLine *meta )
  827. {
  828. const bool isCondition = ( methodType == ConditionerFeature::ConditionMethod );
  829. Var *retVal = NULL;
  830. // The uncondition method inputs are changed
  831. if( isCondition )
  832. retVal = Parent::printMethodHeader( methodType, methodName, stream, meta );
  833. else
  834. {
  835. Var *methodVar = new Var;
  836. methodVar->setName(methodName);
  837. if (GFX->getAdapterType() == OpenGL)
  838. methodVar->setType("vec4");
  839. else
  840. methodVar->setType("inline float4");
  841. DecOp *methodDecl = new DecOp(methodVar);
  842. Var *prepassSampler = new Var;
  843. prepassSampler->setName("prepassSamplerVar");
  844. prepassSampler->setType("sampler2D");
  845. DecOp *prepassSamplerDecl = new DecOp(prepassSampler);
  846. Var *screenUV = new Var;
  847. screenUV->setName("screenUVVar");
  848. if (GFX->getAdapterType() == OpenGL)
  849. screenUV->setType("vec2");
  850. else
  851. screenUV->setType("float2");
  852. DecOp *screenUVDecl = new DecOp(screenUV);
  853. Var *bufferSample = new Var;
  854. bufferSample->setName("bufferSample");
  855. if (GFX->getAdapterType() == OpenGL)
  856. bufferSample->setType("vec4");
  857. else
  858. bufferSample->setType("float4");
  859. DecOp *bufferSampleDecl = new DecOp(bufferSample);
  860. meta->addStatement( new GenOp( "@(@, @)\r\n", methodDecl, prepassSamplerDecl, screenUVDecl ) );
  861. meta->addStatement( new GenOp( "{\r\n" ) );
  862. meta->addStatement( new GenOp( " // Sampler g-buffer\r\n" ) );
  863. // The linear depth target has no mipmaps, so use tex2dlod when
  864. // possible so that the shader compiler can optimize.
  865. meta->addStatement( new GenOp( " #if TORQUE_SM >= 30\r\n" ) );
  866. if (GFX->getAdapterType() == OpenGL)
  867. meta->addStatement( new GenOp( " @ = textureLod(@, @, 0); \r\n", bufferSampleDecl, prepassSampler, screenUV) );
  868. else
  869. meta->addStatement( new GenOp( " @ = tex2Dlod(@, float4(@,0,0));\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
  870. meta->addStatement( new GenOp( " #else\r\n" ) );
  871. if (GFX->getAdapterType() == OpenGL)
  872. meta->addStatement( new GenOp( " @ = texture(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV) );
  873. else
  874. meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
  875. meta->addStatement( new GenOp( " #endif\r\n\r\n" ) );
  876. // We don't use this way of passing var's around, so this should cause a crash
  877. // if something uses this improperly
  878. retVal = bufferSample;
  879. }
  880. return retVal;
  881. }
  882. void RenderPrePassMgr::_initShaders()
  883. {
  884. if ( mClearGBufferShader ) return;
  885. // Find ShaderData
  886. ShaderData *shaderData;
  887. mClearGBufferShader = Sim::findObject( "ClearGBufferShader", shaderData ) ? shaderData->getShader() : NULL;
  888. if ( !mClearGBufferShader )
  889. Con::errorf( "RenderPrePassMgr::_initShaders - could not find ClearGBufferShader" );
  890. // Create StateBlocks
  891. GFXStateBlockDesc desc;
  892. desc.setCullMode( GFXCullNone );
  893. desc.setBlend( true );
  894. desc.setZReadWrite( false, false );
  895. desc.samplersDefined = true;
  896. desc.samplers[0].addressModeU = GFXAddressWrap;
  897. desc.samplers[0].addressModeV = GFXAddressWrap;
  898. desc.samplers[0].addressModeW = GFXAddressWrap;
  899. desc.samplers[0].magFilter = GFXTextureFilterLinear;
  900. desc.samplers[0].minFilter = GFXTextureFilterLinear;
  901. desc.samplers[0].mipFilter = GFXTextureFilterLinear;
  902. desc.samplers[0].textureColorOp = GFXTOPModulate;
  903. mStateblock = GFX->createStateBlock( desc );
  904. // Set up shader constants.
  905. mShaderConsts = mClearGBufferShader->allocConstBuffer();
  906. mSpecularStrengthSC = mClearGBufferShader->getShaderConstHandle( "$specularStrength" );
  907. mSpecularPowerSC = mClearGBufferShader->getShaderConstHandle( "$specularPower" );
  908. }
  909. void RenderPrePassMgr::clearBuffers()
  910. {
  911. // Clear z-buffer.
  912. GFX->clear( GFXClearTarget | GFXClearZBuffer | GFXClearStencil, ColorI::ZERO, 1.0f, 0);
  913. if ( !mClearGBufferShader )
  914. return;
  915. GFXTransformSaver saver;
  916. // Clear the g-buffer.
  917. RectI box(-1, -1, 3, 3);
  918. GFX->setWorldMatrix( MatrixF::Identity );
  919. GFX->setViewMatrix( MatrixF::Identity );
  920. GFX->setProjectionMatrix( MatrixF::Identity );
  921. GFX->setShader(mClearGBufferShader);
  922. GFX->setStateBlock(mStateblock);
  923. Point2F nw(-0.5,-0.5);
  924. Point2F ne(0.5,-0.5);
  925. GFXVertexBufferHandle<GFXVertexPC> verts(GFX, 4, GFXBufferTypeVolatile);
  926. verts.lock();
  927. F32 ulOffset = 0.5f - GFX->getFillConventionOffset();
  928. Point2F upperLeft(-1.0, -1.0);
  929. Point2F lowerRight(1.0, 1.0);
  930. verts[0].point.set( upperLeft.x+nw.x+ulOffset, upperLeft.y+nw.y+ulOffset, 0.0f );
  931. verts[1].point.set( lowerRight.x+ne.x, upperLeft.y+ne.y+ulOffset, 0.0f );
  932. verts[2].point.set( upperLeft.x-ne.x+ulOffset, lowerRight.y-ne.y, 0.0f );
  933. verts[3].point.set( lowerRight.x-nw.x, lowerRight.y-nw.y, 0.0f );
  934. verts.unlock();
  935. GFX->setVertexBuffer( verts );
  936. GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
  937. GFX->setShader(NULL);
  938. }