2
0

lightShadowMap.cpp 24 KB

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