lightShadowMap.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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/shadowMap/lightShadowMap.h"
  24. #include "lighting/shadowMap/shadowMapManager.h"
  25. #include "lighting/shadowMap/shadowMatHook.h"
  26. #include "gfx/gfxDevice.h"
  27. #include "gfx/gfxTextureManager.h"
  28. #include "gfx/gfxOcclusionQuery.h"
  29. #include "gfx/gfxCardProfile.h"
  30. #include "gfx/sim/debugDraw.h"
  31. #include "materials/materialDefinition.h"
  32. #include "materials/baseMatInstance.h"
  33. #include "scene/sceneManager.h"
  34. #include "scene/sceneRenderState.h"
  35. #include "scene/zones/sceneZoneSpace.h"
  36. #include "lighting/lightManager.h"
  37. #include "math/mathUtils.h"
  38. #include "shaderGen/shaderGenVars.h"
  39. #include "core/util/safeDelete.h"
  40. #include "core/stream/bitStream.h"
  41. #include "math/mathIO.h"
  42. #include "materials/shaderData.h"
  43. #include "core/module.h"
  44. // Used for creation in ShadowMapParams::getOrCreateShadowMap()
  45. #include "lighting/shadowMap/singleLightShadowMap.h"
  46. #include "lighting/shadowMap/pssmLightShadowMap.h"
  47. #include "lighting/shadowMap/cubeLightShadowMap.h"
  48. #include "lighting/shadowMap/dualParaboloidLightShadowMap.h"
  49. // Remove this when the shader constants are reworked better
  50. #include "lighting/advanced/advancedLightManager.h"
  51. #include "lighting/advanced/advancedLightBinManager.h"
  52. // TODO: Some cards (Justin's GeForce 7x series) barf on the integer format causing
  53. // filtering artifacts. These can (sometimes) be resolved by switching the format
  54. // to FP16 instead of Int16.
  55. const GFXFormat LightShadowMap::ShadowMapFormat = GFXFormatR32F; // GFXFormatR8G8B8A8;
  56. bool LightShadowMap::smDebugRenderFrustums;
  57. F32 LightShadowMap::smShadowTexScalar = 1.0f;
  58. Vector<LightShadowMap*> LightShadowMap::smUsedShadowMaps;
  59. Vector<LightShadowMap*> LightShadowMap::smShadowMaps;
  60. GFX_ImplementTextureProfile( ShadowMapProfile,
  61. GFXTextureProfile::DiffuseMap,
  62. GFXTextureProfile::PreserveSize |
  63. GFXTextureProfile::RenderTarget |
  64. GFXTextureProfile::Pooled,
  65. GFXTextureProfile::NONE );
  66. GFX_ImplementTextureProfile( ShadowMapZProfile,
  67. GFXTextureProfile::DiffuseMap,
  68. GFXTextureProfile::PreserveSize |
  69. GFXTextureProfile::NoMipmap |
  70. GFXTextureProfile::ZTarget |
  71. GFXTextureProfile::Pooled,
  72. GFXTextureProfile::NONE );
  73. LightShadowMap::LightShadowMap( LightInfo *light )
  74. : mWorldToLightProj( true ),
  75. mLight( light ),
  76. mTexSize( 0 ),
  77. mLastShader( NULL ),
  78. mLastUpdate( 0 ),
  79. mLastCull( 0 ),
  80. mIsViewDependent( false ),
  81. mVizQuery( NULL ),
  82. mWasOccluded( false ),
  83. mLastScreenSize( 0.0f ),
  84. mLastPriority( 0.0f ),
  85. mIsDynamic( false )
  86. {
  87. GFXTextureManager::addEventDelegate( this, &LightShadowMap::_onTextureEvent );
  88. mTarget = GFX->allocRenderToTextureTarget();
  89. mVizQuery = GFX->createOcclusionQuery();
  90. smShadowMaps.push_back(this);
  91. mStaticRefreshTimer = PlatformTimer::create();
  92. mDynamicRefreshTimer = PlatformTimer::create();
  93. }
  94. LightShadowMap::~LightShadowMap()
  95. {
  96. mTarget = NULL;
  97. SAFE_DELETE( mVizQuery );
  98. releaseTextures();
  99. smShadowMaps.remove( this );
  100. smUsedShadowMaps.remove( this );
  101. GFXTextureManager::removeEventDelegate( this, &LightShadowMap::_onTextureEvent );
  102. }
  103. void LightShadowMap::releaseAllTextures()
  104. {
  105. PROFILE_SCOPE( LightShadowMap_ReleaseAllTextures );
  106. for ( U32 i=0; i < smShadowMaps.size(); i++ )
  107. smShadowMaps[i]->releaseTextures();
  108. }
  109. U32 LightShadowMap::releaseUnusedTextures()
  110. {
  111. PROFILE_SCOPE( LightShadowMap_ReleaseUnusedTextures );
  112. const U32 currTime = Sim::getCurrentTime();
  113. const U32 purgeTime = 1000;
  114. for ( U32 i=0; i < smUsedShadowMaps.size(); )
  115. {
  116. LightShadowMap *lsm = smUsedShadowMaps[i];
  117. // If the shadow has not been culled in a while then
  118. // release its textures for other shadows to use.
  119. if ( currTime > ( lsm->mLastCull + purgeTime ) )
  120. {
  121. // Internally this will remove the map from the used
  122. // list, so don't increment the loop.
  123. lsm->releaseTextures();
  124. continue;
  125. }
  126. i++;
  127. }
  128. return smUsedShadowMaps.size();
  129. }
  130. void LightShadowMap::_onTextureEvent( GFXTexCallbackCode code )
  131. {
  132. if ( code == GFXZombify )
  133. releaseTextures();
  134. // We don't initialize here as we want the textures
  135. // to be reallocated when the shadow becomes visible.
  136. }
  137. void LightShadowMap::calcLightMatrices( MatrixF &outLightMatrix, const Frustum &viewFrustum )
  138. {
  139. // Create light matrix, set projection
  140. switch ( mLight->getType() )
  141. {
  142. case LightInfo::Vector :
  143. {
  144. const ShadowMapParams *p = mLight->getExtended<ShadowMapParams>();
  145. // Calculate the bonding box of the shadowed area
  146. // we're interested in... this is the shadow box
  147. // transformed by the frustum transform.
  148. Box3F viewBB( -p->shadowDistance, -p->shadowDistance, -p->shadowDistance,
  149. p->shadowDistance, p->shadowDistance, p->shadowDistance );
  150. viewFrustum.getTransform().mul( viewBB );
  151. // Calculate a light "projection" matrix.
  152. MatrixF lightMatrix = MathUtils::createOrientFromDir(mLight->getDirection());
  153. outLightMatrix = lightMatrix;
  154. static MatrixF rotMat(EulerF( (M_PI_F / 2.0f), 0.0f, 0.0f));
  155. lightMatrix.mul( rotMat );
  156. // This is the box in lightspace
  157. Box3F lightViewBB(viewBB);
  158. lightMatrix.mul(lightViewBB);
  159. // Now, let's position our light based on the lightViewBB
  160. Point3F newLightPos(viewBB.getCenter());
  161. F32 sceneDepth = lightViewBB.maxExtents.z - lightViewBB.minExtents.z;
  162. newLightPos += mLight->getDirection() * ((-sceneDepth / 2.0f)-1.0f); // -1 for the nearplane
  163. outLightMatrix.setPosition(newLightPos);
  164. // Update light info
  165. mLight->setRange( sceneDepth );
  166. mLight->setPosition( newLightPos );
  167. // Set our ortho projection
  168. F32 width = (lightViewBB.maxExtents.x - lightViewBB.minExtents.x) / 2.0f;
  169. F32 height = (lightViewBB.maxExtents.y - lightViewBB.minExtents.y) / 2.0f;
  170. width = getMax(width, height);
  171. GFX->setOrtho(-width, width, -width, width, 1.0f, sceneDepth, true);
  172. // TODO: Width * 2... really isn't that pixels being used as
  173. // meters? Is a real physical metric of scene depth better?
  174. //SceneManager::setVisibleDistance(width * 2.0f);
  175. #if 0
  176. DebugDrawer::get()->drawFrustum(viewFrustum, ColorF(1.0f, 0.0f, 0.0f));
  177. DebugDrawer::get()->drawBox(viewBB.minExtents, viewBB.maxExtents, ColorF(0.0f, 1.0f, 0.0f));
  178. DebugDrawer::get()->drawBox(lightViewBB.minExtents, lightViewBB.maxExtents, ColorF(0.0f, 0.0f, 1.0f));
  179. DebugDrawer::get()->drawBox(newLightPos - Point3F(1,1,1), newLightPos + Point3F(1,1,1), ColorF(1,1,0));
  180. DebugDrawer::get()->drawLine(newLightPos, newLightPos + mLight.mDirection*3.0f, ColorF(0,1,1));
  181. Point3F a(newLightPos);
  182. Point3F b(newLightPos);
  183. Point3F offset(width, height,0.0f);
  184. a -= offset;
  185. b += offset;
  186. DebugDrawer::get()->drawBox(a, b, ColorF(0.5f, 0.5f, 0.5f));
  187. #endif
  188. }
  189. break;
  190. case LightInfo::Spot :
  191. {
  192. outLightMatrix = mLight->getTransform();
  193. F32 fov = mDegToRad( mLight->getOuterConeAngle() );
  194. F32 farDist = mLight->getRange().x;
  195. F32 nearDist = farDist * 0.01f;
  196. F32 left, right, top, bottom;
  197. MathUtils::makeFrustum( &left, &right, &top, &bottom, fov, 1.0f, nearDist );
  198. GFX->setFrustum( left, right, bottom, top, nearDist, farDist );
  199. }
  200. break;
  201. default:
  202. AssertFatal(false, "Unsupported light type!");
  203. }
  204. }
  205. void LightShadowMap::releaseTextures()
  206. {
  207. mShadowMapTex = NULL;
  208. mDebugTarget.setTexture( NULL );
  209. mLastUpdate = 0;
  210. smUsedShadowMaps.remove( this );
  211. }
  212. void LightShadowMap::setDebugTarget( const String &name )
  213. {
  214. mDebugTarget.registerWithName( name );
  215. mDebugTarget.setTexture( mShadowMapTex );
  216. }
  217. GFXTextureObject* LightShadowMap::_getDepthTarget( U32 width, U32 height )
  218. {
  219. // Get a depth texture target from the pooled profile
  220. // which is returned as a temporary.
  221. GFXTexHandle depthTex( width, height, GFXFormatD24S8, &ShadowMapZProfile,
  222. "LightShadowMap::_getDepthTarget()" );
  223. return depthTex;
  224. }
  225. bool LightShadowMap::setTextureStage( U32 currTexFlag, LightingShaderConstants* lsc )
  226. {
  227. if ( currTexFlag == Material::DynamicLight && !isDynamic() )
  228. {
  229. S32 reg = lsc->mShadowMapSC->getSamplerRegister();
  230. if ( reg != -1 )
  231. GFX->setTexture( reg, mShadowMapTex);
  232. return true;
  233. } else if ( currTexFlag == Material::DynamicShadowMap && isDynamic() )
  234. {
  235. S32 reg = lsc->mDynamicShadowMapSC->getSamplerRegister();
  236. if ( reg != -1 )
  237. GFX->setTexture( reg, mShadowMapTex);
  238. return true;
  239. }
  240. else if ( currTexFlag == Material::DynamicLightMask )
  241. {
  242. S32 reg = lsc->mCookieMapSC->getSamplerRegister();
  243. if ( reg != -1 )
  244. {
  245. ShadowMapParams *p = mLight->getExtended<ShadowMapParams>();
  246. if ( lsc->mCookieMapSC->getType() == GFXSCT_SamplerCube )
  247. GFX->setCubeTexture( reg, p->getCookieCubeTex() );
  248. else
  249. GFX->setTexture( reg, p->getCookieTex() );
  250. }
  251. return true;
  252. }
  253. return false;
  254. }
  255. void LightShadowMap::render( RenderPassManager* renderPass,
  256. const SceneRenderState *diffuseState,
  257. bool _dynamic)
  258. {
  259. // control how often shadow maps are refreshed
  260. if (!_dynamic && (mStaticRefreshTimer->getElapsedMs() < getLightInfo()->getStaticRefreshFreq()))
  261. return;
  262. mStaticRefreshTimer->reset();
  263. if (_dynamic && (mDynamicRefreshTimer->getElapsedMs() < getLightInfo()->getDynamicRefreshFreq()))
  264. return;
  265. mDynamicRefreshTimer->reset();
  266. mDebugTarget.setTexture( NULL );
  267. _render( renderPass, diffuseState );
  268. mDebugTarget.setTexture( mShadowMapTex );
  269. // Add it to the used list unless we're been updated.
  270. if ( !mLastUpdate )
  271. {
  272. AssertFatal( !smUsedShadowMaps.contains( this ), "LightShadowMap::render - Used shadow map inserted twice!" );
  273. smUsedShadowMaps.push_back( this );
  274. }
  275. mLastUpdate = Sim::getCurrentTime();
  276. }
  277. void LightShadowMap::preLightRender()
  278. {
  279. PROFILE_SCOPE( LightShadowMap_prepLightRender );
  280. if ( mVizQuery )
  281. {
  282. mWasOccluded = mVizQuery->getStatus( true ) == GFXOcclusionQuery::Occluded;
  283. mVizQuery->begin();
  284. }
  285. }
  286. void LightShadowMap::postLightRender()
  287. {
  288. if ( mVizQuery )
  289. mVizQuery->end();
  290. }
  291. BaseMatInstance* LightShadowMap::getShadowMaterial( BaseMatInstance *inMat ) const
  292. {
  293. // See if we have an existing material hook.
  294. ShadowMaterialHook *hook = static_cast<ShadowMaterialHook*>( inMat->getHook( ShadowMaterialHook::Type ) );
  295. if ( !hook )
  296. {
  297. // Create a hook and initialize it using the incoming material.
  298. hook = new ShadowMaterialHook;
  299. hook->init( inMat );
  300. inMat->addHook( hook );
  301. }
  302. return hook->getShadowMat( getShadowType() );
  303. }
  304. U32 LightShadowMap::getBestTexSize( U32 scale ) const
  305. {
  306. const ShadowMapParams *params = mLight->getExtended<ShadowMapParams>();
  307. // The view dependent shadows don't scale by screen size.
  308. U32 texSize;
  309. if ( isViewDependent() )
  310. texSize = params->texSize;
  311. else
  312. texSize = params->texSize * getMin( 1.0f, mLastScreenSize );
  313. // Apply the shadow texture scale and make
  314. // sure this is a power of 2.
  315. texSize = getNextPow2( texSize * smShadowTexScalar );
  316. // Get the max texture size this card supports and
  317. // scale it down... ensuring the final texSize can
  318. // be scaled up that many times and not go over
  319. // the card maximum.
  320. U32 maxTexSize = GFX->getCardProfiler()->queryProfile( "maxTextureSize", 2048 );
  321. if ( scale > 1 )
  322. maxTexSize >>= ( scale - 1 );
  323. // Never let the shadow texture get smaller than 16x16 as
  324. // it just makes the pool bigger and the fillrate savings
  325. // are less and leass as we get smaller.
  326. texSize = mClamp( texSize, (U32)16, maxTexSize );
  327. // Return it.
  328. return texSize;
  329. }
  330. void LightShadowMap::updatePriority( const SceneRenderState *state, U32 currTimeMs )
  331. {
  332. PROFILE_SCOPE( LightShadowMap_updatePriority );
  333. mLastCull = currTimeMs;
  334. if ( isViewDependent() )
  335. {
  336. mLastScreenSize = 1.0f;
  337. mLastPriority = F32_MAX;
  338. return;
  339. }
  340. U32 timeSinceLastUpdate = currTimeMs - mLastUpdate;
  341. const Point3F &camPt = state->getCameraPosition();
  342. F32 range = mLight->getRange().x;
  343. F32 dist;
  344. if ( mLight->getType() == LightInfo::Spot )
  345. {
  346. // We treat the cone as a cylinder to get the
  347. // approximate projection distance.
  348. Point3F endPt = mLight->getPosition() + ( mLight->getDirection() * range );
  349. Point3F nearPt = MathUtils::mClosestPointOnSegment( mLight->getPosition(), endPt, camPt );
  350. dist = ( camPt - nearPt ).len();
  351. F32 radius = range * mSin( mDegToRad( mLight->getOuterConeAngle() * 0.5f ) );
  352. dist -= radius;
  353. }
  354. else
  355. dist = SphereF( mLight->getPosition(), range ).distanceTo( camPt );
  356. // Get the approximate screen size of the light.
  357. mLastScreenSize = state->projectRadius( dist, range );
  358. mLastScreenSize /= state->getViewport().extent.y;
  359. // Update the priority.
  360. mLastPriority = mPow( mLastScreenSize * 50.0f, 2.0f );
  361. mLastPriority += timeSinceLastUpdate;
  362. mLastPriority *= mLight->getPriority();
  363. }
  364. S32 QSORT_CALLBACK LightShadowMap::cmpPriority( LightShadowMap *const *lsm1, LightShadowMap *const *lsm2 )
  365. {
  366. F32 diff = (*lsm1)->getLastPriority() - (*lsm2)->getLastPriority();
  367. return diff > 0.0f ? -1 : ( diff < 0.0f ? 1 : 0 );
  368. }
  369. void LightShadowMap::_debugRender( SceneRenderState* shadowRenderState )
  370. {
  371. #ifdef TORQUE_DEBUG
  372. // Skip if light does not have debug rendering enabled.
  373. if( !getLightInfo()->isDebugRenderingEnabled() )
  374. return;
  375. DebugDrawer* drawer = DebugDrawer::get();
  376. if( !drawer )
  377. return;
  378. if( smDebugRenderFrustums )
  379. shadowRenderState->getCullingState().debugRenderCullingVolumes();
  380. #endif
  381. }
  382. LightingShaderConstants::LightingShaderConstants()
  383. : mInit( false ),
  384. mShader( NULL ),
  385. mLightParamsSC(NULL),
  386. mLightSpotParamsSC(NULL),
  387. mLightPositionSC(NULL),
  388. mLightDiffuseSC(NULL),
  389. mLightAmbientSC(NULL),
  390. mLightInvRadiusSqSC(NULL),
  391. mLightSpotDirSC(NULL),
  392. mLightSpotAngleSC(NULL),
  393. mLightSpotFalloffSC(NULL),
  394. mShadowMapSC(NULL),
  395. mDynamicShadowMapSC(NULL),
  396. mShadowMapSizeSC(NULL),
  397. mCookieMapSC(NULL),
  398. mRandomDirsConst(NULL),
  399. mShadowSoftnessConst(NULL),
  400. mAtlasXOffsetSC(NULL),
  401. mAtlasYOffsetSC(NULL),
  402. mAtlasScaleSC(NULL),
  403. mFadeStartLength(NULL),
  404. mOverDarkFactorPSSM(NULL),
  405. mTapRotationTexSC(NULL),
  406. mWorldToLightProjSC(NULL),
  407. mViewToLightProjSC(NULL),
  408. mScaleXSC(NULL),
  409. mScaleYSC(NULL),
  410. mOffsetXSC(NULL),
  411. mOffsetYSC(NULL),
  412. mFarPlaneScalePSSM(NULL),
  413. mDynamicWorldToLightProjSC(NULL),
  414. mDynamicViewToLightProjSC(NULL),
  415. mDynamicScaleXSC(NULL),
  416. mDynamicScaleYSC(NULL),
  417. mDynamicOffsetXSC(NULL),
  418. mDynamicOffsetYSC(NULL),
  419. mDynamicFarPlaneScalePSSM(NULL)
  420. {
  421. }
  422. LightingShaderConstants::~LightingShaderConstants()
  423. {
  424. if (mShader.isValid())
  425. {
  426. mShader->getReloadSignal().remove( this, &LightingShaderConstants::_onShaderReload );
  427. mShader = NULL;
  428. }
  429. }
  430. void LightingShaderConstants::init(GFXShader* shader)
  431. {
  432. if (mShader.getPointer() != shader)
  433. {
  434. if (mShader.isValid())
  435. mShader->getReloadSignal().remove( this, &LightingShaderConstants::_onShaderReload );
  436. mShader = shader;
  437. mShader->getReloadSignal().notify( this, &LightingShaderConstants::_onShaderReload );
  438. }
  439. mLightParamsSC = shader->getShaderConstHandle("$lightParams");
  440. mLightSpotParamsSC = shader->getShaderConstHandle("$lightSpotParams");
  441. // NOTE: These are the shader constants used for doing lighting
  442. // during the forward pass. Do not confuse these for the prepass
  443. // lighting constants which are used from AdvancedLightBinManager.
  444. mLightPositionSC = shader->getShaderConstHandle( ShaderGenVars::lightPosition );
  445. mLightDiffuseSC = shader->getShaderConstHandle( ShaderGenVars::lightDiffuse );
  446. mLightAmbientSC = shader->getShaderConstHandle( ShaderGenVars::lightAmbient );
  447. mLightInvRadiusSqSC = shader->getShaderConstHandle( ShaderGenVars::lightInvRadiusSq );
  448. mLightSpotDirSC = shader->getShaderConstHandle( ShaderGenVars::lightSpotDir );
  449. mLightSpotAngleSC = shader->getShaderConstHandle( ShaderGenVars::lightSpotAngle );
  450. mLightSpotFalloffSC = shader->getShaderConstHandle( ShaderGenVars::lightSpotFalloff );
  451. mShadowMapSC = shader->getShaderConstHandle("$shadowMap");
  452. mDynamicShadowMapSC = shader->getShaderConstHandle("$dynamicShadowMap");
  453. mShadowMapSizeSC = shader->getShaderConstHandle("$shadowMapSize");
  454. mCookieMapSC = shader->getShaderConstHandle("$cookieMap");
  455. mShadowSoftnessConst = shader->getShaderConstHandle("$shadowSoftness");
  456. mAtlasXOffsetSC = shader->getShaderConstHandle("$atlasXOffset");
  457. mAtlasYOffsetSC = shader->getShaderConstHandle("$atlasYOffset");
  458. mAtlasScaleSC = shader->getShaderConstHandle("$atlasScale");
  459. mFadeStartLength = shader->getShaderConstHandle("$fadeStartLength");
  460. mOverDarkFactorPSSM = shader->getShaderConstHandle("$overDarkPSSM");
  461. mTapRotationTexSC = shader->getShaderConstHandle( "$gTapRotationTex" );
  462. mWorldToLightProjSC = shader->getShaderConstHandle("$worldToLightProj");
  463. mViewToLightProjSC = shader->getShaderConstHandle("$viewToLightProj");
  464. mScaleXSC = shader->getShaderConstHandle("$scaleX");
  465. mScaleYSC = shader->getShaderConstHandle("$scaleY");
  466. mOffsetXSC = shader->getShaderConstHandle("$offsetX");
  467. mOffsetYSC = shader->getShaderConstHandle("$offsetY");
  468. mFarPlaneScalePSSM = shader->getShaderConstHandle("$farPlaneScalePSSM");
  469. mDynamicWorldToLightProjSC = shader->getShaderConstHandle("$dynamicWorldToLightProj");
  470. mDynamicViewToLightProjSC = shader->getShaderConstHandle("$dynamicViewToLightProj");
  471. mDynamicScaleXSC = shader->getShaderConstHandle("$dynamicScaleX");
  472. mDynamicScaleYSC = shader->getShaderConstHandle("$dynamicScaleY");
  473. mDynamicOffsetXSC = shader->getShaderConstHandle("$dynamicOffsetX");
  474. mDynamicOffsetYSC = shader->getShaderConstHandle("$dynamicOffsetY");
  475. mDynamicFarPlaneScalePSSM = shader->getShaderConstHandle("$dynamicFarPlaneScalePSSM");
  476. mInit = true;
  477. }
  478. void LightingShaderConstants::_onShaderReload()
  479. {
  480. if (mShader.isValid())
  481. init( mShader );
  482. }
  483. MODULE_BEGIN( ShadowMapParams )
  484. MODULE_INIT_BEFORE( LightMapParams )
  485. MODULE_INIT
  486. {
  487. ShadowMapParams::Type = "ShadowMapParams" ;
  488. }
  489. MODULE_END;
  490. LightInfoExType ShadowMapParams::Type( "" );
  491. ShadowMapParams::ShadowMapParams( LightInfo *light )
  492. : mLight( light ),
  493. mShadowMap( NULL ),
  494. mDynamicShadowMap ( NULL ),
  495. isDynamic ( true )
  496. {
  497. attenuationRatio.set( 0.0f, 1.0f, 1.0f );
  498. shadowType = ShadowType_Spot;
  499. overDarkFactor.set(2000.0f, 1000.0f, 500.0f, 100.0f);
  500. numSplits = 4;
  501. logWeight = 0.91f;
  502. texSize = 512;
  503. shadowDistance = 400.0f;
  504. shadowSoftness = 0.15f;
  505. fadeStartDist = 0.0f;
  506. lastSplitTerrainOnly = false;
  507. _validate();
  508. }
  509. ShadowMapParams::~ShadowMapParams()
  510. {
  511. SAFE_DELETE( mShadowMap );
  512. SAFE_DELETE( mDynamicShadowMap );
  513. }
  514. void ShadowMapParams::_validate()
  515. {
  516. switch ( mLight->getType() )
  517. {
  518. case LightInfo::Spot:
  519. shadowType = ShadowType_Spot;
  520. break;
  521. case LightInfo::Vector:
  522. shadowType = ShadowType_PSSM;
  523. break;
  524. case LightInfo::Point:
  525. if ( shadowType < ShadowType_Paraboloid )
  526. shadowType = ShadowType_DualParaboloidSinglePass;
  527. break;
  528. default:
  529. break;
  530. }
  531. // The texture sizes for shadows should always
  532. // be power of 2 in size.
  533. texSize = getNextPow2( texSize );
  534. // The maximum shadow texture size setting we're
  535. // gonna allow... this doesn't use your hardware
  536. // settings as you may be on a lower end system
  537. // than your target machine.
  538. //
  539. // We apply the hardware specific limits during
  540. // shadow rendering.
  541. //
  542. U32 maxTexSize = 4096;
  543. if ( mLight->getType() == LightInfo::Vector )
  544. {
  545. numSplits = mClamp( numSplits, 1, 4 );
  546. // Adjust the shadow texture size for the PSSM
  547. // based on the split count to keep the total
  548. // shadow texture size within 4096.
  549. if ( numSplits == 2 || numSplits == 4 )
  550. maxTexSize = 2048;
  551. if ( numSplits == 3 )
  552. maxTexSize = 1024;
  553. }
  554. else
  555. numSplits = 1;
  556. // Keep it in a valid range... less than 32 is dumb.
  557. texSize = mClamp( texSize, 32, maxTexSize );
  558. }
  559. LightShadowMap* ShadowMapParams::getOrCreateShadowMap(bool _isDynamic)
  560. {
  561. if (_isDynamic && mDynamicShadowMap)
  562. return mDynamicShadowMap;
  563. if (!_isDynamic && mShadowMap)
  564. return mShadowMap;
  565. if ( !mLight->getCastShadows() )
  566. return NULL;
  567. LightShadowMap* newShadowMap = NULL;
  568. switch ( mLight->getType() )
  569. {
  570. case LightInfo::Spot:
  571. newShadowMap = new SingleLightShadowMap( mLight );
  572. break;
  573. case LightInfo::Vector:
  574. newShadowMap = new PSSMLightShadowMap( mLight );
  575. break;
  576. case LightInfo::Point:
  577. if ( shadowType == ShadowType_CubeMap )
  578. newShadowMap = new CubeLightShadowMap( mLight );
  579. else if ( shadowType == ShadowType_Paraboloid )
  580. newShadowMap = new ParaboloidLightShadowMap( mLight );
  581. else
  582. newShadowMap = new DualParaboloidLightShadowMap( mLight );
  583. break;
  584. default:
  585. break;
  586. }
  587. if ( _isDynamic )
  588. {
  589. newShadowMap->setDynamic( true );
  590. mDynamicShadowMap = newShadowMap;
  591. return mDynamicShadowMap;
  592. }
  593. else
  594. {
  595. newShadowMap->setDynamic(false);
  596. mShadowMap = newShadowMap;
  597. return mShadowMap;
  598. }
  599. }
  600. GFXTextureObject* ShadowMapParams::getCookieTex()
  601. {
  602. if ( cookie.isNotEmpty() &&
  603. ( mCookieTex.isNull() ||
  604. cookie != mCookieTex->getPath() ) )
  605. {
  606. mCookieTex.set( cookie,
  607. &GFXDefaultStaticDiffuseProfile,
  608. "ShadowMapParams::getCookieTex()" );
  609. }
  610. else if ( cookie.isEmpty() )
  611. mCookieTex = NULL;
  612. return mCookieTex.getPointer();
  613. }
  614. GFXCubemap* ShadowMapParams::getCookieCubeTex()
  615. {
  616. if ( cookie.isNotEmpty() &&
  617. ( mCookieCubeTex.isNull() ||
  618. cookie != mCookieCubeTex->getPath() ) )
  619. {
  620. mCookieCubeTex.set( cookie );
  621. }
  622. else if ( cookie.isEmpty() )
  623. mCookieCubeTex = NULL;
  624. return mCookieCubeTex.getPointer();
  625. }
  626. void ShadowMapParams::set( const LightInfoEx *ex )
  627. {
  628. // TODO: Do we even need this?
  629. }
  630. void ShadowMapParams::packUpdate( BitStream *stream ) const
  631. {
  632. // HACK: We need to work out proper parameter
  633. // validation when any field changes on the light.
  634. ((ShadowMapParams*)this)->_validate();
  635. stream->writeInt( shadowType, 8 );
  636. mathWrite( *stream, attenuationRatio );
  637. stream->write( texSize );
  638. stream->write( cookie );
  639. stream->write( numSplits );
  640. stream->write( logWeight );
  641. mathWrite(*stream, overDarkFactor);
  642. stream->write( fadeStartDist );
  643. stream->writeFlag( lastSplitTerrainOnly );
  644. stream->write( shadowDistance );
  645. stream->write( shadowSoftness );
  646. }
  647. void ShadowMapParams::unpackUpdate( BitStream *stream )
  648. {
  649. ShadowType newType = (ShadowType)stream->readInt( 8 );
  650. if ( shadowType != newType )
  651. {
  652. // If the shadow type changes delete the shadow
  653. // map so it can be reallocated on the next render.
  654. shadowType = newType;
  655. SAFE_DELETE( mShadowMap );
  656. SAFE_DELETE( mDynamicShadowMap );
  657. }
  658. mathRead( *stream, &attenuationRatio );
  659. stream->read( &texSize );
  660. stream->read( &cookie );
  661. stream->read( &numSplits );
  662. stream->read( &logWeight );
  663. mathRead(*stream, &overDarkFactor);
  664. stream->read( &fadeStartDist );
  665. lastSplitTerrainOnly = stream->readFlag();
  666. stream->read( &shadowDistance );
  667. stream->read( &shadowSoftness );
  668. }