advancedLightBinManager.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  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 "lighting/advanced/advancedLightBinManager.h"
  24. #include "lighting/advanced/advancedLightManager.h"
  25. #include "lighting/advanced/advancedLightBufferConditioner.h"
  26. #include "lighting/shadowMap/shadowMapManager.h"
  27. #include "lighting/shadowMap/shadowMapPass.h"
  28. #include "lighting/shadowMap/lightShadowMap.h"
  29. #include "lighting/common/lightMapParams.h"
  30. #include "renderInstance/renderDeferredMgr.h"
  31. #include "gfx/gfxTransformSaver.h"
  32. #include "scene/sceneManager.h"
  33. #include "scene/sceneRenderState.h"
  34. #include "materials/materialManager.h"
  35. #include "materials/sceneData.h"
  36. #include "core/util/safeDelete.h"
  37. #include "core/util/rgb2luv.h"
  38. #include "gfx/gfxDebugEvent.h"
  39. #include "math/util/matrixSet.h"
  40. #include "console/consoleTypes.h"
  41. #include "gfx/gfxTextureManager.h"
  42. const RenderInstType AdvancedLightBinManager::RIT_LightInfo( "specularLighting" );
  43. const String AdvancedLightBinManager::smBufferName( "specularLighting" );
  44. ShadowFilterMode AdvancedLightBinManager::smShadowFilterMode = ShadowFilterMode_SoftShadowHighQuality;
  45. bool AdvancedLightBinManager::smPSSMDebugRender = false;
  46. bool AdvancedLightBinManager::smUseSSAOMask = false;
  47. ImplementEnumType( ShadowFilterMode,
  48. "The shadow filtering modes for Advanced Lighting shadows.\n"
  49. "@ingroup AdvancedLighting" )
  50. { ShadowFilterMode_None, "None",
  51. "@brief Simple point sampled filtering.\n"
  52. "This is the fastest and lowest quality mode." },
  53. { ShadowFilterMode_SoftShadow, "SoftShadow",
  54. "@brief A variable tap rotated poisson disk soft shadow filter.\n"
  55. "It performs 4 taps to classify the point as in shadow, out of shadow, or along a "
  56. "shadow edge. Samples on the edge get an additional 8 taps to soften them." },
  57. { ShadowFilterMode_SoftShadowHighQuality, "SoftShadowHighQuality",
  58. "@brief A 12 tap rotated poisson disk soft shadow filter.\n"
  59. "It performs all the taps for every point without any early rejection." },
  60. EndImplementEnumType;
  61. // NOTE: The order here matches that of the LightInfo::Type enum.
  62. const String AdvancedLightBinManager::smLightMatNames[] =
  63. {
  64. "AL_PointLightMaterial", // LightInfo::Point
  65. "AL_SpotLightMaterial", // LightInfo::Spot
  66. "AL_VectorLightMaterial", // LightInfo::Vector
  67. "", // LightInfo::Ambient
  68. };
  69. // NOTE: The order here matches that of the LightInfo::Type enum.
  70. const GFXVertexFormat* AdvancedLightBinManager::smLightMatVertex[] =
  71. {
  72. getGFXVertexFormat<AdvancedLightManager::LightVertex>(), // LightInfo::Point
  73. getGFXVertexFormat<AdvancedLightManager::LightVertex>(), // LightInfo::Spot
  74. getGFXVertexFormat<FarFrustumQuadVert>(), // LightInfo::Vector
  75. NULL, // LightInfo::Ambient
  76. };
  77. // NOTE: The order here matches that of the ShadowType enum.
  78. const String AdvancedLightBinManager::smShadowTypeMacro[] =
  79. {
  80. "", // ShadowType_Spot
  81. "", // ShadowType_PSSM,
  82. "SHADOW_PARABOLOID", // ShadowType_Paraboloid,
  83. "SHADOW_DUALPARABOLOID_SINGLE_PASS", // ShadowType_DualParaboloidSinglePass,
  84. "SHADOW_DUALPARABOLOID", // ShadowType_DualParaboloid,
  85. "SHADOW_CUBE", // ShadowType_CubeMap,
  86. };
  87. AdvancedLightBinManager::RenderSignal &AdvancedLightBinManager::getRenderSignal()
  88. {
  89. static RenderSignal theSignal;
  90. return theSignal;
  91. }
  92. IMPLEMENT_CONOBJECT(AdvancedLightBinManager);
  93. ConsoleDocClass( AdvancedLightBinManager,
  94. "@brief Rendering Manager responsible for lighting, shadows, and global variables affecing both.\n\n"
  95. "Should not be exposed to TorqueScript as a game object, meant for internal use only\n\n"
  96. "@ingroup Lighting"
  97. );
  98. AdvancedLightBinManager::AdvancedLightBinManager( AdvancedLightManager *lm /* = NULL */,
  99. ShadowMapManager *sm /* = NULL */,
  100. GFXFormat lightBufferFormat /* = GFXFormatR8G8B8A8 */ )
  101. : RenderBinManager( RIT_LightInfo, 1.0f, 1.0f ),
  102. mNumLightsCulled(0),
  103. mLightManager(lm),
  104. mShadowManager(sm),
  105. mConditioner(NULL)
  106. {
  107. // Create an RGB conditioner
  108. NamedTexTarget* specLightTarg = NamedTexTarget::find(RenderDeferredMgr::SpecularLightBufferName);
  109. mConditioner = new AdvancedLightBufferConditioner(lightBufferFormat,
  110. AdvancedLightBufferConditioner::RGB );
  111. specLightTarg->setConditioner( mConditioner );
  112. mMRTLightmapsDuringDeferred = true;
  113. Con::NotifyDelegate callback( this, &AdvancedLightBinManager::_deleteLightMaterials );
  114. Con::addVariableNotify( "$pref::Shadows::filterMode", callback );
  115. Con::addVariableNotify( "$AL::PSSMDebugRender", callback );
  116. Con::addVariableNotify( "$AL::UseSSAOMask", callback );
  117. }
  118. AdvancedLightBinManager::~AdvancedLightBinManager()
  119. {
  120. _deleteLightMaterials();
  121. SAFE_DELETE(mConditioner);
  122. Con::NotifyDelegate callback( this, &AdvancedLightBinManager::_deleteLightMaterials );
  123. Con::removeVariableNotify( "$pref::shadows::filterMode", callback );
  124. Con::removeVariableNotify( "$AL::PSSMDebugRender", callback );
  125. Con::removeVariableNotify( "$AL::UseSSAOMask", callback );
  126. }
  127. void AdvancedLightBinManager::consoleInit()
  128. {
  129. Parent::consoleInit();
  130. Con::addVariable( "$pref::shadows::filterMode",
  131. TYPEID<ShadowFilterMode>(), &smShadowFilterMode,
  132. "The filter mode to use for shadows.\n"
  133. "@ingroup AdvancedLighting\n" );
  134. Con::addVariable( "$AL::UseSSAOMask", TypeBool, &smUseSSAOMask,
  135. "Used by the SSAO PostEffect to toggle the sampling of ssaomask "
  136. "texture by the light shaders.\n"
  137. "@ingroup AdvancedLighting\n" );
  138. Con::addVariable( "$AL::PSSMDebugRender", TypeBool, &smPSSMDebugRender,
  139. "Enables debug rendering of the PSSM shadows.\n"
  140. "@ingroup AdvancedLighting\n" );
  141. }
  142. bool AdvancedLightBinManager::setTargetSize(const Point2I &newTargetSize)
  143. {
  144. /*bool ret = Parent::setTargetSize( newTargetSize );
  145. // We require the viewport to match the default.
  146. mNamedTarget.setViewport( GFX->getViewport() );
  147. return ret;*/
  148. return true;
  149. }
  150. bool AdvancedLightBinManager::_updateTargets()
  151. {
  152. /* PROFILE_SCOPE(AdvancedLightBinManager_updateTargets);
  153. bool ret = Parent::_updateTargets();
  154. mDiffuseLightingTarget = NamedTexTarget::find("diffuseLighting");
  155. if (mDiffuseLightingTarget.isValid())
  156. {
  157. mDiffuseLightingTex = mDiffuseLightingTarget->getTexture();
  158. for (U32 i = 0; i < mTargetChainLength; i++)
  159. mTargetChain[i]->attachTexture(GFXTextureTarget::Color1, mDiffuseLightingTex);
  160. }
  161. GFX->finalizeReset();
  162. return ret;*/
  163. return true;
  164. }
  165. void AdvancedLightBinManager::addLight( LightInfo *light )
  166. {
  167. // Get the light type.
  168. const LightInfo::Type lightType = light->getType();
  169. AssertFatal( lightType == LightInfo::Point ||
  170. lightType == LightInfo::Spot, "Bogus light type." );
  171. // Find a shadow map for this light, if it has one
  172. ShadowMapParams *lsp = light->getExtended<ShadowMapParams>();
  173. LightShadowMap *lsm = lsp->getShadowMap();
  174. LightShadowMap *dynamicShadowMap = lsp->getShadowMap(true);
  175. // Get the right shadow type.
  176. ShadowType shadowType = ShadowType_None;
  177. if ( light->getCastShadows() &&
  178. lsm && lsm->hasShadowTex() &&
  179. !ShadowMapPass::smDisableShadows )
  180. shadowType = lsm->getShadowType();
  181. // Add the entry
  182. LightBinEntry lEntry;
  183. lEntry.lightInfo = light;
  184. lEntry.shadowMap = lsm;
  185. lEntry.dynamicShadowMap = dynamicShadowMap;
  186. lEntry.lightMaterial = _getLightMaterial( lightType, shadowType, lsp->hasCookieTex() );
  187. if( lightType == LightInfo::Spot )
  188. lEntry.vertBuffer = mLightManager->getConeMesh( lEntry.numPrims, lEntry.primBuffer );
  189. else
  190. lEntry.vertBuffer = mLightManager->getSphereMesh( lEntry.numPrims, lEntry.primBuffer );
  191. // If it's a point light, push front, spot
  192. // light, push back. This helps batches.
  193. Vector<LightBinEntry> &curBin = mLightBin;
  194. if ( light->getType() == LightInfo::Point )
  195. curBin.push_front( lEntry );
  196. else
  197. curBin.push_back( lEntry );
  198. }
  199. void AdvancedLightBinManager::clearAllLights()
  200. {
  201. Con::setIntVariable("lightMetrics::activeLights", mLightBin.size());
  202. Con::setIntVariable("lightMetrics::culledLights", mNumLightsCulled);
  203. mLightBin.clear();
  204. mNumLightsCulled = 0;
  205. }
  206. void AdvancedLightBinManager::render( SceneRenderState *state )
  207. {
  208. PROFILE_SCOPE( AdvancedLightManager_Render );
  209. // Take a look at the SceneRenderState and see if we should skip drawing the pre-pass
  210. if( state->disableAdvancedLightingBins() )
  211. return;
  212. // Automagically save & restore our viewport and transforms.
  213. GFXTransformSaver saver;
  214. if( !mLightManager )
  215. return;
  216. // Get the sunlight. If there's no sun, and no lights in the bins, no draw
  217. LightInfo *sunLight = mLightManager->getSpecialLight( LightManager::slSunLightType, false );
  218. GFXDEBUGEVENT_SCOPE( AdvancedLightBinManager_Render, ColorI::RED );
  219. // Tell the superclass we're about to render
  220. //if ( !_onPreRender( state ) )
  221. // return;
  222. //GFX->clear(GFXClearTarget, ColorI(0, 0, 0, 0), 1.0f, 0);
  223. NamedTexTargetRef diffuseLightingTarget = NamedTexTarget::find("diffuseLighting");
  224. if (diffuseLightingTarget.isNull())
  225. return;
  226. NamedTexTargetRef specularLightingTarget = NamedTexTarget::find("specularLighting");
  227. if (specularLightingTarget.isNull())
  228. return;
  229. GFXTextureTargetRef lightingTargetRef = GFX->allocRenderToTextureTarget();
  230. if (lightingTargetRef.isNull())
  231. return;
  232. //Do a quick pass to update our probes if they're dirty
  233. PROBEMGR->updateDirtyProbes();
  234. lightingTargetRef->attachTexture(GFXTextureTarget::Color0, specularLightingTarget->getTexture());
  235. lightingTargetRef->attachTexture(GFXTextureTarget::Color1, diffuseLightingTarget->getTexture());
  236. GFX->pushActiveRenderTarget();
  237. GFX->setActiveRenderTarget(lightingTargetRef);
  238. GFX->setViewport(specularLightingTarget->getViewport());
  239. // Restore transforms
  240. MatrixSet &matrixSet = getRenderPass()->getMatrixSet();
  241. matrixSet.restoreSceneViewProjection();
  242. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  243. // Set up the SG Data
  244. SceneData sgData;
  245. sgData.init( state );
  246. // There are cases where shadow rendering is disabled.
  247. const bool disableShadows = /*state->isReflectPass() || */ShadowMapPass::smDisableShadows;
  248. // Pick the right material for rendering the sunlight... we only
  249. // cast shadows when its enabled and we're not in a reflection.
  250. LightMaterialInfo *vectorMatInfo;
  251. if ( sunLight &&
  252. sunLight->getCastShadows() &&
  253. !disableShadows &&
  254. sunLight->getExtended<ShadowMapParams>() )
  255. vectorMatInfo = _getLightMaterial( LightInfo::Vector, ShadowType_PSSM, false );
  256. else
  257. vectorMatInfo = _getLightMaterial( LightInfo::Vector, ShadowType_None, false );
  258. // Initialize and set the per-frame parameters after getting
  259. // the vector light material as we use lazy creation.
  260. _setupPerFrameParameters( state );
  261. // Draw sunlight/ambient
  262. if ( sunLight && vectorMatInfo )
  263. {
  264. GFXDEBUGEVENT_SCOPE( AdvancedLightBinManager_Render_Sunlight, ColorI::RED );
  265. // Set up SG data
  266. setupSGData( sgData, state, sunLight );
  267. vectorMatInfo->setLightParameters( sunLight, state );
  268. // Set light holds the active shadow map.
  269. mShadowManager->setLightShadowMapForLight( sunLight );
  270. // Set geometry
  271. GFX->setVertexBuffer( mFarFrustumQuadVerts );
  272. GFX->setPrimitiveBuffer( NULL );
  273. vectorMatInfo->matInstance->mSpecialLight = true;
  274. // Render the material passes
  275. while( vectorMatInfo->matInstance->setupPass( state, sgData ) )
  276. {
  277. vectorMatInfo->matInstance->setSceneInfo( state, sgData );
  278. vectorMatInfo->matInstance->setTransforms( matrixSet, state );
  279. GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
  280. }
  281. }
  282. // Blend the lights in the bin to the light buffer
  283. for( LightBinIterator itr = mLightBin.begin(); itr != mLightBin.end(); itr++ )
  284. {
  285. LightBinEntry& curEntry = *itr;
  286. LightInfo *curLightInfo = curEntry.lightInfo;
  287. LightMaterialInfo *curLightMat = curEntry.lightMaterial;
  288. const U32 numPrims = curEntry.numPrims;
  289. const U32 numVerts = curEntry.vertBuffer->mNumVerts;
  290. ShadowMapParams *lsp = curLightInfo->getExtended<ShadowMapParams>();
  291. // Skip lights which won't affect the scene.
  292. if ( !curLightMat || curLightInfo->getBrightness() <= 0.001f )
  293. continue;
  294. GFXDEBUGEVENT_SCOPE( AdvancedLightBinManager_Render_Light, ColorI::RED );
  295. setupSGData( sgData, state, curLightInfo );
  296. curLightMat->setLightParameters( curLightInfo, state );
  297. mShadowManager->setLightShadowMap( curEntry.shadowMap );
  298. mShadowManager->setLightDynamicShadowMap( curEntry.dynamicShadowMap );
  299. // Set geometry
  300. GFX->setVertexBuffer( curEntry.vertBuffer );
  301. GFX->setPrimitiveBuffer( curEntry.primBuffer );
  302. lsp->getOcclusionQuery()->begin();
  303. curLightMat->matInstance->mSpecialLight = false;
  304. // Render the material passes
  305. while( curLightMat->matInstance->setupPass( state, sgData ) )
  306. {
  307. // Set transforms
  308. matrixSet.setWorld(*sgData.objTrans);
  309. curLightMat->matInstance->setTransforms(matrixSet, state);
  310. curLightMat->matInstance->setSceneInfo(state, sgData);
  311. if(curEntry.primBuffer)
  312. GFX->drawIndexedPrimitive(GFXTriangleList, 0, 0, numVerts, 0, numPrims);
  313. else
  314. GFX->drawPrimitive(GFXTriangleList, 0, numPrims);
  315. }
  316. lsp->getOcclusionQuery()->end();
  317. }
  318. // Set NULL for active shadow map (so nothing gets confused)
  319. mShadowManager->setLightShadowMap(NULL);
  320. mShadowManager->setLightDynamicShadowMap(NULL);
  321. GFX->setVertexBuffer( NULL );
  322. GFX->setPrimitiveBuffer( NULL );
  323. // Fire off a signal to let others know that light-bin rendering is ending now
  324. getRenderSignal().trigger(state, this);
  325. // Finish up the rendering
  326. //_onPostRender();
  327. lightingTargetRef->resolve();
  328. GFX->popActiveRenderTarget();
  329. }
  330. AdvancedLightBinManager::LightMaterialInfo* AdvancedLightBinManager::_getLightMaterial( LightInfo::Type lightType,
  331. ShadowType shadowType,
  332. bool useCookieTex )
  333. {
  334. PROFILE_SCOPE( AdvancedLightBinManager_GetLightMaterial );
  335. // Build the key.
  336. const LightMatKey key( lightType, shadowType, useCookieTex );
  337. // See if we've already built this one.
  338. LightMatTable::Iterator iter = mLightMaterials.find( key );
  339. if ( iter != mLightMaterials.end() )
  340. return iter->value;
  341. // If we got here we need to build a material for
  342. // this light+shadow combination.
  343. LightMaterialInfo *info = NULL;
  344. // First get the light material name and make sure
  345. // this light has a material in the first place.
  346. const String &lightMatName = smLightMatNames[ lightType ];
  347. if ( lightMatName.isNotEmpty() )
  348. {
  349. Vector<GFXShaderMacro> shadowMacros;
  350. // Setup the shadow type macros for this material.
  351. if ( shadowType == ShadowType_None )
  352. shadowMacros.push_back( GFXShaderMacro( "NO_SHADOW" ) );
  353. else
  354. {
  355. shadowMacros.push_back( GFXShaderMacro( smShadowTypeMacro[ shadowType ] ) );
  356. // Do we need to do shadow filtering?
  357. if ( smShadowFilterMode != ShadowFilterMode_None )
  358. {
  359. shadowMacros.push_back( GFXShaderMacro( "SOFTSHADOW" ) );
  360. const F32 SM = GFX->getPixelShaderVersion();
  361. if ( SM >= 3.0f && smShadowFilterMode == ShadowFilterMode_SoftShadowHighQuality )
  362. shadowMacros.push_back( GFXShaderMacro( "SOFTSHADOW_HIGH_QUALITY" ) );
  363. }
  364. }
  365. if ( useCookieTex )
  366. shadowMacros.push_back( GFXShaderMacro( "USE_COOKIE_TEX" ) );
  367. // Its safe to add the PSSM debug macro to all the materials.
  368. if ( smPSSMDebugRender )
  369. shadowMacros.push_back( GFXShaderMacro( "PSSM_DEBUG_RENDER" ) );
  370. // If its a vector light see if we can enable SSAO.
  371. if ( lightType == LightInfo::Vector && smUseSSAOMask )
  372. shadowMacros.push_back( GFXShaderMacro( "USE_SSAO_MASK" ) );
  373. // Now create the material info object.
  374. info = new LightMaterialInfo( lightMatName, smLightMatVertex[ lightType ], shadowMacros );
  375. }
  376. // Push this into the map and return it.
  377. mLightMaterials.insertUnique( key, info );
  378. return info;
  379. }
  380. void AdvancedLightBinManager::_deleteLightMaterials()
  381. {
  382. LightMatTable::Iterator iter = mLightMaterials.begin();
  383. for ( ; iter != mLightMaterials.end(); iter++ )
  384. delete iter->value;
  385. mLightMaterials.clear();
  386. }
  387. void AdvancedLightBinManager::_setupPerFrameParameters( const SceneRenderState *state )
  388. {
  389. PROFILE_SCOPE( AdvancedLightBinManager_SetupPerFrameParameters );
  390. const Frustum &frustum = state->getCameraFrustum();
  391. MatrixF invCam( frustum.getTransform() );
  392. invCam.inverse();
  393. const Point3F *wsFrustumPoints = frustum.getPoints();
  394. const Point3F& cameraPos = frustum.getPosition();
  395. // Perform a camera offset. We need to manually perform this offset on the sun (or vector) light's
  396. // polygon, which is at the far plane.
  397. Point3F cameraOffsetPos = cameraPos;
  398. // Now build the quad for drawing full-screen vector light
  399. // passes.... this is a volatile VB and updates every frame.
  400. FarFrustumQuadVert verts[4];
  401. {
  402. verts[0].point.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraPos);
  403. invCam.mulP(wsFrustumPoints[Frustum::FarTopLeft], &verts[0].normal);
  404. verts[0].texCoord.set(-1.0, 1.0);
  405. verts[0].tangent.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraOffsetPos);
  406. verts[1].point.set(wsFrustumPoints[Frustum::FarTopRight] - cameraPos);
  407. invCam.mulP(wsFrustumPoints[Frustum::FarTopRight], &verts[1].normal);
  408. verts[1].texCoord.set(1.0, 1.0);
  409. verts[1].tangent.set(wsFrustumPoints[Frustum::FarTopRight] - cameraOffsetPos);
  410. verts[2].point.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraPos);
  411. invCam.mulP(wsFrustumPoints[Frustum::FarBottomLeft], &verts[2].normal);
  412. verts[2].texCoord.set(-1.0, -1.0);
  413. verts[2].tangent.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraOffsetPos);
  414. verts[3].point.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraPos);
  415. invCam.mulP(wsFrustumPoints[Frustum::FarBottomRight], &verts[3].normal);
  416. verts[3].texCoord.set(1.0, -1.0);
  417. verts[3].tangent.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraOffsetPos);
  418. }
  419. mFarFrustumQuadVerts.set( GFX, 4 );
  420. dMemcpy( mFarFrustumQuadVerts.lock(), verts, sizeof( verts ) );
  421. mFarFrustumQuadVerts.unlock();
  422. PlaneF farPlane(wsFrustumPoints[Frustum::FarBottomLeft], wsFrustumPoints[Frustum::FarTopLeft], wsFrustumPoints[Frustum::FarTopRight]);
  423. PlaneF vsFarPlane(verts[0].normal, verts[1].normal, verts[2].normal);
  424. // Parameters calculated, assign them to the materials
  425. LightMatTable::Iterator iter = mLightMaterials.begin();
  426. for ( ; iter != mLightMaterials.end(); iter++ )
  427. {
  428. if ( iter->value )
  429. iter->value->setViewParameters( frustum.getNearDist(),
  430. frustum.getFarDist(),
  431. frustum.getPosition(),
  432. farPlane,
  433. vsFarPlane);
  434. }
  435. MatrixSet &matrixSet = getRenderPass()->getMatrixSet();
  436. //matrixSet.restoreSceneViewProjection();
  437. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  438. MatrixF inverseViewMatrix = worldToCameraXfm;
  439. //inverseViewMatrix.fullInverse();
  440. //inverseViewMatrix.transpose();
  441. //MatrixF inverseViewMatrix = MatrixF::Identity;
  442. }
  443. void AdvancedLightBinManager::setupSGData( SceneData &data, const SceneRenderState* state, LightInfo *light )
  444. {
  445. PROFILE_SCOPE( AdvancedLightBinManager_setupSGData );
  446. data.lights[0] = light;
  447. data.ambientLightColor = state->getAmbientLightColor();
  448. data.objTrans = &MatrixF::Identity;
  449. if ( light )
  450. {
  451. if ( light->getType() == LightInfo::Point )
  452. {
  453. // The point light volume gets some flat spots along
  454. // the perimiter mostly visible in the constant and
  455. // quadradic falloff modes.
  456. //
  457. // To account for them slightly increase the scale
  458. // instead of greatly increasing the polycount.
  459. mLightMat = light->getTransform();
  460. mLightMat.scale( light->getRange() * 1.01f );
  461. data.objTrans = &mLightMat;
  462. }
  463. else if ( light->getType() == LightInfo::Spot )
  464. {
  465. mLightMat = light->getTransform();
  466. // Rotate it to face down the -y axis.
  467. MatrixF scaleRotateTranslate( EulerF( M_PI_F / -2.0f, 0.0f, 0.0f ) );
  468. // Calculate the radius based on the range and angle.
  469. F32 range = light->getRange().x;
  470. F32 radius = range * mSin( mDegToRad( light->getOuterConeAngle() ) * 0.5f );
  471. // NOTE: This fudge makes the cone a little bigger
  472. // to remove the facet egde of the cone geometry.
  473. radius *= 1.1f;
  474. // Use the scale to distort the cone to
  475. // match our radius and range.
  476. scaleRotateTranslate.scale( Point3F( radius, radius, range ) );
  477. // Apply the transform and set the position.
  478. mLightMat *= scaleRotateTranslate;
  479. mLightMat.setPosition( light->getPosition() );
  480. data.objTrans = &mLightMat;
  481. }
  482. }
  483. }
  484. void AdvancedLightBinManager::MRTLightmapsDuringDeferred( bool val )
  485. {
  486. // Do not enable if the GFX device can't do MRT's
  487. if ( GFX->getNumRenderTargets() < 2 )
  488. val = false;
  489. if ( mMRTLightmapsDuringDeferred != val )
  490. {
  491. mMRTLightmapsDuringDeferred = val;
  492. // Reload materials to cause a feature recalculation on deferred materials
  493. if(mLightManager->isActive())
  494. MATMGR->flushAndReInitInstances();
  495. RenderDeferredMgr *deferred;
  496. if ( Sim::findObject( "AL_DeferredBin", deferred ) && deferred->getTargetTexture( 0 ) )
  497. deferred->updateTargets();
  498. }
  499. }
  500. AdvancedLightBinManager::LightMaterialInfo::LightMaterialInfo( const String &matName,
  501. const GFXVertexFormat *vertexFormat,
  502. const Vector<GFXShaderMacro> &macros )
  503. : matInstance(NULL),
  504. zNearFarInvNearFar(NULL),
  505. farPlane(NULL),
  506. vsFarPlane(NULL),
  507. negFarPlaneDotEye(NULL),
  508. lightPosition(NULL),
  509. lightDirection(NULL),
  510. lightColor(NULL),
  511. lightAttenuation(NULL),
  512. lightRange(NULL),
  513. lightAmbient(NULL),
  514. lightTrilight(NULL),
  515. lightSpotParams(NULL)
  516. {
  517. Material *mat = MATMGR->getMaterialDefinitionByName( matName );
  518. if ( !mat )
  519. return;
  520. matInstance = new LightMatInstance( *mat );
  521. for ( U32 i=0; i < macros.size(); i++ )
  522. matInstance->addShaderMacro( macros[i].name, macros[i].value );
  523. matInstance->init( MATMGR->getDefaultFeatures(), vertexFormat );
  524. lightDirection = matInstance->getMaterialParameterHandle("$lightDirection");
  525. lightAmbient = matInstance->getMaterialParameterHandle("$lightAmbient");
  526. lightTrilight = matInstance->getMaterialParameterHandle("$lightTrilight");
  527. lightSpotParams = matInstance->getMaterialParameterHandle("$lightSpotParams");
  528. lightAttenuation = matInstance->getMaterialParameterHandle("$lightAttenuation");
  529. lightRange = matInstance->getMaterialParameterHandle("$lightRange");
  530. lightPosition = matInstance->getMaterialParameterHandle("$lightPosition");
  531. farPlane = matInstance->getMaterialParameterHandle("$farPlane");
  532. vsFarPlane = matInstance->getMaterialParameterHandle("$vsFarPlane");
  533. negFarPlaneDotEye = matInstance->getMaterialParameterHandle("$negFarPlaneDotEye");
  534. zNearFarInvNearFar = matInstance->getMaterialParameterHandle("$zNearFarInvNearFar");
  535. lightColor = matInstance->getMaterialParameterHandle("$lightColor");
  536. lightBrightness = matInstance->getMaterialParameterHandle("$lightBrightness");
  537. }
  538. AdvancedLightBinManager::LightMaterialInfo::~LightMaterialInfo()
  539. {
  540. SAFE_DELETE(matInstance);
  541. }
  542. void AdvancedLightBinManager::LightMaterialInfo::setViewParameters( const F32 _zNear,
  543. const F32 _zFar,
  544. const Point3F &_eyePos,
  545. const PlaneF &_farPlane,
  546. const PlaneF &_vsFarPlane)
  547. {
  548. MaterialParameters *matParams = matInstance->getMaterialParameters();
  549. matParams->setSafe( farPlane, *((const Point4F *)&_farPlane) );
  550. matParams->setSafe( vsFarPlane, *((const Point4F *)&_vsFarPlane) );
  551. if ( negFarPlaneDotEye->isValid() )
  552. {
  553. // -dot( farPlane, eyePos )
  554. const F32 negFarPlaneDotEyeVal = -( mDot( *((const Point3F *)&_farPlane), _eyePos ) + _farPlane.d );
  555. matParams->set( negFarPlaneDotEye, negFarPlaneDotEyeVal );
  556. }
  557. matParams->setSafe( zNearFarInvNearFar, Point4F( _zNear, _zFar, 1.0f / _zNear, 1.0f / _zFar ) );
  558. }
  559. void AdvancedLightBinManager::LightMaterialInfo::setLightParameters( const LightInfo *lightInfo, const SceneRenderState* renderState )
  560. {
  561. MaterialParameters *matParams = matInstance->getMaterialParameters();
  562. // Set color in the right format, set alpha to the luminance value for the color.
  563. LinearColorF col = lightInfo->getColor();
  564. // TODO: The specularity control of the light
  565. // is being scaled by the overall lumiance.
  566. //
  567. // Not sure if this may be the source of our
  568. // bad specularity results maybe?
  569. //
  570. const Point3F colorToLumiance( 0.3576f, 0.7152f, 0.1192f );
  571. F32 lumiance = mDot(*((const Point3F *)&lightInfo->getColor()), colorToLumiance );
  572. col.alpha *= lumiance;
  573. matParams->setSafe( lightColor, col );
  574. matParams->setSafe( lightBrightness, lightInfo->getBrightness() );
  575. switch( lightInfo->getType() )
  576. {
  577. case LightInfo::Vector:
  578. {
  579. const VectorF lightDir = lightInfo->getDirection();
  580. matParams->setSafe( lightDirection, lightDir );
  581. // Set small number for alpha since it represents existing specular in
  582. // the vector light. This prevents a divide by zero.
  583. LinearColorF ambientColor = renderState->getAmbientLightColor();
  584. ambientColor.alpha = 0.00001f;
  585. matParams->setSafe( lightAmbient, ambientColor );
  586. // If no alt color is specified, set it to the average of
  587. // the ambient and main color to avoid artifacts.
  588. //
  589. // TODO: Trilight disabled until we properly implement it
  590. // in the light info!
  591. //
  592. //LinearColorF lightAlt = lightInfo->getAltColor();
  593. LinearColorF lightAlt( LinearColorF::BLACK ); // = lightInfo->getAltColor();
  594. if ( lightAlt.red == 0.0f && lightAlt.green == 0.0f && lightAlt.blue == 0.0f )
  595. lightAlt = (lightInfo->getColor() + renderState->getAmbientLightColor()) / 2.0f;
  596. LinearColorF trilightColor = lightAlt;
  597. matParams->setSafe(lightTrilight, trilightColor);
  598. }
  599. break;
  600. case LightInfo::Spot:
  601. {
  602. const F32 outerCone = lightInfo->getOuterConeAngle();
  603. const F32 innerCone = getMin( lightInfo->getInnerConeAngle(), outerCone );
  604. const F32 outerCos = mCos( mDegToRad( outerCone / 2.0f ) );
  605. const F32 innerCos = mCos( mDegToRad( innerCone / 2.0f ) );
  606. Point4F spotParams( outerCos,
  607. innerCos - outerCos,
  608. mCos( mDegToRad( outerCone ) ),
  609. 0.0f );
  610. matParams->setSafe( lightSpotParams, spotParams );
  611. VectorF lightDir = lightInfo->getDirection();
  612. matParams->setSafe( lightDirection, lightDir );
  613. }
  614. // Fall through
  615. case LightInfo::Point:
  616. {
  617. const F32 radius = lightInfo->getRange().x;
  618. matParams->setSafe( lightRange, radius );
  619. matParams->setSafe( lightPosition, lightInfo->getPosition());
  620. // Get the attenuation falloff ratio and normalize it.
  621. Point3F attenRatio = lightInfo->getExtended<ShadowMapParams>()->attenuationRatio;
  622. F32 total = attenRatio.x + attenRatio.y + attenRatio.z;
  623. if ( total > 0.0f )
  624. attenRatio /= total;
  625. Point2F attenParams( ( 1.0f / radius ) * attenRatio.y,
  626. ( 1.0f / ( radius * radius ) ) * attenRatio.z );
  627. matParams->setSafe( lightAttenuation, attenParams );
  628. break;
  629. }
  630. default:
  631. AssertFatal( false, "Bad light type!" );
  632. break;
  633. }
  634. }
  635. bool LightMatInstance::setupPass( SceneRenderState *state, const SceneData &sgData )
  636. {
  637. // Go no further if the material failed to initialize properly.
  638. if ( !mProcessedMaterial ||
  639. mProcessedMaterial->getNumPasses() == 0 )
  640. return false;
  641. U32 reflectStatus = Base;
  642. if (state->isReflectPass())
  643. reflectStatus = Reflecting;
  644. // Fetch the lightmap params
  645. const LightMapParams *lmParams = sgData.lights[0]->getExtended<LightMapParams>();
  646. // If no Lightmap params, let parent handle it
  647. if(lmParams == NULL)
  648. return Parent::setupPass(state, sgData);
  649. // Defaults
  650. bool bRetVal = true;
  651. // What render pass is this...
  652. if(mCurPass == -1)
  653. {
  654. // First pass, reset this flag
  655. mInternalPass = false;
  656. // Pass call to parent
  657. bRetVal = Parent::setupPass(state, sgData);
  658. }
  659. else
  660. {
  661. // If this light is represented in a lightmap, it has already done it's
  662. // job for non-lightmapped geometry. Now render the lightmapped geometry
  663. // pass (specular + shadow-darkening)
  664. if(!mInternalPass && lmParams->representedInLightmap)
  665. mInternalPass = true;
  666. else
  667. return Parent::setupPass(state, sgData);
  668. }
  669. // Set up the shader constants we need to...
  670. if(mLightMapParamsSC->isValid())
  671. {
  672. // If this is an internal pass, special case the parameters
  673. if(mInternalPass)
  674. {
  675. AssertFatal( lmParams->shadowDarkenColor.alpha == -1.0f, "Assumption failed, check unpack code!" );
  676. getMaterialParameters()->set( mLightMapParamsSC, lmParams->shadowDarkenColor );
  677. }
  678. else
  679. getMaterialParameters()->set( mLightMapParamsSC, LinearColorF::WHITE );
  680. }
  681. // Now override stateblock with our own
  682. if(!mInternalPass)
  683. {
  684. // If this is not an internal pass, and this light is represented in lightmaps
  685. // than only effect non-lightmapped geometry for this pass
  686. if (lmParams->representedInLightmap)
  687. {
  688. GFX->setStateBlock(mLitState[StaticLightNonLMGeometry][reflectStatus]);
  689. }
  690. else // This is a normal, dynamic light.
  691. {
  692. if (mSpecialLight)
  693. GFX->setStateBlock(mLitState[SunLight][reflectStatus]);
  694. else
  695. GFX->setStateBlock(mLitState[DynamicLight][reflectStatus]);
  696. }
  697. }
  698. else // Internal pass, this is the add-specular/multiply-darken-color pass
  699. GFX->setStateBlock(mLitState[StaticLightLMGeometry][reflectStatus]);
  700. return bRetVal;
  701. }
  702. bool LightMatInstance::init( const FeatureSet &features, const GFXVertexFormat *vertexFormat )
  703. {
  704. bool success = Parent::init(features, vertexFormat);
  705. // If the initialization failed don't continue.
  706. if ( !success || !mProcessedMaterial || mProcessedMaterial->getNumPasses() == 0 )
  707. return false;
  708. mLightMapParamsSC = getMaterialParameterHandle("$lightMapParams");
  709. // Grab the state block for the first render pass (since this mat instance
  710. // inserts a pass after the first pass)
  711. AssertFatal(mProcessedMaterial->getNumPasses() > 0, "No passes created! Ohnoes");
  712. const RenderPassData *rpd = mProcessedMaterial->getPass(0);
  713. AssertFatal(rpd, "No render pass data!");
  714. AssertFatal(rpd->mRenderStates[0], "No render state 0!");
  715. // Get state block desc for normal (not wireframe, not translucent, not glow, etc)
  716. // render state
  717. GFXStateBlockDesc litState = rpd->mRenderStates[0]->getDesc();
  718. // Create state blocks for each of the 3 possible combos in setupPass
  719. //DynamicLight State: This will effect lightmapped and non-lightmapped geometry
  720. // in the same way.
  721. litState.separateAlphaBlendDefined = true;
  722. litState.separateAlphaBlendEnable = false;
  723. litState.stencilMask = RenderDeferredMgr::OpaqueDynamicLitMask | RenderDeferredMgr::OpaqueStaticLitMask;
  724. litState.setCullMode(GFXCullCW);
  725. mLitState[DynamicLight][Base] = GFX->createStateBlock(litState);
  726. litState.setCullMode(GFXCullCCW);
  727. mLitState[DynamicLight][Reflecting] = GFX->createStateBlock(litState);
  728. litState.separateAlphaBlendDefined = true;
  729. litState.separateAlphaBlendEnable = false;
  730. litState.stencilMask = RenderDeferredMgr::OpaqueDynamicLitMask | RenderDeferredMgr::OpaqueStaticLitMask;
  731. litState.setCullMode(GFXCullCCW);
  732. mLitState[SunLight][Base] = GFX->createStateBlock(litState);
  733. litState.setCullMode(GFXCullCCW);
  734. mLitState[SunLight][Reflecting] = GFX->createStateBlock(litState);
  735. // StaticLightNonLMGeometry State: This will treat non-lightmapped geometry
  736. // in the usual way, but will not effect lightmapped geometry.
  737. litState.separateAlphaBlendDefined = true;
  738. litState.separateAlphaBlendEnable = false;
  739. litState.stencilMask = RenderDeferredMgr::OpaqueDynamicLitMask;
  740. litState.setCullMode(GFXCullCW);
  741. mLitState[StaticLightNonLMGeometry][Base] = GFX->createStateBlock(litState);
  742. litState.setCullMode(GFXCullCCW);
  743. mLitState[StaticLightNonLMGeometry][Reflecting] = GFX->createStateBlock(litState);
  744. // StaticLightLMGeometry State: This will add specular information (alpha) but
  745. // multiply-darken color information.
  746. litState.blendDest = GFXBlendSrcColor;
  747. litState.blendSrc = GFXBlendZero;
  748. litState.stencilMask = RenderDeferredMgr::OpaqueStaticLitMask;
  749. litState.separateAlphaBlendDefined = true;
  750. litState.separateAlphaBlendEnable = true;
  751. litState.separateAlphaBlendSrc = GFXBlendOne;
  752. litState.separateAlphaBlendDest = GFXBlendOne;
  753. litState.separateAlphaBlendOp = GFXBlendOpAdd;
  754. litState.setCullMode(GFXCullCW);
  755. mLitState[StaticLightLMGeometry][Base] = GFX->createStateBlock(litState);
  756. litState.setCullMode(GFXCullCCW);
  757. mLitState[StaticLightLMGeometry][Reflecting] = GFX->createStateBlock(litState);
  758. return true;
  759. }