View.cpp 94 KB

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