rendering_device_vulkan.cpp 384 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483
  1. /*************************************************************************/
  2. /* rendering_device_vulkan.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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 "rendering_device_vulkan.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/compression.h"
  33. #include "core/io/file_access.h"
  34. #include "core/io/marshalls.h"
  35. #include "core/os/os.h"
  36. #include "core/templates/hashfuncs.h"
  37. #include "drivers/vulkan/vulkan_context.h"
  38. #include "thirdparty/misc/smolv.h"
  39. #include "thirdparty/spirv-reflect/spirv_reflect.h"
  40. //#define FORCE_FULL_BARRIER
  41. static const uint32_t SMALL_ALLOCATION_MAX_SIZE = 4096;
  42. // Get the Vulkan object information and possible stage access types (bitwise OR'd with incoming values)
  43. RenderingDeviceVulkan::Buffer *RenderingDeviceVulkan::_get_buffer_from_owner(RID p_buffer, VkPipelineStageFlags &r_stage_mask, VkAccessFlags &r_access_mask, uint32_t p_post_barrier) {
  44. Buffer *buffer = nullptr;
  45. if (vertex_buffer_owner.owns(p_buffer)) {
  46. buffer = vertex_buffer_owner.get_or_null(p_buffer);
  47. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  48. r_access_mask |= VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
  49. if (buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) {
  50. if (p_post_barrier & BARRIER_MASK_RASTER) {
  51. r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  52. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  53. }
  54. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  55. r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  56. r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  57. }
  58. }
  59. } else if (index_buffer_owner.owns(p_buffer)) {
  60. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  61. r_access_mask |= VK_ACCESS_INDEX_READ_BIT;
  62. buffer = index_buffer_owner.get_or_null(p_buffer);
  63. } else if (uniform_buffer_owner.owns(p_buffer)) {
  64. if (p_post_barrier & BARRIER_MASK_RASTER) {
  65. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  66. }
  67. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  68. r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  69. }
  70. r_access_mask |= VK_ACCESS_UNIFORM_READ_BIT;
  71. buffer = uniform_buffer_owner.get_or_null(p_buffer);
  72. } else if (texture_buffer_owner.owns(p_buffer)) {
  73. if (p_post_barrier & BARRIER_MASK_RASTER) {
  74. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  75. r_access_mask |= VK_ACCESS_SHADER_READ_BIT;
  76. }
  77. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  78. r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  79. r_access_mask |= VK_ACCESS_SHADER_READ_BIT;
  80. }
  81. buffer = &texture_buffer_owner.get_or_null(p_buffer)->buffer;
  82. } else if (storage_buffer_owner.owns(p_buffer)) {
  83. buffer = storage_buffer_owner.get_or_null(p_buffer);
  84. if (p_post_barrier & BARRIER_MASK_RASTER) {
  85. r_stage_mask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  86. r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  87. }
  88. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  89. r_stage_mask |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  90. r_access_mask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  91. }
  92. if (buffer->usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) {
  93. r_stage_mask |= VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
  94. r_access_mask |= VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
  95. }
  96. }
  97. return buffer;
  98. }
  99. static void update_external_dependency_for_store(VkSubpassDependency &dependency, bool is_sampled, bool is_storage, bool is_depth) {
  100. // Transitioning from write to read, protect the shaders that may use this next
  101. // Allow for copies/image layout transitions
  102. dependency.dstStageMask |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  103. dependency.dstAccessMask |= VK_ACCESS_TRANSFER_READ_BIT;
  104. if (is_sampled) {
  105. dependency.dstStageMask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  106. dependency.dstAccessMask |= VK_ACCESS_SHADER_READ_BIT;
  107. } else if (is_storage) {
  108. dependency.dstStageMask |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  109. dependency.dstAccessMask |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  110. } else {
  111. dependency.dstStageMask |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  112. dependency.dstAccessMask |= VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  113. }
  114. if (is_depth) {
  115. // Depth resources have additional stages that may be interested in them
  116. dependency.dstStageMask |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  117. dependency.dstAccessMask |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  118. }
  119. }
  120. void RenderingDeviceVulkan::_add_dependency(RID p_id, RID p_depends_on) {
  121. if (!dependency_map.has(p_depends_on)) {
  122. dependency_map[p_depends_on] = Set<RID>();
  123. }
  124. dependency_map[p_depends_on].insert(p_id);
  125. if (!reverse_dependency_map.has(p_id)) {
  126. reverse_dependency_map[p_id] = Set<RID>();
  127. }
  128. reverse_dependency_map[p_id].insert(p_depends_on);
  129. }
  130. void RenderingDeviceVulkan::_free_dependencies(RID p_id) {
  131. //direct dependencies must be freed
  132. Map<RID, Set<RID>>::Element *E = dependency_map.find(p_id);
  133. if (E) {
  134. while (E->get().size()) {
  135. free(E->get().front()->get());
  136. }
  137. dependency_map.erase(E);
  138. }
  139. //reverse dependencies must be unreferenced
  140. E = reverse_dependency_map.find(p_id);
  141. if (E) {
  142. for (Set<RID>::Element *F = E->get().front(); F; F = F->next()) {
  143. Map<RID, Set<RID>>::Element *G = dependency_map.find(F->get());
  144. ERR_CONTINUE(!G);
  145. ERR_CONTINUE(!G->get().has(p_id));
  146. G->get().erase(p_id);
  147. }
  148. reverse_dependency_map.erase(E);
  149. }
  150. }
  151. const VkFormat RenderingDeviceVulkan::vulkan_formats[RenderingDevice::DATA_FORMAT_MAX] = {
  152. VK_FORMAT_R4G4_UNORM_PACK8,
  153. VK_FORMAT_R4G4B4A4_UNORM_PACK16,
  154. VK_FORMAT_B4G4R4A4_UNORM_PACK16,
  155. VK_FORMAT_R5G6B5_UNORM_PACK16,
  156. VK_FORMAT_B5G6R5_UNORM_PACK16,
  157. VK_FORMAT_R5G5B5A1_UNORM_PACK16,
  158. VK_FORMAT_B5G5R5A1_UNORM_PACK16,
  159. VK_FORMAT_A1R5G5B5_UNORM_PACK16,
  160. VK_FORMAT_R8_UNORM,
  161. VK_FORMAT_R8_SNORM,
  162. VK_FORMAT_R8_USCALED,
  163. VK_FORMAT_R8_SSCALED,
  164. VK_FORMAT_R8_UINT,
  165. VK_FORMAT_R8_SINT,
  166. VK_FORMAT_R8_SRGB,
  167. VK_FORMAT_R8G8_UNORM,
  168. VK_FORMAT_R8G8_SNORM,
  169. VK_FORMAT_R8G8_USCALED,
  170. VK_FORMAT_R8G8_SSCALED,
  171. VK_FORMAT_R8G8_UINT,
  172. VK_FORMAT_R8G8_SINT,
  173. VK_FORMAT_R8G8_SRGB,
  174. VK_FORMAT_R8G8B8_UNORM,
  175. VK_FORMAT_R8G8B8_SNORM,
  176. VK_FORMAT_R8G8B8_USCALED,
  177. VK_FORMAT_R8G8B8_SSCALED,
  178. VK_FORMAT_R8G8B8_UINT,
  179. VK_FORMAT_R8G8B8_SINT,
  180. VK_FORMAT_R8G8B8_SRGB,
  181. VK_FORMAT_B8G8R8_UNORM,
  182. VK_FORMAT_B8G8R8_SNORM,
  183. VK_FORMAT_B8G8R8_USCALED,
  184. VK_FORMAT_B8G8R8_SSCALED,
  185. VK_FORMAT_B8G8R8_UINT,
  186. VK_FORMAT_B8G8R8_SINT,
  187. VK_FORMAT_B8G8R8_SRGB,
  188. VK_FORMAT_R8G8B8A8_UNORM,
  189. VK_FORMAT_R8G8B8A8_SNORM,
  190. VK_FORMAT_R8G8B8A8_USCALED,
  191. VK_FORMAT_R8G8B8A8_SSCALED,
  192. VK_FORMAT_R8G8B8A8_UINT,
  193. VK_FORMAT_R8G8B8A8_SINT,
  194. VK_FORMAT_R8G8B8A8_SRGB,
  195. VK_FORMAT_B8G8R8A8_UNORM,
  196. VK_FORMAT_B8G8R8A8_SNORM,
  197. VK_FORMAT_B8G8R8A8_USCALED,
  198. VK_FORMAT_B8G8R8A8_SSCALED,
  199. VK_FORMAT_B8G8R8A8_UINT,
  200. VK_FORMAT_B8G8R8A8_SINT,
  201. VK_FORMAT_B8G8R8A8_SRGB,
  202. VK_FORMAT_A8B8G8R8_UNORM_PACK32,
  203. VK_FORMAT_A8B8G8R8_SNORM_PACK32,
  204. VK_FORMAT_A8B8G8R8_USCALED_PACK32,
  205. VK_FORMAT_A8B8G8R8_SSCALED_PACK32,
  206. VK_FORMAT_A8B8G8R8_UINT_PACK32,
  207. VK_FORMAT_A8B8G8R8_SINT_PACK32,
  208. VK_FORMAT_A8B8G8R8_SRGB_PACK32,
  209. VK_FORMAT_A2R10G10B10_UNORM_PACK32,
  210. VK_FORMAT_A2R10G10B10_SNORM_PACK32,
  211. VK_FORMAT_A2R10G10B10_USCALED_PACK32,
  212. VK_FORMAT_A2R10G10B10_SSCALED_PACK32,
  213. VK_FORMAT_A2R10G10B10_UINT_PACK32,
  214. VK_FORMAT_A2R10G10B10_SINT_PACK32,
  215. VK_FORMAT_A2B10G10R10_UNORM_PACK32,
  216. VK_FORMAT_A2B10G10R10_SNORM_PACK32,
  217. VK_FORMAT_A2B10G10R10_USCALED_PACK32,
  218. VK_FORMAT_A2B10G10R10_SSCALED_PACK32,
  219. VK_FORMAT_A2B10G10R10_UINT_PACK32,
  220. VK_FORMAT_A2B10G10R10_SINT_PACK32,
  221. VK_FORMAT_R16_UNORM,
  222. VK_FORMAT_R16_SNORM,
  223. VK_FORMAT_R16_USCALED,
  224. VK_FORMAT_R16_SSCALED,
  225. VK_FORMAT_R16_UINT,
  226. VK_FORMAT_R16_SINT,
  227. VK_FORMAT_R16_SFLOAT,
  228. VK_FORMAT_R16G16_UNORM,
  229. VK_FORMAT_R16G16_SNORM,
  230. VK_FORMAT_R16G16_USCALED,
  231. VK_FORMAT_R16G16_SSCALED,
  232. VK_FORMAT_R16G16_UINT,
  233. VK_FORMAT_R16G16_SINT,
  234. VK_FORMAT_R16G16_SFLOAT,
  235. VK_FORMAT_R16G16B16_UNORM,
  236. VK_FORMAT_R16G16B16_SNORM,
  237. VK_FORMAT_R16G16B16_USCALED,
  238. VK_FORMAT_R16G16B16_SSCALED,
  239. VK_FORMAT_R16G16B16_UINT,
  240. VK_FORMAT_R16G16B16_SINT,
  241. VK_FORMAT_R16G16B16_SFLOAT,
  242. VK_FORMAT_R16G16B16A16_UNORM,
  243. VK_FORMAT_R16G16B16A16_SNORM,
  244. VK_FORMAT_R16G16B16A16_USCALED,
  245. VK_FORMAT_R16G16B16A16_SSCALED,
  246. VK_FORMAT_R16G16B16A16_UINT,
  247. VK_FORMAT_R16G16B16A16_SINT,
  248. VK_FORMAT_R16G16B16A16_SFLOAT,
  249. VK_FORMAT_R32_UINT,
  250. VK_FORMAT_R32_SINT,
  251. VK_FORMAT_R32_SFLOAT,
  252. VK_FORMAT_R32G32_UINT,
  253. VK_FORMAT_R32G32_SINT,
  254. VK_FORMAT_R32G32_SFLOAT,
  255. VK_FORMAT_R32G32B32_UINT,
  256. VK_FORMAT_R32G32B32_SINT,
  257. VK_FORMAT_R32G32B32_SFLOAT,
  258. VK_FORMAT_R32G32B32A32_UINT,
  259. VK_FORMAT_R32G32B32A32_SINT,
  260. VK_FORMAT_R32G32B32A32_SFLOAT,
  261. VK_FORMAT_R64_UINT,
  262. VK_FORMAT_R64_SINT,
  263. VK_FORMAT_R64_SFLOAT,
  264. VK_FORMAT_R64G64_UINT,
  265. VK_FORMAT_R64G64_SINT,
  266. VK_FORMAT_R64G64_SFLOAT,
  267. VK_FORMAT_R64G64B64_UINT,
  268. VK_FORMAT_R64G64B64_SINT,
  269. VK_FORMAT_R64G64B64_SFLOAT,
  270. VK_FORMAT_R64G64B64A64_UINT,
  271. VK_FORMAT_R64G64B64A64_SINT,
  272. VK_FORMAT_R64G64B64A64_SFLOAT,
  273. VK_FORMAT_B10G11R11_UFLOAT_PACK32,
  274. VK_FORMAT_E5B9G9R9_UFLOAT_PACK32,
  275. VK_FORMAT_D16_UNORM,
  276. VK_FORMAT_X8_D24_UNORM_PACK32,
  277. VK_FORMAT_D32_SFLOAT,
  278. VK_FORMAT_S8_UINT,
  279. VK_FORMAT_D16_UNORM_S8_UINT,
  280. VK_FORMAT_D24_UNORM_S8_UINT,
  281. VK_FORMAT_D32_SFLOAT_S8_UINT,
  282. VK_FORMAT_BC1_RGB_UNORM_BLOCK,
  283. VK_FORMAT_BC1_RGB_SRGB_BLOCK,
  284. VK_FORMAT_BC1_RGBA_UNORM_BLOCK,
  285. VK_FORMAT_BC1_RGBA_SRGB_BLOCK,
  286. VK_FORMAT_BC2_UNORM_BLOCK,
  287. VK_FORMAT_BC2_SRGB_BLOCK,
  288. VK_FORMAT_BC3_UNORM_BLOCK,
  289. VK_FORMAT_BC3_SRGB_BLOCK,
  290. VK_FORMAT_BC4_UNORM_BLOCK,
  291. VK_FORMAT_BC4_SNORM_BLOCK,
  292. VK_FORMAT_BC5_UNORM_BLOCK,
  293. VK_FORMAT_BC5_SNORM_BLOCK,
  294. VK_FORMAT_BC6H_UFLOAT_BLOCK,
  295. VK_FORMAT_BC6H_SFLOAT_BLOCK,
  296. VK_FORMAT_BC7_UNORM_BLOCK,
  297. VK_FORMAT_BC7_SRGB_BLOCK,
  298. VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK,
  299. VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK,
  300. VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK,
  301. VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK,
  302. VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK,
  303. VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK,
  304. VK_FORMAT_EAC_R11_UNORM_BLOCK,
  305. VK_FORMAT_EAC_R11_SNORM_BLOCK,
  306. VK_FORMAT_EAC_R11G11_UNORM_BLOCK,
  307. VK_FORMAT_EAC_R11G11_SNORM_BLOCK,
  308. VK_FORMAT_ASTC_4x4_UNORM_BLOCK,
  309. VK_FORMAT_ASTC_4x4_SRGB_BLOCK,
  310. VK_FORMAT_ASTC_5x4_UNORM_BLOCK,
  311. VK_FORMAT_ASTC_5x4_SRGB_BLOCK,
  312. VK_FORMAT_ASTC_5x5_UNORM_BLOCK,
  313. VK_FORMAT_ASTC_5x5_SRGB_BLOCK,
  314. VK_FORMAT_ASTC_6x5_UNORM_BLOCK,
  315. VK_FORMAT_ASTC_6x5_SRGB_BLOCK,
  316. VK_FORMAT_ASTC_6x6_UNORM_BLOCK,
  317. VK_FORMAT_ASTC_6x6_SRGB_BLOCK,
  318. VK_FORMAT_ASTC_8x5_UNORM_BLOCK,
  319. VK_FORMAT_ASTC_8x5_SRGB_BLOCK,
  320. VK_FORMAT_ASTC_8x6_UNORM_BLOCK,
  321. VK_FORMAT_ASTC_8x6_SRGB_BLOCK,
  322. VK_FORMAT_ASTC_8x8_UNORM_BLOCK,
  323. VK_FORMAT_ASTC_8x8_SRGB_BLOCK,
  324. VK_FORMAT_ASTC_10x5_UNORM_BLOCK,
  325. VK_FORMAT_ASTC_10x5_SRGB_BLOCK,
  326. VK_FORMAT_ASTC_10x6_UNORM_BLOCK,
  327. VK_FORMAT_ASTC_10x6_SRGB_BLOCK,
  328. VK_FORMAT_ASTC_10x8_UNORM_BLOCK,
  329. VK_FORMAT_ASTC_10x8_SRGB_BLOCK,
  330. VK_FORMAT_ASTC_10x10_UNORM_BLOCK,
  331. VK_FORMAT_ASTC_10x10_SRGB_BLOCK,
  332. VK_FORMAT_ASTC_12x10_UNORM_BLOCK,
  333. VK_FORMAT_ASTC_12x10_SRGB_BLOCK,
  334. VK_FORMAT_ASTC_12x12_UNORM_BLOCK,
  335. VK_FORMAT_ASTC_12x12_SRGB_BLOCK,
  336. VK_FORMAT_G8B8G8R8_422_UNORM,
  337. VK_FORMAT_B8G8R8G8_422_UNORM,
  338. VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM,
  339. VK_FORMAT_G8_B8R8_2PLANE_420_UNORM,
  340. VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM,
  341. VK_FORMAT_G8_B8R8_2PLANE_422_UNORM,
  342. VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM,
  343. VK_FORMAT_R10X6_UNORM_PACK16,
  344. VK_FORMAT_R10X6G10X6_UNORM_2PACK16,
  345. VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
  346. VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16,
  347. VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16,
  348. VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16,
  349. VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16,
  350. VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16,
  351. VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16,
  352. VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16,
  353. VK_FORMAT_R12X4_UNORM_PACK16,
  354. VK_FORMAT_R12X4G12X4_UNORM_2PACK16,
  355. VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16,
  356. VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16,
  357. VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16,
  358. VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16,
  359. VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16,
  360. VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16,
  361. VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16,
  362. VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16,
  363. VK_FORMAT_G16B16G16R16_422_UNORM,
  364. VK_FORMAT_B16G16R16G16_422_UNORM,
  365. VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM,
  366. VK_FORMAT_G16_B16R16_2PLANE_420_UNORM,
  367. VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM,
  368. VK_FORMAT_G16_B16R16_2PLANE_422_UNORM,
  369. VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM,
  370. };
  371. const char *RenderingDeviceVulkan::named_formats[RenderingDevice::DATA_FORMAT_MAX] = {
  372. "R4G4_Unorm_Pack8",
  373. "R4G4B4A4_Unorm_Pack16",
  374. "B4G4R4A4_Unorm_Pack16",
  375. "R5G6B5_Unorm_Pack16",
  376. "B5G6R5_Unorm_Pack16",
  377. "R5G5B5A1_Unorm_Pack16",
  378. "B5G5R5A1_Unorm_Pack16",
  379. "A1R5G5B5_Unorm_Pack16",
  380. "R8_Unorm",
  381. "R8_Snorm",
  382. "R8_Uscaled",
  383. "R8_Sscaled",
  384. "R8_Uint",
  385. "R8_Sint",
  386. "R8_Srgb",
  387. "R8G8_Unorm",
  388. "R8G8_Snorm",
  389. "R8G8_Uscaled",
  390. "R8G8_Sscaled",
  391. "R8G8_Uint",
  392. "R8G8_Sint",
  393. "R8G8_Srgb",
  394. "R8G8B8_Unorm",
  395. "R8G8B8_Snorm",
  396. "R8G8B8_Uscaled",
  397. "R8G8B8_Sscaled",
  398. "R8G8B8_Uint",
  399. "R8G8B8_Sint",
  400. "R8G8B8_Srgb",
  401. "B8G8R8_Unorm",
  402. "B8G8R8_Snorm",
  403. "B8G8R8_Uscaled",
  404. "B8G8R8_Sscaled",
  405. "B8G8R8_Uint",
  406. "B8G8R8_Sint",
  407. "B8G8R8_Srgb",
  408. "R8G8B8A8_Unorm",
  409. "R8G8B8A8_Snorm",
  410. "R8G8B8A8_Uscaled",
  411. "R8G8B8A8_Sscaled",
  412. "R8G8B8A8_Uint",
  413. "R8G8B8A8_Sint",
  414. "R8G8B8A8_Srgb",
  415. "B8G8R8A8_Unorm",
  416. "B8G8R8A8_Snorm",
  417. "B8G8R8A8_Uscaled",
  418. "B8G8R8A8_Sscaled",
  419. "B8G8R8A8_Uint",
  420. "B8G8R8A8_Sint",
  421. "B8G8R8A8_Srgb",
  422. "A8B8G8R8_Unorm_Pack32",
  423. "A8B8G8R8_Snorm_Pack32",
  424. "A8B8G8R8_Uscaled_Pack32",
  425. "A8B8G8R8_Sscaled_Pack32",
  426. "A8B8G8R8_Uint_Pack32",
  427. "A8B8G8R8_Sint_Pack32",
  428. "A8B8G8R8_Srgb_Pack32",
  429. "A2R10G10B10_Unorm_Pack32",
  430. "A2R10G10B10_Snorm_Pack32",
  431. "A2R10G10B10_Uscaled_Pack32",
  432. "A2R10G10B10_Sscaled_Pack32",
  433. "A2R10G10B10_Uint_Pack32",
  434. "A2R10G10B10_Sint_Pack32",
  435. "A2B10G10R10_Unorm_Pack32",
  436. "A2B10G10R10_Snorm_Pack32",
  437. "A2B10G10R10_Uscaled_Pack32",
  438. "A2B10G10R10_Sscaled_Pack32",
  439. "A2B10G10R10_Uint_Pack32",
  440. "A2B10G10R10_Sint_Pack32",
  441. "R16_Unorm",
  442. "R16_Snorm",
  443. "R16_Uscaled",
  444. "R16_Sscaled",
  445. "R16_Uint",
  446. "R16_Sint",
  447. "R16_Sfloat",
  448. "R16G16_Unorm",
  449. "R16G16_Snorm",
  450. "R16G16_Uscaled",
  451. "R16G16_Sscaled",
  452. "R16G16_Uint",
  453. "R16G16_Sint",
  454. "R16G16_Sfloat",
  455. "R16G16B16_Unorm",
  456. "R16G16B16_Snorm",
  457. "R16G16B16_Uscaled",
  458. "R16G16B16_Sscaled",
  459. "R16G16B16_Uint",
  460. "R16G16B16_Sint",
  461. "R16G16B16_Sfloat",
  462. "R16G16B16A16_Unorm",
  463. "R16G16B16A16_Snorm",
  464. "R16G16B16A16_Uscaled",
  465. "R16G16B16A16_Sscaled",
  466. "R16G16B16A16_Uint",
  467. "R16G16B16A16_Sint",
  468. "R16G16B16A16_Sfloat",
  469. "R32_Uint",
  470. "R32_Sint",
  471. "R32_Sfloat",
  472. "R32G32_Uint",
  473. "R32G32_Sint",
  474. "R32G32_Sfloat",
  475. "R32G32B32_Uint",
  476. "R32G32B32_Sint",
  477. "R32G32B32_Sfloat",
  478. "R32G32B32A32_Uint",
  479. "R32G32B32A32_Sint",
  480. "R32G32B32A32_Sfloat",
  481. "R64_Uint",
  482. "R64_Sint",
  483. "R64_Sfloat",
  484. "R64G64_Uint",
  485. "R64G64_Sint",
  486. "R64G64_Sfloat",
  487. "R64G64B64_Uint",
  488. "R64G64B64_Sint",
  489. "R64G64B64_Sfloat",
  490. "R64G64B64A64_Uint",
  491. "R64G64B64A64_Sint",
  492. "R64G64B64A64_Sfloat",
  493. "B10G11R11_Ufloat_Pack32",
  494. "E5B9G9R9_Ufloat_Pack32",
  495. "D16_Unorm",
  496. "X8_D24_Unorm_Pack32",
  497. "D32_Sfloat",
  498. "S8_Uint",
  499. "D16_Unorm_S8_Uint",
  500. "D24_Unorm_S8_Uint",
  501. "D32_Sfloat_S8_Uint",
  502. "Bc1_Rgb_Unorm_Block",
  503. "Bc1_Rgb_Srgb_Block",
  504. "Bc1_Rgba_Unorm_Block",
  505. "Bc1_Rgba_Srgb_Block",
  506. "Bc2_Unorm_Block",
  507. "Bc2_Srgb_Block",
  508. "Bc3_Unorm_Block",
  509. "Bc3_Srgb_Block",
  510. "Bc4_Unorm_Block",
  511. "Bc4_Snorm_Block",
  512. "Bc5_Unorm_Block",
  513. "Bc5_Snorm_Block",
  514. "Bc6H_Ufloat_Block",
  515. "Bc6H_Sfloat_Block",
  516. "Bc7_Unorm_Block",
  517. "Bc7_Srgb_Block",
  518. "Etc2_R8G8B8_Unorm_Block",
  519. "Etc2_R8G8B8_Srgb_Block",
  520. "Etc2_R8G8B8A1_Unorm_Block",
  521. "Etc2_R8G8B8A1_Srgb_Block",
  522. "Etc2_R8G8B8A8_Unorm_Block",
  523. "Etc2_R8G8B8A8_Srgb_Block",
  524. "Eac_R11_Unorm_Block",
  525. "Eac_R11_Snorm_Block",
  526. "Eac_R11G11_Unorm_Block",
  527. "Eac_R11G11_Snorm_Block",
  528. "Astc_4X4_Unorm_Block",
  529. "Astc_4X4_Srgb_Block",
  530. "Astc_5X4_Unorm_Block",
  531. "Astc_5X4_Srgb_Block",
  532. "Astc_5X5_Unorm_Block",
  533. "Astc_5X5_Srgb_Block",
  534. "Astc_6X5_Unorm_Block",
  535. "Astc_6X5_Srgb_Block",
  536. "Astc_6X6_Unorm_Block",
  537. "Astc_6X6_Srgb_Block",
  538. "Astc_8X5_Unorm_Block",
  539. "Astc_8X5_Srgb_Block",
  540. "Astc_8X6_Unorm_Block",
  541. "Astc_8X6_Srgb_Block",
  542. "Astc_8X8_Unorm_Block",
  543. "Astc_8X8_Srgb_Block",
  544. "Astc_10X5_Unorm_Block",
  545. "Astc_10X5_Srgb_Block",
  546. "Astc_10X6_Unorm_Block",
  547. "Astc_10X6_Srgb_Block",
  548. "Astc_10X8_Unorm_Block",
  549. "Astc_10X8_Srgb_Block",
  550. "Astc_10X10_Unorm_Block",
  551. "Astc_10X10_Srgb_Block",
  552. "Astc_12X10_Unorm_Block",
  553. "Astc_12X10_Srgb_Block",
  554. "Astc_12X12_Unorm_Block",
  555. "Astc_12X12_Srgb_Block",
  556. "G8B8G8R8_422_Unorm",
  557. "B8G8R8G8_422_Unorm",
  558. "G8_B8_R8_3Plane_420_Unorm",
  559. "G8_B8R8_2Plane_420_Unorm",
  560. "G8_B8_R8_3Plane_422_Unorm",
  561. "G8_B8R8_2Plane_422_Unorm",
  562. "G8_B8_R8_3Plane_444_Unorm",
  563. "R10X6_Unorm_Pack16",
  564. "R10X6G10X6_Unorm_2Pack16",
  565. "R10X6G10X6B10X6A10X6_Unorm_4Pack16",
  566. "G10X6B10X6G10X6R10X6_422_Unorm_4Pack16",
  567. "B10X6G10X6R10X6G10X6_422_Unorm_4Pack16",
  568. "G10X6_B10X6_R10X6_3Plane_420_Unorm_3Pack16",
  569. "G10X6_B10X6R10X6_2Plane_420_Unorm_3Pack16",
  570. "G10X6_B10X6_R10X6_3Plane_422_Unorm_3Pack16",
  571. "G10X6_B10X6R10X6_2Plane_422_Unorm_3Pack16",
  572. "G10X6_B10X6_R10X6_3Plane_444_Unorm_3Pack16",
  573. "R12X4_Unorm_Pack16",
  574. "R12X4G12X4_Unorm_2Pack16",
  575. "R12X4G12X4B12X4A12X4_Unorm_4Pack16",
  576. "G12X4B12X4G12X4R12X4_422_Unorm_4Pack16",
  577. "B12X4G12X4R12X4G12X4_422_Unorm_4Pack16",
  578. "G12X4_B12X4_R12X4_3Plane_420_Unorm_3Pack16",
  579. "G12X4_B12X4R12X4_2Plane_420_Unorm_3Pack16",
  580. "G12X4_B12X4_R12X4_3Plane_422_Unorm_3Pack16",
  581. "G12X4_B12X4R12X4_2Plane_422_Unorm_3Pack16",
  582. "G12X4_B12X4_R12X4_3Plane_444_Unorm_3Pack16",
  583. "G16B16G16R16_422_Unorm",
  584. "B16G16R16G16_422_Unorm",
  585. "G16_B16_R16_3Plane_420_Unorm",
  586. "G16_B16R16_2Plane_420_Unorm",
  587. "G16_B16_R16_3Plane_422_Unorm",
  588. "G16_B16R16_2Plane_422_Unorm",
  589. "G16_B16_R16_3Plane_444_Unorm",
  590. };
  591. int RenderingDeviceVulkan::get_format_vertex_size(DataFormat p_format) {
  592. switch (p_format) {
  593. case DATA_FORMAT_R8_UNORM:
  594. case DATA_FORMAT_R8_SNORM:
  595. case DATA_FORMAT_R8_UINT:
  596. case DATA_FORMAT_R8_SINT:
  597. case DATA_FORMAT_R8G8_UNORM:
  598. case DATA_FORMAT_R8G8_SNORM:
  599. case DATA_FORMAT_R8G8_UINT:
  600. case DATA_FORMAT_R8G8_SINT:
  601. case DATA_FORMAT_R8G8B8_UNORM:
  602. case DATA_FORMAT_R8G8B8_SNORM:
  603. case DATA_FORMAT_R8G8B8_UINT:
  604. case DATA_FORMAT_R8G8B8_SINT:
  605. case DATA_FORMAT_B8G8R8_UNORM:
  606. case DATA_FORMAT_B8G8R8_SNORM:
  607. case DATA_FORMAT_B8G8R8_UINT:
  608. case DATA_FORMAT_B8G8R8_SINT:
  609. case DATA_FORMAT_R8G8B8A8_UNORM:
  610. case DATA_FORMAT_R8G8B8A8_SNORM:
  611. case DATA_FORMAT_R8G8B8A8_UINT:
  612. case DATA_FORMAT_R8G8B8A8_SINT:
  613. case DATA_FORMAT_B8G8R8A8_UNORM:
  614. case DATA_FORMAT_B8G8R8A8_SNORM:
  615. case DATA_FORMAT_B8G8R8A8_UINT:
  616. case DATA_FORMAT_B8G8R8A8_SINT:
  617. case DATA_FORMAT_A2B10G10R10_UNORM_PACK32:
  618. return 4;
  619. case DATA_FORMAT_R16_UNORM:
  620. case DATA_FORMAT_R16_SNORM:
  621. case DATA_FORMAT_R16_UINT:
  622. case DATA_FORMAT_R16_SINT:
  623. case DATA_FORMAT_R16_SFLOAT:
  624. return 4;
  625. case DATA_FORMAT_R16G16_UNORM:
  626. case DATA_FORMAT_R16G16_SNORM:
  627. case DATA_FORMAT_R16G16_UINT:
  628. case DATA_FORMAT_R16G16_SINT:
  629. case DATA_FORMAT_R16G16_SFLOAT:
  630. return 4;
  631. case DATA_FORMAT_R16G16B16_UNORM:
  632. case DATA_FORMAT_R16G16B16_SNORM:
  633. case DATA_FORMAT_R16G16B16_UINT:
  634. case DATA_FORMAT_R16G16B16_SINT:
  635. case DATA_FORMAT_R16G16B16_SFLOAT:
  636. return 8;
  637. case DATA_FORMAT_R16G16B16A16_UNORM:
  638. case DATA_FORMAT_R16G16B16A16_SNORM:
  639. case DATA_FORMAT_R16G16B16A16_UINT:
  640. case DATA_FORMAT_R16G16B16A16_SINT:
  641. case DATA_FORMAT_R16G16B16A16_SFLOAT:
  642. return 8;
  643. case DATA_FORMAT_R32_UINT:
  644. case DATA_FORMAT_R32_SINT:
  645. case DATA_FORMAT_R32_SFLOAT:
  646. return 4;
  647. case DATA_FORMAT_R32G32_UINT:
  648. case DATA_FORMAT_R32G32_SINT:
  649. case DATA_FORMAT_R32G32_SFLOAT:
  650. return 8;
  651. case DATA_FORMAT_R32G32B32_UINT:
  652. case DATA_FORMAT_R32G32B32_SINT:
  653. case DATA_FORMAT_R32G32B32_SFLOAT:
  654. return 12;
  655. case DATA_FORMAT_R32G32B32A32_UINT:
  656. case DATA_FORMAT_R32G32B32A32_SINT:
  657. case DATA_FORMAT_R32G32B32A32_SFLOAT:
  658. return 16;
  659. case DATA_FORMAT_R64_UINT:
  660. case DATA_FORMAT_R64_SINT:
  661. case DATA_FORMAT_R64_SFLOAT:
  662. return 8;
  663. case DATA_FORMAT_R64G64_UINT:
  664. case DATA_FORMAT_R64G64_SINT:
  665. case DATA_FORMAT_R64G64_SFLOAT:
  666. return 16;
  667. case DATA_FORMAT_R64G64B64_UINT:
  668. case DATA_FORMAT_R64G64B64_SINT:
  669. case DATA_FORMAT_R64G64B64_SFLOAT:
  670. return 24;
  671. case DATA_FORMAT_R64G64B64A64_UINT:
  672. case DATA_FORMAT_R64G64B64A64_SINT:
  673. case DATA_FORMAT_R64G64B64A64_SFLOAT:
  674. return 32;
  675. default:
  676. return 0;
  677. }
  678. }
  679. uint32_t RenderingDeviceVulkan::get_image_format_pixel_size(DataFormat p_format) {
  680. switch (p_format) {
  681. case DATA_FORMAT_R4G4_UNORM_PACK8:
  682. return 1;
  683. case DATA_FORMAT_R4G4B4A4_UNORM_PACK16:
  684. case DATA_FORMAT_B4G4R4A4_UNORM_PACK16:
  685. case DATA_FORMAT_R5G6B5_UNORM_PACK16:
  686. case DATA_FORMAT_B5G6R5_UNORM_PACK16:
  687. case DATA_FORMAT_R5G5B5A1_UNORM_PACK16:
  688. case DATA_FORMAT_B5G5R5A1_UNORM_PACK16:
  689. case DATA_FORMAT_A1R5G5B5_UNORM_PACK16:
  690. return 2;
  691. case DATA_FORMAT_R8_UNORM:
  692. case DATA_FORMAT_R8_SNORM:
  693. case DATA_FORMAT_R8_USCALED:
  694. case DATA_FORMAT_R8_SSCALED:
  695. case DATA_FORMAT_R8_UINT:
  696. case DATA_FORMAT_R8_SINT:
  697. case DATA_FORMAT_R8_SRGB:
  698. return 1;
  699. case DATA_FORMAT_R8G8_UNORM:
  700. case DATA_FORMAT_R8G8_SNORM:
  701. case DATA_FORMAT_R8G8_USCALED:
  702. case DATA_FORMAT_R8G8_SSCALED:
  703. case DATA_FORMAT_R8G8_UINT:
  704. case DATA_FORMAT_R8G8_SINT:
  705. case DATA_FORMAT_R8G8_SRGB:
  706. return 2;
  707. case DATA_FORMAT_R8G8B8_UNORM:
  708. case DATA_FORMAT_R8G8B8_SNORM:
  709. case DATA_FORMAT_R8G8B8_USCALED:
  710. case DATA_FORMAT_R8G8B8_SSCALED:
  711. case DATA_FORMAT_R8G8B8_UINT:
  712. case DATA_FORMAT_R8G8B8_SINT:
  713. case DATA_FORMAT_R8G8B8_SRGB:
  714. case DATA_FORMAT_B8G8R8_UNORM:
  715. case DATA_FORMAT_B8G8R8_SNORM:
  716. case DATA_FORMAT_B8G8R8_USCALED:
  717. case DATA_FORMAT_B8G8R8_SSCALED:
  718. case DATA_FORMAT_B8G8R8_UINT:
  719. case DATA_FORMAT_B8G8R8_SINT:
  720. case DATA_FORMAT_B8G8R8_SRGB:
  721. return 3;
  722. case DATA_FORMAT_R8G8B8A8_UNORM:
  723. case DATA_FORMAT_R8G8B8A8_SNORM:
  724. case DATA_FORMAT_R8G8B8A8_USCALED:
  725. case DATA_FORMAT_R8G8B8A8_SSCALED:
  726. case DATA_FORMAT_R8G8B8A8_UINT:
  727. case DATA_FORMAT_R8G8B8A8_SINT:
  728. case DATA_FORMAT_R8G8B8A8_SRGB:
  729. case DATA_FORMAT_B8G8R8A8_UNORM:
  730. case DATA_FORMAT_B8G8R8A8_SNORM:
  731. case DATA_FORMAT_B8G8R8A8_USCALED:
  732. case DATA_FORMAT_B8G8R8A8_SSCALED:
  733. case DATA_FORMAT_B8G8R8A8_UINT:
  734. case DATA_FORMAT_B8G8R8A8_SINT:
  735. case DATA_FORMAT_B8G8R8A8_SRGB:
  736. return 4;
  737. case DATA_FORMAT_A8B8G8R8_UNORM_PACK32:
  738. case DATA_FORMAT_A8B8G8R8_SNORM_PACK32:
  739. case DATA_FORMAT_A8B8G8R8_USCALED_PACK32:
  740. case DATA_FORMAT_A8B8G8R8_SSCALED_PACK32:
  741. case DATA_FORMAT_A8B8G8R8_UINT_PACK32:
  742. case DATA_FORMAT_A8B8G8R8_SINT_PACK32:
  743. case DATA_FORMAT_A8B8G8R8_SRGB_PACK32:
  744. case DATA_FORMAT_A2R10G10B10_UNORM_PACK32:
  745. case DATA_FORMAT_A2R10G10B10_SNORM_PACK32:
  746. case DATA_FORMAT_A2R10G10B10_USCALED_PACK32:
  747. case DATA_FORMAT_A2R10G10B10_SSCALED_PACK32:
  748. case DATA_FORMAT_A2R10G10B10_UINT_PACK32:
  749. case DATA_FORMAT_A2R10G10B10_SINT_PACK32:
  750. case DATA_FORMAT_A2B10G10R10_UNORM_PACK32:
  751. case DATA_FORMAT_A2B10G10R10_SNORM_PACK32:
  752. case DATA_FORMAT_A2B10G10R10_USCALED_PACK32:
  753. case DATA_FORMAT_A2B10G10R10_SSCALED_PACK32:
  754. case DATA_FORMAT_A2B10G10R10_UINT_PACK32:
  755. case DATA_FORMAT_A2B10G10R10_SINT_PACK32:
  756. return 4;
  757. case DATA_FORMAT_R16_UNORM:
  758. case DATA_FORMAT_R16_SNORM:
  759. case DATA_FORMAT_R16_USCALED:
  760. case DATA_FORMAT_R16_SSCALED:
  761. case DATA_FORMAT_R16_UINT:
  762. case DATA_FORMAT_R16_SINT:
  763. case DATA_FORMAT_R16_SFLOAT:
  764. return 2;
  765. case DATA_FORMAT_R16G16_UNORM:
  766. case DATA_FORMAT_R16G16_SNORM:
  767. case DATA_FORMAT_R16G16_USCALED:
  768. case DATA_FORMAT_R16G16_SSCALED:
  769. case DATA_FORMAT_R16G16_UINT:
  770. case DATA_FORMAT_R16G16_SINT:
  771. case DATA_FORMAT_R16G16_SFLOAT:
  772. return 4;
  773. case DATA_FORMAT_R16G16B16_UNORM:
  774. case DATA_FORMAT_R16G16B16_SNORM:
  775. case DATA_FORMAT_R16G16B16_USCALED:
  776. case DATA_FORMAT_R16G16B16_SSCALED:
  777. case DATA_FORMAT_R16G16B16_UINT:
  778. case DATA_FORMAT_R16G16B16_SINT:
  779. case DATA_FORMAT_R16G16B16_SFLOAT:
  780. return 6;
  781. case DATA_FORMAT_R16G16B16A16_UNORM:
  782. case DATA_FORMAT_R16G16B16A16_SNORM:
  783. case DATA_FORMAT_R16G16B16A16_USCALED:
  784. case DATA_FORMAT_R16G16B16A16_SSCALED:
  785. case DATA_FORMAT_R16G16B16A16_UINT:
  786. case DATA_FORMAT_R16G16B16A16_SINT:
  787. case DATA_FORMAT_R16G16B16A16_SFLOAT:
  788. return 8;
  789. case DATA_FORMAT_R32_UINT:
  790. case DATA_FORMAT_R32_SINT:
  791. case DATA_FORMAT_R32_SFLOAT:
  792. return 4;
  793. case DATA_FORMAT_R32G32_UINT:
  794. case DATA_FORMAT_R32G32_SINT:
  795. case DATA_FORMAT_R32G32_SFLOAT:
  796. return 8;
  797. case DATA_FORMAT_R32G32B32_UINT:
  798. case DATA_FORMAT_R32G32B32_SINT:
  799. case DATA_FORMAT_R32G32B32_SFLOAT:
  800. return 12;
  801. case DATA_FORMAT_R32G32B32A32_UINT:
  802. case DATA_FORMAT_R32G32B32A32_SINT:
  803. case DATA_FORMAT_R32G32B32A32_SFLOAT:
  804. return 16;
  805. case DATA_FORMAT_R64_UINT:
  806. case DATA_FORMAT_R64_SINT:
  807. case DATA_FORMAT_R64_SFLOAT:
  808. return 8;
  809. case DATA_FORMAT_R64G64_UINT:
  810. case DATA_FORMAT_R64G64_SINT:
  811. case DATA_FORMAT_R64G64_SFLOAT:
  812. return 16;
  813. case DATA_FORMAT_R64G64B64_UINT:
  814. case DATA_FORMAT_R64G64B64_SINT:
  815. case DATA_FORMAT_R64G64B64_SFLOAT:
  816. return 24;
  817. case DATA_FORMAT_R64G64B64A64_UINT:
  818. case DATA_FORMAT_R64G64B64A64_SINT:
  819. case DATA_FORMAT_R64G64B64A64_SFLOAT:
  820. return 32;
  821. case DATA_FORMAT_B10G11R11_UFLOAT_PACK32:
  822. case DATA_FORMAT_E5B9G9R9_UFLOAT_PACK32:
  823. return 4;
  824. case DATA_FORMAT_D16_UNORM:
  825. return 2;
  826. case DATA_FORMAT_X8_D24_UNORM_PACK32:
  827. return 4;
  828. case DATA_FORMAT_D32_SFLOAT:
  829. return 4;
  830. case DATA_FORMAT_S8_UINT:
  831. return 1;
  832. case DATA_FORMAT_D16_UNORM_S8_UINT:
  833. return 4;
  834. case DATA_FORMAT_D24_UNORM_S8_UINT:
  835. return 4;
  836. case DATA_FORMAT_D32_SFLOAT_S8_UINT:
  837. return 5; //?
  838. case DATA_FORMAT_BC1_RGB_UNORM_BLOCK:
  839. case DATA_FORMAT_BC1_RGB_SRGB_BLOCK:
  840. case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK:
  841. case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK:
  842. case DATA_FORMAT_BC2_UNORM_BLOCK:
  843. case DATA_FORMAT_BC2_SRGB_BLOCK:
  844. case DATA_FORMAT_BC3_UNORM_BLOCK:
  845. case DATA_FORMAT_BC3_SRGB_BLOCK:
  846. case DATA_FORMAT_BC4_UNORM_BLOCK:
  847. case DATA_FORMAT_BC4_SNORM_BLOCK:
  848. case DATA_FORMAT_BC5_UNORM_BLOCK:
  849. case DATA_FORMAT_BC5_SNORM_BLOCK:
  850. case DATA_FORMAT_BC6H_UFLOAT_BLOCK:
  851. case DATA_FORMAT_BC6H_SFLOAT_BLOCK:
  852. case DATA_FORMAT_BC7_UNORM_BLOCK:
  853. case DATA_FORMAT_BC7_SRGB_BLOCK:
  854. return 1;
  855. case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
  856. case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK:
  857. case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK:
  858. case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK:
  859. case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK:
  860. case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK:
  861. return 1;
  862. case DATA_FORMAT_EAC_R11_UNORM_BLOCK:
  863. case DATA_FORMAT_EAC_R11_SNORM_BLOCK:
  864. case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK:
  865. case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK:
  866. return 1;
  867. case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK:
  868. case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK:
  869. case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK:
  870. case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK:
  871. case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK:
  872. case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK:
  873. case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK:
  874. case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK:
  875. case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK:
  876. case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK:
  877. case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK:
  878. case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK:
  879. case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK:
  880. case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK:
  881. case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK:
  882. case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK:
  883. case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK:
  884. case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK:
  885. case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK:
  886. case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK:
  887. case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK:
  888. case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK:
  889. case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK:
  890. case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK:
  891. case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK:
  892. case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK:
  893. case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK:
  894. case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK:
  895. return 1;
  896. case DATA_FORMAT_G8B8G8R8_422_UNORM:
  897. case DATA_FORMAT_B8G8R8G8_422_UNORM:
  898. return 4;
  899. case DATA_FORMAT_G8_B8_R8_3PLANE_420_UNORM:
  900. case DATA_FORMAT_G8_B8R8_2PLANE_420_UNORM:
  901. case DATA_FORMAT_G8_B8_R8_3PLANE_422_UNORM:
  902. case DATA_FORMAT_G8_B8R8_2PLANE_422_UNORM:
  903. case DATA_FORMAT_G8_B8_R8_3PLANE_444_UNORM:
  904. return 4;
  905. case DATA_FORMAT_R10X6_UNORM_PACK16:
  906. case DATA_FORMAT_R10X6G10X6_UNORM_2PACK16:
  907. case DATA_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
  908. case DATA_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16:
  909. case DATA_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16:
  910. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16:
  911. case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16:
  912. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16:
  913. case DATA_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16:
  914. case DATA_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16:
  915. case DATA_FORMAT_R12X4_UNORM_PACK16:
  916. case DATA_FORMAT_R12X4G12X4_UNORM_2PACK16:
  917. case DATA_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16:
  918. case DATA_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16:
  919. case DATA_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16:
  920. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16:
  921. case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16:
  922. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16:
  923. case DATA_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16:
  924. case DATA_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16:
  925. return 2;
  926. case DATA_FORMAT_G16B16G16R16_422_UNORM:
  927. case DATA_FORMAT_B16G16R16G16_422_UNORM:
  928. case DATA_FORMAT_G16_B16_R16_3PLANE_420_UNORM:
  929. case DATA_FORMAT_G16_B16R16_2PLANE_420_UNORM:
  930. case DATA_FORMAT_G16_B16_R16_3PLANE_422_UNORM:
  931. case DATA_FORMAT_G16_B16R16_2PLANE_422_UNORM:
  932. case DATA_FORMAT_G16_B16_R16_3PLANE_444_UNORM:
  933. return 8;
  934. default: {
  935. ERR_PRINT("Format not handled, bug");
  936. }
  937. }
  938. return 1;
  939. }
  940. // https://www.khronos.org/registry/DataFormat/specs/1.1/dataformat.1.1.pdf
  941. void RenderingDeviceVulkan::get_compressed_image_format_block_dimensions(DataFormat p_format, uint32_t &r_w, uint32_t &r_h) {
  942. switch (p_format) {
  943. case DATA_FORMAT_BC1_RGB_UNORM_BLOCK:
  944. case DATA_FORMAT_BC1_RGB_SRGB_BLOCK:
  945. case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK:
  946. case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK:
  947. case DATA_FORMAT_BC2_UNORM_BLOCK:
  948. case DATA_FORMAT_BC2_SRGB_BLOCK:
  949. case DATA_FORMAT_BC3_UNORM_BLOCK:
  950. case DATA_FORMAT_BC3_SRGB_BLOCK:
  951. case DATA_FORMAT_BC4_UNORM_BLOCK:
  952. case DATA_FORMAT_BC4_SNORM_BLOCK:
  953. case DATA_FORMAT_BC5_UNORM_BLOCK:
  954. case DATA_FORMAT_BC5_SNORM_BLOCK:
  955. case DATA_FORMAT_BC6H_UFLOAT_BLOCK:
  956. case DATA_FORMAT_BC6H_SFLOAT_BLOCK:
  957. case DATA_FORMAT_BC7_UNORM_BLOCK:
  958. case DATA_FORMAT_BC7_SRGB_BLOCK:
  959. case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
  960. case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK:
  961. case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK:
  962. case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK:
  963. case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK:
  964. case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK:
  965. case DATA_FORMAT_EAC_R11_UNORM_BLOCK:
  966. case DATA_FORMAT_EAC_R11_SNORM_BLOCK:
  967. case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK:
  968. case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK:
  969. case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: //again, not sure about astc
  970. case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK:
  971. case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK:
  972. case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK:
  973. case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK:
  974. case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK:
  975. case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK:
  976. case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK:
  977. case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK:
  978. case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK:
  979. case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK:
  980. case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK:
  981. case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK:
  982. case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK:
  983. case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK:
  984. case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK:
  985. case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK:
  986. case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK:
  987. case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK:
  988. case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK:
  989. case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK:
  990. case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK:
  991. case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK:
  992. case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK:
  993. case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK:
  994. case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK:
  995. case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK:
  996. case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK:
  997. r_w = 4;
  998. r_h = 4;
  999. return;
  1000. default: {
  1001. r_w = 1;
  1002. r_h = 1;
  1003. }
  1004. }
  1005. }
  1006. uint32_t RenderingDeviceVulkan::get_compressed_image_format_block_byte_size(DataFormat p_format) {
  1007. switch (p_format) {
  1008. case DATA_FORMAT_BC1_RGB_UNORM_BLOCK:
  1009. case DATA_FORMAT_BC1_RGB_SRGB_BLOCK:
  1010. case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK:
  1011. case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK:
  1012. return 8;
  1013. case DATA_FORMAT_BC2_UNORM_BLOCK:
  1014. case DATA_FORMAT_BC2_SRGB_BLOCK:
  1015. return 16;
  1016. case DATA_FORMAT_BC3_UNORM_BLOCK:
  1017. case DATA_FORMAT_BC3_SRGB_BLOCK:
  1018. return 16;
  1019. case DATA_FORMAT_BC4_UNORM_BLOCK:
  1020. case DATA_FORMAT_BC4_SNORM_BLOCK:
  1021. return 8;
  1022. case DATA_FORMAT_BC5_UNORM_BLOCK:
  1023. case DATA_FORMAT_BC5_SNORM_BLOCK:
  1024. return 16;
  1025. case DATA_FORMAT_BC6H_UFLOAT_BLOCK:
  1026. case DATA_FORMAT_BC6H_SFLOAT_BLOCK:
  1027. return 16;
  1028. case DATA_FORMAT_BC7_UNORM_BLOCK:
  1029. case DATA_FORMAT_BC7_SRGB_BLOCK:
  1030. return 16;
  1031. case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
  1032. case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK:
  1033. return 8;
  1034. case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK:
  1035. case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK:
  1036. return 8;
  1037. case DATA_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK:
  1038. case DATA_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK:
  1039. return 16;
  1040. case DATA_FORMAT_EAC_R11_UNORM_BLOCK:
  1041. case DATA_FORMAT_EAC_R11_SNORM_BLOCK:
  1042. return 8;
  1043. case DATA_FORMAT_EAC_R11G11_UNORM_BLOCK:
  1044. case DATA_FORMAT_EAC_R11G11_SNORM_BLOCK:
  1045. return 16;
  1046. case DATA_FORMAT_ASTC_4x4_UNORM_BLOCK: //again, not sure about astc
  1047. case DATA_FORMAT_ASTC_4x4_SRGB_BLOCK:
  1048. case DATA_FORMAT_ASTC_5x4_UNORM_BLOCK:
  1049. case DATA_FORMAT_ASTC_5x4_SRGB_BLOCK:
  1050. case DATA_FORMAT_ASTC_5x5_UNORM_BLOCK:
  1051. case DATA_FORMAT_ASTC_5x5_SRGB_BLOCK:
  1052. case DATA_FORMAT_ASTC_6x5_UNORM_BLOCK:
  1053. case DATA_FORMAT_ASTC_6x5_SRGB_BLOCK:
  1054. case DATA_FORMAT_ASTC_6x6_UNORM_BLOCK:
  1055. case DATA_FORMAT_ASTC_6x6_SRGB_BLOCK:
  1056. case DATA_FORMAT_ASTC_8x5_UNORM_BLOCK:
  1057. case DATA_FORMAT_ASTC_8x5_SRGB_BLOCK:
  1058. case DATA_FORMAT_ASTC_8x6_UNORM_BLOCK:
  1059. case DATA_FORMAT_ASTC_8x6_SRGB_BLOCK:
  1060. case DATA_FORMAT_ASTC_8x8_UNORM_BLOCK:
  1061. case DATA_FORMAT_ASTC_8x8_SRGB_BLOCK:
  1062. case DATA_FORMAT_ASTC_10x5_UNORM_BLOCK:
  1063. case DATA_FORMAT_ASTC_10x5_SRGB_BLOCK:
  1064. case DATA_FORMAT_ASTC_10x6_UNORM_BLOCK:
  1065. case DATA_FORMAT_ASTC_10x6_SRGB_BLOCK:
  1066. case DATA_FORMAT_ASTC_10x8_UNORM_BLOCK:
  1067. case DATA_FORMAT_ASTC_10x8_SRGB_BLOCK:
  1068. case DATA_FORMAT_ASTC_10x10_UNORM_BLOCK:
  1069. case DATA_FORMAT_ASTC_10x10_SRGB_BLOCK:
  1070. case DATA_FORMAT_ASTC_12x10_UNORM_BLOCK:
  1071. case DATA_FORMAT_ASTC_12x10_SRGB_BLOCK:
  1072. case DATA_FORMAT_ASTC_12x12_UNORM_BLOCK:
  1073. case DATA_FORMAT_ASTC_12x12_SRGB_BLOCK:
  1074. return 8; //wrong
  1075. default: {
  1076. }
  1077. }
  1078. return 1;
  1079. }
  1080. uint32_t RenderingDeviceVulkan::get_compressed_image_format_pixel_rshift(DataFormat p_format) {
  1081. switch (p_format) {
  1082. case DATA_FORMAT_BC1_RGB_UNORM_BLOCK: //these formats are half byte size, so rshift is 1
  1083. case DATA_FORMAT_BC1_RGB_SRGB_BLOCK:
  1084. case DATA_FORMAT_BC1_RGBA_UNORM_BLOCK:
  1085. case DATA_FORMAT_BC1_RGBA_SRGB_BLOCK:
  1086. case DATA_FORMAT_BC4_UNORM_BLOCK:
  1087. case DATA_FORMAT_BC4_SNORM_BLOCK:
  1088. case DATA_FORMAT_ETC2_R8G8B8_UNORM_BLOCK:
  1089. case DATA_FORMAT_ETC2_R8G8B8_SRGB_BLOCK:
  1090. case DATA_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK:
  1091. case DATA_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK:
  1092. case DATA_FORMAT_EAC_R11_UNORM_BLOCK:
  1093. case DATA_FORMAT_EAC_R11_SNORM_BLOCK:
  1094. return 1;
  1095. default: {
  1096. }
  1097. }
  1098. return 0;
  1099. }
  1100. bool RenderingDeviceVulkan::format_has_stencil(DataFormat p_format) {
  1101. switch (p_format) {
  1102. case DATA_FORMAT_S8_UINT:
  1103. case DATA_FORMAT_D16_UNORM_S8_UINT:
  1104. case DATA_FORMAT_D24_UNORM_S8_UINT:
  1105. case DATA_FORMAT_D32_SFLOAT_S8_UINT: {
  1106. return true;
  1107. }
  1108. default: {
  1109. }
  1110. }
  1111. return false;
  1112. }
  1113. uint32_t RenderingDeviceVulkan::get_image_format_required_size(DataFormat p_format, uint32_t p_width, uint32_t p_height, uint32_t p_depth, uint32_t p_mipmaps, uint32_t *r_blockw, uint32_t *r_blockh, uint32_t *r_depth) {
  1114. ERR_FAIL_COND_V(p_mipmaps == 0, 0);
  1115. uint32_t w = p_width;
  1116. uint32_t h = p_height;
  1117. uint32_t d = p_depth;
  1118. uint32_t size = 0;
  1119. uint32_t pixel_size = get_image_format_pixel_size(p_format);
  1120. uint32_t pixel_rshift = get_compressed_image_format_pixel_rshift(p_format);
  1121. uint32_t blockw, blockh;
  1122. get_compressed_image_format_block_dimensions(p_format, blockw, blockh);
  1123. for (uint32_t i = 0; i < p_mipmaps; i++) {
  1124. uint32_t bw = w % blockw != 0 ? w + (blockw - w % blockw) : w;
  1125. uint32_t bh = h % blockh != 0 ? h + (blockh - h % blockh) : h;
  1126. uint32_t s = bw * bh;
  1127. s *= pixel_size;
  1128. s >>= pixel_rshift;
  1129. size += s * d;
  1130. if (r_blockw) {
  1131. *r_blockw = bw;
  1132. }
  1133. if (r_blockh) {
  1134. *r_blockh = bh;
  1135. }
  1136. if (r_depth) {
  1137. *r_depth = d;
  1138. }
  1139. w = MAX(blockw, w >> 1);
  1140. h = MAX(blockh, h >> 1);
  1141. d = MAX(1, d >> 1);
  1142. }
  1143. return size;
  1144. }
  1145. uint32_t RenderingDeviceVulkan::get_image_required_mipmaps(uint32_t p_width, uint32_t p_height, uint32_t p_depth) {
  1146. //formats and block size don't really matter here since they can all go down to 1px (even if block is larger)
  1147. int w = p_width;
  1148. int h = p_height;
  1149. int d = p_depth;
  1150. int mipmaps = 1;
  1151. while (true) {
  1152. if (w == 1 && h == 1 && d == 1) {
  1153. break;
  1154. }
  1155. w = MAX(1, w >> 1);
  1156. h = MAX(1, h >> 1);
  1157. d = MAX(1, d >> 1);
  1158. mipmaps++;
  1159. }
  1160. return mipmaps;
  1161. }
  1162. ///////////////////////
  1163. const VkCompareOp RenderingDeviceVulkan::compare_operators[RenderingDevice::COMPARE_OP_MAX] = {
  1164. VK_COMPARE_OP_NEVER,
  1165. VK_COMPARE_OP_LESS,
  1166. VK_COMPARE_OP_EQUAL,
  1167. VK_COMPARE_OP_LESS_OR_EQUAL,
  1168. VK_COMPARE_OP_GREATER,
  1169. VK_COMPARE_OP_NOT_EQUAL,
  1170. VK_COMPARE_OP_GREATER_OR_EQUAL,
  1171. VK_COMPARE_OP_ALWAYS
  1172. };
  1173. const VkStencilOp RenderingDeviceVulkan::stencil_operations[RenderingDevice::STENCIL_OP_MAX] = {
  1174. VK_STENCIL_OP_KEEP,
  1175. VK_STENCIL_OP_ZERO,
  1176. VK_STENCIL_OP_REPLACE,
  1177. VK_STENCIL_OP_INCREMENT_AND_CLAMP,
  1178. VK_STENCIL_OP_DECREMENT_AND_CLAMP,
  1179. VK_STENCIL_OP_INVERT,
  1180. VK_STENCIL_OP_INCREMENT_AND_WRAP,
  1181. VK_STENCIL_OP_DECREMENT_AND_WRAP
  1182. };
  1183. const VkSampleCountFlagBits RenderingDeviceVulkan::rasterization_sample_count[RenderingDevice::TEXTURE_SAMPLES_MAX] = {
  1184. VK_SAMPLE_COUNT_1_BIT,
  1185. VK_SAMPLE_COUNT_2_BIT,
  1186. VK_SAMPLE_COUNT_4_BIT,
  1187. VK_SAMPLE_COUNT_8_BIT,
  1188. VK_SAMPLE_COUNT_16_BIT,
  1189. VK_SAMPLE_COUNT_32_BIT,
  1190. VK_SAMPLE_COUNT_64_BIT,
  1191. };
  1192. const VkLogicOp RenderingDeviceVulkan::logic_operations[RenderingDevice::LOGIC_OP_MAX] = {
  1193. VK_LOGIC_OP_CLEAR,
  1194. VK_LOGIC_OP_AND,
  1195. VK_LOGIC_OP_AND_REVERSE,
  1196. VK_LOGIC_OP_COPY,
  1197. VK_LOGIC_OP_AND_INVERTED,
  1198. VK_LOGIC_OP_NO_OP,
  1199. VK_LOGIC_OP_XOR,
  1200. VK_LOGIC_OP_OR,
  1201. VK_LOGIC_OP_NOR,
  1202. VK_LOGIC_OP_EQUIVALENT,
  1203. VK_LOGIC_OP_INVERT,
  1204. VK_LOGIC_OP_OR_REVERSE,
  1205. VK_LOGIC_OP_COPY_INVERTED,
  1206. VK_LOGIC_OP_OR_INVERTED,
  1207. VK_LOGIC_OP_NAND,
  1208. VK_LOGIC_OP_SET
  1209. };
  1210. const VkBlendFactor RenderingDeviceVulkan::blend_factors[RenderingDevice::BLEND_FACTOR_MAX] = {
  1211. VK_BLEND_FACTOR_ZERO,
  1212. VK_BLEND_FACTOR_ONE,
  1213. VK_BLEND_FACTOR_SRC_COLOR,
  1214. VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR,
  1215. VK_BLEND_FACTOR_DST_COLOR,
  1216. VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR,
  1217. VK_BLEND_FACTOR_SRC_ALPHA,
  1218. VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
  1219. VK_BLEND_FACTOR_DST_ALPHA,
  1220. VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA,
  1221. VK_BLEND_FACTOR_CONSTANT_COLOR,
  1222. VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR,
  1223. VK_BLEND_FACTOR_CONSTANT_ALPHA,
  1224. VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA,
  1225. VK_BLEND_FACTOR_SRC_ALPHA_SATURATE,
  1226. VK_BLEND_FACTOR_SRC1_COLOR,
  1227. VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR,
  1228. VK_BLEND_FACTOR_SRC1_ALPHA,
  1229. VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA
  1230. };
  1231. const VkBlendOp RenderingDeviceVulkan::blend_operations[RenderingDevice::BLEND_OP_MAX] = {
  1232. VK_BLEND_OP_ADD,
  1233. VK_BLEND_OP_SUBTRACT,
  1234. VK_BLEND_OP_REVERSE_SUBTRACT,
  1235. VK_BLEND_OP_MIN,
  1236. VK_BLEND_OP_MAX
  1237. };
  1238. const VkSamplerAddressMode RenderingDeviceVulkan::address_modes[RenderingDevice::SAMPLER_REPEAT_MODE_MAX] = {
  1239. VK_SAMPLER_ADDRESS_MODE_REPEAT,
  1240. VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT,
  1241. VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
  1242. VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
  1243. VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE
  1244. };
  1245. const VkBorderColor RenderingDeviceVulkan::sampler_border_colors[RenderingDevice::SAMPLER_BORDER_COLOR_MAX] = {
  1246. VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK,
  1247. VK_BORDER_COLOR_INT_TRANSPARENT_BLACK,
  1248. VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK,
  1249. VK_BORDER_COLOR_INT_OPAQUE_BLACK,
  1250. VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
  1251. VK_BORDER_COLOR_INT_OPAQUE_WHITE
  1252. };
  1253. const VkImageType RenderingDeviceVulkan::vulkan_image_type[RenderingDevice::TEXTURE_TYPE_MAX] = {
  1254. VK_IMAGE_TYPE_1D,
  1255. VK_IMAGE_TYPE_2D,
  1256. VK_IMAGE_TYPE_3D,
  1257. VK_IMAGE_TYPE_2D,
  1258. VK_IMAGE_TYPE_1D,
  1259. VK_IMAGE_TYPE_2D,
  1260. VK_IMAGE_TYPE_2D
  1261. };
  1262. /***************************/
  1263. /**** BUFFER MANAGEMENT ****/
  1264. /***************************/
  1265. Error RenderingDeviceVulkan::_buffer_allocate(Buffer *p_buffer, uint32_t p_size, uint32_t p_usage, VmaMemoryUsage p_mapping) {
  1266. VkBufferCreateInfo bufferInfo;
  1267. bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  1268. bufferInfo.pNext = nullptr;
  1269. bufferInfo.flags = 0;
  1270. bufferInfo.size = p_size;
  1271. bufferInfo.usage = p_usage;
  1272. bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1273. bufferInfo.queueFamilyIndexCount = 0;
  1274. bufferInfo.pQueueFamilyIndices = nullptr;
  1275. VmaAllocationCreateInfo allocInfo;
  1276. allocInfo.flags = 0;
  1277. allocInfo.usage = p_mapping;
  1278. allocInfo.requiredFlags = 0;
  1279. allocInfo.preferredFlags = 0;
  1280. allocInfo.memoryTypeBits = 0;
  1281. allocInfo.pool = nullptr;
  1282. allocInfo.pUserData = nullptr;
  1283. if (p_size <= SMALL_ALLOCATION_MAX_SIZE) {
  1284. uint32_t mem_type_index = 0;
  1285. vmaFindMemoryTypeIndexForBufferInfo(allocator, &bufferInfo, &allocInfo, &mem_type_index);
  1286. allocInfo.pool = _find_or_create_small_allocs_pool(mem_type_index);
  1287. }
  1288. VkResult err = vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &p_buffer->buffer, &p_buffer->allocation, nullptr);
  1289. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "Can't create buffer of size: " + itos(p_size) + ", error " + itos(err) + ".");
  1290. p_buffer->size = p_size;
  1291. p_buffer->buffer_info.buffer = p_buffer->buffer;
  1292. p_buffer->buffer_info.offset = 0;
  1293. p_buffer->buffer_info.range = p_size;
  1294. p_buffer->usage = p_usage;
  1295. buffer_memory += p_size;
  1296. return OK;
  1297. }
  1298. Error RenderingDeviceVulkan::_buffer_free(Buffer *p_buffer) {
  1299. ERR_FAIL_COND_V(p_buffer->size == 0, ERR_INVALID_PARAMETER);
  1300. buffer_memory -= p_buffer->size;
  1301. vmaDestroyBuffer(allocator, p_buffer->buffer, p_buffer->allocation);
  1302. p_buffer->buffer = VK_NULL_HANDLE;
  1303. p_buffer->allocation = nullptr;
  1304. p_buffer->size = 0;
  1305. return OK;
  1306. }
  1307. Error RenderingDeviceVulkan::_insert_staging_block() {
  1308. VkBufferCreateInfo bufferInfo;
  1309. bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  1310. bufferInfo.pNext = nullptr;
  1311. bufferInfo.flags = 0;
  1312. bufferInfo.size = staging_buffer_block_size;
  1313. bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  1314. bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1315. bufferInfo.queueFamilyIndexCount = 0;
  1316. bufferInfo.pQueueFamilyIndices = nullptr;
  1317. VmaAllocationCreateInfo allocInfo;
  1318. allocInfo.flags = 0;
  1319. allocInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
  1320. allocInfo.requiredFlags = 0;
  1321. allocInfo.preferredFlags = 0;
  1322. allocInfo.memoryTypeBits = 0;
  1323. allocInfo.pool = nullptr;
  1324. allocInfo.pUserData = nullptr;
  1325. StagingBufferBlock block;
  1326. VkResult err = vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &block.buffer, &block.allocation, nullptr);
  1327. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vmaCreateBuffer failed with error " + itos(err) + ".");
  1328. block.frame_used = 0;
  1329. block.fill_amount = 0;
  1330. staging_buffer_blocks.insert(staging_buffer_current, block);
  1331. return OK;
  1332. }
  1333. Error RenderingDeviceVulkan::_staging_buffer_allocate(uint32_t p_amount, uint32_t p_required_align, uint32_t &r_alloc_offset, uint32_t &r_alloc_size, bool p_can_segment, bool p_on_draw_command_buffer) {
  1334. //determine a block to use
  1335. r_alloc_size = p_amount;
  1336. while (true) {
  1337. r_alloc_offset = 0;
  1338. //see if we can use current block
  1339. if (staging_buffer_blocks[staging_buffer_current].frame_used == frames_drawn) {
  1340. //we used this block this frame, let's see if there is still room
  1341. uint32_t write_from = staging_buffer_blocks[staging_buffer_current].fill_amount;
  1342. {
  1343. uint32_t align_remainder = write_from % p_required_align;
  1344. if (align_remainder != 0) {
  1345. write_from += p_required_align - align_remainder;
  1346. }
  1347. }
  1348. int32_t available_bytes = int32_t(staging_buffer_block_size) - int32_t(write_from);
  1349. if ((int32_t)p_amount < available_bytes) {
  1350. //all is good, we should be ok, all will fit
  1351. r_alloc_offset = write_from;
  1352. } else if (p_can_segment && available_bytes >= (int32_t)p_required_align) {
  1353. //ok all won't fit but at least we can fit a chunkie
  1354. //all is good, update what needs to be written to
  1355. r_alloc_offset = write_from;
  1356. r_alloc_size = available_bytes - (available_bytes % p_required_align);
  1357. } else {
  1358. //can't fit it into this buffer.
  1359. //will need to try next buffer
  1360. staging_buffer_current = (staging_buffer_current + 1) % staging_buffer_blocks.size();
  1361. // before doing anything, though, let's check that we didn't manage to fill all blocks
  1362. // possible in a single frame
  1363. if (staging_buffer_blocks[staging_buffer_current].frame_used == frames_drawn) {
  1364. //guess we did.. ok, let's see if we can insert a new block..
  1365. if ((uint64_t)staging_buffer_blocks.size() * staging_buffer_block_size < staging_buffer_max_size) {
  1366. //we can, so we are safe
  1367. Error err = _insert_staging_block();
  1368. if (err) {
  1369. return err;
  1370. }
  1371. //claim for this frame
  1372. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1373. } else {
  1374. // Ok, worst case scenario, all the staging buffers belong to this frame
  1375. // and this frame is not even done.
  1376. // If this is the main thread, it means the user is likely loading a lot of resources at once,
  1377. // otherwise, the thread should just be blocked until the next frame (currently unimplemented)
  1378. if (false) { //separate thread from render
  1379. //block_until_next_frame()
  1380. continue;
  1381. } else {
  1382. //flush EVERYTHING including setup commands. IF not immediate, also need to flush the draw commands
  1383. _flush(true);
  1384. //clear the whole staging buffer
  1385. for (int i = 0; i < staging_buffer_blocks.size(); i++) {
  1386. staging_buffer_blocks.write[i].frame_used = 0;
  1387. staging_buffer_blocks.write[i].fill_amount = 0;
  1388. }
  1389. //claim current
  1390. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1391. }
  1392. }
  1393. } else {
  1394. //not from current frame, so continue and try again
  1395. continue;
  1396. }
  1397. }
  1398. } else if (staging_buffer_blocks[staging_buffer_current].frame_used <= frames_drawn - frame_count) {
  1399. //this is an old block, which was already processed, let's reuse
  1400. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1401. staging_buffer_blocks.write[staging_buffer_current].fill_amount = 0;
  1402. } else if (staging_buffer_blocks[staging_buffer_current].frame_used > frames_drawn - frame_count) {
  1403. //this block may still be in use, let's not touch it unless we have to, so.. can we create a new one?
  1404. if ((uint64_t)staging_buffer_blocks.size() * staging_buffer_block_size < staging_buffer_max_size) {
  1405. //we are still allowed to create a new block, so let's do that and insert it for current pos
  1406. Error err = _insert_staging_block();
  1407. if (err) {
  1408. return err;
  1409. }
  1410. //claim for this frame
  1411. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1412. } else {
  1413. // oops, we are out of room and we can't create more.
  1414. // let's flush older frames.
  1415. // The logic here is that if a game is loading a lot of data from the main thread, it will need to be stalled anyway.
  1416. // If loading from a separate thread, we can block that thread until next frame when more room is made (not currently implemented, though).
  1417. if (false) {
  1418. //separate thread from render
  1419. //block_until_next_frame()
  1420. continue; //and try again
  1421. } else {
  1422. _flush(false);
  1423. for (int i = 0; i < staging_buffer_blocks.size(); i++) {
  1424. //clear all blocks but the ones from this frame
  1425. int block_idx = (i + staging_buffer_current) % staging_buffer_blocks.size();
  1426. if (staging_buffer_blocks[block_idx].frame_used == frames_drawn) {
  1427. break; //ok, we reached something from this frame, abort
  1428. }
  1429. staging_buffer_blocks.write[block_idx].frame_used = 0;
  1430. staging_buffer_blocks.write[block_idx].fill_amount = 0;
  1431. }
  1432. //claim for current frame
  1433. staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn;
  1434. }
  1435. }
  1436. }
  1437. //all was good, break
  1438. break;
  1439. }
  1440. staging_buffer_used = true;
  1441. return OK;
  1442. }
  1443. Error RenderingDeviceVulkan::_buffer_update(Buffer *p_buffer, size_t p_offset, const uint8_t *p_data, size_t p_data_size, bool p_use_draw_command_buffer, uint32_t p_required_align) {
  1444. //submitting may get chunked for various reasons, so convert this to a task
  1445. size_t to_submit = p_data_size;
  1446. size_t submit_from = 0;
  1447. while (to_submit > 0) {
  1448. uint32_t block_write_offset;
  1449. uint32_t block_write_amount;
  1450. Error err = _staging_buffer_allocate(MIN(to_submit, staging_buffer_block_size), p_required_align, block_write_offset, block_write_amount, p_use_draw_command_buffer);
  1451. if (err) {
  1452. return err;
  1453. }
  1454. //map staging buffer (It's CPU and coherent)
  1455. void *data_ptr = nullptr;
  1456. {
  1457. VkResult vkerr = vmaMapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation, &data_ptr);
  1458. ERR_FAIL_COND_V_MSG(vkerr, ERR_CANT_CREATE, "vmaMapMemory failed with error " + itos(vkerr) + ".");
  1459. }
  1460. //copy to staging buffer
  1461. memcpy(((uint8_t *)data_ptr) + block_write_offset, p_data + submit_from, block_write_amount);
  1462. //unmap
  1463. vmaUnmapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation);
  1464. //insert a command to copy this
  1465. VkBufferCopy region;
  1466. region.srcOffset = block_write_offset;
  1467. region.dstOffset = submit_from + p_offset;
  1468. region.size = block_write_amount;
  1469. vkCmdCopyBuffer(p_use_draw_command_buffer ? frames[frame].draw_command_buffer : frames[frame].setup_command_buffer, staging_buffer_blocks[staging_buffer_current].buffer, p_buffer->buffer, 1, &region);
  1470. staging_buffer_blocks.write[staging_buffer_current].fill_amount = block_write_offset + block_write_amount;
  1471. to_submit -= block_write_amount;
  1472. submit_from += block_write_amount;
  1473. }
  1474. return OK;
  1475. }
  1476. void RenderingDeviceVulkan::_memory_barrier(VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_sccess, bool p_sync_with_draw) {
  1477. VkMemoryBarrier mem_barrier;
  1478. mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  1479. mem_barrier.pNext = nullptr;
  1480. mem_barrier.srcAccessMask = p_src_access;
  1481. mem_barrier.dstAccessMask = p_dst_sccess;
  1482. if (p_src_stage_mask == 0 || p_dst_stage_mask == 0) {
  1483. return; //no barrier, since this is invalid
  1484. }
  1485. vkCmdPipelineBarrier(p_sync_with_draw ? frames[frame].draw_command_buffer : frames[frame].setup_command_buffer, p_src_stage_mask, p_dst_stage_mask, 0, 1, &mem_barrier, 0, nullptr, 0, nullptr);
  1486. }
  1487. void RenderingDeviceVulkan::_full_barrier(bool p_sync_with_draw) {
  1488. //used for debug
  1489. _memory_barrier(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
  1490. VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  1491. VK_ACCESS_INDEX_READ_BIT |
  1492. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  1493. VK_ACCESS_UNIFORM_READ_BIT |
  1494. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  1495. VK_ACCESS_SHADER_READ_BIT |
  1496. VK_ACCESS_SHADER_WRITE_BIT |
  1497. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  1498. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  1499. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  1500. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  1501. VK_ACCESS_TRANSFER_READ_BIT |
  1502. VK_ACCESS_TRANSFER_WRITE_BIT |
  1503. VK_ACCESS_HOST_READ_BIT |
  1504. VK_ACCESS_HOST_WRITE_BIT,
  1505. VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  1506. VK_ACCESS_INDEX_READ_BIT |
  1507. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  1508. VK_ACCESS_UNIFORM_READ_BIT |
  1509. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  1510. VK_ACCESS_SHADER_READ_BIT |
  1511. VK_ACCESS_SHADER_WRITE_BIT |
  1512. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  1513. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  1514. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  1515. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  1516. VK_ACCESS_TRANSFER_READ_BIT |
  1517. VK_ACCESS_TRANSFER_WRITE_BIT |
  1518. VK_ACCESS_HOST_READ_BIT |
  1519. VK_ACCESS_HOST_WRITE_BIT,
  1520. p_sync_with_draw);
  1521. }
  1522. void RenderingDeviceVulkan::_buffer_memory_barrier(VkBuffer buffer, uint64_t p_from, uint64_t p_size, VkPipelineStageFlags p_src_stage_mask, VkPipelineStageFlags p_dst_stage_mask, VkAccessFlags p_src_access, VkAccessFlags p_dst_sccess, bool p_sync_with_draw) {
  1523. VkBufferMemoryBarrier buffer_mem_barrier;
  1524. buffer_mem_barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
  1525. buffer_mem_barrier.pNext = nullptr;
  1526. buffer_mem_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  1527. buffer_mem_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  1528. buffer_mem_barrier.srcAccessMask = p_src_access;
  1529. buffer_mem_barrier.dstAccessMask = p_dst_sccess;
  1530. buffer_mem_barrier.buffer = buffer;
  1531. buffer_mem_barrier.offset = p_from;
  1532. buffer_mem_barrier.size = p_size;
  1533. vkCmdPipelineBarrier(p_sync_with_draw ? frames[frame].draw_command_buffer : frames[frame].setup_command_buffer, p_src_stage_mask, p_dst_stage_mask, 0, 0, nullptr, 1, &buffer_mem_barrier, 0, nullptr);
  1534. }
  1535. /*****************/
  1536. /**** TEXTURE ****/
  1537. /*****************/
  1538. RID RenderingDeviceVulkan::texture_create(const TextureFormat &p_format, const TextureView &p_view, const Vector<Vector<uint8_t>> &p_data) {
  1539. _THREAD_SAFE_METHOD_
  1540. VkImageCreateInfo image_create_info;
  1541. image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  1542. image_create_info.pNext = nullptr;
  1543. image_create_info.flags = 0;
  1544. #ifndef _MSC_VER
  1545. #warning TODO check for support via RenderingDevice to enable on mobile when possible
  1546. #endif
  1547. #ifndef ANDROID_ENABLED
  1548. // vkCreateImage fails with format list on Android (VK_ERROR_OUT_OF_HOST_MEMORY)
  1549. VkImageFormatListCreateInfoKHR format_list_create_info; //keep out of the if, needed for creation
  1550. Vector<VkFormat> allowed_formats; //keep out of the if, needed for creation
  1551. #endif
  1552. if (p_format.shareable_formats.size()) {
  1553. image_create_info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
  1554. #ifndef ANDROID_ENABLED
  1555. for (int i = 0; i < p_format.shareable_formats.size(); i++) {
  1556. allowed_formats.push_back(vulkan_formats[p_format.shareable_formats[i]]);
  1557. }
  1558. format_list_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO_KHR;
  1559. format_list_create_info.pNext = nullptr;
  1560. format_list_create_info.viewFormatCount = allowed_formats.size();
  1561. format_list_create_info.pViewFormats = allowed_formats.ptr();
  1562. image_create_info.pNext = &format_list_create_info;
  1563. ERR_FAIL_COND_V_MSG(p_format.shareable_formats.find(p_format.format) == -1, RID(),
  1564. "If supplied a list of shareable formats, the current format must be present in the list");
  1565. ERR_FAIL_COND_V_MSG(p_view.format_override != DATA_FORMAT_MAX && p_format.shareable_formats.find(p_view.format_override) == -1, RID(),
  1566. "If supplied a list of shareable formats, the current view format override must be present in the list");
  1567. #endif
  1568. }
  1569. if (p_format.texture_type == TEXTURE_TYPE_CUBE || p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY) {
  1570. image_create_info.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
  1571. }
  1572. /*if (p_format.type == TEXTURE_TYPE_2D || p_format.type == TEXTURE_TYPE_2D_ARRAY) {
  1573. image_create_info.flags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT;
  1574. }*/
  1575. ERR_FAIL_INDEX_V(p_format.texture_type, TEXTURE_TYPE_MAX, RID());
  1576. image_create_info.imageType = vulkan_image_type[p_format.texture_type];
  1577. ERR_FAIL_COND_V_MSG(p_format.width < 1, RID(), "Width must be equal or greater than 1 for all textures");
  1578. image_create_info.format = vulkan_formats[p_format.format];
  1579. image_create_info.extent.width = p_format.width;
  1580. if (image_create_info.imageType == VK_IMAGE_TYPE_3D || image_create_info.imageType == VK_IMAGE_TYPE_2D) {
  1581. ERR_FAIL_COND_V_MSG(p_format.height < 1, RID(), "Height must be equal or greater than 1 for 2D and 3D textures");
  1582. image_create_info.extent.height = p_format.height;
  1583. } else {
  1584. image_create_info.extent.height = 1;
  1585. }
  1586. if (image_create_info.imageType == VK_IMAGE_TYPE_3D) {
  1587. ERR_FAIL_COND_V_MSG(p_format.depth < 1, RID(), "Depth must be equal or greater than 1 for 3D textures");
  1588. image_create_info.extent.depth = p_format.depth;
  1589. } else {
  1590. image_create_info.extent.depth = 1;
  1591. }
  1592. ERR_FAIL_COND_V(p_format.mipmaps < 1, RID());
  1593. image_create_info.mipLevels = p_format.mipmaps;
  1594. if (p_format.texture_type == TEXTURE_TYPE_1D_ARRAY || p_format.texture_type == TEXTURE_TYPE_2D_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE) {
  1595. ERR_FAIL_COND_V_MSG(p_format.array_layers < 1, RID(),
  1596. "Amount of layers must be equal or greater than 1 for arrays and cubemaps.");
  1597. ERR_FAIL_COND_V_MSG((p_format.texture_type == TEXTURE_TYPE_CUBE_ARRAY || p_format.texture_type == TEXTURE_TYPE_CUBE) && (p_format.array_layers % 6) != 0, RID(),
  1598. "Cubemap and cubemap array textures must provide a layer number that is multiple of 6");
  1599. image_create_info.arrayLayers = p_format.array_layers;
  1600. } else {
  1601. image_create_info.arrayLayers = 1;
  1602. }
  1603. ERR_FAIL_INDEX_V(p_format.samples, TEXTURE_SAMPLES_MAX, RID());
  1604. image_create_info.samples = rasterization_sample_count[p_format.samples];
  1605. image_create_info.tiling = (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) ? VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL;
  1606. //usage
  1607. image_create_info.usage = 0;
  1608. if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) {
  1609. image_create_info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
  1610. }
  1611. if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) {
  1612. image_create_info.usage |= VK_IMAGE_USAGE_STORAGE_BIT;
  1613. }
  1614. if (p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  1615. image_create_info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  1616. }
  1617. if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1618. image_create_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  1619. }
  1620. if (p_format.usage_bits & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT) {
  1621. image_create_info.usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
  1622. }
  1623. if (p_format.usage_bits & TEXTURE_USAGE_CAN_UPDATE_BIT) {
  1624. image_create_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1625. }
  1626. if (p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_FROM_BIT) {
  1627. image_create_info.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
  1628. }
  1629. if (p_format.usage_bits & TEXTURE_USAGE_CAN_COPY_TO_BIT) {
  1630. image_create_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1631. }
  1632. image_create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1633. image_create_info.queueFamilyIndexCount = 0;
  1634. image_create_info.pQueueFamilyIndices = nullptr;
  1635. image_create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  1636. uint32_t required_mipmaps = get_image_required_mipmaps(image_create_info.extent.width, image_create_info.extent.height, image_create_info.extent.depth);
  1637. ERR_FAIL_COND_V_MSG(required_mipmaps < image_create_info.mipLevels, RID(),
  1638. "Too many mipmaps requested for texture format and dimensions (" + itos(image_create_info.mipLevels) + "), maximum allowed: (" + itos(required_mipmaps) + ").");
  1639. if (p_data.size()) {
  1640. ERR_FAIL_COND_V_MSG(!(p_format.usage_bits & TEXTURE_USAGE_CAN_UPDATE_BIT), RID(),
  1641. "Texture needs the TEXTURE_USAGE_CAN_UPDATE_BIT usage flag in order to be updated at initialization or later");
  1642. int expected_images = image_create_info.arrayLayers;
  1643. ERR_FAIL_COND_V_MSG(p_data.size() != expected_images, RID(),
  1644. "Default supplied data for image format is of invalid length (" + itos(p_data.size()) + "), should be (" + itos(expected_images) + ").");
  1645. for (uint32_t i = 0; i < image_create_info.arrayLayers; i++) {
  1646. uint32_t required_size = get_image_format_required_size(p_format.format, image_create_info.extent.width, image_create_info.extent.height, image_create_info.extent.depth, image_create_info.mipLevels);
  1647. ERR_FAIL_COND_V_MSG((uint32_t)p_data[i].size() != required_size, RID(),
  1648. "Data for slice index " + itos(i) + " (mapped to layer " + itos(i) + ") differs in size (supplied: " + itos(p_data[i].size()) + ") than what is required by the format (" + itos(required_size) + ").");
  1649. }
  1650. }
  1651. {
  1652. //validate that this image is supported for the intended use
  1653. VkFormatProperties properties;
  1654. vkGetPhysicalDeviceFormatProperties(context->get_physical_device(), image_create_info.format, &properties);
  1655. VkFormatFeatureFlags flags;
  1656. String format_text = "'" + String(named_formats[p_format.format]) + "'";
  1657. if (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) {
  1658. flags = properties.linearTilingFeatures;
  1659. format_text += " (with CPU read bit)";
  1660. } else {
  1661. flags = properties.optimalTilingFeatures;
  1662. }
  1663. if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT && !(flags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) {
  1664. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as sampling texture.");
  1665. }
  1666. if (p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) {
  1667. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as color attachment.");
  1668. }
  1669. if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  1670. printf("vkformat: %x\n", image_create_info.format);
  1671. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as depth-stencil attachment.");
  1672. }
  1673. if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) {
  1674. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as storage image.");
  1675. }
  1676. if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_ATOMIC_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)) {
  1677. ERR_FAIL_V_MSG(RID(), "Format " + format_text + " does not support usage as atomic storage image.");
  1678. }
  1679. }
  1680. //some view validation
  1681. if (p_view.format_override != DATA_FORMAT_MAX) {
  1682. ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());
  1683. }
  1684. ERR_FAIL_INDEX_V(p_view.swizzle_r, TEXTURE_SWIZZLE_MAX, RID());
  1685. ERR_FAIL_INDEX_V(p_view.swizzle_g, TEXTURE_SWIZZLE_MAX, RID());
  1686. ERR_FAIL_INDEX_V(p_view.swizzle_b, TEXTURE_SWIZZLE_MAX, RID());
  1687. ERR_FAIL_INDEX_V(p_view.swizzle_a, TEXTURE_SWIZZLE_MAX, RID());
  1688. //allocate memory
  1689. uint32_t width, height;
  1690. uint32_t image_size = get_image_format_required_size(p_format.format, p_format.width, p_format.height, p_format.depth, p_format.mipmaps, &width, &height);
  1691. VmaAllocationCreateInfo allocInfo;
  1692. allocInfo.flags = 0;
  1693. allocInfo.pool = nullptr;
  1694. allocInfo.usage = p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT ? VMA_MEMORY_USAGE_CPU_ONLY : VMA_MEMORY_USAGE_GPU_ONLY;
  1695. allocInfo.requiredFlags = 0;
  1696. allocInfo.preferredFlags = 0;
  1697. allocInfo.memoryTypeBits = 0;
  1698. allocInfo.pUserData = nullptr;
  1699. if (image_size <= SMALL_ALLOCATION_MAX_SIZE) {
  1700. uint32_t mem_type_index = 0;
  1701. vmaFindMemoryTypeIndexForImageInfo(allocator, &image_create_info, &allocInfo, &mem_type_index);
  1702. allocInfo.pool = _find_or_create_small_allocs_pool(mem_type_index);
  1703. }
  1704. Texture texture;
  1705. VkResult err = vmaCreateImage(allocator, &image_create_info, &allocInfo, &texture.image, &texture.allocation, &texture.allocation_info);
  1706. ERR_FAIL_COND_V_MSG(err, RID(), "vmaCreateImage failed with error " + itos(err) + ".");
  1707. image_memory += texture.allocation_info.size;
  1708. texture.type = p_format.texture_type;
  1709. texture.format = p_format.format;
  1710. texture.width = image_create_info.extent.width;
  1711. texture.height = image_create_info.extent.height;
  1712. texture.depth = image_create_info.extent.depth;
  1713. texture.layers = image_create_info.arrayLayers;
  1714. texture.mipmaps = image_create_info.mipLevels;
  1715. texture.base_mipmap = 0;
  1716. texture.base_layer = 0;
  1717. texture.usage_flags = p_format.usage_bits;
  1718. texture.samples = p_format.samples;
  1719. texture.allowed_shared_formats = p_format.shareable_formats;
  1720. //set base layout based on usage priority
  1721. if (p_format.usage_bits & TEXTURE_USAGE_SAMPLING_BIT) {
  1722. //first priority, readable
  1723. texture.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  1724. } else if (p_format.usage_bits & TEXTURE_USAGE_STORAGE_BIT) {
  1725. //second priority, storage
  1726. texture.layout = VK_IMAGE_LAYOUT_GENERAL;
  1727. } else if (p_format.usage_bits & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  1728. //third priority, color or depth
  1729. texture.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1730. } else if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1731. texture.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1732. } else {
  1733. texture.layout = VK_IMAGE_LAYOUT_GENERAL;
  1734. }
  1735. if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1736. texture.read_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1737. texture.barrier_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1738. if (format_has_stencil(p_format.format)) {
  1739. texture.barrier_aspect_mask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  1740. }
  1741. } else {
  1742. texture.read_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT;
  1743. texture.barrier_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT;
  1744. }
  1745. texture.bound = false;
  1746. //create view
  1747. VkImageViewCreateInfo image_view_create_info;
  1748. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1749. image_view_create_info.pNext = nullptr;
  1750. image_view_create_info.flags = 0;
  1751. image_view_create_info.image = texture.image;
  1752. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  1753. VK_IMAGE_VIEW_TYPE_1D,
  1754. VK_IMAGE_VIEW_TYPE_2D,
  1755. VK_IMAGE_VIEW_TYPE_3D,
  1756. VK_IMAGE_VIEW_TYPE_CUBE,
  1757. VK_IMAGE_VIEW_TYPE_1D_ARRAY,
  1758. VK_IMAGE_VIEW_TYPE_2D_ARRAY,
  1759. VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
  1760. };
  1761. image_view_create_info.viewType = view_types[p_format.texture_type];
  1762. if (p_view.format_override == DATA_FORMAT_MAX) {
  1763. image_view_create_info.format = image_create_info.format;
  1764. } else {
  1765. image_view_create_info.format = vulkan_formats[p_view.format_override];
  1766. }
  1767. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  1768. VK_COMPONENT_SWIZZLE_IDENTITY,
  1769. VK_COMPONENT_SWIZZLE_ZERO,
  1770. VK_COMPONENT_SWIZZLE_ONE,
  1771. VK_COMPONENT_SWIZZLE_R,
  1772. VK_COMPONENT_SWIZZLE_G,
  1773. VK_COMPONENT_SWIZZLE_B,
  1774. VK_COMPONENT_SWIZZLE_A
  1775. };
  1776. image_view_create_info.components.r = component_swizzles[p_view.swizzle_r];
  1777. image_view_create_info.components.g = component_swizzles[p_view.swizzle_g];
  1778. image_view_create_info.components.b = component_swizzles[p_view.swizzle_b];
  1779. image_view_create_info.components.a = component_swizzles[p_view.swizzle_a];
  1780. image_view_create_info.subresourceRange.baseMipLevel = 0;
  1781. image_view_create_info.subresourceRange.levelCount = image_create_info.mipLevels;
  1782. image_view_create_info.subresourceRange.baseArrayLayer = 0;
  1783. image_view_create_info.subresourceRange.layerCount = image_create_info.arrayLayers;
  1784. if (p_format.usage_bits & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1785. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1786. } else {
  1787. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1788. }
  1789. err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  1790. if (err) {
  1791. vmaDestroyImage(allocator, texture.image, texture.allocation);
  1792. ERR_FAIL_V_MSG(RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  1793. }
  1794. //barrier to set layout
  1795. {
  1796. VkImageMemoryBarrier image_memory_barrier;
  1797. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  1798. image_memory_barrier.pNext = nullptr;
  1799. image_memory_barrier.srcAccessMask = 0;
  1800. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  1801. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  1802. image_memory_barrier.newLayout = texture.layout;
  1803. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  1804. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  1805. image_memory_barrier.image = texture.image;
  1806. image_memory_barrier.subresourceRange.aspectMask = texture.barrier_aspect_mask;
  1807. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  1808. image_memory_barrier.subresourceRange.levelCount = image_create_info.mipLevels;
  1809. image_memory_barrier.subresourceRange.baseArrayLayer = 0;
  1810. image_memory_barrier.subresourceRange.layerCount = image_create_info.arrayLayers;
  1811. vkCmdPipelineBarrier(frames[frame].setup_command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  1812. }
  1813. RID id = texture_owner.make_rid(texture);
  1814. if (p_data.size()) {
  1815. for (uint32_t i = 0; i < image_create_info.arrayLayers; i++) {
  1816. _texture_update(id, i, p_data[i], RD::BARRIER_MASK_ALL, true);
  1817. }
  1818. }
  1819. return id;
  1820. }
  1821. RID RenderingDeviceVulkan::texture_create_shared(const TextureView &p_view, RID p_with_texture) {
  1822. _THREAD_SAFE_METHOD_
  1823. Texture *src_texture = texture_owner.get_or_null(p_with_texture);
  1824. ERR_FAIL_COND_V(!src_texture, RID());
  1825. if (src_texture->owner.is_valid()) { //ahh this is a share
  1826. p_with_texture = src_texture->owner;
  1827. src_texture = texture_owner.get_or_null(src_texture->owner);
  1828. ERR_FAIL_COND_V(!src_texture, RID()); //this is a bug
  1829. }
  1830. //create view
  1831. Texture texture = *src_texture;
  1832. VkImageViewCreateInfo image_view_create_info;
  1833. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1834. image_view_create_info.pNext = nullptr;
  1835. image_view_create_info.flags = 0;
  1836. image_view_create_info.image = texture.image;
  1837. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  1838. VK_IMAGE_VIEW_TYPE_1D,
  1839. VK_IMAGE_VIEW_TYPE_2D,
  1840. VK_IMAGE_VIEW_TYPE_3D,
  1841. VK_IMAGE_VIEW_TYPE_CUBE,
  1842. VK_IMAGE_VIEW_TYPE_1D_ARRAY,
  1843. VK_IMAGE_VIEW_TYPE_2D_ARRAY,
  1844. VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
  1845. };
  1846. image_view_create_info.viewType = view_types[texture.type];
  1847. if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) {
  1848. image_view_create_info.format = vulkan_formats[texture.format];
  1849. } else {
  1850. ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());
  1851. ERR_FAIL_COND_V_MSG(texture.allowed_shared_formats.find(p_view.format_override) == -1, RID(),
  1852. "Format override is not in the list of allowed shareable formats for original texture.");
  1853. image_view_create_info.format = vulkan_formats[p_view.format_override];
  1854. }
  1855. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  1856. VK_COMPONENT_SWIZZLE_IDENTITY,
  1857. VK_COMPONENT_SWIZZLE_ZERO,
  1858. VK_COMPONENT_SWIZZLE_ONE,
  1859. VK_COMPONENT_SWIZZLE_R,
  1860. VK_COMPONENT_SWIZZLE_G,
  1861. VK_COMPONENT_SWIZZLE_B,
  1862. VK_COMPONENT_SWIZZLE_A
  1863. };
  1864. image_view_create_info.components.r = component_swizzles[p_view.swizzle_r];
  1865. image_view_create_info.components.g = component_swizzles[p_view.swizzle_g];
  1866. image_view_create_info.components.b = component_swizzles[p_view.swizzle_b];
  1867. image_view_create_info.components.a = component_swizzles[p_view.swizzle_a];
  1868. image_view_create_info.subresourceRange.baseMipLevel = 0;
  1869. image_view_create_info.subresourceRange.levelCount = texture.mipmaps;
  1870. image_view_create_info.subresourceRange.layerCount = texture.layers;
  1871. image_view_create_info.subresourceRange.baseArrayLayer = 0;
  1872. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1873. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1874. } else {
  1875. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1876. }
  1877. VkImageViewUsageCreateInfo usage_info;
  1878. usage_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO;
  1879. usage_info.pNext = nullptr;
  1880. if (p_view.format_override != DATA_FORMAT_MAX) {
  1881. //need to validate usage with vulkan
  1882. usage_info.usage = 0;
  1883. if (texture.usage_flags & TEXTURE_USAGE_SAMPLING_BIT) {
  1884. usage_info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
  1885. }
  1886. if (texture.usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  1887. if (texture_is_format_supported_for_usage(p_view.format_override, TEXTURE_USAGE_STORAGE_BIT)) {
  1888. usage_info.usage |= VK_IMAGE_USAGE_STORAGE_BIT;
  1889. }
  1890. }
  1891. if (texture.usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  1892. if (texture_is_format_supported_for_usage(p_view.format_override, TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) {
  1893. usage_info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  1894. }
  1895. }
  1896. if (texture.usage_flags & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT) {
  1897. usage_info.usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
  1898. }
  1899. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1900. usage_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  1901. }
  1902. if (texture.usage_flags & TEXTURE_USAGE_CAN_UPDATE_BIT) {
  1903. usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1904. }
  1905. if (texture.usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT) {
  1906. usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
  1907. }
  1908. if (texture.usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT) {
  1909. usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1910. }
  1911. image_view_create_info.pNext = &usage_info;
  1912. }
  1913. VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  1914. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  1915. texture.owner = p_with_texture;
  1916. RID id = texture_owner.make_rid(texture);
  1917. _add_dependency(id, p_with_texture);
  1918. return id;
  1919. }
  1920. RID RenderingDeviceVulkan::texture_create_from_extension(TextureType p_type, DataFormat p_format, TextureSamples p_samples, uint64_t p_flags, uint64_t p_image, uint64_t p_width, uint64_t p_height, uint64_t p_depth, uint64_t p_layers) {
  1921. _THREAD_SAFE_METHOD_
  1922. // This method creates a texture object using a VkImage created by an extension, module or other external source (OpenXR uses this).
  1923. VkImage image = (VkImage)p_image;
  1924. Texture texture;
  1925. texture.image = image;
  1926. // if we leave texture.allocation as a nullptr, would that be enough to detect we don't "own" the image?
  1927. // also leave texture.allocation_info alone
  1928. // we'll set texture.view later on
  1929. texture.type = p_type;
  1930. texture.format = p_format;
  1931. texture.samples = p_samples;
  1932. texture.width = p_width;
  1933. texture.height = p_height;
  1934. texture.depth = p_depth;
  1935. texture.layers = p_layers;
  1936. texture.mipmaps = 0; // maybe make this settable too?
  1937. texture.usage_flags = p_flags;
  1938. texture.base_mipmap = 0;
  1939. texture.base_layer = 0;
  1940. texture.allowed_shared_formats.push_back(RD::DATA_FORMAT_R8G8B8A8_UNORM);
  1941. texture.allowed_shared_formats.push_back(RD::DATA_FORMAT_R8G8B8A8_SRGB);
  1942. // Do we need to do something with texture.layout ?
  1943. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1944. texture.read_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1945. texture.barrier_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1946. // if (format_has_stencil(p_format.format)) {
  1947. // texture.barrier_aspect_mask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  1948. // }
  1949. } else {
  1950. texture.read_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT;
  1951. texture.barrier_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT;
  1952. }
  1953. // Create a view for us to use
  1954. VkImageViewCreateInfo image_view_create_info;
  1955. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1956. image_view_create_info.pNext = nullptr;
  1957. image_view_create_info.flags = 0;
  1958. image_view_create_info.image = texture.image;
  1959. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  1960. VK_IMAGE_VIEW_TYPE_1D,
  1961. VK_IMAGE_VIEW_TYPE_2D,
  1962. VK_IMAGE_VIEW_TYPE_3D,
  1963. VK_IMAGE_VIEW_TYPE_CUBE,
  1964. VK_IMAGE_VIEW_TYPE_1D_ARRAY,
  1965. VK_IMAGE_VIEW_TYPE_2D_ARRAY,
  1966. VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
  1967. };
  1968. image_view_create_info.viewType = view_types[texture.type];
  1969. image_view_create_info.format = vulkan_formats[texture.format];
  1970. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  1971. VK_COMPONENT_SWIZZLE_IDENTITY,
  1972. VK_COMPONENT_SWIZZLE_ZERO,
  1973. VK_COMPONENT_SWIZZLE_ONE,
  1974. VK_COMPONENT_SWIZZLE_R,
  1975. VK_COMPONENT_SWIZZLE_G,
  1976. VK_COMPONENT_SWIZZLE_B,
  1977. VK_COMPONENT_SWIZZLE_A
  1978. };
  1979. // hardcode for now, maybe make this settable from outside..
  1980. image_view_create_info.components.r = component_swizzles[TEXTURE_SWIZZLE_R];
  1981. image_view_create_info.components.g = component_swizzles[TEXTURE_SWIZZLE_G];
  1982. image_view_create_info.components.b = component_swizzles[TEXTURE_SWIZZLE_B];
  1983. image_view_create_info.components.a = component_swizzles[TEXTURE_SWIZZLE_A];
  1984. image_view_create_info.subresourceRange.baseMipLevel = 0;
  1985. image_view_create_info.subresourceRange.levelCount = texture.mipmaps;
  1986. image_view_create_info.subresourceRange.baseArrayLayer = 0;
  1987. image_view_create_info.subresourceRange.layerCount = texture.layers;
  1988. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1989. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1990. } else {
  1991. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1992. }
  1993. VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  1994. if (err) {
  1995. // vmaDestroyImage(allocator, texture.image, texture.allocation);
  1996. ERR_FAIL_V_MSG(RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  1997. }
  1998. //barrier to set layout
  1999. {
  2000. VkImageMemoryBarrier image_memory_barrier;
  2001. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2002. image_memory_barrier.pNext = nullptr;
  2003. image_memory_barrier.srcAccessMask = 0;
  2004. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2005. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2006. image_memory_barrier.newLayout = texture.layout;
  2007. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2008. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2009. image_memory_barrier.image = texture.image;
  2010. image_memory_barrier.subresourceRange.aspectMask = texture.barrier_aspect_mask;
  2011. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2012. image_memory_barrier.subresourceRange.levelCount = texture.mipmaps;
  2013. image_memory_barrier.subresourceRange.baseArrayLayer = 0;
  2014. image_memory_barrier.subresourceRange.layerCount = texture.layers;
  2015. vkCmdPipelineBarrier(frames[frame].setup_command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2016. }
  2017. RID id = texture_owner.make_rid(texture);
  2018. return id;
  2019. }
  2020. RID RenderingDeviceVulkan::texture_create_shared_from_slice(const TextureView &p_view, RID p_with_texture, uint32_t p_layer, uint32_t p_mipmap, uint32_t p_mipmaps, TextureSliceType p_slice_type) {
  2021. _THREAD_SAFE_METHOD_
  2022. Texture *src_texture = texture_owner.get_or_null(p_with_texture);
  2023. ERR_FAIL_COND_V(!src_texture, RID());
  2024. if (src_texture->owner.is_valid()) { //ahh this is a share
  2025. p_with_texture = src_texture->owner;
  2026. src_texture = texture_owner.get_or_null(src_texture->owner);
  2027. ERR_FAIL_COND_V(!src_texture, RID()); //this is a bug
  2028. }
  2029. ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_CUBEMAP && (src_texture->type != TEXTURE_TYPE_CUBE && src_texture->type != TEXTURE_TYPE_CUBE_ARRAY), RID(),
  2030. "Can only create a cubemap slice from a cubemap or cubemap array mipmap");
  2031. ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_3D && src_texture->type != TEXTURE_TYPE_3D, RID(),
  2032. "Can only create a 3D slice from a 3D texture");
  2033. ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_2D_ARRAY && (src_texture->type != TEXTURE_TYPE_2D_ARRAY), RID(),
  2034. "Can only create an array slice from a 2D array mipmap");
  2035. //create view
  2036. ERR_FAIL_UNSIGNED_INDEX_V(p_mipmap, src_texture->mipmaps, RID());
  2037. ERR_FAIL_COND_V(p_mipmap + p_mipmaps > src_texture->mipmaps, RID());
  2038. ERR_FAIL_UNSIGNED_INDEX_V(p_layer, src_texture->layers, RID());
  2039. int slice_layers = 1;
  2040. if (p_slice_type == TEXTURE_SLICE_2D_ARRAY) {
  2041. ERR_FAIL_COND_V_MSG(p_layer != 0, RID(), "layer must be 0 when obtaining a 2D array mipmap slice");
  2042. slice_layers = src_texture->layers;
  2043. } else if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {
  2044. slice_layers = 6;
  2045. }
  2046. Texture texture = *src_texture;
  2047. get_image_format_required_size(texture.format, texture.width, texture.height, texture.depth, p_mipmap + 1, &texture.width, &texture.height);
  2048. texture.mipmaps = p_mipmaps;
  2049. texture.layers = slice_layers;
  2050. texture.base_mipmap = p_mipmap;
  2051. texture.base_layer = p_layer;
  2052. VkImageViewCreateInfo image_view_create_info;
  2053. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  2054. image_view_create_info.pNext = nullptr;
  2055. image_view_create_info.flags = 0;
  2056. image_view_create_info.image = texture.image;
  2057. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  2058. VK_IMAGE_VIEW_TYPE_1D,
  2059. VK_IMAGE_VIEW_TYPE_2D,
  2060. VK_IMAGE_VIEW_TYPE_2D,
  2061. VK_IMAGE_VIEW_TYPE_2D,
  2062. VK_IMAGE_VIEW_TYPE_1D,
  2063. VK_IMAGE_VIEW_TYPE_2D,
  2064. VK_IMAGE_VIEW_TYPE_2D,
  2065. };
  2066. image_view_create_info.viewType = view_types[texture.type];
  2067. if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {
  2068. image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_CUBE;
  2069. } else if (p_slice_type == TEXTURE_SLICE_3D) {
  2070. image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_3D;
  2071. } else if (p_slice_type == TEXTURE_SLICE_2D_ARRAY) {
  2072. image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY;
  2073. }
  2074. if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) {
  2075. image_view_create_info.format = vulkan_formats[texture.format];
  2076. } else {
  2077. ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());
  2078. ERR_FAIL_COND_V_MSG(texture.allowed_shared_formats.find(p_view.format_override) == -1, RID(),
  2079. "Format override is not in the list of allowed shareable formats for original texture.");
  2080. image_view_create_info.format = vulkan_formats[p_view.format_override];
  2081. }
  2082. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  2083. VK_COMPONENT_SWIZZLE_IDENTITY,
  2084. VK_COMPONENT_SWIZZLE_ZERO,
  2085. VK_COMPONENT_SWIZZLE_ONE,
  2086. VK_COMPONENT_SWIZZLE_R,
  2087. VK_COMPONENT_SWIZZLE_G,
  2088. VK_COMPONENT_SWIZZLE_B,
  2089. VK_COMPONENT_SWIZZLE_A
  2090. };
  2091. image_view_create_info.components.r = component_swizzles[p_view.swizzle_r];
  2092. image_view_create_info.components.g = component_swizzles[p_view.swizzle_g];
  2093. image_view_create_info.components.b = component_swizzles[p_view.swizzle_b];
  2094. image_view_create_info.components.a = component_swizzles[p_view.swizzle_a];
  2095. if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {
  2096. ERR_FAIL_COND_V_MSG(p_layer >= src_texture->layers, RID(),
  2097. "Specified layer is invalid for cubemap");
  2098. ERR_FAIL_COND_V_MSG((p_layer % 6) != 0, RID(),
  2099. "Specified layer must be a multiple of 6.");
  2100. }
  2101. image_view_create_info.subresourceRange.baseMipLevel = p_mipmap;
  2102. image_view_create_info.subresourceRange.levelCount = p_mipmaps;
  2103. image_view_create_info.subresourceRange.layerCount = slice_layers;
  2104. image_view_create_info.subresourceRange.baseArrayLayer = p_layer;
  2105. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2106. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  2107. } else {
  2108. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2109. }
  2110. VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  2111. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  2112. texture.owner = p_with_texture;
  2113. RID id = texture_owner.make_rid(texture);
  2114. _add_dependency(id, p_with_texture);
  2115. return id;
  2116. }
  2117. Error RenderingDeviceVulkan::texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, uint32_t p_post_barrier) {
  2118. return _texture_update(p_texture, p_layer, p_data, p_post_barrier, false);
  2119. }
  2120. Error RenderingDeviceVulkan::_texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, uint32_t p_post_barrier, bool p_use_setup_queue) {
  2121. _THREAD_SAFE_METHOD_
  2122. ERR_FAIL_COND_V_MSG((draw_list || compute_list) && !p_use_setup_queue, ERR_INVALID_PARAMETER,
  2123. "Updating textures is forbidden during creation of a draw or compute list");
  2124. Texture *texture = texture_owner.get_or_null(p_texture);
  2125. ERR_FAIL_COND_V(!texture, ERR_INVALID_PARAMETER);
  2126. if (texture->owner != RID()) {
  2127. p_texture = texture->owner;
  2128. texture = texture_owner.get_or_null(texture->owner);
  2129. ERR_FAIL_COND_V(!texture, ERR_BUG); //this is a bug
  2130. }
  2131. ERR_FAIL_COND_V_MSG(texture->bound, ERR_CANT_ACQUIRE_RESOURCE,
  2132. "Texture can't be updated while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2133. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_CAN_UPDATE_BIT), ERR_INVALID_PARAMETER,
  2134. "Texture requires the TEXTURE_USAGE_CAN_UPDATE_BIT in order to be updatable.");
  2135. uint32_t layer_count = texture->layers;
  2136. if (texture->type == TEXTURE_TYPE_CUBE || texture->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2137. layer_count *= 6;
  2138. }
  2139. ERR_FAIL_COND_V(p_layer >= layer_count, ERR_INVALID_PARAMETER);
  2140. uint32_t width, height;
  2141. uint32_t image_size = get_image_format_required_size(texture->format, texture->width, texture->height, texture->depth, texture->mipmaps, &width, &height);
  2142. uint32_t required_size = image_size;
  2143. uint32_t required_align = get_compressed_image_format_block_byte_size(texture->format);
  2144. if (required_align == 1) {
  2145. required_align = get_image_format_pixel_size(texture->format);
  2146. }
  2147. if ((required_align % 4) != 0) { //alignment rules are really strange
  2148. required_align *= 4;
  2149. }
  2150. ERR_FAIL_COND_V_MSG(required_size != (uint32_t)p_data.size(), ERR_INVALID_PARAMETER,
  2151. "Required size for texture update (" + itos(required_size) + ") does not match data supplied size (" + itos(p_data.size()) + ").");
  2152. uint32_t region_size = texture_upload_region_size_px;
  2153. const uint8_t *r = p_data.ptr();
  2154. VkCommandBuffer command_buffer = p_use_setup_queue ? frames[frame].setup_command_buffer : frames[frame].draw_command_buffer;
  2155. //barrier to transfer
  2156. {
  2157. VkImageMemoryBarrier image_memory_barrier;
  2158. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2159. image_memory_barrier.pNext = nullptr;
  2160. image_memory_barrier.srcAccessMask = 0;
  2161. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2162. image_memory_barrier.oldLayout = texture->layout;
  2163. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2164. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2165. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2166. image_memory_barrier.image = texture->image;
  2167. image_memory_barrier.subresourceRange.aspectMask = texture->barrier_aspect_mask;
  2168. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2169. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  2170. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2171. image_memory_barrier.subresourceRange.layerCount = 1;
  2172. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2173. }
  2174. uint32_t mipmap_offset = 0;
  2175. uint32_t logic_width = texture->width;
  2176. uint32_t logic_height = texture->height;
  2177. for (uint32_t mm_i = 0; mm_i < texture->mipmaps; mm_i++) {
  2178. uint32_t depth;
  2179. uint32_t image_total = get_image_format_required_size(texture->format, texture->width, texture->height, texture->depth, mm_i + 1, &width, &height, &depth);
  2180. const uint8_t *read_ptr_mipmap = r + mipmap_offset;
  2181. image_size = image_total - mipmap_offset;
  2182. for (uint32_t z = 0; z < depth; z++) { //for 3D textures, depth may be > 0
  2183. const uint8_t *read_ptr = read_ptr_mipmap + image_size * z / depth;
  2184. for (uint32_t x = 0; x < width; x += region_size) {
  2185. for (uint32_t y = 0; y < height; y += region_size) {
  2186. uint32_t region_w = MIN(region_size, width - x);
  2187. uint32_t region_h = MIN(region_size, height - y);
  2188. uint32_t region_logic_w = MIN(region_size, logic_width - x);
  2189. uint32_t region_logic_h = MIN(region_size, logic_height - y);
  2190. uint32_t pixel_size = get_image_format_pixel_size(texture->format);
  2191. uint32_t to_allocate = region_w * region_h * pixel_size;
  2192. to_allocate >>= get_compressed_image_format_pixel_rshift(texture->format);
  2193. uint32_t alloc_offset, alloc_size;
  2194. Error err = _staging_buffer_allocate(to_allocate, required_align, alloc_offset, alloc_size, false, !p_use_setup_queue);
  2195. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  2196. uint8_t *write_ptr;
  2197. { //map
  2198. void *data_ptr = nullptr;
  2199. VkResult vkerr = vmaMapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation, &data_ptr);
  2200. ERR_FAIL_COND_V_MSG(vkerr, ERR_CANT_CREATE, "vmaMapMemory failed with error " + itos(vkerr) + ".");
  2201. write_ptr = (uint8_t *)data_ptr;
  2202. write_ptr += alloc_offset;
  2203. }
  2204. uint32_t block_w, block_h;
  2205. get_compressed_image_format_block_dimensions(texture->format, block_w, block_h);
  2206. ERR_FAIL_COND_V(region_w % block_w, ERR_BUG);
  2207. ERR_FAIL_COND_V(region_h % block_h, ERR_BUG);
  2208. if (block_w != 1 || block_h != 1) {
  2209. //compressed image (blocks)
  2210. //must copy a block region
  2211. uint32_t block_size = get_compressed_image_format_block_byte_size(texture->format);
  2212. //re-create current variables in blocky format
  2213. uint32_t xb = x / block_w;
  2214. uint32_t yb = y / block_h;
  2215. uint32_t wb = width / block_w;
  2216. //uint32_t hb = height / block_h;
  2217. uint32_t region_wb = region_w / block_w;
  2218. uint32_t region_hb = region_h / block_h;
  2219. for (uint32_t xr = 0; xr < region_wb; xr++) {
  2220. for (uint32_t yr = 0; yr < region_hb; yr++) {
  2221. uint32_t src_offset = ((yr + yb) * wb + xr + xb) * block_size;
  2222. uint32_t dst_offset = (yr * region_wb + xr) * block_size;
  2223. //copy block
  2224. for (uint32_t i = 0; i < block_size; i++) {
  2225. write_ptr[dst_offset + i] = read_ptr[src_offset + i];
  2226. }
  2227. }
  2228. }
  2229. } else {
  2230. //regular image (pixels)
  2231. //must copy a pixel region
  2232. for (uint32_t xr = 0; xr < region_w; xr++) {
  2233. for (uint32_t yr = 0; yr < region_h; yr++) {
  2234. uint32_t src_offset = ((yr + y) * width + xr + x) * pixel_size;
  2235. uint32_t dst_offset = (yr * region_w + xr) * pixel_size;
  2236. //copy block
  2237. for (uint32_t i = 0; i < pixel_size; i++) {
  2238. write_ptr[dst_offset + i] = read_ptr[src_offset + i];
  2239. }
  2240. }
  2241. }
  2242. }
  2243. { //unmap
  2244. vmaUnmapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation);
  2245. }
  2246. VkBufferImageCopy buffer_image_copy;
  2247. buffer_image_copy.bufferOffset = alloc_offset;
  2248. buffer_image_copy.bufferRowLength = 0; //tightly packed
  2249. buffer_image_copy.bufferImageHeight = 0; //tightly packed
  2250. buffer_image_copy.imageSubresource.aspectMask = texture->read_aspect_mask;
  2251. buffer_image_copy.imageSubresource.mipLevel = mm_i;
  2252. buffer_image_copy.imageSubresource.baseArrayLayer = p_layer;
  2253. buffer_image_copy.imageSubresource.layerCount = 1;
  2254. buffer_image_copy.imageOffset.x = x;
  2255. buffer_image_copy.imageOffset.y = y;
  2256. buffer_image_copy.imageOffset.z = z;
  2257. buffer_image_copy.imageExtent.width = region_logic_w;
  2258. buffer_image_copy.imageExtent.height = region_logic_h;
  2259. buffer_image_copy.imageExtent.depth = 1;
  2260. vkCmdCopyBufferToImage(command_buffer, staging_buffer_blocks[staging_buffer_current].buffer, texture->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_image_copy);
  2261. staging_buffer_blocks.write[staging_buffer_current].fill_amount += alloc_size;
  2262. }
  2263. }
  2264. }
  2265. mipmap_offset = image_total;
  2266. logic_width = MAX(1, logic_width >> 1);
  2267. logic_height = MAX(1, logic_height >> 1);
  2268. }
  2269. //barrier to restore layout
  2270. {
  2271. uint32_t barrier_flags = 0;
  2272. uint32_t access_flags = 0;
  2273. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2274. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2275. access_flags |= VK_ACCESS_SHADER_READ_BIT;
  2276. }
  2277. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2278. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2279. access_flags |= VK_ACCESS_SHADER_READ_BIT;
  2280. }
  2281. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2282. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2283. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2284. }
  2285. if (barrier_flags == 0) {
  2286. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2287. }
  2288. VkImageMemoryBarrier image_memory_barrier;
  2289. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2290. image_memory_barrier.pNext = nullptr;
  2291. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2292. image_memory_barrier.dstAccessMask = access_flags;
  2293. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2294. image_memory_barrier.newLayout = texture->layout;
  2295. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2296. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2297. image_memory_barrier.image = texture->image;
  2298. image_memory_barrier.subresourceRange.aspectMask = texture->barrier_aspect_mask;
  2299. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2300. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  2301. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2302. image_memory_barrier.subresourceRange.layerCount = 1;
  2303. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2304. }
  2305. if (texture->used_in_frame != frames_drawn) {
  2306. texture->used_in_raster = false;
  2307. texture->used_in_compute = false;
  2308. texture->used_in_frame = frames_drawn;
  2309. }
  2310. texture->used_in_transfer = true;
  2311. return OK;
  2312. }
  2313. Vector<uint8_t> RenderingDeviceVulkan::_texture_get_data_from_image(Texture *tex, VkImage p_image, VmaAllocation p_allocation, uint32_t p_layer, bool p_2d) {
  2314. uint32_t width, height, depth;
  2315. uint32_t image_size = get_image_format_required_size(tex->format, tex->width, tex->height, p_2d ? 1 : tex->depth, tex->mipmaps, &width, &height, &depth);
  2316. Vector<uint8_t> image_data;
  2317. image_data.resize(image_size);
  2318. void *img_mem;
  2319. vmaMapMemory(allocator, p_allocation, &img_mem);
  2320. uint32_t blockw, blockh;
  2321. get_compressed_image_format_block_dimensions(tex->format, blockw, blockh);
  2322. uint32_t block_size = get_compressed_image_format_block_byte_size(tex->format);
  2323. uint32_t pixel_size = get_image_format_pixel_size(tex->format);
  2324. {
  2325. uint8_t *w = image_data.ptrw();
  2326. uint32_t mipmap_offset = 0;
  2327. for (uint32_t mm_i = 0; mm_i < tex->mipmaps; mm_i++) {
  2328. uint32_t image_total = get_image_format_required_size(tex->format, tex->width, tex->height, p_2d ? 1 : tex->depth, mm_i + 1, &width, &height, &depth);
  2329. uint8_t *write_ptr_mipmap = w + mipmap_offset;
  2330. image_size = image_total - mipmap_offset;
  2331. VkImageSubresource image_sub_resorce;
  2332. image_sub_resorce.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2333. image_sub_resorce.arrayLayer = p_layer;
  2334. image_sub_resorce.mipLevel = mm_i;
  2335. VkSubresourceLayout layout;
  2336. vkGetImageSubresourceLayout(device, p_image, &image_sub_resorce, &layout);
  2337. for (uint32_t z = 0; z < depth; z++) {
  2338. uint8_t *write_ptr = write_ptr_mipmap + z * image_size / depth;
  2339. const uint8_t *slice_read_ptr = ((uint8_t *)img_mem) + layout.offset + z * layout.depthPitch;
  2340. if (block_size > 1) {
  2341. //compressed
  2342. uint32_t line_width = (block_size * (width / blockw));
  2343. for (uint32_t y = 0; y < height / blockh; y++) {
  2344. const uint8_t *rptr = slice_read_ptr + y * layout.rowPitch;
  2345. uint8_t *wptr = write_ptr + y * line_width;
  2346. memcpy(wptr, rptr, line_width);
  2347. }
  2348. } else {
  2349. //uncompressed
  2350. for (uint32_t y = 0; y < height; y++) {
  2351. const uint8_t *rptr = slice_read_ptr + y * layout.rowPitch;
  2352. uint8_t *wptr = write_ptr + y * pixel_size * width;
  2353. memcpy(wptr, rptr, (uint64_t)pixel_size * width);
  2354. }
  2355. }
  2356. }
  2357. mipmap_offset = image_total;
  2358. }
  2359. }
  2360. vmaUnmapMemory(allocator, p_allocation);
  2361. return image_data;
  2362. }
  2363. Vector<uint8_t> RenderingDeviceVulkan::texture_get_data(RID p_texture, uint32_t p_layer) {
  2364. _THREAD_SAFE_METHOD_
  2365. Texture *tex = texture_owner.get_or_null(p_texture);
  2366. ERR_FAIL_COND_V(!tex, Vector<uint8_t>());
  2367. ERR_FAIL_COND_V_MSG(tex->bound, Vector<uint8_t>(),
  2368. "Texture can't be retrieved while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2369. ERR_FAIL_COND_V_MSG(!(tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), Vector<uint8_t>(),
  2370. "Texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved.");
  2371. uint32_t layer_count = tex->layers;
  2372. if (tex->type == TEXTURE_TYPE_CUBE || tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2373. layer_count *= 6;
  2374. }
  2375. ERR_FAIL_COND_V(p_layer >= layer_count, Vector<uint8_t>());
  2376. if (tex->usage_flags & TEXTURE_USAGE_CPU_READ_BIT) {
  2377. //does not need anything fancy, map and read.
  2378. return _texture_get_data_from_image(tex, tex->image, tex->allocation, p_layer);
  2379. } else {
  2380. //compute total image size
  2381. uint32_t width, height, depth;
  2382. uint32_t buffer_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, tex->mipmaps, &width, &height, &depth);
  2383. //allocate buffer
  2384. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer; //makes more sense to retrieve
  2385. Buffer tmp_buffer;
  2386. _buffer_allocate(&tmp_buffer, buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_CPU_ONLY);
  2387. { //Source image barrier
  2388. VkImageMemoryBarrier image_memory_barrier;
  2389. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2390. image_memory_barrier.pNext = nullptr;
  2391. image_memory_barrier.srcAccessMask = 0;
  2392. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2393. image_memory_barrier.oldLayout = tex->layout;
  2394. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2395. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2396. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2397. image_memory_barrier.image = tex->image;
  2398. image_memory_barrier.subresourceRange.aspectMask = tex->barrier_aspect_mask;
  2399. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2400. image_memory_barrier.subresourceRange.levelCount = tex->mipmaps;
  2401. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2402. image_memory_barrier.subresourceRange.layerCount = 1;
  2403. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2404. }
  2405. uint32_t computed_w = tex->width;
  2406. uint32_t computed_h = tex->height;
  2407. uint32_t computed_d = tex->depth;
  2408. uint32_t prev_size = 0;
  2409. uint32_t offset = 0;
  2410. for (uint32_t i = 0; i < tex->mipmaps; i++) {
  2411. VkBufferImageCopy buffer_image_copy;
  2412. uint32_t image_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, i + 1);
  2413. uint32_t size = image_size - prev_size;
  2414. prev_size = image_size;
  2415. buffer_image_copy.bufferOffset = offset;
  2416. buffer_image_copy.bufferImageHeight = 0;
  2417. buffer_image_copy.bufferRowLength = 0;
  2418. buffer_image_copy.imageSubresource.aspectMask = tex->read_aspect_mask;
  2419. buffer_image_copy.imageSubresource.baseArrayLayer = p_layer;
  2420. buffer_image_copy.imageSubresource.layerCount = 1;
  2421. buffer_image_copy.imageSubresource.mipLevel = i;
  2422. buffer_image_copy.imageOffset.x = 0;
  2423. buffer_image_copy.imageOffset.y = 0;
  2424. buffer_image_copy.imageOffset.z = 0;
  2425. buffer_image_copy.imageExtent.width = computed_w;
  2426. buffer_image_copy.imageExtent.height = computed_h;
  2427. buffer_image_copy.imageExtent.depth = computed_d;
  2428. vkCmdCopyImageToBuffer(command_buffer, tex->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, tmp_buffer.buffer, 1, &buffer_image_copy);
  2429. computed_w = MAX(1, computed_w >> 1);
  2430. computed_h = MAX(1, computed_h >> 1);
  2431. computed_d = MAX(1, computed_d >> 1);
  2432. offset += size;
  2433. }
  2434. { //restore src
  2435. VkImageMemoryBarrier image_memory_barrier;
  2436. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2437. image_memory_barrier.pNext = nullptr;
  2438. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2439. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2440. if (tex->usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  2441. image_memory_barrier.dstAccessMask |= VK_ACCESS_SHADER_WRITE_BIT;
  2442. }
  2443. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2444. image_memory_barrier.newLayout = tex->layout;
  2445. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2446. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2447. image_memory_barrier.image = tex->image;
  2448. image_memory_barrier.subresourceRange.aspectMask = tex->barrier_aspect_mask;
  2449. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2450. image_memory_barrier.subresourceRange.levelCount = tex->mipmaps;
  2451. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2452. image_memory_barrier.subresourceRange.layerCount = 1;
  2453. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2454. }
  2455. _flush(true);
  2456. void *buffer_mem;
  2457. VkResult vkerr = vmaMapMemory(allocator, tmp_buffer.allocation, &buffer_mem);
  2458. ERR_FAIL_COND_V_MSG(vkerr, Vector<uint8_t>(), "vmaMapMemory failed with error " + itos(vkerr) + ".");
  2459. Vector<uint8_t> buffer_data;
  2460. {
  2461. buffer_data.resize(buffer_size);
  2462. uint8_t *w = buffer_data.ptrw();
  2463. memcpy(w, buffer_mem, buffer_size);
  2464. }
  2465. vmaUnmapMemory(allocator, tmp_buffer.allocation);
  2466. _buffer_free(&tmp_buffer);
  2467. return buffer_data;
  2468. }
  2469. }
  2470. bool RenderingDeviceVulkan::texture_is_shared(RID p_texture) {
  2471. _THREAD_SAFE_METHOD_
  2472. Texture *tex = texture_owner.get_or_null(p_texture);
  2473. ERR_FAIL_COND_V(!tex, false);
  2474. return tex->owner.is_valid();
  2475. }
  2476. bool RenderingDeviceVulkan::texture_is_valid(RID p_texture) {
  2477. return texture_owner.owns(p_texture);
  2478. }
  2479. Size2i RenderingDeviceVulkan::texture_size(RID p_texture) {
  2480. _THREAD_SAFE_METHOD_
  2481. Texture *tex = texture_owner.get_or_null(p_texture);
  2482. ERR_FAIL_COND_V(!tex, Size2i());
  2483. return Size2i(tex->width, tex->height);
  2484. }
  2485. Error RenderingDeviceVulkan::texture_copy(RID p_from_texture, RID p_to_texture, const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_size, uint32_t p_src_mipmap, uint32_t p_dst_mipmap, uint32_t p_src_layer, uint32_t p_dst_layer, uint32_t p_post_barrier) {
  2486. _THREAD_SAFE_METHOD_
  2487. Texture *src_tex = texture_owner.get_or_null(p_from_texture);
  2488. ERR_FAIL_COND_V(!src_tex, ERR_INVALID_PARAMETER);
  2489. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  2490. "Source texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2491. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER,
  2492. "Source texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved.");
  2493. uint32_t src_layer_count = src_tex->layers;
  2494. uint32_t src_width, src_height, src_depth;
  2495. get_image_format_required_size(src_tex->format, src_tex->width, src_tex->height, src_tex->depth, p_src_mipmap + 1, &src_width, &src_height, &src_depth);
  2496. if (src_tex->type == TEXTURE_TYPE_CUBE || src_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2497. src_layer_count *= 6;
  2498. }
  2499. ERR_FAIL_COND_V(p_from.x < 0 || p_from.x + p_size.x > src_width, ERR_INVALID_PARAMETER);
  2500. ERR_FAIL_COND_V(p_from.y < 0 || p_from.y + p_size.y > src_height, ERR_INVALID_PARAMETER);
  2501. ERR_FAIL_COND_V(p_from.z < 0 || p_from.z + p_size.z > src_depth, ERR_INVALID_PARAMETER);
  2502. ERR_FAIL_COND_V(p_src_mipmap >= src_tex->mipmaps, ERR_INVALID_PARAMETER);
  2503. ERR_FAIL_COND_V(p_src_layer >= src_layer_count, ERR_INVALID_PARAMETER);
  2504. Texture *dst_tex = texture_owner.get_or_null(p_to_texture);
  2505. ERR_FAIL_COND_V(!dst_tex, ERR_INVALID_PARAMETER);
  2506. ERR_FAIL_COND_V_MSG(dst_tex->bound, ERR_INVALID_PARAMETER,
  2507. "Destination texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2508. ERR_FAIL_COND_V_MSG(!(dst_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  2509. "Destination texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be retrieved.");
  2510. uint32_t dst_layer_count = dst_tex->layers;
  2511. uint32_t dst_width, dst_height, dst_depth;
  2512. get_image_format_required_size(dst_tex->format, dst_tex->width, dst_tex->height, dst_tex->depth, p_dst_mipmap + 1, &dst_width, &dst_height, &dst_depth);
  2513. if (dst_tex->type == TEXTURE_TYPE_CUBE || dst_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2514. dst_layer_count *= 6;
  2515. }
  2516. ERR_FAIL_COND_V(p_to.x < 0 || p_to.x + p_size.x > dst_width, ERR_INVALID_PARAMETER);
  2517. ERR_FAIL_COND_V(p_to.y < 0 || p_to.y + p_size.y > dst_height, ERR_INVALID_PARAMETER);
  2518. ERR_FAIL_COND_V(p_to.z < 0 || p_to.z + p_size.z > dst_depth, ERR_INVALID_PARAMETER);
  2519. ERR_FAIL_COND_V(p_dst_mipmap >= dst_tex->mipmaps, ERR_INVALID_PARAMETER);
  2520. ERR_FAIL_COND_V(p_dst_layer >= dst_layer_count, ERR_INVALID_PARAMETER);
  2521. ERR_FAIL_COND_V_MSG(src_tex->read_aspect_mask != dst_tex->read_aspect_mask, ERR_INVALID_PARAMETER,
  2522. "Source and destination texture must be of the same type (color or depth).");
  2523. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  2524. {
  2525. //PRE Copy the image
  2526. { //Source
  2527. VkImageMemoryBarrier image_memory_barrier;
  2528. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2529. image_memory_barrier.pNext = nullptr;
  2530. image_memory_barrier.srcAccessMask = 0;
  2531. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2532. image_memory_barrier.oldLayout = src_tex->layout;
  2533. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2534. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2535. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2536. image_memory_barrier.image = src_tex->image;
  2537. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2538. image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap;
  2539. image_memory_barrier.subresourceRange.levelCount = 1;
  2540. image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer;
  2541. image_memory_barrier.subresourceRange.layerCount = 1;
  2542. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2543. }
  2544. { //Dest
  2545. VkImageMemoryBarrier image_memory_barrier;
  2546. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2547. image_memory_barrier.pNext = nullptr;
  2548. image_memory_barrier.srcAccessMask = 0;
  2549. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2550. image_memory_barrier.oldLayout = dst_tex->layout;
  2551. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2552. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2553. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2554. image_memory_barrier.image = dst_tex->image;
  2555. image_memory_barrier.subresourceRange.aspectMask = dst_tex->read_aspect_mask;
  2556. image_memory_barrier.subresourceRange.baseMipLevel = p_dst_mipmap;
  2557. image_memory_barrier.subresourceRange.levelCount = 1;
  2558. image_memory_barrier.subresourceRange.baseArrayLayer = p_dst_layer;
  2559. image_memory_barrier.subresourceRange.layerCount = 1;
  2560. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2561. }
  2562. //COPY
  2563. {
  2564. VkImageCopy image_copy_region;
  2565. image_copy_region.srcSubresource.aspectMask = src_tex->read_aspect_mask;
  2566. image_copy_region.srcSubresource.baseArrayLayer = p_src_layer;
  2567. image_copy_region.srcSubresource.layerCount = 1;
  2568. image_copy_region.srcSubresource.mipLevel = p_src_mipmap;
  2569. image_copy_region.srcOffset.x = p_from.x;
  2570. image_copy_region.srcOffset.y = p_from.y;
  2571. image_copy_region.srcOffset.z = p_from.z;
  2572. image_copy_region.dstSubresource.aspectMask = dst_tex->read_aspect_mask;
  2573. image_copy_region.dstSubresource.baseArrayLayer = p_dst_layer;
  2574. image_copy_region.dstSubresource.layerCount = 1;
  2575. image_copy_region.dstSubresource.mipLevel = p_dst_mipmap;
  2576. image_copy_region.dstOffset.x = p_to.x;
  2577. image_copy_region.dstOffset.y = p_to.y;
  2578. image_copy_region.dstOffset.z = p_to.z;
  2579. image_copy_region.extent.width = p_size.x;
  2580. image_copy_region.extent.height = p_size.y;
  2581. image_copy_region.extent.depth = p_size.z;
  2582. vkCmdCopyImage(command_buffer, src_tex->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst_tex->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy_region);
  2583. }
  2584. // RESTORE LAYOUT for SRC and DST
  2585. uint32_t barrier_flags = 0;
  2586. uint32_t access_flags = 0;
  2587. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2588. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2589. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2590. }
  2591. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2592. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2593. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2594. }
  2595. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2596. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2597. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2598. }
  2599. if (barrier_flags == 0) {
  2600. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2601. }
  2602. { //restore src
  2603. VkImageMemoryBarrier image_memory_barrier;
  2604. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2605. image_memory_barrier.pNext = nullptr;
  2606. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2607. image_memory_barrier.dstAccessMask = access_flags;
  2608. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2609. image_memory_barrier.newLayout = src_tex->layout;
  2610. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2611. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2612. image_memory_barrier.image = src_tex->image;
  2613. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2614. image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap;
  2615. image_memory_barrier.subresourceRange.levelCount = src_tex->mipmaps;
  2616. image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer;
  2617. image_memory_barrier.subresourceRange.layerCount = 1;
  2618. vkCmdPipelineBarrier(command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2619. }
  2620. { //make dst readable
  2621. VkImageMemoryBarrier image_memory_barrier;
  2622. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2623. image_memory_barrier.pNext = nullptr;
  2624. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2625. image_memory_barrier.dstAccessMask = access_flags;
  2626. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2627. image_memory_barrier.newLayout = dst_tex->layout;
  2628. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2629. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2630. image_memory_barrier.image = dst_tex->image;
  2631. image_memory_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2632. image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap;
  2633. image_memory_barrier.subresourceRange.levelCount = 1;
  2634. image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer;
  2635. image_memory_barrier.subresourceRange.layerCount = 1;
  2636. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2637. }
  2638. }
  2639. return OK;
  2640. }
  2641. Error RenderingDeviceVulkan::texture_resolve_multisample(RID p_from_texture, RID p_to_texture, uint32_t p_post_barrier) {
  2642. _THREAD_SAFE_METHOD_
  2643. Texture *src_tex = texture_owner.get_or_null(p_from_texture);
  2644. ERR_FAIL_COND_V(!src_tex, ERR_INVALID_PARAMETER);
  2645. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  2646. "Source texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2647. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER,
  2648. "Source texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved.");
  2649. ERR_FAIL_COND_V_MSG(src_tex->type != TEXTURE_TYPE_2D, ERR_INVALID_PARAMETER, "Source texture must be 2D (or a slice of a 3D/Cube texture)");
  2650. ERR_FAIL_COND_V_MSG(src_tex->samples == TEXTURE_SAMPLES_1, ERR_INVALID_PARAMETER, "Source texture must be multisampled.");
  2651. Texture *dst_tex = texture_owner.get_or_null(p_to_texture);
  2652. ERR_FAIL_COND_V(!dst_tex, ERR_INVALID_PARAMETER);
  2653. ERR_FAIL_COND_V_MSG(dst_tex->bound, ERR_INVALID_PARAMETER,
  2654. "Destination texture can't be copied while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2655. ERR_FAIL_COND_V_MSG(!(dst_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  2656. "Destination texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be retrieved.");
  2657. ERR_FAIL_COND_V_MSG(dst_tex->type != TEXTURE_TYPE_2D, ERR_INVALID_PARAMETER, "Destination texture must be 2D (or a slice of a 3D/Cube texture).");
  2658. ERR_FAIL_COND_V_MSG(dst_tex->samples != TEXTURE_SAMPLES_1, ERR_INVALID_PARAMETER, "Destination texture must not be multisampled.");
  2659. ERR_FAIL_COND_V_MSG(src_tex->format != dst_tex->format, ERR_INVALID_PARAMETER, "Source and Destination textures must be the same format.");
  2660. ERR_FAIL_COND_V_MSG(src_tex->width != dst_tex->width && src_tex->height != dst_tex->height && src_tex->depth != dst_tex->depth, ERR_INVALID_PARAMETER, "Source and Destination textures must have the same dimensions.");
  2661. ERR_FAIL_COND_V_MSG(src_tex->read_aspect_mask != dst_tex->read_aspect_mask, ERR_INVALID_PARAMETER,
  2662. "Source and destination texture must be of the same type (color or depth).");
  2663. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  2664. {
  2665. //PRE Copy the image
  2666. { //Source
  2667. VkImageMemoryBarrier image_memory_barrier;
  2668. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2669. image_memory_barrier.pNext = nullptr;
  2670. image_memory_barrier.srcAccessMask = 0;
  2671. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2672. image_memory_barrier.oldLayout = src_tex->layout;
  2673. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2674. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2675. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2676. image_memory_barrier.image = src_tex->image;
  2677. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2678. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap;
  2679. image_memory_barrier.subresourceRange.levelCount = 1;
  2680. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer;
  2681. image_memory_barrier.subresourceRange.layerCount = 1;
  2682. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2683. }
  2684. { //Dest
  2685. VkImageMemoryBarrier image_memory_barrier;
  2686. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2687. image_memory_barrier.pNext = nullptr;
  2688. image_memory_barrier.srcAccessMask = 0;
  2689. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2690. image_memory_barrier.oldLayout = dst_tex->layout;
  2691. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2692. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2693. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2694. image_memory_barrier.image = dst_tex->image;
  2695. image_memory_barrier.subresourceRange.aspectMask = dst_tex->read_aspect_mask;
  2696. image_memory_barrier.subresourceRange.baseMipLevel = dst_tex->base_mipmap;
  2697. image_memory_barrier.subresourceRange.levelCount = 1;
  2698. image_memory_barrier.subresourceRange.baseArrayLayer = dst_tex->base_layer;
  2699. image_memory_barrier.subresourceRange.layerCount = 1;
  2700. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2701. }
  2702. //COPY
  2703. {
  2704. VkImageResolve image_copy_region;
  2705. image_copy_region.srcSubresource.aspectMask = src_tex->read_aspect_mask;
  2706. image_copy_region.srcSubresource.baseArrayLayer = src_tex->base_layer;
  2707. image_copy_region.srcSubresource.layerCount = 1;
  2708. image_copy_region.srcSubresource.mipLevel = src_tex->base_mipmap;
  2709. image_copy_region.srcOffset.x = 0;
  2710. image_copy_region.srcOffset.y = 0;
  2711. image_copy_region.srcOffset.z = 0;
  2712. image_copy_region.dstSubresource.aspectMask = dst_tex->read_aspect_mask;
  2713. image_copy_region.dstSubresource.baseArrayLayer = dst_tex->base_layer;
  2714. image_copy_region.dstSubresource.layerCount = 1;
  2715. image_copy_region.dstSubresource.mipLevel = dst_tex->base_mipmap;
  2716. image_copy_region.dstOffset.x = 0;
  2717. image_copy_region.dstOffset.y = 0;
  2718. image_copy_region.dstOffset.z = 0;
  2719. image_copy_region.extent.width = src_tex->width;
  2720. image_copy_region.extent.height = src_tex->height;
  2721. image_copy_region.extent.depth = src_tex->depth;
  2722. vkCmdResolveImage(command_buffer, src_tex->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst_tex->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy_region);
  2723. }
  2724. // RESTORE LAYOUT for SRC and DST
  2725. uint32_t barrier_flags = 0;
  2726. uint32_t access_flags = 0;
  2727. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2728. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2729. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2730. }
  2731. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2732. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2733. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2734. }
  2735. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2736. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2737. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2738. }
  2739. if (barrier_flags == 0) {
  2740. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2741. }
  2742. { //restore src
  2743. VkImageMemoryBarrier image_memory_barrier;
  2744. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2745. image_memory_barrier.pNext = nullptr;
  2746. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2747. image_memory_barrier.dstAccessMask = access_flags;
  2748. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2749. image_memory_barrier.newLayout = src_tex->layout;
  2750. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2751. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2752. image_memory_barrier.image = src_tex->image;
  2753. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2754. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap;
  2755. image_memory_barrier.subresourceRange.levelCount = 1;
  2756. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer;
  2757. image_memory_barrier.subresourceRange.layerCount = 1;
  2758. vkCmdPipelineBarrier(command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2759. }
  2760. { //make dst readable
  2761. VkImageMemoryBarrier image_memory_barrier;
  2762. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2763. image_memory_barrier.pNext = nullptr;
  2764. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2765. image_memory_barrier.dstAccessMask = access_flags;
  2766. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2767. image_memory_barrier.newLayout = dst_tex->layout;
  2768. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2769. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2770. image_memory_barrier.image = dst_tex->image;
  2771. image_memory_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2772. image_memory_barrier.subresourceRange.baseMipLevel = dst_tex->base_mipmap;
  2773. image_memory_barrier.subresourceRange.levelCount = 1;
  2774. image_memory_barrier.subresourceRange.baseArrayLayer = dst_tex->base_layer;
  2775. image_memory_barrier.subresourceRange.layerCount = 1;
  2776. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2777. }
  2778. }
  2779. return OK;
  2780. }
  2781. Error RenderingDeviceVulkan::texture_clear(RID p_texture, const Color &p_color, uint32_t p_base_mipmap, uint32_t p_mipmaps, uint32_t p_base_layer, uint32_t p_layers, uint32_t p_post_barrier) {
  2782. _THREAD_SAFE_METHOD_
  2783. Texture *src_tex = texture_owner.get_or_null(p_texture);
  2784. ERR_FAIL_COND_V(!src_tex, ERR_INVALID_PARAMETER);
  2785. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  2786. "Source texture can't be cleared while a render pass that uses it is being created. Ensure render pass is finalized (and that it was created with RENDER_PASS_CONTENTS_FINISH) to unbind this texture.");
  2787. ERR_FAIL_COND_V(p_layers == 0, ERR_INVALID_PARAMETER);
  2788. ERR_FAIL_COND_V(p_mipmaps == 0, ERR_INVALID_PARAMETER);
  2789. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  2790. "Source texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be cleared.");
  2791. uint32_t src_layer_count = src_tex->layers;
  2792. if (src_tex->type == TEXTURE_TYPE_CUBE || src_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2793. src_layer_count *= 6;
  2794. }
  2795. ERR_FAIL_COND_V(p_base_mipmap + p_mipmaps > src_tex->mipmaps, ERR_INVALID_PARAMETER);
  2796. ERR_FAIL_COND_V(p_base_layer + p_layers > src_layer_count, ERR_INVALID_PARAMETER);
  2797. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  2798. VkImageLayout clear_layout = (src_tex->layout == VK_IMAGE_LAYOUT_GENERAL) ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2799. // NOTE: Perhaps the valid stages/accesses for a given owner should be a property of the owner. (Here and places like _get_buffer_from_owner)
  2800. const VkPipelineStageFlags valid_texture_stages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2801. constexpr VkAccessFlags read_access = VK_ACCESS_SHADER_READ_BIT;
  2802. constexpr VkAccessFlags read_write_access = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2803. const VkAccessFlags valid_texture_access = (src_tex->usage_flags & TEXTURE_USAGE_STORAGE_BIT) ? read_write_access : read_access;
  2804. { // Barrier from previous access with optional layout change (see clear_layout logic above)
  2805. VkImageMemoryBarrier image_memory_barrier;
  2806. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2807. image_memory_barrier.pNext = nullptr;
  2808. image_memory_barrier.srcAccessMask = valid_texture_access;
  2809. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2810. image_memory_barrier.oldLayout = src_tex->layout;
  2811. image_memory_barrier.newLayout = clear_layout;
  2812. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2813. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2814. image_memory_barrier.image = src_tex->image;
  2815. image_memory_barrier.subresourceRange.aspectMask = src_tex->read_aspect_mask;
  2816. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap + p_base_mipmap;
  2817. image_memory_barrier.subresourceRange.levelCount = p_mipmaps;
  2818. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer + p_base_layer;
  2819. image_memory_barrier.subresourceRange.layerCount = p_layers;
  2820. vkCmdPipelineBarrier(command_buffer, valid_texture_stages, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2821. }
  2822. VkClearColorValue clear_color;
  2823. clear_color.float32[0] = p_color.r;
  2824. clear_color.float32[1] = p_color.g;
  2825. clear_color.float32[2] = p_color.b;
  2826. clear_color.float32[3] = p_color.a;
  2827. VkImageSubresourceRange range;
  2828. range.aspectMask = src_tex->read_aspect_mask;
  2829. range.baseArrayLayer = src_tex->base_layer + p_base_layer;
  2830. range.layerCount = p_layers;
  2831. range.baseMipLevel = src_tex->base_mipmap + p_base_mipmap;
  2832. range.levelCount = p_mipmaps;
  2833. vkCmdClearColorImage(command_buffer, src_tex->image, clear_layout, &clear_color, 1, &range);
  2834. { // Barrier to post clear accesses (changing back the layout if needed)
  2835. uint32_t barrier_flags = 0;
  2836. uint32_t access_flags = 0;
  2837. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2838. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2839. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2840. }
  2841. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2842. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2843. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2844. }
  2845. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2846. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2847. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2848. }
  2849. if (barrier_flags == 0) {
  2850. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2851. }
  2852. VkImageMemoryBarrier image_memory_barrier;
  2853. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2854. image_memory_barrier.pNext = nullptr;
  2855. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2856. image_memory_barrier.dstAccessMask = access_flags;
  2857. image_memory_barrier.oldLayout = clear_layout;
  2858. image_memory_barrier.newLayout = src_tex->layout;
  2859. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2860. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2861. image_memory_barrier.image = src_tex->image;
  2862. image_memory_barrier.subresourceRange.aspectMask = src_tex->read_aspect_mask;
  2863. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap + p_base_mipmap;
  2864. image_memory_barrier.subresourceRange.levelCount = p_mipmaps;
  2865. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer + p_base_layer;
  2866. image_memory_barrier.subresourceRange.layerCount = p_layers;
  2867. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2868. }
  2869. if (src_tex->used_in_frame != frames_drawn) {
  2870. src_tex->used_in_raster = false;
  2871. src_tex->used_in_compute = false;
  2872. src_tex->used_in_frame = frames_drawn;
  2873. }
  2874. src_tex->used_in_transfer = true;
  2875. return OK;
  2876. }
  2877. bool RenderingDeviceVulkan::texture_is_format_supported_for_usage(DataFormat p_format, uint32_t p_usage) const {
  2878. ERR_FAIL_INDEX_V(p_format, DATA_FORMAT_MAX, false);
  2879. _THREAD_SAFE_METHOD_
  2880. //validate that this image is supported for the intended use
  2881. VkFormatProperties properties;
  2882. vkGetPhysicalDeviceFormatProperties(context->get_physical_device(), vulkan_formats[p_format], &properties);
  2883. VkFormatFeatureFlags flags;
  2884. if (p_usage & TEXTURE_USAGE_CPU_READ_BIT) {
  2885. flags = properties.linearTilingFeatures;
  2886. } else {
  2887. flags = properties.optimalTilingFeatures;
  2888. }
  2889. if (p_usage & TEXTURE_USAGE_SAMPLING_BIT && !(flags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) {
  2890. return false;
  2891. }
  2892. if (p_usage & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) {
  2893. return false;
  2894. }
  2895. if (p_usage & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  2896. return false;
  2897. }
  2898. if (p_usage & TEXTURE_USAGE_STORAGE_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) {
  2899. return false;
  2900. }
  2901. if (p_usage & TEXTURE_USAGE_STORAGE_ATOMIC_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)) {
  2902. return false;
  2903. }
  2904. return true;
  2905. }
  2906. /********************/
  2907. /**** ATTACHMENT ****/
  2908. /********************/
  2909. VkRenderPass RenderingDeviceVulkan::_render_pass_create(const Vector<AttachmentFormat> &p_attachments, const Vector<FramebufferPass> &p_passes, InitialAction p_initial_action, FinalAction p_final_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, uint32_t p_view_count, Vector<TextureSamples> *r_samples) {
  2910. // Set up dependencies from/to external equivalent to the default (implicit) one, and then amend them
  2911. const VkPipelineStageFlags default_access_mask = VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  2912. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  2913. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  2914. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  2915. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; // From Section 7.1 of Vulkan API Spec v1.1.148
  2916. VkPipelineStageFlags reading_stages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT;
  2917. VkSubpassDependency dependencies[2] = { { VK_SUBPASS_EXTERNAL, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, default_access_mask, 0 },
  2918. { 0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, default_access_mask, 0, 0 } };
  2919. VkSubpassDependency &dependency_from_external = dependencies[0];
  2920. VkSubpassDependency &dependency_to_external = dependencies[1];
  2921. LocalVector<int32_t> attachment_last_pass;
  2922. attachment_last_pass.resize(p_attachments.size());
  2923. Vector<VkAttachmentDescription> attachments;
  2924. for (int i = 0; i < p_attachments.size(); i++) {
  2925. ERR_FAIL_INDEX_V(p_attachments[i].format, DATA_FORMAT_MAX, VK_NULL_HANDLE);
  2926. ERR_FAIL_INDEX_V(p_attachments[i].samples, TEXTURE_SAMPLES_MAX, VK_NULL_HANDLE);
  2927. ERR_FAIL_COND_V_MSG(!(p_attachments[i].usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT)),
  2928. VK_NULL_HANDLE, "Texture format for index (" + itos(i) + ") requires an attachment (color, depth, input or stencil) bit set.");
  2929. VkAttachmentDescription description = {};
  2930. description.flags = 0;
  2931. description.format = vulkan_formats[p_attachments[i].format];
  2932. description.samples = rasterization_sample_count[p_attachments[i].samples];
  2933. bool is_sampled = p_attachments[i].usage_flags & TEXTURE_USAGE_SAMPLING_BIT;
  2934. bool is_storage = p_attachments[i].usage_flags & TEXTURE_USAGE_STORAGE_BIT;
  2935. bool is_depth = p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  2936. // For each UNDEFINED, assume the prior use was a *read*, as we'd be discarding the output of a write
  2937. // Also, each UNDEFINED will do an immediate layout transition (write), s.t. we must ensure execution synchronization vs.
  2938. // the read. If this is a performance issue, one could track the actual last accessor of each resource, adding only that
  2939. // stage
  2940. switch (is_depth ? p_initial_depth_action : p_initial_action) {
  2941. case INITIAL_ACTION_CLEAR_REGION:
  2942. case INITIAL_ACTION_CLEAR: {
  2943. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2944. description.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  2945. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  2946. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2947. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2948. description.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  2949. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  2950. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  2951. dependency_from_external.srcStageMask |= reading_stages;
  2952. } else {
  2953. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2954. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2955. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2956. dependency_from_external.srcStageMask |= reading_stages;
  2957. }
  2958. } break;
  2959. case INITIAL_ACTION_KEEP: {
  2960. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2961. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2962. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  2963. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2964. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2965. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2966. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  2967. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2968. dependency_from_external.srcStageMask |= reading_stages;
  2969. } else {
  2970. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2971. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2972. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2973. dependency_from_external.srcStageMask |= reading_stages;
  2974. }
  2975. } break;
  2976. case INITIAL_ACTION_DROP: {
  2977. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2978. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2979. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  2980. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2981. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2982. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2983. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2984. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2985. dependency_from_external.srcStageMask |= reading_stages;
  2986. } else {
  2987. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2988. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2989. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2990. dependency_from_external.srcStageMask |= reading_stages;
  2991. }
  2992. } break;
  2993. case INITIAL_ACTION_CLEAR_REGION_CONTINUE:
  2994. case INITIAL_ACTION_CONTINUE: {
  2995. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2996. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2997. description.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  2998. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2999. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3000. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3001. description.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  3002. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3003. } else {
  3004. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3005. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3006. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  3007. dependency_from_external.srcStageMask |= reading_stages;
  3008. }
  3009. } break;
  3010. default: {
  3011. ERR_FAIL_V(VK_NULL_HANDLE); //should never reach here
  3012. }
  3013. }
  3014. bool used_last = false;
  3015. {
  3016. int last_pass = p_passes.size() - 1;
  3017. if (is_depth) {
  3018. //likely missing depth resolve?
  3019. if (p_passes[last_pass].depth_attachment == i) {
  3020. used_last = true;
  3021. }
  3022. } else {
  3023. if (p_passes[last_pass].resolve_attachments.size()) {
  3024. //if using resolve attachments, check resolve attachments
  3025. for (int j = 0; j < p_passes[last_pass].resolve_attachments.size(); j++) {
  3026. if (p_passes[last_pass].resolve_attachments[j] == i) {
  3027. used_last = true;
  3028. break;
  3029. }
  3030. }
  3031. } else {
  3032. for (int j = 0; j < p_passes[last_pass].color_attachments.size(); j++) {
  3033. if (p_passes[last_pass].color_attachments[j] == i) {
  3034. used_last = true;
  3035. break;
  3036. }
  3037. }
  3038. }
  3039. }
  3040. if (!used_last) {
  3041. for (int j = 0; j < p_passes[last_pass].preserve_attachments.size(); j++) {
  3042. if (p_passes[last_pass].preserve_attachments[j] == i) {
  3043. used_last = true;
  3044. break;
  3045. }
  3046. }
  3047. }
  3048. }
  3049. FinalAction final_action = p_final_action;
  3050. FinalAction final_depth_action = p_final_depth_action;
  3051. if (!used_last) {
  3052. if (is_depth) {
  3053. final_depth_action = FINAL_ACTION_DISCARD;
  3054. } else {
  3055. final_action = FINAL_ACTION_DISCARD;
  3056. }
  3057. }
  3058. switch (is_depth ? final_depth_action : final_action) {
  3059. case FINAL_ACTION_READ: {
  3060. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3061. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3062. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3063. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  3064. update_external_dependency_for_store(dependency_to_external, is_sampled, is_storage, false);
  3065. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3066. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3067. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
  3068. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  3069. update_external_dependency_for_store(dependency_to_external, is_sampled, is_storage, true);
  3070. } else {
  3071. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3072. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3073. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  3074. // TODO: What does this mean about the next usage (and thus appropriate dependency masks
  3075. }
  3076. } break;
  3077. case FINAL_ACTION_DISCARD: {
  3078. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3079. description.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3080. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3081. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  3082. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3083. description.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3084. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3085. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  3086. } else {
  3087. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3088. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3089. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  3090. }
  3091. } break;
  3092. case FINAL_ACTION_CONTINUE: {
  3093. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3094. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3095. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3096. description.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  3097. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3098. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3099. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
  3100. description.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  3101. } else {
  3102. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3103. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3104. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  3105. }
  3106. } break;
  3107. default: {
  3108. ERR_FAIL_V(VK_NULL_HANDLE); //should never reach here
  3109. }
  3110. }
  3111. attachment_last_pass[i] = -1;
  3112. attachments.push_back(description);
  3113. }
  3114. LocalVector<VkSubpassDescription> subpasses;
  3115. LocalVector<LocalVector<VkAttachmentReference>> color_reference_array;
  3116. LocalVector<LocalVector<VkAttachmentReference>> input_reference_array;
  3117. LocalVector<LocalVector<VkAttachmentReference>> resolve_reference_array;
  3118. LocalVector<LocalVector<uint32_t>> preserve_reference_array;
  3119. LocalVector<VkAttachmentReference> depth_reference_array;
  3120. subpasses.resize(p_passes.size());
  3121. color_reference_array.resize(p_passes.size());
  3122. input_reference_array.resize(p_passes.size());
  3123. resolve_reference_array.resize(p_passes.size());
  3124. preserve_reference_array.resize(p_passes.size());
  3125. depth_reference_array.resize(p_passes.size());
  3126. LocalVector<VkSubpassDependency> subpass_dependencies;
  3127. for (int i = 0; i < p_passes.size(); i++) {
  3128. const FramebufferPass *pass = &p_passes[i];
  3129. LocalVector<VkAttachmentReference> &color_references = color_reference_array[i];
  3130. TextureSamples texture_samples = TEXTURE_SAMPLES_1;
  3131. bool is_multisample_first = true;
  3132. for (int j = 0; j < pass->color_attachments.size(); j++) {
  3133. int32_t attachment = pass->color_attachments[j];
  3134. VkAttachmentReference reference;
  3135. if (attachment == FramebufferPass::ATTACHMENT_UNUSED) {
  3136. reference.attachment = VK_ATTACHMENT_UNUSED;
  3137. reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3138. } else {
  3139. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), color attachment (" + itos(j) + ").");
  3140. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not usable as color attachment.");
  3141. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  3142. if (is_multisample_first) {
  3143. texture_samples = p_attachments[attachment].samples;
  3144. is_multisample_first = false;
  3145. } else {
  3146. ERR_FAIL_COND_V_MSG(texture_samples != p_attachments[attachment].samples, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), if an attachment is marked as multisample, all of them should be multisample and use the same number of samples.");
  3147. }
  3148. reference.attachment = attachment;
  3149. reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  3150. attachment_last_pass[attachment] = i;
  3151. }
  3152. color_references.push_back(reference);
  3153. }
  3154. LocalVector<VkAttachmentReference> &input_references = input_reference_array[i];
  3155. for (int j = 0; j < pass->input_attachments.size(); j++) {
  3156. int32_t attachment = pass->input_attachments[j];
  3157. VkAttachmentReference reference;
  3158. if (attachment == FramebufferPass::ATTACHMENT_UNUSED) {
  3159. reference.attachment = VK_ATTACHMENT_UNUSED;
  3160. reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3161. } else {
  3162. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), input attachment (" + itos(j) + ").");
  3163. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it isn't marked as an input texture.");
  3164. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  3165. reference.attachment = attachment;
  3166. reference.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  3167. attachment_last_pass[attachment] = i;
  3168. }
  3169. input_references.push_back(reference);
  3170. }
  3171. LocalVector<VkAttachmentReference> &resolve_references = resolve_reference_array[i];
  3172. if (pass->resolve_attachments.size() > 0) {
  3173. ERR_FAIL_COND_V_MSG(pass->resolve_attachments.size() != pass->color_attachments.size(), VK_NULL_HANDLE, "The amount of resolve attachments (" + itos(pass->resolve_attachments.size()) + ") must match the number of color attachments (" + itos(pass->color_attachments.size()) + ").");
  3174. ERR_FAIL_COND_V_MSG(texture_samples == TEXTURE_SAMPLES_1, VK_NULL_HANDLE, "Resolve attachments specified, but color attachments are not multisample.");
  3175. }
  3176. for (int j = 0; j < pass->resolve_attachments.size(); j++) {
  3177. int32_t attachment = pass->resolve_attachments[j];
  3178. VkAttachmentReference reference;
  3179. if (attachment == FramebufferPass::ATTACHMENT_UNUSED) {
  3180. reference.attachment = VK_ATTACHMENT_UNUSED;
  3181. reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3182. } else {
  3183. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + ").");
  3184. ERR_FAIL_COND_V_MSG(pass->color_attachments[j] == FramebufferPass::ATTACHMENT_UNUSED, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment (" + itos(j) + "), the respective color attachment is marked as unused.");
  3185. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachment, it isn't marked as a color texture.");
  3186. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  3187. bool multisample = p_attachments[attachment].samples > TEXTURE_SAMPLES_1;
  3188. ERR_FAIL_COND_V_MSG(multisample, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), resolve attachments can't be multisample.");
  3189. reference.attachment = attachment;
  3190. reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  3191. attachment_last_pass[attachment] = i;
  3192. }
  3193. resolve_references.push_back(reference);
  3194. }
  3195. VkAttachmentReference &depth_stencil_reference = depth_reference_array[i];
  3196. if (pass->depth_attachment != FramebufferPass::ATTACHMENT_UNUSED) {
  3197. int32_t attachment = pass->depth_attachment;
  3198. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), depth attachment.");
  3199. ERR_FAIL_COND_V_MSG(!(p_attachments[attachment].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT), VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it's marked as depth, but it's not a depth attachment.");
  3200. ERR_FAIL_COND_V_MSG(attachment_last_pass[attachment] == i, VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), it already was used for something else before in this pass.");
  3201. depth_stencil_reference.attachment = attachment;
  3202. depth_stencil_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  3203. attachment_last_pass[attachment] = i;
  3204. if (is_multisample_first) {
  3205. texture_samples = p_attachments[attachment].samples;
  3206. is_multisample_first = false;
  3207. } else {
  3208. ERR_FAIL_COND_V_MSG(texture_samples != p_attachments[attachment].samples, VK_NULL_HANDLE, "Invalid framebuffer depth format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), if an attachment is marked as multisample, all of them should be multisample and use the same number of samples including the depth.");
  3209. }
  3210. } else {
  3211. depth_stencil_reference.attachment = VK_ATTACHMENT_UNUSED;
  3212. depth_stencil_reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3213. }
  3214. LocalVector<uint32_t> &preserve_references = preserve_reference_array[i];
  3215. for (int j = 0; j < pass->preserve_attachments.size(); j++) {
  3216. int32_t attachment = pass->preserve_attachments[j];
  3217. ERR_FAIL_COND_V_MSG(attachment == FramebufferPass::ATTACHMENT_UNUSED, VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + "). Preserve attachments can't be unused.");
  3218. ERR_FAIL_INDEX_V_MSG(attachment, p_attachments.size(), VK_NULL_HANDLE, "Invalid framebuffer format attachment(" + itos(attachment) + "), in pass (" + itos(i) + "), preserve attachment (" + itos(j) + ").");
  3219. if (attachment_last_pass[attachment] != i) {
  3220. //preserve can still be used to keep depth or color from being discarded after use
  3221. attachment_last_pass[attachment] = i;
  3222. preserve_references.push_back(attachment);
  3223. }
  3224. }
  3225. VkSubpassDescription &subpass = subpasses[i];
  3226. subpass.flags = 0;
  3227. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  3228. subpass.inputAttachmentCount = input_references.size();
  3229. if (input_references.size()) {
  3230. subpass.pInputAttachments = input_references.ptr();
  3231. } else {
  3232. subpass.pInputAttachments = nullptr;
  3233. }
  3234. subpass.colorAttachmentCount = color_references.size();
  3235. if (color_references.size()) {
  3236. subpass.pColorAttachments = color_references.ptr();
  3237. } else {
  3238. subpass.pColorAttachments = nullptr;
  3239. }
  3240. if (depth_stencil_reference.attachment != VK_ATTACHMENT_UNUSED) {
  3241. subpass.pDepthStencilAttachment = &depth_stencil_reference;
  3242. } else {
  3243. subpass.pDepthStencilAttachment = nullptr;
  3244. }
  3245. if (resolve_references.size()) {
  3246. subpass.pResolveAttachments = resolve_references.ptr();
  3247. } else {
  3248. subpass.pResolveAttachments = nullptr;
  3249. }
  3250. subpass.preserveAttachmentCount = preserve_references.size();
  3251. if (preserve_references.size()) {
  3252. subpass.pPreserveAttachments = preserve_references.ptr();
  3253. } else {
  3254. subpass.pPreserveAttachments = nullptr;
  3255. }
  3256. if (r_samples) {
  3257. r_samples->push_back(texture_samples);
  3258. }
  3259. if (i > 0) {
  3260. VkSubpassDependency dependency;
  3261. dependency.srcSubpass = i - 1;
  3262. dependency.dstSubpass = i;
  3263. dependency.srcStageMask = 0;
  3264. dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  3265. dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  3266. dependency.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  3267. dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
  3268. dependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
  3269. subpass_dependencies.push_back(dependency);
  3270. }
  3271. /*
  3272. // NOTE: Big Mallet Approach -- any layout transition causes a full barrier
  3273. if (reference.layout != description.initialLayout) {
  3274. // NOTE: this should be smarter based on the texture's knowledge of its previous role
  3275. dependency_from_external.srcStageMask |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
  3276. dependency_from_external.srcAccessMask |= VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
  3277. }
  3278. if (reference.layout != description.finalLayout) {
  3279. // NOTE: this should be smarter based on the texture's knowledge of its subsequent role
  3280. dependency_to_external.dstStageMask |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
  3281. dependency_to_external.dstAccessMask |= VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
  3282. }
  3283. */
  3284. }
  3285. VkRenderPassCreateInfo render_pass_create_info;
  3286. render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  3287. render_pass_create_info.pNext = nullptr;
  3288. render_pass_create_info.flags = 0;
  3289. render_pass_create_info.attachmentCount = attachments.size();
  3290. render_pass_create_info.pAttachments = attachments.ptr();
  3291. render_pass_create_info.subpassCount = subpasses.size();
  3292. render_pass_create_info.pSubpasses = subpasses.ptr();
  3293. // Commenting this because it seems it just avoids raster and compute to work at the same time.
  3294. // Other barriers seem to be protecting the render pass fine.
  3295. // render_pass_create_info.dependencyCount = 2;
  3296. // render_pass_create_info.pDependencies = dependencies;
  3297. render_pass_create_info.dependencyCount = subpass_dependencies.size();
  3298. if (subpass_dependencies.size()) {
  3299. render_pass_create_info.pDependencies = subpass_dependencies.ptr();
  3300. } else {
  3301. render_pass_create_info.pDependencies = nullptr;
  3302. }
  3303. // These are only used if we use multiview but we need to define them in scope.
  3304. const uint32_t view_mask = (1 << p_view_count) - 1;
  3305. const uint32_t correlation_mask = (1 << p_view_count) - 1;
  3306. Vector<uint32_t> view_masks;
  3307. VkRenderPassMultiviewCreateInfo render_pass_multiview_create_info;
  3308. if (p_view_count > 1) {
  3309. const VulkanContext::MultiviewCapabilities capabilities = context->get_multiview_capabilities();
  3310. // For now this only works with multiview!
  3311. ERR_FAIL_COND_V_MSG(!capabilities.is_supported, VK_NULL_HANDLE, "Multiview not supported");
  3312. // Make sure we limit this to the number of views we support.
  3313. ERR_FAIL_COND_V_MSG(p_view_count > capabilities.max_view_count, VK_NULL_HANDLE, "Hardware does not support requested number of views for Multiview render pass");
  3314. // Set view masks for each subpass
  3315. for (uint32_t i = 0; i < subpasses.size(); i++) {
  3316. view_masks.push_back(view_mask);
  3317. }
  3318. render_pass_multiview_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO;
  3319. render_pass_multiview_create_info.pNext = nullptr;
  3320. render_pass_multiview_create_info.subpassCount = subpasses.size();
  3321. render_pass_multiview_create_info.pViewMasks = view_masks.ptr();
  3322. render_pass_multiview_create_info.dependencyCount = 0;
  3323. render_pass_multiview_create_info.pViewOffsets = nullptr;
  3324. render_pass_multiview_create_info.correlationMaskCount = 1;
  3325. render_pass_multiview_create_info.pCorrelationMasks = &correlation_mask;
  3326. render_pass_create_info.pNext = &render_pass_multiview_create_info;
  3327. }
  3328. VkRenderPass render_pass;
  3329. VkResult res = vkCreateRenderPass(device, &render_pass_create_info, nullptr, &render_pass);
  3330. ERR_FAIL_COND_V_MSG(res, VK_NULL_HANDLE, "vkCreateRenderPass failed with error " + itos(res) + ".");
  3331. return render_pass;
  3332. }
  3333. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create(const Vector<AttachmentFormat> &p_format, uint32_t p_view_count) {
  3334. FramebufferPass pass;
  3335. for (int i = 0; i < p_format.size(); i++) {
  3336. if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3337. pass.depth_attachment = i;
  3338. } else {
  3339. pass.color_attachments.push_back(i);
  3340. }
  3341. }
  3342. Vector<FramebufferPass> passes;
  3343. passes.push_back(pass);
  3344. return framebuffer_format_create_multipass(p_format, passes, p_view_count);
  3345. }
  3346. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create_multipass(const Vector<AttachmentFormat> &p_attachments, Vector<FramebufferPass> &p_passes, uint32_t p_view_count) {
  3347. _THREAD_SAFE_METHOD_
  3348. FramebufferFormatKey key;
  3349. key.attachments = p_attachments;
  3350. key.passes = p_passes;
  3351. key.view_count = p_view_count;
  3352. const Map<FramebufferFormatKey, FramebufferFormatID>::Element *E = framebuffer_format_cache.find(key);
  3353. if (E) {
  3354. //exists, return
  3355. return E->get();
  3356. }
  3357. Vector<TextureSamples> samples;
  3358. VkRenderPass render_pass = _render_pass_create(p_attachments, p_passes, INITIAL_ACTION_CLEAR, FINAL_ACTION_READ, INITIAL_ACTION_CLEAR, FINAL_ACTION_READ, p_view_count, &samples); //actions don't matter for this use case
  3359. if (render_pass == VK_NULL_HANDLE) { //was likely invalid
  3360. return INVALID_ID;
  3361. }
  3362. FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT));
  3363. E = framebuffer_format_cache.insert(key, id);
  3364. FramebufferFormat fb_format;
  3365. fb_format.E = E;
  3366. fb_format.render_pass = render_pass;
  3367. fb_format.pass_samples = samples;
  3368. fb_format.view_count = p_view_count;
  3369. framebuffer_formats[id] = fb_format;
  3370. return id;
  3371. }
  3372. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create_empty(TextureSamples p_samples) {
  3373. FramebufferFormatKey key;
  3374. key.passes.push_back(FramebufferPass());
  3375. const Map<FramebufferFormatKey, FramebufferFormatID>::Element *E = framebuffer_format_cache.find(key);
  3376. if (E) {
  3377. //exists, return
  3378. return E->get();
  3379. }
  3380. VkSubpassDescription subpass;
  3381. subpass.flags = 0;
  3382. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  3383. subpass.inputAttachmentCount = 0; //unsupported for now
  3384. subpass.pInputAttachments = nullptr;
  3385. subpass.colorAttachmentCount = 0;
  3386. subpass.pColorAttachments = nullptr;
  3387. subpass.pDepthStencilAttachment = nullptr;
  3388. subpass.pResolveAttachments = nullptr;
  3389. subpass.preserveAttachmentCount = 0;
  3390. subpass.pPreserveAttachments = nullptr;
  3391. VkRenderPassCreateInfo render_pass_create_info;
  3392. render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  3393. render_pass_create_info.pNext = nullptr;
  3394. render_pass_create_info.flags = 0;
  3395. render_pass_create_info.attachmentCount = 0;
  3396. render_pass_create_info.pAttachments = nullptr;
  3397. render_pass_create_info.subpassCount = 1;
  3398. render_pass_create_info.pSubpasses = &subpass;
  3399. render_pass_create_info.dependencyCount = 0;
  3400. render_pass_create_info.pDependencies = nullptr;
  3401. VkRenderPass render_pass;
  3402. VkResult res = vkCreateRenderPass(device, &render_pass_create_info, nullptr, &render_pass);
  3403. ERR_FAIL_COND_V_MSG(res, 0, "vkCreateRenderPass for empty fb failed with error " + itos(res) + ".");
  3404. if (render_pass == VK_NULL_HANDLE) { //was likely invalid
  3405. return INVALID_ID;
  3406. }
  3407. FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT));
  3408. E = framebuffer_format_cache.insert(key, id);
  3409. FramebufferFormat fb_format;
  3410. fb_format.E = E;
  3411. fb_format.render_pass = render_pass;
  3412. fb_format.pass_samples.push_back(p_samples);
  3413. framebuffer_formats[id] = fb_format;
  3414. return id;
  3415. }
  3416. RenderingDevice::TextureSamples RenderingDeviceVulkan::framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass) {
  3417. Map<FramebufferFormatID, FramebufferFormat>::Element *E = framebuffer_formats.find(p_format);
  3418. ERR_FAIL_COND_V(!E, TEXTURE_SAMPLES_1);
  3419. ERR_FAIL_COND_V(p_pass >= uint32_t(E->get().pass_samples.size()), TEXTURE_SAMPLES_1);
  3420. return E->get().pass_samples[p_pass];
  3421. }
  3422. /***********************/
  3423. /**** RENDER TARGET ****/
  3424. /***********************/
  3425. RID RenderingDeviceVulkan::framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples, FramebufferFormatID p_format_check) {
  3426. _THREAD_SAFE_METHOD_
  3427. Framebuffer framebuffer;
  3428. framebuffer.format_id = framebuffer_format_create_empty(p_samples);
  3429. ERR_FAIL_COND_V(p_format_check != INVALID_FORMAT_ID && framebuffer.format_id != p_format_check, RID());
  3430. framebuffer.size = p_size;
  3431. framebuffer.view_count = 1;
  3432. return framebuffer_owner.make_rid(framebuffer);
  3433. }
  3434. RID RenderingDeviceVulkan::framebuffer_create(const Vector<RID> &p_texture_attachments, FramebufferFormatID p_format_check, uint32_t p_view_count) {
  3435. _THREAD_SAFE_METHOD_
  3436. FramebufferPass pass;
  3437. for (int i = 0; i < p_texture_attachments.size(); i++) {
  3438. Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]);
  3439. ERR_FAIL_COND_V_MSG(!texture, RID(), "Texture index supplied for framebuffer (" + itos(i) + ") is not a valid texture.");
  3440. ERR_FAIL_COND_V_MSG(texture->layers != p_view_count, RID(), "Layers of our texture doesn't match view count for this framebuffer");
  3441. if (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3442. pass.depth_attachment = i;
  3443. } else {
  3444. pass.color_attachments.push_back(i);
  3445. }
  3446. }
  3447. Vector<FramebufferPass> passes;
  3448. passes.push_back(pass);
  3449. return framebuffer_create_multipass(p_texture_attachments, passes, p_format_check, p_view_count);
  3450. }
  3451. RID RenderingDeviceVulkan::framebuffer_create_multipass(const Vector<RID> &p_texture_attachments, Vector<FramebufferPass> &p_passes, FramebufferFormatID p_format_check, uint32_t p_view_count) {
  3452. _THREAD_SAFE_METHOD_
  3453. Vector<AttachmentFormat> attachments;
  3454. Size2i size;
  3455. for (int i = 0; i < p_texture_attachments.size(); i++) {
  3456. Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]);
  3457. ERR_FAIL_COND_V_MSG(!texture, RID(), "Texture index supplied for framebuffer (" + itos(i) + ") is not a valid texture.");
  3458. ERR_FAIL_COND_V_MSG(texture->layers != p_view_count, RID(), "Layers of our texture doesn't match view count for this framebuffer");
  3459. if (i == 0) {
  3460. size.width = texture->width;
  3461. size.height = texture->height;
  3462. } else {
  3463. ERR_FAIL_COND_V_MSG((uint32_t)size.width != texture->width || (uint32_t)size.height != texture->height, RID(),
  3464. "All textures in a framebuffer should be the same size.");
  3465. }
  3466. AttachmentFormat af;
  3467. af.format = texture->format;
  3468. af.samples = texture->samples;
  3469. af.usage_flags = texture->usage_flags;
  3470. attachments.push_back(af);
  3471. }
  3472. FramebufferFormatID format_id = framebuffer_format_create_multipass(attachments, p_passes, p_view_count);
  3473. if (format_id == INVALID_ID) {
  3474. return RID();
  3475. }
  3476. ERR_FAIL_COND_V_MSG(p_format_check != INVALID_ID && format_id != p_format_check, RID(),
  3477. "The format used to check this framebuffer differs from the intended framebuffer format.");
  3478. Framebuffer framebuffer;
  3479. framebuffer.format_id = format_id;
  3480. framebuffer.texture_ids = p_texture_attachments;
  3481. framebuffer.size = size;
  3482. framebuffer.view_count = p_view_count;
  3483. RID id = framebuffer_owner.make_rid(framebuffer);
  3484. for (int i = 0; i < p_texture_attachments.size(); i++) {
  3485. _add_dependency(id, p_texture_attachments[i]);
  3486. }
  3487. return id;
  3488. }
  3489. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_get_format(RID p_framebuffer) {
  3490. _THREAD_SAFE_METHOD_
  3491. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  3492. ERR_FAIL_COND_V(!framebuffer, INVALID_ID);
  3493. return framebuffer->format_id;
  3494. }
  3495. /*****************/
  3496. /**** SAMPLER ****/
  3497. /*****************/
  3498. RID RenderingDeviceVulkan::sampler_create(const SamplerState &p_state) {
  3499. _THREAD_SAFE_METHOD_
  3500. VkSamplerCreateInfo sampler_create_info;
  3501. sampler_create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  3502. sampler_create_info.pNext = nullptr;
  3503. sampler_create_info.flags = 0;
  3504. sampler_create_info.magFilter = p_state.mag_filter == SAMPLER_FILTER_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
  3505. sampler_create_info.minFilter = p_state.min_filter == SAMPLER_FILTER_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
  3506. sampler_create_info.mipmapMode = p_state.mip_filter == SAMPLER_FILTER_LINEAR ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST;
  3507. ERR_FAIL_INDEX_V(p_state.repeat_u, SAMPLER_REPEAT_MODE_MAX, RID());
  3508. sampler_create_info.addressModeU = address_modes[p_state.repeat_u];
  3509. ERR_FAIL_INDEX_V(p_state.repeat_v, SAMPLER_REPEAT_MODE_MAX, RID());
  3510. sampler_create_info.addressModeV = address_modes[p_state.repeat_v];
  3511. ERR_FAIL_INDEX_V(p_state.repeat_w, SAMPLER_REPEAT_MODE_MAX, RID());
  3512. sampler_create_info.addressModeW = address_modes[p_state.repeat_w];
  3513. sampler_create_info.mipLodBias = p_state.lod_bias;
  3514. sampler_create_info.anisotropyEnable = p_state.use_anisotropy;
  3515. sampler_create_info.maxAnisotropy = p_state.anisotropy_max;
  3516. sampler_create_info.compareEnable = p_state.enable_compare;
  3517. ERR_FAIL_INDEX_V(p_state.compare_op, COMPARE_OP_MAX, RID());
  3518. sampler_create_info.compareOp = compare_operators[p_state.compare_op];
  3519. sampler_create_info.minLod = p_state.min_lod;
  3520. sampler_create_info.maxLod = p_state.max_lod;
  3521. ERR_FAIL_INDEX_V(p_state.border_color, SAMPLER_BORDER_COLOR_MAX, RID());
  3522. sampler_create_info.borderColor = sampler_border_colors[p_state.border_color];
  3523. sampler_create_info.unnormalizedCoordinates = p_state.unnormalized_uvw;
  3524. VkSampler sampler;
  3525. VkResult res = vkCreateSampler(device, &sampler_create_info, nullptr, &sampler);
  3526. ERR_FAIL_COND_V_MSG(res, RID(), "vkCreateSampler failed with error " + itos(res) + ".");
  3527. return sampler_owner.make_rid(sampler);
  3528. }
  3529. /**********************/
  3530. /**** VERTEX ARRAY ****/
  3531. /**********************/
  3532. RID RenderingDeviceVulkan::vertex_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data, bool p_use_as_storage) {
  3533. _THREAD_SAFE_METHOD_
  3534. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  3535. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  3536. "Creating buffers with data is forbidden during creation of a draw list");
  3537. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  3538. "Creating buffers with data is forbidden during creation of a draw list");
  3539. uint32_t usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
  3540. if (p_use_as_storage) {
  3541. usage |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
  3542. }
  3543. Buffer buffer;
  3544. _buffer_allocate(&buffer, p_size_bytes, usage, VMA_MEMORY_USAGE_GPU_ONLY);
  3545. if (p_data.size()) {
  3546. uint64_t data_size = p_data.size();
  3547. const uint8_t *r = p_data.ptr();
  3548. _buffer_update(&buffer, 0, r, data_size);
  3549. _buffer_memory_barrier(buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, false);
  3550. }
  3551. return vertex_buffer_owner.make_rid(buffer);
  3552. }
  3553. // Internally reference counted, this ID is warranted to be unique for the same description, but needs to be freed as many times as it was allocated
  3554. RenderingDevice::VertexFormatID RenderingDeviceVulkan::vertex_format_create(const Vector<VertexAttribute> &p_vertex_formats) {
  3555. _THREAD_SAFE_METHOD_
  3556. VertexDescriptionKey key;
  3557. key.vertex_formats = p_vertex_formats;
  3558. VertexFormatID *idptr = vertex_format_cache.getptr(key);
  3559. if (idptr) {
  3560. return *idptr;
  3561. }
  3562. //does not exist, create one and cache it
  3563. VertexDescriptionCache vdcache;
  3564. vdcache.bindings = memnew_arr(VkVertexInputBindingDescription, p_vertex_formats.size());
  3565. vdcache.attributes = memnew_arr(VkVertexInputAttributeDescription, p_vertex_formats.size());
  3566. Set<int> used_locations;
  3567. for (int i = 0; i < p_vertex_formats.size(); i++) {
  3568. ERR_CONTINUE(p_vertex_formats[i].format >= DATA_FORMAT_MAX);
  3569. ERR_FAIL_COND_V(used_locations.has(p_vertex_formats[i].location), INVALID_ID);
  3570. ERR_FAIL_COND_V_MSG(get_format_vertex_size(p_vertex_formats[i].format) == 0, INVALID_ID,
  3571. "Data format for attachment (" + itos(i) + "), '" + named_formats[p_vertex_formats[i].format] + "', is not valid for a vertex array.");
  3572. vdcache.bindings[i].binding = i;
  3573. vdcache.bindings[i].stride = p_vertex_formats[i].stride;
  3574. vdcache.bindings[i].inputRate = p_vertex_formats[i].frequency == VERTEX_FREQUENCY_INSTANCE ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX;
  3575. vdcache.attributes[i].binding = i;
  3576. vdcache.attributes[i].location = p_vertex_formats[i].location;
  3577. vdcache.attributes[i].format = vulkan_formats[p_vertex_formats[i].format];
  3578. vdcache.attributes[i].offset = p_vertex_formats[i].offset;
  3579. used_locations.insert(p_vertex_formats[i].location);
  3580. }
  3581. vdcache.create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  3582. vdcache.create_info.pNext = nullptr;
  3583. vdcache.create_info.flags = 0;
  3584. vdcache.create_info.vertexAttributeDescriptionCount = p_vertex_formats.size();
  3585. vdcache.create_info.pVertexAttributeDescriptions = vdcache.attributes;
  3586. vdcache.create_info.vertexBindingDescriptionCount = p_vertex_formats.size();
  3587. vdcache.create_info.pVertexBindingDescriptions = vdcache.bindings;
  3588. vdcache.vertex_formats = p_vertex_formats;
  3589. VertexFormatID id = VertexFormatID(vertex_format_cache.size()) | (VertexFormatID(ID_TYPE_VERTEX_FORMAT) << ID_BASE_SHIFT);
  3590. vertex_format_cache[key] = id;
  3591. vertex_formats[id] = vdcache;
  3592. return id;
  3593. }
  3594. RID RenderingDeviceVulkan::vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector<RID> &p_src_buffers) {
  3595. _THREAD_SAFE_METHOD_
  3596. ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID());
  3597. const VertexDescriptionCache &vd = vertex_formats[p_vertex_format];
  3598. ERR_FAIL_COND_V(vd.vertex_formats.size() != p_src_buffers.size(), RID());
  3599. for (int i = 0; i < p_src_buffers.size(); i++) {
  3600. ERR_FAIL_COND_V(!vertex_buffer_owner.owns(p_src_buffers[i]), RID());
  3601. }
  3602. VertexArray vertex_array;
  3603. vertex_array.vertex_count = p_vertex_count;
  3604. vertex_array.description = p_vertex_format;
  3605. vertex_array.max_instances_allowed = 0xFFFFFFFF; //by default as many as you want
  3606. for (int i = 0; i < p_src_buffers.size(); i++) {
  3607. Buffer *buffer = vertex_buffer_owner.get_or_null(p_src_buffers[i]);
  3608. //validate with buffer
  3609. {
  3610. const VertexAttribute &atf = vd.vertex_formats[i];
  3611. uint32_t element_size = get_format_vertex_size(atf.format);
  3612. ERR_FAIL_COND_V(element_size == 0, RID()); //should never happens since this was prevalidated
  3613. if (atf.frequency == VERTEX_FREQUENCY_VERTEX) {
  3614. //validate size for regular drawing
  3615. uint64_t total_size = uint64_t(atf.stride) * (p_vertex_count - 1) + atf.offset + element_size;
  3616. ERR_FAIL_COND_V_MSG(total_size > buffer->size, RID(),
  3617. "Attachment (" + itos(i) + ") will read past the end of the buffer.");
  3618. } else {
  3619. //validate size for instances drawing
  3620. uint64_t available = buffer->size - atf.offset;
  3621. ERR_FAIL_COND_V_MSG(available < element_size, RID(),
  3622. "Attachment (" + itos(i) + ") uses instancing, but it's just too small.");
  3623. uint32_t instances_allowed = available / atf.stride;
  3624. vertex_array.max_instances_allowed = MIN(instances_allowed, vertex_array.max_instances_allowed);
  3625. }
  3626. }
  3627. vertex_array.buffers.push_back(buffer->buffer);
  3628. vertex_array.offsets.push_back(0); //offset unused, but passing anyway
  3629. }
  3630. RID id = vertex_array_owner.make_rid(vertex_array);
  3631. for (int i = 0; i < p_src_buffers.size(); i++) {
  3632. _add_dependency(id, p_src_buffers[i]);
  3633. }
  3634. return id;
  3635. }
  3636. RID RenderingDeviceVulkan::index_buffer_create(uint32_t p_index_count, IndexBufferFormat p_format, const Vector<uint8_t> &p_data, bool p_use_restart_indices) {
  3637. _THREAD_SAFE_METHOD_
  3638. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  3639. "Creating buffers with data is forbidden during creation of a draw list");
  3640. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  3641. "Creating buffers with data is forbidden during creation of a draw list");
  3642. ERR_FAIL_COND_V(p_index_count == 0, RID());
  3643. IndexBuffer index_buffer;
  3644. index_buffer.index_type = (p_format == INDEX_BUFFER_FORMAT_UINT16) ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32;
  3645. index_buffer.supports_restart_indices = p_use_restart_indices;
  3646. index_buffer.index_count = p_index_count;
  3647. uint32_t size_bytes = p_index_count * ((p_format == INDEX_BUFFER_FORMAT_UINT16) ? 2 : 4);
  3648. #ifdef DEBUG_ENABLED
  3649. if (p_data.size()) {
  3650. index_buffer.max_index = 0;
  3651. ERR_FAIL_COND_V_MSG((uint32_t)p_data.size() != size_bytes, RID(),
  3652. "Default index buffer initializer array size (" + itos(p_data.size()) + ") does not match format required size (" + itos(size_bytes) + ").");
  3653. const uint8_t *r = p_data.ptr();
  3654. if (p_format == INDEX_BUFFER_FORMAT_UINT16) {
  3655. const uint16_t *index16 = (const uint16_t *)r;
  3656. for (uint32_t i = 0; i < p_index_count; i++) {
  3657. if (p_use_restart_indices && index16[i] == 0xFFFF) {
  3658. continue; //restart index, ignore
  3659. }
  3660. index_buffer.max_index = MAX(index16[i], index_buffer.max_index);
  3661. }
  3662. } else {
  3663. const uint32_t *index32 = (const uint32_t *)r;
  3664. for (uint32_t i = 0; i < p_index_count; i++) {
  3665. if (p_use_restart_indices && index32[i] == 0xFFFFFFFF) {
  3666. continue; //restart index, ignore
  3667. }
  3668. index_buffer.max_index = MAX(index32[i], index_buffer.max_index);
  3669. }
  3670. }
  3671. } else {
  3672. index_buffer.max_index = 0xFFFFFFFF;
  3673. }
  3674. #else
  3675. index_buffer.max_index = 0xFFFFFFFF;
  3676. #endif
  3677. _buffer_allocate(&index_buffer, size_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_ONLY);
  3678. if (p_data.size()) {
  3679. uint64_t data_size = p_data.size();
  3680. const uint8_t *r = p_data.ptr();
  3681. _buffer_update(&index_buffer, 0, r, data_size);
  3682. _buffer_memory_barrier(index_buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_INDEX_READ_BIT, false);
  3683. }
  3684. return index_buffer_owner.make_rid(index_buffer);
  3685. }
  3686. RID RenderingDeviceVulkan::index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count) {
  3687. _THREAD_SAFE_METHOD_
  3688. ERR_FAIL_COND_V(!index_buffer_owner.owns(p_index_buffer), RID());
  3689. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_index_buffer);
  3690. ERR_FAIL_COND_V(p_index_count == 0, RID());
  3691. ERR_FAIL_COND_V(p_index_offset + p_index_count > index_buffer->index_count, RID());
  3692. IndexArray index_array;
  3693. index_array.max_index = index_buffer->max_index;
  3694. index_array.buffer = index_buffer->buffer;
  3695. index_array.offset = p_index_offset;
  3696. index_array.indices = p_index_count;
  3697. index_array.index_type = index_buffer->index_type;
  3698. index_array.supports_restart_indices = index_buffer->supports_restart_indices;
  3699. RID id = index_array_owner.make_rid(index_array);
  3700. _add_dependency(id, p_index_buffer);
  3701. return id;
  3702. }
  3703. /****************/
  3704. /**** SHADER ****/
  3705. /****************/
  3706. static const char *shader_stage_names[RenderingDevice::SHADER_STAGE_MAX] = {
  3707. "Vertex",
  3708. "Fragment",
  3709. "TesselationControl",
  3710. "TesselationEvaluation",
  3711. "Compute"
  3712. };
  3713. static const char *shader_uniform_names[RenderingDevice::UNIFORM_TYPE_MAX] = {
  3714. "Sampler", "CombinedSampler", "Texture", "Image", "TextureBuffer", "SamplerTextureBuffer", "ImageBuffer", "UniformBuffer", "StorageBuffer", "InputAttachment"
  3715. };
  3716. static VkShaderStageFlagBits shader_stage_masks[RenderingDevice::SHADER_STAGE_MAX] = {
  3717. VK_SHADER_STAGE_VERTEX_BIT,
  3718. VK_SHADER_STAGE_FRAGMENT_BIT,
  3719. VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT,
  3720. VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
  3721. VK_SHADER_STAGE_COMPUTE_BIT,
  3722. };
  3723. String RenderingDeviceVulkan::_shader_uniform_debug(RID p_shader, int p_set) {
  3724. String ret;
  3725. const Shader *shader = shader_owner.get_or_null(p_shader);
  3726. ERR_FAIL_COND_V(!shader, String());
  3727. for (int i = 0; i < shader->sets.size(); i++) {
  3728. if (p_set >= 0 && i != p_set) {
  3729. continue;
  3730. }
  3731. for (int j = 0; j < shader->sets[i].uniform_info.size(); j++) {
  3732. const UniformInfo &ui = shader->sets[i].uniform_info[j];
  3733. if (!ret.is_empty()) {
  3734. ret += "\n";
  3735. }
  3736. ret += "Set: " + itos(i) + " Binding: " + itos(ui.binding) + " Type: " + shader_uniform_names[ui.type] + " Length: " + itos(ui.length);
  3737. }
  3738. }
  3739. return ret;
  3740. }
  3741. #if 0
  3742. bool RenderingDeviceVulkan::_uniform_add_binding(Vector<Vector<VkDescriptorSetLayoutBinding> > &bindings, Vector<Vector<UniformInfo> > &uniform_infos, const glslang::TObjectReflection &reflection, RenderingDevice::ShaderStage p_stage, Shader::PushConstant &push_constant, String *r_error) {
  3743. VkDescriptorSetLayoutBinding layout_binding;
  3744. UniformInfo info;
  3745. switch (reflection.getType()->getBasicType()) {
  3746. case glslang::EbtSampler: {
  3747. //print_line("DEBUG: IsSampler");
  3748. if (reflection.getType()->getSampler().dim == glslang::EsdBuffer) {
  3749. //texture buffers
  3750. if (reflection.getType()->getSampler().isCombined()) {
  3751. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  3752. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER;
  3753. //print_line("DEBUG: SAMPLER: texel combined");
  3754. } else if (reflection.getType()->getSampler().isTexture()) {
  3755. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  3756. info.type = UNIFORM_TYPE_TEXTURE_BUFFER;
  3757. //print_line("DEBUG: SAMPLER: texel alone");
  3758. } else if (reflection.getType()->getSampler().isImage()) {
  3759. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  3760. info.type = UNIFORM_TYPE_IMAGE_BUFFER;
  3761. //print_line("DEBUG: SAMPLER: texel buffer");
  3762. } else {
  3763. if (r_error) {
  3764. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' is of unsupported buffer type.";
  3765. }
  3766. return false;
  3767. }
  3768. } else if (reflection.getType()->getSampler().isCombined()) {
  3769. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  3770. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
  3771. //print_line("DEBUG: SAMPLER: combined");
  3772. } else if (reflection.getType()->getSampler().isPureSampler()) {
  3773. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  3774. info.type = UNIFORM_TYPE_SAMPLER;
  3775. //print_line("DEBUG: SAMPLER: sampler");
  3776. } else if (reflection.getType()->getSampler().isTexture()) {
  3777. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  3778. info.type = UNIFORM_TYPE_TEXTURE;
  3779. //print_line("DEBUG: SAMPLER: image");
  3780. } else if (reflection.getType()->getSampler().isImage()) {
  3781. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  3782. info.type = UNIFORM_TYPE_IMAGE;
  3783. //print_line("DEBUG: SAMPLER: storage image");
  3784. } else {
  3785. //print_line("DEBUG: sampler unknown");
  3786. if (r_error) {
  3787. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' is of unsupported sampler type.";
  3788. }
  3789. return false;
  3790. }
  3791. if (reflection.getType()->isArray()) {
  3792. layout_binding.descriptorCount = reflection.getType()->getArraySizes()->getCumulativeSize();
  3793. //print_line("DEBUG: array of size: " + itos(layout_binding.descriptorCount));
  3794. } else {
  3795. layout_binding.descriptorCount = 1;
  3796. }
  3797. info.length = layout_binding.descriptorCount;
  3798. } break;
  3799. /*case glslang::EbtStruct: {
  3800. print_line("DEBUG: Struct");
  3801. } break;*/
  3802. case glslang::EbtBlock: {
  3803. //print_line("DEBUG: Block");
  3804. if (reflection.getType()->getQualifier().storage == glslang::EvqUniform) {
  3805. if (reflection.getType()->getQualifier().layoutPushConstant) {
  3806. uint32_t len = reflection.size;
  3807. if (push_constant.push_constant_size != 0 && push_constant.push_constant_size != len) {
  3808. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' push constants for different stages should all be the same size.";
  3809. return false;
  3810. }
  3811. push_constant.push_constant_size = len;
  3812. push_constant.push_constants_vk_stage |= shader_stage_masks[p_stage];
  3813. return true;
  3814. }
  3815. //print_line("DEBUG: Uniform buffer");
  3816. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  3817. info.type = UNIFORM_TYPE_UNIFORM_BUFFER;
  3818. } else if (reflection.getType()->getQualifier().storage == glslang::EvqBuffer) {
  3819. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  3820. info.type = UNIFORM_TYPE_STORAGE_BUFFER;
  3821. //print_line("DEBUG: Storage buffer");
  3822. } else {
  3823. if (r_error) {
  3824. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' is of unsupported block type: (" + itos(reflection.getType()->getQualifier().storage) + ").";
  3825. }
  3826. return false;
  3827. }
  3828. if (reflection.getType()->isArray()) {
  3829. layout_binding.descriptorCount = reflection.getType()->getArraySizes()->getCumulativeSize();
  3830. //print_line("DEBUG: array of size: " + itos(layout_binding.descriptorCount));
  3831. } else {
  3832. layout_binding.descriptorCount = 1;
  3833. }
  3834. info.length = reflection.size;
  3835. } break;
  3836. /*case glslang::EbtReference: {
  3837. } break;*/
  3838. /*case glslang::EbtAtomicUint: {
  3839. } break;*/
  3840. default: {
  3841. if (reflection.getType()->getQualifier().hasOffset() || reflection.name.find(".") != std::string::npos) {
  3842. //member of uniform block?
  3843. return true;
  3844. }
  3845. if (r_error) {
  3846. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' unsupported uniform type.";
  3847. }
  3848. return false;
  3849. }
  3850. }
  3851. if (!reflection.getType()->getQualifier().hasBinding()) {
  3852. if (r_error) {
  3853. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' lacks a binding number.";
  3854. }
  3855. return false;
  3856. }
  3857. uint32_t set = reflection.getType()->getQualifier().hasSet() ? reflection.getType()->getQualifier().layoutSet : 0;
  3858. if (set >= MAX_UNIFORM_SETS) {
  3859. if (r_error) {
  3860. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' uses a set (" + itos(set) + ") index larger than what is supported (" + itos(MAX_UNIFORM_SETS) + ").";
  3861. }
  3862. return false;
  3863. }
  3864. if (set >= limits.maxBoundDescriptorSets) {
  3865. if (r_error) {
  3866. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' uses a set (" + itos(set) + ") index larger than what is supported by the hardware (" + itos(limits.maxBoundDescriptorSets) + ").";
  3867. }
  3868. return false;
  3869. }
  3870. uint32_t binding = reflection.getType()->getQualifier().layoutBinding;
  3871. if (set < (uint32_t)bindings.size()) {
  3872. //check if this already exists
  3873. for (int i = 0; i < bindings[set].size(); i++) {
  3874. if (bindings[set][i].binding == binding) {
  3875. //already exists, verify that it's the same type
  3876. if (bindings[set][i].descriptorType != layout_binding.descriptorType) {
  3877. if (r_error) {
  3878. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' trying to re-use location for set=" + itos(set) + ", binding=" + itos(binding) + " with different uniform type.";
  3879. }
  3880. return false;
  3881. }
  3882. //also, verify that it's the same size
  3883. if (bindings[set][i].descriptorCount != layout_binding.descriptorCount || uniform_infos[set][i].length != info.length) {
  3884. if (r_error) {
  3885. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' trying to re-use location for set=" + itos(set) + ", binding=" + itos(binding) + " with different uniform size.";
  3886. }
  3887. return false;
  3888. }
  3889. //just append stage mask and return
  3890. bindings.write[set].write[i].stageFlags |= shader_stage_masks[p_stage];
  3891. uniform_infos.write[set].write[i].stages |= 1 << p_stage;
  3892. return true;
  3893. }
  3894. }
  3895. }
  3896. layout_binding.binding = binding;
  3897. layout_binding.stageFlags = shader_stage_masks[p_stage];
  3898. layout_binding.pImmutableSamplers = nullptr; //no support for this yet
  3899. info.stages = 1 << p_stage;
  3900. info.binding = binding;
  3901. if (set >= (uint32_t)bindings.size()) {
  3902. bindings.resize(set + 1);
  3903. uniform_infos.resize(set + 1);
  3904. }
  3905. #if 0
  3906. print_line("stage: " + String(shader_stage_names[p_stage]) + " set: " + itos(set) + " binding: " + itos(info.binding) + " type:" + shader_uniform_names[info.type] + " length: " + itos(info.length));
  3907. #endif
  3908. bindings.write[set].push_back(layout_binding);
  3909. uniform_infos.write[set].push_back(info);
  3910. return true;
  3911. }
  3912. #endif
  3913. //version 1: initial
  3914. //version 2: Added shader name
  3915. #define SHADER_BINARY_VERSION 2
  3916. String RenderingDeviceVulkan::shader_get_binary_cache_key() const {
  3917. return "Vulkan-SV" + itos(SHADER_BINARY_VERSION);
  3918. }
  3919. struct RenderingDeviceVulkanShaderBinaryDataBinding {
  3920. uint32_t type;
  3921. uint32_t binding;
  3922. uint32_t stages;
  3923. uint32_t length; //size of arrays (in total elements), or ubos (in bytes * total elements)
  3924. };
  3925. struct RenderingDeviceVulkanShaderBinarySpecializationConstant {
  3926. uint32_t type;
  3927. uint32_t constant_id;
  3928. union {
  3929. uint32_t int_value;
  3930. float float_value;
  3931. bool bool_value;
  3932. };
  3933. uint32_t stage_flags;
  3934. };
  3935. struct RenderingDeviceVulkanShaderBinaryData {
  3936. uint32_t vertex_input_mask;
  3937. uint32_t fragment_outputs;
  3938. uint32_t specialization_constant_count;
  3939. uint32_t is_compute;
  3940. uint32_t compute_local_size[3];
  3941. uint32_t set_count;
  3942. uint32_t push_constant_size;
  3943. uint32_t push_constants_vk_stage;
  3944. uint32_t stage_count;
  3945. uint32_t shader_name_len;
  3946. };
  3947. Vector<uint8_t> RenderingDeviceVulkan::shader_compile_binary_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv, const String &p_shader_name) {
  3948. RenderingDeviceVulkanShaderBinaryData binary_data;
  3949. binary_data.vertex_input_mask = 0;
  3950. binary_data.fragment_outputs = 0;
  3951. binary_data.specialization_constant_count = 0;
  3952. binary_data.is_compute = 0;
  3953. binary_data.compute_local_size[0] = 0;
  3954. binary_data.compute_local_size[1] = 0;
  3955. binary_data.compute_local_size[2] = 0;
  3956. binary_data.set_count = 0;
  3957. binary_data.push_constant_size = 0;
  3958. binary_data.push_constants_vk_stage = 0;
  3959. Vector<Vector<RenderingDeviceVulkanShaderBinaryDataBinding>> uniform_info; //set bindings
  3960. Vector<RenderingDeviceVulkanShaderBinarySpecializationConstant> specialization_constants;
  3961. uint32_t stages_processed = 0;
  3962. for (int i = 0; i < p_spirv.size(); i++) {
  3963. if (p_spirv[i].shader_stage == SHADER_STAGE_COMPUTE) {
  3964. binary_data.is_compute = true;
  3965. ERR_FAIL_COND_V_MSG(p_spirv.size() != 1, Vector<uint8_t>(),
  3966. "Compute shaders can only receive one stage, dedicated to compute.");
  3967. }
  3968. ERR_FAIL_COND_V_MSG(stages_processed & (1 << p_spirv[i].shader_stage), Vector<uint8_t>(),
  3969. "Stage " + String(shader_stage_names[p_spirv[i].shader_stage]) + " submitted more than once.");
  3970. {
  3971. SpvReflectShaderModule module;
  3972. const uint8_t *spirv = p_spirv[i].spir_v.ptr();
  3973. SpvReflectResult result = spvReflectCreateShaderModule(p_spirv[i].spir_v.size(), spirv, &module);
  3974. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  3975. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed parsing shader.");
  3976. if (binary_data.is_compute) {
  3977. binary_data.compute_local_size[0] = module.entry_points->local_size.x;
  3978. binary_data.compute_local_size[1] = module.entry_points->local_size.y;
  3979. binary_data.compute_local_size[2] = module.entry_points->local_size.z;
  3980. }
  3981. uint32_t binding_count = 0;
  3982. result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, nullptr);
  3983. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  3984. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating descriptor bindings.");
  3985. uint32_t stage = p_spirv[i].shader_stage;
  3986. if (binding_count > 0) {
  3987. //Parse bindings
  3988. Vector<SpvReflectDescriptorBinding *> bindings;
  3989. bindings.resize(binding_count);
  3990. result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, bindings.ptrw());
  3991. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  3992. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed getting descriptor bindings.");
  3993. for (uint32_t j = 0; j < binding_count; j++) {
  3994. const SpvReflectDescriptorBinding &binding = *bindings[j];
  3995. RenderingDeviceVulkanShaderBinaryDataBinding info;
  3996. bool need_array_dimensions = false;
  3997. bool need_block_size = false;
  3998. switch (binding.descriptor_type) {
  3999. case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLER: {
  4000. info.type = UNIFORM_TYPE_SAMPLER;
  4001. need_array_dimensions = true;
  4002. } break;
  4003. case SPV_REFLECT_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: {
  4004. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
  4005. need_array_dimensions = true;
  4006. } break;
  4007. case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLED_IMAGE: {
  4008. info.type = UNIFORM_TYPE_TEXTURE;
  4009. need_array_dimensions = true;
  4010. } break;
  4011. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
  4012. info.type = UNIFORM_TYPE_IMAGE;
  4013. need_array_dimensions = true;
  4014. } break;
  4015. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: {
  4016. info.type = UNIFORM_TYPE_TEXTURE_BUFFER;
  4017. need_array_dimensions = true;
  4018. } break;
  4019. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: {
  4020. info.type = UNIFORM_TYPE_IMAGE_BUFFER;
  4021. need_array_dimensions = true;
  4022. } break;
  4023. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER: {
  4024. info.type = UNIFORM_TYPE_UNIFORM_BUFFER;
  4025. need_block_size = true;
  4026. } break;
  4027. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER: {
  4028. info.type = UNIFORM_TYPE_STORAGE_BUFFER;
  4029. need_block_size = true;
  4030. } break;
  4031. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: {
  4032. ERR_PRINT("Dynamic uniform buffer not supported.");
  4033. continue;
  4034. } break;
  4035. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
  4036. ERR_PRINT("Dynamic storage buffer not supported.");
  4037. continue;
  4038. } break;
  4039. case SPV_REFLECT_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: {
  4040. info.type = UNIFORM_TYPE_INPUT_ATTACHMENT;
  4041. need_array_dimensions = true;
  4042. } break;
  4043. case SPV_REFLECT_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR: {
  4044. ERR_PRINT("Acceleration structure not supported.");
  4045. continue;
  4046. } break;
  4047. }
  4048. if (need_array_dimensions) {
  4049. if (binding.array.dims_count == 0) {
  4050. info.length = 1;
  4051. } else {
  4052. for (uint32_t k = 0; k < binding.array.dims_count; k++) {
  4053. if (k == 0) {
  4054. info.length = binding.array.dims[0];
  4055. } else {
  4056. info.length *= binding.array.dims[k];
  4057. }
  4058. }
  4059. }
  4060. } else if (need_block_size) {
  4061. info.length = binding.block.size;
  4062. } else {
  4063. info.length = 0;
  4064. }
  4065. info.binding = binding.binding;
  4066. uint32_t set = binding.set;
  4067. ERR_FAIL_COND_V_MSG(set >= MAX_UNIFORM_SETS, Vector<uint8_t>(),
  4068. "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' uses a set (" + itos(set) + ") index larger than what is supported (" + itos(MAX_UNIFORM_SETS) + ").");
  4069. ERR_FAIL_COND_V_MSG(set >= limits.maxBoundDescriptorSets, Vector<uint8_t>(),
  4070. "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' uses a set (" + itos(set) + ") index larger than what is supported by the hardware (" + itos(limits.maxBoundDescriptorSets) + ").");
  4071. if (set < (uint32_t)uniform_info.size()) {
  4072. //check if this already exists
  4073. bool exists = false;
  4074. for (int k = 0; k < uniform_info[set].size(); k++) {
  4075. if (uniform_info[set][k].binding == (uint32_t)info.binding) {
  4076. //already exists, verify that it's the same type
  4077. ERR_FAIL_COND_V_MSG(uniform_info[set][k].type != info.type, Vector<uint8_t>(),
  4078. "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' trying to re-use location for set=" + itos(set) + ", binding=" + itos(info.binding) + " with different uniform type.");
  4079. //also, verify that it's the same size
  4080. ERR_FAIL_COND_V_MSG(uniform_info[set][k].length != info.length, Vector<uint8_t>(),
  4081. "On shader stage '" + String(shader_stage_names[stage]) + "', uniform '" + binding.name + "' trying to re-use location for set=" + itos(set) + ", binding=" + itos(info.binding) + " with different uniform size.");
  4082. //just append stage mask and return
  4083. uniform_info.write[set].write[k].stages |= 1 << stage;
  4084. exists = true;
  4085. }
  4086. }
  4087. if (exists) {
  4088. continue; //merged
  4089. }
  4090. }
  4091. info.stages = 1 << stage;
  4092. if (set >= (uint32_t)uniform_info.size()) {
  4093. uniform_info.resize(set + 1);
  4094. }
  4095. uniform_info.write[set].push_back(info);
  4096. }
  4097. }
  4098. {
  4099. //specialization constants
  4100. uint32_t sc_count = 0;
  4101. result = spvReflectEnumerateSpecializationConstants(&module, &sc_count, nullptr);
  4102. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4103. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating specialization constants.");
  4104. if (sc_count) {
  4105. Vector<SpvReflectSpecializationConstant *> spec_constants;
  4106. spec_constants.resize(sc_count);
  4107. result = spvReflectEnumerateSpecializationConstants(&module, &sc_count, spec_constants.ptrw());
  4108. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4109. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining specialization constants.");
  4110. for (uint32_t j = 0; j < sc_count; j++) {
  4111. int32_t existing = -1;
  4112. RenderingDeviceVulkanShaderBinarySpecializationConstant sconst;
  4113. SpvReflectSpecializationConstant *spc = spec_constants[j];
  4114. sconst.constant_id = spc->constant_id;
  4115. sconst.int_value = 0.0; // clear previous value JIC
  4116. switch (spc->constant_type) {
  4117. case SPV_REFLECT_SPECIALIZATION_CONSTANT_BOOL: {
  4118. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL;
  4119. sconst.bool_value = spc->default_value.int_bool_value != 0;
  4120. } break;
  4121. case SPV_REFLECT_SPECIALIZATION_CONSTANT_INT: {
  4122. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT;
  4123. sconst.int_value = spc->default_value.int_bool_value;
  4124. } break;
  4125. case SPV_REFLECT_SPECIALIZATION_CONSTANT_FLOAT: {
  4126. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT;
  4127. sconst.float_value = spc->default_value.float_value;
  4128. } break;
  4129. }
  4130. sconst.stage_flags = 1 << p_spirv[i].shader_stage;
  4131. for (int k = 0; k < specialization_constants.size(); k++) {
  4132. if (specialization_constants[k].constant_id == sconst.constant_id) {
  4133. ERR_FAIL_COND_V_MSG(specialization_constants[k].type != sconst.type, Vector<uint8_t>(), "More than one specialization constant used for id (" + itos(sconst.constant_id) + "), but their types differ.");
  4134. ERR_FAIL_COND_V_MSG(specialization_constants[k].int_value != sconst.int_value, Vector<uint8_t>(), "More than one specialization constant used for id (" + itos(sconst.constant_id) + "), but their default values differ.");
  4135. existing = k;
  4136. break;
  4137. }
  4138. }
  4139. if (existing > 0) {
  4140. specialization_constants.write[existing].stage_flags |= sconst.stage_flags;
  4141. } else {
  4142. specialization_constants.push_back(sconst);
  4143. }
  4144. }
  4145. }
  4146. }
  4147. if (stage == SHADER_STAGE_VERTEX) {
  4148. uint32_t iv_count = 0;
  4149. result = spvReflectEnumerateInputVariables(&module, &iv_count, nullptr);
  4150. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4151. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating input variables.");
  4152. if (iv_count) {
  4153. Vector<SpvReflectInterfaceVariable *> input_vars;
  4154. input_vars.resize(iv_count);
  4155. result = spvReflectEnumerateInputVariables(&module, &iv_count, input_vars.ptrw());
  4156. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4157. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining input variables.");
  4158. for (uint32_t j = 0; j < iv_count; j++) {
  4159. if (input_vars[j] && input_vars[j]->decoration_flags == 0) { //regular input
  4160. binary_data.vertex_input_mask |= (1 << uint32_t(input_vars[j]->location));
  4161. }
  4162. }
  4163. }
  4164. }
  4165. if (stage == SHADER_STAGE_FRAGMENT) {
  4166. uint32_t ov_count = 0;
  4167. result = spvReflectEnumerateOutputVariables(&module, &ov_count, nullptr);
  4168. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4169. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating output variables.");
  4170. if (ov_count) {
  4171. Vector<SpvReflectInterfaceVariable *> output_vars;
  4172. output_vars.resize(ov_count);
  4173. result = spvReflectEnumerateOutputVariables(&module, &ov_count, output_vars.ptrw());
  4174. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4175. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining output variables.");
  4176. for (uint32_t j = 0; j < ov_count; j++) {
  4177. const SpvReflectInterfaceVariable *refvar = output_vars[j];
  4178. if (refvar != nullptr && refvar->built_in != SpvBuiltInFragDepth) {
  4179. binary_data.fragment_outputs |= 1 << refvar->location;
  4180. }
  4181. }
  4182. }
  4183. }
  4184. uint32_t pc_count = 0;
  4185. result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, nullptr);
  4186. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4187. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating push constants.");
  4188. if (pc_count) {
  4189. ERR_FAIL_COND_V_MSG(pc_count > 1, Vector<uint8_t>(),
  4190. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "': Only one push constant is supported, which should be the same across shader stages.");
  4191. Vector<SpvReflectBlockVariable *> pconstants;
  4192. pconstants.resize(pc_count);
  4193. result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, pconstants.ptrw());
  4194. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4195. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining push constants.");
  4196. #if 0
  4197. if (pconstants[0] == nullptr) {
  4198. FileAccess *f = FileAccess::open("res://popo.spv", FileAccess::WRITE);
  4199. f->store_buffer((const uint8_t *)&SpirV[0], SpirV.size() * sizeof(uint32_t));
  4200. memdelete(f);
  4201. }
  4202. #endif
  4203. ERR_FAIL_COND_V_MSG(binary_data.push_constant_size && binary_data.push_constant_size != pconstants[0]->size, Vector<uint8_t>(),
  4204. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "': Push constant block must be the same across shader stages.");
  4205. binary_data.push_constant_size = pconstants[0]->size;
  4206. binary_data.push_constants_vk_stage |= shader_stage_masks[stage];
  4207. //print_line("Stage: " + String(shader_stage_names[stage]) + " push constant of size=" + itos(push_constant.push_constant_size));
  4208. }
  4209. // Destroy the reflection data when no longer required.
  4210. spvReflectDestroyShaderModule(&module);
  4211. }
  4212. stages_processed |= (1 << p_spirv[i].shader_stage);
  4213. }
  4214. Vector<Vector<uint8_t>> compressed_stages;
  4215. Vector<uint32_t> smolv_size;
  4216. Vector<uint32_t> zstd_size; //if 0, stdno t used
  4217. uint32_t stages_binary_size = 0;
  4218. bool strip_debug = false;
  4219. for (int i = 0; i < p_spirv.size(); i++) {
  4220. smolv::ByteArray smolv;
  4221. if (!smolv::Encode(p_spirv[i].spir_v.ptr(), p_spirv[i].spir_v.size(), smolv, strip_debug ? smolv::kEncodeFlagStripDebugInfo : 0)) {
  4222. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Error compressing shader stage :" + String(shader_stage_names[p_spirv[i].shader_stage]));
  4223. } else {
  4224. smolv_size.push_back(smolv.size());
  4225. { //zstd
  4226. Vector<uint8_t> zstd;
  4227. zstd.resize(Compression::get_max_compressed_buffer_size(smolv.size(), Compression::MODE_ZSTD));
  4228. int dst_size = Compression::compress(zstd.ptrw(), &smolv[0], smolv.size(), Compression::MODE_ZSTD);
  4229. if (dst_size > 0 && (uint32_t)dst_size < smolv.size()) {
  4230. zstd_size.push_back(dst_size);
  4231. zstd.resize(dst_size);
  4232. compressed_stages.push_back(zstd);
  4233. } else {
  4234. Vector<uint8_t> smv;
  4235. smv.resize(smolv.size());
  4236. memcpy(smv.ptrw(), &smolv[0], smolv.size());
  4237. zstd_size.push_back(0); //not using zstd
  4238. compressed_stages.push_back(smv);
  4239. }
  4240. }
  4241. }
  4242. uint32_t s = compressed_stages[i].size();
  4243. if (s % 4 != 0) {
  4244. s += 4 - (s % 4);
  4245. }
  4246. stages_binary_size += s;
  4247. }
  4248. binary_data.specialization_constant_count = specialization_constants.size();
  4249. binary_data.set_count = uniform_info.size();
  4250. binary_data.stage_count = p_spirv.size();
  4251. CharString shader_name_utf = p_shader_name.utf8();
  4252. binary_data.shader_name_len = shader_name_utf.length();
  4253. uint32_t total_size = sizeof(uint32_t) * 3; //header + version + main datasize;
  4254. total_size += sizeof(RenderingDeviceVulkanShaderBinaryData);
  4255. total_size += binary_data.shader_name_len;
  4256. if ((binary_data.shader_name_len % 4) != 0) { //alignment rules are really strange
  4257. total_size += 4 - (binary_data.shader_name_len % 4);
  4258. }
  4259. for (int i = 0; i < uniform_info.size(); i++) {
  4260. total_size += sizeof(uint32_t);
  4261. total_size += uniform_info[i].size() * sizeof(RenderingDeviceVulkanShaderBinaryDataBinding);
  4262. }
  4263. total_size += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size();
  4264. total_size += compressed_stages.size() * sizeof(uint32_t) * 3; //sizes
  4265. total_size += stages_binary_size;
  4266. Vector<uint8_t> ret;
  4267. ret.resize(total_size);
  4268. uint32_t offset = 0;
  4269. {
  4270. uint8_t *binptr = ret.ptrw();
  4271. binptr[0] = 'G';
  4272. binptr[1] = 'V';
  4273. binptr[2] = 'B';
  4274. binptr[3] = 'D'; //godot vulkan binary data
  4275. offset += 4;
  4276. encode_uint32(SHADER_BINARY_VERSION, binptr + offset);
  4277. offset += sizeof(uint32_t);
  4278. encode_uint32(sizeof(RenderingDeviceVulkanShaderBinaryData), binptr + offset);
  4279. offset += sizeof(uint32_t);
  4280. memcpy(binptr + offset, &binary_data, sizeof(RenderingDeviceVulkanShaderBinaryData));
  4281. offset += sizeof(RenderingDeviceVulkanShaderBinaryData);
  4282. memcpy(binptr + offset, shader_name_utf.ptr(), binary_data.shader_name_len);
  4283. offset += binary_data.shader_name_len;
  4284. if ((binary_data.shader_name_len % 4) != 0) { //alignment rules are really strange
  4285. offset += 4 - (binary_data.shader_name_len % 4);
  4286. }
  4287. for (int i = 0; i < uniform_info.size(); i++) {
  4288. int count = uniform_info[i].size();
  4289. encode_uint32(count, binptr + offset);
  4290. offset += sizeof(uint32_t);
  4291. if (count > 0) {
  4292. memcpy(binptr + offset, uniform_info[i].ptr(), sizeof(RenderingDeviceVulkanShaderBinaryDataBinding) * count);
  4293. offset += sizeof(RenderingDeviceVulkanShaderBinaryDataBinding) * count;
  4294. }
  4295. }
  4296. if (specialization_constants.size()) {
  4297. memcpy(binptr + offset, specialization_constants.ptr(), sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size());
  4298. offset += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size();
  4299. }
  4300. for (int i = 0; i < compressed_stages.size(); i++) {
  4301. encode_uint32(p_spirv[i].shader_stage, binptr + offset);
  4302. offset += sizeof(uint32_t);
  4303. encode_uint32(smolv_size[i], binptr + offset);
  4304. offset += sizeof(uint32_t);
  4305. encode_uint32(zstd_size[i], binptr + offset);
  4306. offset += sizeof(uint32_t);
  4307. memcpy(binptr + offset, compressed_stages[i].ptr(), compressed_stages[i].size());
  4308. uint32_t s = compressed_stages[i].size();
  4309. if (s % 4 != 0) {
  4310. s += 4 - (s % 4);
  4311. }
  4312. offset += s;
  4313. }
  4314. ERR_FAIL_COND_V(offset != (uint32_t)ret.size(), Vector<uint8_t>());
  4315. }
  4316. return ret;
  4317. }
  4318. RID RenderingDeviceVulkan::shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary) {
  4319. const uint8_t *binptr = p_shader_binary.ptr();
  4320. uint32_t binsize = p_shader_binary.size();
  4321. uint32_t read_offset = 0;
  4322. //consistency check
  4323. ERR_FAIL_COND_V(binsize < sizeof(uint32_t) * 3 + sizeof(RenderingDeviceVulkanShaderBinaryData), RID());
  4324. ERR_FAIL_COND_V(binptr[0] != 'G' || binptr[1] != 'V' || binptr[2] != 'B' || binptr[3] != 'D', RID());
  4325. uint32_t bin_version = decode_uint32(binptr + 4);
  4326. ERR_FAIL_COND_V(bin_version > SHADER_BINARY_VERSION, RID());
  4327. uint32_t bin_data_size = decode_uint32(binptr + 8);
  4328. const RenderingDeviceVulkanShaderBinaryData &binary_data = *(const RenderingDeviceVulkanShaderBinaryData *)(binptr + 12);
  4329. Shader::PushConstant push_constant;
  4330. push_constant.push_constant_size = binary_data.push_constant_size;
  4331. push_constant.push_constants_vk_stage = binary_data.push_constants_vk_stage;
  4332. uint32_t vertex_input_mask = binary_data.vertex_input_mask;
  4333. uint32_t fragment_outputs = binary_data.fragment_outputs;
  4334. bool is_compute = binary_data.is_compute;
  4335. uint32_t compute_local_size[3] = { binary_data.compute_local_size[0], binary_data.compute_local_size[1], binary_data.compute_local_size[2] };
  4336. read_offset += sizeof(uint32_t) * 3 + bin_data_size;
  4337. String name;
  4338. if (binary_data.shader_name_len) {
  4339. name.parse_utf8((const char *)(binptr + read_offset), binary_data.shader_name_len);
  4340. read_offset += binary_data.shader_name_len;
  4341. if ((binary_data.shader_name_len % 4) != 0) { //alignment rules are really strange
  4342. read_offset += 4 - (binary_data.shader_name_len % 4);
  4343. }
  4344. }
  4345. Vector<Vector<VkDescriptorSetLayoutBinding>> set_bindings;
  4346. Vector<Vector<UniformInfo>> uniform_info;
  4347. set_bindings.resize(binary_data.set_count);
  4348. uniform_info.resize(binary_data.set_count);
  4349. for (uint32_t i = 0; i < binary_data.set_count; i++) {
  4350. ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) >= binsize, RID());
  4351. uint32_t set_count = decode_uint32(binptr + read_offset);
  4352. read_offset += sizeof(uint32_t);
  4353. const RenderingDeviceVulkanShaderBinaryDataBinding *set_ptr = (const RenderingDeviceVulkanShaderBinaryDataBinding *)(binptr + read_offset);
  4354. uint32_t set_size = set_count * sizeof(RenderingDeviceVulkanShaderBinaryDataBinding);
  4355. ERR_FAIL_COND_V(read_offset + set_size >= binsize, RID());
  4356. for (uint32_t j = 0; j < set_count; j++) {
  4357. UniformInfo info;
  4358. info.type = UniformType(set_ptr[j].type);
  4359. info.length = set_ptr[j].length;
  4360. info.binding = set_ptr[j].binding;
  4361. info.stages = set_ptr[j].stages;
  4362. VkDescriptorSetLayoutBinding layout_binding;
  4363. layout_binding.pImmutableSamplers = nullptr;
  4364. layout_binding.binding = set_ptr[j].binding;
  4365. layout_binding.descriptorCount = 1;
  4366. layout_binding.stageFlags = 0;
  4367. for (uint32_t k = 0; k < SHADER_STAGE_MAX; k++) {
  4368. if (set_ptr[j].stages & (1 << k)) {
  4369. layout_binding.stageFlags |= shader_stage_masks[k];
  4370. }
  4371. }
  4372. switch (info.type) {
  4373. case UNIFORM_TYPE_SAMPLER: {
  4374. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  4375. layout_binding.descriptorCount = set_ptr[j].length;
  4376. } break;
  4377. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {
  4378. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4379. layout_binding.descriptorCount = set_ptr[j].length;
  4380. } break;
  4381. case UNIFORM_TYPE_TEXTURE: {
  4382. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  4383. layout_binding.descriptorCount = set_ptr[j].length;
  4384. } break;
  4385. case UNIFORM_TYPE_IMAGE: {
  4386. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  4387. layout_binding.descriptorCount = set_ptr[j].length;
  4388. } break;
  4389. case UNIFORM_TYPE_TEXTURE_BUFFER: {
  4390. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  4391. layout_binding.descriptorCount = set_ptr[j].length;
  4392. } break;
  4393. case UNIFORM_TYPE_IMAGE_BUFFER: {
  4394. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  4395. } break;
  4396. case UNIFORM_TYPE_UNIFORM_BUFFER: {
  4397. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  4398. } break;
  4399. case UNIFORM_TYPE_STORAGE_BUFFER: {
  4400. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  4401. } break;
  4402. case UNIFORM_TYPE_INPUT_ATTACHMENT: {
  4403. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
  4404. } break;
  4405. default: {
  4406. ERR_FAIL_V(RID());
  4407. }
  4408. }
  4409. set_bindings.write[i].push_back(layout_binding);
  4410. uniform_info.write[i].push_back(info);
  4411. }
  4412. read_offset += set_size;
  4413. }
  4414. ERR_FAIL_COND_V(read_offset + binary_data.specialization_constant_count * sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) >= binsize, RID());
  4415. Vector<Shader::SpecializationConstant> specialization_constants;
  4416. for (uint32_t i = 0; i < binary_data.specialization_constant_count; i++) {
  4417. const RenderingDeviceVulkanShaderBinarySpecializationConstant &src_sc = *(const RenderingDeviceVulkanShaderBinarySpecializationConstant *)(binptr + read_offset);
  4418. Shader::SpecializationConstant sc;
  4419. sc.constant.int_value = src_sc.int_value;
  4420. sc.constant.type = PipelineSpecializationConstantType(src_sc.type);
  4421. sc.constant.constant_id = src_sc.constant_id;
  4422. sc.stage_flags = src_sc.stage_flags;
  4423. specialization_constants.push_back(sc);
  4424. read_offset += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant);
  4425. }
  4426. Vector<Vector<uint8_t>> stage_spirv_data;
  4427. Vector<ShaderStage> stage_type;
  4428. for (uint32_t i = 0; i < binary_data.stage_count; i++) {
  4429. ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) * 3 >= binsize, RID());
  4430. uint32_t stage = decode_uint32(binptr + read_offset);
  4431. read_offset += sizeof(uint32_t);
  4432. uint32_t smolv_size = decode_uint32(binptr + read_offset);
  4433. read_offset += sizeof(uint32_t);
  4434. uint32_t zstd_size = decode_uint32(binptr + read_offset);
  4435. read_offset += sizeof(uint32_t);
  4436. uint32_t buf_size = (zstd_size > 0) ? zstd_size : smolv_size;
  4437. Vector<uint8_t> smolv;
  4438. const uint8_t *src_smolv = nullptr;
  4439. if (zstd_size > 0) {
  4440. //decompress to smolv
  4441. smolv.resize(smolv_size);
  4442. int dec_smolv_size = Compression::decompress(smolv.ptrw(), smolv.size(), binptr + read_offset, zstd_size, Compression::MODE_ZSTD);
  4443. ERR_FAIL_COND_V(dec_smolv_size != (int32_t)smolv_size, RID());
  4444. src_smolv = smolv.ptr();
  4445. } else {
  4446. src_smolv = binptr + read_offset;
  4447. }
  4448. Vector<uint8_t> spirv;
  4449. uint32_t spirv_size = smolv::GetDecodedBufferSize(src_smolv, smolv_size);
  4450. spirv.resize(spirv_size);
  4451. if (!smolv::Decode(src_smolv, smolv_size, spirv.ptrw(), spirv_size)) {
  4452. ERR_FAIL_V_MSG(RID(), "Malformed smolv input uncompressing shader stage:" + String(shader_stage_names[stage]));
  4453. }
  4454. stage_spirv_data.push_back(spirv);
  4455. stage_type.push_back(ShaderStage(stage));
  4456. if (buf_size % 4 != 0) {
  4457. buf_size += 4 - (buf_size % 4);
  4458. }
  4459. ERR_FAIL_COND_V(read_offset + buf_size > binsize, RID());
  4460. read_offset += buf_size;
  4461. }
  4462. ERR_FAIL_COND_V(read_offset != binsize, RID());
  4463. //all good, let's create modules
  4464. _THREAD_SAFE_METHOD_
  4465. Shader shader;
  4466. shader.vertex_input_mask = vertex_input_mask;
  4467. shader.fragment_output_mask = fragment_outputs;
  4468. shader.push_constant = push_constant;
  4469. shader.is_compute = is_compute;
  4470. shader.compute_local_size[0] = compute_local_size[0];
  4471. shader.compute_local_size[1] = compute_local_size[1];
  4472. shader.compute_local_size[2] = compute_local_size[2];
  4473. shader.specialization_constants = specialization_constants;
  4474. shader.name = name;
  4475. String error_text;
  4476. bool success = true;
  4477. for (int i = 0; i < stage_spirv_data.size(); i++) {
  4478. VkShaderModuleCreateInfo shader_module_create_info;
  4479. shader_module_create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  4480. shader_module_create_info.pNext = nullptr;
  4481. shader_module_create_info.flags = 0;
  4482. shader_module_create_info.codeSize = stage_spirv_data[i].size();
  4483. const uint8_t *r = stage_spirv_data[i].ptr();
  4484. shader_module_create_info.pCode = (const uint32_t *)r;
  4485. VkShaderModule module;
  4486. VkResult res = vkCreateShaderModule(device, &shader_module_create_info, nullptr, &module);
  4487. if (res) {
  4488. success = false;
  4489. error_text = "Error (" + itos(res) + ") creating shader module for stage: " + String(shader_stage_names[stage_type[i]]);
  4490. break;
  4491. }
  4492. const VkShaderStageFlagBits shader_stage_bits[SHADER_STAGE_MAX] = {
  4493. VK_SHADER_STAGE_VERTEX_BIT,
  4494. VK_SHADER_STAGE_FRAGMENT_BIT,
  4495. VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT,
  4496. VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
  4497. VK_SHADER_STAGE_COMPUTE_BIT,
  4498. };
  4499. VkPipelineShaderStageCreateInfo shader_stage;
  4500. shader_stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  4501. shader_stage.pNext = nullptr;
  4502. shader_stage.flags = 0;
  4503. shader_stage.stage = shader_stage_bits[stage_type[i]];
  4504. shader_stage.module = module;
  4505. shader_stage.pName = "main";
  4506. shader_stage.pSpecializationInfo = nullptr;
  4507. shader.pipeline_stages.push_back(shader_stage);
  4508. }
  4509. //proceed to create descriptor sets
  4510. if (success) {
  4511. for (int i = 0; i < set_bindings.size(); i++) {
  4512. //empty ones are fine if they were not used according to spec (binding count will be 0)
  4513. VkDescriptorSetLayoutCreateInfo layout_create_info;
  4514. layout_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  4515. layout_create_info.pNext = nullptr;
  4516. layout_create_info.flags = 0;
  4517. layout_create_info.bindingCount = set_bindings[i].size();
  4518. layout_create_info.pBindings = set_bindings[i].ptr();
  4519. VkDescriptorSetLayout layout;
  4520. VkResult res = vkCreateDescriptorSetLayout(device, &layout_create_info, nullptr, &layout);
  4521. if (res) {
  4522. error_text = "Error (" + itos(res) + ") creating descriptor set layout for set " + itos(i);
  4523. success = false;
  4524. break;
  4525. }
  4526. Shader::Set set;
  4527. set.descriptor_set_layout = layout;
  4528. set.uniform_info = uniform_info[i];
  4529. //sort and hash
  4530. set.uniform_info.sort();
  4531. uint32_t format = 0; //no format, default
  4532. if (set.uniform_info.size()) {
  4533. //has data, needs an actual format;
  4534. UniformSetFormat usformat;
  4535. usformat.uniform_info = set.uniform_info;
  4536. Map<UniformSetFormat, uint32_t>::Element *E = uniform_set_format_cache.find(usformat);
  4537. if (E) {
  4538. format = E->get();
  4539. } else {
  4540. format = uniform_set_format_cache.size() + 1;
  4541. uniform_set_format_cache.insert(usformat, format);
  4542. }
  4543. }
  4544. shader.sets.push_back(set);
  4545. shader.set_formats.push_back(format);
  4546. }
  4547. }
  4548. if (success) {
  4549. //create pipeline layout
  4550. VkPipelineLayoutCreateInfo pipeline_layout_create_info;
  4551. pipeline_layout_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  4552. pipeline_layout_create_info.pNext = nullptr;
  4553. pipeline_layout_create_info.flags = 0;
  4554. pipeline_layout_create_info.setLayoutCount = shader.sets.size();
  4555. Vector<VkDescriptorSetLayout> layouts;
  4556. layouts.resize(shader.sets.size());
  4557. for (int i = 0; i < layouts.size(); i++) {
  4558. layouts.write[i] = shader.sets[i].descriptor_set_layout;
  4559. }
  4560. pipeline_layout_create_info.pSetLayouts = layouts.ptr();
  4561. // Needs to be declared in this outer scope, otherwise it may not outlive its assignment
  4562. // to pipeline_layout_create_info.
  4563. VkPushConstantRange push_constant_range;
  4564. if (push_constant.push_constant_size) {
  4565. push_constant_range.stageFlags = push_constant.push_constants_vk_stage;
  4566. push_constant_range.offset = 0;
  4567. push_constant_range.size = push_constant.push_constant_size;
  4568. pipeline_layout_create_info.pushConstantRangeCount = 1;
  4569. pipeline_layout_create_info.pPushConstantRanges = &push_constant_range;
  4570. } else {
  4571. pipeline_layout_create_info.pushConstantRangeCount = 0;
  4572. pipeline_layout_create_info.pPushConstantRanges = nullptr;
  4573. }
  4574. VkResult err = vkCreatePipelineLayout(device, &pipeline_layout_create_info, nullptr, &shader.pipeline_layout);
  4575. if (err) {
  4576. error_text = "Error (" + itos(err) + ") creating pipeline layout.";
  4577. success = false;
  4578. }
  4579. }
  4580. if (!success) {
  4581. //clean up if failed
  4582. for (int i = 0; i < shader.pipeline_stages.size(); i++) {
  4583. vkDestroyShaderModule(device, shader.pipeline_stages[i].module, nullptr);
  4584. }
  4585. for (int i = 0; i < shader.sets.size(); i++) {
  4586. vkDestroyDescriptorSetLayout(device, shader.sets[i].descriptor_set_layout, nullptr);
  4587. }
  4588. ERR_FAIL_V_MSG(RID(), error_text);
  4589. }
  4590. return shader_owner.make_rid(shader);
  4591. }
  4592. uint32_t RenderingDeviceVulkan::shader_get_vertex_input_attribute_mask(RID p_shader) {
  4593. _THREAD_SAFE_METHOD_
  4594. const Shader *shader = shader_owner.get_or_null(p_shader);
  4595. ERR_FAIL_COND_V(!shader, 0);
  4596. return shader->vertex_input_mask;
  4597. }
  4598. /******************/
  4599. /**** UNIFORMS ****/
  4600. /******************/
  4601. RID RenderingDeviceVulkan::uniform_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data) {
  4602. _THREAD_SAFE_METHOD_
  4603. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  4604. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  4605. "Creating buffers with data is forbidden during creation of a draw list");
  4606. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  4607. "Creating buffers with data is forbidden during creation of a draw list");
  4608. Buffer buffer;
  4609. Error err = _buffer_allocate(&buffer, p_size_bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_ONLY);
  4610. ERR_FAIL_COND_V(err != OK, RID());
  4611. if (p_data.size()) {
  4612. uint64_t data_size = p_data.size();
  4613. const uint8_t *r = p_data.ptr();
  4614. _buffer_update(&buffer, 0, r, data_size);
  4615. _buffer_memory_barrier(buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_UNIFORM_READ_BIT, false);
  4616. }
  4617. return uniform_buffer_owner.make_rid(buffer);
  4618. }
  4619. RID RenderingDeviceVulkan::storage_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data, uint32_t p_usage) {
  4620. _THREAD_SAFE_METHOD_
  4621. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  4622. "Creating buffers with data is forbidden during creation of a draw list");
  4623. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  4624. "Creating buffers with data is forbidden during creation of a draw list");
  4625. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  4626. Buffer buffer;
  4627. buffer.usage = p_usage;
  4628. uint32_t flags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
  4629. if (p_usage & STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT) {
  4630. flags |= VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
  4631. }
  4632. Error err = _buffer_allocate(&buffer, p_size_bytes, flags, VMA_MEMORY_USAGE_GPU_ONLY);
  4633. ERR_FAIL_COND_V(err != OK, RID());
  4634. if (p_data.size()) {
  4635. uint64_t data_size = p_data.size();
  4636. const uint8_t *r = p_data.ptr();
  4637. _buffer_update(&buffer, 0, r, data_size);
  4638. _buffer_memory_barrier(buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, false);
  4639. }
  4640. return storage_buffer_owner.make_rid(buffer);
  4641. }
  4642. RID RenderingDeviceVulkan::texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector<uint8_t> &p_data) {
  4643. _THREAD_SAFE_METHOD_
  4644. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  4645. "Creating buffers with data is forbidden during creation of a draw list");
  4646. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  4647. "Creating buffers with data is forbidden during creation of a draw list");
  4648. uint32_t element_size = get_format_vertex_size(p_format);
  4649. ERR_FAIL_COND_V_MSG(element_size == 0, RID(), "Format requested is not supported for texture buffers");
  4650. uint64_t size_bytes = uint64_t(element_size) * p_size_elements;
  4651. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != size_bytes, RID());
  4652. TextureBuffer texture_buffer;
  4653. Error err = _buffer_allocate(&texture_buffer.buffer, size_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_ONLY);
  4654. ERR_FAIL_COND_V(err != OK, RID());
  4655. if (p_data.size()) {
  4656. uint64_t data_size = p_data.size();
  4657. const uint8_t *r = p_data.ptr();
  4658. _buffer_update(&texture_buffer.buffer, 0, r, data_size);
  4659. _buffer_memory_barrier(texture_buffer.buffer.buffer, 0, data_size, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, false);
  4660. }
  4661. VkBufferViewCreateInfo view_create_info;
  4662. view_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;
  4663. view_create_info.pNext = nullptr;
  4664. view_create_info.flags = 0;
  4665. view_create_info.buffer = texture_buffer.buffer.buffer;
  4666. view_create_info.format = vulkan_formats[p_format];
  4667. view_create_info.offset = 0;
  4668. view_create_info.range = size_bytes;
  4669. texture_buffer.view = VK_NULL_HANDLE;
  4670. VkResult res = vkCreateBufferView(device, &view_create_info, nullptr, &texture_buffer.view);
  4671. if (res) {
  4672. _buffer_free(&texture_buffer.buffer);
  4673. ERR_FAIL_V_MSG(RID(), "Unable to create buffer view, error " + itos(res) + ".");
  4674. }
  4675. //allocate the view
  4676. return texture_buffer_owner.make_rid(texture_buffer);
  4677. }
  4678. RenderingDeviceVulkan::DescriptorPool *RenderingDeviceVulkan::_descriptor_pool_allocate(const DescriptorPoolKey &p_key) {
  4679. if (!descriptor_pools.has(p_key)) {
  4680. descriptor_pools[p_key] = Set<DescriptorPool *>();
  4681. }
  4682. DescriptorPool *pool = nullptr;
  4683. for (Set<DescriptorPool *>::Element *E = descriptor_pools[p_key].front(); E; E = E->next()) {
  4684. if (E->get()->usage < max_descriptors_per_pool) {
  4685. pool = E->get();
  4686. break;
  4687. }
  4688. }
  4689. if (!pool) {
  4690. //create a new one
  4691. pool = memnew(DescriptorPool);
  4692. pool->usage = 0;
  4693. VkDescriptorPoolCreateInfo descriptor_pool_create_info;
  4694. descriptor_pool_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
  4695. descriptor_pool_create_info.pNext = nullptr;
  4696. descriptor_pool_create_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; // can't think how somebody may NOT need this flag..
  4697. descriptor_pool_create_info.maxSets = max_descriptors_per_pool;
  4698. Vector<VkDescriptorPoolSize> sizes;
  4699. //here comes more vulkan API strangeness
  4700. if (p_key.uniform_type[UNIFORM_TYPE_SAMPLER]) {
  4701. VkDescriptorPoolSize s;
  4702. s.type = VK_DESCRIPTOR_TYPE_SAMPLER;
  4703. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_SAMPLER] * max_descriptors_per_pool;
  4704. sizes.push_back(s);
  4705. }
  4706. if (p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE]) {
  4707. VkDescriptorPoolSize s;
  4708. s.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4709. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE] * max_descriptors_per_pool;
  4710. sizes.push_back(s);
  4711. }
  4712. if (p_key.uniform_type[UNIFORM_TYPE_TEXTURE]) {
  4713. VkDescriptorPoolSize s;
  4714. s.type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  4715. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_TEXTURE] * max_descriptors_per_pool;
  4716. sizes.push_back(s);
  4717. }
  4718. if (p_key.uniform_type[UNIFORM_TYPE_IMAGE]) {
  4719. VkDescriptorPoolSize s;
  4720. s.type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  4721. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_IMAGE] * max_descriptors_per_pool;
  4722. sizes.push_back(s);
  4723. }
  4724. if (p_key.uniform_type[UNIFORM_TYPE_TEXTURE_BUFFER] || p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER]) {
  4725. VkDescriptorPoolSize s;
  4726. s.type = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  4727. s.descriptorCount = (p_key.uniform_type[UNIFORM_TYPE_TEXTURE_BUFFER] + p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER]) * max_descriptors_per_pool;
  4728. sizes.push_back(s);
  4729. }
  4730. if (p_key.uniform_type[UNIFORM_TYPE_IMAGE_BUFFER]) {
  4731. VkDescriptorPoolSize s;
  4732. s.type = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  4733. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_IMAGE_BUFFER] * max_descriptors_per_pool;
  4734. sizes.push_back(s);
  4735. }
  4736. if (p_key.uniform_type[UNIFORM_TYPE_UNIFORM_BUFFER]) {
  4737. VkDescriptorPoolSize s;
  4738. s.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  4739. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_UNIFORM_BUFFER] * max_descriptors_per_pool;
  4740. sizes.push_back(s);
  4741. }
  4742. if (p_key.uniform_type[UNIFORM_TYPE_STORAGE_BUFFER]) {
  4743. VkDescriptorPoolSize s;
  4744. s.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  4745. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_STORAGE_BUFFER] * max_descriptors_per_pool;
  4746. sizes.push_back(s);
  4747. }
  4748. if (p_key.uniform_type[UNIFORM_TYPE_INPUT_ATTACHMENT]) {
  4749. VkDescriptorPoolSize s;
  4750. s.type = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
  4751. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_INPUT_ATTACHMENT] * max_descriptors_per_pool;
  4752. sizes.push_back(s);
  4753. }
  4754. descriptor_pool_create_info.poolSizeCount = sizes.size();
  4755. descriptor_pool_create_info.pPoolSizes = sizes.ptr();
  4756. VkResult res = vkCreateDescriptorPool(device, &descriptor_pool_create_info, nullptr, &pool->pool);
  4757. if (res) {
  4758. memdelete(pool);
  4759. ERR_FAIL_COND_V_MSG(res, nullptr, "vkCreateDescriptorPool failed with error " + itos(res) + ".");
  4760. }
  4761. descriptor_pools[p_key].insert(pool);
  4762. }
  4763. pool->usage++;
  4764. return pool;
  4765. }
  4766. void RenderingDeviceVulkan::_descriptor_pool_free(const DescriptorPoolKey &p_key, DescriptorPool *p_pool) {
  4767. #ifdef DEBUG_ENABLED
  4768. ERR_FAIL_COND(!descriptor_pools[p_key].has(p_pool));
  4769. #endif
  4770. ERR_FAIL_COND(p_pool->usage == 0);
  4771. p_pool->usage--;
  4772. if (p_pool->usage == 0) {
  4773. vkDestroyDescriptorPool(device, p_pool->pool, nullptr);
  4774. descriptor_pools[p_key].erase(p_pool);
  4775. memdelete(p_pool);
  4776. if (descriptor_pools[p_key].is_empty()) {
  4777. descriptor_pools.erase(p_key);
  4778. }
  4779. }
  4780. }
  4781. RID RenderingDeviceVulkan::uniform_set_create(const Vector<Uniform> &p_uniforms, RID p_shader, uint32_t p_shader_set) {
  4782. _THREAD_SAFE_METHOD_
  4783. ERR_FAIL_COND_V(p_uniforms.size() == 0, RID());
  4784. Shader *shader = shader_owner.get_or_null(p_shader);
  4785. ERR_FAIL_COND_V(!shader, RID());
  4786. ERR_FAIL_COND_V_MSG(p_shader_set >= (uint32_t)shader->sets.size() || shader->sets[p_shader_set].uniform_info.size() == 0, RID(),
  4787. "Desired set (" + itos(p_shader_set) + ") not used by shader.");
  4788. //see that all sets in shader are satisfied
  4789. const Shader::Set &set = shader->sets[p_shader_set];
  4790. uint32_t uniform_count = p_uniforms.size();
  4791. const Uniform *uniforms = p_uniforms.ptr();
  4792. uint32_t set_uniform_count = set.uniform_info.size();
  4793. const UniformInfo *set_uniforms = set.uniform_info.ptr();
  4794. Vector<VkWriteDescriptorSet> writes;
  4795. DescriptorPoolKey pool_key;
  4796. //to keep them alive until update call
  4797. List<Vector<VkDescriptorBufferInfo>> buffer_infos;
  4798. List<Vector<VkBufferView>> buffer_views;
  4799. List<Vector<VkDescriptorImageInfo>> image_infos;
  4800. //used for verification to make sure a uniform set does not use a framebuffer bound texture
  4801. LocalVector<UniformSet::AttachableTexture> attachable_textures;
  4802. Vector<Texture *> mutable_sampled_textures;
  4803. Vector<Texture *> mutable_storage_textures;
  4804. for (uint32_t i = 0; i < set_uniform_count; i++) {
  4805. const UniformInfo &set_uniform = set_uniforms[i];
  4806. int uniform_idx = -1;
  4807. for (int j = 0; j < (int)uniform_count; j++) {
  4808. if (uniforms[j].binding == set_uniform.binding) {
  4809. uniform_idx = j;
  4810. }
  4811. }
  4812. ERR_FAIL_COND_V_MSG(uniform_idx == -1, RID(),
  4813. "All the shader bindings for the given set must be covered by the uniforms provided. Binding (" + itos(set_uniform.binding) + "), set (" + itos(p_shader_set) + ") was not provided.");
  4814. const Uniform &uniform = uniforms[uniform_idx];
  4815. ERR_FAIL_COND_V_MSG(uniform.uniform_type != set_uniform.type, RID(),
  4816. "Mismatch uniform type for binding (" + itos(set_uniform.binding) + "), set (" + itos(p_shader_set) + "). Expected '" + shader_uniform_names[set_uniform.type] + "', supplied: '" + shader_uniform_names[uniform.uniform_type] + "'.");
  4817. VkWriteDescriptorSet write; //common header
  4818. write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4819. write.pNext = nullptr;
  4820. write.dstSet = VK_NULL_HANDLE; //will assign afterwards when everything is valid
  4821. write.dstBinding = set_uniform.binding;
  4822. write.dstArrayElement = 0;
  4823. write.descriptorCount = 0;
  4824. write.descriptorType = VK_DESCRIPTOR_TYPE_MAX_ENUM; //Invalid value.
  4825. write.pImageInfo = nullptr;
  4826. write.pBufferInfo = nullptr;
  4827. write.pTexelBufferView = nullptr;
  4828. uint32_t type_size = 1;
  4829. switch (uniform.uniform_type) {
  4830. case UNIFORM_TYPE_SAMPLER: {
  4831. if (uniform.ids.size() != set_uniform.length) {
  4832. if (set_uniform.length > 1) {
  4833. ERR_FAIL_V_MSG(RID(), "Sampler (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") sampler elements, so it should be provided equal number of sampler IDs to satisfy it (IDs provided: " + itos(uniform.ids.size()) + ").");
  4834. } else {
  4835. ERR_FAIL_V_MSG(RID(), "Sampler (binding: " + itos(uniform.binding) + ") should provide one ID referencing a sampler (IDs provided: " + itos(uniform.ids.size()) + ").");
  4836. }
  4837. }
  4838. Vector<VkDescriptorImageInfo> image_info;
  4839. for (int j = 0; j < uniform.ids.size(); j++) {
  4840. VkSampler *sampler = sampler_owner.get_or_null(uniform.ids[j]);
  4841. ERR_FAIL_COND_V_MSG(!sampler, RID(), "Sampler (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid sampler.");
  4842. VkDescriptorImageInfo img_info;
  4843. img_info.sampler = *sampler;
  4844. img_info.imageView = VK_NULL_HANDLE;
  4845. img_info.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  4846. image_info.push_back(img_info);
  4847. }
  4848. write.dstArrayElement = 0;
  4849. write.descriptorCount = uniform.ids.size();
  4850. write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  4851. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  4852. write.pBufferInfo = nullptr;
  4853. write.pTexelBufferView = nullptr;
  4854. type_size = uniform.ids.size();
  4855. } break;
  4856. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {
  4857. if (uniform.ids.size() != set_uniform.length * 2) {
  4858. if (set_uniform.length > 1) {
  4859. ERR_FAIL_V_MSG(RID(), "SamplerTexture (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") sampler&texture elements, so it should provided twice the amount of IDs (sampler,texture pairs) to satisfy it (IDs provided: " + itos(uniform.ids.size()) + ").");
  4860. } else {
  4861. ERR_FAIL_V_MSG(RID(), "SamplerTexture (binding: " + itos(uniform.binding) + ") should provide two IDs referencing a sampler and then a texture (IDs provided: " + itos(uniform.ids.size()) + ").");
  4862. }
  4863. }
  4864. Vector<VkDescriptorImageInfo> image_info;
  4865. for (int j = 0; j < uniform.ids.size(); j += 2) {
  4866. VkSampler *sampler = sampler_owner.get_or_null(uniform.ids[j + 0]);
  4867. ERR_FAIL_COND_V_MSG(!sampler, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler.");
  4868. Texture *texture = texture_owner.get_or_null(uniform.ids[j + 1]);
  4869. ERR_FAIL_COND_V_MSG(!texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  4870. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  4871. "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  4872. VkDescriptorImageInfo img_info;
  4873. img_info.sampler = *sampler;
  4874. img_info.imageView = texture->view;
  4875. if (texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT)) {
  4876. UniformSet::AttachableTexture attachable_texture;
  4877. attachable_texture.bind = set_uniform.binding;
  4878. attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.ids[j + 1];
  4879. attachable_textures.push_back(attachable_texture);
  4880. }
  4881. if (texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  4882. //can also be used as storage, add to mutable sampled
  4883. mutable_sampled_textures.push_back(texture);
  4884. }
  4885. if (texture->owner.is_valid()) {
  4886. texture = texture_owner.get_or_null(texture->owner);
  4887. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  4888. }
  4889. img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  4890. image_info.push_back(img_info);
  4891. }
  4892. write.dstArrayElement = 0;
  4893. write.descriptorCount = uniform.ids.size() / 2;
  4894. write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4895. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  4896. write.pBufferInfo = nullptr;
  4897. write.pTexelBufferView = nullptr;
  4898. type_size = uniform.ids.size() / 2;
  4899. } break;
  4900. case UNIFORM_TYPE_TEXTURE: {
  4901. if (uniform.ids.size() != set_uniform.length) {
  4902. if (set_uniform.length > 1) {
  4903. ERR_FAIL_V_MSG(RID(), "Texture (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.ids.size()) + ").");
  4904. } else {
  4905. ERR_FAIL_V_MSG(RID(), "Texture (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.ids.size()) + ").");
  4906. }
  4907. }
  4908. Vector<VkDescriptorImageInfo> image_info;
  4909. for (int j = 0; j < uniform.ids.size(); j++) {
  4910. Texture *texture = texture_owner.get_or_null(uniform.ids[j]);
  4911. ERR_FAIL_COND_V_MSG(!texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  4912. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  4913. "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  4914. VkDescriptorImageInfo img_info;
  4915. img_info.sampler = VK_NULL_HANDLE;
  4916. img_info.imageView = texture->view;
  4917. if (texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT)) {
  4918. UniformSet::AttachableTexture attachable_texture;
  4919. attachable_texture.bind = set_uniform.binding;
  4920. attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.ids[j];
  4921. attachable_textures.push_back(attachable_texture);
  4922. }
  4923. if (texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  4924. //can also be used as storage, add to mutable sampled
  4925. mutable_sampled_textures.push_back(texture);
  4926. }
  4927. if (texture->owner.is_valid()) {
  4928. texture = texture_owner.get_or_null(texture->owner);
  4929. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  4930. }
  4931. img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  4932. image_info.push_back(img_info);
  4933. }
  4934. write.dstArrayElement = 0;
  4935. write.descriptorCount = uniform.ids.size();
  4936. write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  4937. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  4938. write.pBufferInfo = nullptr;
  4939. write.pTexelBufferView = nullptr;
  4940. type_size = uniform.ids.size();
  4941. } break;
  4942. case UNIFORM_TYPE_IMAGE: {
  4943. if (uniform.ids.size() != set_uniform.length) {
  4944. if (set_uniform.length > 1) {
  4945. ERR_FAIL_V_MSG(RID(), "Image (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.ids.size()) + ").");
  4946. } else {
  4947. ERR_FAIL_V_MSG(RID(), "Image (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.ids.size()) + ").");
  4948. }
  4949. }
  4950. Vector<VkDescriptorImageInfo> image_info;
  4951. for (int j = 0; j < uniform.ids.size(); j++) {
  4952. Texture *texture = texture_owner.get_or_null(uniform.ids[j]);
  4953. ERR_FAIL_COND_V_MSG(!texture, RID(),
  4954. "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  4955. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), RID(),
  4956. "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_STORAGE_BIT usage flag set in order to be used as uniform.");
  4957. VkDescriptorImageInfo img_info;
  4958. img_info.sampler = VK_NULL_HANDLE;
  4959. img_info.imageView = texture->view;
  4960. if (texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT) {
  4961. //can also be used as storage, add to mutable sampled
  4962. mutable_storage_textures.push_back(texture);
  4963. }
  4964. if (texture->owner.is_valid()) {
  4965. texture = texture_owner.get_or_null(texture->owner);
  4966. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  4967. }
  4968. img_info.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
  4969. image_info.push_back(img_info);
  4970. }
  4971. write.dstArrayElement = 0;
  4972. write.descriptorCount = uniform.ids.size();
  4973. write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  4974. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  4975. write.pBufferInfo = nullptr;
  4976. write.pTexelBufferView = nullptr;
  4977. type_size = uniform.ids.size();
  4978. } break;
  4979. case UNIFORM_TYPE_TEXTURE_BUFFER: {
  4980. if (uniform.ids.size() != set_uniform.length) {
  4981. if (set_uniform.length > 1) {
  4982. ERR_FAIL_V_MSG(RID(), "Buffer (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") texture buffer elements, so it should be provided equal number of texture buffer IDs to satisfy it (IDs provided: " + itos(uniform.ids.size()) + ").");
  4983. } else {
  4984. ERR_FAIL_V_MSG(RID(), "Buffer (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture buffer (IDs provided: " + itos(uniform.ids.size()) + ").");
  4985. }
  4986. }
  4987. Vector<VkDescriptorBufferInfo> buffer_info;
  4988. Vector<VkBufferView> buffer_view;
  4989. for (int j = 0; j < uniform.ids.size(); j++) {
  4990. TextureBuffer *buffer = texture_buffer_owner.get_or_null(uniform.ids[j]);
  4991. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Texture Buffer (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture buffer.");
  4992. buffer_info.push_back(buffer->buffer.buffer_info);
  4993. buffer_view.push_back(buffer->view);
  4994. }
  4995. write.dstArrayElement = 0;
  4996. write.descriptorCount = uniform.ids.size();
  4997. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  4998. write.pImageInfo = nullptr;
  4999. write.pBufferInfo = buffer_infos.push_back(buffer_info)->get().ptr();
  5000. write.pTexelBufferView = buffer_views.push_back(buffer_view)->get().ptr();
  5001. type_size = uniform.ids.size();
  5002. } break;
  5003. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {
  5004. if (uniform.ids.size() != set_uniform.length * 2) {
  5005. if (set_uniform.length > 1) {
  5006. ERR_FAIL_V_MSG(RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") sampler buffer elements, so it should provided twice the amount of IDs (sampler,buffer pairs) to satisfy it (IDs provided: " + itos(uniform.ids.size()) + ").");
  5007. } else {
  5008. ERR_FAIL_V_MSG(RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ") should provide two IDs referencing a sampler and then a texture buffer (IDs provided: " + itos(uniform.ids.size()) + ").");
  5009. }
  5010. }
  5011. Vector<VkDescriptorImageInfo> image_info;
  5012. Vector<VkDescriptorBufferInfo> buffer_info;
  5013. Vector<VkBufferView> buffer_view;
  5014. for (int j = 0; j < uniform.ids.size(); j += 2) {
  5015. VkSampler *sampler = sampler_owner.get_or_null(uniform.ids[j + 0]);
  5016. ERR_FAIL_COND_V_MSG(!sampler, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler.");
  5017. TextureBuffer *buffer = texture_buffer_owner.get_or_null(uniform.ids[j + 1]);
  5018. VkDescriptorImageInfo img_info;
  5019. img_info.sampler = *sampler;
  5020. img_info.imageView = VK_NULL_HANDLE;
  5021. img_info.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  5022. image_info.push_back(img_info);
  5023. ERR_FAIL_COND_V_MSG(!buffer, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid texture buffer.");
  5024. buffer_info.push_back(buffer->buffer.buffer_info);
  5025. buffer_view.push_back(buffer->view);
  5026. }
  5027. write.dstArrayElement = 0;
  5028. write.descriptorCount = uniform.ids.size() / 2;
  5029. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  5030. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  5031. write.pBufferInfo = buffer_infos.push_back(buffer_info)->get().ptr();
  5032. write.pTexelBufferView = buffer_views.push_back(buffer_view)->get().ptr();
  5033. type_size = uniform.ids.size() / 2;
  5034. } break;
  5035. case UNIFORM_TYPE_IMAGE_BUFFER: {
  5036. //todo
  5037. } break;
  5038. case UNIFORM_TYPE_UNIFORM_BUFFER: {
  5039. ERR_FAIL_COND_V_MSG(uniform.ids.size() != 1, RID(),
  5040. "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.ids.size()) + " provided).");
  5041. Buffer *buffer = uniform_buffer_owner.get_or_null(uniform.ids[0]);
  5042. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") is invalid.");
  5043. ERR_FAIL_COND_V_MSG(buffer->size != (uint32_t)set_uniform.length, RID(),
  5044. "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " does not match size of shader uniform: (" + itos(set_uniform.length) + ").");
  5045. write.dstArrayElement = 0;
  5046. write.descriptorCount = 1;
  5047. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  5048. write.pImageInfo = nullptr;
  5049. write.pBufferInfo = &buffer->buffer_info;
  5050. write.pTexelBufferView = nullptr;
  5051. } break;
  5052. case UNIFORM_TYPE_STORAGE_BUFFER: {
  5053. ERR_FAIL_COND_V_MSG(uniform.ids.size() != 1, RID(),
  5054. "Storage buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.ids.size()) + " provided).");
  5055. Buffer *buffer = nullptr;
  5056. if (storage_buffer_owner.owns(uniform.ids[0])) {
  5057. buffer = storage_buffer_owner.get_or_null(uniform.ids[0]);
  5058. } else if (vertex_buffer_owner.owns(uniform.ids[0])) {
  5059. buffer = vertex_buffer_owner.get_or_null(uniform.ids[0]);
  5060. ERR_FAIL_COND_V_MSG(!(buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT), RID(), "Vertex buffer supplied (binding: " + itos(uniform.binding) + ") was not created with storage flag.");
  5061. }
  5062. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Storage buffer supplied (binding: " + itos(uniform.binding) + ") is invalid.");
  5063. //if 0, then it's sized on link time
  5064. ERR_FAIL_COND_V_MSG(set_uniform.length > 0 && buffer->size != (uint32_t)set_uniform.length, RID(),
  5065. "Storage buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " does not match size of shader uniform: (" + itos(set_uniform.length) + ").");
  5066. write.dstArrayElement = 0;
  5067. write.descriptorCount = 1;
  5068. write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  5069. write.pImageInfo = nullptr;
  5070. write.pBufferInfo = &buffer->buffer_info;
  5071. write.pTexelBufferView = nullptr;
  5072. } break;
  5073. case UNIFORM_TYPE_INPUT_ATTACHMENT: {
  5074. ERR_FAIL_COND_V_MSG(shader->is_compute, RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") supplied for compute shader (this is not allowed).");
  5075. if (uniform.ids.size() != set_uniform.length) {
  5076. if (set_uniform.length > 1) {
  5077. ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") is an array of (" + itos(set_uniform.length) + ") textures, so it should be provided equal number of texture IDs to satisfy it (IDs provided: " + itos(uniform.ids.size()) + ").");
  5078. } else {
  5079. ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.ids.size()) + ").");
  5080. }
  5081. }
  5082. Vector<VkDescriptorImageInfo> image_info;
  5083. for (int j = 0; j < uniform.ids.size(); j++) {
  5084. Texture *texture = texture_owner.get_or_null(uniform.ids[j]);
  5085. ERR_FAIL_COND_V_MSG(!texture, RID(),
  5086. "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  5087. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  5088. "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  5089. VkDescriptorImageInfo img_info;
  5090. img_info.sampler = VK_NULL_HANDLE;
  5091. img_info.imageView = texture->view;
  5092. if (texture->owner.is_valid()) {
  5093. texture = texture_owner.get_or_null(texture->owner);
  5094. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  5095. }
  5096. img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  5097. image_info.push_back(img_info);
  5098. }
  5099. write.dstArrayElement = 0;
  5100. write.descriptorCount = uniform.ids.size();
  5101. write.descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
  5102. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  5103. write.pBufferInfo = nullptr;
  5104. write.pTexelBufferView = nullptr;
  5105. type_size = uniform.ids.size();
  5106. } break;
  5107. default: {
  5108. }
  5109. }
  5110. writes.push_back(write);
  5111. ERR_FAIL_COND_V_MSG(pool_key.uniform_type[set_uniform.type] == MAX_DESCRIPTOR_POOL_ELEMENT, RID(),
  5112. "Uniform set reached the limit of bindings for the same type (" + itos(MAX_DESCRIPTOR_POOL_ELEMENT) + ").");
  5113. pool_key.uniform_type[set_uniform.type] += type_size;
  5114. }
  5115. //need a descriptor pool
  5116. DescriptorPool *pool = _descriptor_pool_allocate(pool_key);
  5117. ERR_FAIL_COND_V(!pool, RID());
  5118. VkDescriptorSetAllocateInfo descriptor_set_allocate_info;
  5119. descriptor_set_allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
  5120. descriptor_set_allocate_info.pNext = nullptr;
  5121. descriptor_set_allocate_info.descriptorPool = pool->pool;
  5122. descriptor_set_allocate_info.descriptorSetCount = 1;
  5123. descriptor_set_allocate_info.pSetLayouts = &shader->sets[p_shader_set].descriptor_set_layout;
  5124. VkDescriptorSet descriptor_set;
  5125. VkResult res = vkAllocateDescriptorSets(device, &descriptor_set_allocate_info, &descriptor_set);
  5126. if (res) {
  5127. _descriptor_pool_free(pool_key, pool); // meh
  5128. ERR_FAIL_V_MSG(RID(), "Cannot allocate descriptor sets, error " + itos(res) + ".");
  5129. }
  5130. UniformSet uniform_set;
  5131. uniform_set.pool = pool;
  5132. uniform_set.pool_key = pool_key;
  5133. uniform_set.descriptor_set = descriptor_set;
  5134. uniform_set.format = shader->set_formats[p_shader_set];
  5135. uniform_set.attachable_textures = attachable_textures;
  5136. uniform_set.mutable_sampled_textures = mutable_sampled_textures;
  5137. uniform_set.mutable_storage_textures = mutable_storage_textures;
  5138. uniform_set.shader_set = p_shader_set;
  5139. uniform_set.shader_id = p_shader;
  5140. RID id = uniform_set_owner.make_rid(uniform_set);
  5141. //add dependencies
  5142. _add_dependency(id, p_shader);
  5143. for (uint32_t i = 0; i < uniform_count; i++) {
  5144. const Uniform &uniform = uniforms[i];
  5145. int id_count = uniform.ids.size();
  5146. const RID *ids = uniform.ids.ptr();
  5147. for (int j = 0; j < id_count; j++) {
  5148. _add_dependency(id, ids[j]);
  5149. }
  5150. }
  5151. //write the contents
  5152. if (writes.size()) {
  5153. for (int i = 0; i < writes.size(); i++) {
  5154. writes.write[i].dstSet = descriptor_set;
  5155. }
  5156. vkUpdateDescriptorSets(device, writes.size(), writes.ptr(), 0, nullptr);
  5157. }
  5158. return id;
  5159. }
  5160. bool RenderingDeviceVulkan::uniform_set_is_valid(RID p_uniform_set) {
  5161. return uniform_set_owner.owns(p_uniform_set);
  5162. }
  5163. void RenderingDeviceVulkan::uniform_set_set_invalidation_callback(RID p_uniform_set, UniformSetInvalidatedCallback p_callback, void *p_userdata) {
  5164. UniformSet *us = uniform_set_owner.get_or_null(p_uniform_set);
  5165. ERR_FAIL_COND(!us);
  5166. us->invalidated_callback = p_callback;
  5167. us->invalidated_callback_userdata = p_userdata;
  5168. }
  5169. Error RenderingDeviceVulkan::buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, uint32_t p_post_barrier) {
  5170. _THREAD_SAFE_METHOD_
  5171. ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER,
  5172. "Updating buffers is forbidden during creation of a draw list");
  5173. ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER,
  5174. "Updating buffers is forbidden during creation of a compute list");
  5175. VkPipelineStageFlags dst_stage_mask = 0;
  5176. VkAccessFlags dst_access = 0;
  5177. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  5178. // Protect subsequent updates...
  5179. dst_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  5180. dst_access = VK_ACCESS_TRANSFER_WRITE_BIT;
  5181. }
  5182. Buffer *buffer = _get_buffer_from_owner(p_buffer, dst_stage_mask, dst_access, p_post_barrier);
  5183. if (!buffer) {
  5184. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type.");
  5185. }
  5186. ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER,
  5187. "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end.");
  5188. // no barrier should be needed here
  5189. // _buffer_memory_barrier(buffer->buffer, p_offset, p_size, dst_stage_mask, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_access, VK_ACCESS_TRANSFER_WRITE_BIT, true);
  5190. Error err = _buffer_update(buffer, p_offset, (uint8_t *)p_data, p_size, p_post_barrier);
  5191. if (err) {
  5192. return err;
  5193. }
  5194. #ifdef FORCE_FULL_BARRIER
  5195. _full_barrier(true);
  5196. #else
  5197. if (dst_stage_mask == 0) {
  5198. dst_stage_mask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  5199. }
  5200. if (p_post_barrier != RD::BARRIER_MASK_NO_BARRIER) {
  5201. _buffer_memory_barrier(buffer->buffer, p_offset, p_size, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_stage_mask, VK_ACCESS_TRANSFER_WRITE_BIT, dst_access, true);
  5202. }
  5203. #endif
  5204. return err;
  5205. }
  5206. Error RenderingDeviceVulkan::buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size, uint32_t p_post_barrier) {
  5207. _THREAD_SAFE_METHOD_
  5208. ERR_FAIL_COND_V_MSG((p_size % 4) != 0, ERR_INVALID_PARAMETER,
  5209. "Size must be a multiple of four");
  5210. ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER,
  5211. "Updating buffers in is forbidden during creation of a draw list");
  5212. ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER,
  5213. "Updating buffers is forbidden during creation of a compute list");
  5214. VkPipelineStageFlags dst_stage_mask = 0;
  5215. VkAccessFlags dst_access = 0;
  5216. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  5217. // Protect subsequent updates...
  5218. dst_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  5219. dst_access = VK_ACCESS_TRANSFER_WRITE_BIT;
  5220. }
  5221. Buffer *buffer = _get_buffer_from_owner(p_buffer, dst_stage_mask, dst_access, p_post_barrier);
  5222. if (!buffer) {
  5223. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type.");
  5224. }
  5225. ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER,
  5226. "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end.");
  5227. // should not be needed
  5228. // _buffer_memory_barrier(buffer->buffer, p_offset, p_size, dst_stage_mask, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_access, VK_ACCESS_TRANSFER_WRITE_BIT, p_post_barrier);
  5229. vkCmdFillBuffer(frames[frame].draw_command_buffer, buffer->buffer, p_offset, p_size, 0);
  5230. #ifdef FORCE_FULL_BARRIER
  5231. _full_barrier(true);
  5232. #else
  5233. if (dst_stage_mask == 0) {
  5234. dst_stage_mask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  5235. }
  5236. _buffer_memory_barrier(buffer->buffer, p_offset, p_size, VK_PIPELINE_STAGE_TRANSFER_BIT, dst_stage_mask, VK_ACCESS_TRANSFER_WRITE_BIT, dst_access, dst_stage_mask);
  5237. #endif
  5238. return OK;
  5239. }
  5240. Vector<uint8_t> RenderingDeviceVulkan::buffer_get_data(RID p_buffer) {
  5241. _THREAD_SAFE_METHOD_
  5242. // It could be this buffer was just created
  5243. VkPipelineShaderStageCreateFlags src_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  5244. VkAccessFlags src_access_mask = VK_ACCESS_TRANSFER_WRITE_BIT;
  5245. // Get the vulkan buffer and the potential stage/access possible
  5246. Buffer *buffer = _get_buffer_from_owner(p_buffer, src_stage_mask, src_access_mask, BARRIER_MASK_ALL);
  5247. if (!buffer) {
  5248. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Buffer is either invalid or this type of buffer can't be retrieved. Only Index and Vertex buffers allow retrieving.");
  5249. }
  5250. // Make sure no one is using the buffer -- the "false" gets us to the same command buffer as below.
  5251. _buffer_memory_barrier(buffer->buffer, 0, buffer->size, src_stage_mask, src_access_mask, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT, false);
  5252. VkCommandBuffer command_buffer = frames[frame].setup_command_buffer;
  5253. Buffer tmp_buffer;
  5254. _buffer_allocate(&tmp_buffer, buffer->size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_CPU_ONLY);
  5255. VkBufferCopy region;
  5256. region.srcOffset = 0;
  5257. region.dstOffset = 0;
  5258. region.size = buffer->size;
  5259. vkCmdCopyBuffer(command_buffer, buffer->buffer, tmp_buffer.buffer, 1, &region); //dst buffer is in CPU, but I wonder if src buffer needs a barrier for this..
  5260. //flush everything so memory can be safely mapped
  5261. _flush(true);
  5262. void *buffer_mem;
  5263. VkResult vkerr = vmaMapMemory(allocator, tmp_buffer.allocation, &buffer_mem);
  5264. ERR_FAIL_COND_V_MSG(vkerr, Vector<uint8_t>(), "vmaMapMemory failed with error " + itos(vkerr) + ".");
  5265. Vector<uint8_t> buffer_data;
  5266. {
  5267. buffer_data.resize(buffer->size);
  5268. uint8_t *w = buffer_data.ptrw();
  5269. memcpy(w, buffer_mem, buffer->size);
  5270. }
  5271. vmaUnmapMemory(allocator, tmp_buffer.allocation);
  5272. _buffer_free(&tmp_buffer);
  5273. return buffer_data;
  5274. }
  5275. /*************************/
  5276. /**** RENDER PIPELINE ****/
  5277. /*************************/
  5278. RID RenderingDeviceVulkan::render_pipeline_create(RID p_shader, FramebufferFormatID p_framebuffer_format, VertexFormatID p_vertex_format, RenderPrimitive p_render_primitive, const PipelineRasterizationState &p_rasterization_state, const PipelineMultisampleState &p_multisample_state, const PipelineDepthStencilState &p_depth_stencil_state, const PipelineColorBlendState &p_blend_state, int p_dynamic_state_flags, uint32_t p_for_render_pass, const Vector<PipelineSpecializationConstant> &p_specialization_constants) {
  5279. _THREAD_SAFE_METHOD_
  5280. //needs a shader
  5281. Shader *shader = shader_owner.get_or_null(p_shader);
  5282. ERR_FAIL_COND_V(!shader, RID());
  5283. ERR_FAIL_COND_V_MSG(shader->is_compute, RID(),
  5284. "Compute shaders can't be used in render pipelines");
  5285. if (p_framebuffer_format == INVALID_ID) {
  5286. //if nothing provided, use an empty one (no attachments)
  5287. p_framebuffer_format = framebuffer_format_create(Vector<AttachmentFormat>());
  5288. }
  5289. ERR_FAIL_COND_V(!framebuffer_formats.has(p_framebuffer_format), RID());
  5290. const FramebufferFormat &fb_format = framebuffer_formats[p_framebuffer_format];
  5291. { //validate shader vs framebuffer
  5292. ERR_FAIL_COND_V_MSG(p_for_render_pass >= uint32_t(fb_format.E->key().passes.size()), RID(), "Render pass requested for pipeline creation (" + itos(p_for_render_pass) + ") is out of bounds");
  5293. const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass];
  5294. uint32_t output_mask = 0;
  5295. for (int i = 0; i < pass.color_attachments.size(); i++) {
  5296. if (pass.color_attachments[i] != FramebufferPass::ATTACHMENT_UNUSED) {
  5297. output_mask |= 1 << i;
  5298. }
  5299. }
  5300. ERR_FAIL_COND_V_MSG(shader->fragment_output_mask != output_mask, RID(),
  5301. "Mismatch fragment shader output mask (" + itos(shader->fragment_output_mask) + ") and framebuffer color output mask (" + itos(output_mask) + ") when binding both in render pipeline.");
  5302. }
  5303. //vertex
  5304. VkPipelineVertexInputStateCreateInfo pipeline_vertex_input_state_create_info;
  5305. if (p_vertex_format != INVALID_ID) {
  5306. //uses vertices, else it does not
  5307. ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID());
  5308. const VertexDescriptionCache &vd = vertex_formats[p_vertex_format];
  5309. pipeline_vertex_input_state_create_info = vd.create_info;
  5310. //validate with inputs
  5311. for (uint32_t i = 0; i < 32; i++) {
  5312. if (!(shader->vertex_input_mask & (1 << i))) {
  5313. continue;
  5314. }
  5315. bool found = false;
  5316. for (int j = 0; j < vd.vertex_formats.size(); j++) {
  5317. if (vd.vertex_formats[j].location == i) {
  5318. found = true;
  5319. }
  5320. }
  5321. ERR_FAIL_COND_V_MSG(!found, RID(),
  5322. "Shader vertex input location (" + itos(i) + ") not provided in vertex input description for pipeline creation.");
  5323. }
  5324. } else {
  5325. //does not use vertices
  5326. pipeline_vertex_input_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  5327. pipeline_vertex_input_state_create_info.pNext = nullptr;
  5328. pipeline_vertex_input_state_create_info.flags = 0;
  5329. pipeline_vertex_input_state_create_info.vertexBindingDescriptionCount = 0;
  5330. pipeline_vertex_input_state_create_info.pVertexBindingDescriptions = nullptr;
  5331. pipeline_vertex_input_state_create_info.vertexAttributeDescriptionCount = 0;
  5332. pipeline_vertex_input_state_create_info.pVertexAttributeDescriptions = nullptr;
  5333. ERR_FAIL_COND_V_MSG(shader->vertex_input_mask != 0, RID(),
  5334. "Shader contains vertex inputs, but no vertex input description was provided for pipeline creation.");
  5335. }
  5336. //input assembly
  5337. ERR_FAIL_INDEX_V(p_render_primitive, RENDER_PRIMITIVE_MAX, RID());
  5338. VkPipelineInputAssemblyStateCreateInfo input_assembly_create_info;
  5339. input_assembly_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  5340. input_assembly_create_info.pNext = nullptr;
  5341. input_assembly_create_info.flags = 0;
  5342. static const VkPrimitiveTopology topology_list[RENDER_PRIMITIVE_MAX] = {
  5343. VK_PRIMITIVE_TOPOLOGY_POINT_LIST,
  5344. VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
  5345. VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY,
  5346. VK_PRIMITIVE_TOPOLOGY_LINE_STRIP,
  5347. VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY,
  5348. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
  5349. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY,
  5350. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
  5351. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY,
  5352. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
  5353. VK_PRIMITIVE_TOPOLOGY_PATCH_LIST
  5354. };
  5355. input_assembly_create_info.topology = topology_list[p_render_primitive];
  5356. input_assembly_create_info.primitiveRestartEnable = (p_render_primitive == RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX);
  5357. //tessellation
  5358. VkPipelineTessellationStateCreateInfo tessellation_create_info;
  5359. tessellation_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO;
  5360. tessellation_create_info.pNext = nullptr;
  5361. tessellation_create_info.flags = 0;
  5362. ERR_FAIL_COND_V(limits.maxTessellationPatchSize > 0 && (p_rasterization_state.patch_control_points < 1 || p_rasterization_state.patch_control_points > limits.maxTessellationPatchSize), RID());
  5363. tessellation_create_info.patchControlPoints = p_rasterization_state.patch_control_points;
  5364. VkPipelineViewportStateCreateInfo viewport_state_create_info;
  5365. viewport_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  5366. viewport_state_create_info.pNext = nullptr;
  5367. viewport_state_create_info.flags = 0;
  5368. viewport_state_create_info.viewportCount = 1; //if VR extensions are supported at some point, this will have to be customizable in the framebuffer format
  5369. viewport_state_create_info.pViewports = nullptr;
  5370. viewport_state_create_info.scissorCount = 1;
  5371. viewport_state_create_info.pScissors = nullptr;
  5372. //rasterization
  5373. VkPipelineRasterizationStateCreateInfo rasterization_state_create_info;
  5374. rasterization_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  5375. rasterization_state_create_info.pNext = nullptr;
  5376. rasterization_state_create_info.flags = 0;
  5377. rasterization_state_create_info.depthClampEnable = p_rasterization_state.enable_depth_clamp;
  5378. rasterization_state_create_info.rasterizerDiscardEnable = p_rasterization_state.discard_primitives;
  5379. rasterization_state_create_info.polygonMode = (p_rasterization_state.wireframe ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL);
  5380. static VkCullModeFlags cull_mode[3] = {
  5381. VK_CULL_MODE_NONE,
  5382. VK_CULL_MODE_FRONT_BIT,
  5383. VK_CULL_MODE_BACK_BIT
  5384. };
  5385. ERR_FAIL_INDEX_V(p_rasterization_state.cull_mode, 3, RID());
  5386. rasterization_state_create_info.cullMode = cull_mode[p_rasterization_state.cull_mode];
  5387. rasterization_state_create_info.frontFace = (p_rasterization_state.front_face == POLYGON_FRONT_FACE_CLOCKWISE ? VK_FRONT_FACE_CLOCKWISE : VK_FRONT_FACE_COUNTER_CLOCKWISE);
  5388. rasterization_state_create_info.depthBiasEnable = p_rasterization_state.depth_bias_enable;
  5389. rasterization_state_create_info.depthBiasConstantFactor = p_rasterization_state.depth_bias_constant_factor;
  5390. rasterization_state_create_info.depthBiasClamp = p_rasterization_state.depth_bias_clamp;
  5391. rasterization_state_create_info.depthBiasSlopeFactor = p_rasterization_state.depth_bias_slope_factor;
  5392. rasterization_state_create_info.lineWidth = p_rasterization_state.line_width;
  5393. //multisample
  5394. VkPipelineMultisampleStateCreateInfo multisample_state_create_info;
  5395. multisample_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  5396. multisample_state_create_info.pNext = nullptr;
  5397. multisample_state_create_info.flags = 0;
  5398. multisample_state_create_info.rasterizationSamples = rasterization_sample_count[p_multisample_state.sample_count];
  5399. multisample_state_create_info.sampleShadingEnable = p_multisample_state.enable_sample_shading;
  5400. multisample_state_create_info.minSampleShading = p_multisample_state.min_sample_shading;
  5401. Vector<VkSampleMask> sample_mask;
  5402. if (p_multisample_state.sample_mask.size()) {
  5403. //use sample mask
  5404. int rasterization_sample_mask_expected_size[TEXTURE_SAMPLES_MAX] = {
  5405. 1, 2, 4, 8, 16, 32, 64
  5406. };
  5407. ERR_FAIL_COND_V(rasterization_sample_mask_expected_size[p_multisample_state.sample_count] != p_multisample_state.sample_mask.size(), RID());
  5408. sample_mask.resize(p_multisample_state.sample_mask.size());
  5409. for (int i = 0; i < p_multisample_state.sample_mask.size(); i++) {
  5410. VkSampleMask mask = p_multisample_state.sample_mask[i];
  5411. sample_mask.push_back(mask);
  5412. }
  5413. multisample_state_create_info.pSampleMask = sample_mask.ptr();
  5414. } else {
  5415. multisample_state_create_info.pSampleMask = nullptr;
  5416. }
  5417. multisample_state_create_info.alphaToCoverageEnable = p_multisample_state.enable_alpha_to_coverage;
  5418. multisample_state_create_info.alphaToOneEnable = p_multisample_state.enable_alpha_to_one;
  5419. //depth stencil
  5420. VkPipelineDepthStencilStateCreateInfo depth_stencil_state_create_info;
  5421. depth_stencil_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  5422. depth_stencil_state_create_info.pNext = nullptr;
  5423. depth_stencil_state_create_info.flags = 0;
  5424. depth_stencil_state_create_info.depthTestEnable = p_depth_stencil_state.enable_depth_test;
  5425. depth_stencil_state_create_info.depthWriteEnable = p_depth_stencil_state.enable_depth_write;
  5426. ERR_FAIL_INDEX_V(p_depth_stencil_state.depth_compare_operator, COMPARE_OP_MAX, RID());
  5427. depth_stencil_state_create_info.depthCompareOp = compare_operators[p_depth_stencil_state.depth_compare_operator];
  5428. depth_stencil_state_create_info.depthBoundsTestEnable = p_depth_stencil_state.enable_depth_range;
  5429. depth_stencil_state_create_info.stencilTestEnable = p_depth_stencil_state.enable_stencil;
  5430. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.fail, STENCIL_OP_MAX, RID());
  5431. depth_stencil_state_create_info.front.failOp = stencil_operations[p_depth_stencil_state.front_op.fail];
  5432. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.pass, STENCIL_OP_MAX, RID());
  5433. depth_stencil_state_create_info.front.passOp = stencil_operations[p_depth_stencil_state.front_op.pass];
  5434. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.depth_fail, STENCIL_OP_MAX, RID());
  5435. depth_stencil_state_create_info.front.depthFailOp = stencil_operations[p_depth_stencil_state.front_op.depth_fail];
  5436. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.compare, COMPARE_OP_MAX, RID());
  5437. depth_stencil_state_create_info.front.compareOp = compare_operators[p_depth_stencil_state.front_op.compare];
  5438. depth_stencil_state_create_info.front.compareMask = p_depth_stencil_state.front_op.compare_mask;
  5439. depth_stencil_state_create_info.front.writeMask = p_depth_stencil_state.front_op.write_mask;
  5440. depth_stencil_state_create_info.front.reference = p_depth_stencil_state.front_op.reference;
  5441. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.fail, STENCIL_OP_MAX, RID());
  5442. depth_stencil_state_create_info.back.failOp = stencil_operations[p_depth_stencil_state.back_op.fail];
  5443. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.pass, STENCIL_OP_MAX, RID());
  5444. depth_stencil_state_create_info.back.passOp = stencil_operations[p_depth_stencil_state.back_op.pass];
  5445. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.depth_fail, STENCIL_OP_MAX, RID());
  5446. depth_stencil_state_create_info.back.depthFailOp = stencil_operations[p_depth_stencil_state.back_op.depth_fail];
  5447. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.compare, COMPARE_OP_MAX, RID());
  5448. depth_stencil_state_create_info.back.compareOp = compare_operators[p_depth_stencil_state.back_op.compare];
  5449. depth_stencil_state_create_info.back.compareMask = p_depth_stencil_state.back_op.compare_mask;
  5450. depth_stencil_state_create_info.back.writeMask = p_depth_stencil_state.back_op.write_mask;
  5451. depth_stencil_state_create_info.back.reference = p_depth_stencil_state.back_op.reference;
  5452. depth_stencil_state_create_info.minDepthBounds = p_depth_stencil_state.depth_range_min;
  5453. depth_stencil_state_create_info.maxDepthBounds = p_depth_stencil_state.depth_range_max;
  5454. //blend state
  5455. VkPipelineColorBlendStateCreateInfo color_blend_state_create_info;
  5456. color_blend_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  5457. color_blend_state_create_info.pNext = nullptr;
  5458. color_blend_state_create_info.flags = 0;
  5459. color_blend_state_create_info.logicOpEnable = p_blend_state.enable_logic_op;
  5460. ERR_FAIL_INDEX_V(p_blend_state.logic_op, LOGIC_OP_MAX, RID());
  5461. color_blend_state_create_info.logicOp = logic_operations[p_blend_state.logic_op];
  5462. Vector<VkPipelineColorBlendAttachmentState> attachment_states;
  5463. {
  5464. const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass];
  5465. for (int i = 0; i < pass.color_attachments.size(); i++) {
  5466. if (pass.color_attachments[i] != FramebufferPass::ATTACHMENT_UNUSED) {
  5467. int idx = attachment_states.size();
  5468. ERR_FAIL_INDEX_V(idx, p_blend_state.attachments.size(), RID());
  5469. VkPipelineColorBlendAttachmentState state;
  5470. state.blendEnable = p_blend_state.attachments[idx].enable_blend;
  5471. ERR_FAIL_INDEX_V(p_blend_state.attachments[idx].src_color_blend_factor, BLEND_FACTOR_MAX, RID());
  5472. state.srcColorBlendFactor = blend_factors[p_blend_state.attachments[idx].src_color_blend_factor];
  5473. ERR_FAIL_INDEX_V(p_blend_state.attachments[idx].dst_color_blend_factor, BLEND_FACTOR_MAX, RID());
  5474. state.dstColorBlendFactor = blend_factors[p_blend_state.attachments[idx].dst_color_blend_factor];
  5475. ERR_FAIL_INDEX_V(p_blend_state.attachments[idx].color_blend_op, BLEND_OP_MAX, RID());
  5476. state.colorBlendOp = blend_operations[p_blend_state.attachments[idx].color_blend_op];
  5477. ERR_FAIL_INDEX_V(p_blend_state.attachments[idx].src_alpha_blend_factor, BLEND_FACTOR_MAX, RID());
  5478. state.srcAlphaBlendFactor = blend_factors[p_blend_state.attachments[idx].src_alpha_blend_factor];
  5479. ERR_FAIL_INDEX_V(p_blend_state.attachments[idx].dst_alpha_blend_factor, BLEND_FACTOR_MAX, RID());
  5480. state.dstAlphaBlendFactor = blend_factors[p_blend_state.attachments[idx].dst_alpha_blend_factor];
  5481. ERR_FAIL_INDEX_V(p_blend_state.attachments[idx].alpha_blend_op, BLEND_OP_MAX, RID());
  5482. state.alphaBlendOp = blend_operations[p_blend_state.attachments[idx].alpha_blend_op];
  5483. state.colorWriteMask = 0;
  5484. if (p_blend_state.attachments[idx].write_r) {
  5485. state.colorWriteMask |= VK_COLOR_COMPONENT_R_BIT;
  5486. }
  5487. if (p_blend_state.attachments[idx].write_g) {
  5488. state.colorWriteMask |= VK_COLOR_COMPONENT_G_BIT;
  5489. }
  5490. if (p_blend_state.attachments[idx].write_b) {
  5491. state.colorWriteMask |= VK_COLOR_COMPONENT_B_BIT;
  5492. }
  5493. if (p_blend_state.attachments[idx].write_a) {
  5494. state.colorWriteMask |= VK_COLOR_COMPONENT_A_BIT;
  5495. }
  5496. attachment_states.push_back(state);
  5497. idx++;
  5498. }
  5499. }
  5500. ERR_FAIL_COND_V(attachment_states.size() != p_blend_state.attachments.size(), RID());
  5501. }
  5502. color_blend_state_create_info.attachmentCount = attachment_states.size();
  5503. color_blend_state_create_info.pAttachments = attachment_states.ptr();
  5504. color_blend_state_create_info.blendConstants[0] = p_blend_state.blend_constant.r;
  5505. color_blend_state_create_info.blendConstants[1] = p_blend_state.blend_constant.g;
  5506. color_blend_state_create_info.blendConstants[2] = p_blend_state.blend_constant.b;
  5507. color_blend_state_create_info.blendConstants[3] = p_blend_state.blend_constant.a;
  5508. //dynamic state
  5509. VkPipelineDynamicStateCreateInfo dynamic_state_create_info;
  5510. dynamic_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
  5511. dynamic_state_create_info.pNext = nullptr;
  5512. dynamic_state_create_info.flags = 0;
  5513. Vector<VkDynamicState> dynamic_states; //vulkan is weird..
  5514. dynamic_states.push_back(VK_DYNAMIC_STATE_VIEWPORT); //viewport and scissor are always dynamic
  5515. dynamic_states.push_back(VK_DYNAMIC_STATE_SCISSOR);
  5516. if (p_dynamic_state_flags & DYNAMIC_STATE_LINE_WIDTH) {
  5517. dynamic_states.push_back(VK_DYNAMIC_STATE_LINE_WIDTH);
  5518. }
  5519. if (p_dynamic_state_flags & DYNAMIC_STATE_DEPTH_BIAS) {
  5520. dynamic_states.push_back(VK_DYNAMIC_STATE_DEPTH_BIAS);
  5521. }
  5522. if (p_dynamic_state_flags & DYNAMIC_STATE_BLEND_CONSTANTS) {
  5523. dynamic_states.push_back(VK_DYNAMIC_STATE_BLEND_CONSTANTS);
  5524. }
  5525. if (p_dynamic_state_flags & DYNAMIC_STATE_DEPTH_BOUNDS) {
  5526. dynamic_states.push_back(VK_DYNAMIC_STATE_DEPTH_BOUNDS);
  5527. }
  5528. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_COMPARE_MASK) {
  5529. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK);
  5530. }
  5531. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_WRITE_MASK) {
  5532. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_WRITE_MASK);
  5533. }
  5534. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_REFERENCE) {
  5535. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_REFERENCE);
  5536. }
  5537. dynamic_state_create_info.dynamicStateCount = dynamic_states.size();
  5538. dynamic_state_create_info.pDynamicStates = dynamic_states.ptr();
  5539. //finally, pipeline create info
  5540. VkGraphicsPipelineCreateInfo graphics_pipeline_create_info;
  5541. graphics_pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  5542. graphics_pipeline_create_info.pNext = nullptr;
  5543. graphics_pipeline_create_info.flags = 0;
  5544. Vector<VkPipelineShaderStageCreateInfo> pipeline_stages = shader->pipeline_stages;
  5545. Vector<VkSpecializationInfo> specialization_info;
  5546. Vector<Vector<VkSpecializationMapEntry>> specialization_map_entries;
  5547. Vector<uint32_t> specialization_constant_data;
  5548. if (shader->specialization_constants.size()) {
  5549. specialization_constant_data.resize(shader->specialization_constants.size());
  5550. uint32_t *data_ptr = specialization_constant_data.ptrw();
  5551. specialization_info.resize(pipeline_stages.size());
  5552. specialization_map_entries.resize(pipeline_stages.size());
  5553. for (int i = 0; i < shader->specialization_constants.size(); i++) {
  5554. //see if overridden
  5555. const Shader::SpecializationConstant &sc = shader->specialization_constants[i];
  5556. data_ptr[i] = sc.constant.int_value; //just copy the 32 bits
  5557. for (int j = 0; j < p_specialization_constants.size(); j++) {
  5558. const PipelineSpecializationConstant &psc = p_specialization_constants[j];
  5559. if (psc.constant_id == sc.constant.constant_id) {
  5560. ERR_FAIL_COND_V_MSG(psc.type != sc.constant.type, RID(), "Specialization constant provided for id (" + itos(sc.constant.constant_id) + ") is of the wrong type.");
  5561. data_ptr[i] = psc.int_value;
  5562. break;
  5563. }
  5564. }
  5565. VkSpecializationMapEntry entry;
  5566. entry.constantID = sc.constant.constant_id;
  5567. entry.offset = i * sizeof(uint32_t);
  5568. entry.size = sizeof(uint32_t);
  5569. for (int j = 0; j < SHADER_STAGE_MAX; j++) {
  5570. if (sc.stage_flags & (1 << j)) {
  5571. VkShaderStageFlagBits stage = shader_stage_masks[j];
  5572. for (int k = 0; k < pipeline_stages.size(); k++) {
  5573. if (pipeline_stages[k].stage == stage) {
  5574. specialization_map_entries.write[k].push_back(entry);
  5575. }
  5576. }
  5577. }
  5578. }
  5579. }
  5580. for (int i = 0; i < pipeline_stages.size(); i++) {
  5581. if (specialization_map_entries[i].size()) {
  5582. specialization_info.write[i].dataSize = specialization_constant_data.size() * sizeof(uint32_t);
  5583. specialization_info.write[i].pData = data_ptr;
  5584. specialization_info.write[i].mapEntryCount = specialization_map_entries[i].size();
  5585. specialization_info.write[i].pMapEntries = specialization_map_entries[i].ptr();
  5586. pipeline_stages.write[i].pSpecializationInfo = specialization_info.ptr() + i;
  5587. }
  5588. }
  5589. }
  5590. graphics_pipeline_create_info.stageCount = pipeline_stages.size();
  5591. graphics_pipeline_create_info.pStages = pipeline_stages.ptr();
  5592. graphics_pipeline_create_info.pVertexInputState = &pipeline_vertex_input_state_create_info;
  5593. graphics_pipeline_create_info.pInputAssemblyState = &input_assembly_create_info;
  5594. graphics_pipeline_create_info.pTessellationState = &tessellation_create_info;
  5595. graphics_pipeline_create_info.pViewportState = &viewport_state_create_info;
  5596. graphics_pipeline_create_info.pRasterizationState = &rasterization_state_create_info;
  5597. graphics_pipeline_create_info.pMultisampleState = &multisample_state_create_info;
  5598. graphics_pipeline_create_info.pDepthStencilState = &depth_stencil_state_create_info;
  5599. graphics_pipeline_create_info.pColorBlendState = &color_blend_state_create_info;
  5600. graphics_pipeline_create_info.pDynamicState = &dynamic_state_create_info;
  5601. graphics_pipeline_create_info.layout = shader->pipeline_layout;
  5602. graphics_pipeline_create_info.renderPass = fb_format.render_pass;
  5603. graphics_pipeline_create_info.subpass = p_for_render_pass;
  5604. graphics_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE;
  5605. graphics_pipeline_create_info.basePipelineIndex = 0;
  5606. RenderPipeline pipeline;
  5607. VkResult err = vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &graphics_pipeline_create_info, nullptr, &pipeline.pipeline);
  5608. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateGraphicsPipelines failed with error " + itos(err) + " for shader '" + shader->name + "'.");
  5609. pipeline.set_formats = shader->set_formats;
  5610. pipeline.push_constant_stages = shader->push_constant.push_constants_vk_stage;
  5611. pipeline.pipeline_layout = shader->pipeline_layout;
  5612. pipeline.shader = p_shader;
  5613. pipeline.push_constant_size = shader->push_constant.push_constant_size;
  5614. #ifdef DEBUG_ENABLED
  5615. pipeline.validation.dynamic_state = p_dynamic_state_flags;
  5616. pipeline.validation.framebuffer_format = p_framebuffer_format;
  5617. pipeline.validation.render_pass = p_for_render_pass;
  5618. pipeline.validation.vertex_format = p_vertex_format;
  5619. pipeline.validation.uses_restart_indices = input_assembly_create_info.primitiveRestartEnable;
  5620. static const uint32_t primitive_divisor[RENDER_PRIMITIVE_MAX] = {
  5621. 1, 2, 1, 1, 1, 3, 1, 1, 1, 1, 1
  5622. };
  5623. pipeline.validation.primitive_divisor = primitive_divisor[p_render_primitive];
  5624. static const uint32_t primitive_minimum[RENDER_PRIMITIVE_MAX] = {
  5625. 1,
  5626. 2,
  5627. 2,
  5628. 2,
  5629. 2,
  5630. 3,
  5631. 3,
  5632. 3,
  5633. 3,
  5634. 3,
  5635. 1,
  5636. };
  5637. pipeline.validation.primitive_minimum = primitive_minimum[p_render_primitive];
  5638. #endif
  5639. //create ID to associate with this pipeline
  5640. RID id = render_pipeline_owner.make_rid(pipeline);
  5641. //now add all the dependencies
  5642. _add_dependency(id, p_shader);
  5643. return id;
  5644. }
  5645. bool RenderingDeviceVulkan::render_pipeline_is_valid(RID p_pipeline) {
  5646. _THREAD_SAFE_METHOD_
  5647. return render_pipeline_owner.owns(p_pipeline);
  5648. }
  5649. /**************************/
  5650. /**** COMPUTE PIPELINE ****/
  5651. /**************************/
  5652. RID RenderingDeviceVulkan::compute_pipeline_create(RID p_shader, const Vector<PipelineSpecializationConstant> &p_specialization_constants) {
  5653. _THREAD_SAFE_METHOD_
  5654. //needs a shader
  5655. Shader *shader = shader_owner.get_or_null(p_shader);
  5656. ERR_FAIL_COND_V(!shader, RID());
  5657. ERR_FAIL_COND_V_MSG(!shader->is_compute, RID(),
  5658. "Non-compute shaders can't be used in compute pipelines");
  5659. //finally, pipeline create info
  5660. VkComputePipelineCreateInfo compute_pipeline_create_info;
  5661. compute_pipeline_create_info.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
  5662. compute_pipeline_create_info.pNext = nullptr;
  5663. compute_pipeline_create_info.flags = 0;
  5664. compute_pipeline_create_info.stage = shader->pipeline_stages[0];
  5665. compute_pipeline_create_info.layout = shader->pipeline_layout;
  5666. compute_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE;
  5667. compute_pipeline_create_info.basePipelineIndex = 0;
  5668. VkSpecializationInfo specialization_info;
  5669. Vector<VkSpecializationMapEntry> specialization_map_entries;
  5670. Vector<uint32_t> specialization_constant_data;
  5671. if (shader->specialization_constants.size()) {
  5672. specialization_constant_data.resize(shader->specialization_constants.size());
  5673. uint32_t *data_ptr = specialization_constant_data.ptrw();
  5674. for (int i = 0; i < shader->specialization_constants.size(); i++) {
  5675. //see if overridden
  5676. const Shader::SpecializationConstant &sc = shader->specialization_constants[i];
  5677. data_ptr[i] = sc.constant.int_value; //just copy the 32 bits
  5678. for (int j = 0; j < p_specialization_constants.size(); j++) {
  5679. const PipelineSpecializationConstant &psc = p_specialization_constants[j];
  5680. if (psc.constant_id == sc.constant.constant_id) {
  5681. ERR_FAIL_COND_V_MSG(psc.type != sc.constant.type, RID(), "Specialization constant provided for id (" + itos(sc.constant.constant_id) + ") is of the wrong type.");
  5682. data_ptr[i] = sc.constant.int_value;
  5683. break;
  5684. }
  5685. }
  5686. VkSpecializationMapEntry entry;
  5687. entry.constantID = sc.constant.constant_id;
  5688. entry.offset = i * sizeof(uint32_t);
  5689. entry.size = sizeof(uint32_t);
  5690. specialization_map_entries.push_back(entry);
  5691. }
  5692. specialization_info.dataSize = specialization_constant_data.size() * sizeof(uint32_t);
  5693. specialization_info.pData = data_ptr;
  5694. specialization_info.mapEntryCount = specialization_map_entries.size();
  5695. specialization_info.pMapEntries = specialization_map_entries.ptr();
  5696. compute_pipeline_create_info.stage.pSpecializationInfo = &specialization_info;
  5697. }
  5698. ComputePipeline pipeline;
  5699. VkResult err = vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute_pipeline_create_info, nullptr, &pipeline.pipeline);
  5700. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateComputePipelines failed with error " + itos(err) + ".");
  5701. pipeline.set_formats = shader->set_formats;
  5702. pipeline.push_constant_stages = shader->push_constant.push_constants_vk_stage;
  5703. pipeline.pipeline_layout = shader->pipeline_layout;
  5704. pipeline.shader = p_shader;
  5705. pipeline.push_constant_size = shader->push_constant.push_constant_size;
  5706. pipeline.local_group_size[0] = shader->compute_local_size[0];
  5707. pipeline.local_group_size[1] = shader->compute_local_size[1];
  5708. pipeline.local_group_size[2] = shader->compute_local_size[2];
  5709. //create ID to associate with this pipeline
  5710. RID id = compute_pipeline_owner.make_rid(pipeline);
  5711. //now add all the dependencies
  5712. _add_dependency(id, p_shader);
  5713. return id;
  5714. }
  5715. bool RenderingDeviceVulkan::compute_pipeline_is_valid(RID p_pipeline) {
  5716. return compute_pipeline_owner.owns(p_pipeline);
  5717. }
  5718. /****************/
  5719. /**** SCREEN ****/
  5720. /****************/
  5721. int RenderingDeviceVulkan::screen_get_width(DisplayServer::WindowID p_screen) const {
  5722. _THREAD_SAFE_METHOD_
  5723. ERR_FAIL_COND_V_MSG(local_device.is_valid(), -1, "Local devices have no screen");
  5724. return context->window_get_width(p_screen);
  5725. }
  5726. int RenderingDeviceVulkan::screen_get_height(DisplayServer::WindowID p_screen) const {
  5727. _THREAD_SAFE_METHOD_
  5728. ERR_FAIL_COND_V_MSG(local_device.is_valid(), -1, "Local devices have no screen");
  5729. return context->window_get_height(p_screen);
  5730. }
  5731. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::screen_get_framebuffer_format() const {
  5732. _THREAD_SAFE_METHOD_
  5733. ERR_FAIL_COND_V_MSG(local_device.is_valid(), INVALID_ID, "Local devices have no screen");
  5734. //very hacky, but not used often per frame so I guess ok
  5735. VkFormat vkformat = context->get_screen_format();
  5736. DataFormat format = DATA_FORMAT_MAX;
  5737. for (int i = 0; i < DATA_FORMAT_MAX; i++) {
  5738. if (vkformat == vulkan_formats[i]) {
  5739. format = DataFormat(i);
  5740. break;
  5741. }
  5742. }
  5743. ERR_FAIL_COND_V(format == DATA_FORMAT_MAX, INVALID_ID);
  5744. AttachmentFormat attachment;
  5745. attachment.format = format;
  5746. attachment.samples = TEXTURE_SAMPLES_1;
  5747. attachment.usage_flags = TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  5748. Vector<AttachmentFormat> screen_attachment;
  5749. screen_attachment.push_back(attachment);
  5750. return const_cast<RenderingDeviceVulkan *>(this)->framebuffer_format_create(screen_attachment);
  5751. }
  5752. /*******************/
  5753. /**** DRAW LIST ****/
  5754. /*******************/
  5755. RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_begin_for_screen(DisplayServer::WindowID p_screen, const Color &p_clear_color) {
  5756. _THREAD_SAFE_METHOD_
  5757. ERR_FAIL_COND_V_MSG(local_device.is_valid(), INVALID_ID, "Local devices have no screen");
  5758. ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  5759. ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  5760. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  5761. if (!context->window_is_valid_swapchain(p_screen)) {
  5762. return INVALID_ID;
  5763. }
  5764. Size2i size = Size2i(context->window_get_width(p_screen), context->window_get_height(p_screen));
  5765. _draw_list_allocate(Rect2i(Vector2i(), size), 0, 0);
  5766. #ifdef DEBUG_ENABLED
  5767. draw_list_framebuffer_format = screen_get_framebuffer_format();
  5768. #endif
  5769. draw_list_subpass_count = 1;
  5770. VkRenderPassBeginInfo render_pass_begin;
  5771. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  5772. render_pass_begin.pNext = nullptr;
  5773. render_pass_begin.renderPass = context->window_get_render_pass(p_screen);
  5774. render_pass_begin.framebuffer = context->window_get_framebuffer(p_screen);
  5775. render_pass_begin.renderArea.extent.width = size.width;
  5776. render_pass_begin.renderArea.extent.height = size.height;
  5777. render_pass_begin.renderArea.offset.x = 0;
  5778. render_pass_begin.renderArea.offset.y = 0;
  5779. render_pass_begin.clearValueCount = 1;
  5780. VkClearValue clear_value;
  5781. clear_value.color.float32[0] = p_clear_color.r;
  5782. clear_value.color.float32[1] = p_clear_color.g;
  5783. clear_value.color.float32[2] = p_clear_color.b;
  5784. clear_value.color.float32[3] = p_clear_color.a;
  5785. render_pass_begin.pClearValues = &clear_value;
  5786. vkCmdBeginRenderPass(command_buffer, &render_pass_begin, VK_SUBPASS_CONTENTS_INLINE);
  5787. uint32_t size_x = screen_get_width(p_screen);
  5788. uint32_t size_y = screen_get_height(p_screen);
  5789. VkViewport viewport;
  5790. viewport.x = 0;
  5791. viewport.y = 0;
  5792. viewport.width = size_x;
  5793. viewport.height = size_y;
  5794. viewport.minDepth = 0;
  5795. viewport.maxDepth = 1.0;
  5796. vkCmdSetViewport(command_buffer, 0, 1, &viewport);
  5797. VkRect2D scissor;
  5798. scissor.offset.x = 0;
  5799. scissor.offset.y = 0;
  5800. scissor.extent.width = size_x;
  5801. scissor.extent.height = size_y;
  5802. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  5803. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  5804. }
  5805. Error RenderingDeviceVulkan::_draw_list_setup_framebuffer(Framebuffer *p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, VkFramebuffer *r_framebuffer, VkRenderPass *r_render_pass, uint32_t *r_subpass_count) {
  5806. Framebuffer::VersionKey vk;
  5807. vk.initial_color_action = p_initial_color_action;
  5808. vk.final_color_action = p_final_color_action;
  5809. vk.initial_depth_action = p_initial_depth_action;
  5810. vk.final_depth_action = p_final_depth_action;
  5811. vk.view_count = p_framebuffer->view_count;
  5812. if (!p_framebuffer->framebuffers.has(vk)) {
  5813. //need to create this version
  5814. Framebuffer::Version version;
  5815. version.render_pass = _render_pass_create(framebuffer_formats[p_framebuffer->format_id].E->key().attachments, framebuffer_formats[p_framebuffer->format_id].E->key().passes, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_framebuffer->view_count);
  5816. VkFramebufferCreateInfo framebuffer_create_info;
  5817. framebuffer_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  5818. framebuffer_create_info.pNext = nullptr;
  5819. framebuffer_create_info.flags = 0;
  5820. framebuffer_create_info.renderPass = version.render_pass;
  5821. Vector<VkImageView> attachments;
  5822. for (int i = 0; i < p_framebuffer->texture_ids.size(); i++) {
  5823. Texture *texture = texture_owner.get_or_null(p_framebuffer->texture_ids[i]);
  5824. ERR_FAIL_COND_V(!texture, ERR_BUG);
  5825. attachments.push_back(texture->view);
  5826. ERR_FAIL_COND_V(texture->width != p_framebuffer->size.width, ERR_BUG);
  5827. ERR_FAIL_COND_V(texture->height != p_framebuffer->size.height, ERR_BUG);
  5828. }
  5829. framebuffer_create_info.attachmentCount = attachments.size();
  5830. framebuffer_create_info.pAttachments = attachments.ptr();
  5831. framebuffer_create_info.width = p_framebuffer->size.width;
  5832. framebuffer_create_info.height = p_framebuffer->size.height;
  5833. framebuffer_create_info.layers = 1;
  5834. VkResult err = vkCreateFramebuffer(device, &framebuffer_create_info, nullptr, &version.framebuffer);
  5835. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vkCreateFramebuffer failed with error " + itos(err) + ".");
  5836. version.subpass_count = framebuffer_formats[p_framebuffer->format_id].E->key().passes.size();
  5837. p_framebuffer->framebuffers.insert(vk, version);
  5838. }
  5839. const Framebuffer::Version &version = p_framebuffer->framebuffers[vk];
  5840. *r_framebuffer = version.framebuffer;
  5841. *r_render_pass = version.render_pass;
  5842. *r_subpass_count = version.subpass_count;
  5843. return OK;
  5844. }
  5845. Error RenderingDeviceVulkan::_draw_list_render_pass_begin(Framebuffer *framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_colors, float p_clear_depth, uint32_t p_clear_stencil, Point2i viewport_offset, Point2i viewport_size, VkFramebuffer vkframebuffer, VkRenderPass render_pass, VkCommandBuffer command_buffer, VkSubpassContents subpass_contents, const Vector<RID> &p_storage_textures) {
  5846. VkRenderPassBeginInfo render_pass_begin;
  5847. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  5848. render_pass_begin.pNext = nullptr;
  5849. render_pass_begin.renderPass = render_pass;
  5850. render_pass_begin.framebuffer = vkframebuffer;
  5851. /*
  5852. * Given how API works, it makes sense to always fully operate on the whole framebuffer.
  5853. * This allows better continue operations for operations like shadowmapping.
  5854. render_pass_begin.renderArea.extent.width = viewport_size.width;
  5855. render_pass_begin.renderArea.extent.height = viewport_size.height;
  5856. render_pass_begin.renderArea.offset.x = viewport_offset.x;
  5857. render_pass_begin.renderArea.offset.y = viewport_offset.y;
  5858. */
  5859. render_pass_begin.renderArea.extent.width = framebuffer->size.width;
  5860. render_pass_begin.renderArea.extent.height = framebuffer->size.height;
  5861. render_pass_begin.renderArea.offset.x = 0;
  5862. render_pass_begin.renderArea.offset.y = 0;
  5863. Vector<VkClearValue> clear_values;
  5864. clear_values.resize(framebuffer->texture_ids.size());
  5865. {
  5866. int color_index = 0;
  5867. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  5868. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  5869. VkClearValue clear_value;
  5870. if (color_index < p_clear_colors.size() && texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  5871. ERR_FAIL_INDEX_V(color_index, p_clear_colors.size(), ERR_BUG); //a bug
  5872. Color clear_color = p_clear_colors[color_index];
  5873. clear_value.color.float32[0] = clear_color.r;
  5874. clear_value.color.float32[1] = clear_color.g;
  5875. clear_value.color.float32[2] = clear_color.b;
  5876. clear_value.color.float32[3] = clear_color.a;
  5877. color_index++;
  5878. } else if (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  5879. clear_value.depthStencil.depth = p_clear_depth;
  5880. clear_value.depthStencil.stencil = p_clear_stencil;
  5881. } else {
  5882. clear_value.color.float32[0] = 0;
  5883. clear_value.color.float32[1] = 0;
  5884. clear_value.color.float32[2] = 0;
  5885. clear_value.color.float32[3] = 0;
  5886. }
  5887. clear_values.write[i] = clear_value;
  5888. }
  5889. }
  5890. render_pass_begin.clearValueCount = clear_values.size();
  5891. render_pass_begin.pClearValues = clear_values.ptr();
  5892. for (int i = 0; i < p_storage_textures.size(); i++) {
  5893. Texture *texture = texture_owner.get_or_null(p_storage_textures[i]);
  5894. ERR_CONTINUE_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), "Supplied storage texture " + itos(i) + " for draw list is not set to be used for storage.");
  5895. if (texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT) {
  5896. //must change layout to general
  5897. VkImageMemoryBarrier image_memory_barrier;
  5898. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  5899. image_memory_barrier.pNext = nullptr;
  5900. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  5901. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  5902. image_memory_barrier.oldLayout = texture->layout;
  5903. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  5904. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  5905. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  5906. image_memory_barrier.image = texture->image;
  5907. image_memory_barrier.subresourceRange.aspectMask = texture->read_aspect_mask;
  5908. image_memory_barrier.subresourceRange.baseMipLevel = texture->base_mipmap;
  5909. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  5910. image_memory_barrier.subresourceRange.baseArrayLayer = texture->base_layer;
  5911. image_memory_barrier.subresourceRange.layerCount = texture->layers;
  5912. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  5913. texture->layout = VK_IMAGE_LAYOUT_GENERAL;
  5914. draw_list_storage_textures.push_back(p_storage_textures[i]);
  5915. }
  5916. }
  5917. vkCmdBeginRenderPass(command_buffer, &render_pass_begin, subpass_contents);
  5918. //mark textures as bound
  5919. draw_list_bound_textures.clear();
  5920. draw_list_unbind_color_textures = p_final_color_action != FINAL_ACTION_CONTINUE;
  5921. draw_list_unbind_depth_textures = p_final_depth_action != FINAL_ACTION_CONTINUE;
  5922. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  5923. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  5924. texture->bound = true;
  5925. draw_list_bound_textures.push_back(framebuffer->texture_ids[i]);
  5926. }
  5927. return OK;
  5928. }
  5929. void RenderingDeviceVulkan::_draw_list_insert_clear_region(DrawList *draw_list, Framebuffer *framebuffer, Point2i viewport_offset, Point2i viewport_size, bool p_clear_color, const Vector<Color> &p_clear_colors, bool p_clear_depth, float p_depth, uint32_t p_stencil) {
  5930. Vector<VkClearAttachment> clear_attachments;
  5931. int color_index = 0;
  5932. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  5933. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  5934. VkClearAttachment clear_at = {};
  5935. if (p_clear_color && texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  5936. ERR_FAIL_INDEX(color_index, p_clear_colors.size()); //a bug
  5937. Color clear_color = p_clear_colors[color_index];
  5938. clear_at.clearValue.color.float32[0] = clear_color.r;
  5939. clear_at.clearValue.color.float32[1] = clear_color.g;
  5940. clear_at.clearValue.color.float32[2] = clear_color.b;
  5941. clear_at.clearValue.color.float32[3] = clear_color.a;
  5942. clear_at.colorAttachment = color_index++;
  5943. clear_at.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  5944. } else if (p_clear_depth && texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  5945. clear_at.clearValue.depthStencil.depth = p_depth;
  5946. clear_at.clearValue.depthStencil.stencil = p_stencil;
  5947. clear_at.colorAttachment = 0;
  5948. clear_at.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  5949. if (format_has_stencil(texture->format)) {
  5950. clear_at.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  5951. }
  5952. } else {
  5953. ERR_CONTINUE(true);
  5954. }
  5955. clear_attachments.push_back(clear_at);
  5956. }
  5957. VkClearRect cr;
  5958. cr.baseArrayLayer = 0;
  5959. cr.layerCount = 1;
  5960. cr.rect.offset.x = viewport_offset.x;
  5961. cr.rect.offset.y = viewport_offset.y;
  5962. cr.rect.extent.width = viewport_size.width;
  5963. cr.rect.extent.height = viewport_size.height;
  5964. vkCmdClearAttachments(draw_list->command_buffer, clear_attachments.size(), clear_attachments.ptr(), 1, &cr);
  5965. }
  5966. RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_begin(RID p_framebuffer, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const Vector<RID> &p_storage_textures) {
  5967. _THREAD_SAFE_METHOD_
  5968. ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  5969. ERR_FAIL_COND_V_MSG(compute_list != nullptr && !compute_list->state.allow_draw_overlap, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  5970. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  5971. ERR_FAIL_COND_V(!framebuffer, INVALID_ID);
  5972. Point2i viewport_offset;
  5973. Point2i viewport_size = framebuffer->size;
  5974. bool needs_clear_color = false;
  5975. bool needs_clear_depth = false;
  5976. if (p_region != Rect2() && p_region != Rect2(Vector2(), viewport_size)) { //check custom region
  5977. Rect2i viewport(viewport_offset, viewport_size);
  5978. Rect2i regioni = p_region;
  5979. if (!(regioni.position.x >= viewport.position.x) && (regioni.position.y >= viewport.position.y) &&
  5980. ((regioni.position.x + regioni.size.x) <= (viewport.position.x + viewport.size.x)) &&
  5981. ((regioni.position.y + regioni.size.y) <= (viewport.position.y + viewport.size.y))) {
  5982. ERR_FAIL_V_MSG(INVALID_ID, "When supplying a custom region, it must be contained within the framebuffer rectangle");
  5983. }
  5984. viewport_offset = regioni.position;
  5985. viewport_size = regioni.size;
  5986. if (p_initial_color_action == INITIAL_ACTION_CLEAR_REGION_CONTINUE) {
  5987. needs_clear_color = true;
  5988. p_initial_color_action = INITIAL_ACTION_CONTINUE;
  5989. }
  5990. if (p_initial_depth_action == INITIAL_ACTION_CLEAR_REGION_CONTINUE) {
  5991. needs_clear_depth = true;
  5992. p_initial_depth_action = INITIAL_ACTION_CONTINUE;
  5993. }
  5994. if (p_initial_color_action == INITIAL_ACTION_CLEAR_REGION) {
  5995. needs_clear_color = true;
  5996. p_initial_color_action = INITIAL_ACTION_KEEP;
  5997. }
  5998. if (p_initial_depth_action == INITIAL_ACTION_CLEAR_REGION) {
  5999. needs_clear_depth = true;
  6000. p_initial_depth_action = INITIAL_ACTION_KEEP;
  6001. }
  6002. }
  6003. if (p_initial_color_action == INITIAL_ACTION_CLEAR) { //check clear values
  6004. int color_count = 0;
  6005. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  6006. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  6007. if (texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  6008. color_count++;
  6009. }
  6010. }
  6011. ERR_FAIL_COND_V_MSG(p_clear_color_values.size() != color_count, INVALID_ID,
  6012. "Clear color values supplied (" + itos(p_clear_color_values.size()) + ") differ from the amount required for framebuffer color attachments (" + itos(color_count) + ").");
  6013. }
  6014. VkFramebuffer vkframebuffer;
  6015. VkRenderPass render_pass;
  6016. Error err = _draw_list_setup_framebuffer(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, &vkframebuffer, &render_pass, &draw_list_subpass_count);
  6017. ERR_FAIL_COND_V(err != OK, INVALID_ID);
  6018. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  6019. err = _draw_list_render_pass_begin(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, viewport_offset, viewport_size, vkframebuffer, render_pass, command_buffer, VK_SUBPASS_CONTENTS_INLINE, p_storage_textures);
  6020. if (err != OK) {
  6021. return INVALID_ID;
  6022. }
  6023. draw_list_render_pass = render_pass;
  6024. draw_list_vkframebuffer = vkframebuffer;
  6025. _draw_list_allocate(Rect2i(viewport_offset, viewport_size), 0, 0);
  6026. #ifdef DEBUG_ENABLED
  6027. draw_list_framebuffer_format = framebuffer->format_id;
  6028. #endif
  6029. draw_list_current_subpass = 0;
  6030. if (needs_clear_color || needs_clear_depth) {
  6031. _draw_list_insert_clear_region(draw_list, framebuffer, viewport_offset, viewport_size, needs_clear_color, p_clear_color_values, needs_clear_depth, p_clear_depth, p_clear_stencil);
  6032. }
  6033. VkViewport viewport;
  6034. viewport.x = viewport_offset.x;
  6035. viewport.y = viewport_offset.y;
  6036. viewport.width = viewport_size.width;
  6037. viewport.height = viewport_size.height;
  6038. viewport.minDepth = 0;
  6039. viewport.maxDepth = 1.0;
  6040. vkCmdSetViewport(command_buffer, 0, 1, &viewport);
  6041. VkRect2D scissor;
  6042. scissor.offset.x = viewport_offset.x;
  6043. scissor.offset.y = viewport_offset.y;
  6044. scissor.extent.width = viewport_size.width;
  6045. scissor.extent.height = viewport_size.height;
  6046. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  6047. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  6048. }
  6049. Error RenderingDeviceVulkan::draw_list_begin_split(RID p_framebuffer, uint32_t p_splits, DrawListID *r_split_ids, InitialAction p_initial_color_action, FinalAction p_final_color_action, InitialAction p_initial_depth_action, FinalAction p_final_depth_action, const Vector<Color> &p_clear_color_values, float p_clear_depth, uint32_t p_clear_stencil, const Rect2 &p_region, const Vector<RID> &p_storage_textures) {
  6050. _THREAD_SAFE_METHOD_
  6051. ERR_FAIL_COND_V(p_splits < 1, ERR_INVALID_DECLARATION);
  6052. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  6053. ERR_FAIL_COND_V(!framebuffer, ERR_INVALID_DECLARATION);
  6054. Point2i viewport_offset;
  6055. Point2i viewport_size = framebuffer->size;
  6056. bool needs_clear_color = false;
  6057. bool needs_clear_depth = false;
  6058. if (p_region != Rect2() && p_region != Rect2(Vector2(), viewport_size)) { //check custom region
  6059. Rect2i viewport(viewport_offset, viewport_size);
  6060. Rect2i regioni = p_region;
  6061. if (!(regioni.position.x >= viewport.position.x) && (regioni.position.y >= viewport.position.y) &&
  6062. ((regioni.position.x + regioni.size.x) <= (viewport.position.x + viewport.size.x)) &&
  6063. ((regioni.position.y + regioni.size.y) <= (viewport.position.y + viewport.size.y))) {
  6064. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "When supplying a custom region, it must be contained within the framebuffer rectangle");
  6065. }
  6066. viewport_offset = regioni.position;
  6067. viewport_size = regioni.size;
  6068. if (p_initial_color_action == INITIAL_ACTION_CLEAR_REGION) {
  6069. needs_clear_color = true;
  6070. p_initial_color_action = INITIAL_ACTION_KEEP;
  6071. }
  6072. if (p_initial_depth_action == INITIAL_ACTION_CLEAR_REGION) {
  6073. needs_clear_depth = true;
  6074. p_initial_depth_action = INITIAL_ACTION_KEEP;
  6075. }
  6076. }
  6077. if (p_initial_color_action == INITIAL_ACTION_CLEAR) { //check clear values
  6078. int color_count = 0;
  6079. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  6080. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  6081. if (texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  6082. color_count++;
  6083. }
  6084. }
  6085. ERR_FAIL_COND_V_MSG(p_clear_color_values.size() != color_count, ERR_INVALID_PARAMETER,
  6086. "Clear color values supplied (" + itos(p_clear_color_values.size()) + ") differ from the amount required for framebuffer (" + itos(color_count) + ").");
  6087. }
  6088. VkFramebuffer vkframebuffer;
  6089. VkRenderPass render_pass;
  6090. Error err = _draw_list_setup_framebuffer(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, &vkframebuffer, &render_pass, &draw_list_subpass_count);
  6091. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  6092. VkCommandBuffer frame_command_buffer = frames[frame].draw_command_buffer;
  6093. err = _draw_list_render_pass_begin(framebuffer, p_initial_color_action, p_final_color_action, p_initial_depth_action, p_final_depth_action, p_clear_color_values, p_clear_depth, p_clear_stencil, viewport_offset, viewport_size, vkframebuffer, render_pass, frame_command_buffer, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS, p_storage_textures);
  6094. if (err != OK) {
  6095. return ERR_CANT_CREATE;
  6096. }
  6097. draw_list_current_subpass = 0;
  6098. #ifdef DEBUG_ENABLED
  6099. draw_list_framebuffer_format = framebuffer->format_id;
  6100. #endif
  6101. draw_list_render_pass = render_pass;
  6102. draw_list_vkframebuffer = vkframebuffer;
  6103. err = _draw_list_allocate(Rect2i(viewport_offset, viewport_size), p_splits, 0);
  6104. if (err != OK) {
  6105. return err;
  6106. }
  6107. if (needs_clear_color || needs_clear_depth) {
  6108. _draw_list_insert_clear_region(&draw_list[0], framebuffer, viewport_offset, viewport_size, needs_clear_color, p_clear_color_values, needs_clear_depth, p_clear_depth, p_clear_stencil);
  6109. }
  6110. for (uint32_t i = 0; i < p_splits; i++) {
  6111. VkViewport viewport;
  6112. viewport.x = viewport_offset.x;
  6113. viewport.y = viewport_offset.y;
  6114. viewport.width = viewport_size.width;
  6115. viewport.height = viewport_size.height;
  6116. viewport.minDepth = 0;
  6117. viewport.maxDepth = 1.0;
  6118. vkCmdSetViewport(draw_list[i].command_buffer, 0, 1, &viewport);
  6119. VkRect2D scissor;
  6120. scissor.offset.x = viewport_offset.x;
  6121. scissor.offset.y = viewport_offset.y;
  6122. scissor.extent.width = viewport_size.width;
  6123. scissor.extent.height = viewport_size.height;
  6124. vkCmdSetScissor(draw_list[i].command_buffer, 0, 1, &scissor);
  6125. r_split_ids[i] = (int64_t(ID_TYPE_SPLIT_DRAW_LIST) << ID_BASE_SHIFT) + i;
  6126. }
  6127. return OK;
  6128. }
  6129. RenderingDeviceVulkan::DrawList *RenderingDeviceVulkan::_get_draw_list_ptr(DrawListID p_id) {
  6130. if (p_id < 0) {
  6131. return nullptr;
  6132. }
  6133. if (!draw_list) {
  6134. return nullptr;
  6135. } else if (p_id == (int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT)) {
  6136. if (draw_list_split) {
  6137. return nullptr;
  6138. }
  6139. return draw_list;
  6140. } else if (p_id >> DrawListID(ID_BASE_SHIFT) == ID_TYPE_SPLIT_DRAW_LIST) {
  6141. if (!draw_list_split) {
  6142. return nullptr;
  6143. }
  6144. uint64_t index = p_id & ((DrawListID(1) << DrawListID(ID_BASE_SHIFT)) - 1); //mask
  6145. if (index >= draw_list_count) {
  6146. return nullptr;
  6147. }
  6148. return &draw_list[index];
  6149. } else {
  6150. return nullptr;
  6151. }
  6152. }
  6153. void RenderingDeviceVulkan::draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline) {
  6154. DrawList *dl = _get_draw_list_ptr(p_list);
  6155. ERR_FAIL_COND(!dl);
  6156. #ifdef DEBUG_ENABLED
  6157. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6158. #endif
  6159. const RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_render_pipeline);
  6160. ERR_FAIL_COND(!pipeline);
  6161. #ifdef DEBUG_ENABLED
  6162. ERR_FAIL_COND(pipeline->validation.framebuffer_format != draw_list_framebuffer_format && pipeline->validation.render_pass != draw_list_current_subpass);
  6163. #endif
  6164. if (p_render_pipeline == dl->state.pipeline) {
  6165. return; //redundant state, return.
  6166. }
  6167. dl->state.pipeline = p_render_pipeline;
  6168. dl->state.pipeline_layout = pipeline->pipeline_layout;
  6169. vkCmdBindPipeline(dl->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline);
  6170. if (dl->state.pipeline_shader != pipeline->shader) {
  6171. // shader changed, so descriptor sets may become incompatible.
  6172. //go through ALL sets, and unbind them (and all those above) if the format is different
  6173. uint32_t pcount = pipeline->set_formats.size(); //formats count in this pipeline
  6174. dl->state.set_count = MAX(dl->state.set_count, pcount);
  6175. const uint32_t *pformats = pipeline->set_formats.ptr(); //pipeline set formats
  6176. bool sets_valid = true; //once invalid, all above become invalid
  6177. for (uint32_t i = 0; i < pcount; i++) {
  6178. //if a part of the format is different, invalidate it (and the rest)
  6179. if (!sets_valid || dl->state.sets[i].pipeline_expected_format != pformats[i]) {
  6180. dl->state.sets[i].bound = false;
  6181. dl->state.sets[i].pipeline_expected_format = pformats[i];
  6182. sets_valid = false;
  6183. }
  6184. }
  6185. for (uint32_t i = pcount; i < dl->state.set_count; i++) {
  6186. //unbind the ones above (not used) if exist
  6187. dl->state.sets[i].bound = false;
  6188. }
  6189. dl->state.set_count = pcount; //update set count
  6190. if (pipeline->push_constant_size) {
  6191. dl->state.pipeline_push_constant_stages = pipeline->push_constant_stages;
  6192. #ifdef DEBUG_ENABLED
  6193. dl->validation.pipeline_push_constant_supplied = false;
  6194. #endif
  6195. }
  6196. dl->state.pipeline_shader = pipeline->shader;
  6197. }
  6198. #ifdef DEBUG_ENABLED
  6199. //update render pass pipeline info
  6200. dl->validation.pipeline_active = true;
  6201. dl->validation.pipeline_dynamic_state = pipeline->validation.dynamic_state;
  6202. dl->validation.pipeline_vertex_format = pipeline->validation.vertex_format;
  6203. dl->validation.pipeline_uses_restart_indices = pipeline->validation.uses_restart_indices;
  6204. dl->validation.pipeline_primitive_divisor = pipeline->validation.primitive_divisor;
  6205. dl->validation.pipeline_primitive_minimum = pipeline->validation.primitive_minimum;
  6206. dl->validation.pipeline_push_constant_size = pipeline->push_constant_size;
  6207. #endif
  6208. }
  6209. void RenderingDeviceVulkan::draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index) {
  6210. #ifdef DEBUG_ENABLED
  6211. ERR_FAIL_COND_MSG(p_index >= limits.maxBoundDescriptorSets || p_index >= MAX_UNIFORM_SETS,
  6212. "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(limits.maxBoundDescriptorSets) + ").");
  6213. #endif
  6214. DrawList *dl = _get_draw_list_ptr(p_list);
  6215. ERR_FAIL_COND(!dl);
  6216. #ifdef DEBUG_ENABLED
  6217. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6218. #endif
  6219. const UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set);
  6220. ERR_FAIL_COND(!uniform_set);
  6221. if (p_index > dl->state.set_count) {
  6222. dl->state.set_count = p_index;
  6223. }
  6224. dl->state.sets[p_index].descriptor_set = uniform_set->descriptor_set; //update set pointer
  6225. dl->state.sets[p_index].bound = false; //needs rebind
  6226. dl->state.sets[p_index].uniform_set_format = uniform_set->format;
  6227. dl->state.sets[p_index].uniform_set = p_uniform_set;
  6228. uint32_t mst_count = uniform_set->mutable_storage_textures.size();
  6229. if (mst_count) {
  6230. Texture **mst_textures = const_cast<UniformSet *>(uniform_set)->mutable_storage_textures.ptrw();
  6231. for (uint32_t i = 0; i < mst_count; i++) {
  6232. if (mst_textures[i]->used_in_frame != frames_drawn) {
  6233. mst_textures[i]->used_in_frame = frames_drawn;
  6234. mst_textures[i]->used_in_transfer = false;
  6235. mst_textures[i]->used_in_compute = false;
  6236. }
  6237. mst_textures[i]->used_in_raster = true;
  6238. }
  6239. }
  6240. #ifdef DEBUG_ENABLED
  6241. { //validate that textures bound are not attached as framebuffer bindings
  6242. uint32_t attachable_count = uniform_set->attachable_textures.size();
  6243. const UniformSet::AttachableTexture *attachable_ptr = uniform_set->attachable_textures.ptr();
  6244. uint32_t bound_count = draw_list_bound_textures.size();
  6245. const RID *bound_ptr = draw_list_bound_textures.ptr();
  6246. for (uint32_t i = 0; i < attachable_count; i++) {
  6247. for (uint32_t j = 0; j < bound_count; j++) {
  6248. ERR_FAIL_COND_MSG(attachable_ptr[i].texture == bound_ptr[j],
  6249. "Attempted to use the same texture in framebuffer attachment and a uniform (set: " + itos(p_index) + ", binding: " + itos(attachable_ptr[i].bind) + "), this is not allowed.");
  6250. }
  6251. }
  6252. }
  6253. #endif
  6254. }
  6255. void RenderingDeviceVulkan::draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array) {
  6256. DrawList *dl = _get_draw_list_ptr(p_list);
  6257. ERR_FAIL_COND(!dl);
  6258. #ifdef DEBUG_ENABLED
  6259. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6260. #endif
  6261. const VertexArray *vertex_array = vertex_array_owner.get_or_null(p_vertex_array);
  6262. ERR_FAIL_COND(!vertex_array);
  6263. if (dl->state.vertex_array == p_vertex_array) {
  6264. return; //already set
  6265. }
  6266. dl->state.vertex_array = p_vertex_array;
  6267. #ifdef DEBUG_ENABLED
  6268. dl->validation.vertex_format = vertex_array->description;
  6269. dl->validation.vertex_max_instances_allowed = vertex_array->max_instances_allowed;
  6270. #endif
  6271. dl->validation.vertex_array_size = vertex_array->vertex_count;
  6272. vkCmdBindVertexBuffers(dl->command_buffer, 0, vertex_array->buffers.size(), vertex_array->buffers.ptr(), vertex_array->offsets.ptr());
  6273. }
  6274. void RenderingDeviceVulkan::draw_list_bind_index_array(DrawListID p_list, RID p_index_array) {
  6275. DrawList *dl = _get_draw_list_ptr(p_list);
  6276. ERR_FAIL_COND(!dl);
  6277. #ifdef DEBUG_ENABLED
  6278. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6279. #endif
  6280. const IndexArray *index_array = index_array_owner.get_or_null(p_index_array);
  6281. ERR_FAIL_COND(!index_array);
  6282. if (dl->state.index_array == p_index_array) {
  6283. return; //already set
  6284. }
  6285. dl->state.index_array = p_index_array;
  6286. #ifdef DEBUG_ENABLED
  6287. dl->validation.index_array_max_index = index_array->max_index;
  6288. #endif
  6289. dl->validation.index_array_size = index_array->indices;
  6290. dl->validation.index_array_offset = index_array->offset;
  6291. vkCmdBindIndexBuffer(dl->command_buffer, index_array->buffer, index_array->offset, index_array->index_type);
  6292. }
  6293. void RenderingDeviceVulkan::draw_list_set_line_width(DrawListID p_list, float p_width) {
  6294. DrawList *dl = _get_draw_list_ptr(p_list);
  6295. ERR_FAIL_COND(!dl);
  6296. #ifdef DEBUG_ENABLED
  6297. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6298. #endif
  6299. vkCmdSetLineWidth(dl->command_buffer, p_width);
  6300. }
  6301. void RenderingDeviceVulkan::draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size) {
  6302. DrawList *dl = _get_draw_list_ptr(p_list);
  6303. ERR_FAIL_COND(!dl);
  6304. #ifdef DEBUG_ENABLED
  6305. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6306. #endif
  6307. #ifdef DEBUG_ENABLED
  6308. ERR_FAIL_COND_MSG(p_data_size != dl->validation.pipeline_push_constant_size,
  6309. "This render pipeline requires (" + itos(dl->validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");
  6310. #endif
  6311. vkCmdPushConstants(dl->command_buffer, dl->state.pipeline_layout, dl->state.pipeline_push_constant_stages, 0, p_data_size, p_data);
  6312. #ifdef DEBUG_ENABLED
  6313. dl->validation.pipeline_push_constant_supplied = true;
  6314. #endif
  6315. }
  6316. void RenderingDeviceVulkan::draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances, uint32_t p_procedural_vertices) {
  6317. DrawList *dl = _get_draw_list_ptr(p_list);
  6318. ERR_FAIL_COND(!dl);
  6319. #ifdef DEBUG_ENABLED
  6320. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6321. #endif
  6322. #ifdef DEBUG_ENABLED
  6323. ERR_FAIL_COND_MSG(!dl->validation.pipeline_active,
  6324. "No render pipeline was set before attempting to draw.");
  6325. if (dl->validation.pipeline_vertex_format != INVALID_ID) {
  6326. //pipeline uses vertices, validate format
  6327. ERR_FAIL_COND_MSG(dl->validation.vertex_format == INVALID_ID,
  6328. "No vertex array was bound, and render pipeline expects vertices.");
  6329. //make sure format is right
  6330. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format != dl->validation.vertex_format,
  6331. "The vertex format used to create the pipeline does not match the vertex format bound.");
  6332. //make sure number of instances is valid
  6333. ERR_FAIL_COND_MSG(p_instances > dl->validation.vertex_max_instances_allowed,
  6334. "Number of instances requested (" + itos(p_instances) + " is larger than the maximum number supported by the bound vertex array (" + itos(dl->validation.vertex_max_instances_allowed) + ").");
  6335. }
  6336. if (dl->validation.pipeline_push_constant_size > 0) {
  6337. //using push constants, check that they were supplied
  6338. ERR_FAIL_COND_MSG(!dl->validation.pipeline_push_constant_supplied,
  6339. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  6340. }
  6341. #endif
  6342. //Bind descriptor sets
  6343. for (uint32_t i = 0; i < dl->state.set_count; i++) {
  6344. if (dl->state.sets[i].pipeline_expected_format == 0) {
  6345. continue; //nothing expected by this pipeline
  6346. }
  6347. #ifdef DEBUG_ENABLED
  6348. if (dl->state.sets[i].pipeline_expected_format != dl->state.sets[i].uniform_set_format) {
  6349. if (dl->state.sets[i].uniform_set_format == 0) {
  6350. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  6351. } else if (uniform_set_owner.owns(dl->state.sets[i].uniform_set)) {
  6352. UniformSet *us = uniform_set_owner.get_or_null(dl->state.sets[i].uniform_set);
  6353. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(dl->state.pipeline_shader));
  6354. } else {
  6355. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(dl->state.pipeline_shader));
  6356. }
  6357. }
  6358. #endif
  6359. if (!dl->state.sets[i].bound) {
  6360. //All good, see if this requires re-binding
  6361. vkCmdBindDescriptorSets(dl->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, dl->state.pipeline_layout, i, 1, &dl->state.sets[i].descriptor_set, 0, nullptr);
  6362. dl->state.sets[i].bound = true;
  6363. }
  6364. }
  6365. if (p_use_indices) {
  6366. #ifdef DEBUG_ENABLED
  6367. ERR_FAIL_COND_MSG(p_procedural_vertices > 0,
  6368. "Procedural vertices can't be used together with indices.");
  6369. ERR_FAIL_COND_MSG(!dl->validation.index_array_size,
  6370. "Draw command requested indices, but no index buffer was set.");
  6371. if (dl->validation.pipeline_vertex_format != INVALID_ID) {
  6372. //uses vertices, do some vertex validations
  6373. ERR_FAIL_COND_MSG(dl->validation.vertex_array_size < dl->validation.index_array_max_index,
  6374. "Index array references (max index: " + itos(dl->validation.index_array_max_index) + ") indices beyond the vertex array size (" + itos(dl->validation.vertex_array_size) + ").");
  6375. }
  6376. ERR_FAIL_COND_MSG(dl->validation.pipeline_uses_restart_indices != dl->validation.index_buffer_uses_restart_indices,
  6377. "The usage of restart indices in index buffer does not match the render primitive in the pipeline.");
  6378. #endif
  6379. uint32_t to_draw = dl->validation.index_array_size;
  6380. #ifdef DEBUG_ENABLED
  6381. ERR_FAIL_COND_MSG(to_draw < dl->validation.pipeline_primitive_minimum,
  6382. "Too few indices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(dl->validation.pipeline_primitive_minimum) + ").");
  6383. ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0,
  6384. "Index amount (" + itos(to_draw) + ") must be a multiple of the amount of indices required by the render primitive (" + itos(dl->validation.pipeline_primitive_divisor) + ").");
  6385. #endif
  6386. vkCmdDrawIndexed(dl->command_buffer, to_draw, p_instances, dl->validation.index_array_offset, 0, 0);
  6387. } else {
  6388. uint32_t to_draw;
  6389. if (p_procedural_vertices > 0) {
  6390. #ifdef DEBUG_ENABLED
  6391. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format != INVALID_ID,
  6392. "Procedural vertices requested, but pipeline expects a vertex array.");
  6393. #endif
  6394. to_draw = p_procedural_vertices;
  6395. } else {
  6396. #ifdef DEBUG_ENABLED
  6397. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format == INVALID_ID,
  6398. "Draw command lacks indices, but pipeline format does not use vertices.");
  6399. #endif
  6400. to_draw = dl->validation.vertex_array_size;
  6401. }
  6402. #ifdef DEBUG_ENABLED
  6403. ERR_FAIL_COND_MSG(to_draw < dl->validation.pipeline_primitive_minimum,
  6404. "Too few vertices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(dl->validation.pipeline_primitive_minimum) + ").");
  6405. ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0,
  6406. "Vertex amount (" + itos(to_draw) + ") must be a multiple of the amount of vertices required by the render primitive (" + itos(dl->validation.pipeline_primitive_divisor) + ").");
  6407. #endif
  6408. vkCmdDraw(dl->command_buffer, to_draw, p_instances, 0, 0);
  6409. }
  6410. }
  6411. void RenderingDeviceVulkan::draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect) {
  6412. DrawList *dl = _get_draw_list_ptr(p_list);
  6413. ERR_FAIL_COND(!dl);
  6414. #ifdef DEBUG_ENABLED
  6415. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6416. #endif
  6417. Rect2i rect = p_rect;
  6418. rect.position += dl->viewport.position;
  6419. rect = dl->viewport.intersection(rect);
  6420. if (rect.get_area() == 0) {
  6421. return;
  6422. }
  6423. VkRect2D scissor;
  6424. scissor.offset.x = rect.position.x;
  6425. scissor.offset.y = rect.position.y;
  6426. scissor.extent.width = rect.size.width;
  6427. scissor.extent.height = rect.size.height;
  6428. vkCmdSetScissor(dl->command_buffer, 0, 1, &scissor);
  6429. }
  6430. void RenderingDeviceVulkan::draw_list_disable_scissor(DrawListID p_list) {
  6431. DrawList *dl = _get_draw_list_ptr(p_list);
  6432. ERR_FAIL_COND(!dl);
  6433. #ifdef DEBUG_ENABLED
  6434. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6435. #endif
  6436. VkRect2D scissor;
  6437. scissor.offset.x = dl->viewport.position.x;
  6438. scissor.offset.y = dl->viewport.position.y;
  6439. scissor.extent.width = dl->viewport.size.width;
  6440. scissor.extent.height = dl->viewport.size.height;
  6441. vkCmdSetScissor(dl->command_buffer, 0, 1, &scissor);
  6442. }
  6443. uint32_t RenderingDeviceVulkan::draw_list_get_current_pass() {
  6444. return draw_list_current_subpass;
  6445. }
  6446. RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_switch_to_next_pass() {
  6447. ERR_FAIL_COND_V(draw_list == nullptr, INVALID_ID);
  6448. ERR_FAIL_COND_V(draw_list_current_subpass >= draw_list_subpass_count - 1, INVALID_FORMAT_ID);
  6449. draw_list_current_subpass++;
  6450. Rect2i viewport;
  6451. _draw_list_free(&viewport);
  6452. vkCmdNextSubpass(frames[frame].draw_command_buffer, VK_SUBPASS_CONTENTS_INLINE);
  6453. _draw_list_allocate(viewport, 0, draw_list_current_subpass);
  6454. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  6455. }
  6456. Error RenderingDeviceVulkan::draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids) {
  6457. ERR_FAIL_COND_V(draw_list == nullptr, ERR_INVALID_PARAMETER);
  6458. ERR_FAIL_COND_V(draw_list_current_subpass >= draw_list_subpass_count - 1, ERR_INVALID_PARAMETER);
  6459. draw_list_current_subpass++;
  6460. Rect2i viewport;
  6461. _draw_list_free(&viewport);
  6462. vkCmdNextSubpass(frames[frame].draw_command_buffer, VK_SUBPASS_CONTENTS_INLINE);
  6463. _draw_list_allocate(viewport, p_splits, draw_list_current_subpass);
  6464. for (uint32_t i = 0; i < p_splits; i++) {
  6465. r_split_ids[i] = (int64_t(ID_TYPE_SPLIT_DRAW_LIST) << ID_BASE_SHIFT) + i;
  6466. }
  6467. return OK;
  6468. }
  6469. Error RenderingDeviceVulkan::_draw_list_allocate(const Rect2i &p_viewport, uint32_t p_splits, uint32_t p_subpass) {
  6470. // Lock while draw_list is active
  6471. _THREAD_SAFE_LOCK_
  6472. if (p_splits == 0) {
  6473. draw_list = memnew(DrawList);
  6474. draw_list->command_buffer = frames[frame].draw_command_buffer;
  6475. draw_list->viewport = p_viewport;
  6476. draw_list_count = 0;
  6477. draw_list_split = false;
  6478. } else {
  6479. if (p_splits > (uint32_t)split_draw_list_allocators.size()) {
  6480. uint32_t from = split_draw_list_allocators.size();
  6481. split_draw_list_allocators.resize(p_splits);
  6482. for (uint32_t i = from; i < p_splits; i++) {
  6483. VkCommandPoolCreateInfo cmd_pool_info;
  6484. cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  6485. cmd_pool_info.pNext = nullptr;
  6486. cmd_pool_info.queueFamilyIndex = context->get_graphics_queue_family_index();
  6487. cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  6488. VkResult res = vkCreateCommandPool(device, &cmd_pool_info, nullptr, &split_draw_list_allocators.write[i].command_pool);
  6489. ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "vkCreateCommandPool failed with error " + itos(res) + ".");
  6490. for (int j = 0; j < frame_count; j++) {
  6491. VkCommandBuffer command_buffer;
  6492. VkCommandBufferAllocateInfo cmdbuf;
  6493. //no command buffer exists, create it.
  6494. cmdbuf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  6495. cmdbuf.pNext = nullptr;
  6496. cmdbuf.commandPool = split_draw_list_allocators[i].command_pool;
  6497. cmdbuf.level = VK_COMMAND_BUFFER_LEVEL_SECONDARY;
  6498. cmdbuf.commandBufferCount = 1;
  6499. VkResult err = vkAllocateCommandBuffers(device, &cmdbuf, &command_buffer);
  6500. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  6501. split_draw_list_allocators.write[i].command_buffers.push_back(command_buffer);
  6502. }
  6503. }
  6504. }
  6505. draw_list = memnew_arr(DrawList, p_splits);
  6506. draw_list_count = p_splits;
  6507. draw_list_split = true;
  6508. for (uint32_t i = 0; i < p_splits; i++) {
  6509. //take a command buffer and initialize it
  6510. VkCommandBuffer command_buffer = split_draw_list_allocators[i].command_buffers[frame];
  6511. VkCommandBufferInheritanceInfo inheritance_info;
  6512. inheritance_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO;
  6513. inheritance_info.pNext = nullptr;
  6514. inheritance_info.renderPass = draw_list_render_pass;
  6515. inheritance_info.subpass = p_subpass;
  6516. inheritance_info.framebuffer = draw_list_vkframebuffer;
  6517. inheritance_info.occlusionQueryEnable = false;
  6518. inheritance_info.queryFlags = 0; //?
  6519. inheritance_info.pipelineStatistics = 0;
  6520. VkCommandBufferBeginInfo cmdbuf_begin;
  6521. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  6522. cmdbuf_begin.pNext = nullptr;
  6523. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT;
  6524. cmdbuf_begin.pInheritanceInfo = &inheritance_info;
  6525. VkResult res = vkResetCommandBuffer(command_buffer, 0);
  6526. if (res) {
  6527. memdelete_arr(draw_list);
  6528. draw_list = nullptr;
  6529. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "vkResetCommandBuffer failed with error " + itos(res) + ".");
  6530. }
  6531. res = vkBeginCommandBuffer(command_buffer, &cmdbuf_begin);
  6532. if (res) {
  6533. memdelete_arr(draw_list);
  6534. draw_list = nullptr;
  6535. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "vkBeginCommandBuffer failed with error " + itos(res) + ".");
  6536. }
  6537. draw_list[i].command_buffer = command_buffer;
  6538. draw_list[i].viewport = p_viewport;
  6539. }
  6540. }
  6541. return OK;
  6542. }
  6543. void RenderingDeviceVulkan::_draw_list_free(Rect2i *r_last_viewport) {
  6544. if (draw_list_split) {
  6545. //send all command buffers
  6546. VkCommandBuffer *command_buffers = (VkCommandBuffer *)alloca(sizeof(VkCommandBuffer) * draw_list_count);
  6547. for (uint32_t i = 0; i < draw_list_count; i++) {
  6548. vkEndCommandBuffer(draw_list[i].command_buffer);
  6549. command_buffers[i] = draw_list[i].command_buffer;
  6550. if (r_last_viewport) {
  6551. if (i == 0 || draw_list[i].viewport_set) {
  6552. *r_last_viewport = draw_list[i].viewport;
  6553. }
  6554. }
  6555. }
  6556. vkCmdExecuteCommands(frames[frame].draw_command_buffer, draw_list_count, command_buffers);
  6557. memdelete_arr(draw_list);
  6558. draw_list = nullptr;
  6559. } else {
  6560. if (r_last_viewport) {
  6561. *r_last_viewport = draw_list->viewport;
  6562. }
  6563. //just end the list
  6564. memdelete(draw_list);
  6565. draw_list = nullptr;
  6566. }
  6567. // draw_list is no longer active
  6568. _THREAD_SAFE_UNLOCK_
  6569. }
  6570. void RenderingDeviceVulkan::draw_list_end(uint32_t p_post_barrier) {
  6571. _THREAD_SAFE_METHOD_
  6572. ERR_FAIL_COND_MSG(!draw_list, "Immediate draw list is already inactive.");
  6573. _draw_list_free();
  6574. vkCmdEndRenderPass(frames[frame].draw_command_buffer);
  6575. for (int i = 0; i < draw_list_bound_textures.size(); i++) {
  6576. Texture *texture = texture_owner.get_or_null(draw_list_bound_textures[i]);
  6577. ERR_CONTINUE(!texture); //wtf
  6578. if (draw_list_unbind_color_textures && (texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) {
  6579. texture->bound = false;
  6580. }
  6581. if (draw_list_unbind_depth_textures && (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  6582. texture->bound = false;
  6583. }
  6584. }
  6585. uint32_t barrier_flags = 0;
  6586. uint32_t access_flags = 0;
  6587. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  6588. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  6589. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6590. }
  6591. if (p_post_barrier & BARRIER_MASK_RASTER) {
  6592. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT /*| VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT*/;
  6593. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT /*| VK_ACCESS_INDIRECT_COMMAND_READ_BIT*/;
  6594. }
  6595. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  6596. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  6597. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  6598. }
  6599. if (barrier_flags == 0) {
  6600. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  6601. }
  6602. draw_list_bound_textures.clear();
  6603. VkImageMemoryBarrier *image_barriers = nullptr;
  6604. uint32_t image_barrier_count = draw_list_storage_textures.size();
  6605. if (image_barrier_count) {
  6606. image_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * draw_list_storage_textures.size());
  6607. }
  6608. uint32_t src_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  6609. uint32_t src_access = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  6610. if (image_barrier_count) {
  6611. src_stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  6612. src_access |= VK_ACCESS_SHADER_WRITE_BIT;
  6613. }
  6614. for (uint32_t i = 0; i < image_barrier_count; i++) {
  6615. Texture *texture = texture_owner.get_or_null(draw_list_storage_textures[i]);
  6616. VkImageMemoryBarrier &image_memory_barrier = image_barriers[i];
  6617. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  6618. image_memory_barrier.pNext = nullptr;
  6619. image_memory_barrier.srcAccessMask = src_access;
  6620. image_memory_barrier.dstAccessMask = access_flags;
  6621. image_memory_barrier.oldLayout = texture->layout;
  6622. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  6623. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6624. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6625. image_memory_barrier.image = texture->image;
  6626. image_memory_barrier.subresourceRange.aspectMask = texture->read_aspect_mask;
  6627. image_memory_barrier.subresourceRange.baseMipLevel = texture->base_mipmap;
  6628. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  6629. image_memory_barrier.subresourceRange.baseArrayLayer = texture->base_layer;
  6630. image_memory_barrier.subresourceRange.layerCount = texture->layers;
  6631. texture->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  6632. }
  6633. draw_list_storage_textures.clear();
  6634. // To ensure proper synchronization, we must make sure rendering is done before:
  6635. // * Some buffer is copied
  6636. // * Another render pass happens (since we may be done)
  6637. #ifdef FORCE_FULL_BARRIER
  6638. _full_barrier(true);
  6639. #else
  6640. VkMemoryBarrier mem_barrier;
  6641. mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  6642. mem_barrier.pNext = nullptr;
  6643. mem_barrier.srcAccessMask = src_access;
  6644. mem_barrier.dstAccessMask = access_flags;
  6645. if (image_barrier_count > 0 || p_post_barrier != BARRIER_MASK_NO_BARRIER) {
  6646. vkCmdPipelineBarrier(frames[frame].draw_command_buffer, src_stage, barrier_flags, 0, 1, &mem_barrier, 0, nullptr, image_barrier_count, image_barriers);
  6647. }
  6648. #endif
  6649. }
  6650. /***********************/
  6651. /**** COMPUTE LISTS ****/
  6652. /***********************/
  6653. RenderingDevice::ComputeListID RenderingDeviceVulkan::compute_list_begin(bool p_allow_draw_overlap) {
  6654. ERR_FAIL_COND_V_MSG(!p_allow_draw_overlap && draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  6655. ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  6656. // Lock while compute_list is active
  6657. _THREAD_SAFE_LOCK_
  6658. compute_list = memnew(ComputeList);
  6659. compute_list->command_buffer = frames[frame].draw_command_buffer;
  6660. compute_list->state.allow_draw_overlap = p_allow_draw_overlap;
  6661. return ID_TYPE_COMPUTE_LIST;
  6662. }
  6663. void RenderingDeviceVulkan::compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline) {
  6664. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6665. ERR_FAIL_COND(!compute_list);
  6666. ComputeList *cl = compute_list;
  6667. const ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_compute_pipeline);
  6668. ERR_FAIL_COND(!pipeline);
  6669. if (p_compute_pipeline == cl->state.pipeline) {
  6670. return; //redundant state, return.
  6671. }
  6672. cl->state.pipeline = p_compute_pipeline;
  6673. cl->state.pipeline_layout = pipeline->pipeline_layout;
  6674. vkCmdBindPipeline(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline->pipeline);
  6675. if (cl->state.pipeline_shader != pipeline->shader) {
  6676. // shader changed, so descriptor sets may become incompatible.
  6677. //go through ALL sets, and unbind them (and all those above) if the format is different
  6678. uint32_t pcount = pipeline->set_formats.size(); //formats count in this pipeline
  6679. cl->state.set_count = MAX(cl->state.set_count, pcount);
  6680. const uint32_t *pformats = pipeline->set_formats.ptr(); //pipeline set formats
  6681. bool sets_valid = true; //once invalid, all above become invalid
  6682. for (uint32_t i = 0; i < pcount; i++) {
  6683. //if a part of the format is different, invalidate it (and the rest)
  6684. if (!sets_valid || cl->state.sets[i].pipeline_expected_format != pformats[i]) {
  6685. cl->state.sets[i].bound = false;
  6686. cl->state.sets[i].pipeline_expected_format = pformats[i];
  6687. sets_valid = false;
  6688. }
  6689. }
  6690. for (uint32_t i = pcount; i < cl->state.set_count; i++) {
  6691. //unbind the ones above (not used) if exist
  6692. cl->state.sets[i].bound = false;
  6693. }
  6694. cl->state.set_count = pcount; //update set count
  6695. if (pipeline->push_constant_size) {
  6696. cl->state.pipeline_push_constant_stages = pipeline->push_constant_stages;
  6697. #ifdef DEBUG_ENABLED
  6698. cl->validation.pipeline_push_constant_supplied = false;
  6699. #endif
  6700. }
  6701. cl->state.pipeline_shader = pipeline->shader;
  6702. cl->state.local_group_size[0] = pipeline->local_group_size[0];
  6703. cl->state.local_group_size[1] = pipeline->local_group_size[1];
  6704. cl->state.local_group_size[2] = pipeline->local_group_size[2];
  6705. }
  6706. #ifdef DEBUG_ENABLED
  6707. //update compute pass pipeline info
  6708. cl->validation.pipeline_active = true;
  6709. cl->validation.pipeline_push_constant_size = pipeline->push_constant_size;
  6710. #endif
  6711. }
  6712. void RenderingDeviceVulkan::compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index) {
  6713. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6714. ERR_FAIL_COND(!compute_list);
  6715. ComputeList *cl = compute_list;
  6716. #ifdef DEBUG_ENABLED
  6717. ERR_FAIL_COND_MSG(p_index >= limits.maxBoundDescriptorSets || p_index >= MAX_UNIFORM_SETS,
  6718. "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(limits.maxBoundDescriptorSets) + ").");
  6719. #endif
  6720. #ifdef DEBUG_ENABLED
  6721. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  6722. #endif
  6723. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set);
  6724. ERR_FAIL_COND(!uniform_set);
  6725. if (p_index > cl->state.set_count) {
  6726. cl->state.set_count = p_index;
  6727. }
  6728. cl->state.sets[p_index].descriptor_set = uniform_set->descriptor_set; //update set pointer
  6729. cl->state.sets[p_index].bound = false; //needs rebind
  6730. cl->state.sets[p_index].uniform_set_format = uniform_set->format;
  6731. cl->state.sets[p_index].uniform_set = p_uniform_set;
  6732. uint32_t textures_to_sampled_count = uniform_set->mutable_sampled_textures.size();
  6733. uint32_t textures_to_storage_count = uniform_set->mutable_storage_textures.size();
  6734. Texture **textures_to_sampled = uniform_set->mutable_sampled_textures.ptrw();
  6735. VkImageMemoryBarrier *texture_barriers = nullptr;
  6736. if (textures_to_sampled_count + textures_to_storage_count) {
  6737. texture_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * (textures_to_sampled_count + textures_to_storage_count));
  6738. }
  6739. uint32_t texture_barrier_count = 0;
  6740. uint32_t src_stage_flags = 0;
  6741. for (uint32_t i = 0; i < textures_to_sampled_count; i++) {
  6742. if (textures_to_sampled[i]->layout != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
  6743. src_stage_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  6744. VkImageMemoryBarrier &image_memory_barrier = texture_barriers[texture_barrier_count++];
  6745. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  6746. image_memory_barrier.pNext = nullptr;
  6747. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6748. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6749. image_memory_barrier.oldLayout = textures_to_sampled[i]->layout;
  6750. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  6751. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6752. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6753. image_memory_barrier.image = textures_to_sampled[i]->image;
  6754. image_memory_barrier.subresourceRange.aspectMask = textures_to_sampled[i]->read_aspect_mask;
  6755. image_memory_barrier.subresourceRange.baseMipLevel = textures_to_sampled[i]->base_mipmap;
  6756. image_memory_barrier.subresourceRange.levelCount = textures_to_sampled[i]->mipmaps;
  6757. image_memory_barrier.subresourceRange.baseArrayLayer = textures_to_sampled[i]->base_layer;
  6758. image_memory_barrier.subresourceRange.layerCount = textures_to_sampled[i]->layers;
  6759. textures_to_sampled[i]->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  6760. cl->state.textures_to_sampled_layout.erase(textures_to_sampled[i]);
  6761. }
  6762. if (textures_to_sampled[i]->used_in_frame != frames_drawn) {
  6763. textures_to_sampled[i]->used_in_frame = frames_drawn;
  6764. textures_to_sampled[i]->used_in_transfer = false;
  6765. textures_to_sampled[i]->used_in_raster = false;
  6766. }
  6767. textures_to_sampled[i]->used_in_compute = true;
  6768. }
  6769. Texture **textures_to_storage = uniform_set->mutable_storage_textures.ptrw();
  6770. for (uint32_t i = 0; i < textures_to_storage_count; i++) {
  6771. if (textures_to_storage[i]->layout != VK_IMAGE_LAYOUT_GENERAL) {
  6772. uint32_t src_access_flags = 0;
  6773. if (textures_to_storage[i]->used_in_frame == frames_drawn) {
  6774. if (textures_to_storage[i]->used_in_compute) {
  6775. src_stage_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  6776. src_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6777. }
  6778. if (textures_to_storage[i]->used_in_raster) {
  6779. src_stage_flags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT;
  6780. src_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6781. }
  6782. if (textures_to_storage[i]->used_in_transfer) {
  6783. src_stage_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  6784. src_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  6785. }
  6786. textures_to_storage[i]->used_in_compute = false;
  6787. textures_to_storage[i]->used_in_raster = false;
  6788. textures_to_storage[i]->used_in_transfer = false;
  6789. } else {
  6790. src_access_flags = 0;
  6791. textures_to_storage[i]->used_in_compute = false;
  6792. textures_to_storage[i]->used_in_raster = false;
  6793. textures_to_storage[i]->used_in_transfer = false;
  6794. textures_to_storage[i]->used_in_frame = frames_drawn;
  6795. }
  6796. VkImageMemoryBarrier &image_memory_barrier = texture_barriers[texture_barrier_count++];
  6797. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  6798. image_memory_barrier.pNext = nullptr;
  6799. image_memory_barrier.srcAccessMask = src_access_flags;
  6800. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6801. image_memory_barrier.oldLayout = textures_to_storage[i]->layout;
  6802. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  6803. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6804. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6805. image_memory_barrier.image = textures_to_storage[i]->image;
  6806. image_memory_barrier.subresourceRange.aspectMask = textures_to_storage[i]->read_aspect_mask;
  6807. image_memory_barrier.subresourceRange.baseMipLevel = textures_to_storage[i]->base_mipmap;
  6808. image_memory_barrier.subresourceRange.levelCount = textures_to_storage[i]->mipmaps;
  6809. image_memory_barrier.subresourceRange.baseArrayLayer = textures_to_storage[i]->base_layer;
  6810. image_memory_barrier.subresourceRange.layerCount = textures_to_storage[i]->layers;
  6811. textures_to_storage[i]->layout = VK_IMAGE_LAYOUT_GENERAL;
  6812. cl->state.textures_to_sampled_layout.insert(textures_to_storage[i]); //needs to go back to sampled layout afterwards
  6813. }
  6814. }
  6815. if (texture_barrier_count) {
  6816. if (src_stage_flags == 0) {
  6817. src_stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  6818. }
  6819. vkCmdPipelineBarrier(cl->command_buffer, src_stage_flags, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, texture_barrier_count, texture_barriers);
  6820. }
  6821. #if 0
  6822. { //validate that textures bound are not attached as framebuffer bindings
  6823. uint32_t attachable_count = uniform_set->attachable_textures.size();
  6824. const RID *attachable_ptr = uniform_set->attachable_textures.ptr();
  6825. uint32_t bound_count = draw_list_bound_textures.size();
  6826. const RID *bound_ptr = draw_list_bound_textures.ptr();
  6827. for (uint32_t i = 0; i < attachable_count; i++) {
  6828. for (uint32_t j = 0; j < bound_count; j++) {
  6829. ERR_FAIL_COND_MSG(attachable_ptr[i] == bound_ptr[j],
  6830. "Attempted to use the same texture in framebuffer attachment and a uniform set, this is not allowed.");
  6831. }
  6832. }
  6833. }
  6834. #endif
  6835. }
  6836. void RenderingDeviceVulkan::compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size) {
  6837. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6838. ERR_FAIL_COND(!compute_list);
  6839. ComputeList *cl = compute_list;
  6840. #ifdef DEBUG_ENABLED
  6841. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  6842. #endif
  6843. #ifdef DEBUG_ENABLED
  6844. ERR_FAIL_COND_MSG(p_data_size != cl->validation.pipeline_push_constant_size,
  6845. "This compute pipeline requires (" + itos(cl->validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");
  6846. #endif
  6847. vkCmdPushConstants(cl->command_buffer, cl->state.pipeline_layout, cl->state.pipeline_push_constant_stages, 0, p_data_size, p_data);
  6848. #ifdef DEBUG_ENABLED
  6849. cl->validation.pipeline_push_constant_supplied = true;
  6850. #endif
  6851. }
  6852. void RenderingDeviceVulkan::compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) {
  6853. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6854. ERR_FAIL_COND(!compute_list);
  6855. ComputeList *cl = compute_list;
  6856. #ifdef DEBUG_ENABLED
  6857. ERR_FAIL_COND_MSG(p_x_groups == 0, "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is zero.");
  6858. ERR_FAIL_COND_MSG(p_z_groups == 0, "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is zero.");
  6859. ERR_FAIL_COND_MSG(p_y_groups == 0, "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is zero.");
  6860. ERR_FAIL_COND_MSG(p_x_groups > limits.maxComputeWorkGroupCount[0],
  6861. "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[0]) + ")");
  6862. ERR_FAIL_COND_MSG(p_y_groups > limits.maxComputeWorkGroupCount[1],
  6863. "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[1]) + ")");
  6864. ERR_FAIL_COND_MSG(p_z_groups > limits.maxComputeWorkGroupCount[2],
  6865. "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[2]) + ")");
  6866. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  6867. #endif
  6868. #ifdef DEBUG_ENABLED
  6869. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  6870. if (cl->validation.pipeline_push_constant_size > 0) {
  6871. //using push constants, check that they were supplied
  6872. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  6873. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  6874. }
  6875. #endif
  6876. //Bind descriptor sets
  6877. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  6878. if (cl->state.sets[i].pipeline_expected_format == 0) {
  6879. continue; //nothing expected by this pipeline
  6880. }
  6881. #ifdef DEBUG_ENABLED
  6882. if (cl->state.sets[i].pipeline_expected_format != cl->state.sets[i].uniform_set_format) {
  6883. if (cl->state.sets[i].uniform_set_format == 0) {
  6884. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  6885. } else if (uniform_set_owner.owns(cl->state.sets[i].uniform_set)) {
  6886. UniformSet *us = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set);
  6887. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader));
  6888. } else {
  6889. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader));
  6890. }
  6891. }
  6892. #endif
  6893. if (!cl->state.sets[i].bound) {
  6894. //All good, see if this requires re-binding
  6895. vkCmdBindDescriptorSets(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, cl->state.pipeline_layout, i, 1, &cl->state.sets[i].descriptor_set, 0, nullptr);
  6896. cl->state.sets[i].bound = true;
  6897. }
  6898. }
  6899. vkCmdDispatch(cl->command_buffer, p_x_groups, p_y_groups, p_z_groups);
  6900. }
  6901. void RenderingDeviceVulkan::compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads) {
  6902. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6903. ERR_FAIL_COND(!compute_list);
  6904. #ifdef DEBUG_ENABLED
  6905. ERR_FAIL_COND_MSG(p_x_threads == 0, "Dispatch amount of X compute threads (" + itos(p_x_threads) + ") is zero.");
  6906. ERR_FAIL_COND_MSG(p_y_threads == 0, "Dispatch amount of Y compute threads (" + itos(p_y_threads) + ") is zero.");
  6907. ERR_FAIL_COND_MSG(p_z_threads == 0, "Dispatch amount of Z compute threads (" + itos(p_z_threads) + ") is zero.");
  6908. #endif
  6909. ComputeList *cl = compute_list;
  6910. #ifdef DEBUG_ENABLED
  6911. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  6912. if (cl->validation.pipeline_push_constant_size > 0) {
  6913. //using push constants, check that they were supplied
  6914. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  6915. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  6916. }
  6917. #endif
  6918. compute_list_dispatch(p_list, (p_x_threads - 1) / cl->state.local_group_size[0] + 1, (p_y_threads - 1) / cl->state.local_group_size[1] + 1, (p_z_threads - 1) / cl->state.local_group_size[2] + 1);
  6919. }
  6920. void RenderingDeviceVulkan::compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset) {
  6921. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6922. ERR_FAIL_COND(!compute_list);
  6923. ComputeList *cl = compute_list;
  6924. Buffer *buffer = storage_buffer_owner.get_or_null(p_buffer);
  6925. ERR_FAIL_COND(!buffer);
  6926. ERR_FAIL_COND_MSG(!(buffer->usage & STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT), "Buffer provided was not created to do indirect dispatch.");
  6927. ERR_FAIL_COND_MSG(p_offset + 12 > buffer->size, "Offset provided (+12) is past the end of buffer.");
  6928. #ifdef DEBUG_ENABLED
  6929. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  6930. #endif
  6931. #ifdef DEBUG_ENABLED
  6932. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  6933. if (cl->validation.pipeline_push_constant_size > 0) {
  6934. //using push constants, check that they were supplied
  6935. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  6936. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  6937. }
  6938. #endif
  6939. //Bind descriptor sets
  6940. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  6941. if (cl->state.sets[i].pipeline_expected_format == 0) {
  6942. continue; //nothing expected by this pipeline
  6943. }
  6944. #ifdef DEBUG_ENABLED
  6945. if (cl->state.sets[i].pipeline_expected_format != cl->state.sets[i].uniform_set_format) {
  6946. if (cl->state.sets[i].uniform_set_format == 0) {
  6947. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  6948. } else if (uniform_set_owner.owns(cl->state.sets[i].uniform_set)) {
  6949. UniformSet *us = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set);
  6950. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + "):\n" + _shader_uniform_debug(us->shader_id, us->shader_set) + "\nare not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader));
  6951. } else {
  6952. ERR_FAIL_MSG("Uniforms supplied for set (" + itos(i) + ", which was was just freed) are not the same format as required by the pipeline shader. Pipeline shader requires the following bindings:\n" + _shader_uniform_debug(cl->state.pipeline_shader));
  6953. }
  6954. }
  6955. #endif
  6956. if (!cl->state.sets[i].bound) {
  6957. //All good, see if this requires re-binding
  6958. vkCmdBindDescriptorSets(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, cl->state.pipeline_layout, i, 1, &cl->state.sets[i].descriptor_set, 0, nullptr);
  6959. cl->state.sets[i].bound = true;
  6960. }
  6961. }
  6962. vkCmdDispatchIndirect(cl->command_buffer, buffer->buffer, p_offset);
  6963. }
  6964. void RenderingDeviceVulkan::compute_list_add_barrier(ComputeListID p_list) {
  6965. #ifdef FORCE_FULL_BARRIER
  6966. _full_barrier(true);
  6967. #else
  6968. _memory_barrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, true);
  6969. #endif
  6970. }
  6971. void RenderingDeviceVulkan::compute_list_end(uint32_t p_post_barrier) {
  6972. ERR_FAIL_COND(!compute_list);
  6973. uint32_t barrier_flags = 0;
  6974. uint32_t access_flags = 0;
  6975. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  6976. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  6977. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6978. }
  6979. if (p_post_barrier & BARRIER_MASK_RASTER) {
  6980. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
  6981. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
  6982. }
  6983. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  6984. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  6985. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  6986. }
  6987. if (barrier_flags == 0) {
  6988. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  6989. }
  6990. VkImageMemoryBarrier *image_barriers = nullptr;
  6991. uint32_t image_barrier_count = compute_list->state.textures_to_sampled_layout.size();
  6992. if (image_barrier_count) {
  6993. image_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * image_barrier_count);
  6994. }
  6995. uint32_t barrier_idx = 0;
  6996. for (Set<Texture *>::Element *E = compute_list->state.textures_to_sampled_layout.front(); E; E = E->next()) {
  6997. VkImageMemoryBarrier &image_memory_barrier = image_barriers[barrier_idx++];
  6998. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  6999. image_memory_barrier.pNext = nullptr;
  7000. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7001. image_memory_barrier.dstAccessMask = access_flags;
  7002. image_memory_barrier.oldLayout = E->get()->layout;
  7003. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  7004. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  7005. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  7006. image_memory_barrier.image = E->get()->image;
  7007. image_memory_barrier.subresourceRange.aspectMask = E->get()->read_aspect_mask;
  7008. image_memory_barrier.subresourceRange.baseMipLevel = E->get()->base_mipmap;
  7009. image_memory_barrier.subresourceRange.levelCount = E->get()->mipmaps;
  7010. image_memory_barrier.subresourceRange.baseArrayLayer = E->get()->base_layer;
  7011. image_memory_barrier.subresourceRange.layerCount = E->get()->layers;
  7012. E->get()->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  7013. if (E->get()->used_in_frame != frames_drawn) {
  7014. E->get()->used_in_transfer = false;
  7015. E->get()->used_in_raster = false;
  7016. E->get()->used_in_compute = false;
  7017. E->get()->used_in_frame = frames_drawn;
  7018. }
  7019. }
  7020. #ifdef FORCE_FULL_BARRIER
  7021. _full_barrier(true);
  7022. #else
  7023. VkMemoryBarrier mem_barrier;
  7024. mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  7025. mem_barrier.pNext = nullptr;
  7026. mem_barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
  7027. mem_barrier.dstAccessMask = access_flags;
  7028. if (image_barrier_count > 0 || p_post_barrier != BARRIER_MASK_NO_BARRIER) {
  7029. vkCmdPipelineBarrier(compute_list->command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, barrier_flags, 0, 1, &mem_barrier, 0, nullptr, image_barrier_count, image_barriers);
  7030. }
  7031. #endif
  7032. memdelete(compute_list);
  7033. compute_list = nullptr;
  7034. // compute_list is no longer active
  7035. _THREAD_SAFE_UNLOCK_
  7036. }
  7037. void RenderingDeviceVulkan::barrier(uint32_t p_from, uint32_t p_to) {
  7038. uint32_t src_barrier_flags = 0;
  7039. uint32_t src_access_flags = 0;
  7040. if (p_from & BARRIER_MASK_COMPUTE) {
  7041. src_barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  7042. src_access_flags |= VK_ACCESS_SHADER_WRITE_BIT;
  7043. }
  7044. if (p_from & BARRIER_MASK_RASTER) {
  7045. src_barrier_flags |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  7046. src_access_flags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  7047. }
  7048. if (p_from & BARRIER_MASK_TRANSFER) {
  7049. src_barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  7050. src_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  7051. }
  7052. if (p_from == 0) {
  7053. src_barrier_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  7054. }
  7055. uint32_t dst_barrier_flags = 0;
  7056. uint32_t dst_access_flags = 0;
  7057. if (p_to & BARRIER_MASK_COMPUTE) {
  7058. dst_barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  7059. dst_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7060. }
  7061. if (p_to & BARRIER_MASK_RASTER) {
  7062. dst_barrier_flags |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
  7063. dst_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
  7064. }
  7065. if (p_to & BARRIER_MASK_TRANSFER) {
  7066. dst_barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  7067. dst_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  7068. }
  7069. if (p_to == 0) {
  7070. dst_barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  7071. }
  7072. _memory_barrier(src_barrier_flags, dst_barrier_flags, src_access_flags, dst_access_flags, true);
  7073. }
  7074. void RenderingDeviceVulkan::full_barrier() {
  7075. #ifndef DEBUG_ENABLED
  7076. ERR_PRINT("Full barrier is debug-only, should not be used in production");
  7077. #endif
  7078. _full_barrier(true);
  7079. }
  7080. #if 0
  7081. void RenderingDeviceVulkan::draw_list_render_secondary_to_framebuffer(ID p_framebuffer, ID *p_draw_lists, uint32_t p_draw_list_count, InitialAction p_initial_action, FinalAction p_final_action, const Vector<Variant> &p_clear_colors) {
  7082. VkCommandBuffer frame_cmdbuf = frames[frame].frame_buffer;
  7083. ERR_FAIL_COND(!frame_cmdbuf);
  7084. VkRenderPassBeginInfo render_pass_begin;
  7085. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  7086. render_pass_begin.pNext = nullptr;
  7087. render_pass_begin.renderPass = context->get_render_pass();
  7088. render_pass_begin.framebuffer = context->get_frame_framebuffer(frame);
  7089. render_pass_begin.renderArea.extent.width = context->get_screen_width(p_screen);
  7090. render_pass_begin.renderArea.extent.height = context->get_screen_height(p_screen);
  7091. render_pass_begin.renderArea.offset.x = 0;
  7092. render_pass_begin.renderArea.offset.y = 0;
  7093. render_pass_begin.clearValueCount = 1;
  7094. VkClearValue clear_value;
  7095. clear_value.color.float32[0] = p_clear_color.r;
  7096. clear_value.color.float32[1] = p_clear_color.g;
  7097. clear_value.color.float32[2] = p_clear_color.b;
  7098. clear_value.color.float32[3] = p_clear_color.a;
  7099. render_pass_begin.pClearValues = &clear_value;
  7100. vkCmdBeginRenderPass(frame_cmdbuf, &render_pass_begin, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS);
  7101. ID screen_format = screen_get_framebuffer_format();
  7102. {
  7103. VkCommandBuffer *command_buffers = (VkCommandBuffer *)alloca(sizeof(VkCommandBuffer) * p_draw_list_count);
  7104. uint32_t command_buffer_count = 0;
  7105. for (uint32_t i = 0; i < p_draw_list_count; i++) {
  7106. DrawList *dl = _get_draw_list_ptr(p_draw_lists[i]);
  7107. ERR_CONTINUE_MSG(!dl, "Draw list index (" + itos(i) + ") is not a valid draw list ID.");
  7108. ERR_CONTINUE_MSG(dl->validation.framebuffer_format != p_format_check,
  7109. "Draw list index (" + itos(i) + ") is created with a framebuffer format incompatible with this render pass.");
  7110. if (dl->validation.active) {
  7111. //needs to be closed, so close it.
  7112. vkEndCommandBuffer(dl->command_buffer);
  7113. dl->validation.active = false;
  7114. }
  7115. command_buffers[command_buffer_count++] = dl->command_buffer;
  7116. }
  7117. print_line("to draw: " + itos(command_buffer_count));
  7118. vkCmdExecuteCommands(p_primary, command_buffer_count, command_buffers);
  7119. }
  7120. vkCmdEndRenderPass(frame_cmdbuf);
  7121. }
  7122. #endif
  7123. void RenderingDeviceVulkan::_free_internal(RID p_id) {
  7124. //push everything so it's disposed of next time this frame index is processed (means, it's safe to do it)
  7125. if (texture_owner.owns(p_id)) {
  7126. Texture *texture = texture_owner.get_or_null(p_id);
  7127. frames[frame].textures_to_dispose_of.push_back(*texture);
  7128. texture_owner.free(p_id);
  7129. } else if (framebuffer_owner.owns(p_id)) {
  7130. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_id);
  7131. frames[frame].framebuffers_to_dispose_of.push_back(*framebuffer);
  7132. framebuffer_owner.free(p_id);
  7133. } else if (sampler_owner.owns(p_id)) {
  7134. VkSampler *sampler = sampler_owner.get_or_null(p_id);
  7135. frames[frame].samplers_to_dispose_of.push_back(*sampler);
  7136. sampler_owner.free(p_id);
  7137. } else if (vertex_buffer_owner.owns(p_id)) {
  7138. Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id);
  7139. frames[frame].buffers_to_dispose_of.push_back(*vertex_buffer);
  7140. vertex_buffer_owner.free(p_id);
  7141. } else if (vertex_array_owner.owns(p_id)) {
  7142. vertex_array_owner.free(p_id);
  7143. } else if (index_buffer_owner.owns(p_id)) {
  7144. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id);
  7145. Buffer b;
  7146. b.allocation = index_buffer->allocation;
  7147. b.buffer = index_buffer->buffer;
  7148. b.size = index_buffer->size;
  7149. b.buffer_info = {};
  7150. frames[frame].buffers_to_dispose_of.push_back(b);
  7151. index_buffer_owner.free(p_id);
  7152. } else if (index_array_owner.owns(p_id)) {
  7153. index_array_owner.free(p_id);
  7154. } else if (shader_owner.owns(p_id)) {
  7155. Shader *shader = shader_owner.get_or_null(p_id);
  7156. frames[frame].shaders_to_dispose_of.push_back(*shader);
  7157. shader_owner.free(p_id);
  7158. } else if (uniform_buffer_owner.owns(p_id)) {
  7159. Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id);
  7160. frames[frame].buffers_to_dispose_of.push_back(*uniform_buffer);
  7161. uniform_buffer_owner.free(p_id);
  7162. } else if (texture_buffer_owner.owns(p_id)) {
  7163. TextureBuffer *texture_buffer = texture_buffer_owner.get_or_null(p_id);
  7164. frames[frame].buffers_to_dispose_of.push_back(texture_buffer->buffer);
  7165. frames[frame].buffer_views_to_dispose_of.push_back(texture_buffer->view);
  7166. texture_buffer_owner.free(p_id);
  7167. } else if (storage_buffer_owner.owns(p_id)) {
  7168. Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id);
  7169. frames[frame].buffers_to_dispose_of.push_back(*storage_buffer);
  7170. storage_buffer_owner.free(p_id);
  7171. } else if (uniform_set_owner.owns(p_id)) {
  7172. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id);
  7173. frames[frame].uniform_sets_to_dispose_of.push_back(*uniform_set);
  7174. uniform_set_owner.free(p_id);
  7175. if (uniform_set->invalidated_callback != nullptr) {
  7176. uniform_set->invalidated_callback(uniform_set->invalidated_callback_userdata);
  7177. }
  7178. } else if (render_pipeline_owner.owns(p_id)) {
  7179. RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id);
  7180. frames[frame].render_pipelines_to_dispose_of.push_back(*pipeline);
  7181. render_pipeline_owner.free(p_id);
  7182. } else if (compute_pipeline_owner.owns(p_id)) {
  7183. ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id);
  7184. frames[frame].compute_pipelines_to_dispose_of.push_back(*pipeline);
  7185. compute_pipeline_owner.free(p_id);
  7186. } else {
  7187. ERR_PRINT("Attempted to free invalid ID: " + itos(p_id.get_id()));
  7188. }
  7189. }
  7190. void RenderingDeviceVulkan::free(RID p_id) {
  7191. _THREAD_SAFE_METHOD_
  7192. _free_dependencies(p_id); //recursively erase dependencies first, to avoid potential API problems
  7193. _free_internal(p_id);
  7194. }
  7195. // The full list of resources that can be named is in the VkObjectType enum
  7196. // We just expose the resources that are owned and can be accessed easily.
  7197. void RenderingDeviceVulkan::set_resource_name(RID p_id, const String p_name) {
  7198. if (texture_owner.owns(p_id)) {
  7199. Texture *texture = texture_owner.get_or_null(p_id);
  7200. if (texture->owner.is_null()) {
  7201. // Don't set the source texture's name when calling on a texture view
  7202. context->set_object_name(VK_OBJECT_TYPE_IMAGE, uint64_t(texture->image), p_name);
  7203. }
  7204. context->set_object_name(VK_OBJECT_TYPE_IMAGE_VIEW, uint64_t(texture->view), p_name + " View");
  7205. } else if (framebuffer_owner.owns(p_id)) {
  7206. //Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_id);
  7207. // Not implemented for now as the relationship between Framebuffer and RenderPass is very complex
  7208. } else if (sampler_owner.owns(p_id)) {
  7209. VkSampler *sampler = sampler_owner.get_or_null(p_id);
  7210. context->set_object_name(VK_OBJECT_TYPE_SAMPLER, uint64_t(*sampler), p_name);
  7211. } else if (vertex_buffer_owner.owns(p_id)) {
  7212. Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id);
  7213. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(vertex_buffer->buffer), p_name);
  7214. } else if (index_buffer_owner.owns(p_id)) {
  7215. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id);
  7216. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(index_buffer->buffer), p_name);
  7217. } else if (shader_owner.owns(p_id)) {
  7218. Shader *shader = shader_owner.get_or_null(p_id);
  7219. context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(shader->pipeline_layout), p_name + " Pipeline Layout");
  7220. for (int i = 0; i < shader->sets.size(); i++) {
  7221. context->set_object_name(VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, uint64_t(shader->sets[i].descriptor_set_layout), p_name);
  7222. }
  7223. } else if (uniform_buffer_owner.owns(p_id)) {
  7224. Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id);
  7225. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(uniform_buffer->buffer), p_name);
  7226. } else if (texture_buffer_owner.owns(p_id)) {
  7227. TextureBuffer *texture_buffer = texture_buffer_owner.get_or_null(p_id);
  7228. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(texture_buffer->buffer.buffer), p_name);
  7229. context->set_object_name(VK_OBJECT_TYPE_BUFFER_VIEW, uint64_t(texture_buffer->view), p_name + " View");
  7230. } else if (storage_buffer_owner.owns(p_id)) {
  7231. Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id);
  7232. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(storage_buffer->buffer), p_name);
  7233. } else if (uniform_set_owner.owns(p_id)) {
  7234. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id);
  7235. context->set_object_name(VK_OBJECT_TYPE_DESCRIPTOR_SET, uint64_t(uniform_set->descriptor_set), p_name);
  7236. } else if (render_pipeline_owner.owns(p_id)) {
  7237. RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id);
  7238. context->set_object_name(VK_OBJECT_TYPE_PIPELINE, uint64_t(pipeline->pipeline), p_name);
  7239. context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(pipeline->pipeline_layout), p_name + " Layout");
  7240. } else if (compute_pipeline_owner.owns(p_id)) {
  7241. ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id);
  7242. context->set_object_name(VK_OBJECT_TYPE_PIPELINE, uint64_t(pipeline->pipeline), p_name);
  7243. context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(pipeline->pipeline_layout), p_name + " Layout");
  7244. } else {
  7245. ERR_PRINT("Attempted to name invalid ID: " + itos(p_id.get_id()));
  7246. }
  7247. }
  7248. void RenderingDeviceVulkan::draw_command_begin_label(String p_label_name, const Color p_color) {
  7249. context->command_begin_label(frames[frame].draw_command_buffer, p_label_name, p_color);
  7250. }
  7251. void RenderingDeviceVulkan::draw_command_insert_label(String p_label_name, const Color p_color) {
  7252. context->command_insert_label(frames[frame].draw_command_buffer, p_label_name, p_color);
  7253. }
  7254. void RenderingDeviceVulkan::draw_command_end_label() {
  7255. context->command_end_label(frames[frame].draw_command_buffer);
  7256. }
  7257. String RenderingDeviceVulkan::get_device_vendor_name() const {
  7258. return context->get_device_vendor_name();
  7259. }
  7260. String RenderingDeviceVulkan::get_device_name() const {
  7261. return context->get_device_name();
  7262. }
  7263. RenderingDevice::DeviceType RenderingDeviceVulkan::get_device_type() const {
  7264. return context->get_device_type();
  7265. }
  7266. String RenderingDeviceVulkan::get_device_pipeline_cache_uuid() const {
  7267. return context->get_device_pipeline_cache_uuid();
  7268. }
  7269. void RenderingDeviceVulkan::_finalize_command_bufers() {
  7270. if (draw_list) {
  7271. ERR_PRINT("Found open draw list at the end of the frame, this should never happen (further drawing will likely not work).");
  7272. }
  7273. if (compute_list) {
  7274. ERR_PRINT("Found open compute list at the end of the frame, this should never happen (further compute will likely not work).");
  7275. }
  7276. { //complete the setup buffer (that needs to be processed before anything else)
  7277. vkEndCommandBuffer(frames[frame].setup_command_buffer);
  7278. vkEndCommandBuffer(frames[frame].draw_command_buffer);
  7279. }
  7280. }
  7281. void RenderingDeviceVulkan::_begin_frame() {
  7282. //erase pending resources
  7283. _free_pending_resources(frame);
  7284. //create setup command buffer and set as the setup buffer
  7285. {
  7286. VkCommandBufferBeginInfo cmdbuf_begin;
  7287. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7288. cmdbuf_begin.pNext = nullptr;
  7289. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7290. cmdbuf_begin.pInheritanceInfo = nullptr;
  7291. VkResult err = vkResetCommandBuffer(frames[frame].setup_command_buffer, 0);
  7292. ERR_FAIL_COND_MSG(err, "vkResetCommandBuffer failed with error " + itos(err) + ".");
  7293. err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  7294. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7295. err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  7296. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7297. if (local_device.is_null()) {
  7298. context->append_command_buffer(frames[frame].draw_command_buffer);
  7299. context->set_setup_buffer(frames[frame].setup_command_buffer); //append now so it's added before everything else
  7300. }
  7301. }
  7302. //advance current frame
  7303. frames_drawn++;
  7304. //advance staging buffer if used
  7305. if (staging_buffer_used) {
  7306. staging_buffer_current = (staging_buffer_current + 1) % staging_buffer_blocks.size();
  7307. staging_buffer_used = false;
  7308. }
  7309. if (frames[frame].timestamp_count) {
  7310. vkGetQueryPoolResults(device, frames[frame].timestamp_pool, 0, frames[frame].timestamp_count, sizeof(uint64_t) * max_timestamp_query_elements, frames[frame].timestamp_result_values, sizeof(uint64_t), VK_QUERY_RESULT_64_BIT);
  7311. vkCmdResetQueryPool(frames[frame].setup_command_buffer, frames[frame].timestamp_pool, 0, frames[frame].timestamp_count);
  7312. SWAP(frames[frame].timestamp_names, frames[frame].timestamp_result_names);
  7313. SWAP(frames[frame].timestamp_cpu_values, frames[frame].timestamp_cpu_result_values);
  7314. }
  7315. frames[frame].timestamp_result_count = frames[frame].timestamp_count;
  7316. frames[frame].timestamp_count = 0;
  7317. frames[frame].index = Engine::get_singleton()->get_frames_drawn();
  7318. }
  7319. void RenderingDeviceVulkan::swap_buffers() {
  7320. ERR_FAIL_COND_MSG(local_device.is_valid(), "Local devices can't swap buffers.");
  7321. _THREAD_SAFE_METHOD_
  7322. _finalize_command_bufers();
  7323. screen_prepared = false;
  7324. //swap buffers
  7325. context->swap_buffers();
  7326. frame = (frame + 1) % frame_count;
  7327. _begin_frame();
  7328. }
  7329. void RenderingDeviceVulkan::submit() {
  7330. ERR_FAIL_COND_MSG(local_device.is_null(), "Only local devices can submit and sync.");
  7331. ERR_FAIL_COND_MSG(local_device_processing, "device already submitted, call sync to wait until done.");
  7332. _finalize_command_bufers();
  7333. VkCommandBuffer command_buffers[2] = { frames[frame].setup_command_buffer, frames[frame].draw_command_buffer };
  7334. context->local_device_push_command_buffers(local_device, command_buffers, 2);
  7335. local_device_processing = true;
  7336. }
  7337. void RenderingDeviceVulkan::sync() {
  7338. ERR_FAIL_COND_MSG(local_device.is_null(), "Only local devices can submit and sync.");
  7339. ERR_FAIL_COND_MSG(!local_device_processing, "sync can only be called after a submit");
  7340. context->local_device_sync(local_device);
  7341. _begin_frame();
  7342. local_device_processing = false;
  7343. }
  7344. VmaPool RenderingDeviceVulkan::_find_or_create_small_allocs_pool(uint32_t p_mem_type_index) {
  7345. if (small_allocs_pools.has(p_mem_type_index)) {
  7346. return small_allocs_pools[p_mem_type_index];
  7347. }
  7348. print_verbose("Creating VMA small objects pool for memory type index " + itos(p_mem_type_index));
  7349. VmaPoolCreateInfo pci;
  7350. pci.memoryTypeIndex = p_mem_type_index;
  7351. pci.flags = 0;
  7352. pci.blockSize = 0;
  7353. pci.minBlockCount = 0;
  7354. pci.maxBlockCount = SIZE_MAX;
  7355. pci.priority = 0.5f;
  7356. pci.minAllocationAlignment = 0;
  7357. pci.pMemoryAllocateNext = nullptr;
  7358. VmaPool pool = VK_NULL_HANDLE;
  7359. VkResult res = vmaCreatePool(allocator, &pci, &pool);
  7360. small_allocs_pools[p_mem_type_index] = pool; // Don't try to create it again if failed the first time
  7361. ERR_FAIL_COND_V_MSG(res, pool, "vmaCreatePool failed with error " + itos(res) + ".");
  7362. return pool;
  7363. }
  7364. void RenderingDeviceVulkan::_free_pending_resources(int p_frame) {
  7365. //free in dependency usage order, so nothing weird happens
  7366. //pipelines
  7367. while (frames[p_frame].render_pipelines_to_dispose_of.front()) {
  7368. RenderPipeline *pipeline = &frames[p_frame].render_pipelines_to_dispose_of.front()->get();
  7369. vkDestroyPipeline(device, pipeline->pipeline, nullptr);
  7370. frames[p_frame].render_pipelines_to_dispose_of.pop_front();
  7371. }
  7372. while (frames[p_frame].compute_pipelines_to_dispose_of.front()) {
  7373. ComputePipeline *pipeline = &frames[p_frame].compute_pipelines_to_dispose_of.front()->get();
  7374. vkDestroyPipeline(device, pipeline->pipeline, nullptr);
  7375. frames[p_frame].compute_pipelines_to_dispose_of.pop_front();
  7376. }
  7377. //uniform sets
  7378. while (frames[p_frame].uniform_sets_to_dispose_of.front()) {
  7379. UniformSet *uniform_set = &frames[p_frame].uniform_sets_to_dispose_of.front()->get();
  7380. vkFreeDescriptorSets(device, uniform_set->pool->pool, 1, &uniform_set->descriptor_set);
  7381. _descriptor_pool_free(uniform_set->pool_key, uniform_set->pool);
  7382. frames[p_frame].uniform_sets_to_dispose_of.pop_front();
  7383. }
  7384. //buffer views
  7385. while (frames[p_frame].buffer_views_to_dispose_of.front()) {
  7386. VkBufferView buffer_view = frames[p_frame].buffer_views_to_dispose_of.front()->get();
  7387. vkDestroyBufferView(device, buffer_view, nullptr);
  7388. frames[p_frame].buffer_views_to_dispose_of.pop_front();
  7389. }
  7390. //shaders
  7391. while (frames[p_frame].shaders_to_dispose_of.front()) {
  7392. Shader *shader = &frames[p_frame].shaders_to_dispose_of.front()->get();
  7393. //descriptor set layout for each set
  7394. for (int i = 0; i < shader->sets.size(); i++) {
  7395. vkDestroyDescriptorSetLayout(device, shader->sets[i].descriptor_set_layout, nullptr);
  7396. }
  7397. //pipeline layout
  7398. vkDestroyPipelineLayout(device, shader->pipeline_layout, nullptr);
  7399. //shaders themselves
  7400. for (int i = 0; i < shader->pipeline_stages.size(); i++) {
  7401. vkDestroyShaderModule(device, shader->pipeline_stages[i].module, nullptr);
  7402. }
  7403. frames[p_frame].shaders_to_dispose_of.pop_front();
  7404. }
  7405. //samplers
  7406. while (frames[p_frame].samplers_to_dispose_of.front()) {
  7407. VkSampler sampler = frames[p_frame].samplers_to_dispose_of.front()->get();
  7408. vkDestroySampler(device, sampler, nullptr);
  7409. frames[p_frame].samplers_to_dispose_of.pop_front();
  7410. }
  7411. //framebuffers
  7412. while (frames[p_frame].framebuffers_to_dispose_of.front()) {
  7413. Framebuffer *framebuffer = &frames[p_frame].framebuffers_to_dispose_of.front()->get();
  7414. for (const KeyValue<Framebuffer::VersionKey, Framebuffer::Version> &E : framebuffer->framebuffers) {
  7415. //first framebuffer, then render pass because it depends on it
  7416. vkDestroyFramebuffer(device, E.value.framebuffer, nullptr);
  7417. vkDestroyRenderPass(device, E.value.render_pass, nullptr);
  7418. }
  7419. frames[p_frame].framebuffers_to_dispose_of.pop_front();
  7420. }
  7421. //textures
  7422. while (frames[p_frame].textures_to_dispose_of.front()) {
  7423. Texture *texture = &frames[p_frame].textures_to_dispose_of.front()->get();
  7424. if (texture->bound) {
  7425. WARN_PRINT("Deleted a texture while it was bound..");
  7426. }
  7427. vkDestroyImageView(device, texture->view, nullptr);
  7428. if (texture->owner.is_null()) {
  7429. //actually owns the image and the allocation too
  7430. image_memory -= texture->allocation_info.size;
  7431. vmaDestroyImage(allocator, texture->image, texture->allocation);
  7432. }
  7433. frames[p_frame].textures_to_dispose_of.pop_front();
  7434. }
  7435. //buffers
  7436. while (frames[p_frame].buffers_to_dispose_of.front()) {
  7437. _buffer_free(&frames[p_frame].buffers_to_dispose_of.front()->get());
  7438. frames[p_frame].buffers_to_dispose_of.pop_front();
  7439. }
  7440. }
  7441. void RenderingDeviceVulkan::prepare_screen_for_drawing() {
  7442. _THREAD_SAFE_METHOD_
  7443. context->prepare_buffers();
  7444. screen_prepared = true;
  7445. }
  7446. uint32_t RenderingDeviceVulkan::get_frame_delay() const {
  7447. return frame_count;
  7448. }
  7449. uint64_t RenderingDeviceVulkan::get_memory_usage(MemoryType p_type) const {
  7450. if (p_type == MEMORY_BUFFERS) {
  7451. return buffer_memory;
  7452. } else if (p_type == MEMORY_TEXTURES) {
  7453. return image_memory;
  7454. } else {
  7455. VmaTotalStatistics stats;
  7456. vmaCalculateStatistics(allocator, &stats);
  7457. return stats.total.statistics.allocationBytes;
  7458. }
  7459. }
  7460. void RenderingDeviceVulkan::_flush(bool p_current_frame) {
  7461. if (local_device.is_valid() && !p_current_frame) {
  7462. return; //flushing previous frames has no effect with local device
  7463. }
  7464. //not doing this crashes RADV (undefined behavior)
  7465. if (p_current_frame) {
  7466. vkEndCommandBuffer(frames[frame].setup_command_buffer);
  7467. vkEndCommandBuffer(frames[frame].draw_command_buffer);
  7468. }
  7469. if (local_device.is_valid()) {
  7470. VkCommandBuffer command_buffers[2] = { frames[frame].setup_command_buffer, frames[frame].draw_command_buffer };
  7471. context->local_device_push_command_buffers(local_device, command_buffers, 2);
  7472. context->local_device_sync(local_device);
  7473. VkCommandBufferBeginInfo cmdbuf_begin;
  7474. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7475. cmdbuf_begin.pNext = nullptr;
  7476. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7477. cmdbuf_begin.pInheritanceInfo = nullptr;
  7478. VkResult err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  7479. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7480. err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  7481. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7482. } else {
  7483. context->flush(p_current_frame, p_current_frame);
  7484. //re-create the setup command
  7485. if (p_current_frame) {
  7486. VkCommandBufferBeginInfo cmdbuf_begin;
  7487. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7488. cmdbuf_begin.pNext = nullptr;
  7489. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7490. cmdbuf_begin.pInheritanceInfo = nullptr;
  7491. VkResult err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  7492. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7493. context->set_setup_buffer(frames[frame].setup_command_buffer); //append now so it's added before everything else
  7494. }
  7495. if (p_current_frame) {
  7496. VkCommandBufferBeginInfo cmdbuf_begin;
  7497. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7498. cmdbuf_begin.pNext = nullptr;
  7499. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7500. cmdbuf_begin.pInheritanceInfo = nullptr;
  7501. VkResult err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  7502. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7503. context->append_command_buffer(frames[frame].draw_command_buffer);
  7504. }
  7505. }
  7506. }
  7507. void RenderingDeviceVulkan::initialize(VulkanContext *p_context, bool p_local_device) {
  7508. // get our device capabilities
  7509. {
  7510. device_capabilities.version_major = p_context->get_vulkan_major();
  7511. device_capabilities.version_minor = p_context->get_vulkan_minor();
  7512. // get info about subgroups
  7513. VulkanContext::SubgroupCapabilities subgroup_capabilities = p_context->get_subgroup_capabilities();
  7514. device_capabilities.subgroup_size = subgroup_capabilities.size;
  7515. device_capabilities.subgroup_in_shaders = subgroup_capabilities.supported_stages_flags_rd();
  7516. device_capabilities.subgroup_operations = subgroup_capabilities.supported_operations_flags_rd();
  7517. // get info about further features
  7518. VulkanContext::MultiviewCapabilities multiview_capabilies = p_context->get_multiview_capabilities();
  7519. device_capabilities.supports_multiview = multiview_capabilies.is_supported && multiview_capabilies.max_view_count > 1;
  7520. device_capabilities.supports_fsr_half_float = p_context->get_shader_capabilities().shader_float16_is_supported && p_context->get_storage_buffer_capabilities().storage_buffer_16_bit_access_is_supported;
  7521. }
  7522. context = p_context;
  7523. device = p_context->get_device();
  7524. if (p_local_device) {
  7525. frame_count = 1;
  7526. local_device = p_context->local_device_create();
  7527. device = p_context->local_device_get_vk_device(local_device);
  7528. } else {
  7529. frame_count = p_context->get_swapchain_image_count() + 1; //always need one extra to ensure it's unused at any time, without having to use a fence for this.
  7530. }
  7531. limits = p_context->get_device_limits();
  7532. max_timestamp_query_elements = 256;
  7533. { //initialize allocator
  7534. VmaAllocatorCreateInfo allocatorInfo;
  7535. memset(&allocatorInfo, 0, sizeof(VmaAllocatorCreateInfo));
  7536. allocatorInfo.physicalDevice = p_context->get_physical_device();
  7537. allocatorInfo.device = device;
  7538. allocatorInfo.instance = p_context->get_instance();
  7539. vmaCreateAllocator(&allocatorInfo, &allocator);
  7540. }
  7541. frames = memnew_arr(Frame, frame_count);
  7542. frame = 0;
  7543. //create setup and frame buffers
  7544. for (int i = 0; i < frame_count; i++) {
  7545. frames[i].index = 0;
  7546. { //create command pool, one per frame is recommended
  7547. VkCommandPoolCreateInfo cmd_pool_info;
  7548. cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  7549. cmd_pool_info.pNext = nullptr;
  7550. cmd_pool_info.queueFamilyIndex = p_context->get_graphics_queue_family_index();
  7551. cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  7552. VkResult res = vkCreateCommandPool(device, &cmd_pool_info, nullptr, &frames[i].command_pool);
  7553. ERR_FAIL_COND_MSG(res, "vkCreateCommandPool failed with error " + itos(res) + ".");
  7554. }
  7555. { //create command buffers
  7556. VkCommandBufferAllocateInfo cmdbuf;
  7557. //no command buffer exists, create it.
  7558. cmdbuf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  7559. cmdbuf.pNext = nullptr;
  7560. cmdbuf.commandPool = frames[i].command_pool;
  7561. cmdbuf.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  7562. cmdbuf.commandBufferCount = 1;
  7563. VkResult err = vkAllocateCommandBuffers(device, &cmdbuf, &frames[i].setup_command_buffer);
  7564. ERR_CONTINUE_MSG(err, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  7565. err = vkAllocateCommandBuffers(device, &cmdbuf, &frames[i].draw_command_buffer);
  7566. ERR_CONTINUE_MSG(err, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  7567. }
  7568. {
  7569. //create query pool
  7570. VkQueryPoolCreateInfo query_pool_create_info;
  7571. query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
  7572. query_pool_create_info.flags = 0;
  7573. query_pool_create_info.pNext = nullptr;
  7574. query_pool_create_info.queryType = VK_QUERY_TYPE_TIMESTAMP;
  7575. query_pool_create_info.queryCount = max_timestamp_query_elements;
  7576. query_pool_create_info.pipelineStatistics = 0;
  7577. vkCreateQueryPool(device, &query_pool_create_info, nullptr, &frames[i].timestamp_pool);
  7578. frames[i].timestamp_names = memnew_arr(String, max_timestamp_query_elements);
  7579. frames[i].timestamp_cpu_values = memnew_arr(uint64_t, max_timestamp_query_elements);
  7580. frames[i].timestamp_count = 0;
  7581. frames[i].timestamp_result_names = memnew_arr(String, max_timestamp_query_elements);
  7582. frames[i].timestamp_cpu_result_values = memnew_arr(uint64_t, max_timestamp_query_elements);
  7583. frames[i].timestamp_result_values = memnew_arr(uint64_t, max_timestamp_query_elements);
  7584. frames[i].timestamp_result_count = 0;
  7585. }
  7586. }
  7587. {
  7588. //begin the first command buffer for the first frame, so
  7589. //setting up things can be done in the meantime until swap_buffers(), which is called before advance.
  7590. VkCommandBufferBeginInfo cmdbuf_begin;
  7591. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7592. cmdbuf_begin.pNext = nullptr;
  7593. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7594. cmdbuf_begin.pInheritanceInfo = nullptr;
  7595. VkResult err = vkBeginCommandBuffer(frames[0].setup_command_buffer, &cmdbuf_begin);
  7596. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7597. err = vkBeginCommandBuffer(frames[0].draw_command_buffer, &cmdbuf_begin);
  7598. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7599. if (local_device.is_null()) {
  7600. context->set_setup_buffer(frames[0].setup_command_buffer); //append now so it's added before everything else
  7601. context->append_command_buffer(frames[0].draw_command_buffer);
  7602. }
  7603. }
  7604. // Note: If adding new project settings here, also duplicate their definition in
  7605. // rendering_server.cpp for headless doctool.
  7606. staging_buffer_block_size = GLOBAL_DEF("rendering/vulkan/staging_buffer/block_size_kb", 256);
  7607. staging_buffer_block_size = MAX(4, staging_buffer_block_size);
  7608. staging_buffer_block_size *= 1024; //kb -> bytes
  7609. staging_buffer_max_size = GLOBAL_DEF("rendering/vulkan/staging_buffer/max_size_mb", 128);
  7610. staging_buffer_max_size = MAX(1, staging_buffer_max_size);
  7611. staging_buffer_max_size *= 1024 * 1024;
  7612. if (staging_buffer_max_size < staging_buffer_block_size * 4) {
  7613. //validate enough blocks
  7614. staging_buffer_max_size = staging_buffer_block_size * 4;
  7615. }
  7616. texture_upload_region_size_px = GLOBAL_DEF("rendering/vulkan/staging_buffer/texture_upload_region_size_px", 64);
  7617. texture_upload_region_size_px = nearest_power_of_2_templated(texture_upload_region_size_px);
  7618. frames_drawn = frame_count; //start from frame count, so everything else is immediately old
  7619. //ensure current staging block is valid and at least one per frame exists
  7620. staging_buffer_current = 0;
  7621. staging_buffer_used = false;
  7622. for (int i = 0; i < frame_count; i++) {
  7623. //staging was never used, create a block
  7624. Error err = _insert_staging_block();
  7625. ERR_CONTINUE(err != OK);
  7626. }
  7627. max_descriptors_per_pool = GLOBAL_DEF("rendering/vulkan/descriptor_pools/max_descriptors_per_pool", 64);
  7628. //check to make sure DescriptorPoolKey is good
  7629. static_assert(sizeof(uint64_t) * 3 >= UNIFORM_TYPE_MAX * sizeof(uint16_t));
  7630. draw_list = nullptr;
  7631. draw_list_count = 0;
  7632. draw_list_split = false;
  7633. compute_list = nullptr;
  7634. }
  7635. template <class T>
  7636. void RenderingDeviceVulkan::_free_rids(T &p_owner, const char *p_type) {
  7637. List<RID> owned;
  7638. p_owner.get_owned_list(&owned);
  7639. if (owned.size()) {
  7640. if (owned.size() == 1) {
  7641. WARN_PRINT(vformat("1 RID of type \"%s\" was leaked.", p_type));
  7642. } else {
  7643. WARN_PRINT(vformat("%d RIDs of type \"%s\" were leaked.", owned.size(), p_type));
  7644. }
  7645. for (const RID &E : owned) {
  7646. free(E);
  7647. }
  7648. }
  7649. }
  7650. void RenderingDeviceVulkan::capture_timestamp(const String &p_name) {
  7651. ERR_FAIL_COND_MSG(draw_list != nullptr, "Capturing timestamps during draw list creation is not allowed. Offending timestamp was: " + p_name);
  7652. ERR_FAIL_COND(frames[frame].timestamp_count >= max_timestamp_query_elements);
  7653. //this should be optional for profiling, else it will slow things down
  7654. {
  7655. VkMemoryBarrier memoryBarrier;
  7656. memoryBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  7657. memoryBarrier.pNext = nullptr;
  7658. memoryBarrier.srcAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  7659. VK_ACCESS_INDEX_READ_BIT |
  7660. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  7661. VK_ACCESS_UNIFORM_READ_BIT |
  7662. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  7663. VK_ACCESS_SHADER_READ_BIT |
  7664. VK_ACCESS_SHADER_WRITE_BIT |
  7665. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  7666. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  7667. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  7668. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  7669. VK_ACCESS_TRANSFER_READ_BIT |
  7670. VK_ACCESS_TRANSFER_WRITE_BIT |
  7671. VK_ACCESS_HOST_READ_BIT |
  7672. VK_ACCESS_HOST_WRITE_BIT;
  7673. memoryBarrier.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  7674. VK_ACCESS_INDEX_READ_BIT |
  7675. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  7676. VK_ACCESS_UNIFORM_READ_BIT |
  7677. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  7678. VK_ACCESS_SHADER_READ_BIT |
  7679. VK_ACCESS_SHADER_WRITE_BIT |
  7680. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  7681. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  7682. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  7683. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  7684. VK_ACCESS_TRANSFER_READ_BIT |
  7685. VK_ACCESS_TRANSFER_WRITE_BIT |
  7686. VK_ACCESS_HOST_READ_BIT |
  7687. VK_ACCESS_HOST_WRITE_BIT;
  7688. vkCmdPipelineBarrier(frames[frame].draw_command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &memoryBarrier, 0, nullptr, 0, nullptr);
  7689. }
  7690. vkCmdWriteTimestamp(frames[frame].draw_command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, frames[frame].timestamp_pool, frames[frame].timestamp_count);
  7691. frames[frame].timestamp_names[frames[frame].timestamp_count] = p_name;
  7692. frames[frame].timestamp_cpu_values[frames[frame].timestamp_count] = OS::get_singleton()->get_ticks_usec();
  7693. frames[frame].timestamp_count++;
  7694. }
  7695. uint64_t RenderingDeviceVulkan::get_driver_resource(DriverResource p_resource, RID p_rid, uint64_t p_index) {
  7696. _THREAD_SAFE_METHOD_
  7697. switch (p_resource) {
  7698. case DRIVER_RESOURCE_VULKAN_DEVICE: {
  7699. return (uint64_t)context->get_device();
  7700. } break;
  7701. case DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE: {
  7702. return (uint64_t)context->get_physical_device();
  7703. } break;
  7704. case DRIVER_RESOURCE_VULKAN_INSTANCE: {
  7705. return (uint64_t)context->get_instance();
  7706. } break;
  7707. case DRIVER_RESOURCE_VULKAN_QUEUE: {
  7708. return (uint64_t)context->get_graphics_queue();
  7709. } break;
  7710. case DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX: {
  7711. return context->get_graphics_queue_family_index();
  7712. } break;
  7713. case DRIVER_RESOURCE_VULKAN_IMAGE: {
  7714. Texture *tex = texture_owner.get_or_null(p_rid);
  7715. ERR_FAIL_NULL_V(tex, 0);
  7716. return (uint64_t)tex->image;
  7717. } break;
  7718. case DRIVER_RESOURCE_VULKAN_IMAGE_VIEW: {
  7719. Texture *tex = texture_owner.get_or_null(p_rid);
  7720. ERR_FAIL_NULL_V(tex, 0);
  7721. return (uint64_t)tex->view;
  7722. } break;
  7723. case DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT: {
  7724. Texture *tex = texture_owner.get_or_null(p_rid);
  7725. ERR_FAIL_NULL_V(tex, 0);
  7726. return vulkan_formats[tex->format];
  7727. } break;
  7728. case DRIVER_RESOURCE_VULKAN_SAMPLER: {
  7729. VkSampler *sampler = sampler_owner.get_or_null(p_rid);
  7730. ERR_FAIL_NULL_V(sampler, 0);
  7731. return uint64_t(*sampler);
  7732. } break;
  7733. case DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET: {
  7734. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_rid);
  7735. ERR_FAIL_NULL_V(uniform_set, 0);
  7736. return uint64_t(uniform_set->descriptor_set);
  7737. } break;
  7738. case DRIVER_RESOURCE_VULKAN_BUFFER: {
  7739. Buffer *buffer = nullptr;
  7740. if (vertex_buffer_owner.owns(p_rid)) {
  7741. buffer = vertex_buffer_owner.get_or_null(p_rid);
  7742. } else if (index_buffer_owner.owns(p_rid)) {
  7743. buffer = index_buffer_owner.get_or_null(p_rid);
  7744. } else if (uniform_buffer_owner.owns(p_rid)) {
  7745. buffer = uniform_buffer_owner.get_or_null(p_rid);
  7746. } else if (texture_buffer_owner.owns(p_rid)) {
  7747. buffer = &texture_buffer_owner.get_or_null(p_rid)->buffer;
  7748. } else if (storage_buffer_owner.owns(p_rid)) {
  7749. buffer = storage_buffer_owner.get_or_null(p_rid);
  7750. }
  7751. ERR_FAIL_NULL_V(buffer, 0);
  7752. return uint64_t(buffer->buffer);
  7753. } break;
  7754. case DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE: {
  7755. ComputePipeline *compute_pipeline = compute_pipeline_owner.get_or_null(p_rid);
  7756. ERR_FAIL_NULL_V(compute_pipeline, 0);
  7757. return uint64_t(compute_pipeline->pipeline);
  7758. } break;
  7759. case DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE: {
  7760. RenderPipeline *render_pipeline = render_pipeline_owner.get_or_null(p_rid);
  7761. ERR_FAIL_NULL_V(render_pipeline, 0);
  7762. return uint64_t(render_pipeline->pipeline);
  7763. } break;
  7764. default: {
  7765. // not supported for this driver
  7766. return 0;
  7767. } break;
  7768. }
  7769. }
  7770. uint32_t RenderingDeviceVulkan::get_captured_timestamps_count() const {
  7771. return frames[frame].timestamp_result_count;
  7772. }
  7773. uint64_t RenderingDeviceVulkan::get_captured_timestamps_frame() const {
  7774. return frames[frame].index;
  7775. }
  7776. static void mult64to128(uint64_t u, uint64_t v, uint64_t &h, uint64_t &l) {
  7777. uint64_t u1 = (u & 0xffffffff);
  7778. uint64_t v1 = (v & 0xffffffff);
  7779. uint64_t t = (u1 * v1);
  7780. uint64_t w3 = (t & 0xffffffff);
  7781. uint64_t k = (t >> 32);
  7782. u >>= 32;
  7783. t = (u * v1) + k;
  7784. k = (t & 0xffffffff);
  7785. uint64_t w1 = (t >> 32);
  7786. v >>= 32;
  7787. t = (u1 * v) + k;
  7788. k = (t >> 32);
  7789. h = (u * v) + w1 + k;
  7790. l = (t << 32) + w3;
  7791. }
  7792. uint64_t RenderingDeviceVulkan::get_captured_timestamp_gpu_time(uint32_t p_index) const {
  7793. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0);
  7794. // this sucks because timestampPeriod multiplier is a float, while the timestamp is 64 bits nanosecs.
  7795. // so, in cases like nvidia which give you enormous numbers and 1 as multiplier, multiplying is next to impossible
  7796. // need to do 128 bits fixed point multiplication to get the right value
  7797. uint64_t shift_bits = 16;
  7798. uint64_t h, l;
  7799. mult64to128(frames[frame].timestamp_result_values[p_index], uint64_t(double(limits.timestampPeriod) * double(1 << shift_bits)), h, l);
  7800. l >>= shift_bits;
  7801. l |= h << (64 - shift_bits);
  7802. return l;
  7803. }
  7804. uint64_t RenderingDeviceVulkan::get_captured_timestamp_cpu_time(uint32_t p_index) const {
  7805. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0);
  7806. return frames[frame].timestamp_cpu_result_values[p_index];
  7807. }
  7808. String RenderingDeviceVulkan::get_captured_timestamp_name(uint32_t p_index) const {
  7809. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, String());
  7810. return frames[frame].timestamp_result_names[p_index];
  7811. }
  7812. int RenderingDeviceVulkan::limit_get(Limit p_limit) {
  7813. switch (p_limit) {
  7814. case LIMIT_MAX_BOUND_UNIFORM_SETS:
  7815. return limits.maxBoundDescriptorSets;
  7816. case LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS:
  7817. return limits.maxColorAttachments;
  7818. case LIMIT_MAX_TEXTURES_PER_UNIFORM_SET:
  7819. return limits.maxDescriptorSetSampledImages;
  7820. case LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET:
  7821. return limits.maxDescriptorSetSamplers;
  7822. case LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET:
  7823. return limits.maxDescriptorSetStorageBuffers;
  7824. case LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET:
  7825. return limits.maxDescriptorSetStorageImages;
  7826. case LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET:
  7827. return limits.maxDescriptorSetUniformBuffers;
  7828. case LIMIT_MAX_DRAW_INDEXED_INDEX:
  7829. return limits.maxDrawIndexedIndexValue;
  7830. case LIMIT_MAX_FRAMEBUFFER_HEIGHT:
  7831. return limits.maxFramebufferHeight;
  7832. case LIMIT_MAX_FRAMEBUFFER_WIDTH:
  7833. return limits.maxFramebufferWidth;
  7834. case LIMIT_MAX_TEXTURE_ARRAY_LAYERS:
  7835. return limits.maxImageArrayLayers;
  7836. case LIMIT_MAX_TEXTURE_SIZE_1D:
  7837. return limits.maxImageDimension1D;
  7838. case LIMIT_MAX_TEXTURE_SIZE_2D:
  7839. return limits.maxImageDimension2D;
  7840. case LIMIT_MAX_TEXTURE_SIZE_3D:
  7841. return limits.maxImageDimension3D;
  7842. case LIMIT_MAX_TEXTURE_SIZE_CUBE:
  7843. return limits.maxImageDimensionCube;
  7844. case LIMIT_MAX_TEXTURES_PER_SHADER_STAGE:
  7845. return limits.maxPerStageDescriptorSampledImages;
  7846. case LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE:
  7847. return limits.maxPerStageDescriptorSamplers;
  7848. case LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE:
  7849. return limits.maxPerStageDescriptorStorageBuffers;
  7850. case LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE:
  7851. return limits.maxPerStageDescriptorStorageImages;
  7852. case LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE:
  7853. return limits.maxPerStageDescriptorUniformBuffers;
  7854. case LIMIT_MAX_PUSH_CONSTANT_SIZE:
  7855. return limits.maxPushConstantsSize;
  7856. case LIMIT_MAX_UNIFORM_BUFFER_SIZE:
  7857. return limits.maxUniformBufferRange;
  7858. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET:
  7859. return limits.maxVertexInputAttributeOffset;
  7860. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES:
  7861. return limits.maxVertexInputAttributes;
  7862. case LIMIT_MAX_VERTEX_INPUT_BINDINGS:
  7863. return limits.maxVertexInputBindings;
  7864. case LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE:
  7865. return limits.maxVertexInputBindingStride;
  7866. case LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
  7867. return limits.minUniformBufferOffsetAlignment;
  7868. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X:
  7869. return limits.maxComputeWorkGroupCount[0];
  7870. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y:
  7871. return limits.maxComputeWorkGroupCount[1];
  7872. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z:
  7873. return limits.maxComputeWorkGroupCount[2];
  7874. case LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS:
  7875. return limits.maxComputeWorkGroupInvocations;
  7876. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X:
  7877. return limits.maxComputeWorkGroupSize[0];
  7878. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y:
  7879. return limits.maxComputeWorkGroupSize[1];
  7880. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z:
  7881. return limits.maxComputeWorkGroupSize[2];
  7882. default:
  7883. ERR_FAIL_V(0);
  7884. }
  7885. return 0;
  7886. }
  7887. void RenderingDeviceVulkan::finalize() {
  7888. //free all resources
  7889. _flush(false);
  7890. _free_rids(render_pipeline_owner, "Pipeline");
  7891. _free_rids(compute_pipeline_owner, "Compute");
  7892. _free_rids(uniform_set_owner, "UniformSet");
  7893. _free_rids(texture_buffer_owner, "TextureBuffer");
  7894. _free_rids(storage_buffer_owner, "StorageBuffer");
  7895. _free_rids(uniform_buffer_owner, "UniformBuffer");
  7896. _free_rids(shader_owner, "Shader");
  7897. _free_rids(index_array_owner, "IndexArray");
  7898. _free_rids(index_buffer_owner, "IndexBuffer");
  7899. _free_rids(vertex_array_owner, "VertexArray");
  7900. _free_rids(vertex_buffer_owner, "VertexBuffer");
  7901. _free_rids(framebuffer_owner, "Framebuffer");
  7902. _free_rids(sampler_owner, "Sampler");
  7903. {
  7904. //for textures it's a bit more difficult because they may be shared
  7905. List<RID> owned;
  7906. texture_owner.get_owned_list(&owned);
  7907. if (owned.size()) {
  7908. if (owned.size() == 1) {
  7909. WARN_PRINT("1 RID of type \"Texture\" was leaked.");
  7910. } else {
  7911. WARN_PRINT(vformat("%d RIDs of type \"Texture\" were leaked.", owned.size()));
  7912. }
  7913. //free shared first
  7914. for (List<RID>::Element *E = owned.front(); E;) {
  7915. List<RID>::Element *N = E->next();
  7916. if (texture_is_shared(E->get())) {
  7917. free(E->get());
  7918. owned.erase(E);
  7919. }
  7920. E = N;
  7921. }
  7922. //free non shared second, this will avoid an error trying to free unexisting textures due to dependencies.
  7923. for (const RID &E : owned) {
  7924. free(E);
  7925. }
  7926. }
  7927. }
  7928. //free everything pending
  7929. for (int i = 0; i < frame_count; i++) {
  7930. int f = (frame + i) % frame_count;
  7931. _free_pending_resources(f);
  7932. vkDestroyCommandPool(device, frames[i].command_pool, nullptr);
  7933. vkDestroyQueryPool(device, frames[i].timestamp_pool, nullptr);
  7934. memdelete_arr(frames[i].timestamp_names);
  7935. memdelete_arr(frames[i].timestamp_cpu_values);
  7936. memdelete_arr(frames[i].timestamp_result_names);
  7937. memdelete_arr(frames[i].timestamp_result_values);
  7938. memdelete_arr(frames[i].timestamp_cpu_result_values);
  7939. }
  7940. for (int i = 0; i < split_draw_list_allocators.size(); i++) {
  7941. vkDestroyCommandPool(device, split_draw_list_allocators[i].command_pool, nullptr);
  7942. }
  7943. memdelete_arr(frames);
  7944. for (int i = 0; i < staging_buffer_blocks.size(); i++) {
  7945. vmaDestroyBuffer(allocator, staging_buffer_blocks[i].buffer, staging_buffer_blocks[i].allocation);
  7946. }
  7947. while (small_allocs_pools.size()) {
  7948. Map<uint32_t, VmaPool>::Element *E = small_allocs_pools.front();
  7949. vmaDestroyPool(allocator, E->get());
  7950. small_allocs_pools.erase(E);
  7951. }
  7952. vmaDestroyAllocator(allocator);
  7953. while (vertex_formats.size()) {
  7954. Map<VertexFormatID, VertexDescriptionCache>::Element *temp = vertex_formats.front();
  7955. memdelete_arr(temp->get().bindings);
  7956. memdelete_arr(temp->get().attributes);
  7957. vertex_formats.erase(temp);
  7958. }
  7959. for (int i = 0; i < framebuffer_formats.size(); i++) {
  7960. vkDestroyRenderPass(device, framebuffer_formats[i].render_pass, nullptr);
  7961. }
  7962. framebuffer_formats.clear();
  7963. //all these should be clear at this point
  7964. ERR_FAIL_COND(descriptor_pools.size());
  7965. ERR_FAIL_COND(dependency_map.size());
  7966. ERR_FAIL_COND(reverse_dependency_map.size());
  7967. }
  7968. RenderingDevice *RenderingDeviceVulkan::create_local_device() {
  7969. RenderingDeviceVulkan *rd = memnew(RenderingDeviceVulkan);
  7970. rd->initialize(context, true);
  7971. return rd;
  7972. }
  7973. RenderingDeviceVulkan::RenderingDeviceVulkan() {
  7974. device_capabilities.device_family = DEVICE_VULKAN;
  7975. }
  7976. RenderingDeviceVulkan::~RenderingDeviceVulkan() {
  7977. if (local_device.is_valid()) {
  7978. finalize();
  7979. context->local_device_free(local_device);
  7980. }
  7981. }