View.cpp 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Camera.h"
  24. #include "DebugRenderer.h"
  25. #include "FileSystem.h"
  26. #include "Geometry.h"
  27. #include "Graphics.h"
  28. #include "GraphicsImpl.h"
  29. #include "Log.h"
  30. #include "Material.h"
  31. #include "OcclusionBuffer.h"
  32. #include "Octree.h"
  33. #include "Renderer.h"
  34. #include "RenderPath.h"
  35. #include "ResourceCache.h"
  36. #include "Profiler.h"
  37. #include "Scene.h"
  38. #include "ShaderVariation.h"
  39. #include "Skybox.h"
  40. #include "Technique.h"
  41. #include "Texture2D.h"
  42. #include "Texture3D.h"
  43. #include "TextureCube.h"
  44. #include "VertexBuffer.h"
  45. #include "View.h"
  46. #include "WorkQueue.h"
  47. #include "DebugNew.h"
  48. namespace Urho3D
  49. {
  50. static const Vector3* directions[] =
  51. {
  52. &Vector3::RIGHT,
  53. &Vector3::LEFT,
  54. &Vector3::UP,
  55. &Vector3::DOWN,
  56. &Vector3::FORWARD,
  57. &Vector3::BACK
  58. };
  59. static const float LIGHT_INTENSITY_THRESHOLD = 0.003f;
  60. /// %Frustum octree query for shadowcasters.
  61. class ShadowCasterOctreeQuery : public FrustumOctreeQuery
  62. {
  63. public:
  64. /// Construct with frustum and query parameters.
  65. ShadowCasterOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  66. unsigned viewMask = DEFAULT_VIEWMASK) :
  67. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask)
  68. {
  69. }
  70. /// Intersection test for drawables.
  71. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  72. {
  73. while (start != end)
  74. {
  75. Drawable* drawable = *start++;
  76. if (drawable->GetCastShadows() && (drawable->GetDrawableFlags() & drawableFlags_) &&
  77. (drawable->GetViewMask() & viewMask_))
  78. {
  79. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  80. result_.Push(drawable);
  81. }
  82. }
  83. }
  84. };
  85. /// %Frustum octree query for zones and occluders.
  86. class ZoneOccluderOctreeQuery : public FrustumOctreeQuery
  87. {
  88. public:
  89. /// Construct with frustum and query parameters.
  90. ZoneOccluderOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  91. unsigned viewMask = DEFAULT_VIEWMASK) :
  92. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask)
  93. {
  94. }
  95. /// Intersection test for drawables.
  96. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  97. {
  98. while (start != end)
  99. {
  100. Drawable* drawable = *start++;
  101. unsigned char flags = drawable->GetDrawableFlags();
  102. if ((flags == DRAWABLE_ZONE || (flags == DRAWABLE_GEOMETRY && drawable->IsOccluder())) && (drawable->GetViewMask() &
  103. viewMask_))
  104. {
  105. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  106. result_.Push(drawable);
  107. }
  108. }
  109. }
  110. };
  111. /// %Frustum octree query with occlusion.
  112. class OccludedFrustumOctreeQuery : public FrustumOctreeQuery
  113. {
  114. public:
  115. /// Construct with frustum, occlusion buffer and query parameters.
  116. OccludedFrustumOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, OcclusionBuffer* buffer, unsigned char
  117. drawableFlags = DRAWABLE_ANY, unsigned viewMask = DEFAULT_VIEWMASK) :
  118. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask),
  119. buffer_(buffer)
  120. {
  121. }
  122. /// Intersection test for an octant.
  123. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  124. {
  125. if (inside)
  126. return buffer_->IsVisible(box) ? INSIDE : OUTSIDE;
  127. else
  128. {
  129. Intersection result = frustum_.IsInside(box);
  130. if (result != OUTSIDE && !buffer_->IsVisible(box))
  131. result = OUTSIDE;
  132. return result;
  133. }
  134. }
  135. /// Intersection test for drawables. Note: drawable occlusion is performed later in worker threads.
  136. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  137. {
  138. while (start != end)
  139. {
  140. Drawable* drawable = *start++;
  141. if ((drawable->GetDrawableFlags() & drawableFlags_) && (drawable->GetViewMask() & viewMask_))
  142. {
  143. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  144. result_.Push(drawable);
  145. }
  146. }
  147. }
  148. /// Occlusion buffer.
  149. OcclusionBuffer* buffer_;
  150. };
  151. void CheckVisibilityWork(const WorkItem* item, unsigned threadIndex)
  152. {
  153. View* view = reinterpret_cast<View*>(item->aux_);
  154. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  155. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  156. OcclusionBuffer* buffer = view->occlusionBuffer_;
  157. const Matrix3x4& viewMatrix = view->camera_->GetView();
  158. Vector3 viewZ = Vector3(viewMatrix.m20_, viewMatrix.m21_, viewMatrix.m22_);
  159. Vector3 absViewZ = viewZ.Abs();
  160. unsigned cameraViewMask = view->camera_->GetViewMask();
  161. bool cameraZoneOverride = view->cameraZoneOverride_;
  162. PerThreadSceneResult& result = view->sceneResults_[threadIndex];
  163. while (start != end)
  164. {
  165. Drawable* drawable = *start++;
  166. bool batchesUpdated = false;
  167. // If draw distance non-zero, update and check it
  168. float maxDistance = drawable->GetDrawDistance();
  169. if (maxDistance > 0.0f)
  170. {
  171. drawable->UpdateBatches(view->frame_);
  172. batchesUpdated = true;
  173. if (drawable->GetDistance() > maxDistance)
  174. continue;
  175. }
  176. if (!buffer || !drawable->IsOccludee() || buffer->IsVisible(drawable->GetWorldBoundingBox()))
  177. {
  178. if (!batchesUpdated)
  179. drawable->UpdateBatches(view->frame_);
  180. drawable->MarkInView(view->frame_);
  181. // For geometries, find zone, clear lights and calculate view space Z range
  182. if (drawable->GetDrawableFlags() & DRAWABLE_GEOMETRY)
  183. {
  184. Zone* drawableZone = drawable->GetZone();
  185. if ((!drawableZone || (drawableZone->GetViewMask() & cameraViewMask) == 0) && !cameraZoneOverride)
  186. view->FindZone(drawable);
  187. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  188. Vector3 center = geomBox.Center();
  189. float viewCenterZ = viewZ.DotProduct(center) + viewMatrix.m23_;
  190. Vector3 edge = geomBox.Size() * 0.5f;
  191. float viewEdgeZ = absViewZ.DotProduct(edge);
  192. float minZ = viewCenterZ - viewEdgeZ;
  193. float maxZ = viewCenterZ + viewEdgeZ;
  194. drawable->SetMinMaxZ(viewCenterZ - viewEdgeZ, viewCenterZ + viewEdgeZ);
  195. drawable->ClearLights();
  196. // Expand the scene bounding box and Z range (skybox not included because of infinite size) and store the drawawble
  197. if (drawable->GetType() != Skybox::GetTypeStatic())
  198. {
  199. result.minZ_ = Min(result.minZ_, minZ);
  200. result.maxZ_ = Max(result.maxZ_, maxZ);
  201. }
  202. result.geometries_.Push(drawable);
  203. }
  204. else if (drawable->GetDrawableFlags() & DRAWABLE_LIGHT)
  205. {
  206. Light* light = static_cast<Light*>(drawable);
  207. // Skip lights which are so dim that they can not contribute to a rendertarget
  208. if (light->GetColor().SumRGB() > LIGHT_INTENSITY_THRESHOLD)
  209. result.lights_.Push(light);
  210. }
  211. }
  212. }
  213. }
  214. void ProcessLightWork(const WorkItem* item, unsigned threadIndex)
  215. {
  216. View* view = reinterpret_cast<View*>(item->aux_);
  217. LightQueryResult* query = reinterpret_cast<LightQueryResult*>(item->start_);
  218. view->ProcessLight(*query, threadIndex);
  219. }
  220. void UpdateDrawableGeometriesWork(const WorkItem* item, unsigned threadIndex)
  221. {
  222. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  223. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  224. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  225. while (start != end)
  226. {
  227. Drawable* drawable = *start++;
  228. drawable->UpdateGeometry(frame);
  229. }
  230. }
  231. void SortBatchQueueFrontToBackWork(const WorkItem* item, unsigned threadIndex)
  232. {
  233. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  234. queue->SortFrontToBack();
  235. }
  236. void SortBatchQueueBackToFrontWork(const WorkItem* item, unsigned threadIndex)
  237. {
  238. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  239. queue->SortBackToFront();
  240. }
  241. void SortLightQueueWork(const WorkItem* item, unsigned threadIndex)
  242. {
  243. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  244. start->litBatches_.SortFrontToBack();
  245. }
  246. void SortShadowQueueWork(const WorkItem* item, unsigned threadIndex)
  247. {
  248. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  249. for (unsigned i = 0; i < start->shadowSplits_.Size(); ++i)
  250. start->shadowSplits_[i].shadowBatches_.SortFrontToBack();
  251. }
  252. View::View(Context* context) :
  253. Object(context),
  254. graphics_(GetSubsystem<Graphics>()),
  255. renderer_(GetSubsystem<Renderer>()),
  256. scene_(0),
  257. octree_(0),
  258. camera_(0),
  259. cameraZone_(0),
  260. farClipZone_(0),
  261. renderTarget_(0),
  262. substituteRenderTarget_(0)
  263. {
  264. // Create octree query and scene results vector for each thread
  265. unsigned numThreads = GetSubsystem<WorkQueue>()->GetNumThreads() + 1; // Worker threads + main thread
  266. tempDrawables_.Resize(numThreads);
  267. sceneResults_.Resize(numThreads);
  268. frame_.camera_ = 0;
  269. }
  270. View::~View()
  271. {
  272. }
  273. bool View::Define(RenderSurface* renderTarget, Viewport* viewport)
  274. {
  275. Scene* scene = viewport->GetScene();
  276. Camera* camera = viewport->GetCamera();
  277. if (!scene || !camera || !camera->IsEnabledEffective())
  278. return false;
  279. // If scene is loading asynchronously, it is incomplete and should not be rendered
  280. if (scene->IsAsyncLoading())
  281. return false;
  282. Octree* octree = scene->GetComponent<Octree>();
  283. if (!octree)
  284. return false;
  285. // Do not accept view if camera projection is illegal
  286. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  287. if (!camera->IsProjectionValid())
  288. return false;
  289. scene_ = scene;
  290. octree_ = octree;
  291. camera_ = camera;
  292. cameraNode_ = camera->GetNode();
  293. renderTarget_ = renderTarget;
  294. renderPath_ = viewport->GetRenderPath();
  295. gBufferPassName_ = StringHash();
  296. basePassName_ = PASS_BASE;
  297. alphaPassName_ = PASS_ALPHA;
  298. lightPassName_ = PASS_LIGHT;
  299. litBasePassName_ = PASS_LITBASE;
  300. litAlphaPassName_ = PASS_LITALPHA;
  301. // Make sure that all necessary batch queues exist
  302. scenePasses_.Clear();
  303. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  304. {
  305. const RenderPathCommand& command = renderPath_->commands_[i];
  306. if (!command.enabled_)
  307. continue;
  308. if (command.type_ == CMD_SCENEPASS)
  309. {
  310. ScenePassInfo info;
  311. info.pass_ = command.pass_;
  312. info.allowInstancing_ = command.sortMode_ != SORT_BACKTOFRONT;
  313. info.markToStencil_ = command.markToStencil_;
  314. info.useScissor_ = command.useScissor_;
  315. info.vertexLights_ = command.vertexLights_;
  316. // Check scenepass metadata for defining custom passes which interact with lighting
  317. String metadata = command.metadata_.Trimmed().ToLower();
  318. if (!metadata.Empty())
  319. {
  320. if (metadata == "gbuffer")
  321. gBufferPassName_ = command.pass_;
  322. else if (metadata == "base")
  323. {
  324. basePassName_ = command.pass_;
  325. litBasePassName_ = "lit" + command.pass_;
  326. }
  327. else if (metadata == "alpha")
  328. {
  329. alphaPassName_ = command.pass_;
  330. litAlphaPassName_ = "lit" + command.pass_;
  331. }
  332. }
  333. HashMap<StringHash, BatchQueue>::Iterator j = batchQueues_.Find(command.pass_);
  334. if (j == batchQueues_.End())
  335. j = batchQueues_.Insert(Pair<StringHash, BatchQueue>(command.pass_, BatchQueue()));
  336. info.batchQueue_ = &j->second_;
  337. scenePasses_.Push(info);
  338. }
  339. else if (command.type_ == CMD_FORWARDLIGHTS)
  340. {
  341. if (!command.pass_.Trimmed().Empty())
  342. lightPassName_ = command.pass_;
  343. }
  344. }
  345. // Get light volume shaders according to the renderpath, if it needs them
  346. deferred_ = false;
  347. deferredAmbient_ = false;
  348. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  349. {
  350. const RenderPathCommand& command = renderPath_->commands_[i];
  351. if (!command.enabled_)
  352. continue;
  353. // Check if ambient pass and G-buffer rendering happens at the same time
  354. if (command.type_ == CMD_SCENEPASS && command.outputNames_.Size() > 1)
  355. {
  356. if (CheckViewportWrite(command))
  357. deferredAmbient_ = true;
  358. }
  359. if (command.type_ == CMD_LIGHTVOLUMES)
  360. {
  361. /// \todo Do not re-query each frame, as it involves string manipulation
  362. renderer_->GetLightVolumeShaders(lightVS_, lightPS_, command.vertexShaderName_, command.vertexShaderDefines_,
  363. command.pixelShaderName_, command.pixelShaderDefines_);
  364. deferred_ = true;
  365. }
  366. }
  367. if (!deferred_)
  368. {
  369. lightVS_.Clear();
  370. lightPS_.Clear();
  371. }
  372. // Validate the rect and calculate size. If zero rect, use whole rendertarget size
  373. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  374. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  375. const IntRect& rect = viewport->GetRect();
  376. if (rect != IntRect::ZERO)
  377. {
  378. viewRect_.left_ = Clamp(rect.left_, 0, rtWidth - 1);
  379. viewRect_.top_ = Clamp(rect.top_, 0, rtHeight - 1);
  380. viewRect_.right_ = Clamp(rect.right_, viewRect_.left_ + 1, rtWidth);
  381. viewRect_.bottom_ = Clamp(rect.bottom_, viewRect_.top_ + 1, rtHeight);
  382. }
  383. else
  384. viewRect_ = IntRect(0, 0, rtWidth, rtHeight);
  385. viewSize_ = viewRect_.Size();
  386. rtSize_ = IntVector2(rtWidth, rtHeight);
  387. // On OpenGL flip the viewport if rendering to a texture for consistent UV addressing with Direct3D9
  388. #ifdef USE_OPENGL
  389. if (renderTarget_)
  390. {
  391. viewRect_.bottom_ = rtSize_.y_ - viewRect_.top_;
  392. viewRect_.top_ = viewRect_.bottom_ - viewSize_.y_;
  393. }
  394. #endif
  395. drawShadows_ = renderer_->GetDrawShadows();
  396. materialQuality_ = renderer_->GetMaterialQuality();
  397. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  398. minInstances_ = renderer_->GetMinInstances();
  399. // Set possible quality overrides from the camera
  400. unsigned viewOverrideFlags = camera_->GetViewOverrideFlags();
  401. if (viewOverrideFlags & VO_LOW_MATERIAL_QUALITY)
  402. materialQuality_ = QUALITY_LOW;
  403. if (viewOverrideFlags & VO_DISABLE_SHADOWS)
  404. drawShadows_ = false;
  405. if (viewOverrideFlags & VO_DISABLE_OCCLUSION)
  406. maxOccluderTriangles_ = 0;
  407. // Occlusion buffer has constant width. If resulting height would be too large due to aspect ratio, disable occlusion
  408. if (viewSize_.y_ > viewSize_.x_ * 4)
  409. maxOccluderTriangles_ = 0;
  410. return true;
  411. }
  412. void View::Update(const FrameInfo& frame)
  413. {
  414. if (!camera_ || !octree_)
  415. return;
  416. frame_.camera_ = camera_;
  417. frame_.timeStep_ = frame.timeStep_;
  418. frame_.frameNumber_ = frame.frameNumber_;
  419. frame_.viewSize_ = viewSize_;
  420. int maxSortedInstances = renderer_->GetMaxSortedInstances();
  421. // Clear buffers, geometry, light, occluder & batch list
  422. renderTargets_.Clear();
  423. geometries_.Clear();
  424. shadowGeometries_.Clear();
  425. lights_.Clear();
  426. zones_.Clear();
  427. occluders_.Clear();
  428. vertexLightQueues_.Clear();
  429. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  430. i->second_.Clear(maxSortedInstances);
  431. // Set automatic aspect ratio if required
  432. if (camera_->GetAutoAspectRatio())
  433. camera_->SetAspectRatio((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  434. GetDrawables();
  435. GetBatches();
  436. }
  437. void View::Render()
  438. {
  439. if (!octree_ || !camera_)
  440. return;
  441. // Actually update geometry data now
  442. UpdateGeometries();
  443. // Allocate screen buffers as necessary
  444. AllocateScreenBuffers();
  445. // Forget parameter sources from the previous view
  446. graphics_->ClearParameterSources();
  447. // If stream offset is supported, write all instance transforms to a single large buffer
  448. // Else we must lock the instance buffer for each batch group
  449. if (renderer_->GetDynamicInstancing() && graphics_->GetStreamOffsetSupport())
  450. PrepareInstancingBuffer();
  451. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  452. // again to ensure correct projection will be used
  453. if (camera_->GetAutoAspectRatio())
  454. camera_->SetAspectRatio((float)(viewSize_.x_) / (float)(viewSize_.y_));
  455. // Bind the face selection and indirection cube maps for point light shadows
  456. if (renderer_->GetDrawShadows())
  457. {
  458. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  459. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  460. }
  461. // Set "view texture" to prevent destination texture sampling during all renderpasses
  462. if (renderTarget_)
  463. {
  464. graphics_->SetViewTexture(renderTarget_->GetParentTexture());
  465. // On OpenGL, flip the projection if rendering to a texture so that the texture can be addressed in the same way
  466. // as a render texture produced on Direct3D9
  467. #ifdef USE_OPENGL
  468. camera_->SetFlipVertical(true);
  469. #endif
  470. }
  471. // Render
  472. ExecuteRenderPathCommands();
  473. #ifdef USE_OPENGL
  474. camera_->SetFlipVertical(false);
  475. #endif
  476. graphics_->SetDepthBias(0.0f, 0.0f);
  477. graphics_->SetScissorTest(false);
  478. graphics_->SetStencilTest(false);
  479. graphics_->SetViewTexture(0);
  480. graphics_->ResetStreamFrequencies();
  481. // Run framebuffer blitting if necessary
  482. if (currentRenderTarget_ != renderTarget_)
  483. BlitFramebuffer(static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture()), renderTarget_, true);
  484. // If this is a main view, draw the associated debug geometry now
  485. if (!renderTarget_)
  486. {
  487. DebugRenderer* debug = octree_->GetComponent<DebugRenderer>();
  488. if (debug)
  489. {
  490. debug->SetView(camera_);
  491. debug->Render();
  492. }
  493. }
  494. // "Forget" the scene, camera, octree and zone after rendering
  495. scene_ = 0;
  496. camera_ = 0;
  497. octree_ = 0;
  498. cameraZone_ = 0;
  499. farClipZone_ = 0;
  500. occlusionBuffer_ = 0;
  501. frame_.camera_ = 0;
  502. }
  503. Graphics* View::GetGraphics() const
  504. {
  505. return graphics_;
  506. }
  507. Renderer* View::GetRenderer() const
  508. {
  509. return renderer_;
  510. }
  511. void View::GetDrawables()
  512. {
  513. PROFILE(GetDrawables);
  514. WorkQueue* queue = GetSubsystem<WorkQueue>();
  515. PODVector<Drawable*>& tempDrawables = tempDrawables_[0];
  516. // Get zones and occluders first
  517. {
  518. ZoneOccluderOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_ZONE, camera_->GetViewMask());
  519. octree_->GetDrawables(query);
  520. }
  521. highestZonePriority_ = M_MIN_INT;
  522. int bestPriority = M_MIN_INT;
  523. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  524. // Get default zone first in case we do not have zones defined
  525. Zone* defaultZone = renderer_->GetDefaultZone();
  526. cameraZone_ = farClipZone_ = defaultZone;
  527. for (PODVector<Drawable*>::ConstIterator i = tempDrawables.Begin(); i != tempDrawables.End(); ++i)
  528. {
  529. Drawable* drawable = *i;
  530. unsigned char flags = drawable->GetDrawableFlags();
  531. if (flags & DRAWABLE_ZONE)
  532. {
  533. Zone* zone = static_cast<Zone*>(drawable);
  534. zones_.Push(zone);
  535. int priority = zone->GetPriority();
  536. if (priority > highestZonePriority_)
  537. highestZonePriority_ = priority;
  538. if (priority > bestPriority && zone->IsInside(cameraPos))
  539. {
  540. cameraZone_ = zone;
  541. bestPriority = priority;
  542. }
  543. }
  544. else
  545. occluders_.Push(drawable);
  546. }
  547. // Determine the zone at far clip distance. If not found, or camera zone has override mode, use camera zone
  548. cameraZoneOverride_ = cameraZone_->GetOverride();
  549. if (!cameraZoneOverride_)
  550. {
  551. Vector3 farClipPos = cameraPos + cameraNode_->GetWorldDirection() * Vector3(0.0f, 0.0f, camera_->GetFarClip());
  552. bestPriority = M_MIN_INT;
  553. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  554. {
  555. int priority = (*i)->GetPriority();
  556. if (priority > bestPriority && (*i)->IsInside(farClipPos))
  557. {
  558. farClipZone_ = *i;
  559. bestPriority = priority;
  560. }
  561. }
  562. }
  563. if (farClipZone_ == defaultZone)
  564. farClipZone_ = cameraZone_;
  565. // If occlusion in use, get & render the occluders
  566. occlusionBuffer_ = 0;
  567. if (maxOccluderTriangles_ > 0)
  568. {
  569. UpdateOccluders(occluders_, camera_);
  570. if (occluders_.Size())
  571. {
  572. PROFILE(DrawOcclusion);
  573. occlusionBuffer_ = renderer_->GetOcclusionBuffer(camera_);
  574. DrawOccluders(occlusionBuffer_, occluders_);
  575. }
  576. }
  577. // Get lights and geometries. Coarse occlusion for octants is used at this point
  578. if (occlusionBuffer_)
  579. {
  580. OccludedFrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), occlusionBuffer_, DRAWABLE_GEOMETRY |
  581. DRAWABLE_LIGHT, camera_->GetViewMask());
  582. octree_->GetDrawables(query);
  583. }
  584. else
  585. {
  586. FrustumOctreeQuery query(tempDrawables, camera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_LIGHT,
  587. camera_->GetViewMask());
  588. octree_->GetDrawables(query);
  589. }
  590. // Check drawable occlusion, find zones for moved drawables and collect geometries & lights in worker threads
  591. {
  592. for (unsigned i = 0; i < sceneResults_.Size(); ++i)
  593. {
  594. PerThreadSceneResult& result = sceneResults_[i];
  595. result.geometries_.Clear();
  596. result.lights_.Clear();
  597. result.minZ_ = M_INFINITY;
  598. result.maxZ_ = 0.0f;
  599. }
  600. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  601. int drawablesPerItem = tempDrawables.Size() / numWorkItems;
  602. WorkItem item;
  603. item.workFunction_ = CheckVisibilityWork;
  604. item.aux_ = this;
  605. PODVector<Drawable*>::Iterator start = tempDrawables.Begin();
  606. // Create a work item for each thread
  607. for (int i = 0; i < numWorkItems; ++i)
  608. {
  609. PODVector<Drawable*>::Iterator end = tempDrawables.End();
  610. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  611. end = start + drawablesPerItem;
  612. item.start_ = &(*start);
  613. item.end_ = &(*end);
  614. queue->AddWorkItem(item);
  615. start = end;
  616. }
  617. queue->Complete(M_MAX_UNSIGNED);
  618. }
  619. // Combine lights, geometries & scene Z range from the threads
  620. geometries_.Clear();
  621. lights_.Clear();
  622. minZ_ = M_INFINITY;
  623. maxZ_ = 0.0f;
  624. if (sceneResults_.Size() > 1)
  625. {
  626. for (unsigned i = 0; i < sceneResults_.Size(); ++i)
  627. {
  628. PerThreadSceneResult& result = sceneResults_[i];
  629. geometries_.Push(result.geometries_);
  630. lights_.Push(result.lights_);
  631. minZ_ = Min(minZ_, result.minZ_);
  632. maxZ_ = Max(maxZ_, result.maxZ_);
  633. }
  634. }
  635. else
  636. {
  637. // If just 1 thread, copy the results directly
  638. PerThreadSceneResult& result = sceneResults_[0];
  639. minZ_ = result.minZ_;
  640. maxZ_ = result.maxZ_;
  641. Swap(geometries_, result.geometries_);
  642. Swap(lights_, result.lights_);
  643. }
  644. if (minZ_ == M_INFINITY)
  645. minZ_ = 0.0f;
  646. // Sort the lights to brightest/closest first
  647. for (unsigned i = 0; i < lights_.Size(); ++i)
  648. {
  649. Light* light = lights_[i];
  650. light->SetIntensitySortValue(camera_->GetDistance(light->GetNode()->GetWorldPosition()));
  651. light->SetLightQueue(0);
  652. }
  653. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  654. }
  655. void View::GetBatches()
  656. {
  657. WorkQueue* queue = GetSubsystem<WorkQueue>();
  658. PODVector<Light*> vertexLights;
  659. BatchQueue* alphaQueue = batchQueues_.Contains(alphaPassName_) ? &batchQueues_[alphaPassName_] : (BatchQueue*)0;
  660. // Check whether to use the lit base pass optimization
  661. bool useLitBase = true;
  662. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  663. {
  664. const RenderPathCommand& command = renderPath_->commands_[i];
  665. if (command.type_ == CMD_FORWARDLIGHTS)
  666. useLitBase = command.useLitBase_;
  667. }
  668. // Process lit geometries and shadow casters for each light
  669. {
  670. PROFILE(ProcessLights);
  671. lightQueryResults_.Resize(lights_.Size());
  672. WorkItem item;
  673. item.workFunction_ = ProcessLightWork;
  674. item.aux_ = this;
  675. for (unsigned i = 0; i < lightQueryResults_.Size(); ++i)
  676. {
  677. LightQueryResult& query = lightQueryResults_[i];
  678. query.light_ = lights_[i];
  679. item.start_ = &query;
  680. queue->AddWorkItem(item);
  681. }
  682. // Ensure all lights have been processed before proceeding
  683. queue->Complete(M_MAX_UNSIGNED);
  684. }
  685. // Build light queues and lit batches
  686. {
  687. PROFILE(GetLightBatches);
  688. // Preallocate light queues: per-pixel lights which have lit geometries
  689. unsigned numLightQueues = 0;
  690. unsigned usedLightQueues = 0;
  691. for (Vector<LightQueryResult>::ConstIterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  692. {
  693. if (!i->light_->GetPerVertex() && i->litGeometries_.Size())
  694. ++numLightQueues;
  695. }
  696. lightQueues_.Resize(numLightQueues);
  697. maxLightsDrawables_.Clear();
  698. unsigned maxSortedInstances = renderer_->GetMaxSortedInstances();
  699. for (Vector<LightQueryResult>::Iterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  700. {
  701. LightQueryResult& query = *i;
  702. // If light has no affected geometries, no need to process further
  703. if (query.litGeometries_.Empty())
  704. continue;
  705. Light* light = query.light_;
  706. // Per-pixel light
  707. if (!light->GetPerVertex())
  708. {
  709. unsigned shadowSplits = query.numSplits_;
  710. // Initialize light queue and store it to the light so that it can be found later
  711. LightBatchQueue& lightQueue = lightQueues_[usedLightQueues++];
  712. light->SetLightQueue(&lightQueue);
  713. lightQueue.light_ = light;
  714. lightQueue.shadowMap_ = 0;
  715. lightQueue.litBatches_.Clear(maxSortedInstances);
  716. lightQueue.volumeBatches_.Clear();
  717. // Allocate shadow map now
  718. if (shadowSplits > 0)
  719. {
  720. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, camera_, viewSize_.x_, viewSize_.y_);
  721. // If did not manage to get a shadow map, convert the light to unshadowed
  722. if (!lightQueue.shadowMap_)
  723. shadowSplits = 0;
  724. }
  725. // Setup shadow batch queues
  726. lightQueue.shadowSplits_.Resize(shadowSplits);
  727. for (unsigned j = 0; j < shadowSplits; ++j)
  728. {
  729. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  730. Camera* shadowCamera = query.shadowCameras_[j];
  731. shadowQueue.shadowCamera_ = shadowCamera;
  732. shadowQueue.nearSplit_ = query.shadowNearSplits_[j];
  733. shadowQueue.farSplit_ = query.shadowFarSplits_[j];
  734. shadowQueue.shadowBatches_.Clear(maxSortedInstances);
  735. // Setup the shadow split viewport and finalize shadow camera parameters
  736. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  737. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, query.shadowCasterBox_[j]);
  738. // Loop through shadow casters
  739. for (PODVector<Drawable*>::ConstIterator k = query.shadowCasters_.Begin() + query.shadowCasterBegin_[j];
  740. k < query.shadowCasters_.Begin() + query.shadowCasterEnd_[j]; ++k)
  741. {
  742. Drawable* drawable = *k;
  743. if (!drawable->IsInView(frame_, false))
  744. {
  745. drawable->MarkInView(frame_, false);
  746. shadowGeometries_.Push(drawable);
  747. }
  748. Zone* zone = GetZone(drawable);
  749. const Vector<SourceBatch>& batches = drawable->GetBatches();
  750. for (unsigned l = 0; l < batches.Size(); ++l)
  751. {
  752. const SourceBatch& srcBatch = batches[l];
  753. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  754. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  755. continue;
  756. Pass* pass = tech->GetPass(PASS_SHADOW);
  757. // Skip if material has no shadow pass
  758. if (!pass)
  759. continue;
  760. Batch destBatch(srcBatch);
  761. destBatch.pass_ = pass;
  762. destBatch.camera_ = shadowCamera;
  763. destBatch.zone_ = zone;
  764. destBatch.lightQueue_ = &lightQueue;
  765. AddBatchToQueue(shadowQueue.shadowBatches_, destBatch, tech);
  766. }
  767. }
  768. }
  769. // Process lit geometries
  770. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  771. {
  772. Drawable* drawable = *j;
  773. drawable->AddLight(light);
  774. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  775. if (!drawable->GetMaxLights())
  776. GetLitBatches(drawable, lightQueue, alphaQueue, useLitBase);
  777. else
  778. maxLightsDrawables_.Insert(drawable);
  779. }
  780. // In deferred modes, store the light volume batch now
  781. if (deferred_)
  782. {
  783. Batch volumeBatch;
  784. volumeBatch.geometry_ = renderer_->GetLightGeometry(light);
  785. volumeBatch.geometryType_ = GEOM_STATIC;
  786. volumeBatch.worldTransform_ = &light->GetVolumeTransform(camera_);
  787. volumeBatch.numWorldTransforms_ = 1;
  788. volumeBatch.overrideView_ = light->GetLightType() == LIGHT_DIRECTIONAL;
  789. volumeBatch.camera_ = camera_;
  790. volumeBatch.lightQueue_ = &lightQueue;
  791. volumeBatch.distance_ = light->GetDistance();
  792. volumeBatch.material_ = 0;
  793. volumeBatch.pass_ = 0;
  794. volumeBatch.zone_ = 0;
  795. renderer_->SetLightVolumeBatchShaders(volumeBatch, lightVS_, lightPS_);
  796. lightQueue.volumeBatches_.Push(volumeBatch);
  797. }
  798. }
  799. // Per-vertex light
  800. else
  801. {
  802. // Add the vertex light to lit drawables. It will be processed later during base pass batch generation
  803. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  804. {
  805. Drawable* drawable = *j;
  806. drawable->AddVertexLight(light);
  807. }
  808. }
  809. }
  810. }
  811. // Process drawables with limited per-pixel light count
  812. if (maxLightsDrawables_.Size())
  813. {
  814. PROFILE(GetMaxLightsBatches);
  815. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  816. {
  817. Drawable* drawable = *i;
  818. drawable->LimitLights();
  819. const PODVector<Light*>& lights = drawable->GetLights();
  820. for (unsigned i = 0; i < lights.Size(); ++i)
  821. {
  822. Light* light = lights[i];
  823. // Find the correct light queue again
  824. LightBatchQueue* queue = light->GetLightQueue();
  825. if (queue)
  826. GetLitBatches(drawable, *queue, alphaQueue, useLitBase);
  827. }
  828. }
  829. }
  830. // Build base pass batches
  831. {
  832. PROFILE(GetBaseBatches);
  833. for (PODVector<Drawable*>::ConstIterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  834. {
  835. Drawable* drawable = *i;
  836. Zone* zone = GetZone(drawable);
  837. const Vector<SourceBatch>& batches = drawable->GetBatches();
  838. const PODVector<Light*>& drawableVertexLights = drawable->GetVertexLights();
  839. if (!drawableVertexLights.Empty())
  840. drawable->LimitVertexLights();
  841. for (unsigned j = 0; j < batches.Size(); ++j)
  842. {
  843. const SourceBatch& srcBatch = batches[j];
  844. // Check here if the material refers to a rendertarget texture with camera(s) attached
  845. // Only check this for backbuffer views (null rendertarget)
  846. if (srcBatch.material_ && srcBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_ && !renderTarget_)
  847. CheckMaterialForAuxView(srcBatch.material_);
  848. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  849. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  850. continue;
  851. Batch destBatch(srcBatch);
  852. destBatch.camera_ = camera_;
  853. destBatch.zone_ = zone;
  854. destBatch.isBase_ = true;
  855. destBatch.pass_ = 0;
  856. destBatch.lightMask_ = GetLightMask(drawable);
  857. // Check each of the scene passes
  858. for (unsigned k = 0; k < scenePasses_.Size(); ++k)
  859. {
  860. ScenePassInfo& info = scenePasses_[k];
  861. destBatch.pass_ = tech->GetPass(info.pass_);
  862. if (!destBatch.pass_)
  863. continue;
  864. // Skip forward base pass if the corresponding litbase pass already exists
  865. if (info.pass_ == basePassName_ && j < 32 && drawable->HasBasePass(j))
  866. continue;
  867. if (info.vertexLights_ && !drawableVertexLights.Empty())
  868. {
  869. // For a deferred opaque batch, check if the vertex lights include converted per-pixel lights, and remove
  870. // them to prevent double-lighting
  871. if (deferred_ && destBatch.pass_->GetBlendMode() == BLEND_REPLACE)
  872. {
  873. vertexLights.Clear();
  874. for (unsigned i = 0; i < drawableVertexLights.Size(); ++i)
  875. {
  876. if (drawableVertexLights[i]->GetPerVertex())
  877. vertexLights.Push(drawableVertexLights[i]);
  878. }
  879. }
  880. else
  881. vertexLights = drawableVertexLights;
  882. if (!vertexLights.Empty())
  883. {
  884. // Find a vertex light queue. If not found, create new
  885. unsigned long long hash = GetVertexLightQueueHash(vertexLights);
  886. HashMap<unsigned long long, LightBatchQueue>::Iterator i = vertexLightQueues_.Find(hash);
  887. if (i == vertexLightQueues_.End())
  888. {
  889. i = vertexLightQueues_.Insert(MakePair(hash, LightBatchQueue()));
  890. i->second_.light_ = 0;
  891. i->second_.shadowMap_ = 0;
  892. i->second_.vertexLights_ = vertexLights;
  893. }
  894. destBatch.lightQueue_ = &(i->second_);
  895. }
  896. }
  897. else
  898. destBatch.lightQueue_ = 0;
  899. bool allowInstancing = info.allowInstancing_;
  900. if (allowInstancing && info.markToStencil_ && destBatch.lightMask_ != (zone->GetLightMask() & 0xff))
  901. allowInstancing = false;
  902. AddBatchToQueue(*info.batchQueue_, destBatch, tech, allowInstancing);
  903. }
  904. }
  905. }
  906. }
  907. }
  908. void View::UpdateGeometries()
  909. {
  910. PROFILE(SortAndUpdateGeometry);
  911. WorkQueue* queue = GetSubsystem<WorkQueue>();
  912. // Sort batches
  913. {
  914. WorkItem item;
  915. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  916. {
  917. const RenderPathCommand& command = renderPath_->commands_[i];
  918. if (!IsNecessary(command))
  919. continue;
  920. if (command.type_ == CMD_SCENEPASS)
  921. {
  922. BatchQueue* passQueue = &batchQueues_[command.pass_];
  923. item.workFunction_ = command.sortMode_ == SORT_FRONTTOBACK ? SortBatchQueueFrontToBackWork :
  924. SortBatchQueueBackToFrontWork;
  925. item.start_ = &batchQueues_[command.pass_];
  926. queue->AddWorkItem(item);
  927. }
  928. }
  929. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  930. {
  931. item.workFunction_ = SortLightQueueWork;
  932. item.start_ = &(*i);
  933. queue->AddWorkItem(item);
  934. if (i->shadowSplits_.Size())
  935. {
  936. item.workFunction_ = SortShadowQueueWork;
  937. queue->AddWorkItem(item);
  938. }
  939. }
  940. }
  941. // Update geometries. Split into threaded and non-threaded updates.
  942. {
  943. nonThreadedGeometries_.Clear();
  944. threadedGeometries_.Clear();
  945. for (PODVector<Drawable*>::Iterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  946. {
  947. UpdateGeometryType type = (*i)->GetUpdateGeometryType();
  948. if (type == UPDATE_MAIN_THREAD)
  949. nonThreadedGeometries_.Push(*i);
  950. else if (type == UPDATE_WORKER_THREAD)
  951. threadedGeometries_.Push(*i);
  952. }
  953. for (PODVector<Drawable*>::Iterator i = shadowGeometries_.Begin(); i != shadowGeometries_.End(); ++i)
  954. {
  955. UpdateGeometryType type = (*i)->GetUpdateGeometryType();
  956. if (type == UPDATE_MAIN_THREAD)
  957. nonThreadedGeometries_.Push(*i);
  958. else if (type == UPDATE_WORKER_THREAD)
  959. threadedGeometries_.Push(*i);
  960. }
  961. if (threadedGeometries_.Size())
  962. {
  963. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  964. int drawablesPerItem = threadedGeometries_.Size() / numWorkItems;
  965. WorkItem item;
  966. item.workFunction_ = UpdateDrawableGeometriesWork;
  967. item.aux_ = const_cast<FrameInfo*>(&frame_);
  968. PODVector<Drawable*>::Iterator start = threadedGeometries_.Begin();
  969. for (int i = 0; i < numWorkItems; ++i)
  970. {
  971. PODVector<Drawable*>::Iterator end = threadedGeometries_.End();
  972. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  973. end = start + drawablesPerItem;
  974. item.start_ = &(*start);
  975. item.end_ = &(*end);
  976. queue->AddWorkItem(item);
  977. start = end;
  978. }
  979. }
  980. // While the work queue is processed, update non-threaded geometries
  981. for (PODVector<Drawable*>::ConstIterator i = nonThreadedGeometries_.Begin(); i != nonThreadedGeometries_.End(); ++i)
  982. (*i)->UpdateGeometry(frame_);
  983. }
  984. // Finally ensure all threaded work has completed
  985. queue->Complete(M_MAX_UNSIGNED);
  986. }
  987. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue, BatchQueue* alphaQueue, bool useLitBase)
  988. {
  989. Light* light = lightQueue.light_;
  990. Zone* zone = GetZone(drawable);
  991. const Vector<SourceBatch>& batches = drawable->GetBatches();
  992. bool hasAmbientGradient = zone->GetAmbientGradient() && zone->GetAmbientStartColor() != zone->GetAmbientEndColor();
  993. // Shadows on transparencies can only be rendered if shadow maps are not reused
  994. bool allowTransparentShadows = !renderer_->GetReuseShadowMaps();
  995. bool allowLitBase = useLitBase && light == drawable->GetFirstLight() && drawable->GetVertexLights().Empty() && !hasAmbientGradient;
  996. for (unsigned i = 0; i < batches.Size(); ++i)
  997. {
  998. const SourceBatch& srcBatch = batches[i];
  999. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  1000. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  1001. continue;
  1002. // Do not create pixel lit forward passes for materials that render into the G-buffer
  1003. if (gBufferPassName_.Value() && tech->HasPass(gBufferPassName_))
  1004. continue;
  1005. Batch destBatch(srcBatch);
  1006. bool isLitAlpha = false;
  1007. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  1008. // Also vertex lighting or ambient gradient require the non-lit base pass, so skip in those cases
  1009. if (i < 32 && allowLitBase)
  1010. {
  1011. destBatch.pass_ = tech->GetPass(litBasePassName_);
  1012. if (destBatch.pass_)
  1013. {
  1014. destBatch.isBase_ = true;
  1015. drawable->SetBasePass(i);
  1016. }
  1017. else
  1018. destBatch.pass_ = tech->GetPass(lightPassName_);
  1019. }
  1020. else
  1021. destBatch.pass_ = tech->GetPass(lightPassName_);
  1022. // If no lit pass, check for lit alpha
  1023. if (!destBatch.pass_)
  1024. {
  1025. destBatch.pass_ = tech->GetPass(litAlphaPassName_);
  1026. isLitAlpha = true;
  1027. }
  1028. // Skip if material does not receive light at all
  1029. if (!destBatch.pass_)
  1030. continue;
  1031. destBatch.camera_ = camera_;
  1032. destBatch.lightQueue_ = &lightQueue;
  1033. destBatch.zone_ = zone;
  1034. if (!isLitAlpha)
  1035. AddBatchToQueue(lightQueue.litBatches_, destBatch, tech);
  1036. else if (alphaQueue)
  1037. {
  1038. // Transparent batches can not be instanced
  1039. AddBatchToQueue(*alphaQueue, destBatch, tech, false, allowTransparentShadows);
  1040. }
  1041. }
  1042. }
  1043. void View::ExecuteRenderPathCommands()
  1044. {
  1045. // If not reusing shadowmaps, render all of them first
  1046. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !lightQueues_.Empty())
  1047. {
  1048. PROFILE(RenderShadowMaps);
  1049. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1050. {
  1051. if (i->shadowMap_)
  1052. RenderShadowMap(*i);
  1053. }
  1054. }
  1055. {
  1056. PROFILE(ExecuteRenderPath);
  1057. // Set for safety in case of empty renderpath
  1058. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1059. currentViewportTexture_ = 0;
  1060. bool viewportModified = false;
  1061. bool isPingponging = false;
  1062. unsigned lastCommandIndex = 0;
  1063. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1064. {
  1065. RenderPathCommand& command = renderPath_->commands_[i];
  1066. if (IsNecessary(command))
  1067. lastCommandIndex = i;
  1068. }
  1069. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1070. {
  1071. RenderPathCommand& command = renderPath_->commands_[i];
  1072. if (!IsNecessary(command))
  1073. continue;
  1074. bool viewportRead = CheckViewportRead(command);
  1075. bool viewportWrite = CheckViewportWrite(command);
  1076. bool beginPingpong = CheckPingpong(i);
  1077. // Has the viewport been modified and will be read as a texture by the current command?
  1078. if (viewportRead && viewportModified)
  1079. {
  1080. // Start pingponging without a blit if already rendering to the substitute render target
  1081. if (currentRenderTarget_ && currentRenderTarget_ == substituteRenderTarget_ && beginPingpong)
  1082. isPingponging = true;
  1083. // If not using pingponging, simply resolve/copy to the first viewport texture
  1084. if (!isPingponging)
  1085. {
  1086. if (!currentRenderTarget_)
  1087. {
  1088. graphics_->ResolveToTexture(viewportTextures_[0], viewRect_);
  1089. currentViewportTexture_ = viewportTextures_[0];
  1090. viewportModified = false;
  1091. }
  1092. else
  1093. {
  1094. if (viewportWrite)
  1095. {
  1096. BlitFramebuffer(static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture()),
  1097. viewportTextures_[0]->GetRenderSurface(), false);
  1098. currentViewportTexture_ = viewportTextures_[0];
  1099. viewportModified = false;
  1100. }
  1101. else
  1102. {
  1103. // If the current render target is already a texture, and we are not writing to it, can read that
  1104. // texture directly instead of blitting. However keep the viewport dirty flag in case a later command
  1105. // will do both read and write, and then we need to blit / resolve
  1106. currentViewportTexture_ = static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture());
  1107. }
  1108. }
  1109. }
  1110. else
  1111. {
  1112. // Swap the pingpong double buffer sides. Texture 0 will be read next
  1113. viewportTextures_[1] = viewportTextures_[0];
  1114. viewportTextures_[0] = static_cast<Texture2D*>(currentRenderTarget_->GetParentTexture());
  1115. currentViewportTexture_ = viewportTextures_[0];
  1116. viewportModified = false;
  1117. }
  1118. }
  1119. if (beginPingpong)
  1120. isPingponging = true;
  1121. // Determine viewport write target
  1122. if (viewportWrite)
  1123. {
  1124. if (isPingponging)
  1125. {
  1126. currentRenderTarget_ = viewportTextures_[1]->GetRenderSurface();
  1127. // If the render path ends into a quad, it can be redirected to the final render target
  1128. if (i == lastCommandIndex && command.type_ == CMD_QUAD)
  1129. currentRenderTarget_ = renderTarget_;
  1130. }
  1131. else
  1132. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1133. }
  1134. switch (command.type_)
  1135. {
  1136. case CMD_CLEAR:
  1137. {
  1138. PROFILE(ClearRenderTarget);
  1139. Color clearColor = command.clearColor_;
  1140. if (command.useFogColor_)
  1141. clearColor = farClipZone_->GetFogColor();
  1142. SetRenderTargets(command);
  1143. graphics_->Clear(command.clearFlags_, clearColor, command.clearDepth_, command.clearStencil_);
  1144. }
  1145. break;
  1146. case CMD_SCENEPASS:
  1147. if (!batchQueues_[command.pass_].IsEmpty())
  1148. {
  1149. PROFILE(RenderScenePass);
  1150. SetRenderTargets(command);
  1151. SetTextures(command);
  1152. graphics_->SetFillMode(camera_->GetFillMode());
  1153. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(), camera_->GetProjection());
  1154. batchQueues_[command.pass_].Draw(this, command.useScissor_, command.markToStencil_);
  1155. }
  1156. break;
  1157. case CMD_QUAD:
  1158. {
  1159. PROFILE(RenderQuad);
  1160. SetRenderTargets(command);
  1161. SetTextures(command);
  1162. RenderQuad(command);
  1163. }
  1164. break;
  1165. case CMD_FORWARDLIGHTS:
  1166. // Render shadow maps + opaque objects' additive lighting
  1167. if (!lightQueues_.Empty())
  1168. {
  1169. PROFILE(RenderLights);
  1170. SetRenderTargets(command);
  1171. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1172. {
  1173. // If reusing shadowmaps, render each of them before the lit batches
  1174. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1175. {
  1176. RenderShadowMap(*i);
  1177. SetRenderTargets(command);
  1178. }
  1179. SetTextures(command);
  1180. graphics_->SetFillMode(camera_->GetFillMode());
  1181. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(), camera_->GetProjection());
  1182. i->litBatches_.Draw(i->light_, this);
  1183. }
  1184. graphics_->SetScissorTest(false);
  1185. graphics_->SetStencilTest(false);
  1186. }
  1187. break;
  1188. case CMD_LIGHTVOLUMES:
  1189. // Render shadow maps + light volumes
  1190. if (!lightQueues_.Empty())
  1191. {
  1192. PROFILE(RenderLightVolumes);
  1193. SetRenderTargets(command);
  1194. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1195. {
  1196. // If reusing shadowmaps, render each of them before the lit batches
  1197. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1198. {
  1199. RenderShadowMap(*i);
  1200. SetRenderTargets(command);
  1201. }
  1202. SetTextures(command);
  1203. for (unsigned j = 0; j < i->volumeBatches_.Size(); ++j)
  1204. {
  1205. SetupLightVolumeBatch(i->volumeBatches_[j]);
  1206. i->volumeBatches_[j].Draw(this);
  1207. }
  1208. }
  1209. graphics_->SetScissorTest(false);
  1210. graphics_->SetStencilTest(false);
  1211. }
  1212. break;
  1213. default:
  1214. break;
  1215. }
  1216. // If current command output to the viewport, mark it modified
  1217. if (viewportWrite)
  1218. viewportModified = true;
  1219. }
  1220. }
  1221. // After executing all commands, reset rendertarget for debug geometry rendering
  1222. graphics_->SetRenderTarget(0, renderTarget_);
  1223. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  1224. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  1225. graphics_->SetDepthStencil(GetDepthStencil(renderTarget_));
  1226. graphics_->SetViewport(viewRect_);
  1227. graphics_->SetFillMode(FILL_SOLID);
  1228. graphics_->SetClipPlane(false);
  1229. }
  1230. void View::SetRenderTargets(RenderPathCommand& command)
  1231. {
  1232. unsigned index = 0;
  1233. IntRect viewPort = viewRect_;
  1234. while (index < command.outputNames_.Size())
  1235. {
  1236. if (!command.outputNames_[index].Compare("viewport", false))
  1237. graphics_->SetRenderTarget(index, currentRenderTarget_);
  1238. else
  1239. {
  1240. StringHash nameHash(command.outputNames_[index]);
  1241. if (renderTargets_.Contains(nameHash))
  1242. {
  1243. Texture2D* texture = renderTargets_[nameHash];
  1244. graphics_->SetRenderTarget(index, texture);
  1245. if (!index)
  1246. {
  1247. // Determine viewport size from rendertarget info
  1248. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1249. {
  1250. const RenderTargetInfo& info = renderPath_->renderTargets_[i];
  1251. if (!info.name_.Compare(command.outputNames_[index], false))
  1252. {
  1253. switch (info.sizeMode_)
  1254. {
  1255. // If absolute or a divided viewport size, use the full texture
  1256. case SIZE_ABSOLUTE:
  1257. case SIZE_VIEWPORTDIVISOR:
  1258. viewPort = IntRect(0, 0, texture->GetWidth(), texture->GetHeight());
  1259. break;
  1260. // If a divided rendertarget size, retain the same viewport, but scaled
  1261. case SIZE_RENDERTARGETDIVISOR:
  1262. if (info.size_.x_ && info.size_.y_)
  1263. {
  1264. viewPort = IntRect(viewRect_.left_ / info.size_.x_, viewRect_.top_ / info.size_.y_,
  1265. viewRect_.right_ / info.size_.x_, viewRect_.bottom_ / info.size_.y_);
  1266. }
  1267. break;
  1268. }
  1269. break;
  1270. }
  1271. }
  1272. }
  1273. }
  1274. else
  1275. graphics_->SetRenderTarget(0, (RenderSurface*)0);
  1276. }
  1277. ++index;
  1278. }
  1279. while (index < MAX_RENDERTARGETS)
  1280. {
  1281. graphics_->SetRenderTarget(index, (RenderSurface*)0);
  1282. ++index;
  1283. }
  1284. graphics_->SetDepthStencil(GetDepthStencil(graphics_->GetRenderTarget(0)));
  1285. graphics_->SetViewport(viewPort);
  1286. graphics_->SetColorWrite(true);
  1287. }
  1288. void View::SetTextures(RenderPathCommand& command)
  1289. {
  1290. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1291. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1292. {
  1293. if (command.textureNames_[i].Empty())
  1294. continue;
  1295. // Bind the rendered output
  1296. if (!command.textureNames_[i].Compare("viewport", false))
  1297. {
  1298. graphics_->SetTexture(i, currentViewportTexture_);
  1299. continue;
  1300. }
  1301. // Bind a rendertarget
  1302. HashMap<StringHash, Texture2D*>::ConstIterator j = renderTargets_.Find(command.textureNames_[i]);
  1303. if (j != renderTargets_.End())
  1304. {
  1305. graphics_->SetTexture(i, j->second_);
  1306. continue;
  1307. }
  1308. // Bind a texture from the resource system
  1309. Texture* texture;
  1310. // Detect cube/3D textures by file extension: they are defined by an XML file
  1311. if (GetExtension(command.textureNames_[i]) == ".xml")
  1312. {
  1313. // Assume 3D textures are only bound to the volume map unit, otherwise it's a cube texture
  1314. if (i == TU_VOLUMEMAP)
  1315. texture = cache->GetResource<Texture3D>(command.textureNames_[i]);
  1316. else
  1317. texture = cache->GetResource<TextureCube>(command.textureNames_[i]);
  1318. }
  1319. else
  1320. texture = cache->GetResource<Texture2D>(command.textureNames_[i]);
  1321. if (texture)
  1322. graphics_->SetTexture(i, texture);
  1323. else
  1324. {
  1325. // If requesting a texture fails, clear the texture name to prevent redundant attempts
  1326. command.textureNames_[i] = String::EMPTY;
  1327. }
  1328. }
  1329. }
  1330. void View::RenderQuad(RenderPathCommand& command)
  1331. {
  1332. // If shader can not be found, clear it from the command to prevent redundant attempts
  1333. /// \todo Do not re-query each frame, as it involves string manipulation
  1334. ShaderVariation* vs = renderer_->GetShader(VS, command.vertexShaderName_, command.vertexShaderDefines_);
  1335. if (!vs)
  1336. command.vertexShaderName_ = String::EMPTY;
  1337. ShaderVariation* ps = renderer_->GetShader(PS, command.pixelShaderName_, command.pixelShaderDefines_);
  1338. if (!ps)
  1339. command.pixelShaderName_ = String::EMPTY;
  1340. // Set shaders & shader parameters and textures
  1341. graphics_->SetShaders(vs, ps);
  1342. const HashMap<StringHash, Variant>& parameters = command.shaderParameters_;
  1343. for (HashMap<StringHash, Variant>::ConstIterator k = parameters.Begin(); k != parameters.End(); ++k)
  1344. graphics_->SetShaderParameter(k->first_, k->second_);
  1345. graphics_->SetShaderParameter(VSP_DELTATIME, frame_.timeStep_);
  1346. graphics_->SetShaderParameter(PSP_DELTATIME, frame_.timeStep_);
  1347. float nearClip = camera_->GetNearClip();
  1348. float farClip = camera_->GetFarClip();
  1349. graphics_->SetShaderParameter(VSP_NEARCLIP, nearClip);
  1350. graphics_->SetShaderParameter(VSP_FARCLIP, farClip);
  1351. graphics_->SetShaderParameter(PSP_NEARCLIP, nearClip);
  1352. graphics_->SetShaderParameter(PSP_FARCLIP, farClip);
  1353. float rtWidth = (float)rtSize_.x_;
  1354. float rtHeight = (float)rtSize_.y_;
  1355. float widthRange = 0.5f * viewSize_.x_ / rtWidth;
  1356. float heightRange = 0.5f * viewSize_.y_ / rtHeight;
  1357. #ifdef USE_OPENGL
  1358. Vector4 bufferUVOffset(((float)viewRect_.left_) / rtWidth + widthRange,
  1359. 1.0f - (((float)viewRect_.top_) / rtHeight + heightRange), widthRange, heightRange);
  1360. #else
  1361. Vector4 bufferUVOffset((0.5f + (float)viewRect_.left_) / rtWidth + widthRange,
  1362. (0.5f + (float)viewRect_.top_) / rtHeight + heightRange, widthRange, heightRange);
  1363. #endif
  1364. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  1365. graphics_->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(1.0f / rtWidth, 1.0f / rtHeight, 0.0f, 0.0f));
  1366. // Set per-rendertarget inverse size / offset shader parameters as necessary
  1367. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1368. {
  1369. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1370. if (!rtInfo.enabled_)
  1371. continue;
  1372. StringHash nameHash(rtInfo.name_);
  1373. if (!renderTargets_.Contains(nameHash))
  1374. continue;
  1375. String invSizeName = rtInfo.name_ + "InvSize";
  1376. String offsetsName = rtInfo.name_ + "Offsets";
  1377. float width = (float)renderTargets_[nameHash]->GetWidth();
  1378. float height = (float)renderTargets_[nameHash]->GetHeight();
  1379. graphics_->SetShaderParameter(invSizeName, Vector4(1.0f / width, 1.0f / height, 0.0f, 0.0f));
  1380. #ifdef USE_OPENGL
  1381. graphics_->SetShaderParameter(offsetsName, Vector4::ZERO);
  1382. #else
  1383. graphics_->SetShaderParameter(offsetsName, Vector4(0.5f / width, 0.5f / height, 0.0f, 0.0f));
  1384. #endif
  1385. }
  1386. graphics_->SetBlendMode(BLEND_REPLACE);
  1387. graphics_->SetDepthTest(CMP_ALWAYS);
  1388. graphics_->SetDepthWrite(false);
  1389. graphics_->SetFillMode(FILL_SOLID);
  1390. graphics_->SetClipPlane(false);
  1391. graphics_->SetScissorTest(false);
  1392. graphics_->SetStencilTest(false);
  1393. DrawFullscreenQuad(false);
  1394. }
  1395. bool View::IsNecessary(const RenderPathCommand& command)
  1396. {
  1397. return command.enabled_ && command.outputNames_.Size() && (command.type_ != CMD_SCENEPASS ||
  1398. !batchQueues_[command.pass_].IsEmpty());
  1399. }
  1400. bool View::CheckViewportRead(const RenderPathCommand& command)
  1401. {
  1402. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1403. {
  1404. if (!command.textureNames_[i].Empty() && !command.textureNames_[i].Compare("viewport", false))
  1405. return true;
  1406. }
  1407. return false;
  1408. }
  1409. bool View::CheckViewportWrite(const RenderPathCommand& command)
  1410. {
  1411. for (unsigned i = 0; i < command.outputNames_.Size(); ++i)
  1412. {
  1413. if (!command.outputNames_[i].Compare("viewport", false))
  1414. return true;
  1415. }
  1416. return false;
  1417. }
  1418. bool View::CheckPingpong(unsigned index)
  1419. {
  1420. // Current command must be a viewport-writing quad to begin the pingpong chain
  1421. RenderPathCommand& current = renderPath_->commands_[index];
  1422. if (current.type_ != CMD_QUAD || !CheckViewportWrite(current))
  1423. return false;
  1424. // If there are commands other than quads that target the viewport, we must keep rendering to the final target and resolving
  1425. // to a viewport texture when necessary instead of pingponging, as a scene pass is not guaranteed to fill the entire viewport
  1426. for (unsigned i = index + 1; i < renderPath_->commands_.Size(); ++i)
  1427. {
  1428. RenderPathCommand& command = renderPath_->commands_[i];
  1429. if (!IsNecessary(command))
  1430. continue;
  1431. if (CheckViewportWrite(command))
  1432. {
  1433. if (command.type_ != CMD_QUAD)
  1434. return false;
  1435. }
  1436. }
  1437. return true;
  1438. }
  1439. void View::AllocateScreenBuffers()
  1440. {
  1441. bool needSubstitute = false;
  1442. unsigned numViewportTextures = 0;
  1443. #ifdef USE_OPENGL
  1444. // Due to FBO limitations, in OpenGL deferred modes need to render to texture first and then blit to the backbuffer
  1445. // Also, if rendering to a texture with full deferred rendering, it must be RGBA to comply with the rest of the buffers.
  1446. if ((deferred_ && !renderTarget_) || (deferredAmbient_ && renderTarget_ && renderTarget_->GetParentTexture()->GetFormat() !=
  1447. Graphics::GetRGBAFormat()))
  1448. needSubstitute = true;
  1449. #endif
  1450. // If backbuffer is antialiased when using deferred rendering, need to reserve a buffer
  1451. if (deferred_ && !renderTarget_ && graphics_->GetMultiSample() > 1)
  1452. needSubstitute = true;
  1453. // Follow final rendertarget format, or use RGB to match the backbuffer format
  1454. unsigned format = renderTarget_ ? renderTarget_->GetParentTexture()->GetFormat() : Graphics::GetRGBFormat();
  1455. // If HDR rendering is enabled use RGBA16f and reserve a buffer
  1456. bool hdrRendering = renderer_->GetHDRRendering();
  1457. if (renderer_->GetHDRRendering())
  1458. {
  1459. format = Graphics::GetRGBAFloat16Format();
  1460. needSubstitute = true;
  1461. }
  1462. #ifdef USE_OPENGL
  1463. if (deferred_ && !hdrRendering)
  1464. format = Graphics::GetRGBAFormat();
  1465. #endif
  1466. // Check for commands which read the viewport, or pingpong between viewport textures
  1467. bool hasViewportRead = false;
  1468. bool hasPingpong = false;
  1469. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1470. {
  1471. const RenderPathCommand& command = renderPath_->commands_[i];
  1472. if (!IsNecessary(command))
  1473. continue;
  1474. if (CheckViewportRead(command))
  1475. hasViewportRead = true;
  1476. if (!hasPingpong && CheckPingpong(i))
  1477. hasPingpong = true;
  1478. }
  1479. if (hasViewportRead)
  1480. {
  1481. ++numViewportTextures;
  1482. // If OpenGL ES, use substitute target to avoid resolve from the backbuffer, which may be slow. However if multisampling
  1483. // is specified, there is no choice
  1484. #ifdef GL_ES_VERSION_2_0
  1485. if (!renderTarget_ && graphics_->GetMultiSample() < 2)
  1486. needSubstitute = true;
  1487. #endif
  1488. // If we have viewport read and target is a cube map, must allocate a substitute target instead as BlitFramebuffer()
  1489. // does not support reading a cube map
  1490. if (renderTarget_ && renderTarget_->GetParentTexture()->GetType() == TextureCube::GetTypeStatic())
  1491. needSubstitute = true;
  1492. if (hasPingpong && !needSubstitute)
  1493. ++numViewportTextures;
  1494. }
  1495. // Allocate screen buffers with filtering active in case the quad commands need that
  1496. // Follow the sRGB mode of the destination render target
  1497. bool sRGB = renderTarget_ ? renderTarget_->GetParentTexture()->GetSRGB() : graphics_->GetSRGB();
  1498. if (needSubstitute)
  1499. {
  1500. substituteRenderTarget_ = needSubstitute ?
  1501. renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, format, true, sRGB)->GetRenderSurface() : (RenderSurface*)0;
  1502. }
  1503. for (unsigned i = 0; i < MAX_VIEWPORT_TEXTURES; ++i)
  1504. {
  1505. viewportTextures_[i] = i < numViewportTextures ? renderer_->GetScreenBuffer(rtSize_.x_, rtSize_.y_, format, true, sRGB) :
  1506. (Texture2D*)0;
  1507. }
  1508. // If using a substitute render target and pingponging, the substitute can act as the second viewport texture
  1509. if (numViewportTextures == 1 && substituteRenderTarget_)
  1510. viewportTextures_[1] = static_cast<Texture2D*>(substituteRenderTarget_->GetParentTexture());
  1511. // Allocate extra render targets defined by the rendering path
  1512. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1513. {
  1514. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1515. if (!rtInfo.enabled_)
  1516. continue;
  1517. unsigned width = rtInfo.size_.x_;
  1518. unsigned height = rtInfo.size_.y_;
  1519. if (rtInfo.sizeMode_ == SIZE_VIEWPORTDIVISOR)
  1520. {
  1521. width = viewSize_.x_ / (width ? width : 1);
  1522. height = viewSize_.y_ / (height ? height : 1);
  1523. }
  1524. if (rtInfo.sizeMode_ == SIZE_RENDERTARGETDIVISOR)
  1525. {
  1526. width = rtSize_.x_ / (width ? width : 1);
  1527. height = rtSize_.y_ / (height ? height : 1);
  1528. }
  1529. renderTargets_[rtInfo.name_] = renderer_->GetScreenBuffer(width, height, rtInfo.format_, rtInfo.filtered_, rtInfo.sRGB_);
  1530. }
  1531. }
  1532. void View::BlitFramebuffer(Texture2D* source, RenderSurface* destination, bool depthWrite)
  1533. {
  1534. if (!source)
  1535. return;
  1536. PROFILE(BlitFramebuffer);
  1537. graphics_->SetBlendMode(BLEND_REPLACE);
  1538. graphics_->SetDepthTest(CMP_ALWAYS);
  1539. graphics_->SetDepthWrite(depthWrite);
  1540. graphics_->SetFillMode(FILL_SOLID);
  1541. graphics_->SetClipPlane(false);
  1542. graphics_->SetScissorTest(false);
  1543. graphics_->SetStencilTest(false);
  1544. graphics_->SetRenderTarget(0, destination);
  1545. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  1546. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  1547. graphics_->SetDepthStencil(GetDepthStencil(destination));
  1548. graphics_->SetViewport(viewRect_);
  1549. String shaderName = "CopyFramebuffer";
  1550. graphics_->SetShaders(renderer_->GetShader(VS, shaderName), renderer_->GetShader(PS, shaderName));
  1551. float rtWidth = (float)rtSize_.x_;
  1552. float rtHeight = (float)rtSize_.y_;
  1553. float widthRange = 0.5f * viewSize_.x_ / rtWidth;
  1554. float heightRange = 0.5f * viewSize_.y_ / rtHeight;
  1555. #ifdef USE_OPENGL
  1556. Vector4 bufferUVOffset(((float)viewRect_.left_) / rtWidth + widthRange,
  1557. 1.0f - (((float)viewRect_.top_) / rtHeight + heightRange), widthRange, heightRange);
  1558. #else
  1559. Vector4 bufferUVOffset((0.5f + (float)viewRect_.left_) / rtWidth + widthRange,
  1560. (0.5f + (float)viewRect_.top_) / rtHeight + heightRange, widthRange, heightRange);
  1561. #endif
  1562. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  1563. graphics_->SetTexture(TU_DIFFUSE, source);
  1564. DrawFullscreenQuad(false);
  1565. }
  1566. void View::DrawFullscreenQuad(bool nearQuad)
  1567. {
  1568. Light* quadDirLight = renderer_->GetQuadDirLight();
  1569. Geometry* geometry = renderer_->GetLightGeometry(quadDirLight);
  1570. Matrix3x4 model = Matrix3x4::IDENTITY;
  1571. Matrix4 projection = Matrix4::IDENTITY;
  1572. #ifdef USE_OPENGL
  1573. if (camera_->GetFlipVertical())
  1574. projection.m11_ = -1.0f;
  1575. model.m23_ = nearQuad ? -1.0f : 1.0f;
  1576. #else
  1577. model.m23_ = nearQuad ? 0.0f : 1.0f;
  1578. #endif
  1579. graphics_->SetCullMode(CULL_NONE);
  1580. graphics_->SetShaderParameter(VSP_MODEL, model);
  1581. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1582. graphics_->ClearTransformSources();
  1583. geometry->Draw(graphics_);
  1584. }
  1585. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  1586. {
  1587. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  1588. float halfViewSize = camera->GetHalfViewSize();
  1589. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  1590. for (PODVector<Drawable*>::Iterator i = occluders.Begin(); i != occluders.End();)
  1591. {
  1592. Drawable* occluder = *i;
  1593. bool erase = false;
  1594. if (!occluder->IsInView(frame_, false))
  1595. occluder->UpdateBatches(frame_);
  1596. // Check occluder's draw distance (in main camera view)
  1597. float maxDistance = occluder->GetDrawDistance();
  1598. if (maxDistance <= 0.0f || occluder->GetDistance() <= maxDistance)
  1599. {
  1600. // Check that occluder is big enough on the screen
  1601. const BoundingBox& box = occluder->GetWorldBoundingBox();
  1602. float diagonal = box.Size().Length();
  1603. float compare;
  1604. if (!camera->IsOrthographic())
  1605. compare = diagonal * halfViewSize / occluder->GetDistance();
  1606. else
  1607. compare = diagonal * invOrthoSize;
  1608. if (compare < occluderSizeThreshold_)
  1609. erase = true;
  1610. else
  1611. {
  1612. // Store amount of triangles divided by screen size as a sorting key
  1613. // (best occluders are big and have few triangles)
  1614. occluder->SetSortValue((float)occluder->GetNumOccluderTriangles() / compare);
  1615. }
  1616. }
  1617. else
  1618. erase = true;
  1619. if (erase)
  1620. i = occluders.Erase(i);
  1621. else
  1622. ++i;
  1623. }
  1624. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1625. if (occluders.Size())
  1626. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1627. }
  1628. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1629. {
  1630. buffer->SetMaxTriangles(maxOccluderTriangles_);
  1631. buffer->Clear();
  1632. for (unsigned i = 0; i < occluders.Size(); ++i)
  1633. {
  1634. Drawable* occluder = occluders[i];
  1635. if (i > 0)
  1636. {
  1637. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1638. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1639. continue;
  1640. }
  1641. // Check for running out of triangles
  1642. if (!occluder->DrawOcclusion(buffer))
  1643. break;
  1644. }
  1645. buffer->BuildDepthHierarchy();
  1646. }
  1647. void View::ProcessLight(LightQueryResult& query, unsigned threadIndex)
  1648. {
  1649. Light* light = query.light_;
  1650. LightType type = light->GetLightType();
  1651. const Frustum& frustum = camera_->GetFrustum();
  1652. // Check if light should be shadowed
  1653. bool isShadowed = drawShadows_ && light->GetCastShadows() && !light->GetPerVertex() && light->GetShadowIntensity() < 1.0f;
  1654. // If shadow distance non-zero, check it
  1655. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  1656. isShadowed = false;
  1657. // OpenGL ES can not support point light shadows
  1658. #ifdef GL_ES_VERSION_2_0
  1659. if (isShadowed && type == LIGHT_POINT)
  1660. isShadowed = false;
  1661. #endif
  1662. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  1663. PODVector<Drawable*>& tempDrawables = tempDrawables_[threadIndex];
  1664. query.litGeometries_.Clear();
  1665. switch (type)
  1666. {
  1667. case LIGHT_DIRECTIONAL:
  1668. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1669. {
  1670. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  1671. query.litGeometries_.Push(geometries_[i]);
  1672. }
  1673. break;
  1674. case LIGHT_SPOT:
  1675. {
  1676. FrustumOctreeQuery octreeQuery(tempDrawables, light->GetFrustum(), DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1677. octree_->GetDrawables(octreeQuery);
  1678. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1679. {
  1680. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1681. query.litGeometries_.Push(tempDrawables[i]);
  1682. }
  1683. }
  1684. break;
  1685. case LIGHT_POINT:
  1686. {
  1687. SphereOctreeQuery octreeQuery(tempDrawables, Sphere(light->GetNode()->GetWorldPosition(), light->GetRange()),
  1688. DRAWABLE_GEOMETRY, camera_->GetViewMask());
  1689. octree_->GetDrawables(octreeQuery);
  1690. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1691. {
  1692. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1693. query.litGeometries_.Push(tempDrawables[i]);
  1694. }
  1695. }
  1696. break;
  1697. }
  1698. // If no lit geometries or not shadowed, no need to process shadow cameras
  1699. if (query.litGeometries_.Empty() || !isShadowed)
  1700. {
  1701. query.numSplits_ = 0;
  1702. return;
  1703. }
  1704. // Determine number of shadow cameras and setup their initial positions
  1705. SetupShadowCameras(query);
  1706. // Process each split for shadow casters
  1707. query.shadowCasters_.Clear();
  1708. for (unsigned i = 0; i < query.numSplits_; ++i)
  1709. {
  1710. Camera* shadowCamera = query.shadowCameras_[i];
  1711. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1712. query.shadowCasterBegin_[i] = query.shadowCasterEnd_[i] = query.shadowCasters_.Size();
  1713. // For point light check that the face is visible: if not, can skip the split
  1714. if (type == LIGHT_POINT && frustum.IsInsideFast(BoundingBox(shadowCameraFrustum)) == OUTSIDE)
  1715. continue;
  1716. // For directional light check that the split is inside the visible scene: if not, can skip the split
  1717. if (type == LIGHT_DIRECTIONAL)
  1718. {
  1719. if (minZ_ > query.shadowFarSplits_[i])
  1720. continue;
  1721. if (maxZ_ < query.shadowNearSplits_[i])
  1722. continue;
  1723. // Reuse lit geometry query for all except directional lights
  1724. ShadowCasterOctreeQuery query(tempDrawables, shadowCameraFrustum, DRAWABLE_GEOMETRY,
  1725. camera_->GetViewMask());
  1726. octree_->GetDrawables(query);
  1727. }
  1728. // Check which shadow casters actually contribute to the shadowing
  1729. ProcessShadowCasters(query, tempDrawables, i);
  1730. }
  1731. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  1732. // only cost has been the shadow camera setup & queries
  1733. if (query.shadowCasters_.Empty())
  1734. query.numSplits_ = 0;
  1735. }
  1736. void View::ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex)
  1737. {
  1738. Light* light = query.light_;
  1739. Camera* shadowCamera = query.shadowCameras_[splitIndex];
  1740. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1741. const Matrix3x4& lightView = shadowCamera->GetView();
  1742. const Matrix4& lightProj = shadowCamera->GetProjection();
  1743. LightType type = light->GetLightType();
  1744. query.shadowCasterBox_[splitIndex].defined_ = false;
  1745. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  1746. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  1747. // frustum, so that shadow casters do not get rendered into unnecessary splits
  1748. Frustum lightViewFrustum;
  1749. if (type != LIGHT_DIRECTIONAL)
  1750. lightViewFrustum = camera_->GetSplitFrustum(minZ_, maxZ_).Transformed(lightView);
  1751. else
  1752. lightViewFrustum = camera_->GetSplitFrustum(Max(minZ_, query.shadowNearSplits_[splitIndex]),
  1753. Min(maxZ_, query.shadowFarSplits_[splitIndex])).Transformed(lightView);
  1754. BoundingBox lightViewFrustumBox(lightViewFrustum);
  1755. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1756. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1757. return;
  1758. BoundingBox lightViewBox;
  1759. BoundingBox lightProjBox;
  1760. for (PODVector<Drawable*>::ConstIterator i = drawables.Begin(); i != drawables.End(); ++i)
  1761. {
  1762. Drawable* drawable = *i;
  1763. // In case this is a point or spot light query result reused for optimization, we may have non-shadowcasters included.
  1764. // Check for that first
  1765. if (!drawable->GetCastShadows())
  1766. continue;
  1767. // Check shadow mask
  1768. if (!(GetShadowMask(drawable) & light->GetLightMask()))
  1769. continue;
  1770. // For point light, check that this drawable is inside the split shadow camera frustum
  1771. if (type == LIGHT_POINT && shadowCameraFrustum.IsInsideFast(drawable->GetWorldBoundingBox()) == OUTSIDE)
  1772. continue;
  1773. // Check shadow distance
  1774. float maxShadowDistance = drawable->GetShadowDistance();
  1775. float drawDistance = drawable->GetDrawDistance();
  1776. bool batchesUpdated = drawable->IsInView(frame_, false);
  1777. if (drawDistance > 0.0f && (maxShadowDistance <= 0.0f || drawDistance < maxShadowDistance))
  1778. maxShadowDistance = drawDistance;
  1779. if (maxShadowDistance > 0.0f)
  1780. {
  1781. if (!batchesUpdated)
  1782. {
  1783. drawable->UpdateBatches(frame_);
  1784. batchesUpdated = true;
  1785. }
  1786. if (drawable->GetDistance() > maxShadowDistance)
  1787. continue;
  1788. }
  1789. // Note: as lights are processed threaded, it is possible a drawable's UpdateBatches() function is called several
  1790. // times. However, this should not cause problems as no scene modification happens at this point.
  1791. if (!batchesUpdated)
  1792. drawable->UpdateBatches(frame_);
  1793. // Project shadow caster bounding box to light view space for visibility check
  1794. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  1795. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  1796. {
  1797. // Merge to shadow caster bounding box and add to the list
  1798. if (type == LIGHT_DIRECTIONAL)
  1799. query.shadowCasterBox_[splitIndex].Merge(lightViewBox);
  1800. else
  1801. {
  1802. lightProjBox = lightViewBox.Projected(lightProj);
  1803. query.shadowCasterBox_[splitIndex].Merge(lightProjBox);
  1804. }
  1805. query.shadowCasters_.Push(drawable);
  1806. }
  1807. }
  1808. query.shadowCasterEnd_[splitIndex] = query.shadowCasters_.Size();
  1809. }
  1810. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  1811. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  1812. {
  1813. if (shadowCamera->IsOrthographic())
  1814. {
  1815. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  1816. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_,lightViewFrustumBox.max_.z_);
  1817. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1818. }
  1819. else
  1820. {
  1821. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  1822. if (drawable->IsInView(frame_))
  1823. return true;
  1824. // For perspective lights, extrusion direction depends on the position of the shadow caster
  1825. Vector3 center = lightViewBox.Center();
  1826. Ray extrusionRay(center, center);
  1827. float extrusionDistance = shadowCamera->GetFarClip();
  1828. float originalDistance = Clamp(center.Length(), M_EPSILON, extrusionDistance);
  1829. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  1830. float sizeFactor = extrusionDistance / originalDistance;
  1831. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  1832. // than necessary, so the test will be conservative
  1833. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  1834. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  1835. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  1836. lightViewBox.Merge(extrudedBox);
  1837. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  1838. }
  1839. }
  1840. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  1841. {
  1842. unsigned width = shadowMap->GetWidth();
  1843. unsigned height = shadowMap->GetHeight();
  1844. int maxCascades = renderer_->GetMaxShadowCascades();
  1845. switch (light->GetLightType())
  1846. {
  1847. case LIGHT_DIRECTIONAL:
  1848. if (maxCascades == 1)
  1849. return IntRect(0, 0, width, height);
  1850. else if (maxCascades == 2)
  1851. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  1852. else
  1853. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  1854. (splitIndex / 2 + 1) * height / 2);
  1855. case LIGHT_SPOT:
  1856. return IntRect(0, 0, width, height);
  1857. case LIGHT_POINT:
  1858. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  1859. (splitIndex / 2 + 1) * height / 3);
  1860. }
  1861. return IntRect();
  1862. }
  1863. void View::SetupShadowCameras(LightQueryResult& query)
  1864. {
  1865. Light* light = query.light_;
  1866. int splits = 0;
  1867. switch (light->GetLightType())
  1868. {
  1869. case LIGHT_DIRECTIONAL:
  1870. {
  1871. const CascadeParameters& cascade = light->GetShadowCascade();
  1872. float nearSplit = camera_->GetNearClip();
  1873. float farSplit;
  1874. while (splits < renderer_->GetMaxShadowCascades())
  1875. {
  1876. // If split is completely beyond camera far clip, we are done
  1877. if (nearSplit > camera_->GetFarClip())
  1878. break;
  1879. farSplit = Min(camera_->GetFarClip(), cascade.splits_[splits]);
  1880. if (farSplit <= nearSplit)
  1881. break;
  1882. // Setup the shadow camera for the split
  1883. Camera* shadowCamera = renderer_->GetShadowCamera();
  1884. query.shadowCameras_[splits] = shadowCamera;
  1885. query.shadowNearSplits_[splits] = nearSplit;
  1886. query.shadowFarSplits_[splits] = farSplit;
  1887. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit);
  1888. nearSplit = farSplit;
  1889. ++splits;
  1890. }
  1891. }
  1892. break;
  1893. case LIGHT_SPOT:
  1894. {
  1895. Camera* shadowCamera = renderer_->GetShadowCamera();
  1896. query.shadowCameras_[0] = shadowCamera;
  1897. Node* cameraNode = shadowCamera->GetNode();
  1898. Node* lightNode = light->GetNode();
  1899. cameraNode->SetTransform(lightNode->GetWorldPosition(), lightNode->GetWorldRotation());
  1900. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1901. shadowCamera->SetFarClip(light->GetRange());
  1902. shadowCamera->SetFov(light->GetFov());
  1903. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  1904. splits = 1;
  1905. }
  1906. break;
  1907. case LIGHT_POINT:
  1908. {
  1909. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  1910. {
  1911. Camera* shadowCamera = renderer_->GetShadowCamera();
  1912. query.shadowCameras_[i] = shadowCamera;
  1913. Node* cameraNode = shadowCamera->GetNode();
  1914. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  1915. cameraNode->SetPosition(light->GetNode()->GetWorldPosition());
  1916. cameraNode->SetDirection(*directions[i]);
  1917. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  1918. shadowCamera->SetFarClip(light->GetRange());
  1919. shadowCamera->SetFov(90.0f);
  1920. shadowCamera->SetAspectRatio(1.0f);
  1921. }
  1922. splits = MAX_CUBEMAP_FACES;
  1923. }
  1924. break;
  1925. }
  1926. query.numSplits_ = splits;
  1927. }
  1928. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit)
  1929. {
  1930. Node* shadowCameraNode = shadowCamera->GetNode();
  1931. Node* lightNode = light->GetNode();
  1932. float extrusionDistance = camera_->GetFarClip();
  1933. const FocusParameters& parameters = light->GetShadowFocus();
  1934. // Calculate initial position & rotation
  1935. Vector3 pos = cameraNode_->GetWorldPosition() - extrusionDistance * lightNode->GetWorldDirection();
  1936. shadowCameraNode->SetTransform(pos, lightNode->GetWorldRotation());
  1937. // Calculate main camera shadowed frustum in light's view space
  1938. farSplit = Min(farSplit, camera_->GetFarClip());
  1939. // Use the scene Z bounds to limit frustum size if applicable
  1940. if (parameters.focus_)
  1941. {
  1942. nearSplit = Max(minZ_, nearSplit);
  1943. farSplit = Min(maxZ_, farSplit);
  1944. }
  1945. Frustum splitFrustum = camera_->GetSplitFrustum(nearSplit, farSplit);
  1946. Polyhedron frustumVolume;
  1947. frustumVolume.Define(splitFrustum);
  1948. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  1949. if (parameters.focus_)
  1950. {
  1951. BoundingBox litGeometriesBox;
  1952. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1953. {
  1954. Drawable* drawable = geometries_[i];
  1955. // Skip skyboxes as they have undefinedly large bounding box size
  1956. if (drawable->GetType() == Skybox::GetTypeStatic())
  1957. continue;
  1958. if (drawable->GetMinZ() <= farSplit && drawable->GetMaxZ() >= nearSplit &&
  1959. (GetLightMask(drawable) & light->GetLightMask()))
  1960. litGeometriesBox.Merge(drawable->GetWorldBoundingBox());
  1961. }
  1962. if (litGeometriesBox.defined_)
  1963. {
  1964. frustumVolume.Clip(litGeometriesBox);
  1965. // If volume became empty, restore it to avoid zero size
  1966. if (frustumVolume.Empty())
  1967. frustumVolume.Define(splitFrustum);
  1968. }
  1969. }
  1970. // Transform frustum volume to light space
  1971. const Matrix3x4& lightView = shadowCamera->GetView();
  1972. frustumVolume.Transform(lightView);
  1973. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  1974. BoundingBox shadowBox;
  1975. if (!parameters.nonUniform_)
  1976. shadowBox.Define(Sphere(frustumVolume));
  1977. else
  1978. shadowBox.Define(frustumVolume);
  1979. shadowCamera->SetOrthographic(true);
  1980. shadowCamera->SetAspectRatio(1.0f);
  1981. shadowCamera->SetNearClip(0.0f);
  1982. shadowCamera->SetFarClip(shadowBox.max_.z_);
  1983. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  1984. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  1985. }
  1986. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  1987. const BoundingBox& shadowCasterBox)
  1988. {
  1989. const FocusParameters& parameters = light->GetShadowFocus();
  1990. float shadowMapWidth = (float)(shadowViewport.Width());
  1991. LightType type = light->GetLightType();
  1992. if (type == LIGHT_DIRECTIONAL)
  1993. {
  1994. BoundingBox shadowBox;
  1995. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  1996. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  1997. shadowBox.min_.y_ = -shadowBox.max_.y_;
  1998. shadowBox.min_.x_ = -shadowBox.max_.x_;
  1999. // Requantize and snap to shadow map texels
  2000. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  2001. }
  2002. if (type == LIGHT_SPOT)
  2003. {
  2004. if (parameters.focus_)
  2005. {
  2006. float viewSizeX = Max(Abs(shadowCasterBox.min_.x_), Abs(shadowCasterBox.max_.x_));
  2007. float viewSizeY = Max(Abs(shadowCasterBox.min_.y_), Abs(shadowCasterBox.max_.y_));
  2008. float viewSize = Max(viewSizeX, viewSizeY);
  2009. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  2010. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  2011. float quantize = parameters.quantize_ * invOrthoSize;
  2012. float minView = parameters.minView_ * invOrthoSize;
  2013. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  2014. if (viewSize < 1.0f)
  2015. shadowCamera->SetZoom(1.0f / viewSize);
  2016. }
  2017. }
  2018. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  2019. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  2020. if (shadowCamera->GetZoom() >= 1.0f)
  2021. {
  2022. if (light->GetLightType() != LIGHT_POINT)
  2023. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  2024. else
  2025. {
  2026. #ifdef USE_OPENGL
  2027. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  2028. #else
  2029. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  2030. #endif
  2031. }
  2032. }
  2033. }
  2034. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  2035. const BoundingBox& viewBox)
  2036. {
  2037. Node* shadowCameraNode = shadowCamera->GetNode();
  2038. const FocusParameters& parameters = light->GetShadowFocus();
  2039. float shadowMapWidth = (float)(shadowViewport.Width());
  2040. float minX = viewBox.min_.x_;
  2041. float minY = viewBox.min_.y_;
  2042. float maxX = viewBox.max_.x_;
  2043. float maxY = viewBox.max_.y_;
  2044. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  2045. Vector2 viewSize(maxX - minX, maxY - minY);
  2046. // Quantize size to reduce swimming
  2047. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  2048. if (parameters.nonUniform_)
  2049. {
  2050. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2051. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  2052. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2053. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  2054. }
  2055. else if (parameters.focus_)
  2056. {
  2057. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  2058. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2059. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2060. viewSize.y_ = viewSize.x_;
  2061. }
  2062. shadowCamera->SetOrthoSize(viewSize);
  2063. // Center shadow camera to the view space bounding box
  2064. Quaternion rot(shadowCameraNode->GetWorldRotation());
  2065. Vector3 adjust(center.x_, center.y_, 0.0f);
  2066. shadowCameraNode->Translate(rot * adjust);
  2067. // If the shadow map viewport is known, snap to whole texels
  2068. if (shadowMapWidth > 0.0f)
  2069. {
  2070. Vector3 viewPos(rot.Inverse() * shadowCameraNode->GetWorldPosition());
  2071. // Take into account that shadow map border will not be used
  2072. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  2073. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  2074. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  2075. shadowCameraNode->Translate(rot * snap);
  2076. }
  2077. }
  2078. void View::FindZone(Drawable* drawable)
  2079. {
  2080. Vector3 center = drawable->GetWorldBoundingBox().Center();
  2081. int bestPriority = M_MIN_INT;
  2082. Zone* newZone = 0;
  2083. // If bounding box center is in view, the zone assignment is conclusive also for next frames. Otherwise it is temporary
  2084. // (possibly incorrect) and must be re-evaluated on the next frame
  2085. bool temporary = !camera_->GetFrustum().IsInside(center);
  2086. // First check if the last zone remains a conclusive result
  2087. Zone* lastZone = drawable->GetLastZone();
  2088. if (lastZone && (lastZone->GetViewMask() & camera_->GetViewMask()) && lastZone->GetPriority() >= highestZonePriority_ &&
  2089. (drawable->GetZoneMask() & lastZone->GetZoneMask()) && lastZone->IsInside(center))
  2090. newZone = lastZone;
  2091. else
  2092. {
  2093. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  2094. {
  2095. Zone* zone = *i;
  2096. int priority = zone->GetPriority();
  2097. if (priority > bestPriority && (drawable->GetZoneMask() & zone->GetZoneMask()) && zone->IsInside(center))
  2098. {
  2099. newZone = zone;
  2100. bestPriority = priority;
  2101. }
  2102. }
  2103. }
  2104. drawable->SetZone(newZone, temporary);
  2105. }
  2106. Technique* View::GetTechnique(Drawable* drawable, Material* material)
  2107. {
  2108. if (!material)
  2109. {
  2110. const Vector<TechniqueEntry>& techniques = renderer_->GetDefaultMaterial()->GetTechniques();
  2111. return techniques.Size() ? techniques[0].technique_ : (Technique*)0;
  2112. }
  2113. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  2114. // If only one technique, no choice
  2115. if (techniques.Size() == 1)
  2116. return techniques[0].technique_;
  2117. else
  2118. {
  2119. float lodDistance = drawable->GetLodDistance();
  2120. // Check for suitable technique. Techniques should be ordered like this:
  2121. // Most distant & highest quality
  2122. // Most distant & lowest quality
  2123. // Second most distant & highest quality
  2124. // ...
  2125. for (unsigned i = 0; i < techniques.Size(); ++i)
  2126. {
  2127. const TechniqueEntry& entry = techniques[i];
  2128. Technique* tech = entry.technique_;
  2129. #ifdef USE_OPENGL
  2130. if (!tech || materialQuality_ < entry.qualityLevel_)
  2131. continue;
  2132. #else
  2133. if (!tech || (tech->IsSM3() && !graphics_->GetSM3Support()) || materialQuality_ < entry.qualityLevel_)
  2134. continue;
  2135. #endif
  2136. if (lodDistance >= entry.lodDistance_)
  2137. return tech;
  2138. }
  2139. // If no suitable technique found, fallback to the last
  2140. return techniques.Size() ? techniques.Back().technique_ : (Technique*)0;
  2141. }
  2142. }
  2143. void View::CheckMaterialForAuxView(Material* material)
  2144. {
  2145. const SharedPtr<Texture>* textures = material->GetTextures();
  2146. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  2147. {
  2148. Texture* texture = textures[i];
  2149. if (texture && texture->GetUsage() == TEXTURE_RENDERTARGET)
  2150. {
  2151. // Have to check cube & 2D textures separately
  2152. if (texture->GetType() == Texture2D::GetTypeStatic())
  2153. {
  2154. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  2155. RenderSurface* target = tex2D->GetRenderSurface();
  2156. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2157. target->QueueUpdate();
  2158. }
  2159. else if (texture->GetType() == TextureCube::GetTypeStatic())
  2160. {
  2161. TextureCube* texCube = static_cast<TextureCube*>(texture);
  2162. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  2163. {
  2164. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  2165. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2166. target->QueueUpdate();
  2167. }
  2168. }
  2169. }
  2170. }
  2171. // Flag as processed so we can early-out next time we come across this material on the same frame
  2172. material->MarkForAuxView(frame_.frameNumber_);
  2173. }
  2174. void View::AddBatchToQueue(BatchQueue& batchQueue, Batch& batch, Technique* tech, bool allowInstancing, bool allowShadows)
  2175. {
  2176. if (!batch.material_)
  2177. batch.material_ = renderer_->GetDefaultMaterial();
  2178. // Convert to instanced if possible
  2179. if (allowInstancing && batch.geometryType_ == GEOM_STATIC && batch.geometry_->GetIndexBuffer() && !batch.overrideView_)
  2180. batch.geometryType_ = GEOM_INSTANCED;
  2181. if (batch.geometryType_ == GEOM_INSTANCED)
  2182. {
  2183. HashMap<BatchGroupKey, BatchGroup>* groups = batch.isBase_ ? &batchQueue.baseBatchGroups_ : &batchQueue.batchGroups_;
  2184. BatchGroupKey key(batch);
  2185. HashMap<BatchGroupKey, BatchGroup>::Iterator i = groups->Find(key);
  2186. if (i == groups->End())
  2187. {
  2188. // Create a new group based on the batch
  2189. // In case the group remains below the instancing limit, do not enable instancing shaders yet
  2190. BatchGroup newGroup(batch);
  2191. newGroup.geometryType_ = GEOM_STATIC;
  2192. renderer_->SetBatchShaders(newGroup, tech, allowShadows);
  2193. newGroup.CalculateSortKey();
  2194. i = groups->Insert(MakePair(key, newGroup));
  2195. }
  2196. int oldSize = i->second_.instances_.Size();
  2197. i->second_.AddTransforms(batch);
  2198. // Convert to using instancing shaders when the instancing limit is reached
  2199. if (oldSize < minInstances_ && (int)i->second_.instances_.Size() >= minInstances_)
  2200. {
  2201. i->second_.geometryType_ = GEOM_INSTANCED;
  2202. renderer_->SetBatchShaders(i->second_, tech, allowShadows);
  2203. i->second_.CalculateSortKey();
  2204. }
  2205. }
  2206. else
  2207. {
  2208. renderer_->SetBatchShaders(batch, tech, allowShadows);
  2209. batch.CalculateSortKey();
  2210. batchQueue.batches_.Push(batch);
  2211. }
  2212. }
  2213. void View::PrepareInstancingBuffer()
  2214. {
  2215. PROFILE(PrepareInstancingBuffer);
  2216. unsigned totalInstances = 0;
  2217. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2218. totalInstances += i->second_.GetNumInstances();
  2219. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2220. {
  2221. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2222. totalInstances += i->shadowSplits_[j].shadowBatches_.GetNumInstances();
  2223. totalInstances += i->litBatches_.GetNumInstances();
  2224. }
  2225. // If fail to set buffer size, fall back to per-group locking
  2226. if (totalInstances && renderer_->ResizeInstancingBuffer(totalInstances))
  2227. {
  2228. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  2229. unsigned freeIndex = 0;
  2230. void* dest = instancingBuffer->Lock(0, totalInstances, true);
  2231. if (!dest)
  2232. return;
  2233. for (HashMap<StringHash, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2234. i->second_.SetTransforms(dest, freeIndex);
  2235. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2236. {
  2237. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2238. i->shadowSplits_[j].shadowBatches_.SetTransforms(dest, freeIndex);
  2239. i->litBatches_.SetTransforms(dest, freeIndex);
  2240. }
  2241. instancingBuffer->Unlock();
  2242. }
  2243. }
  2244. void View::SetupLightVolumeBatch(Batch& batch)
  2245. {
  2246. Light* light = batch.lightQueue_->light_;
  2247. LightType type = light->GetLightType();
  2248. Vector3 cameraPos = cameraNode_->GetWorldPosition();
  2249. float lightDist;
  2250. graphics_->SetBlendMode(BLEND_ADD);
  2251. graphics_->SetDepthBias(0.0f, 0.0f);
  2252. graphics_->SetDepthWrite(false);
  2253. graphics_->SetFillMode(FILL_SOLID);
  2254. graphics_->SetClipPlane(false);
  2255. if (type != LIGHT_DIRECTIONAL)
  2256. {
  2257. if (type == LIGHT_POINT)
  2258. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  2259. else
  2260. lightDist = light->GetFrustum().Distance(cameraPos);
  2261. // Draw front faces if not inside light volume
  2262. if (lightDist < camera_->GetNearClip() * 2.0f)
  2263. {
  2264. renderer_->SetCullMode(CULL_CW, camera_);
  2265. graphics_->SetDepthTest(CMP_GREATER);
  2266. }
  2267. else
  2268. {
  2269. renderer_->SetCullMode(CULL_CCW, camera_);
  2270. graphics_->SetDepthTest(CMP_LESSEQUAL);
  2271. }
  2272. }
  2273. else
  2274. {
  2275. // In case the same camera is used for multiple views with differing aspect ratios (not recommended)
  2276. // refresh the directional light's model transform before rendering
  2277. light->GetVolumeTransform(camera_);
  2278. graphics_->SetCullMode(CULL_NONE);
  2279. graphics_->SetDepthTest(CMP_ALWAYS);
  2280. }
  2281. graphics_->SetScissorTest(false);
  2282. graphics_->SetStencilTest(true, CMP_NOTEQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 0, light->GetLightMask());
  2283. }
  2284. void View::RenderShadowMap(const LightBatchQueue& queue)
  2285. {
  2286. PROFILE(RenderShadowMap);
  2287. Texture2D* shadowMap = queue.shadowMap_;
  2288. graphics_->SetTexture(TU_SHADOWMAP, 0);
  2289. graphics_->SetColorWrite(false);
  2290. graphics_->SetFillMode(FILL_SOLID);
  2291. graphics_->SetClipPlane(false);
  2292. graphics_->SetStencilTest(false);
  2293. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  2294. graphics_->SetDepthStencil(shadowMap);
  2295. graphics_->SetViewport(IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  2296. graphics_->Clear(CLEAR_DEPTH);
  2297. // Set shadow depth bias
  2298. const BiasParameters& parameters = queue.light_->GetShadowBias();
  2299. // Render each of the splits
  2300. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  2301. {
  2302. float multiplier = 1.0f;
  2303. // For directional light cascade splits, adjust depth bias according to the far clip ratio of the splits
  2304. if (i > 0 && queue.light_->GetLightType() == LIGHT_DIRECTIONAL)
  2305. {
  2306. multiplier = Max(queue.shadowSplits_[i].shadowCamera_->GetFarClip() / queue.shadowSplits_[0].shadowCamera_->GetFarClip(), 1.0f);
  2307. multiplier = 1.0f + (multiplier - 1.0f) * queue.light_->GetShadowCascade().biasAutoAdjust_;
  2308. }
  2309. graphics_->SetDepthBias(multiplier * parameters.constantBias_, multiplier * parameters.slopeScaledBias_);
  2310. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  2311. if (!shadowQueue.shadowBatches_.IsEmpty())
  2312. {
  2313. graphics_->SetViewport(shadowQueue.shadowViewport_);
  2314. shadowQueue.shadowBatches_.Draw(this);
  2315. }
  2316. }
  2317. graphics_->SetColorWrite(true);
  2318. graphics_->SetDepthBias(0.0f, 0.0f);
  2319. }
  2320. RenderSurface* View::GetDepthStencil(RenderSurface* renderTarget)
  2321. {
  2322. // If using the backbuffer, return the backbuffer depth-stencil
  2323. if (!renderTarget)
  2324. return 0;
  2325. // Then check for linked depth-stencil
  2326. RenderSurface* depthStencil = renderTarget->GetLinkedDepthStencil();
  2327. // Finally get one from Renderer
  2328. if (!depthStencil)
  2329. depthStencil = renderer_->GetDepthStencil(renderTarget->GetWidth(), renderTarget->GetHeight());
  2330. return depthStencil;
  2331. }
  2332. }