rendering_device_vulkan.cpp 401 KB

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