renderer_scene_cull.cpp 177 KB

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