View.cpp 100 KB

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