renderer_scene_cull.cpp 123 KB

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