View.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  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->getLightType() != LIGHT_DIRECTIONAL) && (!light->getRampTexture()))
  398. light->setRampTexture(mPipeline->getDefaultLightRamp());
  399. if ((light->getLightType() == LIGHT_SPOT) && (!light->getShapeTexture()))
  400. light->setShapeTexture(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->getWorldDirection();
  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. shadowCamera.setPosition(light->getWorldPosition());
  773. shadowCamera.setRotation(light->getWorldRotation());
  774. shadowCamera.setNearClip(light->getShadowNearFarRatio() * light->getRange());
  775. shadowCamera.setFarClip(light->getRange());
  776. shadowCamera.setOrthographic(false);
  777. shadowCamera.setFov(light->getFov());
  778. shadowCamera.setAspectRatio(light->getAspectRatio());
  779. // For spot lights, zoom out shadowmap if far away (reduces fillrate)
  780. if ((light->getLightType() == LIGHT_SPOT) && (parameters.mZoomOut))
  781. {
  782. // Make sure the out-zooming does not start while we are inside the spot
  783. float distance = max((mCamera->getInverseWorldTransform() * light->getWorldPosition()).mZ - light->getRange(), 1.0f);
  784. float lightPixels = (((float)mHeight * light->getRange() * mCamera->getZoom() * 0.5f) / distance);
  785. // Clamp pixel amount to a sufficient minimum to avoid self-shadowing artifacts due to loss of precision
  786. if (lightPixels < SHADOW_MIN_PIXELS)
  787. lightPixels = SHADOW_MIN_PIXELS;
  788. float zoomLevel = min(lightPixels / (float)light->getShadowMap()->getHeight(), 1.0f);
  789. shadowCamera.setZoom(zoomLevel);
  790. }
  791. }
  792. break;
  793. }
  794. }
  795. void View::focusShadowCamera(Light* light, const BoundingBox& geometryBox, const BoundingBox& shadowCasterBox)
  796. {
  797. // If either no geometries or no shadow casters, do nothing
  798. if ((!geometryBox.mDefined) || (!shadowCasterBox.mDefined))
  799. return;
  800. Camera& shadowCamera = light->getShadowCamera();
  801. const FocusParameters& parameters = light->getShadowFocus();
  802. switch (light->getLightType())
  803. {
  804. case LIGHT_DIRECTIONAL:
  805. {
  806. BoundingBox combinedBox;
  807. combinedBox.mMax.mY = shadowCamera.getOrthoSize() * 0.5f;
  808. combinedBox.mMax.mX = shadowCamera.getAspectRatio() * combinedBox.mMax.mY;
  809. combinedBox.mMin.mY = -combinedBox.mMax.mY;
  810. combinedBox.mMin.mX = -combinedBox.mMax.mX;
  811. combinedBox.intersect(geometryBox);
  812. combinedBox.intersect(shadowCasterBox);
  813. quantizeDirShadowCamera(light, combinedBox);
  814. }
  815. break;
  816. case LIGHT_SPOT:
  817. // Can not move, but can zoom the shadow camera. Check for out-zooming (distant shadow map), do nothing in that case
  818. if (shadowCamera.getZoom() >= 1.0f)
  819. {
  820. BoundingBox combinedBox(-1.0f, 1.0f);
  821. combinedBox.intersect(geometryBox);
  822. combinedBox.intersect(shadowCasterBox);
  823. float viewSizeX = max(fabsf(combinedBox.mMin.mX), fabsf(combinedBox.mMax.mX));
  824. float viewSizeY = max(fabsf(combinedBox.mMin.mY), fabsf(combinedBox.mMax.mY));
  825. float viewSize = max(viewSizeX, viewSizeY);
  826. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  827. float invOrthoSize = 1.0f / shadowCamera.getOrthoSize();
  828. float quantize = parameters.mQuantize * invOrthoSize;
  829. float minView = parameters.mMinView * invOrthoSize;
  830. viewSize = max(ceilf(viewSize / quantize) * quantize, minView);
  831. if (viewSize < 1.0f)
  832. shadowCamera.setZoom(1.0f / viewSize);
  833. }
  834. break;
  835. }
  836. }
  837. void View::quantizeDirShadowCamera(Light* light, const BoundingBox& viewBox)
  838. {
  839. Camera& shadowCamera = light->getShadowCamera();
  840. const FocusParameters& parameters = light->getShadowFocus();
  841. float minX = viewBox.mMin.mX;
  842. float minY = viewBox.mMin.mY;
  843. float maxX = viewBox.mMax.mX;
  844. float maxY = viewBox.mMax.mY;
  845. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  846. Vector2 viewSize(maxX - minX, maxY - minY);
  847. // Quantize size to reduce swimming
  848. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  849. if (parameters.mNonUniform)
  850. {
  851. viewSize.mX = ceilf(sqrtf(viewSize.mX / parameters.mQuantize));
  852. viewSize.mY = ceilf(sqrtf(viewSize.mY / parameters.mQuantize));
  853. viewSize.mX = max(viewSize.mX * viewSize.mX * parameters.mQuantize, parameters.mMinView);
  854. viewSize.mY = max(viewSize.mY * viewSize.mY * parameters.mQuantize, parameters.mMinView);
  855. }
  856. else if (parameters.mFocus)
  857. {
  858. viewSize.mX = max(viewSize.mX, viewSize.mY);
  859. viewSize.mX = ceilf(sqrtf(viewSize.mX / parameters.mQuantize));
  860. viewSize.mX = max(viewSize.mX * viewSize.mX * parameters.mQuantize, parameters.mMinView);
  861. viewSize.mY = viewSize.mX;
  862. }
  863. shadowCamera.setOrthoSize(viewSize);
  864. // Center shadow camera to the view space bounding box
  865. const Quaternion& rot = shadowCamera.getRotation();
  866. Vector3 adjust(center.mX, center.mY, 0.0f);
  867. shadowCamera.translate(rot * adjust);
  868. // If there is a shadow map, snap to its whole texels
  869. Texture2D* shadowMap = light->getShadowMap();
  870. if (shadowMap)
  871. {
  872. Vector3 viewPos(rot.getInverse() * shadowCamera.getPosition());
  873. // Take into account that shadow map border will not be used
  874. float invActualSize = 1.0f / (float)(shadowMap->getWidth() - 2);
  875. Vector2 texelSize(viewSize.mX * invActualSize, viewSize.mY * invActualSize);
  876. Vector3 snap(-fmodf(viewPos.mX, texelSize.mX), -fmodf(viewPos.mY, texelSize.mY), 0.0f);
  877. shadowCamera.translate(rot * snap);
  878. }
  879. }
  880. void View::optimizeLightByScissor(Light* light)
  881. {
  882. Renderer* renderer = mPipeline->getRenderer();
  883. if (light)
  884. renderer->setScissorTest(true, getLightScissor(light));
  885. else
  886. renderer->setScissorTest(false);
  887. }
  888. const Rect& View::getLightScissor(Light* light)
  889. {
  890. std::map<Light*, Rect>::iterator i = mLightScissorCache.find(light);
  891. if (i != mLightScissorCache.end())
  892. return i->second;
  893. const Matrix4x3& view = mCamera->getInverseWorldTransform();
  894. const Matrix4& projection = mCamera->getProjection();
  895. switch (light->getLightType())
  896. {
  897. case LIGHT_POINT:
  898. {
  899. BoundingBox viewBox = light->getWorldBoundingBox().getTransformed(view);
  900. return mLightScissorCache[light] = viewBox.getProjected(projection);
  901. }
  902. case LIGHT_SPOT:
  903. case LIGHT_SPLITPOINT:
  904. {
  905. Frustum viewFrustum = light->getFrustum().getTransformed(view);
  906. return mLightScissorCache[light] = viewFrustum.getProjected(projection);
  907. }
  908. default:
  909. return mLightScissorCache[light] = Rect::sFullRect;
  910. }
  911. }
  912. unsigned View::splitLight(Light* light)
  913. {
  914. LightType type = light->getLightType();
  915. if (type == LIGHT_DIRECTIONAL)
  916. {
  917. const CascadeParameters& cascade = light->getShadowCascade();
  918. unsigned splits = cascade.mSplits;
  919. if (splits > MAX_LIGHT_SPLITS - 1)
  920. splits = MAX_LIGHT_SPLITS;
  921. // Orthographic view actually has near clip 0, but clamp it to a theoretical minimum
  922. float farClip = cascade.mShadowRange; // Shadow range end
  923. float nearClip = max(mCamera->getNearClip(), M_MIN_NEARCLIP); // Shadow range start
  924. bool createExtraSplit = farClip < mCamera->getFarClip();
  925. // Practical split scheme (Zhang et al.)
  926. unsigned i;
  927. for (i = 0; i < splits; ++i)
  928. {
  929. // Set a minimum for the fade range to avoid boundary artifacts (missing lighting)
  930. float splitFadeRange = max(cascade.mSplitFadeRange, 0.001f);
  931. float iPerM = (float)i / (float)splits;
  932. float log = nearClip * powf(farClip / nearClip, iPerM);
  933. float uniform = nearClip + (farClip - nearClip) * iPerM;
  934. float nearSplit = log * cascade.mLambda + uniform * (1.0f - cascade.mLambda);
  935. float nearFadeRange = nearSplit * splitFadeRange;
  936. iPerM = (float)(i + 1) / (float)splits;
  937. log = nearClip * powf(farClip / nearClip, iPerM);
  938. uniform = nearClip + (farClip - nearClip) * iPerM;
  939. float farSplit = log * cascade.mLambda + uniform * (1.0f - cascade.mLambda);
  940. float farFadeRange = farSplit * splitFadeRange;
  941. // If split is completely beyond camera far clip, we are done
  942. if ((nearSplit - nearFadeRange) > mCamera->getFarClip())
  943. break;
  944. Light* splitLight = mPipeline->createSplitLight(light);
  945. sSplitLights[i] = splitLight;
  946. // Though the near clip was previously clamped, use the real near clip value for the first split,
  947. // so that there are no unlit portions
  948. if (i)
  949. splitLight->setNearSplit(nearSplit);
  950. else
  951. splitLight->setNearSplit(mCamera->getNearClip());
  952. splitLight->setNearFadeRange(nearFadeRange);
  953. splitLight->setFarSplit(farSplit);
  954. // The final split will not fade
  955. if ((createExtraSplit) || (i < splits - 1))
  956. splitLight->setFarFadeRange(farFadeRange);
  957. // Create an extra unshadowed split if necessary
  958. if ((createExtraSplit) && (i == splits - 1))
  959. {
  960. Light* splitLight = mPipeline->createSplitLight(light);
  961. sSplitLights[i + 1] = splitLight;
  962. splitLight->setNearSplit(farSplit);
  963. splitLight->setNearFadeRange(farFadeRange);
  964. splitLight->setCastShadows(false);
  965. }
  966. }
  967. if (createExtraSplit)
  968. return i + 1;
  969. else
  970. return i;
  971. }
  972. if (type == LIGHT_POINT)
  973. {
  974. static const Vector3 directions[] =
  975. {
  976. Vector3::sRight,
  977. Vector3::sLeft,
  978. Vector3::sUp,
  979. Vector3::sDown,
  980. Vector3::sForward,
  981. Vector3::sBack,
  982. };
  983. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  984. {
  985. Light* splitLight = mPipeline->createSplitLight(light);
  986. sSplitLights[i] = splitLight;
  987. splitLight->setLightType(LIGHT_SPLITPOINT);
  988. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  989. splitLight->setDirection(directions[i]);
  990. splitLight->setFov(90.0f);
  991. splitLight->setAspectRatio(1.0f);
  992. }
  993. return MAX_CUBEMAP_FACES;
  994. }
  995. // A spot light does not actually need splitting. However, we may be rendering several views,
  996. // and in some the light might be unshadowed, so better create an unique copy
  997. Light* splitLight = mPipeline->createSplitLight(light);
  998. sSplitLights[0] = splitLight;
  999. return 1;
  1000. }
  1001. MaterialTechnique* View::getMaterialTechnique(GeometryNode* node, unsigned index)
  1002. {
  1003. Material* mat = node->getBatchMaterial(index);
  1004. if (!mat)
  1005. mat = mPipeline->getDefaultMaterial();
  1006. if (!mat)
  1007. return 0;
  1008. float lodDistance = node->getLodDistance();
  1009. unsigned numTechniques = mat->getNumTechniques();
  1010. // Check for suitable technique. Techniques should be ordered like this:
  1011. // Most distant & highest quality
  1012. // Most distant & lowest quality
  1013. // Second most distant & highest quality
  1014. // ...
  1015. for (unsigned i = 0; i < numTechniques; ++i)
  1016. {
  1017. MaterialTechnique* technique = mat->getTechnique(i);
  1018. if (((!mSM3Support) && (technique->getRequireSM3())) || (mMaterialQuality < technique->getQualityLevel()))
  1019. continue;
  1020. if (lodDistance >= technique->getLodDistance())
  1021. return technique;
  1022. }
  1023. // If no suitable technique found, fallback to the last
  1024. return mat->getTechnique(numTechniques - 1);
  1025. }
  1026. void View::checkTechniqueForAuxView(MaterialTechnique* technique)
  1027. {
  1028. const std::vector<SharedPtr<Texture> >& textures = technique->getTextures();
  1029. for (unsigned i = 0; i < textures.size(); ++i)
  1030. {
  1031. // Have to check cube & 2D textures separately
  1032. Texture* texture = textures[i];
  1033. if (texture)
  1034. {
  1035. if (texture->getType() == Texture2D::getTypeStatic())
  1036. {
  1037. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1038. RenderSurface* target = tex2D->getRenderSurface();
  1039. if (target)
  1040. {
  1041. const Viewport& viewport = target->getViewport();
  1042. if ((viewport.mScene) && (viewport.mCamera))
  1043. mPipeline->addView(target, viewport);
  1044. }
  1045. }
  1046. else if (texture->getType() == TextureCube::getTypeStatic())
  1047. {
  1048. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1049. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1050. {
  1051. RenderSurface* target = texCube->getRenderSurface((CubeMapFace)j);
  1052. if (target)
  1053. {
  1054. const Viewport& viewport = target->getViewport();
  1055. if ((viewport.mScene) && (viewport.mCamera))
  1056. mPipeline->addView(target, viewport);
  1057. }
  1058. }
  1059. }
  1060. }
  1061. }
  1062. // Set frame number so that we can early-out next time we come across this technique on the same frame
  1063. technique->markForAuxView(mFrame.mFrameNumber);
  1064. }
  1065. void View::sortBatches(std::vector<Batch>& originalBatches, std::vector<Batch*>& sortedBatches)
  1066. {
  1067. sortedBatches.resize(originalBatches.size());
  1068. for (unsigned i = 0; i < originalBatches.size(); ++i)
  1069. sortedBatches[i] = &originalBatches[i];
  1070. std::sort(sortedBatches.begin(), sortedBatches.end(), compareBatches);
  1071. }