View.cpp 127 KB

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