renderer_scene_cull.cpp 152 KB

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