View.cpp 81 KB

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