advancedLightBinManager.cpp 35 KB

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