renderer_scene_cull.cpp 166 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336
  1. /**************************************************************************/
  2. /* renderer_scene_cull.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "renderer_scene_cull.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/object/worker_thread_pool.h"
  33. #include "rendering_light_culler.h"
  34. #include "rendering_server_default.h"
  35. #if defined(DEBUG_ENABLED) && defined(TOOLS_ENABLED)
  36. // This is used only to obtain node paths for user-friendly physics interpolation warnings.
  37. #include "scene/main/node.h"
  38. #endif
  39. /* HALTON SEQUENCE */
  40. #ifndef _3D_DISABLED
  41. static float get_halton_value(int p_index, int p_base) {
  42. float f = 1;
  43. float r = 0;
  44. while (p_index > 0) {
  45. f = f / static_cast<float>(p_base);
  46. r = r + f * (p_index % p_base);
  47. p_index = p_index / p_base;
  48. }
  49. return r * 2.0f - 1.0f;
  50. }
  51. #endif // _3D_DISABLED
  52. /* EVENT QUEUING */
  53. void RendererSceneCull::tick() {
  54. if (_interpolation_data.interpolation_enabled) {
  55. update_interpolation_tick(true);
  56. }
  57. }
  58. void RendererSceneCull::pre_draw(bool p_will_draw) {
  59. if (_interpolation_data.interpolation_enabled) {
  60. update_interpolation_frame(p_will_draw);
  61. }
  62. }
  63. /* CAMERA API */
  64. RID RendererSceneCull::camera_allocate() {
  65. return camera_owner.allocate_rid();
  66. }
  67. void RendererSceneCull::camera_initialize(RID p_rid) {
  68. camera_owner.initialize_rid(p_rid);
  69. }
  70. void RendererSceneCull::camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) {
  71. Camera *camera = camera_owner.get_or_null(p_camera);
  72. ERR_FAIL_NULL(camera);
  73. camera->type = Camera::PERSPECTIVE;
  74. camera->fov = p_fovy_degrees;
  75. camera->znear = p_z_near;
  76. camera->zfar = p_z_far;
  77. }
  78. void RendererSceneCull::camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) {
  79. Camera *camera = camera_owner.get_or_null(p_camera);
  80. ERR_FAIL_NULL(camera);
  81. camera->type = Camera::ORTHOGONAL;
  82. camera->size = p_size;
  83. camera->znear = p_z_near;
  84. camera->zfar = p_z_far;
  85. }
  86. void RendererSceneCull::camera_set_frustum(RID p_camera, float p_size, Vector2 p_offset, float p_z_near, float p_z_far) {
  87. Camera *camera = camera_owner.get_or_null(p_camera);
  88. ERR_FAIL_NULL(camera);
  89. camera->type = Camera::FRUSTUM;
  90. camera->size = p_size;
  91. camera->offset = p_offset;
  92. camera->znear = p_z_near;
  93. camera->zfar = p_z_far;
  94. }
  95. void RendererSceneCull::camera_set_transform(RID p_camera, const Transform3D &p_transform) {
  96. Camera *camera = camera_owner.get_or_null(p_camera);
  97. ERR_FAIL_NULL(camera);
  98. camera->transform = p_transform.orthonormalized();
  99. }
  100. void RendererSceneCull::camera_set_cull_mask(RID p_camera, uint32_t p_layers) {
  101. Camera *camera = camera_owner.get_or_null(p_camera);
  102. ERR_FAIL_NULL(camera);
  103. camera->visible_layers = p_layers;
  104. }
  105. void RendererSceneCull::camera_set_environment(RID p_camera, RID p_env) {
  106. Camera *camera = camera_owner.get_or_null(p_camera);
  107. ERR_FAIL_NULL(camera);
  108. camera->env = p_env;
  109. }
  110. void RendererSceneCull::camera_set_camera_attributes(RID p_camera, RID p_attributes) {
  111. Camera *camera = camera_owner.get_or_null(p_camera);
  112. ERR_FAIL_NULL(camera);
  113. camera->attributes = p_attributes;
  114. }
  115. void RendererSceneCull::camera_set_compositor(RID p_camera, RID p_compositor) {
  116. Camera *camera = camera_owner.get_or_null(p_camera);
  117. ERR_FAIL_NULL(camera);
  118. camera->compositor = p_compositor;
  119. }
  120. void RendererSceneCull::camera_set_use_vertical_aspect(RID p_camera, bool p_enable) {
  121. Camera *camera = camera_owner.get_or_null(p_camera);
  122. ERR_FAIL_NULL(camera);
  123. camera->vaspect = p_enable;
  124. }
  125. bool RendererSceneCull::is_camera(RID p_camera) const {
  126. return camera_owner.owns(p_camera);
  127. }
  128. /* OCCLUDER API */
  129. RID RendererSceneCull::occluder_allocate() {
  130. return RendererSceneOcclusionCull::get_singleton()->occluder_allocate();
  131. }
  132. void RendererSceneCull::occluder_initialize(RID p_rid) {
  133. RendererSceneOcclusionCull::get_singleton()->occluder_initialize(p_rid);
  134. }
  135. void RendererSceneCull::occluder_set_mesh(RID p_occluder, const PackedVector3Array &p_vertices, const PackedInt32Array &p_indices) {
  136. RendererSceneOcclusionCull::get_singleton()->occluder_set_mesh(p_occluder, p_vertices, p_indices);
  137. }
  138. /* SCENARIO API */
  139. void RendererSceneCull::_instance_pair(Instance *p_A, Instance *p_B) {
  140. RendererSceneCull *self = (RendererSceneCull *)singleton;
  141. Instance *A = p_A;
  142. Instance *B = p_B;
  143. //instance indices are designed so greater always contains lesser
  144. if (A->base_type > B->base_type) {
  145. SWAP(A, B); //lesser always first
  146. }
  147. if (B->base_type == RS::INSTANCE_LIGHT && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  148. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  149. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  150. if (!(light->cull_mask & A->layer_mask)) {
  151. // Early return if the object's layer mask doesn't match the light's cull mask.
  152. return;
  153. }
  154. geom->lights.insert(B);
  155. light->geometries.insert(A);
  156. if (geom->can_cast_shadows) {
  157. light->make_shadow_dirty();
  158. }
  159. if (A->scenario && A->array_index >= 0) {
  160. InstanceData &idata = A->scenario->instance_data[A->array_index];
  161. idata.flags |= InstanceData::FLAG_GEOM_LIGHTING_DIRTY;
  162. }
  163. if (light->uses_projector) {
  164. geom->projector_count++;
  165. if (geom->projector_count == 1) {
  166. InstanceData &idata = A->scenario->instance_data[A->array_index];
  167. idata.flags |= InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY;
  168. }
  169. }
  170. if (light->uses_softshadow) {
  171. geom->softshadow_count++;
  172. if (geom->softshadow_count == 1) {
  173. InstanceData &idata = A->scenario->instance_data[A->array_index];
  174. idata.flags |= InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY;
  175. }
  176. }
  177. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && B->base_type == RS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  178. if (!(A->layer_mask & RSG::light_storage->reflection_probe_get_reflection_mask(B->base))) {
  179. // Early return if the object's layer mask doesn't match the reflection mask.
  180. return;
  181. }
  182. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  183. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  184. geom->reflection_probes.insert(B);
  185. reflection_probe->geometries.insert(A);
  186. if (A->scenario && A->array_index >= 0) {
  187. InstanceData &idata = A->scenario->instance_data[A->array_index];
  188. idata.flags |= InstanceData::FLAG_GEOM_REFLECTION_DIRTY;
  189. }
  190. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && B->base_type == RS::INSTANCE_DECAL && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  191. InstanceDecalData *decal = static_cast<InstanceDecalData *>(B->base_data);
  192. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  193. if (!(decal->cull_mask & A->layer_mask)) {
  194. // Early return if the object's layer mask doesn't match the decal's cull mask.
  195. return;
  196. }
  197. geom->decals.insert(B);
  198. decal->geometries.insert(A);
  199. if (A->scenario && A->array_index >= 0) {
  200. InstanceData &idata = A->scenario->instance_data[A->array_index];
  201. idata.flags |= InstanceData::FLAG_GEOM_DECAL_DIRTY;
  202. }
  203. } else if (B->base_type == RS::INSTANCE_LIGHTMAP && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  204. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(B->base_data);
  205. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  206. if (A->dynamic_gi) {
  207. geom->lightmap_captures.insert(B);
  208. lightmap_data->geometries.insert(A);
  209. if (A->scenario && A->array_index >= 0) {
  210. InstanceData &idata = A->scenario->instance_data[A->array_index];
  211. idata.flags |= InstanceData::FLAG_LIGHTMAP_CAPTURE;
  212. }
  213. ((RendererSceneCull *)self)->_instance_queue_update(A, false, false); //need to update capture
  214. }
  215. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_VOXEL_GI) && B->base_type == RS::INSTANCE_VOXEL_GI && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  216. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(B->base_data);
  217. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  218. geom->voxel_gi_instances.insert(B);
  219. if (A->dynamic_gi) {
  220. voxel_gi->dynamic_geometries.insert(A);
  221. } else {
  222. voxel_gi->geometries.insert(A);
  223. }
  224. if (A->scenario && A->array_index >= 0) {
  225. InstanceData &idata = A->scenario->instance_data[A->array_index];
  226. idata.flags |= InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY;
  227. }
  228. } else if (B->base_type == RS::INSTANCE_VOXEL_GI && A->base_type == RS::INSTANCE_LIGHT) {
  229. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(B->base_data);
  230. voxel_gi->lights.insert(A);
  231. } else if (B->base_type == RS::INSTANCE_PARTICLES_COLLISION && A->base_type == RS::INSTANCE_PARTICLES) {
  232. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(B->base_data);
  233. if ((collision->cull_mask & A->layer_mask)) {
  234. RSG::particles_storage->particles_add_collision(A->base, collision->instance);
  235. }
  236. }
  237. }
  238. void RendererSceneCull::_instance_unpair(Instance *p_A, Instance *p_B) {
  239. RendererSceneCull *self = singleton;
  240. Instance *A = p_A;
  241. Instance *B = p_B;
  242. //instance indices are designed so greater always contains lesser
  243. if (A->base_type > B->base_type) {
  244. SWAP(A, B); //lesser always first
  245. }
  246. if (B->base_type == RS::INSTANCE_LIGHT && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  247. InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
  248. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  249. if (!(light->cull_mask & A->layer_mask)) {
  250. // Early return if the object's layer mask doesn't match the light's cull mask.
  251. return;
  252. }
  253. geom->lights.erase(B);
  254. light->geometries.erase(A);
  255. if (geom->can_cast_shadows) {
  256. light->make_shadow_dirty();
  257. }
  258. if (A->scenario && A->array_index >= 0) {
  259. InstanceData &idata = A->scenario->instance_data[A->array_index];
  260. idata.flags |= InstanceData::FLAG_GEOM_LIGHTING_DIRTY;
  261. }
  262. if (light->uses_projector) {
  263. #ifdef DEBUG_ENABLED
  264. if (geom->projector_count == 0) {
  265. ERR_PRINT("geom->projector_count==0 - BUG!");
  266. }
  267. #endif
  268. geom->projector_count--;
  269. if (geom->projector_count == 0) {
  270. InstanceData &idata = A->scenario->instance_data[A->array_index];
  271. idata.flags |= InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY;
  272. }
  273. }
  274. if (light->uses_softshadow) {
  275. #ifdef DEBUG_ENABLED
  276. if (geom->softshadow_count == 0) {
  277. ERR_PRINT("geom->softshadow_count==0 - BUG!");
  278. }
  279. #endif
  280. geom->softshadow_count--;
  281. if (geom->softshadow_count == 0) {
  282. InstanceData &idata = A->scenario->instance_data[A->array_index];
  283. idata.flags |= InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY;
  284. }
  285. }
  286. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && B->base_type == RS::INSTANCE_REFLECTION_PROBE && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  287. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
  288. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  289. geom->reflection_probes.erase(B);
  290. reflection_probe->geometries.erase(A);
  291. if (A->scenario && A->array_index >= 0) {
  292. InstanceData &idata = A->scenario->instance_data[A->array_index];
  293. idata.flags |= InstanceData::FLAG_GEOM_REFLECTION_DIRTY;
  294. }
  295. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && B->base_type == RS::INSTANCE_DECAL && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  296. InstanceDecalData *decal = static_cast<InstanceDecalData *>(B->base_data);
  297. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  298. if (!(decal->cull_mask & A->layer_mask)) {
  299. // Early return if the object's layer mask doesn't match the decal's cull mask.
  300. return;
  301. }
  302. geom->decals.erase(B);
  303. decal->geometries.erase(A);
  304. if (A->scenario && A->array_index >= 0) {
  305. InstanceData &idata = A->scenario->instance_data[A->array_index];
  306. idata.flags |= InstanceData::FLAG_GEOM_DECAL_DIRTY;
  307. }
  308. } else if (B->base_type == RS::INSTANCE_LIGHTMAP && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  309. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(B->base_data);
  310. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  311. if (A->dynamic_gi) {
  312. geom->lightmap_captures.erase(B);
  313. if (geom->lightmap_captures.is_empty() && A->scenario && A->array_index >= 0) {
  314. InstanceData &idata = A->scenario->instance_data[A->array_index];
  315. idata.flags &= ~InstanceData::FLAG_LIGHTMAP_CAPTURE;
  316. }
  317. lightmap_data->geometries.erase(A);
  318. self->_instance_queue_update(A, false, false); //need to update capture
  319. }
  320. } else if (self->geometry_instance_pair_mask & (1 << RS::INSTANCE_VOXEL_GI) && B->base_type == RS::INSTANCE_VOXEL_GI && ((1 << A->base_type) & RS::INSTANCE_GEOMETRY_MASK)) {
  321. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(B->base_data);
  322. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
  323. geom->voxel_gi_instances.erase(B);
  324. if (A->dynamic_gi) {
  325. voxel_gi->dynamic_geometries.erase(A);
  326. } else {
  327. voxel_gi->geometries.erase(A);
  328. }
  329. if (A->scenario && A->array_index >= 0) {
  330. InstanceData &idata = A->scenario->instance_data[A->array_index];
  331. idata.flags |= InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY;
  332. }
  333. } else if (B->base_type == RS::INSTANCE_VOXEL_GI && A->base_type == RS::INSTANCE_LIGHT) {
  334. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(B->base_data);
  335. voxel_gi->lights.erase(A);
  336. } else if (B->base_type == RS::INSTANCE_PARTICLES_COLLISION && A->base_type == RS::INSTANCE_PARTICLES) {
  337. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(B->base_data);
  338. if ((collision->cull_mask & A->layer_mask)) {
  339. RSG::particles_storage->particles_remove_collision(A->base, collision->instance);
  340. }
  341. }
  342. }
  343. RID RendererSceneCull::scenario_allocate() {
  344. return scenario_owner.allocate_rid();
  345. }
  346. void RendererSceneCull::scenario_initialize(RID p_rid) {
  347. scenario_owner.initialize_rid(p_rid);
  348. Scenario *scenario = scenario_owner.get_or_null(p_rid);
  349. scenario->self = p_rid;
  350. scenario->reflection_probe_shadow_atlas = RSG::light_storage->shadow_atlas_create();
  351. RSG::light_storage->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas, 1024); //make enough shadows for close distance, don't bother with rest
  352. RSG::light_storage->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 0, 4);
  353. RSG::light_storage->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 1, 4);
  354. RSG::light_storage->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 2, 4);
  355. RSG::light_storage->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 3, 8);
  356. scenario->reflection_atlas = RSG::light_storage->reflection_atlas_create();
  357. scenario->instance_aabbs.set_page_pool(&instance_aabb_page_pool);
  358. scenario->instance_data.set_page_pool(&instance_data_page_pool);
  359. scenario->instance_visibility.set_page_pool(&instance_visibility_data_page_pool);
  360. RendererSceneOcclusionCull::get_singleton()->add_scenario(p_rid);
  361. }
  362. void RendererSceneCull::scenario_set_environment(RID p_scenario, RID p_environment) {
  363. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  364. ERR_FAIL_NULL(scenario);
  365. scenario->environment = p_environment;
  366. }
  367. void RendererSceneCull::scenario_set_camera_attributes(RID p_scenario, RID p_camera_attributes) {
  368. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  369. ERR_FAIL_NULL(scenario);
  370. scenario->camera_attributes = p_camera_attributes;
  371. }
  372. void RendererSceneCull::scenario_set_compositor(RID p_scenario, RID p_compositor) {
  373. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  374. ERR_FAIL_NULL(scenario);
  375. scenario->compositor = p_compositor;
  376. }
  377. void RendererSceneCull::scenario_set_fallback_environment(RID p_scenario, RID p_environment) {
  378. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  379. ERR_FAIL_NULL(scenario);
  380. scenario->fallback_environment = p_environment;
  381. }
  382. void RendererSceneCull::scenario_set_reflection_atlas_size(RID p_scenario, int p_reflection_size, int p_reflection_count) {
  383. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  384. ERR_FAIL_NULL(scenario);
  385. RSG::light_storage->reflection_atlas_set_size(scenario->reflection_atlas, p_reflection_size, p_reflection_count);
  386. }
  387. bool RendererSceneCull::is_scenario(RID p_scenario) const {
  388. return scenario_owner.owns(p_scenario);
  389. }
  390. RID RendererSceneCull::scenario_get_environment(RID p_scenario) {
  391. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  392. ERR_FAIL_NULL_V(scenario, RID());
  393. return scenario->environment;
  394. }
  395. void RendererSceneCull::scenario_remove_viewport_visibility_mask(RID p_scenario, RID p_viewport) {
  396. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  397. ERR_FAIL_NULL(scenario);
  398. if (!scenario->viewport_visibility_masks.has(p_viewport)) {
  399. return;
  400. }
  401. uint64_t mask = scenario->viewport_visibility_masks[p_viewport];
  402. scenario->used_viewport_visibility_bits &= ~mask;
  403. scenario->viewport_visibility_masks.erase(p_viewport);
  404. }
  405. void RendererSceneCull::scenario_add_viewport_visibility_mask(RID p_scenario, RID p_viewport) {
  406. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  407. ERR_FAIL_NULL(scenario);
  408. ERR_FAIL_COND(scenario->viewport_visibility_masks.has(p_viewport));
  409. uint64_t new_mask = 1;
  410. while (new_mask & scenario->used_viewport_visibility_bits) {
  411. new_mask <<= 1;
  412. }
  413. if (new_mask == 0) {
  414. ERR_PRINT("Only 64 viewports per scenario allowed when using visibility ranges.");
  415. new_mask = ((uint64_t)1) << 63;
  416. }
  417. scenario->viewport_visibility_masks[p_viewport] = new_mask;
  418. scenario->used_viewport_visibility_bits |= new_mask;
  419. }
  420. /* INSTANCING API */
  421. void RendererSceneCull::_instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_dependencies) const {
  422. if (p_update_aabb) {
  423. p_instance->update_aabb = true;
  424. }
  425. if (p_update_dependencies) {
  426. p_instance->update_dependencies = true;
  427. }
  428. if (p_instance->update_item.in_list()) {
  429. return;
  430. }
  431. _instance_update_list.add(&p_instance->update_item);
  432. }
  433. RID RendererSceneCull::instance_allocate() {
  434. return instance_owner.allocate_rid();
  435. }
  436. void RendererSceneCull::instance_initialize(RID p_rid) {
  437. instance_owner.initialize_rid(p_rid);
  438. Instance *instance = instance_owner.get_or_null(p_rid);
  439. instance->self = p_rid;
  440. }
  441. void RendererSceneCull::_instance_update_mesh_instance(Instance *p_instance) const {
  442. bool needs_instance = RSG::mesh_storage->mesh_needs_instance(p_instance->base, p_instance->skeleton.is_valid());
  443. if (needs_instance != p_instance->mesh_instance.is_valid()) {
  444. if (needs_instance) {
  445. p_instance->mesh_instance = RSG::mesh_storage->mesh_instance_create(p_instance->base);
  446. } else {
  447. RSG::mesh_storage->mesh_instance_free(p_instance->mesh_instance);
  448. p_instance->mesh_instance = RID();
  449. }
  450. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  451. geom->geometry_instance->set_mesh_instance(p_instance->mesh_instance);
  452. if (p_instance->scenario && p_instance->array_index >= 0) {
  453. InstanceData &idata = p_instance->scenario->instance_data[p_instance->array_index];
  454. if (p_instance->mesh_instance.is_valid()) {
  455. idata.flags |= InstanceData::FLAG_USES_MESH_INSTANCE;
  456. } else {
  457. idata.flags &= ~InstanceData::FLAG_USES_MESH_INSTANCE;
  458. }
  459. }
  460. }
  461. if (p_instance->mesh_instance.is_valid()) {
  462. RSG::mesh_storage->mesh_instance_set_skeleton(p_instance->mesh_instance, p_instance->skeleton);
  463. }
  464. }
  465. void RendererSceneCull::instance_set_base(RID p_instance, RID p_base) {
  466. Instance *instance = instance_owner.get_or_null(p_instance);
  467. ERR_FAIL_NULL(instance);
  468. Scenario *scenario = instance->scenario;
  469. if (instance->base_type != RS::INSTANCE_NONE) {
  470. //free anything related to that base
  471. if (scenario && instance->indexer_id.is_valid()) {
  472. _unpair_instance(instance);
  473. }
  474. if (instance->mesh_instance.is_valid()) {
  475. RSG::mesh_storage->mesh_instance_free(instance->mesh_instance);
  476. instance->mesh_instance = RID();
  477. // no need to set instance data flag here, as it was freed above
  478. }
  479. switch (instance->base_type) {
  480. case RS::INSTANCE_MESH:
  481. case RS::INSTANCE_MULTIMESH:
  482. case RS::INSTANCE_PARTICLES: {
  483. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  484. scene_render->geometry_instance_free(geom->geometry_instance);
  485. } break;
  486. case RS::INSTANCE_LIGHT: {
  487. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  488. if (scenario && instance->visible && RSG::light_storage->light_get_type(instance->base) != RS::LIGHT_DIRECTIONAL && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  489. scenario->dynamic_lights.erase(light->instance);
  490. }
  491. #ifdef DEBUG_ENABLED
  492. if (light->geometries.size()) {
  493. ERR_PRINT("BUG, indexing did not unpair geometries from light.");
  494. }
  495. #endif
  496. if (scenario && light->D) {
  497. scenario->directional_lights.erase(light->D);
  498. light->D = nullptr;
  499. }
  500. RSG::light_storage->light_instance_free(light->instance);
  501. } break;
  502. case RS::INSTANCE_PARTICLES_COLLISION: {
  503. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(instance->base_data);
  504. RSG::utilities->free(collision->instance);
  505. } break;
  506. case RS::INSTANCE_FOG_VOLUME: {
  507. InstanceFogVolumeData *volume = static_cast<InstanceFogVolumeData *>(instance->base_data);
  508. scene_render->free(volume->instance);
  509. } break;
  510. case RS::INSTANCE_VISIBLITY_NOTIFIER: {
  511. //none
  512. } break;
  513. case RS::INSTANCE_REFLECTION_PROBE: {
  514. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  515. RSG::light_storage->reflection_probe_instance_free(reflection_probe->instance);
  516. if (reflection_probe->update_list.in_list()) {
  517. reflection_probe_render_list.remove(&reflection_probe->update_list);
  518. }
  519. } break;
  520. case RS::INSTANCE_DECAL: {
  521. InstanceDecalData *decal = static_cast<InstanceDecalData *>(instance->base_data);
  522. RSG::texture_storage->decal_instance_free(decal->instance);
  523. } break;
  524. case RS::INSTANCE_LIGHTMAP: {
  525. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(instance->base_data);
  526. //erase dependencies, since no longer a lightmap
  527. while (lightmap_data->users.begin()) {
  528. instance_geometry_set_lightmap((*lightmap_data->users.begin())->self, RID(), Rect2(), 0);
  529. }
  530. RSG::light_storage->lightmap_instance_free(lightmap_data->instance);
  531. } break;
  532. case RS::INSTANCE_VOXEL_GI: {
  533. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(instance->base_data);
  534. #ifdef DEBUG_ENABLED
  535. if (voxel_gi->geometries.size()) {
  536. ERR_PRINT("BUG, indexing did not unpair geometries from VoxelGI.");
  537. }
  538. #endif
  539. #ifdef DEBUG_ENABLED
  540. if (voxel_gi->lights.size()) {
  541. ERR_PRINT("BUG, indexing did not unpair lights from VoxelGI.");
  542. }
  543. #endif
  544. if (voxel_gi->update_element.in_list()) {
  545. voxel_gi_update_list.remove(&voxel_gi->update_element);
  546. }
  547. scene_render->free(voxel_gi->probe_instance);
  548. } break;
  549. case RS::INSTANCE_OCCLUDER: {
  550. if (scenario && instance->visible) {
  551. RendererSceneOcclusionCull::get_singleton()->scenario_remove_instance(instance->scenario->self, p_instance);
  552. }
  553. } break;
  554. default: {
  555. }
  556. }
  557. if (instance->base_data) {
  558. memdelete(instance->base_data);
  559. instance->base_data = nullptr;
  560. }
  561. instance->materials.clear();
  562. }
  563. instance->base_type = RS::INSTANCE_NONE;
  564. instance->base = RID();
  565. if (p_base.is_valid()) {
  566. instance->base_type = RSG::utilities->get_base_type(p_base);
  567. // fix up a specific malfunctioning case before the switch, so it can be handled
  568. if (instance->base_type == RS::INSTANCE_NONE && RendererSceneOcclusionCull::get_singleton()->is_occluder(p_base)) {
  569. instance->base_type = RS::INSTANCE_OCCLUDER;
  570. }
  571. switch (instance->base_type) {
  572. case RS::INSTANCE_NONE: {
  573. ERR_PRINT_ONCE("unimplemented base type encountered in renderer scene cull");
  574. return;
  575. }
  576. case RS::INSTANCE_LIGHT: {
  577. InstanceLightData *light = memnew(InstanceLightData);
  578. if (scenario && RSG::light_storage->light_get_type(p_base) == RS::LIGHT_DIRECTIONAL) {
  579. light->D = scenario->directional_lights.push_back(instance);
  580. }
  581. light->instance = RSG::light_storage->light_instance_create(p_base);
  582. instance->base_data = light;
  583. } break;
  584. case RS::INSTANCE_MESH:
  585. case RS::INSTANCE_MULTIMESH:
  586. case RS::INSTANCE_PARTICLES: {
  587. InstanceGeometryData *geom = memnew(InstanceGeometryData);
  588. instance->base_data = geom;
  589. geom->geometry_instance = scene_render->geometry_instance_create(p_base);
  590. ERR_FAIL_NULL(geom->geometry_instance);
  591. geom->geometry_instance->set_skeleton(instance->skeleton);
  592. geom->geometry_instance->set_material_override(instance->material_override);
  593. geom->geometry_instance->set_material_overlay(instance->material_overlay);
  594. geom->geometry_instance->set_surface_materials(instance->materials);
  595. geom->geometry_instance->set_transform(instance->transform, instance->aabb, instance->transformed_aabb);
  596. geom->geometry_instance->set_layer_mask(instance->layer_mask);
  597. geom->geometry_instance->set_pivot_data(instance->sorting_offset, instance->use_aabb_center);
  598. geom->geometry_instance->set_lod_bias(instance->lod_bias);
  599. geom->geometry_instance->set_transparency(instance->transparency);
  600. geom->geometry_instance->set_use_baked_light(instance->baked_light);
  601. geom->geometry_instance->set_use_dynamic_gi(instance->dynamic_gi);
  602. geom->geometry_instance->set_use_lightmap(RID(), instance->lightmap_uv_scale, instance->lightmap_slice_index);
  603. geom->geometry_instance->set_instance_shader_uniforms_offset(instance->instance_uniforms.location());
  604. geom->geometry_instance->set_cast_double_sided_shadows(instance->cast_shadows == RS::SHADOW_CASTING_SETTING_DOUBLE_SIDED);
  605. if (instance->lightmap_sh.size() == 9) {
  606. geom->geometry_instance->set_lightmap_capture(instance->lightmap_sh.ptr());
  607. }
  608. for (Instance *E : instance->visibility_dependencies) {
  609. Instance *dep_instance = E;
  610. ERR_CONTINUE(dep_instance->array_index == -1);
  611. ERR_CONTINUE(dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index != -1);
  612. dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index = instance->array_index;
  613. }
  614. } break;
  615. case RS::INSTANCE_PARTICLES_COLLISION: {
  616. InstanceParticlesCollisionData *collision = memnew(InstanceParticlesCollisionData);
  617. collision->instance = RSG::particles_storage->particles_collision_instance_create(p_base);
  618. RSG::particles_storage->particles_collision_instance_set_active(collision->instance, instance->visible);
  619. instance->base_data = collision;
  620. } break;
  621. case RS::INSTANCE_FOG_VOLUME: {
  622. InstanceFogVolumeData *volume = memnew(InstanceFogVolumeData);
  623. volume->instance = scene_render->fog_volume_instance_create(p_base);
  624. scene_render->fog_volume_instance_set_active(volume->instance, instance->visible);
  625. instance->base_data = volume;
  626. } break;
  627. case RS::INSTANCE_VISIBLITY_NOTIFIER: {
  628. InstanceVisibilityNotifierData *vnd = memnew(InstanceVisibilityNotifierData);
  629. vnd->base = p_base;
  630. instance->base_data = vnd;
  631. } break;
  632. case RS::INSTANCE_REFLECTION_PROBE: {
  633. InstanceReflectionProbeData *reflection_probe = memnew(InstanceReflectionProbeData);
  634. reflection_probe->owner = instance;
  635. instance->base_data = reflection_probe;
  636. reflection_probe->instance = RSG::light_storage->reflection_probe_instance_create(p_base);
  637. } break;
  638. case RS::INSTANCE_DECAL: {
  639. InstanceDecalData *decal = memnew(InstanceDecalData);
  640. decal->owner = instance;
  641. instance->base_data = decal;
  642. decal->instance = RSG::texture_storage->decal_instance_create(p_base);
  643. RSG::texture_storage->decal_instance_set_sorting_offset(decal->instance, instance->sorting_offset);
  644. } break;
  645. case RS::INSTANCE_LIGHTMAP: {
  646. InstanceLightmapData *lightmap_data = memnew(InstanceLightmapData);
  647. instance->base_data = lightmap_data;
  648. lightmap_data->instance = RSG::light_storage->lightmap_instance_create(p_base);
  649. } break;
  650. case RS::INSTANCE_VOXEL_GI: {
  651. InstanceVoxelGIData *voxel_gi = memnew(InstanceVoxelGIData);
  652. instance->base_data = voxel_gi;
  653. voxel_gi->owner = instance;
  654. if (scenario && !voxel_gi->update_element.in_list()) {
  655. voxel_gi_update_list.add(&voxel_gi->update_element);
  656. }
  657. voxel_gi->probe_instance = scene_render->voxel_gi_instance_create(p_base);
  658. } break;
  659. case RS::INSTANCE_OCCLUDER: {
  660. if (scenario) {
  661. RendererSceneOcclusionCull::get_singleton()->scenario_set_instance(scenario->self, p_instance, p_base, instance->transform, instance->visible);
  662. }
  663. } break;
  664. default: {
  665. }
  666. }
  667. instance->base = p_base;
  668. if (instance->base_type == RS::INSTANCE_MESH) {
  669. _instance_update_mesh_instance(instance);
  670. }
  671. //forcefully update the dependency now, so if for some reason it gets removed, we can immediately clear it
  672. RSG::utilities->base_update_dependency(p_base, &instance->dependency_tracker);
  673. }
  674. _instance_queue_update(instance, true, true);
  675. }
  676. void RendererSceneCull::instance_set_scenario(RID p_instance, RID p_scenario) {
  677. Instance *instance = instance_owner.get_or_null(p_instance);
  678. ERR_FAIL_NULL(instance);
  679. if (instance->scenario) {
  680. instance->scenario->instances.remove(&instance->scenario_item);
  681. if (instance->indexer_id.is_valid()) {
  682. _unpair_instance(instance);
  683. }
  684. switch (instance->base_type) {
  685. case RS::INSTANCE_LIGHT: {
  686. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  687. if (instance->visible && RSG::light_storage->light_get_type(instance->base) != RS::LIGHT_DIRECTIONAL && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  688. instance->scenario->dynamic_lights.erase(light->instance);
  689. }
  690. #ifdef DEBUG_ENABLED
  691. if (light->geometries.size()) {
  692. ERR_PRINT("BUG, indexing did not unpair geometries from light.");
  693. }
  694. #endif
  695. if (light->D) {
  696. instance->scenario->directional_lights.erase(light->D);
  697. light->D = nullptr;
  698. }
  699. } break;
  700. case RS::INSTANCE_REFLECTION_PROBE: {
  701. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
  702. RSG::light_storage->reflection_probe_release_atlas_index(reflection_probe->instance);
  703. } break;
  704. case RS::INSTANCE_PARTICLES_COLLISION: {
  705. heightfield_particle_colliders_update_list.erase(instance);
  706. } break;
  707. case RS::INSTANCE_VOXEL_GI: {
  708. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(instance->base_data);
  709. #ifdef DEBUG_ENABLED
  710. if (voxel_gi->geometries.size()) {
  711. ERR_PRINT("BUG, indexing did not unpair geometries from VoxelGI.");
  712. }
  713. #endif
  714. #ifdef DEBUG_ENABLED
  715. if (voxel_gi->lights.size()) {
  716. ERR_PRINT("BUG, indexing did not unpair lights from VoxelGI.");
  717. }
  718. #endif
  719. if (voxel_gi->update_element.in_list()) {
  720. voxel_gi_update_list.remove(&voxel_gi->update_element);
  721. }
  722. } break;
  723. case RS::INSTANCE_OCCLUDER: {
  724. if (instance->visible) {
  725. RendererSceneOcclusionCull::get_singleton()->scenario_remove_instance(instance->scenario->self, p_instance);
  726. }
  727. } break;
  728. default: {
  729. }
  730. }
  731. instance->scenario = nullptr;
  732. }
  733. if (p_scenario.is_valid()) {
  734. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  735. ERR_FAIL_NULL(scenario);
  736. instance->scenario = scenario;
  737. scenario->instances.add(&instance->scenario_item);
  738. switch (instance->base_type) {
  739. case RS::INSTANCE_LIGHT: {
  740. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  741. if (RSG::light_storage->light_get_type(instance->base) == RS::LIGHT_DIRECTIONAL) {
  742. light->D = scenario->directional_lights.push_back(instance);
  743. }
  744. } break;
  745. case RS::INSTANCE_VOXEL_GI: {
  746. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(instance->base_data);
  747. if (!voxel_gi->update_element.in_list()) {
  748. voxel_gi_update_list.add(&voxel_gi->update_element);
  749. }
  750. } break;
  751. case RS::INSTANCE_OCCLUDER: {
  752. RendererSceneOcclusionCull::get_singleton()->scenario_set_instance(scenario->self, p_instance, instance->base, instance->transform, instance->visible);
  753. } break;
  754. default: {
  755. }
  756. }
  757. _instance_queue_update(instance, true, true);
  758. }
  759. }
  760. void RendererSceneCull::instance_set_layer_mask(RID p_instance, uint32_t p_mask) {
  761. Instance *instance = instance_owner.get_or_null(p_instance);
  762. ERR_FAIL_NULL(instance);
  763. if (instance->layer_mask == p_mask) {
  764. return;
  765. }
  766. // Particles always need to be unpaired. Geometry may need to be unpaired, but only if lights or decals use pairing.
  767. // Needs to happen before layer mask changes so we can avoid attempting to unpair something that was never paired.
  768. if (instance->base_type == RS::INSTANCE_PARTICLES ||
  769. (((geometry_instance_pair_mask & (1 << RS::INSTANCE_LIGHT)) || (geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL))) && ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK))) {
  770. _unpair_instance(instance);
  771. singleton->_instance_queue_update(instance, false, false);
  772. }
  773. instance->layer_mask = p_mask;
  774. if (instance->scenario && instance->array_index >= 0) {
  775. instance->scenario->instance_data[instance->array_index].layer_mask = p_mask;
  776. }
  777. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  778. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  779. ERR_FAIL_NULL(geom->geometry_instance);
  780. geom->geometry_instance->set_layer_mask(p_mask);
  781. if (geom->can_cast_shadows) {
  782. for (HashSet<RendererSceneCull::Instance *>::Iterator I = geom->lights.begin(); I != geom->lights.end(); ++I) {
  783. InstanceLightData *light = static_cast<InstanceLightData *>((*I)->base_data);
  784. light->make_shadow_dirty();
  785. }
  786. }
  787. }
  788. }
  789. void RendererSceneCull::instance_set_pivot_data(RID p_instance, float p_sorting_offset, bool p_use_aabb_center) {
  790. Instance *instance = instance_owner.get_or_null(p_instance);
  791. ERR_FAIL_NULL(instance);
  792. instance->sorting_offset = p_sorting_offset;
  793. instance->use_aabb_center = p_use_aabb_center;
  794. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  795. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  796. ERR_FAIL_NULL(geom->geometry_instance);
  797. geom->geometry_instance->set_pivot_data(p_sorting_offset, p_use_aabb_center);
  798. } else if (instance->base_type == RS::INSTANCE_DECAL && instance->base_data) {
  799. InstanceDecalData *decal = static_cast<InstanceDecalData *>(instance->base_data);
  800. RSG::texture_storage->decal_instance_set_sorting_offset(decal->instance, instance->sorting_offset);
  801. }
  802. }
  803. void RendererSceneCull::instance_geometry_set_transparency(RID p_instance, float p_transparency) {
  804. Instance *instance = instance_owner.get_or_null(p_instance);
  805. ERR_FAIL_NULL(instance);
  806. instance->transparency = p_transparency;
  807. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  808. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  809. ERR_FAIL_NULL(geom->geometry_instance);
  810. geom->geometry_instance->set_transparency(p_transparency);
  811. }
  812. }
  813. void RendererSceneCull::instance_set_transform(RID p_instance, const Transform3D &p_transform) {
  814. Instance *instance = instance_owner.get_or_null(p_instance);
  815. ERR_FAIL_NULL(instance);
  816. if (instance->transform == p_transform) {
  817. return; // Must be checked to avoid worst evil.
  818. }
  819. #ifdef DEBUG_ENABLED
  820. for (int i = 0; i < 4; i++) {
  821. const Vector3 &v = i < 3 ? p_transform.basis.rows[i] : p_transform.origin;
  822. ERR_FAIL_COND(!v.is_finite());
  823. }
  824. #endif
  825. instance->transform = p_transform;
  826. _instance_queue_update(instance, true);
  827. }
  828. void RendererSceneCull::instance_attach_object_instance_id(RID p_instance, ObjectID p_id) {
  829. Instance *instance = instance_owner.get_or_null(p_instance);
  830. ERR_FAIL_NULL(instance);
  831. instance->object_id = p_id;
  832. }
  833. void RendererSceneCull::instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) {
  834. Instance *instance = instance_owner.get_or_null(p_instance);
  835. ERR_FAIL_NULL(instance);
  836. if (instance->update_item.in_list()) {
  837. _update_dirty_instance(instance);
  838. }
  839. if (instance->mesh_instance.is_valid()) {
  840. RSG::mesh_storage->mesh_instance_set_blend_shape_weight(instance->mesh_instance, p_shape, p_weight);
  841. }
  842. _instance_queue_update(instance, false, false);
  843. }
  844. void RendererSceneCull::instance_set_surface_override_material(RID p_instance, int p_surface, RID p_material) {
  845. Instance *instance = instance_owner.get_or_null(p_instance);
  846. ERR_FAIL_NULL(instance);
  847. if (instance->base_type == RS::INSTANCE_MESH) {
  848. //may not have been updated yet, may also have not been set yet. When updated will be correcte, worst case
  849. instance->materials.resize(MAX(p_surface + 1, RSG::mesh_storage->mesh_get_surface_count(instance->base)));
  850. }
  851. ERR_FAIL_INDEX(p_surface, instance->materials.size());
  852. instance->materials.write[p_surface] = p_material;
  853. _instance_queue_update(instance, false, true);
  854. }
  855. void RendererSceneCull::instance_set_visible(RID p_instance, bool p_visible) {
  856. Instance *instance = instance_owner.get_or_null(p_instance);
  857. ERR_FAIL_NULL(instance);
  858. if (instance->visible == p_visible) {
  859. return;
  860. }
  861. instance->visible = p_visible;
  862. if (p_visible) {
  863. if (instance->scenario != nullptr) {
  864. _instance_queue_update(instance, true, false);
  865. }
  866. } else if (instance->indexer_id.is_valid()) {
  867. _unpair_instance(instance);
  868. }
  869. if (instance->base_type == RS::INSTANCE_LIGHT) {
  870. InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
  871. if (instance->scenario && RSG::light_storage->light_get_type(instance->base) != RS::LIGHT_DIRECTIONAL && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  872. if (p_visible) {
  873. instance->scenario->dynamic_lights.push_back(light->instance);
  874. } else {
  875. instance->scenario->dynamic_lights.erase(light->instance);
  876. }
  877. }
  878. }
  879. if (instance->base_type == RS::INSTANCE_PARTICLES_COLLISION) {
  880. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(instance->base_data);
  881. RSG::particles_storage->particles_collision_instance_set_active(collision->instance, p_visible);
  882. }
  883. if (instance->base_type == RS::INSTANCE_FOG_VOLUME) {
  884. InstanceFogVolumeData *volume = static_cast<InstanceFogVolumeData *>(instance->base_data);
  885. scene_render->fog_volume_instance_set_active(volume->instance, p_visible);
  886. }
  887. if (instance->base_type == RS::INSTANCE_OCCLUDER) {
  888. if (instance->scenario) {
  889. RendererSceneOcclusionCull::get_singleton()->scenario_set_instance(instance->scenario->self, p_instance, instance->base, instance->transform, p_visible);
  890. }
  891. }
  892. }
  893. void RendererSceneCull::instance_teleport(RID p_instance) {
  894. Instance *instance = instance_owner.get_or_null(p_instance);
  895. ERR_FAIL_NULL(instance);
  896. instance->teleported = true;
  897. }
  898. void RendererSceneCull::instance_set_custom_aabb(RID p_instance, AABB p_aabb) {
  899. Instance *instance = instance_owner.get_or_null(p_instance);
  900. ERR_FAIL_NULL(instance);
  901. if (p_aabb != AABB()) {
  902. // Set custom AABB
  903. if (instance->custom_aabb == nullptr) {
  904. instance->custom_aabb = memnew(AABB);
  905. }
  906. *instance->custom_aabb = p_aabb;
  907. } else {
  908. // Clear custom AABB
  909. if (instance->custom_aabb != nullptr) {
  910. memdelete(instance->custom_aabb);
  911. instance->custom_aabb = nullptr;
  912. }
  913. }
  914. if (instance->scenario) {
  915. _instance_queue_update(instance, true, false);
  916. }
  917. }
  918. void RendererSceneCull::instance_attach_skeleton(RID p_instance, RID p_skeleton) {
  919. Instance *instance = instance_owner.get_or_null(p_instance);
  920. ERR_FAIL_NULL(instance);
  921. if (instance->skeleton == p_skeleton) {
  922. return;
  923. }
  924. instance->skeleton = p_skeleton;
  925. if (p_skeleton.is_valid()) {
  926. //update the dependency now, so if cleared, we remove it
  927. RSG::mesh_storage->skeleton_update_dependency(p_skeleton, &instance->dependency_tracker);
  928. }
  929. _instance_queue_update(instance, true, true);
  930. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  931. _instance_update_mesh_instance(instance);
  932. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  933. ERR_FAIL_NULL(geom->geometry_instance);
  934. geom->geometry_instance->set_skeleton(p_skeleton);
  935. }
  936. }
  937. void RendererSceneCull::instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) {
  938. Instance *instance = instance_owner.get_or_null(p_instance);
  939. ERR_FAIL_NULL(instance);
  940. instance->extra_margin = p_margin;
  941. _instance_queue_update(instance, true, false);
  942. }
  943. void RendererSceneCull::instance_set_ignore_culling(RID p_instance, bool p_enabled) {
  944. Instance *instance = instance_owner.get_or_null(p_instance);
  945. ERR_FAIL_NULL(instance);
  946. instance->ignore_all_culling = p_enabled;
  947. if (instance->scenario && instance->array_index >= 0) {
  948. InstanceData &idata = instance->scenario->instance_data[instance->array_index];
  949. if (instance->ignore_all_culling) {
  950. idata.flags |= InstanceData::FLAG_IGNORE_ALL_CULLING;
  951. } else {
  952. idata.flags &= ~InstanceData::FLAG_IGNORE_ALL_CULLING;
  953. }
  954. }
  955. }
  956. Vector<ObjectID> RendererSceneCull::instances_cull_aabb(const AABB &p_aabb, RID p_scenario) const {
  957. Vector<ObjectID> instances;
  958. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  959. ERR_FAIL_NULL_V(scenario, instances);
  960. update_dirty_instances(); // check dirty instances before culling
  961. struct CullAABB {
  962. Vector<ObjectID> instances;
  963. _FORCE_INLINE_ bool operator()(void *p_data) {
  964. Instance *p_instance = (Instance *)p_data;
  965. if (!p_instance->object_id.is_null()) {
  966. instances.push_back(p_instance->object_id);
  967. }
  968. return false;
  969. }
  970. };
  971. CullAABB cull_aabb;
  972. scenario->indexers[Scenario::INDEXER_GEOMETRY].aabb_query(p_aabb, cull_aabb);
  973. scenario->indexers[Scenario::INDEXER_VOLUMES].aabb_query(p_aabb, cull_aabb);
  974. return cull_aabb.instances;
  975. }
  976. Vector<ObjectID> RendererSceneCull::instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const {
  977. Vector<ObjectID> instances;
  978. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  979. ERR_FAIL_NULL_V(scenario, instances);
  980. update_dirty_instances(); // check dirty instances before culling
  981. struct CullRay {
  982. Vector<ObjectID> instances;
  983. _FORCE_INLINE_ bool operator()(void *p_data) {
  984. Instance *p_instance = (Instance *)p_data;
  985. if (!p_instance->object_id.is_null()) {
  986. instances.push_back(p_instance->object_id);
  987. }
  988. return false;
  989. }
  990. };
  991. CullRay cull_ray;
  992. scenario->indexers[Scenario::INDEXER_GEOMETRY].ray_query(p_from, p_to, cull_ray);
  993. scenario->indexers[Scenario::INDEXER_VOLUMES].ray_query(p_from, p_to, cull_ray);
  994. return cull_ray.instances;
  995. }
  996. Vector<ObjectID> RendererSceneCull::instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario) const {
  997. Vector<ObjectID> instances;
  998. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  999. ERR_FAIL_NULL_V(scenario, instances);
  1000. update_dirty_instances(); // check dirty instances before culling
  1001. Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&p_convex[0], p_convex.size());
  1002. struct CullConvex {
  1003. Vector<ObjectID> instances;
  1004. _FORCE_INLINE_ bool operator()(void *p_data) {
  1005. Instance *p_instance = (Instance *)p_data;
  1006. if (!p_instance->object_id.is_null()) {
  1007. instances.push_back(p_instance->object_id);
  1008. }
  1009. return false;
  1010. }
  1011. };
  1012. CullConvex cull_convex;
  1013. scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(p_convex.ptr(), p_convex.size(), points.ptr(), points.size(), cull_convex);
  1014. scenario->indexers[Scenario::INDEXER_VOLUMES].convex_query(p_convex.ptr(), p_convex.size(), points.ptr(), points.size(), cull_convex);
  1015. return cull_convex.instances;
  1016. }
  1017. void RendererSceneCull::instance_geometry_set_flag(RID p_instance, RS::InstanceFlags p_flags, bool p_enabled) {
  1018. Instance *instance = instance_owner.get_or_null(p_instance);
  1019. ERR_FAIL_NULL(instance);
  1020. //ERR_FAIL_COND(((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK));
  1021. switch (p_flags) {
  1022. case RS::INSTANCE_FLAG_USE_BAKED_LIGHT: {
  1023. instance->baked_light = p_enabled;
  1024. if (instance->scenario && instance->array_index >= 0) {
  1025. InstanceData &idata = instance->scenario->instance_data[instance->array_index];
  1026. if (instance->baked_light) {
  1027. idata.flags |= InstanceData::FLAG_USES_BAKED_LIGHT;
  1028. } else {
  1029. idata.flags &= ~InstanceData::FLAG_USES_BAKED_LIGHT;
  1030. }
  1031. }
  1032. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  1033. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  1034. ERR_FAIL_NULL(geom->geometry_instance);
  1035. geom->geometry_instance->set_use_baked_light(p_enabled);
  1036. }
  1037. } break;
  1038. case RS::INSTANCE_FLAG_USE_DYNAMIC_GI: {
  1039. if (p_enabled == instance->dynamic_gi) {
  1040. //bye, redundant
  1041. return;
  1042. }
  1043. if (instance->indexer_id.is_valid()) {
  1044. _unpair_instance(instance);
  1045. _instance_queue_update(instance, true, true);
  1046. }
  1047. //once out of octree, can be changed
  1048. instance->dynamic_gi = p_enabled;
  1049. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  1050. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  1051. ERR_FAIL_NULL(geom->geometry_instance);
  1052. geom->geometry_instance->set_use_dynamic_gi(p_enabled);
  1053. }
  1054. } break;
  1055. case RS::INSTANCE_FLAG_DRAW_NEXT_FRAME_IF_VISIBLE: {
  1056. instance->redraw_if_visible = p_enabled;
  1057. if (instance->scenario && instance->array_index >= 0) {
  1058. InstanceData &idata = instance->scenario->instance_data[instance->array_index];
  1059. if (instance->redraw_if_visible) {
  1060. idata.flags |= InstanceData::FLAG_REDRAW_IF_VISIBLE;
  1061. } else {
  1062. idata.flags &= ~InstanceData::FLAG_REDRAW_IF_VISIBLE;
  1063. }
  1064. }
  1065. } break;
  1066. case RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING: {
  1067. instance->ignore_occlusion_culling = p_enabled;
  1068. if (instance->scenario && instance->array_index >= 0) {
  1069. InstanceData &idata = instance->scenario->instance_data[instance->array_index];
  1070. if (instance->ignore_occlusion_culling) {
  1071. idata.flags |= InstanceData::FLAG_IGNORE_OCCLUSION_CULLING;
  1072. } else {
  1073. idata.flags &= ~InstanceData::FLAG_IGNORE_OCCLUSION_CULLING;
  1074. }
  1075. }
  1076. } break;
  1077. default: {
  1078. }
  1079. }
  1080. }
  1081. void RendererSceneCull::instance_geometry_set_cast_shadows_setting(RID p_instance, RS::ShadowCastingSetting p_shadow_casting_setting) {
  1082. Instance *instance = instance_owner.get_or_null(p_instance);
  1083. ERR_FAIL_NULL(instance);
  1084. instance->cast_shadows = p_shadow_casting_setting;
  1085. if (instance->scenario && instance->array_index >= 0) {
  1086. InstanceData &idata = instance->scenario->instance_data[instance->array_index];
  1087. if (instance->cast_shadows != RS::SHADOW_CASTING_SETTING_OFF) {
  1088. idata.flags |= InstanceData::FLAG_CAST_SHADOWS;
  1089. } else {
  1090. idata.flags &= ~InstanceData::FLAG_CAST_SHADOWS;
  1091. }
  1092. if (instance->cast_shadows == RS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
  1093. idata.flags |= InstanceData::FLAG_CAST_SHADOWS_ONLY;
  1094. } else {
  1095. idata.flags &= ~InstanceData::FLAG_CAST_SHADOWS_ONLY;
  1096. }
  1097. }
  1098. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  1099. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  1100. ERR_FAIL_NULL(geom->geometry_instance);
  1101. geom->geometry_instance->set_cast_double_sided_shadows(instance->cast_shadows == RS::SHADOW_CASTING_SETTING_DOUBLE_SIDED);
  1102. }
  1103. _instance_queue_update(instance, false, true);
  1104. }
  1105. void RendererSceneCull::instance_geometry_set_material_override(RID p_instance, RID p_material) {
  1106. Instance *instance = instance_owner.get_or_null(p_instance);
  1107. ERR_FAIL_NULL(instance);
  1108. instance->material_override = p_material;
  1109. _instance_queue_update(instance, false, true);
  1110. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  1111. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  1112. ERR_FAIL_NULL(geom->geometry_instance);
  1113. geom->geometry_instance->set_material_override(p_material);
  1114. }
  1115. }
  1116. void RendererSceneCull::instance_geometry_set_material_overlay(RID p_instance, RID p_material) {
  1117. Instance *instance = instance_owner.get_or_null(p_instance);
  1118. ERR_FAIL_NULL(instance);
  1119. instance->material_overlay = p_material;
  1120. _instance_queue_update(instance, false, true);
  1121. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  1122. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  1123. ERR_FAIL_NULL(geom->geometry_instance);
  1124. geom->geometry_instance->set_material_overlay(p_material);
  1125. }
  1126. }
  1127. void RendererSceneCull::instance_geometry_set_visibility_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin, RS::VisibilityRangeFadeMode p_fade_mode) {
  1128. Instance *instance = instance_owner.get_or_null(p_instance);
  1129. ERR_FAIL_NULL(instance);
  1130. instance->visibility_range_begin = p_min;
  1131. instance->visibility_range_end = p_max;
  1132. instance->visibility_range_begin_margin = p_min_margin;
  1133. instance->visibility_range_end_margin = p_max_margin;
  1134. instance->visibility_range_fade_mode = p_fade_mode;
  1135. _update_instance_visibility_dependencies(instance);
  1136. if (instance->scenario && instance->visibility_index != -1) {
  1137. InstanceVisibilityData &vd = instance->scenario->instance_visibility[instance->visibility_index];
  1138. vd.range_begin = instance->visibility_range_begin;
  1139. vd.range_end = instance->visibility_range_end;
  1140. vd.range_begin_margin = instance->visibility_range_begin_margin;
  1141. vd.range_end_margin = instance->visibility_range_end_margin;
  1142. vd.fade_mode = p_fade_mode;
  1143. }
  1144. }
  1145. void RendererSceneCull::instance_set_visibility_parent(RID p_instance, RID p_parent_instance) {
  1146. Instance *instance = instance_owner.get_or_null(p_instance);
  1147. ERR_FAIL_NULL(instance);
  1148. Instance *old_parent = instance->visibility_parent;
  1149. if (old_parent) {
  1150. old_parent->visibility_dependencies.erase(instance);
  1151. instance->visibility_parent = nullptr;
  1152. _update_instance_visibility_depth(old_parent);
  1153. }
  1154. Instance *parent = instance_owner.get_or_null(p_parent_instance);
  1155. ERR_FAIL_COND(p_parent_instance.is_valid() && !parent);
  1156. if (parent) {
  1157. parent->visibility_dependencies.insert(instance);
  1158. instance->visibility_parent = parent;
  1159. bool cycle_detected = _update_instance_visibility_depth(parent);
  1160. if (cycle_detected) {
  1161. ERR_PRINT("Cycle detected in the visibility dependencies tree. The latest change to visibility_parent will have no effect.");
  1162. parent->visibility_dependencies.erase(instance);
  1163. instance->visibility_parent = nullptr;
  1164. }
  1165. }
  1166. _update_instance_visibility_dependencies(instance);
  1167. }
  1168. bool RendererSceneCull::_update_instance_visibility_depth(Instance *p_instance) {
  1169. bool cycle_detected = false;
  1170. HashSet<Instance *> traversed_nodes;
  1171. {
  1172. Instance *instance = p_instance;
  1173. while (instance) {
  1174. if (!instance->visibility_dependencies.is_empty()) {
  1175. uint32_t depth = 0;
  1176. for (const Instance *E : instance->visibility_dependencies) {
  1177. depth = MAX(depth, E->visibility_dependencies_depth);
  1178. }
  1179. instance->visibility_dependencies_depth = depth + 1;
  1180. } else {
  1181. instance->visibility_dependencies_depth = 0;
  1182. }
  1183. if (instance->scenario && instance->visibility_index != -1) {
  1184. instance->scenario->instance_visibility.move(instance->visibility_index, instance->visibility_dependencies_depth);
  1185. }
  1186. traversed_nodes.insert(instance);
  1187. instance = instance->visibility_parent;
  1188. if (traversed_nodes.has(instance)) {
  1189. cycle_detected = true;
  1190. break;
  1191. }
  1192. }
  1193. }
  1194. return cycle_detected;
  1195. }
  1196. void RendererSceneCull::_update_instance_visibility_dependencies(Instance *p_instance) const {
  1197. bool is_geometry_instance = ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) && p_instance->base_data;
  1198. bool has_visibility_range = p_instance->visibility_range_begin > 0.0 || p_instance->visibility_range_end > 0.0;
  1199. bool needs_visibility_cull = has_visibility_range && is_geometry_instance && p_instance->array_index != -1;
  1200. if (!needs_visibility_cull && p_instance->visibility_index != -1) {
  1201. p_instance->scenario->instance_visibility.remove_at(p_instance->visibility_index);
  1202. p_instance->visibility_index = -1;
  1203. } else if (needs_visibility_cull && p_instance->visibility_index == -1) {
  1204. InstanceVisibilityData vd;
  1205. vd.instance = p_instance;
  1206. vd.range_begin = p_instance->visibility_range_begin;
  1207. vd.range_end = p_instance->visibility_range_end;
  1208. vd.range_begin_margin = p_instance->visibility_range_begin_margin;
  1209. vd.range_end_margin = p_instance->visibility_range_end_margin;
  1210. vd.position = p_instance->transformed_aabb.get_center();
  1211. vd.array_index = p_instance->array_index;
  1212. vd.fade_mode = p_instance->visibility_range_fade_mode;
  1213. p_instance->scenario->instance_visibility.insert(vd, p_instance->visibility_dependencies_depth);
  1214. }
  1215. if (p_instance->scenario && p_instance->array_index != -1) {
  1216. InstanceData &idata = p_instance->scenario->instance_data[p_instance->array_index];
  1217. idata.visibility_index = p_instance->visibility_index;
  1218. if (is_geometry_instance) {
  1219. if (has_visibility_range && p_instance->visibility_range_fade_mode == RS::VISIBILITY_RANGE_FADE_SELF) {
  1220. bool begin_enabled = p_instance->visibility_range_begin > 0.0f;
  1221. float begin_min = p_instance->visibility_range_begin - p_instance->visibility_range_begin_margin;
  1222. float begin_max = p_instance->visibility_range_begin + p_instance->visibility_range_begin_margin;
  1223. bool end_enabled = p_instance->visibility_range_end > 0.0f;
  1224. float end_min = p_instance->visibility_range_end - p_instance->visibility_range_end_margin;
  1225. float end_max = p_instance->visibility_range_end + p_instance->visibility_range_end_margin;
  1226. idata.instance_geometry->set_fade_range(begin_enabled, begin_min, begin_max, end_enabled, end_min, end_max);
  1227. } else {
  1228. idata.instance_geometry->set_fade_range(false, 0.0f, 0.0f, false, 0.0f, 0.0f);
  1229. }
  1230. }
  1231. if ((has_visibility_range || p_instance->visibility_parent) && (p_instance->visibility_index == -1 || p_instance->visibility_dependencies_depth == 0)) {
  1232. idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_NEEDS_CHECK;
  1233. } else {
  1234. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_NEEDS_CHECK;
  1235. }
  1236. if (p_instance->visibility_parent) {
  1237. idata.parent_array_index = p_instance->visibility_parent->array_index;
  1238. } else {
  1239. idata.parent_array_index = -1;
  1240. if (is_geometry_instance) {
  1241. idata.instance_geometry->set_parent_fade_alpha(1.0f);
  1242. }
  1243. }
  1244. }
  1245. }
  1246. void RendererSceneCull::instance_geometry_set_lightmap(RID p_instance, RID p_lightmap, const Rect2 &p_lightmap_uv_scale, int p_slice_index) {
  1247. Instance *instance = instance_owner.get_or_null(p_instance);
  1248. ERR_FAIL_NULL(instance);
  1249. if (instance->lightmap) {
  1250. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(((Instance *)instance->lightmap)->base_data);
  1251. lightmap_data->users.erase(instance);
  1252. instance->lightmap = nullptr;
  1253. }
  1254. Instance *lightmap_instance = instance_owner.get_or_null(p_lightmap);
  1255. instance->lightmap = lightmap_instance;
  1256. instance->lightmap_uv_scale = p_lightmap_uv_scale;
  1257. instance->lightmap_slice_index = p_slice_index;
  1258. RID lightmap_instance_rid;
  1259. if (lightmap_instance) {
  1260. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(lightmap_instance->base_data);
  1261. lightmap_data->users.insert(instance);
  1262. lightmap_instance_rid = lightmap_data->instance;
  1263. }
  1264. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  1265. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  1266. ERR_FAIL_NULL(geom->geometry_instance);
  1267. geom->geometry_instance->set_use_lightmap(lightmap_instance_rid, p_lightmap_uv_scale, p_slice_index);
  1268. }
  1269. }
  1270. void RendererSceneCull::instance_geometry_set_lod_bias(RID p_instance, float p_lod_bias) {
  1271. Instance *instance = instance_owner.get_or_null(p_instance);
  1272. ERR_FAIL_NULL(instance);
  1273. instance->lod_bias = p_lod_bias;
  1274. if ((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK && instance->base_data) {
  1275. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  1276. ERR_FAIL_NULL(geom->geometry_instance);
  1277. geom->geometry_instance->set_lod_bias(p_lod_bias);
  1278. }
  1279. }
  1280. void RendererSceneCull::instance_geometry_set_shader_parameter(RID p_instance, const StringName &p_parameter, const Variant &p_value) {
  1281. Instance *instance = instance_owner.get_or_null(p_instance);
  1282. ERR_FAIL_NULL(instance);
  1283. instance->instance_uniforms.set(instance->self, p_parameter, p_value);
  1284. }
  1285. Variant RendererSceneCull::instance_geometry_get_shader_parameter(RID p_instance, const StringName &p_parameter) const {
  1286. const Instance *instance = instance_owner.get_or_null(p_instance);
  1287. ERR_FAIL_NULL_V(instance, Variant());
  1288. return instance->instance_uniforms.get(p_parameter);
  1289. }
  1290. Variant RendererSceneCull::instance_geometry_get_shader_parameter_default_value(RID p_instance, const StringName &p_parameter) const {
  1291. const Instance *instance = instance_owner.get_or_null(p_instance);
  1292. ERR_FAIL_NULL_V(instance, Variant());
  1293. return instance->instance_uniforms.get_default(p_parameter);
  1294. }
  1295. void RendererSceneCull::mesh_generate_pipelines(RID p_mesh, bool p_background_compilation) {
  1296. scene_render->mesh_generate_pipelines(p_mesh, p_background_compilation);
  1297. }
  1298. uint32_t RendererSceneCull::get_pipeline_compilations(RS::PipelineSource p_source) {
  1299. return scene_render->get_pipeline_compilations(p_source);
  1300. }
  1301. void RendererSceneCull::instance_geometry_get_shader_parameter_list(RID p_instance, List<PropertyInfo> *p_parameters) const {
  1302. ERR_FAIL_NULL(p_parameters);
  1303. const Instance *instance = instance_owner.get_or_null(p_instance);
  1304. ERR_FAIL_NULL(instance);
  1305. update_dirty_instances();
  1306. instance->instance_uniforms.get_property_list(*p_parameters);
  1307. }
  1308. void RendererSceneCull::_update_instance(Instance *p_instance) const {
  1309. p_instance->version++;
  1310. // When not using interpolation the transform is used straight.
  1311. const Transform3D *instance_xform = &p_instance->transform;
  1312. // Can possibly use the most up to date current transform here when using physics interpolation ...
  1313. // uncomment the next line for this..
  1314. //if (_interpolation_data.interpolation_enabled && p_instance->interpolated) {
  1315. // instance_xform = &p_instance->transform_curr;
  1316. //}
  1317. // However it does seem that using the interpolated transform (transform) works for keeping AABBs
  1318. // up to date to avoid culling errors.
  1319. if (p_instance->base_type == RS::INSTANCE_LIGHT) {
  1320. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  1321. RSG::light_storage->light_instance_set_transform(light->instance, *instance_xform);
  1322. RSG::light_storage->light_instance_set_aabb(light->instance, instance_xform->xform(p_instance->aabb));
  1323. light->make_shadow_dirty();
  1324. RS::LightBakeMode bake_mode = RSG::light_storage->light_get_bake_mode(p_instance->base);
  1325. if (RSG::light_storage->light_get_type(p_instance->base) != RS::LIGHT_DIRECTIONAL && bake_mode != light->bake_mode) {
  1326. if (p_instance->visible && p_instance->scenario && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  1327. p_instance->scenario->dynamic_lights.erase(light->instance);
  1328. }
  1329. light->bake_mode = bake_mode;
  1330. if (p_instance->visible && p_instance->scenario && light->bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  1331. p_instance->scenario->dynamic_lights.push_back(light->instance);
  1332. }
  1333. }
  1334. uint32_t max_sdfgi_cascade = RSG::light_storage->light_get_max_sdfgi_cascade(p_instance->base);
  1335. if (light->max_sdfgi_cascade != max_sdfgi_cascade) {
  1336. light->max_sdfgi_cascade = max_sdfgi_cascade; //should most likely make sdfgi dirty in scenario
  1337. }
  1338. light->cull_mask = RSG::light_storage->light_get_cull_mask(p_instance->base);
  1339. } else if (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE) {
  1340. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  1341. RSG::light_storage->reflection_probe_instance_set_transform(reflection_probe->instance, *instance_xform);
  1342. if (p_instance->scenario && p_instance->array_index >= 0) {
  1343. InstanceData &idata = p_instance->scenario->instance_data[p_instance->array_index];
  1344. idata.flags |= InstanceData::FLAG_REFLECTION_PROBE_DIRTY;
  1345. }
  1346. } else if (p_instance->base_type == RS::INSTANCE_DECAL) {
  1347. InstanceDecalData *decal = static_cast<InstanceDecalData *>(p_instance->base_data);
  1348. RSG::texture_storage->decal_instance_set_transform(decal->instance, *instance_xform);
  1349. decal->cull_mask = RSG::texture_storage->decal_get_cull_mask(p_instance->base);
  1350. } else if (p_instance->base_type == RS::INSTANCE_LIGHTMAP) {
  1351. InstanceLightmapData *lightmap = static_cast<InstanceLightmapData *>(p_instance->base_data);
  1352. RSG::light_storage->lightmap_instance_set_transform(lightmap->instance, *instance_xform);
  1353. } else if (p_instance->base_type == RS::INSTANCE_VOXEL_GI) {
  1354. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(p_instance->base_data);
  1355. scene_render->voxel_gi_instance_set_transform_to_data(voxel_gi->probe_instance, *instance_xform);
  1356. } else if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
  1357. RSG::particles_storage->particles_set_emission_transform(p_instance->base, *instance_xform);
  1358. } else if (p_instance->base_type == RS::INSTANCE_PARTICLES_COLLISION) {
  1359. InstanceParticlesCollisionData *collision = static_cast<InstanceParticlesCollisionData *>(p_instance->base_data);
  1360. //remove materials no longer used and un-own them
  1361. if (RSG::particles_storage->particles_collision_is_heightfield(p_instance->base)) {
  1362. heightfield_particle_colliders_update_list.insert(p_instance);
  1363. }
  1364. RSG::particles_storage->particles_collision_instance_set_transform(collision->instance, *instance_xform);
  1365. collision->cull_mask = RSG::particles_storage->particles_collision_get_cull_mask(p_instance->base);
  1366. } else if (p_instance->base_type == RS::INSTANCE_FOG_VOLUME) {
  1367. InstanceFogVolumeData *volume = static_cast<InstanceFogVolumeData *>(p_instance->base_data);
  1368. scene_render->fog_volume_instance_set_transform(volume->instance, *instance_xform);
  1369. } else if (p_instance->base_type == RS::INSTANCE_OCCLUDER) {
  1370. if (p_instance->scenario) {
  1371. RendererSceneOcclusionCull::get_singleton()->scenario_set_instance(p_instance->scenario->self, p_instance->self, p_instance->base, *instance_xform, p_instance->visible);
  1372. }
  1373. } else if (p_instance->base_type == RS::INSTANCE_NONE) {
  1374. return;
  1375. }
  1376. if (!p_instance->aabb.has_surface()) {
  1377. return;
  1378. }
  1379. if (p_instance->base_type == RS::INSTANCE_LIGHTMAP) {
  1380. //if this moved, update the captured objects
  1381. InstanceLightmapData *lightmap_data = static_cast<InstanceLightmapData *>(p_instance->base_data);
  1382. //erase dependencies, since no longer a lightmap
  1383. for (Instance *E : lightmap_data->geometries) {
  1384. Instance *geom = E;
  1385. _instance_queue_update(geom, true, false);
  1386. }
  1387. }
  1388. AABB new_aabb;
  1389. new_aabb = instance_xform->xform(p_instance->aabb);
  1390. p_instance->transformed_aabb = new_aabb;
  1391. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1392. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1393. //make sure lights are updated if it casts shadow
  1394. if (geom->can_cast_shadows) {
  1395. for (const Instance *E : geom->lights) {
  1396. InstanceLightData *light = static_cast<InstanceLightData *>(E->base_data);
  1397. light->make_shadow_dirty();
  1398. }
  1399. }
  1400. if (!p_instance->lightmap && geom->lightmap_captures.size()) {
  1401. //affected by lightmap captures, must update capture info!
  1402. _update_instance_lightmap_captures(p_instance);
  1403. } else {
  1404. if (!p_instance->lightmap_sh.is_empty()) {
  1405. p_instance->lightmap_sh.clear(); //don't need SH
  1406. p_instance->lightmap_target_sh.clear(); //don't need SH
  1407. ERR_FAIL_NULL(geom->geometry_instance);
  1408. geom->geometry_instance->set_lightmap_capture(nullptr);
  1409. }
  1410. }
  1411. ERR_FAIL_NULL(geom->geometry_instance);
  1412. geom->geometry_instance->set_transform(*instance_xform, p_instance->aabb, p_instance->transformed_aabb);
  1413. if (p_instance->teleported) {
  1414. geom->geometry_instance->reset_motion_vectors();
  1415. }
  1416. }
  1417. // note: we had to remove is equal approx check here, it meant that det == 0.000004 won't work, which is the case for some of our scenes.
  1418. if (p_instance->scenario == nullptr || !p_instance->visible || instance_xform->basis.determinant() == 0) {
  1419. p_instance->prev_transformed_aabb = p_instance->transformed_aabb;
  1420. return;
  1421. }
  1422. //quantize to improve moving object performance
  1423. AABB bvh_aabb = p_instance->transformed_aabb;
  1424. if (p_instance->indexer_id.is_valid() && bvh_aabb != p_instance->prev_transformed_aabb) {
  1425. //assume motion, see if bounds need to be quantized
  1426. AABB motion_aabb = bvh_aabb.merge(p_instance->prev_transformed_aabb);
  1427. float motion_longest_axis = motion_aabb.get_longest_axis_size();
  1428. float longest_axis = p_instance->transformed_aabb.get_longest_axis_size();
  1429. if (motion_longest_axis < longest_axis * 2) {
  1430. //moved but not a lot, use motion aabb quantizing
  1431. float quantize_size = Math::pow(2.0, Math::ceil(Math::log(motion_longest_axis) / Math::log(2.0))) * 0.5; //one fifth
  1432. bvh_aabb.quantize(quantize_size);
  1433. }
  1434. }
  1435. if (!p_instance->indexer_id.is_valid()) {
  1436. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1437. p_instance->indexer_id = p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY].insert(bvh_aabb, p_instance);
  1438. } else {
  1439. p_instance->indexer_id = p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES].insert(bvh_aabb, p_instance);
  1440. }
  1441. p_instance->array_index = p_instance->scenario->instance_data.size();
  1442. InstanceData idata;
  1443. idata.instance = p_instance;
  1444. idata.layer_mask = p_instance->layer_mask;
  1445. idata.flags = p_instance->base_type; //changing it means de-indexing, so this never needs to be changed later
  1446. idata.base_rid = p_instance->base;
  1447. idata.parent_array_index = p_instance->visibility_parent ? p_instance->visibility_parent->array_index : -1;
  1448. idata.visibility_index = p_instance->visibility_index;
  1449. idata.occlusion_timeout = 0;
  1450. for (Instance *E : p_instance->visibility_dependencies) {
  1451. Instance *dep_instance = E;
  1452. if (dep_instance->array_index != -1) {
  1453. dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index = p_instance->array_index;
  1454. }
  1455. }
  1456. switch (p_instance->base_type) {
  1457. case RS::INSTANCE_MESH:
  1458. case RS::INSTANCE_MULTIMESH:
  1459. case RS::INSTANCE_PARTICLES: {
  1460. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1461. idata.instance_geometry = geom->geometry_instance;
  1462. } break;
  1463. case RS::INSTANCE_LIGHT: {
  1464. InstanceLightData *light_data = static_cast<InstanceLightData *>(p_instance->base_data);
  1465. idata.instance_data_rid = light_data->instance.get_id();
  1466. light_data->uses_projector = RSG::light_storage->light_has_projector(p_instance->base);
  1467. light_data->uses_softshadow = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SIZE) > CMP_EPSILON;
  1468. } break;
  1469. case RS::INSTANCE_REFLECTION_PROBE: {
  1470. idata.instance_data_rid = static_cast<InstanceReflectionProbeData *>(p_instance->base_data)->instance.get_id();
  1471. } break;
  1472. case RS::INSTANCE_DECAL: {
  1473. idata.instance_data_rid = static_cast<InstanceDecalData *>(p_instance->base_data)->instance.get_id();
  1474. } break;
  1475. case RS::INSTANCE_LIGHTMAP: {
  1476. idata.instance_data_rid = static_cast<InstanceLightmapData *>(p_instance->base_data)->instance.get_id();
  1477. } break;
  1478. case RS::INSTANCE_VOXEL_GI: {
  1479. idata.instance_data_rid = static_cast<InstanceVoxelGIData *>(p_instance->base_data)->probe_instance.get_id();
  1480. } break;
  1481. case RS::INSTANCE_FOG_VOLUME: {
  1482. idata.instance_data_rid = static_cast<InstanceFogVolumeData *>(p_instance->base_data)->instance.get_id();
  1483. } break;
  1484. case RS::INSTANCE_VISIBLITY_NOTIFIER: {
  1485. idata.visibility_notifier = static_cast<InstanceVisibilityNotifierData *>(p_instance->base_data);
  1486. } break;
  1487. default: {
  1488. }
  1489. }
  1490. if (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE) {
  1491. //always dirty when added
  1492. idata.flags |= InstanceData::FLAG_REFLECTION_PROBE_DIRTY;
  1493. }
  1494. if (p_instance->cast_shadows != RS::SHADOW_CASTING_SETTING_OFF) {
  1495. idata.flags |= InstanceData::FLAG_CAST_SHADOWS;
  1496. }
  1497. if (p_instance->cast_shadows == RS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
  1498. idata.flags |= InstanceData::FLAG_CAST_SHADOWS_ONLY;
  1499. }
  1500. if (p_instance->redraw_if_visible) {
  1501. idata.flags |= InstanceData::FLAG_REDRAW_IF_VISIBLE;
  1502. }
  1503. // dirty flags should not be set here, since no pairing has happened
  1504. if (p_instance->baked_light) {
  1505. idata.flags |= InstanceData::FLAG_USES_BAKED_LIGHT;
  1506. }
  1507. if (p_instance->mesh_instance.is_valid()) {
  1508. idata.flags |= InstanceData::FLAG_USES_MESH_INSTANCE;
  1509. }
  1510. if (p_instance->ignore_occlusion_culling) {
  1511. idata.flags |= InstanceData::FLAG_IGNORE_OCCLUSION_CULLING;
  1512. }
  1513. if (p_instance->ignore_all_culling) {
  1514. idata.flags |= InstanceData::FLAG_IGNORE_ALL_CULLING;
  1515. }
  1516. p_instance->scenario->instance_data.push_back(idata);
  1517. p_instance->scenario->instance_aabbs.push_back(InstanceBounds(p_instance->transformed_aabb));
  1518. _update_instance_visibility_dependencies(p_instance);
  1519. } else {
  1520. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1521. p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY].update(p_instance->indexer_id, bvh_aabb);
  1522. } else {
  1523. p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES].update(p_instance->indexer_id, bvh_aabb);
  1524. }
  1525. p_instance->scenario->instance_aabbs[p_instance->array_index] = InstanceBounds(p_instance->transformed_aabb);
  1526. }
  1527. if (p_instance->visibility_index != -1) {
  1528. p_instance->scenario->instance_visibility[p_instance->visibility_index].position = p_instance->transformed_aabb.get_center();
  1529. }
  1530. //move instance and repair
  1531. pair_pass++;
  1532. PairInstances pair;
  1533. pair.instance = p_instance;
  1534. pair.pair_allocator = &pair_allocator;
  1535. pair.pair_pass = pair_pass;
  1536. pair.pair_mask = 0;
  1537. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1538. pair.pair_mask |= 1 << RS::INSTANCE_LIGHT;
  1539. pair.pair_mask |= 1 << RS::INSTANCE_VOXEL_GI;
  1540. pair.pair_mask |= 1 << RS::INSTANCE_LIGHTMAP;
  1541. if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
  1542. pair.pair_mask |= 1 << RS::INSTANCE_PARTICLES_COLLISION;
  1543. }
  1544. pair.pair_mask |= geometry_instance_pair_mask;
  1545. pair.bvh2 = &p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES];
  1546. } else if (p_instance->base_type == RS::INSTANCE_LIGHT) {
  1547. pair.pair_mask |= RS::INSTANCE_GEOMETRY_MASK;
  1548. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1549. RS::LightBakeMode bake_mode = RSG::light_storage->light_get_bake_mode(p_instance->base);
  1550. if (bake_mode == RS::LIGHT_BAKE_STATIC || bake_mode == RS::LIGHT_BAKE_DYNAMIC) {
  1551. pair.pair_mask |= (1 << RS::INSTANCE_VOXEL_GI);
  1552. pair.bvh2 = &p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES];
  1553. }
  1554. } else if (p_instance->base_type == RS::INSTANCE_LIGHTMAP) {
  1555. pair.pair_mask = RS::INSTANCE_GEOMETRY_MASK;
  1556. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1557. } else if (geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && (p_instance->base_type == RS::INSTANCE_REFLECTION_PROBE)) {
  1558. pair.pair_mask = RS::INSTANCE_GEOMETRY_MASK;
  1559. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1560. } else if (geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && (p_instance->base_type == RS::INSTANCE_DECAL)) {
  1561. pair.pair_mask = RS::INSTANCE_GEOMETRY_MASK;
  1562. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1563. } else if (p_instance->base_type == RS::INSTANCE_PARTICLES_COLLISION) {
  1564. pair.pair_mask = (1 << RS::INSTANCE_PARTICLES);
  1565. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1566. } else if (p_instance->base_type == RS::INSTANCE_VOXEL_GI) {
  1567. //lights and geometries
  1568. pair.pair_mask = RS::INSTANCE_GEOMETRY_MASK | (1 << RS::INSTANCE_LIGHT);
  1569. pair.bvh = &p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY];
  1570. pair.bvh2 = &p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES];
  1571. }
  1572. pair.pair();
  1573. p_instance->prev_transformed_aabb = p_instance->transformed_aabb;
  1574. }
  1575. void RendererSceneCull::_unpair_instance(Instance *p_instance) {
  1576. if (!p_instance->indexer_id.is_valid()) {
  1577. return; //nothing to do
  1578. }
  1579. while (p_instance->pairs.first()) {
  1580. InstancePair *pair = p_instance->pairs.first()->self();
  1581. Instance *other_instance = p_instance == pair->a ? pair->b : pair->a;
  1582. _instance_unpair(p_instance, other_instance);
  1583. pair_allocator.free(pair);
  1584. }
  1585. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1586. p_instance->scenario->indexers[Scenario::INDEXER_GEOMETRY].remove(p_instance->indexer_id);
  1587. } else {
  1588. p_instance->scenario->indexers[Scenario::INDEXER_VOLUMES].remove(p_instance->indexer_id);
  1589. }
  1590. p_instance->indexer_id = DynamicBVH::ID();
  1591. //replace this by last
  1592. int32_t swap_with_index = p_instance->scenario->instance_data.size() - 1;
  1593. if (swap_with_index != p_instance->array_index) {
  1594. Instance *swapped_instance = p_instance->scenario->instance_data[swap_with_index].instance;
  1595. swapped_instance->array_index = p_instance->array_index; //swap
  1596. p_instance->scenario->instance_data[p_instance->array_index] = p_instance->scenario->instance_data[swap_with_index];
  1597. p_instance->scenario->instance_aabbs[p_instance->array_index] = p_instance->scenario->instance_aabbs[swap_with_index];
  1598. if (swapped_instance->visibility_index != -1) {
  1599. swapped_instance->scenario->instance_visibility[swapped_instance->visibility_index].array_index = swapped_instance->array_index;
  1600. }
  1601. for (Instance *E : swapped_instance->visibility_dependencies) {
  1602. Instance *dep_instance = E;
  1603. if (dep_instance != p_instance && dep_instance->array_index != -1) {
  1604. dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index = swapped_instance->array_index;
  1605. }
  1606. }
  1607. }
  1608. // pop last
  1609. p_instance->scenario->instance_data.pop_back();
  1610. p_instance->scenario->instance_aabbs.pop_back();
  1611. //uninitialize
  1612. p_instance->array_index = -1;
  1613. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1614. // Clear these now because the InstanceData containing the dirty flags is gone
  1615. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1616. ERR_FAIL_NULL(geom->geometry_instance);
  1617. geom->geometry_instance->pair_light_instances(nullptr, 0);
  1618. geom->geometry_instance->pair_reflection_probe_instances(nullptr, 0);
  1619. geom->geometry_instance->pair_decal_instances(nullptr, 0);
  1620. geom->geometry_instance->pair_voxel_gi_instances(nullptr, 0);
  1621. }
  1622. for (Instance *E : p_instance->visibility_dependencies) {
  1623. Instance *dep_instance = E;
  1624. if (dep_instance->array_index != -1) {
  1625. dep_instance->scenario->instance_data[dep_instance->array_index].parent_array_index = -1;
  1626. if ((1 << dep_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  1627. dep_instance->scenario->instance_data[dep_instance->array_index].instance_geometry->set_parent_fade_alpha(1.0f);
  1628. }
  1629. }
  1630. }
  1631. _update_instance_visibility_dependencies(p_instance);
  1632. }
  1633. void RendererSceneCull::_update_instance_aabb(Instance *p_instance) const {
  1634. AABB new_aabb;
  1635. ERR_FAIL_COND(p_instance->base_type != RS::INSTANCE_NONE && !p_instance->base.is_valid());
  1636. switch (p_instance->base_type) {
  1637. case RenderingServer::INSTANCE_NONE: {
  1638. // do nothing
  1639. } break;
  1640. case RenderingServer::INSTANCE_MESH: {
  1641. if (p_instance->custom_aabb) {
  1642. new_aabb = *p_instance->custom_aabb;
  1643. } else {
  1644. new_aabb = RSG::mesh_storage->mesh_get_aabb(p_instance->base, p_instance->skeleton);
  1645. }
  1646. } break;
  1647. case RenderingServer::INSTANCE_MULTIMESH: {
  1648. if (p_instance->custom_aabb) {
  1649. new_aabb = *p_instance->custom_aabb;
  1650. } else {
  1651. new_aabb = RSG::mesh_storage->multimesh_get_aabb(p_instance->base);
  1652. }
  1653. } break;
  1654. case RenderingServer::INSTANCE_PARTICLES: {
  1655. if (p_instance->custom_aabb) {
  1656. new_aabb = *p_instance->custom_aabb;
  1657. } else {
  1658. new_aabb = RSG::particles_storage->particles_get_aabb(p_instance->base);
  1659. }
  1660. } break;
  1661. case RenderingServer::INSTANCE_PARTICLES_COLLISION: {
  1662. new_aabb = RSG::particles_storage->particles_collision_get_aabb(p_instance->base);
  1663. } break;
  1664. case RenderingServer::INSTANCE_FOG_VOLUME: {
  1665. new_aabb = RSG::fog->fog_volume_get_aabb(p_instance->base);
  1666. } break;
  1667. case RenderingServer::INSTANCE_VISIBLITY_NOTIFIER: {
  1668. new_aabb = RSG::utilities->visibility_notifier_get_aabb(p_instance->base);
  1669. } break;
  1670. case RenderingServer::INSTANCE_LIGHT: {
  1671. new_aabb = RSG::light_storage->light_get_aabb(p_instance->base);
  1672. } break;
  1673. case RenderingServer::INSTANCE_REFLECTION_PROBE: {
  1674. new_aabb = RSG::light_storage->reflection_probe_get_aabb(p_instance->base);
  1675. } break;
  1676. case RenderingServer::INSTANCE_DECAL: {
  1677. new_aabb = RSG::texture_storage->decal_get_aabb(p_instance->base);
  1678. } break;
  1679. case RenderingServer::INSTANCE_VOXEL_GI: {
  1680. new_aabb = RSG::gi->voxel_gi_get_bounds(p_instance->base);
  1681. } break;
  1682. case RenderingServer::INSTANCE_LIGHTMAP: {
  1683. new_aabb = RSG::light_storage->lightmap_get_aabb(p_instance->base);
  1684. } break;
  1685. default: {
  1686. }
  1687. }
  1688. if (p_instance->extra_margin) {
  1689. new_aabb.grow_by(p_instance->extra_margin);
  1690. }
  1691. p_instance->aabb = new_aabb;
  1692. }
  1693. void RendererSceneCull::_update_instance_lightmap_captures(Instance *p_instance) const {
  1694. bool first_set = p_instance->lightmap_sh.is_empty();
  1695. p_instance->lightmap_sh.resize(9); //using SH
  1696. p_instance->lightmap_target_sh.resize(9); //using SH
  1697. Color *instance_sh = p_instance->lightmap_target_sh.ptrw();
  1698. bool inside = false;
  1699. Color accum_sh[9];
  1700. float accum_blend = 0.0;
  1701. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  1702. for (Instance *E : geom->lightmap_captures) {
  1703. Instance *lightmap = E;
  1704. bool interior = RSG::light_storage->lightmap_is_interior(lightmap->base);
  1705. if (inside && !interior) {
  1706. continue; //we are inside, ignore exteriors
  1707. }
  1708. Transform3D to_bounds = lightmap->transform.affine_inverse();
  1709. Vector3 center = p_instance->transform.xform(p_instance->aabb.get_center()); //use aabb center
  1710. Vector3 lm_pos = to_bounds.xform(center);
  1711. AABB bounds = RSG::light_storage->lightmap_get_aabb(lightmap->base);
  1712. if (!bounds.has_point(lm_pos)) {
  1713. continue; //not in this lightmap
  1714. }
  1715. Color sh[9];
  1716. RSG::light_storage->lightmap_tap_sh_light(lightmap->base, lm_pos, sh);
  1717. //rotate it
  1718. Basis rot = lightmap->transform.basis.orthonormalized();
  1719. for (int i = 0; i < 3; i++) {
  1720. real_t csh[9];
  1721. for (int j = 0; j < 9; j++) {
  1722. csh[j] = sh[j][i];
  1723. }
  1724. rot.rotate_sh(csh);
  1725. for (int j = 0; j < 9; j++) {
  1726. sh[j][i] = csh[j];
  1727. }
  1728. }
  1729. Vector3 inner_pos = ((lm_pos - bounds.position) / bounds.size) * 2.0 - Vector3(1.0, 1.0, 1.0);
  1730. real_t blend = MAX(Math::abs(inner_pos.x), MAX(Math::abs(inner_pos.y), Math::abs(inner_pos.z)));
  1731. //make blend more rounded
  1732. blend = Math::lerp(inner_pos.length(), blend, blend);
  1733. blend *= blend;
  1734. blend = MAX(0.0, 1.0 - blend);
  1735. if (interior && !inside) {
  1736. //do not blend, just replace
  1737. for (int j = 0; j < 9; j++) {
  1738. accum_sh[j] = sh[j] * blend;
  1739. }
  1740. accum_blend = blend;
  1741. inside = true;
  1742. } else {
  1743. for (int j = 0; j < 9; j++) {
  1744. accum_sh[j] += sh[j] * blend;
  1745. }
  1746. accum_blend += blend;
  1747. }
  1748. }
  1749. if (accum_blend > 0.0) {
  1750. for (int j = 0; j < 9; j++) {
  1751. instance_sh[j] = accum_sh[j] / accum_blend;
  1752. if (first_set) {
  1753. p_instance->lightmap_sh.write[j] = instance_sh[j];
  1754. }
  1755. }
  1756. }
  1757. ERR_FAIL_NULL(geom->geometry_instance);
  1758. geom->geometry_instance->set_lightmap_capture(p_instance->lightmap_sh.ptr());
  1759. }
  1760. void RendererSceneCull::_light_instance_setup_directional_shadow(int p_shadow_index, Instance *p_instance, const Transform3D p_cam_transform, const Projection &p_cam_projection, bool p_cam_orthogonal, bool p_cam_vaspect) {
  1761. // For later tight culling, the light culler needs to know the details of the directional light.
  1762. light_culler->prepare_directional_light(p_instance, p_shadow_index);
  1763. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  1764. Transform3D light_transform = p_instance->transform;
  1765. light_transform.orthonormalize(); //scale does not count on lights
  1766. real_t max_distance = p_cam_projection.get_z_far();
  1767. real_t shadow_max = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SHADOW_MAX_DISTANCE);
  1768. if (shadow_max > 0 && !p_cam_orthogonal) { //its impractical (and leads to unwanted behaviors) to set max distance in orthogonal camera
  1769. max_distance = MIN(shadow_max, max_distance);
  1770. }
  1771. max_distance = MAX(max_distance, p_cam_projection.get_z_near() + 0.001);
  1772. real_t min_distance = MIN(p_cam_projection.get_z_near(), max_distance);
  1773. real_t pancake_size = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SHADOW_PANCAKE_SIZE);
  1774. real_t range = max_distance - min_distance;
  1775. int splits = 0;
  1776. switch (RSG::light_storage->light_directional_get_shadow_mode(p_instance->base)) {
  1777. case RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL:
  1778. splits = 1;
  1779. break;
  1780. case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
  1781. splits = 2;
  1782. break;
  1783. case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS:
  1784. splits = 4;
  1785. break;
  1786. }
  1787. real_t distances[5];
  1788. distances[0] = min_distance;
  1789. for (int i = 0; i < splits; i++) {
  1790. distances[i + 1] = min_distance + RSG::light_storage->light_get_param(p_instance->base, RS::LightParam(RS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET + i)) * range;
  1791. };
  1792. distances[splits] = max_distance;
  1793. real_t texture_size = RSG::light_storage->get_directional_light_shadow_size(light->instance);
  1794. bool overlap = RSG::light_storage->light_directional_get_blend_splits(p_instance->base);
  1795. cull.shadow_count = p_shadow_index + 1;
  1796. cull.shadows[p_shadow_index].cascade_count = splits;
  1797. cull.shadows[p_shadow_index].light_instance = light->instance;
  1798. cull.shadows[p_shadow_index].caster_mask = RSG::light_storage->light_get_shadow_caster_mask(p_instance->base);
  1799. for (int i = 0; i < splits; i++) {
  1800. RENDER_TIMESTAMP("Cull DirectionalLight3D, Split " + itos(i));
  1801. // setup a camera matrix for that range!
  1802. Projection camera_matrix;
  1803. real_t aspect = p_cam_projection.get_aspect();
  1804. if (p_cam_orthogonal) {
  1805. Vector2 vp_he = p_cam_projection.get_viewport_half_extents();
  1806. camera_matrix.set_orthogonal(vp_he.y * 2.0, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
  1807. } else {
  1808. real_t fov = p_cam_projection.get_fov(); //this is actually yfov, because set aspect tries to keep it
  1809. camera_matrix.set_perspective(fov, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], true);
  1810. }
  1811. //obtain the frustum endpoints
  1812. Vector3 endpoints[8]; // frustum plane endpoints
  1813. bool res = camera_matrix.get_endpoints(p_cam_transform, endpoints);
  1814. ERR_CONTINUE(!res);
  1815. // obtain the light frustum ranges (given endpoints)
  1816. Transform3D transform = light_transform; //discard scale and stabilize light
  1817. Vector3 x_vec = transform.basis.get_column(Vector3::AXIS_X).normalized();
  1818. Vector3 y_vec = transform.basis.get_column(Vector3::AXIS_Y).normalized();
  1819. Vector3 z_vec = transform.basis.get_column(Vector3::AXIS_Z).normalized();
  1820. //z_vec points against the camera, like in default opengl
  1821. real_t x_min = 0.f, x_max = 0.f;
  1822. real_t y_min = 0.f, y_max = 0.f;
  1823. real_t z_min = 0.f, z_max = 0.f;
  1824. // FIXME: z_max_cam is defined, computed, but not used below when setting up
  1825. // ortho_camera. Commented out for now to fix warnings but should be investigated.
  1826. real_t x_min_cam = 0.f, x_max_cam = 0.f;
  1827. real_t y_min_cam = 0.f, y_max_cam = 0.f;
  1828. real_t z_min_cam = 0.f;
  1829. //real_t z_max_cam = 0.f;
  1830. //real_t bias_scale = 1.0;
  1831. //real_t aspect_bias_scale = 1.0;
  1832. //used for culling
  1833. for (int j = 0; j < 8; j++) {
  1834. real_t d_x = x_vec.dot(endpoints[j]);
  1835. real_t d_y = y_vec.dot(endpoints[j]);
  1836. real_t d_z = z_vec.dot(endpoints[j]);
  1837. if (j == 0 || d_x < x_min) {
  1838. x_min = d_x;
  1839. }
  1840. if (j == 0 || d_x > x_max) {
  1841. x_max = d_x;
  1842. }
  1843. if (j == 0 || d_y < y_min) {
  1844. y_min = d_y;
  1845. }
  1846. if (j == 0 || d_y > y_max) {
  1847. y_max = d_y;
  1848. }
  1849. if (j == 0 || d_z < z_min) {
  1850. z_min = d_z;
  1851. }
  1852. if (j == 0 || d_z > z_max) {
  1853. z_max = d_z;
  1854. }
  1855. }
  1856. real_t radius = 0;
  1857. real_t soft_shadow_expand = 0;
  1858. Vector3 center;
  1859. {
  1860. //camera viewport stuff
  1861. for (int j = 0; j < 8; j++) {
  1862. center += endpoints[j];
  1863. }
  1864. center /= 8.0;
  1865. //center=x_vec*(x_max-x_min)*0.5 + y_vec*(y_max-y_min)*0.5 + z_vec*(z_max-z_min)*0.5;
  1866. for (int j = 0; j < 8; j++) {
  1867. real_t d = center.distance_to(endpoints[j]);
  1868. if (d > radius) {
  1869. radius = d;
  1870. }
  1871. }
  1872. radius *= texture_size / (texture_size - 2.0); //add a texel by each side
  1873. z_min_cam = z_vec.dot(center) - radius;
  1874. {
  1875. float soft_shadow_angle = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SIZE);
  1876. if (soft_shadow_angle > 0.0) {
  1877. float z_range = (z_vec.dot(center) + radius + pancake_size) - z_min_cam;
  1878. soft_shadow_expand = Math::tan(Math::deg_to_rad(soft_shadow_angle)) * z_range;
  1879. x_max += soft_shadow_expand;
  1880. y_max += soft_shadow_expand;
  1881. x_min -= soft_shadow_expand;
  1882. y_min -= soft_shadow_expand;
  1883. }
  1884. }
  1885. // This trick here is what stabilizes the shadow (make potential jaggies to not move)
  1886. // at the cost of some wasted resolution. Still, the quality increase is very well worth it.
  1887. const real_t unit = (radius + soft_shadow_expand) * 4.0 / texture_size;
  1888. x_max_cam = Math::snapped(x_vec.dot(center) + radius + soft_shadow_expand, unit);
  1889. x_min_cam = Math::snapped(x_vec.dot(center) - radius - soft_shadow_expand, unit);
  1890. y_max_cam = Math::snapped(y_vec.dot(center) + radius + soft_shadow_expand, unit);
  1891. y_min_cam = Math::snapped(y_vec.dot(center) - radius - soft_shadow_expand, unit);
  1892. }
  1893. //now that we know all ranges, we can proceed to make the light frustum planes, for culling octree
  1894. Vector<Plane> light_frustum_planes;
  1895. light_frustum_planes.resize(6);
  1896. //right/left
  1897. light_frustum_planes.write[0] = Plane(x_vec, x_max);
  1898. light_frustum_planes.write[1] = Plane(-x_vec, -x_min);
  1899. //top/bottom
  1900. light_frustum_planes.write[2] = Plane(y_vec, y_max);
  1901. light_frustum_planes.write[3] = Plane(-y_vec, -y_min);
  1902. //near/far
  1903. light_frustum_planes.write[4] = Plane(z_vec, z_max + 1e6);
  1904. light_frustum_planes.write[5] = Plane(-z_vec, -z_min); // z_min is ok, since casters further than far-light plane are not needed
  1905. // a pre pass will need to be needed to determine the actual z-near to be used
  1906. z_max = z_vec.dot(center) + radius + pancake_size;
  1907. {
  1908. Projection ortho_camera;
  1909. real_t half_x = (x_max_cam - x_min_cam) * 0.5;
  1910. real_t half_y = (y_max_cam - y_min_cam) * 0.5;
  1911. ortho_camera.set_orthogonal(-half_x, half_x, -half_y, half_y, 0, (z_max - z_min_cam));
  1912. Vector2 uv_scale(1.0 / (x_max_cam - x_min_cam), 1.0 / (y_max_cam - y_min_cam));
  1913. Transform3D ortho_transform;
  1914. ortho_transform.basis = transform.basis;
  1915. ortho_transform.origin = x_vec * (x_min_cam + half_x) + y_vec * (y_min_cam + half_y) + z_vec * z_max;
  1916. cull.shadows[p_shadow_index].cascades[i].frustum = Frustum(light_frustum_planes);
  1917. cull.shadows[p_shadow_index].cascades[i].projection = ortho_camera;
  1918. cull.shadows[p_shadow_index].cascades[i].transform = ortho_transform;
  1919. cull.shadows[p_shadow_index].cascades[i].zfar = z_max - z_min_cam;
  1920. cull.shadows[p_shadow_index].cascades[i].split = distances[i + 1];
  1921. cull.shadows[p_shadow_index].cascades[i].shadow_texel_size = radius * 2.0 / texture_size;
  1922. cull.shadows[p_shadow_index].cascades[i].bias_scale = (z_max - z_min_cam);
  1923. cull.shadows[p_shadow_index].cascades[i].range_begin = z_max;
  1924. cull.shadows[p_shadow_index].cascades[i].uv_scale = uv_scale;
  1925. }
  1926. }
  1927. }
  1928. bool RendererSceneCull::_light_instance_update_shadow(Instance *p_instance, const Transform3D p_cam_transform, const Projection &p_cam_projection, bool p_cam_orthogonal, bool p_cam_vaspect, RID p_shadow_atlas, Scenario *p_scenario, float p_screen_mesh_lod_threshold, uint32_t p_visible_layers) {
  1929. InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
  1930. Transform3D light_transform = p_instance->transform;
  1931. light_transform.orthonormalize(); //scale does not count on lights
  1932. bool animated_material_found = false;
  1933. switch (RSG::light_storage->light_get_type(p_instance->base)) {
  1934. case RS::LIGHT_DIRECTIONAL: {
  1935. } break;
  1936. case RS::LIGHT_OMNI: {
  1937. RS::LightOmniShadowMode shadow_mode = RSG::light_storage->light_omni_get_shadow_mode(p_instance->base);
  1938. if (shadow_mode == RS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID || !RSG::light_storage->light_instances_can_render_shadow_cube()) {
  1939. if (max_shadows_used + 2 > MAX_UPDATE_SHADOWS) {
  1940. return true;
  1941. }
  1942. for (int i = 0; i < 2; i++) {
  1943. //using this one ensures that raster deferred will have it
  1944. RENDER_TIMESTAMP("Cull OmniLight3D Shadow Paraboloid, Half " + itos(i));
  1945. real_t radius = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  1946. real_t z = i == 0 ? -1 : 1;
  1947. Vector<Plane> planes;
  1948. planes.resize(6);
  1949. planes.write[0] = light_transform.xform(Plane(Vector3(0, 0, z), radius));
  1950. planes.write[1] = light_transform.xform(Plane(Vector3(1, 0, z).normalized(), radius));
  1951. planes.write[2] = light_transform.xform(Plane(Vector3(-1, 0, z).normalized(), radius));
  1952. planes.write[3] = light_transform.xform(Plane(Vector3(0, 1, z).normalized(), radius));
  1953. planes.write[4] = light_transform.xform(Plane(Vector3(0, -1, z).normalized(), radius));
  1954. planes.write[5] = light_transform.xform(Plane(Vector3(0, 0, -z), 0));
  1955. instance_shadow_cull_result.clear();
  1956. Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&planes[0], planes.size());
  1957. struct CullConvex {
  1958. PagedArray<Instance *> *result;
  1959. _FORCE_INLINE_ bool operator()(void *p_data) {
  1960. Instance *p_instance = (Instance *)p_data;
  1961. result->push_back(p_instance);
  1962. return false;
  1963. }
  1964. };
  1965. CullConvex cull_convex;
  1966. cull_convex.result = &instance_shadow_cull_result;
  1967. p_scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(planes.ptr(), planes.size(), points.ptr(), points.size(), cull_convex);
  1968. RendererSceneRender::RenderShadowData &shadow_data = render_shadow_data[max_shadows_used++];
  1969. if (!light->is_shadow_update_full()) {
  1970. light_culler->cull_regular_light(instance_shadow_cull_result);
  1971. }
  1972. for (int j = 0; j < (int)instance_shadow_cull_result.size(); j++) {
  1973. Instance *instance = instance_shadow_cull_result[j];
  1974. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows || !(p_visible_layers & instance->layer_mask & RSG::light_storage->light_get_shadow_caster_mask(p_instance->base))) {
  1975. continue;
  1976. } else {
  1977. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  1978. animated_material_found = true;
  1979. }
  1980. if (instance->mesh_instance.is_valid()) {
  1981. RSG::mesh_storage->mesh_instance_check_for_update(instance->mesh_instance);
  1982. }
  1983. }
  1984. shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance);
  1985. }
  1986. RSG::mesh_storage->update_mesh_instances();
  1987. RSG::light_storage->light_instance_set_shadow_transform(light->instance, Projection(), light_transform, radius, 0, i, 0);
  1988. shadow_data.light = light->instance;
  1989. shadow_data.pass = i;
  1990. }
  1991. } else { //shadow cube
  1992. if (max_shadows_used + 6 > MAX_UPDATE_SHADOWS) {
  1993. return true;
  1994. }
  1995. real_t radius = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  1996. real_t z_near = MIN(0.025f, radius);
  1997. Projection cm;
  1998. cm.set_perspective(90, 1, z_near, radius);
  1999. for (int i = 0; i < 6; i++) {
  2000. RENDER_TIMESTAMP("Cull OmniLight3D Shadow Cube, Side " + itos(i));
  2001. //using this one ensures that raster deferred will have it
  2002. static const Vector3 view_normals[6] = {
  2003. Vector3(+1, 0, 0),
  2004. Vector3(-1, 0, 0),
  2005. Vector3(0, -1, 0),
  2006. Vector3(0, +1, 0),
  2007. Vector3(0, 0, +1),
  2008. Vector3(0, 0, -1)
  2009. };
  2010. static const Vector3 view_up[6] = {
  2011. Vector3(0, -1, 0),
  2012. Vector3(0, -1, 0),
  2013. Vector3(0, 0, -1),
  2014. Vector3(0, 0, +1),
  2015. Vector3(0, -1, 0),
  2016. Vector3(0, -1, 0)
  2017. };
  2018. Transform3D xform = light_transform * Transform3D().looking_at(view_normals[i], view_up[i]);
  2019. Vector<Plane> planes = cm.get_projection_planes(xform);
  2020. instance_shadow_cull_result.clear();
  2021. Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&planes[0], planes.size());
  2022. struct CullConvex {
  2023. PagedArray<Instance *> *result;
  2024. _FORCE_INLINE_ bool operator()(void *p_data) {
  2025. Instance *p_instance = (Instance *)p_data;
  2026. result->push_back(p_instance);
  2027. return false;
  2028. }
  2029. };
  2030. CullConvex cull_convex;
  2031. cull_convex.result = &instance_shadow_cull_result;
  2032. p_scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(planes.ptr(), planes.size(), points.ptr(), points.size(), cull_convex);
  2033. RendererSceneRender::RenderShadowData &shadow_data = render_shadow_data[max_shadows_used++];
  2034. if (!light->is_shadow_update_full()) {
  2035. light_culler->cull_regular_light(instance_shadow_cull_result);
  2036. }
  2037. for (int j = 0; j < (int)instance_shadow_cull_result.size(); j++) {
  2038. Instance *instance = instance_shadow_cull_result[j];
  2039. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows || !(p_visible_layers & instance->layer_mask & RSG::light_storage->light_get_shadow_caster_mask(p_instance->base))) {
  2040. continue;
  2041. } else {
  2042. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  2043. animated_material_found = true;
  2044. }
  2045. if (instance->mesh_instance.is_valid()) {
  2046. RSG::mesh_storage->mesh_instance_check_for_update(instance->mesh_instance);
  2047. }
  2048. }
  2049. shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance);
  2050. }
  2051. RSG::mesh_storage->update_mesh_instances();
  2052. RSG::light_storage->light_instance_set_shadow_transform(light->instance, cm, xform, radius, 0, i, 0);
  2053. shadow_data.light = light->instance;
  2054. shadow_data.pass = i;
  2055. }
  2056. //restore the regular DP matrix
  2057. //RSG::light_storage->light_instance_set_shadow_transform(light->instance, Projection(), light_transform, radius, 0, 0, 0);
  2058. }
  2059. } break;
  2060. case RS::LIGHT_SPOT: {
  2061. RENDER_TIMESTAMP("Cull SpotLight3D Shadow");
  2062. if (max_shadows_used + 1 > MAX_UPDATE_SHADOWS) {
  2063. return true;
  2064. }
  2065. real_t radius = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_RANGE);
  2066. real_t angle = RSG::light_storage->light_get_param(p_instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  2067. real_t z_near = MIN(0.025f, radius);
  2068. Projection cm;
  2069. cm.set_perspective(angle * 2.0, 1.0, z_near, radius);
  2070. Vector<Plane> planes = cm.get_projection_planes(light_transform);
  2071. instance_shadow_cull_result.clear();
  2072. Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&planes[0], planes.size());
  2073. struct CullConvex {
  2074. PagedArray<Instance *> *result;
  2075. _FORCE_INLINE_ bool operator()(void *p_data) {
  2076. Instance *p_instance = (Instance *)p_data;
  2077. result->push_back(p_instance);
  2078. return false;
  2079. }
  2080. };
  2081. CullConvex cull_convex;
  2082. cull_convex.result = &instance_shadow_cull_result;
  2083. p_scenario->indexers[Scenario::INDEXER_GEOMETRY].convex_query(planes.ptr(), planes.size(), points.ptr(), points.size(), cull_convex);
  2084. RendererSceneRender::RenderShadowData &shadow_data = render_shadow_data[max_shadows_used++];
  2085. if (!light->is_shadow_update_full()) {
  2086. light_culler->cull_regular_light(instance_shadow_cull_result);
  2087. }
  2088. for (int j = 0; j < (int)instance_shadow_cull_result.size(); j++) {
  2089. Instance *instance = instance_shadow_cull_result[j];
  2090. if (!instance->visible || !((1 << instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows || !(p_visible_layers & instance->layer_mask & RSG::light_storage->light_get_shadow_caster_mask(p_instance->base))) {
  2091. continue;
  2092. } else {
  2093. if (static_cast<InstanceGeometryData *>(instance->base_data)->material_is_animated) {
  2094. animated_material_found = true;
  2095. }
  2096. if (instance->mesh_instance.is_valid()) {
  2097. RSG::mesh_storage->mesh_instance_check_for_update(instance->mesh_instance);
  2098. }
  2099. }
  2100. shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance);
  2101. }
  2102. RSG::mesh_storage->update_mesh_instances();
  2103. RSG::light_storage->light_instance_set_shadow_transform(light->instance, cm, light_transform, radius, 0, 0, 0);
  2104. shadow_data.light = light->instance;
  2105. shadow_data.pass = 0;
  2106. } break;
  2107. }
  2108. return animated_material_found;
  2109. }
  2110. void RendererSceneCull::render_camera(const Ref<RenderSceneBuffers> &p_render_buffers, RID p_camera, RID p_scenario, RID p_viewport, Size2 p_viewport_size, uint32_t p_jitter_phase_count, float p_screen_mesh_lod_threshold, RID p_shadow_atlas, Ref<XRInterface> &p_xr_interface, RenderInfo *r_render_info) {
  2111. #ifndef _3D_DISABLED
  2112. Camera *camera = camera_owner.get_or_null(p_camera);
  2113. ERR_FAIL_NULL(camera);
  2114. Vector2 jitter;
  2115. float taa_frame_count = 0.0f;
  2116. if (p_jitter_phase_count > 0) {
  2117. uint32_t current_jitter_count = camera_jitter_array.size();
  2118. if (p_jitter_phase_count != current_jitter_count) {
  2119. // Resize the jitter array and fill it with the pre-computed Halton sequence.
  2120. camera_jitter_array.resize(p_jitter_phase_count);
  2121. for (uint32_t i = current_jitter_count; i < p_jitter_phase_count; i++) {
  2122. camera_jitter_array[i].x = get_halton_value(i, 2);
  2123. camera_jitter_array[i].y = get_halton_value(i, 3);
  2124. }
  2125. }
  2126. jitter = camera_jitter_array[RSG::rasterizer->get_frame_number() % p_jitter_phase_count] / p_viewport_size;
  2127. taa_frame_count = float(RSG::rasterizer->get_frame_number() % p_jitter_phase_count);
  2128. }
  2129. RendererSceneRender::CameraData camera_data;
  2130. // Setup Camera(s)
  2131. if (p_xr_interface.is_null()) {
  2132. // Normal camera
  2133. Transform3D transform = camera->transform;
  2134. Projection projection;
  2135. bool vaspect = camera->vaspect;
  2136. bool is_orthogonal = false;
  2137. bool is_frustum = false;
  2138. switch (camera->type) {
  2139. case Camera::ORTHOGONAL: {
  2140. projection.set_orthogonal(
  2141. camera->size,
  2142. p_viewport_size.width / (float)p_viewport_size.height,
  2143. camera->znear,
  2144. camera->zfar,
  2145. camera->vaspect);
  2146. is_orthogonal = true;
  2147. } break;
  2148. case Camera::PERSPECTIVE: {
  2149. projection.set_perspective(
  2150. camera->fov,
  2151. p_viewport_size.width / (float)p_viewport_size.height,
  2152. camera->znear,
  2153. camera->zfar,
  2154. camera->vaspect);
  2155. } break;
  2156. case Camera::FRUSTUM: {
  2157. projection.set_frustum(
  2158. camera->size,
  2159. p_viewport_size.width / (float)p_viewport_size.height,
  2160. camera->offset,
  2161. camera->znear,
  2162. camera->zfar,
  2163. camera->vaspect);
  2164. is_frustum = true;
  2165. } break;
  2166. }
  2167. camera_data.set_camera(transform, projection, is_orthogonal, is_frustum, vaspect, jitter, taa_frame_count, camera->visible_layers);
  2168. #ifndef XR_DISABLED
  2169. } else {
  2170. XRServer *xr_server = XRServer::get_singleton();
  2171. // Setup our camera for our XR interface.
  2172. // We can support multiple views here each with their own camera
  2173. Transform3D transforms[RendererSceneRender::MAX_RENDER_VIEWS];
  2174. Projection projections[RendererSceneRender::MAX_RENDER_VIEWS];
  2175. uint32_t view_count = p_xr_interface->get_view_count();
  2176. ERR_FAIL_COND_MSG(view_count == 0 || view_count > RendererSceneRender::MAX_RENDER_VIEWS, "Requested view count is not supported");
  2177. float aspect = p_viewport_size.width / (float)p_viewport_size.height;
  2178. Transform3D world_origin = xr_server->get_world_origin();
  2179. // We ignore our camera position, it will have been positioned with a slightly old tracking position.
  2180. // Instead we take our origin point and have our XR interface add fresh tracking data! Whoohoo!
  2181. for (uint32_t v = 0; v < view_count; v++) {
  2182. transforms[v] = p_xr_interface->get_transform_for_view(v, world_origin);
  2183. projections[v] = p_xr_interface->get_projection_for_view(v, aspect, camera->znear, camera->zfar);
  2184. }
  2185. // If requested, we move the views to be rendered as if the HMD is at the XROrigin.
  2186. if (unlikely(xr_server->is_camera_locked_to_origin())) {
  2187. Transform3D camera_reset = p_xr_interface->get_camera_transform().affine_inverse() * xr_server->get_reference_frame().affine_inverse();
  2188. for (uint32_t v = 0; v < view_count; v++) {
  2189. transforms[v] *= camera_reset;
  2190. }
  2191. }
  2192. if (view_count == 1) {
  2193. camera_data.set_camera(transforms[0], projections[0], false, false, camera->vaspect, jitter, p_jitter_phase_count, camera->visible_layers);
  2194. } else if (view_count == 2) {
  2195. camera_data.set_multiview_camera(view_count, transforms, projections, false, false, camera->vaspect);
  2196. } else {
  2197. // this won't be called (see fail check above) but keeping this comment to indicate we may support more then 2 views in the future...
  2198. }
  2199. #endif // XR_DISABLED
  2200. }
  2201. RID environment = _render_get_environment(p_camera, p_scenario);
  2202. RID compositor = _render_get_compositor(p_camera, p_scenario);
  2203. RENDER_TIMESTAMP("Update Occlusion Buffer")
  2204. // For now just cull on the first camera
  2205. RendererSceneOcclusionCull::get_singleton()->buffer_update(p_viewport, camera_data.main_transform, camera_data.main_projection, camera_data.is_orthogonal);
  2206. _render_scene(&camera_data, p_render_buffers, environment, camera->attributes, compositor, camera->visible_layers, p_scenario, p_viewport, p_shadow_atlas, RID(), -1, p_screen_mesh_lod_threshold, true, r_render_info);
  2207. #endif
  2208. }
  2209. void RendererSceneCull::_visibility_cull_threaded(uint32_t p_thread, VisibilityCullData *cull_data) {
  2210. uint32_t total_threads = WorkerThreadPool::get_singleton()->get_thread_count();
  2211. uint32_t bin_from = p_thread * cull_data->cull_count / total_threads;
  2212. uint32_t bin_to = (p_thread + 1 == total_threads) ? cull_data->cull_count : ((p_thread + 1) * cull_data->cull_count / total_threads);
  2213. _visibility_cull(*cull_data, cull_data->cull_offset + bin_from, cull_data->cull_offset + bin_to);
  2214. }
  2215. void RendererSceneCull::_visibility_cull(const VisibilityCullData &cull_data, uint64_t p_from, uint64_t p_to) {
  2216. Scenario *scenario = cull_data.scenario;
  2217. for (unsigned int i = p_from; i < p_to; i++) {
  2218. InstanceVisibilityData &vd = scenario->instance_visibility[i];
  2219. InstanceData &idata = scenario->instance_data[vd.array_index];
  2220. if (idata.parent_array_index >= 0) {
  2221. uint32_t parent_flags = scenario->instance_data[idata.parent_array_index].flags;
  2222. if ((parent_flags & InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN) || !(parent_flags & (InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE | InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN))) {
  2223. idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN;
  2224. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE;
  2225. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
  2226. continue;
  2227. }
  2228. }
  2229. int range_check = _visibility_range_check<true>(vd, cull_data.camera_position, cull_data.viewport_mask);
  2230. if (range_check == -1) {
  2231. idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN;
  2232. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE;
  2233. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
  2234. } else if (range_check == 1) {
  2235. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN;
  2236. idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE;
  2237. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
  2238. } else {
  2239. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN;
  2240. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE;
  2241. if (range_check == 2) {
  2242. idata.flags |= InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
  2243. } else {
  2244. idata.flags &= ~InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN;
  2245. }
  2246. }
  2247. }
  2248. }
  2249. template <bool p_fade_check>
  2250. int RendererSceneCull::_visibility_range_check(InstanceVisibilityData &r_vis_data, const Vector3 &p_camera_pos, uint64_t p_viewport_mask) {
  2251. float dist = p_camera_pos.distance_to(r_vis_data.position);
  2252. const RS::VisibilityRangeFadeMode &fade_mode = r_vis_data.fade_mode;
  2253. float begin_offset = -r_vis_data.range_begin_margin;
  2254. float end_offset = r_vis_data.range_end_margin;
  2255. if (fade_mode == RS::VISIBILITY_RANGE_FADE_DISABLED && !(p_viewport_mask & r_vis_data.viewport_state)) {
  2256. begin_offset = -begin_offset;
  2257. end_offset = -end_offset;
  2258. }
  2259. if (r_vis_data.range_end > 0.0f && dist > r_vis_data.range_end + end_offset) {
  2260. r_vis_data.viewport_state &= ~p_viewport_mask;
  2261. return -1;
  2262. } else if (r_vis_data.range_begin > 0.0f && dist < r_vis_data.range_begin + begin_offset) {
  2263. r_vis_data.viewport_state &= ~p_viewport_mask;
  2264. return 1;
  2265. } else {
  2266. r_vis_data.viewport_state |= p_viewport_mask;
  2267. if (p_fade_check) {
  2268. if (fade_mode != RS::VISIBILITY_RANGE_FADE_DISABLED) {
  2269. r_vis_data.children_fade_alpha = 1.0f;
  2270. if (r_vis_data.range_end > 0.0f && dist > r_vis_data.range_end - end_offset) {
  2271. if (fade_mode == RS::VISIBILITY_RANGE_FADE_DEPENDENCIES) {
  2272. r_vis_data.children_fade_alpha = MIN(1.0f, (dist - (r_vis_data.range_end - end_offset)) / (2.0f * r_vis_data.range_end_margin));
  2273. }
  2274. return 2;
  2275. } else if (r_vis_data.range_begin > 0.0f && dist < r_vis_data.range_begin - begin_offset) {
  2276. if (fade_mode == RS::VISIBILITY_RANGE_FADE_DEPENDENCIES) {
  2277. r_vis_data.children_fade_alpha = MIN(1.0f, 1.0 - (dist - (r_vis_data.range_begin + begin_offset)) / (2.0f * r_vis_data.range_begin_margin));
  2278. }
  2279. return 2;
  2280. }
  2281. }
  2282. }
  2283. return 0;
  2284. }
  2285. }
  2286. bool RendererSceneCull::_visibility_parent_check(const CullData &p_cull_data, const InstanceData &p_instance_data) {
  2287. if (p_instance_data.parent_array_index == -1) {
  2288. return true;
  2289. }
  2290. const uint32_t &parent_flags = p_cull_data.scenario->instance_data[p_instance_data.parent_array_index].flags;
  2291. return ((parent_flags & InstanceData::FLAG_VISIBILITY_DEPENDENCY_NEEDS_CHECK) == InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE) || (parent_flags & InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN);
  2292. }
  2293. void RendererSceneCull::_scene_cull_threaded(uint32_t p_thread, CullData *cull_data) {
  2294. uint32_t cull_total = cull_data->scenario->instance_data.size();
  2295. uint32_t total_threads = WorkerThreadPool::get_singleton()->get_thread_count();
  2296. uint32_t cull_from = p_thread * cull_total / total_threads;
  2297. uint32_t cull_to = (p_thread + 1 == total_threads) ? cull_total : ((p_thread + 1) * cull_total / total_threads);
  2298. _scene_cull(*cull_data, scene_cull_result_threads[p_thread], cull_from, cull_to);
  2299. }
  2300. void RendererSceneCull::_scene_cull(CullData &cull_data, InstanceCullResult &cull_result, uint64_t p_from, uint64_t p_to) {
  2301. uint64_t frame_number = RSG::rasterizer->get_frame_number();
  2302. float lightmap_probe_update_speed = RSG::light_storage->lightmap_get_probe_capture_update_speed() * RSG::rasterizer->get_frame_delta_time();
  2303. uint32_t sdfgi_last_light_index = 0xFFFFFFFF;
  2304. uint32_t sdfgi_last_light_cascade = 0xFFFFFFFF;
  2305. RID instance_pair_buffer[MAX_INSTANCE_PAIRS];
  2306. Transform3D inv_cam_transform = cull_data.cam_transform.inverse();
  2307. float z_near = cull_data.camera_matrix->get_z_near();
  2308. bool is_orthogonal = cull_data.camera_matrix->is_orthogonal();
  2309. for (uint64_t i = p_from; i < p_to; i++) {
  2310. bool mesh_visible = false;
  2311. InstanceData &idata = cull_data.scenario->instance_data[i];
  2312. uint32_t visibility_flags = idata.flags & (InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE | InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN | InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN);
  2313. int32_t visibility_check = -1;
  2314. #define HIDDEN_BY_VISIBILITY_CHECKS (visibility_flags == InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN_CLOSE_RANGE || visibility_flags == InstanceData::FLAG_VISIBILITY_DEPENDENCY_HIDDEN)
  2315. #define LAYER_CHECK (cull_data.visible_layers & idata.layer_mask)
  2316. #define IN_FRUSTUM(f) (cull_data.scenario->instance_aabbs[i].in_frustum(f))
  2317. #define VIS_RANGE_CHECK ((idata.visibility_index == -1) || _visibility_range_check<false>(cull_data.scenario->instance_visibility[idata.visibility_index], cull_data.cam_transform.origin, cull_data.visibility_viewport_mask) == 0)
  2318. #define VIS_PARENT_CHECK (_visibility_parent_check(cull_data, idata))
  2319. #define VIS_CHECK (visibility_check < 0 ? (visibility_check = (visibility_flags != InstanceData::FLAG_VISIBILITY_DEPENDENCY_NEEDS_CHECK || (VIS_RANGE_CHECK && VIS_PARENT_CHECK))) : visibility_check)
  2320. #define OCCLUSION_CULLED (cull_data.occlusion_buffer != nullptr && (cull_data.scenario->instance_data[i].flags & InstanceData::FLAG_IGNORE_OCCLUSION_CULLING) == 0 && cull_data.occlusion_buffer->is_occluded(cull_data.scenario->instance_aabbs[i].bounds, cull_data.cam_transform.origin, inv_cam_transform, *cull_data.camera_matrix, z_near, is_orthogonal, cull_data.scenario->instance_data[i].occlusion_timeout))
  2321. if (!HIDDEN_BY_VISIBILITY_CHECKS) {
  2322. if ((LAYER_CHECK && IN_FRUSTUM(cull_data.cull->frustum) && VIS_CHECK && !OCCLUSION_CULLED) || (cull_data.scenario->instance_data[i].flags & InstanceData::FLAG_IGNORE_ALL_CULLING)) {
  2323. uint32_t base_type = idata.flags & InstanceData::FLAG_BASE_TYPE_MASK;
  2324. if (base_type == RS::INSTANCE_LIGHT) {
  2325. cull_result.lights.push_back(idata.instance);
  2326. cull_result.light_instances.push_back(RID::from_uint64(idata.instance_data_rid));
  2327. if (cull_data.shadow_atlas.is_valid() && RSG::light_storage->light_has_shadow(idata.base_rid)) {
  2328. RSG::light_storage->light_instance_mark_visible(RID::from_uint64(idata.instance_data_rid)); //mark it visible for shadow allocation later
  2329. }
  2330. } else if (base_type == RS::INSTANCE_REFLECTION_PROBE) {
  2331. if (cull_data.render_reflection_probe != idata.instance) {
  2332. //avoid entering The Matrix
  2333. if ((idata.flags & InstanceData::FLAG_REFLECTION_PROBE_DIRTY) || RSG::light_storage->reflection_probe_instance_needs_redraw(RID::from_uint64(idata.instance_data_rid))) {
  2334. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(idata.instance->base_data);
  2335. cull_data.cull->lock.lock();
  2336. if (!reflection_probe->update_list.in_list()) {
  2337. reflection_probe->render_step = 0;
  2338. reflection_probe_render_list.add_last(&reflection_probe->update_list);
  2339. }
  2340. cull_data.cull->lock.unlock();
  2341. idata.flags &= ~InstanceData::FLAG_REFLECTION_PROBE_DIRTY;
  2342. }
  2343. if (RSG::light_storage->reflection_probe_instance_has_reflection(RID::from_uint64(idata.instance_data_rid))) {
  2344. cull_result.reflections.push_back(RID::from_uint64(idata.instance_data_rid));
  2345. }
  2346. }
  2347. } else if (base_type == RS::INSTANCE_DECAL) {
  2348. cull_result.decals.push_back(RID::from_uint64(idata.instance_data_rid));
  2349. } else if (base_type == RS::INSTANCE_VOXEL_GI) {
  2350. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(idata.instance->base_data);
  2351. cull_data.cull->lock.lock();
  2352. if (!voxel_gi->update_element.in_list()) {
  2353. voxel_gi_update_list.add(&voxel_gi->update_element);
  2354. }
  2355. cull_data.cull->lock.unlock();
  2356. cull_result.voxel_gi_instances.push_back(RID::from_uint64(idata.instance_data_rid));
  2357. } else if (base_type == RS::INSTANCE_LIGHTMAP) {
  2358. cull_result.lightmaps.push_back(RID::from_uint64(idata.instance_data_rid));
  2359. } else if (base_type == RS::INSTANCE_FOG_VOLUME) {
  2360. cull_result.fog_volumes.push_back(RID::from_uint64(idata.instance_data_rid));
  2361. } else if (base_type == RS::INSTANCE_VISIBLITY_NOTIFIER) {
  2362. InstanceVisibilityNotifierData *vnd = idata.visibility_notifier;
  2363. if (!vnd->list_element.in_list()) {
  2364. visible_notifier_list_lock.lock();
  2365. visible_notifier_list.add(&vnd->list_element);
  2366. visible_notifier_list_lock.unlock();
  2367. vnd->just_visible = true;
  2368. }
  2369. vnd->visible_in_frame = RSG::rasterizer->get_frame_number();
  2370. } else if (((1 << base_type) & RS::INSTANCE_GEOMETRY_MASK) && !(idata.flags & InstanceData::FLAG_CAST_SHADOWS_ONLY)) {
  2371. bool keep = true;
  2372. if (idata.flags & InstanceData::FLAG_REDRAW_IF_VISIBLE) {
  2373. RenderingServerDefault::redraw_request();
  2374. }
  2375. if (base_type == RS::INSTANCE_MESH) {
  2376. mesh_visible = true;
  2377. } else if (base_type == RS::INSTANCE_PARTICLES) {
  2378. //particles visible? process them
  2379. if (RSG::particles_storage->particles_is_inactive(idata.base_rid)) {
  2380. //but if nothing is going on, don't do it.
  2381. keep = false;
  2382. } else {
  2383. cull_data.cull->lock.lock();
  2384. RSG::particles_storage->particles_request_process(idata.base_rid);
  2385. cull_data.cull->lock.unlock();
  2386. RS::get_singleton()->call_on_render_thread(callable_mp_static(&RendererSceneCull::_scene_particles_set_view_axis).bind(idata.base_rid, -cull_data.cam_transform.basis.get_column(2).normalized(), cull_data.cam_transform.basis.get_column(1).normalized()));
  2387. //particles visible? request redraw
  2388. RenderingServerDefault::redraw_request();
  2389. }
  2390. }
  2391. if (idata.parent_array_index != -1) {
  2392. float fade = 1.0f;
  2393. const uint32_t &parent_flags = cull_data.scenario->instance_data[idata.parent_array_index].flags;
  2394. if (parent_flags & InstanceData::FLAG_VISIBILITY_DEPENDENCY_FADE_CHILDREN) {
  2395. const int32_t &parent_idx = cull_data.scenario->instance_data[idata.parent_array_index].visibility_index;
  2396. fade = cull_data.scenario->instance_visibility[parent_idx].children_fade_alpha;
  2397. }
  2398. idata.instance_geometry->set_parent_fade_alpha(fade);
  2399. }
  2400. if (geometry_instance_pair_mask & (1 << RS::INSTANCE_LIGHT) && (idata.flags & InstanceData::FLAG_GEOM_LIGHTING_DIRTY)) {
  2401. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  2402. uint32_t idx = 0;
  2403. for (const Instance *E : geom->lights) {
  2404. InstanceLightData *light = static_cast<InstanceLightData *>(E->base_data);
  2405. if (!(RSG::light_storage->light_get_cull_mask(E->base) & idata.layer_mask)) {
  2406. continue;
  2407. }
  2408. if ((RSG::light_storage->light_get_bake_mode(E->base) == RS::LIGHT_BAKE_STATIC) && idata.instance->lightmap) {
  2409. continue;
  2410. }
  2411. instance_pair_buffer[idx++] = light->instance;
  2412. if (idx == MAX_INSTANCE_PAIRS) {
  2413. break;
  2414. }
  2415. }
  2416. ERR_FAIL_NULL(geom->geometry_instance);
  2417. geom->geometry_instance->pair_light_instances(instance_pair_buffer, idx);
  2418. idata.flags &= ~InstanceData::FLAG_GEOM_LIGHTING_DIRTY;
  2419. }
  2420. if (idata.flags & InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY) {
  2421. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  2422. ERR_FAIL_NULL(geom->geometry_instance);
  2423. cull_data.cull->lock.lock();
  2424. geom->geometry_instance->set_softshadow_projector_pairing(geom->softshadow_count > 0, geom->projector_count > 0);
  2425. cull_data.cull->lock.unlock();
  2426. idata.flags &= ~InstanceData::FLAG_GEOM_PROJECTOR_SOFTSHADOW_DIRTY;
  2427. }
  2428. if (geometry_instance_pair_mask & (1 << RS::INSTANCE_REFLECTION_PROBE) && (idata.flags & InstanceData::FLAG_GEOM_REFLECTION_DIRTY)) {
  2429. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  2430. uint32_t idx = 0;
  2431. for (const Instance *E : geom->reflection_probes) {
  2432. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(E->base_data);
  2433. instance_pair_buffer[idx++] = reflection_probe->instance;
  2434. if (idx == MAX_INSTANCE_PAIRS) {
  2435. break;
  2436. }
  2437. }
  2438. ERR_FAIL_NULL(geom->geometry_instance);
  2439. geom->geometry_instance->pair_reflection_probe_instances(instance_pair_buffer, idx);
  2440. idata.flags &= ~InstanceData::FLAG_GEOM_REFLECTION_DIRTY;
  2441. }
  2442. if (geometry_instance_pair_mask & (1 << RS::INSTANCE_DECAL) && (idata.flags & InstanceData::FLAG_GEOM_DECAL_DIRTY)) {
  2443. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  2444. uint32_t idx = 0;
  2445. for (const Instance *E : geom->decals) {
  2446. InstanceDecalData *decal = static_cast<InstanceDecalData *>(E->base_data);
  2447. instance_pair_buffer[idx++] = decal->instance;
  2448. if (idx == MAX_INSTANCE_PAIRS) {
  2449. break;
  2450. }
  2451. }
  2452. ERR_FAIL_NULL(geom->geometry_instance);
  2453. geom->geometry_instance->pair_decal_instances(instance_pair_buffer, idx);
  2454. idata.flags &= ~InstanceData::FLAG_GEOM_DECAL_DIRTY;
  2455. }
  2456. if (idata.flags & InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY) {
  2457. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  2458. uint32_t idx = 0;
  2459. for (const Instance *E : geom->voxel_gi_instances) {
  2460. InstanceVoxelGIData *voxel_gi = static_cast<InstanceVoxelGIData *>(E->base_data);
  2461. instance_pair_buffer[idx++] = voxel_gi->probe_instance;
  2462. if (idx == MAX_INSTANCE_PAIRS) {
  2463. break;
  2464. }
  2465. }
  2466. ERR_FAIL_NULL(geom->geometry_instance);
  2467. geom->geometry_instance->pair_voxel_gi_instances(instance_pair_buffer, idx);
  2468. idata.flags &= ~InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY;
  2469. }
  2470. if ((idata.flags & InstanceData::FLAG_LIGHTMAP_CAPTURE) && idata.instance->last_frame_pass != frame_number && !idata.instance->lightmap_target_sh.is_empty() && !idata.instance->lightmap_sh.is_empty()) {
  2471. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(idata.instance->base_data);
  2472. Color *sh = idata.instance->lightmap_sh.ptrw();
  2473. const Color *target_sh = idata.instance->lightmap_target_sh.ptr();
  2474. for (uint32_t j = 0; j < 9; j++) {
  2475. sh[j] = sh[j].lerp(target_sh[j], MIN(1.0, lightmap_probe_update_speed));
  2476. }
  2477. ERR_FAIL_NULL(geom->geometry_instance);
  2478. cull_data.cull->lock.lock();
  2479. geom->geometry_instance->set_lightmap_capture(sh);
  2480. cull_data.cull->lock.unlock();
  2481. idata.instance->last_frame_pass = frame_number;
  2482. }
  2483. if (keep) {
  2484. cull_result.geometry_instances.push_back(idata.instance_geometry);
  2485. }
  2486. }
  2487. }
  2488. for (uint32_t j = 0; j < cull_data.cull->shadow_count; j++) {
  2489. if (!light_culler->cull_directional_light(cull_data.scenario->instance_aabbs[i], j)) {
  2490. continue;
  2491. }
  2492. for (uint32_t k = 0; k < cull_data.cull->shadows[j].cascade_count; k++) {
  2493. if (IN_FRUSTUM(cull_data.cull->shadows[j].cascades[k].frustum) && VIS_CHECK) {
  2494. uint32_t base_type = idata.flags & InstanceData::FLAG_BASE_TYPE_MASK;
  2495. if (((1 << base_type) & RS::INSTANCE_GEOMETRY_MASK) && idata.flags & InstanceData::FLAG_CAST_SHADOWS && (LAYER_CHECK & cull_data.cull->shadows[j].caster_mask)) {
  2496. cull_result.directional_shadows[j].cascade_geometry_instances[k].push_back(idata.instance_geometry);
  2497. mesh_visible = true;
  2498. }
  2499. }
  2500. }
  2501. }
  2502. }
  2503. #undef HIDDEN_BY_VISIBILITY_CHECKS
  2504. #undef LAYER_CHECK
  2505. #undef IN_FRUSTUM
  2506. #undef VIS_RANGE_CHECK
  2507. #undef VIS_PARENT_CHECK
  2508. #undef VIS_CHECK
  2509. #undef OCCLUSION_CULLED
  2510. for (uint32_t j = 0; j < cull_data.cull->sdfgi.region_count; j++) {
  2511. if (cull_data.scenario->instance_aabbs[i].in_aabb(cull_data.cull->sdfgi.region_aabb[j])) {
  2512. uint32_t base_type = idata.flags & InstanceData::FLAG_BASE_TYPE_MASK;
  2513. if (base_type == RS::INSTANCE_LIGHT) {
  2514. InstanceLightData *instance_light = (InstanceLightData *)idata.instance->base_data;
  2515. if (instance_light->bake_mode == RS::LIGHT_BAKE_STATIC && cull_data.cull->sdfgi.region_cascade[j] <= instance_light->max_sdfgi_cascade) {
  2516. if (sdfgi_last_light_index != i || sdfgi_last_light_cascade != cull_data.cull->sdfgi.region_cascade[j]) {
  2517. sdfgi_last_light_index = i;
  2518. sdfgi_last_light_cascade = cull_data.cull->sdfgi.region_cascade[j];
  2519. cull_result.sdfgi_cascade_lights[sdfgi_last_light_cascade].push_back(instance_light->instance);
  2520. }
  2521. }
  2522. } else if ((1 << base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  2523. if (idata.flags & InstanceData::FLAG_USES_BAKED_LIGHT) {
  2524. cull_result.sdfgi_region_geometry_instances[j].push_back(idata.instance_geometry);
  2525. mesh_visible = true;
  2526. }
  2527. }
  2528. }
  2529. }
  2530. if (mesh_visible && cull_data.scenario->instance_data[i].flags & InstanceData::FLAG_USES_MESH_INSTANCE) {
  2531. cull_result.mesh_instances.push_back(cull_data.scenario->instance_data[i].instance->mesh_instance);
  2532. }
  2533. }
  2534. }
  2535. void RendererSceneCull::_scene_particles_set_view_axis(RID p_particles, const Vector3 &p_axis, const Vector3 &p_up_axis) {
  2536. RSG::particles_storage->particles_set_view_axis(p_particles, p_axis, p_up_axis);
  2537. }
  2538. void RendererSceneCull::_render_scene(const RendererSceneRender::CameraData *p_camera_data, const Ref<RenderSceneBuffers> &p_render_buffers, RID p_environment, RID p_force_camera_attributes, RID p_compositor, uint32_t p_visible_layers, RID p_scenario, RID p_viewport, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass, float p_screen_mesh_lod_threshold, bool p_using_shadows, RenderingMethod::RenderInfo *r_render_info) {
  2539. Instance *render_reflection_probe = instance_owner.get_or_null(p_reflection_probe); //if null, not rendering to it
  2540. // Prepare the light - camera volume culling system.
  2541. light_culler->prepare_camera(p_camera_data->main_transform, p_camera_data->main_projection);
  2542. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  2543. Vector3 camera_position = p_camera_data->main_transform.origin;
  2544. ERR_FAIL_COND(p_render_buffers.is_null());
  2545. render_pass++;
  2546. scene_render->set_scene_pass(render_pass);
  2547. if (p_reflection_probe.is_null()) {
  2548. //no rendering code here, this is only to set up what needs to be done, request regions, etc.
  2549. scene_render->sdfgi_update(p_render_buffers, p_environment, camera_position); //update conditions for SDFGI (whether its used or not)
  2550. }
  2551. RENDER_TIMESTAMP("Update Visibility Dependencies");
  2552. if (scenario->instance_visibility.get_bin_count() > 0) {
  2553. if (!scenario->viewport_visibility_masks.has(p_viewport)) {
  2554. scenario_add_viewport_visibility_mask(scenario->self, p_viewport);
  2555. }
  2556. VisibilityCullData visibility_cull_data;
  2557. visibility_cull_data.scenario = scenario;
  2558. visibility_cull_data.viewport_mask = scenario->viewport_visibility_masks[p_viewport];
  2559. visibility_cull_data.camera_position = camera_position;
  2560. for (int i = scenario->instance_visibility.get_bin_count() - 1; i > 0; i--) { // We skip bin 0
  2561. visibility_cull_data.cull_offset = scenario->instance_visibility.get_bin_start(i);
  2562. visibility_cull_data.cull_count = scenario->instance_visibility.get_bin_size(i);
  2563. if (visibility_cull_data.cull_count == 0) {
  2564. continue;
  2565. }
  2566. if (visibility_cull_data.cull_count > thread_cull_threshold) {
  2567. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &RendererSceneCull::_visibility_cull_threaded, &visibility_cull_data, WorkerThreadPool::get_singleton()->get_thread_count(), -1, true, SNAME("VisibilityCullInstances"));
  2568. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  2569. } else {
  2570. _visibility_cull(visibility_cull_data, visibility_cull_data.cull_offset, visibility_cull_data.cull_offset + visibility_cull_data.cull_count);
  2571. }
  2572. }
  2573. }
  2574. RENDER_TIMESTAMP("Cull 3D Scene");
  2575. //rasterizer->set_camera(p_camera_data->main_transform, p_camera_data.main_projection, p_camera_data.is_orthogonal);
  2576. /* STEP 2 - CULL */
  2577. Vector<Plane> planes = p_camera_data->main_projection.get_projection_planes(p_camera_data->main_transform);
  2578. cull.frustum = Frustum(planes);
  2579. Vector<RID> directional_lights;
  2580. // directional lights
  2581. {
  2582. cull.shadow_count = 0;
  2583. Vector<Instance *> lights_with_shadow;
  2584. for (Instance *E : scenario->directional_lights) {
  2585. if (!E->visible || !(E->layer_mask & p_visible_layers)) {
  2586. continue;
  2587. }
  2588. if (directional_lights.size() >= RendererSceneRender::MAX_DIRECTIONAL_LIGHTS) {
  2589. break;
  2590. }
  2591. InstanceLightData *light = static_cast<InstanceLightData *>(E->base_data);
  2592. //check shadow..
  2593. if (light) {
  2594. if (p_using_shadows && p_shadow_atlas.is_valid() && RSG::light_storage->light_has_shadow(E->base) && !(RSG::light_storage->light_get_type(E->base) == RS::LIGHT_DIRECTIONAL && RSG::light_storage->light_directional_get_sky_mode(E->base) == RS::LIGHT_DIRECTIONAL_SKY_MODE_SKY_ONLY)) {
  2595. lights_with_shadow.push_back(E);
  2596. }
  2597. //add to list
  2598. directional_lights.push_back(light->instance);
  2599. }
  2600. }
  2601. RSG::light_storage->set_directional_shadow_count(lights_with_shadow.size());
  2602. for (int i = 0; i < lights_with_shadow.size(); i++) {
  2603. _light_instance_setup_directional_shadow(i, lights_with_shadow[i], p_camera_data->main_transform, p_camera_data->main_projection, p_camera_data->is_orthogonal, p_camera_data->vaspect);
  2604. }
  2605. }
  2606. { //sdfgi
  2607. cull.sdfgi.region_count = 0;
  2608. if (p_reflection_probe.is_null()) {
  2609. cull.sdfgi.cascade_light_count = 0;
  2610. uint32_t prev_cascade = 0xFFFFFFFF;
  2611. uint32_t pending_region_count = scene_render->sdfgi_get_pending_region_count(p_render_buffers);
  2612. for (uint32_t i = 0; i < pending_region_count; i++) {
  2613. cull.sdfgi.region_aabb[i] = scene_render->sdfgi_get_pending_region_bounds(p_render_buffers, i);
  2614. uint32_t region_cascade = scene_render->sdfgi_get_pending_region_cascade(p_render_buffers, i);
  2615. cull.sdfgi.region_cascade[i] = region_cascade;
  2616. if (region_cascade != prev_cascade) {
  2617. cull.sdfgi.cascade_light_index[cull.sdfgi.cascade_light_count] = region_cascade;
  2618. cull.sdfgi.cascade_light_count++;
  2619. prev_cascade = region_cascade;
  2620. }
  2621. }
  2622. cull.sdfgi.region_count = pending_region_count;
  2623. }
  2624. }
  2625. scene_cull_result.clear();
  2626. {
  2627. uint64_t cull_from = 0;
  2628. uint64_t cull_to = scenario->instance_data.size();
  2629. CullData cull_data;
  2630. //prepare for eventual thread usage
  2631. cull_data.cull = &cull;
  2632. cull_data.scenario = scenario;
  2633. cull_data.shadow_atlas = p_shadow_atlas;
  2634. cull_data.cam_transform = p_camera_data->main_transform;
  2635. cull_data.visible_layers = p_visible_layers;
  2636. cull_data.render_reflection_probe = render_reflection_probe;
  2637. cull_data.occlusion_buffer = RendererSceneOcclusionCull::get_singleton()->buffer_get_ptr(p_viewport);
  2638. cull_data.camera_matrix = &p_camera_data->main_projection;
  2639. cull_data.visibility_viewport_mask = scenario->viewport_visibility_masks.has(p_viewport) ? scenario->viewport_visibility_masks[p_viewport] : 0;
  2640. //#define DEBUG_CULL_TIME
  2641. #ifdef DEBUG_CULL_TIME
  2642. uint64_t time_from = OS::get_singleton()->get_ticks_usec();
  2643. #endif
  2644. if (cull_to > thread_cull_threshold) {
  2645. //multiple threads
  2646. for (InstanceCullResult &thread : scene_cull_result_threads) {
  2647. thread.clear();
  2648. }
  2649. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &RendererSceneCull::_scene_cull_threaded, &cull_data, scene_cull_result_threads.size(), -1, true, SNAME("RenderCullInstances"));
  2650. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  2651. for (InstanceCullResult &thread : scene_cull_result_threads) {
  2652. scene_cull_result.append_from(thread);
  2653. }
  2654. } else {
  2655. //single threaded
  2656. _scene_cull(cull_data, scene_cull_result, cull_from, cull_to);
  2657. }
  2658. #ifdef DEBUG_CULL_TIME
  2659. static float time_avg = 0;
  2660. static uint32_t time_count = 0;
  2661. time_avg += double(OS::get_singleton()->get_ticks_usec() - time_from) / 1000.0;
  2662. time_count++;
  2663. print_line("time taken: " + rtos(time_avg / time_count));
  2664. #endif
  2665. if (scene_cull_result.mesh_instances.size()) {
  2666. for (uint64_t i = 0; i < scene_cull_result.mesh_instances.size(); i++) {
  2667. RSG::mesh_storage->mesh_instance_check_for_update(scene_cull_result.mesh_instances[i]);
  2668. }
  2669. RSG::mesh_storage->update_mesh_instances();
  2670. }
  2671. }
  2672. //render shadows
  2673. max_shadows_used = 0;
  2674. if (p_using_shadows) { //setup shadow maps
  2675. // Directional Shadows
  2676. for (uint32_t i = 0; i < cull.shadow_count; i++) {
  2677. for (uint32_t j = 0; j < cull.shadows[i].cascade_count; j++) {
  2678. const Cull::Shadow::Cascade &c = cull.shadows[i].cascades[j];
  2679. // print_line("shadow " + itos(i) + " cascade " + itos(j) + " elements: " + itos(c.cull_result.size()));
  2680. RSG::light_storage->light_instance_set_shadow_transform(cull.shadows[i].light_instance, c.projection, c.transform, c.zfar, c.split, j, c.shadow_texel_size, c.bias_scale, c.range_begin, c.uv_scale);
  2681. if (max_shadows_used == MAX_UPDATE_SHADOWS) {
  2682. continue;
  2683. }
  2684. render_shadow_data[max_shadows_used].light = cull.shadows[i].light_instance;
  2685. render_shadow_data[max_shadows_used].pass = j;
  2686. render_shadow_data[max_shadows_used].instances.merge_unordered(scene_cull_result.directional_shadows[i].cascade_geometry_instances[j]);
  2687. max_shadows_used++;
  2688. }
  2689. }
  2690. // Positional Shadows
  2691. for (uint32_t i = 0; i < (uint32_t)scene_cull_result.lights.size(); i++) {
  2692. Instance *ins = scene_cull_result.lights[i];
  2693. if (!p_shadow_atlas.is_valid()) {
  2694. continue;
  2695. }
  2696. InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
  2697. if (!RSG::light_storage->light_instance_is_shadow_visible_at_position(light->instance, camera_position)) {
  2698. continue;
  2699. }
  2700. float coverage = 0.f;
  2701. { //compute coverage
  2702. Transform3D cam_xf = p_camera_data->main_transform;
  2703. float zn = p_camera_data->main_projection.get_z_near();
  2704. Plane p(-cam_xf.basis.get_column(2), cam_xf.origin + cam_xf.basis.get_column(2) * -zn); //camera near plane
  2705. // near plane half width and height
  2706. Vector2 vp_half_extents = p_camera_data->main_projection.get_viewport_half_extents();
  2707. switch (RSG::light_storage->light_get_type(ins->base)) {
  2708. case RS::LIGHT_OMNI: {
  2709. float radius = RSG::light_storage->light_get_param(ins->base, RS::LIGHT_PARAM_RANGE);
  2710. //get two points parallel to near plane
  2711. Vector3 points[2] = {
  2712. ins->transform.origin,
  2713. ins->transform.origin + cam_xf.basis.get_column(0) * radius
  2714. };
  2715. if (!p_camera_data->is_orthogonal) {
  2716. //if using perspetive, map them to near plane
  2717. for (int j = 0; j < 2; j++) {
  2718. if (p.distance_to(points[j]) < 0) {
  2719. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  2720. }
  2721. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  2722. }
  2723. }
  2724. float screen_diameter = points[0].distance_to(points[1]) * 2;
  2725. coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
  2726. } break;
  2727. case RS::LIGHT_SPOT: {
  2728. float radius = RSG::light_storage->light_get_param(ins->base, RS::LIGHT_PARAM_RANGE);
  2729. float angle = RSG::light_storage->light_get_param(ins->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  2730. float w = radius * Math::sin(Math::deg_to_rad(angle));
  2731. float d = radius * Math::cos(Math::deg_to_rad(angle));
  2732. Vector3 base = ins->transform.origin - ins->transform.basis.get_column(2).normalized() * d;
  2733. Vector3 points[2] = {
  2734. base,
  2735. base + cam_xf.basis.get_column(0) * w
  2736. };
  2737. if (!p_camera_data->is_orthogonal) {
  2738. //if using perspetive, map them to near plane
  2739. for (int j = 0; j < 2; j++) {
  2740. if (p.distance_to(points[j]) < 0) {
  2741. points[j].z = -zn; //small hack to keep size constant when hitting the screen
  2742. }
  2743. p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
  2744. }
  2745. }
  2746. float screen_diameter = points[0].distance_to(points[1]) * 2;
  2747. coverage = screen_diameter / (vp_half_extents.x + vp_half_extents.y);
  2748. } break;
  2749. default: {
  2750. ERR_PRINT("Invalid Light Type");
  2751. }
  2752. }
  2753. }
  2754. // We can detect whether multiple cameras are hitting this light, whether or not the shadow is dirty,
  2755. // so that we can turn off tighter caster culling.
  2756. light->detect_light_intersects_multiple_cameras(Engine::get_singleton()->get_frames_drawn());
  2757. if (light->is_shadow_dirty()) {
  2758. // Dirty shadows have no need to be drawn if
  2759. // the light volume doesn't intersect the camera frustum.
  2760. // Returns false if the entire light can be culled.
  2761. bool allow_redraw = light_culler->prepare_regular_light(*ins);
  2762. // Directional lights aren't handled here, _light_instance_update_shadow is called from elsewhere.
  2763. // Checking for this in case this changes, as this is assumed.
  2764. DEV_CHECK_ONCE(RSG::light_storage->light_get_type(ins->base) != RS::LIGHT_DIRECTIONAL);
  2765. // Tighter caster culling to the camera frustum should work correctly with multiple viewports + cameras.
  2766. // The first camera will cull tightly, but if the light is present on more than 1 camera, the second will
  2767. // do a full render, and mark the light as non-dirty.
  2768. // There is however a cost to tighter shadow culling in this situation (2 shadow updates in 1 frame),
  2769. // so we should detect this and switch off tighter caster culling automatically.
  2770. // This is done in the logic for `decrement_shadow_dirty()`.
  2771. if (allow_redraw) {
  2772. light->last_version++;
  2773. light->decrement_shadow_dirty();
  2774. }
  2775. }
  2776. bool redraw = RSG::light_storage->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version);
  2777. if (redraw && max_shadows_used < MAX_UPDATE_SHADOWS) {
  2778. //must redraw!
  2779. RENDER_TIMESTAMP("> Render Light3D " + itos(i));
  2780. if (_light_instance_update_shadow(ins, p_camera_data->main_transform, p_camera_data->main_projection, p_camera_data->is_orthogonal, p_camera_data->vaspect, p_shadow_atlas, scenario, p_screen_mesh_lod_threshold, p_visible_layers)) {
  2781. light->make_shadow_dirty();
  2782. }
  2783. RENDER_TIMESTAMP("< Render Light3D " + itos(i));
  2784. } else {
  2785. if (redraw) {
  2786. light->make_shadow_dirty();
  2787. }
  2788. }
  2789. }
  2790. }
  2791. //render SDFGI
  2792. {
  2793. // Q: Should this whole block be skipped if we're rendering our reflection probe?
  2794. sdfgi_update_data.update_static = false;
  2795. if (cull.sdfgi.region_count > 0) {
  2796. //update regions
  2797. for (uint32_t i = 0; i < cull.sdfgi.region_count; i++) {
  2798. render_sdfgi_data[i].instances.merge_unordered(scene_cull_result.sdfgi_region_geometry_instances[i]);
  2799. render_sdfgi_data[i].region = i;
  2800. }
  2801. //check if static lights were culled
  2802. bool static_lights_culled = false;
  2803. for (uint32_t i = 0; i < cull.sdfgi.cascade_light_count; i++) {
  2804. if (scene_cull_result.sdfgi_cascade_lights[i].size()) {
  2805. static_lights_culled = true;
  2806. break;
  2807. }
  2808. }
  2809. if (static_lights_culled) {
  2810. sdfgi_update_data.static_cascade_count = cull.sdfgi.cascade_light_count;
  2811. sdfgi_update_data.static_cascade_indices = cull.sdfgi.cascade_light_index;
  2812. sdfgi_update_data.static_positional_lights = scene_cull_result.sdfgi_cascade_lights;
  2813. sdfgi_update_data.update_static = true;
  2814. }
  2815. }
  2816. if (p_reflection_probe.is_null()) {
  2817. sdfgi_update_data.directional_lights = &directional_lights;
  2818. sdfgi_update_data.positional_light_instances = scenario->dynamic_lights.ptr();
  2819. sdfgi_update_data.positional_light_count = scenario->dynamic_lights.size();
  2820. }
  2821. }
  2822. //append the directional lights to the lights culled
  2823. for (int i = 0; i < directional_lights.size(); i++) {
  2824. scene_cull_result.light_instances.push_back(directional_lights[i]);
  2825. }
  2826. RID camera_attributes;
  2827. if (p_force_camera_attributes.is_valid()) {
  2828. camera_attributes = p_force_camera_attributes;
  2829. } else {
  2830. camera_attributes = scenario->camera_attributes;
  2831. }
  2832. /* PROCESS GEOMETRY AND DRAW SCENE */
  2833. RID occluders_tex;
  2834. const RendererSceneRender::CameraData *prev_camera_data = p_camera_data;
  2835. if (p_viewport.is_valid()) {
  2836. occluders_tex = RSG::viewport->viewport_get_occluder_debug_texture(p_viewport);
  2837. prev_camera_data = RSG::viewport->viewport_get_prev_camera_data(p_viewport);
  2838. }
  2839. RENDER_TIMESTAMP("Render 3D Scene");
  2840. scene_render->render_scene(p_render_buffers, p_camera_data, prev_camera_data, scene_cull_result.geometry_instances, scene_cull_result.light_instances, scene_cull_result.reflections, scene_cull_result.voxel_gi_instances, scene_cull_result.decals, scene_cull_result.lightmaps, scene_cull_result.fog_volumes, p_environment, camera_attributes, p_compositor, p_shadow_atlas, occluders_tex, p_reflection_probe.is_valid() ? RID() : scenario->reflection_atlas, p_reflection_probe, p_reflection_probe_pass, p_screen_mesh_lod_threshold, render_shadow_data, max_shadows_used, render_sdfgi_data, cull.sdfgi.region_count, &sdfgi_update_data, r_render_info);
  2841. if (p_viewport.is_valid()) {
  2842. RSG::viewport->viewport_set_prev_camera_data(p_viewport, p_camera_data);
  2843. }
  2844. for (uint32_t i = 0; i < max_shadows_used; i++) {
  2845. render_shadow_data[i].instances.clear();
  2846. }
  2847. max_shadows_used = 0;
  2848. for (uint32_t i = 0; i < cull.sdfgi.region_count; i++) {
  2849. render_sdfgi_data[i].instances.clear();
  2850. }
  2851. }
  2852. RID RendererSceneCull::_render_get_environment(RID p_camera, RID p_scenario) {
  2853. Camera *camera = camera_owner.get_or_null(p_camera);
  2854. if (camera && scene_render->is_environment(camera->env)) {
  2855. return camera->env;
  2856. }
  2857. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  2858. if (!scenario) {
  2859. return RID();
  2860. }
  2861. if (scene_render->is_environment(scenario->environment)) {
  2862. return scenario->environment;
  2863. }
  2864. if (scene_render->is_environment(scenario->fallback_environment)) {
  2865. return scenario->fallback_environment;
  2866. }
  2867. return RID();
  2868. }
  2869. RID RendererSceneCull::_render_get_compositor(RID p_camera, RID p_scenario) {
  2870. Camera *camera = camera_owner.get_or_null(p_camera);
  2871. if (camera && scene_render->is_compositor(camera->compositor)) {
  2872. return camera->compositor;
  2873. }
  2874. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  2875. if (scenario && scene_render->is_compositor(scenario->compositor)) {
  2876. return scenario->compositor;
  2877. }
  2878. return RID();
  2879. }
  2880. void RendererSceneCull::render_empty_scene(const Ref<RenderSceneBuffers> &p_render_buffers, RID p_scenario, RID p_shadow_atlas) {
  2881. #ifndef _3D_DISABLED
  2882. Scenario *scenario = scenario_owner.get_or_null(p_scenario);
  2883. RID environment;
  2884. if (scenario->environment.is_valid()) {
  2885. environment = scenario->environment;
  2886. } else {
  2887. environment = scenario->fallback_environment;
  2888. }
  2889. RID compositor = scenario->compositor;
  2890. RENDER_TIMESTAMP("Render Empty 3D Scene");
  2891. RendererSceneRender::CameraData camera_data;
  2892. camera_data.set_camera(Transform3D(), Projection(), true, false, false);
  2893. scene_render->render_scene(p_render_buffers, &camera_data, &camera_data, PagedArray<RenderGeometryInstance *>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), PagedArray<RID>(), environment, RID(), compositor, p_shadow_atlas, RID(), scenario->reflection_atlas, RID(), 0, 0, nullptr, 0, nullptr, 0, nullptr);
  2894. #endif
  2895. }
  2896. bool RendererSceneCull::_render_reflection_probe_step(Instance *p_instance, int p_step) {
  2897. InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
  2898. Scenario *scenario = p_instance->scenario;
  2899. ERR_FAIL_NULL_V(scenario, true);
  2900. RenderingServerDefault::redraw_request(); //update, so it updates in editor
  2901. if (p_step == 0) {
  2902. if (!RSG::light_storage->reflection_probe_instance_begin_render(reflection_probe->instance, scenario->reflection_atlas)) {
  2903. return true; // All full, no atlas entry to render to.
  2904. }
  2905. } else if (!RSG::light_storage->reflection_probe_has_atlas_index(reflection_probe->instance)) {
  2906. // We don't have an atlas to render to, just round off.
  2907. // This is likely due to the atlas being reset.
  2908. // If so the probe will be marked as dirty and start over.
  2909. return true;
  2910. }
  2911. if (p_step >= 0 && p_step < 6) {
  2912. static const Vector3 view_normals[6] = {
  2913. Vector3(+1, 0, 0),
  2914. Vector3(-1, 0, 0),
  2915. Vector3(0, +1, 0),
  2916. Vector3(0, -1, 0),
  2917. Vector3(0, 0, +1),
  2918. Vector3(0, 0, -1)
  2919. };
  2920. static const Vector3 view_up[6] = {
  2921. Vector3(0, -1, 0),
  2922. Vector3(0, -1, 0),
  2923. Vector3(0, 0, +1),
  2924. Vector3(0, 0, -1),
  2925. Vector3(0, -1, 0),
  2926. Vector3(0, -1, 0)
  2927. };
  2928. Vector3 probe_size = RSG::light_storage->reflection_probe_get_size(p_instance->base);
  2929. Vector3 origin_offset = RSG::light_storage->reflection_probe_get_origin_offset(p_instance->base);
  2930. float max_distance = RSG::light_storage->reflection_probe_get_origin_max_distance(p_instance->base);
  2931. float atlas_size = RSG::light_storage->reflection_atlas_get_size(scenario->reflection_atlas);
  2932. float mesh_lod_threshold = RSG::light_storage->reflection_probe_get_mesh_lod_threshold(p_instance->base) / atlas_size;
  2933. Vector3 edge = view_normals[p_step] * probe_size / 2;
  2934. float distance = Math::abs(view_normals[p_step].dot(edge) - view_normals[p_step].dot(origin_offset)); //distance from origin offset to actual view distance limit
  2935. max_distance = MAX(max_distance, distance);
  2936. //render cubemap side
  2937. Projection cm;
  2938. cm.set_perspective(90, 1, 0.01, max_distance);
  2939. Transform3D local_view;
  2940. local_view.set_look_at(origin_offset, origin_offset + view_normals[p_step], view_up[p_step]);
  2941. Transform3D xform = p_instance->transform * local_view;
  2942. RID shadow_atlas;
  2943. bool use_shadows = RSG::light_storage->reflection_probe_renders_shadows(p_instance->base);
  2944. if (use_shadows) {
  2945. shadow_atlas = scenario->reflection_probe_shadow_atlas;
  2946. }
  2947. RID environment;
  2948. if (scenario->environment.is_valid()) {
  2949. environment = scenario->environment;
  2950. } else {
  2951. environment = scenario->fallback_environment;
  2952. }
  2953. RENDER_TIMESTAMP("Render ReflectionProbe, Step " + itos(p_step));
  2954. RendererSceneRender::CameraData camera_data;
  2955. camera_data.set_camera(xform, cm, false, false, false);
  2956. Ref<RenderSceneBuffers> render_buffers = RSG::light_storage->reflection_probe_atlas_get_render_buffers(scenario->reflection_atlas);
  2957. _render_scene(&camera_data, render_buffers, environment, RID(), RID(), RSG::light_storage->reflection_probe_get_cull_mask(p_instance->base), p_instance->scenario->self, RID(), shadow_atlas, reflection_probe->instance, p_step, mesh_lod_threshold, use_shadows);
  2958. } else {
  2959. //do roughness postprocess step until it believes it's done
  2960. RENDER_TIMESTAMP("Post-Process ReflectionProbe, Step " + itos(p_step));
  2961. return RSG::light_storage->reflection_probe_instance_postprocess_step(reflection_probe->instance);
  2962. }
  2963. return false;
  2964. }
  2965. void RendererSceneCull::render_probes() {
  2966. /* REFLECTION PROBES */
  2967. SelfList<InstanceReflectionProbeData> *ref_probe = reflection_probe_render_list.first();
  2968. Vector<SelfList<InstanceReflectionProbeData> *> done_list;
  2969. bool busy = false;
  2970. if (ref_probe) {
  2971. RENDER_TIMESTAMP("Render ReflectionProbes");
  2972. while (ref_probe) {
  2973. SelfList<InstanceReflectionProbeData> *next = ref_probe->next();
  2974. RID base = ref_probe->self()->owner->base;
  2975. switch (RSG::light_storage->reflection_probe_get_update_mode(base)) {
  2976. case RS::REFLECTION_PROBE_UPDATE_ONCE: {
  2977. if (busy) { // Already rendering something.
  2978. break;
  2979. }
  2980. bool done = _render_reflection_probe_step(ref_probe->self()->owner, ref_probe->self()->render_step);
  2981. if (done) {
  2982. done_list.push_back(ref_probe);
  2983. } else {
  2984. ref_probe->self()->render_step++;
  2985. }
  2986. busy = true; // Do not render another one of this kind.
  2987. } break;
  2988. case RS::REFLECTION_PROBE_UPDATE_ALWAYS: {
  2989. int step = 0;
  2990. bool done = false;
  2991. while (!done) {
  2992. done = _render_reflection_probe_step(ref_probe->self()->owner, step);
  2993. step++;
  2994. }
  2995. done_list.push_back(ref_probe);
  2996. } break;
  2997. }
  2998. ref_probe = next;
  2999. }
  3000. // Now remove from our list
  3001. for (SelfList<InstanceReflectionProbeData> *rp : done_list) {
  3002. reflection_probe_render_list.remove(rp);
  3003. }
  3004. }
  3005. /* VOXEL GIS */
  3006. SelfList<InstanceVoxelGIData> *voxel_gi = voxel_gi_update_list.first();
  3007. if (voxel_gi) {
  3008. RENDER_TIMESTAMP("Render VoxelGI");
  3009. }
  3010. while (voxel_gi) {
  3011. SelfList<InstanceVoxelGIData> *next = voxel_gi->next();
  3012. InstanceVoxelGIData *probe = voxel_gi->self();
  3013. //Instance *instance_probe = probe->owner;
  3014. //check if probe must be setup, but don't do if on the lighting thread
  3015. bool cache_dirty = false;
  3016. int cache_count = 0;
  3017. {
  3018. int light_cache_size = probe->light_cache.size();
  3019. const InstanceVoxelGIData::LightCache *caches = probe->light_cache.ptr();
  3020. const RID *instance_caches = probe->light_instances.ptr();
  3021. int idx = 0; //must count visible lights
  3022. for (Instance *E : probe->lights) {
  3023. Instance *instance = E;
  3024. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  3025. if (!instance->visible) {
  3026. continue;
  3027. }
  3028. if (cache_dirty) {
  3029. //do nothing, since idx must count all visible lights anyway
  3030. } else if (idx >= light_cache_size) {
  3031. cache_dirty = true;
  3032. } else {
  3033. const InstanceVoxelGIData::LightCache *cache = &caches[idx];
  3034. if (
  3035. instance_caches[idx] != instance_light->instance ||
  3036. cache->has_shadow != RSG::light_storage->light_has_shadow(instance->base) ||
  3037. cache->type != RSG::light_storage->light_get_type(instance->base) ||
  3038. cache->transform != instance->transform ||
  3039. cache->color != RSG::light_storage->light_get_color(instance->base) ||
  3040. cache->energy != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY) ||
  3041. cache->intensity != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INTENSITY) ||
  3042. cache->bake_energy != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY) ||
  3043. cache->radius != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE) ||
  3044. cache->attenuation != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION) ||
  3045. cache->spot_angle != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE) ||
  3046. cache->spot_attenuation != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION)) {
  3047. cache_dirty = true;
  3048. }
  3049. }
  3050. idx++;
  3051. }
  3052. for (const Instance *instance : probe->owner->scenario->directional_lights) {
  3053. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  3054. if (!instance->visible) {
  3055. continue;
  3056. }
  3057. if (cache_dirty) {
  3058. //do nothing, since idx must count all visible lights anyway
  3059. } else if (idx >= light_cache_size) {
  3060. cache_dirty = true;
  3061. } else {
  3062. const InstanceVoxelGIData::LightCache *cache = &caches[idx];
  3063. if (
  3064. instance_caches[idx] != instance_light->instance ||
  3065. cache->has_shadow != RSG::light_storage->light_has_shadow(instance->base) ||
  3066. cache->type != RSG::light_storage->light_get_type(instance->base) ||
  3067. cache->transform != instance->transform ||
  3068. cache->color != RSG::light_storage->light_get_color(instance->base) ||
  3069. cache->energy != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY) ||
  3070. cache->intensity != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INTENSITY) ||
  3071. cache->bake_energy != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY) ||
  3072. cache->radius != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE) ||
  3073. cache->attenuation != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION) ||
  3074. cache->spot_angle != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE) ||
  3075. cache->spot_attenuation != RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION) ||
  3076. cache->sky_mode != RSG::light_storage->light_directional_get_sky_mode(instance->base)) {
  3077. cache_dirty = true;
  3078. }
  3079. }
  3080. idx++;
  3081. }
  3082. if (idx != light_cache_size) {
  3083. cache_dirty = true;
  3084. }
  3085. cache_count = idx;
  3086. }
  3087. bool update_lights = scene_render->voxel_gi_needs_update(probe->probe_instance);
  3088. if (cache_dirty) {
  3089. probe->light_cache.resize(cache_count);
  3090. probe->light_instances.resize(cache_count);
  3091. if (cache_count) {
  3092. InstanceVoxelGIData::LightCache *caches = probe->light_cache.ptrw();
  3093. RID *instance_caches = probe->light_instances.ptrw();
  3094. int idx = 0; //must count visible lights
  3095. for (Instance *E : probe->lights) {
  3096. Instance *instance = E;
  3097. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  3098. if (!instance->visible) {
  3099. continue;
  3100. }
  3101. InstanceVoxelGIData::LightCache *cache = &caches[idx];
  3102. instance_caches[idx] = instance_light->instance;
  3103. cache->has_shadow = RSG::light_storage->light_has_shadow(instance->base);
  3104. cache->type = RSG::light_storage->light_get_type(instance->base);
  3105. cache->transform = instance->transform;
  3106. cache->color = RSG::light_storage->light_get_color(instance->base);
  3107. cache->energy = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY);
  3108. cache->intensity = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INTENSITY);
  3109. cache->bake_energy = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY);
  3110. cache->radius = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE);
  3111. cache->attenuation = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION);
  3112. cache->spot_angle = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  3113. cache->spot_attenuation = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  3114. idx++;
  3115. }
  3116. for (const Instance *instance : probe->owner->scenario->directional_lights) {
  3117. InstanceLightData *instance_light = (InstanceLightData *)instance->base_data;
  3118. if (!instance->visible) {
  3119. continue;
  3120. }
  3121. InstanceVoxelGIData::LightCache *cache = &caches[idx];
  3122. instance_caches[idx] = instance_light->instance;
  3123. cache->has_shadow = RSG::light_storage->light_has_shadow(instance->base);
  3124. cache->type = RSG::light_storage->light_get_type(instance->base);
  3125. cache->transform = instance->transform;
  3126. cache->color = RSG::light_storage->light_get_color(instance->base);
  3127. cache->energy = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ENERGY);
  3128. cache->intensity = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INTENSITY);
  3129. cache->bake_energy = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_INDIRECT_ENERGY);
  3130. cache->radius = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_RANGE);
  3131. cache->attenuation = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_ATTENUATION);
  3132. cache->spot_angle = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ANGLE);
  3133. cache->spot_attenuation = RSG::light_storage->light_get_param(instance->base, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  3134. cache->sky_mode = RSG::light_storage->light_directional_get_sky_mode(instance->base);
  3135. idx++;
  3136. }
  3137. }
  3138. update_lights = true;
  3139. }
  3140. scene_cull_result.geometry_instances.clear();
  3141. RID instance_pair_buffer[MAX_INSTANCE_PAIRS];
  3142. for (Instance *E : probe->dynamic_geometries) {
  3143. Instance *ins = E;
  3144. if (!ins->visible) {
  3145. continue;
  3146. }
  3147. InstanceGeometryData *geom = (InstanceGeometryData *)ins->base_data;
  3148. if (ins->scenario && ins->array_index >= 0 && (ins->scenario->instance_data[ins->array_index].flags & InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY)) {
  3149. uint32_t idx = 0;
  3150. for (const Instance *F : geom->voxel_gi_instances) {
  3151. InstanceVoxelGIData *voxel_gi2 = static_cast<InstanceVoxelGIData *>(F->base_data);
  3152. instance_pair_buffer[idx++] = voxel_gi2->probe_instance;
  3153. if (idx == MAX_INSTANCE_PAIRS) {
  3154. break;
  3155. }
  3156. }
  3157. ERR_FAIL_NULL(geom->geometry_instance);
  3158. geom->geometry_instance->pair_voxel_gi_instances(instance_pair_buffer, idx);
  3159. ins->scenario->instance_data[ins->array_index].flags &= ~InstanceData::FLAG_GEOM_VOXEL_GI_DIRTY;
  3160. }
  3161. ERR_FAIL_NULL(geom->geometry_instance);
  3162. scene_cull_result.geometry_instances.push_back(geom->geometry_instance);
  3163. }
  3164. scene_render->voxel_gi_update(probe->probe_instance, update_lights, probe->light_instances, scene_cull_result.geometry_instances);
  3165. voxel_gi_update_list.remove(voxel_gi);
  3166. voxel_gi = next;
  3167. }
  3168. }
  3169. void RendererSceneCull::render_particle_colliders() {
  3170. while (heightfield_particle_colliders_update_list.begin()) {
  3171. Instance *hfpc = *heightfield_particle_colliders_update_list.begin();
  3172. if (hfpc->scenario && hfpc->base_type == RS::INSTANCE_PARTICLES_COLLISION && RSG::particles_storage->particles_collision_is_heightfield(hfpc->base)) {
  3173. //update heightfield
  3174. instance_cull_result.clear();
  3175. scene_cull_result.geometry_instances.clear();
  3176. struct CullAABB {
  3177. PagedArray<Instance *> *result;
  3178. uint32_t heightfield_mask;
  3179. _FORCE_INLINE_ bool operator()(void *p_data) {
  3180. Instance *p_instance = (Instance *)p_data;
  3181. if (p_instance->layer_mask & heightfield_mask) {
  3182. result->push_back(p_instance);
  3183. }
  3184. return false;
  3185. }
  3186. };
  3187. CullAABB cull_aabb;
  3188. cull_aabb.result = &instance_cull_result;
  3189. cull_aabb.heightfield_mask = RSG::particles_storage->particles_collision_get_height_field_mask(hfpc->base);
  3190. hfpc->scenario->indexers[Scenario::INDEXER_GEOMETRY].aabb_query(hfpc->transformed_aabb, cull_aabb);
  3191. hfpc->scenario->indexers[Scenario::INDEXER_VOLUMES].aabb_query(hfpc->transformed_aabb, cull_aabb);
  3192. for (int i = 0; i < (int)instance_cull_result.size(); i++) {
  3193. Instance *instance = instance_cull_result[i];
  3194. if (!instance || !((1 << instance->base_type) & (RS::INSTANCE_GEOMETRY_MASK & (~(1 << RS::INSTANCE_PARTICLES))))) { //all but particles to avoid self collision
  3195. continue;
  3196. }
  3197. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(instance->base_data);
  3198. ERR_FAIL_NULL(geom->geometry_instance);
  3199. scene_cull_result.geometry_instances.push_back(geom->geometry_instance);
  3200. }
  3201. scene_render->render_particle_collider_heightfield(hfpc->base, hfpc->transform, scene_cull_result.geometry_instances);
  3202. }
  3203. heightfield_particle_colliders_update_list.remove(heightfield_particle_colliders_update_list.begin());
  3204. }
  3205. }
  3206. void RendererSceneCull::_update_dirty_instance(Instance *p_instance) const {
  3207. if (p_instance->update_aabb) {
  3208. _update_instance_aabb(p_instance);
  3209. }
  3210. if (p_instance->update_dependencies) {
  3211. p_instance->dependency_tracker.update_begin();
  3212. if (p_instance->base.is_valid()) {
  3213. RSG::utilities->base_update_dependency(p_instance->base, &p_instance->dependency_tracker);
  3214. }
  3215. if (p_instance->material_override.is_valid()) {
  3216. RSG::material_storage->material_update_dependency(p_instance->material_override, &p_instance->dependency_tracker);
  3217. }
  3218. if (p_instance->material_overlay.is_valid()) {
  3219. RSG::material_storage->material_update_dependency(p_instance->material_overlay, &p_instance->dependency_tracker);
  3220. }
  3221. if (p_instance->base_type == RS::INSTANCE_MESH) {
  3222. //remove materials no longer used and un-own them
  3223. int new_mat_count = RSG::mesh_storage->mesh_get_surface_count(p_instance->base);
  3224. p_instance->materials.resize(new_mat_count);
  3225. _instance_update_mesh_instance(p_instance);
  3226. }
  3227. if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
  3228. // update the process material dependency
  3229. RID particle_material = RSG::particles_storage->particles_get_process_material(p_instance->base);
  3230. if (particle_material.is_valid()) {
  3231. RSG::material_storage->material_update_dependency(particle_material, &p_instance->dependency_tracker);
  3232. }
  3233. }
  3234. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  3235. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  3236. bool can_cast_shadows = true;
  3237. bool is_animated = false;
  3238. p_instance->instance_uniforms.materials_start();
  3239. if (p_instance->cast_shadows == RS::SHADOW_CASTING_SETTING_OFF) {
  3240. can_cast_shadows = false;
  3241. }
  3242. if (p_instance->material_override.is_valid()) {
  3243. if (!RSG::material_storage->material_casts_shadows(p_instance->material_override)) {
  3244. can_cast_shadows = false;
  3245. }
  3246. is_animated = RSG::material_storage->material_is_animated(p_instance->material_override);
  3247. p_instance->instance_uniforms.materials_append(p_instance->material_override);
  3248. } else {
  3249. if (p_instance->base_type == RS::INSTANCE_MESH) {
  3250. RID mesh = p_instance->base;
  3251. if (mesh.is_valid()) {
  3252. bool cast_shadows = false;
  3253. for (int i = 0; i < p_instance->materials.size(); i++) {
  3254. RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : RSG::mesh_storage->mesh_surface_get_material(mesh, i);
  3255. if (!mat.is_valid()) {
  3256. cast_shadows = true;
  3257. } else {
  3258. if (RSG::material_storage->material_casts_shadows(mat)) {
  3259. cast_shadows = true;
  3260. }
  3261. if (RSG::material_storage->material_is_animated(mat)) {
  3262. is_animated = true;
  3263. }
  3264. p_instance->instance_uniforms.materials_append(mat);
  3265. RSG::material_storage->material_update_dependency(mat, &p_instance->dependency_tracker);
  3266. }
  3267. }
  3268. if (!cast_shadows) {
  3269. can_cast_shadows = false;
  3270. }
  3271. }
  3272. } else if (p_instance->base_type == RS::INSTANCE_MULTIMESH) {
  3273. RID mesh = RSG::mesh_storage->multimesh_get_mesh(p_instance->base);
  3274. if (mesh.is_valid()) {
  3275. bool cast_shadows = false;
  3276. int sc = RSG::mesh_storage->mesh_get_surface_count(mesh);
  3277. for (int i = 0; i < sc; i++) {
  3278. RID mat = RSG::mesh_storage->mesh_surface_get_material(mesh, i);
  3279. if (!mat.is_valid()) {
  3280. cast_shadows = true;
  3281. } else {
  3282. if (RSG::material_storage->material_casts_shadows(mat)) {
  3283. cast_shadows = true;
  3284. }
  3285. if (RSG::material_storage->material_is_animated(mat)) {
  3286. is_animated = true;
  3287. }
  3288. p_instance->instance_uniforms.materials_append(mat);
  3289. RSG::material_storage->material_update_dependency(mat, &p_instance->dependency_tracker);
  3290. }
  3291. }
  3292. if (!cast_shadows) {
  3293. can_cast_shadows = false;
  3294. }
  3295. RSG::utilities->base_update_dependency(mesh, &p_instance->dependency_tracker);
  3296. }
  3297. } else if (p_instance->base_type == RS::INSTANCE_PARTICLES) {
  3298. bool cast_shadows = false;
  3299. int dp = RSG::particles_storage->particles_get_draw_passes(p_instance->base);
  3300. for (int i = 0; i < dp; i++) {
  3301. RID mesh = RSG::particles_storage->particles_get_draw_pass_mesh(p_instance->base, i);
  3302. if (!mesh.is_valid()) {
  3303. continue;
  3304. }
  3305. int sc = RSG::mesh_storage->mesh_get_surface_count(mesh);
  3306. for (int j = 0; j < sc; j++) {
  3307. RID mat = RSG::mesh_storage->mesh_surface_get_material(mesh, j);
  3308. if (!mat.is_valid()) {
  3309. cast_shadows = true;
  3310. } else {
  3311. if (RSG::material_storage->material_casts_shadows(mat)) {
  3312. cast_shadows = true;
  3313. }
  3314. if (RSG::material_storage->material_is_animated(mat)) {
  3315. is_animated = true;
  3316. }
  3317. p_instance->instance_uniforms.materials_append(mat);
  3318. RSG::material_storage->material_update_dependency(mat, &p_instance->dependency_tracker);
  3319. }
  3320. }
  3321. }
  3322. if (!cast_shadows) {
  3323. can_cast_shadows = false;
  3324. }
  3325. }
  3326. }
  3327. if (p_instance->material_overlay.is_valid()) {
  3328. can_cast_shadows = can_cast_shadows && RSG::material_storage->material_casts_shadows(p_instance->material_overlay);
  3329. is_animated = is_animated || RSG::material_storage->material_is_animated(p_instance->material_overlay);
  3330. p_instance->instance_uniforms.materials_append(p_instance->material_overlay);
  3331. }
  3332. if (can_cast_shadows != geom->can_cast_shadows) {
  3333. //ability to cast shadows change, let lights now
  3334. for (const Instance *E : geom->lights) {
  3335. InstanceLightData *light = static_cast<InstanceLightData *>(E->base_data);
  3336. light->make_shadow_dirty();
  3337. }
  3338. geom->can_cast_shadows = can_cast_shadows;
  3339. }
  3340. geom->material_is_animated = is_animated;
  3341. if (p_instance->instance_uniforms.materials_finish(p_instance->self)) {
  3342. geom->geometry_instance->set_instance_shader_uniforms_offset(p_instance->instance_uniforms.location());
  3343. }
  3344. }
  3345. if (p_instance->skeleton.is_valid()) {
  3346. RSG::mesh_storage->skeleton_update_dependency(p_instance->skeleton, &p_instance->dependency_tracker);
  3347. }
  3348. p_instance->dependency_tracker.update_end();
  3349. if ((1 << p_instance->base_type) & RS::INSTANCE_GEOMETRY_MASK) {
  3350. InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
  3351. ERR_FAIL_NULL(geom->geometry_instance);
  3352. geom->geometry_instance->set_surface_materials(p_instance->materials);
  3353. }
  3354. }
  3355. _instance_update_list.remove(&p_instance->update_item);
  3356. _update_instance(p_instance);
  3357. p_instance->teleported = false;
  3358. p_instance->update_aabb = false;
  3359. p_instance->update_dependencies = false;
  3360. }
  3361. void RendererSceneCull::update_dirty_instances() const {
  3362. while (_instance_update_list.first()) {
  3363. _update_dirty_instance(_instance_update_list.first()->self());
  3364. }
  3365. // Update dirty resources after dirty instances as instance updates may affect resources.
  3366. RSG::utilities->update_dirty_resources();
  3367. }
  3368. void RendererSceneCull::update() {
  3369. //optimize bvhs
  3370. uint32_t rid_count = scenario_owner.get_rid_count();
  3371. RID *rids = (RID *)alloca(sizeof(RID) * rid_count);
  3372. scenario_owner.fill_owned_buffer(rids);
  3373. for (uint32_t i = 0; i < rid_count; i++) {
  3374. Scenario *s = scenario_owner.get_or_null(rids[i]);
  3375. s->indexers[Scenario::INDEXER_GEOMETRY].optimize_incremental(indexer_update_iterations);
  3376. s->indexers[Scenario::INDEXER_VOLUMES].optimize_incremental(indexer_update_iterations);
  3377. }
  3378. scene_render->update();
  3379. update_dirty_instances();
  3380. render_particle_colliders();
  3381. }
  3382. bool RendererSceneCull::free(RID p_rid) {
  3383. if (p_rid.is_null()) {
  3384. return true;
  3385. }
  3386. if (scene_render->free(p_rid)) {
  3387. return true;
  3388. }
  3389. if (camera_owner.owns(p_rid)) {
  3390. camera_owner.free(p_rid);
  3391. } else if (scenario_owner.owns(p_rid)) {
  3392. Scenario *scenario = scenario_owner.get_or_null(p_rid);
  3393. while (scenario->instances.first()) {
  3394. instance_set_scenario(scenario->instances.first()->self()->self, RID());
  3395. }
  3396. scenario->instance_aabbs.reset();
  3397. scenario->instance_data.reset();
  3398. scenario->instance_visibility.reset();
  3399. RSG::light_storage->shadow_atlas_free(scenario->reflection_probe_shadow_atlas);
  3400. RSG::light_storage->reflection_atlas_free(scenario->reflection_atlas);
  3401. scenario_owner.free(p_rid);
  3402. RendererSceneOcclusionCull::get_singleton()->remove_scenario(p_rid);
  3403. } else if (RendererSceneOcclusionCull::get_singleton() && RendererSceneOcclusionCull::get_singleton()->is_occluder(p_rid)) {
  3404. RendererSceneOcclusionCull::get_singleton()->free_occluder(p_rid);
  3405. } else if (instance_owner.owns(p_rid)) {
  3406. // delete the instance
  3407. update_dirty_instances();
  3408. Instance *instance = instance_owner.get_or_null(p_rid);
  3409. instance_geometry_set_lightmap(p_rid, RID(), Rect2(), 0);
  3410. instance_set_scenario(p_rid, RID());
  3411. instance_set_base(p_rid, RID());
  3412. instance_geometry_set_material_override(p_rid, RID());
  3413. instance_geometry_set_material_overlay(p_rid, RID());
  3414. instance_attach_skeleton(p_rid, RID());
  3415. instance->instance_uniforms.free(instance->self);
  3416. update_dirty_instances(); //in case something changed this
  3417. instance_owner.free(p_rid);
  3418. } else {
  3419. return false;
  3420. }
  3421. return true;
  3422. }
  3423. TypedArray<Image> RendererSceneCull::bake_render_uv2(RID p_base, const TypedArray<RID> &p_material_overrides, const Size2i &p_image_size) {
  3424. return scene_render->bake_render_uv2(p_base, p_material_overrides, p_image_size);
  3425. }
  3426. void RendererSceneCull::update_visibility_notifiers() {
  3427. SelfList<InstanceVisibilityNotifierData> *E = visible_notifier_list.first();
  3428. while (E) {
  3429. SelfList<InstanceVisibilityNotifierData> *N = E->next();
  3430. InstanceVisibilityNotifierData *visibility_notifier = E->self();
  3431. if (visibility_notifier->just_visible) {
  3432. visibility_notifier->just_visible = false;
  3433. RSG::utilities->visibility_notifier_call(visibility_notifier->base, true, RSG::threaded);
  3434. } else {
  3435. if (visibility_notifier->visible_in_frame != RSG::rasterizer->get_frame_number()) {
  3436. visible_notifier_list.remove(E);
  3437. RSG::utilities->visibility_notifier_call(visibility_notifier->base, false, RSG::threaded);
  3438. }
  3439. }
  3440. E = N;
  3441. }
  3442. }
  3443. /*******************************/
  3444. /* Passthrough to Scene Render */
  3445. /*******************************/
  3446. /* ENVIRONMENT API */
  3447. RendererSceneCull *RendererSceneCull::singleton = nullptr;
  3448. void RendererSceneCull::set_scene_render(RendererSceneRender *p_scene_render) {
  3449. scene_render = p_scene_render;
  3450. geometry_instance_pair_mask = scene_render->geometry_instance_get_pair_mask();
  3451. }
  3452. /* INTERPOLATION API */
  3453. void RendererSceneCull::update_interpolation_tick(bool p_process) {
  3454. // MultiMesh: Update interpolation in storage.
  3455. RSG::mesh_storage->update_interpolation_tick(p_process);
  3456. }
  3457. void RendererSceneCull::update_interpolation_frame(bool p_process) {
  3458. // MultiMesh: Update interpolation in storage.
  3459. RSG::mesh_storage->update_interpolation_frame(p_process);
  3460. }
  3461. void RendererSceneCull::set_physics_interpolation_enabled(bool p_enabled) {
  3462. _interpolation_data.interpolation_enabled = p_enabled;
  3463. }
  3464. RendererSceneCull::RendererSceneCull() {
  3465. render_pass = 1;
  3466. singleton = this;
  3467. instance_cull_result.set_page_pool(&instance_cull_page_pool);
  3468. instance_shadow_cull_result.set_page_pool(&instance_cull_page_pool);
  3469. for (uint32_t i = 0; i < MAX_UPDATE_SHADOWS; i++) {
  3470. render_shadow_data[i].instances.set_page_pool(&geometry_instance_cull_page_pool);
  3471. }
  3472. for (uint32_t i = 0; i < SDFGI_MAX_CASCADES * SDFGI_MAX_REGIONS_PER_CASCADE; i++) {
  3473. render_sdfgi_data[i].instances.set_page_pool(&geometry_instance_cull_page_pool);
  3474. }
  3475. scene_cull_result.init(&rid_cull_page_pool, &geometry_instance_cull_page_pool, &instance_cull_page_pool);
  3476. scene_cull_result_threads.resize(WorkerThreadPool::get_singleton()->get_thread_count());
  3477. for (InstanceCullResult &thread : scene_cull_result_threads) {
  3478. thread.init(&rid_cull_page_pool, &geometry_instance_cull_page_pool, &instance_cull_page_pool);
  3479. }
  3480. indexer_update_iterations = GLOBAL_GET("rendering/limits/spatial_indexer/update_iterations_per_frame");
  3481. thread_cull_threshold = GLOBAL_GET("rendering/limits/spatial_indexer/threaded_cull_minimum_instances");
  3482. thread_cull_threshold = MAX(thread_cull_threshold, (uint32_t)WorkerThreadPool::get_singleton()->get_thread_count()); //make sure there is at least one thread per CPU
  3483. RendererSceneOcclusionCull::HZBuffer::occlusion_jitter_enabled = GLOBAL_GET("rendering/occlusion_culling/jitter_projection");
  3484. dummy_occlusion_culling = memnew(RendererSceneOcclusionCull);
  3485. light_culler = memnew(RenderingLightCuller);
  3486. bool tighter_caster_culling = GLOBAL_DEF("rendering/lights_and_shadows/tighter_shadow_caster_culling", true);
  3487. light_culler->set_caster_culling_active(tighter_caster_culling);
  3488. light_culler->set_light_culling_active(tighter_caster_culling);
  3489. }
  3490. RendererSceneCull::~RendererSceneCull() {
  3491. instance_cull_result.reset();
  3492. instance_shadow_cull_result.reset();
  3493. for (uint32_t i = 0; i < MAX_UPDATE_SHADOWS; i++) {
  3494. render_shadow_data[i].instances.reset();
  3495. }
  3496. for (uint32_t i = 0; i < SDFGI_MAX_CASCADES * SDFGI_MAX_REGIONS_PER_CASCADE; i++) {
  3497. render_sdfgi_data[i].instances.reset();
  3498. }
  3499. scene_cull_result.reset();
  3500. for (InstanceCullResult &thread : scene_cull_result_threads) {
  3501. thread.reset();
  3502. }
  3503. scene_cull_result_threads.clear();
  3504. if (dummy_occlusion_culling) {
  3505. memdelete(dummy_occlusion_culling);
  3506. }
  3507. if (light_culler) {
  3508. memdelete(light_culler);
  3509. light_culler = nullptr;
  3510. }
  3511. }