rendering_device_vulkan.cpp 395 KB

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