View.cpp 80 KB

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