renderPrePassMgr.cpp 40 KB

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