View.cpp 100 KB

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