2
0

View.cpp 73 KB

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