View.cpp 100 KB

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