lightShadowMap.cpp 25 KB

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