rendering_device_vulkan.cpp 361 KB

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