SDL_gpu_vulkan.c 438 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #ifdef SDL_GPU_VULKAN
  20. // Needed for VK_KHR_portability_subset
  21. #define VK_ENABLE_BETA_EXTENSIONS
  22. #define VK_NO_PROTOTYPES
  23. #include "../../video/khronos/vulkan/vulkan.h"
  24. #include <SDL3/SDL_vulkan.h>
  25. #include "../SDL_sysgpu.h"
  26. #define VULKAN_INTERNAL_clamp(val, min, max) SDL_max(min, SDL_min(val, max))
  27. // Global Vulkan Loader Entry Points
  28. static PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL;
  29. #define VULKAN_GLOBAL_FUNCTION(name) \
  30. static PFN_##name name = NULL;
  31. #include "SDL_gpu_vulkan_vkfuncs.h"
  32. typedef struct VulkanExtensions
  33. {
  34. // These extensions are required!
  35. // Globally supported
  36. Uint8 KHR_swapchain;
  37. // Core since 1.1, needed for negative VkViewport::height
  38. Uint8 KHR_maintenance1;
  39. // These extensions are optional!
  40. // Core since 1.2, but requires annoying paperwork to implement
  41. Uint8 KHR_driver_properties;
  42. // Only required for special implementations (i.e. MoltenVK)
  43. Uint8 KHR_portability_subset;
  44. // Only required for decoding HDR ASTC textures
  45. Uint8 EXT_texture_compression_astc_hdr;
  46. } VulkanExtensions;
  47. // Defines
  48. #define SMALL_ALLOCATION_THRESHOLD 2097152 // 2 MiB
  49. #define SMALL_ALLOCATION_SIZE 16777216 // 16 MiB
  50. #define LARGE_ALLOCATION_INCREMENT 67108864 // 64 MiB
  51. #define MAX_UBO_SECTION_SIZE 4096 // 4 KiB
  52. #define DESCRIPTOR_POOL_SIZE 128
  53. #define WINDOW_PROPERTY_DATA "SDL_GPUVulkanWindowPropertyData"
  54. #define IDENTITY_SWIZZLE \
  55. { \
  56. VK_COMPONENT_SWIZZLE_IDENTITY, \
  57. VK_COMPONENT_SWIZZLE_IDENTITY, \
  58. VK_COMPONENT_SWIZZLE_IDENTITY, \
  59. VK_COMPONENT_SWIZZLE_IDENTITY \
  60. }
  61. #define NULL_DESC_LAYOUT (VkDescriptorSetLayout)0
  62. #define NULL_PIPELINE_LAYOUT (VkPipelineLayout)0
  63. #define NULL_RENDER_PASS (SDL_GPURenderPass *)0
  64. #define EXPAND_ELEMENTS_IF_NEEDED(arr, initialValue, type) \
  65. do { \
  66. if (arr->count == arr->capacity) { \
  67. if (arr->capacity == 0) { \
  68. arr->capacity = initialValue; \
  69. } else { \
  70. arr->capacity *= 2; \
  71. } \
  72. arr->elements = (type *)SDL_realloc( \
  73. arr->elements, \
  74. arr->capacity * sizeof(type)); \
  75. } \
  76. } while (0)
  77. #define MOVE_ARRAY_CONTENTS_AND_RESET(i, dstArr, dstCount, srcArr, srcCount) \
  78. do { \
  79. for ((i) = 0; (i) < (srcCount); (i) += 1) { \
  80. (dstArr)[i] = (srcArr)[i]; \
  81. } \
  82. (dstCount) = (srcCount); \
  83. (srcCount) = 0; \
  84. while (0)
  85. // Conversions
  86. static const Uint8 DEVICE_PRIORITY_HIGHPERFORMANCE[] = {
  87. 0, // VK_PHYSICAL_DEVICE_TYPE_OTHER
  88. 3, // VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU
  89. 4, // VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU
  90. 2, // VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU
  91. 1 // VK_PHYSICAL_DEVICE_TYPE_CPU
  92. };
  93. static const Uint8 DEVICE_PRIORITY_LOWPOWER[] = {
  94. 0, // VK_PHYSICAL_DEVICE_TYPE_OTHER
  95. 4, // VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU
  96. 3, // VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU
  97. 2, // VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU
  98. 1 // VK_PHYSICAL_DEVICE_TYPE_CPU
  99. };
  100. static VkPresentModeKHR SDLToVK_PresentMode[] = {
  101. VK_PRESENT_MODE_FIFO_KHR,
  102. VK_PRESENT_MODE_IMMEDIATE_KHR,
  103. VK_PRESENT_MODE_MAILBOX_KHR
  104. };
  105. static VkFormat SDLToVK_TextureFormat[] = {
  106. VK_FORMAT_UNDEFINED, // INVALID
  107. VK_FORMAT_R8_UNORM, // A8_UNORM
  108. VK_FORMAT_R8_UNORM, // R8_UNORM
  109. VK_FORMAT_R8G8_UNORM, // R8G8_UNORM
  110. VK_FORMAT_R8G8B8A8_UNORM, // R8G8B8A8_UNORM
  111. VK_FORMAT_R16_UNORM, // R16_UNORM
  112. VK_FORMAT_R16G16_UNORM, // R16G16_UNORM
  113. VK_FORMAT_R16G16B16A16_UNORM, // R16G16B16A16_UNORM
  114. VK_FORMAT_A2B10G10R10_UNORM_PACK32, // R10G10B10A2_UNORM
  115. VK_FORMAT_R5G6B5_UNORM_PACK16, // B5G6R5_UNORM
  116. VK_FORMAT_A1R5G5B5_UNORM_PACK16, // B5G5R5A1_UNORM
  117. VK_FORMAT_B4G4R4A4_UNORM_PACK16, // B4G4R4A4_UNORM
  118. VK_FORMAT_B8G8R8A8_UNORM, // B8G8R8A8_UNORM
  119. VK_FORMAT_BC1_RGBA_UNORM_BLOCK, // BC1_UNORM
  120. VK_FORMAT_BC2_UNORM_BLOCK, // BC2_UNORM
  121. VK_FORMAT_BC3_UNORM_BLOCK, // BC3_UNORM
  122. VK_FORMAT_BC4_UNORM_BLOCK, // BC4_UNORM
  123. VK_FORMAT_BC5_UNORM_BLOCK, // BC5_UNORM
  124. VK_FORMAT_BC7_UNORM_BLOCK, // BC7_UNORM
  125. VK_FORMAT_BC6H_SFLOAT_BLOCK, // BC6H_FLOAT
  126. VK_FORMAT_BC6H_UFLOAT_BLOCK, // BC6H_UFLOAT
  127. VK_FORMAT_R8_SNORM, // R8_SNORM
  128. VK_FORMAT_R8G8_SNORM, // R8G8_SNORM
  129. VK_FORMAT_R8G8B8A8_SNORM, // R8G8B8A8_SNORM
  130. VK_FORMAT_R16_SNORM, // R16_SNORM
  131. VK_FORMAT_R16G16_SNORM, // R16G16_SNORM
  132. VK_FORMAT_R16G16B16A16_SNORM, // R16G16B16A16_SNORM
  133. VK_FORMAT_R16_SFLOAT, // R16_FLOAT
  134. VK_FORMAT_R16G16_SFLOAT, // R16G16_FLOAT
  135. VK_FORMAT_R16G16B16A16_SFLOAT, // R16G16B16A16_FLOAT
  136. VK_FORMAT_R32_SFLOAT, // R32_FLOAT
  137. VK_FORMAT_R32G32_SFLOAT, // R32G32_FLOAT
  138. VK_FORMAT_R32G32B32A32_SFLOAT, // R32G32B32A32_FLOAT
  139. VK_FORMAT_B10G11R11_UFLOAT_PACK32, // R11G11B10_UFLOAT
  140. VK_FORMAT_R8_UINT, // R8_UINT
  141. VK_FORMAT_R8G8_UINT, // R8G8_UINT
  142. VK_FORMAT_R8G8B8A8_UINT, // R8G8B8A8_UINT
  143. VK_FORMAT_R16_UINT, // R16_UINT
  144. VK_FORMAT_R16G16_UINT, // R16G16_UINT
  145. VK_FORMAT_R16G16B16A16_UINT, // R16G16B16A16_UINT
  146. VK_FORMAT_R32_UINT, // R32_UINT
  147. VK_FORMAT_R32G32_UINT, // R32G32_UINT
  148. VK_FORMAT_R32G32B32A32_UINT, // R32G32B32A32_UINT
  149. VK_FORMAT_R8_SINT, // R8_INT
  150. VK_FORMAT_R8G8_SINT, // R8G8_INT
  151. VK_FORMAT_R8G8B8A8_SINT, // R8G8B8A8_INT
  152. VK_FORMAT_R16_SINT, // R16_INT
  153. VK_FORMAT_R16G16_SINT, // R16G16_INT
  154. VK_FORMAT_R16G16B16A16_SINT, // R16G16B16A16_INT
  155. VK_FORMAT_R32_SINT, // R32_INT
  156. VK_FORMAT_R32G32_SINT, // R32G32_INT
  157. VK_FORMAT_R32G32B32A32_SINT, // R32G32B32A32_INT
  158. VK_FORMAT_R8G8B8A8_SRGB, // R8G8B8A8_UNORM_SRGB
  159. VK_FORMAT_B8G8R8A8_SRGB, // B8G8R8A8_UNORM_SRGB
  160. VK_FORMAT_BC1_RGBA_SRGB_BLOCK, // BC1_UNORM_SRGB
  161. VK_FORMAT_BC2_SRGB_BLOCK, // BC3_UNORM_SRGB
  162. VK_FORMAT_BC3_SRGB_BLOCK, // BC3_UNORM_SRGB
  163. VK_FORMAT_BC7_SRGB_BLOCK, // BC7_UNORM_SRGB
  164. VK_FORMAT_D16_UNORM, // D16_UNORM
  165. VK_FORMAT_X8_D24_UNORM_PACK32, // D24_UNORM
  166. VK_FORMAT_D32_SFLOAT, // D32_FLOAT
  167. VK_FORMAT_D24_UNORM_S8_UINT, // D24_UNORM_S8_UINT
  168. VK_FORMAT_D32_SFLOAT_S8_UINT, // D32_FLOAT_S8_UINT
  169. VK_FORMAT_ASTC_4x4_UNORM_BLOCK, // ASTC_4x4_UNORM
  170. VK_FORMAT_ASTC_5x4_UNORM_BLOCK, // ASTC_5x4_UNORM
  171. VK_FORMAT_ASTC_5x5_UNORM_BLOCK, // ASTC_5x5_UNORM
  172. VK_FORMAT_ASTC_6x5_UNORM_BLOCK, // ASTC_6x5_UNORM
  173. VK_FORMAT_ASTC_6x6_UNORM_BLOCK, // ASTC_6x6_UNORM
  174. VK_FORMAT_ASTC_8x5_UNORM_BLOCK, // ASTC_8x5_UNORM
  175. VK_FORMAT_ASTC_8x6_UNORM_BLOCK, // ASTC_8x6_UNORM
  176. VK_FORMAT_ASTC_8x8_UNORM_BLOCK, // ASTC_8x8_UNORM
  177. VK_FORMAT_ASTC_10x5_UNORM_BLOCK, // ASTC_10x5_UNORM
  178. VK_FORMAT_ASTC_10x6_UNORM_BLOCK, // ASTC_10x6_UNORM
  179. VK_FORMAT_ASTC_10x8_UNORM_BLOCK, // ASTC_10x8_UNORM
  180. VK_FORMAT_ASTC_10x10_UNORM_BLOCK, // ASTC_10x10_UNORM
  181. VK_FORMAT_ASTC_12x10_UNORM_BLOCK, // ASTC_12x10_UNORM
  182. VK_FORMAT_ASTC_12x12_UNORM_BLOCK, // ASTC_12x12_UNORM
  183. VK_FORMAT_ASTC_4x4_SRGB_BLOCK, // ASTC_4x4_UNORM_SRGB
  184. VK_FORMAT_ASTC_5x4_SRGB_BLOCK, // ASTC_5x4_UNORM_SRGB
  185. VK_FORMAT_ASTC_5x5_SRGB_BLOCK, // ASTC_5x5_UNORM_SRGB
  186. VK_FORMAT_ASTC_6x5_SRGB_BLOCK, // ASTC_6x5_UNORM_SRGB
  187. VK_FORMAT_ASTC_6x6_SRGB_BLOCK, // ASTC_6x6_UNORM_SRGB
  188. VK_FORMAT_ASTC_8x5_SRGB_BLOCK, // ASTC_8x5_UNORM_SRGB
  189. VK_FORMAT_ASTC_8x6_SRGB_BLOCK, // ASTC_8x6_UNORM_SRGB
  190. VK_FORMAT_ASTC_8x8_SRGB_BLOCK, // ASTC_8x8_UNORM_SRGB
  191. VK_FORMAT_ASTC_10x5_SRGB_BLOCK, // ASTC_10x5_UNORM_SRGB
  192. VK_FORMAT_ASTC_10x6_SRGB_BLOCK, // ASTC_10x6_UNORM_SRGB
  193. VK_FORMAT_ASTC_10x8_SRGB_BLOCK, // ASTC_10x8_UNORM_SRGB
  194. VK_FORMAT_ASTC_10x10_SRGB_BLOCK, // ASTC_10x10_UNORM_SRGB
  195. VK_FORMAT_ASTC_12x10_SRGB_BLOCK, // ASTC_12x10_UNORM_SRGB
  196. VK_FORMAT_ASTC_12x12_SRGB_BLOCK, // ASTC_12x12_UNORM_SRGB
  197. VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT, // ASTC_4x4_FLOAT
  198. VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT, // ASTC_5x4_FLOAT
  199. VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT, // ASTC_5x5_FLOAT
  200. VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT, // ASTC_6x5_FLOAT
  201. VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT, // ASTC_6x6_FLOAT
  202. VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT, // ASTC_8x5_FLOAT
  203. VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT, // ASTC_8x6_FLOAT
  204. VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT, // ASTC_8x8_FLOAT
  205. VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT, // ASTC_10x5_FLOAT
  206. VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT, // ASTC_10x6_FLOAT
  207. VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT, // ASTC_10x8_FLOAT
  208. VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT, // ASTC_10x10_FLOAT
  209. VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT, // ASTC_12x10_FLOAT
  210. VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK // ASTC_12x12_FLOAT
  211. };
  212. SDL_COMPILE_TIME_ASSERT(SDLToVK_TextureFormat, SDL_arraysize(SDLToVK_TextureFormat) == SDL_GPU_TEXTUREFORMAT_MAX_ENUM_VALUE);
  213. static VkComponentMapping SwizzleForSDLFormat(SDL_GPUTextureFormat format)
  214. {
  215. if (format == SDL_GPU_TEXTUREFORMAT_A8_UNORM) {
  216. // TODO: use VK_FORMAT_A8_UNORM_KHR from VK_KHR_maintenance5 when available
  217. return (VkComponentMapping){
  218. VK_COMPONENT_SWIZZLE_ZERO,
  219. VK_COMPONENT_SWIZZLE_ZERO,
  220. VK_COMPONENT_SWIZZLE_ZERO,
  221. VK_COMPONENT_SWIZZLE_R,
  222. };
  223. }
  224. if (format == SDL_GPU_TEXTUREFORMAT_B4G4R4A4_UNORM) {
  225. // ARGB -> BGRA
  226. // TODO: use VK_FORMAT_A4R4G4B4_UNORM_PACK16_EXT from VK_EXT_4444_formats when available
  227. return (VkComponentMapping){
  228. VK_COMPONENT_SWIZZLE_G,
  229. VK_COMPONENT_SWIZZLE_R,
  230. VK_COMPONENT_SWIZZLE_A,
  231. VK_COMPONENT_SWIZZLE_B,
  232. };
  233. }
  234. return (VkComponentMapping)IDENTITY_SWIZZLE;
  235. }
  236. static VkFormat SwapchainCompositionToFormat[] = {
  237. VK_FORMAT_B8G8R8A8_UNORM, // SDR
  238. VK_FORMAT_B8G8R8A8_SRGB, // SDR_LINEAR
  239. VK_FORMAT_R16G16B16A16_SFLOAT, // HDR_EXTENDED_LINEAR
  240. VK_FORMAT_A2B10G10R10_UNORM_PACK32 // HDR10_ST2084
  241. };
  242. static VkFormat SwapchainCompositionToFallbackFormat[] = {
  243. VK_FORMAT_R8G8B8A8_UNORM, // SDR
  244. VK_FORMAT_R8G8B8A8_SRGB, // SDR_LINEAR
  245. VK_FORMAT_UNDEFINED, // HDR_EXTENDED_LINEAR (no fallback)
  246. VK_FORMAT_UNDEFINED // HDR10_ST2084 (no fallback)
  247. };
  248. static SDL_GPUTextureFormat SwapchainCompositionToSDLFormat(
  249. SDL_GPUSwapchainComposition composition,
  250. bool usingFallback)
  251. {
  252. switch (composition) {
  253. case SDL_GPU_SWAPCHAINCOMPOSITION_SDR:
  254. return usingFallback ? SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM : SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM;
  255. case SDL_GPU_SWAPCHAINCOMPOSITION_SDR_LINEAR:
  256. return usingFallback ? SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB : SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB;
  257. case SDL_GPU_SWAPCHAINCOMPOSITION_HDR_EXTENDED_LINEAR:
  258. return SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT;
  259. case SDL_GPU_SWAPCHAINCOMPOSITION_HDR10_ST2084:
  260. return SDL_GPU_TEXTUREFORMAT_R10G10B10A2_UNORM;
  261. default:
  262. return SDL_GPU_TEXTUREFORMAT_INVALID;
  263. }
  264. }
  265. static VkColorSpaceKHR SwapchainCompositionToColorSpace[] = {
  266. VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, // SDR
  267. VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, // SDR_LINEAR
  268. VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT, // HDR_EXTENDED_LINEAR
  269. VK_COLOR_SPACE_HDR10_ST2084_EXT // HDR10_ST2084
  270. };
  271. static VkComponentMapping SwapchainCompositionSwizzle[] = {
  272. IDENTITY_SWIZZLE, // SDR
  273. IDENTITY_SWIZZLE, // SDR_LINEAR
  274. IDENTITY_SWIZZLE, // HDR_EXTENDED_LINEAR
  275. {
  276. // HDR10_ST2084
  277. VK_COMPONENT_SWIZZLE_R,
  278. VK_COMPONENT_SWIZZLE_G,
  279. VK_COMPONENT_SWIZZLE_B,
  280. VK_COMPONENT_SWIZZLE_A,
  281. }
  282. };
  283. static VkFormat SDLToVK_VertexFormat[] = {
  284. VK_FORMAT_UNDEFINED, // INVALID
  285. VK_FORMAT_R32_SINT, // INT
  286. VK_FORMAT_R32G32_SINT, // INT2
  287. VK_FORMAT_R32G32B32_SINT, // INT3
  288. VK_FORMAT_R32G32B32A32_SINT, // INT4
  289. VK_FORMAT_R32_UINT, // UINT
  290. VK_FORMAT_R32G32_UINT, // UINT2
  291. VK_FORMAT_R32G32B32_UINT, // UINT3
  292. VK_FORMAT_R32G32B32A32_UINT, // UINT4
  293. VK_FORMAT_R32_SFLOAT, // FLOAT
  294. VK_FORMAT_R32G32_SFLOAT, // FLOAT2
  295. VK_FORMAT_R32G32B32_SFLOAT, // FLOAT3
  296. VK_FORMAT_R32G32B32A32_SFLOAT, // FLOAT4
  297. VK_FORMAT_R8G8_SINT, // BYTE2
  298. VK_FORMAT_R8G8B8A8_SINT, // BYTE4
  299. VK_FORMAT_R8G8_UINT, // UBYTE2
  300. VK_FORMAT_R8G8B8A8_UINT, // UBYTE4
  301. VK_FORMAT_R8G8_SNORM, // BYTE2_NORM
  302. VK_FORMAT_R8G8B8A8_SNORM, // BYTE4_NORM
  303. VK_FORMAT_R8G8_UNORM, // UBYTE2_NORM
  304. VK_FORMAT_R8G8B8A8_UNORM, // UBYTE4_NORM
  305. VK_FORMAT_R16G16_SINT, // SHORT2
  306. VK_FORMAT_R16G16B16A16_SINT, // SHORT4
  307. VK_FORMAT_R16G16_UINT, // USHORT2
  308. VK_FORMAT_R16G16B16A16_UINT, // USHORT4
  309. VK_FORMAT_R16G16_SNORM, // SHORT2_NORM
  310. VK_FORMAT_R16G16B16A16_SNORM, // SHORT4_NORM
  311. VK_FORMAT_R16G16_UNORM, // USHORT2_NORM
  312. VK_FORMAT_R16G16B16A16_UNORM, // USHORT4_NORM
  313. VK_FORMAT_R16G16_SFLOAT, // HALF2
  314. VK_FORMAT_R16G16B16A16_SFLOAT // HALF4
  315. };
  316. SDL_COMPILE_TIME_ASSERT(SDLToVK_VertexFormat, SDL_arraysize(SDLToVK_VertexFormat) == SDL_GPU_VERTEXELEMENTFORMAT_MAX_ENUM_VALUE);
  317. static VkIndexType SDLToVK_IndexType[] = {
  318. VK_INDEX_TYPE_UINT16,
  319. VK_INDEX_TYPE_UINT32
  320. };
  321. static VkPrimitiveTopology SDLToVK_PrimitiveType[] = {
  322. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
  323. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
  324. VK_PRIMITIVE_TOPOLOGY_LINE_LIST,
  325. VK_PRIMITIVE_TOPOLOGY_LINE_STRIP,
  326. VK_PRIMITIVE_TOPOLOGY_POINT_LIST
  327. };
  328. static VkCullModeFlags SDLToVK_CullMode[] = {
  329. VK_CULL_MODE_NONE,
  330. VK_CULL_MODE_FRONT_BIT,
  331. VK_CULL_MODE_BACK_BIT,
  332. VK_CULL_MODE_FRONT_AND_BACK
  333. };
  334. static VkFrontFace SDLToVK_FrontFace[] = {
  335. VK_FRONT_FACE_COUNTER_CLOCKWISE,
  336. VK_FRONT_FACE_CLOCKWISE
  337. };
  338. static VkBlendFactor SDLToVK_BlendFactor[] = {
  339. VK_BLEND_FACTOR_ZERO, // INVALID
  340. VK_BLEND_FACTOR_ZERO,
  341. VK_BLEND_FACTOR_ONE,
  342. VK_BLEND_FACTOR_SRC_COLOR,
  343. VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR,
  344. VK_BLEND_FACTOR_DST_COLOR,
  345. VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR,
  346. VK_BLEND_FACTOR_SRC_ALPHA,
  347. VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
  348. VK_BLEND_FACTOR_DST_ALPHA,
  349. VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA,
  350. VK_BLEND_FACTOR_CONSTANT_COLOR,
  351. VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR,
  352. VK_BLEND_FACTOR_SRC_ALPHA_SATURATE
  353. };
  354. SDL_COMPILE_TIME_ASSERT(SDLToVK_BlendFactor, SDL_arraysize(SDLToVK_BlendFactor) == SDL_GPU_BLENDFACTOR_MAX_ENUM_VALUE);
  355. static VkBlendOp SDLToVK_BlendOp[] = {
  356. VK_BLEND_OP_ADD, // INVALID
  357. VK_BLEND_OP_ADD,
  358. VK_BLEND_OP_SUBTRACT,
  359. VK_BLEND_OP_REVERSE_SUBTRACT,
  360. VK_BLEND_OP_MIN,
  361. VK_BLEND_OP_MAX
  362. };
  363. SDL_COMPILE_TIME_ASSERT(SDLToVK_BlendOp, SDL_arraysize(SDLToVK_BlendOp) == SDL_GPU_BLENDOP_MAX_ENUM_VALUE);
  364. static VkCompareOp SDLToVK_CompareOp[] = {
  365. VK_COMPARE_OP_NEVER, // INVALID
  366. VK_COMPARE_OP_NEVER,
  367. VK_COMPARE_OP_LESS,
  368. VK_COMPARE_OP_EQUAL,
  369. VK_COMPARE_OP_LESS_OR_EQUAL,
  370. VK_COMPARE_OP_GREATER,
  371. VK_COMPARE_OP_NOT_EQUAL,
  372. VK_COMPARE_OP_GREATER_OR_EQUAL,
  373. VK_COMPARE_OP_ALWAYS
  374. };
  375. SDL_COMPILE_TIME_ASSERT(SDLToVK_CompareOp, SDL_arraysize(SDLToVK_CompareOp) == SDL_GPU_COMPAREOP_MAX_ENUM_VALUE);
  376. static VkStencilOp SDLToVK_StencilOp[] = {
  377. VK_STENCIL_OP_KEEP, // INVALID
  378. VK_STENCIL_OP_KEEP,
  379. VK_STENCIL_OP_ZERO,
  380. VK_STENCIL_OP_REPLACE,
  381. VK_STENCIL_OP_INCREMENT_AND_CLAMP,
  382. VK_STENCIL_OP_DECREMENT_AND_CLAMP,
  383. VK_STENCIL_OP_INVERT,
  384. VK_STENCIL_OP_INCREMENT_AND_WRAP,
  385. VK_STENCIL_OP_DECREMENT_AND_WRAP
  386. };
  387. SDL_COMPILE_TIME_ASSERT(SDLToVK_StencilOp, SDL_arraysize(SDLToVK_StencilOp) == SDL_GPU_STENCILOP_MAX_ENUM_VALUE);
  388. static VkAttachmentLoadOp SDLToVK_LoadOp[] = {
  389. VK_ATTACHMENT_LOAD_OP_LOAD,
  390. VK_ATTACHMENT_LOAD_OP_CLEAR,
  391. VK_ATTACHMENT_LOAD_OP_DONT_CARE
  392. };
  393. static VkAttachmentStoreOp SDLToVK_StoreOp[] = {
  394. VK_ATTACHMENT_STORE_OP_STORE,
  395. VK_ATTACHMENT_STORE_OP_DONT_CARE,
  396. VK_ATTACHMENT_STORE_OP_DONT_CARE,
  397. VK_ATTACHMENT_STORE_OP_STORE
  398. };
  399. static VkSampleCountFlagBits SDLToVK_SampleCount[] = {
  400. VK_SAMPLE_COUNT_1_BIT,
  401. VK_SAMPLE_COUNT_2_BIT,
  402. VK_SAMPLE_COUNT_4_BIT,
  403. VK_SAMPLE_COUNT_8_BIT
  404. };
  405. static VkVertexInputRate SDLToVK_VertexInputRate[] = {
  406. VK_VERTEX_INPUT_RATE_VERTEX,
  407. VK_VERTEX_INPUT_RATE_INSTANCE
  408. };
  409. static VkFilter SDLToVK_Filter[] = {
  410. VK_FILTER_NEAREST,
  411. VK_FILTER_LINEAR
  412. };
  413. static VkSamplerMipmapMode SDLToVK_SamplerMipmapMode[] = {
  414. VK_SAMPLER_MIPMAP_MODE_NEAREST,
  415. VK_SAMPLER_MIPMAP_MODE_LINEAR
  416. };
  417. static VkSamplerAddressMode SDLToVK_SamplerAddressMode[] = {
  418. VK_SAMPLER_ADDRESS_MODE_REPEAT,
  419. VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT,
  420. VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE
  421. };
  422. // Structures
  423. typedef struct VulkanMemoryAllocation VulkanMemoryAllocation;
  424. typedef struct VulkanBuffer VulkanBuffer;
  425. typedef struct VulkanBufferContainer VulkanBufferContainer;
  426. typedef struct VulkanUniformBuffer VulkanUniformBuffer;
  427. typedef struct VulkanTexture VulkanTexture;
  428. typedef struct VulkanTextureContainer VulkanTextureContainer;
  429. typedef struct VulkanFenceHandle
  430. {
  431. VkFence fence;
  432. SDL_AtomicInt referenceCount;
  433. } VulkanFenceHandle;
  434. // Memory Allocation
  435. typedef struct VulkanMemoryFreeRegion
  436. {
  437. VulkanMemoryAllocation *allocation;
  438. VkDeviceSize offset;
  439. VkDeviceSize size;
  440. Uint32 allocationIndex;
  441. Uint32 sortedIndex;
  442. } VulkanMemoryFreeRegion;
  443. typedef struct VulkanMemoryUsedRegion
  444. {
  445. VulkanMemoryAllocation *allocation;
  446. VkDeviceSize offset;
  447. VkDeviceSize size;
  448. VkDeviceSize resourceOffset; // differs from offset based on alignment
  449. VkDeviceSize resourceSize; // differs from size based on alignment
  450. VkDeviceSize alignment;
  451. Uint8 isBuffer;
  452. union
  453. {
  454. VulkanBuffer *vulkanBuffer;
  455. VulkanTexture *vulkanTexture;
  456. };
  457. } VulkanMemoryUsedRegion;
  458. typedef struct VulkanMemorySubAllocator
  459. {
  460. Uint32 memoryTypeIndex;
  461. VulkanMemoryAllocation **allocations;
  462. Uint32 allocationCount;
  463. VulkanMemoryFreeRegion **sortedFreeRegions;
  464. Uint32 sortedFreeRegionCount;
  465. Uint32 sortedFreeRegionCapacity;
  466. } VulkanMemorySubAllocator;
  467. struct VulkanMemoryAllocation
  468. {
  469. VulkanMemorySubAllocator *allocator;
  470. VkDeviceMemory memory;
  471. VkDeviceSize size;
  472. VulkanMemoryUsedRegion **usedRegions;
  473. Uint32 usedRegionCount;
  474. Uint32 usedRegionCapacity;
  475. VulkanMemoryFreeRegion **freeRegions;
  476. Uint32 freeRegionCount;
  477. Uint32 freeRegionCapacity;
  478. Uint8 availableForAllocation;
  479. VkDeviceSize freeSpace;
  480. VkDeviceSize usedSpace;
  481. Uint8 *mapPointer;
  482. SDL_Mutex *memoryLock;
  483. };
  484. typedef struct VulkanMemoryAllocator
  485. {
  486. VulkanMemorySubAllocator subAllocators[VK_MAX_MEMORY_TYPES];
  487. } VulkanMemoryAllocator;
  488. // Memory structures
  489. typedef enum VulkanBufferType
  490. {
  491. VULKAN_BUFFER_TYPE_GPU,
  492. VULKAN_BUFFER_TYPE_UNIFORM,
  493. VULKAN_BUFFER_TYPE_TRANSFER
  494. } VulkanBufferType;
  495. struct VulkanBuffer
  496. {
  497. VulkanBufferContainer *container;
  498. Uint32 containerIndex;
  499. VkBuffer buffer;
  500. VulkanMemoryUsedRegion *usedRegion;
  501. // Needed for uniforms and defrag
  502. VulkanBufferType type;
  503. SDL_GPUBufferUsageFlags usage;
  504. VkDeviceSize size;
  505. SDL_AtomicInt referenceCount;
  506. bool transitioned;
  507. bool markedForDestroy; // so that defrag doesn't double-free
  508. VulkanUniformBuffer *uniformBufferForDefrag;
  509. };
  510. struct VulkanBufferContainer
  511. {
  512. VulkanBuffer *activeBuffer;
  513. VulkanBuffer **buffers;
  514. Uint32 bufferCapacity;
  515. Uint32 bufferCount;
  516. bool dedicated;
  517. char *debugName;
  518. };
  519. // Renderer Structure
  520. typedef struct QueueFamilyIndices
  521. {
  522. Uint32 graphicsFamily;
  523. Uint32 presentFamily;
  524. Uint32 computeFamily;
  525. Uint32 transferFamily;
  526. } QueueFamilyIndices;
  527. typedef struct VulkanSampler
  528. {
  529. VkSampler sampler;
  530. SDL_AtomicInt referenceCount;
  531. } VulkanSampler;
  532. typedef struct VulkanShader
  533. {
  534. VkShaderModule shaderModule;
  535. char *entrypointName;
  536. SDL_GPUShaderStage stage;
  537. Uint32 numSamplers;
  538. Uint32 numStorageTextures;
  539. Uint32 numStorageBuffers;
  540. Uint32 numUniformBuffers;
  541. SDL_AtomicInt referenceCount;
  542. } VulkanShader;
  543. /* Textures are made up of individual subresources.
  544. * This helps us barrier the resource efficiently.
  545. */
  546. typedef struct VulkanTextureSubresource
  547. {
  548. VulkanTexture *parent;
  549. Uint32 layer;
  550. Uint32 level;
  551. VkImageView *renderTargetViews; // One render target view per depth slice
  552. VkImageView computeWriteView;
  553. VkImageView depthStencilView;
  554. } VulkanTextureSubresource;
  555. struct VulkanTexture
  556. {
  557. VulkanTextureContainer *container;
  558. Uint32 containerIndex;
  559. VulkanMemoryUsedRegion *usedRegion;
  560. VkImage image;
  561. VkImageView fullView; // used for samplers and storage reads
  562. VkComponentMapping swizzle;
  563. VkImageAspectFlags aspectFlags;
  564. Uint32 depth; // used for cleanup only
  565. // FIXME: It'd be nice if we didn't have to have this on the texture...
  566. SDL_GPUTextureUsageFlags usage; // used for defrag transitions only.
  567. Uint32 subresourceCount;
  568. VulkanTextureSubresource *subresources;
  569. bool markedForDestroy; // so that defrag doesn't double-free
  570. SDL_AtomicInt referenceCount;
  571. };
  572. struct VulkanTextureContainer
  573. {
  574. TextureCommonHeader header;
  575. VulkanTexture *activeTexture;
  576. Uint32 textureCapacity;
  577. Uint32 textureCount;
  578. VulkanTexture **textures;
  579. char *debugName;
  580. bool canBeCycled;
  581. };
  582. typedef enum VulkanBufferUsageMode
  583. {
  584. VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE,
  585. VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION,
  586. VULKAN_BUFFER_USAGE_MODE_VERTEX_READ,
  587. VULKAN_BUFFER_USAGE_MODE_INDEX_READ,
  588. VULKAN_BUFFER_USAGE_MODE_INDIRECT,
  589. VULKAN_BUFFER_USAGE_MODE_GRAPHICS_STORAGE_READ,
  590. VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ,
  591. VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE,
  592. } VulkanBufferUsageMode;
  593. typedef enum VulkanTextureUsageMode
  594. {
  595. VULKAN_TEXTURE_USAGE_MODE_UNINITIALIZED,
  596. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  597. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  598. VULKAN_TEXTURE_USAGE_MODE_SAMPLER,
  599. VULKAN_TEXTURE_USAGE_MODE_GRAPHICS_STORAGE_READ,
  600. VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ,
  601. VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE,
  602. VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT,
  603. VULKAN_TEXTURE_USAGE_MODE_DEPTH_STENCIL_ATTACHMENT,
  604. VULKAN_TEXTURE_USAGE_MODE_PRESENT
  605. } VulkanTextureUsageMode;
  606. typedef enum VulkanUniformBufferStage
  607. {
  608. VULKAN_UNIFORM_BUFFER_STAGE_VERTEX,
  609. VULKAN_UNIFORM_BUFFER_STAGE_FRAGMENT,
  610. VULKAN_UNIFORM_BUFFER_STAGE_COMPUTE
  611. } VulkanUniformBufferStage;
  612. typedef struct VulkanFramebuffer
  613. {
  614. VkFramebuffer framebuffer;
  615. SDL_AtomicInt referenceCount;
  616. } VulkanFramebuffer;
  617. typedef struct WindowData
  618. {
  619. SDL_Window *window;
  620. SDL_GPUSwapchainComposition swapchainComposition;
  621. SDL_GPUPresentMode presentMode;
  622. bool needsSwapchainRecreate;
  623. Uint32 swapchainCreateWidth;
  624. Uint32 swapchainCreateHeight;
  625. // Window surface
  626. VkSurfaceKHR surface;
  627. // Swapchain for window surface
  628. VkSwapchainKHR swapchain;
  629. VkFormat format;
  630. VkColorSpaceKHR colorSpace;
  631. VkComponentMapping swapchainSwizzle;
  632. bool usingFallbackFormat;
  633. // Swapchain images
  634. VulkanTextureContainer *textureContainers; // use containers so that swapchain textures can use the same API as other textures
  635. Uint32 imageCount;
  636. Uint32 width;
  637. Uint32 height;
  638. // Synchronization primitives
  639. VkSemaphore imageAvailableSemaphore[MAX_FRAMES_IN_FLIGHT];
  640. VkSemaphore *renderFinishedSemaphore;
  641. SDL_GPUFence *inFlightFences[MAX_FRAMES_IN_FLIGHT];
  642. Uint32 frameCounter;
  643. } WindowData;
  644. typedef struct SwapchainSupportDetails
  645. {
  646. VkSurfaceCapabilitiesKHR capabilities;
  647. VkSurfaceFormatKHR *formats;
  648. Uint32 formatsLength;
  649. VkPresentModeKHR *presentModes;
  650. Uint32 presentModesLength;
  651. } SwapchainSupportDetails;
  652. typedef struct VulkanPresentData
  653. {
  654. WindowData *windowData;
  655. Uint32 swapchainImageIndex;
  656. } VulkanPresentData;
  657. struct VulkanUniformBuffer
  658. {
  659. VulkanBuffer *buffer;
  660. Uint32 drawOffset;
  661. Uint32 writeOffset;
  662. };
  663. typedef struct VulkanDescriptorInfo
  664. {
  665. VkDescriptorType descriptorType;
  666. VkShaderStageFlagBits stageFlag;
  667. } VulkanDescriptorInfo;
  668. typedef struct DescriptorSetPool
  669. {
  670. // It's a pool... of pools!!!
  671. Uint32 poolCount;
  672. VkDescriptorPool *descriptorPools;
  673. // We'll just manage the descriptor sets ourselves instead of freeing the sets
  674. VkDescriptorSet *descriptorSets;
  675. Uint32 descriptorSetCount;
  676. Uint32 descriptorSetIndex;
  677. } DescriptorSetPool;
  678. // A command buffer acquires a cache at command buffer acquisition time
  679. typedef struct DescriptorSetCache
  680. {
  681. // Pools are indexed by DescriptorSetLayoutID which increases monotonically
  682. // There's only a certain number of maximum layouts possible since we de-duplicate them.
  683. DescriptorSetPool *pools;
  684. Uint32 poolCount;
  685. } DescriptorSetCache;
  686. typedef struct DescriptorSetLayoutHashTableKey
  687. {
  688. VkShaderStageFlagBits shaderStage;
  689. // Category 1: read resources
  690. Uint32 samplerCount;
  691. Uint32 storageBufferCount;
  692. Uint32 storageTextureCount;
  693. // Category 2: write resources
  694. Uint32 writeStorageBufferCount;
  695. Uint32 writeStorageTextureCount;
  696. // Category 3: uniform buffers
  697. Uint32 uniformBufferCount;
  698. } DescriptorSetLayoutHashTableKey;
  699. typedef uint32_t DescriptorSetLayoutID;
  700. typedef struct DescriptorSetLayout
  701. {
  702. DescriptorSetLayoutID ID;
  703. VkDescriptorSetLayout descriptorSetLayout;
  704. // Category 1: read resources
  705. Uint32 samplerCount;
  706. Uint32 storageBufferCount;
  707. Uint32 storageTextureCount;
  708. // Category 2: write resources
  709. Uint32 writeStorageBufferCount;
  710. Uint32 writeStorageTextureCount;
  711. // Category 3: uniform buffers
  712. Uint32 uniformBufferCount;
  713. } DescriptorSetLayout;
  714. typedef struct GraphicsPipelineResourceLayoutHashTableKey
  715. {
  716. Uint32 vertexSamplerCount;
  717. Uint32 vertexStorageBufferCount;
  718. Uint32 vertexStorageTextureCount;
  719. Uint32 vertexUniformBufferCount;
  720. Uint32 fragmentSamplerCount;
  721. Uint32 fragmentStorageBufferCount;
  722. Uint32 fragmentStorageTextureCount;
  723. Uint32 fragmentUniformBufferCount;
  724. } GraphicsPipelineResourceLayoutHashTableKey;
  725. typedef struct VulkanGraphicsPipelineResourceLayout
  726. {
  727. VkPipelineLayout pipelineLayout;
  728. /*
  729. * Descriptor set layout is as follows:
  730. * 0: vertex resources
  731. * 1: vertex uniform buffers
  732. * 2: fragment resources
  733. * 3: fragment uniform buffers
  734. */
  735. DescriptorSetLayout *descriptorSetLayouts[4];
  736. Uint32 vertexSamplerCount;
  737. Uint32 vertexStorageBufferCount;
  738. Uint32 vertexStorageTextureCount;
  739. Uint32 vertexUniformBufferCount;
  740. Uint32 fragmentSamplerCount;
  741. Uint32 fragmentStorageBufferCount;
  742. Uint32 fragmentStorageTextureCount;
  743. Uint32 fragmentUniformBufferCount;
  744. } VulkanGraphicsPipelineResourceLayout;
  745. typedef struct VulkanGraphicsPipeline
  746. {
  747. VkPipeline pipeline;
  748. SDL_GPUPrimitiveType primitiveType;
  749. VulkanGraphicsPipelineResourceLayout *resourceLayout;
  750. VulkanShader *vertexShader;
  751. VulkanShader *fragmentShader;
  752. SDL_AtomicInt referenceCount;
  753. } VulkanGraphicsPipeline;
  754. typedef struct ComputePipelineResourceLayoutHashTableKey
  755. {
  756. Uint32 samplerCount;
  757. Uint32 readonlyStorageTextureCount;
  758. Uint32 readonlyStorageBufferCount;
  759. Uint32 readWriteStorageTextureCount;
  760. Uint32 readWriteStorageBufferCount;
  761. Uint32 uniformBufferCount;
  762. } ComputePipelineResourceLayoutHashTableKey;
  763. typedef struct VulkanComputePipelineResourceLayout
  764. {
  765. VkPipelineLayout pipelineLayout;
  766. /*
  767. * Descriptor set layout is as follows:
  768. * 0: samplers, then read-only textures, then read-only buffers
  769. * 1: write-only textures, then write-only buffers
  770. * 2: uniform buffers
  771. */
  772. DescriptorSetLayout *descriptorSetLayouts[3];
  773. Uint32 numSamplers;
  774. Uint32 numReadonlyStorageTextures;
  775. Uint32 numReadonlyStorageBuffers;
  776. Uint32 numReadWriteStorageTextures;
  777. Uint32 numReadWriteStorageBuffers;
  778. Uint32 numUniformBuffers;
  779. } VulkanComputePipelineResourceLayout;
  780. typedef struct VulkanComputePipeline
  781. {
  782. VkShaderModule shaderModule;
  783. VkPipeline pipeline;
  784. VulkanComputePipelineResourceLayout *resourceLayout;
  785. SDL_AtomicInt referenceCount;
  786. } VulkanComputePipeline;
  787. typedef struct RenderPassColorTargetDescription
  788. {
  789. VkFormat format;
  790. SDL_GPULoadOp loadOp;
  791. SDL_GPUStoreOp storeOp;
  792. } RenderPassColorTargetDescription;
  793. typedef struct RenderPassDepthStencilTargetDescription
  794. {
  795. VkFormat format;
  796. SDL_GPULoadOp loadOp;
  797. SDL_GPUStoreOp storeOp;
  798. SDL_GPULoadOp stencilLoadOp;
  799. SDL_GPUStoreOp stencilStoreOp;
  800. } RenderPassDepthStencilTargetDescription;
  801. typedef struct CommandPoolHashTableKey
  802. {
  803. SDL_ThreadID threadID;
  804. } CommandPoolHashTableKey;
  805. typedef struct RenderPassHashTableKey
  806. {
  807. RenderPassColorTargetDescription colorTargetDescriptions[MAX_COLOR_TARGET_BINDINGS];
  808. Uint32 numColorTargets;
  809. VkFormat resolveTargetFormats[MAX_COLOR_TARGET_BINDINGS];
  810. Uint32 numResolveTargets;
  811. RenderPassDepthStencilTargetDescription depthStencilTargetDescription;
  812. VkSampleCountFlagBits sampleCount;
  813. } RenderPassHashTableKey;
  814. typedef struct VulkanRenderPassHashTableValue
  815. {
  816. VkRenderPass handle;
  817. } VulkanRenderPassHashTableValue;
  818. typedef struct FramebufferHashTableKey
  819. {
  820. VkImageView colorAttachmentViews[MAX_COLOR_TARGET_BINDINGS];
  821. Uint32 numColorTargets;
  822. VkImageView resolveAttachmentViews[MAX_COLOR_TARGET_BINDINGS];
  823. Uint32 numResolveAttachments;
  824. VkImageView depthStencilAttachmentView;
  825. Uint32 width;
  826. Uint32 height;
  827. } FramebufferHashTableKey;
  828. // Command structures
  829. typedef struct VulkanFencePool
  830. {
  831. SDL_Mutex *lock;
  832. VulkanFenceHandle **availableFences;
  833. Uint32 availableFenceCount;
  834. Uint32 availableFenceCapacity;
  835. } VulkanFencePool;
  836. typedef struct VulkanCommandPool VulkanCommandPool;
  837. typedef struct VulkanRenderer VulkanRenderer;
  838. typedef struct VulkanCommandBuffer
  839. {
  840. CommandBufferCommonHeader common;
  841. VulkanRenderer *renderer;
  842. VkCommandBuffer commandBuffer;
  843. VulkanCommandPool *commandPool;
  844. VulkanPresentData *presentDatas;
  845. Uint32 presentDataCount;
  846. Uint32 presentDataCapacity;
  847. VkSemaphore *waitSemaphores;
  848. Uint32 waitSemaphoreCount;
  849. Uint32 waitSemaphoreCapacity;
  850. VkSemaphore *signalSemaphores;
  851. Uint32 signalSemaphoreCount;
  852. Uint32 signalSemaphoreCapacity;
  853. VulkanComputePipeline *currentComputePipeline;
  854. VulkanGraphicsPipeline *currentGraphicsPipeline;
  855. // Keep track of resources transitioned away from their default state to barrier them on pass end
  856. VulkanTextureSubresource *colorAttachmentSubresources[MAX_COLOR_TARGET_BINDINGS];
  857. Uint32 colorAttachmentSubresourceCount;
  858. VulkanTextureSubresource *resolveAttachmentSubresources[MAX_COLOR_TARGET_BINDINGS];
  859. Uint32 resolveAttachmentSubresourceCount;
  860. VulkanTextureSubresource *depthStencilAttachmentSubresource; // may be NULL
  861. // Dynamic state
  862. VkViewport currentViewport;
  863. VkRect2D currentScissor;
  864. float blendConstants[4];
  865. Uint8 stencilRef;
  866. // Resource bind state
  867. DescriptorSetCache *descriptorSetCache; // acquired when command buffer is acquired
  868. bool needNewVertexResourceDescriptorSet;
  869. bool needNewVertexUniformDescriptorSet;
  870. bool needNewVertexUniformOffsets;
  871. bool needNewFragmentResourceDescriptorSet;
  872. bool needNewFragmentUniformDescriptorSet;
  873. bool needNewFragmentUniformOffsets;
  874. bool needNewComputeReadOnlyDescriptorSet;
  875. bool needNewComputeReadWriteDescriptorSet;
  876. bool needNewComputeUniformDescriptorSet;
  877. bool needNewComputeUniformOffsets;
  878. VkDescriptorSet vertexResourceDescriptorSet;
  879. VkDescriptorSet vertexUniformDescriptorSet;
  880. VkDescriptorSet fragmentResourceDescriptorSet;
  881. VkDescriptorSet fragmentUniformDescriptorSet;
  882. VkDescriptorSet computeReadOnlyDescriptorSet;
  883. VkDescriptorSet computeReadWriteDescriptorSet;
  884. VkDescriptorSet computeUniformDescriptorSet;
  885. VkBuffer vertexBuffers[MAX_VERTEX_BUFFERS];
  886. VkDeviceSize vertexBufferOffsets[MAX_VERTEX_BUFFERS];
  887. Uint32 vertexBufferCount;
  888. bool needVertexBufferBind;
  889. VulkanTexture *vertexSamplerTextures[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  890. VulkanSampler *vertexSamplers[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  891. VulkanTexture *vertexStorageTextures[MAX_STORAGE_TEXTURES_PER_STAGE];
  892. VulkanBuffer *vertexStorageBuffers[MAX_STORAGE_BUFFERS_PER_STAGE];
  893. VulkanTexture *fragmentSamplerTextures[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  894. VulkanSampler *fragmentSamplers[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  895. VulkanTexture *fragmentStorageTextures[MAX_STORAGE_TEXTURES_PER_STAGE];
  896. VulkanBuffer *fragmentStorageBuffers[MAX_STORAGE_BUFFERS_PER_STAGE];
  897. VulkanTextureSubresource *readWriteComputeStorageTextureSubresources[MAX_COMPUTE_WRITE_TEXTURES];
  898. Uint32 readWriteComputeStorageTextureSubresourceCount;
  899. VulkanBuffer *readWriteComputeStorageBuffers[MAX_COMPUTE_WRITE_BUFFERS];
  900. VulkanTexture *computeSamplerTextures[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  901. VulkanSampler *computeSamplers[MAX_TEXTURE_SAMPLERS_PER_STAGE];
  902. VulkanTexture *readOnlyComputeStorageTextures[MAX_STORAGE_TEXTURES_PER_STAGE];
  903. VulkanBuffer *readOnlyComputeStorageBuffers[MAX_STORAGE_BUFFERS_PER_STAGE];
  904. // Uniform buffers
  905. VulkanUniformBuffer *vertexUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  906. VulkanUniformBuffer *fragmentUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  907. VulkanUniformBuffer *computeUniformBuffers[MAX_UNIFORM_BUFFERS_PER_STAGE];
  908. // Track used resources
  909. VulkanBuffer **usedBuffers;
  910. Sint32 usedBufferCount;
  911. Sint32 usedBufferCapacity;
  912. VulkanTexture **usedTextures;
  913. Sint32 usedTextureCount;
  914. Sint32 usedTextureCapacity;
  915. VulkanSampler **usedSamplers;
  916. Sint32 usedSamplerCount;
  917. Sint32 usedSamplerCapacity;
  918. VulkanGraphicsPipeline **usedGraphicsPipelines;
  919. Sint32 usedGraphicsPipelineCount;
  920. Sint32 usedGraphicsPipelineCapacity;
  921. VulkanComputePipeline **usedComputePipelines;
  922. Sint32 usedComputePipelineCount;
  923. Sint32 usedComputePipelineCapacity;
  924. VulkanFramebuffer **usedFramebuffers;
  925. Sint32 usedFramebufferCount;
  926. Sint32 usedFramebufferCapacity;
  927. VulkanUniformBuffer **usedUniformBuffers;
  928. Sint32 usedUniformBufferCount;
  929. Sint32 usedUniformBufferCapacity;
  930. VulkanFenceHandle *inFlightFence;
  931. bool autoReleaseFence;
  932. bool isDefrag; // Whether this CB was created for defragging
  933. } VulkanCommandBuffer;
  934. struct VulkanCommandPool
  935. {
  936. SDL_ThreadID threadID;
  937. VkCommandPool commandPool;
  938. VulkanCommandBuffer **inactiveCommandBuffers;
  939. Uint32 inactiveCommandBufferCapacity;
  940. Uint32 inactiveCommandBufferCount;
  941. };
  942. // Context
  943. struct VulkanRenderer
  944. {
  945. VkInstance instance;
  946. VkPhysicalDevice physicalDevice;
  947. VkPhysicalDeviceProperties2KHR physicalDeviceProperties;
  948. VkPhysicalDeviceDriverPropertiesKHR physicalDeviceDriverProperties;
  949. VkDevice logicalDevice;
  950. Uint8 integratedMemoryNotification;
  951. Uint8 outOfDeviceLocalMemoryWarning;
  952. Uint8 outofBARMemoryWarning;
  953. Uint8 fillModeOnlyWarning;
  954. bool debugMode;
  955. bool preferLowPower;
  956. Uint32 allowedFramesInFlight;
  957. VulkanExtensions supports;
  958. bool supportsDebugUtils;
  959. bool supportsColorspace;
  960. bool supportsFillModeNonSolid;
  961. bool supportsMultiDrawIndirect;
  962. VulkanMemoryAllocator *memoryAllocator;
  963. VkPhysicalDeviceMemoryProperties memoryProperties;
  964. bool checkEmptyAllocations;
  965. WindowData **claimedWindows;
  966. Uint32 claimedWindowCount;
  967. Uint32 claimedWindowCapacity;
  968. Uint32 queueFamilyIndex;
  969. VkQueue unifiedQueue;
  970. VulkanCommandBuffer **submittedCommandBuffers;
  971. Uint32 submittedCommandBufferCount;
  972. Uint32 submittedCommandBufferCapacity;
  973. VulkanFencePool fencePool;
  974. SDL_HashTable *commandPoolHashTable;
  975. SDL_HashTable *renderPassHashTable;
  976. SDL_HashTable *framebufferHashTable;
  977. SDL_HashTable *graphicsPipelineResourceLayoutHashTable;
  978. SDL_HashTable *computePipelineResourceLayoutHashTable;
  979. SDL_HashTable *descriptorSetLayoutHashTable;
  980. VulkanUniformBuffer **uniformBufferPool;
  981. Uint32 uniformBufferPoolCount;
  982. Uint32 uniformBufferPoolCapacity;
  983. DescriptorSetCache **descriptorSetCachePool;
  984. Uint32 descriptorSetCachePoolCount;
  985. Uint32 descriptorSetCachePoolCapacity;
  986. SDL_AtomicInt layoutResourceID;
  987. Uint32 minUBOAlignment;
  988. // Deferred resource destruction
  989. VulkanTexture **texturesToDestroy;
  990. Uint32 texturesToDestroyCount;
  991. Uint32 texturesToDestroyCapacity;
  992. VulkanBuffer **buffersToDestroy;
  993. Uint32 buffersToDestroyCount;
  994. Uint32 buffersToDestroyCapacity;
  995. VulkanSampler **samplersToDestroy;
  996. Uint32 samplersToDestroyCount;
  997. Uint32 samplersToDestroyCapacity;
  998. VulkanGraphicsPipeline **graphicsPipelinesToDestroy;
  999. Uint32 graphicsPipelinesToDestroyCount;
  1000. Uint32 graphicsPipelinesToDestroyCapacity;
  1001. VulkanComputePipeline **computePipelinesToDestroy;
  1002. Uint32 computePipelinesToDestroyCount;
  1003. Uint32 computePipelinesToDestroyCapacity;
  1004. VulkanShader **shadersToDestroy;
  1005. Uint32 shadersToDestroyCount;
  1006. Uint32 shadersToDestroyCapacity;
  1007. VulkanFramebuffer **framebuffersToDestroy;
  1008. Uint32 framebuffersToDestroyCount;
  1009. Uint32 framebuffersToDestroyCapacity;
  1010. SDL_Mutex *allocatorLock;
  1011. SDL_Mutex *disposeLock;
  1012. SDL_Mutex *submitLock;
  1013. SDL_Mutex *acquireCommandBufferLock;
  1014. SDL_Mutex *acquireUniformBufferLock;
  1015. SDL_Mutex *renderPassFetchLock;
  1016. SDL_Mutex *framebufferFetchLock;
  1017. SDL_Mutex *graphicsPipelineLayoutFetchLock;
  1018. SDL_Mutex *computePipelineLayoutFetchLock;
  1019. SDL_Mutex *descriptorSetLayoutFetchLock;
  1020. SDL_Mutex *windowLock;
  1021. Uint8 defragInProgress;
  1022. VulkanMemoryAllocation **allocationsToDefrag;
  1023. Uint32 allocationsToDefragCount;
  1024. Uint32 allocationsToDefragCapacity;
  1025. #define VULKAN_INSTANCE_FUNCTION(func) \
  1026. PFN_##func func;
  1027. #define VULKAN_DEVICE_FUNCTION(func) \
  1028. PFN_##func func;
  1029. #include "SDL_gpu_vulkan_vkfuncs.h"
  1030. };
  1031. // Forward declarations
  1032. static bool VULKAN_INTERNAL_DefragmentMemory(VulkanRenderer *renderer, VulkanCommandBuffer *commandBuffer);
  1033. static bool VULKAN_INTERNAL_BeginCommandBuffer(VulkanRenderer *renderer, VulkanCommandBuffer *commandBuffer);
  1034. static void VULKAN_ReleaseWindow(SDL_GPURenderer *driverData, SDL_Window *window);
  1035. static bool VULKAN_Wait(SDL_GPURenderer *driverData);
  1036. static bool VULKAN_WaitForFences(SDL_GPURenderer *driverData, bool waitAll, SDL_GPUFence *const *fences, Uint32 numFences);
  1037. static bool VULKAN_Submit(SDL_GPUCommandBuffer *commandBuffer);
  1038. static SDL_GPUCommandBuffer *VULKAN_AcquireCommandBuffer(SDL_GPURenderer *driverData);
  1039. // Error Handling
  1040. static inline const char *VkErrorMessages(VkResult code)
  1041. {
  1042. #define ERR_TO_STR(e) \
  1043. case e: \
  1044. return #e;
  1045. switch (code) {
  1046. ERR_TO_STR(VK_ERROR_OUT_OF_HOST_MEMORY)
  1047. ERR_TO_STR(VK_ERROR_OUT_OF_DEVICE_MEMORY)
  1048. ERR_TO_STR(VK_ERROR_FRAGMENTED_POOL)
  1049. ERR_TO_STR(VK_ERROR_OUT_OF_POOL_MEMORY)
  1050. ERR_TO_STR(VK_ERROR_INITIALIZATION_FAILED)
  1051. ERR_TO_STR(VK_ERROR_LAYER_NOT_PRESENT)
  1052. ERR_TO_STR(VK_ERROR_EXTENSION_NOT_PRESENT)
  1053. ERR_TO_STR(VK_ERROR_FEATURE_NOT_PRESENT)
  1054. ERR_TO_STR(VK_ERROR_TOO_MANY_OBJECTS)
  1055. ERR_TO_STR(VK_ERROR_DEVICE_LOST)
  1056. ERR_TO_STR(VK_ERROR_INCOMPATIBLE_DRIVER)
  1057. ERR_TO_STR(VK_ERROR_OUT_OF_DATE_KHR)
  1058. ERR_TO_STR(VK_ERROR_SURFACE_LOST_KHR)
  1059. ERR_TO_STR(VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT)
  1060. ERR_TO_STR(VK_SUBOPTIMAL_KHR)
  1061. ERR_TO_STR(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR)
  1062. ERR_TO_STR(VK_ERROR_INVALID_SHADER_NV)
  1063. default:
  1064. return "Unhandled VkResult!";
  1065. }
  1066. #undef ERR_TO_STR
  1067. }
  1068. #define SET_ERROR_AND_RETURN(fmt, msg, ret) \
  1069. do { \
  1070. if (renderer->debugMode) { \
  1071. SDL_LogError(SDL_LOG_CATEGORY_GPU, fmt, msg); \
  1072. } \
  1073. SDL_SetError((fmt), (msg)); \
  1074. return ret; \
  1075. } while (0)
  1076. #define SET_STRING_ERROR_AND_RETURN(msg, ret) SET_ERROR_AND_RETURN("%s", msg, ret)
  1077. #define CHECK_VULKAN_ERROR_AND_RETURN(res, fn, ret) \
  1078. do { \
  1079. if ((res) != VK_SUCCESS) { \
  1080. if (renderer->debugMode) { \
  1081. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s %s", #fn, VkErrorMessages(res)); \
  1082. } \
  1083. SDL_SetError("%s %s", #fn, VkErrorMessages(res)); \
  1084. return (ret); \
  1085. } \
  1086. } while (0)
  1087. // Utility
  1088. static inline VkPolygonMode SDLToVK_PolygonMode(
  1089. VulkanRenderer *renderer,
  1090. SDL_GPUFillMode mode)
  1091. {
  1092. if (mode == SDL_GPU_FILLMODE_FILL) {
  1093. return VK_POLYGON_MODE_FILL; // always available!
  1094. }
  1095. if (renderer->supportsFillModeNonSolid && mode == SDL_GPU_FILLMODE_LINE) {
  1096. return VK_POLYGON_MODE_LINE;
  1097. }
  1098. if (!renderer->fillModeOnlyWarning) {
  1099. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Unsupported fill mode requested, using FILL!");
  1100. renderer->fillModeOnlyWarning = 1;
  1101. }
  1102. return VK_POLYGON_MODE_FILL;
  1103. }
  1104. // Memory Management
  1105. // Vulkan: Memory Allocation
  1106. static inline VkDeviceSize VULKAN_INTERNAL_NextHighestAlignment(
  1107. VkDeviceSize n,
  1108. VkDeviceSize align)
  1109. {
  1110. return align * ((n + align - 1) / align);
  1111. }
  1112. static inline Uint32 VULKAN_INTERNAL_NextHighestAlignment32(
  1113. Uint32 n,
  1114. Uint32 align)
  1115. {
  1116. return align * ((n + align - 1) / align);
  1117. }
  1118. static void VULKAN_INTERNAL_MakeMemoryUnavailable(
  1119. VulkanRenderer *renderer,
  1120. VulkanMemoryAllocation *allocation)
  1121. {
  1122. Uint32 i, j;
  1123. VulkanMemoryFreeRegion *freeRegion;
  1124. allocation->availableForAllocation = 0;
  1125. for (i = 0; i < allocation->freeRegionCount; i += 1) {
  1126. freeRegion = allocation->freeRegions[i];
  1127. // close the gap in the sorted list
  1128. if (allocation->allocator->sortedFreeRegionCount > 1) {
  1129. for (j = freeRegion->sortedIndex; j < allocation->allocator->sortedFreeRegionCount - 1; j += 1) {
  1130. allocation->allocator->sortedFreeRegions[j] =
  1131. allocation->allocator->sortedFreeRegions[j + 1];
  1132. allocation->allocator->sortedFreeRegions[j]->sortedIndex = j;
  1133. }
  1134. }
  1135. allocation->allocator->sortedFreeRegionCount -= 1;
  1136. }
  1137. }
  1138. static void VULKAN_INTERNAL_MarkAllocationsForDefrag(
  1139. VulkanRenderer *renderer)
  1140. {
  1141. Uint32 memoryType, allocationIndex;
  1142. VulkanMemorySubAllocator *currentAllocator;
  1143. for (memoryType = 0; memoryType < VK_MAX_MEMORY_TYPES; memoryType += 1) {
  1144. currentAllocator = &renderer->memoryAllocator->subAllocators[memoryType];
  1145. for (allocationIndex = 0; allocationIndex < currentAllocator->allocationCount; allocationIndex += 1) {
  1146. if (currentAllocator->allocations[allocationIndex]->availableForAllocation == 1) {
  1147. if (currentAllocator->allocations[allocationIndex]->freeRegionCount > 1) {
  1148. EXPAND_ARRAY_IF_NEEDED(
  1149. renderer->allocationsToDefrag,
  1150. VulkanMemoryAllocation *,
  1151. renderer->allocationsToDefragCount + 1,
  1152. renderer->allocationsToDefragCapacity,
  1153. renderer->allocationsToDefragCapacity * 2);
  1154. renderer->allocationsToDefrag[renderer->allocationsToDefragCount] =
  1155. currentAllocator->allocations[allocationIndex];
  1156. renderer->allocationsToDefragCount += 1;
  1157. VULKAN_INTERNAL_MakeMemoryUnavailable(
  1158. renderer,
  1159. currentAllocator->allocations[allocationIndex]);
  1160. }
  1161. }
  1162. }
  1163. }
  1164. }
  1165. static void VULKAN_INTERNAL_RemoveMemoryFreeRegion(
  1166. VulkanRenderer *renderer,
  1167. VulkanMemoryFreeRegion *freeRegion)
  1168. {
  1169. Uint32 i;
  1170. SDL_LockMutex(renderer->allocatorLock);
  1171. if (freeRegion->allocation->availableForAllocation) {
  1172. // close the gap in the sorted list
  1173. if (freeRegion->allocation->allocator->sortedFreeRegionCount > 1) {
  1174. for (i = freeRegion->sortedIndex; i < freeRegion->allocation->allocator->sortedFreeRegionCount - 1; i += 1) {
  1175. freeRegion->allocation->allocator->sortedFreeRegions[i] =
  1176. freeRegion->allocation->allocator->sortedFreeRegions[i + 1];
  1177. freeRegion->allocation->allocator->sortedFreeRegions[i]->sortedIndex = i;
  1178. }
  1179. }
  1180. freeRegion->allocation->allocator->sortedFreeRegionCount -= 1;
  1181. }
  1182. // close the gap in the buffer list
  1183. if (freeRegion->allocation->freeRegionCount > 1 && freeRegion->allocationIndex != freeRegion->allocation->freeRegionCount - 1) {
  1184. freeRegion->allocation->freeRegions[freeRegion->allocationIndex] =
  1185. freeRegion->allocation->freeRegions[freeRegion->allocation->freeRegionCount - 1];
  1186. freeRegion->allocation->freeRegions[freeRegion->allocationIndex]->allocationIndex =
  1187. freeRegion->allocationIndex;
  1188. }
  1189. freeRegion->allocation->freeRegionCount -= 1;
  1190. freeRegion->allocation->freeSpace -= freeRegion->size;
  1191. SDL_free(freeRegion);
  1192. SDL_UnlockMutex(renderer->allocatorLock);
  1193. }
  1194. static void VULKAN_INTERNAL_NewMemoryFreeRegion(
  1195. VulkanRenderer *renderer,
  1196. VulkanMemoryAllocation *allocation,
  1197. VkDeviceSize offset,
  1198. VkDeviceSize size)
  1199. {
  1200. VulkanMemoryFreeRegion *newFreeRegion;
  1201. VkDeviceSize newOffset, newSize;
  1202. Sint32 insertionIndex = 0;
  1203. SDL_LockMutex(renderer->allocatorLock);
  1204. // look for an adjacent region to merge
  1205. for (Sint32 i = allocation->freeRegionCount - 1; i >= 0; i -= 1) {
  1206. // check left side
  1207. if (allocation->freeRegions[i]->offset + allocation->freeRegions[i]->size == offset) {
  1208. newOffset = allocation->freeRegions[i]->offset;
  1209. newSize = allocation->freeRegions[i]->size + size;
  1210. VULKAN_INTERNAL_RemoveMemoryFreeRegion(renderer, allocation->freeRegions[i]);
  1211. VULKAN_INTERNAL_NewMemoryFreeRegion(renderer, allocation, newOffset, newSize);
  1212. SDL_UnlockMutex(renderer->allocatorLock);
  1213. return;
  1214. }
  1215. // check right side
  1216. if (allocation->freeRegions[i]->offset == offset + size) {
  1217. newOffset = offset;
  1218. newSize = allocation->freeRegions[i]->size + size;
  1219. VULKAN_INTERNAL_RemoveMemoryFreeRegion(renderer, allocation->freeRegions[i]);
  1220. VULKAN_INTERNAL_NewMemoryFreeRegion(renderer, allocation, newOffset, newSize);
  1221. SDL_UnlockMutex(renderer->allocatorLock);
  1222. return;
  1223. }
  1224. }
  1225. // region is not contiguous with another free region, make a new one
  1226. allocation->freeRegionCount += 1;
  1227. if (allocation->freeRegionCount > allocation->freeRegionCapacity) {
  1228. allocation->freeRegionCapacity *= 2;
  1229. allocation->freeRegions = SDL_realloc(
  1230. allocation->freeRegions,
  1231. sizeof(VulkanMemoryFreeRegion *) * allocation->freeRegionCapacity);
  1232. }
  1233. newFreeRegion = SDL_malloc(sizeof(VulkanMemoryFreeRegion));
  1234. newFreeRegion->offset = offset;
  1235. newFreeRegion->size = size;
  1236. newFreeRegion->allocation = allocation;
  1237. allocation->freeSpace += size;
  1238. allocation->freeRegions[allocation->freeRegionCount - 1] = newFreeRegion;
  1239. newFreeRegion->allocationIndex = allocation->freeRegionCount - 1;
  1240. if (allocation->availableForAllocation) {
  1241. for (Uint32 i = 0; i < allocation->allocator->sortedFreeRegionCount; i += 1) {
  1242. if (allocation->allocator->sortedFreeRegions[i]->size < size) {
  1243. // this is where the new region should go
  1244. break;
  1245. }
  1246. insertionIndex += 1;
  1247. }
  1248. if (allocation->allocator->sortedFreeRegionCount + 1 > allocation->allocator->sortedFreeRegionCapacity) {
  1249. allocation->allocator->sortedFreeRegionCapacity *= 2;
  1250. allocation->allocator->sortedFreeRegions = SDL_realloc(
  1251. allocation->allocator->sortedFreeRegions,
  1252. sizeof(VulkanMemoryFreeRegion *) * allocation->allocator->sortedFreeRegionCapacity);
  1253. }
  1254. // perform insertion sort
  1255. if (allocation->allocator->sortedFreeRegionCount > 0 && (Uint32)insertionIndex != allocation->allocator->sortedFreeRegionCount) {
  1256. for (Sint32 i = allocation->allocator->sortedFreeRegionCount; i > insertionIndex && i > 0; i -= 1) {
  1257. allocation->allocator->sortedFreeRegions[i] = allocation->allocator->sortedFreeRegions[i - 1];
  1258. allocation->allocator->sortedFreeRegions[i]->sortedIndex = i;
  1259. }
  1260. }
  1261. allocation->allocator->sortedFreeRegionCount += 1;
  1262. allocation->allocator->sortedFreeRegions[insertionIndex] = newFreeRegion;
  1263. newFreeRegion->sortedIndex = insertionIndex;
  1264. }
  1265. SDL_UnlockMutex(renderer->allocatorLock);
  1266. }
  1267. static VulkanMemoryUsedRegion *VULKAN_INTERNAL_NewMemoryUsedRegion(
  1268. VulkanRenderer *renderer,
  1269. VulkanMemoryAllocation *allocation,
  1270. VkDeviceSize offset,
  1271. VkDeviceSize size,
  1272. VkDeviceSize resourceOffset,
  1273. VkDeviceSize resourceSize,
  1274. VkDeviceSize alignment)
  1275. {
  1276. VulkanMemoryUsedRegion *memoryUsedRegion;
  1277. SDL_LockMutex(renderer->allocatorLock);
  1278. if (allocation->usedRegionCount == allocation->usedRegionCapacity) {
  1279. allocation->usedRegionCapacity *= 2;
  1280. allocation->usedRegions = SDL_realloc(
  1281. allocation->usedRegions,
  1282. allocation->usedRegionCapacity * sizeof(VulkanMemoryUsedRegion *));
  1283. }
  1284. memoryUsedRegion = SDL_malloc(sizeof(VulkanMemoryUsedRegion));
  1285. memoryUsedRegion->allocation = allocation;
  1286. memoryUsedRegion->offset = offset;
  1287. memoryUsedRegion->size = size;
  1288. memoryUsedRegion->resourceOffset = resourceOffset;
  1289. memoryUsedRegion->resourceSize = resourceSize;
  1290. memoryUsedRegion->alignment = alignment;
  1291. allocation->usedSpace += size;
  1292. allocation->usedRegions[allocation->usedRegionCount] = memoryUsedRegion;
  1293. allocation->usedRegionCount += 1;
  1294. SDL_UnlockMutex(renderer->allocatorLock);
  1295. return memoryUsedRegion;
  1296. }
  1297. static void VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  1298. VulkanRenderer *renderer,
  1299. VulkanMemoryUsedRegion *usedRegion)
  1300. {
  1301. Uint32 i;
  1302. SDL_LockMutex(renderer->allocatorLock);
  1303. for (i = 0; i < usedRegion->allocation->usedRegionCount; i += 1) {
  1304. if (usedRegion->allocation->usedRegions[i] == usedRegion) {
  1305. // plug the hole
  1306. if (i != usedRegion->allocation->usedRegionCount - 1) {
  1307. usedRegion->allocation->usedRegions[i] = usedRegion->allocation->usedRegions[usedRegion->allocation->usedRegionCount - 1];
  1308. }
  1309. break;
  1310. }
  1311. }
  1312. usedRegion->allocation->usedSpace -= usedRegion->size;
  1313. usedRegion->allocation->usedRegionCount -= 1;
  1314. VULKAN_INTERNAL_NewMemoryFreeRegion(
  1315. renderer,
  1316. usedRegion->allocation,
  1317. usedRegion->offset,
  1318. usedRegion->size);
  1319. if (usedRegion->allocation->usedRegionCount == 0) {
  1320. renderer->checkEmptyAllocations = true;
  1321. }
  1322. SDL_free(usedRegion);
  1323. SDL_UnlockMutex(renderer->allocatorLock);
  1324. }
  1325. static bool VULKAN_INTERNAL_CheckMemoryTypeArrayUnique(
  1326. Uint32 memoryTypeIndex,
  1327. const Uint32 *memoryTypeIndexArray,
  1328. Uint32 count)
  1329. {
  1330. Uint32 i = 0;
  1331. for (i = 0; i < count; i += 1) {
  1332. if (memoryTypeIndexArray[i] == memoryTypeIndex) {
  1333. return false;
  1334. }
  1335. }
  1336. return true;
  1337. }
  1338. /* Returns an array of memory type indices in order of preference.
  1339. * Memory types are requested with the following three guidelines:
  1340. *
  1341. * Required: Absolutely necessary
  1342. * Preferred: Nice to have, but not necessary
  1343. * Tolerable: Can be allowed if there are no other options
  1344. *
  1345. * We return memory types in this order:
  1346. * 1. Required and preferred. This is the best category.
  1347. * 2. Required only.
  1348. * 3. Required, preferred, and tolerable.
  1349. * 4. Required and tolerable. This is the worst category.
  1350. */
  1351. static Uint32 *VULKAN_INTERNAL_FindBestMemoryTypes(
  1352. VulkanRenderer *renderer,
  1353. Uint32 typeFilter,
  1354. VkMemoryPropertyFlags requiredProperties,
  1355. VkMemoryPropertyFlags preferredProperties,
  1356. VkMemoryPropertyFlags tolerableProperties,
  1357. Uint32 *pCount)
  1358. {
  1359. Uint32 i;
  1360. Uint32 index = 0;
  1361. Uint32 *result = SDL_malloc(sizeof(Uint32) * renderer->memoryProperties.memoryTypeCount);
  1362. // required + preferred + !tolerable
  1363. for (i = 0; i < renderer->memoryProperties.memoryTypeCount; i += 1) {
  1364. if ((typeFilter & (1 << i)) &&
  1365. (renderer->memoryProperties.memoryTypes[i].propertyFlags & requiredProperties) == requiredProperties &&
  1366. (renderer->memoryProperties.memoryTypes[i].propertyFlags & preferredProperties) == preferredProperties &&
  1367. (renderer->memoryProperties.memoryTypes[i].propertyFlags & tolerableProperties) == 0) {
  1368. if (VULKAN_INTERNAL_CheckMemoryTypeArrayUnique(
  1369. i,
  1370. result,
  1371. index)) {
  1372. result[index] = i;
  1373. index += 1;
  1374. }
  1375. }
  1376. }
  1377. // required + !preferred + !tolerable
  1378. for (i = 0; i < renderer->memoryProperties.memoryTypeCount; i += 1) {
  1379. if ((typeFilter & (1 << i)) &&
  1380. (renderer->memoryProperties.memoryTypes[i].propertyFlags & requiredProperties) == requiredProperties &&
  1381. (renderer->memoryProperties.memoryTypes[i].propertyFlags & preferredProperties) == 0 &&
  1382. (renderer->memoryProperties.memoryTypes[i].propertyFlags & tolerableProperties) == 0) {
  1383. if (VULKAN_INTERNAL_CheckMemoryTypeArrayUnique(
  1384. i,
  1385. result,
  1386. index)) {
  1387. result[index] = i;
  1388. index += 1;
  1389. }
  1390. }
  1391. }
  1392. // required + preferred + tolerable
  1393. for (i = 0; i < renderer->memoryProperties.memoryTypeCount; i += 1) {
  1394. if ((typeFilter & (1 << i)) &&
  1395. (renderer->memoryProperties.memoryTypes[i].propertyFlags & requiredProperties) == requiredProperties &&
  1396. (renderer->memoryProperties.memoryTypes[i].propertyFlags & preferredProperties) == preferredProperties &&
  1397. (renderer->memoryProperties.memoryTypes[i].propertyFlags & tolerableProperties) == tolerableProperties) {
  1398. if (VULKAN_INTERNAL_CheckMemoryTypeArrayUnique(
  1399. i,
  1400. result,
  1401. index)) {
  1402. result[index] = i;
  1403. index += 1;
  1404. }
  1405. }
  1406. }
  1407. // required + !preferred + tolerable
  1408. for (i = 0; i < renderer->memoryProperties.memoryTypeCount; i += 1) {
  1409. if ((typeFilter & (1 << i)) &&
  1410. (renderer->memoryProperties.memoryTypes[i].propertyFlags & requiredProperties) == requiredProperties &&
  1411. (renderer->memoryProperties.memoryTypes[i].propertyFlags & preferredProperties) == 0 &&
  1412. (renderer->memoryProperties.memoryTypes[i].propertyFlags & tolerableProperties) == tolerableProperties) {
  1413. if (VULKAN_INTERNAL_CheckMemoryTypeArrayUnique(
  1414. i,
  1415. result,
  1416. index)) {
  1417. result[index] = i;
  1418. index += 1;
  1419. }
  1420. }
  1421. }
  1422. *pCount = index;
  1423. return result;
  1424. }
  1425. static Uint32 *VULKAN_INTERNAL_FindBestBufferMemoryTypes(
  1426. VulkanRenderer *renderer,
  1427. VkBuffer buffer,
  1428. VkMemoryPropertyFlags requiredMemoryProperties,
  1429. VkMemoryPropertyFlags preferredMemoryProperties,
  1430. VkMemoryPropertyFlags tolerableMemoryProperties,
  1431. VkMemoryRequirements *pMemoryRequirements,
  1432. Uint32 *pCount)
  1433. {
  1434. renderer->vkGetBufferMemoryRequirements(
  1435. renderer->logicalDevice,
  1436. buffer,
  1437. pMemoryRequirements);
  1438. return VULKAN_INTERNAL_FindBestMemoryTypes(
  1439. renderer,
  1440. pMemoryRequirements->memoryTypeBits,
  1441. requiredMemoryProperties,
  1442. preferredMemoryProperties,
  1443. tolerableMemoryProperties,
  1444. pCount);
  1445. }
  1446. static Uint32 *VULKAN_INTERNAL_FindBestImageMemoryTypes(
  1447. VulkanRenderer *renderer,
  1448. VkImage image,
  1449. VkMemoryPropertyFlags preferredMemoryPropertyFlags,
  1450. VkMemoryRequirements *pMemoryRequirements,
  1451. Uint32 *pCount)
  1452. {
  1453. renderer->vkGetImageMemoryRequirements(
  1454. renderer->logicalDevice,
  1455. image,
  1456. pMemoryRequirements);
  1457. return VULKAN_INTERNAL_FindBestMemoryTypes(
  1458. renderer,
  1459. pMemoryRequirements->memoryTypeBits,
  1460. 0,
  1461. preferredMemoryPropertyFlags,
  1462. 0,
  1463. pCount);
  1464. }
  1465. static void VULKAN_INTERNAL_DeallocateMemory(
  1466. VulkanRenderer *renderer,
  1467. VulkanMemorySubAllocator *allocator,
  1468. Uint32 allocationIndex)
  1469. {
  1470. Uint32 i;
  1471. VulkanMemoryAllocation *allocation = allocator->allocations[allocationIndex];
  1472. SDL_LockMutex(renderer->allocatorLock);
  1473. // If this allocation was marked for defrag, cancel that
  1474. for (i = 0; i < renderer->allocationsToDefragCount; i += 1) {
  1475. if (allocation == renderer->allocationsToDefrag[i]) {
  1476. renderer->allocationsToDefrag[i] = renderer->allocationsToDefrag[renderer->allocationsToDefragCount - 1];
  1477. renderer->allocationsToDefragCount -= 1;
  1478. break;
  1479. }
  1480. }
  1481. for (i = 0; i < allocation->freeRegionCount; i += 1) {
  1482. VULKAN_INTERNAL_RemoveMemoryFreeRegion(
  1483. renderer,
  1484. allocation->freeRegions[i]);
  1485. }
  1486. SDL_free(allocation->freeRegions);
  1487. /* no need to iterate used regions because deallocate
  1488. * only happens when there are 0 used regions
  1489. */
  1490. SDL_free(allocation->usedRegions);
  1491. renderer->vkFreeMemory(
  1492. renderer->logicalDevice,
  1493. allocation->memory,
  1494. NULL);
  1495. SDL_DestroyMutex(allocation->memoryLock);
  1496. SDL_free(allocation);
  1497. if (allocationIndex != allocator->allocationCount - 1) {
  1498. allocator->allocations[allocationIndex] = allocator->allocations[allocator->allocationCount - 1];
  1499. }
  1500. allocator->allocationCount -= 1;
  1501. SDL_UnlockMutex(renderer->allocatorLock);
  1502. }
  1503. static Uint8 VULKAN_INTERNAL_AllocateMemory(
  1504. VulkanRenderer *renderer,
  1505. VkBuffer buffer,
  1506. VkImage image,
  1507. Uint32 memoryTypeIndex,
  1508. VkDeviceSize allocationSize,
  1509. Uint8 isHostVisible,
  1510. VulkanMemoryAllocation **pMemoryAllocation)
  1511. {
  1512. VulkanMemoryAllocation *allocation;
  1513. VulkanMemorySubAllocator *allocator = &renderer->memoryAllocator->subAllocators[memoryTypeIndex];
  1514. VkMemoryAllocateInfo allocInfo;
  1515. VkResult result;
  1516. allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  1517. allocInfo.pNext = NULL;
  1518. allocInfo.memoryTypeIndex = memoryTypeIndex;
  1519. allocInfo.allocationSize = allocationSize;
  1520. allocation = SDL_malloc(sizeof(VulkanMemoryAllocation));
  1521. allocation->size = allocationSize;
  1522. allocation->freeSpace = 0; // added by FreeRegions
  1523. allocation->usedSpace = 0; // added by UsedRegions
  1524. allocation->memoryLock = SDL_CreateMutex();
  1525. allocator->allocationCount += 1;
  1526. allocator->allocations = SDL_realloc(
  1527. allocator->allocations,
  1528. sizeof(VulkanMemoryAllocation *) * allocator->allocationCount);
  1529. allocator->allocations[allocator->allocationCount - 1] = allocation;
  1530. allocInfo.pNext = NULL;
  1531. allocation->availableForAllocation = 1;
  1532. allocation->usedRegions = SDL_malloc(sizeof(VulkanMemoryUsedRegion *));
  1533. allocation->usedRegionCount = 0;
  1534. allocation->usedRegionCapacity = 1;
  1535. allocation->freeRegions = SDL_malloc(sizeof(VulkanMemoryFreeRegion *));
  1536. allocation->freeRegionCount = 0;
  1537. allocation->freeRegionCapacity = 1;
  1538. allocation->allocator = allocator;
  1539. result = renderer->vkAllocateMemory(
  1540. renderer->logicalDevice,
  1541. &allocInfo,
  1542. NULL,
  1543. &allocation->memory);
  1544. if (result != VK_SUCCESS) {
  1545. // Uh oh, we couldn't allocate, time to clean up
  1546. SDL_free(allocation->freeRegions);
  1547. allocator->allocationCount -= 1;
  1548. allocator->allocations = SDL_realloc(
  1549. allocator->allocations,
  1550. sizeof(VulkanMemoryAllocation *) * allocator->allocationCount);
  1551. SDL_free(allocation);
  1552. return 0;
  1553. }
  1554. // Persistent mapping for host-visible memory
  1555. if (isHostVisible) {
  1556. result = renderer->vkMapMemory(
  1557. renderer->logicalDevice,
  1558. allocation->memory,
  1559. 0,
  1560. VK_WHOLE_SIZE,
  1561. 0,
  1562. (void **)&allocation->mapPointer);
  1563. CHECK_VULKAN_ERROR_AND_RETURN(result, vkMapMemory, 0);
  1564. } else {
  1565. allocation->mapPointer = NULL;
  1566. }
  1567. VULKAN_INTERNAL_NewMemoryFreeRegion(
  1568. renderer,
  1569. allocation,
  1570. 0,
  1571. allocation->size);
  1572. *pMemoryAllocation = allocation;
  1573. return 1;
  1574. }
  1575. static Uint8 VULKAN_INTERNAL_BindBufferMemory(
  1576. VulkanRenderer *renderer,
  1577. VulkanMemoryUsedRegion *usedRegion,
  1578. VkDeviceSize alignedOffset,
  1579. VkBuffer buffer)
  1580. {
  1581. VkResult vulkanResult;
  1582. SDL_LockMutex(usedRegion->allocation->memoryLock);
  1583. vulkanResult = renderer->vkBindBufferMemory(
  1584. renderer->logicalDevice,
  1585. buffer,
  1586. usedRegion->allocation->memory,
  1587. alignedOffset);
  1588. SDL_UnlockMutex(usedRegion->allocation->memoryLock);
  1589. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkBindBufferMemory, 0);
  1590. return 1;
  1591. }
  1592. static Uint8 VULKAN_INTERNAL_BindImageMemory(
  1593. VulkanRenderer *renderer,
  1594. VulkanMemoryUsedRegion *usedRegion,
  1595. VkDeviceSize alignedOffset,
  1596. VkImage image)
  1597. {
  1598. VkResult vulkanResult;
  1599. SDL_LockMutex(usedRegion->allocation->memoryLock);
  1600. vulkanResult = renderer->vkBindImageMemory(
  1601. renderer->logicalDevice,
  1602. image,
  1603. usedRegion->allocation->memory,
  1604. alignedOffset);
  1605. SDL_UnlockMutex(usedRegion->allocation->memoryLock);
  1606. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkBindImageMemory, 0);
  1607. return 1;
  1608. }
  1609. static Uint8 VULKAN_INTERNAL_BindResourceMemory(
  1610. VulkanRenderer *renderer,
  1611. Uint32 memoryTypeIndex,
  1612. VkMemoryRequirements *memoryRequirements,
  1613. VkDeviceSize resourceSize, // may be different from requirements size!
  1614. bool dedicated, // the entire memory allocation should be used for this resource
  1615. VkBuffer buffer, // may be VK_NULL_HANDLE
  1616. VkImage image, // may be VK_NULL_HANDLE
  1617. VulkanMemoryUsedRegion **pMemoryUsedRegion)
  1618. {
  1619. VulkanMemoryAllocation *allocation;
  1620. VulkanMemorySubAllocator *allocator;
  1621. VulkanMemoryFreeRegion *region;
  1622. VulkanMemoryFreeRegion *selectedRegion;
  1623. VulkanMemoryUsedRegion *usedRegion;
  1624. VkDeviceSize requiredSize, allocationSize;
  1625. VkDeviceSize alignedOffset = 0;
  1626. VkDeviceSize newRegionSize, newRegionOffset;
  1627. Uint8 isHostVisible, smallAllocation, allocationResult;
  1628. Sint32 i;
  1629. isHostVisible =
  1630. (renderer->memoryProperties.memoryTypes[memoryTypeIndex].propertyFlags &
  1631. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0;
  1632. allocator = &renderer->memoryAllocator->subAllocators[memoryTypeIndex];
  1633. requiredSize = memoryRequirements->size;
  1634. smallAllocation = requiredSize <= SMALL_ALLOCATION_THRESHOLD;
  1635. if ((buffer == VK_NULL_HANDLE && image == VK_NULL_HANDLE) ||
  1636. (buffer != VK_NULL_HANDLE && image != VK_NULL_HANDLE)) {
  1637. SDL_LogError(SDL_LOG_CATEGORY_GPU, "BindResourceMemory must be given either a VulkanBuffer or a VulkanTexture");
  1638. return 0;
  1639. }
  1640. SDL_LockMutex(renderer->allocatorLock);
  1641. selectedRegion = NULL;
  1642. if (dedicated) {
  1643. // Force an allocation
  1644. allocationSize = requiredSize;
  1645. } else {
  1646. // Search for a suitable existing free region
  1647. for (i = allocator->sortedFreeRegionCount - 1; i >= 0; i -= 1) {
  1648. region = allocator->sortedFreeRegions[i];
  1649. if (smallAllocation && region->allocation->size != SMALL_ALLOCATION_SIZE) {
  1650. // region is not in a small allocation
  1651. continue;
  1652. }
  1653. if (!smallAllocation && region->allocation->size == SMALL_ALLOCATION_SIZE) {
  1654. // allocation is not small and current region is in a small allocation
  1655. continue;
  1656. }
  1657. alignedOffset = VULKAN_INTERNAL_NextHighestAlignment(
  1658. region->offset,
  1659. memoryRequirements->alignment);
  1660. if (alignedOffset + requiredSize <= region->offset + region->size) {
  1661. selectedRegion = region;
  1662. break;
  1663. }
  1664. }
  1665. if (selectedRegion != NULL) {
  1666. region = selectedRegion;
  1667. allocation = region->allocation;
  1668. usedRegion = VULKAN_INTERNAL_NewMemoryUsedRegion(
  1669. renderer,
  1670. allocation,
  1671. region->offset,
  1672. requiredSize + (alignedOffset - region->offset),
  1673. alignedOffset,
  1674. resourceSize,
  1675. memoryRequirements->alignment);
  1676. usedRegion->isBuffer = buffer != VK_NULL_HANDLE;
  1677. newRegionSize = region->size - ((alignedOffset - region->offset) + requiredSize);
  1678. newRegionOffset = alignedOffset + requiredSize;
  1679. // remove and add modified region to re-sort
  1680. VULKAN_INTERNAL_RemoveMemoryFreeRegion(renderer, region);
  1681. // if size is 0, no need to re-insert
  1682. if (newRegionSize != 0) {
  1683. VULKAN_INTERNAL_NewMemoryFreeRegion(
  1684. renderer,
  1685. allocation,
  1686. newRegionOffset,
  1687. newRegionSize);
  1688. }
  1689. SDL_UnlockMutex(renderer->allocatorLock);
  1690. if (buffer != VK_NULL_HANDLE) {
  1691. if (!VULKAN_INTERNAL_BindBufferMemory(
  1692. renderer,
  1693. usedRegion,
  1694. alignedOffset,
  1695. buffer)) {
  1696. VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  1697. renderer,
  1698. usedRegion);
  1699. return 0;
  1700. }
  1701. } else if (image != VK_NULL_HANDLE) {
  1702. if (!VULKAN_INTERNAL_BindImageMemory(
  1703. renderer,
  1704. usedRegion,
  1705. alignedOffset,
  1706. image)) {
  1707. VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  1708. renderer,
  1709. usedRegion);
  1710. return 0;
  1711. }
  1712. }
  1713. *pMemoryUsedRegion = usedRegion;
  1714. return 1;
  1715. }
  1716. // No suitable free regions exist, allocate a new memory region
  1717. if (
  1718. renderer->allocationsToDefragCount == 0 &&
  1719. !renderer->defragInProgress) {
  1720. // Mark currently fragmented allocations for defrag
  1721. VULKAN_INTERNAL_MarkAllocationsForDefrag(renderer);
  1722. }
  1723. if (requiredSize > SMALL_ALLOCATION_THRESHOLD) {
  1724. // allocate a page of required size aligned to LARGE_ALLOCATION_INCREMENT increments
  1725. allocationSize =
  1726. VULKAN_INTERNAL_NextHighestAlignment(requiredSize, LARGE_ALLOCATION_INCREMENT);
  1727. } else {
  1728. allocationSize = SMALL_ALLOCATION_SIZE;
  1729. }
  1730. }
  1731. allocationResult = VULKAN_INTERNAL_AllocateMemory(
  1732. renderer,
  1733. buffer,
  1734. image,
  1735. memoryTypeIndex,
  1736. allocationSize,
  1737. isHostVisible,
  1738. &allocation);
  1739. // Uh oh, we're out of memory
  1740. if (allocationResult == 0) {
  1741. SDL_UnlockMutex(renderer->allocatorLock);
  1742. // Responsibility of the caller to handle being out of memory
  1743. return 2;
  1744. }
  1745. usedRegion = VULKAN_INTERNAL_NewMemoryUsedRegion(
  1746. renderer,
  1747. allocation,
  1748. 0,
  1749. requiredSize,
  1750. 0,
  1751. resourceSize,
  1752. memoryRequirements->alignment);
  1753. usedRegion->isBuffer = buffer != VK_NULL_HANDLE;
  1754. region = allocation->freeRegions[0];
  1755. newRegionOffset = region->offset + requiredSize;
  1756. newRegionSize = region->size - requiredSize;
  1757. VULKAN_INTERNAL_RemoveMemoryFreeRegion(renderer, region);
  1758. if (newRegionSize != 0) {
  1759. VULKAN_INTERNAL_NewMemoryFreeRegion(
  1760. renderer,
  1761. allocation,
  1762. newRegionOffset,
  1763. newRegionSize);
  1764. }
  1765. SDL_UnlockMutex(renderer->allocatorLock);
  1766. if (buffer != VK_NULL_HANDLE) {
  1767. if (!VULKAN_INTERNAL_BindBufferMemory(
  1768. renderer,
  1769. usedRegion,
  1770. 0,
  1771. buffer)) {
  1772. VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  1773. renderer,
  1774. usedRegion);
  1775. return 0;
  1776. }
  1777. } else if (image != VK_NULL_HANDLE) {
  1778. if (!VULKAN_INTERNAL_BindImageMemory(
  1779. renderer,
  1780. usedRegion,
  1781. 0,
  1782. image)) {
  1783. VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  1784. renderer,
  1785. usedRegion);
  1786. return 0;
  1787. }
  1788. }
  1789. *pMemoryUsedRegion = usedRegion;
  1790. return 1;
  1791. }
  1792. static Uint8 VULKAN_INTERNAL_BindMemoryForImage(
  1793. VulkanRenderer *renderer,
  1794. VkImage image,
  1795. VulkanMemoryUsedRegion **usedRegion)
  1796. {
  1797. Uint8 bindResult = 0;
  1798. Uint32 memoryTypeCount = 0;
  1799. Uint32 *memoryTypesToTry = NULL;
  1800. Uint32 selectedMemoryTypeIndex = 0;
  1801. Uint32 i;
  1802. VkMemoryPropertyFlags preferredMemoryPropertyFlags;
  1803. VkMemoryRequirements memoryRequirements;
  1804. /* Vulkan memory types have several memory properties.
  1805. *
  1806. * Unlike buffers, images are always optimally stored device-local,
  1807. * so that is the only property we prefer here.
  1808. *
  1809. * If memory is constrained, it is fine for the texture to not
  1810. * be device-local.
  1811. */
  1812. preferredMemoryPropertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  1813. memoryTypesToTry = VULKAN_INTERNAL_FindBestImageMemoryTypes(
  1814. renderer,
  1815. image,
  1816. preferredMemoryPropertyFlags,
  1817. &memoryRequirements,
  1818. &memoryTypeCount);
  1819. for (i = 0; i < memoryTypeCount; i += 1) {
  1820. bindResult = VULKAN_INTERNAL_BindResourceMemory(
  1821. renderer,
  1822. memoryTypesToTry[i],
  1823. &memoryRequirements,
  1824. memoryRequirements.size,
  1825. false,
  1826. VK_NULL_HANDLE,
  1827. image,
  1828. usedRegion);
  1829. if (bindResult == 1) {
  1830. selectedMemoryTypeIndex = memoryTypesToTry[i];
  1831. break;
  1832. }
  1833. }
  1834. SDL_free(memoryTypesToTry);
  1835. // Check for warnings on success
  1836. if (bindResult == 1) {
  1837. if (!renderer->outOfDeviceLocalMemoryWarning) {
  1838. if ((renderer->memoryProperties.memoryTypes[selectedMemoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0) {
  1839. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Out of device-local memory, allocating textures on host-local memory!");
  1840. renderer->outOfDeviceLocalMemoryWarning = 1;
  1841. }
  1842. }
  1843. }
  1844. return bindResult;
  1845. }
  1846. static Uint8 VULKAN_INTERNAL_BindMemoryForBuffer(
  1847. VulkanRenderer *renderer,
  1848. VkBuffer buffer,
  1849. VkDeviceSize size,
  1850. VulkanBufferType type,
  1851. bool dedicated,
  1852. VulkanMemoryUsedRegion **usedRegion)
  1853. {
  1854. Uint8 bindResult = 0;
  1855. Uint32 memoryTypeCount = 0;
  1856. Uint32 *memoryTypesToTry = NULL;
  1857. Uint32 selectedMemoryTypeIndex = 0;
  1858. Uint32 i;
  1859. VkMemoryPropertyFlags requiredMemoryPropertyFlags = 0;
  1860. VkMemoryPropertyFlags preferredMemoryPropertyFlags = 0;
  1861. VkMemoryPropertyFlags tolerableMemoryPropertyFlags = 0;
  1862. VkMemoryRequirements memoryRequirements;
  1863. /* Buffers need to be optimally bound to a memory type
  1864. * based on their use case and the architecture of the system.
  1865. *
  1866. * It is important to understand the distinction between device and host.
  1867. *
  1868. * On a traditional high-performance desktop computer,
  1869. * the "device" would be the GPU, and the "host" would be the CPU.
  1870. * Memory being copied between these two must cross the PCI bus.
  1871. * On these systems we have to be concerned about bandwidth limitations
  1872. * and causing memory stalls, so we have taken a great deal of care
  1873. * to structure this API to guide the client towards optimal usage.
  1874. *
  1875. * Other kinds of devices do not necessarily have this distinction.
  1876. * On an iPhone or Nintendo Switch, all memory is accessible both to the
  1877. * GPU and the CPU at all times. These kinds of systems are known as
  1878. * UMA, or Unified Memory Architecture. A desktop computer using the
  1879. * CPU's integrated graphics can also be thought of as UMA.
  1880. *
  1881. * Vulkan memory types have several memory properties.
  1882. * The relevant memory properties are as follows:
  1883. *
  1884. * DEVICE_LOCAL:
  1885. * This memory is on-device and most efficient for device access.
  1886. * On UMA systems all memory is device-local.
  1887. * If memory is not device-local, then it is host-local.
  1888. *
  1889. * HOST_VISIBLE:
  1890. * This memory can be mapped for host access, meaning we can obtain
  1891. * a pointer to directly access the memory.
  1892. *
  1893. * HOST_COHERENT:
  1894. * Host-coherent memory does not require cache management operations
  1895. * when mapped, so we always set this alongside HOST_VISIBLE
  1896. * to avoid extra record keeping.
  1897. *
  1898. * HOST_CACHED:
  1899. * Host-cached memory is faster to access than uncached memory
  1900. * but memory of this type might not always be available.
  1901. *
  1902. * GPU buffers, like vertex buffers, indirect buffers, etc
  1903. * are optimally stored in device-local memory.
  1904. * However, if device-local memory is low, these buffers
  1905. * can be accessed from host-local memory with a performance penalty.
  1906. *
  1907. * Uniform buffers must be host-visible and coherent because
  1908. * the client uses them to quickly push small amounts of data.
  1909. * We prefer uniform buffers to also be device-local because
  1910. * they are accessed by shaders, but the amount of memory
  1911. * that is both device-local and host-visible
  1912. * is often constrained, particularly on low-end devices.
  1913. *
  1914. * Transfer buffers must be host-visible and coherent because
  1915. * the client uses them to stage data to be transferred
  1916. * to device-local memory, or to read back data transferred
  1917. * from the device. We prefer the cache bit for performance
  1918. * but it isn't strictly necessary. We tolerate device-local
  1919. * memory in this situation because, as mentioned above,
  1920. * on certain devices all memory is device-local, and even
  1921. * though the transfer isn't strictly necessary it is still
  1922. * useful for correctly timelining data.
  1923. */
  1924. if (type == VULKAN_BUFFER_TYPE_GPU) {
  1925. preferredMemoryPropertyFlags |=
  1926. VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  1927. } else if (type == VULKAN_BUFFER_TYPE_UNIFORM) {
  1928. requiredMemoryPropertyFlags |=
  1929. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
  1930. VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
  1931. preferredMemoryPropertyFlags |=
  1932. VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  1933. } else if (type == VULKAN_BUFFER_TYPE_TRANSFER) {
  1934. requiredMemoryPropertyFlags |=
  1935. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
  1936. VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
  1937. preferredMemoryPropertyFlags |=
  1938. VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  1939. tolerableMemoryPropertyFlags |=
  1940. VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  1941. } else {
  1942. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized buffer type!");
  1943. return 0;
  1944. }
  1945. memoryTypesToTry = VULKAN_INTERNAL_FindBestBufferMemoryTypes(
  1946. renderer,
  1947. buffer,
  1948. requiredMemoryPropertyFlags,
  1949. preferredMemoryPropertyFlags,
  1950. tolerableMemoryPropertyFlags,
  1951. &memoryRequirements,
  1952. &memoryTypeCount);
  1953. for (i = 0; i < memoryTypeCount; i += 1) {
  1954. bindResult = VULKAN_INTERNAL_BindResourceMemory(
  1955. renderer,
  1956. memoryTypesToTry[i],
  1957. &memoryRequirements,
  1958. size,
  1959. dedicated,
  1960. buffer,
  1961. VK_NULL_HANDLE,
  1962. usedRegion);
  1963. if (bindResult == 1) {
  1964. selectedMemoryTypeIndex = memoryTypesToTry[i];
  1965. break;
  1966. }
  1967. }
  1968. SDL_free(memoryTypesToTry);
  1969. // Check for warnings on success
  1970. if (bindResult == 1) {
  1971. if (type == VULKAN_BUFFER_TYPE_GPU) {
  1972. if (!renderer->outOfDeviceLocalMemoryWarning) {
  1973. if ((renderer->memoryProperties.memoryTypes[selectedMemoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0) {
  1974. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Out of device-local memory, allocating buffers on host-local memory, expect degraded performance!");
  1975. renderer->outOfDeviceLocalMemoryWarning = 1;
  1976. }
  1977. }
  1978. } else if (type == VULKAN_BUFFER_TYPE_UNIFORM) {
  1979. if (!renderer->outofBARMemoryWarning) {
  1980. if ((renderer->memoryProperties.memoryTypes[selectedMemoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0) {
  1981. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Out of BAR memory, allocating uniform buffers on host-local memory, expect degraded performance!");
  1982. renderer->outofBARMemoryWarning = 1;
  1983. }
  1984. }
  1985. } else if (type == VULKAN_BUFFER_TYPE_TRANSFER) {
  1986. if (!renderer->integratedMemoryNotification) {
  1987. if ((renderer->memoryProperties.memoryTypes[selectedMemoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
  1988. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "Integrated memory detected, allocating TransferBuffers on device-local memory!");
  1989. renderer->integratedMemoryNotification = 1;
  1990. }
  1991. }
  1992. }
  1993. }
  1994. return bindResult;
  1995. }
  1996. // Resource tracking
  1997. #define ADD_TO_ARRAY_UNIQUE(resource, type, array, count, capacity) \
  1998. Uint32 i; \
  1999. \
  2000. for (i = 0; i < commandBuffer->count; i += 1) { \
  2001. if (commandBuffer->array[i] == resource) { \
  2002. return; \
  2003. } \
  2004. } \
  2005. \
  2006. if (commandBuffer->count == commandBuffer->capacity) { \
  2007. commandBuffer->capacity += 1; \
  2008. commandBuffer->array = SDL_realloc( \
  2009. commandBuffer->array, \
  2010. commandBuffer->capacity * sizeof(type)); \
  2011. } \
  2012. commandBuffer->array[commandBuffer->count] = resource; \
  2013. commandBuffer->count += 1;
  2014. #define TRACK_RESOURCE(resource, type, array, count, capacity) \
  2015. for (Sint32 i = commandBuffer->count - 1; i >= 0; i -= 1) { \
  2016. if (commandBuffer->array[i] == resource) { \
  2017. return; \
  2018. } \
  2019. } \
  2020. \
  2021. if (commandBuffer->count == commandBuffer->capacity) { \
  2022. commandBuffer->capacity += 1; \
  2023. commandBuffer->array = SDL_realloc( \
  2024. commandBuffer->array, \
  2025. commandBuffer->capacity * sizeof(type)); \
  2026. } \
  2027. commandBuffer->array[commandBuffer->count] = resource; \
  2028. commandBuffer->count += 1; \
  2029. SDL_AtomicIncRef(&resource->referenceCount);
  2030. static void VULKAN_INTERNAL_TrackBuffer(
  2031. VulkanCommandBuffer *commandBuffer,
  2032. VulkanBuffer *buffer)
  2033. {
  2034. TRACK_RESOURCE(
  2035. buffer,
  2036. VulkanBuffer *,
  2037. usedBuffers,
  2038. usedBufferCount,
  2039. usedBufferCapacity)
  2040. }
  2041. static void VULKAN_INTERNAL_TrackTexture(
  2042. VulkanCommandBuffer *commandBuffer,
  2043. VulkanTexture *texture)
  2044. {
  2045. TRACK_RESOURCE(
  2046. texture,
  2047. VulkanTexture *,
  2048. usedTextures,
  2049. usedTextureCount,
  2050. usedTextureCapacity)
  2051. }
  2052. static void VULKAN_INTERNAL_TrackSampler(
  2053. VulkanCommandBuffer *commandBuffer,
  2054. VulkanSampler *sampler)
  2055. {
  2056. TRACK_RESOURCE(
  2057. sampler,
  2058. VulkanSampler *,
  2059. usedSamplers,
  2060. usedSamplerCount,
  2061. usedSamplerCapacity)
  2062. }
  2063. static void VULKAN_INTERNAL_TrackGraphicsPipeline(
  2064. VulkanCommandBuffer *commandBuffer,
  2065. VulkanGraphicsPipeline *graphicsPipeline)
  2066. {
  2067. TRACK_RESOURCE(
  2068. graphicsPipeline,
  2069. VulkanGraphicsPipeline *,
  2070. usedGraphicsPipelines,
  2071. usedGraphicsPipelineCount,
  2072. usedGraphicsPipelineCapacity)
  2073. }
  2074. static void VULKAN_INTERNAL_TrackComputePipeline(
  2075. VulkanCommandBuffer *commandBuffer,
  2076. VulkanComputePipeline *computePipeline)
  2077. {
  2078. TRACK_RESOURCE(
  2079. computePipeline,
  2080. VulkanComputePipeline *,
  2081. usedComputePipelines,
  2082. usedComputePipelineCount,
  2083. usedComputePipelineCapacity)
  2084. }
  2085. static void VULKAN_INTERNAL_TrackFramebuffer(
  2086. VulkanRenderer *renderer,
  2087. VulkanCommandBuffer *commandBuffer,
  2088. VulkanFramebuffer *framebuffer)
  2089. {
  2090. TRACK_RESOURCE(
  2091. framebuffer,
  2092. VulkanFramebuffer *,
  2093. usedFramebuffers,
  2094. usedFramebufferCount,
  2095. usedFramebufferCapacity);
  2096. }
  2097. static void VULKAN_INTERNAL_TrackUniformBuffer(
  2098. VulkanCommandBuffer *commandBuffer,
  2099. VulkanUniformBuffer *uniformBuffer)
  2100. {
  2101. for (Sint32 i = commandBuffer->usedUniformBufferCount - 1; i >= 0; i -= 1) {
  2102. if (commandBuffer->usedUniformBuffers[i] == uniformBuffer) {
  2103. return;
  2104. }
  2105. }
  2106. if (commandBuffer->usedUniformBufferCount == commandBuffer->usedUniformBufferCapacity) {
  2107. commandBuffer->usedUniformBufferCapacity += 1;
  2108. commandBuffer->usedUniformBuffers = SDL_realloc(
  2109. commandBuffer->usedUniformBuffers,
  2110. commandBuffer->usedUniformBufferCapacity * sizeof(VulkanUniformBuffer *));
  2111. }
  2112. commandBuffer->usedUniformBuffers[commandBuffer->usedUniformBufferCount] = uniformBuffer;
  2113. commandBuffer->usedUniformBufferCount += 1;
  2114. VULKAN_INTERNAL_TrackBuffer(
  2115. commandBuffer,
  2116. uniformBuffer->buffer);
  2117. }
  2118. #undef TRACK_RESOURCE
  2119. // Memory Barriers
  2120. /*
  2121. * In Vulkan, we must manually synchronize operations that write to resources on the GPU
  2122. * so that read-after-write, write-after-read, and write-after-write hazards do not occur.
  2123. * Additionally, textures are required to be in specific layouts for specific use cases.
  2124. * Both of these tasks are accomplished with vkCmdPipelineBarrier.
  2125. *
  2126. * To insert the correct barriers, we keep track of "usage modes" for buffers and textures.
  2127. * These indicate the current usage of that resource on the command buffer.
  2128. * The transition from one usage mode to another indicates how the barrier should be constructed.
  2129. *
  2130. * Pipeline barriers cannot be inserted during a render pass, but they can be inserted
  2131. * during a compute or copy pass.
  2132. *
  2133. * This means that the "default" usage mode of any given resource should be that it should be
  2134. * ready for a graphics-read operation, because we cannot barrier during a render pass.
  2135. * In the case where a resource is only used in compute, its default usage mode can be compute-read.
  2136. * This strategy allows us to avoid expensive record keeping of command buffer/resource usage mode pairs,
  2137. * and it fully covers synchronization between all combinations of stages.
  2138. *
  2139. * In Upload and Copy functions, we transition the resource immediately before and after the copy command.
  2140. *
  2141. * When binding a resource for compute, we transition when the Bind functions are called.
  2142. * If a bind slot containing a resource is overwritten, we transition the resource in that slot back to its default.
  2143. * When EndComputePass is called we transition all bound resources back to their default state.
  2144. *
  2145. * When binding a texture as a render pass attachment, we transition the resource on BeginRenderPass
  2146. * and transition it back to its default on EndRenderPass.
  2147. *
  2148. * This strategy imposes certain limitations on resource usage flags.
  2149. * For example, a texture cannot have both the SAMPLER and GRAPHICS_STORAGE usage flags,
  2150. * because then it is impossible for the backend to infer which default usage mode the texture should use.
  2151. *
  2152. * Sync hazards can be detected by setting VK_KHRONOS_VALIDATION_VALIDATE_SYNC=1 when using validation layers.
  2153. */
  2154. static void VULKAN_INTERNAL_BufferMemoryBarrier(
  2155. VulkanRenderer *renderer,
  2156. VulkanCommandBuffer *commandBuffer,
  2157. VulkanBufferUsageMode sourceUsageMode,
  2158. VulkanBufferUsageMode destinationUsageMode,
  2159. VulkanBuffer *buffer)
  2160. {
  2161. VkPipelineStageFlags srcStages = 0;
  2162. VkPipelineStageFlags dstStages = 0;
  2163. VkBufferMemoryBarrier memoryBarrier;
  2164. memoryBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
  2165. memoryBarrier.pNext = NULL;
  2166. memoryBarrier.srcAccessMask = 0;
  2167. memoryBarrier.dstAccessMask = 0;
  2168. memoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2169. memoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2170. memoryBarrier.buffer = buffer->buffer;
  2171. memoryBarrier.offset = 0;
  2172. memoryBarrier.size = buffer->size;
  2173. if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE) {
  2174. srcStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2175. memoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2176. } else if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION) {
  2177. srcStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2178. memoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2179. } else if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_VERTEX_READ) {
  2180. srcStages = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  2181. memoryBarrier.srcAccessMask = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
  2182. } else if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_INDEX_READ) {
  2183. srcStages = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  2184. memoryBarrier.srcAccessMask = VK_ACCESS_INDEX_READ_BIT;
  2185. } else if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_INDIRECT) {
  2186. srcStages = VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
  2187. memoryBarrier.srcAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
  2188. } else if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_GRAPHICS_STORAGE_READ) {
  2189. srcStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2190. memoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2191. } else if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ) {
  2192. srcStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2193. memoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2194. } else if (sourceUsageMode == VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE) {
  2195. srcStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2196. memoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2197. } else {
  2198. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized buffer source barrier type!");
  2199. return;
  2200. }
  2201. if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE) {
  2202. dstStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2203. memoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2204. } else if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION) {
  2205. dstStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2206. memoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2207. } else if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_VERTEX_READ) {
  2208. dstStages = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  2209. memoryBarrier.dstAccessMask = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
  2210. } else if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_INDEX_READ) {
  2211. dstStages = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
  2212. memoryBarrier.dstAccessMask = VK_ACCESS_INDEX_READ_BIT;
  2213. } else if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_INDIRECT) {
  2214. dstStages = VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
  2215. memoryBarrier.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
  2216. } else if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_GRAPHICS_STORAGE_READ) {
  2217. dstStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2218. memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2219. } else if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ) {
  2220. dstStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2221. memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2222. } else if (destinationUsageMode == VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE) {
  2223. dstStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2224. memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2225. } else {
  2226. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized buffer destination barrier type!");
  2227. return;
  2228. }
  2229. renderer->vkCmdPipelineBarrier(
  2230. commandBuffer->commandBuffer,
  2231. srcStages,
  2232. dstStages,
  2233. 0,
  2234. 0,
  2235. NULL,
  2236. 1,
  2237. &memoryBarrier,
  2238. 0,
  2239. NULL);
  2240. buffer->transitioned = true;
  2241. }
  2242. static void VULKAN_INTERNAL_TextureSubresourceMemoryBarrier(
  2243. VulkanRenderer *renderer,
  2244. VulkanCommandBuffer *commandBuffer,
  2245. VulkanTextureUsageMode sourceUsageMode,
  2246. VulkanTextureUsageMode destinationUsageMode,
  2247. VulkanTextureSubresource *textureSubresource)
  2248. {
  2249. VkPipelineStageFlags srcStages = 0;
  2250. VkPipelineStageFlags dstStages = 0;
  2251. VkImageMemoryBarrier memoryBarrier;
  2252. memoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  2253. memoryBarrier.pNext = NULL;
  2254. memoryBarrier.srcAccessMask = 0;
  2255. memoryBarrier.dstAccessMask = 0;
  2256. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2257. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2258. memoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2259. memoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  2260. memoryBarrier.image = textureSubresource->parent->image;
  2261. memoryBarrier.subresourceRange.aspectMask = textureSubresource->parent->aspectFlags;
  2262. memoryBarrier.subresourceRange.baseArrayLayer = textureSubresource->layer;
  2263. memoryBarrier.subresourceRange.layerCount = 1;
  2264. memoryBarrier.subresourceRange.baseMipLevel = textureSubresource->level;
  2265. memoryBarrier.subresourceRange.levelCount = 1;
  2266. if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_UNINITIALIZED) {
  2267. srcStages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  2268. memoryBarrier.srcAccessMask = 0;
  2269. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2270. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE) {
  2271. srcStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2272. memoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2273. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2274. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION) {
  2275. srcStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2276. memoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2277. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2278. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_SAMPLER) {
  2279. srcStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2280. memoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2281. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  2282. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_GRAPHICS_STORAGE_READ) {
  2283. srcStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2284. memoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2285. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
  2286. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ) {
  2287. srcStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2288. memoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2289. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
  2290. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE) {
  2291. srcStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2292. memoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2293. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
  2294. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT) {
  2295. srcStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  2296. memoryBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  2297. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  2298. } else if (sourceUsageMode == VULKAN_TEXTURE_USAGE_MODE_DEPTH_STENCIL_ATTACHMENT) {
  2299. srcStages = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  2300. memoryBarrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  2301. memoryBarrier.oldLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  2302. } else {
  2303. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized texture source barrier type!");
  2304. return;
  2305. }
  2306. if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE) {
  2307. dstStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2308. memoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  2309. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
  2310. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION) {
  2311. dstStages = VK_PIPELINE_STAGE_TRANSFER_BIT;
  2312. memoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  2313. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
  2314. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_SAMPLER) {
  2315. dstStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2316. memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2317. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  2318. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_GRAPHICS_STORAGE_READ) {
  2319. dstStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
  2320. memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2321. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  2322. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ) {
  2323. dstStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2324. memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
  2325. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  2326. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE) {
  2327. dstStages = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
  2328. memoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
  2329. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_GENERAL;
  2330. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT) {
  2331. dstStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  2332. memoryBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  2333. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  2334. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_DEPTH_STENCIL_ATTACHMENT) {
  2335. dstStages = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  2336. memoryBarrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  2337. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  2338. } else if (destinationUsageMode == VULKAN_TEXTURE_USAGE_MODE_PRESENT) {
  2339. dstStages = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  2340. memoryBarrier.dstAccessMask = 0;
  2341. memoryBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
  2342. } else {
  2343. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized texture destination barrier type!");
  2344. return;
  2345. }
  2346. renderer->vkCmdPipelineBarrier(
  2347. commandBuffer->commandBuffer,
  2348. srcStages,
  2349. dstStages,
  2350. 0,
  2351. 0,
  2352. NULL,
  2353. 0,
  2354. NULL,
  2355. 1,
  2356. &memoryBarrier);
  2357. }
  2358. static VulkanBufferUsageMode VULKAN_INTERNAL_DefaultBufferUsageMode(
  2359. VulkanBuffer *buffer)
  2360. {
  2361. // NOTE: order matters here!
  2362. if (buffer->usage & SDL_GPU_BUFFERUSAGE_VERTEX) {
  2363. return VULKAN_BUFFER_USAGE_MODE_VERTEX_READ;
  2364. } else if (buffer->usage & SDL_GPU_BUFFERUSAGE_INDEX) {
  2365. return VULKAN_BUFFER_USAGE_MODE_INDEX_READ;
  2366. } else if (buffer->usage & SDL_GPU_BUFFERUSAGE_INDIRECT) {
  2367. return VULKAN_BUFFER_USAGE_MODE_INDIRECT;
  2368. } else if (buffer->usage & SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ) {
  2369. return VULKAN_BUFFER_USAGE_MODE_GRAPHICS_STORAGE_READ;
  2370. } else if (buffer->usage & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ) {
  2371. return VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ;
  2372. } else if (buffer->usage & SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE) {
  2373. return VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE;
  2374. } else {
  2375. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Buffer has no default usage mode!");
  2376. return VULKAN_BUFFER_USAGE_MODE_VERTEX_READ;
  2377. }
  2378. }
  2379. static VulkanTextureUsageMode VULKAN_INTERNAL_DefaultTextureUsageMode(
  2380. VulkanTexture *texture)
  2381. {
  2382. // NOTE: order matters here!
  2383. // NOTE: graphics storage bits and sampler bit are mutually exclusive!
  2384. if (texture->usage & SDL_GPU_TEXTUREUSAGE_SAMPLER) {
  2385. return VULKAN_TEXTURE_USAGE_MODE_SAMPLER;
  2386. } else if (texture->usage & SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ) {
  2387. return VULKAN_TEXTURE_USAGE_MODE_GRAPHICS_STORAGE_READ;
  2388. } else if (texture->usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) {
  2389. return VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT;
  2390. } else if (texture->usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) {
  2391. return VULKAN_TEXTURE_USAGE_MODE_DEPTH_STENCIL_ATTACHMENT;
  2392. } else if (texture->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ) {
  2393. return VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ;
  2394. } else if (texture->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE) {
  2395. return VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE;
  2396. } else if (texture->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE) {
  2397. return VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE;
  2398. } else {
  2399. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Texture has no default usage mode!");
  2400. return VULKAN_TEXTURE_USAGE_MODE_SAMPLER;
  2401. }
  2402. }
  2403. static void VULKAN_INTERNAL_BufferTransitionFromDefaultUsage(
  2404. VulkanRenderer *renderer,
  2405. VulkanCommandBuffer *commandBuffer,
  2406. VulkanBufferUsageMode destinationUsageMode,
  2407. VulkanBuffer *buffer)
  2408. {
  2409. VULKAN_INTERNAL_BufferMemoryBarrier(
  2410. renderer,
  2411. commandBuffer,
  2412. VULKAN_INTERNAL_DefaultBufferUsageMode(buffer),
  2413. destinationUsageMode,
  2414. buffer);
  2415. }
  2416. static void VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  2417. VulkanRenderer *renderer,
  2418. VulkanCommandBuffer *commandBuffer,
  2419. VulkanBufferUsageMode sourceUsageMode,
  2420. VulkanBuffer *buffer)
  2421. {
  2422. VULKAN_INTERNAL_BufferMemoryBarrier(
  2423. renderer,
  2424. commandBuffer,
  2425. sourceUsageMode,
  2426. VULKAN_INTERNAL_DefaultBufferUsageMode(buffer),
  2427. buffer);
  2428. }
  2429. static void VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  2430. VulkanRenderer *renderer,
  2431. VulkanCommandBuffer *commandBuffer,
  2432. VulkanTextureUsageMode destinationUsageMode,
  2433. VulkanTextureSubresource *textureSubresource)
  2434. {
  2435. VULKAN_INTERNAL_TextureSubresourceMemoryBarrier(
  2436. renderer,
  2437. commandBuffer,
  2438. VULKAN_INTERNAL_DefaultTextureUsageMode(textureSubresource->parent),
  2439. destinationUsageMode,
  2440. textureSubresource);
  2441. }
  2442. static void VULKAN_INTERNAL_TextureTransitionFromDefaultUsage(
  2443. VulkanRenderer *renderer,
  2444. VulkanCommandBuffer *commandBuffer,
  2445. VulkanTextureUsageMode destinationUsageMode,
  2446. VulkanTexture *texture)
  2447. {
  2448. for (Uint32 i = 0; i < texture->subresourceCount; i += 1) {
  2449. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  2450. renderer,
  2451. commandBuffer,
  2452. destinationUsageMode,
  2453. &texture->subresources[i]);
  2454. }
  2455. }
  2456. static void VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  2457. VulkanRenderer *renderer,
  2458. VulkanCommandBuffer *commandBuffer,
  2459. VulkanTextureUsageMode sourceUsageMode,
  2460. VulkanTextureSubresource *textureSubresource)
  2461. {
  2462. VULKAN_INTERNAL_TextureSubresourceMemoryBarrier(
  2463. renderer,
  2464. commandBuffer,
  2465. sourceUsageMode,
  2466. VULKAN_INTERNAL_DefaultTextureUsageMode(textureSubresource->parent),
  2467. textureSubresource);
  2468. }
  2469. static void VULKAN_INTERNAL_TextureTransitionToDefaultUsage(
  2470. VulkanRenderer *renderer,
  2471. VulkanCommandBuffer *commandBuffer,
  2472. VulkanTextureUsageMode sourceUsageMode,
  2473. VulkanTexture *texture)
  2474. {
  2475. // FIXME: could optimize this barrier
  2476. for (Uint32 i = 0; i < texture->subresourceCount; i += 1) {
  2477. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  2478. renderer,
  2479. commandBuffer,
  2480. sourceUsageMode,
  2481. &texture->subresources[i]);
  2482. }
  2483. }
  2484. // Resource Disposal
  2485. static void VULKAN_INTERNAL_ReleaseFramebuffer(
  2486. VulkanRenderer *renderer,
  2487. VulkanFramebuffer *framebuffer)
  2488. {
  2489. SDL_LockMutex(renderer->disposeLock);
  2490. EXPAND_ARRAY_IF_NEEDED(
  2491. renderer->framebuffersToDestroy,
  2492. VulkanFramebuffer *,
  2493. renderer->framebuffersToDestroyCount + 1,
  2494. renderer->framebuffersToDestroyCapacity,
  2495. renderer->framebuffersToDestroyCapacity * 2);
  2496. renderer->framebuffersToDestroy[renderer->framebuffersToDestroyCount] = framebuffer;
  2497. renderer->framebuffersToDestroyCount += 1;
  2498. SDL_UnlockMutex(renderer->disposeLock);
  2499. }
  2500. static void VULKAN_INTERNAL_DestroyFramebuffer(
  2501. VulkanRenderer *renderer,
  2502. VulkanFramebuffer *framebuffer)
  2503. {
  2504. renderer->vkDestroyFramebuffer(
  2505. renderer->logicalDevice,
  2506. framebuffer->framebuffer,
  2507. NULL);
  2508. SDL_free(framebuffer);
  2509. }
  2510. typedef struct CheckOneFramebufferForRemovalData
  2511. {
  2512. Uint32 keysToRemoveCapacity;
  2513. Uint32 keysToRemoveCount;
  2514. FramebufferHashTableKey **keysToRemove;
  2515. VkImageView view;
  2516. } CheckOneFramebufferForRemovalData;
  2517. static bool SDLCALL CheckOneFramebufferForRemoval(void *userdata, const SDL_HashTable *table, const void *vkey, const void *vvalue)
  2518. {
  2519. CheckOneFramebufferForRemovalData *data = (CheckOneFramebufferForRemovalData *) userdata;
  2520. FramebufferHashTableKey *key = (FramebufferHashTableKey *) vkey;
  2521. VkImageView view = data->view;
  2522. bool remove = false;
  2523. for (Uint32 i = 0; i < key->numColorTargets; i += 1) {
  2524. if (key->colorAttachmentViews[i] == view) {
  2525. remove = true;
  2526. }
  2527. }
  2528. for (Uint32 i = 0; i < key->numResolveAttachments; i += 1) {
  2529. if (key->resolveAttachmentViews[i] == view) {
  2530. remove = true;
  2531. }
  2532. }
  2533. if (key->depthStencilAttachmentView == view) {
  2534. remove = true;
  2535. }
  2536. if (remove) {
  2537. if (data->keysToRemoveCount == data->keysToRemoveCapacity) {
  2538. data->keysToRemoveCapacity *= 2;
  2539. void *ptr = SDL_realloc(data->keysToRemove, data->keysToRemoveCapacity * sizeof(FramebufferHashTableKey *));
  2540. if (!ptr) {
  2541. return false; // ugh, stop iterating. We're in trouble.
  2542. }
  2543. data->keysToRemove = (FramebufferHashTableKey **) ptr;
  2544. }
  2545. data->keysToRemove[data->keysToRemoveCount] = key;
  2546. data->keysToRemoveCount++;
  2547. }
  2548. return true; // keep iterating.
  2549. }
  2550. static void VULKAN_INTERNAL_RemoveFramebuffersContainingView(
  2551. VulkanRenderer *renderer,
  2552. VkImageView view)
  2553. {
  2554. // Can't remove while iterating!
  2555. CheckOneFramebufferForRemovalData data = { 8, 0, NULL, view };
  2556. data.keysToRemove = (FramebufferHashTableKey **) SDL_malloc(data.keysToRemoveCapacity * sizeof(FramebufferHashTableKey *));
  2557. if (!data.keysToRemove) {
  2558. return; // uhoh.
  2559. }
  2560. SDL_LockMutex(renderer->framebufferFetchLock);
  2561. SDL_IterateHashTable(renderer->framebufferHashTable, CheckOneFramebufferForRemoval, &data);
  2562. for (Uint32 i = 0; i < data.keysToRemoveCount; i += 1) {
  2563. SDL_RemoveFromHashTable(renderer->framebufferHashTable, (void *)data.keysToRemove[i]);
  2564. }
  2565. SDL_UnlockMutex(renderer->framebufferFetchLock);
  2566. SDL_free(data.keysToRemove);
  2567. }
  2568. static void VULKAN_INTERNAL_DestroyTexture(
  2569. VulkanRenderer *renderer,
  2570. VulkanTexture *texture)
  2571. {
  2572. // Clean up subresources
  2573. for (Uint32 subresourceIndex = 0; subresourceIndex < texture->subresourceCount; subresourceIndex += 1) {
  2574. if (texture->subresources[subresourceIndex].renderTargetViews != NULL) {
  2575. for (Uint32 depthIndex = 0; depthIndex < texture->depth; depthIndex += 1) {
  2576. VULKAN_INTERNAL_RemoveFramebuffersContainingView(
  2577. renderer,
  2578. texture->subresources[subresourceIndex].renderTargetViews[depthIndex]);
  2579. }
  2580. for (Uint32 depthIndex = 0; depthIndex < texture->depth; depthIndex += 1) {
  2581. renderer->vkDestroyImageView(
  2582. renderer->logicalDevice,
  2583. texture->subresources[subresourceIndex].renderTargetViews[depthIndex],
  2584. NULL);
  2585. }
  2586. SDL_free(texture->subresources[subresourceIndex].renderTargetViews);
  2587. }
  2588. if (texture->subresources[subresourceIndex].computeWriteView != VK_NULL_HANDLE) {
  2589. renderer->vkDestroyImageView(
  2590. renderer->logicalDevice,
  2591. texture->subresources[subresourceIndex].computeWriteView,
  2592. NULL);
  2593. }
  2594. if (texture->subresources[subresourceIndex].depthStencilView != VK_NULL_HANDLE) {
  2595. VULKAN_INTERNAL_RemoveFramebuffersContainingView(
  2596. renderer,
  2597. texture->subresources[subresourceIndex].depthStencilView);
  2598. renderer->vkDestroyImageView(
  2599. renderer->logicalDevice,
  2600. texture->subresources[subresourceIndex].depthStencilView,
  2601. NULL);
  2602. }
  2603. }
  2604. SDL_free(texture->subresources);
  2605. if (texture->fullView) {
  2606. renderer->vkDestroyImageView(
  2607. renderer->logicalDevice,
  2608. texture->fullView,
  2609. NULL);
  2610. }
  2611. if (texture->image) {
  2612. renderer->vkDestroyImage(
  2613. renderer->logicalDevice,
  2614. texture->image,
  2615. NULL);
  2616. }
  2617. if (texture->usedRegion) {
  2618. VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  2619. renderer,
  2620. texture->usedRegion);
  2621. }
  2622. SDL_free(texture);
  2623. }
  2624. static void VULKAN_INTERNAL_DestroyBuffer(
  2625. VulkanRenderer *renderer,
  2626. VulkanBuffer *buffer)
  2627. {
  2628. renderer->vkDestroyBuffer(
  2629. renderer->logicalDevice,
  2630. buffer->buffer,
  2631. NULL);
  2632. VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  2633. renderer,
  2634. buffer->usedRegion);
  2635. SDL_free(buffer);
  2636. }
  2637. static void VULKAN_INTERNAL_DestroyCommandPool(
  2638. VulkanRenderer *renderer,
  2639. VulkanCommandPool *commandPool)
  2640. {
  2641. Uint32 i;
  2642. VulkanCommandBuffer *commandBuffer;
  2643. renderer->vkDestroyCommandPool(
  2644. renderer->logicalDevice,
  2645. commandPool->commandPool,
  2646. NULL);
  2647. for (i = 0; i < commandPool->inactiveCommandBufferCount; i += 1) {
  2648. commandBuffer = commandPool->inactiveCommandBuffers[i];
  2649. SDL_free(commandBuffer->presentDatas);
  2650. SDL_free(commandBuffer->waitSemaphores);
  2651. SDL_free(commandBuffer->signalSemaphores);
  2652. SDL_free(commandBuffer->usedBuffers);
  2653. SDL_free(commandBuffer->usedTextures);
  2654. SDL_free(commandBuffer->usedSamplers);
  2655. SDL_free(commandBuffer->usedGraphicsPipelines);
  2656. SDL_free(commandBuffer->usedComputePipelines);
  2657. SDL_free(commandBuffer->usedFramebuffers);
  2658. SDL_free(commandBuffer->usedUniformBuffers);
  2659. SDL_free(commandBuffer);
  2660. }
  2661. SDL_free(commandPool->inactiveCommandBuffers);
  2662. SDL_free(commandPool);
  2663. }
  2664. static void VULKAN_INTERNAL_DestroyDescriptorSetLayout(
  2665. VulkanRenderer *renderer,
  2666. DescriptorSetLayout *layout)
  2667. {
  2668. if (layout == NULL) {
  2669. return;
  2670. }
  2671. if (layout->descriptorSetLayout != VK_NULL_HANDLE) {
  2672. renderer->vkDestroyDescriptorSetLayout(
  2673. renderer->logicalDevice,
  2674. layout->descriptorSetLayout,
  2675. NULL);
  2676. }
  2677. SDL_free(layout);
  2678. }
  2679. static void VULKAN_INTERNAL_DestroyGraphicsPipeline(
  2680. VulkanRenderer *renderer,
  2681. VulkanGraphicsPipeline *graphicsPipeline)
  2682. {
  2683. renderer->vkDestroyPipeline(
  2684. renderer->logicalDevice,
  2685. graphicsPipeline->pipeline,
  2686. NULL);
  2687. (void)SDL_AtomicDecRef(&graphicsPipeline->vertexShader->referenceCount);
  2688. (void)SDL_AtomicDecRef(&graphicsPipeline->fragmentShader->referenceCount);
  2689. SDL_free(graphicsPipeline);
  2690. }
  2691. static void VULKAN_INTERNAL_DestroyComputePipeline(
  2692. VulkanRenderer *renderer,
  2693. VulkanComputePipeline *computePipeline)
  2694. {
  2695. if (computePipeline->pipeline != VK_NULL_HANDLE) {
  2696. renderer->vkDestroyPipeline(
  2697. renderer->logicalDevice,
  2698. computePipeline->pipeline,
  2699. NULL);
  2700. }
  2701. if (computePipeline->shaderModule != VK_NULL_HANDLE) {
  2702. renderer->vkDestroyShaderModule(
  2703. renderer->logicalDevice,
  2704. computePipeline->shaderModule,
  2705. NULL);
  2706. }
  2707. SDL_free(computePipeline);
  2708. }
  2709. static void VULKAN_INTERNAL_DestroyShader(
  2710. VulkanRenderer *renderer,
  2711. VulkanShader *vulkanShader)
  2712. {
  2713. renderer->vkDestroyShaderModule(
  2714. renderer->logicalDevice,
  2715. vulkanShader->shaderModule,
  2716. NULL);
  2717. SDL_free(vulkanShader->entrypointName);
  2718. SDL_free(vulkanShader);
  2719. }
  2720. static void VULKAN_INTERNAL_DestroySampler(
  2721. VulkanRenderer *renderer,
  2722. VulkanSampler *vulkanSampler)
  2723. {
  2724. renderer->vkDestroySampler(
  2725. renderer->logicalDevice,
  2726. vulkanSampler->sampler,
  2727. NULL);
  2728. SDL_free(vulkanSampler);
  2729. }
  2730. static void VULKAN_INTERNAL_DestroySwapchain(
  2731. VulkanRenderer *renderer,
  2732. WindowData *windowData)
  2733. {
  2734. Uint32 i;
  2735. if (windowData == NULL) {
  2736. return;
  2737. }
  2738. for (i = 0; i < windowData->imageCount; i += 1) {
  2739. VULKAN_INTERNAL_RemoveFramebuffersContainingView(
  2740. renderer,
  2741. windowData->textureContainers[i].activeTexture->subresources[0].renderTargetViews[0]);
  2742. renderer->vkDestroyImageView(
  2743. renderer->logicalDevice,
  2744. windowData->textureContainers[i].activeTexture->subresources[0].renderTargetViews[0],
  2745. NULL);
  2746. SDL_free(windowData->textureContainers[i].activeTexture->subresources[0].renderTargetViews);
  2747. SDL_free(windowData->textureContainers[i].activeTexture->subresources);
  2748. SDL_free(windowData->textureContainers[i].activeTexture);
  2749. }
  2750. SDL_free(windowData->textureContainers);
  2751. windowData->textureContainers = NULL;
  2752. if (windowData->swapchain) {
  2753. renderer->vkDestroySwapchainKHR(
  2754. renderer->logicalDevice,
  2755. windowData->swapchain,
  2756. NULL);
  2757. windowData->swapchain = VK_NULL_HANDLE;
  2758. }
  2759. if (windowData->surface) {
  2760. renderer->vkDestroySurfaceKHR(
  2761. renderer->instance,
  2762. windowData->surface,
  2763. NULL);
  2764. windowData->surface = VK_NULL_HANDLE;
  2765. }
  2766. for (i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  2767. if (windowData->imageAvailableSemaphore[i]) {
  2768. renderer->vkDestroySemaphore(
  2769. renderer->logicalDevice,
  2770. windowData->imageAvailableSemaphore[i],
  2771. NULL);
  2772. windowData->imageAvailableSemaphore[i] = VK_NULL_HANDLE;
  2773. }
  2774. }
  2775. for (i = 0; i < windowData->imageCount; i += 1) {
  2776. if (windowData->renderFinishedSemaphore[i]) {
  2777. renderer->vkDestroySemaphore(
  2778. renderer->logicalDevice,
  2779. windowData->renderFinishedSemaphore[i],
  2780. NULL);
  2781. windowData->renderFinishedSemaphore[i] = VK_NULL_HANDLE;
  2782. }
  2783. }
  2784. SDL_free(windowData->renderFinishedSemaphore);
  2785. windowData->renderFinishedSemaphore = NULL;
  2786. windowData->imageCount = 0;
  2787. }
  2788. static void VULKAN_INTERNAL_DestroyGraphicsPipelineResourceLayout(
  2789. VulkanRenderer *renderer,
  2790. VulkanGraphicsPipelineResourceLayout *resourceLayout)
  2791. {
  2792. if (resourceLayout->pipelineLayout != VK_NULL_HANDLE) {
  2793. renderer->vkDestroyPipelineLayout(
  2794. renderer->logicalDevice,
  2795. resourceLayout->pipelineLayout,
  2796. NULL);
  2797. }
  2798. SDL_free(resourceLayout);
  2799. }
  2800. static void VULKAN_INTERNAL_DestroyComputePipelineResourceLayout(
  2801. VulkanRenderer *renderer,
  2802. VulkanComputePipelineResourceLayout *resourceLayout)
  2803. {
  2804. if (resourceLayout->pipelineLayout != VK_NULL_HANDLE) {
  2805. renderer->vkDestroyPipelineLayout(
  2806. renderer->logicalDevice,
  2807. resourceLayout->pipelineLayout,
  2808. NULL);
  2809. }
  2810. SDL_free(resourceLayout);
  2811. }
  2812. static void VULKAN_INTERNAL_DestroyDescriptorSetCache(
  2813. VulkanRenderer *renderer,
  2814. DescriptorSetCache *descriptorSetCache)
  2815. {
  2816. for (Uint32 i = 0; i < descriptorSetCache->poolCount; i += 1) {
  2817. for (Uint32 j = 0; j < descriptorSetCache->pools[i].poolCount; j += 1) {
  2818. renderer->vkDestroyDescriptorPool(
  2819. renderer->logicalDevice,
  2820. descriptorSetCache->pools[i].descriptorPools[j],
  2821. NULL);
  2822. }
  2823. SDL_free(descriptorSetCache->pools[i].descriptorSets);
  2824. SDL_free(descriptorSetCache->pools[i].descriptorPools);
  2825. }
  2826. SDL_free(descriptorSetCache->pools);
  2827. SDL_free(descriptorSetCache);
  2828. }
  2829. // Hashtable functions
  2830. static Uint32 SDLCALL VULKAN_INTERNAL_GraphicsPipelineResourceLayoutHashFunction(void *userdata, const void *key)
  2831. {
  2832. GraphicsPipelineResourceLayoutHashTableKey *hashTableKey = (GraphicsPipelineResourceLayoutHashTableKey *)key;
  2833. /* The algorithm for this hashing function
  2834. * is taken from Josh Bloch's "Effective Java".
  2835. * (https://stackoverflow.com/a/113600/12492383)
  2836. */
  2837. const Uint32 hashFactor = 31;
  2838. Uint32 result = 1;
  2839. result = result * hashFactor + hashTableKey->vertexSamplerCount;
  2840. result = result * hashFactor + hashTableKey->vertexStorageBufferCount;
  2841. result = result * hashFactor + hashTableKey->vertexStorageTextureCount;
  2842. result = result * hashFactor + hashTableKey->vertexUniformBufferCount;
  2843. result = result * hashFactor + hashTableKey->fragmentSamplerCount;
  2844. result = result * hashFactor + hashTableKey->fragmentStorageBufferCount;
  2845. result = result * hashFactor + hashTableKey->fragmentStorageTextureCount;
  2846. result = result * hashFactor + hashTableKey->fragmentUniformBufferCount;
  2847. return result;
  2848. }
  2849. static bool SDLCALL VULKAN_INTERNAL_GraphicsPipelineResourceLayoutHashKeyMatch(void *userdata, const void *aKey, const void *bKey)
  2850. {
  2851. return SDL_memcmp(aKey, bKey, sizeof(GraphicsPipelineResourceLayoutHashTableKey)) == 0;
  2852. }
  2853. static void SDLCALL VULKAN_INTERNAL_GraphicsPipelineResourceLayoutHashDestroy(void *userdata, const void *key, const void *value)
  2854. {
  2855. VulkanRenderer *renderer = (VulkanRenderer *)userdata;
  2856. VulkanGraphicsPipelineResourceLayout *resourceLayout = (VulkanGraphicsPipelineResourceLayout *)value;
  2857. VULKAN_INTERNAL_DestroyGraphicsPipelineResourceLayout(renderer, resourceLayout);
  2858. SDL_free((void*)key);
  2859. }
  2860. static Uint32 SDLCALL VULKAN_INTERNAL_ComputePipelineResourceLayoutHashFunction(void *userdata, const void *key)
  2861. {
  2862. ComputePipelineResourceLayoutHashTableKey *hashTableKey = (ComputePipelineResourceLayoutHashTableKey *)key;
  2863. /* The algorithm for this hashing function
  2864. * is taken from Josh Bloch's "Effective Java".
  2865. * (https://stackoverflow.com/a/113600/12492383)
  2866. */
  2867. const Uint32 hashFactor = 31;
  2868. Uint32 result = 1;
  2869. result = result * hashFactor + hashTableKey->samplerCount;
  2870. result = result * hashFactor + hashTableKey->readonlyStorageTextureCount;
  2871. result = result * hashFactor + hashTableKey->readonlyStorageBufferCount;
  2872. result = result * hashFactor + hashTableKey->readWriteStorageTextureCount;
  2873. result = result * hashFactor + hashTableKey->readWriteStorageBufferCount;
  2874. result = result * hashFactor + hashTableKey->uniformBufferCount;
  2875. return result;
  2876. }
  2877. static bool SDLCALL VULKAN_INTERNAL_ComputePipelineResourceLayoutHashKeyMatch(void *userdata, const void *aKey, const void *bKey)
  2878. {
  2879. return SDL_memcmp(aKey, bKey, sizeof(ComputePipelineResourceLayoutHashTableKey)) == 0;
  2880. }
  2881. static void SDLCALL VULKAN_INTERNAL_ComputePipelineResourceLayoutHashDestroy(void *userdata, const void *key, const void *value)
  2882. {
  2883. VulkanRenderer *renderer = (VulkanRenderer *)userdata;
  2884. VulkanComputePipelineResourceLayout *resourceLayout = (VulkanComputePipelineResourceLayout *)value;
  2885. VULKAN_INTERNAL_DestroyComputePipelineResourceLayout(renderer, resourceLayout);
  2886. SDL_free((void*)key);
  2887. }
  2888. static Uint32 SDLCALL VULKAN_INTERNAL_DescriptorSetLayoutHashFunction(void *userdata, const void *key)
  2889. {
  2890. DescriptorSetLayoutHashTableKey *hashTableKey = (DescriptorSetLayoutHashTableKey *)key;
  2891. /* The algorithm for this hashing function
  2892. * is taken from Josh Bloch's "Effective Java".
  2893. * (https://stackoverflow.com/a/113600/12492383)
  2894. */
  2895. const Uint32 hashFactor = 31;
  2896. Uint32 result = 1;
  2897. result = result * hashFactor + hashTableKey->shaderStage;
  2898. result = result * hashFactor + hashTableKey->samplerCount;
  2899. result = result * hashFactor + hashTableKey->storageTextureCount;
  2900. result = result * hashFactor + hashTableKey->storageBufferCount;
  2901. result = result * hashFactor + hashTableKey->writeStorageTextureCount;
  2902. result = result * hashFactor + hashTableKey->writeStorageBufferCount;
  2903. result = result * hashFactor + hashTableKey->uniformBufferCount;
  2904. return result;
  2905. }
  2906. static bool SDLCALL VULKAN_INTERNAL_DescriptorSetLayoutHashKeyMatch(void *userdata, const void *aKey, const void *bKey)
  2907. {
  2908. return SDL_memcmp(aKey, bKey, sizeof(DescriptorSetLayoutHashTableKey)) == 0;
  2909. }
  2910. static void SDLCALL VULKAN_INTERNAL_DescriptorSetLayoutHashDestroy(void *userdata, const void *key, const void *value)
  2911. {
  2912. VulkanRenderer *renderer = (VulkanRenderer *)userdata;
  2913. DescriptorSetLayout *layout = (DescriptorSetLayout *)value;
  2914. VULKAN_INTERNAL_DestroyDescriptorSetLayout(renderer, layout);
  2915. SDL_free((void*)key);
  2916. }
  2917. static Uint32 SDLCALL VULKAN_INTERNAL_CommandPoolHashFunction(void *userdata, const void *key)
  2918. {
  2919. return (Uint32)((CommandPoolHashTableKey *)key)->threadID;
  2920. }
  2921. static bool SDLCALL VULKAN_INTERNAL_CommandPoolHashKeyMatch(void *userdata, const void *aKey, const void *bKey)
  2922. {
  2923. CommandPoolHashTableKey *a = (CommandPoolHashTableKey *)aKey;
  2924. CommandPoolHashTableKey *b = (CommandPoolHashTableKey *)bKey;
  2925. return a->threadID == b->threadID;
  2926. }
  2927. static void SDLCALL VULKAN_INTERNAL_CommandPoolHashDestroy(void *userdata, const void *key, const void *value)
  2928. {
  2929. VulkanRenderer *renderer = (VulkanRenderer *)userdata;
  2930. VulkanCommandPool *pool = (VulkanCommandPool *)value;
  2931. VULKAN_INTERNAL_DestroyCommandPool(renderer, pool);
  2932. SDL_free((void *)key);
  2933. }
  2934. static Uint32 SDLCALL VULKAN_INTERNAL_RenderPassHashFunction(void *userdata, const void *key)
  2935. {
  2936. RenderPassHashTableKey *hashTableKey = (RenderPassHashTableKey *)key;
  2937. /* The algorithm for this hashing function
  2938. * is taken from Josh Bloch's "Effective Java".
  2939. * (https://stackoverflow.com/a/113600/12492383)
  2940. */
  2941. const Uint32 hashFactor = 31;
  2942. Uint32 result = 1;
  2943. for (Uint32 i = 0; i < hashTableKey->numColorTargets; i += 1) {
  2944. result = result * hashFactor + hashTableKey->colorTargetDescriptions[i].loadOp;
  2945. result = result * hashFactor + hashTableKey->colorTargetDescriptions[i].storeOp;
  2946. result = result * hashFactor + hashTableKey->colorTargetDescriptions[i].format;
  2947. }
  2948. for (Uint32 i = 0; i < hashTableKey->numResolveTargets; i += 1) {
  2949. result = result * hashFactor + hashTableKey->resolveTargetFormats[i];
  2950. }
  2951. result = result * hashFactor + hashTableKey->depthStencilTargetDescription.loadOp;
  2952. result = result * hashFactor + hashTableKey->depthStencilTargetDescription.storeOp;
  2953. result = result * hashFactor + hashTableKey->depthStencilTargetDescription.stencilLoadOp;
  2954. result = result * hashFactor + hashTableKey->depthStencilTargetDescription.stencilStoreOp;
  2955. result = result * hashFactor + hashTableKey->depthStencilTargetDescription.format;
  2956. result = result * hashFactor + hashTableKey->sampleCount;
  2957. return result;
  2958. }
  2959. static bool SDLCALL VULKAN_INTERNAL_RenderPassHashKeyMatch(void *userdata, const void *aKey, const void *bKey)
  2960. {
  2961. RenderPassHashTableKey *a = (RenderPassHashTableKey *)aKey;
  2962. RenderPassHashTableKey *b = (RenderPassHashTableKey *)bKey;
  2963. if (a->numColorTargets != b->numColorTargets) {
  2964. return 0;
  2965. }
  2966. if (a->numResolveTargets != b->numResolveTargets) {
  2967. return 0;
  2968. }
  2969. if (a->sampleCount != b->sampleCount) {
  2970. return 0;
  2971. }
  2972. for (Uint32 i = 0; i < a->numColorTargets; i += 1) {
  2973. if (a->colorTargetDescriptions[i].format != b->colorTargetDescriptions[i].format) {
  2974. return 0;
  2975. }
  2976. if (a->colorTargetDescriptions[i].loadOp != b->colorTargetDescriptions[i].loadOp) {
  2977. return 0;
  2978. }
  2979. if (a->colorTargetDescriptions[i].storeOp != b->colorTargetDescriptions[i].storeOp) {
  2980. return 0;
  2981. }
  2982. }
  2983. for (Uint32 i = 0; i < a->numResolveTargets; i += 1) {
  2984. if (a->resolveTargetFormats[i] != b->resolveTargetFormats[i]) {
  2985. return 0;
  2986. }
  2987. }
  2988. if (a->depthStencilTargetDescription.format != b->depthStencilTargetDescription.format) {
  2989. return 0;
  2990. }
  2991. if (a->depthStencilTargetDescription.loadOp != b->depthStencilTargetDescription.loadOp) {
  2992. return 0;
  2993. }
  2994. if (a->depthStencilTargetDescription.storeOp != b->depthStencilTargetDescription.storeOp) {
  2995. return 0;
  2996. }
  2997. if (a->depthStencilTargetDescription.stencilLoadOp != b->depthStencilTargetDescription.stencilLoadOp) {
  2998. return 0;
  2999. }
  3000. if (a->depthStencilTargetDescription.stencilStoreOp != b->depthStencilTargetDescription.stencilStoreOp) {
  3001. return 0;
  3002. }
  3003. return 1;
  3004. }
  3005. static void SDLCALL VULKAN_INTERNAL_RenderPassHashDestroy(void *userdata, const void *key, const void *value)
  3006. {
  3007. VulkanRenderer *renderer = (VulkanRenderer *)userdata;
  3008. VulkanRenderPassHashTableValue *renderPassWrapper = (VulkanRenderPassHashTableValue *)value;
  3009. renderer->vkDestroyRenderPass(
  3010. renderer->logicalDevice,
  3011. renderPassWrapper->handle,
  3012. NULL);
  3013. SDL_free(renderPassWrapper);
  3014. SDL_free((void *)key);
  3015. }
  3016. static Uint32 SDLCALL VULKAN_INTERNAL_FramebufferHashFunction(void *userdata, const void *key)
  3017. {
  3018. FramebufferHashTableKey *hashTableKey = (FramebufferHashTableKey *)key;
  3019. /* The algorithm for this hashing function
  3020. * is taken from Josh Bloch's "Effective Java".
  3021. * (https://stackoverflow.com/a/113600/12492383)
  3022. */
  3023. const Uint32 hashFactor = 31;
  3024. Uint32 result = 1;
  3025. for (Uint32 i = 0; i < hashTableKey->numColorTargets; i += 1) {
  3026. result = result * hashFactor + (Uint32)(uintptr_t)hashTableKey->colorAttachmentViews[i];
  3027. }
  3028. for (Uint32 i = 0; i < hashTableKey->numResolveAttachments; i += 1) {
  3029. result = result * hashFactor + (Uint32)(uintptr_t)hashTableKey->resolveAttachmentViews[i];
  3030. }
  3031. result = result * hashFactor + (Uint32)(uintptr_t)hashTableKey->depthStencilAttachmentView;
  3032. result = result * hashFactor + hashTableKey->width;
  3033. result = result * hashFactor + hashTableKey->height;
  3034. return result;
  3035. }
  3036. static bool SDLCALL VULKAN_INTERNAL_FramebufferHashKeyMatch(void *userdata, const void *aKey, const void *bKey)
  3037. {
  3038. FramebufferHashTableKey *a = (FramebufferHashTableKey *)aKey;
  3039. FramebufferHashTableKey *b = (FramebufferHashTableKey *)bKey;
  3040. if (a->numColorTargets != b->numColorTargets) {
  3041. return 0;
  3042. }
  3043. if (a->numResolveAttachments != b->numResolveAttachments) {
  3044. return 0;
  3045. }
  3046. for (Uint32 i = 0; i < a->numColorTargets; i += 1) {
  3047. if (a->colorAttachmentViews[i] != b->colorAttachmentViews[i]) {
  3048. return 0;
  3049. }
  3050. }
  3051. for (Uint32 i = 0; i < a->numResolveAttachments; i += 1) {
  3052. if (a->resolveAttachmentViews[i] != b->resolveAttachmentViews[i]) {
  3053. return 0;
  3054. }
  3055. }
  3056. if (a->depthStencilAttachmentView != b->depthStencilAttachmentView) {
  3057. return 0;
  3058. }
  3059. if (a->width != b->width) {
  3060. return 0;
  3061. }
  3062. if (a->height != b->height) {
  3063. return 0;
  3064. }
  3065. return 1;
  3066. }
  3067. static void SDLCALL VULKAN_INTERNAL_FramebufferHashDestroy(void *userdata, const void *key, const void *value)
  3068. {
  3069. VulkanRenderer *renderer = (VulkanRenderer *)userdata;
  3070. VulkanFramebuffer *framebuffer = (VulkanFramebuffer *)value;
  3071. VULKAN_INTERNAL_ReleaseFramebuffer(renderer, framebuffer);
  3072. SDL_free((void *)key);
  3073. }
  3074. // Descriptor pools
  3075. static bool VULKAN_INTERNAL_AllocateDescriptorSets(
  3076. VulkanRenderer *renderer,
  3077. VkDescriptorPool descriptorPool,
  3078. VkDescriptorSetLayout descriptorSetLayout,
  3079. Uint32 descriptorSetCount,
  3080. VkDescriptorSet *descriptorSetArray)
  3081. {
  3082. VkDescriptorSetAllocateInfo descriptorSetAllocateInfo;
  3083. VkDescriptorSetLayout *descriptorSetLayouts = SDL_stack_alloc(VkDescriptorSetLayout, descriptorSetCount);
  3084. VkResult vulkanResult;
  3085. Uint32 i;
  3086. for (i = 0; i < descriptorSetCount; i += 1) {
  3087. descriptorSetLayouts[i] = descriptorSetLayout;
  3088. }
  3089. descriptorSetAllocateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
  3090. descriptorSetAllocateInfo.pNext = NULL;
  3091. descriptorSetAllocateInfo.descriptorPool = descriptorPool;
  3092. descriptorSetAllocateInfo.descriptorSetCount = descriptorSetCount;
  3093. descriptorSetAllocateInfo.pSetLayouts = descriptorSetLayouts;
  3094. vulkanResult = renderer->vkAllocateDescriptorSets(
  3095. renderer->logicalDevice,
  3096. &descriptorSetAllocateInfo,
  3097. descriptorSetArray);
  3098. SDL_stack_free(descriptorSetLayouts);
  3099. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkAllocateDescriptorSets, false);
  3100. return true;
  3101. }
  3102. static bool VULKAN_INTERNAL_AllocateDescriptorsFromPool(
  3103. VulkanRenderer *renderer,
  3104. DescriptorSetLayout *descriptorSetLayout,
  3105. DescriptorSetPool *descriptorSetPool)
  3106. {
  3107. VkDescriptorPoolSize descriptorPoolSizes[
  3108. MAX_TEXTURE_SAMPLERS_PER_STAGE +
  3109. MAX_STORAGE_TEXTURES_PER_STAGE +
  3110. MAX_STORAGE_BUFFERS_PER_STAGE +
  3111. MAX_COMPUTE_WRITE_TEXTURES +
  3112. MAX_COMPUTE_WRITE_BUFFERS +
  3113. MAX_UNIFORM_BUFFERS_PER_STAGE];
  3114. VkDescriptorPoolCreateInfo descriptorPoolInfo;
  3115. VkDescriptorPool pool;
  3116. VkResult vulkanResult;
  3117. // Category 1
  3118. for (Uint32 i = 0; i < descriptorSetLayout->samplerCount; i += 1) {
  3119. descriptorPoolSizes[i].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  3120. descriptorPoolSizes[i].descriptorCount = DESCRIPTOR_POOL_SIZE;
  3121. }
  3122. for (Uint32 i = descriptorSetLayout->samplerCount; i < descriptorSetLayout->samplerCount + descriptorSetLayout->storageTextureCount; i += 1) {
  3123. descriptorPoolSizes[i].type = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; // Yes, we are declaring the storage image as a sampled image, because shaders are stupid.
  3124. descriptorPoolSizes[i].descriptorCount = DESCRIPTOR_POOL_SIZE;
  3125. }
  3126. for (Uint32 i = descriptorSetLayout->samplerCount + descriptorSetLayout->storageTextureCount; i < descriptorSetLayout->samplerCount + descriptorSetLayout->storageTextureCount + descriptorSetLayout->storageBufferCount; i += 1) {
  3127. descriptorPoolSizes[i].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  3128. descriptorPoolSizes[i].descriptorCount = DESCRIPTOR_POOL_SIZE;
  3129. }
  3130. // Category 2
  3131. for (Uint32 i = 0; i < descriptorSetLayout->writeStorageTextureCount; i += 1) {
  3132. descriptorPoolSizes[i].type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  3133. descriptorPoolSizes[i].descriptorCount = DESCRIPTOR_POOL_SIZE;
  3134. }
  3135. for (Uint32 i = descriptorSetLayout->writeStorageTextureCount; i < descriptorSetLayout->writeStorageTextureCount + descriptorSetLayout->writeStorageBufferCount; i += 1) {
  3136. descriptorPoolSizes[i].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  3137. descriptorPoolSizes[i].descriptorCount = DESCRIPTOR_POOL_SIZE;
  3138. }
  3139. // Category 3
  3140. for (Uint32 i = 0; i < descriptorSetLayout->uniformBufferCount; i += 1) {
  3141. descriptorPoolSizes[i].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
  3142. descriptorPoolSizes[i].descriptorCount = DESCRIPTOR_POOL_SIZE;
  3143. }
  3144. descriptorPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
  3145. descriptorPoolInfo.pNext = NULL;
  3146. descriptorPoolInfo.flags = 0;
  3147. descriptorPoolInfo.maxSets = DESCRIPTOR_POOL_SIZE;
  3148. descriptorPoolInfo.poolSizeCount =
  3149. descriptorSetLayout->samplerCount +
  3150. descriptorSetLayout->storageTextureCount +
  3151. descriptorSetLayout->storageBufferCount +
  3152. descriptorSetLayout->writeStorageTextureCount +
  3153. descriptorSetLayout->writeStorageBufferCount +
  3154. descriptorSetLayout->uniformBufferCount;
  3155. descriptorPoolInfo.pPoolSizes = descriptorPoolSizes;
  3156. vulkanResult = renderer->vkCreateDescriptorPool(
  3157. renderer->logicalDevice,
  3158. &descriptorPoolInfo,
  3159. NULL,
  3160. &pool);
  3161. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateDescriptorPool, false);
  3162. descriptorSetPool->poolCount += 1;
  3163. descriptorSetPool->descriptorPools = SDL_realloc(
  3164. descriptorSetPool->descriptorPools,
  3165. sizeof(VkDescriptorPool) * descriptorSetPool->poolCount);
  3166. descriptorSetPool->descriptorPools[descriptorSetPool->poolCount - 1] = pool;
  3167. descriptorSetPool->descriptorSets = SDL_realloc(
  3168. descriptorSetPool->descriptorSets,
  3169. sizeof(VkDescriptorSet) * descriptorSetPool->poolCount * DESCRIPTOR_POOL_SIZE);
  3170. if (!VULKAN_INTERNAL_AllocateDescriptorSets(
  3171. renderer,
  3172. pool,
  3173. descriptorSetLayout->descriptorSetLayout,
  3174. DESCRIPTOR_POOL_SIZE,
  3175. &descriptorSetPool->descriptorSets[descriptorSetPool->descriptorSetCount])) {
  3176. return false;
  3177. }
  3178. descriptorSetPool->descriptorSetCount += DESCRIPTOR_POOL_SIZE;
  3179. return true;
  3180. }
  3181. // NOTE: these categories should be mutually exclusive
  3182. static DescriptorSetLayout *VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3183. VulkanRenderer *renderer,
  3184. VkShaderStageFlagBits shaderStage,
  3185. // Category 1: read resources
  3186. Uint32 samplerCount,
  3187. Uint32 storageTextureCount,
  3188. Uint32 storageBufferCount,
  3189. // Category 2: write resources
  3190. Uint32 writeStorageTextureCount,
  3191. Uint32 writeStorageBufferCount,
  3192. // Category 3: uniform buffers
  3193. Uint32 uniformBufferCount)
  3194. {
  3195. DescriptorSetLayoutHashTableKey key;
  3196. SDL_zero(key);
  3197. DescriptorSetLayout *layout = NULL;
  3198. key.shaderStage = shaderStage;
  3199. key.samplerCount = samplerCount;
  3200. key.storageTextureCount = storageTextureCount;
  3201. key.storageBufferCount = storageBufferCount;
  3202. key.writeStorageTextureCount = writeStorageTextureCount;
  3203. key.writeStorageBufferCount = writeStorageBufferCount;
  3204. key.uniformBufferCount = uniformBufferCount;
  3205. SDL_LockMutex(renderer->descriptorSetLayoutFetchLock);
  3206. if (SDL_FindInHashTable(
  3207. renderer->descriptorSetLayoutHashTable,
  3208. (const void *)&key,
  3209. (const void **)&layout)) {
  3210. SDL_UnlockMutex(renderer->descriptorSetLayoutFetchLock);
  3211. return layout;
  3212. }
  3213. VkDescriptorSetLayout descriptorSetLayout;
  3214. VkDescriptorSetLayoutBinding descriptorSetLayoutBindings[
  3215. MAX_TEXTURE_SAMPLERS_PER_STAGE +
  3216. MAX_STORAGE_TEXTURES_PER_STAGE +
  3217. MAX_STORAGE_BUFFERS_PER_STAGE +
  3218. MAX_COMPUTE_WRITE_TEXTURES +
  3219. MAX_COMPUTE_WRITE_BUFFERS];
  3220. VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo;
  3221. descriptorSetLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  3222. descriptorSetLayoutCreateInfo.pNext = NULL;
  3223. descriptorSetLayoutCreateInfo.flags = 0;
  3224. // Category 1
  3225. for (Uint32 i = 0; i < samplerCount; i += 1) {
  3226. descriptorSetLayoutBindings[i].binding = i;
  3227. descriptorSetLayoutBindings[i].descriptorCount = 1;
  3228. descriptorSetLayoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  3229. descriptorSetLayoutBindings[i].stageFlags = shaderStage;
  3230. descriptorSetLayoutBindings[i].pImmutableSamplers = NULL;
  3231. }
  3232. for (Uint32 i = samplerCount; i < samplerCount + storageTextureCount; i += 1) {
  3233. descriptorSetLayoutBindings[i].binding = i;
  3234. descriptorSetLayoutBindings[i].descriptorCount = 1;
  3235. descriptorSetLayoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; // Yes, we are declaring the storage image as a sampled image, because shaders are stupid.
  3236. descriptorSetLayoutBindings[i].stageFlags = shaderStage;
  3237. descriptorSetLayoutBindings[i].pImmutableSamplers = NULL;
  3238. }
  3239. for (Uint32 i = samplerCount + storageTextureCount; i < samplerCount + storageTextureCount + storageBufferCount; i += 1) {
  3240. descriptorSetLayoutBindings[i].binding = i;
  3241. descriptorSetLayoutBindings[i].descriptorCount = 1;
  3242. descriptorSetLayoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  3243. descriptorSetLayoutBindings[i].stageFlags = shaderStage;
  3244. descriptorSetLayoutBindings[i].pImmutableSamplers = NULL;
  3245. }
  3246. // Category 2
  3247. for (Uint32 i = 0; i < writeStorageTextureCount; i += 1) {
  3248. descriptorSetLayoutBindings[i].binding = i;
  3249. descriptorSetLayoutBindings[i].descriptorCount = 1;
  3250. descriptorSetLayoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  3251. descriptorSetLayoutBindings[i].stageFlags = shaderStage;
  3252. descriptorSetLayoutBindings[i].pImmutableSamplers = NULL;
  3253. }
  3254. for (Uint32 i = writeStorageTextureCount; i < writeStorageTextureCount + writeStorageBufferCount; i += 1) {
  3255. descriptorSetLayoutBindings[i].binding = i;
  3256. descriptorSetLayoutBindings[i].descriptorCount = 1;
  3257. descriptorSetLayoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  3258. descriptorSetLayoutBindings[i].stageFlags = shaderStage;
  3259. descriptorSetLayoutBindings[i].pImmutableSamplers = NULL;
  3260. }
  3261. // Category 3
  3262. for (Uint32 i = 0; i < uniformBufferCount; i += 1) {
  3263. descriptorSetLayoutBindings[i].binding = i;
  3264. descriptorSetLayoutBindings[i].descriptorCount = 1;
  3265. descriptorSetLayoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
  3266. descriptorSetLayoutBindings[i].stageFlags = shaderStage;
  3267. descriptorSetLayoutBindings[i].pImmutableSamplers = NULL;
  3268. }
  3269. descriptorSetLayoutCreateInfo.pBindings = descriptorSetLayoutBindings;
  3270. descriptorSetLayoutCreateInfo.bindingCount =
  3271. samplerCount +
  3272. storageTextureCount +
  3273. storageBufferCount +
  3274. writeStorageTextureCount +
  3275. writeStorageBufferCount +
  3276. uniformBufferCount;
  3277. VkResult vulkanResult = renderer->vkCreateDescriptorSetLayout(
  3278. renderer->logicalDevice,
  3279. &descriptorSetLayoutCreateInfo,
  3280. NULL,
  3281. &descriptorSetLayout);
  3282. if (vulkanResult != VK_SUCCESS) {
  3283. SDL_UnlockMutex(renderer->descriptorSetLayoutFetchLock);
  3284. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateDescriptorSetLayout, NULL);
  3285. }
  3286. layout = SDL_malloc(sizeof(DescriptorSetLayout));
  3287. layout->descriptorSetLayout = descriptorSetLayout;
  3288. layout->samplerCount = samplerCount;
  3289. layout->storageBufferCount = storageBufferCount;
  3290. layout->storageTextureCount = storageTextureCount;
  3291. layout->writeStorageBufferCount = writeStorageBufferCount;
  3292. layout->writeStorageTextureCount = writeStorageTextureCount;
  3293. layout->uniformBufferCount = uniformBufferCount;
  3294. layout->ID = SDL_AtomicIncRef(&renderer->layoutResourceID);
  3295. DescriptorSetLayoutHashTableKey *allocedKey = SDL_malloc(sizeof(DescriptorSetLayoutHashTableKey));
  3296. SDL_memcpy(allocedKey, &key, sizeof(DescriptorSetLayoutHashTableKey));
  3297. SDL_InsertIntoHashTable(
  3298. renderer->descriptorSetLayoutHashTable,
  3299. (const void *)allocedKey,
  3300. (const void *)layout, true);
  3301. SDL_UnlockMutex(renderer->descriptorSetLayoutFetchLock);
  3302. return layout;
  3303. }
  3304. static VulkanGraphicsPipelineResourceLayout *VULKAN_INTERNAL_FetchGraphicsPipelineResourceLayout(
  3305. VulkanRenderer *renderer,
  3306. VulkanShader *vertexShader,
  3307. VulkanShader *fragmentShader)
  3308. {
  3309. GraphicsPipelineResourceLayoutHashTableKey key;
  3310. SDL_zero(key);
  3311. VulkanGraphicsPipelineResourceLayout *pipelineResourceLayout = NULL;
  3312. key.vertexSamplerCount = vertexShader->numSamplers;
  3313. key.vertexStorageTextureCount = vertexShader->numStorageTextures;
  3314. key.vertexStorageBufferCount = vertexShader->numStorageBuffers;
  3315. key.vertexUniformBufferCount = vertexShader->numUniformBuffers;
  3316. key.fragmentSamplerCount = fragmentShader->numSamplers;
  3317. key.fragmentStorageTextureCount = fragmentShader->numStorageTextures;
  3318. key.fragmentStorageBufferCount = fragmentShader->numStorageBuffers;
  3319. key.fragmentUniformBufferCount = fragmentShader->numUniformBuffers;
  3320. SDL_LockMutex(renderer->graphicsPipelineLayoutFetchLock);
  3321. if (SDL_FindInHashTable(
  3322. renderer->graphicsPipelineResourceLayoutHashTable,
  3323. (const void *)&key,
  3324. (const void **)&pipelineResourceLayout)) {
  3325. SDL_UnlockMutex(renderer->graphicsPipelineLayoutFetchLock);
  3326. return pipelineResourceLayout;
  3327. }
  3328. VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo;
  3329. VkDescriptorSetLayout descriptorSetLayouts[4];
  3330. VkResult vulkanResult;
  3331. pipelineResourceLayout = SDL_calloc(1, sizeof(VulkanGraphicsPipelineResourceLayout));
  3332. pipelineResourceLayout->descriptorSetLayouts[0] = VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3333. renderer,
  3334. VK_SHADER_STAGE_VERTEX_BIT,
  3335. vertexShader->numSamplers,
  3336. vertexShader->numStorageTextures,
  3337. vertexShader->numStorageBuffers,
  3338. 0,
  3339. 0,
  3340. 0);
  3341. pipelineResourceLayout->descriptorSetLayouts[1] = VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3342. renderer,
  3343. VK_SHADER_STAGE_VERTEX_BIT,
  3344. 0,
  3345. 0,
  3346. 0,
  3347. 0,
  3348. 0,
  3349. vertexShader->numUniformBuffers);
  3350. pipelineResourceLayout->descriptorSetLayouts[2] = VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3351. renderer,
  3352. VK_SHADER_STAGE_FRAGMENT_BIT,
  3353. fragmentShader->numSamplers,
  3354. fragmentShader->numStorageTextures,
  3355. fragmentShader->numStorageBuffers,
  3356. 0,
  3357. 0,
  3358. 0);
  3359. pipelineResourceLayout->descriptorSetLayouts[3] = VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3360. renderer,
  3361. VK_SHADER_STAGE_FRAGMENT_BIT,
  3362. 0,
  3363. 0,
  3364. 0,
  3365. 0,
  3366. 0,
  3367. fragmentShader->numUniformBuffers);
  3368. descriptorSetLayouts[0] = pipelineResourceLayout->descriptorSetLayouts[0]->descriptorSetLayout;
  3369. descriptorSetLayouts[1] = pipelineResourceLayout->descriptorSetLayouts[1]->descriptorSetLayout;
  3370. descriptorSetLayouts[2] = pipelineResourceLayout->descriptorSetLayouts[2]->descriptorSetLayout;
  3371. descriptorSetLayouts[3] = pipelineResourceLayout->descriptorSetLayouts[3]->descriptorSetLayout;
  3372. pipelineResourceLayout->vertexSamplerCount = vertexShader->numSamplers;
  3373. pipelineResourceLayout->vertexStorageTextureCount = vertexShader->numStorageTextures;
  3374. pipelineResourceLayout->vertexStorageBufferCount = vertexShader->numStorageBuffers;
  3375. pipelineResourceLayout->vertexUniformBufferCount = vertexShader->numUniformBuffers;
  3376. pipelineResourceLayout->fragmentSamplerCount = fragmentShader->numSamplers;
  3377. pipelineResourceLayout->fragmentStorageTextureCount = fragmentShader->numStorageTextures;
  3378. pipelineResourceLayout->fragmentStorageBufferCount = fragmentShader->numStorageBuffers;
  3379. pipelineResourceLayout->fragmentUniformBufferCount = fragmentShader->numUniformBuffers;
  3380. // Create the pipeline layout
  3381. pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  3382. pipelineLayoutCreateInfo.pNext = NULL;
  3383. pipelineLayoutCreateInfo.flags = 0;
  3384. pipelineLayoutCreateInfo.setLayoutCount = 4;
  3385. pipelineLayoutCreateInfo.pSetLayouts = descriptorSetLayouts;
  3386. pipelineLayoutCreateInfo.pushConstantRangeCount = 0;
  3387. pipelineLayoutCreateInfo.pPushConstantRanges = NULL;
  3388. vulkanResult = renderer->vkCreatePipelineLayout(
  3389. renderer->logicalDevice,
  3390. &pipelineLayoutCreateInfo,
  3391. NULL,
  3392. &pipelineResourceLayout->pipelineLayout);
  3393. if (vulkanResult != VK_SUCCESS) {
  3394. VULKAN_INTERNAL_DestroyGraphicsPipelineResourceLayout(renderer, pipelineResourceLayout);
  3395. SDL_UnlockMutex(renderer->graphicsPipelineLayoutFetchLock);
  3396. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreatePipelineLayout, NULL);
  3397. }
  3398. GraphicsPipelineResourceLayoutHashTableKey *allocedKey = SDL_malloc(sizeof(GraphicsPipelineResourceLayoutHashTableKey));
  3399. SDL_memcpy(allocedKey, &key, sizeof(GraphicsPipelineResourceLayoutHashTableKey));
  3400. SDL_InsertIntoHashTable(
  3401. renderer->graphicsPipelineResourceLayoutHashTable,
  3402. (const void *)allocedKey,
  3403. (const void *)pipelineResourceLayout, true);
  3404. SDL_UnlockMutex(renderer->graphicsPipelineLayoutFetchLock);
  3405. return pipelineResourceLayout;
  3406. }
  3407. static VulkanComputePipelineResourceLayout *VULKAN_INTERNAL_FetchComputePipelineResourceLayout(
  3408. VulkanRenderer *renderer,
  3409. const SDL_GPUComputePipelineCreateInfo *createinfo)
  3410. {
  3411. ComputePipelineResourceLayoutHashTableKey key;
  3412. SDL_zero(key);
  3413. VulkanComputePipelineResourceLayout *pipelineResourceLayout = NULL;
  3414. key.samplerCount = createinfo->num_samplers;
  3415. key.readonlyStorageTextureCount = createinfo->num_readonly_storage_textures;
  3416. key.readonlyStorageBufferCount = createinfo->num_readonly_storage_buffers;
  3417. key.readWriteStorageTextureCount = createinfo->num_readwrite_storage_textures;
  3418. key.readWriteStorageBufferCount = createinfo->num_readwrite_storage_buffers;
  3419. key.uniformBufferCount = createinfo->num_uniform_buffers;
  3420. SDL_LockMutex(renderer->computePipelineLayoutFetchLock);
  3421. if (SDL_FindInHashTable(
  3422. renderer->computePipelineResourceLayoutHashTable,
  3423. (const void *)&key,
  3424. (const void **)&pipelineResourceLayout)) {
  3425. SDL_UnlockMutex(renderer->computePipelineLayoutFetchLock);
  3426. return pipelineResourceLayout;
  3427. }
  3428. VkDescriptorSetLayout descriptorSetLayouts[3];
  3429. VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo;
  3430. VkResult vulkanResult;
  3431. pipelineResourceLayout = SDL_calloc(1, sizeof(VulkanComputePipelineResourceLayout));
  3432. pipelineResourceLayout->descriptorSetLayouts[0] = VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3433. renderer,
  3434. VK_SHADER_STAGE_COMPUTE_BIT,
  3435. createinfo->num_samplers,
  3436. createinfo->num_readonly_storage_textures,
  3437. createinfo->num_readonly_storage_buffers,
  3438. 0,
  3439. 0,
  3440. 0);
  3441. pipelineResourceLayout->descriptorSetLayouts[1] = VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3442. renderer,
  3443. VK_SHADER_STAGE_COMPUTE_BIT,
  3444. 0,
  3445. 0,
  3446. 0,
  3447. createinfo->num_readwrite_storage_textures,
  3448. createinfo->num_readwrite_storage_buffers,
  3449. 0);
  3450. pipelineResourceLayout->descriptorSetLayouts[2] = VULKAN_INTERNAL_FetchDescriptorSetLayout(
  3451. renderer,
  3452. VK_SHADER_STAGE_COMPUTE_BIT,
  3453. 0,
  3454. 0,
  3455. 0,
  3456. 0,
  3457. 0,
  3458. createinfo->num_uniform_buffers);
  3459. descriptorSetLayouts[0] = pipelineResourceLayout->descriptorSetLayouts[0]->descriptorSetLayout;
  3460. descriptorSetLayouts[1] = pipelineResourceLayout->descriptorSetLayouts[1]->descriptorSetLayout;
  3461. descriptorSetLayouts[2] = pipelineResourceLayout->descriptorSetLayouts[2]->descriptorSetLayout;
  3462. pipelineResourceLayout->numSamplers = createinfo->num_samplers;
  3463. pipelineResourceLayout->numReadonlyStorageTextures = createinfo->num_readonly_storage_textures;
  3464. pipelineResourceLayout->numReadonlyStorageBuffers = createinfo->num_readonly_storage_buffers;
  3465. pipelineResourceLayout->numReadWriteStorageTextures = createinfo->num_readwrite_storage_textures;
  3466. pipelineResourceLayout->numReadWriteStorageBuffers = createinfo->num_readwrite_storage_buffers;
  3467. pipelineResourceLayout->numUniformBuffers = createinfo->num_uniform_buffers;
  3468. // Create the pipeline layout
  3469. pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  3470. pipelineLayoutCreateInfo.pNext = NULL;
  3471. pipelineLayoutCreateInfo.flags = 0;
  3472. pipelineLayoutCreateInfo.setLayoutCount = 3;
  3473. pipelineLayoutCreateInfo.pSetLayouts = descriptorSetLayouts;
  3474. pipelineLayoutCreateInfo.pushConstantRangeCount = 0;
  3475. pipelineLayoutCreateInfo.pPushConstantRanges = NULL;
  3476. vulkanResult = renderer->vkCreatePipelineLayout(
  3477. renderer->logicalDevice,
  3478. &pipelineLayoutCreateInfo,
  3479. NULL,
  3480. &pipelineResourceLayout->pipelineLayout);
  3481. if (vulkanResult != VK_SUCCESS) {
  3482. VULKAN_INTERNAL_DestroyComputePipelineResourceLayout(renderer, pipelineResourceLayout);
  3483. SDL_UnlockMutex(renderer->computePipelineLayoutFetchLock);
  3484. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreatePipelineLayout, NULL);
  3485. }
  3486. ComputePipelineResourceLayoutHashTableKey *allocedKey = SDL_malloc(sizeof(ComputePipelineResourceLayoutHashTableKey));
  3487. SDL_memcpy(allocedKey, &key, sizeof(ComputePipelineResourceLayoutHashTableKey));
  3488. SDL_InsertIntoHashTable(
  3489. renderer->computePipelineResourceLayoutHashTable,
  3490. (const void *)allocedKey,
  3491. (const void *)pipelineResourceLayout, true);
  3492. SDL_UnlockMutex(renderer->computePipelineLayoutFetchLock);
  3493. return pipelineResourceLayout;
  3494. }
  3495. // Data Buffer
  3496. static VulkanBuffer *VULKAN_INTERNAL_CreateBuffer(
  3497. VulkanRenderer *renderer,
  3498. VkDeviceSize size,
  3499. SDL_GPUBufferUsageFlags usageFlags,
  3500. VulkanBufferType type,
  3501. bool dedicated,
  3502. const char *debugName)
  3503. {
  3504. VulkanBuffer *buffer;
  3505. VkResult vulkanResult;
  3506. VkBufferCreateInfo createinfo;
  3507. VkBufferUsageFlags vulkanUsageFlags = 0;
  3508. Uint8 bindResult;
  3509. if (usageFlags & SDL_GPU_BUFFERUSAGE_VERTEX) {
  3510. vulkanUsageFlags |= VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
  3511. }
  3512. if (usageFlags & SDL_GPU_BUFFERUSAGE_INDEX) {
  3513. vulkanUsageFlags |= VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
  3514. }
  3515. if (usageFlags & (SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ |
  3516. SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ |
  3517. SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE)) {
  3518. vulkanUsageFlags |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
  3519. }
  3520. if (usageFlags & SDL_GPU_BUFFERUSAGE_INDIRECT) {
  3521. vulkanUsageFlags |= VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
  3522. }
  3523. if (type == VULKAN_BUFFER_TYPE_UNIFORM) {
  3524. vulkanUsageFlags |= VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
  3525. } else {
  3526. // GPU buffers need transfer bits for defrag, transfer buffers need them for transfers
  3527. vulkanUsageFlags |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  3528. }
  3529. buffer = SDL_calloc(1, sizeof(VulkanBuffer));
  3530. buffer->size = size;
  3531. buffer->usage = usageFlags;
  3532. buffer->type = type;
  3533. buffer->markedForDestroy = false;
  3534. buffer->transitioned = false;
  3535. createinfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  3536. createinfo.pNext = NULL;
  3537. createinfo.flags = 0;
  3538. createinfo.size = size;
  3539. createinfo.usage = vulkanUsageFlags;
  3540. createinfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  3541. createinfo.queueFamilyIndexCount = 1;
  3542. createinfo.pQueueFamilyIndices = &renderer->queueFamilyIndex;
  3543. // Set transfer bits so we can defrag
  3544. createinfo.usage |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  3545. vulkanResult = renderer->vkCreateBuffer(
  3546. renderer->logicalDevice,
  3547. &createinfo,
  3548. NULL,
  3549. &buffer->buffer);
  3550. if (vulkanResult != VK_SUCCESS) {
  3551. SDL_free(buffer);
  3552. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateBuffer, NULL);
  3553. }
  3554. bindResult = VULKAN_INTERNAL_BindMemoryForBuffer(
  3555. renderer,
  3556. buffer->buffer,
  3557. buffer->size,
  3558. buffer->type,
  3559. dedicated,
  3560. &buffer->usedRegion);
  3561. if (bindResult != 1) {
  3562. renderer->vkDestroyBuffer(
  3563. renderer->logicalDevice,
  3564. buffer->buffer,
  3565. NULL);
  3566. SDL_free(buffer);
  3567. return NULL;
  3568. }
  3569. buffer->usedRegion->vulkanBuffer = buffer; // lol
  3570. SDL_SetAtomicInt(&buffer->referenceCount, 0);
  3571. if (renderer->debugMode && renderer->supportsDebugUtils && debugName != NULL) {
  3572. VkDebugUtilsObjectNameInfoEXT nameInfo;
  3573. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  3574. nameInfo.pNext = NULL;
  3575. nameInfo.pObjectName = debugName;
  3576. nameInfo.objectType = VK_OBJECT_TYPE_BUFFER;
  3577. nameInfo.objectHandle = (uint64_t)buffer->buffer;
  3578. renderer->vkSetDebugUtilsObjectNameEXT(
  3579. renderer->logicalDevice,
  3580. &nameInfo);
  3581. }
  3582. return buffer;
  3583. }
  3584. static VulkanBufferContainer *VULKAN_INTERNAL_CreateBufferContainer(
  3585. VulkanRenderer *renderer,
  3586. VkDeviceSize size,
  3587. SDL_GPUBufferUsageFlags usageFlags,
  3588. VulkanBufferType type,
  3589. bool dedicated,
  3590. const char *debugName)
  3591. {
  3592. VulkanBufferContainer *bufferContainer;
  3593. VulkanBuffer *buffer;
  3594. buffer = VULKAN_INTERNAL_CreateBuffer(
  3595. renderer,
  3596. size,
  3597. usageFlags,
  3598. type,
  3599. dedicated,
  3600. debugName);
  3601. if (buffer == NULL) {
  3602. return NULL;
  3603. }
  3604. bufferContainer = SDL_calloc(1, sizeof(VulkanBufferContainer));
  3605. bufferContainer->activeBuffer = buffer;
  3606. buffer->container = bufferContainer;
  3607. buffer->containerIndex = 0;
  3608. bufferContainer->bufferCapacity = 1;
  3609. bufferContainer->bufferCount = 1;
  3610. bufferContainer->buffers = SDL_calloc(bufferContainer->bufferCapacity, sizeof(VulkanBuffer *));
  3611. bufferContainer->buffers[0] = bufferContainer->activeBuffer;
  3612. bufferContainer->dedicated = dedicated;
  3613. bufferContainer->debugName = NULL;
  3614. if (debugName != NULL) {
  3615. bufferContainer->debugName = SDL_strdup(debugName);
  3616. }
  3617. return bufferContainer;
  3618. }
  3619. // Texture Subresource Utilities
  3620. static Uint32 VULKAN_INTERNAL_GetTextureSubresourceIndex(
  3621. Uint32 mipLevel,
  3622. Uint32 layer,
  3623. Uint32 numLevels)
  3624. {
  3625. return mipLevel + (layer * numLevels);
  3626. }
  3627. static VulkanTextureSubresource *VULKAN_INTERNAL_FetchTextureSubresource(
  3628. VulkanTextureContainer *textureContainer,
  3629. Uint32 layer,
  3630. Uint32 level)
  3631. {
  3632. Uint32 index = VULKAN_INTERNAL_GetTextureSubresourceIndex(
  3633. level,
  3634. layer,
  3635. textureContainer->header.info.num_levels);
  3636. return &textureContainer->activeTexture->subresources[index];
  3637. }
  3638. static bool VULKAN_INTERNAL_CreateRenderTargetView(
  3639. VulkanRenderer *renderer,
  3640. VulkanTexture *texture,
  3641. Uint32 layerOrDepth,
  3642. Uint32 level,
  3643. VkFormat format,
  3644. VkComponentMapping swizzle,
  3645. VkImageView *pView)
  3646. {
  3647. VkResult vulkanResult;
  3648. VkImageViewCreateInfo imageViewCreateInfo;
  3649. // create framebuffer compatible views for RenderTarget
  3650. imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  3651. imageViewCreateInfo.pNext = NULL;
  3652. imageViewCreateInfo.flags = 0;
  3653. imageViewCreateInfo.image = texture->image;
  3654. imageViewCreateInfo.format = format;
  3655. imageViewCreateInfo.components = swizzle;
  3656. imageViewCreateInfo.subresourceRange.aspectMask = texture->aspectFlags;
  3657. imageViewCreateInfo.subresourceRange.baseMipLevel = level;
  3658. imageViewCreateInfo.subresourceRange.levelCount = 1;
  3659. imageViewCreateInfo.subresourceRange.baseArrayLayer = layerOrDepth;
  3660. imageViewCreateInfo.subresourceRange.layerCount = 1;
  3661. imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  3662. vulkanResult = renderer->vkCreateImageView(
  3663. renderer->logicalDevice,
  3664. &imageViewCreateInfo,
  3665. NULL,
  3666. pView);
  3667. if (vulkanResult != VK_SUCCESS) {
  3668. *pView = (VkImageView)VK_NULL_HANDLE;
  3669. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateImageView, false);
  3670. }
  3671. return true;
  3672. }
  3673. static bool VULKAN_INTERNAL_CreateSubresourceView(
  3674. VulkanRenderer *renderer,
  3675. const SDL_GPUTextureCreateInfo *createinfo,
  3676. VulkanTexture *texture,
  3677. Uint32 layer,
  3678. Uint32 level,
  3679. VkComponentMapping swizzle,
  3680. VkImageView *pView)
  3681. {
  3682. VkResult vulkanResult;
  3683. VkImageViewCreateInfo imageViewCreateInfo;
  3684. // create framebuffer compatible views for RenderTarget
  3685. imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  3686. imageViewCreateInfo.pNext = NULL;
  3687. imageViewCreateInfo.flags = 0;
  3688. imageViewCreateInfo.image = texture->image;
  3689. imageViewCreateInfo.format = SDLToVK_TextureFormat[createinfo->format];
  3690. imageViewCreateInfo.components = swizzle;
  3691. imageViewCreateInfo.subresourceRange.aspectMask = texture->aspectFlags;
  3692. imageViewCreateInfo.subresourceRange.baseMipLevel = level;
  3693. imageViewCreateInfo.subresourceRange.levelCount = 1;
  3694. imageViewCreateInfo.subresourceRange.baseArrayLayer = layer;
  3695. imageViewCreateInfo.subresourceRange.layerCount = 1;
  3696. imageViewCreateInfo.viewType = (createinfo->type == SDL_GPU_TEXTURETYPE_3D) ? VK_IMAGE_VIEW_TYPE_3D : VK_IMAGE_VIEW_TYPE_2D;
  3697. vulkanResult = renderer->vkCreateImageView(
  3698. renderer->logicalDevice,
  3699. &imageViewCreateInfo,
  3700. NULL,
  3701. pView);
  3702. if (vulkanResult != VK_SUCCESS) {
  3703. *pView = (VkImageView)VK_NULL_HANDLE;
  3704. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateImageView, false);
  3705. }
  3706. return true;
  3707. }
  3708. // Swapchain
  3709. static bool VULKAN_INTERNAL_QuerySwapchainSupport(
  3710. VulkanRenderer *renderer,
  3711. VkPhysicalDevice physicalDevice,
  3712. VkSurfaceKHR surface,
  3713. SwapchainSupportDetails *outputDetails)
  3714. {
  3715. VkResult result;
  3716. VkBool32 supportsPresent;
  3717. renderer->vkGetPhysicalDeviceSurfaceSupportKHR(
  3718. physicalDevice,
  3719. renderer->queueFamilyIndex,
  3720. surface,
  3721. &supportsPresent);
  3722. // Initialize these in case anything fails
  3723. outputDetails->formatsLength = 0;
  3724. outputDetails->presentModesLength = 0;
  3725. if (!supportsPresent) {
  3726. SET_STRING_ERROR_AND_RETURN("This surface does not support presenting!", false);
  3727. }
  3728. // Run the device surface queries
  3729. result = renderer->vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
  3730. physicalDevice,
  3731. surface,
  3732. &outputDetails->capabilities);
  3733. CHECK_VULKAN_ERROR_AND_RETURN(result, vkGetPhysicalDeviceSurfaceCapabilitiesKHR, false);
  3734. if (!(outputDetails->capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR)) {
  3735. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Opaque presentation unsupported! Expect weird transparency bugs!");
  3736. }
  3737. result = renderer->vkGetPhysicalDeviceSurfaceFormatsKHR(
  3738. physicalDevice,
  3739. surface,
  3740. &outputDetails->formatsLength,
  3741. NULL);
  3742. CHECK_VULKAN_ERROR_AND_RETURN(result, vkGetPhysicalDeviceSurfaceFormatsKHR, false);
  3743. result = renderer->vkGetPhysicalDeviceSurfacePresentModesKHR(
  3744. physicalDevice,
  3745. surface,
  3746. &outputDetails->presentModesLength,
  3747. NULL);
  3748. CHECK_VULKAN_ERROR_AND_RETURN(result, vkGetPhysicalDeviceSurfacePresentModesKHR, false);
  3749. // Generate the arrays, if applicable
  3750. outputDetails->formats = NULL;
  3751. if (outputDetails->formatsLength != 0) {
  3752. outputDetails->formats = (VkSurfaceFormatKHR *)SDL_malloc(
  3753. sizeof(VkSurfaceFormatKHR) * outputDetails->formatsLength);
  3754. if (!outputDetails->formats) { // OOM
  3755. return false;
  3756. }
  3757. result = renderer->vkGetPhysicalDeviceSurfaceFormatsKHR(
  3758. physicalDevice,
  3759. surface,
  3760. &outputDetails->formatsLength,
  3761. outputDetails->formats);
  3762. if (result != VK_SUCCESS) {
  3763. SDL_free(outputDetails->formats);
  3764. CHECK_VULKAN_ERROR_AND_RETURN(result, vkGetPhysicalDeviceSurfaceFormatsKHR, false);
  3765. }
  3766. }
  3767. outputDetails->presentModes = NULL;
  3768. if (outputDetails->presentModesLength != 0) {
  3769. outputDetails->presentModes = (VkPresentModeKHR *)SDL_malloc(
  3770. sizeof(VkPresentModeKHR) * outputDetails->presentModesLength);
  3771. if (!outputDetails->presentModes) { // OOM
  3772. SDL_free(outputDetails->formats);
  3773. return false;
  3774. }
  3775. result = renderer->vkGetPhysicalDeviceSurfacePresentModesKHR(
  3776. physicalDevice,
  3777. surface,
  3778. &outputDetails->presentModesLength,
  3779. outputDetails->presentModes);
  3780. if (result != VK_SUCCESS) {
  3781. SDL_free(outputDetails->formats);
  3782. SDL_free(outputDetails->presentModes);
  3783. CHECK_VULKAN_ERROR_AND_RETURN(result, vkGetPhysicalDeviceSurfacePresentModesKHR, false);
  3784. }
  3785. }
  3786. /* If we made it here, all the queries were successful. This does NOT
  3787. * necessarily mean there are any supported formats or present modes!
  3788. */
  3789. return true;
  3790. }
  3791. static bool VULKAN_INTERNAL_VerifySwapSurfaceFormat(
  3792. VkFormat desiredFormat,
  3793. VkColorSpaceKHR desiredColorSpace,
  3794. VkSurfaceFormatKHR *availableFormats,
  3795. Uint32 availableFormatsLength)
  3796. {
  3797. Uint32 i;
  3798. for (i = 0; i < availableFormatsLength; i += 1) {
  3799. if (availableFormats[i].format == desiredFormat &&
  3800. availableFormats[i].colorSpace == desiredColorSpace) {
  3801. return true;
  3802. }
  3803. }
  3804. return false;
  3805. }
  3806. static bool VULKAN_INTERNAL_VerifySwapPresentMode(
  3807. VkPresentModeKHR presentMode,
  3808. const VkPresentModeKHR *availablePresentModes,
  3809. Uint32 availablePresentModesLength)
  3810. {
  3811. Uint32 i;
  3812. for (i = 0; i < availablePresentModesLength; i += 1) {
  3813. if (availablePresentModes[i] == presentMode) {
  3814. return true;
  3815. }
  3816. }
  3817. return false;
  3818. }
  3819. /* It would be nice if VULKAN_INTERNAL_CreateSwapchain could return a bool.
  3820. * Unfortunately, some Win32 NVIDIA drivers are stupid
  3821. * and will return surface extents of (0, 0)
  3822. * in certain edge cases, and the swapchain extents are not allowed to be 0.
  3823. * In this case, the client probably still wants to claim the window
  3824. * or recreate the swapchain, so we should return 2 to indicate retry.
  3825. * -cosmonaut
  3826. */
  3827. #define VULKAN_INTERNAL_TRY_AGAIN 2
  3828. static Uint32 VULKAN_INTERNAL_CreateSwapchain(
  3829. VulkanRenderer *renderer,
  3830. WindowData *windowData)
  3831. {
  3832. VkResult vulkanResult;
  3833. VkSwapchainCreateInfoKHR swapchainCreateInfo;
  3834. VkImage *swapchainImages;
  3835. VkSemaphoreCreateInfo semaphoreCreateInfo;
  3836. SwapchainSupportDetails swapchainSupportDetails;
  3837. bool hasValidSwapchainComposition, hasValidPresentMode;
  3838. Uint32 i;
  3839. windowData->frameCounter = 0;
  3840. SDL_VideoDevice *_this = SDL_GetVideoDevice();
  3841. SDL_assert(_this && _this->Vulkan_CreateSurface);
  3842. // Each swapchain must have its own surface.
  3843. if (!_this->Vulkan_CreateSurface(
  3844. _this,
  3845. windowData->window,
  3846. renderer->instance,
  3847. NULL, // FIXME: VAllocationCallbacks
  3848. &windowData->surface)) {
  3849. return false;
  3850. }
  3851. SDL_assert(windowData->surface);
  3852. if (!VULKAN_INTERNAL_QuerySwapchainSupport(
  3853. renderer,
  3854. renderer->physicalDevice,
  3855. windowData->surface,
  3856. &swapchainSupportDetails)) {
  3857. renderer->vkDestroySurfaceKHR(
  3858. renderer->instance,
  3859. windowData->surface,
  3860. NULL);
  3861. windowData->surface = VK_NULL_HANDLE;
  3862. if (swapchainSupportDetails.formatsLength > 0) {
  3863. SDL_free(swapchainSupportDetails.formats);
  3864. }
  3865. if (swapchainSupportDetails.presentModesLength > 0) {
  3866. SDL_free(swapchainSupportDetails.presentModes);
  3867. }
  3868. return false;
  3869. }
  3870. // Verify that we can use the requested composition and present mode
  3871. windowData->format = SwapchainCompositionToFormat[windowData->swapchainComposition];
  3872. windowData->colorSpace = SwapchainCompositionToColorSpace[windowData->swapchainComposition];
  3873. windowData->swapchainSwizzle = SwapchainCompositionSwizzle[windowData->swapchainComposition];
  3874. windowData->usingFallbackFormat = false;
  3875. hasValidSwapchainComposition = VULKAN_INTERNAL_VerifySwapSurfaceFormat(
  3876. windowData->format,
  3877. windowData->colorSpace,
  3878. swapchainSupportDetails.formats,
  3879. swapchainSupportDetails.formatsLength);
  3880. if (!hasValidSwapchainComposition) {
  3881. // Let's try again with the fallback format...
  3882. windowData->format = SwapchainCompositionToFallbackFormat[windowData->swapchainComposition];
  3883. windowData->usingFallbackFormat = true;
  3884. hasValidSwapchainComposition = VULKAN_INTERNAL_VerifySwapSurfaceFormat(
  3885. windowData->format,
  3886. windowData->colorSpace,
  3887. swapchainSupportDetails.formats,
  3888. swapchainSupportDetails.formatsLength);
  3889. }
  3890. hasValidPresentMode = VULKAN_INTERNAL_VerifySwapPresentMode(
  3891. SDLToVK_PresentMode[windowData->presentMode],
  3892. swapchainSupportDetails.presentModes,
  3893. swapchainSupportDetails.presentModesLength);
  3894. if (!hasValidSwapchainComposition || !hasValidPresentMode) {
  3895. renderer->vkDestroySurfaceKHR(
  3896. renderer->instance,
  3897. windowData->surface,
  3898. NULL);
  3899. windowData->surface = VK_NULL_HANDLE;
  3900. if (swapchainSupportDetails.formatsLength > 0) {
  3901. SDL_free(swapchainSupportDetails.formats);
  3902. }
  3903. if (swapchainSupportDetails.presentModesLength > 0) {
  3904. SDL_free(swapchainSupportDetails.presentModes);
  3905. }
  3906. if (!hasValidSwapchainComposition) {
  3907. SET_STRING_ERROR_AND_RETURN("Device does not support requested swapchain composition!", false);
  3908. }
  3909. if (!hasValidPresentMode) {
  3910. SET_STRING_ERROR_AND_RETURN("Device does not support requested present_mode!", false);
  3911. }
  3912. return false;
  3913. }
  3914. // NVIDIA + Win32 can return 0 extent when the window is minimized. Try again!
  3915. if (swapchainSupportDetails.capabilities.currentExtent.width == 0 ||
  3916. swapchainSupportDetails.capabilities.currentExtent.height == 0) {
  3917. renderer->vkDestroySurfaceKHR(
  3918. renderer->instance,
  3919. windowData->surface,
  3920. NULL);
  3921. windowData->surface = VK_NULL_HANDLE;
  3922. if (swapchainSupportDetails.formatsLength > 0) {
  3923. SDL_free(swapchainSupportDetails.formats);
  3924. }
  3925. if (swapchainSupportDetails.presentModesLength > 0) {
  3926. SDL_free(swapchainSupportDetails.presentModes);
  3927. }
  3928. return VULKAN_INTERNAL_TRY_AGAIN;
  3929. }
  3930. Uint32 requestedImageCount = renderer->allowedFramesInFlight;
  3931. #ifdef SDL_PLATFORM_APPLE
  3932. windowData->width = swapchainSupportDetails.capabilities.currentExtent.width;
  3933. windowData->height = swapchainSupportDetails.capabilities.currentExtent.height;
  3934. #else
  3935. windowData->width = SDL_clamp(
  3936. windowData->swapchainCreateWidth,
  3937. swapchainSupportDetails.capabilities.minImageExtent.width,
  3938. swapchainSupportDetails.capabilities.maxImageExtent.width);
  3939. windowData->height = SDL_clamp(windowData->swapchainCreateHeight,
  3940. swapchainSupportDetails.capabilities.minImageExtent.height,
  3941. swapchainSupportDetails.capabilities.maxImageExtent.height);
  3942. #endif
  3943. if (swapchainSupportDetails.capabilities.maxImageCount > 0 &&
  3944. requestedImageCount > swapchainSupportDetails.capabilities.maxImageCount) {
  3945. requestedImageCount = swapchainSupportDetails.capabilities.maxImageCount;
  3946. }
  3947. if (requestedImageCount < swapchainSupportDetails.capabilities.minImageCount) {
  3948. requestedImageCount = swapchainSupportDetails.capabilities.minImageCount;
  3949. }
  3950. if (windowData->presentMode == SDL_GPU_PRESENTMODE_MAILBOX) {
  3951. /* Required for proper triple-buffering.
  3952. * Note that this is below the above maxImageCount check!
  3953. * If the driver advertises MAILBOX but does not support 3 swap
  3954. * images, it's not real mailbox support, so let it fail hard.
  3955. * -flibit
  3956. */
  3957. requestedImageCount = SDL_max(requestedImageCount, 3);
  3958. }
  3959. swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
  3960. swapchainCreateInfo.pNext = NULL;
  3961. swapchainCreateInfo.flags = 0;
  3962. swapchainCreateInfo.surface = windowData->surface;
  3963. swapchainCreateInfo.minImageCount = requestedImageCount;
  3964. swapchainCreateInfo.imageFormat = windowData->format;
  3965. swapchainCreateInfo.imageColorSpace = windowData->colorSpace;
  3966. swapchainCreateInfo.imageExtent.width = windowData->width;
  3967. swapchainCreateInfo.imageExtent.height = windowData->height;
  3968. swapchainCreateInfo.imageArrayLayers = 1;
  3969. swapchainCreateInfo.imageUsage =
  3970. VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
  3971. VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  3972. swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
  3973. swapchainCreateInfo.queueFamilyIndexCount = 0;
  3974. swapchainCreateInfo.pQueueFamilyIndices = NULL;
  3975. #ifdef SDL_PLATFORM_ANDROID
  3976. swapchainCreateInfo.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
  3977. #else
  3978. swapchainCreateInfo.preTransform = swapchainSupportDetails.capabilities.currentTransform;
  3979. #endif
  3980. swapchainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  3981. swapchainCreateInfo.presentMode = SDLToVK_PresentMode[windowData->presentMode];
  3982. swapchainCreateInfo.clipped = VK_TRUE;
  3983. swapchainCreateInfo.oldSwapchain = VK_NULL_HANDLE;
  3984. vulkanResult = renderer->vkCreateSwapchainKHR(
  3985. renderer->logicalDevice,
  3986. &swapchainCreateInfo,
  3987. NULL,
  3988. &windowData->swapchain);
  3989. if (swapchainSupportDetails.formatsLength > 0) {
  3990. SDL_free(swapchainSupportDetails.formats);
  3991. }
  3992. if (swapchainSupportDetails.presentModesLength > 0) {
  3993. SDL_free(swapchainSupportDetails.presentModes);
  3994. }
  3995. if (vulkanResult != VK_SUCCESS) {
  3996. renderer->vkDestroySurfaceKHR(
  3997. renderer->instance,
  3998. windowData->surface,
  3999. NULL);
  4000. windowData->surface = VK_NULL_HANDLE;
  4001. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateSwapchainKHR, false);
  4002. }
  4003. vulkanResult = renderer->vkGetSwapchainImagesKHR(
  4004. renderer->logicalDevice,
  4005. windowData->swapchain,
  4006. &windowData->imageCount,
  4007. NULL);
  4008. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkGetSwapchainImagesKHR, false);
  4009. windowData->textureContainers = SDL_malloc(
  4010. sizeof(VulkanTextureContainer) * windowData->imageCount);
  4011. if (!windowData->textureContainers) { // OOM
  4012. renderer->vkDestroySurfaceKHR(
  4013. renderer->instance,
  4014. windowData->surface,
  4015. NULL);
  4016. renderer->vkDestroySwapchainKHR(
  4017. renderer->logicalDevice,
  4018. windowData->swapchain,
  4019. NULL);
  4020. windowData->surface = VK_NULL_HANDLE;
  4021. windowData->swapchain = VK_NULL_HANDLE;
  4022. return false;
  4023. }
  4024. swapchainImages = SDL_stack_alloc(VkImage, windowData->imageCount);
  4025. vulkanResult = renderer->vkGetSwapchainImagesKHR(
  4026. renderer->logicalDevice,
  4027. windowData->swapchain,
  4028. &windowData->imageCount,
  4029. swapchainImages);
  4030. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkGetSwapchainImagesKHR, false);
  4031. for (i = 0; i < windowData->imageCount; i += 1) {
  4032. // Initialize dummy container
  4033. SDL_zero(windowData->textureContainers[i]);
  4034. windowData->textureContainers[i].canBeCycled = false;
  4035. windowData->textureContainers[i].header.info.width = windowData->width;
  4036. windowData->textureContainers[i].header.info.height = windowData->height;
  4037. windowData->textureContainers[i].header.info.layer_count_or_depth = 1;
  4038. windowData->textureContainers[i].header.info.format = SwapchainCompositionToSDLFormat(
  4039. windowData->swapchainComposition,
  4040. windowData->usingFallbackFormat);
  4041. windowData->textureContainers[i].header.info.type = SDL_GPU_TEXTURETYPE_2D;
  4042. windowData->textureContainers[i].header.info.num_levels = 1;
  4043. windowData->textureContainers[i].header.info.sample_count = SDL_GPU_SAMPLECOUNT_1;
  4044. windowData->textureContainers[i].header.info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
  4045. windowData->textureContainers[i].activeTexture = SDL_malloc(sizeof(VulkanTexture));
  4046. windowData->textureContainers[i].activeTexture->image = swapchainImages[i];
  4047. // Swapchain memory is managed by the driver
  4048. windowData->textureContainers[i].activeTexture->usedRegion = NULL;
  4049. windowData->textureContainers[i].activeTexture->swizzle = windowData->swapchainSwizzle;
  4050. windowData->textureContainers[i].activeTexture->aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT;
  4051. windowData->textureContainers[i].activeTexture->depth = 1;
  4052. windowData->textureContainers[i].activeTexture->usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
  4053. windowData->textureContainers[i].activeTexture->container = &windowData->textureContainers[i];
  4054. SDL_SetAtomicInt(&windowData->textureContainers[i].activeTexture->referenceCount, 0);
  4055. // Create slice
  4056. windowData->textureContainers[i].activeTexture->subresourceCount = 1;
  4057. windowData->textureContainers[i].activeTexture->subresources = SDL_malloc(sizeof(VulkanTextureSubresource));
  4058. windowData->textureContainers[i].activeTexture->subresources[0].parent = windowData->textureContainers[i].activeTexture;
  4059. windowData->textureContainers[i].activeTexture->subresources[0].layer = 0;
  4060. windowData->textureContainers[i].activeTexture->subresources[0].level = 0;
  4061. windowData->textureContainers[i].activeTexture->subresources[0].renderTargetViews = SDL_malloc(sizeof(VkImageView));
  4062. if (!VULKAN_INTERNAL_CreateRenderTargetView(
  4063. renderer,
  4064. windowData->textureContainers[i].activeTexture,
  4065. 0,
  4066. 0,
  4067. windowData->format,
  4068. windowData->swapchainSwizzle,
  4069. &windowData->textureContainers[i].activeTexture->subresources[0].renderTargetViews[0])) {
  4070. renderer->vkDestroySurfaceKHR(
  4071. renderer->instance,
  4072. windowData->surface,
  4073. NULL);
  4074. renderer->vkDestroySwapchainKHR(
  4075. renderer->logicalDevice,
  4076. windowData->swapchain,
  4077. NULL);
  4078. windowData->surface = VK_NULL_HANDLE;
  4079. windowData->swapchain = VK_NULL_HANDLE;
  4080. return false;
  4081. }
  4082. }
  4083. SDL_stack_free(swapchainImages);
  4084. semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  4085. semaphoreCreateInfo.pNext = NULL;
  4086. semaphoreCreateInfo.flags = 0;
  4087. for (i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  4088. vulkanResult = renderer->vkCreateSemaphore(
  4089. renderer->logicalDevice,
  4090. &semaphoreCreateInfo,
  4091. NULL,
  4092. &windowData->imageAvailableSemaphore[i]);
  4093. if (vulkanResult != VK_SUCCESS) {
  4094. renderer->vkDestroySurfaceKHR(
  4095. renderer->instance,
  4096. windowData->surface,
  4097. NULL);
  4098. renderer->vkDestroySwapchainKHR(
  4099. renderer->logicalDevice,
  4100. windowData->swapchain,
  4101. NULL);
  4102. windowData->surface = VK_NULL_HANDLE;
  4103. windowData->swapchain = VK_NULL_HANDLE;
  4104. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateSemaphore, false);
  4105. }
  4106. windowData->inFlightFences[i] = NULL;
  4107. }
  4108. windowData->renderFinishedSemaphore = SDL_malloc(
  4109. sizeof(VkSemaphore) * windowData->imageCount);
  4110. for (i = 0; i < windowData->imageCount; i += 1) {
  4111. vulkanResult = renderer->vkCreateSemaphore(
  4112. renderer->logicalDevice,
  4113. &semaphoreCreateInfo,
  4114. NULL,
  4115. &windowData->renderFinishedSemaphore[i]);
  4116. if (vulkanResult != VK_SUCCESS) {
  4117. renderer->vkDestroySurfaceKHR(
  4118. renderer->instance,
  4119. windowData->surface,
  4120. NULL);
  4121. renderer->vkDestroySwapchainKHR(
  4122. renderer->logicalDevice,
  4123. windowData->swapchain,
  4124. NULL);
  4125. windowData->surface = VK_NULL_HANDLE;
  4126. windowData->swapchain = VK_NULL_HANDLE;
  4127. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateSemaphore, false);
  4128. }
  4129. }
  4130. windowData->needsSwapchainRecreate = false;
  4131. return true;
  4132. }
  4133. // Command Buffers
  4134. static bool VULKAN_INTERNAL_BeginCommandBuffer(
  4135. VulkanRenderer *renderer,
  4136. VulkanCommandBuffer *commandBuffer)
  4137. {
  4138. VkCommandBufferBeginInfo beginInfo;
  4139. VkResult result;
  4140. beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  4141. beginInfo.pNext = NULL;
  4142. beginInfo.flags = 0;
  4143. beginInfo.pInheritanceInfo = NULL;
  4144. beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  4145. result = renderer->vkBeginCommandBuffer(
  4146. commandBuffer->commandBuffer,
  4147. &beginInfo);
  4148. CHECK_VULKAN_ERROR_AND_RETURN(result, vkBeginCommandBuffer, false);
  4149. return true;
  4150. }
  4151. static bool VULKAN_INTERNAL_EndCommandBuffer(
  4152. VulkanRenderer *renderer,
  4153. VulkanCommandBuffer *commandBuffer)
  4154. {
  4155. VkResult result = renderer->vkEndCommandBuffer(
  4156. commandBuffer->commandBuffer);
  4157. CHECK_VULKAN_ERROR_AND_RETURN(result, vkEndCommandBuffer, false);
  4158. return true;
  4159. }
  4160. static void VULKAN_DestroyDevice(
  4161. SDL_GPUDevice *device)
  4162. {
  4163. VulkanRenderer *renderer = (VulkanRenderer *)device->driverData;
  4164. VulkanMemorySubAllocator *allocator;
  4165. VULKAN_Wait(device->driverData);
  4166. for (Sint32 i = renderer->claimedWindowCount - 1; i >= 0; i -= 1) {
  4167. VULKAN_ReleaseWindow(device->driverData, renderer->claimedWindows[i]->window);
  4168. }
  4169. SDL_free(renderer->claimedWindows);
  4170. VULKAN_Wait(device->driverData);
  4171. SDL_free(renderer->submittedCommandBuffers);
  4172. for (Uint32 i = 0; i < renderer->uniformBufferPoolCount; i += 1) {
  4173. VULKAN_INTERNAL_DestroyBuffer(
  4174. renderer,
  4175. renderer->uniformBufferPool[i]->buffer);
  4176. SDL_free(renderer->uniformBufferPool[i]);
  4177. }
  4178. SDL_free(renderer->uniformBufferPool);
  4179. for (Uint32 i = 0; i < renderer->descriptorSetCachePoolCount; i += 1) {
  4180. VULKAN_INTERNAL_DestroyDescriptorSetCache(
  4181. renderer,
  4182. renderer->descriptorSetCachePool[i]);
  4183. }
  4184. SDL_free(renderer->descriptorSetCachePool);
  4185. for (Uint32 i = 0; i < renderer->fencePool.availableFenceCount; i += 1) {
  4186. renderer->vkDestroyFence(
  4187. renderer->logicalDevice,
  4188. renderer->fencePool.availableFences[i]->fence,
  4189. NULL);
  4190. SDL_free(renderer->fencePool.availableFences[i]);
  4191. }
  4192. SDL_free(renderer->fencePool.availableFences);
  4193. SDL_DestroyMutex(renderer->fencePool.lock);
  4194. SDL_DestroyHashTable(renderer->commandPoolHashTable);
  4195. SDL_DestroyHashTable(renderer->renderPassHashTable);
  4196. SDL_DestroyHashTable(renderer->framebufferHashTable);
  4197. SDL_DestroyHashTable(renderer->graphicsPipelineResourceLayoutHashTable);
  4198. SDL_DestroyHashTable(renderer->computePipelineResourceLayoutHashTable);
  4199. SDL_DestroyHashTable(renderer->descriptorSetLayoutHashTable);
  4200. for (Uint32 i = 0; i < VK_MAX_MEMORY_TYPES; i += 1) {
  4201. allocator = &renderer->memoryAllocator->subAllocators[i];
  4202. for (Sint32 j = allocator->allocationCount - 1; j >= 0; j -= 1) {
  4203. for (Sint32 k = allocator->allocations[j]->usedRegionCount - 1; k >= 0; k -= 1) {
  4204. VULKAN_INTERNAL_RemoveMemoryUsedRegion(
  4205. renderer,
  4206. allocator->allocations[j]->usedRegions[k]);
  4207. }
  4208. VULKAN_INTERNAL_DeallocateMemory(
  4209. renderer,
  4210. allocator,
  4211. j);
  4212. }
  4213. if (renderer->memoryAllocator->subAllocators[i].allocations != NULL) {
  4214. SDL_free(renderer->memoryAllocator->subAllocators[i].allocations);
  4215. }
  4216. SDL_free(renderer->memoryAllocator->subAllocators[i].sortedFreeRegions);
  4217. }
  4218. SDL_free(renderer->memoryAllocator);
  4219. SDL_free(renderer->texturesToDestroy);
  4220. SDL_free(renderer->buffersToDestroy);
  4221. SDL_free(renderer->graphicsPipelinesToDestroy);
  4222. SDL_free(renderer->computePipelinesToDestroy);
  4223. SDL_free(renderer->shadersToDestroy);
  4224. SDL_free(renderer->samplersToDestroy);
  4225. SDL_free(renderer->framebuffersToDestroy);
  4226. SDL_free(renderer->allocationsToDefrag);
  4227. SDL_DestroyMutex(renderer->allocatorLock);
  4228. SDL_DestroyMutex(renderer->disposeLock);
  4229. SDL_DestroyMutex(renderer->submitLock);
  4230. SDL_DestroyMutex(renderer->acquireCommandBufferLock);
  4231. SDL_DestroyMutex(renderer->acquireUniformBufferLock);
  4232. SDL_DestroyMutex(renderer->renderPassFetchLock);
  4233. SDL_DestroyMutex(renderer->framebufferFetchLock);
  4234. SDL_DestroyMutex(renderer->graphicsPipelineLayoutFetchLock);
  4235. SDL_DestroyMutex(renderer->computePipelineLayoutFetchLock);
  4236. SDL_DestroyMutex(renderer->descriptorSetLayoutFetchLock);
  4237. SDL_DestroyMutex(renderer->windowLock);
  4238. renderer->vkDestroyDevice(renderer->logicalDevice, NULL);
  4239. renderer->vkDestroyInstance(renderer->instance, NULL);
  4240. SDL_free(renderer);
  4241. SDL_free(device);
  4242. SDL_Vulkan_UnloadLibrary();
  4243. }
  4244. static DescriptorSetCache *VULKAN_INTERNAL_AcquireDescriptorSetCache(
  4245. VulkanRenderer *renderer)
  4246. {
  4247. DescriptorSetCache *cache;
  4248. if (renderer->descriptorSetCachePoolCount == 0) {
  4249. cache = SDL_malloc(sizeof(DescriptorSetCache));
  4250. cache->poolCount = 0;
  4251. cache->pools = NULL;
  4252. } else {
  4253. cache = renderer->descriptorSetCachePool[renderer->descriptorSetCachePoolCount - 1];
  4254. renderer->descriptorSetCachePoolCount -= 1;
  4255. }
  4256. return cache;
  4257. }
  4258. static void VULKAN_INTERNAL_ReturnDescriptorSetCacheToPool(
  4259. VulkanRenderer *renderer,
  4260. DescriptorSetCache *descriptorSetCache)
  4261. {
  4262. EXPAND_ARRAY_IF_NEEDED(
  4263. renderer->descriptorSetCachePool,
  4264. DescriptorSetCache *,
  4265. renderer->descriptorSetCachePoolCount + 1,
  4266. renderer->descriptorSetCachePoolCapacity,
  4267. renderer->descriptorSetCachePoolCapacity * 2);
  4268. renderer->descriptorSetCachePool[renderer->descriptorSetCachePoolCount] = descriptorSetCache;
  4269. renderer->descriptorSetCachePoolCount += 1;
  4270. for (Uint32 i = 0; i < descriptorSetCache->poolCount; i += 1) {
  4271. descriptorSetCache->pools[i].descriptorSetIndex = 0;
  4272. }
  4273. }
  4274. static VkDescriptorSet VULKAN_INTERNAL_FetchDescriptorSet(
  4275. VulkanRenderer *renderer,
  4276. VulkanCommandBuffer *vulkanCommandBuffer,
  4277. DescriptorSetLayout *descriptorSetLayout)
  4278. {
  4279. // Grow the pool to meet the descriptor set layout ID
  4280. if (descriptorSetLayout->ID >= vulkanCommandBuffer->descriptorSetCache->poolCount) {
  4281. vulkanCommandBuffer->descriptorSetCache->pools = SDL_realloc(
  4282. vulkanCommandBuffer->descriptorSetCache->pools,
  4283. sizeof(DescriptorSetPool) * (descriptorSetLayout->ID + 1));
  4284. for (Uint32 i = vulkanCommandBuffer->descriptorSetCache->poolCount; i < descriptorSetLayout->ID + 1; i += 1) {
  4285. SDL_zero(vulkanCommandBuffer->descriptorSetCache->pools[i]);
  4286. }
  4287. vulkanCommandBuffer->descriptorSetCache->poolCount = descriptorSetLayout->ID + 1;
  4288. }
  4289. DescriptorSetPool *pool =
  4290. &vulkanCommandBuffer->descriptorSetCache->pools[descriptorSetLayout->ID];
  4291. if (pool->descriptorSetIndex == pool->descriptorSetCount) {
  4292. if (!VULKAN_INTERNAL_AllocateDescriptorsFromPool(
  4293. renderer,
  4294. descriptorSetLayout,
  4295. pool)) {
  4296. return VK_NULL_HANDLE;
  4297. }
  4298. }
  4299. VkDescriptorSet descriptorSet = pool->descriptorSets[pool->descriptorSetIndex];
  4300. pool->descriptorSetIndex += 1;
  4301. return descriptorSet;
  4302. }
  4303. static void VULKAN_INTERNAL_BindGraphicsDescriptorSets(
  4304. VulkanRenderer *renderer,
  4305. VulkanCommandBuffer *commandBuffer)
  4306. {
  4307. VulkanGraphicsPipelineResourceLayout *resourceLayout;
  4308. DescriptorSetLayout *descriptorSetLayout;
  4309. VkWriteDescriptorSet writeDescriptorSets[
  4310. (MAX_TEXTURE_SAMPLERS_PER_STAGE +
  4311. MAX_STORAGE_TEXTURES_PER_STAGE +
  4312. MAX_STORAGE_BUFFERS_PER_STAGE +
  4313. MAX_UNIFORM_BUFFERS_PER_STAGE) * 2];
  4314. VkDescriptorBufferInfo bufferInfos[MAX_STORAGE_BUFFERS_PER_STAGE * 2];
  4315. VkDescriptorImageInfo imageInfos[(MAX_TEXTURE_SAMPLERS_PER_STAGE + MAX_STORAGE_TEXTURES_PER_STAGE) * 2];
  4316. Uint32 dynamicOffsets[MAX_UNIFORM_BUFFERS_PER_STAGE * 2];
  4317. Uint32 writeCount = 0;
  4318. Uint32 bufferInfoCount = 0;
  4319. Uint32 imageInfoCount = 0;
  4320. Uint32 dynamicOffsetCount = 0;
  4321. if (
  4322. !commandBuffer->needVertexBufferBind &&
  4323. !commandBuffer->needNewVertexResourceDescriptorSet &&
  4324. !commandBuffer->needNewVertexUniformDescriptorSet &&
  4325. !commandBuffer->needNewVertexUniformOffsets &&
  4326. !commandBuffer->needNewFragmentResourceDescriptorSet &&
  4327. !commandBuffer->needNewFragmentUniformDescriptorSet &&
  4328. !commandBuffer->needNewFragmentUniformOffsets
  4329. ) {
  4330. return;
  4331. }
  4332. if (commandBuffer->needVertexBufferBind && commandBuffer->vertexBufferCount > 0) {
  4333. renderer->vkCmdBindVertexBuffers(
  4334. commandBuffer->commandBuffer,
  4335. 0,
  4336. commandBuffer->vertexBufferCount,
  4337. commandBuffer->vertexBuffers,
  4338. commandBuffer->vertexBufferOffsets);
  4339. commandBuffer->needVertexBufferBind = false;
  4340. }
  4341. resourceLayout = commandBuffer->currentGraphicsPipeline->resourceLayout;
  4342. if (commandBuffer->needNewVertexResourceDescriptorSet) {
  4343. descriptorSetLayout = resourceLayout->descriptorSetLayouts[0];
  4344. commandBuffer->vertexResourceDescriptorSet = VULKAN_INTERNAL_FetchDescriptorSet(
  4345. renderer,
  4346. commandBuffer,
  4347. descriptorSetLayout);
  4348. for (Uint32 i = 0; i < resourceLayout->vertexSamplerCount; i += 1) {
  4349. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4350. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4351. currentWriteDescriptorSet->pNext = NULL;
  4352. currentWriteDescriptorSet->descriptorCount = 1;
  4353. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4354. currentWriteDescriptorSet->dstArrayElement = 0;
  4355. currentWriteDescriptorSet->dstBinding = i;
  4356. currentWriteDescriptorSet->dstSet = commandBuffer->vertexResourceDescriptorSet;
  4357. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4358. currentWriteDescriptorSet->pBufferInfo = NULL;
  4359. imageInfos[imageInfoCount].sampler = commandBuffer->vertexSamplers[i]->sampler;
  4360. imageInfos[imageInfoCount].imageView = commandBuffer->vertexSamplerTextures[i]->fullView;
  4361. imageInfos[imageInfoCount].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  4362. currentWriteDescriptorSet->pImageInfo = &imageInfos[imageInfoCount];
  4363. writeCount += 1;
  4364. imageInfoCount += 1;
  4365. }
  4366. for (Uint32 i = 0; i < resourceLayout->vertexStorageTextureCount; i += 1) {
  4367. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4368. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4369. currentWriteDescriptorSet->pNext = NULL;
  4370. currentWriteDescriptorSet->descriptorCount = 1;
  4371. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; // Yes, we are declaring a storage image as a sampled image, because shaders are stupid.
  4372. currentWriteDescriptorSet->dstArrayElement = 0;
  4373. currentWriteDescriptorSet->dstBinding = resourceLayout->vertexSamplerCount + i;
  4374. currentWriteDescriptorSet->dstSet = commandBuffer->vertexResourceDescriptorSet;
  4375. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4376. currentWriteDescriptorSet->pBufferInfo = NULL;
  4377. imageInfos[imageInfoCount].sampler = VK_NULL_HANDLE;
  4378. imageInfos[imageInfoCount].imageView = commandBuffer->vertexStorageTextures[i]->fullView;
  4379. imageInfos[imageInfoCount].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
  4380. currentWriteDescriptorSet->pImageInfo = &imageInfos[imageInfoCount];
  4381. writeCount += 1;
  4382. imageInfoCount += 1;
  4383. }
  4384. for (Uint32 i = 0; i < resourceLayout->vertexStorageBufferCount; i += 1) {
  4385. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4386. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4387. currentWriteDescriptorSet->pNext = NULL;
  4388. currentWriteDescriptorSet->descriptorCount = 1;
  4389. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  4390. currentWriteDescriptorSet->dstArrayElement = 0;
  4391. currentWriteDescriptorSet->dstBinding = resourceLayout->vertexSamplerCount + resourceLayout->vertexStorageTextureCount + i;
  4392. currentWriteDescriptorSet->dstSet = commandBuffer->vertexResourceDescriptorSet;
  4393. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4394. currentWriteDescriptorSet->pImageInfo = NULL;
  4395. bufferInfos[bufferInfoCount].buffer = commandBuffer->vertexStorageBuffers[i]->buffer;
  4396. bufferInfos[bufferInfoCount].offset = 0;
  4397. bufferInfos[bufferInfoCount].range = VK_WHOLE_SIZE;
  4398. currentWriteDescriptorSet->pBufferInfo = &bufferInfos[bufferInfoCount];
  4399. writeCount += 1;
  4400. bufferInfoCount += 1;
  4401. }
  4402. commandBuffer->needNewVertexResourceDescriptorSet = false;
  4403. }
  4404. if (commandBuffer->needNewVertexUniformDescriptorSet) {
  4405. descriptorSetLayout = resourceLayout->descriptorSetLayouts[1];
  4406. commandBuffer->vertexUniformDescriptorSet = VULKAN_INTERNAL_FetchDescriptorSet(
  4407. renderer,
  4408. commandBuffer,
  4409. descriptorSetLayout);
  4410. for (Uint32 i = 0; i < resourceLayout->vertexUniformBufferCount; i += 1) {
  4411. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4412. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4413. currentWriteDescriptorSet->pNext = NULL;
  4414. currentWriteDescriptorSet->descriptorCount = 1;
  4415. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
  4416. currentWriteDescriptorSet->dstArrayElement = 0;
  4417. currentWriteDescriptorSet->dstBinding = i;
  4418. currentWriteDescriptorSet->dstSet = commandBuffer->vertexUniformDescriptorSet;
  4419. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4420. currentWriteDescriptorSet->pImageInfo = NULL;
  4421. bufferInfos[bufferInfoCount].buffer = commandBuffer->vertexUniformBuffers[i]->buffer->buffer;
  4422. bufferInfos[bufferInfoCount].offset = 0;
  4423. bufferInfos[bufferInfoCount].range = MAX_UBO_SECTION_SIZE;
  4424. currentWriteDescriptorSet->pBufferInfo = &bufferInfos[bufferInfoCount];
  4425. writeCount += 1;
  4426. bufferInfoCount += 1;
  4427. }
  4428. commandBuffer->needNewVertexUniformDescriptorSet = false;
  4429. }
  4430. for (Uint32 i = 0; i < resourceLayout->vertexUniformBufferCount; i += 1) {
  4431. dynamicOffsets[dynamicOffsetCount] = commandBuffer->vertexUniformBuffers[i]->drawOffset;
  4432. dynamicOffsetCount += 1;
  4433. }
  4434. if (commandBuffer->needNewFragmentResourceDescriptorSet) {
  4435. descriptorSetLayout = resourceLayout->descriptorSetLayouts[2];
  4436. commandBuffer->fragmentResourceDescriptorSet = VULKAN_INTERNAL_FetchDescriptorSet(
  4437. renderer,
  4438. commandBuffer,
  4439. descriptorSetLayout);
  4440. for (Uint32 i = 0; i < resourceLayout->fragmentSamplerCount; i += 1) {
  4441. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4442. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4443. currentWriteDescriptorSet->pNext = NULL;
  4444. currentWriteDescriptorSet->descriptorCount = 1;
  4445. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  4446. currentWriteDescriptorSet->dstArrayElement = 0;
  4447. currentWriteDescriptorSet->dstBinding = i;
  4448. currentWriteDescriptorSet->dstSet = commandBuffer->fragmentResourceDescriptorSet;
  4449. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4450. currentWriteDescriptorSet->pBufferInfo = NULL;
  4451. imageInfos[imageInfoCount].sampler = commandBuffer->fragmentSamplers[i]->sampler;
  4452. imageInfos[imageInfoCount].imageView = commandBuffer->fragmentSamplerTextures[i]->fullView;
  4453. imageInfos[imageInfoCount].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  4454. currentWriteDescriptorSet->pImageInfo = &imageInfos[imageInfoCount];
  4455. writeCount += 1;
  4456. imageInfoCount += 1;
  4457. }
  4458. for (Uint32 i = 0; i < resourceLayout->fragmentStorageTextureCount; i += 1) {
  4459. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4460. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4461. currentWriteDescriptorSet->pNext = NULL;
  4462. currentWriteDescriptorSet->descriptorCount = 1;
  4463. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; // Yes, we are declaring a storage image as a sampled image, because shaders are stupid.
  4464. currentWriteDescriptorSet->dstArrayElement = 0;
  4465. currentWriteDescriptorSet->dstBinding = resourceLayout->fragmentSamplerCount + i;
  4466. currentWriteDescriptorSet->dstSet = commandBuffer->fragmentResourceDescriptorSet;
  4467. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4468. currentWriteDescriptorSet->pBufferInfo = NULL;
  4469. imageInfos[imageInfoCount].sampler = VK_NULL_HANDLE;
  4470. imageInfos[imageInfoCount].imageView = commandBuffer->fragmentStorageTextures[i]->fullView;
  4471. imageInfos[imageInfoCount].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
  4472. currentWriteDescriptorSet->pImageInfo = &imageInfos[imageInfoCount];
  4473. writeCount += 1;
  4474. imageInfoCount += 1;
  4475. }
  4476. for (Uint32 i = 0; i < resourceLayout->fragmentStorageBufferCount; i += 1) {
  4477. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4478. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4479. currentWriteDescriptorSet->pNext = NULL;
  4480. currentWriteDescriptorSet->descriptorCount = 1;
  4481. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  4482. currentWriteDescriptorSet->dstArrayElement = 0;
  4483. currentWriteDescriptorSet->dstBinding = resourceLayout->fragmentSamplerCount + resourceLayout->fragmentStorageTextureCount + i;
  4484. currentWriteDescriptorSet->dstSet = commandBuffer->fragmentResourceDescriptorSet;
  4485. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4486. currentWriteDescriptorSet->pImageInfo = NULL;
  4487. bufferInfos[bufferInfoCount].buffer = commandBuffer->fragmentStorageBuffers[i]->buffer;
  4488. bufferInfos[bufferInfoCount].offset = 0;
  4489. bufferInfos[bufferInfoCount].range = VK_WHOLE_SIZE;
  4490. currentWriteDescriptorSet->pBufferInfo = &bufferInfos[bufferInfoCount];
  4491. writeCount += 1;
  4492. bufferInfoCount += 1;
  4493. }
  4494. commandBuffer->needNewFragmentResourceDescriptorSet = false;
  4495. }
  4496. if (commandBuffer->needNewFragmentUniformDescriptorSet) {
  4497. descriptorSetLayout = resourceLayout->descriptorSetLayouts[3];
  4498. commandBuffer->fragmentUniformDescriptorSet = VULKAN_INTERNAL_FetchDescriptorSet(
  4499. renderer,
  4500. commandBuffer,
  4501. descriptorSetLayout);
  4502. for (Uint32 i = 0; i < resourceLayout->fragmentUniformBufferCount; i += 1) {
  4503. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  4504. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  4505. currentWriteDescriptorSet->pNext = NULL;
  4506. currentWriteDescriptorSet->descriptorCount = 1;
  4507. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
  4508. currentWriteDescriptorSet->dstArrayElement = 0;
  4509. currentWriteDescriptorSet->dstBinding = i;
  4510. currentWriteDescriptorSet->dstSet = commandBuffer->fragmentUniformDescriptorSet;
  4511. currentWriteDescriptorSet->pTexelBufferView = NULL;
  4512. currentWriteDescriptorSet->pImageInfo = NULL;
  4513. bufferInfos[bufferInfoCount].buffer = commandBuffer->fragmentUniformBuffers[i]->buffer->buffer;
  4514. bufferInfos[bufferInfoCount].offset = 0;
  4515. bufferInfos[bufferInfoCount].range = MAX_UBO_SECTION_SIZE;
  4516. currentWriteDescriptorSet->pBufferInfo = &bufferInfos[bufferInfoCount];
  4517. writeCount += 1;
  4518. bufferInfoCount += 1;
  4519. }
  4520. commandBuffer->needNewFragmentUniformDescriptorSet = false;
  4521. }
  4522. for (Uint32 i = 0; i < resourceLayout->fragmentUniformBufferCount; i += 1) {
  4523. dynamicOffsets[dynamicOffsetCount] = commandBuffer->fragmentUniformBuffers[i]->drawOffset;
  4524. dynamicOffsetCount += 1;
  4525. }
  4526. renderer->vkUpdateDescriptorSets(
  4527. renderer->logicalDevice,
  4528. writeCount,
  4529. writeDescriptorSets,
  4530. 0,
  4531. NULL);
  4532. VkDescriptorSet sets[4];
  4533. sets[0] = commandBuffer->vertexResourceDescriptorSet;
  4534. sets[1] = commandBuffer->vertexUniformDescriptorSet;
  4535. sets[2] = commandBuffer->fragmentResourceDescriptorSet;
  4536. sets[3] = commandBuffer->fragmentUniformDescriptorSet;
  4537. renderer->vkCmdBindDescriptorSets(
  4538. commandBuffer->commandBuffer,
  4539. VK_PIPELINE_BIND_POINT_GRAPHICS,
  4540. resourceLayout->pipelineLayout,
  4541. 0,
  4542. 4,
  4543. sets,
  4544. dynamicOffsetCount,
  4545. dynamicOffsets);
  4546. commandBuffer->needNewVertexUniformOffsets = false;
  4547. commandBuffer->needNewFragmentUniformOffsets = false;
  4548. }
  4549. static void VULKAN_DrawIndexedPrimitives(
  4550. SDL_GPUCommandBuffer *commandBuffer,
  4551. Uint32 numIndices,
  4552. Uint32 numInstances,
  4553. Uint32 firstIndex,
  4554. Sint32 vertexOffset,
  4555. Uint32 firstInstance)
  4556. {
  4557. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  4558. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  4559. VULKAN_INTERNAL_BindGraphicsDescriptorSets(renderer, vulkanCommandBuffer);
  4560. renderer->vkCmdDrawIndexed(
  4561. vulkanCommandBuffer->commandBuffer,
  4562. numIndices,
  4563. numInstances,
  4564. firstIndex,
  4565. vertexOffset,
  4566. firstInstance);
  4567. }
  4568. static void VULKAN_DrawPrimitives(
  4569. SDL_GPUCommandBuffer *commandBuffer,
  4570. Uint32 numVertices,
  4571. Uint32 numInstances,
  4572. Uint32 firstVertex,
  4573. Uint32 firstInstance)
  4574. {
  4575. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  4576. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  4577. VULKAN_INTERNAL_BindGraphicsDescriptorSets(renderer, vulkanCommandBuffer);
  4578. renderer->vkCmdDraw(
  4579. vulkanCommandBuffer->commandBuffer,
  4580. numVertices,
  4581. numInstances,
  4582. firstVertex,
  4583. firstInstance);
  4584. }
  4585. static void VULKAN_DrawPrimitivesIndirect(
  4586. SDL_GPUCommandBuffer *commandBuffer,
  4587. SDL_GPUBuffer *buffer,
  4588. Uint32 offset,
  4589. Uint32 drawCount)
  4590. {
  4591. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  4592. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  4593. VulkanBuffer *vulkanBuffer = ((VulkanBufferContainer *)buffer)->activeBuffer;
  4594. Uint32 pitch = sizeof(SDL_GPUIndirectDrawCommand);
  4595. Uint32 i;
  4596. VULKAN_INTERNAL_BindGraphicsDescriptorSets(renderer, vulkanCommandBuffer);
  4597. if (renderer->supportsMultiDrawIndirect) {
  4598. // Real multi-draw!
  4599. renderer->vkCmdDrawIndirect(
  4600. vulkanCommandBuffer->commandBuffer,
  4601. vulkanBuffer->buffer,
  4602. offset,
  4603. drawCount,
  4604. pitch);
  4605. } else {
  4606. // Fake multi-draw...
  4607. for (i = 0; i < drawCount; i += 1) {
  4608. renderer->vkCmdDrawIndirect(
  4609. vulkanCommandBuffer->commandBuffer,
  4610. vulkanBuffer->buffer,
  4611. offset + (pitch * i),
  4612. 1,
  4613. pitch);
  4614. }
  4615. }
  4616. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, vulkanBuffer);
  4617. }
  4618. static void VULKAN_DrawIndexedPrimitivesIndirect(
  4619. SDL_GPUCommandBuffer *commandBuffer,
  4620. SDL_GPUBuffer *buffer,
  4621. Uint32 offset,
  4622. Uint32 drawCount)
  4623. {
  4624. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  4625. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  4626. VulkanBuffer *vulkanBuffer = ((VulkanBufferContainer *)buffer)->activeBuffer;
  4627. Uint32 pitch = sizeof(SDL_GPUIndexedIndirectDrawCommand);
  4628. Uint32 i;
  4629. VULKAN_INTERNAL_BindGraphicsDescriptorSets(renderer, vulkanCommandBuffer);
  4630. if (renderer->supportsMultiDrawIndirect) {
  4631. // Real multi-draw!
  4632. renderer->vkCmdDrawIndexedIndirect(
  4633. vulkanCommandBuffer->commandBuffer,
  4634. vulkanBuffer->buffer,
  4635. offset,
  4636. drawCount,
  4637. pitch);
  4638. } else {
  4639. // Fake multi-draw...
  4640. for (i = 0; i < drawCount; i += 1) {
  4641. renderer->vkCmdDrawIndexedIndirect(
  4642. vulkanCommandBuffer->commandBuffer,
  4643. vulkanBuffer->buffer,
  4644. offset + (pitch * i),
  4645. 1,
  4646. pitch);
  4647. }
  4648. }
  4649. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, vulkanBuffer);
  4650. }
  4651. // Debug Naming
  4652. static void VULKAN_INTERNAL_SetBufferName(
  4653. VulkanRenderer *renderer,
  4654. VulkanBuffer *buffer,
  4655. const char *text)
  4656. {
  4657. VkDebugUtilsObjectNameInfoEXT nameInfo;
  4658. if (renderer->debugMode && renderer->supportsDebugUtils) {
  4659. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  4660. nameInfo.pNext = NULL;
  4661. nameInfo.pObjectName = text;
  4662. nameInfo.objectType = VK_OBJECT_TYPE_BUFFER;
  4663. nameInfo.objectHandle = (uint64_t)buffer->buffer;
  4664. renderer->vkSetDebugUtilsObjectNameEXT(
  4665. renderer->logicalDevice,
  4666. &nameInfo);
  4667. }
  4668. }
  4669. static void VULKAN_SetBufferName(
  4670. SDL_GPURenderer *driverData,
  4671. SDL_GPUBuffer *buffer,
  4672. const char *text)
  4673. {
  4674. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  4675. VulkanBufferContainer *container = (VulkanBufferContainer *)buffer;
  4676. size_t textLength = SDL_strlen(text) + 1;
  4677. if (renderer->debugMode && renderer->supportsDebugUtils) {
  4678. container->debugName = SDL_realloc(
  4679. container->debugName,
  4680. textLength);
  4681. SDL_utf8strlcpy(
  4682. container->debugName,
  4683. text,
  4684. textLength);
  4685. for (Uint32 i = 0; i < container->bufferCount; i += 1) {
  4686. VULKAN_INTERNAL_SetBufferName(
  4687. renderer,
  4688. container->buffers[i],
  4689. text);
  4690. }
  4691. }
  4692. }
  4693. static void VULKAN_INTERNAL_SetTextureName(
  4694. VulkanRenderer *renderer,
  4695. VulkanTexture *texture,
  4696. const char *text)
  4697. {
  4698. VkDebugUtilsObjectNameInfoEXT nameInfo;
  4699. if (renderer->debugMode && renderer->supportsDebugUtils) {
  4700. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  4701. nameInfo.pNext = NULL;
  4702. nameInfo.pObjectName = text;
  4703. nameInfo.objectType = VK_OBJECT_TYPE_IMAGE;
  4704. nameInfo.objectHandle = (uint64_t)texture->image;
  4705. renderer->vkSetDebugUtilsObjectNameEXT(
  4706. renderer->logicalDevice,
  4707. &nameInfo);
  4708. }
  4709. }
  4710. static void VULKAN_SetTextureName(
  4711. SDL_GPURenderer *driverData,
  4712. SDL_GPUTexture *texture,
  4713. const char *text)
  4714. {
  4715. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  4716. VulkanTextureContainer *container = (VulkanTextureContainer *)texture;
  4717. size_t textLength = SDL_strlen(text) + 1;
  4718. if (renderer->debugMode && renderer->supportsDebugUtils) {
  4719. container->debugName = SDL_realloc(
  4720. container->debugName,
  4721. textLength);
  4722. SDL_utf8strlcpy(
  4723. container->debugName,
  4724. text,
  4725. textLength);
  4726. for (Uint32 i = 0; i < container->textureCount; i += 1) {
  4727. VULKAN_INTERNAL_SetTextureName(
  4728. renderer,
  4729. container->textures[i],
  4730. text);
  4731. }
  4732. }
  4733. }
  4734. static void VULKAN_InsertDebugLabel(
  4735. SDL_GPUCommandBuffer *commandBuffer,
  4736. const char *text)
  4737. {
  4738. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  4739. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  4740. VkDebugUtilsLabelEXT labelInfo;
  4741. if (renderer->supportsDebugUtils) {
  4742. SDL_zero(labelInfo);
  4743. labelInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
  4744. labelInfo.pLabelName = text;
  4745. renderer->vkCmdInsertDebugUtilsLabelEXT(
  4746. vulkanCommandBuffer->commandBuffer,
  4747. &labelInfo);
  4748. }
  4749. }
  4750. static void VULKAN_PushDebugGroup(
  4751. SDL_GPUCommandBuffer *commandBuffer,
  4752. const char *name)
  4753. {
  4754. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  4755. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  4756. VkDebugUtilsLabelEXT labelInfo;
  4757. if (renderer->supportsDebugUtils) {
  4758. SDL_zero(labelInfo);
  4759. labelInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
  4760. labelInfo.pLabelName = name;
  4761. renderer->vkCmdBeginDebugUtilsLabelEXT(
  4762. vulkanCommandBuffer->commandBuffer,
  4763. &labelInfo);
  4764. }
  4765. }
  4766. static void VULKAN_PopDebugGroup(
  4767. SDL_GPUCommandBuffer *commandBuffer)
  4768. {
  4769. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  4770. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  4771. if (renderer->supportsDebugUtils) {
  4772. renderer->vkCmdEndDebugUtilsLabelEXT(vulkanCommandBuffer->commandBuffer);
  4773. }
  4774. }
  4775. static VulkanTexture *VULKAN_INTERNAL_CreateTexture(
  4776. VulkanRenderer *renderer,
  4777. bool transitionToDefaultLayout,
  4778. const SDL_GPUTextureCreateInfo *createinfo)
  4779. {
  4780. VkResult vulkanResult;
  4781. VkImageCreateInfo imageCreateInfo;
  4782. VkImageCreateFlags imageCreateFlags = 0;
  4783. VkImageViewCreateInfo imageViewCreateInfo;
  4784. Uint8 bindResult;
  4785. VkImageUsageFlags vkUsageFlags = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  4786. Uint32 layerCount = (createinfo->type == SDL_GPU_TEXTURETYPE_3D) ? 1 : createinfo->layer_count_or_depth;
  4787. Uint32 depth = (createinfo->type == SDL_GPU_TEXTURETYPE_3D) ? createinfo->layer_count_or_depth : 1;
  4788. VulkanTexture *texture = SDL_calloc(1, sizeof(VulkanTexture));
  4789. texture->swizzle = SwizzleForSDLFormat(createinfo->format);
  4790. texture->depth = depth;
  4791. texture->usage = createinfo->usage;
  4792. SDL_SetAtomicInt(&texture->referenceCount, 0);
  4793. if (IsDepthFormat(createinfo->format)) {
  4794. texture->aspectFlags = VK_IMAGE_ASPECT_DEPTH_BIT;
  4795. if (IsStencilFormat(createinfo->format)) {
  4796. texture->aspectFlags |= VK_IMAGE_ASPECT_STENCIL_BIT;
  4797. }
  4798. } else {
  4799. texture->aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT;
  4800. }
  4801. if (createinfo->type == SDL_GPU_TEXTURETYPE_CUBE || createinfo->type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  4802. imageCreateFlags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
  4803. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_3D) {
  4804. imageCreateFlags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT;
  4805. }
  4806. if (createinfo->usage & (SDL_GPU_TEXTUREUSAGE_SAMPLER |
  4807. SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ |
  4808. SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ)) {
  4809. vkUsageFlags |= VK_IMAGE_USAGE_SAMPLED_BIT;
  4810. }
  4811. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) {
  4812. vkUsageFlags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  4813. }
  4814. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) {
  4815. vkUsageFlags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  4816. }
  4817. if (createinfo->usage & (SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE |
  4818. SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE)) {
  4819. vkUsageFlags |= VK_IMAGE_USAGE_STORAGE_BIT;
  4820. }
  4821. imageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  4822. imageCreateInfo.pNext = NULL;
  4823. imageCreateInfo.flags = imageCreateFlags;
  4824. imageCreateInfo.imageType = createinfo->type == SDL_GPU_TEXTURETYPE_3D ? VK_IMAGE_TYPE_3D : VK_IMAGE_TYPE_2D;
  4825. imageCreateInfo.format = SDLToVK_TextureFormat[createinfo->format];
  4826. imageCreateInfo.extent.width = createinfo->width;
  4827. imageCreateInfo.extent.height = createinfo->height;
  4828. imageCreateInfo.extent.depth = depth;
  4829. imageCreateInfo.mipLevels = createinfo->num_levels;
  4830. imageCreateInfo.arrayLayers = layerCount;
  4831. imageCreateInfo.samples = SDLToVK_SampleCount[createinfo->sample_count];
  4832. imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  4833. imageCreateInfo.usage = vkUsageFlags;
  4834. imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  4835. imageCreateInfo.queueFamilyIndexCount = 0;
  4836. imageCreateInfo.pQueueFamilyIndices = NULL;
  4837. imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  4838. vulkanResult = renderer->vkCreateImage(
  4839. renderer->logicalDevice,
  4840. &imageCreateInfo,
  4841. NULL,
  4842. &texture->image);
  4843. if (vulkanResult != VK_SUCCESS) {
  4844. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4845. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateImage, NULL);
  4846. }
  4847. bindResult = VULKAN_INTERNAL_BindMemoryForImage(
  4848. renderer,
  4849. texture->image,
  4850. &texture->usedRegion);
  4851. if (bindResult != 1) {
  4852. renderer->vkDestroyImage(
  4853. renderer->logicalDevice,
  4854. texture->image,
  4855. NULL);
  4856. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4857. SET_STRING_ERROR_AND_RETURN("Unable to bind memory for texture!", NULL);
  4858. }
  4859. texture->usedRegion->vulkanTexture = texture; // lol
  4860. if (createinfo->usage & (SDL_GPU_TEXTUREUSAGE_SAMPLER | SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ | SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ)) {
  4861. imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  4862. imageViewCreateInfo.pNext = NULL;
  4863. imageViewCreateInfo.flags = 0;
  4864. imageViewCreateInfo.image = texture->image;
  4865. imageViewCreateInfo.format = SDLToVK_TextureFormat[createinfo->format];
  4866. imageViewCreateInfo.components = texture->swizzle;
  4867. imageViewCreateInfo.subresourceRange.aspectMask = texture->aspectFlags & ~VK_IMAGE_ASPECT_STENCIL_BIT; // Can't sample stencil values
  4868. imageViewCreateInfo.subresourceRange.baseMipLevel = 0;
  4869. imageViewCreateInfo.subresourceRange.levelCount = createinfo->num_levels;
  4870. imageViewCreateInfo.subresourceRange.baseArrayLayer = 0;
  4871. imageViewCreateInfo.subresourceRange.layerCount = layerCount;
  4872. if (createinfo->type == SDL_GPU_TEXTURETYPE_CUBE) {
  4873. imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_CUBE;
  4874. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  4875. imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_CUBE_ARRAY;
  4876. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_3D) {
  4877. imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_3D;
  4878. } else if (createinfo->type == SDL_GPU_TEXTURETYPE_2D_ARRAY) {
  4879. imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY;
  4880. } else {
  4881. imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  4882. }
  4883. vulkanResult = renderer->vkCreateImageView(
  4884. renderer->logicalDevice,
  4885. &imageViewCreateInfo,
  4886. NULL,
  4887. &texture->fullView);
  4888. if (vulkanResult != VK_SUCCESS) {
  4889. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4890. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, "vkCreateImageView", NULL);
  4891. }
  4892. }
  4893. // Define slices
  4894. texture->subresourceCount = layerCount * createinfo->num_levels;
  4895. texture->subresources = SDL_calloc(
  4896. texture->subresourceCount,
  4897. sizeof(VulkanTextureSubresource));
  4898. for (Uint32 i = 0; i < layerCount; i += 1) {
  4899. for (Uint32 j = 0; j < createinfo->num_levels; j += 1) {
  4900. Uint32 subresourceIndex = VULKAN_INTERNAL_GetTextureSubresourceIndex(
  4901. j,
  4902. i,
  4903. createinfo->num_levels);
  4904. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) {
  4905. texture->subresources[subresourceIndex].renderTargetViews = SDL_malloc(
  4906. depth * sizeof(VkImageView));
  4907. if (depth > 1) {
  4908. for (Uint32 k = 0; k < depth; k += 1) {
  4909. if (!VULKAN_INTERNAL_CreateRenderTargetView(
  4910. renderer,
  4911. texture,
  4912. k,
  4913. j,
  4914. SDLToVK_TextureFormat[createinfo->format],
  4915. texture->swizzle,
  4916. &texture->subresources[subresourceIndex].renderTargetViews[k])) {
  4917. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4918. return NULL;
  4919. }
  4920. }
  4921. } else {
  4922. if (!VULKAN_INTERNAL_CreateRenderTargetView(
  4923. renderer,
  4924. texture,
  4925. i,
  4926. j,
  4927. SDLToVK_TextureFormat[createinfo->format],
  4928. texture->swizzle,
  4929. &texture->subresources[subresourceIndex].renderTargetViews[0])) {
  4930. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4931. return NULL;
  4932. }
  4933. }
  4934. }
  4935. if ((createinfo->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE) || (createinfo->usage & SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE)) {
  4936. if (!VULKAN_INTERNAL_CreateSubresourceView(
  4937. renderer,
  4938. createinfo,
  4939. texture,
  4940. i,
  4941. j,
  4942. texture->swizzle,
  4943. &texture->subresources[subresourceIndex].computeWriteView)) {
  4944. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4945. return NULL;
  4946. }
  4947. }
  4948. if (createinfo->usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) {
  4949. if (!VULKAN_INTERNAL_CreateSubresourceView(
  4950. renderer,
  4951. createinfo,
  4952. texture,
  4953. i,
  4954. j,
  4955. texture->swizzle,
  4956. &texture->subresources[subresourceIndex].depthStencilView)) {
  4957. VULKAN_INTERNAL_DestroyTexture(renderer, texture);
  4958. return NULL;
  4959. }
  4960. }
  4961. texture->subresources[subresourceIndex].parent = texture;
  4962. texture->subresources[subresourceIndex].layer = i;
  4963. texture->subresources[subresourceIndex].level = j;
  4964. }
  4965. }
  4966. // Set debug name if applicable
  4967. if (renderer->debugMode && renderer->supportsDebugUtils && SDL_HasProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_NAME_STRING)) {
  4968. VkDebugUtilsObjectNameInfoEXT nameInfo;
  4969. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  4970. nameInfo.pNext = NULL;
  4971. nameInfo.pObjectName = SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_NAME_STRING, NULL);
  4972. nameInfo.objectType = VK_OBJECT_TYPE_IMAGE;
  4973. nameInfo.objectHandle = (uint64_t)texture->image;
  4974. renderer->vkSetDebugUtilsObjectNameEXT(
  4975. renderer->logicalDevice,
  4976. &nameInfo);
  4977. }
  4978. if (transitionToDefaultLayout) {
  4979. // Let's transition to the default barrier state, because for some reason Vulkan doesn't let us do that with initialLayout.
  4980. VulkanCommandBuffer *barrierCommandBuffer = (VulkanCommandBuffer *)VULKAN_AcquireCommandBuffer((SDL_GPURenderer *)renderer);
  4981. VULKAN_INTERNAL_TextureTransitionToDefaultUsage(
  4982. renderer,
  4983. barrierCommandBuffer,
  4984. VULKAN_TEXTURE_USAGE_MODE_UNINITIALIZED,
  4985. texture);
  4986. VULKAN_INTERNAL_TrackTexture(barrierCommandBuffer, texture);
  4987. VULKAN_Submit((SDL_GPUCommandBuffer *)barrierCommandBuffer);
  4988. }
  4989. return texture;
  4990. }
  4991. static void VULKAN_INTERNAL_CycleActiveBuffer(
  4992. VulkanRenderer *renderer,
  4993. VulkanBufferContainer *container)
  4994. {
  4995. VulkanBuffer *buffer;
  4996. // If a previously-cycled buffer is available, we can use that.
  4997. for (Uint32 i = 0; i < container->bufferCount; i += 1) {
  4998. buffer = container->buffers[i];
  4999. if (SDL_GetAtomicInt(&buffer->referenceCount) == 0) {
  5000. container->activeBuffer = buffer;
  5001. return;
  5002. }
  5003. }
  5004. // No buffer handle is available, create a new one.
  5005. buffer = VULKAN_INTERNAL_CreateBuffer(
  5006. renderer,
  5007. container->activeBuffer->size,
  5008. container->activeBuffer->usage,
  5009. container->activeBuffer->type,
  5010. container->dedicated,
  5011. container->debugName);
  5012. if (!buffer) {
  5013. return;
  5014. }
  5015. EXPAND_ARRAY_IF_NEEDED(
  5016. container->buffers,
  5017. VulkanBuffer *,
  5018. container->bufferCount + 1,
  5019. container->bufferCapacity,
  5020. container->bufferCapacity * 2);
  5021. container->buffers[container->bufferCount] = buffer;
  5022. buffer->container = container;
  5023. buffer->containerIndex = container->bufferCount;
  5024. container->bufferCount += 1;
  5025. container->activeBuffer = buffer;
  5026. }
  5027. static void VULKAN_INTERNAL_CycleActiveTexture(
  5028. VulkanRenderer *renderer,
  5029. VulkanCommandBuffer *commandBuffer,
  5030. VulkanTextureContainer *container)
  5031. {
  5032. VulkanTexture *texture;
  5033. // If a previously-cycled texture is available, we can use that.
  5034. for (Uint32 i = 0; i < container->textureCount; i += 1) {
  5035. texture = container->textures[i];
  5036. if (SDL_GetAtomicInt(&texture->referenceCount) == 0) {
  5037. container->activeTexture = texture;
  5038. return;
  5039. }
  5040. }
  5041. // No texture is available, generate a new one.
  5042. texture = VULKAN_INTERNAL_CreateTexture(
  5043. renderer,
  5044. false,
  5045. &container->header.info);
  5046. VULKAN_INTERNAL_TextureTransitionToDefaultUsage(
  5047. renderer,
  5048. commandBuffer,
  5049. VULKAN_TEXTURE_USAGE_MODE_UNINITIALIZED,
  5050. texture);
  5051. if (!texture) {
  5052. return;
  5053. }
  5054. EXPAND_ARRAY_IF_NEEDED(
  5055. container->textures,
  5056. VulkanTexture *,
  5057. container->textureCount + 1,
  5058. container->textureCapacity,
  5059. container->textureCapacity * 2);
  5060. container->textures[container->textureCount] = texture;
  5061. texture->container = container;
  5062. texture->containerIndex = container->textureCount;
  5063. container->textureCount += 1;
  5064. container->activeTexture = texture;
  5065. }
  5066. static VulkanBuffer *VULKAN_INTERNAL_PrepareBufferForWrite(
  5067. VulkanRenderer *renderer,
  5068. VulkanCommandBuffer *commandBuffer,
  5069. VulkanBufferContainer *bufferContainer,
  5070. bool cycle,
  5071. VulkanBufferUsageMode destinationUsageMode)
  5072. {
  5073. if (
  5074. cycle &&
  5075. SDL_GetAtomicInt(&bufferContainer->activeBuffer->referenceCount) > 0) {
  5076. VULKAN_INTERNAL_CycleActiveBuffer(
  5077. renderer,
  5078. bufferContainer);
  5079. }
  5080. VULKAN_INTERNAL_BufferTransitionFromDefaultUsage(
  5081. renderer,
  5082. commandBuffer,
  5083. destinationUsageMode,
  5084. bufferContainer->activeBuffer);
  5085. return bufferContainer->activeBuffer;
  5086. }
  5087. static VulkanTextureSubresource *VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  5088. VulkanRenderer *renderer,
  5089. VulkanCommandBuffer *commandBuffer,
  5090. VulkanTextureContainer *textureContainer,
  5091. Uint32 layer,
  5092. Uint32 level,
  5093. bool cycle,
  5094. VulkanTextureUsageMode destinationUsageMode)
  5095. {
  5096. VulkanTextureSubresource *textureSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  5097. textureContainer,
  5098. layer,
  5099. level);
  5100. if (
  5101. cycle &&
  5102. textureContainer->canBeCycled &&
  5103. SDL_GetAtomicInt(&textureContainer->activeTexture->referenceCount) > 0) {
  5104. VULKAN_INTERNAL_CycleActiveTexture(
  5105. renderer,
  5106. commandBuffer,
  5107. textureContainer);
  5108. textureSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  5109. textureContainer,
  5110. layer,
  5111. level);
  5112. }
  5113. // always do barrier because of layout transitions
  5114. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  5115. renderer,
  5116. commandBuffer,
  5117. destinationUsageMode,
  5118. textureSubresource);
  5119. return textureSubresource;
  5120. }
  5121. static VkRenderPass VULKAN_INTERNAL_CreateRenderPass(
  5122. VulkanRenderer *renderer,
  5123. VulkanCommandBuffer *commandBuffer,
  5124. const SDL_GPUColorTargetInfo *colorTargetInfos,
  5125. Uint32 numColorTargets,
  5126. const SDL_GPUDepthStencilTargetInfo *depthStencilTargetInfo)
  5127. {
  5128. VkResult vulkanResult;
  5129. VkAttachmentDescription attachmentDescriptions[2 * MAX_COLOR_TARGET_BINDINGS + 1 /* depth */];
  5130. VkAttachmentReference colorAttachmentReferences[MAX_COLOR_TARGET_BINDINGS];
  5131. VkAttachmentReference resolveReferences[MAX_COLOR_TARGET_BINDINGS];
  5132. VkAttachmentReference depthStencilAttachmentReference;
  5133. VkRenderPassCreateInfo renderPassCreateInfo;
  5134. VkSubpassDescription subpass;
  5135. VkRenderPass renderPass;
  5136. Uint32 i;
  5137. Uint32 attachmentDescriptionCount = 0;
  5138. Uint32 colorAttachmentReferenceCount = 0;
  5139. Uint32 resolveReferenceCount = 0;
  5140. for (i = 0; i < numColorTargets; i += 1) {
  5141. VulkanTextureContainer *container = (VulkanTextureContainer *)colorTargetInfos[i].texture;
  5142. attachmentDescriptions[attachmentDescriptionCount].flags = 0;
  5143. attachmentDescriptions[attachmentDescriptionCount].format = SDLToVK_TextureFormat[container->header.info.format];
  5144. attachmentDescriptions[attachmentDescriptionCount].samples = SDLToVK_SampleCount[container->header.info.sample_count];
  5145. attachmentDescriptions[attachmentDescriptionCount].loadOp = SDLToVK_LoadOp[colorTargetInfos[i].load_op];
  5146. attachmentDescriptions[attachmentDescriptionCount].storeOp = SDLToVK_StoreOp[colorTargetInfos[i].store_op];
  5147. attachmentDescriptions[attachmentDescriptionCount].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  5148. attachmentDescriptions[attachmentDescriptionCount].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  5149. attachmentDescriptions[attachmentDescriptionCount].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5150. attachmentDescriptions[attachmentDescriptionCount].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5151. colorAttachmentReferences[colorAttachmentReferenceCount].attachment = attachmentDescriptionCount;
  5152. colorAttachmentReferences[colorAttachmentReferenceCount].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5153. attachmentDescriptionCount += 1;
  5154. colorAttachmentReferenceCount += 1;
  5155. if (colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE || colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE_AND_STORE) {
  5156. VulkanTextureContainer *resolveContainer = (VulkanTextureContainer *)colorTargetInfos[i].resolve_texture;
  5157. attachmentDescriptions[attachmentDescriptionCount].flags = 0;
  5158. attachmentDescriptions[attachmentDescriptionCount].format = SDLToVK_TextureFormat[resolveContainer->header.info.format];
  5159. attachmentDescriptions[attachmentDescriptionCount].samples = SDLToVK_SampleCount[resolveContainer->header.info.sample_count];
  5160. attachmentDescriptions[attachmentDescriptionCount].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; // The texture will be overwritten anyway
  5161. attachmentDescriptions[attachmentDescriptionCount].storeOp = VK_ATTACHMENT_STORE_OP_STORE; // Always store the resolve texture
  5162. attachmentDescriptions[attachmentDescriptionCount].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  5163. attachmentDescriptions[attachmentDescriptionCount].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  5164. attachmentDescriptions[attachmentDescriptionCount].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5165. attachmentDescriptions[attachmentDescriptionCount].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5166. resolveReferences[resolveReferenceCount].attachment = attachmentDescriptionCount;
  5167. resolveReferences[resolveReferenceCount].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5168. attachmentDescriptionCount += 1;
  5169. resolveReferenceCount += 1;
  5170. }
  5171. }
  5172. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  5173. subpass.flags = 0;
  5174. subpass.inputAttachmentCount = 0;
  5175. subpass.pInputAttachments = NULL;
  5176. subpass.colorAttachmentCount = numColorTargets;
  5177. subpass.pColorAttachments = colorAttachmentReferences;
  5178. subpass.preserveAttachmentCount = 0;
  5179. subpass.pPreserveAttachments = NULL;
  5180. if (depthStencilTargetInfo == NULL) {
  5181. subpass.pDepthStencilAttachment = NULL;
  5182. } else {
  5183. VulkanTextureContainer *container = (VulkanTextureContainer *)depthStencilTargetInfo->texture;
  5184. attachmentDescriptions[attachmentDescriptionCount].flags = 0;
  5185. attachmentDescriptions[attachmentDescriptionCount].format = SDLToVK_TextureFormat[container->header.info.format];
  5186. attachmentDescriptions[attachmentDescriptionCount].samples = SDLToVK_SampleCount[container->header.info.sample_count];
  5187. attachmentDescriptions[attachmentDescriptionCount].loadOp = SDLToVK_LoadOp[depthStencilTargetInfo->load_op];
  5188. attachmentDescriptions[attachmentDescriptionCount].storeOp = SDLToVK_StoreOp[depthStencilTargetInfo->store_op];
  5189. attachmentDescriptions[attachmentDescriptionCount].stencilLoadOp = SDLToVK_LoadOp[depthStencilTargetInfo->stencil_load_op];
  5190. attachmentDescriptions[attachmentDescriptionCount].stencilStoreOp = SDLToVK_StoreOp[depthStencilTargetInfo->stencil_store_op];
  5191. attachmentDescriptions[attachmentDescriptionCount].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  5192. attachmentDescriptions[attachmentDescriptionCount].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  5193. depthStencilAttachmentReference.attachment = attachmentDescriptionCount;
  5194. depthStencilAttachmentReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  5195. subpass.pDepthStencilAttachment = &depthStencilAttachmentReference;
  5196. attachmentDescriptionCount += 1;
  5197. }
  5198. if (resolveReferenceCount > 0) {
  5199. subpass.pResolveAttachments = resolveReferences;
  5200. } else {
  5201. subpass.pResolveAttachments = NULL;
  5202. }
  5203. renderPassCreateInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  5204. renderPassCreateInfo.pNext = NULL;
  5205. renderPassCreateInfo.flags = 0;
  5206. renderPassCreateInfo.pAttachments = attachmentDescriptions;
  5207. renderPassCreateInfo.attachmentCount = attachmentDescriptionCount;
  5208. renderPassCreateInfo.subpassCount = 1;
  5209. renderPassCreateInfo.pSubpasses = &subpass;
  5210. renderPassCreateInfo.dependencyCount = 0;
  5211. renderPassCreateInfo.pDependencies = NULL;
  5212. vulkanResult = renderer->vkCreateRenderPass(
  5213. renderer->logicalDevice,
  5214. &renderPassCreateInfo,
  5215. NULL,
  5216. &renderPass);
  5217. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateRenderPass, VK_NULL_HANDLE);
  5218. return renderPass;
  5219. }
  5220. static VkRenderPass VULKAN_INTERNAL_CreateTransientRenderPass(
  5221. VulkanRenderer *renderer,
  5222. SDL_GPUGraphicsPipelineTargetInfo targetInfo,
  5223. VkSampleCountFlagBits sampleCount)
  5224. {
  5225. VkAttachmentDescription attachmentDescriptions[MAX_COLOR_TARGET_BINDINGS + 1 /* depth */];
  5226. VkAttachmentReference colorAttachmentReferences[MAX_COLOR_TARGET_BINDINGS];
  5227. VkAttachmentReference depthStencilAttachmentReference;
  5228. SDL_GPUColorTargetDescription attachmentDescription;
  5229. VkSubpassDescription subpass;
  5230. VkRenderPassCreateInfo renderPassCreateInfo;
  5231. VkRenderPass renderPass;
  5232. VkResult result;
  5233. Uint32 attachmentDescriptionCount = 0;
  5234. Uint32 colorAttachmentReferenceCount = 0;
  5235. Uint32 i;
  5236. for (i = 0; i < targetInfo.num_color_targets; i += 1) {
  5237. attachmentDescription = targetInfo.color_target_descriptions[i];
  5238. attachmentDescriptions[attachmentDescriptionCount].flags = 0;
  5239. attachmentDescriptions[attachmentDescriptionCount].format = SDLToVK_TextureFormat[attachmentDescription.format];
  5240. attachmentDescriptions[attachmentDescriptionCount].samples = sampleCount;
  5241. attachmentDescriptions[attachmentDescriptionCount].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  5242. attachmentDescriptions[attachmentDescriptionCount].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  5243. attachmentDescriptions[attachmentDescriptionCount].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  5244. attachmentDescriptions[attachmentDescriptionCount].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  5245. attachmentDescriptions[attachmentDescriptionCount].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5246. attachmentDescriptions[attachmentDescriptionCount].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5247. colorAttachmentReferences[colorAttachmentReferenceCount].attachment = attachmentDescriptionCount;
  5248. colorAttachmentReferences[colorAttachmentReferenceCount].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  5249. attachmentDescriptionCount += 1;
  5250. colorAttachmentReferenceCount += 1;
  5251. }
  5252. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  5253. subpass.flags = 0;
  5254. subpass.inputAttachmentCount = 0;
  5255. subpass.pInputAttachments = NULL;
  5256. subpass.colorAttachmentCount = targetInfo.num_color_targets;
  5257. subpass.pColorAttachments = colorAttachmentReferences;
  5258. subpass.preserveAttachmentCount = 0;
  5259. subpass.pPreserveAttachments = NULL;
  5260. if (targetInfo.has_depth_stencil_target) {
  5261. attachmentDescriptions[attachmentDescriptionCount].flags = 0;
  5262. attachmentDescriptions[attachmentDescriptionCount].format = SDLToVK_TextureFormat[targetInfo.depth_stencil_format];
  5263. attachmentDescriptions[attachmentDescriptionCount].samples = sampleCount;
  5264. attachmentDescriptions[attachmentDescriptionCount].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  5265. attachmentDescriptions[attachmentDescriptionCount].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  5266. attachmentDescriptions[attachmentDescriptionCount].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  5267. attachmentDescriptions[attachmentDescriptionCount].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  5268. attachmentDescriptions[attachmentDescriptionCount].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  5269. attachmentDescriptions[attachmentDescriptionCount].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  5270. depthStencilAttachmentReference.attachment = attachmentDescriptionCount;
  5271. depthStencilAttachmentReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  5272. subpass.pDepthStencilAttachment = &depthStencilAttachmentReference;
  5273. attachmentDescriptionCount += 1;
  5274. } else {
  5275. subpass.pDepthStencilAttachment = NULL;
  5276. }
  5277. // Resolve attachments aren't needed for transient passes
  5278. subpass.pResolveAttachments = NULL;
  5279. renderPassCreateInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  5280. renderPassCreateInfo.pNext = NULL;
  5281. renderPassCreateInfo.flags = 0;
  5282. renderPassCreateInfo.pAttachments = attachmentDescriptions;
  5283. renderPassCreateInfo.attachmentCount = attachmentDescriptionCount;
  5284. renderPassCreateInfo.subpassCount = 1;
  5285. renderPassCreateInfo.pSubpasses = &subpass;
  5286. renderPassCreateInfo.dependencyCount = 0;
  5287. renderPassCreateInfo.pDependencies = NULL;
  5288. result = renderer->vkCreateRenderPass(
  5289. renderer->logicalDevice,
  5290. &renderPassCreateInfo,
  5291. NULL,
  5292. &renderPass);
  5293. CHECK_VULKAN_ERROR_AND_RETURN(result, vkCreateRenderPass, VK_NULL_HANDLE);
  5294. return renderPass;
  5295. }
  5296. static SDL_GPUGraphicsPipeline *VULKAN_CreateGraphicsPipeline(
  5297. SDL_GPURenderer *driverData,
  5298. const SDL_GPUGraphicsPipelineCreateInfo *createinfo)
  5299. {
  5300. VkResult vulkanResult;
  5301. Uint32 i;
  5302. VulkanGraphicsPipeline *graphicsPipeline = (VulkanGraphicsPipeline *)SDL_malloc(sizeof(VulkanGraphicsPipeline));
  5303. VkGraphicsPipelineCreateInfo vkPipelineCreateInfo;
  5304. VkPipelineShaderStageCreateInfo shaderStageCreateInfos[2];
  5305. VkPipelineVertexInputStateCreateInfo vertexInputStateCreateInfo;
  5306. VkVertexInputBindingDescription *vertexInputBindingDescriptions = SDL_stack_alloc(VkVertexInputBindingDescription, createinfo->vertex_input_state.num_vertex_buffers);
  5307. VkVertexInputAttributeDescription *vertexInputAttributeDescriptions = SDL_stack_alloc(VkVertexInputAttributeDescription, createinfo->vertex_input_state.num_vertex_attributes);
  5308. VkPipelineInputAssemblyStateCreateInfo inputAssemblyStateCreateInfo;
  5309. VkPipelineViewportStateCreateInfo viewportStateCreateInfo;
  5310. VkPipelineRasterizationStateCreateInfo rasterizationStateCreateInfo;
  5311. VkPipelineMultisampleStateCreateInfo multisampleStateCreateInfo;
  5312. VkPipelineDepthStencilStateCreateInfo depthStencilStateCreateInfo;
  5313. VkStencilOpState frontStencilState;
  5314. VkStencilOpState backStencilState;
  5315. VkPipelineColorBlendStateCreateInfo colorBlendStateCreateInfo;
  5316. VkPipelineColorBlendAttachmentState *colorBlendAttachmentStates = SDL_stack_alloc(
  5317. VkPipelineColorBlendAttachmentState,
  5318. createinfo->target_info.num_color_targets);
  5319. static const VkDynamicState dynamicStates[] = {
  5320. VK_DYNAMIC_STATE_VIEWPORT,
  5321. VK_DYNAMIC_STATE_SCISSOR,
  5322. VK_DYNAMIC_STATE_BLEND_CONSTANTS,
  5323. VK_DYNAMIC_STATE_STENCIL_REFERENCE
  5324. };
  5325. VkPipelineDynamicStateCreateInfo dynamicStateCreateInfo;
  5326. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5327. // Create a "compatible" render pass
  5328. VkRenderPass transientRenderPass = VULKAN_INTERNAL_CreateTransientRenderPass(
  5329. renderer,
  5330. createinfo->target_info,
  5331. SDLToVK_SampleCount[createinfo->multisample_state.sample_count]);
  5332. // Dynamic state
  5333. dynamicStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
  5334. dynamicStateCreateInfo.pNext = NULL;
  5335. dynamicStateCreateInfo.flags = 0;
  5336. dynamicStateCreateInfo.dynamicStateCount = SDL_arraysize(dynamicStates);
  5337. dynamicStateCreateInfo.pDynamicStates = dynamicStates;
  5338. // Shader stages
  5339. graphicsPipeline->vertexShader = (VulkanShader *)createinfo->vertex_shader;
  5340. SDL_AtomicIncRef(&graphicsPipeline->vertexShader->referenceCount);
  5341. shaderStageCreateInfos[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  5342. shaderStageCreateInfos[0].pNext = NULL;
  5343. shaderStageCreateInfos[0].flags = 0;
  5344. shaderStageCreateInfos[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
  5345. shaderStageCreateInfos[0].module = graphicsPipeline->vertexShader->shaderModule;
  5346. shaderStageCreateInfos[0].pName = graphicsPipeline->vertexShader->entrypointName;
  5347. shaderStageCreateInfos[0].pSpecializationInfo = NULL;
  5348. graphicsPipeline->fragmentShader = (VulkanShader *)createinfo->fragment_shader;
  5349. SDL_AtomicIncRef(&graphicsPipeline->fragmentShader->referenceCount);
  5350. shaderStageCreateInfos[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  5351. shaderStageCreateInfos[1].pNext = NULL;
  5352. shaderStageCreateInfos[1].flags = 0;
  5353. shaderStageCreateInfos[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
  5354. shaderStageCreateInfos[1].module = graphicsPipeline->fragmentShader->shaderModule;
  5355. shaderStageCreateInfos[1].pName = graphicsPipeline->fragmentShader->entrypointName;
  5356. shaderStageCreateInfos[1].pSpecializationInfo = NULL;
  5357. if (renderer->debugMode) {
  5358. if (graphicsPipeline->vertexShader->stage != SDL_GPU_SHADERSTAGE_VERTEX) {
  5359. SDL_assert_release(!"CreateGraphicsPipeline was passed a fragment shader for the vertex stage");
  5360. }
  5361. if (graphicsPipeline->fragmentShader->stage != SDL_GPU_SHADERSTAGE_FRAGMENT) {
  5362. SDL_assert_release(!"CreateGraphicsPipeline was passed a vertex shader for the fragment stage");
  5363. }
  5364. }
  5365. // Vertex input
  5366. for (i = 0; i < createinfo->vertex_input_state.num_vertex_buffers; i += 1) {
  5367. vertexInputBindingDescriptions[i].binding = createinfo->vertex_input_state.vertex_buffer_descriptions[i].slot;
  5368. vertexInputBindingDescriptions[i].inputRate = SDLToVK_VertexInputRate[createinfo->vertex_input_state.vertex_buffer_descriptions[i].input_rate];
  5369. vertexInputBindingDescriptions[i].stride = createinfo->vertex_input_state.vertex_buffer_descriptions[i].pitch;
  5370. }
  5371. for (i = 0; i < createinfo->vertex_input_state.num_vertex_attributes; i += 1) {
  5372. vertexInputAttributeDescriptions[i].binding = createinfo->vertex_input_state.vertex_attributes[i].buffer_slot;
  5373. vertexInputAttributeDescriptions[i].format = SDLToVK_VertexFormat[createinfo->vertex_input_state.vertex_attributes[i].format];
  5374. vertexInputAttributeDescriptions[i].location = createinfo->vertex_input_state.vertex_attributes[i].location;
  5375. vertexInputAttributeDescriptions[i].offset = createinfo->vertex_input_state.vertex_attributes[i].offset;
  5376. }
  5377. vertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  5378. vertexInputStateCreateInfo.pNext = NULL;
  5379. vertexInputStateCreateInfo.flags = 0;
  5380. vertexInputStateCreateInfo.vertexBindingDescriptionCount = createinfo->vertex_input_state.num_vertex_buffers;
  5381. vertexInputStateCreateInfo.pVertexBindingDescriptions = vertexInputBindingDescriptions;
  5382. vertexInputStateCreateInfo.vertexAttributeDescriptionCount = createinfo->vertex_input_state.num_vertex_attributes;
  5383. vertexInputStateCreateInfo.pVertexAttributeDescriptions = vertexInputAttributeDescriptions;
  5384. // Topology
  5385. inputAssemblyStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  5386. inputAssemblyStateCreateInfo.pNext = NULL;
  5387. inputAssemblyStateCreateInfo.flags = 0;
  5388. inputAssemblyStateCreateInfo.primitiveRestartEnable = VK_FALSE;
  5389. inputAssemblyStateCreateInfo.topology = SDLToVK_PrimitiveType[createinfo->primitive_type];
  5390. graphicsPipeline->primitiveType = createinfo->primitive_type;
  5391. // Viewport
  5392. // NOTE: viewport and scissor are dynamic, and must be set using the command buffer
  5393. viewportStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  5394. viewportStateCreateInfo.pNext = NULL;
  5395. viewportStateCreateInfo.flags = 0;
  5396. viewportStateCreateInfo.viewportCount = 1;
  5397. viewportStateCreateInfo.pViewports = NULL;
  5398. viewportStateCreateInfo.scissorCount = 1;
  5399. viewportStateCreateInfo.pScissors = NULL;
  5400. // Rasterization
  5401. rasterizationStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  5402. rasterizationStateCreateInfo.pNext = NULL;
  5403. rasterizationStateCreateInfo.flags = 0;
  5404. rasterizationStateCreateInfo.depthClampEnable = !createinfo->rasterizer_state.enable_depth_clip;
  5405. rasterizationStateCreateInfo.rasterizerDiscardEnable = VK_FALSE;
  5406. rasterizationStateCreateInfo.polygonMode = SDLToVK_PolygonMode(
  5407. renderer,
  5408. createinfo->rasterizer_state.fill_mode);
  5409. rasterizationStateCreateInfo.cullMode = SDLToVK_CullMode[createinfo->rasterizer_state.cull_mode];
  5410. rasterizationStateCreateInfo.frontFace = SDLToVK_FrontFace[createinfo->rasterizer_state.front_face];
  5411. rasterizationStateCreateInfo.depthBiasEnable =
  5412. createinfo->rasterizer_state.enable_depth_bias;
  5413. rasterizationStateCreateInfo.depthBiasConstantFactor =
  5414. createinfo->rasterizer_state.depth_bias_constant_factor;
  5415. rasterizationStateCreateInfo.depthBiasClamp =
  5416. createinfo->rasterizer_state.depth_bias_clamp;
  5417. rasterizationStateCreateInfo.depthBiasSlopeFactor =
  5418. createinfo->rasterizer_state.depth_bias_slope_factor;
  5419. rasterizationStateCreateInfo.lineWidth = 1.0f;
  5420. // Multisample
  5421. Uint32 sampleMask = 0xFFFFFFFF;
  5422. multisampleStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  5423. multisampleStateCreateInfo.pNext = NULL;
  5424. multisampleStateCreateInfo.flags = 0;
  5425. multisampleStateCreateInfo.rasterizationSamples = SDLToVK_SampleCount[createinfo->multisample_state.sample_count];
  5426. multisampleStateCreateInfo.sampleShadingEnable = VK_FALSE;
  5427. multisampleStateCreateInfo.minSampleShading = 1.0f;
  5428. multisampleStateCreateInfo.pSampleMask = &sampleMask;
  5429. multisampleStateCreateInfo.alphaToCoverageEnable = VK_FALSE;
  5430. multisampleStateCreateInfo.alphaToOneEnable = VK_FALSE;
  5431. // Depth Stencil State
  5432. frontStencilState.failOp = SDLToVK_StencilOp[createinfo->depth_stencil_state.front_stencil_state.fail_op];
  5433. frontStencilState.passOp = SDLToVK_StencilOp[createinfo->depth_stencil_state.front_stencil_state.pass_op];
  5434. frontStencilState.depthFailOp = SDLToVK_StencilOp[createinfo->depth_stencil_state.front_stencil_state.depth_fail_op];
  5435. frontStencilState.compareOp = SDLToVK_CompareOp[createinfo->depth_stencil_state.front_stencil_state.compare_op];
  5436. frontStencilState.compareMask =
  5437. createinfo->depth_stencil_state.compare_mask;
  5438. frontStencilState.writeMask =
  5439. createinfo->depth_stencil_state.write_mask;
  5440. frontStencilState.reference = 0;
  5441. backStencilState.failOp = SDLToVK_StencilOp[createinfo->depth_stencil_state.back_stencil_state.fail_op];
  5442. backStencilState.passOp = SDLToVK_StencilOp[createinfo->depth_stencil_state.back_stencil_state.pass_op];
  5443. backStencilState.depthFailOp = SDLToVK_StencilOp[createinfo->depth_stencil_state.back_stencil_state.depth_fail_op];
  5444. backStencilState.compareOp = SDLToVK_CompareOp[createinfo->depth_stencil_state.back_stencil_state.compare_op];
  5445. backStencilState.compareMask =
  5446. createinfo->depth_stencil_state.compare_mask;
  5447. backStencilState.writeMask =
  5448. createinfo->depth_stencil_state.write_mask;
  5449. backStencilState.reference = 0;
  5450. depthStencilStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  5451. depthStencilStateCreateInfo.pNext = NULL;
  5452. depthStencilStateCreateInfo.flags = 0;
  5453. depthStencilStateCreateInfo.depthTestEnable =
  5454. createinfo->depth_stencil_state.enable_depth_test;
  5455. depthStencilStateCreateInfo.depthWriteEnable =
  5456. createinfo->depth_stencil_state.enable_depth_write;
  5457. depthStencilStateCreateInfo.depthCompareOp = SDLToVK_CompareOp[createinfo->depth_stencil_state.compare_op];
  5458. depthStencilStateCreateInfo.depthBoundsTestEnable = VK_FALSE;
  5459. depthStencilStateCreateInfo.stencilTestEnable =
  5460. createinfo->depth_stencil_state.enable_stencil_test;
  5461. depthStencilStateCreateInfo.front = frontStencilState;
  5462. depthStencilStateCreateInfo.back = backStencilState;
  5463. depthStencilStateCreateInfo.minDepthBounds = 0; // unused
  5464. depthStencilStateCreateInfo.maxDepthBounds = 0; // unused
  5465. // Color Blend
  5466. for (i = 0; i < createinfo->target_info.num_color_targets; i += 1) {
  5467. SDL_GPUColorTargetBlendState blendState = createinfo->target_info.color_target_descriptions[i].blend_state;
  5468. SDL_GPUColorComponentFlags colorWriteMask = blendState.enable_color_write_mask ?
  5469. blendState.color_write_mask :
  5470. 0xF;
  5471. colorBlendAttachmentStates[i].blendEnable =
  5472. blendState.enable_blend;
  5473. colorBlendAttachmentStates[i].srcColorBlendFactor = SDLToVK_BlendFactor[blendState.src_color_blendfactor];
  5474. colorBlendAttachmentStates[i].dstColorBlendFactor = SDLToVK_BlendFactor[blendState.dst_color_blendfactor];
  5475. colorBlendAttachmentStates[i].colorBlendOp = SDLToVK_BlendOp[blendState.color_blend_op];
  5476. colorBlendAttachmentStates[i].srcAlphaBlendFactor = SDLToVK_BlendFactor[blendState.src_alpha_blendfactor];
  5477. colorBlendAttachmentStates[i].dstAlphaBlendFactor = SDLToVK_BlendFactor[blendState.dst_alpha_blendfactor];
  5478. colorBlendAttachmentStates[i].alphaBlendOp = SDLToVK_BlendOp[blendState.alpha_blend_op];
  5479. colorBlendAttachmentStates[i].colorWriteMask =
  5480. colorWriteMask;
  5481. }
  5482. colorBlendStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  5483. colorBlendStateCreateInfo.pNext = NULL;
  5484. colorBlendStateCreateInfo.flags = 0;
  5485. colorBlendStateCreateInfo.attachmentCount =
  5486. createinfo->target_info.num_color_targets;
  5487. colorBlendStateCreateInfo.pAttachments =
  5488. colorBlendAttachmentStates;
  5489. colorBlendStateCreateInfo.blendConstants[0] = 1.0f;
  5490. colorBlendStateCreateInfo.blendConstants[1] = 1.0f;
  5491. colorBlendStateCreateInfo.blendConstants[2] = 1.0f;
  5492. colorBlendStateCreateInfo.blendConstants[3] = 1.0f;
  5493. // We don't support LogicOp, so this is easy.
  5494. colorBlendStateCreateInfo.logicOpEnable = VK_FALSE;
  5495. colorBlendStateCreateInfo.logicOp = 0;
  5496. // Pipeline Layout
  5497. graphicsPipeline->resourceLayout =
  5498. VULKAN_INTERNAL_FetchGraphicsPipelineResourceLayout(
  5499. renderer,
  5500. graphicsPipeline->vertexShader,
  5501. graphicsPipeline->fragmentShader);
  5502. if (graphicsPipeline->resourceLayout == NULL) {
  5503. SDL_stack_free(vertexInputBindingDescriptions);
  5504. SDL_stack_free(vertexInputAttributeDescriptions);
  5505. SDL_stack_free(colorBlendAttachmentStates);
  5506. SDL_free(graphicsPipeline);
  5507. SET_STRING_ERROR_AND_RETURN("Failed to initialize pipeline resource layout!", NULL);
  5508. }
  5509. // Pipeline
  5510. vkPipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  5511. vkPipelineCreateInfo.pNext = NULL;
  5512. vkPipelineCreateInfo.flags = 0;
  5513. vkPipelineCreateInfo.stageCount = 2;
  5514. vkPipelineCreateInfo.pStages = shaderStageCreateInfos;
  5515. vkPipelineCreateInfo.pVertexInputState = &vertexInputStateCreateInfo;
  5516. vkPipelineCreateInfo.pInputAssemblyState = &inputAssemblyStateCreateInfo;
  5517. vkPipelineCreateInfo.pTessellationState = VK_NULL_HANDLE;
  5518. vkPipelineCreateInfo.pViewportState = &viewportStateCreateInfo;
  5519. vkPipelineCreateInfo.pRasterizationState = &rasterizationStateCreateInfo;
  5520. vkPipelineCreateInfo.pMultisampleState = &multisampleStateCreateInfo;
  5521. vkPipelineCreateInfo.pDepthStencilState = &depthStencilStateCreateInfo;
  5522. vkPipelineCreateInfo.pColorBlendState = &colorBlendStateCreateInfo;
  5523. vkPipelineCreateInfo.pDynamicState = &dynamicStateCreateInfo;
  5524. vkPipelineCreateInfo.layout = graphicsPipeline->resourceLayout->pipelineLayout;
  5525. vkPipelineCreateInfo.renderPass = transientRenderPass;
  5526. vkPipelineCreateInfo.subpass = 0;
  5527. vkPipelineCreateInfo.basePipelineHandle = VK_NULL_HANDLE;
  5528. vkPipelineCreateInfo.basePipelineIndex = 0;
  5529. // TODO: enable pipeline caching
  5530. vulkanResult = renderer->vkCreateGraphicsPipelines(
  5531. renderer->logicalDevice,
  5532. VK_NULL_HANDLE,
  5533. 1,
  5534. &vkPipelineCreateInfo,
  5535. NULL,
  5536. &graphicsPipeline->pipeline);
  5537. SDL_stack_free(vertexInputBindingDescriptions);
  5538. SDL_stack_free(vertexInputAttributeDescriptions);
  5539. SDL_stack_free(colorBlendAttachmentStates);
  5540. renderer->vkDestroyRenderPass(
  5541. renderer->logicalDevice,
  5542. transientRenderPass,
  5543. NULL);
  5544. if (vulkanResult != VK_SUCCESS) {
  5545. SDL_free(graphicsPipeline);
  5546. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateGraphicsPipelines, NULL);
  5547. }
  5548. SDL_SetAtomicInt(&graphicsPipeline->referenceCount, 0);
  5549. if (renderer->debugMode && renderer->supportsDebugUtils && SDL_HasProperty(createinfo->props, SDL_PROP_GPU_GRAPHICSPIPELINE_CREATE_NAME_STRING)) {
  5550. VkDebugUtilsObjectNameInfoEXT nameInfo;
  5551. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  5552. nameInfo.pNext = NULL;
  5553. nameInfo.pObjectName = SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_GRAPHICSPIPELINE_CREATE_NAME_STRING, NULL);
  5554. nameInfo.objectType = VK_OBJECT_TYPE_PIPELINE;
  5555. nameInfo.objectHandle = (uint64_t)graphicsPipeline->pipeline;
  5556. renderer->vkSetDebugUtilsObjectNameEXT(
  5557. renderer->logicalDevice,
  5558. &nameInfo);
  5559. }
  5560. return (SDL_GPUGraphicsPipeline *)graphicsPipeline;
  5561. }
  5562. static SDL_GPUComputePipeline *VULKAN_CreateComputePipeline(
  5563. SDL_GPURenderer *driverData,
  5564. const SDL_GPUComputePipelineCreateInfo *createinfo)
  5565. {
  5566. VkShaderModuleCreateInfo shaderModuleCreateInfo;
  5567. VkComputePipelineCreateInfo vkShaderCreateInfo;
  5568. VkPipelineShaderStageCreateInfo pipelineShaderStageCreateInfo;
  5569. VkResult vulkanResult;
  5570. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5571. VulkanComputePipeline *vulkanComputePipeline;
  5572. if (createinfo->format != SDL_GPU_SHADERFORMAT_SPIRV) {
  5573. SET_STRING_ERROR_AND_RETURN("Incompatible shader format for Vulkan!", NULL);
  5574. }
  5575. vulkanComputePipeline = SDL_malloc(sizeof(VulkanComputePipeline));
  5576. shaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  5577. shaderModuleCreateInfo.pNext = NULL;
  5578. shaderModuleCreateInfo.flags = 0;
  5579. shaderModuleCreateInfo.codeSize = createinfo->code_size;
  5580. shaderModuleCreateInfo.pCode = (Uint32 *)createinfo->code;
  5581. vulkanResult = renderer->vkCreateShaderModule(
  5582. renderer->logicalDevice,
  5583. &shaderModuleCreateInfo,
  5584. NULL,
  5585. &vulkanComputePipeline->shaderModule);
  5586. if (vulkanResult != VK_SUCCESS) {
  5587. SDL_free(vulkanComputePipeline);
  5588. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateShaderModule, NULL);
  5589. }
  5590. pipelineShaderStageCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  5591. pipelineShaderStageCreateInfo.pNext = NULL;
  5592. pipelineShaderStageCreateInfo.flags = 0;
  5593. pipelineShaderStageCreateInfo.stage = VK_SHADER_STAGE_COMPUTE_BIT;
  5594. pipelineShaderStageCreateInfo.module = vulkanComputePipeline->shaderModule;
  5595. pipelineShaderStageCreateInfo.pName = createinfo->entrypoint;
  5596. pipelineShaderStageCreateInfo.pSpecializationInfo = NULL;
  5597. vulkanComputePipeline->resourceLayout = VULKAN_INTERNAL_FetchComputePipelineResourceLayout(
  5598. renderer,
  5599. createinfo);
  5600. if (vulkanComputePipeline->resourceLayout == NULL) {
  5601. renderer->vkDestroyShaderModule(
  5602. renderer->logicalDevice,
  5603. vulkanComputePipeline->shaderModule,
  5604. NULL);
  5605. SDL_free(vulkanComputePipeline);
  5606. return NULL;
  5607. }
  5608. vkShaderCreateInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
  5609. vkShaderCreateInfo.pNext = NULL;
  5610. vkShaderCreateInfo.flags = 0;
  5611. vkShaderCreateInfo.stage = pipelineShaderStageCreateInfo;
  5612. vkShaderCreateInfo.layout = vulkanComputePipeline->resourceLayout->pipelineLayout;
  5613. vkShaderCreateInfo.basePipelineHandle = (VkPipeline)VK_NULL_HANDLE;
  5614. vkShaderCreateInfo.basePipelineIndex = 0;
  5615. vulkanResult = renderer->vkCreateComputePipelines(
  5616. renderer->logicalDevice,
  5617. (VkPipelineCache)VK_NULL_HANDLE,
  5618. 1,
  5619. &vkShaderCreateInfo,
  5620. NULL,
  5621. &vulkanComputePipeline->pipeline);
  5622. if (vulkanResult != VK_SUCCESS) {
  5623. VULKAN_INTERNAL_DestroyComputePipeline(renderer, vulkanComputePipeline);
  5624. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateComputePipeline, NULL);
  5625. return NULL;
  5626. }
  5627. SDL_SetAtomicInt(&vulkanComputePipeline->referenceCount, 0);
  5628. if (renderer->debugMode && renderer->supportsDebugUtils && SDL_HasProperty(createinfo->props, SDL_PROP_GPU_COMPUTEPIPELINE_CREATE_NAME_STRING)) {
  5629. VkDebugUtilsObjectNameInfoEXT nameInfo;
  5630. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  5631. nameInfo.pNext = NULL;
  5632. nameInfo.pObjectName = SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_COMPUTEPIPELINE_CREATE_NAME_STRING, NULL);
  5633. nameInfo.objectType = VK_OBJECT_TYPE_PIPELINE;
  5634. nameInfo.objectHandle = (uint64_t)vulkanComputePipeline->pipeline;
  5635. renderer->vkSetDebugUtilsObjectNameEXT(
  5636. renderer->logicalDevice,
  5637. &nameInfo);
  5638. }
  5639. return (SDL_GPUComputePipeline *)vulkanComputePipeline;
  5640. }
  5641. static SDL_GPUSampler *VULKAN_CreateSampler(
  5642. SDL_GPURenderer *driverData,
  5643. const SDL_GPUSamplerCreateInfo *createinfo)
  5644. {
  5645. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5646. VulkanSampler *vulkanSampler = SDL_malloc(sizeof(VulkanSampler));
  5647. VkResult vulkanResult;
  5648. VkSamplerCreateInfo vkSamplerCreateInfo;
  5649. vkSamplerCreateInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  5650. vkSamplerCreateInfo.pNext = NULL;
  5651. vkSamplerCreateInfo.flags = 0;
  5652. vkSamplerCreateInfo.magFilter = SDLToVK_Filter[createinfo->mag_filter];
  5653. vkSamplerCreateInfo.minFilter = SDLToVK_Filter[createinfo->min_filter];
  5654. vkSamplerCreateInfo.mipmapMode = SDLToVK_SamplerMipmapMode[createinfo->mipmap_mode];
  5655. vkSamplerCreateInfo.addressModeU = SDLToVK_SamplerAddressMode[createinfo->address_mode_u];
  5656. vkSamplerCreateInfo.addressModeV = SDLToVK_SamplerAddressMode[createinfo->address_mode_v];
  5657. vkSamplerCreateInfo.addressModeW = SDLToVK_SamplerAddressMode[createinfo->address_mode_w];
  5658. vkSamplerCreateInfo.mipLodBias = createinfo->mip_lod_bias;
  5659. vkSamplerCreateInfo.anisotropyEnable = createinfo->enable_anisotropy;
  5660. vkSamplerCreateInfo.maxAnisotropy = createinfo->max_anisotropy;
  5661. vkSamplerCreateInfo.compareEnable = createinfo->enable_compare;
  5662. vkSamplerCreateInfo.compareOp = SDLToVK_CompareOp[createinfo->compare_op];
  5663. vkSamplerCreateInfo.minLod = createinfo->min_lod;
  5664. vkSamplerCreateInfo.maxLod = createinfo->max_lod;
  5665. vkSamplerCreateInfo.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; // arbitrary, unused
  5666. vkSamplerCreateInfo.unnormalizedCoordinates = VK_FALSE;
  5667. vulkanResult = renderer->vkCreateSampler(
  5668. renderer->logicalDevice,
  5669. &vkSamplerCreateInfo,
  5670. NULL,
  5671. &vulkanSampler->sampler);
  5672. if (vulkanResult != VK_SUCCESS) {
  5673. SDL_free(vulkanSampler);
  5674. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateSampler, NULL);
  5675. }
  5676. SDL_SetAtomicInt(&vulkanSampler->referenceCount, 0);
  5677. if (renderer->debugMode && renderer->supportsDebugUtils && SDL_HasProperty(createinfo->props, SDL_PROP_GPU_SAMPLER_CREATE_NAME_STRING)) {
  5678. VkDebugUtilsObjectNameInfoEXT nameInfo;
  5679. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  5680. nameInfo.pNext = NULL;
  5681. nameInfo.pObjectName = SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_SAMPLER_CREATE_NAME_STRING, NULL);
  5682. nameInfo.objectType = VK_OBJECT_TYPE_SAMPLER;
  5683. nameInfo.objectHandle = (uint64_t)vulkanSampler->sampler;
  5684. renderer->vkSetDebugUtilsObjectNameEXT(
  5685. renderer->logicalDevice,
  5686. &nameInfo);
  5687. }
  5688. return (SDL_GPUSampler *)vulkanSampler;
  5689. }
  5690. static SDL_GPUShader *VULKAN_CreateShader(
  5691. SDL_GPURenderer *driverData,
  5692. const SDL_GPUShaderCreateInfo *createinfo)
  5693. {
  5694. VulkanShader *vulkanShader;
  5695. VkResult vulkanResult;
  5696. VkShaderModuleCreateInfo vkShaderModuleCreateInfo;
  5697. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5698. vulkanShader = SDL_malloc(sizeof(VulkanShader));
  5699. vkShaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  5700. vkShaderModuleCreateInfo.pNext = NULL;
  5701. vkShaderModuleCreateInfo.flags = 0;
  5702. vkShaderModuleCreateInfo.codeSize = createinfo->code_size;
  5703. vkShaderModuleCreateInfo.pCode = (Uint32 *)createinfo->code;
  5704. vulkanResult = renderer->vkCreateShaderModule(
  5705. renderer->logicalDevice,
  5706. &vkShaderModuleCreateInfo,
  5707. NULL,
  5708. &vulkanShader->shaderModule);
  5709. if (vulkanResult != VK_SUCCESS) {
  5710. SDL_free(vulkanShader);
  5711. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateShaderModule, NULL);
  5712. }
  5713. const char *entrypoint = createinfo->entrypoint;
  5714. if (!entrypoint) {
  5715. entrypoint = "main";
  5716. }
  5717. vulkanShader->entrypointName = SDL_strdup(entrypoint);
  5718. vulkanShader->stage = createinfo->stage;
  5719. vulkanShader->numSamplers = createinfo->num_samplers;
  5720. vulkanShader->numStorageTextures = createinfo->num_storage_textures;
  5721. vulkanShader->numStorageBuffers = createinfo->num_storage_buffers;
  5722. vulkanShader->numUniformBuffers = createinfo->num_uniform_buffers;
  5723. SDL_SetAtomicInt(&vulkanShader->referenceCount, 0);
  5724. if (renderer->debugMode && SDL_HasProperty(createinfo->props, SDL_PROP_GPU_SHADER_CREATE_NAME_STRING)) {
  5725. VkDebugUtilsObjectNameInfoEXT nameInfo;
  5726. nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT;
  5727. nameInfo.pNext = NULL;
  5728. nameInfo.pObjectName = SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_SHADER_CREATE_NAME_STRING, NULL);
  5729. nameInfo.objectType = VK_OBJECT_TYPE_SHADER_MODULE;
  5730. nameInfo.objectHandle = (uint64_t)vulkanShader->shaderModule;
  5731. renderer->vkSetDebugUtilsObjectNameEXT(
  5732. renderer->logicalDevice,
  5733. &nameInfo);
  5734. }
  5735. return (SDL_GPUShader *)vulkanShader;
  5736. }
  5737. static bool VULKAN_SupportsSampleCount(
  5738. SDL_GPURenderer *driverData,
  5739. SDL_GPUTextureFormat format,
  5740. SDL_GPUSampleCount sampleCount)
  5741. {
  5742. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5743. VkSampleCountFlags bits = IsDepthFormat(format) ? renderer->physicalDeviceProperties.properties.limits.framebufferDepthSampleCounts : renderer->physicalDeviceProperties.properties.limits.framebufferColorSampleCounts;
  5744. VkSampleCountFlagBits vkSampleCount = SDLToVK_SampleCount[sampleCount];
  5745. return !!(bits & vkSampleCount);
  5746. }
  5747. static SDL_GPUTexture *VULKAN_CreateTexture(
  5748. SDL_GPURenderer *driverData,
  5749. const SDL_GPUTextureCreateInfo *createinfo)
  5750. {
  5751. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5752. VulkanTexture *texture;
  5753. VulkanTextureContainer *container;
  5754. texture = VULKAN_INTERNAL_CreateTexture(
  5755. renderer,
  5756. true,
  5757. createinfo);
  5758. if (texture == NULL) {
  5759. return NULL;
  5760. }
  5761. container = SDL_malloc(sizeof(VulkanTextureContainer));
  5762. // Copy properties so we don't lose information when the client destroys them
  5763. container->header.info = *createinfo;
  5764. container->header.info.props = SDL_CreateProperties();
  5765. if (createinfo->props) {
  5766. SDL_CopyProperties(createinfo->props, container->header.info.props);
  5767. }
  5768. container->canBeCycled = true;
  5769. container->activeTexture = texture;
  5770. container->textureCapacity = 1;
  5771. container->textureCount = 1;
  5772. container->textures = SDL_malloc(
  5773. container->textureCapacity * sizeof(VulkanTexture *));
  5774. container->textures[0] = container->activeTexture;
  5775. container->debugName = NULL;
  5776. if (SDL_HasProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_NAME_STRING)) {
  5777. container->debugName = SDL_strdup(SDL_GetStringProperty(createinfo->props, SDL_PROP_GPU_TEXTURE_CREATE_NAME_STRING, NULL));
  5778. }
  5779. texture->container = container;
  5780. texture->containerIndex = 0;
  5781. return (SDL_GPUTexture *)container;
  5782. }
  5783. static SDL_GPUBuffer *VULKAN_CreateBuffer(
  5784. SDL_GPURenderer *driverData,
  5785. SDL_GPUBufferUsageFlags usageFlags,
  5786. Uint32 size,
  5787. const char *debugName)
  5788. {
  5789. return (SDL_GPUBuffer *)VULKAN_INTERNAL_CreateBufferContainer(
  5790. (VulkanRenderer *)driverData,
  5791. (VkDeviceSize)size,
  5792. usageFlags,
  5793. VULKAN_BUFFER_TYPE_GPU,
  5794. false,
  5795. debugName);
  5796. }
  5797. static VulkanUniformBuffer *VULKAN_INTERNAL_CreateUniformBuffer(
  5798. VulkanRenderer *renderer,
  5799. Uint32 size)
  5800. {
  5801. VulkanUniformBuffer *uniformBuffer = SDL_calloc(1, sizeof(VulkanUniformBuffer));
  5802. uniformBuffer->buffer = VULKAN_INTERNAL_CreateBuffer(
  5803. renderer,
  5804. (VkDeviceSize)size,
  5805. 0,
  5806. VULKAN_BUFFER_TYPE_UNIFORM,
  5807. false,
  5808. NULL);
  5809. uniformBuffer->drawOffset = 0;
  5810. uniformBuffer->writeOffset = 0;
  5811. uniformBuffer->buffer->uniformBufferForDefrag = uniformBuffer;
  5812. return uniformBuffer;
  5813. }
  5814. static SDL_GPUTransferBuffer *VULKAN_CreateTransferBuffer(
  5815. SDL_GPURenderer *driverData,
  5816. SDL_GPUTransferBufferUsage usage,
  5817. Uint32 size,
  5818. const char *debugName)
  5819. {
  5820. return (SDL_GPUTransferBuffer *)VULKAN_INTERNAL_CreateBufferContainer(
  5821. (VulkanRenderer *)driverData,
  5822. (VkDeviceSize)size,
  5823. 0,
  5824. VULKAN_BUFFER_TYPE_TRANSFER,
  5825. true, // Dedicated allocations preserve the data even if a defrag is triggered.
  5826. debugName);
  5827. }
  5828. static void VULKAN_INTERNAL_ReleaseTexture(
  5829. VulkanRenderer *renderer,
  5830. VulkanTexture *vulkanTexture)
  5831. {
  5832. if (vulkanTexture->markedForDestroy) {
  5833. return;
  5834. }
  5835. SDL_LockMutex(renderer->disposeLock);
  5836. EXPAND_ARRAY_IF_NEEDED(
  5837. renderer->texturesToDestroy,
  5838. VulkanTexture *,
  5839. renderer->texturesToDestroyCount + 1,
  5840. renderer->texturesToDestroyCapacity,
  5841. renderer->texturesToDestroyCapacity * 2);
  5842. renderer->texturesToDestroy[renderer->texturesToDestroyCount] = vulkanTexture;
  5843. renderer->texturesToDestroyCount += 1;
  5844. vulkanTexture->markedForDestroy = true;
  5845. SDL_UnlockMutex(renderer->disposeLock);
  5846. }
  5847. static void VULKAN_ReleaseTexture(
  5848. SDL_GPURenderer *driverData,
  5849. SDL_GPUTexture *texture)
  5850. {
  5851. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5852. VulkanTextureContainer *vulkanTextureContainer = (VulkanTextureContainer *)texture;
  5853. Uint32 i;
  5854. SDL_LockMutex(renderer->disposeLock);
  5855. for (i = 0; i < vulkanTextureContainer->textureCount; i += 1) {
  5856. VULKAN_INTERNAL_ReleaseTexture(renderer, vulkanTextureContainer->textures[i]);
  5857. }
  5858. // Containers are just client handles, so we can destroy immediately
  5859. if (vulkanTextureContainer->debugName != NULL) {
  5860. SDL_free(vulkanTextureContainer->debugName);
  5861. }
  5862. SDL_free(vulkanTextureContainer->textures);
  5863. SDL_free(vulkanTextureContainer);
  5864. SDL_UnlockMutex(renderer->disposeLock);
  5865. }
  5866. static void VULKAN_ReleaseSampler(
  5867. SDL_GPURenderer *driverData,
  5868. SDL_GPUSampler *sampler)
  5869. {
  5870. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5871. VulkanSampler *vulkanSampler = (VulkanSampler *)sampler;
  5872. SDL_LockMutex(renderer->disposeLock);
  5873. EXPAND_ARRAY_IF_NEEDED(
  5874. renderer->samplersToDestroy,
  5875. VulkanSampler *,
  5876. renderer->samplersToDestroyCount + 1,
  5877. renderer->samplersToDestroyCapacity,
  5878. renderer->samplersToDestroyCapacity * 2);
  5879. renderer->samplersToDestroy[renderer->samplersToDestroyCount] = vulkanSampler;
  5880. renderer->samplersToDestroyCount += 1;
  5881. SDL_UnlockMutex(renderer->disposeLock);
  5882. }
  5883. static void VULKAN_INTERNAL_ReleaseBuffer(
  5884. VulkanRenderer *renderer,
  5885. VulkanBuffer *vulkanBuffer)
  5886. {
  5887. if (vulkanBuffer->markedForDestroy) {
  5888. return;
  5889. }
  5890. SDL_LockMutex(renderer->disposeLock);
  5891. EXPAND_ARRAY_IF_NEEDED(
  5892. renderer->buffersToDestroy,
  5893. VulkanBuffer *,
  5894. renderer->buffersToDestroyCount + 1,
  5895. renderer->buffersToDestroyCapacity,
  5896. renderer->buffersToDestroyCapacity * 2);
  5897. renderer->buffersToDestroy[renderer->buffersToDestroyCount] = vulkanBuffer;
  5898. renderer->buffersToDestroyCount += 1;
  5899. vulkanBuffer->markedForDestroy = true;
  5900. vulkanBuffer->container = NULL;
  5901. SDL_UnlockMutex(renderer->disposeLock);
  5902. }
  5903. static void VULKAN_INTERNAL_ReleaseBufferContainer(
  5904. VulkanRenderer *renderer,
  5905. VulkanBufferContainer *bufferContainer)
  5906. {
  5907. Uint32 i;
  5908. SDL_LockMutex(renderer->disposeLock);
  5909. for (i = 0; i < bufferContainer->bufferCount; i += 1) {
  5910. VULKAN_INTERNAL_ReleaseBuffer(renderer, bufferContainer->buffers[i]);
  5911. }
  5912. // Containers are just client handles, so we can free immediately
  5913. if (bufferContainer->debugName != NULL) {
  5914. SDL_free(bufferContainer->debugName);
  5915. bufferContainer->debugName = NULL;
  5916. }
  5917. SDL_free(bufferContainer->buffers);
  5918. SDL_free(bufferContainer);
  5919. SDL_UnlockMutex(renderer->disposeLock);
  5920. }
  5921. static void VULKAN_ReleaseBuffer(
  5922. SDL_GPURenderer *driverData,
  5923. SDL_GPUBuffer *buffer)
  5924. {
  5925. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5926. VulkanBufferContainer *vulkanBufferContainer = (VulkanBufferContainer *)buffer;
  5927. VULKAN_INTERNAL_ReleaseBufferContainer(
  5928. renderer,
  5929. vulkanBufferContainer);
  5930. }
  5931. static void VULKAN_ReleaseTransferBuffer(
  5932. SDL_GPURenderer *driverData,
  5933. SDL_GPUTransferBuffer *transferBuffer)
  5934. {
  5935. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5936. VulkanBufferContainer *transferBufferContainer = (VulkanBufferContainer *)transferBuffer;
  5937. VULKAN_INTERNAL_ReleaseBufferContainer(
  5938. renderer,
  5939. transferBufferContainer);
  5940. }
  5941. static void VULKAN_ReleaseShader(
  5942. SDL_GPURenderer *driverData,
  5943. SDL_GPUShader *shader)
  5944. {
  5945. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5946. VulkanShader *vulkanShader = (VulkanShader *)shader;
  5947. SDL_LockMutex(renderer->disposeLock);
  5948. EXPAND_ARRAY_IF_NEEDED(
  5949. renderer->shadersToDestroy,
  5950. VulkanShader *,
  5951. renderer->shadersToDestroyCount + 1,
  5952. renderer->shadersToDestroyCapacity,
  5953. renderer->shadersToDestroyCapacity * 2);
  5954. renderer->shadersToDestroy[renderer->shadersToDestroyCount] = vulkanShader;
  5955. renderer->shadersToDestroyCount += 1;
  5956. SDL_UnlockMutex(renderer->disposeLock);
  5957. }
  5958. static void VULKAN_ReleaseComputePipeline(
  5959. SDL_GPURenderer *driverData,
  5960. SDL_GPUComputePipeline *computePipeline)
  5961. {
  5962. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5963. VulkanComputePipeline *vulkanComputePipeline = (VulkanComputePipeline *)computePipeline;
  5964. SDL_LockMutex(renderer->disposeLock);
  5965. EXPAND_ARRAY_IF_NEEDED(
  5966. renderer->computePipelinesToDestroy,
  5967. VulkanComputePipeline *,
  5968. renderer->computePipelinesToDestroyCount + 1,
  5969. renderer->computePipelinesToDestroyCapacity,
  5970. renderer->computePipelinesToDestroyCapacity * 2);
  5971. renderer->computePipelinesToDestroy[renderer->computePipelinesToDestroyCount] = vulkanComputePipeline;
  5972. renderer->computePipelinesToDestroyCount += 1;
  5973. SDL_UnlockMutex(renderer->disposeLock);
  5974. }
  5975. static void VULKAN_ReleaseGraphicsPipeline(
  5976. SDL_GPURenderer *driverData,
  5977. SDL_GPUGraphicsPipeline *graphicsPipeline)
  5978. {
  5979. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  5980. VulkanGraphicsPipeline *vulkanGraphicsPipeline = (VulkanGraphicsPipeline *)graphicsPipeline;
  5981. SDL_LockMutex(renderer->disposeLock);
  5982. EXPAND_ARRAY_IF_NEEDED(
  5983. renderer->graphicsPipelinesToDestroy,
  5984. VulkanGraphicsPipeline *,
  5985. renderer->graphicsPipelinesToDestroyCount + 1,
  5986. renderer->graphicsPipelinesToDestroyCapacity,
  5987. renderer->graphicsPipelinesToDestroyCapacity * 2);
  5988. renderer->graphicsPipelinesToDestroy[renderer->graphicsPipelinesToDestroyCount] = vulkanGraphicsPipeline;
  5989. renderer->graphicsPipelinesToDestroyCount += 1;
  5990. SDL_UnlockMutex(renderer->disposeLock);
  5991. }
  5992. // Command Buffer render state
  5993. static VkRenderPass VULKAN_INTERNAL_FetchRenderPass(
  5994. VulkanRenderer *renderer,
  5995. VulkanCommandBuffer *commandBuffer,
  5996. const SDL_GPUColorTargetInfo *colorTargetInfos,
  5997. Uint32 numColorTargets,
  5998. const SDL_GPUDepthStencilTargetInfo *depthStencilTargetInfo)
  5999. {
  6000. VulkanRenderPassHashTableValue *renderPassWrapper = NULL;
  6001. VkRenderPass renderPassHandle;
  6002. RenderPassHashTableKey key;
  6003. Uint32 i;
  6004. SDL_zero(key);
  6005. for (i = 0; i < numColorTargets; i += 1) {
  6006. key.colorTargetDescriptions[i].format = SDLToVK_TextureFormat[((VulkanTextureContainer *)colorTargetInfos[i].texture)->header.info.format];
  6007. key.colorTargetDescriptions[i].loadOp = colorTargetInfos[i].load_op;
  6008. key.colorTargetDescriptions[i].storeOp = colorTargetInfos[i].store_op;
  6009. if (colorTargetInfos[i].resolve_texture != NULL) {
  6010. key.resolveTargetFormats[key.numResolveTargets] = SDLToVK_TextureFormat[((VulkanTextureContainer *)colorTargetInfos[i].resolve_texture)->header.info.format];
  6011. key.numResolveTargets += 1;
  6012. }
  6013. }
  6014. key.sampleCount = VK_SAMPLE_COUNT_1_BIT;
  6015. if (numColorTargets > 0) {
  6016. key.sampleCount = SDLToVK_SampleCount[((VulkanTextureContainer *)colorTargetInfos[0].texture)->header.info.sample_count];
  6017. }
  6018. key.numColorTargets = numColorTargets;
  6019. if (depthStencilTargetInfo == NULL) {
  6020. key.depthStencilTargetDescription.format = 0;
  6021. key.depthStencilTargetDescription.loadOp = SDL_GPU_LOADOP_DONT_CARE;
  6022. key.depthStencilTargetDescription.storeOp = SDL_GPU_STOREOP_DONT_CARE;
  6023. key.depthStencilTargetDescription.stencilLoadOp = SDL_GPU_LOADOP_DONT_CARE;
  6024. key.depthStencilTargetDescription.stencilStoreOp = SDL_GPU_STOREOP_DONT_CARE;
  6025. } else {
  6026. key.depthStencilTargetDescription.format = SDLToVK_TextureFormat[((VulkanTextureContainer *)depthStencilTargetInfo->texture)->header.info.format];
  6027. key.depthStencilTargetDescription.loadOp = depthStencilTargetInfo->load_op;
  6028. key.depthStencilTargetDescription.storeOp = depthStencilTargetInfo->store_op;
  6029. key.depthStencilTargetDescription.stencilLoadOp = depthStencilTargetInfo->stencil_load_op;
  6030. key.depthStencilTargetDescription.stencilStoreOp = depthStencilTargetInfo->stencil_store_op;
  6031. }
  6032. SDL_LockMutex(renderer->renderPassFetchLock);
  6033. bool result = SDL_FindInHashTable(
  6034. renderer->renderPassHashTable,
  6035. (const void *)&key,
  6036. (const void **)&renderPassWrapper);
  6037. if (result) {
  6038. SDL_UnlockMutex(renderer->renderPassFetchLock);
  6039. return renderPassWrapper->handle;
  6040. }
  6041. renderPassHandle = VULKAN_INTERNAL_CreateRenderPass(
  6042. renderer,
  6043. commandBuffer,
  6044. colorTargetInfos,
  6045. numColorTargets,
  6046. depthStencilTargetInfo);
  6047. if (renderPassHandle == VK_NULL_HANDLE) {
  6048. SDL_UnlockMutex(renderer->renderPassFetchLock);
  6049. return VK_NULL_HANDLE;
  6050. }
  6051. // Have to malloc the key to store it in the hashtable
  6052. RenderPassHashTableKey *allocedKey = SDL_malloc(sizeof(RenderPassHashTableKey));
  6053. SDL_memcpy(allocedKey, &key, sizeof(RenderPassHashTableKey));
  6054. renderPassWrapper = SDL_malloc(sizeof(VulkanRenderPassHashTableValue));
  6055. renderPassWrapper->handle = renderPassHandle;
  6056. SDL_InsertIntoHashTable(
  6057. renderer->renderPassHashTable,
  6058. (const void *)allocedKey,
  6059. (const void *)renderPassWrapper, true);
  6060. SDL_UnlockMutex(renderer->renderPassFetchLock);
  6061. return renderPassHandle;
  6062. }
  6063. static VulkanFramebuffer *VULKAN_INTERNAL_FetchFramebuffer(
  6064. VulkanRenderer *renderer,
  6065. VkRenderPass renderPass,
  6066. const SDL_GPUColorTargetInfo *colorTargetInfos,
  6067. Uint32 numColorTargets,
  6068. const SDL_GPUDepthStencilTargetInfo *depthStencilTargetInfo,
  6069. Uint32 width,
  6070. Uint32 height)
  6071. {
  6072. VulkanFramebuffer *vulkanFramebuffer = NULL;
  6073. VkFramebufferCreateInfo framebufferInfo;
  6074. VkResult result;
  6075. VkImageView imageViewAttachments[2 * MAX_COLOR_TARGET_BINDINGS + 1 /* depth */];
  6076. FramebufferHashTableKey key;
  6077. Uint32 attachmentCount = 0;
  6078. Uint32 i;
  6079. SDL_zero(imageViewAttachments);
  6080. SDL_zero(key);
  6081. key.numColorTargets = numColorTargets;
  6082. for (i = 0; i < numColorTargets; i += 1) {
  6083. VulkanTextureContainer *container = (VulkanTextureContainer *)colorTargetInfos[i].texture;
  6084. VulkanTextureSubresource *subresource = VULKAN_INTERNAL_FetchTextureSubresource(
  6085. container,
  6086. container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : colorTargetInfos[i].layer_or_depth_plane,
  6087. colorTargetInfos[i].mip_level);
  6088. Uint32 rtvIndex =
  6089. container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? colorTargetInfos[i].layer_or_depth_plane : 0;
  6090. key.colorAttachmentViews[i] = subresource->renderTargetViews[rtvIndex];
  6091. if (colorTargetInfos[i].resolve_texture != NULL) {
  6092. VulkanTextureContainer *resolveTextureContainer = (VulkanTextureContainer *)colorTargetInfos[i].resolve_texture;
  6093. VulkanTextureSubresource *resolveSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  6094. resolveTextureContainer,
  6095. colorTargetInfos[i].layer_or_depth_plane,
  6096. colorTargetInfos[i].mip_level);
  6097. key.resolveAttachmentViews[key.numResolveAttachments] = resolveSubresource->renderTargetViews[0];
  6098. key.numResolveAttachments += 1;
  6099. }
  6100. }
  6101. if (depthStencilTargetInfo == NULL) {
  6102. key.depthStencilAttachmentView = VK_NULL_HANDLE;
  6103. } else {
  6104. VulkanTextureSubresource *subresource = VULKAN_INTERNAL_FetchTextureSubresource(
  6105. (VulkanTextureContainer *)depthStencilTargetInfo->texture,
  6106. 0,
  6107. 0);
  6108. key.depthStencilAttachmentView = subresource->depthStencilView;
  6109. }
  6110. key.width = width;
  6111. key.height = height;
  6112. SDL_LockMutex(renderer->framebufferFetchLock);
  6113. bool findResult = SDL_FindInHashTable(
  6114. renderer->framebufferHashTable,
  6115. (const void *)&key,
  6116. (const void **)&vulkanFramebuffer);
  6117. if (findResult) {
  6118. SDL_UnlockMutex(renderer->framebufferFetchLock);
  6119. return vulkanFramebuffer;
  6120. }
  6121. vulkanFramebuffer = SDL_malloc(sizeof(VulkanFramebuffer));
  6122. SDL_SetAtomicInt(&vulkanFramebuffer->referenceCount, 0);
  6123. // Create a new framebuffer
  6124. for (i = 0; i < numColorTargets; i += 1) {
  6125. VulkanTextureContainer *container = (VulkanTextureContainer *)colorTargetInfos[i].texture;
  6126. VulkanTextureSubresource *subresource = VULKAN_INTERNAL_FetchTextureSubresource(
  6127. container,
  6128. container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : colorTargetInfos[i].layer_or_depth_plane,
  6129. colorTargetInfos[i].mip_level);
  6130. Uint32 rtvIndex =
  6131. container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? colorTargetInfos[i].layer_or_depth_plane : 0;
  6132. imageViewAttachments[attachmentCount] = subresource->renderTargetViews[rtvIndex];
  6133. attachmentCount += 1;
  6134. if (colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE || colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE_AND_STORE) {
  6135. VulkanTextureContainer *resolveContainer = (VulkanTextureContainer *)colorTargetInfos[i].resolve_texture;
  6136. VulkanTextureSubresource *resolveSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  6137. resolveContainer,
  6138. colorTargetInfos[i].resolve_layer,
  6139. colorTargetInfos[i].resolve_mip_level);
  6140. imageViewAttachments[attachmentCount] = resolveSubresource->renderTargetViews[0];
  6141. attachmentCount += 1;
  6142. }
  6143. }
  6144. if (depthStencilTargetInfo != NULL) {
  6145. VulkanTextureSubresource *subresource = VULKAN_INTERNAL_FetchTextureSubresource(
  6146. (VulkanTextureContainer *)depthStencilTargetInfo->texture,
  6147. 0,
  6148. 0);
  6149. imageViewAttachments[attachmentCount] = subresource->depthStencilView;
  6150. attachmentCount += 1;
  6151. }
  6152. framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  6153. framebufferInfo.pNext = NULL;
  6154. framebufferInfo.flags = 0;
  6155. framebufferInfo.renderPass = renderPass;
  6156. framebufferInfo.attachmentCount = attachmentCount;
  6157. framebufferInfo.pAttachments = imageViewAttachments;
  6158. framebufferInfo.width = key.width;
  6159. framebufferInfo.height = key.height;
  6160. framebufferInfo.layers = 1;
  6161. result = renderer->vkCreateFramebuffer(
  6162. renderer->logicalDevice,
  6163. &framebufferInfo,
  6164. NULL,
  6165. &vulkanFramebuffer->framebuffer);
  6166. if (result == VK_SUCCESS) {
  6167. // Have to malloc the key to store it in the hashtable
  6168. FramebufferHashTableKey *allocedKey = SDL_malloc(sizeof(FramebufferHashTableKey));
  6169. SDL_memcpy(allocedKey, &key, sizeof(FramebufferHashTableKey));
  6170. SDL_InsertIntoHashTable(
  6171. renderer->framebufferHashTable,
  6172. (const void *)allocedKey,
  6173. (const void *)vulkanFramebuffer, true);
  6174. } else {
  6175. SDL_free(vulkanFramebuffer);
  6176. SDL_UnlockMutex(renderer->framebufferFetchLock);
  6177. CHECK_VULKAN_ERROR_AND_RETURN(result, vkCreateFramebuffer, NULL);
  6178. }
  6179. SDL_UnlockMutex(renderer->framebufferFetchLock);
  6180. return vulkanFramebuffer;
  6181. }
  6182. static void VULKAN_INTERNAL_SetCurrentViewport(
  6183. VulkanCommandBuffer *commandBuffer,
  6184. const SDL_GPUViewport *viewport)
  6185. {
  6186. VulkanCommandBuffer *vulkanCommandBuffer = commandBuffer;
  6187. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6188. vulkanCommandBuffer->currentViewport.x = viewport->x;
  6189. vulkanCommandBuffer->currentViewport.width = viewport->w;
  6190. vulkanCommandBuffer->currentViewport.minDepth = viewport->min_depth;
  6191. vulkanCommandBuffer->currentViewport.maxDepth = viewport->max_depth;
  6192. // Viewport flip for consistency with other backends
  6193. vulkanCommandBuffer->currentViewport.y = viewport->y + viewport->h;
  6194. vulkanCommandBuffer->currentViewport.height = -viewport->h;
  6195. renderer->vkCmdSetViewport(
  6196. vulkanCommandBuffer->commandBuffer,
  6197. 0,
  6198. 1,
  6199. &vulkanCommandBuffer->currentViewport);
  6200. }
  6201. static void VULKAN_SetViewport(
  6202. SDL_GPUCommandBuffer *commandBuffer,
  6203. const SDL_GPUViewport *viewport)
  6204. {
  6205. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6206. VULKAN_INTERNAL_SetCurrentViewport(
  6207. vulkanCommandBuffer,
  6208. viewport);
  6209. }
  6210. static void VULKAN_INTERNAL_SetCurrentScissor(
  6211. VulkanCommandBuffer *vulkanCommandBuffer,
  6212. const SDL_Rect *scissor)
  6213. {
  6214. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6215. vulkanCommandBuffer->currentScissor.offset.x = scissor->x;
  6216. vulkanCommandBuffer->currentScissor.offset.y = scissor->y;
  6217. vulkanCommandBuffer->currentScissor.extent.width = scissor->w;
  6218. vulkanCommandBuffer->currentScissor.extent.height = scissor->h;
  6219. renderer->vkCmdSetScissor(
  6220. vulkanCommandBuffer->commandBuffer,
  6221. 0,
  6222. 1,
  6223. &vulkanCommandBuffer->currentScissor);
  6224. }
  6225. static void VULKAN_SetScissor(
  6226. SDL_GPUCommandBuffer *commandBuffer,
  6227. const SDL_Rect *scissor)
  6228. {
  6229. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6230. VULKAN_INTERNAL_SetCurrentScissor(
  6231. vulkanCommandBuffer,
  6232. scissor);
  6233. }
  6234. static void VULKAN_INTERNAL_SetCurrentBlendConstants(
  6235. VulkanCommandBuffer *vulkanCommandBuffer,
  6236. SDL_FColor blendConstants)
  6237. {
  6238. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6239. vulkanCommandBuffer->blendConstants[0] = blendConstants.r;
  6240. vulkanCommandBuffer->blendConstants[1] = blendConstants.g;
  6241. vulkanCommandBuffer->blendConstants[2] = blendConstants.b;
  6242. vulkanCommandBuffer->blendConstants[3] = blendConstants.a;
  6243. renderer->vkCmdSetBlendConstants(
  6244. vulkanCommandBuffer->commandBuffer,
  6245. vulkanCommandBuffer->blendConstants);
  6246. }
  6247. static void VULKAN_SetBlendConstants(
  6248. SDL_GPUCommandBuffer *commandBuffer,
  6249. SDL_FColor blendConstants)
  6250. {
  6251. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6252. VULKAN_INTERNAL_SetCurrentBlendConstants(
  6253. vulkanCommandBuffer,
  6254. blendConstants);
  6255. }
  6256. static void VULKAN_INTERNAL_SetCurrentStencilReference(
  6257. VulkanCommandBuffer *vulkanCommandBuffer,
  6258. Uint8 reference)
  6259. {
  6260. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6261. vulkanCommandBuffer->stencilRef = reference;
  6262. renderer->vkCmdSetStencilReference(
  6263. vulkanCommandBuffer->commandBuffer,
  6264. VK_STENCIL_FACE_FRONT_AND_BACK,
  6265. vulkanCommandBuffer->stencilRef);
  6266. }
  6267. static void VULKAN_SetStencilReference(
  6268. SDL_GPUCommandBuffer *commandBuffer,
  6269. Uint8 reference)
  6270. {
  6271. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6272. VULKAN_INTERNAL_SetCurrentStencilReference(
  6273. vulkanCommandBuffer,
  6274. reference);
  6275. }
  6276. static void VULKAN_BindVertexSamplers(
  6277. SDL_GPUCommandBuffer *commandBuffer,
  6278. Uint32 firstSlot,
  6279. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  6280. Uint32 numBindings)
  6281. {
  6282. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6283. for (Uint32 i = 0; i < numBindings; i += 1) {
  6284. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)textureSamplerBindings[i].texture;
  6285. VulkanSampler *sampler = (VulkanSampler *)textureSamplerBindings[i].sampler;
  6286. if (vulkanCommandBuffer->vertexSamplers[firstSlot + i] != sampler) {
  6287. VULKAN_INTERNAL_TrackSampler(
  6288. vulkanCommandBuffer,
  6289. (VulkanSampler *)textureSamplerBindings[i].sampler);
  6290. vulkanCommandBuffer->vertexSamplers[firstSlot + i] = (VulkanSampler *)textureSamplerBindings[i].sampler;
  6291. vulkanCommandBuffer->needNewVertexResourceDescriptorSet = true;
  6292. }
  6293. if (vulkanCommandBuffer->vertexSamplerTextures[firstSlot + i] != textureContainer->activeTexture) {
  6294. VULKAN_INTERNAL_TrackTexture(
  6295. vulkanCommandBuffer,
  6296. textureContainer->activeTexture);
  6297. vulkanCommandBuffer->vertexSamplerTextures[firstSlot + i] = textureContainer->activeTexture;
  6298. vulkanCommandBuffer->needNewVertexResourceDescriptorSet = true;
  6299. }
  6300. }
  6301. }
  6302. static void VULKAN_BindVertexStorageTextures(
  6303. SDL_GPUCommandBuffer *commandBuffer,
  6304. Uint32 firstSlot,
  6305. SDL_GPUTexture *const *storageTextures,
  6306. Uint32 numBindings)
  6307. {
  6308. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6309. for (Uint32 i = 0; i < numBindings; i += 1) {
  6310. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)storageTextures[i];
  6311. if (vulkanCommandBuffer->vertexStorageTextures[firstSlot + i] != textureContainer->activeTexture) {
  6312. VULKAN_INTERNAL_TrackTexture(
  6313. vulkanCommandBuffer,
  6314. textureContainer->activeTexture);
  6315. vulkanCommandBuffer->vertexStorageTextures[firstSlot + i] = textureContainer->activeTexture;
  6316. vulkanCommandBuffer->needNewVertexResourceDescriptorSet = true;
  6317. }
  6318. }
  6319. }
  6320. static void VULKAN_BindVertexStorageBuffers(
  6321. SDL_GPUCommandBuffer *commandBuffer,
  6322. Uint32 firstSlot,
  6323. SDL_GPUBuffer *const *storageBuffers,
  6324. Uint32 numBindings)
  6325. {
  6326. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6327. for (Uint32 i = 0; i < numBindings; i += 1) {
  6328. VulkanBufferContainer *bufferContainer = (VulkanBufferContainer *)storageBuffers[i];
  6329. if (vulkanCommandBuffer->vertexStorageBuffers[firstSlot + i] != bufferContainer->activeBuffer) {
  6330. VULKAN_INTERNAL_TrackBuffer(
  6331. vulkanCommandBuffer,
  6332. bufferContainer->activeBuffer);
  6333. vulkanCommandBuffer->vertexStorageBuffers[firstSlot + i] = bufferContainer->activeBuffer;
  6334. vulkanCommandBuffer->needNewVertexResourceDescriptorSet = true;
  6335. }
  6336. }
  6337. }
  6338. static void VULKAN_BindFragmentSamplers(
  6339. SDL_GPUCommandBuffer *commandBuffer,
  6340. Uint32 firstSlot,
  6341. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  6342. Uint32 numBindings)
  6343. {
  6344. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6345. for (Uint32 i = 0; i < numBindings; i += 1) {
  6346. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)textureSamplerBindings[i].texture;
  6347. VulkanSampler *sampler = (VulkanSampler *)textureSamplerBindings[i].sampler;
  6348. if (vulkanCommandBuffer->fragmentSamplers[firstSlot + i] != sampler) {
  6349. VULKAN_INTERNAL_TrackSampler(
  6350. vulkanCommandBuffer,
  6351. (VulkanSampler *)textureSamplerBindings[i].sampler);
  6352. vulkanCommandBuffer->fragmentSamplers[firstSlot + i] = (VulkanSampler *)textureSamplerBindings[i].sampler;
  6353. vulkanCommandBuffer->needNewFragmentResourceDescriptorSet = true;
  6354. }
  6355. if (vulkanCommandBuffer->fragmentSamplerTextures[firstSlot + i] != textureContainer->activeTexture) {
  6356. VULKAN_INTERNAL_TrackTexture(
  6357. vulkanCommandBuffer,
  6358. textureContainer->activeTexture);
  6359. vulkanCommandBuffer->fragmentSamplerTextures[firstSlot + i] = textureContainer->activeTexture;
  6360. vulkanCommandBuffer->needNewFragmentResourceDescriptorSet = true;
  6361. }
  6362. }
  6363. }
  6364. static void VULKAN_BindFragmentStorageTextures(
  6365. SDL_GPUCommandBuffer *commandBuffer,
  6366. Uint32 firstSlot,
  6367. SDL_GPUTexture *const *storageTextures,
  6368. Uint32 numBindings)
  6369. {
  6370. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6371. for (Uint32 i = 0; i < numBindings; i += 1) {
  6372. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)storageTextures[i];
  6373. if (vulkanCommandBuffer->fragmentStorageTextures[firstSlot + i] != textureContainer->activeTexture) {
  6374. VULKAN_INTERNAL_TrackTexture(
  6375. vulkanCommandBuffer,
  6376. textureContainer->activeTexture);
  6377. vulkanCommandBuffer->fragmentStorageTextures[firstSlot + i] = textureContainer->activeTexture;
  6378. vulkanCommandBuffer->needNewFragmentResourceDescriptorSet = true;
  6379. }
  6380. }
  6381. }
  6382. static void VULKAN_BindFragmentStorageBuffers(
  6383. SDL_GPUCommandBuffer *commandBuffer,
  6384. Uint32 firstSlot,
  6385. SDL_GPUBuffer *const *storageBuffers,
  6386. Uint32 numBindings)
  6387. {
  6388. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6389. VulkanBufferContainer *bufferContainer;
  6390. Uint32 i;
  6391. for (i = 0; i < numBindings; i += 1) {
  6392. bufferContainer = (VulkanBufferContainer *)storageBuffers[i];
  6393. if (vulkanCommandBuffer->fragmentStorageBuffers[firstSlot + i] != bufferContainer->activeBuffer) {
  6394. VULKAN_INTERNAL_TrackBuffer(
  6395. vulkanCommandBuffer,
  6396. bufferContainer->activeBuffer);
  6397. vulkanCommandBuffer->fragmentStorageBuffers[firstSlot + i] = bufferContainer->activeBuffer;
  6398. vulkanCommandBuffer->needNewFragmentResourceDescriptorSet = true;
  6399. }
  6400. }
  6401. }
  6402. static VulkanUniformBuffer *VULKAN_INTERNAL_AcquireUniformBufferFromPool(
  6403. VulkanCommandBuffer *commandBuffer)
  6404. {
  6405. VulkanRenderer *renderer = commandBuffer->renderer;
  6406. VulkanUniformBuffer *uniformBuffer;
  6407. SDL_LockMutex(renderer->acquireUniformBufferLock);
  6408. if (renderer->uniformBufferPoolCount > 0) {
  6409. uniformBuffer = renderer->uniformBufferPool[renderer->uniformBufferPoolCount - 1];
  6410. renderer->uniformBufferPoolCount -= 1;
  6411. } else {
  6412. uniformBuffer = VULKAN_INTERNAL_CreateUniformBuffer(
  6413. renderer,
  6414. UNIFORM_BUFFER_SIZE);
  6415. }
  6416. SDL_UnlockMutex(renderer->acquireUniformBufferLock);
  6417. VULKAN_INTERNAL_TrackUniformBuffer(commandBuffer, uniformBuffer);
  6418. return uniformBuffer;
  6419. }
  6420. static void VULKAN_INTERNAL_ReturnUniformBufferToPool(
  6421. VulkanRenderer *renderer,
  6422. VulkanUniformBuffer *uniformBuffer)
  6423. {
  6424. if (renderer->uniformBufferPoolCount >= renderer->uniformBufferPoolCapacity) {
  6425. renderer->uniformBufferPoolCapacity *= 2;
  6426. renderer->uniformBufferPool = SDL_realloc(
  6427. renderer->uniformBufferPool,
  6428. renderer->uniformBufferPoolCapacity * sizeof(VulkanUniformBuffer *));
  6429. }
  6430. renderer->uniformBufferPool[renderer->uniformBufferPoolCount] = uniformBuffer;
  6431. renderer->uniformBufferPoolCount += 1;
  6432. uniformBuffer->writeOffset = 0;
  6433. uniformBuffer->drawOffset = 0;
  6434. }
  6435. static void VULKAN_INTERNAL_PushUniformData(
  6436. VulkanCommandBuffer *commandBuffer,
  6437. VulkanUniformBufferStage uniformBufferStage,
  6438. Uint32 slotIndex,
  6439. const void *data,
  6440. Uint32 length)
  6441. {
  6442. Uint32 blockSize =
  6443. VULKAN_INTERNAL_NextHighestAlignment32(
  6444. length,
  6445. commandBuffer->renderer->minUBOAlignment);
  6446. VulkanUniformBuffer *uniformBuffer;
  6447. if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_VERTEX) {
  6448. if (commandBuffer->vertexUniformBuffers[slotIndex] == NULL) {
  6449. commandBuffer->vertexUniformBuffers[slotIndex] = VULKAN_INTERNAL_AcquireUniformBufferFromPool(
  6450. commandBuffer);
  6451. }
  6452. uniformBuffer = commandBuffer->vertexUniformBuffers[slotIndex];
  6453. } else if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_FRAGMENT) {
  6454. if (commandBuffer->fragmentUniformBuffers[slotIndex] == NULL) {
  6455. commandBuffer->fragmentUniformBuffers[slotIndex] = VULKAN_INTERNAL_AcquireUniformBufferFromPool(
  6456. commandBuffer);
  6457. }
  6458. uniformBuffer = commandBuffer->fragmentUniformBuffers[slotIndex];
  6459. } else if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_COMPUTE) {
  6460. if (commandBuffer->computeUniformBuffers[slotIndex] == NULL) {
  6461. commandBuffer->computeUniformBuffers[slotIndex] = VULKAN_INTERNAL_AcquireUniformBufferFromPool(
  6462. commandBuffer);
  6463. }
  6464. uniformBuffer = commandBuffer->computeUniformBuffers[slotIndex];
  6465. } else {
  6466. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  6467. return;
  6468. }
  6469. // If there is no more room, acquire a new uniform buffer
  6470. if (uniformBuffer->writeOffset + blockSize + MAX_UBO_SECTION_SIZE >= uniformBuffer->buffer->size) {
  6471. uniformBuffer = VULKAN_INTERNAL_AcquireUniformBufferFromPool(commandBuffer);
  6472. uniformBuffer->drawOffset = 0;
  6473. uniformBuffer->writeOffset = 0;
  6474. if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_VERTEX) {
  6475. commandBuffer->vertexUniformBuffers[slotIndex] = uniformBuffer;
  6476. commandBuffer->needNewVertexUniformDescriptorSet = true;
  6477. } else if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_FRAGMENT) {
  6478. commandBuffer->fragmentUniformBuffers[slotIndex] = uniformBuffer;
  6479. commandBuffer->needNewFragmentUniformDescriptorSet = true;
  6480. } else if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_COMPUTE) {
  6481. commandBuffer->computeUniformBuffers[slotIndex] = uniformBuffer;
  6482. commandBuffer->needNewComputeUniformDescriptorSet = true;
  6483. } else {
  6484. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  6485. return;
  6486. }
  6487. }
  6488. uniformBuffer->drawOffset = uniformBuffer->writeOffset;
  6489. Uint8 *dst =
  6490. uniformBuffer->buffer->usedRegion->allocation->mapPointer +
  6491. uniformBuffer->buffer->usedRegion->resourceOffset +
  6492. uniformBuffer->writeOffset;
  6493. SDL_memcpy(
  6494. dst,
  6495. data,
  6496. length);
  6497. uniformBuffer->writeOffset += blockSize;
  6498. if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_VERTEX) {
  6499. commandBuffer->needNewVertexUniformOffsets = true;
  6500. } else if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_FRAGMENT) {
  6501. commandBuffer->needNewFragmentUniformOffsets = true;
  6502. } else if (uniformBufferStage == VULKAN_UNIFORM_BUFFER_STAGE_COMPUTE) {
  6503. commandBuffer->needNewComputeUniformOffsets = true;
  6504. } else {
  6505. SDL_LogError(SDL_LOG_CATEGORY_GPU, "Unrecognized shader stage!");
  6506. return;
  6507. }
  6508. }
  6509. static void VULKAN_BeginRenderPass(
  6510. SDL_GPUCommandBuffer *commandBuffer,
  6511. const SDL_GPUColorTargetInfo *colorTargetInfos,
  6512. Uint32 numColorTargets,
  6513. const SDL_GPUDepthStencilTargetInfo *depthStencilTargetInfo)
  6514. {
  6515. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6516. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6517. VkRenderPass renderPass;
  6518. VulkanFramebuffer *framebuffer;
  6519. Uint32 w, h;
  6520. VkClearValue *clearValues;
  6521. Uint32 clearCount = 0;
  6522. Uint32 totalColorAttachmentCount = 0;
  6523. Uint32 i;
  6524. SDL_GPUViewport defaultViewport;
  6525. SDL_Rect defaultScissor;
  6526. SDL_FColor defaultBlendConstants;
  6527. Uint32 framebufferWidth = SDL_MAX_UINT32;
  6528. Uint32 framebufferHeight = SDL_MAX_UINT32;
  6529. for (i = 0; i < numColorTargets; i += 1) {
  6530. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)colorTargetInfos[i].texture;
  6531. w = textureContainer->header.info.width >> colorTargetInfos[i].mip_level;
  6532. h = textureContainer->header.info.height >> colorTargetInfos[i].mip_level;
  6533. // The framebuffer cannot be larger than the smallest attachment.
  6534. if (w < framebufferWidth) {
  6535. framebufferWidth = w;
  6536. }
  6537. if (h < framebufferHeight) {
  6538. framebufferHeight = h;
  6539. }
  6540. }
  6541. if (depthStencilTargetInfo != NULL) {
  6542. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)depthStencilTargetInfo->texture;
  6543. w = textureContainer->header.info.width;
  6544. h = textureContainer->header.info.height;
  6545. // The framebuffer cannot be larger than the smallest attachment.
  6546. if (w < framebufferWidth) {
  6547. framebufferWidth = w;
  6548. }
  6549. if (h < framebufferHeight) {
  6550. framebufferHeight = h;
  6551. }
  6552. }
  6553. for (i = 0; i < numColorTargets; i += 1) {
  6554. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)colorTargetInfos[i].texture;
  6555. VulkanTextureSubresource *subresource = VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  6556. renderer,
  6557. vulkanCommandBuffer,
  6558. textureContainer,
  6559. textureContainer->header.info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : colorTargetInfos[i].layer_or_depth_plane,
  6560. colorTargetInfos[i].mip_level,
  6561. colorTargetInfos[i].cycle,
  6562. VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT);
  6563. vulkanCommandBuffer->colorAttachmentSubresources[vulkanCommandBuffer->colorAttachmentSubresourceCount] = subresource;
  6564. vulkanCommandBuffer->colorAttachmentSubresourceCount += 1;
  6565. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, subresource->parent);
  6566. totalColorAttachmentCount += 1;
  6567. clearCount += 1;
  6568. if (colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE || colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE_AND_STORE) {
  6569. VulkanTextureContainer *resolveContainer = (VulkanTextureContainer *)colorTargetInfos[i].resolve_texture;
  6570. VulkanTextureSubresource *resolveSubresource = VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  6571. renderer,
  6572. vulkanCommandBuffer,
  6573. resolveContainer,
  6574. colorTargetInfos[i].resolve_layer,
  6575. colorTargetInfos[i].resolve_mip_level,
  6576. colorTargetInfos[i].cycle_resolve_texture,
  6577. VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT);
  6578. vulkanCommandBuffer->resolveAttachmentSubresources[vulkanCommandBuffer->resolveAttachmentSubresourceCount] = resolveSubresource;
  6579. vulkanCommandBuffer->resolveAttachmentSubresourceCount += 1;
  6580. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, resolveSubresource->parent);
  6581. totalColorAttachmentCount += 1;
  6582. clearCount += 1;
  6583. }
  6584. }
  6585. if (depthStencilTargetInfo != NULL) {
  6586. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)depthStencilTargetInfo->texture;
  6587. VulkanTextureSubresource *subresource = VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  6588. renderer,
  6589. vulkanCommandBuffer,
  6590. textureContainer,
  6591. 0,
  6592. 0,
  6593. depthStencilTargetInfo->cycle,
  6594. VULKAN_TEXTURE_USAGE_MODE_DEPTH_STENCIL_ATTACHMENT);
  6595. vulkanCommandBuffer->depthStencilAttachmentSubresource = subresource;
  6596. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, subresource->parent);
  6597. clearCount += 1;
  6598. }
  6599. // Fetch required render objects
  6600. renderPass = VULKAN_INTERNAL_FetchRenderPass(
  6601. renderer,
  6602. vulkanCommandBuffer,
  6603. colorTargetInfos,
  6604. numColorTargets,
  6605. depthStencilTargetInfo);
  6606. if (renderPass == VK_NULL_HANDLE) {
  6607. return;
  6608. }
  6609. framebuffer = VULKAN_INTERNAL_FetchFramebuffer(
  6610. renderer,
  6611. renderPass,
  6612. colorTargetInfos,
  6613. numColorTargets,
  6614. depthStencilTargetInfo,
  6615. framebufferWidth,
  6616. framebufferHeight);
  6617. if (framebuffer == NULL) {
  6618. return;
  6619. }
  6620. VULKAN_INTERNAL_TrackFramebuffer(renderer, vulkanCommandBuffer, framebuffer);
  6621. // Set clear values
  6622. clearValues = SDL_stack_alloc(VkClearValue, clearCount);
  6623. for (i = 0; i < totalColorAttachmentCount; i += 1) {
  6624. clearValues[i].color.float32[0] = colorTargetInfos[i].clear_color.r;
  6625. clearValues[i].color.float32[1] = colorTargetInfos[i].clear_color.g;
  6626. clearValues[i].color.float32[2] = colorTargetInfos[i].clear_color.b;
  6627. clearValues[i].color.float32[3] = colorTargetInfos[i].clear_color.a;
  6628. if (colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE || colorTargetInfos[i].store_op == SDL_GPU_STOREOP_RESOLVE_AND_STORE) {
  6629. // Skip over the resolve texture, we're not clearing it
  6630. i += 1;
  6631. }
  6632. }
  6633. if (depthStencilTargetInfo != NULL) {
  6634. clearValues[totalColorAttachmentCount].depthStencil.depth =
  6635. depthStencilTargetInfo->clear_depth;
  6636. clearValues[totalColorAttachmentCount].depthStencil.stencil =
  6637. depthStencilTargetInfo->clear_stencil;
  6638. }
  6639. VkRenderPassBeginInfo renderPassBeginInfo;
  6640. renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  6641. renderPassBeginInfo.pNext = NULL;
  6642. renderPassBeginInfo.renderPass = renderPass;
  6643. renderPassBeginInfo.framebuffer = framebuffer->framebuffer;
  6644. renderPassBeginInfo.pClearValues = clearValues;
  6645. renderPassBeginInfo.clearValueCount = clearCount;
  6646. renderPassBeginInfo.renderArea.extent.width = framebufferWidth;
  6647. renderPassBeginInfo.renderArea.extent.height = framebufferHeight;
  6648. renderPassBeginInfo.renderArea.offset.x = 0;
  6649. renderPassBeginInfo.renderArea.offset.y = 0;
  6650. renderer->vkCmdBeginRenderPass(
  6651. vulkanCommandBuffer->commandBuffer,
  6652. &renderPassBeginInfo,
  6653. VK_SUBPASS_CONTENTS_INLINE);
  6654. SDL_stack_free(clearValues);
  6655. // Set sensible default states
  6656. defaultViewport.x = 0;
  6657. defaultViewport.y = 0;
  6658. defaultViewport.w = (float)framebufferWidth;
  6659. defaultViewport.h = (float)framebufferHeight;
  6660. defaultViewport.min_depth = 0;
  6661. defaultViewport.max_depth = 1;
  6662. VULKAN_INTERNAL_SetCurrentViewport(
  6663. vulkanCommandBuffer,
  6664. &defaultViewport);
  6665. defaultScissor.x = 0;
  6666. defaultScissor.y = 0;
  6667. defaultScissor.w = (Sint32)framebufferWidth;
  6668. defaultScissor.h = (Sint32)framebufferHeight;
  6669. VULKAN_INTERNAL_SetCurrentScissor(
  6670. vulkanCommandBuffer,
  6671. &defaultScissor);
  6672. defaultBlendConstants.r = 1.0f;
  6673. defaultBlendConstants.g = 1.0f;
  6674. defaultBlendConstants.b = 1.0f;
  6675. defaultBlendConstants.a = 1.0f;
  6676. VULKAN_INTERNAL_SetCurrentBlendConstants(
  6677. vulkanCommandBuffer,
  6678. defaultBlendConstants);
  6679. VULKAN_INTERNAL_SetCurrentStencilReference(
  6680. vulkanCommandBuffer,
  6681. 0);
  6682. }
  6683. static void VULKAN_BindGraphicsPipeline(
  6684. SDL_GPUCommandBuffer *commandBuffer,
  6685. SDL_GPUGraphicsPipeline *graphicsPipeline)
  6686. {
  6687. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6688. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6689. VulkanGraphicsPipeline *pipeline = (VulkanGraphicsPipeline *)graphicsPipeline;
  6690. renderer->vkCmdBindPipeline(
  6691. vulkanCommandBuffer->commandBuffer,
  6692. VK_PIPELINE_BIND_POINT_GRAPHICS,
  6693. pipeline->pipeline);
  6694. vulkanCommandBuffer->currentGraphicsPipeline = pipeline;
  6695. VULKAN_INTERNAL_TrackGraphicsPipeline(vulkanCommandBuffer, pipeline);
  6696. // Acquire uniform buffers if necessary
  6697. for (Uint32 i = 0; i < pipeline->resourceLayout->vertexUniformBufferCount; i += 1) {
  6698. if (vulkanCommandBuffer->vertexUniformBuffers[i] == NULL) {
  6699. vulkanCommandBuffer->vertexUniformBuffers[i] = VULKAN_INTERNAL_AcquireUniformBufferFromPool(
  6700. vulkanCommandBuffer);
  6701. }
  6702. }
  6703. for (Uint32 i = 0; i < pipeline->resourceLayout->fragmentUniformBufferCount; i += 1) {
  6704. if (vulkanCommandBuffer->fragmentUniformBuffers[i] == NULL) {
  6705. vulkanCommandBuffer->fragmentUniformBuffers[i] = VULKAN_INTERNAL_AcquireUniformBufferFromPool(
  6706. vulkanCommandBuffer);
  6707. }
  6708. }
  6709. // Mark bindings as needed
  6710. vulkanCommandBuffer->needNewVertexResourceDescriptorSet = true;
  6711. vulkanCommandBuffer->needNewFragmentResourceDescriptorSet = true;
  6712. vulkanCommandBuffer->needNewVertexUniformDescriptorSet = true;
  6713. vulkanCommandBuffer->needNewFragmentUniformDescriptorSet = true;
  6714. vulkanCommandBuffer->needNewVertexUniformOffsets = true;
  6715. vulkanCommandBuffer->needNewFragmentUniformOffsets = true;
  6716. }
  6717. static void VULKAN_BindVertexBuffers(
  6718. SDL_GPUCommandBuffer *commandBuffer,
  6719. Uint32 firstSlot,
  6720. const SDL_GPUBufferBinding *bindings,
  6721. Uint32 numBindings)
  6722. {
  6723. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6724. for (Uint32 i = 0; i < numBindings; i += 1) {
  6725. VulkanBuffer *buffer = ((VulkanBufferContainer *)bindings[i].buffer)->activeBuffer;
  6726. if (vulkanCommandBuffer->vertexBuffers[firstSlot + i] != buffer->buffer || vulkanCommandBuffer->vertexBufferOffsets[firstSlot + i] != bindings[i].offset) {
  6727. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, buffer);
  6728. vulkanCommandBuffer->vertexBuffers[firstSlot + i] = buffer->buffer;
  6729. vulkanCommandBuffer->vertexBufferOffsets[firstSlot + i] = bindings[i].offset;
  6730. vulkanCommandBuffer->needVertexBufferBind = true;
  6731. }
  6732. }
  6733. vulkanCommandBuffer->vertexBufferCount =
  6734. SDL_max(vulkanCommandBuffer->vertexBufferCount, firstSlot + numBindings);
  6735. }
  6736. static void VULKAN_BindIndexBuffer(
  6737. SDL_GPUCommandBuffer *commandBuffer,
  6738. const SDL_GPUBufferBinding *binding,
  6739. SDL_GPUIndexElementSize indexElementSize)
  6740. {
  6741. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6742. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6743. VulkanBuffer *vulkanBuffer = ((VulkanBufferContainer *)binding->buffer)->activeBuffer;
  6744. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, vulkanBuffer);
  6745. renderer->vkCmdBindIndexBuffer(
  6746. vulkanCommandBuffer->commandBuffer,
  6747. vulkanBuffer->buffer,
  6748. (VkDeviceSize)binding->offset,
  6749. SDLToVK_IndexType[indexElementSize]);
  6750. }
  6751. static void VULKAN_PushVertexUniformData(
  6752. SDL_GPUCommandBuffer *commandBuffer,
  6753. Uint32 slotIndex,
  6754. const void *data,
  6755. Uint32 length)
  6756. {
  6757. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6758. VULKAN_INTERNAL_PushUniformData(
  6759. vulkanCommandBuffer,
  6760. VULKAN_UNIFORM_BUFFER_STAGE_VERTEX,
  6761. slotIndex,
  6762. data,
  6763. length);
  6764. }
  6765. static void VULKAN_PushFragmentUniformData(
  6766. SDL_GPUCommandBuffer *commandBuffer,
  6767. Uint32 slotIndex,
  6768. const void *data,
  6769. Uint32 length)
  6770. {
  6771. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6772. VULKAN_INTERNAL_PushUniformData(
  6773. vulkanCommandBuffer,
  6774. VULKAN_UNIFORM_BUFFER_STAGE_FRAGMENT,
  6775. slotIndex,
  6776. data,
  6777. length);
  6778. }
  6779. static void VULKAN_EndRenderPass(
  6780. SDL_GPUCommandBuffer *commandBuffer)
  6781. {
  6782. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6783. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6784. Uint32 i;
  6785. renderer->vkCmdEndRenderPass(
  6786. vulkanCommandBuffer->commandBuffer);
  6787. for (i = 0; i < vulkanCommandBuffer->colorAttachmentSubresourceCount; i += 1) {
  6788. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  6789. renderer,
  6790. vulkanCommandBuffer,
  6791. VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT,
  6792. vulkanCommandBuffer->colorAttachmentSubresources[i]);
  6793. }
  6794. vulkanCommandBuffer->colorAttachmentSubresourceCount = 0;
  6795. for (i = 0; i < vulkanCommandBuffer->resolveAttachmentSubresourceCount; i += 1) {
  6796. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  6797. renderer,
  6798. vulkanCommandBuffer,
  6799. VULKAN_TEXTURE_USAGE_MODE_COLOR_ATTACHMENT,
  6800. vulkanCommandBuffer->resolveAttachmentSubresources[i]);
  6801. }
  6802. vulkanCommandBuffer->resolveAttachmentSubresourceCount = 0;
  6803. if (vulkanCommandBuffer->depthStencilAttachmentSubresource != NULL) {
  6804. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  6805. renderer,
  6806. vulkanCommandBuffer,
  6807. VULKAN_TEXTURE_USAGE_MODE_DEPTH_STENCIL_ATTACHMENT,
  6808. vulkanCommandBuffer->depthStencilAttachmentSubresource);
  6809. vulkanCommandBuffer->depthStencilAttachmentSubresource = NULL;
  6810. }
  6811. vulkanCommandBuffer->currentGraphicsPipeline = NULL;
  6812. vulkanCommandBuffer->vertexResourceDescriptorSet = VK_NULL_HANDLE;
  6813. vulkanCommandBuffer->vertexUniformDescriptorSet = VK_NULL_HANDLE;
  6814. vulkanCommandBuffer->fragmentResourceDescriptorSet = VK_NULL_HANDLE;
  6815. vulkanCommandBuffer->fragmentUniformDescriptorSet = VK_NULL_HANDLE;
  6816. // Reset bind state
  6817. SDL_zeroa(vulkanCommandBuffer->colorAttachmentSubresources);
  6818. SDL_zeroa(vulkanCommandBuffer->resolveAttachmentSubresources);
  6819. vulkanCommandBuffer->depthStencilAttachmentSubresource = NULL;
  6820. SDL_zeroa(vulkanCommandBuffer->vertexBuffers);
  6821. SDL_zeroa(vulkanCommandBuffer->vertexBufferOffsets);
  6822. vulkanCommandBuffer->vertexBufferCount = 0;
  6823. SDL_zeroa(vulkanCommandBuffer->vertexSamplers);
  6824. SDL_zeroa(vulkanCommandBuffer->vertexSamplerTextures);
  6825. SDL_zeroa(vulkanCommandBuffer->vertexStorageTextures);
  6826. SDL_zeroa(vulkanCommandBuffer->vertexStorageBuffers);
  6827. SDL_zeroa(vulkanCommandBuffer->fragmentSamplers);
  6828. SDL_zeroa(vulkanCommandBuffer->fragmentSamplerTextures);
  6829. SDL_zeroa(vulkanCommandBuffer->fragmentStorageTextures);
  6830. SDL_zeroa(vulkanCommandBuffer->fragmentStorageBuffers);
  6831. }
  6832. static void VULKAN_BeginComputePass(
  6833. SDL_GPUCommandBuffer *commandBuffer,
  6834. const SDL_GPUStorageTextureReadWriteBinding *storageTextureBindings,
  6835. Uint32 numStorageTextureBindings,
  6836. const SDL_GPUStorageBufferReadWriteBinding *storageBufferBindings,
  6837. Uint32 numStorageBufferBindings)
  6838. {
  6839. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6840. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6841. VulkanBufferContainer *bufferContainer;
  6842. VulkanBuffer *buffer;
  6843. Uint32 i;
  6844. vulkanCommandBuffer->readWriteComputeStorageTextureSubresourceCount = numStorageTextureBindings;
  6845. for (i = 0; i < numStorageTextureBindings; i += 1) {
  6846. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)storageTextureBindings[i].texture;
  6847. VulkanTextureSubresource *subresource = VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  6848. renderer,
  6849. vulkanCommandBuffer,
  6850. textureContainer,
  6851. storageTextureBindings[i].layer,
  6852. storageTextureBindings[i].mip_level,
  6853. storageTextureBindings[i].cycle,
  6854. VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE);
  6855. vulkanCommandBuffer->readWriteComputeStorageTextureSubresources[i] = subresource;
  6856. VULKAN_INTERNAL_TrackTexture(
  6857. vulkanCommandBuffer,
  6858. subresource->parent);
  6859. }
  6860. for (i = 0; i < numStorageBufferBindings; i += 1) {
  6861. bufferContainer = (VulkanBufferContainer *)storageBufferBindings[i].buffer;
  6862. buffer = VULKAN_INTERNAL_PrepareBufferForWrite(
  6863. renderer,
  6864. vulkanCommandBuffer,
  6865. bufferContainer,
  6866. storageBufferBindings[i].cycle,
  6867. VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE);
  6868. vulkanCommandBuffer->readWriteComputeStorageBuffers[i] = buffer;
  6869. VULKAN_INTERNAL_TrackBuffer(
  6870. vulkanCommandBuffer,
  6871. buffer);
  6872. }
  6873. }
  6874. static void VULKAN_BindComputePipeline(
  6875. SDL_GPUCommandBuffer *commandBuffer,
  6876. SDL_GPUComputePipeline *computePipeline)
  6877. {
  6878. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6879. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6880. VulkanComputePipeline *vulkanComputePipeline = (VulkanComputePipeline *)computePipeline;
  6881. renderer->vkCmdBindPipeline(
  6882. vulkanCommandBuffer->commandBuffer,
  6883. VK_PIPELINE_BIND_POINT_COMPUTE,
  6884. vulkanComputePipeline->pipeline);
  6885. vulkanCommandBuffer->currentComputePipeline = vulkanComputePipeline;
  6886. VULKAN_INTERNAL_TrackComputePipeline(vulkanCommandBuffer, vulkanComputePipeline);
  6887. // Acquire uniform buffers if necessary
  6888. for (Uint32 i = 0; i < vulkanComputePipeline->resourceLayout->numUniformBuffers; i += 1) {
  6889. if (vulkanCommandBuffer->computeUniformBuffers[i] == NULL) {
  6890. vulkanCommandBuffer->computeUniformBuffers[i] = VULKAN_INTERNAL_AcquireUniformBufferFromPool(
  6891. vulkanCommandBuffer);
  6892. }
  6893. }
  6894. // Mark binding as needed
  6895. vulkanCommandBuffer->needNewComputeReadWriteDescriptorSet = true;
  6896. vulkanCommandBuffer->needNewComputeReadOnlyDescriptorSet = true;
  6897. vulkanCommandBuffer->needNewComputeUniformDescriptorSet = true;
  6898. vulkanCommandBuffer->needNewComputeUniformOffsets = true;
  6899. }
  6900. static void VULKAN_BindComputeSamplers(
  6901. SDL_GPUCommandBuffer *commandBuffer,
  6902. Uint32 firstSlot,
  6903. const SDL_GPUTextureSamplerBinding *textureSamplerBindings,
  6904. Uint32 numBindings)
  6905. {
  6906. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6907. for (Uint32 i = 0; i < numBindings; i += 1) {
  6908. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)textureSamplerBindings[i].texture;
  6909. VulkanSampler *sampler = (VulkanSampler *)textureSamplerBindings[i].sampler;
  6910. if (vulkanCommandBuffer->computeSamplers[firstSlot + i] != sampler) {
  6911. VULKAN_INTERNAL_TrackSampler(
  6912. vulkanCommandBuffer,
  6913. sampler);
  6914. vulkanCommandBuffer->computeSamplers[firstSlot + i] = sampler;
  6915. vulkanCommandBuffer->needNewComputeReadOnlyDescriptorSet = true;
  6916. }
  6917. if (vulkanCommandBuffer->computeSamplerTextures[firstSlot + i] != textureContainer->activeTexture) {
  6918. VULKAN_INTERNAL_TrackTexture(
  6919. vulkanCommandBuffer,
  6920. textureContainer->activeTexture);
  6921. vulkanCommandBuffer->computeSamplerTextures[firstSlot + i] = textureContainer->activeTexture;
  6922. vulkanCommandBuffer->needNewComputeReadOnlyDescriptorSet = true;
  6923. }
  6924. }
  6925. }
  6926. static void VULKAN_BindComputeStorageTextures(
  6927. SDL_GPUCommandBuffer *commandBuffer,
  6928. Uint32 firstSlot,
  6929. SDL_GPUTexture *const *storageTextures,
  6930. Uint32 numBindings)
  6931. {
  6932. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6933. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6934. for (Uint32 i = 0; i < numBindings; i += 1) {
  6935. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)storageTextures[i];
  6936. if (vulkanCommandBuffer->readOnlyComputeStorageTextures[firstSlot + i] != textureContainer->activeTexture) {
  6937. /* If a different texture as in this slot, transition it back to its default usage */
  6938. if (vulkanCommandBuffer->readOnlyComputeStorageTextures[firstSlot + i] != NULL) {
  6939. VULKAN_INTERNAL_TextureTransitionToDefaultUsage(
  6940. renderer,
  6941. vulkanCommandBuffer,
  6942. VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ,
  6943. vulkanCommandBuffer->readOnlyComputeStorageTextures[firstSlot + i]);
  6944. }
  6945. /* Then transition the new texture and prepare it for binding */
  6946. VULKAN_INTERNAL_TextureTransitionFromDefaultUsage(
  6947. renderer,
  6948. vulkanCommandBuffer,
  6949. VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ,
  6950. textureContainer->activeTexture);
  6951. VULKAN_INTERNAL_TrackTexture(
  6952. vulkanCommandBuffer,
  6953. textureContainer->activeTexture);
  6954. vulkanCommandBuffer->readOnlyComputeStorageTextures[firstSlot + i] = textureContainer->activeTexture;
  6955. vulkanCommandBuffer->needNewComputeReadOnlyDescriptorSet = true;
  6956. }
  6957. }
  6958. }
  6959. static void VULKAN_BindComputeStorageBuffers(
  6960. SDL_GPUCommandBuffer *commandBuffer,
  6961. Uint32 firstSlot,
  6962. SDL_GPUBuffer *const *storageBuffers,
  6963. Uint32 numBindings)
  6964. {
  6965. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6966. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  6967. for (Uint32 i = 0; i < numBindings; i += 1) {
  6968. VulkanBufferContainer *bufferContainer = (VulkanBufferContainer *)storageBuffers[i];
  6969. if (vulkanCommandBuffer->readOnlyComputeStorageBuffers[firstSlot + i] != bufferContainer->activeBuffer) {
  6970. /* If a different buffer was in this slot, transition it back to its default usage */
  6971. if (vulkanCommandBuffer->readOnlyComputeStorageBuffers[firstSlot + i] != NULL) {
  6972. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  6973. renderer,
  6974. vulkanCommandBuffer,
  6975. VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ,
  6976. vulkanCommandBuffer->readOnlyComputeStorageBuffers[firstSlot + i]);
  6977. }
  6978. /* Then transition the new buffer and prepare it for binding */
  6979. VULKAN_INTERNAL_BufferTransitionFromDefaultUsage(
  6980. renderer,
  6981. vulkanCommandBuffer,
  6982. VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ,
  6983. bufferContainer->activeBuffer);
  6984. VULKAN_INTERNAL_TrackBuffer(
  6985. vulkanCommandBuffer,
  6986. bufferContainer->activeBuffer);
  6987. vulkanCommandBuffer->readOnlyComputeStorageBuffers[firstSlot + i] = bufferContainer->activeBuffer;
  6988. vulkanCommandBuffer->needNewComputeReadOnlyDescriptorSet = true;
  6989. }
  6990. }
  6991. }
  6992. static void VULKAN_PushComputeUniformData(
  6993. SDL_GPUCommandBuffer *commandBuffer,
  6994. Uint32 slotIndex,
  6995. const void *data,
  6996. Uint32 length)
  6997. {
  6998. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  6999. VULKAN_INTERNAL_PushUniformData(
  7000. vulkanCommandBuffer,
  7001. VULKAN_UNIFORM_BUFFER_STAGE_COMPUTE,
  7002. slotIndex,
  7003. data,
  7004. length);
  7005. }
  7006. static void VULKAN_INTERNAL_BindComputeDescriptorSets(
  7007. VulkanRenderer *renderer,
  7008. VulkanCommandBuffer *commandBuffer)
  7009. {
  7010. VulkanComputePipelineResourceLayout *resourceLayout;
  7011. DescriptorSetLayout *descriptorSetLayout;
  7012. VkWriteDescriptorSet writeDescriptorSets[
  7013. MAX_TEXTURE_SAMPLERS_PER_STAGE +
  7014. MAX_STORAGE_TEXTURES_PER_STAGE +
  7015. MAX_STORAGE_BUFFERS_PER_STAGE +
  7016. MAX_COMPUTE_WRITE_TEXTURES +
  7017. MAX_COMPUTE_WRITE_BUFFERS +
  7018. MAX_UNIFORM_BUFFERS_PER_STAGE];
  7019. VkDescriptorBufferInfo bufferInfos[MAX_STORAGE_BUFFERS_PER_STAGE + MAX_COMPUTE_WRITE_BUFFERS + MAX_UNIFORM_BUFFERS_PER_STAGE];
  7020. VkDescriptorImageInfo imageInfos[MAX_TEXTURE_SAMPLERS_PER_STAGE + MAX_STORAGE_TEXTURES_PER_STAGE + MAX_COMPUTE_WRITE_TEXTURES];
  7021. Uint32 dynamicOffsets[MAX_UNIFORM_BUFFERS_PER_STAGE];
  7022. Uint32 writeCount = 0;
  7023. Uint32 bufferInfoCount = 0;
  7024. Uint32 imageInfoCount = 0;
  7025. Uint32 dynamicOffsetCount = 0;
  7026. if (
  7027. !commandBuffer->needNewComputeReadOnlyDescriptorSet &&
  7028. !commandBuffer->needNewComputeReadWriteDescriptorSet &&
  7029. !commandBuffer->needNewComputeUniformDescriptorSet &&
  7030. !commandBuffer->needNewComputeUniformOffsets
  7031. ) {
  7032. return;
  7033. }
  7034. resourceLayout = commandBuffer->currentComputePipeline->resourceLayout;
  7035. if (commandBuffer->needNewComputeReadOnlyDescriptorSet) {
  7036. descriptorSetLayout = resourceLayout->descriptorSetLayouts[0];
  7037. commandBuffer->computeReadOnlyDescriptorSet = VULKAN_INTERNAL_FetchDescriptorSet(
  7038. renderer,
  7039. commandBuffer,
  7040. descriptorSetLayout);
  7041. for (Uint32 i = 0; i < resourceLayout->numSamplers; i += 1) {
  7042. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  7043. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  7044. currentWriteDescriptorSet->pNext = NULL;
  7045. currentWriteDescriptorSet->descriptorCount = 1;
  7046. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  7047. currentWriteDescriptorSet->dstArrayElement = 0;
  7048. currentWriteDescriptorSet->dstBinding = i;
  7049. currentWriteDescriptorSet->dstSet = commandBuffer->computeReadOnlyDescriptorSet;
  7050. currentWriteDescriptorSet->pTexelBufferView = NULL;
  7051. currentWriteDescriptorSet->pBufferInfo = NULL;
  7052. imageInfos[imageInfoCount].sampler = commandBuffer->computeSamplers[i]->sampler;
  7053. imageInfos[imageInfoCount].imageView = commandBuffer->computeSamplerTextures[i]->fullView;
  7054. imageInfos[imageInfoCount].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  7055. currentWriteDescriptorSet->pImageInfo = &imageInfos[imageInfoCount];
  7056. writeCount += 1;
  7057. imageInfoCount += 1;
  7058. }
  7059. for (Uint32 i = 0; i < resourceLayout->numReadonlyStorageTextures; i += 1) {
  7060. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  7061. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  7062. currentWriteDescriptorSet->pNext = NULL;
  7063. currentWriteDescriptorSet->descriptorCount = 1;
  7064. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; // Yes, we are declaring the readonly storage texture as a sampled image, because shaders are stupid.
  7065. currentWriteDescriptorSet->dstArrayElement = 0;
  7066. currentWriteDescriptorSet->dstBinding = resourceLayout->numSamplers + i;
  7067. currentWriteDescriptorSet->dstSet = commandBuffer->computeReadOnlyDescriptorSet;
  7068. currentWriteDescriptorSet->pTexelBufferView = NULL;
  7069. currentWriteDescriptorSet->pBufferInfo = NULL;
  7070. imageInfos[imageInfoCount].sampler = VK_NULL_HANDLE;
  7071. imageInfos[imageInfoCount].imageView = commandBuffer->readOnlyComputeStorageTextures[i]->fullView;
  7072. imageInfos[imageInfoCount].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
  7073. currentWriteDescriptorSet->pImageInfo = &imageInfos[imageInfoCount];
  7074. writeCount += 1;
  7075. imageInfoCount += 1;
  7076. }
  7077. for (Uint32 i = 0; i < resourceLayout->numReadonlyStorageBuffers; i += 1) {
  7078. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  7079. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  7080. currentWriteDescriptorSet->pNext = NULL;
  7081. currentWriteDescriptorSet->descriptorCount = 1;
  7082. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  7083. currentWriteDescriptorSet->dstArrayElement = 0;
  7084. currentWriteDescriptorSet->dstBinding = resourceLayout->numSamplers + resourceLayout->numReadonlyStorageTextures + i;
  7085. currentWriteDescriptorSet->dstSet = commandBuffer->computeReadOnlyDescriptorSet;
  7086. currentWriteDescriptorSet->pTexelBufferView = NULL;
  7087. currentWriteDescriptorSet->pImageInfo = NULL;
  7088. bufferInfos[bufferInfoCount].buffer = commandBuffer->readOnlyComputeStorageBuffers[i]->buffer;
  7089. bufferInfos[bufferInfoCount].offset = 0;
  7090. bufferInfos[bufferInfoCount].range = VK_WHOLE_SIZE;
  7091. currentWriteDescriptorSet->pBufferInfo = &bufferInfos[bufferInfoCount];
  7092. writeCount += 1;
  7093. bufferInfoCount += 1;
  7094. }
  7095. commandBuffer->needNewComputeReadOnlyDescriptorSet = false;
  7096. }
  7097. if (commandBuffer->needNewComputeReadWriteDescriptorSet) {
  7098. descriptorSetLayout = resourceLayout->descriptorSetLayouts[1];
  7099. commandBuffer->computeReadWriteDescriptorSet = VULKAN_INTERNAL_FetchDescriptorSet(
  7100. renderer,
  7101. commandBuffer,
  7102. descriptorSetLayout);
  7103. for (Uint32 i = 0; i < resourceLayout->numReadWriteStorageTextures; i += 1) {
  7104. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  7105. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  7106. currentWriteDescriptorSet->pNext = NULL;
  7107. currentWriteDescriptorSet->descriptorCount = 1;
  7108. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
  7109. currentWriteDescriptorSet->dstArrayElement = 0;
  7110. currentWriteDescriptorSet->dstBinding = i;
  7111. currentWriteDescriptorSet->dstSet = commandBuffer->computeReadWriteDescriptorSet;
  7112. currentWriteDescriptorSet->pTexelBufferView = NULL;
  7113. currentWriteDescriptorSet->pBufferInfo = NULL;
  7114. imageInfos[imageInfoCount].sampler = VK_NULL_HANDLE;
  7115. imageInfos[imageInfoCount].imageView = commandBuffer->readWriteComputeStorageTextureSubresources[i]->computeWriteView;
  7116. imageInfos[imageInfoCount].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
  7117. currentWriteDescriptorSet->pImageInfo = &imageInfos[imageInfoCount];
  7118. writeCount += 1;
  7119. imageInfoCount += 1;
  7120. }
  7121. for (Uint32 i = 0; i < resourceLayout->numReadWriteStorageBuffers; i += 1) {
  7122. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  7123. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  7124. currentWriteDescriptorSet->pNext = NULL;
  7125. currentWriteDescriptorSet->descriptorCount = 1;
  7126. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  7127. currentWriteDescriptorSet->dstArrayElement = 0;
  7128. currentWriteDescriptorSet->dstBinding = resourceLayout->numReadWriteStorageTextures + i;
  7129. currentWriteDescriptorSet->dstSet = commandBuffer->computeReadWriteDescriptorSet;
  7130. currentWriteDescriptorSet->pTexelBufferView = NULL;
  7131. currentWriteDescriptorSet->pImageInfo = NULL;
  7132. bufferInfos[bufferInfoCount].buffer = commandBuffer->readWriteComputeStorageBuffers[i]->buffer;
  7133. bufferInfos[bufferInfoCount].offset = 0;
  7134. bufferInfos[bufferInfoCount].range = VK_WHOLE_SIZE;
  7135. currentWriteDescriptorSet->pBufferInfo = &bufferInfos[bufferInfoCount];
  7136. writeCount += 1;
  7137. bufferInfoCount += 1;
  7138. }
  7139. commandBuffer->needNewComputeReadWriteDescriptorSet = false;
  7140. }
  7141. if (commandBuffer->needNewComputeUniformDescriptorSet) {
  7142. descriptorSetLayout = resourceLayout->descriptorSetLayouts[2];
  7143. commandBuffer->computeUniformDescriptorSet = VULKAN_INTERNAL_FetchDescriptorSet(
  7144. renderer,
  7145. commandBuffer,
  7146. descriptorSetLayout);
  7147. for (Uint32 i = 0; i < resourceLayout->numUniformBuffers; i += 1) {
  7148. VkWriteDescriptorSet *currentWriteDescriptorSet = &writeDescriptorSets[writeCount];
  7149. currentWriteDescriptorSet->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  7150. currentWriteDescriptorSet->pNext = NULL;
  7151. currentWriteDescriptorSet->descriptorCount = 1;
  7152. currentWriteDescriptorSet->descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
  7153. currentWriteDescriptorSet->dstArrayElement = 0;
  7154. currentWriteDescriptorSet->dstBinding = i;
  7155. currentWriteDescriptorSet->dstSet = commandBuffer->computeUniformDescriptorSet;
  7156. currentWriteDescriptorSet->pTexelBufferView = NULL;
  7157. currentWriteDescriptorSet->pImageInfo = NULL;
  7158. bufferInfos[bufferInfoCount].buffer = commandBuffer->computeUniformBuffers[i]->buffer->buffer;
  7159. bufferInfos[bufferInfoCount].offset = 0;
  7160. bufferInfos[bufferInfoCount].range = MAX_UBO_SECTION_SIZE;
  7161. currentWriteDescriptorSet->pBufferInfo = &bufferInfos[bufferInfoCount];
  7162. writeCount += 1;
  7163. bufferInfoCount += 1;
  7164. }
  7165. commandBuffer->needNewComputeUniformDescriptorSet = false;
  7166. }
  7167. for (Uint32 i = 0; i < resourceLayout->numUniformBuffers; i += 1) {
  7168. dynamicOffsets[i] = commandBuffer->computeUniformBuffers[i]->drawOffset;
  7169. dynamicOffsetCount += 1;
  7170. }
  7171. renderer->vkUpdateDescriptorSets(
  7172. renderer->logicalDevice,
  7173. writeCount,
  7174. writeDescriptorSets,
  7175. 0,
  7176. NULL);
  7177. VkDescriptorSet sets[3];
  7178. sets[0] = commandBuffer->computeReadOnlyDescriptorSet;
  7179. sets[1] = commandBuffer->computeReadWriteDescriptorSet;
  7180. sets[2] = commandBuffer->computeUniformDescriptorSet;
  7181. renderer->vkCmdBindDescriptorSets(
  7182. commandBuffer->commandBuffer,
  7183. VK_PIPELINE_BIND_POINT_COMPUTE,
  7184. resourceLayout->pipelineLayout,
  7185. 0,
  7186. 3,
  7187. sets,
  7188. dynamicOffsetCount,
  7189. dynamicOffsets);
  7190. commandBuffer->needNewVertexUniformOffsets = false;
  7191. }
  7192. static void VULKAN_DispatchCompute(
  7193. SDL_GPUCommandBuffer *commandBuffer,
  7194. Uint32 groupcountX,
  7195. Uint32 groupcountY,
  7196. Uint32 groupcountZ)
  7197. {
  7198. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7199. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7200. VULKAN_INTERNAL_BindComputeDescriptorSets(renderer, vulkanCommandBuffer);
  7201. renderer->vkCmdDispatch(
  7202. vulkanCommandBuffer->commandBuffer,
  7203. groupcountX,
  7204. groupcountY,
  7205. groupcountZ);
  7206. }
  7207. static void VULKAN_DispatchComputeIndirect(
  7208. SDL_GPUCommandBuffer *commandBuffer,
  7209. SDL_GPUBuffer *buffer,
  7210. Uint32 offset)
  7211. {
  7212. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7213. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7214. VulkanBuffer *vulkanBuffer = ((VulkanBufferContainer *)buffer)->activeBuffer;
  7215. VULKAN_INTERNAL_BindComputeDescriptorSets(renderer, vulkanCommandBuffer);
  7216. renderer->vkCmdDispatchIndirect(
  7217. vulkanCommandBuffer->commandBuffer,
  7218. vulkanBuffer->buffer,
  7219. offset);
  7220. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, vulkanBuffer);
  7221. }
  7222. static void VULKAN_EndComputePass(
  7223. SDL_GPUCommandBuffer *commandBuffer)
  7224. {
  7225. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7226. Uint32 i;
  7227. for (i = 0; i < vulkanCommandBuffer->readWriteComputeStorageTextureSubresourceCount; i += 1) {
  7228. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7229. vulkanCommandBuffer->renderer,
  7230. vulkanCommandBuffer,
  7231. VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE,
  7232. vulkanCommandBuffer->readWriteComputeStorageTextureSubresources[i]);
  7233. vulkanCommandBuffer->readWriteComputeStorageTextureSubresources[i] = NULL;
  7234. }
  7235. vulkanCommandBuffer->readWriteComputeStorageTextureSubresourceCount = 0;
  7236. for (i = 0; i < MAX_COMPUTE_WRITE_BUFFERS; i += 1) {
  7237. if (vulkanCommandBuffer->readWriteComputeStorageBuffers[i] != NULL) {
  7238. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  7239. vulkanCommandBuffer->renderer,
  7240. vulkanCommandBuffer,
  7241. VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ_WRITE,
  7242. vulkanCommandBuffer->readWriteComputeStorageBuffers[i]);
  7243. vulkanCommandBuffer->readWriteComputeStorageBuffers[i] = NULL;
  7244. }
  7245. }
  7246. for (i = 0; i < MAX_STORAGE_TEXTURES_PER_STAGE; i += 1) {
  7247. if (vulkanCommandBuffer->readOnlyComputeStorageTextures[i] != NULL) {
  7248. VULKAN_INTERNAL_TextureTransitionToDefaultUsage(
  7249. vulkanCommandBuffer->renderer,
  7250. vulkanCommandBuffer,
  7251. VULKAN_TEXTURE_USAGE_MODE_COMPUTE_STORAGE_READ,
  7252. vulkanCommandBuffer->readOnlyComputeStorageTextures[i]);
  7253. vulkanCommandBuffer->readOnlyComputeStorageTextures[i] = NULL;
  7254. }
  7255. }
  7256. for (i = 0; i < MAX_STORAGE_BUFFERS_PER_STAGE; i += 1) {
  7257. if (vulkanCommandBuffer->readOnlyComputeStorageBuffers[i] != NULL) {
  7258. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  7259. vulkanCommandBuffer->renderer,
  7260. vulkanCommandBuffer,
  7261. VULKAN_BUFFER_USAGE_MODE_COMPUTE_STORAGE_READ,
  7262. vulkanCommandBuffer->readOnlyComputeStorageBuffers[i]);
  7263. vulkanCommandBuffer->readOnlyComputeStorageBuffers[i] = NULL;
  7264. }
  7265. }
  7266. // we don't need a barrier because sampler state is always the default if sampler bit is set
  7267. SDL_zeroa(vulkanCommandBuffer->computeSamplerTextures);
  7268. SDL_zeroa(vulkanCommandBuffer->computeSamplers);
  7269. vulkanCommandBuffer->currentComputePipeline = NULL;
  7270. vulkanCommandBuffer->computeReadOnlyDescriptorSet = VK_NULL_HANDLE;
  7271. vulkanCommandBuffer->computeReadWriteDescriptorSet = VK_NULL_HANDLE;
  7272. vulkanCommandBuffer->computeUniformDescriptorSet = VK_NULL_HANDLE;
  7273. }
  7274. static void *VULKAN_MapTransferBuffer(
  7275. SDL_GPURenderer *driverData,
  7276. SDL_GPUTransferBuffer *transferBuffer,
  7277. bool cycle)
  7278. {
  7279. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  7280. VulkanBufferContainer *transferBufferContainer = (VulkanBufferContainer *)transferBuffer;
  7281. if (
  7282. cycle &&
  7283. SDL_GetAtomicInt(&transferBufferContainer->activeBuffer->referenceCount) > 0) {
  7284. VULKAN_INTERNAL_CycleActiveBuffer(
  7285. renderer,
  7286. transferBufferContainer);
  7287. }
  7288. Uint8 *bufferPointer =
  7289. transferBufferContainer->activeBuffer->usedRegion->allocation->mapPointer +
  7290. transferBufferContainer->activeBuffer->usedRegion->resourceOffset;
  7291. return bufferPointer;
  7292. }
  7293. static void VULKAN_UnmapTransferBuffer(
  7294. SDL_GPURenderer *driverData,
  7295. SDL_GPUTransferBuffer *transferBuffer)
  7296. {
  7297. // no-op because transfer buffers are persistently mapped
  7298. (void)driverData;
  7299. (void)transferBuffer;
  7300. }
  7301. static void VULKAN_BeginCopyPass(
  7302. SDL_GPUCommandBuffer *commandBuffer)
  7303. {
  7304. // no-op
  7305. (void)commandBuffer;
  7306. }
  7307. static void VULKAN_UploadToTexture(
  7308. SDL_GPUCommandBuffer *commandBuffer,
  7309. const SDL_GPUTextureTransferInfo *source,
  7310. const SDL_GPUTextureRegion *destination,
  7311. bool cycle)
  7312. {
  7313. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7314. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7315. VulkanBufferContainer *transferBufferContainer = (VulkanBufferContainer *)source->transfer_buffer;
  7316. VulkanTextureContainer *vulkanTextureContainer = (VulkanTextureContainer *)destination->texture;
  7317. VulkanTextureSubresource *vulkanTextureSubresource;
  7318. VkBufferImageCopy imageCopy;
  7319. // Note that the transfer buffer does not need a barrier, as it is synced by the client
  7320. vulkanTextureSubresource = VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  7321. renderer,
  7322. vulkanCommandBuffer,
  7323. vulkanTextureContainer,
  7324. destination->layer,
  7325. destination->mip_level,
  7326. cycle,
  7327. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION);
  7328. imageCopy.imageExtent.width = destination->w;
  7329. imageCopy.imageExtent.height = destination->h;
  7330. imageCopy.imageExtent.depth = destination->d;
  7331. imageCopy.imageOffset.x = destination->x;
  7332. imageCopy.imageOffset.y = destination->y;
  7333. imageCopy.imageOffset.z = destination->z;
  7334. imageCopy.imageSubresource.aspectMask = vulkanTextureSubresource->parent->aspectFlags;
  7335. imageCopy.imageSubresource.baseArrayLayer = destination->layer;
  7336. imageCopy.imageSubresource.layerCount = 1;
  7337. imageCopy.imageSubresource.mipLevel = destination->mip_level;
  7338. imageCopy.bufferOffset = source->offset;
  7339. imageCopy.bufferRowLength = source->pixels_per_row;
  7340. imageCopy.bufferImageHeight = source->rows_per_layer;
  7341. renderer->vkCmdCopyBufferToImage(
  7342. vulkanCommandBuffer->commandBuffer,
  7343. transferBufferContainer->activeBuffer->buffer,
  7344. vulkanTextureSubresource->parent->image,
  7345. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  7346. 1,
  7347. &imageCopy);
  7348. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7349. renderer,
  7350. vulkanCommandBuffer,
  7351. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  7352. vulkanTextureSubresource);
  7353. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, transferBufferContainer->activeBuffer);
  7354. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, vulkanTextureSubresource->parent);
  7355. }
  7356. static void VULKAN_UploadToBuffer(
  7357. SDL_GPUCommandBuffer *commandBuffer,
  7358. const SDL_GPUTransferBufferLocation *source,
  7359. const SDL_GPUBufferRegion *destination,
  7360. bool cycle)
  7361. {
  7362. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7363. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7364. VulkanBufferContainer *transferBufferContainer = (VulkanBufferContainer *)source->transfer_buffer;
  7365. VulkanBufferContainer *bufferContainer = (VulkanBufferContainer *)destination->buffer;
  7366. VkBufferCopy bufferCopy;
  7367. // Note that the transfer buffer does not need a barrier, as it is synced by the client
  7368. VulkanBuffer *vulkanBuffer = VULKAN_INTERNAL_PrepareBufferForWrite(
  7369. renderer,
  7370. vulkanCommandBuffer,
  7371. bufferContainer,
  7372. cycle,
  7373. VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION);
  7374. bufferCopy.srcOffset = source->offset;
  7375. bufferCopy.dstOffset = destination->offset;
  7376. bufferCopy.size = destination->size;
  7377. renderer->vkCmdCopyBuffer(
  7378. vulkanCommandBuffer->commandBuffer,
  7379. transferBufferContainer->activeBuffer->buffer,
  7380. vulkanBuffer->buffer,
  7381. 1,
  7382. &bufferCopy);
  7383. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  7384. renderer,
  7385. vulkanCommandBuffer,
  7386. VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION,
  7387. vulkanBuffer);
  7388. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, transferBufferContainer->activeBuffer);
  7389. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, vulkanBuffer);
  7390. }
  7391. // Readback
  7392. static void VULKAN_DownloadFromTexture(
  7393. SDL_GPUCommandBuffer *commandBuffer,
  7394. const SDL_GPUTextureRegion *source,
  7395. const SDL_GPUTextureTransferInfo *destination)
  7396. {
  7397. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7398. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7399. VulkanTextureContainer *textureContainer = (VulkanTextureContainer *)source->texture;
  7400. VulkanTextureSubresource *vulkanTextureSubresource;
  7401. VulkanBufferContainer *transferBufferContainer = (VulkanBufferContainer *)destination->transfer_buffer;
  7402. VkBufferImageCopy imageCopy;
  7403. vulkanTextureSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  7404. textureContainer,
  7405. source->layer,
  7406. source->mip_level);
  7407. // Note that the transfer buffer does not need a barrier, as it is synced by the client
  7408. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  7409. renderer,
  7410. vulkanCommandBuffer,
  7411. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7412. vulkanTextureSubresource);
  7413. imageCopy.imageExtent.width = source->w;
  7414. imageCopy.imageExtent.height = source->h;
  7415. imageCopy.imageExtent.depth = source->d;
  7416. imageCopy.imageOffset.x = source->x;
  7417. imageCopy.imageOffset.y = source->y;
  7418. imageCopy.imageOffset.z = source->z;
  7419. imageCopy.imageSubresource.aspectMask = vulkanTextureSubresource->parent->aspectFlags;
  7420. imageCopy.imageSubresource.baseArrayLayer = source->layer;
  7421. imageCopy.imageSubresource.layerCount = 1;
  7422. imageCopy.imageSubresource.mipLevel = source->mip_level;
  7423. imageCopy.bufferOffset = destination->offset;
  7424. imageCopy.bufferRowLength = destination->pixels_per_row;
  7425. imageCopy.bufferImageHeight = destination->rows_per_layer;
  7426. renderer->vkCmdCopyImageToBuffer(
  7427. vulkanCommandBuffer->commandBuffer,
  7428. vulkanTextureSubresource->parent->image,
  7429. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  7430. transferBufferContainer->activeBuffer->buffer,
  7431. 1,
  7432. &imageCopy);
  7433. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7434. renderer,
  7435. vulkanCommandBuffer,
  7436. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7437. vulkanTextureSubresource);
  7438. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, transferBufferContainer->activeBuffer);
  7439. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, vulkanTextureSubresource->parent);
  7440. }
  7441. static void VULKAN_DownloadFromBuffer(
  7442. SDL_GPUCommandBuffer *commandBuffer,
  7443. const SDL_GPUBufferRegion *source,
  7444. const SDL_GPUTransferBufferLocation *destination)
  7445. {
  7446. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7447. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7448. VulkanBufferContainer *bufferContainer = (VulkanBufferContainer *)source->buffer;
  7449. VulkanBufferContainer *transferBufferContainer = (VulkanBufferContainer *)destination->transfer_buffer;
  7450. VkBufferCopy bufferCopy;
  7451. // Note that transfer buffer does not need a barrier, as it is synced by the client
  7452. VULKAN_INTERNAL_BufferTransitionFromDefaultUsage(
  7453. renderer,
  7454. vulkanCommandBuffer,
  7455. VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE,
  7456. bufferContainer->activeBuffer);
  7457. bufferCopy.srcOffset = source->offset;
  7458. bufferCopy.dstOffset = destination->offset;
  7459. bufferCopy.size = source->size;
  7460. renderer->vkCmdCopyBuffer(
  7461. vulkanCommandBuffer->commandBuffer,
  7462. bufferContainer->activeBuffer->buffer,
  7463. transferBufferContainer->activeBuffer->buffer,
  7464. 1,
  7465. &bufferCopy);
  7466. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  7467. renderer,
  7468. vulkanCommandBuffer,
  7469. VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE,
  7470. bufferContainer->activeBuffer);
  7471. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, transferBufferContainer->activeBuffer);
  7472. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, bufferContainer->activeBuffer);
  7473. }
  7474. static void VULKAN_CopyTextureToTexture(
  7475. SDL_GPUCommandBuffer *commandBuffer,
  7476. const SDL_GPUTextureLocation *source,
  7477. const SDL_GPUTextureLocation *destination,
  7478. Uint32 w,
  7479. Uint32 h,
  7480. Uint32 d,
  7481. bool cycle)
  7482. {
  7483. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7484. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7485. VulkanTextureSubresource *srcSubresource;
  7486. VulkanTextureSubresource *dstSubresource;
  7487. VkImageCopy imageCopy;
  7488. srcSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  7489. (VulkanTextureContainer *)source->texture,
  7490. source->layer,
  7491. source->mip_level);
  7492. dstSubresource = VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  7493. renderer,
  7494. vulkanCommandBuffer,
  7495. (VulkanTextureContainer *)destination->texture,
  7496. destination->layer,
  7497. destination->mip_level,
  7498. cycle,
  7499. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION);
  7500. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  7501. renderer,
  7502. vulkanCommandBuffer,
  7503. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7504. srcSubresource);
  7505. imageCopy.srcOffset.x = source->x;
  7506. imageCopy.srcOffset.y = source->y;
  7507. imageCopy.srcOffset.z = source->z;
  7508. imageCopy.srcSubresource.aspectMask = srcSubresource->parent->aspectFlags;
  7509. imageCopy.srcSubresource.baseArrayLayer = source->layer;
  7510. imageCopy.srcSubresource.layerCount = 1;
  7511. imageCopy.srcSubresource.mipLevel = source->mip_level;
  7512. imageCopy.dstOffset.x = destination->x;
  7513. imageCopy.dstOffset.y = destination->y;
  7514. imageCopy.dstOffset.z = destination->z;
  7515. imageCopy.dstSubresource.aspectMask = dstSubresource->parent->aspectFlags;
  7516. imageCopy.dstSubresource.baseArrayLayer = destination->layer;
  7517. imageCopy.dstSubresource.layerCount = 1;
  7518. imageCopy.dstSubresource.mipLevel = destination->mip_level;
  7519. imageCopy.extent.width = w;
  7520. imageCopy.extent.height = h;
  7521. imageCopy.extent.depth = d;
  7522. renderer->vkCmdCopyImage(
  7523. vulkanCommandBuffer->commandBuffer,
  7524. srcSubresource->parent->image,
  7525. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  7526. dstSubresource->parent->image,
  7527. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  7528. 1,
  7529. &imageCopy);
  7530. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7531. renderer,
  7532. vulkanCommandBuffer,
  7533. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7534. srcSubresource);
  7535. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7536. renderer,
  7537. vulkanCommandBuffer,
  7538. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  7539. dstSubresource);
  7540. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, srcSubresource->parent);
  7541. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, dstSubresource->parent);
  7542. }
  7543. static void VULKAN_CopyBufferToBuffer(
  7544. SDL_GPUCommandBuffer *commandBuffer,
  7545. const SDL_GPUBufferLocation *source,
  7546. const SDL_GPUBufferLocation *destination,
  7547. Uint32 size,
  7548. bool cycle)
  7549. {
  7550. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7551. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7552. VulkanBufferContainer *srcContainer = (VulkanBufferContainer *)source->buffer;
  7553. VulkanBufferContainer *dstContainer = (VulkanBufferContainer *)destination->buffer;
  7554. VkBufferCopy bufferCopy;
  7555. VulkanBuffer *dstBuffer = VULKAN_INTERNAL_PrepareBufferForWrite(
  7556. renderer,
  7557. vulkanCommandBuffer,
  7558. dstContainer,
  7559. cycle,
  7560. VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION);
  7561. VULKAN_INTERNAL_BufferTransitionFromDefaultUsage(
  7562. renderer,
  7563. vulkanCommandBuffer,
  7564. VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE,
  7565. srcContainer->activeBuffer);
  7566. bufferCopy.srcOffset = source->offset;
  7567. bufferCopy.dstOffset = destination->offset;
  7568. bufferCopy.size = size;
  7569. renderer->vkCmdCopyBuffer(
  7570. vulkanCommandBuffer->commandBuffer,
  7571. srcContainer->activeBuffer->buffer,
  7572. dstBuffer->buffer,
  7573. 1,
  7574. &bufferCopy);
  7575. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  7576. renderer,
  7577. vulkanCommandBuffer,
  7578. VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE,
  7579. srcContainer->activeBuffer);
  7580. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  7581. renderer,
  7582. vulkanCommandBuffer,
  7583. VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION,
  7584. dstBuffer);
  7585. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, srcContainer->activeBuffer);
  7586. VULKAN_INTERNAL_TrackBuffer(vulkanCommandBuffer, dstBuffer);
  7587. }
  7588. static void VULKAN_GenerateMipmaps(
  7589. SDL_GPUCommandBuffer *commandBuffer,
  7590. SDL_GPUTexture *texture)
  7591. {
  7592. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7593. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7594. VulkanTextureContainer *container = (VulkanTextureContainer *)texture;
  7595. VulkanTextureSubresource *srcTextureSubresource;
  7596. VulkanTextureSubresource *dstTextureSubresource;
  7597. VkImageBlit blit;
  7598. // Blit each slice sequentially. Barriers, barriers everywhere!
  7599. for (Uint32 layerOrDepthIndex = 0; layerOrDepthIndex < container->header.info.layer_count_or_depth; layerOrDepthIndex += 1)
  7600. for (Uint32 level = 1; level < container->header.info.num_levels; level += 1) {
  7601. Uint32 layer = container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : layerOrDepthIndex;
  7602. Uint32 depth = container->header.info.type == SDL_GPU_TEXTURETYPE_3D ? layerOrDepthIndex : 0;
  7603. Uint32 srcSubresourceIndex = VULKAN_INTERNAL_GetTextureSubresourceIndex(
  7604. level - 1,
  7605. layer,
  7606. container->header.info.num_levels);
  7607. Uint32 dstSubresourceIndex = VULKAN_INTERNAL_GetTextureSubresourceIndex(
  7608. level,
  7609. layer,
  7610. container->header.info.num_levels);
  7611. srcTextureSubresource = &container->activeTexture->subresources[srcSubresourceIndex];
  7612. dstTextureSubresource = &container->activeTexture->subresources[dstSubresourceIndex];
  7613. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  7614. renderer,
  7615. vulkanCommandBuffer,
  7616. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7617. srcTextureSubresource);
  7618. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  7619. renderer,
  7620. vulkanCommandBuffer,
  7621. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  7622. dstTextureSubresource);
  7623. blit.srcOffsets[0].x = 0;
  7624. blit.srcOffsets[0].y = 0;
  7625. blit.srcOffsets[0].z = depth;
  7626. blit.srcOffsets[1].x = container->header.info.width >> (level - 1);
  7627. blit.srcOffsets[1].y = container->header.info.height >> (level - 1);
  7628. blit.srcOffsets[1].z = depth + 1;
  7629. blit.dstOffsets[0].x = 0;
  7630. blit.dstOffsets[0].y = 0;
  7631. blit.dstOffsets[0].z = depth;
  7632. blit.dstOffsets[1].x = container->header.info.width >> level;
  7633. blit.dstOffsets[1].y = container->header.info.height >> level;
  7634. blit.dstOffsets[1].z = depth + 1;
  7635. blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  7636. blit.srcSubresource.baseArrayLayer = layer;
  7637. blit.srcSubresource.layerCount = 1;
  7638. blit.srcSubresource.mipLevel = level - 1;
  7639. blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  7640. blit.dstSubresource.baseArrayLayer = layer;
  7641. blit.dstSubresource.layerCount = 1;
  7642. blit.dstSubresource.mipLevel = level;
  7643. renderer->vkCmdBlitImage(
  7644. vulkanCommandBuffer->commandBuffer,
  7645. container->activeTexture->image,
  7646. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  7647. container->activeTexture->image,
  7648. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  7649. 1,
  7650. &blit,
  7651. VK_FILTER_LINEAR);
  7652. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7653. renderer,
  7654. vulkanCommandBuffer,
  7655. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7656. srcTextureSubresource);
  7657. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7658. renderer,
  7659. vulkanCommandBuffer,
  7660. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  7661. dstTextureSubresource);
  7662. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, srcTextureSubresource->parent);
  7663. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, dstTextureSubresource->parent);
  7664. }
  7665. }
  7666. static void VULKAN_EndCopyPass(
  7667. SDL_GPUCommandBuffer *commandBuffer)
  7668. {
  7669. // no-op
  7670. (void)commandBuffer;
  7671. }
  7672. static void VULKAN_Blit(
  7673. SDL_GPUCommandBuffer *commandBuffer,
  7674. const SDL_GPUBlitInfo *info)
  7675. {
  7676. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  7677. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  7678. TextureCommonHeader *srcHeader = (TextureCommonHeader *)info->source.texture;
  7679. TextureCommonHeader *dstHeader = (TextureCommonHeader *)info->destination.texture;
  7680. VkImageBlit region;
  7681. Uint32 srcLayer = srcHeader->info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : info->source.layer_or_depth_plane;
  7682. Uint32 srcDepth = srcHeader->info.type == SDL_GPU_TEXTURETYPE_3D ? info->source.layer_or_depth_plane : 0;
  7683. Uint32 dstLayer = dstHeader->info.type == SDL_GPU_TEXTURETYPE_3D ? 0 : info->destination.layer_or_depth_plane;
  7684. Uint32 dstDepth = dstHeader->info.type == SDL_GPU_TEXTURETYPE_3D ? info->destination.layer_or_depth_plane : 0;
  7685. int32_t swap;
  7686. // Using BeginRenderPass to clear because vkCmdClearColorImage requires barriers anyway
  7687. if (info->load_op == SDL_GPU_LOADOP_CLEAR) {
  7688. SDL_GPUColorTargetInfo targetInfo;
  7689. SDL_zero(targetInfo);
  7690. targetInfo.texture = info->destination.texture;
  7691. targetInfo.mip_level = info->destination.mip_level;
  7692. targetInfo.layer_or_depth_plane = info->destination.layer_or_depth_plane;
  7693. targetInfo.load_op = SDL_GPU_LOADOP_CLEAR;
  7694. targetInfo.store_op = SDL_GPU_STOREOP_STORE;
  7695. targetInfo.clear_color = info->clear_color;
  7696. targetInfo.cycle = info->cycle;
  7697. VULKAN_BeginRenderPass(
  7698. commandBuffer,
  7699. &targetInfo,
  7700. 1,
  7701. NULL);
  7702. VULKAN_EndRenderPass(commandBuffer);
  7703. }
  7704. VulkanTextureSubresource *srcSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  7705. (VulkanTextureContainer *)info->source.texture,
  7706. srcLayer,
  7707. info->source.mip_level);
  7708. VulkanTextureSubresource *dstSubresource = VULKAN_INTERNAL_PrepareTextureSubresourceForWrite(
  7709. renderer,
  7710. vulkanCommandBuffer,
  7711. (VulkanTextureContainer *)info->destination.texture,
  7712. dstLayer,
  7713. info->destination.mip_level,
  7714. info->cycle,
  7715. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION);
  7716. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  7717. renderer,
  7718. vulkanCommandBuffer,
  7719. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7720. srcSubresource);
  7721. region.srcSubresource.aspectMask = srcSubresource->parent->aspectFlags;
  7722. region.srcSubresource.baseArrayLayer = srcSubresource->layer;
  7723. region.srcSubresource.layerCount = 1;
  7724. region.srcSubresource.mipLevel = srcSubresource->level;
  7725. region.srcOffsets[0].x = info->source.x;
  7726. region.srcOffsets[0].y = info->source.y;
  7727. region.srcOffsets[0].z = srcDepth;
  7728. region.srcOffsets[1].x = info->source.x + info->source.w;
  7729. region.srcOffsets[1].y = info->source.y + info->source.h;
  7730. region.srcOffsets[1].z = srcDepth + 1;
  7731. if (info->flip_mode & SDL_FLIP_HORIZONTAL) {
  7732. // flip the x positions
  7733. swap = region.srcOffsets[0].x;
  7734. region.srcOffsets[0].x = region.srcOffsets[1].x;
  7735. region.srcOffsets[1].x = swap;
  7736. }
  7737. if (info->flip_mode & SDL_FLIP_VERTICAL) {
  7738. // flip the y positions
  7739. swap = region.srcOffsets[0].y;
  7740. region.srcOffsets[0].y = region.srcOffsets[1].y;
  7741. region.srcOffsets[1].y = swap;
  7742. }
  7743. region.dstSubresource.aspectMask = dstSubresource->parent->aspectFlags;
  7744. region.dstSubresource.baseArrayLayer = dstSubresource->layer;
  7745. region.dstSubresource.layerCount = 1;
  7746. region.dstSubresource.mipLevel = dstSubresource->level;
  7747. region.dstOffsets[0].x = info->destination.x;
  7748. region.dstOffsets[0].y = info->destination.y;
  7749. region.dstOffsets[0].z = dstDepth;
  7750. region.dstOffsets[1].x = info->destination.x + info->destination.w;
  7751. region.dstOffsets[1].y = info->destination.y + info->destination.h;
  7752. region.dstOffsets[1].z = dstDepth + 1;
  7753. renderer->vkCmdBlitImage(
  7754. vulkanCommandBuffer->commandBuffer,
  7755. srcSubresource->parent->image,
  7756. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  7757. dstSubresource->parent->image,
  7758. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  7759. 1,
  7760. &region,
  7761. SDLToVK_Filter[info->filter]);
  7762. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7763. renderer,
  7764. vulkanCommandBuffer,
  7765. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  7766. srcSubresource);
  7767. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  7768. renderer,
  7769. vulkanCommandBuffer,
  7770. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  7771. dstSubresource);
  7772. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, srcSubresource->parent);
  7773. VULKAN_INTERNAL_TrackTexture(vulkanCommandBuffer, dstSubresource->parent);
  7774. }
  7775. static bool VULKAN_INTERNAL_AllocateCommandBuffer(
  7776. VulkanRenderer *renderer,
  7777. VulkanCommandPool *vulkanCommandPool)
  7778. {
  7779. VkCommandBufferAllocateInfo allocateInfo;
  7780. VkResult vulkanResult;
  7781. VkCommandBuffer commandBufferHandle;
  7782. VulkanCommandBuffer *commandBuffer;
  7783. vulkanCommandPool->inactiveCommandBufferCapacity += 1;
  7784. vulkanCommandPool->inactiveCommandBuffers = SDL_realloc(
  7785. vulkanCommandPool->inactiveCommandBuffers,
  7786. sizeof(VulkanCommandBuffer *) *
  7787. vulkanCommandPool->inactiveCommandBufferCapacity);
  7788. allocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  7789. allocateInfo.pNext = NULL;
  7790. allocateInfo.commandPool = vulkanCommandPool->commandPool;
  7791. allocateInfo.commandBufferCount = 1;
  7792. allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  7793. vulkanResult = renderer->vkAllocateCommandBuffers(
  7794. renderer->logicalDevice,
  7795. &allocateInfo,
  7796. &commandBufferHandle);
  7797. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkAllocateCommandBuffers, false);
  7798. commandBuffer = SDL_malloc(sizeof(VulkanCommandBuffer));
  7799. commandBuffer->renderer = renderer;
  7800. commandBuffer->commandPool = vulkanCommandPool;
  7801. commandBuffer->commandBuffer = commandBufferHandle;
  7802. commandBuffer->inFlightFence = VK_NULL_HANDLE;
  7803. // Presentation tracking
  7804. commandBuffer->presentDataCapacity = 1;
  7805. commandBuffer->presentDataCount = 0;
  7806. commandBuffer->presentDatas = SDL_malloc(
  7807. commandBuffer->presentDataCapacity * sizeof(VulkanPresentData));
  7808. commandBuffer->waitSemaphoreCapacity = 1;
  7809. commandBuffer->waitSemaphoreCount = 0;
  7810. commandBuffer->waitSemaphores = SDL_malloc(
  7811. commandBuffer->waitSemaphoreCapacity * sizeof(VkSemaphore));
  7812. commandBuffer->signalSemaphoreCapacity = 1;
  7813. commandBuffer->signalSemaphoreCount = 0;
  7814. commandBuffer->signalSemaphores = SDL_malloc(
  7815. commandBuffer->signalSemaphoreCapacity * sizeof(VkSemaphore));
  7816. // Resource bind tracking
  7817. commandBuffer->needVertexBufferBind = false;
  7818. commandBuffer->needNewVertexResourceDescriptorSet = true;
  7819. commandBuffer->needNewVertexUniformDescriptorSet = true;
  7820. commandBuffer->needNewVertexUniformOffsets = true;
  7821. commandBuffer->needNewFragmentResourceDescriptorSet = true;
  7822. commandBuffer->needNewFragmentUniformDescriptorSet = true;
  7823. commandBuffer->needNewFragmentUniformOffsets = true;
  7824. commandBuffer->needNewComputeReadWriteDescriptorSet = true;
  7825. commandBuffer->needNewComputeReadOnlyDescriptorSet = true;
  7826. commandBuffer->needNewComputeUniformDescriptorSet = true;
  7827. commandBuffer->needNewComputeUniformOffsets = true;
  7828. commandBuffer->vertexResourceDescriptorSet = VK_NULL_HANDLE;
  7829. commandBuffer->vertexUniformDescriptorSet = VK_NULL_HANDLE;
  7830. commandBuffer->fragmentResourceDescriptorSet = VK_NULL_HANDLE;
  7831. commandBuffer->fragmentUniformDescriptorSet = VK_NULL_HANDLE;
  7832. commandBuffer->computeReadOnlyDescriptorSet = VK_NULL_HANDLE;
  7833. commandBuffer->computeReadWriteDescriptorSet = VK_NULL_HANDLE;
  7834. commandBuffer->computeUniformDescriptorSet = VK_NULL_HANDLE;
  7835. // Resource tracking
  7836. commandBuffer->usedBufferCapacity = 4;
  7837. commandBuffer->usedBufferCount = 0;
  7838. commandBuffer->usedBuffers = SDL_malloc(
  7839. commandBuffer->usedBufferCapacity * sizeof(VulkanBuffer *));
  7840. commandBuffer->usedTextureCapacity = 4;
  7841. commandBuffer->usedTextureCount = 0;
  7842. commandBuffer->usedTextures = SDL_malloc(
  7843. commandBuffer->usedTextureCapacity * sizeof(VulkanTexture *));
  7844. commandBuffer->usedSamplerCapacity = 4;
  7845. commandBuffer->usedSamplerCount = 0;
  7846. commandBuffer->usedSamplers = SDL_malloc(
  7847. commandBuffer->usedSamplerCapacity * sizeof(VulkanSampler *));
  7848. commandBuffer->usedGraphicsPipelineCapacity = 4;
  7849. commandBuffer->usedGraphicsPipelineCount = 0;
  7850. commandBuffer->usedGraphicsPipelines = SDL_malloc(
  7851. commandBuffer->usedGraphicsPipelineCapacity * sizeof(VulkanGraphicsPipeline *));
  7852. commandBuffer->usedComputePipelineCapacity = 4;
  7853. commandBuffer->usedComputePipelineCount = 0;
  7854. commandBuffer->usedComputePipelines = SDL_malloc(
  7855. commandBuffer->usedComputePipelineCapacity * sizeof(VulkanComputePipeline *));
  7856. commandBuffer->usedFramebufferCapacity = 4;
  7857. commandBuffer->usedFramebufferCount = 0;
  7858. commandBuffer->usedFramebuffers = SDL_malloc(
  7859. commandBuffer->usedFramebufferCapacity * sizeof(VulkanFramebuffer *));
  7860. commandBuffer->usedUniformBufferCapacity = 4;
  7861. commandBuffer->usedUniformBufferCount = 0;
  7862. commandBuffer->usedUniformBuffers = SDL_malloc(
  7863. commandBuffer->usedUniformBufferCapacity * sizeof(VulkanUniformBuffer *));
  7864. // Pool it!
  7865. vulkanCommandPool->inactiveCommandBuffers[vulkanCommandPool->inactiveCommandBufferCount] = commandBuffer;
  7866. vulkanCommandPool->inactiveCommandBufferCount += 1;
  7867. return true;
  7868. }
  7869. static VulkanCommandPool *VULKAN_INTERNAL_FetchCommandPool(
  7870. VulkanRenderer *renderer,
  7871. SDL_ThreadID threadID)
  7872. {
  7873. VulkanCommandPool *vulkanCommandPool = NULL;
  7874. VkCommandPoolCreateInfo commandPoolCreateInfo;
  7875. VkResult vulkanResult;
  7876. CommandPoolHashTableKey key;
  7877. key.threadID = threadID;
  7878. bool result = SDL_FindInHashTable(
  7879. renderer->commandPoolHashTable,
  7880. (const void *)&key,
  7881. (const void **)&vulkanCommandPool);
  7882. if (result) {
  7883. return vulkanCommandPool;
  7884. }
  7885. vulkanCommandPool = (VulkanCommandPool *)SDL_malloc(sizeof(VulkanCommandPool));
  7886. commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  7887. commandPoolCreateInfo.pNext = NULL;
  7888. commandPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  7889. commandPoolCreateInfo.queueFamilyIndex = renderer->queueFamilyIndex;
  7890. vulkanResult = renderer->vkCreateCommandPool(
  7891. renderer->logicalDevice,
  7892. &commandPoolCreateInfo,
  7893. NULL,
  7894. &vulkanCommandPool->commandPool);
  7895. if (vulkanResult != VK_SUCCESS) {
  7896. SDL_free(vulkanCommandPool);
  7897. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateCommandPool, NULL);
  7898. return NULL;
  7899. }
  7900. vulkanCommandPool->threadID = threadID;
  7901. vulkanCommandPool->inactiveCommandBufferCapacity = 0;
  7902. vulkanCommandPool->inactiveCommandBufferCount = 0;
  7903. vulkanCommandPool->inactiveCommandBuffers = NULL;
  7904. if (!VULKAN_INTERNAL_AllocateCommandBuffer(
  7905. renderer,
  7906. vulkanCommandPool)) {
  7907. VULKAN_INTERNAL_DestroyCommandPool(renderer, vulkanCommandPool);
  7908. return NULL;
  7909. }
  7910. CommandPoolHashTableKey *allocedKey = SDL_malloc(sizeof(CommandPoolHashTableKey));
  7911. allocedKey->threadID = threadID;
  7912. SDL_InsertIntoHashTable(
  7913. renderer->commandPoolHashTable,
  7914. (const void *)allocedKey,
  7915. (const void *)vulkanCommandPool, true);
  7916. return vulkanCommandPool;
  7917. }
  7918. static VulkanCommandBuffer *VULKAN_INTERNAL_GetInactiveCommandBufferFromPool(
  7919. VulkanRenderer *renderer,
  7920. SDL_ThreadID threadID)
  7921. {
  7922. VulkanCommandPool *commandPool =
  7923. VULKAN_INTERNAL_FetchCommandPool(renderer, threadID);
  7924. VulkanCommandBuffer *commandBuffer;
  7925. if (commandPool == NULL) {
  7926. return NULL;
  7927. }
  7928. if (commandPool->inactiveCommandBufferCount == 0) {
  7929. if (!VULKAN_INTERNAL_AllocateCommandBuffer(
  7930. renderer,
  7931. commandPool)) {
  7932. return NULL;
  7933. }
  7934. }
  7935. commandBuffer = commandPool->inactiveCommandBuffers[commandPool->inactiveCommandBufferCount - 1];
  7936. commandPool->inactiveCommandBufferCount -= 1;
  7937. return commandBuffer;
  7938. }
  7939. static SDL_GPUCommandBuffer *VULKAN_AcquireCommandBuffer(
  7940. SDL_GPURenderer *driverData)
  7941. {
  7942. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  7943. VkResult result;
  7944. Uint32 i;
  7945. SDL_ThreadID threadID = SDL_GetCurrentThreadID();
  7946. SDL_LockMutex(renderer->acquireCommandBufferLock);
  7947. VulkanCommandBuffer *commandBuffer =
  7948. VULKAN_INTERNAL_GetInactiveCommandBufferFromPool(renderer, threadID);
  7949. commandBuffer->descriptorSetCache = VULKAN_INTERNAL_AcquireDescriptorSetCache(renderer);
  7950. SDL_UnlockMutex(renderer->acquireCommandBufferLock);
  7951. if (commandBuffer == NULL) {
  7952. return NULL;
  7953. }
  7954. // Reset state
  7955. commandBuffer->currentComputePipeline = NULL;
  7956. commandBuffer->currentGraphicsPipeline = NULL;
  7957. SDL_zeroa(commandBuffer->colorAttachmentSubresources);
  7958. SDL_zeroa(commandBuffer->resolveAttachmentSubresources);
  7959. commandBuffer->depthStencilAttachmentSubresource = NULL;
  7960. commandBuffer->colorAttachmentSubresourceCount = 0;
  7961. commandBuffer->resolveAttachmentSubresourceCount = 0;
  7962. for (i = 0; i < MAX_UNIFORM_BUFFERS_PER_STAGE; i += 1) {
  7963. commandBuffer->vertexUniformBuffers[i] = NULL;
  7964. commandBuffer->fragmentUniformBuffers[i] = NULL;
  7965. commandBuffer->computeUniformBuffers[i] = NULL;
  7966. }
  7967. commandBuffer->needVertexBufferBind = false;
  7968. commandBuffer->needNewVertexResourceDescriptorSet = true;
  7969. commandBuffer->needNewVertexUniformDescriptorSet = true;
  7970. commandBuffer->needNewVertexUniformOffsets = true;
  7971. commandBuffer->needNewFragmentResourceDescriptorSet = true;
  7972. commandBuffer->needNewFragmentUniformDescriptorSet = true;
  7973. commandBuffer->needNewFragmentUniformOffsets = true;
  7974. commandBuffer->needNewComputeReadOnlyDescriptorSet = true;
  7975. commandBuffer->needNewComputeUniformDescriptorSet = true;
  7976. commandBuffer->needNewComputeUniformOffsets = true;
  7977. commandBuffer->vertexResourceDescriptorSet = VK_NULL_HANDLE;
  7978. commandBuffer->vertexUniformDescriptorSet = VK_NULL_HANDLE;
  7979. commandBuffer->fragmentResourceDescriptorSet = VK_NULL_HANDLE;
  7980. commandBuffer->fragmentUniformDescriptorSet = VK_NULL_HANDLE;
  7981. commandBuffer->computeReadOnlyDescriptorSet = VK_NULL_HANDLE;
  7982. commandBuffer->computeReadWriteDescriptorSet = VK_NULL_HANDLE;
  7983. commandBuffer->computeUniformDescriptorSet = VK_NULL_HANDLE;
  7984. SDL_zeroa(commandBuffer->vertexBuffers);
  7985. SDL_zeroa(commandBuffer->vertexBufferOffsets);
  7986. commandBuffer->vertexBufferCount = 0;
  7987. SDL_zeroa(commandBuffer->vertexSamplerTextures);
  7988. SDL_zeroa(commandBuffer->vertexSamplers);
  7989. SDL_zeroa(commandBuffer->vertexStorageTextures);
  7990. SDL_zeroa(commandBuffer->vertexStorageBuffers);
  7991. SDL_zeroa(commandBuffer->fragmentSamplerTextures);
  7992. SDL_zeroa(commandBuffer->fragmentSamplers);
  7993. SDL_zeroa(commandBuffer->fragmentStorageTextures);
  7994. SDL_zeroa(commandBuffer->fragmentStorageBuffers);
  7995. SDL_zeroa(commandBuffer->readWriteComputeStorageTextureSubresources);
  7996. commandBuffer->readWriteComputeStorageTextureSubresourceCount = 0;
  7997. SDL_zeroa(commandBuffer->readWriteComputeStorageBuffers);
  7998. SDL_zeroa(commandBuffer->computeSamplerTextures);
  7999. SDL_zeroa(commandBuffer->computeSamplers);
  8000. SDL_zeroa(commandBuffer->readOnlyComputeStorageTextures);
  8001. SDL_zeroa(commandBuffer->readOnlyComputeStorageBuffers);
  8002. commandBuffer->autoReleaseFence = true;
  8003. commandBuffer->isDefrag = 0;
  8004. /* Reset the command buffer here to avoid resets being called
  8005. * from a separate thread than where the command buffer was acquired
  8006. */
  8007. result = renderer->vkResetCommandBuffer(
  8008. commandBuffer->commandBuffer,
  8009. VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT);
  8010. CHECK_VULKAN_ERROR_AND_RETURN(result, vkResetCommandBuffer, NULL);
  8011. if (!VULKAN_INTERNAL_BeginCommandBuffer(renderer, commandBuffer)) {
  8012. return NULL;
  8013. }
  8014. return (SDL_GPUCommandBuffer *)commandBuffer;
  8015. }
  8016. static bool VULKAN_QueryFence(
  8017. SDL_GPURenderer *driverData,
  8018. SDL_GPUFence *fence)
  8019. {
  8020. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8021. VkResult result;
  8022. result = renderer->vkGetFenceStatus(
  8023. renderer->logicalDevice,
  8024. ((VulkanFenceHandle *)fence)->fence);
  8025. if (result == VK_SUCCESS) {
  8026. return true;
  8027. } else if (result == VK_NOT_READY) {
  8028. return false;
  8029. } else {
  8030. SET_ERROR_AND_RETURN("vkGetFenceStatus: %s", VkErrorMessages(result), false);
  8031. }
  8032. }
  8033. static void VULKAN_INTERNAL_ReturnFenceToPool(
  8034. VulkanRenderer *renderer,
  8035. VulkanFenceHandle *fenceHandle)
  8036. {
  8037. SDL_LockMutex(renderer->fencePool.lock);
  8038. EXPAND_ARRAY_IF_NEEDED(
  8039. renderer->fencePool.availableFences,
  8040. VulkanFenceHandle *,
  8041. renderer->fencePool.availableFenceCount + 1,
  8042. renderer->fencePool.availableFenceCapacity,
  8043. renderer->fencePool.availableFenceCapacity * 2);
  8044. renderer->fencePool.availableFences[renderer->fencePool.availableFenceCount] = fenceHandle;
  8045. renderer->fencePool.availableFenceCount += 1;
  8046. SDL_UnlockMutex(renderer->fencePool.lock);
  8047. }
  8048. static void VULKAN_ReleaseFence(
  8049. SDL_GPURenderer *driverData,
  8050. SDL_GPUFence *fence)
  8051. {
  8052. VulkanFenceHandle *handle = (VulkanFenceHandle *)fence;
  8053. if (SDL_AtomicDecRef(&handle->referenceCount)) {
  8054. VULKAN_INTERNAL_ReturnFenceToPool((VulkanRenderer *)driverData, handle);
  8055. }
  8056. }
  8057. static WindowData *VULKAN_INTERNAL_FetchWindowData(
  8058. SDL_Window *window)
  8059. {
  8060. SDL_PropertiesID properties = SDL_GetWindowProperties(window);
  8061. return (WindowData *)SDL_GetPointerProperty(properties, WINDOW_PROPERTY_DATA, NULL);
  8062. }
  8063. static bool VULKAN_INTERNAL_OnWindowResize(void *userdata, SDL_Event *e)
  8064. {
  8065. SDL_Window *w = (SDL_Window *)userdata;
  8066. WindowData *data;
  8067. if (e->type == SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED && e->window.windowID == SDL_GetWindowID(w)) {
  8068. data = VULKAN_INTERNAL_FetchWindowData(w);
  8069. data->needsSwapchainRecreate = true;
  8070. data->swapchainCreateWidth = e->window.data1;
  8071. data->swapchainCreateHeight = e->window.data2;
  8072. }
  8073. return true;
  8074. }
  8075. static bool VULKAN_SupportsSwapchainComposition(
  8076. SDL_GPURenderer *driverData,
  8077. SDL_Window *window,
  8078. SDL_GPUSwapchainComposition swapchainComposition)
  8079. {
  8080. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8081. WindowData *windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8082. VkSurfaceKHR surface;
  8083. SwapchainSupportDetails supportDetails;
  8084. bool result = false;
  8085. if (windowData == NULL) {
  8086. SET_STRING_ERROR_AND_RETURN("Must claim window before querying swapchain composition support!", false);
  8087. }
  8088. surface = windowData->surface;
  8089. if (!surface) {
  8090. SET_STRING_ERROR_AND_RETURN("Window has no Vulkan surface", false);
  8091. }
  8092. if (VULKAN_INTERNAL_QuerySwapchainSupport(
  8093. renderer,
  8094. renderer->physicalDevice,
  8095. surface,
  8096. &supportDetails)) {
  8097. result = VULKAN_INTERNAL_VerifySwapSurfaceFormat(
  8098. SwapchainCompositionToFormat[swapchainComposition],
  8099. SwapchainCompositionToColorSpace[swapchainComposition],
  8100. supportDetails.formats,
  8101. supportDetails.formatsLength);
  8102. if (!result) {
  8103. // Let's try again with the fallback format...
  8104. result = VULKAN_INTERNAL_VerifySwapSurfaceFormat(
  8105. SwapchainCompositionToFallbackFormat[swapchainComposition],
  8106. SwapchainCompositionToColorSpace[swapchainComposition],
  8107. supportDetails.formats,
  8108. supportDetails.formatsLength);
  8109. }
  8110. SDL_free(supportDetails.formats);
  8111. SDL_free(supportDetails.presentModes);
  8112. }
  8113. return result;
  8114. }
  8115. static bool VULKAN_SupportsPresentMode(
  8116. SDL_GPURenderer *driverData,
  8117. SDL_Window *window,
  8118. SDL_GPUPresentMode presentMode)
  8119. {
  8120. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8121. WindowData *windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8122. VkSurfaceKHR surface;
  8123. SwapchainSupportDetails supportDetails;
  8124. bool result = false;
  8125. if (windowData == NULL) {
  8126. SET_STRING_ERROR_AND_RETURN("Must claim window before querying present mode support!", false);
  8127. }
  8128. surface = windowData->surface;
  8129. if (!surface) {
  8130. SET_STRING_ERROR_AND_RETURN("Window has no Vulkan surface", false);
  8131. }
  8132. if (VULKAN_INTERNAL_QuerySwapchainSupport(
  8133. renderer,
  8134. renderer->physicalDevice,
  8135. surface,
  8136. &supportDetails)) {
  8137. result = VULKAN_INTERNAL_VerifySwapPresentMode(
  8138. SDLToVK_PresentMode[presentMode],
  8139. supportDetails.presentModes,
  8140. supportDetails.presentModesLength);
  8141. SDL_free(supportDetails.formats);
  8142. SDL_free(supportDetails.presentModes);
  8143. }
  8144. return result;
  8145. }
  8146. static bool VULKAN_ClaimWindow(
  8147. SDL_GPURenderer *driverData,
  8148. SDL_Window *window)
  8149. {
  8150. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8151. WindowData *windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8152. if (windowData == NULL) {
  8153. windowData = SDL_calloc(1, sizeof(WindowData));
  8154. windowData->window = window;
  8155. windowData->presentMode = SDL_GPU_PRESENTMODE_VSYNC;
  8156. windowData->swapchainComposition = SDL_GPU_SWAPCHAINCOMPOSITION_SDR;
  8157. // On non-Apple platforms the swapchain capability currentExtent can be different from the window,
  8158. // so we have to query the window size.
  8159. #ifndef SDL_PLATFORM_APPLE
  8160. int w, h;
  8161. SDL_SyncWindow(window);
  8162. SDL_GetWindowSizeInPixels(window, &w, &h);
  8163. windowData->swapchainCreateWidth = w;
  8164. windowData->swapchainCreateHeight = h;
  8165. #endif
  8166. Uint32 createSwapchainResult = VULKAN_INTERNAL_CreateSwapchain(renderer, windowData);
  8167. if (createSwapchainResult == 1) {
  8168. SDL_SetPointerProperty(SDL_GetWindowProperties(window), WINDOW_PROPERTY_DATA, windowData);
  8169. SDL_LockMutex(renderer->windowLock);
  8170. if (renderer->claimedWindowCount >= renderer->claimedWindowCapacity) {
  8171. renderer->claimedWindowCapacity *= 2;
  8172. renderer->claimedWindows = SDL_realloc(
  8173. renderer->claimedWindows,
  8174. renderer->claimedWindowCapacity * sizeof(WindowData *));
  8175. }
  8176. renderer->claimedWindows[renderer->claimedWindowCount] = windowData;
  8177. renderer->claimedWindowCount += 1;
  8178. SDL_UnlockMutex(renderer->windowLock);
  8179. SDL_AddEventWatch(VULKAN_INTERNAL_OnWindowResize, window);
  8180. return true;
  8181. } else if (createSwapchainResult == VULKAN_INTERNAL_TRY_AGAIN) {
  8182. windowData->needsSwapchainRecreate = true;
  8183. return true;
  8184. } else {
  8185. SDL_free(windowData);
  8186. return false;
  8187. }
  8188. } else {
  8189. SET_STRING_ERROR_AND_RETURN("Window already claimed!", false);
  8190. }
  8191. }
  8192. static void VULKAN_ReleaseWindow(
  8193. SDL_GPURenderer *driverData,
  8194. SDL_Window *window)
  8195. {
  8196. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8197. WindowData *windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8198. Uint32 i;
  8199. if (windowData == NULL) {
  8200. return;
  8201. }
  8202. VULKAN_Wait(driverData);
  8203. for (i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  8204. if (windowData->inFlightFences[i] != NULL) {
  8205. VULKAN_ReleaseFence(
  8206. driverData,
  8207. windowData->inFlightFences[i]);
  8208. }
  8209. }
  8210. VULKAN_INTERNAL_DestroySwapchain(
  8211. (VulkanRenderer *)driverData,
  8212. windowData);
  8213. SDL_LockMutex(renderer->windowLock);
  8214. for (i = 0; i < renderer->claimedWindowCount; i += 1) {
  8215. if (renderer->claimedWindows[i]->window == window) {
  8216. renderer->claimedWindows[i] = renderer->claimedWindows[renderer->claimedWindowCount - 1];
  8217. renderer->claimedWindowCount -= 1;
  8218. break;
  8219. }
  8220. }
  8221. SDL_UnlockMutex(renderer->windowLock);
  8222. SDL_free(windowData);
  8223. SDL_ClearProperty(SDL_GetWindowProperties(window), WINDOW_PROPERTY_DATA);
  8224. SDL_RemoveEventWatch(VULKAN_INTERNAL_OnWindowResize, window);
  8225. }
  8226. static Uint32 VULKAN_INTERNAL_RecreateSwapchain(
  8227. VulkanRenderer *renderer,
  8228. WindowData *windowData)
  8229. {
  8230. Uint32 i;
  8231. if (!VULKAN_Wait((SDL_GPURenderer *)renderer)) {
  8232. return false;
  8233. }
  8234. for (i = 0; i < MAX_FRAMES_IN_FLIGHT; i += 1) {
  8235. if (windowData->inFlightFences[i] != NULL) {
  8236. VULKAN_ReleaseFence(
  8237. (SDL_GPURenderer *)renderer,
  8238. windowData->inFlightFences[i]);
  8239. windowData->inFlightFences[i] = NULL;
  8240. }
  8241. }
  8242. VULKAN_INTERNAL_DestroySwapchain(renderer, windowData);
  8243. return VULKAN_INTERNAL_CreateSwapchain(renderer, windowData);
  8244. }
  8245. static bool VULKAN_WaitForSwapchain(
  8246. SDL_GPURenderer *driverData,
  8247. SDL_Window *window)
  8248. {
  8249. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8250. WindowData *windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8251. if (windowData == NULL) {
  8252. SET_STRING_ERROR_AND_RETURN("Cannot wait for a swapchain from an unclaimed window!", false);
  8253. }
  8254. if (windowData->inFlightFences[windowData->frameCounter] != NULL) {
  8255. if (!VULKAN_WaitForFences(
  8256. driverData,
  8257. true,
  8258. &windowData->inFlightFences[windowData->frameCounter],
  8259. 1)) {
  8260. return false;
  8261. }
  8262. }
  8263. return true;
  8264. }
  8265. static bool VULKAN_INTERNAL_AcquireSwapchainTexture(
  8266. bool block,
  8267. SDL_GPUCommandBuffer *commandBuffer,
  8268. SDL_Window *window,
  8269. SDL_GPUTexture **swapchainTexture,
  8270. Uint32 *swapchainTextureWidth,
  8271. Uint32 *swapchainTextureHeight)
  8272. {
  8273. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  8274. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  8275. Uint32 swapchainImageIndex;
  8276. WindowData *windowData;
  8277. VkResult acquireResult = VK_SUCCESS;
  8278. VulkanTextureContainer *swapchainTextureContainer = NULL;
  8279. VulkanPresentData *presentData;
  8280. *swapchainTexture = NULL;
  8281. if (swapchainTextureWidth) {
  8282. *swapchainTextureWidth = 0;
  8283. }
  8284. if (swapchainTextureHeight) {
  8285. *swapchainTextureHeight = 0;
  8286. }
  8287. windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8288. if (windowData == NULL) {
  8289. SET_STRING_ERROR_AND_RETURN("Cannot acquire a swapchain texture from an unclaimed window!", false);
  8290. }
  8291. // If window data marked as needing swapchain recreate, try to recreate
  8292. if (windowData->needsSwapchainRecreate) {
  8293. Uint32 recreateSwapchainResult = VULKAN_INTERNAL_RecreateSwapchain(renderer, windowData);
  8294. if (!recreateSwapchainResult) {
  8295. return false;
  8296. } else if (recreateSwapchainResult == VULKAN_INTERNAL_TRY_AGAIN) {
  8297. // Edge case, texture is filled in with NULL but not an error
  8298. if (windowData->inFlightFences[windowData->frameCounter] != NULL) {
  8299. VULKAN_ReleaseFence(
  8300. (SDL_GPURenderer *)renderer,
  8301. windowData->inFlightFences[windowData->frameCounter]);
  8302. windowData->inFlightFences[windowData->frameCounter] = NULL;
  8303. }
  8304. return true;
  8305. }
  8306. }
  8307. if (swapchainTextureWidth) {
  8308. *swapchainTextureWidth = windowData->width;
  8309. }
  8310. if (swapchainTextureHeight) {
  8311. *swapchainTextureHeight = windowData->height;
  8312. }
  8313. if (windowData->inFlightFences[windowData->frameCounter] != NULL) {
  8314. if (block) {
  8315. // If we are blocking, just wait for the fence!
  8316. if (!VULKAN_WaitForFences(
  8317. (SDL_GPURenderer *)renderer,
  8318. true,
  8319. &windowData->inFlightFences[windowData->frameCounter],
  8320. 1)) {
  8321. return false;
  8322. }
  8323. } else {
  8324. // If we are not blocking and the least recent fence is not signaled,
  8325. // return true to indicate that there is no error but rendering should be skipped.
  8326. if (!VULKAN_QueryFence(
  8327. (SDL_GPURenderer *)renderer,
  8328. windowData->inFlightFences[windowData->frameCounter])) {
  8329. return true;
  8330. }
  8331. }
  8332. VULKAN_ReleaseFence(
  8333. (SDL_GPURenderer *)renderer,
  8334. windowData->inFlightFences[windowData->frameCounter]);
  8335. windowData->inFlightFences[windowData->frameCounter] = NULL;
  8336. }
  8337. // Finally, try to acquire!
  8338. while (true) {
  8339. acquireResult = renderer->vkAcquireNextImageKHR(
  8340. renderer->logicalDevice,
  8341. windowData->swapchain,
  8342. SDL_MAX_UINT64,
  8343. windowData->imageAvailableSemaphore[windowData->frameCounter],
  8344. VK_NULL_HANDLE,
  8345. &swapchainImageIndex);
  8346. if (acquireResult == VK_SUCCESS || acquireResult == VK_SUBOPTIMAL_KHR) {
  8347. break; // we got the next image!
  8348. }
  8349. // If acquisition is invalid, let's try to recreate
  8350. Uint32 recreateSwapchainResult = VULKAN_INTERNAL_RecreateSwapchain(renderer, windowData);
  8351. if (!recreateSwapchainResult) {
  8352. return false;
  8353. } else if (recreateSwapchainResult == VULKAN_INTERNAL_TRY_AGAIN) {
  8354. // Edge case, texture is filled in with NULL but not an error
  8355. return true;
  8356. }
  8357. }
  8358. swapchainTextureContainer = &windowData->textureContainers[swapchainImageIndex];
  8359. // We need a special execution dependency with pWaitDstStageMask or image transition can start before acquire finishes
  8360. VkImageMemoryBarrier imageBarrier;
  8361. imageBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  8362. imageBarrier.pNext = NULL;
  8363. imageBarrier.srcAccessMask = 0;
  8364. imageBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  8365. imageBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  8366. imageBarrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  8367. imageBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  8368. imageBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
  8369. imageBarrier.image = swapchainTextureContainer->activeTexture->image;
  8370. imageBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  8371. imageBarrier.subresourceRange.baseMipLevel = 0;
  8372. imageBarrier.subresourceRange.levelCount = 1;
  8373. imageBarrier.subresourceRange.baseArrayLayer = 0;
  8374. imageBarrier.subresourceRange.layerCount = 1;
  8375. renderer->vkCmdPipelineBarrier(
  8376. vulkanCommandBuffer->commandBuffer,
  8377. VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
  8378. VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
  8379. 0,
  8380. 0,
  8381. NULL,
  8382. 0,
  8383. NULL,
  8384. 1,
  8385. &imageBarrier);
  8386. // Set up present struct
  8387. if (vulkanCommandBuffer->presentDataCount == vulkanCommandBuffer->presentDataCapacity) {
  8388. vulkanCommandBuffer->presentDataCapacity += 1;
  8389. vulkanCommandBuffer->presentDatas = SDL_realloc(
  8390. vulkanCommandBuffer->presentDatas,
  8391. vulkanCommandBuffer->presentDataCapacity * sizeof(VulkanPresentData));
  8392. }
  8393. presentData = &vulkanCommandBuffer->presentDatas[vulkanCommandBuffer->presentDataCount];
  8394. vulkanCommandBuffer->presentDataCount += 1;
  8395. presentData->windowData = windowData;
  8396. presentData->swapchainImageIndex = swapchainImageIndex;
  8397. // Set up present semaphores
  8398. if (vulkanCommandBuffer->waitSemaphoreCount == vulkanCommandBuffer->waitSemaphoreCapacity) {
  8399. vulkanCommandBuffer->waitSemaphoreCapacity += 1;
  8400. vulkanCommandBuffer->waitSemaphores = SDL_realloc(
  8401. vulkanCommandBuffer->waitSemaphores,
  8402. vulkanCommandBuffer->waitSemaphoreCapacity * sizeof(VkSemaphore));
  8403. }
  8404. vulkanCommandBuffer->waitSemaphores[vulkanCommandBuffer->waitSemaphoreCount] =
  8405. windowData->imageAvailableSemaphore[windowData->frameCounter];
  8406. vulkanCommandBuffer->waitSemaphoreCount += 1;
  8407. if (vulkanCommandBuffer->signalSemaphoreCount == vulkanCommandBuffer->signalSemaphoreCapacity) {
  8408. vulkanCommandBuffer->signalSemaphoreCapacity += 1;
  8409. vulkanCommandBuffer->signalSemaphores = SDL_realloc(
  8410. vulkanCommandBuffer->signalSemaphores,
  8411. vulkanCommandBuffer->signalSemaphoreCapacity * sizeof(VkSemaphore));
  8412. }
  8413. vulkanCommandBuffer->signalSemaphores[vulkanCommandBuffer->signalSemaphoreCount] =
  8414. windowData->renderFinishedSemaphore[swapchainImageIndex];
  8415. vulkanCommandBuffer->signalSemaphoreCount += 1;
  8416. *swapchainTexture = (SDL_GPUTexture *)swapchainTextureContainer;
  8417. return true;
  8418. }
  8419. static bool VULKAN_AcquireSwapchainTexture(
  8420. SDL_GPUCommandBuffer *command_buffer,
  8421. SDL_Window *window,
  8422. SDL_GPUTexture **swapchain_texture,
  8423. Uint32 *swapchain_texture_width,
  8424. Uint32 *swapchain_texture_height
  8425. ) {
  8426. return VULKAN_INTERNAL_AcquireSwapchainTexture(
  8427. false,
  8428. command_buffer,
  8429. window,
  8430. swapchain_texture,
  8431. swapchain_texture_width,
  8432. swapchain_texture_height);
  8433. }
  8434. static bool VULKAN_WaitAndAcquireSwapchainTexture(
  8435. SDL_GPUCommandBuffer *command_buffer,
  8436. SDL_Window *window,
  8437. SDL_GPUTexture **swapchain_texture,
  8438. Uint32 *swapchain_texture_width,
  8439. Uint32 *swapchain_texture_height
  8440. ) {
  8441. return VULKAN_INTERNAL_AcquireSwapchainTexture(
  8442. true,
  8443. command_buffer,
  8444. window,
  8445. swapchain_texture,
  8446. swapchain_texture_width,
  8447. swapchain_texture_height);
  8448. }
  8449. static SDL_GPUTextureFormat VULKAN_GetSwapchainTextureFormat(
  8450. SDL_GPURenderer *driverData,
  8451. SDL_Window *window)
  8452. {
  8453. VulkanRenderer *renderer = (VulkanRenderer*)driverData;
  8454. WindowData *windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8455. if (windowData == NULL) {
  8456. SET_STRING_ERROR_AND_RETURN("Cannot get swapchain format, window has not been claimed!", SDL_GPU_TEXTUREFORMAT_INVALID);
  8457. }
  8458. return SwapchainCompositionToSDLFormat(
  8459. windowData->swapchainComposition,
  8460. windowData->usingFallbackFormat);
  8461. }
  8462. static bool VULKAN_SetSwapchainParameters(
  8463. SDL_GPURenderer *driverData,
  8464. SDL_Window *window,
  8465. SDL_GPUSwapchainComposition swapchainComposition,
  8466. SDL_GPUPresentMode presentMode)
  8467. {
  8468. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8469. WindowData *windowData = VULKAN_INTERNAL_FetchWindowData(window);
  8470. if (windowData == NULL) {
  8471. SET_STRING_ERROR_AND_RETURN("Cannot set swapchain parameters on unclaimed window!", false);
  8472. }
  8473. if (!VULKAN_SupportsSwapchainComposition(driverData, window, swapchainComposition)) {
  8474. SET_STRING_ERROR_AND_RETURN("Swapchain composition not supported!", false);
  8475. }
  8476. if (!VULKAN_SupportsPresentMode(driverData, window, presentMode)) {
  8477. SET_STRING_ERROR_AND_RETURN("Present mode not supported!", false);
  8478. }
  8479. windowData->presentMode = presentMode;
  8480. windowData->swapchainComposition = swapchainComposition;
  8481. Uint32 recreateSwapchainResult = VULKAN_INTERNAL_RecreateSwapchain(renderer, windowData);
  8482. if (!recreateSwapchainResult) {
  8483. return false;
  8484. } else if (recreateSwapchainResult == VULKAN_INTERNAL_TRY_AGAIN) {
  8485. // Edge case, swapchain extent is (0, 0) but this is not an error
  8486. windowData->needsSwapchainRecreate = true;
  8487. return true;
  8488. }
  8489. return true;
  8490. }
  8491. static bool VULKAN_SetAllowedFramesInFlight(
  8492. SDL_GPURenderer *driverData,
  8493. Uint32 allowedFramesInFlight)
  8494. {
  8495. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8496. renderer->allowedFramesInFlight = allowedFramesInFlight;
  8497. for (Uint32 i = 0; i < renderer->claimedWindowCount; i += 1) {
  8498. WindowData *windowData = renderer->claimedWindows[i];
  8499. Uint32 recreateResult = VULKAN_INTERNAL_RecreateSwapchain(renderer, windowData);
  8500. if (!recreateResult) {
  8501. return false;
  8502. } else if (recreateResult == VULKAN_INTERNAL_TRY_AGAIN) {
  8503. // Edge case, swapchain extent is (0, 0) but this is not an error
  8504. windowData->needsSwapchainRecreate = true;
  8505. }
  8506. }
  8507. return true;
  8508. }
  8509. // Submission structure
  8510. static VulkanFenceHandle *VULKAN_INTERNAL_AcquireFenceFromPool(
  8511. VulkanRenderer *renderer)
  8512. {
  8513. VulkanFenceHandle *handle;
  8514. VkFenceCreateInfo fenceCreateInfo;
  8515. VkFence fence;
  8516. VkResult vulkanResult;
  8517. if (renderer->fencePool.availableFenceCount == 0) {
  8518. // Create fence
  8519. fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  8520. fenceCreateInfo.pNext = NULL;
  8521. fenceCreateInfo.flags = 0;
  8522. vulkanResult = renderer->vkCreateFence(
  8523. renderer->logicalDevice,
  8524. &fenceCreateInfo,
  8525. NULL,
  8526. &fence);
  8527. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateFence, NULL);
  8528. handle = SDL_malloc(sizeof(VulkanFenceHandle));
  8529. handle->fence = fence;
  8530. SDL_SetAtomicInt(&handle->referenceCount, 0);
  8531. return handle;
  8532. }
  8533. SDL_LockMutex(renderer->fencePool.lock);
  8534. handle = renderer->fencePool.availableFences[renderer->fencePool.availableFenceCount - 1];
  8535. renderer->fencePool.availableFenceCount -= 1;
  8536. vulkanResult = renderer->vkResetFences(
  8537. renderer->logicalDevice,
  8538. 1,
  8539. &handle->fence);
  8540. SDL_UnlockMutex(renderer->fencePool.lock);
  8541. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkResetFences, NULL);
  8542. return handle;
  8543. }
  8544. static void VULKAN_INTERNAL_PerformPendingDestroys(
  8545. VulkanRenderer *renderer)
  8546. {
  8547. SDL_LockMutex(renderer->disposeLock);
  8548. for (Sint32 i = renderer->texturesToDestroyCount - 1; i >= 0; i -= 1) {
  8549. if (SDL_GetAtomicInt(&renderer->texturesToDestroy[i]->referenceCount) == 0) {
  8550. VULKAN_INTERNAL_DestroyTexture(
  8551. renderer,
  8552. renderer->texturesToDestroy[i]);
  8553. renderer->texturesToDestroy[i] = renderer->texturesToDestroy[renderer->texturesToDestroyCount - 1];
  8554. renderer->texturesToDestroyCount -= 1;
  8555. }
  8556. }
  8557. for (Sint32 i = renderer->buffersToDestroyCount - 1; i >= 0; i -= 1) {
  8558. if (SDL_GetAtomicInt(&renderer->buffersToDestroy[i]->referenceCount) == 0) {
  8559. VULKAN_INTERNAL_DestroyBuffer(
  8560. renderer,
  8561. renderer->buffersToDestroy[i]);
  8562. renderer->buffersToDestroy[i] = renderer->buffersToDestroy[renderer->buffersToDestroyCount - 1];
  8563. renderer->buffersToDestroyCount -= 1;
  8564. }
  8565. }
  8566. for (Sint32 i = renderer->graphicsPipelinesToDestroyCount - 1; i >= 0; i -= 1) {
  8567. if (SDL_GetAtomicInt(&renderer->graphicsPipelinesToDestroy[i]->referenceCount) == 0) {
  8568. VULKAN_INTERNAL_DestroyGraphicsPipeline(
  8569. renderer,
  8570. renderer->graphicsPipelinesToDestroy[i]);
  8571. renderer->graphicsPipelinesToDestroy[i] = renderer->graphicsPipelinesToDestroy[renderer->graphicsPipelinesToDestroyCount - 1];
  8572. renderer->graphicsPipelinesToDestroyCount -= 1;
  8573. }
  8574. }
  8575. for (Sint32 i = renderer->computePipelinesToDestroyCount - 1; i >= 0; i -= 1) {
  8576. if (SDL_GetAtomicInt(&renderer->computePipelinesToDestroy[i]->referenceCount) == 0) {
  8577. VULKAN_INTERNAL_DestroyComputePipeline(
  8578. renderer,
  8579. renderer->computePipelinesToDestroy[i]);
  8580. renderer->computePipelinesToDestroy[i] = renderer->computePipelinesToDestroy[renderer->computePipelinesToDestroyCount - 1];
  8581. renderer->computePipelinesToDestroyCount -= 1;
  8582. }
  8583. }
  8584. for (Sint32 i = renderer->shadersToDestroyCount - 1; i >= 0; i -= 1) {
  8585. if (SDL_GetAtomicInt(&renderer->shadersToDestroy[i]->referenceCount) == 0) {
  8586. VULKAN_INTERNAL_DestroyShader(
  8587. renderer,
  8588. renderer->shadersToDestroy[i]);
  8589. renderer->shadersToDestroy[i] = renderer->shadersToDestroy[renderer->shadersToDestroyCount - 1];
  8590. renderer->shadersToDestroyCount -= 1;
  8591. }
  8592. }
  8593. for (Sint32 i = renderer->samplersToDestroyCount - 1; i >= 0; i -= 1) {
  8594. if (SDL_GetAtomicInt(&renderer->samplersToDestroy[i]->referenceCount) == 0) {
  8595. VULKAN_INTERNAL_DestroySampler(
  8596. renderer,
  8597. renderer->samplersToDestroy[i]);
  8598. renderer->samplersToDestroy[i] = renderer->samplersToDestroy[renderer->samplersToDestroyCount - 1];
  8599. renderer->samplersToDestroyCount -= 1;
  8600. }
  8601. }
  8602. for (Sint32 i = renderer->framebuffersToDestroyCount - 1; i >= 0; i -= 1) {
  8603. if (SDL_GetAtomicInt(&renderer->framebuffersToDestroy[i]->referenceCount) == 0) {
  8604. VULKAN_INTERNAL_DestroyFramebuffer(
  8605. renderer,
  8606. renderer->framebuffersToDestroy[i]);
  8607. renderer->framebuffersToDestroy[i] = renderer->framebuffersToDestroy[renderer->framebuffersToDestroyCount - 1];
  8608. renderer->framebuffersToDestroyCount -= 1;
  8609. }
  8610. }
  8611. SDL_UnlockMutex(renderer->disposeLock);
  8612. }
  8613. static void VULKAN_INTERNAL_CleanCommandBuffer(
  8614. VulkanRenderer *renderer,
  8615. VulkanCommandBuffer *commandBuffer,
  8616. bool cancel)
  8617. {
  8618. if (commandBuffer->autoReleaseFence) {
  8619. VULKAN_ReleaseFence(
  8620. (SDL_GPURenderer *)renderer,
  8621. (SDL_GPUFence *)commandBuffer->inFlightFence);
  8622. commandBuffer->inFlightFence = NULL;
  8623. }
  8624. // Uniform buffers are now available
  8625. SDL_LockMutex(renderer->acquireUniformBufferLock);
  8626. for (Sint32 i = 0; i < commandBuffer->usedUniformBufferCount; i += 1) {
  8627. VULKAN_INTERNAL_ReturnUniformBufferToPool(
  8628. renderer,
  8629. commandBuffer->usedUniformBuffers[i]);
  8630. }
  8631. commandBuffer->usedUniformBufferCount = 0;
  8632. SDL_UnlockMutex(renderer->acquireUniformBufferLock);
  8633. // Decrement reference counts
  8634. for (Sint32 i = 0; i < commandBuffer->usedBufferCount; i += 1) {
  8635. (void)SDL_AtomicDecRef(&commandBuffer->usedBuffers[i]->referenceCount);
  8636. }
  8637. commandBuffer->usedBufferCount = 0;
  8638. for (Sint32 i = 0; i < commandBuffer->usedTextureCount; i += 1) {
  8639. (void)SDL_AtomicDecRef(&commandBuffer->usedTextures[i]->referenceCount);
  8640. }
  8641. commandBuffer->usedTextureCount = 0;
  8642. for (Sint32 i = 0; i < commandBuffer->usedSamplerCount; i += 1) {
  8643. (void)SDL_AtomicDecRef(&commandBuffer->usedSamplers[i]->referenceCount);
  8644. }
  8645. commandBuffer->usedSamplerCount = 0;
  8646. for (Sint32 i = 0; i < commandBuffer->usedGraphicsPipelineCount; i += 1) {
  8647. (void)SDL_AtomicDecRef(&commandBuffer->usedGraphicsPipelines[i]->referenceCount);
  8648. }
  8649. commandBuffer->usedGraphicsPipelineCount = 0;
  8650. for (Sint32 i = 0; i < commandBuffer->usedComputePipelineCount; i += 1) {
  8651. (void)SDL_AtomicDecRef(&commandBuffer->usedComputePipelines[i]->referenceCount);
  8652. }
  8653. commandBuffer->usedComputePipelineCount = 0;
  8654. for (Sint32 i = 0; i < commandBuffer->usedFramebufferCount; i += 1) {
  8655. (void)SDL_AtomicDecRef(&commandBuffer->usedFramebuffers[i]->referenceCount);
  8656. }
  8657. commandBuffer->usedFramebufferCount = 0;
  8658. // Reset presentation data
  8659. commandBuffer->presentDataCount = 0;
  8660. commandBuffer->waitSemaphoreCount = 0;
  8661. commandBuffer->signalSemaphoreCount = 0;
  8662. // Reset defrag state
  8663. if (commandBuffer->isDefrag) {
  8664. renderer->defragInProgress = 0;
  8665. }
  8666. // Return command buffer to pool
  8667. SDL_LockMutex(renderer->acquireCommandBufferLock);
  8668. if (commandBuffer->commandPool->inactiveCommandBufferCount == commandBuffer->commandPool->inactiveCommandBufferCapacity) {
  8669. commandBuffer->commandPool->inactiveCommandBufferCapacity += 1;
  8670. commandBuffer->commandPool->inactiveCommandBuffers = SDL_realloc(
  8671. commandBuffer->commandPool->inactiveCommandBuffers,
  8672. commandBuffer->commandPool->inactiveCommandBufferCapacity * sizeof(VulkanCommandBuffer *));
  8673. }
  8674. commandBuffer->commandPool->inactiveCommandBuffers[commandBuffer->commandPool->inactiveCommandBufferCount] = commandBuffer;
  8675. commandBuffer->commandPool->inactiveCommandBufferCount += 1;
  8676. // Release descriptor set cache
  8677. VULKAN_INTERNAL_ReturnDescriptorSetCacheToPool(
  8678. renderer,
  8679. commandBuffer->descriptorSetCache);
  8680. commandBuffer->descriptorSetCache = NULL;
  8681. SDL_UnlockMutex(renderer->acquireCommandBufferLock);
  8682. // Remove this command buffer from the submitted list
  8683. if (!cancel) {
  8684. for (Uint32 i = 0; i < renderer->submittedCommandBufferCount; i += 1) {
  8685. if (renderer->submittedCommandBuffers[i] == commandBuffer) {
  8686. renderer->submittedCommandBuffers[i] = renderer->submittedCommandBuffers[renderer->submittedCommandBufferCount - 1];
  8687. renderer->submittedCommandBufferCount -= 1;
  8688. }
  8689. }
  8690. }
  8691. }
  8692. static bool VULKAN_WaitForFences(
  8693. SDL_GPURenderer *driverData,
  8694. bool waitAll,
  8695. SDL_GPUFence *const *fences,
  8696. Uint32 numFences)
  8697. {
  8698. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8699. VkFence *vkFences = SDL_stack_alloc(VkFence, numFences);
  8700. VkResult result;
  8701. for (Uint32 i = 0; i < numFences; i += 1) {
  8702. vkFences[i] = ((VulkanFenceHandle *)fences[i])->fence;
  8703. }
  8704. result = renderer->vkWaitForFences(
  8705. renderer->logicalDevice,
  8706. numFences,
  8707. vkFences,
  8708. waitAll,
  8709. SDL_MAX_UINT64);
  8710. CHECK_VULKAN_ERROR_AND_RETURN(result, vkWaitForFences, false);
  8711. SDL_stack_free(vkFences);
  8712. SDL_LockMutex(renderer->submitLock);
  8713. for (Sint32 i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  8714. result = renderer->vkGetFenceStatus(
  8715. renderer->logicalDevice,
  8716. renderer->submittedCommandBuffers[i]->inFlightFence->fence);
  8717. if (result == VK_SUCCESS) {
  8718. VULKAN_INTERNAL_CleanCommandBuffer(
  8719. renderer,
  8720. renderer->submittedCommandBuffers[i],
  8721. false);
  8722. }
  8723. }
  8724. VULKAN_INTERNAL_PerformPendingDestroys(renderer);
  8725. SDL_UnlockMutex(renderer->submitLock);
  8726. return true;
  8727. }
  8728. static bool VULKAN_Wait(
  8729. SDL_GPURenderer *driverData)
  8730. {
  8731. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  8732. VulkanCommandBuffer *commandBuffer;
  8733. VkResult result;
  8734. Sint32 i;
  8735. result = renderer->vkDeviceWaitIdle(renderer->logicalDevice);
  8736. CHECK_VULKAN_ERROR_AND_RETURN(result, vkDeviceWaitIdle, false);
  8737. SDL_LockMutex(renderer->submitLock);
  8738. for (i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  8739. commandBuffer = renderer->submittedCommandBuffers[i];
  8740. VULKAN_INTERNAL_CleanCommandBuffer(renderer, commandBuffer, false);
  8741. }
  8742. VULKAN_INTERNAL_PerformPendingDestroys(renderer);
  8743. SDL_UnlockMutex(renderer->submitLock);
  8744. return true;
  8745. }
  8746. static SDL_GPUFence *VULKAN_SubmitAndAcquireFence(
  8747. SDL_GPUCommandBuffer *commandBuffer)
  8748. {
  8749. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  8750. vulkanCommandBuffer->autoReleaseFence = false;
  8751. if (!VULKAN_Submit(commandBuffer)) {
  8752. return NULL;
  8753. }
  8754. return (SDL_GPUFence *)vulkanCommandBuffer->inFlightFence;
  8755. }
  8756. static void VULKAN_INTERNAL_ReleaseCommandBuffer(VulkanCommandBuffer *vulkanCommandBuffer)
  8757. {
  8758. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  8759. if (renderer->submittedCommandBufferCount + 1 >= renderer->submittedCommandBufferCapacity) {
  8760. renderer->submittedCommandBufferCapacity = renderer->submittedCommandBufferCount + 1;
  8761. renderer->submittedCommandBuffers = SDL_realloc(
  8762. renderer->submittedCommandBuffers,
  8763. sizeof(VulkanCommandBuffer *) * renderer->submittedCommandBufferCapacity);
  8764. }
  8765. renderer->submittedCommandBuffers[renderer->submittedCommandBufferCount] = vulkanCommandBuffer;
  8766. renderer->submittedCommandBufferCount += 1;
  8767. }
  8768. static bool VULKAN_Submit(
  8769. SDL_GPUCommandBuffer *commandBuffer)
  8770. {
  8771. VulkanCommandBuffer *vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  8772. VulkanRenderer *renderer = vulkanCommandBuffer->renderer;
  8773. VkSubmitInfo submitInfo;
  8774. VkPresentInfoKHR presentInfo;
  8775. VulkanPresentData *presentData;
  8776. VkResult vulkanResult, presentResult = VK_SUCCESS;
  8777. VkPipelineStageFlags waitStages[MAX_PRESENT_COUNT];
  8778. Uint32 swapchainImageIndex;
  8779. VulkanTextureSubresource *swapchainTextureSubresource;
  8780. VulkanMemorySubAllocator *allocator;
  8781. bool performCleanups =
  8782. (renderer->claimedWindowCount > 0 && vulkanCommandBuffer->presentDataCount > 0) ||
  8783. renderer->claimedWindowCount == 0;
  8784. SDL_LockMutex(renderer->submitLock);
  8785. // FIXME: Can this just be permanent?
  8786. for (Uint32 i = 0; i < MAX_PRESENT_COUNT; i += 1) {
  8787. waitStages[i] = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  8788. }
  8789. for (Uint32 j = 0; j < vulkanCommandBuffer->presentDataCount; j += 1) {
  8790. swapchainImageIndex = vulkanCommandBuffer->presentDatas[j].swapchainImageIndex;
  8791. swapchainTextureSubresource = VULKAN_INTERNAL_FetchTextureSubresource(
  8792. &vulkanCommandBuffer->presentDatas[j].windowData->textureContainers[swapchainImageIndex],
  8793. 0,
  8794. 0);
  8795. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  8796. renderer,
  8797. vulkanCommandBuffer,
  8798. VULKAN_TEXTURE_USAGE_MODE_PRESENT,
  8799. swapchainTextureSubresource);
  8800. }
  8801. if (performCleanups &&
  8802. renderer->allocationsToDefragCount > 0 &&
  8803. !renderer->defragInProgress) {
  8804. if (!VULKAN_INTERNAL_DefragmentMemory(renderer, vulkanCommandBuffer))
  8805. {
  8806. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s", "Failed to defragment memory, likely OOM!");
  8807. }
  8808. }
  8809. if (!VULKAN_INTERNAL_EndCommandBuffer(renderer, vulkanCommandBuffer)) {
  8810. SDL_UnlockMutex(renderer->submitLock);
  8811. return false;
  8812. }
  8813. vulkanCommandBuffer->inFlightFence = VULKAN_INTERNAL_AcquireFenceFromPool(renderer);
  8814. if (vulkanCommandBuffer->inFlightFence == NULL) {
  8815. SDL_UnlockMutex(renderer->submitLock);
  8816. return false;
  8817. }
  8818. // Command buffer has a reference to the in-flight fence
  8819. (void)SDL_AtomicIncRef(&vulkanCommandBuffer->inFlightFence->referenceCount);
  8820. submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  8821. submitInfo.pNext = NULL;
  8822. submitInfo.commandBufferCount = 1;
  8823. submitInfo.pCommandBuffers = &vulkanCommandBuffer->commandBuffer;
  8824. submitInfo.pWaitDstStageMask = waitStages;
  8825. submitInfo.pWaitSemaphores = vulkanCommandBuffer->waitSemaphores;
  8826. submitInfo.waitSemaphoreCount = vulkanCommandBuffer->waitSemaphoreCount;
  8827. submitInfo.pSignalSemaphores = vulkanCommandBuffer->signalSemaphores;
  8828. submitInfo.signalSemaphoreCount = vulkanCommandBuffer->signalSemaphoreCount;
  8829. vulkanResult = renderer->vkQueueSubmit(
  8830. renderer->unifiedQueue,
  8831. 1,
  8832. &submitInfo,
  8833. vulkanCommandBuffer->inFlightFence->fence);
  8834. if (vulkanResult != VK_SUCCESS) {
  8835. SDL_UnlockMutex(renderer->submitLock);
  8836. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkQueueSubmit, false);
  8837. }
  8838. // Present, if applicable
  8839. for (Uint32 j = 0; j < vulkanCommandBuffer->presentDataCount; j += 1) {
  8840. presentData = &vulkanCommandBuffer->presentDatas[j];
  8841. presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
  8842. presentInfo.pNext = NULL;
  8843. presentInfo.pWaitSemaphores =
  8844. &presentData->windowData->renderFinishedSemaphore[presentData->swapchainImageIndex];
  8845. presentInfo.waitSemaphoreCount = 1;
  8846. presentInfo.pSwapchains = &presentData->windowData->swapchain;
  8847. presentInfo.swapchainCount = 1;
  8848. presentInfo.pImageIndices = &presentData->swapchainImageIndex;
  8849. presentInfo.pResults = NULL;
  8850. presentResult = renderer->vkQueuePresentKHR(
  8851. renderer->unifiedQueue,
  8852. &presentInfo);
  8853. if (presentResult == VK_SUCCESS || presentResult == VK_SUBOPTIMAL_KHR || presentResult == VK_ERROR_OUT_OF_DATE_KHR) {
  8854. // If presenting, the swapchain is using the in-flight fence
  8855. presentData->windowData->inFlightFences[presentData->windowData->frameCounter] = (SDL_GPUFence*)vulkanCommandBuffer->inFlightFence;
  8856. (void)SDL_AtomicIncRef(&vulkanCommandBuffer->inFlightFence->referenceCount);
  8857. if (presentResult == VK_SUBOPTIMAL_KHR || presentResult == VK_ERROR_OUT_OF_DATE_KHR) {
  8858. presentData->windowData->needsSwapchainRecreate = true;
  8859. }
  8860. } else {
  8861. if (presentResult != VK_SUCCESS) {
  8862. VULKAN_INTERNAL_ReleaseCommandBuffer(vulkanCommandBuffer);
  8863. SDL_UnlockMutex(renderer->submitLock);
  8864. }
  8865. CHECK_VULKAN_ERROR_AND_RETURN(presentResult, vkQueuePresentKHR, false);
  8866. }
  8867. presentData->windowData->frameCounter =
  8868. (presentData->windowData->frameCounter + 1) % renderer->allowedFramesInFlight;
  8869. }
  8870. if (performCleanups) {
  8871. for (Sint32 i = renderer->submittedCommandBufferCount - 1; i >= 0; i -= 1) {
  8872. vulkanResult = renderer->vkGetFenceStatus(
  8873. renderer->logicalDevice,
  8874. renderer->submittedCommandBuffers[i]->inFlightFence->fence);
  8875. if (vulkanResult == VK_SUCCESS) {
  8876. VULKAN_INTERNAL_CleanCommandBuffer(
  8877. renderer,
  8878. renderer->submittedCommandBuffers[i],
  8879. false);
  8880. }
  8881. }
  8882. if (renderer->checkEmptyAllocations) {
  8883. SDL_LockMutex(renderer->allocatorLock);
  8884. for (Uint32 i = 0; i < VK_MAX_MEMORY_TYPES; i += 1) {
  8885. allocator = &renderer->memoryAllocator->subAllocators[i];
  8886. for (Sint32 j = allocator->allocationCount - 1; j >= 0; j -= 1) {
  8887. if (allocator->allocations[j]->usedRegionCount == 0) {
  8888. VULKAN_INTERNAL_DeallocateMemory(
  8889. renderer,
  8890. allocator,
  8891. j);
  8892. }
  8893. }
  8894. }
  8895. renderer->checkEmptyAllocations = false;
  8896. SDL_UnlockMutex(renderer->allocatorLock);
  8897. }
  8898. VULKAN_INTERNAL_PerformPendingDestroys(renderer);
  8899. }
  8900. // Mark command buffer as submitted
  8901. VULKAN_INTERNAL_ReleaseCommandBuffer(vulkanCommandBuffer);
  8902. SDL_UnlockMutex(renderer->submitLock);
  8903. return true;
  8904. }
  8905. static bool VULKAN_Cancel(
  8906. SDL_GPUCommandBuffer *commandBuffer)
  8907. {
  8908. VulkanRenderer *renderer;
  8909. VulkanCommandBuffer *vulkanCommandBuffer;
  8910. VkResult result;
  8911. vulkanCommandBuffer = (VulkanCommandBuffer *)commandBuffer;
  8912. renderer = vulkanCommandBuffer->renderer;
  8913. result = renderer->vkResetCommandBuffer(
  8914. vulkanCommandBuffer->commandBuffer,
  8915. VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT);
  8916. CHECK_VULKAN_ERROR_AND_RETURN(result, vkResetCommandBuffer, false);
  8917. vulkanCommandBuffer->autoReleaseFence = false;
  8918. SDL_LockMutex(renderer->submitLock);
  8919. VULKAN_INTERNAL_CleanCommandBuffer(renderer, vulkanCommandBuffer, true);
  8920. SDL_UnlockMutex(renderer->submitLock);
  8921. return true;
  8922. }
  8923. static bool VULKAN_INTERNAL_DefragmentMemory(
  8924. VulkanRenderer *renderer,
  8925. VulkanCommandBuffer *commandBuffer)
  8926. {
  8927. renderer->defragInProgress = 1;
  8928. commandBuffer->isDefrag = 1;
  8929. SDL_LockMutex(renderer->allocatorLock);
  8930. VulkanMemoryAllocation *allocation = renderer->allocationsToDefrag[renderer->allocationsToDefragCount - 1];
  8931. renderer->allocationsToDefragCount -= 1;
  8932. /* For each used region in the allocation
  8933. * create a new resource, copy the data
  8934. * and re-point the resource containers
  8935. */
  8936. for (Uint32 i = 0; i < allocation->usedRegionCount; i += 1) {
  8937. VulkanMemoryUsedRegion *currentRegion = allocation->usedRegions[i];
  8938. if (currentRegion->isBuffer && !currentRegion->vulkanBuffer->markedForDestroy) {
  8939. currentRegion->vulkanBuffer->usage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  8940. VulkanBuffer *newBuffer = VULKAN_INTERNAL_CreateBuffer(
  8941. renderer,
  8942. currentRegion->vulkanBuffer->size,
  8943. currentRegion->vulkanBuffer->usage,
  8944. currentRegion->vulkanBuffer->type,
  8945. false,
  8946. currentRegion->vulkanBuffer->container != NULL ? currentRegion->vulkanBuffer->container->debugName : NULL);
  8947. if (newBuffer == NULL) {
  8948. SDL_UnlockMutex(renderer->allocatorLock);
  8949. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s", "Failed to allocate defrag buffer!");
  8950. return false;
  8951. }
  8952. // Copy buffer contents if necessary
  8953. if (
  8954. currentRegion->vulkanBuffer->type == VULKAN_BUFFER_TYPE_GPU && currentRegion->vulkanBuffer->transitioned) {
  8955. VULKAN_INTERNAL_BufferTransitionFromDefaultUsage(
  8956. renderer,
  8957. commandBuffer,
  8958. VULKAN_BUFFER_USAGE_MODE_COPY_SOURCE,
  8959. currentRegion->vulkanBuffer);
  8960. VULKAN_INTERNAL_BufferTransitionFromDefaultUsage(
  8961. renderer,
  8962. commandBuffer,
  8963. VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION,
  8964. newBuffer);
  8965. VkBufferCopy bufferCopy;
  8966. bufferCopy.srcOffset = 0;
  8967. bufferCopy.dstOffset = 0;
  8968. bufferCopy.size = currentRegion->resourceSize;
  8969. renderer->vkCmdCopyBuffer(
  8970. commandBuffer->commandBuffer,
  8971. currentRegion->vulkanBuffer->buffer,
  8972. newBuffer->buffer,
  8973. 1,
  8974. &bufferCopy);
  8975. VULKAN_INTERNAL_BufferTransitionToDefaultUsage(
  8976. renderer,
  8977. commandBuffer,
  8978. VULKAN_BUFFER_USAGE_MODE_COPY_DESTINATION,
  8979. newBuffer);
  8980. VULKAN_INTERNAL_TrackBuffer(commandBuffer, currentRegion->vulkanBuffer);
  8981. VULKAN_INTERNAL_TrackBuffer(commandBuffer, newBuffer);
  8982. }
  8983. // re-point original container to new buffer
  8984. newBuffer->container = currentRegion->vulkanBuffer->container;
  8985. newBuffer->containerIndex = currentRegion->vulkanBuffer->containerIndex;
  8986. if (newBuffer->type == VULKAN_BUFFER_TYPE_UNIFORM) {
  8987. currentRegion->vulkanBuffer->uniformBufferForDefrag->buffer = newBuffer;
  8988. } else {
  8989. newBuffer->container->buffers[newBuffer->containerIndex] = newBuffer;
  8990. if (newBuffer->container->activeBuffer == currentRegion->vulkanBuffer) {
  8991. newBuffer->container->activeBuffer = newBuffer;
  8992. }
  8993. }
  8994. if (currentRegion->vulkanBuffer->uniformBufferForDefrag) {
  8995. newBuffer->uniformBufferForDefrag = currentRegion->vulkanBuffer->uniformBufferForDefrag;
  8996. }
  8997. VULKAN_INTERNAL_ReleaseBuffer(renderer, currentRegion->vulkanBuffer);
  8998. } else if (!currentRegion->isBuffer && !currentRegion->vulkanTexture->markedForDestroy) {
  8999. VulkanTexture *newTexture = VULKAN_INTERNAL_CreateTexture(
  9000. renderer,
  9001. false,
  9002. &currentRegion->vulkanTexture->container->header.info);
  9003. if (newTexture == NULL) {
  9004. SDL_UnlockMutex(renderer->allocatorLock);
  9005. SDL_LogError(SDL_LOG_CATEGORY_GPU, "%s", "Failed to allocate defrag buffer!");
  9006. return false;
  9007. }
  9008. SDL_GPUTextureCreateInfo info = currentRegion->vulkanTexture->container->header.info;
  9009. for (Uint32 subresourceIndex = 0; subresourceIndex < currentRegion->vulkanTexture->subresourceCount; subresourceIndex += 1) {
  9010. // copy subresource if necessary
  9011. VulkanTextureSubresource *srcSubresource = &currentRegion->vulkanTexture->subresources[subresourceIndex];
  9012. VulkanTextureSubresource *dstSubresource = &newTexture->subresources[subresourceIndex];
  9013. VULKAN_INTERNAL_TextureSubresourceTransitionFromDefaultUsage(
  9014. renderer,
  9015. commandBuffer,
  9016. VULKAN_TEXTURE_USAGE_MODE_COPY_SOURCE,
  9017. srcSubresource);
  9018. VULKAN_INTERNAL_TextureSubresourceMemoryBarrier(
  9019. renderer,
  9020. commandBuffer,
  9021. VULKAN_TEXTURE_USAGE_MODE_UNINITIALIZED,
  9022. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  9023. dstSubresource);
  9024. VkImageCopy imageCopy;
  9025. imageCopy.srcOffset.x = 0;
  9026. imageCopy.srcOffset.y = 0;
  9027. imageCopy.srcOffset.z = 0;
  9028. imageCopy.srcSubresource.aspectMask = srcSubresource->parent->aspectFlags;
  9029. imageCopy.srcSubresource.baseArrayLayer = srcSubresource->layer;
  9030. imageCopy.srcSubresource.layerCount = 1;
  9031. imageCopy.srcSubresource.mipLevel = srcSubresource->level;
  9032. imageCopy.extent.width = SDL_max(1, info.width >> srcSubresource->level);
  9033. imageCopy.extent.height = SDL_max(1, info.height >> srcSubresource->level);
  9034. imageCopy.extent.depth = info.type == SDL_GPU_TEXTURETYPE_3D ? info.layer_count_or_depth : 1;
  9035. imageCopy.dstOffset.x = 0;
  9036. imageCopy.dstOffset.y = 0;
  9037. imageCopy.dstOffset.z = 0;
  9038. imageCopy.dstSubresource.aspectMask = dstSubresource->parent->aspectFlags;
  9039. imageCopy.dstSubresource.baseArrayLayer = dstSubresource->layer;
  9040. imageCopy.dstSubresource.layerCount = 1;
  9041. imageCopy.dstSubresource.mipLevel = dstSubresource->level;
  9042. renderer->vkCmdCopyImage(
  9043. commandBuffer->commandBuffer,
  9044. currentRegion->vulkanTexture->image,
  9045. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  9046. newTexture->image,
  9047. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  9048. 1,
  9049. &imageCopy);
  9050. VULKAN_INTERNAL_TextureSubresourceTransitionToDefaultUsage(
  9051. renderer,
  9052. commandBuffer,
  9053. VULKAN_TEXTURE_USAGE_MODE_COPY_DESTINATION,
  9054. dstSubresource);
  9055. VULKAN_INTERNAL_TrackTexture(commandBuffer, srcSubresource->parent);
  9056. VULKAN_INTERNAL_TrackTexture(commandBuffer, dstSubresource->parent);
  9057. }
  9058. // re-point original container to new texture
  9059. newTexture->container = currentRegion->vulkanTexture->container;
  9060. newTexture->containerIndex = currentRegion->vulkanTexture->containerIndex;
  9061. newTexture->container->textures[currentRegion->vulkanTexture->containerIndex] = newTexture;
  9062. if (currentRegion->vulkanTexture == currentRegion->vulkanTexture->container->activeTexture) {
  9063. newTexture->container->activeTexture = newTexture;
  9064. }
  9065. VULKAN_INTERNAL_ReleaseTexture(renderer, currentRegion->vulkanTexture);
  9066. }
  9067. }
  9068. SDL_UnlockMutex(renderer->allocatorLock);
  9069. return true;
  9070. }
  9071. // Format Info
  9072. static bool VULKAN_SupportsTextureFormat(
  9073. SDL_GPURenderer *driverData,
  9074. SDL_GPUTextureFormat format,
  9075. SDL_GPUTextureType type,
  9076. SDL_GPUTextureUsageFlags usage)
  9077. {
  9078. VulkanRenderer *renderer = (VulkanRenderer *)driverData;
  9079. VkFormat vulkanFormat = SDLToVK_TextureFormat[format];
  9080. VkImageUsageFlags vulkanUsage = 0;
  9081. VkImageCreateFlags createFlags = 0;
  9082. VkImageFormatProperties properties;
  9083. VkResult vulkanResult;
  9084. if (usage & SDL_GPU_TEXTUREUSAGE_SAMPLER) {
  9085. vulkanUsage |= VK_IMAGE_USAGE_SAMPLED_BIT;
  9086. }
  9087. if (usage & SDL_GPU_TEXTUREUSAGE_COLOR_TARGET) {
  9088. vulkanUsage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  9089. }
  9090. if (usage & SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET) {
  9091. vulkanUsage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  9092. }
  9093. if (usage & (SDL_GPU_TEXTUREUSAGE_GRAPHICS_STORAGE_READ |
  9094. SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_READ |
  9095. SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_WRITE |
  9096. SDL_GPU_TEXTUREUSAGE_COMPUTE_STORAGE_SIMULTANEOUS_READ_WRITE)) {
  9097. vulkanUsage |= VK_IMAGE_USAGE_STORAGE_BIT;
  9098. }
  9099. if (type == SDL_GPU_TEXTURETYPE_CUBE || type == SDL_GPU_TEXTURETYPE_CUBE_ARRAY) {
  9100. createFlags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
  9101. }
  9102. vulkanResult = renderer->vkGetPhysicalDeviceImageFormatProperties(
  9103. renderer->physicalDevice,
  9104. vulkanFormat,
  9105. (type == SDL_GPU_TEXTURETYPE_3D) ? VK_IMAGE_TYPE_3D : VK_IMAGE_TYPE_2D,
  9106. VK_IMAGE_TILING_OPTIMAL,
  9107. vulkanUsage,
  9108. createFlags,
  9109. &properties);
  9110. return vulkanResult == VK_SUCCESS;
  9111. }
  9112. // Device instantiation
  9113. static inline Uint8 CheckDeviceExtensions(
  9114. VkExtensionProperties *extensions,
  9115. Uint32 numExtensions,
  9116. VulkanExtensions *supports)
  9117. {
  9118. Uint32 i;
  9119. SDL_memset(supports, '\0', sizeof(VulkanExtensions));
  9120. for (i = 0; i < numExtensions; i += 1) {
  9121. const char *name = extensions[i].extensionName;
  9122. #define CHECK(ext) \
  9123. if (SDL_strcmp(name, "VK_" #ext) == 0) { \
  9124. supports->ext = 1; \
  9125. }
  9126. CHECK(KHR_swapchain)
  9127. else CHECK(KHR_maintenance1) else CHECK(KHR_driver_properties) else CHECK(KHR_portability_subset) else CHECK(EXT_texture_compression_astc_hdr)
  9128. #undef CHECK
  9129. }
  9130. return (supports->KHR_swapchain &&
  9131. supports->KHR_maintenance1);
  9132. }
  9133. static inline Uint32 GetDeviceExtensionCount(VulkanExtensions *supports)
  9134. {
  9135. return (
  9136. supports->KHR_swapchain +
  9137. supports->KHR_maintenance1 +
  9138. supports->KHR_driver_properties +
  9139. supports->KHR_portability_subset +
  9140. supports->EXT_texture_compression_astc_hdr);
  9141. }
  9142. static inline void CreateDeviceExtensionArray(
  9143. VulkanExtensions *supports,
  9144. const char **extensions)
  9145. {
  9146. Uint8 cur = 0;
  9147. #define CHECK(ext) \
  9148. if (supports->ext) { \
  9149. extensions[cur++] = "VK_" #ext; \
  9150. }
  9151. CHECK(KHR_swapchain)
  9152. CHECK(KHR_maintenance1)
  9153. CHECK(KHR_driver_properties)
  9154. CHECK(KHR_portability_subset)
  9155. CHECK(EXT_texture_compression_astc_hdr)
  9156. #undef CHECK
  9157. }
  9158. static inline Uint8 SupportsInstanceExtension(
  9159. const char *ext,
  9160. VkExtensionProperties *availableExtensions,
  9161. Uint32 numAvailableExtensions)
  9162. {
  9163. Uint32 i;
  9164. for (i = 0; i < numAvailableExtensions; i += 1) {
  9165. if (SDL_strcmp(ext, availableExtensions[i].extensionName) == 0) {
  9166. return 1;
  9167. }
  9168. }
  9169. return 0;
  9170. }
  9171. static Uint8 VULKAN_INTERNAL_CheckInstanceExtensions(
  9172. const char **requiredExtensions,
  9173. Uint32 requiredExtensionsLength,
  9174. bool *supportsDebugUtils,
  9175. bool *supportsColorspace)
  9176. {
  9177. Uint32 extensionCount, i;
  9178. VkExtensionProperties *availableExtensions;
  9179. Uint8 allExtensionsSupported = 1;
  9180. vkEnumerateInstanceExtensionProperties(
  9181. NULL,
  9182. &extensionCount,
  9183. NULL);
  9184. availableExtensions = SDL_malloc(
  9185. extensionCount * sizeof(VkExtensionProperties));
  9186. vkEnumerateInstanceExtensionProperties(
  9187. NULL,
  9188. &extensionCount,
  9189. availableExtensions);
  9190. for (i = 0; i < requiredExtensionsLength; i += 1) {
  9191. if (!SupportsInstanceExtension(
  9192. requiredExtensions[i],
  9193. availableExtensions,
  9194. extensionCount)) {
  9195. allExtensionsSupported = 0;
  9196. break;
  9197. }
  9198. }
  9199. // This is optional, but nice to have!
  9200. *supportsDebugUtils = SupportsInstanceExtension(
  9201. VK_EXT_DEBUG_UTILS_EXTENSION_NAME,
  9202. availableExtensions,
  9203. extensionCount);
  9204. // Also optional and nice to have!
  9205. *supportsColorspace = SupportsInstanceExtension(
  9206. VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME,
  9207. availableExtensions,
  9208. extensionCount);
  9209. SDL_free(availableExtensions);
  9210. return allExtensionsSupported;
  9211. }
  9212. static Uint8 VULKAN_INTERNAL_CheckDeviceExtensions(
  9213. VulkanRenderer *renderer,
  9214. VkPhysicalDevice physicalDevice,
  9215. VulkanExtensions *physicalDeviceExtensions)
  9216. {
  9217. Uint32 extensionCount;
  9218. VkExtensionProperties *availableExtensions;
  9219. Uint8 allExtensionsSupported;
  9220. renderer->vkEnumerateDeviceExtensionProperties(
  9221. physicalDevice,
  9222. NULL,
  9223. &extensionCount,
  9224. NULL);
  9225. availableExtensions = (VkExtensionProperties *)SDL_malloc(
  9226. extensionCount * sizeof(VkExtensionProperties));
  9227. renderer->vkEnumerateDeviceExtensionProperties(
  9228. physicalDevice,
  9229. NULL,
  9230. &extensionCount,
  9231. availableExtensions);
  9232. allExtensionsSupported = CheckDeviceExtensions(
  9233. availableExtensions,
  9234. extensionCount,
  9235. physicalDeviceExtensions);
  9236. SDL_free(availableExtensions);
  9237. return allExtensionsSupported;
  9238. }
  9239. static Uint8 VULKAN_INTERNAL_CheckValidationLayers(
  9240. const char **validationLayers,
  9241. Uint32 validationLayersLength)
  9242. {
  9243. Uint32 layerCount;
  9244. VkLayerProperties *availableLayers;
  9245. Uint32 i, j;
  9246. Uint8 layerFound = 0;
  9247. vkEnumerateInstanceLayerProperties(&layerCount, NULL);
  9248. availableLayers = (VkLayerProperties *)SDL_malloc(
  9249. layerCount * sizeof(VkLayerProperties));
  9250. vkEnumerateInstanceLayerProperties(&layerCount, availableLayers);
  9251. for (i = 0; i < validationLayersLength; i += 1) {
  9252. layerFound = 0;
  9253. for (j = 0; j < layerCount; j += 1) {
  9254. if (SDL_strcmp(validationLayers[i], availableLayers[j].layerName) == 0) {
  9255. layerFound = 1;
  9256. break;
  9257. }
  9258. }
  9259. if (!layerFound) {
  9260. break;
  9261. }
  9262. }
  9263. SDL_free(availableLayers);
  9264. return layerFound;
  9265. }
  9266. static Uint8 VULKAN_INTERNAL_CreateInstance(VulkanRenderer *renderer)
  9267. {
  9268. VkResult vulkanResult;
  9269. VkApplicationInfo appInfo;
  9270. VkInstanceCreateFlags createFlags;
  9271. const char *const *originalInstanceExtensionNames;
  9272. const char **instanceExtensionNames;
  9273. Uint32 instanceExtensionCount;
  9274. VkInstanceCreateInfo createInfo;
  9275. static const char *layerNames[] = { "VK_LAYER_KHRONOS_validation" };
  9276. appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  9277. appInfo.pNext = NULL;
  9278. appInfo.pApplicationName = NULL;
  9279. appInfo.applicationVersion = 0;
  9280. appInfo.pEngineName = "SDLGPU";
  9281. appInfo.engineVersion = SDL_VERSION;
  9282. appInfo.apiVersion = VK_MAKE_VERSION(1, 0, 0);
  9283. createFlags = 0;
  9284. originalInstanceExtensionNames = SDL_Vulkan_GetInstanceExtensions(&instanceExtensionCount);
  9285. if (!originalInstanceExtensionNames) {
  9286. SDL_LogError(
  9287. SDL_LOG_CATEGORY_GPU,
  9288. "SDL_Vulkan_GetInstanceExtensions(): getExtensionCount: %s",
  9289. SDL_GetError());
  9290. return 0;
  9291. }
  9292. /* Extra space for the following extensions:
  9293. * VK_KHR_get_physical_device_properties2
  9294. * VK_EXT_swapchain_colorspace
  9295. * VK_EXT_debug_utils
  9296. * VK_KHR_portability_enumeration
  9297. */
  9298. instanceExtensionNames = SDL_stack_alloc(
  9299. const char *,
  9300. instanceExtensionCount + 4);
  9301. SDL_memcpy((void *)instanceExtensionNames, originalInstanceExtensionNames, instanceExtensionCount * sizeof(const char *));
  9302. // Core since 1.1
  9303. instanceExtensionNames[instanceExtensionCount++] =
  9304. VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME;
  9305. #ifdef SDL_PLATFORM_APPLE
  9306. instanceExtensionNames[instanceExtensionCount++] =
  9307. VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME;
  9308. createFlags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
  9309. #endif
  9310. if (!VULKAN_INTERNAL_CheckInstanceExtensions(
  9311. instanceExtensionNames,
  9312. instanceExtensionCount,
  9313. &renderer->supportsDebugUtils,
  9314. &renderer->supportsColorspace)) {
  9315. SDL_stack_free((char *)instanceExtensionNames);
  9316. SET_STRING_ERROR_AND_RETURN("Required Vulkan instance extensions not supported", false);
  9317. }
  9318. if (renderer->supportsDebugUtils) {
  9319. // Append the debug extension
  9320. instanceExtensionNames[instanceExtensionCount++] =
  9321. VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
  9322. } else {
  9323. SDL_LogWarn(
  9324. SDL_LOG_CATEGORY_GPU,
  9325. "%s is not supported!",
  9326. VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
  9327. }
  9328. if (renderer->supportsColorspace) {
  9329. // Append colorspace extension
  9330. instanceExtensionNames[instanceExtensionCount++] =
  9331. VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME;
  9332. }
  9333. createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  9334. createInfo.pNext = NULL;
  9335. createInfo.flags = createFlags;
  9336. createInfo.pApplicationInfo = &appInfo;
  9337. createInfo.ppEnabledLayerNames = layerNames;
  9338. createInfo.enabledExtensionCount = instanceExtensionCount;
  9339. createInfo.ppEnabledExtensionNames = instanceExtensionNames;
  9340. if (renderer->debugMode) {
  9341. createInfo.enabledLayerCount = SDL_arraysize(layerNames);
  9342. if (!VULKAN_INTERNAL_CheckValidationLayers(
  9343. layerNames,
  9344. createInfo.enabledLayerCount)) {
  9345. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Validation layers not found, continuing without validation");
  9346. createInfo.enabledLayerCount = 0;
  9347. } else {
  9348. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "Validation layers enabled, expect debug level performance!");
  9349. }
  9350. } else {
  9351. createInfo.enabledLayerCount = 0;
  9352. }
  9353. vulkanResult = vkCreateInstance(&createInfo, NULL, &renderer->instance);
  9354. SDL_stack_free((char *)instanceExtensionNames);
  9355. if (vulkanResult != VK_SUCCESS) {
  9356. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateInstance, 0);
  9357. }
  9358. return 1;
  9359. }
  9360. static Uint8 VULKAN_INTERNAL_IsDeviceSuitable(
  9361. VulkanRenderer *renderer,
  9362. VkPhysicalDevice physicalDevice,
  9363. VulkanExtensions *physicalDeviceExtensions,
  9364. Uint32 *queueFamilyIndex,
  9365. Uint8 *deviceRank)
  9366. {
  9367. Uint32 queueFamilyCount, queueFamilyRank, queueFamilyBest;
  9368. VkQueueFamilyProperties *queueProps;
  9369. bool supportsPresent;
  9370. VkPhysicalDeviceProperties deviceProperties;
  9371. VkPhysicalDeviceFeatures deviceFeatures;
  9372. Uint32 i;
  9373. const Uint8 *devicePriority = renderer->preferLowPower ? DEVICE_PRIORITY_LOWPOWER : DEVICE_PRIORITY_HIGHPERFORMANCE;
  9374. /* Get the device rank before doing any checks, in case one fails.
  9375. * Note: If no dedicated device exists, one that supports our features
  9376. * would be fine
  9377. */
  9378. renderer->vkGetPhysicalDeviceProperties(
  9379. physicalDevice,
  9380. &deviceProperties);
  9381. if (*deviceRank < devicePriority[deviceProperties.deviceType]) {
  9382. /* This device outranks the best device we've found so far!
  9383. * This includes a dedicated GPU that has less features than an
  9384. * integrated GPU, because this is a freak case that is almost
  9385. * never intentionally desired by the end user
  9386. */
  9387. *deviceRank = devicePriority[deviceProperties.deviceType];
  9388. } else if (*deviceRank > devicePriority[deviceProperties.deviceType]) {
  9389. /* Device is outranked by a previous device, don't even try to
  9390. * run a query and reset the rank to avoid overwrites
  9391. */
  9392. *deviceRank = 0;
  9393. return 0;
  9394. }
  9395. renderer->vkGetPhysicalDeviceFeatures(
  9396. physicalDevice,
  9397. &deviceFeatures);
  9398. if (!deviceFeatures.independentBlend ||
  9399. !deviceFeatures.imageCubeArray ||
  9400. !deviceFeatures.depthClamp ||
  9401. !deviceFeatures.shaderClipDistance ||
  9402. !deviceFeatures.drawIndirectFirstInstance) {
  9403. return 0;
  9404. }
  9405. if (!VULKAN_INTERNAL_CheckDeviceExtensions(
  9406. renderer,
  9407. physicalDevice,
  9408. physicalDeviceExtensions)) {
  9409. return 0;
  9410. }
  9411. renderer->vkGetPhysicalDeviceQueueFamilyProperties(
  9412. physicalDevice,
  9413. &queueFamilyCount,
  9414. NULL);
  9415. queueProps = SDL_stack_alloc(
  9416. VkQueueFamilyProperties,
  9417. queueFamilyCount);
  9418. renderer->vkGetPhysicalDeviceQueueFamilyProperties(
  9419. physicalDevice,
  9420. &queueFamilyCount,
  9421. queueProps);
  9422. queueFamilyBest = 0;
  9423. *queueFamilyIndex = SDL_MAX_UINT32;
  9424. for (i = 0; i < queueFamilyCount; i += 1) {
  9425. supportsPresent = SDL_Vulkan_GetPresentationSupport(
  9426. renderer->instance,
  9427. physicalDevice,
  9428. i);
  9429. if (!supportsPresent ||
  9430. !(queueProps[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) {
  9431. // Not a graphics family, ignore.
  9432. continue;
  9433. }
  9434. /* The queue family bitflags are kind of annoying.
  9435. *
  9436. * We of course need a graphics family, but we ideally want the
  9437. * _primary_ graphics family. The spec states that at least one
  9438. * graphics family must also be a compute family, so generally
  9439. * drivers make that the first one. But hey, maybe something
  9440. * genuinely can't do compute or something, and FNA doesn't
  9441. * need it, so we'll be open to a non-compute queue family.
  9442. *
  9443. * Additionally, it's common to see the primary queue family
  9444. * have the transfer bit set, which is great! But this is
  9445. * actually optional; it's impossible to NOT have transfers in
  9446. * graphics/compute but it _is_ possible for a graphics/compute
  9447. * family, even the primary one, to just decide not to set the
  9448. * bitflag. Admittedly, a driver may want to isolate transfer
  9449. * queues to a dedicated family so that queues made solely for
  9450. * transfers can have an optimized DMA queue.
  9451. *
  9452. * That, or the driver author got lazy and decided not to set
  9453. * the bit. Looking at you, Android.
  9454. *
  9455. * -flibit
  9456. */
  9457. if (queueProps[i].queueFlags & VK_QUEUE_COMPUTE_BIT) {
  9458. if (queueProps[i].queueFlags & VK_QUEUE_TRANSFER_BIT) {
  9459. // Has all attribs!
  9460. queueFamilyRank = 3;
  9461. } else {
  9462. // Probably has a DMA transfer queue family
  9463. queueFamilyRank = 2;
  9464. }
  9465. } else {
  9466. // Just a graphics family, probably has something better
  9467. queueFamilyRank = 1;
  9468. }
  9469. if (queueFamilyRank > queueFamilyBest) {
  9470. *queueFamilyIndex = i;
  9471. queueFamilyBest = queueFamilyRank;
  9472. }
  9473. }
  9474. SDL_stack_free(queueProps);
  9475. if (*queueFamilyIndex == SDL_MAX_UINT32) {
  9476. // Somehow no graphics queues existed. Compute-only device?
  9477. return 0;
  9478. }
  9479. // FIXME: Need better structure for checking vs storing swapchain support details
  9480. return 1;
  9481. }
  9482. static Uint8 VULKAN_INTERNAL_DeterminePhysicalDevice(VulkanRenderer *renderer)
  9483. {
  9484. VkResult vulkanResult;
  9485. VkPhysicalDevice *physicalDevices;
  9486. VulkanExtensions *physicalDeviceExtensions;
  9487. Uint32 i, physicalDeviceCount;
  9488. Sint32 suitableIndex;
  9489. Uint32 queueFamilyIndex, suitableQueueFamilyIndex;
  9490. Uint8 deviceRank, highestRank;
  9491. vulkanResult = renderer->vkEnumeratePhysicalDevices(
  9492. renderer->instance,
  9493. &physicalDeviceCount,
  9494. NULL);
  9495. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkEnumeratePhysicalDevices, 0);
  9496. if (physicalDeviceCount == 0) {
  9497. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "Failed to find any GPUs with Vulkan support");
  9498. return 0;
  9499. }
  9500. physicalDevices = SDL_stack_alloc(VkPhysicalDevice, physicalDeviceCount);
  9501. physicalDeviceExtensions = SDL_stack_alloc(VulkanExtensions, physicalDeviceCount);
  9502. vulkanResult = renderer->vkEnumeratePhysicalDevices(
  9503. renderer->instance,
  9504. &physicalDeviceCount,
  9505. physicalDevices);
  9506. /* This should be impossible to hit, but from what I can tell this can
  9507. * be triggered not because the array is too small, but because there
  9508. * were drivers that turned out to be bogus, so this is the loader's way
  9509. * of telling us that the list is now smaller than expected :shrug:
  9510. */
  9511. if (vulkanResult == VK_INCOMPLETE) {
  9512. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "vkEnumeratePhysicalDevices returned VK_INCOMPLETE, will keep trying anyway...");
  9513. vulkanResult = VK_SUCCESS;
  9514. }
  9515. if (vulkanResult != VK_SUCCESS) {
  9516. SDL_LogWarn(
  9517. SDL_LOG_CATEGORY_GPU,
  9518. "vkEnumeratePhysicalDevices failed: %s",
  9519. VkErrorMessages(vulkanResult));
  9520. SDL_stack_free(physicalDevices);
  9521. SDL_stack_free(physicalDeviceExtensions);
  9522. return 0;
  9523. }
  9524. // Any suitable device will do, but we'd like the best
  9525. suitableIndex = -1;
  9526. suitableQueueFamilyIndex = 0;
  9527. highestRank = 0;
  9528. for (i = 0; i < physicalDeviceCount; i += 1) {
  9529. deviceRank = highestRank;
  9530. if (VULKAN_INTERNAL_IsDeviceSuitable(
  9531. renderer,
  9532. physicalDevices[i],
  9533. &physicalDeviceExtensions[i],
  9534. &queueFamilyIndex,
  9535. &deviceRank)) {
  9536. /* Use this for rendering.
  9537. * Note that this may override a previous device that
  9538. * supports rendering, but shares the same device rank.
  9539. */
  9540. suitableIndex = i;
  9541. suitableQueueFamilyIndex = queueFamilyIndex;
  9542. highestRank = deviceRank;
  9543. } else if (deviceRank > highestRank) {
  9544. /* In this case, we found a... "realer?" GPU,
  9545. * but it doesn't actually support our Vulkan.
  9546. * We should disqualify all devices below as a
  9547. * result, because if we don't we end up
  9548. * ignoring real hardware and risk using
  9549. * something like LLVMpipe instead!
  9550. * -flibit
  9551. */
  9552. suitableIndex = -1;
  9553. highestRank = deviceRank;
  9554. }
  9555. }
  9556. if (suitableIndex != -1) {
  9557. renderer->supports = physicalDeviceExtensions[suitableIndex];
  9558. renderer->physicalDevice = physicalDevices[suitableIndex];
  9559. renderer->queueFamilyIndex = suitableQueueFamilyIndex;
  9560. } else {
  9561. SDL_stack_free(physicalDevices);
  9562. SDL_stack_free(physicalDeviceExtensions);
  9563. return 0;
  9564. }
  9565. renderer->physicalDeviceProperties.sType =
  9566. VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
  9567. if (renderer->supports.KHR_driver_properties) {
  9568. renderer->physicalDeviceDriverProperties.sType =
  9569. VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
  9570. renderer->physicalDeviceDriverProperties.pNext = NULL;
  9571. renderer->physicalDeviceProperties.pNext =
  9572. &renderer->physicalDeviceDriverProperties;
  9573. renderer->vkGetPhysicalDeviceProperties2KHR(
  9574. renderer->physicalDevice,
  9575. &renderer->physicalDeviceProperties);
  9576. } else {
  9577. renderer->physicalDeviceProperties.pNext = NULL;
  9578. renderer->vkGetPhysicalDeviceProperties(
  9579. renderer->physicalDevice,
  9580. &renderer->physicalDeviceProperties.properties);
  9581. }
  9582. renderer->vkGetPhysicalDeviceMemoryProperties(
  9583. renderer->physicalDevice,
  9584. &renderer->memoryProperties);
  9585. SDL_stack_free(physicalDevices);
  9586. SDL_stack_free(physicalDeviceExtensions);
  9587. return 1;
  9588. }
  9589. static Uint8 VULKAN_INTERNAL_CreateLogicalDevice(
  9590. VulkanRenderer *renderer)
  9591. {
  9592. VkResult vulkanResult;
  9593. VkDeviceCreateInfo deviceCreateInfo;
  9594. VkPhysicalDeviceFeatures desiredDeviceFeatures;
  9595. VkPhysicalDeviceFeatures haveDeviceFeatures;
  9596. VkPhysicalDevicePortabilitySubsetFeaturesKHR portabilityFeatures;
  9597. const char **deviceExtensions;
  9598. VkDeviceQueueCreateInfo queueCreateInfo;
  9599. float queuePriority = 1.0f;
  9600. queueCreateInfo.sType =
  9601. VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  9602. queueCreateInfo.pNext = NULL;
  9603. queueCreateInfo.flags = 0;
  9604. queueCreateInfo.queueFamilyIndex = renderer->queueFamilyIndex;
  9605. queueCreateInfo.queueCount = 1;
  9606. queueCreateInfo.pQueuePriorities = &queuePriority;
  9607. // check feature support
  9608. renderer->vkGetPhysicalDeviceFeatures(
  9609. renderer->physicalDevice,
  9610. &haveDeviceFeatures);
  9611. // specifying used device features
  9612. SDL_zero(desiredDeviceFeatures);
  9613. desiredDeviceFeatures.independentBlend = VK_TRUE;
  9614. desiredDeviceFeatures.samplerAnisotropy = VK_TRUE;
  9615. desiredDeviceFeatures.imageCubeArray = VK_TRUE;
  9616. desiredDeviceFeatures.depthClamp = VK_TRUE;
  9617. desiredDeviceFeatures.shaderClipDistance = VK_TRUE;
  9618. desiredDeviceFeatures.drawIndirectFirstInstance = VK_TRUE;
  9619. if (haveDeviceFeatures.fillModeNonSolid) {
  9620. desiredDeviceFeatures.fillModeNonSolid = VK_TRUE;
  9621. renderer->supportsFillModeNonSolid = true;
  9622. }
  9623. if (haveDeviceFeatures.multiDrawIndirect) {
  9624. desiredDeviceFeatures.multiDrawIndirect = VK_TRUE;
  9625. renderer->supportsMultiDrawIndirect = true;
  9626. }
  9627. // creating the logical device
  9628. deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
  9629. if (renderer->supports.KHR_portability_subset) {
  9630. portabilityFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PORTABILITY_SUBSET_FEATURES_KHR;
  9631. portabilityFeatures.pNext = NULL;
  9632. portabilityFeatures.constantAlphaColorBlendFactors = VK_FALSE;
  9633. portabilityFeatures.events = VK_FALSE;
  9634. portabilityFeatures.imageViewFormatReinterpretation = VK_FALSE;
  9635. portabilityFeatures.imageViewFormatSwizzle = VK_TRUE;
  9636. portabilityFeatures.imageView2DOn3DImage = VK_FALSE;
  9637. portabilityFeatures.multisampleArrayImage = VK_FALSE;
  9638. portabilityFeatures.mutableComparisonSamplers = VK_FALSE;
  9639. portabilityFeatures.pointPolygons = VK_FALSE;
  9640. portabilityFeatures.samplerMipLodBias = VK_FALSE; // Technically should be true, but eh
  9641. portabilityFeatures.separateStencilMaskRef = VK_FALSE;
  9642. portabilityFeatures.shaderSampleRateInterpolationFunctions = VK_FALSE;
  9643. portabilityFeatures.tessellationIsolines = VK_FALSE;
  9644. portabilityFeatures.tessellationPointMode = VK_FALSE;
  9645. portabilityFeatures.triangleFans = VK_FALSE;
  9646. portabilityFeatures.vertexAttributeAccessBeyondStride = VK_FALSE;
  9647. deviceCreateInfo.pNext = &portabilityFeatures;
  9648. } else {
  9649. deviceCreateInfo.pNext = NULL;
  9650. }
  9651. deviceCreateInfo.flags = 0;
  9652. deviceCreateInfo.queueCreateInfoCount = 1;
  9653. deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo;
  9654. deviceCreateInfo.enabledLayerCount = 0;
  9655. deviceCreateInfo.ppEnabledLayerNames = NULL;
  9656. deviceCreateInfo.enabledExtensionCount = GetDeviceExtensionCount(
  9657. &renderer->supports);
  9658. deviceExtensions = SDL_stack_alloc(
  9659. const char *,
  9660. deviceCreateInfo.enabledExtensionCount);
  9661. CreateDeviceExtensionArray(&renderer->supports, deviceExtensions);
  9662. deviceCreateInfo.ppEnabledExtensionNames = deviceExtensions;
  9663. deviceCreateInfo.pEnabledFeatures = &desiredDeviceFeatures;
  9664. vulkanResult = renderer->vkCreateDevice(
  9665. renderer->physicalDevice,
  9666. &deviceCreateInfo,
  9667. NULL,
  9668. &renderer->logicalDevice);
  9669. SDL_stack_free((void *)deviceExtensions);
  9670. CHECK_VULKAN_ERROR_AND_RETURN(vulkanResult, vkCreateDevice, 0);
  9671. // Load vkDevice entry points
  9672. #define VULKAN_DEVICE_FUNCTION(func) \
  9673. renderer->func = (PFN_##func) \
  9674. renderer->vkGetDeviceProcAddr( \
  9675. renderer->logicalDevice, \
  9676. #func);
  9677. #include "SDL_gpu_vulkan_vkfuncs.h"
  9678. renderer->vkGetDeviceQueue(
  9679. renderer->logicalDevice,
  9680. renderer->queueFamilyIndex,
  9681. 0,
  9682. &renderer->unifiedQueue);
  9683. return 1;
  9684. }
  9685. static void VULKAN_INTERNAL_LoadEntryPoints(void)
  9686. {
  9687. // Required for MoltenVK support
  9688. SDL_setenv_unsafe("MVK_CONFIG_FULL_IMAGE_VIEW_SWIZZLE", "1", 1);
  9689. // Load Vulkan entry points
  9690. if (!SDL_Vulkan_LoadLibrary(NULL)) {
  9691. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Vulkan: SDL_Vulkan_LoadLibrary failed!");
  9692. return;
  9693. }
  9694. #ifdef HAVE_GCC_DIAGNOSTIC_PRAGMA
  9695. #pragma GCC diagnostic push
  9696. #pragma GCC diagnostic ignored "-Wpedantic"
  9697. #endif
  9698. vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)SDL_Vulkan_GetVkGetInstanceProcAddr();
  9699. #ifdef HAVE_GCC_DIAGNOSTIC_PRAGMA
  9700. #pragma GCC diagnostic pop
  9701. #endif
  9702. if (vkGetInstanceProcAddr == NULL) {
  9703. SDL_LogWarn(
  9704. SDL_LOG_CATEGORY_GPU,
  9705. "SDL_Vulkan_GetVkGetInstanceProcAddr(): %s",
  9706. SDL_GetError());
  9707. return;
  9708. }
  9709. #define VULKAN_GLOBAL_FUNCTION(name) \
  9710. name = (PFN_##name)vkGetInstanceProcAddr(VK_NULL_HANDLE, #name); \
  9711. if (name == NULL) { \
  9712. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "vkGetInstanceProcAddr(VK_NULL_HANDLE, \"" #name "\") failed"); \
  9713. return; \
  9714. }
  9715. #include "SDL_gpu_vulkan_vkfuncs.h"
  9716. }
  9717. static bool VULKAN_INTERNAL_PrepareVulkan(
  9718. VulkanRenderer *renderer)
  9719. {
  9720. VULKAN_INTERNAL_LoadEntryPoints();
  9721. if (!VULKAN_INTERNAL_CreateInstance(renderer)) {
  9722. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Vulkan: Could not create Vulkan instance");
  9723. return false;
  9724. }
  9725. #define VULKAN_INSTANCE_FUNCTION(func) \
  9726. renderer->func = (PFN_##func)vkGetInstanceProcAddr(renderer->instance, #func);
  9727. #include "SDL_gpu_vulkan_vkfuncs.h"
  9728. if (!VULKAN_INTERNAL_DeterminePhysicalDevice(renderer)) {
  9729. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "Vulkan: Failed to determine a suitable physical device");
  9730. return false;
  9731. }
  9732. return true;
  9733. }
  9734. static bool VULKAN_PrepareDriver(SDL_VideoDevice *_this)
  9735. {
  9736. // Set up dummy VulkanRenderer
  9737. VulkanRenderer *renderer;
  9738. Uint8 result;
  9739. if (_this->Vulkan_CreateSurface == NULL) {
  9740. return false;
  9741. }
  9742. if (!SDL_Vulkan_LoadLibrary(NULL)) {
  9743. return false;
  9744. }
  9745. renderer = (VulkanRenderer *)SDL_malloc(sizeof(VulkanRenderer));
  9746. SDL_memset(renderer, '\0', sizeof(VulkanRenderer));
  9747. result = VULKAN_INTERNAL_PrepareVulkan(renderer);
  9748. if (result) {
  9749. renderer->vkDestroyInstance(renderer->instance, NULL);
  9750. }
  9751. SDL_free(renderer);
  9752. SDL_Vulkan_UnloadLibrary();
  9753. return result;
  9754. }
  9755. static SDL_GPUDevice *VULKAN_CreateDevice(bool debugMode, bool preferLowPower, SDL_PropertiesID props)
  9756. {
  9757. VulkanRenderer *renderer;
  9758. SDL_GPUDevice *result;
  9759. Uint32 i;
  9760. if (!SDL_Vulkan_LoadLibrary(NULL)) {
  9761. SDL_assert(!"This should have failed in PrepareDevice first!");
  9762. return NULL;
  9763. }
  9764. renderer = (VulkanRenderer *)SDL_malloc(sizeof(VulkanRenderer));
  9765. SDL_memset(renderer, '\0', sizeof(VulkanRenderer));
  9766. renderer->debugMode = debugMode;
  9767. renderer->preferLowPower = preferLowPower;
  9768. renderer->allowedFramesInFlight = 2;
  9769. if (!VULKAN_INTERNAL_PrepareVulkan(renderer)) {
  9770. SDL_free(renderer);
  9771. SDL_Vulkan_UnloadLibrary();
  9772. SET_STRING_ERROR_AND_RETURN("Failed to initialize Vulkan!", NULL);
  9773. }
  9774. SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "SDL_GPU Driver: Vulkan");
  9775. SDL_LogInfo(
  9776. SDL_LOG_CATEGORY_GPU,
  9777. "Vulkan Device: %s",
  9778. renderer->physicalDeviceProperties.properties.deviceName);
  9779. if (renderer->supports.KHR_driver_properties) {
  9780. SDL_LogInfo(
  9781. SDL_LOG_CATEGORY_GPU,
  9782. "Vulkan Driver: %s %s",
  9783. renderer->physicalDeviceDriverProperties.driverName,
  9784. renderer->physicalDeviceDriverProperties.driverInfo);
  9785. SDL_LogInfo(
  9786. SDL_LOG_CATEGORY_GPU,
  9787. "Vulkan Conformance: %u.%u.%u",
  9788. renderer->physicalDeviceDriverProperties.conformanceVersion.major,
  9789. renderer->physicalDeviceDriverProperties.conformanceVersion.minor,
  9790. renderer->physicalDeviceDriverProperties.conformanceVersion.patch);
  9791. } else {
  9792. SDL_LogWarn(SDL_LOG_CATEGORY_GPU, "KHR_driver_properties unsupported! Bother your vendor about this!");
  9793. }
  9794. if (!VULKAN_INTERNAL_CreateLogicalDevice(
  9795. renderer)) {
  9796. SDL_free(renderer);
  9797. SDL_Vulkan_UnloadLibrary();
  9798. SET_STRING_ERROR_AND_RETURN("Failed to create logical device!", NULL);
  9799. }
  9800. // FIXME: just move this into this function
  9801. result = (SDL_GPUDevice *)SDL_malloc(sizeof(SDL_GPUDevice));
  9802. ASSIGN_DRIVER(VULKAN)
  9803. result->driverData = (SDL_GPURenderer *)renderer;
  9804. /*
  9805. * Create initial swapchain array
  9806. */
  9807. renderer->claimedWindowCapacity = 1;
  9808. renderer->claimedWindowCount = 0;
  9809. renderer->claimedWindows = SDL_malloc(
  9810. renderer->claimedWindowCapacity * sizeof(WindowData *));
  9811. // Threading
  9812. renderer->allocatorLock = SDL_CreateMutex();
  9813. renderer->disposeLock = SDL_CreateMutex();
  9814. renderer->submitLock = SDL_CreateMutex();
  9815. renderer->acquireCommandBufferLock = SDL_CreateMutex();
  9816. renderer->acquireUniformBufferLock = SDL_CreateMutex();
  9817. renderer->renderPassFetchLock = SDL_CreateMutex();
  9818. renderer->framebufferFetchLock = SDL_CreateMutex();
  9819. renderer->graphicsPipelineLayoutFetchLock = SDL_CreateMutex();
  9820. renderer->computePipelineLayoutFetchLock = SDL_CreateMutex();
  9821. renderer->descriptorSetLayoutFetchLock = SDL_CreateMutex();
  9822. renderer->windowLock = SDL_CreateMutex();
  9823. /*
  9824. * Create submitted command buffer list
  9825. */
  9826. renderer->submittedCommandBufferCapacity = 16;
  9827. renderer->submittedCommandBufferCount = 0;
  9828. renderer->submittedCommandBuffers = SDL_malloc(sizeof(VulkanCommandBuffer *) * renderer->submittedCommandBufferCapacity);
  9829. // Memory Allocator
  9830. renderer->memoryAllocator = (VulkanMemoryAllocator *)SDL_malloc(
  9831. sizeof(VulkanMemoryAllocator));
  9832. for (i = 0; i < VK_MAX_MEMORY_TYPES; i += 1) {
  9833. renderer->memoryAllocator->subAllocators[i].memoryTypeIndex = i;
  9834. renderer->memoryAllocator->subAllocators[i].allocations = NULL;
  9835. renderer->memoryAllocator->subAllocators[i].allocationCount = 0;
  9836. renderer->memoryAllocator->subAllocators[i].sortedFreeRegions = SDL_malloc(
  9837. sizeof(VulkanMemoryFreeRegion *) * 4);
  9838. renderer->memoryAllocator->subAllocators[i].sortedFreeRegionCount = 0;
  9839. renderer->memoryAllocator->subAllocators[i].sortedFreeRegionCapacity = 4;
  9840. }
  9841. // Create uniform buffer pool
  9842. renderer->uniformBufferPoolCount = 32;
  9843. renderer->uniformBufferPoolCapacity = 32;
  9844. renderer->uniformBufferPool = SDL_malloc(
  9845. renderer->uniformBufferPoolCapacity * sizeof(VulkanUniformBuffer *));
  9846. for (i = 0; i < renderer->uniformBufferPoolCount; i += 1) {
  9847. renderer->uniformBufferPool[i] = VULKAN_INTERNAL_CreateUniformBuffer(
  9848. renderer,
  9849. UNIFORM_BUFFER_SIZE);
  9850. }
  9851. renderer->descriptorSetCachePoolCapacity = 8;
  9852. renderer->descriptorSetCachePoolCount = 0;
  9853. renderer->descriptorSetCachePool = SDL_calloc(renderer->descriptorSetCachePoolCapacity, sizeof(DescriptorSetCache *));
  9854. SDL_SetAtomicInt(&renderer->layoutResourceID, 0);
  9855. // Device limits
  9856. renderer->minUBOAlignment = (Uint32)renderer->physicalDeviceProperties.properties.limits.minUniformBufferOffsetAlignment;
  9857. // Initialize caches
  9858. renderer->commandPoolHashTable = SDL_CreateHashTable(
  9859. 0, // !!! FIXME: a real guess here, for a _minimum_ if not a maximum, could be useful.
  9860. false, // manually synchronized due to submission timing
  9861. VULKAN_INTERNAL_CommandPoolHashFunction,
  9862. VULKAN_INTERNAL_CommandPoolHashKeyMatch,
  9863. VULKAN_INTERNAL_CommandPoolHashDestroy,
  9864. (void *)renderer);
  9865. renderer->renderPassHashTable = SDL_CreateHashTable(
  9866. 0, // !!! FIXME: a real guess here, for a _minimum_ if not a maximum, could be useful.
  9867. false, // manually synchronized due to lookup timing
  9868. VULKAN_INTERNAL_RenderPassHashFunction,
  9869. VULKAN_INTERNAL_RenderPassHashKeyMatch,
  9870. VULKAN_INTERNAL_RenderPassHashDestroy,
  9871. (void *)renderer);
  9872. renderer->framebufferHashTable = SDL_CreateHashTable(
  9873. 0, // !!! FIXME: a real guess here, for a _minimum_ if not a maximum, could be useful.
  9874. false, // manually synchronized due to iteration
  9875. VULKAN_INTERNAL_FramebufferHashFunction,
  9876. VULKAN_INTERNAL_FramebufferHashKeyMatch,
  9877. VULKAN_INTERNAL_FramebufferHashDestroy,
  9878. (void *)renderer);
  9879. renderer->graphicsPipelineResourceLayoutHashTable = SDL_CreateHashTable(
  9880. 0, // !!! FIXME: a real guess here, for a _minimum_ if not a maximum, could be useful.
  9881. false, // manually synchronized due to lookup timing
  9882. VULKAN_INTERNAL_GraphicsPipelineResourceLayoutHashFunction,
  9883. VULKAN_INTERNAL_GraphicsPipelineResourceLayoutHashKeyMatch,
  9884. VULKAN_INTERNAL_GraphicsPipelineResourceLayoutHashDestroy,
  9885. (void *)renderer);
  9886. renderer->computePipelineResourceLayoutHashTable = SDL_CreateHashTable(
  9887. 0, // !!! FIXME: a real guess here, for a _minimum_ if not a maximum, could be useful.
  9888. false, // manually synchronized due to lookup timing
  9889. VULKAN_INTERNAL_ComputePipelineResourceLayoutHashFunction,
  9890. VULKAN_INTERNAL_ComputePipelineResourceLayoutHashKeyMatch,
  9891. VULKAN_INTERNAL_ComputePipelineResourceLayoutHashDestroy,
  9892. (void *)renderer);
  9893. renderer->descriptorSetLayoutHashTable = SDL_CreateHashTable(
  9894. 0, // !!! FIXME: a real guess here, for a _minimum_ if not a maximum, could be useful.
  9895. false, // manually synchronized due to lookup timing
  9896. VULKAN_INTERNAL_DescriptorSetLayoutHashFunction,
  9897. VULKAN_INTERNAL_DescriptorSetLayoutHashKeyMatch,
  9898. VULKAN_INTERNAL_DescriptorSetLayoutHashDestroy,
  9899. (void *)renderer);
  9900. // Initialize fence pool
  9901. renderer->fencePool.lock = SDL_CreateMutex();
  9902. renderer->fencePool.availableFenceCapacity = 4;
  9903. renderer->fencePool.availableFenceCount = 0;
  9904. renderer->fencePool.availableFences = SDL_malloc(
  9905. renderer->fencePool.availableFenceCapacity * sizeof(VulkanFenceHandle *));
  9906. // Deferred destroy storage
  9907. renderer->texturesToDestroyCapacity = 16;
  9908. renderer->texturesToDestroyCount = 0;
  9909. renderer->texturesToDestroy = (VulkanTexture **)SDL_malloc(
  9910. sizeof(VulkanTexture *) *
  9911. renderer->texturesToDestroyCapacity);
  9912. renderer->buffersToDestroyCapacity = 16;
  9913. renderer->buffersToDestroyCount = 0;
  9914. renderer->buffersToDestroy = SDL_malloc(
  9915. sizeof(VulkanBuffer *) *
  9916. renderer->buffersToDestroyCapacity);
  9917. renderer->samplersToDestroyCapacity = 16;
  9918. renderer->samplersToDestroyCount = 0;
  9919. renderer->samplersToDestroy = SDL_malloc(
  9920. sizeof(VulkanSampler *) *
  9921. renderer->samplersToDestroyCapacity);
  9922. renderer->graphicsPipelinesToDestroyCapacity = 16;
  9923. renderer->graphicsPipelinesToDestroyCount = 0;
  9924. renderer->graphicsPipelinesToDestroy = SDL_malloc(
  9925. sizeof(VulkanGraphicsPipeline *) *
  9926. renderer->graphicsPipelinesToDestroyCapacity);
  9927. renderer->computePipelinesToDestroyCapacity = 16;
  9928. renderer->computePipelinesToDestroyCount = 0;
  9929. renderer->computePipelinesToDestroy = SDL_malloc(
  9930. sizeof(VulkanComputePipeline *) *
  9931. renderer->computePipelinesToDestroyCapacity);
  9932. renderer->shadersToDestroyCapacity = 16;
  9933. renderer->shadersToDestroyCount = 0;
  9934. renderer->shadersToDestroy = SDL_malloc(
  9935. sizeof(VulkanShader *) *
  9936. renderer->shadersToDestroyCapacity);
  9937. renderer->framebuffersToDestroyCapacity = 16;
  9938. renderer->framebuffersToDestroyCount = 0;
  9939. renderer->framebuffersToDestroy = SDL_malloc(
  9940. sizeof(VulkanFramebuffer *) *
  9941. renderer->framebuffersToDestroyCapacity);
  9942. // Defrag state
  9943. renderer->defragInProgress = 0;
  9944. renderer->allocationsToDefragCount = 0;
  9945. renderer->allocationsToDefragCapacity = 4;
  9946. renderer->allocationsToDefrag = SDL_malloc(
  9947. renderer->allocationsToDefragCapacity * sizeof(VulkanMemoryAllocation *));
  9948. return result;
  9949. }
  9950. SDL_GPUBootstrap VulkanDriver = {
  9951. "vulkan",
  9952. SDL_GPU_SHADERFORMAT_SPIRV,
  9953. VULKAN_PrepareDriver,
  9954. VULKAN_CreateDevice
  9955. };
  9956. #endif // SDL_GPU_VULKAN