rendering_device_vulkan.cpp 387 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588
  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] = HashSet<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] = HashSet<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. HashMap<RID, HashSet<RID>>::Iterator E = dependency_map.find(p_id);
  133. if (E) {
  134. while (E->value.size()) {
  135. free(*E->value.begin());
  136. }
  137. dependency_map.remove(E);
  138. }
  139. //reverse dependencies must be unreferenced
  140. E = reverse_dependency_map.find(p_id);
  141. if (E) {
  142. for (const RID &F : E->value) {
  143. HashMap<RID, HashSet<RID>>::Iterator G = dependency_map.find(F);
  144. ERR_CONTINUE(!G);
  145. ERR_CONTINUE(!G->value.has(p_id));
  146. G->value.erase(p_id);
  147. }
  148. reverse_dependency_map.remove(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(1u, 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. uint32_t w = p_width;
  1148. uint32_t h = p_height;
  1149. uint32_t d = p_depth;
  1150. uint32_t mipmaps = 1;
  1151. while (true) {
  1152. if (w == 1 && h == 1 && d == 1) {
  1153. break;
  1154. }
  1155. w = MAX(1u, w >> 1);
  1156. h = MAX(1u, h >> 1);
  1157. d = MAX(1u, 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_mem_usage, VmaAllocationCreateFlags p_mem_flags) {
  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 = p_mem_flags;
  1277. allocInfo.usage = p_mem_usage;
  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 = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
  1319. allocInfo.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST;
  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) {
  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 {
  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);
  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 = (p_format.usage_bits & TEXTURE_USAGE_CPU_READ_BIT) ? VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT : 0;
  1693. allocInfo.pool = nullptr;
  1694. allocInfo.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE;
  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. #ifdef DEV_ENABLED
  1815. set_resource_name(id, "RID:" + itos(id.get_id()));
  1816. #endif
  1817. if (p_data.size()) {
  1818. for (uint32_t i = 0; i < image_create_info.arrayLayers; i++) {
  1819. _texture_update(id, i, p_data[i], RD::BARRIER_MASK_ALL, true);
  1820. }
  1821. }
  1822. return id;
  1823. }
  1824. RID RenderingDeviceVulkan::texture_create_shared(const TextureView &p_view, RID p_with_texture) {
  1825. _THREAD_SAFE_METHOD_
  1826. Texture *src_texture = texture_owner.get_or_null(p_with_texture);
  1827. ERR_FAIL_COND_V(!src_texture, RID());
  1828. if (src_texture->owner.is_valid()) { //ahh this is a share
  1829. p_with_texture = src_texture->owner;
  1830. src_texture = texture_owner.get_or_null(src_texture->owner);
  1831. ERR_FAIL_COND_V(!src_texture, RID()); //this is a bug
  1832. }
  1833. //create view
  1834. Texture texture = *src_texture;
  1835. VkImageViewCreateInfo image_view_create_info;
  1836. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1837. image_view_create_info.pNext = nullptr;
  1838. image_view_create_info.flags = 0;
  1839. image_view_create_info.image = texture.image;
  1840. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  1841. VK_IMAGE_VIEW_TYPE_1D,
  1842. VK_IMAGE_VIEW_TYPE_2D,
  1843. VK_IMAGE_VIEW_TYPE_3D,
  1844. VK_IMAGE_VIEW_TYPE_CUBE,
  1845. VK_IMAGE_VIEW_TYPE_1D_ARRAY,
  1846. VK_IMAGE_VIEW_TYPE_2D_ARRAY,
  1847. VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
  1848. };
  1849. image_view_create_info.viewType = view_types[texture.type];
  1850. if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) {
  1851. image_view_create_info.format = vulkan_formats[texture.format];
  1852. } else {
  1853. ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());
  1854. ERR_FAIL_COND_V_MSG(texture.allowed_shared_formats.find(p_view.format_override) == -1, RID(),
  1855. "Format override is not in the list of allowed shareable formats for original texture.");
  1856. image_view_create_info.format = vulkan_formats[p_view.format_override];
  1857. }
  1858. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  1859. VK_COMPONENT_SWIZZLE_IDENTITY,
  1860. VK_COMPONENT_SWIZZLE_ZERO,
  1861. VK_COMPONENT_SWIZZLE_ONE,
  1862. VK_COMPONENT_SWIZZLE_R,
  1863. VK_COMPONENT_SWIZZLE_G,
  1864. VK_COMPONENT_SWIZZLE_B,
  1865. VK_COMPONENT_SWIZZLE_A
  1866. };
  1867. image_view_create_info.components.r = component_swizzles[p_view.swizzle_r];
  1868. image_view_create_info.components.g = component_swizzles[p_view.swizzle_g];
  1869. image_view_create_info.components.b = component_swizzles[p_view.swizzle_b];
  1870. image_view_create_info.components.a = component_swizzles[p_view.swizzle_a];
  1871. image_view_create_info.subresourceRange.baseMipLevel = 0;
  1872. image_view_create_info.subresourceRange.levelCount = texture.mipmaps;
  1873. image_view_create_info.subresourceRange.layerCount = texture.layers;
  1874. image_view_create_info.subresourceRange.baseArrayLayer = 0;
  1875. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1876. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1877. } else {
  1878. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1879. }
  1880. VkImageViewUsageCreateInfo usage_info;
  1881. usage_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO;
  1882. usage_info.pNext = nullptr;
  1883. if (p_view.format_override != DATA_FORMAT_MAX) {
  1884. //need to validate usage with vulkan
  1885. usage_info.usage = 0;
  1886. if (texture.usage_flags & TEXTURE_USAGE_SAMPLING_BIT) {
  1887. usage_info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
  1888. }
  1889. if (texture.usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  1890. if (texture_is_format_supported_for_usage(p_view.format_override, TEXTURE_USAGE_STORAGE_BIT)) {
  1891. usage_info.usage |= VK_IMAGE_USAGE_STORAGE_BIT;
  1892. }
  1893. }
  1894. if (texture.usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  1895. if (texture_is_format_supported_for_usage(p_view.format_override, TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) {
  1896. usage_info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  1897. }
  1898. }
  1899. if (texture.usage_flags & TEXTURE_USAGE_INPUT_ATTACHMENT_BIT) {
  1900. usage_info.usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
  1901. }
  1902. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1903. usage_info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  1904. }
  1905. if (texture.usage_flags & TEXTURE_USAGE_CAN_UPDATE_BIT) {
  1906. usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1907. }
  1908. if (texture.usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT) {
  1909. usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
  1910. }
  1911. if (texture.usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT) {
  1912. usage_info.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1913. }
  1914. image_view_create_info.pNext = &usage_info;
  1915. }
  1916. VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  1917. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  1918. texture.owner = p_with_texture;
  1919. RID id = texture_owner.make_rid(texture);
  1920. #ifdef DEV_ENABLED
  1921. set_resource_name(id, "RID:" + itos(id.get_id()));
  1922. #endif
  1923. _add_dependency(id, p_with_texture);
  1924. return id;
  1925. }
  1926. 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) {
  1927. _THREAD_SAFE_METHOD_
  1928. // This method creates a texture object using a VkImage created by an extension, module or other external source (OpenXR uses this).
  1929. VkImage image = (VkImage)p_image;
  1930. Texture texture;
  1931. texture.image = image;
  1932. // if we leave texture.allocation as a nullptr, would that be enough to detect we don't "own" the image?
  1933. // also leave texture.allocation_info alone
  1934. // we'll set texture.view later on
  1935. texture.type = p_type;
  1936. texture.format = p_format;
  1937. texture.samples = p_samples;
  1938. texture.width = p_width;
  1939. texture.height = p_height;
  1940. texture.depth = p_depth;
  1941. texture.layers = p_layers;
  1942. texture.mipmaps = 0; // maybe make this settable too?
  1943. texture.usage_flags = p_flags;
  1944. texture.base_mipmap = 0;
  1945. texture.base_layer = 0;
  1946. texture.allowed_shared_formats.push_back(RD::DATA_FORMAT_R8G8B8A8_UNORM);
  1947. texture.allowed_shared_formats.push_back(RD::DATA_FORMAT_R8G8B8A8_SRGB);
  1948. // Do we need to do something with texture.layout ?
  1949. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1950. texture.read_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1951. texture.barrier_aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1952. // if (format_has_stencil(p_format.format)) {
  1953. // texture.barrier_aspect_mask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  1954. // }
  1955. } else {
  1956. texture.read_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT;
  1957. texture.barrier_aspect_mask = VK_IMAGE_ASPECT_COLOR_BIT;
  1958. }
  1959. // Create a view for us to use
  1960. VkImageViewCreateInfo image_view_create_info;
  1961. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1962. image_view_create_info.pNext = nullptr;
  1963. image_view_create_info.flags = 0;
  1964. image_view_create_info.image = texture.image;
  1965. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  1966. VK_IMAGE_VIEW_TYPE_1D,
  1967. VK_IMAGE_VIEW_TYPE_2D,
  1968. VK_IMAGE_VIEW_TYPE_3D,
  1969. VK_IMAGE_VIEW_TYPE_CUBE,
  1970. VK_IMAGE_VIEW_TYPE_1D_ARRAY,
  1971. VK_IMAGE_VIEW_TYPE_2D_ARRAY,
  1972. VK_IMAGE_VIEW_TYPE_CUBE_ARRAY,
  1973. };
  1974. image_view_create_info.viewType = view_types[texture.type];
  1975. image_view_create_info.format = vulkan_formats[texture.format];
  1976. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  1977. VK_COMPONENT_SWIZZLE_IDENTITY,
  1978. VK_COMPONENT_SWIZZLE_ZERO,
  1979. VK_COMPONENT_SWIZZLE_ONE,
  1980. VK_COMPONENT_SWIZZLE_R,
  1981. VK_COMPONENT_SWIZZLE_G,
  1982. VK_COMPONENT_SWIZZLE_B,
  1983. VK_COMPONENT_SWIZZLE_A
  1984. };
  1985. // hardcode for now, maybe make this settable from outside..
  1986. image_view_create_info.components.r = component_swizzles[TEXTURE_SWIZZLE_R];
  1987. image_view_create_info.components.g = component_swizzles[TEXTURE_SWIZZLE_G];
  1988. image_view_create_info.components.b = component_swizzles[TEXTURE_SWIZZLE_B];
  1989. image_view_create_info.components.a = component_swizzles[TEXTURE_SWIZZLE_A];
  1990. image_view_create_info.subresourceRange.baseMipLevel = 0;
  1991. image_view_create_info.subresourceRange.levelCount = texture.mipmaps;
  1992. image_view_create_info.subresourceRange.baseArrayLayer = 0;
  1993. image_view_create_info.subresourceRange.layerCount = texture.layers;
  1994. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  1995. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  1996. } else {
  1997. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1998. }
  1999. VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  2000. if (err) {
  2001. // vmaDestroyImage(allocator, texture.image, texture.allocation);
  2002. ERR_FAIL_V_MSG(RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  2003. }
  2004. //barrier to set layout
  2005. {
  2006. VkImageMemoryBarrier image_memory_barrier;
  2007. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2008. image_memory_barrier.pNext = nullptr;
  2009. image_memory_barrier.srcAccessMask = 0;
  2010. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2011. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2012. image_memory_barrier.newLayout = texture.layout;
  2013. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2014. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2015. image_memory_barrier.image = texture.image;
  2016. image_memory_barrier.subresourceRange.aspectMask = texture.barrier_aspect_mask;
  2017. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2018. image_memory_barrier.subresourceRange.levelCount = texture.mipmaps;
  2019. image_memory_barrier.subresourceRange.baseArrayLayer = 0;
  2020. image_memory_barrier.subresourceRange.layerCount = texture.layers;
  2021. 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);
  2022. }
  2023. RID id = texture_owner.make_rid(texture);
  2024. #ifdef DEV_ENABLED
  2025. set_resource_name(id, "RID:" + itos(id.get_id()));
  2026. #endif
  2027. return id;
  2028. }
  2029. 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) {
  2030. _THREAD_SAFE_METHOD_
  2031. Texture *src_texture = texture_owner.get_or_null(p_with_texture);
  2032. ERR_FAIL_COND_V(!src_texture, RID());
  2033. if (src_texture->owner.is_valid()) { //ahh this is a share
  2034. p_with_texture = src_texture->owner;
  2035. src_texture = texture_owner.get_or_null(src_texture->owner);
  2036. ERR_FAIL_COND_V(!src_texture, RID()); //this is a bug
  2037. }
  2038. 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(),
  2039. "Can only create a cubemap slice from a cubemap or cubemap array mipmap");
  2040. ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_3D && src_texture->type != TEXTURE_TYPE_3D, RID(),
  2041. "Can only create a 3D slice from a 3D texture");
  2042. ERR_FAIL_COND_V_MSG(p_slice_type == TEXTURE_SLICE_2D_ARRAY && (src_texture->type != TEXTURE_TYPE_2D_ARRAY), RID(),
  2043. "Can only create an array slice from a 2D array mipmap");
  2044. //create view
  2045. ERR_FAIL_UNSIGNED_INDEX_V(p_mipmap, src_texture->mipmaps, RID());
  2046. ERR_FAIL_COND_V(p_mipmap + p_mipmaps > src_texture->mipmaps, RID());
  2047. ERR_FAIL_UNSIGNED_INDEX_V(p_layer, src_texture->layers, RID());
  2048. int slice_layers = 1;
  2049. if (p_slice_type == TEXTURE_SLICE_2D_ARRAY) {
  2050. ERR_FAIL_COND_V_MSG(p_layer != 0, RID(), "layer must be 0 when obtaining a 2D array mipmap slice");
  2051. slice_layers = src_texture->layers;
  2052. } else if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {
  2053. slice_layers = 6;
  2054. }
  2055. Texture texture = *src_texture;
  2056. get_image_format_required_size(texture.format, texture.width, texture.height, texture.depth, p_mipmap + 1, &texture.width, &texture.height);
  2057. texture.mipmaps = p_mipmaps;
  2058. texture.layers = slice_layers;
  2059. texture.base_mipmap = p_mipmap;
  2060. texture.base_layer = p_layer;
  2061. VkImageViewCreateInfo image_view_create_info;
  2062. image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  2063. image_view_create_info.pNext = nullptr;
  2064. image_view_create_info.flags = 0;
  2065. image_view_create_info.image = texture.image;
  2066. static const VkImageViewType view_types[TEXTURE_TYPE_MAX] = {
  2067. VK_IMAGE_VIEW_TYPE_1D,
  2068. VK_IMAGE_VIEW_TYPE_2D,
  2069. VK_IMAGE_VIEW_TYPE_2D,
  2070. VK_IMAGE_VIEW_TYPE_2D,
  2071. VK_IMAGE_VIEW_TYPE_1D,
  2072. VK_IMAGE_VIEW_TYPE_2D,
  2073. VK_IMAGE_VIEW_TYPE_2D,
  2074. };
  2075. image_view_create_info.viewType = view_types[texture.type];
  2076. if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {
  2077. image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_CUBE;
  2078. } else if (p_slice_type == TEXTURE_SLICE_3D) {
  2079. image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_3D;
  2080. } else if (p_slice_type == TEXTURE_SLICE_2D_ARRAY) {
  2081. image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY;
  2082. }
  2083. if (p_slice_type == TEXTURE_SLICE_2D) {
  2084. texture.type = TEXTURE_TYPE_2D;
  2085. } else if (p_slice_type == TEXTURE_SLICE_3D) {
  2086. texture.type = TEXTURE_TYPE_3D;
  2087. }
  2088. if (p_view.format_override == DATA_FORMAT_MAX || p_view.format_override == texture.format) {
  2089. image_view_create_info.format = vulkan_formats[texture.format];
  2090. } else {
  2091. ERR_FAIL_INDEX_V(p_view.format_override, DATA_FORMAT_MAX, RID());
  2092. ERR_FAIL_COND_V_MSG(texture.allowed_shared_formats.find(p_view.format_override) == -1, RID(),
  2093. "Format override is not in the list of allowed shareable formats for original texture.");
  2094. image_view_create_info.format = vulkan_formats[p_view.format_override];
  2095. }
  2096. static const VkComponentSwizzle component_swizzles[TEXTURE_SWIZZLE_MAX] = {
  2097. VK_COMPONENT_SWIZZLE_IDENTITY,
  2098. VK_COMPONENT_SWIZZLE_ZERO,
  2099. VK_COMPONENT_SWIZZLE_ONE,
  2100. VK_COMPONENT_SWIZZLE_R,
  2101. VK_COMPONENT_SWIZZLE_G,
  2102. VK_COMPONENT_SWIZZLE_B,
  2103. VK_COMPONENT_SWIZZLE_A
  2104. };
  2105. image_view_create_info.components.r = component_swizzles[p_view.swizzle_r];
  2106. image_view_create_info.components.g = component_swizzles[p_view.swizzle_g];
  2107. image_view_create_info.components.b = component_swizzles[p_view.swizzle_b];
  2108. image_view_create_info.components.a = component_swizzles[p_view.swizzle_a];
  2109. if (p_slice_type == TEXTURE_SLICE_CUBEMAP) {
  2110. ERR_FAIL_COND_V_MSG(p_layer >= src_texture->layers, RID(),
  2111. "Specified layer is invalid for cubemap");
  2112. ERR_FAIL_COND_V_MSG((p_layer % 6) != 0, RID(),
  2113. "Specified layer must be a multiple of 6.");
  2114. }
  2115. image_view_create_info.subresourceRange.baseMipLevel = p_mipmap;
  2116. image_view_create_info.subresourceRange.levelCount = p_mipmaps;
  2117. image_view_create_info.subresourceRange.layerCount = slice_layers;
  2118. image_view_create_info.subresourceRange.baseArrayLayer = p_layer;
  2119. if (texture.usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2120. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  2121. } else {
  2122. image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2123. }
  2124. VkResult err = vkCreateImageView(device, &image_view_create_info, nullptr, &texture.view);
  2125. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateImageView failed with error " + itos(err) + ".");
  2126. texture.owner = p_with_texture;
  2127. RID id = texture_owner.make_rid(texture);
  2128. #ifdef DEV_ENABLED
  2129. set_resource_name(id, "RID:" + itos(id.get_id()));
  2130. #endif
  2131. _add_dependency(id, p_with_texture);
  2132. return id;
  2133. }
  2134. Error RenderingDeviceVulkan::texture_update(RID p_texture, uint32_t p_layer, const Vector<uint8_t> &p_data, uint32_t p_post_barrier) {
  2135. return _texture_update(p_texture, p_layer, p_data, p_post_barrier, false);
  2136. }
  2137. static _ALWAYS_INLINE_ void _copy_region(uint8_t const *__restrict p_src, uint8_t *__restrict p_dst, uint32_t p_src_x, uint32_t p_src_y, uint32_t p_src_w, uint32_t p_src_h, uint32_t p_src_full_w, uint32_t p_unit_size) {
  2138. uint32_t src_offset = (p_src_y * p_src_full_w + p_src_x) * p_unit_size;
  2139. uint32_t dst_offset = 0;
  2140. for (uint32_t y = p_src_h; y > 0; y--) {
  2141. uint8_t const *__restrict src = p_src + src_offset;
  2142. uint8_t *__restrict dst = p_dst + dst_offset;
  2143. for (uint32_t x = p_src_w * p_unit_size; x > 0; x--) {
  2144. *dst = *src;
  2145. src++;
  2146. dst++;
  2147. }
  2148. src_offset += p_src_full_w * p_unit_size;
  2149. dst_offset += p_src_w * p_unit_size;
  2150. }
  2151. }
  2152. 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) {
  2153. _THREAD_SAFE_METHOD_
  2154. ERR_FAIL_COND_V_MSG((draw_list || compute_list) && !p_use_setup_queue, ERR_INVALID_PARAMETER,
  2155. "Updating textures is forbidden during creation of a draw or compute list");
  2156. Texture *texture = texture_owner.get_or_null(p_texture);
  2157. ERR_FAIL_COND_V(!texture, ERR_INVALID_PARAMETER);
  2158. if (texture->owner != RID()) {
  2159. p_texture = texture->owner;
  2160. texture = texture_owner.get_or_null(texture->owner);
  2161. ERR_FAIL_COND_V(!texture, ERR_BUG); //this is a bug
  2162. }
  2163. ERR_FAIL_COND_V_MSG(texture->bound, ERR_CANT_ACQUIRE_RESOURCE,
  2164. "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.");
  2165. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_CAN_UPDATE_BIT), ERR_INVALID_PARAMETER,
  2166. "Texture requires the TEXTURE_USAGE_CAN_UPDATE_BIT in order to be updatable.");
  2167. uint32_t layer_count = texture->layers;
  2168. if (texture->type == TEXTURE_TYPE_CUBE || texture->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2169. layer_count *= 6;
  2170. }
  2171. ERR_FAIL_COND_V(p_layer >= layer_count, ERR_INVALID_PARAMETER);
  2172. uint32_t width, height;
  2173. uint32_t image_size = get_image_format_required_size(texture->format, texture->width, texture->height, texture->depth, texture->mipmaps, &width, &height);
  2174. uint32_t required_size = image_size;
  2175. uint32_t required_align = get_compressed_image_format_block_byte_size(texture->format);
  2176. if (required_align == 1) {
  2177. required_align = get_image_format_pixel_size(texture->format);
  2178. }
  2179. if ((required_align % 4) != 0) { //alignment rules are really strange
  2180. required_align *= 4;
  2181. }
  2182. ERR_FAIL_COND_V_MSG(required_size != (uint32_t)p_data.size(), ERR_INVALID_PARAMETER,
  2183. "Required size for texture update (" + itos(required_size) + ") does not match data supplied size (" + itos(p_data.size()) + ").");
  2184. uint32_t region_size = texture_upload_region_size_px;
  2185. const uint8_t *r = p_data.ptr();
  2186. VkCommandBuffer command_buffer = p_use_setup_queue ? frames[frame].setup_command_buffer : frames[frame].draw_command_buffer;
  2187. //barrier to transfer
  2188. {
  2189. VkImageMemoryBarrier image_memory_barrier;
  2190. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2191. image_memory_barrier.pNext = nullptr;
  2192. image_memory_barrier.srcAccessMask = 0;
  2193. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2194. image_memory_barrier.oldLayout = texture->layout;
  2195. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2196. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2197. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2198. image_memory_barrier.image = texture->image;
  2199. image_memory_barrier.subresourceRange.aspectMask = texture->barrier_aspect_mask;
  2200. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2201. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  2202. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2203. image_memory_barrier.subresourceRange.layerCount = 1;
  2204. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2205. }
  2206. uint32_t mipmap_offset = 0;
  2207. uint32_t logic_width = texture->width;
  2208. uint32_t logic_height = texture->height;
  2209. for (uint32_t mm_i = 0; mm_i < texture->mipmaps; mm_i++) {
  2210. uint32_t depth;
  2211. uint32_t image_total = get_image_format_required_size(texture->format, texture->width, texture->height, texture->depth, mm_i + 1, &width, &height, &depth);
  2212. const uint8_t *read_ptr_mipmap = r + mipmap_offset;
  2213. image_size = image_total - mipmap_offset;
  2214. for (uint32_t z = 0; z < depth; z++) { //for 3D textures, depth may be > 0
  2215. const uint8_t *read_ptr = read_ptr_mipmap + image_size * z / depth;
  2216. for (uint32_t y = 0; y < height; y += region_size) {
  2217. for (uint32_t x = 0; x < width; x += region_size) {
  2218. uint32_t region_w = MIN(region_size, width - x);
  2219. uint32_t region_h = MIN(region_size, height - y);
  2220. uint32_t region_logic_w = MIN(region_size, logic_width - x);
  2221. uint32_t region_logic_h = MIN(region_size, logic_height - y);
  2222. uint32_t pixel_size = get_image_format_pixel_size(texture->format);
  2223. uint32_t to_allocate = region_w * region_h * pixel_size;
  2224. to_allocate >>= get_compressed_image_format_pixel_rshift(texture->format);
  2225. uint32_t alloc_offset, alloc_size;
  2226. Error err = _staging_buffer_allocate(to_allocate, required_align, alloc_offset, alloc_size, false);
  2227. ERR_FAIL_COND_V(err, ERR_CANT_CREATE);
  2228. uint8_t *write_ptr;
  2229. { //map
  2230. void *data_ptr = nullptr;
  2231. VkResult vkerr = vmaMapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation, &data_ptr);
  2232. ERR_FAIL_COND_V_MSG(vkerr, ERR_CANT_CREATE, "vmaMapMemory failed with error " + itos(vkerr) + ".");
  2233. write_ptr = (uint8_t *)data_ptr;
  2234. write_ptr += alloc_offset;
  2235. }
  2236. uint32_t block_w, block_h;
  2237. get_compressed_image_format_block_dimensions(texture->format, block_w, block_h);
  2238. ERR_FAIL_COND_V(region_w % block_w, ERR_BUG);
  2239. ERR_FAIL_COND_V(region_h % block_h, ERR_BUG);
  2240. if (block_w != 1 || block_h != 1) {
  2241. //compressed image (blocks)
  2242. //must copy a block region
  2243. uint32_t block_size = get_compressed_image_format_block_byte_size(texture->format);
  2244. //re-create current variables in blocky format
  2245. uint32_t xb = x / block_w;
  2246. uint32_t yb = y / block_h;
  2247. uint32_t wb = width / block_w;
  2248. //uint32_t hb = height / block_h;
  2249. uint32_t region_wb = region_w / block_w;
  2250. uint32_t region_hb = region_h / block_h;
  2251. _copy_region(read_ptr, write_ptr, xb, yb, region_wb, region_hb, wb, block_size);
  2252. } else {
  2253. //regular image (pixels)
  2254. //must copy a pixel region
  2255. _copy_region(read_ptr, write_ptr, x, y, region_w, region_h, width, pixel_size);
  2256. }
  2257. { //unmap
  2258. vmaUnmapMemory(allocator, staging_buffer_blocks[staging_buffer_current].allocation);
  2259. }
  2260. VkBufferImageCopy buffer_image_copy;
  2261. buffer_image_copy.bufferOffset = alloc_offset;
  2262. buffer_image_copy.bufferRowLength = 0; //tightly packed
  2263. buffer_image_copy.bufferImageHeight = 0; //tightly packed
  2264. buffer_image_copy.imageSubresource.aspectMask = texture->read_aspect_mask;
  2265. buffer_image_copy.imageSubresource.mipLevel = mm_i;
  2266. buffer_image_copy.imageSubresource.baseArrayLayer = p_layer;
  2267. buffer_image_copy.imageSubresource.layerCount = 1;
  2268. buffer_image_copy.imageOffset.x = x;
  2269. buffer_image_copy.imageOffset.y = y;
  2270. buffer_image_copy.imageOffset.z = z;
  2271. buffer_image_copy.imageExtent.width = region_logic_w;
  2272. buffer_image_copy.imageExtent.height = region_logic_h;
  2273. buffer_image_copy.imageExtent.depth = 1;
  2274. vkCmdCopyBufferToImage(command_buffer, staging_buffer_blocks[staging_buffer_current].buffer, texture->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_image_copy);
  2275. staging_buffer_blocks.write[staging_buffer_current].fill_amount += alloc_size;
  2276. }
  2277. }
  2278. }
  2279. mipmap_offset = image_total;
  2280. logic_width = MAX(1u, logic_width >> 1);
  2281. logic_height = MAX(1u, logic_height >> 1);
  2282. }
  2283. //barrier to restore layout
  2284. {
  2285. uint32_t barrier_flags = 0;
  2286. uint32_t access_flags = 0;
  2287. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2288. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2289. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2290. }
  2291. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2292. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2293. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2294. }
  2295. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2296. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2297. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2298. }
  2299. if (barrier_flags == 0) {
  2300. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2301. }
  2302. VkImageMemoryBarrier image_memory_barrier;
  2303. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2304. image_memory_barrier.pNext = nullptr;
  2305. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2306. image_memory_barrier.dstAccessMask = access_flags;
  2307. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2308. image_memory_barrier.newLayout = texture->layout;
  2309. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2310. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2311. image_memory_barrier.image = texture->image;
  2312. image_memory_barrier.subresourceRange.aspectMask = texture->barrier_aspect_mask;
  2313. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2314. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  2315. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2316. image_memory_barrier.subresourceRange.layerCount = 1;
  2317. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2318. }
  2319. if (texture->used_in_frame != frames_drawn) {
  2320. texture->used_in_raster = false;
  2321. texture->used_in_compute = false;
  2322. texture->used_in_frame = frames_drawn;
  2323. }
  2324. texture->used_in_transfer = true;
  2325. return OK;
  2326. }
  2327. Vector<uint8_t> RenderingDeviceVulkan::_texture_get_data_from_image(Texture *tex, VkImage p_image, VmaAllocation p_allocation, uint32_t p_layer, bool p_2d) {
  2328. uint32_t width, height, depth;
  2329. 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);
  2330. Vector<uint8_t> image_data;
  2331. image_data.resize(image_size);
  2332. void *img_mem;
  2333. vmaMapMemory(allocator, p_allocation, &img_mem);
  2334. uint32_t blockw, blockh;
  2335. get_compressed_image_format_block_dimensions(tex->format, blockw, blockh);
  2336. uint32_t block_size = get_compressed_image_format_block_byte_size(tex->format);
  2337. uint32_t pixel_size = get_image_format_pixel_size(tex->format);
  2338. {
  2339. uint8_t *w = image_data.ptrw();
  2340. uint32_t mipmap_offset = 0;
  2341. for (uint32_t mm_i = 0; mm_i < tex->mipmaps; mm_i++) {
  2342. 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);
  2343. uint8_t *write_ptr_mipmap = w + mipmap_offset;
  2344. image_size = image_total - mipmap_offset;
  2345. VkImageSubresource image_sub_resorce;
  2346. image_sub_resorce.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2347. image_sub_resorce.arrayLayer = p_layer;
  2348. image_sub_resorce.mipLevel = mm_i;
  2349. VkSubresourceLayout layout;
  2350. vkGetImageSubresourceLayout(device, p_image, &image_sub_resorce, &layout);
  2351. for (uint32_t z = 0; z < depth; z++) {
  2352. uint8_t *write_ptr = write_ptr_mipmap + z * image_size / depth;
  2353. const uint8_t *slice_read_ptr = ((uint8_t *)img_mem) + layout.offset + z * layout.depthPitch;
  2354. if (block_size > 1) {
  2355. //compressed
  2356. uint32_t line_width = (block_size * (width / blockw));
  2357. for (uint32_t y = 0; y < height / blockh; y++) {
  2358. const uint8_t *rptr = slice_read_ptr + y * layout.rowPitch;
  2359. uint8_t *wptr = write_ptr + y * line_width;
  2360. memcpy(wptr, rptr, line_width);
  2361. }
  2362. } else {
  2363. //uncompressed
  2364. for (uint32_t y = 0; y < height; y++) {
  2365. const uint8_t *rptr = slice_read_ptr + y * layout.rowPitch;
  2366. uint8_t *wptr = write_ptr + y * pixel_size * width;
  2367. memcpy(wptr, rptr, (uint64_t)pixel_size * width);
  2368. }
  2369. }
  2370. }
  2371. mipmap_offset = image_total;
  2372. }
  2373. }
  2374. vmaUnmapMemory(allocator, p_allocation);
  2375. return image_data;
  2376. }
  2377. Vector<uint8_t> RenderingDeviceVulkan::texture_get_data(RID p_texture, uint32_t p_layer) {
  2378. _THREAD_SAFE_METHOD_
  2379. Texture *tex = texture_owner.get_or_null(p_texture);
  2380. ERR_FAIL_COND_V(!tex, Vector<uint8_t>());
  2381. ERR_FAIL_COND_V_MSG(tex->bound, Vector<uint8_t>(),
  2382. "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.");
  2383. ERR_FAIL_COND_V_MSG(!(tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), Vector<uint8_t>(),
  2384. "Texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved.");
  2385. uint32_t layer_count = tex->layers;
  2386. if (tex->type == TEXTURE_TYPE_CUBE || tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2387. layer_count *= 6;
  2388. }
  2389. ERR_FAIL_COND_V(p_layer >= layer_count, Vector<uint8_t>());
  2390. if (tex->usage_flags & TEXTURE_USAGE_CPU_READ_BIT) {
  2391. //does not need anything fancy, map and read.
  2392. return _texture_get_data_from_image(tex, tex->image, tex->allocation, p_layer);
  2393. } else {
  2394. //compute total image size
  2395. uint32_t width, height, depth;
  2396. uint32_t buffer_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, tex->mipmaps, &width, &height, &depth);
  2397. //allocate buffer
  2398. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer; //makes more sense to retrieve
  2399. Buffer tmp_buffer;
  2400. _buffer_allocate(&tmp_buffer, buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_HOST, VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT);
  2401. { //Source image barrier
  2402. VkImageMemoryBarrier image_memory_barrier;
  2403. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2404. image_memory_barrier.pNext = nullptr;
  2405. image_memory_barrier.srcAccessMask = 0;
  2406. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2407. image_memory_barrier.oldLayout = tex->layout;
  2408. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2409. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2410. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2411. image_memory_barrier.image = tex->image;
  2412. image_memory_barrier.subresourceRange.aspectMask = tex->barrier_aspect_mask;
  2413. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2414. image_memory_barrier.subresourceRange.levelCount = tex->mipmaps;
  2415. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2416. image_memory_barrier.subresourceRange.layerCount = 1;
  2417. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2418. }
  2419. uint32_t computed_w = tex->width;
  2420. uint32_t computed_h = tex->height;
  2421. uint32_t computed_d = tex->depth;
  2422. uint32_t prev_size = 0;
  2423. uint32_t offset = 0;
  2424. for (uint32_t i = 0; i < tex->mipmaps; i++) {
  2425. VkBufferImageCopy buffer_image_copy;
  2426. uint32_t image_size = get_image_format_required_size(tex->format, tex->width, tex->height, tex->depth, i + 1);
  2427. uint32_t size = image_size - prev_size;
  2428. prev_size = image_size;
  2429. buffer_image_copy.bufferOffset = offset;
  2430. buffer_image_copy.bufferImageHeight = 0;
  2431. buffer_image_copy.bufferRowLength = 0;
  2432. buffer_image_copy.imageSubresource.aspectMask = tex->read_aspect_mask;
  2433. buffer_image_copy.imageSubresource.baseArrayLayer = p_layer;
  2434. buffer_image_copy.imageSubresource.layerCount = 1;
  2435. buffer_image_copy.imageSubresource.mipLevel = i;
  2436. buffer_image_copy.imageOffset.x = 0;
  2437. buffer_image_copy.imageOffset.y = 0;
  2438. buffer_image_copy.imageOffset.z = 0;
  2439. buffer_image_copy.imageExtent.width = computed_w;
  2440. buffer_image_copy.imageExtent.height = computed_h;
  2441. buffer_image_copy.imageExtent.depth = computed_d;
  2442. vkCmdCopyImageToBuffer(command_buffer, tex->image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, tmp_buffer.buffer, 1, &buffer_image_copy);
  2443. computed_w = MAX(1u, computed_w >> 1);
  2444. computed_h = MAX(1u, computed_h >> 1);
  2445. computed_d = MAX(1u, computed_d >> 1);
  2446. offset += size;
  2447. }
  2448. { //restore src
  2449. VkImageMemoryBarrier image_memory_barrier;
  2450. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2451. image_memory_barrier.pNext = nullptr;
  2452. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2453. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2454. if (tex->usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  2455. image_memory_barrier.dstAccessMask |= VK_ACCESS_SHADER_WRITE_BIT;
  2456. }
  2457. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2458. image_memory_barrier.newLayout = tex->layout;
  2459. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2460. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2461. image_memory_barrier.image = tex->image;
  2462. image_memory_barrier.subresourceRange.aspectMask = tex->barrier_aspect_mask;
  2463. image_memory_barrier.subresourceRange.baseMipLevel = 0;
  2464. image_memory_barrier.subresourceRange.levelCount = tex->mipmaps;
  2465. image_memory_barrier.subresourceRange.baseArrayLayer = p_layer;
  2466. image_memory_barrier.subresourceRange.layerCount = 1;
  2467. 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);
  2468. }
  2469. _flush(true);
  2470. void *buffer_mem;
  2471. VkResult vkerr = vmaMapMemory(allocator, tmp_buffer.allocation, &buffer_mem);
  2472. ERR_FAIL_COND_V_MSG(vkerr, Vector<uint8_t>(), "vmaMapMemory failed with error " + itos(vkerr) + ".");
  2473. Vector<uint8_t> buffer_data;
  2474. {
  2475. buffer_data.resize(buffer_size);
  2476. uint8_t *w = buffer_data.ptrw();
  2477. memcpy(w, buffer_mem, buffer_size);
  2478. }
  2479. vmaUnmapMemory(allocator, tmp_buffer.allocation);
  2480. _buffer_free(&tmp_buffer);
  2481. return buffer_data;
  2482. }
  2483. }
  2484. bool RenderingDeviceVulkan::texture_is_shared(RID p_texture) {
  2485. _THREAD_SAFE_METHOD_
  2486. Texture *tex = texture_owner.get_or_null(p_texture);
  2487. ERR_FAIL_COND_V(!tex, false);
  2488. return tex->owner.is_valid();
  2489. }
  2490. bool RenderingDeviceVulkan::texture_is_valid(RID p_texture) {
  2491. return texture_owner.owns(p_texture);
  2492. }
  2493. Size2i RenderingDeviceVulkan::texture_size(RID p_texture) {
  2494. _THREAD_SAFE_METHOD_
  2495. Texture *tex = texture_owner.get_or_null(p_texture);
  2496. ERR_FAIL_COND_V(!tex, Size2i());
  2497. return Size2i(tex->width, tex->height);
  2498. }
  2499. 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) {
  2500. _THREAD_SAFE_METHOD_
  2501. Texture *src_tex = texture_owner.get_or_null(p_from_texture);
  2502. ERR_FAIL_COND_V(!src_tex, ERR_INVALID_PARAMETER);
  2503. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  2504. "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.");
  2505. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER,
  2506. "Source texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved.");
  2507. uint32_t src_layer_count = src_tex->layers;
  2508. uint32_t src_width, src_height, src_depth;
  2509. 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);
  2510. if (src_tex->type == TEXTURE_TYPE_CUBE || src_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2511. src_layer_count *= 6;
  2512. }
  2513. ERR_FAIL_COND_V(p_from.x < 0 || p_from.x + p_size.x > src_width, ERR_INVALID_PARAMETER);
  2514. ERR_FAIL_COND_V(p_from.y < 0 || p_from.y + p_size.y > src_height, ERR_INVALID_PARAMETER);
  2515. ERR_FAIL_COND_V(p_from.z < 0 || p_from.z + p_size.z > src_depth, ERR_INVALID_PARAMETER);
  2516. ERR_FAIL_COND_V(p_src_mipmap >= src_tex->mipmaps, ERR_INVALID_PARAMETER);
  2517. ERR_FAIL_COND_V(p_src_layer >= src_layer_count, ERR_INVALID_PARAMETER);
  2518. Texture *dst_tex = texture_owner.get_or_null(p_to_texture);
  2519. ERR_FAIL_COND_V(!dst_tex, ERR_INVALID_PARAMETER);
  2520. ERR_FAIL_COND_V_MSG(dst_tex->bound, ERR_INVALID_PARAMETER,
  2521. "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.");
  2522. ERR_FAIL_COND_V_MSG(!(dst_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  2523. "Destination texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be retrieved.");
  2524. uint32_t dst_layer_count = dst_tex->layers;
  2525. uint32_t dst_width, dst_height, dst_depth;
  2526. 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);
  2527. if (dst_tex->type == TEXTURE_TYPE_CUBE || dst_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2528. dst_layer_count *= 6;
  2529. }
  2530. ERR_FAIL_COND_V(p_to.x < 0 || p_to.x + p_size.x > dst_width, ERR_INVALID_PARAMETER);
  2531. ERR_FAIL_COND_V(p_to.y < 0 || p_to.y + p_size.y > dst_height, ERR_INVALID_PARAMETER);
  2532. ERR_FAIL_COND_V(p_to.z < 0 || p_to.z + p_size.z > dst_depth, ERR_INVALID_PARAMETER);
  2533. ERR_FAIL_COND_V(p_dst_mipmap >= dst_tex->mipmaps, ERR_INVALID_PARAMETER);
  2534. ERR_FAIL_COND_V(p_dst_layer >= dst_layer_count, ERR_INVALID_PARAMETER);
  2535. ERR_FAIL_COND_V_MSG(src_tex->read_aspect_mask != dst_tex->read_aspect_mask, ERR_INVALID_PARAMETER,
  2536. "Source and destination texture must be of the same type (color or depth).");
  2537. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  2538. {
  2539. //PRE Copy the image
  2540. { //Source
  2541. VkImageMemoryBarrier image_memory_barrier;
  2542. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2543. image_memory_barrier.pNext = nullptr;
  2544. image_memory_barrier.srcAccessMask = 0;
  2545. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2546. image_memory_barrier.oldLayout = src_tex->layout;
  2547. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2548. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2549. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2550. image_memory_barrier.image = src_tex->image;
  2551. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2552. image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap;
  2553. image_memory_barrier.subresourceRange.levelCount = 1;
  2554. image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer;
  2555. image_memory_barrier.subresourceRange.layerCount = 1;
  2556. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2557. }
  2558. { //Dest
  2559. VkImageMemoryBarrier image_memory_barrier;
  2560. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2561. image_memory_barrier.pNext = nullptr;
  2562. image_memory_barrier.srcAccessMask = 0;
  2563. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2564. image_memory_barrier.oldLayout = dst_tex->layout;
  2565. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2566. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2567. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2568. image_memory_barrier.image = dst_tex->image;
  2569. image_memory_barrier.subresourceRange.aspectMask = dst_tex->read_aspect_mask;
  2570. image_memory_barrier.subresourceRange.baseMipLevel = p_dst_mipmap;
  2571. image_memory_barrier.subresourceRange.levelCount = 1;
  2572. image_memory_barrier.subresourceRange.baseArrayLayer = p_dst_layer;
  2573. image_memory_barrier.subresourceRange.layerCount = 1;
  2574. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2575. }
  2576. //COPY
  2577. {
  2578. VkImageCopy image_copy_region;
  2579. image_copy_region.srcSubresource.aspectMask = src_tex->read_aspect_mask;
  2580. image_copy_region.srcSubresource.baseArrayLayer = p_src_layer;
  2581. image_copy_region.srcSubresource.layerCount = 1;
  2582. image_copy_region.srcSubresource.mipLevel = p_src_mipmap;
  2583. image_copy_region.srcOffset.x = p_from.x;
  2584. image_copy_region.srcOffset.y = p_from.y;
  2585. image_copy_region.srcOffset.z = p_from.z;
  2586. image_copy_region.dstSubresource.aspectMask = dst_tex->read_aspect_mask;
  2587. image_copy_region.dstSubresource.baseArrayLayer = p_dst_layer;
  2588. image_copy_region.dstSubresource.layerCount = 1;
  2589. image_copy_region.dstSubresource.mipLevel = p_dst_mipmap;
  2590. image_copy_region.dstOffset.x = p_to.x;
  2591. image_copy_region.dstOffset.y = p_to.y;
  2592. image_copy_region.dstOffset.z = p_to.z;
  2593. image_copy_region.extent.width = p_size.x;
  2594. image_copy_region.extent.height = p_size.y;
  2595. image_copy_region.extent.depth = p_size.z;
  2596. 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);
  2597. }
  2598. // RESTORE LAYOUT for SRC and DST
  2599. uint32_t barrier_flags = 0;
  2600. uint32_t access_flags = 0;
  2601. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2602. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2603. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2604. }
  2605. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2606. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2607. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2608. }
  2609. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2610. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2611. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2612. }
  2613. if (barrier_flags == 0) {
  2614. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2615. }
  2616. { //restore src
  2617. VkImageMemoryBarrier image_memory_barrier;
  2618. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2619. image_memory_barrier.pNext = nullptr;
  2620. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2621. image_memory_barrier.dstAccessMask = access_flags;
  2622. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2623. image_memory_barrier.newLayout = src_tex->layout;
  2624. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2625. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2626. image_memory_barrier.image = src_tex->image;
  2627. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2628. image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap;
  2629. image_memory_barrier.subresourceRange.levelCount = src_tex->mipmaps;
  2630. image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer;
  2631. image_memory_barrier.subresourceRange.layerCount = 1;
  2632. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2633. }
  2634. { //make dst readable
  2635. VkImageMemoryBarrier image_memory_barrier;
  2636. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2637. image_memory_barrier.pNext = nullptr;
  2638. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2639. image_memory_barrier.dstAccessMask = access_flags;
  2640. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2641. image_memory_barrier.newLayout = dst_tex->layout;
  2642. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2643. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2644. image_memory_barrier.image = dst_tex->image;
  2645. image_memory_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2646. image_memory_barrier.subresourceRange.baseMipLevel = p_src_mipmap;
  2647. image_memory_barrier.subresourceRange.levelCount = 1;
  2648. image_memory_barrier.subresourceRange.baseArrayLayer = p_src_layer;
  2649. image_memory_barrier.subresourceRange.layerCount = 1;
  2650. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2651. }
  2652. }
  2653. if (dst_tex->used_in_frame != frames_drawn) {
  2654. dst_tex->used_in_raster = false;
  2655. dst_tex->used_in_compute = false;
  2656. dst_tex->used_in_frame = frames_drawn;
  2657. }
  2658. dst_tex->used_in_transfer = true;
  2659. return OK;
  2660. }
  2661. Error RenderingDeviceVulkan::texture_resolve_multisample(RID p_from_texture, RID p_to_texture, uint32_t p_post_barrier) {
  2662. _THREAD_SAFE_METHOD_
  2663. Texture *src_tex = texture_owner.get_or_null(p_from_texture);
  2664. ERR_FAIL_COND_V(!src_tex, ERR_INVALID_PARAMETER);
  2665. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  2666. "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.");
  2667. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_FROM_BIT), ERR_INVALID_PARAMETER,
  2668. "Source texture requires the TEXTURE_USAGE_CAN_COPY_FROM_BIT in order to be retrieved.");
  2669. 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)");
  2670. ERR_FAIL_COND_V_MSG(src_tex->samples == TEXTURE_SAMPLES_1, ERR_INVALID_PARAMETER, "Source texture must be multisampled.");
  2671. Texture *dst_tex = texture_owner.get_or_null(p_to_texture);
  2672. ERR_FAIL_COND_V(!dst_tex, ERR_INVALID_PARAMETER);
  2673. ERR_FAIL_COND_V_MSG(dst_tex->bound, ERR_INVALID_PARAMETER,
  2674. "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.");
  2675. ERR_FAIL_COND_V_MSG(!(dst_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  2676. "Destination texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be retrieved.");
  2677. 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).");
  2678. ERR_FAIL_COND_V_MSG(dst_tex->samples != TEXTURE_SAMPLES_1, ERR_INVALID_PARAMETER, "Destination texture must not be multisampled.");
  2679. ERR_FAIL_COND_V_MSG(src_tex->format != dst_tex->format, ERR_INVALID_PARAMETER, "Source and Destination textures must be the same format.");
  2680. 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.");
  2681. ERR_FAIL_COND_V_MSG(src_tex->read_aspect_mask != dst_tex->read_aspect_mask, ERR_INVALID_PARAMETER,
  2682. "Source and destination texture must be of the same type (color or depth).");
  2683. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  2684. {
  2685. //PRE Copy the image
  2686. { //Source
  2687. VkImageMemoryBarrier image_memory_barrier;
  2688. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2689. image_memory_barrier.pNext = nullptr;
  2690. image_memory_barrier.srcAccessMask = 0;
  2691. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2692. image_memory_barrier.oldLayout = src_tex->layout;
  2693. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2694. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2695. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2696. image_memory_barrier.image = src_tex->image;
  2697. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2698. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap;
  2699. image_memory_barrier.subresourceRange.levelCount = 1;
  2700. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer;
  2701. image_memory_barrier.subresourceRange.layerCount = 1;
  2702. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2703. }
  2704. { //Dest
  2705. VkImageMemoryBarrier image_memory_barrier;
  2706. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2707. image_memory_barrier.pNext = nullptr;
  2708. image_memory_barrier.srcAccessMask = 0;
  2709. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2710. image_memory_barrier.oldLayout = dst_tex->layout;
  2711. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2712. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2713. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2714. image_memory_barrier.image = dst_tex->image;
  2715. image_memory_barrier.subresourceRange.aspectMask = dst_tex->read_aspect_mask;
  2716. image_memory_barrier.subresourceRange.baseMipLevel = dst_tex->base_mipmap;
  2717. image_memory_barrier.subresourceRange.levelCount = 1;
  2718. image_memory_barrier.subresourceRange.baseArrayLayer = dst_tex->base_layer;
  2719. image_memory_barrier.subresourceRange.layerCount = 1;
  2720. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2721. }
  2722. //COPY
  2723. {
  2724. VkImageResolve image_copy_region;
  2725. image_copy_region.srcSubresource.aspectMask = src_tex->read_aspect_mask;
  2726. image_copy_region.srcSubresource.baseArrayLayer = src_tex->base_layer;
  2727. image_copy_region.srcSubresource.layerCount = 1;
  2728. image_copy_region.srcSubresource.mipLevel = src_tex->base_mipmap;
  2729. image_copy_region.srcOffset.x = 0;
  2730. image_copy_region.srcOffset.y = 0;
  2731. image_copy_region.srcOffset.z = 0;
  2732. image_copy_region.dstSubresource.aspectMask = dst_tex->read_aspect_mask;
  2733. image_copy_region.dstSubresource.baseArrayLayer = dst_tex->base_layer;
  2734. image_copy_region.dstSubresource.layerCount = 1;
  2735. image_copy_region.dstSubresource.mipLevel = dst_tex->base_mipmap;
  2736. image_copy_region.dstOffset.x = 0;
  2737. image_copy_region.dstOffset.y = 0;
  2738. image_copy_region.dstOffset.z = 0;
  2739. image_copy_region.extent.width = src_tex->width;
  2740. image_copy_region.extent.height = src_tex->height;
  2741. image_copy_region.extent.depth = src_tex->depth;
  2742. 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);
  2743. }
  2744. // RESTORE LAYOUT for SRC and DST
  2745. uint32_t barrier_flags = 0;
  2746. uint32_t access_flags = 0;
  2747. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2748. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2749. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2750. }
  2751. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2752. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2753. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2754. }
  2755. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2756. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2757. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2758. }
  2759. if (barrier_flags == 0) {
  2760. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2761. }
  2762. { //restore src
  2763. VkImageMemoryBarrier image_memory_barrier;
  2764. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2765. image_memory_barrier.pNext = nullptr;
  2766. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2767. image_memory_barrier.dstAccessMask = access_flags;
  2768. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2769. image_memory_barrier.newLayout = src_tex->layout;
  2770. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2771. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2772. image_memory_barrier.image = src_tex->image;
  2773. image_memory_barrier.subresourceRange.aspectMask = src_tex->barrier_aspect_mask;
  2774. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap;
  2775. image_memory_barrier.subresourceRange.levelCount = 1;
  2776. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer;
  2777. image_memory_barrier.subresourceRange.layerCount = 1;
  2778. vkCmdPipelineBarrier(command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2779. }
  2780. { //make dst readable
  2781. VkImageMemoryBarrier image_memory_barrier;
  2782. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2783. image_memory_barrier.pNext = nullptr;
  2784. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2785. image_memory_barrier.dstAccessMask = access_flags;
  2786. image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2787. image_memory_barrier.newLayout = dst_tex->layout;
  2788. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2789. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2790. image_memory_barrier.image = dst_tex->image;
  2791. image_memory_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2792. image_memory_barrier.subresourceRange.baseMipLevel = dst_tex->base_mipmap;
  2793. image_memory_barrier.subresourceRange.levelCount = 1;
  2794. image_memory_barrier.subresourceRange.baseArrayLayer = dst_tex->base_layer;
  2795. image_memory_barrier.subresourceRange.layerCount = 1;
  2796. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2797. }
  2798. }
  2799. return OK;
  2800. }
  2801. 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) {
  2802. _THREAD_SAFE_METHOD_
  2803. Texture *src_tex = texture_owner.get_or_null(p_texture);
  2804. ERR_FAIL_COND_V(!src_tex, ERR_INVALID_PARAMETER);
  2805. ERR_FAIL_COND_V_MSG(src_tex->bound, ERR_INVALID_PARAMETER,
  2806. "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.");
  2807. ERR_FAIL_COND_V(p_layers == 0, ERR_INVALID_PARAMETER);
  2808. ERR_FAIL_COND_V(p_mipmaps == 0, ERR_INVALID_PARAMETER);
  2809. ERR_FAIL_COND_V_MSG(!(src_tex->usage_flags & TEXTURE_USAGE_CAN_COPY_TO_BIT), ERR_INVALID_PARAMETER,
  2810. "Source texture requires the TEXTURE_USAGE_CAN_COPY_TO_BIT in order to be cleared.");
  2811. uint32_t src_layer_count = src_tex->layers;
  2812. if (src_tex->type == TEXTURE_TYPE_CUBE || src_tex->type == TEXTURE_TYPE_CUBE_ARRAY) {
  2813. src_layer_count *= 6;
  2814. }
  2815. ERR_FAIL_COND_V(p_base_mipmap + p_mipmaps > src_tex->mipmaps, ERR_INVALID_PARAMETER);
  2816. ERR_FAIL_COND_V(p_base_layer + p_layers > src_layer_count, ERR_INVALID_PARAMETER);
  2817. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  2818. VkImageLayout clear_layout = (src_tex->layout == VK_IMAGE_LAYOUT_GENERAL) ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2819. // 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)
  2820. const VkPipelineStageFlags valid_texture_stages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2821. constexpr VkAccessFlags read_access = VK_ACCESS_SHADER_READ_BIT;
  2822. constexpr VkAccessFlags read_write_access = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2823. const VkAccessFlags valid_texture_access = (src_tex->usage_flags & TEXTURE_USAGE_STORAGE_BIT) ? read_write_access : read_access;
  2824. { // Barrier from previous access with optional layout change (see clear_layout logic above)
  2825. VkImageMemoryBarrier image_memory_barrier;
  2826. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2827. image_memory_barrier.pNext = nullptr;
  2828. image_memory_barrier.srcAccessMask = valid_texture_access;
  2829. image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2830. image_memory_barrier.oldLayout = src_tex->layout;
  2831. image_memory_barrier.newLayout = clear_layout;
  2832. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2833. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2834. image_memory_barrier.image = src_tex->image;
  2835. image_memory_barrier.subresourceRange.aspectMask = src_tex->read_aspect_mask;
  2836. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap + p_base_mipmap;
  2837. image_memory_barrier.subresourceRange.levelCount = p_mipmaps;
  2838. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer + p_base_layer;
  2839. image_memory_barrier.subresourceRange.layerCount = p_layers;
  2840. vkCmdPipelineBarrier(command_buffer, valid_texture_stages, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2841. }
  2842. VkClearColorValue clear_color;
  2843. clear_color.float32[0] = p_color.r;
  2844. clear_color.float32[1] = p_color.g;
  2845. clear_color.float32[2] = p_color.b;
  2846. clear_color.float32[3] = p_color.a;
  2847. VkImageSubresourceRange range;
  2848. range.aspectMask = src_tex->read_aspect_mask;
  2849. range.baseArrayLayer = src_tex->base_layer + p_base_layer;
  2850. range.layerCount = p_layers;
  2851. range.baseMipLevel = src_tex->base_mipmap + p_base_mipmap;
  2852. range.levelCount = p_mipmaps;
  2853. vkCmdClearColorImage(command_buffer, src_tex->image, clear_layout, &clear_color, 1, &range);
  2854. { // Barrier to post clear accesses (changing back the layout if needed)
  2855. uint32_t barrier_flags = 0;
  2856. uint32_t access_flags = 0;
  2857. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  2858. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2859. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2860. }
  2861. if (p_post_barrier & BARRIER_MASK_RASTER) {
  2862. barrier_flags |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2863. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2864. }
  2865. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  2866. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  2867. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  2868. }
  2869. if (barrier_flags == 0) {
  2870. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2871. }
  2872. VkImageMemoryBarrier image_memory_barrier;
  2873. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2874. image_memory_barrier.pNext = nullptr;
  2875. image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2876. image_memory_barrier.dstAccessMask = access_flags;
  2877. image_memory_barrier.oldLayout = clear_layout;
  2878. image_memory_barrier.newLayout = src_tex->layout;
  2879. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2880. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2881. image_memory_barrier.image = src_tex->image;
  2882. image_memory_barrier.subresourceRange.aspectMask = src_tex->read_aspect_mask;
  2883. image_memory_barrier.subresourceRange.baseMipLevel = src_tex->base_mipmap + p_base_mipmap;
  2884. image_memory_barrier.subresourceRange.levelCount = p_mipmaps;
  2885. image_memory_barrier.subresourceRange.baseArrayLayer = src_tex->base_layer + p_base_layer;
  2886. image_memory_barrier.subresourceRange.layerCount = p_layers;
  2887. vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, barrier_flags, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
  2888. }
  2889. if (src_tex->used_in_frame != frames_drawn) {
  2890. src_tex->used_in_raster = false;
  2891. src_tex->used_in_compute = false;
  2892. src_tex->used_in_frame = frames_drawn;
  2893. }
  2894. src_tex->used_in_transfer = true;
  2895. return OK;
  2896. }
  2897. bool RenderingDeviceVulkan::texture_is_format_supported_for_usage(DataFormat p_format, uint32_t p_usage) const {
  2898. ERR_FAIL_INDEX_V(p_format, DATA_FORMAT_MAX, false);
  2899. _THREAD_SAFE_METHOD_
  2900. //validate that this image is supported for the intended use
  2901. VkFormatProperties properties;
  2902. vkGetPhysicalDeviceFormatProperties(context->get_physical_device(), vulkan_formats[p_format], &properties);
  2903. VkFormatFeatureFlags flags;
  2904. if (p_usage & TEXTURE_USAGE_CPU_READ_BIT) {
  2905. flags = properties.linearTilingFeatures;
  2906. } else {
  2907. flags = properties.optimalTilingFeatures;
  2908. }
  2909. if (p_usage & TEXTURE_USAGE_SAMPLING_BIT && !(flags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) {
  2910. return false;
  2911. }
  2912. if (p_usage & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) {
  2913. return false;
  2914. }
  2915. if (p_usage & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT && !(flags & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  2916. return false;
  2917. }
  2918. if (p_usage & TEXTURE_USAGE_STORAGE_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) {
  2919. return false;
  2920. }
  2921. if (p_usage & TEXTURE_USAGE_STORAGE_ATOMIC_BIT && !(flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)) {
  2922. return false;
  2923. }
  2924. return true;
  2925. }
  2926. /********************/
  2927. /**** ATTACHMENT ****/
  2928. /********************/
  2929. 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) {
  2930. // Set up dependencies from/to external equivalent to the default (implicit) one, and then amend them
  2931. const VkPipelineStageFlags default_access_mask = VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  2932. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  2933. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  2934. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  2935. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; // From Section 7.1 of Vulkan API Spec v1.1.148
  2936. 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;
  2937. 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 },
  2938. { 0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, default_access_mask, 0, 0 } };
  2939. VkSubpassDependency &dependency_from_external = dependencies[0];
  2940. VkSubpassDependency &dependency_to_external = dependencies[1];
  2941. LocalVector<int32_t> attachment_last_pass;
  2942. attachment_last_pass.resize(p_attachments.size());
  2943. Vector<VkAttachmentDescription> attachments;
  2944. Vector<int> attachment_remap;
  2945. for (int i = 0; i < p_attachments.size(); i++) {
  2946. if (p_attachments[i].usage_flags == AttachmentFormat::UNUSED_ATTACHMENT) {
  2947. attachment_remap.push_back(VK_ATTACHMENT_UNUSED);
  2948. continue;
  2949. }
  2950. ERR_FAIL_INDEX_V(p_attachments[i].format, DATA_FORMAT_MAX, VK_NULL_HANDLE);
  2951. ERR_FAIL_INDEX_V(p_attachments[i].samples, TEXTURE_SAMPLES_MAX, VK_NULL_HANDLE);
  2952. 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)),
  2953. VK_NULL_HANDLE, "Texture format for index (" + itos(i) + ") requires an attachment (color, depth, input or stencil) bit set.");
  2954. VkAttachmentDescription description = {};
  2955. description.flags = 0;
  2956. description.format = vulkan_formats[p_attachments[i].format];
  2957. description.samples = rasterization_sample_count[p_attachments[i].samples];
  2958. bool is_sampled = p_attachments[i].usage_flags & TEXTURE_USAGE_SAMPLING_BIT;
  2959. bool is_storage = p_attachments[i].usage_flags & TEXTURE_USAGE_STORAGE_BIT;
  2960. bool is_depth = p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  2961. // For each UNDEFINED, assume the prior use was a *read*, as we'd be discarding the output of a write
  2962. // Also, each UNDEFINED will do an immediate layout transition (write), s.t. we must ensure execution synchronization vs.
  2963. // the read. If this is a performance issue, one could track the actual last accessor of each resource, adding only that
  2964. // stage
  2965. switch (is_depth ? p_initial_depth_action : p_initial_action) {
  2966. case INITIAL_ACTION_CLEAR_REGION:
  2967. case INITIAL_ACTION_CLEAR: {
  2968. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2969. description.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  2970. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  2971. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2972. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2973. description.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  2974. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  2975. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  2976. dependency_from_external.srcStageMask |= reading_stages;
  2977. } else {
  2978. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2979. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2980. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2981. dependency_from_external.srcStageMask |= reading_stages;
  2982. }
  2983. } break;
  2984. case INITIAL_ACTION_KEEP: {
  2985. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  2986. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2987. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  2988. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2989. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  2990. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2991. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  2992. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2993. dependency_from_external.srcStageMask |= reading_stages;
  2994. } else {
  2995. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2996. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  2997. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  2998. dependency_from_external.srcStageMask |= reading_stages;
  2999. }
  3000. } break;
  3001. case INITIAL_ACTION_DROP: {
  3002. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3003. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3004. description.initialLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  3005. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3006. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3007. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3008. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  3009. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3010. dependency_from_external.srcStageMask |= reading_stages;
  3011. } else {
  3012. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3013. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3014. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  3015. dependency_from_external.srcStageMask |= reading_stages;
  3016. }
  3017. } break;
  3018. case INITIAL_ACTION_CLEAR_REGION_CONTINUE:
  3019. case INITIAL_ACTION_CONTINUE: {
  3020. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3021. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3022. description.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  3023. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3024. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3025. description.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3026. description.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  3027. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  3028. } else {
  3029. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3030. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3031. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  3032. dependency_from_external.srcStageMask |= reading_stages;
  3033. }
  3034. } break;
  3035. default: {
  3036. ERR_FAIL_V(VK_NULL_HANDLE); //should never reach here
  3037. }
  3038. }
  3039. bool used_last = false;
  3040. {
  3041. int last_pass = p_passes.size() - 1;
  3042. if (is_depth) {
  3043. //likely missing depth resolve?
  3044. if (p_passes[last_pass].depth_attachment == i) {
  3045. used_last = true;
  3046. }
  3047. } else {
  3048. if (p_passes[last_pass].resolve_attachments.size()) {
  3049. //if using resolve attachments, check resolve attachments
  3050. for (int j = 0; j < p_passes[last_pass].resolve_attachments.size(); j++) {
  3051. if (p_passes[last_pass].resolve_attachments[j] == i) {
  3052. used_last = true;
  3053. break;
  3054. }
  3055. }
  3056. } else {
  3057. for (int j = 0; j < p_passes[last_pass].color_attachments.size(); j++) {
  3058. if (p_passes[last_pass].color_attachments[j] == i) {
  3059. used_last = true;
  3060. break;
  3061. }
  3062. }
  3063. }
  3064. }
  3065. if (!used_last) {
  3066. for (int j = 0; j < p_passes[last_pass].preserve_attachments.size(); j++) {
  3067. if (p_passes[last_pass].preserve_attachments[j] == i) {
  3068. used_last = true;
  3069. break;
  3070. }
  3071. }
  3072. }
  3073. }
  3074. FinalAction final_action = p_final_action;
  3075. FinalAction final_depth_action = p_final_depth_action;
  3076. if (!used_last) {
  3077. if (is_depth) {
  3078. final_depth_action = FINAL_ACTION_DISCARD;
  3079. } else {
  3080. final_action = FINAL_ACTION_DISCARD;
  3081. }
  3082. }
  3083. switch (is_depth ? final_depth_action : final_action) {
  3084. case FINAL_ACTION_READ: {
  3085. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3086. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3087. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3088. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  3089. update_external_dependency_for_store(dependency_to_external, is_sampled, is_storage, false);
  3090. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3091. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3092. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
  3093. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  3094. update_external_dependency_for_store(dependency_to_external, is_sampled, is_storage, true);
  3095. } else {
  3096. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3097. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3098. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  3099. // TODO: What does this mean about the next usage (and thus appropriate dependency masks
  3100. }
  3101. } break;
  3102. case FINAL_ACTION_DISCARD: {
  3103. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3104. description.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3105. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3106. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  3107. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3108. description.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3109. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3110. description.finalLayout = is_sampled ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : (is_storage ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  3111. } else {
  3112. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3113. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3114. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  3115. }
  3116. } break;
  3117. case FINAL_ACTION_CONTINUE: {
  3118. if (p_attachments[i].usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  3119. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3120. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  3121. description.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  3122. } else if (p_attachments[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3123. description.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  3124. description.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
  3125. description.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  3126. } else {
  3127. description.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3128. description.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  3129. description.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //don't care what is there
  3130. }
  3131. } break;
  3132. default: {
  3133. ERR_FAIL_V(VK_NULL_HANDLE); //should never reach here
  3134. }
  3135. }
  3136. attachment_last_pass[i] = -1;
  3137. attachment_remap.push_back(attachments.size());
  3138. attachments.push_back(description);
  3139. }
  3140. LocalVector<VkSubpassDescription> subpasses;
  3141. LocalVector<LocalVector<VkAttachmentReference>> color_reference_array;
  3142. LocalVector<LocalVector<VkAttachmentReference>> input_reference_array;
  3143. LocalVector<LocalVector<VkAttachmentReference>> resolve_reference_array;
  3144. LocalVector<LocalVector<uint32_t>> preserve_reference_array;
  3145. LocalVector<VkAttachmentReference> depth_reference_array;
  3146. subpasses.resize(p_passes.size());
  3147. color_reference_array.resize(p_passes.size());
  3148. input_reference_array.resize(p_passes.size());
  3149. resolve_reference_array.resize(p_passes.size());
  3150. preserve_reference_array.resize(p_passes.size());
  3151. depth_reference_array.resize(p_passes.size());
  3152. LocalVector<VkSubpassDependency> subpass_dependencies;
  3153. for (int i = 0; i < p_passes.size(); i++) {
  3154. const FramebufferPass *pass = &p_passes[i];
  3155. LocalVector<VkAttachmentReference> &color_references = color_reference_array[i];
  3156. TextureSamples texture_samples = TEXTURE_SAMPLES_1;
  3157. bool is_multisample_first = true;
  3158. for (int j = 0; j < pass->color_attachments.size(); j++) {
  3159. int32_t attachment = pass->color_attachments[j];
  3160. VkAttachmentReference reference;
  3161. if (attachment == FramebufferPass::ATTACHMENT_UNUSED) {
  3162. reference.attachment = VK_ATTACHMENT_UNUSED;
  3163. reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3164. } else {
  3165. 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) + ").");
  3166. 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.");
  3167. 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.");
  3168. if (is_multisample_first) {
  3169. texture_samples = p_attachments[attachment].samples;
  3170. is_multisample_first = false;
  3171. } else {
  3172. 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.");
  3173. }
  3174. reference.attachment = attachment_remap[attachment];
  3175. reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  3176. attachment_last_pass[attachment] = i;
  3177. }
  3178. color_references.push_back(reference);
  3179. }
  3180. LocalVector<VkAttachmentReference> &input_references = input_reference_array[i];
  3181. for (int j = 0; j < pass->input_attachments.size(); j++) {
  3182. int32_t attachment = pass->input_attachments[j];
  3183. VkAttachmentReference reference;
  3184. if (attachment == FramebufferPass::ATTACHMENT_UNUSED) {
  3185. reference.attachment = VK_ATTACHMENT_UNUSED;
  3186. reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3187. } else {
  3188. 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) + ").");
  3189. 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.");
  3190. 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.");
  3191. reference.attachment = attachment_remap[attachment];
  3192. reference.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  3193. attachment_last_pass[attachment] = i;
  3194. }
  3195. input_references.push_back(reference);
  3196. }
  3197. LocalVector<VkAttachmentReference> &resolve_references = resolve_reference_array[i];
  3198. if (pass->resolve_attachments.size() > 0) {
  3199. 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()) + ").");
  3200. ERR_FAIL_COND_V_MSG(texture_samples == TEXTURE_SAMPLES_1, VK_NULL_HANDLE, "Resolve attachments specified, but color attachments are not multisample.");
  3201. }
  3202. for (int j = 0; j < pass->resolve_attachments.size(); j++) {
  3203. int32_t attachment = pass->resolve_attachments[j];
  3204. VkAttachmentReference reference;
  3205. if (attachment == FramebufferPass::ATTACHMENT_UNUSED) {
  3206. reference.attachment = VK_ATTACHMENT_UNUSED;
  3207. reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3208. } else {
  3209. 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) + ").");
  3210. 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.");
  3211. 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.");
  3212. 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.");
  3213. bool multisample = p_attachments[attachment].samples > TEXTURE_SAMPLES_1;
  3214. 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.");
  3215. reference.attachment = attachment_remap[attachment];
  3216. reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  3217. attachment_last_pass[attachment] = i;
  3218. }
  3219. resolve_references.push_back(reference);
  3220. }
  3221. VkAttachmentReference &depth_stencil_reference = depth_reference_array[i];
  3222. if (pass->depth_attachment != FramebufferPass::ATTACHMENT_UNUSED) {
  3223. int32_t attachment = pass->depth_attachment;
  3224. 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.");
  3225. 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.");
  3226. 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.");
  3227. depth_stencil_reference.attachment = attachment_remap[attachment];
  3228. depth_stencil_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  3229. attachment_last_pass[attachment] = i;
  3230. if (is_multisample_first) {
  3231. texture_samples = p_attachments[attachment].samples;
  3232. is_multisample_first = false;
  3233. } else {
  3234. 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.");
  3235. }
  3236. } else {
  3237. depth_stencil_reference.attachment = VK_ATTACHMENT_UNUSED;
  3238. depth_stencil_reference.layout = VK_IMAGE_LAYOUT_UNDEFINED;
  3239. }
  3240. LocalVector<uint32_t> &preserve_references = preserve_reference_array[i];
  3241. for (int j = 0; j < pass->preserve_attachments.size(); j++) {
  3242. int32_t attachment = pass->preserve_attachments[j];
  3243. 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.");
  3244. 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) + ").");
  3245. if (attachment_last_pass[attachment] != i) {
  3246. //preserve can still be used to keep depth or color from being discarded after use
  3247. attachment_last_pass[attachment] = i;
  3248. preserve_references.push_back(attachment);
  3249. }
  3250. }
  3251. VkSubpassDescription &subpass = subpasses[i];
  3252. subpass.flags = 0;
  3253. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  3254. subpass.inputAttachmentCount = input_references.size();
  3255. if (input_references.size()) {
  3256. subpass.pInputAttachments = input_references.ptr();
  3257. } else {
  3258. subpass.pInputAttachments = nullptr;
  3259. }
  3260. subpass.colorAttachmentCount = color_references.size();
  3261. if (color_references.size()) {
  3262. subpass.pColorAttachments = color_references.ptr();
  3263. } else {
  3264. subpass.pColorAttachments = nullptr;
  3265. }
  3266. if (depth_stencil_reference.attachment != VK_ATTACHMENT_UNUSED) {
  3267. subpass.pDepthStencilAttachment = &depth_stencil_reference;
  3268. } else {
  3269. subpass.pDepthStencilAttachment = nullptr;
  3270. }
  3271. if (resolve_references.size()) {
  3272. subpass.pResolveAttachments = resolve_references.ptr();
  3273. } else {
  3274. subpass.pResolveAttachments = nullptr;
  3275. }
  3276. subpass.preserveAttachmentCount = preserve_references.size();
  3277. if (preserve_references.size()) {
  3278. subpass.pPreserveAttachments = preserve_references.ptr();
  3279. } else {
  3280. subpass.pPreserveAttachments = nullptr;
  3281. }
  3282. if (r_samples) {
  3283. r_samples->push_back(texture_samples);
  3284. }
  3285. if (i > 0) {
  3286. VkSubpassDependency dependency;
  3287. dependency.srcSubpass = i - 1;
  3288. dependency.dstSubpass = i;
  3289. dependency.srcStageMask = 0;
  3290. dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  3291. 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;
  3292. dependency.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  3293. 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;
  3294. dependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
  3295. subpass_dependencies.push_back(dependency);
  3296. }
  3297. /*
  3298. // NOTE: Big Mallet Approach -- any layout transition causes a full barrier
  3299. if (reference.layout != description.initialLayout) {
  3300. // NOTE: this should be smarter based on the texture's knowledge of its previous role
  3301. dependency_from_external.srcStageMask |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
  3302. dependency_from_external.srcAccessMask |= VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
  3303. }
  3304. if (reference.layout != description.finalLayout) {
  3305. // NOTE: this should be smarter based on the texture's knowledge of its subsequent role
  3306. dependency_to_external.dstStageMask |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
  3307. dependency_to_external.dstAccessMask |= VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
  3308. }
  3309. */
  3310. }
  3311. VkRenderPassCreateInfo render_pass_create_info;
  3312. render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  3313. render_pass_create_info.pNext = nullptr;
  3314. render_pass_create_info.flags = 0;
  3315. render_pass_create_info.attachmentCount = attachments.size();
  3316. render_pass_create_info.pAttachments = attachments.ptr();
  3317. render_pass_create_info.subpassCount = subpasses.size();
  3318. render_pass_create_info.pSubpasses = subpasses.ptr();
  3319. // Commenting this because it seems it just avoids raster and compute to work at the same time.
  3320. // Other barriers seem to be protecting the render pass fine.
  3321. // render_pass_create_info.dependencyCount = 2;
  3322. // render_pass_create_info.pDependencies = dependencies;
  3323. render_pass_create_info.dependencyCount = subpass_dependencies.size();
  3324. if (subpass_dependencies.size()) {
  3325. render_pass_create_info.pDependencies = subpass_dependencies.ptr();
  3326. } else {
  3327. render_pass_create_info.pDependencies = nullptr;
  3328. }
  3329. // These are only used if we use multiview but we need to define them in scope.
  3330. const uint32_t view_mask = (1 << p_view_count) - 1;
  3331. const uint32_t correlation_mask = (1 << p_view_count) - 1;
  3332. Vector<uint32_t> view_masks;
  3333. VkRenderPassMultiviewCreateInfo render_pass_multiview_create_info;
  3334. if (p_view_count > 1) {
  3335. const VulkanContext::MultiviewCapabilities capabilities = context->get_multiview_capabilities();
  3336. // For now this only works with multiview!
  3337. ERR_FAIL_COND_V_MSG(!capabilities.is_supported, VK_NULL_HANDLE, "Multiview not supported");
  3338. // Make sure we limit this to the number of views we support.
  3339. 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");
  3340. // Set view masks for each subpass
  3341. for (uint32_t i = 0; i < subpasses.size(); i++) {
  3342. view_masks.push_back(view_mask);
  3343. }
  3344. render_pass_multiview_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO;
  3345. render_pass_multiview_create_info.pNext = nullptr;
  3346. render_pass_multiview_create_info.subpassCount = subpasses.size();
  3347. render_pass_multiview_create_info.pViewMasks = view_masks.ptr();
  3348. render_pass_multiview_create_info.dependencyCount = 0;
  3349. render_pass_multiview_create_info.pViewOffsets = nullptr;
  3350. render_pass_multiview_create_info.correlationMaskCount = 1;
  3351. render_pass_multiview_create_info.pCorrelationMasks = &correlation_mask;
  3352. render_pass_create_info.pNext = &render_pass_multiview_create_info;
  3353. }
  3354. VkRenderPass render_pass;
  3355. VkResult res = vkCreateRenderPass(device, &render_pass_create_info, nullptr, &render_pass);
  3356. ERR_FAIL_COND_V_MSG(res, VK_NULL_HANDLE, "vkCreateRenderPass failed with error " + itos(res) + ".");
  3357. return render_pass;
  3358. }
  3359. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create(const Vector<AttachmentFormat> &p_format, uint32_t p_view_count) {
  3360. FramebufferPass pass;
  3361. for (int i = 0; i < p_format.size(); i++) {
  3362. if (p_format[i].usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3363. pass.depth_attachment = i;
  3364. } else {
  3365. pass.color_attachments.push_back(i);
  3366. }
  3367. }
  3368. Vector<FramebufferPass> passes;
  3369. passes.push_back(pass);
  3370. return framebuffer_format_create_multipass(p_format, passes, p_view_count);
  3371. }
  3372. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create_multipass(const Vector<AttachmentFormat> &p_attachments, Vector<FramebufferPass> &p_passes, uint32_t p_view_count) {
  3373. _THREAD_SAFE_METHOD_
  3374. FramebufferFormatKey key;
  3375. key.attachments = p_attachments;
  3376. key.passes = p_passes;
  3377. key.view_count = p_view_count;
  3378. const RBMap<FramebufferFormatKey, FramebufferFormatID>::Element *E = framebuffer_format_cache.find(key);
  3379. if (E) {
  3380. //exists, return
  3381. return E->get();
  3382. }
  3383. Vector<TextureSamples> samples;
  3384. 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
  3385. if (render_pass == VK_NULL_HANDLE) { //was likely invalid
  3386. return INVALID_ID;
  3387. }
  3388. FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT));
  3389. E = framebuffer_format_cache.insert(key, id);
  3390. FramebufferFormat fb_format;
  3391. fb_format.E = E;
  3392. fb_format.render_pass = render_pass;
  3393. fb_format.pass_samples = samples;
  3394. fb_format.view_count = p_view_count;
  3395. framebuffer_formats[id] = fb_format;
  3396. return id;
  3397. }
  3398. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_format_create_empty(TextureSamples p_samples) {
  3399. FramebufferFormatKey key;
  3400. key.passes.push_back(FramebufferPass());
  3401. const RBMap<FramebufferFormatKey, FramebufferFormatID>::Element *E = framebuffer_format_cache.find(key);
  3402. if (E) {
  3403. //exists, return
  3404. return E->get();
  3405. }
  3406. VkSubpassDescription subpass;
  3407. subpass.flags = 0;
  3408. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  3409. subpass.inputAttachmentCount = 0; //unsupported for now
  3410. subpass.pInputAttachments = nullptr;
  3411. subpass.colorAttachmentCount = 0;
  3412. subpass.pColorAttachments = nullptr;
  3413. subpass.pDepthStencilAttachment = nullptr;
  3414. subpass.pResolveAttachments = nullptr;
  3415. subpass.preserveAttachmentCount = 0;
  3416. subpass.pPreserveAttachments = nullptr;
  3417. VkRenderPassCreateInfo render_pass_create_info;
  3418. render_pass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  3419. render_pass_create_info.pNext = nullptr;
  3420. render_pass_create_info.flags = 0;
  3421. render_pass_create_info.attachmentCount = 0;
  3422. render_pass_create_info.pAttachments = nullptr;
  3423. render_pass_create_info.subpassCount = 1;
  3424. render_pass_create_info.pSubpasses = &subpass;
  3425. render_pass_create_info.dependencyCount = 0;
  3426. render_pass_create_info.pDependencies = nullptr;
  3427. VkRenderPass render_pass;
  3428. VkResult res = vkCreateRenderPass(device, &render_pass_create_info, nullptr, &render_pass);
  3429. ERR_FAIL_COND_V_MSG(res, 0, "vkCreateRenderPass for empty fb failed with error " + itos(res) + ".");
  3430. if (render_pass == VK_NULL_HANDLE) { //was likely invalid
  3431. return INVALID_ID;
  3432. }
  3433. FramebufferFormatID id = FramebufferFormatID(framebuffer_format_cache.size()) | (FramebufferFormatID(ID_TYPE_FRAMEBUFFER_FORMAT) << FramebufferFormatID(ID_BASE_SHIFT));
  3434. E = framebuffer_format_cache.insert(key, id);
  3435. FramebufferFormat fb_format;
  3436. fb_format.E = E;
  3437. fb_format.render_pass = render_pass;
  3438. fb_format.pass_samples.push_back(p_samples);
  3439. framebuffer_formats[id] = fb_format;
  3440. return id;
  3441. }
  3442. RenderingDevice::TextureSamples RenderingDeviceVulkan::framebuffer_format_get_texture_samples(FramebufferFormatID p_format, uint32_t p_pass) {
  3443. HashMap<FramebufferFormatID, FramebufferFormat>::Iterator E = framebuffer_formats.find(p_format);
  3444. ERR_FAIL_COND_V(!E, TEXTURE_SAMPLES_1);
  3445. ERR_FAIL_COND_V(p_pass >= uint32_t(E->value.pass_samples.size()), TEXTURE_SAMPLES_1);
  3446. return E->value.pass_samples[p_pass];
  3447. }
  3448. /***********************/
  3449. /**** RENDER TARGET ****/
  3450. /***********************/
  3451. RID RenderingDeviceVulkan::framebuffer_create_empty(const Size2i &p_size, TextureSamples p_samples, FramebufferFormatID p_format_check) {
  3452. _THREAD_SAFE_METHOD_
  3453. Framebuffer framebuffer;
  3454. framebuffer.format_id = framebuffer_format_create_empty(p_samples);
  3455. ERR_FAIL_COND_V(p_format_check != INVALID_FORMAT_ID && framebuffer.format_id != p_format_check, RID());
  3456. framebuffer.size = p_size;
  3457. framebuffer.view_count = 1;
  3458. RID id = framebuffer_owner.make_rid(framebuffer);
  3459. #ifdef DEV_ENABLED
  3460. set_resource_name(id, "RID:" + itos(id.get_id()));
  3461. #endif
  3462. return id;
  3463. }
  3464. RID RenderingDeviceVulkan::framebuffer_create(const Vector<RID> &p_texture_attachments, FramebufferFormatID p_format_check, uint32_t p_view_count) {
  3465. _THREAD_SAFE_METHOD_
  3466. FramebufferPass pass;
  3467. for (int i = 0; i < p_texture_attachments.size(); i++) {
  3468. Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]);
  3469. ERR_FAIL_COND_V_MSG(texture && texture->layers != p_view_count, RID(), "Layers of our texture doesn't match view count for this framebuffer");
  3470. if (texture && texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  3471. pass.depth_attachment = i;
  3472. } else {
  3473. pass.color_attachments.push_back(texture ? i : FramebufferPass::ATTACHMENT_UNUSED);
  3474. }
  3475. }
  3476. Vector<FramebufferPass> passes;
  3477. passes.push_back(pass);
  3478. return framebuffer_create_multipass(p_texture_attachments, passes, p_format_check, p_view_count);
  3479. }
  3480. RID RenderingDeviceVulkan::framebuffer_create_multipass(const Vector<RID> &p_texture_attachments, Vector<FramebufferPass> &p_passes, FramebufferFormatID p_format_check, uint32_t p_view_count) {
  3481. _THREAD_SAFE_METHOD_
  3482. Vector<AttachmentFormat> attachments;
  3483. attachments.resize(p_texture_attachments.size());
  3484. Size2i size;
  3485. bool size_set = false;
  3486. for (int i = 0; i < p_texture_attachments.size(); i++) {
  3487. AttachmentFormat af;
  3488. Texture *texture = texture_owner.get_or_null(p_texture_attachments[i]);
  3489. if (!texture) {
  3490. af.usage_flags = AttachmentFormat::UNUSED_ATTACHMENT;
  3491. } else {
  3492. ERR_FAIL_COND_V_MSG(texture->layers != p_view_count, RID(), "Layers of our texture doesn't match view count for this framebuffer");
  3493. if (!size_set) {
  3494. size.width = texture->width;
  3495. size.height = texture->height;
  3496. size_set = true;
  3497. } else {
  3498. ERR_FAIL_COND_V_MSG((uint32_t)size.width != texture->width || (uint32_t)size.height != texture->height, RID(),
  3499. "All textures in a framebuffer should be the same size.");
  3500. }
  3501. af.format = texture->format;
  3502. af.samples = texture->samples;
  3503. af.usage_flags = texture->usage_flags;
  3504. }
  3505. attachments.write[i] = af;
  3506. }
  3507. ERR_FAIL_COND_V_MSG(!size_set, RID(), "All attachments unused.");
  3508. FramebufferFormatID format_id = framebuffer_format_create_multipass(attachments, p_passes, p_view_count);
  3509. if (format_id == INVALID_ID) {
  3510. return RID();
  3511. }
  3512. ERR_FAIL_COND_V_MSG(p_format_check != INVALID_ID && format_id != p_format_check, RID(),
  3513. "The format used to check this framebuffer differs from the intended framebuffer format.");
  3514. Framebuffer framebuffer;
  3515. framebuffer.format_id = format_id;
  3516. framebuffer.texture_ids = p_texture_attachments;
  3517. framebuffer.size = size;
  3518. framebuffer.view_count = p_view_count;
  3519. RID id = framebuffer_owner.make_rid(framebuffer);
  3520. #ifdef DEV_ENABLED
  3521. set_resource_name(id, "RID:" + itos(id.get_id()));
  3522. #endif
  3523. for (int i = 0; i < p_texture_attachments.size(); i++) {
  3524. if (p_texture_attachments[i].is_valid()) {
  3525. _add_dependency(id, p_texture_attachments[i]);
  3526. }
  3527. }
  3528. return id;
  3529. }
  3530. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::framebuffer_get_format(RID p_framebuffer) {
  3531. _THREAD_SAFE_METHOD_
  3532. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  3533. ERR_FAIL_COND_V(!framebuffer, INVALID_ID);
  3534. return framebuffer->format_id;
  3535. }
  3536. /*****************/
  3537. /**** SAMPLER ****/
  3538. /*****************/
  3539. RID RenderingDeviceVulkan::sampler_create(const SamplerState &p_state) {
  3540. _THREAD_SAFE_METHOD_
  3541. VkSamplerCreateInfo sampler_create_info;
  3542. sampler_create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  3543. sampler_create_info.pNext = nullptr;
  3544. sampler_create_info.flags = 0;
  3545. sampler_create_info.magFilter = p_state.mag_filter == SAMPLER_FILTER_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
  3546. sampler_create_info.minFilter = p_state.min_filter == SAMPLER_FILTER_LINEAR ? VK_FILTER_LINEAR : VK_FILTER_NEAREST;
  3547. sampler_create_info.mipmapMode = p_state.mip_filter == SAMPLER_FILTER_LINEAR ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST;
  3548. ERR_FAIL_INDEX_V(p_state.repeat_u, SAMPLER_REPEAT_MODE_MAX, RID());
  3549. sampler_create_info.addressModeU = address_modes[p_state.repeat_u];
  3550. ERR_FAIL_INDEX_V(p_state.repeat_v, SAMPLER_REPEAT_MODE_MAX, RID());
  3551. sampler_create_info.addressModeV = address_modes[p_state.repeat_v];
  3552. ERR_FAIL_INDEX_V(p_state.repeat_w, SAMPLER_REPEAT_MODE_MAX, RID());
  3553. sampler_create_info.addressModeW = address_modes[p_state.repeat_w];
  3554. sampler_create_info.mipLodBias = p_state.lod_bias;
  3555. sampler_create_info.anisotropyEnable = p_state.use_anisotropy;
  3556. sampler_create_info.maxAnisotropy = p_state.anisotropy_max;
  3557. sampler_create_info.compareEnable = p_state.enable_compare;
  3558. ERR_FAIL_INDEX_V(p_state.compare_op, COMPARE_OP_MAX, RID());
  3559. sampler_create_info.compareOp = compare_operators[p_state.compare_op];
  3560. sampler_create_info.minLod = p_state.min_lod;
  3561. sampler_create_info.maxLod = p_state.max_lod;
  3562. ERR_FAIL_INDEX_V(p_state.border_color, SAMPLER_BORDER_COLOR_MAX, RID());
  3563. sampler_create_info.borderColor = sampler_border_colors[p_state.border_color];
  3564. sampler_create_info.unnormalizedCoordinates = p_state.unnormalized_uvw;
  3565. VkSampler sampler;
  3566. VkResult res = vkCreateSampler(device, &sampler_create_info, nullptr, &sampler);
  3567. ERR_FAIL_COND_V_MSG(res, RID(), "vkCreateSampler failed with error " + itos(res) + ".");
  3568. RID id = sampler_owner.make_rid(sampler);
  3569. #ifdef DEV_ENABLED
  3570. set_resource_name(id, "RID:" + itos(id.get_id()));
  3571. #endif
  3572. return id;
  3573. }
  3574. /**********************/
  3575. /**** VERTEX ARRAY ****/
  3576. /**********************/
  3577. RID RenderingDeviceVulkan::vertex_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data, bool p_use_as_storage) {
  3578. _THREAD_SAFE_METHOD_
  3579. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  3580. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  3581. "Creating buffers with data is forbidden during creation of a draw list");
  3582. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  3583. "Creating buffers with data is forbidden during creation of a draw list");
  3584. uint32_t usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
  3585. if (p_use_as_storage) {
  3586. usage |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
  3587. }
  3588. Buffer buffer;
  3589. _buffer_allocate(&buffer, p_size_bytes, usage, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0);
  3590. if (p_data.size()) {
  3591. uint64_t data_size = p_data.size();
  3592. const uint8_t *r = p_data.ptr();
  3593. _buffer_update(&buffer, 0, r, data_size);
  3594. _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);
  3595. }
  3596. RID id = vertex_buffer_owner.make_rid(buffer);
  3597. #ifdef DEV_ENABLED
  3598. set_resource_name(id, "RID:" + itos(id.get_id()));
  3599. #endif
  3600. return id;
  3601. }
  3602. // 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
  3603. RenderingDevice::VertexFormatID RenderingDeviceVulkan::vertex_format_create(const Vector<VertexAttribute> &p_vertex_formats) {
  3604. _THREAD_SAFE_METHOD_
  3605. VertexDescriptionKey key;
  3606. key.vertex_formats = p_vertex_formats;
  3607. VertexFormatID *idptr = vertex_format_cache.getptr(key);
  3608. if (idptr) {
  3609. return *idptr;
  3610. }
  3611. //does not exist, create one and cache it
  3612. VertexDescriptionCache vdcache;
  3613. vdcache.bindings = memnew_arr(VkVertexInputBindingDescription, p_vertex_formats.size());
  3614. vdcache.attributes = memnew_arr(VkVertexInputAttributeDescription, p_vertex_formats.size());
  3615. HashSet<int> used_locations;
  3616. for (int i = 0; i < p_vertex_formats.size(); i++) {
  3617. ERR_CONTINUE(p_vertex_formats[i].format >= DATA_FORMAT_MAX);
  3618. ERR_FAIL_COND_V(used_locations.has(p_vertex_formats[i].location), INVALID_ID);
  3619. ERR_FAIL_COND_V_MSG(get_format_vertex_size(p_vertex_formats[i].format) == 0, INVALID_ID,
  3620. "Data format for attachment (" + itos(i) + "), '" + named_formats[p_vertex_formats[i].format] + "', is not valid for a vertex array.");
  3621. vdcache.bindings[i].binding = i;
  3622. vdcache.bindings[i].stride = p_vertex_formats[i].stride;
  3623. vdcache.bindings[i].inputRate = p_vertex_formats[i].frequency == VERTEX_FREQUENCY_INSTANCE ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX;
  3624. vdcache.attributes[i].binding = i;
  3625. vdcache.attributes[i].location = p_vertex_formats[i].location;
  3626. vdcache.attributes[i].format = vulkan_formats[p_vertex_formats[i].format];
  3627. vdcache.attributes[i].offset = p_vertex_formats[i].offset;
  3628. used_locations.insert(p_vertex_formats[i].location);
  3629. }
  3630. vdcache.create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  3631. vdcache.create_info.pNext = nullptr;
  3632. vdcache.create_info.flags = 0;
  3633. vdcache.create_info.vertexAttributeDescriptionCount = p_vertex_formats.size();
  3634. vdcache.create_info.pVertexAttributeDescriptions = vdcache.attributes;
  3635. vdcache.create_info.vertexBindingDescriptionCount = p_vertex_formats.size();
  3636. vdcache.create_info.pVertexBindingDescriptions = vdcache.bindings;
  3637. vdcache.vertex_formats = p_vertex_formats;
  3638. VertexFormatID id = VertexFormatID(vertex_format_cache.size()) | (VertexFormatID(ID_TYPE_VERTEX_FORMAT) << ID_BASE_SHIFT);
  3639. vertex_format_cache[key] = id;
  3640. vertex_formats[id] = vdcache;
  3641. return id;
  3642. }
  3643. RID RenderingDeviceVulkan::vertex_array_create(uint32_t p_vertex_count, VertexFormatID p_vertex_format, const Vector<RID> &p_src_buffers) {
  3644. _THREAD_SAFE_METHOD_
  3645. ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID());
  3646. const VertexDescriptionCache &vd = vertex_formats[p_vertex_format];
  3647. ERR_FAIL_COND_V(vd.vertex_formats.size() != p_src_buffers.size(), RID());
  3648. for (int i = 0; i < p_src_buffers.size(); i++) {
  3649. ERR_FAIL_COND_V(!vertex_buffer_owner.owns(p_src_buffers[i]), RID());
  3650. }
  3651. VertexArray vertex_array;
  3652. vertex_array.vertex_count = p_vertex_count;
  3653. vertex_array.description = p_vertex_format;
  3654. vertex_array.max_instances_allowed = 0xFFFFFFFF; //by default as many as you want
  3655. for (int i = 0; i < p_src_buffers.size(); i++) {
  3656. Buffer *buffer = vertex_buffer_owner.get_or_null(p_src_buffers[i]);
  3657. //validate with buffer
  3658. {
  3659. const VertexAttribute &atf = vd.vertex_formats[i];
  3660. uint32_t element_size = get_format_vertex_size(atf.format);
  3661. ERR_FAIL_COND_V(element_size == 0, RID()); //should never happens since this was prevalidated
  3662. if (atf.frequency == VERTEX_FREQUENCY_VERTEX) {
  3663. //validate size for regular drawing
  3664. uint64_t total_size = uint64_t(atf.stride) * (p_vertex_count - 1) + atf.offset + element_size;
  3665. ERR_FAIL_COND_V_MSG(total_size > buffer->size, RID(),
  3666. "Attachment (" + itos(i) + ") will read past the end of the buffer.");
  3667. } else {
  3668. //validate size for instances drawing
  3669. uint64_t available = buffer->size - atf.offset;
  3670. ERR_FAIL_COND_V_MSG(available < element_size, RID(),
  3671. "Attachment (" + itos(i) + ") uses instancing, but it's just too small.");
  3672. uint32_t instances_allowed = available / atf.stride;
  3673. vertex_array.max_instances_allowed = MIN(instances_allowed, vertex_array.max_instances_allowed);
  3674. }
  3675. }
  3676. vertex_array.buffers.push_back(buffer->buffer);
  3677. vertex_array.offsets.push_back(0); //offset unused, but passing anyway
  3678. }
  3679. RID id = vertex_array_owner.make_rid(vertex_array);
  3680. for (int i = 0; i < p_src_buffers.size(); i++) {
  3681. _add_dependency(id, p_src_buffers[i]);
  3682. }
  3683. return id;
  3684. }
  3685. RID RenderingDeviceVulkan::index_buffer_create(uint32_t p_index_count, IndexBufferFormat p_format, const Vector<uint8_t> &p_data, bool p_use_restart_indices) {
  3686. _THREAD_SAFE_METHOD_
  3687. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  3688. "Creating buffers with data is forbidden during creation of a draw list");
  3689. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  3690. "Creating buffers with data is forbidden during creation of a draw list");
  3691. ERR_FAIL_COND_V(p_index_count == 0, RID());
  3692. IndexBuffer index_buffer;
  3693. index_buffer.index_type = (p_format == INDEX_BUFFER_FORMAT_UINT16) ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32;
  3694. index_buffer.supports_restart_indices = p_use_restart_indices;
  3695. index_buffer.index_count = p_index_count;
  3696. uint32_t size_bytes = p_index_count * ((p_format == INDEX_BUFFER_FORMAT_UINT16) ? 2 : 4);
  3697. #ifdef DEBUG_ENABLED
  3698. if (p_data.size()) {
  3699. index_buffer.max_index = 0;
  3700. ERR_FAIL_COND_V_MSG((uint32_t)p_data.size() != size_bytes, RID(),
  3701. "Default index buffer initializer array size (" + itos(p_data.size()) + ") does not match format required size (" + itos(size_bytes) + ").");
  3702. const uint8_t *r = p_data.ptr();
  3703. if (p_format == INDEX_BUFFER_FORMAT_UINT16) {
  3704. const uint16_t *index16 = (const uint16_t *)r;
  3705. for (uint32_t i = 0; i < p_index_count; i++) {
  3706. if (p_use_restart_indices && index16[i] == 0xFFFF) {
  3707. continue; //restart index, ignore
  3708. }
  3709. index_buffer.max_index = MAX(index16[i], index_buffer.max_index);
  3710. }
  3711. } else {
  3712. const uint32_t *index32 = (const uint32_t *)r;
  3713. for (uint32_t i = 0; i < p_index_count; i++) {
  3714. if (p_use_restart_indices && index32[i] == 0xFFFFFFFF) {
  3715. continue; //restart index, ignore
  3716. }
  3717. index_buffer.max_index = MAX(index32[i], index_buffer.max_index);
  3718. }
  3719. }
  3720. } else {
  3721. index_buffer.max_index = 0xFFFFFFFF;
  3722. }
  3723. #else
  3724. index_buffer.max_index = 0xFFFFFFFF;
  3725. #endif
  3726. _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_AUTO_PREFER_DEVICE, 0);
  3727. if (p_data.size()) {
  3728. uint64_t data_size = p_data.size();
  3729. const uint8_t *r = p_data.ptr();
  3730. _buffer_update(&index_buffer, 0, r, data_size);
  3731. _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);
  3732. }
  3733. RID id = index_buffer_owner.make_rid(index_buffer);
  3734. #ifdef DEV_ENABLED
  3735. set_resource_name(id, "RID:" + itos(id.get_id()));
  3736. #endif
  3737. return id;
  3738. }
  3739. RID RenderingDeviceVulkan::index_array_create(RID p_index_buffer, uint32_t p_index_offset, uint32_t p_index_count) {
  3740. _THREAD_SAFE_METHOD_
  3741. ERR_FAIL_COND_V(!index_buffer_owner.owns(p_index_buffer), RID());
  3742. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_index_buffer);
  3743. ERR_FAIL_COND_V(p_index_count == 0, RID());
  3744. ERR_FAIL_COND_V(p_index_offset + p_index_count > index_buffer->index_count, RID());
  3745. IndexArray index_array;
  3746. index_array.max_index = index_buffer->max_index;
  3747. index_array.buffer = index_buffer->buffer;
  3748. index_array.offset = p_index_offset;
  3749. index_array.indices = p_index_count;
  3750. index_array.index_type = index_buffer->index_type;
  3751. index_array.supports_restart_indices = index_buffer->supports_restart_indices;
  3752. RID id = index_array_owner.make_rid(index_array);
  3753. _add_dependency(id, p_index_buffer);
  3754. return id;
  3755. }
  3756. /****************/
  3757. /**** SHADER ****/
  3758. /****************/
  3759. static const char *shader_stage_names[RenderingDevice::SHADER_STAGE_MAX] = {
  3760. "Vertex",
  3761. "Fragment",
  3762. "TesselationControl",
  3763. "TesselationEvaluation",
  3764. "Compute"
  3765. };
  3766. static const char *shader_uniform_names[RenderingDevice::UNIFORM_TYPE_MAX] = {
  3767. "Sampler", "CombinedSampler", "Texture", "Image", "TextureBuffer", "SamplerTextureBuffer", "ImageBuffer", "UniformBuffer", "StorageBuffer", "InputAttachment"
  3768. };
  3769. static VkShaderStageFlagBits shader_stage_masks[RenderingDevice::SHADER_STAGE_MAX] = {
  3770. VK_SHADER_STAGE_VERTEX_BIT,
  3771. VK_SHADER_STAGE_FRAGMENT_BIT,
  3772. VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT,
  3773. VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
  3774. VK_SHADER_STAGE_COMPUTE_BIT,
  3775. };
  3776. String RenderingDeviceVulkan::_shader_uniform_debug(RID p_shader, int p_set) {
  3777. String ret;
  3778. const Shader *shader = shader_owner.get_or_null(p_shader);
  3779. ERR_FAIL_COND_V(!shader, String());
  3780. for (int i = 0; i < shader->sets.size(); i++) {
  3781. if (p_set >= 0 && i != p_set) {
  3782. continue;
  3783. }
  3784. for (int j = 0; j < shader->sets[i].uniform_info.size(); j++) {
  3785. const UniformInfo &ui = shader->sets[i].uniform_info[j];
  3786. if (!ret.is_empty()) {
  3787. ret += "\n";
  3788. }
  3789. ret += "Set: " + itos(i) + " Binding: " + itos(ui.binding) + " Type: " + shader_uniform_names[ui.type] + " Writable: " + (ui.writable ? "Y" : "N") + " Length: " + itos(ui.length);
  3790. }
  3791. }
  3792. return ret;
  3793. }
  3794. #if 0
  3795. 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) {
  3796. VkDescriptorSetLayoutBinding layout_binding;
  3797. UniformInfo info;
  3798. switch (reflection.getType()->getBasicType()) {
  3799. case glslang::EbtSampler: {
  3800. //print_line("DEBUG: IsSampler");
  3801. if (reflection.getType()->getSampler().dim == glslang::EsdBuffer) {
  3802. //texture buffers
  3803. if (reflection.getType()->getSampler().isCombined()) {
  3804. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  3805. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER;
  3806. //print_line("DEBUG: SAMPLER: texel combined");
  3807. } else if (reflection.getType()->getSampler().isTexture()) {
  3808. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  3809. info.type = UNIFORM_TYPE_TEXTURE_BUFFER;
  3810. //print_line("DEBUG: SAMPLER: texel alone");
  3811. } else if (reflection.getType()->getSampler().isImage()) {
  3812. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  3813. info.type = UNIFORM_TYPE_IMAGE_BUFFER;
  3814. //print_line("DEBUG: SAMPLER: texel buffer");
  3815. } else {
  3816. if (r_error) {
  3817. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' is of unsupported buffer type.";
  3818. }
  3819. return false;
  3820. }
  3821. } else if (reflection.getType()->getSampler().isCombined()) {
  3822. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  3823. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
  3824. //print_line("DEBUG: SAMPLER: combined");
  3825. } else if (reflection.getType()->getSampler().isPureSampler()) {
  3826. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  3827. info.type = UNIFORM_TYPE_SAMPLER;
  3828. //print_line("DEBUG: SAMPLER: sampler");
  3829. } else if (reflection.getType()->getSampler().isTexture()) {
  3830. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  3831. info.type = UNIFORM_TYPE_TEXTURE;
  3832. //print_line("DEBUG: SAMPLER: image");
  3833. } else if (reflection.getType()->getSampler().isImage()) {
  3834. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  3835. info.type = UNIFORM_TYPE_IMAGE;
  3836. //print_line("DEBUG: SAMPLER: storage image");
  3837. } else {
  3838. //print_line("DEBUG: sampler unknown");
  3839. if (r_error) {
  3840. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' is of unsupported sampler type.";
  3841. }
  3842. return false;
  3843. }
  3844. if (reflection.getType()->isArray()) {
  3845. layout_binding.descriptorCount = reflection.getType()->getArraySizes()->getCumulativeSize();
  3846. //print_line("DEBUG: array of size: " + itos(layout_binding.descriptorCount));
  3847. } else {
  3848. layout_binding.descriptorCount = 1;
  3849. }
  3850. info.length = layout_binding.descriptorCount;
  3851. } break;
  3852. /*case glslang::EbtStruct: {
  3853. print_line("DEBUG: Struct");
  3854. } break;*/
  3855. case glslang::EbtBlock: {
  3856. //print_line("DEBUG: Block");
  3857. if (reflection.getType()->getQualifier().storage == glslang::EvqUniform) {
  3858. if (reflection.getType()->getQualifier().layoutPushConstant) {
  3859. uint32_t len = reflection.size;
  3860. if (push_constant.push_constant_size != 0 && push_constant.push_constant_size != len) {
  3861. *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.";
  3862. return false;
  3863. }
  3864. push_constant.push_constant_size = len;
  3865. push_constant.push_constants_vk_stage |= shader_stage_masks[p_stage];
  3866. return true;
  3867. }
  3868. //print_line("DEBUG: Uniform buffer");
  3869. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  3870. info.type = UNIFORM_TYPE_UNIFORM_BUFFER;
  3871. } else if (reflection.getType()->getQualifier().storage == glslang::EvqBuffer) {
  3872. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  3873. info.type = UNIFORM_TYPE_STORAGE_BUFFER;
  3874. //print_line("DEBUG: Storage buffer");
  3875. } else {
  3876. if (r_error) {
  3877. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' is of unsupported block type: (" + itos(reflection.getType()->getQualifier().storage) + ").";
  3878. }
  3879. return false;
  3880. }
  3881. if (reflection.getType()->isArray()) {
  3882. layout_binding.descriptorCount = reflection.getType()->getArraySizes()->getCumulativeSize();
  3883. //print_line("DEBUG: array of size: " + itos(layout_binding.descriptorCount));
  3884. } else {
  3885. layout_binding.descriptorCount = 1;
  3886. }
  3887. info.length = reflection.size;
  3888. } break;
  3889. /*case glslang::EbtReference: {
  3890. } break;*/
  3891. /*case glslang::EbtAtomicUint: {
  3892. } break;*/
  3893. default: {
  3894. if (reflection.getType()->getQualifier().hasOffset() || reflection.name.find(".") != std::string::npos) {
  3895. //member of uniform block?
  3896. return true;
  3897. }
  3898. if (r_error) {
  3899. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' unsupported uniform type.";
  3900. }
  3901. return false;
  3902. }
  3903. }
  3904. if (!reflection.getType()->getQualifier().hasBinding()) {
  3905. if (r_error) {
  3906. *r_error = "On shader stage '" + String(shader_stage_names[p_stage]) + "', uniform '" + reflection.name + "' lacks a binding number.";
  3907. }
  3908. return false;
  3909. }
  3910. uint32_t set = reflection.getType()->getQualifier().hasSet() ? reflection.getType()->getQualifier().layoutSet : 0;
  3911. if (set >= MAX_UNIFORM_SETS) {
  3912. if (r_error) {
  3913. *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) + ").";
  3914. }
  3915. return false;
  3916. }
  3917. if (set >= limits.maxBoundDescriptorSets) {
  3918. if (r_error) {
  3919. *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) + ").";
  3920. }
  3921. return false;
  3922. }
  3923. uint32_t binding = reflection.getType()->getQualifier().layoutBinding;
  3924. if (set < (uint32_t)bindings.size()) {
  3925. //check if this already exists
  3926. for (int i = 0; i < bindings[set].size(); i++) {
  3927. if (bindings[set][i].binding == binding) {
  3928. //already exists, verify that it's the same type
  3929. if (bindings[set][i].descriptorType != layout_binding.descriptorType) {
  3930. if (r_error) {
  3931. *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.";
  3932. }
  3933. return false;
  3934. }
  3935. //also, verify that it's the same size
  3936. if (bindings[set][i].descriptorCount != layout_binding.descriptorCount || uniform_infos[set][i].length != info.length) {
  3937. if (r_error) {
  3938. *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.";
  3939. }
  3940. return false;
  3941. }
  3942. //just append stage mask and return
  3943. bindings.write[set].write[i].stageFlags |= shader_stage_masks[p_stage];
  3944. uniform_infos.write[set].write[i].stages |= 1 << p_stage;
  3945. return true;
  3946. }
  3947. }
  3948. }
  3949. layout_binding.binding = binding;
  3950. layout_binding.stageFlags = shader_stage_masks[p_stage];
  3951. layout_binding.pImmutableSamplers = nullptr; //no support for this yet
  3952. info.stages = 1 << p_stage;
  3953. info.binding = binding;
  3954. if (set >= (uint32_t)bindings.size()) {
  3955. bindings.resize(set + 1);
  3956. uniform_infos.resize(set + 1);
  3957. }
  3958. #if 0
  3959. 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));
  3960. #endif
  3961. bindings.write[set].push_back(layout_binding);
  3962. uniform_infos.write[set].push_back(info);
  3963. return true;
  3964. }
  3965. #endif
  3966. //version 1: initial
  3967. //version 2: Added shader name
  3968. //version 3: Added writable
  3969. #define SHADER_BINARY_VERSION 3
  3970. String RenderingDeviceVulkan::shader_get_binary_cache_key() const {
  3971. return "Vulkan-SV" + itos(SHADER_BINARY_VERSION);
  3972. }
  3973. struct RenderingDeviceVulkanShaderBinaryDataBinding {
  3974. uint32_t type;
  3975. uint32_t binding;
  3976. uint32_t stages;
  3977. uint32_t length; //size of arrays (in total elements), or ubos (in bytes * total elements)
  3978. uint32_t writable;
  3979. };
  3980. struct RenderingDeviceVulkanShaderBinarySpecializationConstant {
  3981. uint32_t type;
  3982. uint32_t constant_id;
  3983. union {
  3984. uint32_t int_value;
  3985. float float_value;
  3986. bool bool_value;
  3987. };
  3988. uint32_t stage_flags;
  3989. };
  3990. struct RenderingDeviceVulkanShaderBinaryData {
  3991. uint32_t vertex_input_mask;
  3992. uint32_t fragment_outputs;
  3993. uint32_t specialization_constant_count;
  3994. uint32_t is_compute;
  3995. uint32_t compute_local_size[3];
  3996. uint32_t set_count;
  3997. uint32_t push_constant_size;
  3998. uint32_t push_constants_vk_stage;
  3999. uint32_t stage_count;
  4000. uint32_t shader_name_len;
  4001. };
  4002. Vector<uint8_t> RenderingDeviceVulkan::shader_compile_binary_from_spirv(const Vector<ShaderStageSPIRVData> &p_spirv, const String &p_shader_name) {
  4003. RenderingDeviceVulkanShaderBinaryData binary_data;
  4004. binary_data.vertex_input_mask = 0;
  4005. binary_data.fragment_outputs = 0;
  4006. binary_data.specialization_constant_count = 0;
  4007. binary_data.is_compute = 0;
  4008. binary_data.compute_local_size[0] = 0;
  4009. binary_data.compute_local_size[1] = 0;
  4010. binary_data.compute_local_size[2] = 0;
  4011. binary_data.set_count = 0;
  4012. binary_data.push_constant_size = 0;
  4013. binary_data.push_constants_vk_stage = 0;
  4014. Vector<Vector<RenderingDeviceVulkanShaderBinaryDataBinding>> uniform_info; //set bindings
  4015. Vector<RenderingDeviceVulkanShaderBinarySpecializationConstant> specialization_constants;
  4016. uint32_t stages_processed = 0;
  4017. for (int i = 0; i < p_spirv.size(); i++) {
  4018. if (p_spirv[i].shader_stage == SHADER_STAGE_COMPUTE) {
  4019. binary_data.is_compute = true;
  4020. ERR_FAIL_COND_V_MSG(p_spirv.size() != 1, Vector<uint8_t>(),
  4021. "Compute shaders can only receive one stage, dedicated to compute.");
  4022. }
  4023. ERR_FAIL_COND_V_MSG(stages_processed & (1 << p_spirv[i].shader_stage), Vector<uint8_t>(),
  4024. "Stage " + String(shader_stage_names[p_spirv[i].shader_stage]) + " submitted more than once.");
  4025. {
  4026. SpvReflectShaderModule module;
  4027. const uint8_t *spirv = p_spirv[i].spir_v.ptr();
  4028. SpvReflectResult result = spvReflectCreateShaderModule(p_spirv[i].spir_v.size(), spirv, &module);
  4029. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4030. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed parsing shader.");
  4031. if (binary_data.is_compute) {
  4032. binary_data.compute_local_size[0] = module.entry_points->local_size.x;
  4033. binary_data.compute_local_size[1] = module.entry_points->local_size.y;
  4034. binary_data.compute_local_size[2] = module.entry_points->local_size.z;
  4035. }
  4036. uint32_t binding_count = 0;
  4037. result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, nullptr);
  4038. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4039. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating descriptor bindings.");
  4040. uint32_t stage = p_spirv[i].shader_stage;
  4041. if (binding_count > 0) {
  4042. //Parse bindings
  4043. Vector<SpvReflectDescriptorBinding *> bindings;
  4044. bindings.resize(binding_count);
  4045. result = spvReflectEnumerateDescriptorBindings(&module, &binding_count, bindings.ptrw());
  4046. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4047. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed getting descriptor bindings.");
  4048. for (uint32_t j = 0; j < binding_count; j++) {
  4049. const SpvReflectDescriptorBinding &binding = *bindings[j];
  4050. RenderingDeviceVulkanShaderBinaryDataBinding info;
  4051. bool need_array_dimensions = false;
  4052. bool need_block_size = false;
  4053. bool may_be_writable = false;
  4054. switch (binding.descriptor_type) {
  4055. case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLER: {
  4056. info.type = UNIFORM_TYPE_SAMPLER;
  4057. need_array_dimensions = true;
  4058. } break;
  4059. case SPV_REFLECT_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: {
  4060. info.type = UNIFORM_TYPE_SAMPLER_WITH_TEXTURE;
  4061. need_array_dimensions = true;
  4062. } break;
  4063. case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLED_IMAGE: {
  4064. info.type = UNIFORM_TYPE_TEXTURE;
  4065. need_array_dimensions = true;
  4066. } break;
  4067. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
  4068. info.type = UNIFORM_TYPE_IMAGE;
  4069. need_array_dimensions = true;
  4070. may_be_writable = true;
  4071. } break;
  4072. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: {
  4073. info.type = UNIFORM_TYPE_TEXTURE_BUFFER;
  4074. need_array_dimensions = true;
  4075. } break;
  4076. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: {
  4077. info.type = UNIFORM_TYPE_IMAGE_BUFFER;
  4078. need_array_dimensions = true;
  4079. may_be_writable = true;
  4080. } break;
  4081. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER: {
  4082. info.type = UNIFORM_TYPE_UNIFORM_BUFFER;
  4083. need_block_size = true;
  4084. } break;
  4085. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER: {
  4086. info.type = UNIFORM_TYPE_STORAGE_BUFFER;
  4087. need_block_size = true;
  4088. may_be_writable = true;
  4089. } break;
  4090. case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: {
  4091. ERR_PRINT("Dynamic uniform buffer not supported.");
  4092. continue;
  4093. } break;
  4094. case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
  4095. ERR_PRINT("Dynamic storage buffer not supported.");
  4096. continue;
  4097. } break;
  4098. case SPV_REFLECT_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: {
  4099. info.type = UNIFORM_TYPE_INPUT_ATTACHMENT;
  4100. need_array_dimensions = true;
  4101. } break;
  4102. case SPV_REFLECT_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR: {
  4103. ERR_PRINT("Acceleration structure not supported.");
  4104. continue;
  4105. } break;
  4106. }
  4107. if (need_array_dimensions) {
  4108. if (binding.array.dims_count == 0) {
  4109. info.length = 1;
  4110. } else {
  4111. for (uint32_t k = 0; k < binding.array.dims_count; k++) {
  4112. if (k == 0) {
  4113. info.length = binding.array.dims[0];
  4114. } else {
  4115. info.length *= binding.array.dims[k];
  4116. }
  4117. }
  4118. }
  4119. } else if (need_block_size) {
  4120. info.length = binding.block.size;
  4121. } else {
  4122. info.length = 0;
  4123. }
  4124. if (may_be_writable) {
  4125. info.writable = !(bool)(binding.type_description->decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE);
  4126. } else {
  4127. info.writable = false;
  4128. }
  4129. info.binding = binding.binding;
  4130. uint32_t set = binding.set;
  4131. ERR_FAIL_COND_V_MSG(set >= MAX_UNIFORM_SETS, Vector<uint8_t>(),
  4132. "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) + ").");
  4133. ERR_FAIL_COND_V_MSG(set >= limits.maxBoundDescriptorSets, Vector<uint8_t>(),
  4134. "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) + ").");
  4135. if (set < (uint32_t)uniform_info.size()) {
  4136. //check if this already exists
  4137. bool exists = false;
  4138. for (int k = 0; k < uniform_info[set].size(); k++) {
  4139. if (uniform_info[set][k].binding == (uint32_t)info.binding) {
  4140. //already exists, verify that it's the same type
  4141. ERR_FAIL_COND_V_MSG(uniform_info[set][k].type != info.type, Vector<uint8_t>(),
  4142. "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.");
  4143. //also, verify that it's the same size
  4144. ERR_FAIL_COND_V_MSG(uniform_info[set][k].length != info.length, Vector<uint8_t>(),
  4145. "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.");
  4146. //just append stage mask and return
  4147. uniform_info.write[set].write[k].stages |= 1 << stage;
  4148. exists = true;
  4149. break;
  4150. }
  4151. }
  4152. if (exists) {
  4153. continue; //merged
  4154. }
  4155. }
  4156. info.stages = 1 << stage;
  4157. if (set >= (uint32_t)uniform_info.size()) {
  4158. uniform_info.resize(set + 1);
  4159. }
  4160. uniform_info.write[set].push_back(info);
  4161. }
  4162. }
  4163. {
  4164. //specialization constants
  4165. uint32_t sc_count = 0;
  4166. result = spvReflectEnumerateSpecializationConstants(&module, &sc_count, nullptr);
  4167. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4168. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating specialization constants.");
  4169. if (sc_count) {
  4170. Vector<SpvReflectSpecializationConstant *> spec_constants;
  4171. spec_constants.resize(sc_count);
  4172. result = spvReflectEnumerateSpecializationConstants(&module, &sc_count, spec_constants.ptrw());
  4173. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4174. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining specialization constants.");
  4175. for (uint32_t j = 0; j < sc_count; j++) {
  4176. int32_t existing = -1;
  4177. RenderingDeviceVulkanShaderBinarySpecializationConstant sconst;
  4178. SpvReflectSpecializationConstant *spc = spec_constants[j];
  4179. sconst.constant_id = spc->constant_id;
  4180. sconst.int_value = 0.0; // clear previous value JIC
  4181. switch (spc->constant_type) {
  4182. case SPV_REFLECT_SPECIALIZATION_CONSTANT_BOOL: {
  4183. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_BOOL;
  4184. sconst.bool_value = spc->default_value.int_bool_value != 0;
  4185. } break;
  4186. case SPV_REFLECT_SPECIALIZATION_CONSTANT_INT: {
  4187. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT;
  4188. sconst.int_value = spc->default_value.int_bool_value;
  4189. } break;
  4190. case SPV_REFLECT_SPECIALIZATION_CONSTANT_FLOAT: {
  4191. sconst.type = PIPELINE_SPECIALIZATION_CONSTANT_TYPE_FLOAT;
  4192. sconst.float_value = spc->default_value.float_value;
  4193. } break;
  4194. }
  4195. sconst.stage_flags = 1 << p_spirv[i].shader_stage;
  4196. for (int k = 0; k < specialization_constants.size(); k++) {
  4197. if (specialization_constants[k].constant_id == sconst.constant_id) {
  4198. 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.");
  4199. 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.");
  4200. existing = k;
  4201. break;
  4202. }
  4203. }
  4204. if (existing > 0) {
  4205. specialization_constants.write[existing].stage_flags |= sconst.stage_flags;
  4206. } else {
  4207. specialization_constants.push_back(sconst);
  4208. }
  4209. }
  4210. }
  4211. }
  4212. if (stage == SHADER_STAGE_VERTEX) {
  4213. uint32_t iv_count = 0;
  4214. result = spvReflectEnumerateInputVariables(&module, &iv_count, nullptr);
  4215. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4216. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating input variables.");
  4217. if (iv_count) {
  4218. Vector<SpvReflectInterfaceVariable *> input_vars;
  4219. input_vars.resize(iv_count);
  4220. result = spvReflectEnumerateInputVariables(&module, &iv_count, input_vars.ptrw());
  4221. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4222. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining input variables.");
  4223. for (uint32_t j = 0; j < iv_count; j++) {
  4224. if (input_vars[j] && input_vars[j]->decoration_flags == 0) { //regular input
  4225. binary_data.vertex_input_mask |= (1 << uint32_t(input_vars[j]->location));
  4226. }
  4227. }
  4228. }
  4229. }
  4230. if (stage == SHADER_STAGE_FRAGMENT) {
  4231. uint32_t ov_count = 0;
  4232. result = spvReflectEnumerateOutputVariables(&module, &ov_count, nullptr);
  4233. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4234. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating output variables.");
  4235. if (ov_count) {
  4236. Vector<SpvReflectInterfaceVariable *> output_vars;
  4237. output_vars.resize(ov_count);
  4238. result = spvReflectEnumerateOutputVariables(&module, &ov_count, output_vars.ptrw());
  4239. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4240. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining output variables.");
  4241. for (uint32_t j = 0; j < ov_count; j++) {
  4242. const SpvReflectInterfaceVariable *refvar = output_vars[j];
  4243. if (refvar != nullptr && refvar->built_in != SpvBuiltInFragDepth) {
  4244. binary_data.fragment_outputs |= 1 << refvar->location;
  4245. }
  4246. }
  4247. }
  4248. }
  4249. uint32_t pc_count = 0;
  4250. result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, nullptr);
  4251. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4252. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed enumerating push constants.");
  4253. if (pc_count) {
  4254. ERR_FAIL_COND_V_MSG(pc_count > 1, Vector<uint8_t>(),
  4255. "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.");
  4256. Vector<SpvReflectBlockVariable *> pconstants;
  4257. pconstants.resize(pc_count);
  4258. result = spvReflectEnumeratePushConstantBlocks(&module, &pc_count, pconstants.ptrw());
  4259. ERR_FAIL_COND_V_MSG(result != SPV_REFLECT_RESULT_SUCCESS, Vector<uint8_t>(),
  4260. "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining push constants.");
  4261. #if 0
  4262. if (pconstants[0] == nullptr) {
  4263. Ref<FileAccess> f = FileAccess::open("res://popo.spv", FileAccess::WRITE);
  4264. f->store_buffer((const uint8_t *)&SpirV[0], SpirV.size() * sizeof(uint32_t));
  4265. }
  4266. #endif
  4267. ERR_FAIL_COND_V_MSG(binary_data.push_constant_size && binary_data.push_constant_size != pconstants[0]->size, Vector<uint8_t>(),
  4268. "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.");
  4269. binary_data.push_constant_size = pconstants[0]->size;
  4270. binary_data.push_constants_vk_stage |= shader_stage_masks[stage];
  4271. //print_line("Stage: " + String(shader_stage_names[stage]) + " push constant of size=" + itos(push_constant.push_constant_size));
  4272. }
  4273. // Destroy the reflection data when no longer required.
  4274. spvReflectDestroyShaderModule(&module);
  4275. }
  4276. stages_processed |= (1 << p_spirv[i].shader_stage);
  4277. }
  4278. Vector<Vector<uint8_t>> compressed_stages;
  4279. Vector<uint32_t> smolv_size;
  4280. Vector<uint32_t> zstd_size; //if 0, stdno t used
  4281. uint32_t stages_binary_size = 0;
  4282. bool strip_debug = false;
  4283. for (int i = 0; i < p_spirv.size(); i++) {
  4284. smolv::ByteArray smolv;
  4285. if (!smolv::Encode(p_spirv[i].spir_v.ptr(), p_spirv[i].spir_v.size(), smolv, strip_debug ? smolv::kEncodeFlagStripDebugInfo : 0)) {
  4286. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Error compressing shader stage :" + String(shader_stage_names[p_spirv[i].shader_stage]));
  4287. } else {
  4288. smolv_size.push_back(smolv.size());
  4289. { //zstd
  4290. Vector<uint8_t> zstd;
  4291. zstd.resize(Compression::get_max_compressed_buffer_size(smolv.size(), Compression::MODE_ZSTD));
  4292. int dst_size = Compression::compress(zstd.ptrw(), &smolv[0], smolv.size(), Compression::MODE_ZSTD);
  4293. if (dst_size > 0 && (uint32_t)dst_size < smolv.size()) {
  4294. zstd_size.push_back(dst_size);
  4295. zstd.resize(dst_size);
  4296. compressed_stages.push_back(zstd);
  4297. } else {
  4298. Vector<uint8_t> smv;
  4299. smv.resize(smolv.size());
  4300. memcpy(smv.ptrw(), &smolv[0], smolv.size());
  4301. zstd_size.push_back(0); //not using zstd
  4302. compressed_stages.push_back(smv);
  4303. }
  4304. }
  4305. }
  4306. uint32_t s = compressed_stages[i].size();
  4307. if (s % 4 != 0) {
  4308. s += 4 - (s % 4);
  4309. }
  4310. stages_binary_size += s;
  4311. }
  4312. binary_data.specialization_constant_count = specialization_constants.size();
  4313. binary_data.set_count = uniform_info.size();
  4314. binary_data.stage_count = p_spirv.size();
  4315. CharString shader_name_utf = p_shader_name.utf8();
  4316. binary_data.shader_name_len = shader_name_utf.length();
  4317. uint32_t total_size = sizeof(uint32_t) * 3; //header + version + main datasize;
  4318. total_size += sizeof(RenderingDeviceVulkanShaderBinaryData);
  4319. total_size += binary_data.shader_name_len;
  4320. if ((binary_data.shader_name_len % 4) != 0) { //alignment rules are really strange
  4321. total_size += 4 - (binary_data.shader_name_len % 4);
  4322. }
  4323. for (int i = 0; i < uniform_info.size(); i++) {
  4324. total_size += sizeof(uint32_t);
  4325. total_size += uniform_info[i].size() * sizeof(RenderingDeviceVulkanShaderBinaryDataBinding);
  4326. }
  4327. total_size += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size();
  4328. total_size += compressed_stages.size() * sizeof(uint32_t) * 3; //sizes
  4329. total_size += stages_binary_size;
  4330. Vector<uint8_t> ret;
  4331. ret.resize(total_size);
  4332. {
  4333. uint32_t offset = 0;
  4334. uint8_t *binptr = ret.ptrw();
  4335. binptr[0] = 'G';
  4336. binptr[1] = 'V';
  4337. binptr[2] = 'B';
  4338. binptr[3] = 'D'; //godot vulkan binary data
  4339. offset += 4;
  4340. encode_uint32(SHADER_BINARY_VERSION, binptr + offset);
  4341. offset += sizeof(uint32_t);
  4342. encode_uint32(sizeof(RenderingDeviceVulkanShaderBinaryData), binptr + offset);
  4343. offset += sizeof(uint32_t);
  4344. memcpy(binptr + offset, &binary_data, sizeof(RenderingDeviceVulkanShaderBinaryData));
  4345. offset += sizeof(RenderingDeviceVulkanShaderBinaryData);
  4346. memcpy(binptr + offset, shader_name_utf.ptr(), binary_data.shader_name_len);
  4347. offset += binary_data.shader_name_len;
  4348. if ((binary_data.shader_name_len % 4) != 0) { //alignment rules are really strange
  4349. offset += 4 - (binary_data.shader_name_len % 4);
  4350. }
  4351. for (int i = 0; i < uniform_info.size(); i++) {
  4352. int count = uniform_info[i].size();
  4353. encode_uint32(count, binptr + offset);
  4354. offset += sizeof(uint32_t);
  4355. if (count > 0) {
  4356. memcpy(binptr + offset, uniform_info[i].ptr(), sizeof(RenderingDeviceVulkanShaderBinaryDataBinding) * count);
  4357. offset += sizeof(RenderingDeviceVulkanShaderBinaryDataBinding) * count;
  4358. }
  4359. }
  4360. if (specialization_constants.size()) {
  4361. memcpy(binptr + offset, specialization_constants.ptr(), sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size());
  4362. offset += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) * specialization_constants.size();
  4363. }
  4364. for (int i = 0; i < compressed_stages.size(); i++) {
  4365. encode_uint32(p_spirv[i].shader_stage, binptr + offset);
  4366. offset += sizeof(uint32_t);
  4367. encode_uint32(smolv_size[i], binptr + offset);
  4368. offset += sizeof(uint32_t);
  4369. encode_uint32(zstd_size[i], binptr + offset);
  4370. offset += sizeof(uint32_t);
  4371. memcpy(binptr + offset, compressed_stages[i].ptr(), compressed_stages[i].size());
  4372. uint32_t s = compressed_stages[i].size();
  4373. if (s % 4 != 0) {
  4374. s += 4 - (s % 4);
  4375. }
  4376. offset += s;
  4377. }
  4378. ERR_FAIL_COND_V(offset != (uint32_t)ret.size(), Vector<uint8_t>());
  4379. }
  4380. return ret;
  4381. }
  4382. RID RenderingDeviceVulkan::shader_create_from_bytecode(const Vector<uint8_t> &p_shader_binary) {
  4383. const uint8_t *binptr = p_shader_binary.ptr();
  4384. uint32_t binsize = p_shader_binary.size();
  4385. uint32_t read_offset = 0;
  4386. //consistency check
  4387. ERR_FAIL_COND_V(binsize < sizeof(uint32_t) * 3 + sizeof(RenderingDeviceVulkanShaderBinaryData), RID());
  4388. ERR_FAIL_COND_V(binptr[0] != 'G' || binptr[1] != 'V' || binptr[2] != 'B' || binptr[3] != 'D', RID());
  4389. uint32_t bin_version = decode_uint32(binptr + 4);
  4390. ERR_FAIL_COND_V(bin_version > SHADER_BINARY_VERSION, RID());
  4391. uint32_t bin_data_size = decode_uint32(binptr + 8);
  4392. const RenderingDeviceVulkanShaderBinaryData &binary_data = *(reinterpret_cast<const RenderingDeviceVulkanShaderBinaryData *>(binptr + 12));
  4393. Shader::PushConstant push_constant;
  4394. push_constant.push_constant_size = binary_data.push_constant_size;
  4395. push_constant.push_constants_vk_stage = binary_data.push_constants_vk_stage;
  4396. uint32_t vertex_input_mask = binary_data.vertex_input_mask;
  4397. uint32_t fragment_outputs = binary_data.fragment_outputs;
  4398. bool is_compute = binary_data.is_compute;
  4399. const uint32_t compute_local_size[3] = { binary_data.compute_local_size[0], binary_data.compute_local_size[1], binary_data.compute_local_size[2] };
  4400. read_offset += sizeof(uint32_t) * 3 + bin_data_size;
  4401. String name;
  4402. if (binary_data.shader_name_len) {
  4403. name.parse_utf8((const char *)(binptr + read_offset), binary_data.shader_name_len);
  4404. read_offset += binary_data.shader_name_len;
  4405. if ((binary_data.shader_name_len % 4) != 0) { //alignment rules are really strange
  4406. read_offset += 4 - (binary_data.shader_name_len % 4);
  4407. }
  4408. }
  4409. Vector<Vector<VkDescriptorSetLayoutBinding>> set_bindings;
  4410. Vector<Vector<UniformInfo>> uniform_info;
  4411. set_bindings.resize(binary_data.set_count);
  4412. uniform_info.resize(binary_data.set_count);
  4413. for (uint32_t i = 0; i < binary_data.set_count; i++) {
  4414. ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) >= binsize, RID());
  4415. uint32_t set_count = decode_uint32(binptr + read_offset);
  4416. read_offset += sizeof(uint32_t);
  4417. const RenderingDeviceVulkanShaderBinaryDataBinding *set_ptr = reinterpret_cast<const RenderingDeviceVulkanShaderBinaryDataBinding *>(binptr + read_offset);
  4418. uint32_t set_size = set_count * sizeof(RenderingDeviceVulkanShaderBinaryDataBinding);
  4419. ERR_FAIL_COND_V(read_offset + set_size >= binsize, RID());
  4420. for (uint32_t j = 0; j < set_count; j++) {
  4421. UniformInfo info;
  4422. info.type = UniformType(set_ptr[j].type);
  4423. info.writable = set_ptr[j].writable;
  4424. info.length = set_ptr[j].length;
  4425. info.binding = set_ptr[j].binding;
  4426. info.stages = set_ptr[j].stages;
  4427. VkDescriptorSetLayoutBinding layout_binding;
  4428. layout_binding.pImmutableSamplers = nullptr;
  4429. layout_binding.binding = set_ptr[j].binding;
  4430. layout_binding.descriptorCount = 1;
  4431. layout_binding.stageFlags = 0;
  4432. for (uint32_t k = 0; k < SHADER_STAGE_MAX; k++) {
  4433. if (set_ptr[j].stages & (1 << k)) {
  4434. layout_binding.stageFlags |= shader_stage_masks[k];
  4435. }
  4436. }
  4437. switch (info.type) {
  4438. case UNIFORM_TYPE_SAMPLER: {
  4439. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  4440. layout_binding.descriptorCount = set_ptr[j].length;
  4441. } break;
  4442. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {
  4443. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4444. layout_binding.descriptorCount = set_ptr[j].length;
  4445. } break;
  4446. case UNIFORM_TYPE_TEXTURE: {
  4447. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  4448. layout_binding.descriptorCount = set_ptr[j].length;
  4449. } break;
  4450. case UNIFORM_TYPE_IMAGE: {
  4451. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  4452. layout_binding.descriptorCount = set_ptr[j].length;
  4453. } break;
  4454. case UNIFORM_TYPE_TEXTURE_BUFFER: {
  4455. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  4456. layout_binding.descriptorCount = set_ptr[j].length;
  4457. } break;
  4458. case UNIFORM_TYPE_IMAGE_BUFFER: {
  4459. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  4460. } break;
  4461. case UNIFORM_TYPE_UNIFORM_BUFFER: {
  4462. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  4463. } break;
  4464. case UNIFORM_TYPE_STORAGE_BUFFER: {
  4465. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  4466. } break;
  4467. case UNIFORM_TYPE_INPUT_ATTACHMENT: {
  4468. layout_binding.descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
  4469. } break;
  4470. default: {
  4471. ERR_FAIL_V(RID());
  4472. }
  4473. }
  4474. set_bindings.write[i].push_back(layout_binding);
  4475. uniform_info.write[i].push_back(info);
  4476. }
  4477. read_offset += set_size;
  4478. }
  4479. ERR_FAIL_COND_V(read_offset + binary_data.specialization_constant_count * sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant) >= binsize, RID());
  4480. Vector<Shader::SpecializationConstant> specialization_constants;
  4481. for (uint32_t i = 0; i < binary_data.specialization_constant_count; i++) {
  4482. const RenderingDeviceVulkanShaderBinarySpecializationConstant &src_sc = *(reinterpret_cast<const RenderingDeviceVulkanShaderBinarySpecializationConstant *>(binptr + read_offset));
  4483. Shader::SpecializationConstant sc;
  4484. sc.constant.int_value = src_sc.int_value;
  4485. sc.constant.type = PipelineSpecializationConstantType(src_sc.type);
  4486. sc.constant.constant_id = src_sc.constant_id;
  4487. sc.stage_flags = src_sc.stage_flags;
  4488. specialization_constants.push_back(sc);
  4489. read_offset += sizeof(RenderingDeviceVulkanShaderBinarySpecializationConstant);
  4490. }
  4491. Vector<Vector<uint8_t>> stage_spirv_data;
  4492. Vector<ShaderStage> stage_type;
  4493. for (uint32_t i = 0; i < binary_data.stage_count; i++) {
  4494. ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) * 3 >= binsize, RID());
  4495. uint32_t stage = decode_uint32(binptr + read_offset);
  4496. read_offset += sizeof(uint32_t);
  4497. uint32_t smolv_size = decode_uint32(binptr + read_offset);
  4498. read_offset += sizeof(uint32_t);
  4499. uint32_t zstd_size = decode_uint32(binptr + read_offset);
  4500. read_offset += sizeof(uint32_t);
  4501. uint32_t buf_size = (zstd_size > 0) ? zstd_size : smolv_size;
  4502. Vector<uint8_t> smolv;
  4503. const uint8_t *src_smolv = nullptr;
  4504. if (zstd_size > 0) {
  4505. //decompress to smolv
  4506. smolv.resize(smolv_size);
  4507. int dec_smolv_size = Compression::decompress(smolv.ptrw(), smolv.size(), binptr + read_offset, zstd_size, Compression::MODE_ZSTD);
  4508. ERR_FAIL_COND_V(dec_smolv_size != (int32_t)smolv_size, RID());
  4509. src_smolv = smolv.ptr();
  4510. } else {
  4511. src_smolv = binptr + read_offset;
  4512. }
  4513. Vector<uint8_t> spirv;
  4514. uint32_t spirv_size = smolv::GetDecodedBufferSize(src_smolv, smolv_size);
  4515. spirv.resize(spirv_size);
  4516. if (!smolv::Decode(src_smolv, smolv_size, spirv.ptrw(), spirv_size)) {
  4517. ERR_FAIL_V_MSG(RID(), "Malformed smolv input uncompressing shader stage:" + String(shader_stage_names[stage]));
  4518. }
  4519. stage_spirv_data.push_back(spirv);
  4520. stage_type.push_back(ShaderStage(stage));
  4521. if (buf_size % 4 != 0) {
  4522. buf_size += 4 - (buf_size % 4);
  4523. }
  4524. ERR_FAIL_COND_V(read_offset + buf_size > binsize, RID());
  4525. read_offset += buf_size;
  4526. }
  4527. ERR_FAIL_COND_V(read_offset != binsize, RID());
  4528. //all good, let's create modules
  4529. _THREAD_SAFE_METHOD_
  4530. Shader shader;
  4531. shader.vertex_input_mask = vertex_input_mask;
  4532. shader.fragment_output_mask = fragment_outputs;
  4533. shader.push_constant = push_constant;
  4534. shader.is_compute = is_compute;
  4535. shader.compute_local_size[0] = compute_local_size[0];
  4536. shader.compute_local_size[1] = compute_local_size[1];
  4537. shader.compute_local_size[2] = compute_local_size[2];
  4538. shader.specialization_constants = specialization_constants;
  4539. shader.name = name;
  4540. String error_text;
  4541. bool success = true;
  4542. for (int i = 0; i < stage_spirv_data.size(); i++) {
  4543. VkShaderModuleCreateInfo shader_module_create_info;
  4544. shader_module_create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  4545. shader_module_create_info.pNext = nullptr;
  4546. shader_module_create_info.flags = 0;
  4547. shader_module_create_info.codeSize = stage_spirv_data[i].size();
  4548. const uint8_t *r = stage_spirv_data[i].ptr();
  4549. shader_module_create_info.pCode = (const uint32_t *)r;
  4550. VkShaderModule module;
  4551. VkResult res = vkCreateShaderModule(device, &shader_module_create_info, nullptr, &module);
  4552. if (res) {
  4553. success = false;
  4554. error_text = "Error (" + itos(res) + ") creating shader module for stage: " + String(shader_stage_names[stage_type[i]]);
  4555. break;
  4556. }
  4557. const VkShaderStageFlagBits shader_stage_bits[SHADER_STAGE_MAX] = {
  4558. VK_SHADER_STAGE_VERTEX_BIT,
  4559. VK_SHADER_STAGE_FRAGMENT_BIT,
  4560. VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT,
  4561. VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
  4562. VK_SHADER_STAGE_COMPUTE_BIT,
  4563. };
  4564. VkPipelineShaderStageCreateInfo shader_stage;
  4565. shader_stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  4566. shader_stage.pNext = nullptr;
  4567. shader_stage.flags = 0;
  4568. shader_stage.stage = shader_stage_bits[stage_type[i]];
  4569. shader_stage.module = module;
  4570. shader_stage.pName = "main";
  4571. shader_stage.pSpecializationInfo = nullptr;
  4572. shader.pipeline_stages.push_back(shader_stage);
  4573. }
  4574. //proceed to create descriptor sets
  4575. if (success) {
  4576. for (int i = 0; i < set_bindings.size(); i++) {
  4577. //empty ones are fine if they were not used according to spec (binding count will be 0)
  4578. VkDescriptorSetLayoutCreateInfo layout_create_info;
  4579. layout_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  4580. layout_create_info.pNext = nullptr;
  4581. layout_create_info.flags = 0;
  4582. layout_create_info.bindingCount = set_bindings[i].size();
  4583. layout_create_info.pBindings = set_bindings[i].ptr();
  4584. VkDescriptorSetLayout layout;
  4585. VkResult res = vkCreateDescriptorSetLayout(device, &layout_create_info, nullptr, &layout);
  4586. if (res) {
  4587. error_text = "Error (" + itos(res) + ") creating descriptor set layout for set " + itos(i);
  4588. success = false;
  4589. break;
  4590. }
  4591. Shader::Set set;
  4592. set.descriptor_set_layout = layout;
  4593. set.uniform_info = uniform_info[i];
  4594. //sort and hash
  4595. set.uniform_info.sort();
  4596. uint32_t format = 0; //no format, default
  4597. if (set.uniform_info.size()) {
  4598. //has data, needs an actual format;
  4599. UniformSetFormat usformat;
  4600. usformat.uniform_info = set.uniform_info;
  4601. RBMap<UniformSetFormat, uint32_t>::Element *E = uniform_set_format_cache.find(usformat);
  4602. if (E) {
  4603. format = E->get();
  4604. } else {
  4605. format = uniform_set_format_cache.size() + 1;
  4606. uniform_set_format_cache.insert(usformat, format);
  4607. }
  4608. }
  4609. shader.sets.push_back(set);
  4610. shader.set_formats.push_back(format);
  4611. }
  4612. }
  4613. if (success) {
  4614. //create pipeline layout
  4615. VkPipelineLayoutCreateInfo pipeline_layout_create_info;
  4616. pipeline_layout_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  4617. pipeline_layout_create_info.pNext = nullptr;
  4618. pipeline_layout_create_info.flags = 0;
  4619. pipeline_layout_create_info.setLayoutCount = shader.sets.size();
  4620. Vector<VkDescriptorSetLayout> layouts;
  4621. layouts.resize(shader.sets.size());
  4622. for (int i = 0; i < layouts.size(); i++) {
  4623. layouts.write[i] = shader.sets[i].descriptor_set_layout;
  4624. }
  4625. pipeline_layout_create_info.pSetLayouts = layouts.ptr();
  4626. // Needs to be declared in this outer scope, otherwise it may not outlive its assignment
  4627. // to pipeline_layout_create_info.
  4628. VkPushConstantRange push_constant_range;
  4629. if (push_constant.push_constant_size) {
  4630. push_constant_range.stageFlags = push_constant.push_constants_vk_stage;
  4631. push_constant_range.offset = 0;
  4632. push_constant_range.size = push_constant.push_constant_size;
  4633. pipeline_layout_create_info.pushConstantRangeCount = 1;
  4634. pipeline_layout_create_info.pPushConstantRanges = &push_constant_range;
  4635. } else {
  4636. pipeline_layout_create_info.pushConstantRangeCount = 0;
  4637. pipeline_layout_create_info.pPushConstantRanges = nullptr;
  4638. }
  4639. VkResult err = vkCreatePipelineLayout(device, &pipeline_layout_create_info, nullptr, &shader.pipeline_layout);
  4640. if (err) {
  4641. error_text = "Error (" + itos(err) + ") creating pipeline layout.";
  4642. success = false;
  4643. }
  4644. }
  4645. if (!success) {
  4646. //clean up if failed
  4647. for (int i = 0; i < shader.pipeline_stages.size(); i++) {
  4648. vkDestroyShaderModule(device, shader.pipeline_stages[i].module, nullptr);
  4649. }
  4650. for (int i = 0; i < shader.sets.size(); i++) {
  4651. vkDestroyDescriptorSetLayout(device, shader.sets[i].descriptor_set_layout, nullptr);
  4652. }
  4653. ERR_FAIL_V_MSG(RID(), error_text);
  4654. }
  4655. RID id = shader_owner.make_rid(shader);
  4656. #ifdef DEV_ENABLED
  4657. set_resource_name(id, "RID:" + itos(id.get_id()));
  4658. #endif
  4659. return id;
  4660. }
  4661. uint32_t RenderingDeviceVulkan::shader_get_vertex_input_attribute_mask(RID p_shader) {
  4662. _THREAD_SAFE_METHOD_
  4663. const Shader *shader = shader_owner.get_or_null(p_shader);
  4664. ERR_FAIL_COND_V(!shader, 0);
  4665. return shader->vertex_input_mask;
  4666. }
  4667. /******************/
  4668. /**** UNIFORMS ****/
  4669. /******************/
  4670. RID RenderingDeviceVulkan::uniform_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data) {
  4671. _THREAD_SAFE_METHOD_
  4672. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  4673. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  4674. "Creating buffers with data is forbidden during creation of a draw list");
  4675. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  4676. "Creating buffers with data is forbidden during creation of a draw list");
  4677. Buffer buffer;
  4678. Error err = _buffer_allocate(&buffer, p_size_bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0);
  4679. ERR_FAIL_COND_V(err != OK, RID());
  4680. if (p_data.size()) {
  4681. uint64_t data_size = p_data.size();
  4682. const uint8_t *r = p_data.ptr();
  4683. _buffer_update(&buffer, 0, r, data_size);
  4684. _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);
  4685. }
  4686. RID id = uniform_buffer_owner.make_rid(buffer);
  4687. #ifdef DEV_ENABLED
  4688. set_resource_name(id, "RID:" + itos(id.get_id()));
  4689. #endif
  4690. return id;
  4691. }
  4692. RID RenderingDeviceVulkan::storage_buffer_create(uint32_t p_size_bytes, const Vector<uint8_t> &p_data, uint32_t p_usage) {
  4693. _THREAD_SAFE_METHOD_
  4694. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  4695. "Creating buffers with data is forbidden during creation of a draw list");
  4696. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  4697. "Creating buffers with data is forbidden during creation of a draw list");
  4698. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != p_size_bytes, RID());
  4699. Buffer buffer;
  4700. uint32_t flags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
  4701. if (p_usage & STORAGE_BUFFER_USAGE_DISPATCH_INDIRECT) {
  4702. flags |= VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
  4703. }
  4704. Error err = _buffer_allocate(&buffer, p_size_bytes, flags, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, 0);
  4705. ERR_FAIL_COND_V(err != OK, RID());
  4706. if (p_data.size()) {
  4707. uint64_t data_size = p_data.size();
  4708. const uint8_t *r = p_data.ptr();
  4709. _buffer_update(&buffer, 0, r, data_size);
  4710. _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);
  4711. }
  4712. return storage_buffer_owner.make_rid(buffer);
  4713. }
  4714. RID RenderingDeviceVulkan::texture_buffer_create(uint32_t p_size_elements, DataFormat p_format, const Vector<uint8_t> &p_data) {
  4715. _THREAD_SAFE_METHOD_
  4716. ERR_FAIL_COND_V_MSG(draw_list != nullptr && p_data.size(), RID(),
  4717. "Creating buffers with data is forbidden during creation of a draw list");
  4718. ERR_FAIL_COND_V_MSG(compute_list != nullptr && p_data.size(), RID(),
  4719. "Creating buffers with data is forbidden during creation of a draw list");
  4720. uint32_t element_size = get_format_vertex_size(p_format);
  4721. ERR_FAIL_COND_V_MSG(element_size == 0, RID(), "Format requested is not supported for texture buffers");
  4722. uint64_t size_bytes = uint64_t(element_size) * p_size_elements;
  4723. ERR_FAIL_COND_V(p_data.size() && (uint32_t)p_data.size() != size_bytes, RID());
  4724. TextureBuffer texture_buffer;
  4725. 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_AUTO_PREFER_DEVICE, 0);
  4726. ERR_FAIL_COND_V(err != OK, RID());
  4727. if (p_data.size()) {
  4728. uint64_t data_size = p_data.size();
  4729. const uint8_t *r = p_data.ptr();
  4730. _buffer_update(&texture_buffer.buffer, 0, r, data_size);
  4731. _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);
  4732. }
  4733. VkBufferViewCreateInfo view_create_info;
  4734. view_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;
  4735. view_create_info.pNext = nullptr;
  4736. view_create_info.flags = 0;
  4737. view_create_info.buffer = texture_buffer.buffer.buffer;
  4738. view_create_info.format = vulkan_formats[p_format];
  4739. view_create_info.offset = 0;
  4740. view_create_info.range = size_bytes;
  4741. texture_buffer.view = VK_NULL_HANDLE;
  4742. VkResult res = vkCreateBufferView(device, &view_create_info, nullptr, &texture_buffer.view);
  4743. if (res) {
  4744. _buffer_free(&texture_buffer.buffer);
  4745. ERR_FAIL_V_MSG(RID(), "Unable to create buffer view, error " + itos(res) + ".");
  4746. }
  4747. //allocate the view
  4748. RID id = texture_buffer_owner.make_rid(texture_buffer);
  4749. #ifdef DEV_ENABLED
  4750. set_resource_name(id, "RID:" + itos(id.get_id()));
  4751. #endif
  4752. return id;
  4753. }
  4754. RenderingDeviceVulkan::DescriptorPool *RenderingDeviceVulkan::_descriptor_pool_allocate(const DescriptorPoolKey &p_key) {
  4755. if (!descriptor_pools.has(p_key)) {
  4756. descriptor_pools[p_key] = HashSet<DescriptorPool *>();
  4757. }
  4758. DescriptorPool *pool = nullptr;
  4759. for (DescriptorPool *E : descriptor_pools[p_key]) {
  4760. if (E->usage < max_descriptors_per_pool) {
  4761. pool = E;
  4762. break;
  4763. }
  4764. }
  4765. if (!pool) {
  4766. //create a new one
  4767. pool = memnew(DescriptorPool);
  4768. pool->usage = 0;
  4769. VkDescriptorPoolCreateInfo descriptor_pool_create_info;
  4770. descriptor_pool_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
  4771. descriptor_pool_create_info.pNext = nullptr;
  4772. descriptor_pool_create_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; // can't think how somebody may NOT need this flag..
  4773. descriptor_pool_create_info.maxSets = max_descriptors_per_pool;
  4774. Vector<VkDescriptorPoolSize> sizes;
  4775. //here comes more vulkan API strangeness
  4776. if (p_key.uniform_type[UNIFORM_TYPE_SAMPLER]) {
  4777. VkDescriptorPoolSize s;
  4778. s.type = VK_DESCRIPTOR_TYPE_SAMPLER;
  4779. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_SAMPLER] * max_descriptors_per_pool;
  4780. sizes.push_back(s);
  4781. }
  4782. if (p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE]) {
  4783. VkDescriptorPoolSize s;
  4784. s.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4785. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE] * max_descriptors_per_pool;
  4786. sizes.push_back(s);
  4787. }
  4788. if (p_key.uniform_type[UNIFORM_TYPE_TEXTURE]) {
  4789. VkDescriptorPoolSize s;
  4790. s.type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  4791. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_TEXTURE] * max_descriptors_per_pool;
  4792. sizes.push_back(s);
  4793. }
  4794. if (p_key.uniform_type[UNIFORM_TYPE_IMAGE]) {
  4795. VkDescriptorPoolSize s;
  4796. s.type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  4797. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_IMAGE] * max_descriptors_per_pool;
  4798. sizes.push_back(s);
  4799. }
  4800. if (p_key.uniform_type[UNIFORM_TYPE_TEXTURE_BUFFER] || p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER]) {
  4801. VkDescriptorPoolSize s;
  4802. s.type = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  4803. s.descriptorCount = (p_key.uniform_type[UNIFORM_TYPE_TEXTURE_BUFFER] + p_key.uniform_type[UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER]) * max_descriptors_per_pool;
  4804. sizes.push_back(s);
  4805. }
  4806. if (p_key.uniform_type[UNIFORM_TYPE_IMAGE_BUFFER]) {
  4807. VkDescriptorPoolSize s;
  4808. s.type = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER;
  4809. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_IMAGE_BUFFER] * max_descriptors_per_pool;
  4810. sizes.push_back(s);
  4811. }
  4812. if (p_key.uniform_type[UNIFORM_TYPE_UNIFORM_BUFFER]) {
  4813. VkDescriptorPoolSize s;
  4814. s.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  4815. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_UNIFORM_BUFFER] * max_descriptors_per_pool;
  4816. sizes.push_back(s);
  4817. }
  4818. if (p_key.uniform_type[UNIFORM_TYPE_STORAGE_BUFFER]) {
  4819. VkDescriptorPoolSize s;
  4820. s.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  4821. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_STORAGE_BUFFER] * max_descriptors_per_pool;
  4822. sizes.push_back(s);
  4823. }
  4824. if (p_key.uniform_type[UNIFORM_TYPE_INPUT_ATTACHMENT]) {
  4825. VkDescriptorPoolSize s;
  4826. s.type = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
  4827. s.descriptorCount = p_key.uniform_type[UNIFORM_TYPE_INPUT_ATTACHMENT] * max_descriptors_per_pool;
  4828. sizes.push_back(s);
  4829. }
  4830. descriptor_pool_create_info.poolSizeCount = sizes.size();
  4831. descriptor_pool_create_info.pPoolSizes = sizes.ptr();
  4832. VkResult res = vkCreateDescriptorPool(device, &descriptor_pool_create_info, nullptr, &pool->pool);
  4833. if (res) {
  4834. memdelete(pool);
  4835. ERR_FAIL_COND_V_MSG(res, nullptr, "vkCreateDescriptorPool failed with error " + itos(res) + ".");
  4836. }
  4837. descriptor_pools[p_key].insert(pool);
  4838. }
  4839. pool->usage++;
  4840. return pool;
  4841. }
  4842. void RenderingDeviceVulkan::_descriptor_pool_free(const DescriptorPoolKey &p_key, DescriptorPool *p_pool) {
  4843. #ifdef DEBUG_ENABLED
  4844. ERR_FAIL_COND(!descriptor_pools[p_key].has(p_pool));
  4845. #endif
  4846. ERR_FAIL_COND(p_pool->usage == 0);
  4847. p_pool->usage--;
  4848. if (p_pool->usage == 0) {
  4849. vkDestroyDescriptorPool(device, p_pool->pool, nullptr);
  4850. descriptor_pools[p_key].erase(p_pool);
  4851. memdelete(p_pool);
  4852. if (descriptor_pools[p_key].is_empty()) {
  4853. descriptor_pools.erase(p_key);
  4854. }
  4855. }
  4856. }
  4857. RID RenderingDeviceVulkan::uniform_set_create(const Vector<Uniform> &p_uniforms, RID p_shader, uint32_t p_shader_set) {
  4858. _THREAD_SAFE_METHOD_
  4859. ERR_FAIL_COND_V(p_uniforms.size() == 0, RID());
  4860. Shader *shader = shader_owner.get_or_null(p_shader);
  4861. ERR_FAIL_COND_V(!shader, RID());
  4862. ERR_FAIL_COND_V_MSG(p_shader_set >= (uint32_t)shader->sets.size() || shader->sets[p_shader_set].uniform_info.size() == 0, RID(),
  4863. "Desired set (" + itos(p_shader_set) + ") not used by shader.");
  4864. //see that all sets in shader are satisfied
  4865. const Shader::Set &set = shader->sets[p_shader_set];
  4866. uint32_t uniform_count = p_uniforms.size();
  4867. const Uniform *uniforms = p_uniforms.ptr();
  4868. uint32_t set_uniform_count = set.uniform_info.size();
  4869. const UniformInfo *set_uniforms = set.uniform_info.ptr();
  4870. Vector<VkWriteDescriptorSet> writes;
  4871. DescriptorPoolKey pool_key;
  4872. //to keep them alive until update call
  4873. List<Vector<VkDescriptorBufferInfo>> buffer_infos;
  4874. List<Vector<VkBufferView>> buffer_views;
  4875. List<Vector<VkDescriptorImageInfo>> image_infos;
  4876. //used for verification to make sure a uniform set does not use a framebuffer bound texture
  4877. LocalVector<UniformSet::AttachableTexture> attachable_textures;
  4878. Vector<Texture *> mutable_sampled_textures;
  4879. Vector<Texture *> mutable_storage_textures;
  4880. for (uint32_t i = 0; i < set_uniform_count; i++) {
  4881. const UniformInfo &set_uniform = set_uniforms[i];
  4882. int uniform_idx = -1;
  4883. for (int j = 0; j < (int)uniform_count; j++) {
  4884. if (uniforms[j].binding == set_uniform.binding) {
  4885. uniform_idx = j;
  4886. }
  4887. }
  4888. ERR_FAIL_COND_V_MSG(uniform_idx == -1, RID(),
  4889. "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.");
  4890. const Uniform &uniform = uniforms[uniform_idx];
  4891. ERR_FAIL_COND_V_MSG(uniform.uniform_type != set_uniform.type, RID(),
  4892. "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] + "'.");
  4893. VkWriteDescriptorSet write; //common header
  4894. write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4895. write.pNext = nullptr;
  4896. write.dstSet = VK_NULL_HANDLE; //will assign afterwards when everything is valid
  4897. write.dstBinding = set_uniform.binding;
  4898. write.dstArrayElement = 0;
  4899. write.descriptorCount = 0;
  4900. write.descriptorType = VK_DESCRIPTOR_TYPE_MAX_ENUM; //Invalid value.
  4901. write.pImageInfo = nullptr;
  4902. write.pBufferInfo = nullptr;
  4903. write.pTexelBufferView = nullptr;
  4904. uint32_t type_size = 1;
  4905. switch (uniform.uniform_type) {
  4906. case UNIFORM_TYPE_SAMPLER: {
  4907. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  4908. if (set_uniform.length > 1) {
  4909. 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.get_id_count()) + ").");
  4910. } else {
  4911. ERR_FAIL_V_MSG(RID(), "Sampler (binding: " + itos(uniform.binding) + ") should provide one ID referencing a sampler (IDs provided: " + itos(uniform.get_id_count()) + ").");
  4912. }
  4913. }
  4914. Vector<VkDescriptorImageInfo> image_info;
  4915. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  4916. VkSampler *sampler = sampler_owner.get_or_null(uniform.get_id(j));
  4917. ERR_FAIL_COND_V_MSG(!sampler, RID(), "Sampler (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid sampler.");
  4918. VkDescriptorImageInfo img_info;
  4919. img_info.sampler = *sampler;
  4920. img_info.imageView = VK_NULL_HANDLE;
  4921. img_info.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  4922. image_info.push_back(img_info);
  4923. }
  4924. write.dstArrayElement = 0;
  4925. write.descriptorCount = uniform.get_id_count();
  4926. write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
  4927. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  4928. write.pBufferInfo = nullptr;
  4929. write.pTexelBufferView = nullptr;
  4930. type_size = uniform.get_id_count();
  4931. } break;
  4932. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE: {
  4933. if (uniform.get_id_count() != (uint32_t)set_uniform.length * 2) {
  4934. if (set_uniform.length > 1) {
  4935. 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.get_id_count()) + ").");
  4936. } else {
  4937. 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.get_id_count()) + ").");
  4938. }
  4939. }
  4940. Vector<VkDescriptorImageInfo> image_info;
  4941. for (uint32_t j = 0; j < uniform.get_id_count(); j += 2) {
  4942. VkSampler *sampler = sampler_owner.get_or_null(uniform.get_id(j + 0));
  4943. ERR_FAIL_COND_V_MSG(!sampler, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler.");
  4944. Texture *texture = texture_owner.get_or_null(uniform.get_id(j + 1));
  4945. ERR_FAIL_COND_V_MSG(!texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  4946. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  4947. "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  4948. VkDescriptorImageInfo img_info;
  4949. img_info.sampler = *sampler;
  4950. img_info.imageView = texture->view;
  4951. if (texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT)) {
  4952. UniformSet::AttachableTexture attachable_texture;
  4953. attachable_texture.bind = set_uniform.binding;
  4954. attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.get_id(j + 1);
  4955. attachable_textures.push_back(attachable_texture);
  4956. }
  4957. if (texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  4958. //can also be used as storage, add to mutable sampled
  4959. mutable_sampled_textures.push_back(texture);
  4960. }
  4961. if (texture->owner.is_valid()) {
  4962. texture = texture_owner.get_or_null(texture->owner);
  4963. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  4964. }
  4965. img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  4966. image_info.push_back(img_info);
  4967. }
  4968. write.dstArrayElement = 0;
  4969. write.descriptorCount = uniform.get_id_count() / 2;
  4970. write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4971. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  4972. write.pBufferInfo = nullptr;
  4973. write.pTexelBufferView = nullptr;
  4974. type_size = uniform.get_id_count() / 2;
  4975. } break;
  4976. case UNIFORM_TYPE_TEXTURE: {
  4977. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  4978. if (set_uniform.length > 1) {
  4979. 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.get_id_count()) + ").");
  4980. } else {
  4981. ERR_FAIL_V_MSG(RID(), "Texture (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");
  4982. }
  4983. }
  4984. Vector<VkDescriptorImageInfo> image_info;
  4985. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  4986. Texture *texture = texture_owner.get_or_null(uniform.get_id(j));
  4987. ERR_FAIL_COND_V_MSG(!texture, RID(), "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  4988. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  4989. "Texture (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  4990. VkDescriptorImageInfo img_info;
  4991. img_info.sampler = VK_NULL_HANDLE;
  4992. img_info.imageView = texture->view;
  4993. if (texture->usage_flags & (TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | TEXTURE_USAGE_INPUT_ATTACHMENT_BIT)) {
  4994. UniformSet::AttachableTexture attachable_texture;
  4995. attachable_texture.bind = set_uniform.binding;
  4996. attachable_texture.texture = texture->owner.is_valid() ? texture->owner : uniform.get_id(j);
  4997. attachable_textures.push_back(attachable_texture);
  4998. }
  4999. if (texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT) {
  5000. //can also be used as storage, add to mutable sampled
  5001. mutable_sampled_textures.push_back(texture);
  5002. }
  5003. if (texture->owner.is_valid()) {
  5004. texture = texture_owner.get_or_null(texture->owner);
  5005. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  5006. }
  5007. img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  5008. image_info.push_back(img_info);
  5009. }
  5010. write.dstArrayElement = 0;
  5011. write.descriptorCount = uniform.get_id_count();
  5012. write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
  5013. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  5014. write.pBufferInfo = nullptr;
  5015. write.pTexelBufferView = nullptr;
  5016. type_size = uniform.get_id_count();
  5017. } break;
  5018. case UNIFORM_TYPE_IMAGE: {
  5019. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  5020. if (set_uniform.length > 1) {
  5021. 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.get_id_count()) + ").");
  5022. } else {
  5023. ERR_FAIL_V_MSG(RID(), "Image (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5024. }
  5025. }
  5026. Vector<VkDescriptorImageInfo> image_info;
  5027. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  5028. Texture *texture = texture_owner.get_or_null(uniform.get_id(j));
  5029. ERR_FAIL_COND_V_MSG(!texture, RID(),
  5030. "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  5031. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_STORAGE_BIT), RID(),
  5032. "Image (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_STORAGE_BIT usage flag set in order to be used as uniform.");
  5033. VkDescriptorImageInfo img_info;
  5034. img_info.sampler = VK_NULL_HANDLE;
  5035. img_info.imageView = texture->view;
  5036. if (texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT) {
  5037. //can also be used as storage, add to mutable sampled
  5038. mutable_storage_textures.push_back(texture);
  5039. }
  5040. if (texture->owner.is_valid()) {
  5041. texture = texture_owner.get_or_null(texture->owner);
  5042. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  5043. }
  5044. img_info.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
  5045. image_info.push_back(img_info);
  5046. }
  5047. write.dstArrayElement = 0;
  5048. write.descriptorCount = uniform.get_id_count();
  5049. write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  5050. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  5051. write.pBufferInfo = nullptr;
  5052. write.pTexelBufferView = nullptr;
  5053. type_size = uniform.get_id_count();
  5054. } break;
  5055. case UNIFORM_TYPE_TEXTURE_BUFFER: {
  5056. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  5057. if (set_uniform.length > 1) {
  5058. 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.get_id_count()) + ").");
  5059. } else {
  5060. ERR_FAIL_V_MSG(RID(), "Buffer (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture buffer (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5061. }
  5062. }
  5063. Vector<VkDescriptorBufferInfo> buffer_info;
  5064. Vector<VkBufferView> buffer_view;
  5065. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  5066. TextureBuffer *buffer = texture_buffer_owner.get_or_null(uniform.get_id(j));
  5067. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Texture Buffer (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture buffer.");
  5068. buffer_info.push_back(buffer->buffer.buffer_info);
  5069. buffer_view.push_back(buffer->view);
  5070. }
  5071. write.dstArrayElement = 0;
  5072. write.descriptorCount = uniform.get_id_count();
  5073. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  5074. write.pImageInfo = nullptr;
  5075. write.pBufferInfo = buffer_infos.push_back(buffer_info)->get().ptr();
  5076. write.pTexelBufferView = buffer_views.push_back(buffer_view)->get().ptr();
  5077. type_size = uniform.get_id_count();
  5078. } break;
  5079. case UNIFORM_TYPE_SAMPLER_WITH_TEXTURE_BUFFER: {
  5080. if (uniform.get_id_count() != (uint32_t)set_uniform.length * 2) {
  5081. if (set_uniform.length > 1) {
  5082. 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.get_id_count()) + ").");
  5083. } else {
  5084. 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.get_id_count()) + ").");
  5085. }
  5086. }
  5087. Vector<VkDescriptorImageInfo> image_info;
  5088. Vector<VkDescriptorBufferInfo> buffer_info;
  5089. Vector<VkBufferView> buffer_view;
  5090. for (uint32_t j = 0; j < uniform.get_id_count(); j += 2) {
  5091. VkSampler *sampler = sampler_owner.get_or_null(uniform.get_id(j + 0));
  5092. ERR_FAIL_COND_V_MSG(!sampler, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid sampler.");
  5093. TextureBuffer *buffer = texture_buffer_owner.get_or_null(uniform.get_id(j + 1));
  5094. VkDescriptorImageInfo img_info;
  5095. img_info.sampler = *sampler;
  5096. img_info.imageView = VK_NULL_HANDLE;
  5097. img_info.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  5098. image_info.push_back(img_info);
  5099. ERR_FAIL_COND_V_MSG(!buffer, RID(), "SamplerBuffer (binding: " + itos(uniform.binding) + ", index " + itos(j + 1) + ") is not a valid texture buffer.");
  5100. buffer_info.push_back(buffer->buffer.buffer_info);
  5101. buffer_view.push_back(buffer->view);
  5102. }
  5103. write.dstArrayElement = 0;
  5104. write.descriptorCount = uniform.get_id_count() / 2;
  5105. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER;
  5106. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  5107. write.pBufferInfo = buffer_infos.push_back(buffer_info)->get().ptr();
  5108. write.pTexelBufferView = buffer_views.push_back(buffer_view)->get().ptr();
  5109. type_size = uniform.get_id_count() / 2;
  5110. } break;
  5111. case UNIFORM_TYPE_IMAGE_BUFFER: {
  5112. //todo
  5113. } break;
  5114. case UNIFORM_TYPE_UNIFORM_BUFFER: {
  5115. ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(),
  5116. "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided).");
  5117. Buffer *buffer = uniform_buffer_owner.get_or_null(uniform.get_id(0));
  5118. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") is invalid.");
  5119. ERR_FAIL_COND_V_MSG(buffer->size != (uint32_t)set_uniform.length, RID(),
  5120. "Uniform buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " does not match size of shader uniform: (" + itos(set_uniform.length) + ").");
  5121. write.dstArrayElement = 0;
  5122. write.descriptorCount = 1;
  5123. write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  5124. write.pImageInfo = nullptr;
  5125. write.pBufferInfo = &buffer->buffer_info;
  5126. write.pTexelBufferView = nullptr;
  5127. } break;
  5128. case UNIFORM_TYPE_STORAGE_BUFFER: {
  5129. ERR_FAIL_COND_V_MSG(uniform.get_id_count() != 1, RID(),
  5130. "Storage buffer supplied (binding: " + itos(uniform.binding) + ") must provide one ID (" + itos(uniform.get_id_count()) + " provided).");
  5131. Buffer *buffer = nullptr;
  5132. if (storage_buffer_owner.owns(uniform.get_id(0))) {
  5133. buffer = storage_buffer_owner.get_or_null(uniform.get_id(0));
  5134. } else if (vertex_buffer_owner.owns(uniform.get_id(0))) {
  5135. buffer = vertex_buffer_owner.get_or_null(uniform.get_id(0));
  5136. 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.");
  5137. }
  5138. ERR_FAIL_COND_V_MSG(!buffer, RID(), "Storage buffer supplied (binding: " + itos(uniform.binding) + ") is invalid.");
  5139. //if 0, then it's sized on link time
  5140. ERR_FAIL_COND_V_MSG(set_uniform.length > 0 && buffer->size != (uint32_t)set_uniform.length, RID(),
  5141. "Storage buffer supplied (binding: " + itos(uniform.binding) + ") size (" + itos(buffer->size) + " does not match size of shader uniform: (" + itos(set_uniform.length) + ").");
  5142. write.dstArrayElement = 0;
  5143. write.descriptorCount = 1;
  5144. write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  5145. write.pImageInfo = nullptr;
  5146. write.pBufferInfo = &buffer->buffer_info;
  5147. write.pTexelBufferView = nullptr;
  5148. } break;
  5149. case UNIFORM_TYPE_INPUT_ATTACHMENT: {
  5150. ERR_FAIL_COND_V_MSG(shader->is_compute, RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") supplied for compute shader (this is not allowed).");
  5151. if (uniform.get_id_count() != (uint32_t)set_uniform.length) {
  5152. if (set_uniform.length > 1) {
  5153. 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.get_id_count()) + ").");
  5154. } else {
  5155. ERR_FAIL_V_MSG(RID(), "InputAttachment (binding: " + itos(uniform.binding) + ") should provide one ID referencing a texture (IDs provided: " + itos(uniform.get_id_count()) + ").");
  5156. }
  5157. }
  5158. Vector<VkDescriptorImageInfo> image_info;
  5159. for (uint32_t j = 0; j < uniform.get_id_count(); j++) {
  5160. Texture *texture = texture_owner.get_or_null(uniform.get_id(j));
  5161. ERR_FAIL_COND_V_MSG(!texture, RID(),
  5162. "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") is not a valid texture.");
  5163. ERR_FAIL_COND_V_MSG(!(texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT), RID(),
  5164. "InputAttachment (binding: " + itos(uniform.binding) + ", index " + itos(j) + ") needs the TEXTURE_USAGE_SAMPLING_BIT usage flag set in order to be used as uniform.");
  5165. VkDescriptorImageInfo img_info;
  5166. img_info.sampler = VK_NULL_HANDLE;
  5167. img_info.imageView = texture->view;
  5168. if (texture->owner.is_valid()) {
  5169. texture = texture_owner.get_or_null(texture->owner);
  5170. ERR_FAIL_COND_V(!texture, RID()); //bug, should never happen
  5171. }
  5172. img_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  5173. image_info.push_back(img_info);
  5174. }
  5175. write.dstArrayElement = 0;
  5176. write.descriptorCount = uniform.get_id_count();
  5177. write.descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT;
  5178. write.pImageInfo = image_infos.push_back(image_info)->get().ptr();
  5179. write.pBufferInfo = nullptr;
  5180. write.pTexelBufferView = nullptr;
  5181. type_size = uniform.get_id_count();
  5182. } break;
  5183. default: {
  5184. }
  5185. }
  5186. writes.push_back(write);
  5187. ERR_FAIL_COND_V_MSG(pool_key.uniform_type[set_uniform.type] == MAX_DESCRIPTOR_POOL_ELEMENT, RID(),
  5188. "Uniform set reached the limit of bindings for the same type (" + itos(MAX_DESCRIPTOR_POOL_ELEMENT) + ").");
  5189. pool_key.uniform_type[set_uniform.type] += type_size;
  5190. }
  5191. //need a descriptor pool
  5192. DescriptorPool *pool = _descriptor_pool_allocate(pool_key);
  5193. ERR_FAIL_COND_V(!pool, RID());
  5194. VkDescriptorSetAllocateInfo descriptor_set_allocate_info;
  5195. descriptor_set_allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
  5196. descriptor_set_allocate_info.pNext = nullptr;
  5197. descriptor_set_allocate_info.descriptorPool = pool->pool;
  5198. descriptor_set_allocate_info.descriptorSetCount = 1;
  5199. descriptor_set_allocate_info.pSetLayouts = &shader->sets[p_shader_set].descriptor_set_layout;
  5200. VkDescriptorSet descriptor_set;
  5201. VkResult res = vkAllocateDescriptorSets(device, &descriptor_set_allocate_info, &descriptor_set);
  5202. if (res) {
  5203. _descriptor_pool_free(pool_key, pool); // meh
  5204. ERR_FAIL_V_MSG(RID(), "Cannot allocate descriptor sets, error " + itos(res) + ".");
  5205. }
  5206. UniformSet uniform_set;
  5207. uniform_set.pool = pool;
  5208. uniform_set.pool_key = pool_key;
  5209. uniform_set.descriptor_set = descriptor_set;
  5210. uniform_set.format = shader->set_formats[p_shader_set];
  5211. uniform_set.attachable_textures = attachable_textures;
  5212. uniform_set.mutable_sampled_textures = mutable_sampled_textures;
  5213. uniform_set.mutable_storage_textures = mutable_storage_textures;
  5214. uniform_set.shader_set = p_shader_set;
  5215. uniform_set.shader_id = p_shader;
  5216. RID id = uniform_set_owner.make_rid(uniform_set);
  5217. #ifdef DEV_ENABLED
  5218. set_resource_name(id, "RID:" + itos(id.get_id()));
  5219. #endif
  5220. //add dependencies
  5221. _add_dependency(id, p_shader);
  5222. for (uint32_t i = 0; i < uniform_count; i++) {
  5223. const Uniform &uniform = uniforms[i];
  5224. int id_count = uniform.get_id_count();
  5225. for (int j = 0; j < id_count; j++) {
  5226. _add_dependency(id, uniform.get_id(j));
  5227. }
  5228. }
  5229. //write the contents
  5230. if (writes.size()) {
  5231. for (int i = 0; i < writes.size(); i++) {
  5232. writes.write[i].dstSet = descriptor_set;
  5233. }
  5234. vkUpdateDescriptorSets(device, writes.size(), writes.ptr(), 0, nullptr);
  5235. }
  5236. return id;
  5237. }
  5238. bool RenderingDeviceVulkan::uniform_set_is_valid(RID p_uniform_set) {
  5239. return uniform_set_owner.owns(p_uniform_set);
  5240. }
  5241. void RenderingDeviceVulkan::uniform_set_set_invalidation_callback(RID p_uniform_set, UniformSetInvalidatedCallback p_callback, void *p_userdata) {
  5242. UniformSet *us = uniform_set_owner.get_or_null(p_uniform_set);
  5243. ERR_FAIL_COND(!us);
  5244. us->invalidated_callback = p_callback;
  5245. us->invalidated_callback_userdata = p_userdata;
  5246. }
  5247. Error RenderingDeviceVulkan::buffer_update(RID p_buffer, uint32_t p_offset, uint32_t p_size, const void *p_data, uint32_t p_post_barrier) {
  5248. _THREAD_SAFE_METHOD_
  5249. ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER,
  5250. "Updating buffers is forbidden during creation of a draw list");
  5251. ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER,
  5252. "Updating buffers is forbidden during creation of a compute list");
  5253. VkPipelineStageFlags dst_stage_mask = 0;
  5254. VkAccessFlags dst_access = 0;
  5255. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  5256. // Protect subsequent updates...
  5257. dst_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  5258. dst_access = VK_ACCESS_TRANSFER_WRITE_BIT;
  5259. }
  5260. Buffer *buffer = _get_buffer_from_owner(p_buffer, dst_stage_mask, dst_access, p_post_barrier);
  5261. if (!buffer) {
  5262. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type.");
  5263. }
  5264. ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER,
  5265. "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end.");
  5266. // no barrier should be needed here
  5267. // _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);
  5268. Error err = _buffer_update(buffer, p_offset, (uint8_t *)p_data, p_size, p_post_barrier);
  5269. if (err) {
  5270. return err;
  5271. }
  5272. #ifdef FORCE_FULL_BARRIER
  5273. _full_barrier(true);
  5274. #else
  5275. if (dst_stage_mask == 0) {
  5276. dst_stage_mask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  5277. }
  5278. if (p_post_barrier != RD::BARRIER_MASK_NO_BARRIER) {
  5279. _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);
  5280. }
  5281. #endif
  5282. return err;
  5283. }
  5284. Error RenderingDeviceVulkan::buffer_clear(RID p_buffer, uint32_t p_offset, uint32_t p_size, uint32_t p_post_barrier) {
  5285. _THREAD_SAFE_METHOD_
  5286. ERR_FAIL_COND_V_MSG((p_size % 4) != 0, ERR_INVALID_PARAMETER,
  5287. "Size must be a multiple of four");
  5288. ERR_FAIL_COND_V_MSG(draw_list, ERR_INVALID_PARAMETER,
  5289. "Updating buffers in is forbidden during creation of a draw list");
  5290. ERR_FAIL_COND_V_MSG(compute_list, ERR_INVALID_PARAMETER,
  5291. "Updating buffers is forbidden during creation of a compute list");
  5292. VkPipelineStageFlags dst_stage_mask = 0;
  5293. VkAccessFlags dst_access = 0;
  5294. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  5295. // Protect subsequent updates...
  5296. dst_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  5297. dst_access = VK_ACCESS_TRANSFER_WRITE_BIT;
  5298. }
  5299. Buffer *buffer = _get_buffer_from_owner(p_buffer, dst_stage_mask, dst_access, p_post_barrier);
  5300. if (!buffer) {
  5301. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Buffer argument is not a valid buffer of any type.");
  5302. }
  5303. ERR_FAIL_COND_V_MSG(p_offset + p_size > buffer->size, ERR_INVALID_PARAMETER,
  5304. "Attempted to write buffer (" + itos((p_offset + p_size) - buffer->size) + " bytes) past the end.");
  5305. // should not be needed
  5306. // _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);
  5307. vkCmdFillBuffer(frames[frame].draw_command_buffer, buffer->buffer, p_offset, p_size, 0);
  5308. #ifdef FORCE_FULL_BARRIER
  5309. _full_barrier(true);
  5310. #else
  5311. if (dst_stage_mask == 0) {
  5312. dst_stage_mask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  5313. }
  5314. _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);
  5315. #endif
  5316. return OK;
  5317. }
  5318. Vector<uint8_t> RenderingDeviceVulkan::buffer_get_data(RID p_buffer) {
  5319. _THREAD_SAFE_METHOD_
  5320. // It could be this buffer was just created
  5321. VkPipelineShaderStageCreateFlags src_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  5322. VkAccessFlags src_access_mask = VK_ACCESS_TRANSFER_WRITE_BIT;
  5323. // Get the vulkan buffer and the potential stage/access possible
  5324. Buffer *buffer = _get_buffer_from_owner(p_buffer, src_stage_mask, src_access_mask, BARRIER_MASK_ALL);
  5325. if (!buffer) {
  5326. 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.");
  5327. }
  5328. // Make sure no one is using the buffer -- the "false" gets us to the same command buffer as below.
  5329. _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);
  5330. VkCommandBuffer command_buffer = frames[frame].setup_command_buffer;
  5331. Buffer tmp_buffer;
  5332. _buffer_allocate(&tmp_buffer, buffer->size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_AUTO_PREFER_HOST, VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT);
  5333. VkBufferCopy region;
  5334. region.srcOffset = 0;
  5335. region.dstOffset = 0;
  5336. region.size = buffer->size;
  5337. 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..
  5338. //flush everything so memory can be safely mapped
  5339. _flush(true);
  5340. void *buffer_mem;
  5341. VkResult vkerr = vmaMapMemory(allocator, tmp_buffer.allocation, &buffer_mem);
  5342. ERR_FAIL_COND_V_MSG(vkerr, Vector<uint8_t>(), "vmaMapMemory failed with error " + itos(vkerr) + ".");
  5343. Vector<uint8_t> buffer_data;
  5344. {
  5345. buffer_data.resize(buffer->size);
  5346. uint8_t *w = buffer_data.ptrw();
  5347. memcpy(w, buffer_mem, buffer->size);
  5348. }
  5349. vmaUnmapMemory(allocator, tmp_buffer.allocation);
  5350. _buffer_free(&tmp_buffer);
  5351. return buffer_data;
  5352. }
  5353. /*************************/
  5354. /**** RENDER PIPELINE ****/
  5355. /*************************/
  5356. 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) {
  5357. _THREAD_SAFE_METHOD_
  5358. //needs a shader
  5359. Shader *shader = shader_owner.get_or_null(p_shader);
  5360. ERR_FAIL_COND_V(!shader, RID());
  5361. ERR_FAIL_COND_V_MSG(shader->is_compute, RID(),
  5362. "Compute shaders can't be used in render pipelines");
  5363. if (p_framebuffer_format == INVALID_ID) {
  5364. //if nothing provided, use an empty one (no attachments)
  5365. p_framebuffer_format = framebuffer_format_create(Vector<AttachmentFormat>());
  5366. }
  5367. ERR_FAIL_COND_V(!framebuffer_formats.has(p_framebuffer_format), RID());
  5368. const FramebufferFormat &fb_format = framebuffer_formats[p_framebuffer_format];
  5369. { //validate shader vs framebuffer
  5370. 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");
  5371. const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass];
  5372. uint32_t output_mask = 0;
  5373. for (int i = 0; i < pass.color_attachments.size(); i++) {
  5374. if (pass.color_attachments[i] != FramebufferPass::ATTACHMENT_UNUSED) {
  5375. output_mask |= 1 << i;
  5376. }
  5377. }
  5378. ERR_FAIL_COND_V_MSG(shader->fragment_output_mask != output_mask, RID(),
  5379. "Mismatch fragment shader output mask (" + itos(shader->fragment_output_mask) + ") and framebuffer color output mask (" + itos(output_mask) + ") when binding both in render pipeline.");
  5380. }
  5381. //vertex
  5382. VkPipelineVertexInputStateCreateInfo pipeline_vertex_input_state_create_info;
  5383. if (p_vertex_format != INVALID_ID) {
  5384. //uses vertices, else it does not
  5385. ERR_FAIL_COND_V(!vertex_formats.has(p_vertex_format), RID());
  5386. const VertexDescriptionCache &vd = vertex_formats[p_vertex_format];
  5387. pipeline_vertex_input_state_create_info = vd.create_info;
  5388. //validate with inputs
  5389. for (uint32_t i = 0; i < 32; i++) {
  5390. if (!(shader->vertex_input_mask & (1UL << i))) {
  5391. continue;
  5392. }
  5393. bool found = false;
  5394. for (int j = 0; j < vd.vertex_formats.size(); j++) {
  5395. if (vd.vertex_formats[j].location == i) {
  5396. found = true;
  5397. }
  5398. }
  5399. ERR_FAIL_COND_V_MSG(!found, RID(),
  5400. "Shader vertex input location (" + itos(i) + ") not provided in vertex input description for pipeline creation.");
  5401. }
  5402. } else {
  5403. //does not use vertices
  5404. pipeline_vertex_input_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  5405. pipeline_vertex_input_state_create_info.pNext = nullptr;
  5406. pipeline_vertex_input_state_create_info.flags = 0;
  5407. pipeline_vertex_input_state_create_info.vertexBindingDescriptionCount = 0;
  5408. pipeline_vertex_input_state_create_info.pVertexBindingDescriptions = nullptr;
  5409. pipeline_vertex_input_state_create_info.vertexAttributeDescriptionCount = 0;
  5410. pipeline_vertex_input_state_create_info.pVertexAttributeDescriptions = nullptr;
  5411. ERR_FAIL_COND_V_MSG(shader->vertex_input_mask != 0, RID(),
  5412. "Shader contains vertex inputs, but no vertex input description was provided for pipeline creation.");
  5413. }
  5414. //input assembly
  5415. ERR_FAIL_INDEX_V(p_render_primitive, RENDER_PRIMITIVE_MAX, RID());
  5416. VkPipelineInputAssemblyStateCreateInfo input_assembly_create_info;
  5417. input_assembly_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  5418. input_assembly_create_info.pNext = nullptr;
  5419. input_assembly_create_info.flags = 0;
  5420. static const VkPrimitiveTopology topology_list[RENDER_PRIMITIVE_MAX] = {
  5421. VK_PRIMITIVE_TOPOLOGY_POINT_LIST,
  5422. VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
  5423. VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY,
  5424. VK_PRIMITIVE_TOPOLOGY_LINE_STRIP,
  5425. VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY,
  5426. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
  5427. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY,
  5428. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
  5429. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY,
  5430. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
  5431. VK_PRIMITIVE_TOPOLOGY_PATCH_LIST
  5432. };
  5433. input_assembly_create_info.topology = topology_list[p_render_primitive];
  5434. input_assembly_create_info.primitiveRestartEnable = (p_render_primitive == RENDER_PRIMITIVE_TRIANGLE_STRIPS_WITH_RESTART_INDEX);
  5435. //tessellation
  5436. VkPipelineTessellationStateCreateInfo tessellation_create_info;
  5437. tessellation_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO;
  5438. tessellation_create_info.pNext = nullptr;
  5439. tessellation_create_info.flags = 0;
  5440. ERR_FAIL_COND_V(limits.maxTessellationPatchSize > 0 && (p_rasterization_state.patch_control_points < 1 || p_rasterization_state.patch_control_points > limits.maxTessellationPatchSize), RID());
  5441. tessellation_create_info.patchControlPoints = p_rasterization_state.patch_control_points;
  5442. VkPipelineViewportStateCreateInfo viewport_state_create_info;
  5443. viewport_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  5444. viewport_state_create_info.pNext = nullptr;
  5445. viewport_state_create_info.flags = 0;
  5446. viewport_state_create_info.viewportCount = 1; //if VR extensions are supported at some point, this will have to be customizable in the framebuffer format
  5447. viewport_state_create_info.pViewports = nullptr;
  5448. viewport_state_create_info.scissorCount = 1;
  5449. viewport_state_create_info.pScissors = nullptr;
  5450. //rasterization
  5451. VkPipelineRasterizationStateCreateInfo rasterization_state_create_info;
  5452. rasterization_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  5453. rasterization_state_create_info.pNext = nullptr;
  5454. rasterization_state_create_info.flags = 0;
  5455. rasterization_state_create_info.depthClampEnable = p_rasterization_state.enable_depth_clamp;
  5456. rasterization_state_create_info.rasterizerDiscardEnable = p_rasterization_state.discard_primitives;
  5457. rasterization_state_create_info.polygonMode = (p_rasterization_state.wireframe ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL);
  5458. static const VkCullModeFlags cull_mode[3] = {
  5459. VK_CULL_MODE_NONE,
  5460. VK_CULL_MODE_FRONT_BIT,
  5461. VK_CULL_MODE_BACK_BIT
  5462. };
  5463. ERR_FAIL_INDEX_V(p_rasterization_state.cull_mode, 3, RID());
  5464. rasterization_state_create_info.cullMode = cull_mode[p_rasterization_state.cull_mode];
  5465. rasterization_state_create_info.frontFace = (p_rasterization_state.front_face == POLYGON_FRONT_FACE_CLOCKWISE ? VK_FRONT_FACE_CLOCKWISE : VK_FRONT_FACE_COUNTER_CLOCKWISE);
  5466. rasterization_state_create_info.depthBiasEnable = p_rasterization_state.depth_bias_enable;
  5467. rasterization_state_create_info.depthBiasConstantFactor = p_rasterization_state.depth_bias_constant_factor;
  5468. rasterization_state_create_info.depthBiasClamp = p_rasterization_state.depth_bias_clamp;
  5469. rasterization_state_create_info.depthBiasSlopeFactor = p_rasterization_state.depth_bias_slope_factor;
  5470. rasterization_state_create_info.lineWidth = p_rasterization_state.line_width;
  5471. //multisample
  5472. VkPipelineMultisampleStateCreateInfo multisample_state_create_info;
  5473. multisample_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  5474. multisample_state_create_info.pNext = nullptr;
  5475. multisample_state_create_info.flags = 0;
  5476. multisample_state_create_info.rasterizationSamples = rasterization_sample_count[p_multisample_state.sample_count];
  5477. multisample_state_create_info.sampleShadingEnable = p_multisample_state.enable_sample_shading;
  5478. multisample_state_create_info.minSampleShading = p_multisample_state.min_sample_shading;
  5479. Vector<VkSampleMask> sample_mask;
  5480. if (p_multisample_state.sample_mask.size()) {
  5481. //use sample mask
  5482. const int rasterization_sample_mask_expected_size[TEXTURE_SAMPLES_MAX] = {
  5483. 1, 2, 4, 8, 16, 32, 64
  5484. };
  5485. ERR_FAIL_COND_V(rasterization_sample_mask_expected_size[p_multisample_state.sample_count] != p_multisample_state.sample_mask.size(), RID());
  5486. sample_mask.resize(p_multisample_state.sample_mask.size());
  5487. for (int i = 0; i < p_multisample_state.sample_mask.size(); i++) {
  5488. VkSampleMask mask = p_multisample_state.sample_mask[i];
  5489. sample_mask.push_back(mask);
  5490. }
  5491. multisample_state_create_info.pSampleMask = sample_mask.ptr();
  5492. } else {
  5493. multisample_state_create_info.pSampleMask = nullptr;
  5494. }
  5495. multisample_state_create_info.alphaToCoverageEnable = p_multisample_state.enable_alpha_to_coverage;
  5496. multisample_state_create_info.alphaToOneEnable = p_multisample_state.enable_alpha_to_one;
  5497. //depth stencil
  5498. VkPipelineDepthStencilStateCreateInfo depth_stencil_state_create_info;
  5499. depth_stencil_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  5500. depth_stencil_state_create_info.pNext = nullptr;
  5501. depth_stencil_state_create_info.flags = 0;
  5502. depth_stencil_state_create_info.depthTestEnable = p_depth_stencil_state.enable_depth_test;
  5503. depth_stencil_state_create_info.depthWriteEnable = p_depth_stencil_state.enable_depth_write;
  5504. ERR_FAIL_INDEX_V(p_depth_stencil_state.depth_compare_operator, COMPARE_OP_MAX, RID());
  5505. depth_stencil_state_create_info.depthCompareOp = compare_operators[p_depth_stencil_state.depth_compare_operator];
  5506. depth_stencil_state_create_info.depthBoundsTestEnable = p_depth_stencil_state.enable_depth_range;
  5507. depth_stencil_state_create_info.stencilTestEnable = p_depth_stencil_state.enable_stencil;
  5508. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.fail, STENCIL_OP_MAX, RID());
  5509. depth_stencil_state_create_info.front.failOp = stencil_operations[p_depth_stencil_state.front_op.fail];
  5510. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.pass, STENCIL_OP_MAX, RID());
  5511. depth_stencil_state_create_info.front.passOp = stencil_operations[p_depth_stencil_state.front_op.pass];
  5512. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.depth_fail, STENCIL_OP_MAX, RID());
  5513. depth_stencil_state_create_info.front.depthFailOp = stencil_operations[p_depth_stencil_state.front_op.depth_fail];
  5514. ERR_FAIL_INDEX_V(p_depth_stencil_state.front_op.compare, COMPARE_OP_MAX, RID());
  5515. depth_stencil_state_create_info.front.compareOp = compare_operators[p_depth_stencil_state.front_op.compare];
  5516. depth_stencil_state_create_info.front.compareMask = p_depth_stencil_state.front_op.compare_mask;
  5517. depth_stencil_state_create_info.front.writeMask = p_depth_stencil_state.front_op.write_mask;
  5518. depth_stencil_state_create_info.front.reference = p_depth_stencil_state.front_op.reference;
  5519. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.fail, STENCIL_OP_MAX, RID());
  5520. depth_stencil_state_create_info.back.failOp = stencil_operations[p_depth_stencil_state.back_op.fail];
  5521. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.pass, STENCIL_OP_MAX, RID());
  5522. depth_stencil_state_create_info.back.passOp = stencil_operations[p_depth_stencil_state.back_op.pass];
  5523. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.depth_fail, STENCIL_OP_MAX, RID());
  5524. depth_stencil_state_create_info.back.depthFailOp = stencil_operations[p_depth_stencil_state.back_op.depth_fail];
  5525. ERR_FAIL_INDEX_V(p_depth_stencil_state.back_op.compare, COMPARE_OP_MAX, RID());
  5526. depth_stencil_state_create_info.back.compareOp = compare_operators[p_depth_stencil_state.back_op.compare];
  5527. depth_stencil_state_create_info.back.compareMask = p_depth_stencil_state.back_op.compare_mask;
  5528. depth_stencil_state_create_info.back.writeMask = p_depth_stencil_state.back_op.write_mask;
  5529. depth_stencil_state_create_info.back.reference = p_depth_stencil_state.back_op.reference;
  5530. depth_stencil_state_create_info.minDepthBounds = p_depth_stencil_state.depth_range_min;
  5531. depth_stencil_state_create_info.maxDepthBounds = p_depth_stencil_state.depth_range_max;
  5532. //blend state
  5533. VkPipelineColorBlendStateCreateInfo color_blend_state_create_info;
  5534. color_blend_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  5535. color_blend_state_create_info.pNext = nullptr;
  5536. color_blend_state_create_info.flags = 0;
  5537. color_blend_state_create_info.logicOpEnable = p_blend_state.enable_logic_op;
  5538. ERR_FAIL_INDEX_V(p_blend_state.logic_op, LOGIC_OP_MAX, RID());
  5539. color_blend_state_create_info.logicOp = logic_operations[p_blend_state.logic_op];
  5540. Vector<VkPipelineColorBlendAttachmentState> attachment_states;
  5541. {
  5542. const FramebufferPass &pass = fb_format.E->key().passes[p_for_render_pass];
  5543. attachment_states.resize(pass.color_attachments.size());
  5544. ERR_FAIL_COND_V(p_blend_state.attachments.size() < pass.color_attachments.size(), RID());
  5545. for (int i = 0; i < pass.color_attachments.size(); i++) {
  5546. VkPipelineColorBlendAttachmentState state;
  5547. if (pass.color_attachments[i] == FramebufferPass::ATTACHMENT_UNUSED) {
  5548. state.blendEnable = false;
  5549. state.srcColorBlendFactor = VK_BLEND_FACTOR_ZERO;
  5550. state.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO;
  5551. state.colorBlendOp = VK_BLEND_OP_ADD;
  5552. state.srcAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
  5553. state.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
  5554. state.alphaBlendOp = VK_BLEND_OP_ADD;
  5555. state.colorWriteMask = 0;
  5556. } else {
  5557. state.blendEnable = p_blend_state.attachments[i].enable_blend;
  5558. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_color_blend_factor, BLEND_FACTOR_MAX, RID());
  5559. state.srcColorBlendFactor = blend_factors[p_blend_state.attachments[i].src_color_blend_factor];
  5560. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_color_blend_factor, BLEND_FACTOR_MAX, RID());
  5561. state.dstColorBlendFactor = blend_factors[p_blend_state.attachments[i].dst_color_blend_factor];
  5562. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].color_blend_op, BLEND_OP_MAX, RID());
  5563. state.colorBlendOp = blend_operations[p_blend_state.attachments[i].color_blend_op];
  5564. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].src_alpha_blend_factor, BLEND_FACTOR_MAX, RID());
  5565. state.srcAlphaBlendFactor = blend_factors[p_blend_state.attachments[i].src_alpha_blend_factor];
  5566. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].dst_alpha_blend_factor, BLEND_FACTOR_MAX, RID());
  5567. state.dstAlphaBlendFactor = blend_factors[p_blend_state.attachments[i].dst_alpha_blend_factor];
  5568. ERR_FAIL_INDEX_V(p_blend_state.attachments[i].alpha_blend_op, BLEND_OP_MAX, RID());
  5569. state.alphaBlendOp = blend_operations[p_blend_state.attachments[i].alpha_blend_op];
  5570. state.colorWriteMask = 0;
  5571. if (p_blend_state.attachments[i].write_r) {
  5572. state.colorWriteMask |= VK_COLOR_COMPONENT_R_BIT;
  5573. }
  5574. if (p_blend_state.attachments[i].write_g) {
  5575. state.colorWriteMask |= VK_COLOR_COMPONENT_G_BIT;
  5576. }
  5577. if (p_blend_state.attachments[i].write_b) {
  5578. state.colorWriteMask |= VK_COLOR_COMPONENT_B_BIT;
  5579. }
  5580. if (p_blend_state.attachments[i].write_a) {
  5581. state.colorWriteMask |= VK_COLOR_COMPONENT_A_BIT;
  5582. }
  5583. }
  5584. attachment_states.write[i] = state;
  5585. }
  5586. }
  5587. color_blend_state_create_info.attachmentCount = attachment_states.size();
  5588. color_blend_state_create_info.pAttachments = attachment_states.ptr();
  5589. color_blend_state_create_info.blendConstants[0] = p_blend_state.blend_constant.r;
  5590. color_blend_state_create_info.blendConstants[1] = p_blend_state.blend_constant.g;
  5591. color_blend_state_create_info.blendConstants[2] = p_blend_state.blend_constant.b;
  5592. color_blend_state_create_info.blendConstants[3] = p_blend_state.blend_constant.a;
  5593. //dynamic state
  5594. VkPipelineDynamicStateCreateInfo dynamic_state_create_info;
  5595. dynamic_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
  5596. dynamic_state_create_info.pNext = nullptr;
  5597. dynamic_state_create_info.flags = 0;
  5598. Vector<VkDynamicState> dynamic_states; //vulkan is weird..
  5599. dynamic_states.push_back(VK_DYNAMIC_STATE_VIEWPORT); //viewport and scissor are always dynamic
  5600. dynamic_states.push_back(VK_DYNAMIC_STATE_SCISSOR);
  5601. if (p_dynamic_state_flags & DYNAMIC_STATE_LINE_WIDTH) {
  5602. dynamic_states.push_back(VK_DYNAMIC_STATE_LINE_WIDTH);
  5603. }
  5604. if (p_dynamic_state_flags & DYNAMIC_STATE_DEPTH_BIAS) {
  5605. dynamic_states.push_back(VK_DYNAMIC_STATE_DEPTH_BIAS);
  5606. }
  5607. if (p_dynamic_state_flags & DYNAMIC_STATE_BLEND_CONSTANTS) {
  5608. dynamic_states.push_back(VK_DYNAMIC_STATE_BLEND_CONSTANTS);
  5609. }
  5610. if (p_dynamic_state_flags & DYNAMIC_STATE_DEPTH_BOUNDS) {
  5611. dynamic_states.push_back(VK_DYNAMIC_STATE_DEPTH_BOUNDS);
  5612. }
  5613. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_COMPARE_MASK) {
  5614. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK);
  5615. }
  5616. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_WRITE_MASK) {
  5617. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_WRITE_MASK);
  5618. }
  5619. if (p_dynamic_state_flags & DYNAMIC_STATE_STENCIL_REFERENCE) {
  5620. dynamic_states.push_back(VK_DYNAMIC_STATE_STENCIL_REFERENCE);
  5621. }
  5622. dynamic_state_create_info.dynamicStateCount = dynamic_states.size();
  5623. dynamic_state_create_info.pDynamicStates = dynamic_states.ptr();
  5624. //finally, pipeline create info
  5625. VkGraphicsPipelineCreateInfo graphics_pipeline_create_info;
  5626. graphics_pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  5627. graphics_pipeline_create_info.pNext = nullptr;
  5628. graphics_pipeline_create_info.flags = 0;
  5629. Vector<VkPipelineShaderStageCreateInfo> pipeline_stages = shader->pipeline_stages;
  5630. Vector<VkSpecializationInfo> specialization_info;
  5631. Vector<Vector<VkSpecializationMapEntry>> specialization_map_entries;
  5632. Vector<uint32_t> specialization_constant_data;
  5633. if (shader->specialization_constants.size()) {
  5634. specialization_constant_data.resize(shader->specialization_constants.size());
  5635. uint32_t *data_ptr = specialization_constant_data.ptrw();
  5636. specialization_info.resize(pipeline_stages.size());
  5637. specialization_map_entries.resize(pipeline_stages.size());
  5638. for (int i = 0; i < shader->specialization_constants.size(); i++) {
  5639. //see if overridden
  5640. const Shader::SpecializationConstant &sc = shader->specialization_constants[i];
  5641. data_ptr[i] = sc.constant.int_value; //just copy the 32 bits
  5642. for (int j = 0; j < p_specialization_constants.size(); j++) {
  5643. const PipelineSpecializationConstant &psc = p_specialization_constants[j];
  5644. if (psc.constant_id == sc.constant.constant_id) {
  5645. 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.");
  5646. data_ptr[i] = psc.int_value;
  5647. break;
  5648. }
  5649. }
  5650. VkSpecializationMapEntry entry;
  5651. entry.constantID = sc.constant.constant_id;
  5652. entry.offset = i * sizeof(uint32_t);
  5653. entry.size = sizeof(uint32_t);
  5654. for (int j = 0; j < SHADER_STAGE_MAX; j++) {
  5655. if (sc.stage_flags & (1 << j)) {
  5656. VkShaderStageFlagBits stage = shader_stage_masks[j];
  5657. for (int k = 0; k < pipeline_stages.size(); k++) {
  5658. if (pipeline_stages[k].stage == stage) {
  5659. specialization_map_entries.write[k].push_back(entry);
  5660. }
  5661. }
  5662. }
  5663. }
  5664. }
  5665. for (int i = 0; i < pipeline_stages.size(); i++) {
  5666. if (specialization_map_entries[i].size()) {
  5667. specialization_info.write[i].dataSize = specialization_constant_data.size() * sizeof(uint32_t);
  5668. specialization_info.write[i].pData = data_ptr;
  5669. specialization_info.write[i].mapEntryCount = specialization_map_entries[i].size();
  5670. specialization_info.write[i].pMapEntries = specialization_map_entries[i].ptr();
  5671. pipeline_stages.write[i].pSpecializationInfo = specialization_info.ptr() + i;
  5672. }
  5673. }
  5674. }
  5675. graphics_pipeline_create_info.stageCount = pipeline_stages.size();
  5676. graphics_pipeline_create_info.pStages = pipeline_stages.ptr();
  5677. graphics_pipeline_create_info.pVertexInputState = &pipeline_vertex_input_state_create_info;
  5678. graphics_pipeline_create_info.pInputAssemblyState = &input_assembly_create_info;
  5679. graphics_pipeline_create_info.pTessellationState = &tessellation_create_info;
  5680. graphics_pipeline_create_info.pViewportState = &viewport_state_create_info;
  5681. graphics_pipeline_create_info.pRasterizationState = &rasterization_state_create_info;
  5682. graphics_pipeline_create_info.pMultisampleState = &multisample_state_create_info;
  5683. graphics_pipeline_create_info.pDepthStencilState = &depth_stencil_state_create_info;
  5684. graphics_pipeline_create_info.pColorBlendState = &color_blend_state_create_info;
  5685. graphics_pipeline_create_info.pDynamicState = &dynamic_state_create_info;
  5686. graphics_pipeline_create_info.layout = shader->pipeline_layout;
  5687. graphics_pipeline_create_info.renderPass = fb_format.render_pass;
  5688. graphics_pipeline_create_info.subpass = p_for_render_pass;
  5689. graphics_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE;
  5690. graphics_pipeline_create_info.basePipelineIndex = 0;
  5691. RenderPipeline pipeline;
  5692. VkResult err = vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &graphics_pipeline_create_info, nullptr, &pipeline.pipeline);
  5693. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateGraphicsPipelines failed with error " + itos(err) + " for shader '" + shader->name + "'.");
  5694. pipeline.set_formats = shader->set_formats;
  5695. pipeline.push_constant_stages = shader->push_constant.push_constants_vk_stage;
  5696. pipeline.pipeline_layout = shader->pipeline_layout;
  5697. pipeline.shader = p_shader;
  5698. pipeline.push_constant_size = shader->push_constant.push_constant_size;
  5699. #ifdef DEBUG_ENABLED
  5700. pipeline.validation.dynamic_state = p_dynamic_state_flags;
  5701. pipeline.validation.framebuffer_format = p_framebuffer_format;
  5702. pipeline.validation.render_pass = p_for_render_pass;
  5703. pipeline.validation.vertex_format = p_vertex_format;
  5704. pipeline.validation.uses_restart_indices = input_assembly_create_info.primitiveRestartEnable;
  5705. static const uint32_t primitive_divisor[RENDER_PRIMITIVE_MAX] = {
  5706. 1, 2, 1, 1, 1, 3, 1, 1, 1, 1, 1
  5707. };
  5708. pipeline.validation.primitive_divisor = primitive_divisor[p_render_primitive];
  5709. static const uint32_t primitive_minimum[RENDER_PRIMITIVE_MAX] = {
  5710. 1,
  5711. 2,
  5712. 2,
  5713. 2,
  5714. 2,
  5715. 3,
  5716. 3,
  5717. 3,
  5718. 3,
  5719. 3,
  5720. 1,
  5721. };
  5722. pipeline.validation.primitive_minimum = primitive_minimum[p_render_primitive];
  5723. #endif
  5724. //create ID to associate with this pipeline
  5725. RID id = render_pipeline_owner.make_rid(pipeline);
  5726. #ifdef DEV_ENABLED
  5727. set_resource_name(id, "RID:" + itos(id.get_id()));
  5728. #endif
  5729. //now add all the dependencies
  5730. _add_dependency(id, p_shader);
  5731. return id;
  5732. }
  5733. bool RenderingDeviceVulkan::render_pipeline_is_valid(RID p_pipeline) {
  5734. _THREAD_SAFE_METHOD_
  5735. return render_pipeline_owner.owns(p_pipeline);
  5736. }
  5737. /**************************/
  5738. /**** COMPUTE PIPELINE ****/
  5739. /**************************/
  5740. RID RenderingDeviceVulkan::compute_pipeline_create(RID p_shader, const Vector<PipelineSpecializationConstant> &p_specialization_constants) {
  5741. _THREAD_SAFE_METHOD_
  5742. //needs a shader
  5743. Shader *shader = shader_owner.get_or_null(p_shader);
  5744. ERR_FAIL_COND_V(!shader, RID());
  5745. ERR_FAIL_COND_V_MSG(!shader->is_compute, RID(),
  5746. "Non-compute shaders can't be used in compute pipelines");
  5747. //finally, pipeline create info
  5748. VkComputePipelineCreateInfo compute_pipeline_create_info;
  5749. compute_pipeline_create_info.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
  5750. compute_pipeline_create_info.pNext = nullptr;
  5751. compute_pipeline_create_info.flags = 0;
  5752. compute_pipeline_create_info.stage = shader->pipeline_stages[0];
  5753. compute_pipeline_create_info.layout = shader->pipeline_layout;
  5754. compute_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE;
  5755. compute_pipeline_create_info.basePipelineIndex = 0;
  5756. VkSpecializationInfo specialization_info;
  5757. Vector<VkSpecializationMapEntry> specialization_map_entries;
  5758. Vector<uint32_t> specialization_constant_data;
  5759. if (shader->specialization_constants.size()) {
  5760. specialization_constant_data.resize(shader->specialization_constants.size());
  5761. uint32_t *data_ptr = specialization_constant_data.ptrw();
  5762. for (int i = 0; i < shader->specialization_constants.size(); i++) {
  5763. //see if overridden
  5764. const Shader::SpecializationConstant &sc = shader->specialization_constants[i];
  5765. data_ptr[i] = sc.constant.int_value; //just copy the 32 bits
  5766. for (int j = 0; j < p_specialization_constants.size(); j++) {
  5767. const PipelineSpecializationConstant &psc = p_specialization_constants[j];
  5768. if (psc.constant_id == sc.constant.constant_id) {
  5769. 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.");
  5770. data_ptr[i] = sc.constant.int_value;
  5771. break;
  5772. }
  5773. }
  5774. VkSpecializationMapEntry entry;
  5775. entry.constantID = sc.constant.constant_id;
  5776. entry.offset = i * sizeof(uint32_t);
  5777. entry.size = sizeof(uint32_t);
  5778. specialization_map_entries.push_back(entry);
  5779. }
  5780. specialization_info.dataSize = specialization_constant_data.size() * sizeof(uint32_t);
  5781. specialization_info.pData = data_ptr;
  5782. specialization_info.mapEntryCount = specialization_map_entries.size();
  5783. specialization_info.pMapEntries = specialization_map_entries.ptr();
  5784. compute_pipeline_create_info.stage.pSpecializationInfo = &specialization_info;
  5785. }
  5786. ComputePipeline pipeline;
  5787. VkResult err = vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute_pipeline_create_info, nullptr, &pipeline.pipeline);
  5788. ERR_FAIL_COND_V_MSG(err, RID(), "vkCreateComputePipelines failed with error " + itos(err) + ".");
  5789. pipeline.set_formats = shader->set_formats;
  5790. pipeline.push_constant_stages = shader->push_constant.push_constants_vk_stage;
  5791. pipeline.pipeline_layout = shader->pipeline_layout;
  5792. pipeline.shader = p_shader;
  5793. pipeline.push_constant_size = shader->push_constant.push_constant_size;
  5794. pipeline.local_group_size[0] = shader->compute_local_size[0];
  5795. pipeline.local_group_size[1] = shader->compute_local_size[1];
  5796. pipeline.local_group_size[2] = shader->compute_local_size[2];
  5797. //create ID to associate with this pipeline
  5798. RID id = compute_pipeline_owner.make_rid(pipeline);
  5799. #ifdef DEV_ENABLED
  5800. set_resource_name(id, "RID:" + itos(id.get_id()));
  5801. #endif
  5802. //now add all the dependencies
  5803. _add_dependency(id, p_shader);
  5804. return id;
  5805. }
  5806. bool RenderingDeviceVulkan::compute_pipeline_is_valid(RID p_pipeline) {
  5807. return compute_pipeline_owner.owns(p_pipeline);
  5808. }
  5809. /****************/
  5810. /**** SCREEN ****/
  5811. /****************/
  5812. int RenderingDeviceVulkan::screen_get_width(DisplayServer::WindowID p_screen) const {
  5813. _THREAD_SAFE_METHOD_
  5814. ERR_FAIL_COND_V_MSG(local_device.is_valid(), -1, "Local devices have no screen");
  5815. return context->window_get_width(p_screen);
  5816. }
  5817. int RenderingDeviceVulkan::screen_get_height(DisplayServer::WindowID p_screen) const {
  5818. _THREAD_SAFE_METHOD_
  5819. ERR_FAIL_COND_V_MSG(local_device.is_valid(), -1, "Local devices have no screen");
  5820. return context->window_get_height(p_screen);
  5821. }
  5822. RenderingDevice::FramebufferFormatID RenderingDeviceVulkan::screen_get_framebuffer_format() const {
  5823. _THREAD_SAFE_METHOD_
  5824. ERR_FAIL_COND_V_MSG(local_device.is_valid(), INVALID_ID, "Local devices have no screen");
  5825. //very hacky, but not used often per frame so I guess ok
  5826. VkFormat vkformat = context->get_screen_format();
  5827. DataFormat format = DATA_FORMAT_MAX;
  5828. for (int i = 0; i < DATA_FORMAT_MAX; i++) {
  5829. if (vkformat == vulkan_formats[i]) {
  5830. format = DataFormat(i);
  5831. break;
  5832. }
  5833. }
  5834. ERR_FAIL_COND_V(format == DATA_FORMAT_MAX, INVALID_ID);
  5835. AttachmentFormat attachment;
  5836. attachment.format = format;
  5837. attachment.samples = TEXTURE_SAMPLES_1;
  5838. attachment.usage_flags = TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  5839. Vector<AttachmentFormat> screen_attachment;
  5840. screen_attachment.push_back(attachment);
  5841. return const_cast<RenderingDeviceVulkan *>(this)->framebuffer_format_create(screen_attachment);
  5842. }
  5843. /*******************/
  5844. /**** DRAW LIST ****/
  5845. /*******************/
  5846. RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_begin_for_screen(DisplayServer::WindowID p_screen, const Color &p_clear_color) {
  5847. _THREAD_SAFE_METHOD_
  5848. ERR_FAIL_COND_V_MSG(local_device.is_valid(), INVALID_ID, "Local devices have no screen");
  5849. ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  5850. ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  5851. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  5852. if (!context->window_is_valid_swapchain(p_screen)) {
  5853. return INVALID_ID;
  5854. }
  5855. Size2i size = Size2i(context->window_get_width(p_screen), context->window_get_height(p_screen));
  5856. _draw_list_allocate(Rect2i(Vector2i(), size), 0, 0);
  5857. #ifdef DEBUG_ENABLED
  5858. draw_list_framebuffer_format = screen_get_framebuffer_format();
  5859. #endif
  5860. draw_list_subpass_count = 1;
  5861. VkRenderPassBeginInfo render_pass_begin;
  5862. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  5863. render_pass_begin.pNext = nullptr;
  5864. render_pass_begin.renderPass = context->window_get_render_pass(p_screen);
  5865. render_pass_begin.framebuffer = context->window_get_framebuffer(p_screen);
  5866. render_pass_begin.renderArea.extent.width = size.width;
  5867. render_pass_begin.renderArea.extent.height = size.height;
  5868. render_pass_begin.renderArea.offset.x = 0;
  5869. render_pass_begin.renderArea.offset.y = 0;
  5870. render_pass_begin.clearValueCount = 1;
  5871. VkClearValue clear_value;
  5872. clear_value.color.float32[0] = p_clear_color.r;
  5873. clear_value.color.float32[1] = p_clear_color.g;
  5874. clear_value.color.float32[2] = p_clear_color.b;
  5875. clear_value.color.float32[3] = p_clear_color.a;
  5876. render_pass_begin.pClearValues = &clear_value;
  5877. vkCmdBeginRenderPass(command_buffer, &render_pass_begin, VK_SUBPASS_CONTENTS_INLINE);
  5878. uint32_t size_x = screen_get_width(p_screen);
  5879. uint32_t size_y = screen_get_height(p_screen);
  5880. VkViewport viewport;
  5881. viewport.x = 0;
  5882. viewport.y = 0;
  5883. viewport.width = size_x;
  5884. viewport.height = size_y;
  5885. viewport.minDepth = 0;
  5886. viewport.maxDepth = 1.0;
  5887. vkCmdSetViewport(command_buffer, 0, 1, &viewport);
  5888. VkRect2D scissor;
  5889. scissor.offset.x = 0;
  5890. scissor.offset.y = 0;
  5891. scissor.extent.width = size_x;
  5892. scissor.extent.height = size_y;
  5893. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  5894. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  5895. }
  5896. 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) {
  5897. Framebuffer::VersionKey vk;
  5898. vk.initial_color_action = p_initial_color_action;
  5899. vk.final_color_action = p_final_color_action;
  5900. vk.initial_depth_action = p_initial_depth_action;
  5901. vk.final_depth_action = p_final_depth_action;
  5902. vk.view_count = p_framebuffer->view_count;
  5903. if (!p_framebuffer->framebuffers.has(vk)) {
  5904. //need to create this version
  5905. Framebuffer::Version version;
  5906. 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);
  5907. VkFramebufferCreateInfo framebuffer_create_info;
  5908. framebuffer_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  5909. framebuffer_create_info.pNext = nullptr;
  5910. framebuffer_create_info.flags = 0;
  5911. framebuffer_create_info.renderPass = version.render_pass;
  5912. Vector<VkImageView> attachments;
  5913. for (int i = 0; i < p_framebuffer->texture_ids.size(); i++) {
  5914. Texture *texture = texture_owner.get_or_null(p_framebuffer->texture_ids[i]);
  5915. if (texture) {
  5916. attachments.push_back(texture->view);
  5917. ERR_FAIL_COND_V(texture->width != p_framebuffer->size.width, ERR_BUG);
  5918. ERR_FAIL_COND_V(texture->height != p_framebuffer->size.height, ERR_BUG);
  5919. }
  5920. }
  5921. framebuffer_create_info.attachmentCount = attachments.size();
  5922. framebuffer_create_info.pAttachments = attachments.ptr();
  5923. framebuffer_create_info.width = p_framebuffer->size.width;
  5924. framebuffer_create_info.height = p_framebuffer->size.height;
  5925. framebuffer_create_info.layers = 1;
  5926. VkResult err = vkCreateFramebuffer(device, &framebuffer_create_info, nullptr, &version.framebuffer);
  5927. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vkCreateFramebuffer failed with error " + itos(err) + ".");
  5928. version.subpass_count = framebuffer_formats[p_framebuffer->format_id].E->key().passes.size();
  5929. p_framebuffer->framebuffers.insert(vk, version);
  5930. }
  5931. const Framebuffer::Version &version = p_framebuffer->framebuffers[vk];
  5932. *r_framebuffer = version.framebuffer;
  5933. *r_render_pass = version.render_pass;
  5934. *r_subpass_count = version.subpass_count;
  5935. return OK;
  5936. }
  5937. 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) {
  5938. VkRenderPassBeginInfo render_pass_begin;
  5939. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  5940. render_pass_begin.pNext = nullptr;
  5941. render_pass_begin.renderPass = render_pass;
  5942. render_pass_begin.framebuffer = vkframebuffer;
  5943. /*
  5944. * Given how API works, it makes sense to always fully operate on the whole framebuffer.
  5945. * This allows better continue operations for operations like shadowmapping.
  5946. render_pass_begin.renderArea.extent.width = viewport_size.width;
  5947. render_pass_begin.renderArea.extent.height = viewport_size.height;
  5948. render_pass_begin.renderArea.offset.x = viewport_offset.x;
  5949. render_pass_begin.renderArea.offset.y = viewport_offset.y;
  5950. */
  5951. render_pass_begin.renderArea.extent.width = framebuffer->size.width;
  5952. render_pass_begin.renderArea.extent.height = framebuffer->size.height;
  5953. render_pass_begin.renderArea.offset.x = 0;
  5954. render_pass_begin.renderArea.offset.y = 0;
  5955. Vector<VkClearValue> clear_values;
  5956. clear_values.resize(framebuffer->texture_ids.size());
  5957. int clear_values_count = 0;
  5958. {
  5959. int color_index = 0;
  5960. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  5961. VkClearValue clear_value;
  5962. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  5963. if (!texture) {
  5964. color_index++;
  5965. continue;
  5966. }
  5967. if (color_index < p_clear_colors.size() && texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  5968. ERR_FAIL_INDEX_V(color_index, p_clear_colors.size(), ERR_BUG); //a bug
  5969. Color clear_color = p_clear_colors[color_index];
  5970. clear_value.color.float32[0] = clear_color.r;
  5971. clear_value.color.float32[1] = clear_color.g;
  5972. clear_value.color.float32[2] = clear_color.b;
  5973. clear_value.color.float32[3] = clear_color.a;
  5974. color_index++;
  5975. } else if (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  5976. clear_value.depthStencil.depth = p_clear_depth;
  5977. clear_value.depthStencil.stencil = p_clear_stencil;
  5978. } else {
  5979. clear_value.color.float32[0] = 0;
  5980. clear_value.color.float32[1] = 0;
  5981. clear_value.color.float32[2] = 0;
  5982. clear_value.color.float32[3] = 0;
  5983. }
  5984. clear_values.write[clear_values_count++] = clear_value;
  5985. }
  5986. }
  5987. render_pass_begin.clearValueCount = clear_values_count;
  5988. render_pass_begin.pClearValues = clear_values.ptr();
  5989. for (int i = 0; i < p_storage_textures.size(); i++) {
  5990. Texture *texture = texture_owner.get_or_null(p_storage_textures[i]);
  5991. if (!texture) {
  5992. continue;
  5993. }
  5994. 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.");
  5995. if (texture->usage_flags & TEXTURE_USAGE_SAMPLING_BIT) {
  5996. //must change layout to general
  5997. VkImageMemoryBarrier image_memory_barrier;
  5998. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  5999. image_memory_barrier.pNext = nullptr;
  6000. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6001. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6002. image_memory_barrier.oldLayout = texture->layout;
  6003. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  6004. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6005. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6006. image_memory_barrier.image = texture->image;
  6007. image_memory_barrier.subresourceRange.aspectMask = texture->read_aspect_mask;
  6008. image_memory_barrier.subresourceRange.baseMipLevel = texture->base_mipmap;
  6009. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  6010. image_memory_barrier.subresourceRange.baseArrayLayer = texture->base_layer;
  6011. image_memory_barrier.subresourceRange.layerCount = texture->layers;
  6012. 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);
  6013. texture->layout = VK_IMAGE_LAYOUT_GENERAL;
  6014. draw_list_storage_textures.push_back(p_storage_textures[i]);
  6015. }
  6016. }
  6017. vkCmdBeginRenderPass(command_buffer, &render_pass_begin, subpass_contents);
  6018. //mark textures as bound
  6019. draw_list_bound_textures.clear();
  6020. draw_list_unbind_color_textures = p_final_color_action != FINAL_ACTION_CONTINUE;
  6021. draw_list_unbind_depth_textures = p_final_depth_action != FINAL_ACTION_CONTINUE;
  6022. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  6023. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  6024. if (!texture) {
  6025. continue;
  6026. }
  6027. texture->bound = true;
  6028. draw_list_bound_textures.push_back(framebuffer->texture_ids[i]);
  6029. }
  6030. return OK;
  6031. }
  6032. 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) {
  6033. ERR_FAIL_COND_MSG(p_clear_color && p_clear_colors.size() != framebuffer->texture_ids.size(), "Clear color values supplied (" + itos(p_clear_colors.size()) + ") differ from the amount required for framebuffer color attachments (" + itos(framebuffer->texture_ids.size()) + ").");
  6034. Vector<VkClearAttachment> clear_attachments;
  6035. int color_index = 0;
  6036. int texture_index = 0;
  6037. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  6038. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  6039. if (!texture) {
  6040. texture_index++;
  6041. continue;
  6042. }
  6043. VkClearAttachment clear_at = {};
  6044. if (p_clear_color && texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT) {
  6045. Color clear_color = p_clear_colors[texture_index++];
  6046. clear_at.clearValue.color.float32[0] = clear_color.r;
  6047. clear_at.clearValue.color.float32[1] = clear_color.g;
  6048. clear_at.clearValue.color.float32[2] = clear_color.b;
  6049. clear_at.clearValue.color.float32[3] = clear_color.a;
  6050. clear_at.colorAttachment = color_index++;
  6051. clear_at.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  6052. } else if (p_clear_depth && texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
  6053. clear_at.clearValue.depthStencil.depth = p_depth;
  6054. clear_at.clearValue.depthStencil.stencil = p_stencil;
  6055. clear_at.colorAttachment = 0;
  6056. clear_at.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
  6057. if (format_has_stencil(texture->format)) {
  6058. clear_at.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  6059. }
  6060. } else {
  6061. ERR_CONTINUE(true);
  6062. }
  6063. clear_attachments.push_back(clear_at);
  6064. }
  6065. VkClearRect cr;
  6066. cr.baseArrayLayer = 0;
  6067. cr.layerCount = 1;
  6068. cr.rect.offset.x = viewport_offset.x;
  6069. cr.rect.offset.y = viewport_offset.y;
  6070. cr.rect.extent.width = viewport_size.width;
  6071. cr.rect.extent.height = viewport_size.height;
  6072. vkCmdClearAttachments(draw_list->command_buffer, clear_attachments.size(), clear_attachments.ptr(), 1, &cr);
  6073. }
  6074. 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) {
  6075. _THREAD_SAFE_METHOD_
  6076. ERR_FAIL_COND_V_MSG(draw_list != nullptr, INVALID_ID, "Only one draw list can be active at the same time.");
  6077. 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.");
  6078. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  6079. ERR_FAIL_COND_V(!framebuffer, INVALID_ID);
  6080. Point2i viewport_offset;
  6081. Point2i viewport_size = framebuffer->size;
  6082. bool needs_clear_color = false;
  6083. bool needs_clear_depth = false;
  6084. if (p_region != Rect2() && p_region != Rect2(Vector2(), viewport_size)) { //check custom region
  6085. Rect2i viewport(viewport_offset, viewport_size);
  6086. Rect2i regioni = p_region;
  6087. if (!(regioni.position.x >= viewport.position.x) && (regioni.position.y >= viewport.position.y) &&
  6088. ((regioni.position.x + regioni.size.x) <= (viewport.position.x + viewport.size.x)) &&
  6089. ((regioni.position.y + regioni.size.y) <= (viewport.position.y + viewport.size.y))) {
  6090. ERR_FAIL_V_MSG(INVALID_ID, "When supplying a custom region, it must be contained within the framebuffer rectangle");
  6091. }
  6092. viewport_offset = regioni.position;
  6093. viewport_size = regioni.size;
  6094. if (p_initial_color_action == INITIAL_ACTION_CLEAR_REGION_CONTINUE) {
  6095. needs_clear_color = true;
  6096. p_initial_color_action = INITIAL_ACTION_CONTINUE;
  6097. }
  6098. if (p_initial_depth_action == INITIAL_ACTION_CLEAR_REGION_CONTINUE) {
  6099. needs_clear_depth = true;
  6100. p_initial_depth_action = INITIAL_ACTION_CONTINUE;
  6101. }
  6102. if (p_initial_color_action == INITIAL_ACTION_CLEAR_REGION) {
  6103. needs_clear_color = true;
  6104. p_initial_color_action = INITIAL_ACTION_KEEP;
  6105. }
  6106. if (p_initial_depth_action == INITIAL_ACTION_CLEAR_REGION) {
  6107. needs_clear_depth = true;
  6108. p_initial_depth_action = INITIAL_ACTION_KEEP;
  6109. }
  6110. }
  6111. if (p_initial_color_action == INITIAL_ACTION_CLEAR) { //check clear values
  6112. int color_count = 0;
  6113. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  6114. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  6115. if (!texture || !(texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  6116. color_count++;
  6117. }
  6118. }
  6119. ERR_FAIL_COND_V_MSG(p_clear_color_values.size() != color_count, INVALID_ID, "Clear color values supplied (" + itos(p_clear_color_values.size()) + ") differ from the amount required for framebuffer color attachments (" + itos(color_count) + ").");
  6120. }
  6121. VkFramebuffer vkframebuffer;
  6122. VkRenderPass render_pass;
  6123. 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);
  6124. ERR_FAIL_COND_V(err != OK, INVALID_ID);
  6125. VkCommandBuffer command_buffer = frames[frame].draw_command_buffer;
  6126. 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);
  6127. if (err != OK) {
  6128. return INVALID_ID;
  6129. }
  6130. draw_list_render_pass = render_pass;
  6131. draw_list_vkframebuffer = vkframebuffer;
  6132. _draw_list_allocate(Rect2i(viewport_offset, viewport_size), 0, 0);
  6133. #ifdef DEBUG_ENABLED
  6134. draw_list_framebuffer_format = framebuffer->format_id;
  6135. #endif
  6136. draw_list_current_subpass = 0;
  6137. if (needs_clear_color || needs_clear_depth) {
  6138. _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);
  6139. }
  6140. VkViewport viewport;
  6141. viewport.x = viewport_offset.x;
  6142. viewport.y = viewport_offset.y;
  6143. viewport.width = viewport_size.width;
  6144. viewport.height = viewport_size.height;
  6145. viewport.minDepth = 0;
  6146. viewport.maxDepth = 1.0;
  6147. vkCmdSetViewport(command_buffer, 0, 1, &viewport);
  6148. VkRect2D scissor;
  6149. scissor.offset.x = viewport_offset.x;
  6150. scissor.offset.y = viewport_offset.y;
  6151. scissor.extent.width = viewport_size.width;
  6152. scissor.extent.height = viewport_size.height;
  6153. vkCmdSetScissor(command_buffer, 0, 1, &scissor);
  6154. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  6155. }
  6156. 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) {
  6157. _THREAD_SAFE_METHOD_
  6158. ERR_FAIL_COND_V_MSG(draw_list != nullptr, ERR_BUSY, "Only one draw list can be active at the same time.");
  6159. ERR_FAIL_COND_V_MSG(compute_list != nullptr && !compute_list->state.allow_draw_overlap, ERR_BUSY, "Only one draw/compute list can be active at the same time.");
  6160. ERR_FAIL_COND_V(p_splits < 1, ERR_INVALID_DECLARATION);
  6161. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_framebuffer);
  6162. ERR_FAIL_COND_V(!framebuffer, ERR_INVALID_DECLARATION);
  6163. Point2i viewport_offset;
  6164. Point2i viewport_size = framebuffer->size;
  6165. bool needs_clear_color = false;
  6166. bool needs_clear_depth = false;
  6167. if (p_region != Rect2() && p_region != Rect2(Vector2(), viewport_size)) { //check custom region
  6168. Rect2i viewport(viewport_offset, viewport_size);
  6169. Rect2i regioni = p_region;
  6170. if (!(regioni.position.x >= viewport.position.x) && (regioni.position.y >= viewport.position.y) &&
  6171. ((regioni.position.x + regioni.size.x) <= (viewport.position.x + viewport.size.x)) &&
  6172. ((regioni.position.y + regioni.size.y) <= (viewport.position.y + viewport.size.y))) {
  6173. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "When supplying a custom region, it must be contained within the framebuffer rectangle");
  6174. }
  6175. viewport_offset = regioni.position;
  6176. viewport_size = regioni.size;
  6177. if (p_initial_color_action == INITIAL_ACTION_CLEAR_REGION) {
  6178. needs_clear_color = true;
  6179. p_initial_color_action = INITIAL_ACTION_KEEP;
  6180. }
  6181. if (p_initial_depth_action == INITIAL_ACTION_CLEAR_REGION) {
  6182. needs_clear_depth = true;
  6183. p_initial_depth_action = INITIAL_ACTION_KEEP;
  6184. }
  6185. }
  6186. if (p_initial_color_action == INITIAL_ACTION_CLEAR) { //check clear values
  6187. int color_count = 0;
  6188. for (int i = 0; i < framebuffer->texture_ids.size(); i++) {
  6189. Texture *texture = texture_owner.get_or_null(framebuffer->texture_ids[i]);
  6190. if (!texture || !(texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  6191. color_count++;
  6192. }
  6193. }
  6194. ERR_FAIL_COND_V_MSG(p_clear_color_values.size() != color_count, ERR_INVALID_PARAMETER,
  6195. "Clear color values supplied (" + itos(p_clear_color_values.size()) + ") differ from the amount required for framebuffer (" + itos(color_count) + ").");
  6196. }
  6197. VkFramebuffer vkframebuffer;
  6198. VkRenderPass render_pass;
  6199. 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);
  6200. ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
  6201. VkCommandBuffer frame_command_buffer = frames[frame].draw_command_buffer;
  6202. 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);
  6203. if (err != OK) {
  6204. return ERR_CANT_CREATE;
  6205. }
  6206. draw_list_current_subpass = 0;
  6207. #ifdef DEBUG_ENABLED
  6208. draw_list_framebuffer_format = framebuffer->format_id;
  6209. #endif
  6210. draw_list_render_pass = render_pass;
  6211. draw_list_vkframebuffer = vkframebuffer;
  6212. err = _draw_list_allocate(Rect2i(viewport_offset, viewport_size), p_splits, 0);
  6213. if (err != OK) {
  6214. return err;
  6215. }
  6216. if (needs_clear_color || needs_clear_depth) {
  6217. _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);
  6218. }
  6219. for (uint32_t i = 0; i < p_splits; i++) {
  6220. VkViewport viewport;
  6221. viewport.x = viewport_offset.x;
  6222. viewport.y = viewport_offset.y;
  6223. viewport.width = viewport_size.width;
  6224. viewport.height = viewport_size.height;
  6225. viewport.minDepth = 0;
  6226. viewport.maxDepth = 1.0;
  6227. vkCmdSetViewport(draw_list[i].command_buffer, 0, 1, &viewport);
  6228. VkRect2D scissor;
  6229. scissor.offset.x = viewport_offset.x;
  6230. scissor.offset.y = viewport_offset.y;
  6231. scissor.extent.width = viewport_size.width;
  6232. scissor.extent.height = viewport_size.height;
  6233. vkCmdSetScissor(draw_list[i].command_buffer, 0, 1, &scissor);
  6234. r_split_ids[i] = (int64_t(ID_TYPE_SPLIT_DRAW_LIST) << ID_BASE_SHIFT) + i;
  6235. }
  6236. return OK;
  6237. }
  6238. RenderingDeviceVulkan::DrawList *RenderingDeviceVulkan::_get_draw_list_ptr(DrawListID p_id) {
  6239. if (p_id < 0) {
  6240. return nullptr;
  6241. }
  6242. if (!draw_list) {
  6243. return nullptr;
  6244. } else if (p_id == (int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT)) {
  6245. if (draw_list_split) {
  6246. return nullptr;
  6247. }
  6248. return draw_list;
  6249. } else if (p_id >> DrawListID(ID_BASE_SHIFT) == ID_TYPE_SPLIT_DRAW_LIST) {
  6250. if (!draw_list_split) {
  6251. return nullptr;
  6252. }
  6253. uint64_t index = p_id & ((DrawListID(1) << DrawListID(ID_BASE_SHIFT)) - 1); //mask
  6254. if (index >= draw_list_count) {
  6255. return nullptr;
  6256. }
  6257. return &draw_list[index];
  6258. } else {
  6259. return nullptr;
  6260. }
  6261. }
  6262. void RenderingDeviceVulkan::draw_list_bind_render_pipeline(DrawListID p_list, RID p_render_pipeline) {
  6263. DrawList *dl = _get_draw_list_ptr(p_list);
  6264. ERR_FAIL_COND(!dl);
  6265. #ifdef DEBUG_ENABLED
  6266. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6267. #endif
  6268. const RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_render_pipeline);
  6269. ERR_FAIL_COND(!pipeline);
  6270. #ifdef DEBUG_ENABLED
  6271. ERR_FAIL_COND(pipeline->validation.framebuffer_format != draw_list_framebuffer_format && pipeline->validation.render_pass != draw_list_current_subpass);
  6272. #endif
  6273. if (p_render_pipeline == dl->state.pipeline) {
  6274. return; //redundant state, return.
  6275. }
  6276. dl->state.pipeline = p_render_pipeline;
  6277. dl->state.pipeline_layout = pipeline->pipeline_layout;
  6278. vkCmdBindPipeline(dl->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline);
  6279. if (dl->state.pipeline_shader != pipeline->shader) {
  6280. // shader changed, so descriptor sets may become incompatible.
  6281. //go through ALL sets, and unbind them (and all those above) if the format is different
  6282. uint32_t pcount = pipeline->set_formats.size(); //formats count in this pipeline
  6283. dl->state.set_count = MAX(dl->state.set_count, pcount);
  6284. const uint32_t *pformats = pipeline->set_formats.ptr(); //pipeline set formats
  6285. bool sets_valid = true; //once invalid, all above become invalid
  6286. for (uint32_t i = 0; i < pcount; i++) {
  6287. //if a part of the format is different, invalidate it (and the rest)
  6288. if (!sets_valid || dl->state.sets[i].pipeline_expected_format != pformats[i]) {
  6289. dl->state.sets[i].bound = false;
  6290. dl->state.sets[i].pipeline_expected_format = pformats[i];
  6291. sets_valid = false;
  6292. }
  6293. }
  6294. for (uint32_t i = pcount; i < dl->state.set_count; i++) {
  6295. //unbind the ones above (not used) if exist
  6296. dl->state.sets[i].bound = false;
  6297. }
  6298. dl->state.set_count = pcount; //update set count
  6299. if (pipeline->push_constant_size) {
  6300. dl->state.pipeline_push_constant_stages = pipeline->push_constant_stages;
  6301. #ifdef DEBUG_ENABLED
  6302. dl->validation.pipeline_push_constant_supplied = false;
  6303. #endif
  6304. }
  6305. dl->state.pipeline_shader = pipeline->shader;
  6306. }
  6307. #ifdef DEBUG_ENABLED
  6308. //update render pass pipeline info
  6309. dl->validation.pipeline_active = true;
  6310. dl->validation.pipeline_dynamic_state = pipeline->validation.dynamic_state;
  6311. dl->validation.pipeline_vertex_format = pipeline->validation.vertex_format;
  6312. dl->validation.pipeline_uses_restart_indices = pipeline->validation.uses_restart_indices;
  6313. dl->validation.pipeline_primitive_divisor = pipeline->validation.primitive_divisor;
  6314. dl->validation.pipeline_primitive_minimum = pipeline->validation.primitive_minimum;
  6315. dl->validation.pipeline_push_constant_size = pipeline->push_constant_size;
  6316. #endif
  6317. }
  6318. void RenderingDeviceVulkan::draw_list_bind_uniform_set(DrawListID p_list, RID p_uniform_set, uint32_t p_index) {
  6319. #ifdef DEBUG_ENABLED
  6320. ERR_FAIL_COND_MSG(p_index >= limits.maxBoundDescriptorSets || p_index >= MAX_UNIFORM_SETS,
  6321. "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(limits.maxBoundDescriptorSets) + ").");
  6322. #endif
  6323. DrawList *dl = _get_draw_list_ptr(p_list);
  6324. ERR_FAIL_COND(!dl);
  6325. #ifdef DEBUG_ENABLED
  6326. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6327. #endif
  6328. const UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set);
  6329. ERR_FAIL_COND(!uniform_set);
  6330. if (p_index > dl->state.set_count) {
  6331. dl->state.set_count = p_index;
  6332. }
  6333. dl->state.sets[p_index].descriptor_set = uniform_set->descriptor_set; //update set pointer
  6334. dl->state.sets[p_index].bound = false; //needs rebind
  6335. dl->state.sets[p_index].uniform_set_format = uniform_set->format;
  6336. dl->state.sets[p_index].uniform_set = p_uniform_set;
  6337. uint32_t mst_count = uniform_set->mutable_storage_textures.size();
  6338. if (mst_count) {
  6339. Texture **mst_textures = const_cast<UniformSet *>(uniform_set)->mutable_storage_textures.ptrw();
  6340. for (uint32_t i = 0; i < mst_count; i++) {
  6341. if (mst_textures[i]->used_in_frame != frames_drawn) {
  6342. mst_textures[i]->used_in_frame = frames_drawn;
  6343. mst_textures[i]->used_in_transfer = false;
  6344. mst_textures[i]->used_in_compute = false;
  6345. }
  6346. mst_textures[i]->used_in_raster = true;
  6347. }
  6348. }
  6349. #ifdef DEBUG_ENABLED
  6350. { //validate that textures bound are not attached as framebuffer bindings
  6351. uint32_t attachable_count = uniform_set->attachable_textures.size();
  6352. const UniformSet::AttachableTexture *attachable_ptr = uniform_set->attachable_textures.ptr();
  6353. uint32_t bound_count = draw_list_bound_textures.size();
  6354. const RID *bound_ptr = draw_list_bound_textures.ptr();
  6355. for (uint32_t i = 0; i < attachable_count; i++) {
  6356. for (uint32_t j = 0; j < bound_count; j++) {
  6357. ERR_FAIL_COND_MSG(attachable_ptr[i].texture == bound_ptr[j],
  6358. "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.");
  6359. }
  6360. }
  6361. }
  6362. #endif
  6363. }
  6364. void RenderingDeviceVulkan::draw_list_bind_vertex_array(DrawListID p_list, RID p_vertex_array) {
  6365. DrawList *dl = _get_draw_list_ptr(p_list);
  6366. ERR_FAIL_COND(!dl);
  6367. #ifdef DEBUG_ENABLED
  6368. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6369. #endif
  6370. const VertexArray *vertex_array = vertex_array_owner.get_or_null(p_vertex_array);
  6371. ERR_FAIL_COND(!vertex_array);
  6372. if (dl->state.vertex_array == p_vertex_array) {
  6373. return; //already set
  6374. }
  6375. dl->state.vertex_array = p_vertex_array;
  6376. #ifdef DEBUG_ENABLED
  6377. dl->validation.vertex_format = vertex_array->description;
  6378. dl->validation.vertex_max_instances_allowed = vertex_array->max_instances_allowed;
  6379. #endif
  6380. dl->validation.vertex_array_size = vertex_array->vertex_count;
  6381. vkCmdBindVertexBuffers(dl->command_buffer, 0, vertex_array->buffers.size(), vertex_array->buffers.ptr(), vertex_array->offsets.ptr());
  6382. }
  6383. void RenderingDeviceVulkan::draw_list_bind_index_array(DrawListID p_list, RID p_index_array) {
  6384. DrawList *dl = _get_draw_list_ptr(p_list);
  6385. ERR_FAIL_COND(!dl);
  6386. #ifdef DEBUG_ENABLED
  6387. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6388. #endif
  6389. const IndexArray *index_array = index_array_owner.get_or_null(p_index_array);
  6390. ERR_FAIL_COND(!index_array);
  6391. if (dl->state.index_array == p_index_array) {
  6392. return; //already set
  6393. }
  6394. dl->state.index_array = p_index_array;
  6395. #ifdef DEBUG_ENABLED
  6396. dl->validation.index_array_max_index = index_array->max_index;
  6397. #endif
  6398. dl->validation.index_array_size = index_array->indices;
  6399. dl->validation.index_array_offset = index_array->offset;
  6400. vkCmdBindIndexBuffer(dl->command_buffer, index_array->buffer, index_array->offset, index_array->index_type);
  6401. }
  6402. void RenderingDeviceVulkan::draw_list_set_line_width(DrawListID p_list, float p_width) {
  6403. DrawList *dl = _get_draw_list_ptr(p_list);
  6404. ERR_FAIL_COND(!dl);
  6405. #ifdef DEBUG_ENABLED
  6406. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6407. #endif
  6408. vkCmdSetLineWidth(dl->command_buffer, p_width);
  6409. }
  6410. void RenderingDeviceVulkan::draw_list_set_push_constant(DrawListID p_list, const void *p_data, uint32_t p_data_size) {
  6411. DrawList *dl = _get_draw_list_ptr(p_list);
  6412. ERR_FAIL_COND(!dl);
  6413. #ifdef DEBUG_ENABLED
  6414. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6415. #endif
  6416. #ifdef DEBUG_ENABLED
  6417. ERR_FAIL_COND_MSG(p_data_size != dl->validation.pipeline_push_constant_size,
  6418. "This render pipeline requires (" + itos(dl->validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");
  6419. #endif
  6420. vkCmdPushConstants(dl->command_buffer, dl->state.pipeline_layout, dl->state.pipeline_push_constant_stages, 0, p_data_size, p_data);
  6421. #ifdef DEBUG_ENABLED
  6422. dl->validation.pipeline_push_constant_supplied = true;
  6423. #endif
  6424. }
  6425. void RenderingDeviceVulkan::draw_list_draw(DrawListID p_list, bool p_use_indices, uint32_t p_instances, uint32_t p_procedural_vertices) {
  6426. DrawList *dl = _get_draw_list_ptr(p_list);
  6427. ERR_FAIL_COND(!dl);
  6428. #ifdef DEBUG_ENABLED
  6429. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6430. #endif
  6431. #ifdef DEBUG_ENABLED
  6432. ERR_FAIL_COND_MSG(!dl->validation.pipeline_active,
  6433. "No render pipeline was set before attempting to draw.");
  6434. if (dl->validation.pipeline_vertex_format != INVALID_ID) {
  6435. //pipeline uses vertices, validate format
  6436. ERR_FAIL_COND_MSG(dl->validation.vertex_format == INVALID_ID,
  6437. "No vertex array was bound, and render pipeline expects vertices.");
  6438. //make sure format is right
  6439. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format != dl->validation.vertex_format,
  6440. "The vertex format used to create the pipeline does not match the vertex format bound.");
  6441. //make sure number of instances is valid
  6442. ERR_FAIL_COND_MSG(p_instances > dl->validation.vertex_max_instances_allowed,
  6443. "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) + ").");
  6444. }
  6445. if (dl->validation.pipeline_push_constant_size > 0) {
  6446. //using push constants, check that they were supplied
  6447. ERR_FAIL_COND_MSG(!dl->validation.pipeline_push_constant_supplied,
  6448. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  6449. }
  6450. #endif
  6451. //Bind descriptor sets
  6452. for (uint32_t i = 0; i < dl->state.set_count; i++) {
  6453. if (dl->state.sets[i].pipeline_expected_format == 0) {
  6454. continue; //nothing expected by this pipeline
  6455. }
  6456. #ifdef DEBUG_ENABLED
  6457. if (dl->state.sets[i].pipeline_expected_format != dl->state.sets[i].uniform_set_format) {
  6458. if (dl->state.sets[i].uniform_set_format == 0) {
  6459. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  6460. } else if (uniform_set_owner.owns(dl->state.sets[i].uniform_set)) {
  6461. UniformSet *us = uniform_set_owner.get_or_null(dl->state.sets[i].uniform_set);
  6462. 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));
  6463. } else {
  6464. 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));
  6465. }
  6466. }
  6467. #endif
  6468. if (!dl->state.sets[i].bound) {
  6469. //All good, see if this requires re-binding
  6470. vkCmdBindDescriptorSets(dl->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, dl->state.pipeline_layout, i, 1, &dl->state.sets[i].descriptor_set, 0, nullptr);
  6471. dl->state.sets[i].bound = true;
  6472. }
  6473. }
  6474. if (p_use_indices) {
  6475. #ifdef DEBUG_ENABLED
  6476. ERR_FAIL_COND_MSG(p_procedural_vertices > 0,
  6477. "Procedural vertices can't be used together with indices.");
  6478. ERR_FAIL_COND_MSG(!dl->validation.index_array_size,
  6479. "Draw command requested indices, but no index buffer was set.");
  6480. if (dl->validation.pipeline_vertex_format != INVALID_ID) {
  6481. //uses vertices, do some vertex validations
  6482. ERR_FAIL_COND_MSG(dl->validation.vertex_array_size < dl->validation.index_array_max_index,
  6483. "Index array references (max index: " + itos(dl->validation.index_array_max_index) + ") indices beyond the vertex array size (" + itos(dl->validation.vertex_array_size) + ").");
  6484. }
  6485. ERR_FAIL_COND_MSG(dl->validation.pipeline_uses_restart_indices != dl->validation.index_buffer_uses_restart_indices,
  6486. "The usage of restart indices in index buffer does not match the render primitive in the pipeline.");
  6487. #endif
  6488. uint32_t to_draw = dl->validation.index_array_size;
  6489. #ifdef DEBUG_ENABLED
  6490. ERR_FAIL_COND_MSG(to_draw < dl->validation.pipeline_primitive_minimum,
  6491. "Too few indices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(dl->validation.pipeline_primitive_minimum) + ").");
  6492. ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0,
  6493. "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) + ").");
  6494. #endif
  6495. vkCmdDrawIndexed(dl->command_buffer, to_draw, p_instances, dl->validation.index_array_offset, 0, 0);
  6496. } else {
  6497. uint32_t to_draw;
  6498. if (p_procedural_vertices > 0) {
  6499. #ifdef DEBUG_ENABLED
  6500. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format != INVALID_ID,
  6501. "Procedural vertices requested, but pipeline expects a vertex array.");
  6502. #endif
  6503. to_draw = p_procedural_vertices;
  6504. } else {
  6505. #ifdef DEBUG_ENABLED
  6506. ERR_FAIL_COND_MSG(dl->validation.pipeline_vertex_format == INVALID_ID,
  6507. "Draw command lacks indices, but pipeline format does not use vertices.");
  6508. #endif
  6509. to_draw = dl->validation.vertex_array_size;
  6510. }
  6511. #ifdef DEBUG_ENABLED
  6512. ERR_FAIL_COND_MSG(to_draw < dl->validation.pipeline_primitive_minimum,
  6513. "Too few vertices (" + itos(to_draw) + ") for the render primitive set in the render pipeline (" + itos(dl->validation.pipeline_primitive_minimum) + ").");
  6514. ERR_FAIL_COND_MSG((to_draw % dl->validation.pipeline_primitive_divisor) != 0,
  6515. "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) + ").");
  6516. #endif
  6517. vkCmdDraw(dl->command_buffer, to_draw, p_instances, 0, 0);
  6518. }
  6519. }
  6520. void RenderingDeviceVulkan::draw_list_enable_scissor(DrawListID p_list, const Rect2 &p_rect) {
  6521. DrawList *dl = _get_draw_list_ptr(p_list);
  6522. ERR_FAIL_COND(!dl);
  6523. #ifdef DEBUG_ENABLED
  6524. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6525. #endif
  6526. Rect2i rect = p_rect;
  6527. rect.position += dl->viewport.position;
  6528. rect = dl->viewport.intersection(rect);
  6529. if (rect.get_area() == 0) {
  6530. return;
  6531. }
  6532. VkRect2D scissor;
  6533. scissor.offset.x = rect.position.x;
  6534. scissor.offset.y = rect.position.y;
  6535. scissor.extent.width = rect.size.width;
  6536. scissor.extent.height = rect.size.height;
  6537. vkCmdSetScissor(dl->command_buffer, 0, 1, &scissor);
  6538. }
  6539. void RenderingDeviceVulkan::draw_list_disable_scissor(DrawListID p_list) {
  6540. DrawList *dl = _get_draw_list_ptr(p_list);
  6541. ERR_FAIL_COND(!dl);
  6542. #ifdef DEBUG_ENABLED
  6543. ERR_FAIL_COND_MSG(!dl->validation.active, "Submitted Draw Lists can no longer be modified.");
  6544. #endif
  6545. VkRect2D scissor;
  6546. scissor.offset.x = dl->viewport.position.x;
  6547. scissor.offset.y = dl->viewport.position.y;
  6548. scissor.extent.width = dl->viewport.size.width;
  6549. scissor.extent.height = dl->viewport.size.height;
  6550. vkCmdSetScissor(dl->command_buffer, 0, 1, &scissor);
  6551. }
  6552. uint32_t RenderingDeviceVulkan::draw_list_get_current_pass() {
  6553. return draw_list_current_subpass;
  6554. }
  6555. RenderingDevice::DrawListID RenderingDeviceVulkan::draw_list_switch_to_next_pass() {
  6556. ERR_FAIL_COND_V(draw_list == nullptr, INVALID_ID);
  6557. ERR_FAIL_COND_V(draw_list_current_subpass >= draw_list_subpass_count - 1, INVALID_FORMAT_ID);
  6558. draw_list_current_subpass++;
  6559. Rect2i viewport;
  6560. _draw_list_free(&viewport);
  6561. vkCmdNextSubpass(frames[frame].draw_command_buffer, VK_SUBPASS_CONTENTS_INLINE);
  6562. _draw_list_allocate(viewport, 0, draw_list_current_subpass);
  6563. return int64_t(ID_TYPE_DRAW_LIST) << ID_BASE_SHIFT;
  6564. }
  6565. Error RenderingDeviceVulkan::draw_list_switch_to_next_pass_split(uint32_t p_splits, DrawListID *r_split_ids) {
  6566. ERR_FAIL_COND_V(draw_list == nullptr, ERR_INVALID_PARAMETER);
  6567. ERR_FAIL_COND_V(draw_list_current_subpass >= draw_list_subpass_count - 1, ERR_INVALID_PARAMETER);
  6568. draw_list_current_subpass++;
  6569. Rect2i viewport;
  6570. _draw_list_free(&viewport);
  6571. vkCmdNextSubpass(frames[frame].draw_command_buffer, VK_SUBPASS_CONTENTS_INLINE);
  6572. _draw_list_allocate(viewport, p_splits, draw_list_current_subpass);
  6573. for (uint32_t i = 0; i < p_splits; i++) {
  6574. r_split_ids[i] = (int64_t(ID_TYPE_SPLIT_DRAW_LIST) << ID_BASE_SHIFT) + i;
  6575. }
  6576. return OK;
  6577. }
  6578. Error RenderingDeviceVulkan::_draw_list_allocate(const Rect2i &p_viewport, uint32_t p_splits, uint32_t p_subpass) {
  6579. // Lock while draw_list is active
  6580. _THREAD_SAFE_LOCK_
  6581. if (p_splits == 0) {
  6582. draw_list = memnew(DrawList);
  6583. draw_list->command_buffer = frames[frame].draw_command_buffer;
  6584. draw_list->viewport = p_viewport;
  6585. draw_list_count = 0;
  6586. draw_list_split = false;
  6587. } else {
  6588. if (p_splits > (uint32_t)split_draw_list_allocators.size()) {
  6589. uint32_t from = split_draw_list_allocators.size();
  6590. split_draw_list_allocators.resize(p_splits);
  6591. for (uint32_t i = from; i < p_splits; i++) {
  6592. VkCommandPoolCreateInfo cmd_pool_info;
  6593. cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  6594. cmd_pool_info.pNext = nullptr;
  6595. cmd_pool_info.queueFamilyIndex = context->get_graphics_queue_family_index();
  6596. cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  6597. VkResult res = vkCreateCommandPool(device, &cmd_pool_info, nullptr, &split_draw_list_allocators.write[i].command_pool);
  6598. ERR_FAIL_COND_V_MSG(res, ERR_CANT_CREATE, "vkCreateCommandPool failed with error " + itos(res) + ".");
  6599. for (int j = 0; j < frame_count; j++) {
  6600. VkCommandBuffer command_buffer;
  6601. VkCommandBufferAllocateInfo cmdbuf;
  6602. //no command buffer exists, create it.
  6603. cmdbuf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  6604. cmdbuf.pNext = nullptr;
  6605. cmdbuf.commandPool = split_draw_list_allocators[i].command_pool;
  6606. cmdbuf.level = VK_COMMAND_BUFFER_LEVEL_SECONDARY;
  6607. cmdbuf.commandBufferCount = 1;
  6608. VkResult err = vkAllocateCommandBuffers(device, &cmdbuf, &command_buffer);
  6609. ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  6610. split_draw_list_allocators.write[i].command_buffers.push_back(command_buffer);
  6611. }
  6612. }
  6613. }
  6614. draw_list = memnew_arr(DrawList, p_splits);
  6615. draw_list_count = p_splits;
  6616. draw_list_split = true;
  6617. for (uint32_t i = 0; i < p_splits; i++) {
  6618. //take a command buffer and initialize it
  6619. VkCommandBuffer command_buffer = split_draw_list_allocators[i].command_buffers[frame];
  6620. VkCommandBufferInheritanceInfo inheritance_info;
  6621. inheritance_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO;
  6622. inheritance_info.pNext = nullptr;
  6623. inheritance_info.renderPass = draw_list_render_pass;
  6624. inheritance_info.subpass = p_subpass;
  6625. inheritance_info.framebuffer = draw_list_vkframebuffer;
  6626. inheritance_info.occlusionQueryEnable = false;
  6627. inheritance_info.queryFlags = 0; //?
  6628. inheritance_info.pipelineStatistics = 0;
  6629. VkCommandBufferBeginInfo cmdbuf_begin;
  6630. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  6631. cmdbuf_begin.pNext = nullptr;
  6632. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT;
  6633. cmdbuf_begin.pInheritanceInfo = &inheritance_info;
  6634. VkResult res = vkResetCommandBuffer(command_buffer, 0);
  6635. if (res) {
  6636. memdelete_arr(draw_list);
  6637. draw_list = nullptr;
  6638. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "vkResetCommandBuffer failed with error " + itos(res) + ".");
  6639. }
  6640. res = vkBeginCommandBuffer(command_buffer, &cmdbuf_begin);
  6641. if (res) {
  6642. memdelete_arr(draw_list);
  6643. draw_list = nullptr;
  6644. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "vkBeginCommandBuffer failed with error " + itos(res) + ".");
  6645. }
  6646. draw_list[i].command_buffer = command_buffer;
  6647. draw_list[i].viewport = p_viewport;
  6648. }
  6649. }
  6650. return OK;
  6651. }
  6652. void RenderingDeviceVulkan::_draw_list_free(Rect2i *r_last_viewport) {
  6653. if (draw_list_split) {
  6654. //send all command buffers
  6655. VkCommandBuffer *command_buffers = (VkCommandBuffer *)alloca(sizeof(VkCommandBuffer) * draw_list_count);
  6656. for (uint32_t i = 0; i < draw_list_count; i++) {
  6657. vkEndCommandBuffer(draw_list[i].command_buffer);
  6658. command_buffers[i] = draw_list[i].command_buffer;
  6659. if (r_last_viewport) {
  6660. if (i == 0 || draw_list[i].viewport_set) {
  6661. *r_last_viewport = draw_list[i].viewport;
  6662. }
  6663. }
  6664. }
  6665. vkCmdExecuteCommands(frames[frame].draw_command_buffer, draw_list_count, command_buffers);
  6666. memdelete_arr(draw_list);
  6667. draw_list = nullptr;
  6668. } else {
  6669. if (r_last_viewport) {
  6670. *r_last_viewport = draw_list->viewport;
  6671. }
  6672. //just end the list
  6673. memdelete(draw_list);
  6674. draw_list = nullptr;
  6675. }
  6676. // draw_list is no longer active
  6677. _THREAD_SAFE_UNLOCK_
  6678. }
  6679. void RenderingDeviceVulkan::draw_list_end(uint32_t p_post_barrier) {
  6680. _THREAD_SAFE_METHOD_
  6681. ERR_FAIL_COND_MSG(!draw_list, "Immediate draw list is already inactive.");
  6682. _draw_list_free();
  6683. vkCmdEndRenderPass(frames[frame].draw_command_buffer);
  6684. for (int i = 0; i < draw_list_bound_textures.size(); i++) {
  6685. Texture *texture = texture_owner.get_or_null(draw_list_bound_textures[i]);
  6686. ERR_CONTINUE(!texture); //wtf
  6687. if (draw_list_unbind_color_textures && (texture->usage_flags & TEXTURE_USAGE_COLOR_ATTACHMENT_BIT)) {
  6688. texture->bound = false;
  6689. }
  6690. if (draw_list_unbind_depth_textures && (texture->usage_flags & TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {
  6691. texture->bound = false;
  6692. }
  6693. }
  6694. uint32_t barrier_flags = 0;
  6695. uint32_t access_flags = 0;
  6696. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  6697. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  6698. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6699. }
  6700. if (p_post_barrier & BARRIER_MASK_RASTER) {
  6701. 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*/;
  6702. 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*/;
  6703. }
  6704. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  6705. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  6706. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  6707. }
  6708. if (barrier_flags == 0) {
  6709. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  6710. }
  6711. draw_list_bound_textures.clear();
  6712. VkImageMemoryBarrier *image_barriers = nullptr;
  6713. uint32_t image_barrier_count = draw_list_storage_textures.size();
  6714. if (image_barrier_count) {
  6715. image_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * draw_list_storage_textures.size());
  6716. }
  6717. uint32_t src_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  6718. uint32_t src_access = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  6719. if (image_barrier_count) {
  6720. src_stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  6721. src_access |= VK_ACCESS_SHADER_WRITE_BIT;
  6722. }
  6723. for (uint32_t i = 0; i < image_barrier_count; i++) {
  6724. Texture *texture = texture_owner.get_or_null(draw_list_storage_textures[i]);
  6725. VkImageMemoryBarrier &image_memory_barrier = image_barriers[i];
  6726. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  6727. image_memory_barrier.pNext = nullptr;
  6728. image_memory_barrier.srcAccessMask = src_access;
  6729. image_memory_barrier.dstAccessMask = access_flags;
  6730. image_memory_barrier.oldLayout = texture->layout;
  6731. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  6732. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6733. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6734. image_memory_barrier.image = texture->image;
  6735. image_memory_barrier.subresourceRange.aspectMask = texture->read_aspect_mask;
  6736. image_memory_barrier.subresourceRange.baseMipLevel = texture->base_mipmap;
  6737. image_memory_barrier.subresourceRange.levelCount = texture->mipmaps;
  6738. image_memory_barrier.subresourceRange.baseArrayLayer = texture->base_layer;
  6739. image_memory_barrier.subresourceRange.layerCount = texture->layers;
  6740. texture->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  6741. }
  6742. draw_list_storage_textures.clear();
  6743. // To ensure proper synchronization, we must make sure rendering is done before:
  6744. // * Some buffer is copied
  6745. // * Another render pass happens (since we may be done)
  6746. VkMemoryBarrier mem_barrier;
  6747. mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  6748. mem_barrier.pNext = nullptr;
  6749. mem_barrier.srcAccessMask = src_access;
  6750. mem_barrier.dstAccessMask = access_flags;
  6751. if (image_barrier_count > 0 || p_post_barrier != BARRIER_MASK_NO_BARRIER) {
  6752. vkCmdPipelineBarrier(frames[frame].draw_command_buffer, src_stage, barrier_flags, 0, 1, &mem_barrier, 0, nullptr, image_barrier_count, image_barriers);
  6753. }
  6754. #ifdef FORCE_FULL_BARRIER
  6755. _full_barrier(true);
  6756. #endif
  6757. }
  6758. /***********************/
  6759. /**** COMPUTE LISTS ****/
  6760. /***********************/
  6761. RenderingDevice::ComputeListID RenderingDeviceVulkan::compute_list_begin(bool p_allow_draw_overlap) {
  6762. 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.");
  6763. ERR_FAIL_COND_V_MSG(compute_list != nullptr, INVALID_ID, "Only one draw/compute list can be active at the same time.");
  6764. // Lock while compute_list is active
  6765. _THREAD_SAFE_LOCK_
  6766. compute_list = memnew(ComputeList);
  6767. compute_list->command_buffer = frames[frame].draw_command_buffer;
  6768. compute_list->state.allow_draw_overlap = p_allow_draw_overlap;
  6769. return ID_TYPE_COMPUTE_LIST;
  6770. }
  6771. void RenderingDeviceVulkan::compute_list_bind_compute_pipeline(ComputeListID p_list, RID p_compute_pipeline) {
  6772. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6773. ERR_FAIL_COND(!compute_list);
  6774. ComputeList *cl = compute_list;
  6775. const ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_compute_pipeline);
  6776. ERR_FAIL_COND(!pipeline);
  6777. if (p_compute_pipeline == cl->state.pipeline) {
  6778. return; //redundant state, return.
  6779. }
  6780. cl->state.pipeline = p_compute_pipeline;
  6781. cl->state.pipeline_layout = pipeline->pipeline_layout;
  6782. vkCmdBindPipeline(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline->pipeline);
  6783. if (cl->state.pipeline_shader != pipeline->shader) {
  6784. // shader changed, so descriptor sets may become incompatible.
  6785. //go through ALL sets, and unbind them (and all those above) if the format is different
  6786. uint32_t pcount = pipeline->set_formats.size(); //formats count in this pipeline
  6787. cl->state.set_count = MAX(cl->state.set_count, pcount);
  6788. const uint32_t *pformats = pipeline->set_formats.ptr(); //pipeline set formats
  6789. bool sets_valid = true; //once invalid, all above become invalid
  6790. for (uint32_t i = 0; i < pcount; i++) {
  6791. //if a part of the format is different, invalidate it (and the rest)
  6792. if (!sets_valid || cl->state.sets[i].pipeline_expected_format != pformats[i]) {
  6793. cl->state.sets[i].bound = false;
  6794. cl->state.sets[i].pipeline_expected_format = pformats[i];
  6795. sets_valid = false;
  6796. }
  6797. }
  6798. for (uint32_t i = pcount; i < cl->state.set_count; i++) {
  6799. //unbind the ones above (not used) if exist
  6800. cl->state.sets[i].bound = false;
  6801. }
  6802. cl->state.set_count = pcount; //update set count
  6803. if (pipeline->push_constant_size) {
  6804. cl->state.pipeline_push_constant_stages = pipeline->push_constant_stages;
  6805. #ifdef DEBUG_ENABLED
  6806. cl->validation.pipeline_push_constant_supplied = false;
  6807. #endif
  6808. }
  6809. cl->state.pipeline_shader = pipeline->shader;
  6810. cl->state.local_group_size[0] = pipeline->local_group_size[0];
  6811. cl->state.local_group_size[1] = pipeline->local_group_size[1];
  6812. cl->state.local_group_size[2] = pipeline->local_group_size[2];
  6813. }
  6814. #ifdef DEBUG_ENABLED
  6815. //update compute pass pipeline info
  6816. cl->validation.pipeline_active = true;
  6817. cl->validation.pipeline_push_constant_size = pipeline->push_constant_size;
  6818. #endif
  6819. }
  6820. void RenderingDeviceVulkan::compute_list_bind_uniform_set(ComputeListID p_list, RID p_uniform_set, uint32_t p_index) {
  6821. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6822. ERR_FAIL_COND(!compute_list);
  6823. ComputeList *cl = compute_list;
  6824. #ifdef DEBUG_ENABLED
  6825. ERR_FAIL_COND_MSG(p_index >= limits.maxBoundDescriptorSets || p_index >= MAX_UNIFORM_SETS,
  6826. "Attempting to bind a descriptor set (" + itos(p_index) + ") greater than what the hardware supports (" + itos(limits.maxBoundDescriptorSets) + ").");
  6827. #endif
  6828. #ifdef DEBUG_ENABLED
  6829. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  6830. #endif
  6831. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_uniform_set);
  6832. ERR_FAIL_COND(!uniform_set);
  6833. if (p_index > cl->state.set_count) {
  6834. cl->state.set_count = p_index;
  6835. }
  6836. cl->state.sets[p_index].descriptor_set = uniform_set->descriptor_set; //update set pointer
  6837. cl->state.sets[p_index].bound = false; //needs rebind
  6838. cl->state.sets[p_index].uniform_set_format = uniform_set->format;
  6839. cl->state.sets[p_index].uniform_set = p_uniform_set;
  6840. uint32_t textures_to_sampled_count = uniform_set->mutable_sampled_textures.size();
  6841. uint32_t textures_to_storage_count = uniform_set->mutable_storage_textures.size();
  6842. Texture **textures_to_sampled = uniform_set->mutable_sampled_textures.ptrw();
  6843. VkImageMemoryBarrier *texture_barriers = nullptr;
  6844. if (textures_to_sampled_count + textures_to_storage_count) {
  6845. texture_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * (textures_to_sampled_count + textures_to_storage_count));
  6846. }
  6847. uint32_t texture_barrier_count = 0;
  6848. uint32_t src_stage_flags = 0;
  6849. for (uint32_t i = 0; i < textures_to_sampled_count; i++) {
  6850. if (textures_to_sampled[i]->layout != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
  6851. src_stage_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  6852. VkImageMemoryBarrier &image_memory_barrier = texture_barriers[texture_barrier_count++];
  6853. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  6854. image_memory_barrier.pNext = nullptr;
  6855. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6856. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6857. image_memory_barrier.oldLayout = textures_to_sampled[i]->layout;
  6858. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  6859. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6860. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6861. image_memory_barrier.image = textures_to_sampled[i]->image;
  6862. image_memory_barrier.subresourceRange.aspectMask = textures_to_sampled[i]->read_aspect_mask;
  6863. image_memory_barrier.subresourceRange.baseMipLevel = textures_to_sampled[i]->base_mipmap;
  6864. image_memory_barrier.subresourceRange.levelCount = textures_to_sampled[i]->mipmaps;
  6865. image_memory_barrier.subresourceRange.baseArrayLayer = textures_to_sampled[i]->base_layer;
  6866. image_memory_barrier.subresourceRange.layerCount = textures_to_sampled[i]->layers;
  6867. textures_to_sampled[i]->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  6868. cl->state.textures_to_sampled_layout.erase(textures_to_sampled[i]);
  6869. }
  6870. if (textures_to_sampled[i]->used_in_frame != frames_drawn) {
  6871. textures_to_sampled[i]->used_in_frame = frames_drawn;
  6872. textures_to_sampled[i]->used_in_transfer = false;
  6873. textures_to_sampled[i]->used_in_raster = false;
  6874. }
  6875. textures_to_sampled[i]->used_in_compute = true;
  6876. }
  6877. Texture **textures_to_storage = uniform_set->mutable_storage_textures.ptrw();
  6878. for (uint32_t i = 0; i < textures_to_storage_count; i++) {
  6879. if (textures_to_storage[i]->layout != VK_IMAGE_LAYOUT_GENERAL) {
  6880. uint32_t src_access_flags = 0;
  6881. if (textures_to_storage[i]->used_in_frame == frames_drawn) {
  6882. if (textures_to_storage[i]->used_in_compute) {
  6883. src_stage_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  6884. src_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6885. }
  6886. if (textures_to_storage[i]->used_in_raster) {
  6887. src_stage_flags |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT;
  6888. src_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6889. }
  6890. if (textures_to_storage[i]->used_in_transfer) {
  6891. src_stage_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  6892. src_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  6893. }
  6894. textures_to_storage[i]->used_in_compute = false;
  6895. textures_to_storage[i]->used_in_raster = false;
  6896. textures_to_storage[i]->used_in_transfer = false;
  6897. } else {
  6898. src_access_flags = 0;
  6899. textures_to_storage[i]->used_in_compute = false;
  6900. textures_to_storage[i]->used_in_raster = false;
  6901. textures_to_storage[i]->used_in_transfer = false;
  6902. textures_to_storage[i]->used_in_frame = frames_drawn;
  6903. }
  6904. VkImageMemoryBarrier &image_memory_barrier = texture_barriers[texture_barrier_count++];
  6905. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  6906. image_memory_barrier.pNext = nullptr;
  6907. image_memory_barrier.srcAccessMask = src_access_flags;
  6908. image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  6909. image_memory_barrier.oldLayout = textures_to_storage[i]->layout;
  6910. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  6911. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6912. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  6913. image_memory_barrier.image = textures_to_storage[i]->image;
  6914. image_memory_barrier.subresourceRange.aspectMask = textures_to_storage[i]->read_aspect_mask;
  6915. image_memory_barrier.subresourceRange.baseMipLevel = textures_to_storage[i]->base_mipmap;
  6916. image_memory_barrier.subresourceRange.levelCount = textures_to_storage[i]->mipmaps;
  6917. image_memory_barrier.subresourceRange.baseArrayLayer = textures_to_storage[i]->base_layer;
  6918. image_memory_barrier.subresourceRange.layerCount = textures_to_storage[i]->layers;
  6919. textures_to_storage[i]->layout = VK_IMAGE_LAYOUT_GENERAL;
  6920. cl->state.textures_to_sampled_layout.insert(textures_to_storage[i]); //needs to go back to sampled layout afterwards
  6921. }
  6922. }
  6923. if (texture_barrier_count) {
  6924. if (src_stage_flags == 0) {
  6925. src_stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  6926. }
  6927. vkCmdPipelineBarrier(cl->command_buffer, src_stage_flags, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, texture_barrier_count, texture_barriers);
  6928. }
  6929. #if 0
  6930. { //validate that textures bound are not attached as framebuffer bindings
  6931. uint32_t attachable_count = uniform_set->attachable_textures.size();
  6932. const RID *attachable_ptr = uniform_set->attachable_textures.ptr();
  6933. uint32_t bound_count = draw_list_bound_textures.size();
  6934. const RID *bound_ptr = draw_list_bound_textures.ptr();
  6935. for (uint32_t i = 0; i < attachable_count; i++) {
  6936. for (uint32_t j = 0; j < bound_count; j++) {
  6937. ERR_FAIL_COND_MSG(attachable_ptr[i] == bound_ptr[j],
  6938. "Attempted to use the same texture in framebuffer attachment and a uniform set, this is not allowed.");
  6939. }
  6940. }
  6941. }
  6942. #endif
  6943. }
  6944. void RenderingDeviceVulkan::compute_list_set_push_constant(ComputeListID p_list, const void *p_data, uint32_t p_data_size) {
  6945. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6946. ERR_FAIL_COND(!compute_list);
  6947. ComputeList *cl = compute_list;
  6948. #ifdef DEBUG_ENABLED
  6949. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  6950. #endif
  6951. #ifdef DEBUG_ENABLED
  6952. ERR_FAIL_COND_MSG(p_data_size != cl->validation.pipeline_push_constant_size,
  6953. "This compute pipeline requires (" + itos(cl->validation.pipeline_push_constant_size) + ") bytes of push constant data, supplied: (" + itos(p_data_size) + ")");
  6954. #endif
  6955. vkCmdPushConstants(cl->command_buffer, cl->state.pipeline_layout, cl->state.pipeline_push_constant_stages, 0, p_data_size, p_data);
  6956. #ifdef DEBUG_ENABLED
  6957. cl->validation.pipeline_push_constant_supplied = true;
  6958. #endif
  6959. }
  6960. void RenderingDeviceVulkan::compute_list_dispatch(ComputeListID p_list, uint32_t p_x_groups, uint32_t p_y_groups, uint32_t p_z_groups) {
  6961. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  6962. ERR_FAIL_COND(!compute_list);
  6963. ComputeList *cl = compute_list;
  6964. #ifdef DEBUG_ENABLED
  6965. ERR_FAIL_COND_MSG(p_x_groups == 0, "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is zero.");
  6966. ERR_FAIL_COND_MSG(p_z_groups == 0, "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is zero.");
  6967. ERR_FAIL_COND_MSG(p_y_groups == 0, "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is zero.");
  6968. ERR_FAIL_COND_MSG(p_x_groups > limits.maxComputeWorkGroupCount[0],
  6969. "Dispatch amount of X compute groups (" + itos(p_x_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[0]) + ")");
  6970. ERR_FAIL_COND_MSG(p_y_groups > limits.maxComputeWorkGroupCount[1],
  6971. "Dispatch amount of Y compute groups (" + itos(p_y_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[1]) + ")");
  6972. ERR_FAIL_COND_MSG(p_z_groups > limits.maxComputeWorkGroupCount[2],
  6973. "Dispatch amount of Z compute groups (" + itos(p_z_groups) + ") is larger than device limit (" + itos(limits.maxComputeWorkGroupCount[2]) + ")");
  6974. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  6975. #endif
  6976. #ifdef DEBUG_ENABLED
  6977. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  6978. if (cl->validation.pipeline_push_constant_size > 0) {
  6979. //using push constants, check that they were supplied
  6980. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  6981. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  6982. }
  6983. #endif
  6984. //Bind descriptor sets
  6985. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  6986. if (cl->state.sets[i].pipeline_expected_format == 0) {
  6987. continue; //nothing expected by this pipeline
  6988. }
  6989. #ifdef DEBUG_ENABLED
  6990. if (cl->state.sets[i].pipeline_expected_format != cl->state.sets[i].uniform_set_format) {
  6991. if (cl->state.sets[i].uniform_set_format == 0) {
  6992. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  6993. } else if (uniform_set_owner.owns(cl->state.sets[i].uniform_set)) {
  6994. UniformSet *us = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set);
  6995. 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));
  6996. } else {
  6997. 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));
  6998. }
  6999. }
  7000. #endif
  7001. if (!cl->state.sets[i].bound) {
  7002. //All good, see if this requires re-binding
  7003. vkCmdBindDescriptorSets(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, cl->state.pipeline_layout, i, 1, &cl->state.sets[i].descriptor_set, 0, nullptr);
  7004. cl->state.sets[i].bound = true;
  7005. }
  7006. }
  7007. vkCmdDispatch(cl->command_buffer, p_x_groups, p_y_groups, p_z_groups);
  7008. }
  7009. void RenderingDeviceVulkan::compute_list_dispatch_threads(ComputeListID p_list, uint32_t p_x_threads, uint32_t p_y_threads, uint32_t p_z_threads) {
  7010. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  7011. ERR_FAIL_COND(!compute_list);
  7012. #ifdef DEBUG_ENABLED
  7013. ERR_FAIL_COND_MSG(p_x_threads == 0, "Dispatch amount of X compute threads (" + itos(p_x_threads) + ") is zero.");
  7014. ERR_FAIL_COND_MSG(p_y_threads == 0, "Dispatch amount of Y compute threads (" + itos(p_y_threads) + ") is zero.");
  7015. ERR_FAIL_COND_MSG(p_z_threads == 0, "Dispatch amount of Z compute threads (" + itos(p_z_threads) + ") is zero.");
  7016. #endif
  7017. ComputeList *cl = compute_list;
  7018. #ifdef DEBUG_ENABLED
  7019. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  7020. if (cl->validation.pipeline_push_constant_size > 0) {
  7021. //using push constants, check that they were supplied
  7022. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  7023. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  7024. }
  7025. #endif
  7026. 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);
  7027. }
  7028. void RenderingDeviceVulkan::compute_list_dispatch_indirect(ComputeListID p_list, RID p_buffer, uint32_t p_offset) {
  7029. ERR_FAIL_COND(p_list != ID_TYPE_COMPUTE_LIST);
  7030. ERR_FAIL_COND(!compute_list);
  7031. ComputeList *cl = compute_list;
  7032. Buffer *buffer = storage_buffer_owner.get_or_null(p_buffer);
  7033. ERR_FAIL_COND(!buffer);
  7034. ERR_FAIL_COND_MSG(!(buffer->usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT), "Buffer provided was not created to do indirect dispatch.");
  7035. ERR_FAIL_COND_MSG(p_offset + 12 > buffer->size, "Offset provided (+12) is past the end of buffer.");
  7036. #ifdef DEBUG_ENABLED
  7037. ERR_FAIL_COND_MSG(!cl->validation.active, "Submitted Compute Lists can no longer be modified.");
  7038. #endif
  7039. #ifdef DEBUG_ENABLED
  7040. ERR_FAIL_COND_MSG(!cl->validation.pipeline_active, "No compute pipeline was set before attempting to draw.");
  7041. if (cl->validation.pipeline_push_constant_size > 0) {
  7042. //using push constants, check that they were supplied
  7043. ERR_FAIL_COND_MSG(!cl->validation.pipeline_push_constant_supplied,
  7044. "The shader in this pipeline requires a push constant to be set before drawing, but it's not present.");
  7045. }
  7046. #endif
  7047. //Bind descriptor sets
  7048. for (uint32_t i = 0; i < cl->state.set_count; i++) {
  7049. if (cl->state.sets[i].pipeline_expected_format == 0) {
  7050. continue; //nothing expected by this pipeline
  7051. }
  7052. #ifdef DEBUG_ENABLED
  7053. if (cl->state.sets[i].pipeline_expected_format != cl->state.sets[i].uniform_set_format) {
  7054. if (cl->state.sets[i].uniform_set_format == 0) {
  7055. ERR_FAIL_MSG("Uniforms were never supplied for set (" + itos(i) + ") at the time of drawing, which are required by the pipeline");
  7056. } else if (uniform_set_owner.owns(cl->state.sets[i].uniform_set)) {
  7057. UniformSet *us = uniform_set_owner.get_or_null(cl->state.sets[i].uniform_set);
  7058. 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));
  7059. } else {
  7060. 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));
  7061. }
  7062. }
  7063. #endif
  7064. if (!cl->state.sets[i].bound) {
  7065. //All good, see if this requires re-binding
  7066. vkCmdBindDescriptorSets(cl->command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, cl->state.pipeline_layout, i, 1, &cl->state.sets[i].descriptor_set, 0, nullptr);
  7067. cl->state.sets[i].bound = true;
  7068. }
  7069. }
  7070. vkCmdDispatchIndirect(cl->command_buffer, buffer->buffer, p_offset);
  7071. }
  7072. void RenderingDeviceVulkan::compute_list_add_barrier(ComputeListID p_list) {
  7073. #ifdef FORCE_FULL_BARRIER
  7074. _full_barrier(true);
  7075. #else
  7076. _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);
  7077. #endif
  7078. }
  7079. void RenderingDeviceVulkan::compute_list_end(uint32_t p_post_barrier) {
  7080. ERR_FAIL_COND(!compute_list);
  7081. uint32_t barrier_flags = 0;
  7082. uint32_t access_flags = 0;
  7083. if (p_post_barrier & BARRIER_MASK_COMPUTE) {
  7084. barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  7085. access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7086. }
  7087. if (p_post_barrier & BARRIER_MASK_RASTER) {
  7088. 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;
  7089. 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;
  7090. }
  7091. if (p_post_barrier & BARRIER_MASK_TRANSFER) {
  7092. barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  7093. access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  7094. }
  7095. if (barrier_flags == 0) {
  7096. barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  7097. }
  7098. VkImageMemoryBarrier *image_barriers = nullptr;
  7099. uint32_t image_barrier_count = compute_list->state.textures_to_sampled_layout.size();
  7100. if (image_barrier_count) {
  7101. image_barriers = (VkImageMemoryBarrier *)alloca(sizeof(VkImageMemoryBarrier) * image_barrier_count);
  7102. }
  7103. uint32_t barrier_idx = 0;
  7104. for (Texture *E : compute_list->state.textures_to_sampled_layout) {
  7105. VkImageMemoryBarrier &image_memory_barrier = image_barriers[barrier_idx++];
  7106. image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  7107. image_memory_barrier.pNext = nullptr;
  7108. image_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7109. image_memory_barrier.dstAccessMask = access_flags;
  7110. image_memory_barrier.oldLayout = E->layout;
  7111. image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  7112. image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  7113. image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  7114. image_memory_barrier.image = E->image;
  7115. image_memory_barrier.subresourceRange.aspectMask = E->read_aspect_mask;
  7116. image_memory_barrier.subresourceRange.baseMipLevel = E->base_mipmap;
  7117. image_memory_barrier.subresourceRange.levelCount = E->mipmaps;
  7118. image_memory_barrier.subresourceRange.baseArrayLayer = E->base_layer;
  7119. image_memory_barrier.subresourceRange.layerCount = E->layers;
  7120. E->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  7121. if (E->used_in_frame != frames_drawn) {
  7122. E->used_in_transfer = false;
  7123. E->used_in_raster = false;
  7124. E->used_in_compute = false;
  7125. E->used_in_frame = frames_drawn;
  7126. }
  7127. }
  7128. VkMemoryBarrier mem_barrier;
  7129. mem_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  7130. mem_barrier.pNext = nullptr;
  7131. mem_barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
  7132. mem_barrier.dstAccessMask = access_flags;
  7133. if (image_barrier_count > 0 || p_post_barrier != BARRIER_MASK_NO_BARRIER) {
  7134. vkCmdPipelineBarrier(compute_list->command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, barrier_flags, 0, 1, &mem_barrier, 0, nullptr, image_barrier_count, image_barriers);
  7135. }
  7136. #ifdef FORCE_FULL_BARRIER
  7137. _full_barrier(true);
  7138. #endif
  7139. memdelete(compute_list);
  7140. compute_list = nullptr;
  7141. // compute_list is no longer active
  7142. _THREAD_SAFE_UNLOCK_
  7143. }
  7144. void RenderingDeviceVulkan::barrier(uint32_t p_from, uint32_t p_to) {
  7145. uint32_t src_barrier_flags = 0;
  7146. uint32_t src_access_flags = 0;
  7147. if (p_from & BARRIER_MASK_COMPUTE) {
  7148. src_barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  7149. src_access_flags |= VK_ACCESS_SHADER_WRITE_BIT;
  7150. }
  7151. if (p_from & BARRIER_MASK_RASTER) {
  7152. src_barrier_flags |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  7153. src_access_flags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  7154. }
  7155. if (p_from & BARRIER_MASK_TRANSFER) {
  7156. src_barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  7157. src_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT;
  7158. }
  7159. if (p_from == 0) {
  7160. src_barrier_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  7161. }
  7162. uint32_t dst_barrier_flags = 0;
  7163. uint32_t dst_access_flags = 0;
  7164. if (p_to & BARRIER_MASK_COMPUTE) {
  7165. dst_barrier_flags |= VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  7166. dst_access_flags |= VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  7167. }
  7168. if (p_to & BARRIER_MASK_RASTER) {
  7169. 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;
  7170. 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;
  7171. }
  7172. if (p_to & BARRIER_MASK_TRANSFER) {
  7173. dst_barrier_flags |= VK_PIPELINE_STAGE_TRANSFER_BIT;
  7174. dst_access_flags |= VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
  7175. }
  7176. if (p_to == 0) {
  7177. dst_barrier_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  7178. }
  7179. _memory_barrier(src_barrier_flags, dst_barrier_flags, src_access_flags, dst_access_flags, true);
  7180. }
  7181. void RenderingDeviceVulkan::full_barrier() {
  7182. #ifndef DEBUG_ENABLED
  7183. ERR_PRINT("Full barrier is debug-only, should not be used in production");
  7184. #endif
  7185. _full_barrier(true);
  7186. }
  7187. #if 0
  7188. 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) {
  7189. VkCommandBuffer frame_cmdbuf = frames[frame].frame_buffer;
  7190. ERR_FAIL_COND(!frame_cmdbuf);
  7191. VkRenderPassBeginInfo render_pass_begin;
  7192. render_pass_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  7193. render_pass_begin.pNext = nullptr;
  7194. render_pass_begin.renderPass = context->get_render_pass();
  7195. render_pass_begin.framebuffer = context->get_frame_framebuffer(frame);
  7196. render_pass_begin.renderArea.extent.width = context->get_screen_width(p_screen);
  7197. render_pass_begin.renderArea.extent.height = context->get_screen_height(p_screen);
  7198. render_pass_begin.renderArea.offset.x = 0;
  7199. render_pass_begin.renderArea.offset.y = 0;
  7200. render_pass_begin.clearValueCount = 1;
  7201. VkClearValue clear_value;
  7202. clear_value.color.float32[0] = p_clear_color.r;
  7203. clear_value.color.float32[1] = p_clear_color.g;
  7204. clear_value.color.float32[2] = p_clear_color.b;
  7205. clear_value.color.float32[3] = p_clear_color.a;
  7206. render_pass_begin.pClearValues = &clear_value;
  7207. vkCmdBeginRenderPass(frame_cmdbuf, &render_pass_begin, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS);
  7208. ID screen_format = screen_get_framebuffer_format();
  7209. {
  7210. VkCommandBuffer *command_buffers = (VkCommandBuffer *)alloca(sizeof(VkCommandBuffer) * p_draw_list_count);
  7211. uint32_t command_buffer_count = 0;
  7212. for (uint32_t i = 0; i < p_draw_list_count; i++) {
  7213. DrawList *dl = _get_draw_list_ptr(p_draw_lists[i]);
  7214. ERR_CONTINUE_MSG(!dl, "Draw list index (" + itos(i) + ") is not a valid draw list ID.");
  7215. ERR_CONTINUE_MSG(dl->validation.framebuffer_format != p_format_check,
  7216. "Draw list index (" + itos(i) + ") is created with a framebuffer format incompatible with this render pass.");
  7217. if (dl->validation.active) {
  7218. //needs to be closed, so close it.
  7219. vkEndCommandBuffer(dl->command_buffer);
  7220. dl->validation.active = false;
  7221. }
  7222. command_buffers[command_buffer_count++] = dl->command_buffer;
  7223. }
  7224. print_line("to draw: " + itos(command_buffer_count));
  7225. vkCmdExecuteCommands(p_primary, command_buffer_count, command_buffers);
  7226. }
  7227. vkCmdEndRenderPass(frame_cmdbuf);
  7228. }
  7229. #endif
  7230. void RenderingDeviceVulkan::_free_internal(RID p_id) {
  7231. //push everything so it's disposed of next time this frame index is processed (means, it's safe to do it)
  7232. if (texture_owner.owns(p_id)) {
  7233. Texture *texture = texture_owner.get_or_null(p_id);
  7234. frames[frame].textures_to_dispose_of.push_back(*texture);
  7235. texture_owner.free(p_id);
  7236. } else if (framebuffer_owner.owns(p_id)) {
  7237. Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_id);
  7238. frames[frame].framebuffers_to_dispose_of.push_back(*framebuffer);
  7239. framebuffer_owner.free(p_id);
  7240. } else if (sampler_owner.owns(p_id)) {
  7241. VkSampler *sampler = sampler_owner.get_or_null(p_id);
  7242. frames[frame].samplers_to_dispose_of.push_back(*sampler);
  7243. sampler_owner.free(p_id);
  7244. } else if (vertex_buffer_owner.owns(p_id)) {
  7245. Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id);
  7246. frames[frame].buffers_to_dispose_of.push_back(*vertex_buffer);
  7247. vertex_buffer_owner.free(p_id);
  7248. } else if (vertex_array_owner.owns(p_id)) {
  7249. vertex_array_owner.free(p_id);
  7250. } else if (index_buffer_owner.owns(p_id)) {
  7251. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id);
  7252. Buffer b;
  7253. b.allocation = index_buffer->allocation;
  7254. b.buffer = index_buffer->buffer;
  7255. b.size = index_buffer->size;
  7256. b.buffer_info = {};
  7257. frames[frame].buffers_to_dispose_of.push_back(b);
  7258. index_buffer_owner.free(p_id);
  7259. } else if (index_array_owner.owns(p_id)) {
  7260. index_array_owner.free(p_id);
  7261. } else if (shader_owner.owns(p_id)) {
  7262. Shader *shader = shader_owner.get_or_null(p_id);
  7263. frames[frame].shaders_to_dispose_of.push_back(*shader);
  7264. shader_owner.free(p_id);
  7265. } else if (uniform_buffer_owner.owns(p_id)) {
  7266. Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id);
  7267. frames[frame].buffers_to_dispose_of.push_back(*uniform_buffer);
  7268. uniform_buffer_owner.free(p_id);
  7269. } else if (texture_buffer_owner.owns(p_id)) {
  7270. TextureBuffer *texture_buffer = texture_buffer_owner.get_or_null(p_id);
  7271. frames[frame].buffers_to_dispose_of.push_back(texture_buffer->buffer);
  7272. frames[frame].buffer_views_to_dispose_of.push_back(texture_buffer->view);
  7273. texture_buffer_owner.free(p_id);
  7274. } else if (storage_buffer_owner.owns(p_id)) {
  7275. Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id);
  7276. frames[frame].buffers_to_dispose_of.push_back(*storage_buffer);
  7277. storage_buffer_owner.free(p_id);
  7278. } else if (uniform_set_owner.owns(p_id)) {
  7279. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id);
  7280. frames[frame].uniform_sets_to_dispose_of.push_back(*uniform_set);
  7281. uniform_set_owner.free(p_id);
  7282. if (uniform_set->invalidated_callback != nullptr) {
  7283. uniform_set->invalidated_callback(uniform_set->invalidated_callback_userdata);
  7284. }
  7285. } else if (render_pipeline_owner.owns(p_id)) {
  7286. RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id);
  7287. frames[frame].render_pipelines_to_dispose_of.push_back(*pipeline);
  7288. render_pipeline_owner.free(p_id);
  7289. } else if (compute_pipeline_owner.owns(p_id)) {
  7290. ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id);
  7291. frames[frame].compute_pipelines_to_dispose_of.push_back(*pipeline);
  7292. compute_pipeline_owner.free(p_id);
  7293. } else {
  7294. ERR_PRINT("Attempted to free invalid ID: " + itos(p_id.get_id()));
  7295. }
  7296. }
  7297. void RenderingDeviceVulkan::free(RID p_id) {
  7298. _THREAD_SAFE_METHOD_
  7299. _free_dependencies(p_id); //recursively erase dependencies first, to avoid potential API problems
  7300. _free_internal(p_id);
  7301. }
  7302. // The full list of resources that can be named is in the VkObjectType enum
  7303. // We just expose the resources that are owned and can be accessed easily.
  7304. void RenderingDeviceVulkan::set_resource_name(RID p_id, const String p_name) {
  7305. if (texture_owner.owns(p_id)) {
  7306. Texture *texture = texture_owner.get_or_null(p_id);
  7307. if (texture->owner.is_null()) {
  7308. // Don't set the source texture's name when calling on a texture view
  7309. context->set_object_name(VK_OBJECT_TYPE_IMAGE, uint64_t(texture->image), p_name);
  7310. }
  7311. context->set_object_name(VK_OBJECT_TYPE_IMAGE_VIEW, uint64_t(texture->view), p_name + " View");
  7312. } else if (framebuffer_owner.owns(p_id)) {
  7313. //Framebuffer *framebuffer = framebuffer_owner.get_or_null(p_id);
  7314. // Not implemented for now as the relationship between Framebuffer and RenderPass is very complex
  7315. } else if (sampler_owner.owns(p_id)) {
  7316. VkSampler *sampler = sampler_owner.get_or_null(p_id);
  7317. context->set_object_name(VK_OBJECT_TYPE_SAMPLER, uint64_t(*sampler), p_name);
  7318. } else if (vertex_buffer_owner.owns(p_id)) {
  7319. Buffer *vertex_buffer = vertex_buffer_owner.get_or_null(p_id);
  7320. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(vertex_buffer->buffer), p_name);
  7321. } else if (index_buffer_owner.owns(p_id)) {
  7322. IndexBuffer *index_buffer = index_buffer_owner.get_or_null(p_id);
  7323. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(index_buffer->buffer), p_name);
  7324. } else if (shader_owner.owns(p_id)) {
  7325. Shader *shader = shader_owner.get_or_null(p_id);
  7326. context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(shader->pipeline_layout), p_name + " Pipeline Layout");
  7327. for (int i = 0; i < shader->sets.size(); i++) {
  7328. context->set_object_name(VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, uint64_t(shader->sets[i].descriptor_set_layout), p_name);
  7329. }
  7330. } else if (uniform_buffer_owner.owns(p_id)) {
  7331. Buffer *uniform_buffer = uniform_buffer_owner.get_or_null(p_id);
  7332. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(uniform_buffer->buffer), p_name);
  7333. } else if (texture_buffer_owner.owns(p_id)) {
  7334. TextureBuffer *texture_buffer = texture_buffer_owner.get_or_null(p_id);
  7335. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(texture_buffer->buffer.buffer), p_name);
  7336. context->set_object_name(VK_OBJECT_TYPE_BUFFER_VIEW, uint64_t(texture_buffer->view), p_name + " View");
  7337. } else if (storage_buffer_owner.owns(p_id)) {
  7338. Buffer *storage_buffer = storage_buffer_owner.get_or_null(p_id);
  7339. context->set_object_name(VK_OBJECT_TYPE_BUFFER, uint64_t(storage_buffer->buffer), p_name);
  7340. } else if (uniform_set_owner.owns(p_id)) {
  7341. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_id);
  7342. context->set_object_name(VK_OBJECT_TYPE_DESCRIPTOR_SET, uint64_t(uniform_set->descriptor_set), p_name);
  7343. } else if (render_pipeline_owner.owns(p_id)) {
  7344. RenderPipeline *pipeline = render_pipeline_owner.get_or_null(p_id);
  7345. context->set_object_name(VK_OBJECT_TYPE_PIPELINE, uint64_t(pipeline->pipeline), p_name);
  7346. context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(pipeline->pipeline_layout), p_name + " Layout");
  7347. } else if (compute_pipeline_owner.owns(p_id)) {
  7348. ComputePipeline *pipeline = compute_pipeline_owner.get_or_null(p_id);
  7349. context->set_object_name(VK_OBJECT_TYPE_PIPELINE, uint64_t(pipeline->pipeline), p_name);
  7350. context->set_object_name(VK_OBJECT_TYPE_PIPELINE_LAYOUT, uint64_t(pipeline->pipeline_layout), p_name + " Layout");
  7351. } else {
  7352. ERR_PRINT("Attempted to name invalid ID: " + itos(p_id.get_id()));
  7353. }
  7354. }
  7355. void RenderingDeviceVulkan::draw_command_begin_label(String p_label_name, const Color p_color) {
  7356. context->command_begin_label(frames[frame].draw_command_buffer, p_label_name, p_color);
  7357. }
  7358. void RenderingDeviceVulkan::draw_command_insert_label(String p_label_name, const Color p_color) {
  7359. context->command_insert_label(frames[frame].draw_command_buffer, p_label_name, p_color);
  7360. }
  7361. void RenderingDeviceVulkan::draw_command_end_label() {
  7362. context->command_end_label(frames[frame].draw_command_buffer);
  7363. }
  7364. String RenderingDeviceVulkan::get_device_vendor_name() const {
  7365. return context->get_device_vendor_name();
  7366. }
  7367. String RenderingDeviceVulkan::get_device_name() const {
  7368. return context->get_device_name();
  7369. }
  7370. RenderingDevice::DeviceType RenderingDeviceVulkan::get_device_type() const {
  7371. return context->get_device_type();
  7372. }
  7373. String RenderingDeviceVulkan::get_device_api_version() const {
  7374. return context->get_device_api_version();
  7375. }
  7376. String RenderingDeviceVulkan::get_device_pipeline_cache_uuid() const {
  7377. return context->get_device_pipeline_cache_uuid();
  7378. }
  7379. void RenderingDeviceVulkan::_finalize_command_bufers() {
  7380. if (draw_list) {
  7381. ERR_PRINT("Found open draw list at the end of the frame, this should never happen (further drawing will likely not work).");
  7382. }
  7383. if (compute_list) {
  7384. ERR_PRINT("Found open compute list at the end of the frame, this should never happen (further compute will likely not work).");
  7385. }
  7386. { //complete the setup buffer (that needs to be processed before anything else)
  7387. vkEndCommandBuffer(frames[frame].setup_command_buffer);
  7388. vkEndCommandBuffer(frames[frame].draw_command_buffer);
  7389. }
  7390. }
  7391. void RenderingDeviceVulkan::_begin_frame() {
  7392. //erase pending resources
  7393. _free_pending_resources(frame);
  7394. //create setup command buffer and set as the setup buffer
  7395. {
  7396. VkCommandBufferBeginInfo cmdbuf_begin;
  7397. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7398. cmdbuf_begin.pNext = nullptr;
  7399. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7400. cmdbuf_begin.pInheritanceInfo = nullptr;
  7401. VkResult err = vkResetCommandBuffer(frames[frame].setup_command_buffer, 0);
  7402. ERR_FAIL_COND_MSG(err, "vkResetCommandBuffer failed with error " + itos(err) + ".");
  7403. err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  7404. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7405. err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  7406. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7407. if (local_device.is_null()) {
  7408. context->append_command_buffer(frames[frame].draw_command_buffer);
  7409. context->set_setup_buffer(frames[frame].setup_command_buffer); //append now so it's added before everything else
  7410. }
  7411. }
  7412. //advance current frame
  7413. frames_drawn++;
  7414. //advance staging buffer if used
  7415. if (staging_buffer_used) {
  7416. staging_buffer_current = (staging_buffer_current + 1) % staging_buffer_blocks.size();
  7417. staging_buffer_used = false;
  7418. }
  7419. if (frames[frame].timestamp_count) {
  7420. vkGetQueryPoolResults(device, frames[frame].timestamp_pool, 0, frames[frame].timestamp_count, sizeof(uint64_t) * max_timestamp_query_elements, frames[frame].timestamp_result_values.ptr(), sizeof(uint64_t), VK_QUERY_RESULT_64_BIT);
  7421. vkCmdResetQueryPool(frames[frame].setup_command_buffer, frames[frame].timestamp_pool, 0, frames[frame].timestamp_count);
  7422. SWAP(frames[frame].timestamp_names, frames[frame].timestamp_result_names);
  7423. SWAP(frames[frame].timestamp_cpu_values, frames[frame].timestamp_cpu_result_values);
  7424. }
  7425. frames[frame].timestamp_result_count = frames[frame].timestamp_count;
  7426. frames[frame].timestamp_count = 0;
  7427. frames[frame].index = Engine::get_singleton()->get_frames_drawn();
  7428. }
  7429. void RenderingDeviceVulkan::swap_buffers() {
  7430. ERR_FAIL_COND_MSG(local_device.is_valid(), "Local devices can't swap buffers.");
  7431. _THREAD_SAFE_METHOD_
  7432. _finalize_command_bufers();
  7433. screen_prepared = false;
  7434. //swap buffers
  7435. context->swap_buffers();
  7436. frame = (frame + 1) % frame_count;
  7437. _begin_frame();
  7438. }
  7439. void RenderingDeviceVulkan::submit() {
  7440. ERR_FAIL_COND_MSG(local_device.is_null(), "Only local devices can submit and sync.");
  7441. ERR_FAIL_COND_MSG(local_device_processing, "device already submitted, call sync to wait until done.");
  7442. _finalize_command_bufers();
  7443. VkCommandBuffer command_buffers[2] = { frames[frame].setup_command_buffer, frames[frame].draw_command_buffer };
  7444. context->local_device_push_command_buffers(local_device, command_buffers, 2);
  7445. local_device_processing = true;
  7446. }
  7447. void RenderingDeviceVulkan::sync() {
  7448. ERR_FAIL_COND_MSG(local_device.is_null(), "Only local devices can submit and sync.");
  7449. ERR_FAIL_COND_MSG(!local_device_processing, "sync can only be called after a submit");
  7450. context->local_device_sync(local_device);
  7451. _begin_frame();
  7452. local_device_processing = false;
  7453. }
  7454. VmaPool RenderingDeviceVulkan::_find_or_create_small_allocs_pool(uint32_t p_mem_type_index) {
  7455. if (small_allocs_pools.has(p_mem_type_index)) {
  7456. return small_allocs_pools[p_mem_type_index];
  7457. }
  7458. print_verbose("Creating VMA small objects pool for memory type index " + itos(p_mem_type_index));
  7459. VmaPoolCreateInfo pci;
  7460. pci.memoryTypeIndex = p_mem_type_index;
  7461. pci.flags = 0;
  7462. pci.blockSize = 0;
  7463. pci.minBlockCount = 0;
  7464. pci.maxBlockCount = SIZE_MAX;
  7465. pci.priority = 0.5f;
  7466. pci.minAllocationAlignment = 0;
  7467. pci.pMemoryAllocateNext = nullptr;
  7468. VmaPool pool = VK_NULL_HANDLE;
  7469. VkResult res = vmaCreatePool(allocator, &pci, &pool);
  7470. small_allocs_pools[p_mem_type_index] = pool; // Don't try to create it again if failed the first time
  7471. ERR_FAIL_COND_V_MSG(res, pool, "vmaCreatePool failed with error " + itos(res) + ".");
  7472. return pool;
  7473. }
  7474. void RenderingDeviceVulkan::_free_pending_resources(int p_frame) {
  7475. //free in dependency usage order, so nothing weird happens
  7476. //pipelines
  7477. while (frames[p_frame].render_pipelines_to_dispose_of.front()) {
  7478. RenderPipeline *pipeline = &frames[p_frame].render_pipelines_to_dispose_of.front()->get();
  7479. vkDestroyPipeline(device, pipeline->pipeline, nullptr);
  7480. frames[p_frame].render_pipelines_to_dispose_of.pop_front();
  7481. }
  7482. while (frames[p_frame].compute_pipelines_to_dispose_of.front()) {
  7483. ComputePipeline *pipeline = &frames[p_frame].compute_pipelines_to_dispose_of.front()->get();
  7484. vkDestroyPipeline(device, pipeline->pipeline, nullptr);
  7485. frames[p_frame].compute_pipelines_to_dispose_of.pop_front();
  7486. }
  7487. //uniform sets
  7488. while (frames[p_frame].uniform_sets_to_dispose_of.front()) {
  7489. UniformSet *uniform_set = &frames[p_frame].uniform_sets_to_dispose_of.front()->get();
  7490. vkFreeDescriptorSets(device, uniform_set->pool->pool, 1, &uniform_set->descriptor_set);
  7491. _descriptor_pool_free(uniform_set->pool_key, uniform_set->pool);
  7492. frames[p_frame].uniform_sets_to_dispose_of.pop_front();
  7493. }
  7494. //buffer views
  7495. while (frames[p_frame].buffer_views_to_dispose_of.front()) {
  7496. VkBufferView buffer_view = frames[p_frame].buffer_views_to_dispose_of.front()->get();
  7497. vkDestroyBufferView(device, buffer_view, nullptr);
  7498. frames[p_frame].buffer_views_to_dispose_of.pop_front();
  7499. }
  7500. //shaders
  7501. while (frames[p_frame].shaders_to_dispose_of.front()) {
  7502. Shader *shader = &frames[p_frame].shaders_to_dispose_of.front()->get();
  7503. //descriptor set layout for each set
  7504. for (int i = 0; i < shader->sets.size(); i++) {
  7505. vkDestroyDescriptorSetLayout(device, shader->sets[i].descriptor_set_layout, nullptr);
  7506. }
  7507. //pipeline layout
  7508. vkDestroyPipelineLayout(device, shader->pipeline_layout, nullptr);
  7509. //shaders themselves
  7510. for (int i = 0; i < shader->pipeline_stages.size(); i++) {
  7511. vkDestroyShaderModule(device, shader->pipeline_stages[i].module, nullptr);
  7512. }
  7513. frames[p_frame].shaders_to_dispose_of.pop_front();
  7514. }
  7515. //samplers
  7516. while (frames[p_frame].samplers_to_dispose_of.front()) {
  7517. VkSampler sampler = frames[p_frame].samplers_to_dispose_of.front()->get();
  7518. vkDestroySampler(device, sampler, nullptr);
  7519. frames[p_frame].samplers_to_dispose_of.pop_front();
  7520. }
  7521. //framebuffers
  7522. while (frames[p_frame].framebuffers_to_dispose_of.front()) {
  7523. Framebuffer *framebuffer = &frames[p_frame].framebuffers_to_dispose_of.front()->get();
  7524. for (const KeyValue<Framebuffer::VersionKey, Framebuffer::Version> &E : framebuffer->framebuffers) {
  7525. //first framebuffer, then render pass because it depends on it
  7526. vkDestroyFramebuffer(device, E.value.framebuffer, nullptr);
  7527. vkDestroyRenderPass(device, E.value.render_pass, nullptr);
  7528. }
  7529. frames[p_frame].framebuffers_to_dispose_of.pop_front();
  7530. }
  7531. //textures
  7532. while (frames[p_frame].textures_to_dispose_of.front()) {
  7533. Texture *texture = &frames[p_frame].textures_to_dispose_of.front()->get();
  7534. if (texture->bound) {
  7535. WARN_PRINT("Deleted a texture while it was bound..");
  7536. }
  7537. vkDestroyImageView(device, texture->view, nullptr);
  7538. if (texture->owner.is_null()) {
  7539. //actually owns the image and the allocation too
  7540. image_memory -= texture->allocation_info.size;
  7541. vmaDestroyImage(allocator, texture->image, texture->allocation);
  7542. }
  7543. frames[p_frame].textures_to_dispose_of.pop_front();
  7544. }
  7545. //buffers
  7546. while (frames[p_frame].buffers_to_dispose_of.front()) {
  7547. _buffer_free(&frames[p_frame].buffers_to_dispose_of.front()->get());
  7548. frames[p_frame].buffers_to_dispose_of.pop_front();
  7549. }
  7550. }
  7551. void RenderingDeviceVulkan::prepare_screen_for_drawing() {
  7552. _THREAD_SAFE_METHOD_
  7553. context->prepare_buffers();
  7554. screen_prepared = true;
  7555. }
  7556. uint32_t RenderingDeviceVulkan::get_frame_delay() const {
  7557. return frame_count;
  7558. }
  7559. uint64_t RenderingDeviceVulkan::get_memory_usage(MemoryType p_type) const {
  7560. if (p_type == MEMORY_BUFFERS) {
  7561. return buffer_memory;
  7562. } else if (p_type == MEMORY_TEXTURES) {
  7563. return image_memory;
  7564. } else {
  7565. VmaTotalStatistics stats;
  7566. vmaCalculateStatistics(allocator, &stats);
  7567. return stats.total.statistics.allocationBytes;
  7568. }
  7569. }
  7570. void RenderingDeviceVulkan::_flush(bool p_current_frame) {
  7571. if (local_device.is_valid() && !p_current_frame) {
  7572. return; //flushing previous frames has no effect with local device
  7573. }
  7574. //not doing this crashes RADV (undefined behavior)
  7575. if (p_current_frame) {
  7576. vkEndCommandBuffer(frames[frame].setup_command_buffer);
  7577. vkEndCommandBuffer(frames[frame].draw_command_buffer);
  7578. }
  7579. if (local_device.is_valid()) {
  7580. VkCommandBuffer command_buffers[2] = { frames[frame].setup_command_buffer, frames[frame].draw_command_buffer };
  7581. context->local_device_push_command_buffers(local_device, command_buffers, 2);
  7582. context->local_device_sync(local_device);
  7583. VkCommandBufferBeginInfo cmdbuf_begin;
  7584. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7585. cmdbuf_begin.pNext = nullptr;
  7586. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7587. cmdbuf_begin.pInheritanceInfo = nullptr;
  7588. VkResult err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  7589. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7590. err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  7591. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7592. } else {
  7593. context->flush(p_current_frame, p_current_frame);
  7594. //re-create the setup command
  7595. if (p_current_frame) {
  7596. VkCommandBufferBeginInfo cmdbuf_begin;
  7597. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7598. cmdbuf_begin.pNext = nullptr;
  7599. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7600. cmdbuf_begin.pInheritanceInfo = nullptr;
  7601. VkResult err = vkBeginCommandBuffer(frames[frame].setup_command_buffer, &cmdbuf_begin);
  7602. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7603. context->set_setup_buffer(frames[frame].setup_command_buffer); //append now so it's added before everything else
  7604. }
  7605. if (p_current_frame) {
  7606. VkCommandBufferBeginInfo cmdbuf_begin;
  7607. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7608. cmdbuf_begin.pNext = nullptr;
  7609. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7610. cmdbuf_begin.pInheritanceInfo = nullptr;
  7611. VkResult err = vkBeginCommandBuffer(frames[frame].draw_command_buffer, &cmdbuf_begin);
  7612. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7613. context->append_command_buffer(frames[frame].draw_command_buffer);
  7614. }
  7615. }
  7616. }
  7617. void RenderingDeviceVulkan::initialize(VulkanContext *p_context, bool p_local_device) {
  7618. // get our device capabilities
  7619. {
  7620. device_capabilities.version_major = p_context->get_vulkan_major();
  7621. device_capabilities.version_minor = p_context->get_vulkan_minor();
  7622. // get info about subgroups
  7623. VulkanContext::SubgroupCapabilities subgroup_capabilities = p_context->get_subgroup_capabilities();
  7624. device_capabilities.subgroup_size = subgroup_capabilities.size;
  7625. device_capabilities.subgroup_in_shaders = subgroup_capabilities.supported_stages_flags_rd();
  7626. device_capabilities.subgroup_operations = subgroup_capabilities.supported_operations_flags_rd();
  7627. // get info about further features
  7628. VulkanContext::MultiviewCapabilities multiview_capabilies = p_context->get_multiview_capabilities();
  7629. device_capabilities.supports_multiview = multiview_capabilies.is_supported && multiview_capabilies.max_view_count > 1;
  7630. 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;
  7631. }
  7632. context = p_context;
  7633. device = p_context->get_device();
  7634. if (p_local_device) {
  7635. frame_count = 1;
  7636. local_device = p_context->local_device_create();
  7637. device = p_context->local_device_get_vk_device(local_device);
  7638. } else {
  7639. 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.
  7640. }
  7641. limits = p_context->get_device_limits();
  7642. max_timestamp_query_elements = 256;
  7643. { //initialize allocator
  7644. VmaAllocatorCreateInfo allocatorInfo;
  7645. memset(&allocatorInfo, 0, sizeof(VmaAllocatorCreateInfo));
  7646. allocatorInfo.physicalDevice = p_context->get_physical_device();
  7647. allocatorInfo.device = device;
  7648. allocatorInfo.instance = p_context->get_instance();
  7649. vmaCreateAllocator(&allocatorInfo, &allocator);
  7650. }
  7651. frames.resize(frame_count);
  7652. frame = 0;
  7653. //create setup and frame buffers
  7654. for (int i = 0; i < frame_count; i++) {
  7655. frames[i].index = 0;
  7656. { //create command pool, one per frame is recommended
  7657. VkCommandPoolCreateInfo cmd_pool_info;
  7658. cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  7659. cmd_pool_info.pNext = nullptr;
  7660. cmd_pool_info.queueFamilyIndex = p_context->get_graphics_queue_family_index();
  7661. cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  7662. VkResult res = vkCreateCommandPool(device, &cmd_pool_info, nullptr, &frames[i].command_pool);
  7663. ERR_FAIL_COND_MSG(res, "vkCreateCommandPool failed with error " + itos(res) + ".");
  7664. }
  7665. { //create command buffers
  7666. VkCommandBufferAllocateInfo cmdbuf;
  7667. //no command buffer exists, create it.
  7668. cmdbuf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  7669. cmdbuf.pNext = nullptr;
  7670. cmdbuf.commandPool = frames[i].command_pool;
  7671. cmdbuf.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  7672. cmdbuf.commandBufferCount = 1;
  7673. VkResult err = vkAllocateCommandBuffers(device, &cmdbuf, &frames[i].setup_command_buffer);
  7674. ERR_CONTINUE_MSG(err, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  7675. err = vkAllocateCommandBuffers(device, &cmdbuf, &frames[i].draw_command_buffer);
  7676. ERR_CONTINUE_MSG(err, "vkAllocateCommandBuffers failed with error " + itos(err) + ".");
  7677. }
  7678. {
  7679. //create query pool
  7680. VkQueryPoolCreateInfo query_pool_create_info;
  7681. query_pool_create_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
  7682. query_pool_create_info.flags = 0;
  7683. query_pool_create_info.pNext = nullptr;
  7684. query_pool_create_info.queryType = VK_QUERY_TYPE_TIMESTAMP;
  7685. query_pool_create_info.queryCount = max_timestamp_query_elements;
  7686. query_pool_create_info.pipelineStatistics = 0;
  7687. vkCreateQueryPool(device, &query_pool_create_info, nullptr, &frames[i].timestamp_pool);
  7688. frames[i].timestamp_names.resize(max_timestamp_query_elements);
  7689. frames[i].timestamp_cpu_values.resize(max_timestamp_query_elements);
  7690. frames[i].timestamp_count = 0;
  7691. frames[i].timestamp_result_names.resize(max_timestamp_query_elements);
  7692. frames[i].timestamp_cpu_result_values.resize(max_timestamp_query_elements);
  7693. frames[i].timestamp_result_values.resize(max_timestamp_query_elements);
  7694. frames[i].timestamp_result_count = 0;
  7695. }
  7696. }
  7697. {
  7698. //begin the first command buffer for the first frame, so
  7699. //setting up things can be done in the meantime until swap_buffers(), which is called before advance.
  7700. VkCommandBufferBeginInfo cmdbuf_begin;
  7701. cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  7702. cmdbuf_begin.pNext = nullptr;
  7703. cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  7704. cmdbuf_begin.pInheritanceInfo = nullptr;
  7705. VkResult err = vkBeginCommandBuffer(frames[0].setup_command_buffer, &cmdbuf_begin);
  7706. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7707. err = vkBeginCommandBuffer(frames[0].draw_command_buffer, &cmdbuf_begin);
  7708. ERR_FAIL_COND_MSG(err, "vkBeginCommandBuffer failed with error " + itos(err) + ".");
  7709. if (local_device.is_null()) {
  7710. context->set_setup_buffer(frames[0].setup_command_buffer); //append now so it's added before everything else
  7711. context->append_command_buffer(frames[0].draw_command_buffer);
  7712. }
  7713. }
  7714. // Note: If adding new project settings here, also duplicate their definition in
  7715. // rendering_server.cpp for headless doctool.
  7716. staging_buffer_block_size = GLOBAL_DEF("rendering/vulkan/staging_buffer/block_size_kb", 256);
  7717. staging_buffer_block_size = MAX(4u, staging_buffer_block_size);
  7718. staging_buffer_block_size *= 1024; //kb -> bytes
  7719. staging_buffer_max_size = GLOBAL_DEF("rendering/vulkan/staging_buffer/max_size_mb", 128);
  7720. staging_buffer_max_size = MAX(1u, staging_buffer_max_size);
  7721. staging_buffer_max_size *= 1024 * 1024;
  7722. if (staging_buffer_max_size < staging_buffer_block_size * 4) {
  7723. //validate enough blocks
  7724. staging_buffer_max_size = staging_buffer_block_size * 4;
  7725. }
  7726. texture_upload_region_size_px = GLOBAL_DEF("rendering/vulkan/staging_buffer/texture_upload_region_size_px", 64);
  7727. texture_upload_region_size_px = nearest_power_of_2_templated(texture_upload_region_size_px);
  7728. frames_drawn = frame_count; //start from frame count, so everything else is immediately old
  7729. //ensure current staging block is valid and at least one per frame exists
  7730. staging_buffer_current = 0;
  7731. staging_buffer_used = false;
  7732. for (int i = 0; i < frame_count; i++) {
  7733. //staging was never used, create a block
  7734. Error err = _insert_staging_block();
  7735. ERR_CONTINUE(err != OK);
  7736. }
  7737. max_descriptors_per_pool = GLOBAL_DEF("rendering/vulkan/descriptor_pools/max_descriptors_per_pool", 64);
  7738. //check to make sure DescriptorPoolKey is good
  7739. static_assert(sizeof(uint64_t) * 3 >= UNIFORM_TYPE_MAX * sizeof(uint16_t));
  7740. draw_list = nullptr;
  7741. draw_list_count = 0;
  7742. draw_list_split = false;
  7743. compute_list = nullptr;
  7744. }
  7745. template <class T>
  7746. void RenderingDeviceVulkan::_free_rids(T &p_owner, const char *p_type) {
  7747. List<RID> owned;
  7748. p_owner.get_owned_list(&owned);
  7749. if (owned.size()) {
  7750. if (owned.size() == 1) {
  7751. WARN_PRINT(vformat("1 RID of type \"%s\" was leaked.", p_type));
  7752. } else {
  7753. WARN_PRINT(vformat("%d RIDs of type \"%s\" were leaked.", owned.size(), p_type));
  7754. }
  7755. for (const RID &E : owned) {
  7756. free(E);
  7757. }
  7758. }
  7759. }
  7760. void RenderingDeviceVulkan::capture_timestamp(const String &p_name) {
  7761. ERR_FAIL_COND_MSG(draw_list != nullptr, "Capturing timestamps during draw list creation is not allowed. Offending timestamp was: " + p_name);
  7762. ERR_FAIL_COND(frames[frame].timestamp_count >= max_timestamp_query_elements);
  7763. //this should be optional for profiling, else it will slow things down
  7764. {
  7765. VkMemoryBarrier memoryBarrier;
  7766. memoryBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
  7767. memoryBarrier.pNext = nullptr;
  7768. memoryBarrier.srcAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  7769. VK_ACCESS_INDEX_READ_BIT |
  7770. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  7771. VK_ACCESS_UNIFORM_READ_BIT |
  7772. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  7773. VK_ACCESS_SHADER_READ_BIT |
  7774. VK_ACCESS_SHADER_WRITE_BIT |
  7775. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  7776. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  7777. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  7778. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  7779. VK_ACCESS_TRANSFER_READ_BIT |
  7780. VK_ACCESS_TRANSFER_WRITE_BIT |
  7781. VK_ACCESS_HOST_READ_BIT |
  7782. VK_ACCESS_HOST_WRITE_BIT;
  7783. memoryBarrier.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT |
  7784. VK_ACCESS_INDEX_READ_BIT |
  7785. VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT |
  7786. VK_ACCESS_UNIFORM_READ_BIT |
  7787. VK_ACCESS_INPUT_ATTACHMENT_READ_BIT |
  7788. VK_ACCESS_SHADER_READ_BIT |
  7789. VK_ACCESS_SHADER_WRITE_BIT |
  7790. VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
  7791. VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
  7792. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
  7793. VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
  7794. VK_ACCESS_TRANSFER_READ_BIT |
  7795. VK_ACCESS_TRANSFER_WRITE_BIT |
  7796. VK_ACCESS_HOST_READ_BIT |
  7797. VK_ACCESS_HOST_WRITE_BIT;
  7798. 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);
  7799. }
  7800. vkCmdWriteTimestamp(frames[frame].draw_command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, frames[frame].timestamp_pool, frames[frame].timestamp_count);
  7801. frames[frame].timestamp_names[frames[frame].timestamp_count] = p_name;
  7802. frames[frame].timestamp_cpu_values[frames[frame].timestamp_count] = OS::get_singleton()->get_ticks_usec();
  7803. frames[frame].timestamp_count++;
  7804. }
  7805. uint64_t RenderingDeviceVulkan::get_driver_resource(DriverResource p_resource, RID p_rid, uint64_t p_index) {
  7806. _THREAD_SAFE_METHOD_
  7807. switch (p_resource) {
  7808. case DRIVER_RESOURCE_VULKAN_DEVICE: {
  7809. return (uint64_t)context->get_device();
  7810. } break;
  7811. case DRIVER_RESOURCE_VULKAN_PHYSICAL_DEVICE: {
  7812. return (uint64_t)context->get_physical_device();
  7813. } break;
  7814. case DRIVER_RESOURCE_VULKAN_INSTANCE: {
  7815. return (uint64_t)context->get_instance();
  7816. } break;
  7817. case DRIVER_RESOURCE_VULKAN_QUEUE: {
  7818. return (uint64_t)context->get_graphics_queue();
  7819. } break;
  7820. case DRIVER_RESOURCE_VULKAN_QUEUE_FAMILY_INDEX: {
  7821. return context->get_graphics_queue_family_index();
  7822. } break;
  7823. case DRIVER_RESOURCE_VULKAN_IMAGE: {
  7824. Texture *tex = texture_owner.get_or_null(p_rid);
  7825. ERR_FAIL_NULL_V(tex, 0);
  7826. return (uint64_t)tex->image;
  7827. } break;
  7828. case DRIVER_RESOURCE_VULKAN_IMAGE_VIEW: {
  7829. Texture *tex = texture_owner.get_or_null(p_rid);
  7830. ERR_FAIL_NULL_V(tex, 0);
  7831. return (uint64_t)tex->view;
  7832. } break;
  7833. case DRIVER_RESOURCE_VULKAN_IMAGE_NATIVE_TEXTURE_FORMAT: {
  7834. Texture *tex = texture_owner.get_or_null(p_rid);
  7835. ERR_FAIL_NULL_V(tex, 0);
  7836. return vulkan_formats[tex->format];
  7837. } break;
  7838. case DRIVER_RESOURCE_VULKAN_SAMPLER: {
  7839. VkSampler *sampler = sampler_owner.get_or_null(p_rid);
  7840. ERR_FAIL_NULL_V(sampler, 0);
  7841. return uint64_t(*sampler);
  7842. } break;
  7843. case DRIVER_RESOURCE_VULKAN_DESCRIPTOR_SET: {
  7844. UniformSet *uniform_set = uniform_set_owner.get_or_null(p_rid);
  7845. ERR_FAIL_NULL_V(uniform_set, 0);
  7846. return uint64_t(uniform_set->descriptor_set);
  7847. } break;
  7848. case DRIVER_RESOURCE_VULKAN_BUFFER: {
  7849. Buffer *buffer = nullptr;
  7850. if (vertex_buffer_owner.owns(p_rid)) {
  7851. buffer = vertex_buffer_owner.get_or_null(p_rid);
  7852. } else if (index_buffer_owner.owns(p_rid)) {
  7853. buffer = index_buffer_owner.get_or_null(p_rid);
  7854. } else if (uniform_buffer_owner.owns(p_rid)) {
  7855. buffer = uniform_buffer_owner.get_or_null(p_rid);
  7856. } else if (texture_buffer_owner.owns(p_rid)) {
  7857. buffer = &texture_buffer_owner.get_or_null(p_rid)->buffer;
  7858. } else if (storage_buffer_owner.owns(p_rid)) {
  7859. buffer = storage_buffer_owner.get_or_null(p_rid);
  7860. }
  7861. ERR_FAIL_NULL_V(buffer, 0);
  7862. return uint64_t(buffer->buffer);
  7863. } break;
  7864. case DRIVER_RESOURCE_VULKAN_COMPUTE_PIPELINE: {
  7865. ComputePipeline *compute_pipeline = compute_pipeline_owner.get_or_null(p_rid);
  7866. ERR_FAIL_NULL_V(compute_pipeline, 0);
  7867. return uint64_t(compute_pipeline->pipeline);
  7868. } break;
  7869. case DRIVER_RESOURCE_VULKAN_RENDER_PIPELINE: {
  7870. RenderPipeline *render_pipeline = render_pipeline_owner.get_or_null(p_rid);
  7871. ERR_FAIL_NULL_V(render_pipeline, 0);
  7872. return uint64_t(render_pipeline->pipeline);
  7873. } break;
  7874. default: {
  7875. // not supported for this driver
  7876. return 0;
  7877. } break;
  7878. }
  7879. }
  7880. uint32_t RenderingDeviceVulkan::get_captured_timestamps_count() const {
  7881. return frames[frame].timestamp_result_count;
  7882. }
  7883. uint64_t RenderingDeviceVulkan::get_captured_timestamps_frame() const {
  7884. return frames[frame].index;
  7885. }
  7886. static void mult64to128(uint64_t u, uint64_t v, uint64_t &h, uint64_t &l) {
  7887. uint64_t u1 = (u & 0xffffffff);
  7888. uint64_t v1 = (v & 0xffffffff);
  7889. uint64_t t = (u1 * v1);
  7890. uint64_t w3 = (t & 0xffffffff);
  7891. uint64_t k = (t >> 32);
  7892. u >>= 32;
  7893. t = (u * v1) + k;
  7894. k = (t & 0xffffffff);
  7895. uint64_t w1 = (t >> 32);
  7896. v >>= 32;
  7897. t = (u1 * v) + k;
  7898. k = (t >> 32);
  7899. h = (u * v) + w1 + k;
  7900. l = (t << 32) + w3;
  7901. }
  7902. uint64_t RenderingDeviceVulkan::get_captured_timestamp_gpu_time(uint32_t p_index) const {
  7903. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0);
  7904. // this sucks because timestampPeriod multiplier is a float, while the timestamp is 64 bits nanosecs.
  7905. // so, in cases like nvidia which give you enormous numbers and 1 as multiplier, multiplying is next to impossible
  7906. // need to do 128 bits fixed point multiplication to get the right value
  7907. uint64_t shift_bits = 16;
  7908. uint64_t h, l;
  7909. mult64to128(frames[frame].timestamp_result_values[p_index], uint64_t(double(limits.timestampPeriod) * double(1 << shift_bits)), h, l);
  7910. l >>= shift_bits;
  7911. l |= h << (64 - shift_bits);
  7912. return l;
  7913. }
  7914. uint64_t RenderingDeviceVulkan::get_captured_timestamp_cpu_time(uint32_t p_index) const {
  7915. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, 0);
  7916. return frames[frame].timestamp_cpu_result_values[p_index];
  7917. }
  7918. String RenderingDeviceVulkan::get_captured_timestamp_name(uint32_t p_index) const {
  7919. ERR_FAIL_UNSIGNED_INDEX_V(p_index, frames[frame].timestamp_result_count, String());
  7920. return frames[frame].timestamp_result_names[p_index];
  7921. }
  7922. uint64_t RenderingDeviceVulkan::limit_get(Limit p_limit) {
  7923. switch (p_limit) {
  7924. case LIMIT_MAX_BOUND_UNIFORM_SETS:
  7925. return limits.maxBoundDescriptorSets;
  7926. case LIMIT_MAX_FRAMEBUFFER_COLOR_ATTACHMENTS:
  7927. return limits.maxColorAttachments;
  7928. case LIMIT_MAX_TEXTURES_PER_UNIFORM_SET:
  7929. return limits.maxDescriptorSetSampledImages;
  7930. case LIMIT_MAX_SAMPLERS_PER_UNIFORM_SET:
  7931. return limits.maxDescriptorSetSamplers;
  7932. case LIMIT_MAX_STORAGE_BUFFERS_PER_UNIFORM_SET:
  7933. return limits.maxDescriptorSetStorageBuffers;
  7934. case LIMIT_MAX_STORAGE_IMAGES_PER_UNIFORM_SET:
  7935. return limits.maxDescriptorSetStorageImages;
  7936. case LIMIT_MAX_UNIFORM_BUFFERS_PER_UNIFORM_SET:
  7937. return limits.maxDescriptorSetUniformBuffers;
  7938. case LIMIT_MAX_DRAW_INDEXED_INDEX:
  7939. return limits.maxDrawIndexedIndexValue;
  7940. case LIMIT_MAX_FRAMEBUFFER_HEIGHT:
  7941. return limits.maxFramebufferHeight;
  7942. case LIMIT_MAX_FRAMEBUFFER_WIDTH:
  7943. return limits.maxFramebufferWidth;
  7944. case LIMIT_MAX_TEXTURE_ARRAY_LAYERS:
  7945. return limits.maxImageArrayLayers;
  7946. case LIMIT_MAX_TEXTURE_SIZE_1D:
  7947. return limits.maxImageDimension1D;
  7948. case LIMIT_MAX_TEXTURE_SIZE_2D:
  7949. return limits.maxImageDimension2D;
  7950. case LIMIT_MAX_TEXTURE_SIZE_3D:
  7951. return limits.maxImageDimension3D;
  7952. case LIMIT_MAX_TEXTURE_SIZE_CUBE:
  7953. return limits.maxImageDimensionCube;
  7954. case LIMIT_MAX_TEXTURES_PER_SHADER_STAGE:
  7955. return limits.maxPerStageDescriptorSampledImages;
  7956. case LIMIT_MAX_SAMPLERS_PER_SHADER_STAGE:
  7957. return limits.maxPerStageDescriptorSamplers;
  7958. case LIMIT_MAX_STORAGE_BUFFERS_PER_SHADER_STAGE:
  7959. return limits.maxPerStageDescriptorStorageBuffers;
  7960. case LIMIT_MAX_STORAGE_IMAGES_PER_SHADER_STAGE:
  7961. return limits.maxPerStageDescriptorStorageImages;
  7962. case LIMIT_MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE:
  7963. return limits.maxPerStageDescriptorUniformBuffers;
  7964. case LIMIT_MAX_PUSH_CONSTANT_SIZE:
  7965. return limits.maxPushConstantsSize;
  7966. case LIMIT_MAX_UNIFORM_BUFFER_SIZE:
  7967. return limits.maxUniformBufferRange;
  7968. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTE_OFFSET:
  7969. return limits.maxVertexInputAttributeOffset;
  7970. case LIMIT_MAX_VERTEX_INPUT_ATTRIBUTES:
  7971. return limits.maxVertexInputAttributes;
  7972. case LIMIT_MAX_VERTEX_INPUT_BINDINGS:
  7973. return limits.maxVertexInputBindings;
  7974. case LIMIT_MAX_VERTEX_INPUT_BINDING_STRIDE:
  7975. return limits.maxVertexInputBindingStride;
  7976. case LIMIT_MIN_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
  7977. return limits.minUniformBufferOffsetAlignment;
  7978. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_X:
  7979. return limits.maxComputeWorkGroupCount[0];
  7980. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Y:
  7981. return limits.maxComputeWorkGroupCount[1];
  7982. case LIMIT_MAX_COMPUTE_WORKGROUP_COUNT_Z:
  7983. return limits.maxComputeWorkGroupCount[2];
  7984. case LIMIT_MAX_COMPUTE_WORKGROUP_INVOCATIONS:
  7985. return limits.maxComputeWorkGroupInvocations;
  7986. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_X:
  7987. return limits.maxComputeWorkGroupSize[0];
  7988. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Y:
  7989. return limits.maxComputeWorkGroupSize[1];
  7990. case LIMIT_MAX_COMPUTE_WORKGROUP_SIZE_Z:
  7991. return limits.maxComputeWorkGroupSize[2];
  7992. default:
  7993. ERR_FAIL_V(0);
  7994. }
  7995. return 0;
  7996. }
  7997. void RenderingDeviceVulkan::finalize() {
  7998. //free all resources
  7999. _flush(false);
  8000. _free_rids(render_pipeline_owner, "Pipeline");
  8001. _free_rids(compute_pipeline_owner, "Compute");
  8002. _free_rids(uniform_set_owner, "UniformSet");
  8003. _free_rids(texture_buffer_owner, "TextureBuffer");
  8004. _free_rids(storage_buffer_owner, "StorageBuffer");
  8005. _free_rids(uniform_buffer_owner, "UniformBuffer");
  8006. _free_rids(shader_owner, "Shader");
  8007. _free_rids(index_array_owner, "IndexArray");
  8008. _free_rids(index_buffer_owner, "IndexBuffer");
  8009. _free_rids(vertex_array_owner, "VertexArray");
  8010. _free_rids(vertex_buffer_owner, "VertexBuffer");
  8011. _free_rids(framebuffer_owner, "Framebuffer");
  8012. _free_rids(sampler_owner, "Sampler");
  8013. {
  8014. //for textures it's a bit more difficult because they may be shared
  8015. List<RID> owned;
  8016. texture_owner.get_owned_list(&owned);
  8017. if (owned.size()) {
  8018. if (owned.size() == 1) {
  8019. WARN_PRINT("1 RID of type \"Texture\" was leaked.");
  8020. } else {
  8021. WARN_PRINT(vformat("%d RIDs of type \"Texture\" were leaked.", owned.size()));
  8022. }
  8023. //free shared first
  8024. for (List<RID>::Element *E = owned.front(); E;) {
  8025. List<RID>::Element *N = E->next();
  8026. if (texture_is_shared(E->get())) {
  8027. free(E->get());
  8028. owned.erase(E);
  8029. }
  8030. E = N;
  8031. }
  8032. //free non shared second, this will avoid an error trying to free unexisting textures due to dependencies.
  8033. for (const RID &E : owned) {
  8034. free(E);
  8035. }
  8036. }
  8037. }
  8038. //free everything pending
  8039. for (int i = 0; i < frame_count; i++) {
  8040. int f = (frame + i) % frame_count;
  8041. _free_pending_resources(f);
  8042. vkDestroyCommandPool(device, frames[i].command_pool, nullptr);
  8043. vkDestroyQueryPool(device, frames[i].timestamp_pool, nullptr);
  8044. }
  8045. for (int i = 0; i < split_draw_list_allocators.size(); i++) {
  8046. vkDestroyCommandPool(device, split_draw_list_allocators[i].command_pool, nullptr);
  8047. }
  8048. frames.clear();
  8049. for (int i = 0; i < staging_buffer_blocks.size(); i++) {
  8050. vmaDestroyBuffer(allocator, staging_buffer_blocks[i].buffer, staging_buffer_blocks[i].allocation);
  8051. }
  8052. while (small_allocs_pools.size()) {
  8053. HashMap<uint32_t, VmaPool>::Iterator E = small_allocs_pools.begin();
  8054. vmaDestroyPool(allocator, E->value);
  8055. small_allocs_pools.remove(E);
  8056. }
  8057. vmaDestroyAllocator(allocator);
  8058. while (vertex_formats.size()) {
  8059. HashMap<VertexFormatID, VertexDescriptionCache>::Iterator temp = vertex_formats.begin();
  8060. memdelete_arr(temp->value.bindings);
  8061. memdelete_arr(temp->value.attributes);
  8062. vertex_formats.remove(temp);
  8063. }
  8064. for (KeyValue<FramebufferFormatID, FramebufferFormat> &E : framebuffer_formats) {
  8065. vkDestroyRenderPass(device, E.value.render_pass, nullptr);
  8066. }
  8067. framebuffer_formats.clear();
  8068. //all these should be clear at this point
  8069. ERR_FAIL_COND(descriptor_pools.size());
  8070. ERR_FAIL_COND(dependency_map.size());
  8071. ERR_FAIL_COND(reverse_dependency_map.size());
  8072. }
  8073. RenderingDevice *RenderingDeviceVulkan::create_local_device() {
  8074. RenderingDeviceVulkan *rd = memnew(RenderingDeviceVulkan);
  8075. rd->initialize(context, true);
  8076. return rd;
  8077. }
  8078. RenderingDeviceVulkan::RenderingDeviceVulkan() {
  8079. device_capabilities.device_family = DEVICE_VULKAN;
  8080. }
  8081. RenderingDeviceVulkan::~RenderingDeviceVulkan() {
  8082. if (local_device.is_valid()) {
  8083. finalize();
  8084. context->local_device_free(local_device);
  8085. }
  8086. }