rasterizer_scene_rd.cpp 286 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497
  1. /*************************************************************************/
  2. /* rasterizer_scene_rd.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "rasterizer_scene_rd.h"
  31. #include "core/os/os.h"
  32. #include "core/project_settings.h"
  33. #include "rasterizer_rd.h"
  34. #include "servers/rendering/rendering_server_raster.h"
  35. uint64_t RasterizerSceneRD::auto_exposure_counter = 2;
  36. void get_vogel_disk(float *r_kernel, int p_sample_count) {
  37. const float golden_angle = 2.4;
  38. for (int i = 0; i < p_sample_count; i++) {
  39. float r = Math::sqrt(float(i) + 0.5) / Math::sqrt(float(p_sample_count));
  40. float theta = float(i) * golden_angle;
  41. r_kernel[i * 4] = Math::cos(theta) * r;
  42. r_kernel[i * 4 + 1] = Math::sin(theta) * r;
  43. }
  44. }
  45. void RasterizerSceneRD::_clear_reflection_data(ReflectionData &rd) {
  46. rd.layers.clear();
  47. rd.radiance_base_cubemap = RID();
  48. if (rd.downsampled_radiance_cubemap.is_valid()) {
  49. RD::get_singleton()->free(rd.downsampled_radiance_cubemap);
  50. }
  51. rd.downsampled_radiance_cubemap = RID();
  52. rd.downsampled_layer.mipmaps.clear();
  53. rd.coefficient_buffer = RID();
  54. }
  55. void RasterizerSceneRD::_update_reflection_data(ReflectionData &rd, int p_size, int p_mipmaps, bool p_use_array, RID p_base_cube, int p_base_layer, bool p_low_quality) {
  56. //recreate radiance and all data
  57. int mipmaps = p_mipmaps;
  58. uint32_t w = p_size, h = p_size;
  59. if (p_use_array) {
  60. int layers = p_low_quality ? 8 : roughness_layers;
  61. for (int i = 0; i < layers; i++) {
  62. ReflectionData::Layer layer;
  63. uint32_t mmw = w;
  64. uint32_t mmh = h;
  65. layer.mipmaps.resize(mipmaps);
  66. layer.views.resize(mipmaps);
  67. for (int j = 0; j < mipmaps; j++) {
  68. ReflectionData::Layer::Mipmap &mm = layer.mipmaps.write[j];
  69. mm.size.width = mmw;
  70. mm.size.height = mmh;
  71. for (int k = 0; k < 6; k++) {
  72. mm.views[k] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer + i * 6 + k, j);
  73. Vector<RID> fbtex;
  74. fbtex.push_back(mm.views[k]);
  75. mm.framebuffers[k] = RD::get_singleton()->framebuffer_create(fbtex);
  76. }
  77. layer.views.write[j] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer + i * 6, j, RD::TEXTURE_SLICE_CUBEMAP);
  78. mmw = MAX(1, mmw >> 1);
  79. mmh = MAX(1, mmh >> 1);
  80. }
  81. rd.layers.push_back(layer);
  82. }
  83. } else {
  84. mipmaps = p_low_quality ? 8 : mipmaps;
  85. //regular cubemap, lower quality (aliasing, less memory)
  86. ReflectionData::Layer layer;
  87. uint32_t mmw = w;
  88. uint32_t mmh = h;
  89. layer.mipmaps.resize(mipmaps);
  90. layer.views.resize(mipmaps);
  91. for (int j = 0; j < mipmaps; j++) {
  92. ReflectionData::Layer::Mipmap &mm = layer.mipmaps.write[j];
  93. mm.size.width = mmw;
  94. mm.size.height = mmh;
  95. for (int k = 0; k < 6; k++) {
  96. mm.views[k] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer + k, j);
  97. Vector<RID> fbtex;
  98. fbtex.push_back(mm.views[k]);
  99. mm.framebuffers[k] = RD::get_singleton()->framebuffer_create(fbtex);
  100. }
  101. layer.views.write[j] = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer, j, RD::TEXTURE_SLICE_CUBEMAP);
  102. mmw = MAX(1, mmw >> 1);
  103. mmh = MAX(1, mmh >> 1);
  104. }
  105. rd.layers.push_back(layer);
  106. }
  107. rd.radiance_base_cubemap = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), p_base_cube, p_base_layer, 0, RD::TEXTURE_SLICE_CUBEMAP);
  108. RD::TextureFormat tf;
  109. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  110. tf.width = 64; // Always 64x64
  111. tf.height = 64;
  112. tf.type = RD::TEXTURE_TYPE_CUBE;
  113. tf.array_layers = 6;
  114. tf.mipmaps = 7;
  115. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  116. rd.downsampled_radiance_cubemap = RD::get_singleton()->texture_create(tf, RD::TextureView());
  117. {
  118. uint32_t mmw = 64;
  119. uint32_t mmh = 64;
  120. rd.downsampled_layer.mipmaps.resize(7);
  121. for (int j = 0; j < rd.downsampled_layer.mipmaps.size(); j++) {
  122. ReflectionData::DownsampleLayer::Mipmap &mm = rd.downsampled_layer.mipmaps.write[j];
  123. mm.size.width = mmw;
  124. mm.size.height = mmh;
  125. mm.view = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rd.downsampled_radiance_cubemap, 0, j, RD::TEXTURE_SLICE_CUBEMAP);
  126. mmw = MAX(1, mmw >> 1);
  127. mmh = MAX(1, mmh >> 1);
  128. }
  129. }
  130. }
  131. void RasterizerSceneRD::_create_reflection_fast_filter(ReflectionData &rd, bool p_use_arrays) {
  132. storage->get_effects()->cubemap_downsample(rd.radiance_base_cubemap, rd.downsampled_layer.mipmaps[0].view, rd.downsampled_layer.mipmaps[0].size);
  133. for (int i = 1; i < rd.downsampled_layer.mipmaps.size(); i++) {
  134. storage->get_effects()->cubemap_downsample(rd.downsampled_layer.mipmaps[i - 1].view, rd.downsampled_layer.mipmaps[i].view, rd.downsampled_layer.mipmaps[i].size);
  135. }
  136. Vector<RID> views;
  137. if (p_use_arrays) {
  138. for (int i = 1; i < rd.layers.size(); i++) {
  139. views.push_back(rd.layers[i].views[0]);
  140. }
  141. } else {
  142. for (int i = 1; i < rd.layers[0].views.size(); i++) {
  143. views.push_back(rd.layers[0].views[i]);
  144. }
  145. }
  146. storage->get_effects()->cubemap_filter(rd.downsampled_radiance_cubemap, views, p_use_arrays);
  147. }
  148. void RasterizerSceneRD::_create_reflection_importance_sample(ReflectionData &rd, bool p_use_arrays, int p_cube_side, int p_base_layer) {
  149. if (p_use_arrays) {
  150. //render directly to the layers
  151. storage->get_effects()->cubemap_roughness(rd.radiance_base_cubemap, rd.layers[p_base_layer].views[0], p_cube_side, sky_ggx_samples_quality, float(p_base_layer) / (rd.layers.size() - 1.0), rd.layers[p_base_layer].mipmaps[0].size.x);
  152. } else {
  153. storage->get_effects()->cubemap_roughness(rd.layers[0].views[p_base_layer - 1], rd.layers[0].views[p_base_layer], p_cube_side, sky_ggx_samples_quality, float(p_base_layer) / (rd.layers[0].mipmaps.size() - 1.0), rd.layers[0].mipmaps[p_base_layer].size.x);
  154. }
  155. }
  156. void RasterizerSceneRD::_update_reflection_mipmaps(ReflectionData &rd, int p_start, int p_end) {
  157. for (int i = p_start; i < p_end; i++) {
  158. for (int j = 0; j < rd.layers[i].mipmaps.size() - 1; j++) {
  159. for (int k = 0; k < 6; k++) {
  160. RID view = rd.layers[i].mipmaps[j].views[k];
  161. RID texture = rd.layers[i].mipmaps[j + 1].views[k];
  162. Size2i size = rd.layers[i].mipmaps[j + 1].size;
  163. storage->get_effects()->make_mipmap(view, texture, size);
  164. }
  165. }
  166. }
  167. }
  168. void RasterizerSceneRD::_sdfgi_erase(RenderBuffers *rb) {
  169. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  170. const SDFGI::Cascade &c = rb->sdfgi->cascades[i];
  171. RD::get_singleton()->free(c.light_data);
  172. RD::get_singleton()->free(c.light_aniso_0_tex);
  173. RD::get_singleton()->free(c.light_aniso_1_tex);
  174. RD::get_singleton()->free(c.sdf_tex);
  175. RD::get_singleton()->free(c.solid_cell_dispatch_buffer);
  176. RD::get_singleton()->free(c.solid_cell_buffer);
  177. RD::get_singleton()->free(c.lightprobe_history_tex);
  178. RD::get_singleton()->free(c.lightprobe_average_tex);
  179. RD::get_singleton()->free(c.lights_buffer);
  180. }
  181. RD::get_singleton()->free(rb->sdfgi->render_albedo);
  182. RD::get_singleton()->free(rb->sdfgi->render_emission);
  183. RD::get_singleton()->free(rb->sdfgi->render_emission_aniso);
  184. RD::get_singleton()->free(rb->sdfgi->render_sdf[0]);
  185. RD::get_singleton()->free(rb->sdfgi->render_sdf[1]);
  186. RD::get_singleton()->free(rb->sdfgi->render_sdf_half[0]);
  187. RD::get_singleton()->free(rb->sdfgi->render_sdf_half[1]);
  188. for (int i = 0; i < 8; i++) {
  189. RD::get_singleton()->free(rb->sdfgi->render_occlusion[i]);
  190. }
  191. RD::get_singleton()->free(rb->sdfgi->render_geom_facing);
  192. RD::get_singleton()->free(rb->sdfgi->lightprobe_data);
  193. RD::get_singleton()->free(rb->sdfgi->lightprobe_history_scroll);
  194. RD::get_singleton()->free(rb->sdfgi->occlusion_data);
  195. RD::get_singleton()->free(rb->sdfgi->cascades_ubo);
  196. memdelete(rb->sdfgi);
  197. rb->sdfgi = nullptr;
  198. }
  199. const Vector3i RasterizerSceneRD::SDFGI::Cascade::DIRTY_ALL = Vector3i(0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF);
  200. void RasterizerSceneRD::sdfgi_update(RID p_render_buffers, RID p_environment, const Vector3 &p_world_position) {
  201. Environment *env = environment_owner.getornull(p_environment);
  202. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  203. bool needs_sdfgi = env && env->sdfgi_enabled;
  204. if (!needs_sdfgi) {
  205. if (rb->sdfgi != nullptr) {
  206. //erase it
  207. _sdfgi_erase(rb);
  208. _render_buffers_uniform_set_changed(p_render_buffers);
  209. }
  210. return;
  211. }
  212. static const uint32_t history_frames_to_converge[RS::ENV_SDFGI_CONVERGE_MAX] = { 5, 10, 15, 20, 25, 30 };
  213. uint32_t requested_history_size = history_frames_to_converge[sdfgi_frames_to_converge];
  214. if (rb->sdfgi && (rb->sdfgi->cascade_mode != env->sdfgi_cascades || rb->sdfgi->min_cell_size != env->sdfgi_min_cell_size || requested_history_size != rb->sdfgi->history_size || rb->sdfgi->uses_occlusion != env->sdfgi_use_occlusion || rb->sdfgi->y_scale_mode != env->sdfgi_y_scale)) {
  215. //configuration changed, erase
  216. _sdfgi_erase(rb);
  217. }
  218. SDFGI *sdfgi = rb->sdfgi;
  219. if (sdfgi == nullptr) {
  220. //re-create
  221. rb->sdfgi = memnew(SDFGI);
  222. sdfgi = rb->sdfgi;
  223. sdfgi->cascade_mode = env->sdfgi_cascades;
  224. sdfgi->min_cell_size = env->sdfgi_min_cell_size;
  225. sdfgi->uses_occlusion = env->sdfgi_use_occlusion;
  226. sdfgi->y_scale_mode = env->sdfgi_y_scale;
  227. static const float y_scale[3] = { 1.0, 1.5, 2.0 };
  228. sdfgi->y_mult = y_scale[sdfgi->y_scale_mode];
  229. static const int cascasde_size[3] = { 4, 6, 8 };
  230. sdfgi->cascades.resize(cascasde_size[sdfgi->cascade_mode]);
  231. sdfgi->probe_axis_count = SDFGI::PROBE_DIVISOR + 1;
  232. sdfgi->solid_cell_ratio = sdfgi_solid_cell_ratio;
  233. sdfgi->solid_cell_count = uint32_t(float(sdfgi->cascade_size * sdfgi->cascade_size * sdfgi->cascade_size) * sdfgi->solid_cell_ratio);
  234. float base_cell_size = sdfgi->min_cell_size;
  235. RD::TextureFormat tf_sdf;
  236. tf_sdf.format = RD::DATA_FORMAT_R8_UNORM;
  237. tf_sdf.width = sdfgi->cascade_size; // Always 64x64
  238. tf_sdf.height = sdfgi->cascade_size;
  239. tf_sdf.depth = sdfgi->cascade_size;
  240. tf_sdf.type = RD::TEXTURE_TYPE_3D;
  241. tf_sdf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
  242. {
  243. RD::TextureFormat tf_render = tf_sdf;
  244. tf_render.format = RD::DATA_FORMAT_R16_UINT;
  245. sdfgi->render_albedo = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  246. tf_render.format = RD::DATA_FORMAT_R32_UINT;
  247. sdfgi->render_emission = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  248. sdfgi->render_emission_aniso = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  249. tf_render.format = RD::DATA_FORMAT_R8_UNORM; //at least its easy to visualize
  250. for (int i = 0; i < 8; i++) {
  251. sdfgi->render_occlusion[i] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  252. }
  253. tf_render.format = RD::DATA_FORMAT_R32_UINT;
  254. sdfgi->render_geom_facing = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  255. tf_render.format = RD::DATA_FORMAT_R8G8B8A8_UINT;
  256. sdfgi->render_sdf[0] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  257. sdfgi->render_sdf[1] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  258. tf_render.width /= 2;
  259. tf_render.height /= 2;
  260. tf_render.depth /= 2;
  261. sdfgi->render_sdf_half[0] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  262. sdfgi->render_sdf_half[1] = RD::get_singleton()->texture_create(tf_render, RD::TextureView());
  263. }
  264. RD::TextureFormat tf_occlusion = tf_sdf;
  265. tf_occlusion.format = RD::DATA_FORMAT_R16_UINT;
  266. tf_occlusion.shareable_formats.push_back(RD::DATA_FORMAT_R16_UINT);
  267. tf_occlusion.shareable_formats.push_back(RD::DATA_FORMAT_R4G4B4A4_UNORM_PACK16);
  268. tf_occlusion.depth *= sdfgi->cascades.size(); //use depth for occlusion slices
  269. tf_occlusion.width *= 2; //use width for the other half
  270. RD::TextureFormat tf_light = tf_sdf;
  271. tf_light.format = RD::DATA_FORMAT_R32_UINT;
  272. tf_light.shareable_formats.push_back(RD::DATA_FORMAT_R32_UINT);
  273. tf_light.shareable_formats.push_back(RD::DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32);
  274. RD::TextureFormat tf_aniso0 = tf_sdf;
  275. tf_aniso0.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  276. RD::TextureFormat tf_aniso1 = tf_sdf;
  277. tf_aniso1.format = RD::DATA_FORMAT_R8G8_UNORM;
  278. int passes = nearest_shift(sdfgi->cascade_size) - 1;
  279. //store lightprobe SH
  280. RD::TextureFormat tf_probes;
  281. tf_probes.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  282. tf_probes.width = sdfgi->probe_axis_count * sdfgi->probe_axis_count;
  283. tf_probes.height = sdfgi->probe_axis_count * SDFGI::SH_SIZE;
  284. tf_probes.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
  285. tf_probes.type = RD::TEXTURE_TYPE_2D_ARRAY;
  286. sdfgi->history_size = requested_history_size;
  287. RD::TextureFormat tf_probe_history = tf_probes;
  288. tf_probe_history.format = RD::DATA_FORMAT_R16G16B16A16_SINT; //signed integer because SH are signed
  289. tf_probe_history.array_layers = sdfgi->history_size;
  290. RD::TextureFormat tf_probe_average = tf_probes;
  291. tf_probe_average.format = RD::DATA_FORMAT_R32G32B32A32_SINT; //signed integer because SH are signed
  292. tf_probe_average.type = RD::TEXTURE_TYPE_2D_ARRAY;
  293. tf_probe_average.array_layers = 1;
  294. sdfgi->lightprobe_history_scroll = RD::get_singleton()->texture_create(tf_probe_history, RD::TextureView());
  295. sdfgi->lightprobe_average_scroll = RD::get_singleton()->texture_create(tf_probe_average, RD::TextureView());
  296. {
  297. //octahedral lightprobes
  298. RD::TextureFormat tf_octprobes = tf_probes;
  299. tf_octprobes.array_layers = sdfgi->cascades.size() * 2;
  300. tf_octprobes.format = RD::DATA_FORMAT_R32_UINT; //pack well with RGBE
  301. tf_octprobes.width = sdfgi->probe_axis_count * sdfgi->probe_axis_count * (SDFGI::LIGHTPROBE_OCT_SIZE + 2);
  302. tf_octprobes.height = sdfgi->probe_axis_count * (SDFGI::LIGHTPROBE_OCT_SIZE + 2);
  303. tf_octprobes.shareable_formats.push_back(RD::DATA_FORMAT_R32_UINT);
  304. tf_octprobes.shareable_formats.push_back(RD::DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32);
  305. //lightprobe texture is an octahedral texture
  306. sdfgi->lightprobe_data = RD::get_singleton()->texture_create(tf_octprobes, RD::TextureView());
  307. RD::TextureView tv;
  308. tv.format_override = RD::DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32;
  309. sdfgi->lightprobe_texture = RD::get_singleton()->texture_create_shared(tv, sdfgi->lightprobe_data);
  310. }
  311. sdfgi->cascades_ubo = RD::get_singleton()->uniform_buffer_create(sizeof(SDFGI::Cascade::UBO) * SDFGI::MAX_CASCADES);
  312. sdfgi->occlusion_data = RD::get_singleton()->texture_create(tf_occlusion, RD::TextureView());
  313. {
  314. RD::TextureView tv;
  315. tv.format_override = RD::DATA_FORMAT_R4G4B4A4_UNORM_PACK16;
  316. sdfgi->occlusion_texture = RD::get_singleton()->texture_create_shared(tv, sdfgi->occlusion_data);
  317. }
  318. for (uint32_t i = 0; i < sdfgi->cascades.size(); i++) {
  319. SDFGI::Cascade &cascade = sdfgi->cascades[i];
  320. /* 3D Textures */
  321. cascade.sdf_tex = RD::get_singleton()->texture_create(tf_sdf, RD::TextureView());
  322. cascade.light_data = RD::get_singleton()->texture_create(tf_light, RD::TextureView());
  323. cascade.light_aniso_0_tex = RD::get_singleton()->texture_create(tf_aniso0, RD::TextureView());
  324. cascade.light_aniso_1_tex = RD::get_singleton()->texture_create(tf_aniso1, RD::TextureView());
  325. {
  326. RD::TextureView tv;
  327. tv.format_override = RD::DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32;
  328. cascade.light_tex = RD::get_singleton()->texture_create_shared(tv, cascade.light_data);
  329. RD::get_singleton()->texture_clear(cascade.light_tex, Color(0, 0, 0, 0), 0, 1, 0, 1);
  330. RD::get_singleton()->texture_clear(cascade.light_aniso_0_tex, Color(0, 0, 0, 0), 0, 1, 0, 1);
  331. RD::get_singleton()->texture_clear(cascade.light_aniso_1_tex, Color(0, 0, 0, 0), 0, 1, 0, 1);
  332. }
  333. cascade.cell_size = base_cell_size;
  334. Vector3 world_position = p_world_position;
  335. world_position.y *= sdfgi->y_mult;
  336. int32_t probe_cells = sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
  337. Vector3 probe_size = Vector3(1, 1, 1) * cascade.cell_size * probe_cells;
  338. Vector3i probe_pos = Vector3i((world_position / probe_size + Vector3(0.5, 0.5, 0.5)).floor());
  339. cascade.position = probe_pos * probe_cells;
  340. cascade.dirty_regions = SDFGI::Cascade::DIRTY_ALL;
  341. base_cell_size *= 2.0;
  342. /* Probe History */
  343. cascade.lightprobe_history_tex = RD::get_singleton()->texture_create(tf_probe_history, RD::TextureView());
  344. RD::get_singleton()->texture_clear(cascade.lightprobe_history_tex, Color(0, 0, 0, 0), 0, 1, 0, tf_probe_history.array_layers); //needs to be cleared for average to work
  345. cascade.lightprobe_average_tex = RD::get_singleton()->texture_create(tf_probe_average, RD::TextureView());
  346. RD::get_singleton()->texture_clear(cascade.lightprobe_average_tex, Color(0, 0, 0, 0), 0, 1, 0, 1); //needs to be cleared for average to work
  347. /* Buffers */
  348. cascade.solid_cell_buffer = RD::get_singleton()->storage_buffer_create(sizeof(SDFGI::Cascade::SolidCell) * sdfgi->solid_cell_count);
  349. cascade.solid_cell_dispatch_buffer = RD::get_singleton()->storage_buffer_create(sizeof(uint32_t) * 4, Vector<uint8_t>(), RD::STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT);
  350. cascade.lights_buffer = RD::get_singleton()->storage_buffer_create(sizeof(SDGIShader::Light) * MAX(SDFGI::MAX_STATIC_LIGHTS, SDFGI::MAX_DYNAMIC_LIGHTS));
  351. {
  352. Vector<RD::Uniform> uniforms;
  353. {
  354. RD::Uniform u;
  355. u.type = RD::UNIFORM_TYPE_IMAGE;
  356. u.binding = 1;
  357. u.ids.push_back(sdfgi->render_sdf[(passes & 1) ? 1 : 0]); //if passes are even, we read from buffer 0, else we read from buffer 1
  358. uniforms.push_back(u);
  359. }
  360. {
  361. RD::Uniform u;
  362. u.type = RD::UNIFORM_TYPE_IMAGE;
  363. u.binding = 2;
  364. u.ids.push_back(sdfgi->render_albedo);
  365. uniforms.push_back(u);
  366. }
  367. {
  368. RD::Uniform u;
  369. u.type = RD::UNIFORM_TYPE_IMAGE;
  370. u.binding = 3;
  371. for (int j = 0; j < 8; j++) {
  372. u.ids.push_back(sdfgi->render_occlusion[j]);
  373. }
  374. uniforms.push_back(u);
  375. }
  376. {
  377. RD::Uniform u;
  378. u.type = RD::UNIFORM_TYPE_IMAGE;
  379. u.binding = 4;
  380. u.ids.push_back(sdfgi->render_emission);
  381. uniforms.push_back(u);
  382. }
  383. {
  384. RD::Uniform u;
  385. u.type = RD::UNIFORM_TYPE_IMAGE;
  386. u.binding = 5;
  387. u.ids.push_back(sdfgi->render_emission_aniso);
  388. uniforms.push_back(u);
  389. }
  390. {
  391. RD::Uniform u;
  392. u.type = RD::UNIFORM_TYPE_IMAGE;
  393. u.binding = 6;
  394. u.ids.push_back(sdfgi->render_geom_facing);
  395. uniforms.push_back(u);
  396. }
  397. {
  398. RD::Uniform u;
  399. u.type = RD::UNIFORM_TYPE_IMAGE;
  400. u.binding = 7;
  401. u.ids.push_back(cascade.sdf_tex);
  402. uniforms.push_back(u);
  403. }
  404. {
  405. RD::Uniform u;
  406. u.type = RD::UNIFORM_TYPE_IMAGE;
  407. u.binding = 8;
  408. u.ids.push_back(sdfgi->occlusion_data);
  409. uniforms.push_back(u);
  410. }
  411. {
  412. RD::Uniform u;
  413. u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  414. u.binding = 10;
  415. u.ids.push_back(cascade.solid_cell_dispatch_buffer);
  416. uniforms.push_back(u);
  417. }
  418. {
  419. RD::Uniform u;
  420. u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  421. u.binding = 11;
  422. u.ids.push_back(cascade.solid_cell_buffer);
  423. uniforms.push_back(u);
  424. }
  425. cascade.sdf_store_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_STORE), 0);
  426. }
  427. {
  428. Vector<RD::Uniform> uniforms;
  429. {
  430. RD::Uniform u;
  431. u.type = RD::UNIFORM_TYPE_IMAGE;
  432. u.binding = 1;
  433. u.ids.push_back(sdfgi->render_albedo);
  434. uniforms.push_back(u);
  435. }
  436. {
  437. RD::Uniform u;
  438. u.type = RD::UNIFORM_TYPE_IMAGE;
  439. u.binding = 2;
  440. u.ids.push_back(sdfgi->render_geom_facing);
  441. uniforms.push_back(u);
  442. }
  443. {
  444. RD::Uniform u;
  445. u.type = RD::UNIFORM_TYPE_IMAGE;
  446. u.binding = 3;
  447. u.ids.push_back(sdfgi->render_emission);
  448. uniforms.push_back(u);
  449. }
  450. {
  451. RD::Uniform u;
  452. u.type = RD::UNIFORM_TYPE_IMAGE;
  453. u.binding = 4;
  454. u.ids.push_back(sdfgi->render_emission_aniso);
  455. uniforms.push_back(u);
  456. }
  457. {
  458. RD::Uniform u;
  459. u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  460. u.binding = 5;
  461. u.ids.push_back(cascade.solid_cell_dispatch_buffer);
  462. uniforms.push_back(u);
  463. }
  464. {
  465. RD::Uniform u;
  466. u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  467. u.binding = 6;
  468. u.ids.push_back(cascade.solid_cell_buffer);
  469. uniforms.push_back(u);
  470. }
  471. cascade.scroll_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_SCROLL), 0);
  472. }
  473. {
  474. Vector<RD::Uniform> uniforms;
  475. {
  476. RD::Uniform u;
  477. u.type = RD::UNIFORM_TYPE_IMAGE;
  478. u.binding = 1;
  479. for (int j = 0; j < 8; j++) {
  480. u.ids.push_back(sdfgi->render_occlusion[j]);
  481. }
  482. uniforms.push_back(u);
  483. }
  484. {
  485. RD::Uniform u;
  486. u.type = RD::UNIFORM_TYPE_IMAGE;
  487. u.binding = 2;
  488. u.ids.push_back(sdfgi->occlusion_data);
  489. uniforms.push_back(u);
  490. }
  491. cascade.scroll_occlusion_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_SCROLL_OCCLUSION), 0);
  492. }
  493. }
  494. //direct light
  495. for (uint32_t i = 0; i < sdfgi->cascades.size(); i++) {
  496. SDFGI::Cascade &cascade = sdfgi->cascades[i];
  497. Vector<RD::Uniform> uniforms;
  498. {
  499. RD::Uniform u;
  500. u.binding = 1;
  501. u.type = RD::UNIFORM_TYPE_TEXTURE;
  502. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  503. if (j < rb->sdfgi->cascades.size()) {
  504. u.ids.push_back(rb->sdfgi->cascades[j].sdf_tex);
  505. } else {
  506. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  507. }
  508. }
  509. uniforms.push_back(u);
  510. }
  511. {
  512. RD::Uniform u;
  513. u.binding = 2;
  514. u.type = RD::UNIFORM_TYPE_SAMPLER;
  515. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  516. uniforms.push_back(u);
  517. }
  518. {
  519. RD::Uniform u;
  520. u.binding = 3;
  521. u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  522. u.ids.push_back(cascade.solid_cell_dispatch_buffer);
  523. uniforms.push_back(u);
  524. }
  525. {
  526. RD::Uniform u;
  527. u.binding = 4;
  528. u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  529. u.ids.push_back(cascade.solid_cell_buffer);
  530. uniforms.push_back(u);
  531. }
  532. {
  533. RD::Uniform u;
  534. u.binding = 5;
  535. u.type = RD::UNIFORM_TYPE_IMAGE;
  536. u.ids.push_back(cascade.light_data);
  537. uniforms.push_back(u);
  538. }
  539. {
  540. RD::Uniform u;
  541. u.binding = 6;
  542. u.type = RD::UNIFORM_TYPE_IMAGE;
  543. u.ids.push_back(cascade.light_aniso_0_tex);
  544. uniforms.push_back(u);
  545. }
  546. {
  547. RD::Uniform u;
  548. u.binding = 7;
  549. u.type = RD::UNIFORM_TYPE_IMAGE;
  550. u.ids.push_back(cascade.light_aniso_1_tex);
  551. uniforms.push_back(u);
  552. }
  553. {
  554. RD::Uniform u;
  555. u.binding = 8;
  556. u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  557. u.ids.push_back(rb->sdfgi->cascades_ubo);
  558. uniforms.push_back(u);
  559. }
  560. {
  561. RD::Uniform u;
  562. u.binding = 9;
  563. u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  564. u.ids.push_back(cascade.lights_buffer);
  565. uniforms.push_back(u);
  566. }
  567. {
  568. RD::Uniform u;
  569. u.binding = 10;
  570. u.type = RD::UNIFORM_TYPE_TEXTURE;
  571. u.ids.push_back(rb->sdfgi->lightprobe_texture);
  572. uniforms.push_back(u);
  573. }
  574. cascade.sdf_direct_light_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.direct_light.version_get_shader(sdfgi_shader.direct_light_shader, 0), 0);
  575. }
  576. //preprocess initialize uniform set
  577. {
  578. Vector<RD::Uniform> uniforms;
  579. {
  580. RD::Uniform u;
  581. u.type = RD::UNIFORM_TYPE_IMAGE;
  582. u.binding = 1;
  583. u.ids.push_back(sdfgi->render_albedo);
  584. uniforms.push_back(u);
  585. }
  586. {
  587. RD::Uniform u;
  588. u.type = RD::UNIFORM_TYPE_IMAGE;
  589. u.binding = 2;
  590. u.ids.push_back(sdfgi->render_sdf[0]);
  591. uniforms.push_back(u);
  592. }
  593. sdfgi->sdf_initialize_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD_INITIALIZE), 0);
  594. }
  595. {
  596. Vector<RD::Uniform> uniforms;
  597. {
  598. RD::Uniform u;
  599. u.type = RD::UNIFORM_TYPE_IMAGE;
  600. u.binding = 1;
  601. u.ids.push_back(sdfgi->render_albedo);
  602. uniforms.push_back(u);
  603. }
  604. {
  605. RD::Uniform u;
  606. u.type = RD::UNIFORM_TYPE_IMAGE;
  607. u.binding = 2;
  608. u.ids.push_back(sdfgi->render_sdf_half[0]);
  609. uniforms.push_back(u);
  610. }
  611. sdfgi->sdf_initialize_half_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD_INITIALIZE_HALF), 0);
  612. }
  613. //jump flood uniform set
  614. {
  615. Vector<RD::Uniform> uniforms;
  616. {
  617. RD::Uniform u;
  618. u.type = RD::UNIFORM_TYPE_IMAGE;
  619. u.binding = 1;
  620. u.ids.push_back(sdfgi->render_sdf[0]);
  621. uniforms.push_back(u);
  622. }
  623. {
  624. RD::Uniform u;
  625. u.type = RD::UNIFORM_TYPE_IMAGE;
  626. u.binding = 2;
  627. u.ids.push_back(sdfgi->render_sdf[1]);
  628. uniforms.push_back(u);
  629. }
  630. sdfgi->jump_flood_uniform_set[0] = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD), 0);
  631. SWAP(uniforms.write[0].ids.write[0], uniforms.write[1].ids.write[0]);
  632. sdfgi->jump_flood_uniform_set[1] = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD), 0);
  633. }
  634. //jump flood half uniform set
  635. {
  636. Vector<RD::Uniform> uniforms;
  637. {
  638. RD::Uniform u;
  639. u.type = RD::UNIFORM_TYPE_IMAGE;
  640. u.binding = 1;
  641. u.ids.push_back(sdfgi->render_sdf_half[0]);
  642. uniforms.push_back(u);
  643. }
  644. {
  645. RD::Uniform u;
  646. u.type = RD::UNIFORM_TYPE_IMAGE;
  647. u.binding = 2;
  648. u.ids.push_back(sdfgi->render_sdf_half[1]);
  649. uniforms.push_back(u);
  650. }
  651. sdfgi->jump_flood_half_uniform_set[0] = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD), 0);
  652. SWAP(uniforms.write[0].ids.write[0], uniforms.write[1].ids.write[0]);
  653. sdfgi->jump_flood_half_uniform_set[1] = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD), 0);
  654. }
  655. //upscale half size sdf
  656. {
  657. Vector<RD::Uniform> uniforms;
  658. {
  659. RD::Uniform u;
  660. u.type = RD::UNIFORM_TYPE_IMAGE;
  661. u.binding = 1;
  662. u.ids.push_back(sdfgi->render_albedo);
  663. uniforms.push_back(u);
  664. }
  665. {
  666. RD::Uniform u;
  667. u.type = RD::UNIFORM_TYPE_IMAGE;
  668. u.binding = 2;
  669. u.ids.push_back(sdfgi->render_sdf_half[(passes & 1) ? 0 : 1]); //reverse pass order because half size
  670. uniforms.push_back(u);
  671. }
  672. {
  673. RD::Uniform u;
  674. u.type = RD::UNIFORM_TYPE_IMAGE;
  675. u.binding = 3;
  676. u.ids.push_back(sdfgi->render_sdf[(passes & 1) ? 0 : 1]); //reverse pass order because it needs an extra JFA pass
  677. uniforms.push_back(u);
  678. }
  679. sdfgi->upscale_jfa_uniform_set_index = (passes & 1) ? 0 : 1;
  680. sdfgi->sdf_upscale_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_JUMP_FLOOD_UPSCALE), 0);
  681. }
  682. //occlusion uniform set
  683. {
  684. Vector<RD::Uniform> uniforms;
  685. {
  686. RD::Uniform u;
  687. u.type = RD::UNIFORM_TYPE_IMAGE;
  688. u.binding = 1;
  689. u.ids.push_back(sdfgi->render_albedo);
  690. uniforms.push_back(u);
  691. }
  692. {
  693. RD::Uniform u;
  694. u.type = RD::UNIFORM_TYPE_IMAGE;
  695. u.binding = 2;
  696. for (int i = 0; i < 8; i++) {
  697. u.ids.push_back(sdfgi->render_occlusion[i]);
  698. }
  699. uniforms.push_back(u);
  700. }
  701. {
  702. RD::Uniform u;
  703. u.type = RD::UNIFORM_TYPE_IMAGE;
  704. u.binding = 3;
  705. u.ids.push_back(sdfgi->render_geom_facing);
  706. uniforms.push_back(u);
  707. }
  708. sdfgi->occlusion_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, SDGIShader::PRE_PROCESS_OCCLUSION), 0);
  709. }
  710. for (uint32_t i = 0; i < sdfgi->cascades.size(); i++) {
  711. //integrate uniform
  712. Vector<RD::Uniform> uniforms;
  713. {
  714. RD::Uniform u;
  715. u.binding = 1;
  716. u.type = RD::UNIFORM_TYPE_TEXTURE;
  717. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  718. if (j < sdfgi->cascades.size()) {
  719. u.ids.push_back(sdfgi->cascades[j].sdf_tex);
  720. } else {
  721. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  722. }
  723. }
  724. uniforms.push_back(u);
  725. }
  726. {
  727. RD::Uniform u;
  728. u.binding = 2;
  729. u.type = RD::UNIFORM_TYPE_TEXTURE;
  730. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  731. if (j < sdfgi->cascades.size()) {
  732. u.ids.push_back(sdfgi->cascades[j].light_tex);
  733. } else {
  734. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  735. }
  736. }
  737. uniforms.push_back(u);
  738. }
  739. {
  740. RD::Uniform u;
  741. u.binding = 3;
  742. u.type = RD::UNIFORM_TYPE_TEXTURE;
  743. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  744. if (j < sdfgi->cascades.size()) {
  745. u.ids.push_back(sdfgi->cascades[j].light_aniso_0_tex);
  746. } else {
  747. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  748. }
  749. }
  750. uniforms.push_back(u);
  751. }
  752. {
  753. RD::Uniform u;
  754. u.binding = 4;
  755. u.type = RD::UNIFORM_TYPE_TEXTURE;
  756. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  757. if (j < sdfgi->cascades.size()) {
  758. u.ids.push_back(sdfgi->cascades[j].light_aniso_1_tex);
  759. } else {
  760. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  761. }
  762. }
  763. uniforms.push_back(u);
  764. }
  765. {
  766. RD::Uniform u;
  767. u.type = RD::UNIFORM_TYPE_SAMPLER;
  768. u.binding = 6;
  769. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  770. uniforms.push_back(u);
  771. }
  772. {
  773. RD::Uniform u;
  774. u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  775. u.binding = 7;
  776. u.ids.push_back(sdfgi->cascades_ubo);
  777. uniforms.push_back(u);
  778. }
  779. {
  780. RD::Uniform u;
  781. u.type = RD::UNIFORM_TYPE_IMAGE;
  782. u.binding = 8;
  783. u.ids.push_back(sdfgi->lightprobe_data);
  784. uniforms.push_back(u);
  785. }
  786. {
  787. RD::Uniform u;
  788. u.type = RD::UNIFORM_TYPE_IMAGE;
  789. u.binding = 9;
  790. u.ids.push_back(sdfgi->cascades[i].lightprobe_history_tex);
  791. uniforms.push_back(u);
  792. }
  793. {
  794. RD::Uniform u;
  795. u.type = RD::UNIFORM_TYPE_IMAGE;
  796. u.binding = 10;
  797. u.ids.push_back(sdfgi->cascades[i].lightprobe_average_tex);
  798. uniforms.push_back(u);
  799. }
  800. {
  801. RD::Uniform u;
  802. u.type = RD::UNIFORM_TYPE_IMAGE;
  803. u.binding = 11;
  804. u.ids.push_back(sdfgi->lightprobe_history_scroll);
  805. uniforms.push_back(u);
  806. }
  807. {
  808. RD::Uniform u;
  809. u.type = RD::UNIFORM_TYPE_IMAGE;
  810. u.binding = 12;
  811. u.ids.push_back(sdfgi->lightprobe_average_scroll);
  812. uniforms.push_back(u);
  813. }
  814. {
  815. RD::Uniform u;
  816. u.type = RD::UNIFORM_TYPE_IMAGE;
  817. u.binding = 13;
  818. RID parent_average;
  819. if (i < sdfgi->cascades.size() - 1) {
  820. parent_average = sdfgi->cascades[i + 1].lightprobe_average_tex;
  821. } else {
  822. parent_average = sdfgi->cascades[i - 1].lightprobe_average_tex; //to use something, but it won't be used
  823. }
  824. u.ids.push_back(parent_average);
  825. uniforms.push_back(u);
  826. }
  827. sdfgi->cascades[i].integrate_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.integrate.version_get_shader(sdfgi_shader.integrate_shader, 0), 0);
  828. }
  829. sdfgi->uses_multibounce = env->sdfgi_use_multibounce;
  830. sdfgi->energy = env->sdfgi_energy;
  831. sdfgi->normal_bias = env->sdfgi_normal_bias;
  832. sdfgi->probe_bias = env->sdfgi_probe_bias;
  833. sdfgi->reads_sky = env->sdfgi_read_sky_light;
  834. _render_buffers_uniform_set_changed(p_render_buffers);
  835. return; //done. all levels will need to be rendered which its going to take a bit
  836. }
  837. //check for updates
  838. sdfgi->uses_multibounce = env->sdfgi_use_multibounce;
  839. sdfgi->energy = env->sdfgi_energy;
  840. sdfgi->normal_bias = env->sdfgi_normal_bias;
  841. sdfgi->probe_bias = env->sdfgi_probe_bias;
  842. sdfgi->reads_sky = env->sdfgi_read_sky_light;
  843. int32_t drag_margin = (sdfgi->cascade_size / SDFGI::PROBE_DIVISOR) / 2;
  844. for (uint32_t i = 0; i < sdfgi->cascades.size(); i++) {
  845. SDFGI::Cascade &cascade = sdfgi->cascades[i];
  846. cascade.dirty_regions = Vector3i();
  847. Vector3 probe_half_size = Vector3(1, 1, 1) * cascade.cell_size * float(sdfgi->cascade_size / SDFGI::PROBE_DIVISOR) * 0.5;
  848. probe_half_size = Vector3(0, 0, 0);
  849. Vector3 world_position = p_world_position;
  850. world_position.y *= sdfgi->y_mult;
  851. Vector3i pos_in_cascade = Vector3i((world_position + probe_half_size) / cascade.cell_size);
  852. for (int j = 0; j < 3; j++) {
  853. if (pos_in_cascade[j] < cascade.position[j]) {
  854. while (pos_in_cascade[j] < (cascade.position[j] - drag_margin)) {
  855. cascade.position[j] -= drag_margin * 2;
  856. cascade.dirty_regions[j] += drag_margin * 2;
  857. }
  858. } else if (pos_in_cascade[j] > cascade.position[j]) {
  859. while (pos_in_cascade[j] > (cascade.position[j] + drag_margin)) {
  860. cascade.position[j] += drag_margin * 2;
  861. cascade.dirty_regions[j] -= drag_margin * 2;
  862. }
  863. }
  864. if (cascade.dirty_regions[j] == 0) {
  865. continue; // not dirty
  866. } else if (uint32_t(ABS(cascade.dirty_regions[j])) >= sdfgi->cascade_size) {
  867. //moved too much, just redraw everything (make all dirty)
  868. cascade.dirty_regions = SDFGI::Cascade::DIRTY_ALL;
  869. break;
  870. }
  871. }
  872. if (cascade.dirty_regions != Vector3i() && cascade.dirty_regions != SDFGI::Cascade::DIRTY_ALL) {
  873. //see how much the total dirty volume represents from the total volume
  874. uint32_t total_volume = sdfgi->cascade_size * sdfgi->cascade_size * sdfgi->cascade_size;
  875. uint32_t safe_volume = 1;
  876. for (int j = 0; j < 3; j++) {
  877. safe_volume *= sdfgi->cascade_size - ABS(cascade.dirty_regions[j]);
  878. }
  879. uint32_t dirty_volume = total_volume - safe_volume;
  880. if (dirty_volume > (safe_volume / 2)) {
  881. //more than half the volume is dirty, make all dirty so its only rendered once
  882. cascade.dirty_regions = SDFGI::Cascade::DIRTY_ALL;
  883. }
  884. }
  885. }
  886. }
  887. int RasterizerSceneRD::sdfgi_get_pending_region_count(RID p_render_buffers) const {
  888. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  889. ERR_FAIL_COND_V(rb == nullptr, 0);
  890. if (rb->sdfgi == nullptr) {
  891. return 0;
  892. }
  893. int dirty_count = 0;
  894. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  895. const SDFGI::Cascade &c = rb->sdfgi->cascades[i];
  896. if (c.dirty_regions == SDFGI::Cascade::DIRTY_ALL) {
  897. dirty_count++;
  898. } else {
  899. for (int j = 0; j < 3; j++) {
  900. if (c.dirty_regions[j] != 0) {
  901. dirty_count++;
  902. }
  903. }
  904. }
  905. }
  906. return dirty_count;
  907. }
  908. int RasterizerSceneRD::_sdfgi_get_pending_region_data(RID p_render_buffers, int p_region, Vector3i &r_local_offset, Vector3i &r_local_size, AABB &r_bounds) const {
  909. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  910. ERR_FAIL_COND_V(rb == nullptr, -1);
  911. ERR_FAIL_COND_V(rb->sdfgi == nullptr, -1);
  912. int dirty_count = 0;
  913. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  914. const SDFGI::Cascade &c = rb->sdfgi->cascades[i];
  915. if (c.dirty_regions == SDFGI::Cascade::DIRTY_ALL) {
  916. if (dirty_count == p_region) {
  917. r_local_offset = Vector3i();
  918. r_local_size = Vector3i(1, 1, 1) * rb->sdfgi->cascade_size;
  919. r_bounds.position = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + c.position)) * c.cell_size * Vector3(1, 1.0 / rb->sdfgi->y_mult, 1);
  920. r_bounds.size = Vector3(r_local_size) * c.cell_size * Vector3(1, 1.0 / rb->sdfgi->y_mult, 1);
  921. return i;
  922. }
  923. dirty_count++;
  924. } else {
  925. for (int j = 0; j < 3; j++) {
  926. if (c.dirty_regions[j] != 0) {
  927. if (dirty_count == p_region) {
  928. Vector3i from = Vector3i(0, 0, 0);
  929. Vector3i to = Vector3i(1, 1, 1) * rb->sdfgi->cascade_size;
  930. if (c.dirty_regions[j] > 0) {
  931. //fill from the beginning
  932. to[j] = c.dirty_regions[j];
  933. } else {
  934. //fill from the end
  935. from[j] = to[j] + c.dirty_regions[j];
  936. }
  937. for (int k = 0; k < j; k++) {
  938. // "chip" away previous regions to avoid re-voxelizing the same thing
  939. if (c.dirty_regions[k] > 0) {
  940. from[k] += c.dirty_regions[k];
  941. } else if (c.dirty_regions[k] < 0) {
  942. to[k] += c.dirty_regions[k];
  943. }
  944. }
  945. r_local_offset = from;
  946. r_local_size = to - from;
  947. r_bounds.position = Vector3(from + Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + c.position) * c.cell_size * Vector3(1, 1.0 / rb->sdfgi->y_mult, 1);
  948. r_bounds.size = Vector3(r_local_size) * c.cell_size * Vector3(1, 1.0 / rb->sdfgi->y_mult, 1);
  949. return i;
  950. }
  951. dirty_count++;
  952. }
  953. }
  954. }
  955. }
  956. return -1;
  957. }
  958. AABB RasterizerSceneRD::sdfgi_get_pending_region_bounds(RID p_render_buffers, int p_region) const {
  959. AABB bounds;
  960. Vector3i from;
  961. Vector3i size;
  962. int c = _sdfgi_get_pending_region_data(p_render_buffers, p_region, from, size, bounds);
  963. ERR_FAIL_COND_V(c == -1, AABB());
  964. return bounds;
  965. }
  966. uint32_t RasterizerSceneRD::sdfgi_get_pending_region_cascade(RID p_render_buffers, int p_region) const {
  967. AABB bounds;
  968. Vector3i from;
  969. Vector3i size;
  970. return _sdfgi_get_pending_region_data(p_render_buffers, p_region, from, size, bounds);
  971. }
  972. void RasterizerSceneRD::_sdfgi_update_cascades(RID p_render_buffers) {
  973. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  974. ERR_FAIL_COND(rb == nullptr);
  975. if (rb->sdfgi == nullptr) {
  976. return;
  977. }
  978. //update cascades
  979. SDFGI::Cascade::UBO cascade_data[SDFGI::MAX_CASCADES];
  980. int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
  981. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  982. Vector3 pos = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + rb->sdfgi->cascades[i].position)) * rb->sdfgi->cascades[i].cell_size;
  983. cascade_data[i].offset[0] = pos.x;
  984. cascade_data[i].offset[1] = pos.y;
  985. cascade_data[i].offset[2] = pos.z;
  986. cascade_data[i].to_cell = 1.0 / rb->sdfgi->cascades[i].cell_size;
  987. cascade_data[i].probe_offset[0] = rb->sdfgi->cascades[i].position.x / probe_divisor;
  988. cascade_data[i].probe_offset[1] = rb->sdfgi->cascades[i].position.y / probe_divisor;
  989. cascade_data[i].probe_offset[2] = rb->sdfgi->cascades[i].position.z / probe_divisor;
  990. cascade_data[i].pad = 0;
  991. }
  992. RD::get_singleton()->buffer_update(rb->sdfgi->cascades_ubo, 0, sizeof(SDFGI::Cascade::UBO) * SDFGI::MAX_CASCADES, cascade_data, true);
  993. }
  994. void RasterizerSceneRD::sdfgi_update_probes(RID p_render_buffers, RID p_environment, const RID *p_directional_light_instances, uint32_t p_directional_light_count, const RID *p_positional_light_instances, uint32_t p_positional_light_count) {
  995. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  996. ERR_FAIL_COND(rb == nullptr);
  997. if (rb->sdfgi == nullptr) {
  998. return;
  999. }
  1000. Environment *env = environment_owner.getornull(p_environment);
  1001. RENDER_TIMESTAMP(">SDFGI Update Probes");
  1002. /* Update Cascades UBO */
  1003. _sdfgi_update_cascades(p_render_buffers);
  1004. /* Update Dynamic Lights Buffer */
  1005. RENDER_TIMESTAMP("Update Lights");
  1006. /* Update dynamic lights */
  1007. {
  1008. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  1009. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.direct_light_pipeline[SDGIShader::DIRECT_LIGHT_MODE_DYNAMIC]);
  1010. SDGIShader::DirectLightPushConstant push_constant;
  1011. push_constant.grid_size[0] = rb->sdfgi->cascade_size;
  1012. push_constant.grid_size[1] = rb->sdfgi->cascade_size;
  1013. push_constant.grid_size[2] = rb->sdfgi->cascade_size;
  1014. push_constant.max_cascades = rb->sdfgi->cascades.size();
  1015. push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
  1016. push_constant.multibounce = rb->sdfgi->uses_multibounce;
  1017. push_constant.y_mult = rb->sdfgi->y_mult;
  1018. push_constant.process_offset = 0;
  1019. push_constant.process_increment = 1;
  1020. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  1021. SDFGI::Cascade &cascade = rb->sdfgi->cascades[i];
  1022. { //fill light buffer
  1023. SDGIShader::Light lights[SDFGI::MAX_DYNAMIC_LIGHTS];
  1024. uint32_t idx = 0;
  1025. for (uint32_t j = 0; j < p_directional_light_count; j++) {
  1026. if (idx == SDFGI::MAX_DYNAMIC_LIGHTS) {
  1027. break;
  1028. }
  1029. LightInstance *li = light_instance_owner.getornull(p_directional_light_instances[j]);
  1030. ERR_CONTINUE(!li);
  1031. Vector3 dir = -li->transform.basis.get_axis(Vector3::AXIS_Z);
  1032. dir.y *= rb->sdfgi->y_mult;
  1033. dir.normalize();
  1034. lights[idx].direction[0] = dir.x;
  1035. lights[idx].direction[1] = dir.y;
  1036. lights[idx].direction[2] = dir.z;
  1037. Color color = storage->light_get_color(li->light);
  1038. color = color.to_linear();
  1039. lights[idx].color[0] = color.r;
  1040. lights[idx].color[1] = color.g;
  1041. lights[idx].color[2] = color.b;
  1042. lights[idx].type = RS::LIGHT_DIRECTIONAL;
  1043. lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY);
  1044. lights[idx].has_shadow = storage->light_has_shadow(li->light);
  1045. idx++;
  1046. }
  1047. AABB cascade_aabb;
  1048. cascade_aabb.position = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + cascade.position)) * cascade.cell_size;
  1049. cascade_aabb.size = Vector3(1, 1, 1) * rb->sdfgi->cascade_size * cascade.cell_size;
  1050. for (uint32_t j = 0; j < p_positional_light_count; j++) {
  1051. if (idx == SDFGI::MAX_DYNAMIC_LIGHTS) {
  1052. break;
  1053. }
  1054. LightInstance *li = light_instance_owner.getornull(p_positional_light_instances[j]);
  1055. ERR_CONTINUE(!li);
  1056. uint32_t max_sdfgi_cascade = storage->light_get_max_sdfgi_cascade(li->light);
  1057. if (i > max_sdfgi_cascade) {
  1058. continue;
  1059. }
  1060. if (!cascade_aabb.intersects(li->aabb)) {
  1061. continue;
  1062. }
  1063. Vector3 dir = -li->transform.basis.get_axis(Vector3::AXIS_Z);
  1064. //faster to not do this here
  1065. //dir.y *= rb->sdfgi->y_mult;
  1066. //dir.normalize();
  1067. lights[idx].direction[0] = dir.x;
  1068. lights[idx].direction[1] = dir.y;
  1069. lights[idx].direction[2] = dir.z;
  1070. Vector3 pos = li->transform.origin;
  1071. pos.y *= rb->sdfgi->y_mult;
  1072. lights[idx].position[0] = pos.x;
  1073. lights[idx].position[1] = pos.y;
  1074. lights[idx].position[2] = pos.z;
  1075. Color color = storage->light_get_color(li->light);
  1076. color = color.to_linear();
  1077. lights[idx].color[0] = color.r;
  1078. lights[idx].color[1] = color.g;
  1079. lights[idx].color[2] = color.b;
  1080. lights[idx].type = storage->light_get_type(li->light);
  1081. lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY);
  1082. lights[idx].has_shadow = storage->light_has_shadow(li->light);
  1083. lights[idx].attenuation = storage->light_get_param(li->light, RS::LIGHT_PARAM_ATTENUATION);
  1084. lights[idx].radius = storage->light_get_param(li->light, RS::LIGHT_PARAM_RANGE);
  1085. lights[idx].spot_angle = Math::deg2rad(storage->light_get_param(li->light, RS::LIGHT_PARAM_SPOT_ANGLE));
  1086. lights[idx].spot_attenuation = storage->light_get_param(li->light, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  1087. idx++;
  1088. }
  1089. if (idx > 0) {
  1090. RD::get_singleton()->buffer_update(cascade.lights_buffer, 0, idx * sizeof(SDGIShader::Light), lights, true);
  1091. }
  1092. push_constant.light_count = idx;
  1093. }
  1094. push_constant.cascade = i;
  1095. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, cascade.sdf_direct_light_uniform_set, 0);
  1096. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::DirectLightPushConstant));
  1097. RD::get_singleton()->compute_list_dispatch_indirect(compute_list, cascade.solid_cell_dispatch_buffer, 0);
  1098. }
  1099. RD::get_singleton()->compute_list_end();
  1100. }
  1101. RENDER_TIMESTAMP("Raytrace");
  1102. SDGIShader::IntegratePushConstant push_constant;
  1103. push_constant.grid_size[1] = rb->sdfgi->cascade_size;
  1104. push_constant.grid_size[2] = rb->sdfgi->cascade_size;
  1105. push_constant.grid_size[0] = rb->sdfgi->cascade_size;
  1106. push_constant.max_cascades = rb->sdfgi->cascades.size();
  1107. push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
  1108. push_constant.history_index = rb->sdfgi->render_pass % rb->sdfgi->history_size;
  1109. push_constant.history_size = rb->sdfgi->history_size;
  1110. static const uint32_t ray_count[RS::ENV_SDFGI_RAY_COUNT_MAX] = { 8, 16, 32, 64, 96, 128 };
  1111. push_constant.ray_count = ray_count[sdfgi_ray_count];
  1112. push_constant.ray_bias = rb->sdfgi->probe_bias;
  1113. push_constant.image_size[0] = rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count;
  1114. push_constant.image_size[1] = rb->sdfgi->probe_axis_count;
  1115. RID sky_uniform_set = sdfgi_shader.integrate_default_sky_uniform_set;
  1116. push_constant.sky_mode = SDGIShader::IntegratePushConstant::SKY_MODE_DISABLED;
  1117. push_constant.y_mult = rb->sdfgi->y_mult;
  1118. if (rb->sdfgi->reads_sky && env) {
  1119. push_constant.sky_energy = env->bg_energy;
  1120. if (env->background == RS::ENV_BG_CLEAR_COLOR) {
  1121. push_constant.sky_mode = SDGIShader::IntegratePushConstant::SKY_MODE_COLOR;
  1122. Color c = storage->get_default_clear_color().to_linear();
  1123. push_constant.sky_color[0] = c.r;
  1124. push_constant.sky_color[1] = c.g;
  1125. push_constant.sky_color[2] = c.b;
  1126. } else if (env->background == RS::ENV_BG_COLOR) {
  1127. push_constant.sky_mode = SDGIShader::IntegratePushConstant::SKY_MODE_COLOR;
  1128. Color c = env->bg_color;
  1129. push_constant.sky_color[0] = c.r;
  1130. push_constant.sky_color[1] = c.g;
  1131. push_constant.sky_color[2] = c.b;
  1132. } else if (env->background == RS::ENV_BG_SKY) {
  1133. Sky *sky = sky_owner.getornull(env->sky);
  1134. if (sky && sky->radiance.is_valid()) {
  1135. if (sky->sdfgi_integrate_sky_uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(sky->sdfgi_integrate_sky_uniform_set)) {
  1136. Vector<RD::Uniform> uniforms;
  1137. {
  1138. RD::Uniform u;
  1139. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1140. u.binding = 0;
  1141. u.ids.push_back(sky->radiance);
  1142. uniforms.push_back(u);
  1143. }
  1144. {
  1145. RD::Uniform u;
  1146. u.type = RD::UNIFORM_TYPE_SAMPLER;
  1147. u.binding = 1;
  1148. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  1149. uniforms.push_back(u);
  1150. }
  1151. sky->sdfgi_integrate_sky_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.integrate.version_get_shader(sdfgi_shader.integrate_shader, 0), 1);
  1152. }
  1153. sky_uniform_set = sky->sdfgi_integrate_sky_uniform_set;
  1154. push_constant.sky_mode = SDGIShader::IntegratePushConstant::SKY_MODE_SKY;
  1155. }
  1156. }
  1157. }
  1158. rb->sdfgi->render_pass++;
  1159. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  1160. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.integrate_pipeline[SDGIShader::INTEGRATE_MODE_PROCESS]);
  1161. int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
  1162. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  1163. push_constant.cascade = i;
  1164. push_constant.world_offset[0] = rb->sdfgi->cascades[i].position.x / probe_divisor;
  1165. push_constant.world_offset[1] = rb->sdfgi->cascades[i].position.y / probe_divisor;
  1166. push_constant.world_offset[2] = rb->sdfgi->cascades[i].position.z / probe_divisor;
  1167. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[i].integrate_uniform_set, 0);
  1168. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, sky_uniform_set, 1);
  1169. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::IntegratePushConstant));
  1170. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count, rb->sdfgi->probe_axis_count, 1, 8, 8, 1);
  1171. }
  1172. RD::get_singleton()->compute_list_add_barrier(compute_list); //wait until done
  1173. // Then store values into the lightprobe texture. Separating these steps has a small performance hit, but it allows for multiple bounces
  1174. RENDER_TIMESTAMP("Average Probes");
  1175. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.integrate_pipeline[SDGIShader::INTEGRATE_MODE_STORE]);
  1176. //convert to octahedral to store
  1177. push_constant.image_size[0] *= SDFGI::LIGHTPROBE_OCT_SIZE;
  1178. push_constant.image_size[1] *= SDFGI::LIGHTPROBE_OCT_SIZE;
  1179. for (uint32_t i = 0; i < rb->sdfgi->cascades.size(); i++) {
  1180. push_constant.cascade = i;
  1181. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[i].integrate_uniform_set, 0);
  1182. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::IntegratePushConstant));
  1183. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count * SDFGI::LIGHTPROBE_OCT_SIZE, rb->sdfgi->probe_axis_count * SDFGI::LIGHTPROBE_OCT_SIZE, 1, 8, 8, 1);
  1184. }
  1185. RD::get_singleton()->compute_list_end();
  1186. RENDER_TIMESTAMP("<SDFGI Update Probes");
  1187. }
  1188. void RasterizerSceneRD::_process_gi(RID p_render_buffers, RID p_normal_roughness_buffer, RID p_ambient_buffer, RID p_reflection_buffer, RID p_gi_probe_buffer, RID p_environment, const CameraMatrix &p_projection, const Transform &p_transform, RID *p_gi_probe_cull_result, int p_gi_probe_cull_count) {
  1189. RENDER_TIMESTAMP("Render GI");
  1190. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  1191. ERR_FAIL_COND(rb == nullptr);
  1192. Environment *env = environment_owner.getornull(p_environment);
  1193. GI::PushConstant push_constant;
  1194. push_constant.screen_size[0] = rb->width;
  1195. push_constant.screen_size[1] = rb->height;
  1196. push_constant.z_near = p_projection.get_z_near();
  1197. push_constant.z_far = p_projection.get_z_far();
  1198. push_constant.orthogonal = p_projection.is_orthogonal();
  1199. push_constant.proj_info[0] = -2.0f / (rb->width * p_projection.matrix[0][0]);
  1200. push_constant.proj_info[1] = -2.0f / (rb->height * p_projection.matrix[1][1]);
  1201. push_constant.proj_info[2] = (1.0f - p_projection.matrix[0][2]) / p_projection.matrix[0][0];
  1202. push_constant.proj_info[3] = (1.0f + p_projection.matrix[1][2]) / p_projection.matrix[1][1];
  1203. push_constant.max_giprobes = MIN(RenderBuffers::MAX_GIPROBES, p_gi_probe_cull_count);
  1204. push_constant.high_quality_vct = gi_probe_quality == RS::GI_PROBE_QUALITY_HIGH;
  1205. push_constant.use_sdfgi = rb->sdfgi != nullptr;
  1206. if (env) {
  1207. push_constant.ao_color[0] = env->ao_color.r;
  1208. push_constant.ao_color[1] = env->ao_color.g;
  1209. push_constant.ao_color[2] = env->ao_color.b;
  1210. } else {
  1211. push_constant.ao_color[0] = 0;
  1212. push_constant.ao_color[1] = 0;
  1213. push_constant.ao_color[2] = 0;
  1214. }
  1215. push_constant.cam_rotation[0] = p_transform.basis[0][0];
  1216. push_constant.cam_rotation[1] = p_transform.basis[1][0];
  1217. push_constant.cam_rotation[2] = p_transform.basis[2][0];
  1218. push_constant.cam_rotation[3] = 0;
  1219. push_constant.cam_rotation[4] = p_transform.basis[0][1];
  1220. push_constant.cam_rotation[5] = p_transform.basis[1][1];
  1221. push_constant.cam_rotation[6] = p_transform.basis[2][1];
  1222. push_constant.cam_rotation[7] = 0;
  1223. push_constant.cam_rotation[8] = p_transform.basis[0][2];
  1224. push_constant.cam_rotation[9] = p_transform.basis[1][2];
  1225. push_constant.cam_rotation[10] = p_transform.basis[2][2];
  1226. push_constant.cam_rotation[11] = 0;
  1227. if (rb->sdfgi) {
  1228. GI::SDFGIData sdfgi_data;
  1229. sdfgi_data.grid_size[0] = rb->sdfgi->cascade_size;
  1230. sdfgi_data.grid_size[1] = rb->sdfgi->cascade_size;
  1231. sdfgi_data.grid_size[2] = rb->sdfgi->cascade_size;
  1232. sdfgi_data.max_cascades = rb->sdfgi->cascades.size();
  1233. sdfgi_data.probe_axis_size = rb->sdfgi->probe_axis_count;
  1234. sdfgi_data.cascade_probe_size[0] = sdfgi_data.probe_axis_size - 1; //float version for performance
  1235. sdfgi_data.cascade_probe_size[1] = sdfgi_data.probe_axis_size - 1;
  1236. sdfgi_data.cascade_probe_size[2] = sdfgi_data.probe_axis_size - 1;
  1237. float csize = rb->sdfgi->cascade_size;
  1238. sdfgi_data.probe_to_uvw = 1.0 / float(sdfgi_data.cascade_probe_size[0]);
  1239. sdfgi_data.use_occlusion = rb->sdfgi->uses_occlusion;
  1240. //sdfgi_data.energy = rb->sdfgi->energy;
  1241. sdfgi_data.y_mult = rb->sdfgi->y_mult;
  1242. float cascade_voxel_size = (csize / sdfgi_data.cascade_probe_size[0]);
  1243. float occlusion_clamp = (cascade_voxel_size - 0.5) / cascade_voxel_size;
  1244. sdfgi_data.occlusion_clamp[0] = occlusion_clamp;
  1245. sdfgi_data.occlusion_clamp[1] = occlusion_clamp;
  1246. sdfgi_data.occlusion_clamp[2] = occlusion_clamp;
  1247. sdfgi_data.normal_bias = (rb->sdfgi->normal_bias / csize) * sdfgi_data.cascade_probe_size[0];
  1248. //vec2 tex_pixel_size = 1.0 / vec2(ivec2( (OCT_SIZE+2) * params.probe_axis_size * params.probe_axis_size, (OCT_SIZE+2) * params.probe_axis_size ) );
  1249. //vec3 probe_uv_offset = (ivec3(OCT_SIZE+2,OCT_SIZE+2,(OCT_SIZE+2) * params.probe_axis_size)) * tex_pixel_size.xyx;
  1250. uint32_t oct_size = SDFGI::LIGHTPROBE_OCT_SIZE;
  1251. sdfgi_data.lightprobe_tex_pixel_size[0] = 1.0 / ((oct_size + 2) * sdfgi_data.probe_axis_size * sdfgi_data.probe_axis_size);
  1252. sdfgi_data.lightprobe_tex_pixel_size[1] = 1.0 / ((oct_size + 2) * sdfgi_data.probe_axis_size);
  1253. sdfgi_data.lightprobe_tex_pixel_size[2] = 1.0;
  1254. sdfgi_data.energy = rb->sdfgi->energy;
  1255. sdfgi_data.lightprobe_uv_offset[0] = float(oct_size + 2) * sdfgi_data.lightprobe_tex_pixel_size[0];
  1256. sdfgi_data.lightprobe_uv_offset[1] = float(oct_size + 2) * sdfgi_data.lightprobe_tex_pixel_size[1];
  1257. sdfgi_data.lightprobe_uv_offset[2] = float((oct_size + 2) * sdfgi_data.probe_axis_size) * sdfgi_data.lightprobe_tex_pixel_size[0];
  1258. sdfgi_data.occlusion_renormalize[0] = 0.5;
  1259. sdfgi_data.occlusion_renormalize[1] = 1.0;
  1260. sdfgi_data.occlusion_renormalize[2] = 1.0 / float(sdfgi_data.max_cascades);
  1261. int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
  1262. for (uint32_t i = 0; i < sdfgi_data.max_cascades; i++) {
  1263. GI::SDFGIData::ProbeCascadeData &c = sdfgi_data.cascades[i];
  1264. Vector3 pos = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + rb->sdfgi->cascades[i].position)) * rb->sdfgi->cascades[i].cell_size;
  1265. Vector3 cam_origin = p_transform.origin;
  1266. cam_origin.y *= rb->sdfgi->y_mult;
  1267. pos -= cam_origin; //make pos local to camera, to reduce numerical error
  1268. c.position[0] = pos.x;
  1269. c.position[1] = pos.y;
  1270. c.position[2] = pos.z;
  1271. c.to_probe = 1.0 / (float(rb->sdfgi->cascade_size) * rb->sdfgi->cascades[i].cell_size / float(rb->sdfgi->probe_axis_count - 1));
  1272. Vector3i probe_ofs = rb->sdfgi->cascades[i].position / probe_divisor;
  1273. c.probe_world_offset[0] = probe_ofs.x;
  1274. c.probe_world_offset[1] = probe_ofs.y;
  1275. c.probe_world_offset[2] = probe_ofs.z;
  1276. c.to_cell = 1.0 / rb->sdfgi->cascades[i].cell_size;
  1277. }
  1278. RD::get_singleton()->buffer_update(gi.sdfgi_ubo, 0, sizeof(GI::SDFGIData), &sdfgi_data, true);
  1279. }
  1280. {
  1281. RID gi_probe_buffer = render_buffers_get_gi_probe_buffer(p_render_buffers);
  1282. GI::GIProbeData gi_probe_data[RenderBuffers::MAX_GIPROBES];
  1283. bool giprobes_changed = false;
  1284. Transform to_camera;
  1285. to_camera.origin = p_transform.origin; //only translation, make local
  1286. for (int i = 0; i < RenderBuffers::MAX_GIPROBES; i++) {
  1287. RID texture;
  1288. if (i < p_gi_probe_cull_count) {
  1289. GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_gi_probe_cull_result[i]);
  1290. if (gipi) {
  1291. texture = gipi->texture;
  1292. GI::GIProbeData &gipd = gi_probe_data[i];
  1293. RID base_probe = gipi->probe;
  1294. Transform to_cell = storage->gi_probe_get_to_cell_xform(gipi->probe) * gipi->transform.affine_inverse() * to_camera;
  1295. gipd.xform[0] = to_cell.basis.elements[0][0];
  1296. gipd.xform[1] = to_cell.basis.elements[1][0];
  1297. gipd.xform[2] = to_cell.basis.elements[2][0];
  1298. gipd.xform[3] = 0;
  1299. gipd.xform[4] = to_cell.basis.elements[0][1];
  1300. gipd.xform[5] = to_cell.basis.elements[1][1];
  1301. gipd.xform[6] = to_cell.basis.elements[2][1];
  1302. gipd.xform[7] = 0;
  1303. gipd.xform[8] = to_cell.basis.elements[0][2];
  1304. gipd.xform[9] = to_cell.basis.elements[1][2];
  1305. gipd.xform[10] = to_cell.basis.elements[2][2];
  1306. gipd.xform[11] = 0;
  1307. gipd.xform[12] = to_cell.origin.x;
  1308. gipd.xform[13] = to_cell.origin.y;
  1309. gipd.xform[14] = to_cell.origin.z;
  1310. gipd.xform[15] = 1;
  1311. Vector3 bounds = storage->gi_probe_get_octree_size(base_probe);
  1312. gipd.bounds[0] = bounds.x;
  1313. gipd.bounds[1] = bounds.y;
  1314. gipd.bounds[2] = bounds.z;
  1315. gipd.dynamic_range = storage->gi_probe_get_dynamic_range(base_probe) * storage->gi_probe_get_energy(base_probe);
  1316. gipd.bias = storage->gi_probe_get_bias(base_probe);
  1317. gipd.normal_bias = storage->gi_probe_get_normal_bias(base_probe);
  1318. gipd.blend_ambient = !storage->gi_probe_is_interior(base_probe);
  1319. gipd.anisotropy_strength = 0;
  1320. gipd.ao = storage->gi_probe_get_ao(base_probe);
  1321. gipd.ao_size = Math::pow(storage->gi_probe_get_ao_size(base_probe), 4.0f);
  1322. }
  1323. }
  1324. if (texture == RID()) {
  1325. texture = storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE);
  1326. }
  1327. if (texture != rb->giprobe_textures[i]) {
  1328. giprobes_changed = true;
  1329. rb->giprobe_textures[i] = texture;
  1330. }
  1331. }
  1332. if (giprobes_changed) {
  1333. RD::get_singleton()->free(rb->gi_uniform_set);
  1334. rb->gi_uniform_set = RID();
  1335. }
  1336. if (p_gi_probe_cull_count > 0) {
  1337. RD::get_singleton()->buffer_update(gi_probe_buffer, 0, sizeof(GI::GIProbeData) * MIN(RenderBuffers::MAX_GIPROBES, p_gi_probe_cull_count), gi_probe_data, true);
  1338. }
  1339. }
  1340. if (rb->gi_uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(rb->gi_uniform_set)) {
  1341. Vector<RD::Uniform> uniforms;
  1342. {
  1343. RD::Uniform u;
  1344. u.binding = 1;
  1345. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1346. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  1347. if (rb->sdfgi && j < rb->sdfgi->cascades.size()) {
  1348. u.ids.push_back(rb->sdfgi->cascades[j].sdf_tex);
  1349. } else {
  1350. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  1351. }
  1352. }
  1353. uniforms.push_back(u);
  1354. }
  1355. {
  1356. RD::Uniform u;
  1357. u.binding = 2;
  1358. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1359. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  1360. if (rb->sdfgi && j < rb->sdfgi->cascades.size()) {
  1361. u.ids.push_back(rb->sdfgi->cascades[j].light_tex);
  1362. } else {
  1363. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  1364. }
  1365. }
  1366. uniforms.push_back(u);
  1367. }
  1368. {
  1369. RD::Uniform u;
  1370. u.binding = 3;
  1371. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1372. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  1373. if (rb->sdfgi && j < rb->sdfgi->cascades.size()) {
  1374. u.ids.push_back(rb->sdfgi->cascades[j].light_aniso_0_tex);
  1375. } else {
  1376. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  1377. }
  1378. }
  1379. uniforms.push_back(u);
  1380. }
  1381. {
  1382. RD::Uniform u;
  1383. u.binding = 4;
  1384. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1385. for (uint32_t j = 0; j < SDFGI::MAX_CASCADES; j++) {
  1386. if (rb->sdfgi && j < rb->sdfgi->cascades.size()) {
  1387. u.ids.push_back(rb->sdfgi->cascades[j].light_aniso_1_tex);
  1388. } else {
  1389. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  1390. }
  1391. }
  1392. uniforms.push_back(u);
  1393. }
  1394. {
  1395. RD::Uniform u;
  1396. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1397. u.binding = 5;
  1398. if (rb->sdfgi) {
  1399. u.ids.push_back(rb->sdfgi->occlusion_texture);
  1400. } else {
  1401. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  1402. }
  1403. uniforms.push_back(u);
  1404. }
  1405. {
  1406. RD::Uniform u;
  1407. u.type = RD::UNIFORM_TYPE_SAMPLER;
  1408. u.binding = 6;
  1409. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  1410. uniforms.push_back(u);
  1411. }
  1412. {
  1413. RD::Uniform u;
  1414. u.type = RD::UNIFORM_TYPE_SAMPLER;
  1415. u.binding = 7;
  1416. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  1417. uniforms.push_back(u);
  1418. }
  1419. {
  1420. RD::Uniform u;
  1421. u.type = RD::UNIFORM_TYPE_IMAGE;
  1422. u.binding = 9;
  1423. u.ids.push_back(p_ambient_buffer);
  1424. uniforms.push_back(u);
  1425. }
  1426. {
  1427. RD::Uniform u;
  1428. u.type = RD::UNIFORM_TYPE_IMAGE;
  1429. u.binding = 10;
  1430. u.ids.push_back(p_reflection_buffer);
  1431. uniforms.push_back(u);
  1432. }
  1433. {
  1434. RD::Uniform u;
  1435. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1436. u.binding = 11;
  1437. if (rb->sdfgi) {
  1438. u.ids.push_back(rb->sdfgi->lightprobe_texture);
  1439. } else {
  1440. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_2D_ARRAY_WHITE));
  1441. }
  1442. uniforms.push_back(u);
  1443. }
  1444. {
  1445. RD::Uniform u;
  1446. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1447. u.binding = 12;
  1448. u.ids.push_back(rb->depth_texture);
  1449. uniforms.push_back(u);
  1450. }
  1451. {
  1452. RD::Uniform u;
  1453. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1454. u.binding = 13;
  1455. u.ids.push_back(p_normal_roughness_buffer);
  1456. uniforms.push_back(u);
  1457. }
  1458. {
  1459. RD::Uniform u;
  1460. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1461. u.binding = 14;
  1462. RID buffer = p_gi_probe_buffer.is_valid() ? p_gi_probe_buffer : storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_BLACK);
  1463. u.ids.push_back(buffer);
  1464. uniforms.push_back(u);
  1465. }
  1466. {
  1467. RD::Uniform u;
  1468. u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  1469. u.binding = 15;
  1470. u.ids.push_back(gi.sdfgi_ubo);
  1471. uniforms.push_back(u);
  1472. }
  1473. {
  1474. RD::Uniform u;
  1475. u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  1476. u.binding = 16;
  1477. u.ids.push_back(rb->giprobe_buffer);
  1478. uniforms.push_back(u);
  1479. }
  1480. {
  1481. RD::Uniform u;
  1482. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1483. u.binding = 17;
  1484. for (int i = 0; i < RenderBuffers::MAX_GIPROBES; i++) {
  1485. u.ids.push_back(rb->giprobe_textures[i]);
  1486. }
  1487. uniforms.push_back(u);
  1488. }
  1489. rb->gi_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, gi.shader.version_get_shader(gi.shader_version, 0), 0);
  1490. }
  1491. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  1492. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, gi.pipelines[0]);
  1493. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->gi_uniform_set, 0);
  1494. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GI::PushConstant));
  1495. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->width, rb->height, 1, 8, 8, 1);
  1496. RD::get_singleton()->compute_list_end();
  1497. }
  1498. RID RasterizerSceneRD::sky_create() {
  1499. return sky_owner.make_rid(Sky());
  1500. }
  1501. void RasterizerSceneRD::_sky_invalidate(Sky *p_sky) {
  1502. if (!p_sky->dirty) {
  1503. p_sky->dirty = true;
  1504. p_sky->dirty_list = dirty_sky_list;
  1505. dirty_sky_list = p_sky;
  1506. }
  1507. }
  1508. void RasterizerSceneRD::sky_set_radiance_size(RID p_sky, int p_radiance_size) {
  1509. Sky *sky = sky_owner.getornull(p_sky);
  1510. ERR_FAIL_COND(!sky);
  1511. ERR_FAIL_COND(p_radiance_size < 32 || p_radiance_size > 2048);
  1512. if (sky->radiance_size == p_radiance_size) {
  1513. return;
  1514. }
  1515. sky->radiance_size = p_radiance_size;
  1516. if (sky->mode == RS::SKY_MODE_REALTIME && sky->radiance_size != 256) {
  1517. WARN_PRINT("Realtime Skies can only use a radiance size of 256. Radiance size will be set to 256 internally.");
  1518. sky->radiance_size = 256;
  1519. }
  1520. _sky_invalidate(sky);
  1521. if (sky->radiance.is_valid()) {
  1522. RD::get_singleton()->free(sky->radiance);
  1523. sky->radiance = RID();
  1524. }
  1525. _clear_reflection_data(sky->reflection);
  1526. }
  1527. void RasterizerSceneRD::sky_set_mode(RID p_sky, RS::SkyMode p_mode) {
  1528. Sky *sky = sky_owner.getornull(p_sky);
  1529. ERR_FAIL_COND(!sky);
  1530. if (sky->mode == p_mode) {
  1531. return;
  1532. }
  1533. sky->mode = p_mode;
  1534. if (sky->mode == RS::SKY_MODE_REALTIME && sky->radiance_size != 256) {
  1535. WARN_PRINT("Realtime Skies can only use a radiance size of 256. Radiance size will be set to 256 internally.");
  1536. sky_set_radiance_size(p_sky, 256);
  1537. }
  1538. _sky_invalidate(sky);
  1539. if (sky->radiance.is_valid()) {
  1540. RD::get_singleton()->free(sky->radiance);
  1541. sky->radiance = RID();
  1542. }
  1543. _clear_reflection_data(sky->reflection);
  1544. }
  1545. void RasterizerSceneRD::sky_set_material(RID p_sky, RID p_material) {
  1546. Sky *sky = sky_owner.getornull(p_sky);
  1547. ERR_FAIL_COND(!sky);
  1548. sky->material = p_material;
  1549. _sky_invalidate(sky);
  1550. }
  1551. Ref<Image> RasterizerSceneRD::sky_bake_panorama(RID p_sky, float p_energy, bool p_bake_irradiance, const Size2i &p_size) {
  1552. Sky *sky = sky_owner.getornull(p_sky);
  1553. ERR_FAIL_COND_V(!sky, Ref<Image>());
  1554. _update_dirty_skys();
  1555. if (sky->radiance.is_valid()) {
  1556. RD::TextureFormat tf;
  1557. tf.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  1558. tf.width = p_size.width;
  1559. tf.height = p_size.height;
  1560. tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
  1561. RID rad_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
  1562. storage->get_effects()->copy_cubemap_to_panorama(sky->radiance, rad_tex, p_size, p_bake_irradiance ? roughness_layers : 0, sky->reflection.layers.size() > 1);
  1563. Vector<uint8_t> data = RD::get_singleton()->texture_get_data(rad_tex, 0);
  1564. RD::get_singleton()->free(rad_tex);
  1565. Ref<Image> img;
  1566. img.instance();
  1567. img->create(p_size.width, p_size.height, false, Image::FORMAT_RGBAF, data);
  1568. for (int i = 0; i < p_size.width; i++) {
  1569. for (int j = 0; j < p_size.height; j++) {
  1570. Color c = img->get_pixel(i, j);
  1571. c.r *= p_energy;
  1572. c.g *= p_energy;
  1573. c.b *= p_energy;
  1574. img->set_pixel(i, j, c);
  1575. }
  1576. }
  1577. return img;
  1578. }
  1579. return Ref<Image>();
  1580. }
  1581. void RasterizerSceneRD::_update_dirty_skys() {
  1582. Sky *sky = dirty_sky_list;
  1583. while (sky) {
  1584. bool texture_set_dirty = false;
  1585. //update sky configuration if texture is missing
  1586. if (sky->radiance.is_null()) {
  1587. int mipmaps = Image::get_image_required_mipmaps(sky->radiance_size, sky->radiance_size, Image::FORMAT_RGBAH) + 1;
  1588. uint32_t w = sky->radiance_size, h = sky->radiance_size;
  1589. int layers = roughness_layers;
  1590. if (sky->mode == RS::SKY_MODE_REALTIME) {
  1591. layers = 8;
  1592. if (roughness_layers != 8) {
  1593. WARN_PRINT("When using REALTIME skies, roughness_layers should be set to 8 in the project settings for best quality reflections");
  1594. }
  1595. }
  1596. if (sky_use_cubemap_array) {
  1597. //array (higher quality, 6 times more memory)
  1598. RD::TextureFormat tf;
  1599. tf.array_layers = layers * 6;
  1600. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  1601. tf.type = RD::TEXTURE_TYPE_CUBE_ARRAY;
  1602. tf.mipmaps = mipmaps;
  1603. tf.width = w;
  1604. tf.height = h;
  1605. tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  1606. sky->radiance = RD::get_singleton()->texture_create(tf, RD::TextureView());
  1607. _update_reflection_data(sky->reflection, sky->radiance_size, mipmaps, true, sky->radiance, 0, sky->mode == RS::SKY_MODE_REALTIME);
  1608. } else {
  1609. //regular cubemap, lower quality (aliasing, less memory)
  1610. RD::TextureFormat tf;
  1611. tf.array_layers = 6;
  1612. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  1613. tf.type = RD::TEXTURE_TYPE_CUBE;
  1614. tf.mipmaps = MIN(mipmaps, layers);
  1615. tf.width = w;
  1616. tf.height = h;
  1617. tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  1618. sky->radiance = RD::get_singleton()->texture_create(tf, RD::TextureView());
  1619. _update_reflection_data(sky->reflection, sky->radiance_size, MIN(mipmaps, layers), false, sky->radiance, 0, sky->mode == RS::SKY_MODE_REALTIME);
  1620. }
  1621. texture_set_dirty = true;
  1622. }
  1623. // Create subpass buffers if they haven't been created already
  1624. if (sky->half_res_pass.is_null() && !RD::get_singleton()->texture_is_valid(sky->half_res_pass) && sky->screen_size.x >= 4 && sky->screen_size.y >= 4) {
  1625. RD::TextureFormat tformat;
  1626. tformat.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  1627. tformat.width = sky->screen_size.x / 2;
  1628. tformat.height = sky->screen_size.y / 2;
  1629. tformat.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  1630. tformat.type = RD::TEXTURE_TYPE_2D;
  1631. sky->half_res_pass = RD::get_singleton()->texture_create(tformat, RD::TextureView());
  1632. Vector<RID> texs;
  1633. texs.push_back(sky->half_res_pass);
  1634. sky->half_res_framebuffer = RD::get_singleton()->framebuffer_create(texs);
  1635. texture_set_dirty = true;
  1636. }
  1637. if (sky->quarter_res_pass.is_null() && !RD::get_singleton()->texture_is_valid(sky->quarter_res_pass) && sky->screen_size.x >= 4 && sky->screen_size.y >= 4) {
  1638. RD::TextureFormat tformat;
  1639. tformat.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  1640. tformat.width = sky->screen_size.x / 4;
  1641. tformat.height = sky->screen_size.y / 4;
  1642. tformat.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  1643. tformat.type = RD::TEXTURE_TYPE_2D;
  1644. sky->quarter_res_pass = RD::get_singleton()->texture_create(tformat, RD::TextureView());
  1645. Vector<RID> texs;
  1646. texs.push_back(sky->quarter_res_pass);
  1647. sky->quarter_res_framebuffer = RD::get_singleton()->framebuffer_create(texs);
  1648. texture_set_dirty = true;
  1649. }
  1650. if (texture_set_dirty) {
  1651. for (int i = 0; i < SKY_TEXTURE_SET_MAX; i++) {
  1652. if (sky->texture_uniform_sets[i].is_valid() && RD::get_singleton()->uniform_set_is_valid(sky->texture_uniform_sets[i])) {
  1653. RD::get_singleton()->free(sky->texture_uniform_sets[i]);
  1654. sky->texture_uniform_sets[i] = RID();
  1655. }
  1656. }
  1657. }
  1658. sky->reflection.dirty = true;
  1659. sky->processing_layer = 0;
  1660. Sky *next = sky->dirty_list;
  1661. sky->dirty_list = nullptr;
  1662. sky->dirty = false;
  1663. sky = next;
  1664. }
  1665. dirty_sky_list = nullptr;
  1666. }
  1667. RID RasterizerSceneRD::sky_get_radiance_texture_rd(RID p_sky) const {
  1668. Sky *sky = sky_owner.getornull(p_sky);
  1669. ERR_FAIL_COND_V(!sky, RID());
  1670. return sky->radiance;
  1671. }
  1672. RID RasterizerSceneRD::sky_get_radiance_uniform_set_rd(RID p_sky, RID p_shader, int p_set) const {
  1673. Sky *sky = sky_owner.getornull(p_sky);
  1674. ERR_FAIL_COND_V(!sky, RID());
  1675. if (sky->uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(sky->uniform_set)) {
  1676. sky->uniform_set = RID();
  1677. if (sky->radiance.is_valid()) {
  1678. Vector<RD::Uniform> uniforms;
  1679. {
  1680. RD::Uniform u;
  1681. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1682. u.binding = 0;
  1683. u.ids.push_back(sky->radiance);
  1684. uniforms.push_back(u);
  1685. }
  1686. sky->uniform_set = RD::get_singleton()->uniform_set_create(uniforms, p_shader, p_set);
  1687. }
  1688. }
  1689. return sky->uniform_set;
  1690. }
  1691. RID RasterizerSceneRD::_get_sky_textures(Sky *p_sky, SkyTextureSetVersion p_version) {
  1692. if (p_sky->texture_uniform_sets[p_version].is_valid() && RD::get_singleton()->uniform_set_is_valid(p_sky->texture_uniform_sets[p_version])) {
  1693. return p_sky->texture_uniform_sets[p_version];
  1694. }
  1695. Vector<RD::Uniform> uniforms;
  1696. {
  1697. RD::Uniform u;
  1698. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1699. u.binding = 0;
  1700. if (p_sky->radiance.is_valid() && p_version <= SKY_TEXTURE_SET_QUARTER_RES) {
  1701. u.ids.push_back(p_sky->radiance);
  1702. } else {
  1703. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
  1704. }
  1705. uniforms.push_back(u);
  1706. }
  1707. {
  1708. RD::Uniform u;
  1709. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1710. u.binding = 1; // half res
  1711. if (p_sky->half_res_pass.is_valid() && p_version != SKY_TEXTURE_SET_HALF_RES && p_version != SKY_TEXTURE_SET_CUBEMAP_HALF_RES) {
  1712. if (p_version >= SKY_TEXTURE_SET_CUBEMAP) {
  1713. u.ids.push_back(p_sky->reflection.layers[0].views[1]);
  1714. } else {
  1715. u.ids.push_back(p_sky->half_res_pass);
  1716. }
  1717. } else {
  1718. if (p_version < SKY_TEXTURE_SET_CUBEMAP) {
  1719. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_WHITE));
  1720. } else {
  1721. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
  1722. }
  1723. }
  1724. uniforms.push_back(u);
  1725. }
  1726. {
  1727. RD::Uniform u;
  1728. u.type = RD::UNIFORM_TYPE_TEXTURE;
  1729. u.binding = 2; // quarter res
  1730. if (p_sky->quarter_res_pass.is_valid() && p_version != SKY_TEXTURE_SET_QUARTER_RES && p_version != SKY_TEXTURE_SET_CUBEMAP_QUARTER_RES) {
  1731. if (p_version >= SKY_TEXTURE_SET_CUBEMAP) {
  1732. u.ids.push_back(p_sky->reflection.layers[0].views[2]);
  1733. } else {
  1734. u.ids.push_back(p_sky->quarter_res_pass);
  1735. }
  1736. } else {
  1737. if (p_version < SKY_TEXTURE_SET_CUBEMAP) {
  1738. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_WHITE));
  1739. } else {
  1740. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_CUBEMAP_BLACK));
  1741. }
  1742. }
  1743. uniforms.push_back(u);
  1744. }
  1745. p_sky->texture_uniform_sets[p_version] = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_TEXTURES);
  1746. return p_sky->texture_uniform_sets[p_version];
  1747. }
  1748. RID RasterizerSceneRD::sky_get_material(RID p_sky) const {
  1749. Sky *sky = sky_owner.getornull(p_sky);
  1750. ERR_FAIL_COND_V(!sky, RID());
  1751. return sky->material;
  1752. }
  1753. void RasterizerSceneRD::_draw_sky(bool p_can_continue_color, bool p_can_continue_depth, RID p_fb, RID p_environment, const CameraMatrix &p_projection, const Transform &p_transform) {
  1754. ERR_FAIL_COND(!is_environment(p_environment));
  1755. Sky *sky = sky_owner.getornull(environment_get_sky(p_environment));
  1756. ERR_FAIL_COND(!sky);
  1757. RID sky_material = sky_get_material(environment_get_sky(p_environment));
  1758. SkyMaterialData *material = nullptr;
  1759. if (sky_material.is_valid()) {
  1760. material = (SkyMaterialData *)storage->material_get_data(sky_material, RasterizerStorageRD::SHADER_TYPE_SKY);
  1761. if (!material || !material->shader_data->valid) {
  1762. material = nullptr;
  1763. }
  1764. }
  1765. if (!material) {
  1766. sky_material = sky_shader.default_material;
  1767. material = (SkyMaterialData *)storage->material_get_data(sky_material, RasterizerStorageRD::SHADER_TYPE_SKY);
  1768. }
  1769. ERR_FAIL_COND(!material);
  1770. SkyShaderData *shader_data = material->shader_data;
  1771. ERR_FAIL_COND(!shader_data);
  1772. Basis sky_transform = environment_get_sky_orientation(p_environment);
  1773. sky_transform.invert();
  1774. float multiplier = environment_get_bg_energy(p_environment);
  1775. float custom_fov = environment_get_sky_custom_fov(p_environment);
  1776. // Camera
  1777. CameraMatrix camera;
  1778. if (custom_fov) {
  1779. float near_plane = p_projection.get_z_near();
  1780. float far_plane = p_projection.get_z_far();
  1781. float aspect = p_projection.get_aspect();
  1782. camera.set_perspective(custom_fov, aspect, near_plane, far_plane);
  1783. } else {
  1784. camera = p_projection;
  1785. }
  1786. sky_transform = p_transform.basis * sky_transform;
  1787. if (shader_data->uses_quarter_res) {
  1788. RenderPipelineVertexFormatCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_QUARTER_RES];
  1789. RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_QUARTER_RES);
  1790. Vector<Color> clear_colors;
  1791. clear_colors.push_back(Color(0.0, 0.0, 0.0));
  1792. RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(sky->quarter_res_framebuffer, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
  1793. storage->get_effects()->render_sky(draw_list, time, sky->quarter_res_framebuffer, sky_scene_state.sampler_uniform_set, sky_scene_state.light_uniform_set, pipeline, material->uniform_set, texture_uniform_set, camera, sky_transform, multiplier, p_transform.origin);
  1794. RD::get_singleton()->draw_list_end();
  1795. }
  1796. if (shader_data->uses_half_res) {
  1797. RenderPipelineVertexFormatCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_HALF_RES];
  1798. RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_HALF_RES);
  1799. Vector<Color> clear_colors;
  1800. clear_colors.push_back(Color(0.0, 0.0, 0.0));
  1801. RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(sky->half_res_framebuffer, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CLEAR, RD::FINAL_ACTION_DISCARD, clear_colors);
  1802. storage->get_effects()->render_sky(draw_list, time, sky->half_res_framebuffer, sky_scene_state.sampler_uniform_set, sky_scene_state.light_uniform_set, pipeline, material->uniform_set, texture_uniform_set, camera, sky_transform, multiplier, p_transform.origin);
  1803. RD::get_singleton()->draw_list_end();
  1804. }
  1805. RenderPipelineVertexFormatCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_BACKGROUND];
  1806. RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_BACKGROUND);
  1807. RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(p_fb, RD::INITIAL_ACTION_CONTINUE, p_can_continue_color ? RD::FINAL_ACTION_CONTINUE : RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_CONTINUE, p_can_continue_depth ? RD::FINAL_ACTION_CONTINUE : RD::FINAL_ACTION_READ);
  1808. storage->get_effects()->render_sky(draw_list, time, p_fb, sky_scene_state.sampler_uniform_set, sky_scene_state.light_uniform_set, pipeline, material->uniform_set, texture_uniform_set, camera, sky_transform, multiplier, p_transform.origin);
  1809. RD::get_singleton()->draw_list_end();
  1810. }
  1811. void RasterizerSceneRD::_setup_sky(RID p_environment, const Vector3 &p_position, const Size2i p_screen_size) {
  1812. ERR_FAIL_COND(!is_environment(p_environment));
  1813. Sky *sky = sky_owner.getornull(environment_get_sky(p_environment));
  1814. ERR_FAIL_COND(!sky);
  1815. RID sky_material = sky_get_material(environment_get_sky(p_environment));
  1816. SkyMaterialData *material = nullptr;
  1817. if (sky_material.is_valid()) {
  1818. material = (SkyMaterialData *)storage->material_get_data(sky_material, RasterizerStorageRD::SHADER_TYPE_SKY);
  1819. if (!material || !material->shader_data->valid) {
  1820. material = nullptr;
  1821. }
  1822. }
  1823. if (!material) {
  1824. sky_material = sky_shader.default_material;
  1825. material = (SkyMaterialData *)storage->material_get_data(sky_material, RasterizerStorageRD::SHADER_TYPE_SKY);
  1826. }
  1827. ERR_FAIL_COND(!material);
  1828. SkyShaderData *shader_data = material->shader_data;
  1829. ERR_FAIL_COND(!shader_data);
  1830. // Invalidate supbass buffers if screen size changes
  1831. if (sky->screen_size != p_screen_size) {
  1832. sky->screen_size = p_screen_size;
  1833. sky->screen_size.x = sky->screen_size.x < 4 ? 4 : sky->screen_size.x;
  1834. sky->screen_size.y = sky->screen_size.y < 4 ? 4 : sky->screen_size.y;
  1835. if (shader_data->uses_half_res) {
  1836. if (sky->half_res_pass.is_valid()) {
  1837. RD::get_singleton()->free(sky->half_res_pass);
  1838. sky->half_res_pass = RID();
  1839. }
  1840. _sky_invalidate(sky);
  1841. }
  1842. if (shader_data->uses_quarter_res) {
  1843. if (sky->quarter_res_pass.is_valid()) {
  1844. RD::get_singleton()->free(sky->quarter_res_pass);
  1845. sky->quarter_res_pass = RID();
  1846. }
  1847. _sky_invalidate(sky);
  1848. }
  1849. }
  1850. // Create new subpass buffers if necessary
  1851. if ((shader_data->uses_half_res && sky->half_res_pass.is_null()) ||
  1852. (shader_data->uses_quarter_res && sky->quarter_res_pass.is_null()) ||
  1853. sky->radiance.is_null()) {
  1854. _sky_invalidate(sky);
  1855. _update_dirty_skys();
  1856. }
  1857. if (shader_data->uses_time && time - sky->prev_time > 0.00001) {
  1858. sky->prev_time = time;
  1859. sky->reflection.dirty = true;
  1860. RenderingServerRaster::redraw_request();
  1861. }
  1862. if (material != sky->prev_material) {
  1863. sky->prev_material = material;
  1864. sky->reflection.dirty = true;
  1865. }
  1866. if (material->uniform_set_updated) {
  1867. material->uniform_set_updated = false;
  1868. sky->reflection.dirty = true;
  1869. }
  1870. if (!p_position.is_equal_approx(sky->prev_position) && shader_data->uses_position) {
  1871. sky->prev_position = p_position;
  1872. sky->reflection.dirty = true;
  1873. }
  1874. if (shader_data->uses_light || sky_scene_state.light_uniform_set.is_null()) {
  1875. // Check whether the directional_light_buffer changes
  1876. bool light_data_dirty = false;
  1877. if (sky_scene_state.directional_light_count != sky_scene_state.last_frame_directional_light_count) {
  1878. light_data_dirty = true;
  1879. for (uint32_t i = sky_scene_state.directional_light_count; i < sky_scene_state.max_directional_lights; i++) {
  1880. sky_scene_state.directional_lights[i].enabled = false;
  1881. }
  1882. }
  1883. if (!light_data_dirty) {
  1884. for (uint32_t i = 0; i < sky_scene_state.directional_light_count; i++) {
  1885. if (sky_scene_state.directional_lights[i].direction[0] != sky_scene_state.last_frame_directional_lights[i].direction[0] ||
  1886. sky_scene_state.directional_lights[i].direction[1] != sky_scene_state.last_frame_directional_lights[i].direction[1] ||
  1887. sky_scene_state.directional_lights[i].direction[2] != sky_scene_state.last_frame_directional_lights[i].direction[2] ||
  1888. sky_scene_state.directional_lights[i].energy != sky_scene_state.last_frame_directional_lights[i].energy ||
  1889. sky_scene_state.directional_lights[i].color[0] != sky_scene_state.last_frame_directional_lights[i].color[0] ||
  1890. sky_scene_state.directional_lights[i].color[1] != sky_scene_state.last_frame_directional_lights[i].color[1] ||
  1891. sky_scene_state.directional_lights[i].color[2] != sky_scene_state.last_frame_directional_lights[i].color[2] ||
  1892. sky_scene_state.directional_lights[i].enabled != sky_scene_state.last_frame_directional_lights[i].enabled ||
  1893. sky_scene_state.directional_lights[i].size != sky_scene_state.last_frame_directional_lights[i].size) {
  1894. light_data_dirty = true;
  1895. break;
  1896. }
  1897. }
  1898. }
  1899. if (light_data_dirty || sky_scene_state.light_uniform_set.is_null()) {
  1900. RD::get_singleton()->buffer_update(sky_scene_state.directional_light_buffer, 0, sizeof(SkyDirectionalLightData) * sky_scene_state.max_directional_lights, sky_scene_state.directional_lights, true);
  1901. if (sky_scene_state.light_uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(sky_scene_state.light_uniform_set)) {
  1902. RD::get_singleton()->free(sky_scene_state.light_uniform_set);
  1903. }
  1904. Vector<RD::Uniform> uniforms;
  1905. {
  1906. RD::Uniform u;
  1907. u.binding = 0;
  1908. u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  1909. u.ids.push_back(sky_scene_state.directional_light_buffer);
  1910. uniforms.push_back(u);
  1911. }
  1912. sky_scene_state.light_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_LIGHTS);
  1913. RasterizerSceneRD::SkyDirectionalLightData *temp = sky_scene_state.last_frame_directional_lights;
  1914. sky_scene_state.last_frame_directional_lights = sky_scene_state.directional_lights;
  1915. sky_scene_state.directional_lights = temp;
  1916. sky_scene_state.last_frame_directional_light_count = sky_scene_state.directional_light_count;
  1917. sky->reflection.dirty = true;
  1918. }
  1919. }
  1920. }
  1921. void RasterizerSceneRD::_update_sky(RID p_environment, const CameraMatrix &p_projection, const Transform &p_transform) {
  1922. ERR_FAIL_COND(!is_environment(p_environment));
  1923. Sky *sky = sky_owner.getornull(environment_get_sky(p_environment));
  1924. ERR_FAIL_COND(!sky);
  1925. RID sky_material = sky_get_material(environment_get_sky(p_environment));
  1926. SkyMaterialData *material = nullptr;
  1927. if (sky_material.is_valid()) {
  1928. material = (SkyMaterialData *)storage->material_get_data(sky_material, RasterizerStorageRD::SHADER_TYPE_SKY);
  1929. if (!material || !material->shader_data->valid) {
  1930. material = nullptr;
  1931. }
  1932. }
  1933. if (!material) {
  1934. sky_material = sky_shader.default_material;
  1935. material = (SkyMaterialData *)storage->material_get_data(sky_material, RasterizerStorageRD::SHADER_TYPE_SKY);
  1936. }
  1937. ERR_FAIL_COND(!material);
  1938. SkyShaderData *shader_data = material->shader_data;
  1939. ERR_FAIL_COND(!shader_data);
  1940. float multiplier = environment_get_bg_energy(p_environment);
  1941. bool update_single_frame = sky->mode == RS::SKY_MODE_REALTIME || sky->mode == RS::SKY_MODE_QUALITY;
  1942. RS::SkyMode sky_mode = sky->mode;
  1943. if (sky_mode == RS::SKY_MODE_AUTOMATIC) {
  1944. if (shader_data->uses_time || shader_data->uses_position) {
  1945. update_single_frame = true;
  1946. sky_mode = RS::SKY_MODE_REALTIME;
  1947. } else if (shader_data->uses_light || shader_data->ubo_size > 0) {
  1948. update_single_frame = false;
  1949. sky_mode = RS::SKY_MODE_INCREMENTAL;
  1950. } else {
  1951. update_single_frame = true;
  1952. sky_mode = RS::SKY_MODE_QUALITY;
  1953. }
  1954. }
  1955. if (sky->processing_layer == 0 && sky_mode == RS::SKY_MODE_INCREMENTAL) {
  1956. // On the first frame after creating sky, rebuild in single frame
  1957. update_single_frame = true;
  1958. sky_mode = RS::SKY_MODE_QUALITY;
  1959. }
  1960. int max_processing_layer = sky_use_cubemap_array ? sky->reflection.layers.size() : sky->reflection.layers[0].mipmaps.size();
  1961. // Update radiance cubemap
  1962. if (sky->reflection.dirty && (sky->processing_layer >= max_processing_layer || update_single_frame)) {
  1963. static const Vector3 view_normals[6] = {
  1964. Vector3(+1, 0, 0),
  1965. Vector3(-1, 0, 0),
  1966. Vector3(0, +1, 0),
  1967. Vector3(0, -1, 0),
  1968. Vector3(0, 0, +1),
  1969. Vector3(0, 0, -1)
  1970. };
  1971. static const Vector3 view_up[6] = {
  1972. Vector3(0, -1, 0),
  1973. Vector3(0, -1, 0),
  1974. Vector3(0, 0, +1),
  1975. Vector3(0, 0, -1),
  1976. Vector3(0, -1, 0),
  1977. Vector3(0, -1, 0)
  1978. };
  1979. CameraMatrix cm;
  1980. cm.set_perspective(90, 1, 0.01, 10.0);
  1981. CameraMatrix correction;
  1982. correction.set_depth_correction(true);
  1983. cm = correction * cm;
  1984. if (shader_data->uses_quarter_res) {
  1985. RenderPipelineVertexFormatCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_CUBEMAP_QUARTER_RES];
  1986. Vector<Color> clear_colors;
  1987. clear_colors.push_back(Color(0.0, 0.0, 0.0));
  1988. RD::DrawListID cubemap_draw_list;
  1989. for (int i = 0; i < 6; i++) {
  1990. Transform local_view;
  1991. local_view.set_look_at(Vector3(0, 0, 0), view_normals[i], view_up[i]);
  1992. RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_CUBEMAP_QUARTER_RES);
  1993. cubemap_draw_list = RD::get_singleton()->draw_list_begin(sky->reflection.layers[0].mipmaps[2].framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD);
  1994. storage->get_effects()->render_sky(cubemap_draw_list, time, sky->reflection.layers[0].mipmaps[2].framebuffers[i], sky_scene_state.sampler_uniform_set, sky_scene_state.light_uniform_set, pipeline, material->uniform_set, texture_uniform_set, cm, local_view.basis, multiplier, p_transform.origin);
  1995. RD::get_singleton()->draw_list_end();
  1996. }
  1997. }
  1998. if (shader_data->uses_half_res) {
  1999. RenderPipelineVertexFormatCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_CUBEMAP_HALF_RES];
  2000. Vector<Color> clear_colors;
  2001. clear_colors.push_back(Color(0.0, 0.0, 0.0));
  2002. RD::DrawListID cubemap_draw_list;
  2003. for (int i = 0; i < 6; i++) {
  2004. Transform local_view;
  2005. local_view.set_look_at(Vector3(0, 0, 0), view_normals[i], view_up[i]);
  2006. RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_CUBEMAP_HALF_RES);
  2007. cubemap_draw_list = RD::get_singleton()->draw_list_begin(sky->reflection.layers[0].mipmaps[1].framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD);
  2008. storage->get_effects()->render_sky(cubemap_draw_list, time, sky->reflection.layers[0].mipmaps[1].framebuffers[i], sky_scene_state.sampler_uniform_set, sky_scene_state.light_uniform_set, pipeline, material->uniform_set, texture_uniform_set, cm, local_view.basis, multiplier, p_transform.origin);
  2009. RD::get_singleton()->draw_list_end();
  2010. }
  2011. }
  2012. RD::DrawListID cubemap_draw_list;
  2013. RenderPipelineVertexFormatCacheRD *pipeline = &shader_data->pipelines[SKY_VERSION_CUBEMAP];
  2014. for (int i = 0; i < 6; i++) {
  2015. Transform local_view;
  2016. local_view.set_look_at(Vector3(0, 0, 0), view_normals[i], view_up[i]);
  2017. RID texture_uniform_set = _get_sky_textures(sky, SKY_TEXTURE_SET_CUBEMAP);
  2018. cubemap_draw_list = RD::get_singleton()->draw_list_begin(sky->reflection.layers[0].mipmaps[0].framebuffers[i], RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_READ, RD::INITIAL_ACTION_KEEP, RD::FINAL_ACTION_DISCARD);
  2019. storage->get_effects()->render_sky(cubemap_draw_list, time, sky->reflection.layers[0].mipmaps[0].framebuffers[i], sky_scene_state.sampler_uniform_set, sky_scene_state.light_uniform_set, pipeline, material->uniform_set, texture_uniform_set, cm, local_view.basis, multiplier, p_transform.origin);
  2020. RD::get_singleton()->draw_list_end();
  2021. }
  2022. if (sky_mode == RS::SKY_MODE_REALTIME) {
  2023. _create_reflection_fast_filter(sky->reflection, sky_use_cubemap_array);
  2024. if (sky_use_cubemap_array) {
  2025. _update_reflection_mipmaps(sky->reflection, 0, sky->reflection.layers.size());
  2026. }
  2027. } else {
  2028. if (update_single_frame) {
  2029. for (int i = 1; i < max_processing_layer; i++) {
  2030. _create_reflection_importance_sample(sky->reflection, sky_use_cubemap_array, 10, i);
  2031. }
  2032. if (sky_use_cubemap_array) {
  2033. _update_reflection_mipmaps(sky->reflection, 0, sky->reflection.layers.size());
  2034. }
  2035. } else {
  2036. if (sky_use_cubemap_array) {
  2037. // Multi-Frame so just update the first array level
  2038. _update_reflection_mipmaps(sky->reflection, 0, 1);
  2039. }
  2040. }
  2041. sky->processing_layer = 1;
  2042. }
  2043. sky->reflection.dirty = false;
  2044. } else {
  2045. if (sky_mode == RS::SKY_MODE_INCREMENTAL && sky->processing_layer < max_processing_layer) {
  2046. _create_reflection_importance_sample(sky->reflection, sky_use_cubemap_array, 10, sky->processing_layer);
  2047. if (sky_use_cubemap_array) {
  2048. _update_reflection_mipmaps(sky->reflection, sky->processing_layer, sky->processing_layer + 1);
  2049. }
  2050. sky->processing_layer++;
  2051. }
  2052. }
  2053. }
  2054. /* SKY SHADER */
  2055. void RasterizerSceneRD::SkyShaderData::set_code(const String &p_code) {
  2056. //compile
  2057. code = p_code;
  2058. valid = false;
  2059. ubo_size = 0;
  2060. uniforms.clear();
  2061. if (code == String()) {
  2062. return; //just invalid, but no error
  2063. }
  2064. ShaderCompilerRD::GeneratedCode gen_code;
  2065. ShaderCompilerRD::IdentifierActions actions;
  2066. uses_time = false;
  2067. uses_half_res = false;
  2068. uses_quarter_res = false;
  2069. uses_position = false;
  2070. uses_light = false;
  2071. actions.render_mode_flags["use_half_res_pass"] = &uses_half_res;
  2072. actions.render_mode_flags["use_quarter_res_pass"] = &uses_quarter_res;
  2073. actions.usage_flag_pointers["TIME"] = &uses_time;
  2074. actions.usage_flag_pointers["POSITION"] = &uses_position;
  2075. actions.usage_flag_pointers["LIGHT0_ENABLED"] = &uses_light;
  2076. actions.usage_flag_pointers["LIGHT0_ENERGY"] = &uses_light;
  2077. actions.usage_flag_pointers["LIGHT0_DIRECTION"] = &uses_light;
  2078. actions.usage_flag_pointers["LIGHT0_COLOR"] = &uses_light;
  2079. actions.usage_flag_pointers["LIGHT0_SIZE"] = &uses_light;
  2080. actions.usage_flag_pointers["LIGHT1_ENABLED"] = &uses_light;
  2081. actions.usage_flag_pointers["LIGHT1_ENERGY"] = &uses_light;
  2082. actions.usage_flag_pointers["LIGHT1_DIRECTION"] = &uses_light;
  2083. actions.usage_flag_pointers["LIGHT1_COLOR"] = &uses_light;
  2084. actions.usage_flag_pointers["LIGHT1_SIZE"] = &uses_light;
  2085. actions.usage_flag_pointers["LIGHT2_ENABLED"] = &uses_light;
  2086. actions.usage_flag_pointers["LIGHT2_ENERGY"] = &uses_light;
  2087. actions.usage_flag_pointers["LIGHT2_DIRECTION"] = &uses_light;
  2088. actions.usage_flag_pointers["LIGHT2_COLOR"] = &uses_light;
  2089. actions.usage_flag_pointers["LIGHT2_SIZE"] = &uses_light;
  2090. actions.usage_flag_pointers["LIGHT3_ENABLED"] = &uses_light;
  2091. actions.usage_flag_pointers["LIGHT3_ENERGY"] = &uses_light;
  2092. actions.usage_flag_pointers["LIGHT3_DIRECTION"] = &uses_light;
  2093. actions.usage_flag_pointers["LIGHT3_COLOR"] = &uses_light;
  2094. actions.usage_flag_pointers["LIGHT3_SIZE"] = &uses_light;
  2095. actions.uniforms = &uniforms;
  2096. RasterizerSceneRD *scene_singleton = (RasterizerSceneRD *)RasterizerSceneRD::singleton;
  2097. Error err = scene_singleton->sky_shader.compiler.compile(RS::SHADER_SKY, code, &actions, path, gen_code);
  2098. ERR_FAIL_COND(err != OK);
  2099. if (version.is_null()) {
  2100. version = scene_singleton->sky_shader.shader.version_create();
  2101. }
  2102. #if 0
  2103. print_line("**compiling shader:");
  2104. print_line("**defines:\n");
  2105. for (int i = 0; i < gen_code.defines.size(); i++) {
  2106. print_line(gen_code.defines[i]);
  2107. }
  2108. print_line("\n**uniforms:\n" + gen_code.uniforms);
  2109. // print_line("\n**vertex_globals:\n" + gen_code.vertex_global);
  2110. // print_line("\n**vertex_code:\n" + gen_code.vertex);
  2111. print_line("\n**fragment_globals:\n" + gen_code.fragment_global);
  2112. print_line("\n**fragment_code:\n" + gen_code.fragment);
  2113. print_line("\n**light_code:\n" + gen_code.light);
  2114. #endif
  2115. scene_singleton->sky_shader.shader.version_set_code(version, gen_code.uniforms, gen_code.vertex_global, gen_code.vertex, gen_code.fragment_global, gen_code.light, gen_code.fragment, gen_code.defines);
  2116. ERR_FAIL_COND(!scene_singleton->sky_shader.shader.version_is_valid(version));
  2117. ubo_size = gen_code.uniform_total_size;
  2118. ubo_offsets = gen_code.uniform_offsets;
  2119. texture_uniforms = gen_code.texture_uniforms;
  2120. //update pipelines
  2121. for (int i = 0; i < SKY_VERSION_MAX; i++) {
  2122. RD::PipelineDepthStencilState depth_stencil_state;
  2123. depth_stencil_state.enable_depth_test = true;
  2124. depth_stencil_state.depth_compare_operator = RD::COMPARE_OP_LESS_OR_EQUAL;
  2125. RID shader_variant = scene_singleton->sky_shader.shader.version_get_shader(version, i);
  2126. pipelines[i].setup(shader_variant, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), depth_stencil_state, RD::PipelineColorBlendState::create_disabled(), 0);
  2127. }
  2128. valid = true;
  2129. }
  2130. void RasterizerSceneRD::SkyShaderData::set_default_texture_param(const StringName &p_name, RID p_texture) {
  2131. if (!p_texture.is_valid()) {
  2132. default_texture_params.erase(p_name);
  2133. } else {
  2134. default_texture_params[p_name] = p_texture;
  2135. }
  2136. }
  2137. void RasterizerSceneRD::SkyShaderData::get_param_list(List<PropertyInfo> *p_param_list) const {
  2138. Map<int, StringName> order;
  2139. for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = uniforms.front(); E; E = E->next()) {
  2140. if (E->get().scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_GLOBAL || E->get().scope == ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {
  2141. continue;
  2142. }
  2143. if (E->get().texture_order >= 0) {
  2144. order[E->get().texture_order + 100000] = E->key();
  2145. } else {
  2146. order[E->get().order] = E->key();
  2147. }
  2148. }
  2149. for (Map<int, StringName>::Element *E = order.front(); E; E = E->next()) {
  2150. PropertyInfo pi = ShaderLanguage::uniform_to_property_info(uniforms[E->get()]);
  2151. pi.name = E->get();
  2152. p_param_list->push_back(pi);
  2153. }
  2154. }
  2155. void RasterizerSceneRD::SkyShaderData::get_instance_param_list(List<RasterizerStorage::InstanceShaderParam> *p_param_list) const {
  2156. for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = uniforms.front(); E; E = E->next()) {
  2157. if (E->get().scope != ShaderLanguage::ShaderNode::Uniform::SCOPE_INSTANCE) {
  2158. continue;
  2159. }
  2160. RasterizerStorage::InstanceShaderParam p;
  2161. p.info = ShaderLanguage::uniform_to_property_info(E->get());
  2162. p.info.name = E->key(); //supply name
  2163. p.index = E->get().instance_index;
  2164. p.default_value = ShaderLanguage::constant_value_to_variant(E->get().default_value, E->get().type, E->get().hint);
  2165. p_param_list->push_back(p);
  2166. }
  2167. }
  2168. bool RasterizerSceneRD::SkyShaderData::is_param_texture(const StringName &p_param) const {
  2169. if (!uniforms.has(p_param)) {
  2170. return false;
  2171. }
  2172. return uniforms[p_param].texture_order >= 0;
  2173. }
  2174. bool RasterizerSceneRD::SkyShaderData::is_animated() const {
  2175. return false;
  2176. }
  2177. bool RasterizerSceneRD::SkyShaderData::casts_shadows() const {
  2178. return false;
  2179. }
  2180. Variant RasterizerSceneRD::SkyShaderData::get_default_parameter(const StringName &p_parameter) const {
  2181. if (uniforms.has(p_parameter)) {
  2182. ShaderLanguage::ShaderNode::Uniform uniform = uniforms[p_parameter];
  2183. Vector<ShaderLanguage::ConstantNode::Value> default_value = uniform.default_value;
  2184. return ShaderLanguage::constant_value_to_variant(default_value, uniform.type, uniform.hint);
  2185. }
  2186. return Variant();
  2187. }
  2188. RasterizerSceneRD::SkyShaderData::SkyShaderData() {
  2189. valid = false;
  2190. }
  2191. RasterizerSceneRD::SkyShaderData::~SkyShaderData() {
  2192. RasterizerSceneRD *scene_singleton = (RasterizerSceneRD *)RasterizerSceneRD::singleton;
  2193. ERR_FAIL_COND(!scene_singleton);
  2194. //pipeline variants will clear themselves if shader is gone
  2195. if (version.is_valid()) {
  2196. scene_singleton->sky_shader.shader.version_free(version);
  2197. }
  2198. }
  2199. RasterizerStorageRD::ShaderData *RasterizerSceneRD::_create_sky_shader_func() {
  2200. SkyShaderData *shader_data = memnew(SkyShaderData);
  2201. return shader_data;
  2202. }
  2203. void RasterizerSceneRD::SkyMaterialData::update_parameters(const Map<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) {
  2204. RasterizerSceneRD *scene_singleton = (RasterizerSceneRD *)RasterizerSceneRD::singleton;
  2205. uniform_set_updated = true;
  2206. if ((uint32_t)ubo_data.size() != shader_data->ubo_size) {
  2207. p_uniform_dirty = true;
  2208. if (uniform_buffer.is_valid()) {
  2209. RD::get_singleton()->free(uniform_buffer);
  2210. uniform_buffer = RID();
  2211. }
  2212. ubo_data.resize(shader_data->ubo_size);
  2213. if (ubo_data.size()) {
  2214. uniform_buffer = RD::get_singleton()->uniform_buffer_create(ubo_data.size());
  2215. memset(ubo_data.ptrw(), 0, ubo_data.size()); //clear
  2216. }
  2217. //clear previous uniform set
  2218. if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
  2219. RD::get_singleton()->free(uniform_set);
  2220. uniform_set = RID();
  2221. }
  2222. }
  2223. //check whether buffer changed
  2224. if (p_uniform_dirty && ubo_data.size()) {
  2225. update_uniform_buffer(shader_data->uniforms, shader_data->ubo_offsets.ptr(), p_parameters, ubo_data.ptrw(), ubo_data.size(), false);
  2226. RD::get_singleton()->buffer_update(uniform_buffer, 0, ubo_data.size(), ubo_data.ptrw());
  2227. }
  2228. uint32_t tex_uniform_count = shader_data->texture_uniforms.size();
  2229. if ((uint32_t)texture_cache.size() != tex_uniform_count) {
  2230. texture_cache.resize(tex_uniform_count);
  2231. p_textures_dirty = true;
  2232. //clear previous uniform set
  2233. if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
  2234. RD::get_singleton()->free(uniform_set);
  2235. uniform_set = RID();
  2236. }
  2237. }
  2238. if (p_textures_dirty && tex_uniform_count) {
  2239. update_textures(p_parameters, shader_data->default_texture_params, shader_data->texture_uniforms, texture_cache.ptrw(), true);
  2240. }
  2241. if (shader_data->ubo_size == 0 && shader_data->texture_uniforms.size() == 0) {
  2242. // This material does not require an uniform set, so don't create it.
  2243. return;
  2244. }
  2245. if (!p_textures_dirty && uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
  2246. //no reason to update uniform set, only UBO (or nothing) was needed to update
  2247. return;
  2248. }
  2249. Vector<RD::Uniform> uniforms;
  2250. {
  2251. if (shader_data->ubo_size) {
  2252. RD::Uniform u;
  2253. u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  2254. u.binding = 0;
  2255. u.ids.push_back(uniform_buffer);
  2256. uniforms.push_back(u);
  2257. }
  2258. const RID *textures = texture_cache.ptrw();
  2259. for (uint32_t i = 0; i < tex_uniform_count; i++) {
  2260. RD::Uniform u;
  2261. u.type = RD::UNIFORM_TYPE_TEXTURE;
  2262. u.binding = 1 + i;
  2263. u.ids.push_back(textures[i]);
  2264. uniforms.push_back(u);
  2265. }
  2266. }
  2267. uniform_set = RD::get_singleton()->uniform_set_create(uniforms, scene_singleton->sky_shader.shader.version_get_shader(shader_data->version, 0), SKY_SET_MATERIAL);
  2268. }
  2269. RasterizerSceneRD::SkyMaterialData::~SkyMaterialData() {
  2270. if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) {
  2271. RD::get_singleton()->free(uniform_set);
  2272. }
  2273. if (uniform_buffer.is_valid()) {
  2274. RD::get_singleton()->free(uniform_buffer);
  2275. }
  2276. }
  2277. RasterizerStorageRD::MaterialData *RasterizerSceneRD::_create_sky_material_func(SkyShaderData *p_shader) {
  2278. SkyMaterialData *material_data = memnew(SkyMaterialData);
  2279. material_data->shader_data = p_shader;
  2280. material_data->last_frame = false;
  2281. //update will happen later anyway so do nothing.
  2282. return material_data;
  2283. }
  2284. RID RasterizerSceneRD::environment_create() {
  2285. return environment_owner.make_rid(Environment());
  2286. }
  2287. void RasterizerSceneRD::environment_set_background(RID p_env, RS::EnvironmentBG p_bg) {
  2288. Environment *env = environment_owner.getornull(p_env);
  2289. ERR_FAIL_COND(!env);
  2290. env->background = p_bg;
  2291. }
  2292. void RasterizerSceneRD::environment_set_sky(RID p_env, RID p_sky) {
  2293. Environment *env = environment_owner.getornull(p_env);
  2294. ERR_FAIL_COND(!env);
  2295. env->sky = p_sky;
  2296. }
  2297. void RasterizerSceneRD::environment_set_sky_custom_fov(RID p_env, float p_scale) {
  2298. Environment *env = environment_owner.getornull(p_env);
  2299. ERR_FAIL_COND(!env);
  2300. env->sky_custom_fov = p_scale;
  2301. }
  2302. void RasterizerSceneRD::environment_set_sky_orientation(RID p_env, const Basis &p_orientation) {
  2303. Environment *env = environment_owner.getornull(p_env);
  2304. ERR_FAIL_COND(!env);
  2305. env->sky_orientation = p_orientation;
  2306. }
  2307. void RasterizerSceneRD::environment_set_bg_color(RID p_env, const Color &p_color) {
  2308. Environment *env = environment_owner.getornull(p_env);
  2309. ERR_FAIL_COND(!env);
  2310. env->bg_color = p_color;
  2311. }
  2312. void RasterizerSceneRD::environment_set_bg_energy(RID p_env, float p_energy) {
  2313. Environment *env = environment_owner.getornull(p_env);
  2314. ERR_FAIL_COND(!env);
  2315. env->bg_energy = p_energy;
  2316. }
  2317. void RasterizerSceneRD::environment_set_canvas_max_layer(RID p_env, int p_max_layer) {
  2318. Environment *env = environment_owner.getornull(p_env);
  2319. ERR_FAIL_COND(!env);
  2320. env->canvas_max_layer = p_max_layer;
  2321. }
  2322. void RasterizerSceneRD::environment_set_ambient_light(RID p_env, const Color &p_color, RS::EnvironmentAmbientSource p_ambient, float p_energy, float p_sky_contribution, RS::EnvironmentReflectionSource p_reflection_source, const Color &p_ao_color) {
  2323. Environment *env = environment_owner.getornull(p_env);
  2324. ERR_FAIL_COND(!env);
  2325. env->ambient_light = p_color;
  2326. env->ambient_source = p_ambient;
  2327. env->ambient_light_energy = p_energy;
  2328. env->ambient_sky_contribution = p_sky_contribution;
  2329. env->reflection_source = p_reflection_source;
  2330. env->ao_color = p_ao_color;
  2331. }
  2332. RS::EnvironmentBG RasterizerSceneRD::environment_get_background(RID p_env) const {
  2333. Environment *env = environment_owner.getornull(p_env);
  2334. ERR_FAIL_COND_V(!env, RS::ENV_BG_MAX);
  2335. return env->background;
  2336. }
  2337. RID RasterizerSceneRD::environment_get_sky(RID p_env) const {
  2338. Environment *env = environment_owner.getornull(p_env);
  2339. ERR_FAIL_COND_V(!env, RID());
  2340. return env->sky;
  2341. }
  2342. float RasterizerSceneRD::environment_get_sky_custom_fov(RID p_env) const {
  2343. Environment *env = environment_owner.getornull(p_env);
  2344. ERR_FAIL_COND_V(!env, 0);
  2345. return env->sky_custom_fov;
  2346. }
  2347. Basis RasterizerSceneRD::environment_get_sky_orientation(RID p_env) const {
  2348. Environment *env = environment_owner.getornull(p_env);
  2349. ERR_FAIL_COND_V(!env, Basis());
  2350. return env->sky_orientation;
  2351. }
  2352. Color RasterizerSceneRD::environment_get_bg_color(RID p_env) const {
  2353. Environment *env = environment_owner.getornull(p_env);
  2354. ERR_FAIL_COND_V(!env, Color());
  2355. return env->bg_color;
  2356. }
  2357. float RasterizerSceneRD::environment_get_bg_energy(RID p_env) const {
  2358. Environment *env = environment_owner.getornull(p_env);
  2359. ERR_FAIL_COND_V(!env, 0);
  2360. return env->bg_energy;
  2361. }
  2362. int RasterizerSceneRD::environment_get_canvas_max_layer(RID p_env) const {
  2363. Environment *env = environment_owner.getornull(p_env);
  2364. ERR_FAIL_COND_V(!env, 0);
  2365. return env->canvas_max_layer;
  2366. }
  2367. Color RasterizerSceneRD::environment_get_ambient_light_color(RID p_env) const {
  2368. Environment *env = environment_owner.getornull(p_env);
  2369. ERR_FAIL_COND_V(!env, Color());
  2370. return env->ambient_light;
  2371. }
  2372. RS::EnvironmentAmbientSource RasterizerSceneRD::environment_get_ambient_source(RID p_env) const {
  2373. Environment *env = environment_owner.getornull(p_env);
  2374. ERR_FAIL_COND_V(!env, RS::ENV_AMBIENT_SOURCE_BG);
  2375. return env->ambient_source;
  2376. }
  2377. float RasterizerSceneRD::environment_get_ambient_light_energy(RID p_env) const {
  2378. Environment *env = environment_owner.getornull(p_env);
  2379. ERR_FAIL_COND_V(!env, 0);
  2380. return env->ambient_light_energy;
  2381. }
  2382. float RasterizerSceneRD::environment_get_ambient_sky_contribution(RID p_env) const {
  2383. Environment *env = environment_owner.getornull(p_env);
  2384. ERR_FAIL_COND_V(!env, 0);
  2385. return env->ambient_sky_contribution;
  2386. }
  2387. RS::EnvironmentReflectionSource RasterizerSceneRD::environment_get_reflection_source(RID p_env) const {
  2388. Environment *env = environment_owner.getornull(p_env);
  2389. ERR_FAIL_COND_V(!env, RS::ENV_REFLECTION_SOURCE_DISABLED);
  2390. return env->reflection_source;
  2391. }
  2392. Color RasterizerSceneRD::environment_get_ao_color(RID p_env) const {
  2393. Environment *env = environment_owner.getornull(p_env);
  2394. ERR_FAIL_COND_V(!env, Color());
  2395. return env->ao_color;
  2396. }
  2397. void RasterizerSceneRD::environment_set_tonemap(RID p_env, RS::EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_scale) {
  2398. Environment *env = environment_owner.getornull(p_env);
  2399. ERR_FAIL_COND(!env);
  2400. env->exposure = p_exposure;
  2401. env->tone_mapper = p_tone_mapper;
  2402. if (!env->auto_exposure && p_auto_exposure) {
  2403. env->auto_exposure_version = ++auto_exposure_counter;
  2404. }
  2405. env->auto_exposure = p_auto_exposure;
  2406. env->white = p_white;
  2407. env->min_luminance = p_min_luminance;
  2408. env->max_luminance = p_max_luminance;
  2409. env->auto_exp_speed = p_auto_exp_speed;
  2410. env->auto_exp_scale = p_auto_exp_scale;
  2411. }
  2412. void RasterizerSceneRD::environment_set_glow(RID p_env, bool p_enable, int p_level_flags, float p_intensity, float p_strength, float p_mix, float p_bloom_threshold, RS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_threshold, float p_hdr_bleed_scale, float p_hdr_luminance_cap) {
  2413. Environment *env = environment_owner.getornull(p_env);
  2414. ERR_FAIL_COND(!env);
  2415. env->glow_enabled = p_enable;
  2416. env->glow_levels = p_level_flags;
  2417. env->glow_intensity = p_intensity;
  2418. env->glow_strength = p_strength;
  2419. env->glow_mix = p_mix;
  2420. env->glow_bloom = p_bloom_threshold;
  2421. env->glow_blend_mode = p_blend_mode;
  2422. env->glow_hdr_bleed_threshold = p_hdr_bleed_threshold;
  2423. env->glow_hdr_bleed_scale = p_hdr_bleed_scale;
  2424. env->glow_hdr_luminance_cap = p_hdr_luminance_cap;
  2425. }
  2426. void RasterizerSceneRD::environment_glow_set_use_bicubic_upscale(bool p_enable) {
  2427. glow_bicubic_upscale = p_enable;
  2428. }
  2429. void RasterizerSceneRD::environment_set_sdfgi(RID p_env, bool p_enable, RS::EnvironmentSDFGICascades p_cascades, float p_min_cell_size, RS::EnvironmentSDFGIYScale p_y_scale, bool p_use_occlusion, bool p_use_multibounce, bool p_read_sky, float p_energy, float p_normal_bias, float p_probe_bias) {
  2430. Environment *env = environment_owner.getornull(p_env);
  2431. ERR_FAIL_COND(!env);
  2432. env->sdfgi_enabled = p_enable;
  2433. env->sdfgi_cascades = p_cascades;
  2434. env->sdfgi_min_cell_size = p_min_cell_size;
  2435. env->sdfgi_use_occlusion = p_use_occlusion;
  2436. env->sdfgi_use_multibounce = p_use_multibounce;
  2437. env->sdfgi_read_sky_light = p_read_sky;
  2438. env->sdfgi_energy = p_energy;
  2439. env->sdfgi_normal_bias = p_normal_bias;
  2440. env->sdfgi_probe_bias = p_probe_bias;
  2441. env->sdfgi_y_scale = p_y_scale;
  2442. }
  2443. void RasterizerSceneRD::environment_set_sdfgi_ray_count(RS::EnvironmentSDFGIRayCount p_ray_count) {
  2444. sdfgi_ray_count = p_ray_count;
  2445. }
  2446. void RasterizerSceneRD::environment_set_sdfgi_frames_to_converge(RS::EnvironmentSDFGIFramesToConverge p_frames) {
  2447. sdfgi_frames_to_converge = p_frames;
  2448. }
  2449. void RasterizerSceneRD::environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_fade_int, float p_fade_out, float p_depth_tolerance) {
  2450. Environment *env = environment_owner.getornull(p_env);
  2451. ERR_FAIL_COND(!env);
  2452. env->ssr_enabled = p_enable;
  2453. env->ssr_max_steps = p_max_steps;
  2454. env->ssr_fade_in = p_fade_int;
  2455. env->ssr_fade_out = p_fade_out;
  2456. env->ssr_depth_tolerance = p_depth_tolerance;
  2457. }
  2458. void RasterizerSceneRD::environment_set_ssr_roughness_quality(RS::EnvironmentSSRRoughnessQuality p_quality) {
  2459. ssr_roughness_quality = p_quality;
  2460. }
  2461. RS::EnvironmentSSRRoughnessQuality RasterizerSceneRD::environment_get_ssr_roughness_quality() const {
  2462. return ssr_roughness_quality;
  2463. }
  2464. void RasterizerSceneRD::environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_intensity, float p_bias, float p_light_affect, float p_ao_channel_affect, RS::EnvironmentSSAOBlur p_blur, float p_bilateral_sharpness) {
  2465. Environment *env = environment_owner.getornull(p_env);
  2466. ERR_FAIL_COND(!env);
  2467. env->ssao_enabled = p_enable;
  2468. env->ssao_radius = p_radius;
  2469. env->ssao_intensity = p_intensity;
  2470. env->ssao_bias = p_bias;
  2471. env->ssao_direct_light_affect = p_light_affect;
  2472. env->ssao_ao_channel_affect = p_ao_channel_affect;
  2473. env->ssao_blur = p_blur;
  2474. }
  2475. void RasterizerSceneRD::environment_set_ssao_quality(RS::EnvironmentSSAOQuality p_quality, bool p_half_size) {
  2476. ssao_quality = p_quality;
  2477. ssao_half_size = p_half_size;
  2478. }
  2479. bool RasterizerSceneRD::environment_is_ssao_enabled(RID p_env) const {
  2480. Environment *env = environment_owner.getornull(p_env);
  2481. ERR_FAIL_COND_V(!env, false);
  2482. return env->ssao_enabled;
  2483. }
  2484. float RasterizerSceneRD::environment_get_ssao_ao_affect(RID p_env) const {
  2485. Environment *env = environment_owner.getornull(p_env);
  2486. ERR_FAIL_COND_V(!env, false);
  2487. return env->ssao_ao_channel_affect;
  2488. }
  2489. float RasterizerSceneRD::environment_get_ssao_light_affect(RID p_env) const {
  2490. Environment *env = environment_owner.getornull(p_env);
  2491. ERR_FAIL_COND_V(!env, false);
  2492. return env->ssao_direct_light_affect;
  2493. }
  2494. bool RasterizerSceneRD::environment_is_ssr_enabled(RID p_env) const {
  2495. Environment *env = environment_owner.getornull(p_env);
  2496. ERR_FAIL_COND_V(!env, false);
  2497. return env->ssr_enabled;
  2498. }
  2499. bool RasterizerSceneRD::environment_is_sdfgi_enabled(RID p_env) const {
  2500. Environment *env = environment_owner.getornull(p_env);
  2501. ERR_FAIL_COND_V(!env, false);
  2502. return env->sdfgi_enabled;
  2503. }
  2504. bool RasterizerSceneRD::is_environment(RID p_env) const {
  2505. return environment_owner.owns(p_env);
  2506. }
  2507. Ref<Image> RasterizerSceneRD::environment_bake_panorama(RID p_env, bool p_bake_irradiance, const Size2i &p_size) {
  2508. Environment *env = environment_owner.getornull(p_env);
  2509. ERR_FAIL_COND_V(!env, Ref<Image>());
  2510. if (env->background == RS::ENV_BG_CAMERA_FEED || env->background == RS::ENV_BG_CANVAS || env->background == RS::ENV_BG_KEEP) {
  2511. return Ref<Image>(); //nothing to bake
  2512. }
  2513. if (env->background == RS::ENV_BG_CLEAR_COLOR || env->background == RS::ENV_BG_COLOR) {
  2514. Color color;
  2515. if (env->background == RS::ENV_BG_CLEAR_COLOR) {
  2516. color = storage->get_default_clear_color();
  2517. } else {
  2518. color = env->bg_color;
  2519. }
  2520. color.r *= env->bg_energy;
  2521. color.g *= env->bg_energy;
  2522. color.b *= env->bg_energy;
  2523. Ref<Image> ret;
  2524. ret.instance();
  2525. ret->create(p_size.width, p_size.height, false, Image::FORMAT_RGBAF);
  2526. for (int i = 0; i < p_size.width; i++) {
  2527. for (int j = 0; j < p_size.height; j++) {
  2528. ret->set_pixel(i, j, color);
  2529. }
  2530. }
  2531. return ret;
  2532. }
  2533. if (env->background == RS::ENV_BG_SKY && env->sky.is_valid()) {
  2534. return sky_bake_panorama(env->sky, env->bg_energy, p_bake_irradiance, p_size);
  2535. }
  2536. return Ref<Image>();
  2537. }
  2538. ////////////////////////////////////////////////////////////
  2539. RID RasterizerSceneRD::reflection_atlas_create() {
  2540. ReflectionAtlas ra;
  2541. ra.count = GLOBAL_GET("rendering/quality/reflection_atlas/reflection_count");
  2542. ra.size = GLOBAL_GET("rendering/quality/reflection_atlas/reflection_size");
  2543. return reflection_atlas_owner.make_rid(ra);
  2544. }
  2545. void RasterizerSceneRD::reflection_atlas_set_size(RID p_ref_atlas, int p_reflection_size, int p_reflection_count) {
  2546. ReflectionAtlas *ra = reflection_atlas_owner.getornull(p_ref_atlas);
  2547. ERR_FAIL_COND(!ra);
  2548. if (ra->size == p_reflection_size && ra->count == p_reflection_count) {
  2549. return; //no changes
  2550. }
  2551. ra->size = p_reflection_size;
  2552. ra->count = p_reflection_count;
  2553. if (ra->reflection.is_valid()) {
  2554. //clear and invalidate everything
  2555. RD::get_singleton()->free(ra->reflection);
  2556. ra->reflection = RID();
  2557. RD::get_singleton()->free(ra->depth_buffer);
  2558. ra->depth_buffer = RID();
  2559. for (int i = 0; i < ra->reflections.size(); i++) {
  2560. _clear_reflection_data(ra->reflections.write[i].data);
  2561. if (ra->reflections[i].owner.is_null()) {
  2562. continue;
  2563. }
  2564. reflection_probe_release_atlas_index(ra->reflections[i].owner);
  2565. //rp->atlasindex clear
  2566. }
  2567. ra->reflections.clear();
  2568. }
  2569. }
  2570. ////////////////////////
  2571. RID RasterizerSceneRD::reflection_probe_instance_create(RID p_probe) {
  2572. ReflectionProbeInstance rpi;
  2573. rpi.probe = p_probe;
  2574. return reflection_probe_instance_owner.make_rid(rpi);
  2575. }
  2576. void RasterizerSceneRD::reflection_probe_instance_set_transform(RID p_instance, const Transform &p_transform) {
  2577. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2578. ERR_FAIL_COND(!rpi);
  2579. rpi->transform = p_transform;
  2580. rpi->dirty = true;
  2581. }
  2582. void RasterizerSceneRD::reflection_probe_release_atlas_index(RID p_instance) {
  2583. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2584. ERR_FAIL_COND(!rpi);
  2585. if (rpi->atlas.is_null()) {
  2586. return; //nothing to release
  2587. }
  2588. ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
  2589. ERR_FAIL_COND(!atlas);
  2590. ERR_FAIL_INDEX(rpi->atlas_index, atlas->reflections.size());
  2591. atlas->reflections.write[rpi->atlas_index].owner = RID();
  2592. rpi->atlas_index = -1;
  2593. rpi->atlas = RID();
  2594. }
  2595. bool RasterizerSceneRD::reflection_probe_instance_needs_redraw(RID p_instance) {
  2596. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2597. ERR_FAIL_COND_V(!rpi, false);
  2598. if (rpi->rendering) {
  2599. return false;
  2600. }
  2601. if (rpi->dirty) {
  2602. return true;
  2603. }
  2604. if (storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS) {
  2605. return true;
  2606. }
  2607. return rpi->atlas_index == -1;
  2608. }
  2609. bool RasterizerSceneRD::reflection_probe_instance_has_reflection(RID p_instance) {
  2610. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2611. ERR_FAIL_COND_V(!rpi, false);
  2612. return rpi->atlas.is_valid();
  2613. }
  2614. bool RasterizerSceneRD::reflection_probe_instance_begin_render(RID p_instance, RID p_reflection_atlas) {
  2615. ReflectionAtlas *atlas = reflection_atlas_owner.getornull(p_reflection_atlas);
  2616. ERR_FAIL_COND_V(!atlas, false);
  2617. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2618. ERR_FAIL_COND_V(!rpi, false);
  2619. if (storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS && atlas->reflection.is_valid() && atlas->size != 256) {
  2620. WARN_PRINT("ReflectionProbes set to UPDATE_ALWAYS must have an atlas size of 256. Please update the atlas size in the ProjectSettings.");
  2621. reflection_atlas_set_size(p_reflection_atlas, 256, atlas->count);
  2622. }
  2623. if (storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS && atlas->reflection.is_valid() && atlas->reflections[0].data.layers[0].mipmaps.size() != 8) {
  2624. // Invalidate reflection atlas, need to regenerate
  2625. RD::get_singleton()->free(atlas->reflection);
  2626. atlas->reflection = RID();
  2627. for (int i = 0; i < atlas->reflections.size(); i++) {
  2628. if (atlas->reflections[i].owner.is_null()) {
  2629. continue;
  2630. }
  2631. reflection_probe_release_atlas_index(atlas->reflections[i].owner);
  2632. }
  2633. atlas->reflections.clear();
  2634. }
  2635. if (atlas->reflection.is_null()) {
  2636. int mipmaps = MIN(roughness_layers, Image::get_image_required_mipmaps(atlas->size, atlas->size, Image::FORMAT_RGBAH) + 1);
  2637. mipmaps = storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS ? 8 : mipmaps; // always use 8 mipmaps with real time filtering
  2638. {
  2639. //reflection atlas was unused, create:
  2640. RD::TextureFormat tf;
  2641. tf.array_layers = 6 * atlas->count;
  2642. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  2643. tf.type = RD::TEXTURE_TYPE_CUBE_ARRAY;
  2644. tf.mipmaps = mipmaps;
  2645. tf.width = atlas->size;
  2646. tf.height = atlas->size;
  2647. tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  2648. atlas->reflection = RD::get_singleton()->texture_create(tf, RD::TextureView());
  2649. }
  2650. {
  2651. RD::TextureFormat tf;
  2652. tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
  2653. tf.width = atlas->size;
  2654. tf.height = atlas->size;
  2655. tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
  2656. atlas->depth_buffer = RD::get_singleton()->texture_create(tf, RD::TextureView());
  2657. }
  2658. atlas->reflections.resize(atlas->count);
  2659. for (int i = 0; i < atlas->count; i++) {
  2660. _update_reflection_data(atlas->reflections.write[i].data, atlas->size, mipmaps, false, atlas->reflection, i * 6, storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS);
  2661. for (int j = 0; j < 6; j++) {
  2662. Vector<RID> fb;
  2663. fb.push_back(atlas->reflections.write[i].data.layers[0].mipmaps[0].views[j]);
  2664. fb.push_back(atlas->depth_buffer);
  2665. atlas->reflections.write[i].fbs[j] = RD::get_singleton()->framebuffer_create(fb);
  2666. }
  2667. }
  2668. Vector<RID> fb;
  2669. fb.push_back(atlas->depth_buffer);
  2670. atlas->depth_fb = RD::get_singleton()->framebuffer_create(fb);
  2671. }
  2672. if (rpi->atlas_index == -1) {
  2673. for (int i = 0; i < atlas->reflections.size(); i++) {
  2674. if (atlas->reflections[i].owner.is_null()) {
  2675. rpi->atlas_index = i;
  2676. break;
  2677. }
  2678. }
  2679. //find the one used last
  2680. if (rpi->atlas_index == -1) {
  2681. //everything is in use, find the one least used via LRU
  2682. uint64_t pass_min = 0;
  2683. for (int i = 0; i < atlas->reflections.size(); i++) {
  2684. ReflectionProbeInstance *rpi2 = reflection_probe_instance_owner.getornull(atlas->reflections[i].owner);
  2685. if (rpi2->last_pass < pass_min) {
  2686. pass_min = rpi2->last_pass;
  2687. rpi->atlas_index = i;
  2688. }
  2689. }
  2690. }
  2691. }
  2692. rpi->atlas = p_reflection_atlas;
  2693. rpi->rendering = true;
  2694. rpi->dirty = false;
  2695. rpi->processing_layer = 1;
  2696. rpi->processing_side = 0;
  2697. return true;
  2698. }
  2699. bool RasterizerSceneRD::reflection_probe_instance_postprocess_step(RID p_instance) {
  2700. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2701. ERR_FAIL_COND_V(!rpi, false);
  2702. ERR_FAIL_COND_V(!rpi->rendering, false);
  2703. ERR_FAIL_COND_V(rpi->atlas.is_null(), false);
  2704. ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
  2705. if (!atlas || rpi->atlas_index == -1) {
  2706. //does not belong to an atlas anymore, cancel (was removed from atlas or atlas changed while rendering)
  2707. rpi->rendering = false;
  2708. return false;
  2709. }
  2710. if (storage->reflection_probe_get_update_mode(rpi->probe) == RS::REFLECTION_PROBE_UPDATE_ALWAYS) {
  2711. // Using real time reflections, all roughness is done in one step
  2712. _create_reflection_fast_filter(atlas->reflections.write[rpi->atlas_index].data, false);
  2713. rpi->rendering = false;
  2714. rpi->processing_side = 0;
  2715. rpi->processing_layer = 1;
  2716. return true;
  2717. }
  2718. if (rpi->processing_layer > 1) {
  2719. _create_reflection_importance_sample(atlas->reflections.write[rpi->atlas_index].data, false, 10, rpi->processing_layer);
  2720. rpi->processing_layer++;
  2721. if (rpi->processing_layer == atlas->reflections[rpi->atlas_index].data.layers[0].mipmaps.size()) {
  2722. rpi->rendering = false;
  2723. rpi->processing_side = 0;
  2724. rpi->processing_layer = 1;
  2725. return true;
  2726. }
  2727. return false;
  2728. } else {
  2729. _create_reflection_importance_sample(atlas->reflections.write[rpi->atlas_index].data, false, rpi->processing_side, rpi->processing_layer);
  2730. }
  2731. rpi->processing_side++;
  2732. if (rpi->processing_side == 6) {
  2733. rpi->processing_side = 0;
  2734. rpi->processing_layer++;
  2735. }
  2736. return false;
  2737. }
  2738. uint32_t RasterizerSceneRD::reflection_probe_instance_get_resolution(RID p_instance) {
  2739. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2740. ERR_FAIL_COND_V(!rpi, 0);
  2741. ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
  2742. ERR_FAIL_COND_V(!atlas, 0);
  2743. return atlas->size;
  2744. }
  2745. RID RasterizerSceneRD::reflection_probe_instance_get_framebuffer(RID p_instance, int p_index) {
  2746. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2747. ERR_FAIL_COND_V(!rpi, RID());
  2748. ERR_FAIL_INDEX_V(p_index, 6, RID());
  2749. ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
  2750. ERR_FAIL_COND_V(!atlas, RID());
  2751. return atlas->reflections[rpi->atlas_index].fbs[p_index];
  2752. }
  2753. RID RasterizerSceneRD::reflection_probe_instance_get_depth_framebuffer(RID p_instance, int p_index) {
  2754. ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
  2755. ERR_FAIL_COND_V(!rpi, RID());
  2756. ERR_FAIL_INDEX_V(p_index, 6, RID());
  2757. ReflectionAtlas *atlas = reflection_atlas_owner.getornull(rpi->atlas);
  2758. ERR_FAIL_COND_V(!atlas, RID());
  2759. return atlas->depth_fb;
  2760. }
  2761. ///////////////////////////////////////////////////////////
  2762. RID RasterizerSceneRD::shadow_atlas_create() {
  2763. return shadow_atlas_owner.make_rid(ShadowAtlas());
  2764. }
  2765. void RasterizerSceneRD::shadow_atlas_set_size(RID p_atlas, int p_size) {
  2766. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
  2767. ERR_FAIL_COND(!shadow_atlas);
  2768. ERR_FAIL_COND(p_size < 0);
  2769. p_size = next_power_of_2(p_size);
  2770. if (p_size == shadow_atlas->size) {
  2771. return;
  2772. }
  2773. // erasing atlas
  2774. if (shadow_atlas->depth.is_valid()) {
  2775. RD::get_singleton()->free(shadow_atlas->depth);
  2776. shadow_atlas->depth = RID();
  2777. }
  2778. for (int i = 0; i < 4; i++) {
  2779. //clear subdivisions
  2780. shadow_atlas->quadrants[i].shadows.resize(0);
  2781. shadow_atlas->quadrants[i].shadows.resize(1 << shadow_atlas->quadrants[i].subdivision);
  2782. }
  2783. //erase shadow atlas reference from lights
  2784. for (Map<RID, uint32_t>::Element *E = shadow_atlas->shadow_owners.front(); E; E = E->next()) {
  2785. LightInstance *li = light_instance_owner.getornull(E->key());
  2786. ERR_CONTINUE(!li);
  2787. li->shadow_atlases.erase(p_atlas);
  2788. }
  2789. //clear owners
  2790. shadow_atlas->shadow_owners.clear();
  2791. shadow_atlas->size = p_size;
  2792. if (shadow_atlas->size) {
  2793. RD::TextureFormat tf;
  2794. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  2795. tf.width = shadow_atlas->size;
  2796. tf.height = shadow_atlas->size;
  2797. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  2798. shadow_atlas->depth = RD::get_singleton()->texture_create(tf, RD::TextureView());
  2799. }
  2800. }
  2801. void RasterizerSceneRD::shadow_atlas_set_quadrant_subdivision(RID p_atlas, int p_quadrant, int p_subdivision) {
  2802. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
  2803. ERR_FAIL_COND(!shadow_atlas);
  2804. ERR_FAIL_INDEX(p_quadrant, 4);
  2805. ERR_FAIL_INDEX(p_subdivision, 16384);
  2806. uint32_t subdiv = next_power_of_2(p_subdivision);
  2807. if (subdiv & 0xaaaaaaaa) { //sqrt(subdiv) must be integer
  2808. subdiv <<= 1;
  2809. }
  2810. subdiv = int(Math::sqrt((float)subdiv));
  2811. //obtain the number that will be x*x
  2812. if (shadow_atlas->quadrants[p_quadrant].subdivision == subdiv) {
  2813. return;
  2814. }
  2815. //erase all data from quadrant
  2816. for (int i = 0; i < shadow_atlas->quadrants[p_quadrant].shadows.size(); i++) {
  2817. if (shadow_atlas->quadrants[p_quadrant].shadows[i].owner.is_valid()) {
  2818. shadow_atlas->shadow_owners.erase(shadow_atlas->quadrants[p_quadrant].shadows[i].owner);
  2819. LightInstance *li = light_instance_owner.getornull(shadow_atlas->quadrants[p_quadrant].shadows[i].owner);
  2820. ERR_CONTINUE(!li);
  2821. li->shadow_atlases.erase(p_atlas);
  2822. }
  2823. }
  2824. shadow_atlas->quadrants[p_quadrant].shadows.resize(0);
  2825. shadow_atlas->quadrants[p_quadrant].shadows.resize(subdiv * subdiv);
  2826. shadow_atlas->quadrants[p_quadrant].subdivision = subdiv;
  2827. //cache the smallest subdiv (for faster allocation in light update)
  2828. shadow_atlas->smallest_subdiv = 1 << 30;
  2829. for (int i = 0; i < 4; i++) {
  2830. if (shadow_atlas->quadrants[i].subdivision) {
  2831. shadow_atlas->smallest_subdiv = MIN(shadow_atlas->smallest_subdiv, shadow_atlas->quadrants[i].subdivision);
  2832. }
  2833. }
  2834. if (shadow_atlas->smallest_subdiv == 1 << 30) {
  2835. shadow_atlas->smallest_subdiv = 0;
  2836. }
  2837. //resort the size orders, simple bublesort for 4 elements..
  2838. int swaps = 0;
  2839. do {
  2840. swaps = 0;
  2841. for (int i = 0; i < 3; i++) {
  2842. if (shadow_atlas->quadrants[shadow_atlas->size_order[i]].subdivision < shadow_atlas->quadrants[shadow_atlas->size_order[i + 1]].subdivision) {
  2843. SWAP(shadow_atlas->size_order[i], shadow_atlas->size_order[i + 1]);
  2844. swaps++;
  2845. }
  2846. }
  2847. } while (swaps > 0);
  2848. }
  2849. bool RasterizerSceneRD::_shadow_atlas_find_shadow(ShadowAtlas *shadow_atlas, int *p_in_quadrants, int p_quadrant_count, int p_current_subdiv, uint64_t p_tick, int &r_quadrant, int &r_shadow) {
  2850. for (int i = p_quadrant_count - 1; i >= 0; i--) {
  2851. int qidx = p_in_quadrants[i];
  2852. if (shadow_atlas->quadrants[qidx].subdivision == (uint32_t)p_current_subdiv) {
  2853. return false;
  2854. }
  2855. //look for an empty space
  2856. int sc = shadow_atlas->quadrants[qidx].shadows.size();
  2857. ShadowAtlas::Quadrant::Shadow *sarr = shadow_atlas->quadrants[qidx].shadows.ptrw();
  2858. int found_free_idx = -1; //found a free one
  2859. int found_used_idx = -1; //found existing one, must steal it
  2860. uint64_t min_pass = 0; // pass of the existing one, try to use the least recently used one (LRU fashion)
  2861. for (int j = 0; j < sc; j++) {
  2862. if (!sarr[j].owner.is_valid()) {
  2863. found_free_idx = j;
  2864. break;
  2865. }
  2866. LightInstance *sli = light_instance_owner.getornull(sarr[j].owner);
  2867. ERR_CONTINUE(!sli);
  2868. if (sli->last_scene_pass != scene_pass) {
  2869. //was just allocated, don't kill it so soon, wait a bit..
  2870. if (p_tick - sarr[j].alloc_tick < shadow_atlas_realloc_tolerance_msec) {
  2871. continue;
  2872. }
  2873. if (found_used_idx == -1 || sli->last_scene_pass < min_pass) {
  2874. found_used_idx = j;
  2875. min_pass = sli->last_scene_pass;
  2876. }
  2877. }
  2878. }
  2879. if (found_free_idx == -1 && found_used_idx == -1) {
  2880. continue; //nothing found
  2881. }
  2882. if (found_free_idx == -1 && found_used_idx != -1) {
  2883. found_free_idx = found_used_idx;
  2884. }
  2885. r_quadrant = qidx;
  2886. r_shadow = found_free_idx;
  2887. return true;
  2888. }
  2889. return false;
  2890. }
  2891. bool RasterizerSceneRD::shadow_atlas_update_light(RID p_atlas, RID p_light_intance, float p_coverage, uint64_t p_light_version) {
  2892. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
  2893. ERR_FAIL_COND_V(!shadow_atlas, false);
  2894. LightInstance *li = light_instance_owner.getornull(p_light_intance);
  2895. ERR_FAIL_COND_V(!li, false);
  2896. if (shadow_atlas->size == 0 || shadow_atlas->smallest_subdiv == 0) {
  2897. return false;
  2898. }
  2899. uint32_t quad_size = shadow_atlas->size >> 1;
  2900. int desired_fit = MIN(quad_size / shadow_atlas->smallest_subdiv, next_power_of_2(quad_size * p_coverage));
  2901. int valid_quadrants[4];
  2902. int valid_quadrant_count = 0;
  2903. int best_size = -1; //best size found
  2904. int best_subdiv = -1; //subdiv for the best size
  2905. //find the quadrants this fits into, and the best possible size it can fit into
  2906. for (int i = 0; i < 4; i++) {
  2907. int q = shadow_atlas->size_order[i];
  2908. int sd = shadow_atlas->quadrants[q].subdivision;
  2909. if (sd == 0) {
  2910. continue; //unused
  2911. }
  2912. int max_fit = quad_size / sd;
  2913. if (best_size != -1 && max_fit > best_size) {
  2914. break; //too large
  2915. }
  2916. valid_quadrants[valid_quadrant_count++] = q;
  2917. best_subdiv = sd;
  2918. if (max_fit >= desired_fit) {
  2919. best_size = max_fit;
  2920. }
  2921. }
  2922. ERR_FAIL_COND_V(valid_quadrant_count == 0, false);
  2923. uint64_t tick = OS::get_singleton()->get_ticks_msec();
  2924. //see if it already exists
  2925. if (shadow_atlas->shadow_owners.has(p_light_intance)) {
  2926. //it does!
  2927. uint32_t key = shadow_atlas->shadow_owners[p_light_intance];
  2928. uint32_t q = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
  2929. uint32_t s = key & ShadowAtlas::SHADOW_INDEX_MASK;
  2930. bool should_realloc = shadow_atlas->quadrants[q].subdivision != (uint32_t)best_subdiv && (shadow_atlas->quadrants[q].shadows[s].alloc_tick - tick > shadow_atlas_realloc_tolerance_msec);
  2931. bool should_redraw = shadow_atlas->quadrants[q].shadows[s].version != p_light_version;
  2932. if (!should_realloc) {
  2933. shadow_atlas->quadrants[q].shadows.write[s].version = p_light_version;
  2934. //already existing, see if it should redraw or it's just OK
  2935. return should_redraw;
  2936. }
  2937. int new_quadrant, new_shadow;
  2938. //find a better place
  2939. if (_shadow_atlas_find_shadow(shadow_atlas, valid_quadrants, valid_quadrant_count, shadow_atlas->quadrants[q].subdivision, tick, new_quadrant, new_shadow)) {
  2940. //found a better place!
  2941. ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows.write[new_shadow];
  2942. if (sh->owner.is_valid()) {
  2943. //is taken, but is invalid, erasing it
  2944. shadow_atlas->shadow_owners.erase(sh->owner);
  2945. LightInstance *sli = light_instance_owner.getornull(sh->owner);
  2946. sli->shadow_atlases.erase(p_atlas);
  2947. }
  2948. //erase previous
  2949. shadow_atlas->quadrants[q].shadows.write[s].version = 0;
  2950. shadow_atlas->quadrants[q].shadows.write[s].owner = RID();
  2951. sh->owner = p_light_intance;
  2952. sh->alloc_tick = tick;
  2953. sh->version = p_light_version;
  2954. li->shadow_atlases.insert(p_atlas);
  2955. //make new key
  2956. key = new_quadrant << ShadowAtlas::QUADRANT_SHIFT;
  2957. key |= new_shadow;
  2958. //update it in map
  2959. shadow_atlas->shadow_owners[p_light_intance] = key;
  2960. //make it dirty, as it should redraw anyway
  2961. return true;
  2962. }
  2963. //no better place for this shadow found, keep current
  2964. //already existing, see if it should redraw or it's just OK
  2965. shadow_atlas->quadrants[q].shadows.write[s].version = p_light_version;
  2966. return should_redraw;
  2967. }
  2968. int new_quadrant, new_shadow;
  2969. //find a better place
  2970. if (_shadow_atlas_find_shadow(shadow_atlas, valid_quadrants, valid_quadrant_count, -1, tick, new_quadrant, new_shadow)) {
  2971. //found a better place!
  2972. ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows.write[new_shadow];
  2973. if (sh->owner.is_valid()) {
  2974. //is taken, but is invalid, erasing it
  2975. shadow_atlas->shadow_owners.erase(sh->owner);
  2976. LightInstance *sli = light_instance_owner.getornull(sh->owner);
  2977. sli->shadow_atlases.erase(p_atlas);
  2978. }
  2979. sh->owner = p_light_intance;
  2980. sh->alloc_tick = tick;
  2981. sh->version = p_light_version;
  2982. li->shadow_atlases.insert(p_atlas);
  2983. //make new key
  2984. uint32_t key = new_quadrant << ShadowAtlas::QUADRANT_SHIFT;
  2985. key |= new_shadow;
  2986. //update it in map
  2987. shadow_atlas->shadow_owners[p_light_intance] = key;
  2988. //make it dirty, as it should redraw anyway
  2989. return true;
  2990. }
  2991. //no place to allocate this light, apologies
  2992. return false;
  2993. }
  2994. void RasterizerSceneRD::directional_shadow_atlas_set_size(int p_size) {
  2995. p_size = nearest_power_of_2_templated(p_size);
  2996. if (directional_shadow.size == p_size) {
  2997. return;
  2998. }
  2999. directional_shadow.size = p_size;
  3000. if (directional_shadow.depth.is_valid()) {
  3001. RD::get_singleton()->free(directional_shadow.depth);
  3002. directional_shadow.depth = RID();
  3003. }
  3004. if (p_size > 0) {
  3005. RD::TextureFormat tf;
  3006. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  3007. tf.width = p_size;
  3008. tf.height = p_size;
  3009. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  3010. directional_shadow.depth = RD::get_singleton()->texture_create(tf, RD::TextureView());
  3011. }
  3012. _base_uniforms_changed();
  3013. }
  3014. void RasterizerSceneRD::set_directional_shadow_count(int p_count) {
  3015. directional_shadow.light_count = p_count;
  3016. directional_shadow.current_light = 0;
  3017. }
  3018. static Rect2i _get_directional_shadow_rect(int p_size, int p_shadow_count, int p_shadow_index) {
  3019. int split_h = 1;
  3020. int split_v = 1;
  3021. while (split_h * split_v < p_shadow_count) {
  3022. if (split_h == split_v) {
  3023. split_h <<= 1;
  3024. } else {
  3025. split_v <<= 1;
  3026. }
  3027. }
  3028. Rect2i rect(0, 0, p_size, p_size);
  3029. rect.size.width /= split_h;
  3030. rect.size.height /= split_v;
  3031. rect.position.x = rect.size.width * (p_shadow_index % split_h);
  3032. rect.position.y = rect.size.height * (p_shadow_index / split_h);
  3033. return rect;
  3034. }
  3035. int RasterizerSceneRD::get_directional_light_shadow_size(RID p_light_intance) {
  3036. ERR_FAIL_COND_V(directional_shadow.light_count == 0, 0);
  3037. Rect2i r = _get_directional_shadow_rect(directional_shadow.size, directional_shadow.light_count, 0);
  3038. LightInstance *light_instance = light_instance_owner.getornull(p_light_intance);
  3039. ERR_FAIL_COND_V(!light_instance, 0);
  3040. switch (storage->light_directional_get_shadow_mode(light_instance->light)) {
  3041. case RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL:
  3042. break; //none
  3043. case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
  3044. r.size.height /= 2;
  3045. break;
  3046. case RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS:
  3047. r.size /= 2;
  3048. break;
  3049. }
  3050. return MAX(r.size.width, r.size.height);
  3051. }
  3052. //////////////////////////////////////////////////
  3053. RID RasterizerSceneRD::camera_effects_create() {
  3054. return camera_effects_owner.make_rid(CameraEffects());
  3055. }
  3056. void RasterizerSceneRD::camera_effects_set_dof_blur_quality(RS::DOFBlurQuality p_quality, bool p_use_jitter) {
  3057. dof_blur_quality = p_quality;
  3058. dof_blur_use_jitter = p_use_jitter;
  3059. }
  3060. void RasterizerSceneRD::camera_effects_set_dof_blur_bokeh_shape(RS::DOFBokehShape p_shape) {
  3061. dof_blur_bokeh_shape = p_shape;
  3062. }
  3063. void RasterizerSceneRD::camera_effects_set_dof_blur(RID p_camera_effects, bool p_far_enable, float p_far_distance, float p_far_transition, bool p_near_enable, float p_near_distance, float p_near_transition, float p_amount) {
  3064. CameraEffects *camfx = camera_effects_owner.getornull(p_camera_effects);
  3065. ERR_FAIL_COND(!camfx);
  3066. camfx->dof_blur_far_enabled = p_far_enable;
  3067. camfx->dof_blur_far_distance = p_far_distance;
  3068. camfx->dof_blur_far_transition = p_far_transition;
  3069. camfx->dof_blur_near_enabled = p_near_enable;
  3070. camfx->dof_blur_near_distance = p_near_distance;
  3071. camfx->dof_blur_near_transition = p_near_transition;
  3072. camfx->dof_blur_amount = p_amount;
  3073. }
  3074. void RasterizerSceneRD::camera_effects_set_custom_exposure(RID p_camera_effects, bool p_enable, float p_exposure) {
  3075. CameraEffects *camfx = camera_effects_owner.getornull(p_camera_effects);
  3076. ERR_FAIL_COND(!camfx);
  3077. camfx->override_exposure_enabled = p_enable;
  3078. camfx->override_exposure = p_exposure;
  3079. }
  3080. RID RasterizerSceneRD::light_instance_create(RID p_light) {
  3081. RID li = light_instance_owner.make_rid(LightInstance());
  3082. LightInstance *light_instance = light_instance_owner.getornull(li);
  3083. light_instance->self = li;
  3084. light_instance->light = p_light;
  3085. light_instance->light_type = storage->light_get_type(p_light);
  3086. return li;
  3087. }
  3088. void RasterizerSceneRD::light_instance_set_transform(RID p_light_instance, const Transform &p_transform) {
  3089. LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
  3090. ERR_FAIL_COND(!light_instance);
  3091. light_instance->transform = p_transform;
  3092. }
  3093. void RasterizerSceneRD::light_instance_set_aabb(RID p_light_instance, const AABB &p_aabb) {
  3094. LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
  3095. ERR_FAIL_COND(!light_instance);
  3096. light_instance->aabb = p_aabb;
  3097. }
  3098. void RasterizerSceneRD::light_instance_set_shadow_transform(RID p_light_instance, const CameraMatrix &p_projection, const Transform &p_transform, float p_far, float p_split, int p_pass, float p_shadow_texel_size, float p_bias_scale, float p_range_begin, const Vector2 &p_uv_scale) {
  3099. LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
  3100. ERR_FAIL_COND(!light_instance);
  3101. if (storage->light_get_type(light_instance->light) != RS::LIGHT_DIRECTIONAL) {
  3102. p_pass = 0;
  3103. }
  3104. ERR_FAIL_INDEX(p_pass, 4);
  3105. light_instance->shadow_transform[p_pass].camera = p_projection;
  3106. light_instance->shadow_transform[p_pass].transform = p_transform;
  3107. light_instance->shadow_transform[p_pass].farplane = p_far;
  3108. light_instance->shadow_transform[p_pass].split = p_split;
  3109. light_instance->shadow_transform[p_pass].bias_scale = p_bias_scale;
  3110. light_instance->shadow_transform[p_pass].range_begin = p_range_begin;
  3111. light_instance->shadow_transform[p_pass].shadow_texel_size = p_shadow_texel_size;
  3112. light_instance->shadow_transform[p_pass].uv_scale = p_uv_scale;
  3113. }
  3114. void RasterizerSceneRD::light_instance_mark_visible(RID p_light_instance) {
  3115. LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
  3116. ERR_FAIL_COND(!light_instance);
  3117. light_instance->last_scene_pass = scene_pass;
  3118. }
  3119. RasterizerSceneRD::ShadowCubemap *RasterizerSceneRD::_get_shadow_cubemap(int p_size) {
  3120. if (!shadow_cubemaps.has(p_size)) {
  3121. ShadowCubemap sc;
  3122. {
  3123. RD::TextureFormat tf;
  3124. tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
  3125. tf.width = p_size;
  3126. tf.height = p_size;
  3127. tf.type = RD::TEXTURE_TYPE_CUBE;
  3128. tf.array_layers = 6;
  3129. tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
  3130. sc.cubemap = RD::get_singleton()->texture_create(tf, RD::TextureView());
  3131. }
  3132. for (int i = 0; i < 6; i++) {
  3133. RID side_texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), sc.cubemap, i, 0);
  3134. Vector<RID> fbtex;
  3135. fbtex.push_back(side_texture);
  3136. sc.side_fb[i] = RD::get_singleton()->framebuffer_create(fbtex);
  3137. }
  3138. shadow_cubemaps[p_size] = sc;
  3139. }
  3140. return &shadow_cubemaps[p_size];
  3141. }
  3142. RasterizerSceneRD::ShadowMap *RasterizerSceneRD::_get_shadow_map(const Size2i &p_size) {
  3143. if (!shadow_maps.has(p_size)) {
  3144. ShadowMap sm;
  3145. {
  3146. RD::TextureFormat tf;
  3147. tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
  3148. tf.width = p_size.width;
  3149. tf.height = p_size.height;
  3150. tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
  3151. sm.depth = RD::get_singleton()->texture_create(tf, RD::TextureView());
  3152. }
  3153. Vector<RID> fbtex;
  3154. fbtex.push_back(sm.depth);
  3155. sm.fb = RD::get_singleton()->framebuffer_create(fbtex);
  3156. shadow_maps[p_size] = sm;
  3157. }
  3158. return &shadow_maps[p_size];
  3159. }
  3160. //////////////////////////
  3161. RID RasterizerSceneRD::decal_instance_create(RID p_decal) {
  3162. DecalInstance di;
  3163. di.decal = p_decal;
  3164. return decal_instance_owner.make_rid(di);
  3165. }
  3166. void RasterizerSceneRD::decal_instance_set_transform(RID p_decal, const Transform &p_transform) {
  3167. DecalInstance *di = decal_instance_owner.getornull(p_decal);
  3168. ERR_FAIL_COND(!di);
  3169. di->transform = p_transform;
  3170. }
  3171. /////////////////////////////////
  3172. RID RasterizerSceneRD::gi_probe_instance_create(RID p_base) {
  3173. GIProbeInstance gi_probe;
  3174. gi_probe.probe = p_base;
  3175. RID rid = gi_probe_instance_owner.make_rid(gi_probe);
  3176. return rid;
  3177. }
  3178. void RasterizerSceneRD::gi_probe_instance_set_transform_to_data(RID p_probe, const Transform &p_xform) {
  3179. GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_probe);
  3180. ERR_FAIL_COND(!gi_probe);
  3181. gi_probe->transform = p_xform;
  3182. }
  3183. bool RasterizerSceneRD::gi_probe_needs_update(RID p_probe) const {
  3184. GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_probe);
  3185. ERR_FAIL_COND_V(!gi_probe, false);
  3186. //return true;
  3187. return gi_probe->last_probe_version != storage->gi_probe_get_version(gi_probe->probe);
  3188. }
  3189. void RasterizerSceneRD::gi_probe_update(RID p_probe, bool p_update_light_instances, const Vector<RID> &p_light_instances, int p_dynamic_object_count, InstanceBase **p_dynamic_objects) {
  3190. GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_probe);
  3191. ERR_FAIL_COND(!gi_probe);
  3192. uint32_t data_version = storage->gi_probe_get_data_version(gi_probe->probe);
  3193. // (RE)CREATE IF NEEDED
  3194. if (gi_probe->last_probe_data_version != data_version) {
  3195. //need to re-create everything
  3196. if (gi_probe->texture.is_valid()) {
  3197. RD::get_singleton()->free(gi_probe->texture);
  3198. RD::get_singleton()->free(gi_probe->write_buffer);
  3199. gi_probe->mipmaps.clear();
  3200. }
  3201. for (int i = 0; i < gi_probe->dynamic_maps.size(); i++) {
  3202. RD::get_singleton()->free(gi_probe->dynamic_maps[i].texture);
  3203. RD::get_singleton()->free(gi_probe->dynamic_maps[i].depth);
  3204. }
  3205. gi_probe->dynamic_maps.clear();
  3206. Vector3i octree_size = storage->gi_probe_get_octree_size(gi_probe->probe);
  3207. if (octree_size != Vector3i()) {
  3208. //can create a 3D texture
  3209. Vector<int> levels = storage->gi_probe_get_level_counts(gi_probe->probe);
  3210. RD::TextureFormat tf;
  3211. tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  3212. tf.width = octree_size.x;
  3213. tf.height = octree_size.y;
  3214. tf.depth = octree_size.z;
  3215. tf.type = RD::TEXTURE_TYPE_3D;
  3216. tf.mipmaps = levels.size();
  3217. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT;
  3218. gi_probe->texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  3219. RD::get_singleton()->texture_clear(gi_probe->texture, Color(0, 0, 0, 0), 0, levels.size(), 0, 1, false);
  3220. {
  3221. int total_elements = 0;
  3222. for (int i = 0; i < levels.size(); i++) {
  3223. total_elements += levels[i];
  3224. }
  3225. gi_probe->write_buffer = RD::get_singleton()->storage_buffer_create(total_elements * 16);
  3226. }
  3227. for (int i = 0; i < levels.size(); i++) {
  3228. GIProbeInstance::Mipmap mipmap;
  3229. mipmap.texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), gi_probe->texture, 0, i, RD::TEXTURE_SLICE_3D);
  3230. mipmap.level = levels.size() - i - 1;
  3231. mipmap.cell_offset = 0;
  3232. for (uint32_t j = 0; j < mipmap.level; j++) {
  3233. mipmap.cell_offset += levels[j];
  3234. }
  3235. mipmap.cell_count = levels[mipmap.level];
  3236. Vector<RD::Uniform> uniforms;
  3237. {
  3238. RD::Uniform u;
  3239. u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  3240. u.binding = 1;
  3241. u.ids.push_back(storage->gi_probe_get_octree_buffer(gi_probe->probe));
  3242. uniforms.push_back(u);
  3243. }
  3244. {
  3245. RD::Uniform u;
  3246. u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  3247. u.binding = 2;
  3248. u.ids.push_back(storage->gi_probe_get_data_buffer(gi_probe->probe));
  3249. uniforms.push_back(u);
  3250. }
  3251. {
  3252. RD::Uniform u;
  3253. u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  3254. u.binding = 4;
  3255. u.ids.push_back(gi_probe->write_buffer);
  3256. uniforms.push_back(u);
  3257. }
  3258. {
  3259. RD::Uniform u;
  3260. u.type = RD::UNIFORM_TYPE_TEXTURE;
  3261. u.binding = 9;
  3262. u.ids.push_back(storage->gi_probe_get_sdf_texture(gi_probe->probe));
  3263. uniforms.push_back(u);
  3264. }
  3265. {
  3266. RD::Uniform u;
  3267. u.type = RD::UNIFORM_TYPE_SAMPLER;
  3268. u.binding = 10;
  3269. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  3270. uniforms.push_back(u);
  3271. }
  3272. {
  3273. Vector<RD::Uniform> copy_uniforms = uniforms;
  3274. if (i == 0) {
  3275. {
  3276. RD::Uniform u;
  3277. u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  3278. u.binding = 3;
  3279. u.ids.push_back(gi_probe_lights_uniform);
  3280. copy_uniforms.push_back(u);
  3281. }
  3282. mipmap.uniform_set = RD::get_singleton()->uniform_set_create(copy_uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_COMPUTE_LIGHT], 0);
  3283. copy_uniforms = uniforms; //restore
  3284. {
  3285. RD::Uniform u;
  3286. u.type = RD::UNIFORM_TYPE_TEXTURE;
  3287. u.binding = 5;
  3288. u.ids.push_back(gi_probe->texture);
  3289. copy_uniforms.push_back(u);
  3290. }
  3291. mipmap.second_bounce_uniform_set = RD::get_singleton()->uniform_set_create(copy_uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_COMPUTE_SECOND_BOUNCE], 0);
  3292. } else {
  3293. mipmap.uniform_set = RD::get_singleton()->uniform_set_create(copy_uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_COMPUTE_MIPMAP], 0);
  3294. }
  3295. }
  3296. {
  3297. RD::Uniform u;
  3298. u.type = RD::UNIFORM_TYPE_IMAGE;
  3299. u.binding = 5;
  3300. u.ids.push_back(mipmap.texture);
  3301. uniforms.push_back(u);
  3302. }
  3303. mipmap.write_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_WRITE_TEXTURE], 0);
  3304. gi_probe->mipmaps.push_back(mipmap);
  3305. }
  3306. {
  3307. uint32_t dynamic_map_size = MAX(MAX(octree_size.x, octree_size.y), octree_size.z);
  3308. uint32_t oversample = nearest_power_of_2_templated(4);
  3309. int mipmap_index = 0;
  3310. while (mipmap_index < gi_probe->mipmaps.size()) {
  3311. GIProbeInstance::DynamicMap dmap;
  3312. if (oversample > 0) {
  3313. dmap.size = dynamic_map_size * (1 << oversample);
  3314. dmap.mipmap = -1;
  3315. oversample--;
  3316. } else {
  3317. dmap.size = dynamic_map_size >> mipmap_index;
  3318. dmap.mipmap = mipmap_index;
  3319. mipmap_index++;
  3320. }
  3321. RD::TextureFormat dtf;
  3322. dtf.width = dmap.size;
  3323. dtf.height = dmap.size;
  3324. dtf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  3325. dtf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT;
  3326. if (gi_probe->dynamic_maps.size() == 0) {
  3327. dtf.usage_bits |= RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  3328. }
  3329. dmap.texture = RD::get_singleton()->texture_create(dtf, RD::TextureView());
  3330. if (gi_probe->dynamic_maps.size() == 0) {
  3331. //render depth for first one
  3332. dtf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
  3333. dtf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  3334. dmap.fb_depth = RD::get_singleton()->texture_create(dtf, RD::TextureView());
  3335. }
  3336. //just use depth as-is
  3337. dtf.format = RD::DATA_FORMAT_R32_SFLOAT;
  3338. dtf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  3339. dmap.depth = RD::get_singleton()->texture_create(dtf, RD::TextureView());
  3340. if (gi_probe->dynamic_maps.size() == 0) {
  3341. dtf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  3342. dtf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  3343. dmap.albedo = RD::get_singleton()->texture_create(dtf, RD::TextureView());
  3344. dmap.normal = RD::get_singleton()->texture_create(dtf, RD::TextureView());
  3345. dmap.orm = RD::get_singleton()->texture_create(dtf, RD::TextureView());
  3346. Vector<RID> fb;
  3347. fb.push_back(dmap.albedo);
  3348. fb.push_back(dmap.normal);
  3349. fb.push_back(dmap.orm);
  3350. fb.push_back(dmap.texture); //emission
  3351. fb.push_back(dmap.depth);
  3352. fb.push_back(dmap.fb_depth);
  3353. dmap.fb = RD::get_singleton()->framebuffer_create(fb);
  3354. {
  3355. Vector<RD::Uniform> uniforms;
  3356. {
  3357. RD::Uniform u;
  3358. u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  3359. u.binding = 3;
  3360. u.ids.push_back(gi_probe_lights_uniform);
  3361. uniforms.push_back(u);
  3362. }
  3363. {
  3364. RD::Uniform u;
  3365. u.type = RD::UNIFORM_TYPE_IMAGE;
  3366. u.binding = 5;
  3367. u.ids.push_back(dmap.albedo);
  3368. uniforms.push_back(u);
  3369. }
  3370. {
  3371. RD::Uniform u;
  3372. u.type = RD::UNIFORM_TYPE_IMAGE;
  3373. u.binding = 6;
  3374. u.ids.push_back(dmap.normal);
  3375. uniforms.push_back(u);
  3376. }
  3377. {
  3378. RD::Uniform u;
  3379. u.type = RD::UNIFORM_TYPE_IMAGE;
  3380. u.binding = 7;
  3381. u.ids.push_back(dmap.orm);
  3382. uniforms.push_back(u);
  3383. }
  3384. {
  3385. RD::Uniform u;
  3386. u.type = RD::UNIFORM_TYPE_TEXTURE;
  3387. u.binding = 8;
  3388. u.ids.push_back(dmap.fb_depth);
  3389. uniforms.push_back(u);
  3390. }
  3391. {
  3392. RD::Uniform u;
  3393. u.type = RD::UNIFORM_TYPE_TEXTURE;
  3394. u.binding = 9;
  3395. u.ids.push_back(storage->gi_probe_get_sdf_texture(gi_probe->probe));
  3396. uniforms.push_back(u);
  3397. }
  3398. {
  3399. RD::Uniform u;
  3400. u.type = RD::UNIFORM_TYPE_SAMPLER;
  3401. u.binding = 10;
  3402. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  3403. uniforms.push_back(u);
  3404. }
  3405. {
  3406. RD::Uniform u;
  3407. u.type = RD::UNIFORM_TYPE_IMAGE;
  3408. u.binding = 11;
  3409. u.ids.push_back(dmap.texture);
  3410. uniforms.push_back(u);
  3411. }
  3412. {
  3413. RD::Uniform u;
  3414. u.type = RD::UNIFORM_TYPE_IMAGE;
  3415. u.binding = 12;
  3416. u.ids.push_back(dmap.depth);
  3417. uniforms.push_back(u);
  3418. }
  3419. dmap.uniform_set = RD::get_singleton()->uniform_set_create(uniforms, giprobe_lighting_shader_version_shaders[GI_PROBE_SHADER_VERSION_DYNAMIC_OBJECT_LIGHTING], 0);
  3420. }
  3421. } else {
  3422. bool plot = dmap.mipmap >= 0;
  3423. bool write = dmap.mipmap < (gi_probe->mipmaps.size() - 1);
  3424. Vector<RD::Uniform> uniforms;
  3425. {
  3426. RD::Uniform u;
  3427. u.type = RD::UNIFORM_TYPE_IMAGE;
  3428. u.binding = 5;
  3429. u.ids.push_back(gi_probe->dynamic_maps[gi_probe->dynamic_maps.size() - 1].texture);
  3430. uniforms.push_back(u);
  3431. }
  3432. {
  3433. RD::Uniform u;
  3434. u.type = RD::UNIFORM_TYPE_IMAGE;
  3435. u.binding = 6;
  3436. u.ids.push_back(gi_probe->dynamic_maps[gi_probe->dynamic_maps.size() - 1].depth);
  3437. uniforms.push_back(u);
  3438. }
  3439. if (write) {
  3440. {
  3441. RD::Uniform u;
  3442. u.type = RD::UNIFORM_TYPE_IMAGE;
  3443. u.binding = 7;
  3444. u.ids.push_back(dmap.texture);
  3445. uniforms.push_back(u);
  3446. }
  3447. {
  3448. RD::Uniform u;
  3449. u.type = RD::UNIFORM_TYPE_IMAGE;
  3450. u.binding = 8;
  3451. u.ids.push_back(dmap.depth);
  3452. uniforms.push_back(u);
  3453. }
  3454. }
  3455. {
  3456. RD::Uniform u;
  3457. u.type = RD::UNIFORM_TYPE_TEXTURE;
  3458. u.binding = 9;
  3459. u.ids.push_back(storage->gi_probe_get_sdf_texture(gi_probe->probe));
  3460. uniforms.push_back(u);
  3461. }
  3462. {
  3463. RD::Uniform u;
  3464. u.type = RD::UNIFORM_TYPE_SAMPLER;
  3465. u.binding = 10;
  3466. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  3467. uniforms.push_back(u);
  3468. }
  3469. if (plot) {
  3470. {
  3471. RD::Uniform u;
  3472. u.type = RD::UNIFORM_TYPE_IMAGE;
  3473. u.binding = 11;
  3474. u.ids.push_back(gi_probe->mipmaps[dmap.mipmap].texture);
  3475. uniforms.push_back(u);
  3476. }
  3477. }
  3478. dmap.uniform_set = RD::get_singleton()->uniform_set_create(uniforms, giprobe_lighting_shader_version_shaders[(write && plot) ? GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_WRITE_PLOT : write ? GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_WRITE : GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_PLOT], 0);
  3479. }
  3480. gi_probe->dynamic_maps.push_back(dmap);
  3481. }
  3482. }
  3483. }
  3484. gi_probe->last_probe_data_version = data_version;
  3485. p_update_light_instances = true; //just in case
  3486. _base_uniforms_changed();
  3487. }
  3488. // UDPDATE TIME
  3489. if (gi_probe->has_dynamic_object_data) {
  3490. //if it has dynamic object data, it needs to be cleared
  3491. RD::get_singleton()->texture_clear(gi_probe->texture, Color(0, 0, 0, 0), 0, gi_probe->mipmaps.size(), 0, 1, true);
  3492. }
  3493. uint32_t light_count = 0;
  3494. if (p_update_light_instances || p_dynamic_object_count > 0) {
  3495. light_count = MIN(gi_probe_max_lights, (uint32_t)p_light_instances.size());
  3496. {
  3497. Transform to_cell = storage->gi_probe_get_to_cell_xform(gi_probe->probe);
  3498. Transform to_probe_xform = (gi_probe->transform * to_cell.affine_inverse()).affine_inverse();
  3499. //update lights
  3500. for (uint32_t i = 0; i < light_count; i++) {
  3501. GIProbeLight &l = gi_probe_lights[i];
  3502. RID light_instance = p_light_instances[i];
  3503. RID light = light_instance_get_base_light(light_instance);
  3504. l.type = storage->light_get_type(light);
  3505. l.attenuation = storage->light_get_param(light, RS::LIGHT_PARAM_ATTENUATION);
  3506. l.energy = storage->light_get_param(light, RS::LIGHT_PARAM_ENERGY) * storage->light_get_param(light, RS::LIGHT_PARAM_INDIRECT_ENERGY);
  3507. l.radius = to_cell.basis.xform(Vector3(storage->light_get_param(light, RS::LIGHT_PARAM_RANGE), 0, 0)).length();
  3508. Color color = storage->light_get_color(light).to_linear();
  3509. l.color[0] = color.r;
  3510. l.color[1] = color.g;
  3511. l.color[2] = color.b;
  3512. l.spot_angle_radians = Math::deg2rad(storage->light_get_param(light, RS::LIGHT_PARAM_SPOT_ANGLE));
  3513. l.spot_attenuation = storage->light_get_param(light, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  3514. Transform xform = light_instance_get_base_transform(light_instance);
  3515. Vector3 pos = to_probe_xform.xform(xform.origin);
  3516. Vector3 dir = to_probe_xform.basis.xform(-xform.basis.get_axis(2)).normalized();
  3517. l.position[0] = pos.x;
  3518. l.position[1] = pos.y;
  3519. l.position[2] = pos.z;
  3520. l.direction[0] = dir.x;
  3521. l.direction[1] = dir.y;
  3522. l.direction[2] = dir.z;
  3523. l.has_shadow = storage->light_has_shadow(light);
  3524. }
  3525. RD::get_singleton()->buffer_update(gi_probe_lights_uniform, 0, sizeof(GIProbeLight) * light_count, gi_probe_lights, true);
  3526. }
  3527. }
  3528. if (gi_probe->has_dynamic_object_data || p_update_light_instances || p_dynamic_object_count) {
  3529. // PROCESS MIPMAPS
  3530. if (gi_probe->mipmaps.size()) {
  3531. //can update mipmaps
  3532. Vector3i probe_size = storage->gi_probe_get_octree_size(gi_probe->probe);
  3533. GIProbePushConstant push_constant;
  3534. push_constant.limits[0] = probe_size.x;
  3535. push_constant.limits[1] = probe_size.y;
  3536. push_constant.limits[2] = probe_size.z;
  3537. push_constant.stack_size = gi_probe->mipmaps.size();
  3538. push_constant.emission_scale = 1.0;
  3539. push_constant.propagation = storage->gi_probe_get_propagation(gi_probe->probe);
  3540. push_constant.dynamic_range = storage->gi_probe_get_dynamic_range(gi_probe->probe);
  3541. push_constant.light_count = light_count;
  3542. push_constant.aniso_strength = 0;
  3543. /* print_line("probe update to version " + itos(gi_probe->last_probe_version));
  3544. print_line("propagation " + rtos(push_constant.propagation));
  3545. print_line("dynrange " + rtos(push_constant.dynamic_range));
  3546. */
  3547. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  3548. int passes;
  3549. if (p_update_light_instances) {
  3550. passes = storage->gi_probe_is_using_two_bounces(gi_probe->probe) ? 2 : 1;
  3551. } else {
  3552. passes = 1; //only re-blitting is necessary
  3553. }
  3554. int wg_size = 64;
  3555. int wg_limit_x = RD::get_singleton()->limit_get(RD::LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X);
  3556. for (int pass = 0; pass < passes; pass++) {
  3557. if (p_update_light_instances) {
  3558. for (int i = 0; i < gi_probe->mipmaps.size(); i++) {
  3559. if (i == 0) {
  3560. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[pass == 0 ? GI_PROBE_SHADER_VERSION_COMPUTE_LIGHT : GI_PROBE_SHADER_VERSION_COMPUTE_SECOND_BOUNCE]);
  3561. } else if (i == 1) {
  3562. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_COMPUTE_MIPMAP]);
  3563. }
  3564. if (pass == 1 || i > 0) {
  3565. RD::get_singleton()->compute_list_add_barrier(compute_list); //wait til previous step is done
  3566. }
  3567. if (pass == 0 || i > 0) {
  3568. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->mipmaps[i].uniform_set, 0);
  3569. } else {
  3570. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->mipmaps[i].second_bounce_uniform_set, 0);
  3571. }
  3572. push_constant.cell_offset = gi_probe->mipmaps[i].cell_offset;
  3573. push_constant.cell_count = gi_probe->mipmaps[i].cell_count;
  3574. int wg_todo = (gi_probe->mipmaps[i].cell_count - 1) / wg_size + 1;
  3575. while (wg_todo) {
  3576. int wg_count = MIN(wg_todo, wg_limit_x);
  3577. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GIProbePushConstant));
  3578. RD::get_singleton()->compute_list_dispatch(compute_list, wg_count, 1, 1);
  3579. wg_todo -= wg_count;
  3580. push_constant.cell_offset += wg_count * wg_size;
  3581. }
  3582. }
  3583. RD::get_singleton()->compute_list_add_barrier(compute_list); //wait til previous step is done
  3584. }
  3585. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_WRITE_TEXTURE]);
  3586. for (int i = 0; i < gi_probe->mipmaps.size(); i++) {
  3587. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->mipmaps[i].write_uniform_set, 0);
  3588. push_constant.cell_offset = gi_probe->mipmaps[i].cell_offset;
  3589. push_constant.cell_count = gi_probe->mipmaps[i].cell_count;
  3590. int wg_todo = (gi_probe->mipmaps[i].cell_count - 1) / wg_size + 1;
  3591. while (wg_todo) {
  3592. int wg_count = MIN(wg_todo, wg_limit_x);
  3593. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GIProbePushConstant));
  3594. RD::get_singleton()->compute_list_dispatch(compute_list, wg_count, 1, 1);
  3595. wg_todo -= wg_count;
  3596. push_constant.cell_offset += wg_count * wg_size;
  3597. }
  3598. }
  3599. }
  3600. RD::get_singleton()->compute_list_end();
  3601. }
  3602. }
  3603. gi_probe->has_dynamic_object_data = false; //clear until dynamic object data is used again
  3604. if (p_dynamic_object_count && gi_probe->dynamic_maps.size()) {
  3605. Vector3i octree_size = storage->gi_probe_get_octree_size(gi_probe->probe);
  3606. int multiplier = gi_probe->dynamic_maps[0].size / MAX(MAX(octree_size.x, octree_size.y), octree_size.z);
  3607. Transform oversample_scale;
  3608. oversample_scale.basis.scale(Vector3(multiplier, multiplier, multiplier));
  3609. Transform to_cell = oversample_scale * storage->gi_probe_get_to_cell_xform(gi_probe->probe);
  3610. Transform to_world_xform = gi_probe->transform * to_cell.affine_inverse();
  3611. Transform to_probe_xform = to_world_xform.affine_inverse();
  3612. AABB probe_aabb(Vector3(), octree_size);
  3613. //this could probably be better parallelized in compute..
  3614. for (int i = 0; i < p_dynamic_object_count; i++) {
  3615. InstanceBase *instance = p_dynamic_objects[i];
  3616. //not used, so clear
  3617. instance->depth_layer = 0;
  3618. instance->depth = 0;
  3619. //transform aabb to giprobe
  3620. AABB aabb = (to_probe_xform * instance->transform).xform(instance->aabb);
  3621. //this needs to wrap to grid resolution to avoid jitter
  3622. //also extend margin a bit just in case
  3623. Vector3i begin = aabb.position - Vector3i(1, 1, 1);
  3624. Vector3i end = aabb.position + aabb.size + Vector3i(1, 1, 1);
  3625. for (int j = 0; j < 3; j++) {
  3626. if ((end[j] - begin[j]) & 1) {
  3627. end[j]++; //for half extents split, it needs to be even
  3628. }
  3629. begin[j] = MAX(begin[j], 0);
  3630. end[j] = MIN(end[j], octree_size[j] * multiplier);
  3631. }
  3632. //aabb = aabb.intersection(probe_aabb); //intersect
  3633. aabb.position = begin;
  3634. aabb.size = end - begin;
  3635. //print_line("aabb: " + aabb);
  3636. for (int j = 0; j < 6; j++) {
  3637. //if (j != 0 && j != 3) {
  3638. // continue;
  3639. //}
  3640. static const Vector3 render_z[6] = {
  3641. Vector3(1, 0, 0),
  3642. Vector3(0, 1, 0),
  3643. Vector3(0, 0, 1),
  3644. Vector3(-1, 0, 0),
  3645. Vector3(0, -1, 0),
  3646. Vector3(0, 0, -1),
  3647. };
  3648. static const Vector3 render_up[6] = {
  3649. Vector3(0, 1, 0),
  3650. Vector3(0, 0, 1),
  3651. Vector3(0, 1, 0),
  3652. Vector3(0, 1, 0),
  3653. Vector3(0, 0, 1),
  3654. Vector3(0, 1, 0),
  3655. };
  3656. Vector3 render_dir = render_z[j];
  3657. Vector3 up_dir = render_up[j];
  3658. Vector3 center = aabb.position + aabb.size * 0.5;
  3659. Transform xform;
  3660. xform.set_look_at(center - aabb.size * 0.5 * render_dir, center, up_dir);
  3661. Vector3 x_dir = xform.basis.get_axis(0).abs();
  3662. int x_axis = int(Vector3(0, 1, 2).dot(x_dir));
  3663. Vector3 y_dir = xform.basis.get_axis(1).abs();
  3664. int y_axis = int(Vector3(0, 1, 2).dot(y_dir));
  3665. Vector3 z_dir = -xform.basis.get_axis(2);
  3666. int z_axis = int(Vector3(0, 1, 2).dot(z_dir.abs()));
  3667. Rect2i rect(aabb.position[x_axis], aabb.position[y_axis], aabb.size[x_axis], aabb.size[y_axis]);
  3668. bool x_flip = bool(Vector3(1, 1, 1).dot(xform.basis.get_axis(0)) < 0);
  3669. bool y_flip = bool(Vector3(1, 1, 1).dot(xform.basis.get_axis(1)) < 0);
  3670. bool z_flip = bool(Vector3(1, 1, 1).dot(xform.basis.get_axis(2)) > 0);
  3671. CameraMatrix cm;
  3672. cm.set_orthogonal(-rect.size.width / 2, rect.size.width / 2, -rect.size.height / 2, rect.size.height / 2, 0.0001, aabb.size[z_axis]);
  3673. _render_material(to_world_xform * xform, cm, true, &instance, 1, gi_probe->dynamic_maps[0].fb, Rect2i(Vector2i(), rect.size));
  3674. GIProbeDynamicPushConstant push_constant;
  3675. zeromem(&push_constant, sizeof(GIProbeDynamicPushConstant));
  3676. push_constant.limits[0] = octree_size.x;
  3677. push_constant.limits[1] = octree_size.y;
  3678. push_constant.limits[2] = octree_size.z;
  3679. push_constant.light_count = p_light_instances.size();
  3680. push_constant.x_dir[0] = x_dir[0];
  3681. push_constant.x_dir[1] = x_dir[1];
  3682. push_constant.x_dir[2] = x_dir[2];
  3683. push_constant.y_dir[0] = y_dir[0];
  3684. push_constant.y_dir[1] = y_dir[1];
  3685. push_constant.y_dir[2] = y_dir[2];
  3686. push_constant.z_dir[0] = z_dir[0];
  3687. push_constant.z_dir[1] = z_dir[1];
  3688. push_constant.z_dir[2] = z_dir[2];
  3689. push_constant.z_base = xform.origin[z_axis];
  3690. push_constant.z_sign = (z_flip ? -1.0 : 1.0);
  3691. push_constant.pos_multiplier = float(1.0) / multiplier;
  3692. push_constant.dynamic_range = storage->gi_probe_get_dynamic_range(gi_probe->probe);
  3693. push_constant.flip_x = x_flip;
  3694. push_constant.flip_y = y_flip;
  3695. push_constant.rect_pos[0] = rect.position[0];
  3696. push_constant.rect_pos[1] = rect.position[1];
  3697. push_constant.rect_size[0] = rect.size[0];
  3698. push_constant.rect_size[1] = rect.size[1];
  3699. push_constant.prev_rect_ofs[0] = 0;
  3700. push_constant.prev_rect_ofs[1] = 0;
  3701. push_constant.prev_rect_size[0] = 0;
  3702. push_constant.prev_rect_size[1] = 0;
  3703. push_constant.on_mipmap = false;
  3704. push_constant.propagation = storage->gi_probe_get_propagation(gi_probe->probe);
  3705. push_constant.pad[0] = 0;
  3706. push_constant.pad[1] = 0;
  3707. push_constant.pad[2] = 0;
  3708. //process lighting
  3709. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  3710. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_DYNAMIC_OBJECT_LIGHTING]);
  3711. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->dynamic_maps[0].uniform_set, 0);
  3712. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GIProbeDynamicPushConstant));
  3713. RD::get_singleton()->compute_list_dispatch(compute_list, (rect.size.x - 1) / 8 + 1, (rect.size.y - 1) / 8 + 1, 1);
  3714. //print_line("rect: " + itos(i) + ": " + rect);
  3715. for (int k = 1; k < gi_probe->dynamic_maps.size(); k++) {
  3716. // enlarge the rect if needed so all pixels fit when downscaled,
  3717. // this ensures downsampling is smooth and optimal because no pixels are left behind
  3718. //x
  3719. if (rect.position.x & 1) {
  3720. rect.size.x++;
  3721. push_constant.prev_rect_ofs[0] = 1; //this is used to ensure reading is also optimal
  3722. } else {
  3723. push_constant.prev_rect_ofs[0] = 0;
  3724. }
  3725. if (rect.size.x & 1) {
  3726. rect.size.x++;
  3727. }
  3728. rect.position.x >>= 1;
  3729. rect.size.x = MAX(1, rect.size.x >> 1);
  3730. //y
  3731. if (rect.position.y & 1) {
  3732. rect.size.y++;
  3733. push_constant.prev_rect_ofs[1] = 1;
  3734. } else {
  3735. push_constant.prev_rect_ofs[1] = 0;
  3736. }
  3737. if (rect.size.y & 1) {
  3738. rect.size.y++;
  3739. }
  3740. rect.position.y >>= 1;
  3741. rect.size.y = MAX(1, rect.size.y >> 1);
  3742. //shrink limits to ensure plot does not go outside map
  3743. if (gi_probe->dynamic_maps[k].mipmap > 0) {
  3744. for (int l = 0; l < 3; l++) {
  3745. push_constant.limits[l] = MAX(1, push_constant.limits[l] >> 1);
  3746. }
  3747. }
  3748. //print_line("rect: " + itos(i) + ": " + rect);
  3749. push_constant.rect_pos[0] = rect.position[0];
  3750. push_constant.rect_pos[1] = rect.position[1];
  3751. push_constant.prev_rect_size[0] = push_constant.rect_size[0];
  3752. push_constant.prev_rect_size[1] = push_constant.rect_size[1];
  3753. push_constant.rect_size[0] = rect.size[0];
  3754. push_constant.rect_size[1] = rect.size[1];
  3755. push_constant.on_mipmap = gi_probe->dynamic_maps[k].mipmap > 0;
  3756. RD::get_singleton()->compute_list_add_barrier(compute_list);
  3757. if (gi_probe->dynamic_maps[k].mipmap < 0) {
  3758. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_WRITE]);
  3759. } else if (k < gi_probe->dynamic_maps.size() - 1) {
  3760. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_WRITE_PLOT]);
  3761. } else {
  3762. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, giprobe_lighting_shader_version_pipelines[GI_PROBE_SHADER_VERSION_DYNAMIC_SHRINK_PLOT]);
  3763. }
  3764. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, gi_probe->dynamic_maps[k].uniform_set, 0);
  3765. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(GIProbeDynamicPushConstant));
  3766. RD::get_singleton()->compute_list_dispatch(compute_list, (rect.size.x - 1) / 8 + 1, (rect.size.y - 1) / 8 + 1, 1);
  3767. }
  3768. RD::get_singleton()->compute_list_end();
  3769. }
  3770. }
  3771. gi_probe->has_dynamic_object_data = true; //clear until dynamic object data is used again
  3772. }
  3773. gi_probe->last_probe_version = storage->gi_probe_get_version(gi_probe->probe);
  3774. }
  3775. void RasterizerSceneRD::_debug_giprobe(RID p_gi_probe, RD::DrawListID p_draw_list, RID p_framebuffer, const CameraMatrix &p_camera_with_transform, bool p_lighting, bool p_emission, float p_alpha) {
  3776. GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_gi_probe);
  3777. ERR_FAIL_COND(!gi_probe);
  3778. if (gi_probe->mipmaps.size() == 0) {
  3779. return;
  3780. }
  3781. CameraMatrix transform = (p_camera_with_transform * CameraMatrix(gi_probe->transform)) * CameraMatrix(storage->gi_probe_get_to_cell_xform(gi_probe->probe).affine_inverse());
  3782. int level = 0;
  3783. Vector3i octree_size = storage->gi_probe_get_octree_size(gi_probe->probe);
  3784. GIProbeDebugPushConstant push_constant;
  3785. push_constant.alpha = p_alpha;
  3786. push_constant.dynamic_range = storage->gi_probe_get_dynamic_range(gi_probe->probe);
  3787. push_constant.cell_offset = gi_probe->mipmaps[level].cell_offset;
  3788. push_constant.level = level;
  3789. push_constant.bounds[0] = octree_size.x >> level;
  3790. push_constant.bounds[1] = octree_size.y >> level;
  3791. push_constant.bounds[2] = octree_size.z >> level;
  3792. push_constant.pad = 0;
  3793. for (int i = 0; i < 4; i++) {
  3794. for (int j = 0; j < 4; j++) {
  3795. push_constant.projection[i * 4 + j] = transform.matrix[i][j];
  3796. }
  3797. }
  3798. if (giprobe_debug_uniform_set.is_valid()) {
  3799. RD::get_singleton()->free(giprobe_debug_uniform_set);
  3800. }
  3801. Vector<RD::Uniform> uniforms;
  3802. {
  3803. RD::Uniform u;
  3804. u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  3805. u.binding = 1;
  3806. u.ids.push_back(storage->gi_probe_get_data_buffer(gi_probe->probe));
  3807. uniforms.push_back(u);
  3808. }
  3809. {
  3810. RD::Uniform u;
  3811. u.type = RD::UNIFORM_TYPE_TEXTURE;
  3812. u.binding = 2;
  3813. u.ids.push_back(gi_probe->texture);
  3814. uniforms.push_back(u);
  3815. }
  3816. {
  3817. RD::Uniform u;
  3818. u.type = RD::UNIFORM_TYPE_SAMPLER;
  3819. u.binding = 3;
  3820. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  3821. uniforms.push_back(u);
  3822. }
  3823. int cell_count;
  3824. if (!p_emission && p_lighting && gi_probe->has_dynamic_object_data) {
  3825. cell_count = push_constant.bounds[0] * push_constant.bounds[1] * push_constant.bounds[2];
  3826. } else {
  3827. cell_count = gi_probe->mipmaps[level].cell_count;
  3828. }
  3829. giprobe_debug_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, giprobe_debug_shader_version_shaders[0], 0);
  3830. RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, giprobe_debug_shader_version_pipelines[p_emission ? GI_PROBE_DEBUG_EMISSION : p_lighting ? (gi_probe->has_dynamic_object_data ? GI_PROBE_DEBUG_LIGHT_FULL : GI_PROBE_DEBUG_LIGHT) : GI_PROBE_DEBUG_COLOR].get_render_pipeline(RD::INVALID_ID, RD::get_singleton()->framebuffer_get_format(p_framebuffer)));
  3831. RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, giprobe_debug_uniform_set, 0);
  3832. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(GIProbeDebugPushConstant));
  3833. RD::get_singleton()->draw_list_draw(p_draw_list, false, cell_count, 36);
  3834. }
  3835. void RasterizerSceneRD::_debug_sdfgi_probes(RID p_render_buffers, RD::DrawListID p_draw_list, RID p_framebuffer, const CameraMatrix &p_camera_with_transform) {
  3836. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  3837. ERR_FAIL_COND(!rb);
  3838. if (!rb->sdfgi) {
  3839. return; //nothing to debug
  3840. }
  3841. SDGIShader::DebugProbesPushConstant push_constant;
  3842. for (int i = 0; i < 4; i++) {
  3843. for (int j = 0; j < 4; j++) {
  3844. push_constant.projection[i * 4 + j] = p_camera_with_transform.matrix[i][j];
  3845. }
  3846. }
  3847. //gen spheres from strips
  3848. uint32_t band_points = 16;
  3849. push_constant.band_power = 4;
  3850. push_constant.sections_in_band = ((band_points / 2) - 1);
  3851. push_constant.band_mask = band_points - 2;
  3852. push_constant.section_arc = (Math_PI * 2.0) / float(push_constant.sections_in_band);
  3853. push_constant.y_mult = rb->sdfgi->y_mult;
  3854. uint32_t total_points = push_constant.sections_in_band * band_points;
  3855. uint32_t total_probes = rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count;
  3856. push_constant.grid_size[0] = rb->sdfgi->cascade_size;
  3857. push_constant.grid_size[1] = rb->sdfgi->cascade_size;
  3858. push_constant.grid_size[2] = rb->sdfgi->cascade_size;
  3859. push_constant.cascade = 0;
  3860. push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
  3861. if (!rb->sdfgi->debug_probes_uniform_set.is_valid() || !RD::get_singleton()->uniform_set_is_valid(rb->sdfgi->debug_probes_uniform_set)) {
  3862. Vector<RD::Uniform> uniforms;
  3863. {
  3864. RD::Uniform u;
  3865. u.binding = 1;
  3866. u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  3867. u.ids.push_back(rb->sdfgi->cascades_ubo);
  3868. uniforms.push_back(u);
  3869. }
  3870. {
  3871. RD::Uniform u;
  3872. u.binding = 2;
  3873. u.type = RD::UNIFORM_TYPE_TEXTURE;
  3874. u.ids.push_back(rb->sdfgi->lightprobe_texture);
  3875. uniforms.push_back(u);
  3876. }
  3877. {
  3878. RD::Uniform u;
  3879. u.binding = 3;
  3880. u.type = RD::UNIFORM_TYPE_SAMPLER;
  3881. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  3882. uniforms.push_back(u);
  3883. }
  3884. {
  3885. RD::Uniform u;
  3886. u.binding = 4;
  3887. u.type = RD::UNIFORM_TYPE_TEXTURE;
  3888. u.ids.push_back(rb->sdfgi->occlusion_texture);
  3889. uniforms.push_back(u);
  3890. }
  3891. rb->sdfgi->debug_probes_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.debug_probes.version_get_shader(sdfgi_shader.debug_probes_shader, 0), 0);
  3892. }
  3893. RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, sdfgi_shader.debug_probes_pipeline[SDGIShader::PROBE_DEBUG_PROBES].get_render_pipeline(RD::INVALID_FORMAT_ID, RD::get_singleton()->framebuffer_get_format(p_framebuffer)));
  3894. RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, rb->sdfgi->debug_probes_uniform_set, 0);
  3895. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(SDGIShader::DebugProbesPushConstant));
  3896. RD::get_singleton()->draw_list_draw(p_draw_list, false, total_probes, total_points);
  3897. if (sdfgi_debug_probe_dir != Vector3()) {
  3898. print_line("CLICK DEBUG ME?");
  3899. uint32_t cascade = 0;
  3900. Vector3 offset = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + rb->sdfgi->cascades[cascade].position)) * rb->sdfgi->cascades[cascade].cell_size * Vector3(1.0, 1.0 / rb->sdfgi->y_mult, 1.0);
  3901. Vector3 probe_size = rb->sdfgi->cascades[cascade].cell_size * (rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR) * Vector3(1.0, 1.0 / rb->sdfgi->y_mult, 1.0);
  3902. Vector3 ray_from = sdfgi_debug_probe_pos;
  3903. Vector3 ray_to = sdfgi_debug_probe_pos + sdfgi_debug_probe_dir * rb->sdfgi->cascades[cascade].cell_size * Math::sqrt(3.0) * rb->sdfgi->cascade_size;
  3904. float sphere_radius = 0.2;
  3905. float closest_dist = 1e20;
  3906. sdfgi_debug_probe_enabled = false;
  3907. Vector3i probe_from = rb->sdfgi->cascades[cascade].position / (rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR);
  3908. for (int i = 0; i < (SDFGI::PROBE_DIVISOR + 1); i++) {
  3909. for (int j = 0; j < (SDFGI::PROBE_DIVISOR + 1); j++) {
  3910. for (int k = 0; k < (SDFGI::PROBE_DIVISOR + 1); k++) {
  3911. Vector3 pos = offset + probe_size * Vector3(i, j, k);
  3912. Vector3 res;
  3913. if (Geometry3D::segment_intersects_sphere(ray_from, ray_to, pos, sphere_radius, &res)) {
  3914. float d = ray_from.distance_to(res);
  3915. if (d < closest_dist) {
  3916. closest_dist = d;
  3917. sdfgi_debug_probe_enabled = true;
  3918. sdfgi_debug_probe_index = probe_from + Vector3i(i, j, k);
  3919. }
  3920. }
  3921. }
  3922. }
  3923. }
  3924. if (sdfgi_debug_probe_enabled) {
  3925. print_line("found: " + sdfgi_debug_probe_index);
  3926. } else {
  3927. print_line("no found");
  3928. }
  3929. sdfgi_debug_probe_dir = Vector3();
  3930. }
  3931. if (sdfgi_debug_probe_enabled) {
  3932. uint32_t cascade = 0;
  3933. uint32_t probe_cells = (rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR);
  3934. Vector3i probe_from = rb->sdfgi->cascades[cascade].position / probe_cells;
  3935. Vector3i ofs = sdfgi_debug_probe_index - probe_from;
  3936. if (ofs.x < 0 || ofs.y < 0 || ofs.z < 0) {
  3937. return;
  3938. }
  3939. if (ofs.x > SDFGI::PROBE_DIVISOR || ofs.y > SDFGI::PROBE_DIVISOR || ofs.z > SDFGI::PROBE_DIVISOR) {
  3940. return;
  3941. }
  3942. uint32_t mult = (SDFGI::PROBE_DIVISOR + 1);
  3943. uint32_t index = ofs.z * mult * mult + ofs.y * mult + ofs.x;
  3944. push_constant.probe_debug_index = index;
  3945. uint32_t cell_count = probe_cells * 2 * probe_cells * 2 * probe_cells * 2;
  3946. RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, sdfgi_shader.debug_probes_pipeline[SDGIShader::PROBE_DEBUG_VISIBILITY].get_render_pipeline(RD::INVALID_FORMAT_ID, RD::get_singleton()->framebuffer_get_format(p_framebuffer)));
  3947. RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, rb->sdfgi->debug_probes_uniform_set, 0);
  3948. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(SDGIShader::DebugProbesPushConstant));
  3949. RD::get_singleton()->draw_list_draw(p_draw_list, false, cell_count, total_points);
  3950. }
  3951. }
  3952. ////////////////////////////////
  3953. RID RasterizerSceneRD::render_buffers_create() {
  3954. RenderBuffers rb;
  3955. rb.data = _create_render_buffer_data();
  3956. return render_buffers_owner.make_rid(rb);
  3957. }
  3958. void RasterizerSceneRD::_allocate_blur_textures(RenderBuffers *rb) {
  3959. ERR_FAIL_COND(!rb->blur[0].texture.is_null());
  3960. uint32_t mipmaps_required = Image::get_image_required_mipmaps(rb->width, rb->height, Image::FORMAT_RGBAH);
  3961. RD::TextureFormat tf;
  3962. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  3963. tf.width = rb->width;
  3964. tf.height = rb->height;
  3965. tf.type = RD::TEXTURE_TYPE_2D;
  3966. tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT;
  3967. tf.mipmaps = mipmaps_required;
  3968. rb->blur[0].texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  3969. //the second one is smaller (only used for separatable part of blur)
  3970. tf.width >>= 1;
  3971. tf.height >>= 1;
  3972. tf.mipmaps--;
  3973. rb->blur[1].texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  3974. int base_width = rb->width;
  3975. int base_height = rb->height;
  3976. for (uint32_t i = 0; i < mipmaps_required; i++) {
  3977. RenderBuffers::Blur::Mipmap mm;
  3978. mm.texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rb->blur[0].texture, 0, i);
  3979. mm.width = base_width;
  3980. mm.height = base_height;
  3981. rb->blur[0].mipmaps.push_back(mm);
  3982. if (i > 0) {
  3983. mm.texture = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rb->blur[1].texture, 0, i - 1);
  3984. rb->blur[1].mipmaps.push_back(mm);
  3985. }
  3986. base_width = MAX(1, base_width >> 1);
  3987. base_height = MAX(1, base_height >> 1);
  3988. }
  3989. }
  3990. void RasterizerSceneRD::_allocate_luminance_textures(RenderBuffers *rb) {
  3991. ERR_FAIL_COND(!rb->luminance.current.is_null());
  3992. int w = rb->width;
  3993. int h = rb->height;
  3994. while (true) {
  3995. w = MAX(w / 8, 1);
  3996. h = MAX(h / 8, 1);
  3997. RD::TextureFormat tf;
  3998. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  3999. tf.width = w;
  4000. tf.height = h;
  4001. tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT;
  4002. bool final = w == 1 && h == 1;
  4003. if (final) {
  4004. tf.usage_bits |= RD::TEXTURE_USAGE_SAMPLING_BIT;
  4005. }
  4006. RID texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4007. rb->luminance.reduce.push_back(texture);
  4008. if (final) {
  4009. rb->luminance.current = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4010. break;
  4011. }
  4012. }
  4013. }
  4014. void RasterizerSceneRD::_free_render_buffer_data(RenderBuffers *rb) {
  4015. if (rb->texture.is_valid()) {
  4016. RD::get_singleton()->free(rb->texture);
  4017. rb->texture = RID();
  4018. }
  4019. if (rb->depth_texture.is_valid()) {
  4020. RD::get_singleton()->free(rb->depth_texture);
  4021. rb->depth_texture = RID();
  4022. }
  4023. for (int i = 0; i < 2; i++) {
  4024. if (rb->blur[i].texture.is_valid()) {
  4025. RD::get_singleton()->free(rb->blur[i].texture);
  4026. rb->blur[i].texture = RID();
  4027. rb->blur[i].mipmaps.clear();
  4028. }
  4029. }
  4030. for (int i = 0; i < rb->luminance.reduce.size(); i++) {
  4031. RD::get_singleton()->free(rb->luminance.reduce[i]);
  4032. }
  4033. for (int i = 0; i < rb->luminance.reduce.size(); i++) {
  4034. RD::get_singleton()->free(rb->luminance.reduce[i]);
  4035. }
  4036. rb->luminance.reduce.clear();
  4037. if (rb->luminance.current.is_valid()) {
  4038. RD::get_singleton()->free(rb->luminance.current);
  4039. rb->luminance.current = RID();
  4040. }
  4041. if (rb->ssao.ao[0].is_valid()) {
  4042. RD::get_singleton()->free(rb->ssao.depth);
  4043. RD::get_singleton()->free(rb->ssao.ao[0]);
  4044. if (rb->ssao.ao[1].is_valid()) {
  4045. RD::get_singleton()->free(rb->ssao.ao[1]);
  4046. }
  4047. if (rb->ssao.ao_full.is_valid()) {
  4048. RD::get_singleton()->free(rb->ssao.ao_full);
  4049. }
  4050. rb->ssao.depth = RID();
  4051. rb->ssao.ao[0] = RID();
  4052. rb->ssao.ao[1] = RID();
  4053. rb->ssao.ao_full = RID();
  4054. rb->ssao.depth_slices.clear();
  4055. }
  4056. if (rb->ssr.blur_radius[0].is_valid()) {
  4057. RD::get_singleton()->free(rb->ssr.blur_radius[0]);
  4058. RD::get_singleton()->free(rb->ssr.blur_radius[1]);
  4059. rb->ssr.blur_radius[0] = RID();
  4060. rb->ssr.blur_radius[1] = RID();
  4061. }
  4062. if (rb->ssr.depth_scaled.is_valid()) {
  4063. RD::get_singleton()->free(rb->ssr.depth_scaled);
  4064. rb->ssr.depth_scaled = RID();
  4065. RD::get_singleton()->free(rb->ssr.normal_scaled);
  4066. rb->ssr.normal_scaled = RID();
  4067. }
  4068. }
  4069. void RasterizerSceneRD::_process_sss(RID p_render_buffers, const CameraMatrix &p_camera) {
  4070. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4071. ERR_FAIL_COND(!rb);
  4072. bool can_use_effects = rb->width >= 8 && rb->height >= 8;
  4073. if (!can_use_effects) {
  4074. //just copy
  4075. return;
  4076. }
  4077. if (rb->blur[0].texture.is_null()) {
  4078. _allocate_blur_textures(rb);
  4079. _render_buffers_uniform_set_changed(p_render_buffers);
  4080. }
  4081. storage->get_effects()->sub_surface_scattering(rb->texture, rb->blur[0].mipmaps[0].texture, rb->depth_texture, p_camera, Size2i(rb->width, rb->height), sss_scale, sss_depth_scale, sss_quality);
  4082. }
  4083. void RasterizerSceneRD::_process_ssr(RID p_render_buffers, RID p_dest_framebuffer, RID p_normal_buffer, RID p_specular_buffer, RID p_metallic, const Color &p_metallic_mask, RID p_environment, const CameraMatrix &p_projection, bool p_use_additive) {
  4084. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4085. ERR_FAIL_COND(!rb);
  4086. bool can_use_effects = rb->width >= 8 && rb->height >= 8;
  4087. if (!can_use_effects) {
  4088. //just copy
  4089. storage->get_effects()->merge_specular(p_dest_framebuffer, p_specular_buffer, p_use_additive ? RID() : rb->texture, RID());
  4090. return;
  4091. }
  4092. Environment *env = environment_owner.getornull(p_environment);
  4093. ERR_FAIL_COND(!env);
  4094. ERR_FAIL_COND(!env->ssr_enabled);
  4095. if (rb->ssr.depth_scaled.is_null()) {
  4096. RD::TextureFormat tf;
  4097. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  4098. tf.width = rb->width / 2;
  4099. tf.height = rb->height / 2;
  4100. tf.type = RD::TEXTURE_TYPE_2D;
  4101. tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT;
  4102. rb->ssr.depth_scaled = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4103. tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  4104. rb->ssr.normal_scaled = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4105. }
  4106. if (ssr_roughness_quality != RS::ENV_SSR_ROUGNESS_QUALITY_DISABLED && !rb->ssr.blur_radius[0].is_valid()) {
  4107. RD::TextureFormat tf;
  4108. tf.format = RD::DATA_FORMAT_R8_UNORM;
  4109. tf.width = rb->width / 2;
  4110. tf.height = rb->height / 2;
  4111. tf.type = RD::TEXTURE_TYPE_2D;
  4112. tf.usage_bits = RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
  4113. rb->ssr.blur_radius[0] = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4114. rb->ssr.blur_radius[1] = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4115. }
  4116. if (rb->blur[0].texture.is_null()) {
  4117. _allocate_blur_textures(rb);
  4118. _render_buffers_uniform_set_changed(p_render_buffers);
  4119. }
  4120. storage->get_effects()->screen_space_reflection(rb->texture, p_normal_buffer, ssr_roughness_quality, rb->ssr.blur_radius[0], rb->ssr.blur_radius[1], p_metallic, p_metallic_mask, rb->depth_texture, rb->ssr.depth_scaled, rb->ssr.normal_scaled, rb->blur[0].mipmaps[1].texture, rb->blur[1].mipmaps[0].texture, Size2i(rb->width / 2, rb->height / 2), env->ssr_max_steps, env->ssr_fade_in, env->ssr_fade_out, env->ssr_depth_tolerance, p_projection);
  4121. storage->get_effects()->merge_specular(p_dest_framebuffer, p_specular_buffer, p_use_additive ? RID() : rb->texture, rb->blur[0].mipmaps[1].texture);
  4122. }
  4123. void RasterizerSceneRD::_process_ssao(RID p_render_buffers, RID p_environment, RID p_normal_buffer, const CameraMatrix &p_projection) {
  4124. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4125. ERR_FAIL_COND(!rb);
  4126. Environment *env = environment_owner.getornull(p_environment);
  4127. ERR_FAIL_COND(!env);
  4128. if (rb->ssao.ao[0].is_valid() && rb->ssao.ao_full.is_valid() != ssao_half_size) {
  4129. RD::get_singleton()->free(rb->ssao.depth);
  4130. RD::get_singleton()->free(rb->ssao.ao[0]);
  4131. if (rb->ssao.ao[1].is_valid()) {
  4132. RD::get_singleton()->free(rb->ssao.ao[1]);
  4133. }
  4134. if (rb->ssao.ao_full.is_valid()) {
  4135. RD::get_singleton()->free(rb->ssao.ao_full);
  4136. }
  4137. rb->ssao.depth = RID();
  4138. rb->ssao.ao[0] = RID();
  4139. rb->ssao.ao[1] = RID();
  4140. rb->ssao.ao_full = RID();
  4141. rb->ssao.depth_slices.clear();
  4142. }
  4143. if (!rb->ssao.ao[0].is_valid()) {
  4144. //allocate depth slices
  4145. {
  4146. RD::TextureFormat tf;
  4147. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  4148. tf.width = rb->width / 2;
  4149. tf.height = rb->height / 2;
  4150. tf.mipmaps = Image::get_image_required_mipmaps(tf.width, tf.height, Image::FORMAT_RF) + 1;
  4151. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  4152. rb->ssao.depth = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4153. for (uint32_t i = 0; i < tf.mipmaps; i++) {
  4154. RID slice = RD::get_singleton()->texture_create_shared_from_slice(RD::TextureView(), rb->ssao.depth, 0, i);
  4155. rb->ssao.depth_slices.push_back(slice);
  4156. }
  4157. }
  4158. {
  4159. RD::TextureFormat tf;
  4160. tf.format = RD::DATA_FORMAT_R8_UNORM;
  4161. tf.width = ssao_half_size ? rb->width / 2 : rb->width;
  4162. tf.height = ssao_half_size ? rb->height / 2 : rb->height;
  4163. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  4164. rb->ssao.ao[0] = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4165. rb->ssao.ao[1] = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4166. }
  4167. if (ssao_half_size) {
  4168. //upsample texture
  4169. RD::TextureFormat tf;
  4170. tf.format = RD::DATA_FORMAT_R8_UNORM;
  4171. tf.width = rb->width;
  4172. tf.height = rb->height;
  4173. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  4174. rb->ssao.ao_full = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4175. }
  4176. _render_buffers_uniform_set_changed(p_render_buffers);
  4177. }
  4178. storage->get_effects()->generate_ssao(rb->depth_texture, p_normal_buffer, Size2i(rb->width, rb->height), rb->ssao.depth, rb->ssao.depth_slices, rb->ssao.ao[0], rb->ssao.ao_full.is_valid(), rb->ssao.ao[1], rb->ssao.ao_full, env->ssao_intensity, env->ssao_radius, env->ssao_bias, p_projection, ssao_quality, env->ssao_blur, env->ssao_blur_edge_sharpness);
  4179. }
  4180. void RasterizerSceneRD::_render_buffers_post_process_and_tonemap(RID p_render_buffers, RID p_environment, RID p_camera_effects, const CameraMatrix &p_projection) {
  4181. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4182. ERR_FAIL_COND(!rb);
  4183. Environment *env = environment_owner.getornull(p_environment);
  4184. //glow (if enabled)
  4185. CameraEffects *camfx = camera_effects_owner.getornull(p_camera_effects);
  4186. bool can_use_effects = rb->width >= 8 && rb->height >= 8;
  4187. if (can_use_effects && camfx && (camfx->dof_blur_near_enabled || camfx->dof_blur_far_enabled) && camfx->dof_blur_amount > 0.0) {
  4188. if (rb->blur[0].texture.is_null()) {
  4189. _allocate_blur_textures(rb);
  4190. _render_buffers_uniform_set_changed(p_render_buffers);
  4191. }
  4192. float bokeh_size = camfx->dof_blur_amount * 64.0;
  4193. storage->get_effects()->bokeh_dof(rb->texture, rb->depth_texture, Size2i(rb->width, rb->height), rb->blur[0].mipmaps[0].texture, rb->blur[1].mipmaps[0].texture, rb->blur[0].mipmaps[1].texture, camfx->dof_blur_far_enabled, camfx->dof_blur_far_distance, camfx->dof_blur_far_transition, camfx->dof_blur_near_enabled, camfx->dof_blur_near_distance, camfx->dof_blur_near_transition, bokeh_size, dof_blur_bokeh_shape, dof_blur_quality, dof_blur_use_jitter, p_projection.get_z_near(), p_projection.get_z_far(), p_projection.is_orthogonal());
  4194. }
  4195. if (can_use_effects && env && env->auto_exposure) {
  4196. if (rb->luminance.current.is_null()) {
  4197. _allocate_luminance_textures(rb);
  4198. _render_buffers_uniform_set_changed(p_render_buffers);
  4199. }
  4200. bool set_immediate = env->auto_exposure_version != rb->auto_exposure_version;
  4201. rb->auto_exposure_version = env->auto_exposure_version;
  4202. double step = env->auto_exp_speed * time_step;
  4203. storage->get_effects()->luminance_reduction(rb->texture, Size2i(rb->width, rb->height), rb->luminance.reduce, rb->luminance.current, env->min_luminance, env->max_luminance, step, set_immediate);
  4204. //swap final reduce with prev luminance
  4205. SWAP(rb->luminance.current, rb->luminance.reduce.write[rb->luminance.reduce.size() - 1]);
  4206. RenderingServerRaster::redraw_request(); //redraw all the time if auto exposure rendering is on
  4207. }
  4208. int max_glow_level = -1;
  4209. int glow_mask = 0;
  4210. if (can_use_effects && env && env->glow_enabled) {
  4211. /* see that blur textures are allocated */
  4212. if (rb->blur[0].texture.is_null()) {
  4213. _allocate_blur_textures(rb);
  4214. _render_buffers_uniform_set_changed(p_render_buffers);
  4215. }
  4216. for (int i = 0; i < RS::MAX_GLOW_LEVELS; i++) {
  4217. if (env->glow_levels & (1 << i)) {
  4218. if (i >= rb->blur[1].mipmaps.size()) {
  4219. max_glow_level = rb->blur[1].mipmaps.size() - 1;
  4220. glow_mask |= 1 << max_glow_level;
  4221. } else {
  4222. max_glow_level = i;
  4223. glow_mask |= (1 << i);
  4224. }
  4225. }
  4226. }
  4227. for (int i = 0; i < (max_glow_level + 1); i++) {
  4228. int vp_w = rb->blur[1].mipmaps[i].width;
  4229. int vp_h = rb->blur[1].mipmaps[i].height;
  4230. if (i == 0) {
  4231. RID luminance_texture;
  4232. if (env->auto_exposure && rb->luminance.current.is_valid()) {
  4233. luminance_texture = rb->luminance.current;
  4234. }
  4235. storage->get_effects()->gaussian_glow(rb->texture, rb->blur[0].mipmaps[i + 1].texture, rb->blur[1].mipmaps[i].texture, Size2i(vp_w, vp_h), env->glow_strength, true, env->glow_hdr_luminance_cap, env->exposure, env->glow_bloom, env->glow_hdr_bleed_threshold, env->glow_hdr_bleed_scale, luminance_texture, env->auto_exp_scale);
  4236. } else {
  4237. storage->get_effects()->gaussian_glow(rb->blur[1].mipmaps[i - 1].texture, rb->blur[0].mipmaps[i + 1].texture, rb->blur[1].mipmaps[i].texture, Size2i(vp_w, vp_h), env->glow_strength);
  4238. }
  4239. }
  4240. }
  4241. {
  4242. //tonemap
  4243. RasterizerEffectsRD::TonemapSettings tonemap;
  4244. tonemap.color_correction_texture = storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE);
  4245. if (can_use_effects && env && env->auto_exposure && rb->luminance.current.is_valid()) {
  4246. tonemap.use_auto_exposure = true;
  4247. tonemap.exposure_texture = rb->luminance.current;
  4248. tonemap.auto_exposure_grey = env->auto_exp_scale;
  4249. } else {
  4250. tonemap.exposure_texture = storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_WHITE);
  4251. }
  4252. if (can_use_effects && env && env->glow_enabled) {
  4253. tonemap.use_glow = true;
  4254. tonemap.glow_mode = RasterizerEffectsRD::TonemapSettings::GlowMode(env->glow_blend_mode);
  4255. tonemap.glow_intensity = env->glow_blend_mode == RS::ENV_GLOW_BLEND_MODE_MIX ? env->glow_mix : env->glow_intensity;
  4256. tonemap.glow_level_flags = glow_mask;
  4257. tonemap.glow_texture_size.x = rb->blur[1].mipmaps[0].width;
  4258. tonemap.glow_texture_size.y = rb->blur[1].mipmaps[0].height;
  4259. tonemap.glow_use_bicubic_upscale = glow_bicubic_upscale;
  4260. tonemap.glow_texture = rb->blur[1].texture;
  4261. } else {
  4262. tonemap.glow_texture = storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_BLACK);
  4263. }
  4264. if (rb->screen_space_aa == RS::VIEWPORT_SCREEN_SPACE_AA_FXAA) {
  4265. tonemap.use_fxaa = true;
  4266. }
  4267. tonemap.texture_size = Vector2i(rb->width, rb->height);
  4268. if (env) {
  4269. tonemap.tonemap_mode = env->tone_mapper;
  4270. tonemap.white = env->white;
  4271. tonemap.exposure = env->exposure;
  4272. }
  4273. storage->get_effects()->tonemapper(rb->texture, storage->render_target_get_rd_framebuffer(rb->render_target), tonemap);
  4274. }
  4275. storage->render_target_disable_clear_request(rb->render_target);
  4276. }
  4277. void RasterizerSceneRD::_render_buffers_debug_draw(RID p_render_buffers, RID p_shadow_atlas) {
  4278. RasterizerEffectsRD *effects = storage->get_effects();
  4279. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4280. ERR_FAIL_COND(!rb);
  4281. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SHADOW_ATLAS) {
  4282. if (p_shadow_atlas.is_valid()) {
  4283. RID shadow_atlas_texture = shadow_atlas_get_texture(p_shadow_atlas);
  4284. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4285. effects->copy_to_fb_rect(shadow_atlas_texture, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2i(Vector2(), rtsize / 2), false, true);
  4286. }
  4287. }
  4288. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_DIRECTIONAL_SHADOW_ATLAS) {
  4289. if (directional_shadow_get_texture().is_valid()) {
  4290. RID shadow_atlas_texture = directional_shadow_get_texture();
  4291. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4292. effects->copy_to_fb_rect(shadow_atlas_texture, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2i(Vector2(), rtsize / 2), false, true);
  4293. }
  4294. }
  4295. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_DECAL_ATLAS) {
  4296. RID decal_atlas = storage->decal_atlas_get_texture();
  4297. if (decal_atlas.is_valid()) {
  4298. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4299. effects->copy_to_fb_rect(decal_atlas, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2i(Vector2(), rtsize / 2), false, false, true);
  4300. }
  4301. }
  4302. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SCENE_LUMINANCE) {
  4303. if (rb->luminance.current.is_valid()) {
  4304. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4305. effects->copy_to_fb_rect(rb->luminance.current, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize / 8), false, true);
  4306. }
  4307. }
  4308. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SSAO && rb->ssao.ao[0].is_valid()) {
  4309. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4310. RID ao_buf = rb->ssao.ao_full.is_valid() ? rb->ssao.ao_full : rb->ssao.ao[0];
  4311. effects->copy_to_fb_rect(ao_buf, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize), false, true);
  4312. }
  4313. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_NORMAL_BUFFER && _render_buffers_get_normal_texture(p_render_buffers).is_valid()) {
  4314. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4315. effects->copy_to_fb_rect(_render_buffers_get_normal_texture(p_render_buffers), storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize), false, false);
  4316. }
  4317. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_GI_BUFFER && _render_buffers_get_ambient_texture(p_render_buffers).is_valid()) {
  4318. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4319. RID ambient_texture = _render_buffers_get_ambient_texture(p_render_buffers);
  4320. RID reflection_texture = _render_buffers_get_reflection_texture(p_render_buffers);
  4321. effects->copy_to_fb_rect(ambient_texture, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize), false, false, false, true, reflection_texture);
  4322. }
  4323. }
  4324. void RasterizerSceneRD::_sdfgi_debug_draw(RID p_render_buffers, const CameraMatrix &p_projection, const Transform &p_transform) {
  4325. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4326. ERR_FAIL_COND(!rb);
  4327. if (!rb->sdfgi) {
  4328. return; //eh
  4329. }
  4330. if (!rb->sdfgi->debug_uniform_set.is_valid() || !RD::get_singleton()->uniform_set_is_valid(rb->sdfgi->debug_uniform_set)) {
  4331. Vector<RD::Uniform> uniforms;
  4332. {
  4333. RD::Uniform u;
  4334. u.binding = 1;
  4335. u.type = RD::UNIFORM_TYPE_TEXTURE;
  4336. for (uint32_t i = 0; i < SDFGI::MAX_CASCADES; i++) {
  4337. if (i < rb->sdfgi->cascades.size()) {
  4338. u.ids.push_back(rb->sdfgi->cascades[i].sdf_tex);
  4339. } else {
  4340. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  4341. }
  4342. }
  4343. uniforms.push_back(u);
  4344. }
  4345. {
  4346. RD::Uniform u;
  4347. u.binding = 2;
  4348. u.type = RD::UNIFORM_TYPE_TEXTURE;
  4349. for (uint32_t i = 0; i < SDFGI::MAX_CASCADES; i++) {
  4350. if (i < rb->sdfgi->cascades.size()) {
  4351. u.ids.push_back(rb->sdfgi->cascades[i].light_tex);
  4352. } else {
  4353. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  4354. }
  4355. }
  4356. uniforms.push_back(u);
  4357. }
  4358. {
  4359. RD::Uniform u;
  4360. u.binding = 3;
  4361. u.type = RD::UNIFORM_TYPE_TEXTURE;
  4362. for (uint32_t i = 0; i < SDFGI::MAX_CASCADES; i++) {
  4363. if (i < rb->sdfgi->cascades.size()) {
  4364. u.ids.push_back(rb->sdfgi->cascades[i].light_aniso_0_tex);
  4365. } else {
  4366. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  4367. }
  4368. }
  4369. uniforms.push_back(u);
  4370. }
  4371. {
  4372. RD::Uniform u;
  4373. u.binding = 4;
  4374. u.type = RD::UNIFORM_TYPE_TEXTURE;
  4375. for (uint32_t i = 0; i < SDFGI::MAX_CASCADES; i++) {
  4376. if (i < rb->sdfgi->cascades.size()) {
  4377. u.ids.push_back(rb->sdfgi->cascades[i].light_aniso_1_tex);
  4378. } else {
  4379. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  4380. }
  4381. }
  4382. uniforms.push_back(u);
  4383. }
  4384. {
  4385. RD::Uniform u;
  4386. u.binding = 5;
  4387. u.type = RD::UNIFORM_TYPE_TEXTURE;
  4388. u.ids.push_back(rb->sdfgi->occlusion_texture);
  4389. uniforms.push_back(u);
  4390. }
  4391. {
  4392. RD::Uniform u;
  4393. u.binding = 8;
  4394. u.type = RD::UNIFORM_TYPE_SAMPLER;
  4395. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  4396. uniforms.push_back(u);
  4397. }
  4398. {
  4399. RD::Uniform u;
  4400. u.binding = 9;
  4401. u.type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  4402. u.ids.push_back(rb->sdfgi->cascades_ubo);
  4403. uniforms.push_back(u);
  4404. }
  4405. {
  4406. RD::Uniform u;
  4407. u.binding = 10;
  4408. u.type = RD::UNIFORM_TYPE_IMAGE;
  4409. u.ids.push_back(rb->texture);
  4410. uniforms.push_back(u);
  4411. }
  4412. {
  4413. RD::Uniform u;
  4414. u.binding = 11;
  4415. u.type = RD::UNIFORM_TYPE_TEXTURE;
  4416. u.ids.push_back(rb->sdfgi->lightprobe_texture);
  4417. uniforms.push_back(u);
  4418. }
  4419. rb->sdfgi->debug_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.debug_shader_version, 0);
  4420. }
  4421. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  4422. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.debug_pipeline);
  4423. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->debug_uniform_set, 0);
  4424. SDGIShader::DebugPushConstant push_constant;
  4425. push_constant.grid_size[0] = rb->sdfgi->cascade_size;
  4426. push_constant.grid_size[1] = rb->sdfgi->cascade_size;
  4427. push_constant.grid_size[2] = rb->sdfgi->cascade_size;
  4428. push_constant.max_cascades = rb->sdfgi->cascades.size();
  4429. push_constant.screen_size[0] = rb->width;
  4430. push_constant.screen_size[1] = rb->height;
  4431. push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
  4432. push_constant.use_occlusion = rb->sdfgi->uses_occlusion;
  4433. push_constant.y_mult = rb->sdfgi->y_mult;
  4434. Vector2 vp_half = p_projection.get_viewport_half_extents();
  4435. push_constant.cam_extent[0] = vp_half.x;
  4436. push_constant.cam_extent[1] = vp_half.y;
  4437. push_constant.cam_extent[2] = -p_projection.get_z_near();
  4438. push_constant.cam_transform[0] = p_transform.basis.elements[0][0];
  4439. push_constant.cam_transform[1] = p_transform.basis.elements[1][0];
  4440. push_constant.cam_transform[2] = p_transform.basis.elements[2][0];
  4441. push_constant.cam_transform[3] = 0;
  4442. push_constant.cam_transform[4] = p_transform.basis.elements[0][1];
  4443. push_constant.cam_transform[5] = p_transform.basis.elements[1][1];
  4444. push_constant.cam_transform[6] = p_transform.basis.elements[2][1];
  4445. push_constant.cam_transform[7] = 0;
  4446. push_constant.cam_transform[8] = p_transform.basis.elements[0][2];
  4447. push_constant.cam_transform[9] = p_transform.basis.elements[1][2];
  4448. push_constant.cam_transform[10] = p_transform.basis.elements[2][2];
  4449. push_constant.cam_transform[11] = 0;
  4450. push_constant.cam_transform[12] = p_transform.origin.x;
  4451. push_constant.cam_transform[13] = p_transform.origin.y;
  4452. push_constant.cam_transform[14] = p_transform.origin.z;
  4453. push_constant.cam_transform[15] = 1;
  4454. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::DebugPushConstant));
  4455. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->width, rb->height, 1, 8, 8, 1);
  4456. RD::get_singleton()->compute_list_end();
  4457. Size2 rtsize = storage->render_target_get_size(rb->render_target);
  4458. storage->get_effects()->copy_to_fb_rect(rb->texture, storage->render_target_get_rd_framebuffer(rb->render_target), Rect2(Vector2(), rtsize), true);
  4459. }
  4460. RID RasterizerSceneRD::render_buffers_get_back_buffer_texture(RID p_render_buffers) {
  4461. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4462. ERR_FAIL_COND_V(!rb, RID());
  4463. if (!rb->blur[0].texture.is_valid()) {
  4464. return RID(); //not valid at the moment
  4465. }
  4466. return rb->blur[0].texture;
  4467. }
  4468. RID RasterizerSceneRD::render_buffers_get_ao_texture(RID p_render_buffers) {
  4469. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4470. ERR_FAIL_COND_V(!rb, RID());
  4471. return rb->ssao.ao_full.is_valid() ? rb->ssao.ao_full : rb->ssao.ao[0];
  4472. }
  4473. RID RasterizerSceneRD::render_buffers_get_gi_probe_buffer(RID p_render_buffers) {
  4474. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4475. ERR_FAIL_COND_V(!rb, RID());
  4476. if (rb->giprobe_buffer.is_null()) {
  4477. rb->giprobe_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(GI::GIProbeData) * RenderBuffers::MAX_GIPROBES);
  4478. }
  4479. return rb->giprobe_buffer;
  4480. }
  4481. RID RasterizerSceneRD::render_buffers_get_default_gi_probe_buffer() {
  4482. return default_giprobe_buffer;
  4483. }
  4484. uint32_t RasterizerSceneRD::render_buffers_get_sdfgi_cascade_count(RID p_render_buffers) const {
  4485. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4486. ERR_FAIL_COND_V(!rb, 0);
  4487. ERR_FAIL_COND_V(!rb->sdfgi, 0);
  4488. return rb->sdfgi->cascades.size();
  4489. }
  4490. bool RasterizerSceneRD::render_buffers_is_sdfgi_enabled(RID p_render_buffers) const {
  4491. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4492. ERR_FAIL_COND_V(!rb, false);
  4493. return rb->sdfgi != nullptr;
  4494. }
  4495. RID RasterizerSceneRD::render_buffers_get_sdfgi_irradiance_probes(RID p_render_buffers) const {
  4496. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4497. ERR_FAIL_COND_V(!rb, RID());
  4498. ERR_FAIL_COND_V(!rb->sdfgi, RID());
  4499. return rb->sdfgi->lightprobe_texture;
  4500. }
  4501. Vector3 RasterizerSceneRD::render_buffers_get_sdfgi_cascade_offset(RID p_render_buffers, uint32_t p_cascade) const {
  4502. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4503. ERR_FAIL_COND_V(!rb, Vector3());
  4504. ERR_FAIL_COND_V(!rb->sdfgi, Vector3());
  4505. ERR_FAIL_UNSIGNED_INDEX_V(p_cascade, rb->sdfgi->cascades.size(), Vector3());
  4506. return Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + rb->sdfgi->cascades[p_cascade].position)) * rb->sdfgi->cascades[p_cascade].cell_size;
  4507. }
  4508. Vector3i RasterizerSceneRD::render_buffers_get_sdfgi_cascade_probe_offset(RID p_render_buffers, uint32_t p_cascade) const {
  4509. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4510. ERR_FAIL_COND_V(!rb, Vector3i());
  4511. ERR_FAIL_COND_V(!rb->sdfgi, Vector3i());
  4512. ERR_FAIL_UNSIGNED_INDEX_V(p_cascade, rb->sdfgi->cascades.size(), Vector3i());
  4513. int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
  4514. return rb->sdfgi->cascades[p_cascade].position / probe_divisor;
  4515. }
  4516. float RasterizerSceneRD::render_buffers_get_sdfgi_normal_bias(RID p_render_buffers) const {
  4517. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4518. ERR_FAIL_COND_V(!rb, 0);
  4519. ERR_FAIL_COND_V(!rb->sdfgi, 0);
  4520. return rb->sdfgi->normal_bias;
  4521. }
  4522. float RasterizerSceneRD::render_buffers_get_sdfgi_cascade_probe_size(RID p_render_buffers, uint32_t p_cascade) const {
  4523. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4524. ERR_FAIL_COND_V(!rb, 0);
  4525. ERR_FAIL_COND_V(!rb->sdfgi, 0);
  4526. ERR_FAIL_UNSIGNED_INDEX_V(p_cascade, rb->sdfgi->cascades.size(), 0);
  4527. return float(rb->sdfgi->cascade_size) * rb->sdfgi->cascades[p_cascade].cell_size / float(rb->sdfgi->probe_axis_count - 1);
  4528. }
  4529. uint32_t RasterizerSceneRD::render_buffers_get_sdfgi_cascade_probe_count(RID p_render_buffers) const {
  4530. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4531. ERR_FAIL_COND_V(!rb, 0);
  4532. ERR_FAIL_COND_V(!rb->sdfgi, 0);
  4533. return rb->sdfgi->probe_axis_count;
  4534. }
  4535. uint32_t RasterizerSceneRD::render_buffers_get_sdfgi_cascade_size(RID p_render_buffers) const {
  4536. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4537. ERR_FAIL_COND_V(!rb, 0);
  4538. ERR_FAIL_COND_V(!rb->sdfgi, 0);
  4539. return rb->sdfgi->cascade_size;
  4540. }
  4541. bool RasterizerSceneRD::render_buffers_is_sdfgi_using_occlusion(RID p_render_buffers) const {
  4542. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4543. ERR_FAIL_COND_V(!rb, false);
  4544. ERR_FAIL_COND_V(!rb->sdfgi, false);
  4545. return rb->sdfgi->uses_occlusion;
  4546. }
  4547. float RasterizerSceneRD::render_buffers_get_sdfgi_energy(RID p_render_buffers) const {
  4548. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4549. ERR_FAIL_COND_V(!rb, 0);
  4550. ERR_FAIL_COND_V(!rb->sdfgi, false);
  4551. return rb->sdfgi->energy;
  4552. }
  4553. RID RasterizerSceneRD::render_buffers_get_sdfgi_occlusion_texture(RID p_render_buffers) const {
  4554. const RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4555. ERR_FAIL_COND_V(!rb, RID());
  4556. ERR_FAIL_COND_V(!rb->sdfgi, RID());
  4557. return rb->sdfgi->occlusion_texture;
  4558. }
  4559. void RasterizerSceneRD::render_buffers_configure(RID p_render_buffers, RID p_render_target, int p_width, int p_height, RS::ViewportMSAA p_msaa, RenderingServer::ViewportScreenSpaceAA p_screen_space_aa) {
  4560. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4561. rb->width = p_width;
  4562. rb->height = p_height;
  4563. rb->render_target = p_render_target;
  4564. rb->msaa = p_msaa;
  4565. rb->screen_space_aa = p_screen_space_aa;
  4566. _free_render_buffer_data(rb);
  4567. {
  4568. RD::TextureFormat tf;
  4569. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  4570. tf.width = rb->width;
  4571. tf.height = rb->height;
  4572. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  4573. if (rb->msaa != RS::VIEWPORT_MSAA_DISABLED) {
  4574. tf.usage_bits |= RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  4575. } else {
  4576. tf.usage_bits |= RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  4577. }
  4578. rb->texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4579. }
  4580. {
  4581. RD::TextureFormat tf;
  4582. if (rb->msaa == RS::VIEWPORT_MSAA_DISABLED) {
  4583. tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D24_UNORM_S8_UINT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D24_UNORM_S8_UINT : RD::DATA_FORMAT_D32_SFLOAT_S8_UINT;
  4584. } else {
  4585. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  4586. }
  4587. tf.width = p_width;
  4588. tf.height = p_height;
  4589. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT;
  4590. if (rb->msaa != RS::VIEWPORT_MSAA_DISABLED) {
  4591. tf.usage_bits |= RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;
  4592. } else {
  4593. tf.usage_bits |= RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  4594. }
  4595. rb->depth_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  4596. }
  4597. rb->data->configure(rb->texture, rb->depth_texture, p_width, p_height, p_msaa);
  4598. _render_buffers_uniform_set_changed(p_render_buffers);
  4599. }
  4600. void RasterizerSceneRD::sub_surface_scattering_set_quality(RS::SubSurfaceScatteringQuality p_quality) {
  4601. sss_quality = p_quality;
  4602. }
  4603. RS::SubSurfaceScatteringQuality RasterizerSceneRD::sub_surface_scattering_get_quality() const {
  4604. return sss_quality;
  4605. }
  4606. void RasterizerSceneRD::sub_surface_scattering_set_scale(float p_scale, float p_depth_scale) {
  4607. sss_scale = p_scale;
  4608. sss_depth_scale = p_depth_scale;
  4609. }
  4610. void RasterizerSceneRD::shadows_quality_set(RS::ShadowQuality p_quality) {
  4611. ERR_FAIL_INDEX_MSG(p_quality, RS::SHADOW_QUALITY_MAX, "Shadow quality too high, please see RenderingServer's ShadowQuality enum");
  4612. if (shadows_quality != p_quality) {
  4613. shadows_quality = p_quality;
  4614. switch (shadows_quality) {
  4615. case RS::SHADOW_QUALITY_HARD: {
  4616. penumbra_shadow_samples = 4;
  4617. soft_shadow_samples = 1;
  4618. shadows_quality_radius = 1.0;
  4619. } break;
  4620. case RS::SHADOW_QUALITY_SOFT_LOW: {
  4621. penumbra_shadow_samples = 8;
  4622. soft_shadow_samples = 4;
  4623. shadows_quality_radius = 2.0;
  4624. } break;
  4625. case RS::SHADOW_QUALITY_SOFT_MEDIUM: {
  4626. penumbra_shadow_samples = 12;
  4627. soft_shadow_samples = 8;
  4628. shadows_quality_radius = 2.0;
  4629. } break;
  4630. case RS::SHADOW_QUALITY_SOFT_HIGH: {
  4631. penumbra_shadow_samples = 24;
  4632. soft_shadow_samples = 16;
  4633. shadows_quality_radius = 3.0;
  4634. } break;
  4635. case RS::SHADOW_QUALITY_SOFT_ULTRA: {
  4636. penumbra_shadow_samples = 32;
  4637. soft_shadow_samples = 32;
  4638. shadows_quality_radius = 4.0;
  4639. } break;
  4640. case RS::SHADOW_QUALITY_MAX:
  4641. break;
  4642. }
  4643. get_vogel_disk(penumbra_shadow_kernel, penumbra_shadow_samples);
  4644. get_vogel_disk(soft_shadow_kernel, soft_shadow_samples);
  4645. }
  4646. }
  4647. void RasterizerSceneRD::directional_shadow_quality_set(RS::ShadowQuality p_quality) {
  4648. ERR_FAIL_INDEX_MSG(p_quality, RS::SHADOW_QUALITY_MAX, "Shadow quality too high, please see RenderingServer's ShadowQuality enum");
  4649. if (directional_shadow_quality != p_quality) {
  4650. directional_shadow_quality = p_quality;
  4651. switch (directional_shadow_quality) {
  4652. case RS::SHADOW_QUALITY_HARD: {
  4653. directional_penumbra_shadow_samples = 4;
  4654. directional_soft_shadow_samples = 1;
  4655. directional_shadow_quality_radius = 1.0;
  4656. } break;
  4657. case RS::SHADOW_QUALITY_SOFT_LOW: {
  4658. directional_penumbra_shadow_samples = 8;
  4659. directional_soft_shadow_samples = 4;
  4660. directional_shadow_quality_radius = 2.0;
  4661. } break;
  4662. case RS::SHADOW_QUALITY_SOFT_MEDIUM: {
  4663. directional_penumbra_shadow_samples = 12;
  4664. directional_soft_shadow_samples = 8;
  4665. directional_shadow_quality_radius = 2.0;
  4666. } break;
  4667. case RS::SHADOW_QUALITY_SOFT_HIGH: {
  4668. directional_penumbra_shadow_samples = 24;
  4669. directional_soft_shadow_samples = 16;
  4670. directional_shadow_quality_radius = 3.0;
  4671. } break;
  4672. case RS::SHADOW_QUALITY_SOFT_ULTRA: {
  4673. directional_penumbra_shadow_samples = 32;
  4674. directional_soft_shadow_samples = 32;
  4675. directional_shadow_quality_radius = 4.0;
  4676. } break;
  4677. case RS::SHADOW_QUALITY_MAX:
  4678. break;
  4679. }
  4680. get_vogel_disk(directional_penumbra_shadow_kernel, directional_penumbra_shadow_samples);
  4681. get_vogel_disk(directional_soft_shadow_kernel, directional_soft_shadow_samples);
  4682. }
  4683. }
  4684. int RasterizerSceneRD::get_roughness_layers() const {
  4685. return roughness_layers;
  4686. }
  4687. bool RasterizerSceneRD::is_using_radiance_cubemap_array() const {
  4688. return sky_use_cubemap_array;
  4689. }
  4690. RasterizerSceneRD::RenderBufferData *RasterizerSceneRD::render_buffers_get_data(RID p_render_buffers) {
  4691. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  4692. ERR_FAIL_COND_V(!rb, nullptr);
  4693. return rb->data;
  4694. }
  4695. void RasterizerSceneRD::_setup_reflections(RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, const Transform &p_camera_inverse_transform, RID p_environment) {
  4696. for (int i = 0; i < p_reflection_probe_cull_count; i++) {
  4697. RID rpi = p_reflection_probe_cull_result[i];
  4698. if (i >= (int)cluster.max_reflections) {
  4699. reflection_probe_instance_set_render_index(rpi, 0); //invalid, but something needs to be set
  4700. continue;
  4701. }
  4702. reflection_probe_instance_set_render_index(rpi, i);
  4703. RID base_probe = reflection_probe_instance_get_probe(rpi);
  4704. Cluster::ReflectionData &reflection_ubo = cluster.reflections[i];
  4705. Vector3 extents = storage->reflection_probe_get_extents(base_probe);
  4706. reflection_ubo.box_extents[0] = extents.x;
  4707. reflection_ubo.box_extents[1] = extents.y;
  4708. reflection_ubo.box_extents[2] = extents.z;
  4709. reflection_ubo.index = reflection_probe_instance_get_atlas_index(rpi);
  4710. Vector3 origin_offset = storage->reflection_probe_get_origin_offset(base_probe);
  4711. reflection_ubo.box_offset[0] = origin_offset.x;
  4712. reflection_ubo.box_offset[1] = origin_offset.y;
  4713. reflection_ubo.box_offset[2] = origin_offset.z;
  4714. reflection_ubo.mask = storage->reflection_probe_get_cull_mask(base_probe);
  4715. float intensity = storage->reflection_probe_get_intensity(base_probe);
  4716. bool interior = storage->reflection_probe_is_interior(base_probe);
  4717. bool box_projection = storage->reflection_probe_is_box_projection(base_probe);
  4718. reflection_ubo.params[0] = intensity;
  4719. reflection_ubo.params[1] = 0;
  4720. reflection_ubo.params[2] = interior ? 1.0 : 0.0;
  4721. reflection_ubo.params[3] = box_projection ? 1.0 : 0.0;
  4722. Color ambient_linear = storage->reflection_probe_get_ambient_color(base_probe).to_linear();
  4723. float interior_ambient_energy = storage->reflection_probe_get_ambient_color_energy(base_probe);
  4724. uint32_t ambient_mode = storage->reflection_probe_get_ambient_mode(base_probe);
  4725. reflection_ubo.ambient[0] = ambient_linear.r * interior_ambient_energy;
  4726. reflection_ubo.ambient[1] = ambient_linear.g * interior_ambient_energy;
  4727. reflection_ubo.ambient[2] = ambient_linear.b * interior_ambient_energy;
  4728. reflection_ubo.ambient_mode = ambient_mode;
  4729. Transform transform = reflection_probe_instance_get_transform(rpi);
  4730. Transform proj = (p_camera_inverse_transform * transform).inverse();
  4731. RasterizerStorageRD::store_transform(proj, reflection_ubo.local_matrix);
  4732. cluster.builder.add_reflection_probe(transform, extents);
  4733. reflection_probe_instance_set_render_pass(rpi, RSG::rasterizer->get_frame_number());
  4734. }
  4735. if (p_reflection_probe_cull_count) {
  4736. RD::get_singleton()->buffer_update(cluster.reflection_buffer, 0, MIN(cluster.max_reflections, (unsigned int)p_reflection_probe_cull_count) * sizeof(ReflectionData), cluster.reflections, true);
  4737. }
  4738. }
  4739. void RasterizerSceneRD::_setup_lights(RID *p_light_cull_result, int p_light_cull_count, const Transform &p_camera_inverse_transform, RID p_shadow_atlas, bool p_using_shadows, uint32_t &r_directional_light_count) {
  4740. uint32_t light_count = 0;
  4741. r_directional_light_count = 0;
  4742. sky_scene_state.directional_light_count = 0;
  4743. for (int i = 0; i < p_light_cull_count; i++) {
  4744. RID li = p_light_cull_result[i];
  4745. RID base = light_instance_get_base_light(li);
  4746. ERR_CONTINUE(base.is_null());
  4747. RS::LightType type = storage->light_get_type(base);
  4748. switch (type) {
  4749. case RS::LIGHT_DIRECTIONAL: {
  4750. if (r_directional_light_count >= cluster.max_directional_lights) {
  4751. continue;
  4752. }
  4753. Cluster::DirectionalLightData &light_data = cluster.directional_lights[r_directional_light_count];
  4754. Transform light_transform = light_instance_get_base_transform(li);
  4755. Vector3 direction = p_camera_inverse_transform.basis.xform(light_transform.basis.xform(Vector3(0, 0, 1))).normalized();
  4756. light_data.direction[0] = direction.x;
  4757. light_data.direction[1] = direction.y;
  4758. light_data.direction[2] = direction.z;
  4759. float sign = storage->light_is_negative(base) ? -1 : 1;
  4760. light_data.energy = sign * storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY) * Math_PI;
  4761. Color linear_col = storage->light_get_color(base).to_linear();
  4762. light_data.color[0] = linear_col.r;
  4763. light_data.color[1] = linear_col.g;
  4764. light_data.color[2] = linear_col.b;
  4765. light_data.specular = storage->light_get_param(base, RS::LIGHT_PARAM_SPECULAR);
  4766. light_data.mask = storage->light_get_cull_mask(base);
  4767. float size = storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  4768. light_data.size = 1.0 - Math::cos(Math::deg2rad(size)); //angle to cosine offset
  4769. Color shadow_col = storage->light_get_shadow_color(base).to_linear();
  4770. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_PSSM_SPLITS) {
  4771. light_data.shadow_color1[0] = 1.0;
  4772. light_data.shadow_color1[1] = 0.0;
  4773. light_data.shadow_color1[2] = 0.0;
  4774. light_data.shadow_color1[3] = 1.0;
  4775. light_data.shadow_color2[0] = 0.0;
  4776. light_data.shadow_color2[1] = 1.0;
  4777. light_data.shadow_color2[2] = 0.0;
  4778. light_data.shadow_color2[3] = 1.0;
  4779. light_data.shadow_color3[0] = 0.0;
  4780. light_data.shadow_color3[1] = 0.0;
  4781. light_data.shadow_color3[2] = 1.0;
  4782. light_data.shadow_color3[3] = 1.0;
  4783. light_data.shadow_color4[0] = 1.0;
  4784. light_data.shadow_color4[1] = 1.0;
  4785. light_data.shadow_color4[2] = 0.0;
  4786. light_data.shadow_color4[3] = 1.0;
  4787. } else {
  4788. light_data.shadow_color1[0] = shadow_col.r;
  4789. light_data.shadow_color1[1] = shadow_col.g;
  4790. light_data.shadow_color1[2] = shadow_col.b;
  4791. light_data.shadow_color1[3] = 1.0;
  4792. light_data.shadow_color2[0] = shadow_col.r;
  4793. light_data.shadow_color2[1] = shadow_col.g;
  4794. light_data.shadow_color2[2] = shadow_col.b;
  4795. light_data.shadow_color2[3] = 1.0;
  4796. light_data.shadow_color3[0] = shadow_col.r;
  4797. light_data.shadow_color3[1] = shadow_col.g;
  4798. light_data.shadow_color3[2] = shadow_col.b;
  4799. light_data.shadow_color3[3] = 1.0;
  4800. light_data.shadow_color4[0] = shadow_col.r;
  4801. light_data.shadow_color4[1] = shadow_col.g;
  4802. light_data.shadow_color4[2] = shadow_col.b;
  4803. light_data.shadow_color4[3] = 1.0;
  4804. }
  4805. light_data.shadow_enabled = p_using_shadows && storage->light_has_shadow(base);
  4806. float angular_diameter = storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  4807. if (angular_diameter > 0.0) {
  4808. // I know tan(0) is 0, but let's not risk it with numerical precision.
  4809. // technically this will keep expanding until reaching the sun, but all we care
  4810. // is expand until we reach the radius of the near plane (there can't be more occluders than that)
  4811. angular_diameter = Math::tan(Math::deg2rad(angular_diameter));
  4812. } else {
  4813. angular_diameter = 0.0;
  4814. }
  4815. if (light_data.shadow_enabled) {
  4816. RS::LightDirectionalShadowMode smode = storage->light_directional_get_shadow_mode(base);
  4817. int limit = smode == RS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL ? 0 : (smode == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS ? 1 : 3);
  4818. light_data.blend_splits = storage->light_directional_get_blend_splits(base);
  4819. for (int j = 0; j < 4; j++) {
  4820. Rect2 atlas_rect = light_instance_get_directional_shadow_atlas_rect(li, j);
  4821. CameraMatrix matrix = light_instance_get_shadow_camera(li, j);
  4822. float split = light_instance_get_directional_shadow_split(li, MIN(limit, j));
  4823. CameraMatrix bias;
  4824. bias.set_light_bias();
  4825. CameraMatrix rectm;
  4826. rectm.set_light_atlas_rect(atlas_rect);
  4827. Transform modelview = (p_camera_inverse_transform * light_instance_get_shadow_transform(li, j)).inverse();
  4828. CameraMatrix shadow_mtx = rectm * bias * matrix * modelview;
  4829. light_data.shadow_split_offsets[j] = split;
  4830. float bias_scale = light_instance_get_shadow_bias_scale(li, j);
  4831. light_data.shadow_bias[j] = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) * bias_scale;
  4832. light_data.shadow_normal_bias[j] = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * light_instance_get_directional_shadow_texel_size(li, j);
  4833. light_data.shadow_transmittance_bias[j] = storage->light_get_transmittance_bias(base) * bias_scale;
  4834. light_data.shadow_transmittance_z_scale[j] = light_instance_get_shadow_range(li, j);
  4835. light_data.shadow_range_begin[j] = light_instance_get_shadow_range_begin(li, j);
  4836. RasterizerStorageRD::store_camera(shadow_mtx, light_data.shadow_matrices[j]);
  4837. Vector2 uv_scale = light_instance_get_shadow_uv_scale(li, j);
  4838. uv_scale *= atlas_rect.size; //adapt to atlas size
  4839. switch (j) {
  4840. case 0: {
  4841. light_data.uv_scale1[0] = uv_scale.x;
  4842. light_data.uv_scale1[1] = uv_scale.y;
  4843. } break;
  4844. case 1: {
  4845. light_data.uv_scale2[0] = uv_scale.x;
  4846. light_data.uv_scale2[1] = uv_scale.y;
  4847. } break;
  4848. case 2: {
  4849. light_data.uv_scale3[0] = uv_scale.x;
  4850. light_data.uv_scale3[1] = uv_scale.y;
  4851. } break;
  4852. case 3: {
  4853. light_data.uv_scale4[0] = uv_scale.x;
  4854. light_data.uv_scale4[1] = uv_scale.y;
  4855. } break;
  4856. }
  4857. }
  4858. float fade_start = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_FADE_START);
  4859. light_data.fade_from = -light_data.shadow_split_offsets[3] * MIN(fade_start, 0.999); //using 1.0 would break smoothstep
  4860. light_data.fade_to = -light_data.shadow_split_offsets[3];
  4861. light_data.soft_shadow_scale = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BLUR);
  4862. light_data.softshadow_angle = angular_diameter;
  4863. if (angular_diameter <= 0.0) {
  4864. light_data.soft_shadow_scale *= directional_shadow_quality_radius_get(); // Only use quality radius for PCF
  4865. }
  4866. }
  4867. // Copy to SkyDirectionalLightData
  4868. if (r_directional_light_count < sky_scene_state.max_directional_lights) {
  4869. SkyDirectionalLightData &sky_light_data = sky_scene_state.directional_lights[r_directional_light_count];
  4870. Vector3 world_direction = light_transform.basis.xform(Vector3(0, 0, 1)).normalized();
  4871. sky_light_data.direction[0] = world_direction.x;
  4872. sky_light_data.direction[1] = world_direction.y;
  4873. sky_light_data.direction[2] = -world_direction.z;
  4874. sky_light_data.energy = light_data.energy / Math_PI;
  4875. sky_light_data.color[0] = light_data.color[0];
  4876. sky_light_data.color[1] = light_data.color[1];
  4877. sky_light_data.color[2] = light_data.color[2];
  4878. sky_light_data.enabled = true;
  4879. sky_light_data.size = angular_diameter;
  4880. sky_scene_state.directional_light_count++;
  4881. }
  4882. r_directional_light_count++;
  4883. } break;
  4884. case RS::LIGHT_SPOT:
  4885. case RS::LIGHT_OMNI: {
  4886. if (light_count >= cluster.max_lights) {
  4887. continue;
  4888. }
  4889. Transform light_transform = light_instance_get_base_transform(li);
  4890. Cluster::LightData &light_data = cluster.lights[light_count];
  4891. float sign = storage->light_is_negative(base) ? -1 : 1;
  4892. Color linear_col = storage->light_get_color(base).to_linear();
  4893. light_data.attenuation_energy[0] = Math::make_half_float(storage->light_get_param(base, RS::LIGHT_PARAM_ATTENUATION));
  4894. light_data.attenuation_energy[1] = Math::make_half_float(sign * storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY) * Math_PI);
  4895. light_data.color_specular[0] = MIN(uint32_t(linear_col.r * 255), 255);
  4896. light_data.color_specular[1] = MIN(uint32_t(linear_col.g * 255), 255);
  4897. light_data.color_specular[2] = MIN(uint32_t(linear_col.b * 255), 255);
  4898. light_data.color_specular[3] = MIN(uint32_t(storage->light_get_param(base, RS::LIGHT_PARAM_SPECULAR) * 255), 255);
  4899. float radius = MAX(0.001, storage->light_get_param(base, RS::LIGHT_PARAM_RANGE));
  4900. light_data.inv_radius = 1.0 / radius;
  4901. Vector3 pos = p_camera_inverse_transform.xform(light_transform.origin);
  4902. light_data.position[0] = pos.x;
  4903. light_data.position[1] = pos.y;
  4904. light_data.position[2] = pos.z;
  4905. Vector3 direction = p_camera_inverse_transform.basis.xform(light_transform.basis.xform(Vector3(0, 0, -1))).normalized();
  4906. light_data.direction[0] = direction.x;
  4907. light_data.direction[1] = direction.y;
  4908. light_data.direction[2] = direction.z;
  4909. float size = storage->light_get_param(base, RS::LIGHT_PARAM_SIZE);
  4910. light_data.size = size;
  4911. light_data.cone_attenuation_angle[0] = Math::make_half_float(storage->light_get_param(base, RS::LIGHT_PARAM_SPOT_ATTENUATION));
  4912. float spot_angle = storage->light_get_param(base, RS::LIGHT_PARAM_SPOT_ANGLE);
  4913. light_data.cone_attenuation_angle[1] = Math::make_half_float(Math::cos(Math::deg2rad(spot_angle)));
  4914. light_data.mask = storage->light_get_cull_mask(base);
  4915. light_data.atlas_rect[0] = 0;
  4916. light_data.atlas_rect[1] = 0;
  4917. light_data.atlas_rect[2] = 0;
  4918. light_data.atlas_rect[3] = 0;
  4919. RID projector = storage->light_get_projector(base);
  4920. if (projector.is_valid()) {
  4921. Rect2 rect = storage->decal_atlas_get_texture_rect(projector);
  4922. if (type == RS::LIGHT_SPOT) {
  4923. light_data.projector_rect[0] = rect.position.x;
  4924. light_data.projector_rect[1] = rect.position.y + rect.size.height; //flip because shadow is flipped
  4925. light_data.projector_rect[2] = rect.size.width;
  4926. light_data.projector_rect[3] = -rect.size.height;
  4927. } else {
  4928. light_data.projector_rect[0] = rect.position.x;
  4929. light_data.projector_rect[1] = rect.position.y;
  4930. light_data.projector_rect[2] = rect.size.width;
  4931. light_data.projector_rect[3] = rect.size.height * 0.5; //used by dp, so needs to be half
  4932. }
  4933. } else {
  4934. light_data.projector_rect[0] = 0;
  4935. light_data.projector_rect[1] = 0;
  4936. light_data.projector_rect[2] = 0;
  4937. light_data.projector_rect[3] = 0;
  4938. }
  4939. if (p_using_shadows && p_shadow_atlas.is_valid() && shadow_atlas_owns_light_instance(p_shadow_atlas, li)) {
  4940. // fill in the shadow information
  4941. Color shadow_color = storage->light_get_shadow_color(base);
  4942. light_data.shadow_color_enabled[0] = MIN(uint32_t(shadow_color.r * 255), 255);
  4943. light_data.shadow_color_enabled[1] = MIN(uint32_t(shadow_color.g * 255), 255);
  4944. light_data.shadow_color_enabled[2] = MIN(uint32_t(shadow_color.b * 255), 255);
  4945. light_data.shadow_color_enabled[3] = 255;
  4946. if (type == RS::LIGHT_SPOT) {
  4947. light_data.shadow_bias = (storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) * radius / 10.0);
  4948. float shadow_texel_size = Math::tan(Math::deg2rad(spot_angle)) * radius * 2.0;
  4949. shadow_texel_size *= light_instance_get_shadow_texel_size(li, p_shadow_atlas);
  4950. light_data.shadow_normal_bias = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * shadow_texel_size;
  4951. } else { //omni
  4952. light_data.shadow_bias = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BIAS) * radius / 10.0;
  4953. float shadow_texel_size = light_instance_get_shadow_texel_size(li, p_shadow_atlas);
  4954. light_data.shadow_normal_bias = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * shadow_texel_size * 2.0; // applied in -1 .. 1 space
  4955. }
  4956. light_data.transmittance_bias = storage->light_get_transmittance_bias(base);
  4957. Rect2 rect = light_instance_get_shadow_atlas_rect(li, p_shadow_atlas);
  4958. light_data.atlas_rect[0] = rect.position.x;
  4959. light_data.atlas_rect[1] = rect.position.y;
  4960. light_data.atlas_rect[2] = rect.size.width;
  4961. light_data.atlas_rect[3] = rect.size.height;
  4962. light_data.soft_shadow_scale = storage->light_get_param(base, RS::LIGHT_PARAM_SHADOW_BLUR);
  4963. if (type == RS::LIGHT_OMNI) {
  4964. light_data.atlas_rect[3] *= 0.5; //one paraboloid on top of another
  4965. Transform proj = (p_camera_inverse_transform * light_transform).inverse();
  4966. RasterizerStorageRD::store_transform(proj, light_data.shadow_matrix);
  4967. if (size > 0.0) {
  4968. light_data.soft_shadow_size = size;
  4969. } else {
  4970. light_data.soft_shadow_size = 0.0;
  4971. light_data.soft_shadow_scale *= shadows_quality_radius_get(); // Only use quality radius for PCF
  4972. }
  4973. } else if (type == RS::LIGHT_SPOT) {
  4974. Transform modelview = (p_camera_inverse_transform * light_transform).inverse();
  4975. CameraMatrix bias;
  4976. bias.set_light_bias();
  4977. CameraMatrix shadow_mtx = bias * light_instance_get_shadow_camera(li, 0) * modelview;
  4978. RasterizerStorageRD::store_camera(shadow_mtx, light_data.shadow_matrix);
  4979. if (size > 0.0) {
  4980. CameraMatrix cm = light_instance_get_shadow_camera(li, 0);
  4981. float half_np = cm.get_z_near() * Math::tan(Math::deg2rad(spot_angle));
  4982. light_data.soft_shadow_size = (size * 0.5 / radius) / (half_np / cm.get_z_near()) * rect.size.width;
  4983. } else {
  4984. light_data.soft_shadow_size = 0.0;
  4985. light_data.soft_shadow_scale *= shadows_quality_radius_get(); // Only use quality radius for PCF
  4986. }
  4987. }
  4988. } else {
  4989. light_data.shadow_color_enabled[3] = 0;
  4990. }
  4991. light_instance_set_index(li, light_count);
  4992. cluster.builder.add_light(type == RS::LIGHT_SPOT ? LightClusterBuilder::LIGHT_TYPE_SPOT : LightClusterBuilder::LIGHT_TYPE_OMNI, light_transform, radius, spot_angle);
  4993. light_count++;
  4994. } break;
  4995. }
  4996. light_instance_set_render_pass(li, RSG::rasterizer->get_frame_number());
  4997. //update UBO for forward rendering, blit to texture for clustered
  4998. }
  4999. if (light_count) {
  5000. RD::get_singleton()->buffer_update(cluster.light_buffer, 0, sizeof(Cluster::LightData) * light_count, cluster.lights, true);
  5001. }
  5002. if (r_directional_light_count) {
  5003. RD::get_singleton()->buffer_update(cluster.directional_light_buffer, 0, sizeof(Cluster::DirectionalLightData) * r_directional_light_count, cluster.directional_lights, true);
  5004. }
  5005. }
  5006. void RasterizerSceneRD::_setup_decals(const RID *p_decal_instances, int p_decal_count, const Transform &p_camera_inverse_xform) {
  5007. Transform uv_xform;
  5008. uv_xform.basis.scale(Vector3(2.0, 1.0, 2.0));
  5009. uv_xform.origin = Vector3(-1.0, 0.0, -1.0);
  5010. p_decal_count = MIN((uint32_t)p_decal_count, cluster.max_decals);
  5011. int idx = 0;
  5012. for (int i = 0; i < p_decal_count; i++) {
  5013. RID di = p_decal_instances[i];
  5014. RID decal = decal_instance_get_base(di);
  5015. Transform xform = decal_instance_get_transform(di);
  5016. float fade = 1.0;
  5017. if (storage->decal_is_distance_fade_enabled(decal)) {
  5018. real_t distance = -p_camera_inverse_xform.xform(xform.origin).z;
  5019. float fade_begin = storage->decal_get_distance_fade_begin(decal);
  5020. float fade_length = storage->decal_get_distance_fade_length(decal);
  5021. if (distance > fade_begin) {
  5022. if (distance > fade_begin + fade_length) {
  5023. continue; // do not use this decal, its invisible
  5024. }
  5025. fade = 1.0 - (distance - fade_begin) / fade_length;
  5026. }
  5027. }
  5028. Cluster::DecalData &dd = cluster.decals[idx];
  5029. Vector3 decal_extents = storage->decal_get_extents(decal);
  5030. Transform scale_xform;
  5031. scale_xform.basis.scale(Vector3(decal_extents.x, decal_extents.y, decal_extents.z));
  5032. Transform to_decal_xform = (p_camera_inverse_xform * decal_instance_get_transform(di) * scale_xform * uv_xform).affine_inverse();
  5033. RasterizerStorageRD::store_transform(to_decal_xform, dd.xform);
  5034. Vector3 normal = xform.basis.get_axis(Vector3::AXIS_Y).normalized();
  5035. normal = p_camera_inverse_xform.basis.xform(normal); //camera is normalized, so fine
  5036. dd.normal[0] = normal.x;
  5037. dd.normal[1] = normal.y;
  5038. dd.normal[2] = normal.z;
  5039. dd.normal_fade = storage->decal_get_normal_fade(decal);
  5040. RID albedo_tex = storage->decal_get_texture(decal, RS::DECAL_TEXTURE_ALBEDO);
  5041. RID emission_tex = storage->decal_get_texture(decal, RS::DECAL_TEXTURE_EMISSION);
  5042. if (albedo_tex.is_valid()) {
  5043. Rect2 rect = storage->decal_atlas_get_texture_rect(albedo_tex);
  5044. dd.albedo_rect[0] = rect.position.x;
  5045. dd.albedo_rect[1] = rect.position.y;
  5046. dd.albedo_rect[2] = rect.size.x;
  5047. dd.albedo_rect[3] = rect.size.y;
  5048. } else {
  5049. if (!emission_tex.is_valid()) {
  5050. continue; //no albedo, no emission, no decal.
  5051. }
  5052. dd.albedo_rect[0] = 0;
  5053. dd.albedo_rect[1] = 0;
  5054. dd.albedo_rect[2] = 0;
  5055. dd.albedo_rect[3] = 0;
  5056. }
  5057. RID normal_tex = storage->decal_get_texture(decal, RS::DECAL_TEXTURE_NORMAL);
  5058. if (normal_tex.is_valid()) {
  5059. Rect2 rect = storage->decal_atlas_get_texture_rect(normal_tex);
  5060. dd.normal_rect[0] = rect.position.x;
  5061. dd.normal_rect[1] = rect.position.y;
  5062. dd.normal_rect[2] = rect.size.x;
  5063. dd.normal_rect[3] = rect.size.y;
  5064. Basis normal_xform = p_camera_inverse_xform.basis * xform.basis.orthonormalized();
  5065. RasterizerStorageRD::store_basis_3x4(normal_xform, dd.normal_xform);
  5066. } else {
  5067. dd.normal_rect[0] = 0;
  5068. dd.normal_rect[1] = 0;
  5069. dd.normal_rect[2] = 0;
  5070. dd.normal_rect[3] = 0;
  5071. }
  5072. RID orm_tex = storage->decal_get_texture(decal, RS::DECAL_TEXTURE_ORM);
  5073. if (orm_tex.is_valid()) {
  5074. Rect2 rect = storage->decal_atlas_get_texture_rect(orm_tex);
  5075. dd.orm_rect[0] = rect.position.x;
  5076. dd.orm_rect[1] = rect.position.y;
  5077. dd.orm_rect[2] = rect.size.x;
  5078. dd.orm_rect[3] = rect.size.y;
  5079. } else {
  5080. dd.orm_rect[0] = 0;
  5081. dd.orm_rect[1] = 0;
  5082. dd.orm_rect[2] = 0;
  5083. dd.orm_rect[3] = 0;
  5084. }
  5085. if (emission_tex.is_valid()) {
  5086. Rect2 rect = storage->decal_atlas_get_texture_rect(emission_tex);
  5087. dd.emission_rect[0] = rect.position.x;
  5088. dd.emission_rect[1] = rect.position.y;
  5089. dd.emission_rect[2] = rect.size.x;
  5090. dd.emission_rect[3] = rect.size.y;
  5091. } else {
  5092. dd.emission_rect[0] = 0;
  5093. dd.emission_rect[1] = 0;
  5094. dd.emission_rect[2] = 0;
  5095. dd.emission_rect[3] = 0;
  5096. }
  5097. Color modulate = storage->decal_get_modulate(decal);
  5098. dd.modulate[0] = modulate.r;
  5099. dd.modulate[1] = modulate.g;
  5100. dd.modulate[2] = modulate.b;
  5101. dd.modulate[3] = modulate.a * fade;
  5102. dd.emission_energy = storage->decal_get_emission_energy(decal) * fade;
  5103. dd.albedo_mix = storage->decal_get_albedo_mix(decal);
  5104. dd.mask = storage->decal_get_cull_mask(decal);
  5105. dd.upper_fade = storage->decal_get_upper_fade(decal);
  5106. dd.lower_fade = storage->decal_get_lower_fade(decal);
  5107. cluster.builder.add_decal(xform, decal_extents);
  5108. idx++;
  5109. }
  5110. if (idx > 0) {
  5111. RD::get_singleton()->buffer_update(cluster.decal_buffer, 0, sizeof(Cluster::DecalData) * idx, cluster.decals, true);
  5112. }
  5113. }
  5114. void RasterizerSceneRD::render_scene(RID p_render_buffers, const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, InstanceBase **p_cull_result, int p_cull_count, RID *p_light_cull_result, int p_light_cull_count, RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, RID *p_gi_probe_cull_result, int p_gi_probe_cull_count, RID *p_decal_cull_result, int p_decal_cull_count, InstanceBase **p_lightmap_cull_result, int p_lightmap_cull_count, RID p_environment, RID p_camera_effects, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass) {
  5115. Color clear_color;
  5116. if (p_render_buffers.is_valid()) {
  5117. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  5118. ERR_FAIL_COND(!rb);
  5119. clear_color = storage->render_target_get_clear_request_color(rb->render_target);
  5120. } else {
  5121. clear_color = storage->get_default_clear_color();
  5122. }
  5123. //assign render indices to giprobes
  5124. for (int i = 0; i < p_gi_probe_cull_count; i++) {
  5125. GIProbeInstance *giprobe_inst = gi_probe_instance_owner.getornull(p_gi_probe_cull_result[i]);
  5126. if (giprobe_inst) {
  5127. giprobe_inst->render_index = i;
  5128. }
  5129. }
  5130. if (get_debug_draw_mode() == RS::VIEWPORT_DEBUG_DRAW_UNSHADED) {
  5131. p_light_cull_count = 0;
  5132. p_reflection_probe_cull_count = 0;
  5133. p_gi_probe_cull_count = 0;
  5134. }
  5135. cluster.builder.begin(p_cam_transform.affine_inverse(), p_cam_projection); //prepare cluster
  5136. bool using_shadows = true;
  5137. if (p_reflection_probe.is_valid()) {
  5138. if (!storage->reflection_probe_renders_shadows(reflection_probe_instance_get_probe(p_reflection_probe))) {
  5139. using_shadows = false;
  5140. }
  5141. } else {
  5142. //do not render reflections when rendering a reflection probe
  5143. _setup_reflections(p_reflection_probe_cull_result, p_reflection_probe_cull_count, p_cam_transform.affine_inverse(), p_environment);
  5144. }
  5145. uint32_t directional_light_count = 0;
  5146. _setup_lights(p_light_cull_result, p_light_cull_count, p_cam_transform.affine_inverse(), p_shadow_atlas, using_shadows, directional_light_count);
  5147. _setup_decals(p_decal_cull_result, p_decal_cull_count, p_cam_transform.affine_inverse());
  5148. cluster.builder.bake_cluster(); //bake to cluster
  5149. _render_scene(p_render_buffers, p_cam_transform, p_cam_projection, p_cam_ortogonal, p_cull_result, p_cull_count, directional_light_count, p_gi_probe_cull_result, p_gi_probe_cull_count, p_lightmap_cull_result, p_lightmap_cull_count, p_environment, p_camera_effects, p_shadow_atlas, p_reflection_atlas, p_reflection_probe, p_reflection_probe_pass, clear_color);
  5150. if (p_render_buffers.is_valid()) {
  5151. RENDER_TIMESTAMP("Tonemap");
  5152. _render_buffers_post_process_and_tonemap(p_render_buffers, p_environment, p_camera_effects, p_cam_projection);
  5153. _render_buffers_debug_draw(p_render_buffers, p_shadow_atlas);
  5154. if (debug_draw == RS::VIEWPORT_DEBUG_DRAW_SDFGI) {
  5155. _sdfgi_debug_draw(p_render_buffers, p_cam_projection, p_cam_transform);
  5156. }
  5157. }
  5158. }
  5159. void RasterizerSceneRD::render_shadow(RID p_light, RID p_shadow_atlas, int p_pass, InstanceBase **p_cull_result, int p_cull_count) {
  5160. LightInstance *light_instance = light_instance_owner.getornull(p_light);
  5161. ERR_FAIL_COND(!light_instance);
  5162. Rect2i atlas_rect;
  5163. RID atlas_texture;
  5164. bool using_dual_paraboloid = false;
  5165. bool using_dual_paraboloid_flip = false;
  5166. float znear = 0;
  5167. float zfar = 0;
  5168. RID render_fb;
  5169. RID render_texture;
  5170. float bias = 0;
  5171. float normal_bias = 0;
  5172. bool use_pancake = false;
  5173. bool use_linear_depth = false;
  5174. bool render_cubemap = false;
  5175. bool finalize_cubemap = false;
  5176. CameraMatrix light_projection;
  5177. Transform light_transform;
  5178. if (storage->light_get_type(light_instance->light) == RS::LIGHT_DIRECTIONAL) {
  5179. //set pssm stuff
  5180. if (light_instance->last_scene_shadow_pass != scene_pass) {
  5181. light_instance->directional_rect = _get_directional_shadow_rect(directional_shadow.size, directional_shadow.light_count, directional_shadow.current_light);
  5182. directional_shadow.current_light++;
  5183. light_instance->last_scene_shadow_pass = scene_pass;
  5184. }
  5185. use_pancake = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_SHADOW_PANCAKE_SIZE) > 0;
  5186. light_projection = light_instance->shadow_transform[p_pass].camera;
  5187. light_transform = light_instance->shadow_transform[p_pass].transform;
  5188. atlas_rect.position.x = light_instance->directional_rect.position.x;
  5189. atlas_rect.position.y = light_instance->directional_rect.position.y;
  5190. atlas_rect.size.width = light_instance->directional_rect.size.x;
  5191. atlas_rect.size.height = light_instance->directional_rect.size.y;
  5192. if (storage->light_directional_get_shadow_mode(light_instance->light) == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
  5193. atlas_rect.size.width /= 2;
  5194. atlas_rect.size.height /= 2;
  5195. if (p_pass == 1) {
  5196. atlas_rect.position.x += atlas_rect.size.width;
  5197. } else if (p_pass == 2) {
  5198. atlas_rect.position.y += atlas_rect.size.height;
  5199. } else if (p_pass == 3) {
  5200. atlas_rect.position.x += atlas_rect.size.width;
  5201. atlas_rect.position.y += atlas_rect.size.height;
  5202. }
  5203. } else if (storage->light_directional_get_shadow_mode(light_instance->light) == RS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
  5204. atlas_rect.size.height /= 2;
  5205. if (p_pass == 0) {
  5206. } else {
  5207. atlas_rect.position.y += atlas_rect.size.height;
  5208. }
  5209. }
  5210. light_instance->shadow_transform[p_pass].atlas_rect = atlas_rect;
  5211. light_instance->shadow_transform[p_pass].atlas_rect.position /= directional_shadow.size;
  5212. light_instance->shadow_transform[p_pass].atlas_rect.size /= directional_shadow.size;
  5213. float bias_mult = light_instance->shadow_transform[p_pass].bias_scale;
  5214. zfar = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_RANGE);
  5215. bias = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_SHADOW_BIAS) * bias_mult;
  5216. normal_bias = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS) * bias_mult;
  5217. ShadowMap *shadow_map = _get_shadow_map(atlas_rect.size);
  5218. render_fb = shadow_map->fb;
  5219. render_texture = shadow_map->depth;
  5220. atlas_texture = directional_shadow.depth;
  5221. } else {
  5222. //set from shadow atlas
  5223. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas);
  5224. ERR_FAIL_COND(!shadow_atlas);
  5225. ERR_FAIL_COND(!shadow_atlas->shadow_owners.has(p_light));
  5226. uint32_t key = shadow_atlas->shadow_owners[p_light];
  5227. uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
  5228. uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK;
  5229. ERR_FAIL_INDEX((int)shadow, shadow_atlas->quadrants[quadrant].shadows.size());
  5230. uint32_t quadrant_size = shadow_atlas->size >> 1;
  5231. atlas_rect.position.x = (quadrant & 1) * quadrant_size;
  5232. atlas_rect.position.y = (quadrant >> 1) * quadrant_size;
  5233. uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision);
  5234. atlas_rect.position.x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
  5235. atlas_rect.position.y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
  5236. atlas_rect.size.width = shadow_size;
  5237. atlas_rect.size.height = shadow_size;
  5238. atlas_texture = shadow_atlas->depth;
  5239. zfar = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_RANGE);
  5240. bias = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_SHADOW_BIAS);
  5241. normal_bias = storage->light_get_param(light_instance->light, RS::LIGHT_PARAM_SHADOW_NORMAL_BIAS);
  5242. if (storage->light_get_type(light_instance->light) == RS::LIGHT_OMNI) {
  5243. if (storage->light_omni_get_shadow_mode(light_instance->light) == RS::LIGHT_OMNI_SHADOW_CUBE) {
  5244. ShadowCubemap *cubemap = _get_shadow_cubemap(shadow_size / 2);
  5245. render_fb = cubemap->side_fb[p_pass];
  5246. render_texture = cubemap->cubemap;
  5247. light_projection = light_instance->shadow_transform[0].camera;
  5248. light_transform = light_instance->shadow_transform[0].transform;
  5249. render_cubemap = true;
  5250. finalize_cubemap = p_pass == 5;
  5251. } else {
  5252. light_projection = light_instance->shadow_transform[0].camera;
  5253. light_transform = light_instance->shadow_transform[0].transform;
  5254. atlas_rect.size.height /= 2;
  5255. atlas_rect.position.y += p_pass * atlas_rect.size.height;
  5256. using_dual_paraboloid = true;
  5257. using_dual_paraboloid_flip = p_pass == 1;
  5258. ShadowMap *shadow_map = _get_shadow_map(atlas_rect.size);
  5259. render_fb = shadow_map->fb;
  5260. render_texture = shadow_map->depth;
  5261. }
  5262. } else if (storage->light_get_type(light_instance->light) == RS::LIGHT_SPOT) {
  5263. light_projection = light_instance->shadow_transform[0].camera;
  5264. light_transform = light_instance->shadow_transform[0].transform;
  5265. ShadowMap *shadow_map = _get_shadow_map(atlas_rect.size);
  5266. render_fb = shadow_map->fb;
  5267. render_texture = shadow_map->depth;
  5268. znear = light_instance->shadow_transform[0].camera.get_z_near();
  5269. use_linear_depth = true;
  5270. }
  5271. }
  5272. if (render_cubemap) {
  5273. //rendering to cubemap
  5274. _render_shadow(render_fb, p_cull_result, p_cull_count, light_projection, light_transform, zfar, 0, 0, false, false, use_pancake);
  5275. if (finalize_cubemap) {
  5276. //reblit
  5277. atlas_rect.size.height /= 2;
  5278. storage->get_effects()->copy_cubemap_to_dp(render_texture, atlas_texture, atlas_rect, light_projection.get_z_near(), light_projection.get_z_far(), 0.0, false);
  5279. atlas_rect.position.y += atlas_rect.size.height;
  5280. storage->get_effects()->copy_cubemap_to_dp(render_texture, atlas_texture, atlas_rect, light_projection.get_z_near(), light_projection.get_z_far(), 0.0, true);
  5281. }
  5282. } else {
  5283. //render shadow
  5284. _render_shadow(render_fb, p_cull_result, p_cull_count, light_projection, light_transform, zfar, bias, normal_bias, using_dual_paraboloid, using_dual_paraboloid_flip, use_pancake);
  5285. //copy to atlas
  5286. if (use_linear_depth) {
  5287. storage->get_effects()->copy_depth_to_rect_and_linearize(render_texture, atlas_texture, atlas_rect, true, znear, zfar);
  5288. } else {
  5289. storage->get_effects()->copy_depth_to_rect(render_texture, atlas_texture, atlas_rect, true);
  5290. }
  5291. //does not work from depth to color
  5292. //RD::get_singleton()->texture_copy(render_texture, atlas_texture, Vector3(0, 0, 0), Vector3(atlas_rect.position.x, atlas_rect.position.y, 0), Vector3(atlas_rect.size.x, atlas_rect.size.y, 1), 0, 0, 0, 0, true);
  5293. }
  5294. }
  5295. void RasterizerSceneRD::render_material(const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, InstanceBase **p_cull_result, int p_cull_count, RID p_framebuffer, const Rect2i &p_region) {
  5296. _render_material(p_cam_transform, p_cam_projection, p_cam_ortogonal, p_cull_result, p_cull_count, p_framebuffer, p_region);
  5297. }
  5298. void RasterizerSceneRD::render_sdfgi(RID p_render_buffers, int p_region, InstanceBase **p_cull_result, int p_cull_count) {
  5299. //print_line("rendering region " + itos(p_region));
  5300. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  5301. ERR_FAIL_COND(!rb);
  5302. ERR_FAIL_COND(!rb->sdfgi);
  5303. AABB bounds;
  5304. Vector3i from;
  5305. Vector3i size;
  5306. int cascade_prev = _sdfgi_get_pending_region_data(p_render_buffers, p_region - 1, from, size, bounds);
  5307. int cascade_next = _sdfgi_get_pending_region_data(p_render_buffers, p_region + 1, from, size, bounds);
  5308. int cascade = _sdfgi_get_pending_region_data(p_render_buffers, p_region, from, size, bounds);
  5309. ERR_FAIL_COND(cascade < 0);
  5310. if (cascade_prev != cascade) {
  5311. //initialize render
  5312. RD::get_singleton()->texture_clear(rb->sdfgi->render_albedo, Color(0, 0, 0, 0), 0, 1, 0, 1, true);
  5313. RD::get_singleton()->texture_clear(rb->sdfgi->render_emission, Color(0, 0, 0, 0), 0, 1, 0, 1, true);
  5314. RD::get_singleton()->texture_clear(rb->sdfgi->render_emission_aniso, Color(0, 0, 0, 0), 0, 1, 0, 1, true);
  5315. RD::get_singleton()->texture_clear(rb->sdfgi->render_geom_facing, Color(0, 0, 0, 0), 0, 1, 0, 1, true);
  5316. }
  5317. //print_line("rendering cascade " + itos(p_region) + " objects: " + itos(p_cull_count) + " bounds: " + bounds + " from: " + from + " size: " + size + " cell size: " + rtos(rb->sdfgi->cascades[cascade].cell_size));
  5318. _render_sdfgi(p_render_buffers, from, size, bounds, p_cull_result, p_cull_count, rb->sdfgi->render_albedo, rb->sdfgi->render_emission, rb->sdfgi->render_emission_aniso, rb->sdfgi->render_geom_facing);
  5319. if (cascade_next != cascade) {
  5320. RENDER_TIMESTAMP(">SDFGI Update SDF");
  5321. //done rendering! must update SDF
  5322. //clear dispatch indirect data
  5323. SDGIShader::PreprocessPushConstant push_constant;
  5324. zeromem(&push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  5325. RENDER_TIMESTAMP("Scroll SDF");
  5326. //scroll
  5327. if (rb->sdfgi->cascades[cascade].dirty_regions != SDFGI::Cascade::DIRTY_ALL) {
  5328. //for scroll
  5329. Vector3i dirty = rb->sdfgi->cascades[cascade].dirty_regions;
  5330. push_constant.scroll[0] = dirty.x;
  5331. push_constant.scroll[1] = dirty.y;
  5332. push_constant.scroll[2] = dirty.z;
  5333. } else {
  5334. //for no scroll
  5335. push_constant.scroll[0] = 0;
  5336. push_constant.scroll[1] = 0;
  5337. push_constant.scroll[2] = 0;
  5338. }
  5339. push_constant.grid_size = rb->sdfgi->cascade_size;
  5340. push_constant.cascade = cascade;
  5341. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  5342. if (rb->sdfgi->cascades[cascade].dirty_regions != SDFGI::Cascade::DIRTY_ALL) {
  5343. //must pre scroll existing data because not all is dirty
  5344. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_SCROLL]);
  5345. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].scroll_uniform_set, 0);
  5346. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  5347. RD::get_singleton()->compute_list_dispatch_indirect(compute_list, rb->sdfgi->cascades[cascade].solid_cell_dispatch_buffer, 0);
  5348. // no barrier do all together
  5349. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_SCROLL_OCCLUSION]);
  5350. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].scroll_occlusion_uniform_set, 0);
  5351. Vector3i dirty = rb->sdfgi->cascades[cascade].dirty_regions;
  5352. Vector3i groups;
  5353. groups.x = rb->sdfgi->cascade_size - ABS(dirty.x);
  5354. groups.y = rb->sdfgi->cascade_size - ABS(dirty.y);
  5355. groups.z = rb->sdfgi->cascade_size - ABS(dirty.z);
  5356. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  5357. RD::get_singleton()->compute_list_dispatch_threads(compute_list, groups.x, groups.y, groups.z, 4, 4, 4);
  5358. //no barrier, continue together
  5359. {
  5360. //scroll probes and their history also
  5361. SDGIShader::IntegratePushConstant ipush_constant;
  5362. ipush_constant.grid_size[1] = rb->sdfgi->cascade_size;
  5363. ipush_constant.grid_size[2] = rb->sdfgi->cascade_size;
  5364. ipush_constant.grid_size[0] = rb->sdfgi->cascade_size;
  5365. ipush_constant.max_cascades = rb->sdfgi->cascades.size();
  5366. ipush_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
  5367. ipush_constant.history_index = 0;
  5368. ipush_constant.history_size = rb->sdfgi->history_size;
  5369. ipush_constant.ray_count = 0;
  5370. ipush_constant.ray_bias = 0;
  5371. ipush_constant.sky_mode = 0;
  5372. ipush_constant.sky_energy = 0;
  5373. ipush_constant.sky_color[0] = 0;
  5374. ipush_constant.sky_color[1] = 0;
  5375. ipush_constant.sky_color[2] = 0;
  5376. ipush_constant.y_mult = rb->sdfgi->y_mult;
  5377. ipush_constant.image_size[0] = rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count;
  5378. ipush_constant.image_size[1] = rb->sdfgi->probe_axis_count;
  5379. ipush_constant.image_size[1] = rb->sdfgi->probe_axis_count;
  5380. int32_t probe_divisor = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
  5381. ipush_constant.cascade = cascade;
  5382. ipush_constant.world_offset[0] = rb->sdfgi->cascades[cascade].position.x / probe_divisor;
  5383. ipush_constant.world_offset[1] = rb->sdfgi->cascades[cascade].position.y / probe_divisor;
  5384. ipush_constant.world_offset[2] = rb->sdfgi->cascades[cascade].position.z / probe_divisor;
  5385. ipush_constant.scroll[0] = dirty.x / probe_divisor;
  5386. ipush_constant.scroll[1] = dirty.y / probe_divisor;
  5387. ipush_constant.scroll[2] = dirty.z / probe_divisor;
  5388. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.integrate_pipeline[SDGIShader::INTEGRATE_MODE_SCROLL]);
  5389. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].integrate_uniform_set, 0);
  5390. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, sdfgi_shader.integrate_default_sky_uniform_set, 1);
  5391. RD::get_singleton()->compute_list_set_push_constant(compute_list, &ipush_constant, sizeof(SDGIShader::IntegratePushConstant));
  5392. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count, rb->sdfgi->probe_axis_count, 1, 8, 8, 1);
  5393. RD::get_singleton()->compute_list_add_barrier(compute_list);
  5394. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.integrate_pipeline[SDGIShader::INTEGRATE_MODE_SCROLL_STORE]);
  5395. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].integrate_uniform_set, 0);
  5396. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, sdfgi_shader.integrate_default_sky_uniform_set, 1);
  5397. RD::get_singleton()->compute_list_set_push_constant(compute_list, &ipush_constant, sizeof(SDGIShader::IntegratePushConstant));
  5398. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->probe_axis_count * rb->sdfgi->probe_axis_count, rb->sdfgi->probe_axis_count, 1, 8, 8, 1);
  5399. }
  5400. //ok finally barrier
  5401. RD::get_singleton()->compute_list_add_barrier(compute_list);
  5402. }
  5403. //clear dispatch indirect data
  5404. uint32_t dispatch_indirct_data[4] = { 0, 0, 0, 0 };
  5405. RD::get_singleton()->buffer_update(rb->sdfgi->cascades[cascade].solid_cell_dispatch_buffer, 0, sizeof(uint32_t) * 4, dispatch_indirct_data, true);
  5406. bool half_size = true; //much faster, very little difference
  5407. static const int optimized_jf_group_size = 8;
  5408. if (half_size) {
  5409. push_constant.grid_size >>= 1;
  5410. uint32_t cascade_half_size = rb->sdfgi->cascade_size >> 1;
  5411. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_INITIALIZE_HALF]);
  5412. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->sdf_initialize_half_uniform_set, 0);
  5413. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  5414. RD::get_singleton()->compute_list_dispatch_threads(compute_list, cascade_half_size, cascade_half_size, cascade_half_size, 4, 4, 4);
  5415. RD::get_singleton()->compute_list_add_barrier(compute_list);
  5416. //must start with regular jumpflood
  5417. push_constant.half_size = true;
  5418. {
  5419. RENDER_TIMESTAMP("SDFGI Jump Flood (Half Size)");
  5420. uint32_t s = cascade_half_size;
  5421. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD]);
  5422. int jf_us = 0;
  5423. //start with regular jump flood for very coarse reads, as this is impossible to optimize
  5424. while (s > 1) {
  5425. s /= 2;
  5426. push_constant.step_size = s;
  5427. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_half_uniform_set[jf_us], 0);
  5428. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  5429. RD::get_singleton()->compute_list_dispatch_threads(compute_list, cascade_half_size, cascade_half_size, cascade_half_size, 4, 4, 4);
  5430. RD::get_singleton()->compute_list_add_barrier(compute_list);
  5431. jf_us = jf_us == 0 ? 1 : 0;
  5432. if (cascade_half_size / (s / 2) >= optimized_jf_group_size) {
  5433. break;
  5434. }
  5435. }
  5436. RENDER_TIMESTAMP("SDFGI Jump Flood Optimized (Half Size)");
  5437. //continue with optimized jump flood for smaller reads
  5438. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_OPTIMIZED]);
  5439. while (s > 1) {
  5440. s /= 2;
  5441. push_constant.step_size = s;
  5442. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_half_uniform_set[jf_us], 0);
  5443. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  5444. RD::get_singleton()->compute_list_dispatch_threads(compute_list, cascade_half_size, cascade_half_size, cascade_half_size, optimized_jf_group_size, optimized_jf_group_size, optimized_jf_group_size);
  5445. RD::get_singleton()->compute_list_add_barrier(compute_list);
  5446. jf_us = jf_us == 0 ? 1 : 0;
  5447. }
  5448. }
  5449. // restore grid size for last passes
  5450. push_constant.grid_size = rb->sdfgi->cascade_size;
  5451. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_UPSCALE]);
  5452. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->sdf_upscale_uniform_set, 0);
  5453. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  5454. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, 4, 4, 4);
  5455. RD::get_singleton()->compute_list_add_barrier(compute_list);
  5456. //run one pass of fullsize jumpflood to fix up half size arctifacts
  5457. push_constant.half_size = false;
  5458. push_constant.step_size = 1;
  5459. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_OPTIMIZED]);
  5460. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_uniform_set[rb->sdfgi->upscale_jfa_uniform_set_index], 0);
  5461. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  5462. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, optimized_jf_group_size, optimized_jf_group_size, optimized_jf_group_size);
  5463. RD::get_singleton()->compute_list_add_barrier(compute_list);
  5464. } else {
  5465. //full size jumpflood
  5466. RENDER_TIMESTAMP("SDFGI Jump Flood");
  5467. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_INITIALIZE]);
  5468. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->sdf_initialize_uniform_set, 0);
  5469. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  5470. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, 4, 4, 4);
  5471. RD::get_singleton()->compute_list_add_barrier(compute_list);
  5472. push_constant.half_size = false;
  5473. {
  5474. uint32_t s = rb->sdfgi->cascade_size;
  5475. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD]);
  5476. int jf_us = 0;
  5477. //start with regular jump flood for very coarse reads, as this is impossible to optimize
  5478. while (s > 1) {
  5479. s /= 2;
  5480. push_constant.step_size = s;
  5481. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_uniform_set[jf_us], 0);
  5482. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  5483. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, 4, 4, 4);
  5484. RD::get_singleton()->compute_list_add_barrier(compute_list);
  5485. jf_us = jf_us == 0 ? 1 : 0;
  5486. if (rb->sdfgi->cascade_size / (s / 2) >= optimized_jf_group_size) {
  5487. break;
  5488. }
  5489. }
  5490. RENDER_TIMESTAMP("SDFGI Jump Flood Optimized");
  5491. //continue with optimized jump flood for smaller reads
  5492. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_JUMP_FLOOD_OPTIMIZED]);
  5493. while (s > 1) {
  5494. s /= 2;
  5495. push_constant.step_size = s;
  5496. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->jump_flood_uniform_set[jf_us], 0);
  5497. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  5498. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, optimized_jf_group_size, optimized_jf_group_size, optimized_jf_group_size);
  5499. RD::get_singleton()->compute_list_add_barrier(compute_list);
  5500. jf_us = jf_us == 0 ? 1 : 0;
  5501. }
  5502. }
  5503. }
  5504. RENDER_TIMESTAMP("SDFGI Occlusion");
  5505. // occlusion
  5506. {
  5507. uint32_t probe_size = rb->sdfgi->cascade_size / SDFGI::PROBE_DIVISOR;
  5508. Vector3i probe_global_pos = rb->sdfgi->cascades[cascade].position / probe_size;
  5509. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_OCCLUSION]);
  5510. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->occlusion_uniform_set, 0);
  5511. for (int i = 0; i < 8; i++) {
  5512. //dispatch all at once for performance
  5513. Vector3i offset(i & 1, (i >> 1) & 1, (i >> 2) & 1);
  5514. if ((probe_global_pos.x & 1) != 0) {
  5515. offset.x = (offset.x + 1) & 1;
  5516. }
  5517. if ((probe_global_pos.y & 1) != 0) {
  5518. offset.y = (offset.y + 1) & 1;
  5519. }
  5520. if ((probe_global_pos.z & 1) != 0) {
  5521. offset.z = (offset.z + 1) & 1;
  5522. }
  5523. push_constant.probe_offset[0] = offset.x;
  5524. push_constant.probe_offset[1] = offset.y;
  5525. push_constant.probe_offset[2] = offset.z;
  5526. push_constant.occlusion_index = i;
  5527. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  5528. Vector3i groups = Vector3i(probe_size + 1, probe_size + 1, probe_size + 1) - offset; //if offset, it's one less probe per axis to compute
  5529. RD::get_singleton()->compute_list_dispatch(compute_list, groups.x, groups.y, groups.z);
  5530. }
  5531. RD::get_singleton()->compute_list_add_barrier(compute_list);
  5532. }
  5533. RENDER_TIMESTAMP("SDFGI Store");
  5534. // store
  5535. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.preprocess_pipeline[SDGIShader::PRE_PROCESS_STORE]);
  5536. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, rb->sdfgi->cascades[cascade].sdf_store_uniform_set, 0);
  5537. RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SDGIShader::PreprocessPushConstant));
  5538. RD::get_singleton()->compute_list_dispatch_threads(compute_list, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, 4, 4, 4);
  5539. RD::get_singleton()->compute_list_end();
  5540. //clear these textures, as they will have previous garbage on next draw
  5541. RD::get_singleton()->texture_clear(rb->sdfgi->cascades[cascade].light_tex, Color(0, 0, 0, 0), 0, 1, 0, 1, true);
  5542. RD::get_singleton()->texture_clear(rb->sdfgi->cascades[cascade].light_aniso_0_tex, Color(0, 0, 0, 0), 0, 1, 0, 1, true);
  5543. RD::get_singleton()->texture_clear(rb->sdfgi->cascades[cascade].light_aniso_1_tex, Color(0, 0, 0, 0), 0, 1, 0, 1, true);
  5544. #if 0
  5545. Vector<uint8_t> data = RD::get_singleton()->texture_get_data(rb->sdfgi->cascades[cascade].sdf, 0);
  5546. Ref<Image> img;
  5547. img.instance();
  5548. for (uint32_t i = 0; i < rb->sdfgi->cascade_size; i++) {
  5549. Vector<uint8_t> subarr = data.subarray(128 * 128 * i, 128 * 128 * (i + 1) - 1);
  5550. img->create(rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, false, Image::FORMAT_L8, subarr);
  5551. img->save_png("res://cascade_sdf_" + itos(cascade) + "_" + itos(i) + ".png");
  5552. }
  5553. //finalize render and update sdf
  5554. #endif
  5555. #if 0
  5556. Vector<uint8_t> data = RD::get_singleton()->texture_get_data(rb->sdfgi->render_albedo, 0);
  5557. Ref<Image> img;
  5558. img.instance();
  5559. for (uint32_t i = 0; i < rb->sdfgi->cascade_size; i++) {
  5560. Vector<uint8_t> subarr = data.subarray(128 * 128 * i * 2, 128 * 128 * (i + 1) * 2 - 1);
  5561. img->create(rb->sdfgi->cascade_size, rb->sdfgi->cascade_size, false, Image::FORMAT_RGB565, subarr);
  5562. img->convert(Image::FORMAT_RGBA8);
  5563. img->save_png("res://cascade_" + itos(cascade) + "_" + itos(i) + ".png");
  5564. }
  5565. //finalize render and update sdf
  5566. #endif
  5567. RENDER_TIMESTAMP("<SDFGI Update SDF");
  5568. }
  5569. }
  5570. void RasterizerSceneRD::render_sdfgi_static_lights(RID p_render_buffers, uint32_t p_cascade_count, const uint32_t *p_cascade_indices, const RID **p_positional_light_cull_result, const uint32_t *p_positional_light_cull_count) {
  5571. RenderBuffers *rb = render_buffers_owner.getornull(p_render_buffers);
  5572. ERR_FAIL_COND(!rb);
  5573. ERR_FAIL_COND(!rb->sdfgi);
  5574. ERR_FAIL_COND(p_positional_light_cull_count == 0);
  5575. _sdfgi_update_cascades(p_render_buffers); //need cascades updated for this
  5576. RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin();
  5577. RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, sdfgi_shader.direct_light_pipeline[SDGIShader::DIRECT_LIGHT_MODE_STATIC]);
  5578. SDGIShader::DirectLightPushConstant dl_push_constant;
  5579. dl_push_constant.grid_size[0] = rb->sdfgi->cascade_size;
  5580. dl_push_constant.grid_size[1] = rb->sdfgi->cascade_size;
  5581. dl_push_constant.grid_size[2] = rb->sdfgi->cascade_size;
  5582. dl_push_constant.max_cascades = rb->sdfgi->cascades.size();
  5583. dl_push_constant.probe_axis_size = rb->sdfgi->probe_axis_count;
  5584. dl_push_constant.multibounce = false; // this is static light, do not multibounce yet
  5585. dl_push_constant.y_mult = rb->sdfgi->y_mult;
  5586. //all must be processed
  5587. dl_push_constant.process_offset = 0;
  5588. dl_push_constant.process_increment = 1;
  5589. SDGIShader::Light lights[SDFGI::MAX_STATIC_LIGHTS];
  5590. for (uint32_t i = 0; i < p_cascade_count; i++) {
  5591. ERR_CONTINUE(p_cascade_indices[i] >= rb->sdfgi->cascades.size());
  5592. SDFGI::Cascade &cc = rb->sdfgi->cascades[p_cascade_indices[i]];
  5593. { //fill light buffer
  5594. AABB cascade_aabb;
  5595. cascade_aabb.position = Vector3((Vector3i(1, 1, 1) * -int32_t(rb->sdfgi->cascade_size >> 1) + cc.position)) * cc.cell_size;
  5596. cascade_aabb.size = Vector3(1, 1, 1) * rb->sdfgi->cascade_size * cc.cell_size;
  5597. int idx = 0;
  5598. for (uint32_t j = 0; j < p_positional_light_cull_count[i]; j++) {
  5599. if (idx == SDFGI::MAX_STATIC_LIGHTS) {
  5600. break;
  5601. }
  5602. LightInstance *li = light_instance_owner.getornull(p_positional_light_cull_result[i][j]);
  5603. ERR_CONTINUE(!li);
  5604. uint32_t max_sdfgi_cascade = storage->light_get_max_sdfgi_cascade(li->light);
  5605. if (p_cascade_indices[i] > max_sdfgi_cascade) {
  5606. continue;
  5607. }
  5608. if (!cascade_aabb.intersects(li->aabb)) {
  5609. continue;
  5610. }
  5611. lights[idx].type = storage->light_get_type(li->light);
  5612. Vector3 dir = -li->transform.basis.get_axis(Vector3::AXIS_Z);
  5613. if (lights[idx].type == RS::LIGHT_DIRECTIONAL) {
  5614. dir.y *= rb->sdfgi->y_mult; //only makes sense for directional
  5615. dir.normalize();
  5616. }
  5617. lights[idx].direction[0] = dir.x;
  5618. lights[idx].direction[1] = dir.y;
  5619. lights[idx].direction[2] = dir.z;
  5620. Vector3 pos = li->transform.origin;
  5621. pos.y *= rb->sdfgi->y_mult;
  5622. lights[idx].position[0] = pos.x;
  5623. lights[idx].position[1] = pos.y;
  5624. lights[idx].position[2] = pos.z;
  5625. Color color = storage->light_get_color(li->light);
  5626. color = color.to_linear();
  5627. lights[idx].color[0] = color.r;
  5628. lights[idx].color[1] = color.g;
  5629. lights[idx].color[2] = color.b;
  5630. lights[idx].energy = storage->light_get_param(li->light, RS::LIGHT_PARAM_ENERGY);
  5631. lights[idx].has_shadow = storage->light_has_shadow(li->light);
  5632. lights[idx].attenuation = storage->light_get_param(li->light, RS::LIGHT_PARAM_ATTENUATION);
  5633. lights[idx].radius = storage->light_get_param(li->light, RS::LIGHT_PARAM_RANGE);
  5634. lights[idx].spot_angle = Math::deg2rad(storage->light_get_param(li->light, RS::LIGHT_PARAM_SPOT_ANGLE));
  5635. lights[idx].spot_attenuation = storage->light_get_param(li->light, RS::LIGHT_PARAM_SPOT_ATTENUATION);
  5636. idx++;
  5637. }
  5638. if (idx > 0) {
  5639. RD::get_singleton()->buffer_update(cc.lights_buffer, 0, idx * sizeof(SDGIShader::Light), lights, true);
  5640. }
  5641. dl_push_constant.light_count = idx;
  5642. }
  5643. dl_push_constant.cascade = p_cascade_indices[i];
  5644. if (dl_push_constant.light_count > 0) {
  5645. RD::get_singleton()->compute_list_bind_uniform_set(compute_list, cc.sdf_direct_light_uniform_set, 0);
  5646. RD::get_singleton()->compute_list_set_push_constant(compute_list, &dl_push_constant, sizeof(SDGIShader::DirectLightPushConstant));
  5647. RD::get_singleton()->compute_list_dispatch_indirect(compute_list, cc.solid_cell_dispatch_buffer, 0);
  5648. }
  5649. }
  5650. RD::get_singleton()->compute_list_end();
  5651. }
  5652. bool RasterizerSceneRD::free(RID p_rid) {
  5653. if (render_buffers_owner.owns(p_rid)) {
  5654. RenderBuffers *rb = render_buffers_owner.getornull(p_rid);
  5655. _free_render_buffer_data(rb);
  5656. memdelete(rb->data);
  5657. if (rb->sdfgi) {
  5658. _sdfgi_erase(rb);
  5659. }
  5660. render_buffers_owner.free(p_rid);
  5661. } else if (environment_owner.owns(p_rid)) {
  5662. //not much to delete, just free it
  5663. environment_owner.free(p_rid);
  5664. } else if (camera_effects_owner.owns(p_rid)) {
  5665. //not much to delete, just free it
  5666. camera_effects_owner.free(p_rid);
  5667. } else if (reflection_atlas_owner.owns(p_rid)) {
  5668. reflection_atlas_set_size(p_rid, 0, 0);
  5669. reflection_atlas_owner.free(p_rid);
  5670. } else if (reflection_probe_instance_owner.owns(p_rid)) {
  5671. //not much to delete, just free it
  5672. //ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_rid);
  5673. reflection_probe_release_atlas_index(p_rid);
  5674. reflection_probe_instance_owner.free(p_rid);
  5675. } else if (decal_instance_owner.owns(p_rid)) {
  5676. decal_instance_owner.free(p_rid);
  5677. } else if (gi_probe_instance_owner.owns(p_rid)) {
  5678. GIProbeInstance *gi_probe = gi_probe_instance_owner.getornull(p_rid);
  5679. if (gi_probe->texture.is_valid()) {
  5680. RD::get_singleton()->free(gi_probe->texture);
  5681. RD::get_singleton()->free(gi_probe->write_buffer);
  5682. }
  5683. for (int i = 0; i < gi_probe->dynamic_maps.size(); i++) {
  5684. RD::get_singleton()->free(gi_probe->dynamic_maps[i].texture);
  5685. RD::get_singleton()->free(gi_probe->dynamic_maps[i].depth);
  5686. }
  5687. gi_probe_instance_owner.free(p_rid);
  5688. } else if (sky_owner.owns(p_rid)) {
  5689. _update_dirty_skys();
  5690. Sky *sky = sky_owner.getornull(p_rid);
  5691. if (sky->radiance.is_valid()) {
  5692. RD::get_singleton()->free(sky->radiance);
  5693. sky->radiance = RID();
  5694. }
  5695. _clear_reflection_data(sky->reflection);
  5696. if (sky->uniform_buffer.is_valid()) {
  5697. RD::get_singleton()->free(sky->uniform_buffer);
  5698. sky->uniform_buffer = RID();
  5699. }
  5700. if (sky->half_res_pass.is_valid()) {
  5701. RD::get_singleton()->free(sky->half_res_pass);
  5702. sky->half_res_pass = RID();
  5703. }
  5704. if (sky->quarter_res_pass.is_valid()) {
  5705. RD::get_singleton()->free(sky->quarter_res_pass);
  5706. sky->quarter_res_pass = RID();
  5707. }
  5708. if (sky->material.is_valid()) {
  5709. storage->free(sky->material);
  5710. }
  5711. sky_owner.free(p_rid);
  5712. } else if (light_instance_owner.owns(p_rid)) {
  5713. LightInstance *light_instance = light_instance_owner.getornull(p_rid);
  5714. //remove from shadow atlases..
  5715. for (Set<RID>::Element *E = light_instance->shadow_atlases.front(); E; E = E->next()) {
  5716. ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(E->get());
  5717. ERR_CONTINUE(!shadow_atlas->shadow_owners.has(p_rid));
  5718. uint32_t key = shadow_atlas->shadow_owners[p_rid];
  5719. uint32_t q = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
  5720. uint32_t s = key & ShadowAtlas::SHADOW_INDEX_MASK;
  5721. shadow_atlas->quadrants[q].shadows.write[s].owner = RID();
  5722. shadow_atlas->shadow_owners.erase(p_rid);
  5723. }
  5724. light_instance_owner.free(p_rid);
  5725. } else if (shadow_atlas_owner.owns(p_rid)) {
  5726. shadow_atlas_set_size(p_rid, 0);
  5727. shadow_atlas_owner.free(p_rid);
  5728. } else {
  5729. return false;
  5730. }
  5731. return true;
  5732. }
  5733. void RasterizerSceneRD::set_debug_draw_mode(RS::ViewportDebugDraw p_debug_draw) {
  5734. debug_draw = p_debug_draw;
  5735. }
  5736. void RasterizerSceneRD::update() {
  5737. _update_dirty_skys();
  5738. }
  5739. void RasterizerSceneRD::set_time(double p_time, double p_step) {
  5740. time = p_time;
  5741. time_step = p_step;
  5742. }
  5743. void RasterizerSceneRD::screen_space_roughness_limiter_set_active(bool p_enable, float p_amount, float p_limit) {
  5744. screen_space_roughness_limiter = p_enable;
  5745. screen_space_roughness_limiter_amount = p_amount;
  5746. screen_space_roughness_limiter_limit = p_limit;
  5747. }
  5748. bool RasterizerSceneRD::screen_space_roughness_limiter_is_active() const {
  5749. return screen_space_roughness_limiter;
  5750. }
  5751. float RasterizerSceneRD::screen_space_roughness_limiter_get_amount() const {
  5752. return screen_space_roughness_limiter_amount;
  5753. }
  5754. float RasterizerSceneRD::screen_space_roughness_limiter_get_limit() const {
  5755. return screen_space_roughness_limiter_limit;
  5756. }
  5757. TypedArray<Image> RasterizerSceneRD::bake_render_uv2(RID p_base, const Vector<RID> &p_material_overrides, const Size2i &p_image_size) {
  5758. RD::TextureFormat tf;
  5759. tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
  5760. tf.width = p_image_size.width; // Always 64x64
  5761. tf.height = p_image_size.height;
  5762. tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
  5763. RID albedo_alpha_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
  5764. RID normal_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
  5765. RID orm_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
  5766. tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
  5767. RID emission_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
  5768. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  5769. RID depth_write_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
  5770. tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT;
  5771. tf.format = RD::get_singleton()->texture_is_format_supported_for_usage(RD::DATA_FORMAT_D32_SFLOAT, RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ? RD::DATA_FORMAT_D32_SFLOAT : RD::DATA_FORMAT_X8_D24_UNORM_PACK32;
  5772. RID depth_tex = RD::get_singleton()->texture_create(tf, RD::TextureView());
  5773. Vector<RID> fb_tex;
  5774. fb_tex.push_back(albedo_alpha_tex);
  5775. fb_tex.push_back(normal_tex);
  5776. fb_tex.push_back(orm_tex);
  5777. fb_tex.push_back(emission_tex);
  5778. fb_tex.push_back(depth_write_tex);
  5779. fb_tex.push_back(depth_tex);
  5780. RID fb = RD::get_singleton()->framebuffer_create(fb_tex);
  5781. //RID sampled_light;
  5782. InstanceBase ins;
  5783. ins.base_type = RSG::storage->get_base_type(p_base);
  5784. ins.base = p_base;
  5785. ins.materials.resize(RSG::storage->mesh_get_surface_count(p_base));
  5786. for (int i = 0; i < ins.materials.size(); i++) {
  5787. if (i < p_material_overrides.size()) {
  5788. ins.materials.write[i] = p_material_overrides[i];
  5789. }
  5790. }
  5791. InstanceBase *cull = &ins;
  5792. _render_uv2(&cull, 1, fb, Rect2i(0, 0, p_image_size.width, p_image_size.height));
  5793. TypedArray<Image> ret;
  5794. {
  5795. PackedByteArray data = RD::get_singleton()->texture_get_data(albedo_alpha_tex, 0);
  5796. Ref<Image> img;
  5797. img.instance();
  5798. img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
  5799. RD::get_singleton()->free(albedo_alpha_tex);
  5800. ret.push_back(img);
  5801. }
  5802. {
  5803. PackedByteArray data = RD::get_singleton()->texture_get_data(normal_tex, 0);
  5804. Ref<Image> img;
  5805. img.instance();
  5806. img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
  5807. RD::get_singleton()->free(normal_tex);
  5808. ret.push_back(img);
  5809. }
  5810. {
  5811. PackedByteArray data = RD::get_singleton()->texture_get_data(orm_tex, 0);
  5812. Ref<Image> img;
  5813. img.instance();
  5814. img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBA8, data);
  5815. RD::get_singleton()->free(orm_tex);
  5816. ret.push_back(img);
  5817. }
  5818. {
  5819. PackedByteArray data = RD::get_singleton()->texture_get_data(emission_tex, 0);
  5820. Ref<Image> img;
  5821. img.instance();
  5822. img->create(p_image_size.width, p_image_size.height, false, Image::FORMAT_RGBAH, data);
  5823. RD::get_singleton()->free(emission_tex);
  5824. ret.push_back(img);
  5825. }
  5826. RD::get_singleton()->free(depth_write_tex);
  5827. RD::get_singleton()->free(depth_tex);
  5828. return ret;
  5829. }
  5830. void RasterizerSceneRD::sdfgi_set_debug_probe_select(const Vector3 &p_position, const Vector3 &p_dir) {
  5831. sdfgi_debug_probe_pos = p_position;
  5832. sdfgi_debug_probe_dir = p_dir;
  5833. }
  5834. RasterizerSceneRD *RasterizerSceneRD::singleton = nullptr;
  5835. RID RasterizerSceneRD::get_cluster_builder_texture() {
  5836. return cluster.builder.get_cluster_texture();
  5837. }
  5838. RID RasterizerSceneRD::get_cluster_builder_indices_buffer() {
  5839. return cluster.builder.get_cluster_indices_buffer();
  5840. }
  5841. RID RasterizerSceneRD::get_reflection_probe_buffer() {
  5842. return cluster.reflection_buffer;
  5843. }
  5844. RID RasterizerSceneRD::get_positional_light_buffer() {
  5845. return cluster.light_buffer;
  5846. }
  5847. RID RasterizerSceneRD::get_directional_light_buffer() {
  5848. return cluster.directional_light_buffer;
  5849. }
  5850. RID RasterizerSceneRD::get_decal_buffer() {
  5851. return cluster.decal_buffer;
  5852. }
  5853. int RasterizerSceneRD::get_max_directional_lights() const {
  5854. return cluster.max_directional_lights;
  5855. }
  5856. RasterizerSceneRD::RasterizerSceneRD(RasterizerStorageRD *p_storage) {
  5857. storage = p_storage;
  5858. singleton = this;
  5859. roughness_layers = GLOBAL_GET("rendering/quality/reflections/roughness_layers");
  5860. sky_ggx_samples_quality = GLOBAL_GET("rendering/quality/reflections/ggx_samples");
  5861. sky_use_cubemap_array = GLOBAL_GET("rendering/quality/reflections/texture_array_reflections");
  5862. // sky_use_cubemap_array = false;
  5863. //uint32_t textures_per_stage = RD::get_singleton()->limit_get(RD::LIMIT_MAX_TEXTURES_PER_SHADER_STAGE);
  5864. {
  5865. //kinda complicated to compute the amount of slots, we try to use as many as we can
  5866. gi_probe_max_lights = 32;
  5867. gi_probe_lights = memnew_arr(GIProbeLight, gi_probe_max_lights);
  5868. gi_probe_lights_uniform = RD::get_singleton()->uniform_buffer_create(gi_probe_max_lights * sizeof(GIProbeLight));
  5869. gi_probe_quality = RS::GIProbeQuality(CLAMP(int(GLOBAL_GET("rendering/quality/gi_probes/quality")), 0, 1));
  5870. String defines = "\n#define MAX_LIGHTS " + itos(gi_probe_max_lights) + "\n";
  5871. Vector<String> versions;
  5872. versions.push_back("\n#define MODE_COMPUTE_LIGHT\n");
  5873. versions.push_back("\n#define MODE_SECOND_BOUNCE\n");
  5874. versions.push_back("\n#define MODE_UPDATE_MIPMAPS\n");
  5875. versions.push_back("\n#define MODE_WRITE_TEXTURE\n");
  5876. versions.push_back("\n#define MODE_DYNAMIC\n#define MODE_DYNAMIC_LIGHTING\n");
  5877. versions.push_back("\n#define MODE_DYNAMIC\n#define MODE_DYNAMIC_SHRINK\n#define MODE_DYNAMIC_SHRINK_WRITE\n");
  5878. versions.push_back("\n#define MODE_DYNAMIC\n#define MODE_DYNAMIC_SHRINK\n#define MODE_DYNAMIC_SHRINK_PLOT\n");
  5879. versions.push_back("\n#define MODE_DYNAMIC\n#define MODE_DYNAMIC_SHRINK\n#define MODE_DYNAMIC_SHRINK_PLOT\n#define MODE_DYNAMIC_SHRINK_WRITE\n");
  5880. giprobe_shader.initialize(versions, defines);
  5881. giprobe_lighting_shader_version = giprobe_shader.version_create();
  5882. for (int i = 0; i < GI_PROBE_SHADER_VERSION_MAX; i++) {
  5883. giprobe_lighting_shader_version_shaders[i] = giprobe_shader.version_get_shader(giprobe_lighting_shader_version, i);
  5884. giprobe_lighting_shader_version_pipelines[i] = RD::get_singleton()->compute_pipeline_create(giprobe_lighting_shader_version_shaders[i]);
  5885. }
  5886. }
  5887. {
  5888. String defines;
  5889. Vector<String> versions;
  5890. versions.push_back("\n#define MODE_DEBUG_COLOR\n");
  5891. versions.push_back("\n#define MODE_DEBUG_LIGHT\n");
  5892. versions.push_back("\n#define MODE_DEBUG_EMISSION\n");
  5893. versions.push_back("\n#define MODE_DEBUG_LIGHT\n#define MODE_DEBUG_LIGHT_FULL\n");
  5894. giprobe_debug_shader.initialize(versions, defines);
  5895. giprobe_debug_shader_version = giprobe_debug_shader.version_create();
  5896. for (int i = 0; i < GI_PROBE_DEBUG_MAX; i++) {
  5897. giprobe_debug_shader_version_shaders[i] = giprobe_debug_shader.version_get_shader(giprobe_debug_shader_version, i);
  5898. RD::PipelineRasterizationState rs;
  5899. rs.cull_mode = RD::POLYGON_CULL_FRONT;
  5900. RD::PipelineDepthStencilState ds;
  5901. ds.enable_depth_test = true;
  5902. ds.enable_depth_write = true;
  5903. ds.depth_compare_operator = RD::COMPARE_OP_LESS_OR_EQUAL;
  5904. giprobe_debug_shader_version_pipelines[i].setup(giprobe_debug_shader_version_shaders[i], RD::RENDER_PRIMITIVE_TRIANGLES, rs, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(), 0);
  5905. }
  5906. }
  5907. /* SKY SHADER */
  5908. {
  5909. // Start with the directional lights for the sky
  5910. sky_scene_state.max_directional_lights = 4;
  5911. uint32_t directional_light_buffer_size = sky_scene_state.max_directional_lights * sizeof(SkyDirectionalLightData);
  5912. sky_scene_state.directional_lights = memnew_arr(SkyDirectionalLightData, sky_scene_state.max_directional_lights);
  5913. sky_scene_state.last_frame_directional_lights = memnew_arr(SkyDirectionalLightData, sky_scene_state.max_directional_lights);
  5914. sky_scene_state.last_frame_directional_light_count = sky_scene_state.max_directional_lights + 1;
  5915. sky_scene_state.directional_light_buffer = RD::get_singleton()->uniform_buffer_create(directional_light_buffer_size);
  5916. String defines = "\n#define MAX_DIRECTIONAL_LIGHT_DATA_STRUCTS " + itos(sky_scene_state.max_directional_lights) + "\n";
  5917. // Initialize sky
  5918. Vector<String> sky_modes;
  5919. sky_modes.push_back(""); // Full size
  5920. sky_modes.push_back("\n#define USE_HALF_RES_PASS\n"); // Half Res
  5921. sky_modes.push_back("\n#define USE_QUARTER_RES_PASS\n"); // Quarter res
  5922. sky_modes.push_back("\n#define USE_CUBEMAP_PASS\n"); // Cubemap
  5923. sky_modes.push_back("\n#define USE_CUBEMAP_PASS\n#define USE_HALF_RES_PASS\n"); // Half Res Cubemap
  5924. sky_modes.push_back("\n#define USE_CUBEMAP_PASS\n#define USE_QUARTER_RES_PASS\n"); // Quarter res Cubemap
  5925. sky_shader.shader.initialize(sky_modes, defines);
  5926. }
  5927. // register our shader funds
  5928. storage->shader_set_data_request_function(RasterizerStorageRD::SHADER_TYPE_SKY, _create_sky_shader_funcs);
  5929. storage->material_set_data_request_function(RasterizerStorageRD::SHADER_TYPE_SKY, _create_sky_material_funcs);
  5930. {
  5931. ShaderCompilerRD::DefaultIdentifierActions actions;
  5932. actions.renames["COLOR"] = "color";
  5933. actions.renames["ALPHA"] = "alpha";
  5934. actions.renames["EYEDIR"] = "cube_normal";
  5935. actions.renames["POSITION"] = "params.position_multiplier.xyz";
  5936. actions.renames["SKY_COORDS"] = "panorama_coords";
  5937. actions.renames["SCREEN_UV"] = "uv";
  5938. actions.renames["TIME"] = "params.time";
  5939. actions.renames["HALF_RES_COLOR"] = "half_res_color";
  5940. actions.renames["QUARTER_RES_COLOR"] = "quarter_res_color";
  5941. actions.renames["RADIANCE"] = "radiance";
  5942. actions.renames["LIGHT0_ENABLED"] = "directional_lights.data[0].enabled";
  5943. actions.renames["LIGHT0_DIRECTION"] = "directional_lights.data[0].direction_energy.xyz";
  5944. actions.renames["LIGHT0_ENERGY"] = "directional_lights.data[0].direction_energy.w";
  5945. actions.renames["LIGHT0_COLOR"] = "directional_lights.data[0].color_size.xyz";
  5946. actions.renames["LIGHT0_SIZE"] = "directional_lights.data[0].color_size.w";
  5947. actions.renames["LIGHT1_ENABLED"] = "directional_lights.data[1].enabled";
  5948. actions.renames["LIGHT1_DIRECTION"] = "directional_lights.data[1].direction_energy.xyz";
  5949. actions.renames["LIGHT1_ENERGY"] = "directional_lights.data[1].direction_energy.w";
  5950. actions.renames["LIGHT1_COLOR"] = "directional_lights.data[1].color_size.xyz";
  5951. actions.renames["LIGHT1_SIZE"] = "directional_lights.data[1].color_size.w";
  5952. actions.renames["LIGHT2_ENABLED"] = "directional_lights.data[2].enabled";
  5953. actions.renames["LIGHT2_DIRECTION"] = "directional_lights.data[2].direction_energy.xyz";
  5954. actions.renames["LIGHT2_ENERGY"] = "directional_lights.data[2].direction_energy.w";
  5955. actions.renames["LIGHT2_COLOR"] = "directional_lights.data[2].color_size.xyz";
  5956. actions.renames["LIGHT2_SIZE"] = "directional_lights.data[2].color_size.w";
  5957. actions.renames["LIGHT3_ENABLED"] = "directional_lights.data[3].enabled";
  5958. actions.renames["LIGHT3_DIRECTION"] = "directional_lights.data[3].direction_energy.xyz";
  5959. actions.renames["LIGHT3_ENERGY"] = "directional_lights.data[3].direction_energy.w";
  5960. actions.renames["LIGHT3_COLOR"] = "directional_lights.data[3].color_size.xyz";
  5961. actions.renames["LIGHT3_SIZE"] = "directional_lights.data[3].color_size.w";
  5962. actions.renames["AT_CUBEMAP_PASS"] = "AT_CUBEMAP_PASS";
  5963. actions.renames["AT_HALF_RES_PASS"] = "AT_HALF_RES_PASS";
  5964. actions.renames["AT_QUARTER_RES_PASS"] = "AT_QUARTER_RES_PASS";
  5965. actions.custom_samplers["RADIANCE"] = "material_samplers[3]";
  5966. actions.usage_defines["HALF_RES_COLOR"] = "\n#define USES_HALF_RES_COLOR\n";
  5967. actions.usage_defines["QUARTER_RES_COLOR"] = "\n#define USES_QUARTER_RES_COLOR\n";
  5968. actions.sampler_array_name = "material_samplers";
  5969. actions.base_texture_binding_index = 1;
  5970. actions.texture_layout_set = 1;
  5971. actions.base_uniform_string = "material.";
  5972. actions.base_varying_index = 10;
  5973. actions.default_filter = ShaderLanguage::FILTER_LINEAR_MIPMAP;
  5974. actions.default_repeat = ShaderLanguage::REPEAT_ENABLE;
  5975. actions.global_buffer_array_variable = "global_variables.data";
  5976. sky_shader.compiler.initialize(actions);
  5977. }
  5978. {
  5979. // default material and shader for sky shader
  5980. sky_shader.default_shader = storage->shader_create();
  5981. storage->shader_set_code(sky_shader.default_shader, "shader_type sky; void fragment() { COLOR = vec3(0.0); } \n");
  5982. sky_shader.default_material = storage->material_create();
  5983. storage->material_set_shader(sky_shader.default_material, sky_shader.default_shader);
  5984. SkyMaterialData *md = (SkyMaterialData *)storage->material_get_data(sky_shader.default_material, RasterizerStorageRD::SHADER_TYPE_SKY);
  5985. sky_shader.default_shader_rd = sky_shader.shader.version_get_shader(md->shader_data->version, SKY_VERSION_BACKGROUND);
  5986. Vector<RD::Uniform> uniforms;
  5987. {
  5988. RD::Uniform u;
  5989. u.type = RD::UNIFORM_TYPE_SAMPLER;
  5990. u.binding = 0;
  5991. u.ids.resize(12);
  5992. RID *ids_ptr = u.ids.ptrw();
  5993. ids_ptr[0] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  5994. ids_ptr[1] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  5995. ids_ptr[2] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  5996. ids_ptr[3] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  5997. ids_ptr[4] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  5998. ids_ptr[5] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED);
  5999. ids_ptr[6] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  6000. ids_ptr[7] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  6001. ids_ptr[8] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  6002. ids_ptr[9] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  6003. ids_ptr[10] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_NEAREST_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  6004. ids_ptr[11] = storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC, RS::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED);
  6005. uniforms.push_back(u);
  6006. }
  6007. {
  6008. RD::Uniform u;
  6009. u.type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  6010. u.binding = 1;
  6011. u.ids.push_back(storage->global_variables_get_storage_buffer());
  6012. uniforms.push_back(u);
  6013. }
  6014. sky_scene_state.sampler_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sky_shader.default_shader_rd, SKY_SET_SAMPLERS);
  6015. }
  6016. {
  6017. Vector<String> preprocess_modes;
  6018. preprocess_modes.push_back("\n#define MODE_SCROLL\n");
  6019. preprocess_modes.push_back("\n#define MODE_SCROLL_OCCLUSION\n");
  6020. preprocess_modes.push_back("\n#define MODE_INITIALIZE_JUMP_FLOOD\n");
  6021. preprocess_modes.push_back("\n#define MODE_INITIALIZE_JUMP_FLOOD_HALF\n");
  6022. preprocess_modes.push_back("\n#define MODE_JUMPFLOOD\n");
  6023. preprocess_modes.push_back("\n#define MODE_JUMPFLOOD_OPTIMIZED\n");
  6024. preprocess_modes.push_back("\n#define MODE_UPSCALE_JUMP_FLOOD\n");
  6025. preprocess_modes.push_back("\n#define MODE_OCCLUSION\n");
  6026. preprocess_modes.push_back("\n#define MODE_STORE\n");
  6027. String defines = "\n#define OCCLUSION_SIZE " + itos(SDFGI::CASCADE_SIZE / SDFGI::PROBE_DIVISOR) + "\n";
  6028. sdfgi_shader.preprocess.initialize(preprocess_modes, defines);
  6029. sdfgi_shader.preprocess_shader = sdfgi_shader.preprocess.version_create();
  6030. for (int i = 0; i < SDGIShader::PRE_PROCESS_MAX; i++) {
  6031. sdfgi_shader.preprocess_pipeline[i] = RD::get_singleton()->compute_pipeline_create(sdfgi_shader.preprocess.version_get_shader(sdfgi_shader.preprocess_shader, i));
  6032. }
  6033. }
  6034. {
  6035. //calculate tables
  6036. String defines = "\n#define OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
  6037. Vector<String> direct_light_modes;
  6038. direct_light_modes.push_back("\n#define MODE_PROCESS_STATIC\n");
  6039. direct_light_modes.push_back("\n#define MODE_PROCESS_DYNAMIC\n");
  6040. sdfgi_shader.direct_light.initialize(direct_light_modes, defines);
  6041. sdfgi_shader.direct_light_shader = sdfgi_shader.direct_light.version_create();
  6042. for (int i = 0; i < SDGIShader::DIRECT_LIGHT_MODE_MAX; i++) {
  6043. sdfgi_shader.direct_light_pipeline[i] = RD::get_singleton()->compute_pipeline_create(sdfgi_shader.direct_light.version_get_shader(sdfgi_shader.direct_light_shader, i));
  6044. }
  6045. }
  6046. {
  6047. //calculate tables
  6048. String defines = "\n#define OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
  6049. defines += "\n#define SH_SIZE " + itos(SDFGI::SH_SIZE) + "\n";
  6050. Vector<String> integrate_modes;
  6051. integrate_modes.push_back("\n#define MODE_PROCESS\n");
  6052. integrate_modes.push_back("\n#define MODE_STORE\n");
  6053. integrate_modes.push_back("\n#define MODE_SCROLL\n");
  6054. integrate_modes.push_back("\n#define MODE_SCROLL_STORE\n");
  6055. sdfgi_shader.integrate.initialize(integrate_modes, defines);
  6056. sdfgi_shader.integrate_shader = sdfgi_shader.integrate.version_create();
  6057. for (int i = 0; i < SDGIShader::INTEGRATE_MODE_MAX; i++) {
  6058. sdfgi_shader.integrate_pipeline[i] = RD::get_singleton()->compute_pipeline_create(sdfgi_shader.integrate.version_get_shader(sdfgi_shader.integrate_shader, i));
  6059. }
  6060. {
  6061. Vector<RD::Uniform> uniforms;
  6062. {
  6063. RD::Uniform u;
  6064. u.type = RD::UNIFORM_TYPE_TEXTURE;
  6065. u.binding = 0;
  6066. u.ids.push_back(storage->texture_rd_get_default(RasterizerStorageRD::DEFAULT_RD_TEXTURE_3D_WHITE));
  6067. uniforms.push_back(u);
  6068. }
  6069. {
  6070. RD::Uniform u;
  6071. u.type = RD::UNIFORM_TYPE_SAMPLER;
  6072. u.binding = 1;
  6073. u.ids.push_back(storage->sampler_rd_get_default(RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED));
  6074. uniforms.push_back(u);
  6075. }
  6076. sdfgi_shader.integrate_default_sky_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, sdfgi_shader.integrate.version_get_shader(sdfgi_shader.integrate_shader, 0), 1);
  6077. }
  6078. }
  6079. {
  6080. //calculate tables
  6081. String defines = "\n#define SDFGI_OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
  6082. Vector<String> gi_modes;
  6083. gi_modes.push_back("");
  6084. gi.shader.initialize(gi_modes, defines);
  6085. gi.shader_version = gi.shader.version_create();
  6086. for (int i = 0; i < GI::MODE_MAX; i++) {
  6087. gi.pipelines[i] = RD::get_singleton()->compute_pipeline_create(gi.shader.version_get_shader(gi.shader_version, i));
  6088. }
  6089. gi.sdfgi_ubo = RD::get_singleton()->uniform_buffer_create(sizeof(GI::SDFGIData));
  6090. }
  6091. {
  6092. String defines = "\n#define OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
  6093. Vector<String> debug_modes;
  6094. debug_modes.push_back("");
  6095. sdfgi_shader.debug.initialize(debug_modes, defines);
  6096. sdfgi_shader.debug_shader = sdfgi_shader.debug.version_create();
  6097. sdfgi_shader.debug_shader_version = sdfgi_shader.debug.version_get_shader(sdfgi_shader.debug_shader, 0);
  6098. sdfgi_shader.debug_pipeline = RD::get_singleton()->compute_pipeline_create(sdfgi_shader.debug_shader_version);
  6099. }
  6100. {
  6101. String defines = "\n#define OCT_SIZE " + itos(SDFGI::LIGHTPROBE_OCT_SIZE) + "\n";
  6102. Vector<String> versions;
  6103. versions.push_back("\n#define MODE_PROBES\n");
  6104. versions.push_back("\n#define MODE_VISIBILITY\n");
  6105. sdfgi_shader.debug_probes.initialize(versions, defines);
  6106. sdfgi_shader.debug_probes_shader = sdfgi_shader.debug_probes.version_create();
  6107. {
  6108. RD::PipelineRasterizationState rs;
  6109. rs.cull_mode = RD::POLYGON_CULL_DISABLED;
  6110. RD::PipelineDepthStencilState ds;
  6111. ds.enable_depth_test = true;
  6112. ds.enable_depth_write = true;
  6113. ds.depth_compare_operator = RD::COMPARE_OP_LESS_OR_EQUAL;
  6114. for (int i = 0; i < SDGIShader::PROBE_DEBUG_MAX; i++) {
  6115. RID debug_probes_shader_version = sdfgi_shader.debug_probes.version_get_shader(sdfgi_shader.debug_probes_shader, i);
  6116. sdfgi_shader.debug_probes_pipeline[i].setup(debug_probes_shader_version, RD::RENDER_PRIMITIVE_TRIANGLE_STRIPS, rs, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(), 0);
  6117. }
  6118. }
  6119. }
  6120. //cluster setup
  6121. uint32_t uniform_max_size = RD::get_singleton()->limit_get(RD::LIMIT_MAX_UNIFORM_BUFFER_SIZE);
  6122. { //reflections
  6123. uint32_t reflection_buffer_size;
  6124. if (uniform_max_size < 65536) {
  6125. //Yes, you guessed right, ARM again
  6126. reflection_buffer_size = uniform_max_size;
  6127. } else {
  6128. reflection_buffer_size = 65536;
  6129. }
  6130. cluster.max_reflections = reflection_buffer_size / sizeof(Cluster::ReflectionData);
  6131. cluster.reflections = memnew_arr(Cluster::ReflectionData, cluster.max_reflections);
  6132. cluster.reflection_buffer = RD::get_singleton()->storage_buffer_create(reflection_buffer_size);
  6133. }
  6134. { //lights
  6135. cluster.max_lights = MIN(1024 * 1024, uniform_max_size) / sizeof(Cluster::LightData); //1mb of lights
  6136. uint32_t light_buffer_size = cluster.max_lights * sizeof(Cluster::LightData);
  6137. cluster.lights = memnew_arr(Cluster::LightData, cluster.max_lights);
  6138. cluster.light_buffer = RD::get_singleton()->storage_buffer_create(light_buffer_size);
  6139. //defines += "\n#define MAX_LIGHT_DATA_STRUCTS " + itos(cluster.max_lights) + "\n";
  6140. cluster.max_directional_lights = 8;
  6141. uint32_t directional_light_buffer_size = cluster.max_directional_lights * sizeof(Cluster::DirectionalLightData);
  6142. cluster.directional_lights = memnew_arr(Cluster::DirectionalLightData, cluster.max_directional_lights);
  6143. cluster.directional_light_buffer = RD::get_singleton()->uniform_buffer_create(directional_light_buffer_size);
  6144. }
  6145. { //decals
  6146. cluster.max_decals = MIN(1024 * 1024, uniform_max_size) / sizeof(Cluster::DecalData); //1mb of decals
  6147. uint32_t decal_buffer_size = cluster.max_decals * sizeof(Cluster::DecalData);
  6148. cluster.decals = memnew_arr(Cluster::DecalData, cluster.max_decals);
  6149. cluster.decal_buffer = RD::get_singleton()->storage_buffer_create(decal_buffer_size);
  6150. }
  6151. cluster.builder.setup(16, 8, 24);
  6152. default_giprobe_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(GI::GIProbeData) * RenderBuffers::MAX_GIPROBES);
  6153. camera_effects_set_dof_blur_bokeh_shape(RS::DOFBokehShape(int(GLOBAL_GET("rendering/quality/depth_of_field/depth_of_field_bokeh_shape"))));
  6154. camera_effects_set_dof_blur_quality(RS::DOFBlurQuality(int(GLOBAL_GET("rendering/quality/depth_of_field/depth_of_field_bokeh_quality"))), GLOBAL_GET("rendering/quality/depth_of_field/depth_of_field_use_jitter"));
  6155. environment_set_ssao_quality(RS::EnvironmentSSAOQuality(int(GLOBAL_GET("rendering/quality/ssao/quality"))), GLOBAL_GET("rendering/quality/ssao/half_size"));
  6156. screen_space_roughness_limiter = GLOBAL_GET("rendering/quality/screen_filters/screen_space_roughness_limiter_enabled");
  6157. screen_space_roughness_limiter_amount = GLOBAL_GET("rendering/quality/screen_filters/screen_space_roughness_limiter_amount");
  6158. screen_space_roughness_limiter_limit = GLOBAL_GET("rendering/quality/screen_filters/screen_space_roughness_limiter_limit");
  6159. glow_bicubic_upscale = int(GLOBAL_GET("rendering/quality/glow/upscale_mode")) > 0;
  6160. ssr_roughness_quality = RS::EnvironmentSSRRoughnessQuality(int(GLOBAL_GET("rendering/quality/screen_space_reflection/roughness_quality")));
  6161. sss_quality = RS::SubSurfaceScatteringQuality(int(GLOBAL_GET("rendering/quality/subsurface_scattering/subsurface_scattering_quality")));
  6162. sss_scale = GLOBAL_GET("rendering/quality/subsurface_scattering/subsurface_scattering_scale");
  6163. sss_depth_scale = GLOBAL_GET("rendering/quality/subsurface_scattering/subsurface_scattering_depth_scale");
  6164. directional_penumbra_shadow_kernel = memnew_arr(float, 128);
  6165. directional_soft_shadow_kernel = memnew_arr(float, 128);
  6166. penumbra_shadow_kernel = memnew_arr(float, 128);
  6167. soft_shadow_kernel = memnew_arr(float, 128);
  6168. shadows_quality_set(RS::ShadowQuality(int(GLOBAL_GET("rendering/quality/shadows/soft_shadow_quality"))));
  6169. directional_shadow_quality_set(RS::ShadowQuality(int(GLOBAL_GET("rendering/quality/directional_shadow/soft_shadow_quality"))));
  6170. }
  6171. RasterizerSceneRD::~RasterizerSceneRD() {
  6172. for (Map<Vector2i, ShadowMap>::Element *E = shadow_maps.front(); E; E = E->next()) {
  6173. RD::get_singleton()->free(E->get().depth);
  6174. }
  6175. for (Map<int, ShadowCubemap>::Element *E = shadow_cubemaps.front(); E; E = E->next()) {
  6176. RD::get_singleton()->free(E->get().cubemap);
  6177. }
  6178. if (sky_scene_state.sampler_uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(sky_scene_state.sampler_uniform_set)) {
  6179. RD::get_singleton()->free(sky_scene_state.sampler_uniform_set);
  6180. }
  6181. if (sky_scene_state.light_uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(sky_scene_state.light_uniform_set)) {
  6182. RD::get_singleton()->free(sky_scene_state.light_uniform_set);
  6183. }
  6184. RD::get_singleton()->free(default_giprobe_buffer);
  6185. RD::get_singleton()->free(gi_probe_lights_uniform);
  6186. RD::get_singleton()->free(gi.sdfgi_ubo);
  6187. giprobe_debug_shader.version_free(giprobe_debug_shader_version);
  6188. giprobe_shader.version_free(giprobe_lighting_shader_version);
  6189. gi.shader.version_free(gi.shader_version);
  6190. sdfgi_shader.debug_probes.version_free(sdfgi_shader.debug_probes_shader);
  6191. sdfgi_shader.debug.version_free(sdfgi_shader.debug_shader);
  6192. sdfgi_shader.direct_light.version_free(sdfgi_shader.direct_light_shader);
  6193. sdfgi_shader.integrate.version_free(sdfgi_shader.integrate_shader);
  6194. sdfgi_shader.preprocess.version_free(sdfgi_shader.preprocess_shader);
  6195. memdelete_arr(gi_probe_lights);
  6196. SkyMaterialData *md = (SkyMaterialData *)storage->material_get_data(sky_shader.default_material, RasterizerStorageRD::SHADER_TYPE_SKY);
  6197. sky_shader.shader.version_free(md->shader_data->version);
  6198. RD::get_singleton()->free(sky_scene_state.directional_light_buffer);
  6199. memdelete_arr(sky_scene_state.directional_lights);
  6200. memdelete_arr(sky_scene_state.last_frame_directional_lights);
  6201. storage->free(sky_shader.default_shader);
  6202. storage->free(sky_shader.default_material);
  6203. memdelete_arr(directional_penumbra_shadow_kernel);
  6204. memdelete_arr(directional_soft_shadow_kernel);
  6205. memdelete_arr(penumbra_shadow_kernel);
  6206. memdelete_arr(soft_shadow_kernel);
  6207. {
  6208. RD::get_singleton()->free(cluster.directional_light_buffer);
  6209. RD::get_singleton()->free(cluster.light_buffer);
  6210. RD::get_singleton()->free(cluster.reflection_buffer);
  6211. RD::get_singleton()->free(cluster.decal_buffer);
  6212. memdelete_arr(cluster.directional_lights);
  6213. memdelete_arr(cluster.lights);
  6214. memdelete_arr(cluster.reflections);
  6215. memdelete_arr(cluster.decals);
  6216. }
  6217. }