View.cpp 99 KB

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