rendering_device_vulkan.cpp 295 KB

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