View.cpp 72 KB

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