View.cpp 74 KB

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