rendering_device_vulkan.cpp 375 KB

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