View.cpp 81 KB

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