View.cpp 72 KB

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