2
0

vk_mem_alloc.h 700 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733
  1. //
  2. // Copyright (c) 2017-2021 Advanced Micro Devices, Inc. All rights reserved.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #ifndef AMD_VULKAN_MEMORY_ALLOCATOR_H
  23. #define AMD_VULKAN_MEMORY_ALLOCATOR_H
  24. /** \mainpage Vulkan Memory Allocator
  25. <b>Version 3.0.0-development</b> (2021-06-21)
  26. Copyright (c) 2017-2021 Advanced Micro Devices, Inc. All rights reserved. \n
  27. License: MIT
  28. Documentation of all members: vk_mem_alloc.h
  29. \section main_table_of_contents Table of contents
  30. - <b>User guide</b>
  31. - \subpage quick_start
  32. - [Project setup](@ref quick_start_project_setup)
  33. - [Initialization](@ref quick_start_initialization)
  34. - [Resource allocation](@ref quick_start_resource_allocation)
  35. - \subpage choosing_memory_type
  36. - [Usage](@ref choosing_memory_type_usage)
  37. - [Required and preferred flags](@ref choosing_memory_type_required_preferred_flags)
  38. - [Explicit memory types](@ref choosing_memory_type_explicit_memory_types)
  39. - [Custom memory pools](@ref choosing_memory_type_custom_memory_pools)
  40. - [Dedicated allocations](@ref choosing_memory_type_dedicated_allocations)
  41. - \subpage memory_mapping
  42. - [Mapping functions](@ref memory_mapping_mapping_functions)
  43. - [Persistently mapped memory](@ref memory_mapping_persistently_mapped_memory)
  44. - [Cache flush and invalidate](@ref memory_mapping_cache_control)
  45. - [Finding out if memory is mappable](@ref memory_mapping_finding_if_memory_mappable)
  46. - \subpage staying_within_budget
  47. - [Querying for budget](@ref staying_within_budget_querying_for_budget)
  48. - [Controlling memory usage](@ref staying_within_budget_controlling_memory_usage)
  49. - \subpage resource_aliasing
  50. - \subpage custom_memory_pools
  51. - [Choosing memory type index](@ref custom_memory_pools_MemTypeIndex)
  52. - [Linear allocation algorithm](@ref linear_algorithm)
  53. - [Free-at-once](@ref linear_algorithm_free_at_once)
  54. - [Stack](@ref linear_algorithm_stack)
  55. - [Double stack](@ref linear_algorithm_double_stack)
  56. - [Ring buffer](@ref linear_algorithm_ring_buffer)
  57. - [Buddy allocation algorithm](@ref buddy_algorithm)
  58. - \subpage defragmentation
  59. - [Defragmenting CPU memory](@ref defragmentation_cpu)
  60. - [Defragmenting GPU memory](@ref defragmentation_gpu)
  61. - [Additional notes](@ref defragmentation_additional_notes)
  62. - [Writing custom allocation algorithm](@ref defragmentation_custom_algorithm)
  63. - \subpage lost_allocations
  64. - \subpage statistics
  65. - [Numeric statistics](@ref statistics_numeric_statistics)
  66. - [JSON dump](@ref statistics_json_dump)
  67. - \subpage allocation_annotation
  68. - [Allocation user data](@ref allocation_user_data)
  69. - [Allocation names](@ref allocation_names)
  70. - \subpage debugging_memory_usage
  71. - [Memory initialization](@ref debugging_memory_usage_initialization)
  72. - [Margins](@ref debugging_memory_usage_margins)
  73. - [Corruption detection](@ref debugging_memory_usage_corruption_detection)
  74. - \subpage record_and_replay
  75. - \subpage usage_patterns
  76. - [Common mistakes](@ref usage_patterns_common_mistakes)
  77. - [Simple patterns](@ref usage_patterns_simple)
  78. - [Advanced patterns](@ref usage_patterns_advanced)
  79. - \subpage configuration
  80. - [Pointers to Vulkan functions](@ref config_Vulkan_functions)
  81. - [Custom host memory allocator](@ref custom_memory_allocator)
  82. - [Device memory allocation callbacks](@ref allocation_callbacks)
  83. - [Device heap memory limit](@ref heap_memory_limit)
  84. - \subpage vk_khr_dedicated_allocation
  85. - \subpage enabling_buffer_device_address
  86. - \subpage vk_amd_device_coherent_memory
  87. - \subpage general_considerations
  88. - [Thread safety](@ref general_considerations_thread_safety)
  89. - [Validation layer warnings](@ref general_considerations_validation_layer_warnings)
  90. - [Allocation algorithm](@ref general_considerations_allocation_algorithm)
  91. - [Features not supported](@ref general_considerations_features_not_supported)
  92. \section main_see_also See also
  93. - [Product page on GPUOpen](https://gpuopen.com/gaming-product/vulkan-memory-allocator/)
  94. - [Source repository on GitHub](https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator)
  95. \page quick_start Quick start
  96. \section quick_start_project_setup Project setup
  97. Vulkan Memory Allocator comes in form of a "stb-style" single header file.
  98. You don't need to build it as a separate library project.
  99. You can add this file directly to your project and submit it to code repository next to your other source files.
  100. "Single header" doesn't mean that everything is contained in C/C++ declarations,
  101. like it tends to be in case of inline functions or C++ templates.
  102. It means that implementation is bundled with interface in a single file and needs to be extracted using preprocessor macro.
  103. If you don't do it properly, you will get linker errors.
  104. To do it properly:
  105. -# Include "vk_mem_alloc.h" file in each CPP file where you want to use the library.
  106. This includes declarations of all members of the library.
  107. -# In exactly one CPP file define following macro before this include.
  108. It enables also internal definitions.
  109. \code
  110. #define VMA_IMPLEMENTATION
  111. #include "vk_mem_alloc.h"
  112. \endcode
  113. It may be a good idea to create dedicated CPP file just for this purpose.
  114. Note on language: This library is written in C++, but has C-compatible interface.
  115. Thus you can include and use vk_mem_alloc.h in C or C++ code, but full
  116. implementation with `VMA_IMPLEMENTATION` macro must be compiled as C++, NOT as C.
  117. Please note that this library includes header `<vulkan/vulkan.h>`, which in turn
  118. includes `<windows.h>` on Windows. If you need some specific macros defined
  119. before including these headers (like `WIN32_LEAN_AND_MEAN` or
  120. `WINVER` for Windows, `VK_USE_PLATFORM_WIN32_KHR` for Vulkan), you must define
  121. them before every `#include` of this library.
  122. You may need to configure the way you import Vulkan functions.
  123. - By default, VMA assumes you you link statically with Vulkan API. If this is not the case,
  124. `#define VMA_STATIC_VULKAN_FUNCTIONS 0` before `#include` of the VMA implementation and use another way.
  125. - You can `#define VMA_DYNAMIC_VULKAN_FUNCTIONS 1` and make sure `vkGetInstanceProcAddr` and `vkGetDeviceProcAddr` globals are defined.
  126. All the remaining Vulkan functions will be fetched automatically.
  127. - Finally, you can provide your own pointers to all Vulkan functions needed by VMA using structure member
  128. VmaAllocatorCreateInfo::pVulkanFunctions, if you fetched them in some custom way e.g. using some loader like [Volk](https://github.com/zeux/volk).
  129. \section quick_start_initialization Initialization
  130. At program startup:
  131. -# Initialize Vulkan to have `VkPhysicalDevice`, `VkDevice` and `VkInstance` object.
  132. -# Fill VmaAllocatorCreateInfo structure and create #VmaAllocator object by
  133. calling vmaCreateAllocator().
  134. \code
  135. VmaAllocatorCreateInfo allocatorInfo = {};
  136. allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_2;
  137. allocatorInfo.physicalDevice = physicalDevice;
  138. allocatorInfo.device = device;
  139. allocatorInfo.instance = instance;
  140. VmaAllocator allocator;
  141. vmaCreateAllocator(&allocatorInfo, &allocator);
  142. \endcode
  143. Only members `physicalDevice`, `device`, `instance` are required.
  144. However, you should inform the library which Vulkan version do you use by setting
  145. VmaAllocatorCreateInfo::vulkanApiVersion and which extensions did you enable
  146. by setting VmaAllocatorCreateInfo::flags (like #VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT for VK_KHR_buffer_device_address).
  147. Otherwise, VMA would use only features of Vulkan 1.0 core with no extensions.
  148. \section quick_start_resource_allocation Resource allocation
  149. When you want to create a buffer or image:
  150. -# Fill `VkBufferCreateInfo` / `VkImageCreateInfo` structure.
  151. -# Fill VmaAllocationCreateInfo structure.
  152. -# Call vmaCreateBuffer() / vmaCreateImage() to get `VkBuffer`/`VkImage` with memory
  153. already allocated and bound to it.
  154. \code
  155. VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  156. bufferInfo.size = 65536;
  157. bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  158. VmaAllocationCreateInfo allocInfo = {};
  159. allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  160. VkBuffer buffer;
  161. VmaAllocation allocation;
  162. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  163. \endcode
  164. Don't forget to destroy your objects when no longer needed:
  165. \code
  166. vmaDestroyBuffer(allocator, buffer, allocation);
  167. vmaDestroyAllocator(allocator);
  168. \endcode
  169. \page choosing_memory_type Choosing memory type
  170. Physical devices in Vulkan support various combinations of memory heaps and
  171. types. Help with choosing correct and optimal memory type for your specific
  172. resource is one of the key features of this library. You can use it by filling
  173. appropriate members of VmaAllocationCreateInfo structure, as described below.
  174. You can also combine multiple methods.
  175. -# If you just want to find memory type index that meets your requirements, you
  176. can use function: vmaFindMemoryTypeIndex(), vmaFindMemoryTypeIndexForBufferInfo(),
  177. vmaFindMemoryTypeIndexForImageInfo().
  178. -# If you want to allocate a region of device memory without association with any
  179. specific image or buffer, you can use function vmaAllocateMemory(). Usage of
  180. this function is not recommended and usually not needed.
  181. vmaAllocateMemoryPages() function is also provided for creating multiple allocations at once,
  182. which may be useful for sparse binding.
  183. -# If you already have a buffer or an image created, you want to allocate memory
  184. for it and then you will bind it yourself, you can use function
  185. vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage().
  186. For binding you should use functions: vmaBindBufferMemory(), vmaBindImageMemory()
  187. or their extended versions: vmaBindBufferMemory2(), vmaBindImageMemory2().
  188. -# If you want to create a buffer or an image, allocate memory for it and bind
  189. them together, all in one call, you can use function vmaCreateBuffer(),
  190. vmaCreateImage(). This is the easiest and recommended way to use this library.
  191. When using 3. or 4., the library internally queries Vulkan for memory types
  192. supported for that buffer or image (function `vkGetBufferMemoryRequirements()`)
  193. and uses only one of these types.
  194. If no memory type can be found that meets all the requirements, these functions
  195. return `VK_ERROR_FEATURE_NOT_PRESENT`.
  196. You can leave VmaAllocationCreateInfo structure completely filled with zeros.
  197. It means no requirements are specified for memory type.
  198. It is valid, although not very useful.
  199. \section choosing_memory_type_usage Usage
  200. The easiest way to specify memory requirements is to fill member
  201. VmaAllocationCreateInfo::usage using one of the values of enum #VmaMemoryUsage.
  202. It defines high level, common usage types.
  203. For more details, see description of this enum.
  204. For example, if you want to create a uniform buffer that will be filled using
  205. transfer only once or infrequently and used for rendering every frame, you can
  206. do it using following code:
  207. \code
  208. VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  209. bufferInfo.size = 65536;
  210. bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  211. VmaAllocationCreateInfo allocInfo = {};
  212. allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  213. VkBuffer buffer;
  214. VmaAllocation allocation;
  215. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  216. \endcode
  217. \section choosing_memory_type_required_preferred_flags Required and preferred flags
  218. You can specify more detailed requirements by filling members
  219. VmaAllocationCreateInfo::requiredFlags and VmaAllocationCreateInfo::preferredFlags
  220. with a combination of bits from enum `VkMemoryPropertyFlags`. For example,
  221. if you want to create a buffer that will be persistently mapped on host (so it
  222. must be `HOST_VISIBLE`) and preferably will also be `HOST_COHERENT` and `HOST_CACHED`,
  223. use following code:
  224. \code
  225. VmaAllocationCreateInfo allocInfo = {};
  226. allocInfo.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  227. allocInfo.preferredFlags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  228. allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
  229. VkBuffer buffer;
  230. VmaAllocation allocation;
  231. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  232. \endcode
  233. A memory type is chosen that has all the required flags and as many preferred
  234. flags set as possible.
  235. If you use VmaAllocationCreateInfo::usage, it is just internally converted to
  236. a set of required and preferred flags.
  237. \section choosing_memory_type_explicit_memory_types Explicit memory types
  238. If you inspected memory types available on the physical device and you have
  239. a preference for memory types that you want to use, you can fill member
  240. VmaAllocationCreateInfo::memoryTypeBits. It is a bit mask, where each bit set
  241. means that a memory type with that index is allowed to be used for the
  242. allocation. Special value 0, just like `UINT32_MAX`, means there are no
  243. restrictions to memory type index.
  244. Please note that this member is NOT just a memory type index.
  245. Still you can use it to choose just one, specific memory type.
  246. For example, if you already determined that your buffer should be created in
  247. memory type 2, use following code:
  248. \code
  249. uint32_t memoryTypeIndex = 2;
  250. VmaAllocationCreateInfo allocInfo = {};
  251. allocInfo.memoryTypeBits = 1u << memoryTypeIndex;
  252. VkBuffer buffer;
  253. VmaAllocation allocation;
  254. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  255. \endcode
  256. \section choosing_memory_type_custom_memory_pools Custom memory pools
  257. If you allocate from custom memory pool, all the ways of specifying memory
  258. requirements described above are not applicable and the aforementioned members
  259. of VmaAllocationCreateInfo structure are ignored. Memory type is selected
  260. explicitly when creating the pool and then used to make all the allocations from
  261. that pool. For further details, see \ref custom_memory_pools.
  262. \section choosing_memory_type_dedicated_allocations Dedicated allocations
  263. Memory for allocations is reserved out of larger block of `VkDeviceMemory`
  264. allocated from Vulkan internally. That's the main feature of this whole library.
  265. You can still request a separate memory block to be created for an allocation,
  266. just like you would do in a trivial solution without using any allocator.
  267. In that case, a buffer or image is always bound to that memory at offset 0.
  268. This is called a "dedicated allocation".
  269. You can explicitly request it by using flag #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  270. The library can also internally decide to use dedicated allocation in some cases, e.g.:
  271. - When the size of the allocation is large.
  272. - When [VK_KHR_dedicated_allocation](@ref vk_khr_dedicated_allocation) extension is enabled
  273. and it reports that dedicated allocation is required or recommended for the resource.
  274. - When allocation of next big memory block fails due to not enough device memory,
  275. but allocation with the exact requested size succeeds.
  276. \page memory_mapping Memory mapping
  277. To "map memory" in Vulkan means to obtain a CPU pointer to `VkDeviceMemory`,
  278. to be able to read from it or write to it in CPU code.
  279. Mapping is possible only of memory allocated from a memory type that has
  280. `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag.
  281. Functions `vkMapMemory()`, `vkUnmapMemory()` are designed for this purpose.
  282. You can use them directly with memory allocated by this library,
  283. but it is not recommended because of following issue:
  284. Mapping the same `VkDeviceMemory` block multiple times is illegal - only one mapping at a time is allowed.
  285. This includes mapping disjoint regions. Mapping is not reference-counted internally by Vulkan.
  286. Because of this, Vulkan Memory Allocator provides following facilities:
  287. \section memory_mapping_mapping_functions Mapping functions
  288. The library provides following functions for mapping of a specific #VmaAllocation: vmaMapMemory(), vmaUnmapMemory().
  289. They are safer and more convenient to use than standard Vulkan functions.
  290. You can map an allocation multiple times simultaneously - mapping is reference-counted internally.
  291. You can also map different allocations simultaneously regardless of whether they use the same `VkDeviceMemory` block.
  292. The way it's implemented is that the library always maps entire memory block, not just region of the allocation.
  293. For further details, see description of vmaMapMemory() function.
  294. Example:
  295. \code
  296. // Having these objects initialized:
  297. struct ConstantBuffer
  298. {
  299. ...
  300. };
  301. ConstantBuffer constantBufferData;
  302. VmaAllocator allocator;
  303. VkBuffer constantBuffer;
  304. VmaAllocation constantBufferAllocation;
  305. // You can map and fill your buffer using following code:
  306. void* mappedData;
  307. vmaMapMemory(allocator, constantBufferAllocation, &mappedData);
  308. memcpy(mappedData, &constantBufferData, sizeof(constantBufferData));
  309. vmaUnmapMemory(allocator, constantBufferAllocation);
  310. \endcode
  311. When mapping, you may see a warning from Vulkan validation layer similar to this one:
  312. <i>Mapping an image with layout VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL can result in undefined behavior if this memory is used by the device. Only GENERAL or PREINITIALIZED should be used.</i>
  313. It happens because the library maps entire `VkDeviceMemory` block, where different
  314. types of images and buffers may end up together, especially on GPUs with unified memory like Intel.
  315. You can safely ignore it if you are sure you access only memory of the intended
  316. object that you wanted to map.
  317. \section memory_mapping_persistently_mapped_memory Persistently mapped memory
  318. Kepping your memory persistently mapped is generally OK in Vulkan.
  319. You don't need to unmap it before using its data on the GPU.
  320. The library provides a special feature designed for that:
  321. Allocations made with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag set in
  322. VmaAllocationCreateInfo::flags stay mapped all the time,
  323. so you can just access CPU pointer to it any time
  324. without a need to call any "map" or "unmap" function.
  325. Example:
  326. \code
  327. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  328. bufCreateInfo.size = sizeof(ConstantBuffer);
  329. bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  330. VmaAllocationCreateInfo allocCreateInfo = {};
  331. allocCreateInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
  332. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
  333. VkBuffer buf;
  334. VmaAllocation alloc;
  335. VmaAllocationInfo allocInfo;
  336. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  337. // Buffer is already mapped. You can access its memory.
  338. memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData));
  339. \endcode
  340. There are some exceptions though, when you should consider mapping memory only for a short period of time:
  341. - When operating system is Windows 7 or 8.x (Windows 10 is not affected because it uses WDDM2),
  342. device is discrete AMD GPU,
  343. and memory type is the special 256 MiB pool of `DEVICE_LOCAL + HOST_VISIBLE` memory
  344. (selected when you use #VMA_MEMORY_USAGE_CPU_TO_GPU),
  345. then whenever a memory block allocated from this memory type stays mapped
  346. for the time of any call to `vkQueueSubmit()` or `vkQueuePresentKHR()`, this
  347. block is migrated by WDDM to system RAM, which degrades performance. It doesn't
  348. matter if that particular memory block is actually used by the command buffer
  349. being submitted.
  350. - Keeping many large memory blocks mapped may impact performance or stability of some debugging tools.
  351. \section memory_mapping_cache_control Cache flush and invalidate
  352. Memory in Vulkan doesn't need to be unmapped before using it on GPU,
  353. but unless a memory types has `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT` flag set,
  354. you need to manually **invalidate** cache before reading of mapped pointer
  355. and **flush** cache after writing to mapped pointer.
  356. Map/unmap operations don't do that automatically.
  357. Vulkan provides following functions for this purpose `vkFlushMappedMemoryRanges()`,
  358. `vkInvalidateMappedMemoryRanges()`, but this library provides more convenient
  359. functions that refer to given allocation object: vmaFlushAllocation(),
  360. vmaInvalidateAllocation(),
  361. or multiple objects at once: vmaFlushAllocations(), vmaInvalidateAllocations().
  362. Regions of memory specified for flush/invalidate must be aligned to
  363. `VkPhysicalDeviceLimits::nonCoherentAtomSize`. This is automatically ensured by the library.
  364. In any memory type that is `HOST_VISIBLE` but not `HOST_COHERENT`, all allocations
  365. within blocks are aligned to this value, so their offsets are always multiply of
  366. `nonCoherentAtomSize` and two different allocations never share same "line" of this size.
  367. Please note that memory allocated with #VMA_MEMORY_USAGE_CPU_ONLY is guaranteed to be `HOST_COHERENT`.
  368. Also, Windows drivers from all 3 **PC** GPU vendors (AMD, Intel, NVIDIA)
  369. currently provide `HOST_COHERENT` flag on all memory types that are
  370. `HOST_VISIBLE`, so on this platform you may not need to bother.
  371. \section memory_mapping_finding_if_memory_mappable Finding out if memory is mappable
  372. It may happen that your allocation ends up in memory that is `HOST_VISIBLE` (available for mapping)
  373. despite it wasn't explicitly requested.
  374. For example, application may work on integrated graphics with unified memory (like Intel) or
  375. allocation from video memory might have failed, so the library chose system memory as fallback.
  376. You can detect this case and map such allocation to access its memory on CPU directly,
  377. instead of launching a transfer operation.
  378. In order to do that: inspect `allocInfo.memoryType`, call vmaGetMemoryTypeProperties(),
  379. and look for `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag in properties of that memory type.
  380. \code
  381. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  382. bufCreateInfo.size = sizeof(ConstantBuffer);
  383. bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  384. VmaAllocationCreateInfo allocCreateInfo = {};
  385. allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  386. allocCreateInfo.preferredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  387. VkBuffer buf;
  388. VmaAllocation alloc;
  389. VmaAllocationInfo allocInfo;
  390. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  391. VkMemoryPropertyFlags memFlags;
  392. vmaGetMemoryTypeProperties(allocator, allocInfo.memoryType, &memFlags);
  393. if((memFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
  394. {
  395. // Allocation ended up in mappable memory. You can map it and access it directly.
  396. void* mappedData;
  397. vmaMapMemory(allocator, alloc, &mappedData);
  398. memcpy(mappedData, &constantBufferData, sizeof(constantBufferData));
  399. vmaUnmapMemory(allocator, alloc);
  400. }
  401. else
  402. {
  403. // Allocation ended up in non-mappable memory.
  404. // You need to create CPU-side buffer in VMA_MEMORY_USAGE_CPU_ONLY and make a transfer.
  405. }
  406. \endcode
  407. You can even use #VMA_ALLOCATION_CREATE_MAPPED_BIT flag while creating allocations
  408. that are not necessarily `HOST_VISIBLE` (e.g. using #VMA_MEMORY_USAGE_GPU_ONLY).
  409. If the allocation ends up in memory type that is `HOST_VISIBLE`, it will be persistently mapped and you can use it directly.
  410. If not, the flag is just ignored.
  411. Example:
  412. \code
  413. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  414. bufCreateInfo.size = sizeof(ConstantBuffer);
  415. bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  416. VmaAllocationCreateInfo allocCreateInfo = {};
  417. allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  418. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
  419. VkBuffer buf;
  420. VmaAllocation alloc;
  421. VmaAllocationInfo allocInfo;
  422. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  423. if(allocInfo.pMappedData != nullptr)
  424. {
  425. // Allocation ended up in mappable memory.
  426. // It's persistently mapped. You can access it directly.
  427. memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData));
  428. }
  429. else
  430. {
  431. // Allocation ended up in non-mappable memory.
  432. // You need to create CPU-side buffer in VMA_MEMORY_USAGE_CPU_ONLY and make a transfer.
  433. }
  434. \endcode
  435. \page staying_within_budget Staying within budget
  436. When developing a graphics-intensive game or program, it is important to avoid allocating
  437. more GPU memory than it's physically available. When the memory is over-committed,
  438. various bad things can happen, depending on the specific GPU, graphics driver, and
  439. operating system:
  440. - It may just work without any problems.
  441. - The application may slow down because some memory blocks are moved to system RAM
  442. and the GPU has to access them through PCI Express bus.
  443. - A new allocation may take very long time to complete, even few seconds, and possibly
  444. freeze entire system.
  445. - The new allocation may fail with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  446. - It may even result in GPU crash (TDR), observed as `VK_ERROR_DEVICE_LOST`
  447. returned somewhere later.
  448. \section staying_within_budget_querying_for_budget Querying for budget
  449. To query for current memory usage and available budget, use function vmaGetBudget().
  450. Returned structure #VmaBudget contains quantities expressed in bytes, per Vulkan memory heap.
  451. Please note that this function returns different information and works faster than
  452. vmaCalculateStats(). vmaGetBudget() can be called every frame or even before every
  453. allocation, while vmaCalculateStats() is intended to be used rarely,
  454. only to obtain statistical information, e.g. for debugging purposes.
  455. It is recommended to use <b>VK_EXT_memory_budget</b> device extension to obtain information
  456. about the budget from Vulkan device. VMA is able to use this extension automatically.
  457. When not enabled, the allocator behaves same way, but then it estimates current usage
  458. and available budget based on its internal information and Vulkan memory heap sizes,
  459. which may be less precise. In order to use this extension:
  460. 1. Make sure extensions VK_EXT_memory_budget and VK_KHR_get_physical_device_properties2
  461. required by it are available and enable them. Please note that the first is a device
  462. extension and the second is instance extension!
  463. 2. Use flag #VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT when creating #VmaAllocator object.
  464. 3. Make sure to call vmaSetCurrentFrameIndex() every frame. Budget is queried from
  465. Vulkan inside of it to avoid overhead of querying it with every allocation.
  466. \section staying_within_budget_controlling_memory_usage Controlling memory usage
  467. There are many ways in which you can try to stay within the budget.
  468. First, when making new allocation requires allocating a new memory block, the library
  469. tries not to exceed the budget automatically. If a block with default recommended size
  470. (e.g. 256 MB) would go over budget, a smaller block is allocated, possibly even
  471. dedicated memory for just this resource.
  472. If the size of the requested resource plus current memory usage is more than the
  473. budget, by default the library still tries to create it, leaving it to the Vulkan
  474. implementation whether the allocation succeeds or fails. You can change this behavior
  475. by using #VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT flag. With it, the allocation is
  476. not made if it would exceed the budget or if the budget is already exceeded.
  477. Some other allocations become lost instead to make room for it, if the mechanism of
  478. [lost allocations](@ref lost_allocations) is used.
  479. If that is not possible, the allocation fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  480. Example usage pattern may be to pass the #VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT flag
  481. when creating resources that are not essential for the application (e.g. the texture
  482. of a specific object) and not to pass it when creating critically important resources
  483. (e.g. render targets).
  484. Finally, you can also use #VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT flag to make sure
  485. a new allocation is created only when it fits inside one of the existing memory blocks.
  486. If it would require to allocate a new block, if fails instead with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  487. This also ensures that the function call is very fast because it never goes to Vulkan
  488. to obtain a new block.
  489. Please note that creating \ref custom_memory_pools with VmaPoolCreateInfo::minBlockCount
  490. set to more than 0 will try to allocate memory blocks without checking whether they
  491. fit within budget.
  492. \page resource_aliasing Resource aliasing (overlap)
  493. New explicit graphics APIs (Vulkan and Direct3D 12), thanks to manual memory
  494. management, give an opportunity to alias (overlap) multiple resources in the
  495. same region of memory - a feature not available in the old APIs (Direct3D 11, OpenGL).
  496. It can be useful to save video memory, but it must be used with caution.
  497. For example, if you know the flow of your whole render frame in advance, you
  498. are going to use some intermediate textures or buffers only during a small range of render passes,
  499. and you know these ranges don't overlap in time, you can bind these resources to
  500. the same place in memory, even if they have completely different parameters (width, height, format etc.).
  501. ![Resource aliasing (overlap)](../gfx/Aliasing.png)
  502. Such scenario is possible using VMA, but you need to create your images manually.
  503. Then you need to calculate parameters of an allocation to be made using formula:
  504. - allocation size = max(size of each image)
  505. - allocation alignment = max(alignment of each image)
  506. - allocation memoryTypeBits = bitwise AND(memoryTypeBits of each image)
  507. Following example shows two different images bound to the same place in memory,
  508. allocated to fit largest of them.
  509. \code
  510. // A 512x512 texture to be sampled.
  511. VkImageCreateInfo img1CreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
  512. img1CreateInfo.imageType = VK_IMAGE_TYPE_2D;
  513. img1CreateInfo.extent.width = 512;
  514. img1CreateInfo.extent.height = 512;
  515. img1CreateInfo.extent.depth = 1;
  516. img1CreateInfo.mipLevels = 10;
  517. img1CreateInfo.arrayLayers = 1;
  518. img1CreateInfo.format = VK_FORMAT_R8G8B8A8_SRGB;
  519. img1CreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  520. img1CreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  521. img1CreateInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
  522. img1CreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
  523. // A full screen texture to be used as color attachment.
  524. VkImageCreateInfo img2CreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
  525. img2CreateInfo.imageType = VK_IMAGE_TYPE_2D;
  526. img2CreateInfo.extent.width = 1920;
  527. img2CreateInfo.extent.height = 1080;
  528. img2CreateInfo.extent.depth = 1;
  529. img2CreateInfo.mipLevels = 1;
  530. img2CreateInfo.arrayLayers = 1;
  531. img2CreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
  532. img2CreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  533. img2CreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  534. img2CreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  535. img2CreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
  536. VkImage img1;
  537. res = vkCreateImage(device, &img1CreateInfo, nullptr, &img1);
  538. VkImage img2;
  539. res = vkCreateImage(device, &img2CreateInfo, nullptr, &img2);
  540. VkMemoryRequirements img1MemReq;
  541. vkGetImageMemoryRequirements(device, img1, &img1MemReq);
  542. VkMemoryRequirements img2MemReq;
  543. vkGetImageMemoryRequirements(device, img2, &img2MemReq);
  544. VkMemoryRequirements finalMemReq = {};
  545. finalMemReq.size = std::max(img1MemReq.size, img2MemReq.size);
  546. finalMemReq.alignment = std::max(img1MemReq.alignment, img2MemReq.alignment);
  547. finalMemReq.memoryTypeBits = img1MemReq.memoryTypeBits & img2MemReq.memoryTypeBits;
  548. // Validate if(finalMemReq.memoryTypeBits != 0)
  549. VmaAllocationCreateInfo allocCreateInfo = {};
  550. allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  551. VmaAllocation alloc;
  552. res = vmaAllocateMemory(allocator, &finalMemReq, &allocCreateInfo, &alloc, nullptr);
  553. res = vmaBindImageMemory(allocator, alloc, img1);
  554. res = vmaBindImageMemory(allocator, alloc, img2);
  555. // You can use img1, img2 here, but not at the same time!
  556. vmaFreeMemory(allocator, alloc);
  557. vkDestroyImage(allocator, img2, nullptr);
  558. vkDestroyImage(allocator, img1, nullptr);
  559. \endcode
  560. Remember that using resources that alias in memory requires proper synchronization.
  561. You need to issue a memory barrier to make sure commands that use `img1` and `img2`
  562. don't overlap on GPU timeline.
  563. You also need to treat a resource after aliasing as uninitialized - containing garbage data.
  564. For example, if you use `img1` and then want to use `img2`, you need to issue
  565. an image memory barrier for `img2` with `oldLayout` = `VK_IMAGE_LAYOUT_UNDEFINED`.
  566. Additional considerations:
  567. - Vulkan also allows to interpret contents of memory between aliasing resources consistently in some cases.
  568. See chapter 11.8. "Memory Aliasing" of Vulkan specification or `VK_IMAGE_CREATE_ALIAS_BIT` flag.
  569. - You can create more complex layout where different images and buffers are bound
  570. at different offsets inside one large allocation. For example, one can imagine
  571. a big texture used in some render passes, aliasing with a set of many small buffers
  572. used between in some further passes. To bind a resource at non-zero offset of an allocation,
  573. use vmaBindBufferMemory2() / vmaBindImageMemory2().
  574. - Before allocating memory for the resources you want to alias, check `memoryTypeBits`
  575. returned in memory requirements of each resource to make sure the bits overlap.
  576. Some GPUs may expose multiple memory types suitable e.g. only for buffers or
  577. images with `COLOR_ATTACHMENT` usage, so the sets of memory types supported by your
  578. resources may be disjoint. Aliasing them is not possible in that case.
  579. \page custom_memory_pools Custom memory pools
  580. A memory pool contains a number of `VkDeviceMemory` blocks.
  581. The library automatically creates and manages default pool for each memory type available on the device.
  582. Default memory pool automatically grows in size.
  583. Size of allocated blocks is also variable and managed automatically.
  584. You can create custom pool and allocate memory out of it.
  585. It can be useful if you want to:
  586. - Keep certain kind of allocations separate from others.
  587. - Enforce particular, fixed size of Vulkan memory blocks.
  588. - Limit maximum amount of Vulkan memory allocated for that pool.
  589. - Reserve minimum or fixed amount of Vulkan memory always preallocated for that pool.
  590. To use custom memory pools:
  591. -# Fill VmaPoolCreateInfo structure.
  592. -# Call vmaCreatePool() to obtain #VmaPool handle.
  593. -# When making an allocation, set VmaAllocationCreateInfo::pool to this handle.
  594. You don't need to specify any other parameters of this structure, like `usage`.
  595. Example:
  596. \code
  597. // Create a pool that can have at most 2 blocks, 128 MiB each.
  598. VmaPoolCreateInfo poolCreateInfo = {};
  599. poolCreateInfo.memoryTypeIndex = ...
  600. poolCreateInfo.blockSize = 128ull * 1024 * 1024;
  601. poolCreateInfo.maxBlockCount = 2;
  602. VmaPool pool;
  603. vmaCreatePool(allocator, &poolCreateInfo, &pool);
  604. // Allocate a buffer out of it.
  605. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  606. bufCreateInfo.size = 1024;
  607. bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  608. VmaAllocationCreateInfo allocCreateInfo = {};
  609. allocCreateInfo.pool = pool;
  610. VkBuffer buf;
  611. VmaAllocation alloc;
  612. VmaAllocationInfo allocInfo;
  613. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  614. \endcode
  615. You have to free all allocations made from this pool before destroying it.
  616. \code
  617. vmaDestroyBuffer(allocator, buf, alloc);
  618. vmaDestroyPool(allocator, pool);
  619. \endcode
  620. \section custom_memory_pools_MemTypeIndex Choosing memory type index
  621. When creating a pool, you must explicitly specify memory type index.
  622. To find the one suitable for your buffers or images, you can use helper functions
  623. vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo().
  624. You need to provide structures with example parameters of buffers or images
  625. that you are going to create in that pool.
  626. \code
  627. VkBufferCreateInfo exampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  628. exampleBufCreateInfo.size = 1024; // Whatever.
  629. exampleBufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; // Change if needed.
  630. VmaAllocationCreateInfo allocCreateInfo = {};
  631. allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; // Change if needed.
  632. uint32_t memTypeIndex;
  633. vmaFindMemoryTypeIndexForBufferInfo(allocator, &exampleBufCreateInfo, &allocCreateInfo, &memTypeIndex);
  634. VmaPoolCreateInfo poolCreateInfo = {};
  635. poolCreateInfo.memoryTypeIndex = memTypeIndex;
  636. // ...
  637. \endcode
  638. When creating buffers/images allocated in that pool, provide following parameters:
  639. - `VkBufferCreateInfo`: Prefer to pass same parameters as above.
  640. Otherwise you risk creating resources in a memory type that is not suitable for them, which may result in undefined behavior.
  641. Using different `VK_BUFFER_USAGE_` flags may work, but you shouldn't create images in a pool intended for buffers
  642. or the other way around.
  643. - VmaAllocationCreateInfo: You don't need to pass same parameters. Fill only `pool` member.
  644. Other members are ignored anyway.
  645. \section linear_algorithm Linear allocation algorithm
  646. Each Vulkan memory block managed by this library has accompanying metadata that
  647. keeps track of used and unused regions. By default, the metadata structure and
  648. algorithm tries to find best place for new allocations among free regions to
  649. optimize memory usage. This way you can allocate and free objects in any order.
  650. ![Default allocation algorithm](../gfx/Linear_allocator_1_algo_default.png)
  651. Sometimes there is a need to use simpler, linear allocation algorithm. You can
  652. create custom pool that uses such algorithm by adding flag
  653. #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT to VmaPoolCreateInfo::flags while creating
  654. #VmaPool object. Then an alternative metadata management is used. It always
  655. creates new allocations after last one and doesn't reuse free regions after
  656. allocations freed in the middle. It results in better allocation performance and
  657. less memory consumed by metadata.
  658. ![Linear allocation algorithm](../gfx/Linear_allocator_2_algo_linear.png)
  659. With this one flag, you can create a custom pool that can be used in many ways:
  660. free-at-once, stack, double stack, and ring buffer. See below for details.
  661. \subsection linear_algorithm_free_at_once Free-at-once
  662. In a pool that uses linear algorithm, you still need to free all the allocations
  663. individually, e.g. by using vmaFreeMemory() or vmaDestroyBuffer(). You can free
  664. them in any order. New allocations are always made after last one - free space
  665. in the middle is not reused. However, when you release all the allocation and
  666. the pool becomes empty, allocation starts from the beginning again. This way you
  667. can use linear algorithm to speed up creation of allocations that you are going
  668. to release all at once.
  669. ![Free-at-once](../gfx/Linear_allocator_3_free_at_once.png)
  670. This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount
  671. value that allows multiple memory blocks.
  672. \subsection linear_algorithm_stack Stack
  673. When you free an allocation that was created last, its space can be reused.
  674. Thanks to this, if you always release allocations in the order opposite to their
  675. creation (LIFO - Last In First Out), you can achieve behavior of a stack.
  676. ![Stack](../gfx/Linear_allocator_4_stack.png)
  677. This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount
  678. value that allows multiple memory blocks.
  679. \subsection linear_algorithm_double_stack Double stack
  680. The space reserved by a custom pool with linear algorithm may be used by two
  681. stacks:
  682. - First, default one, growing up from offset 0.
  683. - Second, "upper" one, growing down from the end towards lower offsets.
  684. To make allocation from upper stack, add flag #VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT
  685. to VmaAllocationCreateInfo::flags.
  686. ![Double stack](../gfx/Linear_allocator_7_double_stack.png)
  687. Double stack is available only in pools with one memory block -
  688. VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined.
  689. When the two stacks' ends meet so there is not enough space between them for a
  690. new allocation, such allocation fails with usual
  691. `VK_ERROR_OUT_OF_DEVICE_MEMORY` error.
  692. \subsection linear_algorithm_ring_buffer Ring buffer
  693. When you free some allocations from the beginning and there is not enough free space
  694. for a new one at the end of a pool, allocator's "cursor" wraps around to the
  695. beginning and starts allocation there. Thanks to this, if you always release
  696. allocations in the same order as you created them (FIFO - First In First Out),
  697. you can achieve behavior of a ring buffer / queue.
  698. ![Ring buffer](../gfx/Linear_allocator_5_ring_buffer.png)
  699. Pools with linear algorithm support [lost allocations](@ref lost_allocations) when used as ring buffer.
  700. If there is not enough free space for a new allocation, but existing allocations
  701. from the front of the queue can become lost, they become lost and the allocation
  702. succeeds.
  703. ![Ring buffer with lost allocations](../gfx/Linear_allocator_6_ring_buffer_lost.png)
  704. Ring buffer is available only in pools with one memory block -
  705. VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined.
  706. \section buddy_algorithm Buddy allocation algorithm
  707. There is another allocation algorithm that can be used with custom pools, called
  708. "buddy". Its internal data structure is based on a tree of blocks, each having
  709. size that is a power of two and a half of its parent's size. When you want to
  710. allocate memory of certain size, a free node in the tree is located. If it's too
  711. large, it is recursively split into two halves (called "buddies"). However, if
  712. requested allocation size is not a power of two, the size of a tree node is
  713. aligned up to the nearest power of two and the remaining space is wasted. When
  714. two buddy nodes become free, they are merged back into one larger node.
  715. ![Buddy allocator](../gfx/Buddy_allocator.png)
  716. The advantage of buddy allocation algorithm over default algorithm is faster
  717. allocation and deallocation, as well as smaller external fragmentation. The
  718. disadvantage is more wasted space (internal fragmentation).
  719. For more information, please read ["Buddy memory allocation" on Wikipedia](https://en.wikipedia.org/wiki/Buddy_memory_allocation)
  720. or other sources that describe this concept in general.
  721. To use buddy allocation algorithm with a custom pool, add flag
  722. #VMA_POOL_CREATE_BUDDY_ALGORITHM_BIT to VmaPoolCreateInfo::flags while creating
  723. #VmaPool object.
  724. Several limitations apply to pools that use buddy algorithm:
  725. - It is recommended to use VmaPoolCreateInfo::blockSize that is a power of two.
  726. Otherwise, only largest power of two smaller than the size is used for
  727. allocations. The remaining space always stays unused.
  728. - [Margins](@ref debugging_memory_usage_margins) and
  729. [corruption detection](@ref debugging_memory_usage_corruption_detection)
  730. don't work in such pools.
  731. - [Lost allocations](@ref lost_allocations) don't work in such pools. You can
  732. use them, but they never become lost. Support may be added in the future.
  733. - [Defragmentation](@ref defragmentation) doesn't work with allocations made from
  734. such pool.
  735. \page defragmentation Defragmentation
  736. Interleaved allocations and deallocations of many objects of varying size can
  737. cause fragmentation over time, which can lead to a situation where the library is unable
  738. to find a continuous range of free memory for a new allocation despite there is
  739. enough free space, just scattered across many small free ranges between existing
  740. allocations.
  741. To mitigate this problem, you can use defragmentation feature:
  742. structure #VmaDefragmentationInfo2, function vmaDefragmentationBegin(), vmaDefragmentationEnd().
  743. Given set of allocations,
  744. this function can move them to compact used memory, ensure more continuous free
  745. space and possibly also free some `VkDeviceMemory` blocks.
  746. What the defragmentation does is:
  747. - Updates #VmaAllocation objects to point to new `VkDeviceMemory` and offset.
  748. After allocation has been moved, its VmaAllocationInfo::deviceMemory and/or
  749. VmaAllocationInfo::offset changes. You must query them again using
  750. vmaGetAllocationInfo() if you need them.
  751. - Moves actual data in memory.
  752. What it doesn't do, so you need to do it yourself:
  753. - Recreate buffers and images that were bound to allocations that were defragmented and
  754. bind them with their new places in memory.
  755. You must use `vkDestroyBuffer()`, `vkDestroyImage()`,
  756. `vkCreateBuffer()`, `vkCreateImage()`, vmaBindBufferMemory(), vmaBindImageMemory()
  757. for that purpose and NOT vmaDestroyBuffer(),
  758. vmaDestroyImage(), vmaCreateBuffer(), vmaCreateImage(), because you don't need to
  759. destroy or create allocation objects!
  760. - Recreate views and update descriptors that point to these buffers and images.
  761. \section defragmentation_cpu Defragmenting CPU memory
  762. Following example demonstrates how you can run defragmentation on CPU.
  763. Only allocations created in memory types that are `HOST_VISIBLE` can be defragmented.
  764. Others are ignored.
  765. The way it works is:
  766. - It temporarily maps entire memory blocks when necessary.
  767. - It moves data using `memmove()` function.
  768. \code
  769. // Given following variables already initialized:
  770. VkDevice device;
  771. VmaAllocator allocator;
  772. std::vector<VkBuffer> buffers;
  773. std::vector<VmaAllocation> allocations;
  774. const uint32_t allocCount = (uint32_t)allocations.size();
  775. std::vector<VkBool32> allocationsChanged(allocCount);
  776. VmaDefragmentationInfo2 defragInfo = {};
  777. defragInfo.allocationCount = allocCount;
  778. defragInfo.pAllocations = allocations.data();
  779. defragInfo.pAllocationsChanged = allocationsChanged.data();
  780. defragInfo.maxCpuBytesToMove = VK_WHOLE_SIZE; // No limit.
  781. defragInfo.maxCpuAllocationsToMove = UINT32_MAX; // No limit.
  782. VmaDefragmentationContext defragCtx;
  783. vmaDefragmentationBegin(allocator, &defragInfo, nullptr, &defragCtx);
  784. vmaDefragmentationEnd(allocator, defragCtx);
  785. for(uint32_t i = 0; i < allocCount; ++i)
  786. {
  787. if(allocationsChanged[i])
  788. {
  789. // Destroy buffer that is immutably bound to memory region which is no longer valid.
  790. vkDestroyBuffer(device, buffers[i], nullptr);
  791. // Create new buffer with same parameters.
  792. VkBufferCreateInfo bufferInfo = ...;
  793. vkCreateBuffer(device, &bufferInfo, nullptr, &buffers[i]);
  794. // You can make dummy call to vkGetBufferMemoryRequirements here to silence validation layer warning.
  795. // Bind new buffer to new memory region. Data contained in it is already moved.
  796. VmaAllocationInfo allocInfo;
  797. vmaGetAllocationInfo(allocator, allocations[i], &allocInfo);
  798. vmaBindBufferMemory(allocator, allocations[i], buffers[i]);
  799. }
  800. }
  801. \endcode
  802. Setting VmaDefragmentationInfo2::pAllocationsChanged is optional.
  803. This output array tells whether particular allocation in VmaDefragmentationInfo2::pAllocations at the same index
  804. has been modified during defragmentation.
  805. You can pass null, but you then need to query every allocation passed to defragmentation
  806. for new parameters using vmaGetAllocationInfo() if you might need to recreate and rebind a buffer or image associated with it.
  807. If you use [Custom memory pools](@ref choosing_memory_type_custom_memory_pools),
  808. you can fill VmaDefragmentationInfo2::poolCount and VmaDefragmentationInfo2::pPools
  809. instead of VmaDefragmentationInfo2::allocationCount and VmaDefragmentationInfo2::pAllocations
  810. to defragment all allocations in given pools.
  811. You cannot use VmaDefragmentationInfo2::pAllocationsChanged in that case.
  812. You can also combine both methods.
  813. \section defragmentation_gpu Defragmenting GPU memory
  814. It is also possible to defragment allocations created in memory types that are not `HOST_VISIBLE`.
  815. To do that, you need to pass a command buffer that meets requirements as described in
  816. VmaDefragmentationInfo2::commandBuffer. The way it works is:
  817. - It creates temporary buffers and binds them to entire memory blocks when necessary.
  818. - It issues `vkCmdCopyBuffer()` to passed command buffer.
  819. Example:
  820. \code
  821. // Given following variables already initialized:
  822. VkDevice device;
  823. VmaAllocator allocator;
  824. VkCommandBuffer commandBuffer;
  825. std::vector<VkBuffer> buffers;
  826. std::vector<VmaAllocation> allocations;
  827. const uint32_t allocCount = (uint32_t)allocations.size();
  828. std::vector<VkBool32> allocationsChanged(allocCount);
  829. VkCommandBufferBeginInfo cmdBufBeginInfo = ...;
  830. vkBeginCommandBuffer(commandBuffer, &cmdBufBeginInfo);
  831. VmaDefragmentationInfo2 defragInfo = {};
  832. defragInfo.allocationCount = allocCount;
  833. defragInfo.pAllocations = allocations.data();
  834. defragInfo.pAllocationsChanged = allocationsChanged.data();
  835. defragInfo.maxGpuBytesToMove = VK_WHOLE_SIZE; // Notice it's "GPU" this time.
  836. defragInfo.maxGpuAllocationsToMove = UINT32_MAX; // Notice it's "GPU" this time.
  837. defragInfo.commandBuffer = commandBuffer;
  838. VmaDefragmentationContext defragCtx;
  839. vmaDefragmentationBegin(allocator, &defragInfo, nullptr, &defragCtx);
  840. vkEndCommandBuffer(commandBuffer);
  841. // Submit commandBuffer.
  842. // Wait for a fence that ensures commandBuffer execution finished.
  843. vmaDefragmentationEnd(allocator, defragCtx);
  844. for(uint32_t i = 0; i < allocCount; ++i)
  845. {
  846. if(allocationsChanged[i])
  847. {
  848. // Destroy buffer that is immutably bound to memory region which is no longer valid.
  849. vkDestroyBuffer(device, buffers[i], nullptr);
  850. // Create new buffer with same parameters.
  851. VkBufferCreateInfo bufferInfo = ...;
  852. vkCreateBuffer(device, &bufferInfo, nullptr, &buffers[i]);
  853. // You can make dummy call to vkGetBufferMemoryRequirements here to silence validation layer warning.
  854. // Bind new buffer to new memory region. Data contained in it is already moved.
  855. VmaAllocationInfo allocInfo;
  856. vmaGetAllocationInfo(allocator, allocations[i], &allocInfo);
  857. vmaBindBufferMemory(allocator, allocations[i], buffers[i]);
  858. }
  859. }
  860. \endcode
  861. You can combine these two methods by specifying non-zero `maxGpu*` as well as `maxCpu*` parameters.
  862. The library automatically chooses best method to defragment each memory pool.
  863. You may try not to block your entire program to wait until defragmentation finishes,
  864. but do it in the background, as long as you carefully fullfill requirements described
  865. in function vmaDefragmentationBegin().
  866. \section defragmentation_additional_notes Additional notes
  867. It is only legal to defragment allocations bound to:
  868. - buffers
  869. - images created with `VK_IMAGE_CREATE_ALIAS_BIT`, `VK_IMAGE_TILING_LINEAR`, and
  870. being currently in `VK_IMAGE_LAYOUT_GENERAL` or `VK_IMAGE_LAYOUT_PREINITIALIZED`.
  871. Defragmentation of images created with `VK_IMAGE_TILING_OPTIMAL` or in any other
  872. layout may give undefined results.
  873. If you defragment allocations bound to images, new images to be bound to new
  874. memory region after defragmentation should be created with `VK_IMAGE_LAYOUT_PREINITIALIZED`
  875. and then transitioned to their original layout from before defragmentation if
  876. needed using an image memory barrier.
  877. While using defragmentation, you may experience validation layer warnings, which you just need to ignore.
  878. See [Validation layer warnings](@ref general_considerations_validation_layer_warnings).
  879. Please don't expect memory to be fully compacted after defragmentation.
  880. Algorithms inside are based on some heuristics that try to maximize number of Vulkan
  881. memory blocks to make totally empty to release them, as well as to maximize continuous
  882. empty space inside remaining blocks, while minimizing the number and size of allocations that
  883. need to be moved. Some fragmentation may still remain - this is normal.
  884. \section defragmentation_custom_algorithm Writing custom defragmentation algorithm
  885. If you want to implement your own, custom defragmentation algorithm,
  886. there is infrastructure prepared for that,
  887. but it is not exposed through the library API - you need to hack its source code.
  888. Here are steps needed to do this:
  889. -# Main thing you need to do is to define your own class derived from base abstract
  890. class `VmaDefragmentationAlgorithm` and implement your version of its pure virtual methods.
  891. See definition and comments of this class for details.
  892. -# Your code needs to interact with device memory block metadata.
  893. If you need more access to its data than it's provided by its public interface,
  894. declare your new class as a friend class e.g. in class `VmaBlockMetadata_Generic`.
  895. -# If you want to create a flag that would enable your algorithm or pass some additional
  896. flags to configure it, add them to `VmaDefragmentationFlagBits` and use them in
  897. VmaDefragmentationInfo2::flags.
  898. -# Modify function `VmaBlockVectorDefragmentationContext::Begin` to create object
  899. of your new class whenever needed.
  900. \page lost_allocations Lost allocations
  901. If your game oversubscribes video memory, if may work OK in previous-generation
  902. graphics APIs (DirectX 9, 10, 11, OpenGL) because resources are automatically
  903. paged to system RAM. In Vulkan you can't do it because when you run out of
  904. memory, an allocation just fails. If you have more data (e.g. textures) that can
  905. fit into VRAM and you don't need it all at once, you may want to upload them to
  906. GPU on demand and "push out" ones that are not used for a long time to make room
  907. for the new ones, effectively using VRAM (or a cartain memory pool) as a form of
  908. cache. Vulkan Memory Allocator can help you with that by supporting a concept of
  909. "lost allocations".
  910. To create an allocation that can become lost, include #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT
  911. flag in VmaAllocationCreateInfo::flags. Before using a buffer or image bound to
  912. such allocation in every new frame, you need to query it if it's not lost.
  913. To check it, call vmaTouchAllocation().
  914. If the allocation is lost, you should not use it or buffer/image bound to it.
  915. You mustn't forget to destroy this allocation and this buffer/image.
  916. vmaGetAllocationInfo() can also be used for checking status of the allocation.
  917. Allocation is lost when returned VmaAllocationInfo::deviceMemory == `VK_NULL_HANDLE`.
  918. To create an allocation that can make some other allocations lost to make room
  919. for it, use #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flag. You will
  920. usually use both flags #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT and
  921. #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT at the same time.
  922. Warning! Current implementation uses quite naive, brute force algorithm,
  923. which can make allocation calls that use #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT
  924. flag quite slow. A new, more optimal algorithm and data structure to speed this
  925. up is planned for the future.
  926. <b>Q: When interleaving creation of new allocations with usage of existing ones,
  927. how do you make sure that an allocation won't become lost while it's used in the
  928. current frame?</b>
  929. It is ensured because vmaTouchAllocation() / vmaGetAllocationInfo() not only returns allocation
  930. status/parameters and checks whether it's not lost, but when it's not, it also
  931. atomically marks it as used in the current frame, which makes it impossible to
  932. become lost in that frame. It uses lockless algorithm, so it works fast and
  933. doesn't involve locking any internal mutex.
  934. <b>Q: What if my allocation may still be in use by the GPU when it's rendering a
  935. previous frame while I already submit new frame on the CPU?</b>
  936. You can make sure that allocations "touched" by vmaTouchAllocation() / vmaGetAllocationInfo() will not
  937. become lost for a number of additional frames back from the current one by
  938. specifying this number as VmaAllocatorCreateInfo::frameInUseCount (for default
  939. memory pool) and VmaPoolCreateInfo::frameInUseCount (for custom pool).
  940. <b>Q: How do you inform the library when new frame starts?</b>
  941. You need to call function vmaSetCurrentFrameIndex().
  942. Example code:
  943. \code
  944. struct MyBuffer
  945. {
  946. VkBuffer m_Buf = nullptr;
  947. VmaAllocation m_Alloc = nullptr;
  948. // Called when the buffer is really needed in the current frame.
  949. void EnsureBuffer();
  950. };
  951. void MyBuffer::EnsureBuffer()
  952. {
  953. // Buffer has been created.
  954. if(m_Buf != VK_NULL_HANDLE)
  955. {
  956. // Check if its allocation is not lost + mark it as used in current frame.
  957. if(vmaTouchAllocation(allocator, m_Alloc))
  958. {
  959. // It's all OK - safe to use m_Buf.
  960. return;
  961. }
  962. }
  963. // Buffer not yet exists or lost - destroy and recreate it.
  964. vmaDestroyBuffer(allocator, m_Buf, m_Alloc);
  965. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  966. bufCreateInfo.size = 1024;
  967. bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  968. VmaAllocationCreateInfo allocCreateInfo = {};
  969. allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  970. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT |
  971. VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT;
  972. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &m_Buf, &m_Alloc, nullptr);
  973. }
  974. \endcode
  975. When using lost allocations, you may see some Vulkan validation layer warnings
  976. about overlapping regions of memory bound to different kinds of buffers and
  977. images. This is still valid as long as you implement proper handling of lost
  978. allocations (like in the example above) and don't use them.
  979. You can create an allocation that is already in lost state from the beginning using function
  980. vmaCreateLostAllocation(). It may be useful if you need a "dummy" allocation that is not null.
  981. You can call function vmaMakePoolAllocationsLost() to set all eligible allocations
  982. in a specified custom pool to lost state.
  983. Allocations that have been "touched" in current frame or VmaPoolCreateInfo::frameInUseCount frames back
  984. cannot become lost.
  985. <b>Q: Can I touch allocation that cannot become lost?</b>
  986. Yes, although it has no visible effect.
  987. Calls to vmaGetAllocationInfo() and vmaTouchAllocation() update last use frame index
  988. also for allocations that cannot become lost, but the only way to observe it is to dump
  989. internal allocator state using vmaBuildStatsString().
  990. You can use this feature for debugging purposes to explicitly mark allocations that you use
  991. in current frame and then analyze JSON dump to see for how long each allocation stays unused.
  992. \page statistics Statistics
  993. This library contains functions that return information about its internal state,
  994. especially the amount of memory allocated from Vulkan.
  995. Please keep in mind that these functions need to traverse all internal data structures
  996. to gather these information, so they may be quite time-consuming.
  997. Don't call them too often.
  998. \section statistics_numeric_statistics Numeric statistics
  999. You can query for overall statistics of the allocator using function vmaCalculateStats().
  1000. Information are returned using structure #VmaStats.
  1001. It contains #VmaStatInfo - number of allocated blocks, number of allocations
  1002. (occupied ranges in these blocks), number of unused (free) ranges in these blocks,
  1003. number of bytes used and unused (but still allocated from Vulkan) and other information.
  1004. They are summed across memory heaps, memory types and total for whole allocator.
  1005. You can query for statistics of a custom pool using function vmaGetPoolStats().
  1006. Information are returned using structure #VmaPoolStats.
  1007. You can query for information about specific allocation using function vmaGetAllocationInfo().
  1008. It fill structure #VmaAllocationInfo.
  1009. \section statistics_json_dump JSON dump
  1010. You can dump internal state of the allocator to a string in JSON format using function vmaBuildStatsString().
  1011. The result is guaranteed to be correct JSON.
  1012. It uses ANSI encoding.
  1013. Any strings provided by user (see [Allocation names](@ref allocation_names))
  1014. are copied as-is and properly escaped for JSON, so if they use UTF-8, ISO-8859-2 or any other encoding,
  1015. this JSON string can be treated as using this encoding.
  1016. It must be freed using function vmaFreeStatsString().
  1017. The format of this JSON string is not part of official documentation of the library,
  1018. but it will not change in backward-incompatible way without increasing library major version number
  1019. and appropriate mention in changelog.
  1020. The JSON string contains all the data that can be obtained using vmaCalculateStats().
  1021. It can also contain detailed map of allocated memory blocks and their regions -
  1022. free and occupied by allocations.
  1023. This allows e.g. to visualize the memory or assess fragmentation.
  1024. \page allocation_annotation Allocation names and user data
  1025. \section allocation_user_data Allocation user data
  1026. You can annotate allocations with your own information, e.g. for debugging purposes.
  1027. To do that, fill VmaAllocationCreateInfo::pUserData field when creating
  1028. an allocation. It's an opaque `void*` pointer. You can use it e.g. as a pointer,
  1029. some handle, index, key, ordinal number or any other value that would associate
  1030. the allocation with your custom metadata.
  1031. \code
  1032. VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  1033. // Fill bufferInfo...
  1034. MyBufferMetadata* pMetadata = CreateBufferMetadata();
  1035. VmaAllocationCreateInfo allocCreateInfo = {};
  1036. allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  1037. allocCreateInfo.pUserData = pMetadata;
  1038. VkBuffer buffer;
  1039. VmaAllocation allocation;
  1040. vmaCreateBuffer(allocator, &bufferInfo, &allocCreateInfo, &buffer, &allocation, nullptr);
  1041. \endcode
  1042. The pointer may be later retrieved as VmaAllocationInfo::pUserData:
  1043. \code
  1044. VmaAllocationInfo allocInfo;
  1045. vmaGetAllocationInfo(allocator, allocation, &allocInfo);
  1046. MyBufferMetadata* pMetadata = (MyBufferMetadata*)allocInfo.pUserData;
  1047. \endcode
  1048. It can also be changed using function vmaSetAllocationUserData().
  1049. Values of (non-zero) allocations' `pUserData` are printed in JSON report created by
  1050. vmaBuildStatsString(), in hexadecimal form.
  1051. \section allocation_names Allocation names
  1052. There is alternative mode available where `pUserData` pointer is used to point to
  1053. a null-terminated string, giving a name to the allocation. To use this mode,
  1054. set #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT flag in VmaAllocationCreateInfo::flags.
  1055. Then `pUserData` passed as VmaAllocationCreateInfo::pUserData or argument to
  1056. vmaSetAllocationUserData() must be either null or pointer to a null-terminated string.
  1057. The library creates internal copy of the string, so the pointer you pass doesn't need
  1058. to be valid for whole lifetime of the allocation. You can free it after the call.
  1059. \code
  1060. VkImageCreateInfo imageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
  1061. // Fill imageInfo...
  1062. std::string imageName = "Texture: ";
  1063. imageName += fileName;
  1064. VmaAllocationCreateInfo allocCreateInfo = {};
  1065. allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  1066. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT;
  1067. allocCreateInfo.pUserData = imageName.c_str();
  1068. VkImage image;
  1069. VmaAllocation allocation;
  1070. vmaCreateImage(allocator, &imageInfo, &allocCreateInfo, &image, &allocation, nullptr);
  1071. \endcode
  1072. The value of `pUserData` pointer of the allocation will be different than the one
  1073. you passed when setting allocation's name - pointing to a buffer managed
  1074. internally that holds copy of the string.
  1075. \code
  1076. VmaAllocationInfo allocInfo;
  1077. vmaGetAllocationInfo(allocator, allocation, &allocInfo);
  1078. const char* imageName = (const char*)allocInfo.pUserData;
  1079. printf("Image name: %s\n", imageName);
  1080. \endcode
  1081. That string is also printed in JSON report created by vmaBuildStatsString().
  1082. \note Passing string name to VMA allocation doesn't automatically set it to the Vulkan buffer or image created with it.
  1083. You must do it manually using an extension like VK_EXT_debug_utils, which is independent of this library.
  1084. \page debugging_memory_usage Debugging incorrect memory usage
  1085. If you suspect a bug with memory usage, like usage of uninitialized memory or
  1086. memory being overwritten out of bounds of an allocation,
  1087. you can use debug features of this library to verify this.
  1088. \section debugging_memory_usage_initialization Memory initialization
  1089. If you experience a bug with incorrect and nondeterministic data in your program and you suspect uninitialized memory to be used,
  1090. you can enable automatic memory initialization to verify this.
  1091. To do it, define macro `VMA_DEBUG_INITIALIZE_ALLOCATIONS` to 1.
  1092. \code
  1093. #define VMA_DEBUG_INITIALIZE_ALLOCATIONS 1
  1094. #include "vk_mem_alloc.h"
  1095. \endcode
  1096. It makes memory of all new allocations initialized to bit pattern `0xDCDCDCDC`.
  1097. Before an allocation is destroyed, its memory is filled with bit pattern `0xEFEFEFEF`.
  1098. Memory is automatically mapped and unmapped if necessary.
  1099. If you find these values while debugging your program, good chances are that you incorrectly
  1100. read Vulkan memory that is allocated but not initialized, or already freed, respectively.
  1101. Memory initialization works only with memory types that are `HOST_VISIBLE`.
  1102. It works also with dedicated allocations.
  1103. It doesn't work with allocations created with #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag,
  1104. as they cannot be mapped.
  1105. \section debugging_memory_usage_margins Margins
  1106. By default, allocations are laid out in memory blocks next to each other if possible
  1107. (considering required alignment, `bufferImageGranularity`, and `nonCoherentAtomSize`).
  1108. ![Allocations without margin](../gfx/Margins_1.png)
  1109. Define macro `VMA_DEBUG_MARGIN` to some non-zero value (e.g. 16) to enforce specified
  1110. number of bytes as a margin before and after every allocation.
  1111. \code
  1112. #define VMA_DEBUG_MARGIN 16
  1113. #include "vk_mem_alloc.h"
  1114. \endcode
  1115. ![Allocations with margin](../gfx/Margins_2.png)
  1116. If your bug goes away after enabling margins, it means it may be caused by memory
  1117. being overwritten outside of allocation boundaries. It is not 100% certain though.
  1118. Change in application behavior may also be caused by different order and distribution
  1119. of allocations across memory blocks after margins are applied.
  1120. The margin is applied also before first and after last allocation in a block.
  1121. It may occur only once between two adjacent allocations.
  1122. Margins work with all types of memory.
  1123. Margin is applied only to allocations made out of memory blocks and not to dedicated
  1124. allocations, which have their own memory block of specific size.
  1125. It is thus not applied to allocations made using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT flag
  1126. or those automatically decided to put into dedicated allocations, e.g. due to its
  1127. large size or recommended by VK_KHR_dedicated_allocation extension.
  1128. Margins are also not active in custom pools created with #VMA_POOL_CREATE_BUDDY_ALGORITHM_BIT flag.
  1129. Margins appear in [JSON dump](@ref statistics_json_dump) as part of free space.
  1130. Note that enabling margins increases memory usage and fragmentation.
  1131. \section debugging_memory_usage_corruption_detection Corruption detection
  1132. You can additionally define macro `VMA_DEBUG_DETECT_CORRUPTION` to 1 to enable validation
  1133. of contents of the margins.
  1134. \code
  1135. #define VMA_DEBUG_MARGIN 16
  1136. #define VMA_DEBUG_DETECT_CORRUPTION 1
  1137. #include "vk_mem_alloc.h"
  1138. \endcode
  1139. When this feature is enabled, number of bytes specified as `VMA_DEBUG_MARGIN`
  1140. (it must be multiply of 4) before and after every allocation is filled with a magic number.
  1141. This idea is also know as "canary".
  1142. Memory is automatically mapped and unmapped if necessary.
  1143. This number is validated automatically when the allocation is destroyed.
  1144. If it's not equal to the expected value, `VMA_ASSERT()` is executed.
  1145. It clearly means that either CPU or GPU overwritten the memory outside of boundaries of the allocation,
  1146. which indicates a serious bug.
  1147. You can also explicitly request checking margins of all allocations in all memory blocks
  1148. that belong to specified memory types by using function vmaCheckCorruption(),
  1149. or in memory blocks that belong to specified custom pool, by using function
  1150. vmaCheckPoolCorruption().
  1151. Margin validation (corruption detection) works only for memory types that are
  1152. `HOST_VISIBLE` and `HOST_COHERENT`.
  1153. \page record_and_replay Record and replay
  1154. \section record_and_replay_introduction Introduction
  1155. While using the library, sequence of calls to its functions together with their
  1156. parameters can be recorded to a file and later replayed using standalone player
  1157. application. It can be useful to:
  1158. - Test correctness - check if same sequence of calls will not cause crash or
  1159. failures on a target platform.
  1160. - Gather statistics - see number of allocations, peak memory usage, number of
  1161. calls etc.
  1162. - Benchmark performance - see how much time it takes to replay the whole
  1163. sequence.
  1164. \section record_and_replay_usage Usage
  1165. Recording functionality is disabled by default.
  1166. To enable it, define following macro before every include of this library:
  1167. \code
  1168. #define VMA_RECORDING_ENABLED 1
  1169. \endcode
  1170. <b>To record sequence of calls to a file:</b> Fill in
  1171. VmaAllocatorCreateInfo::pRecordSettings member while creating #VmaAllocator
  1172. object. File is opened and written during whole lifetime of the allocator.
  1173. <b>To replay file:</b> Use VmaReplay - standalone command-line program.
  1174. Precompiled binary can be found in "bin" directory.
  1175. Its source can be found in "src/VmaReplay" directory.
  1176. Its project is generated by Premake.
  1177. Command line syntax is printed when the program is launched without parameters.
  1178. Basic usage:
  1179. VmaReplay.exe MyRecording.csv
  1180. <b>Documentation of file format</b> can be found in file: "docs/Recording file format.md".
  1181. It's a human-readable, text file in CSV format (Comma Separated Values).
  1182. \section record_and_replay_additional_considerations Additional considerations
  1183. - Replaying file that was recorded on a different GPU (with different parameters
  1184. like `bufferImageGranularity`, `nonCoherentAtomSize`, and especially different
  1185. set of memory heaps and types) may give different performance and memory usage
  1186. results, as well as issue some warnings and errors.
  1187. - Current implementation of recording in VMA, as well as VmaReplay application, is
  1188. coded and tested only on Windows. Inclusion of recording code is driven by
  1189. `VMA_RECORDING_ENABLED` macro. Support for other platforms should be easy to
  1190. add. Contributions are welcomed.
  1191. \page usage_patterns Recommended usage patterns
  1192. See also slides from talk:
  1193. [Sawicki, Adam. Advanced Graphics Techniques Tutorial: Memory management in Vulkan and DX12. Game Developers Conference, 2018](https://www.gdcvault.com/play/1025458/Advanced-Graphics-Techniques-Tutorial-New)
  1194. \section usage_patterns_common_mistakes Common mistakes
  1195. <b>Use of CPU_TO_GPU instead of CPU_ONLY memory</b>
  1196. #VMA_MEMORY_USAGE_CPU_TO_GPU is recommended only for resources that will be
  1197. mapped and written by the CPU, as well as read directly by the GPU - like some
  1198. buffers or textures updated every frame (dynamic). If you create a staging copy
  1199. of a resource to be written by CPU and then used as a source of transfer to
  1200. another resource placed in the GPU memory, that staging resource should be
  1201. created with #VMA_MEMORY_USAGE_CPU_ONLY. Please read the descriptions of these
  1202. enums carefully for details.
  1203. <b>Unnecessary use of custom pools</b>
  1204. \ref custom_memory_pools may be useful for special purposes - when you want to
  1205. keep certain type of resources separate e.g. to reserve minimum amount of memory
  1206. for them, limit maximum amount of memory they can occupy, or make some of them
  1207. push out the other through the mechanism of \ref lost_allocations. For most
  1208. resources this is not needed and so it is not recommended to create #VmaPool
  1209. objects and allocations out of them. Allocating from the default pool is sufficient.
  1210. \section usage_patterns_simple Simple patterns
  1211. \subsection usage_patterns_simple_render_targets Render targets
  1212. <b>When:</b>
  1213. Any resources that you frequently write and read on GPU,
  1214. e.g. images used as color attachments (aka "render targets"), depth-stencil attachments,
  1215. images/buffers used as storage image/buffer (aka "Unordered Access View (UAV)").
  1216. <b>What to do:</b>
  1217. Create them in video memory that is fastest to access from GPU using
  1218. #VMA_MEMORY_USAGE_GPU_ONLY.
  1219. Consider using [VK_KHR_dedicated_allocation](@ref vk_khr_dedicated_allocation) extension
  1220. and/or manually creating them as dedicated allocations using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
  1221. especially if they are large or if you plan to destroy and recreate them e.g. when
  1222. display resolution changes.
  1223. Prefer to create such resources first and all other GPU resources (like textures and vertex buffers) later.
  1224. \subsection usage_patterns_simple_immutable_resources Immutable resources
  1225. <b>When:</b>
  1226. Any resources that you fill on CPU only once (aka "immutable") or infrequently
  1227. and then read frequently on GPU,
  1228. e.g. textures, vertex and index buffers, constant buffers that don't change often.
  1229. <b>What to do:</b>
  1230. Create them in video memory that is fastest to access from GPU using
  1231. #VMA_MEMORY_USAGE_GPU_ONLY.
  1232. To initialize content of such resource, create a CPU-side (aka "staging") copy of it
  1233. in system memory - #VMA_MEMORY_USAGE_CPU_ONLY, map it, fill it,
  1234. and submit a transfer from it to the GPU resource.
  1235. You can keep the staging copy if you need it for another upload transfer in the future.
  1236. If you don't, you can destroy it or reuse this buffer for uploading different resource
  1237. after the transfer finishes.
  1238. Prefer to create just buffers in system memory rather than images, even for uploading textures.
  1239. Use `vkCmdCopyBufferToImage()`.
  1240. Dont use images with `VK_IMAGE_TILING_LINEAR`.
  1241. \subsection usage_patterns_dynamic_resources Dynamic resources
  1242. <b>When:</b>
  1243. Any resources that change frequently (aka "dynamic"), e.g. every frame or every draw call,
  1244. written on CPU, read on GPU.
  1245. <b>What to do:</b>
  1246. Create them using #VMA_MEMORY_USAGE_CPU_TO_GPU.
  1247. You can map it and write to it directly on CPU, as well as read from it on GPU.
  1248. This is a more complex situation. Different solutions are possible,
  1249. and the best one depends on specific GPU type, but you can use this simple approach for the start.
  1250. Prefer to write to such resource sequentially (e.g. using `memcpy`).
  1251. Don't perform random access or any reads from it on CPU, as it may be very slow.
  1252. Also note that textures written directly from the host through a mapped pointer need to be in LINEAR not OPTIMAL layout.
  1253. \subsection usage_patterns_readback Readback
  1254. <b>When:</b>
  1255. Resources that contain data written by GPU that you want to read back on CPU,
  1256. e.g. results of some computations.
  1257. <b>What to do:</b>
  1258. Create them using #VMA_MEMORY_USAGE_GPU_TO_CPU.
  1259. You can write to them directly on GPU, as well as map and read them on CPU.
  1260. \section usage_patterns_advanced Advanced patterns
  1261. \subsection usage_patterns_integrated_graphics Detecting integrated graphics
  1262. You can support integrated graphics (like Intel HD Graphics, AMD APU) better
  1263. by detecting it in Vulkan.
  1264. To do it, call `vkGetPhysicalDeviceProperties()`, inspect
  1265. `VkPhysicalDeviceProperties::deviceType` and look for `VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU`.
  1266. When you find it, you can assume that memory is unified and all memory types are comparably fast
  1267. to access from GPU, regardless of `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`.
  1268. You can then sum up sizes of all available memory heaps and treat them as useful for
  1269. your GPU resources, instead of only `DEVICE_LOCAL` ones.
  1270. You can also prefer to create your resources in memory types that are `HOST_VISIBLE` to map them
  1271. directly instead of submitting explicit transfer (see below).
  1272. \subsection usage_patterns_direct_vs_transfer Direct access versus transfer
  1273. For resources that you frequently write on CPU and read on GPU, many solutions are possible:
  1274. -# Create one copy in video memory using #VMA_MEMORY_USAGE_GPU_ONLY,
  1275. second copy in system memory using #VMA_MEMORY_USAGE_CPU_ONLY and submit explicit transfer each time.
  1276. -# Create just a single copy using #VMA_MEMORY_USAGE_CPU_TO_GPU, map it and fill it on CPU,
  1277. read it directly on GPU.
  1278. -# Create just a single copy using #VMA_MEMORY_USAGE_CPU_ONLY, map it and fill it on CPU,
  1279. read it directly on GPU.
  1280. Which solution is the most efficient depends on your resource and especially on the GPU.
  1281. It is best to measure it and then make the decision.
  1282. Some general recommendations:
  1283. - On integrated graphics use (2) or (3) to avoid unnecessary time and memory overhead
  1284. related to using a second copy and making transfer.
  1285. - For small resources (e.g. constant buffers) use (2).
  1286. Discrete AMD cards have special 256 MiB pool of video memory that is directly mappable.
  1287. Even if the resource ends up in system memory, its data may be cached on GPU after first
  1288. fetch over PCIe bus.
  1289. - For larger resources (e.g. textures), decide between (1) and (2).
  1290. You may want to differentiate NVIDIA and AMD, e.g. by looking for memory type that is
  1291. both `DEVICE_LOCAL` and `HOST_VISIBLE`. When you find it, use (2), otherwise use (1).
  1292. Similarly, for resources that you frequently write on GPU and read on CPU, multiple
  1293. solutions are possible:
  1294. -# Create one copy in video memory using #VMA_MEMORY_USAGE_GPU_ONLY,
  1295. second copy in system memory using #VMA_MEMORY_USAGE_GPU_TO_CPU and submit explicit tranfer each time.
  1296. -# Create just single copy using #VMA_MEMORY_USAGE_GPU_TO_CPU, write to it directly on GPU,
  1297. map it and read it on CPU.
  1298. You should take some measurements to decide which option is faster in case of your specific
  1299. resource.
  1300. Note that textures accessed directly from the host through a mapped pointer need to be in LINEAR layout,
  1301. which may slow down their usage on the device.
  1302. Textures accessed only by the device and transfer operations can use OPTIMAL layout.
  1303. If you don't want to specialize your code for specific types of GPUs, you can still make
  1304. an simple optimization for cases when your resource ends up in mappable memory to use it
  1305. directly in this case instead of creating CPU-side staging copy.
  1306. For details see [Finding out if memory is mappable](@ref memory_mapping_finding_if_memory_mappable).
  1307. \page configuration Configuration
  1308. Please check "CONFIGURATION SECTION" in the code to find macros that you can define
  1309. before each include of this file or change directly in this file to provide
  1310. your own implementation of basic facilities like assert, `min()` and `max()` functions,
  1311. mutex, atomic etc.
  1312. The library uses its own implementation of containers by default, but you can switch to using
  1313. STL containers instead.
  1314. For example, define `VMA_ASSERT(expr)` before including the library to provide
  1315. custom implementation of the assertion, compatible with your project.
  1316. By default it is defined to standard C `assert(expr)` in `_DEBUG` configuration
  1317. and empty otherwise.
  1318. \section config_Vulkan_functions Pointers to Vulkan functions
  1319. There are multiple ways to import pointers to Vulkan functions in the library.
  1320. In the simplest case you don't need to do anything.
  1321. If the compilation or linking of your program or the initialization of the #VmaAllocator
  1322. doesn't work for you, you can try to reconfigure it.
  1323. First, the allocator tries to fetch pointers to Vulkan functions linked statically,
  1324. like this:
  1325. \code
  1326. m_VulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkAllocateMemory;
  1327. \endcode
  1328. If you want to disable this feature, set configuration macro: `#define VMA_STATIC_VULKAN_FUNCTIONS 0`.
  1329. Second, you can provide the pointers yourself by setting member VmaAllocatorCreateInfo::pVulkanFunctions.
  1330. You can fetch them e.g. using functions `vkGetInstanceProcAddr` and `vkGetDeviceProcAddr` or
  1331. by using a helper library like [volk](https://github.com/zeux/volk).
  1332. Third, VMA tries to fetch remaining pointers that are still null by calling
  1333. `vkGetInstanceProcAddr` and `vkGetDeviceProcAddr` on its own.
  1334. If you want to disable this feature, set configuration macro: `#define VMA_DYNAMIC_VULKAN_FUNCTIONS 0`.
  1335. Finally, all the function pointers required by the library (considering selected
  1336. Vulkan version and enabled extensions) are checked with `VMA_ASSERT` if they are not null.
  1337. \section custom_memory_allocator Custom host memory allocator
  1338. If you use custom allocator for CPU memory rather than default operator `new`
  1339. and `delete` from C++, you can make this library using your allocator as well
  1340. by filling optional member VmaAllocatorCreateInfo::pAllocationCallbacks. These
  1341. functions will be passed to Vulkan, as well as used by the library itself to
  1342. make any CPU-side allocations.
  1343. \section allocation_callbacks Device memory allocation callbacks
  1344. The library makes calls to `vkAllocateMemory()` and `vkFreeMemory()` internally.
  1345. You can setup callbacks to be informed about these calls, e.g. for the purpose
  1346. of gathering some statistics. To do it, fill optional member
  1347. VmaAllocatorCreateInfo::pDeviceMemoryCallbacks.
  1348. \section heap_memory_limit Device heap memory limit
  1349. When device memory of certain heap runs out of free space, new allocations may
  1350. fail (returning error code) or they may succeed, silently pushing some existing
  1351. memory blocks from GPU VRAM to system RAM (which degrades performance). This
  1352. behavior is implementation-dependent - it depends on GPU vendor and graphics
  1353. driver.
  1354. On AMD cards it can be controlled while creating Vulkan device object by using
  1355. VK_AMD_memory_overallocation_behavior extension, if available.
  1356. Alternatively, if you want to test how your program behaves with limited amount of Vulkan device
  1357. memory available without switching your graphics card to one that really has
  1358. smaller VRAM, you can use a feature of this library intended for this purpose.
  1359. To do it, fill optional member VmaAllocatorCreateInfo::pHeapSizeLimit.
  1360. \page vk_khr_dedicated_allocation VK_KHR_dedicated_allocation
  1361. VK_KHR_dedicated_allocation is a Vulkan extension which can be used to improve
  1362. performance on some GPUs. It augments Vulkan API with possibility to query
  1363. driver whether it prefers particular buffer or image to have its own, dedicated
  1364. allocation (separate `VkDeviceMemory` block) for better efficiency - to be able
  1365. to do some internal optimizations.
  1366. The extension is supported by this library. It will be used automatically when
  1367. enabled. To enable it:
  1368. 1 . When creating Vulkan device, check if following 2 device extensions are
  1369. supported (call `vkEnumerateDeviceExtensionProperties()`).
  1370. If yes, enable them (fill `VkDeviceCreateInfo::ppEnabledExtensionNames`).
  1371. - VK_KHR_get_memory_requirements2
  1372. - VK_KHR_dedicated_allocation
  1373. If you enabled these extensions:
  1374. 2 . Use #VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag when creating
  1375. your #VmaAllocator`to inform the library that you enabled required extensions
  1376. and you want the library to use them.
  1377. \code
  1378. allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT;
  1379. vmaCreateAllocator(&allocatorInfo, &allocator);
  1380. \endcode
  1381. That's all. The extension will be automatically used whenever you create a
  1382. buffer using vmaCreateBuffer() or image using vmaCreateImage().
  1383. When using the extension together with Vulkan Validation Layer, you will receive
  1384. warnings like this:
  1385. vkBindBufferMemory(): Binding memory to buffer 0x33 but vkGetBufferMemoryRequirements() has not been called on that buffer.
  1386. It is OK, you should just ignore it. It happens because you use function
  1387. `vkGetBufferMemoryRequirements2KHR()` instead of standard
  1388. `vkGetBufferMemoryRequirements()`, while the validation layer seems to be
  1389. unaware of it.
  1390. To learn more about this extension, see:
  1391. - [VK_KHR_dedicated_allocation in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/chap50.html#VK_KHR_dedicated_allocation)
  1392. - [VK_KHR_dedicated_allocation unofficial manual](http://asawicki.info/articles/VK_KHR_dedicated_allocation.php5)
  1393. \page vk_amd_device_coherent_memory VK_AMD_device_coherent_memory
  1394. VK_AMD_device_coherent_memory is a device extension that enables access to
  1395. additional memory types with `VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD` and
  1396. `VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` flag. It is useful mostly for
  1397. allocation of buffers intended for writing "breadcrumb markers" in between passes
  1398. or draw calls, which in turn are useful for debugging GPU crash/hang/TDR cases.
  1399. When the extension is available but has not been enabled, Vulkan physical device
  1400. still exposes those memory types, but their usage is forbidden. VMA automatically
  1401. takes care of that - it returns `VK_ERROR_FEATURE_NOT_PRESENT` when an attempt
  1402. to allocate memory of such type is made.
  1403. If you want to use this extension in connection with VMA, follow these steps:
  1404. \section vk_amd_device_coherent_memory_initialization Initialization
  1405. 1) Call `vkEnumerateDeviceExtensionProperties` for the physical device.
  1406. Check if the extension is supported - if returned array of `VkExtensionProperties` contains "VK_AMD_device_coherent_memory".
  1407. 2) Call `vkGetPhysicalDeviceFeatures2` for the physical device instead of old `vkGetPhysicalDeviceFeatures`.
  1408. Attach additional structure `VkPhysicalDeviceCoherentMemoryFeaturesAMD` to `VkPhysicalDeviceFeatures2::pNext` to be returned.
  1409. Check if the device feature is really supported - check if `VkPhysicalDeviceCoherentMemoryFeaturesAMD::deviceCoherentMemory` is true.
  1410. 3) While creating device with `vkCreateDevice`, enable this extension - add "VK_AMD_device_coherent_memory"
  1411. to the list passed as `VkDeviceCreateInfo::ppEnabledExtensionNames`.
  1412. 4) While creating the device, also don't set `VkDeviceCreateInfo::pEnabledFeatures`.
  1413. Fill in `VkPhysicalDeviceFeatures2` structure instead and pass it as `VkDeviceCreateInfo::pNext`.
  1414. Enable this device feature - attach additional structure `VkPhysicalDeviceCoherentMemoryFeaturesAMD` to
  1415. `VkPhysicalDeviceFeatures2::pNext` and set its member `deviceCoherentMemory` to `VK_TRUE`.
  1416. 5) While creating #VmaAllocator with vmaCreateAllocator() inform VMA that you
  1417. have enabled this extension and feature - add #VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT
  1418. to VmaAllocatorCreateInfo::flags.
  1419. \section vk_amd_device_coherent_memory_usage Usage
  1420. After following steps described above, you can create VMA allocations and custom pools
  1421. out of the special `DEVICE_COHERENT` and `DEVICE_UNCACHED` memory types on eligible
  1422. devices. There are multiple ways to do it, for example:
  1423. - You can request or prefer to allocate out of such memory types by adding
  1424. `VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD` to VmaAllocationCreateInfo::requiredFlags
  1425. or VmaAllocationCreateInfo::preferredFlags. Those flags can be freely mixed with
  1426. other ways of \ref choosing_memory_type, like setting VmaAllocationCreateInfo::usage.
  1427. - If you manually found memory type index to use for this purpose, force allocation
  1428. from this specific index by setting VmaAllocationCreateInfo::memoryTypeBits `= 1u << index`.
  1429. \section vk_amd_device_coherent_memory_more_information More information
  1430. To learn more about this extension, see [VK_AMD_device_coherent_memory in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/chap44.html#VK_AMD_device_coherent_memory)
  1431. Example use of this extension can be found in the code of the sample and test suite
  1432. accompanying this library.
  1433. \page enabling_buffer_device_address Enabling buffer device address
  1434. Device extension VK_KHR_buffer_device_address
  1435. allow to fetch raw GPU pointer to a buffer and pass it for usage in a shader code.
  1436. It is promoted to core Vulkan 1.2.
  1437. If you want to use this feature in connection with VMA, follow these steps:
  1438. \section enabling_buffer_device_address_initialization Initialization
  1439. 1) (For Vulkan version < 1.2) Call `vkEnumerateDeviceExtensionProperties` for the physical device.
  1440. Check if the extension is supported - if returned array of `VkExtensionProperties` contains
  1441. "VK_KHR_buffer_device_address".
  1442. 2) Call `vkGetPhysicalDeviceFeatures2` for the physical device instead of old `vkGetPhysicalDeviceFeatures`.
  1443. Attach additional structure `VkPhysicalDeviceBufferDeviceAddressFeatures*` to `VkPhysicalDeviceFeatures2::pNext` to be returned.
  1444. Check if the device feature is really supported - check if `VkPhysicalDeviceBufferDeviceAddressFeatures*::bufferDeviceAddress` is true.
  1445. 3) (For Vulkan version < 1.2) While creating device with `vkCreateDevice`, enable this extension - add
  1446. "VK_KHR_buffer_device_address" to the list passed as `VkDeviceCreateInfo::ppEnabledExtensionNames`.
  1447. 4) While creating the device, also don't set `VkDeviceCreateInfo::pEnabledFeatures`.
  1448. Fill in `VkPhysicalDeviceFeatures2` structure instead and pass it as `VkDeviceCreateInfo::pNext`.
  1449. Enable this device feature - attach additional structure `VkPhysicalDeviceBufferDeviceAddressFeatures*` to
  1450. `VkPhysicalDeviceFeatures2::pNext` and set its member `bufferDeviceAddress` to `VK_TRUE`.
  1451. 5) While creating #VmaAllocator with vmaCreateAllocator() inform VMA that you
  1452. have enabled this feature - add #VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT
  1453. to VmaAllocatorCreateInfo::flags.
  1454. \section enabling_buffer_device_address_usage Usage
  1455. After following steps described above, you can create buffers with `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT*` using VMA.
  1456. The library automatically adds `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT*` to
  1457. allocated memory blocks wherever it might be needed.
  1458. Please note that the library supports only `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT*`.
  1459. The second part of this functionality related to "capture and replay" is not supported,
  1460. as it is intended for usage in debugging tools like RenderDoc, not in everyday Vulkan usage.
  1461. \section enabling_buffer_device_address_more_information More information
  1462. To learn more about this extension, see [VK_KHR_buffer_device_address in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/chap46.html#VK_KHR_buffer_device_address)
  1463. Example use of this extension can be found in the code of the sample and test suite
  1464. accompanying this library.
  1465. \page general_considerations General considerations
  1466. \section general_considerations_thread_safety Thread safety
  1467. - The library has no global state, so separate #VmaAllocator objects can be used
  1468. independently.
  1469. There should be no need to create multiple such objects though - one per `VkDevice` is enough.
  1470. - By default, all calls to functions that take #VmaAllocator as first parameter
  1471. are safe to call from multiple threads simultaneously because they are
  1472. synchronized internally when needed.
  1473. - When the allocator is created with #VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT
  1474. flag, calls to functions that take such #VmaAllocator object must be
  1475. synchronized externally.
  1476. - Access to a #VmaAllocation object must be externally synchronized. For example,
  1477. you must not call vmaGetAllocationInfo() and vmaMapMemory() from different
  1478. threads at the same time if you pass the same #VmaAllocation object to these
  1479. functions.
  1480. \section general_considerations_validation_layer_warnings Validation layer warnings
  1481. When using this library, you can meet following types of warnings issued by
  1482. Vulkan validation layer. They don't necessarily indicate a bug, so you may need
  1483. to just ignore them.
  1484. - *vkBindBufferMemory(): Binding memory to buffer 0xeb8e4 but vkGetBufferMemoryRequirements() has not been called on that buffer.*
  1485. - It happens when VK_KHR_dedicated_allocation extension is enabled.
  1486. `vkGetBufferMemoryRequirements2KHR` function is used instead, while validation layer seems to be unaware of it.
  1487. - *Mapping an image with layout VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL can result in undefined behavior if this memory is used by the device. Only GENERAL or PREINITIALIZED should be used.*
  1488. - It happens when you map a buffer or image, because the library maps entire
  1489. `VkDeviceMemory` block, where different types of images and buffers may end
  1490. up together, especially on GPUs with unified memory like Intel.
  1491. - *Non-linear image 0xebc91 is aliased with linear buffer 0xeb8e4 which may indicate a bug.*
  1492. - It happens when you use lost allocations, and a new image or buffer is
  1493. created in place of an existing object that became lost.
  1494. - It may happen also when you use [defragmentation](@ref defragmentation).
  1495. \section general_considerations_allocation_algorithm Allocation algorithm
  1496. The library uses following algorithm for allocation, in order:
  1497. -# Try to find free range of memory in existing blocks.
  1498. -# If failed, try to create a new block of `VkDeviceMemory`, with preferred block size.
  1499. -# If failed, try to create such block with size/2, size/4, size/8.
  1500. -# If failed and #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flag was
  1501. specified, try to find space in existing blocks, possilby making some other
  1502. allocations lost.
  1503. -# If failed, try to allocate separate `VkDeviceMemory` for this allocation,
  1504. just like when you use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  1505. -# If failed, choose other memory type that meets the requirements specified in
  1506. VmaAllocationCreateInfo and go to point 1.
  1507. -# If failed, return `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  1508. \section general_considerations_features_not_supported Features not supported
  1509. Features deliberately excluded from the scope of this library:
  1510. - Data transfer. Uploading (streaming) and downloading data of buffers and images
  1511. between CPU and GPU memory and related synchronization is responsibility of the user.
  1512. Defining some "texture" object that would automatically stream its data from a
  1513. staging copy in CPU memory to GPU memory would rather be a feature of another,
  1514. higher-level library implemented on top of VMA.
  1515. - Allocations for imported/exported external memory. They tend to require
  1516. explicit memory type index and dedicated allocation anyway, so they don't
  1517. interact with main features of this library. Such special purpose allocations
  1518. should be made manually, using `vkCreateBuffer()` and `vkAllocateMemory()`.
  1519. - Sub-allocation of parts of one large buffer. Although recommended as a good practice,
  1520. it is the user's responsibility to implement such logic on top of VMA.
  1521. - Recreation of buffers and images. Although the library has functions for
  1522. buffer and image creation (vmaCreateBuffer(), vmaCreateImage()), you need to
  1523. recreate these objects yourself after defragmentation. That's because the big
  1524. structures `VkBufferCreateInfo`, `VkImageCreateInfo` are not stored in
  1525. #VmaAllocation object.
  1526. - Handling CPU memory allocation failures. When dynamically creating small C++
  1527. objects in CPU memory (not Vulkan memory), allocation failures are not checked
  1528. and handled gracefully, because that would complicate code significantly and
  1529. is usually not needed in desktop PC applications anyway.
  1530. Success of an allocation is just checked with an assert.
  1531. - Code free of any compiler warnings. Maintaining the library to compile and
  1532. work correctly on so many different platforms is hard enough. Being free of
  1533. any warnings, on any version of any compiler, is simply not feasible.
  1534. - This is a C++ library with C interface.
  1535. Bindings or ports to any other programming languages are welcomed as external projects and
  1536. are not going to be included into this repository.
  1537. */
  1538. #ifdef __cplusplus
  1539. extern "C" {
  1540. #endif
  1541. /*
  1542. Define this macro to 0/1 to disable/enable support for recording functionality,
  1543. available through VmaAllocatorCreateInfo::pRecordSettings.
  1544. */
  1545. #ifndef VMA_RECORDING_ENABLED
  1546. #define VMA_RECORDING_ENABLED 0
  1547. #endif
  1548. #if !defined(NOMINMAX) && defined(VMA_IMPLEMENTATION)
  1549. #define NOMINMAX // For windows.h
  1550. #endif
  1551. #if defined(__ANDROID__) && defined(VK_NO_PROTOTYPES) && VMA_STATIC_VULKAN_FUNCTIONS
  1552. extern PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr;
  1553. extern PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr;
  1554. extern PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties;
  1555. extern PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties;
  1556. extern PFN_vkAllocateMemory vkAllocateMemory;
  1557. extern PFN_vkFreeMemory vkFreeMemory;
  1558. extern PFN_vkMapMemory vkMapMemory;
  1559. extern PFN_vkUnmapMemory vkUnmapMemory;
  1560. extern PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges;
  1561. extern PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges;
  1562. extern PFN_vkBindBufferMemory vkBindBufferMemory;
  1563. extern PFN_vkBindImageMemory vkBindImageMemory;
  1564. extern PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements;
  1565. extern PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements;
  1566. extern PFN_vkCreateBuffer vkCreateBuffer;
  1567. extern PFN_vkDestroyBuffer vkDestroyBuffer;
  1568. extern PFN_vkCreateImage vkCreateImage;
  1569. extern PFN_vkDestroyImage vkDestroyImage;
  1570. extern PFN_vkCmdCopyBuffer vkCmdCopyBuffer;
  1571. #if VMA_VULKAN_VERSION >= 1001000
  1572. extern PFN_vkGetBufferMemoryRequirements2 vkGetBufferMemoryRequirements2;
  1573. extern PFN_vkGetImageMemoryRequirements2 vkGetImageMemoryRequirements2;
  1574. extern PFN_vkBindBufferMemory2 vkBindBufferMemory2;
  1575. extern PFN_vkBindImageMemory2 vkBindImageMemory2;
  1576. extern PFN_vkGetPhysicalDeviceMemoryProperties2 vkGetPhysicalDeviceMemoryProperties2;
  1577. #endif // #if VMA_VULKAN_VERSION >= 1001000
  1578. #endif // #if defined(__ANDROID__) && VMA_STATIC_VULKAN_FUNCTIONS && VK_NO_PROTOTYPES
  1579. #ifndef VULKAN_H_
  1580. #ifdef USE_VOLK
  1581. #include <volk.h>
  1582. #else
  1583. #include <vulkan/vulkan.h>
  1584. #endif
  1585. #endif
  1586. // Define this macro to declare maximum supported Vulkan version in format AAABBBCCC,
  1587. // where AAA = major, BBB = minor, CCC = patch.
  1588. // If you want to use version > 1.0, it still needs to be enabled via VmaAllocatorCreateInfo::vulkanApiVersion.
  1589. #if !defined(VMA_VULKAN_VERSION)
  1590. #if defined(VK_VERSION_1_2)
  1591. #define VMA_VULKAN_VERSION 1002000
  1592. #elif defined(VK_VERSION_1_1)
  1593. #define VMA_VULKAN_VERSION 1001000
  1594. #else
  1595. #define VMA_VULKAN_VERSION 1000000
  1596. #endif
  1597. #endif
  1598. #if !defined(VMA_DEDICATED_ALLOCATION)
  1599. #if VK_KHR_get_memory_requirements2 && VK_KHR_dedicated_allocation
  1600. #define VMA_DEDICATED_ALLOCATION 1
  1601. #else
  1602. #define VMA_DEDICATED_ALLOCATION 0
  1603. #endif
  1604. #endif
  1605. #if !defined(VMA_BIND_MEMORY2)
  1606. #if VK_KHR_bind_memory2
  1607. #define VMA_BIND_MEMORY2 1
  1608. #else
  1609. #define VMA_BIND_MEMORY2 0
  1610. #endif
  1611. #endif
  1612. #if !defined(VMA_MEMORY_BUDGET)
  1613. #if VK_EXT_memory_budget && (VK_KHR_get_physical_device_properties2 || VMA_VULKAN_VERSION >= 1001000)
  1614. #define VMA_MEMORY_BUDGET 1
  1615. #else
  1616. #define VMA_MEMORY_BUDGET 0
  1617. #endif
  1618. #endif
  1619. // Defined to 1 when VK_KHR_buffer_device_address device extension or equivalent core Vulkan 1.2 feature is defined in its headers.
  1620. #if !defined(VMA_BUFFER_DEVICE_ADDRESS)
  1621. #if VK_KHR_buffer_device_address || VMA_VULKAN_VERSION >= 1002000
  1622. #define VMA_BUFFER_DEVICE_ADDRESS 1
  1623. #else
  1624. #define VMA_BUFFER_DEVICE_ADDRESS 0
  1625. #endif
  1626. #endif
  1627. // Defined to 1 when VK_EXT_memory_priority device extension is defined in Vulkan headers.
  1628. #if !defined(VMA_MEMORY_PRIORITY)
  1629. #if VK_EXT_memory_priority
  1630. #define VMA_MEMORY_PRIORITY 1
  1631. #else
  1632. #define VMA_MEMORY_PRIORITY 0
  1633. #endif
  1634. #endif
  1635. // Defined to 1 when VK_KHR_external_memory device extension is defined in Vulkan headers.
  1636. #if !defined(VMA_EXTERNAL_MEMORY)
  1637. #if VK_KHR_external_memory
  1638. #define VMA_EXTERNAL_MEMORY 1
  1639. #else
  1640. #define VMA_EXTERNAL_MEMORY 0
  1641. #endif
  1642. #endif
  1643. // Define these macros to decorate all public functions with additional code,
  1644. // before and after returned type, appropriately. This may be useful for
  1645. // exporting the functions when compiling VMA as a separate library. Example:
  1646. // #define VMA_CALL_PRE __declspec(dllexport)
  1647. // #define VMA_CALL_POST __cdecl
  1648. #ifndef VMA_CALL_PRE
  1649. #define VMA_CALL_PRE
  1650. #endif
  1651. #ifndef VMA_CALL_POST
  1652. #define VMA_CALL_POST
  1653. #endif
  1654. // Define this macro to decorate pointers with an attribute specifying the
  1655. // length of the array they point to if they are not null.
  1656. //
  1657. // The length may be one of
  1658. // - The name of another parameter in the argument list where the pointer is declared
  1659. // - The name of another member in the struct where the pointer is declared
  1660. // - The name of a member of a struct type, meaning the value of that member in
  1661. // the context of the call. For example
  1662. // VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryHeapCount"),
  1663. // this means the number of memory heaps available in the device associated
  1664. // with the VmaAllocator being dealt with.
  1665. #ifndef VMA_LEN_IF_NOT_NULL
  1666. #define VMA_LEN_IF_NOT_NULL(len)
  1667. #endif
  1668. // The VMA_NULLABLE macro is defined to be _Nullable when compiling with Clang.
  1669. // see: https://clang.llvm.org/docs/AttributeReference.html#nullable
  1670. #ifndef VMA_NULLABLE
  1671. #ifdef __clang__
  1672. #define VMA_NULLABLE _Nullable
  1673. #else
  1674. #define VMA_NULLABLE
  1675. #endif
  1676. #endif
  1677. // The VMA_NOT_NULL macro is defined to be _Nonnull when compiling with Clang.
  1678. // see: https://clang.llvm.org/docs/AttributeReference.html#nonnull
  1679. #ifndef VMA_NOT_NULL
  1680. #ifdef __clang__
  1681. #define VMA_NOT_NULL _Nonnull
  1682. #else
  1683. #define VMA_NOT_NULL
  1684. #endif
  1685. #endif
  1686. // If non-dispatchable handles are represented as pointers then we can give
  1687. // then nullability annotations
  1688. #ifndef VMA_NOT_NULL_NON_DISPATCHABLE
  1689. #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
  1690. #define VMA_NOT_NULL_NON_DISPATCHABLE VMA_NOT_NULL
  1691. #else
  1692. #define VMA_NOT_NULL_NON_DISPATCHABLE
  1693. #endif
  1694. #endif
  1695. #ifndef VMA_NULLABLE_NON_DISPATCHABLE
  1696. #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
  1697. #define VMA_NULLABLE_NON_DISPATCHABLE VMA_NULLABLE
  1698. #else
  1699. #define VMA_NULLABLE_NON_DISPATCHABLE
  1700. #endif
  1701. #endif
  1702. /** \struct VmaAllocator
  1703. \brief Represents main object of this library initialized.
  1704. Fill structure #VmaAllocatorCreateInfo and call function vmaCreateAllocator() to create it.
  1705. Call function vmaDestroyAllocator() to destroy it.
  1706. It is recommended to create just one object of this type per `VkDevice` object,
  1707. right after Vulkan is initialized and keep it alive until before Vulkan device is destroyed.
  1708. */
  1709. VK_DEFINE_HANDLE(VmaAllocator)
  1710. /// Callback function called after successful vkAllocateMemory.
  1711. typedef void (VKAPI_PTR *PFN_vmaAllocateDeviceMemoryFunction)(
  1712. VmaAllocator VMA_NOT_NULL allocator,
  1713. uint32_t memoryType,
  1714. VkDeviceMemory VMA_NOT_NULL_NON_DISPATCHABLE memory,
  1715. VkDeviceSize size,
  1716. void* VMA_NULLABLE pUserData);
  1717. /// Callback function called before vkFreeMemory.
  1718. typedef void (VKAPI_PTR *PFN_vmaFreeDeviceMemoryFunction)(
  1719. VmaAllocator VMA_NOT_NULL allocator,
  1720. uint32_t memoryType,
  1721. VkDeviceMemory VMA_NOT_NULL_NON_DISPATCHABLE memory,
  1722. VkDeviceSize size,
  1723. void* VMA_NULLABLE pUserData);
  1724. /** \brief Set of callbacks that the library will call for `vkAllocateMemory` and `vkFreeMemory`.
  1725. Provided for informative purpose, e.g. to gather statistics about number of
  1726. allocations or total amount of memory allocated in Vulkan.
  1727. Used in VmaAllocatorCreateInfo::pDeviceMemoryCallbacks.
  1728. */
  1729. typedef struct VmaDeviceMemoryCallbacks {
  1730. /// Optional, can be null.
  1731. PFN_vmaAllocateDeviceMemoryFunction VMA_NULLABLE pfnAllocate;
  1732. /// Optional, can be null.
  1733. PFN_vmaFreeDeviceMemoryFunction VMA_NULLABLE pfnFree;
  1734. /// Optional, can be null.
  1735. void* VMA_NULLABLE pUserData;
  1736. } VmaDeviceMemoryCallbacks;
  1737. /// Flags for created #VmaAllocator.
  1738. typedef enum VmaAllocatorCreateFlagBits {
  1739. /** \brief Allocator and all objects created from it will not be synchronized internally, so you must guarantee they are used from only one thread at a time or synchronized externally by you.
  1740. Using this flag may increase performance because internal mutexes are not used.
  1741. */
  1742. VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT = 0x00000001,
  1743. /** \brief Enables usage of VK_KHR_dedicated_allocation extension.
  1744. The flag works only if VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_0`.
  1745. When it's `VK_API_VERSION_1_1`, the flag is ignored because the extension has been promoted to Vulkan 1.1.
  1746. Using this extension will automatically allocate dedicated blocks of memory for
  1747. some buffers and images instead of suballocating place for them out of bigger
  1748. memory blocks (as if you explicitly used #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT
  1749. flag) when it is recommended by the driver. It may improve performance on some
  1750. GPUs.
  1751. You may set this flag only if you found out that following device extensions are
  1752. supported, you enabled them while creating Vulkan device passed as
  1753. VmaAllocatorCreateInfo::device, and you want them to be used internally by this
  1754. library:
  1755. - VK_KHR_get_memory_requirements2 (device extension)
  1756. - VK_KHR_dedicated_allocation (device extension)
  1757. When this flag is set, you can experience following warnings reported by Vulkan
  1758. validation layer. You can ignore them.
  1759. > vkBindBufferMemory(): Binding memory to buffer 0x2d but vkGetBufferMemoryRequirements() has not been called on that buffer.
  1760. */
  1761. VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT = 0x00000002,
  1762. /**
  1763. Enables usage of VK_KHR_bind_memory2 extension.
  1764. The flag works only if VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_0`.
  1765. When it's `VK_API_VERSION_1_1`, the flag is ignored because the extension has been promoted to Vulkan 1.1.
  1766. You may set this flag only if you found out that this device extension is supported,
  1767. you enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device,
  1768. and you want it to be used internally by this library.
  1769. The extension provides functions `vkBindBufferMemory2KHR` and `vkBindImageMemory2KHR`,
  1770. which allow to pass a chain of `pNext` structures while binding.
  1771. This flag is required if you use `pNext` parameter in vmaBindBufferMemory2() or vmaBindImageMemory2().
  1772. */
  1773. VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT = 0x00000004,
  1774. /**
  1775. Enables usage of VK_EXT_memory_budget extension.
  1776. You may set this flag only if you found out that this device extension is supported,
  1777. you enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device,
  1778. and you want it to be used internally by this library, along with another instance extension
  1779. VK_KHR_get_physical_device_properties2, which is required by it (or Vulkan 1.1, where this extension is promoted).
  1780. The extension provides query for current memory usage and budget, which will probably
  1781. be more accurate than an estimation used by the library otherwise.
  1782. */
  1783. VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT = 0x00000008,
  1784. /**
  1785. Enables usage of VK_AMD_device_coherent_memory extension.
  1786. You may set this flag only if you:
  1787. - found out that this device extension is supported and enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device,
  1788. - checked that `VkPhysicalDeviceCoherentMemoryFeaturesAMD::deviceCoherentMemory` is true and set it while creating the Vulkan device,
  1789. - want it to be used internally by this library.
  1790. The extension and accompanying device feature provide access to memory types with
  1791. `VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD` and `VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` flags.
  1792. They are useful mostly for writing breadcrumb markers - a common method for debugging GPU crash/hang/TDR.
  1793. When the extension is not enabled, such memory types are still enumerated, but their usage is illegal.
  1794. To protect from this error, if you don't create the allocator with this flag, it will refuse to allocate any memory or create a custom pool in such memory type,
  1795. returning `VK_ERROR_FEATURE_NOT_PRESENT`.
  1796. */
  1797. VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT = 0x00000010,
  1798. /**
  1799. Enables usage of "buffer device address" feature, which allows you to use function
  1800. `vkGetBufferDeviceAddress*` to get raw GPU pointer to a buffer and pass it for usage inside a shader.
  1801. You may set this flag only if you:
  1802. 1. (For Vulkan version < 1.2) Found as available and enabled device extension
  1803. VK_KHR_buffer_device_address.
  1804. This extension is promoted to core Vulkan 1.2.
  1805. 2. Found as available and enabled device feature `VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress`.
  1806. When this flag is set, you can create buffers with `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT` using VMA.
  1807. The library automatically adds `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT` to
  1808. allocated memory blocks wherever it might be needed.
  1809. For more information, see documentation chapter \ref enabling_buffer_device_address.
  1810. */
  1811. VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT = 0x00000020,
  1812. /**
  1813. Enables usage of VK_EXT_memory_priority extension in the library.
  1814. You may set this flag only if you found available and enabled this device extension,
  1815. along with `VkPhysicalDeviceMemoryPriorityFeaturesEXT::memoryPriority == VK_TRUE`,
  1816. while creating Vulkan device passed as VmaAllocatorCreateInfo::device.
  1817. When this flag is used, VmaAllocationCreateInfo::priority and VmaPoolCreateInfo::priority
  1818. are used to set priorities of allocated Vulkan memory. Without it, these variables are ignored.
  1819. A priority must be a floating-point value between 0 and 1, indicating the priority of the allocation relative to other memory allocations.
  1820. Larger values are higher priority. The granularity of the priorities is implementation-dependent.
  1821. It is automatically passed to every call to `vkAllocateMemory` done by the library using structure `VkMemoryPriorityAllocateInfoEXT`.
  1822. The value to be used for default priority is 0.5.
  1823. For more details, see the documentation of the VK_EXT_memory_priority extension.
  1824. */
  1825. VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT = 0x00000040,
  1826. VMA_ALLOCATOR_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  1827. } VmaAllocatorCreateFlagBits;
  1828. typedef VkFlags VmaAllocatorCreateFlags;
  1829. /** \brief Pointers to some Vulkan functions - a subset used by the library.
  1830. Used in VmaAllocatorCreateInfo::pVulkanFunctions.
  1831. */
  1832. typedef struct VmaVulkanFunctions {
  1833. PFN_vkGetPhysicalDeviceProperties VMA_NULLABLE vkGetPhysicalDeviceProperties;
  1834. PFN_vkGetPhysicalDeviceMemoryProperties VMA_NULLABLE vkGetPhysicalDeviceMemoryProperties;
  1835. PFN_vkAllocateMemory VMA_NULLABLE vkAllocateMemory;
  1836. PFN_vkFreeMemory VMA_NULLABLE vkFreeMemory;
  1837. PFN_vkMapMemory VMA_NULLABLE vkMapMemory;
  1838. PFN_vkUnmapMemory VMA_NULLABLE vkUnmapMemory;
  1839. PFN_vkFlushMappedMemoryRanges VMA_NULLABLE vkFlushMappedMemoryRanges;
  1840. PFN_vkInvalidateMappedMemoryRanges VMA_NULLABLE vkInvalidateMappedMemoryRanges;
  1841. PFN_vkBindBufferMemory VMA_NULLABLE vkBindBufferMemory;
  1842. PFN_vkBindImageMemory VMA_NULLABLE vkBindImageMemory;
  1843. PFN_vkGetBufferMemoryRequirements VMA_NULLABLE vkGetBufferMemoryRequirements;
  1844. PFN_vkGetImageMemoryRequirements VMA_NULLABLE vkGetImageMemoryRequirements;
  1845. PFN_vkCreateBuffer VMA_NULLABLE vkCreateBuffer;
  1846. PFN_vkDestroyBuffer VMA_NULLABLE vkDestroyBuffer;
  1847. PFN_vkCreateImage VMA_NULLABLE vkCreateImage;
  1848. PFN_vkDestroyImage VMA_NULLABLE vkDestroyImage;
  1849. PFN_vkCmdCopyBuffer VMA_NULLABLE vkCmdCopyBuffer;
  1850. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  1851. PFN_vkGetBufferMemoryRequirements2KHR VMA_NULLABLE vkGetBufferMemoryRequirements2KHR;
  1852. PFN_vkGetImageMemoryRequirements2KHR VMA_NULLABLE vkGetImageMemoryRequirements2KHR;
  1853. #endif
  1854. #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000
  1855. PFN_vkBindBufferMemory2KHR VMA_NULLABLE vkBindBufferMemory2KHR;
  1856. PFN_vkBindImageMemory2KHR VMA_NULLABLE vkBindImageMemory2KHR;
  1857. #endif
  1858. #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000
  1859. PFN_vkGetPhysicalDeviceMemoryProperties2KHR VMA_NULLABLE vkGetPhysicalDeviceMemoryProperties2KHR;
  1860. #endif
  1861. } VmaVulkanFunctions;
  1862. /// Flags to be used in VmaRecordSettings::flags.
  1863. typedef enum VmaRecordFlagBits {
  1864. /** \brief Enables flush after recording every function call.
  1865. Enable it if you expect your application to crash, which may leave recording file truncated.
  1866. It may degrade performance though.
  1867. */
  1868. VMA_RECORD_FLUSH_AFTER_CALL_BIT = 0x00000001,
  1869. VMA_RECORD_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  1870. } VmaRecordFlagBits;
  1871. typedef VkFlags VmaRecordFlags;
  1872. /// Parameters for recording calls to VMA functions. To be used in VmaAllocatorCreateInfo::pRecordSettings.
  1873. typedef struct VmaRecordSettings
  1874. {
  1875. /// Flags for recording. Use #VmaRecordFlagBits enum.
  1876. VmaRecordFlags flags;
  1877. /** \brief Path to the file that should be written by the recording.
  1878. Suggested extension: "csv".
  1879. If the file already exists, it will be overwritten.
  1880. It will be opened for the whole time #VmaAllocator object is alive.
  1881. If opening this file fails, creation of the whole allocator object fails.
  1882. */
  1883. const char* VMA_NOT_NULL pFilePath;
  1884. } VmaRecordSettings;
  1885. /// Description of a Allocator to be created.
  1886. typedef struct VmaAllocatorCreateInfo
  1887. {
  1888. /// Flags for created allocator. Use #VmaAllocatorCreateFlagBits enum.
  1889. VmaAllocatorCreateFlags flags;
  1890. /// Vulkan physical device.
  1891. /** It must be valid throughout whole lifetime of created allocator. */
  1892. VkPhysicalDevice VMA_NOT_NULL physicalDevice;
  1893. /// Vulkan device.
  1894. /** It must be valid throughout whole lifetime of created allocator. */
  1895. VkDevice VMA_NOT_NULL device;
  1896. /// Preferred size of a single `VkDeviceMemory` block to be allocated from large heaps > 1 GiB. Optional.
  1897. /** Set to 0 to use default, which is currently 256 MiB. */
  1898. VkDeviceSize preferredLargeHeapBlockSize;
  1899. /// Custom CPU memory allocation callbacks. Optional.
  1900. /** Optional, can be null. When specified, will also be used for all CPU-side memory allocations. */
  1901. const VkAllocationCallbacks* VMA_NULLABLE pAllocationCallbacks;
  1902. /// Informative callbacks for `vkAllocateMemory`, `vkFreeMemory`. Optional.
  1903. /** Optional, can be null. */
  1904. const VmaDeviceMemoryCallbacks* VMA_NULLABLE pDeviceMemoryCallbacks;
  1905. /** \brief Maximum number of additional frames that are in use at the same time as current frame.
  1906. This value is used only when you make allocations with
  1907. VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag. Such allocation cannot become
  1908. lost if allocation.lastUseFrameIndex >= allocator.currentFrameIndex - frameInUseCount.
  1909. For example, if you double-buffer your command buffers, so resources used for
  1910. rendering in previous frame may still be in use by the GPU at the moment you
  1911. allocate resources needed for the current frame, set this value to 1.
  1912. If you want to allow any allocations other than used in the current frame to
  1913. become lost, set this value to 0.
  1914. */
  1915. uint32_t frameInUseCount;
  1916. /** \brief Either null or a pointer to an array of limits on maximum number of bytes that can be allocated out of particular Vulkan memory heap.
  1917. If not NULL, it must be a pointer to an array of
  1918. `VkPhysicalDeviceMemoryProperties::memoryHeapCount` elements, defining limit on
  1919. maximum number of bytes that can be allocated out of particular Vulkan memory
  1920. heap.
  1921. Any of the elements may be equal to `VK_WHOLE_SIZE`, which means no limit on that
  1922. heap. This is also the default in case of `pHeapSizeLimit` = NULL.
  1923. If there is a limit defined for a heap:
  1924. - If user tries to allocate more memory from that heap using this allocator,
  1925. the allocation fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  1926. - If the limit is smaller than heap size reported in `VkMemoryHeap::size`, the
  1927. value of this limit will be reported instead when using vmaGetMemoryProperties().
  1928. Warning! Using this feature may not be equivalent to installing a GPU with
  1929. smaller amount of memory, because graphics driver doesn't necessary fail new
  1930. allocations with `VK_ERROR_OUT_OF_DEVICE_MEMORY` result when memory capacity is
  1931. exceeded. It may return success and just silently migrate some device memory
  1932. blocks to system RAM. This driver behavior can also be controlled using
  1933. VK_AMD_memory_overallocation_behavior extension.
  1934. */
  1935. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryHeapCount") pHeapSizeLimit;
  1936. /** \brief Pointers to Vulkan functions. Can be null.
  1937. For details see [Pointers to Vulkan functions](@ref config_Vulkan_functions).
  1938. */
  1939. const VmaVulkanFunctions* VMA_NULLABLE pVulkanFunctions;
  1940. /** \brief Parameters for recording of VMA calls. Can be null.
  1941. If not null, it enables recording of calls to VMA functions to a file.
  1942. If support for recording is not enabled using `VMA_RECORDING_ENABLED` macro,
  1943. creation of the allocator object fails with `VK_ERROR_FEATURE_NOT_PRESENT`.
  1944. */
  1945. const VmaRecordSettings* VMA_NULLABLE pRecordSettings;
  1946. /** \brief Handle to Vulkan instance object.
  1947. Starting from version 3.0.0 this member is no longer optional, it must be set!
  1948. */
  1949. VkInstance VMA_NOT_NULL instance;
  1950. /** \brief Optional. The highest version of Vulkan that the application is designed to use.
  1951. It must be a value in the format as created by macro `VK_MAKE_VERSION` or a constant like: `VK_API_VERSION_1_1`, `VK_API_VERSION_1_0`.
  1952. The patch version number specified is ignored. Only the major and minor versions are considered.
  1953. It must be less or equal (preferably equal) to value as passed to `vkCreateInstance` as `VkApplicationInfo::apiVersion`.
  1954. Only versions 1.0, 1.1, 1.2 are supported by the current implementation.
  1955. Leaving it initialized to zero is equivalent to `VK_API_VERSION_1_0`.
  1956. */
  1957. uint32_t vulkanApiVersion;
  1958. #if VMA_EXTERNAL_MEMORY
  1959. /** \brief Either null or a pointer to an array of external memory handle types for each Vulkan memory type.
  1960. If not NULL, it must be a pointer to an array of `VkPhysicalDeviceMemoryProperties::memoryTypeCount`
  1961. elements, defining external memory handle types of particular Vulkan memory type,
  1962. to be passed using `VkExportMemoryAllocateInfoKHR`.
  1963. Any of the elements may be equal to 0, which means not to use `VkExportMemoryAllocateInfoKHR` on this memory type.
  1964. This is also the default in case of `pTypeExternalMemoryHandleTypes` = NULL.
  1965. */
  1966. const VkExternalMemoryHandleTypeFlagsKHR* VMA_NULLABLE VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryTypeCount") pTypeExternalMemoryHandleTypes;
  1967. #endif // #if VMA_EXTERNAL_MEMORY
  1968. } VmaAllocatorCreateInfo;
  1969. /// Creates Allocator object.
  1970. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAllocator(
  1971. const VmaAllocatorCreateInfo* VMA_NOT_NULL pCreateInfo,
  1972. VmaAllocator VMA_NULLABLE * VMA_NOT_NULL pAllocator);
  1973. /// Destroys allocator object.
  1974. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyAllocator(
  1975. VmaAllocator VMA_NULLABLE allocator);
  1976. /** \brief Information about existing #VmaAllocator object.
  1977. */
  1978. typedef struct VmaAllocatorInfo
  1979. {
  1980. /** \brief Handle to Vulkan instance object.
  1981. This is the same value as has been passed through VmaAllocatorCreateInfo::instance.
  1982. */
  1983. VkInstance VMA_NOT_NULL instance;
  1984. /** \brief Handle to Vulkan physical device object.
  1985. This is the same value as has been passed through VmaAllocatorCreateInfo::physicalDevice.
  1986. */
  1987. VkPhysicalDevice VMA_NOT_NULL physicalDevice;
  1988. /** \brief Handle to Vulkan device object.
  1989. This is the same value as has been passed through VmaAllocatorCreateInfo::device.
  1990. */
  1991. VkDevice VMA_NOT_NULL device;
  1992. } VmaAllocatorInfo;
  1993. /** \brief Returns information about existing #VmaAllocator object - handle to Vulkan device etc.
  1994. It might be useful if you want to keep just the #VmaAllocator handle and fetch other required handles to
  1995. `VkPhysicalDevice`, `VkDevice` etc. every time using this function.
  1996. */
  1997. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocatorInfo(VmaAllocator VMA_NOT_NULL allocator, VmaAllocatorInfo* VMA_NOT_NULL pAllocatorInfo);
  1998. /**
  1999. PhysicalDeviceProperties are fetched from physicalDevice by the allocator.
  2000. You can access it here, without fetching it again on your own.
  2001. */
  2002. VMA_CALL_PRE void VMA_CALL_POST vmaGetPhysicalDeviceProperties(
  2003. VmaAllocator VMA_NOT_NULL allocator,
  2004. const VkPhysicalDeviceProperties* VMA_NULLABLE * VMA_NOT_NULL ppPhysicalDeviceProperties);
  2005. /**
  2006. PhysicalDeviceMemoryProperties are fetched from physicalDevice by the allocator.
  2007. You can access it here, without fetching it again on your own.
  2008. */
  2009. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryProperties(
  2010. VmaAllocator VMA_NOT_NULL allocator,
  2011. const VkPhysicalDeviceMemoryProperties* VMA_NULLABLE * VMA_NOT_NULL ppPhysicalDeviceMemoryProperties);
  2012. /**
  2013. \brief Given Memory Type Index, returns Property Flags of this memory type.
  2014. This is just a convenience function. Same information can be obtained using
  2015. vmaGetMemoryProperties().
  2016. */
  2017. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties(
  2018. VmaAllocator VMA_NOT_NULL allocator,
  2019. uint32_t memoryTypeIndex,
  2020. VkMemoryPropertyFlags* VMA_NOT_NULL pFlags);
  2021. /** \brief Sets index of the current frame.
  2022. This function must be used if you make allocations with
  2023. #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT and
  2024. #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flags to inform the allocator
  2025. when a new frame begins. Allocations queried using vmaGetAllocationInfo() cannot
  2026. become lost in the current frame.
  2027. */
  2028. VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex(
  2029. VmaAllocator VMA_NOT_NULL allocator,
  2030. uint32_t frameIndex);
  2031. /** \brief Calculated statistics of memory usage in entire allocator.
  2032. */
  2033. typedef struct VmaStatInfo
  2034. {
  2035. /// Number of `VkDeviceMemory` Vulkan memory blocks allocated.
  2036. uint32_t blockCount;
  2037. /// Number of #VmaAllocation allocation objects allocated.
  2038. uint32_t allocationCount;
  2039. /// Number of free ranges of memory between allocations.
  2040. uint32_t unusedRangeCount;
  2041. /// Total number of bytes occupied by all allocations.
  2042. VkDeviceSize usedBytes;
  2043. /// Total number of bytes occupied by unused ranges.
  2044. VkDeviceSize unusedBytes;
  2045. VkDeviceSize allocationSizeMin, allocationSizeAvg, allocationSizeMax;
  2046. VkDeviceSize unusedRangeSizeMin, unusedRangeSizeAvg, unusedRangeSizeMax;
  2047. } VmaStatInfo;
  2048. /// General statistics from current state of Allocator.
  2049. typedef struct VmaStats
  2050. {
  2051. VmaStatInfo memoryType[VK_MAX_MEMORY_TYPES];
  2052. VmaStatInfo memoryHeap[VK_MAX_MEMORY_HEAPS];
  2053. VmaStatInfo total;
  2054. } VmaStats;
  2055. /** \brief Retrieves statistics from current state of the Allocator.
  2056. This function is called "calculate" not "get" because it has to traverse all
  2057. internal data structures, so it may be quite slow. For faster but more brief statistics
  2058. suitable to be called every frame or every allocation, use vmaGetBudget().
  2059. Note that when using allocator from multiple threads, returned information may immediately
  2060. become outdated.
  2061. */
  2062. VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStats(
  2063. VmaAllocator VMA_NOT_NULL allocator,
  2064. VmaStats* VMA_NOT_NULL pStats);
  2065. /** \brief Statistics of current memory usage and available budget, in bytes, for specific memory heap.
  2066. */
  2067. typedef struct VmaBudget
  2068. {
  2069. /** \brief Sum size of all `VkDeviceMemory` blocks allocated from particular heap, in bytes.
  2070. */
  2071. VkDeviceSize blockBytes;
  2072. /** \brief Sum size of all allocations created in particular heap, in bytes.
  2073. Usually less or equal than `blockBytes`.
  2074. Difference `blockBytes - allocationBytes` is the amount of memory allocated but unused -
  2075. available for new allocations or wasted due to fragmentation.
  2076. It might be greater than `blockBytes` if there are some allocations in lost state, as they account
  2077. to this value as well.
  2078. */
  2079. VkDeviceSize allocationBytes;
  2080. /** \brief Estimated current memory usage of the program, in bytes.
  2081. Fetched from system using `VK_EXT_memory_budget` extension if enabled.
  2082. It might be different than `blockBytes` (usually higher) due to additional implicit objects
  2083. also occupying the memory, like swapchain, pipelines, descriptor heaps, command buffers, or
  2084. `VkDeviceMemory` blocks allocated outside of this library, if any.
  2085. */
  2086. VkDeviceSize usage;
  2087. /** \brief Estimated amount of memory available to the program, in bytes.
  2088. Fetched from system using `VK_EXT_memory_budget` extension if enabled.
  2089. It might be different (most probably smaller) than `VkMemoryHeap::size[heapIndex]` due to factors
  2090. external to the program, like other programs also consuming system resources.
  2091. Difference `budget - usage` is the amount of additional memory that can probably
  2092. be allocated without problems. Exceeding the budget may result in various problems.
  2093. */
  2094. VkDeviceSize budget;
  2095. } VmaBudget;
  2096. /** \brief Retrieves information about current memory budget for all memory heaps.
  2097. \param[out] pBudget Must point to array with number of elements at least equal to number of memory heaps in physical device used.
  2098. This function is called "get" not "calculate" because it is very fast, suitable to be called
  2099. every frame or every allocation. For more detailed statistics use vmaCalculateStats().
  2100. Note that when using allocator from multiple threads, returned information may immediately
  2101. become outdated.
  2102. */
  2103. VMA_CALL_PRE void VMA_CALL_POST vmaGetBudget(
  2104. VmaAllocator VMA_NOT_NULL allocator,
  2105. VmaBudget* VMA_NOT_NULL pBudget);
  2106. #ifndef VMA_STATS_STRING_ENABLED
  2107. #define VMA_STATS_STRING_ENABLED 1
  2108. #endif
  2109. #if VMA_STATS_STRING_ENABLED
  2110. /// Builds and returns statistics as string in JSON format.
  2111. /** @param[out] ppStatsString Must be freed using vmaFreeStatsString() function.
  2112. */
  2113. VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString(
  2114. VmaAllocator VMA_NOT_NULL allocator,
  2115. char* VMA_NULLABLE * VMA_NOT_NULL ppStatsString,
  2116. VkBool32 detailedMap);
  2117. VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString(
  2118. VmaAllocator VMA_NOT_NULL allocator,
  2119. char* VMA_NULLABLE pStatsString);
  2120. #endif // #if VMA_STATS_STRING_ENABLED
  2121. /** \struct VmaPool
  2122. \brief Represents custom memory pool
  2123. Fill structure VmaPoolCreateInfo and call function vmaCreatePool() to create it.
  2124. Call function vmaDestroyPool() to destroy it.
  2125. For more information see [Custom memory pools](@ref choosing_memory_type_custom_memory_pools).
  2126. */
  2127. VK_DEFINE_HANDLE(VmaPool)
  2128. typedef enum VmaMemoryUsage
  2129. {
  2130. /** No intended memory usage specified.
  2131. Use other members of VmaAllocationCreateInfo to specify your requirements.
  2132. */
  2133. VMA_MEMORY_USAGE_UNKNOWN = 0,
  2134. /** Memory will be used on device only, so fast access from the device is preferred.
  2135. It usually means device-local GPU (video) memory.
  2136. No need to be mappable on host.
  2137. It is roughly equivalent of `D3D12_HEAP_TYPE_DEFAULT`.
  2138. Usage:
  2139. - Resources written and read by device, e.g. images used as attachments.
  2140. - Resources transferred from host once (immutable) or infrequently and read by
  2141. device multiple times, e.g. textures to be sampled, vertex buffers, uniform
  2142. (constant) buffers, and majority of other types of resources used on GPU.
  2143. Allocation may still end up in `HOST_VISIBLE` memory on some implementations.
  2144. In such case, you are free to map it.
  2145. You can use #VMA_ALLOCATION_CREATE_MAPPED_BIT with this usage type.
  2146. */
  2147. VMA_MEMORY_USAGE_GPU_ONLY = 1,
  2148. /** Memory will be mappable on host.
  2149. It usually means CPU (system) memory.
  2150. Guarantees to be `HOST_VISIBLE` and `HOST_COHERENT`.
  2151. CPU access is typically uncached. Writes may be write-combined.
  2152. Resources created in this pool may still be accessible to the device, but access to them can be slow.
  2153. It is roughly equivalent of `D3D12_HEAP_TYPE_UPLOAD`.
  2154. Usage: Staging copy of resources used as transfer source.
  2155. */
  2156. VMA_MEMORY_USAGE_CPU_ONLY = 2,
  2157. /**
  2158. Memory that is both mappable on host (guarantees to be `HOST_VISIBLE`) and preferably fast to access by GPU.
  2159. CPU access is typically uncached. Writes may be write-combined.
  2160. Usage: Resources written frequently by host (dynamic), read by device. E.g. textures (with LINEAR layout), vertex buffers, uniform buffers updated every frame or every draw call.
  2161. */
  2162. VMA_MEMORY_USAGE_CPU_TO_GPU = 3,
  2163. /** Memory mappable on host (guarantees to be `HOST_VISIBLE`) and cached.
  2164. It is roughly equivalent of `D3D12_HEAP_TYPE_READBACK`.
  2165. Usage:
  2166. - Resources written by device, read by host - results of some computations, e.g. screen capture, average scene luminance for HDR tone mapping.
  2167. - Any resources read or accessed randomly on host, e.g. CPU-side copy of vertex buffer used as source of transfer, but also used for collision detection.
  2168. */
  2169. VMA_MEMORY_USAGE_GPU_TO_CPU = 4,
  2170. /** CPU memory - memory that is preferably not `DEVICE_LOCAL`, but also not guaranteed to be `HOST_VISIBLE`.
  2171. Usage: Staging copy of resources moved from GPU memory to CPU memory as part
  2172. of custom paging/residency mechanism, to be moved back to GPU memory when needed.
  2173. */
  2174. VMA_MEMORY_USAGE_CPU_COPY = 5,
  2175. /** Lazily allocated GPU memory having `VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT`.
  2176. Exists mostly on mobile platforms. Using it on desktop PC or other GPUs with no such memory type present will fail the allocation.
  2177. Usage: Memory for transient attachment images (color attachments, depth attachments etc.), created with `VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT`.
  2178. Allocations with this usage are always created as dedicated - it implies #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  2179. */
  2180. VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED = 6,
  2181. VMA_MEMORY_USAGE_MAX_ENUM = 0x7FFFFFFF
  2182. } VmaMemoryUsage;
  2183. /// Flags to be passed as VmaAllocationCreateInfo::flags.
  2184. typedef enum VmaAllocationCreateFlagBits {
  2185. /** \brief Set this flag if the allocation should have its own memory block.
  2186. Use it for special, big resources, like fullscreen images used as attachments.
  2187. You should not use this flag if VmaAllocationCreateInfo::pool is not null.
  2188. */
  2189. VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT = 0x00000001,
  2190. /** \brief Set this flag to only try to allocate from existing `VkDeviceMemory` blocks and never create new such block.
  2191. If new allocation cannot be placed in any of the existing blocks, allocation
  2192. fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY` error.
  2193. You should not use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT and
  2194. #VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT at the same time. It makes no sense.
  2195. If VmaAllocationCreateInfo::pool is not null, this flag is implied and ignored. */
  2196. VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT = 0x00000002,
  2197. /** \brief Set this flag to use a memory that will be persistently mapped and retrieve pointer to it.
  2198. Pointer to mapped memory will be returned through VmaAllocationInfo::pMappedData.
  2199. It is valid to use this flag for allocation made from memory type that is not
  2200. `HOST_VISIBLE`. This flag is then ignored and memory is not mapped. This is
  2201. useful if you need an allocation that is efficient to use on GPU
  2202. (`DEVICE_LOCAL`) and still want to map it directly if possible on platforms that
  2203. support it (e.g. Intel GPU).
  2204. You should not use this flag together with #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT.
  2205. */
  2206. VMA_ALLOCATION_CREATE_MAPPED_BIT = 0x00000004,
  2207. /** Allocation created with this flag can become lost as a result of another
  2208. allocation with #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flag, so you
  2209. must check it before use.
  2210. To check if allocation is not lost, call vmaGetAllocationInfo() and check if
  2211. VmaAllocationInfo::deviceMemory is not `VK_NULL_HANDLE`.
  2212. For details about supporting lost allocations, see Lost Allocations
  2213. chapter of User Guide on Main Page.
  2214. You should not use this flag together with #VMA_ALLOCATION_CREATE_MAPPED_BIT.
  2215. */
  2216. VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT = 0x00000008,
  2217. /** While creating allocation using this flag, other allocations that were
  2218. created with flag #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT can become lost.
  2219. For details about supporting lost allocations, see Lost Allocations
  2220. chapter of User Guide on Main Page.
  2221. */
  2222. VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT = 0x00000010,
  2223. /** Set this flag to treat VmaAllocationCreateInfo::pUserData as pointer to a
  2224. null-terminated string. Instead of copying pointer value, a local copy of the
  2225. string is made and stored in allocation's `pUserData`. The string is automatically
  2226. freed together with the allocation. It is also used in vmaBuildStatsString().
  2227. */
  2228. VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT = 0x00000020,
  2229. /** Allocation will be created from upper stack in a double stack pool.
  2230. This flag is only allowed for custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT flag.
  2231. */
  2232. VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT = 0x00000040,
  2233. /** Create both buffer/image and allocation, but don't bind them together.
  2234. It is useful when you want to bind yourself to do some more advanced binding, e.g. using some extensions.
  2235. The flag is meaningful only with functions that bind by default: vmaCreateBuffer(), vmaCreateImage().
  2236. Otherwise it is ignored.
  2237. */
  2238. VMA_ALLOCATION_CREATE_DONT_BIND_BIT = 0x00000080,
  2239. /** Create allocation only if additional device memory required for it, if any, won't exceed
  2240. memory budget. Otherwise return `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  2241. */
  2242. VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT = 0x00000100,
  2243. /** Allocation strategy that chooses smallest possible free range for the
  2244. allocation.
  2245. */
  2246. VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT = 0x00010000,
  2247. /** Allocation strategy that chooses biggest possible free range for the
  2248. allocation.
  2249. */
  2250. VMA_ALLOCATION_CREATE_STRATEGY_WORST_FIT_BIT = 0x00020000,
  2251. /** Allocation strategy that chooses first suitable free range for the
  2252. allocation.
  2253. "First" doesn't necessarily means the one with smallest offset in memory,
  2254. but rather the one that is easiest and fastest to find.
  2255. */
  2256. VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT = 0x00040000,
  2257. /** Allocation strategy that tries to minimize memory usage.
  2258. */
  2259. VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT = VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT,
  2260. /** Allocation strategy that tries to minimize allocation time.
  2261. */
  2262. VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT = VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT,
  2263. /** Allocation strategy that tries to minimize memory fragmentation.
  2264. */
  2265. VMA_ALLOCATION_CREATE_STRATEGY_MIN_FRAGMENTATION_BIT = VMA_ALLOCATION_CREATE_STRATEGY_WORST_FIT_BIT,
  2266. /** A bit mask to extract only `STRATEGY` bits from entire set of flags.
  2267. */
  2268. VMA_ALLOCATION_CREATE_STRATEGY_MASK =
  2269. VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT |
  2270. VMA_ALLOCATION_CREATE_STRATEGY_WORST_FIT_BIT |
  2271. VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT,
  2272. VMA_ALLOCATION_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  2273. } VmaAllocationCreateFlagBits;
  2274. typedef VkFlags VmaAllocationCreateFlags;
  2275. typedef struct VmaAllocationCreateInfo
  2276. {
  2277. /// Use #VmaAllocationCreateFlagBits enum.
  2278. VmaAllocationCreateFlags flags;
  2279. /** \brief Intended usage of memory.
  2280. You can leave #VMA_MEMORY_USAGE_UNKNOWN if you specify memory requirements in other way. \n
  2281. If `pool` is not null, this member is ignored.
  2282. */
  2283. VmaMemoryUsage usage;
  2284. /** \brief Flags that must be set in a Memory Type chosen for an allocation.
  2285. Leave 0 if you specify memory requirements in other way. \n
  2286. If `pool` is not null, this member is ignored.*/
  2287. VkMemoryPropertyFlags requiredFlags;
  2288. /** \brief Flags that preferably should be set in a memory type chosen for an allocation.
  2289. Set to 0 if no additional flags are preferred. \n
  2290. If `pool` is not null, this member is ignored. */
  2291. VkMemoryPropertyFlags preferredFlags;
  2292. /** \brief Bitmask containing one bit set for every memory type acceptable for this allocation.
  2293. Value 0 is equivalent to `UINT32_MAX` - it means any memory type is accepted if
  2294. it meets other requirements specified by this structure, with no further
  2295. restrictions on memory type index. \n
  2296. If `pool` is not null, this member is ignored.
  2297. */
  2298. uint32_t memoryTypeBits;
  2299. /** \brief Pool that this allocation should be created in.
  2300. Leave `VK_NULL_HANDLE` to allocate from default pool. If not null, members:
  2301. `usage`, `requiredFlags`, `preferredFlags`, `memoryTypeBits` are ignored.
  2302. */
  2303. VmaPool VMA_NULLABLE pool;
  2304. /** \brief Custom general-purpose pointer that will be stored in #VmaAllocation, can be read as VmaAllocationInfo::pUserData and changed using vmaSetAllocationUserData().
  2305. If #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT is used, it must be either
  2306. null or pointer to a null-terminated string. The string will be then copied to
  2307. internal buffer, so it doesn't need to be valid after allocation call.
  2308. */
  2309. void* VMA_NULLABLE pUserData;
  2310. /** \brief A floating-point value between 0 and 1, indicating the priority of the allocation relative to other memory allocations.
  2311. It is used only when #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT flag was used during creation of the #VmaAllocator object
  2312. and this allocation ends up as dedicated or is explicitly forced as dedicated using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  2313. Otherwise, it has the priority of a memory block where it is placed and this variable is ignored.
  2314. */
  2315. float priority;
  2316. } VmaAllocationCreateInfo;
  2317. /**
  2318. \brief Helps to find memoryTypeIndex, given memoryTypeBits and VmaAllocationCreateInfo.
  2319. This algorithm tries to find a memory type that:
  2320. - Is allowed by memoryTypeBits.
  2321. - Contains all the flags from pAllocationCreateInfo->requiredFlags.
  2322. - Matches intended usage.
  2323. - Has as many flags from pAllocationCreateInfo->preferredFlags as possible.
  2324. \return Returns VK_ERROR_FEATURE_NOT_PRESENT if not found. Receiving such result
  2325. from this function or any other allocating function probably means that your
  2326. device doesn't support any memory type with requested features for the specific
  2327. type of resource you want to use it for. Please check parameters of your
  2328. resource, like image layout (OPTIMAL versus LINEAR) or mip level count.
  2329. */
  2330. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex(
  2331. VmaAllocator VMA_NOT_NULL allocator,
  2332. uint32_t memoryTypeBits,
  2333. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  2334. uint32_t* VMA_NOT_NULL pMemoryTypeIndex);
  2335. /**
  2336. \brief Helps to find memoryTypeIndex, given VkBufferCreateInfo and VmaAllocationCreateInfo.
  2337. It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex.
  2338. It internally creates a temporary, dummy buffer that never has memory bound.
  2339. It is just a convenience function, equivalent to calling:
  2340. - `vkCreateBuffer`
  2341. - `vkGetBufferMemoryRequirements`
  2342. - `vmaFindMemoryTypeIndex`
  2343. - `vkDestroyBuffer`
  2344. */
  2345. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo(
  2346. VmaAllocator VMA_NOT_NULL allocator,
  2347. const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo,
  2348. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  2349. uint32_t* VMA_NOT_NULL pMemoryTypeIndex);
  2350. /**
  2351. \brief Helps to find memoryTypeIndex, given VkImageCreateInfo and VmaAllocationCreateInfo.
  2352. It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex.
  2353. It internally creates a temporary, dummy image that never has memory bound.
  2354. It is just a convenience function, equivalent to calling:
  2355. - `vkCreateImage`
  2356. - `vkGetImageMemoryRequirements`
  2357. - `vmaFindMemoryTypeIndex`
  2358. - `vkDestroyImage`
  2359. */
  2360. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo(
  2361. VmaAllocator VMA_NOT_NULL allocator,
  2362. const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo,
  2363. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  2364. uint32_t* VMA_NOT_NULL pMemoryTypeIndex);
  2365. /// Flags to be passed as VmaPoolCreateInfo::flags.
  2366. typedef enum VmaPoolCreateFlagBits {
  2367. /** \brief Use this flag if you always allocate only buffers and linear images or only optimal images out of this pool and so Buffer-Image Granularity can be ignored.
  2368. This is an optional optimization flag.
  2369. If you always allocate using vmaCreateBuffer(), vmaCreateImage(),
  2370. vmaAllocateMemoryForBuffer(), then you don't need to use it because allocator
  2371. knows exact type of your allocations so it can handle Buffer-Image Granularity
  2372. in the optimal way.
  2373. If you also allocate using vmaAllocateMemoryForImage() or vmaAllocateMemory(),
  2374. exact type of such allocations is not known, so allocator must be conservative
  2375. in handling Buffer-Image Granularity, which can lead to suboptimal allocation
  2376. (wasted memory). In that case, if you can make sure you always allocate only
  2377. buffers and linear images or only optimal images out of this pool, use this flag
  2378. to make allocator disregard Buffer-Image Granularity and so make allocations
  2379. faster and more optimal.
  2380. */
  2381. VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT = 0x00000002,
  2382. /** \brief Enables alternative, linear allocation algorithm in this pool.
  2383. Specify this flag to enable linear allocation algorithm, which always creates
  2384. new allocations after last one and doesn't reuse space from allocations freed in
  2385. between. It trades memory consumption for simplified algorithm and data
  2386. structure, which has better performance and uses less memory for metadata.
  2387. By using this flag, you can achieve behavior of free-at-once, stack,
  2388. ring buffer, and double stack. For details, see documentation chapter
  2389. \ref linear_algorithm.
  2390. When using this flag, you must specify VmaPoolCreateInfo::maxBlockCount == 1 (or 0 for default).
  2391. For more details, see [Linear allocation algorithm](@ref linear_algorithm).
  2392. */
  2393. VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT = 0x00000004,
  2394. /** \brief Enables alternative, buddy allocation algorithm in this pool.
  2395. It operates on a tree of blocks, each having size that is a power of two and
  2396. a half of its parent's size. Comparing to default algorithm, this one provides
  2397. faster allocation and deallocation and decreased external fragmentation,
  2398. at the expense of more memory wasted (internal fragmentation).
  2399. For more details, see [Buddy allocation algorithm](@ref buddy_algorithm).
  2400. */
  2401. VMA_POOL_CREATE_BUDDY_ALGORITHM_BIT = 0x00000008,
  2402. /** Bit mask to extract only `ALGORITHM` bits from entire set of flags.
  2403. */
  2404. VMA_POOL_CREATE_ALGORITHM_MASK =
  2405. VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT |
  2406. VMA_POOL_CREATE_BUDDY_ALGORITHM_BIT,
  2407. VMA_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  2408. } VmaPoolCreateFlagBits;
  2409. typedef VkFlags VmaPoolCreateFlags;
  2410. /** \brief Describes parameter of created #VmaPool.
  2411. */
  2412. typedef struct VmaPoolCreateInfo {
  2413. /** \brief Vulkan memory type index to allocate this pool from.
  2414. */
  2415. uint32_t memoryTypeIndex;
  2416. /** \brief Use combination of #VmaPoolCreateFlagBits.
  2417. */
  2418. VmaPoolCreateFlags flags;
  2419. /** \brief Size of a single `VkDeviceMemory` block to be allocated as part of this pool, in bytes. Optional.
  2420. Specify nonzero to set explicit, constant size of memory blocks used by this
  2421. pool.
  2422. Leave 0 to use default and let the library manage block sizes automatically.
  2423. Sizes of particular blocks may vary.
  2424. */
  2425. VkDeviceSize blockSize;
  2426. /** \brief Minimum number of blocks to be always allocated in this pool, even if they stay empty.
  2427. Set to 0 to have no preallocated blocks and allow the pool be completely empty.
  2428. */
  2429. size_t minBlockCount;
  2430. /** \brief Maximum number of blocks that can be allocated in this pool. Optional.
  2431. Set to 0 to use default, which is `SIZE_MAX`, which means no limit.
  2432. Set to same value as VmaPoolCreateInfo::minBlockCount to have fixed amount of memory allocated
  2433. throughout whole lifetime of this pool.
  2434. */
  2435. size_t maxBlockCount;
  2436. /** \brief Maximum number of additional frames that are in use at the same time as current frame.
  2437. This value is used only when you make allocations with
  2438. #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag. Such allocation cannot become
  2439. lost if allocation.lastUseFrameIndex >= allocator.currentFrameIndex - frameInUseCount.
  2440. For example, if you double-buffer your command buffers, so resources used for
  2441. rendering in previous frame may still be in use by the GPU at the moment you
  2442. allocate resources needed for the current frame, set this value to 1.
  2443. If you want to allow any allocations other than used in the current frame to
  2444. become lost, set this value to 0.
  2445. */
  2446. uint32_t frameInUseCount;
  2447. /** \brief A floating-point value between 0 and 1, indicating the priority of the allocations in this pool relative to other memory allocations.
  2448. It is used only when #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT flag was used during creation of the #VmaAllocator object.
  2449. Otherwise, this variable is ignored.
  2450. */
  2451. float priority;
  2452. /** \brief Additional minimum alignment to be used for all allocations created from this pool. Can be 0.
  2453. Leave 0 (default) not to impose any additional alignment. If not 0, it must be a power of two.
  2454. It can be useful in cases where alignment returned by Vulkan by functions like `vkGetBufferMemoryRequirements` is not enough,
  2455. e.g. when doing interop with OpenGL.
  2456. */
  2457. VkDeviceSize minAllocationAlignment;
  2458. /** \brief Additional `pNext` chain to be attached to `VkMemoryAllocateInfo` used for every allocation made by this pool. Optional.
  2459. Optional, can be null. If not null, it must point to a `pNext` chain of structures that can be attached to `VkMemoryAllocateInfo`.
  2460. It can be useful for special needs such as adding `VkExportMemoryAllocateInfoKHR`.
  2461. Structures pointed by this member must remain alive and unchanged for the whole lifetime of the custom pool.
  2462. Please note that some structures, e.g. `VkMemoryPriorityAllocateInfoEXT`, `VkMemoryDedicatedAllocateInfoKHR`,
  2463. can be attached automatically by this library when using other, more convenient of its features.
  2464. */
  2465. void* VMA_NULLABLE pMemoryAllocateNext;
  2466. } VmaPoolCreateInfo;
  2467. /** \brief Describes parameter of existing #VmaPool.
  2468. */
  2469. typedef struct VmaPoolStats {
  2470. /** \brief Total amount of `VkDeviceMemory` allocated from Vulkan for this pool, in bytes.
  2471. */
  2472. VkDeviceSize size;
  2473. /** \brief Total number of bytes in the pool not used by any #VmaAllocation.
  2474. */
  2475. VkDeviceSize unusedSize;
  2476. /** \brief Number of #VmaAllocation objects created from this pool that were not destroyed or lost.
  2477. */
  2478. size_t allocationCount;
  2479. /** \brief Number of continuous memory ranges in the pool not used by any #VmaAllocation.
  2480. */
  2481. size_t unusedRangeCount;
  2482. /** \brief Size of the largest continuous free memory region available for new allocation.
  2483. Making a new allocation of that size is not guaranteed to succeed because of
  2484. possible additional margin required to respect alignment and buffer/image
  2485. granularity.
  2486. */
  2487. VkDeviceSize unusedRangeSizeMax;
  2488. /** \brief Number of `VkDeviceMemory` blocks allocated for this pool.
  2489. */
  2490. size_t blockCount;
  2491. } VmaPoolStats;
  2492. /** \brief Allocates Vulkan device memory and creates #VmaPool object.
  2493. @param allocator Allocator object.
  2494. @param pCreateInfo Parameters of pool to create.
  2495. @param[out] pPool Handle to created pool.
  2496. */
  2497. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool(
  2498. VmaAllocator VMA_NOT_NULL allocator,
  2499. const VmaPoolCreateInfo* VMA_NOT_NULL pCreateInfo,
  2500. VmaPool VMA_NULLABLE * VMA_NOT_NULL pPool);
  2501. /** \brief Destroys #VmaPool object and frees Vulkan device memory.
  2502. */
  2503. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool(
  2504. VmaAllocator VMA_NOT_NULL allocator,
  2505. VmaPool VMA_NULLABLE pool);
  2506. /** \brief Retrieves statistics of existing #VmaPool object.
  2507. @param allocator Allocator object.
  2508. @param pool Pool object.
  2509. @param[out] pPoolStats Statistics of specified pool.
  2510. */
  2511. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStats(
  2512. VmaAllocator VMA_NOT_NULL allocator,
  2513. VmaPool VMA_NOT_NULL pool,
  2514. VmaPoolStats* VMA_NOT_NULL pPoolStats);
  2515. /** \brief Marks all allocations in given pool as lost if they are not used in current frame or VmaPoolCreateInfo::frameInUseCount back from now.
  2516. @param allocator Allocator object.
  2517. @param pool Pool.
  2518. @param[out] pLostAllocationCount Number of allocations marked as lost. Optional - pass null if you don't need this information.
  2519. */
  2520. VMA_CALL_PRE void VMA_CALL_POST vmaMakePoolAllocationsLost(
  2521. VmaAllocator VMA_NOT_NULL allocator,
  2522. VmaPool VMA_NOT_NULL pool,
  2523. size_t* VMA_NULLABLE pLostAllocationCount);
  2524. /** \brief Checks magic number in margins around all allocations in given memory pool in search for corruptions.
  2525. Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero,
  2526. `VMA_DEBUG_MARGIN` is defined to nonzero and the pool is created in memory type that is
  2527. `HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection).
  2528. Possible return values:
  2529. - `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for specified pool.
  2530. - `VK_SUCCESS` - corruption detection has been performed and succeeded.
  2531. - `VK_ERROR_VALIDATION_FAILED_EXT` - corruption detection has been performed and found memory corruptions around one of the allocations.
  2532. `VMA_ASSERT` is also fired in that case.
  2533. - Other value: Error returned by Vulkan, e.g. memory mapping failure.
  2534. */
  2535. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckPoolCorruption(VmaAllocator VMA_NOT_NULL allocator, VmaPool VMA_NOT_NULL pool);
  2536. /** \brief Retrieves name of a custom pool.
  2537. After the call `ppName` is either null or points to an internally-owned null-terminated string
  2538. containing name of the pool that was previously set. The pointer becomes invalid when the pool is
  2539. destroyed or its name is changed using vmaSetPoolName().
  2540. */
  2541. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName(
  2542. VmaAllocator VMA_NOT_NULL allocator,
  2543. VmaPool VMA_NOT_NULL pool,
  2544. const char* VMA_NULLABLE * VMA_NOT_NULL ppName);
  2545. /** \brief Sets name of a custom pool.
  2546. `pName` can be either null or pointer to a null-terminated string with new name for the pool.
  2547. Function makes internal copy of the string, so it can be changed or freed immediately after this call.
  2548. */
  2549. VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName(
  2550. VmaAllocator VMA_NOT_NULL allocator,
  2551. VmaPool VMA_NOT_NULL pool,
  2552. const char* VMA_NULLABLE pName);
  2553. /** \struct VmaAllocation
  2554. \brief Represents single memory allocation.
  2555. It may be either dedicated block of `VkDeviceMemory` or a specific region of a bigger block of this type
  2556. plus unique offset.
  2557. There are multiple ways to create such object.
  2558. You need to fill structure VmaAllocationCreateInfo.
  2559. For more information see [Choosing memory type](@ref choosing_memory_type).
  2560. Although the library provides convenience functions that create Vulkan buffer or image,
  2561. allocate memory for it and bind them together,
  2562. binding of the allocation to a buffer or an image is out of scope of the allocation itself.
  2563. Allocation object can exist without buffer/image bound,
  2564. binding can be done manually by the user, and destruction of it can be done
  2565. independently of destruction of the allocation.
  2566. The object also remembers its size and some other information.
  2567. To retrieve this information, use function vmaGetAllocationInfo() and inspect
  2568. returned structure VmaAllocationInfo.
  2569. Some kinds allocations can be in lost state.
  2570. For more information, see [Lost allocations](@ref lost_allocations).
  2571. */
  2572. VK_DEFINE_HANDLE(VmaAllocation)
  2573. /** \brief Parameters of #VmaAllocation objects, that can be retrieved using function vmaGetAllocationInfo().
  2574. */
  2575. typedef struct VmaAllocationInfo {
  2576. /** \brief Memory type index that this allocation was allocated from.
  2577. It never changes.
  2578. */
  2579. uint32_t memoryType;
  2580. /** \brief Handle to Vulkan memory object.
  2581. Same memory object can be shared by multiple allocations.
  2582. It can change after call to vmaDefragment() if this allocation is passed to the function, or if allocation is lost.
  2583. If the allocation is lost, it is equal to `VK_NULL_HANDLE`.
  2584. */
  2585. VkDeviceMemory VMA_NULLABLE_NON_DISPATCHABLE deviceMemory;
  2586. /** \brief Offset in `VkDeviceMemory` object to the beginning of this allocation, in bytes. `(deviceMemory, offset)` pair is unique to this allocation.
  2587. You usually don't need to use this offset. If you create a buffer or an image together with the allocation using e.g. function
  2588. vmaCreateBuffer(), vmaCreateImage(), functions that operate on these resources refer to the beginning of the buffer or image,
  2589. not entire device memory block. Functions like vmaMapMemory(), vmaBindBufferMemory() also refer to the beginning of the allocation
  2590. and apply this offset automatically.
  2591. It can change after call to vmaDefragment() if this allocation is passed to the function, or if allocation is lost.
  2592. */
  2593. VkDeviceSize offset;
  2594. /** \brief Size of this allocation, in bytes.
  2595. It never changes, unless allocation is lost.
  2596. \note Allocation size returned in this variable may be greater than the size
  2597. requested for the resource e.g. as `VkBufferCreateInfo::size`. Whole size of the
  2598. allocation is accessible for operations on memory e.g. using a pointer after
  2599. mapping with vmaMapMemory(), but operations on the resource e.g. using
  2600. `vkCmdCopyBuffer` must be limited to the size of the resource.
  2601. */
  2602. VkDeviceSize size;
  2603. /** \brief Pointer to the beginning of this allocation as mapped data.
  2604. If the allocation hasn't been mapped using vmaMapMemory() and hasn't been
  2605. created with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag, this value is null.
  2606. It can change after call to vmaMapMemory(), vmaUnmapMemory().
  2607. It can also change after call to vmaDefragment() if this allocation is passed to the function.
  2608. */
  2609. void* VMA_NULLABLE pMappedData;
  2610. /** \brief Custom general-purpose pointer that was passed as VmaAllocationCreateInfo::pUserData or set using vmaSetAllocationUserData().
  2611. It can change after call to vmaSetAllocationUserData() for this allocation.
  2612. */
  2613. void* VMA_NULLABLE pUserData;
  2614. } VmaAllocationInfo;
  2615. /** \brief General purpose memory allocation.
  2616. @param[out] pAllocation Handle to allocated memory.
  2617. @param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
  2618. You should free the memory using vmaFreeMemory() or vmaFreeMemoryPages().
  2619. It is recommended to use vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage(),
  2620. vmaCreateBuffer(), vmaCreateImage() instead whenever possible.
  2621. */
  2622. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory(
  2623. VmaAllocator VMA_NOT_NULL allocator,
  2624. const VkMemoryRequirements* VMA_NOT_NULL pVkMemoryRequirements,
  2625. const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo,
  2626. VmaAllocation VMA_NULLABLE * VMA_NOT_NULL pAllocation,
  2627. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  2628. /** \brief General purpose memory allocation for multiple allocation objects at once.
  2629. @param allocator Allocator object.
  2630. @param pVkMemoryRequirements Memory requirements for each allocation.
  2631. @param pCreateInfo Creation parameters for each alloction.
  2632. @param allocationCount Number of allocations to make.
  2633. @param[out] pAllocations Pointer to array that will be filled with handles to created allocations.
  2634. @param[out] pAllocationInfo Optional. Pointer to array that will be filled with parameters of created allocations.
  2635. You should free the memory using vmaFreeMemory() or vmaFreeMemoryPages().
  2636. Word "pages" is just a suggestion to use this function to allocate pieces of memory needed for sparse binding.
  2637. It is just a general purpose allocation function able to make multiple allocations at once.
  2638. It may be internally optimized to be more efficient than calling vmaAllocateMemory() `allocationCount` times.
  2639. All allocations are made using same parameters. All of them are created out of the same memory pool and type.
  2640. If any allocation fails, all allocations already made within this function call are also freed, so that when
  2641. returned result is not `VK_SUCCESS`, `pAllocation` array is always entirely filled with `VK_NULL_HANDLE`.
  2642. */
  2643. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages(
  2644. VmaAllocator VMA_NOT_NULL allocator,
  2645. const VkMemoryRequirements* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pVkMemoryRequirements,
  2646. const VmaAllocationCreateInfo* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pCreateInfo,
  2647. size_t allocationCount,
  2648. VmaAllocation VMA_NULLABLE * VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations,
  2649. VmaAllocationInfo* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) pAllocationInfo);
  2650. /**
  2651. @param[out] pAllocation Handle to allocated memory.
  2652. @param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
  2653. You should free the memory using vmaFreeMemory().
  2654. */
  2655. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer(
  2656. VmaAllocator VMA_NOT_NULL allocator,
  2657. VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer,
  2658. const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo,
  2659. VmaAllocation VMA_NULLABLE * VMA_NOT_NULL pAllocation,
  2660. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  2661. /// Function similar to vmaAllocateMemoryForBuffer().
  2662. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage(
  2663. VmaAllocator VMA_NOT_NULL allocator,
  2664. VkImage VMA_NOT_NULL_NON_DISPATCHABLE image,
  2665. const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo,
  2666. VmaAllocation VMA_NULLABLE * VMA_NOT_NULL pAllocation,
  2667. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  2668. /** \brief Frees memory previously allocated using vmaAllocateMemory(), vmaAllocateMemoryForBuffer(), or vmaAllocateMemoryForImage().
  2669. Passing `VK_NULL_HANDLE` as `allocation` is valid. Such function call is just skipped.
  2670. */
  2671. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory(
  2672. VmaAllocator VMA_NOT_NULL allocator,
  2673. const VmaAllocation VMA_NULLABLE allocation);
  2674. /** \brief Frees memory and destroys multiple allocations.
  2675. Word "pages" is just a suggestion to use this function to free pieces of memory used for sparse binding.
  2676. It is just a general purpose function to free memory and destroy allocations made using e.g. vmaAllocateMemory(),
  2677. vmaAllocateMemoryPages() and other functions.
  2678. It may be internally optimized to be more efficient than calling vmaFreeMemory() `allocationCount` times.
  2679. Allocations in `pAllocations` array can come from any memory pools and types.
  2680. Passing `VK_NULL_HANDLE` as elements of `pAllocations` array is valid. Such entries are just skipped.
  2681. */
  2682. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages(
  2683. VmaAllocator VMA_NOT_NULL allocator,
  2684. size_t allocationCount,
  2685. const VmaAllocation VMA_NULLABLE * VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations);
  2686. /** \brief Returns current information about specified allocation and atomically marks it as used in current frame.
  2687. Current paramteres of given allocation are returned in `pAllocationInfo`.
  2688. This function also atomically "touches" allocation - marks it as used in current frame,
  2689. just like vmaTouchAllocation().
  2690. If the allocation is in lost state, `pAllocationInfo->deviceMemory == VK_NULL_HANDLE`.
  2691. Although this function uses atomics and doesn't lock any mutex, so it should be quite efficient,
  2692. you can avoid calling it too often.
  2693. - You can retrieve same VmaAllocationInfo structure while creating your resource, from function
  2694. vmaCreateBuffer(), vmaCreateImage(). You can remember it if you are sure parameters don't change
  2695. (e.g. due to defragmentation or allocation becoming lost).
  2696. - If you just want to check if allocation is not lost, vmaTouchAllocation() will work faster.
  2697. */
  2698. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo(
  2699. VmaAllocator VMA_NOT_NULL allocator,
  2700. VmaAllocation VMA_NOT_NULL allocation,
  2701. VmaAllocationInfo* VMA_NOT_NULL pAllocationInfo);
  2702. /** \brief Returns `VK_TRUE` if allocation is not lost and atomically marks it as used in current frame.
  2703. If the allocation has been created with #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag,
  2704. this function returns `VK_TRUE` if it's not in lost state, so it can still be used.
  2705. It then also atomically "touches" the allocation - marks it as used in current frame,
  2706. so that you can be sure it won't become lost in current frame or next `frameInUseCount` frames.
  2707. If the allocation is in lost state, the function returns `VK_FALSE`.
  2708. Memory of such allocation, as well as buffer or image bound to it, should not be used.
  2709. Lost allocation and the buffer/image still need to be destroyed.
  2710. If the allocation has been created without #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag,
  2711. this function always returns `VK_TRUE`.
  2712. */
  2713. VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaTouchAllocation(
  2714. VmaAllocator VMA_NOT_NULL allocator,
  2715. VmaAllocation VMA_NOT_NULL allocation);
  2716. /** \brief Sets pUserData in given allocation to new value.
  2717. If the allocation was created with VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT,
  2718. pUserData must be either null, or pointer to a null-terminated string. The function
  2719. makes local copy of the string and sets it as allocation's `pUserData`. String
  2720. passed as pUserData doesn't need to be valid for whole lifetime of the allocation -
  2721. you can free it after this call. String previously pointed by allocation's
  2722. pUserData is freed from memory.
  2723. If the flag was not used, the value of pointer `pUserData` is just copied to
  2724. allocation's `pUserData`. It is opaque, so you can use it however you want - e.g.
  2725. as a pointer, ordinal number or some handle to you own data.
  2726. */
  2727. VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData(
  2728. VmaAllocator VMA_NOT_NULL allocator,
  2729. VmaAllocation VMA_NOT_NULL allocation,
  2730. void* VMA_NULLABLE pUserData);
  2731. /** \brief Creates new allocation that is in lost state from the beginning.
  2732. It can be useful if you need a dummy, non-null allocation.
  2733. You still need to destroy created object using vmaFreeMemory().
  2734. Returned allocation is not tied to any specific memory pool or memory type and
  2735. not bound to any image or buffer. It has size = 0. It cannot be turned into
  2736. a real, non-empty allocation.
  2737. */
  2738. VMA_CALL_PRE void VMA_CALL_POST vmaCreateLostAllocation(
  2739. VmaAllocator VMA_NOT_NULL allocator,
  2740. VmaAllocation VMA_NULLABLE * VMA_NOT_NULL pAllocation);
  2741. /** \brief Maps memory represented by given allocation and returns pointer to it.
  2742. Maps memory represented by given allocation to make it accessible to CPU code.
  2743. When succeeded, `*ppData` contains pointer to first byte of this memory.
  2744. If the allocation is part of bigger `VkDeviceMemory` block, the pointer is
  2745. correctly offsetted to the beginning of region assigned to this particular
  2746. allocation.
  2747. Mapping is internally reference-counted and synchronized, so despite raw Vulkan
  2748. function `vkMapMemory()` cannot be used to map same block of `VkDeviceMemory`
  2749. multiple times simultaneously, it is safe to call this function on allocations
  2750. assigned to the same memory block. Actual Vulkan memory will be mapped on first
  2751. mapping and unmapped on last unmapping.
  2752. If the function succeeded, you must call vmaUnmapMemory() to unmap the
  2753. allocation when mapping is no longer needed or before freeing the allocation, at
  2754. the latest.
  2755. It also safe to call this function multiple times on the same allocation. You
  2756. must call vmaUnmapMemory() same number of times as you called vmaMapMemory().
  2757. It is also safe to call this function on allocation created with
  2758. #VMA_ALLOCATION_CREATE_MAPPED_BIT flag. Its memory stays mapped all the time.
  2759. You must still call vmaUnmapMemory() same number of times as you called
  2760. vmaMapMemory(). You must not call vmaUnmapMemory() additional time to free the
  2761. "0-th" mapping made automatically due to #VMA_ALLOCATION_CREATE_MAPPED_BIT flag.
  2762. This function fails when used on allocation made in memory type that is not
  2763. `HOST_VISIBLE`.
  2764. This function always fails when called for allocation that was created with
  2765. #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag. Such allocations cannot be
  2766. mapped.
  2767. This function doesn't automatically flush or invalidate caches.
  2768. If the allocation is made from a memory types that is not `HOST_COHERENT`,
  2769. you also need to use vmaInvalidateAllocation() / vmaFlushAllocation(), as required by Vulkan specification.
  2770. */
  2771. VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory(
  2772. VmaAllocator VMA_NOT_NULL allocator,
  2773. VmaAllocation VMA_NOT_NULL allocation,
  2774. void* VMA_NULLABLE * VMA_NOT_NULL ppData);
  2775. /** \brief Unmaps memory represented by given allocation, mapped previously using vmaMapMemory().
  2776. For details, see description of vmaMapMemory().
  2777. This function doesn't automatically flush or invalidate caches.
  2778. If the allocation is made from a memory types that is not `HOST_COHERENT`,
  2779. you also need to use vmaInvalidateAllocation() / vmaFlushAllocation(), as required by Vulkan specification.
  2780. */
  2781. VMA_CALL_PRE void VMA_CALL_POST vmaUnmapMemory(
  2782. VmaAllocator VMA_NOT_NULL allocator,
  2783. VmaAllocation VMA_NOT_NULL allocation);
  2784. /** \brief Flushes memory of given allocation.
  2785. Calls `vkFlushMappedMemoryRanges()` for memory associated with given range of given allocation.
  2786. It needs to be called after writing to a mapped memory for memory types that are not `HOST_COHERENT`.
  2787. Unmap operation doesn't do that automatically.
  2788. - `offset` must be relative to the beginning of allocation.
  2789. - `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation.
  2790. - `offset` and `size` don't have to be aligned.
  2791. They are internally rounded down/up to multiply of `nonCoherentAtomSize`.
  2792. - If `size` is 0, this call is ignored.
  2793. - If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`,
  2794. this call is ignored.
  2795. Warning! `offset` and `size` are relative to the contents of given `allocation`.
  2796. If you mean whole allocation, you can pass 0 and `VK_WHOLE_SIZE`, respectively.
  2797. Do not pass allocation's offset as `offset`!!!
  2798. This function returns the `VkResult` from `vkFlushMappedMemoryRanges` if it is
  2799. called, otherwise `VK_SUCCESS`.
  2800. */
  2801. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocation(
  2802. VmaAllocator VMA_NOT_NULL allocator,
  2803. VmaAllocation VMA_NOT_NULL allocation,
  2804. VkDeviceSize offset,
  2805. VkDeviceSize size);
  2806. /** \brief Invalidates memory of given allocation.
  2807. Calls `vkInvalidateMappedMemoryRanges()` for memory associated with given range of given allocation.
  2808. It needs to be called before reading from a mapped memory for memory types that are not `HOST_COHERENT`.
  2809. Map operation doesn't do that automatically.
  2810. - `offset` must be relative to the beginning of allocation.
  2811. - `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation.
  2812. - `offset` and `size` don't have to be aligned.
  2813. They are internally rounded down/up to multiply of `nonCoherentAtomSize`.
  2814. - If `size` is 0, this call is ignored.
  2815. - If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`,
  2816. this call is ignored.
  2817. Warning! `offset` and `size` are relative to the contents of given `allocation`.
  2818. If you mean whole allocation, you can pass 0 and `VK_WHOLE_SIZE`, respectively.
  2819. Do not pass allocation's offset as `offset`!!!
  2820. This function returns the `VkResult` from `vkInvalidateMappedMemoryRanges` if
  2821. it is called, otherwise `VK_SUCCESS`.
  2822. */
  2823. VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocation(
  2824. VmaAllocator VMA_NOT_NULL allocator,
  2825. VmaAllocation VMA_NOT_NULL allocation,
  2826. VkDeviceSize offset,
  2827. VkDeviceSize size);
  2828. /** \brief Flushes memory of given set of allocations.
  2829. Calls `vkFlushMappedMemoryRanges()` for memory associated with given ranges of given allocations.
  2830. For more information, see documentation of vmaFlushAllocation().
  2831. \param allocator
  2832. \param allocationCount
  2833. \param allocations
  2834. \param offsets If not null, it must point to an array of offsets of regions to flush, relative to the beginning of respective allocations. Null means all ofsets are zero.
  2835. \param sizes If not null, it must point to an array of sizes of regions to flush in respective allocations. Null means `VK_WHOLE_SIZE` for all allocations.
  2836. This function returns the `VkResult` from `vkFlushMappedMemoryRanges` if it is
  2837. called, otherwise `VK_SUCCESS`.
  2838. */
  2839. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocations(
  2840. VmaAllocator VMA_NOT_NULL allocator,
  2841. uint32_t allocationCount,
  2842. const VmaAllocation VMA_NOT_NULL * VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) allocations,
  2843. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) offsets,
  2844. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) sizes);
  2845. /** \brief Invalidates memory of given set of allocations.
  2846. Calls `vkInvalidateMappedMemoryRanges()` for memory associated with given ranges of given allocations.
  2847. For more information, see documentation of vmaInvalidateAllocation().
  2848. \param allocator
  2849. \param allocationCount
  2850. \param allocations
  2851. \param offsets If not null, it must point to an array of offsets of regions to flush, relative to the beginning of respective allocations. Null means all ofsets are zero.
  2852. \param sizes If not null, it must point to an array of sizes of regions to flush in respective allocations. Null means `VK_WHOLE_SIZE` for all allocations.
  2853. This function returns the `VkResult` from `vkInvalidateMappedMemoryRanges` if it is
  2854. called, otherwise `VK_SUCCESS`.
  2855. */
  2856. VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocations(
  2857. VmaAllocator VMA_NOT_NULL allocator,
  2858. uint32_t allocationCount,
  2859. const VmaAllocation VMA_NOT_NULL * VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) allocations,
  2860. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) offsets,
  2861. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) sizes);
  2862. /** \brief Checks magic number in margins around all allocations in given memory types (in both default and custom pools) in search for corruptions.
  2863. @param memoryTypeBits Bit mask, where each bit set means that a memory type with that index should be checked.
  2864. Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero,
  2865. `VMA_DEBUG_MARGIN` is defined to nonzero and only for memory types that are
  2866. `HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection).
  2867. Possible return values:
  2868. - `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for any of specified memory types.
  2869. - `VK_SUCCESS` - corruption detection has been performed and succeeded.
  2870. - `VK_ERROR_VALIDATION_FAILED_EXT` - corruption detection has been performed and found memory corruptions around one of the allocations.
  2871. `VMA_ASSERT` is also fired in that case.
  2872. - Other value: Error returned by Vulkan, e.g. memory mapping failure.
  2873. */
  2874. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckCorruption(VmaAllocator VMA_NOT_NULL allocator, uint32_t memoryTypeBits);
  2875. /** \struct VmaDefragmentationContext
  2876. \brief Represents Opaque object that represents started defragmentation process.
  2877. Fill structure #VmaDefragmentationInfo2 and call function vmaDefragmentationBegin() to create it.
  2878. Call function vmaDefragmentationEnd() to destroy it.
  2879. */
  2880. VK_DEFINE_HANDLE(VmaDefragmentationContext)
  2881. /// Flags to be used in vmaDefragmentationBegin(). None at the moment. Reserved for future use.
  2882. typedef enum VmaDefragmentationFlagBits {
  2883. VMA_DEFRAGMENTATION_FLAG_INCREMENTAL = 0x1,
  2884. VMA_DEFRAGMENTATION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  2885. } VmaDefragmentationFlagBits;
  2886. typedef VkFlags VmaDefragmentationFlags;
  2887. /** \brief Parameters for defragmentation.
  2888. To be used with function vmaDefragmentationBegin().
  2889. */
  2890. typedef struct VmaDefragmentationInfo2 {
  2891. /** \brief Reserved for future use. Should be 0.
  2892. */
  2893. VmaDefragmentationFlags flags;
  2894. /** \brief Number of allocations in `pAllocations` array.
  2895. */
  2896. uint32_t allocationCount;
  2897. /** \brief Pointer to array of allocations that can be defragmented.
  2898. The array should have `allocationCount` elements.
  2899. The array should not contain nulls.
  2900. Elements in the array should be unique - same allocation cannot occur twice.
  2901. It is safe to pass allocations that are in the lost state - they are ignored.
  2902. All allocations not present in this array are considered non-moveable during this defragmentation.
  2903. */
  2904. const VmaAllocation VMA_NOT_NULL * VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations;
  2905. /** \brief Optional, output. Pointer to array that will be filled with information whether the allocation at certain index has been changed during defragmentation.
  2906. The array should have `allocationCount` elements.
  2907. You can pass null if you are not interested in this information.
  2908. */
  2909. VkBool32* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) pAllocationsChanged;
  2910. /** \brief Numer of pools in `pPools` array.
  2911. */
  2912. uint32_t poolCount;
  2913. /** \brief Either null or pointer to array of pools to be defragmented.
  2914. All the allocations in the specified pools can be moved during defragmentation
  2915. and there is no way to check if they were really moved as in `pAllocationsChanged`,
  2916. so you must query all the allocations in all these pools for new `VkDeviceMemory`
  2917. and offset using vmaGetAllocationInfo() if you might need to recreate buffers
  2918. and images bound to them.
  2919. The array should have `poolCount` elements.
  2920. The array should not contain nulls.
  2921. Elements in the array should be unique - same pool cannot occur twice.
  2922. Using this array is equivalent to specifying all allocations from the pools in `pAllocations`.
  2923. It might be more efficient.
  2924. */
  2925. const VmaPool VMA_NOT_NULL * VMA_NULLABLE VMA_LEN_IF_NOT_NULL(poolCount) pPools;
  2926. /** \brief Maximum total numbers of bytes that can be copied while moving allocations to different places using transfers on CPU side, like `memcpy()`, `memmove()`.
  2927. `VK_WHOLE_SIZE` means no limit.
  2928. */
  2929. VkDeviceSize maxCpuBytesToMove;
  2930. /** \brief Maximum number of allocations that can be moved to a different place using transfers on CPU side, like `memcpy()`, `memmove()`.
  2931. `UINT32_MAX` means no limit.
  2932. */
  2933. uint32_t maxCpuAllocationsToMove;
  2934. /** \brief Maximum total numbers of bytes that can be copied while moving allocations to different places using transfers on GPU side, posted to `commandBuffer`.
  2935. `VK_WHOLE_SIZE` means no limit.
  2936. */
  2937. VkDeviceSize maxGpuBytesToMove;
  2938. /** \brief Maximum number of allocations that can be moved to a different place using transfers on GPU side, posted to `commandBuffer`.
  2939. `UINT32_MAX` means no limit.
  2940. */
  2941. uint32_t maxGpuAllocationsToMove;
  2942. /** \brief Optional. Command buffer where GPU copy commands will be posted.
  2943. If not null, it must be a valid command buffer handle that supports Transfer queue type.
  2944. It must be in the recording state and outside of a render pass instance.
  2945. You need to submit it and make sure it finished execution before calling vmaDefragmentationEnd().
  2946. Passing null means that only CPU defragmentation will be performed.
  2947. */
  2948. VkCommandBuffer VMA_NULLABLE commandBuffer;
  2949. } VmaDefragmentationInfo2;
  2950. typedef struct VmaDefragmentationPassMoveInfo {
  2951. VmaAllocation VMA_NOT_NULL allocation;
  2952. VkDeviceMemory VMA_NOT_NULL_NON_DISPATCHABLE memory;
  2953. VkDeviceSize offset;
  2954. } VmaDefragmentationPassMoveInfo;
  2955. /** \brief Parameters for incremental defragmentation steps.
  2956. To be used with function vmaBeginDefragmentationPass().
  2957. */
  2958. typedef struct VmaDefragmentationPassInfo {
  2959. uint32_t moveCount;
  2960. VmaDefragmentationPassMoveInfo* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(moveCount) pMoves;
  2961. } VmaDefragmentationPassInfo;
  2962. /** \brief Deprecated. Optional configuration parameters to be passed to function vmaDefragment().
  2963. \deprecated This is a part of the old interface. It is recommended to use structure #VmaDefragmentationInfo2 and function vmaDefragmentationBegin() instead.
  2964. */
  2965. typedef struct VmaDefragmentationInfo {
  2966. /** \brief Maximum total numbers of bytes that can be copied while moving allocations to different places.
  2967. Default is `VK_WHOLE_SIZE`, which means no limit.
  2968. */
  2969. VkDeviceSize maxBytesToMove;
  2970. /** \brief Maximum number of allocations that can be moved to different place.
  2971. Default is `UINT32_MAX`, which means no limit.
  2972. */
  2973. uint32_t maxAllocationsToMove;
  2974. } VmaDefragmentationInfo;
  2975. /** \brief Statistics returned by function vmaDefragment(). */
  2976. typedef struct VmaDefragmentationStats {
  2977. /// Total number of bytes that have been copied while moving allocations to different places.
  2978. VkDeviceSize bytesMoved;
  2979. /// Total number of bytes that have been released to the system by freeing empty `VkDeviceMemory` objects.
  2980. VkDeviceSize bytesFreed;
  2981. /// Number of allocations that have been moved to different places.
  2982. uint32_t allocationsMoved;
  2983. /// Number of empty `VkDeviceMemory` objects that have been released to the system.
  2984. uint32_t deviceMemoryBlocksFreed;
  2985. } VmaDefragmentationStats;
  2986. /** \brief Begins defragmentation process.
  2987. @param allocator Allocator object.
  2988. @param pInfo Structure filled with parameters of defragmentation.
  2989. @param[out] pStats Optional. Statistics of defragmentation. You can pass null if you are not interested in this information.
  2990. @param[out] pContext Context object that must be passed to vmaDefragmentationEnd() to finish defragmentation.
  2991. @return `VK_SUCCESS` and `*pContext == null` if defragmentation finished within this function call. `VK_NOT_READY` and `*pContext != null` if defragmentation has been started and you need to call vmaDefragmentationEnd() to finish it. Negative value in case of error.
  2992. Use this function instead of old, deprecated vmaDefragment().
  2993. Warning! Between the call to vmaDefragmentationBegin() and vmaDefragmentationEnd():
  2994. - You should not use any of allocations passed as `pInfo->pAllocations` or
  2995. any allocations that belong to pools passed as `pInfo->pPools`,
  2996. including calling vmaGetAllocationInfo(), vmaTouchAllocation(), or access
  2997. their data.
  2998. - Some mutexes protecting internal data structures may be locked, so trying to
  2999. make or free any allocations, bind buffers or images, map memory, or launch
  3000. another simultaneous defragmentation in between may cause stall (when done on
  3001. another thread) or deadlock (when done on the same thread), unless you are
  3002. 100% sure that defragmented allocations are in different pools.
  3003. - Information returned via `pStats` and `pInfo->pAllocationsChanged` are undefined.
  3004. They become valid after call to vmaDefragmentationEnd().
  3005. - If `pInfo->commandBuffer` is not null, you must submit that command buffer
  3006. and make sure it finished execution before calling vmaDefragmentationEnd().
  3007. For more information and important limitations regarding defragmentation, see documentation chapter:
  3008. [Defragmentation](@ref defragmentation).
  3009. */
  3010. VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragmentationBegin(
  3011. VmaAllocator VMA_NOT_NULL allocator,
  3012. const VmaDefragmentationInfo2* VMA_NOT_NULL pInfo,
  3013. VmaDefragmentationStats* VMA_NULLABLE pStats,
  3014. VmaDefragmentationContext VMA_NULLABLE * VMA_NOT_NULL pContext);
  3015. /** \brief Ends defragmentation process.
  3016. Use this function to finish defragmentation started by vmaDefragmentationBegin().
  3017. It is safe to pass `context == null`. The function then does nothing.
  3018. */
  3019. VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragmentationEnd(
  3020. VmaAllocator VMA_NOT_NULL allocator,
  3021. VmaDefragmentationContext VMA_NULLABLE context);
  3022. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentationPass(
  3023. VmaAllocator VMA_NOT_NULL allocator,
  3024. VmaDefragmentationContext VMA_NULLABLE context,
  3025. VmaDefragmentationPassInfo* VMA_NOT_NULL pInfo
  3026. );
  3027. VMA_CALL_PRE VkResult VMA_CALL_POST vmaEndDefragmentationPass(
  3028. VmaAllocator VMA_NOT_NULL allocator,
  3029. VmaDefragmentationContext VMA_NULLABLE context
  3030. );
  3031. /** \brief Deprecated. Compacts memory by moving allocations.
  3032. @param pAllocations Array of allocations that can be moved during this compation.
  3033. @param allocationCount Number of elements in pAllocations and pAllocationsChanged arrays.
  3034. @param[out] pAllocationsChanged Array of boolean values that will indicate whether matching allocation in pAllocations array has been moved. This parameter is optional. Pass null if you don't need this information.
  3035. @param pDefragmentationInfo Configuration parameters. Optional - pass null to use default values.
  3036. @param[out] pDefragmentationStats Statistics returned by the function. Optional - pass null if you don't need this information.
  3037. @return `VK_SUCCESS` if completed, negative error code in case of error.
  3038. \deprecated This is a part of the old interface. It is recommended to use structure #VmaDefragmentationInfo2 and function vmaDefragmentationBegin() instead.
  3039. This function works by moving allocations to different places (different
  3040. `VkDeviceMemory` objects and/or different offsets) in order to optimize memory
  3041. usage. Only allocations that are in `pAllocations` array can be moved. All other
  3042. allocations are considered nonmovable in this call. Basic rules:
  3043. - Only allocations made in memory types that have
  3044. `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` and `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT`
  3045. flags can be compacted. You may pass other allocations but it makes no sense -
  3046. these will never be moved.
  3047. - Custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT or
  3048. #VMA_POOL_CREATE_BUDDY_ALGORITHM_BIT flag are not defragmented. Allocations
  3049. passed to this function that come from such pools are ignored.
  3050. - Allocations created with #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT or
  3051. created as dedicated allocations for any other reason are also ignored.
  3052. - Both allocations made with or without #VMA_ALLOCATION_CREATE_MAPPED_BIT
  3053. flag can be compacted. If not persistently mapped, memory will be mapped
  3054. temporarily inside this function if needed.
  3055. - You must not pass same #VmaAllocation object multiple times in `pAllocations` array.
  3056. The function also frees empty `VkDeviceMemory` blocks.
  3057. Warning: This function may be time-consuming, so you shouldn't call it too often
  3058. (like after every resource creation/destruction).
  3059. You can call it on special occasions (like when reloading a game level or
  3060. when you just destroyed a lot of objects). Calling it every frame may be OK, but
  3061. you should measure that on your platform.
  3062. For more information, see [Defragmentation](@ref defragmentation) chapter.
  3063. */
  3064. VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragment(
  3065. VmaAllocator VMA_NOT_NULL allocator,
  3066. const VmaAllocation VMA_NOT_NULL * VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations,
  3067. size_t allocationCount,
  3068. VkBool32* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) pAllocationsChanged,
  3069. const VmaDefragmentationInfo* VMA_NULLABLE pDefragmentationInfo,
  3070. VmaDefragmentationStats* VMA_NULLABLE pDefragmentationStats);
  3071. /** \brief Binds buffer to allocation.
  3072. Binds specified buffer to region of memory represented by specified allocation.
  3073. Gets `VkDeviceMemory` handle and offset from the allocation.
  3074. If you want to create a buffer, allocate memory for it and bind them together separately,
  3075. you should use this function for binding instead of standard `vkBindBufferMemory()`,
  3076. because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple
  3077. allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously
  3078. (which is illegal in Vulkan).
  3079. It is recommended to use function vmaCreateBuffer() instead of this one.
  3080. */
  3081. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory(
  3082. VmaAllocator VMA_NOT_NULL allocator,
  3083. VmaAllocation VMA_NOT_NULL allocation,
  3084. VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer);
  3085. /** \brief Binds buffer to allocation with additional parameters.
  3086. @param allocationLocalOffset Additional offset to be added while binding, relative to the beginning of the `allocation`. Normally it should be 0.
  3087. @param pNext A chain of structures to be attached to `VkBindBufferMemoryInfoKHR` structure used internally. Normally it should be null.
  3088. This function is similar to vmaBindBufferMemory(), but it provides additional parameters.
  3089. If `pNext` is not null, #VmaAllocator object must have been created with #VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT flag
  3090. or with VmaAllocatorCreateInfo::vulkanApiVersion `>= VK_API_VERSION_1_1`. Otherwise the call fails.
  3091. */
  3092. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2(
  3093. VmaAllocator VMA_NOT_NULL allocator,
  3094. VmaAllocation VMA_NOT_NULL allocation,
  3095. VkDeviceSize allocationLocalOffset,
  3096. VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer,
  3097. const void* VMA_NULLABLE pNext);
  3098. /** \brief Binds image to allocation.
  3099. Binds specified image to region of memory represented by specified allocation.
  3100. Gets `VkDeviceMemory` handle and offset from the allocation.
  3101. If you want to create an image, allocate memory for it and bind them together separately,
  3102. you should use this function for binding instead of standard `vkBindImageMemory()`,
  3103. because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple
  3104. allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously
  3105. (which is illegal in Vulkan).
  3106. It is recommended to use function vmaCreateImage() instead of this one.
  3107. */
  3108. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory(
  3109. VmaAllocator VMA_NOT_NULL allocator,
  3110. VmaAllocation VMA_NOT_NULL allocation,
  3111. VkImage VMA_NOT_NULL_NON_DISPATCHABLE image);
  3112. /** \brief Binds image to allocation with additional parameters.
  3113. @param allocationLocalOffset Additional offset to be added while binding, relative to the beginning of the `allocation`. Normally it should be 0.
  3114. @param pNext A chain of structures to be attached to `VkBindImageMemoryInfoKHR` structure used internally. Normally it should be null.
  3115. This function is similar to vmaBindImageMemory(), but it provides additional parameters.
  3116. If `pNext` is not null, #VmaAllocator object must have been created with #VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT flag
  3117. or with VmaAllocatorCreateInfo::vulkanApiVersion `>= VK_API_VERSION_1_1`. Otherwise the call fails.
  3118. */
  3119. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2(
  3120. VmaAllocator VMA_NOT_NULL allocator,
  3121. VmaAllocation VMA_NOT_NULL allocation,
  3122. VkDeviceSize allocationLocalOffset,
  3123. VkImage VMA_NOT_NULL_NON_DISPATCHABLE image,
  3124. const void* VMA_NULLABLE pNext);
  3125. /**
  3126. @param[out] pBuffer Buffer that was created.
  3127. @param[out] pAllocation Allocation that was created.
  3128. @param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
  3129. This function automatically:
  3130. -# Creates buffer.
  3131. -# Allocates appropriate memory for it.
  3132. -# Binds the buffer with the memory.
  3133. If any of these operations fail, buffer and allocation are not created,
  3134. returned value is negative error code, *pBuffer and *pAllocation are null.
  3135. If the function succeeded, you must destroy both buffer and allocation when you
  3136. no longer need them using either convenience function vmaDestroyBuffer() or
  3137. separately, using `vkDestroyBuffer()` and vmaFreeMemory().
  3138. If #VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag was used,
  3139. VK_KHR_dedicated_allocation extension is used internally to query driver whether
  3140. it requires or prefers the new buffer to have dedicated allocation. If yes,
  3141. and if dedicated allocation is possible (VmaAllocationCreateInfo::pool is null
  3142. and #VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT is not used), it creates dedicated
  3143. allocation for this buffer, just like when using
  3144. #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  3145. \note This function creates a new `VkBuffer`. Sub-allocation of parts of one large buffer,
  3146. although recommended as a good practice, is out of scope of this library and could be implemented
  3147. by the user as a higher-level logic on top of VMA.
  3148. */
  3149. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer(
  3150. VmaAllocator VMA_NOT_NULL allocator,
  3151. const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo,
  3152. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  3153. VkBuffer VMA_NULLABLE_NON_DISPATCHABLE * VMA_NOT_NULL pBuffer,
  3154. VmaAllocation VMA_NULLABLE * VMA_NOT_NULL pAllocation,
  3155. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  3156. /** \brief Destroys Vulkan buffer and frees allocated memory.
  3157. This is just a convenience function equivalent to:
  3158. \code
  3159. vkDestroyBuffer(device, buffer, allocationCallbacks);
  3160. vmaFreeMemory(allocator, allocation);
  3161. \endcode
  3162. It it safe to pass null as buffer and/or allocation.
  3163. */
  3164. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer(
  3165. VmaAllocator VMA_NOT_NULL allocator,
  3166. VkBuffer VMA_NULLABLE_NON_DISPATCHABLE buffer,
  3167. VmaAllocation VMA_NULLABLE allocation);
  3168. /// Function similar to vmaCreateBuffer().
  3169. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage(
  3170. VmaAllocator VMA_NOT_NULL allocator,
  3171. const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo,
  3172. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  3173. VkImage VMA_NULLABLE_NON_DISPATCHABLE * VMA_NOT_NULL pImage,
  3174. VmaAllocation VMA_NULLABLE * VMA_NOT_NULL pAllocation,
  3175. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  3176. /** \brief Destroys Vulkan image and frees allocated memory.
  3177. This is just a convenience function equivalent to:
  3178. \code
  3179. vkDestroyImage(device, image, allocationCallbacks);
  3180. vmaFreeMemory(allocator, allocation);
  3181. \endcode
  3182. It it safe to pass null as image and/or allocation.
  3183. */
  3184. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyImage(
  3185. VmaAllocator VMA_NOT_NULL allocator,
  3186. VkImage VMA_NULLABLE_NON_DISPATCHABLE image,
  3187. VmaAllocation VMA_NULLABLE allocation);
  3188. #ifdef __cplusplus
  3189. }
  3190. #endif
  3191. #endif // AMD_VULKAN_MEMORY_ALLOCATOR_H
  3192. // For Visual Studio IntelliSense.
  3193. #if defined(__cplusplus) && defined(__INTELLISENSE__)
  3194. #define VMA_IMPLEMENTATION
  3195. #endif
  3196. #ifdef VMA_IMPLEMENTATION
  3197. #undef VMA_IMPLEMENTATION
  3198. #include <cstdint>
  3199. #include <cstdlib>
  3200. #include <cstring>
  3201. #include <utility>
  3202. #if VMA_RECORDING_ENABLED
  3203. #include <chrono>
  3204. #if defined(_WIN32)
  3205. #include <windows.h>
  3206. #else
  3207. #include <sstream>
  3208. #include <thread>
  3209. #endif
  3210. #endif
  3211. /*******************************************************************************
  3212. CONFIGURATION SECTION
  3213. Define some of these macros before each #include of this header or change them
  3214. here if you need other then default behavior depending on your environment.
  3215. */
  3216. /*
  3217. Define this macro to 1 to make the library fetch pointers to Vulkan functions
  3218. internally, like:
  3219. vulkanFunctions.vkAllocateMemory = &vkAllocateMemory;
  3220. */
  3221. #if !defined(VMA_STATIC_VULKAN_FUNCTIONS) && !defined(VK_NO_PROTOTYPES)
  3222. #define VMA_STATIC_VULKAN_FUNCTIONS 1
  3223. #endif
  3224. /*
  3225. Define this macro to 1 to make the library fetch pointers to Vulkan functions
  3226. internally, like:
  3227. vulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkGetDeviceProcAddr(m_hDevice, vkAllocateMemory);
  3228. */
  3229. #if !defined(VMA_DYNAMIC_VULKAN_FUNCTIONS)
  3230. #define VMA_DYNAMIC_VULKAN_FUNCTIONS 1
  3231. #if defined(VK_NO_PROTOTYPES)
  3232. extern PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr;
  3233. extern PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr;
  3234. #endif
  3235. #endif
  3236. // Define this macro to 1 to make the library use STL containers instead of its own implementation.
  3237. //#define VMA_USE_STL_CONTAINERS 1
  3238. /* Set this macro to 1 to make the library including and using STL containers:
  3239. std::pair, std::vector, std::list, std::unordered_map.
  3240. Set it to 0 or undefined to make the library using its own implementation of
  3241. the containers.
  3242. */
  3243. #if VMA_USE_STL_CONTAINERS
  3244. #define VMA_USE_STL_VECTOR 1
  3245. #define VMA_USE_STL_UNORDERED_MAP 1
  3246. #define VMA_USE_STL_LIST 1
  3247. #endif
  3248. #ifndef VMA_USE_STL_SHARED_MUTEX
  3249. // Compiler conforms to C++17.
  3250. #if __cplusplus >= 201703L
  3251. #define VMA_USE_STL_SHARED_MUTEX 1
  3252. // Visual studio defines __cplusplus properly only when passed additional parameter: /Zc:__cplusplus
  3253. // Otherwise it's always 199711L, despite shared_mutex works since Visual Studio 2015 Update 2.
  3254. // See: https://blogs.msdn.microsoft.com/vcblog/2018/04/09/msvc-now-correctly-reports-__cplusplus/
  3255. #elif defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 190023918 && __cplusplus == 199711L && _MSVC_LANG >= 201703L
  3256. #define VMA_USE_STL_SHARED_MUTEX 1
  3257. #else
  3258. #define VMA_USE_STL_SHARED_MUTEX 0
  3259. #endif
  3260. #endif
  3261. /*
  3262. THESE INCLUDES ARE NOT ENABLED BY DEFAULT.
  3263. Library has its own container implementation.
  3264. */
  3265. #if VMA_USE_STL_VECTOR
  3266. #include <vector>
  3267. #endif
  3268. #if VMA_USE_STL_UNORDERED_MAP
  3269. #include <unordered_map>
  3270. #endif
  3271. #if VMA_USE_STL_LIST
  3272. #include <list>
  3273. #endif
  3274. /*
  3275. Following headers are used in this CONFIGURATION section only, so feel free to
  3276. remove them if not needed.
  3277. */
  3278. #include <cassert> // for assert
  3279. #include <algorithm> // for min, max
  3280. #include <mutex>
  3281. #ifndef VMA_NULL
  3282. // Value used as null pointer. Define it to e.g.: nullptr, NULL, 0, (void*)0.
  3283. #define VMA_NULL nullptr
  3284. #endif
  3285. #if defined(__ANDROID_API__) && (__ANDROID_API__ < 16)
  3286. #include <cstdlib>
  3287. static void* vma_aligned_alloc(size_t alignment, size_t size)
  3288. {
  3289. // alignment must be >= sizeof(void*)
  3290. if(alignment < sizeof(void*))
  3291. {
  3292. alignment = sizeof(void*);
  3293. }
  3294. return memalign(alignment, size);
  3295. }
  3296. #elif defined(__APPLE__) || defined(__ANDROID__) || (defined(__linux__) && defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC))
  3297. #include <cstdlib>
  3298. #if defined(__APPLE__)
  3299. #include <AvailabilityMacros.h>
  3300. #endif
  3301. static void* vma_aligned_alloc(size_t alignment, size_t size)
  3302. {
  3303. #if defined(__APPLE__) && (defined(MAC_OS_X_VERSION_10_16) || defined(__IPHONE_14_0))
  3304. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_16 || __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0
  3305. // For C++14, usr/include/malloc/_malloc.h declares aligned_alloc()) only
  3306. // with the MacOSX11.0 SDK in Xcode 12 (which is what adds
  3307. // MAC_OS_X_VERSION_10_16), even though the function is marked
  3308. // availabe for 10.15. That's why the preprocessor checks for 10.16 but
  3309. // the __builtin_available checks for 10.15.
  3310. // People who use C++17 could call aligned_alloc with the 10.15 SDK already.
  3311. if (__builtin_available(macOS 10.15, iOS 13, *))
  3312. return aligned_alloc(alignment, size);
  3313. #endif
  3314. #endif
  3315. // alignment must be >= sizeof(void*)
  3316. if(alignment < sizeof(void*))
  3317. {
  3318. alignment = sizeof(void*);
  3319. }
  3320. void *pointer;
  3321. if(posix_memalign(&pointer, alignment, size) == 0)
  3322. return pointer;
  3323. return VMA_NULL;
  3324. }
  3325. #elif defined(_WIN32)
  3326. static void* vma_aligned_alloc(size_t alignment, size_t size)
  3327. {
  3328. return _aligned_malloc(size, alignment);
  3329. }
  3330. #else
  3331. static void* vma_aligned_alloc(size_t alignment, size_t size)
  3332. {
  3333. return aligned_alloc(alignment, size);
  3334. }
  3335. #endif
  3336. #if defined(_WIN32)
  3337. static void vma_aligned_free(void* ptr)
  3338. {
  3339. _aligned_free(ptr);
  3340. }
  3341. #else
  3342. static void vma_aligned_free(void* VMA_NULLABLE ptr)
  3343. {
  3344. free(ptr);
  3345. }
  3346. #endif
  3347. // If your compiler is not compatible with C++11 and definition of
  3348. // aligned_alloc() function is missing, uncommeting following line may help:
  3349. //#include <malloc.h>
  3350. // Normal assert to check for programmer's errors, especially in Debug configuration.
  3351. #ifndef VMA_ASSERT
  3352. #ifdef NDEBUG
  3353. #define VMA_ASSERT(expr)
  3354. #else
  3355. #define VMA_ASSERT(expr) assert(expr)
  3356. #endif
  3357. #endif
  3358. // Assert that will be called very often, like inside data structures e.g. operator[].
  3359. // Making it non-empty can make program slow.
  3360. #ifndef VMA_HEAVY_ASSERT
  3361. #ifdef NDEBUG
  3362. #define VMA_HEAVY_ASSERT(expr)
  3363. #else
  3364. #define VMA_HEAVY_ASSERT(expr) //VMA_ASSERT(expr)
  3365. #endif
  3366. #endif
  3367. #ifndef VMA_ALIGN_OF
  3368. #define VMA_ALIGN_OF(type) (__alignof(type))
  3369. #endif
  3370. #ifndef VMA_SYSTEM_ALIGNED_MALLOC
  3371. #define VMA_SYSTEM_ALIGNED_MALLOC(size, alignment) vma_aligned_alloc((alignment), (size))
  3372. #endif
  3373. #ifndef VMA_SYSTEM_ALIGNED_FREE
  3374. // VMA_SYSTEM_FREE is the old name, but might have been defined by the user
  3375. #if defined(VMA_SYSTEM_FREE)
  3376. #define VMA_SYSTEM_ALIGNED_FREE(ptr) VMA_SYSTEM_FREE(ptr)
  3377. #else
  3378. #define VMA_SYSTEM_ALIGNED_FREE(ptr) vma_aligned_free(ptr)
  3379. #endif
  3380. #endif
  3381. #ifndef VMA_MIN
  3382. #define VMA_MIN(v1, v2) (std::min((v1), (v2)))
  3383. #endif
  3384. #ifndef VMA_MAX
  3385. #define VMA_MAX(v1, v2) (std::max((v1), (v2)))
  3386. #endif
  3387. #ifndef VMA_SWAP
  3388. #define VMA_SWAP(v1, v2) std::swap((v1), (v2))
  3389. #endif
  3390. #ifndef VMA_SORT
  3391. #define VMA_SORT(beg, end, cmp) std::sort(beg, end, cmp)
  3392. #endif
  3393. #ifndef VMA_DEBUG_LOG
  3394. #define VMA_DEBUG_LOG(format, ...)
  3395. /*
  3396. #define VMA_DEBUG_LOG(format, ...) do { \
  3397. printf(format, __VA_ARGS__); \
  3398. printf("\n"); \
  3399. } while(false)
  3400. */
  3401. #endif
  3402. // Define this macro to 1 to enable functions: vmaBuildStatsString, vmaFreeStatsString.
  3403. #if VMA_STATS_STRING_ENABLED
  3404. static inline void VmaUint32ToStr(char* VMA_NOT_NULL outStr, size_t strLen, uint32_t num)
  3405. {
  3406. snprintf(outStr, strLen, "%u", static_cast<unsigned int>(num));
  3407. }
  3408. static inline void VmaUint64ToStr(char* VMA_NOT_NULL outStr, size_t strLen, uint64_t num)
  3409. {
  3410. snprintf(outStr, strLen, "%llu", static_cast<unsigned long long>(num));
  3411. }
  3412. static inline void VmaPtrToStr(char* VMA_NOT_NULL outStr, size_t strLen, const void* ptr)
  3413. {
  3414. snprintf(outStr, strLen, "%p", ptr);
  3415. }
  3416. #endif
  3417. #ifndef VMA_MUTEX
  3418. class VmaMutex
  3419. {
  3420. public:
  3421. void Lock() { m_Mutex.lock(); }
  3422. void Unlock() { m_Mutex.unlock(); }
  3423. bool TryLock() { return m_Mutex.try_lock(); }
  3424. private:
  3425. std::mutex m_Mutex;
  3426. };
  3427. #define VMA_MUTEX VmaMutex
  3428. #endif
  3429. // Read-write mutex, where "read" is shared access, "write" is exclusive access.
  3430. #ifndef VMA_RW_MUTEX
  3431. #if VMA_USE_STL_SHARED_MUTEX
  3432. // Use std::shared_mutex from C++17.
  3433. #include <shared_mutex>
  3434. class VmaRWMutex
  3435. {
  3436. public:
  3437. void LockRead() { m_Mutex.lock_shared(); }
  3438. void UnlockRead() { m_Mutex.unlock_shared(); }
  3439. bool TryLockRead() { return m_Mutex.try_lock_shared(); }
  3440. void LockWrite() { m_Mutex.lock(); }
  3441. void UnlockWrite() { m_Mutex.unlock(); }
  3442. bool TryLockWrite() { return m_Mutex.try_lock(); }
  3443. private:
  3444. std::shared_mutex m_Mutex;
  3445. };
  3446. #define VMA_RW_MUTEX VmaRWMutex
  3447. #elif defined(_WIN32) && defined(WINVER) && WINVER >= 0x0600
  3448. // Use SRWLOCK from WinAPI.
  3449. // Minimum supported client = Windows Vista, server = Windows Server 2008.
  3450. class VmaRWMutex
  3451. {
  3452. public:
  3453. VmaRWMutex() { InitializeSRWLock(&m_Lock); }
  3454. void LockRead() { AcquireSRWLockShared(&m_Lock); }
  3455. void UnlockRead() { ReleaseSRWLockShared(&m_Lock); }
  3456. bool TryLockRead() { return TryAcquireSRWLockShared(&m_Lock) != FALSE; }
  3457. void LockWrite() { AcquireSRWLockExclusive(&m_Lock); }
  3458. void UnlockWrite() { ReleaseSRWLockExclusive(&m_Lock); }
  3459. bool TryLockWrite() { return TryAcquireSRWLockExclusive(&m_Lock) != FALSE; }
  3460. private:
  3461. SRWLOCK m_Lock;
  3462. };
  3463. #define VMA_RW_MUTEX VmaRWMutex
  3464. #else
  3465. // Less efficient fallback: Use normal mutex.
  3466. class VmaRWMutex
  3467. {
  3468. public:
  3469. void LockRead() { m_Mutex.Lock(); }
  3470. void UnlockRead() { m_Mutex.Unlock(); }
  3471. bool TryLockRead() { return m_Mutex.TryLock(); }
  3472. void LockWrite() { m_Mutex.Lock(); }
  3473. void UnlockWrite() { m_Mutex.Unlock(); }
  3474. bool TryLockWrite() { return m_Mutex.TryLock(); }
  3475. private:
  3476. VMA_MUTEX m_Mutex;
  3477. };
  3478. #define VMA_RW_MUTEX VmaRWMutex
  3479. #endif // #if VMA_USE_STL_SHARED_MUTEX
  3480. #endif // #ifndef VMA_RW_MUTEX
  3481. /*
  3482. If providing your own implementation, you need to implement a subset of std::atomic.
  3483. */
  3484. #ifndef VMA_ATOMIC_UINT32
  3485. #include <atomic>
  3486. #define VMA_ATOMIC_UINT32 std::atomic<uint32_t>
  3487. #endif
  3488. #ifndef VMA_ATOMIC_UINT64
  3489. #include <atomic>
  3490. #define VMA_ATOMIC_UINT64 std::atomic<uint64_t>
  3491. #endif
  3492. #ifndef VMA_DEBUG_ALWAYS_DEDICATED_MEMORY
  3493. /**
  3494. Every allocation will have its own memory block.
  3495. Define to 1 for debugging purposes only.
  3496. */
  3497. #define VMA_DEBUG_ALWAYS_DEDICATED_MEMORY (0)
  3498. #endif
  3499. #ifndef VMA_MIN_ALIGNMENT
  3500. /**
  3501. Minimum alignment of all allocations, in bytes.
  3502. Set to more than 1 for debugging purposes. Must be power of two.
  3503. */
  3504. #ifdef VMA_DEBUG_ALIGNMENT // Old name
  3505. #define VMA_MIN_ALIGNMENT VMA_DEBUG_ALIGNMENT
  3506. #else
  3507. #define VMA_MIN_ALIGNMENT (1)
  3508. #endif
  3509. #endif
  3510. #ifndef VMA_DEBUG_MARGIN
  3511. /**
  3512. Minimum margin before and after every allocation, in bytes.
  3513. Set nonzero for debugging purposes only.
  3514. */
  3515. #define VMA_DEBUG_MARGIN (0)
  3516. #endif
  3517. #ifndef VMA_DEBUG_INITIALIZE_ALLOCATIONS
  3518. /**
  3519. Define this macro to 1 to automatically fill new allocations and destroyed
  3520. allocations with some bit pattern.
  3521. */
  3522. #define VMA_DEBUG_INITIALIZE_ALLOCATIONS (0)
  3523. #endif
  3524. #ifndef VMA_DEBUG_DETECT_CORRUPTION
  3525. /**
  3526. Define this macro to 1 together with non-zero value of VMA_DEBUG_MARGIN to
  3527. enable writing magic value to the margin before and after every allocation and
  3528. validating it, so that memory corruptions (out-of-bounds writes) are detected.
  3529. */
  3530. #define VMA_DEBUG_DETECT_CORRUPTION (0)
  3531. #endif
  3532. #ifndef VMA_DEBUG_GLOBAL_MUTEX
  3533. /**
  3534. Set this to 1 for debugging purposes only, to enable single mutex protecting all
  3535. entry calls to the library. Can be useful for debugging multithreading issues.
  3536. */
  3537. #define VMA_DEBUG_GLOBAL_MUTEX (0)
  3538. #endif
  3539. #ifndef VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY
  3540. /**
  3541. Minimum value for VkPhysicalDeviceLimits::bufferImageGranularity.
  3542. Set to more than 1 for debugging purposes only. Must be power of two.
  3543. */
  3544. #define VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY (1)
  3545. #endif
  3546. #ifndef VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT
  3547. /*
  3548. Set this to 1 to make VMA never exceed VkPhysicalDeviceLimits::maxMemoryAllocationCount
  3549. and return error instead of leaving up to Vulkan implementation what to do in such cases.
  3550. */
  3551. #define VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT (0)
  3552. #endif
  3553. #ifndef VMA_SMALL_HEAP_MAX_SIZE
  3554. /// Maximum size of a memory heap in Vulkan to consider it "small".
  3555. #define VMA_SMALL_HEAP_MAX_SIZE (1024ull * 1024 * 1024)
  3556. #endif
  3557. #ifndef VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE
  3558. /// Default size of a block allocated as single VkDeviceMemory from a "large" heap.
  3559. #define VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE (256ull * 1024 * 1024)
  3560. #endif
  3561. #ifndef VMA_CLASS_NO_COPY
  3562. #define VMA_CLASS_NO_COPY(className) \
  3563. private: \
  3564. className(const className&) = delete; \
  3565. className& operator=(const className&) = delete;
  3566. #endif
  3567. static const uint32_t VMA_FRAME_INDEX_LOST = UINT32_MAX;
  3568. // Decimal 2139416166, float NaN, little-endian binary 66 E6 84 7F.
  3569. static const uint32_t VMA_CORRUPTION_DETECTION_MAGIC_VALUE = 0x7F84E666;
  3570. static const uint8_t VMA_ALLOCATION_FILL_PATTERN_CREATED = 0xDC;
  3571. static const uint8_t VMA_ALLOCATION_FILL_PATTERN_DESTROYED = 0xEF;
  3572. /*******************************************************************************
  3573. END OF CONFIGURATION
  3574. */
  3575. // # Copy of some Vulkan definitions so we don't need to check their existence just to handle few constants.
  3576. static const uint32_t VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY = 0x00000040;
  3577. static const uint32_t VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY = 0x00000080;
  3578. static const uint32_t VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY = 0x00020000;
  3579. static const uint32_t VMA_ALLOCATION_INTERNAL_STRATEGY_MIN_OFFSET = 0x10000000u;
  3580. static VkAllocationCallbacks VmaEmptyAllocationCallbacks = {
  3581. VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL };
  3582. // Returns number of bits set to 1 in (v).
  3583. static inline uint32_t VmaCountBitsSet(uint32_t v)
  3584. {
  3585. uint32_t c = v - ((v >> 1) & 0x55555555);
  3586. c = ((c >> 2) & 0x33333333) + (c & 0x33333333);
  3587. c = ((c >> 4) + c) & 0x0F0F0F0F;
  3588. c = ((c >> 8) + c) & 0x00FF00FF;
  3589. c = ((c >> 16) + c) & 0x0000FFFF;
  3590. return c;
  3591. }
  3592. /*
  3593. Returns true if given number is a power of two.
  3594. T must be unsigned integer number or signed integer but always nonnegative.
  3595. For 0 returns true.
  3596. */
  3597. template <typename T>
  3598. inline bool VmaIsPow2(T x)
  3599. {
  3600. return (x & (x-1)) == 0;
  3601. }
  3602. // Aligns given value up to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 16.
  3603. // Use types like uint32_t, uint64_t as T.
  3604. template <typename T>
  3605. static inline T VmaAlignUp(T val, T alignment)
  3606. {
  3607. VMA_HEAVY_ASSERT(VmaIsPow2(alignment));
  3608. return (val + alignment - 1) & ~(alignment - 1);
  3609. }
  3610. // Aligns given value down to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 8.
  3611. // Use types like uint32_t, uint64_t as T.
  3612. template <typename T>
  3613. static inline T VmaAlignDown(T val, T alignment)
  3614. {
  3615. VMA_HEAVY_ASSERT(VmaIsPow2(alignment));
  3616. return val & ~(alignment - 1);
  3617. }
  3618. // Division with mathematical rounding to nearest number.
  3619. template <typename T>
  3620. static inline T VmaRoundDiv(T x, T y)
  3621. {
  3622. return (x + (y / (T)2)) / y;
  3623. }
  3624. // Returns smallest power of 2 greater or equal to v.
  3625. static inline uint32_t VmaNextPow2(uint32_t v)
  3626. {
  3627. v--;
  3628. v |= v >> 1;
  3629. v |= v >> 2;
  3630. v |= v >> 4;
  3631. v |= v >> 8;
  3632. v |= v >> 16;
  3633. v++;
  3634. return v;
  3635. }
  3636. static inline uint64_t VmaNextPow2(uint64_t v)
  3637. {
  3638. v--;
  3639. v |= v >> 1;
  3640. v |= v >> 2;
  3641. v |= v >> 4;
  3642. v |= v >> 8;
  3643. v |= v >> 16;
  3644. v |= v >> 32;
  3645. v++;
  3646. return v;
  3647. }
  3648. // Returns largest power of 2 less or equal to v.
  3649. static inline uint32_t VmaPrevPow2(uint32_t v)
  3650. {
  3651. v |= v >> 1;
  3652. v |= v >> 2;
  3653. v |= v >> 4;
  3654. v |= v >> 8;
  3655. v |= v >> 16;
  3656. v = v ^ (v >> 1);
  3657. return v;
  3658. }
  3659. static inline uint64_t VmaPrevPow2(uint64_t v)
  3660. {
  3661. v |= v >> 1;
  3662. v |= v >> 2;
  3663. v |= v >> 4;
  3664. v |= v >> 8;
  3665. v |= v >> 16;
  3666. v |= v >> 32;
  3667. v = v ^ (v >> 1);
  3668. return v;
  3669. }
  3670. static inline bool VmaStrIsEmpty(const char* pStr)
  3671. {
  3672. return pStr == VMA_NULL || *pStr == '\0';
  3673. }
  3674. #if VMA_STATS_STRING_ENABLED
  3675. static const char* VmaAlgorithmToStr(uint32_t algorithm)
  3676. {
  3677. switch(algorithm)
  3678. {
  3679. case VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT:
  3680. return "Linear";
  3681. case VMA_POOL_CREATE_BUDDY_ALGORITHM_BIT:
  3682. return "Buddy";
  3683. case 0:
  3684. return "Default";
  3685. default:
  3686. VMA_ASSERT(0);
  3687. return "";
  3688. }
  3689. }
  3690. #endif // #if VMA_STATS_STRING_ENABLED
  3691. #ifndef VMA_SORT
  3692. template<typename Iterator, typename Compare>
  3693. Iterator VmaQuickSortPartition(Iterator beg, Iterator end, Compare cmp)
  3694. {
  3695. Iterator centerValue = end; --centerValue;
  3696. Iterator insertIndex = beg;
  3697. for(Iterator memTypeIndex = beg; memTypeIndex < centerValue; ++memTypeIndex)
  3698. {
  3699. if(cmp(*memTypeIndex, *centerValue))
  3700. {
  3701. if(insertIndex != memTypeIndex)
  3702. {
  3703. VMA_SWAP(*memTypeIndex, *insertIndex);
  3704. }
  3705. ++insertIndex;
  3706. }
  3707. }
  3708. if(insertIndex != centerValue)
  3709. {
  3710. VMA_SWAP(*insertIndex, *centerValue);
  3711. }
  3712. return insertIndex;
  3713. }
  3714. template<typename Iterator, typename Compare>
  3715. void VmaQuickSort(Iterator beg, Iterator end, Compare cmp)
  3716. {
  3717. if(beg < end)
  3718. {
  3719. Iterator it = VmaQuickSortPartition<Iterator, Compare>(beg, end, cmp);
  3720. VmaQuickSort<Iterator, Compare>(beg, it, cmp);
  3721. VmaQuickSort<Iterator, Compare>(it + 1, end, cmp);
  3722. }
  3723. }
  3724. #define VMA_SORT(beg, end, cmp) VmaQuickSort(beg, end, cmp)
  3725. #endif // #ifndef VMA_SORT
  3726. /*
  3727. Returns true if two memory blocks occupy overlapping pages.
  3728. ResourceA must be in less memory offset than ResourceB.
  3729. Algorithm is based on "Vulkan 1.0.39 - A Specification (with all registered Vulkan extensions)"
  3730. chapter 11.6 "Resource Memory Association", paragraph "Buffer-Image Granularity".
  3731. */
  3732. static inline bool VmaBlocksOnSamePage(
  3733. VkDeviceSize resourceAOffset,
  3734. VkDeviceSize resourceASize,
  3735. VkDeviceSize resourceBOffset,
  3736. VkDeviceSize pageSize)
  3737. {
  3738. VMA_ASSERT(resourceAOffset + resourceASize <= resourceBOffset && resourceASize > 0 && pageSize > 0);
  3739. VkDeviceSize resourceAEnd = resourceAOffset + resourceASize - 1;
  3740. VkDeviceSize resourceAEndPage = resourceAEnd & ~(pageSize - 1);
  3741. VkDeviceSize resourceBStart = resourceBOffset;
  3742. VkDeviceSize resourceBStartPage = resourceBStart & ~(pageSize - 1);
  3743. return resourceAEndPage == resourceBStartPage;
  3744. }
  3745. enum VmaSuballocationType
  3746. {
  3747. VMA_SUBALLOCATION_TYPE_FREE = 0,
  3748. VMA_SUBALLOCATION_TYPE_UNKNOWN = 1,
  3749. VMA_SUBALLOCATION_TYPE_BUFFER = 2,
  3750. VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN = 3,
  3751. VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR = 4,
  3752. VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL = 5,
  3753. VMA_SUBALLOCATION_TYPE_MAX_ENUM = 0x7FFFFFFF
  3754. };
  3755. /*
  3756. Returns true if given suballocation types could conflict and must respect
  3757. VkPhysicalDeviceLimits::bufferImageGranularity. They conflict if one is buffer
  3758. or linear image and another one is optimal image. If type is unknown, behave
  3759. conservatively.
  3760. */
  3761. static inline bool VmaIsBufferImageGranularityConflict(
  3762. VmaSuballocationType suballocType1,
  3763. VmaSuballocationType suballocType2)
  3764. {
  3765. if(suballocType1 > suballocType2)
  3766. {
  3767. VMA_SWAP(suballocType1, suballocType2);
  3768. }
  3769. switch(suballocType1)
  3770. {
  3771. case VMA_SUBALLOCATION_TYPE_FREE:
  3772. return false;
  3773. case VMA_SUBALLOCATION_TYPE_UNKNOWN:
  3774. return true;
  3775. case VMA_SUBALLOCATION_TYPE_BUFFER:
  3776. return
  3777. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
  3778. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
  3779. case VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN:
  3780. return
  3781. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
  3782. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR ||
  3783. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
  3784. case VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR:
  3785. return
  3786. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
  3787. case VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL:
  3788. return false;
  3789. default:
  3790. VMA_ASSERT(0);
  3791. return true;
  3792. }
  3793. }
  3794. static void VmaWriteMagicValue(void* pData, VkDeviceSize offset)
  3795. {
  3796. #if VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_DETECT_CORRUPTION
  3797. uint32_t* pDst = (uint32_t*)((char*)pData + offset);
  3798. const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t);
  3799. for(size_t i = 0; i < numberCount; ++i, ++pDst)
  3800. {
  3801. *pDst = VMA_CORRUPTION_DETECTION_MAGIC_VALUE;
  3802. }
  3803. #else
  3804. // no-op
  3805. #endif
  3806. }
  3807. static bool VmaValidateMagicValue(const void* pData, VkDeviceSize offset)
  3808. {
  3809. #if VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_DETECT_CORRUPTION
  3810. const uint32_t* pSrc = (const uint32_t*)((const char*)pData + offset);
  3811. const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t);
  3812. for(size_t i = 0; i < numberCount; ++i, ++pSrc)
  3813. {
  3814. if(*pSrc != VMA_CORRUPTION_DETECTION_MAGIC_VALUE)
  3815. {
  3816. return false;
  3817. }
  3818. }
  3819. #endif
  3820. return true;
  3821. }
  3822. /*
  3823. Fills structure with parameters of an example buffer to be used for transfers
  3824. during GPU memory defragmentation.
  3825. */
  3826. static void VmaFillGpuDefragmentationBufferCreateInfo(VkBufferCreateInfo& outBufCreateInfo)
  3827. {
  3828. memset(&outBufCreateInfo, 0, sizeof(outBufCreateInfo));
  3829. outBufCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  3830. outBufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  3831. outBufCreateInfo.size = (VkDeviceSize)VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE; // Example size.
  3832. }
  3833. // Helper RAII class to lock a mutex in constructor and unlock it in destructor (at the end of scope).
  3834. struct VmaMutexLock
  3835. {
  3836. VMA_CLASS_NO_COPY(VmaMutexLock)
  3837. public:
  3838. VmaMutexLock(VMA_MUTEX& mutex, bool useMutex = true) :
  3839. m_pMutex(useMutex ? &mutex : VMA_NULL)
  3840. { if(m_pMutex) { m_pMutex->Lock(); } }
  3841. ~VmaMutexLock()
  3842. { if(m_pMutex) { m_pMutex->Unlock(); } }
  3843. private:
  3844. VMA_MUTEX* m_pMutex;
  3845. };
  3846. // Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for reading.
  3847. struct VmaMutexLockRead
  3848. {
  3849. VMA_CLASS_NO_COPY(VmaMutexLockRead)
  3850. public:
  3851. VmaMutexLockRead(VMA_RW_MUTEX& mutex, bool useMutex) :
  3852. m_pMutex(useMutex ? &mutex : VMA_NULL)
  3853. { if(m_pMutex) { m_pMutex->LockRead(); } }
  3854. ~VmaMutexLockRead() { if(m_pMutex) { m_pMutex->UnlockRead(); } }
  3855. private:
  3856. VMA_RW_MUTEX* m_pMutex;
  3857. };
  3858. // Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for writing.
  3859. struct VmaMutexLockWrite
  3860. {
  3861. VMA_CLASS_NO_COPY(VmaMutexLockWrite)
  3862. public:
  3863. VmaMutexLockWrite(VMA_RW_MUTEX& mutex, bool useMutex) :
  3864. m_pMutex(useMutex ? &mutex : VMA_NULL)
  3865. { if(m_pMutex) { m_pMutex->LockWrite(); } }
  3866. ~VmaMutexLockWrite() { if(m_pMutex) { m_pMutex->UnlockWrite(); } }
  3867. private:
  3868. VMA_RW_MUTEX* m_pMutex;
  3869. };
  3870. #if VMA_DEBUG_GLOBAL_MUTEX
  3871. static VMA_MUTEX gDebugGlobalMutex;
  3872. #define VMA_DEBUG_GLOBAL_MUTEX_LOCK VmaMutexLock debugGlobalMutexLock(gDebugGlobalMutex, true);
  3873. #else
  3874. #define VMA_DEBUG_GLOBAL_MUTEX_LOCK
  3875. #endif
  3876. // Minimum size of a free suballocation to register it in the free suballocation collection.
  3877. static const VkDeviceSize VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER = 16;
  3878. /*
  3879. Performs binary search and returns iterator to first element that is greater or
  3880. equal to (key), according to comparison (cmp).
  3881. Cmp should return true if first argument is less than second argument.
  3882. Returned value is the found element, if present in the collection or place where
  3883. new element with value (key) should be inserted.
  3884. */
  3885. template <typename CmpLess, typename IterT, typename KeyT>
  3886. static IterT VmaBinaryFindFirstNotLess(IterT beg, IterT end, const KeyT &key, const CmpLess& cmp)
  3887. {
  3888. size_t down = 0, up = (end - beg);
  3889. while(down < up)
  3890. {
  3891. const size_t mid = down + (up - down) / 2; // Overflow-safe midpoint calculation
  3892. if(cmp(*(beg+mid), key))
  3893. {
  3894. down = mid + 1;
  3895. }
  3896. else
  3897. {
  3898. up = mid;
  3899. }
  3900. }
  3901. return beg + down;
  3902. }
  3903. template<typename CmpLess, typename IterT, typename KeyT>
  3904. IterT VmaBinaryFindSorted(const IterT& beg, const IterT& end, const KeyT& value, const CmpLess& cmp)
  3905. {
  3906. IterT it = VmaBinaryFindFirstNotLess<CmpLess, IterT, KeyT>(
  3907. beg, end, value, cmp);
  3908. if(it == end ||
  3909. (!cmp(*it, value) && !cmp(value, *it)))
  3910. {
  3911. return it;
  3912. }
  3913. return end;
  3914. }
  3915. /*
  3916. Returns true if all pointers in the array are not-null and unique.
  3917. Warning! O(n^2) complexity. Use only inside VMA_HEAVY_ASSERT.
  3918. T must be pointer type, e.g. VmaAllocation, VmaPool.
  3919. */
  3920. template<typename T>
  3921. static bool VmaValidatePointerArray(uint32_t count, const T* arr)
  3922. {
  3923. for(uint32_t i = 0; i < count; ++i)
  3924. {
  3925. const T iPtr = arr[i];
  3926. if(iPtr == VMA_NULL)
  3927. {
  3928. return false;
  3929. }
  3930. for(uint32_t j = i + 1; j < count; ++j)
  3931. {
  3932. if(iPtr == arr[j])
  3933. {
  3934. return false;
  3935. }
  3936. }
  3937. }
  3938. return true;
  3939. }
  3940. template<typename MainT, typename NewT>
  3941. static inline void VmaPnextChainPushFront(MainT* mainStruct, NewT* newStruct)
  3942. {
  3943. newStruct->pNext = mainStruct->pNext;
  3944. mainStruct->pNext = newStruct;
  3945. }
  3946. ////////////////////////////////////////////////////////////////////////////////
  3947. // Memory allocation
  3948. static void* VmaMalloc(const VkAllocationCallbacks* pAllocationCallbacks, size_t size, size_t alignment)
  3949. {
  3950. void* result = VMA_NULL;
  3951. if((pAllocationCallbacks != VMA_NULL) &&
  3952. (pAllocationCallbacks->pfnAllocation != VMA_NULL))
  3953. {
  3954. result = (*pAllocationCallbacks->pfnAllocation)(
  3955. pAllocationCallbacks->pUserData,
  3956. size,
  3957. alignment,
  3958. VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
  3959. }
  3960. else
  3961. {
  3962. result = VMA_SYSTEM_ALIGNED_MALLOC(size, alignment);
  3963. }
  3964. VMA_ASSERT(result != VMA_NULL && "CPU memory allocation failed.");
  3965. return result;
  3966. }
  3967. static void VmaFree(const VkAllocationCallbacks* pAllocationCallbacks, void* ptr)
  3968. {
  3969. if((pAllocationCallbacks != VMA_NULL) &&
  3970. (pAllocationCallbacks->pfnFree != VMA_NULL))
  3971. {
  3972. (*pAllocationCallbacks->pfnFree)(pAllocationCallbacks->pUserData, ptr);
  3973. }
  3974. else
  3975. {
  3976. VMA_SYSTEM_ALIGNED_FREE(ptr);
  3977. }
  3978. }
  3979. template<typename T>
  3980. static T* VmaAllocate(const VkAllocationCallbacks* pAllocationCallbacks)
  3981. {
  3982. return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T), VMA_ALIGN_OF(T));
  3983. }
  3984. template<typename T>
  3985. static T* VmaAllocateArray(const VkAllocationCallbacks* pAllocationCallbacks, size_t count)
  3986. {
  3987. return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T) * count, VMA_ALIGN_OF(T));
  3988. }
  3989. #define vma_new(allocator, type) new(VmaAllocate<type>(allocator))(type)
  3990. #define vma_new_array(allocator, type, count) new(VmaAllocateArray<type>((allocator), (count)))(type)
  3991. template<typename T>
  3992. static void vma_delete(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr)
  3993. {
  3994. ptr->~T();
  3995. VmaFree(pAllocationCallbacks, ptr);
  3996. }
  3997. template<typename T>
  3998. static void vma_delete_array(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr, size_t count)
  3999. {
  4000. if(ptr != VMA_NULL)
  4001. {
  4002. for(size_t i = count; i--; )
  4003. {
  4004. ptr[i].~T();
  4005. }
  4006. VmaFree(pAllocationCallbacks, ptr);
  4007. }
  4008. }
  4009. static char* VmaCreateStringCopy(const VkAllocationCallbacks* allocs, const char* srcStr)
  4010. {
  4011. if(srcStr != VMA_NULL)
  4012. {
  4013. const size_t len = strlen(srcStr);
  4014. char* const result = vma_new_array(allocs, char, len + 1);
  4015. memcpy(result, srcStr, len + 1);
  4016. return result;
  4017. }
  4018. else
  4019. {
  4020. return VMA_NULL;
  4021. }
  4022. }
  4023. static void VmaFreeString(const VkAllocationCallbacks* allocs, char* str)
  4024. {
  4025. if(str != VMA_NULL)
  4026. {
  4027. const size_t len = strlen(str);
  4028. vma_delete_array(allocs, str, len + 1);
  4029. }
  4030. }
  4031. // STL-compatible allocator.
  4032. template<typename T>
  4033. class VmaStlAllocator
  4034. {
  4035. public:
  4036. const VkAllocationCallbacks* const m_pCallbacks;
  4037. typedef T value_type;
  4038. VmaStlAllocator(const VkAllocationCallbacks* pCallbacks) : m_pCallbacks(pCallbacks) { }
  4039. template<typename U> VmaStlAllocator(const VmaStlAllocator<U>& src) : m_pCallbacks(src.m_pCallbacks) { }
  4040. T* allocate(size_t n) { return VmaAllocateArray<T>(m_pCallbacks, n); }
  4041. void deallocate(T* p, size_t n) { VmaFree(m_pCallbacks, p); }
  4042. template<typename U>
  4043. bool operator==(const VmaStlAllocator<U>& rhs) const
  4044. {
  4045. return m_pCallbacks == rhs.m_pCallbacks;
  4046. }
  4047. template<typename U>
  4048. bool operator!=(const VmaStlAllocator<U>& rhs) const
  4049. {
  4050. return m_pCallbacks != rhs.m_pCallbacks;
  4051. }
  4052. VmaStlAllocator& operator=(const VmaStlAllocator& x) = delete;
  4053. VmaStlAllocator(const VmaStlAllocator&) = default;
  4054. };
  4055. #if VMA_USE_STL_VECTOR
  4056. #define VmaVector std::vector
  4057. template<typename T, typename allocatorT>
  4058. static void VmaVectorInsert(std::vector<T, allocatorT>& vec, size_t index, const T& item)
  4059. {
  4060. vec.insert(vec.begin() + index, item);
  4061. }
  4062. template<typename T, typename allocatorT>
  4063. static void VmaVectorRemove(std::vector<T, allocatorT>& vec, size_t index)
  4064. {
  4065. vec.erase(vec.begin() + index);
  4066. }
  4067. #else // #if VMA_USE_STL_VECTOR
  4068. /* Class with interface compatible with subset of std::vector.
  4069. T must be POD because constructors and destructors are not called and memcpy is
  4070. used for these objects. */
  4071. template<typename T, typename AllocatorT>
  4072. class VmaVector
  4073. {
  4074. public:
  4075. typedef T value_type;
  4076. VmaVector(const AllocatorT& allocator) :
  4077. m_Allocator(allocator),
  4078. m_pArray(VMA_NULL),
  4079. m_Count(0),
  4080. m_Capacity(0)
  4081. {
  4082. }
  4083. VmaVector(size_t count, const AllocatorT& allocator) :
  4084. m_Allocator(allocator),
  4085. m_pArray(count ? (T*)VmaAllocateArray<T>(allocator.m_pCallbacks, count) : VMA_NULL),
  4086. m_Count(count),
  4087. m_Capacity(count)
  4088. {
  4089. }
  4090. // This version of the constructor is here for compatibility with pre-C++14 std::vector.
  4091. // value is unused.
  4092. VmaVector(size_t count, const T& value, const AllocatorT& allocator)
  4093. : VmaVector(count, allocator) {}
  4094. VmaVector(const VmaVector<T, AllocatorT>& src) :
  4095. m_Allocator(src.m_Allocator),
  4096. m_pArray(src.m_Count ? (T*)VmaAllocateArray<T>(src.m_Allocator.m_pCallbacks, src.m_Count) : VMA_NULL),
  4097. m_Count(src.m_Count),
  4098. m_Capacity(src.m_Count)
  4099. {
  4100. if(m_Count != 0)
  4101. {
  4102. memcpy(m_pArray, src.m_pArray, m_Count * sizeof(T));
  4103. }
  4104. }
  4105. ~VmaVector()
  4106. {
  4107. VmaFree(m_Allocator.m_pCallbacks, m_pArray);
  4108. }
  4109. VmaVector& operator=(const VmaVector<T, AllocatorT>& rhs)
  4110. {
  4111. if(&rhs != this)
  4112. {
  4113. resize(rhs.m_Count);
  4114. if(m_Count != 0)
  4115. {
  4116. memcpy(m_pArray, rhs.m_pArray, m_Count * sizeof(T));
  4117. }
  4118. }
  4119. return *this;
  4120. }
  4121. bool empty() const { return m_Count == 0; }
  4122. size_t size() const { return m_Count; }
  4123. T* data() { return m_pArray; }
  4124. const T* data() const { return m_pArray; }
  4125. T& operator[](size_t index)
  4126. {
  4127. VMA_HEAVY_ASSERT(index < m_Count);
  4128. return m_pArray[index];
  4129. }
  4130. const T& operator[](size_t index) const
  4131. {
  4132. VMA_HEAVY_ASSERT(index < m_Count);
  4133. return m_pArray[index];
  4134. }
  4135. T& front()
  4136. {
  4137. VMA_HEAVY_ASSERT(m_Count > 0);
  4138. return m_pArray[0];
  4139. }
  4140. const T& front() const
  4141. {
  4142. VMA_HEAVY_ASSERT(m_Count > 0);
  4143. return m_pArray[0];
  4144. }
  4145. T& back()
  4146. {
  4147. VMA_HEAVY_ASSERT(m_Count > 0);
  4148. return m_pArray[m_Count - 1];
  4149. }
  4150. const T& back() const
  4151. {
  4152. VMA_HEAVY_ASSERT(m_Count > 0);
  4153. return m_pArray[m_Count - 1];
  4154. }
  4155. void reserve(size_t newCapacity, bool freeMemory = false)
  4156. {
  4157. newCapacity = VMA_MAX(newCapacity, m_Count);
  4158. if((newCapacity < m_Capacity) && !freeMemory)
  4159. {
  4160. newCapacity = m_Capacity;
  4161. }
  4162. if(newCapacity != m_Capacity)
  4163. {
  4164. T* const newArray = newCapacity ? VmaAllocateArray<T>(m_Allocator, newCapacity) : VMA_NULL;
  4165. if(m_Count != 0)
  4166. {
  4167. memcpy(newArray, m_pArray, m_Count * sizeof(T));
  4168. }
  4169. VmaFree(m_Allocator.m_pCallbacks, m_pArray);
  4170. m_Capacity = newCapacity;
  4171. m_pArray = newArray;
  4172. }
  4173. }
  4174. void resize(size_t newCount)
  4175. {
  4176. size_t newCapacity = m_Capacity;
  4177. if(newCount > m_Capacity)
  4178. {
  4179. newCapacity = VMA_MAX(newCount, VMA_MAX(m_Capacity * 3 / 2, (size_t)8));
  4180. }
  4181. if(newCapacity != m_Capacity)
  4182. {
  4183. T* const newArray = newCapacity ? VmaAllocateArray<T>(m_Allocator.m_pCallbacks, newCapacity) : VMA_NULL;
  4184. const size_t elementsToCopy = VMA_MIN(m_Count, newCount);
  4185. if(elementsToCopy != 0)
  4186. {
  4187. memcpy(newArray, m_pArray, elementsToCopy * sizeof(T));
  4188. }
  4189. VmaFree(m_Allocator.m_pCallbacks, m_pArray);
  4190. m_Capacity = newCapacity;
  4191. m_pArray = newArray;
  4192. }
  4193. m_Count = newCount;
  4194. }
  4195. void clear()
  4196. {
  4197. resize(0);
  4198. }
  4199. void shrink_to_fit()
  4200. {
  4201. if(m_Capacity > m_Count)
  4202. {
  4203. T* newArray = VMA_NULL;
  4204. if(m_Count > 0)
  4205. {
  4206. newArray = VmaAllocateArray<T>(m_Allocator.m_pCallbacks, m_Count);
  4207. memcpy(newArray, m_pArray, m_Count * sizeof(T));
  4208. }
  4209. VmaFree(m_Allocator.m_pCallbacks, m_pArray);
  4210. m_Capacity = m_Count;
  4211. m_pArray = newArray;
  4212. }
  4213. }
  4214. void insert(size_t index, const T& src)
  4215. {
  4216. VMA_HEAVY_ASSERT(index <= m_Count);
  4217. const size_t oldCount = size();
  4218. resize(oldCount + 1);
  4219. if(index < oldCount)
  4220. {
  4221. memmove(m_pArray + (index + 1), m_pArray + index, (oldCount - index) * sizeof(T));
  4222. }
  4223. m_pArray[index] = src;
  4224. }
  4225. void remove(size_t index)
  4226. {
  4227. VMA_HEAVY_ASSERT(index < m_Count);
  4228. const size_t oldCount = size();
  4229. if(index < oldCount - 1)
  4230. {
  4231. memmove(m_pArray + index, m_pArray + (index + 1), (oldCount - index - 1) * sizeof(T));
  4232. }
  4233. resize(oldCount - 1);
  4234. }
  4235. void push_back(const T& src)
  4236. {
  4237. const size_t newIndex = size();
  4238. resize(newIndex + 1);
  4239. m_pArray[newIndex] = src;
  4240. }
  4241. void pop_back()
  4242. {
  4243. VMA_HEAVY_ASSERT(m_Count > 0);
  4244. resize(size() - 1);
  4245. }
  4246. void push_front(const T& src)
  4247. {
  4248. insert(0, src);
  4249. }
  4250. void pop_front()
  4251. {
  4252. VMA_HEAVY_ASSERT(m_Count > 0);
  4253. remove(0);
  4254. }
  4255. typedef T* iterator;
  4256. typedef const T* const_iterator;
  4257. iterator begin() { return m_pArray; }
  4258. iterator end() { return m_pArray + m_Count; }
  4259. const_iterator cbegin() const { return m_pArray; }
  4260. const_iterator cend() const { return m_pArray + m_Count; }
  4261. const_iterator begin() const { return cbegin(); }
  4262. const_iterator end() const { return cend(); }
  4263. private:
  4264. AllocatorT m_Allocator;
  4265. T* m_pArray;
  4266. size_t m_Count;
  4267. size_t m_Capacity;
  4268. };
  4269. template<typename T, typename allocatorT>
  4270. static void VmaVectorInsert(VmaVector<T, allocatorT>& vec, size_t index, const T& item)
  4271. {
  4272. vec.insert(index, item);
  4273. }
  4274. template<typename T, typename allocatorT>
  4275. static void VmaVectorRemove(VmaVector<T, allocatorT>& vec, size_t index)
  4276. {
  4277. vec.remove(index);
  4278. }
  4279. #endif // #if VMA_USE_STL_VECTOR
  4280. template<typename CmpLess, typename VectorT>
  4281. size_t VmaVectorInsertSorted(VectorT& vector, const typename VectorT::value_type& value)
  4282. {
  4283. const size_t indexToInsert = VmaBinaryFindFirstNotLess(
  4284. vector.data(),
  4285. vector.data() + vector.size(),
  4286. value,
  4287. CmpLess()) - vector.data();
  4288. VmaVectorInsert(vector, indexToInsert, value);
  4289. return indexToInsert;
  4290. }
  4291. template<typename CmpLess, typename VectorT>
  4292. bool VmaVectorRemoveSorted(VectorT& vector, const typename VectorT::value_type& value)
  4293. {
  4294. CmpLess comparator;
  4295. typename VectorT::iterator it = VmaBinaryFindFirstNotLess(
  4296. vector.begin(),
  4297. vector.end(),
  4298. value,
  4299. comparator);
  4300. if((it != vector.end()) && !comparator(*it, value) && !comparator(value, *it))
  4301. {
  4302. size_t indexToRemove = it - vector.begin();
  4303. VmaVectorRemove(vector, indexToRemove);
  4304. return true;
  4305. }
  4306. return false;
  4307. }
  4308. ////////////////////////////////////////////////////////////////////////////////
  4309. // class VmaSmallVector
  4310. /*
  4311. This is a vector (a variable-sized array), optimized for the case when the array is small.
  4312. It contains some number of elements in-place, which allows it to avoid heap allocation
  4313. when the actual number of elements is below that threshold. This allows normal "small"
  4314. cases to be fast without losing generality for large inputs.
  4315. */
  4316. template<typename T, typename AllocatorT, size_t N>
  4317. class VmaSmallVector
  4318. {
  4319. public:
  4320. typedef T value_type;
  4321. VmaSmallVector(const AllocatorT& allocator) :
  4322. m_Count(0),
  4323. m_DynamicArray(allocator)
  4324. {
  4325. }
  4326. VmaSmallVector(size_t count, const AllocatorT& allocator) :
  4327. m_Count(count),
  4328. m_DynamicArray(count > N ? count : 0, allocator)
  4329. {
  4330. }
  4331. template<typename SrcT, typename SrcAllocatorT, size_t SrcN>
  4332. VmaSmallVector(const VmaSmallVector<SrcT, SrcAllocatorT, SrcN>& src) = delete;
  4333. template<typename SrcT, typename SrcAllocatorT, size_t SrcN>
  4334. VmaSmallVector<T, AllocatorT, N>& operator=(const VmaSmallVector<SrcT, SrcAllocatorT, SrcN>& rhs) = delete;
  4335. bool empty() const { return m_Count == 0; }
  4336. size_t size() const { return m_Count; }
  4337. T* data() { return m_Count > N ? m_DynamicArray.data() : m_StaticArray; }
  4338. const T* data() const { return m_Count > N ? m_DynamicArray.data() : m_StaticArray; }
  4339. T& operator[](size_t index)
  4340. {
  4341. VMA_HEAVY_ASSERT(index < m_Count);
  4342. return data()[index];
  4343. }
  4344. const T& operator[](size_t index) const
  4345. {
  4346. VMA_HEAVY_ASSERT(index < m_Count);
  4347. return data()[index];
  4348. }
  4349. T& front()
  4350. {
  4351. VMA_HEAVY_ASSERT(m_Count > 0);
  4352. return data()[0];
  4353. }
  4354. const T& front() const
  4355. {
  4356. VMA_HEAVY_ASSERT(m_Count > 0);
  4357. return data()[0];
  4358. }
  4359. T& back()
  4360. {
  4361. VMA_HEAVY_ASSERT(m_Count > 0);
  4362. return data()[m_Count - 1];
  4363. }
  4364. const T& back() const
  4365. {
  4366. VMA_HEAVY_ASSERT(m_Count > 0);
  4367. return data()[m_Count - 1];
  4368. }
  4369. void resize(size_t newCount, bool freeMemory = false)
  4370. {
  4371. if(newCount > N && m_Count > N)
  4372. {
  4373. // Any direction, staying in m_DynamicArray
  4374. m_DynamicArray.resize(newCount);
  4375. if(freeMemory)
  4376. {
  4377. m_DynamicArray.shrink_to_fit();
  4378. }
  4379. }
  4380. else if(newCount > N && m_Count <= N)
  4381. {
  4382. // Growing, moving from m_StaticArray to m_DynamicArray
  4383. m_DynamicArray.resize(newCount);
  4384. if(m_Count > 0)
  4385. {
  4386. memcpy(m_DynamicArray.data(), m_StaticArray, m_Count * sizeof(T));
  4387. }
  4388. }
  4389. else if(newCount <= N && m_Count > N)
  4390. {
  4391. // Shrinking, moving from m_DynamicArray to m_StaticArray
  4392. if(newCount > 0)
  4393. {
  4394. memcpy(m_StaticArray, m_DynamicArray.data(), newCount * sizeof(T));
  4395. }
  4396. m_DynamicArray.resize(0);
  4397. if(freeMemory)
  4398. {
  4399. m_DynamicArray.shrink_to_fit();
  4400. }
  4401. }
  4402. else
  4403. {
  4404. // Any direction, staying in m_StaticArray - nothing to do here
  4405. }
  4406. m_Count = newCount;
  4407. }
  4408. void clear(bool freeMemory = false)
  4409. {
  4410. m_DynamicArray.clear();
  4411. if(freeMemory)
  4412. {
  4413. m_DynamicArray.shrink_to_fit();
  4414. }
  4415. m_Count = 0;
  4416. }
  4417. void insert(size_t index, const T& src)
  4418. {
  4419. VMA_HEAVY_ASSERT(index <= m_Count);
  4420. const size_t oldCount = size();
  4421. resize(oldCount + 1);
  4422. T* const dataPtr = data();
  4423. if(index < oldCount)
  4424. {
  4425. // I know, this could be more optimal for case where memmove can be memcpy directly from m_StaticArray to m_DynamicArray.
  4426. memmove(dataPtr + (index + 1), dataPtr + index, (oldCount - index) * sizeof(T));
  4427. }
  4428. dataPtr[index] = src;
  4429. }
  4430. void remove(size_t index)
  4431. {
  4432. VMA_HEAVY_ASSERT(index < m_Count);
  4433. const size_t oldCount = size();
  4434. if(index < oldCount - 1)
  4435. {
  4436. // I know, this could be more optimal for case where memmove can be memcpy directly from m_DynamicArray to m_StaticArray.
  4437. T* const dataPtr = data();
  4438. memmove(dataPtr + index, dataPtr + (index + 1), (oldCount - index - 1) * sizeof(T));
  4439. }
  4440. resize(oldCount - 1);
  4441. }
  4442. void push_back(const T& src)
  4443. {
  4444. const size_t newIndex = size();
  4445. resize(newIndex + 1);
  4446. data()[newIndex] = src;
  4447. }
  4448. void pop_back()
  4449. {
  4450. VMA_HEAVY_ASSERT(m_Count > 0);
  4451. resize(size() - 1);
  4452. }
  4453. void push_front(const T& src)
  4454. {
  4455. insert(0, src);
  4456. }
  4457. void pop_front()
  4458. {
  4459. VMA_HEAVY_ASSERT(m_Count > 0);
  4460. remove(0);
  4461. }
  4462. typedef T* iterator;
  4463. iterator begin() { return data(); }
  4464. iterator end() { return data() + m_Count; }
  4465. private:
  4466. size_t m_Count;
  4467. T m_StaticArray[N]; // Used when m_Size <= N
  4468. VmaVector<T, AllocatorT> m_DynamicArray; // Used when m_Size > N
  4469. };
  4470. ////////////////////////////////////////////////////////////////////////////////
  4471. // class VmaPoolAllocator
  4472. /*
  4473. Allocator for objects of type T using a list of arrays (pools) to speed up
  4474. allocation. Number of elements that can be allocated is not bounded because
  4475. allocator can create multiple blocks.
  4476. */
  4477. template<typename T>
  4478. class VmaPoolAllocator
  4479. {
  4480. VMA_CLASS_NO_COPY(VmaPoolAllocator)
  4481. public:
  4482. VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, uint32_t firstBlockCapacity);
  4483. ~VmaPoolAllocator();
  4484. template<typename... Types> T* Alloc(Types... args);
  4485. void Free(T* ptr);
  4486. private:
  4487. union Item
  4488. {
  4489. uint32_t NextFreeIndex;
  4490. alignas(T) char Value[sizeof(T)];
  4491. };
  4492. struct ItemBlock
  4493. {
  4494. Item* pItems;
  4495. uint32_t Capacity;
  4496. uint32_t FirstFreeIndex;
  4497. };
  4498. const VkAllocationCallbacks* m_pAllocationCallbacks;
  4499. const uint32_t m_FirstBlockCapacity;
  4500. VmaVector< ItemBlock, VmaStlAllocator<ItemBlock> > m_ItemBlocks;
  4501. ItemBlock& CreateNewBlock();
  4502. };
  4503. template<typename T>
  4504. VmaPoolAllocator<T>::VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, uint32_t firstBlockCapacity) :
  4505. m_pAllocationCallbacks(pAllocationCallbacks),
  4506. m_FirstBlockCapacity(firstBlockCapacity),
  4507. m_ItemBlocks(VmaStlAllocator<ItemBlock>(pAllocationCallbacks))
  4508. {
  4509. VMA_ASSERT(m_FirstBlockCapacity > 1);
  4510. }
  4511. template<typename T>
  4512. VmaPoolAllocator<T>::~VmaPoolAllocator()
  4513. {
  4514. for(size_t i = m_ItemBlocks.size(); i--; )
  4515. vma_delete_array(m_pAllocationCallbacks, m_ItemBlocks[i].pItems, m_ItemBlocks[i].Capacity);
  4516. m_ItemBlocks.clear();
  4517. }
  4518. template<typename T>
  4519. template<typename... Types> T* VmaPoolAllocator<T>::Alloc(Types... args)
  4520. {
  4521. for(size_t i = m_ItemBlocks.size(); i--; )
  4522. {
  4523. ItemBlock& block = m_ItemBlocks[i];
  4524. // This block has some free items: Use first one.
  4525. if(block.FirstFreeIndex != UINT32_MAX)
  4526. {
  4527. Item* const pItem = &block.pItems[block.FirstFreeIndex];
  4528. block.FirstFreeIndex = pItem->NextFreeIndex;
  4529. T* result = (T*)&pItem->Value;
  4530. new(result)T(std::forward<Types>(args)...); // Explicit constructor call.
  4531. return result;
  4532. }
  4533. }
  4534. // No block has free item: Create new one and use it.
  4535. ItemBlock& newBlock = CreateNewBlock();
  4536. Item* const pItem = &newBlock.pItems[0];
  4537. newBlock.FirstFreeIndex = pItem->NextFreeIndex;
  4538. T* result = (T*)&pItem->Value;
  4539. new(result)T(std::forward<Types>(args)...); // Explicit constructor call.
  4540. return result;
  4541. }
  4542. template<typename T>
  4543. void VmaPoolAllocator<T>::Free(T* ptr)
  4544. {
  4545. // Search all memory blocks to find ptr.
  4546. for(size_t i = m_ItemBlocks.size(); i--; )
  4547. {
  4548. ItemBlock& block = m_ItemBlocks[i];
  4549. // Casting to union.
  4550. Item* pItemPtr;
  4551. memcpy(&pItemPtr, &ptr, sizeof(pItemPtr));
  4552. // Check if pItemPtr is in address range of this block.
  4553. if((pItemPtr >= block.pItems) && (pItemPtr < block.pItems + block.Capacity))
  4554. {
  4555. ptr->~T(); // Explicit destructor call.
  4556. const uint32_t index = static_cast<uint32_t>(pItemPtr - block.pItems);
  4557. pItemPtr->NextFreeIndex = block.FirstFreeIndex;
  4558. block.FirstFreeIndex = index;
  4559. return;
  4560. }
  4561. }
  4562. VMA_ASSERT(0 && "Pointer doesn't belong to this memory pool.");
  4563. }
  4564. template<typename T>
  4565. typename VmaPoolAllocator<T>::ItemBlock& VmaPoolAllocator<T>::CreateNewBlock()
  4566. {
  4567. const uint32_t newBlockCapacity = m_ItemBlocks.empty() ?
  4568. m_FirstBlockCapacity : m_ItemBlocks.back().Capacity * 3 / 2;
  4569. const ItemBlock newBlock = {
  4570. vma_new_array(m_pAllocationCallbacks, Item, newBlockCapacity),
  4571. newBlockCapacity,
  4572. 0 };
  4573. m_ItemBlocks.push_back(newBlock);
  4574. // Setup singly-linked list of all free items in this block.
  4575. for(uint32_t i = 0; i < newBlockCapacity - 1; ++i)
  4576. newBlock.pItems[i].NextFreeIndex = i + 1;
  4577. newBlock.pItems[newBlockCapacity - 1].NextFreeIndex = UINT32_MAX;
  4578. return m_ItemBlocks.back();
  4579. }
  4580. ////////////////////////////////////////////////////////////////////////////////
  4581. // class VmaRawList, VmaList
  4582. #if VMA_USE_STL_LIST
  4583. #define VmaList std::list
  4584. #else // #if VMA_USE_STL_LIST
  4585. template<typename T>
  4586. struct VmaListItem
  4587. {
  4588. VmaListItem* pPrev;
  4589. VmaListItem* pNext;
  4590. T Value;
  4591. };
  4592. // Doubly linked list.
  4593. template<typename T>
  4594. class VmaRawList
  4595. {
  4596. VMA_CLASS_NO_COPY(VmaRawList)
  4597. public:
  4598. typedef VmaListItem<T> ItemType;
  4599. VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks);
  4600. ~VmaRawList();
  4601. void Clear();
  4602. size_t GetCount() const { return m_Count; }
  4603. bool IsEmpty() const { return m_Count == 0; }
  4604. ItemType* Front() { return m_pFront; }
  4605. const ItemType* Front() const { return m_pFront; }
  4606. ItemType* Back() { return m_pBack; }
  4607. const ItemType* Back() const { return m_pBack; }
  4608. ItemType* PushBack();
  4609. ItemType* PushFront();
  4610. ItemType* PushBack(const T& value);
  4611. ItemType* PushFront(const T& value);
  4612. void PopBack();
  4613. void PopFront();
  4614. // Item can be null - it means PushBack.
  4615. ItemType* InsertBefore(ItemType* pItem);
  4616. // Item can be null - it means PushFront.
  4617. ItemType* InsertAfter(ItemType* pItem);
  4618. ItemType* InsertBefore(ItemType* pItem, const T& value);
  4619. ItemType* InsertAfter(ItemType* pItem, const T& value);
  4620. void Remove(ItemType* pItem);
  4621. private:
  4622. const VkAllocationCallbacks* const m_pAllocationCallbacks;
  4623. VmaPoolAllocator<ItemType> m_ItemAllocator;
  4624. ItemType* m_pFront;
  4625. ItemType* m_pBack;
  4626. size_t m_Count;
  4627. };
  4628. template<typename T>
  4629. VmaRawList<T>::VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks) :
  4630. m_pAllocationCallbacks(pAllocationCallbacks),
  4631. m_ItemAllocator(pAllocationCallbacks, 128),
  4632. m_pFront(VMA_NULL),
  4633. m_pBack(VMA_NULL),
  4634. m_Count(0)
  4635. {
  4636. }
  4637. template<typename T>
  4638. VmaRawList<T>::~VmaRawList()
  4639. {
  4640. // Intentionally not calling Clear, because that would be unnecessary
  4641. // computations to return all items to m_ItemAllocator as free.
  4642. }
  4643. template<typename T>
  4644. void VmaRawList<T>::Clear()
  4645. {
  4646. if(IsEmpty() == false)
  4647. {
  4648. ItemType* pItem = m_pBack;
  4649. while(pItem != VMA_NULL)
  4650. {
  4651. ItemType* const pPrevItem = pItem->pPrev;
  4652. m_ItemAllocator.Free(pItem);
  4653. pItem = pPrevItem;
  4654. }
  4655. m_pFront = VMA_NULL;
  4656. m_pBack = VMA_NULL;
  4657. m_Count = 0;
  4658. }
  4659. }
  4660. template<typename T>
  4661. VmaListItem<T>* VmaRawList<T>::PushBack()
  4662. {
  4663. ItemType* const pNewItem = m_ItemAllocator.Alloc();
  4664. pNewItem->pNext = VMA_NULL;
  4665. if(IsEmpty())
  4666. {
  4667. pNewItem->pPrev = VMA_NULL;
  4668. m_pFront = pNewItem;
  4669. m_pBack = pNewItem;
  4670. m_Count = 1;
  4671. }
  4672. else
  4673. {
  4674. pNewItem->pPrev = m_pBack;
  4675. m_pBack->pNext = pNewItem;
  4676. m_pBack = pNewItem;
  4677. ++m_Count;
  4678. }
  4679. return pNewItem;
  4680. }
  4681. template<typename T>
  4682. VmaListItem<T>* VmaRawList<T>::PushFront()
  4683. {
  4684. ItemType* const pNewItem = m_ItemAllocator.Alloc();
  4685. pNewItem->pPrev = VMA_NULL;
  4686. if(IsEmpty())
  4687. {
  4688. pNewItem->pNext = VMA_NULL;
  4689. m_pFront = pNewItem;
  4690. m_pBack = pNewItem;
  4691. m_Count = 1;
  4692. }
  4693. else
  4694. {
  4695. pNewItem->pNext = m_pFront;
  4696. m_pFront->pPrev = pNewItem;
  4697. m_pFront = pNewItem;
  4698. ++m_Count;
  4699. }
  4700. return pNewItem;
  4701. }
  4702. template<typename T>
  4703. VmaListItem<T>* VmaRawList<T>::PushBack(const T& value)
  4704. {
  4705. ItemType* const pNewItem = PushBack();
  4706. pNewItem->Value = value;
  4707. return pNewItem;
  4708. }
  4709. template<typename T>
  4710. VmaListItem<T>* VmaRawList<T>::PushFront(const T& value)
  4711. {
  4712. ItemType* const pNewItem = PushFront();
  4713. pNewItem->Value = value;
  4714. return pNewItem;
  4715. }
  4716. template<typename T>
  4717. void VmaRawList<T>::PopBack()
  4718. {
  4719. VMA_HEAVY_ASSERT(m_Count > 0);
  4720. ItemType* const pBackItem = m_pBack;
  4721. ItemType* const pPrevItem = pBackItem->pPrev;
  4722. if(pPrevItem != VMA_NULL)
  4723. {
  4724. pPrevItem->pNext = VMA_NULL;
  4725. }
  4726. m_pBack = pPrevItem;
  4727. m_ItemAllocator.Free(pBackItem);
  4728. --m_Count;
  4729. }
  4730. template<typename T>
  4731. void VmaRawList<T>::PopFront()
  4732. {
  4733. VMA_HEAVY_ASSERT(m_Count > 0);
  4734. ItemType* const pFrontItem = m_pFront;
  4735. ItemType* const pNextItem = pFrontItem->pNext;
  4736. if(pNextItem != VMA_NULL)
  4737. {
  4738. pNextItem->pPrev = VMA_NULL;
  4739. }
  4740. m_pFront = pNextItem;
  4741. m_ItemAllocator.Free(pFrontItem);
  4742. --m_Count;
  4743. }
  4744. template<typename T>
  4745. void VmaRawList<T>::Remove(ItemType* pItem)
  4746. {
  4747. VMA_HEAVY_ASSERT(pItem != VMA_NULL);
  4748. VMA_HEAVY_ASSERT(m_Count > 0);
  4749. if(pItem->pPrev != VMA_NULL)
  4750. {
  4751. pItem->pPrev->pNext = pItem->pNext;
  4752. }
  4753. else
  4754. {
  4755. VMA_HEAVY_ASSERT(m_pFront == pItem);
  4756. m_pFront = pItem->pNext;
  4757. }
  4758. if(pItem->pNext != VMA_NULL)
  4759. {
  4760. pItem->pNext->pPrev = pItem->pPrev;
  4761. }
  4762. else
  4763. {
  4764. VMA_HEAVY_ASSERT(m_pBack == pItem);
  4765. m_pBack = pItem->pPrev;
  4766. }
  4767. m_ItemAllocator.Free(pItem);
  4768. --m_Count;
  4769. }
  4770. template<typename T>
  4771. VmaListItem<T>* VmaRawList<T>::InsertBefore(ItemType* pItem)
  4772. {
  4773. if(pItem != VMA_NULL)
  4774. {
  4775. ItemType* const prevItem = pItem->pPrev;
  4776. ItemType* const newItem = m_ItemAllocator.Alloc();
  4777. newItem->pPrev = prevItem;
  4778. newItem->pNext = pItem;
  4779. pItem->pPrev = newItem;
  4780. if(prevItem != VMA_NULL)
  4781. {
  4782. prevItem->pNext = newItem;
  4783. }
  4784. else
  4785. {
  4786. VMA_HEAVY_ASSERT(m_pFront == pItem);
  4787. m_pFront = newItem;
  4788. }
  4789. ++m_Count;
  4790. return newItem;
  4791. }
  4792. else
  4793. return PushBack();
  4794. }
  4795. template<typename T>
  4796. VmaListItem<T>* VmaRawList<T>::InsertAfter(ItemType* pItem)
  4797. {
  4798. if(pItem != VMA_NULL)
  4799. {
  4800. ItemType* const nextItem = pItem->pNext;
  4801. ItemType* const newItem = m_ItemAllocator.Alloc();
  4802. newItem->pNext = nextItem;
  4803. newItem->pPrev = pItem;
  4804. pItem->pNext = newItem;
  4805. if(nextItem != VMA_NULL)
  4806. {
  4807. nextItem->pPrev = newItem;
  4808. }
  4809. else
  4810. {
  4811. VMA_HEAVY_ASSERT(m_pBack == pItem);
  4812. m_pBack = newItem;
  4813. }
  4814. ++m_Count;
  4815. return newItem;
  4816. }
  4817. else
  4818. return PushFront();
  4819. }
  4820. template<typename T>
  4821. VmaListItem<T>* VmaRawList<T>::InsertBefore(ItemType* pItem, const T& value)
  4822. {
  4823. ItemType* const newItem = InsertBefore(pItem);
  4824. newItem->Value = value;
  4825. return newItem;
  4826. }
  4827. template<typename T>
  4828. VmaListItem<T>* VmaRawList<T>::InsertAfter(ItemType* pItem, const T& value)
  4829. {
  4830. ItemType* const newItem = InsertAfter(pItem);
  4831. newItem->Value = value;
  4832. return newItem;
  4833. }
  4834. template<typename T, typename AllocatorT>
  4835. class VmaList
  4836. {
  4837. VMA_CLASS_NO_COPY(VmaList)
  4838. public:
  4839. class iterator
  4840. {
  4841. public:
  4842. iterator() :
  4843. m_pList(VMA_NULL),
  4844. m_pItem(VMA_NULL)
  4845. {
  4846. }
  4847. T& operator*() const
  4848. {
  4849. VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
  4850. return m_pItem->Value;
  4851. }
  4852. T* operator->() const
  4853. {
  4854. VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
  4855. return &m_pItem->Value;
  4856. }
  4857. iterator& operator++()
  4858. {
  4859. VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
  4860. m_pItem = m_pItem->pNext;
  4861. return *this;
  4862. }
  4863. iterator& operator--()
  4864. {
  4865. if(m_pItem != VMA_NULL)
  4866. {
  4867. m_pItem = m_pItem->pPrev;
  4868. }
  4869. else
  4870. {
  4871. VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
  4872. m_pItem = m_pList->Back();
  4873. }
  4874. return *this;
  4875. }
  4876. iterator operator++(int)
  4877. {
  4878. iterator result = *this;
  4879. ++*this;
  4880. return result;
  4881. }
  4882. iterator operator--(int)
  4883. {
  4884. iterator result = *this;
  4885. --*this;
  4886. return result;
  4887. }
  4888. bool operator==(const iterator& rhs) const
  4889. {
  4890. VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
  4891. return m_pItem == rhs.m_pItem;
  4892. }
  4893. bool operator!=(const iterator& rhs) const
  4894. {
  4895. VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
  4896. return m_pItem != rhs.m_pItem;
  4897. }
  4898. private:
  4899. VmaRawList<T>* m_pList;
  4900. VmaListItem<T>* m_pItem;
  4901. iterator(VmaRawList<T>* pList, VmaListItem<T>* pItem) :
  4902. m_pList(pList),
  4903. m_pItem(pItem)
  4904. {
  4905. }
  4906. friend class VmaList<T, AllocatorT>;
  4907. };
  4908. class const_iterator
  4909. {
  4910. public:
  4911. const_iterator() :
  4912. m_pList(VMA_NULL),
  4913. m_pItem(VMA_NULL)
  4914. {
  4915. }
  4916. const_iterator(const iterator& src) :
  4917. m_pList(src.m_pList),
  4918. m_pItem(src.m_pItem)
  4919. {
  4920. }
  4921. const T& operator*() const
  4922. {
  4923. VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
  4924. return m_pItem->Value;
  4925. }
  4926. const T* operator->() const
  4927. {
  4928. VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
  4929. return &m_pItem->Value;
  4930. }
  4931. const_iterator& operator++()
  4932. {
  4933. VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
  4934. m_pItem = m_pItem->pNext;
  4935. return *this;
  4936. }
  4937. const_iterator& operator--()
  4938. {
  4939. if(m_pItem != VMA_NULL)
  4940. {
  4941. m_pItem = m_pItem->pPrev;
  4942. }
  4943. else
  4944. {
  4945. VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
  4946. m_pItem = m_pList->Back();
  4947. }
  4948. return *this;
  4949. }
  4950. const_iterator operator++(int)
  4951. {
  4952. const_iterator result = *this;
  4953. ++*this;
  4954. return result;
  4955. }
  4956. const_iterator operator--(int)
  4957. {
  4958. const_iterator result = *this;
  4959. --*this;
  4960. return result;
  4961. }
  4962. bool operator==(const const_iterator& rhs) const
  4963. {
  4964. VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
  4965. return m_pItem == rhs.m_pItem;
  4966. }
  4967. bool operator!=(const const_iterator& rhs) const
  4968. {
  4969. VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
  4970. return m_pItem != rhs.m_pItem;
  4971. }
  4972. private:
  4973. const_iterator(const VmaRawList<T>* pList, const VmaListItem<T>* pItem) :
  4974. m_pList(pList),
  4975. m_pItem(pItem)
  4976. {
  4977. }
  4978. const VmaRawList<T>* m_pList;
  4979. const VmaListItem<T>* m_pItem;
  4980. friend class VmaList<T, AllocatorT>;
  4981. };
  4982. VmaList(const AllocatorT& allocator) : m_RawList(allocator.m_pCallbacks) { }
  4983. bool empty() const { return m_RawList.IsEmpty(); }
  4984. size_t size() const { return m_RawList.GetCount(); }
  4985. iterator begin() { return iterator(&m_RawList, m_RawList.Front()); }
  4986. iterator end() { return iterator(&m_RawList, VMA_NULL); }
  4987. const_iterator cbegin() const { return const_iterator(&m_RawList, m_RawList.Front()); }
  4988. const_iterator cend() const { return const_iterator(&m_RawList, VMA_NULL); }
  4989. const_iterator begin() const { return cbegin(); }
  4990. const_iterator end() const { return cend(); }
  4991. void clear() { m_RawList.Clear(); }
  4992. void push_back(const T& value) { m_RawList.PushBack(value); }
  4993. void erase(iterator it) { m_RawList.Remove(it.m_pItem); }
  4994. iterator insert(iterator it, const T& value) { return iterator(&m_RawList, m_RawList.InsertBefore(it.m_pItem, value)); }
  4995. private:
  4996. VmaRawList<T> m_RawList;
  4997. };
  4998. #endif // #if VMA_USE_STL_LIST
  4999. ////////////////////////////////////////////////////////////////////////////////
  5000. // class VmaIntrusiveLinkedList
  5001. /*
  5002. Expected interface of ItemTypeTraits:
  5003. struct MyItemTypeTraits
  5004. {
  5005. typedef MyItem ItemType;
  5006. static ItemType* GetPrev(const ItemType* item) { return item->myPrevPtr; }
  5007. static ItemType* GetNext(const ItemType* item) { return item->myNextPtr; }
  5008. static ItemType*& AccessPrev(ItemType* item) { return item->myPrevPtr; }
  5009. static ItemType*& AccessNext(ItemType* item) { return item->myNextPtr; }
  5010. };
  5011. */
  5012. template<typename ItemTypeTraits>
  5013. class VmaIntrusiveLinkedList
  5014. {
  5015. public:
  5016. typedef typename ItemTypeTraits::ItemType ItemType;
  5017. static ItemType* GetPrev(const ItemType* item) { return ItemTypeTraits::GetPrev(item); }
  5018. static ItemType* GetNext(const ItemType* item) { return ItemTypeTraits::GetNext(item); }
  5019. // Movable, not copyable.
  5020. VmaIntrusiveLinkedList() { }
  5021. VmaIntrusiveLinkedList(const VmaIntrusiveLinkedList<ItemTypeTraits>& src) = delete;
  5022. VmaIntrusiveLinkedList(VmaIntrusiveLinkedList<ItemTypeTraits>&& src) :
  5023. m_Front(src.m_Front), m_Back(src.m_Back), m_Count(src.m_Count)
  5024. {
  5025. src.m_Front = src.m_Back = VMA_NULL;
  5026. src.m_Count = 0;
  5027. }
  5028. ~VmaIntrusiveLinkedList()
  5029. {
  5030. VMA_HEAVY_ASSERT(IsEmpty());
  5031. }
  5032. VmaIntrusiveLinkedList<ItemTypeTraits>& operator=(const VmaIntrusiveLinkedList<ItemTypeTraits>& src) = delete;
  5033. VmaIntrusiveLinkedList<ItemTypeTraits>& operator=(VmaIntrusiveLinkedList<ItemTypeTraits>&& src)
  5034. {
  5035. if(&src != this)
  5036. {
  5037. VMA_HEAVY_ASSERT(IsEmpty());
  5038. m_Front = src.m_Front;
  5039. m_Back = src.m_Back;
  5040. m_Count = src.m_Count;
  5041. src.m_Front = src.m_Back = VMA_NULL;
  5042. src.m_Count = 0;
  5043. }
  5044. return *this;
  5045. }
  5046. void RemoveAll()
  5047. {
  5048. if(!IsEmpty())
  5049. {
  5050. ItemType* item = m_Back;
  5051. while(item != VMA_NULL)
  5052. {
  5053. ItemType* const prevItem = ItemTypeTraits::AccessPrev(item);
  5054. ItemTypeTraits::AccessPrev(item) = VMA_NULL;
  5055. ItemTypeTraits::AccessNext(item) = VMA_NULL;
  5056. item = prevItem;
  5057. }
  5058. m_Front = VMA_NULL;
  5059. m_Back = VMA_NULL;
  5060. m_Count = 0;
  5061. }
  5062. }
  5063. size_t GetCount() const { return m_Count; }
  5064. bool IsEmpty() const { return m_Count == 0; }
  5065. ItemType* Front() { return m_Front; }
  5066. const ItemType* Front() const { return m_Front; }
  5067. ItemType* Back() { return m_Back; }
  5068. const ItemType* Back() const { return m_Back; }
  5069. void PushBack(ItemType* item)
  5070. {
  5071. VMA_HEAVY_ASSERT(ItemTypeTraits::GetPrev(item) == VMA_NULL && ItemTypeTraits::GetNext(item) == VMA_NULL);
  5072. if(IsEmpty())
  5073. {
  5074. m_Front = item;
  5075. m_Back = item;
  5076. m_Count = 1;
  5077. }
  5078. else
  5079. {
  5080. ItemTypeTraits::AccessPrev(item) = m_Back;
  5081. ItemTypeTraits::AccessNext(m_Back) = item;
  5082. m_Back = item;
  5083. ++m_Count;
  5084. }
  5085. }
  5086. void PushFront(ItemType* item)
  5087. {
  5088. VMA_HEAVY_ASSERT(ItemTypeTraits::GetPrev(item) == VMA_NULL && ItemTypeTraits::GetNext(item) == VMA_NULL);
  5089. if(IsEmpty())
  5090. {
  5091. m_Front = item;
  5092. m_Back = item;
  5093. m_Count = 1;
  5094. }
  5095. else
  5096. {
  5097. ItemTypeTraits::AccessNext(item) = m_Front;
  5098. ItemTypeTraits::AccessPrev(m_Front) = item;
  5099. m_Front = item;
  5100. ++m_Count;
  5101. }
  5102. }
  5103. ItemType* PopBack()
  5104. {
  5105. VMA_HEAVY_ASSERT(m_Count > 0);
  5106. ItemType* const backItem = m_Back;
  5107. ItemType* const prevItem = ItemTypeTraits::GetPrev(backItem);
  5108. if(prevItem != VMA_NULL)
  5109. {
  5110. ItemTypeTraits::AccessNext(prevItem) = VMA_NULL;
  5111. }
  5112. m_Back = prevItem;
  5113. --m_Count;
  5114. ItemTypeTraits::AccessPrev(backItem) = VMA_NULL;
  5115. ItemTypeTraits::AccessNext(backItem) = VMA_NULL;
  5116. return backItem;
  5117. }
  5118. ItemType* PopFront()
  5119. {
  5120. VMA_HEAVY_ASSERT(m_Count > 0);
  5121. ItemType* const frontItem = m_Front;
  5122. ItemType* const nextItem = ItemTypeTraits::GetNext(frontItem);
  5123. if(nextItem != VMA_NULL)
  5124. {
  5125. ItemTypeTraits::AccessPrev(nextItem) = VMA_NULL;
  5126. }
  5127. m_Front = nextItem;
  5128. --m_Count;
  5129. ItemTypeTraits::AccessPrev(frontItem) = VMA_NULL;
  5130. ItemTypeTraits::AccessNext(frontItem) = VMA_NULL;
  5131. return frontItem;
  5132. }
  5133. // MyItem can be null - it means PushBack.
  5134. void InsertBefore(ItemType* existingItem, ItemType* newItem)
  5135. {
  5136. VMA_HEAVY_ASSERT(newItem != VMA_NULL && ItemTypeTraits::GetPrev(newItem) == VMA_NULL && ItemTypeTraits::GetNext(newItem) == VMA_NULL);
  5137. if(existingItem != VMA_NULL)
  5138. {
  5139. ItemType* const prevItem = ItemTypeTraits::GetPrev(existingItem);
  5140. ItemTypeTraits::AccessPrev(newItem) = prevItem;
  5141. ItemTypeTraits::AccessNext(newItem) = existingItem;
  5142. ItemTypeTraits::AccessPrev(existingItem) = newItem;
  5143. if(prevItem != VMA_NULL)
  5144. {
  5145. ItemTypeTraits::AccessNext(prevItem) = newItem;
  5146. }
  5147. else
  5148. {
  5149. VMA_HEAVY_ASSERT(m_Front == existingItem);
  5150. m_Front = newItem;
  5151. }
  5152. ++m_Count;
  5153. }
  5154. else
  5155. PushBack(newItem);
  5156. }
  5157. // MyItem can be null - it means PushFront.
  5158. void InsertAfter(ItemType* existingItem, ItemType* newItem)
  5159. {
  5160. VMA_HEAVY_ASSERT(newItem != VMA_NULL && ItemTypeTraits::GetPrev(newItem) == VMA_NULL && ItemTypeTraits::GetNext(newItem) == VMA_NULL);
  5161. if(existingItem != VMA_NULL)
  5162. {
  5163. ItemType* const nextItem = ItemTypeTraits::GetNext(existingItem);
  5164. ItemTypeTraits::AccessNext(newItem) = nextItem;
  5165. ItemTypeTraits::AccessPrev(newItem) = existingItem;
  5166. ItemTypeTraits::AccessNext(existingItem) = newItem;
  5167. if(nextItem != VMA_NULL)
  5168. {
  5169. ItemTypeTraits::AccessPrev(nextItem) = newItem;
  5170. }
  5171. else
  5172. {
  5173. VMA_HEAVY_ASSERT(m_Back == existingItem);
  5174. m_Back = newItem;
  5175. }
  5176. ++m_Count;
  5177. }
  5178. else
  5179. return PushFront(newItem);
  5180. }
  5181. void Remove(ItemType* item)
  5182. {
  5183. VMA_HEAVY_ASSERT(item != VMA_NULL && m_Count > 0);
  5184. if(ItemTypeTraits::GetPrev(item) != VMA_NULL)
  5185. {
  5186. ItemTypeTraits::AccessNext(ItemTypeTraits::AccessPrev(item)) = ItemTypeTraits::GetNext(item);
  5187. }
  5188. else
  5189. {
  5190. VMA_HEAVY_ASSERT(m_Front == item);
  5191. m_Front = ItemTypeTraits::GetNext(item);
  5192. }
  5193. if(ItemTypeTraits::GetNext(item) != VMA_NULL)
  5194. {
  5195. ItemTypeTraits::AccessPrev(ItemTypeTraits::AccessNext(item)) = ItemTypeTraits::GetPrev(item);
  5196. }
  5197. else
  5198. {
  5199. VMA_HEAVY_ASSERT(m_Back == item);
  5200. m_Back = ItemTypeTraits::GetPrev(item);
  5201. }
  5202. ItemTypeTraits::AccessPrev(item) = VMA_NULL;
  5203. ItemTypeTraits::AccessNext(item) = VMA_NULL;
  5204. --m_Count;
  5205. }
  5206. private:
  5207. ItemType* m_Front = VMA_NULL;
  5208. ItemType* m_Back = VMA_NULL;
  5209. size_t m_Count = 0;
  5210. };
  5211. ////////////////////////////////////////////////////////////////////////////////
  5212. // class VmaMap
  5213. // Unused in this version.
  5214. #if 0
  5215. #if VMA_USE_STL_UNORDERED_MAP
  5216. #define VmaPair std::pair
  5217. #define VMA_MAP_TYPE(KeyT, ValueT) \
  5218. std::unordered_map< KeyT, ValueT, std::hash<KeyT>, std::equal_to<KeyT>, VmaStlAllocator< std::pair<KeyT, ValueT> > >
  5219. #else // #if VMA_USE_STL_UNORDERED_MAP
  5220. template<typename T1, typename T2>
  5221. struct VmaPair
  5222. {
  5223. T1 first;
  5224. T2 second;
  5225. VmaPair() : first(), second() { }
  5226. VmaPair(const T1& firstSrc, const T2& secondSrc) : first(firstSrc), second(secondSrc) { }
  5227. };
  5228. /* Class compatible with subset of interface of std::unordered_map.
  5229. KeyT, ValueT must be POD because they will be stored in VmaVector.
  5230. */
  5231. template<typename KeyT, typename ValueT>
  5232. class VmaMap
  5233. {
  5234. public:
  5235. typedef VmaPair<KeyT, ValueT> PairType;
  5236. typedef PairType* iterator;
  5237. VmaMap(const VmaStlAllocator<PairType>& allocator) : m_Vector(allocator) { }
  5238. iterator begin() { return m_Vector.begin(); }
  5239. iterator end() { return m_Vector.end(); }
  5240. void insert(const PairType& pair);
  5241. iterator find(const KeyT& key);
  5242. void erase(iterator it);
  5243. private:
  5244. VmaVector< PairType, VmaStlAllocator<PairType> > m_Vector;
  5245. };
  5246. #define VMA_MAP_TYPE(KeyT, ValueT) VmaMap<KeyT, ValueT>
  5247. template<typename FirstT, typename SecondT>
  5248. struct VmaPairFirstLess
  5249. {
  5250. bool operator()(const VmaPair<FirstT, SecondT>& lhs, const VmaPair<FirstT, SecondT>& rhs) const
  5251. {
  5252. return lhs.first < rhs.first;
  5253. }
  5254. bool operator()(const VmaPair<FirstT, SecondT>& lhs, const FirstT& rhsFirst) const
  5255. {
  5256. return lhs.first < rhsFirst;
  5257. }
  5258. };
  5259. template<typename KeyT, typename ValueT>
  5260. void VmaMap<KeyT, ValueT>::insert(const PairType& pair)
  5261. {
  5262. const size_t indexToInsert = VmaBinaryFindFirstNotLess(
  5263. m_Vector.data(),
  5264. m_Vector.data() + m_Vector.size(),
  5265. pair,
  5266. VmaPairFirstLess<KeyT, ValueT>()) - m_Vector.data();
  5267. VmaVectorInsert(m_Vector, indexToInsert, pair);
  5268. }
  5269. template<typename KeyT, typename ValueT>
  5270. VmaPair<KeyT, ValueT>* VmaMap<KeyT, ValueT>::find(const KeyT& key)
  5271. {
  5272. PairType* it = VmaBinaryFindFirstNotLess(
  5273. m_Vector.data(),
  5274. m_Vector.data() + m_Vector.size(),
  5275. key,
  5276. VmaPairFirstLess<KeyT, ValueT>());
  5277. if((it != m_Vector.end()) && (it->first == key))
  5278. {
  5279. return it;
  5280. }
  5281. else
  5282. {
  5283. return m_Vector.end();
  5284. }
  5285. }
  5286. template<typename KeyT, typename ValueT>
  5287. void VmaMap<KeyT, ValueT>::erase(iterator it)
  5288. {
  5289. VmaVectorRemove(m_Vector, it - m_Vector.begin());
  5290. }
  5291. #endif // #if VMA_USE_STL_UNORDERED_MAP
  5292. #endif // #if 0
  5293. ////////////////////////////////////////////////////////////////////////////////
  5294. class VmaDeviceMemoryBlock;
  5295. enum VMA_CACHE_OPERATION { VMA_CACHE_FLUSH, VMA_CACHE_INVALIDATE };
  5296. struct VmaAllocation_T
  5297. {
  5298. private:
  5299. static const uint8_t MAP_COUNT_FLAG_PERSISTENT_MAP = 0x80;
  5300. enum FLAGS
  5301. {
  5302. FLAG_USER_DATA_STRING = 0x01,
  5303. };
  5304. public:
  5305. enum ALLOCATION_TYPE
  5306. {
  5307. ALLOCATION_TYPE_NONE,
  5308. ALLOCATION_TYPE_BLOCK,
  5309. ALLOCATION_TYPE_DEDICATED,
  5310. };
  5311. /*
  5312. This struct is allocated using VmaPoolAllocator.
  5313. */
  5314. VmaAllocation_T(uint32_t currentFrameIndex, bool userDataString) :
  5315. m_Alignment{1},
  5316. m_Size{0},
  5317. m_pUserData{VMA_NULL},
  5318. m_LastUseFrameIndex{currentFrameIndex},
  5319. m_MemoryTypeIndex{0},
  5320. m_Type{(uint8_t)ALLOCATION_TYPE_NONE},
  5321. m_SuballocationType{(uint8_t)VMA_SUBALLOCATION_TYPE_UNKNOWN},
  5322. m_MapCount{0},
  5323. m_Flags{userDataString ? (uint8_t)FLAG_USER_DATA_STRING : (uint8_t)0}
  5324. {
  5325. #if VMA_STATS_STRING_ENABLED
  5326. m_CreationFrameIndex = currentFrameIndex;
  5327. m_BufferImageUsage = 0;
  5328. #endif
  5329. }
  5330. ~VmaAllocation_T()
  5331. {
  5332. VMA_ASSERT((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) == 0 && "Allocation was not unmapped before destruction.");
  5333. // Check if owned string was freed.
  5334. VMA_ASSERT(m_pUserData == VMA_NULL);
  5335. }
  5336. void InitBlockAllocation(
  5337. VmaDeviceMemoryBlock* block,
  5338. VkDeviceSize offset,
  5339. VkDeviceSize alignment,
  5340. VkDeviceSize size,
  5341. uint32_t memoryTypeIndex,
  5342. VmaSuballocationType suballocationType,
  5343. bool mapped,
  5344. bool canBecomeLost)
  5345. {
  5346. VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
  5347. VMA_ASSERT(block != VMA_NULL);
  5348. m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK;
  5349. m_Alignment = alignment;
  5350. m_Size = size;
  5351. m_MemoryTypeIndex = memoryTypeIndex;
  5352. m_MapCount = mapped ? MAP_COUNT_FLAG_PERSISTENT_MAP : 0;
  5353. m_SuballocationType = (uint8_t)suballocationType;
  5354. m_BlockAllocation.m_Block = block;
  5355. m_BlockAllocation.m_Offset = offset;
  5356. m_BlockAllocation.m_CanBecomeLost = canBecomeLost;
  5357. }
  5358. void InitLost()
  5359. {
  5360. VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
  5361. VMA_ASSERT(m_LastUseFrameIndex.load() == VMA_FRAME_INDEX_LOST);
  5362. m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK;
  5363. m_MemoryTypeIndex = 0;
  5364. m_BlockAllocation.m_Block = VMA_NULL;
  5365. m_BlockAllocation.m_Offset = 0;
  5366. m_BlockAllocation.m_CanBecomeLost = true;
  5367. }
  5368. void ChangeBlockAllocation(
  5369. VmaAllocator hAllocator,
  5370. VmaDeviceMemoryBlock* block,
  5371. VkDeviceSize offset);
  5372. void ChangeOffset(VkDeviceSize newOffset);
  5373. // pMappedData not null means allocation is created with MAPPED flag.
  5374. void InitDedicatedAllocation(
  5375. uint32_t memoryTypeIndex,
  5376. VkDeviceMemory hMemory,
  5377. VmaSuballocationType suballocationType,
  5378. void* pMappedData,
  5379. VkDeviceSize size)
  5380. {
  5381. VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
  5382. VMA_ASSERT(hMemory != VK_NULL_HANDLE);
  5383. m_Type = (uint8_t)ALLOCATION_TYPE_DEDICATED;
  5384. m_Alignment = 0;
  5385. m_Size = size;
  5386. m_MemoryTypeIndex = memoryTypeIndex;
  5387. m_SuballocationType = (uint8_t)suballocationType;
  5388. m_MapCount = (pMappedData != VMA_NULL) ? MAP_COUNT_FLAG_PERSISTENT_MAP : 0;
  5389. m_DedicatedAllocation.m_hMemory = hMemory;
  5390. m_DedicatedAllocation.m_pMappedData = pMappedData;
  5391. m_DedicatedAllocation.m_Prev = VMA_NULL;
  5392. m_DedicatedAllocation.m_Next = VMA_NULL;
  5393. }
  5394. ALLOCATION_TYPE GetType() const { return (ALLOCATION_TYPE)m_Type; }
  5395. VkDeviceSize GetAlignment() const { return m_Alignment; }
  5396. VkDeviceSize GetSize() const { return m_Size; }
  5397. bool IsUserDataString() const { return (m_Flags & FLAG_USER_DATA_STRING) != 0; }
  5398. void* GetUserData() const { return m_pUserData; }
  5399. void SetUserData(VmaAllocator hAllocator, void* pUserData);
  5400. VmaSuballocationType GetSuballocationType() const { return (VmaSuballocationType)m_SuballocationType; }
  5401. VmaDeviceMemoryBlock* GetBlock() const
  5402. {
  5403. VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK);
  5404. return m_BlockAllocation.m_Block;
  5405. }
  5406. VkDeviceSize GetOffset() const;
  5407. VkDeviceMemory GetMemory() const;
  5408. uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
  5409. bool IsPersistentMap() const { return (m_MapCount & MAP_COUNT_FLAG_PERSISTENT_MAP) != 0; }
  5410. void* GetMappedData() const;
  5411. bool CanBecomeLost() const;
  5412. uint32_t GetLastUseFrameIndex() const
  5413. {
  5414. return m_LastUseFrameIndex.load();
  5415. }
  5416. bool CompareExchangeLastUseFrameIndex(uint32_t& expected, uint32_t desired)
  5417. {
  5418. return m_LastUseFrameIndex.compare_exchange_weak(expected, desired);
  5419. }
  5420. /*
  5421. - If hAllocation.LastUseFrameIndex + frameInUseCount < allocator.CurrentFrameIndex,
  5422. makes it lost by setting LastUseFrameIndex = VMA_FRAME_INDEX_LOST and returns true.
  5423. - Else, returns false.
  5424. If hAllocation is already lost, assert - you should not call it then.
  5425. If hAllocation was not created with CAN_BECOME_LOST_BIT, assert.
  5426. */
  5427. bool MakeLost(uint32_t currentFrameIndex, uint32_t frameInUseCount);
  5428. void DedicatedAllocCalcStatsInfo(VmaStatInfo& outInfo)
  5429. {
  5430. VMA_ASSERT(m_Type == ALLOCATION_TYPE_DEDICATED);
  5431. outInfo.blockCount = 1;
  5432. outInfo.allocationCount = 1;
  5433. outInfo.unusedRangeCount = 0;
  5434. outInfo.usedBytes = m_Size;
  5435. outInfo.unusedBytes = 0;
  5436. outInfo.allocationSizeMin = outInfo.allocationSizeMax = m_Size;
  5437. outInfo.unusedRangeSizeMin = UINT64_MAX;
  5438. outInfo.unusedRangeSizeMax = 0;
  5439. }
  5440. void BlockAllocMap();
  5441. void BlockAllocUnmap();
  5442. VkResult DedicatedAllocMap(VmaAllocator hAllocator, void** ppData);
  5443. void DedicatedAllocUnmap(VmaAllocator hAllocator);
  5444. #if VMA_STATS_STRING_ENABLED
  5445. uint32_t GetCreationFrameIndex() const { return m_CreationFrameIndex; }
  5446. uint32_t GetBufferImageUsage() const { return m_BufferImageUsage; }
  5447. void InitBufferImageUsage(uint32_t bufferImageUsage)
  5448. {
  5449. VMA_ASSERT(m_BufferImageUsage == 0);
  5450. m_BufferImageUsage = bufferImageUsage;
  5451. }
  5452. void PrintParameters(class VmaJsonWriter& json) const;
  5453. #endif
  5454. private:
  5455. VkDeviceSize m_Alignment;
  5456. VkDeviceSize m_Size;
  5457. void* m_pUserData;
  5458. VMA_ATOMIC_UINT32 m_LastUseFrameIndex;
  5459. uint32_t m_MemoryTypeIndex;
  5460. uint8_t m_Type; // ALLOCATION_TYPE
  5461. uint8_t m_SuballocationType; // VmaSuballocationType
  5462. // Bit 0x80 is set when allocation was created with VMA_ALLOCATION_CREATE_MAPPED_BIT.
  5463. // Bits with mask 0x7F are reference counter for vmaMapMemory()/vmaUnmapMemory().
  5464. uint8_t m_MapCount;
  5465. uint8_t m_Flags; // enum FLAGS
  5466. // Allocation out of VmaDeviceMemoryBlock.
  5467. struct BlockAllocation
  5468. {
  5469. VmaDeviceMemoryBlock* m_Block;
  5470. VkDeviceSize m_Offset;
  5471. bool m_CanBecomeLost;
  5472. };
  5473. // Allocation for an object that has its own private VkDeviceMemory.
  5474. struct DedicatedAllocation
  5475. {
  5476. VkDeviceMemory m_hMemory;
  5477. void* m_pMappedData; // Not null means memory is mapped.
  5478. VmaAllocation_T* m_Prev;
  5479. VmaAllocation_T* m_Next;
  5480. };
  5481. union
  5482. {
  5483. // Allocation out of VmaDeviceMemoryBlock.
  5484. BlockAllocation m_BlockAllocation;
  5485. // Allocation for an object that has its own private VkDeviceMemory.
  5486. DedicatedAllocation m_DedicatedAllocation;
  5487. };
  5488. #if VMA_STATS_STRING_ENABLED
  5489. uint32_t m_CreationFrameIndex;
  5490. uint32_t m_BufferImageUsage; // 0 if unknown.
  5491. #endif
  5492. void FreeUserDataString(VmaAllocator hAllocator);
  5493. friend struct VmaDedicatedAllocationListItemTraits;
  5494. };
  5495. struct VmaDedicatedAllocationListItemTraits
  5496. {
  5497. typedef VmaAllocation_T ItemType;
  5498. static ItemType* GetPrev(const ItemType* item)
  5499. {
  5500. VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  5501. return item->m_DedicatedAllocation.m_Prev;
  5502. }
  5503. static ItemType* GetNext(const ItemType* item)
  5504. {
  5505. VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  5506. return item->m_DedicatedAllocation.m_Next;
  5507. }
  5508. static ItemType*& AccessPrev(ItemType* item)
  5509. {
  5510. VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  5511. return item->m_DedicatedAllocation.m_Prev;
  5512. }
  5513. static ItemType*& AccessNext(ItemType* item){
  5514. VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  5515. return item->m_DedicatedAllocation.m_Next;
  5516. }
  5517. };
  5518. /*
  5519. Represents a region of VmaDeviceMemoryBlock that is either assigned and returned as
  5520. allocated memory block or free.
  5521. */
  5522. struct VmaSuballocation
  5523. {
  5524. VkDeviceSize offset;
  5525. VkDeviceSize size;
  5526. VmaAllocation hAllocation;
  5527. VmaSuballocationType type;
  5528. };
  5529. // Comparator for offsets.
  5530. struct VmaSuballocationOffsetLess
  5531. {
  5532. bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const
  5533. {
  5534. return lhs.offset < rhs.offset;
  5535. }
  5536. };
  5537. struct VmaSuballocationOffsetGreater
  5538. {
  5539. bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const
  5540. {
  5541. return lhs.offset > rhs.offset;
  5542. }
  5543. };
  5544. typedef VmaList< VmaSuballocation, VmaStlAllocator<VmaSuballocation> > VmaSuballocationList;
  5545. // Cost of one additional allocation lost, as equivalent in bytes.
  5546. static const VkDeviceSize VMA_LOST_ALLOCATION_COST = 1048576;
  5547. enum class VmaAllocationRequestType
  5548. {
  5549. Normal,
  5550. // Used by "Linear" algorithm.
  5551. UpperAddress,
  5552. EndOf1st,
  5553. EndOf2nd,
  5554. };
  5555. /*
  5556. Parameters of planned allocation inside a VmaDeviceMemoryBlock.
  5557. If canMakeOtherLost was false:
  5558. - item points to a FREE suballocation.
  5559. - itemsToMakeLostCount is 0.
  5560. If canMakeOtherLost was true:
  5561. - item points to first of sequence of suballocations, which are either FREE,
  5562. or point to VmaAllocations that can become lost.
  5563. - itemsToMakeLostCount is the number of VmaAllocations that need to be made lost for
  5564. the requested allocation to succeed.
  5565. */
  5566. struct VmaAllocationRequest
  5567. {
  5568. VkDeviceSize offset;
  5569. VkDeviceSize sumFreeSize; // Sum size of free items that overlap with proposed allocation.
  5570. VkDeviceSize sumItemSize; // Sum size of items to make lost that overlap with proposed allocation.
  5571. VmaSuballocationList::iterator item;
  5572. size_t itemsToMakeLostCount;
  5573. void* customData;
  5574. VmaAllocationRequestType type;
  5575. VkDeviceSize CalcCost() const
  5576. {
  5577. return sumItemSize + itemsToMakeLostCount * VMA_LOST_ALLOCATION_COST;
  5578. }
  5579. };
  5580. /*
  5581. Data structure used for bookkeeping of allocations and unused ranges of memory
  5582. in a single VkDeviceMemory block.
  5583. */
  5584. class VmaBlockMetadata
  5585. {
  5586. public:
  5587. VmaBlockMetadata(VmaAllocator hAllocator);
  5588. virtual ~VmaBlockMetadata() { }
  5589. virtual void Init(VkDeviceSize size) { m_Size = size; }
  5590. // Validates all data structures inside this object. If not valid, returns false.
  5591. virtual bool Validate() const = 0;
  5592. VkDeviceSize GetSize() const { return m_Size; }
  5593. virtual size_t GetAllocationCount() const = 0;
  5594. virtual VkDeviceSize GetSumFreeSize() const = 0;
  5595. virtual VkDeviceSize GetUnusedRangeSizeMax() const = 0;
  5596. // Returns true if this block is empty - contains only single free suballocation.
  5597. virtual bool IsEmpty() const = 0;
  5598. virtual void CalcAllocationStatInfo(VmaStatInfo& outInfo) const = 0;
  5599. // Shouldn't modify blockCount.
  5600. virtual void AddPoolStats(VmaPoolStats& inoutStats) const = 0;
  5601. #if VMA_STATS_STRING_ENABLED
  5602. virtual void PrintDetailedMap(class VmaJsonWriter& json) const = 0;
  5603. #endif
  5604. // Tries to find a place for suballocation with given parameters inside this block.
  5605. // If succeeded, fills pAllocationRequest and returns true.
  5606. // If failed, returns false.
  5607. virtual bool CreateAllocationRequest(
  5608. uint32_t currentFrameIndex,
  5609. uint32_t frameInUseCount,
  5610. VkDeviceSize bufferImageGranularity,
  5611. VkDeviceSize allocSize,
  5612. VkDeviceSize allocAlignment,
  5613. bool upperAddress,
  5614. VmaSuballocationType allocType,
  5615. bool canMakeOtherLost,
  5616. // Always one of VMA_ALLOCATION_CREATE_STRATEGY_* or VMA_ALLOCATION_INTERNAL_STRATEGY_* flags.
  5617. uint32_t strategy,
  5618. VmaAllocationRequest* pAllocationRequest) = 0;
  5619. virtual bool MakeRequestedAllocationsLost(
  5620. uint32_t currentFrameIndex,
  5621. uint32_t frameInUseCount,
  5622. VmaAllocationRequest* pAllocationRequest) = 0;
  5623. virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount) = 0;
  5624. virtual VkResult CheckCorruption(const void* pBlockData) = 0;
  5625. // Makes actual allocation based on request. Request must already be checked and valid.
  5626. virtual void Alloc(
  5627. const VmaAllocationRequest& request,
  5628. VmaSuballocationType type,
  5629. VkDeviceSize allocSize,
  5630. VmaAllocation hAllocation) = 0;
  5631. // Frees suballocation assigned to given memory region.
  5632. virtual void Free(const VmaAllocation allocation) = 0;
  5633. virtual void FreeAtOffset(VkDeviceSize offset) = 0;
  5634. protected:
  5635. const VkAllocationCallbacks* GetAllocationCallbacks() const { return m_pAllocationCallbacks; }
  5636. #if VMA_STATS_STRING_ENABLED
  5637. void PrintDetailedMap_Begin(class VmaJsonWriter& json,
  5638. VkDeviceSize unusedBytes,
  5639. size_t allocationCount,
  5640. size_t unusedRangeCount) const;
  5641. void PrintDetailedMap_Allocation(class VmaJsonWriter& json,
  5642. VkDeviceSize offset,
  5643. VmaAllocation hAllocation) const;
  5644. void PrintDetailedMap_UnusedRange(class VmaJsonWriter& json,
  5645. VkDeviceSize offset,
  5646. VkDeviceSize size) const;
  5647. void PrintDetailedMap_End(class VmaJsonWriter& json) const;
  5648. #endif
  5649. private:
  5650. VkDeviceSize m_Size;
  5651. const VkAllocationCallbacks* m_pAllocationCallbacks;
  5652. };
  5653. #define VMA_VALIDATE(cond) do { if(!(cond)) { \
  5654. VMA_ASSERT(0 && "Validation failed: " #cond); \
  5655. return false; \
  5656. } } while(false)
  5657. class VmaBlockMetadata_Generic : public VmaBlockMetadata
  5658. {
  5659. VMA_CLASS_NO_COPY(VmaBlockMetadata_Generic)
  5660. public:
  5661. VmaBlockMetadata_Generic(VmaAllocator hAllocator);
  5662. virtual ~VmaBlockMetadata_Generic();
  5663. virtual void Init(VkDeviceSize size);
  5664. virtual bool Validate() const;
  5665. virtual size_t GetAllocationCount() const { return m_Suballocations.size() - m_FreeCount; }
  5666. virtual VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize; }
  5667. virtual VkDeviceSize GetUnusedRangeSizeMax() const;
  5668. virtual bool IsEmpty() const;
  5669. virtual void CalcAllocationStatInfo(VmaStatInfo& outInfo) const;
  5670. virtual void AddPoolStats(VmaPoolStats& inoutStats) const;
  5671. #if VMA_STATS_STRING_ENABLED
  5672. virtual void PrintDetailedMap(class VmaJsonWriter& json) const;
  5673. #endif
  5674. virtual bool CreateAllocationRequest(
  5675. uint32_t currentFrameIndex,
  5676. uint32_t frameInUseCount,
  5677. VkDeviceSize bufferImageGranularity,
  5678. VkDeviceSize allocSize,
  5679. VkDeviceSize allocAlignment,
  5680. bool upperAddress,
  5681. VmaSuballocationType allocType,
  5682. bool canMakeOtherLost,
  5683. uint32_t strategy,
  5684. VmaAllocationRequest* pAllocationRequest);
  5685. virtual bool MakeRequestedAllocationsLost(
  5686. uint32_t currentFrameIndex,
  5687. uint32_t frameInUseCount,
  5688. VmaAllocationRequest* pAllocationRequest);
  5689. virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount);
  5690. virtual VkResult CheckCorruption(const void* pBlockData);
  5691. virtual void Alloc(
  5692. const VmaAllocationRequest& request,
  5693. VmaSuballocationType type,
  5694. VkDeviceSize allocSize,
  5695. VmaAllocation hAllocation);
  5696. virtual void Free(const VmaAllocation allocation);
  5697. virtual void FreeAtOffset(VkDeviceSize offset);
  5698. ////////////////////////////////////////////////////////////////////////////////
  5699. // For defragmentation
  5700. bool IsBufferImageGranularityConflictPossible(
  5701. VkDeviceSize bufferImageGranularity,
  5702. VmaSuballocationType& inOutPrevSuballocType) const;
  5703. private:
  5704. friend class VmaDefragmentationAlgorithm_Generic;
  5705. friend class VmaDefragmentationAlgorithm_Fast;
  5706. uint32_t m_FreeCount;
  5707. VkDeviceSize m_SumFreeSize;
  5708. VmaSuballocationList m_Suballocations;
  5709. // Suballocations that are free and have size greater than certain threshold.
  5710. // Sorted by size, ascending.
  5711. VmaVector< VmaSuballocationList::iterator, VmaStlAllocator< VmaSuballocationList::iterator > > m_FreeSuballocationsBySize;
  5712. bool ValidateFreeSuballocationList() const;
  5713. // Checks if requested suballocation with given parameters can be placed in given pFreeSuballocItem.
  5714. // If yes, fills pOffset and returns true. If no, returns false.
  5715. bool CheckAllocation(
  5716. uint32_t currentFrameIndex,
  5717. uint32_t frameInUseCount,
  5718. VkDeviceSize bufferImageGranularity,
  5719. VkDeviceSize allocSize,
  5720. VkDeviceSize allocAlignment,
  5721. VmaSuballocationType allocType,
  5722. VmaSuballocationList::const_iterator suballocItem,
  5723. bool canMakeOtherLost,
  5724. VkDeviceSize* pOffset,
  5725. size_t* itemsToMakeLostCount,
  5726. VkDeviceSize* pSumFreeSize,
  5727. VkDeviceSize* pSumItemSize) const;
  5728. // Given free suballocation, it merges it with following one, which must also be free.
  5729. void MergeFreeWithNext(VmaSuballocationList::iterator item);
  5730. // Releases given suballocation, making it free.
  5731. // Merges it with adjacent free suballocations if applicable.
  5732. // Returns iterator to new free suballocation at this place.
  5733. VmaSuballocationList::iterator FreeSuballocation(VmaSuballocationList::iterator suballocItem);
  5734. // Given free suballocation, it inserts it into sorted list of
  5735. // m_FreeSuballocationsBySize if it's suitable.
  5736. void RegisterFreeSuballocation(VmaSuballocationList::iterator item);
  5737. // Given free suballocation, it removes it from sorted list of
  5738. // m_FreeSuballocationsBySize if it's suitable.
  5739. void UnregisterFreeSuballocation(VmaSuballocationList::iterator item);
  5740. };
  5741. /*
  5742. Allocations and their references in internal data structure look like this:
  5743. if(m_2ndVectorMode == SECOND_VECTOR_EMPTY):
  5744. 0 +-------+
  5745. | |
  5746. | |
  5747. | |
  5748. +-------+
  5749. | Alloc | 1st[m_1stNullItemsBeginCount]
  5750. +-------+
  5751. | Alloc | 1st[m_1stNullItemsBeginCount + 1]
  5752. +-------+
  5753. | ... |
  5754. +-------+
  5755. | Alloc | 1st[1st.size() - 1]
  5756. +-------+
  5757. | |
  5758. | |
  5759. | |
  5760. GetSize() +-------+
  5761. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER):
  5762. 0 +-------+
  5763. | Alloc | 2nd[0]
  5764. +-------+
  5765. | Alloc | 2nd[1]
  5766. +-------+
  5767. | ... |
  5768. +-------+
  5769. | Alloc | 2nd[2nd.size() - 1]
  5770. +-------+
  5771. | |
  5772. | |
  5773. | |
  5774. +-------+
  5775. | Alloc | 1st[m_1stNullItemsBeginCount]
  5776. +-------+
  5777. | Alloc | 1st[m_1stNullItemsBeginCount + 1]
  5778. +-------+
  5779. | ... |
  5780. +-------+
  5781. | Alloc | 1st[1st.size() - 1]
  5782. +-------+
  5783. | |
  5784. GetSize() +-------+
  5785. if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK):
  5786. 0 +-------+
  5787. | |
  5788. | |
  5789. | |
  5790. +-------+
  5791. | Alloc | 1st[m_1stNullItemsBeginCount]
  5792. +-------+
  5793. | Alloc | 1st[m_1stNullItemsBeginCount + 1]
  5794. +-------+
  5795. | ... |
  5796. +-------+
  5797. | Alloc | 1st[1st.size() - 1]
  5798. +-------+
  5799. | |
  5800. | |
  5801. | |
  5802. +-------+
  5803. | Alloc | 2nd[2nd.size() - 1]
  5804. +-------+
  5805. | ... |
  5806. +-------+
  5807. | Alloc | 2nd[1]
  5808. +-------+
  5809. | Alloc | 2nd[0]
  5810. GetSize() +-------+
  5811. */
  5812. class VmaBlockMetadata_Linear : public VmaBlockMetadata
  5813. {
  5814. VMA_CLASS_NO_COPY(VmaBlockMetadata_Linear)
  5815. public:
  5816. VmaBlockMetadata_Linear(VmaAllocator hAllocator);
  5817. virtual ~VmaBlockMetadata_Linear();
  5818. virtual void Init(VkDeviceSize size);
  5819. virtual bool Validate() const;
  5820. virtual size_t GetAllocationCount() const;
  5821. virtual VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize; }
  5822. virtual VkDeviceSize GetUnusedRangeSizeMax() const;
  5823. virtual bool IsEmpty() const { return GetAllocationCount() == 0; }
  5824. virtual void CalcAllocationStatInfo(VmaStatInfo& outInfo) const;
  5825. virtual void AddPoolStats(VmaPoolStats& inoutStats) const;
  5826. #if VMA_STATS_STRING_ENABLED
  5827. virtual void PrintDetailedMap(class VmaJsonWriter& json) const;
  5828. #endif
  5829. virtual bool CreateAllocationRequest(
  5830. uint32_t currentFrameIndex,
  5831. uint32_t frameInUseCount,
  5832. VkDeviceSize bufferImageGranularity,
  5833. VkDeviceSize allocSize,
  5834. VkDeviceSize allocAlignment,
  5835. bool upperAddress,
  5836. VmaSuballocationType allocType,
  5837. bool canMakeOtherLost,
  5838. uint32_t strategy,
  5839. VmaAllocationRequest* pAllocationRequest);
  5840. virtual bool MakeRequestedAllocationsLost(
  5841. uint32_t currentFrameIndex,
  5842. uint32_t frameInUseCount,
  5843. VmaAllocationRequest* pAllocationRequest);
  5844. virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount);
  5845. virtual VkResult CheckCorruption(const void* pBlockData);
  5846. virtual void Alloc(
  5847. const VmaAllocationRequest& request,
  5848. VmaSuballocationType type,
  5849. VkDeviceSize allocSize,
  5850. VmaAllocation hAllocation);
  5851. virtual void Free(const VmaAllocation allocation);
  5852. virtual void FreeAtOffset(VkDeviceSize offset);
  5853. private:
  5854. /*
  5855. There are two suballocation vectors, used in ping-pong way.
  5856. The one with index m_1stVectorIndex is called 1st.
  5857. The one with index (m_1stVectorIndex ^ 1) is called 2nd.
  5858. 2nd can be non-empty only when 1st is not empty.
  5859. When 2nd is not empty, m_2ndVectorMode indicates its mode of operation.
  5860. */
  5861. typedef VmaVector< VmaSuballocation, VmaStlAllocator<VmaSuballocation> > SuballocationVectorType;
  5862. enum SECOND_VECTOR_MODE
  5863. {
  5864. SECOND_VECTOR_EMPTY,
  5865. /*
  5866. Suballocations in 2nd vector are created later than the ones in 1st, but they
  5867. all have smaller offset.
  5868. */
  5869. SECOND_VECTOR_RING_BUFFER,
  5870. /*
  5871. Suballocations in 2nd vector are upper side of double stack.
  5872. They all have offsets higher than those in 1st vector.
  5873. Top of this stack means smaller offsets, but higher indices in this vector.
  5874. */
  5875. SECOND_VECTOR_DOUBLE_STACK,
  5876. };
  5877. VkDeviceSize m_SumFreeSize;
  5878. SuballocationVectorType m_Suballocations0, m_Suballocations1;
  5879. uint32_t m_1stVectorIndex;
  5880. SECOND_VECTOR_MODE m_2ndVectorMode;
  5881. SuballocationVectorType& AccessSuballocations1st() { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; }
  5882. SuballocationVectorType& AccessSuballocations2nd() { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; }
  5883. const SuballocationVectorType& AccessSuballocations1st() const { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; }
  5884. const SuballocationVectorType& AccessSuballocations2nd() const { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; }
  5885. // Number of items in 1st vector with hAllocation = null at the beginning.
  5886. size_t m_1stNullItemsBeginCount;
  5887. // Number of other items in 1st vector with hAllocation = null somewhere in the middle.
  5888. size_t m_1stNullItemsMiddleCount;
  5889. // Number of items in 2nd vector with hAllocation = null.
  5890. size_t m_2ndNullItemsCount;
  5891. bool ShouldCompact1st() const;
  5892. void CleanupAfterFree();
  5893. bool CreateAllocationRequest_LowerAddress(
  5894. uint32_t currentFrameIndex,
  5895. uint32_t frameInUseCount,
  5896. VkDeviceSize bufferImageGranularity,
  5897. VkDeviceSize allocSize,
  5898. VkDeviceSize allocAlignment,
  5899. VmaSuballocationType allocType,
  5900. bool canMakeOtherLost,
  5901. uint32_t strategy,
  5902. VmaAllocationRequest* pAllocationRequest);
  5903. bool CreateAllocationRequest_UpperAddress(
  5904. uint32_t currentFrameIndex,
  5905. uint32_t frameInUseCount,
  5906. VkDeviceSize bufferImageGranularity,
  5907. VkDeviceSize allocSize,
  5908. VkDeviceSize allocAlignment,
  5909. VmaSuballocationType allocType,
  5910. bool canMakeOtherLost,
  5911. uint32_t strategy,
  5912. VmaAllocationRequest* pAllocationRequest);
  5913. };
  5914. /*
  5915. - GetSize() is the original size of allocated memory block.
  5916. - m_UsableSize is this size aligned down to a power of two.
  5917. All allocations and calculations happen relative to m_UsableSize.
  5918. - GetUnusableSize() is the difference between them.
  5919. It is reported as separate, unused range, not available for allocations.
  5920. Node at level 0 has size = m_UsableSize.
  5921. Each next level contains nodes with size 2 times smaller than current level.
  5922. m_LevelCount is the maximum number of levels to use in the current object.
  5923. */
  5924. class VmaBlockMetadata_Buddy : public VmaBlockMetadata
  5925. {
  5926. VMA_CLASS_NO_COPY(VmaBlockMetadata_Buddy)
  5927. public:
  5928. VmaBlockMetadata_Buddy(VmaAllocator hAllocator);
  5929. virtual ~VmaBlockMetadata_Buddy();
  5930. virtual void Init(VkDeviceSize size);
  5931. virtual bool Validate() const;
  5932. virtual size_t GetAllocationCount() const { return m_AllocationCount; }
  5933. virtual VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize + GetUnusableSize(); }
  5934. virtual VkDeviceSize GetUnusedRangeSizeMax() const;
  5935. virtual bool IsEmpty() const { return m_Root->type == Node::TYPE_FREE; }
  5936. virtual void CalcAllocationStatInfo(VmaStatInfo& outInfo) const;
  5937. virtual void AddPoolStats(VmaPoolStats& inoutStats) const;
  5938. #if VMA_STATS_STRING_ENABLED
  5939. virtual void PrintDetailedMap(class VmaJsonWriter& json) const;
  5940. #endif
  5941. virtual bool CreateAllocationRequest(
  5942. uint32_t currentFrameIndex,
  5943. uint32_t frameInUseCount,
  5944. VkDeviceSize bufferImageGranularity,
  5945. VkDeviceSize allocSize,
  5946. VkDeviceSize allocAlignment,
  5947. bool upperAddress,
  5948. VmaSuballocationType allocType,
  5949. bool canMakeOtherLost,
  5950. uint32_t strategy,
  5951. VmaAllocationRequest* pAllocationRequest);
  5952. virtual bool MakeRequestedAllocationsLost(
  5953. uint32_t currentFrameIndex,
  5954. uint32_t frameInUseCount,
  5955. VmaAllocationRequest* pAllocationRequest);
  5956. virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount);
  5957. virtual VkResult CheckCorruption(const void* pBlockData) { return VK_ERROR_FEATURE_NOT_PRESENT; }
  5958. virtual void Alloc(
  5959. const VmaAllocationRequest& request,
  5960. VmaSuballocationType type,
  5961. VkDeviceSize allocSize,
  5962. VmaAllocation hAllocation);
  5963. virtual void Free(const VmaAllocation allocation) { FreeAtOffset(allocation, allocation->GetOffset()); }
  5964. virtual void FreeAtOffset(VkDeviceSize offset) { FreeAtOffset(VMA_NULL, offset); }
  5965. private:
  5966. static const VkDeviceSize MIN_NODE_SIZE = 32;
  5967. static const size_t MAX_LEVELS = 30;
  5968. struct ValidationContext
  5969. {
  5970. size_t calculatedAllocationCount;
  5971. size_t calculatedFreeCount;
  5972. VkDeviceSize calculatedSumFreeSize;
  5973. ValidationContext() :
  5974. calculatedAllocationCount(0),
  5975. calculatedFreeCount(0),
  5976. calculatedSumFreeSize(0) { }
  5977. };
  5978. struct Node
  5979. {
  5980. VkDeviceSize offset;
  5981. enum TYPE
  5982. {
  5983. TYPE_FREE,
  5984. TYPE_ALLOCATION,
  5985. TYPE_SPLIT,
  5986. TYPE_COUNT
  5987. } type;
  5988. Node* parent;
  5989. Node* buddy;
  5990. union
  5991. {
  5992. struct
  5993. {
  5994. Node* prev;
  5995. Node* next;
  5996. } free;
  5997. struct
  5998. {
  5999. VmaAllocation alloc;
  6000. } allocation;
  6001. struct
  6002. {
  6003. Node* leftChild;
  6004. } split;
  6005. };
  6006. };
  6007. // Size of the memory block aligned down to a power of two.
  6008. VkDeviceSize m_UsableSize;
  6009. uint32_t m_LevelCount;
  6010. Node* m_Root;
  6011. struct {
  6012. Node* front;
  6013. Node* back;
  6014. } m_FreeList[MAX_LEVELS];
  6015. // Number of nodes in the tree with type == TYPE_ALLOCATION.
  6016. size_t m_AllocationCount;
  6017. // Number of nodes in the tree with type == TYPE_FREE.
  6018. size_t m_FreeCount;
  6019. // This includes space wasted due to internal fragmentation. Doesn't include unusable size.
  6020. VkDeviceSize m_SumFreeSize;
  6021. VkDeviceSize GetUnusableSize() const { return GetSize() - m_UsableSize; }
  6022. void DeleteNode(Node* node);
  6023. bool ValidateNode(ValidationContext& ctx, const Node* parent, const Node* curr, uint32_t level, VkDeviceSize levelNodeSize) const;
  6024. uint32_t AllocSizeToLevel(VkDeviceSize allocSize) const;
  6025. inline VkDeviceSize LevelToNodeSize(uint32_t level) const { return m_UsableSize >> level; }
  6026. // Alloc passed just for validation. Can be null.
  6027. void FreeAtOffset(VmaAllocation alloc, VkDeviceSize offset);
  6028. void CalcAllocationStatInfoNode(VmaStatInfo& outInfo, const Node* node, VkDeviceSize levelNodeSize) const;
  6029. // Adds node to the front of FreeList at given level.
  6030. // node->type must be FREE.
  6031. // node->free.prev, next can be undefined.
  6032. void AddToFreeListFront(uint32_t level, Node* node);
  6033. // Removes node from FreeList at given level.
  6034. // node->type must be FREE.
  6035. // node->free.prev, next stay untouched.
  6036. void RemoveFromFreeList(uint32_t level, Node* node);
  6037. #if VMA_STATS_STRING_ENABLED
  6038. void PrintDetailedMapNode(class VmaJsonWriter& json, const Node* node, VkDeviceSize levelNodeSize) const;
  6039. #endif
  6040. };
  6041. struct VmaBlockVector;
  6042. /*
  6043. Represents a single block of device memory (`VkDeviceMemory`) with all the
  6044. data about its regions (aka suballocations, #VmaAllocation), assigned and free.
  6045. Thread-safety: This class must be externally synchronized.
  6046. */
  6047. class VmaDeviceMemoryBlock
  6048. {
  6049. VMA_CLASS_NO_COPY(VmaDeviceMemoryBlock)
  6050. public:
  6051. VmaBlockMetadata* m_pMetadata;
  6052. VmaDeviceMemoryBlock(VmaAllocator hAllocator);
  6053. ~VmaDeviceMemoryBlock()
  6054. {
  6055. VMA_ASSERT(m_MapCount == 0 && "VkDeviceMemory block is being destroyed while it is still mapped.");
  6056. VMA_ASSERT(m_hMemory == VK_NULL_HANDLE);
  6057. }
  6058. // Always call after construction.
  6059. void Init(
  6060. VmaAllocator hAllocator,
  6061. VmaBlockVector* parentBlockVector,
  6062. VmaPool hParentPool,
  6063. uint32_t newMemoryTypeIndex,
  6064. VkDeviceMemory newMemory,
  6065. VkDeviceSize newSize,
  6066. uint32_t id,
  6067. uint32_t algorithm);
  6068. // Always call before destruction.
  6069. void Destroy(VmaAllocator allocator);
  6070. VmaBlockVector* GetParentBlockVector() const { return m_ParentBlockVector; }
  6071. VmaPool GetParentPool() const { return m_hParentPool; }
  6072. VkDeviceMemory GetDeviceMemory() const { return m_hMemory; }
  6073. uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
  6074. uint32_t GetId() const { return m_Id; }
  6075. void* GetMappedData() const { return m_pMappedData; }
  6076. // Validates all data structures inside this object. If not valid, returns false.
  6077. bool Validate() const;
  6078. VkResult CheckCorruption(VmaAllocator hAllocator);
  6079. // ppData can be null.
  6080. VkResult Map(VmaAllocator hAllocator, uint32_t count, void** ppData);
  6081. void Unmap(VmaAllocator hAllocator, uint32_t count);
  6082. VkResult WriteMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize);
  6083. VkResult ValidateMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize);
  6084. VkResult BindBufferMemory(
  6085. const VmaAllocator hAllocator,
  6086. const VmaAllocation hAllocation,
  6087. VkDeviceSize allocationLocalOffset,
  6088. VkBuffer hBuffer,
  6089. const void* pNext);
  6090. VkResult BindImageMemory(
  6091. const VmaAllocator hAllocator,
  6092. const VmaAllocation hAllocation,
  6093. VkDeviceSize allocationLocalOffset,
  6094. VkImage hImage,
  6095. const void* pNext);
  6096. private:
  6097. VmaBlockVector* m_ParentBlockVector = VMA_NULL;
  6098. VmaPool m_hParentPool = VK_NULL_HANDLE; // VK_NULL_HANDLE if not belongs to custom pool.
  6099. uint32_t m_MemoryTypeIndex = UINT32_MAX;
  6100. uint32_t m_Id = 0;
  6101. VkDeviceMemory m_hMemory = VK_NULL_HANDLE;
  6102. /*
  6103. Protects access to m_hMemory so it's not used by multiple threads simultaneously, e.g. vkMapMemory, vkBindBufferMemory.
  6104. Also protects m_MapCount, m_pMappedData.
  6105. Allocations, deallocations, any change in m_pMetadata is protected by parent's VmaBlockVector::m_Mutex.
  6106. */
  6107. VMA_MUTEX m_Mutex;
  6108. uint32_t m_MapCount = 0;
  6109. void* m_pMappedData = VMA_NULL;
  6110. };
  6111. struct VmaDefragmentationMove
  6112. {
  6113. size_t srcBlockIndex;
  6114. size_t dstBlockIndex;
  6115. VkDeviceSize srcOffset;
  6116. VkDeviceSize dstOffset;
  6117. VkDeviceSize size;
  6118. VmaAllocation hAllocation;
  6119. VmaDeviceMemoryBlock* pSrcBlock;
  6120. VmaDeviceMemoryBlock* pDstBlock;
  6121. };
  6122. class VmaDefragmentationAlgorithm;
  6123. /*
  6124. Sequence of VmaDeviceMemoryBlock. Represents memory blocks allocated for a specific
  6125. Vulkan memory type.
  6126. Synchronized internally with a mutex.
  6127. */
  6128. struct VmaBlockVector
  6129. {
  6130. VMA_CLASS_NO_COPY(VmaBlockVector)
  6131. public:
  6132. VmaBlockVector(
  6133. VmaAllocator hAllocator,
  6134. VmaPool hParentPool,
  6135. uint32_t memoryTypeIndex,
  6136. VkDeviceSize preferredBlockSize,
  6137. size_t minBlockCount,
  6138. size_t maxBlockCount,
  6139. VkDeviceSize bufferImageGranularity,
  6140. uint32_t frameInUseCount,
  6141. bool explicitBlockSize,
  6142. uint32_t algorithm,
  6143. float priority,
  6144. VkDeviceSize minAllocationAlignment,
  6145. void* pMemoryAllocateNext);
  6146. ~VmaBlockVector();
  6147. VkResult CreateMinBlocks();
  6148. VmaAllocator GetAllocator() const { return m_hAllocator; }
  6149. VmaPool GetParentPool() const { return m_hParentPool; }
  6150. bool IsCustomPool() const { return m_hParentPool != VMA_NULL; }
  6151. uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
  6152. VkDeviceSize GetPreferredBlockSize() const { return m_PreferredBlockSize; }
  6153. VkDeviceSize GetBufferImageGranularity() const { return m_BufferImageGranularity; }
  6154. uint32_t GetFrameInUseCount() const { return m_FrameInUseCount; }
  6155. uint32_t GetAlgorithm() const { return m_Algorithm; }
  6156. void GetPoolStats(VmaPoolStats* pStats);
  6157. bool IsEmpty();
  6158. bool IsCorruptionDetectionEnabled() const;
  6159. VkResult Allocate(
  6160. uint32_t currentFrameIndex,
  6161. VkDeviceSize size,
  6162. VkDeviceSize alignment,
  6163. const VmaAllocationCreateInfo& createInfo,
  6164. VmaSuballocationType suballocType,
  6165. size_t allocationCount,
  6166. VmaAllocation* pAllocations);
  6167. void Free(const VmaAllocation hAllocation);
  6168. // Adds statistics of this BlockVector to pStats.
  6169. void AddStats(VmaStats* pStats);
  6170. #if VMA_STATS_STRING_ENABLED
  6171. void PrintDetailedMap(class VmaJsonWriter& json);
  6172. #endif
  6173. void MakePoolAllocationsLost(
  6174. uint32_t currentFrameIndex,
  6175. size_t* pLostAllocationCount);
  6176. VkResult CheckCorruption();
  6177. // Saves results in pCtx->res.
  6178. void Defragment(
  6179. class VmaBlockVectorDefragmentationContext* pCtx,
  6180. VmaDefragmentationStats* pStats, VmaDefragmentationFlags flags,
  6181. VkDeviceSize& maxCpuBytesToMove, uint32_t& maxCpuAllocationsToMove,
  6182. VkDeviceSize& maxGpuBytesToMove, uint32_t& maxGpuAllocationsToMove,
  6183. VkCommandBuffer commandBuffer);
  6184. void DefragmentationEnd(
  6185. class VmaBlockVectorDefragmentationContext* pCtx,
  6186. uint32_t flags,
  6187. VmaDefragmentationStats* pStats);
  6188. uint32_t ProcessDefragmentations(
  6189. class VmaBlockVectorDefragmentationContext *pCtx,
  6190. VmaDefragmentationPassMoveInfo* pMove, uint32_t maxMoves);
  6191. void CommitDefragmentations(
  6192. class VmaBlockVectorDefragmentationContext *pCtx,
  6193. VmaDefragmentationStats* pStats);
  6194. ////////////////////////////////////////////////////////////////////////////////
  6195. // To be used only while the m_Mutex is locked. Used during defragmentation.
  6196. size_t GetBlockCount() const { return m_Blocks.size(); }
  6197. VmaDeviceMemoryBlock* GetBlock(size_t index) const { return m_Blocks[index]; }
  6198. size_t CalcAllocationCount() const;
  6199. bool IsBufferImageGranularityConflictPossible() const;
  6200. private:
  6201. friend class VmaDefragmentationAlgorithm_Generic;
  6202. const VmaAllocator m_hAllocator;
  6203. const VmaPool m_hParentPool;
  6204. const uint32_t m_MemoryTypeIndex;
  6205. const VkDeviceSize m_PreferredBlockSize;
  6206. const size_t m_MinBlockCount;
  6207. const size_t m_MaxBlockCount;
  6208. const VkDeviceSize m_BufferImageGranularity;
  6209. const uint32_t m_FrameInUseCount;
  6210. const bool m_ExplicitBlockSize;
  6211. const uint32_t m_Algorithm;
  6212. const float m_Priority;
  6213. const VkDeviceSize m_MinAllocationAlignment;
  6214. void* const m_pMemoryAllocateNext;
  6215. VMA_RW_MUTEX m_Mutex;
  6216. /* There can be at most one allocation that is completely empty (except when minBlockCount > 0) -
  6217. a hysteresis to avoid pessimistic case of alternating creation and destruction of a VkDeviceMemory. */
  6218. bool m_HasEmptyBlock;
  6219. // Incrementally sorted by sumFreeSize, ascending.
  6220. VmaVector< VmaDeviceMemoryBlock*, VmaStlAllocator<VmaDeviceMemoryBlock*> > m_Blocks;
  6221. uint32_t m_NextBlockId;
  6222. VkDeviceSize CalcMaxBlockSize() const;
  6223. // Finds and removes given block from vector.
  6224. void Remove(VmaDeviceMemoryBlock* pBlock);
  6225. // Performs single step in sorting m_Blocks. They may not be fully sorted
  6226. // after this call.
  6227. void IncrementallySortBlocks();
  6228. VkResult AllocatePage(
  6229. uint32_t currentFrameIndex,
  6230. VkDeviceSize size,
  6231. VkDeviceSize alignment,
  6232. const VmaAllocationCreateInfo& createInfo,
  6233. VmaSuballocationType suballocType,
  6234. VmaAllocation* pAllocation);
  6235. // To be used only without CAN_MAKE_OTHER_LOST flag.
  6236. VkResult AllocateFromBlock(
  6237. VmaDeviceMemoryBlock* pBlock,
  6238. uint32_t currentFrameIndex,
  6239. VkDeviceSize size,
  6240. VkDeviceSize alignment,
  6241. VmaAllocationCreateFlags allocFlags,
  6242. void* pUserData,
  6243. VmaSuballocationType suballocType,
  6244. uint32_t strategy,
  6245. VmaAllocation* pAllocation);
  6246. VkResult CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex);
  6247. // Saves result to pCtx->res.
  6248. void ApplyDefragmentationMovesCpu(
  6249. class VmaBlockVectorDefragmentationContext* pDefragCtx,
  6250. const VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves);
  6251. // Saves result to pCtx->res.
  6252. void ApplyDefragmentationMovesGpu(
  6253. class VmaBlockVectorDefragmentationContext* pDefragCtx,
  6254. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  6255. VkCommandBuffer commandBuffer);
  6256. /*
  6257. Used during defragmentation. pDefragmentationStats is optional. It's in/out
  6258. - updated with new data.
  6259. */
  6260. void FreeEmptyBlocks(VmaDefragmentationStats* pDefragmentationStats);
  6261. void UpdateHasEmptyBlock();
  6262. };
  6263. struct VmaPool_T
  6264. {
  6265. VMA_CLASS_NO_COPY(VmaPool_T)
  6266. public:
  6267. VmaBlockVector m_BlockVector;
  6268. VmaPool_T(
  6269. VmaAllocator hAllocator,
  6270. const VmaPoolCreateInfo& createInfo,
  6271. VkDeviceSize preferredBlockSize);
  6272. ~VmaPool_T();
  6273. uint32_t GetId() const { return m_Id; }
  6274. void SetId(uint32_t id) { VMA_ASSERT(m_Id == 0); m_Id = id; }
  6275. const char* GetName() const { return m_Name; }
  6276. void SetName(const char* pName);
  6277. #if VMA_STATS_STRING_ENABLED
  6278. //void PrintDetailedMap(class VmaStringBuilder& sb);
  6279. #endif
  6280. private:
  6281. uint32_t m_Id;
  6282. char* m_Name;
  6283. VmaPool_T* m_PrevPool = VMA_NULL;
  6284. VmaPool_T* m_NextPool = VMA_NULL;
  6285. friend struct VmaPoolListItemTraits;
  6286. };
  6287. struct VmaPoolListItemTraits
  6288. {
  6289. typedef VmaPool_T ItemType;
  6290. static ItemType* GetPrev(const ItemType* item) { return item->m_PrevPool; }
  6291. static ItemType* GetNext(const ItemType* item) { return item->m_NextPool; }
  6292. static ItemType*& AccessPrev(ItemType* item) { return item->m_PrevPool; }
  6293. static ItemType*& AccessNext(ItemType* item) { return item->m_NextPool; }
  6294. };
  6295. /*
  6296. Performs defragmentation:
  6297. - Updates `pBlockVector->m_pMetadata`.
  6298. - Updates allocations by calling ChangeBlockAllocation() or ChangeOffset().
  6299. - Does not move actual data, only returns requested moves as `moves`.
  6300. */
  6301. class VmaDefragmentationAlgorithm
  6302. {
  6303. VMA_CLASS_NO_COPY(VmaDefragmentationAlgorithm)
  6304. public:
  6305. VmaDefragmentationAlgorithm(
  6306. VmaAllocator hAllocator,
  6307. VmaBlockVector* pBlockVector,
  6308. uint32_t currentFrameIndex) :
  6309. m_hAllocator(hAllocator),
  6310. m_pBlockVector(pBlockVector),
  6311. m_CurrentFrameIndex(currentFrameIndex)
  6312. {
  6313. }
  6314. virtual ~VmaDefragmentationAlgorithm()
  6315. {
  6316. }
  6317. virtual void AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged) = 0;
  6318. virtual void AddAll() = 0;
  6319. virtual VkResult Defragment(
  6320. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  6321. VkDeviceSize maxBytesToMove,
  6322. uint32_t maxAllocationsToMove,
  6323. VmaDefragmentationFlags flags) = 0;
  6324. virtual VkDeviceSize GetBytesMoved() const = 0;
  6325. virtual uint32_t GetAllocationsMoved() const = 0;
  6326. protected:
  6327. VmaAllocator const m_hAllocator;
  6328. VmaBlockVector* const m_pBlockVector;
  6329. const uint32_t m_CurrentFrameIndex;
  6330. struct AllocationInfo
  6331. {
  6332. VmaAllocation m_hAllocation;
  6333. VkBool32* m_pChanged;
  6334. AllocationInfo() :
  6335. m_hAllocation(VK_NULL_HANDLE),
  6336. m_pChanged(VMA_NULL)
  6337. {
  6338. }
  6339. AllocationInfo(VmaAllocation hAlloc, VkBool32* pChanged) :
  6340. m_hAllocation(hAlloc),
  6341. m_pChanged(pChanged)
  6342. {
  6343. }
  6344. };
  6345. };
  6346. class VmaDefragmentationAlgorithm_Generic : public VmaDefragmentationAlgorithm
  6347. {
  6348. VMA_CLASS_NO_COPY(VmaDefragmentationAlgorithm_Generic)
  6349. public:
  6350. VmaDefragmentationAlgorithm_Generic(
  6351. VmaAllocator hAllocator,
  6352. VmaBlockVector* pBlockVector,
  6353. uint32_t currentFrameIndex,
  6354. bool overlappingMoveSupported);
  6355. virtual ~VmaDefragmentationAlgorithm_Generic();
  6356. virtual void AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged);
  6357. virtual void AddAll() { m_AllAllocations = true; }
  6358. virtual VkResult Defragment(
  6359. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  6360. VkDeviceSize maxBytesToMove,
  6361. uint32_t maxAllocationsToMove,
  6362. VmaDefragmentationFlags flags);
  6363. virtual VkDeviceSize GetBytesMoved() const { return m_BytesMoved; }
  6364. virtual uint32_t GetAllocationsMoved() const { return m_AllocationsMoved; }
  6365. private:
  6366. uint32_t m_AllocationCount;
  6367. bool m_AllAllocations;
  6368. VkDeviceSize m_BytesMoved;
  6369. uint32_t m_AllocationsMoved;
  6370. struct AllocationInfoSizeGreater
  6371. {
  6372. bool operator()(const AllocationInfo& lhs, const AllocationInfo& rhs) const
  6373. {
  6374. return lhs.m_hAllocation->GetSize() > rhs.m_hAllocation->GetSize();
  6375. }
  6376. };
  6377. struct AllocationInfoOffsetGreater
  6378. {
  6379. bool operator()(const AllocationInfo& lhs, const AllocationInfo& rhs) const
  6380. {
  6381. return lhs.m_hAllocation->GetOffset() > rhs.m_hAllocation->GetOffset();
  6382. }
  6383. };
  6384. struct BlockInfo
  6385. {
  6386. size_t m_OriginalBlockIndex;
  6387. VmaDeviceMemoryBlock* m_pBlock;
  6388. bool m_HasNonMovableAllocations;
  6389. VmaVector< AllocationInfo, VmaStlAllocator<AllocationInfo> > m_Allocations;
  6390. BlockInfo(const VkAllocationCallbacks* pAllocationCallbacks) :
  6391. m_OriginalBlockIndex(SIZE_MAX),
  6392. m_pBlock(VMA_NULL),
  6393. m_HasNonMovableAllocations(true),
  6394. m_Allocations(pAllocationCallbacks)
  6395. {
  6396. }
  6397. void CalcHasNonMovableAllocations()
  6398. {
  6399. const size_t blockAllocCount = m_pBlock->m_pMetadata->GetAllocationCount();
  6400. const size_t defragmentAllocCount = m_Allocations.size();
  6401. m_HasNonMovableAllocations = blockAllocCount != defragmentAllocCount;
  6402. }
  6403. void SortAllocationsBySizeDescending()
  6404. {
  6405. VMA_SORT(m_Allocations.begin(), m_Allocations.end(), AllocationInfoSizeGreater());
  6406. }
  6407. void SortAllocationsByOffsetDescending()
  6408. {
  6409. VMA_SORT(m_Allocations.begin(), m_Allocations.end(), AllocationInfoOffsetGreater());
  6410. }
  6411. };
  6412. struct BlockPointerLess
  6413. {
  6414. bool operator()(const BlockInfo* pLhsBlockInfo, const VmaDeviceMemoryBlock* pRhsBlock) const
  6415. {
  6416. return pLhsBlockInfo->m_pBlock < pRhsBlock;
  6417. }
  6418. bool operator()(const BlockInfo* pLhsBlockInfo, const BlockInfo* pRhsBlockInfo) const
  6419. {
  6420. return pLhsBlockInfo->m_pBlock < pRhsBlockInfo->m_pBlock;
  6421. }
  6422. };
  6423. // 1. Blocks with some non-movable allocations go first.
  6424. // 2. Blocks with smaller sumFreeSize go first.
  6425. struct BlockInfoCompareMoveDestination
  6426. {
  6427. bool operator()(const BlockInfo* pLhsBlockInfo, const BlockInfo* pRhsBlockInfo) const
  6428. {
  6429. if(pLhsBlockInfo->m_HasNonMovableAllocations && !pRhsBlockInfo->m_HasNonMovableAllocations)
  6430. {
  6431. return true;
  6432. }
  6433. if(!pLhsBlockInfo->m_HasNonMovableAllocations && pRhsBlockInfo->m_HasNonMovableAllocations)
  6434. {
  6435. return false;
  6436. }
  6437. if(pLhsBlockInfo->m_pBlock->m_pMetadata->GetSumFreeSize() < pRhsBlockInfo->m_pBlock->m_pMetadata->GetSumFreeSize())
  6438. {
  6439. return true;
  6440. }
  6441. return false;
  6442. }
  6443. };
  6444. typedef VmaVector< BlockInfo*, VmaStlAllocator<BlockInfo*> > BlockInfoVector;
  6445. BlockInfoVector m_Blocks;
  6446. VkResult DefragmentRound(
  6447. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  6448. VkDeviceSize maxBytesToMove,
  6449. uint32_t maxAllocationsToMove,
  6450. bool freeOldAllocations);
  6451. size_t CalcBlocksWithNonMovableCount() const;
  6452. static bool MoveMakesSense(
  6453. size_t dstBlockIndex, VkDeviceSize dstOffset,
  6454. size_t srcBlockIndex, VkDeviceSize srcOffset);
  6455. };
  6456. class VmaDefragmentationAlgorithm_Fast : public VmaDefragmentationAlgorithm
  6457. {
  6458. VMA_CLASS_NO_COPY(VmaDefragmentationAlgorithm_Fast)
  6459. public:
  6460. VmaDefragmentationAlgorithm_Fast(
  6461. VmaAllocator hAllocator,
  6462. VmaBlockVector* pBlockVector,
  6463. uint32_t currentFrameIndex,
  6464. bool overlappingMoveSupported);
  6465. virtual ~VmaDefragmentationAlgorithm_Fast();
  6466. virtual void AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged) { ++m_AllocationCount; }
  6467. virtual void AddAll() { m_AllAllocations = true; }
  6468. virtual VkResult Defragment(
  6469. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  6470. VkDeviceSize maxBytesToMove,
  6471. uint32_t maxAllocationsToMove,
  6472. VmaDefragmentationFlags flags);
  6473. virtual VkDeviceSize GetBytesMoved() const { return m_BytesMoved; }
  6474. virtual uint32_t GetAllocationsMoved() const { return m_AllocationsMoved; }
  6475. private:
  6476. struct BlockInfo
  6477. {
  6478. size_t origBlockIndex;
  6479. };
  6480. class FreeSpaceDatabase
  6481. {
  6482. public:
  6483. FreeSpaceDatabase()
  6484. {
  6485. FreeSpace s = {};
  6486. s.blockInfoIndex = SIZE_MAX;
  6487. for(size_t i = 0; i < MAX_COUNT; ++i)
  6488. {
  6489. m_FreeSpaces[i] = s;
  6490. }
  6491. }
  6492. void Register(size_t blockInfoIndex, VkDeviceSize offset, VkDeviceSize size)
  6493. {
  6494. if(size < VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
  6495. {
  6496. return;
  6497. }
  6498. // Find first invalid or the smallest structure.
  6499. size_t bestIndex = SIZE_MAX;
  6500. for(size_t i = 0; i < MAX_COUNT; ++i)
  6501. {
  6502. // Empty structure.
  6503. if(m_FreeSpaces[i].blockInfoIndex == SIZE_MAX)
  6504. {
  6505. bestIndex = i;
  6506. break;
  6507. }
  6508. if(m_FreeSpaces[i].size < size &&
  6509. (bestIndex == SIZE_MAX || m_FreeSpaces[bestIndex].size > m_FreeSpaces[i].size))
  6510. {
  6511. bestIndex = i;
  6512. }
  6513. }
  6514. if(bestIndex != SIZE_MAX)
  6515. {
  6516. m_FreeSpaces[bestIndex].blockInfoIndex = blockInfoIndex;
  6517. m_FreeSpaces[bestIndex].offset = offset;
  6518. m_FreeSpaces[bestIndex].size = size;
  6519. }
  6520. }
  6521. bool Fetch(VkDeviceSize alignment, VkDeviceSize size,
  6522. size_t& outBlockInfoIndex, VkDeviceSize& outDstOffset)
  6523. {
  6524. size_t bestIndex = SIZE_MAX;
  6525. VkDeviceSize bestFreeSpaceAfter = 0;
  6526. for(size_t i = 0; i < MAX_COUNT; ++i)
  6527. {
  6528. // Structure is valid.
  6529. if(m_FreeSpaces[i].blockInfoIndex != SIZE_MAX)
  6530. {
  6531. const VkDeviceSize dstOffset = VmaAlignUp(m_FreeSpaces[i].offset, alignment);
  6532. // Allocation fits into this structure.
  6533. if(dstOffset + size <= m_FreeSpaces[i].offset + m_FreeSpaces[i].size)
  6534. {
  6535. const VkDeviceSize freeSpaceAfter = (m_FreeSpaces[i].offset + m_FreeSpaces[i].size) -
  6536. (dstOffset + size);
  6537. if(bestIndex == SIZE_MAX || freeSpaceAfter > bestFreeSpaceAfter)
  6538. {
  6539. bestIndex = i;
  6540. bestFreeSpaceAfter = freeSpaceAfter;
  6541. }
  6542. }
  6543. }
  6544. }
  6545. if(bestIndex != SIZE_MAX)
  6546. {
  6547. outBlockInfoIndex = m_FreeSpaces[bestIndex].blockInfoIndex;
  6548. outDstOffset = VmaAlignUp(m_FreeSpaces[bestIndex].offset, alignment);
  6549. if(bestFreeSpaceAfter >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
  6550. {
  6551. // Leave this structure for remaining empty space.
  6552. const VkDeviceSize alignmentPlusSize = (outDstOffset - m_FreeSpaces[bestIndex].offset) + size;
  6553. m_FreeSpaces[bestIndex].offset += alignmentPlusSize;
  6554. m_FreeSpaces[bestIndex].size -= alignmentPlusSize;
  6555. }
  6556. else
  6557. {
  6558. // This structure becomes invalid.
  6559. m_FreeSpaces[bestIndex].blockInfoIndex = SIZE_MAX;
  6560. }
  6561. return true;
  6562. }
  6563. return false;
  6564. }
  6565. private:
  6566. static const size_t MAX_COUNT = 4;
  6567. struct FreeSpace
  6568. {
  6569. size_t blockInfoIndex; // SIZE_MAX means this structure is invalid.
  6570. VkDeviceSize offset;
  6571. VkDeviceSize size;
  6572. } m_FreeSpaces[MAX_COUNT];
  6573. };
  6574. const bool m_OverlappingMoveSupported;
  6575. uint32_t m_AllocationCount;
  6576. bool m_AllAllocations;
  6577. VkDeviceSize m_BytesMoved;
  6578. uint32_t m_AllocationsMoved;
  6579. VmaVector< BlockInfo, VmaStlAllocator<BlockInfo> > m_BlockInfos;
  6580. void PreprocessMetadata();
  6581. void PostprocessMetadata();
  6582. void InsertSuballoc(VmaBlockMetadata_Generic* pMetadata, const VmaSuballocation& suballoc);
  6583. };
  6584. struct VmaBlockDefragmentationContext
  6585. {
  6586. enum BLOCK_FLAG
  6587. {
  6588. BLOCK_FLAG_USED = 0x00000001,
  6589. };
  6590. uint32_t flags;
  6591. VkBuffer hBuffer;
  6592. };
  6593. class VmaBlockVectorDefragmentationContext
  6594. {
  6595. VMA_CLASS_NO_COPY(VmaBlockVectorDefragmentationContext)
  6596. public:
  6597. VkResult res;
  6598. bool mutexLocked;
  6599. VmaVector< VmaBlockDefragmentationContext, VmaStlAllocator<VmaBlockDefragmentationContext> > blockContexts;
  6600. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> > defragmentationMoves;
  6601. uint32_t defragmentationMovesProcessed;
  6602. uint32_t defragmentationMovesCommitted;
  6603. bool hasDefragmentationPlan;
  6604. VmaBlockVectorDefragmentationContext(
  6605. VmaAllocator hAllocator,
  6606. VmaPool hCustomPool, // Optional.
  6607. VmaBlockVector* pBlockVector,
  6608. uint32_t currFrameIndex);
  6609. ~VmaBlockVectorDefragmentationContext();
  6610. VmaPool GetCustomPool() const { return m_hCustomPool; }
  6611. VmaBlockVector* GetBlockVector() const { return m_pBlockVector; }
  6612. VmaDefragmentationAlgorithm* GetAlgorithm() const { return m_pAlgorithm; }
  6613. void AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged);
  6614. void AddAll() { m_AllAllocations = true; }
  6615. void Begin(bool overlappingMoveSupported, VmaDefragmentationFlags flags);
  6616. private:
  6617. const VmaAllocator m_hAllocator;
  6618. // Null if not from custom pool.
  6619. const VmaPool m_hCustomPool;
  6620. // Redundant, for convenience not to fetch from m_hCustomPool->m_BlockVector or m_hAllocator->m_pBlockVectors.
  6621. VmaBlockVector* const m_pBlockVector;
  6622. const uint32_t m_CurrFrameIndex;
  6623. // Owner of this object.
  6624. VmaDefragmentationAlgorithm* m_pAlgorithm;
  6625. struct AllocInfo
  6626. {
  6627. VmaAllocation hAlloc;
  6628. VkBool32* pChanged;
  6629. };
  6630. // Used between constructor and Begin.
  6631. VmaVector< AllocInfo, VmaStlAllocator<AllocInfo> > m_Allocations;
  6632. bool m_AllAllocations;
  6633. };
  6634. struct VmaDefragmentationContext_T
  6635. {
  6636. private:
  6637. VMA_CLASS_NO_COPY(VmaDefragmentationContext_T)
  6638. public:
  6639. VmaDefragmentationContext_T(
  6640. VmaAllocator hAllocator,
  6641. uint32_t currFrameIndex,
  6642. uint32_t flags,
  6643. VmaDefragmentationStats* pStats);
  6644. ~VmaDefragmentationContext_T();
  6645. void AddPools(uint32_t poolCount, const VmaPool* pPools);
  6646. void AddAllocations(
  6647. uint32_t allocationCount,
  6648. const VmaAllocation* pAllocations,
  6649. VkBool32* pAllocationsChanged);
  6650. /*
  6651. Returns:
  6652. - `VK_SUCCESS` if succeeded and object can be destroyed immediately.
  6653. - `VK_NOT_READY` if succeeded but the object must remain alive until vmaDefragmentationEnd().
  6654. - Negative value if error occurred and object can be destroyed immediately.
  6655. */
  6656. VkResult Defragment(
  6657. VkDeviceSize maxCpuBytesToMove, uint32_t maxCpuAllocationsToMove,
  6658. VkDeviceSize maxGpuBytesToMove, uint32_t maxGpuAllocationsToMove,
  6659. VkCommandBuffer commandBuffer, VmaDefragmentationStats* pStats, VmaDefragmentationFlags flags);
  6660. VkResult DefragmentPassBegin(VmaDefragmentationPassInfo* pInfo);
  6661. VkResult DefragmentPassEnd();
  6662. private:
  6663. const VmaAllocator m_hAllocator;
  6664. const uint32_t m_CurrFrameIndex;
  6665. const uint32_t m_Flags;
  6666. VmaDefragmentationStats* const m_pStats;
  6667. VkDeviceSize m_MaxCpuBytesToMove;
  6668. uint32_t m_MaxCpuAllocationsToMove;
  6669. VkDeviceSize m_MaxGpuBytesToMove;
  6670. uint32_t m_MaxGpuAllocationsToMove;
  6671. // Owner of these objects.
  6672. VmaBlockVectorDefragmentationContext* m_DefaultPoolContexts[VK_MAX_MEMORY_TYPES];
  6673. // Owner of these objects.
  6674. VmaVector< VmaBlockVectorDefragmentationContext*, VmaStlAllocator<VmaBlockVectorDefragmentationContext*> > m_CustomPoolContexts;
  6675. };
  6676. #if VMA_RECORDING_ENABLED
  6677. class VmaRecorder
  6678. {
  6679. public:
  6680. VmaRecorder();
  6681. VkResult Init(const VmaRecordSettings& settings, bool useMutex);
  6682. void WriteConfiguration(
  6683. const VkPhysicalDeviceProperties& devProps,
  6684. const VkPhysicalDeviceMemoryProperties& memProps,
  6685. uint32_t vulkanApiVersion,
  6686. bool dedicatedAllocationExtensionEnabled,
  6687. bool bindMemory2ExtensionEnabled,
  6688. bool memoryBudgetExtensionEnabled,
  6689. bool deviceCoherentMemoryExtensionEnabled);
  6690. ~VmaRecorder();
  6691. void RecordCreateAllocator(uint32_t frameIndex);
  6692. void RecordDestroyAllocator(uint32_t frameIndex);
  6693. void RecordCreatePool(uint32_t frameIndex,
  6694. const VmaPoolCreateInfo& createInfo,
  6695. VmaPool pool);
  6696. void RecordDestroyPool(uint32_t frameIndex, VmaPool pool);
  6697. void RecordAllocateMemory(uint32_t frameIndex,
  6698. const VkMemoryRequirements& vkMemReq,
  6699. const VmaAllocationCreateInfo& createInfo,
  6700. VmaAllocation allocation);
  6701. void RecordAllocateMemoryPages(uint32_t frameIndex,
  6702. const VkMemoryRequirements& vkMemReq,
  6703. const VmaAllocationCreateInfo& createInfo,
  6704. uint64_t allocationCount,
  6705. const VmaAllocation* pAllocations);
  6706. void RecordAllocateMemoryForBuffer(uint32_t frameIndex,
  6707. const VkMemoryRequirements& vkMemReq,
  6708. bool requiresDedicatedAllocation,
  6709. bool prefersDedicatedAllocation,
  6710. const VmaAllocationCreateInfo& createInfo,
  6711. VmaAllocation allocation);
  6712. void RecordAllocateMemoryForImage(uint32_t frameIndex,
  6713. const VkMemoryRequirements& vkMemReq,
  6714. bool requiresDedicatedAllocation,
  6715. bool prefersDedicatedAllocation,
  6716. const VmaAllocationCreateInfo& createInfo,
  6717. VmaAllocation allocation);
  6718. void RecordFreeMemory(uint32_t frameIndex,
  6719. VmaAllocation allocation);
  6720. void RecordFreeMemoryPages(uint32_t frameIndex,
  6721. uint64_t allocationCount,
  6722. const VmaAllocation* pAllocations);
  6723. void RecordSetAllocationUserData(uint32_t frameIndex,
  6724. VmaAllocation allocation,
  6725. const void* pUserData);
  6726. void RecordCreateLostAllocation(uint32_t frameIndex,
  6727. VmaAllocation allocation);
  6728. void RecordMapMemory(uint32_t frameIndex,
  6729. VmaAllocation allocation);
  6730. void RecordUnmapMemory(uint32_t frameIndex,
  6731. VmaAllocation allocation);
  6732. void RecordFlushAllocation(uint32_t frameIndex,
  6733. VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size);
  6734. void RecordInvalidateAllocation(uint32_t frameIndex,
  6735. VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size);
  6736. void RecordCreateBuffer(uint32_t frameIndex,
  6737. const VkBufferCreateInfo& bufCreateInfo,
  6738. const VmaAllocationCreateInfo& allocCreateInfo,
  6739. VmaAllocation allocation);
  6740. void RecordCreateImage(uint32_t frameIndex,
  6741. const VkImageCreateInfo& imageCreateInfo,
  6742. const VmaAllocationCreateInfo& allocCreateInfo,
  6743. VmaAllocation allocation);
  6744. void RecordDestroyBuffer(uint32_t frameIndex,
  6745. VmaAllocation allocation);
  6746. void RecordDestroyImage(uint32_t frameIndex,
  6747. VmaAllocation allocation);
  6748. void RecordTouchAllocation(uint32_t frameIndex,
  6749. VmaAllocation allocation);
  6750. void RecordGetAllocationInfo(uint32_t frameIndex,
  6751. VmaAllocation allocation);
  6752. void RecordMakePoolAllocationsLost(uint32_t frameIndex,
  6753. VmaPool pool);
  6754. void RecordDefragmentationBegin(uint32_t frameIndex,
  6755. const VmaDefragmentationInfo2& info,
  6756. VmaDefragmentationContext ctx);
  6757. void RecordDefragmentationEnd(uint32_t frameIndex,
  6758. VmaDefragmentationContext ctx);
  6759. void RecordSetPoolName(uint32_t frameIndex,
  6760. VmaPool pool,
  6761. const char* name);
  6762. private:
  6763. struct CallParams
  6764. {
  6765. uint32_t threadId;
  6766. double time;
  6767. };
  6768. class UserDataString
  6769. {
  6770. public:
  6771. UserDataString(VmaAllocationCreateFlags allocFlags, const void* pUserData);
  6772. const char* GetString() const { return m_Str; }
  6773. private:
  6774. char m_PtrStr[17];
  6775. const char* m_Str;
  6776. };
  6777. bool m_UseMutex;
  6778. VmaRecordFlags m_Flags;
  6779. FILE* m_File;
  6780. VMA_MUTEX m_FileMutex;
  6781. std::chrono::time_point<std::chrono::high_resolution_clock> m_RecordingStartTime;
  6782. void GetBasicParams(CallParams& outParams);
  6783. // T must be a pointer type, e.g. VmaAllocation, VmaPool.
  6784. template<typename T>
  6785. void PrintPointerList(uint64_t count, const T* pItems)
  6786. {
  6787. if(count)
  6788. {
  6789. fprintf(m_File, "%p", pItems[0]);
  6790. for(uint64_t i = 1; i < count; ++i)
  6791. {
  6792. fprintf(m_File, " %p", pItems[i]);
  6793. }
  6794. }
  6795. }
  6796. void PrintPointerList(uint64_t count, const VmaAllocation* pItems);
  6797. void Flush();
  6798. };
  6799. #endif // #if VMA_RECORDING_ENABLED
  6800. /*
  6801. Thread-safe wrapper over VmaPoolAllocator free list, for allocation of VmaAllocation_T objects.
  6802. */
  6803. class VmaAllocationObjectAllocator
  6804. {
  6805. VMA_CLASS_NO_COPY(VmaAllocationObjectAllocator)
  6806. public:
  6807. VmaAllocationObjectAllocator(const VkAllocationCallbacks* pAllocationCallbacks);
  6808. template<typename... Types> VmaAllocation Allocate(Types... args);
  6809. void Free(VmaAllocation hAlloc);
  6810. private:
  6811. VMA_MUTEX m_Mutex;
  6812. VmaPoolAllocator<VmaAllocation_T> m_Allocator;
  6813. };
  6814. struct VmaCurrentBudgetData
  6815. {
  6816. VMA_ATOMIC_UINT64 m_BlockBytes[VK_MAX_MEMORY_HEAPS];
  6817. VMA_ATOMIC_UINT64 m_AllocationBytes[VK_MAX_MEMORY_HEAPS];
  6818. #if VMA_MEMORY_BUDGET
  6819. VMA_ATOMIC_UINT32 m_OperationsSinceBudgetFetch;
  6820. VMA_RW_MUTEX m_BudgetMutex;
  6821. uint64_t m_VulkanUsage[VK_MAX_MEMORY_HEAPS];
  6822. uint64_t m_VulkanBudget[VK_MAX_MEMORY_HEAPS];
  6823. uint64_t m_BlockBytesAtBudgetFetch[VK_MAX_MEMORY_HEAPS];
  6824. #endif // #if VMA_MEMORY_BUDGET
  6825. VmaCurrentBudgetData()
  6826. {
  6827. for(uint32_t heapIndex = 0; heapIndex < VK_MAX_MEMORY_HEAPS; ++heapIndex)
  6828. {
  6829. m_BlockBytes[heapIndex] = 0;
  6830. m_AllocationBytes[heapIndex] = 0;
  6831. #if VMA_MEMORY_BUDGET
  6832. m_VulkanUsage[heapIndex] = 0;
  6833. m_VulkanBudget[heapIndex] = 0;
  6834. m_BlockBytesAtBudgetFetch[heapIndex] = 0;
  6835. #endif
  6836. }
  6837. #if VMA_MEMORY_BUDGET
  6838. m_OperationsSinceBudgetFetch = 0;
  6839. #endif
  6840. }
  6841. void AddAllocation(uint32_t heapIndex, VkDeviceSize allocationSize)
  6842. {
  6843. m_AllocationBytes[heapIndex] += allocationSize;
  6844. #if VMA_MEMORY_BUDGET
  6845. ++m_OperationsSinceBudgetFetch;
  6846. #endif
  6847. }
  6848. void RemoveAllocation(uint32_t heapIndex, VkDeviceSize allocationSize)
  6849. {
  6850. VMA_ASSERT(m_AllocationBytes[heapIndex] >= allocationSize); // DELME
  6851. m_AllocationBytes[heapIndex] -= allocationSize;
  6852. #if VMA_MEMORY_BUDGET
  6853. ++m_OperationsSinceBudgetFetch;
  6854. #endif
  6855. }
  6856. };
  6857. // Main allocator object.
  6858. struct VmaAllocator_T
  6859. {
  6860. VMA_CLASS_NO_COPY(VmaAllocator_T)
  6861. public:
  6862. bool m_UseMutex;
  6863. uint32_t m_VulkanApiVersion;
  6864. bool m_UseKhrDedicatedAllocation; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0).
  6865. bool m_UseKhrBindMemory2; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0).
  6866. bool m_UseExtMemoryBudget;
  6867. bool m_UseAmdDeviceCoherentMemory;
  6868. bool m_UseKhrBufferDeviceAddress;
  6869. bool m_UseExtMemoryPriority;
  6870. VkDevice m_hDevice;
  6871. VkInstance m_hInstance;
  6872. bool m_AllocationCallbacksSpecified;
  6873. VkAllocationCallbacks m_AllocationCallbacks;
  6874. VmaDeviceMemoryCallbacks m_DeviceMemoryCallbacks;
  6875. VmaAllocationObjectAllocator m_AllocationObjectAllocator;
  6876. // Each bit (1 << i) is set if HeapSizeLimit is enabled for that heap, so cannot allocate more than the heap size.
  6877. uint32_t m_HeapSizeLimitMask;
  6878. VkPhysicalDeviceProperties m_PhysicalDeviceProperties;
  6879. VkPhysicalDeviceMemoryProperties m_MemProps;
  6880. // Default pools.
  6881. VmaBlockVector* m_pBlockVectors[VK_MAX_MEMORY_TYPES];
  6882. VmaBlockVector* m_pSmallBufferBlockVectors[VK_MAX_MEMORY_TYPES];
  6883. typedef VmaIntrusiveLinkedList<VmaDedicatedAllocationListItemTraits> DedicatedAllocationLinkedList;
  6884. DedicatedAllocationLinkedList m_DedicatedAllocations[VK_MAX_MEMORY_TYPES];
  6885. VMA_RW_MUTEX m_DedicatedAllocationsMutex[VK_MAX_MEMORY_TYPES];
  6886. VmaCurrentBudgetData m_Budget;
  6887. VMA_ATOMIC_UINT32 m_DeviceMemoryCount; // Total number of VkDeviceMemory objects.
  6888. VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo);
  6889. VkResult Init(const VmaAllocatorCreateInfo* pCreateInfo);
  6890. ~VmaAllocator_T();
  6891. const VkAllocationCallbacks* GetAllocationCallbacks() const
  6892. {
  6893. return m_AllocationCallbacksSpecified ? &m_AllocationCallbacks : 0;
  6894. }
  6895. const VmaVulkanFunctions& GetVulkanFunctions() const
  6896. {
  6897. return m_VulkanFunctions;
  6898. }
  6899. VkPhysicalDevice GetPhysicalDevice() const { return m_PhysicalDevice; }
  6900. VkDeviceSize GetBufferImageGranularity() const
  6901. {
  6902. return VMA_MAX(
  6903. static_cast<VkDeviceSize>(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY),
  6904. m_PhysicalDeviceProperties.limits.bufferImageGranularity);
  6905. }
  6906. uint32_t GetMemoryHeapCount() const { return m_MemProps.memoryHeapCount; }
  6907. uint32_t GetMemoryTypeCount() const { return m_MemProps.memoryTypeCount; }
  6908. uint32_t MemoryTypeIndexToHeapIndex(uint32_t memTypeIndex) const
  6909. {
  6910. VMA_ASSERT(memTypeIndex < m_MemProps.memoryTypeCount);
  6911. return m_MemProps.memoryTypes[memTypeIndex].heapIndex;
  6912. }
  6913. // True when specific memory type is HOST_VISIBLE but not HOST_COHERENT.
  6914. bool IsMemoryTypeNonCoherent(uint32_t memTypeIndex) const
  6915. {
  6916. return (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) ==
  6917. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  6918. }
  6919. // Minimum alignment for all allocations in specific memory type.
  6920. VkDeviceSize GetMemoryTypeMinAlignment(uint32_t memTypeIndex) const
  6921. {
  6922. return IsMemoryTypeNonCoherent(memTypeIndex) ?
  6923. VMA_MAX((VkDeviceSize)VMA_MIN_ALIGNMENT, m_PhysicalDeviceProperties.limits.nonCoherentAtomSize) :
  6924. (VkDeviceSize)VMA_MIN_ALIGNMENT;
  6925. }
  6926. bool IsIntegratedGpu() const
  6927. {
  6928. return m_PhysicalDeviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
  6929. }
  6930. uint32_t GetGlobalMemoryTypeBits() const { return m_GlobalMemoryTypeBits; }
  6931. #if VMA_RECORDING_ENABLED
  6932. VmaRecorder* GetRecorder() const { return m_pRecorder; }
  6933. #endif
  6934. void GetBufferMemoryRequirements(
  6935. VkBuffer hBuffer,
  6936. VkMemoryRequirements& memReq,
  6937. bool& requiresDedicatedAllocation,
  6938. bool& prefersDedicatedAllocation) const;
  6939. void GetImageMemoryRequirements(
  6940. VkImage hImage,
  6941. VkMemoryRequirements& memReq,
  6942. bool& requiresDedicatedAllocation,
  6943. bool& prefersDedicatedAllocation) const;
  6944. // Main allocation function.
  6945. VkResult AllocateMemory(
  6946. const VkMemoryRequirements& vkMemReq,
  6947. bool requiresDedicatedAllocation,
  6948. bool prefersDedicatedAllocation,
  6949. VkBuffer dedicatedBuffer,
  6950. VkBufferUsageFlags dedicatedBufferUsage, // UINT32_MAX when unknown.
  6951. VkImage dedicatedImage,
  6952. const VmaAllocationCreateInfo& createInfo,
  6953. VmaSuballocationType suballocType,
  6954. size_t allocationCount,
  6955. VmaAllocation* pAllocations);
  6956. // Main deallocation function.
  6957. void FreeMemory(
  6958. size_t allocationCount,
  6959. const VmaAllocation* pAllocations);
  6960. void CalculateStats(VmaStats* pStats);
  6961. void GetBudget(
  6962. VmaBudget* outBudget, uint32_t firstHeap, uint32_t heapCount);
  6963. #if VMA_STATS_STRING_ENABLED
  6964. void PrintDetailedMap(class VmaJsonWriter& json);
  6965. #endif
  6966. VkResult DefragmentationBegin(
  6967. const VmaDefragmentationInfo2& info,
  6968. VmaDefragmentationStats* pStats,
  6969. VmaDefragmentationContext* pContext);
  6970. VkResult DefragmentationEnd(
  6971. VmaDefragmentationContext context);
  6972. VkResult DefragmentationPassBegin(
  6973. VmaDefragmentationPassInfo* pInfo,
  6974. VmaDefragmentationContext context);
  6975. VkResult DefragmentationPassEnd(
  6976. VmaDefragmentationContext context);
  6977. void GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo);
  6978. bool TouchAllocation(VmaAllocation hAllocation);
  6979. VkResult CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool);
  6980. void DestroyPool(VmaPool pool);
  6981. void GetPoolStats(VmaPool pool, VmaPoolStats* pPoolStats);
  6982. void SetCurrentFrameIndex(uint32_t frameIndex);
  6983. uint32_t GetCurrentFrameIndex() const { return m_CurrentFrameIndex.load(); }
  6984. void MakePoolAllocationsLost(
  6985. VmaPool hPool,
  6986. size_t* pLostAllocationCount);
  6987. VkResult CheckPoolCorruption(VmaPool hPool);
  6988. VkResult CheckCorruption(uint32_t memoryTypeBits);
  6989. void CreateLostAllocation(VmaAllocation* pAllocation);
  6990. // Call to Vulkan function vkAllocateMemory with accompanying bookkeeping.
  6991. VkResult AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory);
  6992. // Call to Vulkan function vkFreeMemory with accompanying bookkeeping.
  6993. void FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory);
  6994. // Call to Vulkan function vkBindBufferMemory or vkBindBufferMemory2KHR.
  6995. VkResult BindVulkanBuffer(
  6996. VkDeviceMemory memory,
  6997. VkDeviceSize memoryOffset,
  6998. VkBuffer buffer,
  6999. const void* pNext);
  7000. // Call to Vulkan function vkBindImageMemory or vkBindImageMemory2KHR.
  7001. VkResult BindVulkanImage(
  7002. VkDeviceMemory memory,
  7003. VkDeviceSize memoryOffset,
  7004. VkImage image,
  7005. const void* pNext);
  7006. VkResult Map(VmaAllocation hAllocation, void** ppData);
  7007. void Unmap(VmaAllocation hAllocation);
  7008. VkResult BindBufferMemory(
  7009. VmaAllocation hAllocation,
  7010. VkDeviceSize allocationLocalOffset,
  7011. VkBuffer hBuffer,
  7012. const void* pNext);
  7013. VkResult BindImageMemory(
  7014. VmaAllocation hAllocation,
  7015. VkDeviceSize allocationLocalOffset,
  7016. VkImage hImage,
  7017. const void* pNext);
  7018. VkResult FlushOrInvalidateAllocation(
  7019. VmaAllocation hAllocation,
  7020. VkDeviceSize offset, VkDeviceSize size,
  7021. VMA_CACHE_OPERATION op);
  7022. VkResult FlushOrInvalidateAllocations(
  7023. uint32_t allocationCount,
  7024. const VmaAllocation* allocations,
  7025. const VkDeviceSize* offsets, const VkDeviceSize* sizes,
  7026. VMA_CACHE_OPERATION op);
  7027. void FillAllocation(const VmaAllocation hAllocation, uint8_t pattern);
  7028. /*
  7029. Returns bit mask of memory types that can support defragmentation on GPU as
  7030. they support creation of required buffer for copy operations.
  7031. */
  7032. uint32_t GetGpuDefragmentationMemoryTypeBits();
  7033. #if VMA_EXTERNAL_MEMORY
  7034. VkExternalMemoryHandleTypeFlagsKHR GetExternalMemoryHandleTypeFlags(uint32_t memTypeIndex) const
  7035. {
  7036. return m_TypeExternalMemoryHandleTypes[memTypeIndex];
  7037. }
  7038. #endif // #if VMA_EXTERNAL_MEMORY
  7039. private:
  7040. VkDeviceSize m_PreferredLargeHeapBlockSize;
  7041. VkPhysicalDevice m_PhysicalDevice;
  7042. VMA_ATOMIC_UINT32 m_CurrentFrameIndex;
  7043. VMA_ATOMIC_UINT32 m_GpuDefragmentationMemoryTypeBits; // UINT32_MAX means uninitialized.
  7044. #if VMA_EXTERNAL_MEMORY
  7045. VkExternalMemoryHandleTypeFlagsKHR m_TypeExternalMemoryHandleTypes[VK_MAX_MEMORY_TYPES];
  7046. #endif // #if VMA_EXTERNAL_MEMORY
  7047. VMA_RW_MUTEX m_PoolsMutex;
  7048. typedef VmaIntrusiveLinkedList<VmaPoolListItemTraits> PoolList;
  7049. // Protected by m_PoolsMutex.
  7050. PoolList m_Pools;
  7051. uint32_t m_NextPoolId;
  7052. VmaVulkanFunctions m_VulkanFunctions;
  7053. // Global bit mask AND-ed with any memoryTypeBits to disallow certain memory types.
  7054. uint32_t m_GlobalMemoryTypeBits;
  7055. #if VMA_RECORDING_ENABLED
  7056. VmaRecorder* m_pRecorder;
  7057. #endif
  7058. void ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions);
  7059. #if VMA_STATIC_VULKAN_FUNCTIONS == 1
  7060. void ImportVulkanFunctions_Static();
  7061. #endif
  7062. void ImportVulkanFunctions_Custom(const VmaVulkanFunctions* pVulkanFunctions);
  7063. #if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1
  7064. void ImportVulkanFunctions_Dynamic();
  7065. #endif
  7066. void ValidateVulkanFunctions();
  7067. VkDeviceSize CalcPreferredBlockSize(uint32_t memTypeIndex);
  7068. VkResult AllocateMemoryOfType(
  7069. VkDeviceSize size,
  7070. VkDeviceSize alignment,
  7071. bool dedicatedAllocation,
  7072. VkBuffer dedicatedBuffer,
  7073. VkBufferUsageFlags dedicatedBufferUsage,
  7074. VkImage dedicatedImage,
  7075. const VmaAllocationCreateInfo& createInfo,
  7076. uint32_t memTypeIndex,
  7077. VmaSuballocationType suballocType,
  7078. size_t allocationCount,
  7079. VmaAllocation* pAllocations);
  7080. // Helper function only to be used inside AllocateDedicatedMemory.
  7081. VkResult AllocateDedicatedMemoryPage(
  7082. VkDeviceSize size,
  7083. VmaSuballocationType suballocType,
  7084. uint32_t memTypeIndex,
  7085. const VkMemoryAllocateInfo& allocInfo,
  7086. bool map,
  7087. bool isUserDataString,
  7088. void* pUserData,
  7089. VmaAllocation* pAllocation);
  7090. // Allocates and registers new VkDeviceMemory specifically for dedicated allocations.
  7091. VkResult AllocateDedicatedMemory(
  7092. VkDeviceSize size,
  7093. VmaSuballocationType suballocType,
  7094. uint32_t memTypeIndex,
  7095. bool withinBudget,
  7096. bool map,
  7097. bool isUserDataString,
  7098. void* pUserData,
  7099. float priority,
  7100. VkBuffer dedicatedBuffer,
  7101. VkBufferUsageFlags dedicatedBufferUsage,
  7102. VkImage dedicatedImage,
  7103. size_t allocationCount,
  7104. VmaAllocation* pAllocations);
  7105. void FreeDedicatedMemory(const VmaAllocation allocation);
  7106. /*
  7107. Calculates and returns bit mask of memory types that can support defragmentation
  7108. on GPU as they support creation of required buffer for copy operations.
  7109. */
  7110. uint32_t CalculateGpuDefragmentationMemoryTypeBits() const;
  7111. uint32_t CalculateGlobalMemoryTypeBits() const;
  7112. bool GetFlushOrInvalidateRange(
  7113. VmaAllocation allocation,
  7114. VkDeviceSize offset, VkDeviceSize size,
  7115. VkMappedMemoryRange& outRange) const;
  7116. #if VMA_MEMORY_BUDGET
  7117. void UpdateVulkanBudget();
  7118. #endif // #if VMA_MEMORY_BUDGET
  7119. };
  7120. ////////////////////////////////////////////////////////////////////////////////
  7121. // Memory allocation #2 after VmaAllocator_T definition
  7122. static void* VmaMalloc(VmaAllocator hAllocator, size_t size, size_t alignment)
  7123. {
  7124. return VmaMalloc(&hAllocator->m_AllocationCallbacks, size, alignment);
  7125. }
  7126. static void VmaFree(VmaAllocator hAllocator, void* ptr)
  7127. {
  7128. VmaFree(&hAllocator->m_AllocationCallbacks, ptr);
  7129. }
  7130. template<typename T>
  7131. static T* VmaAllocate(VmaAllocator hAllocator)
  7132. {
  7133. return (T*)VmaMalloc(hAllocator, sizeof(T), VMA_ALIGN_OF(T));
  7134. }
  7135. template<typename T>
  7136. static T* VmaAllocateArray(VmaAllocator hAllocator, size_t count)
  7137. {
  7138. return (T*)VmaMalloc(hAllocator, sizeof(T) * count, VMA_ALIGN_OF(T));
  7139. }
  7140. template<typename T>
  7141. static void vma_delete(VmaAllocator hAllocator, T* ptr)
  7142. {
  7143. if(ptr != VMA_NULL)
  7144. {
  7145. ptr->~T();
  7146. VmaFree(hAllocator, ptr);
  7147. }
  7148. }
  7149. template<typename T>
  7150. static void vma_delete_array(VmaAllocator hAllocator, T* ptr, size_t count)
  7151. {
  7152. if(ptr != VMA_NULL)
  7153. {
  7154. for(size_t i = count; i--; )
  7155. ptr[i].~T();
  7156. VmaFree(hAllocator, ptr);
  7157. }
  7158. }
  7159. ////////////////////////////////////////////////////////////////////////////////
  7160. // VmaStringBuilder
  7161. #if VMA_STATS_STRING_ENABLED
  7162. class VmaStringBuilder
  7163. {
  7164. public:
  7165. VmaStringBuilder(VmaAllocator alloc) : m_Data(VmaStlAllocator<char>(alloc->GetAllocationCallbacks())) { }
  7166. size_t GetLength() const { return m_Data.size(); }
  7167. const char* GetData() const { return m_Data.data(); }
  7168. void Add(char ch) { m_Data.push_back(ch); }
  7169. void Add(const char* pStr);
  7170. void AddNewLine() { Add('\n'); }
  7171. void AddNumber(uint32_t num);
  7172. void AddNumber(uint64_t num);
  7173. void AddPointer(const void* ptr);
  7174. private:
  7175. VmaVector< char, VmaStlAllocator<char> > m_Data;
  7176. };
  7177. void VmaStringBuilder::Add(const char* pStr)
  7178. {
  7179. const size_t strLen = strlen(pStr);
  7180. if(strLen > 0)
  7181. {
  7182. const size_t oldCount = m_Data.size();
  7183. m_Data.resize(oldCount + strLen);
  7184. memcpy(m_Data.data() + oldCount, pStr, strLen);
  7185. }
  7186. }
  7187. void VmaStringBuilder::AddNumber(uint32_t num)
  7188. {
  7189. char buf[11];
  7190. buf[10] = '\0';
  7191. char *p = &buf[10];
  7192. do
  7193. {
  7194. *--p = '0' + (num % 10);
  7195. num /= 10;
  7196. }
  7197. while(num);
  7198. Add(p);
  7199. }
  7200. void VmaStringBuilder::AddNumber(uint64_t num)
  7201. {
  7202. char buf[21];
  7203. buf[20] = '\0';
  7204. char *p = &buf[20];
  7205. do
  7206. {
  7207. *--p = '0' + (num % 10);
  7208. num /= 10;
  7209. }
  7210. while(num);
  7211. Add(p);
  7212. }
  7213. void VmaStringBuilder::AddPointer(const void* ptr)
  7214. {
  7215. char buf[21];
  7216. VmaPtrToStr(buf, sizeof(buf), ptr);
  7217. Add(buf);
  7218. }
  7219. #endif // #if VMA_STATS_STRING_ENABLED
  7220. ////////////////////////////////////////////////////////////////////////////////
  7221. // VmaJsonWriter
  7222. #if VMA_STATS_STRING_ENABLED
  7223. class VmaJsonWriter
  7224. {
  7225. VMA_CLASS_NO_COPY(VmaJsonWriter)
  7226. public:
  7227. VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb);
  7228. ~VmaJsonWriter();
  7229. void BeginObject(bool singleLine = false);
  7230. void EndObject();
  7231. void BeginArray(bool singleLine = false);
  7232. void EndArray();
  7233. void WriteString(const char* pStr);
  7234. void BeginString(const char* pStr = VMA_NULL);
  7235. void ContinueString(const char* pStr);
  7236. void ContinueString(uint32_t n);
  7237. void ContinueString(uint64_t n);
  7238. void ContinueString_Pointer(const void* ptr);
  7239. void EndString(const char* pStr = VMA_NULL);
  7240. void WriteNumber(uint32_t n);
  7241. void WriteNumber(uint64_t n);
  7242. void WriteBool(bool b);
  7243. void WriteNull();
  7244. private:
  7245. static const char* const INDENT;
  7246. enum COLLECTION_TYPE
  7247. {
  7248. COLLECTION_TYPE_OBJECT,
  7249. COLLECTION_TYPE_ARRAY,
  7250. };
  7251. struct StackItem
  7252. {
  7253. COLLECTION_TYPE type;
  7254. uint32_t valueCount;
  7255. bool singleLineMode;
  7256. };
  7257. VmaStringBuilder& m_SB;
  7258. VmaVector< StackItem, VmaStlAllocator<StackItem> > m_Stack;
  7259. bool m_InsideString;
  7260. void BeginValue(bool isString);
  7261. void WriteIndent(bool oneLess = false);
  7262. };
  7263. const char* const VmaJsonWriter::INDENT = " ";
  7264. VmaJsonWriter::VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb) :
  7265. m_SB(sb),
  7266. m_Stack(VmaStlAllocator<StackItem>(pAllocationCallbacks)),
  7267. m_InsideString(false)
  7268. {
  7269. }
  7270. VmaJsonWriter::~VmaJsonWriter()
  7271. {
  7272. VMA_ASSERT(!m_InsideString);
  7273. VMA_ASSERT(m_Stack.empty());
  7274. }
  7275. void VmaJsonWriter::BeginObject(bool singleLine)
  7276. {
  7277. VMA_ASSERT(!m_InsideString);
  7278. BeginValue(false);
  7279. m_SB.Add('{');
  7280. StackItem item;
  7281. item.type = COLLECTION_TYPE_OBJECT;
  7282. item.valueCount = 0;
  7283. item.singleLineMode = singleLine;
  7284. m_Stack.push_back(item);
  7285. }
  7286. void VmaJsonWriter::EndObject()
  7287. {
  7288. VMA_ASSERT(!m_InsideString);
  7289. WriteIndent(true);
  7290. m_SB.Add('}');
  7291. VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_OBJECT);
  7292. m_Stack.pop_back();
  7293. }
  7294. void VmaJsonWriter::BeginArray(bool singleLine)
  7295. {
  7296. VMA_ASSERT(!m_InsideString);
  7297. BeginValue(false);
  7298. m_SB.Add('[');
  7299. StackItem item;
  7300. item.type = COLLECTION_TYPE_ARRAY;
  7301. item.valueCount = 0;
  7302. item.singleLineMode = singleLine;
  7303. m_Stack.push_back(item);
  7304. }
  7305. void VmaJsonWriter::EndArray()
  7306. {
  7307. VMA_ASSERT(!m_InsideString);
  7308. WriteIndent(true);
  7309. m_SB.Add(']');
  7310. VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_ARRAY);
  7311. m_Stack.pop_back();
  7312. }
  7313. void VmaJsonWriter::WriteString(const char* pStr)
  7314. {
  7315. BeginString(pStr);
  7316. EndString();
  7317. }
  7318. void VmaJsonWriter::BeginString(const char* pStr)
  7319. {
  7320. VMA_ASSERT(!m_InsideString);
  7321. BeginValue(true);
  7322. m_SB.Add('"');
  7323. m_InsideString = true;
  7324. if(pStr != VMA_NULL && pStr[0] != '\0')
  7325. {
  7326. ContinueString(pStr);
  7327. }
  7328. }
  7329. void VmaJsonWriter::ContinueString(const char* pStr)
  7330. {
  7331. VMA_ASSERT(m_InsideString);
  7332. const size_t strLen = strlen(pStr);
  7333. for(size_t i = 0; i < strLen; ++i)
  7334. {
  7335. char ch = pStr[i];
  7336. if(ch == '\\')
  7337. {
  7338. m_SB.Add("\\\\");
  7339. }
  7340. else if(ch == '"')
  7341. {
  7342. m_SB.Add("\\\"");
  7343. }
  7344. else if(ch >= 32)
  7345. {
  7346. m_SB.Add(ch);
  7347. }
  7348. else switch(ch)
  7349. {
  7350. case '\b':
  7351. m_SB.Add("\\b");
  7352. break;
  7353. case '\f':
  7354. m_SB.Add("\\f");
  7355. break;
  7356. case '\n':
  7357. m_SB.Add("\\n");
  7358. break;
  7359. case '\r':
  7360. m_SB.Add("\\r");
  7361. break;
  7362. case '\t':
  7363. m_SB.Add("\\t");
  7364. break;
  7365. default:
  7366. VMA_ASSERT(0 && "Character not currently supported.");
  7367. break;
  7368. }
  7369. }
  7370. }
  7371. void VmaJsonWriter::ContinueString(uint32_t n)
  7372. {
  7373. VMA_ASSERT(m_InsideString);
  7374. m_SB.AddNumber(n);
  7375. }
  7376. void VmaJsonWriter::ContinueString(uint64_t n)
  7377. {
  7378. VMA_ASSERT(m_InsideString);
  7379. m_SB.AddNumber(n);
  7380. }
  7381. void VmaJsonWriter::ContinueString_Pointer(const void* ptr)
  7382. {
  7383. VMA_ASSERT(m_InsideString);
  7384. m_SB.AddPointer(ptr);
  7385. }
  7386. void VmaJsonWriter::EndString(const char* pStr)
  7387. {
  7388. VMA_ASSERT(m_InsideString);
  7389. if(pStr != VMA_NULL && pStr[0] != '\0')
  7390. {
  7391. ContinueString(pStr);
  7392. }
  7393. m_SB.Add('"');
  7394. m_InsideString = false;
  7395. }
  7396. void VmaJsonWriter::WriteNumber(uint32_t n)
  7397. {
  7398. VMA_ASSERT(!m_InsideString);
  7399. BeginValue(false);
  7400. m_SB.AddNumber(n);
  7401. }
  7402. void VmaJsonWriter::WriteNumber(uint64_t n)
  7403. {
  7404. VMA_ASSERT(!m_InsideString);
  7405. BeginValue(false);
  7406. m_SB.AddNumber(n);
  7407. }
  7408. void VmaJsonWriter::WriteBool(bool b)
  7409. {
  7410. VMA_ASSERT(!m_InsideString);
  7411. BeginValue(false);
  7412. m_SB.Add(b ? "true" : "false");
  7413. }
  7414. void VmaJsonWriter::WriteNull()
  7415. {
  7416. VMA_ASSERT(!m_InsideString);
  7417. BeginValue(false);
  7418. m_SB.Add("null");
  7419. }
  7420. void VmaJsonWriter::BeginValue(bool isString)
  7421. {
  7422. if(!m_Stack.empty())
  7423. {
  7424. StackItem& currItem = m_Stack.back();
  7425. if(currItem.type == COLLECTION_TYPE_OBJECT &&
  7426. currItem.valueCount % 2 == 0)
  7427. {
  7428. VMA_ASSERT(isString);
  7429. }
  7430. if(currItem.type == COLLECTION_TYPE_OBJECT &&
  7431. currItem.valueCount % 2 != 0)
  7432. {
  7433. m_SB.Add(": ");
  7434. }
  7435. else if(currItem.valueCount > 0)
  7436. {
  7437. m_SB.Add(", ");
  7438. WriteIndent();
  7439. }
  7440. else
  7441. {
  7442. WriteIndent();
  7443. }
  7444. ++currItem.valueCount;
  7445. }
  7446. }
  7447. void VmaJsonWriter::WriteIndent(bool oneLess)
  7448. {
  7449. if(!m_Stack.empty() && !m_Stack.back().singleLineMode)
  7450. {
  7451. m_SB.AddNewLine();
  7452. size_t count = m_Stack.size();
  7453. if(count > 0 && oneLess)
  7454. {
  7455. --count;
  7456. }
  7457. for(size_t i = 0; i < count; ++i)
  7458. {
  7459. m_SB.Add(INDENT);
  7460. }
  7461. }
  7462. }
  7463. #endif // #if VMA_STATS_STRING_ENABLED
  7464. ////////////////////////////////////////////////////////////////////////////////
  7465. void VmaAllocation_T::SetUserData(VmaAllocator hAllocator, void* pUserData)
  7466. {
  7467. if(IsUserDataString())
  7468. {
  7469. VMA_ASSERT(pUserData == VMA_NULL || pUserData != m_pUserData);
  7470. FreeUserDataString(hAllocator);
  7471. if(pUserData != VMA_NULL)
  7472. {
  7473. m_pUserData = VmaCreateStringCopy(hAllocator->GetAllocationCallbacks(), (const char*)pUserData);
  7474. }
  7475. }
  7476. else
  7477. {
  7478. m_pUserData = pUserData;
  7479. }
  7480. }
  7481. void VmaAllocation_T::ChangeBlockAllocation(
  7482. VmaAllocator hAllocator,
  7483. VmaDeviceMemoryBlock* block,
  7484. VkDeviceSize offset)
  7485. {
  7486. VMA_ASSERT(block != VMA_NULL);
  7487. VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK);
  7488. // Move mapping reference counter from old block to new block.
  7489. if(block != m_BlockAllocation.m_Block)
  7490. {
  7491. uint32_t mapRefCount = m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP;
  7492. if(IsPersistentMap())
  7493. ++mapRefCount;
  7494. m_BlockAllocation.m_Block->Unmap(hAllocator, mapRefCount);
  7495. block->Map(hAllocator, mapRefCount, VMA_NULL);
  7496. }
  7497. m_BlockAllocation.m_Block = block;
  7498. m_BlockAllocation.m_Offset = offset;
  7499. }
  7500. void VmaAllocation_T::ChangeOffset(VkDeviceSize newOffset)
  7501. {
  7502. VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK);
  7503. m_BlockAllocation.m_Offset = newOffset;
  7504. }
  7505. VkDeviceSize VmaAllocation_T::GetOffset() const
  7506. {
  7507. switch(m_Type)
  7508. {
  7509. case ALLOCATION_TYPE_BLOCK:
  7510. return m_BlockAllocation.m_Offset;
  7511. case ALLOCATION_TYPE_DEDICATED:
  7512. return 0;
  7513. default:
  7514. VMA_ASSERT(0);
  7515. return 0;
  7516. }
  7517. }
  7518. VkDeviceMemory VmaAllocation_T::GetMemory() const
  7519. {
  7520. switch(m_Type)
  7521. {
  7522. case ALLOCATION_TYPE_BLOCK:
  7523. return m_BlockAllocation.m_Block->GetDeviceMemory();
  7524. case ALLOCATION_TYPE_DEDICATED:
  7525. return m_DedicatedAllocation.m_hMemory;
  7526. default:
  7527. VMA_ASSERT(0);
  7528. return VK_NULL_HANDLE;
  7529. }
  7530. }
  7531. void* VmaAllocation_T::GetMappedData() const
  7532. {
  7533. switch(m_Type)
  7534. {
  7535. case ALLOCATION_TYPE_BLOCK:
  7536. if(m_MapCount != 0)
  7537. {
  7538. void* pBlockData = m_BlockAllocation.m_Block->GetMappedData();
  7539. VMA_ASSERT(pBlockData != VMA_NULL);
  7540. return (char*)pBlockData + m_BlockAllocation.m_Offset;
  7541. }
  7542. else
  7543. {
  7544. return VMA_NULL;
  7545. }
  7546. break;
  7547. case ALLOCATION_TYPE_DEDICATED:
  7548. VMA_ASSERT((m_DedicatedAllocation.m_pMappedData != VMA_NULL) == (m_MapCount != 0));
  7549. return m_DedicatedAllocation.m_pMappedData;
  7550. default:
  7551. VMA_ASSERT(0);
  7552. return VMA_NULL;
  7553. }
  7554. }
  7555. bool VmaAllocation_T::CanBecomeLost() const
  7556. {
  7557. switch(m_Type)
  7558. {
  7559. case ALLOCATION_TYPE_BLOCK:
  7560. return m_BlockAllocation.m_CanBecomeLost;
  7561. case ALLOCATION_TYPE_DEDICATED:
  7562. return false;
  7563. default:
  7564. VMA_ASSERT(0);
  7565. return false;
  7566. }
  7567. }
  7568. bool VmaAllocation_T::MakeLost(uint32_t currentFrameIndex, uint32_t frameInUseCount)
  7569. {
  7570. VMA_ASSERT(CanBecomeLost());
  7571. /*
  7572. Warning: This is a carefully designed algorithm.
  7573. Do not modify unless you really know what you're doing :)
  7574. */
  7575. uint32_t localLastUseFrameIndex = GetLastUseFrameIndex();
  7576. for(;;)
  7577. {
  7578. if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST)
  7579. {
  7580. VMA_ASSERT(0);
  7581. return false;
  7582. }
  7583. else if(localLastUseFrameIndex + frameInUseCount >= currentFrameIndex)
  7584. {
  7585. return false;
  7586. }
  7587. else // Last use time earlier than current time.
  7588. {
  7589. if(CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, VMA_FRAME_INDEX_LOST))
  7590. {
  7591. // Setting hAllocation.LastUseFrameIndex atomic to VMA_FRAME_INDEX_LOST is enough to mark it as LOST.
  7592. // Calling code just needs to unregister this allocation in owning VmaDeviceMemoryBlock.
  7593. return true;
  7594. }
  7595. }
  7596. }
  7597. }
  7598. #if VMA_STATS_STRING_ENABLED
  7599. // Correspond to values of enum VmaSuballocationType.
  7600. static const char* VMA_SUBALLOCATION_TYPE_NAMES[] = {
  7601. "FREE",
  7602. "UNKNOWN",
  7603. "BUFFER",
  7604. "IMAGE_UNKNOWN",
  7605. "IMAGE_LINEAR",
  7606. "IMAGE_OPTIMAL",
  7607. };
  7608. void VmaAllocation_T::PrintParameters(class VmaJsonWriter& json) const
  7609. {
  7610. json.WriteString("Type");
  7611. json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[m_SuballocationType]);
  7612. json.WriteString("Size");
  7613. json.WriteNumber(m_Size);
  7614. if(m_pUserData != VMA_NULL)
  7615. {
  7616. json.WriteString("UserData");
  7617. if(IsUserDataString())
  7618. {
  7619. json.WriteString((const char*)m_pUserData);
  7620. }
  7621. else
  7622. {
  7623. json.BeginString();
  7624. json.ContinueString_Pointer(m_pUserData);
  7625. json.EndString();
  7626. }
  7627. }
  7628. json.WriteString("CreationFrameIndex");
  7629. json.WriteNumber(m_CreationFrameIndex);
  7630. json.WriteString("LastUseFrameIndex");
  7631. json.WriteNumber(GetLastUseFrameIndex());
  7632. if(m_BufferImageUsage != 0)
  7633. {
  7634. json.WriteString("Usage");
  7635. json.WriteNumber(m_BufferImageUsage);
  7636. }
  7637. }
  7638. #endif
  7639. void VmaAllocation_T::FreeUserDataString(VmaAllocator hAllocator)
  7640. {
  7641. VMA_ASSERT(IsUserDataString());
  7642. VmaFreeString(hAllocator->GetAllocationCallbacks(), (char*)m_pUserData);
  7643. m_pUserData = VMA_NULL;
  7644. }
  7645. void VmaAllocation_T::BlockAllocMap()
  7646. {
  7647. VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK);
  7648. if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) < 0x7F)
  7649. {
  7650. ++m_MapCount;
  7651. }
  7652. else
  7653. {
  7654. VMA_ASSERT(0 && "Allocation mapped too many times simultaneously.");
  7655. }
  7656. }
  7657. void VmaAllocation_T::BlockAllocUnmap()
  7658. {
  7659. VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK);
  7660. if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) != 0)
  7661. {
  7662. --m_MapCount;
  7663. }
  7664. else
  7665. {
  7666. VMA_ASSERT(0 && "Unmapping allocation not previously mapped.");
  7667. }
  7668. }
  7669. VkResult VmaAllocation_T::DedicatedAllocMap(VmaAllocator hAllocator, void** ppData)
  7670. {
  7671. VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED);
  7672. if(m_MapCount != 0)
  7673. {
  7674. if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) < 0x7F)
  7675. {
  7676. VMA_ASSERT(m_DedicatedAllocation.m_pMappedData != VMA_NULL);
  7677. *ppData = m_DedicatedAllocation.m_pMappedData;
  7678. ++m_MapCount;
  7679. return VK_SUCCESS;
  7680. }
  7681. else
  7682. {
  7683. VMA_ASSERT(0 && "Dedicated allocation mapped too many times simultaneously.");
  7684. return VK_ERROR_MEMORY_MAP_FAILED;
  7685. }
  7686. }
  7687. else
  7688. {
  7689. VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)(
  7690. hAllocator->m_hDevice,
  7691. m_DedicatedAllocation.m_hMemory,
  7692. 0, // offset
  7693. VK_WHOLE_SIZE,
  7694. 0, // flags
  7695. ppData);
  7696. if(result == VK_SUCCESS)
  7697. {
  7698. m_DedicatedAllocation.m_pMappedData = *ppData;
  7699. m_MapCount = 1;
  7700. }
  7701. return result;
  7702. }
  7703. }
  7704. void VmaAllocation_T::DedicatedAllocUnmap(VmaAllocator hAllocator)
  7705. {
  7706. VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED);
  7707. if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) != 0)
  7708. {
  7709. --m_MapCount;
  7710. if(m_MapCount == 0)
  7711. {
  7712. m_DedicatedAllocation.m_pMappedData = VMA_NULL;
  7713. (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(
  7714. hAllocator->m_hDevice,
  7715. m_DedicatedAllocation.m_hMemory);
  7716. }
  7717. }
  7718. else
  7719. {
  7720. VMA_ASSERT(0 && "Unmapping dedicated allocation not previously mapped.");
  7721. }
  7722. }
  7723. #if VMA_STATS_STRING_ENABLED
  7724. static void VmaPrintStatInfo(VmaJsonWriter& json, const VmaStatInfo& stat)
  7725. {
  7726. json.BeginObject();
  7727. json.WriteString("Blocks");
  7728. json.WriteNumber(stat.blockCount);
  7729. json.WriteString("Allocations");
  7730. json.WriteNumber(stat.allocationCount);
  7731. json.WriteString("UnusedRanges");
  7732. json.WriteNumber(stat.unusedRangeCount);
  7733. json.WriteString("UsedBytes");
  7734. json.WriteNumber(stat.usedBytes);
  7735. json.WriteString("UnusedBytes");
  7736. json.WriteNumber(stat.unusedBytes);
  7737. if(stat.allocationCount > 1)
  7738. {
  7739. json.WriteString("AllocationSize");
  7740. json.BeginObject(true);
  7741. json.WriteString("Min");
  7742. json.WriteNumber(stat.allocationSizeMin);
  7743. json.WriteString("Avg");
  7744. json.WriteNumber(stat.allocationSizeAvg);
  7745. json.WriteString("Max");
  7746. json.WriteNumber(stat.allocationSizeMax);
  7747. json.EndObject();
  7748. }
  7749. if(stat.unusedRangeCount > 1)
  7750. {
  7751. json.WriteString("UnusedRangeSize");
  7752. json.BeginObject(true);
  7753. json.WriteString("Min");
  7754. json.WriteNumber(stat.unusedRangeSizeMin);
  7755. json.WriteString("Avg");
  7756. json.WriteNumber(stat.unusedRangeSizeAvg);
  7757. json.WriteString("Max");
  7758. json.WriteNumber(stat.unusedRangeSizeMax);
  7759. json.EndObject();
  7760. }
  7761. json.EndObject();
  7762. }
  7763. #endif // #if VMA_STATS_STRING_ENABLED
  7764. struct VmaSuballocationItemSizeLess
  7765. {
  7766. bool operator()(
  7767. const VmaSuballocationList::iterator lhs,
  7768. const VmaSuballocationList::iterator rhs) const
  7769. {
  7770. return lhs->size < rhs->size;
  7771. }
  7772. bool operator()(
  7773. const VmaSuballocationList::iterator lhs,
  7774. VkDeviceSize rhsSize) const
  7775. {
  7776. return lhs->size < rhsSize;
  7777. }
  7778. };
  7779. ////////////////////////////////////////////////////////////////////////////////
  7780. // class VmaBlockMetadata
  7781. VmaBlockMetadata::VmaBlockMetadata(VmaAllocator hAllocator) :
  7782. m_Size(0),
  7783. m_pAllocationCallbacks(hAllocator->GetAllocationCallbacks())
  7784. {
  7785. }
  7786. #if VMA_STATS_STRING_ENABLED
  7787. void VmaBlockMetadata::PrintDetailedMap_Begin(class VmaJsonWriter& json,
  7788. VkDeviceSize unusedBytes,
  7789. size_t allocationCount,
  7790. size_t unusedRangeCount) const
  7791. {
  7792. json.BeginObject();
  7793. json.WriteString("TotalBytes");
  7794. json.WriteNumber(GetSize());
  7795. json.WriteString("UnusedBytes");
  7796. json.WriteNumber(unusedBytes);
  7797. json.WriteString("Allocations");
  7798. json.WriteNumber((uint64_t)allocationCount);
  7799. json.WriteString("UnusedRanges");
  7800. json.WriteNumber((uint64_t)unusedRangeCount);
  7801. json.WriteString("Suballocations");
  7802. json.BeginArray();
  7803. }
  7804. void VmaBlockMetadata::PrintDetailedMap_Allocation(class VmaJsonWriter& json,
  7805. VkDeviceSize offset,
  7806. VmaAllocation hAllocation) const
  7807. {
  7808. json.BeginObject(true);
  7809. json.WriteString("Offset");
  7810. json.WriteNumber(offset);
  7811. hAllocation->PrintParameters(json);
  7812. json.EndObject();
  7813. }
  7814. void VmaBlockMetadata::PrintDetailedMap_UnusedRange(class VmaJsonWriter& json,
  7815. VkDeviceSize offset,
  7816. VkDeviceSize size) const
  7817. {
  7818. json.BeginObject(true);
  7819. json.WriteString("Offset");
  7820. json.WriteNumber(offset);
  7821. json.WriteString("Type");
  7822. json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[VMA_SUBALLOCATION_TYPE_FREE]);
  7823. json.WriteString("Size");
  7824. json.WriteNumber(size);
  7825. json.EndObject();
  7826. }
  7827. void VmaBlockMetadata::PrintDetailedMap_End(class VmaJsonWriter& json) const
  7828. {
  7829. json.EndArray();
  7830. json.EndObject();
  7831. }
  7832. #endif // #if VMA_STATS_STRING_ENABLED
  7833. ////////////////////////////////////////////////////////////////////////////////
  7834. // class VmaBlockMetadata_Generic
  7835. VmaBlockMetadata_Generic::VmaBlockMetadata_Generic(VmaAllocator hAllocator) :
  7836. VmaBlockMetadata(hAllocator),
  7837. m_FreeCount(0),
  7838. m_SumFreeSize(0),
  7839. m_Suballocations(VmaStlAllocator<VmaSuballocation>(hAllocator->GetAllocationCallbacks())),
  7840. m_FreeSuballocationsBySize(VmaStlAllocator<VmaSuballocationList::iterator>(hAllocator->GetAllocationCallbacks()))
  7841. {
  7842. }
  7843. VmaBlockMetadata_Generic::~VmaBlockMetadata_Generic()
  7844. {
  7845. }
  7846. void VmaBlockMetadata_Generic::Init(VkDeviceSize size)
  7847. {
  7848. VmaBlockMetadata::Init(size);
  7849. m_FreeCount = 1;
  7850. m_SumFreeSize = size;
  7851. VmaSuballocation suballoc = {};
  7852. suballoc.offset = 0;
  7853. suballoc.size = size;
  7854. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  7855. suballoc.hAllocation = VK_NULL_HANDLE;
  7856. VMA_ASSERT(size > VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER);
  7857. m_Suballocations.push_back(suballoc);
  7858. VmaSuballocationList::iterator suballocItem = m_Suballocations.end();
  7859. --suballocItem;
  7860. m_FreeSuballocationsBySize.push_back(suballocItem);
  7861. }
  7862. bool VmaBlockMetadata_Generic::Validate() const
  7863. {
  7864. VMA_VALIDATE(!m_Suballocations.empty());
  7865. // Expected offset of new suballocation as calculated from previous ones.
  7866. VkDeviceSize calculatedOffset = 0;
  7867. // Expected number of free suballocations as calculated from traversing their list.
  7868. uint32_t calculatedFreeCount = 0;
  7869. // Expected sum size of free suballocations as calculated from traversing their list.
  7870. VkDeviceSize calculatedSumFreeSize = 0;
  7871. // Expected number of free suballocations that should be registered in
  7872. // m_FreeSuballocationsBySize calculated from traversing their list.
  7873. size_t freeSuballocationsToRegister = 0;
  7874. // True if previous visited suballocation was free.
  7875. bool prevFree = false;
  7876. for(const auto& subAlloc : m_Suballocations)
  7877. {
  7878. // Actual offset of this suballocation doesn't match expected one.
  7879. VMA_VALIDATE(subAlloc.offset == calculatedOffset);
  7880. const bool currFree = (subAlloc.type == VMA_SUBALLOCATION_TYPE_FREE);
  7881. // Two adjacent free suballocations are invalid. They should be merged.
  7882. VMA_VALIDATE(!prevFree || !currFree);
  7883. VMA_VALIDATE(currFree == (subAlloc.hAllocation == VK_NULL_HANDLE));
  7884. if(currFree)
  7885. {
  7886. calculatedSumFreeSize += subAlloc.size;
  7887. ++calculatedFreeCount;
  7888. if(subAlloc.size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
  7889. {
  7890. ++freeSuballocationsToRegister;
  7891. }
  7892. // Margin required between allocations - every free space must be at least that large.
  7893. VMA_VALIDATE(subAlloc.size >= VMA_DEBUG_MARGIN);
  7894. }
  7895. else
  7896. {
  7897. VMA_VALIDATE(subAlloc.hAllocation->GetOffset() == subAlloc.offset);
  7898. VMA_VALIDATE(subAlloc.hAllocation->GetSize() == subAlloc.size);
  7899. // Margin required between allocations - previous allocation must be free.
  7900. VMA_VALIDATE(VMA_DEBUG_MARGIN == 0 || prevFree);
  7901. }
  7902. calculatedOffset += subAlloc.size;
  7903. prevFree = currFree;
  7904. }
  7905. // Number of free suballocations registered in m_FreeSuballocationsBySize doesn't
  7906. // match expected one.
  7907. VMA_VALIDATE(m_FreeSuballocationsBySize.size() == freeSuballocationsToRegister);
  7908. VkDeviceSize lastSize = 0;
  7909. for(size_t i = 0; i < m_FreeSuballocationsBySize.size(); ++i)
  7910. {
  7911. VmaSuballocationList::iterator suballocItem = m_FreeSuballocationsBySize[i];
  7912. // Only free suballocations can be registered in m_FreeSuballocationsBySize.
  7913. VMA_VALIDATE(suballocItem->type == VMA_SUBALLOCATION_TYPE_FREE);
  7914. // They must be sorted by size ascending.
  7915. VMA_VALIDATE(suballocItem->size >= lastSize);
  7916. lastSize = suballocItem->size;
  7917. }
  7918. // Check if totals match calculated values.
  7919. VMA_VALIDATE(ValidateFreeSuballocationList());
  7920. VMA_VALIDATE(calculatedOffset == GetSize());
  7921. VMA_VALIDATE(calculatedSumFreeSize == m_SumFreeSize);
  7922. VMA_VALIDATE(calculatedFreeCount == m_FreeCount);
  7923. return true;
  7924. }
  7925. VkDeviceSize VmaBlockMetadata_Generic::GetUnusedRangeSizeMax() const
  7926. {
  7927. if(!m_FreeSuballocationsBySize.empty())
  7928. {
  7929. return m_FreeSuballocationsBySize.back()->size;
  7930. }
  7931. else
  7932. {
  7933. return 0;
  7934. }
  7935. }
  7936. bool VmaBlockMetadata_Generic::IsEmpty() const
  7937. {
  7938. return (m_Suballocations.size() == 1) && (m_FreeCount == 1);
  7939. }
  7940. void VmaBlockMetadata_Generic::CalcAllocationStatInfo(VmaStatInfo& outInfo) const
  7941. {
  7942. outInfo.blockCount = 1;
  7943. const uint32_t rangeCount = (uint32_t)m_Suballocations.size();
  7944. outInfo.allocationCount = rangeCount - m_FreeCount;
  7945. outInfo.unusedRangeCount = m_FreeCount;
  7946. outInfo.unusedBytes = m_SumFreeSize;
  7947. outInfo.usedBytes = GetSize() - outInfo.unusedBytes;
  7948. outInfo.allocationSizeMin = UINT64_MAX;
  7949. outInfo.allocationSizeMax = 0;
  7950. outInfo.unusedRangeSizeMin = UINT64_MAX;
  7951. outInfo.unusedRangeSizeMax = 0;
  7952. for(const auto& suballoc : m_Suballocations)
  7953. {
  7954. if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  7955. {
  7956. outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size);
  7957. outInfo.allocationSizeMax = VMA_MAX(outInfo.allocationSizeMax, suballoc.size);
  7958. }
  7959. else
  7960. {
  7961. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, suballoc.size);
  7962. outInfo.unusedRangeSizeMax = VMA_MAX(outInfo.unusedRangeSizeMax, suballoc.size);
  7963. }
  7964. }
  7965. }
  7966. void VmaBlockMetadata_Generic::AddPoolStats(VmaPoolStats& inoutStats) const
  7967. {
  7968. const uint32_t rangeCount = (uint32_t)m_Suballocations.size();
  7969. inoutStats.size += GetSize();
  7970. inoutStats.unusedSize += m_SumFreeSize;
  7971. inoutStats.allocationCount += rangeCount - m_FreeCount;
  7972. inoutStats.unusedRangeCount += m_FreeCount;
  7973. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, GetUnusedRangeSizeMax());
  7974. }
  7975. #if VMA_STATS_STRING_ENABLED
  7976. void VmaBlockMetadata_Generic::PrintDetailedMap(class VmaJsonWriter& json) const
  7977. {
  7978. PrintDetailedMap_Begin(json,
  7979. m_SumFreeSize, // unusedBytes
  7980. m_Suballocations.size() - (size_t)m_FreeCount, // allocationCount
  7981. m_FreeCount); // unusedRangeCount
  7982. size_t i = 0;
  7983. for(const auto& suballoc : m_Suballocations)
  7984. {
  7985. if(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE)
  7986. {
  7987. PrintDetailedMap_UnusedRange(json, suballoc.offset, suballoc.size);
  7988. }
  7989. else
  7990. {
  7991. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.hAllocation);
  7992. }
  7993. }
  7994. PrintDetailedMap_End(json);
  7995. }
  7996. #endif // #if VMA_STATS_STRING_ENABLED
  7997. bool VmaBlockMetadata_Generic::CreateAllocationRequest(
  7998. uint32_t currentFrameIndex,
  7999. uint32_t frameInUseCount,
  8000. VkDeviceSize bufferImageGranularity,
  8001. VkDeviceSize allocSize,
  8002. VkDeviceSize allocAlignment,
  8003. bool upperAddress,
  8004. VmaSuballocationType allocType,
  8005. bool canMakeOtherLost,
  8006. uint32_t strategy,
  8007. VmaAllocationRequest* pAllocationRequest)
  8008. {
  8009. VMA_ASSERT(allocSize > 0);
  8010. VMA_ASSERT(!upperAddress);
  8011. VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
  8012. VMA_ASSERT(pAllocationRequest != VMA_NULL);
  8013. VMA_HEAVY_ASSERT(Validate());
  8014. pAllocationRequest->type = VmaAllocationRequestType::Normal;
  8015. // There is not enough total free space in this block to fullfill the request: Early return.
  8016. if(canMakeOtherLost == false &&
  8017. m_SumFreeSize < allocSize + 2 * VMA_DEBUG_MARGIN)
  8018. {
  8019. return false;
  8020. }
  8021. // New algorithm, efficiently searching freeSuballocationsBySize.
  8022. const size_t freeSuballocCount = m_FreeSuballocationsBySize.size();
  8023. if(freeSuballocCount > 0)
  8024. {
  8025. if(strategy == VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT)
  8026. {
  8027. // Find first free suballocation with size not less than allocSize + 2 * VMA_DEBUG_MARGIN.
  8028. VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess(
  8029. m_FreeSuballocationsBySize.data(),
  8030. m_FreeSuballocationsBySize.data() + freeSuballocCount,
  8031. allocSize + 2 * VMA_DEBUG_MARGIN,
  8032. VmaSuballocationItemSizeLess());
  8033. size_t index = it - m_FreeSuballocationsBySize.data();
  8034. for(; index < freeSuballocCount; ++index)
  8035. {
  8036. if(CheckAllocation(
  8037. currentFrameIndex,
  8038. frameInUseCount,
  8039. bufferImageGranularity,
  8040. allocSize,
  8041. allocAlignment,
  8042. allocType,
  8043. m_FreeSuballocationsBySize[index],
  8044. false, // canMakeOtherLost
  8045. &pAllocationRequest->offset,
  8046. &pAllocationRequest->itemsToMakeLostCount,
  8047. &pAllocationRequest->sumFreeSize,
  8048. &pAllocationRequest->sumItemSize))
  8049. {
  8050. pAllocationRequest->item = m_FreeSuballocationsBySize[index];
  8051. return true;
  8052. }
  8053. }
  8054. }
  8055. else if(strategy == VMA_ALLOCATION_INTERNAL_STRATEGY_MIN_OFFSET)
  8056. {
  8057. for(VmaSuballocationList::iterator it = m_Suballocations.begin();
  8058. it != m_Suballocations.end();
  8059. ++it)
  8060. {
  8061. if(it->type == VMA_SUBALLOCATION_TYPE_FREE && CheckAllocation(
  8062. currentFrameIndex,
  8063. frameInUseCount,
  8064. bufferImageGranularity,
  8065. allocSize,
  8066. allocAlignment,
  8067. allocType,
  8068. it,
  8069. false, // canMakeOtherLost
  8070. &pAllocationRequest->offset,
  8071. &pAllocationRequest->itemsToMakeLostCount,
  8072. &pAllocationRequest->sumFreeSize,
  8073. &pAllocationRequest->sumItemSize))
  8074. {
  8075. pAllocationRequest->item = it;
  8076. return true;
  8077. }
  8078. }
  8079. }
  8080. else // WORST_FIT, FIRST_FIT
  8081. {
  8082. // Search staring from biggest suballocations.
  8083. for(size_t index = freeSuballocCount; index--; )
  8084. {
  8085. if(CheckAllocation(
  8086. currentFrameIndex,
  8087. frameInUseCount,
  8088. bufferImageGranularity,
  8089. allocSize,
  8090. allocAlignment,
  8091. allocType,
  8092. m_FreeSuballocationsBySize[index],
  8093. false, // canMakeOtherLost
  8094. &pAllocationRequest->offset,
  8095. &pAllocationRequest->itemsToMakeLostCount,
  8096. &pAllocationRequest->sumFreeSize,
  8097. &pAllocationRequest->sumItemSize))
  8098. {
  8099. pAllocationRequest->item = m_FreeSuballocationsBySize[index];
  8100. return true;
  8101. }
  8102. }
  8103. }
  8104. }
  8105. if(canMakeOtherLost)
  8106. {
  8107. // Brute-force algorithm. TODO: Come up with something better.
  8108. bool found = false;
  8109. VmaAllocationRequest tmpAllocRequest = {};
  8110. tmpAllocRequest.type = VmaAllocationRequestType::Normal;
  8111. for(VmaSuballocationList::iterator suballocIt = m_Suballocations.begin();
  8112. suballocIt != m_Suballocations.end();
  8113. ++suballocIt)
  8114. {
  8115. if(suballocIt->type == VMA_SUBALLOCATION_TYPE_FREE ||
  8116. suballocIt->hAllocation->CanBecomeLost())
  8117. {
  8118. if(CheckAllocation(
  8119. currentFrameIndex,
  8120. frameInUseCount,
  8121. bufferImageGranularity,
  8122. allocSize,
  8123. allocAlignment,
  8124. allocType,
  8125. suballocIt,
  8126. canMakeOtherLost,
  8127. &tmpAllocRequest.offset,
  8128. &tmpAllocRequest.itemsToMakeLostCount,
  8129. &tmpAllocRequest.sumFreeSize,
  8130. &tmpAllocRequest.sumItemSize))
  8131. {
  8132. if(strategy == VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT)
  8133. {
  8134. *pAllocationRequest = tmpAllocRequest;
  8135. pAllocationRequest->item = suballocIt;
  8136. break;
  8137. }
  8138. if(!found || tmpAllocRequest.CalcCost() < pAllocationRequest->CalcCost())
  8139. {
  8140. *pAllocationRequest = tmpAllocRequest;
  8141. pAllocationRequest->item = suballocIt;
  8142. found = true;
  8143. }
  8144. }
  8145. }
  8146. }
  8147. return found;
  8148. }
  8149. return false;
  8150. }
  8151. bool VmaBlockMetadata_Generic::MakeRequestedAllocationsLost(
  8152. uint32_t currentFrameIndex,
  8153. uint32_t frameInUseCount,
  8154. VmaAllocationRequest* pAllocationRequest)
  8155. {
  8156. VMA_ASSERT(pAllocationRequest && pAllocationRequest->type == VmaAllocationRequestType::Normal);
  8157. while(pAllocationRequest->itemsToMakeLostCount > 0)
  8158. {
  8159. if(pAllocationRequest->item->type == VMA_SUBALLOCATION_TYPE_FREE)
  8160. {
  8161. ++pAllocationRequest->item;
  8162. }
  8163. VMA_ASSERT(pAllocationRequest->item != m_Suballocations.end());
  8164. VMA_ASSERT(pAllocationRequest->item->hAllocation != VK_NULL_HANDLE);
  8165. VMA_ASSERT(pAllocationRequest->item->hAllocation->CanBecomeLost());
  8166. if(pAllocationRequest->item->hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
  8167. {
  8168. pAllocationRequest->item = FreeSuballocation(pAllocationRequest->item);
  8169. --pAllocationRequest->itemsToMakeLostCount;
  8170. }
  8171. else
  8172. {
  8173. return false;
  8174. }
  8175. }
  8176. VMA_HEAVY_ASSERT(Validate());
  8177. VMA_ASSERT(pAllocationRequest->item != m_Suballocations.end());
  8178. VMA_ASSERT(pAllocationRequest->item->type == VMA_SUBALLOCATION_TYPE_FREE);
  8179. return true;
  8180. }
  8181. uint32_t VmaBlockMetadata_Generic::MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount)
  8182. {
  8183. uint32_t lostAllocationCount = 0;
  8184. for(VmaSuballocationList::iterator it = m_Suballocations.begin();
  8185. it != m_Suballocations.end();
  8186. ++it)
  8187. {
  8188. if(it->type != VMA_SUBALLOCATION_TYPE_FREE &&
  8189. it->hAllocation->CanBecomeLost() &&
  8190. it->hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
  8191. {
  8192. it = FreeSuballocation(it);
  8193. ++lostAllocationCount;
  8194. }
  8195. }
  8196. return lostAllocationCount;
  8197. }
  8198. VkResult VmaBlockMetadata_Generic::CheckCorruption(const void* pBlockData)
  8199. {
  8200. for(auto& suballoc : m_Suballocations)
  8201. {
  8202. if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  8203. {
  8204. if(!VmaValidateMagicValue(pBlockData, suballoc.offset - VMA_DEBUG_MARGIN))
  8205. {
  8206. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE VALIDATED ALLOCATION!");
  8207. return VK_ERROR_VALIDATION_FAILED_EXT;
  8208. }
  8209. if(!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size))
  8210. {
  8211. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
  8212. return VK_ERROR_VALIDATION_FAILED_EXT;
  8213. }
  8214. }
  8215. }
  8216. return VK_SUCCESS;
  8217. }
  8218. void VmaBlockMetadata_Generic::Alloc(
  8219. const VmaAllocationRequest& request,
  8220. VmaSuballocationType type,
  8221. VkDeviceSize allocSize,
  8222. VmaAllocation hAllocation)
  8223. {
  8224. VMA_ASSERT(request.type == VmaAllocationRequestType::Normal);
  8225. VMA_ASSERT(request.item != m_Suballocations.end());
  8226. VmaSuballocation& suballoc = *request.item;
  8227. // Given suballocation is a free block.
  8228. VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  8229. // Given offset is inside this suballocation.
  8230. VMA_ASSERT(request.offset >= suballoc.offset);
  8231. const VkDeviceSize paddingBegin = request.offset - suballoc.offset;
  8232. VMA_ASSERT(suballoc.size >= paddingBegin + allocSize);
  8233. const VkDeviceSize paddingEnd = suballoc.size - paddingBegin - allocSize;
  8234. // Unregister this free suballocation from m_FreeSuballocationsBySize and update
  8235. // it to become used.
  8236. UnregisterFreeSuballocation(request.item);
  8237. suballoc.offset = request.offset;
  8238. suballoc.size = allocSize;
  8239. suballoc.type = type;
  8240. suballoc.hAllocation = hAllocation;
  8241. // If there are any free bytes remaining at the end, insert new free suballocation after current one.
  8242. if(paddingEnd)
  8243. {
  8244. VmaSuballocation paddingSuballoc = {};
  8245. paddingSuballoc.offset = request.offset + allocSize;
  8246. paddingSuballoc.size = paddingEnd;
  8247. paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  8248. VmaSuballocationList::iterator next = request.item;
  8249. ++next;
  8250. const VmaSuballocationList::iterator paddingEndItem =
  8251. m_Suballocations.insert(next, paddingSuballoc);
  8252. RegisterFreeSuballocation(paddingEndItem);
  8253. }
  8254. // If there are any free bytes remaining at the beginning, insert new free suballocation before current one.
  8255. if(paddingBegin)
  8256. {
  8257. VmaSuballocation paddingSuballoc = {};
  8258. paddingSuballoc.offset = request.offset - paddingBegin;
  8259. paddingSuballoc.size = paddingBegin;
  8260. paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  8261. const VmaSuballocationList::iterator paddingBeginItem =
  8262. m_Suballocations.insert(request.item, paddingSuballoc);
  8263. RegisterFreeSuballocation(paddingBeginItem);
  8264. }
  8265. // Update totals.
  8266. m_FreeCount = m_FreeCount - 1;
  8267. if(paddingBegin > 0)
  8268. {
  8269. ++m_FreeCount;
  8270. }
  8271. if(paddingEnd > 0)
  8272. {
  8273. ++m_FreeCount;
  8274. }
  8275. m_SumFreeSize -= allocSize;
  8276. }
  8277. void VmaBlockMetadata_Generic::Free(const VmaAllocation allocation)
  8278. {
  8279. for(VmaSuballocationList::iterator suballocItem = m_Suballocations.begin();
  8280. suballocItem != m_Suballocations.end();
  8281. ++suballocItem)
  8282. {
  8283. VmaSuballocation& suballoc = *suballocItem;
  8284. if(suballoc.hAllocation == allocation)
  8285. {
  8286. FreeSuballocation(suballocItem);
  8287. VMA_HEAVY_ASSERT(Validate());
  8288. return;
  8289. }
  8290. }
  8291. VMA_ASSERT(0 && "Not found!");
  8292. }
  8293. void VmaBlockMetadata_Generic::FreeAtOffset(VkDeviceSize offset)
  8294. {
  8295. for(VmaSuballocationList::iterator suballocItem = m_Suballocations.begin();
  8296. suballocItem != m_Suballocations.end();
  8297. ++suballocItem)
  8298. {
  8299. VmaSuballocation& suballoc = *suballocItem;
  8300. if(suballoc.offset == offset)
  8301. {
  8302. FreeSuballocation(suballocItem);
  8303. return;
  8304. }
  8305. }
  8306. VMA_ASSERT(0 && "Not found!");
  8307. }
  8308. bool VmaBlockMetadata_Generic::ValidateFreeSuballocationList() const
  8309. {
  8310. VkDeviceSize lastSize = 0;
  8311. for(size_t i = 0, count = m_FreeSuballocationsBySize.size(); i < count; ++i)
  8312. {
  8313. const VmaSuballocationList::iterator it = m_FreeSuballocationsBySize[i];
  8314. VMA_VALIDATE(it->type == VMA_SUBALLOCATION_TYPE_FREE);
  8315. VMA_VALIDATE(it->size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER);
  8316. VMA_VALIDATE(it->size >= lastSize);
  8317. lastSize = it->size;
  8318. }
  8319. return true;
  8320. }
  8321. bool VmaBlockMetadata_Generic::CheckAllocation(
  8322. uint32_t currentFrameIndex,
  8323. uint32_t frameInUseCount,
  8324. VkDeviceSize bufferImageGranularity,
  8325. VkDeviceSize allocSize,
  8326. VkDeviceSize allocAlignment,
  8327. VmaSuballocationType allocType,
  8328. VmaSuballocationList::const_iterator suballocItem,
  8329. bool canMakeOtherLost,
  8330. VkDeviceSize* pOffset,
  8331. size_t* itemsToMakeLostCount,
  8332. VkDeviceSize* pSumFreeSize,
  8333. VkDeviceSize* pSumItemSize) const
  8334. {
  8335. VMA_ASSERT(allocSize > 0);
  8336. VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
  8337. VMA_ASSERT(suballocItem != m_Suballocations.cend());
  8338. VMA_ASSERT(pOffset != VMA_NULL);
  8339. *itemsToMakeLostCount = 0;
  8340. *pSumFreeSize = 0;
  8341. *pSumItemSize = 0;
  8342. if(canMakeOtherLost)
  8343. {
  8344. if(suballocItem->type == VMA_SUBALLOCATION_TYPE_FREE)
  8345. {
  8346. *pSumFreeSize = suballocItem->size;
  8347. }
  8348. else
  8349. {
  8350. if(suballocItem->hAllocation->CanBecomeLost() &&
  8351. suballocItem->hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
  8352. {
  8353. ++*itemsToMakeLostCount;
  8354. *pSumItemSize = suballocItem->size;
  8355. }
  8356. else
  8357. {
  8358. return false;
  8359. }
  8360. }
  8361. // Remaining size is too small for this request: Early return.
  8362. if(GetSize() - suballocItem->offset < allocSize)
  8363. {
  8364. return false;
  8365. }
  8366. // Start from offset equal to beginning of this suballocation.
  8367. *pOffset = suballocItem->offset;
  8368. // Apply VMA_DEBUG_MARGIN at the beginning.
  8369. if(VMA_DEBUG_MARGIN > 0)
  8370. {
  8371. *pOffset += VMA_DEBUG_MARGIN;
  8372. }
  8373. // Apply alignment.
  8374. *pOffset = VmaAlignUp(*pOffset, allocAlignment);
  8375. // Check previous suballocations for BufferImageGranularity conflicts.
  8376. // Make bigger alignment if necessary.
  8377. if(bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment)
  8378. {
  8379. bool bufferImageGranularityConflict = false;
  8380. VmaSuballocationList::const_iterator prevSuballocItem = suballocItem;
  8381. while(prevSuballocItem != m_Suballocations.cbegin())
  8382. {
  8383. --prevSuballocItem;
  8384. const VmaSuballocation& prevSuballoc = *prevSuballocItem;
  8385. if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, *pOffset, bufferImageGranularity))
  8386. {
  8387. if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
  8388. {
  8389. bufferImageGranularityConflict = true;
  8390. break;
  8391. }
  8392. }
  8393. else
  8394. // Already on previous page.
  8395. break;
  8396. }
  8397. if(bufferImageGranularityConflict)
  8398. {
  8399. *pOffset = VmaAlignUp(*pOffset, bufferImageGranularity);
  8400. }
  8401. }
  8402. // Now that we have final *pOffset, check if we are past suballocItem.
  8403. // If yes, return false - this function should be called for another suballocItem as starting point.
  8404. if(*pOffset >= suballocItem->offset + suballocItem->size)
  8405. {
  8406. return false;
  8407. }
  8408. // Calculate padding at the beginning based on current offset.
  8409. const VkDeviceSize paddingBegin = *pOffset - suballocItem->offset;
  8410. // Calculate required margin at the end.
  8411. const VkDeviceSize requiredEndMargin = VMA_DEBUG_MARGIN;
  8412. const VkDeviceSize totalSize = paddingBegin + allocSize + requiredEndMargin;
  8413. // Another early return check.
  8414. if(suballocItem->offset + totalSize > GetSize())
  8415. {
  8416. return false;
  8417. }
  8418. // Advance lastSuballocItem until desired size is reached.
  8419. // Update itemsToMakeLostCount.
  8420. VmaSuballocationList::const_iterator lastSuballocItem = suballocItem;
  8421. if(totalSize > suballocItem->size)
  8422. {
  8423. VkDeviceSize remainingSize = totalSize - suballocItem->size;
  8424. while(remainingSize > 0)
  8425. {
  8426. ++lastSuballocItem;
  8427. if(lastSuballocItem == m_Suballocations.cend())
  8428. {
  8429. return false;
  8430. }
  8431. if(lastSuballocItem->type == VMA_SUBALLOCATION_TYPE_FREE)
  8432. {
  8433. *pSumFreeSize += lastSuballocItem->size;
  8434. }
  8435. else
  8436. {
  8437. VMA_ASSERT(lastSuballocItem->hAllocation != VK_NULL_HANDLE);
  8438. if(lastSuballocItem->hAllocation->CanBecomeLost() &&
  8439. lastSuballocItem->hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
  8440. {
  8441. ++*itemsToMakeLostCount;
  8442. *pSumItemSize += lastSuballocItem->size;
  8443. }
  8444. else
  8445. {
  8446. return false;
  8447. }
  8448. }
  8449. remainingSize = (lastSuballocItem->size < remainingSize) ?
  8450. remainingSize - lastSuballocItem->size : 0;
  8451. }
  8452. }
  8453. // Check next suballocations for BufferImageGranularity conflicts.
  8454. // If conflict exists, we must mark more allocations lost or fail.
  8455. if(allocSize % bufferImageGranularity || *pOffset % bufferImageGranularity)
  8456. {
  8457. VmaSuballocationList::const_iterator nextSuballocItem = lastSuballocItem;
  8458. ++nextSuballocItem;
  8459. while(nextSuballocItem != m_Suballocations.cend())
  8460. {
  8461. const VmaSuballocation& nextSuballoc = *nextSuballocItem;
  8462. if(VmaBlocksOnSamePage(*pOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  8463. {
  8464. if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
  8465. {
  8466. VMA_ASSERT(nextSuballoc.hAllocation != VK_NULL_HANDLE);
  8467. if(nextSuballoc.hAllocation->CanBecomeLost() &&
  8468. nextSuballoc.hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
  8469. {
  8470. ++*itemsToMakeLostCount;
  8471. }
  8472. else
  8473. {
  8474. return false;
  8475. }
  8476. }
  8477. }
  8478. else
  8479. {
  8480. // Already on next page.
  8481. break;
  8482. }
  8483. ++nextSuballocItem;
  8484. }
  8485. }
  8486. }
  8487. else
  8488. {
  8489. const VmaSuballocation& suballoc = *suballocItem;
  8490. VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  8491. *pSumFreeSize = suballoc.size;
  8492. // Size of this suballocation is too small for this request: Early return.
  8493. if(suballoc.size < allocSize)
  8494. {
  8495. return false;
  8496. }
  8497. // Start from offset equal to beginning of this suballocation.
  8498. *pOffset = suballoc.offset;
  8499. // Apply VMA_DEBUG_MARGIN at the beginning.
  8500. if(VMA_DEBUG_MARGIN > 0)
  8501. {
  8502. *pOffset += VMA_DEBUG_MARGIN;
  8503. }
  8504. // Apply alignment.
  8505. *pOffset = VmaAlignUp(*pOffset, allocAlignment);
  8506. // Check previous suballocations for BufferImageGranularity conflicts.
  8507. // Make bigger alignment if necessary.
  8508. if(bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment)
  8509. {
  8510. bool bufferImageGranularityConflict = false;
  8511. VmaSuballocationList::const_iterator prevSuballocItem = suballocItem;
  8512. while(prevSuballocItem != m_Suballocations.cbegin())
  8513. {
  8514. --prevSuballocItem;
  8515. const VmaSuballocation& prevSuballoc = *prevSuballocItem;
  8516. if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, *pOffset, bufferImageGranularity))
  8517. {
  8518. if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
  8519. {
  8520. bufferImageGranularityConflict = true;
  8521. break;
  8522. }
  8523. }
  8524. else
  8525. // Already on previous page.
  8526. break;
  8527. }
  8528. if(bufferImageGranularityConflict)
  8529. {
  8530. *pOffset = VmaAlignUp(*pOffset, bufferImageGranularity);
  8531. }
  8532. }
  8533. // Calculate padding at the beginning based on current offset.
  8534. const VkDeviceSize paddingBegin = *pOffset - suballoc.offset;
  8535. // Calculate required margin at the end.
  8536. const VkDeviceSize requiredEndMargin = VMA_DEBUG_MARGIN;
  8537. // Fail if requested size plus margin before and after is bigger than size of this suballocation.
  8538. if(paddingBegin + allocSize + requiredEndMargin > suballoc.size)
  8539. {
  8540. return false;
  8541. }
  8542. // Check next suballocations for BufferImageGranularity conflicts.
  8543. // If conflict exists, allocation cannot be made here.
  8544. if(allocSize % bufferImageGranularity || *pOffset % bufferImageGranularity)
  8545. {
  8546. VmaSuballocationList::const_iterator nextSuballocItem = suballocItem;
  8547. ++nextSuballocItem;
  8548. while(nextSuballocItem != m_Suballocations.cend())
  8549. {
  8550. const VmaSuballocation& nextSuballoc = *nextSuballocItem;
  8551. if(VmaBlocksOnSamePage(*pOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  8552. {
  8553. if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
  8554. {
  8555. return false;
  8556. }
  8557. }
  8558. else
  8559. {
  8560. // Already on next page.
  8561. break;
  8562. }
  8563. ++nextSuballocItem;
  8564. }
  8565. }
  8566. }
  8567. // All tests passed: Success. pOffset is already filled.
  8568. return true;
  8569. }
  8570. void VmaBlockMetadata_Generic::MergeFreeWithNext(VmaSuballocationList::iterator item)
  8571. {
  8572. VMA_ASSERT(item != m_Suballocations.end());
  8573. VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
  8574. VmaSuballocationList::iterator nextItem = item;
  8575. ++nextItem;
  8576. VMA_ASSERT(nextItem != m_Suballocations.end());
  8577. VMA_ASSERT(nextItem->type == VMA_SUBALLOCATION_TYPE_FREE);
  8578. item->size += nextItem->size;
  8579. --m_FreeCount;
  8580. m_Suballocations.erase(nextItem);
  8581. }
  8582. VmaSuballocationList::iterator VmaBlockMetadata_Generic::FreeSuballocation(VmaSuballocationList::iterator suballocItem)
  8583. {
  8584. // Change this suballocation to be marked as free.
  8585. VmaSuballocation& suballoc = *suballocItem;
  8586. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  8587. suballoc.hAllocation = VK_NULL_HANDLE;
  8588. // Update totals.
  8589. ++m_FreeCount;
  8590. m_SumFreeSize += suballoc.size;
  8591. // Merge with previous and/or next suballocation if it's also free.
  8592. bool mergeWithNext = false;
  8593. bool mergeWithPrev = false;
  8594. VmaSuballocationList::iterator nextItem = suballocItem;
  8595. ++nextItem;
  8596. if((nextItem != m_Suballocations.end()) && (nextItem->type == VMA_SUBALLOCATION_TYPE_FREE))
  8597. {
  8598. mergeWithNext = true;
  8599. }
  8600. VmaSuballocationList::iterator prevItem = suballocItem;
  8601. if(suballocItem != m_Suballocations.begin())
  8602. {
  8603. --prevItem;
  8604. if(prevItem->type == VMA_SUBALLOCATION_TYPE_FREE)
  8605. {
  8606. mergeWithPrev = true;
  8607. }
  8608. }
  8609. if(mergeWithNext)
  8610. {
  8611. UnregisterFreeSuballocation(nextItem);
  8612. MergeFreeWithNext(suballocItem);
  8613. }
  8614. if(mergeWithPrev)
  8615. {
  8616. UnregisterFreeSuballocation(prevItem);
  8617. MergeFreeWithNext(prevItem);
  8618. RegisterFreeSuballocation(prevItem);
  8619. return prevItem;
  8620. }
  8621. else
  8622. {
  8623. RegisterFreeSuballocation(suballocItem);
  8624. return suballocItem;
  8625. }
  8626. }
  8627. void VmaBlockMetadata_Generic::RegisterFreeSuballocation(VmaSuballocationList::iterator item)
  8628. {
  8629. VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
  8630. VMA_ASSERT(item->size > 0);
  8631. // You may want to enable this validation at the beginning or at the end of
  8632. // this function, depending on what do you want to check.
  8633. VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  8634. if(item->size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
  8635. {
  8636. if(m_FreeSuballocationsBySize.empty())
  8637. {
  8638. m_FreeSuballocationsBySize.push_back(item);
  8639. }
  8640. else
  8641. {
  8642. VmaVectorInsertSorted<VmaSuballocationItemSizeLess>(m_FreeSuballocationsBySize, item);
  8643. }
  8644. }
  8645. //VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  8646. }
  8647. void VmaBlockMetadata_Generic::UnregisterFreeSuballocation(VmaSuballocationList::iterator item)
  8648. {
  8649. VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
  8650. VMA_ASSERT(item->size > 0);
  8651. // You may want to enable this validation at the beginning or at the end of
  8652. // this function, depending on what do you want to check.
  8653. VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  8654. if(item->size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
  8655. {
  8656. VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess(
  8657. m_FreeSuballocationsBySize.data(),
  8658. m_FreeSuballocationsBySize.data() + m_FreeSuballocationsBySize.size(),
  8659. item,
  8660. VmaSuballocationItemSizeLess());
  8661. for(size_t index = it - m_FreeSuballocationsBySize.data();
  8662. index < m_FreeSuballocationsBySize.size();
  8663. ++index)
  8664. {
  8665. if(m_FreeSuballocationsBySize[index] == item)
  8666. {
  8667. VmaVectorRemove(m_FreeSuballocationsBySize, index);
  8668. return;
  8669. }
  8670. VMA_ASSERT((m_FreeSuballocationsBySize[index]->size == item->size) && "Not found.");
  8671. }
  8672. VMA_ASSERT(0 && "Not found.");
  8673. }
  8674. //VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  8675. }
  8676. bool VmaBlockMetadata_Generic::IsBufferImageGranularityConflictPossible(
  8677. VkDeviceSize bufferImageGranularity,
  8678. VmaSuballocationType& inOutPrevSuballocType) const
  8679. {
  8680. if(bufferImageGranularity == 1 || IsEmpty())
  8681. {
  8682. return false;
  8683. }
  8684. VkDeviceSize minAlignment = VK_WHOLE_SIZE;
  8685. bool typeConflictFound = false;
  8686. for(const auto& suballoc : m_Suballocations)
  8687. {
  8688. const VmaSuballocationType suballocType = suballoc.type;
  8689. if(suballocType != VMA_SUBALLOCATION_TYPE_FREE)
  8690. {
  8691. minAlignment = VMA_MIN(minAlignment, suballoc.hAllocation->GetAlignment());
  8692. if(VmaIsBufferImageGranularityConflict(inOutPrevSuballocType, suballocType))
  8693. {
  8694. typeConflictFound = true;
  8695. }
  8696. inOutPrevSuballocType = suballocType;
  8697. }
  8698. }
  8699. return typeConflictFound || minAlignment >= bufferImageGranularity;
  8700. }
  8701. ////////////////////////////////////////////////////////////////////////////////
  8702. // class VmaBlockMetadata_Linear
  8703. VmaBlockMetadata_Linear::VmaBlockMetadata_Linear(VmaAllocator hAllocator) :
  8704. VmaBlockMetadata(hAllocator),
  8705. m_SumFreeSize(0),
  8706. m_Suballocations0(VmaStlAllocator<VmaSuballocation>(hAllocator->GetAllocationCallbacks())),
  8707. m_Suballocations1(VmaStlAllocator<VmaSuballocation>(hAllocator->GetAllocationCallbacks())),
  8708. m_1stVectorIndex(0),
  8709. m_2ndVectorMode(SECOND_VECTOR_EMPTY),
  8710. m_1stNullItemsBeginCount(0),
  8711. m_1stNullItemsMiddleCount(0),
  8712. m_2ndNullItemsCount(0)
  8713. {
  8714. }
  8715. VmaBlockMetadata_Linear::~VmaBlockMetadata_Linear()
  8716. {
  8717. }
  8718. void VmaBlockMetadata_Linear::Init(VkDeviceSize size)
  8719. {
  8720. VmaBlockMetadata::Init(size);
  8721. m_SumFreeSize = size;
  8722. }
  8723. bool VmaBlockMetadata_Linear::Validate() const
  8724. {
  8725. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  8726. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  8727. VMA_VALIDATE(suballocations2nd.empty() == (m_2ndVectorMode == SECOND_VECTOR_EMPTY));
  8728. VMA_VALIDATE(!suballocations1st.empty() ||
  8729. suballocations2nd.empty() ||
  8730. m_2ndVectorMode != SECOND_VECTOR_RING_BUFFER);
  8731. if(!suballocations1st.empty())
  8732. {
  8733. // Null item at the beginning should be accounted into m_1stNullItemsBeginCount.
  8734. VMA_VALIDATE(suballocations1st[m_1stNullItemsBeginCount].hAllocation != VK_NULL_HANDLE);
  8735. // Null item at the end should be just pop_back().
  8736. VMA_VALIDATE(suballocations1st.back().hAllocation != VK_NULL_HANDLE);
  8737. }
  8738. if(!suballocations2nd.empty())
  8739. {
  8740. // Null item at the end should be just pop_back().
  8741. VMA_VALIDATE(suballocations2nd.back().hAllocation != VK_NULL_HANDLE);
  8742. }
  8743. VMA_VALIDATE(m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount <= suballocations1st.size());
  8744. VMA_VALIDATE(m_2ndNullItemsCount <= suballocations2nd.size());
  8745. VkDeviceSize sumUsedSize = 0;
  8746. const size_t suballoc1stCount = suballocations1st.size();
  8747. VkDeviceSize offset = VMA_DEBUG_MARGIN;
  8748. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  8749. {
  8750. const size_t suballoc2ndCount = suballocations2nd.size();
  8751. size_t nullItem2ndCount = 0;
  8752. for(size_t i = 0; i < suballoc2ndCount; ++i)
  8753. {
  8754. const VmaSuballocation& suballoc = suballocations2nd[i];
  8755. const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  8756. VMA_VALIDATE(currFree == (suballoc.hAllocation == VK_NULL_HANDLE));
  8757. VMA_VALIDATE(suballoc.offset >= offset);
  8758. if(!currFree)
  8759. {
  8760. VMA_VALIDATE(suballoc.hAllocation->GetOffset() == suballoc.offset);
  8761. VMA_VALIDATE(suballoc.hAllocation->GetSize() == suballoc.size);
  8762. sumUsedSize += suballoc.size;
  8763. }
  8764. else
  8765. {
  8766. ++nullItem2ndCount;
  8767. }
  8768. offset = suballoc.offset + suballoc.size + VMA_DEBUG_MARGIN;
  8769. }
  8770. VMA_VALIDATE(nullItem2ndCount == m_2ndNullItemsCount);
  8771. }
  8772. for(size_t i = 0; i < m_1stNullItemsBeginCount; ++i)
  8773. {
  8774. const VmaSuballocation& suballoc = suballocations1st[i];
  8775. VMA_VALIDATE(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE &&
  8776. suballoc.hAllocation == VK_NULL_HANDLE);
  8777. }
  8778. size_t nullItem1stCount = m_1stNullItemsBeginCount;
  8779. for(size_t i = m_1stNullItemsBeginCount; i < suballoc1stCount; ++i)
  8780. {
  8781. const VmaSuballocation& suballoc = suballocations1st[i];
  8782. const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  8783. VMA_VALIDATE(currFree == (suballoc.hAllocation == VK_NULL_HANDLE));
  8784. VMA_VALIDATE(suballoc.offset >= offset);
  8785. VMA_VALIDATE(i >= m_1stNullItemsBeginCount || currFree);
  8786. if(!currFree)
  8787. {
  8788. VMA_VALIDATE(suballoc.hAllocation->GetOffset() == suballoc.offset);
  8789. VMA_VALIDATE(suballoc.hAllocation->GetSize() == suballoc.size);
  8790. sumUsedSize += suballoc.size;
  8791. }
  8792. else
  8793. {
  8794. ++nullItem1stCount;
  8795. }
  8796. offset = suballoc.offset + suballoc.size + VMA_DEBUG_MARGIN;
  8797. }
  8798. VMA_VALIDATE(nullItem1stCount == m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount);
  8799. if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  8800. {
  8801. const size_t suballoc2ndCount = suballocations2nd.size();
  8802. size_t nullItem2ndCount = 0;
  8803. for(size_t i = suballoc2ndCount; i--; )
  8804. {
  8805. const VmaSuballocation& suballoc = suballocations2nd[i];
  8806. const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  8807. VMA_VALIDATE(currFree == (suballoc.hAllocation == VK_NULL_HANDLE));
  8808. VMA_VALIDATE(suballoc.offset >= offset);
  8809. if(!currFree)
  8810. {
  8811. VMA_VALIDATE(suballoc.hAllocation->GetOffset() == suballoc.offset);
  8812. VMA_VALIDATE(suballoc.hAllocation->GetSize() == suballoc.size);
  8813. sumUsedSize += suballoc.size;
  8814. }
  8815. else
  8816. {
  8817. ++nullItem2ndCount;
  8818. }
  8819. offset = suballoc.offset + suballoc.size + VMA_DEBUG_MARGIN;
  8820. }
  8821. VMA_VALIDATE(nullItem2ndCount == m_2ndNullItemsCount);
  8822. }
  8823. VMA_VALIDATE(offset <= GetSize());
  8824. VMA_VALIDATE(m_SumFreeSize == GetSize() - sumUsedSize);
  8825. return true;
  8826. }
  8827. size_t VmaBlockMetadata_Linear::GetAllocationCount() const
  8828. {
  8829. return AccessSuballocations1st().size() - (m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount) +
  8830. AccessSuballocations2nd().size() - m_2ndNullItemsCount;
  8831. }
  8832. VkDeviceSize VmaBlockMetadata_Linear::GetUnusedRangeSizeMax() const
  8833. {
  8834. const VkDeviceSize size = GetSize();
  8835. /*
  8836. We don't consider gaps inside allocation vectors with freed allocations because
  8837. they are not suitable for reuse in linear allocator. We consider only space that
  8838. is available for new allocations.
  8839. */
  8840. if(IsEmpty())
  8841. {
  8842. return size;
  8843. }
  8844. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  8845. switch(m_2ndVectorMode)
  8846. {
  8847. case SECOND_VECTOR_EMPTY:
  8848. /*
  8849. Available space is after end of 1st, as well as before beginning of 1st (which
  8850. would make it a ring buffer).
  8851. */
  8852. {
  8853. const size_t suballocations1stCount = suballocations1st.size();
  8854. VMA_ASSERT(suballocations1stCount > m_1stNullItemsBeginCount);
  8855. const VmaSuballocation& firstSuballoc = suballocations1st[m_1stNullItemsBeginCount];
  8856. const VmaSuballocation& lastSuballoc = suballocations1st[suballocations1stCount - 1];
  8857. return VMA_MAX(
  8858. firstSuballoc.offset,
  8859. size - (lastSuballoc.offset + lastSuballoc.size));
  8860. }
  8861. break;
  8862. case SECOND_VECTOR_RING_BUFFER:
  8863. /*
  8864. Available space is only between end of 2nd and beginning of 1st.
  8865. */
  8866. {
  8867. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  8868. const VmaSuballocation& lastSuballoc2nd = suballocations2nd.back();
  8869. const VmaSuballocation& firstSuballoc1st = suballocations1st[m_1stNullItemsBeginCount];
  8870. return firstSuballoc1st.offset - (lastSuballoc2nd.offset + lastSuballoc2nd.size);
  8871. }
  8872. break;
  8873. case SECOND_VECTOR_DOUBLE_STACK:
  8874. /*
  8875. Available space is only between end of 1st and top of 2nd.
  8876. */
  8877. {
  8878. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  8879. const VmaSuballocation& topSuballoc2nd = suballocations2nd.back();
  8880. const VmaSuballocation& lastSuballoc1st = suballocations1st.back();
  8881. return topSuballoc2nd.offset - (lastSuballoc1st.offset + lastSuballoc1st.size);
  8882. }
  8883. break;
  8884. default:
  8885. VMA_ASSERT(0);
  8886. return 0;
  8887. }
  8888. }
  8889. void VmaBlockMetadata_Linear::CalcAllocationStatInfo(VmaStatInfo& outInfo) const
  8890. {
  8891. const VkDeviceSize size = GetSize();
  8892. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  8893. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  8894. const size_t suballoc1stCount = suballocations1st.size();
  8895. const size_t suballoc2ndCount = suballocations2nd.size();
  8896. outInfo.blockCount = 1;
  8897. outInfo.allocationCount = (uint32_t)GetAllocationCount();
  8898. outInfo.unusedRangeCount = 0;
  8899. outInfo.usedBytes = 0;
  8900. outInfo.allocationSizeMin = UINT64_MAX;
  8901. outInfo.allocationSizeMax = 0;
  8902. outInfo.unusedRangeSizeMin = UINT64_MAX;
  8903. outInfo.unusedRangeSizeMax = 0;
  8904. VkDeviceSize lastOffset = 0;
  8905. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  8906. {
  8907. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  8908. size_t nextAlloc2ndIndex = 0;
  8909. while(lastOffset < freeSpace2ndTo1stEnd)
  8910. {
  8911. // Find next non-null allocation or move nextAllocIndex to the end.
  8912. while(nextAlloc2ndIndex < suballoc2ndCount &&
  8913. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  8914. {
  8915. ++nextAlloc2ndIndex;
  8916. }
  8917. // Found non-null allocation.
  8918. if(nextAlloc2ndIndex < suballoc2ndCount)
  8919. {
  8920. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  8921. // 1. Process free space before this allocation.
  8922. if(lastOffset < suballoc.offset)
  8923. {
  8924. // There is free space from lastOffset to suballoc.offset.
  8925. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  8926. ++outInfo.unusedRangeCount;
  8927. outInfo.unusedBytes += unusedRangeSize;
  8928. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
  8929. outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
  8930. }
  8931. // 2. Process this allocation.
  8932. // There is allocation with suballoc.offset, suballoc.size.
  8933. outInfo.usedBytes += suballoc.size;
  8934. outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size);
  8935. outInfo.allocationSizeMax = VMA_MIN(outInfo.allocationSizeMax, suballoc.size);
  8936. // 3. Prepare for next iteration.
  8937. lastOffset = suballoc.offset + suballoc.size;
  8938. ++nextAlloc2ndIndex;
  8939. }
  8940. // We are at the end.
  8941. else
  8942. {
  8943. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  8944. if(lastOffset < freeSpace2ndTo1stEnd)
  8945. {
  8946. const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset;
  8947. ++outInfo.unusedRangeCount;
  8948. outInfo.unusedBytes += unusedRangeSize;
  8949. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
  8950. outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
  8951. }
  8952. // End of loop.
  8953. lastOffset = freeSpace2ndTo1stEnd;
  8954. }
  8955. }
  8956. }
  8957. size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
  8958. const VkDeviceSize freeSpace1stTo2ndEnd =
  8959. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
  8960. while(lastOffset < freeSpace1stTo2ndEnd)
  8961. {
  8962. // Find next non-null allocation or move nextAllocIndex to the end.
  8963. while(nextAlloc1stIndex < suballoc1stCount &&
  8964. suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE)
  8965. {
  8966. ++nextAlloc1stIndex;
  8967. }
  8968. // Found non-null allocation.
  8969. if(nextAlloc1stIndex < suballoc1stCount)
  8970. {
  8971. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  8972. // 1. Process free space before this allocation.
  8973. if(lastOffset < suballoc.offset)
  8974. {
  8975. // There is free space from lastOffset to suballoc.offset.
  8976. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  8977. ++outInfo.unusedRangeCount;
  8978. outInfo.unusedBytes += unusedRangeSize;
  8979. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
  8980. outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
  8981. }
  8982. // 2. Process this allocation.
  8983. // There is allocation with suballoc.offset, suballoc.size.
  8984. outInfo.usedBytes += suballoc.size;
  8985. outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size);
  8986. outInfo.allocationSizeMax = VMA_MIN(outInfo.allocationSizeMax, suballoc.size);
  8987. // 3. Prepare for next iteration.
  8988. lastOffset = suballoc.offset + suballoc.size;
  8989. ++nextAlloc1stIndex;
  8990. }
  8991. // We are at the end.
  8992. else
  8993. {
  8994. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  8995. if(lastOffset < freeSpace1stTo2ndEnd)
  8996. {
  8997. const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset;
  8998. ++outInfo.unusedRangeCount;
  8999. outInfo.unusedBytes += unusedRangeSize;
  9000. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
  9001. outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
  9002. }
  9003. // End of loop.
  9004. lastOffset = freeSpace1stTo2ndEnd;
  9005. }
  9006. }
  9007. if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  9008. {
  9009. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  9010. while(lastOffset < size)
  9011. {
  9012. // Find next non-null allocation or move nextAllocIndex to the end.
  9013. while(nextAlloc2ndIndex != SIZE_MAX &&
  9014. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  9015. {
  9016. --nextAlloc2ndIndex;
  9017. }
  9018. // Found non-null allocation.
  9019. if(nextAlloc2ndIndex != SIZE_MAX)
  9020. {
  9021. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  9022. // 1. Process free space before this allocation.
  9023. if(lastOffset < suballoc.offset)
  9024. {
  9025. // There is free space from lastOffset to suballoc.offset.
  9026. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  9027. ++outInfo.unusedRangeCount;
  9028. outInfo.unusedBytes += unusedRangeSize;
  9029. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
  9030. outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
  9031. }
  9032. // 2. Process this allocation.
  9033. // There is allocation with suballoc.offset, suballoc.size.
  9034. outInfo.usedBytes += suballoc.size;
  9035. outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size);
  9036. outInfo.allocationSizeMax = VMA_MIN(outInfo.allocationSizeMax, suballoc.size);
  9037. // 3. Prepare for next iteration.
  9038. lastOffset = suballoc.offset + suballoc.size;
  9039. --nextAlloc2ndIndex;
  9040. }
  9041. // We are at the end.
  9042. else
  9043. {
  9044. // There is free space from lastOffset to size.
  9045. if(lastOffset < size)
  9046. {
  9047. const VkDeviceSize unusedRangeSize = size - lastOffset;
  9048. ++outInfo.unusedRangeCount;
  9049. outInfo.unusedBytes += unusedRangeSize;
  9050. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
  9051. outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
  9052. }
  9053. // End of loop.
  9054. lastOffset = size;
  9055. }
  9056. }
  9057. }
  9058. outInfo.unusedBytes = size - outInfo.usedBytes;
  9059. }
  9060. void VmaBlockMetadata_Linear::AddPoolStats(VmaPoolStats& inoutStats) const
  9061. {
  9062. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  9063. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  9064. const VkDeviceSize size = GetSize();
  9065. const size_t suballoc1stCount = suballocations1st.size();
  9066. const size_t suballoc2ndCount = suballocations2nd.size();
  9067. inoutStats.size += size;
  9068. VkDeviceSize lastOffset = 0;
  9069. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  9070. {
  9071. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  9072. size_t nextAlloc2ndIndex = m_1stNullItemsBeginCount;
  9073. while(lastOffset < freeSpace2ndTo1stEnd)
  9074. {
  9075. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  9076. while(nextAlloc2ndIndex < suballoc2ndCount &&
  9077. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  9078. {
  9079. ++nextAlloc2ndIndex;
  9080. }
  9081. // Found non-null allocation.
  9082. if(nextAlloc2ndIndex < suballoc2ndCount)
  9083. {
  9084. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  9085. // 1. Process free space before this allocation.
  9086. if(lastOffset < suballoc.offset)
  9087. {
  9088. // There is free space from lastOffset to suballoc.offset.
  9089. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  9090. inoutStats.unusedSize += unusedRangeSize;
  9091. ++inoutStats.unusedRangeCount;
  9092. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
  9093. }
  9094. // 2. Process this allocation.
  9095. // There is allocation with suballoc.offset, suballoc.size.
  9096. ++inoutStats.allocationCount;
  9097. // 3. Prepare for next iteration.
  9098. lastOffset = suballoc.offset + suballoc.size;
  9099. ++nextAlloc2ndIndex;
  9100. }
  9101. // We are at the end.
  9102. else
  9103. {
  9104. if(lastOffset < freeSpace2ndTo1stEnd)
  9105. {
  9106. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  9107. const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset;
  9108. inoutStats.unusedSize += unusedRangeSize;
  9109. ++inoutStats.unusedRangeCount;
  9110. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
  9111. }
  9112. // End of loop.
  9113. lastOffset = freeSpace2ndTo1stEnd;
  9114. }
  9115. }
  9116. }
  9117. size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
  9118. const VkDeviceSize freeSpace1stTo2ndEnd =
  9119. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
  9120. while(lastOffset < freeSpace1stTo2ndEnd)
  9121. {
  9122. // Find next non-null allocation or move nextAllocIndex to the end.
  9123. while(nextAlloc1stIndex < suballoc1stCount &&
  9124. suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE)
  9125. {
  9126. ++nextAlloc1stIndex;
  9127. }
  9128. // Found non-null allocation.
  9129. if(nextAlloc1stIndex < suballoc1stCount)
  9130. {
  9131. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  9132. // 1. Process free space before this allocation.
  9133. if(lastOffset < suballoc.offset)
  9134. {
  9135. // There is free space from lastOffset to suballoc.offset.
  9136. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  9137. inoutStats.unusedSize += unusedRangeSize;
  9138. ++inoutStats.unusedRangeCount;
  9139. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
  9140. }
  9141. // 2. Process this allocation.
  9142. // There is allocation with suballoc.offset, suballoc.size.
  9143. ++inoutStats.allocationCount;
  9144. // 3. Prepare for next iteration.
  9145. lastOffset = suballoc.offset + suballoc.size;
  9146. ++nextAlloc1stIndex;
  9147. }
  9148. // We are at the end.
  9149. else
  9150. {
  9151. if(lastOffset < freeSpace1stTo2ndEnd)
  9152. {
  9153. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  9154. const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset;
  9155. inoutStats.unusedSize += unusedRangeSize;
  9156. ++inoutStats.unusedRangeCount;
  9157. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
  9158. }
  9159. // End of loop.
  9160. lastOffset = freeSpace1stTo2ndEnd;
  9161. }
  9162. }
  9163. if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  9164. {
  9165. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  9166. while(lastOffset < size)
  9167. {
  9168. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  9169. while(nextAlloc2ndIndex != SIZE_MAX &&
  9170. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  9171. {
  9172. --nextAlloc2ndIndex;
  9173. }
  9174. // Found non-null allocation.
  9175. if(nextAlloc2ndIndex != SIZE_MAX)
  9176. {
  9177. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  9178. // 1. Process free space before this allocation.
  9179. if(lastOffset < suballoc.offset)
  9180. {
  9181. // There is free space from lastOffset to suballoc.offset.
  9182. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  9183. inoutStats.unusedSize += unusedRangeSize;
  9184. ++inoutStats.unusedRangeCount;
  9185. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
  9186. }
  9187. // 2. Process this allocation.
  9188. // There is allocation with suballoc.offset, suballoc.size.
  9189. ++inoutStats.allocationCount;
  9190. // 3. Prepare for next iteration.
  9191. lastOffset = suballoc.offset + suballoc.size;
  9192. --nextAlloc2ndIndex;
  9193. }
  9194. // We are at the end.
  9195. else
  9196. {
  9197. if(lastOffset < size)
  9198. {
  9199. // There is free space from lastOffset to size.
  9200. const VkDeviceSize unusedRangeSize = size - lastOffset;
  9201. inoutStats.unusedSize += unusedRangeSize;
  9202. ++inoutStats.unusedRangeCount;
  9203. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
  9204. }
  9205. // End of loop.
  9206. lastOffset = size;
  9207. }
  9208. }
  9209. }
  9210. }
  9211. #if VMA_STATS_STRING_ENABLED
  9212. void VmaBlockMetadata_Linear::PrintDetailedMap(class VmaJsonWriter& json) const
  9213. {
  9214. const VkDeviceSize size = GetSize();
  9215. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  9216. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  9217. const size_t suballoc1stCount = suballocations1st.size();
  9218. const size_t suballoc2ndCount = suballocations2nd.size();
  9219. // FIRST PASS
  9220. size_t unusedRangeCount = 0;
  9221. VkDeviceSize usedBytes = 0;
  9222. VkDeviceSize lastOffset = 0;
  9223. size_t alloc2ndCount = 0;
  9224. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  9225. {
  9226. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  9227. size_t nextAlloc2ndIndex = 0;
  9228. while(lastOffset < freeSpace2ndTo1stEnd)
  9229. {
  9230. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  9231. while(nextAlloc2ndIndex < suballoc2ndCount &&
  9232. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  9233. {
  9234. ++nextAlloc2ndIndex;
  9235. }
  9236. // Found non-null allocation.
  9237. if(nextAlloc2ndIndex < suballoc2ndCount)
  9238. {
  9239. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  9240. // 1. Process free space before this allocation.
  9241. if(lastOffset < suballoc.offset)
  9242. {
  9243. // There is free space from lastOffset to suballoc.offset.
  9244. ++unusedRangeCount;
  9245. }
  9246. // 2. Process this allocation.
  9247. // There is allocation with suballoc.offset, suballoc.size.
  9248. ++alloc2ndCount;
  9249. usedBytes += suballoc.size;
  9250. // 3. Prepare for next iteration.
  9251. lastOffset = suballoc.offset + suballoc.size;
  9252. ++nextAlloc2ndIndex;
  9253. }
  9254. // We are at the end.
  9255. else
  9256. {
  9257. if(lastOffset < freeSpace2ndTo1stEnd)
  9258. {
  9259. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  9260. ++unusedRangeCount;
  9261. }
  9262. // End of loop.
  9263. lastOffset = freeSpace2ndTo1stEnd;
  9264. }
  9265. }
  9266. }
  9267. size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
  9268. size_t alloc1stCount = 0;
  9269. const VkDeviceSize freeSpace1stTo2ndEnd =
  9270. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
  9271. while(lastOffset < freeSpace1stTo2ndEnd)
  9272. {
  9273. // Find next non-null allocation or move nextAllocIndex to the end.
  9274. while(nextAlloc1stIndex < suballoc1stCount &&
  9275. suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE)
  9276. {
  9277. ++nextAlloc1stIndex;
  9278. }
  9279. // Found non-null allocation.
  9280. if(nextAlloc1stIndex < suballoc1stCount)
  9281. {
  9282. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  9283. // 1. Process free space before this allocation.
  9284. if(lastOffset < suballoc.offset)
  9285. {
  9286. // There is free space from lastOffset to suballoc.offset.
  9287. ++unusedRangeCount;
  9288. }
  9289. // 2. Process this allocation.
  9290. // There is allocation with suballoc.offset, suballoc.size.
  9291. ++alloc1stCount;
  9292. usedBytes += suballoc.size;
  9293. // 3. Prepare for next iteration.
  9294. lastOffset = suballoc.offset + suballoc.size;
  9295. ++nextAlloc1stIndex;
  9296. }
  9297. // We are at the end.
  9298. else
  9299. {
  9300. if(lastOffset < size)
  9301. {
  9302. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  9303. ++unusedRangeCount;
  9304. }
  9305. // End of loop.
  9306. lastOffset = freeSpace1stTo2ndEnd;
  9307. }
  9308. }
  9309. if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  9310. {
  9311. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  9312. while(lastOffset < size)
  9313. {
  9314. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  9315. while(nextAlloc2ndIndex != SIZE_MAX &&
  9316. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  9317. {
  9318. --nextAlloc2ndIndex;
  9319. }
  9320. // Found non-null allocation.
  9321. if(nextAlloc2ndIndex != SIZE_MAX)
  9322. {
  9323. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  9324. // 1. Process free space before this allocation.
  9325. if(lastOffset < suballoc.offset)
  9326. {
  9327. // There is free space from lastOffset to suballoc.offset.
  9328. ++unusedRangeCount;
  9329. }
  9330. // 2. Process this allocation.
  9331. // There is allocation with suballoc.offset, suballoc.size.
  9332. ++alloc2ndCount;
  9333. usedBytes += suballoc.size;
  9334. // 3. Prepare for next iteration.
  9335. lastOffset = suballoc.offset + suballoc.size;
  9336. --nextAlloc2ndIndex;
  9337. }
  9338. // We are at the end.
  9339. else
  9340. {
  9341. if(lastOffset < size)
  9342. {
  9343. // There is free space from lastOffset to size.
  9344. ++unusedRangeCount;
  9345. }
  9346. // End of loop.
  9347. lastOffset = size;
  9348. }
  9349. }
  9350. }
  9351. const VkDeviceSize unusedBytes = size - usedBytes;
  9352. PrintDetailedMap_Begin(json, unusedBytes, alloc1stCount + alloc2ndCount, unusedRangeCount);
  9353. // SECOND PASS
  9354. lastOffset = 0;
  9355. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  9356. {
  9357. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  9358. size_t nextAlloc2ndIndex = 0;
  9359. while(lastOffset < freeSpace2ndTo1stEnd)
  9360. {
  9361. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  9362. while(nextAlloc2ndIndex < suballoc2ndCount &&
  9363. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  9364. {
  9365. ++nextAlloc2ndIndex;
  9366. }
  9367. // Found non-null allocation.
  9368. if(nextAlloc2ndIndex < suballoc2ndCount)
  9369. {
  9370. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  9371. // 1. Process free space before this allocation.
  9372. if(lastOffset < suballoc.offset)
  9373. {
  9374. // There is free space from lastOffset to suballoc.offset.
  9375. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  9376. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  9377. }
  9378. // 2. Process this allocation.
  9379. // There is allocation with suballoc.offset, suballoc.size.
  9380. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.hAllocation);
  9381. // 3. Prepare for next iteration.
  9382. lastOffset = suballoc.offset + suballoc.size;
  9383. ++nextAlloc2ndIndex;
  9384. }
  9385. // We are at the end.
  9386. else
  9387. {
  9388. if(lastOffset < freeSpace2ndTo1stEnd)
  9389. {
  9390. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  9391. const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset;
  9392. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  9393. }
  9394. // End of loop.
  9395. lastOffset = freeSpace2ndTo1stEnd;
  9396. }
  9397. }
  9398. }
  9399. nextAlloc1stIndex = m_1stNullItemsBeginCount;
  9400. while(lastOffset < freeSpace1stTo2ndEnd)
  9401. {
  9402. // Find next non-null allocation or move nextAllocIndex to the end.
  9403. while(nextAlloc1stIndex < suballoc1stCount &&
  9404. suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE)
  9405. {
  9406. ++nextAlloc1stIndex;
  9407. }
  9408. // Found non-null allocation.
  9409. if(nextAlloc1stIndex < suballoc1stCount)
  9410. {
  9411. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  9412. // 1. Process free space before this allocation.
  9413. if(lastOffset < suballoc.offset)
  9414. {
  9415. // There is free space from lastOffset to suballoc.offset.
  9416. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  9417. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  9418. }
  9419. // 2. Process this allocation.
  9420. // There is allocation with suballoc.offset, suballoc.size.
  9421. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.hAllocation);
  9422. // 3. Prepare for next iteration.
  9423. lastOffset = suballoc.offset + suballoc.size;
  9424. ++nextAlloc1stIndex;
  9425. }
  9426. // We are at the end.
  9427. else
  9428. {
  9429. if(lastOffset < freeSpace1stTo2ndEnd)
  9430. {
  9431. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  9432. const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset;
  9433. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  9434. }
  9435. // End of loop.
  9436. lastOffset = freeSpace1stTo2ndEnd;
  9437. }
  9438. }
  9439. if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  9440. {
  9441. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  9442. while(lastOffset < size)
  9443. {
  9444. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  9445. while(nextAlloc2ndIndex != SIZE_MAX &&
  9446. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  9447. {
  9448. --nextAlloc2ndIndex;
  9449. }
  9450. // Found non-null allocation.
  9451. if(nextAlloc2ndIndex != SIZE_MAX)
  9452. {
  9453. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  9454. // 1. Process free space before this allocation.
  9455. if(lastOffset < suballoc.offset)
  9456. {
  9457. // There is free space from lastOffset to suballoc.offset.
  9458. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  9459. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  9460. }
  9461. // 2. Process this allocation.
  9462. // There is allocation with suballoc.offset, suballoc.size.
  9463. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.hAllocation);
  9464. // 3. Prepare for next iteration.
  9465. lastOffset = suballoc.offset + suballoc.size;
  9466. --nextAlloc2ndIndex;
  9467. }
  9468. // We are at the end.
  9469. else
  9470. {
  9471. if(lastOffset < size)
  9472. {
  9473. // There is free space from lastOffset to size.
  9474. const VkDeviceSize unusedRangeSize = size - lastOffset;
  9475. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  9476. }
  9477. // End of loop.
  9478. lastOffset = size;
  9479. }
  9480. }
  9481. }
  9482. PrintDetailedMap_End(json);
  9483. }
  9484. #endif // #if VMA_STATS_STRING_ENABLED
  9485. bool VmaBlockMetadata_Linear::CreateAllocationRequest(
  9486. uint32_t currentFrameIndex,
  9487. uint32_t frameInUseCount,
  9488. VkDeviceSize bufferImageGranularity,
  9489. VkDeviceSize allocSize,
  9490. VkDeviceSize allocAlignment,
  9491. bool upperAddress,
  9492. VmaSuballocationType allocType,
  9493. bool canMakeOtherLost,
  9494. uint32_t strategy,
  9495. VmaAllocationRequest* pAllocationRequest)
  9496. {
  9497. VMA_ASSERT(allocSize > 0);
  9498. VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
  9499. VMA_ASSERT(pAllocationRequest != VMA_NULL);
  9500. VMA_HEAVY_ASSERT(Validate());
  9501. return upperAddress ?
  9502. CreateAllocationRequest_UpperAddress(
  9503. currentFrameIndex, frameInUseCount, bufferImageGranularity,
  9504. allocSize, allocAlignment, allocType, canMakeOtherLost, strategy, pAllocationRequest) :
  9505. CreateAllocationRequest_LowerAddress(
  9506. currentFrameIndex, frameInUseCount, bufferImageGranularity,
  9507. allocSize, allocAlignment, allocType, canMakeOtherLost, strategy, pAllocationRequest);
  9508. }
  9509. bool VmaBlockMetadata_Linear::CreateAllocationRequest_UpperAddress(
  9510. uint32_t currentFrameIndex,
  9511. uint32_t frameInUseCount,
  9512. VkDeviceSize bufferImageGranularity,
  9513. VkDeviceSize allocSize,
  9514. VkDeviceSize allocAlignment,
  9515. VmaSuballocationType allocType,
  9516. bool canMakeOtherLost,
  9517. uint32_t strategy,
  9518. VmaAllocationRequest* pAllocationRequest)
  9519. {
  9520. const VkDeviceSize size = GetSize();
  9521. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  9522. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  9523. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  9524. {
  9525. VMA_ASSERT(0 && "Trying to use pool with linear algorithm as double stack, while it is already being used as ring buffer.");
  9526. return false;
  9527. }
  9528. // Try to allocate before 2nd.back(), or end of block if 2nd.empty().
  9529. if(allocSize > size)
  9530. {
  9531. return false;
  9532. }
  9533. VkDeviceSize resultBaseOffset = size - allocSize;
  9534. if(!suballocations2nd.empty())
  9535. {
  9536. const VmaSuballocation& lastSuballoc = suballocations2nd.back();
  9537. resultBaseOffset = lastSuballoc.offset - allocSize;
  9538. if(allocSize > lastSuballoc.offset)
  9539. {
  9540. return false;
  9541. }
  9542. }
  9543. // Start from offset equal to end of free space.
  9544. VkDeviceSize resultOffset = resultBaseOffset;
  9545. // Apply VMA_DEBUG_MARGIN at the end.
  9546. if(VMA_DEBUG_MARGIN > 0)
  9547. {
  9548. if(resultOffset < VMA_DEBUG_MARGIN)
  9549. {
  9550. return false;
  9551. }
  9552. resultOffset -= VMA_DEBUG_MARGIN;
  9553. }
  9554. // Apply alignment.
  9555. resultOffset = VmaAlignDown(resultOffset, allocAlignment);
  9556. // Check next suballocations from 2nd for BufferImageGranularity conflicts.
  9557. // Make bigger alignment if necessary.
  9558. if(bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations2nd.empty())
  9559. {
  9560. bool bufferImageGranularityConflict = false;
  9561. for(size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; )
  9562. {
  9563. const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex];
  9564. if(VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  9565. {
  9566. if(VmaIsBufferImageGranularityConflict(nextSuballoc.type, allocType))
  9567. {
  9568. bufferImageGranularityConflict = true;
  9569. break;
  9570. }
  9571. }
  9572. else
  9573. // Already on previous page.
  9574. break;
  9575. }
  9576. if(bufferImageGranularityConflict)
  9577. {
  9578. resultOffset = VmaAlignDown(resultOffset, bufferImageGranularity);
  9579. }
  9580. }
  9581. // There is enough free space.
  9582. const VkDeviceSize endOf1st = !suballocations1st.empty() ?
  9583. suballocations1st.back().offset + suballocations1st.back().size :
  9584. 0;
  9585. if(endOf1st + VMA_DEBUG_MARGIN <= resultOffset)
  9586. {
  9587. // Check previous suballocations for BufferImageGranularity conflicts.
  9588. // If conflict exists, allocation cannot be made here.
  9589. if(bufferImageGranularity > 1)
  9590. {
  9591. for(size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; )
  9592. {
  9593. const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex];
  9594. if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
  9595. {
  9596. if(VmaIsBufferImageGranularityConflict(allocType, prevSuballoc.type))
  9597. {
  9598. return false;
  9599. }
  9600. }
  9601. else
  9602. {
  9603. // Already on next page.
  9604. break;
  9605. }
  9606. }
  9607. }
  9608. // All tests passed: Success.
  9609. pAllocationRequest->offset = resultOffset;
  9610. pAllocationRequest->sumFreeSize = resultBaseOffset + allocSize - endOf1st;
  9611. pAllocationRequest->sumItemSize = 0;
  9612. // pAllocationRequest->item unused.
  9613. pAllocationRequest->itemsToMakeLostCount = 0;
  9614. pAllocationRequest->type = VmaAllocationRequestType::UpperAddress;
  9615. return true;
  9616. }
  9617. return false;
  9618. }
  9619. bool VmaBlockMetadata_Linear::CreateAllocationRequest_LowerAddress(
  9620. uint32_t currentFrameIndex,
  9621. uint32_t frameInUseCount,
  9622. VkDeviceSize bufferImageGranularity,
  9623. VkDeviceSize allocSize,
  9624. VkDeviceSize allocAlignment,
  9625. VmaSuballocationType allocType,
  9626. bool canMakeOtherLost,
  9627. uint32_t strategy,
  9628. VmaAllocationRequest* pAllocationRequest)
  9629. {
  9630. const VkDeviceSize size = GetSize();
  9631. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  9632. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  9633. if(m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  9634. {
  9635. // Try to allocate at the end of 1st vector.
  9636. VkDeviceSize resultBaseOffset = 0;
  9637. if(!suballocations1st.empty())
  9638. {
  9639. const VmaSuballocation& lastSuballoc = suballocations1st.back();
  9640. resultBaseOffset = lastSuballoc.offset + lastSuballoc.size;
  9641. }
  9642. // Start from offset equal to beginning of free space.
  9643. VkDeviceSize resultOffset = resultBaseOffset;
  9644. // Apply VMA_DEBUG_MARGIN at the beginning.
  9645. if(VMA_DEBUG_MARGIN > 0)
  9646. {
  9647. resultOffset += VMA_DEBUG_MARGIN;
  9648. }
  9649. // Apply alignment.
  9650. resultOffset = VmaAlignUp(resultOffset, allocAlignment);
  9651. // Check previous suballocations for BufferImageGranularity conflicts.
  9652. // Make bigger alignment if necessary.
  9653. if(bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations1st.empty())
  9654. {
  9655. bool bufferImageGranularityConflict = false;
  9656. for(size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; )
  9657. {
  9658. const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex];
  9659. if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
  9660. {
  9661. if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
  9662. {
  9663. bufferImageGranularityConflict = true;
  9664. break;
  9665. }
  9666. }
  9667. else
  9668. // Already on previous page.
  9669. break;
  9670. }
  9671. if(bufferImageGranularityConflict)
  9672. {
  9673. resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity);
  9674. }
  9675. }
  9676. const VkDeviceSize freeSpaceEnd = m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ?
  9677. suballocations2nd.back().offset : size;
  9678. // There is enough free space at the end after alignment.
  9679. if(resultOffset + allocSize + VMA_DEBUG_MARGIN <= freeSpaceEnd)
  9680. {
  9681. // Check next suballocations for BufferImageGranularity conflicts.
  9682. // If conflict exists, allocation cannot be made here.
  9683. if((allocSize % bufferImageGranularity || resultOffset % bufferImageGranularity) && m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  9684. {
  9685. for(size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; )
  9686. {
  9687. const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex];
  9688. if(VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  9689. {
  9690. if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
  9691. {
  9692. return false;
  9693. }
  9694. }
  9695. else
  9696. {
  9697. // Already on previous page.
  9698. break;
  9699. }
  9700. }
  9701. }
  9702. // All tests passed: Success.
  9703. pAllocationRequest->offset = resultOffset;
  9704. pAllocationRequest->sumFreeSize = freeSpaceEnd - resultBaseOffset;
  9705. pAllocationRequest->sumItemSize = 0;
  9706. // pAllocationRequest->item, customData unused.
  9707. pAllocationRequest->type = VmaAllocationRequestType::EndOf1st;
  9708. pAllocationRequest->itemsToMakeLostCount = 0;
  9709. return true;
  9710. }
  9711. }
  9712. // Wrap-around to end of 2nd vector. Try to allocate there, watching for the
  9713. // beginning of 1st vector as the end of free space.
  9714. if(m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  9715. {
  9716. VMA_ASSERT(!suballocations1st.empty());
  9717. VkDeviceSize resultBaseOffset = 0;
  9718. if(!suballocations2nd.empty())
  9719. {
  9720. const VmaSuballocation& lastSuballoc = suballocations2nd.back();
  9721. resultBaseOffset = lastSuballoc.offset + lastSuballoc.size;
  9722. }
  9723. // Start from offset equal to beginning of free space.
  9724. VkDeviceSize resultOffset = resultBaseOffset;
  9725. // Apply VMA_DEBUG_MARGIN at the beginning.
  9726. if(VMA_DEBUG_MARGIN > 0)
  9727. {
  9728. resultOffset += VMA_DEBUG_MARGIN;
  9729. }
  9730. // Apply alignment.
  9731. resultOffset = VmaAlignUp(resultOffset, allocAlignment);
  9732. // Check previous suballocations for BufferImageGranularity conflicts.
  9733. // Make bigger alignment if necessary.
  9734. if(bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations2nd.empty())
  9735. {
  9736. bool bufferImageGranularityConflict = false;
  9737. for(size_t prevSuballocIndex = suballocations2nd.size(); prevSuballocIndex--; )
  9738. {
  9739. const VmaSuballocation& prevSuballoc = suballocations2nd[prevSuballocIndex];
  9740. if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
  9741. {
  9742. if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
  9743. {
  9744. bufferImageGranularityConflict = true;
  9745. break;
  9746. }
  9747. }
  9748. else
  9749. // Already on previous page.
  9750. break;
  9751. }
  9752. if(bufferImageGranularityConflict)
  9753. {
  9754. resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity);
  9755. }
  9756. }
  9757. pAllocationRequest->itemsToMakeLostCount = 0;
  9758. pAllocationRequest->sumItemSize = 0;
  9759. size_t index1st = m_1stNullItemsBeginCount;
  9760. if(canMakeOtherLost)
  9761. {
  9762. while(index1st < suballocations1st.size() &&
  9763. resultOffset + allocSize + VMA_DEBUG_MARGIN > suballocations1st[index1st].offset)
  9764. {
  9765. // Next colliding allocation at the beginning of 1st vector found. Try to make it lost.
  9766. const VmaSuballocation& suballoc = suballocations1st[index1st];
  9767. if(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE)
  9768. {
  9769. // No problem.
  9770. }
  9771. else
  9772. {
  9773. VMA_ASSERT(suballoc.hAllocation != VK_NULL_HANDLE);
  9774. if(suballoc.hAllocation->CanBecomeLost() &&
  9775. suballoc.hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
  9776. {
  9777. ++pAllocationRequest->itemsToMakeLostCount;
  9778. pAllocationRequest->sumItemSize += suballoc.size;
  9779. }
  9780. else
  9781. {
  9782. return false;
  9783. }
  9784. }
  9785. ++index1st;
  9786. }
  9787. // Check next suballocations for BufferImageGranularity conflicts.
  9788. // If conflict exists, we must mark more allocations lost or fail.
  9789. if(allocSize % bufferImageGranularity || resultOffset % bufferImageGranularity)
  9790. {
  9791. while(index1st < suballocations1st.size())
  9792. {
  9793. const VmaSuballocation& suballoc = suballocations1st[index1st];
  9794. if(VmaBlocksOnSamePage(resultOffset, allocSize, suballoc.offset, bufferImageGranularity))
  9795. {
  9796. if(suballoc.hAllocation != VK_NULL_HANDLE)
  9797. {
  9798. // Not checking actual VmaIsBufferImageGranularityConflict(allocType, suballoc.type).
  9799. if(suballoc.hAllocation->CanBecomeLost() &&
  9800. suballoc.hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
  9801. {
  9802. ++pAllocationRequest->itemsToMakeLostCount;
  9803. pAllocationRequest->sumItemSize += suballoc.size;
  9804. }
  9805. else
  9806. {
  9807. return false;
  9808. }
  9809. }
  9810. }
  9811. else
  9812. {
  9813. // Already on next page.
  9814. break;
  9815. }
  9816. ++index1st;
  9817. }
  9818. }
  9819. // Special case: There is not enough room at the end for this allocation, even after making all from the 1st lost.
  9820. if(index1st == suballocations1st.size() &&
  9821. resultOffset + allocSize + VMA_DEBUG_MARGIN > size)
  9822. {
  9823. // TODO: This is a known bug that it's not yet implemented and the allocation is failing.
  9824. VMA_DEBUG_LOG("Unsupported special case in custom pool with linear allocation algorithm used as ring buffer with allocations that can be lost.");
  9825. }
  9826. }
  9827. // There is enough free space at the end after alignment.
  9828. if((index1st == suballocations1st.size() && resultOffset + allocSize + VMA_DEBUG_MARGIN <= size) ||
  9829. (index1st < suballocations1st.size() && resultOffset + allocSize + VMA_DEBUG_MARGIN <= suballocations1st[index1st].offset))
  9830. {
  9831. // Check next suballocations for BufferImageGranularity conflicts.
  9832. // If conflict exists, allocation cannot be made here.
  9833. if(allocSize % bufferImageGranularity || resultOffset % bufferImageGranularity)
  9834. {
  9835. for(size_t nextSuballocIndex = index1st;
  9836. nextSuballocIndex < suballocations1st.size();
  9837. nextSuballocIndex++)
  9838. {
  9839. const VmaSuballocation& nextSuballoc = suballocations1st[nextSuballocIndex];
  9840. if(VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  9841. {
  9842. if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
  9843. {
  9844. return false;
  9845. }
  9846. }
  9847. else
  9848. {
  9849. // Already on next page.
  9850. break;
  9851. }
  9852. }
  9853. }
  9854. // All tests passed: Success.
  9855. pAllocationRequest->offset = resultOffset;
  9856. pAllocationRequest->sumFreeSize =
  9857. (index1st < suballocations1st.size() ? suballocations1st[index1st].offset : size)
  9858. - resultBaseOffset
  9859. - pAllocationRequest->sumItemSize;
  9860. pAllocationRequest->type = VmaAllocationRequestType::EndOf2nd;
  9861. // pAllocationRequest->item, customData unused.
  9862. return true;
  9863. }
  9864. }
  9865. return false;
  9866. }
  9867. bool VmaBlockMetadata_Linear::MakeRequestedAllocationsLost(
  9868. uint32_t currentFrameIndex,
  9869. uint32_t frameInUseCount,
  9870. VmaAllocationRequest* pAllocationRequest)
  9871. {
  9872. if(pAllocationRequest->itemsToMakeLostCount == 0)
  9873. {
  9874. return true;
  9875. }
  9876. VMA_ASSERT(m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER);
  9877. // We always start from 1st.
  9878. SuballocationVectorType* suballocations = &AccessSuballocations1st();
  9879. size_t index = m_1stNullItemsBeginCount;
  9880. size_t madeLostCount = 0;
  9881. while(madeLostCount < pAllocationRequest->itemsToMakeLostCount)
  9882. {
  9883. if(index == suballocations->size())
  9884. {
  9885. index = 0;
  9886. // If we get to the end of 1st, we wrap around to beginning of 2nd of 1st.
  9887. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  9888. {
  9889. suballocations = &AccessSuballocations2nd();
  9890. }
  9891. // else: m_2ndVectorMode == SECOND_VECTOR_EMPTY:
  9892. // suballocations continues pointing at AccessSuballocations1st().
  9893. VMA_ASSERT(!suballocations->empty());
  9894. }
  9895. VmaSuballocation& suballoc = (*suballocations)[index];
  9896. if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  9897. {
  9898. VMA_ASSERT(suballoc.hAllocation != VK_NULL_HANDLE);
  9899. VMA_ASSERT(suballoc.hAllocation->CanBecomeLost());
  9900. if(suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
  9901. {
  9902. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  9903. suballoc.hAllocation = VK_NULL_HANDLE;
  9904. m_SumFreeSize += suballoc.size;
  9905. if(suballocations == &AccessSuballocations1st())
  9906. {
  9907. ++m_1stNullItemsMiddleCount;
  9908. }
  9909. else
  9910. {
  9911. ++m_2ndNullItemsCount;
  9912. }
  9913. ++madeLostCount;
  9914. }
  9915. else
  9916. {
  9917. return false;
  9918. }
  9919. }
  9920. ++index;
  9921. }
  9922. CleanupAfterFree();
  9923. //VMA_HEAVY_ASSERT(Validate()); // Already called by CleanupAfterFree().
  9924. return true;
  9925. }
  9926. uint32_t VmaBlockMetadata_Linear::MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount)
  9927. {
  9928. uint32_t lostAllocationCount = 0;
  9929. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  9930. for(size_t i = m_1stNullItemsBeginCount, count = suballocations1st.size(); i < count; ++i)
  9931. {
  9932. VmaSuballocation& suballoc = suballocations1st[i];
  9933. if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE &&
  9934. suballoc.hAllocation->CanBecomeLost() &&
  9935. suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
  9936. {
  9937. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  9938. suballoc.hAllocation = VK_NULL_HANDLE;
  9939. ++m_1stNullItemsMiddleCount;
  9940. m_SumFreeSize += suballoc.size;
  9941. ++lostAllocationCount;
  9942. }
  9943. }
  9944. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  9945. for(size_t i = 0, count = suballocations2nd.size(); i < count; ++i)
  9946. {
  9947. VmaSuballocation& suballoc = suballocations2nd[i];
  9948. if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE &&
  9949. suballoc.hAllocation->CanBecomeLost() &&
  9950. suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
  9951. {
  9952. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  9953. suballoc.hAllocation = VK_NULL_HANDLE;
  9954. ++m_2ndNullItemsCount;
  9955. m_SumFreeSize += suballoc.size;
  9956. ++lostAllocationCount;
  9957. }
  9958. }
  9959. if(lostAllocationCount)
  9960. {
  9961. CleanupAfterFree();
  9962. }
  9963. return lostAllocationCount;
  9964. }
  9965. VkResult VmaBlockMetadata_Linear::CheckCorruption(const void* pBlockData)
  9966. {
  9967. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  9968. for(size_t i = m_1stNullItemsBeginCount, count = suballocations1st.size(); i < count; ++i)
  9969. {
  9970. const VmaSuballocation& suballoc = suballocations1st[i];
  9971. if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  9972. {
  9973. if(!VmaValidateMagicValue(pBlockData, suballoc.offset - VMA_DEBUG_MARGIN))
  9974. {
  9975. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE VALIDATED ALLOCATION!");
  9976. return VK_ERROR_VALIDATION_FAILED_EXT;
  9977. }
  9978. if(!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size))
  9979. {
  9980. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
  9981. return VK_ERROR_VALIDATION_FAILED_EXT;
  9982. }
  9983. }
  9984. }
  9985. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  9986. for(size_t i = 0, count = suballocations2nd.size(); i < count; ++i)
  9987. {
  9988. const VmaSuballocation& suballoc = suballocations2nd[i];
  9989. if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  9990. {
  9991. if(!VmaValidateMagicValue(pBlockData, suballoc.offset - VMA_DEBUG_MARGIN))
  9992. {
  9993. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE VALIDATED ALLOCATION!");
  9994. return VK_ERROR_VALIDATION_FAILED_EXT;
  9995. }
  9996. if(!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size))
  9997. {
  9998. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
  9999. return VK_ERROR_VALIDATION_FAILED_EXT;
  10000. }
  10001. }
  10002. }
  10003. return VK_SUCCESS;
  10004. }
  10005. void VmaBlockMetadata_Linear::Alloc(
  10006. const VmaAllocationRequest& request,
  10007. VmaSuballocationType type,
  10008. VkDeviceSize allocSize,
  10009. VmaAllocation hAllocation)
  10010. {
  10011. const VmaSuballocation newSuballoc = { request.offset, allocSize, hAllocation, type };
  10012. switch(request.type)
  10013. {
  10014. case VmaAllocationRequestType::UpperAddress:
  10015. {
  10016. VMA_ASSERT(m_2ndVectorMode != SECOND_VECTOR_RING_BUFFER &&
  10017. "CRITICAL ERROR: Trying to use linear allocator as double stack while it was already used as ring buffer.");
  10018. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  10019. suballocations2nd.push_back(newSuballoc);
  10020. m_2ndVectorMode = SECOND_VECTOR_DOUBLE_STACK;
  10021. }
  10022. break;
  10023. case VmaAllocationRequestType::EndOf1st:
  10024. {
  10025. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  10026. VMA_ASSERT(suballocations1st.empty() ||
  10027. request.offset >= suballocations1st.back().offset + suballocations1st.back().size);
  10028. // Check if it fits before the end of the block.
  10029. VMA_ASSERT(request.offset + allocSize <= GetSize());
  10030. suballocations1st.push_back(newSuballoc);
  10031. }
  10032. break;
  10033. case VmaAllocationRequestType::EndOf2nd:
  10034. {
  10035. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  10036. // New allocation at the end of 2-part ring buffer, so before first allocation from 1st vector.
  10037. VMA_ASSERT(!suballocations1st.empty() &&
  10038. request.offset + allocSize <= suballocations1st[m_1stNullItemsBeginCount].offset);
  10039. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  10040. switch(m_2ndVectorMode)
  10041. {
  10042. case SECOND_VECTOR_EMPTY:
  10043. // First allocation from second part ring buffer.
  10044. VMA_ASSERT(suballocations2nd.empty());
  10045. m_2ndVectorMode = SECOND_VECTOR_RING_BUFFER;
  10046. break;
  10047. case SECOND_VECTOR_RING_BUFFER:
  10048. // 2-part ring buffer is already started.
  10049. VMA_ASSERT(!suballocations2nd.empty());
  10050. break;
  10051. case SECOND_VECTOR_DOUBLE_STACK:
  10052. VMA_ASSERT(0 && "CRITICAL ERROR: Trying to use linear allocator as ring buffer while it was already used as double stack.");
  10053. break;
  10054. default:
  10055. VMA_ASSERT(0);
  10056. }
  10057. suballocations2nd.push_back(newSuballoc);
  10058. }
  10059. break;
  10060. default:
  10061. VMA_ASSERT(0 && "CRITICAL INTERNAL ERROR.");
  10062. }
  10063. m_SumFreeSize -= newSuballoc.size;
  10064. }
  10065. void VmaBlockMetadata_Linear::Free(const VmaAllocation allocation)
  10066. {
  10067. FreeAtOffset(allocation->GetOffset());
  10068. }
  10069. void VmaBlockMetadata_Linear::FreeAtOffset(VkDeviceSize offset)
  10070. {
  10071. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  10072. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  10073. if(!suballocations1st.empty())
  10074. {
  10075. // First allocation: Mark it as next empty at the beginning.
  10076. VmaSuballocation& firstSuballoc = suballocations1st[m_1stNullItemsBeginCount];
  10077. if(firstSuballoc.offset == offset)
  10078. {
  10079. firstSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  10080. firstSuballoc.hAllocation = VK_NULL_HANDLE;
  10081. m_SumFreeSize += firstSuballoc.size;
  10082. ++m_1stNullItemsBeginCount;
  10083. CleanupAfterFree();
  10084. return;
  10085. }
  10086. }
  10087. // Last allocation in 2-part ring buffer or top of upper stack (same logic).
  10088. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ||
  10089. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  10090. {
  10091. VmaSuballocation& lastSuballoc = suballocations2nd.back();
  10092. if(lastSuballoc.offset == offset)
  10093. {
  10094. m_SumFreeSize += lastSuballoc.size;
  10095. suballocations2nd.pop_back();
  10096. CleanupAfterFree();
  10097. return;
  10098. }
  10099. }
  10100. // Last allocation in 1st vector.
  10101. else if(m_2ndVectorMode == SECOND_VECTOR_EMPTY)
  10102. {
  10103. VmaSuballocation& lastSuballoc = suballocations1st.back();
  10104. if(lastSuballoc.offset == offset)
  10105. {
  10106. m_SumFreeSize += lastSuballoc.size;
  10107. suballocations1st.pop_back();
  10108. CleanupAfterFree();
  10109. return;
  10110. }
  10111. }
  10112. // Item from the middle of 1st vector.
  10113. {
  10114. VmaSuballocation refSuballoc;
  10115. refSuballoc.offset = offset;
  10116. // Rest of members stays uninitialized intentionally for better performance.
  10117. SuballocationVectorType::iterator it = VmaBinaryFindSorted(
  10118. suballocations1st.begin() + m_1stNullItemsBeginCount,
  10119. suballocations1st.end(),
  10120. refSuballoc,
  10121. VmaSuballocationOffsetLess());
  10122. if(it != suballocations1st.end())
  10123. {
  10124. it->type = VMA_SUBALLOCATION_TYPE_FREE;
  10125. it->hAllocation = VK_NULL_HANDLE;
  10126. ++m_1stNullItemsMiddleCount;
  10127. m_SumFreeSize += it->size;
  10128. CleanupAfterFree();
  10129. return;
  10130. }
  10131. }
  10132. if(m_2ndVectorMode != SECOND_VECTOR_EMPTY)
  10133. {
  10134. // Item from the middle of 2nd vector.
  10135. VmaSuballocation refSuballoc;
  10136. refSuballoc.offset = offset;
  10137. // Rest of members stays uninitialized intentionally for better performance.
  10138. SuballocationVectorType::iterator it = m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ?
  10139. VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetLess()) :
  10140. VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetGreater());
  10141. if(it != suballocations2nd.end())
  10142. {
  10143. it->type = VMA_SUBALLOCATION_TYPE_FREE;
  10144. it->hAllocation = VK_NULL_HANDLE;
  10145. ++m_2ndNullItemsCount;
  10146. m_SumFreeSize += it->size;
  10147. CleanupAfterFree();
  10148. return;
  10149. }
  10150. }
  10151. VMA_ASSERT(0 && "Allocation to free not found in linear allocator!");
  10152. }
  10153. bool VmaBlockMetadata_Linear::ShouldCompact1st() const
  10154. {
  10155. const size_t nullItemCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount;
  10156. const size_t suballocCount = AccessSuballocations1st().size();
  10157. return suballocCount > 32 && nullItemCount * 2 >= (suballocCount - nullItemCount) * 3;
  10158. }
  10159. void VmaBlockMetadata_Linear::CleanupAfterFree()
  10160. {
  10161. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  10162. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  10163. if(IsEmpty())
  10164. {
  10165. suballocations1st.clear();
  10166. suballocations2nd.clear();
  10167. m_1stNullItemsBeginCount = 0;
  10168. m_1stNullItemsMiddleCount = 0;
  10169. m_2ndNullItemsCount = 0;
  10170. m_2ndVectorMode = SECOND_VECTOR_EMPTY;
  10171. }
  10172. else
  10173. {
  10174. const size_t suballoc1stCount = suballocations1st.size();
  10175. const size_t nullItem1stCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount;
  10176. VMA_ASSERT(nullItem1stCount <= suballoc1stCount);
  10177. // Find more null items at the beginning of 1st vector.
  10178. while(m_1stNullItemsBeginCount < suballoc1stCount &&
  10179. suballocations1st[m_1stNullItemsBeginCount].hAllocation == VK_NULL_HANDLE)
  10180. {
  10181. ++m_1stNullItemsBeginCount;
  10182. --m_1stNullItemsMiddleCount;
  10183. }
  10184. // Find more null items at the end of 1st vector.
  10185. while(m_1stNullItemsMiddleCount > 0 &&
  10186. suballocations1st.back().hAllocation == VK_NULL_HANDLE)
  10187. {
  10188. --m_1stNullItemsMiddleCount;
  10189. suballocations1st.pop_back();
  10190. }
  10191. // Find more null items at the end of 2nd vector.
  10192. while(m_2ndNullItemsCount > 0 &&
  10193. suballocations2nd.back().hAllocation == VK_NULL_HANDLE)
  10194. {
  10195. --m_2ndNullItemsCount;
  10196. suballocations2nd.pop_back();
  10197. }
  10198. // Find more null items at the beginning of 2nd vector.
  10199. while(m_2ndNullItemsCount > 0 &&
  10200. suballocations2nd[0].hAllocation == VK_NULL_HANDLE)
  10201. {
  10202. --m_2ndNullItemsCount;
  10203. VmaVectorRemove(suballocations2nd, 0);
  10204. }
  10205. if(ShouldCompact1st())
  10206. {
  10207. const size_t nonNullItemCount = suballoc1stCount - nullItem1stCount;
  10208. size_t srcIndex = m_1stNullItemsBeginCount;
  10209. for(size_t dstIndex = 0; dstIndex < nonNullItemCount; ++dstIndex)
  10210. {
  10211. while(suballocations1st[srcIndex].hAllocation == VK_NULL_HANDLE)
  10212. {
  10213. ++srcIndex;
  10214. }
  10215. if(dstIndex != srcIndex)
  10216. {
  10217. suballocations1st[dstIndex] = suballocations1st[srcIndex];
  10218. }
  10219. ++srcIndex;
  10220. }
  10221. suballocations1st.resize(nonNullItemCount);
  10222. m_1stNullItemsBeginCount = 0;
  10223. m_1stNullItemsMiddleCount = 0;
  10224. }
  10225. // 2nd vector became empty.
  10226. if(suballocations2nd.empty())
  10227. {
  10228. m_2ndVectorMode = SECOND_VECTOR_EMPTY;
  10229. }
  10230. // 1st vector became empty.
  10231. if(suballocations1st.size() - m_1stNullItemsBeginCount == 0)
  10232. {
  10233. suballocations1st.clear();
  10234. m_1stNullItemsBeginCount = 0;
  10235. if(!suballocations2nd.empty() && m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  10236. {
  10237. // Swap 1st with 2nd. Now 2nd is empty.
  10238. m_2ndVectorMode = SECOND_VECTOR_EMPTY;
  10239. m_1stNullItemsMiddleCount = m_2ndNullItemsCount;
  10240. while(m_1stNullItemsBeginCount < suballocations2nd.size() &&
  10241. suballocations2nd[m_1stNullItemsBeginCount].hAllocation == VK_NULL_HANDLE)
  10242. {
  10243. ++m_1stNullItemsBeginCount;
  10244. --m_1stNullItemsMiddleCount;
  10245. }
  10246. m_2ndNullItemsCount = 0;
  10247. m_1stVectorIndex ^= 1;
  10248. }
  10249. }
  10250. }
  10251. VMA_HEAVY_ASSERT(Validate());
  10252. }
  10253. ////////////////////////////////////////////////////////////////////////////////
  10254. // class VmaBlockMetadata_Buddy
  10255. VmaBlockMetadata_Buddy::VmaBlockMetadata_Buddy(VmaAllocator hAllocator) :
  10256. VmaBlockMetadata(hAllocator),
  10257. m_Root(VMA_NULL),
  10258. m_AllocationCount(0),
  10259. m_FreeCount(1),
  10260. m_SumFreeSize(0)
  10261. {
  10262. memset(m_FreeList, 0, sizeof(m_FreeList));
  10263. }
  10264. VmaBlockMetadata_Buddy::~VmaBlockMetadata_Buddy()
  10265. {
  10266. DeleteNode(m_Root);
  10267. }
  10268. void VmaBlockMetadata_Buddy::Init(VkDeviceSize size)
  10269. {
  10270. VmaBlockMetadata::Init(size);
  10271. m_UsableSize = VmaPrevPow2(size);
  10272. m_SumFreeSize = m_UsableSize;
  10273. // Calculate m_LevelCount.
  10274. m_LevelCount = 1;
  10275. while(m_LevelCount < MAX_LEVELS &&
  10276. LevelToNodeSize(m_LevelCount) >= MIN_NODE_SIZE)
  10277. {
  10278. ++m_LevelCount;
  10279. }
  10280. Node* rootNode = vma_new(GetAllocationCallbacks(), Node)();
  10281. rootNode->offset = 0;
  10282. rootNode->type = Node::TYPE_FREE;
  10283. rootNode->parent = VMA_NULL;
  10284. rootNode->buddy = VMA_NULL;
  10285. m_Root = rootNode;
  10286. AddToFreeListFront(0, rootNode);
  10287. }
  10288. bool VmaBlockMetadata_Buddy::Validate() const
  10289. {
  10290. // Validate tree.
  10291. ValidationContext ctx;
  10292. if(!ValidateNode(ctx, VMA_NULL, m_Root, 0, LevelToNodeSize(0)))
  10293. {
  10294. VMA_VALIDATE(false && "ValidateNode failed.");
  10295. }
  10296. VMA_VALIDATE(m_AllocationCount == ctx.calculatedAllocationCount);
  10297. VMA_VALIDATE(m_SumFreeSize == ctx.calculatedSumFreeSize);
  10298. // Validate free node lists.
  10299. for(uint32_t level = 0; level < m_LevelCount; ++level)
  10300. {
  10301. VMA_VALIDATE(m_FreeList[level].front == VMA_NULL ||
  10302. m_FreeList[level].front->free.prev == VMA_NULL);
  10303. for(Node* node = m_FreeList[level].front;
  10304. node != VMA_NULL;
  10305. node = node->free.next)
  10306. {
  10307. VMA_VALIDATE(node->type == Node::TYPE_FREE);
  10308. if(node->free.next == VMA_NULL)
  10309. {
  10310. VMA_VALIDATE(m_FreeList[level].back == node);
  10311. }
  10312. else
  10313. {
  10314. VMA_VALIDATE(node->free.next->free.prev == node);
  10315. }
  10316. }
  10317. }
  10318. // Validate that free lists ar higher levels are empty.
  10319. for(uint32_t level = m_LevelCount; level < MAX_LEVELS; ++level)
  10320. {
  10321. VMA_VALIDATE(m_FreeList[level].front == VMA_NULL && m_FreeList[level].back == VMA_NULL);
  10322. }
  10323. return true;
  10324. }
  10325. VkDeviceSize VmaBlockMetadata_Buddy::GetUnusedRangeSizeMax() const
  10326. {
  10327. for(uint32_t level = 0; level < m_LevelCount; ++level)
  10328. {
  10329. if(m_FreeList[level].front != VMA_NULL)
  10330. {
  10331. return LevelToNodeSize(level);
  10332. }
  10333. }
  10334. return 0;
  10335. }
  10336. void VmaBlockMetadata_Buddy::CalcAllocationStatInfo(VmaStatInfo& outInfo) const
  10337. {
  10338. const VkDeviceSize unusableSize = GetUnusableSize();
  10339. outInfo.blockCount = 1;
  10340. outInfo.allocationCount = outInfo.unusedRangeCount = 0;
  10341. outInfo.usedBytes = outInfo.unusedBytes = 0;
  10342. outInfo.allocationSizeMax = outInfo.unusedRangeSizeMax = 0;
  10343. outInfo.allocationSizeMin = outInfo.unusedRangeSizeMin = UINT64_MAX;
  10344. outInfo.allocationSizeAvg = outInfo.unusedRangeSizeAvg = 0; // Unused.
  10345. CalcAllocationStatInfoNode(outInfo, m_Root, LevelToNodeSize(0));
  10346. if(unusableSize > 0)
  10347. {
  10348. ++outInfo.unusedRangeCount;
  10349. outInfo.unusedBytes += unusableSize;
  10350. outInfo.unusedRangeSizeMax = VMA_MAX(outInfo.unusedRangeSizeMax, unusableSize);
  10351. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusableSize);
  10352. }
  10353. }
  10354. void VmaBlockMetadata_Buddy::AddPoolStats(VmaPoolStats& inoutStats) const
  10355. {
  10356. const VkDeviceSize unusableSize = GetUnusableSize();
  10357. inoutStats.size += GetSize();
  10358. inoutStats.unusedSize += m_SumFreeSize + unusableSize;
  10359. inoutStats.allocationCount += m_AllocationCount;
  10360. inoutStats.unusedRangeCount += m_FreeCount;
  10361. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, GetUnusedRangeSizeMax());
  10362. if(unusableSize > 0)
  10363. {
  10364. ++inoutStats.unusedRangeCount;
  10365. // Not updating inoutStats.unusedRangeSizeMax with unusableSize because this space is not available for allocations.
  10366. }
  10367. }
  10368. #if VMA_STATS_STRING_ENABLED
  10369. void VmaBlockMetadata_Buddy::PrintDetailedMap(class VmaJsonWriter& json) const
  10370. {
  10371. // TODO optimize
  10372. VmaStatInfo stat;
  10373. CalcAllocationStatInfo(stat);
  10374. PrintDetailedMap_Begin(
  10375. json,
  10376. stat.unusedBytes,
  10377. stat.allocationCount,
  10378. stat.unusedRangeCount);
  10379. PrintDetailedMapNode(json, m_Root, LevelToNodeSize(0));
  10380. const VkDeviceSize unusableSize = GetUnusableSize();
  10381. if(unusableSize > 0)
  10382. {
  10383. PrintDetailedMap_UnusedRange(json,
  10384. m_UsableSize, // offset
  10385. unusableSize); // size
  10386. }
  10387. PrintDetailedMap_End(json);
  10388. }
  10389. #endif // #if VMA_STATS_STRING_ENABLED
  10390. bool VmaBlockMetadata_Buddy::CreateAllocationRequest(
  10391. uint32_t currentFrameIndex,
  10392. uint32_t frameInUseCount,
  10393. VkDeviceSize bufferImageGranularity,
  10394. VkDeviceSize allocSize,
  10395. VkDeviceSize allocAlignment,
  10396. bool upperAddress,
  10397. VmaSuballocationType allocType,
  10398. bool canMakeOtherLost,
  10399. uint32_t strategy,
  10400. VmaAllocationRequest* pAllocationRequest)
  10401. {
  10402. VMA_ASSERT(!upperAddress && "VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT can be used only with linear algorithm.");
  10403. // Simple way to respect bufferImageGranularity. May be optimized some day.
  10404. // Whenever it might be an OPTIMAL image...
  10405. if(allocType == VMA_SUBALLOCATION_TYPE_UNKNOWN ||
  10406. allocType == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
  10407. allocType == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL)
  10408. {
  10409. allocAlignment = VMA_MAX(allocAlignment, bufferImageGranularity);
  10410. allocSize = VMA_MAX(allocSize, bufferImageGranularity);
  10411. }
  10412. if(allocSize > m_UsableSize)
  10413. {
  10414. return false;
  10415. }
  10416. const uint32_t targetLevel = AllocSizeToLevel(allocSize);
  10417. for(uint32_t level = targetLevel + 1; level--; )
  10418. {
  10419. for(Node* freeNode = m_FreeList[level].front;
  10420. freeNode != VMA_NULL;
  10421. freeNode = freeNode->free.next)
  10422. {
  10423. if(freeNode->offset % allocAlignment == 0)
  10424. {
  10425. pAllocationRequest->type = VmaAllocationRequestType::Normal;
  10426. pAllocationRequest->offset = freeNode->offset;
  10427. pAllocationRequest->sumFreeSize = LevelToNodeSize(level);
  10428. pAllocationRequest->sumItemSize = 0;
  10429. pAllocationRequest->itemsToMakeLostCount = 0;
  10430. pAllocationRequest->customData = (void*)(uintptr_t)level;
  10431. return true;
  10432. }
  10433. }
  10434. }
  10435. return false;
  10436. }
  10437. bool VmaBlockMetadata_Buddy::MakeRequestedAllocationsLost(
  10438. uint32_t currentFrameIndex,
  10439. uint32_t frameInUseCount,
  10440. VmaAllocationRequest* pAllocationRequest)
  10441. {
  10442. /*
  10443. Lost allocations are not supported in buddy allocator at the moment.
  10444. Support might be added in the future.
  10445. */
  10446. return pAllocationRequest->itemsToMakeLostCount == 0;
  10447. }
  10448. uint32_t VmaBlockMetadata_Buddy::MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount)
  10449. {
  10450. /*
  10451. Lost allocations are not supported in buddy allocator at the moment.
  10452. Support might be added in the future.
  10453. */
  10454. return 0;
  10455. }
  10456. void VmaBlockMetadata_Buddy::Alloc(
  10457. const VmaAllocationRequest& request,
  10458. VmaSuballocationType type,
  10459. VkDeviceSize allocSize,
  10460. VmaAllocation hAllocation)
  10461. {
  10462. VMA_ASSERT(request.type == VmaAllocationRequestType::Normal);
  10463. const uint32_t targetLevel = AllocSizeToLevel(allocSize);
  10464. uint32_t currLevel = (uint32_t)(uintptr_t)request.customData;
  10465. Node* currNode = m_FreeList[currLevel].front;
  10466. VMA_ASSERT(currNode != VMA_NULL && currNode->type == Node::TYPE_FREE);
  10467. while(currNode->offset != request.offset)
  10468. {
  10469. currNode = currNode->free.next;
  10470. VMA_ASSERT(currNode != VMA_NULL && currNode->type == Node::TYPE_FREE);
  10471. }
  10472. // Go down, splitting free nodes.
  10473. while(currLevel < targetLevel)
  10474. {
  10475. // currNode is already first free node at currLevel.
  10476. // Remove it from list of free nodes at this currLevel.
  10477. RemoveFromFreeList(currLevel, currNode);
  10478. const uint32_t childrenLevel = currLevel + 1;
  10479. // Create two free sub-nodes.
  10480. Node* leftChild = vma_new(GetAllocationCallbacks(), Node)();
  10481. Node* rightChild = vma_new(GetAllocationCallbacks(), Node)();
  10482. leftChild->offset = currNode->offset;
  10483. leftChild->type = Node::TYPE_FREE;
  10484. leftChild->parent = currNode;
  10485. leftChild->buddy = rightChild;
  10486. rightChild->offset = currNode->offset + LevelToNodeSize(childrenLevel);
  10487. rightChild->type = Node::TYPE_FREE;
  10488. rightChild->parent = currNode;
  10489. rightChild->buddy = leftChild;
  10490. // Convert current currNode to split type.
  10491. currNode->type = Node::TYPE_SPLIT;
  10492. currNode->split.leftChild = leftChild;
  10493. // Add child nodes to free list. Order is important!
  10494. AddToFreeListFront(childrenLevel, rightChild);
  10495. AddToFreeListFront(childrenLevel, leftChild);
  10496. ++m_FreeCount;
  10497. //m_SumFreeSize -= LevelToNodeSize(currLevel) % 2; // Useful only when level node sizes can be non power of 2.
  10498. ++currLevel;
  10499. currNode = m_FreeList[currLevel].front;
  10500. /*
  10501. We can be sure that currNode, as left child of node previously split,
  10502. also fullfills the alignment requirement.
  10503. */
  10504. }
  10505. // Remove from free list.
  10506. VMA_ASSERT(currLevel == targetLevel &&
  10507. currNode != VMA_NULL &&
  10508. currNode->type == Node::TYPE_FREE);
  10509. RemoveFromFreeList(currLevel, currNode);
  10510. // Convert to allocation node.
  10511. currNode->type = Node::TYPE_ALLOCATION;
  10512. currNode->allocation.alloc = hAllocation;
  10513. ++m_AllocationCount;
  10514. --m_FreeCount;
  10515. m_SumFreeSize -= allocSize;
  10516. }
  10517. void VmaBlockMetadata_Buddy::DeleteNode(Node* node)
  10518. {
  10519. if(node->type == Node::TYPE_SPLIT)
  10520. {
  10521. DeleteNode(node->split.leftChild->buddy);
  10522. DeleteNode(node->split.leftChild);
  10523. }
  10524. vma_delete(GetAllocationCallbacks(), node);
  10525. }
  10526. bool VmaBlockMetadata_Buddy::ValidateNode(ValidationContext& ctx, const Node* parent, const Node* curr, uint32_t level, VkDeviceSize levelNodeSize) const
  10527. {
  10528. VMA_VALIDATE(level < m_LevelCount);
  10529. VMA_VALIDATE(curr->parent == parent);
  10530. VMA_VALIDATE((curr->buddy == VMA_NULL) == (parent == VMA_NULL));
  10531. VMA_VALIDATE(curr->buddy == VMA_NULL || curr->buddy->buddy == curr);
  10532. switch(curr->type)
  10533. {
  10534. case Node::TYPE_FREE:
  10535. // curr->free.prev, next are validated separately.
  10536. ctx.calculatedSumFreeSize += levelNodeSize;
  10537. ++ctx.calculatedFreeCount;
  10538. break;
  10539. case Node::TYPE_ALLOCATION:
  10540. ++ctx.calculatedAllocationCount;
  10541. ctx.calculatedSumFreeSize += levelNodeSize - curr->allocation.alloc->GetSize();
  10542. VMA_VALIDATE(curr->allocation.alloc != VK_NULL_HANDLE);
  10543. break;
  10544. case Node::TYPE_SPLIT:
  10545. {
  10546. const uint32_t childrenLevel = level + 1;
  10547. const VkDeviceSize childrenLevelNodeSize = levelNodeSize / 2;
  10548. const Node* const leftChild = curr->split.leftChild;
  10549. VMA_VALIDATE(leftChild != VMA_NULL);
  10550. VMA_VALIDATE(leftChild->offset == curr->offset);
  10551. if(!ValidateNode(ctx, curr, leftChild, childrenLevel, childrenLevelNodeSize))
  10552. {
  10553. VMA_VALIDATE(false && "ValidateNode for left child failed.");
  10554. }
  10555. const Node* const rightChild = leftChild->buddy;
  10556. VMA_VALIDATE(rightChild->offset == curr->offset + childrenLevelNodeSize);
  10557. if(!ValidateNode(ctx, curr, rightChild, childrenLevel, childrenLevelNodeSize))
  10558. {
  10559. VMA_VALIDATE(false && "ValidateNode for right child failed.");
  10560. }
  10561. }
  10562. break;
  10563. default:
  10564. return false;
  10565. }
  10566. return true;
  10567. }
  10568. uint32_t VmaBlockMetadata_Buddy::AllocSizeToLevel(VkDeviceSize allocSize) const
  10569. {
  10570. // I know this could be optimized somehow e.g. by using std::log2p1 from C++20.
  10571. uint32_t level = 0;
  10572. VkDeviceSize currLevelNodeSize = m_UsableSize;
  10573. VkDeviceSize nextLevelNodeSize = currLevelNodeSize >> 1;
  10574. while(allocSize <= nextLevelNodeSize && level + 1 < m_LevelCount)
  10575. {
  10576. ++level;
  10577. currLevelNodeSize = nextLevelNodeSize;
  10578. nextLevelNodeSize = currLevelNodeSize >> 1;
  10579. }
  10580. return level;
  10581. }
  10582. void VmaBlockMetadata_Buddy::FreeAtOffset(VmaAllocation alloc, VkDeviceSize offset)
  10583. {
  10584. // Find node and level.
  10585. Node* node = m_Root;
  10586. VkDeviceSize nodeOffset = 0;
  10587. uint32_t level = 0;
  10588. VkDeviceSize levelNodeSize = LevelToNodeSize(0);
  10589. while(node->type == Node::TYPE_SPLIT)
  10590. {
  10591. const VkDeviceSize nextLevelSize = levelNodeSize >> 1;
  10592. if(offset < nodeOffset + nextLevelSize)
  10593. {
  10594. node = node->split.leftChild;
  10595. }
  10596. else
  10597. {
  10598. node = node->split.leftChild->buddy;
  10599. nodeOffset += nextLevelSize;
  10600. }
  10601. ++level;
  10602. levelNodeSize = nextLevelSize;
  10603. }
  10604. VMA_ASSERT(node != VMA_NULL && node->type == Node::TYPE_ALLOCATION);
  10605. VMA_ASSERT(alloc == VK_NULL_HANDLE || node->allocation.alloc == alloc);
  10606. ++m_FreeCount;
  10607. --m_AllocationCount;
  10608. m_SumFreeSize += alloc->GetSize();
  10609. node->type = Node::TYPE_FREE;
  10610. // Join free nodes if possible.
  10611. while(level > 0 && node->buddy->type == Node::TYPE_FREE)
  10612. {
  10613. RemoveFromFreeList(level, node->buddy);
  10614. Node* const parent = node->parent;
  10615. vma_delete(GetAllocationCallbacks(), node->buddy);
  10616. vma_delete(GetAllocationCallbacks(), node);
  10617. parent->type = Node::TYPE_FREE;
  10618. node = parent;
  10619. --level;
  10620. //m_SumFreeSize += LevelToNodeSize(level) % 2; // Useful only when level node sizes can be non power of 2.
  10621. --m_FreeCount;
  10622. }
  10623. AddToFreeListFront(level, node);
  10624. }
  10625. void VmaBlockMetadata_Buddy::CalcAllocationStatInfoNode(VmaStatInfo& outInfo, const Node* node, VkDeviceSize levelNodeSize) const
  10626. {
  10627. switch(node->type)
  10628. {
  10629. case Node::TYPE_FREE:
  10630. ++outInfo.unusedRangeCount;
  10631. outInfo.unusedBytes += levelNodeSize;
  10632. outInfo.unusedRangeSizeMax = VMA_MAX(outInfo.unusedRangeSizeMax, levelNodeSize);
  10633. outInfo.unusedRangeSizeMin = VMA_MAX(outInfo.unusedRangeSizeMin, levelNodeSize);
  10634. break;
  10635. case Node::TYPE_ALLOCATION:
  10636. {
  10637. const VkDeviceSize allocSize = node->allocation.alloc->GetSize();
  10638. ++outInfo.allocationCount;
  10639. outInfo.usedBytes += allocSize;
  10640. outInfo.allocationSizeMax = VMA_MAX(outInfo.allocationSizeMax, allocSize);
  10641. outInfo.allocationSizeMin = VMA_MAX(outInfo.allocationSizeMin, allocSize);
  10642. const VkDeviceSize unusedRangeSize = levelNodeSize - allocSize;
  10643. if(unusedRangeSize > 0)
  10644. {
  10645. ++outInfo.unusedRangeCount;
  10646. outInfo.unusedBytes += unusedRangeSize;
  10647. outInfo.unusedRangeSizeMax = VMA_MAX(outInfo.unusedRangeSizeMax, unusedRangeSize);
  10648. outInfo.unusedRangeSizeMin = VMA_MAX(outInfo.unusedRangeSizeMin, unusedRangeSize);
  10649. }
  10650. }
  10651. break;
  10652. case Node::TYPE_SPLIT:
  10653. {
  10654. const VkDeviceSize childrenNodeSize = levelNodeSize / 2;
  10655. const Node* const leftChild = node->split.leftChild;
  10656. CalcAllocationStatInfoNode(outInfo, leftChild, childrenNodeSize);
  10657. const Node* const rightChild = leftChild->buddy;
  10658. CalcAllocationStatInfoNode(outInfo, rightChild, childrenNodeSize);
  10659. }
  10660. break;
  10661. default:
  10662. VMA_ASSERT(0);
  10663. }
  10664. }
  10665. void VmaBlockMetadata_Buddy::AddToFreeListFront(uint32_t level, Node* node)
  10666. {
  10667. VMA_ASSERT(node->type == Node::TYPE_FREE);
  10668. // List is empty.
  10669. Node* const frontNode = m_FreeList[level].front;
  10670. if(frontNode == VMA_NULL)
  10671. {
  10672. VMA_ASSERT(m_FreeList[level].back == VMA_NULL);
  10673. node->free.prev = node->free.next = VMA_NULL;
  10674. m_FreeList[level].front = m_FreeList[level].back = node;
  10675. }
  10676. else
  10677. {
  10678. VMA_ASSERT(frontNode->free.prev == VMA_NULL);
  10679. node->free.prev = VMA_NULL;
  10680. node->free.next = frontNode;
  10681. frontNode->free.prev = node;
  10682. m_FreeList[level].front = node;
  10683. }
  10684. }
  10685. void VmaBlockMetadata_Buddy::RemoveFromFreeList(uint32_t level, Node* node)
  10686. {
  10687. VMA_ASSERT(m_FreeList[level].front != VMA_NULL);
  10688. // It is at the front.
  10689. if(node->free.prev == VMA_NULL)
  10690. {
  10691. VMA_ASSERT(m_FreeList[level].front == node);
  10692. m_FreeList[level].front = node->free.next;
  10693. }
  10694. else
  10695. {
  10696. Node* const prevFreeNode = node->free.prev;
  10697. VMA_ASSERT(prevFreeNode->free.next == node);
  10698. prevFreeNode->free.next = node->free.next;
  10699. }
  10700. // It is at the back.
  10701. if(node->free.next == VMA_NULL)
  10702. {
  10703. VMA_ASSERT(m_FreeList[level].back == node);
  10704. m_FreeList[level].back = node->free.prev;
  10705. }
  10706. else
  10707. {
  10708. Node* const nextFreeNode = node->free.next;
  10709. VMA_ASSERT(nextFreeNode->free.prev == node);
  10710. nextFreeNode->free.prev = node->free.prev;
  10711. }
  10712. }
  10713. #if VMA_STATS_STRING_ENABLED
  10714. void VmaBlockMetadata_Buddy::PrintDetailedMapNode(class VmaJsonWriter& json, const Node* node, VkDeviceSize levelNodeSize) const
  10715. {
  10716. switch(node->type)
  10717. {
  10718. case Node::TYPE_FREE:
  10719. PrintDetailedMap_UnusedRange(json, node->offset, levelNodeSize);
  10720. break;
  10721. case Node::TYPE_ALLOCATION:
  10722. {
  10723. PrintDetailedMap_Allocation(json, node->offset, node->allocation.alloc);
  10724. const VkDeviceSize allocSize = node->allocation.alloc->GetSize();
  10725. if(allocSize < levelNodeSize)
  10726. {
  10727. PrintDetailedMap_UnusedRange(json, node->offset + allocSize, levelNodeSize - allocSize);
  10728. }
  10729. }
  10730. break;
  10731. case Node::TYPE_SPLIT:
  10732. {
  10733. const VkDeviceSize childrenNodeSize = levelNodeSize / 2;
  10734. const Node* const leftChild = node->split.leftChild;
  10735. PrintDetailedMapNode(json, leftChild, childrenNodeSize);
  10736. const Node* const rightChild = leftChild->buddy;
  10737. PrintDetailedMapNode(json, rightChild, childrenNodeSize);
  10738. }
  10739. break;
  10740. default:
  10741. VMA_ASSERT(0);
  10742. }
  10743. }
  10744. #endif // #if VMA_STATS_STRING_ENABLED
  10745. ////////////////////////////////////////////////////////////////////////////////
  10746. // class VmaDeviceMemoryBlock
  10747. VmaDeviceMemoryBlock::VmaDeviceMemoryBlock(VmaAllocator hAllocator)
  10748. {
  10749. }
  10750. void VmaDeviceMemoryBlock::Init(
  10751. VmaAllocator hAllocator,
  10752. VmaBlockVector* parentBlockVector,
  10753. VmaPool hParentPool,
  10754. uint32_t newMemoryTypeIndex,
  10755. VkDeviceMemory newMemory,
  10756. VkDeviceSize newSize,
  10757. uint32_t id,
  10758. uint32_t algorithm)
  10759. {
  10760. VMA_ASSERT(parentBlockVector != VMA_NULL);
  10761. VMA_ASSERT(m_hMemory == VK_NULL_HANDLE);
  10762. m_ParentBlockVector = parentBlockVector;
  10763. m_hParentPool = hParentPool;
  10764. m_MemoryTypeIndex = newMemoryTypeIndex;
  10765. m_Id = id;
  10766. m_hMemory = newMemory;
  10767. switch(algorithm)
  10768. {
  10769. case VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT:
  10770. m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_Linear)(hAllocator);
  10771. break;
  10772. case VMA_POOL_CREATE_BUDDY_ALGORITHM_BIT:
  10773. m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_Buddy)(hAllocator);
  10774. break;
  10775. default:
  10776. VMA_ASSERT(0);
  10777. // Fall-through.
  10778. case 0:
  10779. m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_Generic)(hAllocator);
  10780. }
  10781. m_pMetadata->Init(newSize);
  10782. }
  10783. void VmaDeviceMemoryBlock::Destroy(VmaAllocator allocator)
  10784. {
  10785. // This is the most important assert in the entire library.
  10786. // Hitting it means you have some memory leak - unreleased VmaAllocation objects.
  10787. VMA_ASSERT(m_pMetadata->IsEmpty() && "Some allocations were not freed before destruction of this memory block!");
  10788. VMA_ASSERT(m_hMemory != VK_NULL_HANDLE);
  10789. allocator->FreeVulkanMemory(m_MemoryTypeIndex, m_pMetadata->GetSize(), m_hMemory);
  10790. m_hMemory = VK_NULL_HANDLE;
  10791. vma_delete(allocator, m_pMetadata);
  10792. m_pMetadata = VMA_NULL;
  10793. }
  10794. bool VmaDeviceMemoryBlock::Validate() const
  10795. {
  10796. VMA_VALIDATE((m_hMemory != VK_NULL_HANDLE) &&
  10797. (m_pMetadata->GetSize() != 0));
  10798. return m_pMetadata->Validate();
  10799. }
  10800. VkResult VmaDeviceMemoryBlock::CheckCorruption(VmaAllocator hAllocator)
  10801. {
  10802. void* pData = nullptr;
  10803. VkResult res = Map(hAllocator, 1, &pData);
  10804. if(res != VK_SUCCESS)
  10805. {
  10806. return res;
  10807. }
  10808. res = m_pMetadata->CheckCorruption(pData);
  10809. Unmap(hAllocator, 1);
  10810. return res;
  10811. }
  10812. VkResult VmaDeviceMemoryBlock::Map(VmaAllocator hAllocator, uint32_t count, void** ppData)
  10813. {
  10814. if(count == 0)
  10815. {
  10816. return VK_SUCCESS;
  10817. }
  10818. VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
  10819. if(m_MapCount != 0)
  10820. {
  10821. m_MapCount += count;
  10822. VMA_ASSERT(m_pMappedData != VMA_NULL);
  10823. if(ppData != VMA_NULL)
  10824. {
  10825. *ppData = m_pMappedData;
  10826. }
  10827. return VK_SUCCESS;
  10828. }
  10829. else
  10830. {
  10831. VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)(
  10832. hAllocator->m_hDevice,
  10833. m_hMemory,
  10834. 0, // offset
  10835. VK_WHOLE_SIZE,
  10836. 0, // flags
  10837. &m_pMappedData);
  10838. if(result == VK_SUCCESS)
  10839. {
  10840. if(ppData != VMA_NULL)
  10841. {
  10842. *ppData = m_pMappedData;
  10843. }
  10844. m_MapCount = count;
  10845. }
  10846. return result;
  10847. }
  10848. }
  10849. void VmaDeviceMemoryBlock::Unmap(VmaAllocator hAllocator, uint32_t count)
  10850. {
  10851. if(count == 0)
  10852. {
  10853. return;
  10854. }
  10855. VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
  10856. if(m_MapCount >= count)
  10857. {
  10858. m_MapCount -= count;
  10859. if(m_MapCount == 0)
  10860. {
  10861. m_pMappedData = VMA_NULL;
  10862. (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(hAllocator->m_hDevice, m_hMemory);
  10863. }
  10864. }
  10865. else
  10866. {
  10867. VMA_ASSERT(0 && "VkDeviceMemory block is being unmapped while it was not previously mapped.");
  10868. }
  10869. }
  10870. VkResult VmaDeviceMemoryBlock::WriteMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize)
  10871. {
  10872. VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION);
  10873. VMA_ASSERT(allocOffset >= VMA_DEBUG_MARGIN);
  10874. void* pData;
  10875. VkResult res = Map(hAllocator, 1, &pData);
  10876. if(res != VK_SUCCESS)
  10877. {
  10878. return res;
  10879. }
  10880. VmaWriteMagicValue(pData, allocOffset - VMA_DEBUG_MARGIN);
  10881. VmaWriteMagicValue(pData, allocOffset + allocSize);
  10882. Unmap(hAllocator, 1);
  10883. return VK_SUCCESS;
  10884. }
  10885. VkResult VmaDeviceMemoryBlock::ValidateMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize)
  10886. {
  10887. VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION);
  10888. VMA_ASSERT(allocOffset >= VMA_DEBUG_MARGIN);
  10889. void* pData;
  10890. VkResult res = Map(hAllocator, 1, &pData);
  10891. if(res != VK_SUCCESS)
  10892. {
  10893. return res;
  10894. }
  10895. if(!VmaValidateMagicValue(pData, allocOffset - VMA_DEBUG_MARGIN))
  10896. {
  10897. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE FREED ALLOCATION!");
  10898. }
  10899. else if(!VmaValidateMagicValue(pData, allocOffset + allocSize))
  10900. {
  10901. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER FREED ALLOCATION!");
  10902. }
  10903. Unmap(hAllocator, 1);
  10904. return VK_SUCCESS;
  10905. }
  10906. VkResult VmaDeviceMemoryBlock::BindBufferMemory(
  10907. const VmaAllocator hAllocator,
  10908. const VmaAllocation hAllocation,
  10909. VkDeviceSize allocationLocalOffset,
  10910. VkBuffer hBuffer,
  10911. const void* pNext)
  10912. {
  10913. VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK &&
  10914. hAllocation->GetBlock() == this);
  10915. VMA_ASSERT(allocationLocalOffset < hAllocation->GetSize() &&
  10916. "Invalid allocationLocalOffset. Did you forget that this offset is relative to the beginning of the allocation, not the whole memory block?");
  10917. const VkDeviceSize memoryOffset = hAllocation->GetOffset() + allocationLocalOffset;
  10918. // This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads.
  10919. VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
  10920. return hAllocator->BindVulkanBuffer(m_hMemory, memoryOffset, hBuffer, pNext);
  10921. }
  10922. VkResult VmaDeviceMemoryBlock::BindImageMemory(
  10923. const VmaAllocator hAllocator,
  10924. const VmaAllocation hAllocation,
  10925. VkDeviceSize allocationLocalOffset,
  10926. VkImage hImage,
  10927. const void* pNext)
  10928. {
  10929. VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK &&
  10930. hAllocation->GetBlock() == this);
  10931. VMA_ASSERT(allocationLocalOffset < hAllocation->GetSize() &&
  10932. "Invalid allocationLocalOffset. Did you forget that this offset is relative to the beginning of the allocation, not the whole memory block?");
  10933. const VkDeviceSize memoryOffset = hAllocation->GetOffset() + allocationLocalOffset;
  10934. // This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads.
  10935. VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
  10936. return hAllocator->BindVulkanImage(m_hMemory, memoryOffset, hImage, pNext);
  10937. }
  10938. static void InitStatInfo(VmaStatInfo& outInfo)
  10939. {
  10940. memset(&outInfo, 0, sizeof(outInfo));
  10941. outInfo.allocationSizeMin = UINT64_MAX;
  10942. outInfo.unusedRangeSizeMin = UINT64_MAX;
  10943. }
  10944. // Adds statistics srcInfo into inoutInfo, like: inoutInfo += srcInfo.
  10945. static void VmaAddStatInfo(VmaStatInfo& inoutInfo, const VmaStatInfo& srcInfo)
  10946. {
  10947. inoutInfo.blockCount += srcInfo.blockCount;
  10948. inoutInfo.allocationCount += srcInfo.allocationCount;
  10949. inoutInfo.unusedRangeCount += srcInfo.unusedRangeCount;
  10950. inoutInfo.usedBytes += srcInfo.usedBytes;
  10951. inoutInfo.unusedBytes += srcInfo.unusedBytes;
  10952. inoutInfo.allocationSizeMin = VMA_MIN(inoutInfo.allocationSizeMin, srcInfo.allocationSizeMin);
  10953. inoutInfo.allocationSizeMax = VMA_MAX(inoutInfo.allocationSizeMax, srcInfo.allocationSizeMax);
  10954. inoutInfo.unusedRangeSizeMin = VMA_MIN(inoutInfo.unusedRangeSizeMin, srcInfo.unusedRangeSizeMin);
  10955. inoutInfo.unusedRangeSizeMax = VMA_MAX(inoutInfo.unusedRangeSizeMax, srcInfo.unusedRangeSizeMax);
  10956. }
  10957. static void VmaPostprocessCalcStatInfo(VmaStatInfo& inoutInfo)
  10958. {
  10959. inoutInfo.allocationSizeAvg = (inoutInfo.allocationCount > 0) ?
  10960. VmaRoundDiv<VkDeviceSize>(inoutInfo.usedBytes, inoutInfo.allocationCount) : 0;
  10961. inoutInfo.unusedRangeSizeAvg = (inoutInfo.unusedRangeCount > 0) ?
  10962. VmaRoundDiv<VkDeviceSize>(inoutInfo.unusedBytes, inoutInfo.unusedRangeCount) : 0;
  10963. }
  10964. VmaPool_T::VmaPool_T(
  10965. VmaAllocator hAllocator,
  10966. const VmaPoolCreateInfo& createInfo,
  10967. VkDeviceSize preferredBlockSize) :
  10968. m_BlockVector(
  10969. hAllocator,
  10970. this, // hParentPool
  10971. createInfo.memoryTypeIndex,
  10972. createInfo.blockSize != 0 ? createInfo.blockSize : preferredBlockSize,
  10973. createInfo.minBlockCount,
  10974. createInfo.maxBlockCount,
  10975. (createInfo.flags & VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT) != 0 ? 1 : hAllocator->GetBufferImageGranularity(),
  10976. createInfo.frameInUseCount,
  10977. createInfo.blockSize != 0, // explicitBlockSize
  10978. createInfo.flags & VMA_POOL_CREATE_ALGORITHM_MASK, // algorithm
  10979. createInfo.priority,
  10980. VMA_MAX(hAllocator->GetMemoryTypeMinAlignment(createInfo.memoryTypeIndex), createInfo.minAllocationAlignment),
  10981. createInfo.pMemoryAllocateNext),
  10982. m_Id(0),
  10983. m_Name(VMA_NULL)
  10984. {
  10985. }
  10986. VmaPool_T::~VmaPool_T()
  10987. {
  10988. VMA_ASSERT(m_PrevPool == VMA_NULL && m_NextPool == VMA_NULL);
  10989. }
  10990. void VmaPool_T::SetName(const char* pName)
  10991. {
  10992. const VkAllocationCallbacks* allocs = m_BlockVector.GetAllocator()->GetAllocationCallbacks();
  10993. VmaFreeString(allocs, m_Name);
  10994. if(pName != VMA_NULL)
  10995. {
  10996. m_Name = VmaCreateStringCopy(allocs, pName);
  10997. }
  10998. else
  10999. {
  11000. m_Name = VMA_NULL;
  11001. }
  11002. }
  11003. #if VMA_STATS_STRING_ENABLED
  11004. #endif // #if VMA_STATS_STRING_ENABLED
  11005. VmaBlockVector::VmaBlockVector(
  11006. VmaAllocator hAllocator,
  11007. VmaPool hParentPool,
  11008. uint32_t memoryTypeIndex,
  11009. VkDeviceSize preferredBlockSize,
  11010. size_t minBlockCount,
  11011. size_t maxBlockCount,
  11012. VkDeviceSize bufferImageGranularity,
  11013. uint32_t frameInUseCount,
  11014. bool explicitBlockSize,
  11015. uint32_t algorithm,
  11016. float priority,
  11017. VkDeviceSize minAllocationAlignment,
  11018. void* pMemoryAllocateNext) :
  11019. m_hAllocator(hAllocator),
  11020. m_hParentPool(hParentPool),
  11021. m_MemoryTypeIndex(memoryTypeIndex),
  11022. m_PreferredBlockSize(preferredBlockSize),
  11023. m_MinBlockCount(minBlockCount),
  11024. m_MaxBlockCount(maxBlockCount),
  11025. m_BufferImageGranularity(bufferImageGranularity),
  11026. m_FrameInUseCount(frameInUseCount),
  11027. m_ExplicitBlockSize(explicitBlockSize),
  11028. m_Algorithm(algorithm),
  11029. m_Priority(priority),
  11030. m_MinAllocationAlignment(minAllocationAlignment),
  11031. m_pMemoryAllocateNext(pMemoryAllocateNext),
  11032. m_HasEmptyBlock(false),
  11033. m_Blocks(VmaStlAllocator<VmaDeviceMemoryBlock*>(hAllocator->GetAllocationCallbacks())),
  11034. m_NextBlockId(0)
  11035. {
  11036. }
  11037. VmaBlockVector::~VmaBlockVector()
  11038. {
  11039. for(size_t i = m_Blocks.size(); i--; )
  11040. {
  11041. m_Blocks[i]->Destroy(m_hAllocator);
  11042. vma_delete(m_hAllocator, m_Blocks[i]);
  11043. }
  11044. }
  11045. VkResult VmaBlockVector::CreateMinBlocks()
  11046. {
  11047. for(size_t i = 0; i < m_MinBlockCount; ++i)
  11048. {
  11049. VkResult res = CreateBlock(m_PreferredBlockSize, VMA_NULL);
  11050. if(res != VK_SUCCESS)
  11051. {
  11052. return res;
  11053. }
  11054. }
  11055. return VK_SUCCESS;
  11056. }
  11057. void VmaBlockVector::GetPoolStats(VmaPoolStats* pStats)
  11058. {
  11059. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  11060. const size_t blockCount = m_Blocks.size();
  11061. pStats->size = 0;
  11062. pStats->unusedSize = 0;
  11063. pStats->allocationCount = 0;
  11064. pStats->unusedRangeCount = 0;
  11065. pStats->unusedRangeSizeMax = 0;
  11066. pStats->blockCount = blockCount;
  11067. for(uint32_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
  11068. {
  11069. const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
  11070. VMA_ASSERT(pBlock);
  11071. VMA_HEAVY_ASSERT(pBlock->Validate());
  11072. pBlock->m_pMetadata->AddPoolStats(*pStats);
  11073. }
  11074. }
  11075. bool VmaBlockVector::IsEmpty()
  11076. {
  11077. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  11078. return m_Blocks.empty();
  11079. }
  11080. bool VmaBlockVector::IsCorruptionDetectionEnabled() const
  11081. {
  11082. const uint32_t requiredMemFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
  11083. return (VMA_DEBUG_DETECT_CORRUPTION != 0) &&
  11084. (VMA_DEBUG_MARGIN > 0) &&
  11085. (m_Algorithm == 0 || m_Algorithm == VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) &&
  11086. (m_hAllocator->m_MemProps.memoryTypes[m_MemoryTypeIndex].propertyFlags & requiredMemFlags) == requiredMemFlags;
  11087. }
  11088. static const uint32_t VMA_ALLOCATION_TRY_COUNT = 32;
  11089. VkResult VmaBlockVector::Allocate(
  11090. uint32_t currentFrameIndex,
  11091. VkDeviceSize size,
  11092. VkDeviceSize alignment,
  11093. const VmaAllocationCreateInfo& createInfo,
  11094. VmaSuballocationType suballocType,
  11095. size_t allocationCount,
  11096. VmaAllocation* pAllocations)
  11097. {
  11098. size_t allocIndex;
  11099. VkResult res = VK_SUCCESS;
  11100. alignment = VMA_MAX(alignment, m_MinAllocationAlignment);
  11101. if(IsCorruptionDetectionEnabled())
  11102. {
  11103. size = VmaAlignUp<VkDeviceSize>(size, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE));
  11104. alignment = VmaAlignUp<VkDeviceSize>(alignment, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE));
  11105. }
  11106. {
  11107. VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex);
  11108. for(allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  11109. {
  11110. res = AllocatePage(
  11111. currentFrameIndex,
  11112. size,
  11113. alignment,
  11114. createInfo,
  11115. suballocType,
  11116. pAllocations + allocIndex);
  11117. if(res != VK_SUCCESS)
  11118. {
  11119. break;
  11120. }
  11121. }
  11122. }
  11123. if(res != VK_SUCCESS)
  11124. {
  11125. // Free all already created allocations.
  11126. const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex);
  11127. while(allocIndex--)
  11128. {
  11129. VmaAllocation_T* const alloc = pAllocations[allocIndex];
  11130. const VkDeviceSize allocSize = alloc->GetSize();
  11131. Free(alloc);
  11132. m_hAllocator->m_Budget.RemoveAllocation(heapIndex, allocSize);
  11133. }
  11134. memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount);
  11135. }
  11136. return res;
  11137. }
  11138. VkResult VmaBlockVector::AllocatePage(
  11139. uint32_t currentFrameIndex,
  11140. VkDeviceSize size,
  11141. VkDeviceSize alignment,
  11142. const VmaAllocationCreateInfo& createInfo,
  11143. VmaSuballocationType suballocType,
  11144. VmaAllocation* pAllocation)
  11145. {
  11146. const bool isUpperAddress = (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0;
  11147. bool canMakeOtherLost = (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT) != 0;
  11148. const bool mapped = (createInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0;
  11149. const bool isUserDataString = (createInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0;
  11150. VkDeviceSize freeMemory;
  11151. {
  11152. const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex);
  11153. VmaBudget heapBudget = {};
  11154. m_hAllocator->GetBudget(&heapBudget, heapIndex, 1);
  11155. freeMemory = (heapBudget.usage < heapBudget.budget) ? (heapBudget.budget - heapBudget.usage) : 0;
  11156. }
  11157. const bool canFallbackToDedicated = !IsCustomPool();
  11158. const bool canCreateNewBlock =
  11159. ((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0) &&
  11160. (m_Blocks.size() < m_MaxBlockCount) &&
  11161. (freeMemory >= size || !canFallbackToDedicated);
  11162. uint32_t strategy = createInfo.flags & VMA_ALLOCATION_CREATE_STRATEGY_MASK;
  11163. // If linearAlgorithm is used, canMakeOtherLost is available only when used as ring buffer.
  11164. // Which in turn is available only when maxBlockCount = 1.
  11165. if(m_Algorithm == VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT && m_MaxBlockCount > 1)
  11166. {
  11167. canMakeOtherLost = false;
  11168. }
  11169. // Upper address can only be used with linear allocator and within single memory block.
  11170. if(isUpperAddress &&
  11171. (m_Algorithm != VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT || m_MaxBlockCount > 1))
  11172. {
  11173. return VK_ERROR_FEATURE_NOT_PRESENT;
  11174. }
  11175. // Validate strategy.
  11176. switch(strategy)
  11177. {
  11178. case 0:
  11179. strategy = VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT;
  11180. break;
  11181. case VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT:
  11182. case VMA_ALLOCATION_CREATE_STRATEGY_WORST_FIT_BIT:
  11183. case VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT:
  11184. break;
  11185. default:
  11186. return VK_ERROR_FEATURE_NOT_PRESENT;
  11187. }
  11188. // Early reject: requested allocation size is larger that maximum block size for this block vector.
  11189. if(size + 2 * VMA_DEBUG_MARGIN > m_PreferredBlockSize)
  11190. {
  11191. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  11192. }
  11193. /*
  11194. Under certain condition, this whole section can be skipped for optimization, so
  11195. we move on directly to trying to allocate with canMakeOtherLost. That's the case
  11196. e.g. for custom pools with linear algorithm.
  11197. */
  11198. if(!canMakeOtherLost || canCreateNewBlock)
  11199. {
  11200. // 1. Search existing allocations. Try to allocate without making other allocations lost.
  11201. VmaAllocationCreateFlags allocFlagsCopy = createInfo.flags;
  11202. allocFlagsCopy &= ~VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT;
  11203. if(m_Algorithm == VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT)
  11204. {
  11205. // Use only last block.
  11206. if(!m_Blocks.empty())
  11207. {
  11208. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks.back();
  11209. VMA_ASSERT(pCurrBlock);
  11210. VkResult res = AllocateFromBlock(
  11211. pCurrBlock,
  11212. currentFrameIndex,
  11213. size,
  11214. alignment,
  11215. allocFlagsCopy,
  11216. createInfo.pUserData,
  11217. suballocType,
  11218. strategy,
  11219. pAllocation);
  11220. if(res == VK_SUCCESS)
  11221. {
  11222. VMA_DEBUG_LOG(" Returned from last block #%u", pCurrBlock->GetId());
  11223. return VK_SUCCESS;
  11224. }
  11225. }
  11226. }
  11227. else
  11228. {
  11229. if(strategy == VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT)
  11230. {
  11231. // Forward order in m_Blocks - prefer blocks with smallest amount of free space.
  11232. for(size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex )
  11233. {
  11234. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
  11235. VMA_ASSERT(pCurrBlock);
  11236. VkResult res = AllocateFromBlock(
  11237. pCurrBlock,
  11238. currentFrameIndex,
  11239. size,
  11240. alignment,
  11241. allocFlagsCopy,
  11242. createInfo.pUserData,
  11243. suballocType,
  11244. strategy,
  11245. pAllocation);
  11246. if(res == VK_SUCCESS)
  11247. {
  11248. VMA_DEBUG_LOG(" Returned from existing block #%u", pCurrBlock->GetId());
  11249. return VK_SUCCESS;
  11250. }
  11251. }
  11252. }
  11253. else // WORST_FIT, FIRST_FIT
  11254. {
  11255. // Backward order in m_Blocks - prefer blocks with largest amount of free space.
  11256. for(size_t blockIndex = m_Blocks.size(); blockIndex--; )
  11257. {
  11258. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
  11259. VMA_ASSERT(pCurrBlock);
  11260. VkResult res = AllocateFromBlock(
  11261. pCurrBlock,
  11262. currentFrameIndex,
  11263. size,
  11264. alignment,
  11265. allocFlagsCopy,
  11266. createInfo.pUserData,
  11267. suballocType,
  11268. strategy,
  11269. pAllocation);
  11270. if(res == VK_SUCCESS)
  11271. {
  11272. VMA_DEBUG_LOG(" Returned from existing block #%u", pCurrBlock->GetId());
  11273. return VK_SUCCESS;
  11274. }
  11275. }
  11276. }
  11277. }
  11278. // 2. Try to create new block.
  11279. if(canCreateNewBlock)
  11280. {
  11281. // Calculate optimal size for new block.
  11282. VkDeviceSize newBlockSize = m_PreferredBlockSize;
  11283. uint32_t newBlockSizeShift = 0;
  11284. const uint32_t NEW_BLOCK_SIZE_SHIFT_MAX = 3;
  11285. if(!m_ExplicitBlockSize)
  11286. {
  11287. // Allocate 1/8, 1/4, 1/2 as first blocks.
  11288. const VkDeviceSize maxExistingBlockSize = CalcMaxBlockSize();
  11289. for(uint32_t i = 0; i < NEW_BLOCK_SIZE_SHIFT_MAX; ++i)
  11290. {
  11291. const VkDeviceSize smallerNewBlockSize = newBlockSize / 2;
  11292. if(smallerNewBlockSize > maxExistingBlockSize && smallerNewBlockSize >= size * 2)
  11293. {
  11294. newBlockSize = smallerNewBlockSize;
  11295. ++newBlockSizeShift;
  11296. }
  11297. else
  11298. {
  11299. break;
  11300. }
  11301. }
  11302. }
  11303. size_t newBlockIndex = 0;
  11304. VkResult res = (newBlockSize <= freeMemory || !canFallbackToDedicated) ?
  11305. CreateBlock(newBlockSize, &newBlockIndex) : VK_ERROR_OUT_OF_DEVICE_MEMORY;
  11306. // Allocation of this size failed? Try 1/2, 1/4, 1/8 of m_PreferredBlockSize.
  11307. if(!m_ExplicitBlockSize)
  11308. {
  11309. while(res < 0 && newBlockSizeShift < NEW_BLOCK_SIZE_SHIFT_MAX)
  11310. {
  11311. const VkDeviceSize smallerNewBlockSize = newBlockSize / 2;
  11312. if(smallerNewBlockSize >= size)
  11313. {
  11314. newBlockSize = smallerNewBlockSize;
  11315. ++newBlockSizeShift;
  11316. res = (newBlockSize <= freeMemory || !canFallbackToDedicated) ?
  11317. CreateBlock(newBlockSize, &newBlockIndex) : VK_ERROR_OUT_OF_DEVICE_MEMORY;
  11318. }
  11319. else
  11320. {
  11321. break;
  11322. }
  11323. }
  11324. }
  11325. if(res == VK_SUCCESS)
  11326. {
  11327. VmaDeviceMemoryBlock* const pBlock = m_Blocks[newBlockIndex];
  11328. VMA_ASSERT(pBlock->m_pMetadata->GetSize() >= size);
  11329. res = AllocateFromBlock(
  11330. pBlock,
  11331. currentFrameIndex,
  11332. size,
  11333. alignment,
  11334. allocFlagsCopy,
  11335. createInfo.pUserData,
  11336. suballocType,
  11337. strategy,
  11338. pAllocation);
  11339. if(res == VK_SUCCESS)
  11340. {
  11341. VMA_DEBUG_LOG(" Created new block #%u Size=%llu", pBlock->GetId(), newBlockSize);
  11342. return VK_SUCCESS;
  11343. }
  11344. else
  11345. {
  11346. // Allocation from new block failed, possibly due to VMA_DEBUG_MARGIN or alignment.
  11347. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  11348. }
  11349. }
  11350. }
  11351. }
  11352. // 3. Try to allocate from existing blocks with making other allocations lost.
  11353. if(canMakeOtherLost)
  11354. {
  11355. uint32_t tryIndex = 0;
  11356. for(; tryIndex < VMA_ALLOCATION_TRY_COUNT; ++tryIndex)
  11357. {
  11358. VmaDeviceMemoryBlock* pBestRequestBlock = VMA_NULL;
  11359. VmaAllocationRequest bestRequest = {};
  11360. VkDeviceSize bestRequestCost = VK_WHOLE_SIZE;
  11361. // 1. Search existing allocations.
  11362. if(strategy == VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT)
  11363. {
  11364. // Forward order in m_Blocks - prefer blocks with smallest amount of free space.
  11365. for(size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex )
  11366. {
  11367. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
  11368. VMA_ASSERT(pCurrBlock);
  11369. VmaAllocationRequest currRequest = {};
  11370. if(pCurrBlock->m_pMetadata->CreateAllocationRequest(
  11371. currentFrameIndex,
  11372. m_FrameInUseCount,
  11373. m_BufferImageGranularity,
  11374. size,
  11375. alignment,
  11376. (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0,
  11377. suballocType,
  11378. canMakeOtherLost,
  11379. strategy,
  11380. &currRequest))
  11381. {
  11382. const VkDeviceSize currRequestCost = currRequest.CalcCost();
  11383. if(pBestRequestBlock == VMA_NULL ||
  11384. currRequestCost < bestRequestCost)
  11385. {
  11386. pBestRequestBlock = pCurrBlock;
  11387. bestRequest = currRequest;
  11388. bestRequestCost = currRequestCost;
  11389. if(bestRequestCost == 0)
  11390. {
  11391. break;
  11392. }
  11393. }
  11394. }
  11395. }
  11396. }
  11397. else // WORST_FIT, FIRST_FIT
  11398. {
  11399. // Backward order in m_Blocks - prefer blocks with largest amount of free space.
  11400. for(size_t blockIndex = m_Blocks.size(); blockIndex--; )
  11401. {
  11402. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
  11403. VMA_ASSERT(pCurrBlock);
  11404. VmaAllocationRequest currRequest = {};
  11405. if(pCurrBlock->m_pMetadata->CreateAllocationRequest(
  11406. currentFrameIndex,
  11407. m_FrameInUseCount,
  11408. m_BufferImageGranularity,
  11409. size,
  11410. alignment,
  11411. (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0,
  11412. suballocType,
  11413. canMakeOtherLost,
  11414. strategy,
  11415. &currRequest))
  11416. {
  11417. const VkDeviceSize currRequestCost = currRequest.CalcCost();
  11418. if(pBestRequestBlock == VMA_NULL ||
  11419. currRequestCost < bestRequestCost ||
  11420. strategy == VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT)
  11421. {
  11422. pBestRequestBlock = pCurrBlock;
  11423. bestRequest = currRequest;
  11424. bestRequestCost = currRequestCost;
  11425. if(bestRequestCost == 0 ||
  11426. strategy == VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT)
  11427. {
  11428. break;
  11429. }
  11430. }
  11431. }
  11432. }
  11433. }
  11434. if(pBestRequestBlock != VMA_NULL)
  11435. {
  11436. if(mapped)
  11437. {
  11438. VkResult res = pBestRequestBlock->Map(m_hAllocator, 1, VMA_NULL);
  11439. if(res != VK_SUCCESS)
  11440. {
  11441. return res;
  11442. }
  11443. }
  11444. if(pBestRequestBlock->m_pMetadata->MakeRequestedAllocationsLost(
  11445. currentFrameIndex,
  11446. m_FrameInUseCount,
  11447. &bestRequest))
  11448. {
  11449. // Allocate from this pBlock.
  11450. *pAllocation = m_hAllocator->m_AllocationObjectAllocator.Allocate(currentFrameIndex, isUserDataString);
  11451. pBestRequestBlock->m_pMetadata->Alloc(bestRequest, suballocType, size, *pAllocation);
  11452. UpdateHasEmptyBlock();
  11453. (*pAllocation)->InitBlockAllocation(
  11454. pBestRequestBlock,
  11455. bestRequest.offset,
  11456. alignment,
  11457. size,
  11458. m_MemoryTypeIndex,
  11459. suballocType,
  11460. mapped,
  11461. (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0);
  11462. VMA_HEAVY_ASSERT(pBestRequestBlock->Validate());
  11463. VMA_DEBUG_LOG(" Returned from existing block");
  11464. (*pAllocation)->SetUserData(m_hAllocator, createInfo.pUserData);
  11465. m_hAllocator->m_Budget.AddAllocation(m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex), size);
  11466. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
  11467. {
  11468. m_hAllocator->FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED);
  11469. }
  11470. if(IsCorruptionDetectionEnabled())
  11471. {
  11472. VkResult res = pBestRequestBlock->WriteMagicValueAroundAllocation(m_hAllocator, bestRequest.offset, size);
  11473. VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to write magic value.");
  11474. }
  11475. return VK_SUCCESS;
  11476. }
  11477. // else: Some allocations must have been touched while we are here. Next try.
  11478. }
  11479. else
  11480. {
  11481. // Could not find place in any of the blocks - break outer loop.
  11482. break;
  11483. }
  11484. }
  11485. /* Maximum number of tries exceeded - a very unlike event when many other
  11486. threads are simultaneously touching allocations making it impossible to make
  11487. lost at the same time as we try to allocate. */
  11488. if(tryIndex == VMA_ALLOCATION_TRY_COUNT)
  11489. {
  11490. return VK_ERROR_TOO_MANY_OBJECTS;
  11491. }
  11492. }
  11493. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  11494. }
  11495. void VmaBlockVector::Free(
  11496. const VmaAllocation hAllocation)
  11497. {
  11498. VMA_ASSERT(hAllocation->GetBlock()->GetParentBlockVector() == this);
  11499. VmaDeviceMemoryBlock* pBlockToDelete = VMA_NULL;
  11500. bool budgetExceeded = false;
  11501. {
  11502. const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex);
  11503. VmaBudget heapBudget = {};
  11504. m_hAllocator->GetBudget(&heapBudget, heapIndex, 1);
  11505. budgetExceeded = heapBudget.usage >= heapBudget.budget;
  11506. }
  11507. // Scope for lock.
  11508. {
  11509. VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex);
  11510. VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock();
  11511. if(IsCorruptionDetectionEnabled())
  11512. {
  11513. VkResult res = pBlock->ValidateMagicValueAroundAllocation(m_hAllocator, hAllocation->GetOffset(), hAllocation->GetSize());
  11514. VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to validate magic value.");
  11515. }
  11516. if(hAllocation->IsPersistentMap())
  11517. {
  11518. pBlock->Unmap(m_hAllocator, 1);
  11519. }
  11520. pBlock->m_pMetadata->Free(hAllocation);
  11521. VMA_HEAVY_ASSERT(pBlock->Validate());
  11522. VMA_DEBUG_LOG(" Freed from MemoryTypeIndex=%u", m_MemoryTypeIndex);
  11523. const bool canDeleteBlock = m_Blocks.size() > m_MinBlockCount;
  11524. // pBlock became empty after this deallocation.
  11525. if(pBlock->m_pMetadata->IsEmpty())
  11526. {
  11527. // Already has empty block. We don't want to have two, so delete this one.
  11528. if((m_HasEmptyBlock || budgetExceeded) && canDeleteBlock)
  11529. {
  11530. pBlockToDelete = pBlock;
  11531. Remove(pBlock);
  11532. }
  11533. // else: We now have an empty block - leave it.
  11534. }
  11535. // pBlock didn't become empty, but we have another empty block - find and free that one.
  11536. // (This is optional, heuristics.)
  11537. else if(m_HasEmptyBlock && canDeleteBlock)
  11538. {
  11539. VmaDeviceMemoryBlock* pLastBlock = m_Blocks.back();
  11540. if(pLastBlock->m_pMetadata->IsEmpty())
  11541. {
  11542. pBlockToDelete = pLastBlock;
  11543. m_Blocks.pop_back();
  11544. }
  11545. }
  11546. UpdateHasEmptyBlock();
  11547. IncrementallySortBlocks();
  11548. }
  11549. // Destruction of a free block. Deferred until this point, outside of mutex
  11550. // lock, for performance reason.
  11551. if(pBlockToDelete != VMA_NULL)
  11552. {
  11553. VMA_DEBUG_LOG(" Deleted empty block");
  11554. pBlockToDelete->Destroy(m_hAllocator);
  11555. vma_delete(m_hAllocator, pBlockToDelete);
  11556. }
  11557. }
  11558. VkDeviceSize VmaBlockVector::CalcMaxBlockSize() const
  11559. {
  11560. VkDeviceSize result = 0;
  11561. for(size_t i = m_Blocks.size(); i--; )
  11562. {
  11563. result = VMA_MAX(result, m_Blocks[i]->m_pMetadata->GetSize());
  11564. if(result >= m_PreferredBlockSize)
  11565. {
  11566. break;
  11567. }
  11568. }
  11569. return result;
  11570. }
  11571. void VmaBlockVector::Remove(VmaDeviceMemoryBlock* pBlock)
  11572. {
  11573. for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  11574. {
  11575. if(m_Blocks[blockIndex] == pBlock)
  11576. {
  11577. VmaVectorRemove(m_Blocks, blockIndex);
  11578. return;
  11579. }
  11580. }
  11581. VMA_ASSERT(0);
  11582. }
  11583. void VmaBlockVector::IncrementallySortBlocks()
  11584. {
  11585. if(m_Algorithm != VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT)
  11586. {
  11587. // Bubble sort only until first swap.
  11588. for(size_t i = 1; i < m_Blocks.size(); ++i)
  11589. {
  11590. if(m_Blocks[i - 1]->m_pMetadata->GetSumFreeSize() > m_Blocks[i]->m_pMetadata->GetSumFreeSize())
  11591. {
  11592. VMA_SWAP(m_Blocks[i - 1], m_Blocks[i]);
  11593. return;
  11594. }
  11595. }
  11596. }
  11597. }
  11598. VkResult VmaBlockVector::AllocateFromBlock(
  11599. VmaDeviceMemoryBlock* pBlock,
  11600. uint32_t currentFrameIndex,
  11601. VkDeviceSize size,
  11602. VkDeviceSize alignment,
  11603. VmaAllocationCreateFlags allocFlags,
  11604. void* pUserData,
  11605. VmaSuballocationType suballocType,
  11606. uint32_t strategy,
  11607. VmaAllocation* pAllocation)
  11608. {
  11609. VMA_ASSERT((allocFlags & VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT) == 0);
  11610. const bool isUpperAddress = (allocFlags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0;
  11611. const bool mapped = (allocFlags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0;
  11612. const bool isUserDataString = (allocFlags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0;
  11613. VmaAllocationRequest currRequest = {};
  11614. if(pBlock->m_pMetadata->CreateAllocationRequest(
  11615. currentFrameIndex,
  11616. m_FrameInUseCount,
  11617. m_BufferImageGranularity,
  11618. size,
  11619. alignment,
  11620. isUpperAddress,
  11621. suballocType,
  11622. false, // canMakeOtherLost
  11623. strategy,
  11624. &currRequest))
  11625. {
  11626. // Allocate from pCurrBlock.
  11627. VMA_ASSERT(currRequest.itemsToMakeLostCount == 0);
  11628. if(mapped)
  11629. {
  11630. VkResult res = pBlock->Map(m_hAllocator, 1, VMA_NULL);
  11631. if(res != VK_SUCCESS)
  11632. {
  11633. return res;
  11634. }
  11635. }
  11636. *pAllocation = m_hAllocator->m_AllocationObjectAllocator.Allocate(currentFrameIndex, isUserDataString);
  11637. pBlock->m_pMetadata->Alloc(currRequest, suballocType, size, *pAllocation);
  11638. UpdateHasEmptyBlock();
  11639. (*pAllocation)->InitBlockAllocation(
  11640. pBlock,
  11641. currRequest.offset,
  11642. alignment,
  11643. size,
  11644. m_MemoryTypeIndex,
  11645. suballocType,
  11646. mapped,
  11647. (allocFlags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0);
  11648. VMA_HEAVY_ASSERT(pBlock->Validate());
  11649. (*pAllocation)->SetUserData(m_hAllocator, pUserData);
  11650. m_hAllocator->m_Budget.AddAllocation(m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex), size);
  11651. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
  11652. {
  11653. m_hAllocator->FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED);
  11654. }
  11655. if(IsCorruptionDetectionEnabled())
  11656. {
  11657. VkResult res = pBlock->WriteMagicValueAroundAllocation(m_hAllocator, currRequest.offset, size);
  11658. VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to write magic value.");
  11659. }
  11660. return VK_SUCCESS;
  11661. }
  11662. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  11663. }
  11664. VkResult VmaBlockVector::CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex)
  11665. {
  11666. VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
  11667. allocInfo.pNext = m_pMemoryAllocateNext;
  11668. allocInfo.memoryTypeIndex = m_MemoryTypeIndex;
  11669. allocInfo.allocationSize = blockSize;
  11670. #if VMA_BUFFER_DEVICE_ADDRESS
  11671. // Every standalone block can potentially contain a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT - always enable the feature.
  11672. VkMemoryAllocateFlagsInfoKHR allocFlagsInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR };
  11673. if(m_hAllocator->m_UseKhrBufferDeviceAddress)
  11674. {
  11675. allocFlagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR;
  11676. VmaPnextChainPushFront(&allocInfo, &allocFlagsInfo);
  11677. }
  11678. #endif // #if VMA_BUFFER_DEVICE_ADDRESS
  11679. #if VMA_MEMORY_PRIORITY
  11680. VkMemoryPriorityAllocateInfoEXT priorityInfo = { VK_STRUCTURE_TYPE_MEMORY_PRIORITY_ALLOCATE_INFO_EXT };
  11681. if(m_hAllocator->m_UseExtMemoryPriority)
  11682. {
  11683. priorityInfo.priority = m_Priority;
  11684. VmaPnextChainPushFront(&allocInfo, &priorityInfo);
  11685. }
  11686. #endif // #if VMA_MEMORY_PRIORITY
  11687. #if VMA_EXTERNAL_MEMORY
  11688. // Attach VkExportMemoryAllocateInfoKHR if necessary.
  11689. VkExportMemoryAllocateInfoKHR exportMemoryAllocInfo = { VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR };
  11690. exportMemoryAllocInfo.handleTypes = m_hAllocator->GetExternalMemoryHandleTypeFlags(m_MemoryTypeIndex);
  11691. if(exportMemoryAllocInfo.handleTypes != 0)
  11692. {
  11693. VmaPnextChainPushFront(&allocInfo, &exportMemoryAllocInfo);
  11694. }
  11695. #endif // #if VMA_EXTERNAL_MEMORY
  11696. VkDeviceMemory mem = VK_NULL_HANDLE;
  11697. VkResult res = m_hAllocator->AllocateVulkanMemory(&allocInfo, &mem);
  11698. if(res < 0)
  11699. {
  11700. return res;
  11701. }
  11702. // New VkDeviceMemory successfully created.
  11703. // Create new Allocation for it.
  11704. VmaDeviceMemoryBlock* const pBlock = vma_new(m_hAllocator, VmaDeviceMemoryBlock)(m_hAllocator);
  11705. pBlock->Init(
  11706. m_hAllocator,
  11707. this, // parentBlockVector
  11708. m_hParentPool,
  11709. m_MemoryTypeIndex,
  11710. mem,
  11711. allocInfo.allocationSize,
  11712. m_NextBlockId++,
  11713. m_Algorithm);
  11714. m_Blocks.push_back(pBlock);
  11715. if(pNewBlockIndex != VMA_NULL)
  11716. {
  11717. *pNewBlockIndex = m_Blocks.size() - 1;
  11718. }
  11719. return VK_SUCCESS;
  11720. }
  11721. void VmaBlockVector::ApplyDefragmentationMovesCpu(
  11722. class VmaBlockVectorDefragmentationContext* pDefragCtx,
  11723. const VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves)
  11724. {
  11725. const size_t blockCount = m_Blocks.size();
  11726. const bool isNonCoherent = m_hAllocator->IsMemoryTypeNonCoherent(m_MemoryTypeIndex);
  11727. enum BLOCK_FLAG
  11728. {
  11729. BLOCK_FLAG_USED = 0x00000001,
  11730. BLOCK_FLAG_MAPPED_FOR_DEFRAGMENTATION = 0x00000002,
  11731. };
  11732. struct BlockInfo
  11733. {
  11734. uint32_t flags;
  11735. void* pMappedData;
  11736. };
  11737. VmaVector< BlockInfo, VmaStlAllocator<BlockInfo> >
  11738. blockInfo(blockCount, BlockInfo(), VmaStlAllocator<BlockInfo>(m_hAllocator->GetAllocationCallbacks()));
  11739. memset(blockInfo.data(), 0, blockCount * sizeof(BlockInfo));
  11740. // Go over all moves. Mark blocks that are used with BLOCK_FLAG_USED.
  11741. const size_t moveCount = moves.size();
  11742. for(size_t moveIndex = 0; moveIndex < moveCount; ++moveIndex)
  11743. {
  11744. const VmaDefragmentationMove& move = moves[moveIndex];
  11745. blockInfo[move.srcBlockIndex].flags |= BLOCK_FLAG_USED;
  11746. blockInfo[move.dstBlockIndex].flags |= BLOCK_FLAG_USED;
  11747. }
  11748. VMA_ASSERT(pDefragCtx->res == VK_SUCCESS);
  11749. // Go over all blocks. Get mapped pointer or map if necessary.
  11750. for(size_t blockIndex = 0; pDefragCtx->res == VK_SUCCESS && blockIndex < blockCount; ++blockIndex)
  11751. {
  11752. BlockInfo& currBlockInfo = blockInfo[blockIndex];
  11753. VmaDeviceMemoryBlock* pBlock = m_Blocks[blockIndex];
  11754. if((currBlockInfo.flags & BLOCK_FLAG_USED) != 0)
  11755. {
  11756. currBlockInfo.pMappedData = pBlock->GetMappedData();
  11757. // It is not originally mapped - map it.
  11758. if(currBlockInfo.pMappedData == VMA_NULL)
  11759. {
  11760. pDefragCtx->res = pBlock->Map(m_hAllocator, 1, &currBlockInfo.pMappedData);
  11761. if(pDefragCtx->res == VK_SUCCESS)
  11762. {
  11763. currBlockInfo.flags |= BLOCK_FLAG_MAPPED_FOR_DEFRAGMENTATION;
  11764. }
  11765. }
  11766. }
  11767. }
  11768. // Go over all moves. Do actual data transfer.
  11769. if(pDefragCtx->res == VK_SUCCESS)
  11770. {
  11771. const VkDeviceSize nonCoherentAtomSize = m_hAllocator->m_PhysicalDeviceProperties.limits.nonCoherentAtomSize;
  11772. VkMappedMemoryRange memRange = { VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE };
  11773. for(size_t moveIndex = 0; moveIndex < moveCount; ++moveIndex)
  11774. {
  11775. const VmaDefragmentationMove& move = moves[moveIndex];
  11776. const BlockInfo& srcBlockInfo = blockInfo[move.srcBlockIndex];
  11777. const BlockInfo& dstBlockInfo = blockInfo[move.dstBlockIndex];
  11778. VMA_ASSERT(srcBlockInfo.pMappedData && dstBlockInfo.pMappedData);
  11779. // Invalidate source.
  11780. if(isNonCoherent)
  11781. {
  11782. VmaDeviceMemoryBlock* const pSrcBlock = m_Blocks[move.srcBlockIndex];
  11783. memRange.memory = pSrcBlock->GetDeviceMemory();
  11784. memRange.offset = VmaAlignDown(move.srcOffset, nonCoherentAtomSize);
  11785. memRange.size = VMA_MIN(
  11786. VmaAlignUp(move.size + (move.srcOffset - memRange.offset), nonCoherentAtomSize),
  11787. pSrcBlock->m_pMetadata->GetSize() - memRange.offset);
  11788. (*m_hAllocator->GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hAllocator->m_hDevice, 1, &memRange);
  11789. }
  11790. // THE PLACE WHERE ACTUAL DATA COPY HAPPENS.
  11791. memmove(
  11792. reinterpret_cast<char*>(dstBlockInfo.pMappedData) + move.dstOffset,
  11793. reinterpret_cast<char*>(srcBlockInfo.pMappedData) + move.srcOffset,
  11794. static_cast<size_t>(move.size));
  11795. if(IsCorruptionDetectionEnabled())
  11796. {
  11797. VmaWriteMagicValue(dstBlockInfo.pMappedData, move.dstOffset - VMA_DEBUG_MARGIN);
  11798. VmaWriteMagicValue(dstBlockInfo.pMappedData, move.dstOffset + move.size);
  11799. }
  11800. // Flush destination.
  11801. if(isNonCoherent)
  11802. {
  11803. VmaDeviceMemoryBlock* const pDstBlock = m_Blocks[move.dstBlockIndex];
  11804. memRange.memory = pDstBlock->GetDeviceMemory();
  11805. memRange.offset = VmaAlignDown(move.dstOffset, nonCoherentAtomSize);
  11806. memRange.size = VMA_MIN(
  11807. VmaAlignUp(move.size + (move.dstOffset - memRange.offset), nonCoherentAtomSize),
  11808. pDstBlock->m_pMetadata->GetSize() - memRange.offset);
  11809. (*m_hAllocator->GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hAllocator->m_hDevice, 1, &memRange);
  11810. }
  11811. }
  11812. }
  11813. // Go over all blocks in reverse order. Unmap those that were mapped just for defragmentation.
  11814. // Regardless of pCtx->res == VK_SUCCESS.
  11815. for(size_t blockIndex = blockCount; blockIndex--; )
  11816. {
  11817. const BlockInfo& currBlockInfo = blockInfo[blockIndex];
  11818. if((currBlockInfo.flags & BLOCK_FLAG_MAPPED_FOR_DEFRAGMENTATION) != 0)
  11819. {
  11820. VmaDeviceMemoryBlock* pBlock = m_Blocks[blockIndex];
  11821. pBlock->Unmap(m_hAllocator, 1);
  11822. }
  11823. }
  11824. }
  11825. void VmaBlockVector::ApplyDefragmentationMovesGpu(
  11826. class VmaBlockVectorDefragmentationContext* pDefragCtx,
  11827. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  11828. VkCommandBuffer commandBuffer)
  11829. {
  11830. const size_t blockCount = m_Blocks.size();
  11831. pDefragCtx->blockContexts.resize(blockCount);
  11832. memset(pDefragCtx->blockContexts.data(), 0, blockCount * sizeof(VmaBlockDefragmentationContext));
  11833. // Go over all moves. Mark blocks that are used with BLOCK_FLAG_USED.
  11834. const size_t moveCount = moves.size();
  11835. for(size_t moveIndex = 0; moveIndex < moveCount; ++moveIndex)
  11836. {
  11837. const VmaDefragmentationMove& move = moves[moveIndex];
  11838. //if(move.type == VMA_ALLOCATION_TYPE_UNKNOWN)
  11839. {
  11840. // Old school move still require us to map the whole block
  11841. pDefragCtx->blockContexts[move.srcBlockIndex].flags |= VmaBlockDefragmentationContext::BLOCK_FLAG_USED;
  11842. pDefragCtx->blockContexts[move.dstBlockIndex].flags |= VmaBlockDefragmentationContext::BLOCK_FLAG_USED;
  11843. }
  11844. }
  11845. VMA_ASSERT(pDefragCtx->res == VK_SUCCESS);
  11846. // Go over all blocks. Create and bind buffer for whole block if necessary.
  11847. {
  11848. VkBufferCreateInfo bufCreateInfo;
  11849. VmaFillGpuDefragmentationBufferCreateInfo(bufCreateInfo);
  11850. for(size_t blockIndex = 0; pDefragCtx->res == VK_SUCCESS && blockIndex < blockCount; ++blockIndex)
  11851. {
  11852. VmaBlockDefragmentationContext& currBlockCtx = pDefragCtx->blockContexts[blockIndex];
  11853. VmaDeviceMemoryBlock* pBlock = m_Blocks[blockIndex];
  11854. if((currBlockCtx.flags & VmaBlockDefragmentationContext::BLOCK_FLAG_USED) != 0)
  11855. {
  11856. bufCreateInfo.size = pBlock->m_pMetadata->GetSize();
  11857. pDefragCtx->res = (*m_hAllocator->GetVulkanFunctions().vkCreateBuffer)(
  11858. m_hAllocator->m_hDevice, &bufCreateInfo, m_hAllocator->GetAllocationCallbacks(), &currBlockCtx.hBuffer);
  11859. if(pDefragCtx->res == VK_SUCCESS)
  11860. {
  11861. pDefragCtx->res = (*m_hAllocator->GetVulkanFunctions().vkBindBufferMemory)(
  11862. m_hAllocator->m_hDevice, currBlockCtx.hBuffer, pBlock->GetDeviceMemory(), 0);
  11863. }
  11864. }
  11865. }
  11866. }
  11867. // Go over all moves. Post data transfer commands to command buffer.
  11868. if(pDefragCtx->res == VK_SUCCESS)
  11869. {
  11870. for(size_t moveIndex = 0; moveIndex < moveCount; ++moveIndex)
  11871. {
  11872. const VmaDefragmentationMove& move = moves[moveIndex];
  11873. const VmaBlockDefragmentationContext& srcBlockCtx = pDefragCtx->blockContexts[move.srcBlockIndex];
  11874. const VmaBlockDefragmentationContext& dstBlockCtx = pDefragCtx->blockContexts[move.dstBlockIndex];
  11875. VMA_ASSERT(srcBlockCtx.hBuffer && dstBlockCtx.hBuffer);
  11876. VkBufferCopy region = {
  11877. move.srcOffset,
  11878. move.dstOffset,
  11879. move.size };
  11880. (*m_hAllocator->GetVulkanFunctions().vkCmdCopyBuffer)(
  11881. commandBuffer, srcBlockCtx.hBuffer, dstBlockCtx.hBuffer, 1, &region);
  11882. }
  11883. }
  11884. // Save buffers to defrag context for later destruction.
  11885. if(pDefragCtx->res == VK_SUCCESS && moveCount > 0)
  11886. {
  11887. pDefragCtx->res = VK_NOT_READY;
  11888. }
  11889. }
  11890. void VmaBlockVector::FreeEmptyBlocks(VmaDefragmentationStats* pDefragmentationStats)
  11891. {
  11892. for(size_t blockIndex = m_Blocks.size(); blockIndex--; )
  11893. {
  11894. VmaDeviceMemoryBlock* pBlock = m_Blocks[blockIndex];
  11895. if(pBlock->m_pMetadata->IsEmpty())
  11896. {
  11897. if(m_Blocks.size() > m_MinBlockCount)
  11898. {
  11899. if(pDefragmentationStats != VMA_NULL)
  11900. {
  11901. ++pDefragmentationStats->deviceMemoryBlocksFreed;
  11902. pDefragmentationStats->bytesFreed += pBlock->m_pMetadata->GetSize();
  11903. }
  11904. VmaVectorRemove(m_Blocks, blockIndex);
  11905. pBlock->Destroy(m_hAllocator);
  11906. vma_delete(m_hAllocator, pBlock);
  11907. }
  11908. else
  11909. {
  11910. break;
  11911. }
  11912. }
  11913. }
  11914. UpdateHasEmptyBlock();
  11915. }
  11916. void VmaBlockVector::UpdateHasEmptyBlock()
  11917. {
  11918. m_HasEmptyBlock = false;
  11919. for(size_t index = 0, count = m_Blocks.size(); index < count; ++index)
  11920. {
  11921. VmaDeviceMemoryBlock* const pBlock = m_Blocks[index];
  11922. if(pBlock->m_pMetadata->IsEmpty())
  11923. {
  11924. m_HasEmptyBlock = true;
  11925. break;
  11926. }
  11927. }
  11928. }
  11929. #if VMA_STATS_STRING_ENABLED
  11930. void VmaBlockVector::PrintDetailedMap(class VmaJsonWriter& json)
  11931. {
  11932. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  11933. json.BeginObject();
  11934. if(IsCustomPool())
  11935. {
  11936. const char* poolName = m_hParentPool->GetName();
  11937. if(poolName != VMA_NULL && poolName[0] != '\0')
  11938. {
  11939. json.WriteString("Name");
  11940. json.WriteString(poolName);
  11941. }
  11942. json.WriteString("MemoryTypeIndex");
  11943. json.WriteNumber(m_MemoryTypeIndex);
  11944. json.WriteString("BlockSize");
  11945. json.WriteNumber(m_PreferredBlockSize);
  11946. json.WriteString("BlockCount");
  11947. json.BeginObject(true);
  11948. if(m_MinBlockCount > 0)
  11949. {
  11950. json.WriteString("Min");
  11951. json.WriteNumber((uint64_t)m_MinBlockCount);
  11952. }
  11953. if(m_MaxBlockCount < SIZE_MAX)
  11954. {
  11955. json.WriteString("Max");
  11956. json.WriteNumber((uint64_t)m_MaxBlockCount);
  11957. }
  11958. json.WriteString("Cur");
  11959. json.WriteNumber((uint64_t)m_Blocks.size());
  11960. json.EndObject();
  11961. if(m_FrameInUseCount > 0)
  11962. {
  11963. json.WriteString("FrameInUseCount");
  11964. json.WriteNumber(m_FrameInUseCount);
  11965. }
  11966. if(m_Algorithm != 0)
  11967. {
  11968. json.WriteString("Algorithm");
  11969. json.WriteString(VmaAlgorithmToStr(m_Algorithm));
  11970. }
  11971. }
  11972. else
  11973. {
  11974. json.WriteString("PreferredBlockSize");
  11975. json.WriteNumber(m_PreferredBlockSize);
  11976. }
  11977. json.WriteString("Blocks");
  11978. json.BeginObject();
  11979. for(size_t i = 0; i < m_Blocks.size(); ++i)
  11980. {
  11981. json.BeginString();
  11982. json.ContinueString(m_Blocks[i]->GetId());
  11983. json.EndString();
  11984. m_Blocks[i]->m_pMetadata->PrintDetailedMap(json);
  11985. }
  11986. json.EndObject();
  11987. json.EndObject();
  11988. }
  11989. #endif // #if VMA_STATS_STRING_ENABLED
  11990. void VmaBlockVector::Defragment(
  11991. class VmaBlockVectorDefragmentationContext* pCtx,
  11992. VmaDefragmentationStats* pStats, VmaDefragmentationFlags flags,
  11993. VkDeviceSize& maxCpuBytesToMove, uint32_t& maxCpuAllocationsToMove,
  11994. VkDeviceSize& maxGpuBytesToMove, uint32_t& maxGpuAllocationsToMove,
  11995. VkCommandBuffer commandBuffer)
  11996. {
  11997. pCtx->res = VK_SUCCESS;
  11998. const VkMemoryPropertyFlags memPropFlags =
  11999. m_hAllocator->m_MemProps.memoryTypes[m_MemoryTypeIndex].propertyFlags;
  12000. const bool isHostVisible = (memPropFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0;
  12001. const bool canDefragmentOnCpu = maxCpuBytesToMove > 0 && maxCpuAllocationsToMove > 0 &&
  12002. isHostVisible;
  12003. const bool canDefragmentOnGpu = maxGpuBytesToMove > 0 && maxGpuAllocationsToMove > 0 &&
  12004. !IsCorruptionDetectionEnabled() &&
  12005. ((1u << m_MemoryTypeIndex) & m_hAllocator->GetGpuDefragmentationMemoryTypeBits()) != 0;
  12006. // There are options to defragment this memory type.
  12007. if(canDefragmentOnCpu || canDefragmentOnGpu)
  12008. {
  12009. bool defragmentOnGpu;
  12010. // There is only one option to defragment this memory type.
  12011. if(canDefragmentOnGpu != canDefragmentOnCpu)
  12012. {
  12013. defragmentOnGpu = canDefragmentOnGpu;
  12014. }
  12015. // Both options are available: Heuristics to choose the best one.
  12016. else
  12017. {
  12018. defragmentOnGpu = (memPropFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0 ||
  12019. m_hAllocator->IsIntegratedGpu();
  12020. }
  12021. bool overlappingMoveSupported = !defragmentOnGpu;
  12022. if(m_hAllocator->m_UseMutex)
  12023. {
  12024. if(flags & VMA_DEFRAGMENTATION_FLAG_INCREMENTAL)
  12025. {
  12026. if(!m_Mutex.TryLockWrite())
  12027. {
  12028. pCtx->res = VK_ERROR_INITIALIZATION_FAILED;
  12029. return;
  12030. }
  12031. }
  12032. else
  12033. {
  12034. m_Mutex.LockWrite();
  12035. pCtx->mutexLocked = true;
  12036. }
  12037. }
  12038. pCtx->Begin(overlappingMoveSupported, flags);
  12039. // Defragment.
  12040. const VkDeviceSize maxBytesToMove = defragmentOnGpu ? maxGpuBytesToMove : maxCpuBytesToMove;
  12041. const uint32_t maxAllocationsToMove = defragmentOnGpu ? maxGpuAllocationsToMove : maxCpuAllocationsToMove;
  12042. pCtx->res = pCtx->GetAlgorithm()->Defragment(pCtx->defragmentationMoves, maxBytesToMove, maxAllocationsToMove, flags);
  12043. // Accumulate statistics.
  12044. if(pStats != VMA_NULL)
  12045. {
  12046. const VkDeviceSize bytesMoved = pCtx->GetAlgorithm()->GetBytesMoved();
  12047. const uint32_t allocationsMoved = pCtx->GetAlgorithm()->GetAllocationsMoved();
  12048. pStats->bytesMoved += bytesMoved;
  12049. pStats->allocationsMoved += allocationsMoved;
  12050. VMA_ASSERT(bytesMoved <= maxBytesToMove);
  12051. VMA_ASSERT(allocationsMoved <= maxAllocationsToMove);
  12052. if(defragmentOnGpu)
  12053. {
  12054. maxGpuBytesToMove -= bytesMoved;
  12055. maxGpuAllocationsToMove -= allocationsMoved;
  12056. }
  12057. else
  12058. {
  12059. maxCpuBytesToMove -= bytesMoved;
  12060. maxCpuAllocationsToMove -= allocationsMoved;
  12061. }
  12062. }
  12063. if(flags & VMA_DEFRAGMENTATION_FLAG_INCREMENTAL)
  12064. {
  12065. if(m_hAllocator->m_UseMutex)
  12066. m_Mutex.UnlockWrite();
  12067. if(pCtx->res >= VK_SUCCESS && !pCtx->defragmentationMoves.empty())
  12068. pCtx->res = VK_NOT_READY;
  12069. return;
  12070. }
  12071. if(pCtx->res >= VK_SUCCESS)
  12072. {
  12073. if(defragmentOnGpu)
  12074. {
  12075. ApplyDefragmentationMovesGpu(pCtx, pCtx->defragmentationMoves, commandBuffer);
  12076. }
  12077. else
  12078. {
  12079. ApplyDefragmentationMovesCpu(pCtx, pCtx->defragmentationMoves);
  12080. }
  12081. }
  12082. }
  12083. }
  12084. void VmaBlockVector::DefragmentationEnd(
  12085. class VmaBlockVectorDefragmentationContext* pCtx,
  12086. uint32_t flags,
  12087. VmaDefragmentationStats* pStats)
  12088. {
  12089. if(flags & VMA_DEFRAGMENTATION_FLAG_INCREMENTAL && m_hAllocator->m_UseMutex)
  12090. {
  12091. VMA_ASSERT(pCtx->mutexLocked == false);
  12092. // Incremental defragmentation doesn't hold the lock, so when we enter here we don't actually have any
  12093. // lock protecting us. Since we mutate state here, we have to take the lock out now
  12094. m_Mutex.LockWrite();
  12095. pCtx->mutexLocked = true;
  12096. }
  12097. // If the mutex isn't locked we didn't do any work and there is nothing to delete.
  12098. if(pCtx->mutexLocked || !m_hAllocator->m_UseMutex)
  12099. {
  12100. // Destroy buffers.
  12101. for(size_t blockIndex = pCtx->blockContexts.size(); blockIndex--;)
  12102. {
  12103. VmaBlockDefragmentationContext &blockCtx = pCtx->blockContexts[blockIndex];
  12104. if(blockCtx.hBuffer)
  12105. {
  12106. (*m_hAllocator->GetVulkanFunctions().vkDestroyBuffer)(m_hAllocator->m_hDevice, blockCtx.hBuffer, m_hAllocator->GetAllocationCallbacks());
  12107. }
  12108. }
  12109. if(pCtx->res >= VK_SUCCESS)
  12110. {
  12111. FreeEmptyBlocks(pStats);
  12112. }
  12113. }
  12114. if(pCtx->mutexLocked)
  12115. {
  12116. VMA_ASSERT(m_hAllocator->m_UseMutex);
  12117. m_Mutex.UnlockWrite();
  12118. }
  12119. }
  12120. uint32_t VmaBlockVector::ProcessDefragmentations(
  12121. class VmaBlockVectorDefragmentationContext *pCtx,
  12122. VmaDefragmentationPassMoveInfo* pMove, uint32_t maxMoves)
  12123. {
  12124. VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex);
  12125. const uint32_t moveCount = VMA_MIN(uint32_t(pCtx->defragmentationMoves.size()) - pCtx->defragmentationMovesProcessed, maxMoves);
  12126. for(uint32_t i = 0; i < moveCount; ++ i)
  12127. {
  12128. VmaDefragmentationMove& move = pCtx->defragmentationMoves[pCtx->defragmentationMovesProcessed + i];
  12129. pMove->allocation = move.hAllocation;
  12130. pMove->memory = move.pDstBlock->GetDeviceMemory();
  12131. pMove->offset = move.dstOffset;
  12132. ++ pMove;
  12133. }
  12134. pCtx->defragmentationMovesProcessed += moveCount;
  12135. return moveCount;
  12136. }
  12137. void VmaBlockVector::CommitDefragmentations(
  12138. class VmaBlockVectorDefragmentationContext *pCtx,
  12139. VmaDefragmentationStats* pStats)
  12140. {
  12141. VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex);
  12142. for(uint32_t i = pCtx->defragmentationMovesCommitted; i < pCtx->defragmentationMovesProcessed; ++ i)
  12143. {
  12144. const VmaDefragmentationMove &move = pCtx->defragmentationMoves[i];
  12145. move.pSrcBlock->m_pMetadata->FreeAtOffset(move.srcOffset);
  12146. move.hAllocation->ChangeBlockAllocation(m_hAllocator, move.pDstBlock, move.dstOffset);
  12147. }
  12148. pCtx->defragmentationMovesCommitted = pCtx->defragmentationMovesProcessed;
  12149. FreeEmptyBlocks(pStats);
  12150. }
  12151. size_t VmaBlockVector::CalcAllocationCount() const
  12152. {
  12153. size_t result = 0;
  12154. for(size_t i = 0; i < m_Blocks.size(); ++i)
  12155. {
  12156. result += m_Blocks[i]->m_pMetadata->GetAllocationCount();
  12157. }
  12158. return result;
  12159. }
  12160. bool VmaBlockVector::IsBufferImageGranularityConflictPossible() const
  12161. {
  12162. if(m_BufferImageGranularity == 1)
  12163. {
  12164. return false;
  12165. }
  12166. VmaSuballocationType lastSuballocType = VMA_SUBALLOCATION_TYPE_FREE;
  12167. for(size_t i = 0, count = m_Blocks.size(); i < count; ++i)
  12168. {
  12169. VmaDeviceMemoryBlock* const pBlock = m_Blocks[i];
  12170. VMA_ASSERT(m_Algorithm == 0);
  12171. VmaBlockMetadata_Generic* const pMetadata = (VmaBlockMetadata_Generic*)pBlock->m_pMetadata;
  12172. if(pMetadata->IsBufferImageGranularityConflictPossible(m_BufferImageGranularity, lastSuballocType))
  12173. {
  12174. return true;
  12175. }
  12176. }
  12177. return false;
  12178. }
  12179. void VmaBlockVector::MakePoolAllocationsLost(
  12180. uint32_t currentFrameIndex,
  12181. size_t* pLostAllocationCount)
  12182. {
  12183. VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex);
  12184. size_t lostAllocationCount = 0;
  12185. for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  12186. {
  12187. VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
  12188. VMA_ASSERT(pBlock);
  12189. lostAllocationCount += pBlock->m_pMetadata->MakeAllocationsLost(currentFrameIndex, m_FrameInUseCount);
  12190. }
  12191. if(pLostAllocationCount != VMA_NULL)
  12192. {
  12193. *pLostAllocationCount = lostAllocationCount;
  12194. }
  12195. }
  12196. VkResult VmaBlockVector::CheckCorruption()
  12197. {
  12198. if(!IsCorruptionDetectionEnabled())
  12199. {
  12200. return VK_ERROR_FEATURE_NOT_PRESENT;
  12201. }
  12202. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  12203. for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  12204. {
  12205. VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
  12206. VMA_ASSERT(pBlock);
  12207. VkResult res = pBlock->CheckCorruption(m_hAllocator);
  12208. if(res != VK_SUCCESS)
  12209. {
  12210. return res;
  12211. }
  12212. }
  12213. return VK_SUCCESS;
  12214. }
  12215. void VmaBlockVector::AddStats(VmaStats* pStats)
  12216. {
  12217. const uint32_t memTypeIndex = m_MemoryTypeIndex;
  12218. const uint32_t memHeapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(memTypeIndex);
  12219. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  12220. for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  12221. {
  12222. const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
  12223. VMA_ASSERT(pBlock);
  12224. VMA_HEAVY_ASSERT(pBlock->Validate());
  12225. VmaStatInfo allocationStatInfo;
  12226. pBlock->m_pMetadata->CalcAllocationStatInfo(allocationStatInfo);
  12227. VmaAddStatInfo(pStats->total, allocationStatInfo);
  12228. VmaAddStatInfo(pStats->memoryType[memTypeIndex], allocationStatInfo);
  12229. VmaAddStatInfo(pStats->memoryHeap[memHeapIndex], allocationStatInfo);
  12230. }
  12231. }
  12232. ////////////////////////////////////////////////////////////////////////////////
  12233. // VmaDefragmentationAlgorithm_Generic members definition
  12234. VmaDefragmentationAlgorithm_Generic::VmaDefragmentationAlgorithm_Generic(
  12235. VmaAllocator hAllocator,
  12236. VmaBlockVector* pBlockVector,
  12237. uint32_t currentFrameIndex,
  12238. bool overlappingMoveSupported) :
  12239. VmaDefragmentationAlgorithm(hAllocator, pBlockVector, currentFrameIndex),
  12240. m_AllocationCount(0),
  12241. m_AllAllocations(false),
  12242. m_BytesMoved(0),
  12243. m_AllocationsMoved(0),
  12244. m_Blocks(VmaStlAllocator<BlockInfo*>(hAllocator->GetAllocationCallbacks()))
  12245. {
  12246. // Create block info for each block.
  12247. const size_t blockCount = m_pBlockVector->m_Blocks.size();
  12248. for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
  12249. {
  12250. BlockInfo* pBlockInfo = vma_new(m_hAllocator, BlockInfo)(m_hAllocator->GetAllocationCallbacks());
  12251. pBlockInfo->m_OriginalBlockIndex = blockIndex;
  12252. pBlockInfo->m_pBlock = m_pBlockVector->m_Blocks[blockIndex];
  12253. m_Blocks.push_back(pBlockInfo);
  12254. }
  12255. // Sort them by m_pBlock pointer value.
  12256. VMA_SORT(m_Blocks.begin(), m_Blocks.end(), BlockPointerLess());
  12257. }
  12258. VmaDefragmentationAlgorithm_Generic::~VmaDefragmentationAlgorithm_Generic()
  12259. {
  12260. for(size_t i = m_Blocks.size(); i--; )
  12261. {
  12262. vma_delete(m_hAllocator, m_Blocks[i]);
  12263. }
  12264. }
  12265. void VmaDefragmentationAlgorithm_Generic::AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged)
  12266. {
  12267. // Now as we are inside VmaBlockVector::m_Mutex, we can make final check if this allocation was not lost.
  12268. if(hAlloc->GetLastUseFrameIndex() != VMA_FRAME_INDEX_LOST)
  12269. {
  12270. VmaDeviceMemoryBlock* pBlock = hAlloc->GetBlock();
  12271. BlockInfoVector::iterator it = VmaBinaryFindFirstNotLess(m_Blocks.begin(), m_Blocks.end(), pBlock, BlockPointerLess());
  12272. if(it != m_Blocks.end() && (*it)->m_pBlock == pBlock)
  12273. {
  12274. AllocationInfo allocInfo = AllocationInfo(hAlloc, pChanged);
  12275. (*it)->m_Allocations.push_back(allocInfo);
  12276. }
  12277. else
  12278. {
  12279. VMA_ASSERT(0);
  12280. }
  12281. ++m_AllocationCount;
  12282. }
  12283. }
  12284. VkResult VmaDefragmentationAlgorithm_Generic::DefragmentRound(
  12285. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  12286. VkDeviceSize maxBytesToMove,
  12287. uint32_t maxAllocationsToMove,
  12288. bool freeOldAllocations)
  12289. {
  12290. if(m_Blocks.empty())
  12291. {
  12292. return VK_SUCCESS;
  12293. }
  12294. // This is a choice based on research.
  12295. // Option 1:
  12296. uint32_t strategy = VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT;
  12297. // Option 2:
  12298. //uint32_t strategy = VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT;
  12299. // Option 3:
  12300. //uint32_t strategy = VMA_ALLOCATION_CREATE_STRATEGY_MIN_FRAGMENTATION_BIT;
  12301. size_t srcBlockMinIndex = 0;
  12302. // When FAST_ALGORITHM, move allocations from only last out of blocks that contain non-movable allocations.
  12303. /*
  12304. if(m_AlgorithmFlags & VMA_DEFRAGMENTATION_FAST_ALGORITHM_BIT)
  12305. {
  12306. const size_t blocksWithNonMovableCount = CalcBlocksWithNonMovableCount();
  12307. if(blocksWithNonMovableCount > 0)
  12308. {
  12309. srcBlockMinIndex = blocksWithNonMovableCount - 1;
  12310. }
  12311. }
  12312. */
  12313. size_t srcBlockIndex = m_Blocks.size() - 1;
  12314. size_t srcAllocIndex = SIZE_MAX;
  12315. for(;;)
  12316. {
  12317. // 1. Find next allocation to move.
  12318. // 1.1. Start from last to first m_Blocks - they are sorted from most "destination" to most "source".
  12319. // 1.2. Then start from last to first m_Allocations.
  12320. while(srcAllocIndex >= m_Blocks[srcBlockIndex]->m_Allocations.size())
  12321. {
  12322. if(m_Blocks[srcBlockIndex]->m_Allocations.empty())
  12323. {
  12324. // Finished: no more allocations to process.
  12325. if(srcBlockIndex == srcBlockMinIndex)
  12326. {
  12327. return VK_SUCCESS;
  12328. }
  12329. else
  12330. {
  12331. --srcBlockIndex;
  12332. srcAllocIndex = SIZE_MAX;
  12333. }
  12334. }
  12335. else
  12336. {
  12337. srcAllocIndex = m_Blocks[srcBlockIndex]->m_Allocations.size() - 1;
  12338. }
  12339. }
  12340. BlockInfo* pSrcBlockInfo = m_Blocks[srcBlockIndex];
  12341. AllocationInfo& allocInfo = pSrcBlockInfo->m_Allocations[srcAllocIndex];
  12342. const VkDeviceSize size = allocInfo.m_hAllocation->GetSize();
  12343. const VkDeviceSize srcOffset = allocInfo.m_hAllocation->GetOffset();
  12344. const VkDeviceSize alignment = allocInfo.m_hAllocation->GetAlignment();
  12345. const VmaSuballocationType suballocType = allocInfo.m_hAllocation->GetSuballocationType();
  12346. // 2. Try to find new place for this allocation in preceding or current block.
  12347. for(size_t dstBlockIndex = 0; dstBlockIndex <= srcBlockIndex; ++dstBlockIndex)
  12348. {
  12349. BlockInfo* pDstBlockInfo = m_Blocks[dstBlockIndex];
  12350. VmaAllocationRequest dstAllocRequest;
  12351. if(pDstBlockInfo->m_pBlock->m_pMetadata->CreateAllocationRequest(
  12352. m_CurrentFrameIndex,
  12353. m_pBlockVector->GetFrameInUseCount(),
  12354. m_pBlockVector->GetBufferImageGranularity(),
  12355. size,
  12356. alignment,
  12357. false, // upperAddress
  12358. suballocType,
  12359. false, // canMakeOtherLost
  12360. strategy,
  12361. &dstAllocRequest) &&
  12362. MoveMakesSense(
  12363. dstBlockIndex, dstAllocRequest.offset, srcBlockIndex, srcOffset))
  12364. {
  12365. VMA_ASSERT(dstAllocRequest.itemsToMakeLostCount == 0);
  12366. // Reached limit on number of allocations or bytes to move.
  12367. if((m_AllocationsMoved + 1 > maxAllocationsToMove) ||
  12368. (m_BytesMoved + size > maxBytesToMove))
  12369. {
  12370. return VK_SUCCESS;
  12371. }
  12372. VmaDefragmentationMove move = {};
  12373. move.srcBlockIndex = pSrcBlockInfo->m_OriginalBlockIndex;
  12374. move.dstBlockIndex = pDstBlockInfo->m_OriginalBlockIndex;
  12375. move.srcOffset = srcOffset;
  12376. move.dstOffset = dstAllocRequest.offset;
  12377. move.size = size;
  12378. move.hAllocation = allocInfo.m_hAllocation;
  12379. move.pSrcBlock = pSrcBlockInfo->m_pBlock;
  12380. move.pDstBlock = pDstBlockInfo->m_pBlock;
  12381. moves.push_back(move);
  12382. pDstBlockInfo->m_pBlock->m_pMetadata->Alloc(
  12383. dstAllocRequest,
  12384. suballocType,
  12385. size,
  12386. allocInfo.m_hAllocation);
  12387. if(freeOldAllocations)
  12388. {
  12389. pSrcBlockInfo->m_pBlock->m_pMetadata->FreeAtOffset(srcOffset);
  12390. allocInfo.m_hAllocation->ChangeBlockAllocation(m_hAllocator, pDstBlockInfo->m_pBlock, dstAllocRequest.offset);
  12391. }
  12392. if(allocInfo.m_pChanged != VMA_NULL)
  12393. {
  12394. *allocInfo.m_pChanged = VK_TRUE;
  12395. }
  12396. ++m_AllocationsMoved;
  12397. m_BytesMoved += size;
  12398. VmaVectorRemove(pSrcBlockInfo->m_Allocations, srcAllocIndex);
  12399. break;
  12400. }
  12401. }
  12402. // If not processed, this allocInfo remains in pBlockInfo->m_Allocations for next round.
  12403. if(srcAllocIndex > 0)
  12404. {
  12405. --srcAllocIndex;
  12406. }
  12407. else
  12408. {
  12409. if(srcBlockIndex > 0)
  12410. {
  12411. --srcBlockIndex;
  12412. srcAllocIndex = SIZE_MAX;
  12413. }
  12414. else
  12415. {
  12416. return VK_SUCCESS;
  12417. }
  12418. }
  12419. }
  12420. }
  12421. size_t VmaDefragmentationAlgorithm_Generic::CalcBlocksWithNonMovableCount() const
  12422. {
  12423. size_t result = 0;
  12424. for(size_t i = 0; i < m_Blocks.size(); ++i)
  12425. {
  12426. if(m_Blocks[i]->m_HasNonMovableAllocations)
  12427. {
  12428. ++result;
  12429. }
  12430. }
  12431. return result;
  12432. }
  12433. VkResult VmaDefragmentationAlgorithm_Generic::Defragment(
  12434. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  12435. VkDeviceSize maxBytesToMove,
  12436. uint32_t maxAllocationsToMove,
  12437. VmaDefragmentationFlags flags)
  12438. {
  12439. if(!m_AllAllocations && m_AllocationCount == 0)
  12440. {
  12441. return VK_SUCCESS;
  12442. }
  12443. const size_t blockCount = m_Blocks.size();
  12444. for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
  12445. {
  12446. BlockInfo* pBlockInfo = m_Blocks[blockIndex];
  12447. if(m_AllAllocations)
  12448. {
  12449. VmaBlockMetadata_Generic* pMetadata = (VmaBlockMetadata_Generic*)pBlockInfo->m_pBlock->m_pMetadata;
  12450. for(VmaSuballocationList::const_iterator it = pMetadata->m_Suballocations.begin();
  12451. it != pMetadata->m_Suballocations.end();
  12452. ++it)
  12453. {
  12454. if(it->type != VMA_SUBALLOCATION_TYPE_FREE)
  12455. {
  12456. AllocationInfo allocInfo = AllocationInfo(it->hAllocation, VMA_NULL);
  12457. pBlockInfo->m_Allocations.push_back(allocInfo);
  12458. }
  12459. }
  12460. }
  12461. pBlockInfo->CalcHasNonMovableAllocations();
  12462. // This is a choice based on research.
  12463. // Option 1:
  12464. pBlockInfo->SortAllocationsByOffsetDescending();
  12465. // Option 2:
  12466. //pBlockInfo->SortAllocationsBySizeDescending();
  12467. }
  12468. // Sort m_Blocks this time by the main criterium, from most "destination" to most "source" blocks.
  12469. VMA_SORT(m_Blocks.begin(), m_Blocks.end(), BlockInfoCompareMoveDestination());
  12470. // This is a choice based on research.
  12471. const uint32_t roundCount = 2;
  12472. // Execute defragmentation rounds (the main part).
  12473. VkResult result = VK_SUCCESS;
  12474. for(uint32_t round = 0; (round < roundCount) && (result == VK_SUCCESS); ++round)
  12475. {
  12476. result = DefragmentRound(moves, maxBytesToMove, maxAllocationsToMove, !(flags & VMA_DEFRAGMENTATION_FLAG_INCREMENTAL));
  12477. }
  12478. return result;
  12479. }
  12480. bool VmaDefragmentationAlgorithm_Generic::MoveMakesSense(
  12481. size_t dstBlockIndex, VkDeviceSize dstOffset,
  12482. size_t srcBlockIndex, VkDeviceSize srcOffset)
  12483. {
  12484. if(dstBlockIndex < srcBlockIndex)
  12485. {
  12486. return true;
  12487. }
  12488. if(dstBlockIndex > srcBlockIndex)
  12489. {
  12490. return false;
  12491. }
  12492. if(dstOffset < srcOffset)
  12493. {
  12494. return true;
  12495. }
  12496. return false;
  12497. }
  12498. ////////////////////////////////////////////////////////////////////////////////
  12499. // VmaDefragmentationAlgorithm_Fast
  12500. VmaDefragmentationAlgorithm_Fast::VmaDefragmentationAlgorithm_Fast(
  12501. VmaAllocator hAllocator,
  12502. VmaBlockVector* pBlockVector,
  12503. uint32_t currentFrameIndex,
  12504. bool overlappingMoveSupported) :
  12505. VmaDefragmentationAlgorithm(hAllocator, pBlockVector, currentFrameIndex),
  12506. m_OverlappingMoveSupported(overlappingMoveSupported),
  12507. m_AllocationCount(0),
  12508. m_AllAllocations(false),
  12509. m_BytesMoved(0),
  12510. m_AllocationsMoved(0),
  12511. m_BlockInfos(VmaStlAllocator<BlockInfo>(hAllocator->GetAllocationCallbacks()))
  12512. {
  12513. VMA_ASSERT(VMA_DEBUG_MARGIN == 0);
  12514. }
  12515. VmaDefragmentationAlgorithm_Fast::~VmaDefragmentationAlgorithm_Fast()
  12516. {
  12517. }
  12518. VkResult VmaDefragmentationAlgorithm_Fast::Defragment(
  12519. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  12520. VkDeviceSize maxBytesToMove,
  12521. uint32_t maxAllocationsToMove,
  12522. VmaDefragmentationFlags flags)
  12523. {
  12524. VMA_ASSERT(m_AllAllocations || m_pBlockVector->CalcAllocationCount() == m_AllocationCount);
  12525. const size_t blockCount = m_pBlockVector->GetBlockCount();
  12526. if(blockCount == 0 || maxBytesToMove == 0 || maxAllocationsToMove == 0)
  12527. {
  12528. return VK_SUCCESS;
  12529. }
  12530. PreprocessMetadata();
  12531. // Sort blocks in order from most destination.
  12532. m_BlockInfos.resize(blockCount);
  12533. for(size_t i = 0; i < blockCount; ++i)
  12534. {
  12535. m_BlockInfos[i].origBlockIndex = i;
  12536. }
  12537. VMA_SORT(m_BlockInfos.begin(), m_BlockInfos.end(), [this](const BlockInfo& lhs, const BlockInfo& rhs) -> bool {
  12538. return m_pBlockVector->GetBlock(lhs.origBlockIndex)->m_pMetadata->GetSumFreeSize() <
  12539. m_pBlockVector->GetBlock(rhs.origBlockIndex)->m_pMetadata->GetSumFreeSize();
  12540. });
  12541. // THE MAIN ALGORITHM
  12542. FreeSpaceDatabase freeSpaceDb;
  12543. size_t dstBlockInfoIndex = 0;
  12544. size_t dstOrigBlockIndex = m_BlockInfos[dstBlockInfoIndex].origBlockIndex;
  12545. VmaDeviceMemoryBlock* pDstBlock = m_pBlockVector->GetBlock(dstOrigBlockIndex);
  12546. VmaBlockMetadata_Generic* pDstMetadata = (VmaBlockMetadata_Generic*)pDstBlock->m_pMetadata;
  12547. VkDeviceSize dstBlockSize = pDstMetadata->GetSize();
  12548. VkDeviceSize dstOffset = 0;
  12549. bool end = false;
  12550. for(size_t srcBlockInfoIndex = 0; !end && srcBlockInfoIndex < blockCount; ++srcBlockInfoIndex)
  12551. {
  12552. const size_t srcOrigBlockIndex = m_BlockInfos[srcBlockInfoIndex].origBlockIndex;
  12553. VmaDeviceMemoryBlock* const pSrcBlock = m_pBlockVector->GetBlock(srcOrigBlockIndex);
  12554. VmaBlockMetadata_Generic* const pSrcMetadata = (VmaBlockMetadata_Generic*)pSrcBlock->m_pMetadata;
  12555. for(VmaSuballocationList::iterator srcSuballocIt = pSrcMetadata->m_Suballocations.begin();
  12556. !end && srcSuballocIt != pSrcMetadata->m_Suballocations.end(); )
  12557. {
  12558. VmaAllocation_T* const pAlloc = srcSuballocIt->hAllocation;
  12559. const VkDeviceSize srcAllocAlignment = pAlloc->GetAlignment();
  12560. const VkDeviceSize srcAllocSize = srcSuballocIt->size;
  12561. if(m_AllocationsMoved == maxAllocationsToMove ||
  12562. m_BytesMoved + srcAllocSize > maxBytesToMove)
  12563. {
  12564. end = true;
  12565. break;
  12566. }
  12567. const VkDeviceSize srcAllocOffset = srcSuballocIt->offset;
  12568. VmaDefragmentationMove move = {};
  12569. // Try to place it in one of free spaces from the database.
  12570. size_t freeSpaceInfoIndex;
  12571. VkDeviceSize dstAllocOffset;
  12572. if(freeSpaceDb.Fetch(srcAllocAlignment, srcAllocSize,
  12573. freeSpaceInfoIndex, dstAllocOffset))
  12574. {
  12575. size_t freeSpaceOrigBlockIndex = m_BlockInfos[freeSpaceInfoIndex].origBlockIndex;
  12576. VmaDeviceMemoryBlock* pFreeSpaceBlock = m_pBlockVector->GetBlock(freeSpaceOrigBlockIndex);
  12577. VmaBlockMetadata_Generic* pFreeSpaceMetadata = (VmaBlockMetadata_Generic*)pFreeSpaceBlock->m_pMetadata;
  12578. // Same block
  12579. if(freeSpaceInfoIndex == srcBlockInfoIndex)
  12580. {
  12581. VMA_ASSERT(dstAllocOffset <= srcAllocOffset);
  12582. // MOVE OPTION 1: Move the allocation inside the same block by decreasing offset.
  12583. VmaSuballocation suballoc = *srcSuballocIt;
  12584. suballoc.offset = dstAllocOffset;
  12585. suballoc.hAllocation->ChangeOffset(dstAllocOffset);
  12586. m_BytesMoved += srcAllocSize;
  12587. ++m_AllocationsMoved;
  12588. VmaSuballocationList::iterator nextSuballocIt = srcSuballocIt;
  12589. ++nextSuballocIt;
  12590. pSrcMetadata->m_Suballocations.erase(srcSuballocIt);
  12591. srcSuballocIt = nextSuballocIt;
  12592. InsertSuballoc(pFreeSpaceMetadata, suballoc);
  12593. move.srcBlockIndex = srcOrigBlockIndex;
  12594. move.dstBlockIndex = freeSpaceOrigBlockIndex;
  12595. move.srcOffset = srcAllocOffset;
  12596. move.dstOffset = dstAllocOffset;
  12597. move.size = srcAllocSize;
  12598. moves.push_back(move);
  12599. }
  12600. // Different block
  12601. else
  12602. {
  12603. // MOVE OPTION 2: Move the allocation to a different block.
  12604. VMA_ASSERT(freeSpaceInfoIndex < srcBlockInfoIndex);
  12605. VmaSuballocation suballoc = *srcSuballocIt;
  12606. suballoc.offset = dstAllocOffset;
  12607. suballoc.hAllocation->ChangeBlockAllocation(m_hAllocator, pFreeSpaceBlock, dstAllocOffset);
  12608. m_BytesMoved += srcAllocSize;
  12609. ++m_AllocationsMoved;
  12610. VmaSuballocationList::iterator nextSuballocIt = srcSuballocIt;
  12611. ++nextSuballocIt;
  12612. pSrcMetadata->m_Suballocations.erase(srcSuballocIt);
  12613. srcSuballocIt = nextSuballocIt;
  12614. InsertSuballoc(pFreeSpaceMetadata, suballoc);
  12615. move.srcBlockIndex = srcOrigBlockIndex;
  12616. move.dstBlockIndex = freeSpaceOrigBlockIndex;
  12617. move.srcOffset = srcAllocOffset;
  12618. move.dstOffset = dstAllocOffset;
  12619. move.size = srcAllocSize;
  12620. moves.push_back(move);
  12621. }
  12622. }
  12623. else
  12624. {
  12625. dstAllocOffset = VmaAlignUp(dstOffset, srcAllocAlignment);
  12626. // If the allocation doesn't fit before the end of dstBlock, forward to next block.
  12627. while(dstBlockInfoIndex < srcBlockInfoIndex &&
  12628. dstAllocOffset + srcAllocSize > dstBlockSize)
  12629. {
  12630. // But before that, register remaining free space at the end of dst block.
  12631. freeSpaceDb.Register(dstBlockInfoIndex, dstOffset, dstBlockSize - dstOffset);
  12632. ++dstBlockInfoIndex;
  12633. dstOrigBlockIndex = m_BlockInfos[dstBlockInfoIndex].origBlockIndex;
  12634. pDstBlock = m_pBlockVector->GetBlock(dstOrigBlockIndex);
  12635. pDstMetadata = (VmaBlockMetadata_Generic*)pDstBlock->m_pMetadata;
  12636. dstBlockSize = pDstMetadata->GetSize();
  12637. dstOffset = 0;
  12638. dstAllocOffset = 0;
  12639. }
  12640. // Same block
  12641. if(dstBlockInfoIndex == srcBlockInfoIndex)
  12642. {
  12643. VMA_ASSERT(dstAllocOffset <= srcAllocOffset);
  12644. const bool overlap = dstAllocOffset + srcAllocSize > srcAllocOffset;
  12645. bool skipOver = overlap;
  12646. if(overlap && m_OverlappingMoveSupported && dstAllocOffset < srcAllocOffset)
  12647. {
  12648. // If destination and source place overlap, skip if it would move it
  12649. // by only < 1/64 of its size.
  12650. skipOver = (srcAllocOffset - dstAllocOffset) * 64 < srcAllocSize;
  12651. }
  12652. if(skipOver)
  12653. {
  12654. freeSpaceDb.Register(dstBlockInfoIndex, dstOffset, srcAllocOffset - dstOffset);
  12655. dstOffset = srcAllocOffset + srcAllocSize;
  12656. ++srcSuballocIt;
  12657. }
  12658. // MOVE OPTION 1: Move the allocation inside the same block by decreasing offset.
  12659. else
  12660. {
  12661. srcSuballocIt->offset = dstAllocOffset;
  12662. srcSuballocIt->hAllocation->ChangeOffset(dstAllocOffset);
  12663. dstOffset = dstAllocOffset + srcAllocSize;
  12664. m_BytesMoved += srcAllocSize;
  12665. ++m_AllocationsMoved;
  12666. ++srcSuballocIt;
  12667. move.srcBlockIndex = srcOrigBlockIndex;
  12668. move.dstBlockIndex = dstOrigBlockIndex;
  12669. move.srcOffset = srcAllocOffset;
  12670. move.dstOffset = dstAllocOffset;
  12671. move.size = srcAllocSize;
  12672. moves.push_back(move);
  12673. }
  12674. }
  12675. // Different block
  12676. else
  12677. {
  12678. // MOVE OPTION 2: Move the allocation to a different block.
  12679. VMA_ASSERT(dstBlockInfoIndex < srcBlockInfoIndex);
  12680. VMA_ASSERT(dstAllocOffset + srcAllocSize <= dstBlockSize);
  12681. VmaSuballocation suballoc = *srcSuballocIt;
  12682. suballoc.offset = dstAllocOffset;
  12683. suballoc.hAllocation->ChangeBlockAllocation(m_hAllocator, pDstBlock, dstAllocOffset);
  12684. dstOffset = dstAllocOffset + srcAllocSize;
  12685. m_BytesMoved += srcAllocSize;
  12686. ++m_AllocationsMoved;
  12687. VmaSuballocationList::iterator nextSuballocIt = srcSuballocIt;
  12688. ++nextSuballocIt;
  12689. pSrcMetadata->m_Suballocations.erase(srcSuballocIt);
  12690. srcSuballocIt = nextSuballocIt;
  12691. pDstMetadata->m_Suballocations.push_back(suballoc);
  12692. move.srcBlockIndex = srcOrigBlockIndex;
  12693. move.dstBlockIndex = dstOrigBlockIndex;
  12694. move.srcOffset = srcAllocOffset;
  12695. move.dstOffset = dstAllocOffset;
  12696. move.size = srcAllocSize;
  12697. moves.push_back(move);
  12698. }
  12699. }
  12700. }
  12701. }
  12702. m_BlockInfos.clear();
  12703. PostprocessMetadata();
  12704. return VK_SUCCESS;
  12705. }
  12706. void VmaDefragmentationAlgorithm_Fast::PreprocessMetadata()
  12707. {
  12708. const size_t blockCount = m_pBlockVector->GetBlockCount();
  12709. for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
  12710. {
  12711. VmaBlockMetadata_Generic* const pMetadata =
  12712. (VmaBlockMetadata_Generic*)m_pBlockVector->GetBlock(blockIndex)->m_pMetadata;
  12713. pMetadata->m_FreeCount = 0;
  12714. pMetadata->m_SumFreeSize = pMetadata->GetSize();
  12715. pMetadata->m_FreeSuballocationsBySize.clear();
  12716. for(VmaSuballocationList::iterator it = pMetadata->m_Suballocations.begin();
  12717. it != pMetadata->m_Suballocations.end(); )
  12718. {
  12719. if(it->type == VMA_SUBALLOCATION_TYPE_FREE)
  12720. {
  12721. VmaSuballocationList::iterator nextIt = it;
  12722. ++nextIt;
  12723. pMetadata->m_Suballocations.erase(it);
  12724. it = nextIt;
  12725. }
  12726. else
  12727. {
  12728. ++it;
  12729. }
  12730. }
  12731. }
  12732. }
  12733. void VmaDefragmentationAlgorithm_Fast::PostprocessMetadata()
  12734. {
  12735. const size_t blockCount = m_pBlockVector->GetBlockCount();
  12736. for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
  12737. {
  12738. VmaBlockMetadata_Generic* const pMetadata =
  12739. (VmaBlockMetadata_Generic*)m_pBlockVector->GetBlock(blockIndex)->m_pMetadata;
  12740. const VkDeviceSize blockSize = pMetadata->GetSize();
  12741. // No allocations in this block - entire area is free.
  12742. if(pMetadata->m_Suballocations.empty())
  12743. {
  12744. pMetadata->m_FreeCount = 1;
  12745. //pMetadata->m_SumFreeSize is already set to blockSize.
  12746. VmaSuballocation suballoc = {
  12747. 0, // offset
  12748. blockSize, // size
  12749. VMA_NULL, // hAllocation
  12750. VMA_SUBALLOCATION_TYPE_FREE };
  12751. pMetadata->m_Suballocations.push_back(suballoc);
  12752. pMetadata->RegisterFreeSuballocation(pMetadata->m_Suballocations.begin());
  12753. }
  12754. // There are some allocations in this block.
  12755. else
  12756. {
  12757. VkDeviceSize offset = 0;
  12758. VmaSuballocationList::iterator it;
  12759. for(it = pMetadata->m_Suballocations.begin();
  12760. it != pMetadata->m_Suballocations.end();
  12761. ++it)
  12762. {
  12763. VMA_ASSERT(it->type != VMA_SUBALLOCATION_TYPE_FREE);
  12764. VMA_ASSERT(it->offset >= offset);
  12765. // Need to insert preceding free space.
  12766. if(it->offset > offset)
  12767. {
  12768. ++pMetadata->m_FreeCount;
  12769. const VkDeviceSize freeSize = it->offset - offset;
  12770. VmaSuballocation suballoc = {
  12771. offset, // offset
  12772. freeSize, // size
  12773. VMA_NULL, // hAllocation
  12774. VMA_SUBALLOCATION_TYPE_FREE };
  12775. VmaSuballocationList::iterator precedingFreeIt = pMetadata->m_Suballocations.insert(it, suballoc);
  12776. if(freeSize >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
  12777. {
  12778. pMetadata->m_FreeSuballocationsBySize.push_back(precedingFreeIt);
  12779. }
  12780. }
  12781. pMetadata->m_SumFreeSize -= it->size;
  12782. offset = it->offset + it->size;
  12783. }
  12784. // Need to insert trailing free space.
  12785. if(offset < blockSize)
  12786. {
  12787. ++pMetadata->m_FreeCount;
  12788. const VkDeviceSize freeSize = blockSize - offset;
  12789. VmaSuballocation suballoc = {
  12790. offset, // offset
  12791. freeSize, // size
  12792. VMA_NULL, // hAllocation
  12793. VMA_SUBALLOCATION_TYPE_FREE };
  12794. VMA_ASSERT(it == pMetadata->m_Suballocations.end());
  12795. VmaSuballocationList::iterator trailingFreeIt = pMetadata->m_Suballocations.insert(it, suballoc);
  12796. if(freeSize > VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
  12797. {
  12798. pMetadata->m_FreeSuballocationsBySize.push_back(trailingFreeIt);
  12799. }
  12800. }
  12801. VMA_SORT(
  12802. pMetadata->m_FreeSuballocationsBySize.begin(),
  12803. pMetadata->m_FreeSuballocationsBySize.end(),
  12804. VmaSuballocationItemSizeLess());
  12805. }
  12806. VMA_HEAVY_ASSERT(pMetadata->Validate());
  12807. }
  12808. }
  12809. void VmaDefragmentationAlgorithm_Fast::InsertSuballoc(VmaBlockMetadata_Generic* pMetadata, const VmaSuballocation& suballoc)
  12810. {
  12811. // TODO: Optimize somehow. Remember iterator instead of searching for it linearly.
  12812. VmaSuballocationList::iterator it = pMetadata->m_Suballocations.begin();
  12813. while(it != pMetadata->m_Suballocations.end())
  12814. {
  12815. if(it->offset < suballoc.offset)
  12816. {
  12817. ++it;
  12818. }
  12819. }
  12820. pMetadata->m_Suballocations.insert(it, suballoc);
  12821. }
  12822. ////////////////////////////////////////////////////////////////////////////////
  12823. // VmaBlockVectorDefragmentationContext
  12824. VmaBlockVectorDefragmentationContext::VmaBlockVectorDefragmentationContext(
  12825. VmaAllocator hAllocator,
  12826. VmaPool hCustomPool,
  12827. VmaBlockVector* pBlockVector,
  12828. uint32_t currFrameIndex) :
  12829. res(VK_SUCCESS),
  12830. mutexLocked(false),
  12831. blockContexts(VmaStlAllocator<VmaBlockDefragmentationContext>(hAllocator->GetAllocationCallbacks())),
  12832. defragmentationMoves(VmaStlAllocator<VmaDefragmentationMove>(hAllocator->GetAllocationCallbacks())),
  12833. defragmentationMovesProcessed(0),
  12834. defragmentationMovesCommitted(0),
  12835. hasDefragmentationPlan(0),
  12836. m_hAllocator(hAllocator),
  12837. m_hCustomPool(hCustomPool),
  12838. m_pBlockVector(pBlockVector),
  12839. m_CurrFrameIndex(currFrameIndex),
  12840. m_pAlgorithm(VMA_NULL),
  12841. m_Allocations(VmaStlAllocator<AllocInfo>(hAllocator->GetAllocationCallbacks())),
  12842. m_AllAllocations(false)
  12843. {
  12844. }
  12845. VmaBlockVectorDefragmentationContext::~VmaBlockVectorDefragmentationContext()
  12846. {
  12847. vma_delete(m_hAllocator, m_pAlgorithm);
  12848. }
  12849. void VmaBlockVectorDefragmentationContext::AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged)
  12850. {
  12851. AllocInfo info = { hAlloc, pChanged };
  12852. m_Allocations.push_back(info);
  12853. }
  12854. void VmaBlockVectorDefragmentationContext::Begin(bool overlappingMoveSupported, VmaDefragmentationFlags flags)
  12855. {
  12856. const bool allAllocations = m_AllAllocations ||
  12857. m_Allocations.size() == m_pBlockVector->CalcAllocationCount();
  12858. /********************************
  12859. HERE IS THE CHOICE OF DEFRAGMENTATION ALGORITHM.
  12860. ********************************/
  12861. /*
  12862. Fast algorithm is supported only when certain criteria are met:
  12863. - VMA_DEBUG_MARGIN is 0.
  12864. - All allocations in this block vector are moveable.
  12865. - There is no possibility of image/buffer granularity conflict.
  12866. - The defragmentation is not incremental
  12867. */
  12868. if(VMA_DEBUG_MARGIN == 0 &&
  12869. allAllocations &&
  12870. !m_pBlockVector->IsBufferImageGranularityConflictPossible() &&
  12871. !(flags & VMA_DEFRAGMENTATION_FLAG_INCREMENTAL))
  12872. {
  12873. m_pAlgorithm = vma_new(m_hAllocator, VmaDefragmentationAlgorithm_Fast)(
  12874. m_hAllocator, m_pBlockVector, m_CurrFrameIndex, overlappingMoveSupported);
  12875. }
  12876. else
  12877. {
  12878. m_pAlgorithm = vma_new(m_hAllocator, VmaDefragmentationAlgorithm_Generic)(
  12879. m_hAllocator, m_pBlockVector, m_CurrFrameIndex, overlappingMoveSupported);
  12880. }
  12881. if(allAllocations)
  12882. {
  12883. m_pAlgorithm->AddAll();
  12884. }
  12885. else
  12886. {
  12887. for(size_t i = 0, count = m_Allocations.size(); i < count; ++i)
  12888. {
  12889. m_pAlgorithm->AddAllocation(m_Allocations[i].hAlloc, m_Allocations[i].pChanged);
  12890. }
  12891. }
  12892. }
  12893. ////////////////////////////////////////////////////////////////////////////////
  12894. // VmaDefragmentationContext
  12895. VmaDefragmentationContext_T::VmaDefragmentationContext_T(
  12896. VmaAllocator hAllocator,
  12897. uint32_t currFrameIndex,
  12898. uint32_t flags,
  12899. VmaDefragmentationStats* pStats) :
  12900. m_hAllocator(hAllocator),
  12901. m_CurrFrameIndex(currFrameIndex),
  12902. m_Flags(flags),
  12903. m_pStats(pStats),
  12904. m_CustomPoolContexts(VmaStlAllocator<VmaBlockVectorDefragmentationContext*>(hAllocator->GetAllocationCallbacks()))
  12905. {
  12906. memset(m_DefaultPoolContexts, 0, sizeof(m_DefaultPoolContexts));
  12907. }
  12908. VmaDefragmentationContext_T::~VmaDefragmentationContext_T()
  12909. {
  12910. for(size_t i = m_CustomPoolContexts.size(); i--; )
  12911. {
  12912. VmaBlockVectorDefragmentationContext* pBlockVectorCtx = m_CustomPoolContexts[i];
  12913. pBlockVectorCtx->GetBlockVector()->DefragmentationEnd(pBlockVectorCtx, m_Flags, m_pStats);
  12914. vma_delete(m_hAllocator, pBlockVectorCtx);
  12915. }
  12916. for(size_t i = m_hAllocator->m_MemProps.memoryTypeCount; i--; )
  12917. {
  12918. VmaBlockVectorDefragmentationContext* pBlockVectorCtx = m_DefaultPoolContexts[i];
  12919. if(pBlockVectorCtx)
  12920. {
  12921. pBlockVectorCtx->GetBlockVector()->DefragmentationEnd(pBlockVectorCtx, m_Flags, m_pStats);
  12922. vma_delete(m_hAllocator, pBlockVectorCtx);
  12923. }
  12924. }
  12925. }
  12926. void VmaDefragmentationContext_T::AddPools(uint32_t poolCount, const VmaPool* pPools)
  12927. {
  12928. for(uint32_t poolIndex = 0; poolIndex < poolCount; ++poolIndex)
  12929. {
  12930. VmaPool pool = pPools[poolIndex];
  12931. VMA_ASSERT(pool);
  12932. // Pools with algorithm other than default are not defragmented.
  12933. if(pool->m_BlockVector.GetAlgorithm() == 0)
  12934. {
  12935. VmaBlockVectorDefragmentationContext* pBlockVectorDefragCtx = VMA_NULL;
  12936. for(size_t i = m_CustomPoolContexts.size(); i--; )
  12937. {
  12938. if(m_CustomPoolContexts[i]->GetCustomPool() == pool)
  12939. {
  12940. pBlockVectorDefragCtx = m_CustomPoolContexts[i];
  12941. break;
  12942. }
  12943. }
  12944. if(!pBlockVectorDefragCtx)
  12945. {
  12946. pBlockVectorDefragCtx = vma_new(m_hAllocator, VmaBlockVectorDefragmentationContext)(
  12947. m_hAllocator,
  12948. pool,
  12949. &pool->m_BlockVector,
  12950. m_CurrFrameIndex);
  12951. m_CustomPoolContexts.push_back(pBlockVectorDefragCtx);
  12952. }
  12953. pBlockVectorDefragCtx->AddAll();
  12954. }
  12955. }
  12956. }
  12957. void VmaDefragmentationContext_T::AddAllocations(
  12958. uint32_t allocationCount,
  12959. const VmaAllocation* pAllocations,
  12960. VkBool32* pAllocationsChanged)
  12961. {
  12962. // Dispatch pAllocations among defragmentators. Create them when necessary.
  12963. for(uint32_t allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  12964. {
  12965. const VmaAllocation hAlloc = pAllocations[allocIndex];
  12966. VMA_ASSERT(hAlloc);
  12967. // DedicatedAlloc cannot be defragmented.
  12968. if((hAlloc->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK) &&
  12969. // Lost allocation cannot be defragmented.
  12970. (hAlloc->GetLastUseFrameIndex() != VMA_FRAME_INDEX_LOST))
  12971. {
  12972. VmaBlockVectorDefragmentationContext* pBlockVectorDefragCtx = VMA_NULL;
  12973. const VmaPool hAllocPool = hAlloc->GetBlock()->GetParentPool();
  12974. // This allocation belongs to custom pool.
  12975. if(hAllocPool != VK_NULL_HANDLE)
  12976. {
  12977. // Pools with algorithm other than default are not defragmented.
  12978. if(hAllocPool->m_BlockVector.GetAlgorithm() == 0)
  12979. {
  12980. for(size_t i = m_CustomPoolContexts.size(); i--; )
  12981. {
  12982. if(m_CustomPoolContexts[i]->GetCustomPool() == hAllocPool)
  12983. {
  12984. pBlockVectorDefragCtx = m_CustomPoolContexts[i];
  12985. break;
  12986. }
  12987. }
  12988. if(!pBlockVectorDefragCtx)
  12989. {
  12990. pBlockVectorDefragCtx = vma_new(m_hAllocator, VmaBlockVectorDefragmentationContext)(
  12991. m_hAllocator,
  12992. hAllocPool,
  12993. &hAllocPool->m_BlockVector,
  12994. m_CurrFrameIndex);
  12995. m_CustomPoolContexts.push_back(pBlockVectorDefragCtx);
  12996. }
  12997. }
  12998. }
  12999. // This allocation belongs to default pool.
  13000. else
  13001. {
  13002. const uint32_t memTypeIndex = hAlloc->GetMemoryTypeIndex();
  13003. pBlockVectorDefragCtx = m_DefaultPoolContexts[memTypeIndex];
  13004. if(!pBlockVectorDefragCtx)
  13005. {
  13006. pBlockVectorDefragCtx = vma_new(m_hAllocator, VmaBlockVectorDefragmentationContext)(
  13007. m_hAllocator,
  13008. VMA_NULL, // hCustomPool
  13009. m_hAllocator->m_pBlockVectors[memTypeIndex],
  13010. m_CurrFrameIndex);
  13011. m_DefaultPoolContexts[memTypeIndex] = pBlockVectorDefragCtx;
  13012. }
  13013. }
  13014. if(pBlockVectorDefragCtx)
  13015. {
  13016. VkBool32* const pChanged = (pAllocationsChanged != VMA_NULL) ?
  13017. &pAllocationsChanged[allocIndex] : VMA_NULL;
  13018. pBlockVectorDefragCtx->AddAllocation(hAlloc, pChanged);
  13019. }
  13020. }
  13021. }
  13022. }
  13023. VkResult VmaDefragmentationContext_T::Defragment(
  13024. VkDeviceSize maxCpuBytesToMove, uint32_t maxCpuAllocationsToMove,
  13025. VkDeviceSize maxGpuBytesToMove, uint32_t maxGpuAllocationsToMove,
  13026. VkCommandBuffer commandBuffer, VmaDefragmentationStats* pStats, VmaDefragmentationFlags flags)
  13027. {
  13028. if(pStats)
  13029. {
  13030. memset(pStats, 0, sizeof(VmaDefragmentationStats));
  13031. }
  13032. if(flags & VMA_DEFRAGMENTATION_FLAG_INCREMENTAL)
  13033. {
  13034. // For incremental defragmetnations, we just earmark how much we can move
  13035. // The real meat is in the defragmentation steps
  13036. m_MaxCpuBytesToMove = maxCpuBytesToMove;
  13037. m_MaxCpuAllocationsToMove = maxCpuAllocationsToMove;
  13038. m_MaxGpuBytesToMove = maxGpuBytesToMove;
  13039. m_MaxGpuAllocationsToMove = maxGpuAllocationsToMove;
  13040. if(m_MaxCpuBytesToMove == 0 && m_MaxCpuAllocationsToMove == 0 &&
  13041. m_MaxGpuBytesToMove == 0 && m_MaxGpuAllocationsToMove == 0)
  13042. return VK_SUCCESS;
  13043. return VK_NOT_READY;
  13044. }
  13045. if(commandBuffer == VK_NULL_HANDLE)
  13046. {
  13047. maxGpuBytesToMove = 0;
  13048. maxGpuAllocationsToMove = 0;
  13049. }
  13050. VkResult res = VK_SUCCESS;
  13051. // Process default pools.
  13052. for(uint32_t memTypeIndex = 0;
  13053. memTypeIndex < m_hAllocator->GetMemoryTypeCount() && res >= VK_SUCCESS;
  13054. ++memTypeIndex)
  13055. {
  13056. VmaBlockVectorDefragmentationContext* pBlockVectorCtx = m_DefaultPoolContexts[memTypeIndex];
  13057. if(pBlockVectorCtx)
  13058. {
  13059. VMA_ASSERT(pBlockVectorCtx->GetBlockVector());
  13060. pBlockVectorCtx->GetBlockVector()->Defragment(
  13061. pBlockVectorCtx,
  13062. pStats, flags,
  13063. maxCpuBytesToMove, maxCpuAllocationsToMove,
  13064. maxGpuBytesToMove, maxGpuAllocationsToMove,
  13065. commandBuffer);
  13066. if(pBlockVectorCtx->res != VK_SUCCESS)
  13067. {
  13068. res = pBlockVectorCtx->res;
  13069. }
  13070. }
  13071. }
  13072. // Process custom pools.
  13073. for(size_t customCtxIndex = 0, customCtxCount = m_CustomPoolContexts.size();
  13074. customCtxIndex < customCtxCount && res >= VK_SUCCESS;
  13075. ++customCtxIndex)
  13076. {
  13077. VmaBlockVectorDefragmentationContext* pBlockVectorCtx = m_CustomPoolContexts[customCtxIndex];
  13078. VMA_ASSERT(pBlockVectorCtx && pBlockVectorCtx->GetBlockVector());
  13079. pBlockVectorCtx->GetBlockVector()->Defragment(
  13080. pBlockVectorCtx,
  13081. pStats, flags,
  13082. maxCpuBytesToMove, maxCpuAllocationsToMove,
  13083. maxGpuBytesToMove, maxGpuAllocationsToMove,
  13084. commandBuffer);
  13085. if(pBlockVectorCtx->res != VK_SUCCESS)
  13086. {
  13087. res = pBlockVectorCtx->res;
  13088. }
  13089. }
  13090. return res;
  13091. }
  13092. VkResult VmaDefragmentationContext_T::DefragmentPassBegin(VmaDefragmentationPassInfo* pInfo)
  13093. {
  13094. VmaDefragmentationPassMoveInfo* pCurrentMove = pInfo->pMoves;
  13095. uint32_t movesLeft = pInfo->moveCount;
  13096. // Process default pools.
  13097. for(uint32_t memTypeIndex = 0;
  13098. memTypeIndex < m_hAllocator->GetMemoryTypeCount();
  13099. ++memTypeIndex)
  13100. {
  13101. VmaBlockVectorDefragmentationContext *pBlockVectorCtx = m_DefaultPoolContexts[memTypeIndex];
  13102. if(pBlockVectorCtx)
  13103. {
  13104. VMA_ASSERT(pBlockVectorCtx->GetBlockVector());
  13105. if(!pBlockVectorCtx->hasDefragmentationPlan)
  13106. {
  13107. pBlockVectorCtx->GetBlockVector()->Defragment(
  13108. pBlockVectorCtx,
  13109. m_pStats, m_Flags,
  13110. m_MaxCpuBytesToMove, m_MaxCpuAllocationsToMove,
  13111. m_MaxGpuBytesToMove, m_MaxGpuAllocationsToMove,
  13112. VK_NULL_HANDLE);
  13113. if(pBlockVectorCtx->res < VK_SUCCESS)
  13114. continue;
  13115. pBlockVectorCtx->hasDefragmentationPlan = true;
  13116. }
  13117. const uint32_t processed = pBlockVectorCtx->GetBlockVector()->ProcessDefragmentations(
  13118. pBlockVectorCtx,
  13119. pCurrentMove, movesLeft);
  13120. movesLeft -= processed;
  13121. pCurrentMove += processed;
  13122. }
  13123. }
  13124. // Process custom pools.
  13125. for(size_t customCtxIndex = 0, customCtxCount = m_CustomPoolContexts.size();
  13126. customCtxIndex < customCtxCount;
  13127. ++customCtxIndex)
  13128. {
  13129. VmaBlockVectorDefragmentationContext *pBlockVectorCtx = m_CustomPoolContexts[customCtxIndex];
  13130. VMA_ASSERT(pBlockVectorCtx && pBlockVectorCtx->GetBlockVector());
  13131. if(!pBlockVectorCtx->hasDefragmentationPlan)
  13132. {
  13133. pBlockVectorCtx->GetBlockVector()->Defragment(
  13134. pBlockVectorCtx,
  13135. m_pStats, m_Flags,
  13136. m_MaxCpuBytesToMove, m_MaxCpuAllocationsToMove,
  13137. m_MaxGpuBytesToMove, m_MaxGpuAllocationsToMove,
  13138. VK_NULL_HANDLE);
  13139. if(pBlockVectorCtx->res < VK_SUCCESS)
  13140. continue;
  13141. pBlockVectorCtx->hasDefragmentationPlan = true;
  13142. }
  13143. const uint32_t processed = pBlockVectorCtx->GetBlockVector()->ProcessDefragmentations(
  13144. pBlockVectorCtx,
  13145. pCurrentMove, movesLeft);
  13146. movesLeft -= processed;
  13147. pCurrentMove += processed;
  13148. }
  13149. pInfo->moveCount = pInfo->moveCount - movesLeft;
  13150. return VK_SUCCESS;
  13151. }
  13152. VkResult VmaDefragmentationContext_T::DefragmentPassEnd()
  13153. {
  13154. VkResult res = VK_SUCCESS;
  13155. // Process default pools.
  13156. for(uint32_t memTypeIndex = 0;
  13157. memTypeIndex < m_hAllocator->GetMemoryTypeCount();
  13158. ++memTypeIndex)
  13159. {
  13160. VmaBlockVectorDefragmentationContext *pBlockVectorCtx = m_DefaultPoolContexts[memTypeIndex];
  13161. if(pBlockVectorCtx)
  13162. {
  13163. VMA_ASSERT(pBlockVectorCtx->GetBlockVector());
  13164. if(!pBlockVectorCtx->hasDefragmentationPlan)
  13165. {
  13166. res = VK_NOT_READY;
  13167. continue;
  13168. }
  13169. pBlockVectorCtx->GetBlockVector()->CommitDefragmentations(
  13170. pBlockVectorCtx, m_pStats);
  13171. if(pBlockVectorCtx->defragmentationMoves.size() != pBlockVectorCtx->defragmentationMovesCommitted)
  13172. res = VK_NOT_READY;
  13173. }
  13174. }
  13175. // Process custom pools.
  13176. for(size_t customCtxIndex = 0, customCtxCount = m_CustomPoolContexts.size();
  13177. customCtxIndex < customCtxCount;
  13178. ++customCtxIndex)
  13179. {
  13180. VmaBlockVectorDefragmentationContext *pBlockVectorCtx = m_CustomPoolContexts[customCtxIndex];
  13181. VMA_ASSERT(pBlockVectorCtx && pBlockVectorCtx->GetBlockVector());
  13182. if(!pBlockVectorCtx->hasDefragmentationPlan)
  13183. {
  13184. res = VK_NOT_READY;
  13185. continue;
  13186. }
  13187. pBlockVectorCtx->GetBlockVector()->CommitDefragmentations(
  13188. pBlockVectorCtx, m_pStats);
  13189. if(pBlockVectorCtx->defragmentationMoves.size() != pBlockVectorCtx->defragmentationMovesCommitted)
  13190. res = VK_NOT_READY;
  13191. }
  13192. return res;
  13193. }
  13194. ////////////////////////////////////////////////////////////////////////////////
  13195. // VmaRecorder
  13196. #if VMA_RECORDING_ENABLED
  13197. VmaRecorder::VmaRecorder() :
  13198. m_UseMutex(true),
  13199. m_Flags(0),
  13200. m_File(VMA_NULL),
  13201. m_RecordingStartTime(std::chrono::high_resolution_clock::now())
  13202. {
  13203. }
  13204. VkResult VmaRecorder::Init(const VmaRecordSettings& settings, bool useMutex)
  13205. {
  13206. m_UseMutex = useMutex;
  13207. m_Flags = settings.flags;
  13208. #if defined(_WIN32)
  13209. // Open file for writing.
  13210. errno_t err = fopen_s(&m_File, settings.pFilePath, "wb");
  13211. if(err != 0)
  13212. {
  13213. return VK_ERROR_INITIALIZATION_FAILED;
  13214. }
  13215. #else
  13216. // Open file for writing.
  13217. m_File = fopen(settings.pFilePath, "wb");
  13218. if(m_File == 0)
  13219. {
  13220. return VK_ERROR_INITIALIZATION_FAILED;
  13221. }
  13222. #endif
  13223. // Write header.
  13224. fprintf(m_File, "%s\n", "Vulkan Memory Allocator,Calls recording");
  13225. fprintf(m_File, "%s\n", "1,8");
  13226. return VK_SUCCESS;
  13227. }
  13228. VmaRecorder::~VmaRecorder()
  13229. {
  13230. if(m_File != VMA_NULL)
  13231. {
  13232. fclose(m_File);
  13233. }
  13234. }
  13235. void VmaRecorder::RecordCreateAllocator(uint32_t frameIndex)
  13236. {
  13237. CallParams callParams;
  13238. GetBasicParams(callParams);
  13239. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13240. fprintf(m_File, "%u,%.3f,%u,vmaCreateAllocator\n", callParams.threadId, callParams.time, frameIndex);
  13241. Flush();
  13242. }
  13243. void VmaRecorder::RecordDestroyAllocator(uint32_t frameIndex)
  13244. {
  13245. CallParams callParams;
  13246. GetBasicParams(callParams);
  13247. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13248. fprintf(m_File, "%u,%.3f,%u,vmaDestroyAllocator\n", callParams.threadId, callParams.time, frameIndex);
  13249. Flush();
  13250. }
  13251. void VmaRecorder::RecordCreatePool(uint32_t frameIndex, const VmaPoolCreateInfo& createInfo, VmaPool pool)
  13252. {
  13253. CallParams callParams;
  13254. GetBasicParams(callParams);
  13255. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13256. fprintf(m_File, "%u,%.3f,%u,vmaCreatePool,%u,%u,%llu,%llu,%llu,%u,%p\n", callParams.threadId, callParams.time, frameIndex,
  13257. createInfo.memoryTypeIndex,
  13258. createInfo.flags,
  13259. createInfo.blockSize,
  13260. (uint64_t)createInfo.minBlockCount,
  13261. (uint64_t)createInfo.maxBlockCount,
  13262. createInfo.frameInUseCount,
  13263. pool);
  13264. Flush();
  13265. }
  13266. void VmaRecorder::RecordDestroyPool(uint32_t frameIndex, VmaPool pool)
  13267. {
  13268. CallParams callParams;
  13269. GetBasicParams(callParams);
  13270. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13271. fprintf(m_File, "%u,%.3f,%u,vmaDestroyPool,%p\n", callParams.threadId, callParams.time, frameIndex,
  13272. pool);
  13273. Flush();
  13274. }
  13275. void VmaRecorder::RecordAllocateMemory(uint32_t frameIndex,
  13276. const VkMemoryRequirements& vkMemReq,
  13277. const VmaAllocationCreateInfo& createInfo,
  13278. VmaAllocation allocation)
  13279. {
  13280. CallParams callParams;
  13281. GetBasicParams(callParams);
  13282. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13283. UserDataString userDataStr(createInfo.flags, createInfo.pUserData);
  13284. fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemory,%llu,%llu,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
  13285. vkMemReq.size,
  13286. vkMemReq.alignment,
  13287. vkMemReq.memoryTypeBits,
  13288. createInfo.flags,
  13289. createInfo.usage,
  13290. createInfo.requiredFlags,
  13291. createInfo.preferredFlags,
  13292. createInfo.memoryTypeBits,
  13293. createInfo.pool,
  13294. allocation,
  13295. userDataStr.GetString());
  13296. Flush();
  13297. }
  13298. void VmaRecorder::RecordAllocateMemoryPages(uint32_t frameIndex,
  13299. const VkMemoryRequirements& vkMemReq,
  13300. const VmaAllocationCreateInfo& createInfo,
  13301. uint64_t allocationCount,
  13302. const VmaAllocation* pAllocations)
  13303. {
  13304. CallParams callParams;
  13305. GetBasicParams(callParams);
  13306. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13307. UserDataString userDataStr(createInfo.flags, createInfo.pUserData);
  13308. fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemoryPages,%llu,%llu,%u,%u,%u,%u,%u,%u,%p,", callParams.threadId, callParams.time, frameIndex,
  13309. vkMemReq.size,
  13310. vkMemReq.alignment,
  13311. vkMemReq.memoryTypeBits,
  13312. createInfo.flags,
  13313. createInfo.usage,
  13314. createInfo.requiredFlags,
  13315. createInfo.preferredFlags,
  13316. createInfo.memoryTypeBits,
  13317. createInfo.pool);
  13318. PrintPointerList(allocationCount, pAllocations);
  13319. fprintf(m_File, ",%s\n", userDataStr.GetString());
  13320. Flush();
  13321. }
  13322. void VmaRecorder::RecordAllocateMemoryForBuffer(uint32_t frameIndex,
  13323. const VkMemoryRequirements& vkMemReq,
  13324. bool requiresDedicatedAllocation,
  13325. bool prefersDedicatedAllocation,
  13326. const VmaAllocationCreateInfo& createInfo,
  13327. VmaAllocation allocation)
  13328. {
  13329. CallParams callParams;
  13330. GetBasicParams(callParams);
  13331. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13332. UserDataString userDataStr(createInfo.flags, createInfo.pUserData);
  13333. fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemoryForBuffer,%llu,%llu,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
  13334. vkMemReq.size,
  13335. vkMemReq.alignment,
  13336. vkMemReq.memoryTypeBits,
  13337. requiresDedicatedAllocation ? 1 : 0,
  13338. prefersDedicatedAllocation ? 1 : 0,
  13339. createInfo.flags,
  13340. createInfo.usage,
  13341. createInfo.requiredFlags,
  13342. createInfo.preferredFlags,
  13343. createInfo.memoryTypeBits,
  13344. createInfo.pool,
  13345. allocation,
  13346. userDataStr.GetString());
  13347. Flush();
  13348. }
  13349. void VmaRecorder::RecordAllocateMemoryForImage(uint32_t frameIndex,
  13350. const VkMemoryRequirements& vkMemReq,
  13351. bool requiresDedicatedAllocation,
  13352. bool prefersDedicatedAllocation,
  13353. const VmaAllocationCreateInfo& createInfo,
  13354. VmaAllocation allocation)
  13355. {
  13356. CallParams callParams;
  13357. GetBasicParams(callParams);
  13358. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13359. UserDataString userDataStr(createInfo.flags, createInfo.pUserData);
  13360. fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemoryForImage,%llu,%llu,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
  13361. vkMemReq.size,
  13362. vkMemReq.alignment,
  13363. vkMemReq.memoryTypeBits,
  13364. requiresDedicatedAllocation ? 1 : 0,
  13365. prefersDedicatedAllocation ? 1 : 0,
  13366. createInfo.flags,
  13367. createInfo.usage,
  13368. createInfo.requiredFlags,
  13369. createInfo.preferredFlags,
  13370. createInfo.memoryTypeBits,
  13371. createInfo.pool,
  13372. allocation,
  13373. userDataStr.GetString());
  13374. Flush();
  13375. }
  13376. void VmaRecorder::RecordFreeMemory(uint32_t frameIndex,
  13377. VmaAllocation allocation)
  13378. {
  13379. CallParams callParams;
  13380. GetBasicParams(callParams);
  13381. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13382. fprintf(m_File, "%u,%.3f,%u,vmaFreeMemory,%p\n", callParams.threadId, callParams.time, frameIndex,
  13383. allocation);
  13384. Flush();
  13385. }
  13386. void VmaRecorder::RecordFreeMemoryPages(uint32_t frameIndex,
  13387. uint64_t allocationCount,
  13388. const VmaAllocation* pAllocations)
  13389. {
  13390. CallParams callParams;
  13391. GetBasicParams(callParams);
  13392. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13393. fprintf(m_File, "%u,%.3f,%u,vmaFreeMemoryPages,", callParams.threadId, callParams.time, frameIndex);
  13394. PrintPointerList(allocationCount, pAllocations);
  13395. fprintf(m_File, "\n");
  13396. Flush();
  13397. }
  13398. void VmaRecorder::RecordSetAllocationUserData(uint32_t frameIndex,
  13399. VmaAllocation allocation,
  13400. const void* pUserData)
  13401. {
  13402. CallParams callParams;
  13403. GetBasicParams(callParams);
  13404. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13405. UserDataString userDataStr(
  13406. allocation->IsUserDataString() ? VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT : 0,
  13407. pUserData);
  13408. fprintf(m_File, "%u,%.3f,%u,vmaSetAllocationUserData,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
  13409. allocation,
  13410. userDataStr.GetString());
  13411. Flush();
  13412. }
  13413. void VmaRecorder::RecordCreateLostAllocation(uint32_t frameIndex,
  13414. VmaAllocation allocation)
  13415. {
  13416. CallParams callParams;
  13417. GetBasicParams(callParams);
  13418. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13419. fprintf(m_File, "%u,%.3f,%u,vmaCreateLostAllocation,%p\n", callParams.threadId, callParams.time, frameIndex,
  13420. allocation);
  13421. Flush();
  13422. }
  13423. void VmaRecorder::RecordMapMemory(uint32_t frameIndex,
  13424. VmaAllocation allocation)
  13425. {
  13426. CallParams callParams;
  13427. GetBasicParams(callParams);
  13428. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13429. fprintf(m_File, "%u,%.3f,%u,vmaMapMemory,%p\n", callParams.threadId, callParams.time, frameIndex,
  13430. allocation);
  13431. Flush();
  13432. }
  13433. void VmaRecorder::RecordUnmapMemory(uint32_t frameIndex,
  13434. VmaAllocation allocation)
  13435. {
  13436. CallParams callParams;
  13437. GetBasicParams(callParams);
  13438. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13439. fprintf(m_File, "%u,%.3f,%u,vmaUnmapMemory,%p\n", callParams.threadId, callParams.time, frameIndex,
  13440. allocation);
  13441. Flush();
  13442. }
  13443. void VmaRecorder::RecordFlushAllocation(uint32_t frameIndex,
  13444. VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size)
  13445. {
  13446. CallParams callParams;
  13447. GetBasicParams(callParams);
  13448. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13449. fprintf(m_File, "%u,%.3f,%u,vmaFlushAllocation,%p,%llu,%llu\n", callParams.threadId, callParams.time, frameIndex,
  13450. allocation,
  13451. offset,
  13452. size);
  13453. Flush();
  13454. }
  13455. void VmaRecorder::RecordInvalidateAllocation(uint32_t frameIndex,
  13456. VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size)
  13457. {
  13458. CallParams callParams;
  13459. GetBasicParams(callParams);
  13460. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13461. fprintf(m_File, "%u,%.3f,%u,vmaInvalidateAllocation,%p,%llu,%llu\n", callParams.threadId, callParams.time, frameIndex,
  13462. allocation,
  13463. offset,
  13464. size);
  13465. Flush();
  13466. }
  13467. void VmaRecorder::RecordCreateBuffer(uint32_t frameIndex,
  13468. const VkBufferCreateInfo& bufCreateInfo,
  13469. const VmaAllocationCreateInfo& allocCreateInfo,
  13470. VmaAllocation allocation)
  13471. {
  13472. CallParams callParams;
  13473. GetBasicParams(callParams);
  13474. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13475. UserDataString userDataStr(allocCreateInfo.flags, allocCreateInfo.pUserData);
  13476. fprintf(m_File, "%u,%.3f,%u,vmaCreateBuffer,%u,%llu,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
  13477. bufCreateInfo.flags,
  13478. bufCreateInfo.size,
  13479. bufCreateInfo.usage,
  13480. bufCreateInfo.sharingMode,
  13481. allocCreateInfo.flags,
  13482. allocCreateInfo.usage,
  13483. allocCreateInfo.requiredFlags,
  13484. allocCreateInfo.preferredFlags,
  13485. allocCreateInfo.memoryTypeBits,
  13486. allocCreateInfo.pool,
  13487. allocation,
  13488. userDataStr.GetString());
  13489. Flush();
  13490. }
  13491. void VmaRecorder::RecordCreateImage(uint32_t frameIndex,
  13492. const VkImageCreateInfo& imageCreateInfo,
  13493. const VmaAllocationCreateInfo& allocCreateInfo,
  13494. VmaAllocation allocation)
  13495. {
  13496. CallParams callParams;
  13497. GetBasicParams(callParams);
  13498. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13499. UserDataString userDataStr(allocCreateInfo.flags, allocCreateInfo.pUserData);
  13500. fprintf(m_File, "%u,%.3f,%u,vmaCreateImage,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
  13501. imageCreateInfo.flags,
  13502. imageCreateInfo.imageType,
  13503. imageCreateInfo.format,
  13504. imageCreateInfo.extent.width,
  13505. imageCreateInfo.extent.height,
  13506. imageCreateInfo.extent.depth,
  13507. imageCreateInfo.mipLevels,
  13508. imageCreateInfo.arrayLayers,
  13509. imageCreateInfo.samples,
  13510. imageCreateInfo.tiling,
  13511. imageCreateInfo.usage,
  13512. imageCreateInfo.sharingMode,
  13513. imageCreateInfo.initialLayout,
  13514. allocCreateInfo.flags,
  13515. allocCreateInfo.usage,
  13516. allocCreateInfo.requiredFlags,
  13517. allocCreateInfo.preferredFlags,
  13518. allocCreateInfo.memoryTypeBits,
  13519. allocCreateInfo.pool,
  13520. allocation,
  13521. userDataStr.GetString());
  13522. Flush();
  13523. }
  13524. void VmaRecorder::RecordDestroyBuffer(uint32_t frameIndex,
  13525. VmaAllocation allocation)
  13526. {
  13527. CallParams callParams;
  13528. GetBasicParams(callParams);
  13529. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13530. fprintf(m_File, "%u,%.3f,%u,vmaDestroyBuffer,%p\n", callParams.threadId, callParams.time, frameIndex,
  13531. allocation);
  13532. Flush();
  13533. }
  13534. void VmaRecorder::RecordDestroyImage(uint32_t frameIndex,
  13535. VmaAllocation allocation)
  13536. {
  13537. CallParams callParams;
  13538. GetBasicParams(callParams);
  13539. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13540. fprintf(m_File, "%u,%.3f,%u,vmaDestroyImage,%p\n", callParams.threadId, callParams.time, frameIndex,
  13541. allocation);
  13542. Flush();
  13543. }
  13544. void VmaRecorder::RecordTouchAllocation(uint32_t frameIndex,
  13545. VmaAllocation allocation)
  13546. {
  13547. CallParams callParams;
  13548. GetBasicParams(callParams);
  13549. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13550. fprintf(m_File, "%u,%.3f,%u,vmaTouchAllocation,%p\n", callParams.threadId, callParams.time, frameIndex,
  13551. allocation);
  13552. Flush();
  13553. }
  13554. void VmaRecorder::RecordGetAllocationInfo(uint32_t frameIndex,
  13555. VmaAllocation allocation)
  13556. {
  13557. CallParams callParams;
  13558. GetBasicParams(callParams);
  13559. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13560. fprintf(m_File, "%u,%.3f,%u,vmaGetAllocationInfo,%p\n", callParams.threadId, callParams.time, frameIndex,
  13561. allocation);
  13562. Flush();
  13563. }
  13564. void VmaRecorder::RecordMakePoolAllocationsLost(uint32_t frameIndex,
  13565. VmaPool pool)
  13566. {
  13567. CallParams callParams;
  13568. GetBasicParams(callParams);
  13569. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13570. fprintf(m_File, "%u,%.3f,%u,vmaMakePoolAllocationsLost,%p\n", callParams.threadId, callParams.time, frameIndex,
  13571. pool);
  13572. Flush();
  13573. }
  13574. void VmaRecorder::RecordDefragmentationBegin(uint32_t frameIndex,
  13575. const VmaDefragmentationInfo2& info,
  13576. VmaDefragmentationContext ctx)
  13577. {
  13578. CallParams callParams;
  13579. GetBasicParams(callParams);
  13580. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13581. fprintf(m_File, "%u,%.3f,%u,vmaDefragmentationBegin,%u,", callParams.threadId, callParams.time, frameIndex,
  13582. info.flags);
  13583. PrintPointerList(info.allocationCount, info.pAllocations);
  13584. fprintf(m_File, ",");
  13585. PrintPointerList(info.poolCount, info.pPools);
  13586. fprintf(m_File, ",%llu,%u,%llu,%u,%p,%p\n",
  13587. info.maxCpuBytesToMove,
  13588. info.maxCpuAllocationsToMove,
  13589. info.maxGpuBytesToMove,
  13590. info.maxGpuAllocationsToMove,
  13591. info.commandBuffer,
  13592. ctx);
  13593. Flush();
  13594. }
  13595. void VmaRecorder::RecordDefragmentationEnd(uint32_t frameIndex,
  13596. VmaDefragmentationContext ctx)
  13597. {
  13598. CallParams callParams;
  13599. GetBasicParams(callParams);
  13600. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13601. fprintf(m_File, "%u,%.3f,%u,vmaDefragmentationEnd,%p\n", callParams.threadId, callParams.time, frameIndex,
  13602. ctx);
  13603. Flush();
  13604. }
  13605. void VmaRecorder::RecordSetPoolName(uint32_t frameIndex,
  13606. VmaPool pool,
  13607. const char* name)
  13608. {
  13609. CallParams callParams;
  13610. GetBasicParams(callParams);
  13611. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  13612. fprintf(m_File, "%u,%.3f,%u,vmaSetPoolName,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
  13613. pool, name != VMA_NULL ? name : "");
  13614. Flush();
  13615. }
  13616. VmaRecorder::UserDataString::UserDataString(VmaAllocationCreateFlags allocFlags, const void* pUserData)
  13617. {
  13618. if(pUserData != VMA_NULL)
  13619. {
  13620. if((allocFlags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0)
  13621. {
  13622. m_Str = (const char*)pUserData;
  13623. }
  13624. else
  13625. {
  13626. // If VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT is not specified, convert the string's memory address to a string and store it.
  13627. snprintf(m_PtrStr, 17, "%p", pUserData);
  13628. m_Str = m_PtrStr;
  13629. }
  13630. }
  13631. else
  13632. {
  13633. m_Str = "";
  13634. }
  13635. }
  13636. void VmaRecorder::WriteConfiguration(
  13637. const VkPhysicalDeviceProperties& devProps,
  13638. const VkPhysicalDeviceMemoryProperties& memProps,
  13639. uint32_t vulkanApiVersion,
  13640. bool dedicatedAllocationExtensionEnabled,
  13641. bool bindMemory2ExtensionEnabled,
  13642. bool memoryBudgetExtensionEnabled,
  13643. bool deviceCoherentMemoryExtensionEnabled)
  13644. {
  13645. fprintf(m_File, "Config,Begin\n");
  13646. fprintf(m_File, "VulkanApiVersion,%u,%u\n", VK_VERSION_MAJOR(vulkanApiVersion), VK_VERSION_MINOR(vulkanApiVersion));
  13647. fprintf(m_File, "PhysicalDevice,apiVersion,%u\n", devProps.apiVersion);
  13648. fprintf(m_File, "PhysicalDevice,driverVersion,%u\n", devProps.driverVersion);
  13649. fprintf(m_File, "PhysicalDevice,vendorID,%u\n", devProps.vendorID);
  13650. fprintf(m_File, "PhysicalDevice,deviceID,%u\n", devProps.deviceID);
  13651. fprintf(m_File, "PhysicalDevice,deviceType,%u\n", devProps.deviceType);
  13652. fprintf(m_File, "PhysicalDevice,deviceName,%s\n", devProps.deviceName);
  13653. fprintf(m_File, "PhysicalDeviceLimits,maxMemoryAllocationCount,%u\n", devProps.limits.maxMemoryAllocationCount);
  13654. fprintf(m_File, "PhysicalDeviceLimits,bufferImageGranularity,%llu\n", devProps.limits.bufferImageGranularity);
  13655. fprintf(m_File, "PhysicalDeviceLimits,nonCoherentAtomSize,%llu\n", devProps.limits.nonCoherentAtomSize);
  13656. fprintf(m_File, "PhysicalDeviceMemory,HeapCount,%u\n", memProps.memoryHeapCount);
  13657. for(uint32_t i = 0; i < memProps.memoryHeapCount; ++i)
  13658. {
  13659. fprintf(m_File, "PhysicalDeviceMemory,Heap,%u,size,%llu\n", i, memProps.memoryHeaps[i].size);
  13660. fprintf(m_File, "PhysicalDeviceMemory,Heap,%u,flags,%u\n", i, memProps.memoryHeaps[i].flags);
  13661. }
  13662. fprintf(m_File, "PhysicalDeviceMemory,TypeCount,%u\n", memProps.memoryTypeCount);
  13663. for(uint32_t i = 0; i < memProps.memoryTypeCount; ++i)
  13664. {
  13665. fprintf(m_File, "PhysicalDeviceMemory,Type,%u,heapIndex,%u\n", i, memProps.memoryTypes[i].heapIndex);
  13666. fprintf(m_File, "PhysicalDeviceMemory,Type,%u,propertyFlags,%u\n", i, memProps.memoryTypes[i].propertyFlags);
  13667. }
  13668. fprintf(m_File, "Extension,VK_KHR_dedicated_allocation,%u\n", dedicatedAllocationExtensionEnabled ? 1 : 0);
  13669. fprintf(m_File, "Extension,VK_KHR_bind_memory2,%u\n", bindMemory2ExtensionEnabled ? 1 : 0);
  13670. fprintf(m_File, "Extension,VK_EXT_memory_budget,%u\n", memoryBudgetExtensionEnabled ? 1 : 0);
  13671. fprintf(m_File, "Extension,VK_AMD_device_coherent_memory,%u\n", deviceCoherentMemoryExtensionEnabled ? 1 : 0);
  13672. fprintf(m_File, "Macro,VMA_DEBUG_ALWAYS_DEDICATED_MEMORY,%u\n", VMA_DEBUG_ALWAYS_DEDICATED_MEMORY ? 1 : 0);
  13673. fprintf(m_File, "Macro,VMA_MIN_ALIGNMENT,%llu\n", (VkDeviceSize)VMA_MIN_ALIGNMENT);
  13674. fprintf(m_File, "Macro,VMA_DEBUG_MARGIN,%llu\n", (VkDeviceSize)VMA_DEBUG_MARGIN);
  13675. fprintf(m_File, "Macro,VMA_DEBUG_INITIALIZE_ALLOCATIONS,%u\n", VMA_DEBUG_INITIALIZE_ALLOCATIONS ? 1 : 0);
  13676. fprintf(m_File, "Macro,VMA_DEBUG_DETECT_CORRUPTION,%u\n", VMA_DEBUG_DETECT_CORRUPTION ? 1 : 0);
  13677. fprintf(m_File, "Macro,VMA_DEBUG_GLOBAL_MUTEX,%u\n", VMA_DEBUG_GLOBAL_MUTEX ? 1 : 0);
  13678. fprintf(m_File, "Macro,VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY,%llu\n", (VkDeviceSize)VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY);
  13679. fprintf(m_File, "Macro,VMA_SMALL_HEAP_MAX_SIZE,%llu\n", (VkDeviceSize)VMA_SMALL_HEAP_MAX_SIZE);
  13680. fprintf(m_File, "Macro,VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE,%llu\n", (VkDeviceSize)VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE);
  13681. fprintf(m_File, "Config,End\n");
  13682. }
  13683. void VmaRecorder::GetBasicParams(CallParams& outParams)
  13684. {
  13685. #if defined(_WIN32)
  13686. outParams.threadId = GetCurrentThreadId();
  13687. #else
  13688. // Use C++11 features to get thread id and convert it to uint32_t.
  13689. // There is room for optimization since sstream is quite slow.
  13690. // Is there a better way to convert std::this_thread::get_id() to uint32_t?
  13691. std::thread::id thread_id = std::this_thread::get_id();
  13692. std::stringstream thread_id_to_string_converter;
  13693. thread_id_to_string_converter << thread_id;
  13694. std::string thread_id_as_string = thread_id_to_string_converter.str();
  13695. outParams.threadId = static_cast<uint32_t>(std::stoi(thread_id_as_string.c_str()));
  13696. #endif
  13697. auto current_time = std::chrono::high_resolution_clock::now();
  13698. outParams.time = std::chrono::duration<double, std::chrono::seconds::period>(current_time - m_RecordingStartTime).count();
  13699. }
  13700. void VmaRecorder::PrintPointerList(uint64_t count, const VmaAllocation* pItems)
  13701. {
  13702. if(count)
  13703. {
  13704. fprintf(m_File, "%p", pItems[0]);
  13705. for(uint64_t i = 1; i < count; ++i)
  13706. {
  13707. fprintf(m_File, " %p", pItems[i]);
  13708. }
  13709. }
  13710. }
  13711. void VmaRecorder::Flush()
  13712. {
  13713. if((m_Flags & VMA_RECORD_FLUSH_AFTER_CALL_BIT) != 0)
  13714. {
  13715. fflush(m_File);
  13716. }
  13717. }
  13718. #endif // #if VMA_RECORDING_ENABLED
  13719. ////////////////////////////////////////////////////////////////////////////////
  13720. // VmaAllocationObjectAllocator
  13721. VmaAllocationObjectAllocator::VmaAllocationObjectAllocator(const VkAllocationCallbacks* pAllocationCallbacks) :
  13722. m_Allocator(pAllocationCallbacks, 1024)
  13723. {
  13724. }
  13725. template<typename... Types> VmaAllocation VmaAllocationObjectAllocator::Allocate(Types... args)
  13726. {
  13727. VmaMutexLock mutexLock(m_Mutex);
  13728. return m_Allocator.Alloc<Types...>(std::forward<Types>(args)...);
  13729. }
  13730. void VmaAllocationObjectAllocator::Free(VmaAllocation hAlloc)
  13731. {
  13732. VmaMutexLock mutexLock(m_Mutex);
  13733. m_Allocator.Free(hAlloc);
  13734. }
  13735. ////////////////////////////////////////////////////////////////////////////////
  13736. // VmaAllocator_T
  13737. VmaAllocator_T::VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo) :
  13738. m_UseMutex((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT) == 0),
  13739. m_VulkanApiVersion(pCreateInfo->vulkanApiVersion != 0 ? pCreateInfo->vulkanApiVersion : VK_API_VERSION_1_0),
  13740. m_UseKhrDedicatedAllocation((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0),
  13741. m_UseKhrBindMemory2((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT) != 0),
  13742. m_UseExtMemoryBudget((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT) != 0),
  13743. m_UseAmdDeviceCoherentMemory((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT) != 0),
  13744. m_UseKhrBufferDeviceAddress((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT) != 0),
  13745. m_UseExtMemoryPriority((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT) != 0),
  13746. m_hDevice(pCreateInfo->device),
  13747. m_hInstance(pCreateInfo->instance),
  13748. m_AllocationCallbacksSpecified(pCreateInfo->pAllocationCallbacks != VMA_NULL),
  13749. m_AllocationCallbacks(pCreateInfo->pAllocationCallbacks ?
  13750. *pCreateInfo->pAllocationCallbacks : VmaEmptyAllocationCallbacks),
  13751. m_AllocationObjectAllocator(&m_AllocationCallbacks),
  13752. m_HeapSizeLimitMask(0),
  13753. m_DeviceMemoryCount(0),
  13754. m_PreferredLargeHeapBlockSize(0),
  13755. m_PhysicalDevice(pCreateInfo->physicalDevice),
  13756. m_CurrentFrameIndex(0),
  13757. m_GpuDefragmentationMemoryTypeBits(UINT32_MAX),
  13758. m_NextPoolId(0),
  13759. m_GlobalMemoryTypeBits(UINT32_MAX)
  13760. #if VMA_RECORDING_ENABLED
  13761. ,m_pRecorder(VMA_NULL)
  13762. #endif
  13763. {
  13764. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  13765. {
  13766. m_UseKhrDedicatedAllocation = false;
  13767. m_UseKhrBindMemory2 = false;
  13768. }
  13769. if(VMA_DEBUG_DETECT_CORRUPTION)
  13770. {
  13771. // Needs to be multiply of uint32_t size because we are going to write VMA_CORRUPTION_DETECTION_MAGIC_VALUE to it.
  13772. VMA_ASSERT(VMA_DEBUG_MARGIN % sizeof(uint32_t) == 0);
  13773. }
  13774. VMA_ASSERT(pCreateInfo->physicalDevice && pCreateInfo->device && pCreateInfo->instance);
  13775. if(m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0))
  13776. {
  13777. #if !(VMA_DEDICATED_ALLOCATION)
  13778. if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0)
  13779. {
  13780. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT set but required extensions are disabled by preprocessor macros.");
  13781. }
  13782. #endif
  13783. #if !(VMA_BIND_MEMORY2)
  13784. if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT) != 0)
  13785. {
  13786. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT set but required extension is disabled by preprocessor macros.");
  13787. }
  13788. #endif
  13789. }
  13790. #if !(VMA_MEMORY_BUDGET)
  13791. if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT) != 0)
  13792. {
  13793. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT set but required extension is disabled by preprocessor macros.");
  13794. }
  13795. #endif
  13796. #if !(VMA_BUFFER_DEVICE_ADDRESS)
  13797. if(m_UseKhrBufferDeviceAddress)
  13798. {
  13799. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT is set but required extension or Vulkan 1.2 is not available in your Vulkan header or its support in VMA has been disabled by a preprocessor macro.");
  13800. }
  13801. #endif
  13802. #if VMA_VULKAN_VERSION < 1002000
  13803. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 2, 0))
  13804. {
  13805. VMA_ASSERT(0 && "vulkanApiVersion >= VK_API_VERSION_1_2 but required Vulkan version is disabled by preprocessor macros.");
  13806. }
  13807. #endif
  13808. #if VMA_VULKAN_VERSION < 1001000
  13809. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  13810. {
  13811. VMA_ASSERT(0 && "vulkanApiVersion >= VK_API_VERSION_1_1 but required Vulkan version is disabled by preprocessor macros.");
  13812. }
  13813. #endif
  13814. #if !(VMA_MEMORY_PRIORITY)
  13815. if(m_UseExtMemoryPriority)
  13816. {
  13817. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT is set but required extension is not available in your Vulkan header or its support in VMA has been disabled by a preprocessor macro.");
  13818. }
  13819. #endif
  13820. memset(&m_DeviceMemoryCallbacks, 0 ,sizeof(m_DeviceMemoryCallbacks));
  13821. memset(&m_PhysicalDeviceProperties, 0, sizeof(m_PhysicalDeviceProperties));
  13822. memset(&m_MemProps, 0, sizeof(m_MemProps));
  13823. memset(&m_pBlockVectors, 0, sizeof(m_pBlockVectors));
  13824. memset(&m_pSmallBufferBlockVectors, 0, sizeof(m_pSmallBufferBlockVectors));
  13825. memset(&m_VulkanFunctions, 0, sizeof(m_VulkanFunctions));
  13826. #if VMA_EXTERNAL_MEMORY
  13827. memset(&m_TypeExternalMemoryHandleTypes, 0, sizeof(m_TypeExternalMemoryHandleTypes));
  13828. #endif // #if VMA_EXTERNAL_MEMORY
  13829. if(pCreateInfo->pDeviceMemoryCallbacks != VMA_NULL)
  13830. {
  13831. m_DeviceMemoryCallbacks.pUserData = pCreateInfo->pDeviceMemoryCallbacks->pUserData;
  13832. m_DeviceMemoryCallbacks.pfnAllocate = pCreateInfo->pDeviceMemoryCallbacks->pfnAllocate;
  13833. m_DeviceMemoryCallbacks.pfnFree = pCreateInfo->pDeviceMemoryCallbacks->pfnFree;
  13834. }
  13835. ImportVulkanFunctions(pCreateInfo->pVulkanFunctions);
  13836. (*m_VulkanFunctions.vkGetPhysicalDeviceProperties)(m_PhysicalDevice, &m_PhysicalDeviceProperties);
  13837. (*m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties)(m_PhysicalDevice, &m_MemProps);
  13838. VMA_ASSERT(VmaIsPow2(VMA_MIN_ALIGNMENT));
  13839. VMA_ASSERT(VmaIsPow2(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY));
  13840. VMA_ASSERT(VmaIsPow2(m_PhysicalDeviceProperties.limits.bufferImageGranularity));
  13841. VMA_ASSERT(VmaIsPow2(m_PhysicalDeviceProperties.limits.nonCoherentAtomSize));
  13842. m_PreferredLargeHeapBlockSize = (pCreateInfo->preferredLargeHeapBlockSize != 0) ?
  13843. pCreateInfo->preferredLargeHeapBlockSize : static_cast<VkDeviceSize>(VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE);
  13844. m_GlobalMemoryTypeBits = CalculateGlobalMemoryTypeBits();
  13845. #if VMA_EXTERNAL_MEMORY
  13846. if(pCreateInfo->pTypeExternalMemoryHandleTypes != VMA_NULL)
  13847. {
  13848. memcpy(m_TypeExternalMemoryHandleTypes, pCreateInfo->pTypeExternalMemoryHandleTypes,
  13849. sizeof(VkExternalMemoryHandleTypeFlagsKHR) * GetMemoryTypeCount());
  13850. }
  13851. #endif // #if VMA_EXTERNAL_MEMORY
  13852. if(pCreateInfo->pHeapSizeLimit != VMA_NULL)
  13853. {
  13854. for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex)
  13855. {
  13856. const VkDeviceSize limit = pCreateInfo->pHeapSizeLimit[heapIndex];
  13857. if(limit != VK_WHOLE_SIZE)
  13858. {
  13859. m_HeapSizeLimitMask |= 1u << heapIndex;
  13860. if(limit < m_MemProps.memoryHeaps[heapIndex].size)
  13861. {
  13862. m_MemProps.memoryHeaps[heapIndex].size = limit;
  13863. }
  13864. }
  13865. }
  13866. }
  13867. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13868. {
  13869. const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(memTypeIndex);
  13870. m_pBlockVectors[memTypeIndex] = vma_new(this, VmaBlockVector)(
  13871. this,
  13872. VK_NULL_HANDLE, // hParentPool
  13873. memTypeIndex,
  13874. preferredBlockSize,
  13875. 0,
  13876. SIZE_MAX,
  13877. GetBufferImageGranularity(),
  13878. pCreateInfo->frameInUseCount,
  13879. false, // explicitBlockSize
  13880. false, // linearAlgorithm
  13881. 0.5f, // priority (0.5 is the default per Vulkan spec)
  13882. GetMemoryTypeMinAlignment(memTypeIndex), // minAllocationAlignment
  13883. VMA_NULL); // // pMemoryAllocateNext
  13884. m_pSmallBufferBlockVectors[memTypeIndex] = vma_new(this, VmaBlockVector)(
  13885. this,
  13886. VK_NULL_HANDLE, // hParentPool
  13887. memTypeIndex,
  13888. preferredBlockSize,
  13889. 0,
  13890. SIZE_MAX,
  13891. 1, // bufferImageGranularity forced to 1 !!!
  13892. pCreateInfo->frameInUseCount,
  13893. false, // explicitBlockSize
  13894. false, // linearAlgorithm
  13895. 0.5f, // priority (0.5 is the default per Vulkan spec)
  13896. GetMemoryTypeMinAlignment(memTypeIndex), // minAllocationAlignment
  13897. VMA_NULL); // // pMemoryAllocateNext
  13898. // No need to call m_pBlockVectors[memTypeIndex][blockVectorTypeIndex]->CreateMinBlocks here,
  13899. // becase minBlockCount is 0.
  13900. }
  13901. }
  13902. VkResult VmaAllocator_T::Init(const VmaAllocatorCreateInfo* pCreateInfo)
  13903. {
  13904. VkResult res = VK_SUCCESS;
  13905. if(pCreateInfo->pRecordSettings != VMA_NULL &&
  13906. !VmaStrIsEmpty(pCreateInfo->pRecordSettings->pFilePath))
  13907. {
  13908. #if VMA_RECORDING_ENABLED
  13909. m_pRecorder = vma_new(this, VmaRecorder)();
  13910. res = m_pRecorder->Init(*pCreateInfo->pRecordSettings, m_UseMutex);
  13911. if(res != VK_SUCCESS)
  13912. {
  13913. return res;
  13914. }
  13915. m_pRecorder->WriteConfiguration(
  13916. m_PhysicalDeviceProperties,
  13917. m_MemProps,
  13918. m_VulkanApiVersion,
  13919. m_UseKhrDedicatedAllocation,
  13920. m_UseKhrBindMemory2,
  13921. m_UseExtMemoryBudget,
  13922. m_UseAmdDeviceCoherentMemory);
  13923. m_pRecorder->RecordCreateAllocator(GetCurrentFrameIndex());
  13924. #else
  13925. VMA_ASSERT(0 && "VmaAllocatorCreateInfo::pRecordSettings used, but not supported due to VMA_RECORDING_ENABLED not defined to 1.");
  13926. return VK_ERROR_FEATURE_NOT_PRESENT;
  13927. #endif
  13928. }
  13929. #if VMA_MEMORY_BUDGET
  13930. if(m_UseExtMemoryBudget)
  13931. {
  13932. UpdateVulkanBudget();
  13933. }
  13934. #endif // #if VMA_MEMORY_BUDGET
  13935. return res;
  13936. }
  13937. VmaAllocator_T::~VmaAllocator_T()
  13938. {
  13939. #if VMA_RECORDING_ENABLED
  13940. if(m_pRecorder != VMA_NULL)
  13941. {
  13942. m_pRecorder->RecordDestroyAllocator(GetCurrentFrameIndex());
  13943. vma_delete(this, m_pRecorder);
  13944. }
  13945. #endif
  13946. VMA_ASSERT(m_Pools.IsEmpty());
  13947. for(size_t memTypeIndex = GetMemoryTypeCount(); memTypeIndex--; )
  13948. {
  13949. if(!m_DedicatedAllocations[memTypeIndex].IsEmpty())
  13950. {
  13951. VMA_ASSERT(0 && "Unfreed dedicated allocations found.");
  13952. }
  13953. vma_delete(this, m_pSmallBufferBlockVectors[memTypeIndex]);
  13954. vma_delete(this, m_pBlockVectors[memTypeIndex]);
  13955. }
  13956. }
  13957. void VmaAllocator_T::ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions)
  13958. {
  13959. #if VMA_STATIC_VULKAN_FUNCTIONS == 1
  13960. ImportVulkanFunctions_Static();
  13961. #endif
  13962. if(pVulkanFunctions != VMA_NULL)
  13963. {
  13964. ImportVulkanFunctions_Custom(pVulkanFunctions);
  13965. }
  13966. #if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1
  13967. ImportVulkanFunctions_Dynamic();
  13968. #endif
  13969. ValidateVulkanFunctions();
  13970. }
  13971. #if VMA_STATIC_VULKAN_FUNCTIONS == 1
  13972. void VmaAllocator_T::ImportVulkanFunctions_Static()
  13973. {
  13974. // Vulkan 1.0
  13975. m_VulkanFunctions.vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)vkGetPhysicalDeviceProperties;
  13976. m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)vkGetPhysicalDeviceMemoryProperties;
  13977. m_VulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkAllocateMemory;
  13978. m_VulkanFunctions.vkFreeMemory = (PFN_vkFreeMemory)vkFreeMemory;
  13979. m_VulkanFunctions.vkMapMemory = (PFN_vkMapMemory)vkMapMemory;
  13980. m_VulkanFunctions.vkUnmapMemory = (PFN_vkUnmapMemory)vkUnmapMemory;
  13981. m_VulkanFunctions.vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)vkFlushMappedMemoryRanges;
  13982. m_VulkanFunctions.vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)vkInvalidateMappedMemoryRanges;
  13983. m_VulkanFunctions.vkBindBufferMemory = (PFN_vkBindBufferMemory)vkBindBufferMemory;
  13984. m_VulkanFunctions.vkBindImageMemory = (PFN_vkBindImageMemory)vkBindImageMemory;
  13985. m_VulkanFunctions.vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)vkGetBufferMemoryRequirements;
  13986. m_VulkanFunctions.vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)vkGetImageMemoryRequirements;
  13987. m_VulkanFunctions.vkCreateBuffer = (PFN_vkCreateBuffer)vkCreateBuffer;
  13988. m_VulkanFunctions.vkDestroyBuffer = (PFN_vkDestroyBuffer)vkDestroyBuffer;
  13989. m_VulkanFunctions.vkCreateImage = (PFN_vkCreateImage)vkCreateImage;
  13990. m_VulkanFunctions.vkDestroyImage = (PFN_vkDestroyImage)vkDestroyImage;
  13991. m_VulkanFunctions.vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)vkCmdCopyBuffer;
  13992. // Vulkan 1.1
  13993. #if VMA_VULKAN_VERSION >= 1001000
  13994. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  13995. {
  13996. m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR = (PFN_vkGetBufferMemoryRequirements2)vkGetBufferMemoryRequirements2;
  13997. m_VulkanFunctions.vkGetImageMemoryRequirements2KHR = (PFN_vkGetImageMemoryRequirements2)vkGetImageMemoryRequirements2;
  13998. m_VulkanFunctions.vkBindBufferMemory2KHR = (PFN_vkBindBufferMemory2)vkBindBufferMemory2;
  13999. m_VulkanFunctions.vkBindImageMemory2KHR = (PFN_vkBindImageMemory2)vkBindImageMemory2;
  14000. m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR = (PFN_vkGetPhysicalDeviceMemoryProperties2)vkGetPhysicalDeviceMemoryProperties2;
  14001. }
  14002. #endif
  14003. }
  14004. #endif // #if VMA_STATIC_VULKAN_FUNCTIONS == 1
  14005. void VmaAllocator_T::ImportVulkanFunctions_Custom(const VmaVulkanFunctions* pVulkanFunctions)
  14006. {
  14007. VMA_ASSERT(pVulkanFunctions != VMA_NULL);
  14008. #define VMA_COPY_IF_NOT_NULL(funcName) \
  14009. if(pVulkanFunctions->funcName != VMA_NULL) m_VulkanFunctions.funcName = pVulkanFunctions->funcName;
  14010. VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceProperties);
  14011. VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties);
  14012. VMA_COPY_IF_NOT_NULL(vkAllocateMemory);
  14013. VMA_COPY_IF_NOT_NULL(vkFreeMemory);
  14014. VMA_COPY_IF_NOT_NULL(vkMapMemory);
  14015. VMA_COPY_IF_NOT_NULL(vkUnmapMemory);
  14016. VMA_COPY_IF_NOT_NULL(vkFlushMappedMemoryRanges);
  14017. VMA_COPY_IF_NOT_NULL(vkInvalidateMappedMemoryRanges);
  14018. VMA_COPY_IF_NOT_NULL(vkBindBufferMemory);
  14019. VMA_COPY_IF_NOT_NULL(vkBindImageMemory);
  14020. VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements);
  14021. VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements);
  14022. VMA_COPY_IF_NOT_NULL(vkCreateBuffer);
  14023. VMA_COPY_IF_NOT_NULL(vkDestroyBuffer);
  14024. VMA_COPY_IF_NOT_NULL(vkCreateImage);
  14025. VMA_COPY_IF_NOT_NULL(vkDestroyImage);
  14026. VMA_COPY_IF_NOT_NULL(vkCmdCopyBuffer);
  14027. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  14028. VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements2KHR);
  14029. VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements2KHR);
  14030. #endif
  14031. #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000
  14032. VMA_COPY_IF_NOT_NULL(vkBindBufferMemory2KHR);
  14033. VMA_COPY_IF_NOT_NULL(vkBindImageMemory2KHR);
  14034. #endif
  14035. #if VMA_MEMORY_BUDGET
  14036. VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties2KHR);
  14037. #endif
  14038. #undef VMA_COPY_IF_NOT_NULL
  14039. }
  14040. #if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1
  14041. void VmaAllocator_T::ImportVulkanFunctions_Dynamic()
  14042. {
  14043. #define VMA_FETCH_INSTANCE_FUNC(memberName, functionPointerType, functionNameString) \
  14044. if(m_VulkanFunctions.memberName == VMA_NULL) \
  14045. m_VulkanFunctions.memberName = \
  14046. (functionPointerType)vkGetInstanceProcAddr(m_hInstance, functionNameString);
  14047. #define VMA_FETCH_DEVICE_FUNC(memberName, functionPointerType, functionNameString) \
  14048. if(m_VulkanFunctions.memberName == VMA_NULL) \
  14049. m_VulkanFunctions.memberName = \
  14050. (functionPointerType)vkGetDeviceProcAddr(m_hDevice, functionNameString);
  14051. VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceProperties, PFN_vkGetPhysicalDeviceProperties, "vkGetPhysicalDeviceProperties");
  14052. VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties, PFN_vkGetPhysicalDeviceMemoryProperties, "vkGetPhysicalDeviceMemoryProperties");
  14053. VMA_FETCH_DEVICE_FUNC(vkAllocateMemory, PFN_vkAllocateMemory, "vkAllocateMemory");
  14054. VMA_FETCH_DEVICE_FUNC(vkFreeMemory, PFN_vkFreeMemory, "vkFreeMemory");
  14055. VMA_FETCH_DEVICE_FUNC(vkMapMemory, PFN_vkMapMemory, "vkMapMemory");
  14056. VMA_FETCH_DEVICE_FUNC(vkUnmapMemory, PFN_vkUnmapMemory, "vkUnmapMemory");
  14057. VMA_FETCH_DEVICE_FUNC(vkFlushMappedMemoryRanges, PFN_vkFlushMappedMemoryRanges, "vkFlushMappedMemoryRanges");
  14058. VMA_FETCH_DEVICE_FUNC(vkInvalidateMappedMemoryRanges, PFN_vkInvalidateMappedMemoryRanges, "vkInvalidateMappedMemoryRanges");
  14059. VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory, PFN_vkBindBufferMemory, "vkBindBufferMemory");
  14060. VMA_FETCH_DEVICE_FUNC(vkBindImageMemory, PFN_vkBindImageMemory, "vkBindImageMemory");
  14061. VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements, PFN_vkGetBufferMemoryRequirements, "vkGetBufferMemoryRequirements");
  14062. VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements, PFN_vkGetImageMemoryRequirements, "vkGetImageMemoryRequirements");
  14063. VMA_FETCH_DEVICE_FUNC(vkCreateBuffer, PFN_vkCreateBuffer, "vkCreateBuffer");
  14064. VMA_FETCH_DEVICE_FUNC(vkDestroyBuffer, PFN_vkDestroyBuffer, "vkDestroyBuffer");
  14065. VMA_FETCH_DEVICE_FUNC(vkCreateImage, PFN_vkCreateImage, "vkCreateImage");
  14066. VMA_FETCH_DEVICE_FUNC(vkDestroyImage, PFN_vkDestroyImage, "vkDestroyImage");
  14067. VMA_FETCH_DEVICE_FUNC(vkCmdCopyBuffer, PFN_vkCmdCopyBuffer, "vkCmdCopyBuffer");
  14068. #if VMA_VULKAN_VERSION >= 1001000
  14069. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  14070. {
  14071. VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements2KHR, PFN_vkGetBufferMemoryRequirements2, "vkGetBufferMemoryRequirements2");
  14072. VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements2KHR, PFN_vkGetImageMemoryRequirements2, "vkGetImageMemoryRequirements2");
  14073. VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory2KHR, PFN_vkBindBufferMemory2, "vkBindBufferMemory2");
  14074. VMA_FETCH_DEVICE_FUNC(vkBindImageMemory2KHR, PFN_vkBindImageMemory2, "vkBindImageMemory2");
  14075. VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties2KHR, PFN_vkGetPhysicalDeviceMemoryProperties2, "vkGetPhysicalDeviceMemoryProperties2");
  14076. }
  14077. #endif
  14078. #if VMA_DEDICATED_ALLOCATION
  14079. if(m_UseKhrDedicatedAllocation)
  14080. {
  14081. VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements2KHR, PFN_vkGetBufferMemoryRequirements2KHR, "vkGetBufferMemoryRequirements2KHR");
  14082. VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements2KHR, PFN_vkGetImageMemoryRequirements2KHR, "vkGetImageMemoryRequirements2KHR");
  14083. }
  14084. #endif
  14085. #if VMA_BIND_MEMORY2
  14086. if(m_UseKhrBindMemory2)
  14087. {
  14088. VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory2KHR, PFN_vkBindBufferMemory2KHR, "vkBindBufferMemory2KHR");
  14089. VMA_FETCH_DEVICE_FUNC(vkBindImageMemory2KHR, PFN_vkBindImageMemory2KHR, "vkBindImageMemory2KHR");
  14090. }
  14091. #endif // #if VMA_BIND_MEMORY2
  14092. #if VMA_MEMORY_BUDGET
  14093. if(m_UseExtMemoryBudget)
  14094. {
  14095. VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties2KHR, PFN_vkGetPhysicalDeviceMemoryProperties2KHR, "vkGetPhysicalDeviceMemoryProperties2KHR");
  14096. }
  14097. #endif // #if VMA_MEMORY_BUDGET
  14098. #undef VMA_FETCH_DEVICE_FUNC
  14099. #undef VMA_FETCH_INSTANCE_FUNC
  14100. }
  14101. #endif // #if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1
  14102. void VmaAllocator_T::ValidateVulkanFunctions()
  14103. {
  14104. VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceProperties != VMA_NULL);
  14105. VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties != VMA_NULL);
  14106. VMA_ASSERT(m_VulkanFunctions.vkAllocateMemory != VMA_NULL);
  14107. VMA_ASSERT(m_VulkanFunctions.vkFreeMemory != VMA_NULL);
  14108. VMA_ASSERT(m_VulkanFunctions.vkMapMemory != VMA_NULL);
  14109. VMA_ASSERT(m_VulkanFunctions.vkUnmapMemory != VMA_NULL);
  14110. VMA_ASSERT(m_VulkanFunctions.vkFlushMappedMemoryRanges != VMA_NULL);
  14111. VMA_ASSERT(m_VulkanFunctions.vkInvalidateMappedMemoryRanges != VMA_NULL);
  14112. VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory != VMA_NULL);
  14113. VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory != VMA_NULL);
  14114. VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements != VMA_NULL);
  14115. VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements != VMA_NULL);
  14116. VMA_ASSERT(m_VulkanFunctions.vkCreateBuffer != VMA_NULL);
  14117. VMA_ASSERT(m_VulkanFunctions.vkDestroyBuffer != VMA_NULL);
  14118. VMA_ASSERT(m_VulkanFunctions.vkCreateImage != VMA_NULL);
  14119. VMA_ASSERT(m_VulkanFunctions.vkDestroyImage != VMA_NULL);
  14120. VMA_ASSERT(m_VulkanFunctions.vkCmdCopyBuffer != VMA_NULL);
  14121. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  14122. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0) || m_UseKhrDedicatedAllocation)
  14123. {
  14124. VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR != VMA_NULL);
  14125. VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements2KHR != VMA_NULL);
  14126. }
  14127. #endif
  14128. #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000
  14129. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0) || m_UseKhrBindMemory2)
  14130. {
  14131. VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory2KHR != VMA_NULL);
  14132. VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory2KHR != VMA_NULL);
  14133. }
  14134. #endif
  14135. #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000
  14136. if(m_UseExtMemoryBudget || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  14137. {
  14138. VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR != VMA_NULL);
  14139. }
  14140. #endif
  14141. }
  14142. VkDeviceSize VmaAllocator_T::CalcPreferredBlockSize(uint32_t memTypeIndex)
  14143. {
  14144. const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex);
  14145. const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size;
  14146. const bool isSmallHeap = heapSize <= VMA_SMALL_HEAP_MAX_SIZE;
  14147. return VmaAlignUp(isSmallHeap ? (heapSize / 8) : m_PreferredLargeHeapBlockSize, (VkDeviceSize)32);
  14148. }
  14149. VkResult VmaAllocator_T::AllocateMemoryOfType(
  14150. VkDeviceSize size,
  14151. VkDeviceSize alignment,
  14152. bool dedicatedAllocation,
  14153. VkBuffer dedicatedBuffer,
  14154. VkBufferUsageFlags dedicatedBufferUsage,
  14155. VkImage dedicatedImage,
  14156. const VmaAllocationCreateInfo& createInfo,
  14157. uint32_t memTypeIndex,
  14158. VmaSuballocationType suballocType,
  14159. size_t allocationCount,
  14160. VmaAllocation* pAllocations)
  14161. {
  14162. VMA_ASSERT(pAllocations != VMA_NULL);
  14163. VMA_DEBUG_LOG(" AllocateMemory: MemoryTypeIndex=%u, AllocationCount=%zu, Size=%llu", memTypeIndex, allocationCount, size);
  14164. VmaAllocationCreateInfo finalCreateInfo = createInfo;
  14165. // If memory type is not HOST_VISIBLE, disable MAPPED.
  14166. if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 &&
  14167. (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  14168. {
  14169. finalCreateInfo.flags &= ~VMA_ALLOCATION_CREATE_MAPPED_BIT;
  14170. }
  14171. // If memory is lazily allocated, it should be always dedicated.
  14172. if(finalCreateInfo.usage == VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED)
  14173. {
  14174. finalCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  14175. }
  14176. bool isSmallBuffer = dedicatedBuffer != VK_NULL_HANDLE && size <= 4096; // TODO
  14177. VmaBlockVector* const blockVector = isSmallBuffer ? m_pSmallBufferBlockVectors[memTypeIndex] : m_pBlockVectors[memTypeIndex];
  14178. VMA_ASSERT(blockVector);
  14179. const VkDeviceSize preferredBlockSize = blockVector->GetPreferredBlockSize();
  14180. bool preferDedicatedMemory =
  14181. VMA_DEBUG_ALWAYS_DEDICATED_MEMORY ||
  14182. dedicatedAllocation ||
  14183. // Heuristics: Allocate dedicated memory if requested size if greater than half of preferred block size.
  14184. size > preferredBlockSize / 2;
  14185. if(preferDedicatedMemory &&
  14186. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0 &&
  14187. finalCreateInfo.pool == VK_NULL_HANDLE)
  14188. {
  14189. finalCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  14190. }
  14191. if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0)
  14192. {
  14193. if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
  14194. {
  14195. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  14196. }
  14197. else
  14198. {
  14199. return AllocateDedicatedMemory(
  14200. size,
  14201. suballocType,
  14202. memTypeIndex,
  14203. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT) != 0,
  14204. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0,
  14205. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0,
  14206. finalCreateInfo.pUserData,
  14207. finalCreateInfo.priority,
  14208. dedicatedBuffer,
  14209. dedicatedBufferUsage,
  14210. dedicatedImage,
  14211. allocationCount,
  14212. pAllocations);
  14213. }
  14214. }
  14215. else
  14216. {
  14217. VkResult res = blockVector->Allocate(
  14218. m_CurrentFrameIndex.load(),
  14219. size,
  14220. alignment,
  14221. finalCreateInfo,
  14222. suballocType,
  14223. allocationCount,
  14224. pAllocations);
  14225. if(res == VK_SUCCESS)
  14226. {
  14227. return res;
  14228. }
  14229. // 5. Try dedicated memory.
  14230. if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
  14231. {
  14232. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  14233. }
  14234. // Protection against creating each allocation as dedicated when we reach or exceed heap size/budget,
  14235. // which can quickly deplete maxMemoryAllocationCount: Don't try dedicated allocations when above
  14236. // 3/4 of the maximum allocation count.
  14237. if(m_DeviceMemoryCount.load() > m_PhysicalDeviceProperties.limits.maxMemoryAllocationCount * 3 / 4)
  14238. {
  14239. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  14240. }
  14241. res = AllocateDedicatedMemory(
  14242. size,
  14243. suballocType,
  14244. memTypeIndex,
  14245. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT) != 0,
  14246. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0,
  14247. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0,
  14248. finalCreateInfo.pUserData,
  14249. finalCreateInfo.priority,
  14250. dedicatedBuffer,
  14251. dedicatedBufferUsage,
  14252. dedicatedImage,
  14253. allocationCount,
  14254. pAllocations);
  14255. if(res == VK_SUCCESS)
  14256. {
  14257. // Succeeded: AllocateDedicatedMemory function already filld pMemory, nothing more to do here.
  14258. VMA_DEBUG_LOG(" Allocated as DedicatedMemory");
  14259. return VK_SUCCESS;
  14260. }
  14261. else
  14262. {
  14263. // Everything failed: Return error code.
  14264. VMA_DEBUG_LOG(" vkAllocateMemory FAILED");
  14265. return res;
  14266. }
  14267. }
  14268. }
  14269. VkResult VmaAllocator_T::AllocateDedicatedMemory(
  14270. VkDeviceSize size,
  14271. VmaSuballocationType suballocType,
  14272. uint32_t memTypeIndex,
  14273. bool withinBudget,
  14274. bool map,
  14275. bool isUserDataString,
  14276. void* pUserData,
  14277. float priority,
  14278. VkBuffer dedicatedBuffer,
  14279. VkBufferUsageFlags dedicatedBufferUsage,
  14280. VkImage dedicatedImage,
  14281. size_t allocationCount,
  14282. VmaAllocation* pAllocations)
  14283. {
  14284. VMA_ASSERT(allocationCount > 0 && pAllocations);
  14285. if(withinBudget)
  14286. {
  14287. const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex);
  14288. VmaBudget heapBudget = {};
  14289. GetBudget(&heapBudget, heapIndex, 1);
  14290. if(heapBudget.usage + size * allocationCount > heapBudget.budget)
  14291. {
  14292. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  14293. }
  14294. }
  14295. VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
  14296. allocInfo.memoryTypeIndex = memTypeIndex;
  14297. allocInfo.allocationSize = size;
  14298. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  14299. VkMemoryDedicatedAllocateInfoKHR dedicatedAllocInfo = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR };
  14300. if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  14301. {
  14302. if(dedicatedBuffer != VK_NULL_HANDLE)
  14303. {
  14304. VMA_ASSERT(dedicatedImage == VK_NULL_HANDLE);
  14305. dedicatedAllocInfo.buffer = dedicatedBuffer;
  14306. VmaPnextChainPushFront(&allocInfo, &dedicatedAllocInfo);
  14307. }
  14308. else if(dedicatedImage != VK_NULL_HANDLE)
  14309. {
  14310. dedicatedAllocInfo.image = dedicatedImage;
  14311. VmaPnextChainPushFront(&allocInfo, &dedicatedAllocInfo);
  14312. }
  14313. }
  14314. #endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  14315. #if VMA_BUFFER_DEVICE_ADDRESS
  14316. VkMemoryAllocateFlagsInfoKHR allocFlagsInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR };
  14317. if(m_UseKhrBufferDeviceAddress)
  14318. {
  14319. bool canContainBufferWithDeviceAddress = true;
  14320. if(dedicatedBuffer != VK_NULL_HANDLE)
  14321. {
  14322. canContainBufferWithDeviceAddress = dedicatedBufferUsage == UINT32_MAX || // Usage flags unknown
  14323. (dedicatedBufferUsage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT) != 0;
  14324. }
  14325. else if(dedicatedImage != VK_NULL_HANDLE)
  14326. {
  14327. canContainBufferWithDeviceAddress = false;
  14328. }
  14329. if(canContainBufferWithDeviceAddress)
  14330. {
  14331. allocFlagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR;
  14332. VmaPnextChainPushFront(&allocInfo, &allocFlagsInfo);
  14333. }
  14334. }
  14335. #endif // #if VMA_BUFFER_DEVICE_ADDRESS
  14336. #if VMA_MEMORY_PRIORITY
  14337. VkMemoryPriorityAllocateInfoEXT priorityInfo = { VK_STRUCTURE_TYPE_MEMORY_PRIORITY_ALLOCATE_INFO_EXT };
  14338. if(m_UseExtMemoryPriority)
  14339. {
  14340. priorityInfo.priority = priority;
  14341. VmaPnextChainPushFront(&allocInfo, &priorityInfo);
  14342. }
  14343. #endif // #if VMA_MEMORY_PRIORITY
  14344. #if VMA_EXTERNAL_MEMORY
  14345. // Attach VkExportMemoryAllocateInfoKHR if necessary.
  14346. VkExportMemoryAllocateInfoKHR exportMemoryAllocInfo = { VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR };
  14347. exportMemoryAllocInfo.handleTypes = GetExternalMemoryHandleTypeFlags(memTypeIndex);
  14348. if(exportMemoryAllocInfo.handleTypes != 0)
  14349. {
  14350. VmaPnextChainPushFront(&allocInfo, &exportMemoryAllocInfo);
  14351. }
  14352. #endif // #if VMA_EXTERNAL_MEMORY
  14353. size_t allocIndex;
  14354. VkResult res = VK_SUCCESS;
  14355. for(allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  14356. {
  14357. res = AllocateDedicatedMemoryPage(
  14358. size,
  14359. suballocType,
  14360. memTypeIndex,
  14361. allocInfo,
  14362. map,
  14363. isUserDataString,
  14364. pUserData,
  14365. pAllocations + allocIndex);
  14366. if(res != VK_SUCCESS)
  14367. {
  14368. break;
  14369. }
  14370. }
  14371. if(res == VK_SUCCESS)
  14372. {
  14373. // Register them in m_DedicatedAllocations.
  14374. {
  14375. VmaMutexLockWrite lock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
  14376. DedicatedAllocationLinkedList& dedicatedAllocations = m_DedicatedAllocations[memTypeIndex];
  14377. for(allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  14378. {
  14379. dedicatedAllocations.PushBack(pAllocations[allocIndex]);
  14380. }
  14381. }
  14382. VMA_DEBUG_LOG(" Allocated DedicatedMemory Count=%zu, MemoryTypeIndex=#%u", allocationCount, memTypeIndex);
  14383. }
  14384. else
  14385. {
  14386. // Free all already created allocations.
  14387. while(allocIndex--)
  14388. {
  14389. VmaAllocation currAlloc = pAllocations[allocIndex];
  14390. VkDeviceMemory hMemory = currAlloc->GetMemory();
  14391. /*
  14392. There is no need to call this, because Vulkan spec allows to skip vkUnmapMemory
  14393. before vkFreeMemory.
  14394. if(currAlloc->GetMappedData() != VMA_NULL)
  14395. {
  14396. (*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory);
  14397. }
  14398. */
  14399. FreeVulkanMemory(memTypeIndex, currAlloc->GetSize(), hMemory);
  14400. m_Budget.RemoveAllocation(MemoryTypeIndexToHeapIndex(memTypeIndex), currAlloc->GetSize());
  14401. currAlloc->SetUserData(this, VMA_NULL);
  14402. m_AllocationObjectAllocator.Free(currAlloc);
  14403. }
  14404. memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount);
  14405. }
  14406. return res;
  14407. }
  14408. VkResult VmaAllocator_T::AllocateDedicatedMemoryPage(
  14409. VkDeviceSize size,
  14410. VmaSuballocationType suballocType,
  14411. uint32_t memTypeIndex,
  14412. const VkMemoryAllocateInfo& allocInfo,
  14413. bool map,
  14414. bool isUserDataString,
  14415. void* pUserData,
  14416. VmaAllocation* pAllocation)
  14417. {
  14418. VkDeviceMemory hMemory = VK_NULL_HANDLE;
  14419. VkResult res = AllocateVulkanMemory(&allocInfo, &hMemory);
  14420. if(res < 0)
  14421. {
  14422. VMA_DEBUG_LOG(" vkAllocateMemory FAILED");
  14423. return res;
  14424. }
  14425. void* pMappedData = VMA_NULL;
  14426. if(map)
  14427. {
  14428. res = (*m_VulkanFunctions.vkMapMemory)(
  14429. m_hDevice,
  14430. hMemory,
  14431. 0,
  14432. VK_WHOLE_SIZE,
  14433. 0,
  14434. &pMappedData);
  14435. if(res < 0)
  14436. {
  14437. VMA_DEBUG_LOG(" vkMapMemory FAILED");
  14438. FreeVulkanMemory(memTypeIndex, size, hMemory);
  14439. return res;
  14440. }
  14441. }
  14442. *pAllocation = m_AllocationObjectAllocator.Allocate(m_CurrentFrameIndex.load(), isUserDataString);
  14443. (*pAllocation)->InitDedicatedAllocation(memTypeIndex, hMemory, suballocType, pMappedData, size);
  14444. (*pAllocation)->SetUserData(this, pUserData);
  14445. m_Budget.AddAllocation(MemoryTypeIndexToHeapIndex(memTypeIndex), size);
  14446. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
  14447. {
  14448. FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED);
  14449. }
  14450. return VK_SUCCESS;
  14451. }
  14452. void VmaAllocator_T::GetBufferMemoryRequirements(
  14453. VkBuffer hBuffer,
  14454. VkMemoryRequirements& memReq,
  14455. bool& requiresDedicatedAllocation,
  14456. bool& prefersDedicatedAllocation) const
  14457. {
  14458. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  14459. if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  14460. {
  14461. VkBufferMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR };
  14462. memReqInfo.buffer = hBuffer;
  14463. VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR };
  14464. VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR };
  14465. VmaPnextChainPushFront(&memReq2, &memDedicatedReq);
  14466. (*m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2);
  14467. memReq = memReq2.memoryRequirements;
  14468. requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE);
  14469. prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE);
  14470. }
  14471. else
  14472. #endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  14473. {
  14474. (*m_VulkanFunctions.vkGetBufferMemoryRequirements)(m_hDevice, hBuffer, &memReq);
  14475. requiresDedicatedAllocation = false;
  14476. prefersDedicatedAllocation = false;
  14477. }
  14478. }
  14479. void VmaAllocator_T::GetImageMemoryRequirements(
  14480. VkImage hImage,
  14481. VkMemoryRequirements& memReq,
  14482. bool& requiresDedicatedAllocation,
  14483. bool& prefersDedicatedAllocation) const
  14484. {
  14485. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  14486. if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  14487. {
  14488. VkImageMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR };
  14489. memReqInfo.image = hImage;
  14490. VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR };
  14491. VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR };
  14492. VmaPnextChainPushFront(&memReq2, &memDedicatedReq);
  14493. (*m_VulkanFunctions.vkGetImageMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2);
  14494. memReq = memReq2.memoryRequirements;
  14495. requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE);
  14496. prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE);
  14497. }
  14498. else
  14499. #endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  14500. {
  14501. (*m_VulkanFunctions.vkGetImageMemoryRequirements)(m_hDevice, hImage, &memReq);
  14502. requiresDedicatedAllocation = false;
  14503. prefersDedicatedAllocation = false;
  14504. }
  14505. }
  14506. VkResult VmaAllocator_T::AllocateMemory(
  14507. const VkMemoryRequirements& vkMemReq,
  14508. bool requiresDedicatedAllocation,
  14509. bool prefersDedicatedAllocation,
  14510. VkBuffer dedicatedBuffer,
  14511. VkBufferUsageFlags dedicatedBufferUsage,
  14512. VkImage dedicatedImage,
  14513. const VmaAllocationCreateInfo& createInfo,
  14514. VmaSuballocationType suballocType,
  14515. size_t allocationCount,
  14516. VmaAllocation* pAllocations)
  14517. {
  14518. memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount);
  14519. VMA_ASSERT(VmaIsPow2(vkMemReq.alignment));
  14520. if(vkMemReq.size == 0)
  14521. {
  14522. return VK_ERROR_VALIDATION_FAILED_EXT;
  14523. }
  14524. if((createInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0 &&
  14525. (createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
  14526. {
  14527. VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT together with VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT makes no sense.");
  14528. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  14529. }
  14530. if((createInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 &&
  14531. (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0)
  14532. {
  14533. VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_MAPPED_BIT together with VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT is invalid.");
  14534. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  14535. }
  14536. if(requiresDedicatedAllocation)
  14537. {
  14538. if((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
  14539. {
  14540. VMA_ASSERT(0 && "VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT specified while dedicated allocation is required.");
  14541. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  14542. }
  14543. if(createInfo.pool != VK_NULL_HANDLE)
  14544. {
  14545. VMA_ASSERT(0 && "Pool specified while dedicated allocation is required.");
  14546. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  14547. }
  14548. }
  14549. if((createInfo.pool != VK_NULL_HANDLE) &&
  14550. ((createInfo.flags & (VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT)) != 0))
  14551. {
  14552. VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT when pool != null is invalid.");
  14553. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  14554. }
  14555. if(createInfo.pool != VK_NULL_HANDLE)
  14556. {
  14557. VmaAllocationCreateInfo createInfoForPool = createInfo;
  14558. // If memory type is not HOST_VISIBLE, disable MAPPED.
  14559. if((createInfoForPool.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 &&
  14560. (m_MemProps.memoryTypes[createInfo.pool->m_BlockVector.GetMemoryTypeIndex()].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  14561. {
  14562. createInfoForPool.flags &= ~VMA_ALLOCATION_CREATE_MAPPED_BIT;
  14563. }
  14564. return createInfo.pool->m_BlockVector.Allocate(
  14565. m_CurrentFrameIndex.load(),
  14566. vkMemReq.size,
  14567. vkMemReq.alignment,
  14568. createInfoForPool,
  14569. suballocType,
  14570. allocationCount,
  14571. pAllocations);
  14572. }
  14573. else
  14574. {
  14575. // Bit mask of memory Vulkan types acceptable for this allocation.
  14576. uint32_t memoryTypeBits = vkMemReq.memoryTypeBits;
  14577. uint32_t memTypeIndex = UINT32_MAX;
  14578. VkResult res = vmaFindMemoryTypeIndex(this, memoryTypeBits, &createInfo, &memTypeIndex);
  14579. if(res == VK_SUCCESS)
  14580. {
  14581. res = AllocateMemoryOfType(
  14582. vkMemReq.size,
  14583. vkMemReq.alignment,
  14584. requiresDedicatedAllocation || prefersDedicatedAllocation,
  14585. dedicatedBuffer,
  14586. dedicatedBufferUsage,
  14587. dedicatedImage,
  14588. createInfo,
  14589. memTypeIndex,
  14590. suballocType,
  14591. allocationCount,
  14592. pAllocations);
  14593. // Succeeded on first try.
  14594. if(res == VK_SUCCESS)
  14595. {
  14596. return res;
  14597. }
  14598. // Allocation from this memory type failed. Try other compatible memory types.
  14599. else
  14600. {
  14601. for(;;)
  14602. {
  14603. // Remove old memTypeIndex from list of possibilities.
  14604. memoryTypeBits &= ~(1u << memTypeIndex);
  14605. // Find alternative memTypeIndex.
  14606. res = vmaFindMemoryTypeIndex(this, memoryTypeBits, &createInfo, &memTypeIndex);
  14607. if(res == VK_SUCCESS)
  14608. {
  14609. res = AllocateMemoryOfType(
  14610. vkMemReq.size,
  14611. vkMemReq.alignment,
  14612. requiresDedicatedAllocation || prefersDedicatedAllocation,
  14613. dedicatedBuffer,
  14614. dedicatedBufferUsage,
  14615. dedicatedImage,
  14616. createInfo,
  14617. memTypeIndex,
  14618. suballocType,
  14619. allocationCount,
  14620. pAllocations);
  14621. // Allocation from this alternative memory type succeeded.
  14622. if(res == VK_SUCCESS)
  14623. {
  14624. return res;
  14625. }
  14626. // else: Allocation from this memory type failed. Try next one - next loop iteration.
  14627. }
  14628. // No other matching memory type index could be found.
  14629. else
  14630. {
  14631. // Not returning res, which is VK_ERROR_FEATURE_NOT_PRESENT, because we already failed to allocate once.
  14632. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  14633. }
  14634. }
  14635. }
  14636. }
  14637. // Can't find any single memory type maching requirements. res is VK_ERROR_FEATURE_NOT_PRESENT.
  14638. else
  14639. return res;
  14640. }
  14641. }
  14642. void VmaAllocator_T::FreeMemory(
  14643. size_t allocationCount,
  14644. const VmaAllocation* pAllocations)
  14645. {
  14646. VMA_ASSERT(pAllocations);
  14647. for(size_t allocIndex = allocationCount; allocIndex--; )
  14648. {
  14649. VmaAllocation allocation = pAllocations[allocIndex];
  14650. if(allocation != VK_NULL_HANDLE)
  14651. {
  14652. if(TouchAllocation(allocation))
  14653. {
  14654. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
  14655. {
  14656. FillAllocation(allocation, VMA_ALLOCATION_FILL_PATTERN_DESTROYED);
  14657. }
  14658. switch(allocation->GetType())
  14659. {
  14660. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  14661. {
  14662. VmaBlockVector* pBlockVector = VMA_NULL;
  14663. VmaPool hPool = allocation->GetBlock()->GetParentPool();
  14664. if(hPool != VK_NULL_HANDLE)
  14665. {
  14666. pBlockVector = &hPool->m_BlockVector;
  14667. }
  14668. else
  14669. {
  14670. pBlockVector = allocation->GetBlock()->GetParentBlockVector();
  14671. }
  14672. pBlockVector->Free(allocation);
  14673. }
  14674. break;
  14675. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  14676. FreeDedicatedMemory(allocation);
  14677. break;
  14678. default:
  14679. VMA_ASSERT(0);
  14680. }
  14681. }
  14682. // Do this regardless of whether the allocation is lost. Lost allocations still account to Budget.AllocationBytes.
  14683. m_Budget.RemoveAllocation(MemoryTypeIndexToHeapIndex(allocation->GetMemoryTypeIndex()), allocation->GetSize());
  14684. allocation->SetUserData(this, VMA_NULL);
  14685. m_AllocationObjectAllocator.Free(allocation);
  14686. }
  14687. }
  14688. }
  14689. void VmaAllocator_T::CalculateStats(VmaStats* pStats)
  14690. {
  14691. // Initialize.
  14692. InitStatInfo(pStats->total);
  14693. for(size_t i = 0; i < VK_MAX_MEMORY_TYPES; ++i)
  14694. InitStatInfo(pStats->memoryType[i]);
  14695. for(size_t i = 0; i < VK_MAX_MEMORY_HEAPS; ++i)
  14696. InitStatInfo(pStats->memoryHeap[i]);
  14697. // Process default pools.
  14698. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  14699. {
  14700. VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex];
  14701. VMA_ASSERT(pBlockVector);
  14702. pBlockVector->AddStats(pStats);
  14703. VmaBlockVector* const pSmallBufferBlockVector = m_pSmallBufferBlockVectors[memTypeIndex];
  14704. VMA_ASSERT(pSmallBufferBlockVector);
  14705. pSmallBufferBlockVector->AddStats(pStats);
  14706. }
  14707. // Process custom pools.
  14708. {
  14709. VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex);
  14710. for(VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool))
  14711. {
  14712. pool->m_BlockVector.AddStats(pStats);
  14713. }
  14714. }
  14715. // Process dedicated allocations.
  14716. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  14717. {
  14718. const uint32_t memHeapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex);
  14719. VmaMutexLockRead dedicatedAllocationsLock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
  14720. DedicatedAllocationLinkedList& dedicatedAllocList = m_DedicatedAllocations[memTypeIndex];
  14721. for(VmaAllocation alloc = dedicatedAllocList.Front();
  14722. alloc != VMA_NULL; alloc = dedicatedAllocList.GetNext(alloc))
  14723. {
  14724. VmaStatInfo allocationStatInfo;
  14725. alloc->DedicatedAllocCalcStatsInfo(allocationStatInfo);
  14726. VmaAddStatInfo(pStats->total, allocationStatInfo);
  14727. VmaAddStatInfo(pStats->memoryType[memTypeIndex], allocationStatInfo);
  14728. VmaAddStatInfo(pStats->memoryHeap[memHeapIndex], allocationStatInfo);
  14729. }
  14730. }
  14731. // Postprocess.
  14732. VmaPostprocessCalcStatInfo(pStats->total);
  14733. for(size_t i = 0; i < GetMemoryTypeCount(); ++i)
  14734. VmaPostprocessCalcStatInfo(pStats->memoryType[i]);
  14735. for(size_t i = 0; i < GetMemoryHeapCount(); ++i)
  14736. VmaPostprocessCalcStatInfo(pStats->memoryHeap[i]);
  14737. }
  14738. void VmaAllocator_T::GetBudget(VmaBudget* outBudget, uint32_t firstHeap, uint32_t heapCount)
  14739. {
  14740. #if VMA_MEMORY_BUDGET
  14741. if(m_UseExtMemoryBudget)
  14742. {
  14743. if(m_Budget.m_OperationsSinceBudgetFetch < 30)
  14744. {
  14745. VmaMutexLockRead lockRead(m_Budget.m_BudgetMutex, m_UseMutex);
  14746. for(uint32_t i = 0; i < heapCount; ++i, ++outBudget)
  14747. {
  14748. const uint32_t heapIndex = firstHeap + i;
  14749. outBudget->blockBytes = m_Budget.m_BlockBytes[heapIndex];
  14750. outBudget->allocationBytes = m_Budget.m_AllocationBytes[heapIndex];
  14751. if(m_Budget.m_VulkanUsage[heapIndex] + outBudget->blockBytes > m_Budget.m_BlockBytesAtBudgetFetch[heapIndex])
  14752. {
  14753. outBudget->usage = m_Budget.m_VulkanUsage[heapIndex] +
  14754. outBudget->blockBytes - m_Budget.m_BlockBytesAtBudgetFetch[heapIndex];
  14755. }
  14756. else
  14757. {
  14758. outBudget->usage = 0;
  14759. }
  14760. // Have to take MIN with heap size because explicit HeapSizeLimit is included in it.
  14761. outBudget->budget = VMA_MIN(
  14762. m_Budget.m_VulkanBudget[heapIndex], m_MemProps.memoryHeaps[heapIndex].size);
  14763. }
  14764. }
  14765. else
  14766. {
  14767. UpdateVulkanBudget(); // Outside of mutex lock
  14768. GetBudget(outBudget, firstHeap, heapCount); // Recursion
  14769. }
  14770. }
  14771. else
  14772. #endif
  14773. {
  14774. for(uint32_t i = 0; i < heapCount; ++i, ++outBudget)
  14775. {
  14776. const uint32_t heapIndex = firstHeap + i;
  14777. outBudget->blockBytes = m_Budget.m_BlockBytes[heapIndex];
  14778. outBudget->allocationBytes = m_Budget.m_AllocationBytes[heapIndex];
  14779. outBudget->usage = outBudget->blockBytes;
  14780. outBudget->budget = m_MemProps.memoryHeaps[heapIndex].size * 8 / 10; // 80% heuristics.
  14781. }
  14782. }
  14783. }
  14784. static const uint32_t VMA_VENDOR_ID_AMD = 4098;
  14785. VkResult VmaAllocator_T::DefragmentationBegin(
  14786. const VmaDefragmentationInfo2& info,
  14787. VmaDefragmentationStats* pStats,
  14788. VmaDefragmentationContext* pContext)
  14789. {
  14790. if(info.pAllocationsChanged != VMA_NULL)
  14791. {
  14792. memset(info.pAllocationsChanged, 0, info.allocationCount * sizeof(VkBool32));
  14793. }
  14794. *pContext = vma_new(this, VmaDefragmentationContext_T)(
  14795. this, m_CurrentFrameIndex.load(), info.flags, pStats);
  14796. (*pContext)->AddPools(info.poolCount, info.pPools);
  14797. (*pContext)->AddAllocations(
  14798. info.allocationCount, info.pAllocations, info.pAllocationsChanged);
  14799. VkResult res = (*pContext)->Defragment(
  14800. info.maxCpuBytesToMove, info.maxCpuAllocationsToMove,
  14801. info.maxGpuBytesToMove, info.maxGpuAllocationsToMove,
  14802. info.commandBuffer, pStats, info.flags);
  14803. if(res != VK_NOT_READY)
  14804. {
  14805. vma_delete(this, *pContext);
  14806. *pContext = VMA_NULL;
  14807. }
  14808. return res;
  14809. }
  14810. VkResult VmaAllocator_T::DefragmentationEnd(
  14811. VmaDefragmentationContext context)
  14812. {
  14813. vma_delete(this, context);
  14814. return VK_SUCCESS;
  14815. }
  14816. VkResult VmaAllocator_T::DefragmentationPassBegin(
  14817. VmaDefragmentationPassInfo* pInfo,
  14818. VmaDefragmentationContext context)
  14819. {
  14820. return context->DefragmentPassBegin(pInfo);
  14821. }
  14822. VkResult VmaAllocator_T::DefragmentationPassEnd(
  14823. VmaDefragmentationContext context)
  14824. {
  14825. return context->DefragmentPassEnd();
  14826. }
  14827. void VmaAllocator_T::GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo)
  14828. {
  14829. if(hAllocation->CanBecomeLost())
  14830. {
  14831. /*
  14832. Warning: This is a carefully designed algorithm.
  14833. Do not modify unless you really know what you're doing :)
  14834. */
  14835. const uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load();
  14836. uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex();
  14837. for(;;)
  14838. {
  14839. if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST)
  14840. {
  14841. pAllocationInfo->memoryType = UINT32_MAX;
  14842. pAllocationInfo->deviceMemory = VK_NULL_HANDLE;
  14843. pAllocationInfo->offset = 0;
  14844. pAllocationInfo->size = hAllocation->GetSize();
  14845. pAllocationInfo->pMappedData = VMA_NULL;
  14846. pAllocationInfo->pUserData = hAllocation->GetUserData();
  14847. return;
  14848. }
  14849. else if(localLastUseFrameIndex == localCurrFrameIndex)
  14850. {
  14851. pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex();
  14852. pAllocationInfo->deviceMemory = hAllocation->GetMemory();
  14853. pAllocationInfo->offset = hAllocation->GetOffset();
  14854. pAllocationInfo->size = hAllocation->GetSize();
  14855. pAllocationInfo->pMappedData = VMA_NULL;
  14856. pAllocationInfo->pUserData = hAllocation->GetUserData();
  14857. return;
  14858. }
  14859. else // Last use time earlier than current time.
  14860. {
  14861. if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex))
  14862. {
  14863. localLastUseFrameIndex = localCurrFrameIndex;
  14864. }
  14865. }
  14866. }
  14867. }
  14868. else
  14869. {
  14870. #if VMA_STATS_STRING_ENABLED
  14871. uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load();
  14872. uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex();
  14873. for(;;)
  14874. {
  14875. VMA_ASSERT(localLastUseFrameIndex != VMA_FRAME_INDEX_LOST);
  14876. if(localLastUseFrameIndex == localCurrFrameIndex)
  14877. {
  14878. break;
  14879. }
  14880. else // Last use time earlier than current time.
  14881. {
  14882. if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex))
  14883. {
  14884. localLastUseFrameIndex = localCurrFrameIndex;
  14885. }
  14886. }
  14887. }
  14888. #endif
  14889. pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex();
  14890. pAllocationInfo->deviceMemory = hAllocation->GetMemory();
  14891. pAllocationInfo->offset = hAllocation->GetOffset();
  14892. pAllocationInfo->size = hAllocation->GetSize();
  14893. pAllocationInfo->pMappedData = hAllocation->GetMappedData();
  14894. pAllocationInfo->pUserData = hAllocation->GetUserData();
  14895. }
  14896. }
  14897. bool VmaAllocator_T::TouchAllocation(VmaAllocation hAllocation)
  14898. {
  14899. // This is a stripped-down version of VmaAllocator_T::GetAllocationInfo.
  14900. if(hAllocation->CanBecomeLost())
  14901. {
  14902. uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load();
  14903. uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex();
  14904. for(;;)
  14905. {
  14906. if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST)
  14907. {
  14908. return false;
  14909. }
  14910. else if(localLastUseFrameIndex == localCurrFrameIndex)
  14911. {
  14912. return true;
  14913. }
  14914. else // Last use time earlier than current time.
  14915. {
  14916. if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex))
  14917. {
  14918. localLastUseFrameIndex = localCurrFrameIndex;
  14919. }
  14920. }
  14921. }
  14922. }
  14923. else
  14924. {
  14925. #if VMA_STATS_STRING_ENABLED
  14926. uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load();
  14927. uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex();
  14928. for(;;)
  14929. {
  14930. VMA_ASSERT(localLastUseFrameIndex != VMA_FRAME_INDEX_LOST);
  14931. if(localLastUseFrameIndex == localCurrFrameIndex)
  14932. {
  14933. break;
  14934. }
  14935. else // Last use time earlier than current time.
  14936. {
  14937. if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex))
  14938. {
  14939. localLastUseFrameIndex = localCurrFrameIndex;
  14940. }
  14941. }
  14942. }
  14943. #endif
  14944. return true;
  14945. }
  14946. }
  14947. VkResult VmaAllocator_T::CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool)
  14948. {
  14949. VMA_DEBUG_LOG(" CreatePool: MemoryTypeIndex=%u, flags=%u", pCreateInfo->memoryTypeIndex, pCreateInfo->flags);
  14950. VmaPoolCreateInfo newCreateInfo = *pCreateInfo;
  14951. // Protection against uninitialized new structure member. If garbage data are left there, this pointer dereference would crash.
  14952. if(pCreateInfo->pMemoryAllocateNext)
  14953. {
  14954. VMA_ASSERT(((const VkBaseInStructure*)pCreateInfo->pMemoryAllocateNext)->sType != 0);
  14955. }
  14956. if(newCreateInfo.maxBlockCount == 0)
  14957. {
  14958. newCreateInfo.maxBlockCount = SIZE_MAX;
  14959. }
  14960. if(newCreateInfo.minBlockCount > newCreateInfo.maxBlockCount)
  14961. {
  14962. return VK_ERROR_INITIALIZATION_FAILED;
  14963. }
  14964. // Memory type index out of range or forbidden.
  14965. if(pCreateInfo->memoryTypeIndex >= GetMemoryTypeCount() ||
  14966. ((1u << pCreateInfo->memoryTypeIndex) & m_GlobalMemoryTypeBits) == 0)
  14967. {
  14968. return VK_ERROR_FEATURE_NOT_PRESENT;
  14969. }
  14970. if(newCreateInfo.minAllocationAlignment > 0)
  14971. {
  14972. VMA_ASSERT(VmaIsPow2(newCreateInfo.minAllocationAlignment));
  14973. }
  14974. const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(newCreateInfo.memoryTypeIndex);
  14975. *pPool = vma_new(this, VmaPool_T)(this, newCreateInfo, preferredBlockSize);
  14976. VkResult res = (*pPool)->m_BlockVector.CreateMinBlocks();
  14977. if(res != VK_SUCCESS)
  14978. {
  14979. vma_delete(this, *pPool);
  14980. *pPool = VMA_NULL;
  14981. return res;
  14982. }
  14983. // Add to m_Pools.
  14984. {
  14985. VmaMutexLockWrite lock(m_PoolsMutex, m_UseMutex);
  14986. (*pPool)->SetId(m_NextPoolId++);
  14987. m_Pools.PushBack(*pPool);
  14988. }
  14989. return VK_SUCCESS;
  14990. }
  14991. void VmaAllocator_T::DestroyPool(VmaPool pool)
  14992. {
  14993. // Remove from m_Pools.
  14994. {
  14995. VmaMutexLockWrite lock(m_PoolsMutex, m_UseMutex);
  14996. m_Pools.Remove(pool);
  14997. }
  14998. vma_delete(this, pool);
  14999. }
  15000. void VmaAllocator_T::GetPoolStats(VmaPool pool, VmaPoolStats* pPoolStats)
  15001. {
  15002. pool->m_BlockVector.GetPoolStats(pPoolStats);
  15003. }
  15004. void VmaAllocator_T::SetCurrentFrameIndex(uint32_t frameIndex)
  15005. {
  15006. m_CurrentFrameIndex.store(frameIndex);
  15007. #if VMA_MEMORY_BUDGET
  15008. if(m_UseExtMemoryBudget)
  15009. {
  15010. UpdateVulkanBudget();
  15011. }
  15012. #endif // #if VMA_MEMORY_BUDGET
  15013. }
  15014. void VmaAllocator_T::MakePoolAllocationsLost(
  15015. VmaPool hPool,
  15016. size_t* pLostAllocationCount)
  15017. {
  15018. hPool->m_BlockVector.MakePoolAllocationsLost(
  15019. m_CurrentFrameIndex.load(),
  15020. pLostAllocationCount);
  15021. }
  15022. VkResult VmaAllocator_T::CheckPoolCorruption(VmaPool hPool)
  15023. {
  15024. return hPool->m_BlockVector.CheckCorruption();
  15025. }
  15026. VkResult VmaAllocator_T::CheckCorruption(uint32_t memoryTypeBits)
  15027. {
  15028. VkResult finalRes = VK_ERROR_FEATURE_NOT_PRESENT;
  15029. // Process default pools.
  15030. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  15031. {
  15032. if(((1u << memTypeIndex) & memoryTypeBits) != 0)
  15033. {
  15034. VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex];
  15035. VMA_ASSERT(pBlockVector);
  15036. VkResult localRes = pBlockVector->CheckCorruption();
  15037. switch(localRes)
  15038. {
  15039. case VK_ERROR_FEATURE_NOT_PRESENT:
  15040. break;
  15041. case VK_SUCCESS:
  15042. finalRes = VK_SUCCESS;
  15043. break;
  15044. default:
  15045. return localRes;
  15046. }
  15047. }
  15048. }
  15049. // Process custom pools.
  15050. {
  15051. VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex);
  15052. for(VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool))
  15053. {
  15054. if(((1u << pool->m_BlockVector.GetMemoryTypeIndex()) & memoryTypeBits) != 0)
  15055. {
  15056. VkResult localRes = pool->m_BlockVector.CheckCorruption();
  15057. switch(localRes)
  15058. {
  15059. case VK_ERROR_FEATURE_NOT_PRESENT:
  15060. break;
  15061. case VK_SUCCESS:
  15062. finalRes = VK_SUCCESS;
  15063. break;
  15064. default:
  15065. return localRes;
  15066. }
  15067. }
  15068. }
  15069. }
  15070. return finalRes;
  15071. }
  15072. void VmaAllocator_T::CreateLostAllocation(VmaAllocation* pAllocation)
  15073. {
  15074. *pAllocation = m_AllocationObjectAllocator.Allocate(VMA_FRAME_INDEX_LOST, false);
  15075. (*pAllocation)->InitLost();
  15076. }
  15077. // An object that increments given atomic but decrements it back in the destructor unless Commit() is called.
  15078. template<typename T>
  15079. struct AtomicTransactionalIncrement
  15080. {
  15081. public:
  15082. typedef std::atomic<T> AtomicT;
  15083. ~AtomicTransactionalIncrement()
  15084. {
  15085. if(m_Atomic)
  15086. --(*m_Atomic);
  15087. }
  15088. T Increment(AtomicT* atomic)
  15089. {
  15090. m_Atomic = atomic;
  15091. return m_Atomic->fetch_add(1);
  15092. }
  15093. void Commit()
  15094. {
  15095. m_Atomic = nullptr;
  15096. }
  15097. private:
  15098. AtomicT* m_Atomic = nullptr;
  15099. };
  15100. VkResult VmaAllocator_T::AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory)
  15101. {
  15102. AtomicTransactionalIncrement<uint32_t> deviceMemoryCountIncrement;
  15103. const uint64_t prevDeviceMemoryCount = deviceMemoryCountIncrement.Increment(&m_DeviceMemoryCount);
  15104. #if VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT
  15105. if(prevDeviceMemoryCount >= m_PhysicalDeviceProperties.limits.maxMemoryAllocationCount)
  15106. {
  15107. return VK_ERROR_TOO_MANY_OBJECTS;
  15108. }
  15109. #endif
  15110. const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(pAllocateInfo->memoryTypeIndex);
  15111. // HeapSizeLimit is in effect for this heap.
  15112. if((m_HeapSizeLimitMask & (1u << heapIndex)) != 0)
  15113. {
  15114. const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size;
  15115. VkDeviceSize blockBytes = m_Budget.m_BlockBytes[heapIndex];
  15116. for(;;)
  15117. {
  15118. const VkDeviceSize blockBytesAfterAllocation = blockBytes + pAllocateInfo->allocationSize;
  15119. if(blockBytesAfterAllocation > heapSize)
  15120. {
  15121. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  15122. }
  15123. if(m_Budget.m_BlockBytes[heapIndex].compare_exchange_strong(blockBytes, blockBytesAfterAllocation))
  15124. {
  15125. break;
  15126. }
  15127. }
  15128. }
  15129. else
  15130. {
  15131. m_Budget.m_BlockBytes[heapIndex] += pAllocateInfo->allocationSize;
  15132. }
  15133. // VULKAN CALL vkAllocateMemory.
  15134. VkResult res = (*m_VulkanFunctions.vkAllocateMemory)(m_hDevice, pAllocateInfo, GetAllocationCallbacks(), pMemory);
  15135. if(res == VK_SUCCESS)
  15136. {
  15137. #if VMA_MEMORY_BUDGET
  15138. ++m_Budget.m_OperationsSinceBudgetFetch;
  15139. #endif
  15140. // Informative callback.
  15141. if(m_DeviceMemoryCallbacks.pfnAllocate != VMA_NULL)
  15142. {
  15143. (*m_DeviceMemoryCallbacks.pfnAllocate)(this, pAllocateInfo->memoryTypeIndex, *pMemory, pAllocateInfo->allocationSize, m_DeviceMemoryCallbacks.pUserData);
  15144. }
  15145. deviceMemoryCountIncrement.Commit();
  15146. }
  15147. else
  15148. {
  15149. m_Budget.m_BlockBytes[heapIndex] -= pAllocateInfo->allocationSize;
  15150. }
  15151. return res;
  15152. }
  15153. void VmaAllocator_T::FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory)
  15154. {
  15155. // Informative callback.
  15156. if(m_DeviceMemoryCallbacks.pfnFree != VMA_NULL)
  15157. {
  15158. (*m_DeviceMemoryCallbacks.pfnFree)(this, memoryType, hMemory, size, m_DeviceMemoryCallbacks.pUserData);
  15159. }
  15160. // VULKAN CALL vkFreeMemory.
  15161. (*m_VulkanFunctions.vkFreeMemory)(m_hDevice, hMemory, GetAllocationCallbacks());
  15162. m_Budget.m_BlockBytes[MemoryTypeIndexToHeapIndex(memoryType)] -= size;
  15163. --m_DeviceMemoryCount;
  15164. }
  15165. VkResult VmaAllocator_T::BindVulkanBuffer(
  15166. VkDeviceMemory memory,
  15167. VkDeviceSize memoryOffset,
  15168. VkBuffer buffer,
  15169. const void* pNext)
  15170. {
  15171. if(pNext != VMA_NULL)
  15172. {
  15173. #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2
  15174. if((m_UseKhrBindMemory2 || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) &&
  15175. m_VulkanFunctions.vkBindBufferMemory2KHR != VMA_NULL)
  15176. {
  15177. VkBindBufferMemoryInfoKHR bindBufferMemoryInfo = { VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR };
  15178. bindBufferMemoryInfo.pNext = pNext;
  15179. bindBufferMemoryInfo.buffer = buffer;
  15180. bindBufferMemoryInfo.memory = memory;
  15181. bindBufferMemoryInfo.memoryOffset = memoryOffset;
  15182. return (*m_VulkanFunctions.vkBindBufferMemory2KHR)(m_hDevice, 1, &bindBufferMemoryInfo);
  15183. }
  15184. else
  15185. #endif // #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2
  15186. {
  15187. return VK_ERROR_EXTENSION_NOT_PRESENT;
  15188. }
  15189. }
  15190. else
  15191. {
  15192. return (*m_VulkanFunctions.vkBindBufferMemory)(m_hDevice, buffer, memory, memoryOffset);
  15193. }
  15194. }
  15195. VkResult VmaAllocator_T::BindVulkanImage(
  15196. VkDeviceMemory memory,
  15197. VkDeviceSize memoryOffset,
  15198. VkImage image,
  15199. const void* pNext)
  15200. {
  15201. if(pNext != VMA_NULL)
  15202. {
  15203. #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2
  15204. if((m_UseKhrBindMemory2 || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) &&
  15205. m_VulkanFunctions.vkBindImageMemory2KHR != VMA_NULL)
  15206. {
  15207. VkBindImageMemoryInfoKHR bindBufferMemoryInfo = { VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO_KHR };
  15208. bindBufferMemoryInfo.pNext = pNext;
  15209. bindBufferMemoryInfo.image = image;
  15210. bindBufferMemoryInfo.memory = memory;
  15211. bindBufferMemoryInfo.memoryOffset = memoryOffset;
  15212. return (*m_VulkanFunctions.vkBindImageMemory2KHR)(m_hDevice, 1, &bindBufferMemoryInfo);
  15213. }
  15214. else
  15215. #endif // #if VMA_BIND_MEMORY2
  15216. {
  15217. return VK_ERROR_EXTENSION_NOT_PRESENT;
  15218. }
  15219. }
  15220. else
  15221. {
  15222. return (*m_VulkanFunctions.vkBindImageMemory)(m_hDevice, image, memory, memoryOffset);
  15223. }
  15224. }
  15225. VkResult VmaAllocator_T::Map(VmaAllocation hAllocation, void** ppData)
  15226. {
  15227. if(hAllocation->CanBecomeLost())
  15228. {
  15229. return VK_ERROR_MEMORY_MAP_FAILED;
  15230. }
  15231. switch(hAllocation->GetType())
  15232. {
  15233. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  15234. {
  15235. VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
  15236. char *pBytes = VMA_NULL;
  15237. VkResult res = pBlock->Map(this, 1, (void**)&pBytes);
  15238. if(res == VK_SUCCESS)
  15239. {
  15240. *ppData = pBytes + (ptrdiff_t)hAllocation->GetOffset();
  15241. hAllocation->BlockAllocMap();
  15242. }
  15243. return res;
  15244. }
  15245. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  15246. return hAllocation->DedicatedAllocMap(this, ppData);
  15247. default:
  15248. VMA_ASSERT(0);
  15249. return VK_ERROR_MEMORY_MAP_FAILED;
  15250. }
  15251. }
  15252. void VmaAllocator_T::Unmap(VmaAllocation hAllocation)
  15253. {
  15254. switch(hAllocation->GetType())
  15255. {
  15256. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  15257. {
  15258. VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
  15259. hAllocation->BlockAllocUnmap();
  15260. pBlock->Unmap(this, 1);
  15261. }
  15262. break;
  15263. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  15264. hAllocation->DedicatedAllocUnmap(this);
  15265. break;
  15266. default:
  15267. VMA_ASSERT(0);
  15268. }
  15269. }
  15270. VkResult VmaAllocator_T::BindBufferMemory(
  15271. VmaAllocation hAllocation,
  15272. VkDeviceSize allocationLocalOffset,
  15273. VkBuffer hBuffer,
  15274. const void* pNext)
  15275. {
  15276. VkResult res = VK_SUCCESS;
  15277. switch(hAllocation->GetType())
  15278. {
  15279. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  15280. res = BindVulkanBuffer(hAllocation->GetMemory(), allocationLocalOffset, hBuffer, pNext);
  15281. break;
  15282. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  15283. {
  15284. VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
  15285. VMA_ASSERT(pBlock && "Binding buffer to allocation that doesn't belong to any block. Is the allocation lost?");
  15286. res = pBlock->BindBufferMemory(this, hAllocation, allocationLocalOffset, hBuffer, pNext);
  15287. break;
  15288. }
  15289. default:
  15290. VMA_ASSERT(0);
  15291. }
  15292. return res;
  15293. }
  15294. VkResult VmaAllocator_T::BindImageMemory(
  15295. VmaAllocation hAllocation,
  15296. VkDeviceSize allocationLocalOffset,
  15297. VkImage hImage,
  15298. const void* pNext)
  15299. {
  15300. VkResult res = VK_SUCCESS;
  15301. switch(hAllocation->GetType())
  15302. {
  15303. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  15304. res = BindVulkanImage(hAllocation->GetMemory(), allocationLocalOffset, hImage, pNext);
  15305. break;
  15306. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  15307. {
  15308. VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock();
  15309. VMA_ASSERT(pBlock && "Binding image to allocation that doesn't belong to any block. Is the allocation lost?");
  15310. res = pBlock->BindImageMemory(this, hAllocation, allocationLocalOffset, hImage, pNext);
  15311. break;
  15312. }
  15313. default:
  15314. VMA_ASSERT(0);
  15315. }
  15316. return res;
  15317. }
  15318. VkResult VmaAllocator_T::FlushOrInvalidateAllocation(
  15319. VmaAllocation hAllocation,
  15320. VkDeviceSize offset, VkDeviceSize size,
  15321. VMA_CACHE_OPERATION op)
  15322. {
  15323. VkResult res = VK_SUCCESS;
  15324. VkMappedMemoryRange memRange = {};
  15325. if(GetFlushOrInvalidateRange(hAllocation, offset, size, memRange))
  15326. {
  15327. switch(op)
  15328. {
  15329. case VMA_CACHE_FLUSH:
  15330. res = (*GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hDevice, 1, &memRange);
  15331. break;
  15332. case VMA_CACHE_INVALIDATE:
  15333. res = (*GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hDevice, 1, &memRange);
  15334. break;
  15335. default:
  15336. VMA_ASSERT(0);
  15337. }
  15338. }
  15339. // else: Just ignore this call.
  15340. return res;
  15341. }
  15342. VkResult VmaAllocator_T::FlushOrInvalidateAllocations(
  15343. uint32_t allocationCount,
  15344. const VmaAllocation* allocations,
  15345. const VkDeviceSize* offsets, const VkDeviceSize* sizes,
  15346. VMA_CACHE_OPERATION op)
  15347. {
  15348. typedef VmaStlAllocator<VkMappedMemoryRange> RangeAllocator;
  15349. typedef VmaSmallVector<VkMappedMemoryRange, RangeAllocator, 16> RangeVector;
  15350. RangeVector ranges = RangeVector(RangeAllocator(GetAllocationCallbacks()));
  15351. for(uint32_t allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  15352. {
  15353. const VmaAllocation alloc = allocations[allocIndex];
  15354. const VkDeviceSize offset = offsets != VMA_NULL ? offsets[allocIndex] : 0;
  15355. const VkDeviceSize size = sizes != VMA_NULL ? sizes[allocIndex] : VK_WHOLE_SIZE;
  15356. VkMappedMemoryRange newRange;
  15357. if(GetFlushOrInvalidateRange(alloc, offset, size, newRange))
  15358. {
  15359. ranges.push_back(newRange);
  15360. }
  15361. }
  15362. VkResult res = VK_SUCCESS;
  15363. if(!ranges.empty())
  15364. {
  15365. switch(op)
  15366. {
  15367. case VMA_CACHE_FLUSH:
  15368. res = (*GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hDevice, (uint32_t)ranges.size(), ranges.data());
  15369. break;
  15370. case VMA_CACHE_INVALIDATE:
  15371. res = (*GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hDevice, (uint32_t)ranges.size(), ranges.data());
  15372. break;
  15373. default:
  15374. VMA_ASSERT(0);
  15375. }
  15376. }
  15377. // else: Just ignore this call.
  15378. return res;
  15379. }
  15380. void VmaAllocator_T::FreeDedicatedMemory(const VmaAllocation allocation)
  15381. {
  15382. VMA_ASSERT(allocation && allocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  15383. const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
  15384. {
  15385. VmaMutexLockWrite lock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
  15386. DedicatedAllocationLinkedList& dedicatedAllocations = m_DedicatedAllocations[memTypeIndex];
  15387. dedicatedAllocations.Remove(allocation);
  15388. }
  15389. VkDeviceMemory hMemory = allocation->GetMemory();
  15390. /*
  15391. There is no need to call this, because Vulkan spec allows to skip vkUnmapMemory
  15392. before vkFreeMemory.
  15393. if(allocation->GetMappedData() != VMA_NULL)
  15394. {
  15395. (*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory);
  15396. }
  15397. */
  15398. FreeVulkanMemory(memTypeIndex, allocation->GetSize(), hMemory);
  15399. VMA_DEBUG_LOG(" Freed DedicatedMemory MemoryTypeIndex=%u", memTypeIndex);
  15400. }
  15401. uint32_t VmaAllocator_T::CalculateGpuDefragmentationMemoryTypeBits() const
  15402. {
  15403. VkBufferCreateInfo dummyBufCreateInfo;
  15404. VmaFillGpuDefragmentationBufferCreateInfo(dummyBufCreateInfo);
  15405. uint32_t memoryTypeBits = 0;
  15406. // Create buffer.
  15407. VkBuffer buf = VK_NULL_HANDLE;
  15408. VkResult res = (*GetVulkanFunctions().vkCreateBuffer)(
  15409. m_hDevice, &dummyBufCreateInfo, GetAllocationCallbacks(), &buf);
  15410. if(res == VK_SUCCESS)
  15411. {
  15412. // Query for supported memory types.
  15413. VkMemoryRequirements memReq;
  15414. (*GetVulkanFunctions().vkGetBufferMemoryRequirements)(m_hDevice, buf, &memReq);
  15415. memoryTypeBits = memReq.memoryTypeBits;
  15416. // Destroy buffer.
  15417. (*GetVulkanFunctions().vkDestroyBuffer)(m_hDevice, buf, GetAllocationCallbacks());
  15418. }
  15419. return memoryTypeBits;
  15420. }
  15421. uint32_t VmaAllocator_T::CalculateGlobalMemoryTypeBits() const
  15422. {
  15423. // Make sure memory information is already fetched.
  15424. VMA_ASSERT(GetMemoryTypeCount() > 0);
  15425. uint32_t memoryTypeBits = UINT32_MAX;
  15426. if(!m_UseAmdDeviceCoherentMemory)
  15427. {
  15428. // Exclude memory types that have VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD.
  15429. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  15430. {
  15431. if((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY) != 0)
  15432. {
  15433. memoryTypeBits &= ~(1u << memTypeIndex);
  15434. }
  15435. }
  15436. }
  15437. return memoryTypeBits;
  15438. }
  15439. bool VmaAllocator_T::GetFlushOrInvalidateRange(
  15440. VmaAllocation allocation,
  15441. VkDeviceSize offset, VkDeviceSize size,
  15442. VkMappedMemoryRange& outRange) const
  15443. {
  15444. const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
  15445. if(size > 0 && IsMemoryTypeNonCoherent(memTypeIndex))
  15446. {
  15447. const VkDeviceSize nonCoherentAtomSize = m_PhysicalDeviceProperties.limits.nonCoherentAtomSize;
  15448. const VkDeviceSize allocationSize = allocation->GetSize();
  15449. VMA_ASSERT(offset <= allocationSize);
  15450. outRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  15451. outRange.pNext = VMA_NULL;
  15452. outRange.memory = allocation->GetMemory();
  15453. switch(allocation->GetType())
  15454. {
  15455. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  15456. outRange.offset = VmaAlignDown(offset, nonCoherentAtomSize);
  15457. if(size == VK_WHOLE_SIZE)
  15458. {
  15459. outRange.size = allocationSize - outRange.offset;
  15460. }
  15461. else
  15462. {
  15463. VMA_ASSERT(offset + size <= allocationSize);
  15464. outRange.size = VMA_MIN(
  15465. VmaAlignUp(size + (offset - outRange.offset), nonCoherentAtomSize),
  15466. allocationSize - outRange.offset);
  15467. }
  15468. break;
  15469. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  15470. {
  15471. // 1. Still within this allocation.
  15472. outRange.offset = VmaAlignDown(offset, nonCoherentAtomSize);
  15473. if(size == VK_WHOLE_SIZE)
  15474. {
  15475. size = allocationSize - offset;
  15476. }
  15477. else
  15478. {
  15479. VMA_ASSERT(offset + size <= allocationSize);
  15480. }
  15481. outRange.size = VmaAlignUp(size + (offset - outRange.offset), nonCoherentAtomSize);
  15482. // 2. Adjust to whole block.
  15483. const VkDeviceSize allocationOffset = allocation->GetOffset();
  15484. VMA_ASSERT(allocationOffset % nonCoherentAtomSize == 0);
  15485. const VkDeviceSize blockSize = allocation->GetBlock()->m_pMetadata->GetSize();
  15486. outRange.offset += allocationOffset;
  15487. outRange.size = VMA_MIN(outRange.size, blockSize - outRange.offset);
  15488. break;
  15489. }
  15490. default:
  15491. VMA_ASSERT(0);
  15492. }
  15493. return true;
  15494. }
  15495. return false;
  15496. }
  15497. #if VMA_MEMORY_BUDGET
  15498. void VmaAllocator_T::UpdateVulkanBudget()
  15499. {
  15500. VMA_ASSERT(m_UseExtMemoryBudget);
  15501. VkPhysicalDeviceMemoryProperties2KHR memProps = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2_KHR };
  15502. VkPhysicalDeviceMemoryBudgetPropertiesEXT budgetProps = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT };
  15503. VmaPnextChainPushFront(&memProps, &budgetProps);
  15504. GetVulkanFunctions().vkGetPhysicalDeviceMemoryProperties2KHR(m_PhysicalDevice, &memProps);
  15505. {
  15506. VmaMutexLockWrite lockWrite(m_Budget.m_BudgetMutex, m_UseMutex);
  15507. for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex)
  15508. {
  15509. m_Budget.m_VulkanUsage[heapIndex] = budgetProps.heapUsage[heapIndex];
  15510. m_Budget.m_VulkanBudget[heapIndex] = budgetProps.heapBudget[heapIndex];
  15511. m_Budget.m_BlockBytesAtBudgetFetch[heapIndex] = m_Budget.m_BlockBytes[heapIndex].load();
  15512. // Some bugged drivers return the budget incorrectly, e.g. 0 or much bigger than heap size.
  15513. if(m_Budget.m_VulkanBudget[heapIndex] == 0)
  15514. {
  15515. m_Budget.m_VulkanBudget[heapIndex] = m_MemProps.memoryHeaps[heapIndex].size * 8 / 10; // 80% heuristics.
  15516. }
  15517. else if(m_Budget.m_VulkanBudget[heapIndex] > m_MemProps.memoryHeaps[heapIndex].size)
  15518. {
  15519. m_Budget.m_VulkanBudget[heapIndex] = m_MemProps.memoryHeaps[heapIndex].size;
  15520. }
  15521. if(m_Budget.m_VulkanUsage[heapIndex] == 0 && m_Budget.m_BlockBytesAtBudgetFetch[heapIndex] > 0)
  15522. {
  15523. m_Budget.m_VulkanUsage[heapIndex] = m_Budget.m_BlockBytesAtBudgetFetch[heapIndex];
  15524. }
  15525. }
  15526. m_Budget.m_OperationsSinceBudgetFetch = 0;
  15527. }
  15528. }
  15529. #endif // #if VMA_MEMORY_BUDGET
  15530. void VmaAllocator_T::FillAllocation(const VmaAllocation hAllocation, uint8_t pattern)
  15531. {
  15532. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS &&
  15533. !hAllocation->CanBecomeLost() &&
  15534. (m_MemProps.memoryTypes[hAllocation->GetMemoryTypeIndex()].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
  15535. {
  15536. void* pData = VMA_NULL;
  15537. VkResult res = Map(hAllocation, &pData);
  15538. if(res == VK_SUCCESS)
  15539. {
  15540. memset(pData, (int)pattern, (size_t)hAllocation->GetSize());
  15541. FlushOrInvalidateAllocation(hAllocation, 0, VK_WHOLE_SIZE, VMA_CACHE_FLUSH);
  15542. Unmap(hAllocation);
  15543. }
  15544. else
  15545. {
  15546. VMA_ASSERT(0 && "VMA_DEBUG_INITIALIZE_ALLOCATIONS is enabled, but couldn't map memory to fill allocation.");
  15547. }
  15548. }
  15549. }
  15550. uint32_t VmaAllocator_T::GetGpuDefragmentationMemoryTypeBits()
  15551. {
  15552. uint32_t memoryTypeBits = m_GpuDefragmentationMemoryTypeBits.load();
  15553. if(memoryTypeBits == UINT32_MAX)
  15554. {
  15555. memoryTypeBits = CalculateGpuDefragmentationMemoryTypeBits();
  15556. m_GpuDefragmentationMemoryTypeBits.store(memoryTypeBits);
  15557. }
  15558. return memoryTypeBits;
  15559. }
  15560. #if VMA_STATS_STRING_ENABLED
  15561. void VmaAllocator_T::PrintDetailedMap(VmaJsonWriter& json)
  15562. {
  15563. bool dedicatedAllocationsStarted = false;
  15564. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  15565. {
  15566. VmaMutexLockRead dedicatedAllocationsLock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
  15567. DedicatedAllocationLinkedList& dedicatedAllocList = m_DedicatedAllocations[memTypeIndex];
  15568. if(!dedicatedAllocList.IsEmpty())
  15569. {
  15570. if(dedicatedAllocationsStarted == false)
  15571. {
  15572. dedicatedAllocationsStarted = true;
  15573. json.WriteString("DedicatedAllocations");
  15574. json.BeginObject();
  15575. }
  15576. json.BeginString("Type ");
  15577. json.ContinueString(memTypeIndex);
  15578. json.EndString();
  15579. json.BeginArray();
  15580. for(VmaAllocation alloc = dedicatedAllocList.Front();
  15581. alloc != VMA_NULL; alloc = dedicatedAllocList.GetNext(alloc))
  15582. {
  15583. json.BeginObject(true);
  15584. alloc->PrintParameters(json);
  15585. json.EndObject();
  15586. }
  15587. json.EndArray();
  15588. }
  15589. }
  15590. if(dedicatedAllocationsStarted)
  15591. {
  15592. json.EndObject();
  15593. }
  15594. // Default pools
  15595. {
  15596. bool allocationsStarted = false;
  15597. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  15598. {
  15599. if(m_pBlockVectors[memTypeIndex]->IsEmpty() == false)
  15600. {
  15601. if(allocationsStarted == false)
  15602. {
  15603. allocationsStarted = true;
  15604. json.WriteString("DefaultPools");
  15605. json.BeginObject();
  15606. }
  15607. json.BeginString("Type ");
  15608. json.ContinueString(memTypeIndex);
  15609. json.EndString();
  15610. m_pBlockVectors[memTypeIndex]->PrintDetailedMap(json);
  15611. }
  15612. }
  15613. if(allocationsStarted)
  15614. {
  15615. json.EndObject();
  15616. }
  15617. }
  15618. // Small buffer pools
  15619. {
  15620. bool allocationsStarted = false;
  15621. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  15622. {
  15623. if(m_pSmallBufferBlockVectors[memTypeIndex]->IsEmpty() == false)
  15624. {
  15625. if(allocationsStarted == false)
  15626. {
  15627. allocationsStarted = true;
  15628. json.WriteString("SmallBufferPools");
  15629. json.BeginObject();
  15630. }
  15631. json.BeginString("Type ");
  15632. json.ContinueString(memTypeIndex);
  15633. json.EndString();
  15634. m_pSmallBufferBlockVectors[memTypeIndex]->PrintDetailedMap(json);
  15635. }
  15636. }
  15637. if(allocationsStarted)
  15638. {
  15639. json.EndObject();
  15640. }
  15641. }
  15642. // Custom pools
  15643. {
  15644. VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex);
  15645. if(!m_Pools.IsEmpty())
  15646. {
  15647. json.WriteString("Pools");
  15648. json.BeginObject();
  15649. for(VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool))
  15650. {
  15651. json.BeginString();
  15652. json.ContinueString(pool->GetId());
  15653. json.EndString();
  15654. pool->m_BlockVector.PrintDetailedMap(json);
  15655. }
  15656. json.EndObject();
  15657. }
  15658. }
  15659. }
  15660. #endif // #if VMA_STATS_STRING_ENABLED
  15661. ////////////////////////////////////////////////////////////////////////////////
  15662. // Public interface
  15663. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAllocator(
  15664. const VmaAllocatorCreateInfo* pCreateInfo,
  15665. VmaAllocator* pAllocator)
  15666. {
  15667. VMA_ASSERT(pCreateInfo && pAllocator);
  15668. VMA_ASSERT(pCreateInfo->vulkanApiVersion == 0 ||
  15669. (VK_VERSION_MAJOR(pCreateInfo->vulkanApiVersion) == 1 && VK_VERSION_MINOR(pCreateInfo->vulkanApiVersion) <= 2));
  15670. VMA_DEBUG_LOG("vmaCreateAllocator");
  15671. *pAllocator = vma_new(pCreateInfo->pAllocationCallbacks, VmaAllocator_T)(pCreateInfo);
  15672. return (*pAllocator)->Init(pCreateInfo);
  15673. }
  15674. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyAllocator(
  15675. VmaAllocator allocator)
  15676. {
  15677. if(allocator != VK_NULL_HANDLE)
  15678. {
  15679. VMA_DEBUG_LOG("vmaDestroyAllocator");
  15680. VkAllocationCallbacks allocationCallbacks = allocator->m_AllocationCallbacks;
  15681. vma_delete(&allocationCallbacks, allocator);
  15682. }
  15683. }
  15684. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocatorInfo(VmaAllocator allocator, VmaAllocatorInfo* pAllocatorInfo)
  15685. {
  15686. VMA_ASSERT(allocator && pAllocatorInfo);
  15687. pAllocatorInfo->instance = allocator->m_hInstance;
  15688. pAllocatorInfo->physicalDevice = allocator->GetPhysicalDevice();
  15689. pAllocatorInfo->device = allocator->m_hDevice;
  15690. }
  15691. VMA_CALL_PRE void VMA_CALL_POST vmaGetPhysicalDeviceProperties(
  15692. VmaAllocator allocator,
  15693. const VkPhysicalDeviceProperties **ppPhysicalDeviceProperties)
  15694. {
  15695. VMA_ASSERT(allocator && ppPhysicalDeviceProperties);
  15696. *ppPhysicalDeviceProperties = &allocator->m_PhysicalDeviceProperties;
  15697. }
  15698. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryProperties(
  15699. VmaAllocator allocator,
  15700. const VkPhysicalDeviceMemoryProperties** ppPhysicalDeviceMemoryProperties)
  15701. {
  15702. VMA_ASSERT(allocator && ppPhysicalDeviceMemoryProperties);
  15703. *ppPhysicalDeviceMemoryProperties = &allocator->m_MemProps;
  15704. }
  15705. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties(
  15706. VmaAllocator allocator,
  15707. uint32_t memoryTypeIndex,
  15708. VkMemoryPropertyFlags* pFlags)
  15709. {
  15710. VMA_ASSERT(allocator && pFlags);
  15711. VMA_ASSERT(memoryTypeIndex < allocator->GetMemoryTypeCount());
  15712. *pFlags = allocator->m_MemProps.memoryTypes[memoryTypeIndex].propertyFlags;
  15713. }
  15714. VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex(
  15715. VmaAllocator allocator,
  15716. uint32_t frameIndex)
  15717. {
  15718. VMA_ASSERT(allocator);
  15719. VMA_ASSERT(frameIndex != VMA_FRAME_INDEX_LOST);
  15720. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15721. allocator->SetCurrentFrameIndex(frameIndex);
  15722. }
  15723. VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStats(
  15724. VmaAllocator allocator,
  15725. VmaStats* pStats)
  15726. {
  15727. VMA_ASSERT(allocator && pStats);
  15728. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15729. allocator->CalculateStats(pStats);
  15730. }
  15731. VMA_CALL_PRE void VMA_CALL_POST vmaGetBudget(
  15732. VmaAllocator allocator,
  15733. VmaBudget* pBudget)
  15734. {
  15735. VMA_ASSERT(allocator && pBudget);
  15736. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15737. allocator->GetBudget(pBudget, 0, allocator->GetMemoryHeapCount());
  15738. }
  15739. #if VMA_STATS_STRING_ENABLED
  15740. VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString(
  15741. VmaAllocator allocator,
  15742. char** ppStatsString,
  15743. VkBool32 detailedMap)
  15744. {
  15745. VMA_ASSERT(allocator && ppStatsString);
  15746. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15747. VmaStringBuilder sb(allocator);
  15748. {
  15749. VmaJsonWriter json(allocator->GetAllocationCallbacks(), sb);
  15750. json.BeginObject();
  15751. VmaBudget budget[VK_MAX_MEMORY_HEAPS];
  15752. allocator->GetBudget(budget, 0, allocator->GetMemoryHeapCount());
  15753. VmaStats stats;
  15754. allocator->CalculateStats(&stats);
  15755. json.WriteString("Total");
  15756. VmaPrintStatInfo(json, stats.total);
  15757. for(uint32_t heapIndex = 0; heapIndex < allocator->GetMemoryHeapCount(); ++heapIndex)
  15758. {
  15759. json.BeginString("Heap ");
  15760. json.ContinueString(heapIndex);
  15761. json.EndString();
  15762. json.BeginObject();
  15763. json.WriteString("Size");
  15764. json.WriteNumber(allocator->m_MemProps.memoryHeaps[heapIndex].size);
  15765. json.WriteString("Flags");
  15766. json.BeginArray(true);
  15767. if((allocator->m_MemProps.memoryHeaps[heapIndex].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) != 0)
  15768. {
  15769. json.WriteString("DEVICE_LOCAL");
  15770. }
  15771. json.EndArray();
  15772. json.WriteString("Budget");
  15773. json.BeginObject();
  15774. {
  15775. json.WriteString("BlockBytes");
  15776. json.WriteNumber(budget[heapIndex].blockBytes);
  15777. json.WriteString("AllocationBytes");
  15778. json.WriteNumber(budget[heapIndex].allocationBytes);
  15779. json.WriteString("Usage");
  15780. json.WriteNumber(budget[heapIndex].usage);
  15781. json.WriteString("Budget");
  15782. json.WriteNumber(budget[heapIndex].budget);
  15783. }
  15784. json.EndObject();
  15785. if(stats.memoryHeap[heapIndex].blockCount > 0)
  15786. {
  15787. json.WriteString("Stats");
  15788. VmaPrintStatInfo(json, stats.memoryHeap[heapIndex]);
  15789. }
  15790. for(uint32_t typeIndex = 0; typeIndex < allocator->GetMemoryTypeCount(); ++typeIndex)
  15791. {
  15792. if(allocator->MemoryTypeIndexToHeapIndex(typeIndex) == heapIndex)
  15793. {
  15794. json.BeginString("Type ");
  15795. json.ContinueString(typeIndex);
  15796. json.EndString();
  15797. json.BeginObject();
  15798. json.WriteString("Flags");
  15799. json.BeginArray(true);
  15800. VkMemoryPropertyFlags flags = allocator->m_MemProps.memoryTypes[typeIndex].propertyFlags;
  15801. if((flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0)
  15802. {
  15803. json.WriteString("DEVICE_LOCAL");
  15804. }
  15805. if((flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
  15806. {
  15807. json.WriteString("HOST_VISIBLE");
  15808. }
  15809. if((flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0)
  15810. {
  15811. json.WriteString("HOST_COHERENT");
  15812. }
  15813. if((flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) != 0)
  15814. {
  15815. json.WriteString("HOST_CACHED");
  15816. }
  15817. if((flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) != 0)
  15818. {
  15819. json.WriteString("LAZILY_ALLOCATED");
  15820. }
  15821. #if VMA_VULKAN_VERSION >= 1001000
  15822. if((flags & VK_MEMORY_PROPERTY_PROTECTED_BIT) != 0)
  15823. {
  15824. json.WriteString("PROTECTED");
  15825. }
  15826. #endif // #if VMA_VULKAN_VERSION >= 1001000
  15827. #if VK_AMD_device_coherent_memory
  15828. if((flags & VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY) != 0)
  15829. {
  15830. json.WriteString("DEVICE_COHERENT");
  15831. }
  15832. if((flags & VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY) != 0)
  15833. {
  15834. json.WriteString("DEVICE_UNCACHED");
  15835. }
  15836. #endif // #if VK_AMD_device_coherent_memory
  15837. json.EndArray();
  15838. if(stats.memoryType[typeIndex].blockCount > 0)
  15839. {
  15840. json.WriteString("Stats");
  15841. VmaPrintStatInfo(json, stats.memoryType[typeIndex]);
  15842. }
  15843. json.EndObject();
  15844. }
  15845. }
  15846. json.EndObject();
  15847. }
  15848. if(detailedMap == VK_TRUE)
  15849. {
  15850. allocator->PrintDetailedMap(json);
  15851. }
  15852. json.EndObject();
  15853. }
  15854. const size_t len = sb.GetLength();
  15855. char* const pChars = vma_new_array(allocator, char, len + 1);
  15856. if(len > 0)
  15857. {
  15858. memcpy(pChars, sb.GetData(), len);
  15859. }
  15860. pChars[len] = '\0';
  15861. *ppStatsString = pChars;
  15862. }
  15863. VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString(
  15864. VmaAllocator allocator,
  15865. char* pStatsString)
  15866. {
  15867. if(pStatsString != VMA_NULL)
  15868. {
  15869. VMA_ASSERT(allocator);
  15870. size_t len = strlen(pStatsString);
  15871. vma_delete_array(allocator, pStatsString, len + 1);
  15872. }
  15873. }
  15874. #endif // #if VMA_STATS_STRING_ENABLED
  15875. /*
  15876. This function is not protected by any mutex because it just reads immutable data.
  15877. */
  15878. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex(
  15879. VmaAllocator allocator,
  15880. uint32_t memoryTypeBits,
  15881. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  15882. uint32_t* pMemoryTypeIndex)
  15883. {
  15884. VMA_ASSERT(allocator != VK_NULL_HANDLE);
  15885. VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
  15886. VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
  15887. memoryTypeBits &= allocator->GetGlobalMemoryTypeBits();
  15888. if(pAllocationCreateInfo->memoryTypeBits != 0)
  15889. {
  15890. memoryTypeBits &= pAllocationCreateInfo->memoryTypeBits;
  15891. }
  15892. uint32_t requiredFlags = pAllocationCreateInfo->requiredFlags;
  15893. uint32_t preferredFlags = pAllocationCreateInfo->preferredFlags;
  15894. uint32_t notPreferredFlags = 0;
  15895. // Convert usage to requiredFlags and preferredFlags.
  15896. switch(pAllocationCreateInfo->usage)
  15897. {
  15898. case VMA_MEMORY_USAGE_UNKNOWN:
  15899. break;
  15900. case VMA_MEMORY_USAGE_GPU_ONLY:
  15901. if(!allocator->IsIntegratedGpu() || (preferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  15902. {
  15903. preferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  15904. }
  15905. break;
  15906. case VMA_MEMORY_USAGE_CPU_ONLY:
  15907. requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
  15908. break;
  15909. case VMA_MEMORY_USAGE_CPU_TO_GPU:
  15910. requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  15911. if(!allocator->IsIntegratedGpu() || (preferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  15912. {
  15913. preferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  15914. }
  15915. break;
  15916. case VMA_MEMORY_USAGE_GPU_TO_CPU:
  15917. requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  15918. preferredFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  15919. break;
  15920. case VMA_MEMORY_USAGE_CPU_COPY:
  15921. notPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  15922. break;
  15923. case VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED:
  15924. requiredFlags |= VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT;
  15925. break;
  15926. default:
  15927. VMA_ASSERT(0);
  15928. break;
  15929. }
  15930. // Avoid DEVICE_COHERENT unless explicitly requested.
  15931. if(((pAllocationCreateInfo->requiredFlags | pAllocationCreateInfo->preferredFlags) &
  15932. (VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY | VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY)) == 0)
  15933. {
  15934. notPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY;
  15935. }
  15936. *pMemoryTypeIndex = UINT32_MAX;
  15937. uint32_t minCost = UINT32_MAX;
  15938. for(uint32_t memTypeIndex = 0, memTypeBit = 1;
  15939. memTypeIndex < allocator->GetMemoryTypeCount();
  15940. ++memTypeIndex, memTypeBit <<= 1)
  15941. {
  15942. // This memory type is acceptable according to memoryTypeBits bitmask.
  15943. if((memTypeBit & memoryTypeBits) != 0)
  15944. {
  15945. const VkMemoryPropertyFlags currFlags =
  15946. allocator->m_MemProps.memoryTypes[memTypeIndex].propertyFlags;
  15947. // This memory type contains requiredFlags.
  15948. if((requiredFlags & ~currFlags) == 0)
  15949. {
  15950. // Calculate cost as number of bits from preferredFlags not present in this memory type.
  15951. uint32_t currCost = VmaCountBitsSet(preferredFlags & ~currFlags) +
  15952. VmaCountBitsSet(currFlags & notPreferredFlags);
  15953. // Remember memory type with lowest cost.
  15954. if(currCost < minCost)
  15955. {
  15956. *pMemoryTypeIndex = memTypeIndex;
  15957. if(currCost == 0)
  15958. {
  15959. return VK_SUCCESS;
  15960. }
  15961. minCost = currCost;
  15962. }
  15963. }
  15964. }
  15965. }
  15966. return (*pMemoryTypeIndex != UINT32_MAX) ? VK_SUCCESS : VK_ERROR_FEATURE_NOT_PRESENT;
  15967. }
  15968. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo(
  15969. VmaAllocator allocator,
  15970. const VkBufferCreateInfo* pBufferCreateInfo,
  15971. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  15972. uint32_t* pMemoryTypeIndex)
  15973. {
  15974. VMA_ASSERT(allocator != VK_NULL_HANDLE);
  15975. VMA_ASSERT(pBufferCreateInfo != VMA_NULL);
  15976. VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
  15977. VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
  15978. const VkDevice hDev = allocator->m_hDevice;
  15979. VkBuffer hBuffer = VK_NULL_HANDLE;
  15980. VkResult res = allocator->GetVulkanFunctions().vkCreateBuffer(
  15981. hDev, pBufferCreateInfo, allocator->GetAllocationCallbacks(), &hBuffer);
  15982. if(res == VK_SUCCESS)
  15983. {
  15984. VkMemoryRequirements memReq = {};
  15985. allocator->GetVulkanFunctions().vkGetBufferMemoryRequirements(
  15986. hDev, hBuffer, &memReq);
  15987. res = vmaFindMemoryTypeIndex(
  15988. allocator,
  15989. memReq.memoryTypeBits,
  15990. pAllocationCreateInfo,
  15991. pMemoryTypeIndex);
  15992. allocator->GetVulkanFunctions().vkDestroyBuffer(
  15993. hDev, hBuffer, allocator->GetAllocationCallbacks());
  15994. }
  15995. return res;
  15996. }
  15997. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo(
  15998. VmaAllocator allocator,
  15999. const VkImageCreateInfo* pImageCreateInfo,
  16000. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  16001. uint32_t* pMemoryTypeIndex)
  16002. {
  16003. VMA_ASSERT(allocator != VK_NULL_HANDLE);
  16004. VMA_ASSERT(pImageCreateInfo != VMA_NULL);
  16005. VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
  16006. VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
  16007. const VkDevice hDev = allocator->m_hDevice;
  16008. VkImage hImage = VK_NULL_HANDLE;
  16009. VkResult res = allocator->GetVulkanFunctions().vkCreateImage(
  16010. hDev, pImageCreateInfo, allocator->GetAllocationCallbacks(), &hImage);
  16011. if(res == VK_SUCCESS)
  16012. {
  16013. VkMemoryRequirements memReq = {};
  16014. allocator->GetVulkanFunctions().vkGetImageMemoryRequirements(
  16015. hDev, hImage, &memReq);
  16016. res = vmaFindMemoryTypeIndex(
  16017. allocator,
  16018. memReq.memoryTypeBits,
  16019. pAllocationCreateInfo,
  16020. pMemoryTypeIndex);
  16021. allocator->GetVulkanFunctions().vkDestroyImage(
  16022. hDev, hImage, allocator->GetAllocationCallbacks());
  16023. }
  16024. return res;
  16025. }
  16026. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool(
  16027. VmaAllocator allocator,
  16028. const VmaPoolCreateInfo* pCreateInfo,
  16029. VmaPool* pPool)
  16030. {
  16031. VMA_ASSERT(allocator && pCreateInfo && pPool);
  16032. VMA_DEBUG_LOG("vmaCreatePool");
  16033. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16034. VkResult res = allocator->CreatePool(pCreateInfo, pPool);
  16035. #if VMA_RECORDING_ENABLED
  16036. if(allocator->GetRecorder() != VMA_NULL)
  16037. {
  16038. allocator->GetRecorder()->RecordCreatePool(allocator->GetCurrentFrameIndex(), *pCreateInfo, *pPool);
  16039. }
  16040. #endif
  16041. return res;
  16042. }
  16043. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool(
  16044. VmaAllocator allocator,
  16045. VmaPool pool)
  16046. {
  16047. VMA_ASSERT(allocator);
  16048. if(pool == VK_NULL_HANDLE)
  16049. {
  16050. return;
  16051. }
  16052. VMA_DEBUG_LOG("vmaDestroyPool");
  16053. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16054. #if VMA_RECORDING_ENABLED
  16055. if(allocator->GetRecorder() != VMA_NULL)
  16056. {
  16057. allocator->GetRecorder()->RecordDestroyPool(allocator->GetCurrentFrameIndex(), pool);
  16058. }
  16059. #endif
  16060. allocator->DestroyPool(pool);
  16061. }
  16062. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStats(
  16063. VmaAllocator allocator,
  16064. VmaPool pool,
  16065. VmaPoolStats* pPoolStats)
  16066. {
  16067. VMA_ASSERT(allocator && pool && pPoolStats);
  16068. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16069. allocator->GetPoolStats(pool, pPoolStats);
  16070. }
  16071. VMA_CALL_PRE void VMA_CALL_POST vmaMakePoolAllocationsLost(
  16072. VmaAllocator allocator,
  16073. VmaPool pool,
  16074. size_t* pLostAllocationCount)
  16075. {
  16076. VMA_ASSERT(allocator && pool);
  16077. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16078. #if VMA_RECORDING_ENABLED
  16079. if(allocator->GetRecorder() != VMA_NULL)
  16080. {
  16081. allocator->GetRecorder()->RecordMakePoolAllocationsLost(allocator->GetCurrentFrameIndex(), pool);
  16082. }
  16083. #endif
  16084. allocator->MakePoolAllocationsLost(pool, pLostAllocationCount);
  16085. }
  16086. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckPoolCorruption(VmaAllocator allocator, VmaPool pool)
  16087. {
  16088. VMA_ASSERT(allocator && pool);
  16089. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16090. VMA_DEBUG_LOG("vmaCheckPoolCorruption");
  16091. return allocator->CheckPoolCorruption(pool);
  16092. }
  16093. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName(
  16094. VmaAllocator allocator,
  16095. VmaPool pool,
  16096. const char** ppName)
  16097. {
  16098. VMA_ASSERT(allocator && pool && ppName);
  16099. VMA_DEBUG_LOG("vmaGetPoolName");
  16100. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16101. *ppName = pool->GetName();
  16102. }
  16103. VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName(
  16104. VmaAllocator allocator,
  16105. VmaPool pool,
  16106. const char* pName)
  16107. {
  16108. VMA_ASSERT(allocator && pool);
  16109. VMA_DEBUG_LOG("vmaSetPoolName");
  16110. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16111. pool->SetName(pName);
  16112. #if VMA_RECORDING_ENABLED
  16113. if(allocator->GetRecorder() != VMA_NULL)
  16114. {
  16115. allocator->GetRecorder()->RecordSetPoolName(allocator->GetCurrentFrameIndex(), pool, pName);
  16116. }
  16117. #endif
  16118. }
  16119. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory(
  16120. VmaAllocator allocator,
  16121. const VkMemoryRequirements* pVkMemoryRequirements,
  16122. const VmaAllocationCreateInfo* pCreateInfo,
  16123. VmaAllocation* pAllocation,
  16124. VmaAllocationInfo* pAllocationInfo)
  16125. {
  16126. VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocation);
  16127. VMA_DEBUG_LOG("vmaAllocateMemory");
  16128. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16129. VkResult result = allocator->AllocateMemory(
  16130. *pVkMemoryRequirements,
  16131. false, // requiresDedicatedAllocation
  16132. false, // prefersDedicatedAllocation
  16133. VK_NULL_HANDLE, // dedicatedBuffer
  16134. UINT32_MAX, // dedicatedBufferUsage
  16135. VK_NULL_HANDLE, // dedicatedImage
  16136. *pCreateInfo,
  16137. VMA_SUBALLOCATION_TYPE_UNKNOWN,
  16138. 1, // allocationCount
  16139. pAllocation);
  16140. #if VMA_RECORDING_ENABLED
  16141. if(allocator->GetRecorder() != VMA_NULL)
  16142. {
  16143. allocator->GetRecorder()->RecordAllocateMemory(
  16144. allocator->GetCurrentFrameIndex(),
  16145. *pVkMemoryRequirements,
  16146. *pCreateInfo,
  16147. *pAllocation);
  16148. }
  16149. #endif
  16150. if(pAllocationInfo != VMA_NULL && result == VK_SUCCESS)
  16151. {
  16152. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  16153. }
  16154. return result;
  16155. }
  16156. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages(
  16157. VmaAllocator allocator,
  16158. const VkMemoryRequirements* pVkMemoryRequirements,
  16159. const VmaAllocationCreateInfo* pCreateInfo,
  16160. size_t allocationCount,
  16161. VmaAllocation* pAllocations,
  16162. VmaAllocationInfo* pAllocationInfo)
  16163. {
  16164. if(allocationCount == 0)
  16165. {
  16166. return VK_SUCCESS;
  16167. }
  16168. VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocations);
  16169. VMA_DEBUG_LOG("vmaAllocateMemoryPages");
  16170. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16171. VkResult result = allocator->AllocateMemory(
  16172. *pVkMemoryRequirements,
  16173. false, // requiresDedicatedAllocation
  16174. false, // prefersDedicatedAllocation
  16175. VK_NULL_HANDLE, // dedicatedBuffer
  16176. UINT32_MAX, // dedicatedBufferUsage
  16177. VK_NULL_HANDLE, // dedicatedImage
  16178. *pCreateInfo,
  16179. VMA_SUBALLOCATION_TYPE_UNKNOWN,
  16180. allocationCount,
  16181. pAllocations);
  16182. #if VMA_RECORDING_ENABLED
  16183. if(allocator->GetRecorder() != VMA_NULL)
  16184. {
  16185. allocator->GetRecorder()->RecordAllocateMemoryPages(
  16186. allocator->GetCurrentFrameIndex(),
  16187. *pVkMemoryRequirements,
  16188. *pCreateInfo,
  16189. (uint64_t)allocationCount,
  16190. pAllocations);
  16191. }
  16192. #endif
  16193. if(pAllocationInfo != VMA_NULL && result == VK_SUCCESS)
  16194. {
  16195. for(size_t i = 0; i < allocationCount; ++i)
  16196. {
  16197. allocator->GetAllocationInfo(pAllocations[i], pAllocationInfo + i);
  16198. }
  16199. }
  16200. return result;
  16201. }
  16202. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer(
  16203. VmaAllocator allocator,
  16204. VkBuffer buffer,
  16205. const VmaAllocationCreateInfo* pCreateInfo,
  16206. VmaAllocation* pAllocation,
  16207. VmaAllocationInfo* pAllocationInfo)
  16208. {
  16209. VMA_ASSERT(allocator && buffer != VK_NULL_HANDLE && pCreateInfo && pAllocation);
  16210. VMA_DEBUG_LOG("vmaAllocateMemoryForBuffer");
  16211. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16212. VkMemoryRequirements vkMemReq = {};
  16213. bool requiresDedicatedAllocation = false;
  16214. bool prefersDedicatedAllocation = false;
  16215. allocator->GetBufferMemoryRequirements(buffer, vkMemReq,
  16216. requiresDedicatedAllocation,
  16217. prefersDedicatedAllocation);
  16218. VkResult result = allocator->AllocateMemory(
  16219. vkMemReq,
  16220. requiresDedicatedAllocation,
  16221. prefersDedicatedAllocation,
  16222. buffer, // dedicatedBuffer
  16223. UINT32_MAX, // dedicatedBufferUsage
  16224. VK_NULL_HANDLE, // dedicatedImage
  16225. *pCreateInfo,
  16226. VMA_SUBALLOCATION_TYPE_BUFFER,
  16227. 1, // allocationCount
  16228. pAllocation);
  16229. #if VMA_RECORDING_ENABLED
  16230. if(allocator->GetRecorder() != VMA_NULL)
  16231. {
  16232. allocator->GetRecorder()->RecordAllocateMemoryForBuffer(
  16233. allocator->GetCurrentFrameIndex(),
  16234. vkMemReq,
  16235. requiresDedicatedAllocation,
  16236. prefersDedicatedAllocation,
  16237. *pCreateInfo,
  16238. *pAllocation);
  16239. }
  16240. #endif
  16241. if(pAllocationInfo && result == VK_SUCCESS)
  16242. {
  16243. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  16244. }
  16245. return result;
  16246. }
  16247. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage(
  16248. VmaAllocator allocator,
  16249. VkImage image,
  16250. const VmaAllocationCreateInfo* pCreateInfo,
  16251. VmaAllocation* pAllocation,
  16252. VmaAllocationInfo* pAllocationInfo)
  16253. {
  16254. VMA_ASSERT(allocator && image != VK_NULL_HANDLE && pCreateInfo && pAllocation);
  16255. VMA_DEBUG_LOG("vmaAllocateMemoryForImage");
  16256. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16257. VkMemoryRequirements vkMemReq = {};
  16258. bool requiresDedicatedAllocation = false;
  16259. bool prefersDedicatedAllocation = false;
  16260. allocator->GetImageMemoryRequirements(image, vkMemReq,
  16261. requiresDedicatedAllocation, prefersDedicatedAllocation);
  16262. VkResult result = allocator->AllocateMemory(
  16263. vkMemReq,
  16264. requiresDedicatedAllocation,
  16265. prefersDedicatedAllocation,
  16266. VK_NULL_HANDLE, // dedicatedBuffer
  16267. UINT32_MAX, // dedicatedBufferUsage
  16268. image, // dedicatedImage
  16269. *pCreateInfo,
  16270. VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN,
  16271. 1, // allocationCount
  16272. pAllocation);
  16273. #if VMA_RECORDING_ENABLED
  16274. if(allocator->GetRecorder() != VMA_NULL)
  16275. {
  16276. allocator->GetRecorder()->RecordAllocateMemoryForImage(
  16277. allocator->GetCurrentFrameIndex(),
  16278. vkMemReq,
  16279. requiresDedicatedAllocation,
  16280. prefersDedicatedAllocation,
  16281. *pCreateInfo,
  16282. *pAllocation);
  16283. }
  16284. #endif
  16285. if(pAllocationInfo && result == VK_SUCCESS)
  16286. {
  16287. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  16288. }
  16289. return result;
  16290. }
  16291. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory(
  16292. VmaAllocator allocator,
  16293. VmaAllocation allocation)
  16294. {
  16295. VMA_ASSERT(allocator);
  16296. if(allocation == VK_NULL_HANDLE)
  16297. {
  16298. return;
  16299. }
  16300. VMA_DEBUG_LOG("vmaFreeMemory");
  16301. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16302. #if VMA_RECORDING_ENABLED
  16303. if(allocator->GetRecorder() != VMA_NULL)
  16304. {
  16305. allocator->GetRecorder()->RecordFreeMemory(
  16306. allocator->GetCurrentFrameIndex(),
  16307. allocation);
  16308. }
  16309. #endif
  16310. allocator->FreeMemory(
  16311. 1, // allocationCount
  16312. &allocation);
  16313. }
  16314. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages(
  16315. VmaAllocator allocator,
  16316. size_t allocationCount,
  16317. const VmaAllocation* pAllocations)
  16318. {
  16319. if(allocationCount == 0)
  16320. {
  16321. return;
  16322. }
  16323. VMA_ASSERT(allocator);
  16324. VMA_DEBUG_LOG("vmaFreeMemoryPages");
  16325. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16326. #if VMA_RECORDING_ENABLED
  16327. if(allocator->GetRecorder() != VMA_NULL)
  16328. {
  16329. allocator->GetRecorder()->RecordFreeMemoryPages(
  16330. allocator->GetCurrentFrameIndex(),
  16331. (uint64_t)allocationCount,
  16332. pAllocations);
  16333. }
  16334. #endif
  16335. allocator->FreeMemory(allocationCount, pAllocations);
  16336. }
  16337. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo(
  16338. VmaAllocator allocator,
  16339. VmaAllocation allocation,
  16340. VmaAllocationInfo* pAllocationInfo)
  16341. {
  16342. VMA_ASSERT(allocator && allocation && pAllocationInfo);
  16343. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16344. #if VMA_RECORDING_ENABLED
  16345. if(allocator->GetRecorder() != VMA_NULL)
  16346. {
  16347. allocator->GetRecorder()->RecordGetAllocationInfo(
  16348. allocator->GetCurrentFrameIndex(),
  16349. allocation);
  16350. }
  16351. #endif
  16352. allocator->GetAllocationInfo(allocation, pAllocationInfo);
  16353. }
  16354. VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaTouchAllocation(
  16355. VmaAllocator allocator,
  16356. VmaAllocation allocation)
  16357. {
  16358. VMA_ASSERT(allocator && allocation);
  16359. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16360. #if VMA_RECORDING_ENABLED
  16361. if(allocator->GetRecorder() != VMA_NULL)
  16362. {
  16363. allocator->GetRecorder()->RecordTouchAllocation(
  16364. allocator->GetCurrentFrameIndex(),
  16365. allocation);
  16366. }
  16367. #endif
  16368. return allocator->TouchAllocation(allocation);
  16369. }
  16370. VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData(
  16371. VmaAllocator allocator,
  16372. VmaAllocation allocation,
  16373. void* pUserData)
  16374. {
  16375. VMA_ASSERT(allocator && allocation);
  16376. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16377. allocation->SetUserData(allocator, pUserData);
  16378. #if VMA_RECORDING_ENABLED
  16379. if(allocator->GetRecorder() != VMA_NULL)
  16380. {
  16381. allocator->GetRecorder()->RecordSetAllocationUserData(
  16382. allocator->GetCurrentFrameIndex(),
  16383. allocation,
  16384. pUserData);
  16385. }
  16386. #endif
  16387. }
  16388. VMA_CALL_PRE void VMA_CALL_POST vmaCreateLostAllocation(
  16389. VmaAllocator allocator,
  16390. VmaAllocation* pAllocation)
  16391. {
  16392. VMA_ASSERT(allocator && pAllocation);
  16393. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  16394. allocator->CreateLostAllocation(pAllocation);
  16395. #if VMA_RECORDING_ENABLED
  16396. if(allocator->GetRecorder() != VMA_NULL)
  16397. {
  16398. allocator->GetRecorder()->RecordCreateLostAllocation(
  16399. allocator->GetCurrentFrameIndex(),
  16400. *pAllocation);
  16401. }
  16402. #endif
  16403. }
  16404. VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory(
  16405. VmaAllocator allocator,
  16406. VmaAllocation allocation,
  16407. void** ppData)
  16408. {
  16409. VMA_ASSERT(allocator && allocation && ppData);
  16410. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16411. VkResult res = allocator->Map(allocation, ppData);
  16412. #if VMA_RECORDING_ENABLED
  16413. if(allocator->GetRecorder() != VMA_NULL)
  16414. {
  16415. allocator->GetRecorder()->RecordMapMemory(
  16416. allocator->GetCurrentFrameIndex(),
  16417. allocation);
  16418. }
  16419. #endif
  16420. return res;
  16421. }
  16422. VMA_CALL_PRE void VMA_CALL_POST vmaUnmapMemory(
  16423. VmaAllocator allocator,
  16424. VmaAllocation allocation)
  16425. {
  16426. VMA_ASSERT(allocator && allocation);
  16427. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16428. #if VMA_RECORDING_ENABLED
  16429. if(allocator->GetRecorder() != VMA_NULL)
  16430. {
  16431. allocator->GetRecorder()->RecordUnmapMemory(
  16432. allocator->GetCurrentFrameIndex(),
  16433. allocation);
  16434. }
  16435. #endif
  16436. allocator->Unmap(allocation);
  16437. }
  16438. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocation(VmaAllocator allocator, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size)
  16439. {
  16440. VMA_ASSERT(allocator && allocation);
  16441. VMA_DEBUG_LOG("vmaFlushAllocation");
  16442. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16443. const VkResult res = allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_FLUSH);
  16444. #if VMA_RECORDING_ENABLED
  16445. if(allocator->GetRecorder() != VMA_NULL)
  16446. {
  16447. allocator->GetRecorder()->RecordFlushAllocation(
  16448. allocator->GetCurrentFrameIndex(),
  16449. allocation, offset, size);
  16450. }
  16451. #endif
  16452. return res;
  16453. }
  16454. VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocation(VmaAllocator allocator, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size)
  16455. {
  16456. VMA_ASSERT(allocator && allocation);
  16457. VMA_DEBUG_LOG("vmaInvalidateAllocation");
  16458. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16459. const VkResult res = allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_INVALIDATE);
  16460. #if VMA_RECORDING_ENABLED
  16461. if(allocator->GetRecorder() != VMA_NULL)
  16462. {
  16463. allocator->GetRecorder()->RecordInvalidateAllocation(
  16464. allocator->GetCurrentFrameIndex(),
  16465. allocation, offset, size);
  16466. }
  16467. #endif
  16468. return res;
  16469. }
  16470. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocations(
  16471. VmaAllocator allocator,
  16472. uint32_t allocationCount,
  16473. const VmaAllocation* allocations,
  16474. const VkDeviceSize* offsets,
  16475. const VkDeviceSize* sizes)
  16476. {
  16477. VMA_ASSERT(allocator);
  16478. if(allocationCount == 0)
  16479. {
  16480. return VK_SUCCESS;
  16481. }
  16482. VMA_ASSERT(allocations);
  16483. VMA_DEBUG_LOG("vmaFlushAllocations");
  16484. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16485. const VkResult res = allocator->FlushOrInvalidateAllocations(allocationCount, allocations, offsets, sizes, VMA_CACHE_FLUSH);
  16486. #if VMA_RECORDING_ENABLED
  16487. if(allocator->GetRecorder() != VMA_NULL)
  16488. {
  16489. //TODO
  16490. }
  16491. #endif
  16492. return res;
  16493. }
  16494. VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocations(
  16495. VmaAllocator allocator,
  16496. uint32_t allocationCount,
  16497. const VmaAllocation* allocations,
  16498. const VkDeviceSize* offsets,
  16499. const VkDeviceSize* sizes)
  16500. {
  16501. VMA_ASSERT(allocator);
  16502. if(allocationCount == 0)
  16503. {
  16504. return VK_SUCCESS;
  16505. }
  16506. VMA_ASSERT(allocations);
  16507. VMA_DEBUG_LOG("vmaInvalidateAllocations");
  16508. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16509. const VkResult res = allocator->FlushOrInvalidateAllocations(allocationCount, allocations, offsets, sizes, VMA_CACHE_INVALIDATE);
  16510. #if VMA_RECORDING_ENABLED
  16511. if(allocator->GetRecorder() != VMA_NULL)
  16512. {
  16513. //TODO
  16514. }
  16515. #endif
  16516. return res;
  16517. }
  16518. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckCorruption(VmaAllocator allocator, uint32_t memoryTypeBits)
  16519. {
  16520. VMA_ASSERT(allocator);
  16521. VMA_DEBUG_LOG("vmaCheckCorruption");
  16522. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16523. return allocator->CheckCorruption(memoryTypeBits);
  16524. }
  16525. VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragment(
  16526. VmaAllocator allocator,
  16527. const VmaAllocation* pAllocations,
  16528. size_t allocationCount,
  16529. VkBool32* pAllocationsChanged,
  16530. const VmaDefragmentationInfo *pDefragmentationInfo,
  16531. VmaDefragmentationStats* pDefragmentationStats)
  16532. {
  16533. // Deprecated interface, reimplemented using new one.
  16534. VmaDefragmentationInfo2 info2 = {};
  16535. info2.allocationCount = (uint32_t)allocationCount;
  16536. info2.pAllocations = pAllocations;
  16537. info2.pAllocationsChanged = pAllocationsChanged;
  16538. if(pDefragmentationInfo != VMA_NULL)
  16539. {
  16540. info2.maxCpuAllocationsToMove = pDefragmentationInfo->maxAllocationsToMove;
  16541. info2.maxCpuBytesToMove = pDefragmentationInfo->maxBytesToMove;
  16542. }
  16543. else
  16544. {
  16545. info2.maxCpuAllocationsToMove = UINT32_MAX;
  16546. info2.maxCpuBytesToMove = VK_WHOLE_SIZE;
  16547. }
  16548. // info2.flags, maxGpuAllocationsToMove, maxGpuBytesToMove, commandBuffer deliberately left zero.
  16549. VmaDefragmentationContext ctx;
  16550. VkResult res = vmaDefragmentationBegin(allocator, &info2, pDefragmentationStats, &ctx);
  16551. if(res == VK_NOT_READY)
  16552. {
  16553. res = vmaDefragmentationEnd( allocator, ctx);
  16554. }
  16555. return res;
  16556. }
  16557. VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragmentationBegin(
  16558. VmaAllocator allocator,
  16559. const VmaDefragmentationInfo2* pInfo,
  16560. VmaDefragmentationStats* pStats,
  16561. VmaDefragmentationContext *pContext)
  16562. {
  16563. VMA_ASSERT(allocator && pInfo && pContext);
  16564. // Degenerate case: Nothing to defragment.
  16565. if(pInfo->allocationCount == 0 && pInfo->poolCount == 0)
  16566. {
  16567. return VK_SUCCESS;
  16568. }
  16569. VMA_ASSERT(pInfo->allocationCount == 0 || pInfo->pAllocations != VMA_NULL);
  16570. VMA_ASSERT(pInfo->poolCount == 0 || pInfo->pPools != VMA_NULL);
  16571. VMA_HEAVY_ASSERT(VmaValidatePointerArray(pInfo->allocationCount, pInfo->pAllocations));
  16572. VMA_HEAVY_ASSERT(VmaValidatePointerArray(pInfo->poolCount, pInfo->pPools));
  16573. VMA_DEBUG_LOG("vmaDefragmentationBegin");
  16574. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16575. VkResult res = allocator->DefragmentationBegin(*pInfo, pStats, pContext);
  16576. #if VMA_RECORDING_ENABLED
  16577. if(allocator->GetRecorder() != VMA_NULL)
  16578. {
  16579. allocator->GetRecorder()->RecordDefragmentationBegin(
  16580. allocator->GetCurrentFrameIndex(), *pInfo, *pContext);
  16581. }
  16582. #endif
  16583. return res;
  16584. }
  16585. VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragmentationEnd(
  16586. VmaAllocator allocator,
  16587. VmaDefragmentationContext context)
  16588. {
  16589. VMA_ASSERT(allocator);
  16590. VMA_DEBUG_LOG("vmaDefragmentationEnd");
  16591. if(context != VK_NULL_HANDLE)
  16592. {
  16593. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16594. #if VMA_RECORDING_ENABLED
  16595. if(allocator->GetRecorder() != VMA_NULL)
  16596. {
  16597. allocator->GetRecorder()->RecordDefragmentationEnd(
  16598. allocator->GetCurrentFrameIndex(), context);
  16599. }
  16600. #endif
  16601. return allocator->DefragmentationEnd(context);
  16602. }
  16603. else
  16604. {
  16605. return VK_SUCCESS;
  16606. }
  16607. }
  16608. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentationPass(
  16609. VmaAllocator allocator,
  16610. VmaDefragmentationContext context,
  16611. VmaDefragmentationPassInfo* pInfo
  16612. )
  16613. {
  16614. VMA_ASSERT(allocator);
  16615. VMA_ASSERT(pInfo);
  16616. VMA_DEBUG_LOG("vmaBeginDefragmentationPass");
  16617. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16618. if(context == VK_NULL_HANDLE)
  16619. {
  16620. pInfo->moveCount = 0;
  16621. return VK_SUCCESS;
  16622. }
  16623. return allocator->DefragmentationPassBegin(pInfo, context);
  16624. }
  16625. VMA_CALL_PRE VkResult VMA_CALL_POST vmaEndDefragmentationPass(
  16626. VmaAllocator allocator,
  16627. VmaDefragmentationContext context)
  16628. {
  16629. VMA_ASSERT(allocator);
  16630. VMA_DEBUG_LOG("vmaEndDefragmentationPass");
  16631. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16632. if(context == VK_NULL_HANDLE)
  16633. return VK_SUCCESS;
  16634. return allocator->DefragmentationPassEnd(context);
  16635. }
  16636. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory(
  16637. VmaAllocator allocator,
  16638. VmaAllocation allocation,
  16639. VkBuffer buffer)
  16640. {
  16641. VMA_ASSERT(allocator && allocation && buffer);
  16642. VMA_DEBUG_LOG("vmaBindBufferMemory");
  16643. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16644. return allocator->BindBufferMemory(allocation, 0, buffer, VMA_NULL);
  16645. }
  16646. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2(
  16647. VmaAllocator allocator,
  16648. VmaAllocation allocation,
  16649. VkDeviceSize allocationLocalOffset,
  16650. VkBuffer buffer,
  16651. const void* pNext)
  16652. {
  16653. VMA_ASSERT(allocator && allocation && buffer);
  16654. VMA_DEBUG_LOG("vmaBindBufferMemory2");
  16655. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16656. return allocator->BindBufferMemory(allocation, allocationLocalOffset, buffer, pNext);
  16657. }
  16658. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory(
  16659. VmaAllocator allocator,
  16660. VmaAllocation allocation,
  16661. VkImage image)
  16662. {
  16663. VMA_ASSERT(allocator && allocation && image);
  16664. VMA_DEBUG_LOG("vmaBindImageMemory");
  16665. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16666. return allocator->BindImageMemory(allocation, 0, image, VMA_NULL);
  16667. }
  16668. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2(
  16669. VmaAllocator allocator,
  16670. VmaAllocation allocation,
  16671. VkDeviceSize allocationLocalOffset,
  16672. VkImage image,
  16673. const void* pNext)
  16674. {
  16675. VMA_ASSERT(allocator && allocation && image);
  16676. VMA_DEBUG_LOG("vmaBindImageMemory2");
  16677. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16678. return allocator->BindImageMemory(allocation, allocationLocalOffset, image, pNext);
  16679. }
  16680. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer(
  16681. VmaAllocator allocator,
  16682. const VkBufferCreateInfo* pBufferCreateInfo,
  16683. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  16684. VkBuffer* pBuffer,
  16685. VmaAllocation* pAllocation,
  16686. VmaAllocationInfo* pAllocationInfo)
  16687. {
  16688. VMA_ASSERT(allocator && pBufferCreateInfo && pAllocationCreateInfo && pBuffer && pAllocation);
  16689. if(pBufferCreateInfo->size == 0)
  16690. {
  16691. return VK_ERROR_VALIDATION_FAILED_EXT;
  16692. }
  16693. if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY) != 0 &&
  16694. !allocator->m_UseKhrBufferDeviceAddress)
  16695. {
  16696. VMA_ASSERT(0 && "Creating a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT is not valid if VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT was not used.");
  16697. return VK_ERROR_VALIDATION_FAILED_EXT;
  16698. }
  16699. VMA_DEBUG_LOG("vmaCreateBuffer");
  16700. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16701. *pBuffer = VK_NULL_HANDLE;
  16702. *pAllocation = VK_NULL_HANDLE;
  16703. // 1. Create VkBuffer.
  16704. VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)(
  16705. allocator->m_hDevice,
  16706. pBufferCreateInfo,
  16707. allocator->GetAllocationCallbacks(),
  16708. pBuffer);
  16709. if(res >= 0)
  16710. {
  16711. // 2. vkGetBufferMemoryRequirements.
  16712. VkMemoryRequirements vkMemReq = {};
  16713. bool requiresDedicatedAllocation = false;
  16714. bool prefersDedicatedAllocation = false;
  16715. allocator->GetBufferMemoryRequirements(*pBuffer, vkMemReq,
  16716. requiresDedicatedAllocation, prefersDedicatedAllocation);
  16717. // 3. Allocate memory using allocator.
  16718. res = allocator->AllocateMemory(
  16719. vkMemReq,
  16720. requiresDedicatedAllocation,
  16721. prefersDedicatedAllocation,
  16722. *pBuffer, // dedicatedBuffer
  16723. pBufferCreateInfo->usage, // dedicatedBufferUsage
  16724. VK_NULL_HANDLE, // dedicatedImage
  16725. *pAllocationCreateInfo,
  16726. VMA_SUBALLOCATION_TYPE_BUFFER,
  16727. 1, // allocationCount
  16728. pAllocation);
  16729. #if VMA_RECORDING_ENABLED
  16730. if(allocator->GetRecorder() != VMA_NULL)
  16731. {
  16732. allocator->GetRecorder()->RecordCreateBuffer(
  16733. allocator->GetCurrentFrameIndex(),
  16734. *pBufferCreateInfo,
  16735. *pAllocationCreateInfo,
  16736. *pAllocation);
  16737. }
  16738. #endif
  16739. if(res >= 0)
  16740. {
  16741. // 3. Bind buffer with memory.
  16742. if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0)
  16743. {
  16744. res = allocator->BindBufferMemory(*pAllocation, 0, *pBuffer, VMA_NULL);
  16745. }
  16746. if(res >= 0)
  16747. {
  16748. // All steps succeeded.
  16749. #if VMA_STATS_STRING_ENABLED
  16750. (*pAllocation)->InitBufferImageUsage(pBufferCreateInfo->usage);
  16751. #endif
  16752. if(pAllocationInfo != VMA_NULL)
  16753. {
  16754. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  16755. }
  16756. return VK_SUCCESS;
  16757. }
  16758. allocator->FreeMemory(
  16759. 1, // allocationCount
  16760. pAllocation);
  16761. *pAllocation = VK_NULL_HANDLE;
  16762. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
  16763. *pBuffer = VK_NULL_HANDLE;
  16764. return res;
  16765. }
  16766. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
  16767. *pBuffer = VK_NULL_HANDLE;
  16768. return res;
  16769. }
  16770. return res;
  16771. }
  16772. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer(
  16773. VmaAllocator allocator,
  16774. VkBuffer buffer,
  16775. VmaAllocation allocation)
  16776. {
  16777. VMA_ASSERT(allocator);
  16778. if(buffer == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE)
  16779. {
  16780. return;
  16781. }
  16782. VMA_DEBUG_LOG("vmaDestroyBuffer");
  16783. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16784. #if VMA_RECORDING_ENABLED
  16785. if(allocator->GetRecorder() != VMA_NULL)
  16786. {
  16787. allocator->GetRecorder()->RecordDestroyBuffer(
  16788. allocator->GetCurrentFrameIndex(),
  16789. allocation);
  16790. }
  16791. #endif
  16792. if(buffer != VK_NULL_HANDLE)
  16793. {
  16794. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, buffer, allocator->GetAllocationCallbacks());
  16795. }
  16796. if(allocation != VK_NULL_HANDLE)
  16797. {
  16798. allocator->FreeMemory(
  16799. 1, // allocationCount
  16800. &allocation);
  16801. }
  16802. }
  16803. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage(
  16804. VmaAllocator allocator,
  16805. const VkImageCreateInfo* pImageCreateInfo,
  16806. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  16807. VkImage* pImage,
  16808. VmaAllocation* pAllocation,
  16809. VmaAllocationInfo* pAllocationInfo)
  16810. {
  16811. VMA_ASSERT(allocator && pImageCreateInfo && pAllocationCreateInfo && pImage && pAllocation);
  16812. if(pImageCreateInfo->extent.width == 0 ||
  16813. pImageCreateInfo->extent.height == 0 ||
  16814. pImageCreateInfo->extent.depth == 0 ||
  16815. pImageCreateInfo->mipLevels == 0 ||
  16816. pImageCreateInfo->arrayLayers == 0)
  16817. {
  16818. return VK_ERROR_VALIDATION_FAILED_EXT;
  16819. }
  16820. VMA_DEBUG_LOG("vmaCreateImage");
  16821. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16822. *pImage = VK_NULL_HANDLE;
  16823. *pAllocation = VK_NULL_HANDLE;
  16824. // 1. Create VkImage.
  16825. VkResult res = (*allocator->GetVulkanFunctions().vkCreateImage)(
  16826. allocator->m_hDevice,
  16827. pImageCreateInfo,
  16828. allocator->GetAllocationCallbacks(),
  16829. pImage);
  16830. if(res >= 0)
  16831. {
  16832. VmaSuballocationType suballocType = pImageCreateInfo->tiling == VK_IMAGE_TILING_OPTIMAL ?
  16833. VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL :
  16834. VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR;
  16835. // 2. Allocate memory using allocator.
  16836. VkMemoryRequirements vkMemReq = {};
  16837. bool requiresDedicatedAllocation = false;
  16838. bool prefersDedicatedAllocation = false;
  16839. allocator->GetImageMemoryRequirements(*pImage, vkMemReq,
  16840. requiresDedicatedAllocation, prefersDedicatedAllocation);
  16841. res = allocator->AllocateMemory(
  16842. vkMemReq,
  16843. requiresDedicatedAllocation,
  16844. prefersDedicatedAllocation,
  16845. VK_NULL_HANDLE, // dedicatedBuffer
  16846. UINT32_MAX, // dedicatedBufferUsage
  16847. *pImage, // dedicatedImage
  16848. *pAllocationCreateInfo,
  16849. suballocType,
  16850. 1, // allocationCount
  16851. pAllocation);
  16852. #if VMA_RECORDING_ENABLED
  16853. if(allocator->GetRecorder() != VMA_NULL)
  16854. {
  16855. allocator->GetRecorder()->RecordCreateImage(
  16856. allocator->GetCurrentFrameIndex(),
  16857. *pImageCreateInfo,
  16858. *pAllocationCreateInfo,
  16859. *pAllocation);
  16860. }
  16861. #endif
  16862. if(res >= 0)
  16863. {
  16864. // 3. Bind image with memory.
  16865. if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0)
  16866. {
  16867. res = allocator->BindImageMemory(*pAllocation, 0, *pImage, VMA_NULL);
  16868. }
  16869. if(res >= 0)
  16870. {
  16871. // All steps succeeded.
  16872. #if VMA_STATS_STRING_ENABLED
  16873. (*pAllocation)->InitBufferImageUsage(pImageCreateInfo->usage);
  16874. #endif
  16875. if(pAllocationInfo != VMA_NULL)
  16876. {
  16877. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  16878. }
  16879. return VK_SUCCESS;
  16880. }
  16881. allocator->FreeMemory(
  16882. 1, // allocationCount
  16883. pAllocation);
  16884. *pAllocation = VK_NULL_HANDLE;
  16885. (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks());
  16886. *pImage = VK_NULL_HANDLE;
  16887. return res;
  16888. }
  16889. (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks());
  16890. *pImage = VK_NULL_HANDLE;
  16891. return res;
  16892. }
  16893. return res;
  16894. }
  16895. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyImage(
  16896. VmaAllocator allocator,
  16897. VkImage image,
  16898. VmaAllocation allocation)
  16899. {
  16900. VMA_ASSERT(allocator);
  16901. if(image == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE)
  16902. {
  16903. return;
  16904. }
  16905. VMA_DEBUG_LOG("vmaDestroyImage");
  16906. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  16907. #if VMA_RECORDING_ENABLED
  16908. if(allocator->GetRecorder() != VMA_NULL)
  16909. {
  16910. allocator->GetRecorder()->RecordDestroyImage(
  16911. allocator->GetCurrentFrameIndex(),
  16912. allocation);
  16913. }
  16914. #endif
  16915. if(image != VK_NULL_HANDLE)
  16916. {
  16917. (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, image, allocator->GetAllocationCallbacks());
  16918. }
  16919. if(allocation != VK_NULL_HANDLE)
  16920. {
  16921. allocator->FreeMemory(
  16922. 1, // allocationCount
  16923. &allocation);
  16924. }
  16925. }
  16926. #endif // #ifdef VMA_IMPLEMENTATION