View.cpp 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  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 "Camera.h"
  25. #include "DebugRenderer.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "Light.h"
  29. #include "Log.h"
  30. #include "Material.h"
  31. #include "OcclusionBuffer.h"
  32. #include "Octree.h"
  33. #include "OctreeQuery.h"
  34. #include "Renderer.h"
  35. #include "Profiler.h"
  36. #include "Scene.h"
  37. #include "ShaderVariation.h"
  38. #include "Sort.h"
  39. #include "Technique.h"
  40. #include "Texture2D.h"
  41. #include "TextureCube.h"
  42. #include "VertexBuffer.h"
  43. #include "View.h"
  44. #include "Zone.h"
  45. #include "DebugNew.h"
  46. static const Vector3 directions[] =
  47. {
  48. Vector3(1.0f, 0.0f, 0.0f),
  49. Vector3(-1.0f, 0.0f, 0.0f),
  50. Vector3(0.0f, 1.0f, 0.0f),
  51. Vector3(0.0f, -1.0f, 0.0f),
  52. Vector3(0.0f, 0.0f, 1.0f),
  53. Vector3(0.0f, 0.0f, -1.0f)
  54. };
  55. OBJECTTYPESTATIC(View);
  56. View::View(Context* context) :
  57. Object(context),
  58. graphics_(GetSubsystem<Graphics>()),
  59. renderer_(GetSubsystem<Renderer>()),
  60. octree_(0),
  61. camera_(0),
  62. cameraZone_(0),
  63. farClipZone_(0),
  64. renderTarget_(0),
  65. depthStencil_(0)
  66. {
  67. frame_.camera_ = 0;
  68. }
  69. View::~View()
  70. {
  71. }
  72. bool View::Define(RenderSurface* renderTarget, const Viewport& viewport)
  73. {
  74. if (!viewport.scene_ || !viewport.camera_)
  75. return false;
  76. // If scene is loading asynchronously, it is incomplete and should not be rendered
  77. if (viewport.scene_->IsAsyncLoading())
  78. return false;
  79. Octree* octree = viewport.scene_->GetComponent<Octree>();
  80. if (!octree)
  81. return false;
  82. octree_ = octree;
  83. camera_ = viewport.camera_;
  84. renderTarget_ = renderTarget;
  85. if (!renderTarget)
  86. depthStencil_ = 0;
  87. else
  88. depthStencil_ = renderTarget->GetLinkedDepthBuffer();
  89. // Validate the rect and calculate size. If zero rect, use whole render target size
  90. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  91. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  92. if (viewport.rect_ != IntRect::ZERO)
  93. {
  94. screenRect_.left_ = Clamp(viewport.rect_.left_, 0, rtWidth - 1);
  95. screenRect_.top_ = Clamp(viewport.rect_.top_, 0, rtHeight - 1);
  96. screenRect_.right_ = Clamp(viewport.rect_.right_, screenRect_.left_ + 1, rtWidth);
  97. screenRect_.bottom_ = Clamp(viewport.rect_.bottom_, screenRect_.top_ + 1, rtHeight);
  98. }
  99. else
  100. screenRect_ = IntRect(0, 0, rtWidth, rtHeight);
  101. width_ = screenRect_.right_ - screenRect_.left_;
  102. height_ = screenRect_.bottom_ - screenRect_.top_;
  103. // Set possible quality overrides from the camera
  104. drawShadows_ = renderer_->GetDrawShadows();
  105. materialQuality_ = renderer_->GetMaterialQuality();
  106. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  107. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  108. if (viewOverrideFlags & VO_LOW_MATERIAL_QUALITY)
  109. materialQuality_ = QUALITY_LOW;
  110. if (viewOverrideFlags & VO_DISABLE_SHADOWS)
  111. drawShadows_ = false;
  112. if (viewOverrideFlags & VO_DISABLE_OCCLUSION)
  113. maxOccluderTriangles_ = 0;
  114. return true;
  115. }
  116. void View::Update(const FrameInfo& frame)
  117. {
  118. if (!camera_ || !octree_)
  119. return;
  120. frame_.camera_ = camera_;
  121. frame_.timeStep_ = frame.timeStep_;
  122. frame_.frameNumber_ = frame.frameNumber_;
  123. frame_.viewSize_ = IntVector2(width_, height_);
  124. shadowFrame_ = frame_;
  125. // Clear old light scissor cache, geometry, light, occluder & batch lists
  126. lightScissorCache_.Clear();
  127. geometries_.Clear();
  128. geometryDepthBounds_.Clear();
  129. lights_.Clear();
  130. occluders_.Clear();
  131. shadowOccluders_.Clear();
  132. baseQueue_.Clear();
  133. preAlphaQueue_.Clear();
  134. alphaQueue_.Clear();
  135. postAlphaQueue_.Clear();
  136. lightQueues_.Clear();
  137. // Do not update if camera projection is illegal
  138. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  139. if (!camera_->IsProjectionValid())
  140. return;
  141. // Set automatic aspect ratio if required
  142. if (camera_->GetAutoAspectRatio())
  143. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  144. // Cache the camera frustum to avoid recalculating it constantly
  145. frustum_ = camera_->GetFrustum();
  146. // Reset shadow map allocations; they can be reused between views as each is rendered completely at a time
  147. renderer_->ResetShadowMapAllocations();
  148. GetDrawables();
  149. GetBatches();
  150. }
  151. void View::Render()
  152. {
  153. if (!octree_ || !camera_)
  154. return;
  155. // Forget parameter sources from the previous view
  156. graphics_->ClearParameterSources();
  157. // If stream offset is supported, write all instance transforms to a single large buffer
  158. // Else we must lock the instance buffer for each batch group
  159. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  160. PrepareInstancingBuffer();
  161. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  162. // again to ensure correct projection will be used
  163. if (camera_->GetAutoAspectRatio())
  164. camera_->SetAspectRatio((float)(screenRect_.right_ - screenRect_.left_) / (float)(screenRect_.bottom_ - screenRect_.top_));
  165. graphics_->SetColorWrite(true);
  166. graphics_->SetFillMode(FILL_SOLID);
  167. // Bind the face selection and indirection cube maps for point light shadows
  168. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  169. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  170. // Reset the light optimization stencil reference value
  171. lightStencilValue_ = 1;
  172. // Render
  173. RenderBatches();
  174. graphics_->SetScissorTest(false);
  175. graphics_->SetStencilTest(false);
  176. graphics_->ResetStreamFrequencies();
  177. // If this is a main view, draw the associated debug geometry now
  178. if (!renderTarget_)
  179. {
  180. Scene* scene = static_cast<Scene*>(octree_->GetNode());
  181. if (scene)
  182. {
  183. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  184. if (debug)
  185. {
  186. debug->SetView(camera_);
  187. debug->Render();
  188. }
  189. }
  190. }
  191. // "Forget" the camera, octree and zone after rendering
  192. camera_ = 0;
  193. octree_ = 0;
  194. cameraZone_ = 0;
  195. farClipZone_ = 0;
  196. frame_.camera_ = 0;
  197. }
  198. void View::GetDrawables()
  199. {
  200. int highestZonePriority = M_MIN_INT;
  201. {
  202. PROFILE(GetZones);
  203. // Get default zone first in case we do not have zones defined
  204. Zone* defaultZone = renderer_->GetDefaultZone();
  205. cameraZone_ = farClipZone_ = defaultZone;
  206. FrustumOctreeQuery query(reinterpret_cast<PODVector<Drawable*>&>(zones_), frustum_, DRAWABLE_ZONE);
  207. octree_->GetDrawables(query);
  208. // Find the visible zones, and the zone the camera is in. Determine also the highest zone priority to aid in seeing
  209. // whether a zone query result for a drawable is conclusive
  210. int bestPriority = M_MIN_INT;
  211. Vector3 cameraPos = camera_->GetWorldPosition();
  212. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  213. {
  214. int priority = (*i)->GetPriority();
  215. if (priority > highestZonePriority)
  216. highestZonePriority = priority;
  217. if ((*i)->IsInside(cameraPos) && priority > bestPriority)
  218. {
  219. cameraZone_ = *i;
  220. bestPriority = priority;
  221. }
  222. }
  223. // Determine the zone at far clip distance. If not found, or camera zone has override mode, use camera zone
  224. cameraZoneOverride_ = cameraZone_->GetOverride();
  225. if (!cameraZoneOverride_)
  226. {
  227. Vector3 farClipPos = cameraPos + camera_->GetNode()->GetWorldDirection() * Vector3(0, 0, camera_->GetFarClip());
  228. bestPriority = M_MIN_INT;
  229. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  230. {
  231. int priority = (*i)->GetPriority();
  232. if ((*i)->IsInside(farClipPos) && priority > bestPriority)
  233. {
  234. farClipZone_ = *i;
  235. bestPriority = priority;
  236. }
  237. }
  238. }
  239. if (farClipZone_ == defaultZone)
  240. farClipZone_ = cameraZone_;
  241. }
  242. {
  243. PROFILE(GetDrawables);
  244. // If occlusion in use, get & render the occluders, then build the depth buffer hierarchy
  245. OcclusionBuffer* buffer = 0;
  246. if (maxOccluderTriangles_ > 0)
  247. {
  248. FrustumOctreeQuery query(occluders_, frustum_, DRAWABLE_GEOMETRY, camera_->GetViewMask(), true, false);
  249. octree_->GetDrawables(query);
  250. UpdateOccluders(occluders_, camera_);
  251. if (occluders_.Size())
  252. {
  253. buffer = renderer_->GetOrCreateOcclusionBuffer(camera_, maxOccluderTriangles_);
  254. DrawOccluders(buffer, occluders_);
  255. buffer->BuildDepthHierarchy();
  256. }
  257. }
  258. if (!buffer)
  259. {
  260. // Get geometries & lights without occlusion
  261. FrustumOctreeQuery query(tempDrawables_, frustum_, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  262. octree_->GetDrawables(query);
  263. }
  264. else
  265. {
  266. // Get geometries & lights using occlusion
  267. OccludedFrustumOctreeQuery query(tempDrawables_, frustum_, buffer, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT,
  268. camera_->GetViewMask());
  269. octree_->GetDrawables(query);
  270. }
  271. // Add unculled geometries & lights
  272. octree_->GetUnculledDrawables(tempDrawables_, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT);
  273. // Sort into geometries & lights, and build visible scene bounding boxes in world and view space
  274. sceneBox_.min_ = sceneBox_.max_ = Vector3::ZERO;
  275. sceneBox_.defined_ = false;
  276. sceneViewBox_.min_ = sceneViewBox_.max_ = Vector3::ZERO;
  277. sceneViewBox_.defined_ = false;
  278. Matrix3x4 view(camera_->GetInverseWorldTransform());
  279. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  280. {
  281. Drawable* drawable = tempDrawables_[i];
  282. drawable->UpdateDistance(frame_);
  283. // If draw distance non-zero, check it
  284. float maxDistance = drawable->GetDrawDistance();
  285. if (maxDistance > 0.0f && drawable->GetDistance() > maxDistance)
  286. continue;
  287. unsigned flags = drawable->GetDrawableFlags();
  288. if (flags & DRAWABLE_GEOMETRY)
  289. {
  290. // Find new zone for the drawable if necessary
  291. if (!drawable->GetZone() && !cameraZoneOverride_)
  292. FindZone(drawable, highestZonePriority);
  293. drawable->ClearLights();
  294. drawable->MarkInView(frame_);
  295. drawable->UpdateGeometry(frame_);
  296. // Expand the scene bounding boxes. However, do not take "infinite" objects such as the skybox into account,
  297. // as the bounding boxes are also used for shadow focusing
  298. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  299. BoundingBox geomViewBox = geomBox.Transformed(view);
  300. if (geomBox.Size().LengthFast() < M_LARGE_VALUE)
  301. {
  302. sceneBox_.Merge(geomBox);
  303. sceneViewBox_.Merge(geomViewBox);
  304. }
  305. // Store depth info for split directional light queries
  306. GeometryDepthBounds bounds;
  307. bounds.min_ = geomViewBox.min_.z_;
  308. bounds.max_ = geomViewBox.max_.z_;
  309. geometryDepthBounds_.Push(bounds);
  310. geometries_.Push(drawable);
  311. }
  312. else if (flags & DRAWABLE_LIGHT)
  313. {
  314. Light* light = static_cast<Light*>(drawable);
  315. light->MarkInView(frame_);
  316. lights_.Push(light);
  317. }
  318. }
  319. // Sort the lights to brightest/closest first
  320. for (unsigned i = 0; i < lights_.Size(); ++i)
  321. {
  322. Light* light = lights_[i];
  323. light->SetIntensitySortValue(camera_->GetDistance(light->GetWorldPosition()));
  324. }
  325. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  326. }
  327. }
  328. void View::GetBatches()
  329. {
  330. maxLightsDrawables_.Clear();
  331. lightQueueIndex_.Clear();
  332. bool fallback = graphics_->GetFallback();
  333. // Go through lights
  334. {
  335. PROFILE_MULTIPLE(GetLightBatches, lights_.Size());
  336. // Preallocate enough light queues so that we can store pointers to them without having to worry about the
  337. // vector reallocating itself
  338. lightQueues_.Resize(lights_.Size());
  339. unsigned lightQueueCount = 0;
  340. for (unsigned i = 0; i < lights_.Size(); ++i)
  341. {
  342. Light* light = lights_[i];
  343. unsigned shadowSplits = ProcessLight(light);
  344. if (litGeometries_.Empty())
  345. continue;
  346. // Initialize light queue. Store pointer-to-index mapping so that the queue can be found later
  347. LightBatchQueue& lightQueue = lightQueues_[lightQueueCount];
  348. lightQueueIndex_[light] = lightQueueCount;
  349. lightQueue.light_ = light;
  350. lightQueue.litBatches_.Clear();
  351. // Allocate shadow map now
  352. lightQueue.shadowMap_ = 0;
  353. if (shadowSplits > 0)
  354. {
  355. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, width_, height_);
  356. // If did not manage to get a shadow map, convert the light to unshadowed
  357. if (!lightQueue.shadowMap_)
  358. shadowSplits = 0;
  359. }
  360. // Setup shadow batch queues
  361. lightQueue.shadowSplits_.Resize(shadowSplits);
  362. for (unsigned j = 0; j < shadowSplits; ++j)
  363. {
  364. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  365. Camera* shadowCamera = shadowCameras_[j];
  366. shadowQueue.shadowCamera_ = shadowCameras_[j];
  367. shadowQueue.nearSplit_ = shadowNearSplits_[j];
  368. shadowQueue.farSplit_ = shadowFarSplits_[j];
  369. shadowFrame_.camera_ = shadowCamera;
  370. // Setup the shadow split viewport and finalize shadow camera parameters
  371. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  372. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, shadowCasterBox_[j]);
  373. // Loop through shadow casters
  374. for (unsigned k = 0; k < shadowCasters_[j].Size(); ++k)
  375. {
  376. Drawable* drawable = shadowCasters_[j][k];
  377. unsigned numBatches = drawable->GetNumBatches();
  378. for (unsigned l = 0; l < numBatches; ++l)
  379. {
  380. Batch shadowBatch;
  381. drawable->GetBatch(shadowFrame_, l, shadowBatch);
  382. Technique* tech = GetTechnique(drawable, shadowBatch.material_);
  383. if (!shadowBatch.geometry_ || !tech)
  384. continue;
  385. Pass* pass = tech->GetPass(PASS_SHADOW);
  386. // Skip if material has no shadow pass
  387. if (!pass)
  388. continue;
  389. // Fill the rest of the batch
  390. shadowBatch.camera_ = shadowCamera;
  391. shadowBatch.lightQueue_ = &lightQueue;
  392. renderer_->SetBatchShaders(shadowBatch, tech, pass);
  393. shadowQueue.shadowBatches_.AddBatch(shadowBatch);
  394. }
  395. }
  396. }
  397. // Loop through lit geometries
  398. for (unsigned j = 0; j < litGeometries_.Size(); ++j)
  399. {
  400. Drawable* drawable = litGeometries_[j];
  401. drawable->AddLight(light);
  402. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  403. if (!drawable->GetMaxLights())
  404. GetLitBatches(drawable, lightQueue);
  405. else
  406. maxLightsDrawables_.Insert(drawable);
  407. }
  408. ++lightQueueCount;
  409. }
  410. // Resize the light queue vector now that final size is known
  411. lightQueues_.Resize(lightQueueCount);
  412. }
  413. // Process drawables with limited light count
  414. if (maxLightsDrawables_.Size())
  415. {
  416. PROFILE(GetMaxLightsBatches);
  417. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  418. {
  419. Drawable* drawable = *i;
  420. drawable->LimitLights();
  421. const PODVector<Light*>& lights = drawable->GetLights();
  422. for (unsigned i = 0; i < lights.Size(); ++i)
  423. {
  424. Light* light = lights[i];
  425. // Find the correct light queue again
  426. Map<Light*, unsigned>::Iterator j = lightQueueIndex_.Find(light);
  427. if (j != lightQueueIndex_.End())
  428. GetLitBatches(drawable, lightQueues_[j->second_]);
  429. }
  430. }
  431. }
  432. // Go through geometries for base pass batches
  433. {
  434. PROFILE(GetBaseBatches);
  435. for (unsigned i = 0; i < geometries_.Size(); ++i)
  436. {
  437. Drawable* drawable = geometries_[i];
  438. unsigned numBatches = drawable->GetNumBatches();
  439. for (unsigned j = 0; j < numBatches; ++j)
  440. {
  441. Batch baseBatch;
  442. drawable->GetBatch(frame_, j, baseBatch);
  443. Technique* tech = GetTechnique(drawable, baseBatch.material_);
  444. if (!baseBatch.geometry_ || !tech)
  445. continue;
  446. // Check here if the material technique refers to a render target texture with camera(s) attached
  447. // Only check this for the main view (null rendertarget)
  448. if (!renderTarget_ && baseBatch.material_ && baseBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_)
  449. CheckMaterialForAuxView(baseBatch.material_);
  450. // If object already has a lit base pass, can skip the unlit base pass
  451. if (drawable->HasBasePass(j))
  452. continue;
  453. // Fill the rest of the batch
  454. baseBatch.camera_ = camera_;
  455. baseBatch.zone_ = GetZone(drawable);
  456. baseBatch.hasPriority_ = true;
  457. Pass* pass = 0;
  458. // Check for unlit base pass
  459. pass = tech->GetPass(PASS_BASE);
  460. if (pass)
  461. {
  462. renderer_->SetBatchShaders(baseBatch, tech, pass);
  463. if (pass->GetBlendMode() == BLEND_REPLACE)
  464. baseQueue_.AddBatch(baseBatch);
  465. else
  466. alphaQueue_.AddBatch(baseBatch, false);
  467. continue;
  468. }
  469. // If no base pass, finally check for prealpha / postalpha custom passes
  470. pass = tech->GetPass(PASS_PREALPHA);
  471. if (pass)
  472. {
  473. renderer_->SetBatchShaders(baseBatch, tech, pass);
  474. preAlphaQueue_.AddBatch(baseBatch);
  475. continue;
  476. }
  477. pass = tech->GetPass(PASS_POSTALPHA);
  478. if (pass)
  479. {
  480. renderer_->SetBatchShaders(baseBatch, tech, pass);
  481. postAlphaQueue_.AddBatch(baseBatch, false);
  482. continue;
  483. }
  484. }
  485. }
  486. }
  487. // All batches have been collected. Sort them now
  488. SortBatches();
  489. }
  490. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue)
  491. {
  492. Light* light = lightQueue.light_;
  493. Light* firstLight = drawable->GetFirstLight();
  494. // Shadows on transparencies can only be rendered if shadow maps are not reused
  495. bool allowTransparentShadows = !renderer_->GetReuseShadowMaps();
  496. unsigned numBatches = drawable->GetNumBatches();
  497. for (unsigned i = 0; i < numBatches; ++i)
  498. {
  499. Batch litBatch;
  500. drawable->GetBatch(frame_, i, litBatch);
  501. Technique* tech = GetTechnique(drawable, litBatch.material_);
  502. if (!litBatch.geometry_ || !tech)
  503. continue;
  504. Pass* pass = 0;
  505. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  506. if (light == firstLight && !drawable->HasBasePass(i))
  507. {
  508. pass = tech->GetPass(PASS_LITBASE);
  509. if (pass)
  510. {
  511. litBatch.hasPriority_ = true;
  512. drawable->SetBasePass(i);
  513. }
  514. }
  515. // If no lit base pass, get ordinary light pass
  516. if (!pass)
  517. pass = tech->GetPass(PASS_LIGHT);
  518. // Skip if material does not receive light at all
  519. if (!pass)
  520. continue;
  521. // Fill the rest of the batch
  522. litBatch.camera_ = camera_;
  523. litBatch.lightQueue_ = &lightQueue;
  524. litBatch.zone_ = GetZone(drawable);
  525. // Check from the ambient pass whether the object is opaque or transparent
  526. Pass* ambientPass = tech->GetPass(PASS_BASE);
  527. if (!ambientPass || ambientPass->GetBlendMode() == BLEND_REPLACE)
  528. {
  529. renderer_->SetBatchShaders(litBatch, tech, pass);
  530. lightQueue.litBatches_.AddBatch(litBatch);
  531. }
  532. else
  533. {
  534. renderer_->SetBatchShaders(litBatch, tech, pass, allowTransparentShadows);
  535. alphaQueue_.AddBatch(litBatch, true);
  536. }
  537. }
  538. }
  539. void View::RenderBatches()
  540. {
  541. // If not reusing shadowmaps, render all of them first
  542. if (!renderer_->GetReuseShadowMaps())
  543. {
  544. PROFILE(RenderShadowMaps);
  545. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  546. {
  547. LightBatchQueue& queue = lightQueues_[i];
  548. if (queue.shadowMap_)
  549. RenderShadowMap(queue);
  550. }
  551. }
  552. {
  553. // Render opaque object base pass
  554. PROFILE(RenderAmbient);
  555. graphics_->SetRenderTarget(0, renderTarget_);
  556. graphics_->SetDepthStencil(depthStencil_);
  557. graphics_->SetViewport(screenRect_);
  558. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH | CLEAR_STENCIL, farClipZone_->GetFogColor());
  559. RenderBatchQueue(baseQueue_);
  560. }
  561. {
  562. // Render shadow maps + opaque objects' shadowed additive lighting
  563. PROFILE(RenderLights);
  564. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  565. {
  566. LightBatchQueue& queue = lightQueues_[i];
  567. // If reusing shadowmaps, render each of them before the lit batches
  568. if (renderer_->GetReuseShadowMaps() && queue.shadowMap_)
  569. RenderShadowMap(queue);
  570. graphics_->SetRenderTarget(0, renderTarget_);
  571. graphics_->SetDepthStencil(depthStencil_);
  572. graphics_->SetViewport(screenRect_);
  573. RenderLightBatchQueue(queue.litBatches_, queue.light_);
  574. }
  575. }
  576. graphics_->SetScissorTest(false);
  577. graphics_->SetStencilTest(false);
  578. graphics_->SetRenderTarget(0, renderTarget_);
  579. graphics_->SetDepthStencil(depthStencil_);
  580. graphics_->SetViewport(screenRect_);
  581. if (!preAlphaQueue_.IsEmpty())
  582. {
  583. // Render pre-alpha custom pass
  584. PROFILE(RenderPreAlpha);
  585. RenderBatchQueue(preAlphaQueue_);
  586. }
  587. if (!alphaQueue_.IsEmpty())
  588. {
  589. // Render transparent objects (both base passes & additive lighting)
  590. PROFILE(RenderAlpha);
  591. RenderBatchQueue(alphaQueue_, true);
  592. }
  593. if (!postAlphaQueue_.IsEmpty())
  594. {
  595. // Render pre-alpha custom pass
  596. PROFILE(RenderPostAlpha);
  597. RenderBatchQueue(postAlphaQueue_);
  598. }
  599. }
  600. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  601. {
  602. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  603. float halfViewSize = camera->GetHalfViewSize();
  604. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  605. Vector3 cameraPos = camera->GetWorldPosition();
  606. for (unsigned i = 0; i < occluders.Size(); ++i)
  607. {
  608. Drawable* occluder = occluders[i];
  609. occluder->UpdateDistance(frame_);
  610. bool erase = false;
  611. // Check occluder's draw distance (in main camera view)
  612. float maxDistance = occluder->GetDrawDistance();
  613. if (maxDistance > 0.0f && occluder->GetDistance() > maxDistance)
  614. erase = true;
  615. // Check that occluder is big enough on the screen
  616. const BoundingBox& box = occluder->GetWorldBoundingBox();
  617. float diagonal = (box.max_ - box.min_).LengthFast();
  618. float compare;
  619. if (!camera->IsOrthographic())
  620. compare = diagonal * halfViewSize / occluder->GetDistance();
  621. else
  622. compare = diagonal * invOrthoSize;
  623. if (compare < occluderSizeThreshold_)
  624. erase = true;
  625. if (!erase)
  626. {
  627. unsigned totalTriangles = 0;
  628. unsigned batches = occluder->GetNumBatches();
  629. Batch tempBatch;
  630. for (unsigned j = 0; j < batches; ++j)
  631. {
  632. occluder->GetBatch(frame_, j, tempBatch);
  633. if (tempBatch.geometry_)
  634. totalTriangles += tempBatch.geometry_->GetIndexCount() / 3;
  635. }
  636. // Store amount of triangles divided by screen size as a sorting key
  637. // (best occluders are big and have few triangles)
  638. occluder->SetSortValue((float)totalTriangles / compare);
  639. }
  640. else
  641. {
  642. occluders.Erase(occluders.Begin() + i);
  643. --i;
  644. }
  645. }
  646. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  647. if (occluders.Size())
  648. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  649. }
  650. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  651. {
  652. for (unsigned i = 0; i < occluders.Size(); ++i)
  653. {
  654. Drawable* occluder = occluders[i];
  655. if (i > 0)
  656. {
  657. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  658. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  659. continue;
  660. }
  661. occluder->UpdateGeometry(frame_);
  662. // Check for running out of triangles
  663. if (!occluder->DrawOcclusion(buffer))
  664. return;
  665. }
  666. }
  667. unsigned View::ProcessLight(Light* light)
  668. {
  669. // Check if light should be shadowed
  670. bool isShadowed = drawShadows_ && light->GetCastShadows() && light->GetShadowIntensity() < 1.0f;
  671. unsigned shadowSplits = 0;
  672. // If shadow distance non-zero, check it
  673. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  674. isShadowed = false;
  675. LightType type = light->GetLightType();
  676. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  677. litGeometries_.Clear();
  678. switch (type)
  679. {
  680. case LIGHT_DIRECTIONAL:
  681. for (unsigned i = 0; i < geometries_.Size(); ++i)
  682. {
  683. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  684. litGeometries_.Push(geometries_[i]);
  685. }
  686. break;
  687. case LIGHT_SPOT:
  688. {
  689. FrustumOctreeQuery query(tempDrawables_, light->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask());
  690. octree_->GetDrawables(query);
  691. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  692. {
  693. if (tempDrawables_[i]->IsInView(frame_) && (GetLightMask(tempDrawables_[i]) & light->GetLightMask()))
  694. litGeometries_.Push(tempDrawables_[i]);
  695. }
  696. }
  697. break;
  698. case LIGHT_POINT:
  699. {
  700. SphereOctreeQuery query(tempDrawables_, Sphere(light->GetWorldPosition(), light->GetRange()), DRAWABLE_GEOMETRY,
  701. camera_->GetViewMask());
  702. octree_->GetDrawables(query);
  703. for (unsigned i = 0; i < tempDrawables_.Size(); ++i)
  704. {
  705. if (tempDrawables_[i]->IsInView(frame_) && (GetLightMask(tempDrawables_[i]) & light->GetLightMask()))
  706. litGeometries_.Push(tempDrawables_[i]);
  707. }
  708. }
  709. break;
  710. }
  711. // If no lit geometries or not shadowed, no need to process shadow cameras
  712. if (litGeometries_.Empty() || !isShadowed)
  713. return 0;
  714. // Determine number of shadow cameras and setup their initial positions
  715. shadowSplits = SetupShadowCameras(light);
  716. // For a shadowed directional light, get occluders once using the whole (non-split) light frustum
  717. bool useOcclusion = false;
  718. OcclusionBuffer* buffer = 0;
  719. if (maxOccluderTriangles_ > 0 && isShadowed && light->GetLightType() == LIGHT_DIRECTIONAL)
  720. {
  721. // This shadow camera is never used for actually querying shadow casters, just occluders
  722. Camera* shadowCamera = renderer_->CreateShadowCamera();
  723. SetupDirLightShadowCamera(shadowCamera, light, 0.0f, Min(light->GetShadowCascade().GetShadowRange(), camera_->GetFarClip()),
  724. true);
  725. // Get occluders, which must be shadow-casting themselves
  726. FrustumOctreeQuery query(shadowOccluders_, shadowCamera->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask(),
  727. true, true);
  728. octree_->GetDrawables(query);
  729. UpdateOccluders(shadowOccluders_, shadowCamera);
  730. if (shadowOccluders_.Size())
  731. {
  732. // Shadow viewport is rectangular and consumes more CPU fillrate, so halve size
  733. buffer = renderer_->GetOrCreateOcclusionBuffer(shadowCamera, maxOccluderTriangles_, true);
  734. DrawOccluders(buffer, shadowOccluders_);
  735. buffer->BuildDepthHierarchy();
  736. useOcclusion = true;
  737. }
  738. }
  739. // Process each split for shadow casters
  740. bool hasShadowCasters = false;
  741. for (unsigned i = 0; i < shadowSplits; ++i)
  742. {
  743. shadowCasters_[i].Clear();
  744. shadowCasterBox_[i].defined_ = false;
  745. Camera* shadowCamera = shadowCameras_[i];
  746. if (!useOcclusion)
  747. {
  748. // For spot light (which has only one shadow split) we can optimize by reusing the query for
  749. // lit geometries, whose result still exists in tempDrawables_
  750. if (type != LIGHT_SPOT)
  751. {
  752. Frustum shadowCameraFrustum = shadowCamera->GetFrustum();
  753. // If a point light face, check that the face is visible: if not, there is no need to query and render
  754. // the shadow casters
  755. if (type == LIGHT_POINT)
  756. {
  757. BoundingBox shadowCameraBox(shadowCameraFrustum);
  758. if (frustum_.IsInsideFast(shadowCameraBox) == OUTSIDE)
  759. continue;
  760. }
  761. FrustumOctreeQuery query(tempDrawables_, shadowCameraFrustum, DRAWABLE_GEOMETRY, camera_->GetViewMask(),
  762. false, true);
  763. octree_->GetDrawables(query);
  764. }
  765. }
  766. else
  767. {
  768. OccludedFrustumOctreeQuery query(tempDrawables_, shadowCamera->GetFrustum(), buffer,
  769. DRAWABLE_GEOMETRY, camera_->GetViewMask(), false, true);
  770. octree_->GetDrawables(query);
  771. }
  772. // Check which shadow casters actually contribute to the shadowing
  773. ProcessShadowCasters(light, i, tempDrawables_, shadowCasterBox_[i]);
  774. if (shadowCasters_[i].Size())
  775. hasShadowCasters = true;
  776. }
  777. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  778. // only cost has been the shadow camera setup & queries
  779. if (!hasShadowCasters)
  780. shadowSplits = 0;
  781. return shadowSplits;
  782. }
  783. void View::ProcessShadowCasters(Light* light, unsigned splitIndex, const PODVector<Drawable*>& result, BoundingBox& shadowCasterBox)
  784. {
  785. Matrix3x4 lightView;
  786. Matrix4 lightProj;
  787. Camera* shadowCamera = shadowCameras_[splitIndex];
  788. lightView = shadowCamera->GetInverseWorldTransform();
  789. lightProj = shadowCamera->GetProjection();
  790. bool dirLight = shadowCamera->IsOrthographic();
  791. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  792. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  793. // frustum, so that shadow casters do not get rendered into unnecessary splits
  794. Frustum lightViewFrustum;
  795. if (!dirLight)
  796. lightViewFrustum = camera_->GetSplitFrustum(sceneViewBox_.min_.z_, sceneViewBox_.max_.z_).Transformed(lightView);
  797. else
  798. lightViewFrustum = camera_->GetSplitFrustum(Max(sceneViewBox_.min_.z_, shadowNearSplits_[splitIndex]),
  799. Min(sceneViewBox_.max_.z_, shadowFarSplits_[splitIndex])).Transformed(lightView);
  800. BoundingBox lightViewFrustumBox(lightViewFrustum);
  801. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  802. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  803. return;
  804. BoundingBox lightViewBox;
  805. BoundingBox lightProjBox;
  806. for (unsigned i = 0; i < result.Size(); ++i)
  807. {
  808. Drawable* drawable = static_cast<Drawable*>(result[i]);
  809. // In case this is a spot light query result reused for optimization, we may have non-shadowcasters included.
  810. // Check for that first
  811. if (!drawable->GetCastShadows())
  812. continue;
  813. drawable->UpdateDistance(frame_);
  814. // Check shadow distance
  815. float maxShadowDistance = drawable->GetShadowDistance();
  816. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  817. continue;
  818. // Check light mask
  819. if (!(GetLightMask(drawable) & light->GetLightMask()))
  820. continue;
  821. // Project shadow caster bounding box to light view space for visibility check
  822. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  823. if (drawable->IsInView(frame_) || IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum,
  824. lightViewFrustumBox))
  825. {
  826. // Update geometry now if not updated yet
  827. if (!drawable->IsInView(frame_))
  828. {
  829. drawable->MarkInShadowView(frame_);
  830. drawable->UpdateGeometry(frame_);
  831. }
  832. // Merge to shadow caster bounding box and add to the list
  833. if (dirLight)
  834. shadowCasterBox.Merge(lightViewBox);
  835. else
  836. {
  837. lightProjBox = lightViewBox.Projected(lightProj);
  838. shadowCasterBox.Merge(lightProjBox);
  839. }
  840. shadowCasters_[splitIndex].Push(drawable);
  841. }
  842. }
  843. }
  844. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  845. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  846. {
  847. // If shadow caster is also an occluder, must let it be visible, because it has potentially already culled
  848. // away other shadow casters (could also check the actual shadow occluder vector, but that would be slower)
  849. if (drawable->IsOccluder())
  850. return true;
  851. if (shadowCamera->IsOrthographic())
  852. {
  853. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  854. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  855. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  856. }
  857. else
  858. {
  859. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  860. if (drawable->IsInView(frame_))
  861. return true;
  862. // For perspective lights, extrusion direction depends on the position of the shadow caster
  863. Vector3 center = lightViewBox.Center();
  864. Ray extrusionRay(center, center.Normalized());
  865. float extrusionDistance = shadowCamera->GetFarClip();
  866. float originalDistance = Clamp(center.LengthFast(), M_EPSILON, extrusionDistance);
  867. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  868. float sizeFactor = extrusionDistance / originalDistance;
  869. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  870. // than necessary, so the test will be conservative
  871. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  872. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  873. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  874. lightViewBox.Merge(extrudedBox);
  875. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  876. }
  877. }
  878. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  879. {
  880. unsigned width = shadowMap->GetWidth();
  881. unsigned height = shadowMap->GetHeight();
  882. int maxCascades = renderer_->GetMaxShadowCascades();
  883. switch (light->GetLightType())
  884. {
  885. case LIGHT_DIRECTIONAL:
  886. if (maxCascades == 1)
  887. return IntRect(0, 0, width, height);
  888. else if (maxCascades == 2)
  889. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  890. else
  891. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  892. (splitIndex / 2 + 1) * height / 2);
  893. case LIGHT_SPOT:
  894. return IntRect(0, 0, width, height);
  895. case LIGHT_POINT:
  896. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  897. (splitIndex / 2 + 1) * height / 3);
  898. }
  899. return IntRect();
  900. }
  901. void View::OptimizeLightByScissor(Light* light)
  902. {
  903. if (light)
  904. graphics_->SetScissorTest(true, GetLightScissor(light));
  905. else
  906. graphics_->SetScissorTest(false);
  907. }
  908. void View::OptimizeLightByStencil(Light* light)
  909. {
  910. if (light && renderer_->GetLightStencilMasking())
  911. {
  912. Geometry* geometry = renderer_->GetLightGeometry(light);
  913. if (!geometry)
  914. {
  915. graphics_->SetStencilTest(false);
  916. return;
  917. }
  918. LightType type = light->GetLightType();
  919. Matrix3x4 view(camera_->GetInverseWorldTransform());
  920. Matrix4 projection(camera_->GetProjection());
  921. float lightDist;
  922. if (type == LIGHT_POINT)
  923. lightDist = Sphere(light->GetWorldPosition(), light->GetRange() * 1.25f).DistanceFast(camera_->GetWorldPosition());
  924. else
  925. lightDist = light->GetFrustum().Distance(camera_->GetWorldPosition());
  926. // If the camera is actually inside the light volume, do not draw to stencil as it would waste fillrate
  927. if (lightDist < M_EPSILON)
  928. {
  929. graphics_->SetStencilTest(false);
  930. return;
  931. }
  932. // If the stencil value has wrapped, clear the whole stencil first
  933. if (!lightStencilValue_)
  934. {
  935. graphics_->Clear(CLEAR_STENCIL);
  936. lightStencilValue_ = 1;
  937. }
  938. // If possible, render the stencil volume front faces. However, close to the near clip plane render back faces instead
  939. // to avoid clipping the front faces.
  940. if (lightDist < camera_->GetNearClip() * 2.0f)
  941. {
  942. graphics_->SetCullMode(CULL_CW);
  943. graphics_->SetDepthTest(CMP_GREATER);
  944. }
  945. else
  946. {
  947. graphics_->SetCullMode(CULL_CCW);
  948. graphics_->SetDepthTest(CMP_LESSEQUAL);
  949. }
  950. graphics_->SetColorWrite(false);
  951. graphics_->SetDepthWrite(false);
  952. graphics_->SetStencilTest(true, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, lightStencilValue_);
  953. graphics_->SetShaders(renderer_->GetStencilVS(), renderer_->GetStencilPS());
  954. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * view);
  955. graphics_->SetShaderParameter(VSP_MODEL, light->GetVolumeTransform());
  956. geometry->Draw(graphics_);
  957. graphics_->ClearTransformSources();
  958. graphics_->SetColorWrite(true);
  959. graphics_->SetStencilTest(true, CMP_EQUAL, OP_KEEP, OP_KEEP, OP_KEEP, lightStencilValue_);
  960. // Increase stencil value for next light
  961. ++lightStencilValue_;
  962. }
  963. else
  964. graphics_->SetStencilTest(false);
  965. }
  966. const Rect& View::GetLightScissor(Light* light)
  967. {
  968. HashMap<Light*, Rect>::Iterator i = lightScissorCache_.Find(light);
  969. if (i != lightScissorCache_.End())
  970. return i->second_;
  971. Matrix3x4 view(camera_->GetInverseWorldTransform());
  972. Matrix4 projection(camera_->GetProjection());
  973. switch (light->GetLightType())
  974. {
  975. case LIGHT_POINT:
  976. {
  977. BoundingBox viewBox(light->GetWorldBoundingBox().Transformed(view));
  978. return lightScissorCache_[light] = viewBox.Projected(projection);
  979. }
  980. case LIGHT_SPOT:
  981. {
  982. Frustum viewFrustum(light->GetFrustum().Transformed(view));
  983. return lightScissorCache_[light] = viewFrustum.Projected(projection);
  984. }
  985. default:
  986. return lightScissorCache_[light] = Rect::FULL;
  987. }
  988. }
  989. unsigned View::SetupShadowCameras(Light* light)
  990. {
  991. LightType type = light->GetLightType();
  992. if (type == LIGHT_DIRECTIONAL)
  993. {
  994. const CascadeParameters& cascade = light->GetShadowCascade();
  995. int splits = 0;
  996. float nearSplit = camera_->GetNearClip();
  997. float farSplit;
  998. while (splits < renderer_->GetMaxShadowCascades())
  999. {
  1000. // If split is completely beyond camera far clip, we are done
  1001. if (nearSplit > camera_->GetFarClip())
  1002. break;
  1003. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  1004. if (farSplit <= nearSplit)
  1005. break;
  1006. // Setup the shadow camera for the split
  1007. Camera* shadowCamera = renderer_->CreateShadowCamera();
  1008. shadowCameras_[splits] = shadowCamera;
  1009. shadowNearSplits_[splits] = nearSplit;
  1010. shadowFarSplits_[splits] = farSplit;
  1011. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit, false);
  1012. nearSplit = farSplit;
  1013. ++splits;
  1014. }
  1015. return splits;
  1016. }
  1017. if (type == LIGHT_SPOT)
  1018. {
  1019. Camera* shadowCamera = renderer_->CreateShadowCamera();
  1020. shadowCameras_[0] = shadowCamera;
  1021. Node* cameraNode = shadowCamera->GetNode();
  1022. cameraNode->SetTransform(light->GetWorldPosition(), light->GetWorldRotation());
  1023. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1024. shadowCamera->SetFarClip(light->GetRange());
  1025. shadowCamera->SetFov(light->GetFov());
  1026. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1027. return 1;
  1028. }
  1029. if (type == LIGHT_POINT)
  1030. {
  1031. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1032. {
  1033. Camera* shadowCamera = renderer_->CreateShadowCamera();
  1034. shadowCameras_[i] = shadowCamera;
  1035. Node* cameraNode = shadowCamera->GetNode();
  1036. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1037. cameraNode->SetPosition(light->GetWorldPosition());
  1038. cameraNode->SetDirection(directions[i]);
  1039. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1040. shadowCamera->SetFarClip(light->GetRange());
  1041. shadowCamera->SetFov(90.0f);
  1042. shadowCamera->SetAspectRatio(1.0f);
  1043. }
  1044. return MAX_CUBEMAP_FACES;
  1045. }
  1046. return 0;
  1047. }
  1048. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit, bool shadowOcclusion)
  1049. {
  1050. Node* cameraNode = shadowCamera->GetNode();
  1051. float extrusionDistance = camera_->GetFarClip();
  1052. const FocusParameters& parameters = light->GetShadowFocus();
  1053. // Calculate initial position & rotation
  1054. Vector3 lightWorldDirection = light->GetWorldRotation() * Vector3::FORWARD;
  1055. Vector3 pos = camera_->GetWorldPosition() - extrusionDistance * lightWorldDirection;
  1056. cameraNode->SetTransform(pos, light->GetWorldRotation());
  1057. // Calculate main camera shadowed frustum in light's view space
  1058. farSplit = Min(farSplit, camera_->GetFarClip());
  1059. // Use the scene Z bounds to limit frustum size if applicable
  1060. if (shadowOcclusion || parameters.focus_)
  1061. {
  1062. nearSplit = Max(sceneViewBox_.min_.z_, nearSplit);
  1063. farSplit = Min(sceneViewBox_.max_.z_, farSplit);
  1064. }
  1065. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  1066. frustumVolume_.Define(splitFrustum);
  1067. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  1068. if (!shadowOcclusion && parameters.focus_)
  1069. {
  1070. PROFILE(ClipFrustumVolume);
  1071. BoundingBox litGeometriesBox;
  1072. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1073. {
  1074. // Skip "infinite" objects like the skybox
  1075. const BoundingBox& geomBox = geometries_[i]->GetWorldBoundingBox();
  1076. if (geomBox.Size().LengthFast() < M_LARGE_VALUE)
  1077. {
  1078. if (geometryDepthBounds_[i].min_ <= farSplit && geometryDepthBounds_[i].max_ >= nearSplit &&
  1079. (GetLightMask(geometries_[i]) & light->GetLightMask()))
  1080. litGeometriesBox.Merge(geomBox);
  1081. }
  1082. }
  1083. if (litGeometriesBox.defined_)
  1084. {
  1085. frustumVolume_.Clip(litGeometriesBox);
  1086. // If volume became empty, restore it to avoid zero size
  1087. if (frustumVolume_.Empty())
  1088. frustumVolume_.Define(splitFrustum);
  1089. }
  1090. }
  1091. // Transform frustum volume to light space
  1092. Matrix3x4 lightView(shadowCamera->GetInverseWorldTransform());
  1093. frustumVolume_.Transform(lightView);
  1094. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  1095. BoundingBox shadowBox;
  1096. if (shadowOcclusion || !parameters.nonUniform_)
  1097. shadowBox.Define(Sphere(frustumVolume_));
  1098. else
  1099. shadowBox.Define(frustumVolume_);
  1100. shadowCamera->SetOrthographic(true);
  1101. shadowCamera->SetAspectRatio(1.0f);
  1102. shadowCamera->SetNearClip(0.0f);
  1103. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1104. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  1105. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  1106. }
  1107. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1108. const BoundingBox& shadowCasterBox)
  1109. {
  1110. const FocusParameters& parameters = light->GetShadowFocus();
  1111. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1112. LightType type = light->GetLightType();
  1113. if (type == LIGHT_DIRECTIONAL)
  1114. {
  1115. BoundingBox shadowBox;
  1116. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1117. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  1118. shadowBox.min_.y_ = -shadowBox.max_.y_;
  1119. shadowBox.min_.x_ = -shadowBox.max_.x_;
  1120. // Requantize and snap to shadow map texels
  1121. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  1122. }
  1123. if (type == LIGHT_SPOT)
  1124. {
  1125. if (parameters.focus_)
  1126. {
  1127. float viewSizeX = Max(fabsf(shadowCasterBox.min_.x_), fabsf(shadowCasterBox.max_.x_));
  1128. float viewSizeY = Max(fabsf(shadowCasterBox.min_.y_), fabsf(shadowCasterBox.max_.y_));
  1129. float viewSize = Max(viewSizeX, viewSizeY);
  1130. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  1131. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  1132. float quantize = parameters.quantize_ * invOrthoSize;
  1133. float minView = parameters.minView_ * invOrthoSize;
  1134. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  1135. if (viewSize < 1.0f)
  1136. shadowCamera->SetZoom(1.0f / viewSize);
  1137. }
  1138. }
  1139. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  1140. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  1141. if (shadowCamera->GetZoom() >= 1.0f)
  1142. {
  1143. if (light->GetLightType() != LIGHT_POINT)
  1144. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  1145. else
  1146. {
  1147. #ifdef USE_OPENGL
  1148. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  1149. #else
  1150. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  1151. #endif
  1152. }
  1153. }
  1154. }
  1155. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1156. const BoundingBox& viewBox)
  1157. {
  1158. Node* cameraNode = shadowCamera->GetNode();
  1159. const FocusParameters& parameters = light->GetShadowFocus();
  1160. float shadowMapWidth = (float)(shadowViewport.right_ - shadowViewport.left_);
  1161. float minX = viewBox.min_.x_;
  1162. float minY = viewBox.min_.y_;
  1163. float maxX = viewBox.max_.x_;
  1164. float maxY = viewBox.max_.y_;
  1165. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  1166. Vector2 viewSize(maxX - minX, maxY - minY);
  1167. // Quantize size to reduce swimming
  1168. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  1169. if (parameters.nonUniform_)
  1170. {
  1171. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1172. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  1173. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1174. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  1175. }
  1176. else if (parameters.focus_)
  1177. {
  1178. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  1179. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  1180. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  1181. viewSize.y_ = viewSize.x_;
  1182. }
  1183. shadowCamera->SetOrthoSize(viewSize);
  1184. // Center shadow camera to the view space bounding box
  1185. Vector3 pos(shadowCamera->GetWorldPosition());
  1186. Quaternion rot(shadowCamera->GetWorldRotation());
  1187. Vector3 adjust(center.x_, center.y_, 0.0f);
  1188. cameraNode->Translate(rot * adjust);
  1189. // If the shadow map viewport is known, snap to whole texels
  1190. if (shadowMapWidth > 0.0f)
  1191. {
  1192. Vector3 viewPos(rot.Inverse() * cameraNode->GetWorldPosition());
  1193. // Take into account that shadow map border will not be used
  1194. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  1195. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  1196. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  1197. cameraNode->Translate(rot * snap);
  1198. }
  1199. }
  1200. void View::FindZone(Drawable* drawable, int highestZonePriority)
  1201. {
  1202. Vector3 center = drawable->GetWorldBoundingBox().Center();
  1203. // First check if the last zone remains a conclusive result
  1204. Zone* lastZone = drawable->GetLastZone();
  1205. if (lastZone && lastZone->IsInside(center) && (drawable->GetZoneMask() & lastZone->GetZoneMask()) && lastZone->GetPriority()
  1206. >= highestZonePriority)
  1207. drawable->SetZone(lastZone);
  1208. // Then check if the visible zones contain the node center
  1209. else
  1210. {
  1211. int bestPriority = M_MIN_INT;
  1212. Zone* newZone = 0;
  1213. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  1214. {
  1215. int priority = (*i)->GetPriority();
  1216. if ((*i)->IsInside(center) && (drawable->GetZoneMask() & (*i)->GetZoneMask()) && priority > bestPriority)
  1217. {
  1218. newZone = *i;
  1219. bestPriority = priority;
  1220. }
  1221. }
  1222. // Finally, if no zone found yet, query the octree for zones at node center
  1223. if (!newZone)
  1224. {
  1225. PointOctreeQuery query(reinterpret_cast<PODVector<Drawable*>&>(tempZones_), center, DRAWABLE_ZONE);
  1226. octree_->GetDrawables(query);
  1227. bestPriority = M_MIN_INT;
  1228. for (PODVector<Zone*>::Iterator i = tempZones_.Begin(); i != tempZones_.End(); ++i)
  1229. {
  1230. int priority = (*i)->GetPriority();
  1231. if ((*i)->IsInside(center) && (drawable->GetZoneMask() & (*i)->GetZoneMask()) && priority > bestPriority)
  1232. {
  1233. newZone = *i;
  1234. bestPriority = priority;
  1235. }
  1236. }
  1237. }
  1238. drawable->SetZone(newZone);
  1239. }
  1240. }
  1241. Zone* View::GetZone(Drawable* drawable)
  1242. {
  1243. if (cameraZoneOverride_)
  1244. return cameraZone_;
  1245. Zone* drawableZone = drawable->GetZone();
  1246. return drawableZone ? drawableZone : cameraZone_;
  1247. }
  1248. unsigned View::GetLightMask(Drawable* drawable)
  1249. {
  1250. return drawable->GetLightMask() & GetZone(drawable)->GetLightMask();
  1251. }
  1252. Technique* View::GetTechnique(Drawable* drawable, Material*& material)
  1253. {
  1254. if (!material)
  1255. material = renderer_->GetDefaultMaterial();
  1256. if (!material)
  1257. return 0;
  1258. float lodDistance = drawable->GetLodDistance();
  1259. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  1260. if (techniques.Empty())
  1261. return 0;
  1262. // Check for suitable technique. Techniques should be ordered like this:
  1263. // Most distant & highest quality
  1264. // Most distant & lowest quality
  1265. // Second most distant & highest quality
  1266. // ...
  1267. for (unsigned i = 0; i < techniques.Size(); ++i)
  1268. {
  1269. const TechniqueEntry& entry = techniques[i];
  1270. Technique* technique = entry.technique_;
  1271. if (!technique || (technique->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  1272. continue;
  1273. if (lodDistance >= entry.lodDistance_)
  1274. return technique;
  1275. }
  1276. // If no suitable technique found, fallback to the last
  1277. return techniques.Back().technique_;
  1278. }
  1279. void View::CheckMaterialForAuxView(Material* material)
  1280. {
  1281. const Vector<SharedPtr<Texture> >& textures = material->GetTextures();
  1282. for (unsigned i = 0; i < textures.Size(); ++i)
  1283. {
  1284. // Have to check cube & 2D textures separately
  1285. Texture* texture = textures[i];
  1286. if (texture)
  1287. {
  1288. if (texture->GetType() == Texture2D::GetTypeStatic())
  1289. {
  1290. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  1291. RenderSurface* target = tex2D->GetRenderSurface();
  1292. if (target)
  1293. {
  1294. const Viewport& viewport = target->GetViewport();
  1295. if (viewport.scene_ && viewport.camera_)
  1296. renderer_->AddView(target, viewport);
  1297. }
  1298. }
  1299. else if (texture->GetType() == TextureCube::GetTypeStatic())
  1300. {
  1301. TextureCube* texCube = static_cast<TextureCube*>(texture);
  1302. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  1303. {
  1304. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  1305. if (target)
  1306. {
  1307. const Viewport& viewport = target->GetViewport();
  1308. if (viewport.scene_ && viewport.camera_)
  1309. renderer_->AddView(target, viewport);
  1310. }
  1311. }
  1312. }
  1313. }
  1314. }
  1315. // Set frame number so that we can early-out next time we come across this material on the same frame
  1316. material->MarkForAuxView(frame_.frameNumber_);
  1317. }
  1318. void View::SortBatches()
  1319. {
  1320. PROFILE(SortBatches);
  1321. baseQueue_.SortFrontToBack();
  1322. preAlphaQueue_.SortFrontToBack();
  1323. alphaQueue_.SortBackToFront();
  1324. postAlphaQueue_.SortBackToFront();
  1325. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1326. {
  1327. for (unsigned j = 0; j < lightQueues_[i].shadowSplits_.Size(); ++j)
  1328. lightQueues_[i].shadowSplits_[j].shadowBatches_.SortFrontToBack();
  1329. lightQueues_[i].litBatches_.SortFrontToBack();
  1330. }
  1331. }
  1332. void View::PrepareInstancingBuffer()
  1333. {
  1334. PROFILE(PrepareInstancingBuffer);
  1335. unsigned totalInstances = 0;
  1336. totalInstances += baseQueue_.GetNumInstances(renderer_);
  1337. totalInstances += preAlphaQueue_.GetNumInstances(renderer_);
  1338. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1339. {
  1340. for (unsigned j = 0; j < lightQueues_[i].shadowSplits_.Size(); ++j)
  1341. totalInstances += lightQueues_[i].shadowSplits_[j].shadowBatches_.GetNumInstances(renderer_);
  1342. totalInstances += lightQueues_[i].litBatches_.GetNumInstances(renderer_);
  1343. }
  1344. // If fail to set buffer size, fall back to per-group locking
  1345. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  1346. {
  1347. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  1348. unsigned freeIndex = 0;
  1349. void* lockedData = instancingBuffer->Lock(0, totalInstances, LOCK_DISCARD);
  1350. if (lockedData)
  1351. {
  1352. baseQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1353. preAlphaQueue_.SetTransforms(renderer_, lockedData, freeIndex);
  1354. for (unsigned i = 0; i < lightQueues_.Size(); ++i)
  1355. {
  1356. for (unsigned j = 0; j < lightQueues_[i].shadowSplits_.Size(); ++j)
  1357. lightQueues_[i].shadowSplits_[j].shadowBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1358. lightQueues_[i].litBatches_.SetTransforms(renderer_, lockedData, freeIndex);
  1359. }
  1360. instancingBuffer->Unlock();
  1361. }
  1362. }
  1363. }
  1364. void View::RenderBatchQueue(const BatchQueue& queue, bool useScissor)
  1365. {
  1366. graphics_->SetScissorTest(false);
  1367. graphics_->SetStencilTest(false);
  1368. // Priority instanced
  1369. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedPriorityBatchGroups_.Begin(); i !=
  1370. queue.sortedPriorityBatchGroups_.End(); ++i)
  1371. {
  1372. BatchGroup* group = *i;
  1373. group->Draw(graphics_, renderer_);
  1374. }
  1375. // Priority non-instanced
  1376. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1377. {
  1378. Batch* batch = *i;
  1379. batch->Draw(graphics_, renderer_);
  1380. }
  1381. // Non-priority instanced
  1382. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1383. {
  1384. BatchGroup* group = *i;
  1385. if (useScissor && group->lightQueue_)
  1386. OptimizeLightByScissor(group->lightQueue_->light_);
  1387. group->Draw(graphics_, renderer_);
  1388. }
  1389. // Non-priority non-instanced
  1390. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1391. {
  1392. Batch* batch = *i;
  1393. if (useScissor)
  1394. {
  1395. if (!batch->hasPriority_ && batch->lightQueue_)
  1396. OptimizeLightByScissor(batch->lightQueue_->light_);
  1397. else
  1398. graphics_->SetScissorTest(false);
  1399. }
  1400. batch->Draw(graphics_, renderer_);
  1401. }
  1402. }
  1403. void View::RenderLightBatchQueue(const BatchQueue& queue, Light* light)
  1404. {
  1405. graphics_->SetScissorTest(false);
  1406. graphics_->SetStencilTest(false);
  1407. // Priority instanced
  1408. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedPriorityBatchGroups_.Begin(); i !=
  1409. queue.sortedPriorityBatchGroups_.End(); ++i)
  1410. {
  1411. BatchGroup* group = *i;
  1412. group->Draw(graphics_, renderer_);
  1413. }
  1414. // Priority non-instanced
  1415. for (PODVector<Batch*>::ConstIterator i = queue.sortedPriorityBatches_.Begin(); i != queue.sortedPriorityBatches_.End(); ++i)
  1416. {
  1417. Batch* batch = *i;
  1418. batch->Draw(graphics_, renderer_);
  1419. }
  1420. // All base passes have been drawn. Optimize at this point by both stencil volume and scissor
  1421. OptimizeLightByStencil(light);
  1422. OptimizeLightByScissor(light);
  1423. // Non-priority instanced
  1424. for (PODVector<BatchGroup*>::ConstIterator i = queue.sortedBatchGroups_.Begin(); i != queue.sortedBatchGroups_.End(); ++i)
  1425. {
  1426. BatchGroup* group = *i;
  1427. group->Draw(graphics_, renderer_);
  1428. }
  1429. // Non-priority non-instanced
  1430. for (PODVector<Batch*>::ConstIterator i = queue.sortedBatches_.Begin(); i != queue.sortedBatches_.End(); ++i)
  1431. {
  1432. Batch* batch = *i;
  1433. batch->Draw(graphics_, renderer_);
  1434. }
  1435. }
  1436. void View::RenderShadowMap(const LightBatchQueue& queue)
  1437. {
  1438. PROFILE(RenderShadowMap);
  1439. Texture2D* shadowMap = queue.shadowMap_;
  1440. graphics_->SetStencilTest(false);
  1441. graphics_->SetTexture(TU_SHADOWMAP, 0);
  1442. if (!graphics_->GetFallback())
  1443. {
  1444. graphics_->SetColorWrite(false);
  1445. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  1446. graphics_->SetDepthStencil(shadowMap);
  1447. graphics_->Clear(CLEAR_DEPTH);
  1448. }
  1449. else
  1450. {
  1451. graphics_->SetColorWrite(true);
  1452. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface());
  1453. graphics_->SetDepthStencil(shadowMap->GetRenderSurface()->GetLinkedDepthBuffer());
  1454. graphics_->Clear(CLEAR_COLOR | CLEAR_DEPTH, Color::WHITE);
  1455. }
  1456. // Set shadow depth bias
  1457. BiasParameters parameters = queue.light_->GetShadowBias();
  1458. // Adjust the light's constant depth bias according to global shadow map resolution
  1459. /// \todo Should remove this adjustment and find a more flexible solution
  1460. unsigned shadowMapSize = renderer_->GetShadowMapSize();
  1461. if (shadowMapSize <= 512)
  1462. parameters.constantBias_ *= 2.0f;
  1463. else if (shadowMapSize >= 2048)
  1464. parameters.constantBias_ *= 0.5f;
  1465. graphics_->SetDepthBias(parameters.constantBias_, parameters.slopeScaledBias_);
  1466. // Render each of the splits
  1467. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  1468. {
  1469. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  1470. if (!shadowQueue.shadowBatches_.IsEmpty())
  1471. {
  1472. graphics_->SetViewport(shadowQueue.shadowViewport_);
  1473. // Set a scissor rectangle to match possible shadow map size reduction by out-zooming
  1474. // However, do not do this for point lights, which need to render continuously across cube faces
  1475. float width = (float)(shadowQueue.shadowViewport_.right_ - shadowQueue.shadowViewport_.left_);
  1476. if (queue.light_->GetLightType() != LIGHT_POINT)
  1477. {
  1478. float zoom = Min(shadowQueue.shadowCamera_->GetZoom(), width - 2.0f / width);
  1479. Rect zoomRect(Vector2(-1.0f, -1.0f) * zoom, Vector2(1.0f, 1.0f) * zoom);
  1480. graphics_->SetScissorTest(true, zoomRect, false);
  1481. }
  1482. else
  1483. graphics_->SetScissorTest(false);
  1484. // Draw instanced and non-instanced shadow casters
  1485. RenderBatchQueue(shadowQueue.shadowBatches_);
  1486. }
  1487. }
  1488. graphics_->SetColorWrite(true);
  1489. graphics_->SetDepthBias(0.0f, 0.0f);
  1490. }