pssmLightShadowMap.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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/pssmLightShadowMap.h"
  24. #include "lighting/common/lightMapParams.h"
  25. #include "console/console.h"
  26. #include "scene/sceneManager.h"
  27. #include "scene/sceneRenderState.h"
  28. #include "lighting/lightManager.h"
  29. #include "gfx/gfxDevice.h"
  30. #include "gfx/gfxTransformSaver.h"
  31. #include "gfx/util/gfxFrustumSaver.h"
  32. #include "renderInstance/renderPassManager.h"
  33. #include "gui/controls/guiBitmapCtrl.h"
  34. #include "lighting/shadowMap/shadowMapManager.h"
  35. #include "materials/shaderData.h"
  36. #include "ts/tsShapeInstance.h"
  37. #include "console/consoleTypes.h"
  38. #include "math/mathUtils.h"
  39. AFTER_MODULE_INIT( Sim )
  40. {
  41. Con::addVariable( "$pref::PSSM::detailAdjustScale",
  42. TypeF32, &PSSMLightShadowMap::smDetailAdjustScale,
  43. "@brief Scales the model LOD when rendering into the PSSM shadow.\n"
  44. "Use this to reduce the draw calls when rendering the shadow by having "
  45. "meshes LOD out nearer to the camera than normal.\n"
  46. "@see $pref::TS::detailAdjust\n"
  47. "@ingroup AdvancedLighting" );
  48. Con::addVariable( "$pref::PSSM::smallestVisiblePixelSize",
  49. TypeF32, &PSSMLightShadowMap::smSmallestVisiblePixelSize,
  50. "@brief The smallest pixel size an object can be and still be rendered into the PSSM shadow.\n"
  51. "Use this to force culling of small objects which contribute little to the final shadow.\n"
  52. "@see $pref::TS::smallestVisiblePixelSize\n"
  53. "@ingroup AdvancedLighting" );
  54. }
  55. F32 PSSMLightShadowMap::smDetailAdjustScale = 0.85f;
  56. F32 PSSMLightShadowMap::smSmallestVisiblePixelSize = 25.0f;
  57. PSSMLightShadowMap::PSSMLightShadowMap( LightInfo *light )
  58. : LightShadowMap( light ),
  59. mNumSplits( 1 ),
  60. mLogWeight(0.91f)
  61. {
  62. for (U32 i = 0; i <= MAX_SPLITS; i++) //% depth distance
  63. mSplitDist[i] = mPow(F32(i/MAX_SPLITS),2.0f);
  64. mIsViewDependent = true;
  65. }
  66. void PSSMLightShadowMap::_setNumSplits( U32 numSplits, U32 texSize )
  67. {
  68. AssertFatal(numSplits > 0 && numSplits <= MAX_SPLITS,
  69. avar("PSSMLightShadowMap::_setNumSplits() - Splits must be between 1 and %d!", MAX_SPLITS));
  70. releaseTextures();
  71. mNumSplits = numSplits;
  72. mTexSize = texSize;
  73. F32 texWidth, texHeight;
  74. // If the split count is less than 4 then do a
  75. // 1xN layout of shadow maps...
  76. if ( mNumSplits < 4 )
  77. {
  78. texHeight = texSize;
  79. texWidth = texSize * mNumSplits;
  80. for ( U32 i = 0; i < 4; i++ )
  81. {
  82. mViewports[i].extent.set(texSize, texSize);
  83. mViewports[i].point.set(texSize*i, 0);
  84. }
  85. }
  86. else
  87. {
  88. // ... with 4 splits do a 2x2.
  89. texWidth = texHeight = texSize * 2;
  90. for ( U32 i = 0; i < 4; i++ )
  91. {
  92. F32 xOff = (i == 1 || i == 3) ? 0.5f : 0.0f;
  93. F32 yOff = (i > 1) ? 0.5f : 0.0f;
  94. mViewports[i].extent.set( texSize, texSize );
  95. mViewports[i].point.set( xOff * texWidth, yOff * texHeight );
  96. }
  97. }
  98. mShadowMapTex.set( texWidth, texHeight,
  99. ShadowMapFormat, &ShadowMapProfile,
  100. "PSSMLightShadowMap" );
  101. }
  102. void PSSMLightShadowMap::_calcSplitPos(const Frustum& currFrustum)
  103. {
  104. const F32 nearDist = 0.01f; // TODO: Should this be adjustable or different?
  105. const F32 farDist = currFrustum.getFarDist();
  106. for ( U32 i = 1; i < mNumSplits; i++ )
  107. {
  108. F32 step = (F32) i / (F32) mNumSplits;
  109. F32 logSplit = nearDist * mPow(farDist / nearDist, step);
  110. F32 linearSplit = nearDist + (farDist - nearDist) * step;
  111. mSplitDist[i] = mLerp( linearSplit, logSplit, mClampF( mLogWeight, 0.0f, 1.0f ) );
  112. }
  113. mSplitDist[0] = nearDist;
  114. mSplitDist[mNumSplits] = farDist;
  115. }
  116. Box3F PSSMLightShadowMap::_calcClipSpaceAABB(const Frustum& f, const MatrixF& transform, F32 farDist)
  117. {
  118. PROFILE_SCOPE(PSSMLightShadowMap_calcClipSpaceAABB);
  119. // Transform frustum corners to light space.
  120. Point3F transformedPoints[8];
  121. const Point3F* frustumPoints = f.getPoints();
  122. for (U32 i = 0; i < 8; i++) {
  123. transformedPoints[i] = frustumPoints[i];
  124. transform.mulP(transformedPoints[i]);
  125. }
  126. // Compute the AABB for the transformed points.
  127. Box3F result;
  128. result.minExtents.set(F32_MAX, F32_MAX, F32_MAX);
  129. result.maxExtents.set(-F32_MAX, -F32_MAX, -F32_MAX);
  130. for (U32 i = 0; i < 8; i++) {
  131. result.minExtents.setMin(transformedPoints[i]);
  132. result.maxExtents.setMax(transformedPoints[i]);
  133. }
  134. // Clamp Z to within near and far distances to avoid over-extension.
  135. result.minExtents.z = getMax(result.minExtents.z, 0.0f); // Z must be non-negative in light space.
  136. result.maxExtents.z = getMin(result.maxExtents.z, farDist);
  137. return result;
  138. }
  139. // This "rounds" the projection matrix to remove subtexel movement during shadow map
  140. // rasterization. This is here to reduce shadow shimmering.
  141. void PSSMLightShadowMap::_roundProjection(const MatrixF& lightMat, const MatrixF& cropMatrix, Point3F &offset, U32 splitNum)
  142. {
  143. // Combine the matrices to transform into light projection space.
  144. MatrixF lightProjection = cropMatrix * lightMat;
  145. // Project origin to screen space.
  146. Point4F origin(0, 0, 0, 1);
  147. lightProjection.mul(origin);
  148. origin /= origin.w;
  149. // Convert to texture space (based on shadow map resolution).
  150. F32 texelWidth = mShadowMapTex->getWidth() / (mNumSplits < 4 ? mNumSplits : 2);
  151. Point2F texelScale(texelWidth * 0.5f, mShadowMapTex->getHeight() * 0.5f);
  152. // Adjust origin to align to nearest texel.
  153. Point2F originTexelSpace(origin.x * texelScale.x, origin.y * texelScale.y);
  154. Point2F roundedOriginTexelSpace(mFloor(originTexelSpace.x + 0.5f), mFloor(originTexelSpace.y + 0.5f));
  155. Point2F texelOffset = (roundedOriginTexelSpace - originTexelSpace) / texelScale;
  156. // Apply the offset back to the projection matrix.
  157. offset.x += texelOffset.x;
  158. offset.y += texelOffset.y;
  159. }
  160. void PSSMLightShadowMap::_adjustScaleAndOffset(Box3F& clipAABB, Point3F& scale, Point3F& offset) {
  161. scale.x = 2.0f / (clipAABB.maxExtents.x - clipAABB.minExtents.x);
  162. scale.y = 2.0f / (clipAABB.maxExtents.y - clipAABB.minExtents.y);
  163. scale.z = 1.0f;
  164. // Center the offset to tightly align the projection.
  165. offset.x = -0.5f * (clipAABB.maxExtents.x + clipAABB.minExtents.x) * scale.x;
  166. offset.y = -0.5f * (clipAABB.maxExtents.y + clipAABB.minExtents.y) * scale.y;
  167. offset.z = 0.0f;
  168. }
  169. void PSSMLightShadowMap::_render( RenderPassManager* renderPass,
  170. const SceneRenderState *diffuseState )
  171. {
  172. PROFILE_SCOPE(PSSMLightShadowMap_render);
  173. const ShadowMapParams *params = mLight->getExtended<ShadowMapParams>();
  174. const LightMapParams *lmParams = mLight->getExtended<LightMapParams>();
  175. const bool bUseLightmappedGeometry = lmParams ? !lmParams->representedInLightmap || lmParams->includeLightmappedGeometryInShadow : true;
  176. const U32 texSize = getBestTexSize( params->numSplits < 4 ? params->numSplits : 2 );
  177. if ( mShadowMapTex.isNull() ||
  178. mNumSplits != params->numSplits ||
  179. mTexSize != texSize )
  180. {
  181. _setNumSplits( params->numSplits, texSize );
  182. mShadowMapDepth = _getDepthTarget( mShadowMapTex->getWidth(), mShadowMapTex->getHeight() );
  183. }
  184. mLogWeight = params->logWeight;
  185. Frustum fullFrustum( diffuseState->getCameraFrustum() );
  186. fullFrustum.cropNearFar(fullFrustum.getNearDist(), params->shadowDistance);
  187. GFXFrustumSaver frustSaver;
  188. GFXTransformSaver saver;
  189. // Set our render target
  190. GFX->pushActiveRenderTarget();
  191. mTarget->attachTexture( GFXTextureTarget::Color0, mShadowMapTex );
  192. mTarget->attachTexture( GFXTextureTarget::DepthStencil, mShadowMapDepth );
  193. GFX->setActiveRenderTarget( mTarget );
  194. GFX->clear( GFXClearStencil | GFXClearZBuffer | GFXClearTarget, ColorI(255,255,255), 0.0f, 0 );
  195. // Calculate our standard light matrices
  196. MatrixF lightMatrix;
  197. calcLightMatrices( lightMatrix, diffuseState->getCameraFrustum() );
  198. lightMatrix.inverse();
  199. MatrixF tempProjMat = GFX->getProjectionMatrix();
  200. tempProjMat.reverseProjection();
  201. MatrixF lightViewProj = tempProjMat * lightMatrix;
  202. // TODO: This is just retrieving the near and far calculated
  203. // in calcLightMatrices... we should make that clear.
  204. F32 pnear, pfar;
  205. GFX->getFrustum( NULL, NULL, NULL, NULL, &pnear, &pfar, NULL );
  206. // Set our view up
  207. GFX->setWorldMatrix(lightMatrix);
  208. MatrixF toLightSpace = lightMatrix; // * invCurrentView;
  209. _calcSplitPos(fullFrustum);
  210. mWorldToLightProj = tempProjMat * toLightSpace;
  211. // Apply the PSSM
  212. const F32 savedSmallestVisible = TSShapeInstance::smSmallestVisiblePixelSize;
  213. const F32 savedDetailAdjust = TSShapeInstance::smDetailAdjust;
  214. TSShapeInstance::smDetailAdjust *= smDetailAdjustScale;
  215. TSShapeInstance::smSmallestVisiblePixelSize = smSmallestVisiblePixelSize;
  216. Vector< Vector<PlaneF> > _extraCull;
  217. _calcPlanesCullForShadowCasters( _extraCull, fullFrustum, mLight->getDirection() );
  218. for (U32 i = 0; i < mNumSplits; i++)
  219. {
  220. GFXTransformSaver splitSaver;
  221. // Calculate a sub-frustum
  222. Frustum subFrustum(fullFrustum);
  223. subFrustum.cropNearFar(mSplitDist[i], mSplitDist[i+1]);
  224. // Calculate our AABB in the light's clip space.
  225. Box3F clipAABB = _calcClipSpaceAABB(subFrustum, lightViewProj, fullFrustum.getFarDist());
  226. // Calculate our crop matrix
  227. Point3F scale;
  228. Point3F offset;
  229. _adjustScaleAndOffset(clipAABB, scale, offset);
  230. MatrixF cropMatrix(true);
  231. cropMatrix.scale(scale);
  232. cropMatrix.setPosition(offset);
  233. _roundProjection(lightMatrix, cropMatrix, offset, i);
  234. cropMatrix.setPosition(offset);
  235. // Save scale/offset for shader computations
  236. mScaleProj[i].set(scale);
  237. mOffsetProj[i].set(offset);
  238. // Adjust the far plane to the max z we got (maybe add a little to deal with split overlap)
  239. bool isOrtho;
  240. {
  241. F32 left, right, bottom, top, nearDist, farDist;
  242. GFX->getFrustum(&left, &right, &bottom, &top, &nearDist, &farDist,&isOrtho);
  243. // BTRTODO: Fix me!
  244. farDist = clipAABB.maxExtents.z;
  245. if (!isOrtho)
  246. GFX->setFrustum(left, right, bottom, top, nearDist, farDist);
  247. else
  248. {
  249. // Calculate a new far plane, add a fudge factor to avoid bringing
  250. // the far plane in too close.
  251. F32 newFar = pfar * clipAABB.maxExtents.z + 1.0f;
  252. mFarPlaneScalePSSM[i] = (pfar - pnear) / (newFar - pnear);
  253. GFX->setOrtho(left, right, bottom, top, pnear, newFar, true);
  254. }
  255. }
  256. // Crop matrix multiply needs to be post-projection.
  257. MatrixF alightProj = GFX->getProjectionMatrix();
  258. alightProj = cropMatrix * alightProj;
  259. // Set our new projection
  260. GFX->setProjectionMatrix(alightProj);
  261. // Render into the quad of the shadow map we are using.
  262. GFX->setViewport(mViewports[i]);
  263. SceneManager* sceneManager = diffuseState->getSceneManager();
  264. // The frustum is currently the full size and has not had
  265. // cropping applied.
  266. //
  267. // We make that adjustment here.
  268. const Frustum& uncroppedFrustum = GFX->getFrustum();
  269. Frustum croppedFrustum;
  270. scale *= 0.5f;
  271. croppedFrustum.set(
  272. isOrtho,
  273. uncroppedFrustum.getNearLeft() / scale.x,
  274. uncroppedFrustum.getNearRight() / scale.x,
  275. uncroppedFrustum.getNearTop() / scale.y,
  276. uncroppedFrustum.getNearBottom() / scale.y,
  277. uncroppedFrustum.getNearDist(),
  278. uncroppedFrustum.getFarDist(),
  279. uncroppedFrustum.getTransform()
  280. );
  281. MatrixF camera = GFX->getWorldMatrix();
  282. camera.inverse();
  283. croppedFrustum.setTransform( camera );
  284. // Setup the scene state and use the diffuse state
  285. // camera position and screen metrics values so that
  286. // lod is done the same as in the diffuse pass.
  287. SceneRenderState shadowRenderState
  288. (
  289. sceneManager,
  290. SPT_Shadow,
  291. SceneCameraState( diffuseState->getViewport(), croppedFrustum,
  292. GFX->getWorldMatrix(), GFX->getProjectionMatrix() ),
  293. renderPass
  294. );
  295. shadowRenderState.getMaterialDelegate().bind( this, &LightShadowMap::getShadowMaterial );
  296. shadowRenderState.renderNonLightmappedMeshes( true );
  297. shadowRenderState.renderLightmappedMeshes( bUseLightmappedGeometry );
  298. shadowRenderState.setDiffuseCameraTransform( diffuseState->getCameraTransform() );
  299. shadowRenderState.setWorldToScreenScale( diffuseState->getWorldToScreenScale() );
  300. PlaneSetF planeSet( _extraCull[i].address(), _extraCull[i].size() );
  301. shadowRenderState.getCullingState().setExtraPlanesCull( planeSet );
  302. U32 objectMask = SHADOW_TYPEMASK;
  303. if ( i == mNumSplits-1 && params->lastSplitTerrainOnly )
  304. objectMask = TerrainObjectType;
  305. sceneManager->renderSceneNoLights( &shadowRenderState, objectMask );
  306. shadowRenderState.getCullingState().clearExtraPlanesCull();
  307. _debugRender( &shadowRenderState );
  308. }
  309. // Restore the original TS lod settings.
  310. TSShapeInstance::smSmallestVisiblePixelSize = savedSmallestVisible;
  311. TSShapeInstance::smDetailAdjust = savedDetailAdjust;
  312. // Release our render target
  313. mTarget->resolve();
  314. GFX->popActiveRenderTarget();
  315. }
  316. void PSSMLightShadowMap::setShaderParameters(GFXShaderConstBuffer* params, LightingShaderConstants* lsc)
  317. {
  318. PROFILE_SCOPE( PSSMLightShadowMap_setShaderParameters );
  319. AssertFatal(mNumSplits > 0 && mNumSplits <= MAX_SPLITS,
  320. avar("PSSMLightShadowMap::_setNumSplits() - Splits must be between 1 and %d!", MAX_SPLITS));
  321. if ( lsc->mTapRotationTexSC->isValid() )
  322. GFX->setTexture( lsc->mTapRotationTexSC->getSamplerRegister(),
  323. SHADOWMGR->getTapRotationTex() );
  324. const ShadowMapParams *p = mLight->getExtended<ShadowMapParams>();
  325. Point4F sx(Point4F::Zero),
  326. sy(Point4F::Zero),
  327. ox(Point4F::Zero),
  328. oy(Point4F::Zero),
  329. aXOff(Point4F::Zero),
  330. aYOff(Point4F::Zero);
  331. for (U32 i = 0; i < mNumSplits; i++)
  332. {
  333. sx[i] = mScaleProj[i].x;
  334. sy[i] = mScaleProj[i].y;
  335. ox[i] = mOffsetProj[i].x;
  336. oy[i] = mOffsetProj[i].y;
  337. }
  338. Point2F shadowMapAtlas;
  339. if (mNumSplits < 4)
  340. {
  341. shadowMapAtlas.x = 1.0f / (F32)mNumSplits;
  342. shadowMapAtlas.y = 1.0f;
  343. // 1xmNumSplits
  344. for (U32 i = 0; i < mNumSplits; i++)
  345. aXOff[i] = (F32)i * shadowMapAtlas.x;
  346. }
  347. else
  348. {
  349. shadowMapAtlas.set(0.5f, 0.5f);
  350. // 2x2
  351. for (U32 i = 0; i < mNumSplits; i++)
  352. {
  353. if (i == 1 || i == 3)
  354. aXOff[i] = 0.5f;
  355. if (i > 1)
  356. aYOff[i] = 0.5f;
  357. }
  358. }
  359. // These values change based on static/dynamic.
  360. params->setSafe(lsc->mScaleXSC, sx);
  361. params->setSafe(lsc->mScaleYSC, sy);
  362. params->setSafe(lsc->mOffsetXSC, ox);
  363. params->setSafe(lsc->mOffsetYSC, oy);
  364. params->setSafe(lsc->mFarPlaneScalePSSM, mFarPlaneScalePSSM);
  365. params->setSafe(lsc->mAtlasXOffsetSC, aXOff);
  366. params->setSafe(lsc->mAtlasYOffsetSC, aYOff);
  367. params->setSafe(lsc->mAtlasScaleSC, shadowMapAtlas);
  368. Point4F lightParams( mLight->getRange().x, p->overDarkFactor.x, 0.0f, 0.0f );
  369. params->setSafe( lsc->mLightParamsSC, lightParams );
  370. Point2F fadeStartLength(p->fadeStartDist, 0.0f);
  371. if (fadeStartLength.x == 0.0f)
  372. {
  373. // By default, lets fade the last half of the last split.
  374. fadeStartLength.x = (mSplitDist[mNumSplits-1] + mSplitDist[mNumSplits]) / 2.0f;
  375. }
  376. fadeStartLength.y = 1.0f / (mSplitDist[mNumSplits] - fadeStartLength.x);
  377. params->setSafe( lsc->mFadeStartLength, fadeStartLength);
  378. params->setSafe( lsc->mOverDarkFactorPSSM, p->overDarkFactor);
  379. // The softness is a factor of the texel size.
  380. params->setSafe( lsc->mShadowSoftnessConst, p->shadowSoftness * ( 1.0f / mTexSize ) );
  381. }
  382. void PSSMLightShadowMap::_calcPlanesCullForShadowCasters(Vector< Vector<PlaneF> > &out, const Frustum &viewFrustum, const Point3F &_ligthDir)
  383. {
  384. #define ENABLE_CULL_ASSERT
  385. PROFILE_SCOPE(PSSMLightShadowMap_render_getCullFrustrum);
  386. Point3F ligthDir = _ligthDir;
  387. PlaneF lightFarPlane, lightNearPlane;
  388. MatrixF lightFarPlaneMat(true);
  389. MatrixF invLightFarPlaneMat(true);
  390. // init data
  391. {
  392. ligthDir.normalize();
  393. Point3F viewDir = viewFrustum.getTransform().getForwardVector();
  394. viewDir.normalize();
  395. const Point3F viewPosition = viewFrustum.getPosition();
  396. const F32 viewDistance = viewFrustum.getBounds().len();
  397. lightNearPlane = PlaneF(viewPosition + (viewDistance * -ligthDir), ligthDir);
  398. const Point3F lightFarPlanePos = viewPosition + (viewDistance * ligthDir);
  399. lightFarPlane = PlaneF(lightFarPlanePos, -ligthDir);
  400. lightFarPlaneMat = MathUtils::createOrientFromDir(-ligthDir);
  401. lightFarPlaneMat.setPosition(lightFarPlanePos);
  402. lightFarPlaneMat.invertTo(&invLightFarPlaneMat);
  403. }
  404. Vector<Point2F> projVertices;
  405. //project all frustum vertices into plane
  406. // all vertices are 2d and local to far plane
  407. projVertices.setSize(8);
  408. for (int i = 0; i < 8; ++i) //
  409. {
  410. const Point3F &point = viewFrustum.getPoints()[i];
  411. #ifdef ENABLE_CULL_ASSERT
  412. AssertFatal( PlaneF::Front == lightNearPlane.whichSide(point), "" );
  413. AssertFatal( PlaneF::Front == lightFarPlane.whichSide(point), "" );
  414. #endif
  415. Point3F localPoint(lightFarPlane.project(point));
  416. invLightFarPlaneMat.mulP(localPoint);
  417. projVertices[i] = Point2F(localPoint.x, localPoint.z);
  418. }
  419. //create hull arround projected proints
  420. Vector<Point2F> hullVerts;
  421. MathUtils::mBuildHull2D(projVertices, hullVerts);
  422. Vector<PlaneF> planes;
  423. planes.push_back(lightNearPlane);
  424. planes.push_back(lightFarPlane);
  425. //build planes
  426. for (int i = 0; i < (hullVerts.size() - 1); ++i)
  427. {
  428. Point2F pos2D = (hullVerts[i] + hullVerts[i + 1]) / 2;
  429. Point3F pos3D(pos2D.x, 0, pos2D.y);
  430. Point3F pos3DA(hullVerts[i].x, 0, hullVerts[i].y);
  431. Point3F pos3DB(hullVerts[i + 1].x, 0, hullVerts[i + 1].y);
  432. // move hull points to 3d space
  433. lightFarPlaneMat.mulP(pos3D);
  434. lightFarPlaneMat.mulP(pos3DA);
  435. lightFarPlaneMat.mulP(pos3DB);
  436. PlaneF plane(pos3D, MathUtils::mTriangleNormal(pos3DB, pos3DA, (pos3DA - ligthDir)));
  437. planes.push_back(plane);
  438. }
  439. //recalculate planes for each splits
  440. for (int split = 0; split < mNumSplits; ++split)
  441. {
  442. Frustum subFrustum(viewFrustum);
  443. subFrustum.cropNearFar(mSplitDist[split], mSplitDist[split + 1]);
  444. subFrustum.setFarDist(getMin(subFrustum.getFarDist()*2.5f, viewFrustum.getFarDist()));
  445. subFrustum.update();
  446. Vector<PlaneF> subPlanes = planes;
  447. for (int planeIdx = 0; planeIdx < subPlanes.size(); ++planeIdx)
  448. {
  449. PlaneF &plane = subPlanes[planeIdx];
  450. F32 minDist = 0;
  451. //calculate near vertex distance
  452. for (int vertexIdx = 0; vertexIdx < 8; ++vertexIdx)
  453. {
  454. Point3F point = subFrustum.getPoints()[vertexIdx];
  455. minDist = getMin(plane.distToPlane(point), minDist);
  456. }
  457. // move plane to near vertex
  458. Point3F newPos = plane.getPosition() + (plane.getNormal() * minDist);
  459. plane = PlaneF(newPos, plane.getNormal());
  460. #ifdef ENABLE_CULL_ASSERT
  461. for(int x = 0; x < 8; ++x)
  462. {
  463. AssertFatal( PlaneF::Back != plane.whichSide( subFrustum.getPoints()[x] ), "");
  464. }
  465. #endif
  466. }
  467. out.push_back(subPlanes);
  468. }
  469. #undef ENABLE_CULL_ASSERT
  470. }