renderer_scene_cull.cpp 139 KB

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