View.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "DebugRenderer.h"
  25. #include "Geometry.h"
  26. #include "GeometryNode.h"
  27. #include "Light.h"
  28. #include "Log.h"
  29. #include "Material.h"
  30. #include "OcclusionBuffer.h"
  31. #include "Octree.h"
  32. #include "OctreeQuery.h"
  33. #include "Pipeline.h"
  34. #include "PixelShader.h"
  35. #include "Profiler.h"
  36. #include "Renderer.h"
  37. #include "Scene.h"
  38. #include "Texture2D.h"
  39. #include "TextureCube.h"
  40. #include "VertexShader.h"
  41. #include "View.h"
  42. #include <algorithm>
  43. Zone View::sDefaultZone;
  44. Light* View::sSplitLights[MAX_LIGHT_SPLITS];
  45. std::vector<GeometryNode*> View::sLitGeometries[MAX_LIGHT_SPLITS];
  46. std::vector<GeometryNode*> View::sShadowCasters[MAX_LIGHT_SPLITS];
  47. static std::vector<VolumeNode*> tempNodes;
  48. static bool compareNodes(const VolumeNode* lhs, const VolumeNode* rhs)
  49. {
  50. return lhs->getSortValue() < rhs->getSortValue();
  51. }
  52. View::View(Pipeline* pipeline) :
  53. mPipeline(pipeline),
  54. mOctree(0),
  55. mCamera(0),
  56. mZone(0),
  57. mRenderTarget(0),
  58. mDepthStencil(0),
  59. mSM3Support(pipeline->getRenderer()->getSM3Support())
  60. {
  61. mFrame.mCamera = 0;
  62. }
  63. View::~View()
  64. {
  65. }
  66. bool View::define(RenderSurface* renderTarget, const Viewport& viewport)
  67. {
  68. if ((!viewport.mScene) || (!viewport.mCamera))
  69. return false;
  70. // If scene is loading asynchronously, it is incomplete and should not be rendered
  71. if (viewport.mScene->isAsyncLoading())
  72. return false;
  73. Octree* octree = viewport.mScene->getExtension<Octree>();
  74. if (!octree)
  75. return false;
  76. Renderer* renderer = mPipeline->getRenderer();
  77. // In deferred mode, check for the render texture being too large
  78. if ((renderer->getRenderMode() != RENDER_FORWARD) && (renderTarget))
  79. {
  80. if ((renderTarget->getWidth() > renderer->getWidth()) || (renderTarget->getHeight() > renderer->getHeight()))
  81. {
  82. // Display message only once per rendertarget, do not spam each frame
  83. static std::set<RenderSurface*> errorDisplayed;
  84. if (errorDisplayed.find(renderTarget) == errorDisplayed.end())
  85. {
  86. errorDisplayed.insert(renderTarget);
  87. LOGERROR("Render texture is larger than the G-buffer, can not render");
  88. }
  89. return false;
  90. }
  91. }
  92. mOctree = octree;
  93. mCamera = viewport.mCamera;
  94. mRenderTarget = renderTarget;
  95. if (renderTarget)
  96. mDepthStencil = renderTarget->getLinkedDepthBuffer();
  97. else
  98. mDepthStencil = 0;
  99. mZone = &sDefaultZone;
  100. // Validate the rect and calculate size. If zero rect, use whole render target size
  101. int rtWidth = renderTarget ? renderTarget->getWidth() : renderer->getWidth();
  102. int rtHeight = renderTarget ? renderTarget->getHeight() : renderer->getHeight();
  103. if (viewport.mRect != IntRect::sZero)
  104. {
  105. mScreenRect.mLeft = clamp(viewport.mRect.mLeft, 0, rtWidth - 1);
  106. mScreenRect.mTop = clamp(viewport.mRect.mTop, 0, rtHeight - 1);
  107. mScreenRect.mRight = clamp(viewport.mRect.mRight, mScreenRect.mLeft + 1, rtWidth);
  108. mScreenRect.mBottom = clamp(viewport.mRect.mBottom, mScreenRect.mTop + 1, rtHeight);
  109. }
  110. else
  111. mScreenRect = IntRect(0, 0, rtWidth, rtHeight);
  112. mWidth = mScreenRect.mRight - mScreenRect.mLeft;
  113. mHeight = mScreenRect.mBottom - mScreenRect.mTop;
  114. // Set possible quality overrides from the camera
  115. mDrawShadows = mPipeline->getDrawShadows() && (mCamera->getDrawShadowsOverride());
  116. mLightDetailLevel = min(mPipeline->getLightDetailLevel(), mCamera->getLightDetailLevelOverride());
  117. mMaterialQuality = min(mPipeline->getMaterialQuality(), mCamera->getMaterialQualityOverride());
  118. mMaxOccluderTriangles = min(mPipeline->getMaxOccluderTriangles(), mCamera->getMaxOccluderTrianglesOverride());
  119. // Clear light scissor cache, geometry, light, occluder & batch lists
  120. mLightScissorCache.clear();
  121. mGeometries.clear();
  122. mGeometryDepthBounds.clear();
  123. mLights.clear();
  124. mOccluders.clear();
  125. mShadowOccluders.clear();
  126. mGBufferQueue.clear();
  127. mNegativeLightQueue.clear();
  128. mNoShadowLightQueue.clear();
  129. mAmbientQueue.clear();
  130. mNegativeQueue.clear();
  131. mForwardQueue.clear();
  132. mPostOpaqueQueue.clear();
  133. mTransparentQueue.clear();
  134. mLightQueues.clear();
  135. return true;
  136. }
  137. void View::update(const FrameInfo& frame)
  138. {
  139. if ((!mCamera) || (!mOctree))
  140. return;
  141. mFrame.mCamera = mCamera;
  142. mFrame.mTimeStep = frame.mTimeStep;
  143. mFrame.mFrameNumber = frame.mFrameNumber;
  144. // Set automatic aspect ratio if required
  145. if (mCamera->getAutoAspectRatio())
  146. mCamera->setAspectRatio((float)(mScreenRect.mRight - mScreenRect.mLeft) / (float)(mScreenRect.mBottom - mScreenRect.mTop));
  147. getNodes();
  148. if (mPipeline->getRenderer()->getRenderMode() != RENDER_FORWARD)
  149. getBatchesDeferred();
  150. else
  151. getBatchesForward();
  152. }
  153. void View::render()
  154. {
  155. if ((!mOctree) || (!mCamera))
  156. return;
  157. Renderer* renderer = mPipeline->getRenderer();
  158. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  159. // again to ensure the correct projection will be used
  160. if (mCamera->getAutoAspectRatio())
  161. mCamera->setAspectRatio((float)(mScreenRect.mRight - mScreenRect.mLeft) / (float)(mScreenRect.mBottom - mScreenRect.mTop));
  162. // Set the "view texture" to ensure the rendertarget will not be bound as a texture during G-buffer rendering
  163. if (mRenderTarget)
  164. renderer->setViewTexture(mRenderTarget->getParentTexture());
  165. else
  166. renderer->setViewTexture(0);
  167. // Set per-view shader parameters
  168. float fogStart = mZone->getFogStart();
  169. float fogEnd = mZone->getFogEnd();
  170. float fogRange = max(fogEnd - fogStart, M_EPSILON);
  171. float farClip = mCamera->getFarClip();
  172. float nearClip = mCamera->getNearClip();
  173. Vector4 fogParams(fogStart / farClip, fogEnd / farClip, 1.0f / (fogRange / farClip), 0.0f);
  174. Vector4 elapsedTime(mPipeline->getElapsedTime(), 0.0f, 0.0f, 0.0f);
  175. Vector4 depthReconstruct = Vector4::sZero;
  176. // Non-hardware depth & orthographic modes use linear depth, else reconstruct from z/w
  177. if ((!mCamera->isOrthographic()) && (renderer->getHardwareDepthSupport()))
  178. {
  179. depthReconstruct.mX = farClip / (farClip - nearClip);
  180. depthReconstruct.mY = -nearClip / (farClip - nearClip);
  181. }
  182. renderer->setVertexShaderConstant(getVSRegister(VSP_AMBIENTCOLOR), mZone->getAmbientColor());
  183. renderer->setVertexShaderConstant(getVSRegister(VSP_ELAPSEDTIME), elapsedTime);
  184. renderer->setPixelShaderConstant(getPSRegister(PSP_AMBIENTCOLOR), mZone->getAmbientColor());
  185. renderer->setPixelShaderConstant(getPSRegister(PSP_DEPTHRECONSTRUCT), depthReconstruct);
  186. renderer->setPixelShaderConstant(getPSRegister(PSP_ELAPSEDTIME), elapsedTime);
  187. renderer->setPixelShaderConstant(getPSRegister(PSP_FOGCOLOR), mZone->getFogColor());
  188. renderer->setPixelShaderConstant(getPSRegister(PSP_FOGPARAMS), fogParams);
  189. if (mPipeline->getRenderer()->getRenderMode() != RENDER_FORWARD)
  190. renderBatchesDeferred();
  191. else
  192. renderBatchesForward();
  193. // If this is a main view, draw the associated debug geometry
  194. if (!mRenderTarget)
  195. {
  196. Scene* scene = mOctree->getScene();
  197. if (scene)
  198. {
  199. DebugRenderer* debug = mOctree->getScene()->getExtension<DebugRenderer>();
  200. if (debug)
  201. debug->render(mPipeline, mCamera);
  202. }
  203. }
  204. // "Forget" the camera, octree and zone after rendering
  205. mCamera = 0;
  206. mOctree = 0;
  207. mZone = 0;
  208. mFrame.mCamera = 0;
  209. }
  210. void View::getNodes()
  211. {
  212. PROFILE(View_GetNodes);
  213. Renderer* renderer = mPipeline->getRenderer();
  214. // Get zones & find the zone camera is in
  215. static std::vector<Zone*> zones;
  216. PointOctreeQuery query(reinterpret_cast<std::vector<VolumeNode*>& >(zones), mCamera->getWorldPosition(), NODE_ZONE);
  217. mOctree->getNodes(query);
  218. int highestZonePriority = M_MIN_INT;
  219. const Vector3& cameraPos = mCamera->getWorldPosition();
  220. for (unsigned i = 0; i < zones.size(); ++i)
  221. {
  222. Zone* zone = zones[i];
  223. if ((zone->isInside(cameraPos)) && (zone->getPriority() > highestZonePriority))
  224. {
  225. mZone = zone;
  226. highestZonePriority = zone->getPriority();
  227. }
  228. }
  229. // If occlusion in use, get & render the occluders, then build the depth buffer hierarchy
  230. bool useOcclusion = false;
  231. OcclusionBuffer* buffer = 0;
  232. if (mMaxOccluderTriangles > 0)
  233. {
  234. FrustumOctreeQuery query(reinterpret_cast<std::vector<VolumeNode*>& >(mOccluders), mCamera->getFrustum(),
  235. NODE_GEOMETRY, true, false);
  236. mOctree->getNodes(query);
  237. updateOccluders(mOccluders, *mCamera);
  238. if (mOccluders.size())
  239. {
  240. buffer = mPipeline->getOrCreateOcclusionBuffer(*mCamera, mMaxOccluderTriangles);
  241. drawOccluders(buffer, mOccluders);
  242. buffer->buildDepthHierarchy();
  243. useOcclusion = true;
  244. }
  245. }
  246. if (!useOcclusion)
  247. {
  248. // Get geometries & lights without occlusion
  249. FrustumOctreeQuery query(tempNodes, mCamera->getFrustum(), NODE_GEOMETRY | NODE_LIGHT);
  250. mOctree->getNodes(query);
  251. }
  252. else
  253. {
  254. // Get geometries & lights using occlusion
  255. OccludedFrustumOctreeQuery query(tempNodes, mCamera->getFrustum(), buffer, NODE_GEOMETRY | NODE_LIGHT);
  256. mOctree->getNodes(query);
  257. }
  258. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  259. mSceneBox.mMin = mSceneBox.mMax = Vector3::sZero;
  260. mSceneBox.mDefined = false;
  261. mSceneViewBox.mMin = mSceneViewBox.mMax = Vector3::sZero;
  262. mSceneViewBox.mDefined = false;
  263. const Matrix4x3& view = mCamera->getInverseWorldTransform();
  264. unsigned cameraViewMask = mCamera->getViewMask();
  265. for (unsigned i = 0; i < tempNodes.size(); ++i)
  266. {
  267. VolumeNode* node = tempNodes[i];
  268. // Check view mask
  269. if (!(cameraViewMask & node->getViewMask()))
  270. continue;
  271. node->updateDistance(mFrame);
  272. // If draw distance non-zero, check it
  273. float maxDistance = node->getDrawDistance();
  274. if ((maxDistance != 0.0f) && (node->getDistance() > maxDistance))
  275. continue;
  276. unsigned flags = node->getNodeFlags();
  277. if (flags & NODE_GEOMETRY)
  278. {
  279. GeometryNode* geom = static_cast<GeometryNode*>(node);
  280. geom->markInView(mFrame);
  281. geom->updateGeometry(mFrame, renderer);
  282. // Expand the scene bounding boxes
  283. const BoundingBox& geomBox = geom->getWorldBoundingBox();
  284. BoundingBox geomViewBox = geomBox.getTransformed(view);
  285. mSceneBox.merge(geomBox);
  286. mSceneViewBox.merge(geomViewBox);
  287. // Store depth info to speed up split directional light queries
  288. GeometryDepthBounds bounds;
  289. bounds.mMin = geomViewBox.mMin.mZ;
  290. bounds.mMax = geomViewBox.mMax.mZ;
  291. mGeometryDepthBounds.push_back(bounds);
  292. mGeometries.push_back(geom);
  293. }
  294. else if (flags & NODE_LIGHT)
  295. {
  296. Light* light = static_cast<Light*>(node);
  297. // Skip if detail level does not include this light
  298. if (light->getDetailLevel() > mLightDetailLevel)
  299. continue;
  300. // Skip if light is culled by the zone
  301. if (!(light->getLightMask() & mZone->getLightMask()))
  302. continue;
  303. light->markInView(mFrame);
  304. mLights.push_back(light);
  305. }
  306. }
  307. }
  308. void View::clearLastParameterSources()
  309. {
  310. VertexShader::clearLastParameterSources();
  311. PixelShader::clearLastParameterSources();
  312. }
  313. void View::updateOccluders(std::vector<GeometryNode*>& occluders, Camera& camera)
  314. {
  315. float occluderSizeThreshold = mPipeline->getOccluderSizeThreshold();
  316. float halfViewSize = camera.getHalfViewSize();
  317. float invOrthoSize = 1.0f / camera.getOrthoSize();
  318. Vector3 cameraPos = camera.getWorldPosition();
  319. unsigned cameraViewMask = camera.getViewMask();
  320. for (unsigned i = 0; i < occluders.size(); ++i)
  321. {
  322. GeometryNode* node = occluders[i];
  323. node->updateDistance(mFrame);
  324. bool erase = false;
  325. // Check view mask
  326. if (!(cameraViewMask & node->getViewMask()))
  327. erase = true;
  328. // Check occluder's draw distance (in main camera view)
  329. float maxDistance = node->getDrawDistance();
  330. if ((maxDistance != 0.0f) && (node->getDistance() > maxDistance))
  331. erase = true;
  332. // Check that occluder is big enough on the screen
  333. const BoundingBox& box = node->getWorldBoundingBox();
  334. float diagonal = (box.mMax - box.mMin).getLengthFast();
  335. float compare;
  336. if (!camera.isOrthographic())
  337. compare = diagonal * halfViewSize / node->getDistance();
  338. else
  339. compare = diagonal * invOrthoSize;
  340. if (compare < occluderSizeThreshold)
  341. erase = true;
  342. if (!erase)
  343. {
  344. unsigned totalTriangles = 0;
  345. unsigned batches = node->getNumBatches();
  346. for (unsigned j = 0; j < batches; ++j)
  347. {
  348. Geometry* geom = node->getBatchGeometry(j);
  349. if (geom)
  350. totalTriangles += geom->getIndexCount() / 3;
  351. }
  352. // Store squared distance from occlusion camera multiplied by amount of triangles as a sorting key
  353. // (best occluders are near and have few triangles)
  354. node->setSortValue((node->getWorldPosition() - cameraPos).getLengthSquared() * totalTriangles);
  355. }
  356. else
  357. {
  358. occluders.erase(occluders.begin() + i);
  359. --i;
  360. }
  361. }
  362. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  363. if (occluders.size())
  364. std::sort(occluders.begin(), occluders.end(), compareNodes);
  365. }
  366. void View::drawOccluders(OcclusionBuffer* buffer, const std::vector<GeometryNode*>& occluders)
  367. {
  368. Renderer* renderer = mPipeline->getRenderer();
  369. for (unsigned i = 0; i < occluders.size(); ++i)
  370. {
  371. GeometryNode* node = occluders[i];
  372. if (!node->isOccluder())
  373. continue;
  374. if (i > 0)
  375. {
  376. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  377. if (!buffer->isVisible(node->getWorldBoundingBox()))
  378. continue;
  379. }
  380. node->updateGeometry(mFrame, renderer);
  381. // Check for running out of triangles
  382. if (!node->drawOcclusion(buffer))
  383. return;
  384. }
  385. }
  386. unsigned View::processLight(Light* light)
  387. {
  388. unsigned litGeometries = 0;
  389. unsigned shadowCasters = 0;
  390. unsigned splitLights;
  391. // Check if light detail level allows the light to be shadowed. Also negative lights are never shadowed
  392. bool isShadowed = (mDrawShadows) && (light->getCastShadows()) && (!light->isNegative()) && (light->getShadowDetailLevel() <= mLightDetailLevel);
  393. // If shadow distance non-zero, check it
  394. if ((isShadowed) && (light->getShadowDistance() > 0.0f) && (light->getDistance() > light->getShadowDistance()))
  395. isShadowed = false;
  396. // If light has no ramp textures defined, set defaults
  397. if (!light->getRampTexture())
  398. light->setRampTexture(mPipeline->getDefaultLightRamp());
  399. if (!light->getSpotTexture())
  400. light->setSpotTexture(mPipeline->getDefaultLightSpot());
  401. // Split the light if necessary
  402. if (isShadowed)
  403. splitLights = splitLight(light);
  404. else
  405. {
  406. // No splitting, use the original light
  407. sSplitLights[0] = light;
  408. splitLights = 1;
  409. }
  410. // For a shadowed directional light, get occluders once using the whole (non-split) light frustum
  411. bool useOcclusion = false;
  412. OcclusionBuffer* buffer = 0;
  413. if ((mMaxOccluderTriangles > 0) && (isShadowed) && (light->getLightType() == LIGHT_DIRECTIONAL))
  414. {
  415. // This shadow camera is never used for actually querying shadow casters, just occluders
  416. setupShadowCamera(light, true);
  417. Camera& shadowCamera = light->getShadowCamera();
  418. // Get occluders, which must be shadow-casting themselves
  419. FrustumOctreeQuery query(reinterpret_cast<std::vector<VolumeNode*>& >(mShadowOccluders), shadowCamera.getFrustum(),
  420. NODE_GEOMETRY, true, true);
  421. mOctree->getNodes(query);
  422. updateOccluders(mShadowOccluders, shadowCamera);
  423. if (mShadowOccluders.size())
  424. {
  425. // Shadow viewport is rectangular and consumes more CPU fillrate, so halve size
  426. buffer = mPipeline->getOrCreateOcclusionBuffer(shadowCamera, mMaxOccluderTriangles, true);
  427. drawOccluders(buffer, mShadowOccluders);
  428. buffer->buildDepthHierarchy();
  429. useOcclusion = true;
  430. }
  431. }
  432. // Process each split for shadow camera update, lit geometries, and shadow casters
  433. for (unsigned i = 0; i < splitLights; ++i)
  434. {
  435. sLitGeometries[i].clear();
  436. sShadowCasters[i].clear();
  437. }
  438. for (unsigned i = 0; i < splitLights; ++i)
  439. {
  440. LightType type = sSplitLights[i]->getLightType();
  441. bool isSplitShadowed = (isShadowed) && (sSplitLights[i]->getCastShadows());
  442. // If shadow casting, choose the shadow map & update shadow camera
  443. if (isSplitShadowed)
  444. {
  445. sSplitLights[i]->setShadowMap(mPipeline->getShadowMap(sSplitLights[i]->getShadowResolution()));
  446. setupShadowCamera(sSplitLights[i]);
  447. }
  448. else
  449. sSplitLights[i]->setShadowMap(0);
  450. BoundingBox geometryBox;
  451. BoundingBox shadowCasterBox;
  452. switch (type)
  453. {
  454. case LIGHT_DIRECTIONAL:
  455. // Loop through visible geometries and check if they belong to this split
  456. {
  457. float nearSplit = sSplitLights[i]->getNearSplit() - sSplitLights[i]->getNearFadeRange();
  458. float farSplit = sSplitLights[i]->getFarSplit();
  459. // If split extends to the whole visible frustum, no depth check necessary
  460. bool optimize = (nearSplit <= mCamera->getNearClip()) && (farSplit >= mCamera->getFarClip());
  461. // If whole visible scene is outside the split, can reject trivially
  462. if ((mSceneViewBox.mMin.mZ > farSplit) || (mSceneViewBox.mMax.mZ < nearSplit))
  463. {
  464. sSplitLights[i]->setShadowMap(0);
  465. continue;
  466. }
  467. const Matrix4x3& lightView = sSplitLights[i]->getShadowCamera().getInverseWorldTransform();
  468. bool generateBoxes = (isSplitShadowed) && (sSplitLights[i]->getShadowFocus().mFocus);
  469. unsigned lightMask = sSplitLights[i]->getLightMask();
  470. if (!optimize)
  471. {
  472. for (unsigned j = 0; j < mGeometries.size(); ++j)
  473. {
  474. const GeometryDepthBounds& bounds = mGeometryDepthBounds[j];
  475. if ((bounds.mMin <= farSplit) && (bounds.mMax >= nearSplit) && (lightMask & mGeometries[j]->getLightMask()))
  476. {
  477. sLitGeometries[i].push_back(mGeometries[j]);
  478. if (generateBoxes)
  479. geometryBox.merge(mGeometries[j]->getWorldBoundingBox().getTransformed(lightView));
  480. }
  481. }
  482. }
  483. else
  484. {
  485. for (unsigned j = 0; j < mGeometries.size(); ++j)
  486. {
  487. if (lightMask & mGeometries[j]->getLightMask())
  488. {
  489. sLitGeometries[i].push_back(mGeometries[j]);
  490. if (generateBoxes)
  491. geometryBox.merge(mGeometries[j]->getWorldBoundingBox().getTransformed(lightView));
  492. }
  493. }
  494. }
  495. }
  496. // Then get shadow casters by shadow camera frustum query. Use occlusion because of potentially many geometries
  497. if ((isSplitShadowed) && (sLitGeometries[i].size()))
  498. {
  499. Camera& shadowCamera = sSplitLights[i]->getShadowCamera();
  500. if (!useOcclusion)
  501. {
  502. // Get potential shadow casters without occlusion
  503. FrustumOctreeQuery query(tempNodes, shadowCamera.getFrustum(), NODE_GEOMETRY);
  504. mOctree->getNodes(query);
  505. }
  506. else
  507. {
  508. // Get potential shadow casters with occlusion
  509. OccludedFrustumOctreeQuery query(tempNodes, shadowCamera.getFrustum(), buffer,
  510. NODE_GEOMETRY);
  511. mOctree->getNodes(query);
  512. }
  513. processLightQuery(i, tempNodes, geometryBox, shadowCasterBox, false, isSplitShadowed);
  514. }
  515. break;
  516. case LIGHT_POINT:
  517. {
  518. SphereOctreeQuery query(tempNodes, Sphere(sSplitLights[i]->getWorldPosition(), sSplitLights[i]->getRange()),
  519. NODE_GEOMETRY);
  520. mOctree->getNodes(query);
  521. processLightQuery(i, tempNodes, geometryBox, shadowCasterBox, true, false);
  522. }
  523. break;
  524. case LIGHT_SPOT:
  525. case LIGHT_SPLITPOINT:
  526. {
  527. FrustumOctreeQuery query(tempNodes, sSplitLights[i]->getFrustum(), NODE_GEOMETRY);
  528. mOctree->getNodes(query);
  529. processLightQuery(i, tempNodes, geometryBox, shadowCasterBox, true, isSplitShadowed);
  530. }
  531. break;
  532. }
  533. // Optimization: if a particular split has no shadow casters, render as unshadowed
  534. if (!sShadowCasters[i].size())
  535. sSplitLights[i]->setShadowMap(0);
  536. // Focus shadow camera as applicable
  537. if (sSplitLights[i]->getShadowMap())
  538. {
  539. if (sSplitLights[i]->getShadowFocus().mFocus)
  540. focusShadowCamera(sSplitLights[i], geometryBox, shadowCasterBox);
  541. // Set a zoom factor to ensure that we do not render to the shadow map border
  542. // (clamp addressing is necessary because border mode /w hardware shadow maps is not supported by all GPUs)
  543. Camera& shadowCamera = sSplitLights[i]->getShadowCamera();
  544. Texture2D* shadowMap = sSplitLights[i]->getShadowMap();
  545. if (shadowCamera.getZoom() >= 1.0f)
  546. shadowCamera.setZoom(shadowCamera.getZoom() * ((float)(shadowMap->getWidth() - 2) / (float)shadowMap->getWidth()));
  547. }
  548. // Update count of total lit geometries & shadow casters
  549. litGeometries += sLitGeometries[i].size();
  550. shadowCasters += sShadowCasters[i].size();
  551. }
  552. // If no lit geometries at all, no need to process further
  553. if (!litGeometries)
  554. splitLights = 0;
  555. // If no shadow casters at all, concatenate lit geometries into one & return the original light
  556. else if (!shadowCasters)
  557. {
  558. if (splitLights > 1)
  559. {
  560. // Make sure there are no duplicates
  561. static std::set<GeometryNode*> allLitGeometries;
  562. allLitGeometries.clear();
  563. for (unsigned i = 0; i < splitLights; ++i)
  564. {
  565. for (std::vector<GeometryNode*>::iterator j = sLitGeometries[i].begin(); j != sLitGeometries[i].end(); ++j)
  566. allLitGeometries.insert(*j);
  567. }
  568. sLitGeometries[0].resize(allLitGeometries.size());
  569. unsigned index = 0;
  570. for (std::set<GeometryNode*>::iterator i = allLitGeometries.begin(); i != allLitGeometries.end(); ++i)
  571. sLitGeometries[0][index++] = *i;
  572. }
  573. sSplitLights[0] = light;
  574. sSplitLights[0]->setShadowMap(0);
  575. splitLights = 1;
  576. }
  577. return splitLights;
  578. }
  579. void View::processLightQuery(unsigned splitIndex, const std::vector<VolumeNode*>& result, BoundingBox& geometryBox,
  580. BoundingBox& shadowCasterBox, bool getLitGeometries, bool getShadowCasters)
  581. {
  582. Renderer* renderer = mPipeline->getRenderer();
  583. Light* light = sSplitLights[splitIndex];
  584. // Transform scene frustum into shadow camera's view space for shadow caster visibility check
  585. Camera& shadowCamera = light->getShadowCamera();
  586. const Matrix4x3& lightView = shadowCamera.getInverseWorldTransform();
  587. const Matrix4& lightProj = shadowCamera.getProjection();
  588. // For point & spot lights, we can use the whole scene frustum. For directional lights, use the
  589. // intersection of the scene frustum and the split frustum, so that shadow casters do not get
  590. // rendered into unnecessary splits
  591. Frustum lightViewFrustum;
  592. if (light->getLightType() != LIGHT_DIRECTIONAL)
  593. {
  594. lightViewFrustum = mCamera->getSplitFrustum(
  595. mSceneViewBox.mMin.mZ, mSceneViewBox.mMax.mZ).getTransformed(lightView);
  596. }
  597. else
  598. {
  599. lightViewFrustum = mCamera->getSplitFrustum(
  600. max(mSceneViewBox.mMin.mZ, light->getNearSplit() - light->getNearFadeRange()),
  601. min(mSceneViewBox.mMax.mZ, light->getFarSplit())
  602. ).getTransformed(lightView);
  603. }
  604. BoundingBox lightViewFrustumBox;
  605. lightViewFrustumBox.define(lightViewFrustum);
  606. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  607. if (lightViewFrustum.mVertices[0] == lightViewFrustum.mVertices[4])
  608. getShadowCasters = false;
  609. // Generate merged light view geometry/shadowcaster bounding boxes box for shadow focusing
  610. bool mergeBoxes = (light->getLightType() != LIGHT_SPLITPOINT) && (light->getShadowMap()) && (light->getShadowFocus().mFocus);
  611. bool projectBoxes = !shadowCamera.isOrthographic();
  612. BoundingBox lightViewBox;
  613. BoundingBox lightProjBox;
  614. unsigned lightMask = light->getLightMask();
  615. for (unsigned i = 0; i < result.size(); ++i)
  616. {
  617. GeometryNode* geom = static_cast<GeometryNode*>(result[i]);
  618. geom->updateDistance(mFrame);
  619. bool boxGenerated = false;
  620. // If draw distance non-zero, check it
  621. float maxDistance = geom->getDrawDistance();
  622. if ((maxDistance != 0.0f) && (geom->getDistance() > maxDistance))
  623. continue;
  624. // Check light mask
  625. if (!(lightMask & geom->getLightMask()))
  626. continue;
  627. // Get lit geometry only if inside main camera frustum this frame
  628. if (getLitGeometries)
  629. {
  630. if (geom->isInView(mFrame))
  631. {
  632. if (mergeBoxes)
  633. {
  634. // Transform bounding box into light view space, and to projection space if needed
  635. lightViewBox = geom->getWorldBoundingBox().getTransformed(lightView);
  636. if (!projectBoxes)
  637. geometryBox.merge(lightViewBox);
  638. else
  639. {
  640. lightProjBox = lightViewBox.getProjected(lightProj);
  641. geometryBox.merge(lightProjBox);
  642. }
  643. boxGenerated = true;
  644. }
  645. sLitGeometries[splitIndex].push_back(geom);
  646. }
  647. }
  648. // Shadow caster need not be inside main camera frustum: in that case we try to detect whether
  649. // the shadow projection intersects the view
  650. if ((getShadowCasters) && (geom->getCastShadows()))
  651. {
  652. // If shadow distance non-zero, check it
  653. float maxShadowDistance = geom->getShadowDistance();
  654. if ((maxShadowDistance != 0.0f) && (geom->getDistance() > maxShadowDistance))
  655. continue;
  656. // Check if any of the geometry's materials casts shadows
  657. unsigned numMat = geom->getNumBatches();
  658. for (unsigned i = 0; i < numMat; ++i)
  659. {
  660. Material* material = geom->getBatchMaterial(i);
  661. // Note: if material is null, default will be used, and it casts shadows
  662. if ((!material) || (material->getCastShadows()))
  663. {
  664. if (!boxGenerated)
  665. lightViewBox = geom->getWorldBoundingBox().getTransformed(lightView);
  666. if (isShadowCasterVisible(geom, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  667. {
  668. if (mergeBoxes)
  669. {
  670. if (!projectBoxes)
  671. shadowCasterBox.merge(lightViewBox);
  672. else
  673. {
  674. if (!boxGenerated)
  675. lightProjBox = lightViewBox.getProjected(lightProj);
  676. shadowCasterBox.merge(lightProjBox);
  677. }
  678. }
  679. // Update geometry now if not updated yet
  680. if (!geom->isInView(mFrame))
  681. {
  682. geom->markInShadowView(mFrame);
  683. geom->updateGeometry(mFrame, renderer);
  684. }
  685. sShadowCasters[splitIndex].push_back(geom);
  686. }
  687. break;
  688. }
  689. }
  690. }
  691. }
  692. }
  693. bool View::isShadowCasterVisible(GeometryNode* geom, BoundingBox lightViewBox, const Camera& shadowCamera,
  694. const Matrix4x3& lightView, const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  695. {
  696. // If shadow caster is also an occluder, must let it be visible, because it has potentially already culled
  697. // away other shadow casters (could also check the actual shadow occluder vector, but that would be slower)
  698. if (geom->isOccluder())
  699. return true;
  700. if (shadowCamera.isOrthographic())
  701. {
  702. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  703. lightViewBox.mMax.mZ = max(lightViewBox.mMax.mZ,lightViewFrustumBox.mMax.mZ);
  704. return lightViewFrustum.isInsideFast(lightViewBox) != OUTSIDE;
  705. }
  706. else
  707. {
  708. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  709. if (geom->isInView(mFrame))
  710. return true;
  711. // For perspective lights, extrusion direction depends on the position of the shadow caster
  712. Vector3 center = lightViewBox.getCenter();
  713. Ray extrusionRay(center, center.getNormalized());
  714. float extrusionDistance = shadowCamera.getFarClip();
  715. float originalDistance = clamp(center.getLengthFast(), M_EPSILON, extrusionDistance);
  716. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  717. float sizeFactor = extrusionDistance / originalDistance;
  718. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  719. // than necessary, so the test will be conservative
  720. Vector3 newCenter = extrusionDistance * extrusionRay.mDirection;
  721. Vector3 newHalfSize = lightViewBox.getSize() * sizeFactor * 0.5f;
  722. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  723. lightViewBox.merge(extrudedBox);
  724. return lightViewFrustum.isInsideFast(lightViewBox) != OUTSIDE;
  725. }
  726. }
  727. void View::setupShadowCamera(Light* light, bool shadowOcclusion)
  728. {
  729. Camera& shadowCamera = light->getShadowCamera();
  730. const FocusParameters& parameters = light->getShadowFocus();
  731. // Reset zoom
  732. shadowCamera.setZoom(1.0f);
  733. switch(light->getLightType())
  734. {
  735. case LIGHT_DIRECTIONAL:
  736. {
  737. float extrusionDistance = mCamera->getFarClip();
  738. // Calculate initial position & rotation
  739. Vector3 lightWorldDirection = light->getWorldRotation() * light->getDirection();
  740. Vector3 pos = mCamera->getWorldPosition() - extrusionDistance * lightWorldDirection;
  741. Quaternion rot(Vector3::sForward, lightWorldDirection);
  742. shadowCamera.setPosition(pos);
  743. shadowCamera.setRotation(rot);
  744. // Calculate main camera shadowed frustum in light's view space
  745. float sceneMaxZ = mCamera->getFarClip();
  746. // When shadow focusing is enabled, use the scene far Z to limit maximum frustum size
  747. if ((shadowOcclusion) || (parameters.mFocus))
  748. sceneMaxZ = min(mSceneViewBox.mMax.mZ, sceneMaxZ);
  749. const Matrix4x3& lightView = shadowCamera.getInverseWorldTransform();
  750. Frustum lightViewSplitFrustum = mCamera->getSplitFrustum(light->getNearSplit() - light->getNearFadeRange(),
  751. min(light->getFarSplit(), sceneMaxZ)).getTransformed(lightView);
  752. // Fit the frustum inside a bounding box. If uniform size, use a sphere instead
  753. BoundingBox shadowBox;
  754. if ((!shadowOcclusion) && (parameters.mNonUniform))
  755. shadowBox.define(lightViewSplitFrustum);
  756. else
  757. {
  758. Sphere shadowSphere;
  759. shadowSphere.define(lightViewSplitFrustum);
  760. shadowBox.define(shadowSphere);
  761. }
  762. shadowCamera.setOrthographic(true);
  763. shadowCamera.setNearClip(0.0f);
  764. shadowCamera.setFarClip(shadowBox.mMax.mZ);
  765. // Center shadow camera on the bounding box, snap to whole texels
  766. quantizeDirShadowCamera(light, shadowBox);
  767. }
  768. break;
  769. case LIGHT_SPOT:
  770. case LIGHT_SPLITPOINT:
  771. {
  772. Quaternion rotation(Vector3(0.0f, 0.0f, 1.0f), light->getDirection());
  773. shadowCamera.setPosition(light->getWorldPosition());
  774. shadowCamera.setRotation(light->getWorldRotation() * rotation);
  775. shadowCamera.setNearClip(light->getShadowNearFarRatio() * light->getRange());
  776. shadowCamera.setFarClip(light->getRange());
  777. shadowCamera.setOrthographic(false);
  778. shadowCamera.setFov(light->getFov());
  779. shadowCamera.setAspectRatio(light->getAspectRatio());
  780. // For spot lights, zoom out shadowmap if far away (reduces fillrate)
  781. if ((light->getLightType() == LIGHT_SPOT) && (parameters.mZoomOut))
  782. {
  783. // Make sure the out-zooming does not start while we are inside the spot
  784. float distance = max((mCamera->getInverseWorldTransform() * light->getWorldPosition()).mZ - light->getRange(), 1.0f);
  785. float lightPixels = (((float)mHeight * light->getRange() * mCamera->getZoom() * 0.5f) / distance);
  786. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  787. if (lightPixels < SHADOW_MIN_PIXELS)
  788. lightPixels = SHADOW_MIN_PIXELS;
  789. float zoomLevel = min(lightPixels / (float)light->getShadowMap()->getHeight(), 1.0f);
  790. shadowCamera.setZoom(zoomLevel);
  791. }
  792. }
  793. break;
  794. }
  795. }
  796. void View::focusShadowCamera(Light* light, const BoundingBox& geometryBox, const BoundingBox& shadowCasterBox)
  797. {
  798. // If either no geometries or no shadow casters, do nothing
  799. if ((!geometryBox.mDefined) || (!shadowCasterBox.mDefined))
  800. return;
  801. Camera& shadowCamera = light->getShadowCamera();
  802. const FocusParameters& parameters = light->getShadowFocus();
  803. switch (light->getLightType())
  804. {
  805. case LIGHT_DIRECTIONAL:
  806. {
  807. BoundingBox combinedBox;
  808. combinedBox.mMax.mY = shadowCamera.getOrthoSize() * 0.5f;
  809. combinedBox.mMax.mX = shadowCamera.getAspectRatio() * combinedBox.mMax.mY;
  810. combinedBox.mMin.mY = -combinedBox.mMax.mY;
  811. combinedBox.mMin.mX = -combinedBox.mMax.mX;
  812. combinedBox.intersect(geometryBox);
  813. combinedBox.intersect(shadowCasterBox);
  814. quantizeDirShadowCamera(light, combinedBox);
  815. }
  816. break;
  817. case LIGHT_SPOT:
  818. // Can not move, but can zoom the shadow camera. Check for out-zooming (distant shadow map), do nothing in that case
  819. if (shadowCamera.getZoom() >= 1.0f)
  820. {
  821. BoundingBox combinedBox(-1.0f, 1.0f);
  822. combinedBox.intersect(geometryBox);
  823. combinedBox.intersect(shadowCasterBox);
  824. float viewSizeX = max(fabsf(combinedBox.mMin.mX), fabsf(combinedBox.mMax.mX));
  825. float viewSizeY = max(fabsf(combinedBox.mMin.mY), fabsf(combinedBox.mMax.mY));
  826. float viewSize = max(viewSizeX, viewSizeY);
  827. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  828. float invOrthoSize = 1.0f / shadowCamera.getOrthoSize();
  829. float quantize = parameters.mQuantize * invOrthoSize;
  830. float minView = parameters.mMinView * invOrthoSize;
  831. viewSize = max(ceilf(viewSize / quantize) * quantize, minView);
  832. if (viewSize < 1.0f)
  833. shadowCamera.setZoom(1.0f / viewSize);
  834. }
  835. break;
  836. }
  837. }
  838. void View::quantizeDirShadowCamera(Light* light, const BoundingBox& viewBox)
  839. {
  840. Camera& shadowCamera = light->getShadowCamera();
  841. const FocusParameters& parameters = light->getShadowFocus();
  842. float minX = viewBox.mMin.mX;
  843. float minY = viewBox.mMin.mY;
  844. float maxX = viewBox.mMax.mX;
  845. float maxY = viewBox.mMax.mY;
  846. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  847. Vector2 viewSize(maxX - minX, maxY - minY);
  848. // Quantize size to reduce swimming
  849. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  850. if (parameters.mNonUniform)
  851. {
  852. viewSize.mX = ceilf(sqrtf(viewSize.mX / parameters.mQuantize));
  853. viewSize.mY = ceilf(sqrtf(viewSize.mY / parameters.mQuantize));
  854. viewSize.mX = max(viewSize.mX * viewSize.mX * parameters.mQuantize, parameters.mMinView);
  855. viewSize.mY = max(viewSize.mY * viewSize.mY * parameters.mQuantize, parameters.mMinView);
  856. }
  857. else if (parameters.mFocus)
  858. {
  859. viewSize.mX = max(viewSize.mX, viewSize.mY);
  860. viewSize.mX = ceilf(sqrtf(viewSize.mX / parameters.mQuantize));
  861. viewSize.mX = max(viewSize.mX * viewSize.mX * parameters.mQuantize, parameters.mMinView);
  862. viewSize.mY = viewSize.mX;
  863. }
  864. shadowCamera.setOrthoSize(viewSize);
  865. // Center shadow camera to the view space bounding box
  866. const Quaternion& rot = shadowCamera.getRotation();
  867. Vector3 adjust(center.mX, center.mY, 0.0f);
  868. shadowCamera.translate(rot * adjust);
  869. // If there is a shadow map, snap to its whole texels
  870. Texture2D* shadowMap = light->getShadowMap();
  871. if (shadowMap)
  872. {
  873. Vector3 viewPos(rot.getInverse() * shadowCamera.getPosition());
  874. // Take into account that shadow map border will not be used
  875. float invActualSize = 1.0f / (float)(shadowMap->getWidth() - 2);
  876. Vector2 texelSize(viewSize.mX * invActualSize, viewSize.mY * invActualSize);
  877. Vector3 snap(-fmodf(viewPos.mX, texelSize.mX), -fmodf(viewPos.mY, texelSize.mY), 0.0f);
  878. shadowCamera.translate(rot * snap);
  879. }
  880. }
  881. void View::optimizeLightByScissor(Light* light)
  882. {
  883. Renderer* renderer = mPipeline->getRenderer();
  884. if (light)
  885. renderer->setScissorTest(true, getLightScissor(light));
  886. else
  887. renderer->setScissorTest(false);
  888. }
  889. const Rect& View::getLightScissor(Light* light)
  890. {
  891. std::map<Light*, Rect>::iterator i = mLightScissorCache.find(light);
  892. if (i != mLightScissorCache.end())
  893. return i->second;
  894. const Matrix4x3& view = mCamera->getInverseWorldTransform();
  895. const Matrix4& projection = mCamera->getProjection();
  896. switch (light->getLightType())
  897. {
  898. case LIGHT_POINT:
  899. {
  900. BoundingBox viewBox = light->getWorldBoundingBox().getTransformed(view);
  901. return mLightScissorCache[light] = viewBox.getProjected(projection);
  902. }
  903. case LIGHT_SPOT:
  904. case LIGHT_SPLITPOINT:
  905. {
  906. Frustum viewFrustum = light->getFrustum().getTransformed(view);
  907. return mLightScissorCache[light] = viewFrustum.getProjected(projection);
  908. }
  909. default:
  910. return mLightScissorCache[light] = Rect::sFullRect;
  911. }
  912. }
  913. unsigned View::splitLight(Light* light)
  914. {
  915. LightType type = light->getLightType();
  916. if (type == LIGHT_DIRECTIONAL)
  917. {
  918. const CascadeParameters& cascade = light->getShadowCascade();
  919. unsigned splits = cascade.mSplits;
  920. if (splits > MAX_LIGHT_SPLITS - 1)
  921. splits = MAX_LIGHT_SPLITS;
  922. // Orthographic view actually has near clip 0, but clamp it to a theoretical minimum
  923. float farClip = cascade.mShadowRange; // Shadow range end
  924. float nearClip = max(mCamera->getNearClip(), M_MIN_NEARCLIP); // Shadow range start
  925. bool createExtraSplit = farClip < mCamera->getFarClip();
  926. // Practical split scheme (Zhang et al.)
  927. unsigned i;
  928. for (i = 0; i < splits; ++i)
  929. {
  930. // Set a minimum for the fade range to avoid boundary artifacts (missing lighting)
  931. float splitFadeRange = max(cascade.mSplitFadeRange, 0.001f);
  932. float iPerM = (float)i / (float)splits;
  933. float log = nearClip * powf(farClip / nearClip, iPerM);
  934. float uniform = nearClip + (farClip - nearClip) * iPerM;
  935. float nearSplit = log * cascade.mLambda + uniform * (1.0f - cascade.mLambda);
  936. float nearFadeRange = nearSplit * splitFadeRange;
  937. iPerM = (float)(i + 1) / (float)splits;
  938. log = nearClip * powf(farClip / nearClip, iPerM);
  939. uniform = nearClip + (farClip - nearClip) * iPerM;
  940. float farSplit = log * cascade.mLambda + uniform * (1.0f - cascade.mLambda);
  941. float farFadeRange = farSplit * splitFadeRange;
  942. // If split is completely beyond camera far clip, we are done
  943. if ((nearSplit - nearFadeRange) > mCamera->getFarClip())
  944. break;
  945. Light* splitLight = mPipeline->createSplitLight(light);
  946. sSplitLights[i] = splitLight;
  947. // Though the near clip was previously clamped, use the real near clip value for the first split,
  948. // so that there are no unlit portions
  949. if (i)
  950. splitLight->setNearSplit(nearSplit);
  951. else
  952. splitLight->setNearSplit(mCamera->getNearClip());
  953. splitLight->setNearFadeRange(nearFadeRange);
  954. splitLight->setFarSplit(farSplit);
  955. // The final split will not fade
  956. if ((createExtraSplit) || (i < splits - 1))
  957. splitLight->setFarFadeRange(farFadeRange);
  958. // Create an extra unshadowed split if necessary
  959. if ((createExtraSplit) && (i == splits - 1))
  960. {
  961. Light* splitLight = mPipeline->createSplitLight(light);
  962. sSplitLights[i + 1] = splitLight;
  963. splitLight->setNearSplit(farSplit);
  964. splitLight->setNearFadeRange(farFadeRange);
  965. splitLight->setCastShadows(false);
  966. }
  967. }
  968. if (createExtraSplit)
  969. return i + 1;
  970. else
  971. return i;
  972. }
  973. if (type == LIGHT_POINT)
  974. {
  975. static const Vector3 directions[] =
  976. {
  977. Vector3::sRight,
  978. Vector3::sLeft,
  979. Vector3::sUp,
  980. Vector3::sDown,
  981. Vector3::sForward,
  982. Vector3::sBack,
  983. };
  984. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  985. {
  986. Light* splitLight = mPipeline->createSplitLight(light);
  987. sSplitLights[i] = splitLight;
  988. splitLight->setLightType(LIGHT_SPLITPOINT);
  989. splitLight->setRotation(Quaternion::sIdentity);
  990. splitLight->setDirection(directions[i]);
  991. splitLight->setFov(90.0f);
  992. splitLight->setAspectRatio(1.0f);
  993. }
  994. return MAX_CUBEMAP_FACES;
  995. }
  996. // A spot light does not actually need splitting. However, we may be rendering several views,
  997. // and in some the light might be unshadowed, so better create an unique copy
  998. Light* splitLight = mPipeline->createSplitLight(light);
  999. sSplitLights[0] = splitLight;
  1000. return 1;
  1001. }
  1002. MaterialTechnique* View::getMaterialTechnique(GeometryNode* node, unsigned index)
  1003. {
  1004. Material* mat = node->getBatchMaterial(index);
  1005. if (!mat)
  1006. mat = mPipeline->getDefaultMaterial();
  1007. if (!mat)
  1008. return 0;
  1009. float lodDistance = node->getLodDistance();
  1010. unsigned numTechniques = mat->getNumTechniques();
  1011. // Check for suitable technique. Techniques should be ordered like this:
  1012. // Most distant & highest quality
  1013. // Most distant & lowest quality
  1014. // Second most distant & highest quality
  1015. // ...
  1016. for (unsigned i = 0; i < numTechniques; ++i)
  1017. {
  1018. MaterialTechnique* technique = mat->getTechnique(i);
  1019. if (((!mSM3Support) && (technique->getRequireSM3())) || (mMaterialQuality < technique->getQualityLevel()))
  1020. continue;
  1021. if (lodDistance >= technique->getLodDistance())
  1022. return technique;
  1023. }
  1024. // If no suitable technique found, fallback to the last
  1025. return mat->getTechnique(numTechniques - 1);
  1026. }
  1027. void View::checkTechniqueForAuxView(MaterialTechnique* technique)
  1028. {
  1029. const std::vector<SharedPtr<Texture> >& textures = technique->getTextures();
  1030. for (unsigned i = 0; i < textures.size(); ++i)
  1031. {
  1032. // Have to check cube & 2D textures separately
  1033. Texture* texture = textures[i];
  1034. if (texture)
  1035. {
  1036. if (texture->getType() == Texture2D::getTypeStatic())
  1037. {
  1038. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1039. RenderSurface* target = tex2D->getRenderSurface();
  1040. if (target)
  1041. {
  1042. const Viewport& viewport = target->getViewport();
  1043. if ((viewport.mScene) && (viewport.mCamera))
  1044. mPipeline->addView(target, viewport);
  1045. }
  1046. }
  1047. else if (texture->getType() == TextureCube::getTypeStatic())
  1048. {
  1049. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1050. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1051. {
  1052. RenderSurface* target = texCube->getRenderSurface((CubeMapFace)j);
  1053. if (target)
  1054. {
  1055. const Viewport& viewport = target->getViewport();
  1056. if ((viewport.mScene) && (viewport.mCamera))
  1057. mPipeline->addView(target, viewport);
  1058. }
  1059. }
  1060. }
  1061. }
  1062. }
  1063. // Set frame number so that we can early-out next time we come across this technique on the same frame
  1064. technique->markForAuxView(mFrame.mFrameNumber);
  1065. }
  1066. void View::sortBatches(std::vector<Batch>& originalBatches, std::vector<Batch*>& sortedBatches)
  1067. {
  1068. sortedBatches.resize(originalBatches.size());
  1069. for (unsigned i = 0; i < originalBatches.size(); ++i)
  1070. sortedBatches[i] = &originalBatches[i];
  1071. std::sort(sortedBatches.begin(), sortedBatches.end(), compareBatches);
  1072. }