View.cpp 49 KB

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