View.cpp 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Profiler.h"
  24. #include "../Core/WorkQueue.h"
  25. #include "../Graphics/Camera.h"
  26. #include "../Graphics/DebugRenderer.h"
  27. #include "../Graphics/Geometry.h"
  28. #include "../Graphics/Graphics.h"
  29. #include "../Graphics/GraphicsEvents.h"
  30. #include "../Graphics/GraphicsImpl.h"
  31. #include "../Graphics/Material.h"
  32. #include "../Graphics/OcclusionBuffer.h"
  33. #include "../Graphics/Octree.h"
  34. #include "../Graphics/Renderer.h"
  35. #include "../Graphics/RenderPath.h"
  36. #include "../Graphics/ShaderVariation.h"
  37. #include "../Graphics/Skybox.h"
  38. #include "../Graphics/Technique.h"
  39. #include "../Graphics/Texture2D.h"
  40. #include "../Graphics/Texture3D.h"
  41. #include "../Graphics/TextureCube.h"
  42. #include "../Graphics/VertexBuffer.h"
  43. #include "../Graphics/View.h"
  44. #include "../IO/FileSystem.h"
  45. #include "../IO/Log.h"
  46. #include "../Resource/ResourceCache.h"
  47. #include "../Scene/Scene.h"
  48. #include "../UI/UI.h"
  49. #include "../DebugNew.h"
  50. namespace Urho3D
  51. {
  52. static const Vector3* directions[] =
  53. {
  54. &Vector3::RIGHT,
  55. &Vector3::LEFT,
  56. &Vector3::UP,
  57. &Vector3::DOWN,
  58. &Vector3::FORWARD,
  59. &Vector3::BACK
  60. };
  61. /// %Frustum octree query for shadowcasters.
  62. class ShadowCasterOctreeQuery : public FrustumOctreeQuery
  63. {
  64. public:
  65. /// Construct with frustum and query parameters.
  66. ShadowCasterOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  67. unsigned viewMask = DEFAULT_VIEWMASK) :
  68. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask)
  69. {
  70. }
  71. /// Intersection test for drawables.
  72. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  73. {
  74. while (start != end)
  75. {
  76. Drawable* drawable = *start++;
  77. if (drawable->GetCastShadows() && (drawable->GetDrawableFlags() & drawableFlags_) &&
  78. (drawable->GetViewMask() & viewMask_))
  79. {
  80. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  81. result_.Push(drawable);
  82. }
  83. }
  84. }
  85. };
  86. /// %Frustum octree query for zones and occluders.
  87. class ZoneOccluderOctreeQuery : public FrustumOctreeQuery
  88. {
  89. public:
  90. /// Construct with frustum and query parameters.
  91. ZoneOccluderOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, unsigned char drawableFlags = DRAWABLE_ANY,
  92. unsigned viewMask = DEFAULT_VIEWMASK) :
  93. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask)
  94. {
  95. }
  96. /// Intersection test for drawables.
  97. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  98. {
  99. while (start != end)
  100. {
  101. Drawable* drawable = *start++;
  102. unsigned char flags = drawable->GetDrawableFlags();
  103. if ((flags == DRAWABLE_ZONE || (flags == DRAWABLE_GEOMETRY && drawable->IsOccluder())) &&
  104. (drawable->GetViewMask() & viewMask_))
  105. {
  106. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  107. result_.Push(drawable);
  108. }
  109. }
  110. }
  111. };
  112. /// %Frustum octree query with occlusion.
  113. class OccludedFrustumOctreeQuery : public FrustumOctreeQuery
  114. {
  115. public:
  116. /// Construct with frustum, occlusion buffer and query parameters.
  117. OccludedFrustumOctreeQuery(PODVector<Drawable*>& result, const Frustum& frustum, OcclusionBuffer* buffer,
  118. unsigned char drawableFlags = DRAWABLE_ANY, unsigned viewMask = DEFAULT_VIEWMASK) :
  119. FrustumOctreeQuery(result, frustum, drawableFlags, viewMask),
  120. buffer_(buffer)
  121. {
  122. }
  123. /// Intersection test for an octant.
  124. virtual Intersection TestOctant(const BoundingBox& box, bool inside)
  125. {
  126. if (inside)
  127. return buffer_->IsVisible(box) ? INSIDE : OUTSIDE;
  128. else
  129. {
  130. Intersection result = frustum_.IsInside(box);
  131. if (result != OUTSIDE && !buffer_->IsVisible(box))
  132. result = OUTSIDE;
  133. return result;
  134. }
  135. }
  136. /// Intersection test for drawables. Note: drawable occlusion is performed later in worker threads.
  137. virtual void TestDrawables(Drawable** start, Drawable** end, bool inside)
  138. {
  139. while (start != end)
  140. {
  141. Drawable* drawable = *start++;
  142. if ((drawable->GetDrawableFlags() & drawableFlags_) && (drawable->GetViewMask() & viewMask_))
  143. {
  144. if (inside || frustum_.IsInsideFast(drawable->GetWorldBoundingBox()))
  145. result_.Push(drawable);
  146. }
  147. }
  148. }
  149. /// Occlusion buffer.
  150. OcclusionBuffer* buffer_;
  151. };
  152. void CheckVisibilityWork(const WorkItem* item, unsigned threadIndex)
  153. {
  154. View* view = reinterpret_cast<View*>(item->aux_);
  155. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  156. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  157. OcclusionBuffer* buffer = view->occlusionBuffer_;
  158. const Matrix3x4& viewMatrix = view->cullCamera_->GetView();
  159. Vector3 viewZ = Vector3(viewMatrix.m20_, viewMatrix.m21_, viewMatrix.m22_);
  160. Vector3 absViewZ = viewZ.Abs();
  161. unsigned cameraViewMask = view->cullCamera_->GetViewMask();
  162. bool cameraZoneOverride = view->cameraZoneOverride_;
  163. PerThreadSceneResult& result = view->sceneResults_[threadIndex];
  164. while (start != end)
  165. {
  166. Drawable* drawable = *start++;
  167. if (!buffer || !drawable->IsOccludee() || buffer->IsVisible(drawable->GetWorldBoundingBox()))
  168. {
  169. drawable->UpdateBatches(view->frame_);
  170. // If draw distance non-zero, update and check it
  171. float maxDistance = drawable->GetDrawDistance();
  172. if (maxDistance > 0.0f)
  173. {
  174. if (drawable->GetDistance() > maxDistance)
  175. continue;
  176. }
  177. drawable->MarkInView(view->frame_);
  178. // For geometries, find zone, clear lights and calculate view space Z range
  179. if (drawable->GetDrawableFlags() & DRAWABLE_GEOMETRY)
  180. {
  181. Zone* drawableZone = drawable->GetZone();
  182. if (!cameraZoneOverride &&
  183. (drawable->IsZoneDirty() || !drawableZone || (drawableZone->GetViewMask() & cameraViewMask) == 0))
  184. view->FindZone(drawable);
  185. const BoundingBox& geomBox = drawable->GetWorldBoundingBox();
  186. Vector3 center = geomBox.Center();
  187. Vector3 edge = geomBox.Size() * 0.5f;
  188. // Do not add "infinite" objects like skybox to prevent shadow map focusing behaving erroneously
  189. if (edge.LengthSquared() < M_LARGE_VALUE * M_LARGE_VALUE)
  190. {
  191. float viewCenterZ = viewZ.DotProduct(center) + viewMatrix.m23_;
  192. float viewEdgeZ = absViewZ.DotProduct(edge);
  193. float minZ = viewCenterZ - viewEdgeZ;
  194. float maxZ = viewCenterZ + viewEdgeZ;
  195. drawable->SetMinMaxZ(viewCenterZ - viewEdgeZ, viewCenterZ + viewEdgeZ);
  196. result.minZ_ = Min(result.minZ_, minZ);
  197. result.maxZ_ = Max(result.maxZ_, maxZ);
  198. }
  199. else
  200. drawable->SetMinMaxZ(M_LARGE_VALUE, M_LARGE_VALUE);
  201. result.geometries_.Push(drawable);
  202. }
  203. else if (drawable->GetDrawableFlags() & DRAWABLE_LIGHT)
  204. {
  205. Light* light = static_cast<Light*>(drawable);
  206. // Skip lights with zero brightness or black color
  207. if (!light->GetEffectiveColor().Equals(Color::BLACK))
  208. result.lights_.Push(light);
  209. }
  210. }
  211. }
  212. }
  213. void ProcessLightWork(const WorkItem* item, unsigned threadIndex)
  214. {
  215. View* view = reinterpret_cast<View*>(item->aux_);
  216. LightQueryResult* query = reinterpret_cast<LightQueryResult*>(item->start_);
  217. view->ProcessLight(*query, threadIndex);
  218. }
  219. void UpdateDrawableGeometriesWork(const WorkItem* item, unsigned threadIndex)
  220. {
  221. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  222. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  223. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  224. while (start != end)
  225. {
  226. Drawable* drawable = *start++;
  227. // We may leave null pointer holes in the queue if a drawable is found out to require a main thread update
  228. if (drawable)
  229. drawable->UpdateGeometry(frame);
  230. }
  231. }
  232. void SortBatchQueueFrontToBackWork(const WorkItem* item, unsigned threadIndex)
  233. {
  234. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  235. queue->SortFrontToBack();
  236. }
  237. void SortBatchQueueBackToFrontWork(const WorkItem* item, unsigned threadIndex)
  238. {
  239. BatchQueue* queue = reinterpret_cast<BatchQueue*>(item->start_);
  240. queue->SortBackToFront();
  241. }
  242. void SortLightQueueWork(const WorkItem* item, unsigned threadIndex)
  243. {
  244. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  245. start->litBaseBatches_.SortFrontToBack();
  246. start->litBatches_.SortFrontToBack();
  247. }
  248. void SortShadowQueueWork(const WorkItem* item, unsigned threadIndex)
  249. {
  250. LightBatchQueue* start = reinterpret_cast<LightBatchQueue*>(item->start_);
  251. for (unsigned i = 0; i < start->shadowSplits_.Size(); ++i)
  252. start->shadowSplits_[i].shadowBatches_.SortFrontToBack();
  253. }
  254. View::View(Context* context) :
  255. Object(context),
  256. graphics_(GetSubsystem<Graphics>()),
  257. renderer_(GetSubsystem<Renderer>()),
  258. scene_(0),
  259. octree_(0),
  260. cullCamera_(0),
  261. camera_(0),
  262. sourceView_(0),
  263. cameraZone_(0),
  264. farClipZone_(0),
  265. occlusionBuffer_(0),
  266. renderTarget_(0),
  267. substituteRenderTarget_(0)
  268. {
  269. // Create octree query and scene results vector for each thread
  270. unsigned numThreads = GetSubsystem<WorkQueue>()->GetNumThreads() + 1; // Worker threads + main thread
  271. tempDrawables_.Resize(numThreads);
  272. sceneResults_.Resize(numThreads);
  273. frame_.camera_ = 0;
  274. }
  275. View::~View()
  276. {
  277. }
  278. bool View::Define(RenderSurface* renderTarget, Viewport* viewport)
  279. {
  280. sourceView_ = 0;
  281. renderPath_ = viewport->GetRenderPath();
  282. if (!renderPath_)
  283. return false;
  284. renderTarget_ = renderTarget;
  285. drawDebug_ = viewport->GetDrawDebug();
  286. // Validate the rect and calculate size. If zero rect, use whole rendertarget size
  287. int rtWidth = renderTarget ? renderTarget->GetWidth() : graphics_->GetWidth();
  288. int rtHeight = renderTarget ? renderTarget->GetHeight() : graphics_->GetHeight();
  289. const IntRect& rect = viewport->GetRect();
  290. if (rect != IntRect::ZERO)
  291. {
  292. viewRect_.left_ = Clamp(rect.left_, 0, rtWidth - 1);
  293. viewRect_.top_ = Clamp(rect.top_, 0, rtHeight - 1);
  294. viewRect_.right_ = Clamp(rect.right_, viewRect_.left_ + 1, rtWidth);
  295. viewRect_.bottom_ = Clamp(rect.bottom_, viewRect_.top_ + 1, rtHeight);
  296. }
  297. else
  298. viewRect_ = IntRect(0, 0, rtWidth, rtHeight);
  299. viewSize_ = viewRect_.Size();
  300. rtSize_ = IntVector2(rtWidth, rtHeight);
  301. // On OpenGL flip the viewport if rendering to a texture for consistent UV addressing with Direct3D9
  302. #ifdef URHO3D_OPENGL
  303. if (renderTarget_)
  304. {
  305. viewRect_.bottom_ = rtHeight - viewRect_.top_;
  306. viewRect_.top_ = viewRect_.bottom_ - viewSize_.y_;
  307. }
  308. #endif
  309. scene_ = viewport->GetScene();
  310. cullCamera_ = viewport->GetCullCamera();
  311. camera_ = viewport->GetCamera();
  312. if (!cullCamera_)
  313. cullCamera_ = camera_;
  314. else
  315. {
  316. // If view specifies a culling camera (view preparation sharing), check if already prepared
  317. sourceView_ = renderer_->GetPreparedView(cullCamera_);
  318. if (sourceView_ && sourceView_->scene_ == scene_ && sourceView_->renderPath_ == renderPath_)
  319. {
  320. // Copy properties needed later in rendering
  321. deferred_ = sourceView_->deferred_;
  322. deferredAmbient_ = sourceView_->deferredAmbient_;
  323. useLitBase_ = sourceView_->useLitBase_;
  324. hasScenePasses_ = sourceView_->hasScenePasses_;
  325. noStencil_ = sourceView_->noStencil_;
  326. lightVolumeCommand_ = sourceView_->lightVolumeCommand_;
  327. octree_ = sourceView_->octree_;
  328. return true;
  329. }
  330. else
  331. {
  332. // Mismatch in scene or renderpath, fall back to unique view preparation
  333. sourceView_ = 0;
  334. }
  335. }
  336. // Set default passes
  337. gBufferPassIndex_ = M_MAX_UNSIGNED;
  338. basePassIndex_ = Technique::GetPassIndex("base");
  339. alphaPassIndex_ = Technique::GetPassIndex("alpha");
  340. lightPassIndex_ = Technique::GetPassIndex("light");
  341. litBasePassIndex_ = Technique::GetPassIndex("litbase");
  342. litAlphaPassIndex_ = Technique::GetPassIndex("litalpha");
  343. deferred_ = false;
  344. deferredAmbient_ = false;
  345. useLitBase_ = false;
  346. hasScenePasses_ = false;
  347. noStencil_ = false;
  348. lightVolumeCommand_ = 0;
  349. scenePasses_.Clear();
  350. geometriesUpdated_ = false;
  351. #ifdef URHO3D_OPENGL
  352. #ifdef GL_ES_VERSION_2_0
  353. // On OpenGL ES we assume a stencil is not available or would not give a good performance, and disable light stencil
  354. // optimizations in any case
  355. noStencil_ = true;
  356. #else
  357. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  358. {
  359. const RenderPathCommand& command = renderPath_->commands_[i];
  360. if (!command.enabled_)
  361. continue;
  362. if (command.depthStencilName_.Length())
  363. {
  364. // Using a readable depth texture will disable light stencil optimizations on OpenGL, as for compatibility reasons
  365. // we are using a depth format without stencil channel
  366. noStencil_ = true;
  367. break;
  368. }
  369. }
  370. #endif
  371. #endif
  372. // Make sure that all necessary batch queues exist
  373. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  374. {
  375. RenderPathCommand& command = renderPath_->commands_[i];
  376. if (!command.enabled_)
  377. continue;
  378. if (command.type_ == CMD_SCENEPASS)
  379. {
  380. hasScenePasses_ = true;
  381. ScenePassInfo info;
  382. info.passIndex_ = command.passIndex_ = Technique::GetPassIndex(command.pass_);
  383. info.allowInstancing_ = command.sortMode_ != SORT_BACKTOFRONT;
  384. info.markToStencil_ = !noStencil_ && command.markToStencil_;
  385. info.vertexLights_ = command.vertexLights_;
  386. // Check scenepass metadata for defining custom passes which interact with lighting
  387. if (!command.metadata_.Empty())
  388. {
  389. if (command.metadata_ == "gbuffer")
  390. gBufferPassIndex_ = command.passIndex_;
  391. else if (command.metadata_ == "base" && command.pass_ != "base")
  392. {
  393. basePassIndex_ = command.passIndex_;
  394. litBasePassIndex_ = Technique::GetPassIndex("lit" + command.pass_);
  395. }
  396. else if (command.metadata_ == "alpha" && command.pass_ != "alpha")
  397. {
  398. alphaPassIndex_ = command.passIndex_;
  399. litAlphaPassIndex_ = Technique::GetPassIndex("lit" + command.pass_);
  400. }
  401. }
  402. HashMap<unsigned, BatchQueue>::Iterator j = batchQueues_.Find(info.passIndex_);
  403. if (j == batchQueues_.End())
  404. j = batchQueues_.Insert(Pair<unsigned, BatchQueue>(info.passIndex_, BatchQueue()));
  405. info.batchQueue_ = &j->second_;
  406. scenePasses_.Push(info);
  407. }
  408. // Allow a custom forward light pass
  409. else if (command.type_ == CMD_FORWARDLIGHTS && !command.pass_.Empty())
  410. lightPassIndex_ = command.passIndex_ = Technique::GetPassIndex(command.pass_);
  411. }
  412. octree_ = 0;
  413. // Get default zone first in case we do not have zones defined
  414. cameraZone_ = farClipZone_ = renderer_->GetDefaultZone();
  415. if (hasScenePasses_)
  416. {
  417. if (!scene_ || !cullCamera_ || !cullCamera_->IsEnabledEffective())
  418. return false;
  419. // If scene is loading scene content asynchronously, it is incomplete and should not be rendered
  420. if (scene_->IsAsyncLoading() && scene_->GetAsyncLoadMode() > LOAD_RESOURCES_ONLY)
  421. return false;
  422. octree_ = scene_->GetComponent<Octree>();
  423. if (!octree_)
  424. return false;
  425. // Do not accept view if camera projection is illegal
  426. // (there is a possibility of crash if occlusion is used and it can not clip properly)
  427. if (!cullCamera_->IsProjectionValid())
  428. return false;
  429. }
  430. // Go through commands to check for deferred rendering and other flags
  431. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  432. {
  433. const RenderPathCommand& command = renderPath_->commands_[i];
  434. if (!command.enabled_)
  435. continue;
  436. // Check if ambient pass and G-buffer rendering happens at the same time
  437. if (command.type_ == CMD_SCENEPASS && command.outputs_.Size() > 1)
  438. {
  439. if (CheckViewportWrite(command))
  440. deferredAmbient_ = true;
  441. }
  442. else if (command.type_ == CMD_LIGHTVOLUMES)
  443. {
  444. lightVolumeCommand_ = &command;
  445. deferred_ = true;
  446. }
  447. else if (command.type_ == CMD_FORWARDLIGHTS)
  448. useLitBase_ = command.useLitBase_;
  449. }
  450. drawShadows_ = renderer_->GetDrawShadows();
  451. materialQuality_ = renderer_->GetMaterialQuality();
  452. maxOccluderTriangles_ = renderer_->GetMaxOccluderTriangles();
  453. minInstances_ = renderer_->GetMinInstances();
  454. // Set possible quality overrides from the camera
  455. // Note that the culling camera is used here (its settings are authoritative) while the render camera
  456. // will be just used for the final view & projection matrices
  457. unsigned viewOverrideFlags = cullCamera_ ? cullCamera_->GetViewOverrideFlags() : VO_NONE;
  458. if (viewOverrideFlags & VO_LOW_MATERIAL_QUALITY)
  459. materialQuality_ = QUALITY_LOW;
  460. if (viewOverrideFlags & VO_DISABLE_SHADOWS)
  461. drawShadows_ = false;
  462. if (viewOverrideFlags & VO_DISABLE_OCCLUSION)
  463. maxOccluderTriangles_ = 0;
  464. // Occlusion buffer has constant width. If resulting height would be too large due to aspect ratio, disable occlusion
  465. if (viewSize_.y_ > viewSize_.x_ * 4)
  466. maxOccluderTriangles_ = 0;
  467. return true;
  468. }
  469. void View::Update(const FrameInfo& frame)
  470. {
  471. // No need to update if using another prepared view
  472. if (sourceView_)
  473. return;
  474. frame_.camera_ = cullCamera_;
  475. frame_.timeStep_ = frame.timeStep_;
  476. frame_.frameNumber_ = frame.frameNumber_;
  477. frame_.viewSize_ = viewSize_;
  478. using namespace BeginViewUpdate;
  479. VariantMap& eventData = GetEventDataMap();
  480. eventData[P_VIEW] = this;
  481. eventData[P_SURFACE] = renderTarget_;
  482. eventData[P_TEXTURE] = (renderTarget_ ? renderTarget_->GetParentTexture() : 0);
  483. eventData[P_SCENE] = scene_;
  484. eventData[P_CAMERA] = cullCamera_;
  485. renderer_->SendEvent(E_BEGINVIEWUPDATE, eventData);
  486. int maxSortedInstances = renderer_->GetMaxSortedInstances();
  487. // Clear buffers, geometry, light, occluder & batch list
  488. renderTargets_.Clear();
  489. geometries_.Clear();
  490. lights_.Clear();
  491. zones_.Clear();
  492. occluders_.Clear();
  493. activeOccluders_ = 0;
  494. vertexLightQueues_.Clear();
  495. for (HashMap<unsigned, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  496. i->second_.Clear(maxSortedInstances);
  497. if (hasScenePasses_ && (!cullCamera_ || !octree_))
  498. {
  499. renderer_->SendEvent(E_ENDVIEWUPDATE, eventData);
  500. return;
  501. }
  502. // Set automatic aspect ratio if required
  503. if (cullCamera_ && cullCamera_->GetAutoAspectRatio())
  504. cullCamera_->SetAspectRatioInternal((float)frame_.viewSize_.x_ / (float)frame_.viewSize_.y_);
  505. GetDrawables();
  506. GetBatches();
  507. renderer_->StorePreparedView(this, cullCamera_);
  508. renderer_->SendEvent(E_ENDVIEWUPDATE, eventData);
  509. }
  510. void View::Render()
  511. {
  512. if (hasScenePasses_ && (!octree_ || !camera_))
  513. return;
  514. UpdateGeometries();
  515. // Allocate screen buffers as necessary
  516. AllocateScreenBuffers();
  517. // Forget parameter sources from the previous view
  518. graphics_->ClearParameterSources();
  519. if (renderer_->GetDynamicInstancing() && graphics_->GetInstancingSupport())
  520. PrepareInstancingBuffer();
  521. // It is possible, though not recommended, that the same camera is used for multiple main views. Set automatic aspect ratio
  522. // to ensure correct projection will be used
  523. if (camera_)
  524. {
  525. if (camera_->GetAutoAspectRatio())
  526. camera_->SetAspectRatioInternal((float)(viewSize_.x_) / (float)(viewSize_.y_));
  527. }
  528. // Bind the face selection and indirection cube maps for point light shadows
  529. #ifndef GL_ES_VERSION_2_0
  530. if (renderer_->GetDrawShadows())
  531. {
  532. graphics_->SetTexture(TU_FACESELECT, renderer_->GetFaceSelectCubeMap());
  533. graphics_->SetTexture(TU_INDIRECTION, renderer_->GetIndirectionCubeMap());
  534. }
  535. #endif
  536. if (renderTarget_)
  537. {
  538. // On OpenGL, flip the projection if rendering to a texture so that the texture can be addressed in the same way
  539. // as a render texture produced on Direct3D9
  540. #ifdef URHO3D_OPENGL
  541. if (camera_)
  542. camera_->SetFlipVertical(true);
  543. #endif
  544. }
  545. // Render
  546. ExecuteRenderPathCommands();
  547. // Reset state after commands
  548. graphics_->SetFillMode(FILL_SOLID);
  549. graphics_->SetClipPlane(false);
  550. graphics_->SetColorWrite(true);
  551. graphics_->SetDepthBias(0.0f, 0.0f);
  552. graphics_->SetScissorTest(false);
  553. graphics_->SetStencilTest(false);
  554. // Draw the associated debug geometry now if enabled
  555. if (drawDebug_ && octree_ && camera_)
  556. {
  557. DebugRenderer* debug = octree_->GetComponent<DebugRenderer>();
  558. if (debug && debug->IsEnabledEffective() && debug->HasContent())
  559. {
  560. // If used resolve from backbuffer, blit first to the backbuffer to ensure correct depth buffer on OpenGL
  561. // Otherwise use the last rendertarget and blit after debug geometry
  562. if (usedResolve_ && currentRenderTarget_ != renderTarget_)
  563. {
  564. BlitFramebuffer(currentRenderTarget_->GetParentTexture(), renderTarget_, false);
  565. currentRenderTarget_ = renderTarget_;
  566. }
  567. graphics_->SetRenderTarget(0, currentRenderTarget_);
  568. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  569. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  570. graphics_->SetDepthStencil(GetDepthStencil(currentRenderTarget_));
  571. IntVector2 rtSizeNow = graphics_->GetRenderTargetDimensions();
  572. IntRect viewport = (currentRenderTarget_ == renderTarget_) ? viewRect_ : IntRect(0, 0, rtSizeNow.x_,
  573. rtSizeNow.y_);
  574. graphics_->SetViewport(viewport);
  575. debug->SetView(camera_);
  576. debug->Render();
  577. }
  578. }
  579. #ifdef URHO3D_OPENGL
  580. if (camera_)
  581. camera_->SetFlipVertical(false);
  582. #endif
  583. // Run framebuffer blitting if necessary. If scene was resolved from backbuffer, do not touch depth
  584. // (backbuffer should contain proper depth already)
  585. if (currentRenderTarget_ != renderTarget_)
  586. BlitFramebuffer(currentRenderTarget_->GetParentTexture(), renderTarget_, !usedResolve_);
  587. }
  588. Graphics* View::GetGraphics() const
  589. {
  590. return graphics_;
  591. }
  592. Renderer* View::GetRenderer() const
  593. {
  594. return renderer_;
  595. }
  596. View* View::GetSourceView() const
  597. {
  598. return sourceView_;
  599. }
  600. void View::SetGlobalShaderParameters()
  601. {
  602. graphics_->SetShaderParameter(VSP_DELTATIME, frame_.timeStep_);
  603. graphics_->SetShaderParameter(PSP_DELTATIME, frame_.timeStep_);
  604. if (scene_)
  605. {
  606. float elapsedTime = scene_->GetElapsedTime();
  607. graphics_->SetShaderParameter(VSP_ELAPSEDTIME, elapsedTime);
  608. graphics_->SetShaderParameter(PSP_ELAPSEDTIME, elapsedTime);
  609. }
  610. }
  611. void View::SetCameraShaderParameters(Camera* camera, bool setProjection)
  612. {
  613. if (!camera)
  614. return;
  615. Matrix3x4 cameraEffectiveTransform = camera->GetEffectiveWorldTransform();
  616. graphics_->SetShaderParameter(VSP_CAMERAPOS, cameraEffectiveTransform.Translation());
  617. graphics_->SetShaderParameter(VSP_CAMERAROT, cameraEffectiveTransform.RotationMatrix());
  618. graphics_->SetShaderParameter(PSP_CAMERAPOS, cameraEffectiveTransform.Translation());
  619. float nearClip = camera->GetNearClip();
  620. float farClip = camera->GetFarClip();
  621. graphics_->SetShaderParameter(VSP_NEARCLIP, nearClip);
  622. graphics_->SetShaderParameter(VSP_FARCLIP, farClip);
  623. graphics_->SetShaderParameter(PSP_NEARCLIP, nearClip);
  624. graphics_->SetShaderParameter(PSP_FARCLIP, farClip);
  625. Vector4 depthMode = Vector4::ZERO;
  626. if (camera->IsOrthographic())
  627. {
  628. depthMode.x_ = 1.0f;
  629. #ifdef URHO3D_OPENGL
  630. depthMode.z_ = 0.5f;
  631. depthMode.w_ = 0.5f;
  632. #else
  633. depthMode.z_ = 1.0f;
  634. #endif
  635. }
  636. else
  637. depthMode.w_ = 1.0f / camera->GetFarClip();
  638. graphics_->SetShaderParameter(VSP_DEPTHMODE, depthMode);
  639. Vector4 depthReconstruct
  640. (farClip / (farClip - nearClip), -nearClip / (farClip - nearClip), camera->IsOrthographic() ? 1.0f : 0.0f,
  641. camera->IsOrthographic() ? 0.0f : 1.0f);
  642. graphics_->SetShaderParameter(PSP_DEPTHRECONSTRUCT, depthReconstruct);
  643. Vector3 nearVector, farVector;
  644. camera->GetFrustumSize(nearVector, farVector);
  645. graphics_->SetShaderParameter(VSP_FRUSTUMSIZE, farVector);
  646. if (setProjection)
  647. {
  648. Matrix4 projection = camera->GetProjection();
  649. #ifdef URHO3D_OPENGL
  650. // Add constant depth bias manually to the projection matrix due to glPolygonOffset() inconsistency
  651. float constantBias = 2.0f * graphics_->GetDepthConstantBias();
  652. projection.m22_ += projection.m32_ * constantBias;
  653. projection.m23_ += projection.m33_ * constantBias;
  654. #endif
  655. graphics_->SetShaderParameter(VSP_VIEWINV, camera->GetView().Inverse());
  656. graphics_->SetShaderParameter(VSP_VIEW, camera->GetView());
  657. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection * camera->GetView());
  658. }
  659. }
  660. void View::SetGBufferShaderParameters(const IntVector2& texSize, const IntRect& viewRect)
  661. {
  662. float texWidth = (float)texSize.x_;
  663. float texHeight = (float)texSize.y_;
  664. float widthRange = 0.5f * viewRect.Width() / texWidth;
  665. float heightRange = 0.5f * viewRect.Height() / texHeight;
  666. #ifdef URHO3D_OPENGL
  667. Vector4 bufferUVOffset(((float)viewRect.left_) / texWidth + widthRange,
  668. 1.0f - (((float)viewRect.top_) / texHeight + heightRange), widthRange, heightRange);
  669. #else
  670. const Vector2& pixelUVOffset = Graphics::GetPixelUVOffset();
  671. Vector4 bufferUVOffset((pixelUVOffset.x_ + (float)viewRect.left_) / texWidth + widthRange,
  672. (pixelUVOffset.y_ + (float)viewRect.top_) / texHeight + heightRange, widthRange, heightRange);
  673. #endif
  674. graphics_->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
  675. float invSizeX = 1.0f / texWidth;
  676. float invSizeY = 1.0f / texHeight;
  677. graphics_->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector2(invSizeX, invSizeY));
  678. }
  679. void View::GetDrawables()
  680. {
  681. if (!octree_ || !cullCamera_)
  682. return;
  683. URHO3D_PROFILE(GetDrawables);
  684. WorkQueue* queue = GetSubsystem<WorkQueue>();
  685. PODVector<Drawable*>& tempDrawables = tempDrawables_[0];
  686. // Get zones and occluders first
  687. {
  688. ZoneOccluderOctreeQuery
  689. query(tempDrawables, cullCamera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_ZONE, cullCamera_->GetViewMask());
  690. octree_->GetDrawables(query);
  691. }
  692. highestZonePriority_ = M_MIN_INT;
  693. int bestPriority = M_MIN_INT;
  694. Node* cameraNode = cullCamera_->GetNode();
  695. Vector3 cameraPos = cameraNode->GetWorldPosition();
  696. for (PODVector<Drawable*>::ConstIterator i = tempDrawables.Begin(); i != tempDrawables.End(); ++i)
  697. {
  698. Drawable* drawable = *i;
  699. unsigned char flags = drawable->GetDrawableFlags();
  700. if (flags & DRAWABLE_ZONE)
  701. {
  702. Zone* zone = static_cast<Zone*>(drawable);
  703. zones_.Push(zone);
  704. int priority = zone->GetPriority();
  705. if (priority > highestZonePriority_)
  706. highestZonePriority_ = priority;
  707. if (priority > bestPriority && zone->IsInside(cameraPos))
  708. {
  709. cameraZone_ = zone;
  710. bestPriority = priority;
  711. }
  712. }
  713. else
  714. occluders_.Push(drawable);
  715. }
  716. // Determine the zone at far clip distance. If not found, or camera zone has override mode, use camera zone
  717. cameraZoneOverride_ = cameraZone_->GetOverride();
  718. if (!cameraZoneOverride_)
  719. {
  720. Vector3 farClipPos = cameraPos + cameraNode->GetWorldDirection() * Vector3(0.0f, 0.0f, cullCamera_->GetFarClip());
  721. bestPriority = M_MIN_INT;
  722. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  723. {
  724. int priority = (*i)->GetPriority();
  725. if (priority > bestPriority && (*i)->IsInside(farClipPos))
  726. {
  727. farClipZone_ = *i;
  728. bestPriority = priority;
  729. }
  730. }
  731. }
  732. if (farClipZone_ == renderer_->GetDefaultZone())
  733. farClipZone_ = cameraZone_;
  734. // If occlusion in use, get & render the occluders
  735. occlusionBuffer_ = 0;
  736. if (maxOccluderTriangles_ > 0)
  737. {
  738. UpdateOccluders(occluders_, cullCamera_);
  739. if (occluders_.Size())
  740. {
  741. URHO3D_PROFILE(DrawOcclusion);
  742. occlusionBuffer_ = renderer_->GetOcclusionBuffer(cullCamera_);
  743. DrawOccluders(occlusionBuffer_, occluders_);
  744. }
  745. }
  746. else
  747. occluders_.Clear();
  748. // Get lights and geometries. Coarse occlusion for octants is used at this point
  749. if (occlusionBuffer_)
  750. {
  751. OccludedFrustumOctreeQuery query
  752. (tempDrawables, cullCamera_->GetFrustum(), occlusionBuffer_, DRAWABLE_GEOMETRY | DRAWABLE_LIGHT, cullCamera_->GetViewMask());
  753. octree_->GetDrawables(query);
  754. }
  755. else
  756. {
  757. FrustumOctreeQuery query(tempDrawables, cullCamera_->GetFrustum(), DRAWABLE_GEOMETRY | DRAWABLE_LIGHT, cullCamera_->GetViewMask());
  758. octree_->GetDrawables(query);
  759. }
  760. // Check drawable occlusion, find zones for moved drawables and collect geometries & lights in worker threads
  761. {
  762. for (unsigned i = 0; i < sceneResults_.Size(); ++i)
  763. {
  764. PerThreadSceneResult& result = sceneResults_[i];
  765. result.geometries_.Clear();
  766. result.lights_.Clear();
  767. result.minZ_ = M_INFINITY;
  768. result.maxZ_ = 0.0f;
  769. }
  770. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  771. int drawablesPerItem = tempDrawables.Size() / numWorkItems;
  772. PODVector<Drawable*>::Iterator start = tempDrawables.Begin();
  773. // Create a work item for each thread
  774. for (int i = 0; i < numWorkItems; ++i)
  775. {
  776. SharedPtr<WorkItem> item = queue->GetFreeItem();
  777. item->priority_ = M_MAX_UNSIGNED;
  778. item->workFunction_ = CheckVisibilityWork;
  779. item->aux_ = this;
  780. PODVector<Drawable*>::Iterator end = tempDrawables.End();
  781. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  782. end = start + drawablesPerItem;
  783. item->start_ = &(*start);
  784. item->end_ = &(*end);
  785. queue->AddWorkItem(item);
  786. start = end;
  787. }
  788. queue->Complete(M_MAX_UNSIGNED);
  789. }
  790. // Combine lights, geometries & scene Z range from the threads
  791. geometries_.Clear();
  792. lights_.Clear();
  793. minZ_ = M_INFINITY;
  794. maxZ_ = 0.0f;
  795. if (sceneResults_.Size() > 1)
  796. {
  797. for (unsigned i = 0; i < sceneResults_.Size(); ++i)
  798. {
  799. PerThreadSceneResult& result = sceneResults_[i];
  800. geometries_.Push(result.geometries_);
  801. lights_.Push(result.lights_);
  802. minZ_ = Min(minZ_, result.minZ_);
  803. maxZ_ = Max(maxZ_, result.maxZ_);
  804. }
  805. }
  806. else
  807. {
  808. // If just 1 thread, copy the results directly
  809. PerThreadSceneResult& result = sceneResults_[0];
  810. minZ_ = result.minZ_;
  811. maxZ_ = result.maxZ_;
  812. Swap(geometries_, result.geometries_);
  813. Swap(lights_, result.lights_);
  814. }
  815. if (minZ_ == M_INFINITY)
  816. minZ_ = 0.0f;
  817. // Sort the lights to brightest/closest first, and per-vertex lights first so that per-vertex base pass can be evaluated first
  818. for (unsigned i = 0; i < lights_.Size(); ++i)
  819. {
  820. Light* light = lights_[i];
  821. light->SetIntensitySortValue(cullCamera_->GetDistance(light->GetNode()->GetWorldPosition()));
  822. light->SetLightQueue(0);
  823. }
  824. Sort(lights_.Begin(), lights_.End(), CompareLights);
  825. }
  826. void View::GetBatches()
  827. {
  828. if (!octree_ || !cullCamera_)
  829. return;
  830. nonThreadedGeometries_.Clear();
  831. threadedGeometries_.Clear();
  832. ProcessLights();
  833. GetLightBatches();
  834. GetBaseBatches();
  835. }
  836. void View::ProcessLights()
  837. {
  838. // Process lit geometries and shadow casters for each light
  839. URHO3D_PROFILE(ProcessLights);
  840. WorkQueue* queue = GetSubsystem<WorkQueue>();
  841. lightQueryResults_.Resize(lights_.Size());
  842. for (unsigned i = 0; i < lightQueryResults_.Size(); ++i)
  843. {
  844. SharedPtr<WorkItem> item = queue->GetFreeItem();
  845. item->priority_ = M_MAX_UNSIGNED;
  846. item->workFunction_ = ProcessLightWork;
  847. item->aux_ = this;
  848. LightQueryResult& query = lightQueryResults_[i];
  849. query.light_ = lights_[i];
  850. item->start_ = &query;
  851. queue->AddWorkItem(item);
  852. }
  853. // Ensure all lights have been processed before proceeding
  854. queue->Complete(M_MAX_UNSIGNED);
  855. }
  856. void View::GetLightBatches()
  857. {
  858. BatchQueue* alphaQueue = batchQueues_.Contains(alphaPassIndex_) ? &batchQueues_[alphaPassIndex_] : (BatchQueue*)0;
  859. // Build light queues and lit batches
  860. {
  861. URHO3D_PROFILE(GetLightBatches);
  862. // Preallocate light queues: per-pixel lights which have lit geometries
  863. unsigned numLightQueues = 0;
  864. unsigned usedLightQueues = 0;
  865. for (Vector<LightQueryResult>::ConstIterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  866. {
  867. if (!i->light_->GetPerVertex() && i->litGeometries_.Size())
  868. ++numLightQueues;
  869. }
  870. lightQueues_.Resize(numLightQueues);
  871. maxLightsDrawables_.Clear();
  872. unsigned maxSortedInstances = (unsigned)renderer_->GetMaxSortedInstances();
  873. for (Vector<LightQueryResult>::Iterator i = lightQueryResults_.Begin(); i != lightQueryResults_.End(); ++i)
  874. {
  875. LightQueryResult& query = *i;
  876. // If light has no affected geometries, no need to process further
  877. if (query.litGeometries_.Empty())
  878. continue;
  879. Light* light = query.light_;
  880. // Per-pixel light
  881. if (!light->GetPerVertex())
  882. {
  883. unsigned shadowSplits = query.numSplits_;
  884. // Initialize light queue and store it to the light so that it can be found later
  885. LightBatchQueue& lightQueue = lightQueues_[usedLightQueues++];
  886. light->SetLightQueue(&lightQueue);
  887. lightQueue.light_ = light;
  888. lightQueue.negative_ = light->IsNegative();
  889. lightQueue.shadowMap_ = 0;
  890. lightQueue.litBaseBatches_.Clear(maxSortedInstances);
  891. lightQueue.litBatches_.Clear(maxSortedInstances);
  892. lightQueue.volumeBatches_.Clear();
  893. // Allocate shadow map now
  894. if (shadowSplits > 0)
  895. {
  896. lightQueue.shadowMap_ = renderer_->GetShadowMap(light, cullCamera_, (unsigned)viewSize_.x_, (unsigned)viewSize_.y_);
  897. // If did not manage to get a shadow map, convert the light to unshadowed
  898. if (!lightQueue.shadowMap_)
  899. shadowSplits = 0;
  900. }
  901. // Setup shadow batch queues
  902. lightQueue.shadowSplits_.Resize(shadowSplits);
  903. for (unsigned j = 0; j < shadowSplits; ++j)
  904. {
  905. ShadowBatchQueue& shadowQueue = lightQueue.shadowSplits_[j];
  906. Camera* shadowCamera = query.shadowCameras_[j];
  907. shadowQueue.shadowCamera_ = shadowCamera;
  908. shadowQueue.nearSplit_ = query.shadowNearSplits_[j];
  909. shadowQueue.farSplit_ = query.shadowFarSplits_[j];
  910. shadowQueue.shadowBatches_.Clear(maxSortedInstances);
  911. // Setup the shadow split viewport and finalize shadow camera parameters
  912. shadowQueue.shadowViewport_ = GetShadowMapViewport(light, j, lightQueue.shadowMap_);
  913. FinalizeShadowCamera(shadowCamera, light, shadowQueue.shadowViewport_, query.shadowCasterBox_[j]);
  914. // Loop through shadow casters
  915. for (PODVector<Drawable*>::ConstIterator k = query.shadowCasters_.Begin() + query.shadowCasterBegin_[j];
  916. k < query.shadowCasters_.Begin() + query.shadowCasterEnd_[j]; ++k)
  917. {
  918. Drawable* drawable = *k;
  919. // If drawable is not in actual view frustum, mark it in view here and check its geometry update type
  920. if (!drawable->IsInView(frame_, true))
  921. {
  922. drawable->MarkInView(frame_.frameNumber_);
  923. UpdateGeometryType type = drawable->GetUpdateGeometryType();
  924. if (type == UPDATE_MAIN_THREAD)
  925. nonThreadedGeometries_.Push(drawable);
  926. else if (type == UPDATE_WORKER_THREAD)
  927. threadedGeometries_.Push(drawable);
  928. }
  929. Zone* zone = GetZone(drawable);
  930. const Vector<SourceBatch>& batches = drawable->GetBatches();
  931. for (unsigned l = 0; l < batches.Size(); ++l)
  932. {
  933. const SourceBatch& srcBatch = batches[l];
  934. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  935. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  936. continue;
  937. Pass* pass = tech->GetSupportedPass(Technique::shadowPassIndex);
  938. // Skip if material has no shadow pass
  939. if (!pass)
  940. continue;
  941. Batch destBatch(srcBatch);
  942. destBatch.pass_ = pass;
  943. destBatch.zone_ = zone;
  944. AddBatchToQueue(shadowQueue.shadowBatches_, destBatch, tech);
  945. }
  946. }
  947. }
  948. // Process lit geometries
  949. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  950. {
  951. Drawable* drawable = *j;
  952. drawable->AddLight(light);
  953. // If drawable limits maximum lights, only record the light, and check maximum count / build batches later
  954. if (!drawable->GetMaxLights())
  955. GetLitBatches(drawable, lightQueue, alphaQueue);
  956. else
  957. maxLightsDrawables_.Insert(drawable);
  958. }
  959. // In deferred modes, store the light volume batch now
  960. if (deferred_)
  961. {
  962. Batch volumeBatch;
  963. volumeBatch.geometry_ = renderer_->GetLightGeometry(light);
  964. volumeBatch.geometryType_ = GEOM_STATIC;
  965. volumeBatch.worldTransform_ = &light->GetVolumeTransform(cullCamera_);
  966. volumeBatch.numWorldTransforms_ = 1;
  967. volumeBatch.lightQueue_ = &lightQueue;
  968. volumeBatch.distance_ = light->GetDistance();
  969. volumeBatch.material_ = 0;
  970. volumeBatch.pass_ = 0;
  971. volumeBatch.zone_ = 0;
  972. renderer_->SetLightVolumeBatchShaders(volumeBatch, cullCamera_, lightVolumeCommand_->vertexShaderName_,
  973. lightVolumeCommand_->pixelShaderName_, lightVolumeCommand_->vertexShaderDefines_,
  974. lightVolumeCommand_->pixelShaderDefines_);
  975. lightQueue.volumeBatches_.Push(volumeBatch);
  976. }
  977. }
  978. // Per-vertex light
  979. else
  980. {
  981. // Add the vertex light to lit drawables. It will be processed later during base pass batch generation
  982. for (PODVector<Drawable*>::ConstIterator j = query.litGeometries_.Begin(); j != query.litGeometries_.End(); ++j)
  983. {
  984. Drawable* drawable = *j;
  985. drawable->AddVertexLight(light);
  986. }
  987. }
  988. }
  989. }
  990. // Process drawables with limited per-pixel light count
  991. if (maxLightsDrawables_.Size())
  992. {
  993. URHO3D_PROFILE(GetMaxLightsBatches);
  994. for (HashSet<Drawable*>::Iterator i = maxLightsDrawables_.Begin(); i != maxLightsDrawables_.End(); ++i)
  995. {
  996. Drawable* drawable = *i;
  997. drawable->LimitLights();
  998. const PODVector<Light*>& lights = drawable->GetLights();
  999. for (unsigned i = 0; i < lights.Size(); ++i)
  1000. {
  1001. Light* light = lights[i];
  1002. // Find the correct light queue again
  1003. LightBatchQueue* queue = light->GetLightQueue();
  1004. if (queue)
  1005. GetLitBatches(drawable, *queue, alphaQueue);
  1006. }
  1007. }
  1008. }
  1009. }
  1010. void View::GetBaseBatches()
  1011. {
  1012. URHO3D_PROFILE(GetBaseBatches);
  1013. for (PODVector<Drawable*>::ConstIterator i = geometries_.Begin(); i != geometries_.End(); ++i)
  1014. {
  1015. Drawable* drawable = *i;
  1016. UpdateGeometryType type = drawable->GetUpdateGeometryType();
  1017. if (type == UPDATE_MAIN_THREAD)
  1018. nonThreadedGeometries_.Push(drawable);
  1019. else if (type == UPDATE_WORKER_THREAD)
  1020. threadedGeometries_.Push(drawable);
  1021. const Vector<SourceBatch>& batches = drawable->GetBatches();
  1022. bool vertexLightsProcessed = false;
  1023. for (unsigned j = 0; j < batches.Size(); ++j)
  1024. {
  1025. const SourceBatch& srcBatch = batches[j];
  1026. // Check here if the material refers to a rendertarget texture with camera(s) attached
  1027. // Only check this for backbuffer views (null rendertarget)
  1028. if (srcBatch.material_ && srcBatch.material_->GetAuxViewFrameNumber() != frame_.frameNumber_ && !renderTarget_)
  1029. CheckMaterialForAuxView(srcBatch.material_);
  1030. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  1031. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  1032. continue;
  1033. // Check each of the scene passes
  1034. for (unsigned k = 0; k < scenePasses_.Size(); ++k)
  1035. {
  1036. ScenePassInfo& info = scenePasses_[k];
  1037. // Skip forward base pass if the corresponding litbase pass already exists
  1038. if (info.passIndex_ == basePassIndex_ && j < 32 && drawable->HasBasePass(j))
  1039. continue;
  1040. Pass* pass = tech->GetSupportedPass(info.passIndex_);
  1041. if (!pass)
  1042. continue;
  1043. Batch destBatch(srcBatch);
  1044. destBatch.pass_ = pass;
  1045. destBatch.zone_ = GetZone(drawable);
  1046. destBatch.isBase_ = true;
  1047. destBatch.lightMask_ = (unsigned char)GetLightMask(drawable);
  1048. if (info.vertexLights_)
  1049. {
  1050. const PODVector<Light*>& drawableVertexLights = drawable->GetVertexLights();
  1051. if (drawableVertexLights.Size() && !vertexLightsProcessed)
  1052. {
  1053. // Limit vertex lights. If this is a deferred opaque batch, remove converted per-pixel lights,
  1054. // as they will be rendered as light volumes in any case, and drawing them also as vertex lights
  1055. // would result in double lighting
  1056. drawable->LimitVertexLights(deferred_ && destBatch.pass_->GetBlendMode() == BLEND_REPLACE);
  1057. vertexLightsProcessed = true;
  1058. }
  1059. if (drawableVertexLights.Size())
  1060. {
  1061. // Find a vertex light queue. If not found, create new
  1062. unsigned long long hash = GetVertexLightQueueHash(drawableVertexLights);
  1063. HashMap<unsigned long long, LightBatchQueue>::Iterator i = vertexLightQueues_.Find(hash);
  1064. if (i == vertexLightQueues_.End())
  1065. {
  1066. i = vertexLightQueues_.Insert(MakePair(hash, LightBatchQueue()));
  1067. i->second_.light_ = 0;
  1068. i->second_.shadowMap_ = 0;
  1069. i->second_.vertexLights_ = drawableVertexLights;
  1070. }
  1071. destBatch.lightQueue_ = &(i->second_);
  1072. }
  1073. }
  1074. else
  1075. destBatch.lightQueue_ = 0;
  1076. bool allowInstancing = info.allowInstancing_;
  1077. if (allowInstancing && info.markToStencil_ && destBatch.lightMask_ != (destBatch.zone_->GetLightMask() & 0xff))
  1078. allowInstancing = false;
  1079. AddBatchToQueue(*info.batchQueue_, destBatch, tech, allowInstancing);
  1080. }
  1081. }
  1082. }
  1083. }
  1084. void View::UpdateGeometries()
  1085. {
  1086. // Update geometries in the source view if necessary (prepare order may differ from render order)
  1087. if (sourceView_ && !sourceView_->geometriesUpdated_)
  1088. {
  1089. sourceView_->UpdateGeometries();
  1090. return;
  1091. }
  1092. URHO3D_PROFILE(SortAndUpdateGeometry);
  1093. WorkQueue* queue = GetSubsystem<WorkQueue>();
  1094. // Sort batches
  1095. {
  1096. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1097. {
  1098. const RenderPathCommand& command = renderPath_->commands_[i];
  1099. if (!IsNecessary(command))
  1100. continue;
  1101. if (command.type_ == CMD_SCENEPASS)
  1102. {
  1103. SharedPtr<WorkItem> item = queue->GetFreeItem();
  1104. item->priority_ = M_MAX_UNSIGNED;
  1105. item->workFunction_ =
  1106. command.sortMode_ == SORT_FRONTTOBACK ? SortBatchQueueFrontToBackWork : SortBatchQueueBackToFrontWork;
  1107. item->start_ = &batchQueues_[command.passIndex_];
  1108. queue->AddWorkItem(item);
  1109. }
  1110. }
  1111. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  1112. {
  1113. SharedPtr<WorkItem> lightItem = queue->GetFreeItem();
  1114. lightItem->priority_ = M_MAX_UNSIGNED;
  1115. lightItem->workFunction_ = SortLightQueueWork;
  1116. lightItem->start_ = &(*i);
  1117. queue->AddWorkItem(lightItem);
  1118. if (i->shadowSplits_.Size())
  1119. {
  1120. SharedPtr<WorkItem> shadowItem = queue->GetFreeItem();
  1121. shadowItem->priority_ = M_MAX_UNSIGNED;
  1122. shadowItem->workFunction_ = SortShadowQueueWork;
  1123. shadowItem->start_ = &(*i);
  1124. queue->AddWorkItem(shadowItem);
  1125. }
  1126. }
  1127. }
  1128. // Update geometries. Split into threaded and non-threaded updates.
  1129. {
  1130. if (threadedGeometries_.Size())
  1131. {
  1132. // In special cases (context loss, multi-view) a drawable may theoretically first have reported a threaded update, but will actually
  1133. // require a main thread update. Check these cases first and move as applicable. The threaded work routine will tolerate the null
  1134. // pointer holes that we leave to the threaded update queue.
  1135. for (PODVector<Drawable*>::Iterator i = threadedGeometries_.Begin(); i != threadedGeometries_.End(); ++i)
  1136. {
  1137. if ((*i)->GetUpdateGeometryType() == UPDATE_MAIN_THREAD)
  1138. {
  1139. nonThreadedGeometries_.Push(*i);
  1140. *i = 0;
  1141. }
  1142. }
  1143. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  1144. int drawablesPerItem = threadedGeometries_.Size() / numWorkItems;
  1145. PODVector<Drawable*>::Iterator start = threadedGeometries_.Begin();
  1146. for (int i = 0; i < numWorkItems; ++i)
  1147. {
  1148. PODVector<Drawable*>::Iterator end = threadedGeometries_.End();
  1149. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  1150. end = start + drawablesPerItem;
  1151. SharedPtr<WorkItem> item = queue->GetFreeItem();
  1152. item->priority_ = M_MAX_UNSIGNED;
  1153. item->workFunction_ = UpdateDrawableGeometriesWork;
  1154. item->aux_ = const_cast<FrameInfo*>(&frame_);
  1155. item->start_ = &(*start);
  1156. item->end_ = &(*end);
  1157. queue->AddWorkItem(item);
  1158. start = end;
  1159. }
  1160. }
  1161. // While the work queue is processed, update non-threaded geometries
  1162. for (PODVector<Drawable*>::ConstIterator i = nonThreadedGeometries_.Begin(); i != nonThreadedGeometries_.End(); ++i)
  1163. (*i)->UpdateGeometry(frame_);
  1164. }
  1165. // Finally ensure all threaded work has completed
  1166. queue->Complete(M_MAX_UNSIGNED);
  1167. geometriesUpdated_ = true;
  1168. }
  1169. void View::GetLitBatches(Drawable* drawable, LightBatchQueue& lightQueue, BatchQueue* alphaQueue)
  1170. {
  1171. Light* light = lightQueue.light_;
  1172. Zone* zone = GetZone(drawable);
  1173. const Vector<SourceBatch>& batches = drawable->GetBatches();
  1174. bool allowLitBase =
  1175. useLitBase_ && !lightQueue.negative_ && light == drawable->GetFirstLight() && drawable->GetVertexLights().Empty() &&
  1176. !zone->GetAmbientGradient();
  1177. for (unsigned i = 0; i < batches.Size(); ++i)
  1178. {
  1179. const SourceBatch& srcBatch = batches[i];
  1180. Technique* tech = GetTechnique(drawable, srcBatch.material_);
  1181. if (!srcBatch.geometry_ || !srcBatch.numWorldTransforms_ || !tech)
  1182. continue;
  1183. // Do not create pixel lit forward passes for materials that render into the G-buffer
  1184. if (gBufferPassIndex_ != M_MAX_UNSIGNED && tech->HasPass(gBufferPassIndex_))
  1185. continue;
  1186. Batch destBatch(srcBatch);
  1187. bool isLitAlpha = false;
  1188. // Check for lit base pass. Because it uses the replace blend mode, it must be ensured to be the first light
  1189. // Also vertex lighting or ambient gradient require the non-lit base pass, so skip in those cases
  1190. if (i < 32 && allowLitBase)
  1191. {
  1192. destBatch.pass_ = tech->GetSupportedPass(litBasePassIndex_);
  1193. if (destBatch.pass_)
  1194. {
  1195. destBatch.isBase_ = true;
  1196. drawable->SetBasePass(i);
  1197. }
  1198. else
  1199. destBatch.pass_ = tech->GetSupportedPass(lightPassIndex_);
  1200. }
  1201. else
  1202. destBatch.pass_ = tech->GetSupportedPass(lightPassIndex_);
  1203. // If no lit pass, check for lit alpha
  1204. if (!destBatch.pass_)
  1205. {
  1206. destBatch.pass_ = tech->GetSupportedPass(litAlphaPassIndex_);
  1207. isLitAlpha = true;
  1208. }
  1209. // Skip if material does not receive light at all
  1210. if (!destBatch.pass_)
  1211. continue;
  1212. destBatch.lightQueue_ = &lightQueue;
  1213. destBatch.zone_ = zone;
  1214. if (!isLitAlpha)
  1215. {
  1216. if (destBatch.isBase_)
  1217. AddBatchToQueue(lightQueue.litBaseBatches_, destBatch, tech);
  1218. else
  1219. AddBatchToQueue(lightQueue.litBatches_, destBatch, tech);
  1220. }
  1221. else if (alphaQueue)
  1222. {
  1223. // Transparent batches can not be instanced, and shadows on transparencies can only be rendered if shadow maps are
  1224. // not reused
  1225. AddBatchToQueue(*alphaQueue, destBatch, tech, false, !renderer_->GetReuseShadowMaps());
  1226. }
  1227. }
  1228. }
  1229. void View::ExecuteRenderPathCommands()
  1230. {
  1231. View* actualView = sourceView_ ? sourceView_ : this;
  1232. // If not reusing shadowmaps, render all of them first
  1233. if (!renderer_->GetReuseShadowMaps() && renderer_->GetDrawShadows() && !actualView->lightQueues_.Empty())
  1234. {
  1235. URHO3D_PROFILE(RenderShadowMaps);
  1236. for (Vector<LightBatchQueue>::Iterator i = actualView->lightQueues_.Begin(); i != actualView->lightQueues_.End(); ++i)
  1237. {
  1238. if (i->shadowMap_)
  1239. RenderShadowMap(*i);
  1240. }
  1241. }
  1242. {
  1243. URHO3D_PROFILE(ExecuteRenderPath);
  1244. // Set for safety in case of empty renderpath
  1245. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1246. currentViewportTexture_ = 0;
  1247. bool viewportModified = false;
  1248. bool isPingponging = false;
  1249. usedResolve_ = false;
  1250. unsigned lastCommandIndex = 0;
  1251. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1252. {
  1253. RenderPathCommand& command = renderPath_->commands_[i];
  1254. if (actualView->IsNecessary(command))
  1255. lastCommandIndex = i;
  1256. }
  1257. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1258. {
  1259. RenderPathCommand& command = renderPath_->commands_[i];
  1260. if (!actualView->IsNecessary(command))
  1261. continue;
  1262. bool viewportRead = actualView->CheckViewportRead(command);
  1263. bool viewportWrite = actualView->CheckViewportWrite(command);
  1264. bool beginPingpong = actualView->CheckPingpong(i);
  1265. // Has the viewport been modified and will be read as a texture by the current command?
  1266. if (viewportRead && viewportModified)
  1267. {
  1268. // Start pingponging without a blit if already rendering to the substitute render target
  1269. if (currentRenderTarget_ && currentRenderTarget_ == substituteRenderTarget_ && beginPingpong)
  1270. isPingponging = true;
  1271. // If not using pingponging, simply resolve/copy to the first viewport texture
  1272. if (!isPingponging)
  1273. {
  1274. if (!currentRenderTarget_)
  1275. {
  1276. graphics_->ResolveToTexture(dynamic_cast<Texture2D*>(viewportTextures_[0]), viewRect_);
  1277. currentViewportTexture_ = viewportTextures_[0];
  1278. viewportModified = false;
  1279. usedResolve_ = true;
  1280. }
  1281. else
  1282. {
  1283. if (viewportWrite)
  1284. {
  1285. BlitFramebuffer(currentRenderTarget_->GetParentTexture(),
  1286. GetRenderSurfaceFromTexture(viewportTextures_[0]), false);
  1287. currentViewportTexture_ = viewportTextures_[0];
  1288. viewportModified = false;
  1289. }
  1290. else
  1291. {
  1292. // If the current render target is already a texture, and we are not writing to it, can read that
  1293. // texture directly instead of blitting. However keep the viewport dirty flag in case a later command
  1294. // will do both read and write, and then we need to blit / resolve
  1295. currentViewportTexture_ = currentRenderTarget_->GetParentTexture();
  1296. }
  1297. }
  1298. }
  1299. else
  1300. {
  1301. // Swap the pingpong double buffer sides. Texture 0 will be read next
  1302. viewportTextures_[1] = viewportTextures_[0];
  1303. viewportTextures_[0] = currentRenderTarget_->GetParentTexture();
  1304. currentViewportTexture_ = viewportTextures_[0];
  1305. viewportModified = false;
  1306. }
  1307. }
  1308. if (beginPingpong)
  1309. isPingponging = true;
  1310. // Determine viewport write target
  1311. if (viewportWrite)
  1312. {
  1313. if (isPingponging)
  1314. {
  1315. currentRenderTarget_ = GetRenderSurfaceFromTexture(viewportTextures_[1]);
  1316. // If the render path ends into a quad, it can be redirected to the final render target
  1317. // However, on OpenGL we can not reliably do this in case the final target is the backbuffer, and we want to
  1318. // render depth buffer sensitive debug geometry afterward (backbuffer and textures can not share depth)
  1319. #ifndef URHO3D_OPENGL
  1320. if (i == lastCommandIndex && command.type_ == CMD_QUAD)
  1321. #else
  1322. if (i == lastCommandIndex && command.type_ == CMD_QUAD && renderTarget_)
  1323. #endif
  1324. currentRenderTarget_ = renderTarget_;
  1325. }
  1326. else
  1327. currentRenderTarget_ = substituteRenderTarget_ ? substituteRenderTarget_ : renderTarget_;
  1328. }
  1329. switch (command.type_)
  1330. {
  1331. case CMD_CLEAR:
  1332. {
  1333. URHO3D_PROFILE(ClearRenderTarget);
  1334. Color clearColor = command.clearColor_;
  1335. if (command.useFogColor_)
  1336. clearColor = actualView->farClipZone_->GetFogColor();
  1337. SetRenderTargets(command);
  1338. graphics_->Clear(command.clearFlags_, clearColor, command.clearDepth_, command.clearStencil_);
  1339. }
  1340. break;
  1341. case CMD_SCENEPASS:
  1342. {
  1343. BatchQueue& queue = actualView->batchQueues_[command.passIndex_];
  1344. if (!queue.IsEmpty())
  1345. {
  1346. URHO3D_PROFILE(RenderScenePass);
  1347. SetRenderTargets(command);
  1348. bool allowDepthWrite = SetTextures(command);
  1349. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(),
  1350. camera_->GetProjection());
  1351. queue.Draw(this, camera_, command.markToStencil_, false, allowDepthWrite);
  1352. }
  1353. }
  1354. break;
  1355. case CMD_QUAD:
  1356. {
  1357. URHO3D_PROFILE(RenderQuad);
  1358. SetRenderTargets(command);
  1359. SetTextures(command);
  1360. RenderQuad(command);
  1361. }
  1362. break;
  1363. case CMD_FORWARDLIGHTS:
  1364. // Render shadow maps + opaque objects' additive lighting
  1365. if (!actualView->lightQueues_.Empty())
  1366. {
  1367. URHO3D_PROFILE(RenderLights);
  1368. SetRenderTargets(command);
  1369. for (Vector<LightBatchQueue>::Iterator i = actualView->lightQueues_.Begin(); i != actualView->lightQueues_.End(); ++i)
  1370. {
  1371. // If reusing shadowmaps, render each of them before the lit batches
  1372. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1373. {
  1374. RenderShadowMap(*i);
  1375. SetRenderTargets(command);
  1376. }
  1377. bool allowDepthWrite = SetTextures(command);
  1378. graphics_->SetClipPlane(camera_->GetUseClipping(), camera_->GetClipPlane(), camera_->GetView(),
  1379. camera_->GetProjection());
  1380. // Draw base (replace blend) batches first
  1381. i->litBaseBatches_.Draw(this, camera_, false, false, allowDepthWrite);
  1382. // Then, if there are additive passes, optimize the light and draw them
  1383. if (!i->litBatches_.IsEmpty())
  1384. {
  1385. renderer_->OptimizeLightByScissor(i->light_, camera_);
  1386. if (!noStencil_)
  1387. renderer_->OptimizeLightByStencil(i->light_, camera_);
  1388. i->litBatches_.Draw(this, camera_, false, true, allowDepthWrite);
  1389. }
  1390. }
  1391. graphics_->SetScissorTest(false);
  1392. graphics_->SetStencilTest(false);
  1393. }
  1394. break;
  1395. case CMD_LIGHTVOLUMES:
  1396. // Render shadow maps + light volumes
  1397. if (!actualView->lightQueues_.Empty())
  1398. {
  1399. URHO3D_PROFILE(RenderLightVolumes);
  1400. SetRenderTargets(command);
  1401. for (Vector<LightBatchQueue>::Iterator i = actualView->lightQueues_.Begin(); i != actualView->lightQueues_.End(); ++i)
  1402. {
  1403. // If reusing shadowmaps, render each of them before the lit batches
  1404. if (renderer_->GetReuseShadowMaps() && i->shadowMap_)
  1405. {
  1406. RenderShadowMap(*i);
  1407. SetRenderTargets(command);
  1408. }
  1409. SetTextures(command);
  1410. for (unsigned j = 0; j < i->volumeBatches_.Size(); ++j)
  1411. {
  1412. SetupLightVolumeBatch(i->volumeBatches_[j]);
  1413. i->volumeBatches_[j].Draw(this, camera_, false);
  1414. }
  1415. }
  1416. graphics_->SetScissorTest(false);
  1417. graphics_->SetStencilTest(false);
  1418. }
  1419. break;
  1420. case CMD_RENDERUI:
  1421. {
  1422. SetRenderTargets(command);
  1423. GetSubsystem<UI>()->Render(false);
  1424. }
  1425. break;
  1426. default:
  1427. break;
  1428. }
  1429. // If current command output to the viewport, mark it modified
  1430. if (viewportWrite)
  1431. viewportModified = true;
  1432. }
  1433. }
  1434. }
  1435. void View::SetRenderTargets(RenderPathCommand& command)
  1436. {
  1437. unsigned index = 0;
  1438. bool useColorWrite = true;
  1439. bool useCustomDepth = false;
  1440. bool useViewportOutput = false;
  1441. while (index < command.outputs_.Size())
  1442. {
  1443. if (!command.outputs_[index].first_.Compare("viewport", false))
  1444. {
  1445. graphics_->SetRenderTarget(index, currentRenderTarget_);
  1446. useViewportOutput = true;
  1447. }
  1448. else
  1449. {
  1450. Texture* texture = FindNamedTexture(command.outputs_[index].first_, true, false);
  1451. // Check for depth only rendering (by specifying a depth texture as the sole output)
  1452. if (!index && command.outputs_.Size() == 1 && texture && (texture->GetFormat() == Graphics::GetReadableDepthFormat() ||
  1453. texture->GetFormat() == Graphics::GetDepthStencilFormat()))
  1454. {
  1455. useColorWrite = false;
  1456. useCustomDepth = true;
  1457. #if !defined(URHO3D_OPENGL) && !defined(URHO3D_D3D11)
  1458. // On D3D9 actual depth-only rendering is illegal, we need a color rendertarget
  1459. if (!depthOnlyDummyTexture_)
  1460. {
  1461. depthOnlyDummyTexture_ = renderer_->GetScreenBuffer(texture->GetWidth(), texture->GetHeight(),
  1462. graphics_->GetDummyColorFormat(), false, false, false);
  1463. }
  1464. #endif
  1465. graphics_->SetRenderTarget(0, GetRenderSurfaceFromTexture(depthOnlyDummyTexture_));
  1466. graphics_->SetDepthStencil(GetRenderSurfaceFromTexture(texture));
  1467. }
  1468. else
  1469. graphics_->SetRenderTarget(index, GetRenderSurfaceFromTexture(texture, command.outputs_[index].second_));
  1470. }
  1471. ++index;
  1472. }
  1473. while (index < MAX_RENDERTARGETS)
  1474. {
  1475. graphics_->SetRenderTarget(index, (RenderSurface*)0);
  1476. ++index;
  1477. }
  1478. if (command.depthStencilName_.Length())
  1479. {
  1480. Texture* depthTexture = FindNamedTexture(command.depthStencilName_, true, false);
  1481. if (depthTexture)
  1482. {
  1483. useCustomDepth = true;
  1484. graphics_->SetDepthStencil(GetRenderSurfaceFromTexture(depthTexture));
  1485. }
  1486. }
  1487. // When rendering to the final destination rendertarget, use the actual viewport. Otherwise texture rendertargets should use
  1488. // their full size as the viewport
  1489. IntVector2 rtSizeNow = graphics_->GetRenderTargetDimensions();
  1490. IntRect viewport = (useViewportOutput && currentRenderTarget_ == renderTarget_) ? viewRect_ : IntRect(0, 0, rtSizeNow.x_,
  1491. rtSizeNow.y_);
  1492. if (!useCustomDepth)
  1493. graphics_->SetDepthStencil(GetDepthStencil(graphics_->GetRenderTarget(0)));
  1494. graphics_->SetViewport(viewport);
  1495. graphics_->SetColorWrite(useColorWrite);
  1496. }
  1497. bool View::SetTextures(RenderPathCommand& command)
  1498. {
  1499. bool allowDepthWrite = true;
  1500. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1501. {
  1502. if (command.textureNames_[i].Empty())
  1503. continue;
  1504. // Bind the rendered output
  1505. if (!command.textureNames_[i].Compare("viewport", false))
  1506. {
  1507. graphics_->SetTexture(i, currentViewportTexture_);
  1508. continue;
  1509. }
  1510. #ifdef DESKTOP_GRAPHICS
  1511. Texture* texture = FindNamedTexture(command.textureNames_[i], false, i == TU_VOLUMEMAP);
  1512. #else
  1513. Texture* texture = FindNamedTexture(command.textureNames_[i], false, false);
  1514. #endif
  1515. if (texture)
  1516. {
  1517. graphics_->SetTexture(i, texture);
  1518. // Check if the current depth stencil is being sampled
  1519. if (graphics_->GetDepthStencil() && texture == graphics_->GetDepthStencil()->GetParentTexture())
  1520. allowDepthWrite = false;
  1521. }
  1522. else
  1523. {
  1524. // If requesting a texture fails, clear the texture name to prevent redundant attempts
  1525. command.textureNames_[i] = String::EMPTY;
  1526. }
  1527. }
  1528. return allowDepthWrite;
  1529. }
  1530. void View::RenderQuad(RenderPathCommand& command)
  1531. {
  1532. if (command.vertexShaderName_.Empty() || command.pixelShaderName_.Empty())
  1533. return;
  1534. // If shader can not be found, clear it from the command to prevent redundant attempts
  1535. ShaderVariation* vs = graphics_->GetShader(VS, command.vertexShaderName_, command.vertexShaderDefines_);
  1536. if (!vs)
  1537. command.vertexShaderName_ = String::EMPTY;
  1538. ShaderVariation* ps = graphics_->GetShader(PS, command.pixelShaderName_, command.pixelShaderDefines_);
  1539. if (!ps)
  1540. command.pixelShaderName_ = String::EMPTY;
  1541. // Set shaders & shader parameters and textures
  1542. graphics_->SetShaders(vs, ps);
  1543. const HashMap<StringHash, Variant>& parameters = command.shaderParameters_;
  1544. for (HashMap<StringHash, Variant>::ConstIterator k = parameters.Begin(); k != parameters.End(); ++k)
  1545. graphics_->SetShaderParameter(k->first_, k->second_);
  1546. SetGlobalShaderParameters();
  1547. SetCameraShaderParameters(camera_, false);
  1548. // During renderpath commands the G-Buffer or viewport texture is assumed to always be viewport-sized
  1549. IntRect viewport = graphics_->GetViewport();
  1550. IntVector2 viewSize = IntVector2(viewport.Width(), viewport.Height());
  1551. SetGBufferShaderParameters(viewSize, IntRect(0, 0, viewSize.x_, viewSize.y_));
  1552. // Set per-rendertarget inverse size / offset shader parameters as necessary
  1553. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1554. {
  1555. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1556. if (!rtInfo.enabled_)
  1557. continue;
  1558. StringHash nameHash(rtInfo.name_);
  1559. if (!renderTargets_.Contains(nameHash))
  1560. continue;
  1561. String invSizeName = rtInfo.name_ + "InvSize";
  1562. String offsetsName = rtInfo.name_ + "Offsets";
  1563. float width = (float)renderTargets_[nameHash]->GetWidth();
  1564. float height = (float)renderTargets_[nameHash]->GetHeight();
  1565. const Vector2& pixelUVOffset = Graphics::GetPixelUVOffset();
  1566. graphics_->SetShaderParameter(invSizeName, Vector2(1.0f / width, 1.0f / height));
  1567. graphics_->SetShaderParameter(offsetsName, Vector2(pixelUVOffset.x_ / width, pixelUVOffset.y_ / height));
  1568. }
  1569. graphics_->SetBlendMode(command.blendMode_);
  1570. graphics_->SetDepthTest(CMP_ALWAYS);
  1571. graphics_->SetDepthWrite(false);
  1572. graphics_->SetFillMode(FILL_SOLID);
  1573. graphics_->SetClipPlane(false);
  1574. graphics_->SetScissorTest(false);
  1575. graphics_->SetStencilTest(false);
  1576. DrawFullscreenQuad(false);
  1577. }
  1578. bool View::IsNecessary(const RenderPathCommand& command)
  1579. {
  1580. return command.enabled_ && command.outputs_.Size() &&
  1581. (command.type_ != CMD_SCENEPASS || !batchQueues_[command.passIndex_].IsEmpty());
  1582. }
  1583. bool View::CheckViewportRead(const RenderPathCommand& command)
  1584. {
  1585. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1586. {
  1587. if (!command.textureNames_[i].Empty() && !command.textureNames_[i].Compare("viewport", false))
  1588. return true;
  1589. }
  1590. return false;
  1591. }
  1592. bool View::CheckViewportWrite(const RenderPathCommand& command)
  1593. {
  1594. for (unsigned i = 0; i < command.outputs_.Size(); ++i)
  1595. {
  1596. if (!command.outputs_[i].first_.Compare("viewport", false))
  1597. return true;
  1598. }
  1599. return false;
  1600. }
  1601. bool View::CheckPingpong(unsigned index)
  1602. {
  1603. // Current command must be a viewport-reading & writing quad to begin the pingpong chain
  1604. RenderPathCommand& current = renderPath_->commands_[index];
  1605. if (current.type_ != CMD_QUAD || !CheckViewportRead(current) || !CheckViewportWrite(current))
  1606. return false;
  1607. // If there are commands other than quads that target the viewport, we must keep rendering to the final target and resolving
  1608. // to a viewport texture when necessary instead of pingponging, as a scene pass is not guaranteed to fill the entire viewport
  1609. for (unsigned i = index + 1; i < renderPath_->commands_.Size(); ++i)
  1610. {
  1611. RenderPathCommand& command = renderPath_->commands_[i];
  1612. if (!IsNecessary(command))
  1613. continue;
  1614. if (CheckViewportWrite(command))
  1615. {
  1616. if (command.type_ != CMD_QUAD)
  1617. return false;
  1618. }
  1619. }
  1620. return true;
  1621. }
  1622. void View::AllocateScreenBuffers()
  1623. {
  1624. View* actualView = sourceView_ ? sourceView_ : this;
  1625. bool hasScenePassToRTs = false;
  1626. bool hasCustomDepth = false;
  1627. bool hasViewportRead = false;
  1628. bool hasPingpong = false;
  1629. bool needSubstitute = false;
  1630. unsigned numViewportTextures = 0;
  1631. depthOnlyDummyTexture_ = 0;
  1632. // Check for commands with special meaning: has custom depth, renders a scene pass to other than the destination viewport,
  1633. // read the viewport, or pingpong between viewport textures. These may trigger the need to substitute the destination RT
  1634. for (unsigned i = 0; i < renderPath_->commands_.Size(); ++i)
  1635. {
  1636. const RenderPathCommand& command = renderPath_->commands_[i];
  1637. if (!actualView->IsNecessary(command))
  1638. continue;
  1639. if (!hasViewportRead && CheckViewportRead(command))
  1640. hasViewportRead = true;
  1641. if (!hasPingpong && CheckPingpong(i))
  1642. hasPingpong = true;
  1643. if (command.depthStencilName_.Length())
  1644. hasCustomDepth = true;
  1645. if (!hasScenePassToRTs && command.type_ == CMD_SCENEPASS)
  1646. {
  1647. for (unsigned j = 0; j < command.outputs_.Size(); ++j)
  1648. {
  1649. if (command.outputs_[j].first_.Compare("viewport", false))
  1650. {
  1651. hasScenePassToRTs = true;
  1652. break;
  1653. }
  1654. }
  1655. }
  1656. }
  1657. #ifdef URHO3D_OPENGL
  1658. // Due to FBO limitations, in OpenGL deferred modes need to render to texture first and then blit to the backbuffer
  1659. // Also, if rendering to a texture with full deferred rendering, it must be RGBA to comply with the rest of the buffers,
  1660. // unless using OpenGL 3
  1661. if (((deferred_ || hasScenePassToRTs) && !renderTarget_) || (!Graphics::GetGL3Support() && deferredAmbient_ && renderTarget_
  1662. && renderTarget_->GetParentTexture()->GetFormat() != Graphics::GetRGBAFormat()))
  1663. needSubstitute = true;
  1664. // Also need substitute if rendering to backbuffer using a custom (readable) depth buffer
  1665. if (!renderTarget_ && hasCustomDepth)
  1666. needSubstitute = true;
  1667. #endif
  1668. // If backbuffer is antialiased when using deferred rendering, need to reserve a buffer
  1669. if (deferred_ && !renderTarget_ && graphics_->GetMultiSample() > 1)
  1670. needSubstitute = true;
  1671. // If viewport is smaller than whole texture/backbuffer in deferred rendering, need to reserve a buffer, as the G-buffer
  1672. // textures will be sized equal to the viewport
  1673. if (viewSize_.x_ < rtSize_.x_ || viewSize_.y_ < rtSize_.y_)
  1674. {
  1675. if (deferred_ || hasScenePassToRTs || hasCustomDepth)
  1676. needSubstitute = true;
  1677. }
  1678. // Follow final rendertarget format, or use RGB to match the backbuffer format
  1679. unsigned format = renderTarget_ ? renderTarget_->GetParentTexture()->GetFormat() : Graphics::GetRGBFormat();
  1680. // If HDR rendering is enabled use RGBA16f and reserve a buffer
  1681. if (renderer_->GetHDRRendering())
  1682. {
  1683. format = Graphics::GetRGBAFloat16Format();
  1684. needSubstitute = true;
  1685. }
  1686. #ifdef URHO3D_OPENGL
  1687. // On OpenGL 2 ensure that all MRT buffers are RGBA in deferred rendering
  1688. if (deferred_ && !renderer_->GetHDRRendering() && !Graphics::GetGL3Support())
  1689. format = Graphics::GetRGBAFormat();
  1690. #endif
  1691. if (hasViewportRead)
  1692. {
  1693. ++numViewportTextures;
  1694. // If OpenGL ES, use substitute target to avoid resolve from the backbuffer, which may be slow. However if multisampling
  1695. // is specified, there is no choice
  1696. #ifdef GL_ES_VERSION_2_0
  1697. if (!renderTarget_ && graphics_->GetMultiSample() < 2)
  1698. needSubstitute = true;
  1699. #endif
  1700. // If we have viewport read and target is a cube map, must allocate a substitute target instead as BlitFramebuffer()
  1701. // does not support reading a cube map
  1702. if (renderTarget_ && renderTarget_->GetParentTexture()->GetType() == TextureCube::GetTypeStatic())
  1703. needSubstitute = true;
  1704. // If rendering to a texture, but the viewport is less than the whole texture, use a substitute to ensure
  1705. // postprocessing shaders will never read outside the viewport
  1706. if (renderTarget_ && (viewSize_.x_ < renderTarget_->GetWidth() || viewSize_.y_ < renderTarget_->GetHeight()))
  1707. needSubstitute = true;
  1708. if (hasPingpong && !needSubstitute)
  1709. ++numViewportTextures;
  1710. }
  1711. // Allocate screen buffers with filtering active in case the quad commands need that
  1712. // Follow the sRGB mode of the destination render target
  1713. bool sRGB = renderTarget_ ? renderTarget_->GetParentTexture()->GetSRGB() : graphics_->GetSRGB();
  1714. substituteRenderTarget_ = needSubstitute ? GetRenderSurfaceFromTexture(renderer_->GetScreenBuffer(viewSize_.x_, viewSize_.y_,
  1715. format, false, true, sRGB)) : (RenderSurface*)0;
  1716. for (unsigned i = 0; i < MAX_VIEWPORT_TEXTURES; ++i)
  1717. {
  1718. viewportTextures_[i] =
  1719. i < numViewportTextures ? renderer_->GetScreenBuffer(viewSize_.x_, viewSize_.y_, format, false, true, sRGB) :
  1720. (Texture*)0;
  1721. }
  1722. // If using a substitute render target and pingponging, the substitute can act as the second viewport texture
  1723. if (numViewportTextures == 1 && substituteRenderTarget_)
  1724. viewportTextures_[1] = substituteRenderTarget_->GetParentTexture();
  1725. // Allocate extra render targets defined by the rendering path
  1726. for (unsigned i = 0; i < renderPath_->renderTargets_.Size(); ++i)
  1727. {
  1728. const RenderTargetInfo& rtInfo = renderPath_->renderTargets_[i];
  1729. if (!rtInfo.enabled_)
  1730. continue;
  1731. float width = rtInfo.size_.x_;
  1732. float height = rtInfo.size_.y_;
  1733. if (rtInfo.sizeMode_ == SIZE_VIEWPORTDIVISOR)
  1734. {
  1735. width = (float)viewSize_.x_ / Max(width, M_EPSILON);
  1736. height = (float)viewSize_.y_ / Max(height, M_EPSILON);
  1737. }
  1738. else if (rtInfo.sizeMode_ == SIZE_VIEWPORTMULTIPLIER)
  1739. {
  1740. width = (float)viewSize_.x_ * width;
  1741. height = (float)viewSize_.y_ * height;
  1742. }
  1743. int intWidth = (int)(width + 0.5f);
  1744. int intHeight = (int)(height + 0.5f);
  1745. // If the rendertarget is persistent, key it with a hash derived from the RT name and the view's pointer
  1746. renderTargets_[rtInfo.name_] =
  1747. renderer_->GetScreenBuffer(intWidth, intHeight, rtInfo.format_, rtInfo.cubemap_, rtInfo.filtered_, rtInfo.sRGB_,
  1748. rtInfo.persistent_ ? StringHash(rtInfo.name_).Value() + (unsigned)(size_t)this : 0);
  1749. }
  1750. }
  1751. void View::BlitFramebuffer(Texture* source, RenderSurface* destination, bool depthWrite)
  1752. {
  1753. if (!source)
  1754. return;
  1755. URHO3D_PROFILE(BlitFramebuffer);
  1756. // If blitting to the destination rendertarget, use the actual viewport. Intermediate textures on the other hand
  1757. // are always viewport-sized
  1758. IntVector2 srcSize(source->GetWidth(), source->GetHeight());
  1759. IntVector2 destSize = destination ? IntVector2(destination->GetWidth(), destination->GetHeight()) : IntVector2(
  1760. graphics_->GetWidth(), graphics_->GetHeight());
  1761. IntRect srcRect = (GetRenderSurfaceFromTexture(source) == renderTarget_) ? viewRect_ : IntRect(0, 0, srcSize.x_, srcSize.y_);
  1762. IntRect destRect = (destination == renderTarget_) ? viewRect_ : IntRect(0, 0, destSize.x_, destSize.y_);
  1763. graphics_->SetBlendMode(BLEND_REPLACE);
  1764. graphics_->SetDepthTest(CMP_ALWAYS);
  1765. graphics_->SetDepthWrite(depthWrite);
  1766. graphics_->SetFillMode(FILL_SOLID);
  1767. graphics_->SetClipPlane(false);
  1768. graphics_->SetScissorTest(false);
  1769. graphics_->SetStencilTest(false);
  1770. graphics_->SetRenderTarget(0, destination);
  1771. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  1772. graphics_->SetRenderTarget(i, (RenderSurface*)0);
  1773. graphics_->SetDepthStencil(GetDepthStencil(destination));
  1774. graphics_->SetViewport(destRect);
  1775. static const String shaderName("CopyFramebuffer");
  1776. graphics_->SetShaders(graphics_->GetShader(VS, shaderName), graphics_->GetShader(PS, shaderName));
  1777. SetGBufferShaderParameters(srcSize, srcRect);
  1778. graphics_->SetTexture(TU_DIFFUSE, source);
  1779. DrawFullscreenQuad(false);
  1780. }
  1781. void View::DrawFullscreenQuad(bool nearQuad)
  1782. {
  1783. Geometry* geometry = renderer_->GetQuadGeometry();
  1784. Matrix3x4 model = Matrix3x4::IDENTITY;
  1785. Matrix4 projection = Matrix4::IDENTITY;
  1786. #ifdef URHO3D_OPENGL
  1787. if (camera_ && camera_->GetFlipVertical())
  1788. projection.m11_ = -1.0f;
  1789. model.m23_ = nearQuad ? -1.0f : 1.0f;
  1790. #else
  1791. model.m23_ = nearQuad ? 0.0f : 1.0f;
  1792. #endif
  1793. graphics_->SetCullMode(CULL_NONE);
  1794. graphics_->SetShaderParameter(VSP_MODEL, model);
  1795. graphics_->SetShaderParameter(VSP_VIEWPROJ, projection);
  1796. graphics_->ClearTransformSources();
  1797. geometry->Draw(graphics_);
  1798. }
  1799. void View::UpdateOccluders(PODVector<Drawable*>& occluders, Camera* camera)
  1800. {
  1801. float occluderSizeThreshold_ = renderer_->GetOccluderSizeThreshold();
  1802. float halfViewSize = camera->GetHalfViewSize();
  1803. float invOrthoSize = 1.0f / camera->GetOrthoSize();
  1804. for (PODVector<Drawable*>::Iterator i = occluders.Begin(); i != occluders.End();)
  1805. {
  1806. Drawable* occluder = *i;
  1807. bool erase = false;
  1808. if (!occluder->IsInView(frame_, true))
  1809. occluder->UpdateBatches(frame_);
  1810. // Check occluder's draw distance (in main camera view)
  1811. float maxDistance = occluder->GetDrawDistance();
  1812. if (maxDistance <= 0.0f || occluder->GetDistance() <= maxDistance)
  1813. {
  1814. // Check that occluder is big enough on the screen
  1815. const BoundingBox& box = occluder->GetWorldBoundingBox();
  1816. float diagonal = box.Size().Length();
  1817. float compare;
  1818. if (!camera->IsOrthographic())
  1819. compare = diagonal * halfViewSize / occluder->GetDistance();
  1820. else
  1821. compare = diagonal * invOrthoSize;
  1822. if (compare < occluderSizeThreshold_)
  1823. erase = true;
  1824. else
  1825. {
  1826. // Store amount of triangles divided by screen size as a sorting key
  1827. // (best occluders are big and have few triangles)
  1828. occluder->SetSortValue((float)occluder->GetNumOccluderTriangles() / compare);
  1829. }
  1830. }
  1831. else
  1832. erase = true;
  1833. if (erase)
  1834. i = occluders.Erase(i);
  1835. else
  1836. ++i;
  1837. }
  1838. // Sort occluders so that if triangle budget is exceeded, best occluders have been drawn
  1839. if (occluders.Size())
  1840. Sort(occluders.Begin(), occluders.End(), CompareDrawables);
  1841. }
  1842. void View::DrawOccluders(OcclusionBuffer* buffer, const PODVector<Drawable*>& occluders)
  1843. {
  1844. buffer->SetMaxTriangles((unsigned)maxOccluderTriangles_);
  1845. buffer->Clear();
  1846. if (!buffer->IsThreaded())
  1847. {
  1848. // If not threaded, draw occluders one by one and test the next occluder against already rasterized depth
  1849. for (unsigned i = 0; i < occluders.Size(); ++i)
  1850. {
  1851. Drawable* occluder = occluders[i];
  1852. if (i > 0)
  1853. {
  1854. // For subsequent occluders, do a test against the pixel-level occlusion buffer to see if rendering is necessary
  1855. if (!buffer->IsVisible(occluder->GetWorldBoundingBox()))
  1856. continue;
  1857. }
  1858. // Check for running out of triangles
  1859. ++activeOccluders_;
  1860. bool success = occluder->DrawOcclusion(buffer);
  1861. // Draw triangles submitted by this occluder
  1862. buffer->DrawTriangles();
  1863. if (!success)
  1864. break;
  1865. }
  1866. }
  1867. else
  1868. {
  1869. // In threaded mode submit all triangles first, then render (cannot test in this case)
  1870. for (unsigned i = 0; i < occluders.Size(); ++i)
  1871. {
  1872. // Check for running out of triangles
  1873. ++activeOccluders_;
  1874. if (!occluders[i]->DrawOcclusion(buffer))
  1875. break;
  1876. }
  1877. buffer->DrawTriangles();
  1878. }
  1879. // Finally build the depth mip levels
  1880. buffer->BuildDepthHierarchy();
  1881. }
  1882. void View::ProcessLight(LightQueryResult& query, unsigned threadIndex)
  1883. {
  1884. Light* light = query.light_;
  1885. LightType type = light->GetLightType();
  1886. const Frustum& frustum = cullCamera_->GetFrustum();
  1887. // Check if light should be shadowed
  1888. bool isShadowed = drawShadows_ && light->GetCastShadows() && !light->GetPerVertex() && light->GetShadowIntensity() < 1.0f;
  1889. // If shadow distance non-zero, check it
  1890. if (isShadowed && light->GetShadowDistance() > 0.0f && light->GetDistance() > light->GetShadowDistance())
  1891. isShadowed = false;
  1892. // OpenGL ES can not support point light shadows
  1893. #ifdef GL_ES_VERSION_2_0
  1894. if (isShadowed && type == LIGHT_POINT)
  1895. isShadowed = false;
  1896. #endif
  1897. // Get lit geometries. They must match the light mask and be inside the main camera frustum to be considered
  1898. PODVector<Drawable*>& tempDrawables = tempDrawables_[threadIndex];
  1899. query.litGeometries_.Clear();
  1900. switch (type)
  1901. {
  1902. case LIGHT_DIRECTIONAL:
  1903. for (unsigned i = 0; i < geometries_.Size(); ++i)
  1904. {
  1905. if (GetLightMask(geometries_[i]) & light->GetLightMask())
  1906. query.litGeometries_.Push(geometries_[i]);
  1907. }
  1908. break;
  1909. case LIGHT_SPOT:
  1910. {
  1911. FrustumOctreeQuery octreeQuery(tempDrawables, light->GetFrustum(), DRAWABLE_GEOMETRY,
  1912. cullCamera_->GetViewMask());
  1913. octree_->GetDrawables(octreeQuery);
  1914. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1915. {
  1916. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1917. query.litGeometries_.Push(tempDrawables[i]);
  1918. }
  1919. }
  1920. break;
  1921. case LIGHT_POINT:
  1922. {
  1923. SphereOctreeQuery octreeQuery(tempDrawables, Sphere(light->GetNode()->GetWorldPosition(), light->GetRange()),
  1924. DRAWABLE_GEOMETRY, cullCamera_->GetViewMask());
  1925. octree_->GetDrawables(octreeQuery);
  1926. for (unsigned i = 0; i < tempDrawables.Size(); ++i)
  1927. {
  1928. if (tempDrawables[i]->IsInView(frame_) && (GetLightMask(tempDrawables[i]) & light->GetLightMask()))
  1929. query.litGeometries_.Push(tempDrawables[i]);
  1930. }
  1931. }
  1932. break;
  1933. }
  1934. // If no lit geometries or not shadowed, no need to process shadow cameras
  1935. if (query.litGeometries_.Empty() || !isShadowed)
  1936. {
  1937. query.numSplits_ = 0;
  1938. return;
  1939. }
  1940. // Determine number of shadow cameras and setup their initial positions
  1941. SetupShadowCameras(query);
  1942. // Process each split for shadow casters
  1943. query.shadowCasters_.Clear();
  1944. for (unsigned i = 0; i < query.numSplits_; ++i)
  1945. {
  1946. Camera* shadowCamera = query.shadowCameras_[i];
  1947. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1948. query.shadowCasterBegin_[i] = query.shadowCasterEnd_[i] = query.shadowCasters_.Size();
  1949. // For point light check that the face is visible: if not, can skip the split
  1950. if (type == LIGHT_POINT && frustum.IsInsideFast(BoundingBox(shadowCameraFrustum)) == OUTSIDE)
  1951. continue;
  1952. // For directional light check that the split is inside the visible scene: if not, can skip the split
  1953. if (type == LIGHT_DIRECTIONAL)
  1954. {
  1955. if (minZ_ > query.shadowFarSplits_[i])
  1956. continue;
  1957. if (maxZ_ < query.shadowNearSplits_[i])
  1958. continue;
  1959. // Reuse lit geometry query for all except directional lights
  1960. ShadowCasterOctreeQuery query(tempDrawables, shadowCameraFrustum, DRAWABLE_GEOMETRY, cullCamera_->GetViewMask());
  1961. octree_->GetDrawables(query);
  1962. }
  1963. // Check which shadow casters actually contribute to the shadowing
  1964. ProcessShadowCasters(query, tempDrawables, i);
  1965. }
  1966. // If no shadow casters, the light can be rendered unshadowed. At this point we have not allocated a shadow map yet, so the
  1967. // only cost has been the shadow camera setup & queries
  1968. if (query.shadowCasters_.Empty())
  1969. query.numSplits_ = 0;
  1970. }
  1971. void View::ProcessShadowCasters(LightQueryResult& query, const PODVector<Drawable*>& drawables, unsigned splitIndex)
  1972. {
  1973. Light* light = query.light_;
  1974. Camera* shadowCamera = query.shadowCameras_[splitIndex];
  1975. const Frustum& shadowCameraFrustum = shadowCamera->GetFrustum();
  1976. const Matrix3x4& lightView = shadowCamera->GetView();
  1977. const Matrix4& lightProj = shadowCamera->GetProjection();
  1978. LightType type = light->GetLightType();
  1979. query.shadowCasterBox_[splitIndex].Clear();
  1980. // Transform scene frustum into shadow camera's view space for shadow caster visibility check. For point & spot lights,
  1981. // we can use the whole scene frustum. For directional lights, use the intersection of the scene frustum and the split
  1982. // frustum, so that shadow casters do not get rendered into unnecessary splits
  1983. Frustum lightViewFrustum;
  1984. if (type != LIGHT_DIRECTIONAL)
  1985. lightViewFrustum = cullCamera_->GetSplitFrustum(minZ_, maxZ_).Transformed(lightView);
  1986. else
  1987. lightViewFrustum = cullCamera_->GetSplitFrustum(Max(minZ_, query.shadowNearSplits_[splitIndex]),
  1988. Min(maxZ_, query.shadowFarSplits_[splitIndex])).Transformed(lightView);
  1989. BoundingBox lightViewFrustumBox(lightViewFrustum);
  1990. // Check for degenerate split frustum: in that case there is no need to get shadow casters
  1991. if (lightViewFrustum.vertices_[0] == lightViewFrustum.vertices_[4])
  1992. return;
  1993. BoundingBox lightViewBox;
  1994. BoundingBox lightProjBox;
  1995. for (PODVector<Drawable*>::ConstIterator i = drawables.Begin(); i != drawables.End(); ++i)
  1996. {
  1997. Drawable* drawable = *i;
  1998. // In case this is a point or spot light query result reused for optimization, we may have non-shadowcasters included.
  1999. // Check for that first
  2000. if (!drawable->GetCastShadows())
  2001. continue;
  2002. // Check shadow mask
  2003. if (!(GetShadowMask(drawable) & light->GetLightMask()))
  2004. continue;
  2005. // For point light, check that this drawable is inside the split shadow camera frustum
  2006. if (type == LIGHT_POINT && shadowCameraFrustum.IsInsideFast(drawable->GetWorldBoundingBox()) == OUTSIDE)
  2007. continue;
  2008. // Check shadow distance
  2009. // Note: as lights are processed threaded, it is possible a drawable's UpdateBatches() function is called several
  2010. // times. However, this should not cause problems as no scene modification happens at this point.
  2011. if (!drawable->IsInView(frame_, true))
  2012. drawable->UpdateBatches(frame_);
  2013. float maxShadowDistance = drawable->GetShadowDistance();
  2014. float drawDistance = drawable->GetDrawDistance();
  2015. if (drawDistance > 0.0f && (maxShadowDistance <= 0.0f || drawDistance < maxShadowDistance))
  2016. maxShadowDistance = drawDistance;
  2017. if (maxShadowDistance > 0.0f && drawable->GetDistance() > maxShadowDistance)
  2018. continue;
  2019. // Project shadow caster bounding box to light view space for visibility check
  2020. lightViewBox = drawable->GetWorldBoundingBox().Transformed(lightView);
  2021. if (IsShadowCasterVisible(drawable, lightViewBox, shadowCamera, lightView, lightViewFrustum, lightViewFrustumBox))
  2022. {
  2023. // Merge to shadow caster bounding box (only needed for focused spot lights) and add to the list
  2024. if (type == LIGHT_SPOT && light->GetShadowFocus().focus_)
  2025. {
  2026. lightProjBox = lightViewBox.Projected(lightProj);
  2027. query.shadowCasterBox_[splitIndex].Merge(lightProjBox);
  2028. }
  2029. query.shadowCasters_.Push(drawable);
  2030. }
  2031. }
  2032. query.shadowCasterEnd_[splitIndex] = query.shadowCasters_.Size();
  2033. }
  2034. bool View::IsShadowCasterVisible(Drawable* drawable, BoundingBox lightViewBox, Camera* shadowCamera, const Matrix3x4& lightView,
  2035. const Frustum& lightViewFrustum, const BoundingBox& lightViewFrustumBox)
  2036. {
  2037. if (shadowCamera->IsOrthographic())
  2038. {
  2039. // Extrude the light space bounding box up to the far edge of the frustum's light space bounding box
  2040. lightViewBox.max_.z_ = Max(lightViewBox.max_.z_, lightViewFrustumBox.max_.z_);
  2041. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  2042. }
  2043. else
  2044. {
  2045. // If light is not directional, can do a simple check: if object is visible, its shadow is too
  2046. if (drawable->IsInView(frame_))
  2047. return true;
  2048. // For perspective lights, extrusion direction depends on the position of the shadow caster
  2049. Vector3 center = lightViewBox.Center();
  2050. Ray extrusionRay(center, center);
  2051. float extrusionDistance = shadowCamera->GetFarClip();
  2052. float originalDistance = Clamp(center.Length(), M_EPSILON, extrusionDistance);
  2053. // Because of the perspective, the bounding box must also grow when it is extruded to the distance
  2054. float sizeFactor = extrusionDistance / originalDistance;
  2055. // Calculate the endpoint box and merge it to the original. Because it's axis-aligned, it will be larger
  2056. // than necessary, so the test will be conservative
  2057. Vector3 newCenter = extrusionDistance * extrusionRay.direction_;
  2058. Vector3 newHalfSize = lightViewBox.Size() * sizeFactor * 0.5f;
  2059. BoundingBox extrudedBox(newCenter - newHalfSize, newCenter + newHalfSize);
  2060. lightViewBox.Merge(extrudedBox);
  2061. return lightViewFrustum.IsInsideFast(lightViewBox) != OUTSIDE;
  2062. }
  2063. }
  2064. IntRect View::GetShadowMapViewport(Light* light, unsigned splitIndex, Texture2D* shadowMap)
  2065. {
  2066. unsigned width = (unsigned)shadowMap->GetWidth();
  2067. unsigned height = (unsigned)shadowMap->GetHeight();
  2068. switch (light->GetLightType())
  2069. {
  2070. case LIGHT_DIRECTIONAL:
  2071. {
  2072. int numSplits = light->GetNumShadowSplits();
  2073. if (numSplits == 1)
  2074. return IntRect(0, 0, width, height);
  2075. else if (numSplits == 2)
  2076. return IntRect(splitIndex * width / 2, 0, (splitIndex + 1) * width / 2, height);
  2077. else
  2078. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 2, ((splitIndex & 1) + 1) * width / 2,
  2079. (splitIndex / 2 + 1) * height / 2);
  2080. }
  2081. case LIGHT_SPOT:
  2082. return IntRect(0, 0, width, height);
  2083. case LIGHT_POINT:
  2084. return IntRect((splitIndex & 1) * width / 2, (splitIndex / 2) * height / 3, ((splitIndex & 1) + 1) * width / 2,
  2085. (splitIndex / 2 + 1) * height / 3);
  2086. }
  2087. return IntRect();
  2088. }
  2089. void View::SetupShadowCameras(LightQueryResult& query)
  2090. {
  2091. Light* light = query.light_;
  2092. int splits = 0;
  2093. switch (light->GetLightType())
  2094. {
  2095. case LIGHT_DIRECTIONAL:
  2096. {
  2097. const CascadeParameters& cascade = light->GetShadowCascade();
  2098. float nearSplit = cullCamera_->GetNearClip();
  2099. float farSplit;
  2100. int numSplits = light->GetNumShadowSplits();
  2101. while (splits < numSplits)
  2102. {
  2103. // If split is completely beyond camera far clip, we are done
  2104. if (nearSplit > cullCamera_->GetFarClip())
  2105. break;
  2106. farSplit = Min(cullCamera_->GetFarClip(), cascade.splits_[splits]);
  2107. if (farSplit <= nearSplit)
  2108. break;
  2109. // Setup the shadow camera for the split
  2110. Camera* shadowCamera = renderer_->GetShadowCamera();
  2111. query.shadowCameras_[splits] = shadowCamera;
  2112. query.shadowNearSplits_[splits] = nearSplit;
  2113. query.shadowFarSplits_[splits] = farSplit;
  2114. SetupDirLightShadowCamera(shadowCamera, light, nearSplit, farSplit);
  2115. nearSplit = farSplit;
  2116. ++splits;
  2117. }
  2118. }
  2119. break;
  2120. case LIGHT_SPOT:
  2121. {
  2122. Camera* shadowCamera = renderer_->GetShadowCamera();
  2123. query.shadowCameras_[0] = shadowCamera;
  2124. Node* cameraNode = shadowCamera->GetNode();
  2125. Node* lightNode = light->GetNode();
  2126. cameraNode->SetTransform(lightNode->GetWorldPosition(), lightNode->GetWorldRotation());
  2127. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  2128. shadowCamera->SetFarClip(light->GetRange());
  2129. shadowCamera->SetFov(light->GetFov());
  2130. shadowCamera->SetAspectRatio(light->GetAspectRatio());
  2131. splits = 1;
  2132. }
  2133. break;
  2134. case LIGHT_POINT:
  2135. {
  2136. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  2137. {
  2138. Camera* shadowCamera = renderer_->GetShadowCamera();
  2139. query.shadowCameras_[i] = shadowCamera;
  2140. Node* cameraNode = shadowCamera->GetNode();
  2141. // When making a shadowed point light, align the splits along X, Y and Z axes regardless of light rotation
  2142. cameraNode->SetPosition(light->GetNode()->GetWorldPosition());
  2143. cameraNode->SetDirection(*directions[i]);
  2144. shadowCamera->SetNearClip(light->GetShadowNearFarRatio() * light->GetRange());
  2145. shadowCamera->SetFarClip(light->GetRange());
  2146. shadowCamera->SetFov(90.0f);
  2147. shadowCamera->SetAspectRatio(1.0f);
  2148. }
  2149. splits = MAX_CUBEMAP_FACES;
  2150. }
  2151. break;
  2152. }
  2153. query.numSplits_ = (unsigned)splits;
  2154. }
  2155. void View::SetupDirLightShadowCamera(Camera* shadowCamera, Light* light, float nearSplit, float farSplit)
  2156. {
  2157. Node* shadowCameraNode = shadowCamera->GetNode();
  2158. Node* lightNode = light->GetNode();
  2159. float extrusionDistance = cullCamera_->GetFarClip();
  2160. const FocusParameters& parameters = light->GetShadowFocus();
  2161. // Calculate initial position & rotation
  2162. Vector3 pos = cullCamera_->GetNode()->GetWorldPosition() - extrusionDistance * lightNode->GetWorldDirection();
  2163. shadowCameraNode->SetTransform(pos, lightNode->GetWorldRotation());
  2164. // Calculate main camera shadowed frustum in light's view space
  2165. farSplit = Min(farSplit, cullCamera_->GetFarClip());
  2166. // Use the scene Z bounds to limit frustum size if applicable
  2167. if (parameters.focus_)
  2168. {
  2169. nearSplit = Max(minZ_, nearSplit);
  2170. farSplit = Min(maxZ_, farSplit);
  2171. }
  2172. Frustum splitFrustum = cullCamera_->GetSplitFrustum(nearSplit, farSplit);
  2173. Polyhedron frustumVolume;
  2174. frustumVolume.Define(splitFrustum);
  2175. // If focusing enabled, clip the frustum volume by the combined bounding box of the lit geometries within the frustum
  2176. if (parameters.focus_)
  2177. {
  2178. BoundingBox litGeometriesBox;
  2179. for (unsigned i = 0; i < geometries_.Size(); ++i)
  2180. {
  2181. Drawable* drawable = geometries_[i];
  2182. if (drawable->GetMinZ() <= farSplit && drawable->GetMaxZ() >= nearSplit &&
  2183. (GetLightMask(drawable) & light->GetLightMask()))
  2184. litGeometriesBox.Merge(drawable->GetWorldBoundingBox());
  2185. }
  2186. if (litGeometriesBox.Defined())
  2187. {
  2188. frustumVolume.Clip(litGeometriesBox);
  2189. // If volume became empty, restore it to avoid zero size
  2190. if (frustumVolume.Empty())
  2191. frustumVolume.Define(splitFrustum);
  2192. }
  2193. }
  2194. // Transform frustum volume to light space
  2195. const Matrix3x4& lightView = shadowCamera->GetView();
  2196. frustumVolume.Transform(lightView);
  2197. // Fit the frustum volume inside a bounding box. If uniform size, use a sphere instead
  2198. BoundingBox shadowBox;
  2199. if (!parameters.nonUniform_)
  2200. shadowBox.Define(Sphere(frustumVolume));
  2201. else
  2202. shadowBox.Define(frustumVolume);
  2203. shadowCamera->SetOrthographic(true);
  2204. shadowCamera->SetAspectRatio(1.0f);
  2205. shadowCamera->SetNearClip(0.0f);
  2206. shadowCamera->SetFarClip(shadowBox.max_.z_);
  2207. // Center shadow camera on the bounding box. Can not snap to texels yet as the shadow map viewport is unknown
  2208. QuantizeDirLightShadowCamera(shadowCamera, light, IntRect(0, 0, 0, 0), shadowBox);
  2209. }
  2210. void View::FinalizeShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  2211. const BoundingBox& shadowCasterBox)
  2212. {
  2213. const FocusParameters& parameters = light->GetShadowFocus();
  2214. float shadowMapWidth = (float)(shadowViewport.Width());
  2215. LightType type = light->GetLightType();
  2216. if (type == LIGHT_DIRECTIONAL)
  2217. {
  2218. BoundingBox shadowBox;
  2219. shadowBox.max_.y_ = shadowCamera->GetOrthoSize() * 0.5f;
  2220. shadowBox.max_.x_ = shadowCamera->GetAspectRatio() * shadowBox.max_.y_;
  2221. shadowBox.min_.y_ = -shadowBox.max_.y_;
  2222. shadowBox.min_.x_ = -shadowBox.max_.x_;
  2223. // Requantize and snap to shadow map texels
  2224. QuantizeDirLightShadowCamera(shadowCamera, light, shadowViewport, shadowBox);
  2225. }
  2226. if (type == LIGHT_SPOT && parameters.focus_)
  2227. {
  2228. float viewSizeX = Max(Abs(shadowCasterBox.min_.x_), Abs(shadowCasterBox.max_.x_));
  2229. float viewSizeY = Max(Abs(shadowCasterBox.min_.y_), Abs(shadowCasterBox.max_.y_));
  2230. float viewSize = Max(viewSizeX, viewSizeY);
  2231. // Scale the quantization parameters, because view size is in projection space (-1.0 - 1.0)
  2232. float invOrthoSize = 1.0f / shadowCamera->GetOrthoSize();
  2233. float quantize = parameters.quantize_ * invOrthoSize;
  2234. float minView = parameters.minView_ * invOrthoSize;
  2235. viewSize = Max(ceilf(viewSize / quantize) * quantize, minView);
  2236. if (viewSize < 1.0f)
  2237. shadowCamera->SetZoom(1.0f / viewSize);
  2238. }
  2239. // Perform a finalization step for all lights: ensure zoom out of 2 pixels to eliminate border filtering issues
  2240. // For point lights use 4 pixels, as they must not cross sides of the virtual cube map (maximum 3x3 PCF)
  2241. if (shadowCamera->GetZoom() >= 1.0f)
  2242. {
  2243. if (light->GetLightType() != LIGHT_POINT)
  2244. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 2.0f) / shadowMapWidth));
  2245. else
  2246. {
  2247. #ifdef URHO3D_OPENGL
  2248. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 3.0f) / shadowMapWidth));
  2249. #else
  2250. shadowCamera->SetZoom(shadowCamera->GetZoom() * ((shadowMapWidth - 4.0f) / shadowMapWidth));
  2251. #endif
  2252. }
  2253. }
  2254. }
  2255. void View::QuantizeDirLightShadowCamera(Camera* shadowCamera, Light* light, const IntRect& shadowViewport,
  2256. const BoundingBox& viewBox)
  2257. {
  2258. Node* shadowCameraNode = shadowCamera->GetNode();
  2259. const FocusParameters& parameters = light->GetShadowFocus();
  2260. float shadowMapWidth = (float)(shadowViewport.Width());
  2261. float minX = viewBox.min_.x_;
  2262. float minY = viewBox.min_.y_;
  2263. float maxX = viewBox.max_.x_;
  2264. float maxY = viewBox.max_.y_;
  2265. Vector2 center((minX + maxX) * 0.5f, (minY + maxY) * 0.5f);
  2266. Vector2 viewSize(maxX - minX, maxY - minY);
  2267. // Quantize size to reduce swimming
  2268. // Note: if size is uniform and there is no focusing, quantization is unnecessary
  2269. if (parameters.nonUniform_)
  2270. {
  2271. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2272. viewSize.y_ = ceilf(sqrtf(viewSize.y_ / parameters.quantize_));
  2273. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2274. viewSize.y_ = Max(viewSize.y_ * viewSize.y_ * parameters.quantize_, parameters.minView_);
  2275. }
  2276. else if (parameters.focus_)
  2277. {
  2278. viewSize.x_ = Max(viewSize.x_, viewSize.y_);
  2279. viewSize.x_ = ceilf(sqrtf(viewSize.x_ / parameters.quantize_));
  2280. viewSize.x_ = Max(viewSize.x_ * viewSize.x_ * parameters.quantize_, parameters.minView_);
  2281. viewSize.y_ = viewSize.x_;
  2282. }
  2283. shadowCamera->SetOrthoSize(viewSize);
  2284. // Center shadow camera to the view space bounding box
  2285. Quaternion rot(shadowCameraNode->GetWorldRotation());
  2286. Vector3 adjust(center.x_, center.y_, 0.0f);
  2287. shadowCameraNode->Translate(rot * adjust, TS_WORLD);
  2288. // If the shadow map viewport is known, snap to whole texels
  2289. if (shadowMapWidth > 0.0f)
  2290. {
  2291. Vector3 viewPos(rot.Inverse() * shadowCameraNode->GetWorldPosition());
  2292. // Take into account that shadow map border will not be used
  2293. float invActualSize = 1.0f / (shadowMapWidth - 2.0f);
  2294. Vector2 texelSize(viewSize.x_ * invActualSize, viewSize.y_ * invActualSize);
  2295. Vector3 snap(-fmodf(viewPos.x_, texelSize.x_), -fmodf(viewPos.y_, texelSize.y_), 0.0f);
  2296. shadowCameraNode->Translate(rot * snap, TS_WORLD);
  2297. }
  2298. }
  2299. void View::FindZone(Drawable* drawable)
  2300. {
  2301. Vector3 center = drawable->GetWorldBoundingBox().Center();
  2302. int bestPriority = M_MIN_INT;
  2303. Zone* newZone = 0;
  2304. // If bounding box center is in view, the zone assignment is conclusive also for next frames. Otherwise it is temporary
  2305. // (possibly incorrect) and must be re-evaluated on the next frame
  2306. bool temporary = !cullCamera_->GetFrustum().IsInside(center);
  2307. // First check if the current zone remains a conclusive result
  2308. Zone* lastZone = drawable->GetZone();
  2309. if (lastZone && (lastZone->GetViewMask() & cullCamera_->GetViewMask()) && lastZone->GetPriority() >= highestZonePriority_ &&
  2310. (drawable->GetZoneMask() & lastZone->GetZoneMask()) && lastZone->IsInside(center))
  2311. newZone = lastZone;
  2312. else
  2313. {
  2314. for (PODVector<Zone*>::Iterator i = zones_.Begin(); i != zones_.End(); ++i)
  2315. {
  2316. Zone* zone = *i;
  2317. int priority = zone->GetPriority();
  2318. if (priority > bestPriority && (drawable->GetZoneMask() & zone->GetZoneMask()) && zone->IsInside(center))
  2319. {
  2320. newZone = zone;
  2321. bestPriority = priority;
  2322. }
  2323. }
  2324. }
  2325. drawable->SetZone(newZone, temporary);
  2326. }
  2327. Technique* View::GetTechnique(Drawable* drawable, Material* material)
  2328. {
  2329. if (!material)
  2330. return renderer_->GetDefaultMaterial()->GetTechniques()[0].technique_;
  2331. const Vector<TechniqueEntry>& techniques = material->GetTechniques();
  2332. // If only one technique, no choice
  2333. if (techniques.Size() == 1)
  2334. return techniques[0].technique_;
  2335. else
  2336. {
  2337. float lodDistance = drawable->GetLodDistance();
  2338. // Check for suitable technique. Techniques should be ordered like this:
  2339. // Most distant & highest quality
  2340. // Most distant & lowest quality
  2341. // Second most distant & highest quality
  2342. // ...
  2343. for (unsigned i = 0; i < techniques.Size(); ++i)
  2344. {
  2345. const TechniqueEntry& entry = techniques[i];
  2346. Technique* tech = entry.technique_;
  2347. if (!tech || (!tech->IsSupported()) || materialQuality_ < entry.qualityLevel_)
  2348. continue;
  2349. if (lodDistance >= entry.lodDistance_)
  2350. return tech;
  2351. }
  2352. // If no suitable technique found, fallback to the last
  2353. return techniques.Size() ? techniques.Back().technique_ : (Technique*)0;
  2354. }
  2355. }
  2356. void View::CheckMaterialForAuxView(Material* material)
  2357. {
  2358. const HashMap<TextureUnit, SharedPtr<Texture> >& textures = material->GetTextures();
  2359. for (HashMap<TextureUnit, SharedPtr<Texture> >::ConstIterator i = textures.Begin(); i != textures.End(); ++i)
  2360. {
  2361. Texture* texture = i->second_.Get();
  2362. if (texture && texture->GetUsage() == TEXTURE_RENDERTARGET)
  2363. {
  2364. // Have to check cube & 2D textures separately
  2365. if (texture->GetType() == Texture2D::GetTypeStatic())
  2366. {
  2367. Texture2D* tex2D = static_cast<Texture2D*>(texture);
  2368. RenderSurface* target = tex2D->GetRenderSurface();
  2369. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2370. target->QueueUpdate();
  2371. }
  2372. else if (texture->GetType() == TextureCube::GetTypeStatic())
  2373. {
  2374. TextureCube* texCube = static_cast<TextureCube*>(texture);
  2375. for (unsigned j = 0; j < MAX_CUBEMAP_FACES; ++j)
  2376. {
  2377. RenderSurface* target = texCube->GetRenderSurface((CubeMapFace)j);
  2378. if (target && target->GetUpdateMode() == SURFACE_UPDATEVISIBLE)
  2379. target->QueueUpdate();
  2380. }
  2381. }
  2382. }
  2383. }
  2384. // Flag as processed so we can early-out next time we come across this material on the same frame
  2385. material->MarkForAuxView(frame_.frameNumber_);
  2386. }
  2387. void View::AddBatchToQueue(BatchQueue& batchQueue, Batch& batch, Technique* tech, bool allowInstancing, bool allowShadows)
  2388. {
  2389. if (!batch.material_)
  2390. batch.material_ = renderer_->GetDefaultMaterial();
  2391. // Convert to instanced if possible
  2392. if (allowInstancing && batch.geometryType_ == GEOM_STATIC && batch.geometry_->GetIndexBuffer())
  2393. batch.geometryType_ = GEOM_INSTANCED;
  2394. if (batch.geometryType_ == GEOM_INSTANCED)
  2395. {
  2396. BatchGroupKey key(batch);
  2397. HashMap<BatchGroupKey, BatchGroup>::Iterator i = batchQueue.batchGroups_.Find(key);
  2398. if (i == batchQueue.batchGroups_.End())
  2399. {
  2400. // Create a new group based on the batch
  2401. // In case the group remains below the instancing limit, do not enable instancing shaders yet
  2402. BatchGroup newGroup(batch);
  2403. newGroup.geometryType_ = GEOM_STATIC;
  2404. renderer_->SetBatchShaders(newGroup, tech, allowShadows);
  2405. newGroup.CalculateSortKey();
  2406. i = batchQueue.batchGroups_.Insert(MakePair(key, newGroup));
  2407. }
  2408. int oldSize = i->second_.instances_.Size();
  2409. i->second_.AddTransforms(batch);
  2410. // Convert to using instancing shaders when the instancing limit is reached
  2411. if (oldSize < minInstances_ && (int)i->second_.instances_.Size() >= minInstances_)
  2412. {
  2413. i->second_.geometryType_ = GEOM_INSTANCED;
  2414. renderer_->SetBatchShaders(i->second_, tech, allowShadows);
  2415. i->second_.CalculateSortKey();
  2416. }
  2417. }
  2418. else
  2419. {
  2420. renderer_->SetBatchShaders(batch, tech, allowShadows);
  2421. batch.CalculateSortKey();
  2422. // If batch is static with multiple world transforms and cannot instance, we must push copies of the batch individually
  2423. if (batch.geometryType_ == GEOM_STATIC && batch.numWorldTransforms_ > 1)
  2424. {
  2425. unsigned numTransforms = batch.numWorldTransforms_;
  2426. batch.numWorldTransforms_ = 1;
  2427. for (unsigned i = 0; i < numTransforms; ++i)
  2428. {
  2429. // Move the transform pointer to generate copies of the batch which only refer to 1 world transform
  2430. batchQueue.batches_.Push(batch);
  2431. ++batch.worldTransform_;
  2432. }
  2433. }
  2434. else
  2435. batchQueue.batches_.Push(batch);
  2436. }
  2437. }
  2438. void View::PrepareInstancingBuffer()
  2439. {
  2440. // Prepare instancing buffer from the source view
  2441. /// \todo If rendering the same view several times back-to-back, would not need to refill the buffer
  2442. if (sourceView_)
  2443. {
  2444. sourceView_->PrepareInstancingBuffer();
  2445. return;
  2446. }
  2447. URHO3D_PROFILE(PrepareInstancingBuffer);
  2448. unsigned totalInstances = 0;
  2449. for (HashMap<unsigned, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2450. totalInstances += i->second_.GetNumInstances();
  2451. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2452. {
  2453. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2454. totalInstances += i->shadowSplits_[j].shadowBatches_.GetNumInstances();
  2455. totalInstances += i->litBaseBatches_.GetNumInstances();
  2456. totalInstances += i->litBatches_.GetNumInstances();
  2457. }
  2458. if (!totalInstances || !renderer_->ResizeInstancingBuffer(totalInstances))
  2459. return;
  2460. VertexBuffer* instancingBuffer = renderer_->GetInstancingBuffer();
  2461. unsigned freeIndex = 0;
  2462. void* dest = instancingBuffer->Lock(0, totalInstances, true);
  2463. if (!dest)
  2464. return;
  2465. for (HashMap<unsigned, BatchQueue>::Iterator i = batchQueues_.Begin(); i != batchQueues_.End(); ++i)
  2466. i->second_.SetTransforms(dest, freeIndex);
  2467. for (Vector<LightBatchQueue>::Iterator i = lightQueues_.Begin(); i != lightQueues_.End(); ++i)
  2468. {
  2469. for (unsigned j = 0; j < i->shadowSplits_.Size(); ++j)
  2470. i->shadowSplits_[j].shadowBatches_.SetTransforms(dest, freeIndex);
  2471. i->litBaseBatches_.SetTransforms(dest, freeIndex);
  2472. i->litBatches_.SetTransforms(dest, freeIndex);
  2473. }
  2474. instancingBuffer->Unlock();
  2475. }
  2476. void View::SetupLightVolumeBatch(Batch& batch)
  2477. {
  2478. Light* light = batch.lightQueue_->light_;
  2479. LightType type = light->GetLightType();
  2480. Vector3 cameraPos = camera_->GetNode()->GetWorldPosition();
  2481. float lightDist;
  2482. graphics_->SetBlendMode(light->IsNegative() ? BLEND_SUBTRACT : BLEND_ADD);
  2483. graphics_->SetDepthBias(0.0f, 0.0f);
  2484. graphics_->SetDepthWrite(false);
  2485. graphics_->SetFillMode(FILL_SOLID);
  2486. graphics_->SetClipPlane(false);
  2487. if (type != LIGHT_DIRECTIONAL)
  2488. {
  2489. if (type == LIGHT_POINT)
  2490. lightDist = Sphere(light->GetNode()->GetWorldPosition(), light->GetRange() * 1.25f).Distance(cameraPos);
  2491. else
  2492. lightDist = light->GetFrustum().Distance(cameraPos);
  2493. // Draw front faces if not inside light volume
  2494. if (lightDist < camera_->GetNearClip() * 2.0f)
  2495. {
  2496. renderer_->SetCullMode(CULL_CW, camera_);
  2497. graphics_->SetDepthTest(CMP_GREATER);
  2498. }
  2499. else
  2500. {
  2501. renderer_->SetCullMode(CULL_CCW, camera_);
  2502. graphics_->SetDepthTest(CMP_LESSEQUAL);
  2503. }
  2504. }
  2505. else
  2506. {
  2507. // In case the same camera is used for multiple views with differing aspect ratios (not recommended)
  2508. // refresh the directional light's model transform before rendering
  2509. light->GetVolumeTransform(camera_);
  2510. graphics_->SetCullMode(CULL_NONE);
  2511. graphics_->SetDepthTest(CMP_ALWAYS);
  2512. }
  2513. graphics_->SetScissorTest(false);
  2514. if (!noStencil_)
  2515. graphics_->SetStencilTest(true, CMP_NOTEQUAL, OP_KEEP, OP_KEEP, OP_KEEP, 0, light->GetLightMask());
  2516. else
  2517. graphics_->SetStencilTest(false);
  2518. }
  2519. void View::RenderShadowMap(const LightBatchQueue& queue)
  2520. {
  2521. URHO3D_PROFILE(RenderShadowMap);
  2522. Texture2D* shadowMap = queue.shadowMap_;
  2523. graphics_->SetTexture(TU_SHADOWMAP, 0);
  2524. graphics_->SetFillMode(FILL_SOLID);
  2525. graphics_->SetClipPlane(false);
  2526. graphics_->SetStencilTest(false);
  2527. // Set shadow depth bias
  2528. BiasParameters parameters = queue.light_->GetShadowBias();
  2529. // the shadow map is a depth stencil map
  2530. if (shadowMap->GetUsage() == TEXTURE_DEPTHSTENCIL)
  2531. {
  2532. graphics_->SetColorWrite(false);
  2533. graphics_->SetDepthStencil(shadowMap);
  2534. graphics_->SetRenderTarget(0, shadowMap->GetRenderSurface()->GetLinkedRenderTarget());
  2535. // disable other render targets
  2536. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  2537. graphics_->SetRenderTarget(i, (RenderSurface*) 0);
  2538. graphics_->SetViewport(IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  2539. graphics_->Clear(CLEAR_DEPTH);
  2540. }
  2541. else // if the shadow map is a render texture
  2542. {
  2543. graphics_->SetColorWrite(true);
  2544. graphics_->SetRenderTarget(0, shadowMap);
  2545. // disable other render targets
  2546. for (unsigned i = 1; i < MAX_RENDERTARGETS; ++i)
  2547. graphics_->SetRenderTarget(i, (RenderSurface*) 0);
  2548. graphics_->SetDepthStencil(renderer_->GetDepthStencil(shadowMap->GetWidth(), shadowMap->GetHeight()));
  2549. graphics_->SetViewport(IntRect(0, 0, shadowMap->GetWidth(), shadowMap->GetHeight()));
  2550. graphics_->Clear(CLEAR_DEPTH | CLEAR_COLOR, Color::WHITE);
  2551. parameters = BiasParameters(0.0f, 0.0f);
  2552. }
  2553. // Render each of the splits
  2554. for (unsigned i = 0; i < queue.shadowSplits_.Size(); ++i)
  2555. {
  2556. const ShadowBatchQueue& shadowQueue = queue.shadowSplits_[i];
  2557. float multiplier = 1.0f;
  2558. // For directional light cascade splits, adjust depth bias according to the far clip ratio of the splits
  2559. if (i > 0 && queue.light_->GetLightType() == LIGHT_DIRECTIONAL)
  2560. {
  2561. multiplier =
  2562. Max(shadowQueue.shadowCamera_->GetFarClip() / queue.shadowSplits_[0].shadowCamera_->GetFarClip(), 1.0f);
  2563. multiplier = 1.0f + (multiplier - 1.0f) * queue.light_->GetShadowCascade().biasAutoAdjust_;
  2564. // Quantize multiplier to prevent creation of too many rasterizer states on D3D11
  2565. multiplier = (int)(multiplier * 10.0f) / 10.0f;
  2566. }
  2567. // Perform further modification of depth bias on OpenGL ES, as shadow calculations' precision is limited
  2568. float addition = 0.0f;
  2569. #ifdef GL_ES_VERSION_2_0
  2570. multiplier *= renderer_->GetMobileShadowBiasMul();
  2571. addition = renderer_->GetMobileShadowBiasAdd();
  2572. #endif
  2573. graphics_->SetDepthBias(multiplier * parameters.constantBias_ + addition, multiplier * parameters.slopeScaledBias_);
  2574. if (!shadowQueue.shadowBatches_.IsEmpty())
  2575. {
  2576. graphics_->SetViewport(shadowQueue.shadowViewport_);
  2577. shadowQueue.shadowBatches_.Draw(this, shadowQueue.shadowCamera_, false, false, true);
  2578. }
  2579. }
  2580. renderer_->ApplyShadowMapFilter(this, shadowMap);
  2581. // reset some parameters
  2582. graphics_->SetColorWrite(true);
  2583. graphics_->SetDepthBias(0.0f, 0.0f);
  2584. }
  2585. RenderSurface* View::GetDepthStencil(RenderSurface* renderTarget)
  2586. {
  2587. // If using the backbuffer, return the backbuffer depth-stencil
  2588. if (!renderTarget)
  2589. return 0;
  2590. // Then check for linked depth-stencil
  2591. RenderSurface* depthStencil = renderTarget->GetLinkedDepthStencil();
  2592. // Finally get one from Renderer
  2593. if (!depthStencil)
  2594. depthStencil = renderer_->GetDepthStencil(renderTarget->GetWidth(), renderTarget->GetHeight());
  2595. return depthStencil;
  2596. }
  2597. RenderSurface* View::GetRenderSurfaceFromTexture(Texture* texture, CubeMapFace face)
  2598. {
  2599. if (!texture)
  2600. return 0;
  2601. if (texture->GetType() == Texture2D::GetTypeStatic())
  2602. return static_cast<Texture2D*>(texture)->GetRenderSurface();
  2603. else if (texture->GetType() == TextureCube::GetTypeStatic())
  2604. return static_cast<TextureCube*>(texture)->GetRenderSurface(face);
  2605. else
  2606. return 0;
  2607. }
  2608. Texture* View::FindNamedTexture(const String& name, bool isRenderTarget, bool isVolumeMap)
  2609. {
  2610. // Check rendertargets first
  2611. StringHash nameHash(name);
  2612. if (renderTargets_.Contains(nameHash))
  2613. return renderTargets_[nameHash];
  2614. // Then the resource system
  2615. ResourceCache* cache = GetSubsystem<ResourceCache>();
  2616. // Check existing resources first. This does not load resources, so we can afford to guess the resource type wrong
  2617. // without having to rely on the file extension
  2618. Texture* texture = cache->GetExistingResource<Texture2D>(name);
  2619. if (!texture)
  2620. texture = cache->GetExistingResource<TextureCube>(name);
  2621. if (!texture)
  2622. texture = cache->GetExistingResource<Texture3D>(name);
  2623. if (texture)
  2624. return texture;
  2625. // If not a rendertarget (which will never be loaded from a file), finally also try to load the texture
  2626. // This will log an error if not found; the texture binding will be cleared in that case to not constantly spam the log
  2627. if (!isRenderTarget)
  2628. {
  2629. if (GetExtension(name) == ".xml")
  2630. {
  2631. // Assume 3D textures are only bound to the volume map unit, otherwise it's a cube texture
  2632. #ifdef DESKTOP_GRAPHICS
  2633. if (isVolumeMap)
  2634. return cache->GetResource<Texture3D>(name);
  2635. else
  2636. #endif
  2637. return cache->GetResource<TextureCube>(name);
  2638. }
  2639. else
  2640. return cache->GetResource<Texture2D>(name);
  2641. }
  2642. return 0;
  2643. }
  2644. }