View.cpp 100 KB

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