renderDeferredMgr.cpp 38 KB

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