vk_mem_alloc.h 715 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558
  1. //
  2. // Copyright (c) 2017-2022 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.1 (2022-05-26)</b>
  26. Copyright (c) 2017-2022 Advanced Micro Devices, Inc. All rights reserved. \n
  27. License: MIT
  28. <b>API documentation divided into groups:</b> [Modules](modules.html)
  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. - \subpage staying_within_budget
  46. - [Querying for budget](@ref staying_within_budget_querying_for_budget)
  47. - [Controlling memory usage](@ref staying_within_budget_controlling_memory_usage)
  48. - \subpage resource_aliasing
  49. - \subpage custom_memory_pools
  50. - [Choosing memory type index](@ref custom_memory_pools_MemTypeIndex)
  51. - [Linear allocation algorithm](@ref linear_algorithm)
  52. - [Free-at-once](@ref linear_algorithm_free_at_once)
  53. - [Stack](@ref linear_algorithm_stack)
  54. - [Double stack](@ref linear_algorithm_double_stack)
  55. - [Ring buffer](@ref linear_algorithm_ring_buffer)
  56. - \subpage defragmentation
  57. - \subpage statistics
  58. - [Numeric statistics](@ref statistics_numeric_statistics)
  59. - [JSON dump](@ref statistics_json_dump)
  60. - \subpage allocation_annotation
  61. - [Allocation user data](@ref allocation_user_data)
  62. - [Allocation names](@ref allocation_names)
  63. - \subpage virtual_allocator
  64. - \subpage debugging_memory_usage
  65. - [Memory initialization](@ref debugging_memory_usage_initialization)
  66. - [Margins](@ref debugging_memory_usage_margins)
  67. - [Corruption detection](@ref debugging_memory_usage_corruption_detection)
  68. - \subpage opengl_interop
  69. - \subpage usage_patterns
  70. - [GPU-only resource](@ref usage_patterns_gpu_only)
  71. - [Staging copy for upload](@ref usage_patterns_staging_copy_upload)
  72. - [Readback](@ref usage_patterns_readback)
  73. - [Advanced data uploading](@ref usage_patterns_advanced_data_uploading)
  74. - [Other use cases](@ref usage_patterns_other_use_cases)
  75. - \subpage configuration
  76. - [Pointers to Vulkan functions](@ref config_Vulkan_functions)
  77. - [Custom host memory allocator](@ref custom_memory_allocator)
  78. - [Device memory allocation callbacks](@ref allocation_callbacks)
  79. - [Device heap memory limit](@ref heap_memory_limit)
  80. - <b>Extension support</b>
  81. - \subpage vk_khr_dedicated_allocation
  82. - \subpage enabling_buffer_device_address
  83. - \subpage vk_ext_memory_priority
  84. - \subpage vk_amd_device_coherent_memory
  85. - \subpage general_considerations
  86. - [Thread safety](@ref general_considerations_thread_safety)
  87. - [Versioning and compatibility](@ref general_considerations_versioning_and_compatibility)
  88. - [Validation layer warnings](@ref general_considerations_validation_layer_warnings)
  89. - [Allocation algorithm](@ref general_considerations_allocation_algorithm)
  90. - [Features not supported](@ref general_considerations_features_not_supported)
  91. \section main_see_also See also
  92. - [**Product page on GPUOpen**](https://gpuopen.com/gaming-product/vulkan-memory-allocator/)
  93. - [**Source repository on GitHub**](https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator)
  94. \defgroup group_init Library initialization
  95. \brief API elements related to the initialization and management of the entire library, especially #VmaAllocator object.
  96. \defgroup group_alloc Memory allocation
  97. \brief API elements related to the allocation, deallocation, and management of Vulkan memory, buffers, images.
  98. Most basic ones being: vmaCreateBuffer(), vmaCreateImage().
  99. \defgroup group_virtual Virtual allocator
  100. \brief API elements related to the mechanism of \ref virtual_allocator - using the core allocation algorithm
  101. for user-defined purpose without allocating any real GPU memory.
  102. \defgroup group_stats Statistics
  103. \brief API elements that query current status of the allocator, from memory usage, budget, to full dump of the internal state in JSON format.
  104. See documentation chapter: \ref statistics.
  105. */
  106. #ifdef __cplusplus
  107. extern "C" {
  108. #endif
  109. #ifndef VULKAN_H_
  110. #include <vulkan/vulkan.h>
  111. #endif
  112. // Define this macro to declare maximum supported Vulkan version in format AAABBBCCC,
  113. // where AAA = major, BBB = minor, CCC = patch.
  114. // If you want to use version > 1.0, it still needs to be enabled via VmaAllocatorCreateInfo::vulkanApiVersion.
  115. #if !defined(VMA_VULKAN_VERSION)
  116. #if defined(VK_VERSION_1_3)
  117. #define VMA_VULKAN_VERSION 1003000
  118. #elif defined(VK_VERSION_1_2)
  119. #define VMA_VULKAN_VERSION 1002000
  120. #elif defined(VK_VERSION_1_1)
  121. #define VMA_VULKAN_VERSION 1001000
  122. #else
  123. #define VMA_VULKAN_VERSION 1000000
  124. #endif
  125. #endif
  126. #if defined(__ANDROID__) && defined(VK_NO_PROTOTYPES) && VMA_STATIC_VULKAN_FUNCTIONS
  127. extern PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr;
  128. extern PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr;
  129. extern PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties;
  130. extern PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties;
  131. extern PFN_vkAllocateMemory vkAllocateMemory;
  132. extern PFN_vkFreeMemory vkFreeMemory;
  133. extern PFN_vkMapMemory vkMapMemory;
  134. extern PFN_vkUnmapMemory vkUnmapMemory;
  135. extern PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges;
  136. extern PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges;
  137. extern PFN_vkBindBufferMemory vkBindBufferMemory;
  138. extern PFN_vkBindImageMemory vkBindImageMemory;
  139. extern PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements;
  140. extern PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements;
  141. extern PFN_vkCreateBuffer vkCreateBuffer;
  142. extern PFN_vkDestroyBuffer vkDestroyBuffer;
  143. extern PFN_vkCreateImage vkCreateImage;
  144. extern PFN_vkDestroyImage vkDestroyImage;
  145. extern PFN_vkCmdCopyBuffer vkCmdCopyBuffer;
  146. #if VMA_VULKAN_VERSION >= 1001000
  147. extern PFN_vkGetBufferMemoryRequirements2 vkGetBufferMemoryRequirements2;
  148. extern PFN_vkGetImageMemoryRequirements2 vkGetImageMemoryRequirements2;
  149. extern PFN_vkBindBufferMemory2 vkBindBufferMemory2;
  150. extern PFN_vkBindImageMemory2 vkBindImageMemory2;
  151. extern PFN_vkGetPhysicalDeviceMemoryProperties2 vkGetPhysicalDeviceMemoryProperties2;
  152. #endif // #if VMA_VULKAN_VERSION >= 1001000
  153. #endif // #if defined(__ANDROID__) && VMA_STATIC_VULKAN_FUNCTIONS && VK_NO_PROTOTYPES
  154. #if !defined(VMA_DEDICATED_ALLOCATION)
  155. #if VK_KHR_get_memory_requirements2 && VK_KHR_dedicated_allocation
  156. #define VMA_DEDICATED_ALLOCATION 1
  157. #else
  158. #define VMA_DEDICATED_ALLOCATION 0
  159. #endif
  160. #endif
  161. #if !defined(VMA_BIND_MEMORY2)
  162. #if VK_KHR_bind_memory2
  163. #define VMA_BIND_MEMORY2 1
  164. #else
  165. #define VMA_BIND_MEMORY2 0
  166. #endif
  167. #endif
  168. #if !defined(VMA_MEMORY_BUDGET)
  169. #if VK_EXT_memory_budget && (VK_KHR_get_physical_device_properties2 || VMA_VULKAN_VERSION >= 1001000)
  170. #define VMA_MEMORY_BUDGET 1
  171. #else
  172. #define VMA_MEMORY_BUDGET 0
  173. #endif
  174. #endif
  175. // Defined to 1 when VK_KHR_buffer_device_address device extension or equivalent core Vulkan 1.2 feature is defined in its headers.
  176. #if !defined(VMA_BUFFER_DEVICE_ADDRESS)
  177. #if VK_KHR_buffer_device_address || VMA_VULKAN_VERSION >= 1002000
  178. #define VMA_BUFFER_DEVICE_ADDRESS 1
  179. #else
  180. #define VMA_BUFFER_DEVICE_ADDRESS 0
  181. #endif
  182. #endif
  183. // Defined to 1 when VK_EXT_memory_priority device extension is defined in Vulkan headers.
  184. #if !defined(VMA_MEMORY_PRIORITY)
  185. #if VK_EXT_memory_priority
  186. #define VMA_MEMORY_PRIORITY 1
  187. #else
  188. #define VMA_MEMORY_PRIORITY 0
  189. #endif
  190. #endif
  191. // Defined to 1 when VK_KHR_external_memory device extension is defined in Vulkan headers.
  192. #if !defined(VMA_EXTERNAL_MEMORY)
  193. #if VK_KHR_external_memory
  194. #define VMA_EXTERNAL_MEMORY 1
  195. #else
  196. #define VMA_EXTERNAL_MEMORY 0
  197. #endif
  198. #endif
  199. // Define these macros to decorate all public functions with additional code,
  200. // before and after returned type, appropriately. This may be useful for
  201. // exporting the functions when compiling VMA as a separate library. Example:
  202. // #define VMA_CALL_PRE __declspec(dllexport)
  203. // #define VMA_CALL_POST __cdecl
  204. #ifndef VMA_CALL_PRE
  205. #define VMA_CALL_PRE
  206. #endif
  207. #ifndef VMA_CALL_POST
  208. #define VMA_CALL_POST
  209. #endif
  210. // Define this macro to decorate pointers with an attribute specifying the
  211. // length of the array they point to if they are not null.
  212. //
  213. // The length may be one of
  214. // - The name of another parameter in the argument list where the pointer is declared
  215. // - The name of another member in the struct where the pointer is declared
  216. // - The name of a member of a struct type, meaning the value of that member in
  217. // the context of the call. For example
  218. // VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryHeapCount"),
  219. // this means the number of memory heaps available in the device associated
  220. // with the VmaAllocator being dealt with.
  221. #ifndef VMA_LEN_IF_NOT_NULL
  222. #define VMA_LEN_IF_NOT_NULL(len)
  223. #endif
  224. // The VMA_NULLABLE macro is defined to be _Nullable when compiling with Clang.
  225. // see: https://clang.llvm.org/docs/AttributeReference.html#nullable
  226. #ifndef VMA_NULLABLE
  227. #ifdef __clang__
  228. #define VMA_NULLABLE _Nullable
  229. #else
  230. #define VMA_NULLABLE
  231. #endif
  232. #endif
  233. // The VMA_NOT_NULL macro is defined to be _Nonnull when compiling with Clang.
  234. // see: https://clang.llvm.org/docs/AttributeReference.html#nonnull
  235. #ifndef VMA_NOT_NULL
  236. #ifdef __clang__
  237. #define VMA_NOT_NULL _Nonnull
  238. #else
  239. #define VMA_NOT_NULL
  240. #endif
  241. #endif
  242. // If non-dispatchable handles are represented as pointers then we can give
  243. // then nullability annotations
  244. #ifndef VMA_NOT_NULL_NON_DISPATCHABLE
  245. #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
  246. #define VMA_NOT_NULL_NON_DISPATCHABLE VMA_NOT_NULL
  247. #else
  248. #define VMA_NOT_NULL_NON_DISPATCHABLE
  249. #endif
  250. #endif
  251. #ifndef VMA_NULLABLE_NON_DISPATCHABLE
  252. #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
  253. #define VMA_NULLABLE_NON_DISPATCHABLE VMA_NULLABLE
  254. #else
  255. #define VMA_NULLABLE_NON_DISPATCHABLE
  256. #endif
  257. #endif
  258. #ifndef VMA_STATS_STRING_ENABLED
  259. #define VMA_STATS_STRING_ENABLED 1
  260. #endif
  261. ////////////////////////////////////////////////////////////////////////////////
  262. ////////////////////////////////////////////////////////////////////////////////
  263. //
  264. // INTERFACE
  265. //
  266. ////////////////////////////////////////////////////////////////////////////////
  267. ////////////////////////////////////////////////////////////////////////////////
  268. // Sections for managing code placement in file, only for development purposes e.g. for convenient folding inside an IDE.
  269. #ifndef _VMA_ENUM_DECLARATIONS
  270. /**
  271. \addtogroup group_init
  272. @{
  273. */
  274. /// Flags for created #VmaAllocator.
  275. typedef enum VmaAllocatorCreateFlagBits
  276. {
  277. /** \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.
  278. Using this flag may increase performance because internal mutexes are not used.
  279. */
  280. VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT = 0x00000001,
  281. /** \brief Enables usage of VK_KHR_dedicated_allocation extension.
  282. The flag works only if VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_0`.
  283. When it is `VK_API_VERSION_1_1`, the flag is ignored because the extension has been promoted to Vulkan 1.1.
  284. Using this extension will automatically allocate dedicated blocks of memory for
  285. some buffers and images instead of suballocating place for them out of bigger
  286. memory blocks (as if you explicitly used #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT
  287. flag) when it is recommended by the driver. It may improve performance on some
  288. GPUs.
  289. You may set this flag only if you found out that following device extensions are
  290. supported, you enabled them while creating Vulkan device passed as
  291. VmaAllocatorCreateInfo::device, and you want them to be used internally by this
  292. library:
  293. - VK_KHR_get_memory_requirements2 (device extension)
  294. - VK_KHR_dedicated_allocation (device extension)
  295. When this flag is set, you can experience following warnings reported by Vulkan
  296. validation layer. You can ignore them.
  297. > vkBindBufferMemory(): Binding memory to buffer 0x2d but vkGetBufferMemoryRequirements() has not been called on that buffer.
  298. */
  299. VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT = 0x00000002,
  300. /**
  301. Enables usage of VK_KHR_bind_memory2 extension.
  302. The flag works only if VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_0`.
  303. When it is `VK_API_VERSION_1_1`, the flag is ignored because the extension has been promoted to Vulkan 1.1.
  304. You may set this flag only if you found out that this device extension is supported,
  305. you enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device,
  306. and you want it to be used internally by this library.
  307. The extension provides functions `vkBindBufferMemory2KHR` and `vkBindImageMemory2KHR`,
  308. which allow to pass a chain of `pNext` structures while binding.
  309. This flag is required if you use `pNext` parameter in vmaBindBufferMemory2() or vmaBindImageMemory2().
  310. */
  311. VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT = 0x00000004,
  312. /**
  313. Enables usage of VK_EXT_memory_budget extension.
  314. You may set this flag only if you found out that this device extension is supported,
  315. you enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device,
  316. and you want it to be used internally by this library, along with another instance extension
  317. VK_KHR_get_physical_device_properties2, which is required by it (or Vulkan 1.1, where this extension is promoted).
  318. The extension provides query for current memory usage and budget, which will probably
  319. be more accurate than an estimation used by the library otherwise.
  320. */
  321. VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT = 0x00000008,
  322. /**
  323. Enables usage of VK_AMD_device_coherent_memory extension.
  324. You may set this flag only if you:
  325. - found out that this device extension is supported and enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device,
  326. - checked that `VkPhysicalDeviceCoherentMemoryFeaturesAMD::deviceCoherentMemory` is true and set it while creating the Vulkan device,
  327. - want it to be used internally by this library.
  328. The extension and accompanying device feature provide access to memory types with
  329. `VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD` and `VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` flags.
  330. They are useful mostly for writing breadcrumb markers - a common method for debugging GPU crash/hang/TDR.
  331. When the extension is not enabled, such memory types are still enumerated, but their usage is illegal.
  332. 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,
  333. returning `VK_ERROR_FEATURE_NOT_PRESENT`.
  334. */
  335. VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT = 0x00000010,
  336. /**
  337. Enables usage of "buffer device address" feature, which allows you to use function
  338. `vkGetBufferDeviceAddress*` to get raw GPU pointer to a buffer and pass it for usage inside a shader.
  339. You may set this flag only if you:
  340. 1. (For Vulkan version < 1.2) Found as available and enabled device extension
  341. VK_KHR_buffer_device_address.
  342. This extension is promoted to core Vulkan 1.2.
  343. 2. Found as available and enabled device feature `VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress`.
  344. When this flag is set, you can create buffers with `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT` using VMA.
  345. The library automatically adds `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT` to
  346. allocated memory blocks wherever it might be needed.
  347. For more information, see documentation chapter \ref enabling_buffer_device_address.
  348. */
  349. VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT = 0x00000020,
  350. /**
  351. Enables usage of VK_EXT_memory_priority extension in the library.
  352. You may set this flag only if you found available and enabled this device extension,
  353. along with `VkPhysicalDeviceMemoryPriorityFeaturesEXT::memoryPriority == VK_TRUE`,
  354. while creating Vulkan device passed as VmaAllocatorCreateInfo::device.
  355. When this flag is used, VmaAllocationCreateInfo::priority and VmaPoolCreateInfo::priority
  356. are used to set priorities of allocated Vulkan memory. Without it, these variables are ignored.
  357. A priority must be a floating-point value between 0 and 1, indicating the priority of the allocation relative to other memory allocations.
  358. Larger values are higher priority. The granularity of the priorities is implementation-dependent.
  359. It is automatically passed to every call to `vkAllocateMemory` done by the library using structure `VkMemoryPriorityAllocateInfoEXT`.
  360. The value to be used for default priority is 0.5.
  361. For more details, see the documentation of the VK_EXT_memory_priority extension.
  362. */
  363. VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT = 0x00000040,
  364. VMA_ALLOCATOR_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  365. } VmaAllocatorCreateFlagBits;
  366. /// See #VmaAllocatorCreateFlagBits.
  367. typedef VkFlags VmaAllocatorCreateFlags;
  368. /** @} */
  369. /**
  370. \addtogroup group_alloc
  371. @{
  372. */
  373. /// \brief Intended usage of the allocated memory.
  374. typedef enum VmaMemoryUsage
  375. {
  376. /** No intended memory usage specified.
  377. Use other members of VmaAllocationCreateInfo to specify your requirements.
  378. */
  379. VMA_MEMORY_USAGE_UNKNOWN = 0,
  380. /**
  381. \deprecated Obsolete, preserved for backward compatibility.
  382. Prefers `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`.
  383. */
  384. VMA_MEMORY_USAGE_GPU_ONLY = 1,
  385. /**
  386. \deprecated Obsolete, preserved for backward compatibility.
  387. Guarantees `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` and `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT`.
  388. */
  389. VMA_MEMORY_USAGE_CPU_ONLY = 2,
  390. /**
  391. \deprecated Obsolete, preserved for backward compatibility.
  392. Guarantees `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`, prefers `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`.
  393. */
  394. VMA_MEMORY_USAGE_CPU_TO_GPU = 3,
  395. /**
  396. \deprecated Obsolete, preserved for backward compatibility.
  397. Guarantees `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`, prefers `VK_MEMORY_PROPERTY_HOST_CACHED_BIT`.
  398. */
  399. VMA_MEMORY_USAGE_GPU_TO_CPU = 4,
  400. /**
  401. \deprecated Obsolete, preserved for backward compatibility.
  402. Prefers not `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`.
  403. */
  404. VMA_MEMORY_USAGE_CPU_COPY = 5,
  405. /**
  406. Lazily allocated GPU memory having `VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT`.
  407. Exists mostly on mobile platforms. Using it on desktop PC or other GPUs with no such memory type present will fail the allocation.
  408. Usage: Memory for transient attachment images (color attachments, depth attachments etc.), created with `VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT`.
  409. Allocations with this usage are always created as dedicated - it implies #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  410. */
  411. VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED = 6,
  412. /**
  413. Selects best memory type automatically.
  414. This flag is recommended for most common use cases.
  415. When using this flag, if you want to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT),
  416. you must pass one of the flags: #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT
  417. in VmaAllocationCreateInfo::flags.
  418. It can be used only with functions that let the library know `VkBufferCreateInfo` or `VkImageCreateInfo`, e.g.
  419. vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo()
  420. and not with generic memory allocation functions.
  421. */
  422. VMA_MEMORY_USAGE_AUTO = 7,
  423. /**
  424. Selects best memory type automatically with preference for GPU (device) memory.
  425. When using this flag, if you want to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT),
  426. you must pass one of the flags: #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT
  427. in VmaAllocationCreateInfo::flags.
  428. It can be used only with functions that let the library know `VkBufferCreateInfo` or `VkImageCreateInfo`, e.g.
  429. vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo()
  430. and not with generic memory allocation functions.
  431. */
  432. VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE = 8,
  433. /**
  434. Selects best memory type automatically with preference for CPU (host) memory.
  435. When using this flag, if you want to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT),
  436. you must pass one of the flags: #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT
  437. in VmaAllocationCreateInfo::flags.
  438. It can be used only with functions that let the library know `VkBufferCreateInfo` or `VkImageCreateInfo`, e.g.
  439. vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo()
  440. and not with generic memory allocation functions.
  441. */
  442. VMA_MEMORY_USAGE_AUTO_PREFER_HOST = 9,
  443. VMA_MEMORY_USAGE_MAX_ENUM = 0x7FFFFFFF
  444. } VmaMemoryUsage;
  445. /// Flags to be passed as VmaAllocationCreateInfo::flags.
  446. typedef enum VmaAllocationCreateFlagBits
  447. {
  448. /** \brief Set this flag if the allocation should have its own memory block.
  449. Use it for special, big resources, like fullscreen images used as attachments.
  450. */
  451. VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT = 0x00000001,
  452. /** \brief Set this flag to only try to allocate from existing `VkDeviceMemory` blocks and never create new such block.
  453. If new allocation cannot be placed in any of the existing blocks, allocation
  454. fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY` error.
  455. You should not use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT and
  456. #VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT at the same time. It makes no sense.
  457. */
  458. VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT = 0x00000002,
  459. /** \brief Set this flag to use a memory that will be persistently mapped and retrieve pointer to it.
  460. Pointer to mapped memory will be returned through VmaAllocationInfo::pMappedData.
  461. It is valid to use this flag for allocation made from memory type that is not
  462. `HOST_VISIBLE`. This flag is then ignored and memory is not mapped. This is
  463. useful if you need an allocation that is efficient to use on GPU
  464. (`DEVICE_LOCAL`) and still want to map it directly if possible on platforms that
  465. support it (e.g. Intel GPU).
  466. */
  467. VMA_ALLOCATION_CREATE_MAPPED_BIT = 0x00000004,
  468. /** \deprecated Preserved for backward compatibility. Consider using vmaSetAllocationName() instead.
  469. Set this flag to treat VmaAllocationCreateInfo::pUserData as pointer to a
  470. null-terminated string. Instead of copying pointer value, a local copy of the
  471. string is made and stored in allocation's `pName`. The string is automatically
  472. freed together with the allocation. It is also used in vmaBuildStatsString().
  473. */
  474. VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT = 0x00000020,
  475. /** Allocation will be created from upper stack in a double stack pool.
  476. This flag is only allowed for custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT flag.
  477. */
  478. VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT = 0x00000040,
  479. /** Create both buffer/image and allocation, but don't bind them together.
  480. It is useful when you want to bind yourself to do some more advanced binding, e.g. using some extensions.
  481. The flag is meaningful only with functions that bind by default: vmaCreateBuffer(), vmaCreateImage().
  482. Otherwise it is ignored.
  483. If you want to make sure the new buffer/image is not tied to the new memory allocation
  484. through `VkMemoryDedicatedAllocateInfoKHR` structure in case the allocation ends up in its own memory block,
  485. use also flag #VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT.
  486. */
  487. VMA_ALLOCATION_CREATE_DONT_BIND_BIT = 0x00000080,
  488. /** Create allocation only if additional device memory required for it, if any, won't exceed
  489. memory budget. Otherwise return `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  490. */
  491. VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT = 0x00000100,
  492. /** \brief Set this flag if the allocated memory will have aliasing resources.
  493. Usage of this flag prevents supplying `VkMemoryDedicatedAllocateInfoKHR` when #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT is specified.
  494. Otherwise created dedicated memory will not be suitable for aliasing resources, resulting in Vulkan Validation Layer errors.
  495. */
  496. VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT = 0x00000200,
  497. /**
  498. Requests possibility to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT).
  499. - If you use #VMA_MEMORY_USAGE_AUTO or other `VMA_MEMORY_USAGE_AUTO*` value,
  500. you must use this flag to be able to map the allocation. Otherwise, mapping is incorrect.
  501. - If you use other value of #VmaMemoryUsage, this flag is ignored and mapping is always possible in memory types that are `HOST_VISIBLE`.
  502. This includes allocations created in \ref custom_memory_pools.
  503. Declares that mapped memory will only be written sequentially, e.g. using `memcpy()` or a loop writing number-by-number,
  504. never read or accessed randomly, so a memory type can be selected that is uncached and write-combined.
  505. \warning Violating this declaration may work correctly, but will likely be very slow.
  506. Watch out for implicit reads introduced by doing e.g. `pMappedData[i] += x;`
  507. Better prepare your data in a local variable and `memcpy()` it to the mapped pointer all at once.
  508. */
  509. VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT = 0x00000400,
  510. /**
  511. Requests possibility to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT).
  512. - If you use #VMA_MEMORY_USAGE_AUTO or other `VMA_MEMORY_USAGE_AUTO*` value,
  513. you must use this flag to be able to map the allocation. Otherwise, mapping is incorrect.
  514. - If you use other value of #VmaMemoryUsage, this flag is ignored and mapping is always possible in memory types that are `HOST_VISIBLE`.
  515. This includes allocations created in \ref custom_memory_pools.
  516. Declares that mapped memory can be read, written, and accessed in random order,
  517. so a `HOST_CACHED` memory type is required.
  518. */
  519. VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT = 0x00000800,
  520. /**
  521. Together with #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT,
  522. it says that despite request for host access, a not-`HOST_VISIBLE` memory type can be selected
  523. if it may improve performance.
  524. By using this flag, you declare that you will check if the allocation ended up in a `HOST_VISIBLE` memory type
  525. (e.g. using vmaGetAllocationMemoryProperties()) and if not, you will create some "staging" buffer and
  526. issue an explicit transfer to write/read your data.
  527. To prepare for this possibility, don't forget to add appropriate flags like
  528. `VK_BUFFER_USAGE_TRANSFER_DST_BIT`, `VK_BUFFER_USAGE_TRANSFER_SRC_BIT` to the parameters of created buffer or image.
  529. */
  530. VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT = 0x00001000,
  531. /** Allocation strategy that chooses smallest possible free range for the allocation
  532. to minimize memory usage and fragmentation, possibly at the expense of allocation time.
  533. */
  534. VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT = 0x00010000,
  535. /** Allocation strategy that chooses first suitable free range for the allocation -
  536. not necessarily in terms of the smallest offset but the one that is easiest and fastest to find
  537. to minimize allocation time, possibly at the expense of allocation quality.
  538. */
  539. VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT = 0x00020000,
  540. /** Allocation strategy that chooses always the lowest offset in available space.
  541. This is not the most efficient strategy but achieves highly packed data.
  542. Used internally by defragmentation, not recomended in typical usage.
  543. */
  544. VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT = 0x00040000,
  545. /** Alias to #VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT.
  546. */
  547. VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT,
  548. /** Alias to #VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT.
  549. */
  550. VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT,
  551. /** A bit mask to extract only `STRATEGY` bits from entire set of flags.
  552. */
  553. VMA_ALLOCATION_CREATE_STRATEGY_MASK =
  554. VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT |
  555. VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT |
  556. VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT,
  557. VMA_ALLOCATION_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  558. } VmaAllocationCreateFlagBits;
  559. /// See #VmaAllocationCreateFlagBits.
  560. typedef VkFlags VmaAllocationCreateFlags;
  561. /// Flags to be passed as VmaPoolCreateInfo::flags.
  562. typedef enum VmaPoolCreateFlagBits
  563. {
  564. /** \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.
  565. This is an optional optimization flag.
  566. If you always allocate using vmaCreateBuffer(), vmaCreateImage(),
  567. vmaAllocateMemoryForBuffer(), then you don't need to use it because allocator
  568. knows exact type of your allocations so it can handle Buffer-Image Granularity
  569. in the optimal way.
  570. If you also allocate using vmaAllocateMemoryForImage() or vmaAllocateMemory(),
  571. exact type of such allocations is not known, so allocator must be conservative
  572. in handling Buffer-Image Granularity, which can lead to suboptimal allocation
  573. (wasted memory). In that case, if you can make sure you always allocate only
  574. buffers and linear images or only optimal images out of this pool, use this flag
  575. to make allocator disregard Buffer-Image Granularity and so make allocations
  576. faster and more optimal.
  577. */
  578. VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT = 0x00000002,
  579. /** \brief Enables alternative, linear allocation algorithm in this pool.
  580. Specify this flag to enable linear allocation algorithm, which always creates
  581. new allocations after last one and doesn't reuse space from allocations freed in
  582. between. It trades memory consumption for simplified algorithm and data
  583. structure, which has better performance and uses less memory for metadata.
  584. By using this flag, you can achieve behavior of free-at-once, stack,
  585. ring buffer, and double stack.
  586. For details, see documentation chapter \ref linear_algorithm.
  587. */
  588. VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT = 0x00000004,
  589. /** Bit mask to extract only `ALGORITHM` bits from entire set of flags.
  590. */
  591. VMA_POOL_CREATE_ALGORITHM_MASK =
  592. VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT,
  593. VMA_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  594. } VmaPoolCreateFlagBits;
  595. /// Flags to be passed as VmaPoolCreateInfo::flags. See #VmaPoolCreateFlagBits.
  596. typedef VkFlags VmaPoolCreateFlags;
  597. /// Flags to be passed as VmaDefragmentationInfo::flags.
  598. typedef enum VmaDefragmentationFlagBits
  599. {
  600. /* \brief Use simple but fast algorithm for defragmentation.
  601. May not achieve best results but will require least time to compute and least allocations to copy.
  602. */
  603. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT = 0x1,
  604. /* \brief Default defragmentation algorithm, applied also when no `ALGORITHM` flag is specified.
  605. Offers a balance between defragmentation quality and the amount of allocations and bytes that need to be moved.
  606. */
  607. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT = 0x2,
  608. /* \brief Perform full defragmentation of memory.
  609. Can result in notably more time to compute and allocations to copy, but will achieve best memory packing.
  610. */
  611. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT = 0x4,
  612. /** \brief Use the most roboust algorithm at the cost of time to compute and number of copies to make.
  613. Only available when bufferImageGranularity is greater than 1, since it aims to reduce
  614. alignment issues between different types of resources.
  615. Otherwise falls back to same behavior as #VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT.
  616. */
  617. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT = 0x8,
  618. /// A bit mask to extract only `ALGORITHM` bits from entire set of flags.
  619. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_MASK =
  620. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT |
  621. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT |
  622. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT |
  623. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT,
  624. VMA_DEFRAGMENTATION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  625. } VmaDefragmentationFlagBits;
  626. /// See #VmaDefragmentationFlagBits.
  627. typedef VkFlags VmaDefragmentationFlags;
  628. /// Operation performed on single defragmentation move. See structure #VmaDefragmentationMove.
  629. typedef enum VmaDefragmentationMoveOperation
  630. {
  631. /// Buffer/image has been recreated at `dstTmpAllocation`, data has been copied, old buffer/image has been destroyed. `srcAllocation` should be changed to point to the new place. This is the default value set by vmaBeginDefragmentationPass().
  632. VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY = 0,
  633. /// Set this value if you cannot move the allocation. New place reserved at `dstTmpAllocation` will be freed. `srcAllocation` will remain unchanged.
  634. VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE = 1,
  635. /// Set this value if you decide to abandon the allocation and you destroyed the buffer/image. New place reserved at `dstTmpAllocation` will be freed, along with `srcAllocation`, which will be destroyed.
  636. VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY = 2,
  637. } VmaDefragmentationMoveOperation;
  638. /** @} */
  639. /**
  640. \addtogroup group_virtual
  641. @{
  642. */
  643. /// Flags to be passed as VmaVirtualBlockCreateInfo::flags.
  644. typedef enum VmaVirtualBlockCreateFlagBits
  645. {
  646. /** \brief Enables alternative, linear allocation algorithm in this virtual block.
  647. Specify this flag to enable linear allocation algorithm, which always creates
  648. new allocations after last one and doesn't reuse space from allocations freed in
  649. between. It trades memory consumption for simplified algorithm and data
  650. structure, which has better performance and uses less memory for metadata.
  651. By using this flag, you can achieve behavior of free-at-once, stack,
  652. ring buffer, and double stack.
  653. For details, see documentation chapter \ref linear_algorithm.
  654. */
  655. VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT = 0x00000001,
  656. /** \brief Bit mask to extract only `ALGORITHM` bits from entire set of flags.
  657. */
  658. VMA_VIRTUAL_BLOCK_CREATE_ALGORITHM_MASK =
  659. VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT,
  660. VMA_VIRTUAL_BLOCK_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  661. } VmaVirtualBlockCreateFlagBits;
  662. /// Flags to be passed as VmaVirtualBlockCreateInfo::flags. See #VmaVirtualBlockCreateFlagBits.
  663. typedef VkFlags VmaVirtualBlockCreateFlags;
  664. /// Flags to be passed as VmaVirtualAllocationCreateInfo::flags.
  665. typedef enum VmaVirtualAllocationCreateFlagBits
  666. {
  667. /** \brief Allocation will be created from upper stack in a double stack pool.
  668. This flag is only allowed for virtual blocks created with #VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT flag.
  669. */
  670. VMA_VIRTUAL_ALLOCATION_CREATE_UPPER_ADDRESS_BIT = VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT,
  671. /** \brief Allocation strategy that tries to minimize memory usage.
  672. */
  673. VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT,
  674. /** \brief Allocation strategy that tries to minimize allocation time.
  675. */
  676. VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT,
  677. /** Allocation strategy that chooses always the lowest offset in available space.
  678. This is not the most efficient strategy but achieves highly packed data.
  679. */
  680. VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT,
  681. /** \brief A bit mask to extract only `STRATEGY` bits from entire set of flags.
  682. These strategy flags are binary compatible with equivalent flags in #VmaAllocationCreateFlagBits.
  683. */
  684. VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MASK = VMA_ALLOCATION_CREATE_STRATEGY_MASK,
  685. VMA_VIRTUAL_ALLOCATION_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  686. } VmaVirtualAllocationCreateFlagBits;
  687. /// Flags to be passed as VmaVirtualAllocationCreateInfo::flags. See #VmaVirtualAllocationCreateFlagBits.
  688. typedef VkFlags VmaVirtualAllocationCreateFlags;
  689. /** @} */
  690. #endif // _VMA_ENUM_DECLARATIONS
  691. #ifndef _VMA_DATA_TYPES_DECLARATIONS
  692. /**
  693. \addtogroup group_init
  694. @{ */
  695. /** \struct VmaAllocator
  696. \brief Represents main object of this library initialized.
  697. Fill structure #VmaAllocatorCreateInfo and call function vmaCreateAllocator() to create it.
  698. Call function vmaDestroyAllocator() to destroy it.
  699. It is recommended to create just one object of this type per `VkDevice` object,
  700. right after Vulkan is initialized and keep it alive until before Vulkan device is destroyed.
  701. */
  702. VK_DEFINE_HANDLE(VmaAllocator)
  703. /** @} */
  704. /**
  705. \addtogroup group_alloc
  706. @{
  707. */
  708. /** \struct VmaPool
  709. \brief Represents custom memory pool
  710. Fill structure VmaPoolCreateInfo and call function vmaCreatePool() to create it.
  711. Call function vmaDestroyPool() to destroy it.
  712. For more information see [Custom memory pools](@ref choosing_memory_type_custom_memory_pools).
  713. */
  714. VK_DEFINE_HANDLE(VmaPool)
  715. /** \struct VmaAllocation
  716. \brief Represents single memory allocation.
  717. It may be either dedicated block of `VkDeviceMemory` or a specific region of a bigger block of this type
  718. plus unique offset.
  719. There are multiple ways to create such object.
  720. You need to fill structure VmaAllocationCreateInfo.
  721. For more information see [Choosing memory type](@ref choosing_memory_type).
  722. Although the library provides convenience functions that create Vulkan buffer or image,
  723. allocate memory for it and bind them together,
  724. binding of the allocation to a buffer or an image is out of scope of the allocation itself.
  725. Allocation object can exist without buffer/image bound,
  726. binding can be done manually by the user, and destruction of it can be done
  727. independently of destruction of the allocation.
  728. The object also remembers its size and some other information.
  729. To retrieve this information, use function vmaGetAllocationInfo() and inspect
  730. returned structure VmaAllocationInfo.
  731. */
  732. VK_DEFINE_HANDLE(VmaAllocation)
  733. /** \struct VmaDefragmentationContext
  734. \brief An opaque object that represents started defragmentation process.
  735. Fill structure #VmaDefragmentationInfo and call function vmaBeginDefragmentation() to create it.
  736. Call function vmaEndDefragmentation() to destroy it.
  737. */
  738. VK_DEFINE_HANDLE(VmaDefragmentationContext)
  739. /** @} */
  740. /**
  741. \addtogroup group_virtual
  742. @{
  743. */
  744. /** \struct VmaVirtualAllocation
  745. \brief Represents single memory allocation done inside VmaVirtualBlock.
  746. Use it as a unique identifier to virtual allocation within the single block.
  747. Use value `VK_NULL_HANDLE` to represent a null/invalid allocation.
  748. */
  749. VK_DEFINE_NON_DISPATCHABLE_HANDLE(VmaVirtualAllocation);
  750. /** @} */
  751. /**
  752. \addtogroup group_virtual
  753. @{
  754. */
  755. /** \struct VmaVirtualBlock
  756. \brief Handle to a virtual block object that allows to use core allocation algorithm without allocating any real GPU memory.
  757. Fill in #VmaVirtualBlockCreateInfo structure and use vmaCreateVirtualBlock() to create it. Use vmaDestroyVirtualBlock() to destroy it.
  758. For more information, see documentation chapter \ref virtual_allocator.
  759. This object is not thread-safe - should not be used from multiple threads simultaneously, must be synchronized externally.
  760. */
  761. VK_DEFINE_HANDLE(VmaVirtualBlock)
  762. /** @} */
  763. /**
  764. \addtogroup group_init
  765. @{
  766. */
  767. /// Callback function called after successful vkAllocateMemory.
  768. typedef void (VKAPI_PTR* PFN_vmaAllocateDeviceMemoryFunction)(
  769. VmaAllocator VMA_NOT_NULL allocator,
  770. uint32_t memoryType,
  771. VkDeviceMemory VMA_NOT_NULL_NON_DISPATCHABLE memory,
  772. VkDeviceSize size,
  773. void* VMA_NULLABLE pUserData);
  774. /// Callback function called before vkFreeMemory.
  775. typedef void (VKAPI_PTR* PFN_vmaFreeDeviceMemoryFunction)(
  776. VmaAllocator VMA_NOT_NULL allocator,
  777. uint32_t memoryType,
  778. VkDeviceMemory VMA_NOT_NULL_NON_DISPATCHABLE memory,
  779. VkDeviceSize size,
  780. void* VMA_NULLABLE pUserData);
  781. /** \brief Set of callbacks that the library will call for `vkAllocateMemory` and `vkFreeMemory`.
  782. Provided for informative purpose, e.g. to gather statistics about number of
  783. allocations or total amount of memory allocated in Vulkan.
  784. Used in VmaAllocatorCreateInfo::pDeviceMemoryCallbacks.
  785. */
  786. typedef struct VmaDeviceMemoryCallbacks
  787. {
  788. /// Optional, can be null.
  789. PFN_vmaAllocateDeviceMemoryFunction VMA_NULLABLE pfnAllocate;
  790. /// Optional, can be null.
  791. PFN_vmaFreeDeviceMemoryFunction VMA_NULLABLE pfnFree;
  792. /// Optional, can be null.
  793. void* VMA_NULLABLE pUserData;
  794. } VmaDeviceMemoryCallbacks;
  795. /** \brief Pointers to some Vulkan functions - a subset used by the library.
  796. Used in VmaAllocatorCreateInfo::pVulkanFunctions.
  797. */
  798. typedef struct VmaVulkanFunctions
  799. {
  800. /// Required when using VMA_DYNAMIC_VULKAN_FUNCTIONS.
  801. PFN_vkGetInstanceProcAddr VMA_NULLABLE vkGetInstanceProcAddr;
  802. /// Required when using VMA_DYNAMIC_VULKAN_FUNCTIONS.
  803. PFN_vkGetDeviceProcAddr VMA_NULLABLE vkGetDeviceProcAddr;
  804. PFN_vkGetPhysicalDeviceProperties VMA_NULLABLE vkGetPhysicalDeviceProperties;
  805. PFN_vkGetPhysicalDeviceMemoryProperties VMA_NULLABLE vkGetPhysicalDeviceMemoryProperties;
  806. PFN_vkAllocateMemory VMA_NULLABLE vkAllocateMemory;
  807. PFN_vkFreeMemory VMA_NULLABLE vkFreeMemory;
  808. PFN_vkMapMemory VMA_NULLABLE vkMapMemory;
  809. PFN_vkUnmapMemory VMA_NULLABLE vkUnmapMemory;
  810. PFN_vkFlushMappedMemoryRanges VMA_NULLABLE vkFlushMappedMemoryRanges;
  811. PFN_vkInvalidateMappedMemoryRanges VMA_NULLABLE vkInvalidateMappedMemoryRanges;
  812. PFN_vkBindBufferMemory VMA_NULLABLE vkBindBufferMemory;
  813. PFN_vkBindImageMemory VMA_NULLABLE vkBindImageMemory;
  814. PFN_vkGetBufferMemoryRequirements VMA_NULLABLE vkGetBufferMemoryRequirements;
  815. PFN_vkGetImageMemoryRequirements VMA_NULLABLE vkGetImageMemoryRequirements;
  816. PFN_vkCreateBuffer VMA_NULLABLE vkCreateBuffer;
  817. PFN_vkDestroyBuffer VMA_NULLABLE vkDestroyBuffer;
  818. PFN_vkCreateImage VMA_NULLABLE vkCreateImage;
  819. PFN_vkDestroyImage VMA_NULLABLE vkDestroyImage;
  820. PFN_vkCmdCopyBuffer VMA_NULLABLE vkCmdCopyBuffer;
  821. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  822. /// Fetch "vkGetBufferMemoryRequirements2" on Vulkan >= 1.1, fetch "vkGetBufferMemoryRequirements2KHR" when using VK_KHR_dedicated_allocation extension.
  823. PFN_vkGetBufferMemoryRequirements2KHR VMA_NULLABLE vkGetBufferMemoryRequirements2KHR;
  824. /// Fetch "vkGetImageMemoryRequirements2" on Vulkan >= 1.1, fetch "vkGetImageMemoryRequirements2KHR" when using VK_KHR_dedicated_allocation extension.
  825. PFN_vkGetImageMemoryRequirements2KHR VMA_NULLABLE vkGetImageMemoryRequirements2KHR;
  826. #endif
  827. #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000
  828. /// Fetch "vkBindBufferMemory2" on Vulkan >= 1.1, fetch "vkBindBufferMemory2KHR" when using VK_KHR_bind_memory2 extension.
  829. PFN_vkBindBufferMemory2KHR VMA_NULLABLE vkBindBufferMemory2KHR;
  830. /// Fetch "vkBindImageMemory2" on Vulkan >= 1.1, fetch "vkBindImageMemory2KHR" when using VK_KHR_bind_memory2 extension.
  831. PFN_vkBindImageMemory2KHR VMA_NULLABLE vkBindImageMemory2KHR;
  832. #endif
  833. #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000
  834. PFN_vkGetPhysicalDeviceMemoryProperties2KHR VMA_NULLABLE vkGetPhysicalDeviceMemoryProperties2KHR;
  835. #endif
  836. #if VMA_VULKAN_VERSION >= 1003000
  837. /// Fetch from "vkGetDeviceBufferMemoryRequirements" on Vulkan >= 1.3, but you can also fetch it from "vkGetDeviceBufferMemoryRequirementsKHR" if you enabled extension VK_KHR_maintenance4.
  838. PFN_vkGetDeviceBufferMemoryRequirements VMA_NULLABLE vkGetDeviceBufferMemoryRequirements;
  839. /// Fetch from "vkGetDeviceImageMemoryRequirements" on Vulkan >= 1.3, but you can also fetch it from "vkGetDeviceImageMemoryRequirementsKHR" if you enabled extension VK_KHR_maintenance4.
  840. PFN_vkGetDeviceImageMemoryRequirements VMA_NULLABLE vkGetDeviceImageMemoryRequirements;
  841. #endif
  842. } VmaVulkanFunctions;
  843. /// Description of a Allocator to be created.
  844. typedef struct VmaAllocatorCreateInfo
  845. {
  846. /// Flags for created allocator. Use #VmaAllocatorCreateFlagBits enum.
  847. VmaAllocatorCreateFlags flags;
  848. /// Vulkan physical device.
  849. /** It must be valid throughout whole lifetime of created allocator. */
  850. VkPhysicalDevice VMA_NOT_NULL physicalDevice;
  851. /// Vulkan device.
  852. /** It must be valid throughout whole lifetime of created allocator. */
  853. VkDevice VMA_NOT_NULL device;
  854. /// Preferred size of a single `VkDeviceMemory` block to be allocated from large heaps > 1 GiB. Optional.
  855. /** Set to 0 to use default, which is currently 256 MiB. */
  856. VkDeviceSize preferredLargeHeapBlockSize;
  857. /// Custom CPU memory allocation callbacks. Optional.
  858. /** Optional, can be null. When specified, will also be used for all CPU-side memory allocations. */
  859. const VkAllocationCallbacks* VMA_NULLABLE pAllocationCallbacks;
  860. /// Informative callbacks for `vkAllocateMemory`, `vkFreeMemory`. Optional.
  861. /** Optional, can be null. */
  862. const VmaDeviceMemoryCallbacks* VMA_NULLABLE pDeviceMemoryCallbacks;
  863. /** \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.
  864. If not NULL, it must be a pointer to an array of
  865. `VkPhysicalDeviceMemoryProperties::memoryHeapCount` elements, defining limit on
  866. maximum number of bytes that can be allocated out of particular Vulkan memory
  867. heap.
  868. Any of the elements may be equal to `VK_WHOLE_SIZE`, which means no limit on that
  869. heap. This is also the default in case of `pHeapSizeLimit` = NULL.
  870. If there is a limit defined for a heap:
  871. - If user tries to allocate more memory from that heap using this allocator,
  872. the allocation fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  873. - If the limit is smaller than heap size reported in `VkMemoryHeap::size`, the
  874. value of this limit will be reported instead when using vmaGetMemoryProperties().
  875. Warning! Using this feature may not be equivalent to installing a GPU with
  876. smaller amount of memory, because graphics driver doesn't necessary fail new
  877. allocations with `VK_ERROR_OUT_OF_DEVICE_MEMORY` result when memory capacity is
  878. exceeded. It may return success and just silently migrate some device memory
  879. blocks to system RAM. This driver behavior can also be controlled using
  880. VK_AMD_memory_overallocation_behavior extension.
  881. */
  882. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryHeapCount") pHeapSizeLimit;
  883. /** \brief Pointers to Vulkan functions. Can be null.
  884. For details see [Pointers to Vulkan functions](@ref config_Vulkan_functions).
  885. */
  886. const VmaVulkanFunctions* VMA_NULLABLE pVulkanFunctions;
  887. /** \brief Handle to Vulkan instance object.
  888. Starting from version 3.0.0 this member is no longer optional, it must be set!
  889. */
  890. VkInstance VMA_NOT_NULL instance;
  891. /** \brief Optional. The highest version of Vulkan that the application is designed to use.
  892. 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`.
  893. The patch version number specified is ignored. Only the major and minor versions are considered.
  894. It must be less or equal (preferably equal) to value as passed to `vkCreateInstance` as `VkApplicationInfo::apiVersion`.
  895. Only versions 1.0, 1.1, 1.2, 1.3 are supported by the current implementation.
  896. Leaving it initialized to zero is equivalent to `VK_API_VERSION_1_0`.
  897. */
  898. uint32_t vulkanApiVersion;
  899. #if VMA_EXTERNAL_MEMORY
  900. /** \brief Either null or a pointer to an array of external memory handle types for each Vulkan memory type.
  901. If not NULL, it must be a pointer to an array of `VkPhysicalDeviceMemoryProperties::memoryTypeCount`
  902. elements, defining external memory handle types of particular Vulkan memory type,
  903. to be passed using `VkExportMemoryAllocateInfoKHR`.
  904. Any of the elements may be equal to 0, which means not to use `VkExportMemoryAllocateInfoKHR` on this memory type.
  905. This is also the default in case of `pTypeExternalMemoryHandleTypes` = NULL.
  906. */
  907. const VkExternalMemoryHandleTypeFlagsKHR* VMA_NULLABLE VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryTypeCount") pTypeExternalMemoryHandleTypes;
  908. #endif // #if VMA_EXTERNAL_MEMORY
  909. } VmaAllocatorCreateInfo;
  910. /// Information about existing #VmaAllocator object.
  911. typedef struct VmaAllocatorInfo
  912. {
  913. /** \brief Handle to Vulkan instance object.
  914. This is the same value as has been passed through VmaAllocatorCreateInfo::instance.
  915. */
  916. VkInstance VMA_NOT_NULL instance;
  917. /** \brief Handle to Vulkan physical device object.
  918. This is the same value as has been passed through VmaAllocatorCreateInfo::physicalDevice.
  919. */
  920. VkPhysicalDevice VMA_NOT_NULL physicalDevice;
  921. /** \brief Handle to Vulkan device object.
  922. This is the same value as has been passed through VmaAllocatorCreateInfo::device.
  923. */
  924. VkDevice VMA_NOT_NULL device;
  925. } VmaAllocatorInfo;
  926. /** @} */
  927. /**
  928. \addtogroup group_stats
  929. @{
  930. */
  931. /** \brief Calculated statistics of memory usage e.g. in a specific memory type, heap, custom pool, or total.
  932. These are fast to calculate.
  933. See functions: vmaGetHeapBudgets(), vmaGetPoolStatistics().
  934. */
  935. typedef struct VmaStatistics
  936. {
  937. /** \brief Number of `VkDeviceMemory` objects - Vulkan memory blocks allocated.
  938. */
  939. uint32_t blockCount;
  940. /** \brief Number of #VmaAllocation objects allocated.
  941. Dedicated allocations have their own blocks, so each one adds 1 to `allocationCount` as well as `blockCount`.
  942. */
  943. uint32_t allocationCount;
  944. /** \brief Number of bytes allocated in `VkDeviceMemory` blocks.
  945. \note To avoid confusion, please be aware that what Vulkan calls an "allocation" - a whole `VkDeviceMemory` object
  946. (e.g. as in `VkPhysicalDeviceLimits::maxMemoryAllocationCount`) is called a "block" in VMA, while VMA calls
  947. "allocation" a #VmaAllocation object that represents a memory region sub-allocated from such block, usually for a single buffer or image.
  948. */
  949. VkDeviceSize blockBytes;
  950. /** \brief Total number of bytes occupied by all #VmaAllocation objects.
  951. Always less or equal than `blockBytes`.
  952. Difference `(blockBytes - allocationBytes)` is the amount of memory allocated from Vulkan
  953. but unused by any #VmaAllocation.
  954. */
  955. VkDeviceSize allocationBytes;
  956. } VmaStatistics;
  957. /** \brief More detailed statistics than #VmaStatistics.
  958. These are slower to calculate. Use for debugging purposes.
  959. See functions: vmaCalculateStatistics(), vmaCalculatePoolStatistics().
  960. Previous version of the statistics API provided averages, but they have been removed
  961. because they can be easily calculated as:
  962. \code
  963. VkDeviceSize allocationSizeAvg = detailedStats.statistics.allocationBytes / detailedStats.statistics.allocationCount;
  964. VkDeviceSize unusedBytes = detailedStats.statistics.blockBytes - detailedStats.statistics.allocationBytes;
  965. VkDeviceSize unusedRangeSizeAvg = unusedBytes / detailedStats.unusedRangeCount;
  966. \endcode
  967. */
  968. typedef struct VmaDetailedStatistics
  969. {
  970. /// Basic statistics.
  971. VmaStatistics statistics;
  972. /// Number of free ranges of memory between allocations.
  973. uint32_t unusedRangeCount;
  974. /// Smallest allocation size. `VK_WHOLE_SIZE` if there are 0 allocations.
  975. VkDeviceSize allocationSizeMin;
  976. /// Largest allocation size. 0 if there are 0 allocations.
  977. VkDeviceSize allocationSizeMax;
  978. /// Smallest empty range size. `VK_WHOLE_SIZE` if there are 0 empty ranges.
  979. VkDeviceSize unusedRangeSizeMin;
  980. /// Largest empty range size. 0 if there are 0 empty ranges.
  981. VkDeviceSize unusedRangeSizeMax;
  982. } VmaDetailedStatistics;
  983. /** \brief General statistics from current state of the Allocator -
  984. total memory usage across all memory heaps and types.
  985. These are slower to calculate. Use for debugging purposes.
  986. See function vmaCalculateStatistics().
  987. */
  988. typedef struct VmaTotalStatistics
  989. {
  990. VmaDetailedStatistics memoryType[VK_MAX_MEMORY_TYPES];
  991. VmaDetailedStatistics memoryHeap[VK_MAX_MEMORY_HEAPS];
  992. VmaDetailedStatistics total;
  993. } VmaTotalStatistics;
  994. /** \brief Statistics of current memory usage and available budget for a specific memory heap.
  995. These are fast to calculate.
  996. See function vmaGetHeapBudgets().
  997. */
  998. typedef struct VmaBudget
  999. {
  1000. /** \brief Statistics fetched from the library.
  1001. */
  1002. VmaStatistics statistics;
  1003. /** \brief Estimated current memory usage of the program, in bytes.
  1004. Fetched from system using VK_EXT_memory_budget extension if enabled.
  1005. It might be different than `statistics.blockBytes` (usually higher) due to additional implicit objects
  1006. also occupying the memory, like swapchain, pipelines, descriptor heaps, command buffers, or
  1007. `VkDeviceMemory` blocks allocated outside of this library, if any.
  1008. */
  1009. VkDeviceSize usage;
  1010. /** \brief Estimated amount of memory available to the program, in bytes.
  1011. Fetched from system using VK_EXT_memory_budget extension if enabled.
  1012. It might be different (most probably smaller) than `VkMemoryHeap::size[heapIndex]` due to factors
  1013. external to the program, decided by the operating system.
  1014. Difference `budget - usage` is the amount of additional memory that can probably
  1015. be allocated without problems. Exceeding the budget may result in various problems.
  1016. */
  1017. VkDeviceSize budget;
  1018. } VmaBudget;
  1019. /** @} */
  1020. /**
  1021. \addtogroup group_alloc
  1022. @{
  1023. */
  1024. /** \brief Parameters of new #VmaAllocation.
  1025. To be used with functions like vmaCreateBuffer(), vmaCreateImage(), and many others.
  1026. */
  1027. typedef struct VmaAllocationCreateInfo
  1028. {
  1029. /// Use #VmaAllocationCreateFlagBits enum.
  1030. VmaAllocationCreateFlags flags;
  1031. /** \brief Intended usage of memory.
  1032. You can leave #VMA_MEMORY_USAGE_UNKNOWN if you specify memory requirements in other way. \n
  1033. If `pool` is not null, this member is ignored.
  1034. */
  1035. VmaMemoryUsage usage;
  1036. /** \brief Flags that must be set in a Memory Type chosen for an allocation.
  1037. Leave 0 if you specify memory requirements in other way. \n
  1038. If `pool` is not null, this member is ignored.*/
  1039. VkMemoryPropertyFlags requiredFlags;
  1040. /** \brief Flags that preferably should be set in a memory type chosen for an allocation.
  1041. Set to 0 if no additional flags are preferred. \n
  1042. If `pool` is not null, this member is ignored. */
  1043. VkMemoryPropertyFlags preferredFlags;
  1044. /** \brief Bitmask containing one bit set for every memory type acceptable for this allocation.
  1045. Value 0 is equivalent to `UINT32_MAX` - it means any memory type is accepted if
  1046. it meets other requirements specified by this structure, with no further
  1047. restrictions on memory type index. \n
  1048. If `pool` is not null, this member is ignored.
  1049. */
  1050. uint32_t memoryTypeBits;
  1051. /** \brief Pool that this allocation should be created in.
  1052. Leave `VK_NULL_HANDLE` to allocate from default pool. If not null, members:
  1053. `usage`, `requiredFlags`, `preferredFlags`, `memoryTypeBits` are ignored.
  1054. */
  1055. VmaPool VMA_NULLABLE pool;
  1056. /** \brief Custom general-purpose pointer that will be stored in #VmaAllocation, can be read as VmaAllocationInfo::pUserData and changed using vmaSetAllocationUserData().
  1057. If #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT is used, it must be either
  1058. null or pointer to a null-terminated string. The string will be then copied to
  1059. internal buffer, so it doesn't need to be valid after allocation call.
  1060. */
  1061. void* VMA_NULLABLE pUserData;
  1062. /** \brief A floating-point value between 0 and 1, indicating the priority of the allocation relative to other memory allocations.
  1063. It is used only when #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT flag was used during creation of the #VmaAllocator object
  1064. and this allocation ends up as dedicated or is explicitly forced as dedicated using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  1065. Otherwise, it has the priority of a memory block where it is placed and this variable is ignored.
  1066. */
  1067. float priority;
  1068. } VmaAllocationCreateInfo;
  1069. /// Describes parameter of created #VmaPool.
  1070. typedef struct VmaPoolCreateInfo
  1071. {
  1072. /** \brief Vulkan memory type index to allocate this pool from.
  1073. */
  1074. uint32_t memoryTypeIndex;
  1075. /** \brief Use combination of #VmaPoolCreateFlagBits.
  1076. */
  1077. VmaPoolCreateFlags flags;
  1078. /** \brief Size of a single `VkDeviceMemory` block to be allocated as part of this pool, in bytes. Optional.
  1079. Specify nonzero to set explicit, constant size of memory blocks used by this
  1080. pool.
  1081. Leave 0 to use default and let the library manage block sizes automatically.
  1082. Sizes of particular blocks may vary.
  1083. In this case, the pool will also support dedicated allocations.
  1084. */
  1085. VkDeviceSize blockSize;
  1086. /** \brief Minimum number of blocks to be always allocated in this pool, even if they stay empty.
  1087. Set to 0 to have no preallocated blocks and allow the pool be completely empty.
  1088. */
  1089. size_t minBlockCount;
  1090. /** \brief Maximum number of blocks that can be allocated in this pool. Optional.
  1091. Set to 0 to use default, which is `SIZE_MAX`, which means no limit.
  1092. Set to same value as VmaPoolCreateInfo::minBlockCount to have fixed amount of memory allocated
  1093. throughout whole lifetime of this pool.
  1094. */
  1095. size_t maxBlockCount;
  1096. /** \brief A floating-point value between 0 and 1, indicating the priority of the allocations in this pool relative to other memory allocations.
  1097. It is used only when #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT flag was used during creation of the #VmaAllocator object.
  1098. Otherwise, this variable is ignored.
  1099. */
  1100. float priority;
  1101. /** \brief Additional minimum alignment to be used for all allocations created from this pool. Can be 0.
  1102. Leave 0 (default) not to impose any additional alignment. If not 0, it must be a power of two.
  1103. It can be useful in cases where alignment returned by Vulkan by functions like `vkGetBufferMemoryRequirements` is not enough,
  1104. e.g. when doing interop with OpenGL.
  1105. */
  1106. VkDeviceSize minAllocationAlignment;
  1107. /** \brief Additional `pNext` chain to be attached to `VkMemoryAllocateInfo` used for every allocation made by this pool. Optional.
  1108. Optional, can be null. If not null, it must point to a `pNext` chain of structures that can be attached to `VkMemoryAllocateInfo`.
  1109. It can be useful for special needs such as adding `VkExportMemoryAllocateInfoKHR`.
  1110. Structures pointed by this member must remain alive and unchanged for the whole lifetime of the custom pool.
  1111. Please note that some structures, e.g. `VkMemoryPriorityAllocateInfoEXT`, `VkMemoryDedicatedAllocateInfoKHR`,
  1112. can be attached automatically by this library when using other, more convenient of its features.
  1113. */
  1114. void* VMA_NULLABLE pMemoryAllocateNext;
  1115. } VmaPoolCreateInfo;
  1116. /** @} */
  1117. /**
  1118. \addtogroup group_alloc
  1119. @{
  1120. */
  1121. /// Parameters of #VmaAllocation objects, that can be retrieved using function vmaGetAllocationInfo().
  1122. typedef struct VmaAllocationInfo
  1123. {
  1124. /** \brief Memory type index that this allocation was allocated from.
  1125. It never changes.
  1126. */
  1127. uint32_t memoryType;
  1128. /** \brief Handle to Vulkan memory object.
  1129. Same memory object can be shared by multiple allocations.
  1130. It can change after the allocation is moved during \ref defragmentation.
  1131. */
  1132. VkDeviceMemory VMA_NULLABLE_NON_DISPATCHABLE deviceMemory;
  1133. /** \brief Offset in `VkDeviceMemory` object to the beginning of this allocation, in bytes. `(deviceMemory, offset)` pair is unique to this allocation.
  1134. 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
  1135. vmaCreateBuffer(), vmaCreateImage(), functions that operate on these resources refer to the beginning of the buffer or image,
  1136. not entire device memory block. Functions like vmaMapMemory(), vmaBindBufferMemory() also refer to the beginning of the allocation
  1137. and apply this offset automatically.
  1138. It can change after the allocation is moved during \ref defragmentation.
  1139. */
  1140. VkDeviceSize offset;
  1141. /** \brief Size of this allocation, in bytes.
  1142. It never changes.
  1143. \note Allocation size returned in this variable may be greater than the size
  1144. requested for the resource e.g. as `VkBufferCreateInfo::size`. Whole size of the
  1145. allocation is accessible for operations on memory e.g. using a pointer after
  1146. mapping with vmaMapMemory(), but operations on the resource e.g. using
  1147. `vkCmdCopyBuffer` must be limited to the size of the resource.
  1148. */
  1149. VkDeviceSize size;
  1150. /** \brief Pointer to the beginning of this allocation as mapped data.
  1151. If the allocation hasn't been mapped using vmaMapMemory() and hasn't been
  1152. created with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag, this value is null.
  1153. It can change after call to vmaMapMemory(), vmaUnmapMemory().
  1154. It can also change after the allocation is moved during \ref defragmentation.
  1155. */
  1156. void* VMA_NULLABLE pMappedData;
  1157. /** \brief Custom general-purpose pointer that was passed as VmaAllocationCreateInfo::pUserData or set using vmaSetAllocationUserData().
  1158. It can change after call to vmaSetAllocationUserData() for this allocation.
  1159. */
  1160. void* VMA_NULLABLE pUserData;
  1161. /** \brief Custom allocation name that was set with vmaSetAllocationName().
  1162. It can change after call to vmaSetAllocationName() for this allocation.
  1163. Another way to set custom name is to pass it in VmaAllocationCreateInfo::pUserData with
  1164. additional flag #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT set [DEPRECATED].
  1165. */
  1166. const char* VMA_NULLABLE pName;
  1167. } VmaAllocationInfo;
  1168. /** \brief Parameters for defragmentation.
  1169. To be used with function vmaBeginDefragmentation().
  1170. */
  1171. typedef struct VmaDefragmentationInfo
  1172. {
  1173. /// \brief Use combination of #VmaDefragmentationFlagBits.
  1174. VmaDefragmentationFlags flags;
  1175. /** \brief Custom pool to be defragmented.
  1176. If null then default pools will undergo defragmentation process.
  1177. */
  1178. VmaPool VMA_NULLABLE pool;
  1179. /** \brief Maximum numbers of bytes that can be copied during single pass, while moving allocations to different places.
  1180. `0` means no limit.
  1181. */
  1182. VkDeviceSize maxBytesPerPass;
  1183. /** \brief Maximum number of allocations that can be moved during single pass to a different place.
  1184. `0` means no limit.
  1185. */
  1186. uint32_t maxAllocationsPerPass;
  1187. } VmaDefragmentationInfo;
  1188. /// Single move of an allocation to be done for defragmentation.
  1189. typedef struct VmaDefragmentationMove
  1190. {
  1191. /// Operation to be performed on the allocation by vmaEndDefragmentationPass(). Default value is #VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY. You can modify it.
  1192. VmaDefragmentationMoveOperation operation;
  1193. /// Allocation that should be moved.
  1194. VmaAllocation VMA_NOT_NULL srcAllocation;
  1195. /** \brief Temporary allocation pointing to destination memory that will replace `srcAllocation`.
  1196. \warning Do not store this allocation in your data structures! It exists only temporarily, for the duration of the defragmentation pass,
  1197. to be used for binding new buffer/image to the destination memory using e.g. vmaBindBufferMemory().
  1198. vmaEndDefragmentationPass() will destroy it and make `srcAllocation` point to this memory.
  1199. */
  1200. VmaAllocation VMA_NOT_NULL dstTmpAllocation;
  1201. } VmaDefragmentationMove;
  1202. /** \brief Parameters for incremental defragmentation steps.
  1203. To be used with function vmaBeginDefragmentationPass().
  1204. */
  1205. typedef struct VmaDefragmentationPassMoveInfo
  1206. {
  1207. /// Number of elements in the `pMoves` array.
  1208. uint32_t moveCount;
  1209. /** \brief Array of moves to be performed by the user in the current defragmentation pass.
  1210. Pointer to an array of `moveCount` elements, owned by VMA, created in vmaBeginDefragmentationPass(), destroyed in vmaEndDefragmentationPass().
  1211. For each element, you should:
  1212. 1. Create a new buffer/image in the place pointed by VmaDefragmentationMove::dstMemory + VmaDefragmentationMove::dstOffset.
  1213. 2. Copy data from the VmaDefragmentationMove::srcAllocation e.g. using `vkCmdCopyBuffer`, `vkCmdCopyImage`.
  1214. 3. Make sure these commands finished executing on the GPU.
  1215. 4. Destroy the old buffer/image.
  1216. Only then you can finish defragmentation pass by calling vmaEndDefragmentationPass().
  1217. After this call, the allocation will point to the new place in memory.
  1218. Alternatively, if you cannot move specific allocation, you can set VmaDefragmentationMove::operation to #VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE.
  1219. Alternatively, if you decide you want to completely remove the allocation:
  1220. 1. Destroy its buffer/image.
  1221. 2. Set VmaDefragmentationMove::operation to #VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY.
  1222. Then, after vmaEndDefragmentationPass() the allocation will be freed.
  1223. */
  1224. VmaDefragmentationMove* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(moveCount) pMoves;
  1225. } VmaDefragmentationPassMoveInfo;
  1226. /// Statistics returned for defragmentation process in function vmaEndDefragmentation().
  1227. typedef struct VmaDefragmentationStats
  1228. {
  1229. /// Total number of bytes that have been copied while moving allocations to different places.
  1230. VkDeviceSize bytesMoved;
  1231. /// Total number of bytes that have been released to the system by freeing empty `VkDeviceMemory` objects.
  1232. VkDeviceSize bytesFreed;
  1233. /// Number of allocations that have been moved to different places.
  1234. uint32_t allocationsMoved;
  1235. /// Number of empty `VkDeviceMemory` objects that have been released to the system.
  1236. uint32_t deviceMemoryBlocksFreed;
  1237. } VmaDefragmentationStats;
  1238. /** @} */
  1239. /**
  1240. \addtogroup group_virtual
  1241. @{
  1242. */
  1243. /// Parameters of created #VmaVirtualBlock object to be passed to vmaCreateVirtualBlock().
  1244. typedef struct VmaVirtualBlockCreateInfo
  1245. {
  1246. /** \brief Total size of the virtual block.
  1247. Sizes can be expressed in bytes or any units you want as long as you are consistent in using them.
  1248. For example, if you allocate from some array of structures, 1 can mean single instance of entire structure.
  1249. */
  1250. VkDeviceSize size;
  1251. /** \brief Use combination of #VmaVirtualBlockCreateFlagBits.
  1252. */
  1253. VmaVirtualBlockCreateFlags flags;
  1254. /** \brief Custom CPU memory allocation callbacks. Optional.
  1255. Optional, can be null. When specified, they will be used for all CPU-side memory allocations.
  1256. */
  1257. const VkAllocationCallbacks* VMA_NULLABLE pAllocationCallbacks;
  1258. } VmaVirtualBlockCreateInfo;
  1259. /// Parameters of created virtual allocation to be passed to vmaVirtualAllocate().
  1260. typedef struct VmaVirtualAllocationCreateInfo
  1261. {
  1262. /** \brief Size of the allocation.
  1263. Cannot be zero.
  1264. */
  1265. VkDeviceSize size;
  1266. /** \brief Required alignment of the allocation. Optional.
  1267. Must be power of two. Special value 0 has the same meaning as 1 - means no special alignment is required, so allocation can start at any offset.
  1268. */
  1269. VkDeviceSize alignment;
  1270. /** \brief Use combination of #VmaVirtualAllocationCreateFlagBits.
  1271. */
  1272. VmaVirtualAllocationCreateFlags flags;
  1273. /** \brief Custom pointer to be associated with the allocation. Optional.
  1274. It can be any value and can be used for user-defined purposes. It can be fetched or changed later.
  1275. */
  1276. void* VMA_NULLABLE pUserData;
  1277. } VmaVirtualAllocationCreateInfo;
  1278. /// Parameters of an existing virtual allocation, returned by vmaGetVirtualAllocationInfo().
  1279. typedef struct VmaVirtualAllocationInfo
  1280. {
  1281. /** \brief Offset of the allocation.
  1282. Offset at which the allocation was made.
  1283. */
  1284. VkDeviceSize offset;
  1285. /** \brief Size of the allocation.
  1286. Same value as passed in VmaVirtualAllocationCreateInfo::size.
  1287. */
  1288. VkDeviceSize size;
  1289. /** \brief Custom pointer associated with the allocation.
  1290. Same value as passed in VmaVirtualAllocationCreateInfo::pUserData or to vmaSetVirtualAllocationUserData().
  1291. */
  1292. void* VMA_NULLABLE pUserData;
  1293. } VmaVirtualAllocationInfo;
  1294. /** @} */
  1295. #endif // _VMA_DATA_TYPES_DECLARATIONS
  1296. #ifndef _VMA_FUNCTION_HEADERS
  1297. /**
  1298. \addtogroup group_init
  1299. @{
  1300. */
  1301. /// Creates #VmaAllocator object.
  1302. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAllocator(
  1303. const VmaAllocatorCreateInfo* VMA_NOT_NULL pCreateInfo,
  1304. VmaAllocator VMA_NULLABLE* VMA_NOT_NULL pAllocator);
  1305. /// Destroys allocator object.
  1306. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyAllocator(
  1307. VmaAllocator VMA_NULLABLE allocator);
  1308. /** \brief Returns information about existing #VmaAllocator object - handle to Vulkan device etc.
  1309. It might be useful if you want to keep just the #VmaAllocator handle and fetch other required handles to
  1310. `VkPhysicalDevice`, `VkDevice` etc. every time using this function.
  1311. */
  1312. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocatorInfo(
  1313. VmaAllocator VMA_NOT_NULL allocator,
  1314. VmaAllocatorInfo* VMA_NOT_NULL pAllocatorInfo);
  1315. /**
  1316. PhysicalDeviceProperties are fetched from physicalDevice by the allocator.
  1317. You can access it here, without fetching it again on your own.
  1318. */
  1319. VMA_CALL_PRE void VMA_CALL_POST vmaGetPhysicalDeviceProperties(
  1320. VmaAllocator VMA_NOT_NULL allocator,
  1321. const VkPhysicalDeviceProperties* VMA_NULLABLE* VMA_NOT_NULL ppPhysicalDeviceProperties);
  1322. /**
  1323. PhysicalDeviceMemoryProperties are fetched from physicalDevice by the allocator.
  1324. You can access it here, without fetching it again on your own.
  1325. */
  1326. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryProperties(
  1327. VmaAllocator VMA_NOT_NULL allocator,
  1328. const VkPhysicalDeviceMemoryProperties* VMA_NULLABLE* VMA_NOT_NULL ppPhysicalDeviceMemoryProperties);
  1329. /**
  1330. \brief Given Memory Type Index, returns Property Flags of this memory type.
  1331. This is just a convenience function. Same information can be obtained using
  1332. vmaGetMemoryProperties().
  1333. */
  1334. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties(
  1335. VmaAllocator VMA_NOT_NULL allocator,
  1336. uint32_t memoryTypeIndex,
  1337. VkMemoryPropertyFlags* VMA_NOT_NULL pFlags);
  1338. /** \brief Sets index of the current frame.
  1339. */
  1340. VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex(
  1341. VmaAllocator VMA_NOT_NULL allocator,
  1342. uint32_t frameIndex);
  1343. /** @} */
  1344. /**
  1345. \addtogroup group_stats
  1346. @{
  1347. */
  1348. /** \brief Retrieves statistics from current state of the Allocator.
  1349. This function is called "calculate" not "get" because it has to traverse all
  1350. internal data structures, so it may be quite slow. Use it for debugging purposes.
  1351. For faster but more brief statistics suitable to be called every frame or every allocation,
  1352. use vmaGetHeapBudgets().
  1353. Note that when using allocator from multiple threads, returned information may immediately
  1354. become outdated.
  1355. */
  1356. VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStatistics(
  1357. VmaAllocator VMA_NOT_NULL allocator,
  1358. VmaTotalStatistics* VMA_NOT_NULL pStats);
  1359. /** \brief Retrieves information about current memory usage and budget for all memory heaps.
  1360. \param allocator
  1361. \param[out] pBudgets Must point to array with number of elements at least equal to number of memory heaps in physical device used.
  1362. This function is called "get" not "calculate" because it is very fast, suitable to be called
  1363. every frame or every allocation. For more detailed statistics use vmaCalculateStatistics().
  1364. Note that when using allocator from multiple threads, returned information may immediately
  1365. become outdated.
  1366. */
  1367. VMA_CALL_PRE void VMA_CALL_POST vmaGetHeapBudgets(
  1368. VmaAllocator VMA_NOT_NULL allocator,
  1369. VmaBudget* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryHeapCount") pBudgets);
  1370. /** @} */
  1371. /**
  1372. \addtogroup group_alloc
  1373. @{
  1374. */
  1375. /**
  1376. \brief Helps to find memoryTypeIndex, given memoryTypeBits and VmaAllocationCreateInfo.
  1377. This algorithm tries to find a memory type that:
  1378. - Is allowed by memoryTypeBits.
  1379. - Contains all the flags from pAllocationCreateInfo->requiredFlags.
  1380. - Matches intended usage.
  1381. - Has as many flags from pAllocationCreateInfo->preferredFlags as possible.
  1382. \return Returns VK_ERROR_FEATURE_NOT_PRESENT if not found. Receiving such result
  1383. from this function or any other allocating function probably means that your
  1384. device doesn't support any memory type with requested features for the specific
  1385. type of resource you want to use it for. Please check parameters of your
  1386. resource, like image layout (OPTIMAL versus LINEAR) or mip level count.
  1387. */
  1388. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex(
  1389. VmaAllocator VMA_NOT_NULL allocator,
  1390. uint32_t memoryTypeBits,
  1391. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  1392. uint32_t* VMA_NOT_NULL pMemoryTypeIndex);
  1393. /**
  1394. \brief Helps to find memoryTypeIndex, given VkBufferCreateInfo and VmaAllocationCreateInfo.
  1395. It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex.
  1396. It internally creates a temporary, dummy buffer that never has memory bound.
  1397. */
  1398. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo(
  1399. VmaAllocator VMA_NOT_NULL allocator,
  1400. const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo,
  1401. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  1402. uint32_t* VMA_NOT_NULL pMemoryTypeIndex);
  1403. /**
  1404. \brief Helps to find memoryTypeIndex, given VkImageCreateInfo and VmaAllocationCreateInfo.
  1405. It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex.
  1406. It internally creates a temporary, dummy image that never has memory bound.
  1407. */
  1408. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo(
  1409. VmaAllocator VMA_NOT_NULL allocator,
  1410. const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo,
  1411. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  1412. uint32_t* VMA_NOT_NULL pMemoryTypeIndex);
  1413. /** \brief Allocates Vulkan device memory and creates #VmaPool object.
  1414. \param allocator Allocator object.
  1415. \param pCreateInfo Parameters of pool to create.
  1416. \param[out] pPool Handle to created pool.
  1417. */
  1418. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool(
  1419. VmaAllocator VMA_NOT_NULL allocator,
  1420. const VmaPoolCreateInfo* VMA_NOT_NULL pCreateInfo,
  1421. VmaPool VMA_NULLABLE* VMA_NOT_NULL pPool);
  1422. /** \brief Destroys #VmaPool object and frees Vulkan device memory.
  1423. */
  1424. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool(
  1425. VmaAllocator VMA_NOT_NULL allocator,
  1426. VmaPool VMA_NULLABLE pool);
  1427. /** @} */
  1428. /**
  1429. \addtogroup group_stats
  1430. @{
  1431. */
  1432. /** \brief Retrieves statistics of existing #VmaPool object.
  1433. \param allocator Allocator object.
  1434. \param pool Pool object.
  1435. \param[out] pPoolStats Statistics of specified pool.
  1436. */
  1437. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStatistics(
  1438. VmaAllocator VMA_NOT_NULL allocator,
  1439. VmaPool VMA_NOT_NULL pool,
  1440. VmaStatistics* VMA_NOT_NULL pPoolStats);
  1441. /** \brief Retrieves detailed statistics of existing #VmaPool object.
  1442. \param allocator Allocator object.
  1443. \param pool Pool object.
  1444. \param[out] pPoolStats Statistics of specified pool.
  1445. */
  1446. VMA_CALL_PRE void VMA_CALL_POST vmaCalculatePoolStatistics(
  1447. VmaAllocator VMA_NOT_NULL allocator,
  1448. VmaPool VMA_NOT_NULL pool,
  1449. VmaDetailedStatistics* VMA_NOT_NULL pPoolStats);
  1450. /** @} */
  1451. /**
  1452. \addtogroup group_alloc
  1453. @{
  1454. */
  1455. /** \brief Checks magic number in margins around all allocations in given memory pool in search for corruptions.
  1456. Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero,
  1457. `VMA_DEBUG_MARGIN` is defined to nonzero and the pool is created in memory type that is
  1458. `HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection).
  1459. Possible return values:
  1460. - `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for specified pool.
  1461. - `VK_SUCCESS` - corruption detection has been performed and succeeded.
  1462. - `VK_ERROR_UNKNOWN` - corruption detection has been performed and found memory corruptions around one of the allocations.
  1463. `VMA_ASSERT` is also fired in that case.
  1464. - Other value: Error returned by Vulkan, e.g. memory mapping failure.
  1465. */
  1466. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckPoolCorruption(
  1467. VmaAllocator VMA_NOT_NULL allocator,
  1468. VmaPool VMA_NOT_NULL pool);
  1469. /** \brief Retrieves name of a custom pool.
  1470. After the call `ppName` is either null or points to an internally-owned null-terminated string
  1471. containing name of the pool that was previously set. The pointer becomes invalid when the pool is
  1472. destroyed or its name is changed using vmaSetPoolName().
  1473. */
  1474. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName(
  1475. VmaAllocator VMA_NOT_NULL allocator,
  1476. VmaPool VMA_NOT_NULL pool,
  1477. const char* VMA_NULLABLE* VMA_NOT_NULL ppName);
  1478. /** \brief Sets name of a custom pool.
  1479. `pName` can be either null or pointer to a null-terminated string with new name for the pool.
  1480. Function makes internal copy of the string, so it can be changed or freed immediately after this call.
  1481. */
  1482. VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName(
  1483. VmaAllocator VMA_NOT_NULL allocator,
  1484. VmaPool VMA_NOT_NULL pool,
  1485. const char* VMA_NULLABLE pName);
  1486. /** \brief General purpose memory allocation.
  1487. \param allocator
  1488. \param pVkMemoryRequirements
  1489. \param pCreateInfo
  1490. \param[out] pAllocation Handle to allocated memory.
  1491. \param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
  1492. You should free the memory using vmaFreeMemory() or vmaFreeMemoryPages().
  1493. It is recommended to use vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage(),
  1494. vmaCreateBuffer(), vmaCreateImage() instead whenever possible.
  1495. */
  1496. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory(
  1497. VmaAllocator VMA_NOT_NULL allocator,
  1498. const VkMemoryRequirements* VMA_NOT_NULL pVkMemoryRequirements,
  1499. const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo,
  1500. VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation,
  1501. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  1502. /** \brief General purpose memory allocation for multiple allocation objects at once.
  1503. \param allocator Allocator object.
  1504. \param pVkMemoryRequirements Memory requirements for each allocation.
  1505. \param pCreateInfo Creation parameters for each allocation.
  1506. \param allocationCount Number of allocations to make.
  1507. \param[out] pAllocations Pointer to array that will be filled with handles to created allocations.
  1508. \param[out] pAllocationInfo Optional. Pointer to array that will be filled with parameters of created allocations.
  1509. You should free the memory using vmaFreeMemory() or vmaFreeMemoryPages().
  1510. Word "pages" is just a suggestion to use this function to allocate pieces of memory needed for sparse binding.
  1511. It is just a general purpose allocation function able to make multiple allocations at once.
  1512. It may be internally optimized to be more efficient than calling vmaAllocateMemory() `allocationCount` times.
  1513. All allocations are made using same parameters. All of them are created out of the same memory pool and type.
  1514. If any allocation fails, all allocations already made within this function call are also freed, so that when
  1515. returned result is not `VK_SUCCESS`, `pAllocation` array is always entirely filled with `VK_NULL_HANDLE`.
  1516. */
  1517. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages(
  1518. VmaAllocator VMA_NOT_NULL allocator,
  1519. const VkMemoryRequirements* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pVkMemoryRequirements,
  1520. const VmaAllocationCreateInfo* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pCreateInfo,
  1521. size_t allocationCount,
  1522. VmaAllocation VMA_NULLABLE* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations,
  1523. VmaAllocationInfo* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) pAllocationInfo);
  1524. /** \brief Allocates memory suitable for given `VkBuffer`.
  1525. \param allocator
  1526. \param buffer
  1527. \param pCreateInfo
  1528. \param[out] pAllocation Handle to allocated memory.
  1529. \param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
  1530. It only creates #VmaAllocation. To bind the memory to the buffer, use vmaBindBufferMemory().
  1531. This is a special-purpose function. In most cases you should use vmaCreateBuffer().
  1532. You must free the allocation using vmaFreeMemory() when no longer needed.
  1533. */
  1534. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer(
  1535. VmaAllocator VMA_NOT_NULL allocator,
  1536. VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer,
  1537. const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo,
  1538. VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation,
  1539. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  1540. /** \brief Allocates memory suitable for given `VkImage`.
  1541. \param allocator
  1542. \param image
  1543. \param pCreateInfo
  1544. \param[out] pAllocation Handle to allocated memory.
  1545. \param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
  1546. It only creates #VmaAllocation. To bind the memory to the buffer, use vmaBindImageMemory().
  1547. This is a special-purpose function. In most cases you should use vmaCreateImage().
  1548. You must free the allocation using vmaFreeMemory() when no longer needed.
  1549. */
  1550. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage(
  1551. VmaAllocator VMA_NOT_NULL allocator,
  1552. VkImage VMA_NOT_NULL_NON_DISPATCHABLE image,
  1553. const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo,
  1554. VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation,
  1555. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  1556. /** \brief Frees memory previously allocated using vmaAllocateMemory(), vmaAllocateMemoryForBuffer(), or vmaAllocateMemoryForImage().
  1557. Passing `VK_NULL_HANDLE` as `allocation` is valid. Such function call is just skipped.
  1558. */
  1559. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory(
  1560. VmaAllocator VMA_NOT_NULL allocator,
  1561. const VmaAllocation VMA_NULLABLE allocation);
  1562. /** \brief Frees memory and destroys multiple allocations.
  1563. Word "pages" is just a suggestion to use this function to free pieces of memory used for sparse binding.
  1564. It is just a general purpose function to free memory and destroy allocations made using e.g. vmaAllocateMemory(),
  1565. vmaAllocateMemoryPages() and other functions.
  1566. It may be internally optimized to be more efficient than calling vmaFreeMemory() `allocationCount` times.
  1567. Allocations in `pAllocations` array can come from any memory pools and types.
  1568. Passing `VK_NULL_HANDLE` as elements of `pAllocations` array is valid. Such entries are just skipped.
  1569. */
  1570. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages(
  1571. VmaAllocator VMA_NOT_NULL allocator,
  1572. size_t allocationCount,
  1573. const VmaAllocation VMA_NULLABLE* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations);
  1574. /** \brief Returns current information about specified allocation.
  1575. Current paramteres of given allocation are returned in `pAllocationInfo`.
  1576. Although this function doesn't lock any mutex, so it should be quite efficient,
  1577. you should avoid calling it too often.
  1578. You can retrieve same VmaAllocationInfo structure while creating your resource, from function
  1579. vmaCreateBuffer(), vmaCreateImage(). You can remember it if you are sure parameters don't change
  1580. (e.g. due to defragmentation).
  1581. */
  1582. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo(
  1583. VmaAllocator VMA_NOT_NULL allocator,
  1584. VmaAllocation VMA_NOT_NULL allocation,
  1585. VmaAllocationInfo* VMA_NOT_NULL pAllocationInfo);
  1586. /** \brief Sets pUserData in given allocation to new value.
  1587. The value of pointer `pUserData` is copied to allocation's `pUserData`.
  1588. It is opaque, so you can use it however you want - e.g.
  1589. as a pointer, ordinal number or some handle to you own data.
  1590. */
  1591. VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData(
  1592. VmaAllocator VMA_NOT_NULL allocator,
  1593. VmaAllocation VMA_NOT_NULL allocation,
  1594. void* VMA_NULLABLE pUserData);
  1595. /** \brief Sets pName in given allocation to new value.
  1596. `pName` must be either null, or pointer to a null-terminated string. The function
  1597. makes local copy of the string and sets it as allocation's `pName`. String
  1598. passed as pName doesn't need to be valid for whole lifetime of the allocation -
  1599. you can free it after this call. String previously pointed by allocation's
  1600. `pName` is freed from memory.
  1601. */
  1602. VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationName(
  1603. VmaAllocator VMA_NOT_NULL allocator,
  1604. VmaAllocation VMA_NOT_NULL allocation,
  1605. const char* VMA_NULLABLE pName);
  1606. /**
  1607. \brief Given an allocation, returns Property Flags of its memory type.
  1608. This is just a convenience function. Same information can be obtained using
  1609. vmaGetAllocationInfo() + vmaGetMemoryProperties().
  1610. */
  1611. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationMemoryProperties(
  1612. VmaAllocator VMA_NOT_NULL allocator,
  1613. VmaAllocation VMA_NOT_NULL allocation,
  1614. VkMemoryPropertyFlags* VMA_NOT_NULL pFlags);
  1615. /** \brief Maps memory represented by given allocation and returns pointer to it.
  1616. Maps memory represented by given allocation to make it accessible to CPU code.
  1617. When succeeded, `*ppData` contains pointer to first byte of this memory.
  1618. \warning
  1619. If the allocation is part of a bigger `VkDeviceMemory` block, returned pointer is
  1620. correctly offsetted to the beginning of region assigned to this particular allocation.
  1621. Unlike the result of `vkMapMemory`, it points to the allocation, not to the beginning of the whole block.
  1622. You should not add VmaAllocationInfo::offset to it!
  1623. Mapping is internally reference-counted and synchronized, so despite raw Vulkan
  1624. function `vkMapMemory()` cannot be used to map same block of `VkDeviceMemory`
  1625. multiple times simultaneously, it is safe to call this function on allocations
  1626. assigned to the same memory block. Actual Vulkan memory will be mapped on first
  1627. mapping and unmapped on last unmapping.
  1628. If the function succeeded, you must call vmaUnmapMemory() to unmap the
  1629. allocation when mapping is no longer needed or before freeing the allocation, at
  1630. the latest.
  1631. It also safe to call this function multiple times on the same allocation. You
  1632. must call vmaUnmapMemory() same number of times as you called vmaMapMemory().
  1633. It is also safe to call this function on allocation created with
  1634. #VMA_ALLOCATION_CREATE_MAPPED_BIT flag. Its memory stays mapped all the time.
  1635. You must still call vmaUnmapMemory() same number of times as you called
  1636. vmaMapMemory(). You must not call vmaUnmapMemory() additional time to free the
  1637. "0-th" mapping made automatically due to #VMA_ALLOCATION_CREATE_MAPPED_BIT flag.
  1638. This function fails when used on allocation made in memory type that is not
  1639. `HOST_VISIBLE`.
  1640. This function doesn't automatically flush or invalidate caches.
  1641. If the allocation is made from a memory types that is not `HOST_COHERENT`,
  1642. you also need to use vmaInvalidateAllocation() / vmaFlushAllocation(), as required by Vulkan specification.
  1643. */
  1644. VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory(
  1645. VmaAllocator VMA_NOT_NULL allocator,
  1646. VmaAllocation VMA_NOT_NULL allocation,
  1647. void* VMA_NULLABLE* VMA_NOT_NULL ppData);
  1648. /** \brief Unmaps memory represented by given allocation, mapped previously using vmaMapMemory().
  1649. For details, see description of vmaMapMemory().
  1650. This function doesn't automatically flush or invalidate caches.
  1651. If the allocation is made from a memory types that is not `HOST_COHERENT`,
  1652. you also need to use vmaInvalidateAllocation() / vmaFlushAllocation(), as required by Vulkan specification.
  1653. */
  1654. VMA_CALL_PRE void VMA_CALL_POST vmaUnmapMemory(
  1655. VmaAllocator VMA_NOT_NULL allocator,
  1656. VmaAllocation VMA_NOT_NULL allocation);
  1657. /** \brief Flushes memory of given allocation.
  1658. Calls `vkFlushMappedMemoryRanges()` for memory associated with given range of given allocation.
  1659. It needs to be called after writing to a mapped memory for memory types that are not `HOST_COHERENT`.
  1660. Unmap operation doesn't do that automatically.
  1661. - `offset` must be relative to the beginning of allocation.
  1662. - `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation.
  1663. - `offset` and `size` don't have to be aligned.
  1664. They are internally rounded down/up to multiply of `nonCoherentAtomSize`.
  1665. - If `size` is 0, this call is ignored.
  1666. - If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`,
  1667. this call is ignored.
  1668. Warning! `offset` and `size` are relative to the contents of given `allocation`.
  1669. If you mean whole allocation, you can pass 0 and `VK_WHOLE_SIZE`, respectively.
  1670. Do not pass allocation's offset as `offset`!!!
  1671. This function returns the `VkResult` from `vkFlushMappedMemoryRanges` if it is
  1672. called, otherwise `VK_SUCCESS`.
  1673. */
  1674. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocation(
  1675. VmaAllocator VMA_NOT_NULL allocator,
  1676. VmaAllocation VMA_NOT_NULL allocation,
  1677. VkDeviceSize offset,
  1678. VkDeviceSize size);
  1679. /** \brief Invalidates memory of given allocation.
  1680. Calls `vkInvalidateMappedMemoryRanges()` for memory associated with given range of given allocation.
  1681. It needs to be called before reading from a mapped memory for memory types that are not `HOST_COHERENT`.
  1682. Map operation doesn't do that automatically.
  1683. - `offset` must be relative to the beginning of allocation.
  1684. - `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation.
  1685. - `offset` and `size` don't have to be aligned.
  1686. They are internally rounded down/up to multiply of `nonCoherentAtomSize`.
  1687. - If `size` is 0, this call is ignored.
  1688. - If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`,
  1689. this call is ignored.
  1690. Warning! `offset` and `size` are relative to the contents of given `allocation`.
  1691. If you mean whole allocation, you can pass 0 and `VK_WHOLE_SIZE`, respectively.
  1692. Do not pass allocation's offset as `offset`!!!
  1693. This function returns the `VkResult` from `vkInvalidateMappedMemoryRanges` if
  1694. it is called, otherwise `VK_SUCCESS`.
  1695. */
  1696. VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocation(
  1697. VmaAllocator VMA_NOT_NULL allocator,
  1698. VmaAllocation VMA_NOT_NULL allocation,
  1699. VkDeviceSize offset,
  1700. VkDeviceSize size);
  1701. /** \brief Flushes memory of given set of allocations.
  1702. Calls `vkFlushMappedMemoryRanges()` for memory associated with given ranges of given allocations.
  1703. For more information, see documentation of vmaFlushAllocation().
  1704. \param allocator
  1705. \param allocationCount
  1706. \param allocations
  1707. \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.
  1708. \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.
  1709. This function returns the `VkResult` from `vkFlushMappedMemoryRanges` if it is
  1710. called, otherwise `VK_SUCCESS`.
  1711. */
  1712. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocations(
  1713. VmaAllocator VMA_NOT_NULL allocator,
  1714. uint32_t allocationCount,
  1715. const VmaAllocation VMA_NOT_NULL* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) allocations,
  1716. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) offsets,
  1717. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) sizes);
  1718. /** \brief Invalidates memory of given set of allocations.
  1719. Calls `vkInvalidateMappedMemoryRanges()` for memory associated with given ranges of given allocations.
  1720. For more information, see documentation of vmaInvalidateAllocation().
  1721. \param allocator
  1722. \param allocationCount
  1723. \param allocations
  1724. \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.
  1725. \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.
  1726. This function returns the `VkResult` from `vkInvalidateMappedMemoryRanges` if it is
  1727. called, otherwise `VK_SUCCESS`.
  1728. */
  1729. VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocations(
  1730. VmaAllocator VMA_NOT_NULL allocator,
  1731. uint32_t allocationCount,
  1732. const VmaAllocation VMA_NOT_NULL* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) allocations,
  1733. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) offsets,
  1734. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) sizes);
  1735. /** \brief Checks magic number in margins around all allocations in given memory types (in both default and custom pools) in search for corruptions.
  1736. \param allocator
  1737. \param memoryTypeBits Bit mask, where each bit set means that a memory type with that index should be checked.
  1738. Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero,
  1739. `VMA_DEBUG_MARGIN` is defined to nonzero and only for memory types that are
  1740. `HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection).
  1741. Possible return values:
  1742. - `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for any of specified memory types.
  1743. - `VK_SUCCESS` - corruption detection has been performed and succeeded.
  1744. - `VK_ERROR_UNKNOWN` - corruption detection has been performed and found memory corruptions around one of the allocations.
  1745. `VMA_ASSERT` is also fired in that case.
  1746. - Other value: Error returned by Vulkan, e.g. memory mapping failure.
  1747. */
  1748. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckCorruption(
  1749. VmaAllocator VMA_NOT_NULL allocator,
  1750. uint32_t memoryTypeBits);
  1751. /** \brief Begins defragmentation process.
  1752. \param allocator Allocator object.
  1753. \param pInfo Structure filled with parameters of defragmentation.
  1754. \param[out] pContext Context object that must be passed to vmaEndDefragmentation() to finish defragmentation.
  1755. \returns
  1756. - `VK_SUCCESS` if defragmentation can begin.
  1757. - `VK_ERROR_FEATURE_NOT_PRESENT` if defragmentation is not supported.
  1758. For more information about defragmentation, see documentation chapter:
  1759. [Defragmentation](@ref defragmentation).
  1760. */
  1761. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentation(
  1762. VmaAllocator VMA_NOT_NULL allocator,
  1763. const VmaDefragmentationInfo* VMA_NOT_NULL pInfo,
  1764. VmaDefragmentationContext VMA_NULLABLE* VMA_NOT_NULL pContext);
  1765. /** \brief Ends defragmentation process.
  1766. \param allocator Allocator object.
  1767. \param context Context object that has been created by vmaBeginDefragmentation().
  1768. \param[out] pStats Optional stats for the defragmentation. Can be null.
  1769. Use this function to finish defragmentation started by vmaBeginDefragmentation().
  1770. */
  1771. VMA_CALL_PRE void VMA_CALL_POST vmaEndDefragmentation(
  1772. VmaAllocator VMA_NOT_NULL allocator,
  1773. VmaDefragmentationContext VMA_NOT_NULL context,
  1774. VmaDefragmentationStats* VMA_NULLABLE pStats);
  1775. /** \brief Starts single defragmentation pass.
  1776. \param allocator Allocator object.
  1777. \param context Context object that has been created by vmaBeginDefragmentation().
  1778. \param[out] pPassInfo Computed informations for current pass.
  1779. \returns
  1780. - `VK_SUCCESS` if no more moves are possible. Then you can omit call to vmaEndDefragmentationPass() and simply end whole defragmentation.
  1781. - `VK_INCOMPLETE` if there are pending moves returned in `pPassInfo`. You need to perform them, call vmaEndDefragmentationPass(),
  1782. and then preferably try another pass with vmaBeginDefragmentationPass().
  1783. */
  1784. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentationPass(
  1785. VmaAllocator VMA_NOT_NULL allocator,
  1786. VmaDefragmentationContext VMA_NOT_NULL context,
  1787. VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo);
  1788. /** \brief Ends single defragmentation pass.
  1789. \param allocator Allocator object.
  1790. \param context Context object that has been created by vmaBeginDefragmentation().
  1791. \param pPassInfo Computed informations for current pass filled by vmaBeginDefragmentationPass() and possibly modified by you.
  1792. Returns `VK_SUCCESS` if no more moves are possible or `VK_INCOMPLETE` if more defragmentations are possible.
  1793. Ends incremental defragmentation pass and commits all defragmentation moves from `pPassInfo`.
  1794. After this call:
  1795. - Allocations at `pPassInfo[i].srcAllocation` that had `pPassInfo[i].operation ==` #VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY
  1796. (which is the default) will be pointing to the new destination place.
  1797. - Allocation at `pPassInfo[i].srcAllocation` that had `pPassInfo[i].operation ==` #VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY
  1798. will be freed.
  1799. If no more moves are possible you can end whole defragmentation.
  1800. */
  1801. VMA_CALL_PRE VkResult VMA_CALL_POST vmaEndDefragmentationPass(
  1802. VmaAllocator VMA_NOT_NULL allocator,
  1803. VmaDefragmentationContext VMA_NOT_NULL context,
  1804. VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo);
  1805. /** \brief Binds buffer to allocation.
  1806. Binds specified buffer to region of memory represented by specified allocation.
  1807. Gets `VkDeviceMemory` handle and offset from the allocation.
  1808. If you want to create a buffer, allocate memory for it and bind them together separately,
  1809. you should use this function for binding instead of standard `vkBindBufferMemory()`,
  1810. because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple
  1811. allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously
  1812. (which is illegal in Vulkan).
  1813. It is recommended to use function vmaCreateBuffer() instead of this one.
  1814. */
  1815. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory(
  1816. VmaAllocator VMA_NOT_NULL allocator,
  1817. VmaAllocation VMA_NOT_NULL allocation,
  1818. VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer);
  1819. /** \brief Binds buffer to allocation with additional parameters.
  1820. \param allocator
  1821. \param allocation
  1822. \param allocationLocalOffset Additional offset to be added while binding, relative to the beginning of the `allocation`. Normally it should be 0.
  1823. \param buffer
  1824. \param pNext A chain of structures to be attached to `VkBindBufferMemoryInfoKHR` structure used internally. Normally it should be null.
  1825. This function is similar to vmaBindBufferMemory(), but it provides additional parameters.
  1826. If `pNext` is not null, #VmaAllocator object must have been created with #VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT flag
  1827. or with VmaAllocatorCreateInfo::vulkanApiVersion `>= VK_API_VERSION_1_1`. Otherwise the call fails.
  1828. */
  1829. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2(
  1830. VmaAllocator VMA_NOT_NULL allocator,
  1831. VmaAllocation VMA_NOT_NULL allocation,
  1832. VkDeviceSize allocationLocalOffset,
  1833. VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer,
  1834. const void* VMA_NULLABLE pNext);
  1835. /** \brief Binds image to allocation.
  1836. Binds specified image to region of memory represented by specified allocation.
  1837. Gets `VkDeviceMemory` handle and offset from the allocation.
  1838. If you want to create an image, allocate memory for it and bind them together separately,
  1839. you should use this function for binding instead of standard `vkBindImageMemory()`,
  1840. because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple
  1841. allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously
  1842. (which is illegal in Vulkan).
  1843. It is recommended to use function vmaCreateImage() instead of this one.
  1844. */
  1845. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory(
  1846. VmaAllocator VMA_NOT_NULL allocator,
  1847. VmaAllocation VMA_NOT_NULL allocation,
  1848. VkImage VMA_NOT_NULL_NON_DISPATCHABLE image);
  1849. /** \brief Binds image to allocation with additional parameters.
  1850. \param allocator
  1851. \param allocation
  1852. \param allocationLocalOffset Additional offset to be added while binding, relative to the beginning of the `allocation`. Normally it should be 0.
  1853. \param image
  1854. \param pNext A chain of structures to be attached to `VkBindImageMemoryInfoKHR` structure used internally. Normally it should be null.
  1855. This function is similar to vmaBindImageMemory(), but it provides additional parameters.
  1856. If `pNext` is not null, #VmaAllocator object must have been created with #VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT flag
  1857. or with VmaAllocatorCreateInfo::vulkanApiVersion `>= VK_API_VERSION_1_1`. Otherwise the call fails.
  1858. */
  1859. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2(
  1860. VmaAllocator VMA_NOT_NULL allocator,
  1861. VmaAllocation VMA_NOT_NULL allocation,
  1862. VkDeviceSize allocationLocalOffset,
  1863. VkImage VMA_NOT_NULL_NON_DISPATCHABLE image,
  1864. const void* VMA_NULLABLE pNext);
  1865. /** \brief Creates a new `VkBuffer`, allocates and binds memory for it.
  1866. \param allocator
  1867. \param pBufferCreateInfo
  1868. \param pAllocationCreateInfo
  1869. \param[out] pBuffer Buffer that was created.
  1870. \param[out] pAllocation Allocation that was created.
  1871. \param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
  1872. This function automatically:
  1873. -# Creates buffer.
  1874. -# Allocates appropriate memory for it.
  1875. -# Binds the buffer with the memory.
  1876. If any of these operations fail, buffer and allocation are not created,
  1877. returned value is negative error code, `*pBuffer` and `*pAllocation` are null.
  1878. If the function succeeded, you must destroy both buffer and allocation when you
  1879. no longer need them using either convenience function vmaDestroyBuffer() or
  1880. separately, using `vkDestroyBuffer()` and vmaFreeMemory().
  1881. If #VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag was used,
  1882. VK_KHR_dedicated_allocation extension is used internally to query driver whether
  1883. it requires or prefers the new buffer to have dedicated allocation. If yes,
  1884. and if dedicated allocation is possible
  1885. (#VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT is not used), it creates dedicated
  1886. allocation for this buffer, just like when using
  1887. #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  1888. \note This function creates a new `VkBuffer`. Sub-allocation of parts of one large buffer,
  1889. although recommended as a good practice, is out of scope of this library and could be implemented
  1890. by the user as a higher-level logic on top of VMA.
  1891. */
  1892. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer(
  1893. VmaAllocator VMA_NOT_NULL allocator,
  1894. const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo,
  1895. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  1896. VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer,
  1897. VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation,
  1898. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  1899. /** \brief Creates a buffer with additional minimum alignment.
  1900. Similar to vmaCreateBuffer() but provides additional parameter `minAlignment` which allows to specify custom,
  1901. minimum alignment to be used when placing the buffer inside a larger memory block, which may be needed e.g.
  1902. for interop with OpenGL.
  1903. */
  1904. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBufferWithAlignment(
  1905. VmaAllocator VMA_NOT_NULL allocator,
  1906. const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo,
  1907. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  1908. VkDeviceSize minAlignment,
  1909. VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer,
  1910. VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation,
  1911. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  1912. /** \brief Creates a new `VkBuffer`, binds already created memory for it.
  1913. \param allocator
  1914. \param allocation Allocation that provides memory to be used for binding new buffer to it.
  1915. \param pBufferCreateInfo
  1916. \param[out] pBuffer Buffer that was created.
  1917. This function automatically:
  1918. -# Creates buffer.
  1919. -# Binds the buffer with the supplied memory.
  1920. If any of these operations fail, buffer is not created,
  1921. returned value is negative error code and `*pBuffer` is null.
  1922. If the function succeeded, you must destroy the buffer when you
  1923. no longer need it using `vkDestroyBuffer()`. If you want to also destroy the corresponding
  1924. allocation you can use convenience function vmaDestroyBuffer().
  1925. */
  1926. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingBuffer(
  1927. VmaAllocator VMA_NOT_NULL allocator,
  1928. VmaAllocation VMA_NOT_NULL allocation,
  1929. const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo,
  1930. VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer);
  1931. /** \brief Destroys Vulkan buffer and frees allocated memory.
  1932. This is just a convenience function equivalent to:
  1933. \code
  1934. vkDestroyBuffer(device, buffer, allocationCallbacks);
  1935. vmaFreeMemory(allocator, allocation);
  1936. \endcode
  1937. It it safe to pass null as buffer and/or allocation.
  1938. */
  1939. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer(
  1940. VmaAllocator VMA_NOT_NULL allocator,
  1941. VkBuffer VMA_NULLABLE_NON_DISPATCHABLE buffer,
  1942. VmaAllocation VMA_NULLABLE allocation);
  1943. /// Function similar to vmaCreateBuffer().
  1944. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage(
  1945. VmaAllocator VMA_NOT_NULL allocator,
  1946. const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo,
  1947. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  1948. VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage,
  1949. VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation,
  1950. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  1951. /// Function similar to vmaCreateAliasingBuffer().
  1952. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingImage(
  1953. VmaAllocator VMA_NOT_NULL allocator,
  1954. VmaAllocation VMA_NOT_NULL allocation,
  1955. const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo,
  1956. VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage);
  1957. /** \brief Destroys Vulkan image and frees allocated memory.
  1958. This is just a convenience function equivalent to:
  1959. \code
  1960. vkDestroyImage(device, image, allocationCallbacks);
  1961. vmaFreeMemory(allocator, allocation);
  1962. \endcode
  1963. It it safe to pass null as image and/or allocation.
  1964. */
  1965. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyImage(
  1966. VmaAllocator VMA_NOT_NULL allocator,
  1967. VkImage VMA_NULLABLE_NON_DISPATCHABLE image,
  1968. VmaAllocation VMA_NULLABLE allocation);
  1969. /** @} */
  1970. /**
  1971. \addtogroup group_virtual
  1972. @{
  1973. */
  1974. /** \brief Creates new #VmaVirtualBlock object.
  1975. \param pCreateInfo Parameters for creation.
  1976. \param[out] pVirtualBlock Returned virtual block object or `VMA_NULL` if creation failed.
  1977. */
  1978. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateVirtualBlock(
  1979. const VmaVirtualBlockCreateInfo* VMA_NOT_NULL pCreateInfo,
  1980. VmaVirtualBlock VMA_NULLABLE* VMA_NOT_NULL pVirtualBlock);
  1981. /** \brief Destroys #VmaVirtualBlock object.
  1982. Please note that you should consciously handle virtual allocations that could remain unfreed in the block.
  1983. You should either free them individually using vmaVirtualFree() or call vmaClearVirtualBlock()
  1984. if you are sure this is what you want. If you do neither, an assert is called.
  1985. If you keep pointers to some additional metadata associated with your virtual allocations in their `pUserData`,
  1986. don't forget to free them.
  1987. */
  1988. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyVirtualBlock(
  1989. VmaVirtualBlock VMA_NULLABLE virtualBlock);
  1990. /** \brief Returns true of the #VmaVirtualBlock is empty - contains 0 virtual allocations and has all its space available for new allocations.
  1991. */
  1992. VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaIsVirtualBlockEmpty(
  1993. VmaVirtualBlock VMA_NOT_NULL virtualBlock);
  1994. /** \brief Returns information about a specific virtual allocation within a virtual block, like its size and `pUserData` pointer.
  1995. */
  1996. VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualAllocationInfo(
  1997. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  1998. VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation, VmaVirtualAllocationInfo* VMA_NOT_NULL pVirtualAllocInfo);
  1999. /** \brief Allocates new virtual allocation inside given #VmaVirtualBlock.
  2000. If the allocation fails due to not enough free space available, `VK_ERROR_OUT_OF_DEVICE_MEMORY` is returned
  2001. (despite the function doesn't ever allocate actual GPU memory).
  2002. `pAllocation` is then set to `VK_NULL_HANDLE` and `pOffset`, if not null, it set to `UINT64_MAX`.
  2003. \param virtualBlock Virtual block
  2004. \param pCreateInfo Parameters for the allocation
  2005. \param[out] pAllocation Returned handle of the new allocation
  2006. \param[out] pOffset Returned offset of the new allocation. Optional, can be null.
  2007. */
  2008. VMA_CALL_PRE VkResult VMA_CALL_POST vmaVirtualAllocate(
  2009. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2010. const VmaVirtualAllocationCreateInfo* VMA_NOT_NULL pCreateInfo,
  2011. VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pAllocation,
  2012. VkDeviceSize* VMA_NULLABLE pOffset);
  2013. /** \brief Frees virtual allocation inside given #VmaVirtualBlock.
  2014. It is correct to call this function with `allocation == VK_NULL_HANDLE` - it does nothing.
  2015. */
  2016. VMA_CALL_PRE void VMA_CALL_POST vmaVirtualFree(
  2017. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2018. VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE allocation);
  2019. /** \brief Frees all virtual allocations inside given #VmaVirtualBlock.
  2020. You must either call this function or free each virtual allocation individually with vmaVirtualFree()
  2021. before destroying a virtual block. Otherwise, an assert is called.
  2022. If you keep pointer to some additional metadata associated with your virtual allocation in its `pUserData`,
  2023. don't forget to free it as well.
  2024. */
  2025. VMA_CALL_PRE void VMA_CALL_POST vmaClearVirtualBlock(
  2026. VmaVirtualBlock VMA_NOT_NULL virtualBlock);
  2027. /** \brief Changes custom pointer associated with given virtual allocation.
  2028. */
  2029. VMA_CALL_PRE void VMA_CALL_POST vmaSetVirtualAllocationUserData(
  2030. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2031. VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation,
  2032. void* VMA_NULLABLE pUserData);
  2033. /** \brief Calculates and returns statistics about virtual allocations and memory usage in given #VmaVirtualBlock.
  2034. This function is fast to call. For more detailed statistics, see vmaCalculateVirtualBlockStatistics().
  2035. */
  2036. VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualBlockStatistics(
  2037. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2038. VmaStatistics* VMA_NOT_NULL pStats);
  2039. /** \brief Calculates and returns detailed statistics about virtual allocations and memory usage in given #VmaVirtualBlock.
  2040. This function is slow to call. Use for debugging purposes.
  2041. For less detailed statistics, see vmaGetVirtualBlockStatistics().
  2042. */
  2043. VMA_CALL_PRE void VMA_CALL_POST vmaCalculateVirtualBlockStatistics(
  2044. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2045. VmaDetailedStatistics* VMA_NOT_NULL pStats);
  2046. /** @} */
  2047. #if VMA_STATS_STRING_ENABLED
  2048. /**
  2049. \addtogroup group_stats
  2050. @{
  2051. */
  2052. /** \brief Builds and returns a null-terminated string in JSON format with information about given #VmaVirtualBlock.
  2053. \param virtualBlock Virtual block.
  2054. \param[out] ppStatsString Returned string.
  2055. \param detailedMap Pass `VK_FALSE` to only obtain statistics as returned by vmaCalculateVirtualBlockStatistics(). Pass `VK_TRUE` to also obtain full list of allocations and free spaces.
  2056. Returned string must be freed using vmaFreeVirtualBlockStatsString().
  2057. */
  2058. VMA_CALL_PRE void VMA_CALL_POST vmaBuildVirtualBlockStatsString(
  2059. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2060. char* VMA_NULLABLE* VMA_NOT_NULL ppStatsString,
  2061. VkBool32 detailedMap);
  2062. /// Frees a string returned by vmaBuildVirtualBlockStatsString().
  2063. VMA_CALL_PRE void VMA_CALL_POST vmaFreeVirtualBlockStatsString(
  2064. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2065. char* VMA_NULLABLE pStatsString);
  2066. /** \brief Builds and returns statistics as a null-terminated string in JSON format.
  2067. \param allocator
  2068. \param[out] ppStatsString Must be freed using vmaFreeStatsString() function.
  2069. \param detailedMap
  2070. */
  2071. VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString(
  2072. VmaAllocator VMA_NOT_NULL allocator,
  2073. char* VMA_NULLABLE* VMA_NOT_NULL ppStatsString,
  2074. VkBool32 detailedMap);
  2075. VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString(
  2076. VmaAllocator VMA_NOT_NULL allocator,
  2077. char* VMA_NULLABLE pStatsString);
  2078. /** @} */
  2079. #endif // VMA_STATS_STRING_ENABLED
  2080. #endif // _VMA_FUNCTION_HEADERS
  2081. #ifdef __cplusplus
  2082. }
  2083. #endif
  2084. #endif // AMD_VULKAN_MEMORY_ALLOCATOR_H
  2085. ////////////////////////////////////////////////////////////////////////////////
  2086. ////////////////////////////////////////////////////////////////////////////////
  2087. //
  2088. // IMPLEMENTATION
  2089. //
  2090. ////////////////////////////////////////////////////////////////////////////////
  2091. ////////////////////////////////////////////////////////////////////////////////
  2092. // For Visual Studio IntelliSense.
  2093. #if defined(__cplusplus) && defined(__INTELLISENSE__)
  2094. #define VMA_IMPLEMENTATION
  2095. #endif
  2096. #ifdef VMA_IMPLEMENTATION
  2097. #undef VMA_IMPLEMENTATION
  2098. #include <cstdint>
  2099. #include <cstdlib>
  2100. #include <cstring>
  2101. #include <utility>
  2102. #include <type_traits>
  2103. #ifdef _MSC_VER
  2104. #include <intrin.h> // For functions like __popcnt, _BitScanForward etc.
  2105. #endif
  2106. #if __cplusplus >= 202002L || _MSVC_LANG >= 202002L // C++20
  2107. #include <bit> // For std::popcount
  2108. #endif
  2109. /*******************************************************************************
  2110. CONFIGURATION SECTION
  2111. Define some of these macros before each #include of this header or change them
  2112. here if you need other then default behavior depending on your environment.
  2113. */
  2114. #ifndef _VMA_CONFIGURATION
  2115. /*
  2116. Define this macro to 1 to make the library fetch pointers to Vulkan functions
  2117. internally, like:
  2118. vulkanFunctions.vkAllocateMemory = &vkAllocateMemory;
  2119. */
  2120. #if !defined(VMA_STATIC_VULKAN_FUNCTIONS) && !defined(VK_NO_PROTOTYPES)
  2121. #define VMA_STATIC_VULKAN_FUNCTIONS 1
  2122. #endif
  2123. /*
  2124. Define this macro to 1 to make the library fetch pointers to Vulkan functions
  2125. internally, like:
  2126. vulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkGetDeviceProcAddr(device, "vkAllocateMemory");
  2127. To use this feature in new versions of VMA you now have to pass
  2128. VmaVulkanFunctions::vkGetInstanceProcAddr and vkGetDeviceProcAddr as
  2129. VmaAllocatorCreateInfo::pVulkanFunctions. Other members can be null.
  2130. */
  2131. #if !defined(VMA_DYNAMIC_VULKAN_FUNCTIONS)
  2132. #define VMA_DYNAMIC_VULKAN_FUNCTIONS 1
  2133. #endif
  2134. #ifndef VMA_USE_STL_SHARED_MUTEX
  2135. // Compiler conforms to C++17.
  2136. #if __cplusplus >= 201703L
  2137. #define VMA_USE_STL_SHARED_MUTEX 1
  2138. // Visual studio defines __cplusplus properly only when passed additional parameter: /Zc:__cplusplus
  2139. // Otherwise it is always 199711L, despite shared_mutex works since Visual Studio 2015 Update 2.
  2140. #elif defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 190023918 && __cplusplus == 199711L && _MSVC_LANG >= 201703L
  2141. #define VMA_USE_STL_SHARED_MUTEX 1
  2142. #else
  2143. #define VMA_USE_STL_SHARED_MUTEX 0
  2144. #endif
  2145. #endif
  2146. /*
  2147. Define this macro to include custom header files without having to edit this file directly, e.g.:
  2148. // Inside of "my_vma_configuration_user_includes.h":
  2149. #include "my_custom_assert.h" // for MY_CUSTOM_ASSERT
  2150. #include "my_custom_min.h" // for my_custom_min
  2151. #include <algorithm>
  2152. #include <mutex>
  2153. // Inside a different file, which includes "vk_mem_alloc.h":
  2154. #define VMA_CONFIGURATION_USER_INCLUDES_H "my_vma_configuration_user_includes.h"
  2155. #define VMA_ASSERT(expr) MY_CUSTOM_ASSERT(expr)
  2156. #define VMA_MIN(v1, v2) (my_custom_min(v1, v2))
  2157. #include "vk_mem_alloc.h"
  2158. ...
  2159. The following headers are used in this CONFIGURATION section only, so feel free to
  2160. remove them if not needed.
  2161. */
  2162. #if !defined(VMA_CONFIGURATION_USER_INCLUDES_H)
  2163. #include <cassert> // for assert
  2164. #include <algorithm> // for min, max
  2165. #include <mutex>
  2166. #else
  2167. #include VMA_CONFIGURATION_USER_INCLUDES_H
  2168. #endif
  2169. #ifndef VMA_NULL
  2170. // Value used as null pointer. Define it to e.g.: nullptr, NULL, 0, (void*)0.
  2171. #define VMA_NULL nullptr
  2172. #endif
  2173. #if defined(__ANDROID_API__) && (__ANDROID_API__ < 16)
  2174. #include <cstdlib>
  2175. static void* vma_aligned_alloc(size_t alignment, size_t size)
  2176. {
  2177. // alignment must be >= sizeof(void*)
  2178. if(alignment < sizeof(void*))
  2179. {
  2180. alignment = sizeof(void*);
  2181. }
  2182. return memalign(alignment, size);
  2183. }
  2184. #elif defined(__APPLE__) || defined(__ANDROID__) || (defined(__linux__) && defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC))
  2185. #include <cstdlib>
  2186. #if defined(__APPLE__)
  2187. #include <AvailabilityMacros.h>
  2188. #endif
  2189. static void* vma_aligned_alloc(size_t alignment, size_t size)
  2190. {
  2191. // Unfortunately, aligned_alloc causes VMA to crash due to it returning null pointers. (At least under 11.4)
  2192. // Therefore, for now disable this specific exception until a proper solution is found.
  2193. //#if defined(__APPLE__) && (defined(MAC_OS_X_VERSION_10_16) || defined(__IPHONE_14_0))
  2194. //#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_16 || __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0
  2195. // // For C++14, usr/include/malloc/_malloc.h declares aligned_alloc()) only
  2196. // // with the MacOSX11.0 SDK in Xcode 12 (which is what adds
  2197. // // MAC_OS_X_VERSION_10_16), even though the function is marked
  2198. // // availabe for 10.15. That is why the preprocessor checks for 10.16 but
  2199. // // the __builtin_available checks for 10.15.
  2200. // // People who use C++17 could call aligned_alloc with the 10.15 SDK already.
  2201. // if (__builtin_available(macOS 10.15, iOS 13, *))
  2202. // return aligned_alloc(alignment, size);
  2203. //#endif
  2204. //#endif
  2205. // alignment must be >= sizeof(void*)
  2206. if(alignment < sizeof(void*))
  2207. {
  2208. alignment = sizeof(void*);
  2209. }
  2210. void *pointer;
  2211. if(posix_memalign(&pointer, alignment, size) == 0)
  2212. return pointer;
  2213. return VMA_NULL;
  2214. }
  2215. #elif defined(_WIN32)
  2216. static void* vma_aligned_alloc(size_t alignment, size_t size)
  2217. {
  2218. return _aligned_malloc(size, alignment);
  2219. }
  2220. #else
  2221. static void* vma_aligned_alloc(size_t alignment, size_t size)
  2222. {
  2223. return aligned_alloc(alignment, size);
  2224. }
  2225. #endif
  2226. #if defined(_WIN32)
  2227. static void vma_aligned_free(void* ptr)
  2228. {
  2229. _aligned_free(ptr);
  2230. }
  2231. #else
  2232. static void vma_aligned_free(void* VMA_NULLABLE ptr)
  2233. {
  2234. free(ptr);
  2235. }
  2236. #endif
  2237. // If your compiler is not compatible with C++11 and definition of
  2238. // aligned_alloc() function is missing, uncommeting following line may help:
  2239. //#include <malloc.h>
  2240. // Normal assert to check for programmer's errors, especially in Debug configuration.
  2241. #ifndef VMA_ASSERT
  2242. #ifdef NDEBUG
  2243. #define VMA_ASSERT(expr)
  2244. #else
  2245. #define VMA_ASSERT(expr) assert(expr)
  2246. #endif
  2247. #endif
  2248. // Assert that will be called very often, like inside data structures e.g. operator[].
  2249. // Making it non-empty can make program slow.
  2250. #ifndef VMA_HEAVY_ASSERT
  2251. #ifdef NDEBUG
  2252. #define VMA_HEAVY_ASSERT(expr)
  2253. #else
  2254. #define VMA_HEAVY_ASSERT(expr) //VMA_ASSERT(expr)
  2255. #endif
  2256. #endif
  2257. #ifndef VMA_ALIGN_OF
  2258. #define VMA_ALIGN_OF(type) (__alignof(type))
  2259. #endif
  2260. #ifndef VMA_SYSTEM_ALIGNED_MALLOC
  2261. #define VMA_SYSTEM_ALIGNED_MALLOC(size, alignment) vma_aligned_alloc((alignment), (size))
  2262. #endif
  2263. #ifndef VMA_SYSTEM_ALIGNED_FREE
  2264. // VMA_SYSTEM_FREE is the old name, but might have been defined by the user
  2265. #if defined(VMA_SYSTEM_FREE)
  2266. #define VMA_SYSTEM_ALIGNED_FREE(ptr) VMA_SYSTEM_FREE(ptr)
  2267. #else
  2268. #define VMA_SYSTEM_ALIGNED_FREE(ptr) vma_aligned_free(ptr)
  2269. #endif
  2270. #endif
  2271. #ifndef VMA_COUNT_BITS_SET
  2272. // Returns number of bits set to 1 in (v)
  2273. #define VMA_COUNT_BITS_SET(v) VmaCountBitsSet(v)
  2274. #endif
  2275. #ifndef VMA_BITSCAN_LSB
  2276. // Scans integer for index of first nonzero value from the Least Significant Bit (LSB). If mask is 0 then returns UINT8_MAX
  2277. #define VMA_BITSCAN_LSB(mask) VmaBitScanLSB(mask)
  2278. #endif
  2279. #ifndef VMA_BITSCAN_MSB
  2280. // Scans integer for index of first nonzero value from the Most Significant Bit (MSB). If mask is 0 then returns UINT8_MAX
  2281. #define VMA_BITSCAN_MSB(mask) VmaBitScanMSB(mask)
  2282. #endif
  2283. #ifndef VMA_MIN
  2284. #define VMA_MIN(v1, v2) ((std::min)((v1), (v2)))
  2285. #endif
  2286. #ifndef VMA_MAX
  2287. #define VMA_MAX(v1, v2) ((std::max)((v1), (v2)))
  2288. #endif
  2289. #ifndef VMA_SWAP
  2290. #define VMA_SWAP(v1, v2) std::swap((v1), (v2))
  2291. #endif
  2292. #ifndef VMA_SORT
  2293. #define VMA_SORT(beg, end, cmp) std::sort(beg, end, cmp)
  2294. #endif
  2295. #ifndef VMA_DEBUG_LOG
  2296. #define VMA_DEBUG_LOG(format, ...)
  2297. /*
  2298. #define VMA_DEBUG_LOG(format, ...) do { \
  2299. printf(format, __VA_ARGS__); \
  2300. printf("\n"); \
  2301. } while(false)
  2302. */
  2303. #endif
  2304. // Define this macro to 1 to enable functions: vmaBuildStatsString, vmaFreeStatsString.
  2305. #if VMA_STATS_STRING_ENABLED
  2306. static inline void VmaUint32ToStr(char* VMA_NOT_NULL outStr, size_t strLen, uint32_t num)
  2307. {
  2308. snprintf(outStr, strLen, "%u", static_cast<unsigned int>(num));
  2309. }
  2310. static inline void VmaUint64ToStr(char* VMA_NOT_NULL outStr, size_t strLen, uint64_t num)
  2311. {
  2312. snprintf(outStr, strLen, "%llu", static_cast<unsigned long long>(num));
  2313. }
  2314. static inline void VmaPtrToStr(char* VMA_NOT_NULL outStr, size_t strLen, const void* ptr)
  2315. {
  2316. snprintf(outStr, strLen, "%p", ptr);
  2317. }
  2318. #endif
  2319. #ifndef VMA_MUTEX
  2320. class VmaMutex
  2321. {
  2322. public:
  2323. void Lock() { m_Mutex.lock(); }
  2324. void Unlock() { m_Mutex.unlock(); }
  2325. bool TryLock() { return m_Mutex.try_lock(); }
  2326. private:
  2327. std::mutex m_Mutex;
  2328. };
  2329. #define VMA_MUTEX VmaMutex
  2330. #endif
  2331. // Read-write mutex, where "read" is shared access, "write" is exclusive access.
  2332. #ifndef VMA_RW_MUTEX
  2333. #if VMA_USE_STL_SHARED_MUTEX
  2334. // Use std::shared_mutex from C++17.
  2335. #include <shared_mutex>
  2336. class VmaRWMutex
  2337. {
  2338. public:
  2339. void LockRead() { m_Mutex.lock_shared(); }
  2340. void UnlockRead() { m_Mutex.unlock_shared(); }
  2341. bool TryLockRead() { return m_Mutex.try_lock_shared(); }
  2342. void LockWrite() { m_Mutex.lock(); }
  2343. void UnlockWrite() { m_Mutex.unlock(); }
  2344. bool TryLockWrite() { return m_Mutex.try_lock(); }
  2345. private:
  2346. std::shared_mutex m_Mutex;
  2347. };
  2348. #define VMA_RW_MUTEX VmaRWMutex
  2349. #elif defined(_WIN32) && defined(WINVER) && WINVER >= 0x0600
  2350. // Use SRWLOCK from WinAPI.
  2351. // Minimum supported client = Windows Vista, server = Windows Server 2008.
  2352. class VmaRWMutex
  2353. {
  2354. public:
  2355. VmaRWMutex() { InitializeSRWLock(&m_Lock); }
  2356. void LockRead() { AcquireSRWLockShared(&m_Lock); }
  2357. void UnlockRead() { ReleaseSRWLockShared(&m_Lock); }
  2358. bool TryLockRead() { return TryAcquireSRWLockShared(&m_Lock) != FALSE; }
  2359. void LockWrite() { AcquireSRWLockExclusive(&m_Lock); }
  2360. void UnlockWrite() { ReleaseSRWLockExclusive(&m_Lock); }
  2361. bool TryLockWrite() { return TryAcquireSRWLockExclusive(&m_Lock) != FALSE; }
  2362. private:
  2363. SRWLOCK m_Lock;
  2364. };
  2365. #define VMA_RW_MUTEX VmaRWMutex
  2366. #else
  2367. // Less efficient fallback: Use normal mutex.
  2368. class VmaRWMutex
  2369. {
  2370. public:
  2371. void LockRead() { m_Mutex.Lock(); }
  2372. void UnlockRead() { m_Mutex.Unlock(); }
  2373. bool TryLockRead() { return m_Mutex.TryLock(); }
  2374. void LockWrite() { m_Mutex.Lock(); }
  2375. void UnlockWrite() { m_Mutex.Unlock(); }
  2376. bool TryLockWrite() { return m_Mutex.TryLock(); }
  2377. private:
  2378. VMA_MUTEX m_Mutex;
  2379. };
  2380. #define VMA_RW_MUTEX VmaRWMutex
  2381. #endif // #if VMA_USE_STL_SHARED_MUTEX
  2382. #endif // #ifndef VMA_RW_MUTEX
  2383. /*
  2384. If providing your own implementation, you need to implement a subset of std::atomic.
  2385. */
  2386. #ifndef VMA_ATOMIC_UINT32
  2387. #include <atomic>
  2388. #define VMA_ATOMIC_UINT32 std::atomic<uint32_t>
  2389. #endif
  2390. #ifndef VMA_ATOMIC_UINT64
  2391. #include <atomic>
  2392. #define VMA_ATOMIC_UINT64 std::atomic<uint64_t>
  2393. #endif
  2394. #ifndef VMA_DEBUG_ALWAYS_DEDICATED_MEMORY
  2395. /**
  2396. Every allocation will have its own memory block.
  2397. Define to 1 for debugging purposes only.
  2398. */
  2399. #define VMA_DEBUG_ALWAYS_DEDICATED_MEMORY (0)
  2400. #endif
  2401. #ifndef VMA_MIN_ALIGNMENT
  2402. /**
  2403. Minimum alignment of all allocations, in bytes.
  2404. Set to more than 1 for debugging purposes. Must be power of two.
  2405. */
  2406. #ifdef VMA_DEBUG_ALIGNMENT // Old name
  2407. #define VMA_MIN_ALIGNMENT VMA_DEBUG_ALIGNMENT
  2408. #else
  2409. #define VMA_MIN_ALIGNMENT (1)
  2410. #endif
  2411. #endif
  2412. #ifndef VMA_DEBUG_MARGIN
  2413. /**
  2414. Minimum margin after every allocation, in bytes.
  2415. Set nonzero for debugging purposes only.
  2416. */
  2417. #define VMA_DEBUG_MARGIN (0)
  2418. #endif
  2419. #ifndef VMA_DEBUG_INITIALIZE_ALLOCATIONS
  2420. /**
  2421. Define this macro to 1 to automatically fill new allocations and destroyed
  2422. allocations with some bit pattern.
  2423. */
  2424. #define VMA_DEBUG_INITIALIZE_ALLOCATIONS (0)
  2425. #endif
  2426. #ifndef VMA_DEBUG_DETECT_CORRUPTION
  2427. /**
  2428. Define this macro to 1 together with non-zero value of VMA_DEBUG_MARGIN to
  2429. enable writing magic value to the margin after every allocation and
  2430. validating it, so that memory corruptions (out-of-bounds writes) are detected.
  2431. */
  2432. #define VMA_DEBUG_DETECT_CORRUPTION (0)
  2433. #endif
  2434. #ifndef VMA_DEBUG_GLOBAL_MUTEX
  2435. /**
  2436. Set this to 1 for debugging purposes only, to enable single mutex protecting all
  2437. entry calls to the library. Can be useful for debugging multithreading issues.
  2438. */
  2439. #define VMA_DEBUG_GLOBAL_MUTEX (0)
  2440. #endif
  2441. #ifndef VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY
  2442. /**
  2443. Minimum value for VkPhysicalDeviceLimits::bufferImageGranularity.
  2444. Set to more than 1 for debugging purposes only. Must be power of two.
  2445. */
  2446. #define VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY (1)
  2447. #endif
  2448. #ifndef VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT
  2449. /*
  2450. Set this to 1 to make VMA never exceed VkPhysicalDeviceLimits::maxMemoryAllocationCount
  2451. and return error instead of leaving up to Vulkan implementation what to do in such cases.
  2452. */
  2453. #define VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT (0)
  2454. #endif
  2455. #ifndef VMA_SMALL_HEAP_MAX_SIZE
  2456. /// Maximum size of a memory heap in Vulkan to consider it "small".
  2457. #define VMA_SMALL_HEAP_MAX_SIZE (1024ull * 1024 * 1024)
  2458. #endif
  2459. #ifndef VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE
  2460. /// Default size of a block allocated as single VkDeviceMemory from a "large" heap.
  2461. #define VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE (256ull * 1024 * 1024)
  2462. #endif
  2463. /*
  2464. Mapping hysteresis is a logic that launches when vmaMapMemory/vmaUnmapMemory is called
  2465. or a persistently mapped allocation is created and destroyed several times in a row.
  2466. It keeps additional +1 mapping of a device memory block to prevent calling actual
  2467. vkMapMemory/vkUnmapMemory too many times, which may improve performance and help
  2468. tools like RenderDOc.
  2469. */
  2470. #ifndef VMA_MAPPING_HYSTERESIS_ENABLED
  2471. #define VMA_MAPPING_HYSTERESIS_ENABLED 1
  2472. #endif
  2473. #ifndef VMA_CLASS_NO_COPY
  2474. #define VMA_CLASS_NO_COPY(className) \
  2475. private: \
  2476. className(const className&) = delete; \
  2477. className& operator=(const className&) = delete;
  2478. #endif
  2479. #define VMA_VALIDATE(cond) do { if(!(cond)) { \
  2480. VMA_ASSERT(0 && "Validation failed: " #cond); \
  2481. return false; \
  2482. } } while(false)
  2483. /*******************************************************************************
  2484. END OF CONFIGURATION
  2485. */
  2486. #endif // _VMA_CONFIGURATION
  2487. static const uint8_t VMA_ALLOCATION_FILL_PATTERN_CREATED = 0xDC;
  2488. static const uint8_t VMA_ALLOCATION_FILL_PATTERN_DESTROYED = 0xEF;
  2489. // Decimal 2139416166, float NaN, little-endian binary 66 E6 84 7F.
  2490. static const uint32_t VMA_CORRUPTION_DETECTION_MAGIC_VALUE = 0x7F84E666;
  2491. // Copy of some Vulkan definitions so we don't need to check their existence just to handle few constants.
  2492. static const uint32_t VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY = 0x00000040;
  2493. static const uint32_t VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY = 0x00000080;
  2494. static const uint32_t VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY = 0x00020000;
  2495. static const uint32_t VK_IMAGE_CREATE_DISJOINT_BIT_COPY = 0x00000200;
  2496. static const int32_t VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT_COPY = 1000158000;
  2497. static const uint32_t VMA_ALLOCATION_INTERNAL_STRATEGY_MIN_OFFSET = 0x10000000u;
  2498. static const uint32_t VMA_ALLOCATION_TRY_COUNT = 32;
  2499. static const uint32_t VMA_VENDOR_ID_AMD = 4098;
  2500. // This one is tricky. Vulkan specification defines this code as available since
  2501. // Vulkan 1.0, but doesn't actually define it in Vulkan SDK earlier than 1.2.131.
  2502. // See pull request #207.
  2503. #define VK_ERROR_UNKNOWN_COPY ((VkResult)-13)
  2504. #if VMA_STATS_STRING_ENABLED
  2505. // Correspond to values of enum VmaSuballocationType.
  2506. static const char* VMA_SUBALLOCATION_TYPE_NAMES[] =
  2507. {
  2508. "FREE",
  2509. "UNKNOWN",
  2510. "BUFFER",
  2511. "IMAGE_UNKNOWN",
  2512. "IMAGE_LINEAR",
  2513. "IMAGE_OPTIMAL",
  2514. };
  2515. #endif
  2516. static VkAllocationCallbacks VmaEmptyAllocationCallbacks =
  2517. { VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL };
  2518. #ifndef _VMA_ENUM_DECLARATIONS
  2519. enum VmaSuballocationType
  2520. {
  2521. VMA_SUBALLOCATION_TYPE_FREE = 0,
  2522. VMA_SUBALLOCATION_TYPE_UNKNOWN = 1,
  2523. VMA_SUBALLOCATION_TYPE_BUFFER = 2,
  2524. VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN = 3,
  2525. VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR = 4,
  2526. VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL = 5,
  2527. VMA_SUBALLOCATION_TYPE_MAX_ENUM = 0x7FFFFFFF
  2528. };
  2529. enum VMA_CACHE_OPERATION
  2530. {
  2531. VMA_CACHE_FLUSH,
  2532. VMA_CACHE_INVALIDATE
  2533. };
  2534. enum class VmaAllocationRequestType
  2535. {
  2536. Normal,
  2537. TLSF,
  2538. // Used by "Linear" algorithm.
  2539. UpperAddress,
  2540. EndOf1st,
  2541. EndOf2nd,
  2542. };
  2543. #endif // _VMA_ENUM_DECLARATIONS
  2544. #ifndef _VMA_FORWARD_DECLARATIONS
  2545. // Opaque handle used by allocation algorithms to identify single allocation in any conforming way.
  2546. VK_DEFINE_NON_DISPATCHABLE_HANDLE(VmaAllocHandle);
  2547. struct VmaMutexLock;
  2548. struct VmaMutexLockRead;
  2549. struct VmaMutexLockWrite;
  2550. template<typename T>
  2551. struct AtomicTransactionalIncrement;
  2552. template<typename T>
  2553. struct VmaStlAllocator;
  2554. template<typename T, typename AllocatorT>
  2555. class VmaVector;
  2556. template<typename T, typename AllocatorT, size_t N>
  2557. class VmaSmallVector;
  2558. template<typename T>
  2559. class VmaPoolAllocator;
  2560. template<typename T>
  2561. struct VmaListItem;
  2562. template<typename T>
  2563. class VmaRawList;
  2564. template<typename T, typename AllocatorT>
  2565. class VmaList;
  2566. template<typename ItemTypeTraits>
  2567. class VmaIntrusiveLinkedList;
  2568. // Unused in this version
  2569. #if 0
  2570. template<typename T1, typename T2>
  2571. struct VmaPair;
  2572. template<typename FirstT, typename SecondT>
  2573. struct VmaPairFirstLess;
  2574. template<typename KeyT, typename ValueT>
  2575. class VmaMap;
  2576. #endif
  2577. #if VMA_STATS_STRING_ENABLED
  2578. class VmaStringBuilder;
  2579. class VmaJsonWriter;
  2580. #endif
  2581. class VmaDeviceMemoryBlock;
  2582. struct VmaDedicatedAllocationListItemTraits;
  2583. class VmaDedicatedAllocationList;
  2584. struct VmaSuballocation;
  2585. struct VmaSuballocationOffsetLess;
  2586. struct VmaSuballocationOffsetGreater;
  2587. struct VmaSuballocationItemSizeLess;
  2588. typedef VmaList<VmaSuballocation, VmaStlAllocator<VmaSuballocation>> VmaSuballocationList;
  2589. struct VmaAllocationRequest;
  2590. class VmaBlockMetadata;
  2591. class VmaBlockMetadata_Linear;
  2592. class VmaBlockMetadata_TLSF;
  2593. class VmaBlockVector;
  2594. struct VmaPoolListItemTraits;
  2595. struct VmaCurrentBudgetData;
  2596. class VmaAllocationObjectAllocator;
  2597. #endif // _VMA_FORWARD_DECLARATIONS
  2598. #ifndef _VMA_FUNCTIONS
  2599. /*
  2600. Returns number of bits set to 1 in (v).
  2601. On specific platforms and compilers you can use instrinsics like:
  2602. Visual Studio:
  2603. return __popcnt(v);
  2604. GCC, Clang:
  2605. return static_cast<uint32_t>(__builtin_popcount(v));
  2606. Define macro VMA_COUNT_BITS_SET to provide your optimized implementation.
  2607. But you need to check in runtime whether user's CPU supports these, as some old processors don't.
  2608. */
  2609. static inline uint32_t VmaCountBitsSet(uint32_t v)
  2610. {
  2611. #if __cplusplus >= 202002L || _MSVC_LANG >= 202002L // C++20
  2612. return std::popcount(v);
  2613. #else
  2614. uint32_t c = v - ((v >> 1) & 0x55555555);
  2615. c = ((c >> 2) & 0x33333333) + (c & 0x33333333);
  2616. c = ((c >> 4) + c) & 0x0F0F0F0F;
  2617. c = ((c >> 8) + c) & 0x00FF00FF;
  2618. c = ((c >> 16) + c) & 0x0000FFFF;
  2619. return c;
  2620. #endif
  2621. }
  2622. static inline uint8_t VmaBitScanLSB(uint64_t mask)
  2623. {
  2624. #if defined(_MSC_VER) && defined(_WIN64)
  2625. unsigned long pos;
  2626. if (_BitScanForward64(&pos, mask))
  2627. return static_cast<uint8_t>(pos);
  2628. return UINT8_MAX;
  2629. #elif defined __GNUC__ || defined __clang__
  2630. return static_cast<uint8_t>(__builtin_ffsll(mask)) - 1U;
  2631. #else
  2632. uint8_t pos = 0;
  2633. uint64_t bit = 1;
  2634. do
  2635. {
  2636. if (mask & bit)
  2637. return pos;
  2638. bit <<= 1;
  2639. } while (pos++ < 63);
  2640. return UINT8_MAX;
  2641. #endif
  2642. }
  2643. static inline uint8_t VmaBitScanLSB(uint32_t mask)
  2644. {
  2645. #ifdef _MSC_VER
  2646. unsigned long pos;
  2647. if (_BitScanForward(&pos, mask))
  2648. return static_cast<uint8_t>(pos);
  2649. return UINT8_MAX;
  2650. #elif defined __GNUC__ || defined __clang__
  2651. return static_cast<uint8_t>(__builtin_ffs(mask)) - 1U;
  2652. #else
  2653. uint8_t pos = 0;
  2654. uint32_t bit = 1;
  2655. do
  2656. {
  2657. if (mask & bit)
  2658. return pos;
  2659. bit <<= 1;
  2660. } while (pos++ < 31);
  2661. return UINT8_MAX;
  2662. #endif
  2663. }
  2664. static inline uint8_t VmaBitScanMSB(uint64_t mask)
  2665. {
  2666. #if defined(_MSC_VER) && defined(_WIN64)
  2667. unsigned long pos;
  2668. if (_BitScanReverse64(&pos, mask))
  2669. return static_cast<uint8_t>(pos);
  2670. #elif defined __GNUC__ || defined __clang__
  2671. if (mask)
  2672. return 63 - static_cast<uint8_t>(__builtin_clzll(mask));
  2673. #else
  2674. uint8_t pos = 63;
  2675. uint64_t bit = 1ULL << 63;
  2676. do
  2677. {
  2678. if (mask & bit)
  2679. return pos;
  2680. bit >>= 1;
  2681. } while (pos-- > 0);
  2682. #endif
  2683. return UINT8_MAX;
  2684. }
  2685. static inline uint8_t VmaBitScanMSB(uint32_t mask)
  2686. {
  2687. #ifdef _MSC_VER
  2688. unsigned long pos;
  2689. if (_BitScanReverse(&pos, mask))
  2690. return static_cast<uint8_t>(pos);
  2691. #elif defined __GNUC__ || defined __clang__
  2692. if (mask)
  2693. return 31 - static_cast<uint8_t>(__builtin_clz(mask));
  2694. #else
  2695. uint8_t pos = 31;
  2696. uint32_t bit = 1UL << 31;
  2697. do
  2698. {
  2699. if (mask & bit)
  2700. return pos;
  2701. bit >>= 1;
  2702. } while (pos-- > 0);
  2703. #endif
  2704. return UINT8_MAX;
  2705. }
  2706. /*
  2707. Returns true if given number is a power of two.
  2708. T must be unsigned integer number or signed integer but always nonnegative.
  2709. For 0 returns true.
  2710. */
  2711. template <typename T>
  2712. inline bool VmaIsPow2(T x)
  2713. {
  2714. return (x & (x - 1)) == 0;
  2715. }
  2716. // Aligns given value up to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 16.
  2717. // Use types like uint32_t, uint64_t as T.
  2718. template <typename T>
  2719. static inline T VmaAlignUp(T val, T alignment)
  2720. {
  2721. VMA_HEAVY_ASSERT(VmaIsPow2(alignment));
  2722. return (val + alignment - 1) & ~(alignment - 1);
  2723. }
  2724. // Aligns given value down to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 8.
  2725. // Use types like uint32_t, uint64_t as T.
  2726. template <typename T>
  2727. static inline T VmaAlignDown(T val, T alignment)
  2728. {
  2729. VMA_HEAVY_ASSERT(VmaIsPow2(alignment));
  2730. return val & ~(alignment - 1);
  2731. }
  2732. // Division with mathematical rounding to nearest number.
  2733. template <typename T>
  2734. static inline T VmaRoundDiv(T x, T y)
  2735. {
  2736. return (x + (y / (T)2)) / y;
  2737. }
  2738. // Divide by 'y' and round up to nearest integer.
  2739. template <typename T>
  2740. static inline T VmaDivideRoundingUp(T x, T y)
  2741. {
  2742. return (x + y - (T)1) / y;
  2743. }
  2744. // Returns smallest power of 2 greater or equal to v.
  2745. static inline uint32_t VmaNextPow2(uint32_t v)
  2746. {
  2747. v--;
  2748. v |= v >> 1;
  2749. v |= v >> 2;
  2750. v |= v >> 4;
  2751. v |= v >> 8;
  2752. v |= v >> 16;
  2753. v++;
  2754. return v;
  2755. }
  2756. static inline uint64_t VmaNextPow2(uint64_t v)
  2757. {
  2758. v--;
  2759. v |= v >> 1;
  2760. v |= v >> 2;
  2761. v |= v >> 4;
  2762. v |= v >> 8;
  2763. v |= v >> 16;
  2764. v |= v >> 32;
  2765. v++;
  2766. return v;
  2767. }
  2768. // Returns largest power of 2 less or equal to v.
  2769. static inline uint32_t VmaPrevPow2(uint32_t v)
  2770. {
  2771. v |= v >> 1;
  2772. v |= v >> 2;
  2773. v |= v >> 4;
  2774. v |= v >> 8;
  2775. v |= v >> 16;
  2776. v = v ^ (v >> 1);
  2777. return v;
  2778. }
  2779. static inline uint64_t VmaPrevPow2(uint64_t v)
  2780. {
  2781. v |= v >> 1;
  2782. v |= v >> 2;
  2783. v |= v >> 4;
  2784. v |= v >> 8;
  2785. v |= v >> 16;
  2786. v |= v >> 32;
  2787. v = v ^ (v >> 1);
  2788. return v;
  2789. }
  2790. static inline bool VmaStrIsEmpty(const char* pStr)
  2791. {
  2792. return pStr == VMA_NULL || *pStr == '\0';
  2793. }
  2794. /*
  2795. Returns true if two memory blocks occupy overlapping pages.
  2796. ResourceA must be in less memory offset than ResourceB.
  2797. Algorithm is based on "Vulkan 1.0.39 - A Specification (with all registered Vulkan extensions)"
  2798. chapter 11.6 "Resource Memory Association", paragraph "Buffer-Image Granularity".
  2799. */
  2800. static inline bool VmaBlocksOnSamePage(
  2801. VkDeviceSize resourceAOffset,
  2802. VkDeviceSize resourceASize,
  2803. VkDeviceSize resourceBOffset,
  2804. VkDeviceSize pageSize)
  2805. {
  2806. VMA_ASSERT(resourceAOffset + resourceASize <= resourceBOffset && resourceASize > 0 && pageSize > 0);
  2807. VkDeviceSize resourceAEnd = resourceAOffset + resourceASize - 1;
  2808. VkDeviceSize resourceAEndPage = resourceAEnd & ~(pageSize - 1);
  2809. VkDeviceSize resourceBStart = resourceBOffset;
  2810. VkDeviceSize resourceBStartPage = resourceBStart & ~(pageSize - 1);
  2811. return resourceAEndPage == resourceBStartPage;
  2812. }
  2813. /*
  2814. Returns true if given suballocation types could conflict and must respect
  2815. VkPhysicalDeviceLimits::bufferImageGranularity. They conflict if one is buffer
  2816. or linear image and another one is optimal image. If type is unknown, behave
  2817. conservatively.
  2818. */
  2819. static inline bool VmaIsBufferImageGranularityConflict(
  2820. VmaSuballocationType suballocType1,
  2821. VmaSuballocationType suballocType2)
  2822. {
  2823. if (suballocType1 > suballocType2)
  2824. {
  2825. VMA_SWAP(suballocType1, suballocType2);
  2826. }
  2827. switch (suballocType1)
  2828. {
  2829. case VMA_SUBALLOCATION_TYPE_FREE:
  2830. return false;
  2831. case VMA_SUBALLOCATION_TYPE_UNKNOWN:
  2832. return true;
  2833. case VMA_SUBALLOCATION_TYPE_BUFFER:
  2834. return
  2835. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
  2836. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
  2837. case VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN:
  2838. return
  2839. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
  2840. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR ||
  2841. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
  2842. case VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR:
  2843. return
  2844. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
  2845. case VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL:
  2846. return false;
  2847. default:
  2848. VMA_ASSERT(0);
  2849. return true;
  2850. }
  2851. }
  2852. static void VmaWriteMagicValue(void* pData, VkDeviceSize offset)
  2853. {
  2854. #if VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_DETECT_CORRUPTION
  2855. uint32_t* pDst = (uint32_t*)((char*)pData + offset);
  2856. const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t);
  2857. for (size_t i = 0; i < numberCount; ++i, ++pDst)
  2858. {
  2859. *pDst = VMA_CORRUPTION_DETECTION_MAGIC_VALUE;
  2860. }
  2861. #else
  2862. // no-op
  2863. #endif
  2864. }
  2865. static bool VmaValidateMagicValue(const void* pData, VkDeviceSize offset)
  2866. {
  2867. #if VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_DETECT_CORRUPTION
  2868. const uint32_t* pSrc = (const uint32_t*)((const char*)pData + offset);
  2869. const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t);
  2870. for (size_t i = 0; i < numberCount; ++i, ++pSrc)
  2871. {
  2872. if (*pSrc != VMA_CORRUPTION_DETECTION_MAGIC_VALUE)
  2873. {
  2874. return false;
  2875. }
  2876. }
  2877. #endif
  2878. return true;
  2879. }
  2880. /*
  2881. Fills structure with parameters of an example buffer to be used for transfers
  2882. during GPU memory defragmentation.
  2883. */
  2884. static void VmaFillGpuDefragmentationBufferCreateInfo(VkBufferCreateInfo& outBufCreateInfo)
  2885. {
  2886. memset(&outBufCreateInfo, 0, sizeof(outBufCreateInfo));
  2887. outBufCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  2888. outBufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  2889. outBufCreateInfo.size = (VkDeviceSize)VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE; // Example size.
  2890. }
  2891. /*
  2892. Performs binary search and returns iterator to first element that is greater or
  2893. equal to (key), according to comparison (cmp).
  2894. Cmp should return true if first argument is less than second argument.
  2895. Returned value is the found element, if present in the collection or place where
  2896. new element with value (key) should be inserted.
  2897. */
  2898. template <typename CmpLess, typename IterT, typename KeyT>
  2899. static IterT VmaBinaryFindFirstNotLess(IterT beg, IterT end, const KeyT& key, const CmpLess& cmp)
  2900. {
  2901. size_t down = 0, up = (end - beg);
  2902. while (down < up)
  2903. {
  2904. const size_t mid = down + (up - down) / 2; // Overflow-safe midpoint calculation
  2905. if (cmp(*(beg + mid), key))
  2906. {
  2907. down = mid + 1;
  2908. }
  2909. else
  2910. {
  2911. up = mid;
  2912. }
  2913. }
  2914. return beg + down;
  2915. }
  2916. template<typename CmpLess, typename IterT, typename KeyT>
  2917. IterT VmaBinaryFindSorted(const IterT& beg, const IterT& end, const KeyT& value, const CmpLess& cmp)
  2918. {
  2919. IterT it = VmaBinaryFindFirstNotLess<CmpLess, IterT, KeyT>(
  2920. beg, end, value, cmp);
  2921. if (it == end ||
  2922. (!cmp(*it, value) && !cmp(value, *it)))
  2923. {
  2924. return it;
  2925. }
  2926. return end;
  2927. }
  2928. /*
  2929. Returns true if all pointers in the array are not-null and unique.
  2930. Warning! O(n^2) complexity. Use only inside VMA_HEAVY_ASSERT.
  2931. T must be pointer type, e.g. VmaAllocation, VmaPool.
  2932. */
  2933. template<typename T>
  2934. static bool VmaValidatePointerArray(uint32_t count, const T* arr)
  2935. {
  2936. for (uint32_t i = 0; i < count; ++i)
  2937. {
  2938. const T iPtr = arr[i];
  2939. if (iPtr == VMA_NULL)
  2940. {
  2941. return false;
  2942. }
  2943. for (uint32_t j = i + 1; j < count; ++j)
  2944. {
  2945. if (iPtr == arr[j])
  2946. {
  2947. return false;
  2948. }
  2949. }
  2950. }
  2951. return true;
  2952. }
  2953. template<typename MainT, typename NewT>
  2954. static inline void VmaPnextChainPushFront(MainT* mainStruct, NewT* newStruct)
  2955. {
  2956. newStruct->pNext = mainStruct->pNext;
  2957. mainStruct->pNext = newStruct;
  2958. }
  2959. // This is the main algorithm that guides the selection of a memory type best for an allocation -
  2960. // converts usage to required/preferred/not preferred flags.
  2961. static bool FindMemoryPreferences(
  2962. bool isIntegratedGPU,
  2963. const VmaAllocationCreateInfo& allocCreateInfo,
  2964. VkFlags bufImgUsage, // VkBufferCreateInfo::usage or VkImageCreateInfo::usage. UINT32_MAX if unknown.
  2965. VkMemoryPropertyFlags& outRequiredFlags,
  2966. VkMemoryPropertyFlags& outPreferredFlags,
  2967. VkMemoryPropertyFlags& outNotPreferredFlags)
  2968. {
  2969. outRequiredFlags = allocCreateInfo.requiredFlags;
  2970. outPreferredFlags = allocCreateInfo.preferredFlags;
  2971. outNotPreferredFlags = 0;
  2972. switch(allocCreateInfo.usage)
  2973. {
  2974. case VMA_MEMORY_USAGE_UNKNOWN:
  2975. break;
  2976. case VMA_MEMORY_USAGE_GPU_ONLY:
  2977. if(!isIntegratedGPU || (outPreferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  2978. {
  2979. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  2980. }
  2981. break;
  2982. case VMA_MEMORY_USAGE_CPU_ONLY:
  2983. outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
  2984. break;
  2985. case VMA_MEMORY_USAGE_CPU_TO_GPU:
  2986. outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  2987. if(!isIntegratedGPU || (outPreferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  2988. {
  2989. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  2990. }
  2991. break;
  2992. case VMA_MEMORY_USAGE_GPU_TO_CPU:
  2993. outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  2994. outPreferredFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  2995. break;
  2996. case VMA_MEMORY_USAGE_CPU_COPY:
  2997. outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  2998. break;
  2999. case VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED:
  3000. outRequiredFlags |= VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT;
  3001. break;
  3002. case VMA_MEMORY_USAGE_AUTO:
  3003. case VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE:
  3004. case VMA_MEMORY_USAGE_AUTO_PREFER_HOST:
  3005. {
  3006. if(bufImgUsage == UINT32_MAX)
  3007. {
  3008. VMA_ASSERT(0 && "VMA_MEMORY_USAGE_AUTO* values can only be used with functions like vmaCreateBuffer, vmaCreateImage so that the details of the created resource are known.");
  3009. return false;
  3010. }
  3011. // This relies on values of VK_IMAGE_USAGE_TRANSFER* being the same VK_BUFFER_IMAGE_TRANSFER*.
  3012. const bool deviceAccess = (bufImgUsage & ~(VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT)) != 0;
  3013. const bool hostAccessSequentialWrite = (allocCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT) != 0;
  3014. const bool hostAccessRandom = (allocCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT) != 0;
  3015. const bool hostAccessAllowTransferInstead = (allocCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT) != 0;
  3016. const bool preferDevice = allocCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE;
  3017. const bool preferHost = allocCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_HOST;
  3018. // CPU random access - e.g. a buffer written to or transferred from GPU to read back on CPU.
  3019. if(hostAccessRandom)
  3020. {
  3021. if(!isIntegratedGPU && deviceAccess && hostAccessAllowTransferInstead && !preferHost)
  3022. {
  3023. // Nice if it will end up in HOST_VISIBLE, but more importantly prefer DEVICE_LOCAL.
  3024. // Omitting HOST_VISIBLE here is intentional.
  3025. // In case there is DEVICE_LOCAL | HOST_VISIBLE | HOST_CACHED, it will pick that one.
  3026. // Otherwise, this will give same weight to DEVICE_LOCAL as HOST_VISIBLE | HOST_CACHED and select the former if occurs first on the list.
  3027. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  3028. }
  3029. else
  3030. {
  3031. // Always CPU memory, cached.
  3032. outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  3033. }
  3034. }
  3035. // CPU sequential write - may be CPU or host-visible GPU memory, uncached and write-combined.
  3036. else if(hostAccessSequentialWrite)
  3037. {
  3038. // Want uncached and write-combined.
  3039. outNotPreferredFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  3040. if(!isIntegratedGPU && deviceAccess && hostAccessAllowTransferInstead && !preferHost)
  3041. {
  3042. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  3043. }
  3044. else
  3045. {
  3046. outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  3047. // Direct GPU access, CPU sequential write (e.g. a dynamic uniform buffer updated every frame)
  3048. if(deviceAccess)
  3049. {
  3050. // Could go to CPU memory or GPU BAR/unified. Up to the user to decide. If no preference, choose GPU memory.
  3051. if(preferHost)
  3052. outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3053. else
  3054. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3055. }
  3056. // GPU no direct access, CPU sequential write (e.g. an upload buffer to be transferred to the GPU)
  3057. else
  3058. {
  3059. // Could go to CPU memory or GPU BAR/unified. Up to the user to decide. If no preference, choose CPU memory.
  3060. if(preferDevice)
  3061. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3062. else
  3063. outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3064. }
  3065. }
  3066. }
  3067. // No CPU access
  3068. else
  3069. {
  3070. // GPU access, no CPU access (e.g. a color attachment image) - prefer GPU memory
  3071. if(deviceAccess)
  3072. {
  3073. // ...unless there is a clear preference from the user not to do so.
  3074. if(preferHost)
  3075. outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3076. else
  3077. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3078. }
  3079. // No direct GPU access, no CPU access, just transfers.
  3080. // It may be staging copy intended for e.g. preserving image for next frame (then better GPU memory) or
  3081. // a "swap file" copy to free some GPU memory (then better CPU memory).
  3082. // Up to the user to decide. If no preferece, assume the former and choose GPU memory.
  3083. if(preferHost)
  3084. outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3085. else
  3086. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3087. }
  3088. break;
  3089. }
  3090. default:
  3091. VMA_ASSERT(0);
  3092. }
  3093. // Avoid DEVICE_COHERENT unless explicitly requested.
  3094. if(((allocCreateInfo.requiredFlags | allocCreateInfo.preferredFlags) &
  3095. (VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY | VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY)) == 0)
  3096. {
  3097. outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY;
  3098. }
  3099. return true;
  3100. }
  3101. ////////////////////////////////////////////////////////////////////////////////
  3102. // Memory allocation
  3103. static void* VmaMalloc(const VkAllocationCallbacks* pAllocationCallbacks, size_t size, size_t alignment)
  3104. {
  3105. void* result = VMA_NULL;
  3106. if ((pAllocationCallbacks != VMA_NULL) &&
  3107. (pAllocationCallbacks->pfnAllocation != VMA_NULL))
  3108. {
  3109. result = (*pAllocationCallbacks->pfnAllocation)(
  3110. pAllocationCallbacks->pUserData,
  3111. size,
  3112. alignment,
  3113. VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
  3114. }
  3115. else
  3116. {
  3117. result = VMA_SYSTEM_ALIGNED_MALLOC(size, alignment);
  3118. }
  3119. VMA_ASSERT(result != VMA_NULL && "CPU memory allocation failed.");
  3120. return result;
  3121. }
  3122. static void VmaFree(const VkAllocationCallbacks* pAllocationCallbacks, void* ptr)
  3123. {
  3124. if ((pAllocationCallbacks != VMA_NULL) &&
  3125. (pAllocationCallbacks->pfnFree != VMA_NULL))
  3126. {
  3127. (*pAllocationCallbacks->pfnFree)(pAllocationCallbacks->pUserData, ptr);
  3128. }
  3129. else
  3130. {
  3131. VMA_SYSTEM_ALIGNED_FREE(ptr);
  3132. }
  3133. }
  3134. template<typename T>
  3135. static T* VmaAllocate(const VkAllocationCallbacks* pAllocationCallbacks)
  3136. {
  3137. return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T), VMA_ALIGN_OF(T));
  3138. }
  3139. template<typename T>
  3140. static T* VmaAllocateArray(const VkAllocationCallbacks* pAllocationCallbacks, size_t count)
  3141. {
  3142. return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T) * count, VMA_ALIGN_OF(T));
  3143. }
  3144. #define vma_new(allocator, type) new(VmaAllocate<type>(allocator))(type)
  3145. #define vma_new_array(allocator, type, count) new(VmaAllocateArray<type>((allocator), (count)))(type)
  3146. template<typename T>
  3147. static void vma_delete(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr)
  3148. {
  3149. ptr->~T();
  3150. VmaFree(pAllocationCallbacks, ptr);
  3151. }
  3152. template<typename T>
  3153. static void vma_delete_array(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr, size_t count)
  3154. {
  3155. if (ptr != VMA_NULL)
  3156. {
  3157. for (size_t i = count; i--; )
  3158. {
  3159. ptr[i].~T();
  3160. }
  3161. VmaFree(pAllocationCallbacks, ptr);
  3162. }
  3163. }
  3164. static char* VmaCreateStringCopy(const VkAllocationCallbacks* allocs, const char* srcStr)
  3165. {
  3166. if (srcStr != VMA_NULL)
  3167. {
  3168. const size_t len = strlen(srcStr);
  3169. char* const result = vma_new_array(allocs, char, len + 1);
  3170. memcpy(result, srcStr, len + 1);
  3171. return result;
  3172. }
  3173. return VMA_NULL;
  3174. }
  3175. #if VMA_STATS_STRING_ENABLED
  3176. static char* VmaCreateStringCopy(const VkAllocationCallbacks* allocs, const char* srcStr, size_t strLen)
  3177. {
  3178. if (srcStr != VMA_NULL)
  3179. {
  3180. char* const result = vma_new_array(allocs, char, strLen + 1);
  3181. memcpy(result, srcStr, strLen);
  3182. result[strLen] = '\0';
  3183. return result;
  3184. }
  3185. return VMA_NULL;
  3186. }
  3187. #endif // VMA_STATS_STRING_ENABLED
  3188. static void VmaFreeString(const VkAllocationCallbacks* allocs, char* str)
  3189. {
  3190. if (str != VMA_NULL)
  3191. {
  3192. const size_t len = strlen(str);
  3193. vma_delete_array(allocs, str, len + 1);
  3194. }
  3195. }
  3196. template<typename CmpLess, typename VectorT>
  3197. size_t VmaVectorInsertSorted(VectorT& vector, const typename VectorT::value_type& value)
  3198. {
  3199. const size_t indexToInsert = VmaBinaryFindFirstNotLess(
  3200. vector.data(),
  3201. vector.data() + vector.size(),
  3202. value,
  3203. CmpLess()) - vector.data();
  3204. VmaVectorInsert(vector, indexToInsert, value);
  3205. return indexToInsert;
  3206. }
  3207. template<typename CmpLess, typename VectorT>
  3208. bool VmaVectorRemoveSorted(VectorT& vector, const typename VectorT::value_type& value)
  3209. {
  3210. CmpLess comparator;
  3211. typename VectorT::iterator it = VmaBinaryFindFirstNotLess(
  3212. vector.begin(),
  3213. vector.end(),
  3214. value,
  3215. comparator);
  3216. if ((it != vector.end()) && !comparator(*it, value) && !comparator(value, *it))
  3217. {
  3218. size_t indexToRemove = it - vector.begin();
  3219. VmaVectorRemove(vector, indexToRemove);
  3220. return true;
  3221. }
  3222. return false;
  3223. }
  3224. #endif // _VMA_FUNCTIONS
  3225. #ifndef _VMA_STATISTICS_FUNCTIONS
  3226. static void VmaClearStatistics(VmaStatistics& outStats)
  3227. {
  3228. outStats.blockCount = 0;
  3229. outStats.allocationCount = 0;
  3230. outStats.blockBytes = 0;
  3231. outStats.allocationBytes = 0;
  3232. }
  3233. static void VmaAddStatistics(VmaStatistics& inoutStats, const VmaStatistics& src)
  3234. {
  3235. inoutStats.blockCount += src.blockCount;
  3236. inoutStats.allocationCount += src.allocationCount;
  3237. inoutStats.blockBytes += src.blockBytes;
  3238. inoutStats.allocationBytes += src.allocationBytes;
  3239. }
  3240. static void VmaClearDetailedStatistics(VmaDetailedStatistics& outStats)
  3241. {
  3242. VmaClearStatistics(outStats.statistics);
  3243. outStats.unusedRangeCount = 0;
  3244. outStats.allocationSizeMin = VK_WHOLE_SIZE;
  3245. outStats.allocationSizeMax = 0;
  3246. outStats.unusedRangeSizeMin = VK_WHOLE_SIZE;
  3247. outStats.unusedRangeSizeMax = 0;
  3248. }
  3249. static void VmaAddDetailedStatisticsAllocation(VmaDetailedStatistics& inoutStats, VkDeviceSize size)
  3250. {
  3251. inoutStats.statistics.allocationCount++;
  3252. inoutStats.statistics.allocationBytes += size;
  3253. inoutStats.allocationSizeMin = VMA_MIN(inoutStats.allocationSizeMin, size);
  3254. inoutStats.allocationSizeMax = VMA_MAX(inoutStats.allocationSizeMax, size);
  3255. }
  3256. static void VmaAddDetailedStatisticsUnusedRange(VmaDetailedStatistics& inoutStats, VkDeviceSize size)
  3257. {
  3258. inoutStats.unusedRangeCount++;
  3259. inoutStats.unusedRangeSizeMin = VMA_MIN(inoutStats.unusedRangeSizeMin, size);
  3260. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, size);
  3261. }
  3262. static void VmaAddDetailedStatistics(VmaDetailedStatistics& inoutStats, const VmaDetailedStatistics& src)
  3263. {
  3264. VmaAddStatistics(inoutStats.statistics, src.statistics);
  3265. inoutStats.unusedRangeCount += src.unusedRangeCount;
  3266. inoutStats.allocationSizeMin = VMA_MIN(inoutStats.allocationSizeMin, src.allocationSizeMin);
  3267. inoutStats.allocationSizeMax = VMA_MAX(inoutStats.allocationSizeMax, src.allocationSizeMax);
  3268. inoutStats.unusedRangeSizeMin = VMA_MIN(inoutStats.unusedRangeSizeMin, src.unusedRangeSizeMin);
  3269. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, src.unusedRangeSizeMax);
  3270. }
  3271. #endif // _VMA_STATISTICS_FUNCTIONS
  3272. #ifndef _VMA_MUTEX_LOCK
  3273. // Helper RAII class to lock a mutex in constructor and unlock it in destructor (at the end of scope).
  3274. struct VmaMutexLock
  3275. {
  3276. VMA_CLASS_NO_COPY(VmaMutexLock)
  3277. public:
  3278. VmaMutexLock(VMA_MUTEX& mutex, bool useMutex = true) :
  3279. m_pMutex(useMutex ? &mutex : VMA_NULL)
  3280. {
  3281. if (m_pMutex) { m_pMutex->Lock(); }
  3282. }
  3283. ~VmaMutexLock() { if (m_pMutex) { m_pMutex->Unlock(); } }
  3284. private:
  3285. VMA_MUTEX* m_pMutex;
  3286. };
  3287. // Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for reading.
  3288. struct VmaMutexLockRead
  3289. {
  3290. VMA_CLASS_NO_COPY(VmaMutexLockRead)
  3291. public:
  3292. VmaMutexLockRead(VMA_RW_MUTEX& mutex, bool useMutex) :
  3293. m_pMutex(useMutex ? &mutex : VMA_NULL)
  3294. {
  3295. if (m_pMutex) { m_pMutex->LockRead(); }
  3296. }
  3297. ~VmaMutexLockRead() { if (m_pMutex) { m_pMutex->UnlockRead(); } }
  3298. private:
  3299. VMA_RW_MUTEX* m_pMutex;
  3300. };
  3301. // Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for writing.
  3302. struct VmaMutexLockWrite
  3303. {
  3304. VMA_CLASS_NO_COPY(VmaMutexLockWrite)
  3305. public:
  3306. VmaMutexLockWrite(VMA_RW_MUTEX& mutex, bool useMutex)
  3307. : m_pMutex(useMutex ? &mutex : VMA_NULL)
  3308. {
  3309. if (m_pMutex) { m_pMutex->LockWrite(); }
  3310. }
  3311. ~VmaMutexLockWrite() { if (m_pMutex) { m_pMutex->UnlockWrite(); } }
  3312. private:
  3313. VMA_RW_MUTEX* m_pMutex;
  3314. };
  3315. #if VMA_DEBUG_GLOBAL_MUTEX
  3316. static VMA_MUTEX gDebugGlobalMutex;
  3317. #define VMA_DEBUG_GLOBAL_MUTEX_LOCK VmaMutexLock debugGlobalMutexLock(gDebugGlobalMutex, true);
  3318. #else
  3319. #define VMA_DEBUG_GLOBAL_MUTEX_LOCK
  3320. #endif
  3321. #endif // _VMA_MUTEX_LOCK
  3322. #ifndef _VMA_ATOMIC_TRANSACTIONAL_INCREMENT
  3323. // An object that increments given atomic but decrements it back in the destructor unless Commit() is called.
  3324. template<typename T>
  3325. struct AtomicTransactionalIncrement
  3326. {
  3327. public:
  3328. typedef std::atomic<T> AtomicT;
  3329. ~AtomicTransactionalIncrement()
  3330. {
  3331. if(m_Atomic)
  3332. --(*m_Atomic);
  3333. }
  3334. void Commit() { m_Atomic = nullptr; }
  3335. T Increment(AtomicT* atomic)
  3336. {
  3337. m_Atomic = atomic;
  3338. return m_Atomic->fetch_add(1);
  3339. }
  3340. private:
  3341. AtomicT* m_Atomic = nullptr;
  3342. };
  3343. #endif // _VMA_ATOMIC_TRANSACTIONAL_INCREMENT
  3344. #ifndef _VMA_STL_ALLOCATOR
  3345. // STL-compatible allocator.
  3346. template<typename T>
  3347. struct VmaStlAllocator
  3348. {
  3349. const VkAllocationCallbacks* const m_pCallbacks;
  3350. typedef T value_type;
  3351. VmaStlAllocator(const VkAllocationCallbacks* pCallbacks) : m_pCallbacks(pCallbacks) {}
  3352. template<typename U>
  3353. VmaStlAllocator(const VmaStlAllocator<U>& src) : m_pCallbacks(src.m_pCallbacks) {}
  3354. VmaStlAllocator(const VmaStlAllocator&) = default;
  3355. VmaStlAllocator& operator=(const VmaStlAllocator&) = delete;
  3356. T* allocate(size_t n) { return VmaAllocateArray<T>(m_pCallbacks, n); }
  3357. void deallocate(T* p, size_t n) { VmaFree(m_pCallbacks, p); }
  3358. template<typename U>
  3359. bool operator==(const VmaStlAllocator<U>& rhs) const
  3360. {
  3361. return m_pCallbacks == rhs.m_pCallbacks;
  3362. }
  3363. template<typename U>
  3364. bool operator!=(const VmaStlAllocator<U>& rhs) const
  3365. {
  3366. return m_pCallbacks != rhs.m_pCallbacks;
  3367. }
  3368. };
  3369. #endif // _VMA_STL_ALLOCATOR
  3370. #ifndef _VMA_VECTOR
  3371. /* Class with interface compatible with subset of std::vector.
  3372. T must be POD because constructors and destructors are not called and memcpy is
  3373. used for these objects. */
  3374. template<typename T, typename AllocatorT>
  3375. class VmaVector
  3376. {
  3377. public:
  3378. typedef T value_type;
  3379. typedef T* iterator;
  3380. typedef const T* const_iterator;
  3381. VmaVector(const AllocatorT& allocator);
  3382. VmaVector(size_t count, const AllocatorT& allocator);
  3383. // This version of the constructor is here for compatibility with pre-C++14 std::vector.
  3384. // value is unused.
  3385. VmaVector(size_t count, const T& value, const AllocatorT& allocator) : VmaVector(count, allocator) {}
  3386. VmaVector(const VmaVector<T, AllocatorT>& src);
  3387. VmaVector& operator=(const VmaVector& rhs);
  3388. ~VmaVector() { VmaFree(m_Allocator.m_pCallbacks, m_pArray); }
  3389. bool empty() const { return m_Count == 0; }
  3390. size_t size() const { return m_Count; }
  3391. T* data() { return m_pArray; }
  3392. T& front() { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[0]; }
  3393. T& back() { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[m_Count - 1]; }
  3394. const T* data() const { return m_pArray; }
  3395. const T& front() const { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[0]; }
  3396. const T& back() const { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[m_Count - 1]; }
  3397. iterator begin() { return m_pArray; }
  3398. iterator end() { return m_pArray + m_Count; }
  3399. const_iterator cbegin() const { return m_pArray; }
  3400. const_iterator cend() const { return m_pArray + m_Count; }
  3401. const_iterator begin() const { return cbegin(); }
  3402. const_iterator end() const { return cend(); }
  3403. void pop_front() { VMA_HEAVY_ASSERT(m_Count > 0); remove(0); }
  3404. void pop_back() { VMA_HEAVY_ASSERT(m_Count > 0); resize(size() - 1); }
  3405. void push_front(const T& src) { insert(0, src); }
  3406. void push_back(const T& src);
  3407. void reserve(size_t newCapacity, bool freeMemory = false);
  3408. void resize(size_t newCount);
  3409. void clear() { resize(0); }
  3410. void shrink_to_fit();
  3411. void insert(size_t index, const T& src);
  3412. void remove(size_t index);
  3413. T& operator[](size_t index) { VMA_HEAVY_ASSERT(index < m_Count); return m_pArray[index]; }
  3414. const T& operator[](size_t index) const { VMA_HEAVY_ASSERT(index < m_Count); return m_pArray[index]; }
  3415. private:
  3416. AllocatorT m_Allocator;
  3417. T* m_pArray;
  3418. size_t m_Count;
  3419. size_t m_Capacity;
  3420. };
  3421. #ifndef _VMA_VECTOR_FUNCTIONS
  3422. template<typename T, typename AllocatorT>
  3423. VmaVector<T, AllocatorT>::VmaVector(const AllocatorT& allocator)
  3424. : m_Allocator(allocator),
  3425. m_pArray(VMA_NULL),
  3426. m_Count(0),
  3427. m_Capacity(0) {}
  3428. template<typename T, typename AllocatorT>
  3429. VmaVector<T, AllocatorT>::VmaVector(size_t count, const AllocatorT& allocator)
  3430. : m_Allocator(allocator),
  3431. m_pArray(count ? (T*)VmaAllocateArray<T>(allocator.m_pCallbacks, count) : VMA_NULL),
  3432. m_Count(count),
  3433. m_Capacity(count) {}
  3434. template<typename T, typename AllocatorT>
  3435. VmaVector<T, AllocatorT>::VmaVector(const VmaVector& src)
  3436. : m_Allocator(src.m_Allocator),
  3437. m_pArray(src.m_Count ? (T*)VmaAllocateArray<T>(src.m_Allocator.m_pCallbacks, src.m_Count) : VMA_NULL),
  3438. m_Count(src.m_Count),
  3439. m_Capacity(src.m_Count)
  3440. {
  3441. if (m_Count != 0)
  3442. {
  3443. memcpy(m_pArray, src.m_pArray, m_Count * sizeof(T));
  3444. }
  3445. }
  3446. template<typename T, typename AllocatorT>
  3447. VmaVector<T, AllocatorT>& VmaVector<T, AllocatorT>::operator=(const VmaVector& rhs)
  3448. {
  3449. if (&rhs != this)
  3450. {
  3451. resize(rhs.m_Count);
  3452. if (m_Count != 0)
  3453. {
  3454. memcpy(m_pArray, rhs.m_pArray, m_Count * sizeof(T));
  3455. }
  3456. }
  3457. return *this;
  3458. }
  3459. template<typename T, typename AllocatorT>
  3460. void VmaVector<T, AllocatorT>::push_back(const T& src)
  3461. {
  3462. const size_t newIndex = size();
  3463. resize(newIndex + 1);
  3464. m_pArray[newIndex] = src;
  3465. }
  3466. template<typename T, typename AllocatorT>
  3467. void VmaVector<T, AllocatorT>::reserve(size_t newCapacity, bool freeMemory)
  3468. {
  3469. newCapacity = VMA_MAX(newCapacity, m_Count);
  3470. if ((newCapacity < m_Capacity) && !freeMemory)
  3471. {
  3472. newCapacity = m_Capacity;
  3473. }
  3474. if (newCapacity != m_Capacity)
  3475. {
  3476. T* const newArray = newCapacity ? VmaAllocateArray<T>(m_Allocator, newCapacity) : VMA_NULL;
  3477. if (m_Count != 0)
  3478. {
  3479. memcpy(newArray, m_pArray, m_Count * sizeof(T));
  3480. }
  3481. VmaFree(m_Allocator.m_pCallbacks, m_pArray);
  3482. m_Capacity = newCapacity;
  3483. m_pArray = newArray;
  3484. }
  3485. }
  3486. template<typename T, typename AllocatorT>
  3487. void VmaVector<T, AllocatorT>::resize(size_t newCount)
  3488. {
  3489. size_t newCapacity = m_Capacity;
  3490. if (newCount > m_Capacity)
  3491. {
  3492. newCapacity = VMA_MAX(newCount, VMA_MAX(m_Capacity * 3 / 2, (size_t)8));
  3493. }
  3494. if (newCapacity != m_Capacity)
  3495. {
  3496. T* const newArray = newCapacity ? VmaAllocateArray<T>(m_Allocator.m_pCallbacks, newCapacity) : VMA_NULL;
  3497. const size_t elementsToCopy = VMA_MIN(m_Count, newCount);
  3498. if (elementsToCopy != 0)
  3499. {
  3500. memcpy(newArray, m_pArray, elementsToCopy * sizeof(T));
  3501. }
  3502. VmaFree(m_Allocator.m_pCallbacks, m_pArray);
  3503. m_Capacity = newCapacity;
  3504. m_pArray = newArray;
  3505. }
  3506. m_Count = newCount;
  3507. }
  3508. template<typename T, typename AllocatorT>
  3509. void VmaVector<T, AllocatorT>::shrink_to_fit()
  3510. {
  3511. if (m_Capacity > m_Count)
  3512. {
  3513. T* newArray = VMA_NULL;
  3514. if (m_Count > 0)
  3515. {
  3516. newArray = VmaAllocateArray<T>(m_Allocator.m_pCallbacks, m_Count);
  3517. memcpy(newArray, m_pArray, m_Count * sizeof(T));
  3518. }
  3519. VmaFree(m_Allocator.m_pCallbacks, m_pArray);
  3520. m_Capacity = m_Count;
  3521. m_pArray = newArray;
  3522. }
  3523. }
  3524. template<typename T, typename AllocatorT>
  3525. void VmaVector<T, AllocatorT>::insert(size_t index, const T& src)
  3526. {
  3527. VMA_HEAVY_ASSERT(index <= m_Count);
  3528. const size_t oldCount = size();
  3529. resize(oldCount + 1);
  3530. if (index < oldCount)
  3531. {
  3532. memmove(m_pArray + (index + 1), m_pArray + index, (oldCount - index) * sizeof(T));
  3533. }
  3534. m_pArray[index] = src;
  3535. }
  3536. template<typename T, typename AllocatorT>
  3537. void VmaVector<T, AllocatorT>::remove(size_t index)
  3538. {
  3539. VMA_HEAVY_ASSERT(index < m_Count);
  3540. const size_t oldCount = size();
  3541. if (index < oldCount - 1)
  3542. {
  3543. memmove(m_pArray + index, m_pArray + (index + 1), (oldCount - index - 1) * sizeof(T));
  3544. }
  3545. resize(oldCount - 1);
  3546. }
  3547. #endif // _VMA_VECTOR_FUNCTIONS
  3548. template<typename T, typename allocatorT>
  3549. static void VmaVectorInsert(VmaVector<T, allocatorT>& vec, size_t index, const T& item)
  3550. {
  3551. vec.insert(index, item);
  3552. }
  3553. template<typename T, typename allocatorT>
  3554. static void VmaVectorRemove(VmaVector<T, allocatorT>& vec, size_t index)
  3555. {
  3556. vec.remove(index);
  3557. }
  3558. #endif // _VMA_VECTOR
  3559. #ifndef _VMA_SMALL_VECTOR
  3560. /*
  3561. This is a vector (a variable-sized array), optimized for the case when the array is small.
  3562. It contains some number of elements in-place, which allows it to avoid heap allocation
  3563. when the actual number of elements is below that threshold. This allows normal "small"
  3564. cases to be fast without losing generality for large inputs.
  3565. */
  3566. template<typename T, typename AllocatorT, size_t N>
  3567. class VmaSmallVector
  3568. {
  3569. public:
  3570. typedef T value_type;
  3571. typedef T* iterator;
  3572. VmaSmallVector(const AllocatorT& allocator);
  3573. VmaSmallVector(size_t count, const AllocatorT& allocator);
  3574. template<typename SrcT, typename SrcAllocatorT, size_t SrcN>
  3575. VmaSmallVector(const VmaSmallVector<SrcT, SrcAllocatorT, SrcN>&) = delete;
  3576. template<typename SrcT, typename SrcAllocatorT, size_t SrcN>
  3577. VmaSmallVector<T, AllocatorT, N>& operator=(const VmaSmallVector<SrcT, SrcAllocatorT, SrcN>&) = delete;
  3578. ~VmaSmallVector() = default;
  3579. bool empty() const { return m_Count == 0; }
  3580. size_t size() const { return m_Count; }
  3581. T* data() { return m_Count > N ? m_DynamicArray.data() : m_StaticArray; }
  3582. T& front() { VMA_HEAVY_ASSERT(m_Count > 0); return data()[0]; }
  3583. T& back() { VMA_HEAVY_ASSERT(m_Count > 0); return data()[m_Count - 1]; }
  3584. const T* data() const { return m_Count > N ? m_DynamicArray.data() : m_StaticArray; }
  3585. const T& front() const { VMA_HEAVY_ASSERT(m_Count > 0); return data()[0]; }
  3586. const T& back() const { VMA_HEAVY_ASSERT(m_Count > 0); return data()[m_Count - 1]; }
  3587. iterator begin() { return data(); }
  3588. iterator end() { return data() + m_Count; }
  3589. void pop_front() { VMA_HEAVY_ASSERT(m_Count > 0); remove(0); }
  3590. void pop_back() { VMA_HEAVY_ASSERT(m_Count > 0); resize(size() - 1); }
  3591. void push_front(const T& src) { insert(0, src); }
  3592. void push_back(const T& src);
  3593. void resize(size_t newCount, bool freeMemory = false);
  3594. void clear(bool freeMemory = false);
  3595. void insert(size_t index, const T& src);
  3596. void remove(size_t index);
  3597. T& operator[](size_t index) { VMA_HEAVY_ASSERT(index < m_Count); return data()[index]; }
  3598. const T& operator[](size_t index) const { VMA_HEAVY_ASSERT(index < m_Count); return data()[index]; }
  3599. private:
  3600. size_t m_Count;
  3601. T m_StaticArray[N]; // Used when m_Size <= N
  3602. VmaVector<T, AllocatorT> m_DynamicArray; // Used when m_Size > N
  3603. };
  3604. #ifndef _VMA_SMALL_VECTOR_FUNCTIONS
  3605. template<typename T, typename AllocatorT, size_t N>
  3606. VmaSmallVector<T, AllocatorT, N>::VmaSmallVector(const AllocatorT& allocator)
  3607. : m_Count(0),
  3608. m_DynamicArray(allocator) {}
  3609. template<typename T, typename AllocatorT, size_t N>
  3610. VmaSmallVector<T, AllocatorT, N>::VmaSmallVector(size_t count, const AllocatorT& allocator)
  3611. : m_Count(count),
  3612. m_DynamicArray(count > N ? count : 0, allocator) {}
  3613. template<typename T, typename AllocatorT, size_t N>
  3614. void VmaSmallVector<T, AllocatorT, N>::push_back(const T& src)
  3615. {
  3616. const size_t newIndex = size();
  3617. resize(newIndex + 1);
  3618. data()[newIndex] = src;
  3619. }
  3620. template<typename T, typename AllocatorT, size_t N>
  3621. void VmaSmallVector<T, AllocatorT, N>::resize(size_t newCount, bool freeMemory)
  3622. {
  3623. if (newCount > N && m_Count > N)
  3624. {
  3625. // Any direction, staying in m_DynamicArray
  3626. m_DynamicArray.resize(newCount);
  3627. if (freeMemory)
  3628. {
  3629. m_DynamicArray.shrink_to_fit();
  3630. }
  3631. }
  3632. else if (newCount > N && m_Count <= N)
  3633. {
  3634. // Growing, moving from m_StaticArray to m_DynamicArray
  3635. m_DynamicArray.resize(newCount);
  3636. if (m_Count > 0)
  3637. {
  3638. memcpy(m_DynamicArray.data(), m_StaticArray, m_Count * sizeof(T));
  3639. }
  3640. }
  3641. else if (newCount <= N && m_Count > N)
  3642. {
  3643. // Shrinking, moving from m_DynamicArray to m_StaticArray
  3644. if (newCount > 0)
  3645. {
  3646. memcpy(m_StaticArray, m_DynamicArray.data(), newCount * sizeof(T));
  3647. }
  3648. m_DynamicArray.resize(0);
  3649. if (freeMemory)
  3650. {
  3651. m_DynamicArray.shrink_to_fit();
  3652. }
  3653. }
  3654. else
  3655. {
  3656. // Any direction, staying in m_StaticArray - nothing to do here
  3657. }
  3658. m_Count = newCount;
  3659. }
  3660. template<typename T, typename AllocatorT, size_t N>
  3661. void VmaSmallVector<T, AllocatorT, N>::clear(bool freeMemory)
  3662. {
  3663. m_DynamicArray.clear();
  3664. if (freeMemory)
  3665. {
  3666. m_DynamicArray.shrink_to_fit();
  3667. }
  3668. m_Count = 0;
  3669. }
  3670. template<typename T, typename AllocatorT, size_t N>
  3671. void VmaSmallVector<T, AllocatorT, N>::insert(size_t index, const T& src)
  3672. {
  3673. VMA_HEAVY_ASSERT(index <= m_Count);
  3674. const size_t oldCount = size();
  3675. resize(oldCount + 1);
  3676. T* const dataPtr = data();
  3677. if (index < oldCount)
  3678. {
  3679. // I know, this could be more optimal for case where memmove can be memcpy directly from m_StaticArray to m_DynamicArray.
  3680. memmove(dataPtr + (index + 1), dataPtr + index, (oldCount - index) * sizeof(T));
  3681. }
  3682. dataPtr[index] = src;
  3683. }
  3684. template<typename T, typename AllocatorT, size_t N>
  3685. void VmaSmallVector<T, AllocatorT, N>::remove(size_t index)
  3686. {
  3687. VMA_HEAVY_ASSERT(index < m_Count);
  3688. const size_t oldCount = size();
  3689. if (index < oldCount - 1)
  3690. {
  3691. // I know, this could be more optimal for case where memmove can be memcpy directly from m_DynamicArray to m_StaticArray.
  3692. T* const dataPtr = data();
  3693. memmove(dataPtr + index, dataPtr + (index + 1), (oldCount - index - 1) * sizeof(T));
  3694. }
  3695. resize(oldCount - 1);
  3696. }
  3697. #endif // _VMA_SMALL_VECTOR_FUNCTIONS
  3698. #endif // _VMA_SMALL_VECTOR
  3699. #ifndef _VMA_POOL_ALLOCATOR
  3700. /*
  3701. Allocator for objects of type T using a list of arrays (pools) to speed up
  3702. allocation. Number of elements that can be allocated is not bounded because
  3703. allocator can create multiple blocks.
  3704. */
  3705. template<typename T>
  3706. class VmaPoolAllocator
  3707. {
  3708. VMA_CLASS_NO_COPY(VmaPoolAllocator)
  3709. public:
  3710. VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, uint32_t firstBlockCapacity);
  3711. ~VmaPoolAllocator();
  3712. template<typename... Types> T* Alloc(Types&&... args);
  3713. void Free(T* ptr);
  3714. private:
  3715. union Item
  3716. {
  3717. uint32_t NextFreeIndex;
  3718. alignas(T) char Value[sizeof(T)];
  3719. };
  3720. struct ItemBlock
  3721. {
  3722. Item* pItems;
  3723. uint32_t Capacity;
  3724. uint32_t FirstFreeIndex;
  3725. };
  3726. const VkAllocationCallbacks* m_pAllocationCallbacks;
  3727. const uint32_t m_FirstBlockCapacity;
  3728. VmaVector<ItemBlock, VmaStlAllocator<ItemBlock>> m_ItemBlocks;
  3729. ItemBlock& CreateNewBlock();
  3730. };
  3731. #ifndef _VMA_POOL_ALLOCATOR_FUNCTIONS
  3732. template<typename T>
  3733. VmaPoolAllocator<T>::VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, uint32_t firstBlockCapacity)
  3734. : m_pAllocationCallbacks(pAllocationCallbacks),
  3735. m_FirstBlockCapacity(firstBlockCapacity),
  3736. m_ItemBlocks(VmaStlAllocator<ItemBlock>(pAllocationCallbacks))
  3737. {
  3738. VMA_ASSERT(m_FirstBlockCapacity > 1);
  3739. }
  3740. template<typename T>
  3741. VmaPoolAllocator<T>::~VmaPoolAllocator()
  3742. {
  3743. for (size_t i = m_ItemBlocks.size(); i--;)
  3744. vma_delete_array(m_pAllocationCallbacks, m_ItemBlocks[i].pItems, m_ItemBlocks[i].Capacity);
  3745. m_ItemBlocks.clear();
  3746. }
  3747. template<typename T>
  3748. template<typename... Types> T* VmaPoolAllocator<T>::Alloc(Types&&... args)
  3749. {
  3750. for (size_t i = m_ItemBlocks.size(); i--; )
  3751. {
  3752. ItemBlock& block = m_ItemBlocks[i];
  3753. // This block has some free items: Use first one.
  3754. if (block.FirstFreeIndex != UINT32_MAX)
  3755. {
  3756. Item* const pItem = &block.pItems[block.FirstFreeIndex];
  3757. block.FirstFreeIndex = pItem->NextFreeIndex;
  3758. T* result = (T*)&pItem->Value;
  3759. new(result)T(std::forward<Types>(args)...); // Explicit constructor call.
  3760. return result;
  3761. }
  3762. }
  3763. // No block has free item: Create new one and use it.
  3764. ItemBlock& newBlock = CreateNewBlock();
  3765. Item* const pItem = &newBlock.pItems[0];
  3766. newBlock.FirstFreeIndex = pItem->NextFreeIndex;
  3767. T* result = (T*)&pItem->Value;
  3768. new(result) T(std::forward<Types>(args)...); // Explicit constructor call.
  3769. return result;
  3770. }
  3771. template<typename T>
  3772. void VmaPoolAllocator<T>::Free(T* ptr)
  3773. {
  3774. // Search all memory blocks to find ptr.
  3775. for (size_t i = m_ItemBlocks.size(); i--; )
  3776. {
  3777. ItemBlock& block = m_ItemBlocks[i];
  3778. // Casting to union.
  3779. Item* pItemPtr;
  3780. memcpy(&pItemPtr, &ptr, sizeof(pItemPtr));
  3781. // Check if pItemPtr is in address range of this block.
  3782. if ((pItemPtr >= block.pItems) && (pItemPtr < block.pItems + block.Capacity))
  3783. {
  3784. ptr->~T(); // Explicit destructor call.
  3785. const uint32_t index = static_cast<uint32_t>(pItemPtr - block.pItems);
  3786. pItemPtr->NextFreeIndex = block.FirstFreeIndex;
  3787. block.FirstFreeIndex = index;
  3788. return;
  3789. }
  3790. }
  3791. VMA_ASSERT(0 && "Pointer doesn't belong to this memory pool.");
  3792. }
  3793. template<typename T>
  3794. typename VmaPoolAllocator<T>::ItemBlock& VmaPoolAllocator<T>::CreateNewBlock()
  3795. {
  3796. const uint32_t newBlockCapacity = m_ItemBlocks.empty() ?
  3797. m_FirstBlockCapacity : m_ItemBlocks.back().Capacity * 3 / 2;
  3798. const ItemBlock newBlock =
  3799. {
  3800. vma_new_array(m_pAllocationCallbacks, Item, newBlockCapacity),
  3801. newBlockCapacity,
  3802. 0
  3803. };
  3804. m_ItemBlocks.push_back(newBlock);
  3805. // Setup singly-linked list of all free items in this block.
  3806. for (uint32_t i = 0; i < newBlockCapacity - 1; ++i)
  3807. newBlock.pItems[i].NextFreeIndex = i + 1;
  3808. newBlock.pItems[newBlockCapacity - 1].NextFreeIndex = UINT32_MAX;
  3809. return m_ItemBlocks.back();
  3810. }
  3811. #endif // _VMA_POOL_ALLOCATOR_FUNCTIONS
  3812. #endif // _VMA_POOL_ALLOCATOR
  3813. #ifndef _VMA_RAW_LIST
  3814. template<typename T>
  3815. struct VmaListItem
  3816. {
  3817. VmaListItem* pPrev;
  3818. VmaListItem* pNext;
  3819. T Value;
  3820. };
  3821. // Doubly linked list.
  3822. template<typename T>
  3823. class VmaRawList
  3824. {
  3825. VMA_CLASS_NO_COPY(VmaRawList)
  3826. public:
  3827. typedef VmaListItem<T> ItemType;
  3828. VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks);
  3829. // Intentionally not calling Clear, because that would be unnecessary
  3830. // computations to return all items to m_ItemAllocator as free.
  3831. ~VmaRawList() = default;
  3832. size_t GetCount() const { return m_Count; }
  3833. bool IsEmpty() const { return m_Count == 0; }
  3834. ItemType* Front() { return m_pFront; }
  3835. ItemType* Back() { return m_pBack; }
  3836. const ItemType* Front() const { return m_pFront; }
  3837. const ItemType* Back() const { return m_pBack; }
  3838. ItemType* PushFront();
  3839. ItemType* PushBack();
  3840. ItemType* PushFront(const T& value);
  3841. ItemType* PushBack(const T& value);
  3842. void PopFront();
  3843. void PopBack();
  3844. // Item can be null - it means PushBack.
  3845. ItemType* InsertBefore(ItemType* pItem);
  3846. // Item can be null - it means PushFront.
  3847. ItemType* InsertAfter(ItemType* pItem);
  3848. ItemType* InsertBefore(ItemType* pItem, const T& value);
  3849. ItemType* InsertAfter(ItemType* pItem, const T& value);
  3850. void Clear();
  3851. void Remove(ItemType* pItem);
  3852. private:
  3853. const VkAllocationCallbacks* const m_pAllocationCallbacks;
  3854. VmaPoolAllocator<ItemType> m_ItemAllocator;
  3855. ItemType* m_pFront;
  3856. ItemType* m_pBack;
  3857. size_t m_Count;
  3858. };
  3859. #ifndef _VMA_RAW_LIST_FUNCTIONS
  3860. template<typename T>
  3861. VmaRawList<T>::VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks)
  3862. : m_pAllocationCallbacks(pAllocationCallbacks),
  3863. m_ItemAllocator(pAllocationCallbacks, 128),
  3864. m_pFront(VMA_NULL),
  3865. m_pBack(VMA_NULL),
  3866. m_Count(0) {}
  3867. template<typename T>
  3868. VmaListItem<T>* VmaRawList<T>::PushFront()
  3869. {
  3870. ItemType* const pNewItem = m_ItemAllocator.Alloc();
  3871. pNewItem->pPrev = VMA_NULL;
  3872. if (IsEmpty())
  3873. {
  3874. pNewItem->pNext = VMA_NULL;
  3875. m_pFront = pNewItem;
  3876. m_pBack = pNewItem;
  3877. m_Count = 1;
  3878. }
  3879. else
  3880. {
  3881. pNewItem->pNext = m_pFront;
  3882. m_pFront->pPrev = pNewItem;
  3883. m_pFront = pNewItem;
  3884. ++m_Count;
  3885. }
  3886. return pNewItem;
  3887. }
  3888. template<typename T>
  3889. VmaListItem<T>* VmaRawList<T>::PushBack()
  3890. {
  3891. ItemType* const pNewItem = m_ItemAllocator.Alloc();
  3892. pNewItem->pNext = VMA_NULL;
  3893. if(IsEmpty())
  3894. {
  3895. pNewItem->pPrev = VMA_NULL;
  3896. m_pFront = pNewItem;
  3897. m_pBack = pNewItem;
  3898. m_Count = 1;
  3899. }
  3900. else
  3901. {
  3902. pNewItem->pPrev = m_pBack;
  3903. m_pBack->pNext = pNewItem;
  3904. m_pBack = pNewItem;
  3905. ++m_Count;
  3906. }
  3907. return pNewItem;
  3908. }
  3909. template<typename T>
  3910. VmaListItem<T>* VmaRawList<T>::PushFront(const T& value)
  3911. {
  3912. ItemType* const pNewItem = PushFront();
  3913. pNewItem->Value = value;
  3914. return pNewItem;
  3915. }
  3916. template<typename T>
  3917. VmaListItem<T>* VmaRawList<T>::PushBack(const T& value)
  3918. {
  3919. ItemType* const pNewItem = PushBack();
  3920. pNewItem->Value = value;
  3921. return pNewItem;
  3922. }
  3923. template<typename T>
  3924. void VmaRawList<T>::PopFront()
  3925. {
  3926. VMA_HEAVY_ASSERT(m_Count > 0);
  3927. ItemType* const pFrontItem = m_pFront;
  3928. ItemType* const pNextItem = pFrontItem->pNext;
  3929. if (pNextItem != VMA_NULL)
  3930. {
  3931. pNextItem->pPrev = VMA_NULL;
  3932. }
  3933. m_pFront = pNextItem;
  3934. m_ItemAllocator.Free(pFrontItem);
  3935. --m_Count;
  3936. }
  3937. template<typename T>
  3938. void VmaRawList<T>::PopBack()
  3939. {
  3940. VMA_HEAVY_ASSERT(m_Count > 0);
  3941. ItemType* const pBackItem = m_pBack;
  3942. ItemType* const pPrevItem = pBackItem->pPrev;
  3943. if(pPrevItem != VMA_NULL)
  3944. {
  3945. pPrevItem->pNext = VMA_NULL;
  3946. }
  3947. m_pBack = pPrevItem;
  3948. m_ItemAllocator.Free(pBackItem);
  3949. --m_Count;
  3950. }
  3951. template<typename T>
  3952. void VmaRawList<T>::Clear()
  3953. {
  3954. if (IsEmpty() == false)
  3955. {
  3956. ItemType* pItem = m_pBack;
  3957. while (pItem != VMA_NULL)
  3958. {
  3959. ItemType* const pPrevItem = pItem->pPrev;
  3960. m_ItemAllocator.Free(pItem);
  3961. pItem = pPrevItem;
  3962. }
  3963. m_pFront = VMA_NULL;
  3964. m_pBack = VMA_NULL;
  3965. m_Count = 0;
  3966. }
  3967. }
  3968. template<typename T>
  3969. void VmaRawList<T>::Remove(ItemType* pItem)
  3970. {
  3971. VMA_HEAVY_ASSERT(pItem != VMA_NULL);
  3972. VMA_HEAVY_ASSERT(m_Count > 0);
  3973. if(pItem->pPrev != VMA_NULL)
  3974. {
  3975. pItem->pPrev->pNext = pItem->pNext;
  3976. }
  3977. else
  3978. {
  3979. VMA_HEAVY_ASSERT(m_pFront == pItem);
  3980. m_pFront = pItem->pNext;
  3981. }
  3982. if(pItem->pNext != VMA_NULL)
  3983. {
  3984. pItem->pNext->pPrev = pItem->pPrev;
  3985. }
  3986. else
  3987. {
  3988. VMA_HEAVY_ASSERT(m_pBack == pItem);
  3989. m_pBack = pItem->pPrev;
  3990. }
  3991. m_ItemAllocator.Free(pItem);
  3992. --m_Count;
  3993. }
  3994. template<typename T>
  3995. VmaListItem<T>* VmaRawList<T>::InsertBefore(ItemType* pItem)
  3996. {
  3997. if(pItem != VMA_NULL)
  3998. {
  3999. ItemType* const prevItem = pItem->pPrev;
  4000. ItemType* const newItem = m_ItemAllocator.Alloc();
  4001. newItem->pPrev = prevItem;
  4002. newItem->pNext = pItem;
  4003. pItem->pPrev = newItem;
  4004. if(prevItem != VMA_NULL)
  4005. {
  4006. prevItem->pNext = newItem;
  4007. }
  4008. else
  4009. {
  4010. VMA_HEAVY_ASSERT(m_pFront == pItem);
  4011. m_pFront = newItem;
  4012. }
  4013. ++m_Count;
  4014. return newItem;
  4015. }
  4016. else
  4017. return PushBack();
  4018. }
  4019. template<typename T>
  4020. VmaListItem<T>* VmaRawList<T>::InsertAfter(ItemType* pItem)
  4021. {
  4022. if(pItem != VMA_NULL)
  4023. {
  4024. ItemType* const nextItem = pItem->pNext;
  4025. ItemType* const newItem = m_ItemAllocator.Alloc();
  4026. newItem->pNext = nextItem;
  4027. newItem->pPrev = pItem;
  4028. pItem->pNext = newItem;
  4029. if(nextItem != VMA_NULL)
  4030. {
  4031. nextItem->pPrev = newItem;
  4032. }
  4033. else
  4034. {
  4035. VMA_HEAVY_ASSERT(m_pBack == pItem);
  4036. m_pBack = newItem;
  4037. }
  4038. ++m_Count;
  4039. return newItem;
  4040. }
  4041. else
  4042. return PushFront();
  4043. }
  4044. template<typename T>
  4045. VmaListItem<T>* VmaRawList<T>::InsertBefore(ItemType* pItem, const T& value)
  4046. {
  4047. ItemType* const newItem = InsertBefore(pItem);
  4048. newItem->Value = value;
  4049. return newItem;
  4050. }
  4051. template<typename T>
  4052. VmaListItem<T>* VmaRawList<T>::InsertAfter(ItemType* pItem, const T& value)
  4053. {
  4054. ItemType* const newItem = InsertAfter(pItem);
  4055. newItem->Value = value;
  4056. return newItem;
  4057. }
  4058. #endif // _VMA_RAW_LIST_FUNCTIONS
  4059. #endif // _VMA_RAW_LIST
  4060. #ifndef _VMA_LIST
  4061. template<typename T, typename AllocatorT>
  4062. class VmaList
  4063. {
  4064. VMA_CLASS_NO_COPY(VmaList)
  4065. public:
  4066. class reverse_iterator;
  4067. class const_iterator;
  4068. class const_reverse_iterator;
  4069. class iterator
  4070. {
  4071. friend class const_iterator;
  4072. friend class VmaList<T, AllocatorT>;
  4073. public:
  4074. iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {}
  4075. iterator(const reverse_iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {}
  4076. T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; }
  4077. T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; }
  4078. bool operator==(const iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; }
  4079. bool operator!=(const iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; }
  4080. iterator operator++(int) { iterator result = *this; ++*this; return result; }
  4081. iterator operator--(int) { iterator result = *this; --*this; return result; }
  4082. iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pNext; return *this; }
  4083. iterator& operator--();
  4084. private:
  4085. VmaRawList<T>* m_pList;
  4086. VmaListItem<T>* m_pItem;
  4087. iterator(VmaRawList<T>* pList, VmaListItem<T>* pItem) : m_pList(pList), m_pItem(pItem) {}
  4088. };
  4089. class reverse_iterator
  4090. {
  4091. friend class const_reverse_iterator;
  4092. friend class VmaList<T, AllocatorT>;
  4093. public:
  4094. reverse_iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {}
  4095. reverse_iterator(const iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {}
  4096. T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; }
  4097. T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; }
  4098. bool operator==(const reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; }
  4099. bool operator!=(const reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; }
  4100. reverse_iterator operator++(int) { reverse_iterator result = *this; ++* this; return result; }
  4101. reverse_iterator operator--(int) { reverse_iterator result = *this; --* this; return result; }
  4102. reverse_iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pPrev; return *this; }
  4103. reverse_iterator& operator--();
  4104. private:
  4105. VmaRawList<T>* m_pList;
  4106. VmaListItem<T>* m_pItem;
  4107. reverse_iterator(VmaRawList<T>* pList, VmaListItem<T>* pItem) : m_pList(pList), m_pItem(pItem) {}
  4108. };
  4109. class const_iterator
  4110. {
  4111. friend class VmaList<T, AllocatorT>;
  4112. public:
  4113. const_iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {}
  4114. const_iterator(const iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {}
  4115. const_iterator(const reverse_iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {}
  4116. iterator drop_const() { return { const_cast<VmaRawList<T>*>(m_pList), const_cast<VmaListItem<T>*>(m_pItem) }; }
  4117. const T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; }
  4118. const T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; }
  4119. bool operator==(const const_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; }
  4120. bool operator!=(const const_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; }
  4121. const_iterator operator++(int) { const_iterator result = *this; ++* this; return result; }
  4122. const_iterator operator--(int) { const_iterator result = *this; --* this; return result; }
  4123. const_iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pNext; return *this; }
  4124. const_iterator& operator--();
  4125. private:
  4126. const VmaRawList<T>* m_pList;
  4127. const VmaListItem<T>* m_pItem;
  4128. const_iterator(const VmaRawList<T>* pList, const VmaListItem<T>* pItem) : m_pList(pList), m_pItem(pItem) {}
  4129. };
  4130. class const_reverse_iterator
  4131. {
  4132. friend class VmaList<T, AllocatorT>;
  4133. public:
  4134. const_reverse_iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {}
  4135. const_reverse_iterator(const reverse_iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {}
  4136. const_reverse_iterator(const iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {}
  4137. reverse_iterator drop_const() { return { const_cast<VmaRawList<T>*>(m_pList), const_cast<VmaListItem<T>*>(m_pItem) }; }
  4138. const T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; }
  4139. const T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; }
  4140. bool operator==(const const_reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; }
  4141. bool operator!=(const const_reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; }
  4142. const_reverse_iterator operator++(int) { const_reverse_iterator result = *this; ++* this; return result; }
  4143. const_reverse_iterator operator--(int) { const_reverse_iterator result = *this; --* this; return result; }
  4144. const_reverse_iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pPrev; return *this; }
  4145. const_reverse_iterator& operator--();
  4146. private:
  4147. const VmaRawList<T>* m_pList;
  4148. const VmaListItem<T>* m_pItem;
  4149. const_reverse_iterator(const VmaRawList<T>* pList, const VmaListItem<T>* pItem) : m_pList(pList), m_pItem(pItem) {}
  4150. };
  4151. VmaList(const AllocatorT& allocator) : m_RawList(allocator.m_pCallbacks) {}
  4152. bool empty() const { return m_RawList.IsEmpty(); }
  4153. size_t size() const { return m_RawList.GetCount(); }
  4154. iterator begin() { return iterator(&m_RawList, m_RawList.Front()); }
  4155. iterator end() { return iterator(&m_RawList, VMA_NULL); }
  4156. const_iterator cbegin() const { return const_iterator(&m_RawList, m_RawList.Front()); }
  4157. const_iterator cend() const { return const_iterator(&m_RawList, VMA_NULL); }
  4158. const_iterator begin() const { return cbegin(); }
  4159. const_iterator end() const { return cend(); }
  4160. reverse_iterator rbegin() { return reverse_iterator(&m_RawList, m_RawList.Back()); }
  4161. reverse_iterator rend() { return reverse_iterator(&m_RawList, VMA_NULL); }
  4162. const_reverse_iterator crbegin() const { return const_reverse_iterator(&m_RawList, m_RawList.Back()); }
  4163. const_reverse_iterator crend() const { return const_reverse_iterator(&m_RawList, VMA_NULL); }
  4164. const_reverse_iterator rbegin() const { return crbegin(); }
  4165. const_reverse_iterator rend() const { return crend(); }
  4166. void push_back(const T& value) { m_RawList.PushBack(value); }
  4167. iterator insert(iterator it, const T& value) { return iterator(&m_RawList, m_RawList.InsertBefore(it.m_pItem, value)); }
  4168. void clear() { m_RawList.Clear(); }
  4169. void erase(iterator it) { m_RawList.Remove(it.m_pItem); }
  4170. private:
  4171. VmaRawList<T> m_RawList;
  4172. };
  4173. #ifndef _VMA_LIST_FUNCTIONS
  4174. template<typename T, typename AllocatorT>
  4175. typename VmaList<T, AllocatorT>::iterator& VmaList<T, AllocatorT>::iterator::operator--()
  4176. {
  4177. if (m_pItem != VMA_NULL)
  4178. {
  4179. m_pItem = m_pItem->pPrev;
  4180. }
  4181. else
  4182. {
  4183. VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
  4184. m_pItem = m_pList->Back();
  4185. }
  4186. return *this;
  4187. }
  4188. template<typename T, typename AllocatorT>
  4189. typename VmaList<T, AllocatorT>::reverse_iterator& VmaList<T, AllocatorT>::reverse_iterator::operator--()
  4190. {
  4191. if (m_pItem != VMA_NULL)
  4192. {
  4193. m_pItem = m_pItem->pNext;
  4194. }
  4195. else
  4196. {
  4197. VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
  4198. m_pItem = m_pList->Front();
  4199. }
  4200. return *this;
  4201. }
  4202. template<typename T, typename AllocatorT>
  4203. typename VmaList<T, AllocatorT>::const_iterator& VmaList<T, AllocatorT>::const_iterator::operator--()
  4204. {
  4205. if (m_pItem != VMA_NULL)
  4206. {
  4207. m_pItem = m_pItem->pPrev;
  4208. }
  4209. else
  4210. {
  4211. VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
  4212. m_pItem = m_pList->Back();
  4213. }
  4214. return *this;
  4215. }
  4216. template<typename T, typename AllocatorT>
  4217. typename VmaList<T, AllocatorT>::const_reverse_iterator& VmaList<T, AllocatorT>::const_reverse_iterator::operator--()
  4218. {
  4219. if (m_pItem != VMA_NULL)
  4220. {
  4221. m_pItem = m_pItem->pNext;
  4222. }
  4223. else
  4224. {
  4225. VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
  4226. m_pItem = m_pList->Back();
  4227. }
  4228. return *this;
  4229. }
  4230. #endif // _VMA_LIST_FUNCTIONS
  4231. #endif // _VMA_LIST
  4232. #ifndef _VMA_INTRUSIVE_LINKED_LIST
  4233. /*
  4234. Expected interface of ItemTypeTraits:
  4235. struct MyItemTypeTraits
  4236. {
  4237. typedef MyItem ItemType;
  4238. static ItemType* GetPrev(const ItemType* item) { return item->myPrevPtr; }
  4239. static ItemType* GetNext(const ItemType* item) { return item->myNextPtr; }
  4240. static ItemType*& AccessPrev(ItemType* item) { return item->myPrevPtr; }
  4241. static ItemType*& AccessNext(ItemType* item) { return item->myNextPtr; }
  4242. };
  4243. */
  4244. template<typename ItemTypeTraits>
  4245. class VmaIntrusiveLinkedList
  4246. {
  4247. public:
  4248. typedef typename ItemTypeTraits::ItemType ItemType;
  4249. static ItemType* GetPrev(const ItemType* item) { return ItemTypeTraits::GetPrev(item); }
  4250. static ItemType* GetNext(const ItemType* item) { return ItemTypeTraits::GetNext(item); }
  4251. // Movable, not copyable.
  4252. VmaIntrusiveLinkedList() = default;
  4253. VmaIntrusiveLinkedList(VmaIntrusiveLinkedList && src);
  4254. VmaIntrusiveLinkedList(const VmaIntrusiveLinkedList&) = delete;
  4255. VmaIntrusiveLinkedList& operator=(VmaIntrusiveLinkedList&& src);
  4256. VmaIntrusiveLinkedList& operator=(const VmaIntrusiveLinkedList&) = delete;
  4257. ~VmaIntrusiveLinkedList() { VMA_HEAVY_ASSERT(IsEmpty()); }
  4258. size_t GetCount() const { return m_Count; }
  4259. bool IsEmpty() const { return m_Count == 0; }
  4260. ItemType* Front() { return m_Front; }
  4261. ItemType* Back() { return m_Back; }
  4262. const ItemType* Front() const { return m_Front; }
  4263. const ItemType* Back() const { return m_Back; }
  4264. void PushBack(ItemType* item);
  4265. void PushFront(ItemType* item);
  4266. ItemType* PopBack();
  4267. ItemType* PopFront();
  4268. // MyItem can be null - it means PushBack.
  4269. void InsertBefore(ItemType* existingItem, ItemType* newItem);
  4270. // MyItem can be null - it means PushFront.
  4271. void InsertAfter(ItemType* existingItem, ItemType* newItem);
  4272. void Remove(ItemType* item);
  4273. void RemoveAll();
  4274. private:
  4275. ItemType* m_Front = VMA_NULL;
  4276. ItemType* m_Back = VMA_NULL;
  4277. size_t m_Count = 0;
  4278. };
  4279. #ifndef _VMA_INTRUSIVE_LINKED_LIST_FUNCTIONS
  4280. template<typename ItemTypeTraits>
  4281. VmaIntrusiveLinkedList<ItemTypeTraits>::VmaIntrusiveLinkedList(VmaIntrusiveLinkedList&& src)
  4282. : m_Front(src.m_Front), m_Back(src.m_Back), m_Count(src.m_Count)
  4283. {
  4284. src.m_Front = src.m_Back = VMA_NULL;
  4285. src.m_Count = 0;
  4286. }
  4287. template<typename ItemTypeTraits>
  4288. VmaIntrusiveLinkedList<ItemTypeTraits>& VmaIntrusiveLinkedList<ItemTypeTraits>::operator=(VmaIntrusiveLinkedList&& src)
  4289. {
  4290. if (&src != this)
  4291. {
  4292. VMA_HEAVY_ASSERT(IsEmpty());
  4293. m_Front = src.m_Front;
  4294. m_Back = src.m_Back;
  4295. m_Count = src.m_Count;
  4296. src.m_Front = src.m_Back = VMA_NULL;
  4297. src.m_Count = 0;
  4298. }
  4299. return *this;
  4300. }
  4301. template<typename ItemTypeTraits>
  4302. void VmaIntrusiveLinkedList<ItemTypeTraits>::PushBack(ItemType* item)
  4303. {
  4304. VMA_HEAVY_ASSERT(ItemTypeTraits::GetPrev(item) == VMA_NULL && ItemTypeTraits::GetNext(item) == VMA_NULL);
  4305. if (IsEmpty())
  4306. {
  4307. m_Front = item;
  4308. m_Back = item;
  4309. m_Count = 1;
  4310. }
  4311. else
  4312. {
  4313. ItemTypeTraits::AccessPrev(item) = m_Back;
  4314. ItemTypeTraits::AccessNext(m_Back) = item;
  4315. m_Back = item;
  4316. ++m_Count;
  4317. }
  4318. }
  4319. template<typename ItemTypeTraits>
  4320. void VmaIntrusiveLinkedList<ItemTypeTraits>::PushFront(ItemType* item)
  4321. {
  4322. VMA_HEAVY_ASSERT(ItemTypeTraits::GetPrev(item) == VMA_NULL && ItemTypeTraits::GetNext(item) == VMA_NULL);
  4323. if (IsEmpty())
  4324. {
  4325. m_Front = item;
  4326. m_Back = item;
  4327. m_Count = 1;
  4328. }
  4329. else
  4330. {
  4331. ItemTypeTraits::AccessNext(item) = m_Front;
  4332. ItemTypeTraits::AccessPrev(m_Front) = item;
  4333. m_Front = item;
  4334. ++m_Count;
  4335. }
  4336. }
  4337. template<typename ItemTypeTraits>
  4338. typename VmaIntrusiveLinkedList<ItemTypeTraits>::ItemType* VmaIntrusiveLinkedList<ItemTypeTraits>::PopBack()
  4339. {
  4340. VMA_HEAVY_ASSERT(m_Count > 0);
  4341. ItemType* const backItem = m_Back;
  4342. ItemType* const prevItem = ItemTypeTraits::GetPrev(backItem);
  4343. if (prevItem != VMA_NULL)
  4344. {
  4345. ItemTypeTraits::AccessNext(prevItem) = VMA_NULL;
  4346. }
  4347. m_Back = prevItem;
  4348. --m_Count;
  4349. ItemTypeTraits::AccessPrev(backItem) = VMA_NULL;
  4350. ItemTypeTraits::AccessNext(backItem) = VMA_NULL;
  4351. return backItem;
  4352. }
  4353. template<typename ItemTypeTraits>
  4354. typename VmaIntrusiveLinkedList<ItemTypeTraits>::ItemType* VmaIntrusiveLinkedList<ItemTypeTraits>::PopFront()
  4355. {
  4356. VMA_HEAVY_ASSERT(m_Count > 0);
  4357. ItemType* const frontItem = m_Front;
  4358. ItemType* const nextItem = ItemTypeTraits::GetNext(frontItem);
  4359. if (nextItem != VMA_NULL)
  4360. {
  4361. ItemTypeTraits::AccessPrev(nextItem) = VMA_NULL;
  4362. }
  4363. m_Front = nextItem;
  4364. --m_Count;
  4365. ItemTypeTraits::AccessPrev(frontItem) = VMA_NULL;
  4366. ItemTypeTraits::AccessNext(frontItem) = VMA_NULL;
  4367. return frontItem;
  4368. }
  4369. template<typename ItemTypeTraits>
  4370. void VmaIntrusiveLinkedList<ItemTypeTraits>::InsertBefore(ItemType* existingItem, ItemType* newItem)
  4371. {
  4372. VMA_HEAVY_ASSERT(newItem != VMA_NULL && ItemTypeTraits::GetPrev(newItem) == VMA_NULL && ItemTypeTraits::GetNext(newItem) == VMA_NULL);
  4373. if (existingItem != VMA_NULL)
  4374. {
  4375. ItemType* const prevItem = ItemTypeTraits::GetPrev(existingItem);
  4376. ItemTypeTraits::AccessPrev(newItem) = prevItem;
  4377. ItemTypeTraits::AccessNext(newItem) = existingItem;
  4378. ItemTypeTraits::AccessPrev(existingItem) = newItem;
  4379. if (prevItem != VMA_NULL)
  4380. {
  4381. ItemTypeTraits::AccessNext(prevItem) = newItem;
  4382. }
  4383. else
  4384. {
  4385. VMA_HEAVY_ASSERT(m_Front == existingItem);
  4386. m_Front = newItem;
  4387. }
  4388. ++m_Count;
  4389. }
  4390. else
  4391. PushBack(newItem);
  4392. }
  4393. template<typename ItemTypeTraits>
  4394. void VmaIntrusiveLinkedList<ItemTypeTraits>::InsertAfter(ItemType* existingItem, ItemType* newItem)
  4395. {
  4396. VMA_HEAVY_ASSERT(newItem != VMA_NULL && ItemTypeTraits::GetPrev(newItem) == VMA_NULL && ItemTypeTraits::GetNext(newItem) == VMA_NULL);
  4397. if (existingItem != VMA_NULL)
  4398. {
  4399. ItemType* const nextItem = ItemTypeTraits::GetNext(existingItem);
  4400. ItemTypeTraits::AccessNext(newItem) = nextItem;
  4401. ItemTypeTraits::AccessPrev(newItem) = existingItem;
  4402. ItemTypeTraits::AccessNext(existingItem) = newItem;
  4403. if (nextItem != VMA_NULL)
  4404. {
  4405. ItemTypeTraits::AccessPrev(nextItem) = newItem;
  4406. }
  4407. else
  4408. {
  4409. VMA_HEAVY_ASSERT(m_Back == existingItem);
  4410. m_Back = newItem;
  4411. }
  4412. ++m_Count;
  4413. }
  4414. else
  4415. return PushFront(newItem);
  4416. }
  4417. template<typename ItemTypeTraits>
  4418. void VmaIntrusiveLinkedList<ItemTypeTraits>::Remove(ItemType* item)
  4419. {
  4420. VMA_HEAVY_ASSERT(item != VMA_NULL && m_Count > 0);
  4421. if (ItemTypeTraits::GetPrev(item) != VMA_NULL)
  4422. {
  4423. ItemTypeTraits::AccessNext(ItemTypeTraits::AccessPrev(item)) = ItemTypeTraits::GetNext(item);
  4424. }
  4425. else
  4426. {
  4427. VMA_HEAVY_ASSERT(m_Front == item);
  4428. m_Front = ItemTypeTraits::GetNext(item);
  4429. }
  4430. if (ItemTypeTraits::GetNext(item) != VMA_NULL)
  4431. {
  4432. ItemTypeTraits::AccessPrev(ItemTypeTraits::AccessNext(item)) = ItemTypeTraits::GetPrev(item);
  4433. }
  4434. else
  4435. {
  4436. VMA_HEAVY_ASSERT(m_Back == item);
  4437. m_Back = ItemTypeTraits::GetPrev(item);
  4438. }
  4439. ItemTypeTraits::AccessPrev(item) = VMA_NULL;
  4440. ItemTypeTraits::AccessNext(item) = VMA_NULL;
  4441. --m_Count;
  4442. }
  4443. template<typename ItemTypeTraits>
  4444. void VmaIntrusiveLinkedList<ItemTypeTraits>::RemoveAll()
  4445. {
  4446. if (!IsEmpty())
  4447. {
  4448. ItemType* item = m_Back;
  4449. while (item != VMA_NULL)
  4450. {
  4451. ItemType* const prevItem = ItemTypeTraits::AccessPrev(item);
  4452. ItemTypeTraits::AccessPrev(item) = VMA_NULL;
  4453. ItemTypeTraits::AccessNext(item) = VMA_NULL;
  4454. item = prevItem;
  4455. }
  4456. m_Front = VMA_NULL;
  4457. m_Back = VMA_NULL;
  4458. m_Count = 0;
  4459. }
  4460. }
  4461. #endif // _VMA_INTRUSIVE_LINKED_LIST_FUNCTIONS
  4462. #endif // _VMA_INTRUSIVE_LINKED_LIST
  4463. // Unused in this version.
  4464. #if 0
  4465. #ifndef _VMA_PAIR
  4466. template<typename T1, typename T2>
  4467. struct VmaPair
  4468. {
  4469. T1 first;
  4470. T2 second;
  4471. VmaPair() : first(), second() {}
  4472. VmaPair(const T1& firstSrc, const T2& secondSrc) : first(firstSrc), second(secondSrc) {}
  4473. };
  4474. template<typename FirstT, typename SecondT>
  4475. struct VmaPairFirstLess
  4476. {
  4477. bool operator()(const VmaPair<FirstT, SecondT>& lhs, const VmaPair<FirstT, SecondT>& rhs) const
  4478. {
  4479. return lhs.first < rhs.first;
  4480. }
  4481. bool operator()(const VmaPair<FirstT, SecondT>& lhs, const FirstT& rhsFirst) const
  4482. {
  4483. return lhs.first < rhsFirst;
  4484. }
  4485. };
  4486. #endif // _VMA_PAIR
  4487. #ifndef _VMA_MAP
  4488. /* Class compatible with subset of interface of std::unordered_map.
  4489. KeyT, ValueT must be POD because they will be stored in VmaVector.
  4490. */
  4491. template<typename KeyT, typename ValueT>
  4492. class VmaMap
  4493. {
  4494. public:
  4495. typedef VmaPair<KeyT, ValueT> PairType;
  4496. typedef PairType* iterator;
  4497. VmaMap(const VmaStlAllocator<PairType>& allocator) : m_Vector(allocator) {}
  4498. iterator begin() { return m_Vector.begin(); }
  4499. iterator end() { return m_Vector.end(); }
  4500. size_t size() { return m_Vector.size(); }
  4501. void insert(const PairType& pair);
  4502. iterator find(const KeyT& key);
  4503. void erase(iterator it);
  4504. private:
  4505. VmaVector< PairType, VmaStlAllocator<PairType>> m_Vector;
  4506. };
  4507. #ifndef _VMA_MAP_FUNCTIONS
  4508. template<typename KeyT, typename ValueT>
  4509. void VmaMap<KeyT, ValueT>::insert(const PairType& pair)
  4510. {
  4511. const size_t indexToInsert = VmaBinaryFindFirstNotLess(
  4512. m_Vector.data(),
  4513. m_Vector.data() + m_Vector.size(),
  4514. pair,
  4515. VmaPairFirstLess<KeyT, ValueT>()) - m_Vector.data();
  4516. VmaVectorInsert(m_Vector, indexToInsert, pair);
  4517. }
  4518. template<typename KeyT, typename ValueT>
  4519. VmaPair<KeyT, ValueT>* VmaMap<KeyT, ValueT>::find(const KeyT& key)
  4520. {
  4521. PairType* it = VmaBinaryFindFirstNotLess(
  4522. m_Vector.data(),
  4523. m_Vector.data() + m_Vector.size(),
  4524. key,
  4525. VmaPairFirstLess<KeyT, ValueT>());
  4526. if ((it != m_Vector.end()) && (it->first == key))
  4527. {
  4528. return it;
  4529. }
  4530. else
  4531. {
  4532. return m_Vector.end();
  4533. }
  4534. }
  4535. template<typename KeyT, typename ValueT>
  4536. void VmaMap<KeyT, ValueT>::erase(iterator it)
  4537. {
  4538. VmaVectorRemove(m_Vector, it - m_Vector.begin());
  4539. }
  4540. #endif // _VMA_MAP_FUNCTIONS
  4541. #endif // _VMA_MAP
  4542. #endif // #if 0
  4543. #if !defined(_VMA_STRING_BUILDER) && VMA_STATS_STRING_ENABLED
  4544. class VmaStringBuilder
  4545. {
  4546. public:
  4547. VmaStringBuilder(const VkAllocationCallbacks* allocationCallbacks) : m_Data(VmaStlAllocator<char>(allocationCallbacks)) {}
  4548. ~VmaStringBuilder() = default;
  4549. size_t GetLength() const { return m_Data.size(); }
  4550. const char* GetData() const { return m_Data.data(); }
  4551. void AddNewLine() { Add('\n'); }
  4552. void Add(char ch) { m_Data.push_back(ch); }
  4553. void Add(const char* pStr);
  4554. void AddNumber(uint32_t num);
  4555. void AddNumber(uint64_t num);
  4556. void AddPointer(const void* ptr);
  4557. private:
  4558. VmaVector<char, VmaStlAllocator<char>> m_Data;
  4559. };
  4560. #ifndef _VMA_STRING_BUILDER_FUNCTIONS
  4561. void VmaStringBuilder::Add(const char* pStr)
  4562. {
  4563. const size_t strLen = strlen(pStr);
  4564. if (strLen > 0)
  4565. {
  4566. const size_t oldCount = m_Data.size();
  4567. m_Data.resize(oldCount + strLen);
  4568. memcpy(m_Data.data() + oldCount, pStr, strLen);
  4569. }
  4570. }
  4571. void VmaStringBuilder::AddNumber(uint32_t num)
  4572. {
  4573. char buf[11];
  4574. buf[10] = '\0';
  4575. char* p = &buf[10];
  4576. do
  4577. {
  4578. *--p = '0' + (num % 10);
  4579. num /= 10;
  4580. } while (num);
  4581. Add(p);
  4582. }
  4583. void VmaStringBuilder::AddNumber(uint64_t num)
  4584. {
  4585. char buf[21];
  4586. buf[20] = '\0';
  4587. char* p = &buf[20];
  4588. do
  4589. {
  4590. *--p = '0' + (num % 10);
  4591. num /= 10;
  4592. } while (num);
  4593. Add(p);
  4594. }
  4595. void VmaStringBuilder::AddPointer(const void* ptr)
  4596. {
  4597. char buf[21];
  4598. VmaPtrToStr(buf, sizeof(buf), ptr);
  4599. Add(buf);
  4600. }
  4601. #endif //_VMA_STRING_BUILDER_FUNCTIONS
  4602. #endif // _VMA_STRING_BUILDER
  4603. #if !defined(_VMA_JSON_WRITER) && VMA_STATS_STRING_ENABLED
  4604. /*
  4605. Allows to conveniently build a correct JSON document to be written to the
  4606. VmaStringBuilder passed to the constructor.
  4607. */
  4608. class VmaJsonWriter
  4609. {
  4610. VMA_CLASS_NO_COPY(VmaJsonWriter)
  4611. public:
  4612. // sb - string builder to write the document to. Must remain alive for the whole lifetime of this object.
  4613. VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb);
  4614. ~VmaJsonWriter();
  4615. // Begins object by writing "{".
  4616. // Inside an object, you must call pairs of WriteString and a value, e.g.:
  4617. // j.BeginObject(true); j.WriteString("A"); j.WriteNumber(1); j.WriteString("B"); j.WriteNumber(2); j.EndObject();
  4618. // Will write: { "A": 1, "B": 2 }
  4619. void BeginObject(bool singleLine = false);
  4620. // Ends object by writing "}".
  4621. void EndObject();
  4622. // Begins array by writing "[".
  4623. // Inside an array, you can write a sequence of any values.
  4624. void BeginArray(bool singleLine = false);
  4625. // Ends array by writing "[".
  4626. void EndArray();
  4627. // Writes a string value inside "".
  4628. // pStr can contain any ANSI characters, including '"', new line etc. - they will be properly escaped.
  4629. void WriteString(const char* pStr);
  4630. // Begins writing a string value.
  4631. // Call BeginString, ContinueString, ContinueString, ..., EndString instead of
  4632. // WriteString to conveniently build the string content incrementally, made of
  4633. // parts including numbers.
  4634. void BeginString(const char* pStr = VMA_NULL);
  4635. // Posts next part of an open string.
  4636. void ContinueString(const char* pStr);
  4637. // Posts next part of an open string. The number is converted to decimal characters.
  4638. void ContinueString(uint32_t n);
  4639. void ContinueString(uint64_t n);
  4640. void ContinueString_Size(size_t n);
  4641. // Posts next part of an open string. Pointer value is converted to characters
  4642. // using "%p" formatting - shown as hexadecimal number, e.g.: 000000081276Ad00
  4643. void ContinueString_Pointer(const void* ptr);
  4644. // Ends writing a string value by writing '"'.
  4645. void EndString(const char* pStr = VMA_NULL);
  4646. // Writes a number value.
  4647. void WriteNumber(uint32_t n);
  4648. void WriteNumber(uint64_t n);
  4649. void WriteSize(size_t n);
  4650. // Writes a boolean value - false or true.
  4651. void WriteBool(bool b);
  4652. // Writes a null value.
  4653. void WriteNull();
  4654. private:
  4655. enum COLLECTION_TYPE
  4656. {
  4657. COLLECTION_TYPE_OBJECT,
  4658. COLLECTION_TYPE_ARRAY,
  4659. };
  4660. struct StackItem
  4661. {
  4662. COLLECTION_TYPE type;
  4663. uint32_t valueCount;
  4664. bool singleLineMode;
  4665. };
  4666. static const char* const INDENT;
  4667. VmaStringBuilder& m_SB;
  4668. VmaVector< StackItem, VmaStlAllocator<StackItem> > m_Stack;
  4669. bool m_InsideString;
  4670. // Write size_t for less than 64bits
  4671. void WriteSize(size_t n, std::integral_constant<bool, false>) { m_SB.AddNumber(static_cast<uint32_t>(n)); }
  4672. // Write size_t for 64bits
  4673. void WriteSize(size_t n, std::integral_constant<bool, true>) { m_SB.AddNumber(static_cast<uint64_t>(n)); }
  4674. void BeginValue(bool isString);
  4675. void WriteIndent(bool oneLess = false);
  4676. };
  4677. const char* const VmaJsonWriter::INDENT = " ";
  4678. #ifndef _VMA_JSON_WRITER_FUNCTIONS
  4679. VmaJsonWriter::VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb)
  4680. : m_SB(sb),
  4681. m_Stack(VmaStlAllocator<StackItem>(pAllocationCallbacks)),
  4682. m_InsideString(false) {}
  4683. VmaJsonWriter::~VmaJsonWriter()
  4684. {
  4685. VMA_ASSERT(!m_InsideString);
  4686. VMA_ASSERT(m_Stack.empty());
  4687. }
  4688. void VmaJsonWriter::BeginObject(bool singleLine)
  4689. {
  4690. VMA_ASSERT(!m_InsideString);
  4691. BeginValue(false);
  4692. m_SB.Add('{');
  4693. StackItem item;
  4694. item.type = COLLECTION_TYPE_OBJECT;
  4695. item.valueCount = 0;
  4696. item.singleLineMode = singleLine;
  4697. m_Stack.push_back(item);
  4698. }
  4699. void VmaJsonWriter::EndObject()
  4700. {
  4701. VMA_ASSERT(!m_InsideString);
  4702. WriteIndent(true);
  4703. m_SB.Add('}');
  4704. VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_OBJECT);
  4705. m_Stack.pop_back();
  4706. }
  4707. void VmaJsonWriter::BeginArray(bool singleLine)
  4708. {
  4709. VMA_ASSERT(!m_InsideString);
  4710. BeginValue(false);
  4711. m_SB.Add('[');
  4712. StackItem item;
  4713. item.type = COLLECTION_TYPE_ARRAY;
  4714. item.valueCount = 0;
  4715. item.singleLineMode = singleLine;
  4716. m_Stack.push_back(item);
  4717. }
  4718. void VmaJsonWriter::EndArray()
  4719. {
  4720. VMA_ASSERT(!m_InsideString);
  4721. WriteIndent(true);
  4722. m_SB.Add(']');
  4723. VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_ARRAY);
  4724. m_Stack.pop_back();
  4725. }
  4726. void VmaJsonWriter::WriteString(const char* pStr)
  4727. {
  4728. BeginString(pStr);
  4729. EndString();
  4730. }
  4731. void VmaJsonWriter::BeginString(const char* pStr)
  4732. {
  4733. VMA_ASSERT(!m_InsideString);
  4734. BeginValue(true);
  4735. m_SB.Add('"');
  4736. m_InsideString = true;
  4737. if (pStr != VMA_NULL && pStr[0] != '\0')
  4738. {
  4739. ContinueString(pStr);
  4740. }
  4741. }
  4742. void VmaJsonWriter::ContinueString(const char* pStr)
  4743. {
  4744. VMA_ASSERT(m_InsideString);
  4745. const size_t strLen = strlen(pStr);
  4746. for (size_t i = 0; i < strLen; ++i)
  4747. {
  4748. char ch = pStr[i];
  4749. if (ch == '\\')
  4750. {
  4751. m_SB.Add("\\\\");
  4752. }
  4753. else if (ch == '"')
  4754. {
  4755. m_SB.Add("\\\"");
  4756. }
  4757. else if (ch >= 32)
  4758. {
  4759. m_SB.Add(ch);
  4760. }
  4761. else switch (ch)
  4762. {
  4763. case '\b':
  4764. m_SB.Add("\\b");
  4765. break;
  4766. case '\f':
  4767. m_SB.Add("\\f");
  4768. break;
  4769. case '\n':
  4770. m_SB.Add("\\n");
  4771. break;
  4772. case '\r':
  4773. m_SB.Add("\\r");
  4774. break;
  4775. case '\t':
  4776. m_SB.Add("\\t");
  4777. break;
  4778. default:
  4779. VMA_ASSERT(0 && "Character not currently supported.");
  4780. break;
  4781. }
  4782. }
  4783. }
  4784. void VmaJsonWriter::ContinueString(uint32_t n)
  4785. {
  4786. VMA_ASSERT(m_InsideString);
  4787. m_SB.AddNumber(n);
  4788. }
  4789. void VmaJsonWriter::ContinueString(uint64_t n)
  4790. {
  4791. VMA_ASSERT(m_InsideString);
  4792. m_SB.AddNumber(n);
  4793. }
  4794. void VmaJsonWriter::ContinueString_Size(size_t n)
  4795. {
  4796. VMA_ASSERT(m_InsideString);
  4797. // Fix for AppleClang incorrect type casting
  4798. // TODO: Change to if constexpr when C++17 used as minimal standard
  4799. WriteSize(n, std::is_same<size_t, uint64_t>{});
  4800. }
  4801. void VmaJsonWriter::ContinueString_Pointer(const void* ptr)
  4802. {
  4803. VMA_ASSERT(m_InsideString);
  4804. m_SB.AddPointer(ptr);
  4805. }
  4806. void VmaJsonWriter::EndString(const char* pStr)
  4807. {
  4808. VMA_ASSERT(m_InsideString);
  4809. if (pStr != VMA_NULL && pStr[0] != '\0')
  4810. {
  4811. ContinueString(pStr);
  4812. }
  4813. m_SB.Add('"');
  4814. m_InsideString = false;
  4815. }
  4816. void VmaJsonWriter::WriteNumber(uint32_t n)
  4817. {
  4818. VMA_ASSERT(!m_InsideString);
  4819. BeginValue(false);
  4820. m_SB.AddNumber(n);
  4821. }
  4822. void VmaJsonWriter::WriteNumber(uint64_t n)
  4823. {
  4824. VMA_ASSERT(!m_InsideString);
  4825. BeginValue(false);
  4826. m_SB.AddNumber(n);
  4827. }
  4828. void VmaJsonWriter::WriteSize(size_t n)
  4829. {
  4830. VMA_ASSERT(!m_InsideString);
  4831. BeginValue(false);
  4832. // Fix for AppleClang incorrect type casting
  4833. // TODO: Change to if constexpr when C++17 used as minimal standard
  4834. WriteSize(n, std::is_same<size_t, uint64_t>{});
  4835. }
  4836. void VmaJsonWriter::WriteBool(bool b)
  4837. {
  4838. VMA_ASSERT(!m_InsideString);
  4839. BeginValue(false);
  4840. m_SB.Add(b ? "true" : "false");
  4841. }
  4842. void VmaJsonWriter::WriteNull()
  4843. {
  4844. VMA_ASSERT(!m_InsideString);
  4845. BeginValue(false);
  4846. m_SB.Add("null");
  4847. }
  4848. void VmaJsonWriter::BeginValue(bool isString)
  4849. {
  4850. if (!m_Stack.empty())
  4851. {
  4852. StackItem& currItem = m_Stack.back();
  4853. if (currItem.type == COLLECTION_TYPE_OBJECT &&
  4854. currItem.valueCount % 2 == 0)
  4855. {
  4856. VMA_ASSERT(isString);
  4857. }
  4858. if (currItem.type == COLLECTION_TYPE_OBJECT &&
  4859. currItem.valueCount % 2 != 0)
  4860. {
  4861. m_SB.Add(": ");
  4862. }
  4863. else if (currItem.valueCount > 0)
  4864. {
  4865. m_SB.Add(", ");
  4866. WriteIndent();
  4867. }
  4868. else
  4869. {
  4870. WriteIndent();
  4871. }
  4872. ++currItem.valueCount;
  4873. }
  4874. }
  4875. void VmaJsonWriter::WriteIndent(bool oneLess)
  4876. {
  4877. if (!m_Stack.empty() && !m_Stack.back().singleLineMode)
  4878. {
  4879. m_SB.AddNewLine();
  4880. size_t count = m_Stack.size();
  4881. if (count > 0 && oneLess)
  4882. {
  4883. --count;
  4884. }
  4885. for (size_t i = 0; i < count; ++i)
  4886. {
  4887. m_SB.Add(INDENT);
  4888. }
  4889. }
  4890. }
  4891. #endif // _VMA_JSON_WRITER_FUNCTIONS
  4892. static void VmaPrintDetailedStatistics(VmaJsonWriter& json, const VmaDetailedStatistics& stat)
  4893. {
  4894. json.BeginObject();
  4895. json.WriteString("BlockCount");
  4896. json.WriteNumber(stat.statistics.blockCount);
  4897. json.WriteString("BlockBytes");
  4898. json.WriteNumber(stat.statistics.blockBytes);
  4899. json.WriteString("AllocationCount");
  4900. json.WriteNumber(stat.statistics.allocationCount);
  4901. json.WriteString("AllocationBytes");
  4902. json.WriteNumber(stat.statistics.allocationBytes);
  4903. json.WriteString("UnusedRangeCount");
  4904. json.WriteNumber(stat.unusedRangeCount);
  4905. if (stat.statistics.allocationCount > 1)
  4906. {
  4907. json.WriteString("AllocationSizeMin");
  4908. json.WriteNumber(stat.allocationSizeMin);
  4909. json.WriteString("AllocationSizeMax");
  4910. json.WriteNumber(stat.allocationSizeMax);
  4911. }
  4912. if (stat.unusedRangeCount > 1)
  4913. {
  4914. json.WriteString("UnusedRangeSizeMin");
  4915. json.WriteNumber(stat.unusedRangeSizeMin);
  4916. json.WriteString("UnusedRangeSizeMax");
  4917. json.WriteNumber(stat.unusedRangeSizeMax);
  4918. }
  4919. json.EndObject();
  4920. }
  4921. #endif // _VMA_JSON_WRITER
  4922. #ifndef _VMA_MAPPING_HYSTERESIS
  4923. class VmaMappingHysteresis
  4924. {
  4925. VMA_CLASS_NO_COPY(VmaMappingHysteresis)
  4926. public:
  4927. VmaMappingHysteresis() = default;
  4928. uint32_t GetExtraMapping() const { return m_ExtraMapping; }
  4929. // Call when Map was called.
  4930. // Returns true if switched to extra +1 mapping reference count.
  4931. bool PostMap()
  4932. {
  4933. #if VMA_MAPPING_HYSTERESIS_ENABLED
  4934. if(m_ExtraMapping == 0)
  4935. {
  4936. ++m_MajorCounter;
  4937. if(m_MajorCounter >= COUNTER_MIN_EXTRA_MAPPING)
  4938. {
  4939. m_ExtraMapping = 1;
  4940. m_MajorCounter = 0;
  4941. m_MinorCounter = 0;
  4942. return true;
  4943. }
  4944. }
  4945. else // m_ExtraMapping == 1
  4946. PostMinorCounter();
  4947. #endif // #if VMA_MAPPING_HYSTERESIS_ENABLED
  4948. return false;
  4949. }
  4950. // Call when Unmap was called.
  4951. void PostUnmap()
  4952. {
  4953. #if VMA_MAPPING_HYSTERESIS_ENABLED
  4954. if(m_ExtraMapping == 0)
  4955. ++m_MajorCounter;
  4956. else // m_ExtraMapping == 1
  4957. PostMinorCounter();
  4958. #endif // #if VMA_MAPPING_HYSTERESIS_ENABLED
  4959. }
  4960. // Call when allocation was made from the memory block.
  4961. void PostAlloc()
  4962. {
  4963. #if VMA_MAPPING_HYSTERESIS_ENABLED
  4964. if(m_ExtraMapping == 1)
  4965. ++m_MajorCounter;
  4966. else // m_ExtraMapping == 0
  4967. PostMinorCounter();
  4968. #endif // #if VMA_MAPPING_HYSTERESIS_ENABLED
  4969. }
  4970. // Call when allocation was freed from the memory block.
  4971. // Returns true if switched to extra -1 mapping reference count.
  4972. bool PostFree()
  4973. {
  4974. #if VMA_MAPPING_HYSTERESIS_ENABLED
  4975. if(m_ExtraMapping == 1)
  4976. {
  4977. ++m_MajorCounter;
  4978. if(m_MajorCounter >= COUNTER_MIN_EXTRA_MAPPING &&
  4979. m_MajorCounter > m_MinorCounter + 1)
  4980. {
  4981. m_ExtraMapping = 0;
  4982. m_MajorCounter = 0;
  4983. m_MinorCounter = 0;
  4984. return true;
  4985. }
  4986. }
  4987. else // m_ExtraMapping == 0
  4988. PostMinorCounter();
  4989. #endif // #if VMA_MAPPING_HYSTERESIS_ENABLED
  4990. return false;
  4991. }
  4992. private:
  4993. static const int32_t COUNTER_MIN_EXTRA_MAPPING = 7;
  4994. uint32_t m_MinorCounter = 0;
  4995. uint32_t m_MajorCounter = 0;
  4996. uint32_t m_ExtraMapping = 0; // 0 or 1.
  4997. void PostMinorCounter()
  4998. {
  4999. if(m_MinorCounter < m_MajorCounter)
  5000. {
  5001. ++m_MinorCounter;
  5002. }
  5003. else if(m_MajorCounter > 0)
  5004. {
  5005. --m_MajorCounter;
  5006. --m_MinorCounter;
  5007. }
  5008. }
  5009. };
  5010. #endif // _VMA_MAPPING_HYSTERESIS
  5011. #ifndef _VMA_DEVICE_MEMORY_BLOCK
  5012. /*
  5013. Represents a single block of device memory (`VkDeviceMemory`) with all the
  5014. data about its regions (aka suballocations, #VmaAllocation), assigned and free.
  5015. Thread-safety:
  5016. - Access to m_pMetadata must be externally synchronized.
  5017. - Map, Unmap, Bind* are synchronized internally.
  5018. */
  5019. class VmaDeviceMemoryBlock
  5020. {
  5021. VMA_CLASS_NO_COPY(VmaDeviceMemoryBlock)
  5022. public:
  5023. VmaBlockMetadata* m_pMetadata;
  5024. VmaDeviceMemoryBlock(VmaAllocator hAllocator);
  5025. ~VmaDeviceMemoryBlock();
  5026. // Always call after construction.
  5027. void Init(
  5028. VmaAllocator hAllocator,
  5029. VmaPool hParentPool,
  5030. uint32_t newMemoryTypeIndex,
  5031. VkDeviceMemory newMemory,
  5032. VkDeviceSize newSize,
  5033. uint32_t id,
  5034. uint32_t algorithm,
  5035. VkDeviceSize bufferImageGranularity);
  5036. // Always call before destruction.
  5037. void Destroy(VmaAllocator allocator);
  5038. VmaPool GetParentPool() const { return m_hParentPool; }
  5039. VkDeviceMemory GetDeviceMemory() const { return m_hMemory; }
  5040. uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
  5041. uint32_t GetId() const { return m_Id; }
  5042. void* GetMappedData() const { return m_pMappedData; }
  5043. uint32_t GetMapRefCount() const { return m_MapCount; }
  5044. // Call when allocation/free was made from m_pMetadata.
  5045. // Used for m_MappingHysteresis.
  5046. void PostAlloc() { m_MappingHysteresis.PostAlloc(); }
  5047. void PostFree(VmaAllocator hAllocator);
  5048. // Validates all data structures inside this object. If not valid, returns false.
  5049. bool Validate() const;
  5050. VkResult CheckCorruption(VmaAllocator hAllocator);
  5051. // ppData can be null.
  5052. VkResult Map(VmaAllocator hAllocator, uint32_t count, void** ppData);
  5053. void Unmap(VmaAllocator hAllocator, uint32_t count);
  5054. VkResult WriteMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize);
  5055. VkResult ValidateMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize);
  5056. VkResult BindBufferMemory(
  5057. const VmaAllocator hAllocator,
  5058. const VmaAllocation hAllocation,
  5059. VkDeviceSize allocationLocalOffset,
  5060. VkBuffer hBuffer,
  5061. const void* pNext);
  5062. VkResult BindImageMemory(
  5063. const VmaAllocator hAllocator,
  5064. const VmaAllocation hAllocation,
  5065. VkDeviceSize allocationLocalOffset,
  5066. VkImage hImage,
  5067. const void* pNext);
  5068. private:
  5069. VmaPool m_hParentPool; // VK_NULL_HANDLE if not belongs to custom pool.
  5070. uint32_t m_MemoryTypeIndex;
  5071. uint32_t m_Id;
  5072. VkDeviceMemory m_hMemory;
  5073. /*
  5074. Protects access to m_hMemory so it is not used by multiple threads simultaneously, e.g. vkMapMemory, vkBindBufferMemory.
  5075. Also protects m_MapCount, m_pMappedData.
  5076. Allocations, deallocations, any change in m_pMetadata is protected by parent's VmaBlockVector::m_Mutex.
  5077. */
  5078. VMA_MUTEX m_MapAndBindMutex;
  5079. VmaMappingHysteresis m_MappingHysteresis;
  5080. uint32_t m_MapCount;
  5081. void* m_pMappedData;
  5082. };
  5083. #endif // _VMA_DEVICE_MEMORY_BLOCK
  5084. #ifndef _VMA_ALLOCATION_T
  5085. struct VmaAllocation_T
  5086. {
  5087. friend struct VmaDedicatedAllocationListItemTraits;
  5088. enum FLAGS
  5089. {
  5090. FLAG_PERSISTENT_MAP = 0x01,
  5091. FLAG_MAPPING_ALLOWED = 0x02,
  5092. };
  5093. public:
  5094. enum ALLOCATION_TYPE
  5095. {
  5096. ALLOCATION_TYPE_NONE,
  5097. ALLOCATION_TYPE_BLOCK,
  5098. ALLOCATION_TYPE_DEDICATED,
  5099. };
  5100. // This struct is allocated using VmaPoolAllocator.
  5101. VmaAllocation_T(bool mappingAllowed);
  5102. ~VmaAllocation_T();
  5103. void InitBlockAllocation(
  5104. VmaDeviceMemoryBlock* block,
  5105. VmaAllocHandle allocHandle,
  5106. VkDeviceSize alignment,
  5107. VkDeviceSize size,
  5108. uint32_t memoryTypeIndex,
  5109. VmaSuballocationType suballocationType,
  5110. bool mapped);
  5111. // pMappedData not null means allocation is created with MAPPED flag.
  5112. void InitDedicatedAllocation(
  5113. VmaPool hParentPool,
  5114. uint32_t memoryTypeIndex,
  5115. VkDeviceMemory hMemory,
  5116. VmaSuballocationType suballocationType,
  5117. void* pMappedData,
  5118. VkDeviceSize size);
  5119. ALLOCATION_TYPE GetType() const { return (ALLOCATION_TYPE)m_Type; }
  5120. VkDeviceSize GetAlignment() const { return m_Alignment; }
  5121. VkDeviceSize GetSize() const { return m_Size; }
  5122. void* GetUserData() const { return m_pUserData; }
  5123. const char* GetName() const { return m_pName; }
  5124. VmaSuballocationType GetSuballocationType() const { return (VmaSuballocationType)m_SuballocationType; }
  5125. VmaDeviceMemoryBlock* GetBlock() const { VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK); return m_BlockAllocation.m_Block; }
  5126. uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
  5127. bool IsPersistentMap() const { return (m_Flags & FLAG_PERSISTENT_MAP) != 0; }
  5128. bool IsMappingAllowed() const { return (m_Flags & FLAG_MAPPING_ALLOWED) != 0; }
  5129. void SetUserData(VmaAllocator hAllocator, void* pUserData) { m_pUserData = pUserData; }
  5130. void SetName(VmaAllocator hAllocator, const char* pName);
  5131. void FreeName(VmaAllocator hAllocator);
  5132. uint8_t SwapBlockAllocation(VmaAllocator hAllocator, VmaAllocation allocation);
  5133. VmaAllocHandle GetAllocHandle() const;
  5134. VkDeviceSize GetOffset() const;
  5135. VmaPool GetParentPool() const;
  5136. VkDeviceMemory GetMemory() const;
  5137. void* GetMappedData() const;
  5138. void BlockAllocMap();
  5139. void BlockAllocUnmap();
  5140. VkResult DedicatedAllocMap(VmaAllocator hAllocator, void** ppData);
  5141. void DedicatedAllocUnmap(VmaAllocator hAllocator);
  5142. #if VMA_STATS_STRING_ENABLED
  5143. uint32_t GetBufferImageUsage() const { return m_BufferImageUsage; }
  5144. void InitBufferImageUsage(uint32_t bufferImageUsage);
  5145. void PrintParameters(class VmaJsonWriter& json) const;
  5146. #endif
  5147. private:
  5148. // Allocation out of VmaDeviceMemoryBlock.
  5149. struct BlockAllocation
  5150. {
  5151. VmaDeviceMemoryBlock* m_Block;
  5152. VmaAllocHandle m_AllocHandle;
  5153. };
  5154. // Allocation for an object that has its own private VkDeviceMemory.
  5155. struct DedicatedAllocation
  5156. {
  5157. VmaPool m_hParentPool; // VK_NULL_HANDLE if not belongs to custom pool.
  5158. VkDeviceMemory m_hMemory;
  5159. void* m_pMappedData; // Not null means memory is mapped.
  5160. VmaAllocation_T* m_Prev;
  5161. VmaAllocation_T* m_Next;
  5162. };
  5163. union
  5164. {
  5165. // Allocation out of VmaDeviceMemoryBlock.
  5166. BlockAllocation m_BlockAllocation;
  5167. // Allocation for an object that has its own private VkDeviceMemory.
  5168. DedicatedAllocation m_DedicatedAllocation;
  5169. };
  5170. VkDeviceSize m_Alignment;
  5171. VkDeviceSize m_Size;
  5172. void* m_pUserData;
  5173. char* m_pName;
  5174. uint32_t m_MemoryTypeIndex;
  5175. uint8_t m_Type; // ALLOCATION_TYPE
  5176. uint8_t m_SuballocationType; // VmaSuballocationType
  5177. // Reference counter for vmaMapMemory()/vmaUnmapMemory().
  5178. uint8_t m_MapCount;
  5179. uint8_t m_Flags; // enum FLAGS
  5180. #if VMA_STATS_STRING_ENABLED
  5181. uint32_t m_BufferImageUsage; // 0 if unknown.
  5182. #endif
  5183. };
  5184. #endif // _VMA_ALLOCATION_T
  5185. #ifndef _VMA_DEDICATED_ALLOCATION_LIST_ITEM_TRAITS
  5186. struct VmaDedicatedAllocationListItemTraits
  5187. {
  5188. typedef VmaAllocation_T ItemType;
  5189. static ItemType* GetPrev(const ItemType* item)
  5190. {
  5191. VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  5192. return item->m_DedicatedAllocation.m_Prev;
  5193. }
  5194. static ItemType* GetNext(const ItemType* item)
  5195. {
  5196. VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  5197. return item->m_DedicatedAllocation.m_Next;
  5198. }
  5199. static ItemType*& AccessPrev(ItemType* item)
  5200. {
  5201. VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  5202. return item->m_DedicatedAllocation.m_Prev;
  5203. }
  5204. static ItemType*& AccessNext(ItemType* item)
  5205. {
  5206. VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  5207. return item->m_DedicatedAllocation.m_Next;
  5208. }
  5209. };
  5210. #endif // _VMA_DEDICATED_ALLOCATION_LIST_ITEM_TRAITS
  5211. #ifndef _VMA_DEDICATED_ALLOCATION_LIST
  5212. /*
  5213. Stores linked list of VmaAllocation_T objects.
  5214. Thread-safe, synchronized internally.
  5215. */
  5216. class VmaDedicatedAllocationList
  5217. {
  5218. public:
  5219. VmaDedicatedAllocationList() {}
  5220. ~VmaDedicatedAllocationList();
  5221. void Init(bool useMutex) { m_UseMutex = useMutex; }
  5222. bool Validate();
  5223. void AddDetailedStatistics(VmaDetailedStatistics& inoutStats);
  5224. void AddStatistics(VmaStatistics& inoutStats);
  5225. #if VMA_STATS_STRING_ENABLED
  5226. // Writes JSON array with the list of allocations.
  5227. void BuildStatsString(VmaJsonWriter& json);
  5228. #endif
  5229. bool IsEmpty();
  5230. void Register(VmaAllocation alloc);
  5231. void Unregister(VmaAllocation alloc);
  5232. private:
  5233. typedef VmaIntrusiveLinkedList<VmaDedicatedAllocationListItemTraits> DedicatedAllocationLinkedList;
  5234. bool m_UseMutex = true;
  5235. VMA_RW_MUTEX m_Mutex;
  5236. DedicatedAllocationLinkedList m_AllocationList;
  5237. };
  5238. #ifndef _VMA_DEDICATED_ALLOCATION_LIST_FUNCTIONS
  5239. VmaDedicatedAllocationList::~VmaDedicatedAllocationList()
  5240. {
  5241. VMA_HEAVY_ASSERT(Validate());
  5242. if (!m_AllocationList.IsEmpty())
  5243. {
  5244. VMA_ASSERT(false && "Unfreed dedicated allocations found!");
  5245. }
  5246. }
  5247. bool VmaDedicatedAllocationList::Validate()
  5248. {
  5249. const size_t declaredCount = m_AllocationList.GetCount();
  5250. size_t actualCount = 0;
  5251. VmaMutexLockRead lock(m_Mutex, m_UseMutex);
  5252. for (VmaAllocation alloc = m_AllocationList.Front();
  5253. alloc != VMA_NULL; alloc = m_AllocationList.GetNext(alloc))
  5254. {
  5255. ++actualCount;
  5256. }
  5257. VMA_VALIDATE(actualCount == declaredCount);
  5258. return true;
  5259. }
  5260. void VmaDedicatedAllocationList::AddDetailedStatistics(VmaDetailedStatistics& inoutStats)
  5261. {
  5262. for(auto* item = m_AllocationList.Front(); item != nullptr; item = DedicatedAllocationLinkedList::GetNext(item))
  5263. {
  5264. const VkDeviceSize size = item->GetSize();
  5265. inoutStats.statistics.blockCount++;
  5266. inoutStats.statistics.blockBytes += size;
  5267. VmaAddDetailedStatisticsAllocation(inoutStats, item->GetSize());
  5268. }
  5269. }
  5270. void VmaDedicatedAllocationList::AddStatistics(VmaStatistics& inoutStats)
  5271. {
  5272. VmaMutexLockRead lock(m_Mutex, m_UseMutex);
  5273. const uint32_t allocCount = (uint32_t)m_AllocationList.GetCount();
  5274. inoutStats.blockCount += allocCount;
  5275. inoutStats.allocationCount += allocCount;
  5276. for(auto* item = m_AllocationList.Front(); item != nullptr; item = DedicatedAllocationLinkedList::GetNext(item))
  5277. {
  5278. const VkDeviceSize size = item->GetSize();
  5279. inoutStats.blockBytes += size;
  5280. inoutStats.allocationBytes += size;
  5281. }
  5282. }
  5283. #if VMA_STATS_STRING_ENABLED
  5284. void VmaDedicatedAllocationList::BuildStatsString(VmaJsonWriter& json)
  5285. {
  5286. VmaMutexLockRead lock(m_Mutex, m_UseMutex);
  5287. json.BeginArray();
  5288. for (VmaAllocation alloc = m_AllocationList.Front();
  5289. alloc != VMA_NULL; alloc = m_AllocationList.GetNext(alloc))
  5290. {
  5291. json.BeginObject(true);
  5292. alloc->PrintParameters(json);
  5293. json.EndObject();
  5294. }
  5295. json.EndArray();
  5296. }
  5297. #endif // VMA_STATS_STRING_ENABLED
  5298. bool VmaDedicatedAllocationList::IsEmpty()
  5299. {
  5300. VmaMutexLockRead lock(m_Mutex, m_UseMutex);
  5301. return m_AllocationList.IsEmpty();
  5302. }
  5303. void VmaDedicatedAllocationList::Register(VmaAllocation alloc)
  5304. {
  5305. VmaMutexLockWrite lock(m_Mutex, m_UseMutex);
  5306. m_AllocationList.PushBack(alloc);
  5307. }
  5308. void VmaDedicatedAllocationList::Unregister(VmaAllocation alloc)
  5309. {
  5310. VmaMutexLockWrite lock(m_Mutex, m_UseMutex);
  5311. m_AllocationList.Remove(alloc);
  5312. }
  5313. #endif // _VMA_DEDICATED_ALLOCATION_LIST_FUNCTIONS
  5314. #endif // _VMA_DEDICATED_ALLOCATION_LIST
  5315. #ifndef _VMA_SUBALLOCATION
  5316. /*
  5317. Represents a region of VmaDeviceMemoryBlock that is either assigned and returned as
  5318. allocated memory block or free.
  5319. */
  5320. struct VmaSuballocation
  5321. {
  5322. VkDeviceSize offset;
  5323. VkDeviceSize size;
  5324. void* userData;
  5325. VmaSuballocationType type;
  5326. };
  5327. // Comparator for offsets.
  5328. struct VmaSuballocationOffsetLess
  5329. {
  5330. bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const
  5331. {
  5332. return lhs.offset < rhs.offset;
  5333. }
  5334. };
  5335. struct VmaSuballocationOffsetGreater
  5336. {
  5337. bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const
  5338. {
  5339. return lhs.offset > rhs.offset;
  5340. }
  5341. };
  5342. struct VmaSuballocationItemSizeLess
  5343. {
  5344. bool operator()(const VmaSuballocationList::iterator lhs,
  5345. const VmaSuballocationList::iterator rhs) const
  5346. {
  5347. return lhs->size < rhs->size;
  5348. }
  5349. bool operator()(const VmaSuballocationList::iterator lhs,
  5350. VkDeviceSize rhsSize) const
  5351. {
  5352. return lhs->size < rhsSize;
  5353. }
  5354. };
  5355. #endif // _VMA_SUBALLOCATION
  5356. #ifndef _VMA_ALLOCATION_REQUEST
  5357. /*
  5358. Parameters of planned allocation inside a VmaDeviceMemoryBlock.
  5359. item points to a FREE suballocation.
  5360. */
  5361. struct VmaAllocationRequest
  5362. {
  5363. VmaAllocHandle allocHandle;
  5364. VkDeviceSize size;
  5365. VmaSuballocationList::iterator item;
  5366. void* customData;
  5367. uint64_t algorithmData;
  5368. VmaAllocationRequestType type;
  5369. };
  5370. #endif // _VMA_ALLOCATION_REQUEST
  5371. #ifndef _VMA_BLOCK_METADATA
  5372. /*
  5373. Data structure used for bookkeeping of allocations and unused ranges of memory
  5374. in a single VkDeviceMemory block.
  5375. */
  5376. class VmaBlockMetadata
  5377. {
  5378. public:
  5379. // pAllocationCallbacks, if not null, must be owned externally - alive and unchanged for the whole lifetime of this object.
  5380. VmaBlockMetadata(const VkAllocationCallbacks* pAllocationCallbacks,
  5381. VkDeviceSize bufferImageGranularity, bool isVirtual);
  5382. virtual ~VmaBlockMetadata() = default;
  5383. virtual void Init(VkDeviceSize size) { m_Size = size; }
  5384. bool IsVirtual() const { return m_IsVirtual; }
  5385. VkDeviceSize GetSize() const { return m_Size; }
  5386. // Validates all data structures inside this object. If not valid, returns false.
  5387. virtual bool Validate() const = 0;
  5388. virtual size_t GetAllocationCount() const = 0;
  5389. virtual size_t GetFreeRegionsCount() const = 0;
  5390. virtual VkDeviceSize GetSumFreeSize() const = 0;
  5391. // Returns true if this block is empty - contains only single free suballocation.
  5392. virtual bool IsEmpty() const = 0;
  5393. virtual void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) = 0;
  5394. virtual VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const = 0;
  5395. virtual void* GetAllocationUserData(VmaAllocHandle allocHandle) const = 0;
  5396. virtual VmaAllocHandle GetAllocationListBegin() const = 0;
  5397. virtual VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const = 0;
  5398. virtual VkDeviceSize GetNextFreeRegionSize(VmaAllocHandle alloc) const = 0;
  5399. // Shouldn't modify blockCount.
  5400. virtual void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const = 0;
  5401. virtual void AddStatistics(VmaStatistics& inoutStats) const = 0;
  5402. #if VMA_STATS_STRING_ENABLED
  5403. virtual void PrintDetailedMap(class VmaJsonWriter& json) const = 0;
  5404. #endif
  5405. // Tries to find a place for suballocation with given parameters inside this block.
  5406. // If succeeded, fills pAllocationRequest and returns true.
  5407. // If failed, returns false.
  5408. virtual bool CreateAllocationRequest(
  5409. VkDeviceSize allocSize,
  5410. VkDeviceSize allocAlignment,
  5411. bool upperAddress,
  5412. VmaSuballocationType allocType,
  5413. // Always one of VMA_ALLOCATION_CREATE_STRATEGY_* or VMA_ALLOCATION_INTERNAL_STRATEGY_* flags.
  5414. uint32_t strategy,
  5415. VmaAllocationRequest* pAllocationRequest) = 0;
  5416. virtual VkResult CheckCorruption(const void* pBlockData) = 0;
  5417. // Makes actual allocation based on request. Request must already be checked and valid.
  5418. virtual void Alloc(
  5419. const VmaAllocationRequest& request,
  5420. VmaSuballocationType type,
  5421. void* userData) = 0;
  5422. // Frees suballocation assigned to given memory region.
  5423. virtual void Free(VmaAllocHandle allocHandle) = 0;
  5424. // Frees all allocations.
  5425. // Careful! Don't call it if there are VmaAllocation objects owned by userData of cleared allocations!
  5426. virtual void Clear() = 0;
  5427. virtual void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) = 0;
  5428. virtual void DebugLogAllAllocations() const = 0;
  5429. protected:
  5430. const VkAllocationCallbacks* GetAllocationCallbacks() const { return m_pAllocationCallbacks; }
  5431. VkDeviceSize GetBufferImageGranularity() const { return m_BufferImageGranularity; }
  5432. VkDeviceSize GetDebugMargin() const { return IsVirtual() ? 0 : VMA_DEBUG_MARGIN; }
  5433. void DebugLogAllocation(VkDeviceSize offset, VkDeviceSize size, void* userData) const;
  5434. #if VMA_STATS_STRING_ENABLED
  5435. // mapRefCount == UINT32_MAX means unspecified.
  5436. void PrintDetailedMap_Begin(class VmaJsonWriter& json,
  5437. VkDeviceSize unusedBytes,
  5438. size_t allocationCount,
  5439. size_t unusedRangeCount) const;
  5440. void PrintDetailedMap_Allocation(class VmaJsonWriter& json,
  5441. VkDeviceSize offset, VkDeviceSize size, void* userData) const;
  5442. void PrintDetailedMap_UnusedRange(class VmaJsonWriter& json,
  5443. VkDeviceSize offset,
  5444. VkDeviceSize size) const;
  5445. void PrintDetailedMap_End(class VmaJsonWriter& json) const;
  5446. #endif
  5447. private:
  5448. VkDeviceSize m_Size;
  5449. const VkAllocationCallbacks* m_pAllocationCallbacks;
  5450. const VkDeviceSize m_BufferImageGranularity;
  5451. const bool m_IsVirtual;
  5452. };
  5453. #ifndef _VMA_BLOCK_METADATA_FUNCTIONS
  5454. VmaBlockMetadata::VmaBlockMetadata(const VkAllocationCallbacks* pAllocationCallbacks,
  5455. VkDeviceSize bufferImageGranularity, bool isVirtual)
  5456. : m_Size(0),
  5457. m_pAllocationCallbacks(pAllocationCallbacks),
  5458. m_BufferImageGranularity(bufferImageGranularity),
  5459. m_IsVirtual(isVirtual) {}
  5460. void VmaBlockMetadata::DebugLogAllocation(VkDeviceSize offset, VkDeviceSize size, void* userData) const
  5461. {
  5462. if (IsVirtual())
  5463. {
  5464. VMA_DEBUG_LOG("UNFREED VIRTUAL ALLOCATION; Offset: %llu; Size: %llu; UserData: %p", offset, size, userData);
  5465. }
  5466. else
  5467. {
  5468. VMA_ASSERT(userData != VMA_NULL);
  5469. VmaAllocation allocation = reinterpret_cast<VmaAllocation>(userData);
  5470. userData = allocation->GetUserData();
  5471. const char* name = allocation->GetName();
  5472. #if VMA_STATS_STRING_ENABLED
  5473. VMA_DEBUG_LOG("UNFREED ALLOCATION; Offset: %llu; Size: %llu; UserData: %p; Name: %s; Type: %s; Usage: %u",
  5474. offset, size, userData, name ? name : "vma_empty",
  5475. VMA_SUBALLOCATION_TYPE_NAMES[allocation->GetSuballocationType()],
  5476. allocation->GetBufferImageUsage());
  5477. #else
  5478. VMA_DEBUG_LOG("UNFREED ALLOCATION; Offset: %llu; Size: %llu; UserData: %p; Name: %s; Type: %u",
  5479. offset, size, userData, name ? name : "vma_empty",
  5480. (uint32_t)allocation->GetSuballocationType());
  5481. #endif // VMA_STATS_STRING_ENABLED
  5482. }
  5483. }
  5484. #if VMA_STATS_STRING_ENABLED
  5485. void VmaBlockMetadata::PrintDetailedMap_Begin(class VmaJsonWriter& json,
  5486. VkDeviceSize unusedBytes, size_t allocationCount, size_t unusedRangeCount) const
  5487. {
  5488. json.WriteString("TotalBytes");
  5489. json.WriteNumber(GetSize());
  5490. json.WriteString("UnusedBytes");
  5491. json.WriteSize(unusedBytes);
  5492. json.WriteString("Allocations");
  5493. json.WriteSize(allocationCount);
  5494. json.WriteString("UnusedRanges");
  5495. json.WriteSize(unusedRangeCount);
  5496. json.WriteString("Suballocations");
  5497. json.BeginArray();
  5498. }
  5499. void VmaBlockMetadata::PrintDetailedMap_Allocation(class VmaJsonWriter& json,
  5500. VkDeviceSize offset, VkDeviceSize size, void* userData) const
  5501. {
  5502. json.BeginObject(true);
  5503. json.WriteString("Offset");
  5504. json.WriteNumber(offset);
  5505. if (IsVirtual())
  5506. {
  5507. json.WriteString("Size");
  5508. json.WriteNumber(size);
  5509. if (userData)
  5510. {
  5511. json.WriteString("CustomData");
  5512. json.BeginString();
  5513. json.ContinueString_Pointer(userData);
  5514. json.EndString();
  5515. }
  5516. }
  5517. else
  5518. {
  5519. ((VmaAllocation)userData)->PrintParameters(json);
  5520. }
  5521. json.EndObject();
  5522. }
  5523. void VmaBlockMetadata::PrintDetailedMap_UnusedRange(class VmaJsonWriter& json,
  5524. VkDeviceSize offset, VkDeviceSize size) const
  5525. {
  5526. json.BeginObject(true);
  5527. json.WriteString("Offset");
  5528. json.WriteNumber(offset);
  5529. json.WriteString("Type");
  5530. json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[VMA_SUBALLOCATION_TYPE_FREE]);
  5531. json.WriteString("Size");
  5532. json.WriteNumber(size);
  5533. json.EndObject();
  5534. }
  5535. void VmaBlockMetadata::PrintDetailedMap_End(class VmaJsonWriter& json) const
  5536. {
  5537. json.EndArray();
  5538. }
  5539. #endif // VMA_STATS_STRING_ENABLED
  5540. #endif // _VMA_BLOCK_METADATA_FUNCTIONS
  5541. #endif // _VMA_BLOCK_METADATA
  5542. #ifndef _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY
  5543. // Before deleting object of this class remember to call 'Destroy()'
  5544. class VmaBlockBufferImageGranularity final
  5545. {
  5546. public:
  5547. struct ValidationContext
  5548. {
  5549. const VkAllocationCallbacks* allocCallbacks;
  5550. uint16_t* pageAllocs;
  5551. };
  5552. VmaBlockBufferImageGranularity(VkDeviceSize bufferImageGranularity);
  5553. ~VmaBlockBufferImageGranularity();
  5554. bool IsEnabled() const { return m_BufferImageGranularity > MAX_LOW_BUFFER_IMAGE_GRANULARITY; }
  5555. void Init(const VkAllocationCallbacks* pAllocationCallbacks, VkDeviceSize size);
  5556. // Before destroying object you must call free it's memory
  5557. void Destroy(const VkAllocationCallbacks* pAllocationCallbacks);
  5558. void RoundupAllocRequest(VmaSuballocationType allocType,
  5559. VkDeviceSize& inOutAllocSize,
  5560. VkDeviceSize& inOutAllocAlignment) const;
  5561. bool CheckConflictAndAlignUp(VkDeviceSize& inOutAllocOffset,
  5562. VkDeviceSize allocSize,
  5563. VkDeviceSize blockOffset,
  5564. VkDeviceSize blockSize,
  5565. VmaSuballocationType allocType) const;
  5566. void AllocPages(uint8_t allocType, VkDeviceSize offset, VkDeviceSize size);
  5567. void FreePages(VkDeviceSize offset, VkDeviceSize size);
  5568. void Clear();
  5569. ValidationContext StartValidation(const VkAllocationCallbacks* pAllocationCallbacks,
  5570. bool isVirutal) const;
  5571. bool Validate(ValidationContext& ctx, VkDeviceSize offset, VkDeviceSize size) const;
  5572. bool FinishValidation(ValidationContext& ctx) const;
  5573. private:
  5574. static const uint16_t MAX_LOW_BUFFER_IMAGE_GRANULARITY = 256;
  5575. struct RegionInfo
  5576. {
  5577. uint8_t allocType;
  5578. uint16_t allocCount;
  5579. };
  5580. VkDeviceSize m_BufferImageGranularity;
  5581. uint32_t m_RegionCount;
  5582. RegionInfo* m_RegionInfo;
  5583. uint32_t GetStartPage(VkDeviceSize offset) const { return OffsetToPageIndex(offset & ~(m_BufferImageGranularity - 1)); }
  5584. uint32_t GetEndPage(VkDeviceSize offset, VkDeviceSize size) const { return OffsetToPageIndex((offset + size - 1) & ~(m_BufferImageGranularity - 1)); }
  5585. uint32_t OffsetToPageIndex(VkDeviceSize offset) const;
  5586. void AllocPage(RegionInfo& page, uint8_t allocType);
  5587. };
  5588. #ifndef _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY_FUNCTIONS
  5589. VmaBlockBufferImageGranularity::VmaBlockBufferImageGranularity(VkDeviceSize bufferImageGranularity)
  5590. : m_BufferImageGranularity(bufferImageGranularity),
  5591. m_RegionCount(0),
  5592. m_RegionInfo(VMA_NULL) {}
  5593. VmaBlockBufferImageGranularity::~VmaBlockBufferImageGranularity()
  5594. {
  5595. VMA_ASSERT(m_RegionInfo == VMA_NULL && "Free not called before destroying object!");
  5596. }
  5597. void VmaBlockBufferImageGranularity::Init(const VkAllocationCallbacks* pAllocationCallbacks, VkDeviceSize size)
  5598. {
  5599. if (IsEnabled())
  5600. {
  5601. m_RegionCount = static_cast<uint32_t>(VmaDivideRoundingUp(size, m_BufferImageGranularity));
  5602. m_RegionInfo = vma_new_array(pAllocationCallbacks, RegionInfo, m_RegionCount);
  5603. memset(m_RegionInfo, 0, m_RegionCount * sizeof(RegionInfo));
  5604. }
  5605. }
  5606. void VmaBlockBufferImageGranularity::Destroy(const VkAllocationCallbacks* pAllocationCallbacks)
  5607. {
  5608. if (m_RegionInfo)
  5609. {
  5610. vma_delete_array(pAllocationCallbacks, m_RegionInfo, m_RegionCount);
  5611. m_RegionInfo = VMA_NULL;
  5612. }
  5613. }
  5614. void VmaBlockBufferImageGranularity::RoundupAllocRequest(VmaSuballocationType allocType,
  5615. VkDeviceSize& inOutAllocSize,
  5616. VkDeviceSize& inOutAllocAlignment) const
  5617. {
  5618. if (m_BufferImageGranularity > 1 &&
  5619. m_BufferImageGranularity <= MAX_LOW_BUFFER_IMAGE_GRANULARITY)
  5620. {
  5621. if (allocType == VMA_SUBALLOCATION_TYPE_UNKNOWN ||
  5622. allocType == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
  5623. allocType == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL)
  5624. {
  5625. inOutAllocAlignment = VMA_MAX(inOutAllocAlignment, m_BufferImageGranularity);
  5626. inOutAllocSize = VmaAlignUp(inOutAllocSize, m_BufferImageGranularity);
  5627. }
  5628. }
  5629. }
  5630. bool VmaBlockBufferImageGranularity::CheckConflictAndAlignUp(VkDeviceSize& inOutAllocOffset,
  5631. VkDeviceSize allocSize,
  5632. VkDeviceSize blockOffset,
  5633. VkDeviceSize blockSize,
  5634. VmaSuballocationType allocType) const
  5635. {
  5636. if (IsEnabled())
  5637. {
  5638. uint32_t startPage = GetStartPage(inOutAllocOffset);
  5639. if (m_RegionInfo[startPage].allocCount > 0 &&
  5640. VmaIsBufferImageGranularityConflict(static_cast<VmaSuballocationType>(m_RegionInfo[startPage].allocType), allocType))
  5641. {
  5642. inOutAllocOffset = VmaAlignUp(inOutAllocOffset, m_BufferImageGranularity);
  5643. if (blockSize < allocSize + inOutAllocOffset - blockOffset)
  5644. return true;
  5645. ++startPage;
  5646. }
  5647. uint32_t endPage = GetEndPage(inOutAllocOffset, allocSize);
  5648. if (endPage != startPage &&
  5649. m_RegionInfo[endPage].allocCount > 0 &&
  5650. VmaIsBufferImageGranularityConflict(static_cast<VmaSuballocationType>(m_RegionInfo[endPage].allocType), allocType))
  5651. {
  5652. return true;
  5653. }
  5654. }
  5655. return false;
  5656. }
  5657. void VmaBlockBufferImageGranularity::AllocPages(uint8_t allocType, VkDeviceSize offset, VkDeviceSize size)
  5658. {
  5659. if (IsEnabled())
  5660. {
  5661. uint32_t startPage = GetStartPage(offset);
  5662. AllocPage(m_RegionInfo[startPage], allocType);
  5663. uint32_t endPage = GetEndPage(offset, size);
  5664. if (startPage != endPage)
  5665. AllocPage(m_RegionInfo[endPage], allocType);
  5666. }
  5667. }
  5668. void VmaBlockBufferImageGranularity::FreePages(VkDeviceSize offset, VkDeviceSize size)
  5669. {
  5670. if (IsEnabled())
  5671. {
  5672. uint32_t startPage = GetStartPage(offset);
  5673. --m_RegionInfo[startPage].allocCount;
  5674. if (m_RegionInfo[startPage].allocCount == 0)
  5675. m_RegionInfo[startPage].allocType = VMA_SUBALLOCATION_TYPE_FREE;
  5676. uint32_t endPage = GetEndPage(offset, size);
  5677. if (startPage != endPage)
  5678. {
  5679. --m_RegionInfo[endPage].allocCount;
  5680. if (m_RegionInfo[endPage].allocCount == 0)
  5681. m_RegionInfo[endPage].allocType = VMA_SUBALLOCATION_TYPE_FREE;
  5682. }
  5683. }
  5684. }
  5685. void VmaBlockBufferImageGranularity::Clear()
  5686. {
  5687. if (m_RegionInfo)
  5688. memset(m_RegionInfo, 0, m_RegionCount * sizeof(RegionInfo));
  5689. }
  5690. VmaBlockBufferImageGranularity::ValidationContext VmaBlockBufferImageGranularity::StartValidation(
  5691. const VkAllocationCallbacks* pAllocationCallbacks, bool isVirutal) const
  5692. {
  5693. ValidationContext ctx{ pAllocationCallbacks, VMA_NULL };
  5694. if (!isVirutal && IsEnabled())
  5695. {
  5696. ctx.pageAllocs = vma_new_array(pAllocationCallbacks, uint16_t, m_RegionCount);
  5697. memset(ctx.pageAllocs, 0, m_RegionCount * sizeof(uint16_t));
  5698. }
  5699. return ctx;
  5700. }
  5701. bool VmaBlockBufferImageGranularity::Validate(ValidationContext& ctx,
  5702. VkDeviceSize offset, VkDeviceSize size) const
  5703. {
  5704. if (IsEnabled())
  5705. {
  5706. uint32_t start = GetStartPage(offset);
  5707. ++ctx.pageAllocs[start];
  5708. VMA_VALIDATE(m_RegionInfo[start].allocCount > 0);
  5709. uint32_t end = GetEndPage(offset, size);
  5710. if (start != end)
  5711. {
  5712. ++ctx.pageAllocs[end];
  5713. VMA_VALIDATE(m_RegionInfo[end].allocCount > 0);
  5714. }
  5715. }
  5716. return true;
  5717. }
  5718. bool VmaBlockBufferImageGranularity::FinishValidation(ValidationContext& ctx) const
  5719. {
  5720. // Check proper page structure
  5721. if (IsEnabled())
  5722. {
  5723. VMA_ASSERT(ctx.pageAllocs != VMA_NULL && "Validation context not initialized!");
  5724. for (uint32_t page = 0; page < m_RegionCount; ++page)
  5725. {
  5726. VMA_VALIDATE(ctx.pageAllocs[page] == m_RegionInfo[page].allocCount);
  5727. }
  5728. vma_delete_array(ctx.allocCallbacks, ctx.pageAllocs, m_RegionCount);
  5729. ctx.pageAllocs = VMA_NULL;
  5730. }
  5731. return true;
  5732. }
  5733. uint32_t VmaBlockBufferImageGranularity::OffsetToPageIndex(VkDeviceSize offset) const
  5734. {
  5735. return static_cast<uint32_t>(offset >> VMA_BITSCAN_MSB(m_BufferImageGranularity));
  5736. }
  5737. void VmaBlockBufferImageGranularity::AllocPage(RegionInfo& page, uint8_t allocType)
  5738. {
  5739. // When current alloc type is free then it can be overriden by new type
  5740. if (page.allocCount == 0 || (page.allocCount > 0 && page.allocType == VMA_SUBALLOCATION_TYPE_FREE))
  5741. page.allocType = allocType;
  5742. ++page.allocCount;
  5743. }
  5744. #endif // _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY_FUNCTIONS
  5745. #endif // _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY
  5746. #if 0
  5747. #ifndef _VMA_BLOCK_METADATA_GENERIC
  5748. class VmaBlockMetadata_Generic : public VmaBlockMetadata
  5749. {
  5750. friend class VmaDefragmentationAlgorithm_Generic;
  5751. friend class VmaDefragmentationAlgorithm_Fast;
  5752. VMA_CLASS_NO_COPY(VmaBlockMetadata_Generic)
  5753. public:
  5754. VmaBlockMetadata_Generic(const VkAllocationCallbacks* pAllocationCallbacks,
  5755. VkDeviceSize bufferImageGranularity, bool isVirtual);
  5756. virtual ~VmaBlockMetadata_Generic() = default;
  5757. size_t GetAllocationCount() const override { return m_Suballocations.size() - m_FreeCount; }
  5758. VkDeviceSize GetSumFreeSize() const override { return m_SumFreeSize; }
  5759. bool IsEmpty() const override { return (m_Suballocations.size() == 1) && (m_FreeCount == 1); }
  5760. void Free(VmaAllocHandle allocHandle) override { FreeSuballocation(FindAtOffset((VkDeviceSize)allocHandle - 1)); }
  5761. VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const override { return (VkDeviceSize)allocHandle - 1; };
  5762. void Init(VkDeviceSize size) override;
  5763. bool Validate() const override;
  5764. void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const override;
  5765. void AddStatistics(VmaStatistics& inoutStats) const override;
  5766. #if VMA_STATS_STRING_ENABLED
  5767. void PrintDetailedMap(class VmaJsonWriter& json, uint32_t mapRefCount) const override;
  5768. #endif
  5769. bool CreateAllocationRequest(
  5770. VkDeviceSize allocSize,
  5771. VkDeviceSize allocAlignment,
  5772. bool upperAddress,
  5773. VmaSuballocationType allocType,
  5774. uint32_t strategy,
  5775. VmaAllocationRequest* pAllocationRequest) override;
  5776. VkResult CheckCorruption(const void* pBlockData) override;
  5777. void Alloc(
  5778. const VmaAllocationRequest& request,
  5779. VmaSuballocationType type,
  5780. void* userData) override;
  5781. void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) override;
  5782. void* GetAllocationUserData(VmaAllocHandle allocHandle) const override;
  5783. VmaAllocHandle GetAllocationListBegin() const override;
  5784. VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const override;
  5785. void Clear() override;
  5786. void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) override;
  5787. void DebugLogAllAllocations() const override;
  5788. private:
  5789. uint32_t m_FreeCount;
  5790. VkDeviceSize m_SumFreeSize;
  5791. VmaSuballocationList m_Suballocations;
  5792. // Suballocations that are free. Sorted by size, ascending.
  5793. VmaVector<VmaSuballocationList::iterator, VmaStlAllocator<VmaSuballocationList::iterator>> m_FreeSuballocationsBySize;
  5794. VkDeviceSize AlignAllocationSize(VkDeviceSize size) const { return IsVirtual() ? size : VmaAlignUp(size, (VkDeviceSize)16); }
  5795. VmaSuballocationList::iterator FindAtOffset(VkDeviceSize offset) const;
  5796. bool ValidateFreeSuballocationList() const;
  5797. // Checks if requested suballocation with given parameters can be placed in given pFreeSuballocItem.
  5798. // If yes, fills pOffset and returns true. If no, returns false.
  5799. bool CheckAllocation(
  5800. VkDeviceSize allocSize,
  5801. VkDeviceSize allocAlignment,
  5802. VmaSuballocationType allocType,
  5803. VmaSuballocationList::const_iterator suballocItem,
  5804. VmaAllocHandle* pAllocHandle) const;
  5805. // Given free suballocation, it merges it with following one, which must also be free.
  5806. void MergeFreeWithNext(VmaSuballocationList::iterator item);
  5807. // Releases given suballocation, making it free.
  5808. // Merges it with adjacent free suballocations if applicable.
  5809. // Returns iterator to new free suballocation at this place.
  5810. VmaSuballocationList::iterator FreeSuballocation(VmaSuballocationList::iterator suballocItem);
  5811. // Given free suballocation, it inserts it into sorted list of
  5812. // m_FreeSuballocationsBySize if it is suitable.
  5813. void RegisterFreeSuballocation(VmaSuballocationList::iterator item);
  5814. // Given free suballocation, it removes it from sorted list of
  5815. // m_FreeSuballocationsBySize if it is suitable.
  5816. void UnregisterFreeSuballocation(VmaSuballocationList::iterator item);
  5817. };
  5818. #ifndef _VMA_BLOCK_METADATA_GENERIC_FUNCTIONS
  5819. VmaBlockMetadata_Generic::VmaBlockMetadata_Generic(const VkAllocationCallbacks* pAllocationCallbacks,
  5820. VkDeviceSize bufferImageGranularity, bool isVirtual)
  5821. : VmaBlockMetadata(pAllocationCallbacks, bufferImageGranularity, isVirtual),
  5822. m_FreeCount(0),
  5823. m_SumFreeSize(0),
  5824. m_Suballocations(VmaStlAllocator<VmaSuballocation>(pAllocationCallbacks)),
  5825. m_FreeSuballocationsBySize(VmaStlAllocator<VmaSuballocationList::iterator>(pAllocationCallbacks)) {}
  5826. void VmaBlockMetadata_Generic::Init(VkDeviceSize size)
  5827. {
  5828. VmaBlockMetadata::Init(size);
  5829. m_FreeCount = 1;
  5830. m_SumFreeSize = size;
  5831. VmaSuballocation suballoc = {};
  5832. suballoc.offset = 0;
  5833. suballoc.size = size;
  5834. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  5835. m_Suballocations.push_back(suballoc);
  5836. m_FreeSuballocationsBySize.push_back(m_Suballocations.begin());
  5837. }
  5838. bool VmaBlockMetadata_Generic::Validate() const
  5839. {
  5840. VMA_VALIDATE(!m_Suballocations.empty());
  5841. // Expected offset of new suballocation as calculated from previous ones.
  5842. VkDeviceSize calculatedOffset = 0;
  5843. // Expected number of free suballocations as calculated from traversing their list.
  5844. uint32_t calculatedFreeCount = 0;
  5845. // Expected sum size of free suballocations as calculated from traversing their list.
  5846. VkDeviceSize calculatedSumFreeSize = 0;
  5847. // Expected number of free suballocations that should be registered in
  5848. // m_FreeSuballocationsBySize calculated from traversing their list.
  5849. size_t freeSuballocationsToRegister = 0;
  5850. // True if previous visited suballocation was free.
  5851. bool prevFree = false;
  5852. const VkDeviceSize debugMargin = GetDebugMargin();
  5853. for (const auto& subAlloc : m_Suballocations)
  5854. {
  5855. // Actual offset of this suballocation doesn't match expected one.
  5856. VMA_VALIDATE(subAlloc.offset == calculatedOffset);
  5857. const bool currFree = (subAlloc.type == VMA_SUBALLOCATION_TYPE_FREE);
  5858. // Two adjacent free suballocations are invalid. They should be merged.
  5859. VMA_VALIDATE(!prevFree || !currFree);
  5860. VmaAllocation alloc = (VmaAllocation)subAlloc.userData;
  5861. if (!IsVirtual())
  5862. {
  5863. VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE));
  5864. }
  5865. if (currFree)
  5866. {
  5867. calculatedSumFreeSize += subAlloc.size;
  5868. ++calculatedFreeCount;
  5869. ++freeSuballocationsToRegister;
  5870. // Margin required between allocations - every free space must be at least that large.
  5871. VMA_VALIDATE(subAlloc.size >= debugMargin);
  5872. }
  5873. else
  5874. {
  5875. if (!IsVirtual())
  5876. {
  5877. VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == subAlloc.offset + 1);
  5878. VMA_VALIDATE(alloc->GetSize() == subAlloc.size);
  5879. }
  5880. // Margin required between allocations - previous allocation must be free.
  5881. VMA_VALIDATE(debugMargin == 0 || prevFree);
  5882. }
  5883. calculatedOffset += subAlloc.size;
  5884. prevFree = currFree;
  5885. }
  5886. // Number of free suballocations registered in m_FreeSuballocationsBySize doesn't
  5887. // match expected one.
  5888. VMA_VALIDATE(m_FreeSuballocationsBySize.size() == freeSuballocationsToRegister);
  5889. VkDeviceSize lastSize = 0;
  5890. for (size_t i = 0; i < m_FreeSuballocationsBySize.size(); ++i)
  5891. {
  5892. VmaSuballocationList::iterator suballocItem = m_FreeSuballocationsBySize[i];
  5893. // Only free suballocations can be registered in m_FreeSuballocationsBySize.
  5894. VMA_VALIDATE(suballocItem->type == VMA_SUBALLOCATION_TYPE_FREE);
  5895. // They must be sorted by size ascending.
  5896. VMA_VALIDATE(suballocItem->size >= lastSize);
  5897. lastSize = suballocItem->size;
  5898. }
  5899. // Check if totals match calculated values.
  5900. VMA_VALIDATE(ValidateFreeSuballocationList());
  5901. VMA_VALIDATE(calculatedOffset == GetSize());
  5902. VMA_VALIDATE(calculatedSumFreeSize == m_SumFreeSize);
  5903. VMA_VALIDATE(calculatedFreeCount == m_FreeCount);
  5904. return true;
  5905. }
  5906. void VmaBlockMetadata_Generic::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const
  5907. {
  5908. const uint32_t rangeCount = (uint32_t)m_Suballocations.size();
  5909. inoutStats.statistics.blockCount++;
  5910. inoutStats.statistics.blockBytes += GetSize();
  5911. for (const auto& suballoc : m_Suballocations)
  5912. {
  5913. if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  5914. VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size);
  5915. else
  5916. VmaAddDetailedStatisticsUnusedRange(inoutStats, suballoc.size);
  5917. }
  5918. }
  5919. void VmaBlockMetadata_Generic::AddStatistics(VmaStatistics& inoutStats) const
  5920. {
  5921. inoutStats.blockCount++;
  5922. inoutStats.allocationCount += (uint32_t)m_Suballocations.size() - m_FreeCount;
  5923. inoutStats.blockBytes += GetSize();
  5924. inoutStats.allocationBytes += GetSize() - m_SumFreeSize;
  5925. }
  5926. #if VMA_STATS_STRING_ENABLED
  5927. void VmaBlockMetadata_Generic::PrintDetailedMap(class VmaJsonWriter& json, uint32_t mapRefCount) const
  5928. {
  5929. PrintDetailedMap_Begin(json,
  5930. m_SumFreeSize, // unusedBytes
  5931. m_Suballocations.size() - (size_t)m_FreeCount, // allocationCount
  5932. m_FreeCount, // unusedRangeCount
  5933. mapRefCount);
  5934. for (const auto& suballoc : m_Suballocations)
  5935. {
  5936. if (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE)
  5937. {
  5938. PrintDetailedMap_UnusedRange(json, suballoc.offset, suballoc.size);
  5939. }
  5940. else
  5941. {
  5942. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData);
  5943. }
  5944. }
  5945. PrintDetailedMap_End(json);
  5946. }
  5947. #endif // VMA_STATS_STRING_ENABLED
  5948. bool VmaBlockMetadata_Generic::CreateAllocationRequest(
  5949. VkDeviceSize allocSize,
  5950. VkDeviceSize allocAlignment,
  5951. bool upperAddress,
  5952. VmaSuballocationType allocType,
  5953. uint32_t strategy,
  5954. VmaAllocationRequest* pAllocationRequest)
  5955. {
  5956. VMA_ASSERT(allocSize > 0);
  5957. VMA_ASSERT(!upperAddress);
  5958. VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
  5959. VMA_ASSERT(pAllocationRequest != VMA_NULL);
  5960. VMA_HEAVY_ASSERT(Validate());
  5961. allocSize = AlignAllocationSize(allocSize);
  5962. pAllocationRequest->type = VmaAllocationRequestType::Normal;
  5963. pAllocationRequest->size = allocSize;
  5964. const VkDeviceSize debugMargin = GetDebugMargin();
  5965. // There is not enough total free space in this block to fulfill the request: Early return.
  5966. if (m_SumFreeSize < allocSize + debugMargin)
  5967. {
  5968. return false;
  5969. }
  5970. // New algorithm, efficiently searching freeSuballocationsBySize.
  5971. const size_t freeSuballocCount = m_FreeSuballocationsBySize.size();
  5972. if (freeSuballocCount > 0)
  5973. {
  5974. if (strategy == 0 ||
  5975. strategy == VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT)
  5976. {
  5977. // Find first free suballocation with size not less than allocSize + debugMargin.
  5978. VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess(
  5979. m_FreeSuballocationsBySize.data(),
  5980. m_FreeSuballocationsBySize.data() + freeSuballocCount,
  5981. allocSize + debugMargin,
  5982. VmaSuballocationItemSizeLess());
  5983. size_t index = it - m_FreeSuballocationsBySize.data();
  5984. for (; index < freeSuballocCount; ++index)
  5985. {
  5986. if (CheckAllocation(
  5987. allocSize,
  5988. allocAlignment,
  5989. allocType,
  5990. m_FreeSuballocationsBySize[index],
  5991. &pAllocationRequest->allocHandle))
  5992. {
  5993. pAllocationRequest->item = m_FreeSuballocationsBySize[index];
  5994. return true;
  5995. }
  5996. }
  5997. }
  5998. else if (strategy == VMA_ALLOCATION_INTERNAL_STRATEGY_MIN_OFFSET)
  5999. {
  6000. for (VmaSuballocationList::iterator it = m_Suballocations.begin();
  6001. it != m_Suballocations.end();
  6002. ++it)
  6003. {
  6004. if (it->type == VMA_SUBALLOCATION_TYPE_FREE && CheckAllocation(
  6005. allocSize,
  6006. allocAlignment,
  6007. allocType,
  6008. it,
  6009. &pAllocationRequest->allocHandle))
  6010. {
  6011. pAllocationRequest->item = it;
  6012. return true;
  6013. }
  6014. }
  6015. }
  6016. else
  6017. {
  6018. VMA_ASSERT(strategy & (VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT | VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT ));
  6019. // Search staring from biggest suballocations.
  6020. for (size_t index = freeSuballocCount; index--; )
  6021. {
  6022. if (CheckAllocation(
  6023. allocSize,
  6024. allocAlignment,
  6025. allocType,
  6026. m_FreeSuballocationsBySize[index],
  6027. &pAllocationRequest->allocHandle))
  6028. {
  6029. pAllocationRequest->item = m_FreeSuballocationsBySize[index];
  6030. return true;
  6031. }
  6032. }
  6033. }
  6034. }
  6035. return false;
  6036. }
  6037. VkResult VmaBlockMetadata_Generic::CheckCorruption(const void* pBlockData)
  6038. {
  6039. for (auto& suballoc : m_Suballocations)
  6040. {
  6041. if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  6042. {
  6043. if (!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size))
  6044. {
  6045. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
  6046. return VK_ERROR_UNKNOWN_COPY;
  6047. }
  6048. }
  6049. }
  6050. return VK_SUCCESS;
  6051. }
  6052. void VmaBlockMetadata_Generic::Alloc(
  6053. const VmaAllocationRequest& request,
  6054. VmaSuballocationType type,
  6055. void* userData)
  6056. {
  6057. VMA_ASSERT(request.type == VmaAllocationRequestType::Normal);
  6058. VMA_ASSERT(request.item != m_Suballocations.end());
  6059. VmaSuballocation& suballoc = *request.item;
  6060. // Given suballocation is a free block.
  6061. VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  6062. // Given offset is inside this suballocation.
  6063. VMA_ASSERT((VkDeviceSize)request.allocHandle - 1 >= suballoc.offset);
  6064. const VkDeviceSize paddingBegin = (VkDeviceSize)request.allocHandle - suballoc.offset - 1;
  6065. VMA_ASSERT(suballoc.size >= paddingBegin + request.size);
  6066. const VkDeviceSize paddingEnd = suballoc.size - paddingBegin - request.size;
  6067. // Unregister this free suballocation from m_FreeSuballocationsBySize and update
  6068. // it to become used.
  6069. UnregisterFreeSuballocation(request.item);
  6070. suballoc.offset = (VkDeviceSize)request.allocHandle - 1;
  6071. suballoc.size = request.size;
  6072. suballoc.type = type;
  6073. suballoc.userData = userData;
  6074. // If there are any free bytes remaining at the end, insert new free suballocation after current one.
  6075. if (paddingEnd)
  6076. {
  6077. VmaSuballocation paddingSuballoc = {};
  6078. paddingSuballoc.offset = suballoc.offset + suballoc.size;
  6079. paddingSuballoc.size = paddingEnd;
  6080. paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  6081. VmaSuballocationList::iterator next = request.item;
  6082. ++next;
  6083. const VmaSuballocationList::iterator paddingEndItem =
  6084. m_Suballocations.insert(next, paddingSuballoc);
  6085. RegisterFreeSuballocation(paddingEndItem);
  6086. }
  6087. // If there are any free bytes remaining at the beginning, insert new free suballocation before current one.
  6088. if (paddingBegin)
  6089. {
  6090. VmaSuballocation paddingSuballoc = {};
  6091. paddingSuballoc.offset = suballoc.offset - paddingBegin;
  6092. paddingSuballoc.size = paddingBegin;
  6093. paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  6094. const VmaSuballocationList::iterator paddingBeginItem =
  6095. m_Suballocations.insert(request.item, paddingSuballoc);
  6096. RegisterFreeSuballocation(paddingBeginItem);
  6097. }
  6098. // Update totals.
  6099. m_FreeCount = m_FreeCount - 1;
  6100. if (paddingBegin > 0)
  6101. {
  6102. ++m_FreeCount;
  6103. }
  6104. if (paddingEnd > 0)
  6105. {
  6106. ++m_FreeCount;
  6107. }
  6108. m_SumFreeSize -= request.size;
  6109. }
  6110. void VmaBlockMetadata_Generic::GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo)
  6111. {
  6112. outInfo.offset = (VkDeviceSize)allocHandle - 1;
  6113. const VmaSuballocation& suballoc = *FindAtOffset(outInfo.offset);
  6114. outInfo.size = suballoc.size;
  6115. outInfo.pUserData = suballoc.userData;
  6116. }
  6117. void* VmaBlockMetadata_Generic::GetAllocationUserData(VmaAllocHandle allocHandle) const
  6118. {
  6119. return FindAtOffset((VkDeviceSize)allocHandle - 1)->userData;
  6120. }
  6121. VmaAllocHandle VmaBlockMetadata_Generic::GetAllocationListBegin() const
  6122. {
  6123. if (IsEmpty())
  6124. return VK_NULL_HANDLE;
  6125. for (const auto& suballoc : m_Suballocations)
  6126. {
  6127. if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  6128. return (VmaAllocHandle)(suballoc.offset + 1);
  6129. }
  6130. VMA_ASSERT(false && "Should contain at least 1 allocation!");
  6131. return VK_NULL_HANDLE;
  6132. }
  6133. VmaAllocHandle VmaBlockMetadata_Generic::GetNextAllocation(VmaAllocHandle prevAlloc) const
  6134. {
  6135. VmaSuballocationList::const_iterator prev = FindAtOffset((VkDeviceSize)prevAlloc - 1);
  6136. for (VmaSuballocationList::const_iterator it = ++prev; it != m_Suballocations.end(); ++it)
  6137. {
  6138. if (it->type != VMA_SUBALLOCATION_TYPE_FREE)
  6139. return (VmaAllocHandle)(it->offset + 1);
  6140. }
  6141. return VK_NULL_HANDLE;
  6142. }
  6143. void VmaBlockMetadata_Generic::Clear()
  6144. {
  6145. const VkDeviceSize size = GetSize();
  6146. VMA_ASSERT(IsVirtual());
  6147. m_FreeCount = 1;
  6148. m_SumFreeSize = size;
  6149. m_Suballocations.clear();
  6150. m_FreeSuballocationsBySize.clear();
  6151. VmaSuballocation suballoc = {};
  6152. suballoc.offset = 0;
  6153. suballoc.size = size;
  6154. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  6155. m_Suballocations.push_back(suballoc);
  6156. m_FreeSuballocationsBySize.push_back(m_Suballocations.begin());
  6157. }
  6158. void VmaBlockMetadata_Generic::SetAllocationUserData(VmaAllocHandle allocHandle, void* userData)
  6159. {
  6160. VmaSuballocation& suballoc = *FindAtOffset((VkDeviceSize)allocHandle - 1);
  6161. suballoc.userData = userData;
  6162. }
  6163. void VmaBlockMetadata_Generic::DebugLogAllAllocations() const
  6164. {
  6165. for (const auto& suballoc : m_Suballocations)
  6166. {
  6167. if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  6168. DebugLogAllocation(suballoc.offset, suballoc.size, suballoc.userData);
  6169. }
  6170. }
  6171. VmaSuballocationList::iterator VmaBlockMetadata_Generic::FindAtOffset(VkDeviceSize offset) const
  6172. {
  6173. VMA_HEAVY_ASSERT(!m_Suballocations.empty());
  6174. const VkDeviceSize last = m_Suballocations.rbegin()->offset;
  6175. if (last == offset)
  6176. return m_Suballocations.rbegin().drop_const();
  6177. const VkDeviceSize first = m_Suballocations.begin()->offset;
  6178. if (first == offset)
  6179. return m_Suballocations.begin().drop_const();
  6180. const size_t suballocCount = m_Suballocations.size();
  6181. const VkDeviceSize step = (last - first + m_Suballocations.begin()->size) / suballocCount;
  6182. auto findSuballocation = [&](auto begin, auto end) -> VmaSuballocationList::iterator
  6183. {
  6184. for (auto suballocItem = begin;
  6185. suballocItem != end;
  6186. ++suballocItem)
  6187. {
  6188. if (suballocItem->offset == offset)
  6189. return suballocItem.drop_const();
  6190. }
  6191. VMA_ASSERT(false && "Not found!");
  6192. return m_Suballocations.end().drop_const();
  6193. };
  6194. // If requested offset is closer to the end of range, search from the end
  6195. if (offset - first > suballocCount * step / 2)
  6196. {
  6197. return findSuballocation(m_Suballocations.rbegin(), m_Suballocations.rend());
  6198. }
  6199. return findSuballocation(m_Suballocations.begin(), m_Suballocations.end());
  6200. }
  6201. bool VmaBlockMetadata_Generic::ValidateFreeSuballocationList() const
  6202. {
  6203. VkDeviceSize lastSize = 0;
  6204. for (size_t i = 0, count = m_FreeSuballocationsBySize.size(); i < count; ++i)
  6205. {
  6206. const VmaSuballocationList::iterator it = m_FreeSuballocationsBySize[i];
  6207. VMA_VALIDATE(it->type == VMA_SUBALLOCATION_TYPE_FREE);
  6208. VMA_VALIDATE(it->size >= lastSize);
  6209. lastSize = it->size;
  6210. }
  6211. return true;
  6212. }
  6213. bool VmaBlockMetadata_Generic::CheckAllocation(
  6214. VkDeviceSize allocSize,
  6215. VkDeviceSize allocAlignment,
  6216. VmaSuballocationType allocType,
  6217. VmaSuballocationList::const_iterator suballocItem,
  6218. VmaAllocHandle* pAllocHandle) const
  6219. {
  6220. VMA_ASSERT(allocSize > 0);
  6221. VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
  6222. VMA_ASSERT(suballocItem != m_Suballocations.cend());
  6223. VMA_ASSERT(pAllocHandle != VMA_NULL);
  6224. const VkDeviceSize debugMargin = GetDebugMargin();
  6225. const VkDeviceSize bufferImageGranularity = GetBufferImageGranularity();
  6226. const VmaSuballocation& suballoc = *suballocItem;
  6227. VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  6228. // Size of this suballocation is too small for this request: Early return.
  6229. if (suballoc.size < allocSize)
  6230. {
  6231. return false;
  6232. }
  6233. // Start from offset equal to beginning of this suballocation.
  6234. VkDeviceSize offset = suballoc.offset + (suballocItem == m_Suballocations.cbegin() ? 0 : GetDebugMargin());
  6235. // Apply debugMargin from the end of previous alloc.
  6236. if (debugMargin > 0)
  6237. {
  6238. offset += debugMargin;
  6239. }
  6240. // Apply alignment.
  6241. offset = VmaAlignUp(offset, allocAlignment);
  6242. // Check previous suballocations for BufferImageGranularity conflicts.
  6243. // Make bigger alignment if necessary.
  6244. if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment)
  6245. {
  6246. bool bufferImageGranularityConflict = false;
  6247. VmaSuballocationList::const_iterator prevSuballocItem = suballocItem;
  6248. while (prevSuballocItem != m_Suballocations.cbegin())
  6249. {
  6250. --prevSuballocItem;
  6251. const VmaSuballocation& prevSuballoc = *prevSuballocItem;
  6252. if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, offset, bufferImageGranularity))
  6253. {
  6254. if (VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
  6255. {
  6256. bufferImageGranularityConflict = true;
  6257. break;
  6258. }
  6259. }
  6260. else
  6261. // Already on previous page.
  6262. break;
  6263. }
  6264. if (bufferImageGranularityConflict)
  6265. {
  6266. offset = VmaAlignUp(offset, bufferImageGranularity);
  6267. }
  6268. }
  6269. // Calculate padding at the beginning based on current offset.
  6270. const VkDeviceSize paddingBegin = offset - suballoc.offset;
  6271. // Fail if requested size plus margin after is bigger than size of this suballocation.
  6272. if (paddingBegin + allocSize + debugMargin > suballoc.size)
  6273. {
  6274. return false;
  6275. }
  6276. // Check next suballocations for BufferImageGranularity conflicts.
  6277. // If conflict exists, allocation cannot be made here.
  6278. if (allocSize % bufferImageGranularity || offset % bufferImageGranularity)
  6279. {
  6280. VmaSuballocationList::const_iterator nextSuballocItem = suballocItem;
  6281. ++nextSuballocItem;
  6282. while (nextSuballocItem != m_Suballocations.cend())
  6283. {
  6284. const VmaSuballocation& nextSuballoc = *nextSuballocItem;
  6285. if (VmaBlocksOnSamePage(offset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  6286. {
  6287. if (VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
  6288. {
  6289. return false;
  6290. }
  6291. }
  6292. else
  6293. {
  6294. // Already on next page.
  6295. break;
  6296. }
  6297. ++nextSuballocItem;
  6298. }
  6299. }
  6300. *pAllocHandle = (VmaAllocHandle)(offset + 1);
  6301. // All tests passed: Success. pAllocHandle is already filled.
  6302. return true;
  6303. }
  6304. void VmaBlockMetadata_Generic::MergeFreeWithNext(VmaSuballocationList::iterator item)
  6305. {
  6306. VMA_ASSERT(item != m_Suballocations.end());
  6307. VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
  6308. VmaSuballocationList::iterator nextItem = item;
  6309. ++nextItem;
  6310. VMA_ASSERT(nextItem != m_Suballocations.end());
  6311. VMA_ASSERT(nextItem->type == VMA_SUBALLOCATION_TYPE_FREE);
  6312. item->size += nextItem->size;
  6313. --m_FreeCount;
  6314. m_Suballocations.erase(nextItem);
  6315. }
  6316. VmaSuballocationList::iterator VmaBlockMetadata_Generic::FreeSuballocation(VmaSuballocationList::iterator suballocItem)
  6317. {
  6318. // Change this suballocation to be marked as free.
  6319. VmaSuballocation& suballoc = *suballocItem;
  6320. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  6321. suballoc.userData = VMA_NULL;
  6322. // Update totals.
  6323. ++m_FreeCount;
  6324. m_SumFreeSize += suballoc.size;
  6325. // Merge with previous and/or next suballocation if it's also free.
  6326. bool mergeWithNext = false;
  6327. bool mergeWithPrev = false;
  6328. VmaSuballocationList::iterator nextItem = suballocItem;
  6329. ++nextItem;
  6330. if ((nextItem != m_Suballocations.end()) && (nextItem->type == VMA_SUBALLOCATION_TYPE_FREE))
  6331. {
  6332. mergeWithNext = true;
  6333. }
  6334. VmaSuballocationList::iterator prevItem = suballocItem;
  6335. if (suballocItem != m_Suballocations.begin())
  6336. {
  6337. --prevItem;
  6338. if (prevItem->type == VMA_SUBALLOCATION_TYPE_FREE)
  6339. {
  6340. mergeWithPrev = true;
  6341. }
  6342. }
  6343. if (mergeWithNext)
  6344. {
  6345. UnregisterFreeSuballocation(nextItem);
  6346. MergeFreeWithNext(suballocItem);
  6347. }
  6348. if (mergeWithPrev)
  6349. {
  6350. UnregisterFreeSuballocation(prevItem);
  6351. MergeFreeWithNext(prevItem);
  6352. RegisterFreeSuballocation(prevItem);
  6353. return prevItem;
  6354. }
  6355. else
  6356. {
  6357. RegisterFreeSuballocation(suballocItem);
  6358. return suballocItem;
  6359. }
  6360. }
  6361. void VmaBlockMetadata_Generic::RegisterFreeSuballocation(VmaSuballocationList::iterator item)
  6362. {
  6363. VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
  6364. VMA_ASSERT(item->size > 0);
  6365. // You may want to enable this validation at the beginning or at the end of
  6366. // this function, depending on what do you want to check.
  6367. VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  6368. if (m_FreeSuballocationsBySize.empty())
  6369. {
  6370. m_FreeSuballocationsBySize.push_back(item);
  6371. }
  6372. else
  6373. {
  6374. VmaVectorInsertSorted<VmaSuballocationItemSizeLess>(m_FreeSuballocationsBySize, item);
  6375. }
  6376. //VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  6377. }
  6378. void VmaBlockMetadata_Generic::UnregisterFreeSuballocation(VmaSuballocationList::iterator item)
  6379. {
  6380. VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
  6381. VMA_ASSERT(item->size > 0);
  6382. // You may want to enable this validation at the beginning or at the end of
  6383. // this function, depending on what do you want to check.
  6384. VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  6385. VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess(
  6386. m_FreeSuballocationsBySize.data(),
  6387. m_FreeSuballocationsBySize.data() + m_FreeSuballocationsBySize.size(),
  6388. item,
  6389. VmaSuballocationItemSizeLess());
  6390. for (size_t index = it - m_FreeSuballocationsBySize.data();
  6391. index < m_FreeSuballocationsBySize.size();
  6392. ++index)
  6393. {
  6394. if (m_FreeSuballocationsBySize[index] == item)
  6395. {
  6396. VmaVectorRemove(m_FreeSuballocationsBySize, index);
  6397. return;
  6398. }
  6399. VMA_ASSERT((m_FreeSuballocationsBySize[index]->size == item->size) && "Not found.");
  6400. }
  6401. VMA_ASSERT(0 && "Not found.");
  6402. //VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  6403. }
  6404. #endif // _VMA_BLOCK_METADATA_GENERIC_FUNCTIONS
  6405. #endif // _VMA_BLOCK_METADATA_GENERIC
  6406. #endif // #if 0
  6407. #ifndef _VMA_BLOCK_METADATA_LINEAR
  6408. /*
  6409. Allocations and their references in internal data structure look like this:
  6410. if(m_2ndVectorMode == SECOND_VECTOR_EMPTY):
  6411. 0 +-------+
  6412. | |
  6413. | |
  6414. | |
  6415. +-------+
  6416. | Alloc | 1st[m_1stNullItemsBeginCount]
  6417. +-------+
  6418. | Alloc | 1st[m_1stNullItemsBeginCount + 1]
  6419. +-------+
  6420. | ... |
  6421. +-------+
  6422. | Alloc | 1st[1st.size() - 1]
  6423. +-------+
  6424. | |
  6425. | |
  6426. | |
  6427. GetSize() +-------+
  6428. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER):
  6429. 0 +-------+
  6430. | Alloc | 2nd[0]
  6431. +-------+
  6432. | Alloc | 2nd[1]
  6433. +-------+
  6434. | ... |
  6435. +-------+
  6436. | Alloc | 2nd[2nd.size() - 1]
  6437. +-------+
  6438. | |
  6439. | |
  6440. | |
  6441. +-------+
  6442. | Alloc | 1st[m_1stNullItemsBeginCount]
  6443. +-------+
  6444. | Alloc | 1st[m_1stNullItemsBeginCount + 1]
  6445. +-------+
  6446. | ... |
  6447. +-------+
  6448. | Alloc | 1st[1st.size() - 1]
  6449. +-------+
  6450. | |
  6451. GetSize() +-------+
  6452. if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK):
  6453. 0 +-------+
  6454. | |
  6455. | |
  6456. | |
  6457. +-------+
  6458. | Alloc | 1st[m_1stNullItemsBeginCount]
  6459. +-------+
  6460. | Alloc | 1st[m_1stNullItemsBeginCount + 1]
  6461. +-------+
  6462. | ... |
  6463. +-------+
  6464. | Alloc | 1st[1st.size() - 1]
  6465. +-------+
  6466. | |
  6467. | |
  6468. | |
  6469. +-------+
  6470. | Alloc | 2nd[2nd.size() - 1]
  6471. +-------+
  6472. | ... |
  6473. +-------+
  6474. | Alloc | 2nd[1]
  6475. +-------+
  6476. | Alloc | 2nd[0]
  6477. GetSize() +-------+
  6478. */
  6479. class VmaBlockMetadata_Linear : public VmaBlockMetadata
  6480. {
  6481. VMA_CLASS_NO_COPY(VmaBlockMetadata_Linear)
  6482. public:
  6483. VmaBlockMetadata_Linear(const VkAllocationCallbacks* pAllocationCallbacks,
  6484. VkDeviceSize bufferImageGranularity, bool isVirtual);
  6485. virtual ~VmaBlockMetadata_Linear() = default;
  6486. VkDeviceSize GetSumFreeSize() const override { return m_SumFreeSize; }
  6487. bool IsEmpty() const override { return GetAllocationCount() == 0; }
  6488. VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const override { return (VkDeviceSize)allocHandle - 1; };
  6489. void Init(VkDeviceSize size) override;
  6490. bool Validate() const override;
  6491. size_t GetAllocationCount() const override;
  6492. size_t GetFreeRegionsCount() const override;
  6493. void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const override;
  6494. void AddStatistics(VmaStatistics& inoutStats) const override;
  6495. #if VMA_STATS_STRING_ENABLED
  6496. void PrintDetailedMap(class VmaJsonWriter& json) const override;
  6497. #endif
  6498. bool CreateAllocationRequest(
  6499. VkDeviceSize allocSize,
  6500. VkDeviceSize allocAlignment,
  6501. bool upperAddress,
  6502. VmaSuballocationType allocType,
  6503. uint32_t strategy,
  6504. VmaAllocationRequest* pAllocationRequest) override;
  6505. VkResult CheckCorruption(const void* pBlockData) override;
  6506. void Alloc(
  6507. const VmaAllocationRequest& request,
  6508. VmaSuballocationType type,
  6509. void* userData) override;
  6510. void Free(VmaAllocHandle allocHandle) override;
  6511. void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) override;
  6512. void* GetAllocationUserData(VmaAllocHandle allocHandle) const override;
  6513. VmaAllocHandle GetAllocationListBegin() const override;
  6514. VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const override;
  6515. VkDeviceSize GetNextFreeRegionSize(VmaAllocHandle alloc) const override;
  6516. void Clear() override;
  6517. void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) override;
  6518. void DebugLogAllAllocations() const override;
  6519. private:
  6520. /*
  6521. There are two suballocation vectors, used in ping-pong way.
  6522. The one with index m_1stVectorIndex is called 1st.
  6523. The one with index (m_1stVectorIndex ^ 1) is called 2nd.
  6524. 2nd can be non-empty only when 1st is not empty.
  6525. When 2nd is not empty, m_2ndVectorMode indicates its mode of operation.
  6526. */
  6527. typedef VmaVector<VmaSuballocation, VmaStlAllocator<VmaSuballocation>> SuballocationVectorType;
  6528. enum SECOND_VECTOR_MODE
  6529. {
  6530. SECOND_VECTOR_EMPTY,
  6531. /*
  6532. Suballocations in 2nd vector are created later than the ones in 1st, but they
  6533. all have smaller offset.
  6534. */
  6535. SECOND_VECTOR_RING_BUFFER,
  6536. /*
  6537. Suballocations in 2nd vector are upper side of double stack.
  6538. They all have offsets higher than those in 1st vector.
  6539. Top of this stack means smaller offsets, but higher indices in this vector.
  6540. */
  6541. SECOND_VECTOR_DOUBLE_STACK,
  6542. };
  6543. VkDeviceSize m_SumFreeSize;
  6544. SuballocationVectorType m_Suballocations0, m_Suballocations1;
  6545. uint32_t m_1stVectorIndex;
  6546. SECOND_VECTOR_MODE m_2ndVectorMode;
  6547. // Number of items in 1st vector with hAllocation = null at the beginning.
  6548. size_t m_1stNullItemsBeginCount;
  6549. // Number of other items in 1st vector with hAllocation = null somewhere in the middle.
  6550. size_t m_1stNullItemsMiddleCount;
  6551. // Number of items in 2nd vector with hAllocation = null.
  6552. size_t m_2ndNullItemsCount;
  6553. SuballocationVectorType& AccessSuballocations1st() { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; }
  6554. SuballocationVectorType& AccessSuballocations2nd() { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; }
  6555. const SuballocationVectorType& AccessSuballocations1st() const { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; }
  6556. const SuballocationVectorType& AccessSuballocations2nd() const { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; }
  6557. VmaSuballocation& FindSuballocation(VkDeviceSize offset) const;
  6558. bool ShouldCompact1st() const;
  6559. void CleanupAfterFree();
  6560. bool CreateAllocationRequest_LowerAddress(
  6561. VkDeviceSize allocSize,
  6562. VkDeviceSize allocAlignment,
  6563. VmaSuballocationType allocType,
  6564. uint32_t strategy,
  6565. VmaAllocationRequest* pAllocationRequest);
  6566. bool CreateAllocationRequest_UpperAddress(
  6567. VkDeviceSize allocSize,
  6568. VkDeviceSize allocAlignment,
  6569. VmaSuballocationType allocType,
  6570. uint32_t strategy,
  6571. VmaAllocationRequest* pAllocationRequest);
  6572. };
  6573. #ifndef _VMA_BLOCK_METADATA_LINEAR_FUNCTIONS
  6574. VmaBlockMetadata_Linear::VmaBlockMetadata_Linear(const VkAllocationCallbacks* pAllocationCallbacks,
  6575. VkDeviceSize bufferImageGranularity, bool isVirtual)
  6576. : VmaBlockMetadata(pAllocationCallbacks, bufferImageGranularity, isVirtual),
  6577. m_SumFreeSize(0),
  6578. m_Suballocations0(VmaStlAllocator<VmaSuballocation>(pAllocationCallbacks)),
  6579. m_Suballocations1(VmaStlAllocator<VmaSuballocation>(pAllocationCallbacks)),
  6580. m_1stVectorIndex(0),
  6581. m_2ndVectorMode(SECOND_VECTOR_EMPTY),
  6582. m_1stNullItemsBeginCount(0),
  6583. m_1stNullItemsMiddleCount(0),
  6584. m_2ndNullItemsCount(0) {}
  6585. void VmaBlockMetadata_Linear::Init(VkDeviceSize size)
  6586. {
  6587. VmaBlockMetadata::Init(size);
  6588. m_SumFreeSize = size;
  6589. }
  6590. bool VmaBlockMetadata_Linear::Validate() const
  6591. {
  6592. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  6593. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  6594. VMA_VALIDATE(suballocations2nd.empty() == (m_2ndVectorMode == SECOND_VECTOR_EMPTY));
  6595. VMA_VALIDATE(!suballocations1st.empty() ||
  6596. suballocations2nd.empty() ||
  6597. m_2ndVectorMode != SECOND_VECTOR_RING_BUFFER);
  6598. if (!suballocations1st.empty())
  6599. {
  6600. // Null item at the beginning should be accounted into m_1stNullItemsBeginCount.
  6601. VMA_VALIDATE(suballocations1st[m_1stNullItemsBeginCount].type != VMA_SUBALLOCATION_TYPE_FREE);
  6602. // Null item at the end should be just pop_back().
  6603. VMA_VALIDATE(suballocations1st.back().type != VMA_SUBALLOCATION_TYPE_FREE);
  6604. }
  6605. if (!suballocations2nd.empty())
  6606. {
  6607. // Null item at the end should be just pop_back().
  6608. VMA_VALIDATE(suballocations2nd.back().type != VMA_SUBALLOCATION_TYPE_FREE);
  6609. }
  6610. VMA_VALIDATE(m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount <= suballocations1st.size());
  6611. VMA_VALIDATE(m_2ndNullItemsCount <= suballocations2nd.size());
  6612. VkDeviceSize sumUsedSize = 0;
  6613. const size_t suballoc1stCount = suballocations1st.size();
  6614. const VkDeviceSize debugMargin = GetDebugMargin();
  6615. VkDeviceSize offset = 0;
  6616. if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  6617. {
  6618. const size_t suballoc2ndCount = suballocations2nd.size();
  6619. size_t nullItem2ndCount = 0;
  6620. for (size_t i = 0; i < suballoc2ndCount; ++i)
  6621. {
  6622. const VmaSuballocation& suballoc = suballocations2nd[i];
  6623. const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  6624. VmaAllocation const alloc = (VmaAllocation)suballoc.userData;
  6625. if (!IsVirtual())
  6626. {
  6627. VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE));
  6628. }
  6629. VMA_VALIDATE(suballoc.offset >= offset);
  6630. if (!currFree)
  6631. {
  6632. if (!IsVirtual())
  6633. {
  6634. VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == suballoc.offset + 1);
  6635. VMA_VALIDATE(alloc->GetSize() == suballoc.size);
  6636. }
  6637. sumUsedSize += suballoc.size;
  6638. }
  6639. else
  6640. {
  6641. ++nullItem2ndCount;
  6642. }
  6643. offset = suballoc.offset + suballoc.size + debugMargin;
  6644. }
  6645. VMA_VALIDATE(nullItem2ndCount == m_2ndNullItemsCount);
  6646. }
  6647. for (size_t i = 0; i < m_1stNullItemsBeginCount; ++i)
  6648. {
  6649. const VmaSuballocation& suballoc = suballocations1st[i];
  6650. VMA_VALIDATE(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE &&
  6651. suballoc.userData == VMA_NULL);
  6652. }
  6653. size_t nullItem1stCount = m_1stNullItemsBeginCount;
  6654. for (size_t i = m_1stNullItemsBeginCount; i < suballoc1stCount; ++i)
  6655. {
  6656. const VmaSuballocation& suballoc = suballocations1st[i];
  6657. const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  6658. VmaAllocation const alloc = (VmaAllocation)suballoc.userData;
  6659. if (!IsVirtual())
  6660. {
  6661. VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE));
  6662. }
  6663. VMA_VALIDATE(suballoc.offset >= offset);
  6664. VMA_VALIDATE(i >= m_1stNullItemsBeginCount || currFree);
  6665. if (!currFree)
  6666. {
  6667. if (!IsVirtual())
  6668. {
  6669. VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == suballoc.offset + 1);
  6670. VMA_VALIDATE(alloc->GetSize() == suballoc.size);
  6671. }
  6672. sumUsedSize += suballoc.size;
  6673. }
  6674. else
  6675. {
  6676. ++nullItem1stCount;
  6677. }
  6678. offset = suballoc.offset + suballoc.size + debugMargin;
  6679. }
  6680. VMA_VALIDATE(nullItem1stCount == m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount);
  6681. if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  6682. {
  6683. const size_t suballoc2ndCount = suballocations2nd.size();
  6684. size_t nullItem2ndCount = 0;
  6685. for (size_t i = suballoc2ndCount; i--; )
  6686. {
  6687. const VmaSuballocation& suballoc = suballocations2nd[i];
  6688. const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  6689. VmaAllocation const alloc = (VmaAllocation)suballoc.userData;
  6690. if (!IsVirtual())
  6691. {
  6692. VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE));
  6693. }
  6694. VMA_VALIDATE(suballoc.offset >= offset);
  6695. if (!currFree)
  6696. {
  6697. if (!IsVirtual())
  6698. {
  6699. VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == suballoc.offset + 1);
  6700. VMA_VALIDATE(alloc->GetSize() == suballoc.size);
  6701. }
  6702. sumUsedSize += suballoc.size;
  6703. }
  6704. else
  6705. {
  6706. ++nullItem2ndCount;
  6707. }
  6708. offset = suballoc.offset + suballoc.size + debugMargin;
  6709. }
  6710. VMA_VALIDATE(nullItem2ndCount == m_2ndNullItemsCount);
  6711. }
  6712. VMA_VALIDATE(offset <= GetSize());
  6713. VMA_VALIDATE(m_SumFreeSize == GetSize() - sumUsedSize);
  6714. return true;
  6715. }
  6716. size_t VmaBlockMetadata_Linear::GetAllocationCount() const
  6717. {
  6718. return AccessSuballocations1st().size() - m_1stNullItemsBeginCount - m_1stNullItemsMiddleCount +
  6719. AccessSuballocations2nd().size() - m_2ndNullItemsCount;
  6720. }
  6721. size_t VmaBlockMetadata_Linear::GetFreeRegionsCount() const
  6722. {
  6723. // Function only used for defragmentation, which is disabled for this algorithm
  6724. VMA_ASSERT(0);
  6725. return SIZE_MAX;
  6726. }
  6727. void VmaBlockMetadata_Linear::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const
  6728. {
  6729. const VkDeviceSize size = GetSize();
  6730. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  6731. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  6732. const size_t suballoc1stCount = suballocations1st.size();
  6733. const size_t suballoc2ndCount = suballocations2nd.size();
  6734. inoutStats.statistics.blockCount++;
  6735. inoutStats.statistics.blockBytes += size;
  6736. VkDeviceSize lastOffset = 0;
  6737. if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  6738. {
  6739. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  6740. size_t nextAlloc2ndIndex = 0;
  6741. while (lastOffset < freeSpace2ndTo1stEnd)
  6742. {
  6743. // Find next non-null allocation or move nextAllocIndex to the end.
  6744. while (nextAlloc2ndIndex < suballoc2ndCount &&
  6745. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  6746. {
  6747. ++nextAlloc2ndIndex;
  6748. }
  6749. // Found non-null allocation.
  6750. if (nextAlloc2ndIndex < suballoc2ndCount)
  6751. {
  6752. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  6753. // 1. Process free space before this allocation.
  6754. if (lastOffset < suballoc.offset)
  6755. {
  6756. // There is free space from lastOffset to suballoc.offset.
  6757. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  6758. VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize);
  6759. }
  6760. // 2. Process this allocation.
  6761. // There is allocation with suballoc.offset, suballoc.size.
  6762. VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size);
  6763. // 3. Prepare for next iteration.
  6764. lastOffset = suballoc.offset + suballoc.size;
  6765. ++nextAlloc2ndIndex;
  6766. }
  6767. // We are at the end.
  6768. else
  6769. {
  6770. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  6771. if (lastOffset < freeSpace2ndTo1stEnd)
  6772. {
  6773. const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset;
  6774. VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize);
  6775. }
  6776. // End of loop.
  6777. lastOffset = freeSpace2ndTo1stEnd;
  6778. }
  6779. }
  6780. }
  6781. size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
  6782. const VkDeviceSize freeSpace1stTo2ndEnd =
  6783. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
  6784. while (lastOffset < freeSpace1stTo2ndEnd)
  6785. {
  6786. // Find next non-null allocation or move nextAllocIndex to the end.
  6787. while (nextAlloc1stIndex < suballoc1stCount &&
  6788. suballocations1st[nextAlloc1stIndex].userData == VMA_NULL)
  6789. {
  6790. ++nextAlloc1stIndex;
  6791. }
  6792. // Found non-null allocation.
  6793. if (nextAlloc1stIndex < suballoc1stCount)
  6794. {
  6795. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  6796. // 1. Process free space before this allocation.
  6797. if (lastOffset < suballoc.offset)
  6798. {
  6799. // There is free space from lastOffset to suballoc.offset.
  6800. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  6801. VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize);
  6802. }
  6803. // 2. Process this allocation.
  6804. // There is allocation with suballoc.offset, suballoc.size.
  6805. VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size);
  6806. // 3. Prepare for next iteration.
  6807. lastOffset = suballoc.offset + suballoc.size;
  6808. ++nextAlloc1stIndex;
  6809. }
  6810. // We are at the end.
  6811. else
  6812. {
  6813. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  6814. if (lastOffset < freeSpace1stTo2ndEnd)
  6815. {
  6816. const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset;
  6817. VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize);
  6818. }
  6819. // End of loop.
  6820. lastOffset = freeSpace1stTo2ndEnd;
  6821. }
  6822. }
  6823. if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  6824. {
  6825. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  6826. while (lastOffset < size)
  6827. {
  6828. // Find next non-null allocation or move nextAllocIndex to the end.
  6829. while (nextAlloc2ndIndex != SIZE_MAX &&
  6830. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  6831. {
  6832. --nextAlloc2ndIndex;
  6833. }
  6834. // Found non-null allocation.
  6835. if (nextAlloc2ndIndex != SIZE_MAX)
  6836. {
  6837. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  6838. // 1. Process free space before this allocation.
  6839. if (lastOffset < suballoc.offset)
  6840. {
  6841. // There is free space from lastOffset to suballoc.offset.
  6842. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  6843. VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize);
  6844. }
  6845. // 2. Process this allocation.
  6846. // There is allocation with suballoc.offset, suballoc.size.
  6847. VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size);
  6848. // 3. Prepare for next iteration.
  6849. lastOffset = suballoc.offset + suballoc.size;
  6850. --nextAlloc2ndIndex;
  6851. }
  6852. // We are at the end.
  6853. else
  6854. {
  6855. // There is free space from lastOffset to size.
  6856. if (lastOffset < size)
  6857. {
  6858. const VkDeviceSize unusedRangeSize = size - lastOffset;
  6859. VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize);
  6860. }
  6861. // End of loop.
  6862. lastOffset = size;
  6863. }
  6864. }
  6865. }
  6866. }
  6867. void VmaBlockMetadata_Linear::AddStatistics(VmaStatistics& inoutStats) const
  6868. {
  6869. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  6870. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  6871. const VkDeviceSize size = GetSize();
  6872. const size_t suballoc1stCount = suballocations1st.size();
  6873. const size_t suballoc2ndCount = suballocations2nd.size();
  6874. inoutStats.blockCount++;
  6875. inoutStats.blockBytes += size;
  6876. inoutStats.allocationBytes += size - m_SumFreeSize;
  6877. VkDeviceSize lastOffset = 0;
  6878. if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  6879. {
  6880. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  6881. size_t nextAlloc2ndIndex = m_1stNullItemsBeginCount;
  6882. while (lastOffset < freeSpace2ndTo1stEnd)
  6883. {
  6884. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  6885. while (nextAlloc2ndIndex < suballoc2ndCount &&
  6886. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  6887. {
  6888. ++nextAlloc2ndIndex;
  6889. }
  6890. // Found non-null allocation.
  6891. if (nextAlloc2ndIndex < suballoc2ndCount)
  6892. {
  6893. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  6894. // 1. Process free space before this allocation.
  6895. if (lastOffset < suballoc.offset)
  6896. {
  6897. // There is free space from lastOffset to suballoc.offset.
  6898. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  6899. }
  6900. // 2. Process this allocation.
  6901. // There is allocation with suballoc.offset, suballoc.size.
  6902. ++inoutStats.allocationCount;
  6903. // 3. Prepare for next iteration.
  6904. lastOffset = suballoc.offset + suballoc.size;
  6905. ++nextAlloc2ndIndex;
  6906. }
  6907. // We are at the end.
  6908. else
  6909. {
  6910. if (lastOffset < freeSpace2ndTo1stEnd)
  6911. {
  6912. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  6913. const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset;
  6914. }
  6915. // End of loop.
  6916. lastOffset = freeSpace2ndTo1stEnd;
  6917. }
  6918. }
  6919. }
  6920. size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
  6921. const VkDeviceSize freeSpace1stTo2ndEnd =
  6922. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
  6923. while (lastOffset < freeSpace1stTo2ndEnd)
  6924. {
  6925. // Find next non-null allocation or move nextAllocIndex to the end.
  6926. while (nextAlloc1stIndex < suballoc1stCount &&
  6927. suballocations1st[nextAlloc1stIndex].userData == VMA_NULL)
  6928. {
  6929. ++nextAlloc1stIndex;
  6930. }
  6931. // Found non-null allocation.
  6932. if (nextAlloc1stIndex < suballoc1stCount)
  6933. {
  6934. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  6935. // 1. Process free space before this allocation.
  6936. if (lastOffset < suballoc.offset)
  6937. {
  6938. // There is free space from lastOffset to suballoc.offset.
  6939. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  6940. }
  6941. // 2. Process this allocation.
  6942. // There is allocation with suballoc.offset, suballoc.size.
  6943. ++inoutStats.allocationCount;
  6944. // 3. Prepare for next iteration.
  6945. lastOffset = suballoc.offset + suballoc.size;
  6946. ++nextAlloc1stIndex;
  6947. }
  6948. // We are at the end.
  6949. else
  6950. {
  6951. if (lastOffset < freeSpace1stTo2ndEnd)
  6952. {
  6953. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  6954. const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset;
  6955. }
  6956. // End of loop.
  6957. lastOffset = freeSpace1stTo2ndEnd;
  6958. }
  6959. }
  6960. if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  6961. {
  6962. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  6963. while (lastOffset < size)
  6964. {
  6965. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  6966. while (nextAlloc2ndIndex != SIZE_MAX &&
  6967. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  6968. {
  6969. --nextAlloc2ndIndex;
  6970. }
  6971. // Found non-null allocation.
  6972. if (nextAlloc2ndIndex != SIZE_MAX)
  6973. {
  6974. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  6975. // 1. Process free space before this allocation.
  6976. if (lastOffset < suballoc.offset)
  6977. {
  6978. // There is free space from lastOffset to suballoc.offset.
  6979. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  6980. }
  6981. // 2. Process this allocation.
  6982. // There is allocation with suballoc.offset, suballoc.size.
  6983. ++inoutStats.allocationCount;
  6984. // 3. Prepare for next iteration.
  6985. lastOffset = suballoc.offset + suballoc.size;
  6986. --nextAlloc2ndIndex;
  6987. }
  6988. // We are at the end.
  6989. else
  6990. {
  6991. if (lastOffset < size)
  6992. {
  6993. // There is free space from lastOffset to size.
  6994. const VkDeviceSize unusedRangeSize = size - lastOffset;
  6995. }
  6996. // End of loop.
  6997. lastOffset = size;
  6998. }
  6999. }
  7000. }
  7001. }
  7002. #if VMA_STATS_STRING_ENABLED
  7003. void VmaBlockMetadata_Linear::PrintDetailedMap(class VmaJsonWriter& json) const
  7004. {
  7005. const VkDeviceSize size = GetSize();
  7006. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7007. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7008. const size_t suballoc1stCount = suballocations1st.size();
  7009. const size_t suballoc2ndCount = suballocations2nd.size();
  7010. // FIRST PASS
  7011. size_t unusedRangeCount = 0;
  7012. VkDeviceSize usedBytes = 0;
  7013. VkDeviceSize lastOffset = 0;
  7014. size_t alloc2ndCount = 0;
  7015. if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  7016. {
  7017. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  7018. size_t nextAlloc2ndIndex = 0;
  7019. while (lastOffset < freeSpace2ndTo1stEnd)
  7020. {
  7021. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  7022. while (nextAlloc2ndIndex < suballoc2ndCount &&
  7023. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  7024. {
  7025. ++nextAlloc2ndIndex;
  7026. }
  7027. // Found non-null allocation.
  7028. if (nextAlloc2ndIndex < suballoc2ndCount)
  7029. {
  7030. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  7031. // 1. Process free space before this allocation.
  7032. if (lastOffset < suballoc.offset)
  7033. {
  7034. // There is free space from lastOffset to suballoc.offset.
  7035. ++unusedRangeCount;
  7036. }
  7037. // 2. Process this allocation.
  7038. // There is allocation with suballoc.offset, suballoc.size.
  7039. ++alloc2ndCount;
  7040. usedBytes += suballoc.size;
  7041. // 3. Prepare for next iteration.
  7042. lastOffset = suballoc.offset + suballoc.size;
  7043. ++nextAlloc2ndIndex;
  7044. }
  7045. // We are at the end.
  7046. else
  7047. {
  7048. if (lastOffset < freeSpace2ndTo1stEnd)
  7049. {
  7050. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  7051. ++unusedRangeCount;
  7052. }
  7053. // End of loop.
  7054. lastOffset = freeSpace2ndTo1stEnd;
  7055. }
  7056. }
  7057. }
  7058. size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
  7059. size_t alloc1stCount = 0;
  7060. const VkDeviceSize freeSpace1stTo2ndEnd =
  7061. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
  7062. while (lastOffset < freeSpace1stTo2ndEnd)
  7063. {
  7064. // Find next non-null allocation or move nextAllocIndex to the end.
  7065. while (nextAlloc1stIndex < suballoc1stCount &&
  7066. suballocations1st[nextAlloc1stIndex].userData == VMA_NULL)
  7067. {
  7068. ++nextAlloc1stIndex;
  7069. }
  7070. // Found non-null allocation.
  7071. if (nextAlloc1stIndex < suballoc1stCount)
  7072. {
  7073. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  7074. // 1. Process free space before this allocation.
  7075. if (lastOffset < suballoc.offset)
  7076. {
  7077. // There is free space from lastOffset to suballoc.offset.
  7078. ++unusedRangeCount;
  7079. }
  7080. // 2. Process this allocation.
  7081. // There is allocation with suballoc.offset, suballoc.size.
  7082. ++alloc1stCount;
  7083. usedBytes += suballoc.size;
  7084. // 3. Prepare for next iteration.
  7085. lastOffset = suballoc.offset + suballoc.size;
  7086. ++nextAlloc1stIndex;
  7087. }
  7088. // We are at the end.
  7089. else
  7090. {
  7091. if (lastOffset < size)
  7092. {
  7093. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  7094. ++unusedRangeCount;
  7095. }
  7096. // End of loop.
  7097. lastOffset = freeSpace1stTo2ndEnd;
  7098. }
  7099. }
  7100. if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  7101. {
  7102. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  7103. while (lastOffset < size)
  7104. {
  7105. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  7106. while (nextAlloc2ndIndex != SIZE_MAX &&
  7107. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  7108. {
  7109. --nextAlloc2ndIndex;
  7110. }
  7111. // Found non-null allocation.
  7112. if (nextAlloc2ndIndex != SIZE_MAX)
  7113. {
  7114. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  7115. // 1. Process free space before this allocation.
  7116. if (lastOffset < suballoc.offset)
  7117. {
  7118. // There is free space from lastOffset to suballoc.offset.
  7119. ++unusedRangeCount;
  7120. }
  7121. // 2. Process this allocation.
  7122. // There is allocation with suballoc.offset, suballoc.size.
  7123. ++alloc2ndCount;
  7124. usedBytes += suballoc.size;
  7125. // 3. Prepare for next iteration.
  7126. lastOffset = suballoc.offset + suballoc.size;
  7127. --nextAlloc2ndIndex;
  7128. }
  7129. // We are at the end.
  7130. else
  7131. {
  7132. if (lastOffset < size)
  7133. {
  7134. // There is free space from lastOffset to size.
  7135. ++unusedRangeCount;
  7136. }
  7137. // End of loop.
  7138. lastOffset = size;
  7139. }
  7140. }
  7141. }
  7142. const VkDeviceSize unusedBytes = size - usedBytes;
  7143. PrintDetailedMap_Begin(json, unusedBytes, alloc1stCount + alloc2ndCount, unusedRangeCount);
  7144. // SECOND PASS
  7145. lastOffset = 0;
  7146. if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  7147. {
  7148. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  7149. size_t nextAlloc2ndIndex = 0;
  7150. while (lastOffset < freeSpace2ndTo1stEnd)
  7151. {
  7152. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  7153. while (nextAlloc2ndIndex < suballoc2ndCount &&
  7154. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  7155. {
  7156. ++nextAlloc2ndIndex;
  7157. }
  7158. // Found non-null allocation.
  7159. if (nextAlloc2ndIndex < suballoc2ndCount)
  7160. {
  7161. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  7162. // 1. Process free space before this allocation.
  7163. if (lastOffset < suballoc.offset)
  7164. {
  7165. // There is free space from lastOffset to suballoc.offset.
  7166. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  7167. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  7168. }
  7169. // 2. Process this allocation.
  7170. // There is allocation with suballoc.offset, suballoc.size.
  7171. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData);
  7172. // 3. Prepare for next iteration.
  7173. lastOffset = suballoc.offset + suballoc.size;
  7174. ++nextAlloc2ndIndex;
  7175. }
  7176. // We are at the end.
  7177. else
  7178. {
  7179. if (lastOffset < freeSpace2ndTo1stEnd)
  7180. {
  7181. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  7182. const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset;
  7183. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  7184. }
  7185. // End of loop.
  7186. lastOffset = freeSpace2ndTo1stEnd;
  7187. }
  7188. }
  7189. }
  7190. nextAlloc1stIndex = m_1stNullItemsBeginCount;
  7191. while (lastOffset < freeSpace1stTo2ndEnd)
  7192. {
  7193. // Find next non-null allocation or move nextAllocIndex to the end.
  7194. while (nextAlloc1stIndex < suballoc1stCount &&
  7195. suballocations1st[nextAlloc1stIndex].userData == VMA_NULL)
  7196. {
  7197. ++nextAlloc1stIndex;
  7198. }
  7199. // Found non-null allocation.
  7200. if (nextAlloc1stIndex < suballoc1stCount)
  7201. {
  7202. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  7203. // 1. Process free space before this allocation.
  7204. if (lastOffset < suballoc.offset)
  7205. {
  7206. // There is free space from lastOffset to suballoc.offset.
  7207. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  7208. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  7209. }
  7210. // 2. Process this allocation.
  7211. // There is allocation with suballoc.offset, suballoc.size.
  7212. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData);
  7213. // 3. Prepare for next iteration.
  7214. lastOffset = suballoc.offset + suballoc.size;
  7215. ++nextAlloc1stIndex;
  7216. }
  7217. // We are at the end.
  7218. else
  7219. {
  7220. if (lastOffset < freeSpace1stTo2ndEnd)
  7221. {
  7222. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  7223. const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset;
  7224. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  7225. }
  7226. // End of loop.
  7227. lastOffset = freeSpace1stTo2ndEnd;
  7228. }
  7229. }
  7230. if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  7231. {
  7232. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  7233. while (lastOffset < size)
  7234. {
  7235. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  7236. while (nextAlloc2ndIndex != SIZE_MAX &&
  7237. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  7238. {
  7239. --nextAlloc2ndIndex;
  7240. }
  7241. // Found non-null allocation.
  7242. if (nextAlloc2ndIndex != SIZE_MAX)
  7243. {
  7244. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  7245. // 1. Process free space before this allocation.
  7246. if (lastOffset < suballoc.offset)
  7247. {
  7248. // There is free space from lastOffset to suballoc.offset.
  7249. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  7250. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  7251. }
  7252. // 2. Process this allocation.
  7253. // There is allocation with suballoc.offset, suballoc.size.
  7254. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData);
  7255. // 3. Prepare for next iteration.
  7256. lastOffset = suballoc.offset + suballoc.size;
  7257. --nextAlloc2ndIndex;
  7258. }
  7259. // We are at the end.
  7260. else
  7261. {
  7262. if (lastOffset < size)
  7263. {
  7264. // There is free space from lastOffset to size.
  7265. const VkDeviceSize unusedRangeSize = size - lastOffset;
  7266. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  7267. }
  7268. // End of loop.
  7269. lastOffset = size;
  7270. }
  7271. }
  7272. }
  7273. PrintDetailedMap_End(json);
  7274. }
  7275. #endif // VMA_STATS_STRING_ENABLED
  7276. bool VmaBlockMetadata_Linear::CreateAllocationRequest(
  7277. VkDeviceSize allocSize,
  7278. VkDeviceSize allocAlignment,
  7279. bool upperAddress,
  7280. VmaSuballocationType allocType,
  7281. uint32_t strategy,
  7282. VmaAllocationRequest* pAllocationRequest)
  7283. {
  7284. VMA_ASSERT(allocSize > 0);
  7285. VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
  7286. VMA_ASSERT(pAllocationRequest != VMA_NULL);
  7287. VMA_HEAVY_ASSERT(Validate());
  7288. pAllocationRequest->size = allocSize;
  7289. return upperAddress ?
  7290. CreateAllocationRequest_UpperAddress(
  7291. allocSize, allocAlignment, allocType, strategy, pAllocationRequest) :
  7292. CreateAllocationRequest_LowerAddress(
  7293. allocSize, allocAlignment, allocType, strategy, pAllocationRequest);
  7294. }
  7295. VkResult VmaBlockMetadata_Linear::CheckCorruption(const void* pBlockData)
  7296. {
  7297. VMA_ASSERT(!IsVirtual());
  7298. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7299. for (size_t i = m_1stNullItemsBeginCount, count = suballocations1st.size(); i < count; ++i)
  7300. {
  7301. const VmaSuballocation& suballoc = suballocations1st[i];
  7302. if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  7303. {
  7304. if (!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size))
  7305. {
  7306. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
  7307. return VK_ERROR_UNKNOWN_COPY;
  7308. }
  7309. }
  7310. }
  7311. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7312. for (size_t i = 0, count = suballocations2nd.size(); i < count; ++i)
  7313. {
  7314. const VmaSuballocation& suballoc = suballocations2nd[i];
  7315. if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  7316. {
  7317. if (!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size))
  7318. {
  7319. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
  7320. return VK_ERROR_UNKNOWN_COPY;
  7321. }
  7322. }
  7323. }
  7324. return VK_SUCCESS;
  7325. }
  7326. void VmaBlockMetadata_Linear::Alloc(
  7327. const VmaAllocationRequest& request,
  7328. VmaSuballocationType type,
  7329. void* userData)
  7330. {
  7331. const VkDeviceSize offset = (VkDeviceSize)request.allocHandle - 1;
  7332. const VmaSuballocation newSuballoc = { offset, request.size, userData, type };
  7333. switch (request.type)
  7334. {
  7335. case VmaAllocationRequestType::UpperAddress:
  7336. {
  7337. VMA_ASSERT(m_2ndVectorMode != SECOND_VECTOR_RING_BUFFER &&
  7338. "CRITICAL ERROR: Trying to use linear allocator as double stack while it was already used as ring buffer.");
  7339. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7340. suballocations2nd.push_back(newSuballoc);
  7341. m_2ndVectorMode = SECOND_VECTOR_DOUBLE_STACK;
  7342. }
  7343. break;
  7344. case VmaAllocationRequestType::EndOf1st:
  7345. {
  7346. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7347. VMA_ASSERT(suballocations1st.empty() ||
  7348. offset >= suballocations1st.back().offset + suballocations1st.back().size);
  7349. // Check if it fits before the end of the block.
  7350. VMA_ASSERT(offset + request.size <= GetSize());
  7351. suballocations1st.push_back(newSuballoc);
  7352. }
  7353. break;
  7354. case VmaAllocationRequestType::EndOf2nd:
  7355. {
  7356. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7357. // New allocation at the end of 2-part ring buffer, so before first allocation from 1st vector.
  7358. VMA_ASSERT(!suballocations1st.empty() &&
  7359. offset + request.size <= suballocations1st[m_1stNullItemsBeginCount].offset);
  7360. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7361. switch (m_2ndVectorMode)
  7362. {
  7363. case SECOND_VECTOR_EMPTY:
  7364. // First allocation from second part ring buffer.
  7365. VMA_ASSERT(suballocations2nd.empty());
  7366. m_2ndVectorMode = SECOND_VECTOR_RING_BUFFER;
  7367. break;
  7368. case SECOND_VECTOR_RING_BUFFER:
  7369. // 2-part ring buffer is already started.
  7370. VMA_ASSERT(!suballocations2nd.empty());
  7371. break;
  7372. case SECOND_VECTOR_DOUBLE_STACK:
  7373. VMA_ASSERT(0 && "CRITICAL ERROR: Trying to use linear allocator as ring buffer while it was already used as double stack.");
  7374. break;
  7375. default:
  7376. VMA_ASSERT(0);
  7377. }
  7378. suballocations2nd.push_back(newSuballoc);
  7379. }
  7380. break;
  7381. default:
  7382. VMA_ASSERT(0 && "CRITICAL INTERNAL ERROR.");
  7383. }
  7384. m_SumFreeSize -= newSuballoc.size;
  7385. }
  7386. void VmaBlockMetadata_Linear::Free(VmaAllocHandle allocHandle)
  7387. {
  7388. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7389. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7390. VkDeviceSize offset = (VkDeviceSize)allocHandle - 1;
  7391. if (!suballocations1st.empty())
  7392. {
  7393. // First allocation: Mark it as next empty at the beginning.
  7394. VmaSuballocation& firstSuballoc = suballocations1st[m_1stNullItemsBeginCount];
  7395. if (firstSuballoc.offset == offset)
  7396. {
  7397. firstSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  7398. firstSuballoc.userData = VMA_NULL;
  7399. m_SumFreeSize += firstSuballoc.size;
  7400. ++m_1stNullItemsBeginCount;
  7401. CleanupAfterFree();
  7402. return;
  7403. }
  7404. }
  7405. // Last allocation in 2-part ring buffer or top of upper stack (same logic).
  7406. if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ||
  7407. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  7408. {
  7409. VmaSuballocation& lastSuballoc = suballocations2nd.back();
  7410. if (lastSuballoc.offset == offset)
  7411. {
  7412. m_SumFreeSize += lastSuballoc.size;
  7413. suballocations2nd.pop_back();
  7414. CleanupAfterFree();
  7415. return;
  7416. }
  7417. }
  7418. // Last allocation in 1st vector.
  7419. else if (m_2ndVectorMode == SECOND_VECTOR_EMPTY)
  7420. {
  7421. VmaSuballocation& lastSuballoc = suballocations1st.back();
  7422. if (lastSuballoc.offset == offset)
  7423. {
  7424. m_SumFreeSize += lastSuballoc.size;
  7425. suballocations1st.pop_back();
  7426. CleanupAfterFree();
  7427. return;
  7428. }
  7429. }
  7430. VmaSuballocation refSuballoc;
  7431. refSuballoc.offset = offset;
  7432. // Rest of members stays uninitialized intentionally for better performance.
  7433. // Item from the middle of 1st vector.
  7434. {
  7435. const SuballocationVectorType::iterator it = VmaBinaryFindSorted(
  7436. suballocations1st.begin() + m_1stNullItemsBeginCount,
  7437. suballocations1st.end(),
  7438. refSuballoc,
  7439. VmaSuballocationOffsetLess());
  7440. if (it != suballocations1st.end())
  7441. {
  7442. it->type = VMA_SUBALLOCATION_TYPE_FREE;
  7443. it->userData = VMA_NULL;
  7444. ++m_1stNullItemsMiddleCount;
  7445. m_SumFreeSize += it->size;
  7446. CleanupAfterFree();
  7447. return;
  7448. }
  7449. }
  7450. if (m_2ndVectorMode != SECOND_VECTOR_EMPTY)
  7451. {
  7452. // Item from the middle of 2nd vector.
  7453. const SuballocationVectorType::iterator it = m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ?
  7454. VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetLess()) :
  7455. VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetGreater());
  7456. if (it != suballocations2nd.end())
  7457. {
  7458. it->type = VMA_SUBALLOCATION_TYPE_FREE;
  7459. it->userData = VMA_NULL;
  7460. ++m_2ndNullItemsCount;
  7461. m_SumFreeSize += it->size;
  7462. CleanupAfterFree();
  7463. return;
  7464. }
  7465. }
  7466. VMA_ASSERT(0 && "Allocation to free not found in linear allocator!");
  7467. }
  7468. void VmaBlockMetadata_Linear::GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo)
  7469. {
  7470. outInfo.offset = (VkDeviceSize)allocHandle - 1;
  7471. VmaSuballocation& suballoc = FindSuballocation(outInfo.offset);
  7472. outInfo.size = suballoc.size;
  7473. outInfo.pUserData = suballoc.userData;
  7474. }
  7475. void* VmaBlockMetadata_Linear::GetAllocationUserData(VmaAllocHandle allocHandle) const
  7476. {
  7477. return FindSuballocation((VkDeviceSize)allocHandle - 1).userData;
  7478. }
  7479. VmaAllocHandle VmaBlockMetadata_Linear::GetAllocationListBegin() const
  7480. {
  7481. // Function only used for defragmentation, which is disabled for this algorithm
  7482. VMA_ASSERT(0);
  7483. return VK_NULL_HANDLE;
  7484. }
  7485. VmaAllocHandle VmaBlockMetadata_Linear::GetNextAllocation(VmaAllocHandle prevAlloc) const
  7486. {
  7487. // Function only used for defragmentation, which is disabled for this algorithm
  7488. VMA_ASSERT(0);
  7489. return VK_NULL_HANDLE;
  7490. }
  7491. VkDeviceSize VmaBlockMetadata_Linear::GetNextFreeRegionSize(VmaAllocHandle alloc) const
  7492. {
  7493. // Function only used for defragmentation, which is disabled for this algorithm
  7494. VMA_ASSERT(0);
  7495. return 0;
  7496. }
  7497. void VmaBlockMetadata_Linear::Clear()
  7498. {
  7499. m_SumFreeSize = GetSize();
  7500. m_Suballocations0.clear();
  7501. m_Suballocations1.clear();
  7502. // Leaving m_1stVectorIndex unchanged - it doesn't matter.
  7503. m_2ndVectorMode = SECOND_VECTOR_EMPTY;
  7504. m_1stNullItemsBeginCount = 0;
  7505. m_1stNullItemsMiddleCount = 0;
  7506. m_2ndNullItemsCount = 0;
  7507. }
  7508. void VmaBlockMetadata_Linear::SetAllocationUserData(VmaAllocHandle allocHandle, void* userData)
  7509. {
  7510. VmaSuballocation& suballoc = FindSuballocation((VkDeviceSize)allocHandle - 1);
  7511. suballoc.userData = userData;
  7512. }
  7513. void VmaBlockMetadata_Linear::DebugLogAllAllocations() const
  7514. {
  7515. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7516. for (auto it = suballocations1st.begin() + m_1stNullItemsBeginCount; it != suballocations1st.end(); ++it)
  7517. if (it->type != VMA_SUBALLOCATION_TYPE_FREE)
  7518. DebugLogAllocation(it->offset, it->size, it->userData);
  7519. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7520. for (auto it = suballocations2nd.begin(); it != suballocations2nd.end(); ++it)
  7521. if (it->type != VMA_SUBALLOCATION_TYPE_FREE)
  7522. DebugLogAllocation(it->offset, it->size, it->userData);
  7523. }
  7524. VmaSuballocation& VmaBlockMetadata_Linear::FindSuballocation(VkDeviceSize offset) const
  7525. {
  7526. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7527. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7528. VmaSuballocation refSuballoc;
  7529. refSuballoc.offset = offset;
  7530. // Rest of members stays uninitialized intentionally for better performance.
  7531. // Item from the 1st vector.
  7532. {
  7533. SuballocationVectorType::const_iterator it = VmaBinaryFindSorted(
  7534. suballocations1st.begin() + m_1stNullItemsBeginCount,
  7535. suballocations1st.end(),
  7536. refSuballoc,
  7537. VmaSuballocationOffsetLess());
  7538. if (it != suballocations1st.end())
  7539. {
  7540. return const_cast<VmaSuballocation&>(*it);
  7541. }
  7542. }
  7543. if (m_2ndVectorMode != SECOND_VECTOR_EMPTY)
  7544. {
  7545. // Rest of members stays uninitialized intentionally for better performance.
  7546. SuballocationVectorType::const_iterator it = m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ?
  7547. VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetLess()) :
  7548. VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetGreater());
  7549. if (it != suballocations2nd.end())
  7550. {
  7551. return const_cast<VmaSuballocation&>(*it);
  7552. }
  7553. }
  7554. VMA_ASSERT(0 && "Allocation not found in linear allocator!");
  7555. return const_cast<VmaSuballocation&>(suballocations1st.back()); // Should never occur.
  7556. }
  7557. bool VmaBlockMetadata_Linear::ShouldCompact1st() const
  7558. {
  7559. const size_t nullItemCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount;
  7560. const size_t suballocCount = AccessSuballocations1st().size();
  7561. return suballocCount > 32 && nullItemCount * 2 >= (suballocCount - nullItemCount) * 3;
  7562. }
  7563. void VmaBlockMetadata_Linear::CleanupAfterFree()
  7564. {
  7565. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7566. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7567. if (IsEmpty())
  7568. {
  7569. suballocations1st.clear();
  7570. suballocations2nd.clear();
  7571. m_1stNullItemsBeginCount = 0;
  7572. m_1stNullItemsMiddleCount = 0;
  7573. m_2ndNullItemsCount = 0;
  7574. m_2ndVectorMode = SECOND_VECTOR_EMPTY;
  7575. }
  7576. else
  7577. {
  7578. const size_t suballoc1stCount = suballocations1st.size();
  7579. const size_t nullItem1stCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount;
  7580. VMA_ASSERT(nullItem1stCount <= suballoc1stCount);
  7581. // Find more null items at the beginning of 1st vector.
  7582. while (m_1stNullItemsBeginCount < suballoc1stCount &&
  7583. suballocations1st[m_1stNullItemsBeginCount].type == VMA_SUBALLOCATION_TYPE_FREE)
  7584. {
  7585. ++m_1stNullItemsBeginCount;
  7586. --m_1stNullItemsMiddleCount;
  7587. }
  7588. // Find more null items at the end of 1st vector.
  7589. while (m_1stNullItemsMiddleCount > 0 &&
  7590. suballocations1st.back().type == VMA_SUBALLOCATION_TYPE_FREE)
  7591. {
  7592. --m_1stNullItemsMiddleCount;
  7593. suballocations1st.pop_back();
  7594. }
  7595. // Find more null items at the end of 2nd vector.
  7596. while (m_2ndNullItemsCount > 0 &&
  7597. suballocations2nd.back().type == VMA_SUBALLOCATION_TYPE_FREE)
  7598. {
  7599. --m_2ndNullItemsCount;
  7600. suballocations2nd.pop_back();
  7601. }
  7602. // Find more null items at the beginning of 2nd vector.
  7603. while (m_2ndNullItemsCount > 0 &&
  7604. suballocations2nd[0].type == VMA_SUBALLOCATION_TYPE_FREE)
  7605. {
  7606. --m_2ndNullItemsCount;
  7607. VmaVectorRemove(suballocations2nd, 0);
  7608. }
  7609. if (ShouldCompact1st())
  7610. {
  7611. const size_t nonNullItemCount = suballoc1stCount - nullItem1stCount;
  7612. size_t srcIndex = m_1stNullItemsBeginCount;
  7613. for (size_t dstIndex = 0; dstIndex < nonNullItemCount; ++dstIndex)
  7614. {
  7615. while (suballocations1st[srcIndex].type == VMA_SUBALLOCATION_TYPE_FREE)
  7616. {
  7617. ++srcIndex;
  7618. }
  7619. if (dstIndex != srcIndex)
  7620. {
  7621. suballocations1st[dstIndex] = suballocations1st[srcIndex];
  7622. }
  7623. ++srcIndex;
  7624. }
  7625. suballocations1st.resize(nonNullItemCount);
  7626. m_1stNullItemsBeginCount = 0;
  7627. m_1stNullItemsMiddleCount = 0;
  7628. }
  7629. // 2nd vector became empty.
  7630. if (suballocations2nd.empty())
  7631. {
  7632. m_2ndVectorMode = SECOND_VECTOR_EMPTY;
  7633. }
  7634. // 1st vector became empty.
  7635. if (suballocations1st.size() - m_1stNullItemsBeginCount == 0)
  7636. {
  7637. suballocations1st.clear();
  7638. m_1stNullItemsBeginCount = 0;
  7639. if (!suballocations2nd.empty() && m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  7640. {
  7641. // Swap 1st with 2nd. Now 2nd is empty.
  7642. m_2ndVectorMode = SECOND_VECTOR_EMPTY;
  7643. m_1stNullItemsMiddleCount = m_2ndNullItemsCount;
  7644. while (m_1stNullItemsBeginCount < suballocations2nd.size() &&
  7645. suballocations2nd[m_1stNullItemsBeginCount].type == VMA_SUBALLOCATION_TYPE_FREE)
  7646. {
  7647. ++m_1stNullItemsBeginCount;
  7648. --m_1stNullItemsMiddleCount;
  7649. }
  7650. m_2ndNullItemsCount = 0;
  7651. m_1stVectorIndex ^= 1;
  7652. }
  7653. }
  7654. }
  7655. VMA_HEAVY_ASSERT(Validate());
  7656. }
  7657. bool VmaBlockMetadata_Linear::CreateAllocationRequest_LowerAddress(
  7658. VkDeviceSize allocSize,
  7659. VkDeviceSize allocAlignment,
  7660. VmaSuballocationType allocType,
  7661. uint32_t strategy,
  7662. VmaAllocationRequest* pAllocationRequest)
  7663. {
  7664. const VkDeviceSize blockSize = GetSize();
  7665. const VkDeviceSize debugMargin = GetDebugMargin();
  7666. const VkDeviceSize bufferImageGranularity = GetBufferImageGranularity();
  7667. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7668. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7669. if (m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  7670. {
  7671. // Try to allocate at the end of 1st vector.
  7672. VkDeviceSize resultBaseOffset = 0;
  7673. if (!suballocations1st.empty())
  7674. {
  7675. const VmaSuballocation& lastSuballoc = suballocations1st.back();
  7676. resultBaseOffset = lastSuballoc.offset + lastSuballoc.size + debugMargin;
  7677. }
  7678. // Start from offset equal to beginning of free space.
  7679. VkDeviceSize resultOffset = resultBaseOffset;
  7680. // Apply alignment.
  7681. resultOffset = VmaAlignUp(resultOffset, allocAlignment);
  7682. // Check previous suballocations for BufferImageGranularity conflicts.
  7683. // Make bigger alignment if necessary.
  7684. if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations1st.empty())
  7685. {
  7686. bool bufferImageGranularityConflict = false;
  7687. for (size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; )
  7688. {
  7689. const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex];
  7690. if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
  7691. {
  7692. if (VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
  7693. {
  7694. bufferImageGranularityConflict = true;
  7695. break;
  7696. }
  7697. }
  7698. else
  7699. // Already on previous page.
  7700. break;
  7701. }
  7702. if (bufferImageGranularityConflict)
  7703. {
  7704. resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity);
  7705. }
  7706. }
  7707. const VkDeviceSize freeSpaceEnd = m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ?
  7708. suballocations2nd.back().offset : blockSize;
  7709. // There is enough free space at the end after alignment.
  7710. if (resultOffset + allocSize + debugMargin <= freeSpaceEnd)
  7711. {
  7712. // Check next suballocations for BufferImageGranularity conflicts.
  7713. // If conflict exists, allocation cannot be made here.
  7714. if ((allocSize % bufferImageGranularity || resultOffset % bufferImageGranularity) && m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  7715. {
  7716. for (size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; )
  7717. {
  7718. const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex];
  7719. if (VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  7720. {
  7721. if (VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
  7722. {
  7723. return false;
  7724. }
  7725. }
  7726. else
  7727. {
  7728. // Already on previous page.
  7729. break;
  7730. }
  7731. }
  7732. }
  7733. // All tests passed: Success.
  7734. pAllocationRequest->allocHandle = (VmaAllocHandle)(resultOffset + 1);
  7735. // pAllocationRequest->item, customData unused.
  7736. pAllocationRequest->type = VmaAllocationRequestType::EndOf1st;
  7737. return true;
  7738. }
  7739. }
  7740. // Wrap-around to end of 2nd vector. Try to allocate there, watching for the
  7741. // beginning of 1st vector as the end of free space.
  7742. if (m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  7743. {
  7744. VMA_ASSERT(!suballocations1st.empty());
  7745. VkDeviceSize resultBaseOffset = 0;
  7746. if (!suballocations2nd.empty())
  7747. {
  7748. const VmaSuballocation& lastSuballoc = suballocations2nd.back();
  7749. resultBaseOffset = lastSuballoc.offset + lastSuballoc.size + debugMargin;
  7750. }
  7751. // Start from offset equal to beginning of free space.
  7752. VkDeviceSize resultOffset = resultBaseOffset;
  7753. // Apply alignment.
  7754. resultOffset = VmaAlignUp(resultOffset, allocAlignment);
  7755. // Check previous suballocations for BufferImageGranularity conflicts.
  7756. // Make bigger alignment if necessary.
  7757. if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations2nd.empty())
  7758. {
  7759. bool bufferImageGranularityConflict = false;
  7760. for (size_t prevSuballocIndex = suballocations2nd.size(); prevSuballocIndex--; )
  7761. {
  7762. const VmaSuballocation& prevSuballoc = suballocations2nd[prevSuballocIndex];
  7763. if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
  7764. {
  7765. if (VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
  7766. {
  7767. bufferImageGranularityConflict = true;
  7768. break;
  7769. }
  7770. }
  7771. else
  7772. // Already on previous page.
  7773. break;
  7774. }
  7775. if (bufferImageGranularityConflict)
  7776. {
  7777. resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity);
  7778. }
  7779. }
  7780. size_t index1st = m_1stNullItemsBeginCount;
  7781. // There is enough free space at the end after alignment.
  7782. if ((index1st == suballocations1st.size() && resultOffset + allocSize + debugMargin <= blockSize) ||
  7783. (index1st < suballocations1st.size() && resultOffset + allocSize + debugMargin <= suballocations1st[index1st].offset))
  7784. {
  7785. // Check next suballocations for BufferImageGranularity conflicts.
  7786. // If conflict exists, allocation cannot be made here.
  7787. if (allocSize % bufferImageGranularity || resultOffset % bufferImageGranularity)
  7788. {
  7789. for (size_t nextSuballocIndex = index1st;
  7790. nextSuballocIndex < suballocations1st.size();
  7791. nextSuballocIndex++)
  7792. {
  7793. const VmaSuballocation& nextSuballoc = suballocations1st[nextSuballocIndex];
  7794. if (VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  7795. {
  7796. if (VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
  7797. {
  7798. return false;
  7799. }
  7800. }
  7801. else
  7802. {
  7803. // Already on next page.
  7804. break;
  7805. }
  7806. }
  7807. }
  7808. // All tests passed: Success.
  7809. pAllocationRequest->allocHandle = (VmaAllocHandle)(resultOffset + 1);
  7810. pAllocationRequest->type = VmaAllocationRequestType::EndOf2nd;
  7811. // pAllocationRequest->item, customData unused.
  7812. return true;
  7813. }
  7814. }
  7815. return false;
  7816. }
  7817. bool VmaBlockMetadata_Linear::CreateAllocationRequest_UpperAddress(
  7818. VkDeviceSize allocSize,
  7819. VkDeviceSize allocAlignment,
  7820. VmaSuballocationType allocType,
  7821. uint32_t strategy,
  7822. VmaAllocationRequest* pAllocationRequest)
  7823. {
  7824. const VkDeviceSize blockSize = GetSize();
  7825. const VkDeviceSize bufferImageGranularity = GetBufferImageGranularity();
  7826. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7827. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7828. if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  7829. {
  7830. VMA_ASSERT(0 && "Trying to use pool with linear algorithm as double stack, while it is already being used as ring buffer.");
  7831. return false;
  7832. }
  7833. // Try to allocate before 2nd.back(), or end of block if 2nd.empty().
  7834. if (allocSize > blockSize)
  7835. {
  7836. return false;
  7837. }
  7838. VkDeviceSize resultBaseOffset = blockSize - allocSize;
  7839. if (!suballocations2nd.empty())
  7840. {
  7841. const VmaSuballocation& lastSuballoc = suballocations2nd.back();
  7842. resultBaseOffset = lastSuballoc.offset - allocSize;
  7843. if (allocSize > lastSuballoc.offset)
  7844. {
  7845. return false;
  7846. }
  7847. }
  7848. // Start from offset equal to end of free space.
  7849. VkDeviceSize resultOffset = resultBaseOffset;
  7850. const VkDeviceSize debugMargin = GetDebugMargin();
  7851. // Apply debugMargin at the end.
  7852. if (debugMargin > 0)
  7853. {
  7854. if (resultOffset < debugMargin)
  7855. {
  7856. return false;
  7857. }
  7858. resultOffset -= debugMargin;
  7859. }
  7860. // Apply alignment.
  7861. resultOffset = VmaAlignDown(resultOffset, allocAlignment);
  7862. // Check next suballocations from 2nd for BufferImageGranularity conflicts.
  7863. // Make bigger alignment if necessary.
  7864. if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations2nd.empty())
  7865. {
  7866. bool bufferImageGranularityConflict = false;
  7867. for (size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; )
  7868. {
  7869. const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex];
  7870. if (VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  7871. {
  7872. if (VmaIsBufferImageGranularityConflict(nextSuballoc.type, allocType))
  7873. {
  7874. bufferImageGranularityConflict = true;
  7875. break;
  7876. }
  7877. }
  7878. else
  7879. // Already on previous page.
  7880. break;
  7881. }
  7882. if (bufferImageGranularityConflict)
  7883. {
  7884. resultOffset = VmaAlignDown(resultOffset, bufferImageGranularity);
  7885. }
  7886. }
  7887. // There is enough free space.
  7888. const VkDeviceSize endOf1st = !suballocations1st.empty() ?
  7889. suballocations1st.back().offset + suballocations1st.back().size :
  7890. 0;
  7891. if (endOf1st + debugMargin <= resultOffset)
  7892. {
  7893. // Check previous suballocations for BufferImageGranularity conflicts.
  7894. // If conflict exists, allocation cannot be made here.
  7895. if (bufferImageGranularity > 1)
  7896. {
  7897. for (size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; )
  7898. {
  7899. const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex];
  7900. if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
  7901. {
  7902. if (VmaIsBufferImageGranularityConflict(allocType, prevSuballoc.type))
  7903. {
  7904. return false;
  7905. }
  7906. }
  7907. else
  7908. {
  7909. // Already on next page.
  7910. break;
  7911. }
  7912. }
  7913. }
  7914. // All tests passed: Success.
  7915. pAllocationRequest->allocHandle = (VmaAllocHandle)(resultOffset + 1);
  7916. // pAllocationRequest->item unused.
  7917. pAllocationRequest->type = VmaAllocationRequestType::UpperAddress;
  7918. return true;
  7919. }
  7920. return false;
  7921. }
  7922. #endif // _VMA_BLOCK_METADATA_LINEAR_FUNCTIONS
  7923. #endif // _VMA_BLOCK_METADATA_LINEAR
  7924. #if 0
  7925. #ifndef _VMA_BLOCK_METADATA_BUDDY
  7926. /*
  7927. - GetSize() is the original size of allocated memory block.
  7928. - m_UsableSize is this size aligned down to a power of two.
  7929. All allocations and calculations happen relative to m_UsableSize.
  7930. - GetUnusableSize() is the difference between them.
  7931. It is reported as separate, unused range, not available for allocations.
  7932. Node at level 0 has size = m_UsableSize.
  7933. Each next level contains nodes with size 2 times smaller than current level.
  7934. m_LevelCount is the maximum number of levels to use in the current object.
  7935. */
  7936. class VmaBlockMetadata_Buddy : public VmaBlockMetadata
  7937. {
  7938. VMA_CLASS_NO_COPY(VmaBlockMetadata_Buddy)
  7939. public:
  7940. VmaBlockMetadata_Buddy(const VkAllocationCallbacks* pAllocationCallbacks,
  7941. VkDeviceSize bufferImageGranularity, bool isVirtual);
  7942. virtual ~VmaBlockMetadata_Buddy();
  7943. size_t GetAllocationCount() const override { return m_AllocationCount; }
  7944. VkDeviceSize GetSumFreeSize() const override { return m_SumFreeSize + GetUnusableSize(); }
  7945. bool IsEmpty() const override { return m_Root->type == Node::TYPE_FREE; }
  7946. VkResult CheckCorruption(const void* pBlockData) override { return VK_ERROR_FEATURE_NOT_PRESENT; }
  7947. VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const override { return (VkDeviceSize)allocHandle - 1; };
  7948. void DebugLogAllAllocations() const override { DebugLogAllAllocationNode(m_Root, 0); }
  7949. void Init(VkDeviceSize size) override;
  7950. bool Validate() const override;
  7951. void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const override;
  7952. void AddStatistics(VmaStatistics& inoutStats) const override;
  7953. #if VMA_STATS_STRING_ENABLED
  7954. void PrintDetailedMap(class VmaJsonWriter& json, uint32_t mapRefCount) const override;
  7955. #endif
  7956. bool CreateAllocationRequest(
  7957. VkDeviceSize allocSize,
  7958. VkDeviceSize allocAlignment,
  7959. bool upperAddress,
  7960. VmaSuballocationType allocType,
  7961. uint32_t strategy,
  7962. VmaAllocationRequest* pAllocationRequest) override;
  7963. void Alloc(
  7964. const VmaAllocationRequest& request,
  7965. VmaSuballocationType type,
  7966. void* userData) override;
  7967. void Free(VmaAllocHandle allocHandle) override;
  7968. void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) override;
  7969. void* GetAllocationUserData(VmaAllocHandle allocHandle) const override;
  7970. VmaAllocHandle GetAllocationListBegin() const override;
  7971. VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const override;
  7972. void Clear() override;
  7973. void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) override;
  7974. private:
  7975. static const size_t MAX_LEVELS = 48;
  7976. struct ValidationContext
  7977. {
  7978. size_t calculatedAllocationCount = 0;
  7979. size_t calculatedFreeCount = 0;
  7980. VkDeviceSize calculatedSumFreeSize = 0;
  7981. };
  7982. struct Node
  7983. {
  7984. VkDeviceSize offset;
  7985. enum TYPE
  7986. {
  7987. TYPE_FREE,
  7988. TYPE_ALLOCATION,
  7989. TYPE_SPLIT,
  7990. TYPE_COUNT
  7991. } type;
  7992. Node* parent;
  7993. Node* buddy;
  7994. union
  7995. {
  7996. struct
  7997. {
  7998. Node* prev;
  7999. Node* next;
  8000. } free;
  8001. struct
  8002. {
  8003. void* userData;
  8004. } allocation;
  8005. struct
  8006. {
  8007. Node* leftChild;
  8008. } split;
  8009. };
  8010. };
  8011. // Size of the memory block aligned down to a power of two.
  8012. VkDeviceSize m_UsableSize;
  8013. uint32_t m_LevelCount;
  8014. VmaPoolAllocator<Node> m_NodeAllocator;
  8015. Node* m_Root;
  8016. struct
  8017. {
  8018. Node* front;
  8019. Node* back;
  8020. } m_FreeList[MAX_LEVELS];
  8021. // Number of nodes in the tree with type == TYPE_ALLOCATION.
  8022. size_t m_AllocationCount;
  8023. // Number of nodes in the tree with type == TYPE_FREE.
  8024. size_t m_FreeCount;
  8025. // Doesn't include space wasted due to internal fragmentation - allocation sizes are just aligned up to node sizes.
  8026. // Doesn't include unusable size.
  8027. VkDeviceSize m_SumFreeSize;
  8028. VkDeviceSize GetUnusableSize() const { return GetSize() - m_UsableSize; }
  8029. VkDeviceSize LevelToNodeSize(uint32_t level) const { return m_UsableSize >> level; }
  8030. VkDeviceSize AlignAllocationSize(VkDeviceSize size) const
  8031. {
  8032. if (!IsVirtual())
  8033. {
  8034. size = VmaAlignUp(size, (VkDeviceSize)16);
  8035. }
  8036. return VmaNextPow2(size);
  8037. }
  8038. Node* FindAllocationNode(VkDeviceSize offset, uint32_t& outLevel) const;
  8039. void DeleteNodeChildren(Node* node);
  8040. bool ValidateNode(ValidationContext& ctx, const Node* parent, const Node* curr, uint32_t level, VkDeviceSize levelNodeSize) const;
  8041. uint32_t AllocSizeToLevel(VkDeviceSize allocSize) const;
  8042. void AddNodeToDetailedStatistics(VmaDetailedStatistics& inoutStats, const Node* node, VkDeviceSize levelNodeSize) const;
  8043. // Adds node to the front of FreeList at given level.
  8044. // node->type must be FREE.
  8045. // node->free.prev, next can be undefined.
  8046. void AddToFreeListFront(uint32_t level, Node* node);
  8047. // Removes node from FreeList at given level.
  8048. // node->type must be FREE.
  8049. // node->free.prev, next stay untouched.
  8050. void RemoveFromFreeList(uint32_t level, Node* node);
  8051. void DebugLogAllAllocationNode(Node* node, uint32_t level) const;
  8052. #if VMA_STATS_STRING_ENABLED
  8053. void PrintDetailedMapNode(class VmaJsonWriter& json, const Node* node, VkDeviceSize levelNodeSize) const;
  8054. #endif
  8055. };
  8056. #ifndef _VMA_BLOCK_METADATA_BUDDY_FUNCTIONS
  8057. VmaBlockMetadata_Buddy::VmaBlockMetadata_Buddy(const VkAllocationCallbacks* pAllocationCallbacks,
  8058. VkDeviceSize bufferImageGranularity, bool isVirtual)
  8059. : VmaBlockMetadata(pAllocationCallbacks, bufferImageGranularity, isVirtual),
  8060. m_NodeAllocator(pAllocationCallbacks, 32), // firstBlockCapacity
  8061. m_Root(VMA_NULL),
  8062. m_AllocationCount(0),
  8063. m_FreeCount(1),
  8064. m_SumFreeSize(0)
  8065. {
  8066. memset(m_FreeList, 0, sizeof(m_FreeList));
  8067. }
  8068. VmaBlockMetadata_Buddy::~VmaBlockMetadata_Buddy()
  8069. {
  8070. DeleteNodeChildren(m_Root);
  8071. m_NodeAllocator.Free(m_Root);
  8072. }
  8073. void VmaBlockMetadata_Buddy::Init(VkDeviceSize size)
  8074. {
  8075. VmaBlockMetadata::Init(size);
  8076. m_UsableSize = VmaPrevPow2(size);
  8077. m_SumFreeSize = m_UsableSize;
  8078. // Calculate m_LevelCount.
  8079. const VkDeviceSize minNodeSize = IsVirtual() ? 1 : 16;
  8080. m_LevelCount = 1;
  8081. while (m_LevelCount < MAX_LEVELS &&
  8082. LevelToNodeSize(m_LevelCount) >= minNodeSize)
  8083. {
  8084. ++m_LevelCount;
  8085. }
  8086. Node* rootNode = m_NodeAllocator.Alloc();
  8087. rootNode->offset = 0;
  8088. rootNode->type = Node::TYPE_FREE;
  8089. rootNode->parent = VMA_NULL;
  8090. rootNode->buddy = VMA_NULL;
  8091. m_Root = rootNode;
  8092. AddToFreeListFront(0, rootNode);
  8093. }
  8094. bool VmaBlockMetadata_Buddy::Validate() const
  8095. {
  8096. // Validate tree.
  8097. ValidationContext ctx;
  8098. if (!ValidateNode(ctx, VMA_NULL, m_Root, 0, LevelToNodeSize(0)))
  8099. {
  8100. VMA_VALIDATE(false && "ValidateNode failed.");
  8101. }
  8102. VMA_VALIDATE(m_AllocationCount == ctx.calculatedAllocationCount);
  8103. VMA_VALIDATE(m_SumFreeSize == ctx.calculatedSumFreeSize);
  8104. // Validate free node lists.
  8105. for (uint32_t level = 0; level < m_LevelCount; ++level)
  8106. {
  8107. VMA_VALIDATE(m_FreeList[level].front == VMA_NULL ||
  8108. m_FreeList[level].front->free.prev == VMA_NULL);
  8109. for (Node* node = m_FreeList[level].front;
  8110. node != VMA_NULL;
  8111. node = node->free.next)
  8112. {
  8113. VMA_VALIDATE(node->type == Node::TYPE_FREE);
  8114. if (node->free.next == VMA_NULL)
  8115. {
  8116. VMA_VALIDATE(m_FreeList[level].back == node);
  8117. }
  8118. else
  8119. {
  8120. VMA_VALIDATE(node->free.next->free.prev == node);
  8121. }
  8122. }
  8123. }
  8124. // Validate that free lists ar higher levels are empty.
  8125. for (uint32_t level = m_LevelCount; level < MAX_LEVELS; ++level)
  8126. {
  8127. VMA_VALIDATE(m_FreeList[level].front == VMA_NULL && m_FreeList[level].back == VMA_NULL);
  8128. }
  8129. return true;
  8130. }
  8131. void VmaBlockMetadata_Buddy::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const
  8132. {
  8133. inoutStats.statistics.blockCount++;
  8134. inoutStats.statistics.blockBytes += GetSize();
  8135. AddNodeToDetailedStatistics(inoutStats, m_Root, LevelToNodeSize(0));
  8136. const VkDeviceSize unusableSize = GetUnusableSize();
  8137. if (unusableSize > 0)
  8138. VmaAddDetailedStatisticsUnusedRange(inoutStats, unusableSize);
  8139. }
  8140. void VmaBlockMetadata_Buddy::AddStatistics(VmaStatistics& inoutStats) const
  8141. {
  8142. inoutStats.blockCount++;
  8143. inoutStats.allocationCount += (uint32_t)m_AllocationCount;
  8144. inoutStats.blockBytes += GetSize();
  8145. inoutStats.allocationBytes += GetSize() - m_SumFreeSize;
  8146. }
  8147. #if VMA_STATS_STRING_ENABLED
  8148. void VmaBlockMetadata_Buddy::PrintDetailedMap(class VmaJsonWriter& json, uint32_t mapRefCount) const
  8149. {
  8150. VmaDetailedStatistics stats;
  8151. VmaClearDetailedStatistics(stats);
  8152. AddDetailedStatistics(stats);
  8153. PrintDetailedMap_Begin(
  8154. json,
  8155. stats.statistics.blockBytes - stats.statistics.allocationBytes,
  8156. stats.statistics.allocationCount,
  8157. stats.unusedRangeCount,
  8158. mapRefCount);
  8159. PrintDetailedMapNode(json, m_Root, LevelToNodeSize(0));
  8160. const VkDeviceSize unusableSize = GetUnusableSize();
  8161. if (unusableSize > 0)
  8162. {
  8163. PrintDetailedMap_UnusedRange(json,
  8164. m_UsableSize, // offset
  8165. unusableSize); // size
  8166. }
  8167. PrintDetailedMap_End(json);
  8168. }
  8169. #endif // VMA_STATS_STRING_ENABLED
  8170. bool VmaBlockMetadata_Buddy::CreateAllocationRequest(
  8171. VkDeviceSize allocSize,
  8172. VkDeviceSize allocAlignment,
  8173. bool upperAddress,
  8174. VmaSuballocationType allocType,
  8175. uint32_t strategy,
  8176. VmaAllocationRequest* pAllocationRequest)
  8177. {
  8178. VMA_ASSERT(!upperAddress && "VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT can be used only with linear algorithm.");
  8179. allocSize = AlignAllocationSize(allocSize);
  8180. // Simple way to respect bufferImageGranularity. May be optimized some day.
  8181. // Whenever it might be an OPTIMAL image...
  8182. if (allocType == VMA_SUBALLOCATION_TYPE_UNKNOWN ||
  8183. allocType == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
  8184. allocType == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL)
  8185. {
  8186. allocAlignment = VMA_MAX(allocAlignment, GetBufferImageGranularity());
  8187. allocSize = VmaAlignUp(allocSize, GetBufferImageGranularity());
  8188. }
  8189. if (allocSize > m_UsableSize)
  8190. {
  8191. return false;
  8192. }
  8193. const uint32_t targetLevel = AllocSizeToLevel(allocSize);
  8194. for (uint32_t level = targetLevel; level--; )
  8195. {
  8196. for (Node* freeNode = m_FreeList[level].front;
  8197. freeNode != VMA_NULL;
  8198. freeNode = freeNode->free.next)
  8199. {
  8200. if (freeNode->offset % allocAlignment == 0)
  8201. {
  8202. pAllocationRequest->type = VmaAllocationRequestType::Normal;
  8203. pAllocationRequest->allocHandle = (VmaAllocHandle)(freeNode->offset + 1);
  8204. pAllocationRequest->size = allocSize;
  8205. pAllocationRequest->customData = (void*)(uintptr_t)level;
  8206. return true;
  8207. }
  8208. }
  8209. }
  8210. return false;
  8211. }
  8212. void VmaBlockMetadata_Buddy::Alloc(
  8213. const VmaAllocationRequest& request,
  8214. VmaSuballocationType type,
  8215. void* userData)
  8216. {
  8217. VMA_ASSERT(request.type == VmaAllocationRequestType::Normal);
  8218. const uint32_t targetLevel = AllocSizeToLevel(request.size);
  8219. uint32_t currLevel = (uint32_t)(uintptr_t)request.customData;
  8220. Node* currNode = m_FreeList[currLevel].front;
  8221. VMA_ASSERT(currNode != VMA_NULL && currNode->type == Node::TYPE_FREE);
  8222. const VkDeviceSize offset = (VkDeviceSize)request.allocHandle - 1;
  8223. while (currNode->offset != offset)
  8224. {
  8225. currNode = currNode->free.next;
  8226. VMA_ASSERT(currNode != VMA_NULL && currNode->type == Node::TYPE_FREE);
  8227. }
  8228. // Go down, splitting free nodes.
  8229. while (currLevel < targetLevel)
  8230. {
  8231. // currNode is already first free node at currLevel.
  8232. // Remove it from list of free nodes at this currLevel.
  8233. RemoveFromFreeList(currLevel, currNode);
  8234. const uint32_t childrenLevel = currLevel + 1;
  8235. // Create two free sub-nodes.
  8236. Node* leftChild = m_NodeAllocator.Alloc();
  8237. Node* rightChild = m_NodeAllocator.Alloc();
  8238. leftChild->offset = currNode->offset;
  8239. leftChild->type = Node::TYPE_FREE;
  8240. leftChild->parent = currNode;
  8241. leftChild->buddy = rightChild;
  8242. rightChild->offset = currNode->offset + LevelToNodeSize(childrenLevel);
  8243. rightChild->type = Node::TYPE_FREE;
  8244. rightChild->parent = currNode;
  8245. rightChild->buddy = leftChild;
  8246. // Convert current currNode to split type.
  8247. currNode->type = Node::TYPE_SPLIT;
  8248. currNode->split.leftChild = leftChild;
  8249. // Add child nodes to free list. Order is important!
  8250. AddToFreeListFront(childrenLevel, rightChild);
  8251. AddToFreeListFront(childrenLevel, leftChild);
  8252. ++m_FreeCount;
  8253. ++currLevel;
  8254. currNode = m_FreeList[currLevel].front;
  8255. /*
  8256. We can be sure that currNode, as left child of node previously split,
  8257. also fulfills the alignment requirement.
  8258. */
  8259. }
  8260. // Remove from free list.
  8261. VMA_ASSERT(currLevel == targetLevel &&
  8262. currNode != VMA_NULL &&
  8263. currNode->type == Node::TYPE_FREE);
  8264. RemoveFromFreeList(currLevel, currNode);
  8265. // Convert to allocation node.
  8266. currNode->type = Node::TYPE_ALLOCATION;
  8267. currNode->allocation.userData = userData;
  8268. ++m_AllocationCount;
  8269. --m_FreeCount;
  8270. m_SumFreeSize -= request.size;
  8271. }
  8272. void VmaBlockMetadata_Buddy::GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo)
  8273. {
  8274. uint32_t level = 0;
  8275. outInfo.offset = (VkDeviceSize)allocHandle - 1;
  8276. const Node* const node = FindAllocationNode(outInfo.offset, level);
  8277. outInfo.size = LevelToNodeSize(level);
  8278. outInfo.pUserData = node->allocation.userData;
  8279. }
  8280. void* VmaBlockMetadata_Buddy::GetAllocationUserData(VmaAllocHandle allocHandle) const
  8281. {
  8282. uint32_t level = 0;
  8283. const Node* const node = FindAllocationNode((VkDeviceSize)allocHandle - 1, level);
  8284. return node->allocation.userData;
  8285. }
  8286. VmaAllocHandle VmaBlockMetadata_Buddy::GetAllocationListBegin() const
  8287. {
  8288. // Function only used for defragmentation, which is disabled for this algorithm
  8289. return VK_NULL_HANDLE;
  8290. }
  8291. VmaAllocHandle VmaBlockMetadata_Buddy::GetNextAllocation(VmaAllocHandle prevAlloc) const
  8292. {
  8293. // Function only used for defragmentation, which is disabled for this algorithm
  8294. return VK_NULL_HANDLE;
  8295. }
  8296. void VmaBlockMetadata_Buddy::DeleteNodeChildren(Node* node)
  8297. {
  8298. if (node->type == Node::TYPE_SPLIT)
  8299. {
  8300. DeleteNodeChildren(node->split.leftChild->buddy);
  8301. DeleteNodeChildren(node->split.leftChild);
  8302. const VkAllocationCallbacks* allocationCallbacks = GetAllocationCallbacks();
  8303. m_NodeAllocator.Free(node->split.leftChild->buddy);
  8304. m_NodeAllocator.Free(node->split.leftChild);
  8305. }
  8306. }
  8307. void VmaBlockMetadata_Buddy::Clear()
  8308. {
  8309. DeleteNodeChildren(m_Root);
  8310. m_Root->type = Node::TYPE_FREE;
  8311. m_AllocationCount = 0;
  8312. m_FreeCount = 1;
  8313. m_SumFreeSize = m_UsableSize;
  8314. }
  8315. void VmaBlockMetadata_Buddy::SetAllocationUserData(VmaAllocHandle allocHandle, void* userData)
  8316. {
  8317. uint32_t level = 0;
  8318. Node* const node = FindAllocationNode((VkDeviceSize)allocHandle - 1, level);
  8319. node->allocation.userData = userData;
  8320. }
  8321. VmaBlockMetadata_Buddy::Node* VmaBlockMetadata_Buddy::FindAllocationNode(VkDeviceSize offset, uint32_t& outLevel) const
  8322. {
  8323. Node* node = m_Root;
  8324. VkDeviceSize nodeOffset = 0;
  8325. outLevel = 0;
  8326. VkDeviceSize levelNodeSize = LevelToNodeSize(0);
  8327. while (node->type == Node::TYPE_SPLIT)
  8328. {
  8329. const VkDeviceSize nextLevelNodeSize = levelNodeSize >> 1;
  8330. if (offset < nodeOffset + nextLevelNodeSize)
  8331. {
  8332. node = node->split.leftChild;
  8333. }
  8334. else
  8335. {
  8336. node = node->split.leftChild->buddy;
  8337. nodeOffset += nextLevelNodeSize;
  8338. }
  8339. ++outLevel;
  8340. levelNodeSize = nextLevelNodeSize;
  8341. }
  8342. VMA_ASSERT(node != VMA_NULL && node->type == Node::TYPE_ALLOCATION);
  8343. return node;
  8344. }
  8345. bool VmaBlockMetadata_Buddy::ValidateNode(ValidationContext& ctx, const Node* parent, const Node* curr, uint32_t level, VkDeviceSize levelNodeSize) const
  8346. {
  8347. VMA_VALIDATE(level < m_LevelCount);
  8348. VMA_VALIDATE(curr->parent == parent);
  8349. VMA_VALIDATE((curr->buddy == VMA_NULL) == (parent == VMA_NULL));
  8350. VMA_VALIDATE(curr->buddy == VMA_NULL || curr->buddy->buddy == curr);
  8351. switch (curr->type)
  8352. {
  8353. case Node::TYPE_FREE:
  8354. // curr->free.prev, next are validated separately.
  8355. ctx.calculatedSumFreeSize += levelNodeSize;
  8356. ++ctx.calculatedFreeCount;
  8357. break;
  8358. case Node::TYPE_ALLOCATION:
  8359. ++ctx.calculatedAllocationCount;
  8360. if (!IsVirtual())
  8361. {
  8362. VMA_VALIDATE(curr->allocation.userData != VMA_NULL);
  8363. }
  8364. break;
  8365. case Node::TYPE_SPLIT:
  8366. {
  8367. const uint32_t childrenLevel = level + 1;
  8368. const VkDeviceSize childrenLevelNodeSize = levelNodeSize >> 1;
  8369. const Node* const leftChild = curr->split.leftChild;
  8370. VMA_VALIDATE(leftChild != VMA_NULL);
  8371. VMA_VALIDATE(leftChild->offset == curr->offset);
  8372. if (!ValidateNode(ctx, curr, leftChild, childrenLevel, childrenLevelNodeSize))
  8373. {
  8374. VMA_VALIDATE(false && "ValidateNode for left child failed.");
  8375. }
  8376. const Node* const rightChild = leftChild->buddy;
  8377. VMA_VALIDATE(rightChild->offset == curr->offset + childrenLevelNodeSize);
  8378. if (!ValidateNode(ctx, curr, rightChild, childrenLevel, childrenLevelNodeSize))
  8379. {
  8380. VMA_VALIDATE(false && "ValidateNode for right child failed.");
  8381. }
  8382. }
  8383. break;
  8384. default:
  8385. return false;
  8386. }
  8387. return true;
  8388. }
  8389. uint32_t VmaBlockMetadata_Buddy::AllocSizeToLevel(VkDeviceSize allocSize) const
  8390. {
  8391. // I know this could be optimized somehow e.g. by using std::log2p1 from C++20.
  8392. uint32_t level = 0;
  8393. VkDeviceSize currLevelNodeSize = m_UsableSize;
  8394. VkDeviceSize nextLevelNodeSize = currLevelNodeSize >> 1;
  8395. while (allocSize <= nextLevelNodeSize && level + 1 < m_LevelCount)
  8396. {
  8397. ++level;
  8398. currLevelNodeSize >>= 1;
  8399. nextLevelNodeSize >>= 1;
  8400. }
  8401. return level;
  8402. }
  8403. void VmaBlockMetadata_Buddy::Free(VmaAllocHandle allocHandle)
  8404. {
  8405. uint32_t level = 0;
  8406. Node* node = FindAllocationNode((VkDeviceSize)allocHandle - 1, level);
  8407. ++m_FreeCount;
  8408. --m_AllocationCount;
  8409. m_SumFreeSize += LevelToNodeSize(level);
  8410. node->type = Node::TYPE_FREE;
  8411. // Join free nodes if possible.
  8412. while (level > 0 && node->buddy->type == Node::TYPE_FREE)
  8413. {
  8414. RemoveFromFreeList(level, node->buddy);
  8415. Node* const parent = node->parent;
  8416. m_NodeAllocator.Free(node->buddy);
  8417. m_NodeAllocator.Free(node);
  8418. parent->type = Node::TYPE_FREE;
  8419. node = parent;
  8420. --level;
  8421. --m_FreeCount;
  8422. }
  8423. AddToFreeListFront(level, node);
  8424. }
  8425. void VmaBlockMetadata_Buddy::AddNodeToDetailedStatistics(VmaDetailedStatistics& inoutStats, const Node* node, VkDeviceSize levelNodeSize) const
  8426. {
  8427. switch (node->type)
  8428. {
  8429. case Node::TYPE_FREE:
  8430. VmaAddDetailedStatisticsUnusedRange(inoutStats, levelNodeSize);
  8431. break;
  8432. case Node::TYPE_ALLOCATION:
  8433. VmaAddDetailedStatisticsAllocation(inoutStats, levelNodeSize);
  8434. break;
  8435. case Node::TYPE_SPLIT:
  8436. {
  8437. const VkDeviceSize childrenNodeSize = levelNodeSize / 2;
  8438. const Node* const leftChild = node->split.leftChild;
  8439. AddNodeToDetailedStatistics(inoutStats, leftChild, childrenNodeSize);
  8440. const Node* const rightChild = leftChild->buddy;
  8441. AddNodeToDetailedStatistics(inoutStats, rightChild, childrenNodeSize);
  8442. }
  8443. break;
  8444. default:
  8445. VMA_ASSERT(0);
  8446. }
  8447. }
  8448. void VmaBlockMetadata_Buddy::AddToFreeListFront(uint32_t level, Node* node)
  8449. {
  8450. VMA_ASSERT(node->type == Node::TYPE_FREE);
  8451. // List is empty.
  8452. Node* const frontNode = m_FreeList[level].front;
  8453. if (frontNode == VMA_NULL)
  8454. {
  8455. VMA_ASSERT(m_FreeList[level].back == VMA_NULL);
  8456. node->free.prev = node->free.next = VMA_NULL;
  8457. m_FreeList[level].front = m_FreeList[level].back = node;
  8458. }
  8459. else
  8460. {
  8461. VMA_ASSERT(frontNode->free.prev == VMA_NULL);
  8462. node->free.prev = VMA_NULL;
  8463. node->free.next = frontNode;
  8464. frontNode->free.prev = node;
  8465. m_FreeList[level].front = node;
  8466. }
  8467. }
  8468. void VmaBlockMetadata_Buddy::RemoveFromFreeList(uint32_t level, Node* node)
  8469. {
  8470. VMA_ASSERT(m_FreeList[level].front != VMA_NULL);
  8471. // It is at the front.
  8472. if (node->free.prev == VMA_NULL)
  8473. {
  8474. VMA_ASSERT(m_FreeList[level].front == node);
  8475. m_FreeList[level].front = node->free.next;
  8476. }
  8477. else
  8478. {
  8479. Node* const prevFreeNode = node->free.prev;
  8480. VMA_ASSERT(prevFreeNode->free.next == node);
  8481. prevFreeNode->free.next = node->free.next;
  8482. }
  8483. // It is at the back.
  8484. if (node->free.next == VMA_NULL)
  8485. {
  8486. VMA_ASSERT(m_FreeList[level].back == node);
  8487. m_FreeList[level].back = node->free.prev;
  8488. }
  8489. else
  8490. {
  8491. Node* const nextFreeNode = node->free.next;
  8492. VMA_ASSERT(nextFreeNode->free.prev == node);
  8493. nextFreeNode->free.prev = node->free.prev;
  8494. }
  8495. }
  8496. void VmaBlockMetadata_Buddy::DebugLogAllAllocationNode(Node* node, uint32_t level) const
  8497. {
  8498. switch (node->type)
  8499. {
  8500. case Node::TYPE_FREE:
  8501. break;
  8502. case Node::TYPE_ALLOCATION:
  8503. DebugLogAllocation(node->offset, LevelToNodeSize(level), node->allocation.userData);
  8504. break;
  8505. case Node::TYPE_SPLIT:
  8506. {
  8507. ++level;
  8508. DebugLogAllAllocationNode(node->split.leftChild, level);
  8509. DebugLogAllAllocationNode(node->split.leftChild->buddy, level);
  8510. }
  8511. break;
  8512. default:
  8513. VMA_ASSERT(0);
  8514. }
  8515. }
  8516. #if VMA_STATS_STRING_ENABLED
  8517. void VmaBlockMetadata_Buddy::PrintDetailedMapNode(class VmaJsonWriter& json, const Node* node, VkDeviceSize levelNodeSize) const
  8518. {
  8519. switch (node->type)
  8520. {
  8521. case Node::TYPE_FREE:
  8522. PrintDetailedMap_UnusedRange(json, node->offset, levelNodeSize);
  8523. break;
  8524. case Node::TYPE_ALLOCATION:
  8525. PrintDetailedMap_Allocation(json, node->offset, levelNodeSize, node->allocation.userData);
  8526. break;
  8527. case Node::TYPE_SPLIT:
  8528. {
  8529. const VkDeviceSize childrenNodeSize = levelNodeSize / 2;
  8530. const Node* const leftChild = node->split.leftChild;
  8531. PrintDetailedMapNode(json, leftChild, childrenNodeSize);
  8532. const Node* const rightChild = leftChild->buddy;
  8533. PrintDetailedMapNode(json, rightChild, childrenNodeSize);
  8534. }
  8535. break;
  8536. default:
  8537. VMA_ASSERT(0);
  8538. }
  8539. }
  8540. #endif // VMA_STATS_STRING_ENABLED
  8541. #endif // _VMA_BLOCK_METADATA_BUDDY_FUNCTIONS
  8542. #endif // _VMA_BLOCK_METADATA_BUDDY
  8543. #endif // #if 0
  8544. #ifndef _VMA_BLOCK_METADATA_TLSF
  8545. // To not search current larger region if first allocation won't succeed and skip to smaller range
  8546. // use with VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT as strategy in CreateAllocationRequest().
  8547. // When fragmentation and reusal of previous blocks doesn't matter then use with
  8548. // VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT for fastest alloc time possible.
  8549. class VmaBlockMetadata_TLSF : public VmaBlockMetadata
  8550. {
  8551. VMA_CLASS_NO_COPY(VmaBlockMetadata_TLSF)
  8552. public:
  8553. VmaBlockMetadata_TLSF(const VkAllocationCallbacks* pAllocationCallbacks,
  8554. VkDeviceSize bufferImageGranularity, bool isVirtual);
  8555. virtual ~VmaBlockMetadata_TLSF();
  8556. size_t GetAllocationCount() const override { return m_AllocCount; }
  8557. size_t GetFreeRegionsCount() const override { return m_BlocksFreeCount + 1; }
  8558. VkDeviceSize GetSumFreeSize() const override { return m_BlocksFreeSize + m_NullBlock->size; }
  8559. bool IsEmpty() const override { return m_NullBlock->offset == 0; }
  8560. VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const override { return ((Block*)allocHandle)->offset; };
  8561. void Init(VkDeviceSize size) override;
  8562. bool Validate() const override;
  8563. void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const override;
  8564. void AddStatistics(VmaStatistics& inoutStats) const override;
  8565. #if VMA_STATS_STRING_ENABLED
  8566. void PrintDetailedMap(class VmaJsonWriter& json) const override;
  8567. #endif
  8568. bool CreateAllocationRequest(
  8569. VkDeviceSize allocSize,
  8570. VkDeviceSize allocAlignment,
  8571. bool upperAddress,
  8572. VmaSuballocationType allocType,
  8573. uint32_t strategy,
  8574. VmaAllocationRequest* pAllocationRequest) override;
  8575. VkResult CheckCorruption(const void* pBlockData) override;
  8576. void Alloc(
  8577. const VmaAllocationRequest& request,
  8578. VmaSuballocationType type,
  8579. void* userData) override;
  8580. void Free(VmaAllocHandle allocHandle) override;
  8581. void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) override;
  8582. void* GetAllocationUserData(VmaAllocHandle allocHandle) const override;
  8583. VmaAllocHandle GetAllocationListBegin() const override;
  8584. VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const override;
  8585. VkDeviceSize GetNextFreeRegionSize(VmaAllocHandle alloc) const override;
  8586. void Clear() override;
  8587. void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) override;
  8588. void DebugLogAllAllocations() const override;
  8589. private:
  8590. // According to original paper it should be preferable 4 or 5:
  8591. // M. Masmano, I. Ripoll, A. Crespo, and J. Real "TLSF: a New Dynamic Memory Allocator for Real-Time Systems"
  8592. // http://www.gii.upv.es/tlsf/files/ecrts04_tlsf.pdf
  8593. static const uint8_t SECOND_LEVEL_INDEX = 5;
  8594. static const uint16_t SMALL_BUFFER_SIZE = 256;
  8595. static const uint32_t INITIAL_BLOCK_ALLOC_COUNT = 16;
  8596. static const uint8_t MEMORY_CLASS_SHIFT = 7;
  8597. static const uint8_t MAX_MEMORY_CLASSES = 65 - MEMORY_CLASS_SHIFT;
  8598. class Block
  8599. {
  8600. public:
  8601. VkDeviceSize offset;
  8602. VkDeviceSize size;
  8603. Block* prevPhysical;
  8604. Block* nextPhysical;
  8605. void MarkFree() { prevFree = VMA_NULL; }
  8606. void MarkTaken() { prevFree = this; }
  8607. bool IsFree() const { return prevFree != this; }
  8608. void*& UserData() { VMA_HEAVY_ASSERT(!IsFree()); return userData; }
  8609. Block*& PrevFree() { return prevFree; }
  8610. Block*& NextFree() { VMA_HEAVY_ASSERT(IsFree()); return nextFree; }
  8611. private:
  8612. Block* prevFree; // Address of the same block here indicates that block is taken
  8613. union
  8614. {
  8615. Block* nextFree;
  8616. void* userData;
  8617. };
  8618. };
  8619. size_t m_AllocCount;
  8620. // Total number of free blocks besides null block
  8621. size_t m_BlocksFreeCount;
  8622. // Total size of free blocks excluding null block
  8623. VkDeviceSize m_BlocksFreeSize;
  8624. uint32_t m_IsFreeBitmap;
  8625. uint8_t m_MemoryClasses;
  8626. uint32_t m_InnerIsFreeBitmap[MAX_MEMORY_CLASSES];
  8627. uint32_t m_ListsCount;
  8628. /*
  8629. * 0: 0-3 lists for small buffers
  8630. * 1+: 0-(2^SLI-1) lists for normal buffers
  8631. */
  8632. Block** m_FreeList;
  8633. VmaPoolAllocator<Block> m_BlockAllocator;
  8634. Block* m_NullBlock;
  8635. VmaBlockBufferImageGranularity m_GranularityHandler;
  8636. uint8_t SizeToMemoryClass(VkDeviceSize size) const;
  8637. uint16_t SizeToSecondIndex(VkDeviceSize size, uint8_t memoryClass) const;
  8638. uint32_t GetListIndex(uint8_t memoryClass, uint16_t secondIndex) const;
  8639. uint32_t GetListIndex(VkDeviceSize size) const;
  8640. void RemoveFreeBlock(Block* block);
  8641. void InsertFreeBlock(Block* block);
  8642. void MergeBlock(Block* block, Block* prev);
  8643. Block* FindFreeBlock(VkDeviceSize size, uint32_t& listIndex) const;
  8644. bool CheckBlock(
  8645. Block& block,
  8646. uint32_t listIndex,
  8647. VkDeviceSize allocSize,
  8648. VkDeviceSize allocAlignment,
  8649. VmaSuballocationType allocType,
  8650. VmaAllocationRequest* pAllocationRequest);
  8651. };
  8652. #ifndef _VMA_BLOCK_METADATA_TLSF_FUNCTIONS
  8653. VmaBlockMetadata_TLSF::VmaBlockMetadata_TLSF(const VkAllocationCallbacks* pAllocationCallbacks,
  8654. VkDeviceSize bufferImageGranularity, bool isVirtual)
  8655. : VmaBlockMetadata(pAllocationCallbacks, bufferImageGranularity, isVirtual),
  8656. m_AllocCount(0),
  8657. m_BlocksFreeCount(0),
  8658. m_BlocksFreeSize(0),
  8659. m_IsFreeBitmap(0),
  8660. m_MemoryClasses(0),
  8661. m_ListsCount(0),
  8662. m_FreeList(VMA_NULL),
  8663. m_BlockAllocator(pAllocationCallbacks, INITIAL_BLOCK_ALLOC_COUNT),
  8664. m_NullBlock(VMA_NULL),
  8665. m_GranularityHandler(bufferImageGranularity) {}
  8666. VmaBlockMetadata_TLSF::~VmaBlockMetadata_TLSF()
  8667. {
  8668. if (m_FreeList)
  8669. vma_delete_array(GetAllocationCallbacks(), m_FreeList, m_ListsCount);
  8670. m_GranularityHandler.Destroy(GetAllocationCallbacks());
  8671. }
  8672. void VmaBlockMetadata_TLSF::Init(VkDeviceSize size)
  8673. {
  8674. VmaBlockMetadata::Init(size);
  8675. if (!IsVirtual())
  8676. m_GranularityHandler.Init(GetAllocationCallbacks(), size);
  8677. m_NullBlock = m_BlockAllocator.Alloc();
  8678. m_NullBlock->size = size;
  8679. m_NullBlock->offset = 0;
  8680. m_NullBlock->prevPhysical = VMA_NULL;
  8681. m_NullBlock->nextPhysical = VMA_NULL;
  8682. m_NullBlock->MarkFree();
  8683. m_NullBlock->NextFree() = VMA_NULL;
  8684. m_NullBlock->PrevFree() = VMA_NULL;
  8685. uint8_t memoryClass = SizeToMemoryClass(size);
  8686. uint16_t sli = SizeToSecondIndex(size, memoryClass);
  8687. m_ListsCount = (memoryClass == 0 ? 0 : (memoryClass - 1) * (1UL << SECOND_LEVEL_INDEX) + sli) + 1;
  8688. if (IsVirtual())
  8689. m_ListsCount += 1UL << SECOND_LEVEL_INDEX;
  8690. else
  8691. m_ListsCount += 4;
  8692. m_MemoryClasses = memoryClass + 2;
  8693. memset(m_InnerIsFreeBitmap, 0, MAX_MEMORY_CLASSES * sizeof(uint32_t));
  8694. m_FreeList = vma_new_array(GetAllocationCallbacks(), Block*, m_ListsCount);
  8695. memset(m_FreeList, 0, m_ListsCount * sizeof(Block*));
  8696. }
  8697. bool VmaBlockMetadata_TLSF::Validate() const
  8698. {
  8699. VMA_VALIDATE(GetSumFreeSize() <= GetSize());
  8700. VkDeviceSize calculatedSize = m_NullBlock->size;
  8701. VkDeviceSize calculatedFreeSize = m_NullBlock->size;
  8702. size_t allocCount = 0;
  8703. size_t freeCount = 0;
  8704. // Check integrity of free lists
  8705. for (uint32_t list = 0; list < m_ListsCount; ++list)
  8706. {
  8707. Block* block = m_FreeList[list];
  8708. if (block != VMA_NULL)
  8709. {
  8710. VMA_VALIDATE(block->IsFree());
  8711. VMA_VALIDATE(block->PrevFree() == VMA_NULL);
  8712. while (block->NextFree())
  8713. {
  8714. VMA_VALIDATE(block->NextFree()->IsFree());
  8715. VMA_VALIDATE(block->NextFree()->PrevFree() == block);
  8716. block = block->NextFree();
  8717. }
  8718. }
  8719. }
  8720. VkDeviceSize nextOffset = m_NullBlock->offset;
  8721. auto validateCtx = m_GranularityHandler.StartValidation(GetAllocationCallbacks(), IsVirtual());
  8722. VMA_VALIDATE(m_NullBlock->nextPhysical == VMA_NULL);
  8723. if (m_NullBlock->prevPhysical)
  8724. {
  8725. VMA_VALIDATE(m_NullBlock->prevPhysical->nextPhysical == m_NullBlock);
  8726. }
  8727. // Check all blocks
  8728. for (Block* prev = m_NullBlock->prevPhysical; prev != VMA_NULL; prev = prev->prevPhysical)
  8729. {
  8730. VMA_VALIDATE(prev->offset + prev->size == nextOffset);
  8731. nextOffset = prev->offset;
  8732. calculatedSize += prev->size;
  8733. uint32_t listIndex = GetListIndex(prev->size);
  8734. if (prev->IsFree())
  8735. {
  8736. ++freeCount;
  8737. // Check if free block belongs to free list
  8738. Block* freeBlock = m_FreeList[listIndex];
  8739. VMA_VALIDATE(freeBlock != VMA_NULL);
  8740. bool found = false;
  8741. do
  8742. {
  8743. if (freeBlock == prev)
  8744. found = true;
  8745. freeBlock = freeBlock->NextFree();
  8746. } while (!found && freeBlock != VMA_NULL);
  8747. VMA_VALIDATE(found);
  8748. calculatedFreeSize += prev->size;
  8749. }
  8750. else
  8751. {
  8752. ++allocCount;
  8753. // Check if taken block is not on a free list
  8754. Block* freeBlock = m_FreeList[listIndex];
  8755. while (freeBlock)
  8756. {
  8757. VMA_VALIDATE(freeBlock != prev);
  8758. freeBlock = freeBlock->NextFree();
  8759. }
  8760. if (!IsVirtual())
  8761. {
  8762. VMA_VALIDATE(m_GranularityHandler.Validate(validateCtx, prev->offset, prev->size));
  8763. }
  8764. }
  8765. if (prev->prevPhysical)
  8766. {
  8767. VMA_VALIDATE(prev->prevPhysical->nextPhysical == prev);
  8768. }
  8769. }
  8770. if (!IsVirtual())
  8771. {
  8772. VMA_VALIDATE(m_GranularityHandler.FinishValidation(validateCtx));
  8773. }
  8774. VMA_VALIDATE(nextOffset == 0);
  8775. VMA_VALIDATE(calculatedSize == GetSize());
  8776. VMA_VALIDATE(calculatedFreeSize == GetSumFreeSize());
  8777. VMA_VALIDATE(allocCount == m_AllocCount);
  8778. VMA_VALIDATE(freeCount == m_BlocksFreeCount);
  8779. return true;
  8780. }
  8781. void VmaBlockMetadata_TLSF::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const
  8782. {
  8783. inoutStats.statistics.blockCount++;
  8784. inoutStats.statistics.blockBytes += GetSize();
  8785. if (m_NullBlock->size > 0)
  8786. VmaAddDetailedStatisticsUnusedRange(inoutStats, m_NullBlock->size);
  8787. for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical)
  8788. {
  8789. if (block->IsFree())
  8790. VmaAddDetailedStatisticsUnusedRange(inoutStats, block->size);
  8791. else
  8792. VmaAddDetailedStatisticsAllocation(inoutStats, block->size);
  8793. }
  8794. }
  8795. void VmaBlockMetadata_TLSF::AddStatistics(VmaStatistics& inoutStats) const
  8796. {
  8797. inoutStats.blockCount++;
  8798. inoutStats.allocationCount += (uint32_t)m_AllocCount;
  8799. inoutStats.blockBytes += GetSize();
  8800. inoutStats.allocationBytes += GetSize() - GetSumFreeSize();
  8801. }
  8802. #if VMA_STATS_STRING_ENABLED
  8803. void VmaBlockMetadata_TLSF::PrintDetailedMap(class VmaJsonWriter& json) const
  8804. {
  8805. size_t blockCount = m_AllocCount + m_BlocksFreeCount;
  8806. VmaStlAllocator<Block*> allocator(GetAllocationCallbacks());
  8807. VmaVector<Block*, VmaStlAllocator<Block*>> blockList(blockCount, allocator);
  8808. size_t i = blockCount;
  8809. for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical)
  8810. {
  8811. blockList[--i] = block;
  8812. }
  8813. VMA_ASSERT(i == 0);
  8814. VmaDetailedStatistics stats;
  8815. VmaClearDetailedStatistics(stats);
  8816. AddDetailedStatistics(stats);
  8817. PrintDetailedMap_Begin(json,
  8818. stats.statistics.blockBytes - stats.statistics.allocationBytes,
  8819. stats.statistics.allocationCount,
  8820. stats.unusedRangeCount);
  8821. for (; i < blockCount; ++i)
  8822. {
  8823. Block* block = blockList[i];
  8824. if (block->IsFree())
  8825. PrintDetailedMap_UnusedRange(json, block->offset, block->size);
  8826. else
  8827. PrintDetailedMap_Allocation(json, block->offset, block->size, block->UserData());
  8828. }
  8829. if (m_NullBlock->size > 0)
  8830. PrintDetailedMap_UnusedRange(json, m_NullBlock->offset, m_NullBlock->size);
  8831. PrintDetailedMap_End(json);
  8832. }
  8833. #endif
  8834. bool VmaBlockMetadata_TLSF::CreateAllocationRequest(
  8835. VkDeviceSize allocSize,
  8836. VkDeviceSize allocAlignment,
  8837. bool upperAddress,
  8838. VmaSuballocationType allocType,
  8839. uint32_t strategy,
  8840. VmaAllocationRequest* pAllocationRequest)
  8841. {
  8842. VMA_ASSERT(allocSize > 0 && "Cannot allocate empty block!");
  8843. VMA_ASSERT(!upperAddress && "VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT can be used only with linear algorithm.");
  8844. // For small granularity round up
  8845. if (!IsVirtual())
  8846. m_GranularityHandler.RoundupAllocRequest(allocType, allocSize, allocAlignment);
  8847. allocSize += GetDebugMargin();
  8848. // Quick check for too small pool
  8849. if (allocSize > GetSumFreeSize())
  8850. return false;
  8851. // If no free blocks in pool then check only null block
  8852. if (m_BlocksFreeCount == 0)
  8853. return CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest);
  8854. // Round up to the next block
  8855. VkDeviceSize sizeForNextList = allocSize;
  8856. VkDeviceSize smallSizeStep = SMALL_BUFFER_SIZE / (IsVirtual() ? 1 << SECOND_LEVEL_INDEX : 4);
  8857. if (allocSize > SMALL_BUFFER_SIZE)
  8858. {
  8859. sizeForNextList += (1ULL << (VMA_BITSCAN_MSB(allocSize) - SECOND_LEVEL_INDEX));
  8860. }
  8861. else if (allocSize > SMALL_BUFFER_SIZE - smallSizeStep)
  8862. sizeForNextList = SMALL_BUFFER_SIZE + 1;
  8863. else
  8864. sizeForNextList += smallSizeStep;
  8865. uint32_t nextListIndex = 0;
  8866. uint32_t prevListIndex = 0;
  8867. Block* nextListBlock = VMA_NULL;
  8868. Block* prevListBlock = VMA_NULL;
  8869. // Check blocks according to strategies
  8870. if (strategy & VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT)
  8871. {
  8872. // Quick check for larger block first
  8873. nextListBlock = FindFreeBlock(sizeForNextList, nextListIndex);
  8874. if (nextListBlock != VMA_NULL && CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8875. return true;
  8876. // If not fitted then null block
  8877. if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest))
  8878. return true;
  8879. // Null block failed, search larger bucket
  8880. while (nextListBlock)
  8881. {
  8882. if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8883. return true;
  8884. nextListBlock = nextListBlock->NextFree();
  8885. }
  8886. // Failed again, check best fit bucket
  8887. prevListBlock = FindFreeBlock(allocSize, prevListIndex);
  8888. while (prevListBlock)
  8889. {
  8890. if (CheckBlock(*prevListBlock, prevListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8891. return true;
  8892. prevListBlock = prevListBlock->NextFree();
  8893. }
  8894. }
  8895. else if (strategy & VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT)
  8896. {
  8897. // Check best fit bucket
  8898. prevListBlock = FindFreeBlock(allocSize, prevListIndex);
  8899. while (prevListBlock)
  8900. {
  8901. if (CheckBlock(*prevListBlock, prevListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8902. return true;
  8903. prevListBlock = prevListBlock->NextFree();
  8904. }
  8905. // If failed check null block
  8906. if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest))
  8907. return true;
  8908. // Check larger bucket
  8909. nextListBlock = FindFreeBlock(sizeForNextList, nextListIndex);
  8910. while (nextListBlock)
  8911. {
  8912. if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8913. return true;
  8914. nextListBlock = nextListBlock->NextFree();
  8915. }
  8916. }
  8917. else if (strategy & VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT )
  8918. {
  8919. // Perform search from the start
  8920. VmaStlAllocator<Block*> allocator(GetAllocationCallbacks());
  8921. VmaVector<Block*, VmaStlAllocator<Block*>> blockList(m_BlocksFreeCount, allocator);
  8922. size_t i = m_BlocksFreeCount;
  8923. for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical)
  8924. {
  8925. if (block->IsFree() && block->size >= allocSize)
  8926. blockList[--i] = block;
  8927. }
  8928. for (; i < m_BlocksFreeCount; ++i)
  8929. {
  8930. Block& block = *blockList[i];
  8931. if (CheckBlock(block, GetListIndex(block.size), allocSize, allocAlignment, allocType, pAllocationRequest))
  8932. return true;
  8933. }
  8934. // If failed check null block
  8935. if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest))
  8936. return true;
  8937. // Whole range searched, no more memory
  8938. return false;
  8939. }
  8940. else
  8941. {
  8942. // Check larger bucket
  8943. nextListBlock = FindFreeBlock(sizeForNextList, nextListIndex);
  8944. while (nextListBlock)
  8945. {
  8946. if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8947. return true;
  8948. nextListBlock = nextListBlock->NextFree();
  8949. }
  8950. // If failed check null block
  8951. if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest))
  8952. return true;
  8953. // Check best fit bucket
  8954. prevListBlock = FindFreeBlock(allocSize, prevListIndex);
  8955. while (prevListBlock)
  8956. {
  8957. if (CheckBlock(*prevListBlock, prevListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8958. return true;
  8959. prevListBlock = prevListBlock->NextFree();
  8960. }
  8961. }
  8962. // Worst case, full search has to be done
  8963. while (++nextListIndex < m_ListsCount)
  8964. {
  8965. nextListBlock = m_FreeList[nextListIndex];
  8966. while (nextListBlock)
  8967. {
  8968. if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8969. return true;
  8970. nextListBlock = nextListBlock->NextFree();
  8971. }
  8972. }
  8973. // No more memory sadly
  8974. return false;
  8975. }
  8976. VkResult VmaBlockMetadata_TLSF::CheckCorruption(const void* pBlockData)
  8977. {
  8978. for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical)
  8979. {
  8980. if (!block->IsFree())
  8981. {
  8982. if (!VmaValidateMagicValue(pBlockData, block->offset + block->size))
  8983. {
  8984. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
  8985. return VK_ERROR_UNKNOWN_COPY;
  8986. }
  8987. }
  8988. }
  8989. return VK_SUCCESS;
  8990. }
  8991. void VmaBlockMetadata_TLSF::Alloc(
  8992. const VmaAllocationRequest& request,
  8993. VmaSuballocationType type,
  8994. void* userData)
  8995. {
  8996. VMA_ASSERT(request.type == VmaAllocationRequestType::TLSF);
  8997. // Get block and pop it from the free list
  8998. Block* currentBlock = (Block*)request.allocHandle;
  8999. VkDeviceSize offset = request.algorithmData;
  9000. VMA_ASSERT(currentBlock != VMA_NULL);
  9001. VMA_ASSERT(currentBlock->offset <= offset);
  9002. if (currentBlock != m_NullBlock)
  9003. RemoveFreeBlock(currentBlock);
  9004. VkDeviceSize debugMargin = GetDebugMargin();
  9005. VkDeviceSize misssingAlignment = offset - currentBlock->offset;
  9006. // Append missing alignment to prev block or create new one
  9007. if (misssingAlignment)
  9008. {
  9009. Block* prevBlock = currentBlock->prevPhysical;
  9010. VMA_ASSERT(prevBlock != VMA_NULL && "There should be no missing alignment at offset 0!");
  9011. if (prevBlock->IsFree() && prevBlock->size != debugMargin)
  9012. {
  9013. uint32_t oldList = GetListIndex(prevBlock->size);
  9014. prevBlock->size += misssingAlignment;
  9015. // Check if new size crosses list bucket
  9016. if (oldList != GetListIndex(prevBlock->size))
  9017. {
  9018. prevBlock->size -= misssingAlignment;
  9019. RemoveFreeBlock(prevBlock);
  9020. prevBlock->size += misssingAlignment;
  9021. InsertFreeBlock(prevBlock);
  9022. }
  9023. else
  9024. m_BlocksFreeSize += misssingAlignment;
  9025. }
  9026. else
  9027. {
  9028. Block* newBlock = m_BlockAllocator.Alloc();
  9029. currentBlock->prevPhysical = newBlock;
  9030. prevBlock->nextPhysical = newBlock;
  9031. newBlock->prevPhysical = prevBlock;
  9032. newBlock->nextPhysical = currentBlock;
  9033. newBlock->size = misssingAlignment;
  9034. newBlock->offset = currentBlock->offset;
  9035. newBlock->MarkTaken();
  9036. InsertFreeBlock(newBlock);
  9037. }
  9038. currentBlock->size -= misssingAlignment;
  9039. currentBlock->offset += misssingAlignment;
  9040. }
  9041. VkDeviceSize size = request.size + debugMargin;
  9042. if (currentBlock->size == size)
  9043. {
  9044. if (currentBlock == m_NullBlock)
  9045. {
  9046. // Setup new null block
  9047. m_NullBlock = m_BlockAllocator.Alloc();
  9048. m_NullBlock->size = 0;
  9049. m_NullBlock->offset = currentBlock->offset + size;
  9050. m_NullBlock->prevPhysical = currentBlock;
  9051. m_NullBlock->nextPhysical = VMA_NULL;
  9052. m_NullBlock->MarkFree();
  9053. m_NullBlock->PrevFree() = VMA_NULL;
  9054. m_NullBlock->NextFree() = VMA_NULL;
  9055. currentBlock->nextPhysical = m_NullBlock;
  9056. currentBlock->MarkTaken();
  9057. }
  9058. }
  9059. else
  9060. {
  9061. VMA_ASSERT(currentBlock->size > size && "Proper block already found, shouldn't find smaller one!");
  9062. // Create new free block
  9063. Block* newBlock = m_BlockAllocator.Alloc();
  9064. newBlock->size = currentBlock->size - size;
  9065. newBlock->offset = currentBlock->offset + size;
  9066. newBlock->prevPhysical = currentBlock;
  9067. newBlock->nextPhysical = currentBlock->nextPhysical;
  9068. currentBlock->nextPhysical = newBlock;
  9069. currentBlock->size = size;
  9070. if (currentBlock == m_NullBlock)
  9071. {
  9072. m_NullBlock = newBlock;
  9073. m_NullBlock->MarkFree();
  9074. m_NullBlock->NextFree() = VMA_NULL;
  9075. m_NullBlock->PrevFree() = VMA_NULL;
  9076. currentBlock->MarkTaken();
  9077. }
  9078. else
  9079. {
  9080. newBlock->nextPhysical->prevPhysical = newBlock;
  9081. newBlock->MarkTaken();
  9082. InsertFreeBlock(newBlock);
  9083. }
  9084. }
  9085. currentBlock->UserData() = userData;
  9086. if (debugMargin > 0)
  9087. {
  9088. currentBlock->size -= debugMargin;
  9089. Block* newBlock = m_BlockAllocator.Alloc();
  9090. newBlock->size = debugMargin;
  9091. newBlock->offset = currentBlock->offset + currentBlock->size;
  9092. newBlock->prevPhysical = currentBlock;
  9093. newBlock->nextPhysical = currentBlock->nextPhysical;
  9094. newBlock->MarkTaken();
  9095. currentBlock->nextPhysical->prevPhysical = newBlock;
  9096. currentBlock->nextPhysical = newBlock;
  9097. InsertFreeBlock(newBlock);
  9098. }
  9099. if (!IsVirtual())
  9100. m_GranularityHandler.AllocPages((uint8_t)(uintptr_t)request.customData,
  9101. currentBlock->offset, currentBlock->size);
  9102. ++m_AllocCount;
  9103. }
  9104. void VmaBlockMetadata_TLSF::Free(VmaAllocHandle allocHandle)
  9105. {
  9106. Block* block = (Block*)allocHandle;
  9107. Block* next = block->nextPhysical;
  9108. VMA_ASSERT(!block->IsFree() && "Block is already free!");
  9109. if (!IsVirtual())
  9110. m_GranularityHandler.FreePages(block->offset, block->size);
  9111. --m_AllocCount;
  9112. VkDeviceSize debugMargin = GetDebugMargin();
  9113. if (debugMargin > 0)
  9114. {
  9115. RemoveFreeBlock(next);
  9116. MergeBlock(next, block);
  9117. block = next;
  9118. next = next->nextPhysical;
  9119. }
  9120. // Try merging
  9121. Block* prev = block->prevPhysical;
  9122. if (prev != VMA_NULL && prev->IsFree() && prev->size != debugMargin)
  9123. {
  9124. RemoveFreeBlock(prev);
  9125. MergeBlock(block, prev);
  9126. }
  9127. if (!next->IsFree())
  9128. InsertFreeBlock(block);
  9129. else if (next == m_NullBlock)
  9130. MergeBlock(m_NullBlock, block);
  9131. else
  9132. {
  9133. RemoveFreeBlock(next);
  9134. MergeBlock(next, block);
  9135. InsertFreeBlock(next);
  9136. }
  9137. }
  9138. void VmaBlockMetadata_TLSF::GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo)
  9139. {
  9140. Block* block = (Block*)allocHandle;
  9141. VMA_ASSERT(!block->IsFree() && "Cannot get allocation info for free block!");
  9142. outInfo.offset = block->offset;
  9143. outInfo.size = block->size;
  9144. outInfo.pUserData = block->UserData();
  9145. }
  9146. void* VmaBlockMetadata_TLSF::GetAllocationUserData(VmaAllocHandle allocHandle) const
  9147. {
  9148. Block* block = (Block*)allocHandle;
  9149. VMA_ASSERT(!block->IsFree() && "Cannot get user data for free block!");
  9150. return block->UserData();
  9151. }
  9152. VmaAllocHandle VmaBlockMetadata_TLSF::GetAllocationListBegin() const
  9153. {
  9154. if (m_AllocCount == 0)
  9155. return VK_NULL_HANDLE;
  9156. for (Block* block = m_NullBlock->prevPhysical; block; block = block->prevPhysical)
  9157. {
  9158. if (!block->IsFree())
  9159. return (VmaAllocHandle)block;
  9160. }
  9161. VMA_ASSERT(false && "If m_AllocCount > 0 then should find any allocation!");
  9162. return VK_NULL_HANDLE;
  9163. }
  9164. VmaAllocHandle VmaBlockMetadata_TLSF::GetNextAllocation(VmaAllocHandle prevAlloc) const
  9165. {
  9166. Block* startBlock = (Block*)prevAlloc;
  9167. VMA_ASSERT(!startBlock->IsFree() && "Incorrect block!");
  9168. for (Block* block = startBlock->prevPhysical; block; block = block->prevPhysical)
  9169. {
  9170. if (!block->IsFree())
  9171. return (VmaAllocHandle)block;
  9172. }
  9173. return VK_NULL_HANDLE;
  9174. }
  9175. VkDeviceSize VmaBlockMetadata_TLSF::GetNextFreeRegionSize(VmaAllocHandle alloc) const
  9176. {
  9177. Block* block = (Block*)alloc;
  9178. VMA_ASSERT(!block->IsFree() && "Incorrect block!");
  9179. if (block->prevPhysical)
  9180. return block->prevPhysical->IsFree() ? block->prevPhysical->size : 0;
  9181. return 0;
  9182. }
  9183. void VmaBlockMetadata_TLSF::Clear()
  9184. {
  9185. m_AllocCount = 0;
  9186. m_BlocksFreeCount = 0;
  9187. m_BlocksFreeSize = 0;
  9188. m_IsFreeBitmap = 0;
  9189. m_NullBlock->offset = 0;
  9190. m_NullBlock->size = GetSize();
  9191. Block* block = m_NullBlock->prevPhysical;
  9192. m_NullBlock->prevPhysical = VMA_NULL;
  9193. while (block)
  9194. {
  9195. Block* prev = block->prevPhysical;
  9196. m_BlockAllocator.Free(block);
  9197. block = prev;
  9198. }
  9199. memset(m_FreeList, 0, m_ListsCount * sizeof(Block*));
  9200. memset(m_InnerIsFreeBitmap, 0, m_MemoryClasses * sizeof(uint32_t));
  9201. m_GranularityHandler.Clear();
  9202. }
  9203. void VmaBlockMetadata_TLSF::SetAllocationUserData(VmaAllocHandle allocHandle, void* userData)
  9204. {
  9205. Block* block = (Block*)allocHandle;
  9206. VMA_ASSERT(!block->IsFree() && "Trying to set user data for not allocated block!");
  9207. block->UserData() = userData;
  9208. }
  9209. void VmaBlockMetadata_TLSF::DebugLogAllAllocations() const
  9210. {
  9211. for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical)
  9212. if (!block->IsFree())
  9213. DebugLogAllocation(block->offset, block->size, block->UserData());
  9214. }
  9215. uint8_t VmaBlockMetadata_TLSF::SizeToMemoryClass(VkDeviceSize size) const
  9216. {
  9217. if (size > SMALL_BUFFER_SIZE)
  9218. return VMA_BITSCAN_MSB(size) - MEMORY_CLASS_SHIFT;
  9219. return 0;
  9220. }
  9221. uint16_t VmaBlockMetadata_TLSF::SizeToSecondIndex(VkDeviceSize size, uint8_t memoryClass) const
  9222. {
  9223. if (memoryClass == 0)
  9224. {
  9225. if (IsVirtual())
  9226. return static_cast<uint16_t>((size - 1) / 8);
  9227. else
  9228. return static_cast<uint16_t>((size - 1) / 64);
  9229. }
  9230. return static_cast<uint16_t>((size >> (memoryClass + MEMORY_CLASS_SHIFT - SECOND_LEVEL_INDEX)) ^ (1U << SECOND_LEVEL_INDEX));
  9231. }
  9232. uint32_t VmaBlockMetadata_TLSF::GetListIndex(uint8_t memoryClass, uint16_t secondIndex) const
  9233. {
  9234. if (memoryClass == 0)
  9235. return secondIndex;
  9236. const uint32_t index = static_cast<uint32_t>(memoryClass - 1) * (1 << SECOND_LEVEL_INDEX) + secondIndex;
  9237. if (IsVirtual())
  9238. return index + (1 << SECOND_LEVEL_INDEX);
  9239. else
  9240. return index + 4;
  9241. }
  9242. uint32_t VmaBlockMetadata_TLSF::GetListIndex(VkDeviceSize size) const
  9243. {
  9244. uint8_t memoryClass = SizeToMemoryClass(size);
  9245. return GetListIndex(memoryClass, SizeToSecondIndex(size, memoryClass));
  9246. }
  9247. void VmaBlockMetadata_TLSF::RemoveFreeBlock(Block* block)
  9248. {
  9249. VMA_ASSERT(block != m_NullBlock);
  9250. VMA_ASSERT(block->IsFree());
  9251. if (block->NextFree() != VMA_NULL)
  9252. block->NextFree()->PrevFree() = block->PrevFree();
  9253. if (block->PrevFree() != VMA_NULL)
  9254. block->PrevFree()->NextFree() = block->NextFree();
  9255. else
  9256. {
  9257. uint8_t memClass = SizeToMemoryClass(block->size);
  9258. uint16_t secondIndex = SizeToSecondIndex(block->size, memClass);
  9259. uint32_t index = GetListIndex(memClass, secondIndex);
  9260. VMA_ASSERT(m_FreeList[index] == block);
  9261. m_FreeList[index] = block->NextFree();
  9262. if (block->NextFree() == VMA_NULL)
  9263. {
  9264. m_InnerIsFreeBitmap[memClass] &= ~(1U << secondIndex);
  9265. if (m_InnerIsFreeBitmap[memClass] == 0)
  9266. m_IsFreeBitmap &= ~(1UL << memClass);
  9267. }
  9268. }
  9269. block->MarkTaken();
  9270. block->UserData() = VMA_NULL;
  9271. --m_BlocksFreeCount;
  9272. m_BlocksFreeSize -= block->size;
  9273. }
  9274. void VmaBlockMetadata_TLSF::InsertFreeBlock(Block* block)
  9275. {
  9276. VMA_ASSERT(block != m_NullBlock);
  9277. VMA_ASSERT(!block->IsFree() && "Cannot insert block twice!");
  9278. uint8_t memClass = SizeToMemoryClass(block->size);
  9279. uint16_t secondIndex = SizeToSecondIndex(block->size, memClass);
  9280. uint32_t index = GetListIndex(memClass, secondIndex);
  9281. VMA_ASSERT(index < m_ListsCount);
  9282. block->PrevFree() = VMA_NULL;
  9283. block->NextFree() = m_FreeList[index];
  9284. m_FreeList[index] = block;
  9285. if (block->NextFree() != VMA_NULL)
  9286. block->NextFree()->PrevFree() = block;
  9287. else
  9288. {
  9289. m_InnerIsFreeBitmap[memClass] |= 1U << secondIndex;
  9290. m_IsFreeBitmap |= 1UL << memClass;
  9291. }
  9292. ++m_BlocksFreeCount;
  9293. m_BlocksFreeSize += block->size;
  9294. }
  9295. void VmaBlockMetadata_TLSF::MergeBlock(Block* block, Block* prev)
  9296. {
  9297. VMA_ASSERT(block->prevPhysical == prev && "Cannot merge seperate physical regions!");
  9298. VMA_ASSERT(!prev->IsFree() && "Cannot merge block that belongs to free list!");
  9299. block->offset = prev->offset;
  9300. block->size += prev->size;
  9301. block->prevPhysical = prev->prevPhysical;
  9302. if (block->prevPhysical)
  9303. block->prevPhysical->nextPhysical = block;
  9304. m_BlockAllocator.Free(prev);
  9305. }
  9306. VmaBlockMetadata_TLSF::Block* VmaBlockMetadata_TLSF::FindFreeBlock(VkDeviceSize size, uint32_t& listIndex) const
  9307. {
  9308. uint8_t memoryClass = SizeToMemoryClass(size);
  9309. uint32_t innerFreeMap = m_InnerIsFreeBitmap[memoryClass] & (~0U << SizeToSecondIndex(size, memoryClass));
  9310. if (!innerFreeMap)
  9311. {
  9312. // Check higher levels for avaiable blocks
  9313. uint32_t freeMap = m_IsFreeBitmap & (~0UL << (memoryClass + 1));
  9314. if (!freeMap)
  9315. return VMA_NULL; // No more memory avaible
  9316. // Find lowest free region
  9317. memoryClass = VMA_BITSCAN_LSB(freeMap);
  9318. innerFreeMap = m_InnerIsFreeBitmap[memoryClass];
  9319. VMA_ASSERT(innerFreeMap != 0);
  9320. }
  9321. // Find lowest free subregion
  9322. listIndex = GetListIndex(memoryClass, VMA_BITSCAN_LSB(innerFreeMap));
  9323. VMA_ASSERT(m_FreeList[listIndex]);
  9324. return m_FreeList[listIndex];
  9325. }
  9326. bool VmaBlockMetadata_TLSF::CheckBlock(
  9327. Block& block,
  9328. uint32_t listIndex,
  9329. VkDeviceSize allocSize,
  9330. VkDeviceSize allocAlignment,
  9331. VmaSuballocationType allocType,
  9332. VmaAllocationRequest* pAllocationRequest)
  9333. {
  9334. VMA_ASSERT(block.IsFree() && "Block is already taken!");
  9335. VkDeviceSize alignedOffset = VmaAlignUp(block.offset, allocAlignment);
  9336. if (block.size < allocSize + alignedOffset - block.offset)
  9337. return false;
  9338. // Check for granularity conflicts
  9339. if (!IsVirtual() &&
  9340. m_GranularityHandler.CheckConflictAndAlignUp(alignedOffset, allocSize, block.offset, block.size, allocType))
  9341. return false;
  9342. // Alloc successful
  9343. pAllocationRequest->type = VmaAllocationRequestType::TLSF;
  9344. pAllocationRequest->allocHandle = (VmaAllocHandle)&block;
  9345. pAllocationRequest->size = allocSize - GetDebugMargin();
  9346. pAllocationRequest->customData = (void*)allocType;
  9347. pAllocationRequest->algorithmData = alignedOffset;
  9348. // Place block at the start of list if it's normal block
  9349. if (listIndex != m_ListsCount && block.PrevFree())
  9350. {
  9351. block.PrevFree()->NextFree() = block.NextFree();
  9352. if (block.NextFree())
  9353. block.NextFree()->PrevFree() = block.PrevFree();
  9354. block.PrevFree() = VMA_NULL;
  9355. block.NextFree() = m_FreeList[listIndex];
  9356. m_FreeList[listIndex] = &block;
  9357. if (block.NextFree())
  9358. block.NextFree()->PrevFree() = &block;
  9359. }
  9360. return true;
  9361. }
  9362. #endif // _VMA_BLOCK_METADATA_TLSF_FUNCTIONS
  9363. #endif // _VMA_BLOCK_METADATA_TLSF
  9364. #ifndef _VMA_BLOCK_VECTOR
  9365. /*
  9366. Sequence of VmaDeviceMemoryBlock. Represents memory blocks allocated for a specific
  9367. Vulkan memory type.
  9368. Synchronized internally with a mutex.
  9369. */
  9370. class VmaBlockVector
  9371. {
  9372. friend struct VmaDefragmentationContext_T;
  9373. VMA_CLASS_NO_COPY(VmaBlockVector)
  9374. public:
  9375. VmaBlockVector(
  9376. VmaAllocator hAllocator,
  9377. VmaPool hParentPool,
  9378. uint32_t memoryTypeIndex,
  9379. VkDeviceSize preferredBlockSize,
  9380. size_t minBlockCount,
  9381. size_t maxBlockCount,
  9382. VkDeviceSize bufferImageGranularity,
  9383. bool explicitBlockSize,
  9384. uint32_t algorithm,
  9385. float priority,
  9386. VkDeviceSize minAllocationAlignment,
  9387. void* pMemoryAllocateNext);
  9388. ~VmaBlockVector();
  9389. VmaAllocator GetAllocator() const { return m_hAllocator; }
  9390. VmaPool GetParentPool() const { return m_hParentPool; }
  9391. bool IsCustomPool() const { return m_hParentPool != VMA_NULL; }
  9392. uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
  9393. VkDeviceSize GetPreferredBlockSize() const { return m_PreferredBlockSize; }
  9394. VkDeviceSize GetBufferImageGranularity() const { return m_BufferImageGranularity; }
  9395. uint32_t GetAlgorithm() const { return m_Algorithm; }
  9396. bool HasExplicitBlockSize() const { return m_ExplicitBlockSize; }
  9397. float GetPriority() const { return m_Priority; }
  9398. const void* GetAllocationNextPtr() const { return m_pMemoryAllocateNext; }
  9399. // To be used only while the m_Mutex is locked. Used during defragmentation.
  9400. size_t GetBlockCount() const { return m_Blocks.size(); }
  9401. // To be used only while the m_Mutex is locked. Used during defragmentation.
  9402. VmaDeviceMemoryBlock* GetBlock(size_t index) const { return m_Blocks[index]; }
  9403. VMA_RW_MUTEX &GetMutex() { return m_Mutex; }
  9404. VkResult CreateMinBlocks();
  9405. void AddStatistics(VmaStatistics& inoutStats);
  9406. void AddDetailedStatistics(VmaDetailedStatistics& inoutStats);
  9407. bool IsEmpty();
  9408. bool IsCorruptionDetectionEnabled() const;
  9409. VkResult Allocate(
  9410. VkDeviceSize size,
  9411. VkDeviceSize alignment,
  9412. const VmaAllocationCreateInfo& createInfo,
  9413. VmaSuballocationType suballocType,
  9414. size_t allocationCount,
  9415. VmaAllocation* pAllocations);
  9416. void Free(const VmaAllocation hAllocation);
  9417. #if VMA_STATS_STRING_ENABLED
  9418. void PrintDetailedMap(class VmaJsonWriter& json);
  9419. #endif
  9420. VkResult CheckCorruption();
  9421. private:
  9422. const VmaAllocator m_hAllocator;
  9423. const VmaPool m_hParentPool;
  9424. const uint32_t m_MemoryTypeIndex;
  9425. const VkDeviceSize m_PreferredBlockSize;
  9426. const size_t m_MinBlockCount;
  9427. const size_t m_MaxBlockCount;
  9428. const VkDeviceSize m_BufferImageGranularity;
  9429. const bool m_ExplicitBlockSize;
  9430. const uint32_t m_Algorithm;
  9431. const float m_Priority;
  9432. const VkDeviceSize m_MinAllocationAlignment;
  9433. void* const m_pMemoryAllocateNext;
  9434. VMA_RW_MUTEX m_Mutex;
  9435. // Incrementally sorted by sumFreeSize, ascending.
  9436. VmaVector<VmaDeviceMemoryBlock*, VmaStlAllocator<VmaDeviceMemoryBlock*>> m_Blocks;
  9437. uint32_t m_NextBlockId;
  9438. bool m_IncrementalSort = true;
  9439. void SetIncrementalSort(bool val) { m_IncrementalSort = val; }
  9440. VkDeviceSize CalcMaxBlockSize() const;
  9441. // Finds and removes given block from vector.
  9442. void Remove(VmaDeviceMemoryBlock* pBlock);
  9443. // Performs single step in sorting m_Blocks. They may not be fully sorted
  9444. // after this call.
  9445. void IncrementallySortBlocks();
  9446. void SortByFreeSize();
  9447. VkResult AllocatePage(
  9448. VkDeviceSize size,
  9449. VkDeviceSize alignment,
  9450. const VmaAllocationCreateInfo& createInfo,
  9451. VmaSuballocationType suballocType,
  9452. VmaAllocation* pAllocation);
  9453. VkResult AllocateFromBlock(
  9454. VmaDeviceMemoryBlock* pBlock,
  9455. VkDeviceSize size,
  9456. VkDeviceSize alignment,
  9457. VmaAllocationCreateFlags allocFlags,
  9458. void* pUserData,
  9459. VmaSuballocationType suballocType,
  9460. uint32_t strategy,
  9461. VmaAllocation* pAllocation);
  9462. VkResult CommitAllocationRequest(
  9463. VmaAllocationRequest& allocRequest,
  9464. VmaDeviceMemoryBlock* pBlock,
  9465. VkDeviceSize alignment,
  9466. VmaAllocationCreateFlags allocFlags,
  9467. void* pUserData,
  9468. VmaSuballocationType suballocType,
  9469. VmaAllocation* pAllocation);
  9470. VkResult CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex);
  9471. bool HasEmptyBlock();
  9472. };
  9473. #endif // _VMA_BLOCK_VECTOR
  9474. #ifndef _VMA_DEFRAGMENTATION_CONTEXT
  9475. struct VmaDefragmentationContext_T
  9476. {
  9477. VMA_CLASS_NO_COPY(VmaDefragmentationContext_T)
  9478. public:
  9479. VmaDefragmentationContext_T(
  9480. VmaAllocator hAllocator,
  9481. const VmaDefragmentationInfo& info);
  9482. ~VmaDefragmentationContext_T();
  9483. void GetStats(VmaDefragmentationStats& outStats) { outStats = m_GlobalStats; }
  9484. VkResult DefragmentPassBegin(VmaDefragmentationPassMoveInfo& moveInfo);
  9485. VkResult DefragmentPassEnd(VmaDefragmentationPassMoveInfo& moveInfo);
  9486. private:
  9487. // Max number of allocations to ignore due to size constraints before ending single pass
  9488. static const uint8_t MAX_ALLOCS_TO_IGNORE = 16;
  9489. enum class CounterStatus { Pass, Ignore, End };
  9490. struct FragmentedBlock
  9491. {
  9492. uint32_t data;
  9493. VmaDeviceMemoryBlock* block;
  9494. };
  9495. struct StateBalanced
  9496. {
  9497. VkDeviceSize avgFreeSize = 0;
  9498. VkDeviceSize avgAllocSize = UINT64_MAX;
  9499. };
  9500. struct StateExtensive
  9501. {
  9502. enum class Operation : uint8_t
  9503. {
  9504. FindFreeBlockBuffer, FindFreeBlockTexture, FindFreeBlockAll,
  9505. MoveBuffers, MoveTextures, MoveAll,
  9506. Cleanup, Done
  9507. };
  9508. Operation operation = Operation::FindFreeBlockTexture;
  9509. size_t firstFreeBlock = SIZE_MAX;
  9510. };
  9511. struct MoveAllocationData
  9512. {
  9513. VkDeviceSize size;
  9514. VkDeviceSize alignment;
  9515. VmaSuballocationType type;
  9516. VmaAllocationCreateFlags flags;
  9517. VmaDefragmentationMove move = {};
  9518. };
  9519. const VkDeviceSize m_MaxPassBytes;
  9520. const uint32_t m_MaxPassAllocations;
  9521. VmaStlAllocator<VmaDefragmentationMove> m_MoveAllocator;
  9522. VmaVector<VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove>> m_Moves;
  9523. uint8_t m_IgnoredAllocs = 0;
  9524. uint32_t m_Algorithm;
  9525. uint32_t m_BlockVectorCount;
  9526. VmaBlockVector* m_PoolBlockVector;
  9527. VmaBlockVector** m_pBlockVectors;
  9528. size_t m_ImmovableBlockCount = 0;
  9529. VmaDefragmentationStats m_GlobalStats = { 0 };
  9530. VmaDefragmentationStats m_PassStats = { 0 };
  9531. void* m_AlgorithmState = VMA_NULL;
  9532. static MoveAllocationData GetMoveData(VmaAllocHandle handle, VmaBlockMetadata* metadata);
  9533. CounterStatus CheckCounters(VkDeviceSize bytes);
  9534. bool IncrementCounters(VkDeviceSize bytes);
  9535. bool ReallocWithinBlock(VmaBlockVector& vector, VmaDeviceMemoryBlock* block);
  9536. bool AllocInOtherBlock(size_t start, size_t end, MoveAllocationData& data, VmaBlockVector& vector);
  9537. bool ComputeDefragmentation(VmaBlockVector& vector, size_t index);
  9538. bool ComputeDefragmentation_Fast(VmaBlockVector& vector);
  9539. bool ComputeDefragmentation_Balanced(VmaBlockVector& vector, size_t index, bool update);
  9540. bool ComputeDefragmentation_Full(VmaBlockVector& vector);
  9541. bool ComputeDefragmentation_Extensive(VmaBlockVector& vector, size_t index);
  9542. void UpdateVectorStatistics(VmaBlockVector& vector, StateBalanced& state);
  9543. bool MoveDataToFreeBlocks(VmaSuballocationType currentType,
  9544. VmaBlockVector& vector, size_t firstFreeBlock,
  9545. bool& texturePresent, bool& bufferPresent, bool& otherPresent);
  9546. };
  9547. #endif // _VMA_DEFRAGMENTATION_CONTEXT
  9548. #ifndef _VMA_POOL_T
  9549. struct VmaPool_T
  9550. {
  9551. friend struct VmaPoolListItemTraits;
  9552. VMA_CLASS_NO_COPY(VmaPool_T)
  9553. public:
  9554. VmaBlockVector m_BlockVector;
  9555. VmaDedicatedAllocationList m_DedicatedAllocations;
  9556. VmaPool_T(
  9557. VmaAllocator hAllocator,
  9558. const VmaPoolCreateInfo& createInfo,
  9559. VkDeviceSize preferredBlockSize);
  9560. ~VmaPool_T();
  9561. uint32_t GetId() const { return m_Id; }
  9562. void SetId(uint32_t id) { VMA_ASSERT(m_Id == 0); m_Id = id; }
  9563. const char* GetName() const { return m_Name; }
  9564. void SetName(const char* pName);
  9565. #if VMA_STATS_STRING_ENABLED
  9566. //void PrintDetailedMap(class VmaStringBuilder& sb);
  9567. #endif
  9568. private:
  9569. uint32_t m_Id;
  9570. char* m_Name;
  9571. VmaPool_T* m_PrevPool = VMA_NULL;
  9572. VmaPool_T* m_NextPool = VMA_NULL;
  9573. };
  9574. struct VmaPoolListItemTraits
  9575. {
  9576. typedef VmaPool_T ItemType;
  9577. static ItemType* GetPrev(const ItemType* item) { return item->m_PrevPool; }
  9578. static ItemType* GetNext(const ItemType* item) { return item->m_NextPool; }
  9579. static ItemType*& AccessPrev(ItemType* item) { return item->m_PrevPool; }
  9580. static ItemType*& AccessNext(ItemType* item) { return item->m_NextPool; }
  9581. };
  9582. #endif // _VMA_POOL_T
  9583. #ifndef _VMA_CURRENT_BUDGET_DATA
  9584. struct VmaCurrentBudgetData
  9585. {
  9586. VMA_ATOMIC_UINT32 m_BlockCount[VK_MAX_MEMORY_HEAPS];
  9587. VMA_ATOMIC_UINT32 m_AllocationCount[VK_MAX_MEMORY_HEAPS];
  9588. VMA_ATOMIC_UINT64 m_BlockBytes[VK_MAX_MEMORY_HEAPS];
  9589. VMA_ATOMIC_UINT64 m_AllocationBytes[VK_MAX_MEMORY_HEAPS];
  9590. #if VMA_MEMORY_BUDGET
  9591. VMA_ATOMIC_UINT32 m_OperationsSinceBudgetFetch;
  9592. VMA_RW_MUTEX m_BudgetMutex;
  9593. uint64_t m_VulkanUsage[VK_MAX_MEMORY_HEAPS];
  9594. uint64_t m_VulkanBudget[VK_MAX_MEMORY_HEAPS];
  9595. uint64_t m_BlockBytesAtBudgetFetch[VK_MAX_MEMORY_HEAPS];
  9596. #endif // VMA_MEMORY_BUDGET
  9597. VmaCurrentBudgetData();
  9598. void AddAllocation(uint32_t heapIndex, VkDeviceSize allocationSize);
  9599. void RemoveAllocation(uint32_t heapIndex, VkDeviceSize allocationSize);
  9600. };
  9601. #ifndef _VMA_CURRENT_BUDGET_DATA_FUNCTIONS
  9602. VmaCurrentBudgetData::VmaCurrentBudgetData()
  9603. {
  9604. for (uint32_t heapIndex = 0; heapIndex < VK_MAX_MEMORY_HEAPS; ++heapIndex)
  9605. {
  9606. m_BlockCount[heapIndex] = 0;
  9607. m_AllocationCount[heapIndex] = 0;
  9608. m_BlockBytes[heapIndex] = 0;
  9609. m_AllocationBytes[heapIndex] = 0;
  9610. #if VMA_MEMORY_BUDGET
  9611. m_VulkanUsage[heapIndex] = 0;
  9612. m_VulkanBudget[heapIndex] = 0;
  9613. m_BlockBytesAtBudgetFetch[heapIndex] = 0;
  9614. #endif
  9615. }
  9616. #if VMA_MEMORY_BUDGET
  9617. m_OperationsSinceBudgetFetch = 0;
  9618. #endif
  9619. }
  9620. void VmaCurrentBudgetData::AddAllocation(uint32_t heapIndex, VkDeviceSize allocationSize)
  9621. {
  9622. m_AllocationBytes[heapIndex] += allocationSize;
  9623. ++m_AllocationCount[heapIndex];
  9624. #if VMA_MEMORY_BUDGET
  9625. ++m_OperationsSinceBudgetFetch;
  9626. #endif
  9627. }
  9628. void VmaCurrentBudgetData::RemoveAllocation(uint32_t heapIndex, VkDeviceSize allocationSize)
  9629. {
  9630. VMA_ASSERT(m_AllocationBytes[heapIndex] >= allocationSize);
  9631. m_AllocationBytes[heapIndex] -= allocationSize;
  9632. VMA_ASSERT(m_AllocationCount[heapIndex] > 0);
  9633. --m_AllocationCount[heapIndex];
  9634. #if VMA_MEMORY_BUDGET
  9635. ++m_OperationsSinceBudgetFetch;
  9636. #endif
  9637. }
  9638. #endif // _VMA_CURRENT_BUDGET_DATA_FUNCTIONS
  9639. #endif // _VMA_CURRENT_BUDGET_DATA
  9640. #ifndef _VMA_ALLOCATION_OBJECT_ALLOCATOR
  9641. /*
  9642. Thread-safe wrapper over VmaPoolAllocator free list, for allocation of VmaAllocation_T objects.
  9643. */
  9644. class VmaAllocationObjectAllocator
  9645. {
  9646. VMA_CLASS_NO_COPY(VmaAllocationObjectAllocator)
  9647. public:
  9648. VmaAllocationObjectAllocator(const VkAllocationCallbacks* pAllocationCallbacks)
  9649. : m_Allocator(pAllocationCallbacks, 1024) {}
  9650. template<typename... Types> VmaAllocation Allocate(Types&&... args);
  9651. void Free(VmaAllocation hAlloc);
  9652. private:
  9653. VMA_MUTEX m_Mutex;
  9654. VmaPoolAllocator<VmaAllocation_T> m_Allocator;
  9655. };
  9656. template<typename... Types>
  9657. VmaAllocation VmaAllocationObjectAllocator::Allocate(Types&&... args)
  9658. {
  9659. VmaMutexLock mutexLock(m_Mutex);
  9660. return m_Allocator.Alloc<Types...>(std::forward<Types>(args)...);
  9661. }
  9662. void VmaAllocationObjectAllocator::Free(VmaAllocation hAlloc)
  9663. {
  9664. VmaMutexLock mutexLock(m_Mutex);
  9665. m_Allocator.Free(hAlloc);
  9666. }
  9667. #endif // _VMA_ALLOCATION_OBJECT_ALLOCATOR
  9668. #ifndef _VMA_VIRTUAL_BLOCK_T
  9669. struct VmaVirtualBlock_T
  9670. {
  9671. VMA_CLASS_NO_COPY(VmaVirtualBlock_T)
  9672. public:
  9673. const bool m_AllocationCallbacksSpecified;
  9674. const VkAllocationCallbacks m_AllocationCallbacks;
  9675. VmaVirtualBlock_T(const VmaVirtualBlockCreateInfo& createInfo);
  9676. ~VmaVirtualBlock_T();
  9677. VkResult Init() { return VK_SUCCESS; }
  9678. bool IsEmpty() const { return m_Metadata->IsEmpty(); }
  9679. void Free(VmaVirtualAllocation allocation) { m_Metadata->Free((VmaAllocHandle)allocation); }
  9680. void SetAllocationUserData(VmaVirtualAllocation allocation, void* userData) { m_Metadata->SetAllocationUserData((VmaAllocHandle)allocation, userData); }
  9681. void Clear() { m_Metadata->Clear(); }
  9682. const VkAllocationCallbacks* GetAllocationCallbacks() const;
  9683. void GetAllocationInfo(VmaVirtualAllocation allocation, VmaVirtualAllocationInfo& outInfo);
  9684. VkResult Allocate(const VmaVirtualAllocationCreateInfo& createInfo, VmaVirtualAllocation& outAllocation,
  9685. VkDeviceSize* outOffset);
  9686. void GetStatistics(VmaStatistics& outStats) const;
  9687. void CalculateDetailedStatistics(VmaDetailedStatistics& outStats) const;
  9688. #if VMA_STATS_STRING_ENABLED
  9689. void BuildStatsString(bool detailedMap, VmaStringBuilder& sb) const;
  9690. #endif
  9691. private:
  9692. VmaBlockMetadata* m_Metadata;
  9693. };
  9694. #ifndef _VMA_VIRTUAL_BLOCK_T_FUNCTIONS
  9695. VmaVirtualBlock_T::VmaVirtualBlock_T(const VmaVirtualBlockCreateInfo& createInfo)
  9696. : m_AllocationCallbacksSpecified(createInfo.pAllocationCallbacks != VMA_NULL),
  9697. m_AllocationCallbacks(createInfo.pAllocationCallbacks != VMA_NULL ? *createInfo.pAllocationCallbacks : VmaEmptyAllocationCallbacks)
  9698. {
  9699. const uint32_t algorithm = createInfo.flags & VMA_VIRTUAL_BLOCK_CREATE_ALGORITHM_MASK;
  9700. switch (algorithm)
  9701. {
  9702. default:
  9703. VMA_ASSERT(0);
  9704. case 0:
  9705. m_Metadata = vma_new(GetAllocationCallbacks(), VmaBlockMetadata_TLSF)(VK_NULL_HANDLE, 1, true);
  9706. break;
  9707. case VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT:
  9708. m_Metadata = vma_new(GetAllocationCallbacks(), VmaBlockMetadata_Linear)(VK_NULL_HANDLE, 1, true);
  9709. break;
  9710. }
  9711. m_Metadata->Init(createInfo.size);
  9712. }
  9713. VmaVirtualBlock_T::~VmaVirtualBlock_T()
  9714. {
  9715. // Define macro VMA_DEBUG_LOG to receive the list of the unfreed allocations
  9716. if (!m_Metadata->IsEmpty())
  9717. m_Metadata->DebugLogAllAllocations();
  9718. // This is the most important assert in the entire library.
  9719. // Hitting it means you have some memory leak - unreleased virtual allocations.
  9720. VMA_ASSERT(m_Metadata->IsEmpty() && "Some virtual allocations were not freed before destruction of this virtual block!");
  9721. vma_delete(GetAllocationCallbacks(), m_Metadata);
  9722. }
  9723. const VkAllocationCallbacks* VmaVirtualBlock_T::GetAllocationCallbacks() const
  9724. {
  9725. return m_AllocationCallbacksSpecified ? &m_AllocationCallbacks : VMA_NULL;
  9726. }
  9727. void VmaVirtualBlock_T::GetAllocationInfo(VmaVirtualAllocation allocation, VmaVirtualAllocationInfo& outInfo)
  9728. {
  9729. m_Metadata->GetAllocationInfo((VmaAllocHandle)allocation, outInfo);
  9730. }
  9731. VkResult VmaVirtualBlock_T::Allocate(const VmaVirtualAllocationCreateInfo& createInfo, VmaVirtualAllocation& outAllocation,
  9732. VkDeviceSize* outOffset)
  9733. {
  9734. VmaAllocationRequest request = {};
  9735. if (m_Metadata->CreateAllocationRequest(
  9736. createInfo.size, // allocSize
  9737. VMA_MAX(createInfo.alignment, (VkDeviceSize)1), // allocAlignment
  9738. (createInfo.flags & VMA_VIRTUAL_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0, // upperAddress
  9739. VMA_SUBALLOCATION_TYPE_UNKNOWN, // allocType - unimportant
  9740. createInfo.flags & VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MASK, // strategy
  9741. &request))
  9742. {
  9743. m_Metadata->Alloc(request,
  9744. VMA_SUBALLOCATION_TYPE_UNKNOWN, // type - unimportant
  9745. createInfo.pUserData);
  9746. outAllocation = (VmaVirtualAllocation)request.allocHandle;
  9747. if(outOffset)
  9748. *outOffset = m_Metadata->GetAllocationOffset(request.allocHandle);
  9749. return VK_SUCCESS;
  9750. }
  9751. outAllocation = (VmaVirtualAllocation)VK_NULL_HANDLE;
  9752. if (outOffset)
  9753. *outOffset = UINT64_MAX;
  9754. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  9755. }
  9756. void VmaVirtualBlock_T::GetStatistics(VmaStatistics& outStats) const
  9757. {
  9758. VmaClearStatistics(outStats);
  9759. m_Metadata->AddStatistics(outStats);
  9760. }
  9761. void VmaVirtualBlock_T::CalculateDetailedStatistics(VmaDetailedStatistics& outStats) const
  9762. {
  9763. VmaClearDetailedStatistics(outStats);
  9764. m_Metadata->AddDetailedStatistics(outStats);
  9765. }
  9766. #if VMA_STATS_STRING_ENABLED
  9767. void VmaVirtualBlock_T::BuildStatsString(bool detailedMap, VmaStringBuilder& sb) const
  9768. {
  9769. VmaJsonWriter json(GetAllocationCallbacks(), sb);
  9770. json.BeginObject();
  9771. VmaDetailedStatistics stats;
  9772. CalculateDetailedStatistics(stats);
  9773. json.WriteString("Stats");
  9774. VmaPrintDetailedStatistics(json, stats);
  9775. if (detailedMap)
  9776. {
  9777. json.WriteString("Details");
  9778. json.BeginObject();
  9779. m_Metadata->PrintDetailedMap(json);
  9780. json.EndObject();
  9781. }
  9782. json.EndObject();
  9783. }
  9784. #endif // VMA_STATS_STRING_ENABLED
  9785. #endif // _VMA_VIRTUAL_BLOCK_T_FUNCTIONS
  9786. #endif // _VMA_VIRTUAL_BLOCK_T
  9787. // Main allocator object.
  9788. struct VmaAllocator_T
  9789. {
  9790. VMA_CLASS_NO_COPY(VmaAllocator_T)
  9791. public:
  9792. bool m_UseMutex;
  9793. uint32_t m_VulkanApiVersion;
  9794. bool m_UseKhrDedicatedAllocation; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0).
  9795. bool m_UseKhrBindMemory2; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0).
  9796. bool m_UseExtMemoryBudget;
  9797. bool m_UseAmdDeviceCoherentMemory;
  9798. bool m_UseKhrBufferDeviceAddress;
  9799. bool m_UseExtMemoryPriority;
  9800. VkDevice m_hDevice;
  9801. VkInstance m_hInstance;
  9802. bool m_AllocationCallbacksSpecified;
  9803. VkAllocationCallbacks m_AllocationCallbacks;
  9804. VmaDeviceMemoryCallbacks m_DeviceMemoryCallbacks;
  9805. VmaAllocationObjectAllocator m_AllocationObjectAllocator;
  9806. // Each bit (1 << i) is set if HeapSizeLimit is enabled for that heap, so cannot allocate more than the heap size.
  9807. uint32_t m_HeapSizeLimitMask;
  9808. VkPhysicalDeviceProperties m_PhysicalDeviceProperties;
  9809. VkPhysicalDeviceMemoryProperties m_MemProps;
  9810. // Default pools.
  9811. VmaBlockVector* m_pBlockVectors[VK_MAX_MEMORY_TYPES];
  9812. VmaDedicatedAllocationList m_DedicatedAllocations[VK_MAX_MEMORY_TYPES];
  9813. VmaCurrentBudgetData m_Budget;
  9814. VMA_ATOMIC_UINT32 m_DeviceMemoryCount; // Total number of VkDeviceMemory objects.
  9815. VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo);
  9816. VkResult Init(const VmaAllocatorCreateInfo* pCreateInfo);
  9817. ~VmaAllocator_T();
  9818. const VkAllocationCallbacks* GetAllocationCallbacks() const
  9819. {
  9820. return m_AllocationCallbacksSpecified ? &m_AllocationCallbacks : VMA_NULL;
  9821. }
  9822. const VmaVulkanFunctions& GetVulkanFunctions() const
  9823. {
  9824. return m_VulkanFunctions;
  9825. }
  9826. VkPhysicalDevice GetPhysicalDevice() const { return m_PhysicalDevice; }
  9827. VkDeviceSize GetBufferImageGranularity() const
  9828. {
  9829. return VMA_MAX(
  9830. static_cast<VkDeviceSize>(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY),
  9831. m_PhysicalDeviceProperties.limits.bufferImageGranularity);
  9832. }
  9833. uint32_t GetMemoryHeapCount() const { return m_MemProps.memoryHeapCount; }
  9834. uint32_t GetMemoryTypeCount() const { return m_MemProps.memoryTypeCount; }
  9835. uint32_t MemoryTypeIndexToHeapIndex(uint32_t memTypeIndex) const
  9836. {
  9837. VMA_ASSERT(memTypeIndex < m_MemProps.memoryTypeCount);
  9838. return m_MemProps.memoryTypes[memTypeIndex].heapIndex;
  9839. }
  9840. // True when specific memory type is HOST_VISIBLE but not HOST_COHERENT.
  9841. bool IsMemoryTypeNonCoherent(uint32_t memTypeIndex) const
  9842. {
  9843. return (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) ==
  9844. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  9845. }
  9846. // Minimum alignment for all allocations in specific memory type.
  9847. VkDeviceSize GetMemoryTypeMinAlignment(uint32_t memTypeIndex) const
  9848. {
  9849. return IsMemoryTypeNonCoherent(memTypeIndex) ?
  9850. VMA_MAX((VkDeviceSize)VMA_MIN_ALIGNMENT, m_PhysicalDeviceProperties.limits.nonCoherentAtomSize) :
  9851. (VkDeviceSize)VMA_MIN_ALIGNMENT;
  9852. }
  9853. bool IsIntegratedGpu() const
  9854. {
  9855. return m_PhysicalDeviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
  9856. }
  9857. uint32_t GetGlobalMemoryTypeBits() const { return m_GlobalMemoryTypeBits; }
  9858. void GetBufferMemoryRequirements(
  9859. VkBuffer hBuffer,
  9860. VkMemoryRequirements& memReq,
  9861. bool& requiresDedicatedAllocation,
  9862. bool& prefersDedicatedAllocation) const;
  9863. void GetImageMemoryRequirements(
  9864. VkImage hImage,
  9865. VkMemoryRequirements& memReq,
  9866. bool& requiresDedicatedAllocation,
  9867. bool& prefersDedicatedAllocation) const;
  9868. VkResult FindMemoryTypeIndex(
  9869. uint32_t memoryTypeBits,
  9870. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  9871. VkFlags bufImgUsage, // VkBufferCreateInfo::usage or VkImageCreateInfo::usage. UINT32_MAX if unknown.
  9872. uint32_t* pMemoryTypeIndex) const;
  9873. // Main allocation function.
  9874. VkResult AllocateMemory(
  9875. const VkMemoryRequirements& vkMemReq,
  9876. bool requiresDedicatedAllocation,
  9877. bool prefersDedicatedAllocation,
  9878. VkBuffer dedicatedBuffer,
  9879. VkImage dedicatedImage,
  9880. VkFlags dedicatedBufferImageUsage, // UINT32_MAX if unknown.
  9881. const VmaAllocationCreateInfo& createInfo,
  9882. VmaSuballocationType suballocType,
  9883. size_t allocationCount,
  9884. VmaAllocation* pAllocations);
  9885. // Main deallocation function.
  9886. void FreeMemory(
  9887. size_t allocationCount,
  9888. const VmaAllocation* pAllocations);
  9889. void CalculateStatistics(VmaTotalStatistics* pStats);
  9890. void GetHeapBudgets(
  9891. VmaBudget* outBudgets, uint32_t firstHeap, uint32_t heapCount);
  9892. #if VMA_STATS_STRING_ENABLED
  9893. void PrintDetailedMap(class VmaJsonWriter& json);
  9894. #endif
  9895. void GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo);
  9896. VkResult CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool);
  9897. void DestroyPool(VmaPool pool);
  9898. void GetPoolStatistics(VmaPool pool, VmaStatistics* pPoolStats);
  9899. void CalculatePoolStatistics(VmaPool pool, VmaDetailedStatistics* pPoolStats);
  9900. void SetCurrentFrameIndex(uint32_t frameIndex);
  9901. uint32_t GetCurrentFrameIndex() const { return m_CurrentFrameIndex.load(); }
  9902. VkResult CheckPoolCorruption(VmaPool hPool);
  9903. VkResult CheckCorruption(uint32_t memoryTypeBits);
  9904. // Call to Vulkan function vkAllocateMemory with accompanying bookkeeping.
  9905. VkResult AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory);
  9906. // Call to Vulkan function vkFreeMemory with accompanying bookkeeping.
  9907. void FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory);
  9908. // Call to Vulkan function vkBindBufferMemory or vkBindBufferMemory2KHR.
  9909. VkResult BindVulkanBuffer(
  9910. VkDeviceMemory memory,
  9911. VkDeviceSize memoryOffset,
  9912. VkBuffer buffer,
  9913. const void* pNext);
  9914. // Call to Vulkan function vkBindImageMemory or vkBindImageMemory2KHR.
  9915. VkResult BindVulkanImage(
  9916. VkDeviceMemory memory,
  9917. VkDeviceSize memoryOffset,
  9918. VkImage image,
  9919. const void* pNext);
  9920. VkResult Map(VmaAllocation hAllocation, void** ppData);
  9921. void Unmap(VmaAllocation hAllocation);
  9922. VkResult BindBufferMemory(
  9923. VmaAllocation hAllocation,
  9924. VkDeviceSize allocationLocalOffset,
  9925. VkBuffer hBuffer,
  9926. const void* pNext);
  9927. VkResult BindImageMemory(
  9928. VmaAllocation hAllocation,
  9929. VkDeviceSize allocationLocalOffset,
  9930. VkImage hImage,
  9931. const void* pNext);
  9932. VkResult FlushOrInvalidateAllocation(
  9933. VmaAllocation hAllocation,
  9934. VkDeviceSize offset, VkDeviceSize size,
  9935. VMA_CACHE_OPERATION op);
  9936. VkResult FlushOrInvalidateAllocations(
  9937. uint32_t allocationCount,
  9938. const VmaAllocation* allocations,
  9939. const VkDeviceSize* offsets, const VkDeviceSize* sizes,
  9940. VMA_CACHE_OPERATION op);
  9941. void FillAllocation(const VmaAllocation hAllocation, uint8_t pattern);
  9942. /*
  9943. Returns bit mask of memory types that can support defragmentation on GPU as
  9944. they support creation of required buffer for copy operations.
  9945. */
  9946. uint32_t GetGpuDefragmentationMemoryTypeBits();
  9947. #if VMA_EXTERNAL_MEMORY
  9948. VkExternalMemoryHandleTypeFlagsKHR GetExternalMemoryHandleTypeFlags(uint32_t memTypeIndex) const
  9949. {
  9950. return m_TypeExternalMemoryHandleTypes[memTypeIndex];
  9951. }
  9952. #endif // #if VMA_EXTERNAL_MEMORY
  9953. private:
  9954. VkDeviceSize m_PreferredLargeHeapBlockSize;
  9955. VkPhysicalDevice m_PhysicalDevice;
  9956. VMA_ATOMIC_UINT32 m_CurrentFrameIndex;
  9957. VMA_ATOMIC_UINT32 m_GpuDefragmentationMemoryTypeBits; // UINT32_MAX means uninitialized.
  9958. #if VMA_EXTERNAL_MEMORY
  9959. VkExternalMemoryHandleTypeFlagsKHR m_TypeExternalMemoryHandleTypes[VK_MAX_MEMORY_TYPES];
  9960. #endif // #if VMA_EXTERNAL_MEMORY
  9961. VMA_RW_MUTEX m_PoolsMutex;
  9962. typedef VmaIntrusiveLinkedList<VmaPoolListItemTraits> PoolList;
  9963. // Protected by m_PoolsMutex.
  9964. PoolList m_Pools;
  9965. uint32_t m_NextPoolId;
  9966. VmaVulkanFunctions m_VulkanFunctions;
  9967. // Global bit mask AND-ed with any memoryTypeBits to disallow certain memory types.
  9968. uint32_t m_GlobalMemoryTypeBits;
  9969. void ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions);
  9970. #if VMA_STATIC_VULKAN_FUNCTIONS == 1
  9971. void ImportVulkanFunctions_Static();
  9972. #endif
  9973. void ImportVulkanFunctions_Custom(const VmaVulkanFunctions* pVulkanFunctions);
  9974. #if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1
  9975. void ImportVulkanFunctions_Dynamic();
  9976. #endif
  9977. void ValidateVulkanFunctions();
  9978. VkDeviceSize CalcPreferredBlockSize(uint32_t memTypeIndex);
  9979. VkResult AllocateMemoryOfType(
  9980. VmaPool pool,
  9981. VkDeviceSize size,
  9982. VkDeviceSize alignment,
  9983. bool dedicatedPreferred,
  9984. VkBuffer dedicatedBuffer,
  9985. VkImage dedicatedImage,
  9986. VkFlags dedicatedBufferImageUsage,
  9987. const VmaAllocationCreateInfo& createInfo,
  9988. uint32_t memTypeIndex,
  9989. VmaSuballocationType suballocType,
  9990. VmaDedicatedAllocationList& dedicatedAllocations,
  9991. VmaBlockVector& blockVector,
  9992. size_t allocationCount,
  9993. VmaAllocation* pAllocations);
  9994. // Helper function only to be used inside AllocateDedicatedMemory.
  9995. VkResult AllocateDedicatedMemoryPage(
  9996. VmaPool pool,
  9997. VkDeviceSize size,
  9998. VmaSuballocationType suballocType,
  9999. uint32_t memTypeIndex,
  10000. const VkMemoryAllocateInfo& allocInfo,
  10001. bool map,
  10002. bool isUserDataString,
  10003. bool isMappingAllowed,
  10004. void* pUserData,
  10005. VmaAllocation* pAllocation);
  10006. // Allocates and registers new VkDeviceMemory specifically for dedicated allocations.
  10007. VkResult AllocateDedicatedMemory(
  10008. VmaPool pool,
  10009. VkDeviceSize size,
  10010. VmaSuballocationType suballocType,
  10011. VmaDedicatedAllocationList& dedicatedAllocations,
  10012. uint32_t memTypeIndex,
  10013. bool map,
  10014. bool isUserDataString,
  10015. bool isMappingAllowed,
  10016. bool canAliasMemory,
  10017. void* pUserData,
  10018. float priority,
  10019. VkBuffer dedicatedBuffer,
  10020. VkImage dedicatedImage,
  10021. VkFlags dedicatedBufferImageUsage,
  10022. size_t allocationCount,
  10023. VmaAllocation* pAllocations,
  10024. const void* pNextChain = nullptr);
  10025. void FreeDedicatedMemory(const VmaAllocation allocation);
  10026. VkResult CalcMemTypeParams(
  10027. VmaAllocationCreateInfo& outCreateInfo,
  10028. uint32_t memTypeIndex,
  10029. VkDeviceSize size,
  10030. size_t allocationCount);
  10031. VkResult CalcAllocationParams(
  10032. VmaAllocationCreateInfo& outCreateInfo,
  10033. bool dedicatedRequired,
  10034. bool dedicatedPreferred);
  10035. /*
  10036. Calculates and returns bit mask of memory types that can support defragmentation
  10037. on GPU as they support creation of required buffer for copy operations.
  10038. */
  10039. uint32_t CalculateGpuDefragmentationMemoryTypeBits() const;
  10040. uint32_t CalculateGlobalMemoryTypeBits() const;
  10041. bool GetFlushOrInvalidateRange(
  10042. VmaAllocation allocation,
  10043. VkDeviceSize offset, VkDeviceSize size,
  10044. VkMappedMemoryRange& outRange) const;
  10045. #if VMA_MEMORY_BUDGET
  10046. void UpdateVulkanBudget();
  10047. #endif // #if VMA_MEMORY_BUDGET
  10048. };
  10049. #ifndef _VMA_MEMORY_FUNCTIONS
  10050. static void* VmaMalloc(VmaAllocator hAllocator, size_t size, size_t alignment)
  10051. {
  10052. return VmaMalloc(&hAllocator->m_AllocationCallbacks, size, alignment);
  10053. }
  10054. static void VmaFree(VmaAllocator hAllocator, void* ptr)
  10055. {
  10056. VmaFree(&hAllocator->m_AllocationCallbacks, ptr);
  10057. }
  10058. template<typename T>
  10059. static T* VmaAllocate(VmaAllocator hAllocator)
  10060. {
  10061. return (T*)VmaMalloc(hAllocator, sizeof(T), VMA_ALIGN_OF(T));
  10062. }
  10063. template<typename T>
  10064. static T* VmaAllocateArray(VmaAllocator hAllocator, size_t count)
  10065. {
  10066. return (T*)VmaMalloc(hAllocator, sizeof(T) * count, VMA_ALIGN_OF(T));
  10067. }
  10068. template<typename T>
  10069. static void vma_delete(VmaAllocator hAllocator, T* ptr)
  10070. {
  10071. if(ptr != VMA_NULL)
  10072. {
  10073. ptr->~T();
  10074. VmaFree(hAllocator, ptr);
  10075. }
  10076. }
  10077. template<typename T>
  10078. static void vma_delete_array(VmaAllocator hAllocator, T* ptr, size_t count)
  10079. {
  10080. if(ptr != VMA_NULL)
  10081. {
  10082. for(size_t i = count; i--; )
  10083. ptr[i].~T();
  10084. VmaFree(hAllocator, ptr);
  10085. }
  10086. }
  10087. #endif // _VMA_MEMORY_FUNCTIONS
  10088. #ifndef _VMA_DEVICE_MEMORY_BLOCK_FUNCTIONS
  10089. VmaDeviceMemoryBlock::VmaDeviceMemoryBlock(VmaAllocator hAllocator)
  10090. : m_pMetadata(VMA_NULL),
  10091. m_MemoryTypeIndex(UINT32_MAX),
  10092. m_Id(0),
  10093. m_hMemory(VK_NULL_HANDLE),
  10094. m_MapCount(0),
  10095. m_pMappedData(VMA_NULL) {}
  10096. VmaDeviceMemoryBlock::~VmaDeviceMemoryBlock()
  10097. {
  10098. VMA_ASSERT(m_MapCount == 0 && "VkDeviceMemory block is being destroyed while it is still mapped.");
  10099. VMA_ASSERT(m_hMemory == VK_NULL_HANDLE);
  10100. }
  10101. void VmaDeviceMemoryBlock::Init(
  10102. VmaAllocator hAllocator,
  10103. VmaPool hParentPool,
  10104. uint32_t newMemoryTypeIndex,
  10105. VkDeviceMemory newMemory,
  10106. VkDeviceSize newSize,
  10107. uint32_t id,
  10108. uint32_t algorithm,
  10109. VkDeviceSize bufferImageGranularity)
  10110. {
  10111. VMA_ASSERT(m_hMemory == VK_NULL_HANDLE);
  10112. m_hParentPool = hParentPool;
  10113. m_MemoryTypeIndex = newMemoryTypeIndex;
  10114. m_Id = id;
  10115. m_hMemory = newMemory;
  10116. switch (algorithm)
  10117. {
  10118. case VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT:
  10119. m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_Linear)(hAllocator->GetAllocationCallbacks(),
  10120. bufferImageGranularity, false); // isVirtual
  10121. break;
  10122. default:
  10123. VMA_ASSERT(0);
  10124. // Fall-through.
  10125. case 0:
  10126. m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_TLSF)(hAllocator->GetAllocationCallbacks(),
  10127. bufferImageGranularity, false); // isVirtual
  10128. }
  10129. m_pMetadata->Init(newSize);
  10130. }
  10131. void VmaDeviceMemoryBlock::Destroy(VmaAllocator allocator)
  10132. {
  10133. // Define macro VMA_DEBUG_LOG to receive the list of the unfreed allocations
  10134. if (!m_pMetadata->IsEmpty())
  10135. m_pMetadata->DebugLogAllAllocations();
  10136. // This is the most important assert in the entire library.
  10137. // Hitting it means you have some memory leak - unreleased VmaAllocation objects.
  10138. VMA_ASSERT(m_pMetadata->IsEmpty() && "Some allocations were not freed before destruction of this memory block!");
  10139. VMA_ASSERT(m_hMemory != VK_NULL_HANDLE);
  10140. allocator->FreeVulkanMemory(m_MemoryTypeIndex, m_pMetadata->GetSize(), m_hMemory);
  10141. m_hMemory = VK_NULL_HANDLE;
  10142. vma_delete(allocator, m_pMetadata);
  10143. m_pMetadata = VMA_NULL;
  10144. }
  10145. void VmaDeviceMemoryBlock::PostFree(VmaAllocator hAllocator)
  10146. {
  10147. if(m_MappingHysteresis.PostFree())
  10148. {
  10149. VMA_ASSERT(m_MappingHysteresis.GetExtraMapping() == 0);
  10150. if (m_MapCount == 0)
  10151. {
  10152. m_pMappedData = VMA_NULL;
  10153. (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(hAllocator->m_hDevice, m_hMemory);
  10154. }
  10155. }
  10156. }
  10157. bool VmaDeviceMemoryBlock::Validate() const
  10158. {
  10159. VMA_VALIDATE((m_hMemory != VK_NULL_HANDLE) &&
  10160. (m_pMetadata->GetSize() != 0));
  10161. return m_pMetadata->Validate();
  10162. }
  10163. VkResult VmaDeviceMemoryBlock::CheckCorruption(VmaAllocator hAllocator)
  10164. {
  10165. void* pData = nullptr;
  10166. VkResult res = Map(hAllocator, 1, &pData);
  10167. if (res != VK_SUCCESS)
  10168. {
  10169. return res;
  10170. }
  10171. res = m_pMetadata->CheckCorruption(pData);
  10172. Unmap(hAllocator, 1);
  10173. return res;
  10174. }
  10175. VkResult VmaDeviceMemoryBlock::Map(VmaAllocator hAllocator, uint32_t count, void** ppData)
  10176. {
  10177. if (count == 0)
  10178. {
  10179. return VK_SUCCESS;
  10180. }
  10181. VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex);
  10182. const uint32_t oldTotalMapCount = m_MapCount + m_MappingHysteresis.GetExtraMapping();
  10183. m_MappingHysteresis.PostMap();
  10184. if (oldTotalMapCount != 0)
  10185. {
  10186. m_MapCount += count;
  10187. VMA_ASSERT(m_pMappedData != VMA_NULL);
  10188. if (ppData != VMA_NULL)
  10189. {
  10190. *ppData = m_pMappedData;
  10191. }
  10192. return VK_SUCCESS;
  10193. }
  10194. else
  10195. {
  10196. VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)(
  10197. hAllocator->m_hDevice,
  10198. m_hMemory,
  10199. 0, // offset
  10200. VK_WHOLE_SIZE,
  10201. 0, // flags
  10202. &m_pMappedData);
  10203. if (result == VK_SUCCESS)
  10204. {
  10205. if (ppData != VMA_NULL)
  10206. {
  10207. *ppData = m_pMappedData;
  10208. }
  10209. m_MapCount = count;
  10210. }
  10211. return result;
  10212. }
  10213. }
  10214. void VmaDeviceMemoryBlock::Unmap(VmaAllocator hAllocator, uint32_t count)
  10215. {
  10216. if (count == 0)
  10217. {
  10218. return;
  10219. }
  10220. VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex);
  10221. if (m_MapCount >= count)
  10222. {
  10223. m_MapCount -= count;
  10224. const uint32_t totalMapCount = m_MapCount + m_MappingHysteresis.GetExtraMapping();
  10225. if (totalMapCount == 0)
  10226. {
  10227. m_pMappedData = VMA_NULL;
  10228. (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(hAllocator->m_hDevice, m_hMemory);
  10229. }
  10230. m_MappingHysteresis.PostUnmap();
  10231. }
  10232. else
  10233. {
  10234. VMA_ASSERT(0 && "VkDeviceMemory block is being unmapped while it was not previously mapped.");
  10235. }
  10236. }
  10237. VkResult VmaDeviceMemoryBlock::WriteMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize)
  10238. {
  10239. VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION);
  10240. void* pData;
  10241. VkResult res = Map(hAllocator, 1, &pData);
  10242. if (res != VK_SUCCESS)
  10243. {
  10244. return res;
  10245. }
  10246. VmaWriteMagicValue(pData, allocOffset + allocSize);
  10247. Unmap(hAllocator, 1);
  10248. return VK_SUCCESS;
  10249. }
  10250. VkResult VmaDeviceMemoryBlock::ValidateMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize)
  10251. {
  10252. VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION);
  10253. void* pData;
  10254. VkResult res = Map(hAllocator, 1, &pData);
  10255. if (res != VK_SUCCESS)
  10256. {
  10257. return res;
  10258. }
  10259. if (!VmaValidateMagicValue(pData, allocOffset + allocSize))
  10260. {
  10261. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER FREED ALLOCATION!");
  10262. }
  10263. Unmap(hAllocator, 1);
  10264. return VK_SUCCESS;
  10265. }
  10266. VkResult VmaDeviceMemoryBlock::BindBufferMemory(
  10267. const VmaAllocator hAllocator,
  10268. const VmaAllocation hAllocation,
  10269. VkDeviceSize allocationLocalOffset,
  10270. VkBuffer hBuffer,
  10271. const void* pNext)
  10272. {
  10273. VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK &&
  10274. hAllocation->GetBlock() == this);
  10275. VMA_ASSERT(allocationLocalOffset < hAllocation->GetSize() &&
  10276. "Invalid allocationLocalOffset. Did you forget that this offset is relative to the beginning of the allocation, not the whole memory block?");
  10277. const VkDeviceSize memoryOffset = hAllocation->GetOffset() + allocationLocalOffset;
  10278. // This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads.
  10279. VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex);
  10280. return hAllocator->BindVulkanBuffer(m_hMemory, memoryOffset, hBuffer, pNext);
  10281. }
  10282. VkResult VmaDeviceMemoryBlock::BindImageMemory(
  10283. const VmaAllocator hAllocator,
  10284. const VmaAllocation hAllocation,
  10285. VkDeviceSize allocationLocalOffset,
  10286. VkImage hImage,
  10287. const void* pNext)
  10288. {
  10289. VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK &&
  10290. hAllocation->GetBlock() == this);
  10291. VMA_ASSERT(allocationLocalOffset < hAllocation->GetSize() &&
  10292. "Invalid allocationLocalOffset. Did you forget that this offset is relative to the beginning of the allocation, not the whole memory block?");
  10293. const VkDeviceSize memoryOffset = hAllocation->GetOffset() + allocationLocalOffset;
  10294. // This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads.
  10295. VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex);
  10296. return hAllocator->BindVulkanImage(m_hMemory, memoryOffset, hImage, pNext);
  10297. }
  10298. #endif // _VMA_DEVICE_MEMORY_BLOCK_FUNCTIONS
  10299. #ifndef _VMA_ALLOCATION_T_FUNCTIONS
  10300. VmaAllocation_T::VmaAllocation_T(bool mappingAllowed)
  10301. : m_Alignment{ 1 },
  10302. m_Size{ 0 },
  10303. m_pUserData{ VMA_NULL },
  10304. m_pName{ VMA_NULL },
  10305. m_MemoryTypeIndex{ 0 },
  10306. m_Type{ (uint8_t)ALLOCATION_TYPE_NONE },
  10307. m_SuballocationType{ (uint8_t)VMA_SUBALLOCATION_TYPE_UNKNOWN },
  10308. m_MapCount{ 0 },
  10309. m_Flags{ 0 }
  10310. {
  10311. if(mappingAllowed)
  10312. m_Flags |= (uint8_t)FLAG_MAPPING_ALLOWED;
  10313. #if VMA_STATS_STRING_ENABLED
  10314. m_BufferImageUsage = 0;
  10315. #endif
  10316. }
  10317. VmaAllocation_T::~VmaAllocation_T()
  10318. {
  10319. VMA_ASSERT(m_MapCount == 0 && "Allocation was not unmapped before destruction.");
  10320. // Check if owned string was freed.
  10321. VMA_ASSERT(m_pName == VMA_NULL);
  10322. }
  10323. void VmaAllocation_T::InitBlockAllocation(
  10324. VmaDeviceMemoryBlock* block,
  10325. VmaAllocHandle allocHandle,
  10326. VkDeviceSize alignment,
  10327. VkDeviceSize size,
  10328. uint32_t memoryTypeIndex,
  10329. VmaSuballocationType suballocationType,
  10330. bool mapped)
  10331. {
  10332. VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
  10333. VMA_ASSERT(block != VMA_NULL);
  10334. m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK;
  10335. m_Alignment = alignment;
  10336. m_Size = size;
  10337. m_MemoryTypeIndex = memoryTypeIndex;
  10338. if(mapped)
  10339. {
  10340. VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it.");
  10341. m_Flags |= (uint8_t)FLAG_PERSISTENT_MAP;
  10342. }
  10343. m_SuballocationType = (uint8_t)suballocationType;
  10344. m_BlockAllocation.m_Block = block;
  10345. m_BlockAllocation.m_AllocHandle = allocHandle;
  10346. }
  10347. void VmaAllocation_T::InitDedicatedAllocation(
  10348. VmaPool hParentPool,
  10349. uint32_t memoryTypeIndex,
  10350. VkDeviceMemory hMemory,
  10351. VmaSuballocationType suballocationType,
  10352. void* pMappedData,
  10353. VkDeviceSize size)
  10354. {
  10355. VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
  10356. VMA_ASSERT(hMemory != VK_NULL_HANDLE);
  10357. m_Type = (uint8_t)ALLOCATION_TYPE_DEDICATED;
  10358. m_Alignment = 0;
  10359. m_Size = size;
  10360. m_MemoryTypeIndex = memoryTypeIndex;
  10361. m_SuballocationType = (uint8_t)suballocationType;
  10362. if(pMappedData != VMA_NULL)
  10363. {
  10364. VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it.");
  10365. m_Flags |= (uint8_t)FLAG_PERSISTENT_MAP;
  10366. }
  10367. m_DedicatedAllocation.m_hParentPool = hParentPool;
  10368. m_DedicatedAllocation.m_hMemory = hMemory;
  10369. m_DedicatedAllocation.m_pMappedData = pMappedData;
  10370. m_DedicatedAllocation.m_Prev = VMA_NULL;
  10371. m_DedicatedAllocation.m_Next = VMA_NULL;
  10372. }
  10373. void VmaAllocation_T::SetName(VmaAllocator hAllocator, const char* pName)
  10374. {
  10375. VMA_ASSERT(pName == VMA_NULL || pName != m_pName);
  10376. FreeName(hAllocator);
  10377. if (pName != VMA_NULL)
  10378. m_pName = VmaCreateStringCopy(hAllocator->GetAllocationCallbacks(), pName);
  10379. }
  10380. uint8_t VmaAllocation_T::SwapBlockAllocation(VmaAllocator hAllocator, VmaAllocation allocation)
  10381. {
  10382. VMA_ASSERT(allocation != VMA_NULL);
  10383. VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK);
  10384. VMA_ASSERT(allocation->m_Type == ALLOCATION_TYPE_BLOCK);
  10385. if (m_MapCount != 0)
  10386. m_BlockAllocation.m_Block->Unmap(hAllocator, m_MapCount);
  10387. m_BlockAllocation.m_Block->m_pMetadata->SetAllocationUserData(m_BlockAllocation.m_AllocHandle, allocation);
  10388. VMA_SWAP(m_BlockAllocation, allocation->m_BlockAllocation);
  10389. m_BlockAllocation.m_Block->m_pMetadata->SetAllocationUserData(m_BlockAllocation.m_AllocHandle, this);
  10390. #if VMA_STATS_STRING_ENABLED
  10391. VMA_SWAP(m_BufferImageUsage, allocation->m_BufferImageUsage);
  10392. #endif
  10393. return m_MapCount;
  10394. }
  10395. VmaAllocHandle VmaAllocation_T::GetAllocHandle() const
  10396. {
  10397. switch (m_Type)
  10398. {
  10399. case ALLOCATION_TYPE_BLOCK:
  10400. return m_BlockAllocation.m_AllocHandle;
  10401. case ALLOCATION_TYPE_DEDICATED:
  10402. return VK_NULL_HANDLE;
  10403. default:
  10404. VMA_ASSERT(0);
  10405. return VK_NULL_HANDLE;
  10406. }
  10407. }
  10408. VkDeviceSize VmaAllocation_T::GetOffset() const
  10409. {
  10410. switch (m_Type)
  10411. {
  10412. case ALLOCATION_TYPE_BLOCK:
  10413. return m_BlockAllocation.m_Block->m_pMetadata->GetAllocationOffset(m_BlockAllocation.m_AllocHandle);
  10414. case ALLOCATION_TYPE_DEDICATED:
  10415. return 0;
  10416. default:
  10417. VMA_ASSERT(0);
  10418. return 0;
  10419. }
  10420. }
  10421. VmaPool VmaAllocation_T::GetParentPool() const
  10422. {
  10423. switch (m_Type)
  10424. {
  10425. case ALLOCATION_TYPE_BLOCK:
  10426. return m_BlockAllocation.m_Block->GetParentPool();
  10427. case ALLOCATION_TYPE_DEDICATED:
  10428. return m_DedicatedAllocation.m_hParentPool;
  10429. default:
  10430. VMA_ASSERT(0);
  10431. return VK_NULL_HANDLE;
  10432. }
  10433. }
  10434. VkDeviceMemory VmaAllocation_T::GetMemory() const
  10435. {
  10436. switch (m_Type)
  10437. {
  10438. case ALLOCATION_TYPE_BLOCK:
  10439. return m_BlockAllocation.m_Block->GetDeviceMemory();
  10440. case ALLOCATION_TYPE_DEDICATED:
  10441. return m_DedicatedAllocation.m_hMemory;
  10442. default:
  10443. VMA_ASSERT(0);
  10444. return VK_NULL_HANDLE;
  10445. }
  10446. }
  10447. void* VmaAllocation_T::GetMappedData() const
  10448. {
  10449. switch (m_Type)
  10450. {
  10451. case ALLOCATION_TYPE_BLOCK:
  10452. if (m_MapCount != 0 || IsPersistentMap())
  10453. {
  10454. void* pBlockData = m_BlockAllocation.m_Block->GetMappedData();
  10455. VMA_ASSERT(pBlockData != VMA_NULL);
  10456. return (char*)pBlockData + GetOffset();
  10457. }
  10458. else
  10459. {
  10460. return VMA_NULL;
  10461. }
  10462. break;
  10463. case ALLOCATION_TYPE_DEDICATED:
  10464. VMA_ASSERT((m_DedicatedAllocation.m_pMappedData != VMA_NULL) == (m_MapCount != 0 || IsPersistentMap()));
  10465. return m_DedicatedAllocation.m_pMappedData;
  10466. default:
  10467. VMA_ASSERT(0);
  10468. return VMA_NULL;
  10469. }
  10470. }
  10471. void VmaAllocation_T::BlockAllocMap()
  10472. {
  10473. VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK);
  10474. VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it.");
  10475. if (m_MapCount < 0xFF)
  10476. {
  10477. ++m_MapCount;
  10478. }
  10479. else
  10480. {
  10481. VMA_ASSERT(0 && "Allocation mapped too many times simultaneously.");
  10482. }
  10483. }
  10484. void VmaAllocation_T::BlockAllocUnmap()
  10485. {
  10486. VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK);
  10487. if (m_MapCount > 0)
  10488. {
  10489. --m_MapCount;
  10490. }
  10491. else
  10492. {
  10493. VMA_ASSERT(0 && "Unmapping allocation not previously mapped.");
  10494. }
  10495. }
  10496. VkResult VmaAllocation_T::DedicatedAllocMap(VmaAllocator hAllocator, void** ppData)
  10497. {
  10498. VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED);
  10499. VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it.");
  10500. if (m_MapCount != 0 || IsPersistentMap())
  10501. {
  10502. if (m_MapCount < 0xFF)
  10503. {
  10504. VMA_ASSERT(m_DedicatedAllocation.m_pMappedData != VMA_NULL);
  10505. *ppData = m_DedicatedAllocation.m_pMappedData;
  10506. ++m_MapCount;
  10507. return VK_SUCCESS;
  10508. }
  10509. else
  10510. {
  10511. VMA_ASSERT(0 && "Dedicated allocation mapped too many times simultaneously.");
  10512. return VK_ERROR_MEMORY_MAP_FAILED;
  10513. }
  10514. }
  10515. else
  10516. {
  10517. VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)(
  10518. hAllocator->m_hDevice,
  10519. m_DedicatedAllocation.m_hMemory,
  10520. 0, // offset
  10521. VK_WHOLE_SIZE,
  10522. 0, // flags
  10523. ppData);
  10524. if (result == VK_SUCCESS)
  10525. {
  10526. m_DedicatedAllocation.m_pMappedData = *ppData;
  10527. m_MapCount = 1;
  10528. }
  10529. return result;
  10530. }
  10531. }
  10532. void VmaAllocation_T::DedicatedAllocUnmap(VmaAllocator hAllocator)
  10533. {
  10534. VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED);
  10535. if (m_MapCount > 0)
  10536. {
  10537. --m_MapCount;
  10538. if (m_MapCount == 0 && !IsPersistentMap())
  10539. {
  10540. m_DedicatedAllocation.m_pMappedData = VMA_NULL;
  10541. (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(
  10542. hAllocator->m_hDevice,
  10543. m_DedicatedAllocation.m_hMemory);
  10544. }
  10545. }
  10546. else
  10547. {
  10548. VMA_ASSERT(0 && "Unmapping dedicated allocation not previously mapped.");
  10549. }
  10550. }
  10551. #if VMA_STATS_STRING_ENABLED
  10552. void VmaAllocation_T::InitBufferImageUsage(uint32_t bufferImageUsage)
  10553. {
  10554. VMA_ASSERT(m_BufferImageUsage == 0);
  10555. m_BufferImageUsage = bufferImageUsage;
  10556. }
  10557. void VmaAllocation_T::PrintParameters(class VmaJsonWriter& json) const
  10558. {
  10559. json.WriteString("Type");
  10560. json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[m_SuballocationType]);
  10561. json.WriteString("Size");
  10562. json.WriteNumber(m_Size);
  10563. json.WriteString("Usage");
  10564. json.WriteNumber(m_BufferImageUsage);
  10565. if (m_pUserData != VMA_NULL)
  10566. {
  10567. json.WriteString("CustomData");
  10568. json.BeginString();
  10569. json.ContinueString_Pointer(m_pUserData);
  10570. json.EndString();
  10571. }
  10572. if (m_pName != VMA_NULL)
  10573. {
  10574. json.WriteString("Name");
  10575. json.WriteString(m_pName);
  10576. }
  10577. }
  10578. #endif // VMA_STATS_STRING_ENABLED
  10579. void VmaAllocation_T::FreeName(VmaAllocator hAllocator)
  10580. {
  10581. if(m_pName)
  10582. {
  10583. VmaFreeString(hAllocator->GetAllocationCallbacks(), m_pName);
  10584. m_pName = VMA_NULL;
  10585. }
  10586. }
  10587. #endif // _VMA_ALLOCATION_T_FUNCTIONS
  10588. #ifndef _VMA_BLOCK_VECTOR_FUNCTIONS
  10589. VmaBlockVector::VmaBlockVector(
  10590. VmaAllocator hAllocator,
  10591. VmaPool hParentPool,
  10592. uint32_t memoryTypeIndex,
  10593. VkDeviceSize preferredBlockSize,
  10594. size_t minBlockCount,
  10595. size_t maxBlockCount,
  10596. VkDeviceSize bufferImageGranularity,
  10597. bool explicitBlockSize,
  10598. uint32_t algorithm,
  10599. float priority,
  10600. VkDeviceSize minAllocationAlignment,
  10601. void* pMemoryAllocateNext)
  10602. : m_hAllocator(hAllocator),
  10603. m_hParentPool(hParentPool),
  10604. m_MemoryTypeIndex(memoryTypeIndex),
  10605. m_PreferredBlockSize(preferredBlockSize),
  10606. m_MinBlockCount(minBlockCount),
  10607. m_MaxBlockCount(maxBlockCount),
  10608. m_BufferImageGranularity(bufferImageGranularity),
  10609. m_ExplicitBlockSize(explicitBlockSize),
  10610. m_Algorithm(algorithm),
  10611. m_Priority(priority),
  10612. m_MinAllocationAlignment(minAllocationAlignment),
  10613. m_pMemoryAllocateNext(pMemoryAllocateNext),
  10614. m_Blocks(VmaStlAllocator<VmaDeviceMemoryBlock*>(hAllocator->GetAllocationCallbacks())),
  10615. m_NextBlockId(0) {}
  10616. VmaBlockVector::~VmaBlockVector()
  10617. {
  10618. for (size_t i = m_Blocks.size(); i--; )
  10619. {
  10620. m_Blocks[i]->Destroy(m_hAllocator);
  10621. vma_delete(m_hAllocator, m_Blocks[i]);
  10622. }
  10623. }
  10624. VkResult VmaBlockVector::CreateMinBlocks()
  10625. {
  10626. for (size_t i = 0; i < m_MinBlockCount; ++i)
  10627. {
  10628. VkResult res = CreateBlock(m_PreferredBlockSize, VMA_NULL);
  10629. if (res != VK_SUCCESS)
  10630. {
  10631. return res;
  10632. }
  10633. }
  10634. return VK_SUCCESS;
  10635. }
  10636. void VmaBlockVector::AddStatistics(VmaStatistics& inoutStats)
  10637. {
  10638. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  10639. const size_t blockCount = m_Blocks.size();
  10640. for (uint32_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
  10641. {
  10642. const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
  10643. VMA_ASSERT(pBlock);
  10644. VMA_HEAVY_ASSERT(pBlock->Validate());
  10645. pBlock->m_pMetadata->AddStatistics(inoutStats);
  10646. }
  10647. }
  10648. void VmaBlockVector::AddDetailedStatistics(VmaDetailedStatistics& inoutStats)
  10649. {
  10650. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  10651. const size_t blockCount = m_Blocks.size();
  10652. for (uint32_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
  10653. {
  10654. const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
  10655. VMA_ASSERT(pBlock);
  10656. VMA_HEAVY_ASSERT(pBlock->Validate());
  10657. pBlock->m_pMetadata->AddDetailedStatistics(inoutStats);
  10658. }
  10659. }
  10660. bool VmaBlockVector::IsEmpty()
  10661. {
  10662. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  10663. return m_Blocks.empty();
  10664. }
  10665. bool VmaBlockVector::IsCorruptionDetectionEnabled() const
  10666. {
  10667. const uint32_t requiredMemFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
  10668. return (VMA_DEBUG_DETECT_CORRUPTION != 0) &&
  10669. (VMA_DEBUG_MARGIN > 0) &&
  10670. (m_Algorithm == 0 || m_Algorithm == VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) &&
  10671. (m_hAllocator->m_MemProps.memoryTypes[m_MemoryTypeIndex].propertyFlags & requiredMemFlags) == requiredMemFlags;
  10672. }
  10673. VkResult VmaBlockVector::Allocate(
  10674. VkDeviceSize size,
  10675. VkDeviceSize alignment,
  10676. const VmaAllocationCreateInfo& createInfo,
  10677. VmaSuballocationType suballocType,
  10678. size_t allocationCount,
  10679. VmaAllocation* pAllocations)
  10680. {
  10681. size_t allocIndex;
  10682. VkResult res = VK_SUCCESS;
  10683. alignment = VMA_MAX(alignment, m_MinAllocationAlignment);
  10684. if (IsCorruptionDetectionEnabled())
  10685. {
  10686. size = VmaAlignUp<VkDeviceSize>(size, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE));
  10687. alignment = VmaAlignUp<VkDeviceSize>(alignment, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE));
  10688. }
  10689. {
  10690. VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex);
  10691. for (allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  10692. {
  10693. res = AllocatePage(
  10694. size,
  10695. alignment,
  10696. createInfo,
  10697. suballocType,
  10698. pAllocations + allocIndex);
  10699. if (res != VK_SUCCESS)
  10700. {
  10701. break;
  10702. }
  10703. }
  10704. }
  10705. if (res != VK_SUCCESS)
  10706. {
  10707. // Free all already created allocations.
  10708. while (allocIndex--)
  10709. Free(pAllocations[allocIndex]);
  10710. memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount);
  10711. }
  10712. return res;
  10713. }
  10714. VkResult VmaBlockVector::AllocatePage(
  10715. VkDeviceSize size,
  10716. VkDeviceSize alignment,
  10717. const VmaAllocationCreateInfo& createInfo,
  10718. VmaSuballocationType suballocType,
  10719. VmaAllocation* pAllocation)
  10720. {
  10721. const bool isUpperAddress = (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0;
  10722. VkDeviceSize freeMemory;
  10723. {
  10724. const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex);
  10725. VmaBudget heapBudget = {};
  10726. m_hAllocator->GetHeapBudgets(&heapBudget, heapIndex, 1);
  10727. freeMemory = (heapBudget.usage < heapBudget.budget) ? (heapBudget.budget - heapBudget.usage) : 0;
  10728. }
  10729. const bool canFallbackToDedicated = !HasExplicitBlockSize() &&
  10730. (createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0;
  10731. const bool canCreateNewBlock =
  10732. ((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0) &&
  10733. (m_Blocks.size() < m_MaxBlockCount) &&
  10734. (freeMemory >= size || !canFallbackToDedicated);
  10735. uint32_t strategy = createInfo.flags & VMA_ALLOCATION_CREATE_STRATEGY_MASK;
  10736. // Upper address can only be used with linear allocator and within single memory block.
  10737. if (isUpperAddress &&
  10738. (m_Algorithm != VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT || m_MaxBlockCount > 1))
  10739. {
  10740. return VK_ERROR_FEATURE_NOT_PRESENT;
  10741. }
  10742. // Early reject: requested allocation size is larger that maximum block size for this block vector.
  10743. if (size + VMA_DEBUG_MARGIN > m_PreferredBlockSize)
  10744. {
  10745. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10746. }
  10747. // 1. Search existing allocations. Try to allocate.
  10748. if (m_Algorithm == VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT)
  10749. {
  10750. // Use only last block.
  10751. if (!m_Blocks.empty())
  10752. {
  10753. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks.back();
  10754. VMA_ASSERT(pCurrBlock);
  10755. VkResult res = AllocateFromBlock(
  10756. pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation);
  10757. if (res == VK_SUCCESS)
  10758. {
  10759. VMA_DEBUG_LOG(" Returned from last block #%u", pCurrBlock->GetId());
  10760. IncrementallySortBlocks();
  10761. return VK_SUCCESS;
  10762. }
  10763. }
  10764. }
  10765. else
  10766. {
  10767. if (strategy != VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT) // MIN_MEMORY or default
  10768. {
  10769. const bool isHostVisible =
  10770. (m_hAllocator->m_MemProps.memoryTypes[m_MemoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0;
  10771. if(isHostVisible)
  10772. {
  10773. const bool isMappingAllowed = (createInfo.flags &
  10774. (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0;
  10775. /*
  10776. For non-mappable allocations, check blocks that are not mapped first.
  10777. For mappable allocations, check blocks that are already mapped first.
  10778. This way, having many blocks, we will separate mappable and non-mappable allocations,
  10779. hopefully limiting the number of blocks that are mapped, which will help tools like RenderDoc.
  10780. */
  10781. for(size_t mappingI = 0; mappingI < 2; ++mappingI)
  10782. {
  10783. // Forward order in m_Blocks - prefer blocks with smallest amount of free space.
  10784. for (size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  10785. {
  10786. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
  10787. VMA_ASSERT(pCurrBlock);
  10788. const bool isBlockMapped = pCurrBlock->GetMappedData() != VMA_NULL;
  10789. if((mappingI == 0) == (isMappingAllowed == isBlockMapped))
  10790. {
  10791. VkResult res = AllocateFromBlock(
  10792. pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation);
  10793. if (res == VK_SUCCESS)
  10794. {
  10795. VMA_DEBUG_LOG(" Returned from existing block #%u", pCurrBlock->GetId());
  10796. IncrementallySortBlocks();
  10797. return VK_SUCCESS;
  10798. }
  10799. }
  10800. }
  10801. }
  10802. }
  10803. else
  10804. {
  10805. // Forward order in m_Blocks - prefer blocks with smallest amount of free space.
  10806. for (size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  10807. {
  10808. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
  10809. VMA_ASSERT(pCurrBlock);
  10810. VkResult res = AllocateFromBlock(
  10811. pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation);
  10812. if (res == VK_SUCCESS)
  10813. {
  10814. VMA_DEBUG_LOG(" Returned from existing block #%u", pCurrBlock->GetId());
  10815. IncrementallySortBlocks();
  10816. return VK_SUCCESS;
  10817. }
  10818. }
  10819. }
  10820. }
  10821. else // VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT
  10822. {
  10823. // Backward order in m_Blocks - prefer blocks with largest amount of free space.
  10824. for (size_t blockIndex = m_Blocks.size(); blockIndex--; )
  10825. {
  10826. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
  10827. VMA_ASSERT(pCurrBlock);
  10828. VkResult res = AllocateFromBlock(pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation);
  10829. if (res == VK_SUCCESS)
  10830. {
  10831. VMA_DEBUG_LOG(" Returned from existing block #%u", pCurrBlock->GetId());
  10832. IncrementallySortBlocks();
  10833. return VK_SUCCESS;
  10834. }
  10835. }
  10836. }
  10837. }
  10838. // 2. Try to create new block.
  10839. if (canCreateNewBlock)
  10840. {
  10841. // Calculate optimal size for new block.
  10842. VkDeviceSize newBlockSize = m_PreferredBlockSize;
  10843. uint32_t newBlockSizeShift = 0;
  10844. const uint32_t NEW_BLOCK_SIZE_SHIFT_MAX = 3;
  10845. if (!m_ExplicitBlockSize)
  10846. {
  10847. // Allocate 1/8, 1/4, 1/2 as first blocks.
  10848. const VkDeviceSize maxExistingBlockSize = CalcMaxBlockSize();
  10849. for (uint32_t i = 0; i < NEW_BLOCK_SIZE_SHIFT_MAX; ++i)
  10850. {
  10851. const VkDeviceSize smallerNewBlockSize = newBlockSize / 2;
  10852. if (smallerNewBlockSize > maxExistingBlockSize && smallerNewBlockSize >= size * 2)
  10853. {
  10854. newBlockSize = smallerNewBlockSize;
  10855. ++newBlockSizeShift;
  10856. }
  10857. else
  10858. {
  10859. break;
  10860. }
  10861. }
  10862. }
  10863. size_t newBlockIndex = 0;
  10864. VkResult res = (newBlockSize <= freeMemory || !canFallbackToDedicated) ?
  10865. CreateBlock(newBlockSize, &newBlockIndex) : VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10866. // Allocation of this size failed? Try 1/2, 1/4, 1/8 of m_PreferredBlockSize.
  10867. if (!m_ExplicitBlockSize)
  10868. {
  10869. while (res < 0 && newBlockSizeShift < NEW_BLOCK_SIZE_SHIFT_MAX)
  10870. {
  10871. const VkDeviceSize smallerNewBlockSize = newBlockSize / 2;
  10872. if (smallerNewBlockSize >= size)
  10873. {
  10874. newBlockSize = smallerNewBlockSize;
  10875. ++newBlockSizeShift;
  10876. res = (newBlockSize <= freeMemory || !canFallbackToDedicated) ?
  10877. CreateBlock(newBlockSize, &newBlockIndex) : VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10878. }
  10879. else
  10880. {
  10881. break;
  10882. }
  10883. }
  10884. }
  10885. if (res == VK_SUCCESS)
  10886. {
  10887. VmaDeviceMemoryBlock* const pBlock = m_Blocks[newBlockIndex];
  10888. VMA_ASSERT(pBlock->m_pMetadata->GetSize() >= size);
  10889. res = AllocateFromBlock(
  10890. pBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation);
  10891. if (res == VK_SUCCESS)
  10892. {
  10893. VMA_DEBUG_LOG(" Created new block #%u Size=%llu", pBlock->GetId(), newBlockSize);
  10894. IncrementallySortBlocks();
  10895. return VK_SUCCESS;
  10896. }
  10897. else
  10898. {
  10899. // Allocation from new block failed, possibly due to VMA_DEBUG_MARGIN or alignment.
  10900. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10901. }
  10902. }
  10903. }
  10904. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10905. }
  10906. void VmaBlockVector::Free(const VmaAllocation hAllocation)
  10907. {
  10908. VmaDeviceMemoryBlock* pBlockToDelete = VMA_NULL;
  10909. bool budgetExceeded = false;
  10910. {
  10911. const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex);
  10912. VmaBudget heapBudget = {};
  10913. m_hAllocator->GetHeapBudgets(&heapBudget, heapIndex, 1);
  10914. budgetExceeded = heapBudget.usage >= heapBudget.budget;
  10915. }
  10916. // Scope for lock.
  10917. {
  10918. VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex);
  10919. VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock();
  10920. if (IsCorruptionDetectionEnabled())
  10921. {
  10922. VkResult res = pBlock->ValidateMagicValueAfterAllocation(m_hAllocator, hAllocation->GetOffset(), hAllocation->GetSize());
  10923. VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to validate magic value.");
  10924. }
  10925. if (hAllocation->IsPersistentMap())
  10926. {
  10927. pBlock->Unmap(m_hAllocator, 1);
  10928. }
  10929. const bool hadEmptyBlockBeforeFree = HasEmptyBlock();
  10930. pBlock->m_pMetadata->Free(hAllocation->GetAllocHandle());
  10931. pBlock->PostFree(m_hAllocator);
  10932. VMA_HEAVY_ASSERT(pBlock->Validate());
  10933. VMA_DEBUG_LOG(" Freed from MemoryTypeIndex=%u", m_MemoryTypeIndex);
  10934. const bool canDeleteBlock = m_Blocks.size() > m_MinBlockCount;
  10935. // pBlock became empty after this deallocation.
  10936. if (pBlock->m_pMetadata->IsEmpty())
  10937. {
  10938. // Already had empty block. We don't want to have two, so delete this one.
  10939. if ((hadEmptyBlockBeforeFree || budgetExceeded) && canDeleteBlock)
  10940. {
  10941. pBlockToDelete = pBlock;
  10942. Remove(pBlock);
  10943. }
  10944. // else: We now have one empty block - leave it. A hysteresis to avoid allocating whole block back and forth.
  10945. }
  10946. // pBlock didn't become empty, but we have another empty block - find and free that one.
  10947. // (This is optional, heuristics.)
  10948. else if (hadEmptyBlockBeforeFree && canDeleteBlock)
  10949. {
  10950. VmaDeviceMemoryBlock* pLastBlock = m_Blocks.back();
  10951. if (pLastBlock->m_pMetadata->IsEmpty())
  10952. {
  10953. pBlockToDelete = pLastBlock;
  10954. m_Blocks.pop_back();
  10955. }
  10956. }
  10957. IncrementallySortBlocks();
  10958. }
  10959. // Destruction of a free block. Deferred until this point, outside of mutex
  10960. // lock, for performance reason.
  10961. if (pBlockToDelete != VMA_NULL)
  10962. {
  10963. VMA_DEBUG_LOG(" Deleted empty block #%u", pBlockToDelete->GetId());
  10964. pBlockToDelete->Destroy(m_hAllocator);
  10965. vma_delete(m_hAllocator, pBlockToDelete);
  10966. }
  10967. m_hAllocator->m_Budget.RemoveAllocation(m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex), hAllocation->GetSize());
  10968. m_hAllocator->m_AllocationObjectAllocator.Free(hAllocation);
  10969. }
  10970. VkDeviceSize VmaBlockVector::CalcMaxBlockSize() const
  10971. {
  10972. VkDeviceSize result = 0;
  10973. for (size_t i = m_Blocks.size(); i--; )
  10974. {
  10975. result = VMA_MAX(result, m_Blocks[i]->m_pMetadata->GetSize());
  10976. if (result >= m_PreferredBlockSize)
  10977. {
  10978. break;
  10979. }
  10980. }
  10981. return result;
  10982. }
  10983. void VmaBlockVector::Remove(VmaDeviceMemoryBlock* pBlock)
  10984. {
  10985. for (uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  10986. {
  10987. if (m_Blocks[blockIndex] == pBlock)
  10988. {
  10989. VmaVectorRemove(m_Blocks, blockIndex);
  10990. return;
  10991. }
  10992. }
  10993. VMA_ASSERT(0);
  10994. }
  10995. void VmaBlockVector::IncrementallySortBlocks()
  10996. {
  10997. if (!m_IncrementalSort)
  10998. return;
  10999. if (m_Algorithm != VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT)
  11000. {
  11001. // Bubble sort only until first swap.
  11002. for (size_t i = 1; i < m_Blocks.size(); ++i)
  11003. {
  11004. if (m_Blocks[i - 1]->m_pMetadata->GetSumFreeSize() > m_Blocks[i]->m_pMetadata->GetSumFreeSize())
  11005. {
  11006. VMA_SWAP(m_Blocks[i - 1], m_Blocks[i]);
  11007. return;
  11008. }
  11009. }
  11010. }
  11011. }
  11012. void VmaBlockVector::SortByFreeSize()
  11013. {
  11014. VMA_SORT(m_Blocks.begin(), m_Blocks.end(),
  11015. [](VmaDeviceMemoryBlock* b1, VmaDeviceMemoryBlock* b2) -> bool
  11016. {
  11017. return b1->m_pMetadata->GetSumFreeSize() < b2->m_pMetadata->GetSumFreeSize();
  11018. });
  11019. }
  11020. VkResult VmaBlockVector::AllocateFromBlock(
  11021. VmaDeviceMemoryBlock* pBlock,
  11022. VkDeviceSize size,
  11023. VkDeviceSize alignment,
  11024. VmaAllocationCreateFlags allocFlags,
  11025. void* pUserData,
  11026. VmaSuballocationType suballocType,
  11027. uint32_t strategy,
  11028. VmaAllocation* pAllocation)
  11029. {
  11030. const bool isUpperAddress = (allocFlags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0;
  11031. VmaAllocationRequest currRequest = {};
  11032. if (pBlock->m_pMetadata->CreateAllocationRequest(
  11033. size,
  11034. alignment,
  11035. isUpperAddress,
  11036. suballocType,
  11037. strategy,
  11038. &currRequest))
  11039. {
  11040. return CommitAllocationRequest(currRequest, pBlock, alignment, allocFlags, pUserData, suballocType, pAllocation);
  11041. }
  11042. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  11043. }
  11044. VkResult VmaBlockVector::CommitAllocationRequest(
  11045. VmaAllocationRequest& allocRequest,
  11046. VmaDeviceMemoryBlock* pBlock,
  11047. VkDeviceSize alignment,
  11048. VmaAllocationCreateFlags allocFlags,
  11049. void* pUserData,
  11050. VmaSuballocationType suballocType,
  11051. VmaAllocation* pAllocation)
  11052. {
  11053. const bool mapped = (allocFlags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0;
  11054. const bool isUserDataString = (allocFlags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0;
  11055. const bool isMappingAllowed = (allocFlags &
  11056. (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0;
  11057. pBlock->PostAlloc();
  11058. // Allocate from pCurrBlock.
  11059. if (mapped)
  11060. {
  11061. VkResult res = pBlock->Map(m_hAllocator, 1, VMA_NULL);
  11062. if (res != VK_SUCCESS)
  11063. {
  11064. return res;
  11065. }
  11066. }
  11067. *pAllocation = m_hAllocator->m_AllocationObjectAllocator.Allocate(isMappingAllowed);
  11068. pBlock->m_pMetadata->Alloc(allocRequest, suballocType, *pAllocation);
  11069. (*pAllocation)->InitBlockAllocation(
  11070. pBlock,
  11071. allocRequest.allocHandle,
  11072. alignment,
  11073. allocRequest.size, // Not size, as actual allocation size may be larger than requested!
  11074. m_MemoryTypeIndex,
  11075. suballocType,
  11076. mapped);
  11077. VMA_HEAVY_ASSERT(pBlock->Validate());
  11078. if (isUserDataString)
  11079. (*pAllocation)->SetName(m_hAllocator, (const char*)pUserData);
  11080. else
  11081. (*pAllocation)->SetUserData(m_hAllocator, pUserData);
  11082. m_hAllocator->m_Budget.AddAllocation(m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex), allocRequest.size);
  11083. if (VMA_DEBUG_INITIALIZE_ALLOCATIONS)
  11084. {
  11085. m_hAllocator->FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED);
  11086. }
  11087. if (IsCorruptionDetectionEnabled())
  11088. {
  11089. VkResult res = pBlock->WriteMagicValueAfterAllocation(m_hAllocator, (*pAllocation)->GetOffset(), allocRequest.size);
  11090. VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to write magic value.");
  11091. }
  11092. return VK_SUCCESS;
  11093. }
  11094. VkResult VmaBlockVector::CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex)
  11095. {
  11096. VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
  11097. allocInfo.pNext = m_pMemoryAllocateNext;
  11098. allocInfo.memoryTypeIndex = m_MemoryTypeIndex;
  11099. allocInfo.allocationSize = blockSize;
  11100. #if VMA_BUFFER_DEVICE_ADDRESS
  11101. // Every standalone block can potentially contain a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT - always enable the feature.
  11102. VkMemoryAllocateFlagsInfoKHR allocFlagsInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR };
  11103. if (m_hAllocator->m_UseKhrBufferDeviceAddress)
  11104. {
  11105. allocFlagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR;
  11106. VmaPnextChainPushFront(&allocInfo, &allocFlagsInfo);
  11107. }
  11108. #endif // VMA_BUFFER_DEVICE_ADDRESS
  11109. #if VMA_MEMORY_PRIORITY
  11110. VkMemoryPriorityAllocateInfoEXT priorityInfo = { VK_STRUCTURE_TYPE_MEMORY_PRIORITY_ALLOCATE_INFO_EXT };
  11111. if (m_hAllocator->m_UseExtMemoryPriority)
  11112. {
  11113. VMA_ASSERT(m_Priority >= 0.f && m_Priority <= 1.f);
  11114. priorityInfo.priority = m_Priority;
  11115. VmaPnextChainPushFront(&allocInfo, &priorityInfo);
  11116. }
  11117. #endif // VMA_MEMORY_PRIORITY
  11118. #if VMA_EXTERNAL_MEMORY
  11119. // Attach VkExportMemoryAllocateInfoKHR if necessary.
  11120. VkExportMemoryAllocateInfoKHR exportMemoryAllocInfo = { VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR };
  11121. exportMemoryAllocInfo.handleTypes = m_hAllocator->GetExternalMemoryHandleTypeFlags(m_MemoryTypeIndex);
  11122. if (exportMemoryAllocInfo.handleTypes != 0)
  11123. {
  11124. VmaPnextChainPushFront(&allocInfo, &exportMemoryAllocInfo);
  11125. }
  11126. #endif // VMA_EXTERNAL_MEMORY
  11127. VkDeviceMemory mem = VK_NULL_HANDLE;
  11128. VkResult res = m_hAllocator->AllocateVulkanMemory(&allocInfo, &mem);
  11129. if (res < 0)
  11130. {
  11131. return res;
  11132. }
  11133. // New VkDeviceMemory successfully created.
  11134. // Create new Allocation for it.
  11135. VmaDeviceMemoryBlock* const pBlock = vma_new(m_hAllocator, VmaDeviceMemoryBlock)(m_hAllocator);
  11136. pBlock->Init(
  11137. m_hAllocator,
  11138. m_hParentPool,
  11139. m_MemoryTypeIndex,
  11140. mem,
  11141. allocInfo.allocationSize,
  11142. m_NextBlockId++,
  11143. m_Algorithm,
  11144. m_BufferImageGranularity);
  11145. m_Blocks.push_back(pBlock);
  11146. if (pNewBlockIndex != VMA_NULL)
  11147. {
  11148. *pNewBlockIndex = m_Blocks.size() - 1;
  11149. }
  11150. return VK_SUCCESS;
  11151. }
  11152. bool VmaBlockVector::HasEmptyBlock()
  11153. {
  11154. for (size_t index = 0, count = m_Blocks.size(); index < count; ++index)
  11155. {
  11156. VmaDeviceMemoryBlock* const pBlock = m_Blocks[index];
  11157. if (pBlock->m_pMetadata->IsEmpty())
  11158. {
  11159. return true;
  11160. }
  11161. }
  11162. return false;
  11163. }
  11164. #if VMA_STATS_STRING_ENABLED
  11165. void VmaBlockVector::PrintDetailedMap(class VmaJsonWriter& json)
  11166. {
  11167. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  11168. json.BeginObject();
  11169. for (size_t i = 0; i < m_Blocks.size(); ++i)
  11170. {
  11171. json.BeginString();
  11172. json.ContinueString(m_Blocks[i]->GetId());
  11173. json.EndString();
  11174. json.BeginObject();
  11175. json.WriteString("MapRefCount");
  11176. json.WriteNumber(m_Blocks[i]->GetMapRefCount());
  11177. m_Blocks[i]->m_pMetadata->PrintDetailedMap(json);
  11178. json.EndObject();
  11179. }
  11180. json.EndObject();
  11181. }
  11182. #endif // VMA_STATS_STRING_ENABLED
  11183. VkResult VmaBlockVector::CheckCorruption()
  11184. {
  11185. if (!IsCorruptionDetectionEnabled())
  11186. {
  11187. return VK_ERROR_FEATURE_NOT_PRESENT;
  11188. }
  11189. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  11190. for (uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  11191. {
  11192. VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
  11193. VMA_ASSERT(pBlock);
  11194. VkResult res = pBlock->CheckCorruption(m_hAllocator);
  11195. if (res != VK_SUCCESS)
  11196. {
  11197. return res;
  11198. }
  11199. }
  11200. return VK_SUCCESS;
  11201. }
  11202. #endif // _VMA_BLOCK_VECTOR_FUNCTIONS
  11203. #ifndef _VMA_DEFRAGMENTATION_CONTEXT_FUNCTIONS
  11204. VmaDefragmentationContext_T::VmaDefragmentationContext_T(
  11205. VmaAllocator hAllocator,
  11206. const VmaDefragmentationInfo& info)
  11207. : m_MaxPassBytes(info.maxBytesPerPass == 0 ? VK_WHOLE_SIZE : info.maxBytesPerPass),
  11208. m_MaxPassAllocations(info.maxAllocationsPerPass == 0 ? UINT32_MAX : info.maxAllocationsPerPass),
  11209. m_MoveAllocator(hAllocator->GetAllocationCallbacks()),
  11210. m_Moves(m_MoveAllocator)
  11211. {
  11212. m_Algorithm = info.flags & VMA_DEFRAGMENTATION_FLAG_ALGORITHM_MASK;
  11213. if (info.pool != VMA_NULL)
  11214. {
  11215. m_BlockVectorCount = 1;
  11216. m_PoolBlockVector = &info.pool->m_BlockVector;
  11217. m_pBlockVectors = &m_PoolBlockVector;
  11218. m_PoolBlockVector->SetIncrementalSort(false);
  11219. m_PoolBlockVector->SortByFreeSize();
  11220. }
  11221. else
  11222. {
  11223. m_BlockVectorCount = hAllocator->GetMemoryTypeCount();
  11224. m_PoolBlockVector = VMA_NULL;
  11225. m_pBlockVectors = hAllocator->m_pBlockVectors;
  11226. for (uint32_t i = 0; i < m_BlockVectorCount; ++i)
  11227. {
  11228. VmaBlockVector* vector = m_pBlockVectors[i];
  11229. if (vector != VMA_NULL)
  11230. {
  11231. vector->SetIncrementalSort(false);
  11232. vector->SortByFreeSize();
  11233. }
  11234. }
  11235. }
  11236. switch (m_Algorithm)
  11237. {
  11238. case 0: // Default algorithm
  11239. m_Algorithm = VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT;
  11240. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT:
  11241. {
  11242. m_AlgorithmState = vma_new_array(hAllocator, StateBalanced, m_BlockVectorCount);
  11243. break;
  11244. }
  11245. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT:
  11246. {
  11247. if (hAllocator->GetBufferImageGranularity() > 1)
  11248. {
  11249. m_AlgorithmState = vma_new_array(hAllocator, StateExtensive, m_BlockVectorCount);
  11250. }
  11251. break;
  11252. }
  11253. }
  11254. }
  11255. VmaDefragmentationContext_T::~VmaDefragmentationContext_T()
  11256. {
  11257. if (m_PoolBlockVector != VMA_NULL)
  11258. {
  11259. m_PoolBlockVector->SetIncrementalSort(true);
  11260. }
  11261. else
  11262. {
  11263. for (uint32_t i = 0; i < m_BlockVectorCount; ++i)
  11264. {
  11265. VmaBlockVector* vector = m_pBlockVectors[i];
  11266. if (vector != VMA_NULL)
  11267. vector->SetIncrementalSort(true);
  11268. }
  11269. }
  11270. if (m_AlgorithmState)
  11271. {
  11272. switch (m_Algorithm)
  11273. {
  11274. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT:
  11275. vma_delete_array(m_MoveAllocator.m_pCallbacks, reinterpret_cast<StateBalanced*>(m_AlgorithmState), m_BlockVectorCount);
  11276. break;
  11277. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT:
  11278. vma_delete_array(m_MoveAllocator.m_pCallbacks, reinterpret_cast<StateExtensive*>(m_AlgorithmState), m_BlockVectorCount);
  11279. break;
  11280. default:
  11281. VMA_ASSERT(0);
  11282. }
  11283. }
  11284. }
  11285. VkResult VmaDefragmentationContext_T::DefragmentPassBegin(VmaDefragmentationPassMoveInfo& moveInfo)
  11286. {
  11287. if (m_PoolBlockVector != VMA_NULL)
  11288. {
  11289. VmaMutexLockWrite lock(m_PoolBlockVector->GetMutex(), m_PoolBlockVector->GetAllocator()->m_UseMutex);
  11290. if (m_PoolBlockVector->GetBlockCount() > 1)
  11291. ComputeDefragmentation(*m_PoolBlockVector, 0);
  11292. else if (m_PoolBlockVector->GetBlockCount() == 1)
  11293. ReallocWithinBlock(*m_PoolBlockVector, m_PoolBlockVector->GetBlock(0));
  11294. }
  11295. else
  11296. {
  11297. for (uint32_t i = 0; i < m_BlockVectorCount; ++i)
  11298. {
  11299. if (m_pBlockVectors[i] != VMA_NULL)
  11300. {
  11301. VmaMutexLockWrite lock(m_pBlockVectors[i]->GetMutex(), m_pBlockVectors[i]->GetAllocator()->m_UseMutex);
  11302. if (m_pBlockVectors[i]->GetBlockCount() > 1)
  11303. {
  11304. if (ComputeDefragmentation(*m_pBlockVectors[i], i))
  11305. break;
  11306. }
  11307. else if (m_pBlockVectors[i]->GetBlockCount() == 1)
  11308. {
  11309. if (ReallocWithinBlock(*m_pBlockVectors[i], m_pBlockVectors[i]->GetBlock(0)))
  11310. break;
  11311. }
  11312. }
  11313. }
  11314. }
  11315. moveInfo.moveCount = static_cast<uint32_t>(m_Moves.size());
  11316. if (moveInfo.moveCount > 0)
  11317. {
  11318. moveInfo.pMoves = m_Moves.data();
  11319. return VK_INCOMPLETE;
  11320. }
  11321. moveInfo.pMoves = VMA_NULL;
  11322. return VK_SUCCESS;
  11323. }
  11324. VkResult VmaDefragmentationContext_T::DefragmentPassEnd(VmaDefragmentationPassMoveInfo& moveInfo)
  11325. {
  11326. VMA_ASSERT(moveInfo.moveCount > 0 ? moveInfo.pMoves != VMA_NULL : true);
  11327. VkResult result = VK_SUCCESS;
  11328. VmaStlAllocator<FragmentedBlock> blockAllocator(m_MoveAllocator.m_pCallbacks);
  11329. VmaVector<FragmentedBlock, VmaStlAllocator<FragmentedBlock>> immovableBlocks(blockAllocator);
  11330. VmaVector<FragmentedBlock, VmaStlAllocator<FragmentedBlock>> mappedBlocks(blockAllocator);
  11331. VmaAllocator allocator = VMA_NULL;
  11332. for (uint32_t i = 0; i < moveInfo.moveCount; ++i)
  11333. {
  11334. VmaDefragmentationMove& move = moveInfo.pMoves[i];
  11335. size_t prevCount = 0, currentCount = 0;
  11336. VkDeviceSize freedBlockSize = 0;
  11337. uint32_t vectorIndex;
  11338. VmaBlockVector* vector;
  11339. if (m_PoolBlockVector != VMA_NULL)
  11340. {
  11341. vectorIndex = 0;
  11342. vector = m_PoolBlockVector;
  11343. }
  11344. else
  11345. {
  11346. vectorIndex = move.srcAllocation->GetMemoryTypeIndex();
  11347. vector = m_pBlockVectors[vectorIndex];
  11348. VMA_ASSERT(vector != VMA_NULL);
  11349. }
  11350. switch (move.operation)
  11351. {
  11352. case VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY:
  11353. {
  11354. uint8_t mapCount = move.srcAllocation->SwapBlockAllocation(vector->m_hAllocator, move.dstTmpAllocation);
  11355. if (mapCount > 0)
  11356. {
  11357. allocator = vector->m_hAllocator;
  11358. VmaDeviceMemoryBlock* newMapBlock = move.srcAllocation->GetBlock();
  11359. bool notPresent = true;
  11360. for (FragmentedBlock& block : mappedBlocks)
  11361. {
  11362. if (block.block == newMapBlock)
  11363. {
  11364. notPresent = false;
  11365. block.data += mapCount;
  11366. break;
  11367. }
  11368. }
  11369. if (notPresent)
  11370. mappedBlocks.push_back({ mapCount, newMapBlock });
  11371. }
  11372. // Scope for locks, Free have it's own lock
  11373. {
  11374. VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11375. prevCount = vector->GetBlockCount();
  11376. freedBlockSize = move.dstTmpAllocation->GetBlock()->m_pMetadata->GetSize();
  11377. }
  11378. vector->Free(move.dstTmpAllocation);
  11379. {
  11380. VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11381. currentCount = vector->GetBlockCount();
  11382. }
  11383. result = VK_INCOMPLETE;
  11384. break;
  11385. }
  11386. case VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE:
  11387. {
  11388. m_PassStats.bytesMoved -= move.srcAllocation->GetSize();
  11389. --m_PassStats.allocationsMoved;
  11390. vector->Free(move.dstTmpAllocation);
  11391. VmaDeviceMemoryBlock* newBlock = move.srcAllocation->GetBlock();
  11392. bool notPresent = true;
  11393. for (const FragmentedBlock& block : immovableBlocks)
  11394. {
  11395. if (block.block == newBlock)
  11396. {
  11397. notPresent = false;
  11398. break;
  11399. }
  11400. }
  11401. if (notPresent)
  11402. immovableBlocks.push_back({ vectorIndex, newBlock });
  11403. break;
  11404. }
  11405. case VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY:
  11406. {
  11407. m_PassStats.bytesMoved -= move.srcAllocation->GetSize();
  11408. --m_PassStats.allocationsMoved;
  11409. // Scope for locks, Free have it's own lock
  11410. {
  11411. VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11412. prevCount = vector->GetBlockCount();
  11413. freedBlockSize = move.srcAllocation->GetBlock()->m_pMetadata->GetSize();
  11414. }
  11415. vector->Free(move.srcAllocation);
  11416. {
  11417. VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11418. currentCount = vector->GetBlockCount();
  11419. }
  11420. freedBlockSize *= prevCount - currentCount;
  11421. VkDeviceSize dstBlockSize;
  11422. {
  11423. VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11424. dstBlockSize = move.dstTmpAllocation->GetBlock()->m_pMetadata->GetSize();
  11425. }
  11426. vector->Free(move.dstTmpAllocation);
  11427. {
  11428. VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11429. freedBlockSize += dstBlockSize * (currentCount - vector->GetBlockCount());
  11430. currentCount = vector->GetBlockCount();
  11431. }
  11432. result = VK_INCOMPLETE;
  11433. break;
  11434. }
  11435. default:
  11436. VMA_ASSERT(0);
  11437. }
  11438. if (prevCount > currentCount)
  11439. {
  11440. size_t freedBlocks = prevCount - currentCount;
  11441. m_PassStats.deviceMemoryBlocksFreed += static_cast<uint32_t>(freedBlocks);
  11442. m_PassStats.bytesFreed += freedBlockSize;
  11443. }
  11444. switch (m_Algorithm)
  11445. {
  11446. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT:
  11447. {
  11448. if (m_AlgorithmState != VMA_NULL)
  11449. {
  11450. // Avoid unnecessary tries to allocate when new free block is avaiable
  11451. StateExtensive& state = reinterpret_cast<StateExtensive*>(m_AlgorithmState)[vectorIndex];
  11452. if (state.firstFreeBlock != SIZE_MAX)
  11453. {
  11454. const size_t diff = prevCount - currentCount;
  11455. if (state.firstFreeBlock >= diff)
  11456. {
  11457. state.firstFreeBlock -= diff;
  11458. if (state.firstFreeBlock != 0)
  11459. state.firstFreeBlock -= vector->GetBlock(state.firstFreeBlock - 1)->m_pMetadata->IsEmpty();
  11460. }
  11461. else
  11462. state.firstFreeBlock = 0;
  11463. }
  11464. }
  11465. }
  11466. }
  11467. }
  11468. moveInfo.moveCount = 0;
  11469. moveInfo.pMoves = VMA_NULL;
  11470. m_Moves.clear();
  11471. // Update stats
  11472. m_GlobalStats.allocationsMoved += m_PassStats.allocationsMoved;
  11473. m_GlobalStats.bytesFreed += m_PassStats.bytesFreed;
  11474. m_GlobalStats.bytesMoved += m_PassStats.bytesMoved;
  11475. m_GlobalStats.deviceMemoryBlocksFreed += m_PassStats.deviceMemoryBlocksFreed;
  11476. m_PassStats = { 0 };
  11477. // Move blocks with immovable allocations according to algorithm
  11478. if (immovableBlocks.size() > 0)
  11479. {
  11480. switch (m_Algorithm)
  11481. {
  11482. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT:
  11483. {
  11484. if (m_AlgorithmState != VMA_NULL)
  11485. {
  11486. bool swapped = false;
  11487. // Move to the start of free blocks range
  11488. for (const FragmentedBlock& block : immovableBlocks)
  11489. {
  11490. StateExtensive& state = reinterpret_cast<StateExtensive*>(m_AlgorithmState)[block.data];
  11491. if (state.operation != StateExtensive::Operation::Cleanup)
  11492. {
  11493. VmaBlockVector* vector = m_pBlockVectors[block.data];
  11494. VmaMutexLockWrite lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11495. for (size_t i = 0, count = vector->GetBlockCount() - m_ImmovableBlockCount; i < count; ++i)
  11496. {
  11497. if (vector->GetBlock(i) == block.block)
  11498. {
  11499. VMA_SWAP(vector->m_Blocks[i], vector->m_Blocks[vector->GetBlockCount() - ++m_ImmovableBlockCount]);
  11500. if (state.firstFreeBlock != SIZE_MAX)
  11501. {
  11502. if (i + 1 < state.firstFreeBlock)
  11503. {
  11504. if (state.firstFreeBlock > 1)
  11505. VMA_SWAP(vector->m_Blocks[i], vector->m_Blocks[--state.firstFreeBlock]);
  11506. else
  11507. --state.firstFreeBlock;
  11508. }
  11509. }
  11510. swapped = true;
  11511. break;
  11512. }
  11513. }
  11514. }
  11515. }
  11516. if (swapped)
  11517. result = VK_INCOMPLETE;
  11518. break;
  11519. }
  11520. }
  11521. default:
  11522. {
  11523. // Move to the begining
  11524. for (const FragmentedBlock& block : immovableBlocks)
  11525. {
  11526. VmaBlockVector* vector = m_pBlockVectors[block.data];
  11527. VmaMutexLockWrite lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11528. for (size_t i = m_ImmovableBlockCount; i < vector->GetBlockCount(); ++i)
  11529. {
  11530. if (vector->GetBlock(i) == block.block)
  11531. {
  11532. VMA_SWAP(vector->m_Blocks[i], vector->m_Blocks[m_ImmovableBlockCount++]);
  11533. break;
  11534. }
  11535. }
  11536. }
  11537. break;
  11538. }
  11539. }
  11540. }
  11541. // Bulk-map destination blocks
  11542. for (const FragmentedBlock& block : mappedBlocks)
  11543. {
  11544. VkResult res = block.block->Map(allocator, block.data, VMA_NULL);
  11545. VMA_ASSERT(res == VK_SUCCESS);
  11546. }
  11547. return result;
  11548. }
  11549. bool VmaDefragmentationContext_T::ComputeDefragmentation(VmaBlockVector& vector, size_t index)
  11550. {
  11551. switch (m_Algorithm)
  11552. {
  11553. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT:
  11554. return ComputeDefragmentation_Fast(vector);
  11555. default:
  11556. VMA_ASSERT(0);
  11557. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT:
  11558. return ComputeDefragmentation_Balanced(vector, index, true);
  11559. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT:
  11560. return ComputeDefragmentation_Full(vector);
  11561. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT:
  11562. return ComputeDefragmentation_Extensive(vector, index);
  11563. }
  11564. }
  11565. VmaDefragmentationContext_T::MoveAllocationData VmaDefragmentationContext_T::GetMoveData(
  11566. VmaAllocHandle handle, VmaBlockMetadata* metadata)
  11567. {
  11568. MoveAllocationData moveData;
  11569. moveData.move.srcAllocation = (VmaAllocation)metadata->GetAllocationUserData(handle);
  11570. moveData.size = moveData.move.srcAllocation->GetSize();
  11571. moveData.alignment = moveData.move.srcAllocation->GetAlignment();
  11572. moveData.type = moveData.move.srcAllocation->GetSuballocationType();
  11573. moveData.flags = 0;
  11574. if (moveData.move.srcAllocation->IsPersistentMap())
  11575. moveData.flags |= VMA_ALLOCATION_CREATE_MAPPED_BIT;
  11576. if (moveData.move.srcAllocation->IsMappingAllowed())
  11577. moveData.flags |= VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT;
  11578. return moveData;
  11579. }
  11580. VmaDefragmentationContext_T::CounterStatus VmaDefragmentationContext_T::CheckCounters(VkDeviceSize bytes)
  11581. {
  11582. // Ignore allocation if will exceed max size for copy
  11583. if (m_PassStats.bytesMoved + bytes > m_MaxPassBytes)
  11584. {
  11585. if (++m_IgnoredAllocs < MAX_ALLOCS_TO_IGNORE)
  11586. return CounterStatus::Ignore;
  11587. else
  11588. return CounterStatus::End;
  11589. }
  11590. return CounterStatus::Pass;
  11591. }
  11592. bool VmaDefragmentationContext_T::IncrementCounters(VkDeviceSize bytes)
  11593. {
  11594. m_PassStats.bytesMoved += bytes;
  11595. // Early return when max found
  11596. if (++m_PassStats.allocationsMoved >= m_MaxPassAllocations || m_PassStats.bytesMoved >= m_MaxPassBytes)
  11597. {
  11598. VMA_ASSERT(m_PassStats.allocationsMoved == m_MaxPassAllocations ||
  11599. m_PassStats.bytesMoved == m_MaxPassBytes && "Exceeded maximal pass threshold!");
  11600. return true;
  11601. }
  11602. return false;
  11603. }
  11604. bool VmaDefragmentationContext_T::ReallocWithinBlock(VmaBlockVector& vector, VmaDeviceMemoryBlock* block)
  11605. {
  11606. VmaBlockMetadata* metadata = block->m_pMetadata;
  11607. for (VmaAllocHandle handle = metadata->GetAllocationListBegin();
  11608. handle != VK_NULL_HANDLE;
  11609. handle = metadata->GetNextAllocation(handle))
  11610. {
  11611. MoveAllocationData moveData = GetMoveData(handle, metadata);
  11612. // Ignore newly created allocations by defragmentation algorithm
  11613. if (moveData.move.srcAllocation->GetUserData() == this)
  11614. continue;
  11615. switch (CheckCounters(moveData.move.srcAllocation->GetSize()))
  11616. {
  11617. case CounterStatus::Ignore:
  11618. continue;
  11619. case CounterStatus::End:
  11620. return true;
  11621. default:
  11622. VMA_ASSERT(0);
  11623. case CounterStatus::Pass:
  11624. break;
  11625. }
  11626. VkDeviceSize offset = moveData.move.srcAllocation->GetOffset();
  11627. if (offset != 0 && metadata->GetSumFreeSize() >= moveData.size)
  11628. {
  11629. VmaAllocationRequest request = {};
  11630. if (metadata->CreateAllocationRequest(
  11631. moveData.size,
  11632. moveData.alignment,
  11633. false,
  11634. moveData.type,
  11635. VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT,
  11636. &request))
  11637. {
  11638. if (metadata->GetAllocationOffset(request.allocHandle) < offset)
  11639. {
  11640. if (vector.CommitAllocationRequest(
  11641. request,
  11642. block,
  11643. moveData.alignment,
  11644. moveData.flags,
  11645. this,
  11646. moveData.type,
  11647. &moveData.move.dstTmpAllocation) == VK_SUCCESS)
  11648. {
  11649. m_Moves.push_back(moveData.move);
  11650. if (IncrementCounters(moveData.size))
  11651. return true;
  11652. }
  11653. }
  11654. }
  11655. }
  11656. }
  11657. return false;
  11658. }
  11659. bool VmaDefragmentationContext_T::AllocInOtherBlock(size_t start, size_t end, MoveAllocationData& data, VmaBlockVector& vector)
  11660. {
  11661. for (; start < end; ++start)
  11662. {
  11663. VmaDeviceMemoryBlock* dstBlock = vector.GetBlock(start);
  11664. if (dstBlock->m_pMetadata->GetSumFreeSize() >= data.size)
  11665. {
  11666. if (vector.AllocateFromBlock(dstBlock,
  11667. data.size,
  11668. data.alignment,
  11669. data.flags,
  11670. this,
  11671. data.type,
  11672. 0,
  11673. &data.move.dstTmpAllocation) == VK_SUCCESS)
  11674. {
  11675. m_Moves.push_back(data.move);
  11676. if (IncrementCounters(data.size))
  11677. return true;
  11678. break;
  11679. }
  11680. }
  11681. }
  11682. return false;
  11683. }
  11684. bool VmaDefragmentationContext_T::ComputeDefragmentation_Fast(VmaBlockVector& vector)
  11685. {
  11686. // Move only between blocks
  11687. // Go through allocations in last blocks and try to fit them inside first ones
  11688. for (size_t i = vector.GetBlockCount() - 1; i > m_ImmovableBlockCount; --i)
  11689. {
  11690. VmaBlockMetadata* metadata = vector.GetBlock(i)->m_pMetadata;
  11691. for (VmaAllocHandle handle = metadata->GetAllocationListBegin();
  11692. handle != VK_NULL_HANDLE;
  11693. handle = metadata->GetNextAllocation(handle))
  11694. {
  11695. MoveAllocationData moveData = GetMoveData(handle, metadata);
  11696. // Ignore newly created allocations by defragmentation algorithm
  11697. if (moveData.move.srcAllocation->GetUserData() == this)
  11698. continue;
  11699. switch (CheckCounters(moveData.move.srcAllocation->GetSize()))
  11700. {
  11701. case CounterStatus::Ignore:
  11702. continue;
  11703. case CounterStatus::End:
  11704. return true;
  11705. default:
  11706. VMA_ASSERT(0);
  11707. case CounterStatus::Pass:
  11708. break;
  11709. }
  11710. // Check all previous blocks for free space
  11711. if (AllocInOtherBlock(0, i, moveData, vector))
  11712. return true;
  11713. }
  11714. }
  11715. return false;
  11716. }
  11717. bool VmaDefragmentationContext_T::ComputeDefragmentation_Balanced(VmaBlockVector& vector, size_t index, bool update)
  11718. {
  11719. // Go over every allocation and try to fit it in previous blocks at lowest offsets,
  11720. // if not possible: realloc within single block to minimize offset (exclude offset == 0),
  11721. // but only if there are noticable gaps between them (some heuristic, ex. average size of allocation in block)
  11722. VMA_ASSERT(m_AlgorithmState != VMA_NULL);
  11723. StateBalanced& vectorState = reinterpret_cast<StateBalanced*>(m_AlgorithmState)[index];
  11724. if (update && vectorState.avgAllocSize == UINT64_MAX)
  11725. UpdateVectorStatistics(vector, vectorState);
  11726. const size_t startMoveCount = m_Moves.size();
  11727. VkDeviceSize minimalFreeRegion = vectorState.avgFreeSize / 2;
  11728. for (size_t i = vector.GetBlockCount() - 1; i > m_ImmovableBlockCount; --i)
  11729. {
  11730. VmaDeviceMemoryBlock* block = vector.GetBlock(i);
  11731. VmaBlockMetadata* metadata = block->m_pMetadata;
  11732. VkDeviceSize prevFreeRegionSize = 0;
  11733. for (VmaAllocHandle handle = metadata->GetAllocationListBegin();
  11734. handle != VK_NULL_HANDLE;
  11735. handle = metadata->GetNextAllocation(handle))
  11736. {
  11737. MoveAllocationData moveData = GetMoveData(handle, metadata);
  11738. // Ignore newly created allocations by defragmentation algorithm
  11739. if (moveData.move.srcAllocation->GetUserData() == this)
  11740. continue;
  11741. switch (CheckCounters(moveData.move.srcAllocation->GetSize()))
  11742. {
  11743. case CounterStatus::Ignore:
  11744. continue;
  11745. case CounterStatus::End:
  11746. return true;
  11747. default:
  11748. VMA_ASSERT(0);
  11749. case CounterStatus::Pass:
  11750. break;
  11751. }
  11752. // Check all previous blocks for free space
  11753. const size_t prevMoveCount = m_Moves.size();
  11754. if (AllocInOtherBlock(0, i, moveData, vector))
  11755. return true;
  11756. VkDeviceSize nextFreeRegionSize = metadata->GetNextFreeRegionSize(handle);
  11757. // If no room found then realloc within block for lower offset
  11758. VkDeviceSize offset = moveData.move.srcAllocation->GetOffset();
  11759. if (prevMoveCount == m_Moves.size() && offset != 0 && metadata->GetSumFreeSize() >= moveData.size)
  11760. {
  11761. // Check if realloc will make sense
  11762. if (prevFreeRegionSize >= minimalFreeRegion ||
  11763. nextFreeRegionSize >= minimalFreeRegion ||
  11764. moveData.size <= vectorState.avgFreeSize ||
  11765. moveData.size <= vectorState.avgAllocSize)
  11766. {
  11767. VmaAllocationRequest request = {};
  11768. if (metadata->CreateAllocationRequest(
  11769. moveData.size,
  11770. moveData.alignment,
  11771. false,
  11772. moveData.type,
  11773. VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT,
  11774. &request))
  11775. {
  11776. if (metadata->GetAllocationOffset(request.allocHandle) < offset)
  11777. {
  11778. if (vector.CommitAllocationRequest(
  11779. request,
  11780. block,
  11781. moveData.alignment,
  11782. moveData.flags,
  11783. this,
  11784. moveData.type,
  11785. &moveData.move.dstTmpAllocation) == VK_SUCCESS)
  11786. {
  11787. m_Moves.push_back(moveData.move);
  11788. if (IncrementCounters(moveData.size))
  11789. return true;
  11790. }
  11791. }
  11792. }
  11793. }
  11794. }
  11795. prevFreeRegionSize = nextFreeRegionSize;
  11796. }
  11797. }
  11798. // No moves perfomed, update statistics to current vector state
  11799. if (startMoveCount == m_Moves.size() && !update)
  11800. {
  11801. vectorState.avgAllocSize = UINT64_MAX;
  11802. return ComputeDefragmentation_Balanced(vector, index, false);
  11803. }
  11804. return false;
  11805. }
  11806. bool VmaDefragmentationContext_T::ComputeDefragmentation_Full(VmaBlockVector& vector)
  11807. {
  11808. // Go over every allocation and try to fit it in previous blocks at lowest offsets,
  11809. // if not possible: realloc within single block to minimize offset (exclude offset == 0)
  11810. for (size_t i = vector.GetBlockCount() - 1; i > m_ImmovableBlockCount; --i)
  11811. {
  11812. VmaDeviceMemoryBlock* block = vector.GetBlock(i);
  11813. VmaBlockMetadata* metadata = block->m_pMetadata;
  11814. for (VmaAllocHandle handle = metadata->GetAllocationListBegin();
  11815. handle != VK_NULL_HANDLE;
  11816. handle = metadata->GetNextAllocation(handle))
  11817. {
  11818. MoveAllocationData moveData = GetMoveData(handle, metadata);
  11819. // Ignore newly created allocations by defragmentation algorithm
  11820. if (moveData.move.srcAllocation->GetUserData() == this)
  11821. continue;
  11822. switch (CheckCounters(moveData.move.srcAllocation->GetSize()))
  11823. {
  11824. case CounterStatus::Ignore:
  11825. continue;
  11826. case CounterStatus::End:
  11827. return true;
  11828. default:
  11829. VMA_ASSERT(0);
  11830. case CounterStatus::Pass:
  11831. break;
  11832. }
  11833. // Check all previous blocks for free space
  11834. const size_t prevMoveCount = m_Moves.size();
  11835. if (AllocInOtherBlock(0, i, moveData, vector))
  11836. return true;
  11837. // If no room found then realloc within block for lower offset
  11838. VkDeviceSize offset = moveData.move.srcAllocation->GetOffset();
  11839. if (prevMoveCount == m_Moves.size() && offset != 0 && metadata->GetSumFreeSize() >= moveData.size)
  11840. {
  11841. VmaAllocationRequest request = {};
  11842. if (metadata->CreateAllocationRequest(
  11843. moveData.size,
  11844. moveData.alignment,
  11845. false,
  11846. moveData.type,
  11847. VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT,
  11848. &request))
  11849. {
  11850. if (metadata->GetAllocationOffset(request.allocHandle) < offset)
  11851. {
  11852. if (vector.CommitAllocationRequest(
  11853. request,
  11854. block,
  11855. moveData.alignment,
  11856. moveData.flags,
  11857. this,
  11858. moveData.type,
  11859. &moveData.move.dstTmpAllocation) == VK_SUCCESS)
  11860. {
  11861. m_Moves.push_back(moveData.move);
  11862. if (IncrementCounters(moveData.size))
  11863. return true;
  11864. }
  11865. }
  11866. }
  11867. }
  11868. }
  11869. }
  11870. return false;
  11871. }
  11872. bool VmaDefragmentationContext_T::ComputeDefragmentation_Extensive(VmaBlockVector& vector, size_t index)
  11873. {
  11874. // First free single block, then populate it to the brim, then free another block, and so on
  11875. // Fallback to previous algorithm since without granularity conflicts it can achieve max packing
  11876. if (vector.m_BufferImageGranularity == 1)
  11877. return ComputeDefragmentation_Full(vector);
  11878. VMA_ASSERT(m_AlgorithmState != VMA_NULL);
  11879. StateExtensive& vectorState = reinterpret_cast<StateExtensive*>(m_AlgorithmState)[index];
  11880. bool texturePresent = false, bufferPresent = false, otherPresent = false;
  11881. switch (vectorState.operation)
  11882. {
  11883. case StateExtensive::Operation::Done: // Vector defragmented
  11884. return false;
  11885. case StateExtensive::Operation::FindFreeBlockBuffer:
  11886. case StateExtensive::Operation::FindFreeBlockTexture:
  11887. case StateExtensive::Operation::FindFreeBlockAll:
  11888. {
  11889. // No more blocks to free, just perform fast realloc and move to cleanup
  11890. if (vectorState.firstFreeBlock == 0)
  11891. {
  11892. vectorState.operation = StateExtensive::Operation::Cleanup;
  11893. return ComputeDefragmentation_Fast(vector);
  11894. }
  11895. // No free blocks, have to clear last one
  11896. size_t last = (vectorState.firstFreeBlock == SIZE_MAX ? vector.GetBlockCount() : vectorState.firstFreeBlock) - 1;
  11897. VmaBlockMetadata* freeMetadata = vector.GetBlock(last)->m_pMetadata;
  11898. const size_t prevMoveCount = m_Moves.size();
  11899. for (VmaAllocHandle handle = freeMetadata->GetAllocationListBegin();
  11900. handle != VK_NULL_HANDLE;
  11901. handle = freeMetadata->GetNextAllocation(handle))
  11902. {
  11903. MoveAllocationData moveData = GetMoveData(handle, freeMetadata);
  11904. switch (CheckCounters(moveData.move.srcAllocation->GetSize()))
  11905. {
  11906. case CounterStatus::Ignore:
  11907. continue;
  11908. case CounterStatus::End:
  11909. return true;
  11910. default:
  11911. VMA_ASSERT(0);
  11912. case CounterStatus::Pass:
  11913. break;
  11914. }
  11915. // Check all previous blocks for free space
  11916. if (AllocInOtherBlock(0, last, moveData, vector))
  11917. {
  11918. // Full clear performed already
  11919. if (prevMoveCount != m_Moves.size() && freeMetadata->GetNextAllocation(handle) == VK_NULL_HANDLE)
  11920. reinterpret_cast<size_t*>(m_AlgorithmState)[index] = last;
  11921. return true;
  11922. }
  11923. }
  11924. if (prevMoveCount == m_Moves.size())
  11925. {
  11926. // Cannot perform full clear, have to move data in other blocks around
  11927. if (last != 0)
  11928. {
  11929. for (size_t i = last - 1; i; --i)
  11930. {
  11931. if (ReallocWithinBlock(vector, vector.GetBlock(i)))
  11932. return true;
  11933. }
  11934. }
  11935. if (prevMoveCount == m_Moves.size())
  11936. {
  11937. // No possible reallocs within blocks, try to move them around fast
  11938. return ComputeDefragmentation_Fast(vector);
  11939. }
  11940. }
  11941. else
  11942. {
  11943. switch (vectorState.operation)
  11944. {
  11945. case StateExtensive::Operation::FindFreeBlockBuffer:
  11946. vectorState.operation = StateExtensive::Operation::MoveBuffers;
  11947. break;
  11948. default:
  11949. VMA_ASSERT(0);
  11950. case StateExtensive::Operation::FindFreeBlockTexture:
  11951. vectorState.operation = StateExtensive::Operation::MoveTextures;
  11952. break;
  11953. case StateExtensive::Operation::FindFreeBlockAll:
  11954. vectorState.operation = StateExtensive::Operation::MoveAll;
  11955. break;
  11956. }
  11957. vectorState.firstFreeBlock = last;
  11958. // Nothing done, block found without reallocations, can perform another reallocs in same pass
  11959. return ComputeDefragmentation_Extensive(vector, index);
  11960. }
  11961. break;
  11962. }
  11963. case StateExtensive::Operation::MoveTextures:
  11964. {
  11965. if (MoveDataToFreeBlocks(VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL, vector,
  11966. vectorState.firstFreeBlock, texturePresent, bufferPresent, otherPresent))
  11967. {
  11968. if (texturePresent)
  11969. {
  11970. vectorState.operation = StateExtensive::Operation::FindFreeBlockTexture;
  11971. return ComputeDefragmentation_Extensive(vector, index);
  11972. }
  11973. if (!bufferPresent && !otherPresent)
  11974. {
  11975. vectorState.operation = StateExtensive::Operation::Cleanup;
  11976. break;
  11977. }
  11978. // No more textures to move, check buffers
  11979. vectorState.operation = StateExtensive::Operation::MoveBuffers;
  11980. bufferPresent = false;
  11981. otherPresent = false;
  11982. }
  11983. else
  11984. break;
  11985. }
  11986. case StateExtensive::Operation::MoveBuffers:
  11987. {
  11988. if (MoveDataToFreeBlocks(VMA_SUBALLOCATION_TYPE_BUFFER, vector,
  11989. vectorState.firstFreeBlock, texturePresent, bufferPresent, otherPresent))
  11990. {
  11991. if (bufferPresent)
  11992. {
  11993. vectorState.operation = StateExtensive::Operation::FindFreeBlockBuffer;
  11994. return ComputeDefragmentation_Extensive(vector, index);
  11995. }
  11996. if (!otherPresent)
  11997. {
  11998. vectorState.operation = StateExtensive::Operation::Cleanup;
  11999. break;
  12000. }
  12001. // No more buffers to move, check all others
  12002. vectorState.operation = StateExtensive::Operation::MoveAll;
  12003. otherPresent = false;
  12004. }
  12005. else
  12006. break;
  12007. }
  12008. case StateExtensive::Operation::MoveAll:
  12009. {
  12010. if (MoveDataToFreeBlocks(VMA_SUBALLOCATION_TYPE_FREE, vector,
  12011. vectorState.firstFreeBlock, texturePresent, bufferPresent, otherPresent))
  12012. {
  12013. if (otherPresent)
  12014. {
  12015. vectorState.operation = StateExtensive::Operation::FindFreeBlockBuffer;
  12016. return ComputeDefragmentation_Extensive(vector, index);
  12017. }
  12018. // Everything moved
  12019. vectorState.operation = StateExtensive::Operation::Cleanup;
  12020. }
  12021. break;
  12022. }
  12023. case StateExtensive::Operation::Cleanup:
  12024. // Cleanup is handled below so that other operations may reuse the cleanup code. This case is here to prevent the unhandled enum value warning (C4062).
  12025. break;
  12026. }
  12027. if (vectorState.operation == StateExtensive::Operation::Cleanup)
  12028. {
  12029. // All other work done, pack data in blocks even tighter if possible
  12030. const size_t prevMoveCount = m_Moves.size();
  12031. for (size_t i = 0; i < vector.GetBlockCount(); ++i)
  12032. {
  12033. if (ReallocWithinBlock(vector, vector.GetBlock(i)))
  12034. return true;
  12035. }
  12036. if (prevMoveCount == m_Moves.size())
  12037. vectorState.operation = StateExtensive::Operation::Done;
  12038. }
  12039. return false;
  12040. }
  12041. void VmaDefragmentationContext_T::UpdateVectorStatistics(VmaBlockVector& vector, StateBalanced& state)
  12042. {
  12043. size_t allocCount = 0;
  12044. size_t freeCount = 0;
  12045. state.avgFreeSize = 0;
  12046. state.avgAllocSize = 0;
  12047. for (size_t i = 0; i < vector.GetBlockCount(); ++i)
  12048. {
  12049. VmaBlockMetadata* metadata = vector.GetBlock(i)->m_pMetadata;
  12050. allocCount += metadata->GetAllocationCount();
  12051. freeCount += metadata->GetFreeRegionsCount();
  12052. state.avgFreeSize += metadata->GetSumFreeSize();
  12053. state.avgAllocSize += metadata->GetSize();
  12054. }
  12055. state.avgAllocSize = (state.avgAllocSize - state.avgFreeSize) / allocCount;
  12056. state.avgFreeSize /= freeCount;
  12057. }
  12058. bool VmaDefragmentationContext_T::MoveDataToFreeBlocks(VmaSuballocationType currentType,
  12059. VmaBlockVector& vector, size_t firstFreeBlock,
  12060. bool& texturePresent, bool& bufferPresent, bool& otherPresent)
  12061. {
  12062. const size_t prevMoveCount = m_Moves.size();
  12063. for (size_t i = firstFreeBlock ; i;)
  12064. {
  12065. VmaDeviceMemoryBlock* block = vector.GetBlock(--i);
  12066. VmaBlockMetadata* metadata = block->m_pMetadata;
  12067. for (VmaAllocHandle handle = metadata->GetAllocationListBegin();
  12068. handle != VK_NULL_HANDLE;
  12069. handle = metadata->GetNextAllocation(handle))
  12070. {
  12071. MoveAllocationData moveData = GetMoveData(handle, metadata);
  12072. // Ignore newly created allocations by defragmentation algorithm
  12073. if (moveData.move.srcAllocation->GetUserData() == this)
  12074. continue;
  12075. switch (CheckCounters(moveData.move.srcAllocation->GetSize()))
  12076. {
  12077. case CounterStatus::Ignore:
  12078. continue;
  12079. case CounterStatus::End:
  12080. return true;
  12081. default:
  12082. VMA_ASSERT(0);
  12083. case CounterStatus::Pass:
  12084. break;
  12085. }
  12086. // Move only single type of resources at once
  12087. if (!VmaIsBufferImageGranularityConflict(moveData.type, currentType))
  12088. {
  12089. // Try to fit allocation into free blocks
  12090. if (AllocInOtherBlock(firstFreeBlock, vector.GetBlockCount(), moveData, vector))
  12091. return false;
  12092. }
  12093. if (!VmaIsBufferImageGranularityConflict(moveData.type, VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL))
  12094. texturePresent = true;
  12095. else if (!VmaIsBufferImageGranularityConflict(moveData.type, VMA_SUBALLOCATION_TYPE_BUFFER))
  12096. bufferPresent = true;
  12097. else
  12098. otherPresent = true;
  12099. }
  12100. }
  12101. return prevMoveCount == m_Moves.size();
  12102. }
  12103. #endif // _VMA_DEFRAGMENTATION_CONTEXT_FUNCTIONS
  12104. #ifndef _VMA_POOL_T_FUNCTIONS
  12105. VmaPool_T::VmaPool_T(
  12106. VmaAllocator hAllocator,
  12107. const VmaPoolCreateInfo& createInfo,
  12108. VkDeviceSize preferredBlockSize)
  12109. : m_BlockVector(
  12110. hAllocator,
  12111. this, // hParentPool
  12112. createInfo.memoryTypeIndex,
  12113. createInfo.blockSize != 0 ? createInfo.blockSize : preferredBlockSize,
  12114. createInfo.minBlockCount,
  12115. createInfo.maxBlockCount,
  12116. (createInfo.flags& VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT) != 0 ? 1 : hAllocator->GetBufferImageGranularity(),
  12117. createInfo.blockSize != 0, // explicitBlockSize
  12118. createInfo.flags & VMA_POOL_CREATE_ALGORITHM_MASK, // algorithm
  12119. createInfo.priority,
  12120. VMA_MAX(hAllocator->GetMemoryTypeMinAlignment(createInfo.memoryTypeIndex), createInfo.minAllocationAlignment),
  12121. createInfo.pMemoryAllocateNext),
  12122. m_Id(0),
  12123. m_Name(VMA_NULL) {}
  12124. VmaPool_T::~VmaPool_T()
  12125. {
  12126. VMA_ASSERT(m_PrevPool == VMA_NULL && m_NextPool == VMA_NULL);
  12127. }
  12128. void VmaPool_T::SetName(const char* pName)
  12129. {
  12130. const VkAllocationCallbacks* allocs = m_BlockVector.GetAllocator()->GetAllocationCallbacks();
  12131. VmaFreeString(allocs, m_Name);
  12132. if (pName != VMA_NULL)
  12133. {
  12134. m_Name = VmaCreateStringCopy(allocs, pName);
  12135. }
  12136. else
  12137. {
  12138. m_Name = VMA_NULL;
  12139. }
  12140. }
  12141. #endif // _VMA_POOL_T_FUNCTIONS
  12142. #ifndef _VMA_ALLOCATOR_T_FUNCTIONS
  12143. VmaAllocator_T::VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo) :
  12144. m_UseMutex((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT) == 0),
  12145. m_VulkanApiVersion(pCreateInfo->vulkanApiVersion != 0 ? pCreateInfo->vulkanApiVersion : VK_API_VERSION_1_0),
  12146. m_UseKhrDedicatedAllocation((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0),
  12147. m_UseKhrBindMemory2((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT) != 0),
  12148. m_UseExtMemoryBudget((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT) != 0),
  12149. m_UseAmdDeviceCoherentMemory((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT) != 0),
  12150. m_UseKhrBufferDeviceAddress((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT) != 0),
  12151. m_UseExtMemoryPriority((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT) != 0),
  12152. m_hDevice(pCreateInfo->device),
  12153. m_hInstance(pCreateInfo->instance),
  12154. m_AllocationCallbacksSpecified(pCreateInfo->pAllocationCallbacks != VMA_NULL),
  12155. m_AllocationCallbacks(pCreateInfo->pAllocationCallbacks ?
  12156. *pCreateInfo->pAllocationCallbacks : VmaEmptyAllocationCallbacks),
  12157. m_AllocationObjectAllocator(&m_AllocationCallbacks),
  12158. m_HeapSizeLimitMask(0),
  12159. m_DeviceMemoryCount(0),
  12160. m_PreferredLargeHeapBlockSize(0),
  12161. m_PhysicalDevice(pCreateInfo->physicalDevice),
  12162. m_GpuDefragmentationMemoryTypeBits(UINT32_MAX),
  12163. m_NextPoolId(0),
  12164. m_GlobalMemoryTypeBits(UINT32_MAX)
  12165. {
  12166. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12167. {
  12168. m_UseKhrDedicatedAllocation = false;
  12169. m_UseKhrBindMemory2 = false;
  12170. }
  12171. if(VMA_DEBUG_DETECT_CORRUPTION)
  12172. {
  12173. // Needs to be multiply of uint32_t size because we are going to write VMA_CORRUPTION_DETECTION_MAGIC_VALUE to it.
  12174. VMA_ASSERT(VMA_DEBUG_MARGIN % sizeof(uint32_t) == 0);
  12175. }
  12176. VMA_ASSERT(pCreateInfo->physicalDevice && pCreateInfo->device && pCreateInfo->instance);
  12177. if(m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0))
  12178. {
  12179. #if !(VMA_DEDICATED_ALLOCATION)
  12180. if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0)
  12181. {
  12182. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT set but required extensions are disabled by preprocessor macros.");
  12183. }
  12184. #endif
  12185. #if !(VMA_BIND_MEMORY2)
  12186. if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT) != 0)
  12187. {
  12188. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT set but required extension is disabled by preprocessor macros.");
  12189. }
  12190. #endif
  12191. }
  12192. #if !(VMA_MEMORY_BUDGET)
  12193. if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT) != 0)
  12194. {
  12195. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT set but required extension is disabled by preprocessor macros.");
  12196. }
  12197. #endif
  12198. #if !(VMA_BUFFER_DEVICE_ADDRESS)
  12199. if(m_UseKhrBufferDeviceAddress)
  12200. {
  12201. 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.");
  12202. }
  12203. #endif
  12204. #if VMA_VULKAN_VERSION < 1002000
  12205. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 2, 0))
  12206. {
  12207. VMA_ASSERT(0 && "vulkanApiVersion >= VK_API_VERSION_1_2 but required Vulkan version is disabled by preprocessor macros.");
  12208. }
  12209. #endif
  12210. #if VMA_VULKAN_VERSION < 1001000
  12211. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12212. {
  12213. VMA_ASSERT(0 && "vulkanApiVersion >= VK_API_VERSION_1_1 but required Vulkan version is disabled by preprocessor macros.");
  12214. }
  12215. #endif
  12216. #if !(VMA_MEMORY_PRIORITY)
  12217. if(m_UseExtMemoryPriority)
  12218. {
  12219. 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.");
  12220. }
  12221. #endif
  12222. memset(&m_DeviceMemoryCallbacks, 0 ,sizeof(m_DeviceMemoryCallbacks));
  12223. memset(&m_PhysicalDeviceProperties, 0, sizeof(m_PhysicalDeviceProperties));
  12224. memset(&m_MemProps, 0, sizeof(m_MemProps));
  12225. memset(&m_pBlockVectors, 0, sizeof(m_pBlockVectors));
  12226. memset(&m_VulkanFunctions, 0, sizeof(m_VulkanFunctions));
  12227. #if VMA_EXTERNAL_MEMORY
  12228. memset(&m_TypeExternalMemoryHandleTypes, 0, sizeof(m_TypeExternalMemoryHandleTypes));
  12229. #endif // #if VMA_EXTERNAL_MEMORY
  12230. if(pCreateInfo->pDeviceMemoryCallbacks != VMA_NULL)
  12231. {
  12232. m_DeviceMemoryCallbacks.pUserData = pCreateInfo->pDeviceMemoryCallbacks->pUserData;
  12233. m_DeviceMemoryCallbacks.pfnAllocate = pCreateInfo->pDeviceMemoryCallbacks->pfnAllocate;
  12234. m_DeviceMemoryCallbacks.pfnFree = pCreateInfo->pDeviceMemoryCallbacks->pfnFree;
  12235. }
  12236. ImportVulkanFunctions(pCreateInfo->pVulkanFunctions);
  12237. (*m_VulkanFunctions.vkGetPhysicalDeviceProperties)(m_PhysicalDevice, &m_PhysicalDeviceProperties);
  12238. (*m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties)(m_PhysicalDevice, &m_MemProps);
  12239. VMA_ASSERT(VmaIsPow2(VMA_MIN_ALIGNMENT));
  12240. VMA_ASSERT(VmaIsPow2(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY));
  12241. VMA_ASSERT(VmaIsPow2(m_PhysicalDeviceProperties.limits.bufferImageGranularity));
  12242. VMA_ASSERT(VmaIsPow2(m_PhysicalDeviceProperties.limits.nonCoherentAtomSize));
  12243. m_PreferredLargeHeapBlockSize = (pCreateInfo->preferredLargeHeapBlockSize != 0) ?
  12244. pCreateInfo->preferredLargeHeapBlockSize : static_cast<VkDeviceSize>(VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE);
  12245. m_GlobalMemoryTypeBits = CalculateGlobalMemoryTypeBits();
  12246. #if VMA_EXTERNAL_MEMORY
  12247. if(pCreateInfo->pTypeExternalMemoryHandleTypes != VMA_NULL)
  12248. {
  12249. memcpy(m_TypeExternalMemoryHandleTypes, pCreateInfo->pTypeExternalMemoryHandleTypes,
  12250. sizeof(VkExternalMemoryHandleTypeFlagsKHR) * GetMemoryTypeCount());
  12251. }
  12252. #endif // #if VMA_EXTERNAL_MEMORY
  12253. if(pCreateInfo->pHeapSizeLimit != VMA_NULL)
  12254. {
  12255. for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex)
  12256. {
  12257. const VkDeviceSize limit = pCreateInfo->pHeapSizeLimit[heapIndex];
  12258. if(limit != VK_WHOLE_SIZE)
  12259. {
  12260. m_HeapSizeLimitMask |= 1u << heapIndex;
  12261. if(limit < m_MemProps.memoryHeaps[heapIndex].size)
  12262. {
  12263. m_MemProps.memoryHeaps[heapIndex].size = limit;
  12264. }
  12265. }
  12266. }
  12267. }
  12268. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  12269. {
  12270. // Create only supported types
  12271. if((m_GlobalMemoryTypeBits & (1u << memTypeIndex)) != 0)
  12272. {
  12273. const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(memTypeIndex);
  12274. m_pBlockVectors[memTypeIndex] = vma_new(this, VmaBlockVector)(
  12275. this,
  12276. VK_NULL_HANDLE, // hParentPool
  12277. memTypeIndex,
  12278. preferredBlockSize,
  12279. 0,
  12280. SIZE_MAX,
  12281. GetBufferImageGranularity(),
  12282. false, // explicitBlockSize
  12283. 0, // algorithm
  12284. 0.5f, // priority (0.5 is the default per Vulkan spec)
  12285. GetMemoryTypeMinAlignment(memTypeIndex), // minAllocationAlignment
  12286. VMA_NULL); // // pMemoryAllocateNext
  12287. // No need to call m_pBlockVectors[memTypeIndex][blockVectorTypeIndex]->CreateMinBlocks here,
  12288. // becase minBlockCount is 0.
  12289. }
  12290. }
  12291. }
  12292. VkResult VmaAllocator_T::Init(const VmaAllocatorCreateInfo* pCreateInfo)
  12293. {
  12294. VkResult res = VK_SUCCESS;
  12295. #if VMA_MEMORY_BUDGET
  12296. if(m_UseExtMemoryBudget)
  12297. {
  12298. UpdateVulkanBudget();
  12299. }
  12300. #endif // #if VMA_MEMORY_BUDGET
  12301. return res;
  12302. }
  12303. VmaAllocator_T::~VmaAllocator_T()
  12304. {
  12305. VMA_ASSERT(m_Pools.IsEmpty());
  12306. for(size_t memTypeIndex = GetMemoryTypeCount(); memTypeIndex--; )
  12307. {
  12308. vma_delete(this, m_pBlockVectors[memTypeIndex]);
  12309. }
  12310. }
  12311. void VmaAllocator_T::ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions)
  12312. {
  12313. #if VMA_STATIC_VULKAN_FUNCTIONS == 1
  12314. ImportVulkanFunctions_Static();
  12315. #endif
  12316. if(pVulkanFunctions != VMA_NULL)
  12317. {
  12318. ImportVulkanFunctions_Custom(pVulkanFunctions);
  12319. }
  12320. #if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1
  12321. ImportVulkanFunctions_Dynamic();
  12322. #endif
  12323. ValidateVulkanFunctions();
  12324. }
  12325. #if VMA_STATIC_VULKAN_FUNCTIONS == 1
  12326. void VmaAllocator_T::ImportVulkanFunctions_Static()
  12327. {
  12328. // Vulkan 1.0
  12329. m_VulkanFunctions.vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)vkGetInstanceProcAddr;
  12330. m_VulkanFunctions.vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr)vkGetDeviceProcAddr;
  12331. m_VulkanFunctions.vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)vkGetPhysicalDeviceProperties;
  12332. m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)vkGetPhysicalDeviceMemoryProperties;
  12333. m_VulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkAllocateMemory;
  12334. m_VulkanFunctions.vkFreeMemory = (PFN_vkFreeMemory)vkFreeMemory;
  12335. m_VulkanFunctions.vkMapMemory = (PFN_vkMapMemory)vkMapMemory;
  12336. m_VulkanFunctions.vkUnmapMemory = (PFN_vkUnmapMemory)vkUnmapMemory;
  12337. m_VulkanFunctions.vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)vkFlushMappedMemoryRanges;
  12338. m_VulkanFunctions.vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)vkInvalidateMappedMemoryRanges;
  12339. m_VulkanFunctions.vkBindBufferMemory = (PFN_vkBindBufferMemory)vkBindBufferMemory;
  12340. m_VulkanFunctions.vkBindImageMemory = (PFN_vkBindImageMemory)vkBindImageMemory;
  12341. m_VulkanFunctions.vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)vkGetBufferMemoryRequirements;
  12342. m_VulkanFunctions.vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)vkGetImageMemoryRequirements;
  12343. m_VulkanFunctions.vkCreateBuffer = (PFN_vkCreateBuffer)vkCreateBuffer;
  12344. m_VulkanFunctions.vkDestroyBuffer = (PFN_vkDestroyBuffer)vkDestroyBuffer;
  12345. m_VulkanFunctions.vkCreateImage = (PFN_vkCreateImage)vkCreateImage;
  12346. m_VulkanFunctions.vkDestroyImage = (PFN_vkDestroyImage)vkDestroyImage;
  12347. m_VulkanFunctions.vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)vkCmdCopyBuffer;
  12348. // Vulkan 1.1
  12349. #if VMA_VULKAN_VERSION >= 1001000
  12350. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12351. {
  12352. m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR = (PFN_vkGetBufferMemoryRequirements2)vkGetBufferMemoryRequirements2;
  12353. m_VulkanFunctions.vkGetImageMemoryRequirements2KHR = (PFN_vkGetImageMemoryRequirements2)vkGetImageMemoryRequirements2;
  12354. m_VulkanFunctions.vkBindBufferMemory2KHR = (PFN_vkBindBufferMemory2)vkBindBufferMemory2;
  12355. m_VulkanFunctions.vkBindImageMemory2KHR = (PFN_vkBindImageMemory2)vkBindImageMemory2;
  12356. m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR = (PFN_vkGetPhysicalDeviceMemoryProperties2)vkGetPhysicalDeviceMemoryProperties2;
  12357. }
  12358. #endif
  12359. #if VMA_VULKAN_VERSION >= 1003000
  12360. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 3, 0))
  12361. {
  12362. m_VulkanFunctions.vkGetDeviceBufferMemoryRequirements = (PFN_vkGetDeviceBufferMemoryRequirements)vkGetDeviceBufferMemoryRequirements;
  12363. m_VulkanFunctions.vkGetDeviceImageMemoryRequirements = (PFN_vkGetDeviceImageMemoryRequirements)vkGetDeviceImageMemoryRequirements;
  12364. }
  12365. #endif
  12366. }
  12367. #endif // VMA_STATIC_VULKAN_FUNCTIONS == 1
  12368. void VmaAllocator_T::ImportVulkanFunctions_Custom(const VmaVulkanFunctions* pVulkanFunctions)
  12369. {
  12370. VMA_ASSERT(pVulkanFunctions != VMA_NULL);
  12371. #define VMA_COPY_IF_NOT_NULL(funcName) \
  12372. if(pVulkanFunctions->funcName != VMA_NULL) m_VulkanFunctions.funcName = pVulkanFunctions->funcName;
  12373. VMA_COPY_IF_NOT_NULL(vkGetInstanceProcAddr);
  12374. VMA_COPY_IF_NOT_NULL(vkGetDeviceProcAddr);
  12375. VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceProperties);
  12376. VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties);
  12377. VMA_COPY_IF_NOT_NULL(vkAllocateMemory);
  12378. VMA_COPY_IF_NOT_NULL(vkFreeMemory);
  12379. VMA_COPY_IF_NOT_NULL(vkMapMemory);
  12380. VMA_COPY_IF_NOT_NULL(vkUnmapMemory);
  12381. VMA_COPY_IF_NOT_NULL(vkFlushMappedMemoryRanges);
  12382. VMA_COPY_IF_NOT_NULL(vkInvalidateMappedMemoryRanges);
  12383. VMA_COPY_IF_NOT_NULL(vkBindBufferMemory);
  12384. VMA_COPY_IF_NOT_NULL(vkBindImageMemory);
  12385. VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements);
  12386. VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements);
  12387. VMA_COPY_IF_NOT_NULL(vkCreateBuffer);
  12388. VMA_COPY_IF_NOT_NULL(vkDestroyBuffer);
  12389. VMA_COPY_IF_NOT_NULL(vkCreateImage);
  12390. VMA_COPY_IF_NOT_NULL(vkDestroyImage);
  12391. VMA_COPY_IF_NOT_NULL(vkCmdCopyBuffer);
  12392. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12393. VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements2KHR);
  12394. VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements2KHR);
  12395. #endif
  12396. #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000
  12397. VMA_COPY_IF_NOT_NULL(vkBindBufferMemory2KHR);
  12398. VMA_COPY_IF_NOT_NULL(vkBindImageMemory2KHR);
  12399. #endif
  12400. #if VMA_MEMORY_BUDGET
  12401. VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties2KHR);
  12402. #endif
  12403. #if VMA_VULKAN_VERSION >= 1003000
  12404. VMA_COPY_IF_NOT_NULL(vkGetDeviceBufferMemoryRequirements);
  12405. VMA_COPY_IF_NOT_NULL(vkGetDeviceImageMemoryRequirements);
  12406. #endif
  12407. #undef VMA_COPY_IF_NOT_NULL
  12408. }
  12409. #if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1
  12410. void VmaAllocator_T::ImportVulkanFunctions_Dynamic()
  12411. {
  12412. VMA_ASSERT(m_VulkanFunctions.vkGetInstanceProcAddr && m_VulkanFunctions.vkGetDeviceProcAddr &&
  12413. "To use VMA_DYNAMIC_VULKAN_FUNCTIONS in new versions of VMA you now have to pass "
  12414. "VmaVulkanFunctions::vkGetInstanceProcAddr and vkGetDeviceProcAddr as VmaAllocatorCreateInfo::pVulkanFunctions. "
  12415. "Other members can be null.");
  12416. #define VMA_FETCH_INSTANCE_FUNC(memberName, functionPointerType, functionNameString) \
  12417. if(m_VulkanFunctions.memberName == VMA_NULL) \
  12418. m_VulkanFunctions.memberName = \
  12419. (functionPointerType)m_VulkanFunctions.vkGetInstanceProcAddr(m_hInstance, functionNameString);
  12420. #define VMA_FETCH_DEVICE_FUNC(memberName, functionPointerType, functionNameString) \
  12421. if(m_VulkanFunctions.memberName == VMA_NULL) \
  12422. m_VulkanFunctions.memberName = \
  12423. (functionPointerType)m_VulkanFunctions.vkGetDeviceProcAddr(m_hDevice, functionNameString);
  12424. VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceProperties, PFN_vkGetPhysicalDeviceProperties, "vkGetPhysicalDeviceProperties");
  12425. VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties, PFN_vkGetPhysicalDeviceMemoryProperties, "vkGetPhysicalDeviceMemoryProperties");
  12426. VMA_FETCH_DEVICE_FUNC(vkAllocateMemory, PFN_vkAllocateMemory, "vkAllocateMemory");
  12427. VMA_FETCH_DEVICE_FUNC(vkFreeMemory, PFN_vkFreeMemory, "vkFreeMemory");
  12428. VMA_FETCH_DEVICE_FUNC(vkMapMemory, PFN_vkMapMemory, "vkMapMemory");
  12429. VMA_FETCH_DEVICE_FUNC(vkUnmapMemory, PFN_vkUnmapMemory, "vkUnmapMemory");
  12430. VMA_FETCH_DEVICE_FUNC(vkFlushMappedMemoryRanges, PFN_vkFlushMappedMemoryRanges, "vkFlushMappedMemoryRanges");
  12431. VMA_FETCH_DEVICE_FUNC(vkInvalidateMappedMemoryRanges, PFN_vkInvalidateMappedMemoryRanges, "vkInvalidateMappedMemoryRanges");
  12432. VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory, PFN_vkBindBufferMemory, "vkBindBufferMemory");
  12433. VMA_FETCH_DEVICE_FUNC(vkBindImageMemory, PFN_vkBindImageMemory, "vkBindImageMemory");
  12434. VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements, PFN_vkGetBufferMemoryRequirements, "vkGetBufferMemoryRequirements");
  12435. VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements, PFN_vkGetImageMemoryRequirements, "vkGetImageMemoryRequirements");
  12436. VMA_FETCH_DEVICE_FUNC(vkCreateBuffer, PFN_vkCreateBuffer, "vkCreateBuffer");
  12437. VMA_FETCH_DEVICE_FUNC(vkDestroyBuffer, PFN_vkDestroyBuffer, "vkDestroyBuffer");
  12438. VMA_FETCH_DEVICE_FUNC(vkCreateImage, PFN_vkCreateImage, "vkCreateImage");
  12439. VMA_FETCH_DEVICE_FUNC(vkDestroyImage, PFN_vkDestroyImage, "vkDestroyImage");
  12440. VMA_FETCH_DEVICE_FUNC(vkCmdCopyBuffer, PFN_vkCmdCopyBuffer, "vkCmdCopyBuffer");
  12441. #if VMA_VULKAN_VERSION >= 1001000
  12442. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12443. {
  12444. VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements2KHR, PFN_vkGetBufferMemoryRequirements2, "vkGetBufferMemoryRequirements2");
  12445. VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements2KHR, PFN_vkGetImageMemoryRequirements2, "vkGetImageMemoryRequirements2");
  12446. VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory2KHR, PFN_vkBindBufferMemory2, "vkBindBufferMemory2");
  12447. VMA_FETCH_DEVICE_FUNC(vkBindImageMemory2KHR, PFN_vkBindImageMemory2, "vkBindImageMemory2");
  12448. VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties2KHR, PFN_vkGetPhysicalDeviceMemoryProperties2, "vkGetPhysicalDeviceMemoryProperties2");
  12449. }
  12450. #endif
  12451. #if VMA_DEDICATED_ALLOCATION
  12452. if(m_UseKhrDedicatedAllocation)
  12453. {
  12454. VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements2KHR, PFN_vkGetBufferMemoryRequirements2KHR, "vkGetBufferMemoryRequirements2KHR");
  12455. VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements2KHR, PFN_vkGetImageMemoryRequirements2KHR, "vkGetImageMemoryRequirements2KHR");
  12456. }
  12457. #endif
  12458. #if VMA_BIND_MEMORY2
  12459. if(m_UseKhrBindMemory2)
  12460. {
  12461. VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory2KHR, PFN_vkBindBufferMemory2KHR, "vkBindBufferMemory2KHR");
  12462. VMA_FETCH_DEVICE_FUNC(vkBindImageMemory2KHR, PFN_vkBindImageMemory2KHR, "vkBindImageMemory2KHR");
  12463. }
  12464. #endif // #if VMA_BIND_MEMORY2
  12465. #if VMA_MEMORY_BUDGET
  12466. if(m_UseExtMemoryBudget)
  12467. {
  12468. VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties2KHR, PFN_vkGetPhysicalDeviceMemoryProperties2KHR, "vkGetPhysicalDeviceMemoryProperties2KHR");
  12469. }
  12470. #endif // #if VMA_MEMORY_BUDGET
  12471. #if VMA_VULKAN_VERSION >= 1003000
  12472. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 3, 0))
  12473. {
  12474. VMA_FETCH_DEVICE_FUNC(vkGetDeviceBufferMemoryRequirements, PFN_vkGetDeviceBufferMemoryRequirements, "vkGetDeviceBufferMemoryRequirements");
  12475. VMA_FETCH_DEVICE_FUNC(vkGetDeviceImageMemoryRequirements, PFN_vkGetDeviceImageMemoryRequirements, "vkGetDeviceImageMemoryRequirements");
  12476. }
  12477. #endif
  12478. #undef VMA_FETCH_DEVICE_FUNC
  12479. #undef VMA_FETCH_INSTANCE_FUNC
  12480. }
  12481. #endif // VMA_DYNAMIC_VULKAN_FUNCTIONS == 1
  12482. void VmaAllocator_T::ValidateVulkanFunctions()
  12483. {
  12484. VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceProperties != VMA_NULL);
  12485. VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties != VMA_NULL);
  12486. VMA_ASSERT(m_VulkanFunctions.vkAllocateMemory != VMA_NULL);
  12487. VMA_ASSERT(m_VulkanFunctions.vkFreeMemory != VMA_NULL);
  12488. VMA_ASSERT(m_VulkanFunctions.vkMapMemory != VMA_NULL);
  12489. VMA_ASSERT(m_VulkanFunctions.vkUnmapMemory != VMA_NULL);
  12490. VMA_ASSERT(m_VulkanFunctions.vkFlushMappedMemoryRanges != VMA_NULL);
  12491. VMA_ASSERT(m_VulkanFunctions.vkInvalidateMappedMemoryRanges != VMA_NULL);
  12492. VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory != VMA_NULL);
  12493. VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory != VMA_NULL);
  12494. VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements != VMA_NULL);
  12495. VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements != VMA_NULL);
  12496. VMA_ASSERT(m_VulkanFunctions.vkCreateBuffer != VMA_NULL);
  12497. VMA_ASSERT(m_VulkanFunctions.vkDestroyBuffer != VMA_NULL);
  12498. VMA_ASSERT(m_VulkanFunctions.vkCreateImage != VMA_NULL);
  12499. VMA_ASSERT(m_VulkanFunctions.vkDestroyImage != VMA_NULL);
  12500. VMA_ASSERT(m_VulkanFunctions.vkCmdCopyBuffer != VMA_NULL);
  12501. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12502. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0) || m_UseKhrDedicatedAllocation)
  12503. {
  12504. VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR != VMA_NULL);
  12505. VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements2KHR != VMA_NULL);
  12506. }
  12507. #endif
  12508. #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000
  12509. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0) || m_UseKhrBindMemory2)
  12510. {
  12511. VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory2KHR != VMA_NULL);
  12512. VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory2KHR != VMA_NULL);
  12513. }
  12514. #endif
  12515. #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000
  12516. if(m_UseExtMemoryBudget || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12517. {
  12518. VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR != VMA_NULL);
  12519. }
  12520. #endif
  12521. #if VMA_VULKAN_VERSION >= 1003000
  12522. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 3, 0))
  12523. {
  12524. VMA_ASSERT(m_VulkanFunctions.vkGetDeviceBufferMemoryRequirements != VMA_NULL);
  12525. VMA_ASSERT(m_VulkanFunctions.vkGetDeviceImageMemoryRequirements != VMA_NULL);
  12526. }
  12527. #endif
  12528. }
  12529. VkDeviceSize VmaAllocator_T::CalcPreferredBlockSize(uint32_t memTypeIndex)
  12530. {
  12531. const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex);
  12532. const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size;
  12533. const bool isSmallHeap = heapSize <= VMA_SMALL_HEAP_MAX_SIZE;
  12534. return VmaAlignUp(isSmallHeap ? (heapSize / 8) : m_PreferredLargeHeapBlockSize, (VkDeviceSize)32);
  12535. }
  12536. VkResult VmaAllocator_T::AllocateMemoryOfType(
  12537. VmaPool pool,
  12538. VkDeviceSize size,
  12539. VkDeviceSize alignment,
  12540. bool dedicatedPreferred,
  12541. VkBuffer dedicatedBuffer,
  12542. VkImage dedicatedImage,
  12543. VkFlags dedicatedBufferImageUsage,
  12544. const VmaAllocationCreateInfo& createInfo,
  12545. uint32_t memTypeIndex,
  12546. VmaSuballocationType suballocType,
  12547. VmaDedicatedAllocationList& dedicatedAllocations,
  12548. VmaBlockVector& blockVector,
  12549. size_t allocationCount,
  12550. VmaAllocation* pAllocations)
  12551. {
  12552. VMA_ASSERT(pAllocations != VMA_NULL);
  12553. VMA_DEBUG_LOG(" AllocateMemory: MemoryTypeIndex=%u, AllocationCount=%zu, Size=%llu", memTypeIndex, allocationCount, size);
  12554. VmaAllocationCreateInfo finalCreateInfo = createInfo;
  12555. VkResult res = CalcMemTypeParams(
  12556. finalCreateInfo,
  12557. memTypeIndex,
  12558. size,
  12559. allocationCount);
  12560. if(res != VK_SUCCESS)
  12561. return res;
  12562. if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0)
  12563. {
  12564. return AllocateDedicatedMemory(
  12565. pool,
  12566. size,
  12567. suballocType,
  12568. dedicatedAllocations,
  12569. memTypeIndex,
  12570. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0,
  12571. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0,
  12572. (finalCreateInfo.flags &
  12573. (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0,
  12574. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT) != 0,
  12575. finalCreateInfo.pUserData,
  12576. finalCreateInfo.priority,
  12577. dedicatedBuffer,
  12578. dedicatedImage,
  12579. dedicatedBufferImageUsage,
  12580. allocationCount,
  12581. pAllocations,
  12582. blockVector.GetAllocationNextPtr());
  12583. }
  12584. else
  12585. {
  12586. const bool canAllocateDedicated =
  12587. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0 &&
  12588. (pool == VK_NULL_HANDLE || !blockVector.HasExplicitBlockSize());
  12589. if(canAllocateDedicated)
  12590. {
  12591. // Heuristics: Allocate dedicated memory if requested size if greater than half of preferred block size.
  12592. if(size > blockVector.GetPreferredBlockSize() / 2)
  12593. {
  12594. dedicatedPreferred = true;
  12595. }
  12596. // Protection against creating each allocation as dedicated when we reach or exceed heap size/budget,
  12597. // which can quickly deplete maxMemoryAllocationCount: Don't prefer dedicated allocations when above
  12598. // 3/4 of the maximum allocation count.
  12599. if(m_DeviceMemoryCount.load() > m_PhysicalDeviceProperties.limits.maxMemoryAllocationCount * 3 / 4)
  12600. {
  12601. dedicatedPreferred = false;
  12602. }
  12603. if(dedicatedPreferred)
  12604. {
  12605. res = AllocateDedicatedMemory(
  12606. pool,
  12607. size,
  12608. suballocType,
  12609. dedicatedAllocations,
  12610. memTypeIndex,
  12611. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0,
  12612. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0,
  12613. (finalCreateInfo.flags &
  12614. (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0,
  12615. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT) != 0,
  12616. finalCreateInfo.pUserData,
  12617. finalCreateInfo.priority,
  12618. dedicatedBuffer,
  12619. dedicatedImage,
  12620. dedicatedBufferImageUsage,
  12621. allocationCount,
  12622. pAllocations,
  12623. blockVector.GetAllocationNextPtr());
  12624. if(res == VK_SUCCESS)
  12625. {
  12626. // Succeeded: AllocateDedicatedMemory function already filld pMemory, nothing more to do here.
  12627. VMA_DEBUG_LOG(" Allocated as DedicatedMemory");
  12628. return VK_SUCCESS;
  12629. }
  12630. }
  12631. }
  12632. res = blockVector.Allocate(
  12633. size,
  12634. alignment,
  12635. finalCreateInfo,
  12636. suballocType,
  12637. allocationCount,
  12638. pAllocations);
  12639. if(res == VK_SUCCESS)
  12640. return VK_SUCCESS;
  12641. // Try dedicated memory.
  12642. if(canAllocateDedicated && !dedicatedPreferred)
  12643. {
  12644. res = AllocateDedicatedMemory(
  12645. pool,
  12646. size,
  12647. suballocType,
  12648. dedicatedAllocations,
  12649. memTypeIndex,
  12650. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0,
  12651. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0,
  12652. (finalCreateInfo.flags &
  12653. (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0,
  12654. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT) != 0,
  12655. finalCreateInfo.pUserData,
  12656. finalCreateInfo.priority,
  12657. dedicatedBuffer,
  12658. dedicatedImage,
  12659. dedicatedBufferImageUsage,
  12660. allocationCount,
  12661. pAllocations,
  12662. blockVector.GetAllocationNextPtr());
  12663. if(res == VK_SUCCESS)
  12664. {
  12665. // Succeeded: AllocateDedicatedMemory function already filld pMemory, nothing more to do here.
  12666. VMA_DEBUG_LOG(" Allocated as DedicatedMemory");
  12667. return VK_SUCCESS;
  12668. }
  12669. }
  12670. // Everything failed: Return error code.
  12671. VMA_DEBUG_LOG(" vkAllocateMemory FAILED");
  12672. return res;
  12673. }
  12674. }
  12675. VkResult VmaAllocator_T::AllocateDedicatedMemory(
  12676. VmaPool pool,
  12677. VkDeviceSize size,
  12678. VmaSuballocationType suballocType,
  12679. VmaDedicatedAllocationList& dedicatedAllocations,
  12680. uint32_t memTypeIndex,
  12681. bool map,
  12682. bool isUserDataString,
  12683. bool isMappingAllowed,
  12684. bool canAliasMemory,
  12685. void* pUserData,
  12686. float priority,
  12687. VkBuffer dedicatedBuffer,
  12688. VkImage dedicatedImage,
  12689. VkFlags dedicatedBufferImageUsage,
  12690. size_t allocationCount,
  12691. VmaAllocation* pAllocations,
  12692. const void* pNextChain)
  12693. {
  12694. VMA_ASSERT(allocationCount > 0 && pAllocations);
  12695. VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
  12696. allocInfo.memoryTypeIndex = memTypeIndex;
  12697. allocInfo.allocationSize = size;
  12698. allocInfo.pNext = pNextChain;
  12699. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12700. VkMemoryDedicatedAllocateInfoKHR dedicatedAllocInfo = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR };
  12701. if(!canAliasMemory)
  12702. {
  12703. if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12704. {
  12705. if(dedicatedBuffer != VK_NULL_HANDLE)
  12706. {
  12707. VMA_ASSERT(dedicatedImage == VK_NULL_HANDLE);
  12708. dedicatedAllocInfo.buffer = dedicatedBuffer;
  12709. VmaPnextChainPushFront(&allocInfo, &dedicatedAllocInfo);
  12710. }
  12711. else if(dedicatedImage != VK_NULL_HANDLE)
  12712. {
  12713. dedicatedAllocInfo.image = dedicatedImage;
  12714. VmaPnextChainPushFront(&allocInfo, &dedicatedAllocInfo);
  12715. }
  12716. }
  12717. }
  12718. #endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12719. #if VMA_BUFFER_DEVICE_ADDRESS
  12720. VkMemoryAllocateFlagsInfoKHR allocFlagsInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR };
  12721. if(m_UseKhrBufferDeviceAddress)
  12722. {
  12723. bool canContainBufferWithDeviceAddress = true;
  12724. if(dedicatedBuffer != VK_NULL_HANDLE)
  12725. {
  12726. canContainBufferWithDeviceAddress = dedicatedBufferImageUsage == UINT32_MAX || // Usage flags unknown
  12727. (dedicatedBufferImageUsage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT) != 0;
  12728. }
  12729. else if(dedicatedImage != VK_NULL_HANDLE)
  12730. {
  12731. canContainBufferWithDeviceAddress = false;
  12732. }
  12733. if(canContainBufferWithDeviceAddress)
  12734. {
  12735. allocFlagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR;
  12736. VmaPnextChainPushFront(&allocInfo, &allocFlagsInfo);
  12737. }
  12738. }
  12739. #endif // #if VMA_BUFFER_DEVICE_ADDRESS
  12740. #if VMA_MEMORY_PRIORITY
  12741. VkMemoryPriorityAllocateInfoEXT priorityInfo = { VK_STRUCTURE_TYPE_MEMORY_PRIORITY_ALLOCATE_INFO_EXT };
  12742. if(m_UseExtMemoryPriority)
  12743. {
  12744. VMA_ASSERT(priority >= 0.f && priority <= 1.f);
  12745. priorityInfo.priority = priority;
  12746. VmaPnextChainPushFront(&allocInfo, &priorityInfo);
  12747. }
  12748. #endif // #if VMA_MEMORY_PRIORITY
  12749. #if VMA_EXTERNAL_MEMORY
  12750. // Attach VkExportMemoryAllocateInfoKHR if necessary.
  12751. VkExportMemoryAllocateInfoKHR exportMemoryAllocInfo = { VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR };
  12752. exportMemoryAllocInfo.handleTypes = GetExternalMemoryHandleTypeFlags(memTypeIndex);
  12753. if(exportMemoryAllocInfo.handleTypes != 0)
  12754. {
  12755. VmaPnextChainPushFront(&allocInfo, &exportMemoryAllocInfo);
  12756. }
  12757. #endif // #if VMA_EXTERNAL_MEMORY
  12758. size_t allocIndex;
  12759. VkResult res = VK_SUCCESS;
  12760. for(allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  12761. {
  12762. res = AllocateDedicatedMemoryPage(
  12763. pool,
  12764. size,
  12765. suballocType,
  12766. memTypeIndex,
  12767. allocInfo,
  12768. map,
  12769. isUserDataString,
  12770. isMappingAllowed,
  12771. pUserData,
  12772. pAllocations + allocIndex);
  12773. if(res != VK_SUCCESS)
  12774. {
  12775. break;
  12776. }
  12777. }
  12778. if(res == VK_SUCCESS)
  12779. {
  12780. for (allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  12781. {
  12782. dedicatedAllocations.Register(pAllocations[allocIndex]);
  12783. }
  12784. VMA_DEBUG_LOG(" Allocated DedicatedMemory Count=%zu, MemoryTypeIndex=#%u", allocationCount, memTypeIndex);
  12785. }
  12786. else
  12787. {
  12788. // Free all already created allocations.
  12789. while(allocIndex--)
  12790. {
  12791. VmaAllocation currAlloc = pAllocations[allocIndex];
  12792. VkDeviceMemory hMemory = currAlloc->GetMemory();
  12793. /*
  12794. There is no need to call this, because Vulkan spec allows to skip vkUnmapMemory
  12795. before vkFreeMemory.
  12796. if(currAlloc->GetMappedData() != VMA_NULL)
  12797. {
  12798. (*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory);
  12799. }
  12800. */
  12801. FreeVulkanMemory(memTypeIndex, currAlloc->GetSize(), hMemory);
  12802. m_Budget.RemoveAllocation(MemoryTypeIndexToHeapIndex(memTypeIndex), currAlloc->GetSize());
  12803. m_AllocationObjectAllocator.Free(currAlloc);
  12804. }
  12805. memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount);
  12806. }
  12807. return res;
  12808. }
  12809. VkResult VmaAllocator_T::AllocateDedicatedMemoryPage(
  12810. VmaPool pool,
  12811. VkDeviceSize size,
  12812. VmaSuballocationType suballocType,
  12813. uint32_t memTypeIndex,
  12814. const VkMemoryAllocateInfo& allocInfo,
  12815. bool map,
  12816. bool isUserDataString,
  12817. bool isMappingAllowed,
  12818. void* pUserData,
  12819. VmaAllocation* pAllocation)
  12820. {
  12821. VkDeviceMemory hMemory = VK_NULL_HANDLE;
  12822. VkResult res = AllocateVulkanMemory(&allocInfo, &hMemory);
  12823. if(res < 0)
  12824. {
  12825. VMA_DEBUG_LOG(" vkAllocateMemory FAILED");
  12826. return res;
  12827. }
  12828. void* pMappedData = VMA_NULL;
  12829. if(map)
  12830. {
  12831. res = (*m_VulkanFunctions.vkMapMemory)(
  12832. m_hDevice,
  12833. hMemory,
  12834. 0,
  12835. VK_WHOLE_SIZE,
  12836. 0,
  12837. &pMappedData);
  12838. if(res < 0)
  12839. {
  12840. VMA_DEBUG_LOG(" vkMapMemory FAILED");
  12841. FreeVulkanMemory(memTypeIndex, size, hMemory);
  12842. return res;
  12843. }
  12844. }
  12845. *pAllocation = m_AllocationObjectAllocator.Allocate(isMappingAllowed);
  12846. (*pAllocation)->InitDedicatedAllocation(pool, memTypeIndex, hMemory, suballocType, pMappedData, size);
  12847. if (isUserDataString)
  12848. (*pAllocation)->SetName(this, (const char*)pUserData);
  12849. else
  12850. (*pAllocation)->SetUserData(this, pUserData);
  12851. m_Budget.AddAllocation(MemoryTypeIndexToHeapIndex(memTypeIndex), size);
  12852. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
  12853. {
  12854. FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED);
  12855. }
  12856. return VK_SUCCESS;
  12857. }
  12858. void VmaAllocator_T::GetBufferMemoryRequirements(
  12859. VkBuffer hBuffer,
  12860. VkMemoryRequirements& memReq,
  12861. bool& requiresDedicatedAllocation,
  12862. bool& prefersDedicatedAllocation) const
  12863. {
  12864. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12865. if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12866. {
  12867. VkBufferMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR };
  12868. memReqInfo.buffer = hBuffer;
  12869. VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR };
  12870. VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR };
  12871. VmaPnextChainPushFront(&memReq2, &memDedicatedReq);
  12872. (*m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2);
  12873. memReq = memReq2.memoryRequirements;
  12874. requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE);
  12875. prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE);
  12876. }
  12877. else
  12878. #endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12879. {
  12880. (*m_VulkanFunctions.vkGetBufferMemoryRequirements)(m_hDevice, hBuffer, &memReq);
  12881. requiresDedicatedAllocation = false;
  12882. prefersDedicatedAllocation = false;
  12883. }
  12884. }
  12885. void VmaAllocator_T::GetImageMemoryRequirements(
  12886. VkImage hImage,
  12887. VkMemoryRequirements& memReq,
  12888. bool& requiresDedicatedAllocation,
  12889. bool& prefersDedicatedAllocation) const
  12890. {
  12891. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12892. if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12893. {
  12894. VkImageMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR };
  12895. memReqInfo.image = hImage;
  12896. VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR };
  12897. VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR };
  12898. VmaPnextChainPushFront(&memReq2, &memDedicatedReq);
  12899. (*m_VulkanFunctions.vkGetImageMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2);
  12900. memReq = memReq2.memoryRequirements;
  12901. requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE);
  12902. prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE);
  12903. }
  12904. else
  12905. #endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12906. {
  12907. (*m_VulkanFunctions.vkGetImageMemoryRequirements)(m_hDevice, hImage, &memReq);
  12908. requiresDedicatedAllocation = false;
  12909. prefersDedicatedAllocation = false;
  12910. }
  12911. }
  12912. VkResult VmaAllocator_T::FindMemoryTypeIndex(
  12913. uint32_t memoryTypeBits,
  12914. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  12915. VkFlags bufImgUsage,
  12916. uint32_t* pMemoryTypeIndex) const
  12917. {
  12918. memoryTypeBits &= GetGlobalMemoryTypeBits();
  12919. if(pAllocationCreateInfo->memoryTypeBits != 0)
  12920. {
  12921. memoryTypeBits &= pAllocationCreateInfo->memoryTypeBits;
  12922. }
  12923. VkMemoryPropertyFlags requiredFlags = 0, preferredFlags = 0, notPreferredFlags = 0;
  12924. if(!FindMemoryPreferences(
  12925. IsIntegratedGpu(),
  12926. *pAllocationCreateInfo,
  12927. bufImgUsage,
  12928. requiredFlags, preferredFlags, notPreferredFlags))
  12929. {
  12930. return VK_ERROR_FEATURE_NOT_PRESENT;
  12931. }
  12932. *pMemoryTypeIndex = UINT32_MAX;
  12933. uint32_t minCost = UINT32_MAX;
  12934. for(uint32_t memTypeIndex = 0, memTypeBit = 1;
  12935. memTypeIndex < GetMemoryTypeCount();
  12936. ++memTypeIndex, memTypeBit <<= 1)
  12937. {
  12938. // This memory type is acceptable according to memoryTypeBits bitmask.
  12939. if((memTypeBit & memoryTypeBits) != 0)
  12940. {
  12941. const VkMemoryPropertyFlags currFlags =
  12942. m_MemProps.memoryTypes[memTypeIndex].propertyFlags;
  12943. // This memory type contains requiredFlags.
  12944. if((requiredFlags & ~currFlags) == 0)
  12945. {
  12946. // Calculate cost as number of bits from preferredFlags not present in this memory type.
  12947. uint32_t currCost = VMA_COUNT_BITS_SET(preferredFlags & ~currFlags) +
  12948. VMA_COUNT_BITS_SET(currFlags & notPreferredFlags);
  12949. // Remember memory type with lowest cost.
  12950. if(currCost < minCost)
  12951. {
  12952. *pMemoryTypeIndex = memTypeIndex;
  12953. if(currCost == 0)
  12954. {
  12955. return VK_SUCCESS;
  12956. }
  12957. minCost = currCost;
  12958. }
  12959. }
  12960. }
  12961. }
  12962. return (*pMemoryTypeIndex != UINT32_MAX) ? VK_SUCCESS : VK_ERROR_FEATURE_NOT_PRESENT;
  12963. }
  12964. VkResult VmaAllocator_T::CalcMemTypeParams(
  12965. VmaAllocationCreateInfo& inoutCreateInfo,
  12966. uint32_t memTypeIndex,
  12967. VkDeviceSize size,
  12968. size_t allocationCount)
  12969. {
  12970. // If memory type is not HOST_VISIBLE, disable MAPPED.
  12971. if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 &&
  12972. (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  12973. {
  12974. inoutCreateInfo.flags &= ~VMA_ALLOCATION_CREATE_MAPPED_BIT;
  12975. }
  12976. if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0 &&
  12977. (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT) != 0)
  12978. {
  12979. const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex);
  12980. VmaBudget heapBudget = {};
  12981. GetHeapBudgets(&heapBudget, heapIndex, 1);
  12982. if(heapBudget.usage + size * allocationCount > heapBudget.budget)
  12983. {
  12984. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  12985. }
  12986. }
  12987. return VK_SUCCESS;
  12988. }
  12989. VkResult VmaAllocator_T::CalcAllocationParams(
  12990. VmaAllocationCreateInfo& inoutCreateInfo,
  12991. bool dedicatedRequired,
  12992. bool dedicatedPreferred)
  12993. {
  12994. VMA_ASSERT((inoutCreateInfo.flags &
  12995. (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) !=
  12996. (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT) &&
  12997. "Specifying both flags VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT and VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT is incorrect.");
  12998. VMA_ASSERT((((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT) == 0 ||
  12999. (inoutCreateInfo.flags & (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0)) &&
  13000. "Specifying VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT requires also VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT.");
  13001. if(inoutCreateInfo.usage == VMA_MEMORY_USAGE_AUTO || inoutCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE || inoutCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_HOST)
  13002. {
  13003. if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0)
  13004. {
  13005. VMA_ASSERT((inoutCreateInfo.flags & (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0 &&
  13006. "When using VMA_ALLOCATION_CREATE_MAPPED_BIT and usage = VMA_MEMORY_USAGE_AUTO*, you must also specify VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT.");
  13007. }
  13008. }
  13009. // If memory is lazily allocated, it should be always dedicated.
  13010. if(dedicatedRequired ||
  13011. inoutCreateInfo.usage == VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED)
  13012. {
  13013. inoutCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  13014. }
  13015. if(inoutCreateInfo.pool != VK_NULL_HANDLE)
  13016. {
  13017. if(inoutCreateInfo.pool->m_BlockVector.HasExplicitBlockSize() &&
  13018. (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0)
  13019. {
  13020. VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT while current custom pool doesn't support dedicated allocations.");
  13021. return VK_ERROR_FEATURE_NOT_PRESENT;
  13022. }
  13023. inoutCreateInfo.priority = inoutCreateInfo.pool->m_BlockVector.GetPriority();
  13024. }
  13025. if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0 &&
  13026. (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
  13027. {
  13028. VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT together with VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT makes no sense.");
  13029. return VK_ERROR_FEATURE_NOT_PRESENT;
  13030. }
  13031. if(VMA_DEBUG_ALWAYS_DEDICATED_MEMORY &&
  13032. (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
  13033. {
  13034. inoutCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  13035. }
  13036. // Non-auto USAGE values imply HOST_ACCESS flags.
  13037. // And so does VMA_MEMORY_USAGE_UNKNOWN because it is used with custom pools.
  13038. // Which specific flag is used doesn't matter. They change things only when used with VMA_MEMORY_USAGE_AUTO*.
  13039. // Otherwise they just protect from assert on mapping.
  13040. if(inoutCreateInfo.usage != VMA_MEMORY_USAGE_AUTO &&
  13041. inoutCreateInfo.usage != VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE &&
  13042. inoutCreateInfo.usage != VMA_MEMORY_USAGE_AUTO_PREFER_HOST)
  13043. {
  13044. if((inoutCreateInfo.flags & (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) == 0)
  13045. {
  13046. inoutCreateInfo.flags |= VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT;
  13047. }
  13048. }
  13049. return VK_SUCCESS;
  13050. }
  13051. VkResult VmaAllocator_T::AllocateMemory(
  13052. const VkMemoryRequirements& vkMemReq,
  13053. bool requiresDedicatedAllocation,
  13054. bool prefersDedicatedAllocation,
  13055. VkBuffer dedicatedBuffer,
  13056. VkImage dedicatedImage,
  13057. VkFlags dedicatedBufferImageUsage,
  13058. const VmaAllocationCreateInfo& createInfo,
  13059. VmaSuballocationType suballocType,
  13060. size_t allocationCount,
  13061. VmaAllocation* pAllocations)
  13062. {
  13063. memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount);
  13064. VMA_ASSERT(VmaIsPow2(vkMemReq.alignment));
  13065. if(vkMemReq.size == 0)
  13066. {
  13067. return VK_ERROR_INITIALIZATION_FAILED;
  13068. }
  13069. VmaAllocationCreateInfo createInfoFinal = createInfo;
  13070. VkResult res = CalcAllocationParams(createInfoFinal, requiresDedicatedAllocation, prefersDedicatedAllocation);
  13071. if(res != VK_SUCCESS)
  13072. return res;
  13073. if(createInfoFinal.pool != VK_NULL_HANDLE)
  13074. {
  13075. VmaBlockVector& blockVector = createInfoFinal.pool->m_BlockVector;
  13076. return AllocateMemoryOfType(
  13077. createInfoFinal.pool,
  13078. vkMemReq.size,
  13079. vkMemReq.alignment,
  13080. prefersDedicatedAllocation,
  13081. dedicatedBuffer,
  13082. dedicatedImage,
  13083. dedicatedBufferImageUsage,
  13084. createInfoFinal,
  13085. blockVector.GetMemoryTypeIndex(),
  13086. suballocType,
  13087. createInfoFinal.pool->m_DedicatedAllocations,
  13088. blockVector,
  13089. allocationCount,
  13090. pAllocations);
  13091. }
  13092. else
  13093. {
  13094. // Bit mask of memory Vulkan types acceptable for this allocation.
  13095. uint32_t memoryTypeBits = vkMemReq.memoryTypeBits;
  13096. uint32_t memTypeIndex = UINT32_MAX;
  13097. res = FindMemoryTypeIndex(memoryTypeBits, &createInfoFinal, dedicatedBufferImageUsage, &memTypeIndex);
  13098. // Can't find any single memory type matching requirements. res is VK_ERROR_FEATURE_NOT_PRESENT.
  13099. if(res != VK_SUCCESS)
  13100. return res;
  13101. do
  13102. {
  13103. VmaBlockVector* blockVector = m_pBlockVectors[memTypeIndex];
  13104. VMA_ASSERT(blockVector && "Trying to use unsupported memory type!");
  13105. res = AllocateMemoryOfType(
  13106. VK_NULL_HANDLE,
  13107. vkMemReq.size,
  13108. vkMemReq.alignment,
  13109. requiresDedicatedAllocation || prefersDedicatedAllocation,
  13110. dedicatedBuffer,
  13111. dedicatedImage,
  13112. dedicatedBufferImageUsage,
  13113. createInfoFinal,
  13114. memTypeIndex,
  13115. suballocType,
  13116. m_DedicatedAllocations[memTypeIndex],
  13117. *blockVector,
  13118. allocationCount,
  13119. pAllocations);
  13120. // Allocation succeeded
  13121. if(res == VK_SUCCESS)
  13122. return VK_SUCCESS;
  13123. // Remove old memTypeIndex from list of possibilities.
  13124. memoryTypeBits &= ~(1u << memTypeIndex);
  13125. // Find alternative memTypeIndex.
  13126. res = FindMemoryTypeIndex(memoryTypeBits, &createInfoFinal, dedicatedBufferImageUsage, &memTypeIndex);
  13127. } while(res == VK_SUCCESS);
  13128. // No other matching memory type index could be found.
  13129. // Not returning res, which is VK_ERROR_FEATURE_NOT_PRESENT, because we already failed to allocate once.
  13130. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  13131. }
  13132. }
  13133. void VmaAllocator_T::FreeMemory(
  13134. size_t allocationCount,
  13135. const VmaAllocation* pAllocations)
  13136. {
  13137. VMA_ASSERT(pAllocations);
  13138. for(size_t allocIndex = allocationCount; allocIndex--; )
  13139. {
  13140. VmaAllocation allocation = pAllocations[allocIndex];
  13141. if(allocation != VK_NULL_HANDLE)
  13142. {
  13143. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
  13144. {
  13145. FillAllocation(allocation, VMA_ALLOCATION_FILL_PATTERN_DESTROYED);
  13146. }
  13147. allocation->FreeName(this);
  13148. switch(allocation->GetType())
  13149. {
  13150. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13151. {
  13152. VmaBlockVector* pBlockVector = VMA_NULL;
  13153. VmaPool hPool = allocation->GetParentPool();
  13154. if(hPool != VK_NULL_HANDLE)
  13155. {
  13156. pBlockVector = &hPool->m_BlockVector;
  13157. }
  13158. else
  13159. {
  13160. const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
  13161. pBlockVector = m_pBlockVectors[memTypeIndex];
  13162. VMA_ASSERT(pBlockVector && "Trying to free memory of unsupported type!");
  13163. }
  13164. pBlockVector->Free(allocation);
  13165. }
  13166. break;
  13167. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13168. FreeDedicatedMemory(allocation);
  13169. break;
  13170. default:
  13171. VMA_ASSERT(0);
  13172. }
  13173. }
  13174. }
  13175. }
  13176. void VmaAllocator_T::CalculateStatistics(VmaTotalStatistics* pStats)
  13177. {
  13178. // Initialize.
  13179. VmaClearDetailedStatistics(pStats->total);
  13180. for(uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; ++i)
  13181. VmaClearDetailedStatistics(pStats->memoryType[i]);
  13182. for(uint32_t i = 0; i < VK_MAX_MEMORY_HEAPS; ++i)
  13183. VmaClearDetailedStatistics(pStats->memoryHeap[i]);
  13184. // Process default pools.
  13185. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13186. {
  13187. VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex];
  13188. if (pBlockVector != VMA_NULL)
  13189. pBlockVector->AddDetailedStatistics(pStats->memoryType[memTypeIndex]);
  13190. }
  13191. // Process custom pools.
  13192. {
  13193. VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex);
  13194. for(VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool))
  13195. {
  13196. VmaBlockVector& blockVector = pool->m_BlockVector;
  13197. const uint32_t memTypeIndex = blockVector.GetMemoryTypeIndex();
  13198. blockVector.AddDetailedStatistics(pStats->memoryType[memTypeIndex]);
  13199. pool->m_DedicatedAllocations.AddDetailedStatistics(pStats->memoryType[memTypeIndex]);
  13200. }
  13201. }
  13202. // Process dedicated allocations.
  13203. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13204. {
  13205. m_DedicatedAllocations[memTypeIndex].AddDetailedStatistics(pStats->memoryType[memTypeIndex]);
  13206. }
  13207. // Sum from memory types to memory heaps.
  13208. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13209. {
  13210. const uint32_t memHeapIndex = m_MemProps.memoryTypes[memTypeIndex].heapIndex;
  13211. VmaAddDetailedStatistics(pStats->memoryHeap[memHeapIndex], pStats->memoryType[memTypeIndex]);
  13212. }
  13213. // Sum from memory heaps to total.
  13214. for(uint32_t memHeapIndex = 0; memHeapIndex < GetMemoryHeapCount(); ++memHeapIndex)
  13215. VmaAddDetailedStatistics(pStats->total, pStats->memoryHeap[memHeapIndex]);
  13216. VMA_ASSERT(pStats->total.statistics.allocationCount == 0 ||
  13217. pStats->total.allocationSizeMax >= pStats->total.allocationSizeMin);
  13218. VMA_ASSERT(pStats->total.unusedRangeCount == 0 ||
  13219. pStats->total.unusedRangeSizeMax >= pStats->total.unusedRangeSizeMin);
  13220. }
  13221. void VmaAllocator_T::GetHeapBudgets(VmaBudget* outBudgets, uint32_t firstHeap, uint32_t heapCount)
  13222. {
  13223. #if VMA_MEMORY_BUDGET
  13224. if(m_UseExtMemoryBudget)
  13225. {
  13226. if(m_Budget.m_OperationsSinceBudgetFetch < 30)
  13227. {
  13228. VmaMutexLockRead lockRead(m_Budget.m_BudgetMutex, m_UseMutex);
  13229. for(uint32_t i = 0; i < heapCount; ++i, ++outBudgets)
  13230. {
  13231. const uint32_t heapIndex = firstHeap + i;
  13232. outBudgets->statistics.blockCount = m_Budget.m_BlockCount[heapIndex];
  13233. outBudgets->statistics.allocationCount = m_Budget.m_AllocationCount[heapIndex];
  13234. outBudgets->statistics.blockBytes = m_Budget.m_BlockBytes[heapIndex];
  13235. outBudgets->statistics.allocationBytes = m_Budget.m_AllocationBytes[heapIndex];
  13236. if(m_Budget.m_VulkanUsage[heapIndex] + outBudgets->statistics.blockBytes > m_Budget.m_BlockBytesAtBudgetFetch[heapIndex])
  13237. {
  13238. outBudgets->usage = m_Budget.m_VulkanUsage[heapIndex] +
  13239. outBudgets->statistics.blockBytes - m_Budget.m_BlockBytesAtBudgetFetch[heapIndex];
  13240. }
  13241. else
  13242. {
  13243. outBudgets->usage = 0;
  13244. }
  13245. // Have to take MIN with heap size because explicit HeapSizeLimit is included in it.
  13246. outBudgets->budget = VMA_MIN(
  13247. m_Budget.m_VulkanBudget[heapIndex], m_MemProps.memoryHeaps[heapIndex].size);
  13248. }
  13249. }
  13250. else
  13251. {
  13252. UpdateVulkanBudget(); // Outside of mutex lock
  13253. GetHeapBudgets(outBudgets, firstHeap, heapCount); // Recursion
  13254. }
  13255. }
  13256. else
  13257. #endif
  13258. {
  13259. for(uint32_t i = 0; i < heapCount; ++i, ++outBudgets)
  13260. {
  13261. const uint32_t heapIndex = firstHeap + i;
  13262. outBudgets->statistics.blockCount = m_Budget.m_BlockCount[heapIndex];
  13263. outBudgets->statistics.allocationCount = m_Budget.m_AllocationCount[heapIndex];
  13264. outBudgets->statistics.blockBytes = m_Budget.m_BlockBytes[heapIndex];
  13265. outBudgets->statistics.allocationBytes = m_Budget.m_AllocationBytes[heapIndex];
  13266. outBudgets->usage = outBudgets->statistics.blockBytes;
  13267. outBudgets->budget = m_MemProps.memoryHeaps[heapIndex].size * 8 / 10; // 80% heuristics.
  13268. }
  13269. }
  13270. }
  13271. void VmaAllocator_T::GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo)
  13272. {
  13273. pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex();
  13274. pAllocationInfo->deviceMemory = hAllocation->GetMemory();
  13275. pAllocationInfo->offset = hAllocation->GetOffset();
  13276. pAllocationInfo->size = hAllocation->GetSize();
  13277. pAllocationInfo->pMappedData = hAllocation->GetMappedData();
  13278. pAllocationInfo->pUserData = hAllocation->GetUserData();
  13279. pAllocationInfo->pName = hAllocation->GetName();
  13280. }
  13281. VkResult VmaAllocator_T::CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool)
  13282. {
  13283. VMA_DEBUG_LOG(" CreatePool: MemoryTypeIndex=%u, flags=%u", pCreateInfo->memoryTypeIndex, pCreateInfo->flags);
  13284. VmaPoolCreateInfo newCreateInfo = *pCreateInfo;
  13285. // Protection against uninitialized new structure member. If garbage data are left there, this pointer dereference would crash.
  13286. if(pCreateInfo->pMemoryAllocateNext)
  13287. {
  13288. VMA_ASSERT(((const VkBaseInStructure*)pCreateInfo->pMemoryAllocateNext)->sType != 0);
  13289. }
  13290. if(newCreateInfo.maxBlockCount == 0)
  13291. {
  13292. newCreateInfo.maxBlockCount = SIZE_MAX;
  13293. }
  13294. if(newCreateInfo.minBlockCount > newCreateInfo.maxBlockCount)
  13295. {
  13296. return VK_ERROR_INITIALIZATION_FAILED;
  13297. }
  13298. // Memory type index out of range or forbidden.
  13299. if(pCreateInfo->memoryTypeIndex >= GetMemoryTypeCount() ||
  13300. ((1u << pCreateInfo->memoryTypeIndex) & m_GlobalMemoryTypeBits) == 0)
  13301. {
  13302. return VK_ERROR_FEATURE_NOT_PRESENT;
  13303. }
  13304. if(newCreateInfo.minAllocationAlignment > 0)
  13305. {
  13306. VMA_ASSERT(VmaIsPow2(newCreateInfo.minAllocationAlignment));
  13307. }
  13308. const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(newCreateInfo.memoryTypeIndex);
  13309. *pPool = vma_new(this, VmaPool_T)(this, newCreateInfo, preferredBlockSize);
  13310. VkResult res = (*pPool)->m_BlockVector.CreateMinBlocks();
  13311. if(res != VK_SUCCESS)
  13312. {
  13313. vma_delete(this, *pPool);
  13314. *pPool = VMA_NULL;
  13315. return res;
  13316. }
  13317. // Add to m_Pools.
  13318. {
  13319. VmaMutexLockWrite lock(m_PoolsMutex, m_UseMutex);
  13320. (*pPool)->SetId(m_NextPoolId++);
  13321. m_Pools.PushBack(*pPool);
  13322. }
  13323. return VK_SUCCESS;
  13324. }
  13325. void VmaAllocator_T::DestroyPool(VmaPool pool)
  13326. {
  13327. // Remove from m_Pools.
  13328. {
  13329. VmaMutexLockWrite lock(m_PoolsMutex, m_UseMutex);
  13330. m_Pools.Remove(pool);
  13331. }
  13332. vma_delete(this, pool);
  13333. }
  13334. void VmaAllocator_T::GetPoolStatistics(VmaPool pool, VmaStatistics* pPoolStats)
  13335. {
  13336. VmaClearStatistics(*pPoolStats);
  13337. pool->m_BlockVector.AddStatistics(*pPoolStats);
  13338. pool->m_DedicatedAllocations.AddStatistics(*pPoolStats);
  13339. }
  13340. void VmaAllocator_T::CalculatePoolStatistics(VmaPool pool, VmaDetailedStatistics* pPoolStats)
  13341. {
  13342. VmaClearDetailedStatistics(*pPoolStats);
  13343. pool->m_BlockVector.AddDetailedStatistics(*pPoolStats);
  13344. pool->m_DedicatedAllocations.AddDetailedStatistics(*pPoolStats);
  13345. }
  13346. void VmaAllocator_T::SetCurrentFrameIndex(uint32_t frameIndex)
  13347. {
  13348. m_CurrentFrameIndex.store(frameIndex);
  13349. #if VMA_MEMORY_BUDGET
  13350. if(m_UseExtMemoryBudget)
  13351. {
  13352. UpdateVulkanBudget();
  13353. }
  13354. #endif // #if VMA_MEMORY_BUDGET
  13355. }
  13356. VkResult VmaAllocator_T::CheckPoolCorruption(VmaPool hPool)
  13357. {
  13358. return hPool->m_BlockVector.CheckCorruption();
  13359. }
  13360. VkResult VmaAllocator_T::CheckCorruption(uint32_t memoryTypeBits)
  13361. {
  13362. VkResult finalRes = VK_ERROR_FEATURE_NOT_PRESENT;
  13363. // Process default pools.
  13364. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13365. {
  13366. VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex];
  13367. if(pBlockVector != VMA_NULL)
  13368. {
  13369. VkResult localRes = pBlockVector->CheckCorruption();
  13370. switch(localRes)
  13371. {
  13372. case VK_ERROR_FEATURE_NOT_PRESENT:
  13373. break;
  13374. case VK_SUCCESS:
  13375. finalRes = VK_SUCCESS;
  13376. break;
  13377. default:
  13378. return localRes;
  13379. }
  13380. }
  13381. }
  13382. // Process custom pools.
  13383. {
  13384. VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex);
  13385. for(VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool))
  13386. {
  13387. if(((1u << pool->m_BlockVector.GetMemoryTypeIndex()) & memoryTypeBits) != 0)
  13388. {
  13389. VkResult localRes = pool->m_BlockVector.CheckCorruption();
  13390. switch(localRes)
  13391. {
  13392. case VK_ERROR_FEATURE_NOT_PRESENT:
  13393. break;
  13394. case VK_SUCCESS:
  13395. finalRes = VK_SUCCESS;
  13396. break;
  13397. default:
  13398. return localRes;
  13399. }
  13400. }
  13401. }
  13402. }
  13403. return finalRes;
  13404. }
  13405. VkResult VmaAllocator_T::AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory)
  13406. {
  13407. AtomicTransactionalIncrement<uint32_t> deviceMemoryCountIncrement;
  13408. const uint64_t prevDeviceMemoryCount = deviceMemoryCountIncrement.Increment(&m_DeviceMemoryCount);
  13409. #if VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT
  13410. if(prevDeviceMemoryCount >= m_PhysicalDeviceProperties.limits.maxMemoryAllocationCount)
  13411. {
  13412. return VK_ERROR_TOO_MANY_OBJECTS;
  13413. }
  13414. #endif
  13415. const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(pAllocateInfo->memoryTypeIndex);
  13416. // HeapSizeLimit is in effect for this heap.
  13417. if((m_HeapSizeLimitMask & (1u << heapIndex)) != 0)
  13418. {
  13419. const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size;
  13420. VkDeviceSize blockBytes = m_Budget.m_BlockBytes[heapIndex];
  13421. for(;;)
  13422. {
  13423. const VkDeviceSize blockBytesAfterAllocation = blockBytes + pAllocateInfo->allocationSize;
  13424. if(blockBytesAfterAllocation > heapSize)
  13425. {
  13426. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  13427. }
  13428. if(m_Budget.m_BlockBytes[heapIndex].compare_exchange_strong(blockBytes, blockBytesAfterAllocation))
  13429. {
  13430. break;
  13431. }
  13432. }
  13433. }
  13434. else
  13435. {
  13436. m_Budget.m_BlockBytes[heapIndex] += pAllocateInfo->allocationSize;
  13437. }
  13438. ++m_Budget.m_BlockCount[heapIndex];
  13439. // VULKAN CALL vkAllocateMemory.
  13440. VkResult res = (*m_VulkanFunctions.vkAllocateMemory)(m_hDevice, pAllocateInfo, GetAllocationCallbacks(), pMemory);
  13441. if(res == VK_SUCCESS)
  13442. {
  13443. #if VMA_MEMORY_BUDGET
  13444. ++m_Budget.m_OperationsSinceBudgetFetch;
  13445. #endif
  13446. // Informative callback.
  13447. if(m_DeviceMemoryCallbacks.pfnAllocate != VMA_NULL)
  13448. {
  13449. (*m_DeviceMemoryCallbacks.pfnAllocate)(this, pAllocateInfo->memoryTypeIndex, *pMemory, pAllocateInfo->allocationSize, m_DeviceMemoryCallbacks.pUserData);
  13450. }
  13451. deviceMemoryCountIncrement.Commit();
  13452. }
  13453. else
  13454. {
  13455. --m_Budget.m_BlockCount[heapIndex];
  13456. m_Budget.m_BlockBytes[heapIndex] -= pAllocateInfo->allocationSize;
  13457. }
  13458. return res;
  13459. }
  13460. void VmaAllocator_T::FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory)
  13461. {
  13462. // Informative callback.
  13463. if(m_DeviceMemoryCallbacks.pfnFree != VMA_NULL)
  13464. {
  13465. (*m_DeviceMemoryCallbacks.pfnFree)(this, memoryType, hMemory, size, m_DeviceMemoryCallbacks.pUserData);
  13466. }
  13467. // VULKAN CALL vkFreeMemory.
  13468. (*m_VulkanFunctions.vkFreeMemory)(m_hDevice, hMemory, GetAllocationCallbacks());
  13469. const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memoryType);
  13470. --m_Budget.m_BlockCount[heapIndex];
  13471. m_Budget.m_BlockBytes[heapIndex] -= size;
  13472. --m_DeviceMemoryCount;
  13473. }
  13474. VkResult VmaAllocator_T::BindVulkanBuffer(
  13475. VkDeviceMemory memory,
  13476. VkDeviceSize memoryOffset,
  13477. VkBuffer buffer,
  13478. const void* pNext)
  13479. {
  13480. if(pNext != VMA_NULL)
  13481. {
  13482. #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2
  13483. if((m_UseKhrBindMemory2 || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) &&
  13484. m_VulkanFunctions.vkBindBufferMemory2KHR != VMA_NULL)
  13485. {
  13486. VkBindBufferMemoryInfoKHR bindBufferMemoryInfo = { VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR };
  13487. bindBufferMemoryInfo.pNext = pNext;
  13488. bindBufferMemoryInfo.buffer = buffer;
  13489. bindBufferMemoryInfo.memory = memory;
  13490. bindBufferMemoryInfo.memoryOffset = memoryOffset;
  13491. return (*m_VulkanFunctions.vkBindBufferMemory2KHR)(m_hDevice, 1, &bindBufferMemoryInfo);
  13492. }
  13493. else
  13494. #endif // #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2
  13495. {
  13496. return VK_ERROR_EXTENSION_NOT_PRESENT;
  13497. }
  13498. }
  13499. else
  13500. {
  13501. return (*m_VulkanFunctions.vkBindBufferMemory)(m_hDevice, buffer, memory, memoryOffset);
  13502. }
  13503. }
  13504. VkResult VmaAllocator_T::BindVulkanImage(
  13505. VkDeviceMemory memory,
  13506. VkDeviceSize memoryOffset,
  13507. VkImage image,
  13508. const void* pNext)
  13509. {
  13510. if(pNext != VMA_NULL)
  13511. {
  13512. #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2
  13513. if((m_UseKhrBindMemory2 || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) &&
  13514. m_VulkanFunctions.vkBindImageMemory2KHR != VMA_NULL)
  13515. {
  13516. VkBindImageMemoryInfoKHR bindBufferMemoryInfo = { VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO_KHR };
  13517. bindBufferMemoryInfo.pNext = pNext;
  13518. bindBufferMemoryInfo.image = image;
  13519. bindBufferMemoryInfo.memory = memory;
  13520. bindBufferMemoryInfo.memoryOffset = memoryOffset;
  13521. return (*m_VulkanFunctions.vkBindImageMemory2KHR)(m_hDevice, 1, &bindBufferMemoryInfo);
  13522. }
  13523. else
  13524. #endif // #if VMA_BIND_MEMORY2
  13525. {
  13526. return VK_ERROR_EXTENSION_NOT_PRESENT;
  13527. }
  13528. }
  13529. else
  13530. {
  13531. return (*m_VulkanFunctions.vkBindImageMemory)(m_hDevice, image, memory, memoryOffset);
  13532. }
  13533. }
  13534. VkResult VmaAllocator_T::Map(VmaAllocation hAllocation, void** ppData)
  13535. {
  13536. switch(hAllocation->GetType())
  13537. {
  13538. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13539. {
  13540. VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
  13541. char *pBytes = VMA_NULL;
  13542. VkResult res = pBlock->Map(this, 1, (void**)&pBytes);
  13543. if(res == VK_SUCCESS)
  13544. {
  13545. *ppData = pBytes + (ptrdiff_t)hAllocation->GetOffset();
  13546. hAllocation->BlockAllocMap();
  13547. }
  13548. return res;
  13549. }
  13550. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13551. return hAllocation->DedicatedAllocMap(this, ppData);
  13552. default:
  13553. VMA_ASSERT(0);
  13554. return VK_ERROR_MEMORY_MAP_FAILED;
  13555. }
  13556. }
  13557. void VmaAllocator_T::Unmap(VmaAllocation hAllocation)
  13558. {
  13559. switch(hAllocation->GetType())
  13560. {
  13561. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13562. {
  13563. VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
  13564. hAllocation->BlockAllocUnmap();
  13565. pBlock->Unmap(this, 1);
  13566. }
  13567. break;
  13568. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13569. hAllocation->DedicatedAllocUnmap(this);
  13570. break;
  13571. default:
  13572. VMA_ASSERT(0);
  13573. }
  13574. }
  13575. VkResult VmaAllocator_T::BindBufferMemory(
  13576. VmaAllocation hAllocation,
  13577. VkDeviceSize allocationLocalOffset,
  13578. VkBuffer hBuffer,
  13579. const void* pNext)
  13580. {
  13581. VkResult res = VK_SUCCESS;
  13582. switch(hAllocation->GetType())
  13583. {
  13584. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13585. res = BindVulkanBuffer(hAllocation->GetMemory(), allocationLocalOffset, hBuffer, pNext);
  13586. break;
  13587. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13588. {
  13589. VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
  13590. VMA_ASSERT(pBlock && "Binding buffer to allocation that doesn't belong to any block.");
  13591. res = pBlock->BindBufferMemory(this, hAllocation, allocationLocalOffset, hBuffer, pNext);
  13592. break;
  13593. }
  13594. default:
  13595. VMA_ASSERT(0);
  13596. }
  13597. return res;
  13598. }
  13599. VkResult VmaAllocator_T::BindImageMemory(
  13600. VmaAllocation hAllocation,
  13601. VkDeviceSize allocationLocalOffset,
  13602. VkImage hImage,
  13603. const void* pNext)
  13604. {
  13605. VkResult res = VK_SUCCESS;
  13606. switch(hAllocation->GetType())
  13607. {
  13608. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13609. res = BindVulkanImage(hAllocation->GetMemory(), allocationLocalOffset, hImage, pNext);
  13610. break;
  13611. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13612. {
  13613. VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock();
  13614. VMA_ASSERT(pBlock && "Binding image to allocation that doesn't belong to any block.");
  13615. res = pBlock->BindImageMemory(this, hAllocation, allocationLocalOffset, hImage, pNext);
  13616. break;
  13617. }
  13618. default:
  13619. VMA_ASSERT(0);
  13620. }
  13621. return res;
  13622. }
  13623. VkResult VmaAllocator_T::FlushOrInvalidateAllocation(
  13624. VmaAllocation hAllocation,
  13625. VkDeviceSize offset, VkDeviceSize size,
  13626. VMA_CACHE_OPERATION op)
  13627. {
  13628. VkResult res = VK_SUCCESS;
  13629. VkMappedMemoryRange memRange = {};
  13630. if(GetFlushOrInvalidateRange(hAllocation, offset, size, memRange))
  13631. {
  13632. switch(op)
  13633. {
  13634. case VMA_CACHE_FLUSH:
  13635. res = (*GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hDevice, 1, &memRange);
  13636. break;
  13637. case VMA_CACHE_INVALIDATE:
  13638. res = (*GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hDevice, 1, &memRange);
  13639. break;
  13640. default:
  13641. VMA_ASSERT(0);
  13642. }
  13643. }
  13644. // else: Just ignore this call.
  13645. return res;
  13646. }
  13647. VkResult VmaAllocator_T::FlushOrInvalidateAllocations(
  13648. uint32_t allocationCount,
  13649. const VmaAllocation* allocations,
  13650. const VkDeviceSize* offsets, const VkDeviceSize* sizes,
  13651. VMA_CACHE_OPERATION op)
  13652. {
  13653. typedef VmaStlAllocator<VkMappedMemoryRange> RangeAllocator;
  13654. typedef VmaSmallVector<VkMappedMemoryRange, RangeAllocator, 16> RangeVector;
  13655. RangeVector ranges = RangeVector(RangeAllocator(GetAllocationCallbacks()));
  13656. for(uint32_t allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  13657. {
  13658. const VmaAllocation alloc = allocations[allocIndex];
  13659. const VkDeviceSize offset = offsets != VMA_NULL ? offsets[allocIndex] : 0;
  13660. const VkDeviceSize size = sizes != VMA_NULL ? sizes[allocIndex] : VK_WHOLE_SIZE;
  13661. VkMappedMemoryRange newRange;
  13662. if(GetFlushOrInvalidateRange(alloc, offset, size, newRange))
  13663. {
  13664. ranges.push_back(newRange);
  13665. }
  13666. }
  13667. VkResult res = VK_SUCCESS;
  13668. if(!ranges.empty())
  13669. {
  13670. switch(op)
  13671. {
  13672. case VMA_CACHE_FLUSH:
  13673. res = (*GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hDevice, (uint32_t)ranges.size(), ranges.data());
  13674. break;
  13675. case VMA_CACHE_INVALIDATE:
  13676. res = (*GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hDevice, (uint32_t)ranges.size(), ranges.data());
  13677. break;
  13678. default:
  13679. VMA_ASSERT(0);
  13680. }
  13681. }
  13682. // else: Just ignore this call.
  13683. return res;
  13684. }
  13685. void VmaAllocator_T::FreeDedicatedMemory(const VmaAllocation allocation)
  13686. {
  13687. VMA_ASSERT(allocation && allocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  13688. const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
  13689. VmaPool parentPool = allocation->GetParentPool();
  13690. if(parentPool == VK_NULL_HANDLE)
  13691. {
  13692. // Default pool
  13693. m_DedicatedAllocations[memTypeIndex].Unregister(allocation);
  13694. }
  13695. else
  13696. {
  13697. // Custom pool
  13698. parentPool->m_DedicatedAllocations.Unregister(allocation);
  13699. }
  13700. VkDeviceMemory hMemory = allocation->GetMemory();
  13701. /*
  13702. There is no need to call this, because Vulkan spec allows to skip vkUnmapMemory
  13703. before vkFreeMemory.
  13704. if(allocation->GetMappedData() != VMA_NULL)
  13705. {
  13706. (*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory);
  13707. }
  13708. */
  13709. FreeVulkanMemory(memTypeIndex, allocation->GetSize(), hMemory);
  13710. m_Budget.RemoveAllocation(MemoryTypeIndexToHeapIndex(allocation->GetMemoryTypeIndex()), allocation->GetSize());
  13711. m_AllocationObjectAllocator.Free(allocation);
  13712. VMA_DEBUG_LOG(" Freed DedicatedMemory MemoryTypeIndex=%u", memTypeIndex);
  13713. }
  13714. uint32_t VmaAllocator_T::CalculateGpuDefragmentationMemoryTypeBits() const
  13715. {
  13716. VkBufferCreateInfo dummyBufCreateInfo;
  13717. VmaFillGpuDefragmentationBufferCreateInfo(dummyBufCreateInfo);
  13718. uint32_t memoryTypeBits = 0;
  13719. // Create buffer.
  13720. VkBuffer buf = VK_NULL_HANDLE;
  13721. VkResult res = (*GetVulkanFunctions().vkCreateBuffer)(
  13722. m_hDevice, &dummyBufCreateInfo, GetAllocationCallbacks(), &buf);
  13723. if(res == VK_SUCCESS)
  13724. {
  13725. // Query for supported memory types.
  13726. VkMemoryRequirements memReq;
  13727. (*GetVulkanFunctions().vkGetBufferMemoryRequirements)(m_hDevice, buf, &memReq);
  13728. memoryTypeBits = memReq.memoryTypeBits;
  13729. // Destroy buffer.
  13730. (*GetVulkanFunctions().vkDestroyBuffer)(m_hDevice, buf, GetAllocationCallbacks());
  13731. }
  13732. return memoryTypeBits;
  13733. }
  13734. uint32_t VmaAllocator_T::CalculateGlobalMemoryTypeBits() const
  13735. {
  13736. // Make sure memory information is already fetched.
  13737. VMA_ASSERT(GetMemoryTypeCount() > 0);
  13738. uint32_t memoryTypeBits = UINT32_MAX;
  13739. if(!m_UseAmdDeviceCoherentMemory)
  13740. {
  13741. // Exclude memory types that have VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD.
  13742. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13743. {
  13744. if((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY) != 0)
  13745. {
  13746. memoryTypeBits &= ~(1u << memTypeIndex);
  13747. }
  13748. }
  13749. }
  13750. return memoryTypeBits;
  13751. }
  13752. bool VmaAllocator_T::GetFlushOrInvalidateRange(
  13753. VmaAllocation allocation,
  13754. VkDeviceSize offset, VkDeviceSize size,
  13755. VkMappedMemoryRange& outRange) const
  13756. {
  13757. const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
  13758. if(size > 0 && IsMemoryTypeNonCoherent(memTypeIndex))
  13759. {
  13760. const VkDeviceSize nonCoherentAtomSize = m_PhysicalDeviceProperties.limits.nonCoherentAtomSize;
  13761. const VkDeviceSize allocationSize = allocation->GetSize();
  13762. VMA_ASSERT(offset <= allocationSize);
  13763. outRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  13764. outRange.pNext = VMA_NULL;
  13765. outRange.memory = allocation->GetMemory();
  13766. switch(allocation->GetType())
  13767. {
  13768. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13769. outRange.offset = VmaAlignDown(offset, nonCoherentAtomSize);
  13770. if(size == VK_WHOLE_SIZE)
  13771. {
  13772. outRange.size = allocationSize - outRange.offset;
  13773. }
  13774. else
  13775. {
  13776. VMA_ASSERT(offset + size <= allocationSize);
  13777. outRange.size = VMA_MIN(
  13778. VmaAlignUp(size + (offset - outRange.offset), nonCoherentAtomSize),
  13779. allocationSize - outRange.offset);
  13780. }
  13781. break;
  13782. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13783. {
  13784. // 1. Still within this allocation.
  13785. outRange.offset = VmaAlignDown(offset, nonCoherentAtomSize);
  13786. if(size == VK_WHOLE_SIZE)
  13787. {
  13788. size = allocationSize - offset;
  13789. }
  13790. else
  13791. {
  13792. VMA_ASSERT(offset + size <= allocationSize);
  13793. }
  13794. outRange.size = VmaAlignUp(size + (offset - outRange.offset), nonCoherentAtomSize);
  13795. // 2. Adjust to whole block.
  13796. const VkDeviceSize allocationOffset = allocation->GetOffset();
  13797. VMA_ASSERT(allocationOffset % nonCoherentAtomSize == 0);
  13798. const VkDeviceSize blockSize = allocation->GetBlock()->m_pMetadata->GetSize();
  13799. outRange.offset += allocationOffset;
  13800. outRange.size = VMA_MIN(outRange.size, blockSize - outRange.offset);
  13801. break;
  13802. }
  13803. default:
  13804. VMA_ASSERT(0);
  13805. }
  13806. return true;
  13807. }
  13808. return false;
  13809. }
  13810. #if VMA_MEMORY_BUDGET
  13811. void VmaAllocator_T::UpdateVulkanBudget()
  13812. {
  13813. VMA_ASSERT(m_UseExtMemoryBudget);
  13814. VkPhysicalDeviceMemoryProperties2KHR memProps = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2_KHR };
  13815. VkPhysicalDeviceMemoryBudgetPropertiesEXT budgetProps = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT };
  13816. VmaPnextChainPushFront(&memProps, &budgetProps);
  13817. GetVulkanFunctions().vkGetPhysicalDeviceMemoryProperties2KHR(m_PhysicalDevice, &memProps);
  13818. {
  13819. VmaMutexLockWrite lockWrite(m_Budget.m_BudgetMutex, m_UseMutex);
  13820. for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex)
  13821. {
  13822. m_Budget.m_VulkanUsage[heapIndex] = budgetProps.heapUsage[heapIndex];
  13823. m_Budget.m_VulkanBudget[heapIndex] = budgetProps.heapBudget[heapIndex];
  13824. m_Budget.m_BlockBytesAtBudgetFetch[heapIndex] = m_Budget.m_BlockBytes[heapIndex].load();
  13825. // Some bugged drivers return the budget incorrectly, e.g. 0 or much bigger than heap size.
  13826. if(m_Budget.m_VulkanBudget[heapIndex] == 0)
  13827. {
  13828. m_Budget.m_VulkanBudget[heapIndex] = m_MemProps.memoryHeaps[heapIndex].size * 8 / 10; // 80% heuristics.
  13829. }
  13830. else if(m_Budget.m_VulkanBudget[heapIndex] > m_MemProps.memoryHeaps[heapIndex].size)
  13831. {
  13832. m_Budget.m_VulkanBudget[heapIndex] = m_MemProps.memoryHeaps[heapIndex].size;
  13833. }
  13834. if(m_Budget.m_VulkanUsage[heapIndex] == 0 && m_Budget.m_BlockBytesAtBudgetFetch[heapIndex] > 0)
  13835. {
  13836. m_Budget.m_VulkanUsage[heapIndex] = m_Budget.m_BlockBytesAtBudgetFetch[heapIndex];
  13837. }
  13838. }
  13839. m_Budget.m_OperationsSinceBudgetFetch = 0;
  13840. }
  13841. }
  13842. #endif // VMA_MEMORY_BUDGET
  13843. void VmaAllocator_T::FillAllocation(const VmaAllocation hAllocation, uint8_t pattern)
  13844. {
  13845. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS &&
  13846. hAllocation->IsMappingAllowed() &&
  13847. (m_MemProps.memoryTypes[hAllocation->GetMemoryTypeIndex()].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
  13848. {
  13849. void* pData = VMA_NULL;
  13850. VkResult res = Map(hAllocation, &pData);
  13851. if(res == VK_SUCCESS)
  13852. {
  13853. memset(pData, (int)pattern, (size_t)hAllocation->GetSize());
  13854. FlushOrInvalidateAllocation(hAllocation, 0, VK_WHOLE_SIZE, VMA_CACHE_FLUSH);
  13855. Unmap(hAllocation);
  13856. }
  13857. else
  13858. {
  13859. VMA_ASSERT(0 && "VMA_DEBUG_INITIALIZE_ALLOCATIONS is enabled, but couldn't map memory to fill allocation.");
  13860. }
  13861. }
  13862. }
  13863. uint32_t VmaAllocator_T::GetGpuDefragmentationMemoryTypeBits()
  13864. {
  13865. uint32_t memoryTypeBits = m_GpuDefragmentationMemoryTypeBits.load();
  13866. if(memoryTypeBits == UINT32_MAX)
  13867. {
  13868. memoryTypeBits = CalculateGpuDefragmentationMemoryTypeBits();
  13869. m_GpuDefragmentationMemoryTypeBits.store(memoryTypeBits);
  13870. }
  13871. return memoryTypeBits;
  13872. }
  13873. #if VMA_STATS_STRING_ENABLED
  13874. void VmaAllocator_T::PrintDetailedMap(VmaJsonWriter& json)
  13875. {
  13876. json.WriteString("DefaultPools");
  13877. json.BeginObject();
  13878. {
  13879. for (uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13880. {
  13881. VmaBlockVector* pBlockVector = m_pBlockVectors[memTypeIndex];
  13882. VmaDedicatedAllocationList& dedicatedAllocList = m_DedicatedAllocations[memTypeIndex];
  13883. if (pBlockVector != VMA_NULL)
  13884. {
  13885. json.BeginString("Type ");
  13886. json.ContinueString(memTypeIndex);
  13887. json.EndString();
  13888. json.BeginObject();
  13889. {
  13890. json.WriteString("PreferredBlockSize");
  13891. json.WriteNumber(pBlockVector->GetPreferredBlockSize());
  13892. json.WriteString("Blocks");
  13893. pBlockVector->PrintDetailedMap(json);
  13894. json.WriteString("DedicatedAllocations");
  13895. dedicatedAllocList.BuildStatsString(json);
  13896. }
  13897. json.EndObject();
  13898. }
  13899. }
  13900. }
  13901. json.EndObject();
  13902. json.WriteString("CustomPools");
  13903. json.BeginObject();
  13904. {
  13905. VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex);
  13906. if (!m_Pools.IsEmpty())
  13907. {
  13908. for (uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13909. {
  13910. bool displayType = true;
  13911. size_t index = 0;
  13912. for (VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool))
  13913. {
  13914. VmaBlockVector& blockVector = pool->m_BlockVector;
  13915. if (blockVector.GetMemoryTypeIndex() == memTypeIndex)
  13916. {
  13917. if (displayType)
  13918. {
  13919. json.BeginString("Type ");
  13920. json.ContinueString(memTypeIndex);
  13921. json.EndString();
  13922. json.BeginArray();
  13923. displayType = false;
  13924. }
  13925. json.BeginObject();
  13926. {
  13927. json.WriteString("Name");
  13928. json.BeginString();
  13929. json.ContinueString_Size(index++);
  13930. if (pool->GetName())
  13931. {
  13932. json.ContinueString(" - ");
  13933. json.ContinueString(pool->GetName());
  13934. }
  13935. json.EndString();
  13936. json.WriteString("PreferredBlockSize");
  13937. json.WriteNumber(blockVector.GetPreferredBlockSize());
  13938. json.WriteString("Blocks");
  13939. blockVector.PrintDetailedMap(json);
  13940. json.WriteString("DedicatedAllocations");
  13941. pool->m_DedicatedAllocations.BuildStatsString(json);
  13942. }
  13943. json.EndObject();
  13944. }
  13945. }
  13946. if (!displayType)
  13947. json.EndArray();
  13948. }
  13949. }
  13950. }
  13951. json.EndObject();
  13952. }
  13953. #endif // VMA_STATS_STRING_ENABLED
  13954. #endif // _VMA_ALLOCATOR_T_FUNCTIONS
  13955. #ifndef _VMA_PUBLIC_INTERFACE
  13956. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAllocator(
  13957. const VmaAllocatorCreateInfo* pCreateInfo,
  13958. VmaAllocator* pAllocator)
  13959. {
  13960. VMA_ASSERT(pCreateInfo && pAllocator);
  13961. VMA_ASSERT(pCreateInfo->vulkanApiVersion == 0 ||
  13962. (VK_VERSION_MAJOR(pCreateInfo->vulkanApiVersion) == 1 && VK_VERSION_MINOR(pCreateInfo->vulkanApiVersion) <= 3));
  13963. VMA_DEBUG_LOG("vmaCreateAllocator");
  13964. *pAllocator = vma_new(pCreateInfo->pAllocationCallbacks, VmaAllocator_T)(pCreateInfo);
  13965. VkResult result = (*pAllocator)->Init(pCreateInfo);
  13966. if(result < 0)
  13967. {
  13968. vma_delete(pCreateInfo->pAllocationCallbacks, *pAllocator);
  13969. *pAllocator = VK_NULL_HANDLE;
  13970. }
  13971. return result;
  13972. }
  13973. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyAllocator(
  13974. VmaAllocator allocator)
  13975. {
  13976. if(allocator != VK_NULL_HANDLE)
  13977. {
  13978. VMA_DEBUG_LOG("vmaDestroyAllocator");
  13979. VkAllocationCallbacks allocationCallbacks = allocator->m_AllocationCallbacks; // Have to copy the callbacks when destroying.
  13980. vma_delete(&allocationCallbacks, allocator);
  13981. }
  13982. }
  13983. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocatorInfo(VmaAllocator allocator, VmaAllocatorInfo* pAllocatorInfo)
  13984. {
  13985. VMA_ASSERT(allocator && pAllocatorInfo);
  13986. pAllocatorInfo->instance = allocator->m_hInstance;
  13987. pAllocatorInfo->physicalDevice = allocator->GetPhysicalDevice();
  13988. pAllocatorInfo->device = allocator->m_hDevice;
  13989. }
  13990. VMA_CALL_PRE void VMA_CALL_POST vmaGetPhysicalDeviceProperties(
  13991. VmaAllocator allocator,
  13992. const VkPhysicalDeviceProperties **ppPhysicalDeviceProperties)
  13993. {
  13994. VMA_ASSERT(allocator && ppPhysicalDeviceProperties);
  13995. *ppPhysicalDeviceProperties = &allocator->m_PhysicalDeviceProperties;
  13996. }
  13997. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryProperties(
  13998. VmaAllocator allocator,
  13999. const VkPhysicalDeviceMemoryProperties** ppPhysicalDeviceMemoryProperties)
  14000. {
  14001. VMA_ASSERT(allocator && ppPhysicalDeviceMemoryProperties);
  14002. *ppPhysicalDeviceMemoryProperties = &allocator->m_MemProps;
  14003. }
  14004. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties(
  14005. VmaAllocator allocator,
  14006. uint32_t memoryTypeIndex,
  14007. VkMemoryPropertyFlags* pFlags)
  14008. {
  14009. VMA_ASSERT(allocator && pFlags);
  14010. VMA_ASSERT(memoryTypeIndex < allocator->GetMemoryTypeCount());
  14011. *pFlags = allocator->m_MemProps.memoryTypes[memoryTypeIndex].propertyFlags;
  14012. }
  14013. VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex(
  14014. VmaAllocator allocator,
  14015. uint32_t frameIndex)
  14016. {
  14017. VMA_ASSERT(allocator);
  14018. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14019. allocator->SetCurrentFrameIndex(frameIndex);
  14020. }
  14021. VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStatistics(
  14022. VmaAllocator allocator,
  14023. VmaTotalStatistics* pStats)
  14024. {
  14025. VMA_ASSERT(allocator && pStats);
  14026. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14027. allocator->CalculateStatistics(pStats);
  14028. }
  14029. VMA_CALL_PRE void VMA_CALL_POST vmaGetHeapBudgets(
  14030. VmaAllocator allocator,
  14031. VmaBudget* pBudgets)
  14032. {
  14033. VMA_ASSERT(allocator && pBudgets);
  14034. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14035. allocator->GetHeapBudgets(pBudgets, 0, allocator->GetMemoryHeapCount());
  14036. }
  14037. #if VMA_STATS_STRING_ENABLED
  14038. VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString(
  14039. VmaAllocator allocator,
  14040. char** ppStatsString,
  14041. VkBool32 detailedMap)
  14042. {
  14043. VMA_ASSERT(allocator && ppStatsString);
  14044. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14045. VmaStringBuilder sb(allocator->GetAllocationCallbacks());
  14046. {
  14047. VmaBudget budgets[VK_MAX_MEMORY_HEAPS];
  14048. allocator->GetHeapBudgets(budgets, 0, allocator->GetMemoryHeapCount());
  14049. VmaTotalStatistics stats;
  14050. allocator->CalculateStatistics(&stats);
  14051. VmaJsonWriter json(allocator->GetAllocationCallbacks(), sb);
  14052. json.BeginObject();
  14053. {
  14054. json.WriteString("General");
  14055. json.BeginObject();
  14056. {
  14057. const VkPhysicalDeviceProperties& deviceProperties = allocator->m_PhysicalDeviceProperties;
  14058. const VkPhysicalDeviceMemoryProperties& memoryProperties = allocator->m_MemProps;
  14059. json.WriteString("API");
  14060. json.WriteString("Vulkan");
  14061. json.WriteString("apiVersion");
  14062. json.BeginString();
  14063. json.ContinueString(VK_API_VERSION_MAJOR(deviceProperties.apiVersion));
  14064. json.ContinueString(".");
  14065. json.ContinueString(VK_API_VERSION_MINOR(deviceProperties.apiVersion));
  14066. json.ContinueString(".");
  14067. json.ContinueString(VK_API_VERSION_PATCH(deviceProperties.apiVersion));
  14068. json.EndString();
  14069. json.WriteString("GPU");
  14070. json.WriteString(deviceProperties.deviceName);
  14071. json.WriteString("deviceType");
  14072. json.WriteNumber(static_cast<uint32_t>(deviceProperties.deviceType));
  14073. json.WriteString("maxMemoryAllocationCount");
  14074. json.WriteNumber(deviceProperties.limits.maxMemoryAllocationCount);
  14075. json.WriteString("bufferImageGranularity");
  14076. json.WriteNumber(deviceProperties.limits.bufferImageGranularity);
  14077. json.WriteString("nonCoherentAtomSize");
  14078. json.WriteNumber(deviceProperties.limits.nonCoherentAtomSize);
  14079. json.WriteString("memoryHeapCount");
  14080. json.WriteNumber(memoryProperties.memoryHeapCount);
  14081. json.WriteString("memoryTypeCount");
  14082. json.WriteNumber(memoryProperties.memoryTypeCount);
  14083. }
  14084. json.EndObject();
  14085. }
  14086. {
  14087. json.WriteString("Total");
  14088. VmaPrintDetailedStatistics(json, stats.total);
  14089. }
  14090. {
  14091. json.WriteString("MemoryInfo");
  14092. json.BeginObject();
  14093. {
  14094. for (uint32_t heapIndex = 0; heapIndex < allocator->GetMemoryHeapCount(); ++heapIndex)
  14095. {
  14096. json.BeginString("Heap ");
  14097. json.ContinueString(heapIndex);
  14098. json.EndString();
  14099. json.BeginObject();
  14100. {
  14101. const VkMemoryHeap& heapInfo = allocator->m_MemProps.memoryHeaps[heapIndex];
  14102. json.WriteString("Flags");
  14103. json.BeginArray(true);
  14104. {
  14105. if (heapInfo.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT)
  14106. json.WriteString("DEVICE_LOCAL");
  14107. #if VMA_VULKAN_VERSION >= 1001000
  14108. if (heapInfo.flags & VK_MEMORY_HEAP_MULTI_INSTANCE_BIT)
  14109. json.WriteString("MULTI_INSTANCE");
  14110. #endif
  14111. VkMemoryHeapFlags flags = heapInfo.flags &
  14112. ~(VK_MEMORY_HEAP_DEVICE_LOCAL_BIT
  14113. #if VMA_VULKAN_VERSION >= 1001000
  14114. | VK_MEMORY_HEAP_MULTI_INSTANCE_BIT
  14115. #endif
  14116. );
  14117. if (flags != 0)
  14118. json.WriteNumber(flags);
  14119. }
  14120. json.EndArray();
  14121. json.WriteString("Size");
  14122. json.WriteNumber(heapInfo.size);
  14123. json.WriteString("Budget");
  14124. json.BeginObject();
  14125. {
  14126. json.WriteString("BudgetBytes");
  14127. json.WriteNumber(budgets[heapIndex].budget);
  14128. json.WriteString("UsageBytes");
  14129. json.WriteNumber(budgets[heapIndex].usage);
  14130. }
  14131. json.EndObject();
  14132. json.WriteString("Stats");
  14133. VmaPrintDetailedStatistics(json, stats.memoryHeap[heapIndex]);
  14134. json.WriteString("MemoryPools");
  14135. json.BeginObject();
  14136. {
  14137. for (uint32_t typeIndex = 0; typeIndex < allocator->GetMemoryTypeCount(); ++typeIndex)
  14138. {
  14139. if (allocator->MemoryTypeIndexToHeapIndex(typeIndex) == heapIndex)
  14140. {
  14141. json.BeginString("Type ");
  14142. json.ContinueString(typeIndex);
  14143. json.EndString();
  14144. json.BeginObject();
  14145. {
  14146. json.WriteString("Flags");
  14147. json.BeginArray(true);
  14148. {
  14149. VkMemoryPropertyFlags flags = allocator->m_MemProps.memoryTypes[typeIndex].propertyFlags;
  14150. if (flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)
  14151. json.WriteString("DEVICE_LOCAL");
  14152. if (flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
  14153. json.WriteString("HOST_VISIBLE");
  14154. if (flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
  14155. json.WriteString("HOST_COHERENT");
  14156. if (flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT)
  14157. json.WriteString("HOST_CACHED");
  14158. if (flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT)
  14159. json.WriteString("LAZILY_ALLOCATED");
  14160. #if VMA_VULKAN_VERSION >= 1001000
  14161. if (flags & VK_MEMORY_PROPERTY_PROTECTED_BIT)
  14162. json.WriteString("PROTECTED");
  14163. #endif
  14164. #if VK_AMD_device_coherent_memory
  14165. if (flags & VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY)
  14166. json.WriteString("DEVICE_COHERENT_AMD");
  14167. if (flags & VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY)
  14168. json.WriteString("DEVICE_UNCACHED_AMD");
  14169. #endif
  14170. flags &= ~(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT
  14171. #if VMA_VULKAN_VERSION >= 1001000
  14172. | VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT
  14173. #endif
  14174. #if VK_AMD_device_coherent_memory
  14175. | VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY
  14176. | VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY
  14177. #endif
  14178. | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT
  14179. | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT
  14180. | VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
  14181. if (flags != 0)
  14182. json.WriteNumber(flags);
  14183. }
  14184. json.EndArray();
  14185. json.WriteString("Stats");
  14186. VmaPrintDetailedStatistics(json, stats.memoryType[typeIndex]);
  14187. }
  14188. json.EndObject();
  14189. }
  14190. }
  14191. }
  14192. json.EndObject();
  14193. }
  14194. json.EndObject();
  14195. }
  14196. }
  14197. json.EndObject();
  14198. }
  14199. if (detailedMap == VK_TRUE)
  14200. allocator->PrintDetailedMap(json);
  14201. json.EndObject();
  14202. }
  14203. *ppStatsString = VmaCreateStringCopy(allocator->GetAllocationCallbacks(), sb.GetData(), sb.GetLength());
  14204. }
  14205. VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString(
  14206. VmaAllocator allocator,
  14207. char* pStatsString)
  14208. {
  14209. if(pStatsString != VMA_NULL)
  14210. {
  14211. VMA_ASSERT(allocator);
  14212. VmaFreeString(allocator->GetAllocationCallbacks(), pStatsString);
  14213. }
  14214. }
  14215. #endif // VMA_STATS_STRING_ENABLED
  14216. /*
  14217. This function is not protected by any mutex because it just reads immutable data.
  14218. */
  14219. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex(
  14220. VmaAllocator allocator,
  14221. uint32_t memoryTypeBits,
  14222. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14223. uint32_t* pMemoryTypeIndex)
  14224. {
  14225. VMA_ASSERT(allocator != VK_NULL_HANDLE);
  14226. VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
  14227. VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
  14228. return allocator->FindMemoryTypeIndex(memoryTypeBits, pAllocationCreateInfo, UINT32_MAX, pMemoryTypeIndex);
  14229. }
  14230. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo(
  14231. VmaAllocator allocator,
  14232. const VkBufferCreateInfo* pBufferCreateInfo,
  14233. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14234. uint32_t* pMemoryTypeIndex)
  14235. {
  14236. VMA_ASSERT(allocator != VK_NULL_HANDLE);
  14237. VMA_ASSERT(pBufferCreateInfo != VMA_NULL);
  14238. VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
  14239. VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
  14240. const VkDevice hDev = allocator->m_hDevice;
  14241. const VmaVulkanFunctions* funcs = &allocator->GetVulkanFunctions();
  14242. VkResult res;
  14243. #if VMA_VULKAN_VERSION >= 1003000
  14244. if(funcs->vkGetDeviceBufferMemoryRequirements)
  14245. {
  14246. // Can query straight from VkBufferCreateInfo :)
  14247. VkDeviceBufferMemoryRequirements devBufMemReq = {VK_STRUCTURE_TYPE_DEVICE_BUFFER_MEMORY_REQUIREMENTS};
  14248. devBufMemReq.pCreateInfo = pBufferCreateInfo;
  14249. VkMemoryRequirements2 memReq = {VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2};
  14250. (*funcs->vkGetDeviceBufferMemoryRequirements)(hDev, &devBufMemReq, &memReq);
  14251. res = allocator->FindMemoryTypeIndex(
  14252. memReq.memoryRequirements.memoryTypeBits, pAllocationCreateInfo, pBufferCreateInfo->usage, pMemoryTypeIndex);
  14253. }
  14254. else
  14255. #endif // #if VMA_VULKAN_VERSION >= 1003000
  14256. {
  14257. // Must create a dummy buffer to query :(
  14258. VkBuffer hBuffer = VK_NULL_HANDLE;
  14259. res = funcs->vkCreateBuffer(
  14260. hDev, pBufferCreateInfo, allocator->GetAllocationCallbacks(), &hBuffer);
  14261. if(res == VK_SUCCESS)
  14262. {
  14263. VkMemoryRequirements memReq = {};
  14264. funcs->vkGetBufferMemoryRequirements(hDev, hBuffer, &memReq);
  14265. res = allocator->FindMemoryTypeIndex(
  14266. memReq.memoryTypeBits, pAllocationCreateInfo, pBufferCreateInfo->usage, pMemoryTypeIndex);
  14267. funcs->vkDestroyBuffer(
  14268. hDev, hBuffer, allocator->GetAllocationCallbacks());
  14269. }
  14270. }
  14271. return res;
  14272. }
  14273. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo(
  14274. VmaAllocator allocator,
  14275. const VkImageCreateInfo* pImageCreateInfo,
  14276. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14277. uint32_t* pMemoryTypeIndex)
  14278. {
  14279. VMA_ASSERT(allocator != VK_NULL_HANDLE);
  14280. VMA_ASSERT(pImageCreateInfo != VMA_NULL);
  14281. VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
  14282. VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
  14283. const VkDevice hDev = allocator->m_hDevice;
  14284. const VmaVulkanFunctions* funcs = &allocator->GetVulkanFunctions();
  14285. VkResult res;
  14286. #if VMA_VULKAN_VERSION >= 1003000
  14287. if(funcs->vkGetDeviceImageMemoryRequirements)
  14288. {
  14289. // Can query straight from VkImageCreateInfo :)
  14290. VkDeviceImageMemoryRequirements devImgMemReq = {VK_STRUCTURE_TYPE_DEVICE_IMAGE_MEMORY_REQUIREMENTS};
  14291. devImgMemReq.pCreateInfo = pImageCreateInfo;
  14292. VMA_ASSERT(pImageCreateInfo->tiling != VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT_COPY && (pImageCreateInfo->flags & VK_IMAGE_CREATE_DISJOINT_BIT_COPY) == 0 &&
  14293. "Cannot use this VkImageCreateInfo with vmaFindMemoryTypeIndexForImageInfo as I don't know what to pass as VkDeviceImageMemoryRequirements::planeAspect.");
  14294. VkMemoryRequirements2 memReq = {VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2};
  14295. (*funcs->vkGetDeviceImageMemoryRequirements)(hDev, &devImgMemReq, &memReq);
  14296. res = allocator->FindMemoryTypeIndex(
  14297. memReq.memoryRequirements.memoryTypeBits, pAllocationCreateInfo, pImageCreateInfo->usage, pMemoryTypeIndex);
  14298. }
  14299. else
  14300. #endif // #if VMA_VULKAN_VERSION >= 1003000
  14301. {
  14302. // Must create a dummy image to query :(
  14303. VkImage hImage = VK_NULL_HANDLE;
  14304. res = funcs->vkCreateImage(
  14305. hDev, pImageCreateInfo, allocator->GetAllocationCallbacks(), &hImage);
  14306. if(res == VK_SUCCESS)
  14307. {
  14308. VkMemoryRequirements memReq = {};
  14309. funcs->vkGetImageMemoryRequirements(hDev, hImage, &memReq);
  14310. res = allocator->FindMemoryTypeIndex(
  14311. memReq.memoryTypeBits, pAllocationCreateInfo, pImageCreateInfo->usage, pMemoryTypeIndex);
  14312. funcs->vkDestroyImage(
  14313. hDev, hImage, allocator->GetAllocationCallbacks());
  14314. }
  14315. }
  14316. return res;
  14317. }
  14318. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool(
  14319. VmaAllocator allocator,
  14320. const VmaPoolCreateInfo* pCreateInfo,
  14321. VmaPool* pPool)
  14322. {
  14323. VMA_ASSERT(allocator && pCreateInfo && pPool);
  14324. VMA_DEBUG_LOG("vmaCreatePool");
  14325. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14326. return allocator->CreatePool(pCreateInfo, pPool);
  14327. }
  14328. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool(
  14329. VmaAllocator allocator,
  14330. VmaPool pool)
  14331. {
  14332. VMA_ASSERT(allocator);
  14333. if(pool == VK_NULL_HANDLE)
  14334. {
  14335. return;
  14336. }
  14337. VMA_DEBUG_LOG("vmaDestroyPool");
  14338. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14339. allocator->DestroyPool(pool);
  14340. }
  14341. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStatistics(
  14342. VmaAllocator allocator,
  14343. VmaPool pool,
  14344. VmaStatistics* pPoolStats)
  14345. {
  14346. VMA_ASSERT(allocator && pool && pPoolStats);
  14347. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14348. allocator->GetPoolStatistics(pool, pPoolStats);
  14349. }
  14350. VMA_CALL_PRE void VMA_CALL_POST vmaCalculatePoolStatistics(
  14351. VmaAllocator allocator,
  14352. VmaPool pool,
  14353. VmaDetailedStatistics* pPoolStats)
  14354. {
  14355. VMA_ASSERT(allocator && pool && pPoolStats);
  14356. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14357. allocator->CalculatePoolStatistics(pool, pPoolStats);
  14358. }
  14359. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckPoolCorruption(VmaAllocator allocator, VmaPool pool)
  14360. {
  14361. VMA_ASSERT(allocator && pool);
  14362. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14363. VMA_DEBUG_LOG("vmaCheckPoolCorruption");
  14364. return allocator->CheckPoolCorruption(pool);
  14365. }
  14366. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName(
  14367. VmaAllocator allocator,
  14368. VmaPool pool,
  14369. const char** ppName)
  14370. {
  14371. VMA_ASSERT(allocator && pool && ppName);
  14372. VMA_DEBUG_LOG("vmaGetPoolName");
  14373. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14374. *ppName = pool->GetName();
  14375. }
  14376. VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName(
  14377. VmaAllocator allocator,
  14378. VmaPool pool,
  14379. const char* pName)
  14380. {
  14381. VMA_ASSERT(allocator && pool);
  14382. VMA_DEBUG_LOG("vmaSetPoolName");
  14383. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14384. pool->SetName(pName);
  14385. }
  14386. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory(
  14387. VmaAllocator allocator,
  14388. const VkMemoryRequirements* pVkMemoryRequirements,
  14389. const VmaAllocationCreateInfo* pCreateInfo,
  14390. VmaAllocation* pAllocation,
  14391. VmaAllocationInfo* pAllocationInfo)
  14392. {
  14393. VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocation);
  14394. VMA_DEBUG_LOG("vmaAllocateMemory");
  14395. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14396. VkResult result = allocator->AllocateMemory(
  14397. *pVkMemoryRequirements,
  14398. false, // requiresDedicatedAllocation
  14399. false, // prefersDedicatedAllocation
  14400. VK_NULL_HANDLE, // dedicatedBuffer
  14401. VK_NULL_HANDLE, // dedicatedImage
  14402. UINT32_MAX, // dedicatedBufferImageUsage
  14403. *pCreateInfo,
  14404. VMA_SUBALLOCATION_TYPE_UNKNOWN,
  14405. 1, // allocationCount
  14406. pAllocation);
  14407. if(pAllocationInfo != VMA_NULL && result == VK_SUCCESS)
  14408. {
  14409. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  14410. }
  14411. return result;
  14412. }
  14413. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages(
  14414. VmaAllocator allocator,
  14415. const VkMemoryRequirements* pVkMemoryRequirements,
  14416. const VmaAllocationCreateInfo* pCreateInfo,
  14417. size_t allocationCount,
  14418. VmaAllocation* pAllocations,
  14419. VmaAllocationInfo* pAllocationInfo)
  14420. {
  14421. if(allocationCount == 0)
  14422. {
  14423. return VK_SUCCESS;
  14424. }
  14425. VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocations);
  14426. VMA_DEBUG_LOG("vmaAllocateMemoryPages");
  14427. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14428. VkResult result = allocator->AllocateMemory(
  14429. *pVkMemoryRequirements,
  14430. false, // requiresDedicatedAllocation
  14431. false, // prefersDedicatedAllocation
  14432. VK_NULL_HANDLE, // dedicatedBuffer
  14433. VK_NULL_HANDLE, // dedicatedImage
  14434. UINT32_MAX, // dedicatedBufferImageUsage
  14435. *pCreateInfo,
  14436. VMA_SUBALLOCATION_TYPE_UNKNOWN,
  14437. allocationCount,
  14438. pAllocations);
  14439. if(pAllocationInfo != VMA_NULL && result == VK_SUCCESS)
  14440. {
  14441. for(size_t i = 0; i < allocationCount; ++i)
  14442. {
  14443. allocator->GetAllocationInfo(pAllocations[i], pAllocationInfo + i);
  14444. }
  14445. }
  14446. return result;
  14447. }
  14448. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer(
  14449. VmaAllocator allocator,
  14450. VkBuffer buffer,
  14451. const VmaAllocationCreateInfo* pCreateInfo,
  14452. VmaAllocation* pAllocation,
  14453. VmaAllocationInfo* pAllocationInfo)
  14454. {
  14455. VMA_ASSERT(allocator && buffer != VK_NULL_HANDLE && pCreateInfo && pAllocation);
  14456. VMA_DEBUG_LOG("vmaAllocateMemoryForBuffer");
  14457. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14458. VkMemoryRequirements vkMemReq = {};
  14459. bool requiresDedicatedAllocation = false;
  14460. bool prefersDedicatedAllocation = false;
  14461. allocator->GetBufferMemoryRequirements(buffer, vkMemReq,
  14462. requiresDedicatedAllocation,
  14463. prefersDedicatedAllocation);
  14464. VkResult result = allocator->AllocateMemory(
  14465. vkMemReq,
  14466. requiresDedicatedAllocation,
  14467. prefersDedicatedAllocation,
  14468. buffer, // dedicatedBuffer
  14469. VK_NULL_HANDLE, // dedicatedImage
  14470. UINT32_MAX, // dedicatedBufferImageUsage
  14471. *pCreateInfo,
  14472. VMA_SUBALLOCATION_TYPE_BUFFER,
  14473. 1, // allocationCount
  14474. pAllocation);
  14475. if(pAllocationInfo && result == VK_SUCCESS)
  14476. {
  14477. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  14478. }
  14479. return result;
  14480. }
  14481. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage(
  14482. VmaAllocator allocator,
  14483. VkImage image,
  14484. const VmaAllocationCreateInfo* pCreateInfo,
  14485. VmaAllocation* pAllocation,
  14486. VmaAllocationInfo* pAllocationInfo)
  14487. {
  14488. VMA_ASSERT(allocator && image != VK_NULL_HANDLE && pCreateInfo && pAllocation);
  14489. VMA_DEBUG_LOG("vmaAllocateMemoryForImage");
  14490. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14491. VkMemoryRequirements vkMemReq = {};
  14492. bool requiresDedicatedAllocation = false;
  14493. bool prefersDedicatedAllocation = false;
  14494. allocator->GetImageMemoryRequirements(image, vkMemReq,
  14495. requiresDedicatedAllocation, prefersDedicatedAllocation);
  14496. VkResult result = allocator->AllocateMemory(
  14497. vkMemReq,
  14498. requiresDedicatedAllocation,
  14499. prefersDedicatedAllocation,
  14500. VK_NULL_HANDLE, // dedicatedBuffer
  14501. image, // dedicatedImage
  14502. UINT32_MAX, // dedicatedBufferImageUsage
  14503. *pCreateInfo,
  14504. VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN,
  14505. 1, // allocationCount
  14506. pAllocation);
  14507. if(pAllocationInfo && result == VK_SUCCESS)
  14508. {
  14509. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  14510. }
  14511. return result;
  14512. }
  14513. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory(
  14514. VmaAllocator allocator,
  14515. VmaAllocation allocation)
  14516. {
  14517. VMA_ASSERT(allocator);
  14518. if(allocation == VK_NULL_HANDLE)
  14519. {
  14520. return;
  14521. }
  14522. VMA_DEBUG_LOG("vmaFreeMemory");
  14523. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14524. allocator->FreeMemory(
  14525. 1, // allocationCount
  14526. &allocation);
  14527. }
  14528. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages(
  14529. VmaAllocator allocator,
  14530. size_t allocationCount,
  14531. const VmaAllocation* pAllocations)
  14532. {
  14533. if(allocationCount == 0)
  14534. {
  14535. return;
  14536. }
  14537. VMA_ASSERT(allocator);
  14538. VMA_DEBUG_LOG("vmaFreeMemoryPages");
  14539. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14540. allocator->FreeMemory(allocationCount, pAllocations);
  14541. }
  14542. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo(
  14543. VmaAllocator allocator,
  14544. VmaAllocation allocation,
  14545. VmaAllocationInfo* pAllocationInfo)
  14546. {
  14547. VMA_ASSERT(allocator && allocation && pAllocationInfo);
  14548. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14549. allocator->GetAllocationInfo(allocation, pAllocationInfo);
  14550. }
  14551. VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData(
  14552. VmaAllocator allocator,
  14553. VmaAllocation allocation,
  14554. void* pUserData)
  14555. {
  14556. VMA_ASSERT(allocator && allocation);
  14557. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14558. allocation->SetUserData(allocator, pUserData);
  14559. }
  14560. VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationName(
  14561. VmaAllocator VMA_NOT_NULL allocator,
  14562. VmaAllocation VMA_NOT_NULL allocation,
  14563. const char* VMA_NULLABLE pName)
  14564. {
  14565. allocation->SetName(allocator, pName);
  14566. }
  14567. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationMemoryProperties(
  14568. VmaAllocator VMA_NOT_NULL allocator,
  14569. VmaAllocation VMA_NOT_NULL allocation,
  14570. VkMemoryPropertyFlags* VMA_NOT_NULL pFlags)
  14571. {
  14572. VMA_ASSERT(allocator && allocation && pFlags);
  14573. const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
  14574. *pFlags = allocator->m_MemProps.memoryTypes[memTypeIndex].propertyFlags;
  14575. }
  14576. VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory(
  14577. VmaAllocator allocator,
  14578. VmaAllocation allocation,
  14579. void** ppData)
  14580. {
  14581. VMA_ASSERT(allocator && allocation && ppData);
  14582. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14583. return allocator->Map(allocation, ppData);
  14584. }
  14585. VMA_CALL_PRE void VMA_CALL_POST vmaUnmapMemory(
  14586. VmaAllocator allocator,
  14587. VmaAllocation allocation)
  14588. {
  14589. VMA_ASSERT(allocator && allocation);
  14590. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14591. allocator->Unmap(allocation);
  14592. }
  14593. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocation(
  14594. VmaAllocator allocator,
  14595. VmaAllocation allocation,
  14596. VkDeviceSize offset,
  14597. VkDeviceSize size)
  14598. {
  14599. VMA_ASSERT(allocator && allocation);
  14600. VMA_DEBUG_LOG("vmaFlushAllocation");
  14601. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14602. const VkResult res = allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_FLUSH);
  14603. return res;
  14604. }
  14605. VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocation(
  14606. VmaAllocator allocator,
  14607. VmaAllocation allocation,
  14608. VkDeviceSize offset,
  14609. VkDeviceSize size)
  14610. {
  14611. VMA_ASSERT(allocator && allocation);
  14612. VMA_DEBUG_LOG("vmaInvalidateAllocation");
  14613. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14614. const VkResult res = allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_INVALIDATE);
  14615. return res;
  14616. }
  14617. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocations(
  14618. VmaAllocator allocator,
  14619. uint32_t allocationCount,
  14620. const VmaAllocation* allocations,
  14621. const VkDeviceSize* offsets,
  14622. const VkDeviceSize* sizes)
  14623. {
  14624. VMA_ASSERT(allocator);
  14625. if(allocationCount == 0)
  14626. {
  14627. return VK_SUCCESS;
  14628. }
  14629. VMA_ASSERT(allocations);
  14630. VMA_DEBUG_LOG("vmaFlushAllocations");
  14631. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14632. const VkResult res = allocator->FlushOrInvalidateAllocations(allocationCount, allocations, offsets, sizes, VMA_CACHE_FLUSH);
  14633. return res;
  14634. }
  14635. VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocations(
  14636. VmaAllocator allocator,
  14637. uint32_t allocationCount,
  14638. const VmaAllocation* allocations,
  14639. const VkDeviceSize* offsets,
  14640. const VkDeviceSize* sizes)
  14641. {
  14642. VMA_ASSERT(allocator);
  14643. if(allocationCount == 0)
  14644. {
  14645. return VK_SUCCESS;
  14646. }
  14647. VMA_ASSERT(allocations);
  14648. VMA_DEBUG_LOG("vmaInvalidateAllocations");
  14649. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14650. const VkResult res = allocator->FlushOrInvalidateAllocations(allocationCount, allocations, offsets, sizes, VMA_CACHE_INVALIDATE);
  14651. return res;
  14652. }
  14653. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckCorruption(
  14654. VmaAllocator allocator,
  14655. uint32_t memoryTypeBits)
  14656. {
  14657. VMA_ASSERT(allocator);
  14658. VMA_DEBUG_LOG("vmaCheckCorruption");
  14659. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14660. return allocator->CheckCorruption(memoryTypeBits);
  14661. }
  14662. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentation(
  14663. VmaAllocator allocator,
  14664. const VmaDefragmentationInfo* pInfo,
  14665. VmaDefragmentationContext* pContext)
  14666. {
  14667. VMA_ASSERT(allocator && pInfo && pContext);
  14668. VMA_DEBUG_LOG("vmaBeginDefragmentation");
  14669. if (pInfo->pool != VMA_NULL)
  14670. {
  14671. // Check if run on supported algorithms
  14672. if (pInfo->pool->m_BlockVector.GetAlgorithm() & VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT)
  14673. return VK_ERROR_FEATURE_NOT_PRESENT;
  14674. }
  14675. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14676. *pContext = vma_new(allocator, VmaDefragmentationContext_T)(allocator, *pInfo);
  14677. return VK_SUCCESS;
  14678. }
  14679. VMA_CALL_PRE void VMA_CALL_POST vmaEndDefragmentation(
  14680. VmaAllocator allocator,
  14681. VmaDefragmentationContext context,
  14682. VmaDefragmentationStats* pStats)
  14683. {
  14684. VMA_ASSERT(allocator && context);
  14685. VMA_DEBUG_LOG("vmaEndDefragmentation");
  14686. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14687. if (pStats)
  14688. context->GetStats(*pStats);
  14689. vma_delete(allocator, context);
  14690. }
  14691. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentationPass(
  14692. VmaAllocator VMA_NOT_NULL allocator,
  14693. VmaDefragmentationContext VMA_NOT_NULL context,
  14694. VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo)
  14695. {
  14696. VMA_ASSERT(context && pPassInfo);
  14697. VMA_DEBUG_LOG("vmaBeginDefragmentationPass");
  14698. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14699. return context->DefragmentPassBegin(*pPassInfo);
  14700. }
  14701. VMA_CALL_PRE VkResult VMA_CALL_POST vmaEndDefragmentationPass(
  14702. VmaAllocator VMA_NOT_NULL allocator,
  14703. VmaDefragmentationContext VMA_NOT_NULL context,
  14704. VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo)
  14705. {
  14706. VMA_ASSERT(context && pPassInfo);
  14707. VMA_DEBUG_LOG("vmaEndDefragmentationPass");
  14708. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14709. return context->DefragmentPassEnd(*pPassInfo);
  14710. }
  14711. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory(
  14712. VmaAllocator allocator,
  14713. VmaAllocation allocation,
  14714. VkBuffer buffer)
  14715. {
  14716. VMA_ASSERT(allocator && allocation && buffer);
  14717. VMA_DEBUG_LOG("vmaBindBufferMemory");
  14718. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14719. return allocator->BindBufferMemory(allocation, 0, buffer, VMA_NULL);
  14720. }
  14721. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2(
  14722. VmaAllocator allocator,
  14723. VmaAllocation allocation,
  14724. VkDeviceSize allocationLocalOffset,
  14725. VkBuffer buffer,
  14726. const void* pNext)
  14727. {
  14728. VMA_ASSERT(allocator && allocation && buffer);
  14729. VMA_DEBUG_LOG("vmaBindBufferMemory2");
  14730. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14731. return allocator->BindBufferMemory(allocation, allocationLocalOffset, buffer, pNext);
  14732. }
  14733. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory(
  14734. VmaAllocator allocator,
  14735. VmaAllocation allocation,
  14736. VkImage image)
  14737. {
  14738. VMA_ASSERT(allocator && allocation && image);
  14739. VMA_DEBUG_LOG("vmaBindImageMemory");
  14740. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14741. return allocator->BindImageMemory(allocation, 0, image, VMA_NULL);
  14742. }
  14743. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2(
  14744. VmaAllocator allocator,
  14745. VmaAllocation allocation,
  14746. VkDeviceSize allocationLocalOffset,
  14747. VkImage image,
  14748. const void* pNext)
  14749. {
  14750. VMA_ASSERT(allocator && allocation && image);
  14751. VMA_DEBUG_LOG("vmaBindImageMemory2");
  14752. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14753. return allocator->BindImageMemory(allocation, allocationLocalOffset, image, pNext);
  14754. }
  14755. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer(
  14756. VmaAllocator allocator,
  14757. const VkBufferCreateInfo* pBufferCreateInfo,
  14758. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14759. VkBuffer* pBuffer,
  14760. VmaAllocation* pAllocation,
  14761. VmaAllocationInfo* pAllocationInfo)
  14762. {
  14763. VMA_ASSERT(allocator && pBufferCreateInfo && pAllocationCreateInfo && pBuffer && pAllocation);
  14764. if(pBufferCreateInfo->size == 0)
  14765. {
  14766. return VK_ERROR_INITIALIZATION_FAILED;
  14767. }
  14768. if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY) != 0 &&
  14769. !allocator->m_UseKhrBufferDeviceAddress)
  14770. {
  14771. 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.");
  14772. return VK_ERROR_INITIALIZATION_FAILED;
  14773. }
  14774. VMA_DEBUG_LOG("vmaCreateBuffer");
  14775. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14776. *pBuffer = VK_NULL_HANDLE;
  14777. *pAllocation = VK_NULL_HANDLE;
  14778. // 1. Create VkBuffer.
  14779. VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)(
  14780. allocator->m_hDevice,
  14781. pBufferCreateInfo,
  14782. allocator->GetAllocationCallbacks(),
  14783. pBuffer);
  14784. if(res >= 0)
  14785. {
  14786. // 2. vkGetBufferMemoryRequirements.
  14787. VkMemoryRequirements vkMemReq = {};
  14788. bool requiresDedicatedAllocation = false;
  14789. bool prefersDedicatedAllocation = false;
  14790. allocator->GetBufferMemoryRequirements(*pBuffer, vkMemReq,
  14791. requiresDedicatedAllocation, prefersDedicatedAllocation);
  14792. // 3. Allocate memory using allocator.
  14793. res = allocator->AllocateMemory(
  14794. vkMemReq,
  14795. requiresDedicatedAllocation,
  14796. prefersDedicatedAllocation,
  14797. *pBuffer, // dedicatedBuffer
  14798. VK_NULL_HANDLE, // dedicatedImage
  14799. pBufferCreateInfo->usage, // dedicatedBufferImageUsage
  14800. *pAllocationCreateInfo,
  14801. VMA_SUBALLOCATION_TYPE_BUFFER,
  14802. 1, // allocationCount
  14803. pAllocation);
  14804. if(res >= 0)
  14805. {
  14806. // 3. Bind buffer with memory.
  14807. if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0)
  14808. {
  14809. res = allocator->BindBufferMemory(*pAllocation, 0, *pBuffer, VMA_NULL);
  14810. }
  14811. if(res >= 0)
  14812. {
  14813. // All steps succeeded.
  14814. #if VMA_STATS_STRING_ENABLED
  14815. (*pAllocation)->InitBufferImageUsage(pBufferCreateInfo->usage);
  14816. #endif
  14817. if(pAllocationInfo != VMA_NULL)
  14818. {
  14819. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  14820. }
  14821. return VK_SUCCESS;
  14822. }
  14823. allocator->FreeMemory(
  14824. 1, // allocationCount
  14825. pAllocation);
  14826. *pAllocation = VK_NULL_HANDLE;
  14827. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
  14828. *pBuffer = VK_NULL_HANDLE;
  14829. return res;
  14830. }
  14831. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
  14832. *pBuffer = VK_NULL_HANDLE;
  14833. return res;
  14834. }
  14835. return res;
  14836. }
  14837. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBufferWithAlignment(
  14838. VmaAllocator allocator,
  14839. const VkBufferCreateInfo* pBufferCreateInfo,
  14840. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14841. VkDeviceSize minAlignment,
  14842. VkBuffer* pBuffer,
  14843. VmaAllocation* pAllocation,
  14844. VmaAllocationInfo* pAllocationInfo)
  14845. {
  14846. VMA_ASSERT(allocator && pBufferCreateInfo && pAllocationCreateInfo && VmaIsPow2(minAlignment) && pBuffer && pAllocation);
  14847. if(pBufferCreateInfo->size == 0)
  14848. {
  14849. return VK_ERROR_INITIALIZATION_FAILED;
  14850. }
  14851. if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY) != 0 &&
  14852. !allocator->m_UseKhrBufferDeviceAddress)
  14853. {
  14854. 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.");
  14855. return VK_ERROR_INITIALIZATION_FAILED;
  14856. }
  14857. VMA_DEBUG_LOG("vmaCreateBufferWithAlignment");
  14858. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14859. *pBuffer = VK_NULL_HANDLE;
  14860. *pAllocation = VK_NULL_HANDLE;
  14861. // 1. Create VkBuffer.
  14862. VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)(
  14863. allocator->m_hDevice,
  14864. pBufferCreateInfo,
  14865. allocator->GetAllocationCallbacks(),
  14866. pBuffer);
  14867. if(res >= 0)
  14868. {
  14869. // 2. vkGetBufferMemoryRequirements.
  14870. VkMemoryRequirements vkMemReq = {};
  14871. bool requiresDedicatedAllocation = false;
  14872. bool prefersDedicatedAllocation = false;
  14873. allocator->GetBufferMemoryRequirements(*pBuffer, vkMemReq,
  14874. requiresDedicatedAllocation, prefersDedicatedAllocation);
  14875. // 2a. Include minAlignment
  14876. vkMemReq.alignment = VMA_MAX(vkMemReq.alignment, minAlignment);
  14877. // 3. Allocate memory using allocator.
  14878. res = allocator->AllocateMemory(
  14879. vkMemReq,
  14880. requiresDedicatedAllocation,
  14881. prefersDedicatedAllocation,
  14882. *pBuffer, // dedicatedBuffer
  14883. VK_NULL_HANDLE, // dedicatedImage
  14884. pBufferCreateInfo->usage, // dedicatedBufferImageUsage
  14885. *pAllocationCreateInfo,
  14886. VMA_SUBALLOCATION_TYPE_BUFFER,
  14887. 1, // allocationCount
  14888. pAllocation);
  14889. if(res >= 0)
  14890. {
  14891. // 3. Bind buffer with memory.
  14892. if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0)
  14893. {
  14894. res = allocator->BindBufferMemory(*pAllocation, 0, *pBuffer, VMA_NULL);
  14895. }
  14896. if(res >= 0)
  14897. {
  14898. // All steps succeeded.
  14899. #if VMA_STATS_STRING_ENABLED
  14900. (*pAllocation)->InitBufferImageUsage(pBufferCreateInfo->usage);
  14901. #endif
  14902. if(pAllocationInfo != VMA_NULL)
  14903. {
  14904. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  14905. }
  14906. return VK_SUCCESS;
  14907. }
  14908. allocator->FreeMemory(
  14909. 1, // allocationCount
  14910. pAllocation);
  14911. *pAllocation = VK_NULL_HANDLE;
  14912. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
  14913. *pBuffer = VK_NULL_HANDLE;
  14914. return res;
  14915. }
  14916. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
  14917. *pBuffer = VK_NULL_HANDLE;
  14918. return res;
  14919. }
  14920. return res;
  14921. }
  14922. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingBuffer(
  14923. VmaAllocator VMA_NOT_NULL allocator,
  14924. VmaAllocation VMA_NOT_NULL allocation,
  14925. const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo,
  14926. VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer)
  14927. {
  14928. VMA_ASSERT(allocator && pBufferCreateInfo && pBuffer && allocation);
  14929. VMA_DEBUG_LOG("vmaCreateAliasingBuffer");
  14930. *pBuffer = VK_NULL_HANDLE;
  14931. if (pBufferCreateInfo->size == 0)
  14932. {
  14933. return VK_ERROR_INITIALIZATION_FAILED;
  14934. }
  14935. if ((pBufferCreateInfo->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY) != 0 &&
  14936. !allocator->m_UseKhrBufferDeviceAddress)
  14937. {
  14938. 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.");
  14939. return VK_ERROR_INITIALIZATION_FAILED;
  14940. }
  14941. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14942. // 1. Create VkBuffer.
  14943. VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)(
  14944. allocator->m_hDevice,
  14945. pBufferCreateInfo,
  14946. allocator->GetAllocationCallbacks(),
  14947. pBuffer);
  14948. if (res >= 0)
  14949. {
  14950. // 2. Bind buffer with memory.
  14951. res = allocator->BindBufferMemory(allocation, 0, *pBuffer, VMA_NULL);
  14952. if (res >= 0)
  14953. {
  14954. return VK_SUCCESS;
  14955. }
  14956. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
  14957. }
  14958. return res;
  14959. }
  14960. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer(
  14961. VmaAllocator allocator,
  14962. VkBuffer buffer,
  14963. VmaAllocation allocation)
  14964. {
  14965. VMA_ASSERT(allocator);
  14966. if(buffer == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE)
  14967. {
  14968. return;
  14969. }
  14970. VMA_DEBUG_LOG("vmaDestroyBuffer");
  14971. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14972. if(buffer != VK_NULL_HANDLE)
  14973. {
  14974. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, buffer, allocator->GetAllocationCallbacks());
  14975. }
  14976. if(allocation != VK_NULL_HANDLE)
  14977. {
  14978. allocator->FreeMemory(
  14979. 1, // allocationCount
  14980. &allocation);
  14981. }
  14982. }
  14983. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage(
  14984. VmaAllocator allocator,
  14985. const VkImageCreateInfo* pImageCreateInfo,
  14986. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14987. VkImage* pImage,
  14988. VmaAllocation* pAllocation,
  14989. VmaAllocationInfo* pAllocationInfo)
  14990. {
  14991. VMA_ASSERT(allocator && pImageCreateInfo && pAllocationCreateInfo && pImage && pAllocation);
  14992. if(pImageCreateInfo->extent.width == 0 ||
  14993. pImageCreateInfo->extent.height == 0 ||
  14994. pImageCreateInfo->extent.depth == 0 ||
  14995. pImageCreateInfo->mipLevels == 0 ||
  14996. pImageCreateInfo->arrayLayers == 0)
  14997. {
  14998. return VK_ERROR_INITIALIZATION_FAILED;
  14999. }
  15000. VMA_DEBUG_LOG("vmaCreateImage");
  15001. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15002. *pImage = VK_NULL_HANDLE;
  15003. *pAllocation = VK_NULL_HANDLE;
  15004. // 1. Create VkImage.
  15005. VkResult res = (*allocator->GetVulkanFunctions().vkCreateImage)(
  15006. allocator->m_hDevice,
  15007. pImageCreateInfo,
  15008. allocator->GetAllocationCallbacks(),
  15009. pImage);
  15010. if(res >= 0)
  15011. {
  15012. VmaSuballocationType suballocType = pImageCreateInfo->tiling == VK_IMAGE_TILING_OPTIMAL ?
  15013. VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL :
  15014. VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR;
  15015. // 2. Allocate memory using allocator.
  15016. VkMemoryRequirements vkMemReq = {};
  15017. bool requiresDedicatedAllocation = false;
  15018. bool prefersDedicatedAllocation = false;
  15019. allocator->GetImageMemoryRequirements(*pImage, vkMemReq,
  15020. requiresDedicatedAllocation, prefersDedicatedAllocation);
  15021. res = allocator->AllocateMemory(
  15022. vkMemReq,
  15023. requiresDedicatedAllocation,
  15024. prefersDedicatedAllocation,
  15025. VK_NULL_HANDLE, // dedicatedBuffer
  15026. *pImage, // dedicatedImage
  15027. pImageCreateInfo->usage, // dedicatedBufferImageUsage
  15028. *pAllocationCreateInfo,
  15029. suballocType,
  15030. 1, // allocationCount
  15031. pAllocation);
  15032. if(res >= 0)
  15033. {
  15034. // 3. Bind image with memory.
  15035. if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0)
  15036. {
  15037. res = allocator->BindImageMemory(*pAllocation, 0, *pImage, VMA_NULL);
  15038. }
  15039. if(res >= 0)
  15040. {
  15041. // All steps succeeded.
  15042. #if VMA_STATS_STRING_ENABLED
  15043. (*pAllocation)->InitBufferImageUsage(pImageCreateInfo->usage);
  15044. #endif
  15045. if(pAllocationInfo != VMA_NULL)
  15046. {
  15047. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  15048. }
  15049. return VK_SUCCESS;
  15050. }
  15051. allocator->FreeMemory(
  15052. 1, // allocationCount
  15053. pAllocation);
  15054. *pAllocation = VK_NULL_HANDLE;
  15055. (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks());
  15056. *pImage = VK_NULL_HANDLE;
  15057. return res;
  15058. }
  15059. (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks());
  15060. *pImage = VK_NULL_HANDLE;
  15061. return res;
  15062. }
  15063. return res;
  15064. }
  15065. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingImage(
  15066. VmaAllocator VMA_NOT_NULL allocator,
  15067. VmaAllocation VMA_NOT_NULL allocation,
  15068. const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo,
  15069. VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage)
  15070. {
  15071. VMA_ASSERT(allocator && pImageCreateInfo && pImage && allocation);
  15072. *pImage = VK_NULL_HANDLE;
  15073. VMA_DEBUG_LOG("vmaCreateImage");
  15074. if (pImageCreateInfo->extent.width == 0 ||
  15075. pImageCreateInfo->extent.height == 0 ||
  15076. pImageCreateInfo->extent.depth == 0 ||
  15077. pImageCreateInfo->mipLevels == 0 ||
  15078. pImageCreateInfo->arrayLayers == 0)
  15079. {
  15080. return VK_ERROR_INITIALIZATION_FAILED;
  15081. }
  15082. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15083. // 1. Create VkImage.
  15084. VkResult res = (*allocator->GetVulkanFunctions().vkCreateImage)(
  15085. allocator->m_hDevice,
  15086. pImageCreateInfo,
  15087. allocator->GetAllocationCallbacks(),
  15088. pImage);
  15089. if (res >= 0)
  15090. {
  15091. // 2. Bind image with memory.
  15092. res = allocator->BindImageMemory(allocation, 0, *pImage, VMA_NULL);
  15093. if (res >= 0)
  15094. {
  15095. return VK_SUCCESS;
  15096. }
  15097. (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks());
  15098. }
  15099. return res;
  15100. }
  15101. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyImage(
  15102. VmaAllocator VMA_NOT_NULL allocator,
  15103. VkImage VMA_NULLABLE_NON_DISPATCHABLE image,
  15104. VmaAllocation VMA_NULLABLE allocation)
  15105. {
  15106. VMA_ASSERT(allocator);
  15107. if(image == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE)
  15108. {
  15109. return;
  15110. }
  15111. VMA_DEBUG_LOG("vmaDestroyImage");
  15112. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15113. if(image != VK_NULL_HANDLE)
  15114. {
  15115. (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, image, allocator->GetAllocationCallbacks());
  15116. }
  15117. if(allocation != VK_NULL_HANDLE)
  15118. {
  15119. allocator->FreeMemory(
  15120. 1, // allocationCount
  15121. &allocation);
  15122. }
  15123. }
  15124. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateVirtualBlock(
  15125. const VmaVirtualBlockCreateInfo* VMA_NOT_NULL pCreateInfo,
  15126. VmaVirtualBlock VMA_NULLABLE * VMA_NOT_NULL pVirtualBlock)
  15127. {
  15128. VMA_ASSERT(pCreateInfo && pVirtualBlock);
  15129. VMA_ASSERT(pCreateInfo->size > 0);
  15130. VMA_DEBUG_LOG("vmaCreateVirtualBlock");
  15131. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15132. *pVirtualBlock = vma_new(pCreateInfo->pAllocationCallbacks, VmaVirtualBlock_T)(*pCreateInfo);
  15133. VkResult res = (*pVirtualBlock)->Init();
  15134. if(res < 0)
  15135. {
  15136. vma_delete(pCreateInfo->pAllocationCallbacks, *pVirtualBlock);
  15137. *pVirtualBlock = VK_NULL_HANDLE;
  15138. }
  15139. return res;
  15140. }
  15141. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyVirtualBlock(VmaVirtualBlock VMA_NULLABLE virtualBlock)
  15142. {
  15143. if(virtualBlock != VK_NULL_HANDLE)
  15144. {
  15145. VMA_DEBUG_LOG("vmaDestroyVirtualBlock");
  15146. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15147. VkAllocationCallbacks allocationCallbacks = virtualBlock->m_AllocationCallbacks; // Have to copy the callbacks when destroying.
  15148. vma_delete(&allocationCallbacks, virtualBlock);
  15149. }
  15150. }
  15151. VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaIsVirtualBlockEmpty(VmaVirtualBlock VMA_NOT_NULL virtualBlock)
  15152. {
  15153. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE);
  15154. VMA_DEBUG_LOG("vmaIsVirtualBlockEmpty");
  15155. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15156. return virtualBlock->IsEmpty() ? VK_TRUE : VK_FALSE;
  15157. }
  15158. VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualAllocationInfo(VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  15159. VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation, VmaVirtualAllocationInfo* VMA_NOT_NULL pVirtualAllocInfo)
  15160. {
  15161. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pVirtualAllocInfo != VMA_NULL);
  15162. VMA_DEBUG_LOG("vmaGetVirtualAllocationInfo");
  15163. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15164. virtualBlock->GetAllocationInfo(allocation, *pVirtualAllocInfo);
  15165. }
  15166. VMA_CALL_PRE VkResult VMA_CALL_POST vmaVirtualAllocate(VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  15167. const VmaVirtualAllocationCreateInfo* VMA_NOT_NULL pCreateInfo, VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pAllocation,
  15168. VkDeviceSize* VMA_NULLABLE pOffset)
  15169. {
  15170. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pCreateInfo != VMA_NULL && pAllocation != VMA_NULL);
  15171. VMA_DEBUG_LOG("vmaVirtualAllocate");
  15172. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15173. return virtualBlock->Allocate(*pCreateInfo, *pAllocation, pOffset);
  15174. }
  15175. VMA_CALL_PRE void VMA_CALL_POST vmaVirtualFree(VmaVirtualBlock VMA_NOT_NULL virtualBlock, VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE allocation)
  15176. {
  15177. if(allocation != VK_NULL_HANDLE)
  15178. {
  15179. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE);
  15180. VMA_DEBUG_LOG("vmaVirtualFree");
  15181. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15182. virtualBlock->Free(allocation);
  15183. }
  15184. }
  15185. VMA_CALL_PRE void VMA_CALL_POST vmaClearVirtualBlock(VmaVirtualBlock VMA_NOT_NULL virtualBlock)
  15186. {
  15187. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE);
  15188. VMA_DEBUG_LOG("vmaClearVirtualBlock");
  15189. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15190. virtualBlock->Clear();
  15191. }
  15192. VMA_CALL_PRE void VMA_CALL_POST vmaSetVirtualAllocationUserData(VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  15193. VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation, void* VMA_NULLABLE pUserData)
  15194. {
  15195. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE);
  15196. VMA_DEBUG_LOG("vmaSetVirtualAllocationUserData");
  15197. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15198. virtualBlock->SetAllocationUserData(allocation, pUserData);
  15199. }
  15200. VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualBlockStatistics(VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  15201. VmaStatistics* VMA_NOT_NULL pStats)
  15202. {
  15203. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pStats != VMA_NULL);
  15204. VMA_DEBUG_LOG("vmaGetVirtualBlockStatistics");
  15205. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15206. virtualBlock->GetStatistics(*pStats);
  15207. }
  15208. VMA_CALL_PRE void VMA_CALL_POST vmaCalculateVirtualBlockStatistics(VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  15209. VmaDetailedStatistics* VMA_NOT_NULL pStats)
  15210. {
  15211. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pStats != VMA_NULL);
  15212. VMA_DEBUG_LOG("vmaCalculateVirtualBlockStatistics");
  15213. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15214. virtualBlock->CalculateDetailedStatistics(*pStats);
  15215. }
  15216. #if VMA_STATS_STRING_ENABLED
  15217. VMA_CALL_PRE void VMA_CALL_POST vmaBuildVirtualBlockStatsString(VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  15218. char* VMA_NULLABLE * VMA_NOT_NULL ppStatsString, VkBool32 detailedMap)
  15219. {
  15220. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && ppStatsString != VMA_NULL);
  15221. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15222. const VkAllocationCallbacks* allocationCallbacks = virtualBlock->GetAllocationCallbacks();
  15223. VmaStringBuilder sb(allocationCallbacks);
  15224. virtualBlock->BuildStatsString(detailedMap != VK_FALSE, sb);
  15225. *ppStatsString = VmaCreateStringCopy(allocationCallbacks, sb.GetData(), sb.GetLength());
  15226. }
  15227. VMA_CALL_PRE void VMA_CALL_POST vmaFreeVirtualBlockStatsString(VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  15228. char* VMA_NULLABLE pStatsString)
  15229. {
  15230. if(pStatsString != VMA_NULL)
  15231. {
  15232. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE);
  15233. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15234. VmaFreeString(virtualBlock->GetAllocationCallbacks(), pStatsString);
  15235. }
  15236. }
  15237. #endif // VMA_STATS_STRING_ENABLED
  15238. #endif // _VMA_PUBLIC_INTERFACE
  15239. #endif // VMA_IMPLEMENTATION
  15240. /**
  15241. \page quick_start Quick start
  15242. \section quick_start_project_setup Project setup
  15243. Vulkan Memory Allocator comes in form of a "stb-style" single header file.
  15244. You don't need to build it as a separate library project.
  15245. You can add this file directly to your project and submit it to code repository next to your other source files.
  15246. "Single header" doesn't mean that everything is contained in C/C++ declarations,
  15247. like it tends to be in case of inline functions or C++ templates.
  15248. It means that implementation is bundled with interface in a single file and needs to be extracted using preprocessor macro.
  15249. If you don't do it properly, you will get linker errors.
  15250. To do it properly:
  15251. -# Include "vk_mem_alloc.h" file in each CPP file where you want to use the library.
  15252. This includes declarations of all members of the library.
  15253. -# In exactly one CPP file define following macro before this include.
  15254. It enables also internal definitions.
  15255. \code
  15256. #define VMA_IMPLEMENTATION
  15257. #include "vk_mem_alloc.h"
  15258. \endcode
  15259. It may be a good idea to create dedicated CPP file just for this purpose.
  15260. This library includes header `<vulkan/vulkan.h>`, which in turn
  15261. includes `<windows.h>` on Windows. If you need some specific macros defined
  15262. before including these headers (like `WIN32_LEAN_AND_MEAN` or
  15263. `WINVER` for Windows, `VK_USE_PLATFORM_WIN32_KHR` for Vulkan), you must define
  15264. them before every `#include` of this library.
  15265. This library is written in C++, but has C-compatible interface.
  15266. Thus you can include and use vk_mem_alloc.h in C or C++ code, but full
  15267. implementation with `VMA_IMPLEMENTATION` macro must be compiled as C++, NOT as C.
  15268. Some features of C++14 used. STL containers, RTTI, or C++ exceptions are not used.
  15269. \section quick_start_initialization Initialization
  15270. At program startup:
  15271. -# Initialize Vulkan to have `VkPhysicalDevice`, `VkDevice` and `VkInstance` object.
  15272. -# Fill VmaAllocatorCreateInfo structure and create #VmaAllocator object by
  15273. calling vmaCreateAllocator().
  15274. Only members `physicalDevice`, `device`, `instance` are required.
  15275. However, you should inform the library which Vulkan version do you use by setting
  15276. VmaAllocatorCreateInfo::vulkanApiVersion and which extensions did you enable
  15277. by setting VmaAllocatorCreateInfo::flags (like #VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT for VK_KHR_buffer_device_address).
  15278. Otherwise, VMA would use only features of Vulkan 1.0 core with no extensions.
  15279. You may need to configure importing Vulkan functions. There are 3 ways to do this:
  15280. -# **If you link with Vulkan static library** (e.g. "vulkan-1.lib" on Windows):
  15281. - You don't need to do anything.
  15282. - VMA will use these, as macro `VMA_STATIC_VULKAN_FUNCTIONS` is defined to 1 by default.
  15283. -# **If you want VMA to fetch pointers to Vulkan functions dynamically** using `vkGetInstanceProcAddr`,
  15284. `vkGetDeviceProcAddr` (this is the option presented in the example below):
  15285. - Define `VMA_STATIC_VULKAN_FUNCTIONS` to 0, `VMA_DYNAMIC_VULKAN_FUNCTIONS` to 1.
  15286. - Provide pointers to these two functions via VmaVulkanFunctions::vkGetInstanceProcAddr,
  15287. VmaVulkanFunctions::vkGetDeviceProcAddr.
  15288. - The library will fetch pointers to all other functions it needs internally.
  15289. -# **If you fetch pointers to all Vulkan functions in a custom way**, e.g. using some loader like
  15290. [Volk](https://github.com/zeux/volk):
  15291. - Define `VMA_STATIC_VULKAN_FUNCTIONS` and `VMA_DYNAMIC_VULKAN_FUNCTIONS` to 0.
  15292. - Pass these pointers via structure #VmaVulkanFunctions.
  15293. \code
  15294. VmaVulkanFunctions vulkanFunctions = {};
  15295. vulkanFunctions.vkGetInstanceProcAddr = &vkGetInstanceProcAddr;
  15296. vulkanFunctions.vkGetDeviceProcAddr = &vkGetDeviceProcAddr;
  15297. VmaAllocatorCreateInfo allocatorCreateInfo = {};
  15298. allocatorCreateInfo.vulkanApiVersion = VK_API_VERSION_1_2;
  15299. allocatorCreateInfo.physicalDevice = physicalDevice;
  15300. allocatorCreateInfo.device = device;
  15301. allocatorCreateInfo.instance = instance;
  15302. allocatorCreateInfo.pVulkanFunctions = &vulkanFunctions;
  15303. VmaAllocator allocator;
  15304. vmaCreateAllocator(&allocatorCreateInfo, &allocator);
  15305. \endcode
  15306. \section quick_start_resource_allocation Resource allocation
  15307. When you want to create a buffer or image:
  15308. -# Fill `VkBufferCreateInfo` / `VkImageCreateInfo` structure.
  15309. -# Fill VmaAllocationCreateInfo structure.
  15310. -# Call vmaCreateBuffer() / vmaCreateImage() to get `VkBuffer`/`VkImage` with memory
  15311. already allocated and bound to it, plus #VmaAllocation objects that represents its underlying memory.
  15312. \code
  15313. VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  15314. bufferInfo.size = 65536;
  15315. bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  15316. VmaAllocationCreateInfo allocInfo = {};
  15317. allocInfo.usage = VMA_MEMORY_USAGE_AUTO;
  15318. VkBuffer buffer;
  15319. VmaAllocation allocation;
  15320. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  15321. \endcode
  15322. Don't forget to destroy your objects when no longer needed:
  15323. \code
  15324. vmaDestroyBuffer(allocator, buffer, allocation);
  15325. vmaDestroyAllocator(allocator);
  15326. \endcode
  15327. \page choosing_memory_type Choosing memory type
  15328. Physical devices in Vulkan support various combinations of memory heaps and
  15329. types. Help with choosing correct and optimal memory type for your specific
  15330. resource is one of the key features of this library. You can use it by filling
  15331. appropriate members of VmaAllocationCreateInfo structure, as described below.
  15332. You can also combine multiple methods.
  15333. -# If you just want to find memory type index that meets your requirements, you
  15334. can use function: vmaFindMemoryTypeIndexForBufferInfo(),
  15335. vmaFindMemoryTypeIndexForImageInfo(), vmaFindMemoryTypeIndex().
  15336. -# If you want to allocate a region of device memory without association with any
  15337. specific image or buffer, you can use function vmaAllocateMemory(). Usage of
  15338. this function is not recommended and usually not needed.
  15339. vmaAllocateMemoryPages() function is also provided for creating multiple allocations at once,
  15340. which may be useful for sparse binding.
  15341. -# If you already have a buffer or an image created, you want to allocate memory
  15342. for it and then you will bind it yourself, you can use function
  15343. vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage().
  15344. For binding you should use functions: vmaBindBufferMemory(), vmaBindImageMemory()
  15345. or their extended versions: vmaBindBufferMemory2(), vmaBindImageMemory2().
  15346. -# **This is the easiest and recommended way to use this library:**
  15347. If you want to create a buffer or an image, allocate memory for it and bind
  15348. them together, all in one call, you can use function vmaCreateBuffer(),
  15349. vmaCreateImage().
  15350. When using 3. or 4., the library internally queries Vulkan for memory types
  15351. supported for that buffer or image (function `vkGetBufferMemoryRequirements()`)
  15352. and uses only one of these types.
  15353. If no memory type can be found that meets all the requirements, these functions
  15354. return `VK_ERROR_FEATURE_NOT_PRESENT`.
  15355. You can leave VmaAllocationCreateInfo structure completely filled with zeros.
  15356. It means no requirements are specified for memory type.
  15357. It is valid, although not very useful.
  15358. \section choosing_memory_type_usage Usage
  15359. The easiest way to specify memory requirements is to fill member
  15360. VmaAllocationCreateInfo::usage using one of the values of enum #VmaMemoryUsage.
  15361. It defines high level, common usage types.
  15362. Since version 3 of the library, it is recommended to use #VMA_MEMORY_USAGE_AUTO to let it select best memory type for your resource automatically.
  15363. For example, if you want to create a uniform buffer that will be filled using
  15364. transfer only once or infrequently and then used for rendering every frame as a uniform buffer, you can
  15365. do it using following code. The buffer will most likely end up in a memory type with
  15366. `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT` to be fast to access by the GPU device.
  15367. \code
  15368. VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  15369. bufferInfo.size = 65536;
  15370. bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  15371. VmaAllocationCreateInfo allocInfo = {};
  15372. allocInfo.usage = VMA_MEMORY_USAGE_AUTO;
  15373. VkBuffer buffer;
  15374. VmaAllocation allocation;
  15375. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  15376. \endcode
  15377. If you have a preference for putting the resource in GPU (device) memory or CPU (host) memory
  15378. on systems with discrete graphics card that have the memories separate, you can use
  15379. #VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE or #VMA_MEMORY_USAGE_AUTO_PREFER_HOST.
  15380. When using `VMA_MEMORY_USAGE_AUTO*` while you want to map the allocated memory,
  15381. you also need to specify one of the host access flags:
  15382. #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT.
  15383. This will help the library decide about preferred memory type to ensure it has `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`
  15384. so you can map it.
  15385. For example, a staging buffer that will be filled via mapped pointer and then
  15386. used as a source of transfer to the buffer decribed previously can be created like this.
  15387. It will likely and up in a memory type that is `HOST_VISIBLE` and `HOST_COHERENT`
  15388. but not `HOST_CACHED` (meaning uncached, write-combined) and not `DEVICE_LOCAL` (meaning system RAM).
  15389. \code
  15390. VkBufferCreateInfo stagingBufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  15391. stagingBufferInfo.size = 65536;
  15392. stagingBufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  15393. VmaAllocationCreateInfo stagingAllocInfo = {};
  15394. stagingAllocInfo.usage = VMA_MEMORY_USAGE_AUTO;
  15395. stagingAllocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
  15396. VkBuffer stagingBuffer;
  15397. VmaAllocation stagingAllocation;
  15398. vmaCreateBuffer(allocator, &stagingBufferInfo, &stagingAllocInfo, &stagingBuffer, &stagingAllocation, nullptr);
  15399. \endcode
  15400. For more examples of creating different kinds of resources, see chapter \ref usage_patterns.
  15401. Usage values `VMA_MEMORY_USAGE_AUTO*` are legal to use only when the library knows
  15402. about the resource being created by having `VkBufferCreateInfo` / `VkImageCreateInfo` passed,
  15403. so they work with functions like: vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo() etc.
  15404. If you allocate raw memory using function vmaAllocateMemory(), you have to use other means of selecting
  15405. memory type, as decribed below.
  15406. \note
  15407. Old usage values (`VMA_MEMORY_USAGE_GPU_ONLY`, `VMA_MEMORY_USAGE_CPU_ONLY`,
  15408. `VMA_MEMORY_USAGE_CPU_TO_GPU`, `VMA_MEMORY_USAGE_GPU_TO_CPU`, `VMA_MEMORY_USAGE_CPU_COPY`)
  15409. are still available and work same way as in previous versions of the library
  15410. for backward compatibility, but they are not recommended.
  15411. \section choosing_memory_type_required_preferred_flags Required and preferred flags
  15412. You can specify more detailed requirements by filling members
  15413. VmaAllocationCreateInfo::requiredFlags and VmaAllocationCreateInfo::preferredFlags
  15414. with a combination of bits from enum `VkMemoryPropertyFlags`. For example,
  15415. if you want to create a buffer that will be persistently mapped on host (so it
  15416. must be `HOST_VISIBLE`) and preferably will also be `HOST_COHERENT` and `HOST_CACHED`,
  15417. use following code:
  15418. \code
  15419. VmaAllocationCreateInfo allocInfo = {};
  15420. allocInfo.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  15421. allocInfo.preferredFlags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  15422. allocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT;
  15423. VkBuffer buffer;
  15424. VmaAllocation allocation;
  15425. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  15426. \endcode
  15427. A memory type is chosen that has all the required flags and as many preferred
  15428. flags set as possible.
  15429. Value passed in VmaAllocationCreateInfo::usage is internally converted to a set of required and preferred flags,
  15430. plus some extra "magic" (heuristics).
  15431. \section choosing_memory_type_explicit_memory_types Explicit memory types
  15432. If you inspected memory types available on the physical device and you have
  15433. a preference for memory types that you want to use, you can fill member
  15434. VmaAllocationCreateInfo::memoryTypeBits. It is a bit mask, where each bit set
  15435. means that a memory type with that index is allowed to be used for the
  15436. allocation. Special value 0, just like `UINT32_MAX`, means there are no
  15437. restrictions to memory type index.
  15438. Please note that this member is NOT just a memory type index.
  15439. Still you can use it to choose just one, specific memory type.
  15440. For example, if you already determined that your buffer should be created in
  15441. memory type 2, use following code:
  15442. \code
  15443. uint32_t memoryTypeIndex = 2;
  15444. VmaAllocationCreateInfo allocInfo = {};
  15445. allocInfo.memoryTypeBits = 1u << memoryTypeIndex;
  15446. VkBuffer buffer;
  15447. VmaAllocation allocation;
  15448. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  15449. \endcode
  15450. \section choosing_memory_type_custom_memory_pools Custom memory pools
  15451. If you allocate from custom memory pool, all the ways of specifying memory
  15452. requirements described above are not applicable and the aforementioned members
  15453. of VmaAllocationCreateInfo structure are ignored. Memory type is selected
  15454. explicitly when creating the pool and then used to make all the allocations from
  15455. that pool. For further details, see \ref custom_memory_pools.
  15456. \section choosing_memory_type_dedicated_allocations Dedicated allocations
  15457. Memory for allocations is reserved out of larger block of `VkDeviceMemory`
  15458. allocated from Vulkan internally. That is the main feature of this whole library.
  15459. You can still request a separate memory block to be created for an allocation,
  15460. just like you would do in a trivial solution without using any allocator.
  15461. In that case, a buffer or image is always bound to that memory at offset 0.
  15462. This is called a "dedicated allocation".
  15463. You can explicitly request it by using flag #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  15464. The library can also internally decide to use dedicated allocation in some cases, e.g.:
  15465. - When the size of the allocation is large.
  15466. - When [VK_KHR_dedicated_allocation](@ref vk_khr_dedicated_allocation) extension is enabled
  15467. and it reports that dedicated allocation is required or recommended for the resource.
  15468. - When allocation of next big memory block fails due to not enough device memory,
  15469. but allocation with the exact requested size succeeds.
  15470. \page memory_mapping Memory mapping
  15471. To "map memory" in Vulkan means to obtain a CPU pointer to `VkDeviceMemory`,
  15472. to be able to read from it or write to it in CPU code.
  15473. Mapping is possible only of memory allocated from a memory type that has
  15474. `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag.
  15475. Functions `vkMapMemory()`, `vkUnmapMemory()` are designed for this purpose.
  15476. You can use them directly with memory allocated by this library,
  15477. but it is not recommended because of following issue:
  15478. Mapping the same `VkDeviceMemory` block multiple times is illegal - only one mapping at a time is allowed.
  15479. This includes mapping disjoint regions. Mapping is not reference-counted internally by Vulkan.
  15480. Because of this, Vulkan Memory Allocator provides following facilities:
  15481. \note If you want to be able to map an allocation, you need to specify one of the flags
  15482. #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT
  15483. in VmaAllocationCreateInfo::flags. These flags are required for an allocation to be mappable
  15484. when using #VMA_MEMORY_USAGE_AUTO or other `VMA_MEMORY_USAGE_AUTO*` enum values.
  15485. For other usage values they are ignored and every such allocation made in `HOST_VISIBLE` memory type is mappable,
  15486. but they can still be used for consistency.
  15487. \section memory_mapping_mapping_functions Mapping functions
  15488. The library provides following functions for mapping of a specific #VmaAllocation: vmaMapMemory(), vmaUnmapMemory().
  15489. They are safer and more convenient to use than standard Vulkan functions.
  15490. You can map an allocation multiple times simultaneously - mapping is reference-counted internally.
  15491. You can also map different allocations simultaneously regardless of whether they use the same `VkDeviceMemory` block.
  15492. The way it is implemented is that the library always maps entire memory block, not just region of the allocation.
  15493. For further details, see description of vmaMapMemory() function.
  15494. Example:
  15495. \code
  15496. // Having these objects initialized:
  15497. struct ConstantBuffer
  15498. {
  15499. ...
  15500. };
  15501. ConstantBuffer constantBufferData = ...
  15502. VmaAllocator allocator = ...
  15503. VkBuffer constantBuffer = ...
  15504. VmaAllocation constantBufferAllocation = ...
  15505. // You can map and fill your buffer using following code:
  15506. void* mappedData;
  15507. vmaMapMemory(allocator, constantBufferAllocation, &mappedData);
  15508. memcpy(mappedData, &constantBufferData, sizeof(constantBufferData));
  15509. vmaUnmapMemory(allocator, constantBufferAllocation);
  15510. \endcode
  15511. When mapping, you may see a warning from Vulkan validation layer similar to this one:
  15512. <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>
  15513. It happens because the library maps entire `VkDeviceMemory` block, where different
  15514. types of images and buffers may end up together, especially on GPUs with unified memory like Intel.
  15515. You can safely ignore it if you are sure you access only memory of the intended
  15516. object that you wanted to map.
  15517. \section memory_mapping_persistently_mapped_memory Persistently mapped memory
  15518. Kepping your memory persistently mapped is generally OK in Vulkan.
  15519. You don't need to unmap it before using its data on the GPU.
  15520. The library provides a special feature designed for that:
  15521. Allocations made with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag set in
  15522. VmaAllocationCreateInfo::flags stay mapped all the time,
  15523. so you can just access CPU pointer to it any time
  15524. without a need to call any "map" or "unmap" function.
  15525. Example:
  15526. \code
  15527. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  15528. bufCreateInfo.size = sizeof(ConstantBuffer);
  15529. bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  15530. VmaAllocationCreateInfo allocCreateInfo = {};
  15531. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  15532. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT |
  15533. VMA_ALLOCATION_CREATE_MAPPED_BIT;
  15534. VkBuffer buf;
  15535. VmaAllocation alloc;
  15536. VmaAllocationInfo allocInfo;
  15537. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  15538. // Buffer is already mapped. You can access its memory.
  15539. memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData));
  15540. \endcode
  15541. \note #VMA_ALLOCATION_CREATE_MAPPED_BIT by itself doesn't guarantee that the allocation will end up
  15542. in a mappable memory type.
  15543. For this, you need to also specify #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or
  15544. #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT.
  15545. #VMA_ALLOCATION_CREATE_MAPPED_BIT only guarantees that if the memory is `HOST_VISIBLE`, the allocation will be mapped on creation.
  15546. For an example of how to make use of this fact, see section \ref usage_patterns_advanced_data_uploading.
  15547. \section memory_mapping_cache_control Cache flush and invalidate
  15548. Memory in Vulkan doesn't need to be unmapped before using it on GPU,
  15549. but unless a memory types has `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT` flag set,
  15550. you need to manually **invalidate** cache before reading of mapped pointer
  15551. and **flush** cache after writing to mapped pointer.
  15552. Map/unmap operations don't do that automatically.
  15553. Vulkan provides following functions for this purpose `vkFlushMappedMemoryRanges()`,
  15554. `vkInvalidateMappedMemoryRanges()`, but this library provides more convenient
  15555. functions that refer to given allocation object: vmaFlushAllocation(),
  15556. vmaInvalidateAllocation(),
  15557. or multiple objects at once: vmaFlushAllocations(), vmaInvalidateAllocations().
  15558. Regions of memory specified for flush/invalidate must be aligned to
  15559. `VkPhysicalDeviceLimits::nonCoherentAtomSize`. This is automatically ensured by the library.
  15560. In any memory type that is `HOST_VISIBLE` but not `HOST_COHERENT`, all allocations
  15561. within blocks are aligned to this value, so their offsets are always multiply of
  15562. `nonCoherentAtomSize` and two different allocations never share same "line" of this size.
  15563. Also, Windows drivers from all 3 PC GPU vendors (AMD, Intel, NVIDIA)
  15564. currently provide `HOST_COHERENT` flag on all memory types that are
  15565. `HOST_VISIBLE`, so on PC you may not need to bother.
  15566. \page staying_within_budget Staying within budget
  15567. When developing a graphics-intensive game or program, it is important to avoid allocating
  15568. more GPU memory than it is physically available. When the memory is over-committed,
  15569. various bad things can happen, depending on the specific GPU, graphics driver, and
  15570. operating system:
  15571. - It may just work without any problems.
  15572. - The application may slow down because some memory blocks are moved to system RAM
  15573. and the GPU has to access them through PCI Express bus.
  15574. - A new allocation may take very long time to complete, even few seconds, and possibly
  15575. freeze entire system.
  15576. - The new allocation may fail with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  15577. - It may even result in GPU crash (TDR), observed as `VK_ERROR_DEVICE_LOST`
  15578. returned somewhere later.
  15579. \section staying_within_budget_querying_for_budget Querying for budget
  15580. To query for current memory usage and available budget, use function vmaGetHeapBudgets().
  15581. Returned structure #VmaBudget contains quantities expressed in bytes, per Vulkan memory heap.
  15582. Please note that this function returns different information and works faster than
  15583. vmaCalculateStatistics(). vmaGetHeapBudgets() can be called every frame or even before every
  15584. allocation, while vmaCalculateStatistics() is intended to be used rarely,
  15585. only to obtain statistical information, e.g. for debugging purposes.
  15586. It is recommended to use <b>VK_EXT_memory_budget</b> device extension to obtain information
  15587. about the budget from Vulkan device. VMA is able to use this extension automatically.
  15588. When not enabled, the allocator behaves same way, but then it estimates current usage
  15589. and available budget based on its internal information and Vulkan memory heap sizes,
  15590. which may be less precise. In order to use this extension:
  15591. 1. Make sure extensions VK_EXT_memory_budget and VK_KHR_get_physical_device_properties2
  15592. required by it are available and enable them. Please note that the first is a device
  15593. extension and the second is instance extension!
  15594. 2. Use flag #VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT when creating #VmaAllocator object.
  15595. 3. Make sure to call vmaSetCurrentFrameIndex() every frame. Budget is queried from
  15596. Vulkan inside of it to avoid overhead of querying it with every allocation.
  15597. \section staying_within_budget_controlling_memory_usage Controlling memory usage
  15598. There are many ways in which you can try to stay within the budget.
  15599. First, when making new allocation requires allocating a new memory block, the library
  15600. tries not to exceed the budget automatically. If a block with default recommended size
  15601. (e.g. 256 MB) would go over budget, a smaller block is allocated, possibly even
  15602. dedicated memory for just this resource.
  15603. If the size of the requested resource plus current memory usage is more than the
  15604. budget, by default the library still tries to create it, leaving it to the Vulkan
  15605. implementation whether the allocation succeeds or fails. You can change this behavior
  15606. by using #VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT flag. With it, the allocation is
  15607. not made if it would exceed the budget or if the budget is already exceeded.
  15608. VMA then tries to make the allocation from the next eligible Vulkan memory type.
  15609. The all of them fail, the call then fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  15610. Example usage pattern may be to pass the #VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT flag
  15611. when creating resources that are not essential for the application (e.g. the texture
  15612. of a specific object) and not to pass it when creating critically important resources
  15613. (e.g. render targets).
  15614. On AMD graphics cards there is a custom vendor extension available: <b>VK_AMD_memory_overallocation_behavior</b>
  15615. that allows to control the behavior of the Vulkan implementation in out-of-memory cases -
  15616. whether it should fail with an error code or still allow the allocation.
  15617. Usage of this extension involves only passing extra structure on Vulkan device creation,
  15618. so it is out of scope of this library.
  15619. Finally, you can also use #VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT flag to make sure
  15620. a new allocation is created only when it fits inside one of the existing memory blocks.
  15621. If it would require to allocate a new block, if fails instead with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  15622. This also ensures that the function call is very fast because it never goes to Vulkan
  15623. to obtain a new block.
  15624. \note Creating \ref custom_memory_pools with VmaPoolCreateInfo::minBlockCount
  15625. set to more than 0 will currently try to allocate memory blocks without checking whether they
  15626. fit within budget.
  15627. \page resource_aliasing Resource aliasing (overlap)
  15628. New explicit graphics APIs (Vulkan and Direct3D 12), thanks to manual memory
  15629. management, give an opportunity to alias (overlap) multiple resources in the
  15630. same region of memory - a feature not available in the old APIs (Direct3D 11, OpenGL).
  15631. It can be useful to save video memory, but it must be used with caution.
  15632. For example, if you know the flow of your whole render frame in advance, you
  15633. are going to use some intermediate textures or buffers only during a small range of render passes,
  15634. and you know these ranges don't overlap in time, you can bind these resources to
  15635. the same place in memory, even if they have completely different parameters (width, height, format etc.).
  15636. ![Resource aliasing (overlap)](../gfx/Aliasing.png)
  15637. Such scenario is possible using VMA, but you need to create your images manually.
  15638. Then you need to calculate parameters of an allocation to be made using formula:
  15639. - allocation size = max(size of each image)
  15640. - allocation alignment = max(alignment of each image)
  15641. - allocation memoryTypeBits = bitwise AND(memoryTypeBits of each image)
  15642. Following example shows two different images bound to the same place in memory,
  15643. allocated to fit largest of them.
  15644. \code
  15645. // A 512x512 texture to be sampled.
  15646. VkImageCreateInfo img1CreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
  15647. img1CreateInfo.imageType = VK_IMAGE_TYPE_2D;
  15648. img1CreateInfo.extent.width = 512;
  15649. img1CreateInfo.extent.height = 512;
  15650. img1CreateInfo.extent.depth = 1;
  15651. img1CreateInfo.mipLevels = 10;
  15652. img1CreateInfo.arrayLayers = 1;
  15653. img1CreateInfo.format = VK_FORMAT_R8G8B8A8_SRGB;
  15654. img1CreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  15655. img1CreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  15656. img1CreateInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
  15657. img1CreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
  15658. // A full screen texture to be used as color attachment.
  15659. VkImageCreateInfo img2CreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
  15660. img2CreateInfo.imageType = VK_IMAGE_TYPE_2D;
  15661. img2CreateInfo.extent.width = 1920;
  15662. img2CreateInfo.extent.height = 1080;
  15663. img2CreateInfo.extent.depth = 1;
  15664. img2CreateInfo.mipLevels = 1;
  15665. img2CreateInfo.arrayLayers = 1;
  15666. img2CreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
  15667. img2CreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  15668. img2CreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  15669. img2CreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  15670. img2CreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
  15671. VkImage img1;
  15672. res = vkCreateImage(device, &img1CreateInfo, nullptr, &img1);
  15673. VkImage img2;
  15674. res = vkCreateImage(device, &img2CreateInfo, nullptr, &img2);
  15675. VkMemoryRequirements img1MemReq;
  15676. vkGetImageMemoryRequirements(device, img1, &img1MemReq);
  15677. VkMemoryRequirements img2MemReq;
  15678. vkGetImageMemoryRequirements(device, img2, &img2MemReq);
  15679. VkMemoryRequirements finalMemReq = {};
  15680. finalMemReq.size = std::max(img1MemReq.size, img2MemReq.size);
  15681. finalMemReq.alignment = std::max(img1MemReq.alignment, img2MemReq.alignment);
  15682. finalMemReq.memoryTypeBits = img1MemReq.memoryTypeBits & img2MemReq.memoryTypeBits;
  15683. // Validate if(finalMemReq.memoryTypeBits != 0)
  15684. VmaAllocationCreateInfo allocCreateInfo = {};
  15685. allocCreateInfo.preferredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  15686. VmaAllocation alloc;
  15687. res = vmaAllocateMemory(allocator, &finalMemReq, &allocCreateInfo, &alloc, nullptr);
  15688. res = vmaBindImageMemory(allocator, alloc, img1);
  15689. res = vmaBindImageMemory(allocator, alloc, img2);
  15690. // You can use img1, img2 here, but not at the same time!
  15691. vmaFreeMemory(allocator, alloc);
  15692. vkDestroyImage(allocator, img2, nullptr);
  15693. vkDestroyImage(allocator, img1, nullptr);
  15694. \endcode
  15695. Remember that using resources that alias in memory requires proper synchronization.
  15696. You need to issue a memory barrier to make sure commands that use `img1` and `img2`
  15697. don't overlap on GPU timeline.
  15698. You also need to treat a resource after aliasing as uninitialized - containing garbage data.
  15699. For example, if you use `img1` and then want to use `img2`, you need to issue
  15700. an image memory barrier for `img2` with `oldLayout` = `VK_IMAGE_LAYOUT_UNDEFINED`.
  15701. Additional considerations:
  15702. - Vulkan also allows to interpret contents of memory between aliasing resources consistently in some cases.
  15703. See chapter 11.8. "Memory Aliasing" of Vulkan specification or `VK_IMAGE_CREATE_ALIAS_BIT` flag.
  15704. - You can create more complex layout where different images and buffers are bound
  15705. at different offsets inside one large allocation. For example, one can imagine
  15706. a big texture used in some render passes, aliasing with a set of many small buffers
  15707. used between in some further passes. To bind a resource at non-zero offset in an allocation,
  15708. use vmaBindBufferMemory2() / vmaBindImageMemory2().
  15709. - Before allocating memory for the resources you want to alias, check `memoryTypeBits`
  15710. returned in memory requirements of each resource to make sure the bits overlap.
  15711. Some GPUs may expose multiple memory types suitable e.g. only for buffers or
  15712. images with `COLOR_ATTACHMENT` usage, so the sets of memory types supported by your
  15713. resources may be disjoint. Aliasing them is not possible in that case.
  15714. \page custom_memory_pools Custom memory pools
  15715. A memory pool contains a number of `VkDeviceMemory` blocks.
  15716. The library automatically creates and manages default pool for each memory type available on the device.
  15717. Default memory pool automatically grows in size.
  15718. Size of allocated blocks is also variable and managed automatically.
  15719. You can create custom pool and allocate memory out of it.
  15720. It can be useful if you want to:
  15721. - Keep certain kind of allocations separate from others.
  15722. - Enforce particular, fixed size of Vulkan memory blocks.
  15723. - Limit maximum amount of Vulkan memory allocated for that pool.
  15724. - Reserve minimum or fixed amount of Vulkan memory always preallocated for that pool.
  15725. - Use extra parameters for a set of your allocations that are available in #VmaPoolCreateInfo but not in
  15726. #VmaAllocationCreateInfo - e.g., custom minimum alignment, custom `pNext` chain.
  15727. - Perform defragmentation on a specific subset of your allocations.
  15728. To use custom memory pools:
  15729. -# Fill VmaPoolCreateInfo structure.
  15730. -# Call vmaCreatePool() to obtain #VmaPool handle.
  15731. -# When making an allocation, set VmaAllocationCreateInfo::pool to this handle.
  15732. You don't need to specify any other parameters of this structure, like `usage`.
  15733. Example:
  15734. \code
  15735. // Find memoryTypeIndex for the pool.
  15736. VkBufferCreateInfo sampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  15737. sampleBufCreateInfo.size = 0x10000; // Doesn't matter.
  15738. sampleBufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  15739. VmaAllocationCreateInfo sampleAllocCreateInfo = {};
  15740. sampleAllocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  15741. uint32_t memTypeIndex;
  15742. VkResult res = vmaFindMemoryTypeIndexForBufferInfo(allocator,
  15743. &sampleBufCreateInfo, &sampleAllocCreateInfo, &memTypeIndex);
  15744. // Check res...
  15745. // Create a pool that can have at most 2 blocks, 128 MiB each.
  15746. VmaPoolCreateInfo poolCreateInfo = {};
  15747. poolCreateInfo.memoryTypeIndex = memTypeIndex;
  15748. poolCreateInfo.blockSize = 128ull * 1024 * 1024;
  15749. poolCreateInfo.maxBlockCount = 2;
  15750. VmaPool pool;
  15751. res = vmaCreatePool(allocator, &poolCreateInfo, &pool);
  15752. // Check res...
  15753. // Allocate a buffer out of it.
  15754. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  15755. bufCreateInfo.size = 1024;
  15756. bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  15757. VmaAllocationCreateInfo allocCreateInfo = {};
  15758. allocCreateInfo.pool = pool;
  15759. VkBuffer buf;
  15760. VmaAllocation alloc;
  15761. res = vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, nullptr);
  15762. // Check res...
  15763. \endcode
  15764. You have to free all allocations made from this pool before destroying it.
  15765. \code
  15766. vmaDestroyBuffer(allocator, buf, alloc);
  15767. vmaDestroyPool(allocator, pool);
  15768. \endcode
  15769. New versions of this library support creating dedicated allocations in custom pools.
  15770. It is supported only when VmaPoolCreateInfo::blockSize = 0.
  15771. To use this feature, set VmaAllocationCreateInfo::pool to the pointer to your custom pool and
  15772. VmaAllocationCreateInfo::flags to #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  15773. \note Excessive use of custom pools is a common mistake when using this library.
  15774. Custom pools may be useful for special purposes - when you want to
  15775. keep certain type of resources separate e.g. to reserve minimum amount of memory
  15776. for them or limit maximum amount of memory they can occupy. For most
  15777. resources this is not needed and so it is not recommended to create #VmaPool
  15778. objects and allocations out of them. Allocating from the default pool is sufficient.
  15779. \section custom_memory_pools_MemTypeIndex Choosing memory type index
  15780. When creating a pool, you must explicitly specify memory type index.
  15781. To find the one suitable for your buffers or images, you can use helper functions
  15782. vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo().
  15783. You need to provide structures with example parameters of buffers or images
  15784. that you are going to create in that pool.
  15785. \code
  15786. VkBufferCreateInfo exampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  15787. exampleBufCreateInfo.size = 1024; // Doesn't matter
  15788. exampleBufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  15789. VmaAllocationCreateInfo allocCreateInfo = {};
  15790. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  15791. uint32_t memTypeIndex;
  15792. vmaFindMemoryTypeIndexForBufferInfo(allocator, &exampleBufCreateInfo, &allocCreateInfo, &memTypeIndex);
  15793. VmaPoolCreateInfo poolCreateInfo = {};
  15794. poolCreateInfo.memoryTypeIndex = memTypeIndex;
  15795. // ...
  15796. \endcode
  15797. When creating buffers/images allocated in that pool, provide following parameters:
  15798. - `VkBufferCreateInfo`: Prefer to pass same parameters as above.
  15799. Otherwise you risk creating resources in a memory type that is not suitable for them, which may result in undefined behavior.
  15800. Using different `VK_BUFFER_USAGE_` flags may work, but you shouldn't create images in a pool intended for buffers
  15801. or the other way around.
  15802. - VmaAllocationCreateInfo: You don't need to pass same parameters. Fill only `pool` member.
  15803. Other members are ignored anyway.
  15804. \section linear_algorithm Linear allocation algorithm
  15805. Each Vulkan memory block managed by this library has accompanying metadata that
  15806. keeps track of used and unused regions. By default, the metadata structure and
  15807. algorithm tries to find best place for new allocations among free regions to
  15808. optimize memory usage. This way you can allocate and free objects in any order.
  15809. ![Default allocation algorithm](../gfx/Linear_allocator_1_algo_default.png)
  15810. Sometimes there is a need to use simpler, linear allocation algorithm. You can
  15811. create custom pool that uses such algorithm by adding flag
  15812. #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT to VmaPoolCreateInfo::flags while creating
  15813. #VmaPool object. Then an alternative metadata management is used. It always
  15814. creates new allocations after last one and doesn't reuse free regions after
  15815. allocations freed in the middle. It results in better allocation performance and
  15816. less memory consumed by metadata.
  15817. ![Linear allocation algorithm](../gfx/Linear_allocator_2_algo_linear.png)
  15818. With this one flag, you can create a custom pool that can be used in many ways:
  15819. free-at-once, stack, double stack, and ring buffer. See below for details.
  15820. You don't need to specify explicitly which of these options you are going to use - it is detected automatically.
  15821. \subsection linear_algorithm_free_at_once Free-at-once
  15822. In a pool that uses linear algorithm, you still need to free all the allocations
  15823. individually, e.g. by using vmaFreeMemory() or vmaDestroyBuffer(). You can free
  15824. them in any order. New allocations are always made after last one - free space
  15825. in the middle is not reused. However, when you release all the allocation and
  15826. the pool becomes empty, allocation starts from the beginning again. This way you
  15827. can use linear algorithm to speed up creation of allocations that you are going
  15828. to release all at once.
  15829. ![Free-at-once](../gfx/Linear_allocator_3_free_at_once.png)
  15830. This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount
  15831. value that allows multiple memory blocks.
  15832. \subsection linear_algorithm_stack Stack
  15833. When you free an allocation that was created last, its space can be reused.
  15834. Thanks to this, if you always release allocations in the order opposite to their
  15835. creation (LIFO - Last In First Out), you can achieve behavior of a stack.
  15836. ![Stack](../gfx/Linear_allocator_4_stack.png)
  15837. This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount
  15838. value that allows multiple memory blocks.
  15839. \subsection linear_algorithm_double_stack Double stack
  15840. The space reserved by a custom pool with linear algorithm may be used by two
  15841. stacks:
  15842. - First, default one, growing up from offset 0.
  15843. - Second, "upper" one, growing down from the end towards lower offsets.
  15844. To make allocation from the upper stack, add flag #VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT
  15845. to VmaAllocationCreateInfo::flags.
  15846. ![Double stack](../gfx/Linear_allocator_7_double_stack.png)
  15847. Double stack is available only in pools with one memory block -
  15848. VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined.
  15849. When the two stacks' ends meet so there is not enough space between them for a
  15850. new allocation, such allocation fails with usual
  15851. `VK_ERROR_OUT_OF_DEVICE_MEMORY` error.
  15852. \subsection linear_algorithm_ring_buffer Ring buffer
  15853. When you free some allocations from the beginning and there is not enough free space
  15854. for a new one at the end of a pool, allocator's "cursor" wraps around to the
  15855. beginning and starts allocation there. Thanks to this, if you always release
  15856. allocations in the same order as you created them (FIFO - First In First Out),
  15857. you can achieve behavior of a ring buffer / queue.
  15858. ![Ring buffer](../gfx/Linear_allocator_5_ring_buffer.png)
  15859. Ring buffer is available only in pools with one memory block -
  15860. VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined.
  15861. \note \ref defragmentation is not supported in custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT.
  15862. \page defragmentation Defragmentation
  15863. Interleaved allocations and deallocations of many objects of varying size can
  15864. cause fragmentation over time, which can lead to a situation where the library is unable
  15865. to find a continuous range of free memory for a new allocation despite there is
  15866. enough free space, just scattered across many small free ranges between existing
  15867. allocations.
  15868. To mitigate this problem, you can use defragmentation feature.
  15869. It doesn't happen automatically though and needs your cooperation,
  15870. because VMA is a low level library that only allocates memory.
  15871. It cannot recreate buffers and images in a new place as it doesn't remember the contents of `VkBufferCreateInfo` / `VkImageCreateInfo` structures.
  15872. It cannot copy their contents as it doesn't record any commands to a command buffer.
  15873. Example:
  15874. \code
  15875. VmaDefragmentationInfo defragInfo = {};
  15876. defragInfo.pool = myPool;
  15877. defragInfo.flags = VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT;
  15878. VmaDefragmentationContext defragCtx;
  15879. VkResult res = vmaBeginDefragmentation(allocator, &defragInfo, &defragCtx);
  15880. // Check res...
  15881. for(;;)
  15882. {
  15883. VmaDefragmentationPassMoveInfo pass;
  15884. res = vmaBeginDefragmentationPass(allocator, defragCtx, &pass);
  15885. if(res == VK_SUCCESS)
  15886. break;
  15887. else if(res != VK_INCOMPLETE)
  15888. // Handle error...
  15889. for(uint32_t i = 0; i < pass.moveCount; ++i)
  15890. {
  15891. // Inspect pass.pMoves[i].srcAllocation, identify what buffer/image it represents.
  15892. VmaAllocationInfo allocInfo;
  15893. vmaGetAllocationInfo(allocator, pMoves[i].srcAllocation, &allocInfo);
  15894. MyEngineResourceData* resData = (MyEngineResourceData*)allocInfo.pUserData;
  15895. // Recreate and bind this buffer/image at: pass.pMoves[i].dstMemory, pass.pMoves[i].dstOffset.
  15896. VkImageCreateInfo imgCreateInfo = ...
  15897. VkImage newImg;
  15898. res = vkCreateImage(device, &imgCreateInfo, nullptr, &newImg);
  15899. // Check res...
  15900. res = vmaBindImageMemory(allocator, pMoves[i].dstTmpAllocation, newImg);
  15901. // Check res...
  15902. // Issue a vkCmdCopyBuffer/vkCmdCopyImage to copy its content to the new place.
  15903. vkCmdCopyImage(cmdBuf, resData->img, ..., newImg, ...);
  15904. }
  15905. // Make sure the copy commands finished executing.
  15906. vkWaitForFences(...);
  15907. // Destroy old buffers/images bound with pass.pMoves[i].srcAllocation.
  15908. for(uint32_t i = 0; i < pass.moveCount; ++i)
  15909. {
  15910. // ...
  15911. vkDestroyImage(device, resData->img, nullptr);
  15912. }
  15913. // Update appropriate descriptors to point to the new places...
  15914. res = vmaEndDefragmentationPass(allocator, defragCtx, &pass);
  15915. if(res == VK_SUCCESS)
  15916. break;
  15917. else if(res != VK_INCOMPLETE)
  15918. // Handle error...
  15919. }
  15920. vmaEndDefragmentation(allocator, defragCtx, nullptr);
  15921. \endcode
  15922. Although functions like vmaCreateBuffer(), vmaCreateImage(), vmaDestroyBuffer(), vmaDestroyImage()
  15923. create/destroy an allocation and a buffer/image at once, these are just a shortcut for
  15924. creating the resource, allocating memory, and binding them together.
  15925. Defragmentation works on memory allocations only. You must handle the rest manually.
  15926. Defragmentation is an iterative process that should repreat "passes" as long as related functions
  15927. return `VK_INCOMPLETE` not `VK_SUCCESS`.
  15928. In each pass:
  15929. 1. vmaBeginDefragmentationPass() function call:
  15930. - Calculates and returns the list of allocations to be moved in this pass.
  15931. Note this can be a time-consuming process.
  15932. - Reserves destination memory for them by creating temporary destination allocations
  15933. that you can query for their `VkDeviceMemory` + offset using vmaGetAllocationInfo().
  15934. 2. Inside the pass, **you should**:
  15935. - Inspect the returned list of allocations to be moved.
  15936. - Create new buffers/images and bind them at the returned destination temporary allocations.
  15937. - Copy data from source to destination resources if necessary.
  15938. - Destroy the source buffers/images, but NOT their allocations.
  15939. 3. vmaEndDefragmentationPass() function call:
  15940. - Frees the source memory reserved for the allocations that are moved.
  15941. - Modifies source #VmaAllocation objects that are moved to point to the destination reserved memory.
  15942. - Frees `VkDeviceMemory` blocks that became empty.
  15943. Unlike in previous iterations of the defragmentation API, there is no list of "movable" allocations passed as a parameter.
  15944. Defragmentation algorithm tries to move all suitable allocations.
  15945. You can, however, refuse to move some of them inside a defragmentation pass, by setting
  15946. `pass.pMoves[i].operation` to #VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE.
  15947. This is not recommended and may result in suboptimal packing of the allocations after defragmentation.
  15948. If you cannot ensure any allocation can be moved, it is better to keep movable allocations separate in a custom pool.
  15949. Inside a pass, for each allocation that should be moved:
  15950. - You should copy its data from the source to the destination place by calling e.g. `vkCmdCopyBuffer()`, `vkCmdCopyImage()`.
  15951. - You need to make sure these commands finished executing before destroying the source buffers/images and before calling vmaEndDefragmentationPass().
  15952. - If a resource doesn't contain any meaningful data, e.g. it is a transient color attachment image to be cleared,
  15953. filled, and used temporarily in each rendering frame, you can just recreate this image
  15954. without copying its data.
  15955. - If the resource is in `HOST_VISIBLE` and `HOST_CACHED` memory, you can copy its data on the CPU
  15956. using `memcpy()`.
  15957. - If you cannot move the allocation, you can set `pass.pMoves[i].operation` to #VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE.
  15958. This will cancel the move.
  15959. - vmaEndDefragmentationPass() will then free the destination memory
  15960. not the source memory of the allocation, leaving it unchanged.
  15961. - If you decide the allocation is unimportant and can be destroyed instead of moved (e.g. it wasn't used for long time),
  15962. you can set `pass.pMoves[i].operation` to #VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY.
  15963. - vmaEndDefragmentationPass() will then free both source and destination memory, and will destroy the source #VmaAllocation object.
  15964. You can defragment a specific custom pool by setting VmaDefragmentationInfo::pool
  15965. (like in the example above) or all the default pools by setting this member to null.
  15966. Defragmentation is always performed in each pool separately.
  15967. Allocations are never moved between different Vulkan memory types.
  15968. The size of the destination memory reserved for a moved allocation is the same as the original one.
  15969. Alignment of an allocation as it was determined using `vkGetBufferMemoryRequirements()` etc. is also respected after defragmentation.
  15970. Buffers/images should be recreated with the same `VkBufferCreateInfo` / `VkImageCreateInfo` parameters as the original ones.
  15971. You can perform the defragmentation incrementally to limit the number of allocations and bytes to be moved
  15972. in each pass, e.g. to call it in sync with render frames and not to experience too big hitches.
  15973. See members: VmaDefragmentationInfo::maxBytesPerPass, VmaDefragmentationInfo::maxAllocationsPerPass.
  15974. It is also safe to perform the defragmentation asynchronously to render frames and other Vulkan and VMA
  15975. usage, possibly from multiple threads, with the exception that allocations
  15976. returned in VmaDefragmentationPassMoveInfo::pMoves shouldn't be destroyed until the defragmentation pass is ended.
  15977. <b>Mapping</b> is preserved on allocations that are moved during defragmentation.
  15978. Whether through #VMA_ALLOCATION_CREATE_MAPPED_BIT or vmaMapMemory(), the allocations
  15979. are mapped at their new place. Of course, pointer to the mapped data changes, so it needs to be queried
  15980. using VmaAllocationInfo::pMappedData.
  15981. \note Defragmentation is not supported in custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT.
  15982. \page statistics Statistics
  15983. This library contains several functions that return information about its internal state,
  15984. especially the amount of memory allocated from Vulkan.
  15985. \section statistics_numeric_statistics Numeric statistics
  15986. If you need to obtain basic statistics about memory usage per heap, together with current budget,
  15987. you can call function vmaGetHeapBudgets() and inspect structure #VmaBudget.
  15988. This is useful to keep track of memory usage and stay withing budget
  15989. (see also \ref staying_within_budget).
  15990. Example:
  15991. \code
  15992. uint32_t heapIndex = ...
  15993. VmaBudget budgets[VK_MAX_MEMORY_HEAPS];
  15994. vmaGetHeapBudgets(allocator, budgets);
  15995. printf("My heap currently has %u allocations taking %llu B,\n",
  15996. budgets[heapIndex].statistics.allocationCount,
  15997. budgets[heapIndex].statistics.allocationBytes);
  15998. printf("allocated out of %u Vulkan device memory blocks taking %llu B,\n",
  15999. budgets[heapIndex].statistics.blockCount,
  16000. budgets[heapIndex].statistics.blockBytes);
  16001. printf("Vulkan reports total usage %llu B with budget %llu B.\n",
  16002. budgets[heapIndex].usage,
  16003. budgets[heapIndex].budget);
  16004. \endcode
  16005. You can query for more detailed statistics per memory heap, type, and totals,
  16006. including minimum and maximum allocation size and unused range size,
  16007. by calling function vmaCalculateStatistics() and inspecting structure #VmaTotalStatistics.
  16008. This function is slower though, as it has to traverse all the internal data structures,
  16009. so it should be used only for debugging purposes.
  16010. You can query for statistics of a custom pool using function vmaGetPoolStatistics()
  16011. or vmaCalculatePoolStatistics().
  16012. You can query for information about a specific allocation using function vmaGetAllocationInfo().
  16013. It fill structure #VmaAllocationInfo.
  16014. \section statistics_json_dump JSON dump
  16015. You can dump internal state of the allocator to a string in JSON format using function vmaBuildStatsString().
  16016. The result is guaranteed to be correct JSON.
  16017. It uses ANSI encoding.
  16018. Any strings provided by user (see [Allocation names](@ref allocation_names))
  16019. are copied as-is and properly escaped for JSON, so if they use UTF-8, ISO-8859-2 or any other encoding,
  16020. this JSON string can be treated as using this encoding.
  16021. It must be freed using function vmaFreeStatsString().
  16022. The format of this JSON string is not part of official documentation of the library,
  16023. but it will not change in backward-incompatible way without increasing library major version number
  16024. and appropriate mention in changelog.
  16025. The JSON string contains all the data that can be obtained using vmaCalculateStatistics().
  16026. It can also contain detailed map of allocated memory blocks and their regions -
  16027. free and occupied by allocations.
  16028. This allows e.g. to visualize the memory or assess fragmentation.
  16029. \page allocation_annotation Allocation names and user data
  16030. \section allocation_user_data Allocation user data
  16031. You can annotate allocations with your own information, e.g. for debugging purposes.
  16032. To do that, fill VmaAllocationCreateInfo::pUserData field when creating
  16033. an allocation. It is an opaque `void*` pointer. You can use it e.g. as a pointer,
  16034. some handle, index, key, ordinal number or any other value that would associate
  16035. the allocation with your custom metadata.
  16036. It it useful to identify appropriate data structures in your engine given #VmaAllocation,
  16037. e.g. when doing \ref defragmentation.
  16038. \code
  16039. VkBufferCreateInfo bufCreateInfo = ...
  16040. MyBufferMetadata* pMetadata = CreateBufferMetadata();
  16041. VmaAllocationCreateInfo allocCreateInfo = {};
  16042. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  16043. allocCreateInfo.pUserData = pMetadata;
  16044. VkBuffer buffer;
  16045. VmaAllocation allocation;
  16046. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buffer, &allocation, nullptr);
  16047. \endcode
  16048. The pointer may be later retrieved as VmaAllocationInfo::pUserData:
  16049. \code
  16050. VmaAllocationInfo allocInfo;
  16051. vmaGetAllocationInfo(allocator, allocation, &allocInfo);
  16052. MyBufferMetadata* pMetadata = (MyBufferMetadata*)allocInfo.pUserData;
  16053. \endcode
  16054. It can also be changed using function vmaSetAllocationUserData().
  16055. Values of (non-zero) allocations' `pUserData` are printed in JSON report created by
  16056. vmaBuildStatsString() in hexadecimal form.
  16057. \section allocation_names Allocation names
  16058. An allocation can also carry a null-terminated string, giving a name to the allocation.
  16059. To set it, call vmaSetAllocationName().
  16060. The library creates internal copy of the string, so the pointer you pass doesn't need
  16061. to be valid for whole lifetime of the allocation. You can free it after the call.
  16062. \code
  16063. std::string imageName = "Texture: ";
  16064. imageName += fileName;
  16065. vmaSetAllocationName(allocator, allocation, imageName.c_str());
  16066. \endcode
  16067. The string can be later retrieved by inspecting VmaAllocationInfo::pName.
  16068. It is also printed in JSON report created by vmaBuildStatsString().
  16069. \note Setting string name to VMA allocation doesn't automatically set it to the Vulkan buffer or image created with it.
  16070. You must do it manually using an extension like VK_EXT_debug_utils, which is independent of this library.
  16071. \page virtual_allocator Virtual allocator
  16072. As an extra feature, the core allocation algorithm of the library is exposed through a simple and convenient API of "virtual allocator".
  16073. It doesn't allocate any real GPU memory. It just keeps track of used and free regions of a "virtual block".
  16074. You can use it to allocate your own memory or other objects, even completely unrelated to Vulkan.
  16075. A common use case is sub-allocation of pieces of one large GPU buffer.
  16076. \section virtual_allocator_creating_virtual_block Creating virtual block
  16077. To use this functionality, there is no main "allocator" object.
  16078. You don't need to have #VmaAllocator object created.
  16079. All you need to do is to create a separate #VmaVirtualBlock object for each block of memory you want to be managed by the allocator:
  16080. -# Fill in #VmaVirtualBlockCreateInfo structure.
  16081. -# Call vmaCreateVirtualBlock(). Get new #VmaVirtualBlock object.
  16082. Example:
  16083. \code
  16084. VmaVirtualBlockCreateInfo blockCreateInfo = {};
  16085. blockCreateInfo.size = 1048576; // 1 MB
  16086. VmaVirtualBlock block;
  16087. VkResult res = vmaCreateVirtualBlock(&blockCreateInfo, &block);
  16088. \endcode
  16089. \section virtual_allocator_making_virtual_allocations Making virtual allocations
  16090. #VmaVirtualBlock object contains internal data structure that keeps track of free and occupied regions
  16091. using the same code as the main Vulkan memory allocator.
  16092. Similarly to #VmaAllocation for standard GPU allocations, there is #VmaVirtualAllocation type
  16093. that represents an opaque handle to an allocation withing the virtual block.
  16094. In order to make such allocation:
  16095. -# Fill in #VmaVirtualAllocationCreateInfo structure.
  16096. -# Call vmaVirtualAllocate(). Get new #VmaVirtualAllocation object that represents the allocation.
  16097. You can also receive `VkDeviceSize offset` that was assigned to the allocation.
  16098. Example:
  16099. \code
  16100. VmaVirtualAllocationCreateInfo allocCreateInfo = {};
  16101. allocCreateInfo.size = 4096; // 4 KB
  16102. VmaVirtualAllocation alloc;
  16103. VkDeviceSize offset;
  16104. res = vmaVirtualAllocate(block, &allocCreateInfo, &alloc, &offset);
  16105. if(res == VK_SUCCESS)
  16106. {
  16107. // Use the 4 KB of your memory starting at offset.
  16108. }
  16109. else
  16110. {
  16111. // Allocation failed - no space for it could be found. Handle this error!
  16112. }
  16113. \endcode
  16114. \section virtual_allocator_deallocation Deallocation
  16115. When no longer needed, an allocation can be freed by calling vmaVirtualFree().
  16116. You can only pass to this function an allocation that was previously returned by vmaVirtualAllocate()
  16117. called for the same #VmaVirtualBlock.
  16118. When whole block is no longer needed, the block object can be released by calling vmaDestroyVirtualBlock().
  16119. All allocations must be freed before the block is destroyed, which is checked internally by an assert.
  16120. However, if you don't want to call vmaVirtualFree() for each allocation, you can use vmaClearVirtualBlock() to free them all at once -
  16121. a feature not available in normal Vulkan memory allocator. Example:
  16122. \code
  16123. vmaVirtualFree(block, alloc);
  16124. vmaDestroyVirtualBlock(block);
  16125. \endcode
  16126. \section virtual_allocator_allocation_parameters Allocation parameters
  16127. You can attach a custom pointer to each allocation by using vmaSetVirtualAllocationUserData().
  16128. Its default value is null.
  16129. It can be used to store any data that needs to be associated with that allocation - e.g. an index, a handle, or a pointer to some
  16130. larger data structure containing more information. Example:
  16131. \code
  16132. struct CustomAllocData
  16133. {
  16134. std::string m_AllocName;
  16135. };
  16136. CustomAllocData* allocData = new CustomAllocData();
  16137. allocData->m_AllocName = "My allocation 1";
  16138. vmaSetVirtualAllocationUserData(block, alloc, allocData);
  16139. \endcode
  16140. The pointer can later be fetched, along with allocation offset and size, by passing the allocation handle to function
  16141. vmaGetVirtualAllocationInfo() and inspecting returned structure #VmaVirtualAllocationInfo.
  16142. If you allocated a new object to be used as the custom pointer, don't forget to delete that object before freeing the allocation!
  16143. Example:
  16144. \code
  16145. VmaVirtualAllocationInfo allocInfo;
  16146. vmaGetVirtualAllocationInfo(block, alloc, &allocInfo);
  16147. delete (CustomAllocData*)allocInfo.pUserData;
  16148. vmaVirtualFree(block, alloc);
  16149. \endcode
  16150. \section virtual_allocator_alignment_and_units Alignment and units
  16151. It feels natural to express sizes and offsets in bytes.
  16152. If an offset of an allocation needs to be aligned to a multiply of some number (e.g. 4 bytes), you can fill optional member
  16153. VmaVirtualAllocationCreateInfo::alignment to request it. Example:
  16154. \code
  16155. VmaVirtualAllocationCreateInfo allocCreateInfo = {};
  16156. allocCreateInfo.size = 4096; // 4 KB
  16157. allocCreateInfo.alignment = 4; // Returned offset must be a multiply of 4 B
  16158. VmaVirtualAllocation alloc;
  16159. res = vmaVirtualAllocate(block, &allocCreateInfo, &alloc, nullptr);
  16160. \endcode
  16161. Alignments of different allocations made from one block may vary.
  16162. However, if all alignments and sizes are always multiply of some size e.g. 4 B or `sizeof(MyDataStruct)`,
  16163. you can express all sizes, alignments, and offsets in multiples of that size instead of individual bytes.
  16164. It might be more convenient, but you need to make sure to use this new unit consistently in all the places:
  16165. - VmaVirtualBlockCreateInfo::size
  16166. - VmaVirtualAllocationCreateInfo::size and VmaVirtualAllocationCreateInfo::alignment
  16167. - Using offset returned by vmaVirtualAllocate() or in VmaVirtualAllocationInfo::offset
  16168. \section virtual_allocator_statistics Statistics
  16169. You can obtain statistics of a virtual block using vmaGetVirtualBlockStatistics()
  16170. (to get brief statistics that are fast to calculate)
  16171. or vmaCalculateVirtualBlockStatistics() (to get more detailed statistics, slower to calculate).
  16172. The functions fill structures #VmaStatistics, #VmaDetailedStatistics respectively - same as used by the normal Vulkan memory allocator.
  16173. Example:
  16174. \code
  16175. VmaStatistics stats;
  16176. vmaGetVirtualBlockStatistics(block, &stats);
  16177. printf("My virtual block has %llu bytes used by %u virtual allocations\n",
  16178. stats.allocationBytes, stats.allocationCount);
  16179. \endcode
  16180. You can also request a full list of allocations and free regions as a string in JSON format by calling
  16181. vmaBuildVirtualBlockStatsString().
  16182. Returned string must be later freed using vmaFreeVirtualBlockStatsString().
  16183. The format of this string differs from the one returned by the main Vulkan allocator, but it is similar.
  16184. \section virtual_allocator_additional_considerations Additional considerations
  16185. The "virtual allocator" functionality is implemented on a level of individual memory blocks.
  16186. Keeping track of a whole collection of blocks, allocating new ones when out of free space,
  16187. deleting empty ones, and deciding which one to try first for a new allocation must be implemented by the user.
  16188. Alternative allocation algorithms are supported, just like in custom pools of the real GPU memory.
  16189. See enum #VmaVirtualBlockCreateFlagBits to learn how to specify them (e.g. #VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT).
  16190. You can find their description in chapter \ref custom_memory_pools.
  16191. Allocation strategies are also supported.
  16192. See enum #VmaVirtualAllocationCreateFlagBits to learn how to specify them (e.g. #VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT).
  16193. Following features are supported only by the allocator of the real GPU memory and not by virtual allocations:
  16194. buffer-image granularity, `VMA_DEBUG_MARGIN`, `VMA_MIN_ALIGNMENT`.
  16195. \page debugging_memory_usage Debugging incorrect memory usage
  16196. If you suspect a bug with memory usage, like usage of uninitialized memory or
  16197. memory being overwritten out of bounds of an allocation,
  16198. you can use debug features of this library to verify this.
  16199. \section debugging_memory_usage_initialization Memory initialization
  16200. If you experience a bug with incorrect and nondeterministic data in your program and you suspect uninitialized memory to be used,
  16201. you can enable automatic memory initialization to verify this.
  16202. To do it, define macro `VMA_DEBUG_INITIALIZE_ALLOCATIONS` to 1.
  16203. \code
  16204. #define VMA_DEBUG_INITIALIZE_ALLOCATIONS 1
  16205. #include "vk_mem_alloc.h"
  16206. \endcode
  16207. It makes memory of new allocations initialized to bit pattern `0xDCDCDCDC`.
  16208. Before an allocation is destroyed, its memory is filled with bit pattern `0xEFEFEFEF`.
  16209. Memory is automatically mapped and unmapped if necessary.
  16210. If you find these values while debugging your program, good chances are that you incorrectly
  16211. read Vulkan memory that is allocated but not initialized, or already freed, respectively.
  16212. Memory initialization works only with memory types that are `HOST_VISIBLE` and with allocations that can be mapped.
  16213. It works also with dedicated allocations.
  16214. \section debugging_memory_usage_margins Margins
  16215. By default, allocations are laid out in memory blocks next to each other if possible
  16216. (considering required alignment, `bufferImageGranularity`, and `nonCoherentAtomSize`).
  16217. ![Allocations without margin](../gfx/Margins_1.png)
  16218. Define macro `VMA_DEBUG_MARGIN` to some non-zero value (e.g. 16) to enforce specified
  16219. number of bytes as a margin after every allocation.
  16220. \code
  16221. #define VMA_DEBUG_MARGIN 16
  16222. #include "vk_mem_alloc.h"
  16223. \endcode
  16224. ![Allocations with margin](../gfx/Margins_2.png)
  16225. If your bug goes away after enabling margins, it means it may be caused by memory
  16226. being overwritten outside of allocation boundaries. It is not 100% certain though.
  16227. Change in application behavior may also be caused by different order and distribution
  16228. of allocations across memory blocks after margins are applied.
  16229. Margins work with all types of memory.
  16230. Margin is applied only to allocations made out of memory blocks and not to dedicated
  16231. allocations, which have their own memory block of specific size.
  16232. It is thus not applied to allocations made using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT flag
  16233. or those automatically decided to put into dedicated allocations, e.g. due to its
  16234. large size or recommended by VK_KHR_dedicated_allocation extension.
  16235. Margins appear in [JSON dump](@ref statistics_json_dump) as part of free space.
  16236. Note that enabling margins increases memory usage and fragmentation.
  16237. Margins do not apply to \ref virtual_allocator.
  16238. \section debugging_memory_usage_corruption_detection Corruption detection
  16239. You can additionally define macro `VMA_DEBUG_DETECT_CORRUPTION` to 1 to enable validation
  16240. of contents of the margins.
  16241. \code
  16242. #define VMA_DEBUG_MARGIN 16
  16243. #define VMA_DEBUG_DETECT_CORRUPTION 1
  16244. #include "vk_mem_alloc.h"
  16245. \endcode
  16246. When this feature is enabled, number of bytes specified as `VMA_DEBUG_MARGIN`
  16247. (it must be multiply of 4) after every allocation is filled with a magic number.
  16248. This idea is also know as "canary".
  16249. Memory is automatically mapped and unmapped if necessary.
  16250. This number is validated automatically when the allocation is destroyed.
  16251. If it is not equal to the expected value, `VMA_ASSERT()` is executed.
  16252. It clearly means that either CPU or GPU overwritten the memory outside of boundaries of the allocation,
  16253. which indicates a serious bug.
  16254. You can also explicitly request checking margins of all allocations in all memory blocks
  16255. that belong to specified memory types by using function vmaCheckCorruption(),
  16256. or in memory blocks that belong to specified custom pool, by using function
  16257. vmaCheckPoolCorruption().
  16258. Margin validation (corruption detection) works only for memory types that are
  16259. `HOST_VISIBLE` and `HOST_COHERENT`.
  16260. \page opengl_interop OpenGL Interop
  16261. VMA provides some features that help with interoperability with OpenGL.
  16262. \section opengl_interop_exporting_memory Exporting memory
  16263. If you want to attach `VkExportMemoryAllocateInfoKHR` structure to `pNext` chain of memory allocations made by the library:
  16264. It is recommended to create \ref custom_memory_pools for such allocations.
  16265. Define and fill in your `VkExportMemoryAllocateInfoKHR` structure and attach it to VmaPoolCreateInfo::pMemoryAllocateNext
  16266. while creating the custom pool.
  16267. Please note that the structure must remain alive and unchanged for the whole lifetime of the #VmaPool,
  16268. not only while creating it, as no copy of the structure is made,
  16269. but its original pointer is used for each allocation instead.
  16270. If you want to export all memory allocated by the library from certain memory types,
  16271. also dedicated allocations or other allocations made from default pools,
  16272. an alternative solution is to fill in VmaAllocatorCreateInfo::pTypeExternalMemoryHandleTypes.
  16273. It should point to an array with `VkExternalMemoryHandleTypeFlagsKHR` to be automatically passed by the library
  16274. through `VkExportMemoryAllocateInfoKHR` on each allocation made from a specific memory type.
  16275. Please note that new versions of the library also support dedicated allocations created in custom pools.
  16276. You should not mix these two methods in a way that allows to apply both to the same memory type.
  16277. Otherwise, `VkExportMemoryAllocateInfoKHR` structure would be attached twice to the `pNext` chain of `VkMemoryAllocateInfo`.
  16278. \section opengl_interop_custom_alignment Custom alignment
  16279. Buffers or images exported to a different API like OpenGL may require a different alignment,
  16280. higher than the one used by the library automatically, queried from functions like `vkGetBufferMemoryRequirements`.
  16281. To impose such alignment:
  16282. It is recommended to create \ref custom_memory_pools for such allocations.
  16283. Set VmaPoolCreateInfo::minAllocationAlignment member to the minimum alignment required for each allocation
  16284. to be made out of this pool.
  16285. The alignment actually used will be the maximum of this member and the alignment returned for the specific buffer or image
  16286. from a function like `vkGetBufferMemoryRequirements`, which is called by VMA automatically.
  16287. If you want to create a buffer with a specific minimum alignment out of default pools,
  16288. use special function vmaCreateBufferWithAlignment(), which takes additional parameter `minAlignment`.
  16289. Note the problem of alignment affects only resources placed inside bigger `VkDeviceMemory` blocks and not dedicated
  16290. allocations, as these, by definition, always have alignment = 0 because the resource is bound to the beginning of its dedicated block.
  16291. Contrary to Direct3D 12, Vulkan doesn't have a concept of alignment of the entire memory block passed on its allocation.
  16292. \page usage_patterns Recommended usage patterns
  16293. Vulkan gives great flexibility in memory allocation.
  16294. This chapter shows the most common patterns.
  16295. See also slides from talk:
  16296. [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)
  16297. \section usage_patterns_gpu_only GPU-only resource
  16298. <b>When:</b>
  16299. Any resources that you frequently write and read on GPU,
  16300. e.g. images used as color attachments (aka "render targets"), depth-stencil attachments,
  16301. images/buffers used as storage image/buffer (aka "Unordered Access View (UAV)").
  16302. <b>What to do:</b>
  16303. Let the library select the optimal memory type, which will likely have `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`.
  16304. \code
  16305. VkImageCreateInfo imgCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
  16306. imgCreateInfo.imageType = VK_IMAGE_TYPE_2D;
  16307. imgCreateInfo.extent.width = 3840;
  16308. imgCreateInfo.extent.height = 2160;
  16309. imgCreateInfo.extent.depth = 1;
  16310. imgCreateInfo.mipLevels = 1;
  16311. imgCreateInfo.arrayLayers = 1;
  16312. imgCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
  16313. imgCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  16314. imgCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  16315. imgCreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  16316. imgCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
  16317. VmaAllocationCreateInfo allocCreateInfo = {};
  16318. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  16319. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  16320. allocCreateInfo.priority = 1.0f;
  16321. VkImage img;
  16322. VmaAllocation alloc;
  16323. vmaCreateImage(allocator, &imgCreateInfo, &allocCreateInfo, &img, &alloc, nullptr);
  16324. \endcode
  16325. <b>Also consider:</b>
  16326. Consider creating them as dedicated allocations using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
  16327. especially if they are large or if you plan to destroy and recreate them with different sizes
  16328. e.g. when display resolution changes.
  16329. Prefer to create such resources first and all other GPU resources (like textures and vertex buffers) later.
  16330. When VK_EXT_memory_priority extension is enabled, it is also worth setting high priority to such allocation
  16331. to decrease chances to be evicted to system memory by the operating system.
  16332. \section usage_patterns_staging_copy_upload Staging copy for upload
  16333. <b>When:</b>
  16334. A "staging" buffer than you want to map and fill from CPU code, then use as a source od transfer
  16335. to some GPU resource.
  16336. <b>What to do:</b>
  16337. Use flag #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT.
  16338. Let the library select the optimal memory type, which will always have `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`.
  16339. \code
  16340. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  16341. bufCreateInfo.size = 65536;
  16342. bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  16343. VmaAllocationCreateInfo allocCreateInfo = {};
  16344. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  16345. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT |
  16346. VMA_ALLOCATION_CREATE_MAPPED_BIT;
  16347. VkBuffer buf;
  16348. VmaAllocation alloc;
  16349. VmaAllocationInfo allocInfo;
  16350. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  16351. ...
  16352. memcpy(allocInfo.pMappedData, myData, myDataSize);
  16353. \endcode
  16354. <b>Also consider:</b>
  16355. You can map the allocation using vmaMapMemory() or you can create it as persistenly mapped
  16356. using #VMA_ALLOCATION_CREATE_MAPPED_BIT, as in the example above.
  16357. \section usage_patterns_readback Readback
  16358. <b>When:</b>
  16359. Buffers for data written by or transferred from the GPU that you want to read back on the CPU,
  16360. e.g. results of some computations.
  16361. <b>What to do:</b>
  16362. Use flag #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT.
  16363. Let the library select the optimal memory type, which will always have `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`
  16364. and `VK_MEMORY_PROPERTY_HOST_CACHED_BIT`.
  16365. \code
  16366. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  16367. bufCreateInfo.size = 65536;
  16368. bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  16369. VmaAllocationCreateInfo allocCreateInfo = {};
  16370. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  16371. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT |
  16372. VMA_ALLOCATION_CREATE_MAPPED_BIT;
  16373. VkBuffer buf;
  16374. VmaAllocation alloc;
  16375. VmaAllocationInfo allocInfo;
  16376. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  16377. ...
  16378. const float* downloadedData = (const float*)allocInfo.pMappedData;
  16379. \endcode
  16380. \section usage_patterns_advanced_data_uploading Advanced data uploading
  16381. For resources that you frequently write on CPU via mapped pointer and
  16382. freqnently read on GPU e.g. as a uniform buffer (also called "dynamic"), multiple options are possible:
  16383. -# Easiest solution is to have one copy of the resource in `HOST_VISIBLE` memory,
  16384. even if it means system RAM (not `DEVICE_LOCAL`) on systems with a discrete graphics card,
  16385. and make the device reach out to that resource directly.
  16386. - Reads performed by the device will then go through PCI Express bus.
  16387. The performace of this access may be limited, but it may be fine depending on the size
  16388. of this resource (whether it is small enough to quickly end up in GPU cache) and the sparsity
  16389. of access.
  16390. -# On systems with unified memory (e.g. AMD APU or Intel integrated graphics, mobile chips),
  16391. a memory type may be available that is both `HOST_VISIBLE` (available for mapping) and `DEVICE_LOCAL`
  16392. (fast to access from the GPU). Then, it is likely the best choice for such type of resource.
  16393. -# Systems with a discrete graphics card and separate video memory may or may not expose
  16394. a memory type that is both `HOST_VISIBLE` and `DEVICE_LOCAL`, also known as Base Address Register (BAR).
  16395. If they do, it represents a piece of VRAM (or entire VRAM, if ReBAR is enabled in the motherboard BIOS)
  16396. that is available to CPU for mapping.
  16397. - Writes performed by the host to that memory go through PCI Express bus.
  16398. The performance of these writes may be limited, but it may be fine, especially on PCIe 4.0,
  16399. as long as rules of using uncached and write-combined memory are followed - only sequential writes and no reads.
  16400. -# Finally, you may need or prefer to create a separate copy of the resource in `DEVICE_LOCAL` memory,
  16401. a separate "staging" copy in `HOST_VISIBLE` memory and perform an explicit transfer command between them.
  16402. Thankfully, VMA offers an aid to create and use such resources in the the way optimal
  16403. for the current Vulkan device. To help the library make the best choice,
  16404. use flag #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT together with
  16405. #VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT.
  16406. It will then prefer a memory type that is both `DEVICE_LOCAL` and `HOST_VISIBLE` (integrated memory or BAR),
  16407. but if no such memory type is available or allocation from it fails
  16408. (PC graphics cards have only 256 MB of BAR by default, unless ReBAR is supported and enabled in BIOS),
  16409. it will fall back to `DEVICE_LOCAL` memory for fast GPU access.
  16410. It is then up to you to detect that the allocation ended up in a memory type that is not `HOST_VISIBLE`,
  16411. so you need to create another "staging" allocation and perform explicit transfers.
  16412. \code
  16413. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  16414. bufCreateInfo.size = 65536;
  16415. bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  16416. VmaAllocationCreateInfo allocCreateInfo = {};
  16417. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  16418. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT |
  16419. VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT |
  16420. VMA_ALLOCATION_CREATE_MAPPED_BIT;
  16421. VkBuffer buf;
  16422. VmaAllocation alloc;
  16423. VmaAllocationInfo allocInfo;
  16424. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  16425. VkMemoryPropertyFlags memPropFlags;
  16426. vmaGetAllocationMemoryProperties(allocator, alloc, &memPropFlags);
  16427. if(memPropFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
  16428. {
  16429. // Allocation ended up in a mappable memory and is already mapped - write to it directly.
  16430. // [Executed in runtime]:
  16431. memcpy(allocInfo.pMappedData, myData, myDataSize);
  16432. }
  16433. else
  16434. {
  16435. // Allocation ended up in a non-mappable memory - need to transfer.
  16436. VkBufferCreateInfo stagingBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  16437. stagingBufCreateInfo.size = 65536;
  16438. stagingBufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  16439. VmaAllocationCreateInfo stagingAllocCreateInfo = {};
  16440. stagingAllocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  16441. stagingAllocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT |
  16442. VMA_ALLOCATION_CREATE_MAPPED_BIT;
  16443. VkBuffer stagingBuf;
  16444. VmaAllocation stagingAlloc;
  16445. VmaAllocationInfo stagingAllocInfo;
  16446. vmaCreateBuffer(allocator, &stagingBufCreateInfo, &stagingAllocCreateInfo,
  16447. &stagingBuf, &stagingAlloc, stagingAllocInfo);
  16448. // [Executed in runtime]:
  16449. memcpy(stagingAllocInfo.pMappedData, myData, myDataSize);
  16450. //vkCmdPipelineBarrier: VK_ACCESS_HOST_WRITE_BIT --> VK_ACCESS_TRANSFER_READ_BIT
  16451. VkBufferCopy bufCopy = {
  16452. 0, // srcOffset
  16453. 0, // dstOffset,
  16454. myDataSize); // size
  16455. vkCmdCopyBuffer(cmdBuf, stagingBuf, buf, 1, &bufCopy);
  16456. }
  16457. \endcode
  16458. \section usage_patterns_other_use_cases Other use cases
  16459. Here are some other, less obvious use cases and their recommended settings:
  16460. - An image that is used only as transfer source and destination, but it should stay on the device,
  16461. as it is used to temporarily store a copy of some texture, e.g. from the current to the next frame,
  16462. for temporal antialiasing or other temporal effects.
  16463. - Use `VkImageCreateInfo::usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT`
  16464. - Use VmaAllocationCreateInfo::usage = #VMA_MEMORY_USAGE_AUTO
  16465. - An image that is used only as transfer source and destination, but it should be placed
  16466. in the system RAM despite it doesn't need to be mapped, because it serves as a "swap" copy to evict
  16467. least recently used textures from VRAM.
  16468. - Use `VkImageCreateInfo::usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT`
  16469. - Use VmaAllocationCreateInfo::usage = #VMA_MEMORY_USAGE_AUTO_PREFER_HOST,
  16470. as VMA needs a hint here to differentiate from the previous case.
  16471. - A buffer that you want to map and write from the CPU, directly read from the GPU
  16472. (e.g. as a uniform or vertex buffer), but you have a clear preference to place it in device or
  16473. host memory due to its large size.
  16474. - Use `VkBufferCreateInfo::usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT`
  16475. - Use VmaAllocationCreateInfo::usage = #VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE or #VMA_MEMORY_USAGE_AUTO_PREFER_HOST
  16476. - Use VmaAllocationCreateInfo::flags = #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT
  16477. \page configuration Configuration
  16478. Please check "CONFIGURATION SECTION" in the code to find macros that you can define
  16479. before each include of this file or change directly in this file to provide
  16480. your own implementation of basic facilities like assert, `min()` and `max()` functions,
  16481. mutex, atomic etc.
  16482. The library uses its own implementation of containers by default, but you can switch to using
  16483. STL containers instead.
  16484. For example, define `VMA_ASSERT(expr)` before including the library to provide
  16485. custom implementation of the assertion, compatible with your project.
  16486. By default it is defined to standard C `assert(expr)` in `_DEBUG` configuration
  16487. and empty otherwise.
  16488. \section config_Vulkan_functions Pointers to Vulkan functions
  16489. There are multiple ways to import pointers to Vulkan functions in the library.
  16490. In the simplest case you don't need to do anything.
  16491. If the compilation or linking of your program or the initialization of the #VmaAllocator
  16492. doesn't work for you, you can try to reconfigure it.
  16493. First, the allocator tries to fetch pointers to Vulkan functions linked statically,
  16494. like this:
  16495. \code
  16496. m_VulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkAllocateMemory;
  16497. \endcode
  16498. If you want to disable this feature, set configuration macro: `#define VMA_STATIC_VULKAN_FUNCTIONS 0`.
  16499. Second, you can provide the pointers yourself by setting member VmaAllocatorCreateInfo::pVulkanFunctions.
  16500. You can fetch them e.g. using functions `vkGetInstanceProcAddr` and `vkGetDeviceProcAddr` or
  16501. by using a helper library like [volk](https://github.com/zeux/volk).
  16502. Third, VMA tries to fetch remaining pointers that are still null by calling
  16503. `vkGetInstanceProcAddr` and `vkGetDeviceProcAddr` on its own.
  16504. You need to only fill in VmaVulkanFunctions::vkGetInstanceProcAddr and VmaVulkanFunctions::vkGetDeviceProcAddr.
  16505. Other pointers will be fetched automatically.
  16506. If you want to disable this feature, set configuration macro: `#define VMA_DYNAMIC_VULKAN_FUNCTIONS 0`.
  16507. Finally, all the function pointers required by the library (considering selected
  16508. Vulkan version and enabled extensions) are checked with `VMA_ASSERT` if they are not null.
  16509. \section custom_memory_allocator Custom host memory allocator
  16510. If you use custom allocator for CPU memory rather than default operator `new`
  16511. and `delete` from C++, you can make this library using your allocator as well
  16512. by filling optional member VmaAllocatorCreateInfo::pAllocationCallbacks. These
  16513. functions will be passed to Vulkan, as well as used by the library itself to
  16514. make any CPU-side allocations.
  16515. \section allocation_callbacks Device memory allocation callbacks
  16516. The library makes calls to `vkAllocateMemory()` and `vkFreeMemory()` internally.
  16517. You can setup callbacks to be informed about these calls, e.g. for the purpose
  16518. of gathering some statistics. To do it, fill optional member
  16519. VmaAllocatorCreateInfo::pDeviceMemoryCallbacks.
  16520. \section heap_memory_limit Device heap memory limit
  16521. When device memory of certain heap runs out of free space, new allocations may
  16522. fail (returning error code) or they may succeed, silently pushing some existing_
  16523. memory blocks from GPU VRAM to system RAM (which degrades performance). This
  16524. behavior is implementation-dependent - it depends on GPU vendor and graphics
  16525. driver.
  16526. On AMD cards it can be controlled while creating Vulkan device object by using
  16527. VK_AMD_memory_overallocation_behavior extension, if available.
  16528. Alternatively, if you want to test how your program behaves with limited amount of Vulkan device
  16529. memory available without switching your graphics card to one that really has
  16530. smaller VRAM, you can use a feature of this library intended for this purpose.
  16531. To do it, fill optional member VmaAllocatorCreateInfo::pHeapSizeLimit.
  16532. \page vk_khr_dedicated_allocation VK_KHR_dedicated_allocation
  16533. VK_KHR_dedicated_allocation is a Vulkan extension which can be used to improve
  16534. performance on some GPUs. It augments Vulkan API with possibility to query
  16535. driver whether it prefers particular buffer or image to have its own, dedicated
  16536. allocation (separate `VkDeviceMemory` block) for better efficiency - to be able
  16537. to do some internal optimizations. The extension is supported by this library.
  16538. It will be used automatically when enabled.
  16539. It has been promoted to core Vulkan 1.1, so if you use eligible Vulkan version
  16540. and inform VMA about it by setting VmaAllocatorCreateInfo::vulkanApiVersion,
  16541. you are all set.
  16542. Otherwise, if you want to use it as an extension:
  16543. 1 . When creating Vulkan device, check if following 2 device extensions are
  16544. supported (call `vkEnumerateDeviceExtensionProperties()`).
  16545. If yes, enable them (fill `VkDeviceCreateInfo::ppEnabledExtensionNames`).
  16546. - VK_KHR_get_memory_requirements2
  16547. - VK_KHR_dedicated_allocation
  16548. If you enabled these extensions:
  16549. 2 . Use #VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag when creating
  16550. your #VmaAllocator to inform the library that you enabled required extensions
  16551. and you want the library to use them.
  16552. \code
  16553. allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT;
  16554. vmaCreateAllocator(&allocatorInfo, &allocator);
  16555. \endcode
  16556. That is all. The extension will be automatically used whenever you create a
  16557. buffer using vmaCreateBuffer() or image using vmaCreateImage().
  16558. When using the extension together with Vulkan Validation Layer, you will receive
  16559. warnings like this:
  16560. _vkBindBufferMemory(): Binding memory to buffer 0x33 but vkGetBufferMemoryRequirements() has not been called on that buffer._
  16561. It is OK, you should just ignore it. It happens because you use function
  16562. `vkGetBufferMemoryRequirements2KHR()` instead of standard
  16563. `vkGetBufferMemoryRequirements()`, while the validation layer seems to be
  16564. unaware of it.
  16565. To learn more about this extension, see:
  16566. - [VK_KHR_dedicated_allocation in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/chap50.html#VK_KHR_dedicated_allocation)
  16567. - [VK_KHR_dedicated_allocation unofficial manual](http://asawicki.info/articles/VK_KHR_dedicated_allocation.php5)
  16568. \page vk_ext_memory_priority VK_EXT_memory_priority
  16569. VK_EXT_memory_priority is a device extension that allows to pass additional "priority"
  16570. value to Vulkan memory allocations that the implementation may use prefer certain
  16571. buffers and images that are critical for performance to stay in device-local memory
  16572. in cases when the memory is over-subscribed, while some others may be moved to the system memory.
  16573. VMA offers convenient usage of this extension.
  16574. If you enable it, you can pass "priority" parameter when creating allocations or custom pools
  16575. and the library automatically passes the value to Vulkan using this extension.
  16576. If you want to use this extension in connection with VMA, follow these steps:
  16577. \section vk_ext_memory_priority_initialization Initialization
  16578. 1) Call `vkEnumerateDeviceExtensionProperties` for the physical device.
  16579. Check if the extension is supported - if returned array of `VkExtensionProperties` contains "VK_EXT_memory_priority".
  16580. 2) Call `vkGetPhysicalDeviceFeatures2` for the physical device instead of old `vkGetPhysicalDeviceFeatures`.
  16581. Attach additional structure `VkPhysicalDeviceMemoryPriorityFeaturesEXT` to `VkPhysicalDeviceFeatures2::pNext` to be returned.
  16582. Check if the device feature is really supported - check if `VkPhysicalDeviceMemoryPriorityFeaturesEXT::memoryPriority` is true.
  16583. 3) While creating device with `vkCreateDevice`, enable this extension - add "VK_EXT_memory_priority"
  16584. to the list passed as `VkDeviceCreateInfo::ppEnabledExtensionNames`.
  16585. 4) While creating the device, also don't set `VkDeviceCreateInfo::pEnabledFeatures`.
  16586. Fill in `VkPhysicalDeviceFeatures2` structure instead and pass it as `VkDeviceCreateInfo::pNext`.
  16587. Enable this device feature - attach additional structure `VkPhysicalDeviceMemoryPriorityFeaturesEXT` to
  16588. `VkPhysicalDeviceFeatures2::pNext` chain and set its member `memoryPriority` to `VK_TRUE`.
  16589. 5) While creating #VmaAllocator with vmaCreateAllocator() inform VMA that you
  16590. have enabled this extension and feature - add #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT
  16591. to VmaAllocatorCreateInfo::flags.
  16592. \section vk_ext_memory_priority_usage Usage
  16593. When using this extension, you should initialize following member:
  16594. - VmaAllocationCreateInfo::priority when creating a dedicated allocation with #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  16595. - VmaPoolCreateInfo::priority when creating a custom pool.
  16596. It should be a floating-point value between `0.0f` and `1.0f`, where recommended default is `0.5f`.
  16597. Memory allocated with higher value can be treated by the Vulkan implementation as higher priority
  16598. and so it can have lower chances of being pushed out to system memory, experiencing degraded performance.
  16599. It might be a good idea to create performance-critical resources like color-attachment or depth-stencil images
  16600. as dedicated and set high priority to them. For example:
  16601. \code
  16602. VkImageCreateInfo imgCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
  16603. imgCreateInfo.imageType = VK_IMAGE_TYPE_2D;
  16604. imgCreateInfo.extent.width = 3840;
  16605. imgCreateInfo.extent.height = 2160;
  16606. imgCreateInfo.extent.depth = 1;
  16607. imgCreateInfo.mipLevels = 1;
  16608. imgCreateInfo.arrayLayers = 1;
  16609. imgCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
  16610. imgCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  16611. imgCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  16612. imgCreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  16613. imgCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
  16614. VmaAllocationCreateInfo allocCreateInfo = {};
  16615. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  16616. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  16617. allocCreateInfo.priority = 1.0f;
  16618. VkImage img;
  16619. VmaAllocation alloc;
  16620. vmaCreateImage(allocator, &imgCreateInfo, &allocCreateInfo, &img, &alloc, nullptr);
  16621. \endcode
  16622. `priority` member is ignored in the following situations:
  16623. - Allocations created in custom pools: They inherit the priority, along with all other allocation parameters
  16624. from the parametrs passed in #VmaPoolCreateInfo when the pool was created.
  16625. - Allocations created in default pools: They inherit the priority from the parameters
  16626. VMA used when creating default pools, which means `priority == 0.5f`.
  16627. \page vk_amd_device_coherent_memory VK_AMD_device_coherent_memory
  16628. VK_AMD_device_coherent_memory is a device extension that enables access to
  16629. additional memory types with `VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD` and
  16630. `VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` flag. It is useful mostly for
  16631. allocation of buffers intended for writing "breadcrumb markers" in between passes
  16632. or draw calls, which in turn are useful for debugging GPU crash/hang/TDR cases.
  16633. When the extension is available but has not been enabled, Vulkan physical device
  16634. still exposes those memory types, but their usage is forbidden. VMA automatically
  16635. takes care of that - it returns `VK_ERROR_FEATURE_NOT_PRESENT` when an attempt
  16636. to allocate memory of such type is made.
  16637. If you want to use this extension in connection with VMA, follow these steps:
  16638. \section vk_amd_device_coherent_memory_initialization Initialization
  16639. 1) Call `vkEnumerateDeviceExtensionProperties` for the physical device.
  16640. Check if the extension is supported - if returned array of `VkExtensionProperties` contains "VK_AMD_device_coherent_memory".
  16641. 2) Call `vkGetPhysicalDeviceFeatures2` for the physical device instead of old `vkGetPhysicalDeviceFeatures`.
  16642. Attach additional structure `VkPhysicalDeviceCoherentMemoryFeaturesAMD` to `VkPhysicalDeviceFeatures2::pNext` to be returned.
  16643. Check if the device feature is really supported - check if `VkPhysicalDeviceCoherentMemoryFeaturesAMD::deviceCoherentMemory` is true.
  16644. 3) While creating device with `vkCreateDevice`, enable this extension - add "VK_AMD_device_coherent_memory"
  16645. to the list passed as `VkDeviceCreateInfo::ppEnabledExtensionNames`.
  16646. 4) While creating the device, also don't set `VkDeviceCreateInfo::pEnabledFeatures`.
  16647. Fill in `VkPhysicalDeviceFeatures2` structure instead and pass it as `VkDeviceCreateInfo::pNext`.
  16648. Enable this device feature - attach additional structure `VkPhysicalDeviceCoherentMemoryFeaturesAMD` to
  16649. `VkPhysicalDeviceFeatures2::pNext` and set its member `deviceCoherentMemory` to `VK_TRUE`.
  16650. 5) While creating #VmaAllocator with vmaCreateAllocator() inform VMA that you
  16651. have enabled this extension and feature - add #VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT
  16652. to VmaAllocatorCreateInfo::flags.
  16653. \section vk_amd_device_coherent_memory_usage Usage
  16654. After following steps described above, you can create VMA allocations and custom pools
  16655. out of the special `DEVICE_COHERENT` and `DEVICE_UNCACHED` memory types on eligible
  16656. devices. There are multiple ways to do it, for example:
  16657. - You can request or prefer to allocate out of such memory types by adding
  16658. `VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` to VmaAllocationCreateInfo::requiredFlags
  16659. or VmaAllocationCreateInfo::preferredFlags. Those flags can be freely mixed with
  16660. other ways of \ref choosing_memory_type, like setting VmaAllocationCreateInfo::usage.
  16661. - If you manually found memory type index to use for this purpose, force allocation
  16662. from this specific index by setting VmaAllocationCreateInfo::memoryTypeBits `= 1u << index`.
  16663. \section vk_amd_device_coherent_memory_more_information More information
  16664. 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/man/html/VK_AMD_device_coherent_memory.html)
  16665. Example use of this extension can be found in the code of the sample and test suite
  16666. accompanying this library.
  16667. \page enabling_buffer_device_address Enabling buffer device address
  16668. Device extension VK_KHR_buffer_device_address
  16669. allow to fetch raw GPU pointer to a buffer and pass it for usage in a shader code.
  16670. It has been promoted to core Vulkan 1.2.
  16671. If you want to use this feature in connection with VMA, follow these steps:
  16672. \section enabling_buffer_device_address_initialization Initialization
  16673. 1) (For Vulkan version < 1.2) Call `vkEnumerateDeviceExtensionProperties` for the physical device.
  16674. Check if the extension is supported - if returned array of `VkExtensionProperties` contains
  16675. "VK_KHR_buffer_device_address".
  16676. 2) Call `vkGetPhysicalDeviceFeatures2` for the physical device instead of old `vkGetPhysicalDeviceFeatures`.
  16677. Attach additional structure `VkPhysicalDeviceBufferDeviceAddressFeatures*` to `VkPhysicalDeviceFeatures2::pNext` to be returned.
  16678. Check if the device feature is really supported - check if `VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress` is true.
  16679. 3) (For Vulkan version < 1.2) While creating device with `vkCreateDevice`, enable this extension - add
  16680. "VK_KHR_buffer_device_address" to the list passed as `VkDeviceCreateInfo::ppEnabledExtensionNames`.
  16681. 4) While creating the device, also don't set `VkDeviceCreateInfo::pEnabledFeatures`.
  16682. Fill in `VkPhysicalDeviceFeatures2` structure instead and pass it as `VkDeviceCreateInfo::pNext`.
  16683. Enable this device feature - attach additional structure `VkPhysicalDeviceBufferDeviceAddressFeatures*` to
  16684. `VkPhysicalDeviceFeatures2::pNext` and set its member `bufferDeviceAddress` to `VK_TRUE`.
  16685. 5) While creating #VmaAllocator with vmaCreateAllocator() inform VMA that you
  16686. have enabled this feature - add #VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT
  16687. to VmaAllocatorCreateInfo::flags.
  16688. \section enabling_buffer_device_address_usage Usage
  16689. After following steps described above, you can create buffers with `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT*` using VMA.
  16690. The library automatically adds `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT*` to
  16691. allocated memory blocks wherever it might be needed.
  16692. Please note that the library supports only `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT*`.
  16693. The second part of this functionality related to "capture and replay" is not supported,
  16694. as it is intended for usage in debugging tools like RenderDoc, not in everyday Vulkan usage.
  16695. \section enabling_buffer_device_address_more_information More information
  16696. 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)
  16697. Example use of this extension can be found in the code of the sample and test suite
  16698. accompanying this library.
  16699. \page general_considerations General considerations
  16700. \section general_considerations_thread_safety Thread safety
  16701. - The library has no global state, so separate #VmaAllocator objects can be used
  16702. independently.
  16703. There should be no need to create multiple such objects though - one per `VkDevice` is enough.
  16704. - By default, all calls to functions that take #VmaAllocator as first parameter
  16705. are safe to call from multiple threads simultaneously because they are
  16706. synchronized internally when needed.
  16707. This includes allocation and deallocation from default memory pool, as well as custom #VmaPool.
  16708. - When the allocator is created with #VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT
  16709. flag, calls to functions that take such #VmaAllocator object must be
  16710. synchronized externally.
  16711. - Access to a #VmaAllocation object must be externally synchronized. For example,
  16712. you must not call vmaGetAllocationInfo() and vmaMapMemory() from different
  16713. threads at the same time if you pass the same #VmaAllocation object to these
  16714. functions.
  16715. - #VmaVirtualBlock is not safe to be used from multiple threads simultaneously.
  16716. \section general_considerations_versioning_and_compatibility Versioning and compatibility
  16717. The library uses [**Semantic Versioning**](https://semver.org/),
  16718. which means version numbers follow convention: Major.Minor.Patch (e.g. 2.3.0), where:
  16719. - Incremented Patch version means a release is backward- and forward-compatible,
  16720. introducing only some internal improvements, bug fixes, optimizations etc.
  16721. or changes that are out of scope of the official API described in this documentation.
  16722. - Incremented Minor version means a release is backward-compatible,
  16723. so existing code that uses the library should continue to work, while some new
  16724. symbols could have been added: new structures, functions, new values in existing
  16725. enums and bit flags, new structure members, but not new function parameters.
  16726. - Incrementing Major version means a release could break some backward compatibility.
  16727. All changes between official releases are documented in file "CHANGELOG.md".
  16728. \warning Backward compatiblity is considered on the level of C++ source code, not binary linkage.
  16729. Adding new members to existing structures is treated as backward compatible if initializing
  16730. the new members to binary zero results in the old behavior.
  16731. You should always fully initialize all library structures to zeros and not rely on their
  16732. exact binary size.
  16733. \section general_considerations_validation_layer_warnings Validation layer warnings
  16734. When using this library, you can meet following types of warnings issued by
  16735. Vulkan validation layer. They don't necessarily indicate a bug, so you may need
  16736. to just ignore them.
  16737. - *vkBindBufferMemory(): Binding memory to buffer 0xeb8e4 but vkGetBufferMemoryRequirements() has not been called on that buffer.*
  16738. - It happens when VK_KHR_dedicated_allocation extension is enabled.
  16739. `vkGetBufferMemoryRequirements2KHR` function is used instead, while validation layer seems to be unaware of it.
  16740. - *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.*
  16741. - It happens when you map a buffer or image, because the library maps entire
  16742. `VkDeviceMemory` block, where different types of images and buffers may end
  16743. up together, especially on GPUs with unified memory like Intel.
  16744. - *Non-linear image 0xebc91 is aliased with linear buffer 0xeb8e4 which may indicate a bug.*
  16745. - It may happen when you use [defragmentation](@ref defragmentation).
  16746. \section general_considerations_allocation_algorithm Allocation algorithm
  16747. The library uses following algorithm for allocation, in order:
  16748. -# Try to find free range of memory in existing blocks.
  16749. -# If failed, try to create a new block of `VkDeviceMemory`, with preferred block size.
  16750. -# If failed, try to create such block with size / 2, size / 4, size / 8.
  16751. -# If failed, try to allocate separate `VkDeviceMemory` for this allocation,
  16752. just like when you use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  16753. -# If failed, choose other memory type that meets the requirements specified in
  16754. VmaAllocationCreateInfo and go to point 1.
  16755. -# If failed, return `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  16756. \section general_considerations_features_not_supported Features not supported
  16757. Features deliberately excluded from the scope of this library:
  16758. -# **Data transfer.** Uploading (streaming) and downloading data of buffers and images
  16759. between CPU and GPU memory and related synchronization is responsibility of the user.
  16760. Defining some "texture" object that would automatically stream its data from a
  16761. staging copy in CPU memory to GPU memory would rather be a feature of another,
  16762. higher-level library implemented on top of VMA.
  16763. VMA doesn't record any commands to a `VkCommandBuffer`. It just allocates memory.
  16764. -# **Recreation of buffers and images.** Although the library has functions for
  16765. buffer and image creation: vmaCreateBuffer(), vmaCreateImage(), you need to
  16766. recreate these objects yourself after defragmentation. That is because the big
  16767. structures `VkBufferCreateInfo`, `VkImageCreateInfo` are not stored in
  16768. #VmaAllocation object.
  16769. -# **Handling CPU memory allocation failures.** When dynamically creating small C++
  16770. objects in CPU memory (not Vulkan memory), allocation failures are not checked
  16771. and handled gracefully, because that would complicate code significantly and
  16772. is usually not needed in desktop PC applications anyway.
  16773. Success of an allocation is just checked with an assert.
  16774. -# **Code free of any compiler warnings.** Maintaining the library to compile and
  16775. work correctly on so many different platforms is hard enough. Being free of
  16776. any warnings, on any version of any compiler, is simply not feasible.
  16777. There are many preprocessor macros that make some variables unused, function parameters unreferenced,
  16778. or conditional expressions constant in some configurations.
  16779. The code of this library should not be bigger or more complicated just to silence these warnings.
  16780. It is recommended to disable such warnings instead.
  16781. -# This is a C++ library with C interface. **Bindings or ports to any other programming languages** are welcome as external projects but
  16782. are not going to be included into this repository.
  16783. */