rendering_device_vulkan.cpp 372 KB

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