rendering_device_vulkan.cpp 283 KB

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