2
0

View.cpp 72 KB

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