vk_mem_alloc.h 619 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746
  1. //
  2. // Copyright (c) 2017-2019 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. #ifdef __cplusplus
  25. extern "C" {
  26. #endif
  27. /** \mainpage Vulkan Memory Allocator
  28. <b>Version 2.3.0</b> (2019-12-04)
  29. Copyright (c) 2017-2019 Advanced Micro Devices, Inc. All rights reserved. \n
  30. License: MIT
  31. Documentation of all members: vk_mem_alloc.h
  32. \section main_table_of_contents Table of contents
  33. - <b>User guide</b>
  34. - \subpage quick_start
  35. - [Project setup](@ref quick_start_project_setup)
  36. - [Initialization](@ref quick_start_initialization)
  37. - [Resource allocation](@ref quick_start_resource_allocation)
  38. - \subpage choosing_memory_type
  39. - [Usage](@ref choosing_memory_type_usage)
  40. - [Required and preferred flags](@ref choosing_memory_type_required_preferred_flags)
  41. - [Explicit memory types](@ref choosing_memory_type_explicit_memory_types)
  42. - [Custom memory pools](@ref choosing_memory_type_custom_memory_pools)
  43. - [Dedicated allocations](@ref choosing_memory_type_dedicated_allocations)
  44. - \subpage memory_mapping
  45. - [Mapping functions](@ref memory_mapping_mapping_functions)
  46. - [Persistently mapped memory](@ref memory_mapping_persistently_mapped_memory)
  47. - [Cache flush and invalidate](@ref memory_mapping_cache_control)
  48. - [Finding out if memory is mappable](@ref memory_mapping_finding_if_memory_mappable)
  49. - \subpage staying_within_budget
  50. - [Querying for budget](@ref staying_within_budget_querying_for_budget)
  51. - [Controlling memory usage](@ref staying_within_budget_controlling_memory_usage)
  52. - \subpage custom_memory_pools
  53. - [Choosing memory type index](@ref custom_memory_pools_MemTypeIndex)
  54. - [Linear allocation algorithm](@ref linear_algorithm)
  55. - [Free-at-once](@ref linear_algorithm_free_at_once)
  56. - [Stack](@ref linear_algorithm_stack)
  57. - [Double stack](@ref linear_algorithm_double_stack)
  58. - [Ring buffer](@ref linear_algorithm_ring_buffer)
  59. - [Buddy allocation algorithm](@ref buddy_algorithm)
  60. - \subpage defragmentation
  61. - [Defragmenting CPU memory](@ref defragmentation_cpu)
  62. - [Defragmenting GPU memory](@ref defragmentation_gpu)
  63. - [Additional notes](@ref defragmentation_additional_notes)
  64. - [Writing custom allocation algorithm](@ref defragmentation_custom_algorithm)
  65. - \subpage lost_allocations
  66. - \subpage statistics
  67. - [Numeric statistics](@ref statistics_numeric_statistics)
  68. - [JSON dump](@ref statistics_json_dump)
  69. - \subpage allocation_annotation
  70. - [Allocation user data](@ref allocation_user_data)
  71. - [Allocation names](@ref allocation_names)
  72. - \subpage debugging_memory_usage
  73. - [Memory initialization](@ref debugging_memory_usage_initialization)
  74. - [Margins](@ref debugging_memory_usage_margins)
  75. - [Corruption detection](@ref debugging_memory_usage_corruption_detection)
  76. - \subpage record_and_replay
  77. - \subpage usage_patterns
  78. - [Common mistakes](@ref usage_patterns_common_mistakes)
  79. - [Simple patterns](@ref usage_patterns_simple)
  80. - [Advanced patterns](@ref usage_patterns_advanced)
  81. - \subpage configuration
  82. - [Pointers to Vulkan functions](@ref config_Vulkan_functions)
  83. - [Custom host memory allocator](@ref custom_memory_allocator)
  84. - [Device memory allocation callbacks](@ref allocation_callbacks)
  85. - [Device heap memory limit](@ref heap_memory_limit)
  86. - \subpage vk_khr_dedicated_allocation
  87. - \subpage general_considerations
  88. - [Thread safety](@ref general_considerations_thread_safety)
  89. - [Validation layer warnings](@ref general_considerations_validation_layer_warnings)
  90. - [Allocation algorithm](@ref general_considerations_allocation_algorithm)
  91. - [Features not supported](@ref general_considerations_features_not_supported)
  92. \section main_see_also See also
  93. - [Product page on GPUOpen](https://gpuopen.com/gaming-product/vulkan-memory-allocator/)
  94. - [Source repository on GitHub](https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator)
  95. \page quick_start Quick start
  96. \section quick_start_project_setup Project setup
  97. Vulkan Memory Allocator comes in form of a "stb-style" single header file.
  98. You don't need to build it as a separate library project.
  99. You can add this file directly to your project and submit it to code repository next to your other source files.
  100. "Single header" doesn't mean that everything is contained in C/C++ declarations,
  101. like it tends to be in case of inline functions or C++ templates.
  102. It means that implementation is bundled with interface in a single file and needs to be extracted using preprocessor macro.
  103. If you don't do it properly, you will get linker errors.
  104. To do it properly:
  105. -# Include "vk_mem_alloc.h" file in each CPP file where you want to use the library.
  106. This includes declarations of all members of the library.
  107. -# In exacly one CPP file define following macro before this include.
  108. It enables also internal definitions.
  109. \code
  110. #define VMA_IMPLEMENTATION
  111. #include "vk_mem_alloc.h"
  112. \endcode
  113. It may be a good idea to create dedicated CPP file just for this purpose.
  114. Note on language: This library is written in C++, but has C-compatible interface.
  115. Thus you can include and use vk_mem_alloc.h in C or C++ code, but full
  116. implementation with `VMA_IMPLEMENTATION` macro must be compiled as C++, NOT as C.
  117. Please note that this library includes header `<vulkan/vulkan.h>`, which in turn
  118. includes `<windows.h>` on Windows. If you need some specific macros defined
  119. before including these headers (like `WIN32_LEAN_AND_MEAN` or
  120. `WINVER` for Windows, `VK_USE_PLATFORM_WIN32_KHR` for Vulkan), you must define
  121. them before every `#include` of this library.
  122. \section quick_start_initialization Initialization
  123. At program startup:
  124. -# Initialize Vulkan to have `VkPhysicalDevice` and `VkDevice` object.
  125. -# Fill VmaAllocatorCreateInfo structure and create #VmaAllocator object by
  126. calling vmaCreateAllocator().
  127. \code
  128. VmaAllocatorCreateInfo allocatorInfo = {};
  129. allocatorInfo.physicalDevice = physicalDevice;
  130. allocatorInfo.device = device;
  131. VmaAllocator allocator;
  132. vmaCreateAllocator(&allocatorInfo, &allocator);
  133. \endcode
  134. \section quick_start_resource_allocation Resource allocation
  135. When you want to create a buffer or image:
  136. -# Fill `VkBufferCreateInfo` / `VkImageCreateInfo` structure.
  137. -# Fill VmaAllocationCreateInfo structure.
  138. -# Call vmaCreateBuffer() / vmaCreateImage() to get `VkBuffer`/`VkImage` with memory
  139. already allocated and bound to it.
  140. \code
  141. VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  142. bufferInfo.size = 65536;
  143. bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  144. VmaAllocationCreateInfo allocInfo = {};
  145. allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  146. VkBuffer buffer;
  147. VmaAllocation allocation;
  148. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  149. \endcode
  150. Don't forget to destroy your objects when no longer needed:
  151. \code
  152. vmaDestroyBuffer(allocator, buffer, allocation);
  153. vmaDestroyAllocator(allocator);
  154. \endcode
  155. \page choosing_memory_type Choosing memory type
  156. Physical devices in Vulkan support various combinations of memory heaps and
  157. types. Help with choosing correct and optimal memory type for your specific
  158. resource is one of the key features of this library. You can use it by filling
  159. appropriate members of VmaAllocationCreateInfo structure, as described below.
  160. You can also combine multiple methods.
  161. -# If you just want to find memory type index that meets your requirements, you
  162. can use function: vmaFindMemoryTypeIndex(), vmaFindMemoryTypeIndexForBufferInfo(),
  163. vmaFindMemoryTypeIndexForImageInfo().
  164. -# If you want to allocate a region of device memory without association with any
  165. specific image or buffer, you can use function vmaAllocateMemory(). Usage of
  166. this function is not recommended and usually not needed.
  167. vmaAllocateMemoryPages() function is also provided for creating multiple allocations at once,
  168. which may be useful for sparse binding.
  169. -# If you already have a buffer or an image created, you want to allocate memory
  170. for it and then you will bind it yourself, you can use function
  171. vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage().
  172. For binding you should use functions: vmaBindBufferMemory(), vmaBindImageMemory()
  173. or their extended versions: vmaBindBufferMemory2(), vmaBindImageMemory2().
  174. -# If you want to create a buffer or an image, allocate memory for it and bind
  175. them together, all in one call, you can use function vmaCreateBuffer(),
  176. vmaCreateImage(). This is the easiest and recommended way to use this library.
  177. When using 3. or 4., the library internally queries Vulkan for memory types
  178. supported for that buffer or image (function `vkGetBufferMemoryRequirements()`)
  179. and uses only one of these types.
  180. If no memory type can be found that meets all the requirements, these functions
  181. return `VK_ERROR_FEATURE_NOT_PRESENT`.
  182. You can leave VmaAllocationCreateInfo structure completely filled with zeros.
  183. It means no requirements are specified for memory type.
  184. It is valid, although not very useful.
  185. \section choosing_memory_type_usage Usage
  186. The easiest way to specify memory requirements is to fill member
  187. VmaAllocationCreateInfo::usage using one of the values of enum #VmaMemoryUsage.
  188. It defines high level, common usage types.
  189. For more details, see description of this enum.
  190. For example, if you want to create a uniform buffer that will be filled using
  191. transfer only once or infrequently and used for rendering every frame, you can
  192. do it using following code:
  193. \code
  194. VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  195. bufferInfo.size = 65536;
  196. bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  197. VmaAllocationCreateInfo allocInfo = {};
  198. allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  199. VkBuffer buffer;
  200. VmaAllocation allocation;
  201. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  202. \endcode
  203. \section choosing_memory_type_required_preferred_flags Required and preferred flags
  204. You can specify more detailed requirements by filling members
  205. VmaAllocationCreateInfo::requiredFlags and VmaAllocationCreateInfo::preferredFlags
  206. with a combination of bits from enum `VkMemoryPropertyFlags`. For example,
  207. if you want to create a buffer that will be persistently mapped on host (so it
  208. must be `HOST_VISIBLE`) and preferably will also be `HOST_COHERENT` and `HOST_CACHED`,
  209. use following code:
  210. \code
  211. VmaAllocationCreateInfo allocInfo = {};
  212. allocInfo.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  213. allocInfo.preferredFlags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  214. allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
  215. VkBuffer buffer;
  216. VmaAllocation allocation;
  217. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  218. \endcode
  219. A memory type is chosen that has all the required flags and as many preferred
  220. flags set as possible.
  221. If you use VmaAllocationCreateInfo::usage, it is just internally converted to
  222. a set of required and preferred flags.
  223. \section choosing_memory_type_explicit_memory_types Explicit memory types
  224. If you inspected memory types available on the physical device and you have
  225. a preference for memory types that you want to use, you can fill member
  226. VmaAllocationCreateInfo::memoryTypeBits. It is a bit mask, where each bit set
  227. means that a memory type with that index is allowed to be used for the
  228. allocation. Special value 0, just like `UINT32_MAX`, means there are no
  229. restrictions to memory type index.
  230. Please note that this member is NOT just a memory type index.
  231. Still you can use it to choose just one, specific memory type.
  232. For example, if you already determined that your buffer should be created in
  233. memory type 2, use following code:
  234. \code
  235. uint32_t memoryTypeIndex = 2;
  236. VmaAllocationCreateInfo allocInfo = {};
  237. allocInfo.memoryTypeBits = 1u << memoryTypeIndex;
  238. VkBuffer buffer;
  239. VmaAllocation allocation;
  240. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  241. \endcode
  242. \section choosing_memory_type_custom_memory_pools Custom memory pools
  243. If you allocate from custom memory pool, all the ways of specifying memory
  244. requirements described above are not applicable and the aforementioned members
  245. of VmaAllocationCreateInfo structure are ignored. Memory type is selected
  246. explicitly when creating the pool and then used to make all the allocations from
  247. that pool. For further details, see \ref custom_memory_pools.
  248. \section choosing_memory_type_dedicated_allocations Dedicated allocations
  249. Memory for allocations is reserved out of larger block of `VkDeviceMemory`
  250. allocated from Vulkan internally. That's the main feature of this whole library.
  251. You can still request a separate memory block to be created for an allocation,
  252. just like you would do in a trivial solution without using any allocator.
  253. In that case, a buffer or image is always bound to that memory at offset 0.
  254. This is called a "dedicated allocation".
  255. You can explicitly request it by using flag #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  256. The library can also internally decide to use dedicated allocation in some cases, e.g.:
  257. - When the size of the allocation is large.
  258. - When [VK_KHR_dedicated_allocation](@ref vk_khr_dedicated_allocation) extension is enabled
  259. and it reports that dedicated allocation is required or recommended for the resource.
  260. - When allocation of next big memory block fails due to not enough device memory,
  261. but allocation with the exact requested size succeeds.
  262. \page memory_mapping Memory mapping
  263. To "map memory" in Vulkan means to obtain a CPU pointer to `VkDeviceMemory`,
  264. to be able to read from it or write to it in CPU code.
  265. Mapping is possible only of memory allocated from a memory type that has
  266. `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag.
  267. Functions `vkMapMemory()`, `vkUnmapMemory()` are designed for this purpose.
  268. You can use them directly with memory allocated by this library,
  269. but it is not recommended because of following issue:
  270. Mapping the same `VkDeviceMemory` block multiple times is illegal - only one mapping at a time is allowed.
  271. This includes mapping disjoint regions. Mapping is not reference-counted internally by Vulkan.
  272. Because of this, Vulkan Memory Allocator provides following facilities:
  273. \section memory_mapping_mapping_functions Mapping functions
  274. The library provides following functions for mapping of a specific #VmaAllocation: vmaMapMemory(), vmaUnmapMemory().
  275. They are safer and more convenient to use than standard Vulkan functions.
  276. You can map an allocation multiple times simultaneously - mapping is reference-counted internally.
  277. You can also map different allocations simultaneously regardless of whether they use the same `VkDeviceMemory` block.
  278. The way it's implemented is that the library always maps entire memory block, not just region of the allocation.
  279. For further details, see description of vmaMapMemory() function.
  280. Example:
  281. \code
  282. // Having these objects initialized:
  283. struct ConstantBuffer
  284. {
  285. ...
  286. };
  287. ConstantBuffer constantBufferData;
  288. VmaAllocator allocator;
  289. VkBuffer constantBuffer;
  290. VmaAllocation constantBufferAllocation;
  291. // You can map and fill your buffer using following code:
  292. void* mappedData;
  293. vmaMapMemory(allocator, constantBufferAllocation, &mappedData);
  294. memcpy(mappedData, &constantBufferData, sizeof(constantBufferData));
  295. vmaUnmapMemory(allocator, constantBufferAllocation);
  296. \endcode
  297. When mapping, you may see a warning from Vulkan validation layer similar to this one:
  298. <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>
  299. It happens because the library maps entire `VkDeviceMemory` block, where different
  300. types of images and buffers may end up together, especially on GPUs with unified memory like Intel.
  301. You can safely ignore it if you are sure you access only memory of the intended
  302. object that you wanted to map.
  303. \section memory_mapping_persistently_mapped_memory Persistently mapped memory
  304. Kepping your memory persistently mapped is generally OK in Vulkan.
  305. You don't need to unmap it before using its data on the GPU.
  306. The library provides a special feature designed for that:
  307. Allocations made with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag set in
  308. VmaAllocationCreateInfo::flags stay mapped all the time,
  309. so you can just access CPU pointer to it any time
  310. without a need to call any "map" or "unmap" function.
  311. Example:
  312. \code
  313. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  314. bufCreateInfo.size = sizeof(ConstantBuffer);
  315. bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  316. VmaAllocationCreateInfo allocCreateInfo = {};
  317. allocCreateInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
  318. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
  319. VkBuffer buf;
  320. VmaAllocation alloc;
  321. VmaAllocationInfo allocInfo;
  322. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  323. // Buffer is already mapped. You can access its memory.
  324. memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData));
  325. \endcode
  326. There are some exceptions though, when you should consider mapping memory only for a short period of time:
  327. - When operating system is Windows 7 or 8.x (Windows 10 is not affected because it uses WDDM2),
  328. device is discrete AMD GPU,
  329. and memory type is the special 256 MiB pool of `DEVICE_LOCAL + HOST_VISIBLE` memory
  330. (selected when you use #VMA_MEMORY_USAGE_CPU_TO_GPU),
  331. then whenever a memory block allocated from this memory type stays mapped
  332. for the time of any call to `vkQueueSubmit()` or `vkQueuePresentKHR()`, this
  333. block is migrated by WDDM to system RAM, which degrades performance. It doesn't
  334. matter if that particular memory block is actually used by the command buffer
  335. being submitted.
  336. - On Mac/MoltenVK there is a known bug - [Issue #175](https://github.com/KhronosGroup/MoltenVK/issues/175)
  337. which requires unmapping before GPU can see updated texture.
  338. - Keeping many large memory blocks mapped may impact performance or stability of some debugging tools.
  339. \section memory_mapping_cache_control Cache flush and invalidate
  340. Memory in Vulkan doesn't need to be unmapped before using it on GPU,
  341. but unless a memory types has `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT` flag set,
  342. you need to manually **invalidate** cache before reading of mapped pointer
  343. and **flush** cache after writing to mapped pointer.
  344. Map/unmap operations don't do that automatically.
  345. Vulkan provides following functions for this purpose `vkFlushMappedMemoryRanges()`,
  346. `vkInvalidateMappedMemoryRanges()`, but this library provides more convenient
  347. functions that refer to given allocation object: vmaFlushAllocation(),
  348. vmaInvalidateAllocation().
  349. Regions of memory specified for flush/invalidate must be aligned to
  350. `VkPhysicalDeviceLimits::nonCoherentAtomSize`. This is automatically ensured by the library.
  351. In any memory type that is `HOST_VISIBLE` but not `HOST_COHERENT`, all allocations
  352. within blocks are aligned to this value, so their offsets are always multiply of
  353. `nonCoherentAtomSize` and two different allocations never share same "line" of this size.
  354. Please note that memory allocated with #VMA_MEMORY_USAGE_CPU_ONLY is guaranteed to be `HOST_COHERENT`.
  355. Also, Windows drivers from all 3 **PC** GPU vendors (AMD, Intel, NVIDIA)
  356. currently provide `HOST_COHERENT` flag on all memory types that are
  357. `HOST_VISIBLE`, so on this platform you may not need to bother.
  358. \section memory_mapping_finding_if_memory_mappable Finding out if memory is mappable
  359. It may happen that your allocation ends up in memory that is `HOST_VISIBLE` (available for mapping)
  360. despite it wasn't explicitly requested.
  361. For example, application may work on integrated graphics with unified memory (like Intel) or
  362. allocation from video memory might have failed, so the library chose system memory as fallback.
  363. You can detect this case and map such allocation to access its memory on CPU directly,
  364. instead of launching a transfer operation.
  365. In order to do that: inspect `allocInfo.memoryType`, call vmaGetMemoryTypeProperties(),
  366. and look for `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag in properties of that memory type.
  367. \code
  368. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  369. bufCreateInfo.size = sizeof(ConstantBuffer);
  370. bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  371. VmaAllocationCreateInfo allocCreateInfo = {};
  372. allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  373. allocCreateInfo.preferredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  374. VkBuffer buf;
  375. VmaAllocation alloc;
  376. VmaAllocationInfo allocInfo;
  377. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  378. VkMemoryPropertyFlags memFlags;
  379. vmaGetMemoryTypeProperties(allocator, allocInfo.memoryType, &memFlags);
  380. if((memFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  381. {
  382. // Allocation ended up in mappable memory. You can map it and access it directly.
  383. void* mappedData;
  384. vmaMapMemory(allocator, alloc, &mappedData);
  385. memcpy(mappedData, &constantBufferData, sizeof(constantBufferData));
  386. vmaUnmapMemory(allocator, alloc);
  387. }
  388. else
  389. {
  390. // Allocation ended up in non-mappable memory.
  391. // You need to create CPU-side buffer in VMA_MEMORY_USAGE_CPU_ONLY and make a transfer.
  392. }
  393. \endcode
  394. You can even use #VMA_ALLOCATION_CREATE_MAPPED_BIT flag while creating allocations
  395. that are not necessarily `HOST_VISIBLE` (e.g. using #VMA_MEMORY_USAGE_GPU_ONLY).
  396. If the allocation ends up in memory type that is `HOST_VISIBLE`, it will be persistently mapped and you can use it directly.
  397. If not, the flag is just ignored.
  398. Example:
  399. \code
  400. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  401. bufCreateInfo.size = sizeof(ConstantBuffer);
  402. bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  403. VmaAllocationCreateInfo allocCreateInfo = {};
  404. allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  405. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
  406. VkBuffer buf;
  407. VmaAllocation alloc;
  408. VmaAllocationInfo allocInfo;
  409. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  410. if(allocInfo.pUserData != nullptr)
  411. {
  412. // Allocation ended up in mappable memory.
  413. // It's persistently mapped. You can access it directly.
  414. memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData));
  415. }
  416. else
  417. {
  418. // Allocation ended up in non-mappable memory.
  419. // You need to create CPU-side buffer in VMA_MEMORY_USAGE_CPU_ONLY and make a transfer.
  420. }
  421. \endcode
  422. \page staying_within_budget Staying within budget
  423. When developing a graphics-intensive game or program, it is important to avoid allocating
  424. more GPU memory than it's physically available. When the memory is over-committed,
  425. various bad things can happen, depending on the specific GPU, graphics driver, and
  426. operating system:
  427. - It may just work without any problems.
  428. - The application may slow down because some memory blocks are moved to system RAM
  429. and the GPU has to access them through PCI Express bus.
  430. - A new allocation may take very long time to complete, even few seconds, and possibly
  431. freeze entire system.
  432. - The new allocation may fail with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  433. - It may even result in GPU crash (TDR), observed as `VK_ERROR_DEVICE_LOST`
  434. returned somewhere later.
  435. \section staying_within_budget_querying_for_budget Querying for budget
  436. To query for current memory usage and available budget, use function vmaGetBudget().
  437. Returned structure #VmaBudget contains quantities expressed in bytes, per Vulkan memory heap.
  438. Please note that this function returns different information and works faster than
  439. vmaCalculateStats(). vmaGetBudget() can be called every frame or even before every
  440. allocation, while vmaCalculateStats() is intended to be used rarely,
  441. only to obtain statistical information, e.g. for debugging purposes.
  442. It is recommended to use <b>VK_EXT_memory_budget</b> device extension to obtain information
  443. about the budget from Vulkan device. VMA is able to use this extension automatically.
  444. When not enabled, the allocator behaves same way, but then it estimates current usage
  445. and available budget based on its internal information and Vulkan memory heap sizes,
  446. which may be less precise. In order to use this extension:
  447. 1. Make sure extensions VK_EXT_memory_budget and VK_KHR_get_physical_device_properties2
  448. required by it are available and enable them. Please note that the first is a device
  449. extension and the second is instance extension!
  450. 2. Use flag #VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT when creating #VmaAllocator object.
  451. 3. Make sure to call vmaSetCurrentFrameIndex() every frame. Budget is queried from
  452. Vulkan inside of it to avoid overhead of querying it with every allocation.
  453. \section staying_within_budget_controlling_memory_usage Controlling memory usage
  454. There are many ways in which you can try to stay within the budget.
  455. First, when making new allocation requires allocating a new memory block, the library
  456. tries not to exceed the budget automatically. If a block with default recommended size
  457. (e.g. 256 MB) would go over budget, a smaller block is allocated, possibly even
  458. dedicated memory for just this resource.
  459. If the size of the requested resource plus current memory usage is more than the
  460. budget, by default the library still tries to create it, leaving it to the Vulkan
  461. implementation whether the allocation succeeds or fails. You can change this behavior
  462. by using #VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT flag. With it, the allocation is
  463. not made if it would exceed the budget or if the budget is already exceeded.
  464. Some other allocations become lost instead to make room for it, if the mechanism of
  465. [lost allocations](@ref lost_allocations) is used.
  466. If that is not possible, the allocation fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  467. Example usage pattern may be to pass the #VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT flag
  468. when creating resources that are not essential for the application (e.g. the texture
  469. of a specific object) and not to pass it when creating critically important resources
  470. (e.g. render targets).
  471. Finally, you can also use #VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT flag to make sure
  472. a new allocation is created only when it fits inside one of the existing memory blocks.
  473. If it would require to allocate a new block, if fails instead with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  474. This also ensures that the function call is very fast because it never goes to Vulkan
  475. to obtain a new block.
  476. Please note that creating \ref custom_memory_pools with VmaPoolCreateInfo::minBlockCount
  477. set to more than 0 will try to allocate memory blocks without checking whether they
  478. fit within budget.
  479. \page custom_memory_pools Custom memory pools
  480. A memory pool contains a number of `VkDeviceMemory` blocks.
  481. The library automatically creates and manages default pool for each memory type available on the device.
  482. Default memory pool automatically grows in size.
  483. Size of allocated blocks is also variable and managed automatically.
  484. You can create custom pool and allocate memory out of it.
  485. It can be useful if you want to:
  486. - Keep certain kind of allocations separate from others.
  487. - Enforce particular, fixed size of Vulkan memory blocks.
  488. - Limit maximum amount of Vulkan memory allocated for that pool.
  489. - Reserve minimum or fixed amount of Vulkan memory always preallocated for that pool.
  490. To use custom memory pools:
  491. -# Fill VmaPoolCreateInfo structure.
  492. -# Call vmaCreatePool() to obtain #VmaPool handle.
  493. -# When making an allocation, set VmaAllocationCreateInfo::pool to this handle.
  494. You don't need to specify any other parameters of this structure, like `usage`.
  495. Example:
  496. \code
  497. // Create a pool that can have at most 2 blocks, 128 MiB each.
  498. VmaPoolCreateInfo poolCreateInfo = {};
  499. poolCreateInfo.memoryTypeIndex = ...
  500. poolCreateInfo.blockSize = 128ull * 1024 * 1024;
  501. poolCreateInfo.maxBlockCount = 2;
  502. VmaPool pool;
  503. vmaCreatePool(allocator, &poolCreateInfo, &pool);
  504. // Allocate a buffer out of it.
  505. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  506. bufCreateInfo.size = 1024;
  507. bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  508. VmaAllocationCreateInfo allocCreateInfo = {};
  509. allocCreateInfo.pool = pool;
  510. VkBuffer buf;
  511. VmaAllocation alloc;
  512. VmaAllocationInfo allocInfo;
  513. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  514. \endcode
  515. You have to free all allocations made from this pool before destroying it.
  516. \code
  517. vmaDestroyBuffer(allocator, buf, alloc);
  518. vmaDestroyPool(allocator, pool);
  519. \endcode
  520. \section custom_memory_pools_MemTypeIndex Choosing memory type index
  521. When creating a pool, you must explicitly specify memory type index.
  522. To find the one suitable for your buffers or images, you can use helper functions
  523. vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo().
  524. You need to provide structures with example parameters of buffers or images
  525. that you are going to create in that pool.
  526. \code
  527. VkBufferCreateInfo exampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  528. exampleBufCreateInfo.size = 1024; // Whatever.
  529. exampleBufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; // Change if needed.
  530. VmaAllocationCreateInfo allocCreateInfo = {};
  531. allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; // Change if needed.
  532. uint32_t memTypeIndex;
  533. vmaFindMemoryTypeIndexForBufferInfo(allocator, &exampleBufCreateInfo, &allocCreateInfo, &memTypeIndex);
  534. VmaPoolCreateInfo poolCreateInfo = {};
  535. poolCreateInfo.memoryTypeIndex = memTypeIndex;
  536. // ...
  537. \endcode
  538. When creating buffers/images allocated in that pool, provide following parameters:
  539. - `VkBufferCreateInfo`: Prefer to pass same parameters as above.
  540. Otherwise you risk creating resources in a memory type that is not suitable for them, which may result in undefined behavior.
  541. Using different `VK_BUFFER_USAGE_` flags may work, but you shouldn't create images in a pool intended for buffers
  542. or the other way around.
  543. - VmaAllocationCreateInfo: You don't need to pass same parameters. Fill only `pool` member.
  544. Other members are ignored anyway.
  545. \section linear_algorithm Linear allocation algorithm
  546. Each Vulkan memory block managed by this library has accompanying metadata that
  547. keeps track of used and unused regions. By default, the metadata structure and
  548. algorithm tries to find best place for new allocations among free regions to
  549. optimize memory usage. This way you can allocate and free objects in any order.
  550. ![Default allocation algorithm](../gfx/Linear_allocator_1_algo_default.png)
  551. Sometimes there is a need to use simpler, linear allocation algorithm. You can
  552. create custom pool that uses such algorithm by adding flag
  553. #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT to VmaPoolCreateInfo::flags while creating
  554. #VmaPool object. Then an alternative metadata management is used. It always
  555. creates new allocations after last one and doesn't reuse free regions after
  556. allocations freed in the middle. It results in better allocation performance and
  557. less memory consumed by metadata.
  558. ![Linear allocation algorithm](../gfx/Linear_allocator_2_algo_linear.png)
  559. With this one flag, you can create a custom pool that can be used in many ways:
  560. free-at-once, stack, double stack, and ring buffer. See below for details.
  561. \subsection linear_algorithm_free_at_once Free-at-once
  562. In a pool that uses linear algorithm, you still need to free all the allocations
  563. individually, e.g. by using vmaFreeMemory() or vmaDestroyBuffer(). You can free
  564. them in any order. New allocations are always made after last one - free space
  565. in the middle is not reused. However, when you release all the allocation and
  566. the pool becomes empty, allocation starts from the beginning again. This way you
  567. can use linear algorithm to speed up creation of allocations that you are going
  568. to release all at once.
  569. ![Free-at-once](../gfx/Linear_allocator_3_free_at_once.png)
  570. This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount
  571. value that allows multiple memory blocks.
  572. \subsection linear_algorithm_stack Stack
  573. When you free an allocation that was created last, its space can be reused.
  574. Thanks to this, if you always release allocations in the order opposite to their
  575. creation (LIFO - Last In First Out), you can achieve behavior of a stack.
  576. ![Stack](../gfx/Linear_allocator_4_stack.png)
  577. This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount
  578. value that allows multiple memory blocks.
  579. \subsection linear_algorithm_double_stack Double stack
  580. The space reserved by a custom pool with linear algorithm may be used by two
  581. stacks:
  582. - First, default one, growing up from offset 0.
  583. - Second, "upper" one, growing down from the end towards lower offsets.
  584. To make allocation from upper stack, add flag #VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT
  585. to VmaAllocationCreateInfo::flags.
  586. ![Double stack](../gfx/Linear_allocator_7_double_stack.png)
  587. Double stack is available only in pools with one memory block -
  588. VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined.
  589. When the two stacks' ends meet so there is not enough space between them for a
  590. new allocation, such allocation fails with usual
  591. `VK_ERROR_OUT_OF_DEVICE_MEMORY` error.
  592. \subsection linear_algorithm_ring_buffer Ring buffer
  593. When you free some allocations from the beginning and there is not enough free space
  594. for a new one at the end of a pool, allocator's "cursor" wraps around to the
  595. beginning and starts allocation there. Thanks to this, if you always release
  596. allocations in the same order as you created them (FIFO - First In First Out),
  597. you can achieve behavior of a ring buffer / queue.
  598. ![Ring buffer](../gfx/Linear_allocator_5_ring_buffer.png)
  599. Pools with linear algorithm support [lost allocations](@ref lost_allocations) when used as ring buffer.
  600. If there is not enough free space for a new allocation, but existing allocations
  601. from the front of the queue can become lost, they become lost and the allocation
  602. succeeds.
  603. ![Ring buffer with lost allocations](../gfx/Linear_allocator_6_ring_buffer_lost.png)
  604. Ring buffer is available only in pools with one memory block -
  605. VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined.
  606. \section buddy_algorithm Buddy allocation algorithm
  607. There is another allocation algorithm that can be used with custom pools, called
  608. "buddy". Its internal data structure is based on a tree of blocks, each having
  609. size that is a power of two and a half of its parent's size. When you want to
  610. allocate memory of certain size, a free node in the tree is located. If it's too
  611. large, it is recursively split into two halves (called "buddies"). However, if
  612. requested allocation size is not a power of two, the size of a tree node is
  613. aligned up to the nearest power of two and the remaining space is wasted. When
  614. two buddy nodes become free, they are merged back into one larger node.
  615. ![Buddy allocator](../gfx/Buddy_allocator.png)
  616. The advantage of buddy allocation algorithm over default algorithm is faster
  617. allocation and deallocation, as well as smaller external fragmentation. The
  618. disadvantage is more wasted space (internal fragmentation).
  619. For more information, please read ["Buddy memory allocation" on Wikipedia](https://en.wikipedia.org/wiki/Buddy_memory_allocation)
  620. or other sources that describe this concept in general.
  621. To use buddy allocation algorithm with a custom pool, add flag
  622. #VMA_POOL_CREATE_BUDDY_ALGORITHM_BIT to VmaPoolCreateInfo::flags while creating
  623. #VmaPool object.
  624. Several limitations apply to pools that use buddy algorithm:
  625. - It is recommended to use VmaPoolCreateInfo::blockSize that is a power of two.
  626. Otherwise, only largest power of two smaller than the size is used for
  627. allocations. The remaining space always stays unused.
  628. - [Margins](@ref debugging_memory_usage_margins) and
  629. [corruption detection](@ref debugging_memory_usage_corruption_detection)
  630. don't work in such pools.
  631. - [Lost allocations](@ref lost_allocations) don't work in such pools. You can
  632. use them, but they never become lost. Support may be added in the future.
  633. - [Defragmentation](@ref defragmentation) doesn't work with allocations made from
  634. such pool.
  635. \page defragmentation Defragmentation
  636. Interleaved allocations and deallocations of many objects of varying size can
  637. cause fragmentation over time, which can lead to a situation where the library is unable
  638. to find a continuous range of free memory for a new allocation despite there is
  639. enough free space, just scattered across many small free ranges between existing
  640. allocations.
  641. To mitigate this problem, you can use defragmentation feature:
  642. structure #VmaDefragmentationInfo2, function vmaDefragmentationBegin(), vmaDefragmentationEnd().
  643. Given set of allocations,
  644. this function can move them to compact used memory, ensure more continuous free
  645. space and possibly also free some `VkDeviceMemory` blocks.
  646. What the defragmentation does is:
  647. - Updates #VmaAllocation objects to point to new `VkDeviceMemory` and offset.
  648. After allocation has been moved, its VmaAllocationInfo::deviceMemory and/or
  649. VmaAllocationInfo::offset changes. You must query them again using
  650. vmaGetAllocationInfo() if you need them.
  651. - Moves actual data in memory.
  652. What it doesn't do, so you need to do it yourself:
  653. - Recreate buffers and images that were bound to allocations that were defragmented and
  654. bind them with their new places in memory.
  655. You must use `vkDestroyBuffer()`, `vkDestroyImage()`,
  656. `vkCreateBuffer()`, `vkCreateImage()`, vmaBindBufferMemory(), vmaBindImageMemory()
  657. for that purpose and NOT vmaDestroyBuffer(),
  658. vmaDestroyImage(), vmaCreateBuffer(), vmaCreateImage(), because you don't need to
  659. destroy or create allocation objects!
  660. - Recreate views and update descriptors that point to these buffers and images.
  661. \section defragmentation_cpu Defragmenting CPU memory
  662. Following example demonstrates how you can run defragmentation on CPU.
  663. Only allocations created in memory types that are `HOST_VISIBLE` can be defragmented.
  664. Others are ignored.
  665. The way it works is:
  666. - It temporarily maps entire memory blocks when necessary.
  667. - It moves data using `memmove()` function.
  668. \code
  669. // Given following variables already initialized:
  670. VkDevice device;
  671. VmaAllocator allocator;
  672. std::vector<VkBuffer> buffers;
  673. std::vector<VmaAllocation> allocations;
  674. const uint32_t allocCount = (uint32_t)allocations.size();
  675. std::vector<VkBool32> allocationsChanged(allocCount);
  676. VmaDefragmentationInfo2 defragInfo = {};
  677. defragInfo.allocationCount = allocCount;
  678. defragInfo.pAllocations = allocations.data();
  679. defragInfo.pAllocationsChanged = allocationsChanged.data();
  680. defragInfo.maxCpuBytesToMove = VK_WHOLE_SIZE; // No limit.
  681. defragInfo.maxCpuAllocationsToMove = UINT32_MAX; // No limit.
  682. VmaDefragmentationContext defragCtx;
  683. vmaDefragmentationBegin(allocator, &defragInfo, nullptr, &defragCtx);
  684. vmaDefragmentationEnd(allocator, defragCtx);
  685. for(uint32_t i = 0; i < allocCount; ++i)
  686. {
  687. if(allocationsChanged[i])
  688. {
  689. // Destroy buffer that is immutably bound to memory region which is no longer valid.
  690. vkDestroyBuffer(device, buffers[i], nullptr);
  691. // Create new buffer with same parameters.
  692. VkBufferCreateInfo bufferInfo = ...;
  693. vkCreateBuffer(device, &bufferInfo, nullptr, &buffers[i]);
  694. // You can make dummy call to vkGetBufferMemoryRequirements here to silence validation layer warning.
  695. // Bind new buffer to new memory region. Data contained in it is already moved.
  696. VmaAllocationInfo allocInfo;
  697. vmaGetAllocationInfo(allocator, allocations[i], &allocInfo);
  698. vmaBindBufferMemory(allocator, allocations[i], buffers[i]);
  699. }
  700. }
  701. \endcode
  702. Setting VmaDefragmentationInfo2::pAllocationsChanged is optional.
  703. This output array tells whether particular allocation in VmaDefragmentationInfo2::pAllocations at the same index
  704. has been modified during defragmentation.
  705. You can pass null, but you then need to query every allocation passed to defragmentation
  706. for new parameters using vmaGetAllocationInfo() if you might need to recreate and rebind a buffer or image associated with it.
  707. If you use [Custom memory pools](@ref choosing_memory_type_custom_memory_pools),
  708. you can fill VmaDefragmentationInfo2::poolCount and VmaDefragmentationInfo2::pPools
  709. instead of VmaDefragmentationInfo2::allocationCount and VmaDefragmentationInfo2::pAllocations
  710. to defragment all allocations in given pools.
  711. You cannot use VmaDefragmentationInfo2::pAllocationsChanged in that case.
  712. You can also combine both methods.
  713. \section defragmentation_gpu Defragmenting GPU memory
  714. It is also possible to defragment allocations created in memory types that are not `HOST_VISIBLE`.
  715. To do that, you need to pass a command buffer that meets requirements as described in
  716. VmaDefragmentationInfo2::commandBuffer. The way it works is:
  717. - It creates temporary buffers and binds them to entire memory blocks when necessary.
  718. - It issues `vkCmdCopyBuffer()` to passed command buffer.
  719. Example:
  720. \code
  721. // Given following variables already initialized:
  722. VkDevice device;
  723. VmaAllocator allocator;
  724. VkCommandBuffer commandBuffer;
  725. std::vector<VkBuffer> buffers;
  726. std::vector<VmaAllocation> allocations;
  727. const uint32_t allocCount = (uint32_t)allocations.size();
  728. std::vector<VkBool32> allocationsChanged(allocCount);
  729. VkCommandBufferBeginInfo cmdBufBeginInfo = ...;
  730. vkBeginCommandBuffer(commandBuffer, &cmdBufBeginInfo);
  731. VmaDefragmentationInfo2 defragInfo = {};
  732. defragInfo.allocationCount = allocCount;
  733. defragInfo.pAllocations = allocations.data();
  734. defragInfo.pAllocationsChanged = allocationsChanged.data();
  735. defragInfo.maxGpuBytesToMove = VK_WHOLE_SIZE; // Notice it's "GPU" this time.
  736. defragInfo.maxGpuAllocationsToMove = UINT32_MAX; // Notice it's "GPU" this time.
  737. defragInfo.commandBuffer = commandBuffer;
  738. VmaDefragmentationContext defragCtx;
  739. vmaDefragmentationBegin(allocator, &defragInfo, nullptr, &defragCtx);
  740. vkEndCommandBuffer(commandBuffer);
  741. // Submit commandBuffer.
  742. // Wait for a fence that ensures commandBuffer execution finished.
  743. vmaDefragmentationEnd(allocator, defragCtx);
  744. for(uint32_t i = 0; i < allocCount; ++i)
  745. {
  746. if(allocationsChanged[i])
  747. {
  748. // Destroy buffer that is immutably bound to memory region which is no longer valid.
  749. vkDestroyBuffer(device, buffers[i], nullptr);
  750. // Create new buffer with same parameters.
  751. VkBufferCreateInfo bufferInfo = ...;
  752. vkCreateBuffer(device, &bufferInfo, nullptr, &buffers[i]);
  753. // You can make dummy call to vkGetBufferMemoryRequirements here to silence validation layer warning.
  754. // Bind new buffer to new memory region. Data contained in it is already moved.
  755. VmaAllocationInfo allocInfo;
  756. vmaGetAllocationInfo(allocator, allocations[i], &allocInfo);
  757. vmaBindBufferMemory(allocator, allocations[i], buffers[i]);
  758. }
  759. }
  760. \endcode
  761. You can combine these two methods by specifying non-zero `maxGpu*` as well as `maxCpu*` parameters.
  762. The library automatically chooses best method to defragment each memory pool.
  763. You may try not to block your entire program to wait until defragmentation finishes,
  764. but do it in the background, as long as you carefully fullfill requirements described
  765. in function vmaDefragmentationBegin().
  766. \section defragmentation_additional_notes Additional notes
  767. It is only legal to defragment allocations bound to:
  768. - buffers
  769. - images created with `VK_IMAGE_CREATE_ALIAS_BIT`, `VK_IMAGE_TILING_LINEAR`, and
  770. being currently in `VK_IMAGE_LAYOUT_GENERAL` or `VK_IMAGE_LAYOUT_PREINITIALIZED`.
  771. Defragmentation of images created with `VK_IMAGE_TILING_OPTIMAL` or in any other
  772. layout may give undefined results.
  773. If you defragment allocations bound to images, new images to be bound to new
  774. memory region after defragmentation should be created with `VK_IMAGE_LAYOUT_PREINITIALIZED`
  775. and then transitioned to their original layout from before defragmentation if
  776. needed using an image memory barrier.
  777. While using defragmentation, you may experience validation layer warnings, which you just need to ignore.
  778. See [Validation layer warnings](@ref general_considerations_validation_layer_warnings).
  779. Please don't expect memory to be fully compacted after defragmentation.
  780. Algorithms inside are based on some heuristics that try to maximize number of Vulkan
  781. memory blocks to make totally empty to release them, as well as to maximimze continuous
  782. empty space inside remaining blocks, while minimizing the number and size of allocations that
  783. need to be moved. Some fragmentation may still remain - this is normal.
  784. \section defragmentation_custom_algorithm Writing custom defragmentation algorithm
  785. If you want to implement your own, custom defragmentation algorithm,
  786. there is infrastructure prepared for that,
  787. but it is not exposed through the library API - you need to hack its source code.
  788. Here are steps needed to do this:
  789. -# Main thing you need to do is to define your own class derived from base abstract
  790. class `VmaDefragmentationAlgorithm` and implement your version of its pure virtual methods.
  791. See definition and comments of this class for details.
  792. -# Your code needs to interact with device memory block metadata.
  793. If you need more access to its data than it's provided by its public interface,
  794. declare your new class as a friend class e.g. in class `VmaBlockMetadata_Generic`.
  795. -# If you want to create a flag that would enable your algorithm or pass some additional
  796. flags to configure it, add them to `VmaDefragmentationFlagBits` and use them in
  797. VmaDefragmentationInfo2::flags.
  798. -# Modify function `VmaBlockVectorDefragmentationContext::Begin` to create object
  799. of your new class whenever needed.
  800. \page lost_allocations Lost allocations
  801. If your game oversubscribes video memory, if may work OK in previous-generation
  802. graphics APIs (DirectX 9, 10, 11, OpenGL) because resources are automatically
  803. paged to system RAM. In Vulkan you can't do it because when you run out of
  804. memory, an allocation just fails. If you have more data (e.g. textures) that can
  805. fit into VRAM and you don't need it all at once, you may want to upload them to
  806. GPU on demand and "push out" ones that are not used for a long time to make room
  807. for the new ones, effectively using VRAM (or a cartain memory pool) as a form of
  808. cache. Vulkan Memory Allocator can help you with that by supporting a concept of
  809. "lost allocations".
  810. To create an allocation that can become lost, include #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT
  811. flag in VmaAllocationCreateInfo::flags. Before using a buffer or image bound to
  812. such allocation in every new frame, you need to query it if it's not lost.
  813. To check it, call vmaTouchAllocation().
  814. If the allocation is lost, you should not use it or buffer/image bound to it.
  815. You mustn't forget to destroy this allocation and this buffer/image.
  816. vmaGetAllocationInfo() can also be used for checking status of the allocation.
  817. Allocation is lost when returned VmaAllocationInfo::deviceMemory == `VK_NULL_HANDLE`.
  818. To create an allocation that can make some other allocations lost to make room
  819. for it, use #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flag. You will
  820. usually use both flags #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT and
  821. #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT at the same time.
  822. Warning! Current implementation uses quite naive, brute force algorithm,
  823. which can make allocation calls that use #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT
  824. flag quite slow. A new, more optimal algorithm and data structure to speed this
  825. up is planned for the future.
  826. <b>Q: When interleaving creation of new allocations with usage of existing ones,
  827. how do you make sure that an allocation won't become lost while it's used in the
  828. current frame?</b>
  829. It is ensured because vmaTouchAllocation() / vmaGetAllocationInfo() not only returns allocation
  830. status/parameters and checks whether it's not lost, but when it's not, it also
  831. atomically marks it as used in the current frame, which makes it impossible to
  832. become lost in that frame. It uses lockless algorithm, so it works fast and
  833. doesn't involve locking any internal mutex.
  834. <b>Q: What if my allocation may still be in use by the GPU when it's rendering a
  835. previous frame while I already submit new frame on the CPU?</b>
  836. You can make sure that allocations "touched" by vmaTouchAllocation() / vmaGetAllocationInfo() will not
  837. become lost for a number of additional frames back from the current one by
  838. specifying this number as VmaAllocatorCreateInfo::frameInUseCount (for default
  839. memory pool) and VmaPoolCreateInfo::frameInUseCount (for custom pool).
  840. <b>Q: How do you inform the library when new frame starts?</b>
  841. You need to call function vmaSetCurrentFrameIndex().
  842. Example code:
  843. \code
  844. struct MyBuffer
  845. {
  846. VkBuffer m_Buf = nullptr;
  847. VmaAllocation m_Alloc = nullptr;
  848. // Called when the buffer is really needed in the current frame.
  849. void EnsureBuffer();
  850. };
  851. void MyBuffer::EnsureBuffer()
  852. {
  853. // Buffer has been created.
  854. if(m_Buf != VK_NULL_HANDLE)
  855. {
  856. // Check if its allocation is not lost + mark it as used in current frame.
  857. if(vmaTouchAllocation(allocator, m_Alloc))
  858. {
  859. // It's all OK - safe to use m_Buf.
  860. return;
  861. }
  862. }
  863. // Buffer not yet exists or lost - destroy and recreate it.
  864. vmaDestroyBuffer(allocator, m_Buf, m_Alloc);
  865. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  866. bufCreateInfo.size = 1024;
  867. bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  868. VmaAllocationCreateInfo allocCreateInfo = {};
  869. allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  870. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT |
  871. VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT;
  872. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &m_Buf, &m_Alloc, nullptr);
  873. }
  874. \endcode
  875. When using lost allocations, you may see some Vulkan validation layer warnings
  876. about overlapping regions of memory bound to different kinds of buffers and
  877. images. This is still valid as long as you implement proper handling of lost
  878. allocations (like in the example above) and don't use them.
  879. You can create an allocation that is already in lost state from the beginning using function
  880. vmaCreateLostAllocation(). It may be useful if you need a "dummy" allocation that is not null.
  881. You can call function vmaMakePoolAllocationsLost() to set all eligible allocations
  882. in a specified custom pool to lost state.
  883. Allocations that have been "touched" in current frame or VmaPoolCreateInfo::frameInUseCount frames back
  884. cannot become lost.
  885. <b>Q: Can I touch allocation that cannot become lost?</b>
  886. Yes, although it has no visible effect.
  887. Calls to vmaGetAllocationInfo() and vmaTouchAllocation() update last use frame index
  888. also for allocations that cannot become lost, but the only way to observe it is to dump
  889. internal allocator state using vmaBuildStatsString().
  890. You can use this feature for debugging purposes to explicitly mark allocations that you use
  891. in current frame and then analyze JSON dump to see for how long each allocation stays unused.
  892. \page statistics Statistics
  893. This library contains functions that return information about its internal state,
  894. especially the amount of memory allocated from Vulkan.
  895. Please keep in mind that these functions need to traverse all internal data structures
  896. to gather these information, so they may be quite time-consuming.
  897. Don't call them too often.
  898. \section statistics_numeric_statistics Numeric statistics
  899. You can query for overall statistics of the allocator using function vmaCalculateStats().
  900. Information are returned using structure #VmaStats.
  901. It contains #VmaStatInfo - number of allocated blocks, number of allocations
  902. (occupied ranges in these blocks), number of unused (free) ranges in these blocks,
  903. number of bytes used and unused (but still allocated from Vulkan) and other information.
  904. They are summed across memory heaps, memory types and total for whole allocator.
  905. You can query for statistics of a custom pool using function vmaGetPoolStats().
  906. Information are returned using structure #VmaPoolStats.
  907. You can query for information about specific allocation using function vmaGetAllocationInfo().
  908. It fill structure #VmaAllocationInfo.
  909. \section statistics_json_dump JSON dump
  910. You can dump internal state of the allocator to a string in JSON format using function vmaBuildStatsString().
  911. The result is guaranteed to be correct JSON.
  912. It uses ANSI encoding.
  913. Any strings provided by user (see [Allocation names](@ref allocation_names))
  914. are copied as-is and properly escaped for JSON, so if they use UTF-8, ISO-8859-2 or any other encoding,
  915. this JSON string can be treated as using this encoding.
  916. It must be freed using function vmaFreeStatsString().
  917. The format of this JSON string is not part of official documentation of the library,
  918. but it will not change in backward-incompatible way without increasing library major version number
  919. and appropriate mention in changelog.
  920. The JSON string contains all the data that can be obtained using vmaCalculateStats().
  921. It can also contain detailed map of allocated memory blocks and their regions -
  922. free and occupied by allocations.
  923. This allows e.g. to visualize the memory or assess fragmentation.
  924. \page allocation_annotation Allocation names and user data
  925. \section allocation_user_data Allocation user data
  926. You can annotate allocations with your own information, e.g. for debugging purposes.
  927. To do that, fill VmaAllocationCreateInfo::pUserData field when creating
  928. an allocation. It's an opaque `void*` pointer. You can use it e.g. as a pointer,
  929. some handle, index, key, ordinal number or any other value that would associate
  930. the allocation with your custom metadata.
  931. \code
  932. VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  933. // Fill bufferInfo...
  934. MyBufferMetadata* pMetadata = CreateBufferMetadata();
  935. VmaAllocationCreateInfo allocCreateInfo = {};
  936. allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  937. allocCreateInfo.pUserData = pMetadata;
  938. VkBuffer buffer;
  939. VmaAllocation allocation;
  940. vmaCreateBuffer(allocator, &bufferInfo, &allocCreateInfo, &buffer, &allocation, nullptr);
  941. \endcode
  942. The pointer may be later retrieved as VmaAllocationInfo::pUserData:
  943. \code
  944. VmaAllocationInfo allocInfo;
  945. vmaGetAllocationInfo(allocator, allocation, &allocInfo);
  946. MyBufferMetadata* pMetadata = (MyBufferMetadata*)allocInfo.pUserData;
  947. \endcode
  948. It can also be changed using function vmaSetAllocationUserData().
  949. Values of (non-zero) allocations' `pUserData` are printed in JSON report created by
  950. vmaBuildStatsString(), in hexadecimal form.
  951. \section allocation_names Allocation names
  952. There is alternative mode available where `pUserData` pointer is used to point to
  953. a null-terminated string, giving a name to the allocation. To use this mode,
  954. set #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT flag in VmaAllocationCreateInfo::flags.
  955. Then `pUserData` passed as VmaAllocationCreateInfo::pUserData or argument to
  956. vmaSetAllocationUserData() must be either null or pointer to a null-terminated string.
  957. The library creates internal copy of the string, so the pointer you pass doesn't need
  958. to be valid for whole lifetime of the allocation. You can free it after the call.
  959. \code
  960. VkImageCreateInfo imageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
  961. // Fill imageInfo...
  962. std::string imageName = "Texture: ";
  963. imageName += fileName;
  964. VmaAllocationCreateInfo allocCreateInfo = {};
  965. allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
  966. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT;
  967. allocCreateInfo.pUserData = imageName.c_str();
  968. VkImage image;
  969. VmaAllocation allocation;
  970. vmaCreateImage(allocator, &imageInfo, &allocCreateInfo, &image, &allocation, nullptr);
  971. \endcode
  972. The value of `pUserData` pointer of the allocation will be different than the one
  973. you passed when setting allocation's name - pointing to a buffer managed
  974. internally that holds copy of the string.
  975. \code
  976. VmaAllocationInfo allocInfo;
  977. vmaGetAllocationInfo(allocator, allocation, &allocInfo);
  978. const char* imageName = (const char*)allocInfo.pUserData;
  979. printf("Image name: %s\n", imageName);
  980. \endcode
  981. That string is also printed in JSON report created by vmaBuildStatsString().
  982. \page debugging_memory_usage Debugging incorrect memory usage
  983. If you suspect a bug with memory usage, like usage of uninitialized memory or
  984. memory being overwritten out of bounds of an allocation,
  985. you can use debug features of this library to verify this.
  986. \section debugging_memory_usage_initialization Memory initialization
  987. If you experience a bug with incorrect and nondeterministic data in your program and you suspect uninitialized memory to be used,
  988. you can enable automatic memory initialization to verify this.
  989. To do it, define macro `VMA_DEBUG_INITIALIZE_ALLOCATIONS` to 1.
  990. \code
  991. #define VMA_DEBUG_INITIALIZE_ALLOCATIONS 1
  992. #include "vk_mem_alloc.h"
  993. \endcode
  994. It makes memory of all new allocations initialized to bit pattern `0xDCDCDCDC`.
  995. Before an allocation is destroyed, its memory is filled with bit pattern `0xEFEFEFEF`.
  996. Memory is automatically mapped and unmapped if necessary.
  997. If you find these values while debugging your program, good chances are that you incorrectly
  998. read Vulkan memory that is allocated but not initialized, or already freed, respectively.
  999. Memory initialization works only with memory types that are `HOST_VISIBLE`.
  1000. It works also with dedicated allocations.
  1001. It doesn't work with allocations created with #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag,
  1002. as they cannot be mapped.
  1003. \section debugging_memory_usage_margins Margins
  1004. By default, allocations are laid out in memory blocks next to each other if possible
  1005. (considering required alignment, `bufferImageGranularity`, and `nonCoherentAtomSize`).
  1006. ![Allocations without margin](../gfx/Margins_1.png)
  1007. Define macro `VMA_DEBUG_MARGIN` to some non-zero value (e.g. 16) to enforce specified
  1008. number of bytes as a margin before and after every allocation.
  1009. \code
  1010. #define VMA_DEBUG_MARGIN 16
  1011. #include "vk_mem_alloc.h"
  1012. \endcode
  1013. ![Allocations with margin](../gfx/Margins_2.png)
  1014. If your bug goes away after enabling margins, it means it may be caused by memory
  1015. being overwritten outside of allocation boundaries. It is not 100% certain though.
  1016. Change in application behavior may also be caused by different order and distribution
  1017. of allocations across memory blocks after margins are applied.
  1018. The margin is applied also before first and after last allocation in a block.
  1019. It may occur only once between two adjacent allocations.
  1020. Margins work with all types of memory.
  1021. Margin is applied only to allocations made out of memory blocks and not to dedicated
  1022. allocations, which have their own memory block of specific size.
  1023. It is thus not applied to allocations made using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT flag
  1024. or those automatically decided to put into dedicated allocations, e.g. due to its
  1025. large size or recommended by VK_KHR_dedicated_allocation extension.
  1026. Margins are also not active in custom pools created with #VMA_POOL_CREATE_BUDDY_ALGORITHM_BIT flag.
  1027. Margins appear in [JSON dump](@ref statistics_json_dump) as part of free space.
  1028. Note that enabling margins increases memory usage and fragmentation.
  1029. \section debugging_memory_usage_corruption_detection Corruption detection
  1030. You can additionally define macro `VMA_DEBUG_DETECT_CORRUPTION` to 1 to enable validation
  1031. of contents of the margins.
  1032. \code
  1033. #define VMA_DEBUG_MARGIN 16
  1034. #define VMA_DEBUG_DETECT_CORRUPTION 1
  1035. #include "vk_mem_alloc.h"
  1036. \endcode
  1037. When this feature is enabled, number of bytes specified as `VMA_DEBUG_MARGIN`
  1038. (it must be multiply of 4) before and after every allocation is filled with a magic number.
  1039. This idea is also know as "canary".
  1040. Memory is automatically mapped and unmapped if necessary.
  1041. This number is validated automatically when the allocation is destroyed.
  1042. If it's not equal to the expected value, `VMA_ASSERT()` is executed.
  1043. It clearly means that either CPU or GPU overwritten the memory outside of boundaries of the allocation,
  1044. which indicates a serious bug.
  1045. You can also explicitly request checking margins of all allocations in all memory blocks
  1046. that belong to specified memory types by using function vmaCheckCorruption(),
  1047. or in memory blocks that belong to specified custom pool, by using function
  1048. vmaCheckPoolCorruption().
  1049. Margin validation (corruption detection) works only for memory types that are
  1050. `HOST_VISIBLE` and `HOST_COHERENT`.
  1051. \page record_and_replay Record and replay
  1052. \section record_and_replay_introduction Introduction
  1053. While using the library, sequence of calls to its functions together with their
  1054. parameters can be recorded to a file and later replayed using standalone player
  1055. application. It can be useful to:
  1056. - Test correctness - check if same sequence of calls will not cause crash or
  1057. failures on a target platform.
  1058. - Gather statistics - see number of allocations, peak memory usage, number of
  1059. calls etc.
  1060. - Benchmark performance - see how much time it takes to replay the whole
  1061. sequence.
  1062. \section record_and_replay_usage Usage
  1063. Recording functionality is disabled by default.
  1064. To enable it, define following macro before every include of this library:
  1065. \code
  1066. #define VMA_RECORDING_ENABLED 1
  1067. \endcode
  1068. <b>To record sequence of calls to a file:</b> Fill in
  1069. VmaAllocatorCreateInfo::pRecordSettings member while creating #VmaAllocator
  1070. object. File is opened and written during whole lifetime of the allocator.
  1071. <b>To replay file:</b> Use VmaReplay - standalone command-line program.
  1072. Precompiled binary can be found in "bin" directory.
  1073. Its source can be found in "src/VmaReplay" directory.
  1074. Its project is generated by Premake.
  1075. Command line syntax is printed when the program is launched without parameters.
  1076. Basic usage:
  1077. VmaReplay.exe MyRecording.csv
  1078. <b>Documentation of file format</b> can be found in file: "docs/Recording file format.md".
  1079. It's a human-readable, text file in CSV format (Comma Separated Values).
  1080. \section record_and_replay_additional_considerations Additional considerations
  1081. - Replaying file that was recorded on a different GPU (with different parameters
  1082. like `bufferImageGranularity`, `nonCoherentAtomSize`, and especially different
  1083. set of memory heaps and types) may give different performance and memory usage
  1084. results, as well as issue some warnings and errors.
  1085. - Current implementation of recording in VMA, as well as VmaReplay application, is
  1086. coded and tested only on Windows. Inclusion of recording code is driven by
  1087. `VMA_RECORDING_ENABLED` macro. Support for other platforms should be easy to
  1088. add. Contributions are welcomed.
  1089. \page usage_patterns Recommended usage patterns
  1090. See also slides from talk:
  1091. [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)
  1092. \section usage_patterns_common_mistakes Common mistakes
  1093. <b>Use of CPU_TO_GPU instead of CPU_ONLY memory</b>
  1094. #VMA_MEMORY_USAGE_CPU_TO_GPU is recommended only for resources that will be
  1095. mapped and written by the CPU, as well as read directly by the GPU - like some
  1096. buffers or textures updated every frame (dynamic). If you create a staging copy
  1097. of a resource to be written by CPU and then used as a source of transfer to
  1098. another resource placed in the GPU memory, that staging resource should be
  1099. created with #VMA_MEMORY_USAGE_CPU_ONLY. Please read the descriptions of these
  1100. enums carefully for details.
  1101. <b>Unnecessary use of custom pools</b>
  1102. \ref custom_memory_pools may be useful for special purposes - when you want to
  1103. keep certain type of resources separate e.g. to reserve minimum amount of memory
  1104. for them, limit maximum amount of memory they can occupy, or make some of them
  1105. push out the other through the mechanism of \ref lost_allocations. For most
  1106. resources this is not needed and so it is not recommended to create #VmaPool
  1107. objects and allocations out of them. Allocating from the default pool is sufficient.
  1108. \section usage_patterns_simple Simple patterns
  1109. \subsection usage_patterns_simple_render_targets Render targets
  1110. <b>When:</b>
  1111. Any resources that you frequently write and read on GPU,
  1112. e.g. images used as color attachments (aka "render targets"), depth-stencil attachments,
  1113. images/buffers used as storage image/buffer (aka "Unordered Access View (UAV)").
  1114. <b>What to do:</b>
  1115. Create them in video memory that is fastest to access from GPU using
  1116. #VMA_MEMORY_USAGE_GPU_ONLY.
  1117. Consider using [VK_KHR_dedicated_allocation](@ref vk_khr_dedicated_allocation) extension
  1118. and/or manually creating them as dedicated allocations using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
  1119. especially if they are large or if you plan to destroy and recreate them e.g. when
  1120. display resolution changes.
  1121. Prefer to create such resources first and all other GPU resources (like textures and vertex buffers) later.
  1122. \subsection usage_patterns_simple_immutable_resources Immutable resources
  1123. <b>When:</b>
  1124. Any resources that you fill on CPU only once (aka "immutable") or infrequently
  1125. and then read frequently on GPU,
  1126. e.g. textures, vertex and index buffers, constant buffers that don't change often.
  1127. <b>What to do:</b>
  1128. Create them in video memory that is fastest to access from GPU using
  1129. #VMA_MEMORY_USAGE_GPU_ONLY.
  1130. To initialize content of such resource, create a CPU-side (aka "staging") copy of it
  1131. in system memory - #VMA_MEMORY_USAGE_CPU_ONLY, map it, fill it,
  1132. and submit a transfer from it to the GPU resource.
  1133. You can keep the staging copy if you need it for another upload transfer in the future.
  1134. If you don't, you can destroy it or reuse this buffer for uploading different resource
  1135. after the transfer finishes.
  1136. Prefer to create just buffers in system memory rather than images, even for uploading textures.
  1137. Use `vkCmdCopyBufferToImage()`.
  1138. Dont use images with `VK_IMAGE_TILING_LINEAR`.
  1139. \subsection usage_patterns_dynamic_resources Dynamic resources
  1140. <b>When:</b>
  1141. Any resources that change frequently (aka "dynamic"), e.g. every frame or every draw call,
  1142. written on CPU, read on GPU.
  1143. <b>What to do:</b>
  1144. Create them using #VMA_MEMORY_USAGE_CPU_TO_GPU.
  1145. You can map it and write to it directly on CPU, as well as read from it on GPU.
  1146. This is a more complex situation. Different solutions are possible,
  1147. and the best one depends on specific GPU type, but you can use this simple approach for the start.
  1148. Prefer to write to such resource sequentially (e.g. using `memcpy`).
  1149. Don't perform random access or any reads from it on CPU, as it may be very slow.
  1150. \subsection usage_patterns_readback Readback
  1151. <b>When:</b>
  1152. Resources that contain data written by GPU that you want to read back on CPU,
  1153. e.g. results of some computations.
  1154. <b>What to do:</b>
  1155. Create them using #VMA_MEMORY_USAGE_GPU_TO_CPU.
  1156. You can write to them directly on GPU, as well as map and read them on CPU.
  1157. \section usage_patterns_advanced Advanced patterns
  1158. \subsection usage_patterns_integrated_graphics Detecting integrated graphics
  1159. You can support integrated graphics (like Intel HD Graphics, AMD APU) better
  1160. by detecting it in Vulkan.
  1161. To do it, call `vkGetPhysicalDeviceProperties()`, inspect
  1162. `VkPhysicalDeviceProperties::deviceType` and look for `VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU`.
  1163. When you find it, you can assume that memory is unified and all memory types are comparably fast
  1164. to access from GPU, regardless of `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`.
  1165. You can then sum up sizes of all available memory heaps and treat them as useful for
  1166. your GPU resources, instead of only `DEVICE_LOCAL` ones.
  1167. You can also prefer to create your resources in memory types that are `HOST_VISIBLE` to map them
  1168. directly instead of submitting explicit transfer (see below).
  1169. \subsection usage_patterns_direct_vs_transfer Direct access versus transfer
  1170. For resources that you frequently write on CPU and read on GPU, many solutions are possible:
  1171. -# Create one copy in video memory using #VMA_MEMORY_USAGE_GPU_ONLY,
  1172. second copy in system memory using #VMA_MEMORY_USAGE_CPU_ONLY and submit explicit tranfer each time.
  1173. -# Create just single copy using #VMA_MEMORY_USAGE_CPU_TO_GPU, map it and fill it on CPU,
  1174. read it directly on GPU.
  1175. -# Create just single copy using #VMA_MEMORY_USAGE_CPU_ONLY, map it and fill it on CPU,
  1176. read it directly on GPU.
  1177. Which solution is the most efficient depends on your resource and especially on the GPU.
  1178. It is best to measure it and then make the decision.
  1179. Some general recommendations:
  1180. - On integrated graphics use (2) or (3) to avoid unnecesary time and memory overhead
  1181. related to using a second copy and making transfer.
  1182. - For small resources (e.g. constant buffers) use (2).
  1183. Discrete AMD cards have special 256 MiB pool of video memory that is directly mappable.
  1184. Even if the resource ends up in system memory, its data may be cached on GPU after first
  1185. fetch over PCIe bus.
  1186. - For larger resources (e.g. textures), decide between (1) and (2).
  1187. You may want to differentiate NVIDIA and AMD, e.g. by looking for memory type that is
  1188. both `DEVICE_LOCAL` and `HOST_VISIBLE`. When you find it, use (2), otherwise use (1).
  1189. Similarly, for resources that you frequently write on GPU and read on CPU, multiple
  1190. solutions are possible:
  1191. -# Create one copy in video memory using #VMA_MEMORY_USAGE_GPU_ONLY,
  1192. second copy in system memory using #VMA_MEMORY_USAGE_GPU_TO_CPU and submit explicit tranfer each time.
  1193. -# Create just single copy using #VMA_MEMORY_USAGE_GPU_TO_CPU, write to it directly on GPU,
  1194. map it and read it on CPU.
  1195. You should take some measurements to decide which option is faster in case of your specific
  1196. resource.
  1197. If you don't want to specialize your code for specific types of GPUs, you can still make
  1198. an simple optimization for cases when your resource ends up in mappable memory to use it
  1199. directly in this case instead of creating CPU-side staging copy.
  1200. For details see [Finding out if memory is mappable](@ref memory_mapping_finding_if_memory_mappable).
  1201. \page configuration Configuration
  1202. Please check "CONFIGURATION SECTION" in the code to find macros that you can define
  1203. before each include of this file or change directly in this file to provide
  1204. your own implementation of basic facilities like assert, `min()` and `max()` functions,
  1205. mutex, atomic etc.
  1206. The library uses its own implementation of containers by default, but you can switch to using
  1207. STL containers instead.
  1208. For example, define `VMA_ASSERT(expr)` before including the library to provide
  1209. custom implementation of the assertion, compatible with your project.
  1210. By default it is defined to standard C `assert(expr)` in `_DEBUG` configuration
  1211. and empty otherwise.
  1212. \section config_Vulkan_functions Pointers to Vulkan functions
  1213. The library uses Vulkan functions straight from the `vulkan.h` header by default.
  1214. If you want to provide your own pointers to these functions, e.g. fetched using
  1215. `vkGetInstanceProcAddr()` and `vkGetDeviceProcAddr()`:
  1216. -# Define `VMA_STATIC_VULKAN_FUNCTIONS 0`.
  1217. -# Provide valid pointers through VmaAllocatorCreateInfo::pVulkanFunctions.
  1218. \section custom_memory_allocator Custom host memory allocator
  1219. If you use custom allocator for CPU memory rather than default operator `new`
  1220. and `delete` from C++, you can make this library using your allocator as well
  1221. by filling optional member VmaAllocatorCreateInfo::pAllocationCallbacks. These
  1222. functions will be passed to Vulkan, as well as used by the library itself to
  1223. make any CPU-side allocations.
  1224. \section allocation_callbacks Device memory allocation callbacks
  1225. The library makes calls to `vkAllocateMemory()` and `vkFreeMemory()` internally.
  1226. You can setup callbacks to be informed about these calls, e.g. for the purpose
  1227. of gathering some statistics. To do it, fill optional member
  1228. VmaAllocatorCreateInfo::pDeviceMemoryCallbacks.
  1229. \section heap_memory_limit Device heap memory limit
  1230. When device memory of certain heap runs out of free space, new allocations may
  1231. fail (returning error code) or they may succeed, silently pushing some existing
  1232. memory blocks from GPU VRAM to system RAM (which degrades performance). This
  1233. behavior is implementation-dependant - it depends on GPU vendor and graphics
  1234. driver.
  1235. On AMD cards it can be controlled while creating Vulkan device object by using
  1236. VK_AMD_memory_overallocation_behavior extension, if available.
  1237. Alternatively, if you want to test how your program behaves with limited amount of Vulkan device
  1238. memory available without switching your graphics card to one that really has
  1239. smaller VRAM, you can use a feature of this library intended for this purpose.
  1240. To do it, fill optional member VmaAllocatorCreateInfo::pHeapSizeLimit.
  1241. \page vk_khr_dedicated_allocation VK_KHR_dedicated_allocation
  1242. VK_KHR_dedicated_allocation is a Vulkan extension which can be used to improve
  1243. performance on some GPUs. It augments Vulkan API with possibility to query
  1244. driver whether it prefers particular buffer or image to have its own, dedicated
  1245. allocation (separate `VkDeviceMemory` block) for better efficiency - to be able
  1246. to do some internal optimizations.
  1247. The extension is supported by this library. It will be used automatically when
  1248. enabled. To enable it:
  1249. 1 . When creating Vulkan device, check if following 2 device extensions are
  1250. supported (call `vkEnumerateDeviceExtensionProperties()`).
  1251. If yes, enable them (fill `VkDeviceCreateInfo::ppEnabledExtensionNames`).
  1252. - VK_KHR_get_memory_requirements2
  1253. - VK_KHR_dedicated_allocation
  1254. If you enabled these extensions:
  1255. 2 . Use #VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag when creating
  1256. your #VmaAllocator`to inform the library that you enabled required extensions
  1257. and you want the library to use them.
  1258. \code
  1259. allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT;
  1260. vmaCreateAllocator(&allocatorInfo, &allocator);
  1261. \endcode
  1262. That's all. The extension will be automatically used whenever you create a
  1263. buffer using vmaCreateBuffer() or image using vmaCreateImage().
  1264. When using the extension together with Vulkan Validation Layer, you will receive
  1265. warnings like this:
  1266. vkBindBufferMemory(): Binding memory to buffer 0x33 but vkGetBufferMemoryRequirements() has not been called on that buffer.
  1267. It is OK, you should just ignore it. It happens because you use function
  1268. `vkGetBufferMemoryRequirements2KHR()` instead of standard
  1269. `vkGetBufferMemoryRequirements()`, while the validation layer seems to be
  1270. unaware of it.
  1271. To learn more about this extension, see:
  1272. - [VK_KHR_dedicated_allocation in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.0-extensions/html/vkspec.html#VK_KHR_dedicated_allocation)
  1273. - [VK_KHR_dedicated_allocation unofficial manual](http://asawicki.info/articles/VK_KHR_dedicated_allocation.php5)
  1274. \page general_considerations General considerations
  1275. \section general_considerations_thread_safety Thread safety
  1276. - The library has no global state, so separate #VmaAllocator objects can be used
  1277. independently.
  1278. There should be no need to create multiple such objects though - one per `VkDevice` is enough.
  1279. - By default, all calls to functions that take #VmaAllocator as first parameter
  1280. are safe to call from multiple threads simultaneously because they are
  1281. synchronized internally when needed.
  1282. - When the allocator is created with #VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT
  1283. flag, calls to functions that take such #VmaAllocator object must be
  1284. synchronized externally.
  1285. - Access to a #VmaAllocation object must be externally synchronized. For example,
  1286. you must not call vmaGetAllocationInfo() and vmaMapMemory() from different
  1287. threads at the same time if you pass the same #VmaAllocation object to these
  1288. functions.
  1289. \section general_considerations_validation_layer_warnings Validation layer warnings
  1290. When using this library, you can meet following types of warnings issued by
  1291. Vulkan validation layer. They don't necessarily indicate a bug, so you may need
  1292. to just ignore them.
  1293. - *vkBindBufferMemory(): Binding memory to buffer 0xeb8e4 but vkGetBufferMemoryRequirements() has not been called on that buffer.*
  1294. - It happens when VK_KHR_dedicated_allocation extension is enabled.
  1295. `vkGetBufferMemoryRequirements2KHR` function is used instead, while validation layer seems to be unaware of it.
  1296. - *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.*
  1297. - It happens when you map a buffer or image, because the library maps entire
  1298. `VkDeviceMemory` block, where different types of images and buffers may end
  1299. up together, especially on GPUs with unified memory like Intel.
  1300. - *Non-linear image 0xebc91 is aliased with linear buffer 0xeb8e4 which may indicate a bug.*
  1301. - It happens when you use lost allocations, and a new image or buffer is
  1302. created in place of an existing object that bacame lost.
  1303. - It may happen also when you use [defragmentation](@ref defragmentation).
  1304. \section general_considerations_allocation_algorithm Allocation algorithm
  1305. The library uses following algorithm for allocation, in order:
  1306. -# Try to find free range of memory in existing blocks.
  1307. -# If failed, try to create a new block of `VkDeviceMemory`, with preferred block size.
  1308. -# If failed, try to create such block with size/2, size/4, size/8.
  1309. -# If failed and #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flag was
  1310. specified, try to find space in existing blocks, possilby making some other
  1311. allocations lost.
  1312. -# If failed, try to allocate separate `VkDeviceMemory` for this allocation,
  1313. just like when you use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  1314. -# If failed, choose other memory type that meets the requirements specified in
  1315. VmaAllocationCreateInfo and go to point 1.
  1316. -# If failed, return `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  1317. \section general_considerations_features_not_supported Features not supported
  1318. Features deliberately excluded from the scope of this library:
  1319. - Data transfer. Uploading (straming) and downloading data of buffers and images
  1320. between CPU and GPU memory and related synchronization is responsibility of the user.
  1321. Defining some "texture" object that would automatically stream its data from a
  1322. staging copy in CPU memory to GPU memory would rather be a feature of another,
  1323. higher-level library implemented on top of VMA.
  1324. - Allocations for imported/exported external memory. They tend to require
  1325. explicit memory type index and dedicated allocation anyway, so they don't
  1326. interact with main features of this library. Such special purpose allocations
  1327. should be made manually, using `vkCreateBuffer()` and `vkAllocateMemory()`.
  1328. - Recreation of buffers and images. Although the library has functions for
  1329. buffer and image creation (vmaCreateBuffer(), vmaCreateImage()), you need to
  1330. recreate these objects yourself after defragmentation. That's because the big
  1331. structures `VkBufferCreateInfo`, `VkImageCreateInfo` are not stored in
  1332. #VmaAllocation object.
  1333. - Handling CPU memory allocation failures. When dynamically creating small C++
  1334. objects in CPU memory (not Vulkan memory), allocation failures are not checked
  1335. and handled gracefully, because that would complicate code significantly and
  1336. is usually not needed in desktop PC applications anyway.
  1337. - Code free of any compiler warnings. Maintaining the library to compile and
  1338. work correctly on so many different platforms is hard enough. Being free of
  1339. any warnings, on any version of any compiler, is simply not feasible.
  1340. - This is a C++ library with C interface.
  1341. Bindings or ports to any other programming languages are welcomed as external projects and
  1342. are not going to be included into this repository.
  1343. */
  1344. /*
  1345. Define this macro to 0/1 to disable/enable support for recording functionality,
  1346. available through VmaAllocatorCreateInfo::pRecordSettings.
  1347. */
  1348. #ifndef VMA_RECORDING_ENABLED
  1349. #define VMA_RECORDING_ENABLED 0
  1350. #endif
  1351. #ifndef NOMINMAX
  1352. #define NOMINMAX // For windows.h
  1353. #endif
  1354. #ifndef VULKAN_H_
  1355. #include <vulkan/vulkan.h>
  1356. #endif
  1357. #if VMA_RECORDING_ENABLED
  1358. #include <windows.h>
  1359. #endif
  1360. // Define this macro to declare maximum supported Vulkan version in format AAABBBCCC,
  1361. // where AAA = major, BBB = minor, CCC = patch.
  1362. // If you want to use version > 1.0, it still needs to be enabled via VmaAllocatorCreateInfo::vulkanApiVersion.
  1363. #if !defined(VMA_VULKAN_VERSION)
  1364. #if defined(VK_VERSION_1_1)
  1365. #define VMA_VULKAN_VERSION 1001000
  1366. #else
  1367. #define VMA_VULKAN_VERSION 1000000
  1368. #endif
  1369. #endif
  1370. #if !defined(VMA_DEDICATED_ALLOCATION)
  1371. #if VK_KHR_get_memory_requirements2 && VK_KHR_dedicated_allocation
  1372. #define VMA_DEDICATED_ALLOCATION 1
  1373. #else
  1374. #define VMA_DEDICATED_ALLOCATION 0
  1375. #endif
  1376. #endif
  1377. #if !defined(VMA_BIND_MEMORY2)
  1378. #if VK_KHR_bind_memory2
  1379. #define VMA_BIND_MEMORY2 1
  1380. #else
  1381. #define VMA_BIND_MEMORY2 0
  1382. #endif
  1383. #endif
  1384. #if !defined(VMA_MEMORY_BUDGET)
  1385. #if VK_EXT_memory_budget && (VK_KHR_get_physical_device_properties2 || VMA_VULKAN_VERSION >= 1001000)
  1386. #define VMA_MEMORY_BUDGET 1
  1387. #else
  1388. #define VMA_MEMORY_BUDGET 0
  1389. #endif
  1390. #endif
  1391. // Define these macros to decorate all public functions with additional code,
  1392. // before and after returned type, appropriately. This may be useful for
  1393. // exporing the functions when compiling VMA as a separate library. Example:
  1394. // #define VMA_CALL_PRE __declspec(dllexport)
  1395. // #define VMA_CALL_POST __cdecl
  1396. #ifndef VMA_CALL_PRE
  1397. #define VMA_CALL_PRE
  1398. #endif
  1399. #ifndef VMA_CALL_POST
  1400. #define VMA_CALL_POST
  1401. #endif
  1402. /** \struct VmaAllocator
  1403. \brief Represents main object of this library initialized.
  1404. Fill structure #VmaAllocatorCreateInfo and call function vmaCreateAllocator() to create it.
  1405. Call function vmaDestroyAllocator() to destroy it.
  1406. It is recommended to create just one object of this type per `VkDevice` object,
  1407. right after Vulkan is initialized and keep it alive until before Vulkan device is destroyed.
  1408. */
  1409. VK_DEFINE_HANDLE(VmaAllocator)
  1410. /// Callback function called after successful vkAllocateMemory.
  1411. typedef void (VKAPI_PTR *PFN_vmaAllocateDeviceMemoryFunction)(
  1412. VmaAllocator allocator,
  1413. uint32_t memoryType,
  1414. VkDeviceMemory memory,
  1415. VkDeviceSize size);
  1416. /// Callback function called before vkFreeMemory.
  1417. typedef void (VKAPI_PTR *PFN_vmaFreeDeviceMemoryFunction)(
  1418. VmaAllocator allocator,
  1419. uint32_t memoryType,
  1420. VkDeviceMemory memory,
  1421. VkDeviceSize size);
  1422. /** \brief Set of callbacks that the library will call for `vkAllocateMemory` and `vkFreeMemory`.
  1423. Provided for informative purpose, e.g. to gather statistics about number of
  1424. allocations or total amount of memory allocated in Vulkan.
  1425. Used in VmaAllocatorCreateInfo::pDeviceMemoryCallbacks.
  1426. */
  1427. typedef struct VmaDeviceMemoryCallbacks {
  1428. /// Optional, can be null.
  1429. PFN_vmaAllocateDeviceMemoryFunction pfnAllocate;
  1430. /// Optional, can be null.
  1431. PFN_vmaFreeDeviceMemoryFunction pfnFree;
  1432. } VmaDeviceMemoryCallbacks;
  1433. /// Flags for created #VmaAllocator.
  1434. typedef enum VmaAllocatorCreateFlagBits {
  1435. /** \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.
  1436. Using this flag may increase performance because internal mutexes are not used.
  1437. */
  1438. VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT = 0x00000001,
  1439. /** \brief Enables usage of VK_KHR_dedicated_allocation extension.
  1440. The flag works only if VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_0`.
  1441. When it's `VK_API_VERSION_1_1`, the flag is ignored because the extension has been promoted to Vulkan 1.1.
  1442. Using this extenion will automatically allocate dedicated blocks of memory for
  1443. some buffers and images instead of suballocating place for them out of bigger
  1444. memory blocks (as if you explicitly used #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT
  1445. flag) when it is recommended by the driver. It may improve performance on some
  1446. GPUs.
  1447. You may set this flag only if you found out that following device extensions are
  1448. supported, you enabled them while creating Vulkan device passed as
  1449. VmaAllocatorCreateInfo::device, and you want them to be used internally by this
  1450. library:
  1451. - VK_KHR_get_memory_requirements2 (device extension)
  1452. - VK_KHR_dedicated_allocation (device extension)
  1453. When this flag is set, you can experience following warnings reported by Vulkan
  1454. validation layer. You can ignore them.
  1455. > vkBindBufferMemory(): Binding memory to buffer 0x2d but vkGetBufferMemoryRequirements() has not been called on that buffer.
  1456. */
  1457. VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT = 0x00000002,
  1458. /**
  1459. Enables usage of VK_KHR_bind_memory2 extension.
  1460. The flag works only if VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_0`.
  1461. When it's `VK_API_VERSION_1_1`, the flag is ignored because the extension has been promoted to Vulkan 1.1.
  1462. You may set this flag only if you found out that this device extension is supported,
  1463. you enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device,
  1464. and you want it to be used internally by this library.
  1465. The extension provides functions `vkBindBufferMemory2KHR` and `vkBindImageMemory2KHR`,
  1466. which allow to pass a chain of `pNext` structures while binding.
  1467. This flag is required if you use `pNext` parameter in vmaBindBufferMemory2() or vmaBindImageMemory2().
  1468. */
  1469. VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT = 0x00000004,
  1470. /**
  1471. Enables usage of VK_EXT_memory_budget extension.
  1472. You may set this flag only if you found out that this device extension is supported,
  1473. you enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device,
  1474. and you want it to be used internally by this library, along with another instance extension
  1475. VK_KHR_get_physical_device_properties2, which is required by it (or Vulkan 1.1, where this extension is promoted).
  1476. The extension provides query for current memory usage and budget, which will probably
  1477. be more accurate than an estimation used by the library otherwise.
  1478. */
  1479. VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT = 0x00000008,
  1480. VMA_ALLOCATOR_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  1481. } VmaAllocatorCreateFlagBits;
  1482. typedef VkFlags VmaAllocatorCreateFlags;
  1483. /** \brief Pointers to some Vulkan functions - a subset used by the library.
  1484. Used in VmaAllocatorCreateInfo::pVulkanFunctions.
  1485. */
  1486. typedef struct VmaVulkanFunctions {
  1487. PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties;
  1488. PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties;
  1489. PFN_vkAllocateMemory vkAllocateMemory;
  1490. PFN_vkFreeMemory vkFreeMemory;
  1491. PFN_vkMapMemory vkMapMemory;
  1492. PFN_vkUnmapMemory vkUnmapMemory;
  1493. PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges;
  1494. PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges;
  1495. PFN_vkBindBufferMemory vkBindBufferMemory;
  1496. PFN_vkBindImageMemory vkBindImageMemory;
  1497. PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements;
  1498. PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements;
  1499. PFN_vkCreateBuffer vkCreateBuffer;
  1500. PFN_vkDestroyBuffer vkDestroyBuffer;
  1501. PFN_vkCreateImage vkCreateImage;
  1502. PFN_vkDestroyImage vkDestroyImage;
  1503. PFN_vkCmdCopyBuffer vkCmdCopyBuffer;
  1504. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  1505. PFN_vkGetBufferMemoryRequirements2KHR vkGetBufferMemoryRequirements2KHR;
  1506. PFN_vkGetImageMemoryRequirements2KHR vkGetImageMemoryRequirements2KHR;
  1507. #endif
  1508. #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000
  1509. PFN_vkBindBufferMemory2KHR vkBindBufferMemory2KHR;
  1510. PFN_vkBindImageMemory2KHR vkBindImageMemory2KHR;
  1511. #endif
  1512. #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000
  1513. PFN_vkGetPhysicalDeviceMemoryProperties2KHR vkGetPhysicalDeviceMemoryProperties2KHR;
  1514. #endif
  1515. } VmaVulkanFunctions;
  1516. /// Flags to be used in VmaRecordSettings::flags.
  1517. typedef enum VmaRecordFlagBits {
  1518. /** \brief Enables flush after recording every function call.
  1519. Enable it if you expect your application to crash, which may leave recording file truncated.
  1520. It may degrade performance though.
  1521. */
  1522. VMA_RECORD_FLUSH_AFTER_CALL_BIT = 0x00000001,
  1523. VMA_RECORD_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  1524. } VmaRecordFlagBits;
  1525. typedef VkFlags VmaRecordFlags;
  1526. /// Parameters for recording calls to VMA functions. To be used in VmaAllocatorCreateInfo::pRecordSettings.
  1527. typedef struct VmaRecordSettings
  1528. {
  1529. /// Flags for recording. Use #VmaRecordFlagBits enum.
  1530. VmaRecordFlags flags;
  1531. /** \brief Path to the file that should be written by the recording.
  1532. Suggested extension: "csv".
  1533. If the file already exists, it will be overwritten.
  1534. It will be opened for the whole time #VmaAllocator object is alive.
  1535. If opening this file fails, creation of the whole allocator object fails.
  1536. */
  1537. const char* pFilePath;
  1538. } VmaRecordSettings;
  1539. /// Description of a Allocator to be created.
  1540. typedef struct VmaAllocatorCreateInfo
  1541. {
  1542. /// Flags for created allocator. Use #VmaAllocatorCreateFlagBits enum.
  1543. VmaAllocatorCreateFlags flags;
  1544. /// Vulkan physical device.
  1545. /** It must be valid throughout whole lifetime of created allocator. */
  1546. VkPhysicalDevice physicalDevice;
  1547. /// Vulkan device.
  1548. /** It must be valid throughout whole lifetime of created allocator. */
  1549. VkDevice device;
  1550. /// Preferred size of a single `VkDeviceMemory` block to be allocated from large heaps > 1 GiB. Optional.
  1551. /** Set to 0 to use default, which is currently 256 MiB. */
  1552. VkDeviceSize preferredLargeHeapBlockSize;
  1553. /// Custom CPU memory allocation callbacks. Optional.
  1554. /** Optional, can be null. When specified, will also be used for all CPU-side memory allocations. */
  1555. const VkAllocationCallbacks* pAllocationCallbacks;
  1556. /// Informative callbacks for `vkAllocateMemory`, `vkFreeMemory`. Optional.
  1557. /** Optional, can be null. */
  1558. const VmaDeviceMemoryCallbacks* pDeviceMemoryCallbacks;
  1559. /** \brief Maximum number of additional frames that are in use at the same time as current frame.
  1560. This value is used only when you make allocations with
  1561. VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag. Such allocation cannot become
  1562. lost if allocation.lastUseFrameIndex >= allocator.currentFrameIndex - frameInUseCount.
  1563. For example, if you double-buffer your command buffers, so resources used for
  1564. rendering in previous frame may still be in use by the GPU at the moment you
  1565. allocate resources needed for the current frame, set this value to 1.
  1566. If you want to allow any allocations other than used in the current frame to
  1567. become lost, set this value to 0.
  1568. */
  1569. uint32_t frameInUseCount;
  1570. /** \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.
  1571. If not NULL, it must be a pointer to an array of
  1572. `VkPhysicalDeviceMemoryProperties::memoryHeapCount` elements, defining limit on
  1573. maximum number of bytes that can be allocated out of particular Vulkan memory
  1574. heap.
  1575. Any of the elements may be equal to `VK_WHOLE_SIZE`, which means no limit on that
  1576. heap. This is also the default in case of `pHeapSizeLimit` = NULL.
  1577. If there is a limit defined for a heap:
  1578. - If user tries to allocate more memory from that heap using this allocator,
  1579. the allocation fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  1580. - If the limit is smaller than heap size reported in `VkMemoryHeap::size`, the
  1581. value of this limit will be reported instead when using vmaGetMemoryProperties().
  1582. Warning! Using this feature may not be equivalent to installing a GPU with
  1583. smaller amount of memory, because graphics driver doesn't necessary fail new
  1584. allocations with `VK_ERROR_OUT_OF_DEVICE_MEMORY` result when memory capacity is
  1585. exceeded. It may return success and just silently migrate some device memory
  1586. blocks to system RAM. This driver behavior can also be controlled using
  1587. VK_AMD_memory_overallocation_behavior extension.
  1588. */
  1589. const VkDeviceSize* pHeapSizeLimit;
  1590. /** \brief Pointers to Vulkan functions. Can be null if you leave define `VMA_STATIC_VULKAN_FUNCTIONS 1`.
  1591. If you leave define `VMA_STATIC_VULKAN_FUNCTIONS 1` in configuration section,
  1592. you can pass null as this member, because the library will fetch pointers to
  1593. Vulkan functions internally in a static way, like:
  1594. vulkanFunctions.vkAllocateMemory = &vkAllocateMemory;
  1595. Fill this member if you want to provide your own pointers to Vulkan functions,
  1596. e.g. fetched using `vkGetInstanceProcAddr()` and `vkGetDeviceProcAddr()`.
  1597. */
  1598. const VmaVulkanFunctions* pVulkanFunctions;
  1599. /** \brief Parameters for recording of VMA calls. Can be null.
  1600. If not null, it enables recording of calls to VMA functions to a file.
  1601. If support for recording is not enabled using `VMA_RECORDING_ENABLED` macro,
  1602. creation of the allocator object fails with `VK_ERROR_FEATURE_NOT_PRESENT`.
  1603. */
  1604. const VmaRecordSettings* pRecordSettings;
  1605. /** \brief Optional handle to Vulkan instance object.
  1606. Optional, can be null. Must be set if #VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT flas is used
  1607. or if `vulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)`.
  1608. */
  1609. VkInstance instance;
  1610. /** \brief Optional. The highest version of Vulkan that the application is designed to use.
  1611. 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`.
  1612. The patch version number specified is ignored. Only the major and minor versions are considered.
  1613. It must be less or euqal (preferably equal) to value as passed to `vkCreateInstance` as `VkApplicationInfo::apiVersion`.
  1614. Only versions 1.0 and 1.1 are supported by the current implementation.
  1615. Leaving it initialized to zero is equivalent to `VK_API_VERSION_1_0`.
  1616. */
  1617. uint32_t vulkanApiVersion;
  1618. } VmaAllocatorCreateInfo;
  1619. /// Creates Allocator object.
  1620. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAllocator(
  1621. const VmaAllocatorCreateInfo* pCreateInfo,
  1622. VmaAllocator* pAllocator);
  1623. /// Destroys allocator object.
  1624. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyAllocator(
  1625. VmaAllocator allocator);
  1626. /**
  1627. PhysicalDeviceProperties are fetched from physicalDevice by the allocator.
  1628. You can access it here, without fetching it again on your own.
  1629. */
  1630. VMA_CALL_PRE void VMA_CALL_POST vmaGetPhysicalDeviceProperties(
  1631. VmaAllocator allocator,
  1632. const VkPhysicalDeviceProperties** ppPhysicalDeviceProperties);
  1633. /**
  1634. PhysicalDeviceMemoryProperties are fetched from physicalDevice by the allocator.
  1635. You can access it here, without fetching it again on your own.
  1636. */
  1637. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryProperties(
  1638. VmaAllocator allocator,
  1639. const VkPhysicalDeviceMemoryProperties** ppPhysicalDeviceMemoryProperties);
  1640. /**
  1641. \brief Given Memory Type Index, returns Property Flags of this memory type.
  1642. This is just a convenience function. Same information can be obtained using
  1643. vmaGetMemoryProperties().
  1644. */
  1645. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties(
  1646. VmaAllocator allocator,
  1647. uint32_t memoryTypeIndex,
  1648. VkMemoryPropertyFlags* pFlags);
  1649. /** \brief Sets index of the current frame.
  1650. This function must be used if you make allocations with
  1651. #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT and
  1652. #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flags to inform the allocator
  1653. when a new frame begins. Allocations queried using vmaGetAllocationInfo() cannot
  1654. become lost in the current frame.
  1655. */
  1656. VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex(
  1657. VmaAllocator allocator,
  1658. uint32_t frameIndex);
  1659. /** \brief Calculated statistics of memory usage in entire allocator.
  1660. */
  1661. typedef struct VmaStatInfo
  1662. {
  1663. /// Number of `VkDeviceMemory` Vulkan memory blocks allocated.
  1664. uint32_t blockCount;
  1665. /// Number of #VmaAllocation allocation objects allocated.
  1666. uint32_t allocationCount;
  1667. /// Number of free ranges of memory between allocations.
  1668. uint32_t unusedRangeCount;
  1669. /// Total number of bytes occupied by all allocations.
  1670. VkDeviceSize usedBytes;
  1671. /// Total number of bytes occupied by unused ranges.
  1672. VkDeviceSize unusedBytes;
  1673. VkDeviceSize allocationSizeMin, allocationSizeAvg, allocationSizeMax;
  1674. VkDeviceSize unusedRangeSizeMin, unusedRangeSizeAvg, unusedRangeSizeMax;
  1675. } VmaStatInfo;
  1676. /// General statistics from current state of Allocator.
  1677. typedef struct VmaStats
  1678. {
  1679. VmaStatInfo memoryType[VK_MAX_MEMORY_TYPES];
  1680. VmaStatInfo memoryHeap[VK_MAX_MEMORY_HEAPS];
  1681. VmaStatInfo total;
  1682. } VmaStats;
  1683. /** \brief Retrieves statistics from current state of the Allocator.
  1684. This function is called "calculate" not "get" because it has to traverse all
  1685. internal data structures, so it may be quite slow. For faster but more brief statistics
  1686. suitable to be called every frame or every allocation, use vmaGetBudget().
  1687. Note that when using allocator from multiple threads, returned information may immediately
  1688. become outdated.
  1689. */
  1690. VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStats(
  1691. VmaAllocator allocator,
  1692. VmaStats* pStats);
  1693. /** \brief Statistics of current memory usage and available budget, in bytes, for specific memory heap.
  1694. */
  1695. typedef struct VmaBudget
  1696. {
  1697. /** \brief Sum size of all `VkDeviceMemory` blocks allocated from particular heap, in bytes.
  1698. */
  1699. VkDeviceSize blockBytes;
  1700. /** \brief Sum size of all allocations created in particular heap, in bytes.
  1701. Usually less or equal than `blockBytes`.
  1702. Difference `blockBytes - allocationBytes` is the amount of memory allocated but unused -
  1703. available for new allocations or wasted due to fragmentation.
  1704. It might be greater than `blockBytes` if there are some allocations in lost state, as they account
  1705. to this value as well.
  1706. */
  1707. VkDeviceSize allocationBytes;
  1708. /** \brief Estimated current memory usage of the program, in bytes.
  1709. Fetched from system using `VK_EXT_memory_budget` extension if enabled.
  1710. It might be different than `blockBytes` (usually higher) due to additional implicit objects
  1711. also occupying the memory, like swapchain, pipelines, descriptor heaps, command buffers, or
  1712. `VkDeviceMemory` blocks allocated outside of this library, if any.
  1713. */
  1714. VkDeviceSize usage;
  1715. /** \brief Estimated amount of memory available to the program, in bytes.
  1716. Fetched from system using `VK_EXT_memory_budget` extension if enabled.
  1717. It might be different (most probably smaller) than `VkMemoryHeap::size[heapIndex]` due to factors
  1718. external to the program, like other programs also consuming system resources.
  1719. Difference `budget - usage` is the amount of additional memory that can probably
  1720. be allocated without problems. Exceeding the budget may result in various problems.
  1721. */
  1722. VkDeviceSize budget;
  1723. } VmaBudget;
  1724. /** \brief Retrieves information about current memory budget for all memory heaps.
  1725. \param[out] pBudget Must point to array with number of elements at least equal to number of memory heaps in physical device used.
  1726. This function is called "get" not "calculate" because it is very fast, suitable to be called
  1727. every frame or every allocation. For more detailed statistics use vmaCalculateStats().
  1728. Note that when using allocator from multiple threads, returned information may immediately
  1729. become outdated.
  1730. */
  1731. VMA_CALL_PRE void VMA_CALL_POST vmaGetBudget(
  1732. VmaAllocator allocator,
  1733. VmaBudget* pBudget);
  1734. #ifndef VMA_STATS_STRING_ENABLED
  1735. #define VMA_STATS_STRING_ENABLED 1
  1736. #endif
  1737. #if VMA_STATS_STRING_ENABLED
  1738. /// Builds and returns statistics as string in JSON format.
  1739. /** @param[out] ppStatsString Must be freed using vmaFreeStatsString() function.
  1740. */
  1741. VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString(
  1742. VmaAllocator allocator,
  1743. char** ppStatsString,
  1744. VkBool32 detailedMap);
  1745. VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString(
  1746. VmaAllocator allocator,
  1747. char* pStatsString);
  1748. #endif // #if VMA_STATS_STRING_ENABLED
  1749. /** \struct VmaPool
  1750. \brief Represents custom memory pool
  1751. Fill structure VmaPoolCreateInfo and call function vmaCreatePool() to create it.
  1752. Call function vmaDestroyPool() to destroy it.
  1753. For more information see [Custom memory pools](@ref choosing_memory_type_custom_memory_pools).
  1754. */
  1755. VK_DEFINE_HANDLE(VmaPool)
  1756. typedef enum VmaMemoryUsage
  1757. {
  1758. /** No intended memory usage specified.
  1759. Use other members of VmaAllocationCreateInfo to specify your requirements.
  1760. */
  1761. VMA_MEMORY_USAGE_UNKNOWN = 0,
  1762. /** Memory will be used on device only, so fast access from the device is preferred.
  1763. It usually means device-local GPU (video) memory.
  1764. No need to be mappable on host.
  1765. It is roughly equivalent of `D3D12_HEAP_TYPE_DEFAULT`.
  1766. Usage:
  1767. - Resources written and read by device, e.g. images used as attachments.
  1768. - Resources transferred from host once (immutable) or infrequently and read by
  1769. device multiple times, e.g. textures to be sampled, vertex buffers, uniform
  1770. (constant) buffers, and majority of other types of resources used on GPU.
  1771. Allocation may still end up in `HOST_VISIBLE` memory on some implementations.
  1772. In such case, you are free to map it.
  1773. You can use #VMA_ALLOCATION_CREATE_MAPPED_BIT with this usage type.
  1774. */
  1775. VMA_MEMORY_USAGE_GPU_ONLY = 1,
  1776. /** Memory will be mappable on host.
  1777. It usually means CPU (system) memory.
  1778. Guarantees to be `HOST_VISIBLE` and `HOST_COHERENT`.
  1779. CPU access is typically uncached. Writes may be write-combined.
  1780. Resources created in this pool may still be accessible to the device, but access to them can be slow.
  1781. It is roughly equivalent of `D3D12_HEAP_TYPE_UPLOAD`.
  1782. Usage: Staging copy of resources used as transfer source.
  1783. */
  1784. VMA_MEMORY_USAGE_CPU_ONLY = 2,
  1785. /**
  1786. Memory that is both mappable on host (guarantees to be `HOST_VISIBLE`) and preferably fast to access by GPU.
  1787. CPU access is typically uncached. Writes may be write-combined.
  1788. Usage: Resources written frequently by host (dynamic), read by device. E.g. textures, vertex buffers, uniform buffers updated every frame or every draw call.
  1789. */
  1790. VMA_MEMORY_USAGE_CPU_TO_GPU = 3,
  1791. /** Memory mappable on host (guarantees to be `HOST_VISIBLE`) and cached.
  1792. It is roughly equivalent of `D3D12_HEAP_TYPE_READBACK`.
  1793. Usage:
  1794. - Resources written by device, read by host - results of some computations, e.g. screen capture, average scene luminance for HDR tone mapping.
  1795. - Any resources read or accessed randomly on host, e.g. CPU-side copy of vertex buffer used as source of transfer, but also used for collision detection.
  1796. */
  1797. VMA_MEMORY_USAGE_GPU_TO_CPU = 4,
  1798. /** CPU memory - memory that is preferably not `DEVICE_LOCAL`, but also not guaranteed to be `HOST_VISIBLE`.
  1799. Usage: Staging copy of resources moved from GPU memory to CPU memory as part
  1800. of custom paging/residency mechanism, to be moved back to GPU memory when needed.
  1801. */
  1802. VMA_MEMORY_USAGE_CPU_COPY = 5,
  1803. /** Lazily allocated GPU memory having `VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT`.
  1804. Exists mostly on mobile platforms. Using it on desktop PC or other GPUs with no such memory type present will fail the allocation.
  1805. Usage: Memory for transient attachment images (color attachments, depth attachments etc.), created with `VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT`.
  1806. Allocations with this usage are always created as dedicated - it implies #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  1807. */
  1808. VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED = 6,
  1809. VMA_MEMORY_USAGE_MAX_ENUM = 0x7FFFFFFF
  1810. } VmaMemoryUsage;
  1811. /// Flags to be passed as VmaAllocationCreateInfo::flags.
  1812. typedef enum VmaAllocationCreateFlagBits {
  1813. /** \brief Set this flag if the allocation should have its own memory block.
  1814. Use it for special, big resources, like fullscreen images used as attachments.
  1815. You should not use this flag if VmaAllocationCreateInfo::pool is not null.
  1816. */
  1817. VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT = 0x00000001,
  1818. /** \brief Set this flag to only try to allocate from existing `VkDeviceMemory` blocks and never create new such block.
  1819. If new allocation cannot be placed in any of the existing blocks, allocation
  1820. fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY` error.
  1821. You should not use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT and
  1822. #VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT at the same time. It makes no sense.
  1823. If VmaAllocationCreateInfo::pool is not null, this flag is implied and ignored. */
  1824. VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT = 0x00000002,
  1825. /** \brief Set this flag to use a memory that will be persistently mapped and retrieve pointer to it.
  1826. Pointer to mapped memory will be returned through VmaAllocationInfo::pMappedData.
  1827. Is it valid to use this flag for allocation made from memory type that is not
  1828. `HOST_VISIBLE`. This flag is then ignored and memory is not mapped. This is
  1829. useful if you need an allocation that is efficient to use on GPU
  1830. (`DEVICE_LOCAL`) and still want to map it directly if possible on platforms that
  1831. support it (e.g. Intel GPU).
  1832. You should not use this flag together with #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT.
  1833. */
  1834. VMA_ALLOCATION_CREATE_MAPPED_BIT = 0x00000004,
  1835. /** Allocation created with this flag can become lost as a result of another
  1836. allocation with #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flag, so you
  1837. must check it before use.
  1838. To check if allocation is not lost, call vmaGetAllocationInfo() and check if
  1839. VmaAllocationInfo::deviceMemory is not `VK_NULL_HANDLE`.
  1840. For details about supporting lost allocations, see Lost Allocations
  1841. chapter of User Guide on Main Page.
  1842. You should not use this flag together with #VMA_ALLOCATION_CREATE_MAPPED_BIT.
  1843. */
  1844. VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT = 0x00000008,
  1845. /** While creating allocation using this flag, other allocations that were
  1846. created with flag #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT can become lost.
  1847. For details about supporting lost allocations, see Lost Allocations
  1848. chapter of User Guide on Main Page.
  1849. */
  1850. VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT = 0x00000010,
  1851. /** Set this flag to treat VmaAllocationCreateInfo::pUserData as pointer to a
  1852. null-terminated string. Instead of copying pointer value, a local copy of the
  1853. string is made and stored in allocation's `pUserData`. The string is automatically
  1854. freed together with the allocation. It is also used in vmaBuildStatsString().
  1855. */
  1856. VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT = 0x00000020,
  1857. /** Allocation will be created from upper stack in a double stack pool.
  1858. This flag is only allowed for custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT flag.
  1859. */
  1860. VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT = 0x00000040,
  1861. /** Create both buffer/image and allocation, but don't bind them together.
  1862. It is useful when you want to bind yourself to do some more advanced binding, e.g. using some extensions.
  1863. The flag is meaningful only with functions that bind by default: vmaCreateBuffer(), vmaCreateImage().
  1864. Otherwise it is ignored.
  1865. */
  1866. VMA_ALLOCATION_CREATE_DONT_BIND_BIT = 0x00000080,
  1867. /** Create allocation only if additional device memory required for it, if any, won't exceed
  1868. memory budget. Otherwise return `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  1869. */
  1870. VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT = 0x00000100,
  1871. /** Allocation strategy that chooses smallest possible free range for the
  1872. allocation.
  1873. */
  1874. VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT = 0x00010000,
  1875. /** Allocation strategy that chooses biggest possible free range for the
  1876. allocation.
  1877. */
  1878. VMA_ALLOCATION_CREATE_STRATEGY_WORST_FIT_BIT = 0x00020000,
  1879. /** Allocation strategy that chooses first suitable free range for the
  1880. allocation.
  1881. "First" doesn't necessarily means the one with smallest offset in memory,
  1882. but rather the one that is easiest and fastest to find.
  1883. */
  1884. VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT = 0x00040000,
  1885. /** Allocation strategy that tries to minimize memory usage.
  1886. */
  1887. VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT = VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT,
  1888. /** Allocation strategy that tries to minimize allocation time.
  1889. */
  1890. VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT = VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT,
  1891. /** Allocation strategy that tries to minimize memory fragmentation.
  1892. */
  1893. VMA_ALLOCATION_CREATE_STRATEGY_MIN_FRAGMENTATION_BIT = VMA_ALLOCATION_CREATE_STRATEGY_WORST_FIT_BIT,
  1894. /** A bit mask to extract only `STRATEGY` bits from entire set of flags.
  1895. */
  1896. VMA_ALLOCATION_CREATE_STRATEGY_MASK =
  1897. VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT |
  1898. VMA_ALLOCATION_CREATE_STRATEGY_WORST_FIT_BIT |
  1899. VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT,
  1900. VMA_ALLOCATION_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  1901. } VmaAllocationCreateFlagBits;
  1902. typedef VkFlags VmaAllocationCreateFlags;
  1903. typedef struct VmaAllocationCreateInfo
  1904. {
  1905. /// Use #VmaAllocationCreateFlagBits enum.
  1906. VmaAllocationCreateFlags flags;
  1907. /** \brief Intended usage of memory.
  1908. You can leave #VMA_MEMORY_USAGE_UNKNOWN if you specify memory requirements in other way. \n
  1909. If `pool` is not null, this member is ignored.
  1910. */
  1911. VmaMemoryUsage usage;
  1912. /** \brief Flags that must be set in a Memory Type chosen for an allocation.
  1913. Leave 0 if you specify memory requirements in other way. \n
  1914. If `pool` is not null, this member is ignored.*/
  1915. VkMemoryPropertyFlags requiredFlags;
  1916. /** \brief Flags that preferably should be set in a memory type chosen for an allocation.
  1917. Set to 0 if no additional flags are prefered. \n
  1918. If `pool` is not null, this member is ignored. */
  1919. VkMemoryPropertyFlags preferredFlags;
  1920. /** \brief Bitmask containing one bit set for every memory type acceptable for this allocation.
  1921. Value 0 is equivalent to `UINT32_MAX` - it means any memory type is accepted if
  1922. it meets other requirements specified by this structure, with no further
  1923. restrictions on memory type index. \n
  1924. If `pool` is not null, this member is ignored.
  1925. */
  1926. uint32_t memoryTypeBits;
  1927. /** \brief Pool that this allocation should be created in.
  1928. Leave `VK_NULL_HANDLE` to allocate from default pool. If not null, members:
  1929. `usage`, `requiredFlags`, `preferredFlags`, `memoryTypeBits` are ignored.
  1930. */
  1931. VmaPool pool;
  1932. /** \brief Custom general-purpose pointer that will be stored in #VmaAllocation, can be read as VmaAllocationInfo::pUserData and changed using vmaSetAllocationUserData().
  1933. If #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT is used, it must be either
  1934. null or pointer to a null-terminated string. The string will be then copied to
  1935. internal buffer, so it doesn't need to be valid after allocation call.
  1936. */
  1937. void* pUserData;
  1938. } VmaAllocationCreateInfo;
  1939. /**
  1940. \brief Helps to find memoryTypeIndex, given memoryTypeBits and VmaAllocationCreateInfo.
  1941. This algorithm tries to find a memory type that:
  1942. - Is allowed by memoryTypeBits.
  1943. - Contains all the flags from pAllocationCreateInfo->requiredFlags.
  1944. - Matches intended usage.
  1945. - Has as many flags from pAllocationCreateInfo->preferredFlags as possible.
  1946. \return Returns VK_ERROR_FEATURE_NOT_PRESENT if not found. Receiving such result
  1947. from this function or any other allocating function probably means that your
  1948. device doesn't support any memory type with requested features for the specific
  1949. type of resource you want to use it for. Please check parameters of your
  1950. resource, like image layout (OPTIMAL versus LINEAR) or mip level count.
  1951. */
  1952. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex(
  1953. VmaAllocator allocator,
  1954. uint32_t memoryTypeBits,
  1955. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  1956. uint32_t* pMemoryTypeIndex);
  1957. /**
  1958. \brief Helps to find memoryTypeIndex, given VkBufferCreateInfo and VmaAllocationCreateInfo.
  1959. It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex.
  1960. It internally creates a temporary, dummy buffer that never has memory bound.
  1961. It is just a convenience function, equivalent to calling:
  1962. - `vkCreateBuffer`
  1963. - `vkGetBufferMemoryRequirements`
  1964. - `vmaFindMemoryTypeIndex`
  1965. - `vkDestroyBuffer`
  1966. */
  1967. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo(
  1968. VmaAllocator allocator,
  1969. const VkBufferCreateInfo* pBufferCreateInfo,
  1970. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  1971. uint32_t* pMemoryTypeIndex);
  1972. /**
  1973. \brief Helps to find memoryTypeIndex, given VkImageCreateInfo and VmaAllocationCreateInfo.
  1974. It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex.
  1975. It internally creates a temporary, dummy image that never has memory bound.
  1976. It is just a convenience function, equivalent to calling:
  1977. - `vkCreateImage`
  1978. - `vkGetImageMemoryRequirements`
  1979. - `vmaFindMemoryTypeIndex`
  1980. - `vkDestroyImage`
  1981. */
  1982. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo(
  1983. VmaAllocator allocator,
  1984. const VkImageCreateInfo* pImageCreateInfo,
  1985. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  1986. uint32_t* pMemoryTypeIndex);
  1987. /// Flags to be passed as VmaPoolCreateInfo::flags.
  1988. typedef enum VmaPoolCreateFlagBits {
  1989. /** \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.
  1990. This is an optional optimization flag.
  1991. If you always allocate using vmaCreateBuffer(), vmaCreateImage(),
  1992. vmaAllocateMemoryForBuffer(), then you don't need to use it because allocator
  1993. knows exact type of your allocations so it can handle Buffer-Image Granularity
  1994. in the optimal way.
  1995. If you also allocate using vmaAllocateMemoryForImage() or vmaAllocateMemory(),
  1996. exact type of such allocations is not known, so allocator must be conservative
  1997. in handling Buffer-Image Granularity, which can lead to suboptimal allocation
  1998. (wasted memory). In that case, if you can make sure you always allocate only
  1999. buffers and linear images or only optimal images out of this pool, use this flag
  2000. to make allocator disregard Buffer-Image Granularity and so make allocations
  2001. faster and more optimal.
  2002. */
  2003. VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT = 0x00000002,
  2004. /** \brief Enables alternative, linear allocation algorithm in this pool.
  2005. Specify this flag to enable linear allocation algorithm, which always creates
  2006. new allocations after last one and doesn't reuse space from allocations freed in
  2007. between. It trades memory consumption for simplified algorithm and data
  2008. structure, which has better performance and uses less memory for metadata.
  2009. By using this flag, you can achieve behavior of free-at-once, stack,
  2010. ring buffer, and double stack. For details, see documentation chapter
  2011. \ref linear_algorithm.
  2012. When using this flag, you must specify VmaPoolCreateInfo::maxBlockCount == 1 (or 0 for default).
  2013. For more details, see [Linear allocation algorithm](@ref linear_algorithm).
  2014. */
  2015. VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT = 0x00000004,
  2016. /** \brief Enables alternative, buddy allocation algorithm in this pool.
  2017. It operates on a tree of blocks, each having size that is a power of two and
  2018. a half of its parent's size. Comparing to default algorithm, this one provides
  2019. faster allocation and deallocation and decreased external fragmentation,
  2020. at the expense of more memory wasted (internal fragmentation).
  2021. For more details, see [Buddy allocation algorithm](@ref buddy_algorithm).
  2022. */
  2023. VMA_POOL_CREATE_BUDDY_ALGORITHM_BIT = 0x00000008,
  2024. /** Bit mask to extract only `ALGORITHM` bits from entire set of flags.
  2025. */
  2026. VMA_POOL_CREATE_ALGORITHM_MASK =
  2027. VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT |
  2028. VMA_POOL_CREATE_BUDDY_ALGORITHM_BIT,
  2029. VMA_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  2030. } VmaPoolCreateFlagBits;
  2031. typedef VkFlags VmaPoolCreateFlags;
  2032. /** \brief Describes parameter of created #VmaPool.
  2033. */
  2034. typedef struct VmaPoolCreateInfo {
  2035. /** \brief Vulkan memory type index to allocate this pool from.
  2036. */
  2037. uint32_t memoryTypeIndex;
  2038. /** \brief Use combination of #VmaPoolCreateFlagBits.
  2039. */
  2040. VmaPoolCreateFlags flags;
  2041. /** \brief Size of a single `VkDeviceMemory` block to be allocated as part of this pool, in bytes. Optional.
  2042. Specify nonzero to set explicit, constant size of memory blocks used by this
  2043. pool.
  2044. Leave 0 to use default and let the library manage block sizes automatically.
  2045. Sizes of particular blocks may vary.
  2046. */
  2047. VkDeviceSize blockSize;
  2048. /** \brief Minimum number of blocks to be always allocated in this pool, even if they stay empty.
  2049. Set to 0 to have no preallocated blocks and allow the pool be completely empty.
  2050. */
  2051. size_t minBlockCount;
  2052. /** \brief Maximum number of blocks that can be allocated in this pool. Optional.
  2053. Set to 0 to use default, which is `SIZE_MAX`, which means no limit.
  2054. Set to same value as VmaPoolCreateInfo::minBlockCount to have fixed amount of memory allocated
  2055. throughout whole lifetime of this pool.
  2056. */
  2057. size_t maxBlockCount;
  2058. /** \brief Maximum number of additional frames that are in use at the same time as current frame.
  2059. This value is used only when you make allocations with
  2060. #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag. Such allocation cannot become
  2061. lost if allocation.lastUseFrameIndex >= allocator.currentFrameIndex - frameInUseCount.
  2062. For example, if you double-buffer your command buffers, so resources used for
  2063. rendering in previous frame may still be in use by the GPU at the moment you
  2064. allocate resources needed for the current frame, set this value to 1.
  2065. If you want to allow any allocations other than used in the current frame to
  2066. become lost, set this value to 0.
  2067. */
  2068. uint32_t frameInUseCount;
  2069. } VmaPoolCreateInfo;
  2070. /** \brief Describes parameter of existing #VmaPool.
  2071. */
  2072. typedef struct VmaPoolStats {
  2073. /** \brief Total amount of `VkDeviceMemory` allocated from Vulkan for this pool, in bytes.
  2074. */
  2075. VkDeviceSize size;
  2076. /** \brief Total number of bytes in the pool not used by any #VmaAllocation.
  2077. */
  2078. VkDeviceSize unusedSize;
  2079. /** \brief Number of #VmaAllocation objects created from this pool that were not destroyed or lost.
  2080. */
  2081. size_t allocationCount;
  2082. /** \brief Number of continuous memory ranges in the pool not used by any #VmaAllocation.
  2083. */
  2084. size_t unusedRangeCount;
  2085. /** \brief Size of the largest continuous free memory region available for new allocation.
  2086. Making a new allocation of that size is not guaranteed to succeed because of
  2087. possible additional margin required to respect alignment and buffer/image
  2088. granularity.
  2089. */
  2090. VkDeviceSize unusedRangeSizeMax;
  2091. /** \brief Number of `VkDeviceMemory` blocks allocated for this pool.
  2092. */
  2093. size_t blockCount;
  2094. } VmaPoolStats;
  2095. /** \brief Allocates Vulkan device memory and creates #VmaPool object.
  2096. @param allocator Allocator object.
  2097. @param pCreateInfo Parameters of pool to create.
  2098. @param[out] pPool Handle to created pool.
  2099. */
  2100. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool(
  2101. VmaAllocator allocator,
  2102. const VmaPoolCreateInfo* pCreateInfo,
  2103. VmaPool* pPool);
  2104. /** \brief Destroys #VmaPool object and frees Vulkan device memory.
  2105. */
  2106. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool(
  2107. VmaAllocator allocator,
  2108. VmaPool pool);
  2109. /** \brief Retrieves statistics of existing #VmaPool object.
  2110. @param allocator Allocator object.
  2111. @param pool Pool object.
  2112. @param[out] pPoolStats Statistics of specified pool.
  2113. */
  2114. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStats(
  2115. VmaAllocator allocator,
  2116. VmaPool pool,
  2117. VmaPoolStats* pPoolStats);
  2118. /** \brief Marks all allocations in given pool as lost if they are not used in current frame or VmaPoolCreateInfo::frameInUseCount back from now.
  2119. @param allocator Allocator object.
  2120. @param pool Pool.
  2121. @param[out] pLostAllocationCount Number of allocations marked as lost. Optional - pass null if you don't need this information.
  2122. */
  2123. VMA_CALL_PRE void VMA_CALL_POST vmaMakePoolAllocationsLost(
  2124. VmaAllocator allocator,
  2125. VmaPool pool,
  2126. size_t* pLostAllocationCount);
  2127. /** \brief Checks magic number in margins around all allocations in given memory pool in search for corruptions.
  2128. Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero,
  2129. `VMA_DEBUG_MARGIN` is defined to nonzero and the pool is created in memory type that is
  2130. `HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection).
  2131. Possible return values:
  2132. - `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for specified pool.
  2133. - `VK_SUCCESS` - corruption detection has been performed and succeeded.
  2134. - `VK_ERROR_VALIDATION_FAILED_EXT` - corruption detection has been performed and found memory corruptions around one of the allocations.
  2135. `VMA_ASSERT` is also fired in that case.
  2136. - Other value: Error returned by Vulkan, e.g. memory mapping failure.
  2137. */
  2138. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckPoolCorruption(VmaAllocator allocator, VmaPool pool);
  2139. /** \brief Retrieves name of a custom pool.
  2140. After the call `ppName` is either null or points to an internally-owned null-terminated string
  2141. containing name of the pool that was previously set. The pointer becomes invalid when the pool is
  2142. destroyed or its name is changed using vmaSetPoolName().
  2143. */
  2144. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName(
  2145. VmaAllocator allocator,
  2146. VmaPool pool,
  2147. const char** ppName);
  2148. /** \brief Sets name of a custom pool.
  2149. `pName` can be either null or pointer to a null-terminated string with new name for the pool.
  2150. Function makes internal copy of the string, so it can be changed or freed immediately after this call.
  2151. */
  2152. VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName(
  2153. VmaAllocator allocator,
  2154. VmaPool pool,
  2155. const char* pName);
  2156. /** \struct VmaAllocation
  2157. \brief Represents single memory allocation.
  2158. It may be either dedicated block of `VkDeviceMemory` or a specific region of a bigger block of this type
  2159. plus unique offset.
  2160. There are multiple ways to create such object.
  2161. You need to fill structure VmaAllocationCreateInfo.
  2162. For more information see [Choosing memory type](@ref choosing_memory_type).
  2163. Although the library provides convenience functions that create Vulkan buffer or image,
  2164. allocate memory for it and bind them together,
  2165. binding of the allocation to a buffer or an image is out of scope of the allocation itself.
  2166. Allocation object can exist without buffer/image bound,
  2167. binding can be done manually by the user, and destruction of it can be done
  2168. independently of destruction of the allocation.
  2169. The object also remembers its size and some other information.
  2170. To retrieve this information, use function vmaGetAllocationInfo() and inspect
  2171. returned structure VmaAllocationInfo.
  2172. Some kinds allocations can be in lost state.
  2173. For more information, see [Lost allocations](@ref lost_allocations).
  2174. */
  2175. VK_DEFINE_HANDLE(VmaAllocation)
  2176. /** \brief Parameters of #VmaAllocation objects, that can be retrieved using function vmaGetAllocationInfo().
  2177. */
  2178. typedef struct VmaAllocationInfo {
  2179. /** \brief Memory type index that this allocation was allocated from.
  2180. It never changes.
  2181. */
  2182. uint32_t memoryType;
  2183. /** \brief Handle to Vulkan memory object.
  2184. Same memory object can be shared by multiple allocations.
  2185. It can change after call to vmaDefragment() if this allocation is passed to the function, or if allocation is lost.
  2186. If the allocation is lost, it is equal to `VK_NULL_HANDLE`.
  2187. */
  2188. VkDeviceMemory deviceMemory;
  2189. /** \brief Offset into deviceMemory object to the beginning of this allocation, in bytes. (deviceMemory, offset) pair is unique to this allocation.
  2190. It can change after call to vmaDefragment() if this allocation is passed to the function, or if allocation is lost.
  2191. */
  2192. VkDeviceSize offset;
  2193. /** \brief Size of this allocation, in bytes.
  2194. It never changes, unless allocation is lost.
  2195. */
  2196. VkDeviceSize size;
  2197. /** \brief Pointer to the beginning of this allocation as mapped data.
  2198. If the allocation hasn't been mapped using vmaMapMemory() and hasn't been
  2199. created with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag, this value null.
  2200. It can change after call to vmaMapMemory(), vmaUnmapMemory().
  2201. It can also change after call to vmaDefragment() if this allocation is passed to the function.
  2202. */
  2203. void* pMappedData;
  2204. /** \brief Custom general-purpose pointer that was passed as VmaAllocationCreateInfo::pUserData or set using vmaSetAllocationUserData().
  2205. It can change after call to vmaSetAllocationUserData() for this allocation.
  2206. */
  2207. void* pUserData;
  2208. } VmaAllocationInfo;
  2209. /** \brief General purpose memory allocation.
  2210. @param[out] pAllocation Handle to allocated memory.
  2211. @param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
  2212. You should free the memory using vmaFreeMemory() or vmaFreeMemoryPages().
  2213. It is recommended to use vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage(),
  2214. vmaCreateBuffer(), vmaCreateImage() instead whenever possible.
  2215. */
  2216. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory(
  2217. VmaAllocator allocator,
  2218. const VkMemoryRequirements* pVkMemoryRequirements,
  2219. const VmaAllocationCreateInfo* pCreateInfo,
  2220. VmaAllocation* pAllocation,
  2221. VmaAllocationInfo* pAllocationInfo);
  2222. /** \brief General purpose memory allocation for multiple allocation objects at once.
  2223. @param allocator Allocator object.
  2224. @param pVkMemoryRequirements Memory requirements for each allocation.
  2225. @param pCreateInfo Creation parameters for each alloction.
  2226. @param allocationCount Number of allocations to make.
  2227. @param[out] pAllocations Pointer to array that will be filled with handles to created allocations.
  2228. @param[out] pAllocationInfo Optional. Pointer to array that will be filled with parameters of created allocations.
  2229. You should free the memory using vmaFreeMemory() or vmaFreeMemoryPages().
  2230. Word "pages" is just a suggestion to use this function to allocate pieces of memory needed for sparse binding.
  2231. It is just a general purpose allocation function able to make multiple allocations at once.
  2232. It may be internally optimized to be more efficient than calling vmaAllocateMemory() `allocationCount` times.
  2233. All allocations are made using same parameters. All of them are created out of the same memory pool and type.
  2234. If any allocation fails, all allocations already made within this function call are also freed, so that when
  2235. returned result is not `VK_SUCCESS`, `pAllocation` array is always entirely filled with `VK_NULL_HANDLE`.
  2236. */
  2237. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages(
  2238. VmaAllocator allocator,
  2239. const VkMemoryRequirements* pVkMemoryRequirements,
  2240. const VmaAllocationCreateInfo* pCreateInfo,
  2241. size_t allocationCount,
  2242. VmaAllocation* pAllocations,
  2243. VmaAllocationInfo* pAllocationInfo);
  2244. /**
  2245. @param[out] pAllocation Handle to allocated memory.
  2246. @param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
  2247. You should free the memory using vmaFreeMemory().
  2248. */
  2249. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer(
  2250. VmaAllocator allocator,
  2251. VkBuffer buffer,
  2252. const VmaAllocationCreateInfo* pCreateInfo,
  2253. VmaAllocation* pAllocation,
  2254. VmaAllocationInfo* pAllocationInfo);
  2255. /// Function similar to vmaAllocateMemoryForBuffer().
  2256. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage(
  2257. VmaAllocator allocator,
  2258. VkImage image,
  2259. const VmaAllocationCreateInfo* pCreateInfo,
  2260. VmaAllocation* pAllocation,
  2261. VmaAllocationInfo* pAllocationInfo);
  2262. /** \brief Frees memory previously allocated using vmaAllocateMemory(), vmaAllocateMemoryForBuffer(), or vmaAllocateMemoryForImage().
  2263. Passing `VK_NULL_HANDLE` as `allocation` is valid. Such function call is just skipped.
  2264. */
  2265. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory(
  2266. VmaAllocator allocator,
  2267. VmaAllocation allocation);
  2268. /** \brief Frees memory and destroys multiple allocations.
  2269. Word "pages" is just a suggestion to use this function to free pieces of memory used for sparse binding.
  2270. It is just a general purpose function to free memory and destroy allocations made using e.g. vmaAllocateMemory(),
  2271. vmaAllocateMemoryPages() and other functions.
  2272. It may be internally optimized to be more efficient than calling vmaFreeMemory() `allocationCount` times.
  2273. Allocations in `pAllocations` array can come from any memory pools and types.
  2274. Passing `VK_NULL_HANDLE` as elements of `pAllocations` array is valid. Such entries are just skipped.
  2275. */
  2276. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages(
  2277. VmaAllocator allocator,
  2278. size_t allocationCount,
  2279. VmaAllocation* pAllocations);
  2280. /** \brief Deprecated.
  2281. In version 2.2.0 it used to try to change allocation's size without moving or reallocating it.
  2282. In current version it returns `VK_SUCCESS` only if `newSize` equals current allocation's size.
  2283. Otherwise returns `VK_ERROR_OUT_OF_POOL_MEMORY`, indicating that allocation's size could not be changed.
  2284. */
  2285. VMA_CALL_PRE VkResult VMA_CALL_POST vmaResizeAllocation(
  2286. VmaAllocator allocator,
  2287. VmaAllocation allocation,
  2288. VkDeviceSize newSize);
  2289. /** \brief Returns current information about specified allocation and atomically marks it as used in current frame.
  2290. Current paramters of given allocation are returned in `pAllocationInfo`.
  2291. This function also atomically "touches" allocation - marks it as used in current frame,
  2292. just like vmaTouchAllocation().
  2293. If the allocation is in lost state, `pAllocationInfo->deviceMemory == VK_NULL_HANDLE`.
  2294. Although this function uses atomics and doesn't lock any mutex, so it should be quite efficient,
  2295. you can avoid calling it too often.
  2296. - You can retrieve same VmaAllocationInfo structure while creating your resource, from function
  2297. vmaCreateBuffer(), vmaCreateImage(). You can remember it if you are sure parameters don't change
  2298. (e.g. due to defragmentation or allocation becoming lost).
  2299. - If you just want to check if allocation is not lost, vmaTouchAllocation() will work faster.
  2300. */
  2301. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo(
  2302. VmaAllocator allocator,
  2303. VmaAllocation allocation,
  2304. VmaAllocationInfo* pAllocationInfo);
  2305. /** \brief Returns `VK_TRUE` if allocation is not lost and atomically marks it as used in current frame.
  2306. If the allocation has been created with #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag,
  2307. this function returns `VK_TRUE` if it's not in lost state, so it can still be used.
  2308. It then also atomically "touches" the allocation - marks it as used in current frame,
  2309. so that you can be sure it won't become lost in current frame or next `frameInUseCount` frames.
  2310. If the allocation is in lost state, the function returns `VK_FALSE`.
  2311. Memory of such allocation, as well as buffer or image bound to it, should not be used.
  2312. Lost allocation and the buffer/image still need to be destroyed.
  2313. If the allocation has been created without #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag,
  2314. this function always returns `VK_TRUE`.
  2315. */
  2316. VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaTouchAllocation(
  2317. VmaAllocator allocator,
  2318. VmaAllocation allocation);
  2319. /** \brief Sets pUserData in given allocation to new value.
  2320. If the allocation was created with VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT,
  2321. pUserData must be either null, or pointer to a null-terminated string. The function
  2322. makes local copy of the string and sets it as allocation's `pUserData`. String
  2323. passed as pUserData doesn't need to be valid for whole lifetime of the allocation -
  2324. you can free it after this call. String previously pointed by allocation's
  2325. pUserData is freed from memory.
  2326. If the flag was not used, the value of pointer `pUserData` is just copied to
  2327. allocation's `pUserData`. It is opaque, so you can use it however you want - e.g.
  2328. as a pointer, ordinal number or some handle to you own data.
  2329. */
  2330. VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData(
  2331. VmaAllocator allocator,
  2332. VmaAllocation allocation,
  2333. void* pUserData);
  2334. /** \brief Creates new allocation that is in lost state from the beginning.
  2335. It can be useful if you need a dummy, non-null allocation.
  2336. You still need to destroy created object using vmaFreeMemory().
  2337. Returned allocation is not tied to any specific memory pool or memory type and
  2338. not bound to any image or buffer. It has size = 0. It cannot be turned into
  2339. a real, non-empty allocation.
  2340. */
  2341. VMA_CALL_PRE void VMA_CALL_POST vmaCreateLostAllocation(
  2342. VmaAllocator allocator,
  2343. VmaAllocation* pAllocation);
  2344. /** \brief Maps memory represented by given allocation and returns pointer to it.
  2345. Maps memory represented by given allocation to make it accessible to CPU code.
  2346. When succeeded, `*ppData` contains pointer to first byte of this memory.
  2347. If the allocation is part of bigger `VkDeviceMemory` block, the pointer is
  2348. correctly offseted to the beginning of region assigned to this particular
  2349. allocation.
  2350. Mapping is internally reference-counted and synchronized, so despite raw Vulkan
  2351. function `vkMapMemory()` cannot be used to map same block of `VkDeviceMemory`
  2352. multiple times simultaneously, it is safe to call this function on allocations
  2353. assigned to the same memory block. Actual Vulkan memory will be mapped on first
  2354. mapping and unmapped on last unmapping.
  2355. If the function succeeded, you must call vmaUnmapMemory() to unmap the
  2356. allocation when mapping is no longer needed or before freeing the allocation, at
  2357. the latest.
  2358. It also safe to call this function multiple times on the same allocation. You
  2359. must call vmaUnmapMemory() same number of times as you called vmaMapMemory().
  2360. It is also safe to call this function on allocation created with
  2361. #VMA_ALLOCATION_CREATE_MAPPED_BIT flag. Its memory stays mapped all the time.
  2362. You must still call vmaUnmapMemory() same number of times as you called
  2363. vmaMapMemory(). You must not call vmaUnmapMemory() additional time to free the
  2364. "0-th" mapping made automatically due to #VMA_ALLOCATION_CREATE_MAPPED_BIT flag.
  2365. This function fails when used on allocation made in memory type that is not
  2366. `HOST_VISIBLE`.
  2367. This function always fails when called for allocation that was created with
  2368. #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag. Such allocations cannot be
  2369. mapped.
  2370. This function doesn't automatically flush or invalidate caches.
  2371. If the allocation is made from a memory types that is not `HOST_COHERENT`,
  2372. you also need to use vmaInvalidateAllocation() / vmaFlushAllocation(), as required by Vulkan specification.
  2373. */
  2374. VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory(
  2375. VmaAllocator allocator,
  2376. VmaAllocation allocation,
  2377. void** ppData);
  2378. /** \brief Unmaps memory represented by given allocation, mapped previously using vmaMapMemory().
  2379. For details, see description of vmaMapMemory().
  2380. This function doesn't automatically flush or invalidate caches.
  2381. If the allocation is made from a memory types that is not `HOST_COHERENT`,
  2382. you also need to use vmaInvalidateAllocation() / vmaFlushAllocation(), as required by Vulkan specification.
  2383. */
  2384. VMA_CALL_PRE void VMA_CALL_POST vmaUnmapMemory(
  2385. VmaAllocator allocator,
  2386. VmaAllocation allocation);
  2387. /** \brief Flushes memory of given allocation.
  2388. Calls `vkFlushMappedMemoryRanges()` for memory associated with given range of given allocation.
  2389. It needs to be called after writing to a mapped memory for memory types that are not `HOST_COHERENT`.
  2390. Unmap operation doesn't do that automatically.
  2391. - `offset` must be relative to the beginning of allocation.
  2392. - `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation.
  2393. - `offset` and `size` don't have to be aligned.
  2394. They are internally rounded down/up to multiply of `nonCoherentAtomSize`.
  2395. - If `size` is 0, this call is ignored.
  2396. - If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`,
  2397. this call is ignored.
  2398. Warning! `offset` and `size` are relative to the contents of given `allocation`.
  2399. If you mean whole allocation, you can pass 0 and `VK_WHOLE_SIZE`, respectively.
  2400. Do not pass allocation's offset as `offset`!!!
  2401. */
  2402. VMA_CALL_PRE void VMA_CALL_POST vmaFlushAllocation(VmaAllocator allocator, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size);
  2403. /** \brief Invalidates memory of given allocation.
  2404. Calls `vkInvalidateMappedMemoryRanges()` for memory associated with given range of given allocation.
  2405. It needs to be called before reading from a mapped memory for memory types that are not `HOST_COHERENT`.
  2406. Map operation doesn't do that automatically.
  2407. - `offset` must be relative to the beginning of allocation.
  2408. - `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation.
  2409. - `offset` and `size` don't have to be aligned.
  2410. They are internally rounded down/up to multiply of `nonCoherentAtomSize`.
  2411. - If `size` is 0, this call is ignored.
  2412. - If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`,
  2413. this call is ignored.
  2414. Warning! `offset` and `size` are relative to the contents of given `allocation`.
  2415. If you mean whole allocation, you can pass 0 and `VK_WHOLE_SIZE`, respectively.
  2416. Do not pass allocation's offset as `offset`!!!
  2417. */
  2418. VMA_CALL_PRE void VMA_CALL_POST vmaInvalidateAllocation(VmaAllocator allocator, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size);
  2419. /** \brief Checks magic number in margins around all allocations in given memory types (in both default and custom pools) in search for corruptions.
  2420. @param memoryTypeBits Bit mask, where each bit set means that a memory type with that index should be checked.
  2421. Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero,
  2422. `VMA_DEBUG_MARGIN` is defined to nonzero and only for memory types that are
  2423. `HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection).
  2424. Possible return values:
  2425. - `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for any of specified memory types.
  2426. - `VK_SUCCESS` - corruption detection has been performed and succeeded.
  2427. - `VK_ERROR_VALIDATION_FAILED_EXT` - corruption detection has been performed and found memory corruptions around one of the allocations.
  2428. `VMA_ASSERT` is also fired in that case.
  2429. - Other value: Error returned by Vulkan, e.g. memory mapping failure.
  2430. */
  2431. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckCorruption(VmaAllocator allocator, uint32_t memoryTypeBits);
  2432. /** \struct VmaDefragmentationContext
  2433. \brief Represents Opaque object that represents started defragmentation process.
  2434. Fill structure #VmaDefragmentationInfo2 and call function vmaDefragmentationBegin() to create it.
  2435. Call function vmaDefragmentationEnd() to destroy it.
  2436. */
  2437. VK_DEFINE_HANDLE(VmaDefragmentationContext)
  2438. /// Flags to be used in vmaDefragmentationBegin(). None at the moment. Reserved for future use.
  2439. typedef enum VmaDefragmentationFlagBits {
  2440. VMA_DEFRAGMENTATION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  2441. } VmaDefragmentationFlagBits;
  2442. typedef VkFlags VmaDefragmentationFlags;
  2443. /** \brief Parameters for defragmentation.
  2444. To be used with function vmaDefragmentationBegin().
  2445. */
  2446. typedef struct VmaDefragmentationInfo2 {
  2447. /** \brief Reserved for future use. Should be 0.
  2448. */
  2449. VmaDefragmentationFlags flags;
  2450. /** \brief Number of allocations in `pAllocations` array.
  2451. */
  2452. uint32_t allocationCount;
  2453. /** \brief Pointer to array of allocations that can be defragmented.
  2454. The array should have `allocationCount` elements.
  2455. The array should not contain nulls.
  2456. Elements in the array should be unique - same allocation cannot occur twice.
  2457. It is safe to pass allocations that are in the lost state - they are ignored.
  2458. All allocations not present in this array are considered non-moveable during this defragmentation.
  2459. */
  2460. VmaAllocation* pAllocations;
  2461. /** \brief Optional, output. Pointer to array that will be filled with information whether the allocation at certain index has been changed during defragmentation.
  2462. The array should have `allocationCount` elements.
  2463. You can pass null if you are not interested in this information.
  2464. */
  2465. VkBool32* pAllocationsChanged;
  2466. /** \brief Numer of pools in `pPools` array.
  2467. */
  2468. uint32_t poolCount;
  2469. /** \brief Either null or pointer to array of pools to be defragmented.
  2470. All the allocations in the specified pools can be moved during defragmentation
  2471. and there is no way to check if they were really moved as in `pAllocationsChanged`,
  2472. so you must query all the allocations in all these pools for new `VkDeviceMemory`
  2473. and offset using vmaGetAllocationInfo() if you might need to recreate buffers
  2474. and images bound to them.
  2475. The array should have `poolCount` elements.
  2476. The array should not contain nulls.
  2477. Elements in the array should be unique - same pool cannot occur twice.
  2478. Using this array is equivalent to specifying all allocations from the pools in `pAllocations`.
  2479. It might be more efficient.
  2480. */
  2481. VmaPool* pPools;
  2482. /** \brief Maximum total numbers of bytes that can be copied while moving allocations to different places using transfers on CPU side, like `memcpy()`, `memmove()`.
  2483. `VK_WHOLE_SIZE` means no limit.
  2484. */
  2485. VkDeviceSize maxCpuBytesToMove;
  2486. /** \brief Maximum number of allocations that can be moved to a different place using transfers on CPU side, like `memcpy()`, `memmove()`.
  2487. `UINT32_MAX` means no limit.
  2488. */
  2489. uint32_t maxCpuAllocationsToMove;
  2490. /** \brief Maximum total numbers of bytes that can be copied while moving allocations to different places using transfers on GPU side, posted to `commandBuffer`.
  2491. `VK_WHOLE_SIZE` means no limit.
  2492. */
  2493. VkDeviceSize maxGpuBytesToMove;
  2494. /** \brief Maximum number of allocations that can be moved to a different place using transfers on GPU side, posted to `commandBuffer`.
  2495. `UINT32_MAX` means no limit.
  2496. */
  2497. uint32_t maxGpuAllocationsToMove;
  2498. /** \brief Optional. Command buffer where GPU copy commands will be posted.
  2499. If not null, it must be a valid command buffer handle that supports Transfer queue type.
  2500. It must be in the recording state and outside of a render pass instance.
  2501. You need to submit it and make sure it finished execution before calling vmaDefragmentationEnd().
  2502. Passing null means that only CPU defragmentation will be performed.
  2503. */
  2504. VkCommandBuffer commandBuffer;
  2505. } VmaDefragmentationInfo2;
  2506. /** \brief Deprecated. Optional configuration parameters to be passed to function vmaDefragment().
  2507. \deprecated This is a part of the old interface. It is recommended to use structure #VmaDefragmentationInfo2 and function vmaDefragmentationBegin() instead.
  2508. */
  2509. typedef struct VmaDefragmentationInfo {
  2510. /** \brief Maximum total numbers of bytes that can be copied while moving allocations to different places.
  2511. Default is `VK_WHOLE_SIZE`, which means no limit.
  2512. */
  2513. VkDeviceSize maxBytesToMove;
  2514. /** \brief Maximum number of allocations that can be moved to different place.
  2515. Default is `UINT32_MAX`, which means no limit.
  2516. */
  2517. uint32_t maxAllocationsToMove;
  2518. } VmaDefragmentationInfo;
  2519. /** \brief Statistics returned by function vmaDefragment(). */
  2520. typedef struct VmaDefragmentationStats {
  2521. /// Total number of bytes that have been copied while moving allocations to different places.
  2522. VkDeviceSize bytesMoved;
  2523. /// Total number of bytes that have been released to the system by freeing empty `VkDeviceMemory` objects.
  2524. VkDeviceSize bytesFreed;
  2525. /// Number of allocations that have been moved to different places.
  2526. uint32_t allocationsMoved;
  2527. /// Number of empty `VkDeviceMemory` objects that have been released to the system.
  2528. uint32_t deviceMemoryBlocksFreed;
  2529. } VmaDefragmentationStats;
  2530. /** \brief Begins defragmentation process.
  2531. @param allocator Allocator object.
  2532. @param pInfo Structure filled with parameters of defragmentation.
  2533. @param[out] pStats Optional. Statistics of defragmentation. You can pass null if you are not interested in this information.
  2534. @param[out] pContext Context object that must be passed to vmaDefragmentationEnd() to finish defragmentation.
  2535. @return `VK_SUCCESS` and `*pContext == null` if defragmentation finished within this function call. `VK_NOT_READY` and `*pContext != null` if defragmentation has been started and you need to call vmaDefragmentationEnd() to finish it. Negative value in case of error.
  2536. Use this function instead of old, deprecated vmaDefragment().
  2537. Warning! Between the call to vmaDefragmentationBegin() and vmaDefragmentationEnd():
  2538. - You should not use any of allocations passed as `pInfo->pAllocations` or
  2539. any allocations that belong to pools passed as `pInfo->pPools`,
  2540. including calling vmaGetAllocationInfo(), vmaTouchAllocation(), or access
  2541. their data.
  2542. - Some mutexes protecting internal data structures may be locked, so trying to
  2543. make or free any allocations, bind buffers or images, map memory, or launch
  2544. another simultaneous defragmentation in between may cause stall (when done on
  2545. another thread) or deadlock (when done on the same thread), unless you are
  2546. 100% sure that defragmented allocations are in different pools.
  2547. - Information returned via `pStats` and `pInfo->pAllocationsChanged` are undefined.
  2548. They become valid after call to vmaDefragmentationEnd().
  2549. - If `pInfo->commandBuffer` is not null, you must submit that command buffer
  2550. and make sure it finished execution before calling vmaDefragmentationEnd().
  2551. For more information and important limitations regarding defragmentation, see documentation chapter:
  2552. [Defragmentation](@ref defragmentation).
  2553. */
  2554. VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragmentationBegin(
  2555. VmaAllocator allocator,
  2556. const VmaDefragmentationInfo2* pInfo,
  2557. VmaDefragmentationStats* pStats,
  2558. VmaDefragmentationContext *pContext);
  2559. /** \brief Ends defragmentation process.
  2560. Use this function to finish defragmentation started by vmaDefragmentationBegin().
  2561. It is safe to pass `context == null`. The function then does nothing.
  2562. */
  2563. VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragmentationEnd(
  2564. VmaAllocator allocator,
  2565. VmaDefragmentationContext context);
  2566. /** \brief Deprecated. Compacts memory by moving allocations.
  2567. @param pAllocations Array of allocations that can be moved during this compation.
  2568. @param allocationCount Number of elements in pAllocations and pAllocationsChanged arrays.
  2569. @param[out] pAllocationsChanged Array of boolean values that will indicate whether matching allocation in pAllocations array has been moved. This parameter is optional. Pass null if you don't need this information.
  2570. @param pDefragmentationInfo Configuration parameters. Optional - pass null to use default values.
  2571. @param[out] pDefragmentationStats Statistics returned by the function. Optional - pass null if you don't need this information.
  2572. @return `VK_SUCCESS` if completed, negative error code in case of error.
  2573. \deprecated This is a part of the old interface. It is recommended to use structure #VmaDefragmentationInfo2 and function vmaDefragmentationBegin() instead.
  2574. This function works by moving allocations to different places (different
  2575. `VkDeviceMemory` objects and/or different offsets) in order to optimize memory
  2576. usage. Only allocations that are in `pAllocations` array can be moved. All other
  2577. allocations are considered nonmovable in this call. Basic rules:
  2578. - Only allocations made in memory types that have
  2579. `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` and `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT`
  2580. flags can be compacted. You may pass other allocations but it makes no sense -
  2581. these will never be moved.
  2582. - Custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT or
  2583. #VMA_POOL_CREATE_BUDDY_ALGORITHM_BIT flag are not defragmented. Allocations
  2584. passed to this function that come from such pools are ignored.
  2585. - Allocations created with #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT or
  2586. created as dedicated allocations for any other reason are also ignored.
  2587. - Both allocations made with or without #VMA_ALLOCATION_CREATE_MAPPED_BIT
  2588. flag can be compacted. If not persistently mapped, memory will be mapped
  2589. temporarily inside this function if needed.
  2590. - You must not pass same #VmaAllocation object multiple times in `pAllocations` array.
  2591. The function also frees empty `VkDeviceMemory` blocks.
  2592. Warning: This function may be time-consuming, so you shouldn't call it too often
  2593. (like after every resource creation/destruction).
  2594. You can call it on special occasions (like when reloading a game level or
  2595. when you just destroyed a lot of objects). Calling it every frame may be OK, but
  2596. you should measure that on your platform.
  2597. For more information, see [Defragmentation](@ref defragmentation) chapter.
  2598. */
  2599. VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragment(
  2600. VmaAllocator allocator,
  2601. VmaAllocation* pAllocations,
  2602. size_t allocationCount,
  2603. VkBool32* pAllocationsChanged,
  2604. const VmaDefragmentationInfo *pDefragmentationInfo,
  2605. VmaDefragmentationStats* pDefragmentationStats);
  2606. /** \brief Binds buffer to allocation.
  2607. Binds specified buffer to region of memory represented by specified allocation.
  2608. Gets `VkDeviceMemory` handle and offset from the allocation.
  2609. If you want to create a buffer, allocate memory for it and bind them together separately,
  2610. you should use this function for binding instead of standard `vkBindBufferMemory()`,
  2611. because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple
  2612. allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously
  2613. (which is illegal in Vulkan).
  2614. It is recommended to use function vmaCreateBuffer() instead of this one.
  2615. */
  2616. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory(
  2617. VmaAllocator allocator,
  2618. VmaAllocation allocation,
  2619. VkBuffer buffer);
  2620. /** \brief Binds buffer to allocation with additional parameters.
  2621. @param allocationLocalOffset Additional offset to be added while binding, relative to the beginnig of the `allocation`. Normally it should be 0.
  2622. @param pNext A chain of structures to be attached to `VkBindBufferMemoryInfoKHR` structure used internally. Normally it should be null.
  2623. This function is similar to vmaBindBufferMemory(), but it provides additional parameters.
  2624. If `pNext` is not null, #VmaAllocator object must have been created with #VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT flag
  2625. or with VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_1`. Otherwise the call fails.
  2626. */
  2627. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2(
  2628. VmaAllocator allocator,
  2629. VmaAllocation allocation,
  2630. VkDeviceSize allocationLocalOffset,
  2631. VkBuffer buffer,
  2632. const void* pNext);
  2633. /** \brief Binds image to allocation.
  2634. Binds specified image to region of memory represented by specified allocation.
  2635. Gets `VkDeviceMemory` handle and offset from the allocation.
  2636. If you want to create an image, allocate memory for it and bind them together separately,
  2637. you should use this function for binding instead of standard `vkBindImageMemory()`,
  2638. because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple
  2639. allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously
  2640. (which is illegal in Vulkan).
  2641. It is recommended to use function vmaCreateImage() instead of this one.
  2642. */
  2643. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory(
  2644. VmaAllocator allocator,
  2645. VmaAllocation allocation,
  2646. VkImage image);
  2647. /** \brief Binds image to allocation with additional parameters.
  2648. @param allocationLocalOffset Additional offset to be added while binding, relative to the beginnig of the `allocation`. Normally it should be 0.
  2649. @param pNext A chain of structures to be attached to `VkBindImageMemoryInfoKHR` structure used internally. Normally it should be null.
  2650. This function is similar to vmaBindImageMemory(), but it provides additional parameters.
  2651. If `pNext` is not null, #VmaAllocator object must have been created with #VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT flag
  2652. or with VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_1`. Otherwise the call fails.
  2653. */
  2654. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2(
  2655. VmaAllocator allocator,
  2656. VmaAllocation allocation,
  2657. VkDeviceSize allocationLocalOffset,
  2658. VkImage image,
  2659. const void* pNext);
  2660. /**
  2661. @param[out] pBuffer Buffer that was created.
  2662. @param[out] pAllocation Allocation that was created.
  2663. @param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
  2664. This function automatically:
  2665. -# Creates buffer.
  2666. -# Allocates appropriate memory for it.
  2667. -# Binds the buffer with the memory.
  2668. If any of these operations fail, buffer and allocation are not created,
  2669. returned value is negative error code, *pBuffer and *pAllocation are null.
  2670. If the function succeeded, you must destroy both buffer and allocation when you
  2671. no longer need them using either convenience function vmaDestroyBuffer() or
  2672. separately, using `vkDestroyBuffer()` and vmaFreeMemory().
  2673. If VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag was used,
  2674. VK_KHR_dedicated_allocation extension is used internally to query driver whether
  2675. it requires or prefers the new buffer to have dedicated allocation. If yes,
  2676. and if dedicated allocation is possible (VmaAllocationCreateInfo::pool is null
  2677. and VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT is not used), it creates dedicated
  2678. allocation for this buffer, just like when using
  2679. VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  2680. */
  2681. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer(
  2682. VmaAllocator allocator,
  2683. const VkBufferCreateInfo* pBufferCreateInfo,
  2684. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  2685. VkBuffer* pBuffer,
  2686. VmaAllocation* pAllocation,
  2687. VmaAllocationInfo* pAllocationInfo);
  2688. /** \brief Destroys Vulkan buffer and frees allocated memory.
  2689. This is just a convenience function equivalent to:
  2690. \code
  2691. vkDestroyBuffer(device, buffer, allocationCallbacks);
  2692. vmaFreeMemory(allocator, allocation);
  2693. \endcode
  2694. It it safe to pass null as buffer and/or allocation.
  2695. */
  2696. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer(
  2697. VmaAllocator allocator,
  2698. VkBuffer buffer,
  2699. VmaAllocation allocation);
  2700. /// Function similar to vmaCreateBuffer().
  2701. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage(
  2702. VmaAllocator allocator,
  2703. const VkImageCreateInfo* pImageCreateInfo,
  2704. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  2705. VkImage* pImage,
  2706. VmaAllocation* pAllocation,
  2707. VmaAllocationInfo* pAllocationInfo);
  2708. /** \brief Destroys Vulkan image and frees allocated memory.
  2709. This is just a convenience function equivalent to:
  2710. \code
  2711. vkDestroyImage(device, image, allocationCallbacks);
  2712. vmaFreeMemory(allocator, allocation);
  2713. \endcode
  2714. It it safe to pass null as image and/or allocation.
  2715. */
  2716. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyImage(
  2717. VmaAllocator allocator,
  2718. VkImage image,
  2719. VmaAllocation allocation);
  2720. #ifdef __cplusplus
  2721. }
  2722. #endif
  2723. #endif // AMD_VULKAN_MEMORY_ALLOCATOR_H
  2724. // For Visual Studio IntelliSense.
  2725. #if defined(__cplusplus) && defined(__INTELLISENSE__)
  2726. #define VMA_IMPLEMENTATION
  2727. #endif
  2728. #ifdef VMA_IMPLEMENTATION
  2729. #undef VMA_IMPLEMENTATION
  2730. #include <cstdint>
  2731. #include <cstdlib>
  2732. #include <cstring>
  2733. /*******************************************************************************
  2734. CONFIGURATION SECTION
  2735. Define some of these macros before each #include of this header or change them
  2736. here if you need other then default behavior depending on your environment.
  2737. */
  2738. /*
  2739. Define this macro to 1 to make the library fetch pointers to Vulkan functions
  2740. internally, like:
  2741. vulkanFunctions.vkAllocateMemory = &vkAllocateMemory;
  2742. Define to 0 if you are going to provide you own pointers to Vulkan functions via
  2743. VmaAllocatorCreateInfo::pVulkanFunctions.
  2744. */
  2745. #if !defined(VMA_STATIC_VULKAN_FUNCTIONS) && !defined(VK_NO_PROTOTYPES)
  2746. #define VMA_STATIC_VULKAN_FUNCTIONS 1
  2747. #endif
  2748. // Define this macro to 1 to make the library use STL containers instead of its own implementation.
  2749. //#define VMA_USE_STL_CONTAINERS 1
  2750. /* Set this macro to 1 to make the library including and using STL containers:
  2751. std::pair, std::vector, std::list, std::unordered_map.
  2752. Set it to 0 or undefined to make the library using its own implementation of
  2753. the containers.
  2754. */
  2755. #if VMA_USE_STL_CONTAINERS
  2756. #define VMA_USE_STL_VECTOR 1
  2757. #define VMA_USE_STL_UNORDERED_MAP 1
  2758. #define VMA_USE_STL_LIST 1
  2759. #endif
  2760. #ifndef VMA_USE_STL_SHARED_MUTEX
  2761. // Compiler conforms to C++17.
  2762. #if __cplusplus >= 201703L
  2763. #define VMA_USE_STL_SHARED_MUTEX 1
  2764. // Visual studio defines __cplusplus properly only when passed additional parameter: /Zc:__cplusplus
  2765. // Otherwise it's always 199711L, despite shared_mutex works since Visual Studio 2015 Update 2.
  2766. // See: https://blogs.msdn.microsoft.com/vcblog/2018/04/09/msvc-now-correctly-reports-__cplusplus/
  2767. #elif defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 190023918 && __cplusplus == 199711L && _MSVC_LANG >= 201703L
  2768. #define VMA_USE_STL_SHARED_MUTEX 1
  2769. #else
  2770. #define VMA_USE_STL_SHARED_MUTEX 0
  2771. #endif
  2772. #endif
  2773. /*
  2774. THESE INCLUDES ARE NOT ENABLED BY DEFAULT.
  2775. Library has its own container implementation.
  2776. */
  2777. #if VMA_USE_STL_VECTOR
  2778. #include <vector>
  2779. #endif
  2780. #if VMA_USE_STL_UNORDERED_MAP
  2781. #include <unordered_map>
  2782. #endif
  2783. #if VMA_USE_STL_LIST
  2784. #include <list>
  2785. #endif
  2786. /*
  2787. Following headers are used in this CONFIGURATION section only, so feel free to
  2788. remove them if not needed.
  2789. */
  2790. #include <cassert> // for assert
  2791. #include <algorithm> // for min, max
  2792. #include <mutex>
  2793. #ifndef VMA_NULL
  2794. // Value used as null pointer. Define it to e.g.: nullptr, NULL, 0, (void*)0.
  2795. #define VMA_NULL nullptr
  2796. #endif
  2797. #if defined(__ANDROID_API__) && (__ANDROID_API__ < 16)
  2798. #include <cstdlib>
  2799. void *aligned_alloc(size_t alignment, size_t size)
  2800. {
  2801. // alignment must be >= sizeof(void*)
  2802. if(alignment < sizeof(void*))
  2803. {
  2804. alignment = sizeof(void*);
  2805. }
  2806. return memalign(alignment, size);
  2807. }
  2808. #elif defined(__APPLE__) || defined(__ANDROID__) || (defined(__linux__) && defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC))
  2809. #include <cstdlib>
  2810. void *aligned_alloc(size_t alignment, size_t size)
  2811. {
  2812. // alignment must be >= sizeof(void*)
  2813. if(alignment < sizeof(void*))
  2814. {
  2815. alignment = sizeof(void*);
  2816. }
  2817. void *pointer;
  2818. if(posix_memalign(&pointer, alignment, size) == 0)
  2819. return pointer;
  2820. return VMA_NULL;
  2821. }
  2822. #endif
  2823. // If your compiler is not compatible with C++11 and definition of
  2824. // aligned_alloc() function is missing, uncommeting following line may help:
  2825. //#include <malloc.h>
  2826. // Normal assert to check for programmer's errors, especially in Debug configuration.
  2827. #ifndef VMA_ASSERT
  2828. #ifdef _DEBUG
  2829. #define VMA_ASSERT(expr) assert(expr)
  2830. #else
  2831. #define VMA_ASSERT(expr)
  2832. #endif
  2833. #endif
  2834. // Assert that will be called very often, like inside data structures e.g. operator[].
  2835. // Making it non-empty can make program slow.
  2836. #ifndef VMA_HEAVY_ASSERT
  2837. #ifdef _DEBUG
  2838. #define VMA_HEAVY_ASSERT(expr) //VMA_ASSERT(expr)
  2839. #else
  2840. #define VMA_HEAVY_ASSERT(expr)
  2841. #endif
  2842. #endif
  2843. #ifndef VMA_ALIGN_OF
  2844. #define VMA_ALIGN_OF(type) (__alignof(type))
  2845. #endif
  2846. #ifndef VMA_SYSTEM_ALIGNED_MALLOC
  2847. #if defined(_WIN32)
  2848. #define VMA_SYSTEM_ALIGNED_MALLOC(size, alignment) (_aligned_malloc((size), (alignment)))
  2849. #else
  2850. #define VMA_SYSTEM_ALIGNED_MALLOC(size, alignment) (aligned_alloc((alignment), (size) ))
  2851. #endif
  2852. #endif
  2853. #ifndef VMA_SYSTEM_FREE
  2854. #if defined(_WIN32)
  2855. #define VMA_SYSTEM_FREE(ptr) _aligned_free(ptr)
  2856. #else
  2857. #define VMA_SYSTEM_FREE(ptr) free(ptr)
  2858. #endif
  2859. #endif
  2860. #ifndef VMA_MIN
  2861. #define VMA_MIN(v1, v2) (std::min((v1), (v2)))
  2862. #endif
  2863. #ifndef VMA_MAX
  2864. #define VMA_MAX(v1, v2) (std::max((v1), (v2)))
  2865. #endif
  2866. #ifndef VMA_SWAP
  2867. #define VMA_SWAP(v1, v2) std::swap((v1), (v2))
  2868. #endif
  2869. #ifndef VMA_SORT
  2870. #define VMA_SORT(beg, end, cmp) std::sort(beg, end, cmp)
  2871. #endif
  2872. #ifndef VMA_DEBUG_LOG
  2873. #define VMA_DEBUG_LOG(format, ...)
  2874. /*
  2875. #define VMA_DEBUG_LOG(format, ...) do { \
  2876. printf(format, __VA_ARGS__); \
  2877. printf("\n"); \
  2878. } while(false)
  2879. */
  2880. #endif
  2881. // Define this macro to 1 to enable functions: vmaBuildStatsString, vmaFreeStatsString.
  2882. #if VMA_STATS_STRING_ENABLED
  2883. static inline void VmaUint32ToStr(char* outStr, size_t strLen, uint32_t num)
  2884. {
  2885. snprintf(outStr, strLen, "%u", static_cast<unsigned int>(num));
  2886. }
  2887. static inline void VmaUint64ToStr(char* outStr, size_t strLen, uint64_t num)
  2888. {
  2889. snprintf(outStr, strLen, "%llu", static_cast<unsigned long long>(num));
  2890. }
  2891. static inline void VmaPtrToStr(char* outStr, size_t strLen, const void* ptr)
  2892. {
  2893. snprintf(outStr, strLen, "%p", ptr);
  2894. }
  2895. #endif
  2896. #ifndef VMA_MUTEX
  2897. class VmaMutex
  2898. {
  2899. public:
  2900. void Lock() { m_Mutex.lock(); }
  2901. void Unlock() { m_Mutex.unlock(); }
  2902. private:
  2903. std::mutex m_Mutex;
  2904. };
  2905. #define VMA_MUTEX VmaMutex
  2906. #endif
  2907. // Read-write mutex, where "read" is shared access, "write" is exclusive access.
  2908. #ifndef VMA_RW_MUTEX
  2909. #if VMA_USE_STL_SHARED_MUTEX
  2910. // Use std::shared_mutex from C++17.
  2911. #include <shared_mutex>
  2912. class VmaRWMutex
  2913. {
  2914. public:
  2915. void LockRead() { m_Mutex.lock_shared(); }
  2916. void UnlockRead() { m_Mutex.unlock_shared(); }
  2917. void LockWrite() { m_Mutex.lock(); }
  2918. void UnlockWrite() { m_Mutex.unlock(); }
  2919. private:
  2920. std::shared_mutex m_Mutex;
  2921. };
  2922. #define VMA_RW_MUTEX VmaRWMutex
  2923. #elif defined(_WIN32) && defined(WINVER) && WINVER >= 0x0600
  2924. // Use SRWLOCK from WinAPI.
  2925. // Minimum supported client = Windows Vista, server = Windows Server 2008.
  2926. class VmaRWMutex
  2927. {
  2928. public:
  2929. VmaRWMutex() { InitializeSRWLock(&m_Lock); }
  2930. void LockRead() { AcquireSRWLockShared(&m_Lock); }
  2931. void UnlockRead() { ReleaseSRWLockShared(&m_Lock); }
  2932. void LockWrite() { AcquireSRWLockExclusive(&m_Lock); }
  2933. void UnlockWrite() { ReleaseSRWLockExclusive(&m_Lock); }
  2934. private:
  2935. SRWLOCK m_Lock;
  2936. };
  2937. #define VMA_RW_MUTEX VmaRWMutex
  2938. #else
  2939. // Less efficient fallback: Use normal mutex.
  2940. class VmaRWMutex
  2941. {
  2942. public:
  2943. void LockRead() { m_Mutex.Lock(); }
  2944. void UnlockRead() { m_Mutex.Unlock(); }
  2945. void LockWrite() { m_Mutex.Lock(); }
  2946. void UnlockWrite() { m_Mutex.Unlock(); }
  2947. private:
  2948. VMA_MUTEX m_Mutex;
  2949. };
  2950. #define VMA_RW_MUTEX VmaRWMutex
  2951. #endif // #if VMA_USE_STL_SHARED_MUTEX
  2952. #endif // #ifndef VMA_RW_MUTEX
  2953. /*
  2954. If providing your own implementation, you need to implement a subset of std::atomic.
  2955. */
  2956. #ifndef VMA_ATOMIC_UINT32
  2957. #include <atomic>
  2958. #define VMA_ATOMIC_UINT32 std::atomic<uint32_t>
  2959. #endif
  2960. #ifndef VMA_ATOMIC_UINT64
  2961. #include <atomic>
  2962. #define VMA_ATOMIC_UINT64 std::atomic<uint64_t>
  2963. #endif
  2964. #ifndef VMA_DEBUG_ALWAYS_DEDICATED_MEMORY
  2965. /**
  2966. Every allocation will have its own memory block.
  2967. Define to 1 for debugging purposes only.
  2968. */
  2969. #define VMA_DEBUG_ALWAYS_DEDICATED_MEMORY (0)
  2970. #endif
  2971. #ifndef VMA_DEBUG_ALIGNMENT
  2972. /**
  2973. Minimum alignment of all allocations, in bytes.
  2974. Set to more than 1 for debugging purposes only. Must be power of two.
  2975. */
  2976. #define VMA_DEBUG_ALIGNMENT (1)
  2977. #endif
  2978. #ifndef VMA_DEBUG_MARGIN
  2979. /**
  2980. Minimum margin before and after every allocation, in bytes.
  2981. Set nonzero for debugging purposes only.
  2982. */
  2983. #define VMA_DEBUG_MARGIN (0)
  2984. #endif
  2985. #ifndef VMA_DEBUG_INITIALIZE_ALLOCATIONS
  2986. /**
  2987. Define this macro to 1 to automatically fill new allocations and destroyed
  2988. allocations with some bit pattern.
  2989. */
  2990. #define VMA_DEBUG_INITIALIZE_ALLOCATIONS (0)
  2991. #endif
  2992. #ifndef VMA_DEBUG_DETECT_CORRUPTION
  2993. /**
  2994. Define this macro to 1 together with non-zero value of VMA_DEBUG_MARGIN to
  2995. enable writing magic value to the margin before and after every allocation and
  2996. validating it, so that memory corruptions (out-of-bounds writes) are detected.
  2997. */
  2998. #define VMA_DEBUG_DETECT_CORRUPTION (0)
  2999. #endif
  3000. #ifndef VMA_DEBUG_GLOBAL_MUTEX
  3001. /**
  3002. Set this to 1 for debugging purposes only, to enable single mutex protecting all
  3003. entry calls to the library. Can be useful for debugging multithreading issues.
  3004. */
  3005. #define VMA_DEBUG_GLOBAL_MUTEX (0)
  3006. #endif
  3007. #ifndef VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY
  3008. /**
  3009. Minimum value for VkPhysicalDeviceLimits::bufferImageGranularity.
  3010. Set to more than 1 for debugging purposes only. Must be power of two.
  3011. */
  3012. #define VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY (1)
  3013. #endif
  3014. #ifndef VMA_SMALL_HEAP_MAX_SIZE
  3015. /// Maximum size of a memory heap in Vulkan to consider it "small".
  3016. #define VMA_SMALL_HEAP_MAX_SIZE (1024ull * 1024 * 1024)
  3017. #endif
  3018. #ifndef VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE
  3019. /// Default size of a block allocated as single VkDeviceMemory from a "large" heap.
  3020. #define VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE (256ull * 1024 * 1024)
  3021. #endif
  3022. #ifndef VMA_CLASS_NO_COPY
  3023. #define VMA_CLASS_NO_COPY(className) \
  3024. private: \
  3025. className(const className&) = delete; \
  3026. className& operator=(const className&) = delete;
  3027. #endif
  3028. static const uint32_t VMA_FRAME_INDEX_LOST = UINT32_MAX;
  3029. // Decimal 2139416166, float NaN, little-endian binary 66 E6 84 7F.
  3030. static const uint32_t VMA_CORRUPTION_DETECTION_MAGIC_VALUE = 0x7F84E666;
  3031. static const uint8_t VMA_ALLOCATION_FILL_PATTERN_CREATED = 0xDC;
  3032. static const uint8_t VMA_ALLOCATION_FILL_PATTERN_DESTROYED = 0xEF;
  3033. /*******************************************************************************
  3034. END OF CONFIGURATION
  3035. */
  3036. static const uint32_t VMA_ALLOCATION_INTERNAL_STRATEGY_MIN_OFFSET = 0x10000000u;
  3037. static VkAllocationCallbacks VmaEmptyAllocationCallbacks = {
  3038. VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL };
  3039. // Returns number of bits set to 1 in (v).
  3040. static inline uint32_t VmaCountBitsSet(uint32_t v)
  3041. {
  3042. uint32_t c = v - ((v >> 1) & 0x55555555);
  3043. c = ((c >> 2) & 0x33333333) + (c & 0x33333333);
  3044. c = ((c >> 4) + c) & 0x0F0F0F0F;
  3045. c = ((c >> 8) + c) & 0x00FF00FF;
  3046. c = ((c >> 16) + c) & 0x0000FFFF;
  3047. return c;
  3048. }
  3049. // Aligns given value up to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 16.
  3050. // Use types like uint32_t, uint64_t as T.
  3051. template <typename T>
  3052. static inline T VmaAlignUp(T val, T align)
  3053. {
  3054. return (val + align - 1) / align * align;
  3055. }
  3056. // Aligns given value down to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 8.
  3057. // Use types like uint32_t, uint64_t as T.
  3058. template <typename T>
  3059. static inline T VmaAlignDown(T val, T align)
  3060. {
  3061. return val / align * align;
  3062. }
  3063. // Division with mathematical rounding to nearest number.
  3064. template <typename T>
  3065. static inline T VmaRoundDiv(T x, T y)
  3066. {
  3067. return (x + (y / (T)2)) / y;
  3068. }
  3069. /*
  3070. Returns true if given number is a power of two.
  3071. T must be unsigned integer number or signed integer but always nonnegative.
  3072. For 0 returns true.
  3073. */
  3074. template <typename T>
  3075. inline bool VmaIsPow2(T x)
  3076. {
  3077. return (x & (x-1)) == 0;
  3078. }
  3079. // Returns smallest power of 2 greater or equal to v.
  3080. static inline uint32_t VmaNextPow2(uint32_t v)
  3081. {
  3082. v--;
  3083. v |= v >> 1;
  3084. v |= v >> 2;
  3085. v |= v >> 4;
  3086. v |= v >> 8;
  3087. v |= v >> 16;
  3088. v++;
  3089. return v;
  3090. }
  3091. static inline uint64_t VmaNextPow2(uint64_t v)
  3092. {
  3093. v--;
  3094. v |= v >> 1;
  3095. v |= v >> 2;
  3096. v |= v >> 4;
  3097. v |= v >> 8;
  3098. v |= v >> 16;
  3099. v |= v >> 32;
  3100. v++;
  3101. return v;
  3102. }
  3103. // Returns largest power of 2 less or equal to v.
  3104. static inline uint32_t VmaPrevPow2(uint32_t v)
  3105. {
  3106. v |= v >> 1;
  3107. v |= v >> 2;
  3108. v |= v >> 4;
  3109. v |= v >> 8;
  3110. v |= v >> 16;
  3111. v = v ^ (v >> 1);
  3112. return v;
  3113. }
  3114. static inline uint64_t VmaPrevPow2(uint64_t v)
  3115. {
  3116. v |= v >> 1;
  3117. v |= v >> 2;
  3118. v |= v >> 4;
  3119. v |= v >> 8;
  3120. v |= v >> 16;
  3121. v |= v >> 32;
  3122. v = v ^ (v >> 1);
  3123. return v;
  3124. }
  3125. static inline bool VmaStrIsEmpty(const char* pStr)
  3126. {
  3127. return pStr == VMA_NULL || *pStr == '\0';
  3128. }
  3129. #if VMA_STATS_STRING_ENABLED
  3130. static const char* VmaAlgorithmToStr(uint32_t algorithm)
  3131. {
  3132. switch(algorithm)
  3133. {
  3134. case VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT:
  3135. return "Linear";
  3136. case VMA_POOL_CREATE_BUDDY_ALGORITHM_BIT:
  3137. return "Buddy";
  3138. case 0:
  3139. return "Default";
  3140. default:
  3141. VMA_ASSERT(0);
  3142. return "";
  3143. }
  3144. }
  3145. #endif // #if VMA_STATS_STRING_ENABLED
  3146. #ifndef VMA_SORT
  3147. template<typename Iterator, typename Compare>
  3148. Iterator VmaQuickSortPartition(Iterator beg, Iterator end, Compare cmp)
  3149. {
  3150. Iterator centerValue = end; --centerValue;
  3151. Iterator insertIndex = beg;
  3152. for(Iterator memTypeIndex = beg; memTypeIndex < centerValue; ++memTypeIndex)
  3153. {
  3154. if(cmp(*memTypeIndex, *centerValue))
  3155. {
  3156. if(insertIndex != memTypeIndex)
  3157. {
  3158. VMA_SWAP(*memTypeIndex, *insertIndex);
  3159. }
  3160. ++insertIndex;
  3161. }
  3162. }
  3163. if(insertIndex != centerValue)
  3164. {
  3165. VMA_SWAP(*insertIndex, *centerValue);
  3166. }
  3167. return insertIndex;
  3168. }
  3169. template<typename Iterator, typename Compare>
  3170. void VmaQuickSort(Iterator beg, Iterator end, Compare cmp)
  3171. {
  3172. if(beg < end)
  3173. {
  3174. Iterator it = VmaQuickSortPartition<Iterator, Compare>(beg, end, cmp);
  3175. VmaQuickSort<Iterator, Compare>(beg, it, cmp);
  3176. VmaQuickSort<Iterator, Compare>(it + 1, end, cmp);
  3177. }
  3178. }
  3179. #define VMA_SORT(beg, end, cmp) VmaQuickSort(beg, end, cmp)
  3180. #endif // #ifndef VMA_SORT
  3181. /*
  3182. Returns true if two memory blocks occupy overlapping pages.
  3183. ResourceA must be in less memory offset than ResourceB.
  3184. Algorithm is based on "Vulkan 1.0.39 - A Specification (with all registered Vulkan extensions)"
  3185. chapter 11.6 "Resource Memory Association", paragraph "Buffer-Image Granularity".
  3186. */
  3187. static inline bool VmaBlocksOnSamePage(
  3188. VkDeviceSize resourceAOffset,
  3189. VkDeviceSize resourceASize,
  3190. VkDeviceSize resourceBOffset,
  3191. VkDeviceSize pageSize)
  3192. {
  3193. VMA_ASSERT(resourceAOffset + resourceASize <= resourceBOffset && resourceASize > 0 && pageSize > 0);
  3194. VkDeviceSize resourceAEnd = resourceAOffset + resourceASize - 1;
  3195. VkDeviceSize resourceAEndPage = resourceAEnd & ~(pageSize - 1);
  3196. VkDeviceSize resourceBStart = resourceBOffset;
  3197. VkDeviceSize resourceBStartPage = resourceBStart & ~(pageSize - 1);
  3198. return resourceAEndPage == resourceBStartPage;
  3199. }
  3200. enum VmaSuballocationType
  3201. {
  3202. VMA_SUBALLOCATION_TYPE_FREE = 0,
  3203. VMA_SUBALLOCATION_TYPE_UNKNOWN = 1,
  3204. VMA_SUBALLOCATION_TYPE_BUFFER = 2,
  3205. VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN = 3,
  3206. VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR = 4,
  3207. VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL = 5,
  3208. VMA_SUBALLOCATION_TYPE_MAX_ENUM = 0x7FFFFFFF
  3209. };
  3210. /*
  3211. Returns true if given suballocation types could conflict and must respect
  3212. VkPhysicalDeviceLimits::bufferImageGranularity. They conflict if one is buffer
  3213. or linear image and another one is optimal image. If type is unknown, behave
  3214. conservatively.
  3215. */
  3216. static inline bool VmaIsBufferImageGranularityConflict(
  3217. VmaSuballocationType suballocType1,
  3218. VmaSuballocationType suballocType2)
  3219. {
  3220. if(suballocType1 > suballocType2)
  3221. {
  3222. VMA_SWAP(suballocType1, suballocType2);
  3223. }
  3224. switch(suballocType1)
  3225. {
  3226. case VMA_SUBALLOCATION_TYPE_FREE:
  3227. return false;
  3228. case VMA_SUBALLOCATION_TYPE_UNKNOWN:
  3229. return true;
  3230. case VMA_SUBALLOCATION_TYPE_BUFFER:
  3231. return
  3232. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
  3233. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
  3234. case VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN:
  3235. return
  3236. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
  3237. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR ||
  3238. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
  3239. case VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR:
  3240. return
  3241. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
  3242. case VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL:
  3243. return false;
  3244. default:
  3245. VMA_ASSERT(0);
  3246. return true;
  3247. }
  3248. }
  3249. static void VmaWriteMagicValue(void* pData, VkDeviceSize offset)
  3250. {
  3251. #if VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_DETECT_CORRUPTION
  3252. uint32_t* pDst = (uint32_t*)((char*)pData + offset);
  3253. const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t);
  3254. for(size_t i = 0; i < numberCount; ++i, ++pDst)
  3255. {
  3256. *pDst = VMA_CORRUPTION_DETECTION_MAGIC_VALUE;
  3257. }
  3258. #else
  3259. // no-op
  3260. #endif
  3261. }
  3262. static bool VmaValidateMagicValue(const void* pData, VkDeviceSize offset)
  3263. {
  3264. #if VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_DETECT_CORRUPTION
  3265. const uint32_t* pSrc = (const uint32_t*)((const char*)pData + offset);
  3266. const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t);
  3267. for(size_t i = 0; i < numberCount; ++i, ++pSrc)
  3268. {
  3269. if(*pSrc != VMA_CORRUPTION_DETECTION_MAGIC_VALUE)
  3270. {
  3271. return false;
  3272. }
  3273. }
  3274. #endif
  3275. return true;
  3276. }
  3277. /*
  3278. Fills structure with parameters of an example buffer to be used for transfers
  3279. during GPU memory defragmentation.
  3280. */
  3281. static void VmaFillGpuDefragmentationBufferCreateInfo(VkBufferCreateInfo& outBufCreateInfo)
  3282. {
  3283. memset(&outBufCreateInfo, 0, sizeof(outBufCreateInfo));
  3284. outBufCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  3285. outBufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  3286. outBufCreateInfo.size = (VkDeviceSize)VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE; // Example size.
  3287. }
  3288. // Helper RAII class to lock a mutex in constructor and unlock it in destructor (at the end of scope).
  3289. struct VmaMutexLock
  3290. {
  3291. VMA_CLASS_NO_COPY(VmaMutexLock)
  3292. public:
  3293. VmaMutexLock(VMA_MUTEX& mutex, bool useMutex = true) :
  3294. m_pMutex(useMutex ? &mutex : VMA_NULL)
  3295. { if(m_pMutex) { m_pMutex->Lock(); } }
  3296. ~VmaMutexLock()
  3297. { if(m_pMutex) { m_pMutex->Unlock(); } }
  3298. private:
  3299. VMA_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 reading.
  3302. struct VmaMutexLockRead
  3303. {
  3304. VMA_CLASS_NO_COPY(VmaMutexLockRead)
  3305. public:
  3306. VmaMutexLockRead(VMA_RW_MUTEX& mutex, bool useMutex) :
  3307. m_pMutex(useMutex ? &mutex : VMA_NULL)
  3308. { if(m_pMutex) { m_pMutex->LockRead(); } }
  3309. ~VmaMutexLockRead() { if(m_pMutex) { m_pMutex->UnlockRead(); } }
  3310. private:
  3311. VMA_RW_MUTEX* m_pMutex;
  3312. };
  3313. // Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for writing.
  3314. struct VmaMutexLockWrite
  3315. {
  3316. VMA_CLASS_NO_COPY(VmaMutexLockWrite)
  3317. public:
  3318. VmaMutexLockWrite(VMA_RW_MUTEX& mutex, bool useMutex) :
  3319. m_pMutex(useMutex ? &mutex : VMA_NULL)
  3320. { if(m_pMutex) { m_pMutex->LockWrite(); } }
  3321. ~VmaMutexLockWrite() { if(m_pMutex) { m_pMutex->UnlockWrite(); } }
  3322. private:
  3323. VMA_RW_MUTEX* m_pMutex;
  3324. };
  3325. #if VMA_DEBUG_GLOBAL_MUTEX
  3326. static VMA_MUTEX gDebugGlobalMutex;
  3327. #define VMA_DEBUG_GLOBAL_MUTEX_LOCK VmaMutexLock debugGlobalMutexLock(gDebugGlobalMutex, true);
  3328. #else
  3329. #define VMA_DEBUG_GLOBAL_MUTEX_LOCK
  3330. #endif
  3331. // Minimum size of a free suballocation to register it in the free suballocation collection.
  3332. static const VkDeviceSize VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER = 16;
  3333. /*
  3334. Performs binary search and returns iterator to first element that is greater or
  3335. equal to (key), according to comparison (cmp).
  3336. Cmp should return true if first argument is less than second argument.
  3337. Returned value is the found element, if present in the collection or place where
  3338. new element with value (key) should be inserted.
  3339. */
  3340. template <typename CmpLess, typename IterT, typename KeyT>
  3341. static IterT VmaBinaryFindFirstNotLess(IterT beg, IterT end, const KeyT &key, const CmpLess& cmp)
  3342. {
  3343. size_t down = 0, up = (end - beg);
  3344. while(down < up)
  3345. {
  3346. const size_t mid = (down + up) / 2;
  3347. if(cmp(*(beg+mid), key))
  3348. {
  3349. down = mid + 1;
  3350. }
  3351. else
  3352. {
  3353. up = mid;
  3354. }
  3355. }
  3356. return beg + down;
  3357. }
  3358. template<typename CmpLess, typename IterT, typename KeyT>
  3359. IterT VmaBinaryFindSorted(const IterT& beg, const IterT& end, const KeyT& value, const CmpLess& cmp)
  3360. {
  3361. IterT it = VmaBinaryFindFirstNotLess<CmpLess, IterT, KeyT>(
  3362. beg, end, value, cmp);
  3363. if(it == end ||
  3364. (!cmp(*it, value) && !cmp(value, *it)))
  3365. {
  3366. return it;
  3367. }
  3368. return end;
  3369. }
  3370. /*
  3371. Returns true if all pointers in the array are not-null and unique.
  3372. Warning! O(n^2) complexity. Use only inside VMA_HEAVY_ASSERT.
  3373. T must be pointer type, e.g. VmaAllocation, VmaPool.
  3374. */
  3375. template<typename T>
  3376. static bool VmaValidatePointerArray(uint32_t count, const T* arr)
  3377. {
  3378. for(uint32_t i = 0; i < count; ++i)
  3379. {
  3380. const T iPtr = arr[i];
  3381. if(iPtr == VMA_NULL)
  3382. {
  3383. return false;
  3384. }
  3385. for(uint32_t j = i + 1; j < count; ++j)
  3386. {
  3387. if(iPtr == arr[j])
  3388. {
  3389. return false;
  3390. }
  3391. }
  3392. }
  3393. return true;
  3394. }
  3395. ////////////////////////////////////////////////////////////////////////////////
  3396. // Memory allocation
  3397. static void* VmaMalloc(const VkAllocationCallbacks* pAllocationCallbacks, size_t size, size_t alignment)
  3398. {
  3399. if((pAllocationCallbacks != VMA_NULL) &&
  3400. (pAllocationCallbacks->pfnAllocation != VMA_NULL))
  3401. {
  3402. return (*pAllocationCallbacks->pfnAllocation)(
  3403. pAllocationCallbacks->pUserData,
  3404. size,
  3405. alignment,
  3406. VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
  3407. }
  3408. else
  3409. {
  3410. return VMA_SYSTEM_ALIGNED_MALLOC(size, alignment);
  3411. }
  3412. }
  3413. static void VmaFree(const VkAllocationCallbacks* pAllocationCallbacks, void* ptr)
  3414. {
  3415. if((pAllocationCallbacks != VMA_NULL) &&
  3416. (pAllocationCallbacks->pfnFree != VMA_NULL))
  3417. {
  3418. (*pAllocationCallbacks->pfnFree)(pAllocationCallbacks->pUserData, ptr);
  3419. }
  3420. else
  3421. {
  3422. VMA_SYSTEM_FREE(ptr);
  3423. }
  3424. }
  3425. template<typename T>
  3426. static T* VmaAllocate(const VkAllocationCallbacks* pAllocationCallbacks)
  3427. {
  3428. return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T), VMA_ALIGN_OF(T));
  3429. }
  3430. template<typename T>
  3431. static T* VmaAllocateArray(const VkAllocationCallbacks* pAllocationCallbacks, size_t count)
  3432. {
  3433. return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T) * count, VMA_ALIGN_OF(T));
  3434. }
  3435. #define vma_new(allocator, type) new(VmaAllocate<type>(allocator))(type)
  3436. #define vma_new_array(allocator, type, count) new(VmaAllocateArray<type>((allocator), (count)))(type)
  3437. template<typename T>
  3438. static void vma_delete(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr)
  3439. {
  3440. ptr->~T();
  3441. VmaFree(pAllocationCallbacks, ptr);
  3442. }
  3443. template<typename T>
  3444. static void vma_delete_array(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr, size_t count)
  3445. {
  3446. if(ptr != VMA_NULL)
  3447. {
  3448. for(size_t i = count; i--; )
  3449. {
  3450. ptr[i].~T();
  3451. }
  3452. VmaFree(pAllocationCallbacks, ptr);
  3453. }
  3454. }
  3455. static char* VmaCreateStringCopy(const VkAllocationCallbacks* allocs, const char* srcStr)
  3456. {
  3457. if(srcStr != VMA_NULL)
  3458. {
  3459. const size_t len = strlen(srcStr);
  3460. char* const result = vma_new_array(allocs, char, len + 1);
  3461. memcpy(result, srcStr, len + 1);
  3462. return result;
  3463. }
  3464. else
  3465. {
  3466. return VMA_NULL;
  3467. }
  3468. }
  3469. static void VmaFreeString(const VkAllocationCallbacks* allocs, char* str)
  3470. {
  3471. if(str != VMA_NULL)
  3472. {
  3473. const size_t len = strlen(str);
  3474. vma_delete_array(allocs, str, len + 1);
  3475. }
  3476. }
  3477. // STL-compatible allocator.
  3478. template<typename T>
  3479. class VmaStlAllocator
  3480. {
  3481. public:
  3482. const VkAllocationCallbacks* const m_pCallbacks;
  3483. typedef T value_type;
  3484. VmaStlAllocator(const VkAllocationCallbacks* pCallbacks) : m_pCallbacks(pCallbacks) { }
  3485. template<typename U> VmaStlAllocator(const VmaStlAllocator<U>& src) : m_pCallbacks(src.m_pCallbacks) { }
  3486. T* allocate(size_t n) { return VmaAllocateArray<T>(m_pCallbacks, n); }
  3487. void deallocate(T* p, size_t n) { VmaFree(m_pCallbacks, p); }
  3488. template<typename U>
  3489. bool operator==(const VmaStlAllocator<U>& rhs) const
  3490. {
  3491. return m_pCallbacks == rhs.m_pCallbacks;
  3492. }
  3493. template<typename U>
  3494. bool operator!=(const VmaStlAllocator<U>& rhs) const
  3495. {
  3496. return m_pCallbacks != rhs.m_pCallbacks;
  3497. }
  3498. VmaStlAllocator& operator=(const VmaStlAllocator& x) = delete;
  3499. };
  3500. #if VMA_USE_STL_VECTOR
  3501. #define VmaVector std::vector
  3502. template<typename T, typename allocatorT>
  3503. static void VmaVectorInsert(std::vector<T, allocatorT>& vec, size_t index, const T& item)
  3504. {
  3505. vec.insert(vec.begin() + index, item);
  3506. }
  3507. template<typename T, typename allocatorT>
  3508. static void VmaVectorRemove(std::vector<T, allocatorT>& vec, size_t index)
  3509. {
  3510. vec.erase(vec.begin() + index);
  3511. }
  3512. #else // #if VMA_USE_STL_VECTOR
  3513. /* Class with interface compatible with subset of std::vector.
  3514. T must be POD because constructors and destructors are not called and memcpy is
  3515. used for these objects. */
  3516. template<typename T, typename AllocatorT>
  3517. class VmaVector
  3518. {
  3519. public:
  3520. typedef T value_type;
  3521. VmaVector(const AllocatorT& allocator) :
  3522. m_Allocator(allocator),
  3523. m_pArray(VMA_NULL),
  3524. m_Count(0),
  3525. m_Capacity(0)
  3526. {
  3527. }
  3528. VmaVector(size_t count, const AllocatorT& allocator) :
  3529. m_Allocator(allocator),
  3530. m_pArray(count ? (T*)VmaAllocateArray<T>(allocator.m_pCallbacks, count) : VMA_NULL),
  3531. m_Count(count),
  3532. m_Capacity(count)
  3533. {
  3534. }
  3535. // This version of the constructor is here for compatibility with pre-C++14 std::vector.
  3536. // value is unused.
  3537. VmaVector(size_t count, const T& value, const AllocatorT& allocator)
  3538. : VmaVector(count, allocator) {}
  3539. VmaVector(const VmaVector<T, AllocatorT>& src) :
  3540. m_Allocator(src.m_Allocator),
  3541. m_pArray(src.m_Count ? (T*)VmaAllocateArray<T>(src.m_Allocator.m_pCallbacks, src.m_Count) : VMA_NULL),
  3542. m_Count(src.m_Count),
  3543. m_Capacity(src.m_Count)
  3544. {
  3545. if(m_Count != 0)
  3546. {
  3547. memcpy(m_pArray, src.m_pArray, m_Count * sizeof(T));
  3548. }
  3549. }
  3550. ~VmaVector()
  3551. {
  3552. VmaFree(m_Allocator.m_pCallbacks, m_pArray);
  3553. }
  3554. VmaVector& operator=(const VmaVector<T, AllocatorT>& rhs)
  3555. {
  3556. if(&rhs != this)
  3557. {
  3558. resize(rhs.m_Count);
  3559. if(m_Count != 0)
  3560. {
  3561. memcpy(m_pArray, rhs.m_pArray, m_Count * sizeof(T));
  3562. }
  3563. }
  3564. return *this;
  3565. }
  3566. bool empty() const { return m_Count == 0; }
  3567. size_t size() const { return m_Count; }
  3568. T* data() { return m_pArray; }
  3569. const T* data() const { return m_pArray; }
  3570. T& operator[](size_t index)
  3571. {
  3572. VMA_HEAVY_ASSERT(index < m_Count);
  3573. return m_pArray[index];
  3574. }
  3575. const T& operator[](size_t index) const
  3576. {
  3577. VMA_HEAVY_ASSERT(index < m_Count);
  3578. return m_pArray[index];
  3579. }
  3580. T& front()
  3581. {
  3582. VMA_HEAVY_ASSERT(m_Count > 0);
  3583. return m_pArray[0];
  3584. }
  3585. const T& front() const
  3586. {
  3587. VMA_HEAVY_ASSERT(m_Count > 0);
  3588. return m_pArray[0];
  3589. }
  3590. T& back()
  3591. {
  3592. VMA_HEAVY_ASSERT(m_Count > 0);
  3593. return m_pArray[m_Count - 1];
  3594. }
  3595. const T& back() const
  3596. {
  3597. VMA_HEAVY_ASSERT(m_Count > 0);
  3598. return m_pArray[m_Count - 1];
  3599. }
  3600. void reserve(size_t newCapacity, bool freeMemory = false)
  3601. {
  3602. newCapacity = VMA_MAX(newCapacity, m_Count);
  3603. if((newCapacity < m_Capacity) && !freeMemory)
  3604. {
  3605. newCapacity = m_Capacity;
  3606. }
  3607. if(newCapacity != m_Capacity)
  3608. {
  3609. T* const newArray = newCapacity ? VmaAllocateArray<T>(m_Allocator, newCapacity) : VMA_NULL;
  3610. if(m_Count != 0)
  3611. {
  3612. memcpy(newArray, m_pArray, m_Count * sizeof(T));
  3613. }
  3614. VmaFree(m_Allocator.m_pCallbacks, m_pArray);
  3615. m_Capacity = newCapacity;
  3616. m_pArray = newArray;
  3617. }
  3618. }
  3619. void resize(size_t newCount, bool freeMemory = false)
  3620. {
  3621. size_t newCapacity = m_Capacity;
  3622. if(newCount > m_Capacity)
  3623. {
  3624. newCapacity = VMA_MAX(newCount, VMA_MAX(m_Capacity * 3 / 2, (size_t)8));
  3625. }
  3626. else if(freeMemory)
  3627. {
  3628. newCapacity = newCount;
  3629. }
  3630. if(newCapacity != m_Capacity)
  3631. {
  3632. T* const newArray = newCapacity ? VmaAllocateArray<T>(m_Allocator.m_pCallbacks, newCapacity) : VMA_NULL;
  3633. const size_t elementsToCopy = VMA_MIN(m_Count, newCount);
  3634. if(elementsToCopy != 0)
  3635. {
  3636. memcpy(newArray, m_pArray, elementsToCopy * sizeof(T));
  3637. }
  3638. VmaFree(m_Allocator.m_pCallbacks, m_pArray);
  3639. m_Capacity = newCapacity;
  3640. m_pArray = newArray;
  3641. }
  3642. m_Count = newCount;
  3643. }
  3644. void clear(bool freeMemory = false)
  3645. {
  3646. resize(0, freeMemory);
  3647. }
  3648. void insert(size_t index, const T& src)
  3649. {
  3650. VMA_HEAVY_ASSERT(index <= m_Count);
  3651. const size_t oldCount = size();
  3652. resize(oldCount + 1);
  3653. if(index < oldCount)
  3654. {
  3655. memmove(m_pArray + (index + 1), m_pArray + index, (oldCount - index) * sizeof(T));
  3656. }
  3657. m_pArray[index] = src;
  3658. }
  3659. void remove(size_t index)
  3660. {
  3661. VMA_HEAVY_ASSERT(index < m_Count);
  3662. const size_t oldCount = size();
  3663. if(index < oldCount - 1)
  3664. {
  3665. memmove(m_pArray + index, m_pArray + (index + 1), (oldCount - index - 1) * sizeof(T));
  3666. }
  3667. resize(oldCount - 1);
  3668. }
  3669. void push_back(const T& src)
  3670. {
  3671. const size_t newIndex = size();
  3672. resize(newIndex + 1);
  3673. m_pArray[newIndex] = src;
  3674. }
  3675. void pop_back()
  3676. {
  3677. VMA_HEAVY_ASSERT(m_Count > 0);
  3678. resize(size() - 1);
  3679. }
  3680. void push_front(const T& src)
  3681. {
  3682. insert(0, src);
  3683. }
  3684. void pop_front()
  3685. {
  3686. VMA_HEAVY_ASSERT(m_Count > 0);
  3687. remove(0);
  3688. }
  3689. typedef T* iterator;
  3690. iterator begin() { return m_pArray; }
  3691. iterator end() { return m_pArray + m_Count; }
  3692. private:
  3693. AllocatorT m_Allocator;
  3694. T* m_pArray;
  3695. size_t m_Count;
  3696. size_t m_Capacity;
  3697. };
  3698. template<typename T, typename allocatorT>
  3699. static void VmaVectorInsert(VmaVector<T, allocatorT>& vec, size_t index, const T& item)
  3700. {
  3701. vec.insert(index, item);
  3702. }
  3703. template<typename T, typename allocatorT>
  3704. static void VmaVectorRemove(VmaVector<T, allocatorT>& vec, size_t index)
  3705. {
  3706. vec.remove(index);
  3707. }
  3708. #endif // #if VMA_USE_STL_VECTOR
  3709. template<typename CmpLess, typename VectorT>
  3710. size_t VmaVectorInsertSorted(VectorT& vector, const typename VectorT::value_type& value)
  3711. {
  3712. const size_t indexToInsert = VmaBinaryFindFirstNotLess(
  3713. vector.data(),
  3714. vector.data() + vector.size(),
  3715. value,
  3716. CmpLess()) - vector.data();
  3717. VmaVectorInsert(vector, indexToInsert, value);
  3718. return indexToInsert;
  3719. }
  3720. template<typename CmpLess, typename VectorT>
  3721. bool VmaVectorRemoveSorted(VectorT& vector, const typename VectorT::value_type& value)
  3722. {
  3723. CmpLess comparator;
  3724. typename VectorT::iterator it = VmaBinaryFindFirstNotLess(
  3725. vector.begin(),
  3726. vector.end(),
  3727. value,
  3728. comparator);
  3729. if((it != vector.end()) && !comparator(*it, value) && !comparator(value, *it))
  3730. {
  3731. size_t indexToRemove = it - vector.begin();
  3732. VmaVectorRemove(vector, indexToRemove);
  3733. return true;
  3734. }
  3735. return false;
  3736. }
  3737. ////////////////////////////////////////////////////////////////////////////////
  3738. // class VmaPoolAllocator
  3739. /*
  3740. Allocator for objects of type T using a list of arrays (pools) to speed up
  3741. allocation. Number of elements that can be allocated is not bounded because
  3742. allocator can create multiple blocks.
  3743. */
  3744. template<typename T>
  3745. class VmaPoolAllocator
  3746. {
  3747. VMA_CLASS_NO_COPY(VmaPoolAllocator)
  3748. public:
  3749. VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, uint32_t firstBlockCapacity);
  3750. ~VmaPoolAllocator();
  3751. T* Alloc();
  3752. void Free(T* ptr);
  3753. private:
  3754. union Item
  3755. {
  3756. uint32_t NextFreeIndex;
  3757. alignas(T) char Value[sizeof(T)];
  3758. };
  3759. struct ItemBlock
  3760. {
  3761. Item* pItems;
  3762. uint32_t Capacity;
  3763. uint32_t FirstFreeIndex;
  3764. };
  3765. const VkAllocationCallbacks* m_pAllocationCallbacks;
  3766. const uint32_t m_FirstBlockCapacity;
  3767. VmaVector< ItemBlock, VmaStlAllocator<ItemBlock> > m_ItemBlocks;
  3768. ItemBlock& CreateNewBlock();
  3769. };
  3770. template<typename T>
  3771. VmaPoolAllocator<T>::VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, uint32_t firstBlockCapacity) :
  3772. m_pAllocationCallbacks(pAllocationCallbacks),
  3773. m_FirstBlockCapacity(firstBlockCapacity),
  3774. m_ItemBlocks(VmaStlAllocator<ItemBlock>(pAllocationCallbacks))
  3775. {
  3776. VMA_ASSERT(m_FirstBlockCapacity > 1);
  3777. }
  3778. template<typename T>
  3779. VmaPoolAllocator<T>::~VmaPoolAllocator()
  3780. {
  3781. for(size_t i = m_ItemBlocks.size(); i--; )
  3782. vma_delete_array(m_pAllocationCallbacks, m_ItemBlocks[i].pItems, m_ItemBlocks[i].Capacity);
  3783. m_ItemBlocks.clear();
  3784. }
  3785. template<typename T>
  3786. T* VmaPoolAllocator<T>::Alloc()
  3787. {
  3788. for(size_t i = m_ItemBlocks.size(); i--; )
  3789. {
  3790. ItemBlock& block = m_ItemBlocks[i];
  3791. // This block has some free items: Use first one.
  3792. if(block.FirstFreeIndex != UINT32_MAX)
  3793. {
  3794. Item* const pItem = &block.pItems[block.FirstFreeIndex];
  3795. block.FirstFreeIndex = pItem->NextFreeIndex;
  3796. T* result = (T*)&pItem->Value;
  3797. new(result)T(); // Explicit constructor call.
  3798. return result;
  3799. }
  3800. }
  3801. // No block has free item: Create new one and use it.
  3802. ItemBlock& newBlock = CreateNewBlock();
  3803. Item* const pItem = &newBlock.pItems[0];
  3804. newBlock.FirstFreeIndex = pItem->NextFreeIndex;
  3805. T* result = (T*)&pItem->Value;
  3806. new(result)T(); // Explicit constructor call.
  3807. return result;
  3808. }
  3809. template<typename T>
  3810. void VmaPoolAllocator<T>::Free(T* ptr)
  3811. {
  3812. // Search all memory blocks to find ptr.
  3813. for(size_t i = m_ItemBlocks.size(); i--; )
  3814. {
  3815. ItemBlock& block = m_ItemBlocks[i];
  3816. // Casting to union.
  3817. Item* pItemPtr;
  3818. memcpy(&pItemPtr, &ptr, sizeof(pItemPtr));
  3819. // Check if pItemPtr is in address range of this block.
  3820. if((pItemPtr >= block.pItems) && (pItemPtr < block.pItems + block.Capacity))
  3821. {
  3822. ptr->~T(); // Explicit destructor call.
  3823. const uint32_t index = static_cast<uint32_t>(pItemPtr - block.pItems);
  3824. pItemPtr->NextFreeIndex = block.FirstFreeIndex;
  3825. block.FirstFreeIndex = index;
  3826. return;
  3827. }
  3828. }
  3829. VMA_ASSERT(0 && "Pointer doesn't belong to this memory pool.");
  3830. }
  3831. template<typename T>
  3832. typename VmaPoolAllocator<T>::ItemBlock& VmaPoolAllocator<T>::CreateNewBlock()
  3833. {
  3834. const uint32_t newBlockCapacity = m_ItemBlocks.empty() ?
  3835. m_FirstBlockCapacity : m_ItemBlocks.back().Capacity * 3 / 2;
  3836. const ItemBlock newBlock = {
  3837. vma_new_array(m_pAllocationCallbacks, Item, newBlockCapacity),
  3838. newBlockCapacity,
  3839. 0 };
  3840. m_ItemBlocks.push_back(newBlock);
  3841. // Setup singly-linked list of all free items in this block.
  3842. for(uint32_t i = 0; i < newBlockCapacity - 1; ++i)
  3843. newBlock.pItems[i].NextFreeIndex = i + 1;
  3844. newBlock.pItems[newBlockCapacity - 1].NextFreeIndex = UINT32_MAX;
  3845. return m_ItemBlocks.back();
  3846. }
  3847. ////////////////////////////////////////////////////////////////////////////////
  3848. // class VmaRawList, VmaList
  3849. #if VMA_USE_STL_LIST
  3850. #define VmaList std::list
  3851. #else // #if VMA_USE_STL_LIST
  3852. template<typename T>
  3853. struct VmaListItem
  3854. {
  3855. VmaListItem* pPrev;
  3856. VmaListItem* pNext;
  3857. T Value;
  3858. };
  3859. // Doubly linked list.
  3860. template<typename T>
  3861. class VmaRawList
  3862. {
  3863. VMA_CLASS_NO_COPY(VmaRawList)
  3864. public:
  3865. typedef VmaListItem<T> ItemType;
  3866. VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks);
  3867. ~VmaRawList();
  3868. void Clear();
  3869. size_t GetCount() const { return m_Count; }
  3870. bool IsEmpty() const { return m_Count == 0; }
  3871. ItemType* Front() { return m_pFront; }
  3872. const ItemType* Front() const { return m_pFront; }
  3873. ItemType* Back() { return m_pBack; }
  3874. const ItemType* Back() const { return m_pBack; }
  3875. ItemType* PushBack();
  3876. ItemType* PushFront();
  3877. ItemType* PushBack(const T& value);
  3878. ItemType* PushFront(const T& value);
  3879. void PopBack();
  3880. void PopFront();
  3881. // Item can be null - it means PushBack.
  3882. ItemType* InsertBefore(ItemType* pItem);
  3883. // Item can be null - it means PushFront.
  3884. ItemType* InsertAfter(ItemType* pItem);
  3885. ItemType* InsertBefore(ItemType* pItem, const T& value);
  3886. ItemType* InsertAfter(ItemType* pItem, const T& value);
  3887. void Remove(ItemType* pItem);
  3888. private:
  3889. const VkAllocationCallbacks* const m_pAllocationCallbacks;
  3890. VmaPoolAllocator<ItemType> m_ItemAllocator;
  3891. ItemType* m_pFront;
  3892. ItemType* m_pBack;
  3893. size_t m_Count;
  3894. };
  3895. template<typename T>
  3896. VmaRawList<T>::VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks) :
  3897. m_pAllocationCallbacks(pAllocationCallbacks),
  3898. m_ItemAllocator(pAllocationCallbacks, 128),
  3899. m_pFront(VMA_NULL),
  3900. m_pBack(VMA_NULL),
  3901. m_Count(0)
  3902. {
  3903. }
  3904. template<typename T>
  3905. VmaRawList<T>::~VmaRawList()
  3906. {
  3907. // Intentionally not calling Clear, because that would be unnecessary
  3908. // computations to return all items to m_ItemAllocator as free.
  3909. }
  3910. template<typename T>
  3911. void VmaRawList<T>::Clear()
  3912. {
  3913. if(IsEmpty() == false)
  3914. {
  3915. ItemType* pItem = m_pBack;
  3916. while(pItem != VMA_NULL)
  3917. {
  3918. ItemType* const pPrevItem = pItem->pPrev;
  3919. m_ItemAllocator.Free(pItem);
  3920. pItem = pPrevItem;
  3921. }
  3922. m_pFront = VMA_NULL;
  3923. m_pBack = VMA_NULL;
  3924. m_Count = 0;
  3925. }
  3926. }
  3927. template<typename T>
  3928. VmaListItem<T>* VmaRawList<T>::PushBack()
  3929. {
  3930. ItemType* const pNewItem = m_ItemAllocator.Alloc();
  3931. pNewItem->pNext = VMA_NULL;
  3932. if(IsEmpty())
  3933. {
  3934. pNewItem->pPrev = VMA_NULL;
  3935. m_pFront = pNewItem;
  3936. m_pBack = pNewItem;
  3937. m_Count = 1;
  3938. }
  3939. else
  3940. {
  3941. pNewItem->pPrev = m_pBack;
  3942. m_pBack->pNext = pNewItem;
  3943. m_pBack = pNewItem;
  3944. ++m_Count;
  3945. }
  3946. return pNewItem;
  3947. }
  3948. template<typename T>
  3949. VmaListItem<T>* VmaRawList<T>::PushFront()
  3950. {
  3951. ItemType* const pNewItem = m_ItemAllocator.Alloc();
  3952. pNewItem->pPrev = VMA_NULL;
  3953. if(IsEmpty())
  3954. {
  3955. pNewItem->pNext = VMA_NULL;
  3956. m_pFront = pNewItem;
  3957. m_pBack = pNewItem;
  3958. m_Count = 1;
  3959. }
  3960. else
  3961. {
  3962. pNewItem->pNext = m_pFront;
  3963. m_pFront->pPrev = pNewItem;
  3964. m_pFront = pNewItem;
  3965. ++m_Count;
  3966. }
  3967. return pNewItem;
  3968. }
  3969. template<typename T>
  3970. VmaListItem<T>* VmaRawList<T>::PushBack(const T& value)
  3971. {
  3972. ItemType* const pNewItem = PushBack();
  3973. pNewItem->Value = value;
  3974. return pNewItem;
  3975. }
  3976. template<typename T>
  3977. VmaListItem<T>* VmaRawList<T>::PushFront(const T& value)
  3978. {
  3979. ItemType* const pNewItem = PushFront();
  3980. pNewItem->Value = value;
  3981. return pNewItem;
  3982. }
  3983. template<typename T>
  3984. void VmaRawList<T>::PopBack()
  3985. {
  3986. VMA_HEAVY_ASSERT(m_Count > 0);
  3987. ItemType* const pBackItem = m_pBack;
  3988. ItemType* const pPrevItem = pBackItem->pPrev;
  3989. if(pPrevItem != VMA_NULL)
  3990. {
  3991. pPrevItem->pNext = VMA_NULL;
  3992. }
  3993. m_pBack = pPrevItem;
  3994. m_ItemAllocator.Free(pBackItem);
  3995. --m_Count;
  3996. }
  3997. template<typename T>
  3998. void VmaRawList<T>::PopFront()
  3999. {
  4000. VMA_HEAVY_ASSERT(m_Count > 0);
  4001. ItemType* const pFrontItem = m_pFront;
  4002. ItemType* const pNextItem = pFrontItem->pNext;
  4003. if(pNextItem != VMA_NULL)
  4004. {
  4005. pNextItem->pPrev = VMA_NULL;
  4006. }
  4007. m_pFront = pNextItem;
  4008. m_ItemAllocator.Free(pFrontItem);
  4009. --m_Count;
  4010. }
  4011. template<typename T>
  4012. void VmaRawList<T>::Remove(ItemType* pItem)
  4013. {
  4014. VMA_HEAVY_ASSERT(pItem != VMA_NULL);
  4015. VMA_HEAVY_ASSERT(m_Count > 0);
  4016. if(pItem->pPrev != VMA_NULL)
  4017. {
  4018. pItem->pPrev->pNext = pItem->pNext;
  4019. }
  4020. else
  4021. {
  4022. VMA_HEAVY_ASSERT(m_pFront == pItem);
  4023. m_pFront = pItem->pNext;
  4024. }
  4025. if(pItem->pNext != VMA_NULL)
  4026. {
  4027. pItem->pNext->pPrev = pItem->pPrev;
  4028. }
  4029. else
  4030. {
  4031. VMA_HEAVY_ASSERT(m_pBack == pItem);
  4032. m_pBack = pItem->pPrev;
  4033. }
  4034. m_ItemAllocator.Free(pItem);
  4035. --m_Count;
  4036. }
  4037. template<typename T>
  4038. VmaListItem<T>* VmaRawList<T>::InsertBefore(ItemType* pItem)
  4039. {
  4040. if(pItem != VMA_NULL)
  4041. {
  4042. ItemType* const prevItem = pItem->pPrev;
  4043. ItemType* const newItem = m_ItemAllocator.Alloc();
  4044. newItem->pPrev = prevItem;
  4045. newItem->pNext = pItem;
  4046. pItem->pPrev = newItem;
  4047. if(prevItem != VMA_NULL)
  4048. {
  4049. prevItem->pNext = newItem;
  4050. }
  4051. else
  4052. {
  4053. VMA_HEAVY_ASSERT(m_pFront == pItem);
  4054. m_pFront = newItem;
  4055. }
  4056. ++m_Count;
  4057. return newItem;
  4058. }
  4059. else
  4060. return PushBack();
  4061. }
  4062. template<typename T>
  4063. VmaListItem<T>* VmaRawList<T>::InsertAfter(ItemType* pItem)
  4064. {
  4065. if(pItem != VMA_NULL)
  4066. {
  4067. ItemType* const nextItem = pItem->pNext;
  4068. ItemType* const newItem = m_ItemAllocator.Alloc();
  4069. newItem->pNext = nextItem;
  4070. newItem->pPrev = pItem;
  4071. pItem->pNext = newItem;
  4072. if(nextItem != VMA_NULL)
  4073. {
  4074. nextItem->pPrev = newItem;
  4075. }
  4076. else
  4077. {
  4078. VMA_HEAVY_ASSERT(m_pBack == pItem);
  4079. m_pBack = newItem;
  4080. }
  4081. ++m_Count;
  4082. return newItem;
  4083. }
  4084. else
  4085. return PushFront();
  4086. }
  4087. template<typename T>
  4088. VmaListItem<T>* VmaRawList<T>::InsertBefore(ItemType* pItem, const T& value)
  4089. {
  4090. ItemType* const newItem = InsertBefore(pItem);
  4091. newItem->Value = value;
  4092. return newItem;
  4093. }
  4094. template<typename T>
  4095. VmaListItem<T>* VmaRawList<T>::InsertAfter(ItemType* pItem, const T& value)
  4096. {
  4097. ItemType* const newItem = InsertAfter(pItem);
  4098. newItem->Value = value;
  4099. return newItem;
  4100. }
  4101. template<typename T, typename AllocatorT>
  4102. class VmaList
  4103. {
  4104. VMA_CLASS_NO_COPY(VmaList)
  4105. public:
  4106. class iterator
  4107. {
  4108. public:
  4109. iterator() :
  4110. m_pList(VMA_NULL),
  4111. m_pItem(VMA_NULL)
  4112. {
  4113. }
  4114. T& operator*() const
  4115. {
  4116. VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
  4117. return m_pItem->Value;
  4118. }
  4119. T* operator->() const
  4120. {
  4121. VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
  4122. return &m_pItem->Value;
  4123. }
  4124. iterator& operator++()
  4125. {
  4126. VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
  4127. m_pItem = m_pItem->pNext;
  4128. return *this;
  4129. }
  4130. iterator& operator--()
  4131. {
  4132. if(m_pItem != VMA_NULL)
  4133. {
  4134. m_pItem = m_pItem->pPrev;
  4135. }
  4136. else
  4137. {
  4138. VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
  4139. m_pItem = m_pList->Back();
  4140. }
  4141. return *this;
  4142. }
  4143. iterator operator++(int)
  4144. {
  4145. iterator result = *this;
  4146. ++*this;
  4147. return result;
  4148. }
  4149. iterator operator--(int)
  4150. {
  4151. iterator result = *this;
  4152. --*this;
  4153. return result;
  4154. }
  4155. bool operator==(const iterator& rhs) const
  4156. {
  4157. VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
  4158. return m_pItem == rhs.m_pItem;
  4159. }
  4160. bool operator!=(const iterator& rhs) const
  4161. {
  4162. VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
  4163. return m_pItem != rhs.m_pItem;
  4164. }
  4165. private:
  4166. VmaRawList<T>* m_pList;
  4167. VmaListItem<T>* m_pItem;
  4168. iterator(VmaRawList<T>* pList, VmaListItem<T>* pItem) :
  4169. m_pList(pList),
  4170. m_pItem(pItem)
  4171. {
  4172. }
  4173. friend class VmaList<T, AllocatorT>;
  4174. };
  4175. class const_iterator
  4176. {
  4177. public:
  4178. const_iterator() :
  4179. m_pList(VMA_NULL),
  4180. m_pItem(VMA_NULL)
  4181. {
  4182. }
  4183. const_iterator(const iterator& src) :
  4184. m_pList(src.m_pList),
  4185. m_pItem(src.m_pItem)
  4186. {
  4187. }
  4188. const T& operator*() const
  4189. {
  4190. VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
  4191. return m_pItem->Value;
  4192. }
  4193. const T* operator->() const
  4194. {
  4195. VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
  4196. return &m_pItem->Value;
  4197. }
  4198. const_iterator& operator++()
  4199. {
  4200. VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
  4201. m_pItem = m_pItem->pNext;
  4202. return *this;
  4203. }
  4204. const_iterator& operator--()
  4205. {
  4206. if(m_pItem != VMA_NULL)
  4207. {
  4208. m_pItem = m_pItem->pPrev;
  4209. }
  4210. else
  4211. {
  4212. VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
  4213. m_pItem = m_pList->Back();
  4214. }
  4215. return *this;
  4216. }
  4217. const_iterator operator++(int)
  4218. {
  4219. const_iterator result = *this;
  4220. ++*this;
  4221. return result;
  4222. }
  4223. const_iterator operator--(int)
  4224. {
  4225. const_iterator result = *this;
  4226. --*this;
  4227. return result;
  4228. }
  4229. bool operator==(const const_iterator& rhs) const
  4230. {
  4231. VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
  4232. return m_pItem == rhs.m_pItem;
  4233. }
  4234. bool operator!=(const const_iterator& rhs) const
  4235. {
  4236. VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
  4237. return m_pItem != rhs.m_pItem;
  4238. }
  4239. private:
  4240. const_iterator(const VmaRawList<T>* pList, const VmaListItem<T>* pItem) :
  4241. m_pList(pList),
  4242. m_pItem(pItem)
  4243. {
  4244. }
  4245. const VmaRawList<T>* m_pList;
  4246. const VmaListItem<T>* m_pItem;
  4247. friend class VmaList<T, AllocatorT>;
  4248. };
  4249. VmaList(const AllocatorT& allocator) : m_RawList(allocator.m_pCallbacks) { }
  4250. bool empty() const { return m_RawList.IsEmpty(); }
  4251. size_t size() const { return m_RawList.GetCount(); }
  4252. iterator begin() { return iterator(&m_RawList, m_RawList.Front()); }
  4253. iterator end() { return iterator(&m_RawList, VMA_NULL); }
  4254. const_iterator cbegin() const { return const_iterator(&m_RawList, m_RawList.Front()); }
  4255. const_iterator cend() const { return const_iterator(&m_RawList, VMA_NULL); }
  4256. void clear() { m_RawList.Clear(); }
  4257. void push_back(const T& value) { m_RawList.PushBack(value); }
  4258. void erase(iterator it) { m_RawList.Remove(it.m_pItem); }
  4259. iterator insert(iterator it, const T& value) { return iterator(&m_RawList, m_RawList.InsertBefore(it.m_pItem, value)); }
  4260. private:
  4261. VmaRawList<T> m_RawList;
  4262. };
  4263. #endif // #if VMA_USE_STL_LIST
  4264. ////////////////////////////////////////////////////////////////////////////////
  4265. // class VmaMap
  4266. // Unused in this version.
  4267. #if 0
  4268. #if VMA_USE_STL_UNORDERED_MAP
  4269. #define VmaPair std::pair
  4270. #define VMA_MAP_TYPE(KeyT, ValueT) \
  4271. std::unordered_map< KeyT, ValueT, std::hash<KeyT>, std::equal_to<KeyT>, VmaStlAllocator< std::pair<KeyT, ValueT> > >
  4272. #else // #if VMA_USE_STL_UNORDERED_MAP
  4273. template<typename T1, typename T2>
  4274. struct VmaPair
  4275. {
  4276. T1 first;
  4277. T2 second;
  4278. VmaPair() : first(), second() { }
  4279. VmaPair(const T1& firstSrc, const T2& secondSrc) : first(firstSrc), second(secondSrc) { }
  4280. };
  4281. /* Class compatible with subset of interface of std::unordered_map.
  4282. KeyT, ValueT must be POD because they will be stored in VmaVector.
  4283. */
  4284. template<typename KeyT, typename ValueT>
  4285. class VmaMap
  4286. {
  4287. public:
  4288. typedef VmaPair<KeyT, ValueT> PairType;
  4289. typedef PairType* iterator;
  4290. VmaMap(const VmaStlAllocator<PairType>& allocator) : m_Vector(allocator) { }
  4291. iterator begin() { return m_Vector.begin(); }
  4292. iterator end() { return m_Vector.end(); }
  4293. void insert(const PairType& pair);
  4294. iterator find(const KeyT& key);
  4295. void erase(iterator it);
  4296. private:
  4297. VmaVector< PairType, VmaStlAllocator<PairType> > m_Vector;
  4298. };
  4299. #define VMA_MAP_TYPE(KeyT, ValueT) VmaMap<KeyT, ValueT>
  4300. template<typename FirstT, typename SecondT>
  4301. struct VmaPairFirstLess
  4302. {
  4303. bool operator()(const VmaPair<FirstT, SecondT>& lhs, const VmaPair<FirstT, SecondT>& rhs) const
  4304. {
  4305. return lhs.first < rhs.first;
  4306. }
  4307. bool operator()(const VmaPair<FirstT, SecondT>& lhs, const FirstT& rhsFirst) const
  4308. {
  4309. return lhs.first < rhsFirst;
  4310. }
  4311. };
  4312. template<typename KeyT, typename ValueT>
  4313. void VmaMap<KeyT, ValueT>::insert(const PairType& pair)
  4314. {
  4315. const size_t indexToInsert = VmaBinaryFindFirstNotLess(
  4316. m_Vector.data(),
  4317. m_Vector.data() + m_Vector.size(),
  4318. pair,
  4319. VmaPairFirstLess<KeyT, ValueT>()) - m_Vector.data();
  4320. VmaVectorInsert(m_Vector, indexToInsert, pair);
  4321. }
  4322. template<typename KeyT, typename ValueT>
  4323. VmaPair<KeyT, ValueT>* VmaMap<KeyT, ValueT>::find(const KeyT& key)
  4324. {
  4325. PairType* it = VmaBinaryFindFirstNotLess(
  4326. m_Vector.data(),
  4327. m_Vector.data() + m_Vector.size(),
  4328. key,
  4329. VmaPairFirstLess<KeyT, ValueT>());
  4330. if((it != m_Vector.end()) && (it->first == key))
  4331. {
  4332. return it;
  4333. }
  4334. else
  4335. {
  4336. return m_Vector.end();
  4337. }
  4338. }
  4339. template<typename KeyT, typename ValueT>
  4340. void VmaMap<KeyT, ValueT>::erase(iterator it)
  4341. {
  4342. VmaVectorRemove(m_Vector, it - m_Vector.begin());
  4343. }
  4344. #endif // #if VMA_USE_STL_UNORDERED_MAP
  4345. #endif // #if 0
  4346. ////////////////////////////////////////////////////////////////////////////////
  4347. class VmaDeviceMemoryBlock;
  4348. enum VMA_CACHE_OPERATION { VMA_CACHE_FLUSH, VMA_CACHE_INVALIDATE };
  4349. struct VmaAllocation_T
  4350. {
  4351. private:
  4352. static const uint8_t MAP_COUNT_FLAG_PERSISTENT_MAP = 0x80;
  4353. enum FLAGS
  4354. {
  4355. FLAG_USER_DATA_STRING = 0x01,
  4356. };
  4357. public:
  4358. enum ALLOCATION_TYPE
  4359. {
  4360. ALLOCATION_TYPE_NONE,
  4361. ALLOCATION_TYPE_BLOCK,
  4362. ALLOCATION_TYPE_DEDICATED,
  4363. };
  4364. /*
  4365. This struct is allocated using VmaPoolAllocator.
  4366. */
  4367. void Ctor(uint32_t currentFrameIndex, bool userDataString)
  4368. {
  4369. m_Alignment = 1;
  4370. m_Size = 0;
  4371. m_MemoryTypeIndex = 0;
  4372. m_pUserData = VMA_NULL;
  4373. m_LastUseFrameIndex = currentFrameIndex;
  4374. m_Type = (uint8_t)ALLOCATION_TYPE_NONE;
  4375. m_SuballocationType = (uint8_t)VMA_SUBALLOCATION_TYPE_UNKNOWN;
  4376. m_MapCount = 0;
  4377. m_Flags = userDataString ? (uint8_t)FLAG_USER_DATA_STRING : 0;
  4378. #if VMA_STATS_STRING_ENABLED
  4379. m_CreationFrameIndex = currentFrameIndex;
  4380. m_BufferImageUsage = 0;
  4381. #endif
  4382. }
  4383. void Dtor()
  4384. {
  4385. VMA_ASSERT((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) == 0 && "Allocation was not unmapped before destruction.");
  4386. // Check if owned string was freed.
  4387. VMA_ASSERT(m_pUserData == VMA_NULL);
  4388. }
  4389. void InitBlockAllocation(
  4390. VmaDeviceMemoryBlock* block,
  4391. VkDeviceSize offset,
  4392. VkDeviceSize alignment,
  4393. VkDeviceSize size,
  4394. uint32_t memoryTypeIndex,
  4395. VmaSuballocationType suballocationType,
  4396. bool mapped,
  4397. bool canBecomeLost)
  4398. {
  4399. VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
  4400. VMA_ASSERT(block != VMA_NULL);
  4401. m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK;
  4402. m_Alignment = alignment;
  4403. m_Size = size;
  4404. m_MemoryTypeIndex = memoryTypeIndex;
  4405. m_MapCount = mapped ? MAP_COUNT_FLAG_PERSISTENT_MAP : 0;
  4406. m_SuballocationType = (uint8_t)suballocationType;
  4407. m_BlockAllocation.m_Block = block;
  4408. m_BlockAllocation.m_Offset = offset;
  4409. m_BlockAllocation.m_CanBecomeLost = canBecomeLost;
  4410. }
  4411. void InitLost()
  4412. {
  4413. VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
  4414. VMA_ASSERT(m_LastUseFrameIndex.load() == VMA_FRAME_INDEX_LOST);
  4415. m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK;
  4416. m_MemoryTypeIndex = 0;
  4417. m_BlockAllocation.m_Block = VMA_NULL;
  4418. m_BlockAllocation.m_Offset = 0;
  4419. m_BlockAllocation.m_CanBecomeLost = true;
  4420. }
  4421. void ChangeBlockAllocation(
  4422. VmaAllocator hAllocator,
  4423. VmaDeviceMemoryBlock* block,
  4424. VkDeviceSize offset);
  4425. void ChangeOffset(VkDeviceSize newOffset);
  4426. // pMappedData not null means allocation is created with MAPPED flag.
  4427. void InitDedicatedAllocation(
  4428. uint32_t memoryTypeIndex,
  4429. VkDeviceMemory hMemory,
  4430. VmaSuballocationType suballocationType,
  4431. void* pMappedData,
  4432. VkDeviceSize size)
  4433. {
  4434. VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
  4435. VMA_ASSERT(hMemory != VK_NULL_HANDLE);
  4436. m_Type = (uint8_t)ALLOCATION_TYPE_DEDICATED;
  4437. m_Alignment = 0;
  4438. m_Size = size;
  4439. m_MemoryTypeIndex = memoryTypeIndex;
  4440. m_SuballocationType = (uint8_t)suballocationType;
  4441. m_MapCount = (pMappedData != VMA_NULL) ? MAP_COUNT_FLAG_PERSISTENT_MAP : 0;
  4442. m_DedicatedAllocation.m_hMemory = hMemory;
  4443. m_DedicatedAllocation.m_pMappedData = pMappedData;
  4444. }
  4445. ALLOCATION_TYPE GetType() const { return (ALLOCATION_TYPE)m_Type; }
  4446. VkDeviceSize GetAlignment() const { return m_Alignment; }
  4447. VkDeviceSize GetSize() const { return m_Size; }
  4448. bool IsUserDataString() const { return (m_Flags & FLAG_USER_DATA_STRING) != 0; }
  4449. void* GetUserData() const { return m_pUserData; }
  4450. void SetUserData(VmaAllocator hAllocator, void* pUserData);
  4451. VmaSuballocationType GetSuballocationType() const { return (VmaSuballocationType)m_SuballocationType; }
  4452. VmaDeviceMemoryBlock* GetBlock() const
  4453. {
  4454. VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK);
  4455. return m_BlockAllocation.m_Block;
  4456. }
  4457. VkDeviceSize GetOffset() const;
  4458. VkDeviceMemory GetMemory() const;
  4459. uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
  4460. bool IsPersistentMap() const { return (m_MapCount & MAP_COUNT_FLAG_PERSISTENT_MAP) != 0; }
  4461. void* GetMappedData() const;
  4462. bool CanBecomeLost() const;
  4463. uint32_t GetLastUseFrameIndex() const
  4464. {
  4465. return m_LastUseFrameIndex.load();
  4466. }
  4467. bool CompareExchangeLastUseFrameIndex(uint32_t& expected, uint32_t desired)
  4468. {
  4469. return m_LastUseFrameIndex.compare_exchange_weak(expected, desired);
  4470. }
  4471. /*
  4472. - If hAllocation.LastUseFrameIndex + frameInUseCount < allocator.CurrentFrameIndex,
  4473. makes it lost by setting LastUseFrameIndex = VMA_FRAME_INDEX_LOST and returns true.
  4474. - Else, returns false.
  4475. If hAllocation is already lost, assert - you should not call it then.
  4476. If hAllocation was not created with CAN_BECOME_LOST_BIT, assert.
  4477. */
  4478. bool MakeLost(uint32_t currentFrameIndex, uint32_t frameInUseCount);
  4479. void DedicatedAllocCalcStatsInfo(VmaStatInfo& outInfo)
  4480. {
  4481. VMA_ASSERT(m_Type == ALLOCATION_TYPE_DEDICATED);
  4482. outInfo.blockCount = 1;
  4483. outInfo.allocationCount = 1;
  4484. outInfo.unusedRangeCount = 0;
  4485. outInfo.usedBytes = m_Size;
  4486. outInfo.unusedBytes = 0;
  4487. outInfo.allocationSizeMin = outInfo.allocationSizeMax = m_Size;
  4488. outInfo.unusedRangeSizeMin = UINT64_MAX;
  4489. outInfo.unusedRangeSizeMax = 0;
  4490. }
  4491. void BlockAllocMap();
  4492. void BlockAllocUnmap();
  4493. VkResult DedicatedAllocMap(VmaAllocator hAllocator, void** ppData);
  4494. void DedicatedAllocUnmap(VmaAllocator hAllocator);
  4495. #if VMA_STATS_STRING_ENABLED
  4496. uint32_t GetCreationFrameIndex() const { return m_CreationFrameIndex; }
  4497. uint32_t GetBufferImageUsage() const { return m_BufferImageUsage; }
  4498. void InitBufferImageUsage(uint32_t bufferImageUsage)
  4499. {
  4500. VMA_ASSERT(m_BufferImageUsage == 0);
  4501. m_BufferImageUsage = bufferImageUsage;
  4502. }
  4503. void PrintParameters(class VmaJsonWriter& json) const;
  4504. #endif
  4505. private:
  4506. VkDeviceSize m_Alignment;
  4507. VkDeviceSize m_Size;
  4508. void* m_pUserData;
  4509. VMA_ATOMIC_UINT32 m_LastUseFrameIndex;
  4510. uint32_t m_MemoryTypeIndex;
  4511. uint8_t m_Type; // ALLOCATION_TYPE
  4512. uint8_t m_SuballocationType; // VmaSuballocationType
  4513. // Bit 0x80 is set when allocation was created with VMA_ALLOCATION_CREATE_MAPPED_BIT.
  4514. // Bits with mask 0x7F are reference counter for vmaMapMemory()/vmaUnmapMemory().
  4515. uint8_t m_MapCount;
  4516. uint8_t m_Flags; // enum FLAGS
  4517. // Allocation out of VmaDeviceMemoryBlock.
  4518. struct BlockAllocation
  4519. {
  4520. VmaDeviceMemoryBlock* m_Block;
  4521. VkDeviceSize m_Offset;
  4522. bool m_CanBecomeLost;
  4523. };
  4524. // Allocation for an object that has its own private VkDeviceMemory.
  4525. struct DedicatedAllocation
  4526. {
  4527. VkDeviceMemory m_hMemory;
  4528. void* m_pMappedData; // Not null means memory is mapped.
  4529. };
  4530. union
  4531. {
  4532. // Allocation out of VmaDeviceMemoryBlock.
  4533. BlockAllocation m_BlockAllocation;
  4534. // Allocation for an object that has its own private VkDeviceMemory.
  4535. DedicatedAllocation m_DedicatedAllocation;
  4536. };
  4537. #if VMA_STATS_STRING_ENABLED
  4538. uint32_t m_CreationFrameIndex;
  4539. uint32_t m_BufferImageUsage; // 0 if unknown.
  4540. #endif
  4541. void FreeUserDataString(VmaAllocator hAllocator);
  4542. };
  4543. /*
  4544. Represents a region of VmaDeviceMemoryBlock that is either assigned and returned as
  4545. allocated memory block or free.
  4546. */
  4547. struct VmaSuballocation
  4548. {
  4549. VkDeviceSize offset;
  4550. VkDeviceSize size;
  4551. VmaAllocation hAllocation;
  4552. VmaSuballocationType type;
  4553. };
  4554. // Comparator for offsets.
  4555. struct VmaSuballocationOffsetLess
  4556. {
  4557. bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const
  4558. {
  4559. return lhs.offset < rhs.offset;
  4560. }
  4561. };
  4562. struct VmaSuballocationOffsetGreater
  4563. {
  4564. bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const
  4565. {
  4566. return lhs.offset > rhs.offset;
  4567. }
  4568. };
  4569. typedef VmaList< VmaSuballocation, VmaStlAllocator<VmaSuballocation> > VmaSuballocationList;
  4570. // Cost of one additional allocation lost, as equivalent in bytes.
  4571. static const VkDeviceSize VMA_LOST_ALLOCATION_COST = 1048576;
  4572. enum class VmaAllocationRequestType
  4573. {
  4574. Normal,
  4575. // Used by "Linear" algorithm.
  4576. UpperAddress,
  4577. EndOf1st,
  4578. EndOf2nd,
  4579. };
  4580. /*
  4581. Parameters of planned allocation inside a VmaDeviceMemoryBlock.
  4582. If canMakeOtherLost was false:
  4583. - item points to a FREE suballocation.
  4584. - itemsToMakeLostCount is 0.
  4585. If canMakeOtherLost was true:
  4586. - item points to first of sequence of suballocations, which are either FREE,
  4587. or point to VmaAllocations that can become lost.
  4588. - itemsToMakeLostCount is the number of VmaAllocations that need to be made lost for
  4589. the requested allocation to succeed.
  4590. */
  4591. struct VmaAllocationRequest
  4592. {
  4593. VkDeviceSize offset;
  4594. VkDeviceSize sumFreeSize; // Sum size of free items that overlap with proposed allocation.
  4595. VkDeviceSize sumItemSize; // Sum size of items to make lost that overlap with proposed allocation.
  4596. VmaSuballocationList::iterator item;
  4597. size_t itemsToMakeLostCount;
  4598. void* customData;
  4599. VmaAllocationRequestType type;
  4600. VkDeviceSize CalcCost() const
  4601. {
  4602. return sumItemSize + itemsToMakeLostCount * VMA_LOST_ALLOCATION_COST;
  4603. }
  4604. };
  4605. /*
  4606. Data structure used for bookkeeping of allocations and unused ranges of memory
  4607. in a single VkDeviceMemory block.
  4608. */
  4609. class VmaBlockMetadata
  4610. {
  4611. public:
  4612. VmaBlockMetadata(VmaAllocator hAllocator);
  4613. virtual ~VmaBlockMetadata() { }
  4614. virtual void Init(VkDeviceSize size) { m_Size = size; }
  4615. // Validates all data structures inside this object. If not valid, returns false.
  4616. virtual bool Validate() const = 0;
  4617. VkDeviceSize GetSize() const { return m_Size; }
  4618. virtual size_t GetAllocationCount() const = 0;
  4619. virtual VkDeviceSize GetSumFreeSize() const = 0;
  4620. virtual VkDeviceSize GetUnusedRangeSizeMax() const = 0;
  4621. // Returns true if this block is empty - contains only single free suballocation.
  4622. virtual bool IsEmpty() const = 0;
  4623. virtual void CalcAllocationStatInfo(VmaStatInfo& outInfo) const = 0;
  4624. // Shouldn't modify blockCount.
  4625. virtual void AddPoolStats(VmaPoolStats& inoutStats) const = 0;
  4626. #if VMA_STATS_STRING_ENABLED
  4627. virtual void PrintDetailedMap(class VmaJsonWriter& json) const = 0;
  4628. #endif
  4629. // Tries to find a place for suballocation with given parameters inside this block.
  4630. // If succeeded, fills pAllocationRequest and returns true.
  4631. // If failed, returns false.
  4632. virtual bool CreateAllocationRequest(
  4633. uint32_t currentFrameIndex,
  4634. uint32_t frameInUseCount,
  4635. VkDeviceSize bufferImageGranularity,
  4636. VkDeviceSize allocSize,
  4637. VkDeviceSize allocAlignment,
  4638. bool upperAddress,
  4639. VmaSuballocationType allocType,
  4640. bool canMakeOtherLost,
  4641. // Always one of VMA_ALLOCATION_CREATE_STRATEGY_* or VMA_ALLOCATION_INTERNAL_STRATEGY_* flags.
  4642. uint32_t strategy,
  4643. VmaAllocationRequest* pAllocationRequest) = 0;
  4644. virtual bool MakeRequestedAllocationsLost(
  4645. uint32_t currentFrameIndex,
  4646. uint32_t frameInUseCount,
  4647. VmaAllocationRequest* pAllocationRequest) = 0;
  4648. virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount) = 0;
  4649. virtual VkResult CheckCorruption(const void* pBlockData) = 0;
  4650. // Makes actual allocation based on request. Request must already be checked and valid.
  4651. virtual void Alloc(
  4652. const VmaAllocationRequest& request,
  4653. VmaSuballocationType type,
  4654. VkDeviceSize allocSize,
  4655. VmaAllocation hAllocation) = 0;
  4656. // Frees suballocation assigned to given memory region.
  4657. virtual void Free(const VmaAllocation allocation) = 0;
  4658. virtual void FreeAtOffset(VkDeviceSize offset) = 0;
  4659. protected:
  4660. const VkAllocationCallbacks* GetAllocationCallbacks() const { return m_pAllocationCallbacks; }
  4661. #if VMA_STATS_STRING_ENABLED
  4662. void PrintDetailedMap_Begin(class VmaJsonWriter& json,
  4663. VkDeviceSize unusedBytes,
  4664. size_t allocationCount,
  4665. size_t unusedRangeCount) const;
  4666. void PrintDetailedMap_Allocation(class VmaJsonWriter& json,
  4667. VkDeviceSize offset,
  4668. VmaAllocation hAllocation) const;
  4669. void PrintDetailedMap_UnusedRange(class VmaJsonWriter& json,
  4670. VkDeviceSize offset,
  4671. VkDeviceSize size) const;
  4672. void PrintDetailedMap_End(class VmaJsonWriter& json) const;
  4673. #endif
  4674. private:
  4675. VkDeviceSize m_Size;
  4676. const VkAllocationCallbacks* m_pAllocationCallbacks;
  4677. };
  4678. #define VMA_VALIDATE(cond) do { if(!(cond)) { \
  4679. VMA_ASSERT(0 && "Validation failed: " #cond); \
  4680. return false; \
  4681. } } while(false)
  4682. class VmaBlockMetadata_Generic : public VmaBlockMetadata
  4683. {
  4684. VMA_CLASS_NO_COPY(VmaBlockMetadata_Generic)
  4685. public:
  4686. VmaBlockMetadata_Generic(VmaAllocator hAllocator);
  4687. virtual ~VmaBlockMetadata_Generic();
  4688. virtual void Init(VkDeviceSize size);
  4689. virtual bool Validate() const;
  4690. virtual size_t GetAllocationCount() const { return m_Suballocations.size() - m_FreeCount; }
  4691. virtual VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize; }
  4692. virtual VkDeviceSize GetUnusedRangeSizeMax() const;
  4693. virtual bool IsEmpty() const;
  4694. virtual void CalcAllocationStatInfo(VmaStatInfo& outInfo) const;
  4695. virtual void AddPoolStats(VmaPoolStats& inoutStats) const;
  4696. #if VMA_STATS_STRING_ENABLED
  4697. virtual void PrintDetailedMap(class VmaJsonWriter& json) const;
  4698. #endif
  4699. virtual bool CreateAllocationRequest(
  4700. uint32_t currentFrameIndex,
  4701. uint32_t frameInUseCount,
  4702. VkDeviceSize bufferImageGranularity,
  4703. VkDeviceSize allocSize,
  4704. VkDeviceSize allocAlignment,
  4705. bool upperAddress,
  4706. VmaSuballocationType allocType,
  4707. bool canMakeOtherLost,
  4708. uint32_t strategy,
  4709. VmaAllocationRequest* pAllocationRequest);
  4710. virtual bool MakeRequestedAllocationsLost(
  4711. uint32_t currentFrameIndex,
  4712. uint32_t frameInUseCount,
  4713. VmaAllocationRequest* pAllocationRequest);
  4714. virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount);
  4715. virtual VkResult CheckCorruption(const void* pBlockData);
  4716. virtual void Alloc(
  4717. const VmaAllocationRequest& request,
  4718. VmaSuballocationType type,
  4719. VkDeviceSize allocSize,
  4720. VmaAllocation hAllocation);
  4721. virtual void Free(const VmaAllocation allocation);
  4722. virtual void FreeAtOffset(VkDeviceSize offset);
  4723. ////////////////////////////////////////////////////////////////////////////////
  4724. // For defragmentation
  4725. bool IsBufferImageGranularityConflictPossible(
  4726. VkDeviceSize bufferImageGranularity,
  4727. VmaSuballocationType& inOutPrevSuballocType) const;
  4728. private:
  4729. friend class VmaDefragmentationAlgorithm_Generic;
  4730. friend class VmaDefragmentationAlgorithm_Fast;
  4731. uint32_t m_FreeCount;
  4732. VkDeviceSize m_SumFreeSize;
  4733. VmaSuballocationList m_Suballocations;
  4734. // Suballocations that are free and have size greater than certain threshold.
  4735. // Sorted by size, ascending.
  4736. VmaVector< VmaSuballocationList::iterator, VmaStlAllocator< VmaSuballocationList::iterator > > m_FreeSuballocationsBySize;
  4737. bool ValidateFreeSuballocationList() const;
  4738. // Checks if requested suballocation with given parameters can be placed in given pFreeSuballocItem.
  4739. // If yes, fills pOffset and returns true. If no, returns false.
  4740. bool CheckAllocation(
  4741. uint32_t currentFrameIndex,
  4742. uint32_t frameInUseCount,
  4743. VkDeviceSize bufferImageGranularity,
  4744. VkDeviceSize allocSize,
  4745. VkDeviceSize allocAlignment,
  4746. VmaSuballocationType allocType,
  4747. VmaSuballocationList::const_iterator suballocItem,
  4748. bool canMakeOtherLost,
  4749. VkDeviceSize* pOffset,
  4750. size_t* itemsToMakeLostCount,
  4751. VkDeviceSize* pSumFreeSize,
  4752. VkDeviceSize* pSumItemSize) const;
  4753. // Given free suballocation, it merges it with following one, which must also be free.
  4754. void MergeFreeWithNext(VmaSuballocationList::iterator item);
  4755. // Releases given suballocation, making it free.
  4756. // Merges it with adjacent free suballocations if applicable.
  4757. // Returns iterator to new free suballocation at this place.
  4758. VmaSuballocationList::iterator FreeSuballocation(VmaSuballocationList::iterator suballocItem);
  4759. // Given free suballocation, it inserts it into sorted list of
  4760. // m_FreeSuballocationsBySize if it's suitable.
  4761. void RegisterFreeSuballocation(VmaSuballocationList::iterator item);
  4762. // Given free suballocation, it removes it from sorted list of
  4763. // m_FreeSuballocationsBySize if it's suitable.
  4764. void UnregisterFreeSuballocation(VmaSuballocationList::iterator item);
  4765. };
  4766. /*
  4767. Allocations and their references in internal data structure look like this:
  4768. if(m_2ndVectorMode == SECOND_VECTOR_EMPTY):
  4769. 0 +-------+
  4770. | |
  4771. | |
  4772. | |
  4773. +-------+
  4774. | Alloc | 1st[m_1stNullItemsBeginCount]
  4775. +-------+
  4776. | Alloc | 1st[m_1stNullItemsBeginCount + 1]
  4777. +-------+
  4778. | ... |
  4779. +-------+
  4780. | Alloc | 1st[1st.size() - 1]
  4781. +-------+
  4782. | |
  4783. | |
  4784. | |
  4785. GetSize() +-------+
  4786. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER):
  4787. 0 +-------+
  4788. | Alloc | 2nd[0]
  4789. +-------+
  4790. | Alloc | 2nd[1]
  4791. +-------+
  4792. | ... |
  4793. +-------+
  4794. | Alloc | 2nd[2nd.size() - 1]
  4795. +-------+
  4796. | |
  4797. | |
  4798. | |
  4799. +-------+
  4800. | Alloc | 1st[m_1stNullItemsBeginCount]
  4801. +-------+
  4802. | Alloc | 1st[m_1stNullItemsBeginCount + 1]
  4803. +-------+
  4804. | ... |
  4805. +-------+
  4806. | Alloc | 1st[1st.size() - 1]
  4807. +-------+
  4808. | |
  4809. GetSize() +-------+
  4810. if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK):
  4811. 0 +-------+
  4812. | |
  4813. | |
  4814. | |
  4815. +-------+
  4816. | Alloc | 1st[m_1stNullItemsBeginCount]
  4817. +-------+
  4818. | Alloc | 1st[m_1stNullItemsBeginCount + 1]
  4819. +-------+
  4820. | ... |
  4821. +-------+
  4822. | Alloc | 1st[1st.size() - 1]
  4823. +-------+
  4824. | |
  4825. | |
  4826. | |
  4827. +-------+
  4828. | Alloc | 2nd[2nd.size() - 1]
  4829. +-------+
  4830. | ... |
  4831. +-------+
  4832. | Alloc | 2nd[1]
  4833. +-------+
  4834. | Alloc | 2nd[0]
  4835. GetSize() +-------+
  4836. */
  4837. class VmaBlockMetadata_Linear : public VmaBlockMetadata
  4838. {
  4839. VMA_CLASS_NO_COPY(VmaBlockMetadata_Linear)
  4840. public:
  4841. VmaBlockMetadata_Linear(VmaAllocator hAllocator);
  4842. virtual ~VmaBlockMetadata_Linear();
  4843. virtual void Init(VkDeviceSize size);
  4844. virtual bool Validate() const;
  4845. virtual size_t GetAllocationCount() const;
  4846. virtual VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize; }
  4847. virtual VkDeviceSize GetUnusedRangeSizeMax() const;
  4848. virtual bool IsEmpty() const { return GetAllocationCount() == 0; }
  4849. virtual void CalcAllocationStatInfo(VmaStatInfo& outInfo) const;
  4850. virtual void AddPoolStats(VmaPoolStats& inoutStats) const;
  4851. #if VMA_STATS_STRING_ENABLED
  4852. virtual void PrintDetailedMap(class VmaJsonWriter& json) const;
  4853. #endif
  4854. virtual bool CreateAllocationRequest(
  4855. uint32_t currentFrameIndex,
  4856. uint32_t frameInUseCount,
  4857. VkDeviceSize bufferImageGranularity,
  4858. VkDeviceSize allocSize,
  4859. VkDeviceSize allocAlignment,
  4860. bool upperAddress,
  4861. VmaSuballocationType allocType,
  4862. bool canMakeOtherLost,
  4863. uint32_t strategy,
  4864. VmaAllocationRequest* pAllocationRequest);
  4865. virtual bool MakeRequestedAllocationsLost(
  4866. uint32_t currentFrameIndex,
  4867. uint32_t frameInUseCount,
  4868. VmaAllocationRequest* pAllocationRequest);
  4869. virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount);
  4870. virtual VkResult CheckCorruption(const void* pBlockData);
  4871. virtual void Alloc(
  4872. const VmaAllocationRequest& request,
  4873. VmaSuballocationType type,
  4874. VkDeviceSize allocSize,
  4875. VmaAllocation hAllocation);
  4876. virtual void Free(const VmaAllocation allocation);
  4877. virtual void FreeAtOffset(VkDeviceSize offset);
  4878. private:
  4879. /*
  4880. There are two suballocation vectors, used in ping-pong way.
  4881. The one with index m_1stVectorIndex is called 1st.
  4882. The one with index (m_1stVectorIndex ^ 1) is called 2nd.
  4883. 2nd can be non-empty only when 1st is not empty.
  4884. When 2nd is not empty, m_2ndVectorMode indicates its mode of operation.
  4885. */
  4886. typedef VmaVector< VmaSuballocation, VmaStlAllocator<VmaSuballocation> > SuballocationVectorType;
  4887. enum SECOND_VECTOR_MODE
  4888. {
  4889. SECOND_VECTOR_EMPTY,
  4890. /*
  4891. Suballocations in 2nd vector are created later than the ones in 1st, but they
  4892. all have smaller offset.
  4893. */
  4894. SECOND_VECTOR_RING_BUFFER,
  4895. /*
  4896. Suballocations in 2nd vector are upper side of double stack.
  4897. They all have offsets higher than those in 1st vector.
  4898. Top of this stack means smaller offsets, but higher indices in this vector.
  4899. */
  4900. SECOND_VECTOR_DOUBLE_STACK,
  4901. };
  4902. VkDeviceSize m_SumFreeSize;
  4903. SuballocationVectorType m_Suballocations0, m_Suballocations1;
  4904. uint32_t m_1stVectorIndex;
  4905. SECOND_VECTOR_MODE m_2ndVectorMode;
  4906. SuballocationVectorType& AccessSuballocations1st() { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; }
  4907. SuballocationVectorType& AccessSuballocations2nd() { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; }
  4908. const SuballocationVectorType& AccessSuballocations1st() const { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; }
  4909. const SuballocationVectorType& AccessSuballocations2nd() const { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; }
  4910. // Number of items in 1st vector with hAllocation = null at the beginning.
  4911. size_t m_1stNullItemsBeginCount;
  4912. // Number of other items in 1st vector with hAllocation = null somewhere in the middle.
  4913. size_t m_1stNullItemsMiddleCount;
  4914. // Number of items in 2nd vector with hAllocation = null.
  4915. size_t m_2ndNullItemsCount;
  4916. bool ShouldCompact1st() const;
  4917. void CleanupAfterFree();
  4918. bool CreateAllocationRequest_LowerAddress(
  4919. uint32_t currentFrameIndex,
  4920. uint32_t frameInUseCount,
  4921. VkDeviceSize bufferImageGranularity,
  4922. VkDeviceSize allocSize,
  4923. VkDeviceSize allocAlignment,
  4924. VmaSuballocationType allocType,
  4925. bool canMakeOtherLost,
  4926. uint32_t strategy,
  4927. VmaAllocationRequest* pAllocationRequest);
  4928. bool CreateAllocationRequest_UpperAddress(
  4929. uint32_t currentFrameIndex,
  4930. uint32_t frameInUseCount,
  4931. VkDeviceSize bufferImageGranularity,
  4932. VkDeviceSize allocSize,
  4933. VkDeviceSize allocAlignment,
  4934. VmaSuballocationType allocType,
  4935. bool canMakeOtherLost,
  4936. uint32_t strategy,
  4937. VmaAllocationRequest* pAllocationRequest);
  4938. };
  4939. /*
  4940. - GetSize() is the original size of allocated memory block.
  4941. - m_UsableSize is this size aligned down to a power of two.
  4942. All allocations and calculations happen relative to m_UsableSize.
  4943. - GetUnusableSize() is the difference between them.
  4944. It is repoted as separate, unused range, not available for allocations.
  4945. Node at level 0 has size = m_UsableSize.
  4946. Each next level contains nodes with size 2 times smaller than current level.
  4947. m_LevelCount is the maximum number of levels to use in the current object.
  4948. */
  4949. class VmaBlockMetadata_Buddy : public VmaBlockMetadata
  4950. {
  4951. VMA_CLASS_NO_COPY(VmaBlockMetadata_Buddy)
  4952. public:
  4953. VmaBlockMetadata_Buddy(VmaAllocator hAllocator);
  4954. virtual ~VmaBlockMetadata_Buddy();
  4955. virtual void Init(VkDeviceSize size);
  4956. virtual bool Validate() const;
  4957. virtual size_t GetAllocationCount() const { return m_AllocationCount; }
  4958. virtual VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize + GetUnusableSize(); }
  4959. virtual VkDeviceSize GetUnusedRangeSizeMax() const;
  4960. virtual bool IsEmpty() const { return m_Root->type == Node::TYPE_FREE; }
  4961. virtual void CalcAllocationStatInfo(VmaStatInfo& outInfo) const;
  4962. virtual void AddPoolStats(VmaPoolStats& inoutStats) const;
  4963. #if VMA_STATS_STRING_ENABLED
  4964. virtual void PrintDetailedMap(class VmaJsonWriter& json) const;
  4965. #endif
  4966. virtual bool CreateAllocationRequest(
  4967. uint32_t currentFrameIndex,
  4968. uint32_t frameInUseCount,
  4969. VkDeviceSize bufferImageGranularity,
  4970. VkDeviceSize allocSize,
  4971. VkDeviceSize allocAlignment,
  4972. bool upperAddress,
  4973. VmaSuballocationType allocType,
  4974. bool canMakeOtherLost,
  4975. uint32_t strategy,
  4976. VmaAllocationRequest* pAllocationRequest);
  4977. virtual bool MakeRequestedAllocationsLost(
  4978. uint32_t currentFrameIndex,
  4979. uint32_t frameInUseCount,
  4980. VmaAllocationRequest* pAllocationRequest);
  4981. virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount);
  4982. virtual VkResult CheckCorruption(const void* pBlockData) { return VK_ERROR_FEATURE_NOT_PRESENT; }
  4983. virtual void Alloc(
  4984. const VmaAllocationRequest& request,
  4985. VmaSuballocationType type,
  4986. VkDeviceSize allocSize,
  4987. VmaAllocation hAllocation);
  4988. virtual void Free(const VmaAllocation allocation) { FreeAtOffset(allocation, allocation->GetOffset()); }
  4989. virtual void FreeAtOffset(VkDeviceSize offset) { FreeAtOffset(VMA_NULL, offset); }
  4990. private:
  4991. static const VkDeviceSize MIN_NODE_SIZE = 32;
  4992. static const size_t MAX_LEVELS = 30;
  4993. struct ValidationContext
  4994. {
  4995. size_t calculatedAllocationCount;
  4996. size_t calculatedFreeCount;
  4997. VkDeviceSize calculatedSumFreeSize;
  4998. ValidationContext() :
  4999. calculatedAllocationCount(0),
  5000. calculatedFreeCount(0),
  5001. calculatedSumFreeSize(0) { }
  5002. };
  5003. struct Node
  5004. {
  5005. VkDeviceSize offset;
  5006. enum TYPE
  5007. {
  5008. TYPE_FREE,
  5009. TYPE_ALLOCATION,
  5010. TYPE_SPLIT,
  5011. TYPE_COUNT
  5012. } type;
  5013. Node* parent;
  5014. Node* buddy;
  5015. union
  5016. {
  5017. struct
  5018. {
  5019. Node* prev;
  5020. Node* next;
  5021. } free;
  5022. struct
  5023. {
  5024. VmaAllocation alloc;
  5025. } allocation;
  5026. struct
  5027. {
  5028. Node* leftChild;
  5029. } split;
  5030. };
  5031. };
  5032. // Size of the memory block aligned down to a power of two.
  5033. VkDeviceSize m_UsableSize;
  5034. uint32_t m_LevelCount;
  5035. Node* m_Root;
  5036. struct {
  5037. Node* front;
  5038. Node* back;
  5039. } m_FreeList[MAX_LEVELS];
  5040. // Number of nodes in the tree with type == TYPE_ALLOCATION.
  5041. size_t m_AllocationCount;
  5042. // Number of nodes in the tree with type == TYPE_FREE.
  5043. size_t m_FreeCount;
  5044. // This includes space wasted due to internal fragmentation. Doesn't include unusable size.
  5045. VkDeviceSize m_SumFreeSize;
  5046. VkDeviceSize GetUnusableSize() const { return GetSize() - m_UsableSize; }
  5047. void DeleteNode(Node* node);
  5048. bool ValidateNode(ValidationContext& ctx, const Node* parent, const Node* curr, uint32_t level, VkDeviceSize levelNodeSize) const;
  5049. uint32_t AllocSizeToLevel(VkDeviceSize allocSize) const;
  5050. inline VkDeviceSize LevelToNodeSize(uint32_t level) const { return m_UsableSize >> level; }
  5051. // Alloc passed just for validation. Can be null.
  5052. void FreeAtOffset(VmaAllocation alloc, VkDeviceSize offset);
  5053. void CalcAllocationStatInfoNode(VmaStatInfo& outInfo, const Node* node, VkDeviceSize levelNodeSize) const;
  5054. // Adds node to the front of FreeList at given level.
  5055. // node->type must be FREE.
  5056. // node->free.prev, next can be undefined.
  5057. void AddToFreeListFront(uint32_t level, Node* node);
  5058. // Removes node from FreeList at given level.
  5059. // node->type must be FREE.
  5060. // node->free.prev, next stay untouched.
  5061. void RemoveFromFreeList(uint32_t level, Node* node);
  5062. #if VMA_STATS_STRING_ENABLED
  5063. void PrintDetailedMapNode(class VmaJsonWriter& json, const Node* node, VkDeviceSize levelNodeSize) const;
  5064. #endif
  5065. };
  5066. /*
  5067. Represents a single block of device memory (`VkDeviceMemory`) with all the
  5068. data about its regions (aka suballocations, #VmaAllocation), assigned and free.
  5069. Thread-safety: This class must be externally synchronized.
  5070. */
  5071. class VmaDeviceMemoryBlock
  5072. {
  5073. VMA_CLASS_NO_COPY(VmaDeviceMemoryBlock)
  5074. public:
  5075. VmaBlockMetadata* m_pMetadata;
  5076. VmaDeviceMemoryBlock(VmaAllocator hAllocator);
  5077. ~VmaDeviceMemoryBlock()
  5078. {
  5079. VMA_ASSERT(m_MapCount == 0 && "VkDeviceMemory block is being destroyed while it is still mapped.");
  5080. VMA_ASSERT(m_hMemory == VK_NULL_HANDLE);
  5081. }
  5082. // Always call after construction.
  5083. void Init(
  5084. VmaAllocator hAllocator,
  5085. VmaPool hParentPool,
  5086. uint32_t newMemoryTypeIndex,
  5087. VkDeviceMemory newMemory,
  5088. VkDeviceSize newSize,
  5089. uint32_t id,
  5090. uint32_t algorithm);
  5091. // Always call before destruction.
  5092. void Destroy(VmaAllocator allocator);
  5093. VmaPool GetParentPool() const { return m_hParentPool; }
  5094. VkDeviceMemory GetDeviceMemory() const { return m_hMemory; }
  5095. uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
  5096. uint32_t GetId() const { return m_Id; }
  5097. void* GetMappedData() const { return m_pMappedData; }
  5098. // Validates all data structures inside this object. If not valid, returns false.
  5099. bool Validate() const;
  5100. VkResult CheckCorruption(VmaAllocator hAllocator);
  5101. // ppData can be null.
  5102. VkResult Map(VmaAllocator hAllocator, uint32_t count, void** ppData);
  5103. void Unmap(VmaAllocator hAllocator, uint32_t count);
  5104. VkResult WriteMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize);
  5105. VkResult ValidateMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize);
  5106. VkResult BindBufferMemory(
  5107. const VmaAllocator hAllocator,
  5108. const VmaAllocation hAllocation,
  5109. VkDeviceSize allocationLocalOffset,
  5110. VkBuffer hBuffer,
  5111. const void* pNext);
  5112. VkResult BindImageMemory(
  5113. const VmaAllocator hAllocator,
  5114. const VmaAllocation hAllocation,
  5115. VkDeviceSize allocationLocalOffset,
  5116. VkImage hImage,
  5117. const void* pNext);
  5118. private:
  5119. VmaPool m_hParentPool; // VK_NULL_HANDLE if not belongs to custom pool.
  5120. uint32_t m_MemoryTypeIndex;
  5121. uint32_t m_Id;
  5122. VkDeviceMemory m_hMemory;
  5123. /*
  5124. Protects access to m_hMemory so it's not used by multiple threads simultaneously, e.g. vkMapMemory, vkBindBufferMemory.
  5125. Also protects m_MapCount, m_pMappedData.
  5126. Allocations, deallocations, any change in m_pMetadata is protected by parent's VmaBlockVector::m_Mutex.
  5127. */
  5128. VMA_MUTEX m_Mutex;
  5129. uint32_t m_MapCount;
  5130. void* m_pMappedData;
  5131. };
  5132. struct VmaPointerLess
  5133. {
  5134. bool operator()(const void* lhs, const void* rhs) const
  5135. {
  5136. return lhs < rhs;
  5137. }
  5138. };
  5139. struct VmaDefragmentationMove
  5140. {
  5141. size_t srcBlockIndex;
  5142. size_t dstBlockIndex;
  5143. VkDeviceSize srcOffset;
  5144. VkDeviceSize dstOffset;
  5145. VkDeviceSize size;
  5146. };
  5147. class VmaDefragmentationAlgorithm;
  5148. /*
  5149. Sequence of VmaDeviceMemoryBlock. Represents memory blocks allocated for a specific
  5150. Vulkan memory type.
  5151. Synchronized internally with a mutex.
  5152. */
  5153. struct VmaBlockVector
  5154. {
  5155. VMA_CLASS_NO_COPY(VmaBlockVector)
  5156. public:
  5157. VmaBlockVector(
  5158. VmaAllocator hAllocator,
  5159. VmaPool hParentPool,
  5160. uint32_t memoryTypeIndex,
  5161. VkDeviceSize preferredBlockSize,
  5162. size_t minBlockCount,
  5163. size_t maxBlockCount,
  5164. VkDeviceSize bufferImageGranularity,
  5165. uint32_t frameInUseCount,
  5166. bool explicitBlockSize,
  5167. uint32_t algorithm);
  5168. ~VmaBlockVector();
  5169. VkResult CreateMinBlocks();
  5170. VmaAllocator GetAllocator() const { return m_hAllocator; }
  5171. VmaPool GetParentPool() const { return m_hParentPool; }
  5172. bool IsCustomPool() const { return m_hParentPool != VMA_NULL; }
  5173. uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
  5174. VkDeviceSize GetPreferredBlockSize() const { return m_PreferredBlockSize; }
  5175. VkDeviceSize GetBufferImageGranularity() const { return m_BufferImageGranularity; }
  5176. uint32_t GetFrameInUseCount() const { return m_FrameInUseCount; }
  5177. uint32_t GetAlgorithm() const { return m_Algorithm; }
  5178. void GetPoolStats(VmaPoolStats* pStats);
  5179. bool IsEmpty();
  5180. bool IsCorruptionDetectionEnabled() const;
  5181. VkResult Allocate(
  5182. uint32_t currentFrameIndex,
  5183. VkDeviceSize size,
  5184. VkDeviceSize alignment,
  5185. const VmaAllocationCreateInfo& createInfo,
  5186. VmaSuballocationType suballocType,
  5187. size_t allocationCount,
  5188. VmaAllocation* pAllocations);
  5189. void Free(const VmaAllocation hAllocation);
  5190. // Adds statistics of this BlockVector to pStats.
  5191. void AddStats(VmaStats* pStats);
  5192. #if VMA_STATS_STRING_ENABLED
  5193. void PrintDetailedMap(class VmaJsonWriter& json);
  5194. #endif
  5195. void MakePoolAllocationsLost(
  5196. uint32_t currentFrameIndex,
  5197. size_t* pLostAllocationCount);
  5198. VkResult CheckCorruption();
  5199. // Saves results in pCtx->res.
  5200. void Defragment(
  5201. class VmaBlockVectorDefragmentationContext* pCtx,
  5202. VmaDefragmentationStats* pStats,
  5203. VkDeviceSize& maxCpuBytesToMove, uint32_t& maxCpuAllocationsToMove,
  5204. VkDeviceSize& maxGpuBytesToMove, uint32_t& maxGpuAllocationsToMove,
  5205. VkCommandBuffer commandBuffer);
  5206. void DefragmentationEnd(
  5207. class VmaBlockVectorDefragmentationContext* pCtx,
  5208. VmaDefragmentationStats* pStats);
  5209. ////////////////////////////////////////////////////////////////////////////////
  5210. // To be used only while the m_Mutex is locked. Used during defragmentation.
  5211. size_t GetBlockCount() const { return m_Blocks.size(); }
  5212. VmaDeviceMemoryBlock* GetBlock(size_t index) const { return m_Blocks[index]; }
  5213. size_t CalcAllocationCount() const;
  5214. bool IsBufferImageGranularityConflictPossible() const;
  5215. private:
  5216. friend class VmaDefragmentationAlgorithm_Generic;
  5217. const VmaAllocator m_hAllocator;
  5218. const VmaPool m_hParentPool;
  5219. const uint32_t m_MemoryTypeIndex;
  5220. const VkDeviceSize m_PreferredBlockSize;
  5221. const size_t m_MinBlockCount;
  5222. const size_t m_MaxBlockCount;
  5223. const VkDeviceSize m_BufferImageGranularity;
  5224. const uint32_t m_FrameInUseCount;
  5225. const bool m_ExplicitBlockSize;
  5226. const uint32_t m_Algorithm;
  5227. VMA_RW_MUTEX m_Mutex;
  5228. /* There can be at most one allocation that is completely empty (except when minBlockCount > 0) -
  5229. a hysteresis to avoid pessimistic case of alternating creation and destruction of a VkDeviceMemory. */
  5230. bool m_HasEmptyBlock;
  5231. // Incrementally sorted by sumFreeSize, ascending.
  5232. VmaVector< VmaDeviceMemoryBlock*, VmaStlAllocator<VmaDeviceMemoryBlock*> > m_Blocks;
  5233. uint32_t m_NextBlockId;
  5234. VkDeviceSize CalcMaxBlockSize() const;
  5235. // Finds and removes given block from vector.
  5236. void Remove(VmaDeviceMemoryBlock* pBlock);
  5237. // Performs single step in sorting m_Blocks. They may not be fully sorted
  5238. // after this call.
  5239. void IncrementallySortBlocks();
  5240. VkResult AllocatePage(
  5241. uint32_t currentFrameIndex,
  5242. VkDeviceSize size,
  5243. VkDeviceSize alignment,
  5244. const VmaAllocationCreateInfo& createInfo,
  5245. VmaSuballocationType suballocType,
  5246. VmaAllocation* pAllocation);
  5247. // To be used only without CAN_MAKE_OTHER_LOST flag.
  5248. VkResult AllocateFromBlock(
  5249. VmaDeviceMemoryBlock* pBlock,
  5250. uint32_t currentFrameIndex,
  5251. VkDeviceSize size,
  5252. VkDeviceSize alignment,
  5253. VmaAllocationCreateFlags allocFlags,
  5254. void* pUserData,
  5255. VmaSuballocationType suballocType,
  5256. uint32_t strategy,
  5257. VmaAllocation* pAllocation);
  5258. VkResult CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex);
  5259. // Saves result to pCtx->res.
  5260. void ApplyDefragmentationMovesCpu(
  5261. class VmaBlockVectorDefragmentationContext* pDefragCtx,
  5262. const VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves);
  5263. // Saves result to pCtx->res.
  5264. void ApplyDefragmentationMovesGpu(
  5265. class VmaBlockVectorDefragmentationContext* pDefragCtx,
  5266. const VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  5267. VkCommandBuffer commandBuffer);
  5268. /*
  5269. Used during defragmentation. pDefragmentationStats is optional. It's in/out
  5270. - updated with new data.
  5271. */
  5272. void FreeEmptyBlocks(VmaDefragmentationStats* pDefragmentationStats);
  5273. void UpdateHasEmptyBlock();
  5274. };
  5275. struct VmaPool_T
  5276. {
  5277. VMA_CLASS_NO_COPY(VmaPool_T)
  5278. public:
  5279. VmaBlockVector m_BlockVector;
  5280. VmaPool_T(
  5281. VmaAllocator hAllocator,
  5282. const VmaPoolCreateInfo& createInfo,
  5283. VkDeviceSize preferredBlockSize);
  5284. ~VmaPool_T();
  5285. uint32_t GetId() const { return m_Id; }
  5286. void SetId(uint32_t id) { VMA_ASSERT(m_Id == 0); m_Id = id; }
  5287. const char* GetName() const { return m_Name; }
  5288. void SetName(const char* pName);
  5289. #if VMA_STATS_STRING_ENABLED
  5290. //void PrintDetailedMap(class VmaStringBuilder& sb);
  5291. #endif
  5292. private:
  5293. uint32_t m_Id;
  5294. char* m_Name;
  5295. };
  5296. /*
  5297. Performs defragmentation:
  5298. - Updates `pBlockVector->m_pMetadata`.
  5299. - Updates allocations by calling ChangeBlockAllocation() or ChangeOffset().
  5300. - Does not move actual data, only returns requested moves as `moves`.
  5301. */
  5302. class VmaDefragmentationAlgorithm
  5303. {
  5304. VMA_CLASS_NO_COPY(VmaDefragmentationAlgorithm)
  5305. public:
  5306. VmaDefragmentationAlgorithm(
  5307. VmaAllocator hAllocator,
  5308. VmaBlockVector* pBlockVector,
  5309. uint32_t currentFrameIndex) :
  5310. m_hAllocator(hAllocator),
  5311. m_pBlockVector(pBlockVector),
  5312. m_CurrentFrameIndex(currentFrameIndex)
  5313. {
  5314. }
  5315. virtual ~VmaDefragmentationAlgorithm()
  5316. {
  5317. }
  5318. virtual void AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged) = 0;
  5319. virtual void AddAll() = 0;
  5320. virtual VkResult Defragment(
  5321. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  5322. VkDeviceSize maxBytesToMove,
  5323. uint32_t maxAllocationsToMove) = 0;
  5324. virtual VkDeviceSize GetBytesMoved() const = 0;
  5325. virtual uint32_t GetAllocationsMoved() const = 0;
  5326. protected:
  5327. VmaAllocator const m_hAllocator;
  5328. VmaBlockVector* const m_pBlockVector;
  5329. const uint32_t m_CurrentFrameIndex;
  5330. struct AllocationInfo
  5331. {
  5332. VmaAllocation m_hAllocation;
  5333. VkBool32* m_pChanged;
  5334. AllocationInfo() :
  5335. m_hAllocation(VK_NULL_HANDLE),
  5336. m_pChanged(VMA_NULL)
  5337. {
  5338. }
  5339. AllocationInfo(VmaAllocation hAlloc, VkBool32* pChanged) :
  5340. m_hAllocation(hAlloc),
  5341. m_pChanged(pChanged)
  5342. {
  5343. }
  5344. };
  5345. };
  5346. class VmaDefragmentationAlgorithm_Generic : public VmaDefragmentationAlgorithm
  5347. {
  5348. VMA_CLASS_NO_COPY(VmaDefragmentationAlgorithm_Generic)
  5349. public:
  5350. VmaDefragmentationAlgorithm_Generic(
  5351. VmaAllocator hAllocator,
  5352. VmaBlockVector* pBlockVector,
  5353. uint32_t currentFrameIndex,
  5354. bool overlappingMoveSupported);
  5355. virtual ~VmaDefragmentationAlgorithm_Generic();
  5356. virtual void AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged);
  5357. virtual void AddAll() { m_AllAllocations = true; }
  5358. virtual VkResult Defragment(
  5359. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  5360. VkDeviceSize maxBytesToMove,
  5361. uint32_t maxAllocationsToMove);
  5362. virtual VkDeviceSize GetBytesMoved() const { return m_BytesMoved; }
  5363. virtual uint32_t GetAllocationsMoved() const { return m_AllocationsMoved; }
  5364. private:
  5365. uint32_t m_AllocationCount;
  5366. bool m_AllAllocations;
  5367. VkDeviceSize m_BytesMoved;
  5368. uint32_t m_AllocationsMoved;
  5369. struct AllocationInfoSizeGreater
  5370. {
  5371. bool operator()(const AllocationInfo& lhs, const AllocationInfo& rhs) const
  5372. {
  5373. return lhs.m_hAllocation->GetSize() > rhs.m_hAllocation->GetSize();
  5374. }
  5375. };
  5376. struct AllocationInfoOffsetGreater
  5377. {
  5378. bool operator()(const AllocationInfo& lhs, const AllocationInfo& rhs) const
  5379. {
  5380. return lhs.m_hAllocation->GetOffset() > rhs.m_hAllocation->GetOffset();
  5381. }
  5382. };
  5383. struct BlockInfo
  5384. {
  5385. size_t m_OriginalBlockIndex;
  5386. VmaDeviceMemoryBlock* m_pBlock;
  5387. bool m_HasNonMovableAllocations;
  5388. VmaVector< AllocationInfo, VmaStlAllocator<AllocationInfo> > m_Allocations;
  5389. BlockInfo(const VkAllocationCallbacks* pAllocationCallbacks) :
  5390. m_OriginalBlockIndex(SIZE_MAX),
  5391. m_pBlock(VMA_NULL),
  5392. m_HasNonMovableAllocations(true),
  5393. m_Allocations(pAllocationCallbacks)
  5394. {
  5395. }
  5396. void CalcHasNonMovableAllocations()
  5397. {
  5398. const size_t blockAllocCount = m_pBlock->m_pMetadata->GetAllocationCount();
  5399. const size_t defragmentAllocCount = m_Allocations.size();
  5400. m_HasNonMovableAllocations = blockAllocCount != defragmentAllocCount;
  5401. }
  5402. void SortAllocationsBySizeDescending()
  5403. {
  5404. VMA_SORT(m_Allocations.begin(), m_Allocations.end(), AllocationInfoSizeGreater());
  5405. }
  5406. void SortAllocationsByOffsetDescending()
  5407. {
  5408. VMA_SORT(m_Allocations.begin(), m_Allocations.end(), AllocationInfoOffsetGreater());
  5409. }
  5410. };
  5411. struct BlockPointerLess
  5412. {
  5413. bool operator()(const BlockInfo* pLhsBlockInfo, const VmaDeviceMemoryBlock* pRhsBlock) const
  5414. {
  5415. return pLhsBlockInfo->m_pBlock < pRhsBlock;
  5416. }
  5417. bool operator()(const BlockInfo* pLhsBlockInfo, const BlockInfo* pRhsBlockInfo) const
  5418. {
  5419. return pLhsBlockInfo->m_pBlock < pRhsBlockInfo->m_pBlock;
  5420. }
  5421. };
  5422. // 1. Blocks with some non-movable allocations go first.
  5423. // 2. Blocks with smaller sumFreeSize go first.
  5424. struct BlockInfoCompareMoveDestination
  5425. {
  5426. bool operator()(const BlockInfo* pLhsBlockInfo, const BlockInfo* pRhsBlockInfo) const
  5427. {
  5428. if(pLhsBlockInfo->m_HasNonMovableAllocations && !pRhsBlockInfo->m_HasNonMovableAllocations)
  5429. {
  5430. return true;
  5431. }
  5432. if(!pLhsBlockInfo->m_HasNonMovableAllocations && pRhsBlockInfo->m_HasNonMovableAllocations)
  5433. {
  5434. return false;
  5435. }
  5436. if(pLhsBlockInfo->m_pBlock->m_pMetadata->GetSumFreeSize() < pRhsBlockInfo->m_pBlock->m_pMetadata->GetSumFreeSize())
  5437. {
  5438. return true;
  5439. }
  5440. return false;
  5441. }
  5442. };
  5443. typedef VmaVector< BlockInfo*, VmaStlAllocator<BlockInfo*> > BlockInfoVector;
  5444. BlockInfoVector m_Blocks;
  5445. VkResult DefragmentRound(
  5446. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  5447. VkDeviceSize maxBytesToMove,
  5448. uint32_t maxAllocationsToMove);
  5449. size_t CalcBlocksWithNonMovableCount() const;
  5450. static bool MoveMakesSense(
  5451. size_t dstBlockIndex, VkDeviceSize dstOffset,
  5452. size_t srcBlockIndex, VkDeviceSize srcOffset);
  5453. };
  5454. class VmaDefragmentationAlgorithm_Fast : public VmaDefragmentationAlgorithm
  5455. {
  5456. VMA_CLASS_NO_COPY(VmaDefragmentationAlgorithm_Fast)
  5457. public:
  5458. VmaDefragmentationAlgorithm_Fast(
  5459. VmaAllocator hAllocator,
  5460. VmaBlockVector* pBlockVector,
  5461. uint32_t currentFrameIndex,
  5462. bool overlappingMoveSupported);
  5463. virtual ~VmaDefragmentationAlgorithm_Fast();
  5464. virtual void AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged) { ++m_AllocationCount; }
  5465. virtual void AddAll() { m_AllAllocations = true; }
  5466. virtual VkResult Defragment(
  5467. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  5468. VkDeviceSize maxBytesToMove,
  5469. uint32_t maxAllocationsToMove);
  5470. virtual VkDeviceSize GetBytesMoved() const { return m_BytesMoved; }
  5471. virtual uint32_t GetAllocationsMoved() const { return m_AllocationsMoved; }
  5472. private:
  5473. struct BlockInfo
  5474. {
  5475. size_t origBlockIndex;
  5476. };
  5477. class FreeSpaceDatabase
  5478. {
  5479. public:
  5480. FreeSpaceDatabase()
  5481. {
  5482. FreeSpace s = {};
  5483. s.blockInfoIndex = SIZE_MAX;
  5484. for(size_t i = 0; i < MAX_COUNT; ++i)
  5485. {
  5486. m_FreeSpaces[i] = s;
  5487. }
  5488. }
  5489. void Register(size_t blockInfoIndex, VkDeviceSize offset, VkDeviceSize size)
  5490. {
  5491. if(size < VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
  5492. {
  5493. return;
  5494. }
  5495. // Find first invalid or the smallest structure.
  5496. size_t bestIndex = SIZE_MAX;
  5497. for(size_t i = 0; i < MAX_COUNT; ++i)
  5498. {
  5499. // Empty structure.
  5500. if(m_FreeSpaces[i].blockInfoIndex == SIZE_MAX)
  5501. {
  5502. bestIndex = i;
  5503. break;
  5504. }
  5505. if(m_FreeSpaces[i].size < size &&
  5506. (bestIndex == SIZE_MAX || m_FreeSpaces[bestIndex].size > m_FreeSpaces[i].size))
  5507. {
  5508. bestIndex = i;
  5509. }
  5510. }
  5511. if(bestIndex != SIZE_MAX)
  5512. {
  5513. m_FreeSpaces[bestIndex].blockInfoIndex = blockInfoIndex;
  5514. m_FreeSpaces[bestIndex].offset = offset;
  5515. m_FreeSpaces[bestIndex].size = size;
  5516. }
  5517. }
  5518. bool Fetch(VkDeviceSize alignment, VkDeviceSize size,
  5519. size_t& outBlockInfoIndex, VkDeviceSize& outDstOffset)
  5520. {
  5521. size_t bestIndex = SIZE_MAX;
  5522. VkDeviceSize bestFreeSpaceAfter = 0;
  5523. for(size_t i = 0; i < MAX_COUNT; ++i)
  5524. {
  5525. // Structure is valid.
  5526. if(m_FreeSpaces[i].blockInfoIndex != SIZE_MAX)
  5527. {
  5528. const VkDeviceSize dstOffset = VmaAlignUp(m_FreeSpaces[i].offset, alignment);
  5529. // Allocation fits into this structure.
  5530. if(dstOffset + size <= m_FreeSpaces[i].offset + m_FreeSpaces[i].size)
  5531. {
  5532. const VkDeviceSize freeSpaceAfter = (m_FreeSpaces[i].offset + m_FreeSpaces[i].size) -
  5533. (dstOffset + size);
  5534. if(bestIndex == SIZE_MAX || freeSpaceAfter > bestFreeSpaceAfter)
  5535. {
  5536. bestIndex = i;
  5537. bestFreeSpaceAfter = freeSpaceAfter;
  5538. }
  5539. }
  5540. }
  5541. }
  5542. if(bestIndex != SIZE_MAX)
  5543. {
  5544. outBlockInfoIndex = m_FreeSpaces[bestIndex].blockInfoIndex;
  5545. outDstOffset = VmaAlignUp(m_FreeSpaces[bestIndex].offset, alignment);
  5546. if(bestFreeSpaceAfter >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
  5547. {
  5548. // Leave this structure for remaining empty space.
  5549. const VkDeviceSize alignmentPlusSize = (outDstOffset - m_FreeSpaces[bestIndex].offset) + size;
  5550. m_FreeSpaces[bestIndex].offset += alignmentPlusSize;
  5551. m_FreeSpaces[bestIndex].size -= alignmentPlusSize;
  5552. }
  5553. else
  5554. {
  5555. // This structure becomes invalid.
  5556. m_FreeSpaces[bestIndex].blockInfoIndex = SIZE_MAX;
  5557. }
  5558. return true;
  5559. }
  5560. return false;
  5561. }
  5562. private:
  5563. static const size_t MAX_COUNT = 4;
  5564. struct FreeSpace
  5565. {
  5566. size_t blockInfoIndex; // SIZE_MAX means this structure is invalid.
  5567. VkDeviceSize offset;
  5568. VkDeviceSize size;
  5569. } m_FreeSpaces[MAX_COUNT];
  5570. };
  5571. const bool m_OverlappingMoveSupported;
  5572. uint32_t m_AllocationCount;
  5573. bool m_AllAllocations;
  5574. VkDeviceSize m_BytesMoved;
  5575. uint32_t m_AllocationsMoved;
  5576. VmaVector< BlockInfo, VmaStlAllocator<BlockInfo> > m_BlockInfos;
  5577. void PreprocessMetadata();
  5578. void PostprocessMetadata();
  5579. void InsertSuballoc(VmaBlockMetadata_Generic* pMetadata, const VmaSuballocation& suballoc);
  5580. };
  5581. struct VmaBlockDefragmentationContext
  5582. {
  5583. enum BLOCK_FLAG
  5584. {
  5585. BLOCK_FLAG_USED = 0x00000001,
  5586. };
  5587. uint32_t flags;
  5588. VkBuffer hBuffer;
  5589. };
  5590. class VmaBlockVectorDefragmentationContext
  5591. {
  5592. VMA_CLASS_NO_COPY(VmaBlockVectorDefragmentationContext)
  5593. public:
  5594. VkResult res;
  5595. bool mutexLocked;
  5596. VmaVector< VmaBlockDefragmentationContext, VmaStlAllocator<VmaBlockDefragmentationContext> > blockContexts;
  5597. VmaBlockVectorDefragmentationContext(
  5598. VmaAllocator hAllocator,
  5599. VmaPool hCustomPool, // Optional.
  5600. VmaBlockVector* pBlockVector,
  5601. uint32_t currFrameIndex);
  5602. ~VmaBlockVectorDefragmentationContext();
  5603. VmaPool GetCustomPool() const { return m_hCustomPool; }
  5604. VmaBlockVector* GetBlockVector() const { return m_pBlockVector; }
  5605. VmaDefragmentationAlgorithm* GetAlgorithm() const { return m_pAlgorithm; }
  5606. void AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged);
  5607. void AddAll() { m_AllAllocations = true; }
  5608. void Begin(bool overlappingMoveSupported);
  5609. private:
  5610. const VmaAllocator m_hAllocator;
  5611. // Null if not from custom pool.
  5612. const VmaPool m_hCustomPool;
  5613. // Redundant, for convenience not to fetch from m_hCustomPool->m_BlockVector or m_hAllocator->m_pBlockVectors.
  5614. VmaBlockVector* const m_pBlockVector;
  5615. const uint32_t m_CurrFrameIndex;
  5616. // Owner of this object.
  5617. VmaDefragmentationAlgorithm* m_pAlgorithm;
  5618. struct AllocInfo
  5619. {
  5620. VmaAllocation hAlloc;
  5621. VkBool32* pChanged;
  5622. };
  5623. // Used between constructor and Begin.
  5624. VmaVector< AllocInfo, VmaStlAllocator<AllocInfo> > m_Allocations;
  5625. bool m_AllAllocations;
  5626. };
  5627. struct VmaDefragmentationContext_T
  5628. {
  5629. private:
  5630. VMA_CLASS_NO_COPY(VmaDefragmentationContext_T)
  5631. public:
  5632. VmaDefragmentationContext_T(
  5633. VmaAllocator hAllocator,
  5634. uint32_t currFrameIndex,
  5635. uint32_t flags,
  5636. VmaDefragmentationStats* pStats);
  5637. ~VmaDefragmentationContext_T();
  5638. void AddPools(uint32_t poolCount, VmaPool* pPools);
  5639. void AddAllocations(
  5640. uint32_t allocationCount,
  5641. VmaAllocation* pAllocations,
  5642. VkBool32* pAllocationsChanged);
  5643. /*
  5644. Returns:
  5645. - `VK_SUCCESS` if succeeded and object can be destroyed immediately.
  5646. - `VK_NOT_READY` if succeeded but the object must remain alive until vmaDefragmentationEnd().
  5647. - Negative value if error occured and object can be destroyed immediately.
  5648. */
  5649. VkResult Defragment(
  5650. VkDeviceSize maxCpuBytesToMove, uint32_t maxCpuAllocationsToMove,
  5651. VkDeviceSize maxGpuBytesToMove, uint32_t maxGpuAllocationsToMove,
  5652. VkCommandBuffer commandBuffer, VmaDefragmentationStats* pStats);
  5653. private:
  5654. const VmaAllocator m_hAllocator;
  5655. const uint32_t m_CurrFrameIndex;
  5656. const uint32_t m_Flags;
  5657. VmaDefragmentationStats* const m_pStats;
  5658. // Owner of these objects.
  5659. VmaBlockVectorDefragmentationContext* m_DefaultPoolContexts[VK_MAX_MEMORY_TYPES];
  5660. // Owner of these objects.
  5661. VmaVector< VmaBlockVectorDefragmentationContext*, VmaStlAllocator<VmaBlockVectorDefragmentationContext*> > m_CustomPoolContexts;
  5662. };
  5663. #if VMA_RECORDING_ENABLED
  5664. class VmaRecorder
  5665. {
  5666. public:
  5667. VmaRecorder();
  5668. VkResult Init(const VmaRecordSettings& settings, bool useMutex);
  5669. void WriteConfiguration(
  5670. const VkPhysicalDeviceProperties& devProps,
  5671. const VkPhysicalDeviceMemoryProperties& memProps,
  5672. uint32_t vulkanApiVersion,
  5673. bool dedicatedAllocationExtensionEnabled,
  5674. bool bindMemory2ExtensionEnabled,
  5675. bool memoryBudgetExtensionEnabled);
  5676. ~VmaRecorder();
  5677. void RecordCreateAllocator(uint32_t frameIndex);
  5678. void RecordDestroyAllocator(uint32_t frameIndex);
  5679. void RecordCreatePool(uint32_t frameIndex,
  5680. const VmaPoolCreateInfo& createInfo,
  5681. VmaPool pool);
  5682. void RecordDestroyPool(uint32_t frameIndex, VmaPool pool);
  5683. void RecordAllocateMemory(uint32_t frameIndex,
  5684. const VkMemoryRequirements& vkMemReq,
  5685. const VmaAllocationCreateInfo& createInfo,
  5686. VmaAllocation allocation);
  5687. void RecordAllocateMemoryPages(uint32_t frameIndex,
  5688. const VkMemoryRequirements& vkMemReq,
  5689. const VmaAllocationCreateInfo& createInfo,
  5690. uint64_t allocationCount,
  5691. const VmaAllocation* pAllocations);
  5692. void RecordAllocateMemoryForBuffer(uint32_t frameIndex,
  5693. const VkMemoryRequirements& vkMemReq,
  5694. bool requiresDedicatedAllocation,
  5695. bool prefersDedicatedAllocation,
  5696. const VmaAllocationCreateInfo& createInfo,
  5697. VmaAllocation allocation);
  5698. void RecordAllocateMemoryForImage(uint32_t frameIndex,
  5699. const VkMemoryRequirements& vkMemReq,
  5700. bool requiresDedicatedAllocation,
  5701. bool prefersDedicatedAllocation,
  5702. const VmaAllocationCreateInfo& createInfo,
  5703. VmaAllocation allocation);
  5704. void RecordFreeMemory(uint32_t frameIndex,
  5705. VmaAllocation allocation);
  5706. void RecordFreeMemoryPages(uint32_t frameIndex,
  5707. uint64_t allocationCount,
  5708. const VmaAllocation* pAllocations);
  5709. void RecordSetAllocationUserData(uint32_t frameIndex,
  5710. VmaAllocation allocation,
  5711. const void* pUserData);
  5712. void RecordCreateLostAllocation(uint32_t frameIndex,
  5713. VmaAllocation allocation);
  5714. void RecordMapMemory(uint32_t frameIndex,
  5715. VmaAllocation allocation);
  5716. void RecordUnmapMemory(uint32_t frameIndex,
  5717. VmaAllocation allocation);
  5718. void RecordFlushAllocation(uint32_t frameIndex,
  5719. VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size);
  5720. void RecordInvalidateAllocation(uint32_t frameIndex,
  5721. VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size);
  5722. void RecordCreateBuffer(uint32_t frameIndex,
  5723. const VkBufferCreateInfo& bufCreateInfo,
  5724. const VmaAllocationCreateInfo& allocCreateInfo,
  5725. VmaAllocation allocation);
  5726. void RecordCreateImage(uint32_t frameIndex,
  5727. const VkImageCreateInfo& imageCreateInfo,
  5728. const VmaAllocationCreateInfo& allocCreateInfo,
  5729. VmaAllocation allocation);
  5730. void RecordDestroyBuffer(uint32_t frameIndex,
  5731. VmaAllocation allocation);
  5732. void RecordDestroyImage(uint32_t frameIndex,
  5733. VmaAllocation allocation);
  5734. void RecordTouchAllocation(uint32_t frameIndex,
  5735. VmaAllocation allocation);
  5736. void RecordGetAllocationInfo(uint32_t frameIndex,
  5737. VmaAllocation allocation);
  5738. void RecordMakePoolAllocationsLost(uint32_t frameIndex,
  5739. VmaPool pool);
  5740. void RecordDefragmentationBegin(uint32_t frameIndex,
  5741. const VmaDefragmentationInfo2& info,
  5742. VmaDefragmentationContext ctx);
  5743. void RecordDefragmentationEnd(uint32_t frameIndex,
  5744. VmaDefragmentationContext ctx);
  5745. void RecordSetPoolName(uint32_t frameIndex,
  5746. VmaPool pool,
  5747. const char* name);
  5748. private:
  5749. struct CallParams
  5750. {
  5751. uint32_t threadId;
  5752. double time;
  5753. };
  5754. class UserDataString
  5755. {
  5756. public:
  5757. UserDataString(VmaAllocationCreateFlags allocFlags, const void* pUserData);
  5758. const char* GetString() const { return m_Str; }
  5759. private:
  5760. char m_PtrStr[17];
  5761. const char* m_Str;
  5762. };
  5763. bool m_UseMutex;
  5764. VmaRecordFlags m_Flags;
  5765. FILE* m_File;
  5766. VMA_MUTEX m_FileMutex;
  5767. int64_t m_Freq;
  5768. int64_t m_StartCounter;
  5769. void GetBasicParams(CallParams& outParams);
  5770. // T must be a pointer type, e.g. VmaAllocation, VmaPool.
  5771. template<typename T>
  5772. void PrintPointerList(uint64_t count, const T* pItems)
  5773. {
  5774. if(count)
  5775. {
  5776. fprintf(m_File, "%p", pItems[0]);
  5777. for(uint64_t i = 1; i < count; ++i)
  5778. {
  5779. fprintf(m_File, " %p", pItems[i]);
  5780. }
  5781. }
  5782. }
  5783. void PrintPointerList(uint64_t count, const VmaAllocation* pItems);
  5784. void Flush();
  5785. };
  5786. #endif // #if VMA_RECORDING_ENABLED
  5787. /*
  5788. Thread-safe wrapper over VmaPoolAllocator free list, for allocation of VmaAllocation_T objects.
  5789. */
  5790. class VmaAllocationObjectAllocator
  5791. {
  5792. VMA_CLASS_NO_COPY(VmaAllocationObjectAllocator)
  5793. public:
  5794. VmaAllocationObjectAllocator(const VkAllocationCallbacks* pAllocationCallbacks);
  5795. VmaAllocation Allocate();
  5796. void Free(VmaAllocation hAlloc);
  5797. private:
  5798. VMA_MUTEX m_Mutex;
  5799. VmaPoolAllocator<VmaAllocation_T> m_Allocator;
  5800. };
  5801. struct VmaCurrentBudgetData
  5802. {
  5803. VMA_ATOMIC_UINT64 m_BlockBytes[VK_MAX_MEMORY_HEAPS];
  5804. VMA_ATOMIC_UINT64 m_AllocationBytes[VK_MAX_MEMORY_HEAPS];
  5805. #if VMA_MEMORY_BUDGET
  5806. VMA_ATOMIC_UINT32 m_OperationsSinceBudgetFetch;
  5807. VMA_RW_MUTEX m_BudgetMutex;
  5808. uint64_t m_VulkanUsage[VK_MAX_MEMORY_HEAPS];
  5809. uint64_t m_VulkanBudget[VK_MAX_MEMORY_HEAPS];
  5810. uint64_t m_BlockBytesAtBudgetFetch[VK_MAX_MEMORY_HEAPS];
  5811. #endif // #if VMA_MEMORY_BUDGET
  5812. VmaCurrentBudgetData()
  5813. {
  5814. for(uint32_t heapIndex = 0; heapIndex < VK_MAX_MEMORY_HEAPS; ++heapIndex)
  5815. {
  5816. m_BlockBytes[heapIndex] = 0;
  5817. m_AllocationBytes[heapIndex] = 0;
  5818. #if VMA_MEMORY_BUDGET
  5819. m_VulkanUsage[heapIndex] = 0;
  5820. m_VulkanBudget[heapIndex] = 0;
  5821. m_BlockBytesAtBudgetFetch[heapIndex] = 0;
  5822. #endif
  5823. }
  5824. #if VMA_MEMORY_BUDGET
  5825. m_OperationsSinceBudgetFetch = 0;
  5826. #endif
  5827. }
  5828. void AddAllocation(uint32_t heapIndex, VkDeviceSize allocationSize)
  5829. {
  5830. m_AllocationBytes[heapIndex] += allocationSize;
  5831. #if VMA_MEMORY_BUDGET
  5832. ++m_OperationsSinceBudgetFetch;
  5833. #endif
  5834. }
  5835. void RemoveAllocation(uint32_t heapIndex, VkDeviceSize allocationSize)
  5836. {
  5837. VMA_ASSERT(m_AllocationBytes[heapIndex] >= allocationSize); // DELME
  5838. m_AllocationBytes[heapIndex] -= allocationSize;
  5839. #if VMA_MEMORY_BUDGET
  5840. ++m_OperationsSinceBudgetFetch;
  5841. #endif
  5842. }
  5843. };
  5844. // Main allocator object.
  5845. struct VmaAllocator_T
  5846. {
  5847. VMA_CLASS_NO_COPY(VmaAllocator_T)
  5848. public:
  5849. bool m_UseMutex;
  5850. uint32_t m_VulkanApiVersion;
  5851. bool m_UseKhrDedicatedAllocation; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0).
  5852. bool m_UseKhrBindMemory2; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0).
  5853. bool m_UseExtMemoryBudget;
  5854. VkDevice m_hDevice;
  5855. VkInstance m_hInstance;
  5856. bool m_AllocationCallbacksSpecified;
  5857. VkAllocationCallbacks m_AllocationCallbacks;
  5858. VmaDeviceMemoryCallbacks m_DeviceMemoryCallbacks;
  5859. VmaAllocationObjectAllocator m_AllocationObjectAllocator;
  5860. // Each bit (1 << i) is set if HeapSizeLimit is enabled for that heap, so cannot allocate more than the heap size.
  5861. uint32_t m_HeapSizeLimitMask;
  5862. VkPhysicalDeviceProperties m_PhysicalDeviceProperties;
  5863. VkPhysicalDeviceMemoryProperties m_MemProps;
  5864. // Default pools.
  5865. VmaBlockVector* m_pBlockVectors[VK_MAX_MEMORY_TYPES];
  5866. // Each vector is sorted by memory (handle value).
  5867. typedef VmaVector< VmaAllocation, VmaStlAllocator<VmaAllocation> > AllocationVectorType;
  5868. AllocationVectorType* m_pDedicatedAllocations[VK_MAX_MEMORY_TYPES];
  5869. VMA_RW_MUTEX m_DedicatedAllocationsMutex[VK_MAX_MEMORY_TYPES];
  5870. VmaCurrentBudgetData m_Budget;
  5871. VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo);
  5872. VkResult Init(const VmaAllocatorCreateInfo* pCreateInfo);
  5873. ~VmaAllocator_T();
  5874. const VkAllocationCallbacks* GetAllocationCallbacks() const
  5875. {
  5876. return m_AllocationCallbacksSpecified ? &m_AllocationCallbacks : 0;
  5877. }
  5878. const VmaVulkanFunctions& GetVulkanFunctions() const
  5879. {
  5880. return m_VulkanFunctions;
  5881. }
  5882. VkDeviceSize GetBufferImageGranularity() const
  5883. {
  5884. return VMA_MAX(
  5885. static_cast<VkDeviceSize>(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY),
  5886. m_PhysicalDeviceProperties.limits.bufferImageGranularity);
  5887. }
  5888. uint32_t GetMemoryHeapCount() const { return m_MemProps.memoryHeapCount; }
  5889. uint32_t GetMemoryTypeCount() const { return m_MemProps.memoryTypeCount; }
  5890. uint32_t MemoryTypeIndexToHeapIndex(uint32_t memTypeIndex) const
  5891. {
  5892. VMA_ASSERT(memTypeIndex < m_MemProps.memoryTypeCount);
  5893. return m_MemProps.memoryTypes[memTypeIndex].heapIndex;
  5894. }
  5895. // True when specific memory type is HOST_VISIBLE but not HOST_COHERENT.
  5896. bool IsMemoryTypeNonCoherent(uint32_t memTypeIndex) const
  5897. {
  5898. return (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) ==
  5899. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  5900. }
  5901. // Minimum alignment for all allocations in specific memory type.
  5902. VkDeviceSize GetMemoryTypeMinAlignment(uint32_t memTypeIndex) const
  5903. {
  5904. return IsMemoryTypeNonCoherent(memTypeIndex) ?
  5905. VMA_MAX((VkDeviceSize)VMA_DEBUG_ALIGNMENT, m_PhysicalDeviceProperties.limits.nonCoherentAtomSize) :
  5906. (VkDeviceSize)VMA_DEBUG_ALIGNMENT;
  5907. }
  5908. bool IsIntegratedGpu() const
  5909. {
  5910. return m_PhysicalDeviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
  5911. }
  5912. #if VMA_RECORDING_ENABLED
  5913. VmaRecorder* GetRecorder() const { return m_pRecorder; }
  5914. #endif
  5915. void GetBufferMemoryRequirements(
  5916. VkBuffer hBuffer,
  5917. VkMemoryRequirements& memReq,
  5918. bool& requiresDedicatedAllocation,
  5919. bool& prefersDedicatedAllocation) const;
  5920. void GetImageMemoryRequirements(
  5921. VkImage hImage,
  5922. VkMemoryRequirements& memReq,
  5923. bool& requiresDedicatedAllocation,
  5924. bool& prefersDedicatedAllocation) const;
  5925. // Main allocation function.
  5926. VkResult AllocateMemory(
  5927. const VkMemoryRequirements& vkMemReq,
  5928. bool requiresDedicatedAllocation,
  5929. bool prefersDedicatedAllocation,
  5930. VkBuffer dedicatedBuffer,
  5931. VkImage dedicatedImage,
  5932. const VmaAllocationCreateInfo& createInfo,
  5933. VmaSuballocationType suballocType,
  5934. size_t allocationCount,
  5935. VmaAllocation* pAllocations);
  5936. // Main deallocation function.
  5937. void FreeMemory(
  5938. size_t allocationCount,
  5939. const VmaAllocation* pAllocations);
  5940. VkResult ResizeAllocation(
  5941. const VmaAllocation alloc,
  5942. VkDeviceSize newSize);
  5943. void CalculateStats(VmaStats* pStats);
  5944. void GetBudget(
  5945. VmaBudget* outBudget, uint32_t firstHeap, uint32_t heapCount);
  5946. #if VMA_STATS_STRING_ENABLED
  5947. void PrintDetailedMap(class VmaJsonWriter& json);
  5948. #endif
  5949. VkResult DefragmentationBegin(
  5950. const VmaDefragmentationInfo2& info,
  5951. VmaDefragmentationStats* pStats,
  5952. VmaDefragmentationContext* pContext);
  5953. VkResult DefragmentationEnd(
  5954. VmaDefragmentationContext context);
  5955. void GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo);
  5956. bool TouchAllocation(VmaAllocation hAllocation);
  5957. VkResult CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool);
  5958. void DestroyPool(VmaPool pool);
  5959. void GetPoolStats(VmaPool pool, VmaPoolStats* pPoolStats);
  5960. void SetCurrentFrameIndex(uint32_t frameIndex);
  5961. uint32_t GetCurrentFrameIndex() const { return m_CurrentFrameIndex.load(); }
  5962. void MakePoolAllocationsLost(
  5963. VmaPool hPool,
  5964. size_t* pLostAllocationCount);
  5965. VkResult CheckPoolCorruption(VmaPool hPool);
  5966. VkResult CheckCorruption(uint32_t memoryTypeBits);
  5967. void CreateLostAllocation(VmaAllocation* pAllocation);
  5968. // Call to Vulkan function vkAllocateMemory with accompanying bookkeeping.
  5969. VkResult AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory);
  5970. // Call to Vulkan function vkFreeMemory with accompanying bookkeeping.
  5971. void FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory);
  5972. // Call to Vulkan function vkBindBufferMemory or vkBindBufferMemory2KHR.
  5973. VkResult BindVulkanBuffer(
  5974. VkDeviceMemory memory,
  5975. VkDeviceSize memoryOffset,
  5976. VkBuffer buffer,
  5977. const void* pNext);
  5978. // Call to Vulkan function vkBindImageMemory or vkBindImageMemory2KHR.
  5979. VkResult BindVulkanImage(
  5980. VkDeviceMemory memory,
  5981. VkDeviceSize memoryOffset,
  5982. VkImage image,
  5983. const void* pNext);
  5984. VkResult Map(VmaAllocation hAllocation, void** ppData);
  5985. void Unmap(VmaAllocation hAllocation);
  5986. VkResult BindBufferMemory(
  5987. VmaAllocation hAllocation,
  5988. VkDeviceSize allocationLocalOffset,
  5989. VkBuffer hBuffer,
  5990. const void* pNext);
  5991. VkResult BindImageMemory(
  5992. VmaAllocation hAllocation,
  5993. VkDeviceSize allocationLocalOffset,
  5994. VkImage hImage,
  5995. const void* pNext);
  5996. void FlushOrInvalidateAllocation(
  5997. VmaAllocation hAllocation,
  5998. VkDeviceSize offset, VkDeviceSize size,
  5999. VMA_CACHE_OPERATION op);
  6000. void FillAllocation(const VmaAllocation hAllocation, uint8_t pattern);
  6001. /*
  6002. Returns bit mask of memory types that can support defragmentation on GPU as
  6003. they support creation of required buffer for copy operations.
  6004. */
  6005. uint32_t GetGpuDefragmentationMemoryTypeBits();
  6006. private:
  6007. VkDeviceSize m_PreferredLargeHeapBlockSize;
  6008. VkPhysicalDevice m_PhysicalDevice;
  6009. VMA_ATOMIC_UINT32 m_CurrentFrameIndex;
  6010. VMA_ATOMIC_UINT32 m_GpuDefragmentationMemoryTypeBits; // UINT32_MAX means uninitialized.
  6011. VMA_RW_MUTEX m_PoolsMutex;
  6012. // Protected by m_PoolsMutex. Sorted by pointer value.
  6013. VmaVector<VmaPool, VmaStlAllocator<VmaPool> > m_Pools;
  6014. uint32_t m_NextPoolId;
  6015. VmaVulkanFunctions m_VulkanFunctions;
  6016. #if VMA_RECORDING_ENABLED
  6017. VmaRecorder* m_pRecorder;
  6018. #endif
  6019. void ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions);
  6020. VkDeviceSize CalcPreferredBlockSize(uint32_t memTypeIndex);
  6021. VkResult AllocateMemoryOfType(
  6022. VkDeviceSize size,
  6023. VkDeviceSize alignment,
  6024. bool dedicatedAllocation,
  6025. VkBuffer dedicatedBuffer,
  6026. VkImage dedicatedImage,
  6027. const VmaAllocationCreateInfo& createInfo,
  6028. uint32_t memTypeIndex,
  6029. VmaSuballocationType suballocType,
  6030. size_t allocationCount,
  6031. VmaAllocation* pAllocations);
  6032. // Helper function only to be used inside AllocateDedicatedMemory.
  6033. VkResult AllocateDedicatedMemoryPage(
  6034. VkDeviceSize size,
  6035. VmaSuballocationType suballocType,
  6036. uint32_t memTypeIndex,
  6037. const VkMemoryAllocateInfo& allocInfo,
  6038. bool map,
  6039. bool isUserDataString,
  6040. void* pUserData,
  6041. VmaAllocation* pAllocation);
  6042. // Allocates and registers new VkDeviceMemory specifically for dedicated allocations.
  6043. VkResult AllocateDedicatedMemory(
  6044. VkDeviceSize size,
  6045. VmaSuballocationType suballocType,
  6046. uint32_t memTypeIndex,
  6047. bool withinBudget,
  6048. bool map,
  6049. bool isUserDataString,
  6050. void* pUserData,
  6051. VkBuffer dedicatedBuffer,
  6052. VkImage dedicatedImage,
  6053. size_t allocationCount,
  6054. VmaAllocation* pAllocations);
  6055. void FreeDedicatedMemory(const VmaAllocation allocation);
  6056. /*
  6057. Calculates and returns bit mask of memory types that can support defragmentation
  6058. on GPU as they support creation of required buffer for copy operations.
  6059. */
  6060. uint32_t CalculateGpuDefragmentationMemoryTypeBits() const;
  6061. #if VMA_MEMORY_BUDGET
  6062. void UpdateVulkanBudget();
  6063. #endif // #if VMA_MEMORY_BUDGET
  6064. };
  6065. ////////////////////////////////////////////////////////////////////////////////
  6066. // Memory allocation #2 after VmaAllocator_T definition
  6067. static void* VmaMalloc(VmaAllocator hAllocator, size_t size, size_t alignment)
  6068. {
  6069. return VmaMalloc(&hAllocator->m_AllocationCallbacks, size, alignment);
  6070. }
  6071. static void VmaFree(VmaAllocator hAllocator, void* ptr)
  6072. {
  6073. VmaFree(&hAllocator->m_AllocationCallbacks, ptr);
  6074. }
  6075. template<typename T>
  6076. static T* VmaAllocate(VmaAllocator hAllocator)
  6077. {
  6078. return (T*)VmaMalloc(hAllocator, sizeof(T), VMA_ALIGN_OF(T));
  6079. }
  6080. template<typename T>
  6081. static T* VmaAllocateArray(VmaAllocator hAllocator, size_t count)
  6082. {
  6083. return (T*)VmaMalloc(hAllocator, sizeof(T) * count, VMA_ALIGN_OF(T));
  6084. }
  6085. template<typename T>
  6086. static void vma_delete(VmaAllocator hAllocator, T* ptr)
  6087. {
  6088. if(ptr != VMA_NULL)
  6089. {
  6090. ptr->~T();
  6091. VmaFree(hAllocator, ptr);
  6092. }
  6093. }
  6094. template<typename T>
  6095. static void vma_delete_array(VmaAllocator hAllocator, T* ptr, size_t count)
  6096. {
  6097. if(ptr != VMA_NULL)
  6098. {
  6099. for(size_t i = count; i--; )
  6100. ptr[i].~T();
  6101. VmaFree(hAllocator, ptr);
  6102. }
  6103. }
  6104. ////////////////////////////////////////////////////////////////////////////////
  6105. // VmaStringBuilder
  6106. #if VMA_STATS_STRING_ENABLED
  6107. class VmaStringBuilder
  6108. {
  6109. public:
  6110. VmaStringBuilder(VmaAllocator alloc) : m_Data(VmaStlAllocator<char>(alloc->GetAllocationCallbacks())) { }
  6111. size_t GetLength() const { return m_Data.size(); }
  6112. const char* GetData() const { return m_Data.data(); }
  6113. void Add(char ch) { m_Data.push_back(ch); }
  6114. void Add(const char* pStr);
  6115. void AddNewLine() { Add('\n'); }
  6116. void AddNumber(uint32_t num);
  6117. void AddNumber(uint64_t num);
  6118. void AddPointer(const void* ptr);
  6119. private:
  6120. VmaVector< char, VmaStlAllocator<char> > m_Data;
  6121. };
  6122. void VmaStringBuilder::Add(const char* pStr)
  6123. {
  6124. const size_t strLen = strlen(pStr);
  6125. if(strLen > 0)
  6126. {
  6127. const size_t oldCount = m_Data.size();
  6128. m_Data.resize(oldCount + strLen);
  6129. memcpy(m_Data.data() + oldCount, pStr, strLen);
  6130. }
  6131. }
  6132. void VmaStringBuilder::AddNumber(uint32_t num)
  6133. {
  6134. char buf[11];
  6135. buf[10] = '\0';
  6136. char *p = &buf[10];
  6137. do
  6138. {
  6139. *--p = '0' + (num % 10);
  6140. num /= 10;
  6141. }
  6142. while(num);
  6143. Add(p);
  6144. }
  6145. void VmaStringBuilder::AddNumber(uint64_t num)
  6146. {
  6147. char buf[21];
  6148. buf[20] = '\0';
  6149. char *p = &buf[20];
  6150. do
  6151. {
  6152. *--p = '0' + (num % 10);
  6153. num /= 10;
  6154. }
  6155. while(num);
  6156. Add(p);
  6157. }
  6158. void VmaStringBuilder::AddPointer(const void* ptr)
  6159. {
  6160. char buf[21];
  6161. VmaPtrToStr(buf, sizeof(buf), ptr);
  6162. Add(buf);
  6163. }
  6164. #endif // #if VMA_STATS_STRING_ENABLED
  6165. ////////////////////////////////////////////////////////////////////////////////
  6166. // VmaJsonWriter
  6167. #if VMA_STATS_STRING_ENABLED
  6168. class VmaJsonWriter
  6169. {
  6170. VMA_CLASS_NO_COPY(VmaJsonWriter)
  6171. public:
  6172. VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb);
  6173. ~VmaJsonWriter();
  6174. void BeginObject(bool singleLine = false);
  6175. void EndObject();
  6176. void BeginArray(bool singleLine = false);
  6177. void EndArray();
  6178. void WriteString(const char* pStr);
  6179. void BeginString(const char* pStr = VMA_NULL);
  6180. void ContinueString(const char* pStr);
  6181. void ContinueString(uint32_t n);
  6182. void ContinueString(uint64_t n);
  6183. void ContinueString_Pointer(const void* ptr);
  6184. void EndString(const char* pStr = VMA_NULL);
  6185. void WriteNumber(uint32_t n);
  6186. void WriteNumber(uint64_t n);
  6187. void WriteBool(bool b);
  6188. void WriteNull();
  6189. private:
  6190. static const char* const INDENT;
  6191. enum COLLECTION_TYPE
  6192. {
  6193. COLLECTION_TYPE_OBJECT,
  6194. COLLECTION_TYPE_ARRAY,
  6195. };
  6196. struct StackItem
  6197. {
  6198. COLLECTION_TYPE type;
  6199. uint32_t valueCount;
  6200. bool singleLineMode;
  6201. };
  6202. VmaStringBuilder& m_SB;
  6203. VmaVector< StackItem, VmaStlAllocator<StackItem> > m_Stack;
  6204. bool m_InsideString;
  6205. void BeginValue(bool isString);
  6206. void WriteIndent(bool oneLess = false);
  6207. };
  6208. const char* const VmaJsonWriter::INDENT = " ";
  6209. VmaJsonWriter::VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb) :
  6210. m_SB(sb),
  6211. m_Stack(VmaStlAllocator<StackItem>(pAllocationCallbacks)),
  6212. m_InsideString(false)
  6213. {
  6214. }
  6215. VmaJsonWriter::~VmaJsonWriter()
  6216. {
  6217. VMA_ASSERT(!m_InsideString);
  6218. VMA_ASSERT(m_Stack.empty());
  6219. }
  6220. void VmaJsonWriter::BeginObject(bool singleLine)
  6221. {
  6222. VMA_ASSERT(!m_InsideString);
  6223. BeginValue(false);
  6224. m_SB.Add('{');
  6225. StackItem item;
  6226. item.type = COLLECTION_TYPE_OBJECT;
  6227. item.valueCount = 0;
  6228. item.singleLineMode = singleLine;
  6229. m_Stack.push_back(item);
  6230. }
  6231. void VmaJsonWriter::EndObject()
  6232. {
  6233. VMA_ASSERT(!m_InsideString);
  6234. WriteIndent(true);
  6235. m_SB.Add('}');
  6236. VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_OBJECT);
  6237. m_Stack.pop_back();
  6238. }
  6239. void VmaJsonWriter::BeginArray(bool singleLine)
  6240. {
  6241. VMA_ASSERT(!m_InsideString);
  6242. BeginValue(false);
  6243. m_SB.Add('[');
  6244. StackItem item;
  6245. item.type = COLLECTION_TYPE_ARRAY;
  6246. item.valueCount = 0;
  6247. item.singleLineMode = singleLine;
  6248. m_Stack.push_back(item);
  6249. }
  6250. void VmaJsonWriter::EndArray()
  6251. {
  6252. VMA_ASSERT(!m_InsideString);
  6253. WriteIndent(true);
  6254. m_SB.Add(']');
  6255. VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_ARRAY);
  6256. m_Stack.pop_back();
  6257. }
  6258. void VmaJsonWriter::WriteString(const char* pStr)
  6259. {
  6260. BeginString(pStr);
  6261. EndString();
  6262. }
  6263. void VmaJsonWriter::BeginString(const char* pStr)
  6264. {
  6265. VMA_ASSERT(!m_InsideString);
  6266. BeginValue(true);
  6267. m_SB.Add('"');
  6268. m_InsideString = true;
  6269. if(pStr != VMA_NULL && pStr[0] != '\0')
  6270. {
  6271. ContinueString(pStr);
  6272. }
  6273. }
  6274. void VmaJsonWriter::ContinueString(const char* pStr)
  6275. {
  6276. VMA_ASSERT(m_InsideString);
  6277. const size_t strLen = strlen(pStr);
  6278. for(size_t i = 0; i < strLen; ++i)
  6279. {
  6280. char ch = pStr[i];
  6281. if(ch == '\\')
  6282. {
  6283. m_SB.Add("\\\\");
  6284. }
  6285. else if(ch == '"')
  6286. {
  6287. m_SB.Add("\\\"");
  6288. }
  6289. else if(ch >= 32)
  6290. {
  6291. m_SB.Add(ch);
  6292. }
  6293. else switch(ch)
  6294. {
  6295. case '\b':
  6296. m_SB.Add("\\b");
  6297. break;
  6298. case '\f':
  6299. m_SB.Add("\\f");
  6300. break;
  6301. case '\n':
  6302. m_SB.Add("\\n");
  6303. break;
  6304. case '\r':
  6305. m_SB.Add("\\r");
  6306. break;
  6307. case '\t':
  6308. m_SB.Add("\\t");
  6309. break;
  6310. default:
  6311. VMA_ASSERT(0 && "Character not currently supported.");
  6312. break;
  6313. }
  6314. }
  6315. }
  6316. void VmaJsonWriter::ContinueString(uint32_t n)
  6317. {
  6318. VMA_ASSERT(m_InsideString);
  6319. m_SB.AddNumber(n);
  6320. }
  6321. void VmaJsonWriter::ContinueString(uint64_t n)
  6322. {
  6323. VMA_ASSERT(m_InsideString);
  6324. m_SB.AddNumber(n);
  6325. }
  6326. void VmaJsonWriter::ContinueString_Pointer(const void* ptr)
  6327. {
  6328. VMA_ASSERT(m_InsideString);
  6329. m_SB.AddPointer(ptr);
  6330. }
  6331. void VmaJsonWriter::EndString(const char* pStr)
  6332. {
  6333. VMA_ASSERT(m_InsideString);
  6334. if(pStr != VMA_NULL && pStr[0] != '\0')
  6335. {
  6336. ContinueString(pStr);
  6337. }
  6338. m_SB.Add('"');
  6339. m_InsideString = false;
  6340. }
  6341. void VmaJsonWriter::WriteNumber(uint32_t n)
  6342. {
  6343. VMA_ASSERT(!m_InsideString);
  6344. BeginValue(false);
  6345. m_SB.AddNumber(n);
  6346. }
  6347. void VmaJsonWriter::WriteNumber(uint64_t n)
  6348. {
  6349. VMA_ASSERT(!m_InsideString);
  6350. BeginValue(false);
  6351. m_SB.AddNumber(n);
  6352. }
  6353. void VmaJsonWriter::WriteBool(bool b)
  6354. {
  6355. VMA_ASSERT(!m_InsideString);
  6356. BeginValue(false);
  6357. m_SB.Add(b ? "true" : "false");
  6358. }
  6359. void VmaJsonWriter::WriteNull()
  6360. {
  6361. VMA_ASSERT(!m_InsideString);
  6362. BeginValue(false);
  6363. m_SB.Add("null");
  6364. }
  6365. void VmaJsonWriter::BeginValue(bool isString)
  6366. {
  6367. if(!m_Stack.empty())
  6368. {
  6369. StackItem& currItem = m_Stack.back();
  6370. if(currItem.type == COLLECTION_TYPE_OBJECT &&
  6371. currItem.valueCount % 2 == 0)
  6372. {
  6373. VMA_ASSERT(isString);
  6374. }
  6375. if(currItem.type == COLLECTION_TYPE_OBJECT &&
  6376. currItem.valueCount % 2 != 0)
  6377. {
  6378. m_SB.Add(": ");
  6379. }
  6380. else if(currItem.valueCount > 0)
  6381. {
  6382. m_SB.Add(", ");
  6383. WriteIndent();
  6384. }
  6385. else
  6386. {
  6387. WriteIndent();
  6388. }
  6389. ++currItem.valueCount;
  6390. }
  6391. }
  6392. void VmaJsonWriter::WriteIndent(bool oneLess)
  6393. {
  6394. if(!m_Stack.empty() && !m_Stack.back().singleLineMode)
  6395. {
  6396. m_SB.AddNewLine();
  6397. size_t count = m_Stack.size();
  6398. if(count > 0 && oneLess)
  6399. {
  6400. --count;
  6401. }
  6402. for(size_t i = 0; i < count; ++i)
  6403. {
  6404. m_SB.Add(INDENT);
  6405. }
  6406. }
  6407. }
  6408. #endif // #if VMA_STATS_STRING_ENABLED
  6409. ////////////////////////////////////////////////////////////////////////////////
  6410. void VmaAllocation_T::SetUserData(VmaAllocator hAllocator, void* pUserData)
  6411. {
  6412. if(IsUserDataString())
  6413. {
  6414. VMA_ASSERT(pUserData == VMA_NULL || pUserData != m_pUserData);
  6415. FreeUserDataString(hAllocator);
  6416. if(pUserData != VMA_NULL)
  6417. {
  6418. m_pUserData = VmaCreateStringCopy(hAllocator->GetAllocationCallbacks(), (const char*)pUserData);
  6419. }
  6420. }
  6421. else
  6422. {
  6423. m_pUserData = pUserData;
  6424. }
  6425. }
  6426. void VmaAllocation_T::ChangeBlockAllocation(
  6427. VmaAllocator hAllocator,
  6428. VmaDeviceMemoryBlock* block,
  6429. VkDeviceSize offset)
  6430. {
  6431. VMA_ASSERT(block != VMA_NULL);
  6432. VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK);
  6433. // Move mapping reference counter from old block to new block.
  6434. if(block != m_BlockAllocation.m_Block)
  6435. {
  6436. uint32_t mapRefCount = m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP;
  6437. if(IsPersistentMap())
  6438. ++mapRefCount;
  6439. m_BlockAllocation.m_Block->Unmap(hAllocator, mapRefCount);
  6440. block->Map(hAllocator, mapRefCount, VMA_NULL);
  6441. }
  6442. m_BlockAllocation.m_Block = block;
  6443. m_BlockAllocation.m_Offset = offset;
  6444. }
  6445. void VmaAllocation_T::ChangeOffset(VkDeviceSize newOffset)
  6446. {
  6447. VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK);
  6448. m_BlockAllocation.m_Offset = newOffset;
  6449. }
  6450. VkDeviceSize VmaAllocation_T::GetOffset() const
  6451. {
  6452. switch(m_Type)
  6453. {
  6454. case ALLOCATION_TYPE_BLOCK:
  6455. return m_BlockAllocation.m_Offset;
  6456. case ALLOCATION_TYPE_DEDICATED:
  6457. return 0;
  6458. default:
  6459. VMA_ASSERT(0);
  6460. return 0;
  6461. }
  6462. }
  6463. VkDeviceMemory VmaAllocation_T::GetMemory() const
  6464. {
  6465. switch(m_Type)
  6466. {
  6467. case ALLOCATION_TYPE_BLOCK:
  6468. return m_BlockAllocation.m_Block->GetDeviceMemory();
  6469. case ALLOCATION_TYPE_DEDICATED:
  6470. return m_DedicatedAllocation.m_hMemory;
  6471. default:
  6472. VMA_ASSERT(0);
  6473. return VK_NULL_HANDLE;
  6474. }
  6475. }
  6476. void* VmaAllocation_T::GetMappedData() const
  6477. {
  6478. switch(m_Type)
  6479. {
  6480. case ALLOCATION_TYPE_BLOCK:
  6481. if(m_MapCount != 0)
  6482. {
  6483. void* pBlockData = m_BlockAllocation.m_Block->GetMappedData();
  6484. VMA_ASSERT(pBlockData != VMA_NULL);
  6485. return (char*)pBlockData + m_BlockAllocation.m_Offset;
  6486. }
  6487. else
  6488. {
  6489. return VMA_NULL;
  6490. }
  6491. break;
  6492. case ALLOCATION_TYPE_DEDICATED:
  6493. VMA_ASSERT((m_DedicatedAllocation.m_pMappedData != VMA_NULL) == (m_MapCount != 0));
  6494. return m_DedicatedAllocation.m_pMappedData;
  6495. default:
  6496. VMA_ASSERT(0);
  6497. return VMA_NULL;
  6498. }
  6499. }
  6500. bool VmaAllocation_T::CanBecomeLost() const
  6501. {
  6502. switch(m_Type)
  6503. {
  6504. case ALLOCATION_TYPE_BLOCK:
  6505. return m_BlockAllocation.m_CanBecomeLost;
  6506. case ALLOCATION_TYPE_DEDICATED:
  6507. return false;
  6508. default:
  6509. VMA_ASSERT(0);
  6510. return false;
  6511. }
  6512. }
  6513. bool VmaAllocation_T::MakeLost(uint32_t currentFrameIndex, uint32_t frameInUseCount)
  6514. {
  6515. VMA_ASSERT(CanBecomeLost());
  6516. /*
  6517. Warning: This is a carefully designed algorithm.
  6518. Do not modify unless you really know what you're doing :)
  6519. */
  6520. uint32_t localLastUseFrameIndex = GetLastUseFrameIndex();
  6521. for(;;)
  6522. {
  6523. if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST)
  6524. {
  6525. VMA_ASSERT(0);
  6526. return false;
  6527. }
  6528. else if(localLastUseFrameIndex + frameInUseCount >= currentFrameIndex)
  6529. {
  6530. return false;
  6531. }
  6532. else // Last use time earlier than current time.
  6533. {
  6534. if(CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, VMA_FRAME_INDEX_LOST))
  6535. {
  6536. // Setting hAllocation.LastUseFrameIndex atomic to VMA_FRAME_INDEX_LOST is enough to mark it as LOST.
  6537. // Calling code just needs to unregister this allocation in owning VmaDeviceMemoryBlock.
  6538. return true;
  6539. }
  6540. }
  6541. }
  6542. }
  6543. #if VMA_STATS_STRING_ENABLED
  6544. // Correspond to values of enum VmaSuballocationType.
  6545. static const char* VMA_SUBALLOCATION_TYPE_NAMES[] = {
  6546. "FREE",
  6547. "UNKNOWN",
  6548. "BUFFER",
  6549. "IMAGE_UNKNOWN",
  6550. "IMAGE_LINEAR",
  6551. "IMAGE_OPTIMAL",
  6552. };
  6553. void VmaAllocation_T::PrintParameters(class VmaJsonWriter& json) const
  6554. {
  6555. json.WriteString("Type");
  6556. json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[m_SuballocationType]);
  6557. json.WriteString("Size");
  6558. json.WriteNumber(m_Size);
  6559. if(m_pUserData != VMA_NULL)
  6560. {
  6561. json.WriteString("UserData");
  6562. if(IsUserDataString())
  6563. {
  6564. json.WriteString((const char*)m_pUserData);
  6565. }
  6566. else
  6567. {
  6568. json.BeginString();
  6569. json.ContinueString_Pointer(m_pUserData);
  6570. json.EndString();
  6571. }
  6572. }
  6573. json.WriteString("CreationFrameIndex");
  6574. json.WriteNumber(m_CreationFrameIndex);
  6575. json.WriteString("LastUseFrameIndex");
  6576. json.WriteNumber(GetLastUseFrameIndex());
  6577. if(m_BufferImageUsage != 0)
  6578. {
  6579. json.WriteString("Usage");
  6580. json.WriteNumber(m_BufferImageUsage);
  6581. }
  6582. }
  6583. #endif
  6584. void VmaAllocation_T::FreeUserDataString(VmaAllocator hAllocator)
  6585. {
  6586. VMA_ASSERT(IsUserDataString());
  6587. VmaFreeString(hAllocator->GetAllocationCallbacks(), (char*)m_pUserData);
  6588. m_pUserData = VMA_NULL;
  6589. }
  6590. void VmaAllocation_T::BlockAllocMap()
  6591. {
  6592. VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK);
  6593. if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) < 0x7F)
  6594. {
  6595. ++m_MapCount;
  6596. }
  6597. else
  6598. {
  6599. VMA_ASSERT(0 && "Allocation mapped too many times simultaneously.");
  6600. }
  6601. }
  6602. void VmaAllocation_T::BlockAllocUnmap()
  6603. {
  6604. VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK);
  6605. if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) != 0)
  6606. {
  6607. --m_MapCount;
  6608. }
  6609. else
  6610. {
  6611. VMA_ASSERT(0 && "Unmapping allocation not previously mapped.");
  6612. }
  6613. }
  6614. VkResult VmaAllocation_T::DedicatedAllocMap(VmaAllocator hAllocator, void** ppData)
  6615. {
  6616. VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED);
  6617. if(m_MapCount != 0)
  6618. {
  6619. if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) < 0x7F)
  6620. {
  6621. VMA_ASSERT(m_DedicatedAllocation.m_pMappedData != VMA_NULL);
  6622. *ppData = m_DedicatedAllocation.m_pMappedData;
  6623. ++m_MapCount;
  6624. return VK_SUCCESS;
  6625. }
  6626. else
  6627. {
  6628. VMA_ASSERT(0 && "Dedicated allocation mapped too many times simultaneously.");
  6629. return VK_ERROR_MEMORY_MAP_FAILED;
  6630. }
  6631. }
  6632. else
  6633. {
  6634. VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)(
  6635. hAllocator->m_hDevice,
  6636. m_DedicatedAllocation.m_hMemory,
  6637. 0, // offset
  6638. VK_WHOLE_SIZE,
  6639. 0, // flags
  6640. ppData);
  6641. if(result == VK_SUCCESS)
  6642. {
  6643. m_DedicatedAllocation.m_pMappedData = *ppData;
  6644. m_MapCount = 1;
  6645. }
  6646. return result;
  6647. }
  6648. }
  6649. void VmaAllocation_T::DedicatedAllocUnmap(VmaAllocator hAllocator)
  6650. {
  6651. VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED);
  6652. if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) != 0)
  6653. {
  6654. --m_MapCount;
  6655. if(m_MapCount == 0)
  6656. {
  6657. m_DedicatedAllocation.m_pMappedData = VMA_NULL;
  6658. (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(
  6659. hAllocator->m_hDevice,
  6660. m_DedicatedAllocation.m_hMemory);
  6661. }
  6662. }
  6663. else
  6664. {
  6665. VMA_ASSERT(0 && "Unmapping dedicated allocation not previously mapped.");
  6666. }
  6667. }
  6668. #if VMA_STATS_STRING_ENABLED
  6669. static void VmaPrintStatInfo(VmaJsonWriter& json, const VmaStatInfo& stat)
  6670. {
  6671. json.BeginObject();
  6672. json.WriteString("Blocks");
  6673. json.WriteNumber(stat.blockCount);
  6674. json.WriteString("Allocations");
  6675. json.WriteNumber(stat.allocationCount);
  6676. json.WriteString("UnusedRanges");
  6677. json.WriteNumber(stat.unusedRangeCount);
  6678. json.WriteString("UsedBytes");
  6679. json.WriteNumber(stat.usedBytes);
  6680. json.WriteString("UnusedBytes");
  6681. json.WriteNumber(stat.unusedBytes);
  6682. if(stat.allocationCount > 1)
  6683. {
  6684. json.WriteString("AllocationSize");
  6685. json.BeginObject(true);
  6686. json.WriteString("Min");
  6687. json.WriteNumber(stat.allocationSizeMin);
  6688. json.WriteString("Avg");
  6689. json.WriteNumber(stat.allocationSizeAvg);
  6690. json.WriteString("Max");
  6691. json.WriteNumber(stat.allocationSizeMax);
  6692. json.EndObject();
  6693. }
  6694. if(stat.unusedRangeCount > 1)
  6695. {
  6696. json.WriteString("UnusedRangeSize");
  6697. json.BeginObject(true);
  6698. json.WriteString("Min");
  6699. json.WriteNumber(stat.unusedRangeSizeMin);
  6700. json.WriteString("Avg");
  6701. json.WriteNumber(stat.unusedRangeSizeAvg);
  6702. json.WriteString("Max");
  6703. json.WriteNumber(stat.unusedRangeSizeMax);
  6704. json.EndObject();
  6705. }
  6706. json.EndObject();
  6707. }
  6708. #endif // #if VMA_STATS_STRING_ENABLED
  6709. struct VmaSuballocationItemSizeLess
  6710. {
  6711. bool operator()(
  6712. const VmaSuballocationList::iterator lhs,
  6713. const VmaSuballocationList::iterator rhs) const
  6714. {
  6715. return lhs->size < rhs->size;
  6716. }
  6717. bool operator()(
  6718. const VmaSuballocationList::iterator lhs,
  6719. VkDeviceSize rhsSize) const
  6720. {
  6721. return lhs->size < rhsSize;
  6722. }
  6723. };
  6724. ////////////////////////////////////////////////////////////////////////////////
  6725. // class VmaBlockMetadata
  6726. VmaBlockMetadata::VmaBlockMetadata(VmaAllocator hAllocator) :
  6727. m_Size(0),
  6728. m_pAllocationCallbacks(hAllocator->GetAllocationCallbacks())
  6729. {
  6730. }
  6731. #if VMA_STATS_STRING_ENABLED
  6732. void VmaBlockMetadata::PrintDetailedMap_Begin(class VmaJsonWriter& json,
  6733. VkDeviceSize unusedBytes,
  6734. size_t allocationCount,
  6735. size_t unusedRangeCount) const
  6736. {
  6737. json.BeginObject();
  6738. json.WriteString("TotalBytes");
  6739. json.WriteNumber(GetSize());
  6740. json.WriteString("UnusedBytes");
  6741. json.WriteNumber(unusedBytes);
  6742. json.WriteString("Allocations");
  6743. json.WriteNumber((uint64_t)allocationCount);
  6744. json.WriteString("UnusedRanges");
  6745. json.WriteNumber((uint64_t)unusedRangeCount);
  6746. json.WriteString("Suballocations");
  6747. json.BeginArray();
  6748. }
  6749. void VmaBlockMetadata::PrintDetailedMap_Allocation(class VmaJsonWriter& json,
  6750. VkDeviceSize offset,
  6751. VmaAllocation hAllocation) const
  6752. {
  6753. json.BeginObject(true);
  6754. json.WriteString("Offset");
  6755. json.WriteNumber(offset);
  6756. hAllocation->PrintParameters(json);
  6757. json.EndObject();
  6758. }
  6759. void VmaBlockMetadata::PrintDetailedMap_UnusedRange(class VmaJsonWriter& json,
  6760. VkDeviceSize offset,
  6761. VkDeviceSize size) const
  6762. {
  6763. json.BeginObject(true);
  6764. json.WriteString("Offset");
  6765. json.WriteNumber(offset);
  6766. json.WriteString("Type");
  6767. json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[VMA_SUBALLOCATION_TYPE_FREE]);
  6768. json.WriteString("Size");
  6769. json.WriteNumber(size);
  6770. json.EndObject();
  6771. }
  6772. void VmaBlockMetadata::PrintDetailedMap_End(class VmaJsonWriter& json) const
  6773. {
  6774. json.EndArray();
  6775. json.EndObject();
  6776. }
  6777. #endif // #if VMA_STATS_STRING_ENABLED
  6778. ////////////////////////////////////////////////////////////////////////////////
  6779. // class VmaBlockMetadata_Generic
  6780. VmaBlockMetadata_Generic::VmaBlockMetadata_Generic(VmaAllocator hAllocator) :
  6781. VmaBlockMetadata(hAllocator),
  6782. m_FreeCount(0),
  6783. m_SumFreeSize(0),
  6784. m_Suballocations(VmaStlAllocator<VmaSuballocation>(hAllocator->GetAllocationCallbacks())),
  6785. m_FreeSuballocationsBySize(VmaStlAllocator<VmaSuballocationList::iterator>(hAllocator->GetAllocationCallbacks()))
  6786. {
  6787. }
  6788. VmaBlockMetadata_Generic::~VmaBlockMetadata_Generic()
  6789. {
  6790. }
  6791. void VmaBlockMetadata_Generic::Init(VkDeviceSize size)
  6792. {
  6793. VmaBlockMetadata::Init(size);
  6794. m_FreeCount = 1;
  6795. m_SumFreeSize = size;
  6796. VmaSuballocation suballoc = {};
  6797. suballoc.offset = 0;
  6798. suballoc.size = size;
  6799. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  6800. suballoc.hAllocation = VK_NULL_HANDLE;
  6801. VMA_ASSERT(size > VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER);
  6802. m_Suballocations.push_back(suballoc);
  6803. VmaSuballocationList::iterator suballocItem = m_Suballocations.end();
  6804. --suballocItem;
  6805. m_FreeSuballocationsBySize.push_back(suballocItem);
  6806. }
  6807. bool VmaBlockMetadata_Generic::Validate() const
  6808. {
  6809. VMA_VALIDATE(!m_Suballocations.empty());
  6810. // Expected offset of new suballocation as calculated from previous ones.
  6811. VkDeviceSize calculatedOffset = 0;
  6812. // Expected number of free suballocations as calculated from traversing their list.
  6813. uint32_t calculatedFreeCount = 0;
  6814. // Expected sum size of free suballocations as calculated from traversing their list.
  6815. VkDeviceSize calculatedSumFreeSize = 0;
  6816. // Expected number of free suballocations that should be registered in
  6817. // m_FreeSuballocationsBySize calculated from traversing their list.
  6818. size_t freeSuballocationsToRegister = 0;
  6819. // True if previous visited suballocation was free.
  6820. bool prevFree = false;
  6821. for(VmaSuballocationList::const_iterator suballocItem = m_Suballocations.cbegin();
  6822. suballocItem != m_Suballocations.cend();
  6823. ++suballocItem)
  6824. {
  6825. const VmaSuballocation& subAlloc = *suballocItem;
  6826. // Actual offset of this suballocation doesn't match expected one.
  6827. VMA_VALIDATE(subAlloc.offset == calculatedOffset);
  6828. const bool currFree = (subAlloc.type == VMA_SUBALLOCATION_TYPE_FREE);
  6829. // Two adjacent free suballocations are invalid. They should be merged.
  6830. VMA_VALIDATE(!prevFree || !currFree);
  6831. VMA_VALIDATE(currFree == (subAlloc.hAllocation == VK_NULL_HANDLE));
  6832. if(currFree)
  6833. {
  6834. calculatedSumFreeSize += subAlloc.size;
  6835. ++calculatedFreeCount;
  6836. if(subAlloc.size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
  6837. {
  6838. ++freeSuballocationsToRegister;
  6839. }
  6840. // Margin required between allocations - every free space must be at least that large.
  6841. VMA_VALIDATE(subAlloc.size >= VMA_DEBUG_MARGIN);
  6842. }
  6843. else
  6844. {
  6845. VMA_VALIDATE(subAlloc.hAllocation->GetOffset() == subAlloc.offset);
  6846. VMA_VALIDATE(subAlloc.hAllocation->GetSize() == subAlloc.size);
  6847. // Margin required between allocations - previous allocation must be free.
  6848. VMA_VALIDATE(VMA_DEBUG_MARGIN == 0 || prevFree);
  6849. }
  6850. calculatedOffset += subAlloc.size;
  6851. prevFree = currFree;
  6852. }
  6853. // Number of free suballocations registered in m_FreeSuballocationsBySize doesn't
  6854. // match expected one.
  6855. VMA_VALIDATE(m_FreeSuballocationsBySize.size() == freeSuballocationsToRegister);
  6856. VkDeviceSize lastSize = 0;
  6857. for(size_t i = 0; i < m_FreeSuballocationsBySize.size(); ++i)
  6858. {
  6859. VmaSuballocationList::iterator suballocItem = m_FreeSuballocationsBySize[i];
  6860. // Only free suballocations can be registered in m_FreeSuballocationsBySize.
  6861. VMA_VALIDATE(suballocItem->type == VMA_SUBALLOCATION_TYPE_FREE);
  6862. // They must be sorted by size ascending.
  6863. VMA_VALIDATE(suballocItem->size >= lastSize);
  6864. lastSize = suballocItem->size;
  6865. }
  6866. // Check if totals match calculacted values.
  6867. VMA_VALIDATE(ValidateFreeSuballocationList());
  6868. VMA_VALIDATE(calculatedOffset == GetSize());
  6869. VMA_VALIDATE(calculatedSumFreeSize == m_SumFreeSize);
  6870. VMA_VALIDATE(calculatedFreeCount == m_FreeCount);
  6871. return true;
  6872. }
  6873. VkDeviceSize VmaBlockMetadata_Generic::GetUnusedRangeSizeMax() const
  6874. {
  6875. if(!m_FreeSuballocationsBySize.empty())
  6876. {
  6877. return m_FreeSuballocationsBySize.back()->size;
  6878. }
  6879. else
  6880. {
  6881. return 0;
  6882. }
  6883. }
  6884. bool VmaBlockMetadata_Generic::IsEmpty() const
  6885. {
  6886. return (m_Suballocations.size() == 1) && (m_FreeCount == 1);
  6887. }
  6888. void VmaBlockMetadata_Generic::CalcAllocationStatInfo(VmaStatInfo& outInfo) const
  6889. {
  6890. outInfo.blockCount = 1;
  6891. const uint32_t rangeCount = (uint32_t)m_Suballocations.size();
  6892. outInfo.allocationCount = rangeCount - m_FreeCount;
  6893. outInfo.unusedRangeCount = m_FreeCount;
  6894. outInfo.unusedBytes = m_SumFreeSize;
  6895. outInfo.usedBytes = GetSize() - outInfo.unusedBytes;
  6896. outInfo.allocationSizeMin = UINT64_MAX;
  6897. outInfo.allocationSizeMax = 0;
  6898. outInfo.unusedRangeSizeMin = UINT64_MAX;
  6899. outInfo.unusedRangeSizeMax = 0;
  6900. for(VmaSuballocationList::const_iterator suballocItem = m_Suballocations.cbegin();
  6901. suballocItem != m_Suballocations.cend();
  6902. ++suballocItem)
  6903. {
  6904. const VmaSuballocation& suballoc = *suballocItem;
  6905. if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  6906. {
  6907. outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size);
  6908. outInfo.allocationSizeMax = VMA_MAX(outInfo.allocationSizeMax, suballoc.size);
  6909. }
  6910. else
  6911. {
  6912. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, suballoc.size);
  6913. outInfo.unusedRangeSizeMax = VMA_MAX(outInfo.unusedRangeSizeMax, suballoc.size);
  6914. }
  6915. }
  6916. }
  6917. void VmaBlockMetadata_Generic::AddPoolStats(VmaPoolStats& inoutStats) const
  6918. {
  6919. const uint32_t rangeCount = (uint32_t)m_Suballocations.size();
  6920. inoutStats.size += GetSize();
  6921. inoutStats.unusedSize += m_SumFreeSize;
  6922. inoutStats.allocationCount += rangeCount - m_FreeCount;
  6923. inoutStats.unusedRangeCount += m_FreeCount;
  6924. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, GetUnusedRangeSizeMax());
  6925. }
  6926. #if VMA_STATS_STRING_ENABLED
  6927. void VmaBlockMetadata_Generic::PrintDetailedMap(class VmaJsonWriter& json) const
  6928. {
  6929. PrintDetailedMap_Begin(json,
  6930. m_SumFreeSize, // unusedBytes
  6931. m_Suballocations.size() - (size_t)m_FreeCount, // allocationCount
  6932. m_FreeCount); // unusedRangeCount
  6933. size_t i = 0;
  6934. for(VmaSuballocationList::const_iterator suballocItem = m_Suballocations.cbegin();
  6935. suballocItem != m_Suballocations.cend();
  6936. ++suballocItem, ++i)
  6937. {
  6938. if(suballocItem->type == VMA_SUBALLOCATION_TYPE_FREE)
  6939. {
  6940. PrintDetailedMap_UnusedRange(json, suballocItem->offset, suballocItem->size);
  6941. }
  6942. else
  6943. {
  6944. PrintDetailedMap_Allocation(json, suballocItem->offset, suballocItem->hAllocation);
  6945. }
  6946. }
  6947. PrintDetailedMap_End(json);
  6948. }
  6949. #endif // #if VMA_STATS_STRING_ENABLED
  6950. bool VmaBlockMetadata_Generic::CreateAllocationRequest(
  6951. uint32_t currentFrameIndex,
  6952. uint32_t frameInUseCount,
  6953. VkDeviceSize bufferImageGranularity,
  6954. VkDeviceSize allocSize,
  6955. VkDeviceSize allocAlignment,
  6956. bool upperAddress,
  6957. VmaSuballocationType allocType,
  6958. bool canMakeOtherLost,
  6959. uint32_t strategy,
  6960. VmaAllocationRequest* pAllocationRequest)
  6961. {
  6962. VMA_ASSERT(allocSize > 0);
  6963. VMA_ASSERT(!upperAddress);
  6964. VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
  6965. VMA_ASSERT(pAllocationRequest != VMA_NULL);
  6966. VMA_HEAVY_ASSERT(Validate());
  6967. pAllocationRequest->type = VmaAllocationRequestType::Normal;
  6968. // There is not enough total free space in this block to fullfill the request: Early return.
  6969. if(canMakeOtherLost == false &&
  6970. m_SumFreeSize < allocSize + 2 * VMA_DEBUG_MARGIN)
  6971. {
  6972. return false;
  6973. }
  6974. // New algorithm, efficiently searching freeSuballocationsBySize.
  6975. const size_t freeSuballocCount = m_FreeSuballocationsBySize.size();
  6976. if(freeSuballocCount > 0)
  6977. {
  6978. if(strategy == VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT)
  6979. {
  6980. // Find first free suballocation with size not less than allocSize + 2 * VMA_DEBUG_MARGIN.
  6981. VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess(
  6982. m_FreeSuballocationsBySize.data(),
  6983. m_FreeSuballocationsBySize.data() + freeSuballocCount,
  6984. allocSize + 2 * VMA_DEBUG_MARGIN,
  6985. VmaSuballocationItemSizeLess());
  6986. size_t index = it - m_FreeSuballocationsBySize.data();
  6987. for(; index < freeSuballocCount; ++index)
  6988. {
  6989. if(CheckAllocation(
  6990. currentFrameIndex,
  6991. frameInUseCount,
  6992. bufferImageGranularity,
  6993. allocSize,
  6994. allocAlignment,
  6995. allocType,
  6996. m_FreeSuballocationsBySize[index],
  6997. false, // canMakeOtherLost
  6998. &pAllocationRequest->offset,
  6999. &pAllocationRequest->itemsToMakeLostCount,
  7000. &pAllocationRequest->sumFreeSize,
  7001. &pAllocationRequest->sumItemSize))
  7002. {
  7003. pAllocationRequest->item = m_FreeSuballocationsBySize[index];
  7004. return true;
  7005. }
  7006. }
  7007. }
  7008. else if(strategy == VMA_ALLOCATION_INTERNAL_STRATEGY_MIN_OFFSET)
  7009. {
  7010. for(VmaSuballocationList::iterator it = m_Suballocations.begin();
  7011. it != m_Suballocations.end();
  7012. ++it)
  7013. {
  7014. if(it->type == VMA_SUBALLOCATION_TYPE_FREE && CheckAllocation(
  7015. currentFrameIndex,
  7016. frameInUseCount,
  7017. bufferImageGranularity,
  7018. allocSize,
  7019. allocAlignment,
  7020. allocType,
  7021. it,
  7022. false, // canMakeOtherLost
  7023. &pAllocationRequest->offset,
  7024. &pAllocationRequest->itemsToMakeLostCount,
  7025. &pAllocationRequest->sumFreeSize,
  7026. &pAllocationRequest->sumItemSize))
  7027. {
  7028. pAllocationRequest->item = it;
  7029. return true;
  7030. }
  7031. }
  7032. }
  7033. else // WORST_FIT, FIRST_FIT
  7034. {
  7035. // Search staring from biggest suballocations.
  7036. for(size_t index = freeSuballocCount; index--; )
  7037. {
  7038. if(CheckAllocation(
  7039. currentFrameIndex,
  7040. frameInUseCount,
  7041. bufferImageGranularity,
  7042. allocSize,
  7043. allocAlignment,
  7044. allocType,
  7045. m_FreeSuballocationsBySize[index],
  7046. false, // canMakeOtherLost
  7047. &pAllocationRequest->offset,
  7048. &pAllocationRequest->itemsToMakeLostCount,
  7049. &pAllocationRequest->sumFreeSize,
  7050. &pAllocationRequest->sumItemSize))
  7051. {
  7052. pAllocationRequest->item = m_FreeSuballocationsBySize[index];
  7053. return true;
  7054. }
  7055. }
  7056. }
  7057. }
  7058. if(canMakeOtherLost)
  7059. {
  7060. // Brute-force algorithm. TODO: Come up with something better.
  7061. bool found = false;
  7062. VmaAllocationRequest tmpAllocRequest = {};
  7063. tmpAllocRequest.type = VmaAllocationRequestType::Normal;
  7064. for(VmaSuballocationList::iterator suballocIt = m_Suballocations.begin();
  7065. suballocIt != m_Suballocations.end();
  7066. ++suballocIt)
  7067. {
  7068. if(suballocIt->type == VMA_SUBALLOCATION_TYPE_FREE ||
  7069. suballocIt->hAllocation->CanBecomeLost())
  7070. {
  7071. if(CheckAllocation(
  7072. currentFrameIndex,
  7073. frameInUseCount,
  7074. bufferImageGranularity,
  7075. allocSize,
  7076. allocAlignment,
  7077. allocType,
  7078. suballocIt,
  7079. canMakeOtherLost,
  7080. &tmpAllocRequest.offset,
  7081. &tmpAllocRequest.itemsToMakeLostCount,
  7082. &tmpAllocRequest.sumFreeSize,
  7083. &tmpAllocRequest.sumItemSize))
  7084. {
  7085. if(strategy == VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT)
  7086. {
  7087. *pAllocationRequest = tmpAllocRequest;
  7088. pAllocationRequest->item = suballocIt;
  7089. break;
  7090. }
  7091. if(!found || tmpAllocRequest.CalcCost() < pAllocationRequest->CalcCost())
  7092. {
  7093. *pAllocationRequest = tmpAllocRequest;
  7094. pAllocationRequest->item = suballocIt;
  7095. found = true;
  7096. }
  7097. }
  7098. }
  7099. }
  7100. return found;
  7101. }
  7102. return false;
  7103. }
  7104. bool VmaBlockMetadata_Generic::MakeRequestedAllocationsLost(
  7105. uint32_t currentFrameIndex,
  7106. uint32_t frameInUseCount,
  7107. VmaAllocationRequest* pAllocationRequest)
  7108. {
  7109. VMA_ASSERT(pAllocationRequest && pAllocationRequest->type == VmaAllocationRequestType::Normal);
  7110. while(pAllocationRequest->itemsToMakeLostCount > 0)
  7111. {
  7112. if(pAllocationRequest->item->type == VMA_SUBALLOCATION_TYPE_FREE)
  7113. {
  7114. ++pAllocationRequest->item;
  7115. }
  7116. VMA_ASSERT(pAllocationRequest->item != m_Suballocations.end());
  7117. VMA_ASSERT(pAllocationRequest->item->hAllocation != VK_NULL_HANDLE);
  7118. VMA_ASSERT(pAllocationRequest->item->hAllocation->CanBecomeLost());
  7119. if(pAllocationRequest->item->hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
  7120. {
  7121. pAllocationRequest->item = FreeSuballocation(pAllocationRequest->item);
  7122. --pAllocationRequest->itemsToMakeLostCount;
  7123. }
  7124. else
  7125. {
  7126. return false;
  7127. }
  7128. }
  7129. VMA_HEAVY_ASSERT(Validate());
  7130. VMA_ASSERT(pAllocationRequest->item != m_Suballocations.end());
  7131. VMA_ASSERT(pAllocationRequest->item->type == VMA_SUBALLOCATION_TYPE_FREE);
  7132. return true;
  7133. }
  7134. uint32_t VmaBlockMetadata_Generic::MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount)
  7135. {
  7136. uint32_t lostAllocationCount = 0;
  7137. for(VmaSuballocationList::iterator it = m_Suballocations.begin();
  7138. it != m_Suballocations.end();
  7139. ++it)
  7140. {
  7141. if(it->type != VMA_SUBALLOCATION_TYPE_FREE &&
  7142. it->hAllocation->CanBecomeLost() &&
  7143. it->hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
  7144. {
  7145. it = FreeSuballocation(it);
  7146. ++lostAllocationCount;
  7147. }
  7148. }
  7149. return lostAllocationCount;
  7150. }
  7151. VkResult VmaBlockMetadata_Generic::CheckCorruption(const void* pBlockData)
  7152. {
  7153. for(VmaSuballocationList::iterator it = m_Suballocations.begin();
  7154. it != m_Suballocations.end();
  7155. ++it)
  7156. {
  7157. if(it->type != VMA_SUBALLOCATION_TYPE_FREE)
  7158. {
  7159. if(!VmaValidateMagicValue(pBlockData, it->offset - VMA_DEBUG_MARGIN))
  7160. {
  7161. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE VALIDATED ALLOCATION!");
  7162. return VK_ERROR_VALIDATION_FAILED_EXT;
  7163. }
  7164. if(!VmaValidateMagicValue(pBlockData, it->offset + it->size))
  7165. {
  7166. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
  7167. return VK_ERROR_VALIDATION_FAILED_EXT;
  7168. }
  7169. }
  7170. }
  7171. return VK_SUCCESS;
  7172. }
  7173. void VmaBlockMetadata_Generic::Alloc(
  7174. const VmaAllocationRequest& request,
  7175. VmaSuballocationType type,
  7176. VkDeviceSize allocSize,
  7177. VmaAllocation hAllocation)
  7178. {
  7179. VMA_ASSERT(request.type == VmaAllocationRequestType::Normal);
  7180. VMA_ASSERT(request.item != m_Suballocations.end());
  7181. VmaSuballocation& suballoc = *request.item;
  7182. // Given suballocation is a free block.
  7183. VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  7184. // Given offset is inside this suballocation.
  7185. VMA_ASSERT(request.offset >= suballoc.offset);
  7186. const VkDeviceSize paddingBegin = request.offset - suballoc.offset;
  7187. VMA_ASSERT(suballoc.size >= paddingBegin + allocSize);
  7188. const VkDeviceSize paddingEnd = suballoc.size - paddingBegin - allocSize;
  7189. // Unregister this free suballocation from m_FreeSuballocationsBySize and update
  7190. // it to become used.
  7191. UnregisterFreeSuballocation(request.item);
  7192. suballoc.offset = request.offset;
  7193. suballoc.size = allocSize;
  7194. suballoc.type = type;
  7195. suballoc.hAllocation = hAllocation;
  7196. // If there are any free bytes remaining at the end, insert new free suballocation after current one.
  7197. if(paddingEnd)
  7198. {
  7199. VmaSuballocation paddingSuballoc = {};
  7200. paddingSuballoc.offset = request.offset + allocSize;
  7201. paddingSuballoc.size = paddingEnd;
  7202. paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  7203. VmaSuballocationList::iterator next = request.item;
  7204. ++next;
  7205. const VmaSuballocationList::iterator paddingEndItem =
  7206. m_Suballocations.insert(next, paddingSuballoc);
  7207. RegisterFreeSuballocation(paddingEndItem);
  7208. }
  7209. // If there are any free bytes remaining at the beginning, insert new free suballocation before current one.
  7210. if(paddingBegin)
  7211. {
  7212. VmaSuballocation paddingSuballoc = {};
  7213. paddingSuballoc.offset = request.offset - paddingBegin;
  7214. paddingSuballoc.size = paddingBegin;
  7215. paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  7216. const VmaSuballocationList::iterator paddingBeginItem =
  7217. m_Suballocations.insert(request.item, paddingSuballoc);
  7218. RegisterFreeSuballocation(paddingBeginItem);
  7219. }
  7220. // Update totals.
  7221. m_FreeCount = m_FreeCount - 1;
  7222. if(paddingBegin > 0)
  7223. {
  7224. ++m_FreeCount;
  7225. }
  7226. if(paddingEnd > 0)
  7227. {
  7228. ++m_FreeCount;
  7229. }
  7230. m_SumFreeSize -= allocSize;
  7231. }
  7232. void VmaBlockMetadata_Generic::Free(const VmaAllocation allocation)
  7233. {
  7234. for(VmaSuballocationList::iterator suballocItem = m_Suballocations.begin();
  7235. suballocItem != m_Suballocations.end();
  7236. ++suballocItem)
  7237. {
  7238. VmaSuballocation& suballoc = *suballocItem;
  7239. if(suballoc.hAllocation == allocation)
  7240. {
  7241. FreeSuballocation(suballocItem);
  7242. VMA_HEAVY_ASSERT(Validate());
  7243. return;
  7244. }
  7245. }
  7246. VMA_ASSERT(0 && "Not found!");
  7247. }
  7248. void VmaBlockMetadata_Generic::FreeAtOffset(VkDeviceSize offset)
  7249. {
  7250. for(VmaSuballocationList::iterator suballocItem = m_Suballocations.begin();
  7251. suballocItem != m_Suballocations.end();
  7252. ++suballocItem)
  7253. {
  7254. VmaSuballocation& suballoc = *suballocItem;
  7255. if(suballoc.offset == offset)
  7256. {
  7257. FreeSuballocation(suballocItem);
  7258. return;
  7259. }
  7260. }
  7261. VMA_ASSERT(0 && "Not found!");
  7262. }
  7263. bool VmaBlockMetadata_Generic::ValidateFreeSuballocationList() const
  7264. {
  7265. VkDeviceSize lastSize = 0;
  7266. for(size_t i = 0, count = m_FreeSuballocationsBySize.size(); i < count; ++i)
  7267. {
  7268. const VmaSuballocationList::iterator it = m_FreeSuballocationsBySize[i];
  7269. VMA_VALIDATE(it->type == VMA_SUBALLOCATION_TYPE_FREE);
  7270. VMA_VALIDATE(it->size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER);
  7271. VMA_VALIDATE(it->size >= lastSize);
  7272. lastSize = it->size;
  7273. }
  7274. return true;
  7275. }
  7276. bool VmaBlockMetadata_Generic::CheckAllocation(
  7277. uint32_t currentFrameIndex,
  7278. uint32_t frameInUseCount,
  7279. VkDeviceSize bufferImageGranularity,
  7280. VkDeviceSize allocSize,
  7281. VkDeviceSize allocAlignment,
  7282. VmaSuballocationType allocType,
  7283. VmaSuballocationList::const_iterator suballocItem,
  7284. bool canMakeOtherLost,
  7285. VkDeviceSize* pOffset,
  7286. size_t* itemsToMakeLostCount,
  7287. VkDeviceSize* pSumFreeSize,
  7288. VkDeviceSize* pSumItemSize) const
  7289. {
  7290. VMA_ASSERT(allocSize > 0);
  7291. VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
  7292. VMA_ASSERT(suballocItem != m_Suballocations.cend());
  7293. VMA_ASSERT(pOffset != VMA_NULL);
  7294. *itemsToMakeLostCount = 0;
  7295. *pSumFreeSize = 0;
  7296. *pSumItemSize = 0;
  7297. if(canMakeOtherLost)
  7298. {
  7299. if(suballocItem->type == VMA_SUBALLOCATION_TYPE_FREE)
  7300. {
  7301. *pSumFreeSize = suballocItem->size;
  7302. }
  7303. else
  7304. {
  7305. if(suballocItem->hAllocation->CanBecomeLost() &&
  7306. suballocItem->hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
  7307. {
  7308. ++*itemsToMakeLostCount;
  7309. *pSumItemSize = suballocItem->size;
  7310. }
  7311. else
  7312. {
  7313. return false;
  7314. }
  7315. }
  7316. // Remaining size is too small for this request: Early return.
  7317. if(GetSize() - suballocItem->offset < allocSize)
  7318. {
  7319. return false;
  7320. }
  7321. // Start from offset equal to beginning of this suballocation.
  7322. *pOffset = suballocItem->offset;
  7323. // Apply VMA_DEBUG_MARGIN at the beginning.
  7324. if(VMA_DEBUG_MARGIN > 0)
  7325. {
  7326. *pOffset += VMA_DEBUG_MARGIN;
  7327. }
  7328. // Apply alignment.
  7329. *pOffset = VmaAlignUp(*pOffset, allocAlignment);
  7330. // Check previous suballocations for BufferImageGranularity conflicts.
  7331. // Make bigger alignment if necessary.
  7332. if(bufferImageGranularity > 1)
  7333. {
  7334. bool bufferImageGranularityConflict = false;
  7335. VmaSuballocationList::const_iterator prevSuballocItem = suballocItem;
  7336. while(prevSuballocItem != m_Suballocations.cbegin())
  7337. {
  7338. --prevSuballocItem;
  7339. const VmaSuballocation& prevSuballoc = *prevSuballocItem;
  7340. if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, *pOffset, bufferImageGranularity))
  7341. {
  7342. if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
  7343. {
  7344. bufferImageGranularityConflict = true;
  7345. break;
  7346. }
  7347. }
  7348. else
  7349. // Already on previous page.
  7350. break;
  7351. }
  7352. if(bufferImageGranularityConflict)
  7353. {
  7354. *pOffset = VmaAlignUp(*pOffset, bufferImageGranularity);
  7355. }
  7356. }
  7357. // Now that we have final *pOffset, check if we are past suballocItem.
  7358. // If yes, return false - this function should be called for another suballocItem as starting point.
  7359. if(*pOffset >= suballocItem->offset + suballocItem->size)
  7360. {
  7361. return false;
  7362. }
  7363. // Calculate padding at the beginning based on current offset.
  7364. const VkDeviceSize paddingBegin = *pOffset - suballocItem->offset;
  7365. // Calculate required margin at the end.
  7366. const VkDeviceSize requiredEndMargin = VMA_DEBUG_MARGIN;
  7367. const VkDeviceSize totalSize = paddingBegin + allocSize + requiredEndMargin;
  7368. // Another early return check.
  7369. if(suballocItem->offset + totalSize > GetSize())
  7370. {
  7371. return false;
  7372. }
  7373. // Advance lastSuballocItem until desired size is reached.
  7374. // Update itemsToMakeLostCount.
  7375. VmaSuballocationList::const_iterator lastSuballocItem = suballocItem;
  7376. if(totalSize > suballocItem->size)
  7377. {
  7378. VkDeviceSize remainingSize = totalSize - suballocItem->size;
  7379. while(remainingSize > 0)
  7380. {
  7381. ++lastSuballocItem;
  7382. if(lastSuballocItem == m_Suballocations.cend())
  7383. {
  7384. return false;
  7385. }
  7386. if(lastSuballocItem->type == VMA_SUBALLOCATION_TYPE_FREE)
  7387. {
  7388. *pSumFreeSize += lastSuballocItem->size;
  7389. }
  7390. else
  7391. {
  7392. VMA_ASSERT(lastSuballocItem->hAllocation != VK_NULL_HANDLE);
  7393. if(lastSuballocItem->hAllocation->CanBecomeLost() &&
  7394. lastSuballocItem->hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
  7395. {
  7396. ++*itemsToMakeLostCount;
  7397. *pSumItemSize += lastSuballocItem->size;
  7398. }
  7399. else
  7400. {
  7401. return false;
  7402. }
  7403. }
  7404. remainingSize = (lastSuballocItem->size < remainingSize) ?
  7405. remainingSize - lastSuballocItem->size : 0;
  7406. }
  7407. }
  7408. // Check next suballocations for BufferImageGranularity conflicts.
  7409. // If conflict exists, we must mark more allocations lost or fail.
  7410. if(bufferImageGranularity > 1)
  7411. {
  7412. VmaSuballocationList::const_iterator nextSuballocItem = lastSuballocItem;
  7413. ++nextSuballocItem;
  7414. while(nextSuballocItem != m_Suballocations.cend())
  7415. {
  7416. const VmaSuballocation& nextSuballoc = *nextSuballocItem;
  7417. if(VmaBlocksOnSamePage(*pOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  7418. {
  7419. if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
  7420. {
  7421. VMA_ASSERT(nextSuballoc.hAllocation != VK_NULL_HANDLE);
  7422. if(nextSuballoc.hAllocation->CanBecomeLost() &&
  7423. nextSuballoc.hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
  7424. {
  7425. ++*itemsToMakeLostCount;
  7426. }
  7427. else
  7428. {
  7429. return false;
  7430. }
  7431. }
  7432. }
  7433. else
  7434. {
  7435. // Already on next page.
  7436. break;
  7437. }
  7438. ++nextSuballocItem;
  7439. }
  7440. }
  7441. }
  7442. else
  7443. {
  7444. const VmaSuballocation& suballoc = *suballocItem;
  7445. VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  7446. *pSumFreeSize = suballoc.size;
  7447. // Size of this suballocation is too small for this request: Early return.
  7448. if(suballoc.size < allocSize)
  7449. {
  7450. return false;
  7451. }
  7452. // Start from offset equal to beginning of this suballocation.
  7453. *pOffset = suballoc.offset;
  7454. // Apply VMA_DEBUG_MARGIN at the beginning.
  7455. if(VMA_DEBUG_MARGIN > 0)
  7456. {
  7457. *pOffset += VMA_DEBUG_MARGIN;
  7458. }
  7459. // Apply alignment.
  7460. *pOffset = VmaAlignUp(*pOffset, allocAlignment);
  7461. // Check previous suballocations for BufferImageGranularity conflicts.
  7462. // Make bigger alignment if necessary.
  7463. if(bufferImageGranularity > 1)
  7464. {
  7465. bool bufferImageGranularityConflict = false;
  7466. VmaSuballocationList::const_iterator prevSuballocItem = suballocItem;
  7467. while(prevSuballocItem != m_Suballocations.cbegin())
  7468. {
  7469. --prevSuballocItem;
  7470. const VmaSuballocation& prevSuballoc = *prevSuballocItem;
  7471. if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, *pOffset, bufferImageGranularity))
  7472. {
  7473. if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
  7474. {
  7475. bufferImageGranularityConflict = true;
  7476. break;
  7477. }
  7478. }
  7479. else
  7480. // Already on previous page.
  7481. break;
  7482. }
  7483. if(bufferImageGranularityConflict)
  7484. {
  7485. *pOffset = VmaAlignUp(*pOffset, bufferImageGranularity);
  7486. }
  7487. }
  7488. // Calculate padding at the beginning based on current offset.
  7489. const VkDeviceSize paddingBegin = *pOffset - suballoc.offset;
  7490. // Calculate required margin at the end.
  7491. const VkDeviceSize requiredEndMargin = VMA_DEBUG_MARGIN;
  7492. // Fail if requested size plus margin before and after is bigger than size of this suballocation.
  7493. if(paddingBegin + allocSize + requiredEndMargin > suballoc.size)
  7494. {
  7495. return false;
  7496. }
  7497. // Check next suballocations for BufferImageGranularity conflicts.
  7498. // If conflict exists, allocation cannot be made here.
  7499. if(bufferImageGranularity > 1)
  7500. {
  7501. VmaSuballocationList::const_iterator nextSuballocItem = suballocItem;
  7502. ++nextSuballocItem;
  7503. while(nextSuballocItem != m_Suballocations.cend())
  7504. {
  7505. const VmaSuballocation& nextSuballoc = *nextSuballocItem;
  7506. if(VmaBlocksOnSamePage(*pOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  7507. {
  7508. if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
  7509. {
  7510. return false;
  7511. }
  7512. }
  7513. else
  7514. {
  7515. // Already on next page.
  7516. break;
  7517. }
  7518. ++nextSuballocItem;
  7519. }
  7520. }
  7521. }
  7522. // All tests passed: Success. pOffset is already filled.
  7523. return true;
  7524. }
  7525. void VmaBlockMetadata_Generic::MergeFreeWithNext(VmaSuballocationList::iterator item)
  7526. {
  7527. VMA_ASSERT(item != m_Suballocations.end());
  7528. VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
  7529. VmaSuballocationList::iterator nextItem = item;
  7530. ++nextItem;
  7531. VMA_ASSERT(nextItem != m_Suballocations.end());
  7532. VMA_ASSERT(nextItem->type == VMA_SUBALLOCATION_TYPE_FREE);
  7533. item->size += nextItem->size;
  7534. --m_FreeCount;
  7535. m_Suballocations.erase(nextItem);
  7536. }
  7537. VmaSuballocationList::iterator VmaBlockMetadata_Generic::FreeSuballocation(VmaSuballocationList::iterator suballocItem)
  7538. {
  7539. // Change this suballocation to be marked as free.
  7540. VmaSuballocation& suballoc = *suballocItem;
  7541. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  7542. suballoc.hAllocation = VK_NULL_HANDLE;
  7543. // Update totals.
  7544. ++m_FreeCount;
  7545. m_SumFreeSize += suballoc.size;
  7546. // Merge with previous and/or next suballocation if it's also free.
  7547. bool mergeWithNext = false;
  7548. bool mergeWithPrev = false;
  7549. VmaSuballocationList::iterator nextItem = suballocItem;
  7550. ++nextItem;
  7551. if((nextItem != m_Suballocations.end()) && (nextItem->type == VMA_SUBALLOCATION_TYPE_FREE))
  7552. {
  7553. mergeWithNext = true;
  7554. }
  7555. VmaSuballocationList::iterator prevItem = suballocItem;
  7556. if(suballocItem != m_Suballocations.begin())
  7557. {
  7558. --prevItem;
  7559. if(prevItem->type == VMA_SUBALLOCATION_TYPE_FREE)
  7560. {
  7561. mergeWithPrev = true;
  7562. }
  7563. }
  7564. if(mergeWithNext)
  7565. {
  7566. UnregisterFreeSuballocation(nextItem);
  7567. MergeFreeWithNext(suballocItem);
  7568. }
  7569. if(mergeWithPrev)
  7570. {
  7571. UnregisterFreeSuballocation(prevItem);
  7572. MergeFreeWithNext(prevItem);
  7573. RegisterFreeSuballocation(prevItem);
  7574. return prevItem;
  7575. }
  7576. else
  7577. {
  7578. RegisterFreeSuballocation(suballocItem);
  7579. return suballocItem;
  7580. }
  7581. }
  7582. void VmaBlockMetadata_Generic::RegisterFreeSuballocation(VmaSuballocationList::iterator item)
  7583. {
  7584. VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
  7585. VMA_ASSERT(item->size > 0);
  7586. // You may want to enable this validation at the beginning or at the end of
  7587. // this function, depending on what do you want to check.
  7588. VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  7589. if(item->size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
  7590. {
  7591. if(m_FreeSuballocationsBySize.empty())
  7592. {
  7593. m_FreeSuballocationsBySize.push_back(item);
  7594. }
  7595. else
  7596. {
  7597. VmaVectorInsertSorted<VmaSuballocationItemSizeLess>(m_FreeSuballocationsBySize, item);
  7598. }
  7599. }
  7600. //VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  7601. }
  7602. void VmaBlockMetadata_Generic::UnregisterFreeSuballocation(VmaSuballocationList::iterator item)
  7603. {
  7604. VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
  7605. VMA_ASSERT(item->size > 0);
  7606. // You may want to enable this validation at the beginning or at the end of
  7607. // this function, depending on what do you want to check.
  7608. VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  7609. if(item->size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
  7610. {
  7611. VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess(
  7612. m_FreeSuballocationsBySize.data(),
  7613. m_FreeSuballocationsBySize.data() + m_FreeSuballocationsBySize.size(),
  7614. item,
  7615. VmaSuballocationItemSizeLess());
  7616. for(size_t index = it - m_FreeSuballocationsBySize.data();
  7617. index < m_FreeSuballocationsBySize.size();
  7618. ++index)
  7619. {
  7620. if(m_FreeSuballocationsBySize[index] == item)
  7621. {
  7622. VmaVectorRemove(m_FreeSuballocationsBySize, index);
  7623. return;
  7624. }
  7625. VMA_ASSERT((m_FreeSuballocationsBySize[index]->size == item->size) && "Not found.");
  7626. }
  7627. VMA_ASSERT(0 && "Not found.");
  7628. }
  7629. //VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  7630. }
  7631. bool VmaBlockMetadata_Generic::IsBufferImageGranularityConflictPossible(
  7632. VkDeviceSize bufferImageGranularity,
  7633. VmaSuballocationType& inOutPrevSuballocType) const
  7634. {
  7635. if(bufferImageGranularity == 1 || IsEmpty())
  7636. {
  7637. return false;
  7638. }
  7639. VkDeviceSize minAlignment = VK_WHOLE_SIZE;
  7640. bool typeConflictFound = false;
  7641. for(VmaSuballocationList::const_iterator it = m_Suballocations.cbegin();
  7642. it != m_Suballocations.cend();
  7643. ++it)
  7644. {
  7645. const VmaSuballocationType suballocType = it->type;
  7646. if(suballocType != VMA_SUBALLOCATION_TYPE_FREE)
  7647. {
  7648. minAlignment = VMA_MIN(minAlignment, it->hAllocation->GetAlignment());
  7649. if(VmaIsBufferImageGranularityConflict(inOutPrevSuballocType, suballocType))
  7650. {
  7651. typeConflictFound = true;
  7652. }
  7653. inOutPrevSuballocType = suballocType;
  7654. }
  7655. }
  7656. return typeConflictFound || minAlignment >= bufferImageGranularity;
  7657. }
  7658. ////////////////////////////////////////////////////////////////////////////////
  7659. // class VmaBlockMetadata_Linear
  7660. VmaBlockMetadata_Linear::VmaBlockMetadata_Linear(VmaAllocator hAllocator) :
  7661. VmaBlockMetadata(hAllocator),
  7662. m_SumFreeSize(0),
  7663. m_Suballocations0(VmaStlAllocator<VmaSuballocation>(hAllocator->GetAllocationCallbacks())),
  7664. m_Suballocations1(VmaStlAllocator<VmaSuballocation>(hAllocator->GetAllocationCallbacks())),
  7665. m_1stVectorIndex(0),
  7666. m_2ndVectorMode(SECOND_VECTOR_EMPTY),
  7667. m_1stNullItemsBeginCount(0),
  7668. m_1stNullItemsMiddleCount(0),
  7669. m_2ndNullItemsCount(0)
  7670. {
  7671. }
  7672. VmaBlockMetadata_Linear::~VmaBlockMetadata_Linear()
  7673. {
  7674. }
  7675. void VmaBlockMetadata_Linear::Init(VkDeviceSize size)
  7676. {
  7677. VmaBlockMetadata::Init(size);
  7678. m_SumFreeSize = size;
  7679. }
  7680. bool VmaBlockMetadata_Linear::Validate() const
  7681. {
  7682. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7683. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7684. VMA_VALIDATE(suballocations2nd.empty() == (m_2ndVectorMode == SECOND_VECTOR_EMPTY));
  7685. VMA_VALIDATE(!suballocations1st.empty() ||
  7686. suballocations2nd.empty() ||
  7687. m_2ndVectorMode != SECOND_VECTOR_RING_BUFFER);
  7688. if(!suballocations1st.empty())
  7689. {
  7690. // Null item at the beginning should be accounted into m_1stNullItemsBeginCount.
  7691. VMA_VALIDATE(suballocations1st[m_1stNullItemsBeginCount].hAllocation != VK_NULL_HANDLE);
  7692. // Null item at the end should be just pop_back().
  7693. VMA_VALIDATE(suballocations1st.back().hAllocation != VK_NULL_HANDLE);
  7694. }
  7695. if(!suballocations2nd.empty())
  7696. {
  7697. // Null item at the end should be just pop_back().
  7698. VMA_VALIDATE(suballocations2nd.back().hAllocation != VK_NULL_HANDLE);
  7699. }
  7700. VMA_VALIDATE(m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount <= suballocations1st.size());
  7701. VMA_VALIDATE(m_2ndNullItemsCount <= suballocations2nd.size());
  7702. VkDeviceSize sumUsedSize = 0;
  7703. const size_t suballoc1stCount = suballocations1st.size();
  7704. VkDeviceSize offset = VMA_DEBUG_MARGIN;
  7705. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  7706. {
  7707. const size_t suballoc2ndCount = suballocations2nd.size();
  7708. size_t nullItem2ndCount = 0;
  7709. for(size_t i = 0; i < suballoc2ndCount; ++i)
  7710. {
  7711. const VmaSuballocation& suballoc = suballocations2nd[i];
  7712. const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  7713. VMA_VALIDATE(currFree == (suballoc.hAllocation == VK_NULL_HANDLE));
  7714. VMA_VALIDATE(suballoc.offset >= offset);
  7715. if(!currFree)
  7716. {
  7717. VMA_VALIDATE(suballoc.hAllocation->GetOffset() == suballoc.offset);
  7718. VMA_VALIDATE(suballoc.hAllocation->GetSize() == suballoc.size);
  7719. sumUsedSize += suballoc.size;
  7720. }
  7721. else
  7722. {
  7723. ++nullItem2ndCount;
  7724. }
  7725. offset = suballoc.offset + suballoc.size + VMA_DEBUG_MARGIN;
  7726. }
  7727. VMA_VALIDATE(nullItem2ndCount == m_2ndNullItemsCount);
  7728. }
  7729. for(size_t i = 0; i < m_1stNullItemsBeginCount; ++i)
  7730. {
  7731. const VmaSuballocation& suballoc = suballocations1st[i];
  7732. VMA_VALIDATE(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE &&
  7733. suballoc.hAllocation == VK_NULL_HANDLE);
  7734. }
  7735. size_t nullItem1stCount = m_1stNullItemsBeginCount;
  7736. for(size_t i = m_1stNullItemsBeginCount; i < suballoc1stCount; ++i)
  7737. {
  7738. const VmaSuballocation& suballoc = suballocations1st[i];
  7739. const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  7740. VMA_VALIDATE(currFree == (suballoc.hAllocation == VK_NULL_HANDLE));
  7741. VMA_VALIDATE(suballoc.offset >= offset);
  7742. VMA_VALIDATE(i >= m_1stNullItemsBeginCount || currFree);
  7743. if(!currFree)
  7744. {
  7745. VMA_VALIDATE(suballoc.hAllocation->GetOffset() == suballoc.offset);
  7746. VMA_VALIDATE(suballoc.hAllocation->GetSize() == suballoc.size);
  7747. sumUsedSize += suballoc.size;
  7748. }
  7749. else
  7750. {
  7751. ++nullItem1stCount;
  7752. }
  7753. offset = suballoc.offset + suballoc.size + VMA_DEBUG_MARGIN;
  7754. }
  7755. VMA_VALIDATE(nullItem1stCount == m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount);
  7756. if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  7757. {
  7758. const size_t suballoc2ndCount = suballocations2nd.size();
  7759. size_t nullItem2ndCount = 0;
  7760. for(size_t i = suballoc2ndCount; i--; )
  7761. {
  7762. const VmaSuballocation& suballoc = suballocations2nd[i];
  7763. const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  7764. VMA_VALIDATE(currFree == (suballoc.hAllocation == VK_NULL_HANDLE));
  7765. VMA_VALIDATE(suballoc.offset >= offset);
  7766. if(!currFree)
  7767. {
  7768. VMA_VALIDATE(suballoc.hAllocation->GetOffset() == suballoc.offset);
  7769. VMA_VALIDATE(suballoc.hAllocation->GetSize() == suballoc.size);
  7770. sumUsedSize += suballoc.size;
  7771. }
  7772. else
  7773. {
  7774. ++nullItem2ndCount;
  7775. }
  7776. offset = suballoc.offset + suballoc.size + VMA_DEBUG_MARGIN;
  7777. }
  7778. VMA_VALIDATE(nullItem2ndCount == m_2ndNullItemsCount);
  7779. }
  7780. VMA_VALIDATE(offset <= GetSize());
  7781. VMA_VALIDATE(m_SumFreeSize == GetSize() - sumUsedSize);
  7782. return true;
  7783. }
  7784. size_t VmaBlockMetadata_Linear::GetAllocationCount() const
  7785. {
  7786. return AccessSuballocations1st().size() - (m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount) +
  7787. AccessSuballocations2nd().size() - m_2ndNullItemsCount;
  7788. }
  7789. VkDeviceSize VmaBlockMetadata_Linear::GetUnusedRangeSizeMax() const
  7790. {
  7791. const VkDeviceSize size = GetSize();
  7792. /*
  7793. We don't consider gaps inside allocation vectors with freed allocations because
  7794. they are not suitable for reuse in linear allocator. We consider only space that
  7795. is available for new allocations.
  7796. */
  7797. if(IsEmpty())
  7798. {
  7799. return size;
  7800. }
  7801. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7802. switch(m_2ndVectorMode)
  7803. {
  7804. case SECOND_VECTOR_EMPTY:
  7805. /*
  7806. Available space is after end of 1st, as well as before beginning of 1st (which
  7807. whould make it a ring buffer).
  7808. */
  7809. {
  7810. const size_t suballocations1stCount = suballocations1st.size();
  7811. VMA_ASSERT(suballocations1stCount > m_1stNullItemsBeginCount);
  7812. const VmaSuballocation& firstSuballoc = suballocations1st[m_1stNullItemsBeginCount];
  7813. const VmaSuballocation& lastSuballoc = suballocations1st[suballocations1stCount - 1];
  7814. return VMA_MAX(
  7815. firstSuballoc.offset,
  7816. size - (lastSuballoc.offset + lastSuballoc.size));
  7817. }
  7818. break;
  7819. case SECOND_VECTOR_RING_BUFFER:
  7820. /*
  7821. Available space is only between end of 2nd and beginning of 1st.
  7822. */
  7823. {
  7824. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7825. const VmaSuballocation& lastSuballoc2nd = suballocations2nd.back();
  7826. const VmaSuballocation& firstSuballoc1st = suballocations1st[m_1stNullItemsBeginCount];
  7827. return firstSuballoc1st.offset - (lastSuballoc2nd.offset + lastSuballoc2nd.size);
  7828. }
  7829. break;
  7830. case SECOND_VECTOR_DOUBLE_STACK:
  7831. /*
  7832. Available space is only between end of 1st and top of 2nd.
  7833. */
  7834. {
  7835. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7836. const VmaSuballocation& topSuballoc2nd = suballocations2nd.back();
  7837. const VmaSuballocation& lastSuballoc1st = suballocations1st.back();
  7838. return topSuballoc2nd.offset - (lastSuballoc1st.offset + lastSuballoc1st.size);
  7839. }
  7840. break;
  7841. default:
  7842. VMA_ASSERT(0);
  7843. return 0;
  7844. }
  7845. }
  7846. void VmaBlockMetadata_Linear::CalcAllocationStatInfo(VmaStatInfo& outInfo) const
  7847. {
  7848. const VkDeviceSize size = GetSize();
  7849. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7850. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7851. const size_t suballoc1stCount = suballocations1st.size();
  7852. const size_t suballoc2ndCount = suballocations2nd.size();
  7853. outInfo.blockCount = 1;
  7854. outInfo.allocationCount = (uint32_t)GetAllocationCount();
  7855. outInfo.unusedRangeCount = 0;
  7856. outInfo.usedBytes = 0;
  7857. outInfo.allocationSizeMin = UINT64_MAX;
  7858. outInfo.allocationSizeMax = 0;
  7859. outInfo.unusedRangeSizeMin = UINT64_MAX;
  7860. outInfo.unusedRangeSizeMax = 0;
  7861. VkDeviceSize lastOffset = 0;
  7862. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  7863. {
  7864. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  7865. size_t nextAlloc2ndIndex = 0;
  7866. while(lastOffset < freeSpace2ndTo1stEnd)
  7867. {
  7868. // Find next non-null allocation or move nextAllocIndex to the end.
  7869. while(nextAlloc2ndIndex < suballoc2ndCount &&
  7870. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  7871. {
  7872. ++nextAlloc2ndIndex;
  7873. }
  7874. // Found non-null allocation.
  7875. if(nextAlloc2ndIndex < suballoc2ndCount)
  7876. {
  7877. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  7878. // 1. Process free space before this allocation.
  7879. if(lastOffset < suballoc.offset)
  7880. {
  7881. // There is free space from lastOffset to suballoc.offset.
  7882. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  7883. ++outInfo.unusedRangeCount;
  7884. outInfo.unusedBytes += unusedRangeSize;
  7885. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
  7886. outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
  7887. }
  7888. // 2. Process this allocation.
  7889. // There is allocation with suballoc.offset, suballoc.size.
  7890. outInfo.usedBytes += suballoc.size;
  7891. outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size);
  7892. outInfo.allocationSizeMax = VMA_MIN(outInfo.allocationSizeMax, suballoc.size);
  7893. // 3. Prepare for next iteration.
  7894. lastOffset = suballoc.offset + suballoc.size;
  7895. ++nextAlloc2ndIndex;
  7896. }
  7897. // We are at the end.
  7898. else
  7899. {
  7900. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  7901. if(lastOffset < freeSpace2ndTo1stEnd)
  7902. {
  7903. const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset;
  7904. ++outInfo.unusedRangeCount;
  7905. outInfo.unusedBytes += unusedRangeSize;
  7906. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
  7907. outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
  7908. }
  7909. // End of loop.
  7910. lastOffset = freeSpace2ndTo1stEnd;
  7911. }
  7912. }
  7913. }
  7914. size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
  7915. const VkDeviceSize freeSpace1stTo2ndEnd =
  7916. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
  7917. while(lastOffset < freeSpace1stTo2ndEnd)
  7918. {
  7919. // Find next non-null allocation or move nextAllocIndex to the end.
  7920. while(nextAlloc1stIndex < suballoc1stCount &&
  7921. suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE)
  7922. {
  7923. ++nextAlloc1stIndex;
  7924. }
  7925. // Found non-null allocation.
  7926. if(nextAlloc1stIndex < suballoc1stCount)
  7927. {
  7928. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  7929. // 1. Process free space before this allocation.
  7930. if(lastOffset < suballoc.offset)
  7931. {
  7932. // There is free space from lastOffset to suballoc.offset.
  7933. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  7934. ++outInfo.unusedRangeCount;
  7935. outInfo.unusedBytes += unusedRangeSize;
  7936. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
  7937. outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
  7938. }
  7939. // 2. Process this allocation.
  7940. // There is allocation with suballoc.offset, suballoc.size.
  7941. outInfo.usedBytes += suballoc.size;
  7942. outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size);
  7943. outInfo.allocationSizeMax = VMA_MIN(outInfo.allocationSizeMax, suballoc.size);
  7944. // 3. Prepare for next iteration.
  7945. lastOffset = suballoc.offset + suballoc.size;
  7946. ++nextAlloc1stIndex;
  7947. }
  7948. // We are at the end.
  7949. else
  7950. {
  7951. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  7952. if(lastOffset < freeSpace1stTo2ndEnd)
  7953. {
  7954. const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset;
  7955. ++outInfo.unusedRangeCount;
  7956. outInfo.unusedBytes += unusedRangeSize;
  7957. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
  7958. outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
  7959. }
  7960. // End of loop.
  7961. lastOffset = freeSpace1stTo2ndEnd;
  7962. }
  7963. }
  7964. if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  7965. {
  7966. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  7967. while(lastOffset < size)
  7968. {
  7969. // Find next non-null allocation or move nextAllocIndex to the end.
  7970. while(nextAlloc2ndIndex != SIZE_MAX &&
  7971. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  7972. {
  7973. --nextAlloc2ndIndex;
  7974. }
  7975. // Found non-null allocation.
  7976. if(nextAlloc2ndIndex != SIZE_MAX)
  7977. {
  7978. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  7979. // 1. Process free space before this allocation.
  7980. if(lastOffset < suballoc.offset)
  7981. {
  7982. // There is free space from lastOffset to suballoc.offset.
  7983. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  7984. ++outInfo.unusedRangeCount;
  7985. outInfo.unusedBytes += unusedRangeSize;
  7986. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
  7987. outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
  7988. }
  7989. // 2. Process this allocation.
  7990. // There is allocation with suballoc.offset, suballoc.size.
  7991. outInfo.usedBytes += suballoc.size;
  7992. outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size);
  7993. outInfo.allocationSizeMax = VMA_MIN(outInfo.allocationSizeMax, suballoc.size);
  7994. // 3. Prepare for next iteration.
  7995. lastOffset = suballoc.offset + suballoc.size;
  7996. --nextAlloc2ndIndex;
  7997. }
  7998. // We are at the end.
  7999. else
  8000. {
  8001. // There is free space from lastOffset to size.
  8002. if(lastOffset < size)
  8003. {
  8004. const VkDeviceSize unusedRangeSize = size - lastOffset;
  8005. ++outInfo.unusedRangeCount;
  8006. outInfo.unusedBytes += unusedRangeSize;
  8007. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
  8008. outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
  8009. }
  8010. // End of loop.
  8011. lastOffset = size;
  8012. }
  8013. }
  8014. }
  8015. outInfo.unusedBytes = size - outInfo.usedBytes;
  8016. }
  8017. void VmaBlockMetadata_Linear::AddPoolStats(VmaPoolStats& inoutStats) const
  8018. {
  8019. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  8020. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  8021. const VkDeviceSize size = GetSize();
  8022. const size_t suballoc1stCount = suballocations1st.size();
  8023. const size_t suballoc2ndCount = suballocations2nd.size();
  8024. inoutStats.size += size;
  8025. VkDeviceSize lastOffset = 0;
  8026. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  8027. {
  8028. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  8029. size_t nextAlloc2ndIndex = m_1stNullItemsBeginCount;
  8030. while(lastOffset < freeSpace2ndTo1stEnd)
  8031. {
  8032. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  8033. while(nextAlloc2ndIndex < suballoc2ndCount &&
  8034. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  8035. {
  8036. ++nextAlloc2ndIndex;
  8037. }
  8038. // Found non-null allocation.
  8039. if(nextAlloc2ndIndex < suballoc2ndCount)
  8040. {
  8041. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  8042. // 1. Process free space before this allocation.
  8043. if(lastOffset < suballoc.offset)
  8044. {
  8045. // There is free space from lastOffset to suballoc.offset.
  8046. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  8047. inoutStats.unusedSize += unusedRangeSize;
  8048. ++inoutStats.unusedRangeCount;
  8049. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
  8050. }
  8051. // 2. Process this allocation.
  8052. // There is allocation with suballoc.offset, suballoc.size.
  8053. ++inoutStats.allocationCount;
  8054. // 3. Prepare for next iteration.
  8055. lastOffset = suballoc.offset + suballoc.size;
  8056. ++nextAlloc2ndIndex;
  8057. }
  8058. // We are at the end.
  8059. else
  8060. {
  8061. if(lastOffset < freeSpace2ndTo1stEnd)
  8062. {
  8063. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  8064. const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset;
  8065. inoutStats.unusedSize += unusedRangeSize;
  8066. ++inoutStats.unusedRangeCount;
  8067. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
  8068. }
  8069. // End of loop.
  8070. lastOffset = freeSpace2ndTo1stEnd;
  8071. }
  8072. }
  8073. }
  8074. size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
  8075. const VkDeviceSize freeSpace1stTo2ndEnd =
  8076. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
  8077. while(lastOffset < freeSpace1stTo2ndEnd)
  8078. {
  8079. // Find next non-null allocation or move nextAllocIndex to the end.
  8080. while(nextAlloc1stIndex < suballoc1stCount &&
  8081. suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE)
  8082. {
  8083. ++nextAlloc1stIndex;
  8084. }
  8085. // Found non-null allocation.
  8086. if(nextAlloc1stIndex < suballoc1stCount)
  8087. {
  8088. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  8089. // 1. Process free space before this allocation.
  8090. if(lastOffset < suballoc.offset)
  8091. {
  8092. // There is free space from lastOffset to suballoc.offset.
  8093. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  8094. inoutStats.unusedSize += unusedRangeSize;
  8095. ++inoutStats.unusedRangeCount;
  8096. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
  8097. }
  8098. // 2. Process this allocation.
  8099. // There is allocation with suballoc.offset, suballoc.size.
  8100. ++inoutStats.allocationCount;
  8101. // 3. Prepare for next iteration.
  8102. lastOffset = suballoc.offset + suballoc.size;
  8103. ++nextAlloc1stIndex;
  8104. }
  8105. // We are at the end.
  8106. else
  8107. {
  8108. if(lastOffset < freeSpace1stTo2ndEnd)
  8109. {
  8110. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  8111. const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset;
  8112. inoutStats.unusedSize += unusedRangeSize;
  8113. ++inoutStats.unusedRangeCount;
  8114. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
  8115. }
  8116. // End of loop.
  8117. lastOffset = freeSpace1stTo2ndEnd;
  8118. }
  8119. }
  8120. if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  8121. {
  8122. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  8123. while(lastOffset < size)
  8124. {
  8125. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  8126. while(nextAlloc2ndIndex != SIZE_MAX &&
  8127. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  8128. {
  8129. --nextAlloc2ndIndex;
  8130. }
  8131. // Found non-null allocation.
  8132. if(nextAlloc2ndIndex != SIZE_MAX)
  8133. {
  8134. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  8135. // 1. Process free space before this allocation.
  8136. if(lastOffset < suballoc.offset)
  8137. {
  8138. // There is free space from lastOffset to suballoc.offset.
  8139. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  8140. inoutStats.unusedSize += unusedRangeSize;
  8141. ++inoutStats.unusedRangeCount;
  8142. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
  8143. }
  8144. // 2. Process this allocation.
  8145. // There is allocation with suballoc.offset, suballoc.size.
  8146. ++inoutStats.allocationCount;
  8147. // 3. Prepare for next iteration.
  8148. lastOffset = suballoc.offset + suballoc.size;
  8149. --nextAlloc2ndIndex;
  8150. }
  8151. // We are at the end.
  8152. else
  8153. {
  8154. if(lastOffset < size)
  8155. {
  8156. // There is free space from lastOffset to size.
  8157. const VkDeviceSize unusedRangeSize = size - lastOffset;
  8158. inoutStats.unusedSize += unusedRangeSize;
  8159. ++inoutStats.unusedRangeCount;
  8160. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
  8161. }
  8162. // End of loop.
  8163. lastOffset = size;
  8164. }
  8165. }
  8166. }
  8167. }
  8168. #if VMA_STATS_STRING_ENABLED
  8169. void VmaBlockMetadata_Linear::PrintDetailedMap(class VmaJsonWriter& json) const
  8170. {
  8171. const VkDeviceSize size = GetSize();
  8172. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  8173. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  8174. const size_t suballoc1stCount = suballocations1st.size();
  8175. const size_t suballoc2ndCount = suballocations2nd.size();
  8176. // FIRST PASS
  8177. size_t unusedRangeCount = 0;
  8178. VkDeviceSize usedBytes = 0;
  8179. VkDeviceSize lastOffset = 0;
  8180. size_t alloc2ndCount = 0;
  8181. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  8182. {
  8183. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  8184. size_t nextAlloc2ndIndex = 0;
  8185. while(lastOffset < freeSpace2ndTo1stEnd)
  8186. {
  8187. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  8188. while(nextAlloc2ndIndex < suballoc2ndCount &&
  8189. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  8190. {
  8191. ++nextAlloc2ndIndex;
  8192. }
  8193. // Found non-null allocation.
  8194. if(nextAlloc2ndIndex < suballoc2ndCount)
  8195. {
  8196. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  8197. // 1. Process free space before this allocation.
  8198. if(lastOffset < suballoc.offset)
  8199. {
  8200. // There is free space from lastOffset to suballoc.offset.
  8201. ++unusedRangeCount;
  8202. }
  8203. // 2. Process this allocation.
  8204. // There is allocation with suballoc.offset, suballoc.size.
  8205. ++alloc2ndCount;
  8206. usedBytes += suballoc.size;
  8207. // 3. Prepare for next iteration.
  8208. lastOffset = suballoc.offset + suballoc.size;
  8209. ++nextAlloc2ndIndex;
  8210. }
  8211. // We are at the end.
  8212. else
  8213. {
  8214. if(lastOffset < freeSpace2ndTo1stEnd)
  8215. {
  8216. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  8217. ++unusedRangeCount;
  8218. }
  8219. // End of loop.
  8220. lastOffset = freeSpace2ndTo1stEnd;
  8221. }
  8222. }
  8223. }
  8224. size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
  8225. size_t alloc1stCount = 0;
  8226. const VkDeviceSize freeSpace1stTo2ndEnd =
  8227. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
  8228. while(lastOffset < freeSpace1stTo2ndEnd)
  8229. {
  8230. // Find next non-null allocation or move nextAllocIndex to the end.
  8231. while(nextAlloc1stIndex < suballoc1stCount &&
  8232. suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE)
  8233. {
  8234. ++nextAlloc1stIndex;
  8235. }
  8236. // Found non-null allocation.
  8237. if(nextAlloc1stIndex < suballoc1stCount)
  8238. {
  8239. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  8240. // 1. Process free space before this allocation.
  8241. if(lastOffset < suballoc.offset)
  8242. {
  8243. // There is free space from lastOffset to suballoc.offset.
  8244. ++unusedRangeCount;
  8245. }
  8246. // 2. Process this allocation.
  8247. // There is allocation with suballoc.offset, suballoc.size.
  8248. ++alloc1stCount;
  8249. usedBytes += suballoc.size;
  8250. // 3. Prepare for next iteration.
  8251. lastOffset = suballoc.offset + suballoc.size;
  8252. ++nextAlloc1stIndex;
  8253. }
  8254. // We are at the end.
  8255. else
  8256. {
  8257. if(lastOffset < size)
  8258. {
  8259. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  8260. ++unusedRangeCount;
  8261. }
  8262. // End of loop.
  8263. lastOffset = freeSpace1stTo2ndEnd;
  8264. }
  8265. }
  8266. if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  8267. {
  8268. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  8269. while(lastOffset < size)
  8270. {
  8271. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  8272. while(nextAlloc2ndIndex != SIZE_MAX &&
  8273. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  8274. {
  8275. --nextAlloc2ndIndex;
  8276. }
  8277. // Found non-null allocation.
  8278. if(nextAlloc2ndIndex != SIZE_MAX)
  8279. {
  8280. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  8281. // 1. Process free space before this allocation.
  8282. if(lastOffset < suballoc.offset)
  8283. {
  8284. // There is free space from lastOffset to suballoc.offset.
  8285. ++unusedRangeCount;
  8286. }
  8287. // 2. Process this allocation.
  8288. // There is allocation with suballoc.offset, suballoc.size.
  8289. ++alloc2ndCount;
  8290. usedBytes += suballoc.size;
  8291. // 3. Prepare for next iteration.
  8292. lastOffset = suballoc.offset + suballoc.size;
  8293. --nextAlloc2ndIndex;
  8294. }
  8295. // We are at the end.
  8296. else
  8297. {
  8298. if(lastOffset < size)
  8299. {
  8300. // There is free space from lastOffset to size.
  8301. ++unusedRangeCount;
  8302. }
  8303. // End of loop.
  8304. lastOffset = size;
  8305. }
  8306. }
  8307. }
  8308. const VkDeviceSize unusedBytes = size - usedBytes;
  8309. PrintDetailedMap_Begin(json, unusedBytes, alloc1stCount + alloc2ndCount, unusedRangeCount);
  8310. // SECOND PASS
  8311. lastOffset = 0;
  8312. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  8313. {
  8314. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  8315. size_t nextAlloc2ndIndex = 0;
  8316. while(lastOffset < freeSpace2ndTo1stEnd)
  8317. {
  8318. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  8319. while(nextAlloc2ndIndex < suballoc2ndCount &&
  8320. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  8321. {
  8322. ++nextAlloc2ndIndex;
  8323. }
  8324. // Found non-null allocation.
  8325. if(nextAlloc2ndIndex < suballoc2ndCount)
  8326. {
  8327. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  8328. // 1. Process free space before this allocation.
  8329. if(lastOffset < suballoc.offset)
  8330. {
  8331. // There is free space from lastOffset to suballoc.offset.
  8332. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  8333. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  8334. }
  8335. // 2. Process this allocation.
  8336. // There is allocation with suballoc.offset, suballoc.size.
  8337. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.hAllocation);
  8338. // 3. Prepare for next iteration.
  8339. lastOffset = suballoc.offset + suballoc.size;
  8340. ++nextAlloc2ndIndex;
  8341. }
  8342. // We are at the end.
  8343. else
  8344. {
  8345. if(lastOffset < freeSpace2ndTo1stEnd)
  8346. {
  8347. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  8348. const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset;
  8349. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  8350. }
  8351. // End of loop.
  8352. lastOffset = freeSpace2ndTo1stEnd;
  8353. }
  8354. }
  8355. }
  8356. nextAlloc1stIndex = m_1stNullItemsBeginCount;
  8357. while(lastOffset < freeSpace1stTo2ndEnd)
  8358. {
  8359. // Find next non-null allocation or move nextAllocIndex to the end.
  8360. while(nextAlloc1stIndex < suballoc1stCount &&
  8361. suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE)
  8362. {
  8363. ++nextAlloc1stIndex;
  8364. }
  8365. // Found non-null allocation.
  8366. if(nextAlloc1stIndex < suballoc1stCount)
  8367. {
  8368. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  8369. // 1. Process free space before this allocation.
  8370. if(lastOffset < suballoc.offset)
  8371. {
  8372. // There is free space from lastOffset to suballoc.offset.
  8373. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  8374. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  8375. }
  8376. // 2. Process this allocation.
  8377. // There is allocation with suballoc.offset, suballoc.size.
  8378. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.hAllocation);
  8379. // 3. Prepare for next iteration.
  8380. lastOffset = suballoc.offset + suballoc.size;
  8381. ++nextAlloc1stIndex;
  8382. }
  8383. // We are at the end.
  8384. else
  8385. {
  8386. if(lastOffset < freeSpace1stTo2ndEnd)
  8387. {
  8388. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  8389. const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset;
  8390. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  8391. }
  8392. // End of loop.
  8393. lastOffset = freeSpace1stTo2ndEnd;
  8394. }
  8395. }
  8396. if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  8397. {
  8398. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  8399. while(lastOffset < size)
  8400. {
  8401. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  8402. while(nextAlloc2ndIndex != SIZE_MAX &&
  8403. suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
  8404. {
  8405. --nextAlloc2ndIndex;
  8406. }
  8407. // Found non-null allocation.
  8408. if(nextAlloc2ndIndex != SIZE_MAX)
  8409. {
  8410. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  8411. // 1. Process free space before this allocation.
  8412. if(lastOffset < suballoc.offset)
  8413. {
  8414. // There is free space from lastOffset to suballoc.offset.
  8415. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  8416. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  8417. }
  8418. // 2. Process this allocation.
  8419. // There is allocation with suballoc.offset, suballoc.size.
  8420. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.hAllocation);
  8421. // 3. Prepare for next iteration.
  8422. lastOffset = suballoc.offset + suballoc.size;
  8423. --nextAlloc2ndIndex;
  8424. }
  8425. // We are at the end.
  8426. else
  8427. {
  8428. if(lastOffset < size)
  8429. {
  8430. // There is free space from lastOffset to size.
  8431. const VkDeviceSize unusedRangeSize = size - lastOffset;
  8432. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  8433. }
  8434. // End of loop.
  8435. lastOffset = size;
  8436. }
  8437. }
  8438. }
  8439. PrintDetailedMap_End(json);
  8440. }
  8441. #endif // #if VMA_STATS_STRING_ENABLED
  8442. bool VmaBlockMetadata_Linear::CreateAllocationRequest(
  8443. uint32_t currentFrameIndex,
  8444. uint32_t frameInUseCount,
  8445. VkDeviceSize bufferImageGranularity,
  8446. VkDeviceSize allocSize,
  8447. VkDeviceSize allocAlignment,
  8448. bool upperAddress,
  8449. VmaSuballocationType allocType,
  8450. bool canMakeOtherLost,
  8451. uint32_t strategy,
  8452. VmaAllocationRequest* pAllocationRequest)
  8453. {
  8454. VMA_ASSERT(allocSize > 0);
  8455. VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
  8456. VMA_ASSERT(pAllocationRequest != VMA_NULL);
  8457. VMA_HEAVY_ASSERT(Validate());
  8458. return upperAddress ?
  8459. CreateAllocationRequest_UpperAddress(
  8460. currentFrameIndex, frameInUseCount, bufferImageGranularity,
  8461. allocSize, allocAlignment, allocType, canMakeOtherLost, strategy, pAllocationRequest) :
  8462. CreateAllocationRequest_LowerAddress(
  8463. currentFrameIndex, frameInUseCount, bufferImageGranularity,
  8464. allocSize, allocAlignment, allocType, canMakeOtherLost, strategy, pAllocationRequest);
  8465. }
  8466. bool VmaBlockMetadata_Linear::CreateAllocationRequest_UpperAddress(
  8467. uint32_t currentFrameIndex,
  8468. uint32_t frameInUseCount,
  8469. VkDeviceSize bufferImageGranularity,
  8470. VkDeviceSize allocSize,
  8471. VkDeviceSize allocAlignment,
  8472. VmaSuballocationType allocType,
  8473. bool canMakeOtherLost,
  8474. uint32_t strategy,
  8475. VmaAllocationRequest* pAllocationRequest)
  8476. {
  8477. const VkDeviceSize size = GetSize();
  8478. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  8479. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  8480. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  8481. {
  8482. VMA_ASSERT(0 && "Trying to use pool with linear algorithm as double stack, while it is already being used as ring buffer.");
  8483. return false;
  8484. }
  8485. // Try to allocate before 2nd.back(), or end of block if 2nd.empty().
  8486. if(allocSize > size)
  8487. {
  8488. return false;
  8489. }
  8490. VkDeviceSize resultBaseOffset = size - allocSize;
  8491. if(!suballocations2nd.empty())
  8492. {
  8493. const VmaSuballocation& lastSuballoc = suballocations2nd.back();
  8494. resultBaseOffset = lastSuballoc.offset - allocSize;
  8495. if(allocSize > lastSuballoc.offset)
  8496. {
  8497. return false;
  8498. }
  8499. }
  8500. // Start from offset equal to end of free space.
  8501. VkDeviceSize resultOffset = resultBaseOffset;
  8502. // Apply VMA_DEBUG_MARGIN at the end.
  8503. if(VMA_DEBUG_MARGIN > 0)
  8504. {
  8505. if(resultOffset < VMA_DEBUG_MARGIN)
  8506. {
  8507. return false;
  8508. }
  8509. resultOffset -= VMA_DEBUG_MARGIN;
  8510. }
  8511. // Apply alignment.
  8512. resultOffset = VmaAlignDown(resultOffset, allocAlignment);
  8513. // Check next suballocations from 2nd for BufferImageGranularity conflicts.
  8514. // Make bigger alignment if necessary.
  8515. if(bufferImageGranularity > 1 && !suballocations2nd.empty())
  8516. {
  8517. bool bufferImageGranularityConflict = false;
  8518. for(size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; )
  8519. {
  8520. const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex];
  8521. if(VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  8522. {
  8523. if(VmaIsBufferImageGranularityConflict(nextSuballoc.type, allocType))
  8524. {
  8525. bufferImageGranularityConflict = true;
  8526. break;
  8527. }
  8528. }
  8529. else
  8530. // Already on previous page.
  8531. break;
  8532. }
  8533. if(bufferImageGranularityConflict)
  8534. {
  8535. resultOffset = VmaAlignDown(resultOffset, bufferImageGranularity);
  8536. }
  8537. }
  8538. // There is enough free space.
  8539. const VkDeviceSize endOf1st = !suballocations1st.empty() ?
  8540. suballocations1st.back().offset + suballocations1st.back().size :
  8541. 0;
  8542. if(endOf1st + VMA_DEBUG_MARGIN <= resultOffset)
  8543. {
  8544. // Check previous suballocations for BufferImageGranularity conflicts.
  8545. // If conflict exists, allocation cannot be made here.
  8546. if(bufferImageGranularity > 1)
  8547. {
  8548. for(size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; )
  8549. {
  8550. const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex];
  8551. if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
  8552. {
  8553. if(VmaIsBufferImageGranularityConflict(allocType, prevSuballoc.type))
  8554. {
  8555. return false;
  8556. }
  8557. }
  8558. else
  8559. {
  8560. // Already on next page.
  8561. break;
  8562. }
  8563. }
  8564. }
  8565. // All tests passed: Success.
  8566. pAllocationRequest->offset = resultOffset;
  8567. pAllocationRequest->sumFreeSize = resultBaseOffset + allocSize - endOf1st;
  8568. pAllocationRequest->sumItemSize = 0;
  8569. // pAllocationRequest->item unused.
  8570. pAllocationRequest->itemsToMakeLostCount = 0;
  8571. pAllocationRequest->type = VmaAllocationRequestType::UpperAddress;
  8572. return true;
  8573. }
  8574. return false;
  8575. }
  8576. bool VmaBlockMetadata_Linear::CreateAllocationRequest_LowerAddress(
  8577. uint32_t currentFrameIndex,
  8578. uint32_t frameInUseCount,
  8579. VkDeviceSize bufferImageGranularity,
  8580. VkDeviceSize allocSize,
  8581. VkDeviceSize allocAlignment,
  8582. VmaSuballocationType allocType,
  8583. bool canMakeOtherLost,
  8584. uint32_t strategy,
  8585. VmaAllocationRequest* pAllocationRequest)
  8586. {
  8587. const VkDeviceSize size = GetSize();
  8588. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  8589. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  8590. if(m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  8591. {
  8592. // Try to allocate at the end of 1st vector.
  8593. VkDeviceSize resultBaseOffset = 0;
  8594. if(!suballocations1st.empty())
  8595. {
  8596. const VmaSuballocation& lastSuballoc = suballocations1st.back();
  8597. resultBaseOffset = lastSuballoc.offset + lastSuballoc.size;
  8598. }
  8599. // Start from offset equal to beginning of free space.
  8600. VkDeviceSize resultOffset = resultBaseOffset;
  8601. // Apply VMA_DEBUG_MARGIN at the beginning.
  8602. if(VMA_DEBUG_MARGIN > 0)
  8603. {
  8604. resultOffset += VMA_DEBUG_MARGIN;
  8605. }
  8606. // Apply alignment.
  8607. resultOffset = VmaAlignUp(resultOffset, allocAlignment);
  8608. // Check previous suballocations for BufferImageGranularity conflicts.
  8609. // Make bigger alignment if necessary.
  8610. if(bufferImageGranularity > 1 && !suballocations1st.empty())
  8611. {
  8612. bool bufferImageGranularityConflict = false;
  8613. for(size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; )
  8614. {
  8615. const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex];
  8616. if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
  8617. {
  8618. if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
  8619. {
  8620. bufferImageGranularityConflict = true;
  8621. break;
  8622. }
  8623. }
  8624. else
  8625. // Already on previous page.
  8626. break;
  8627. }
  8628. if(bufferImageGranularityConflict)
  8629. {
  8630. resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity);
  8631. }
  8632. }
  8633. const VkDeviceSize freeSpaceEnd = m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ?
  8634. suballocations2nd.back().offset : size;
  8635. // There is enough free space at the end after alignment.
  8636. if(resultOffset + allocSize + VMA_DEBUG_MARGIN <= freeSpaceEnd)
  8637. {
  8638. // Check next suballocations for BufferImageGranularity conflicts.
  8639. // If conflict exists, allocation cannot be made here.
  8640. if(bufferImageGranularity > 1 && m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  8641. {
  8642. for(size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; )
  8643. {
  8644. const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex];
  8645. if(VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  8646. {
  8647. if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
  8648. {
  8649. return false;
  8650. }
  8651. }
  8652. else
  8653. {
  8654. // Already on previous page.
  8655. break;
  8656. }
  8657. }
  8658. }
  8659. // All tests passed: Success.
  8660. pAllocationRequest->offset = resultOffset;
  8661. pAllocationRequest->sumFreeSize = freeSpaceEnd - resultBaseOffset;
  8662. pAllocationRequest->sumItemSize = 0;
  8663. // pAllocationRequest->item, customData unused.
  8664. pAllocationRequest->type = VmaAllocationRequestType::EndOf1st;
  8665. pAllocationRequest->itemsToMakeLostCount = 0;
  8666. return true;
  8667. }
  8668. }
  8669. // Wrap-around to end of 2nd vector. Try to allocate there, watching for the
  8670. // beginning of 1st vector as the end of free space.
  8671. if(m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  8672. {
  8673. VMA_ASSERT(!suballocations1st.empty());
  8674. VkDeviceSize resultBaseOffset = 0;
  8675. if(!suballocations2nd.empty())
  8676. {
  8677. const VmaSuballocation& lastSuballoc = suballocations2nd.back();
  8678. resultBaseOffset = lastSuballoc.offset + lastSuballoc.size;
  8679. }
  8680. // Start from offset equal to beginning of free space.
  8681. VkDeviceSize resultOffset = resultBaseOffset;
  8682. // Apply VMA_DEBUG_MARGIN at the beginning.
  8683. if(VMA_DEBUG_MARGIN > 0)
  8684. {
  8685. resultOffset += VMA_DEBUG_MARGIN;
  8686. }
  8687. // Apply alignment.
  8688. resultOffset = VmaAlignUp(resultOffset, allocAlignment);
  8689. // Check previous suballocations for BufferImageGranularity conflicts.
  8690. // Make bigger alignment if necessary.
  8691. if(bufferImageGranularity > 1 && !suballocations2nd.empty())
  8692. {
  8693. bool bufferImageGranularityConflict = false;
  8694. for(size_t prevSuballocIndex = suballocations2nd.size(); prevSuballocIndex--; )
  8695. {
  8696. const VmaSuballocation& prevSuballoc = suballocations2nd[prevSuballocIndex];
  8697. if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
  8698. {
  8699. if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
  8700. {
  8701. bufferImageGranularityConflict = true;
  8702. break;
  8703. }
  8704. }
  8705. else
  8706. // Already on previous page.
  8707. break;
  8708. }
  8709. if(bufferImageGranularityConflict)
  8710. {
  8711. resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity);
  8712. }
  8713. }
  8714. pAllocationRequest->itemsToMakeLostCount = 0;
  8715. pAllocationRequest->sumItemSize = 0;
  8716. size_t index1st = m_1stNullItemsBeginCount;
  8717. if(canMakeOtherLost)
  8718. {
  8719. while(index1st < suballocations1st.size() &&
  8720. resultOffset + allocSize + VMA_DEBUG_MARGIN > suballocations1st[index1st].offset)
  8721. {
  8722. // Next colliding allocation at the beginning of 1st vector found. Try to make it lost.
  8723. const VmaSuballocation& suballoc = suballocations1st[index1st];
  8724. if(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE)
  8725. {
  8726. // No problem.
  8727. }
  8728. else
  8729. {
  8730. VMA_ASSERT(suballoc.hAllocation != VK_NULL_HANDLE);
  8731. if(suballoc.hAllocation->CanBecomeLost() &&
  8732. suballoc.hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
  8733. {
  8734. ++pAllocationRequest->itemsToMakeLostCount;
  8735. pAllocationRequest->sumItemSize += suballoc.size;
  8736. }
  8737. else
  8738. {
  8739. return false;
  8740. }
  8741. }
  8742. ++index1st;
  8743. }
  8744. // Check next suballocations for BufferImageGranularity conflicts.
  8745. // If conflict exists, we must mark more allocations lost or fail.
  8746. if(bufferImageGranularity > 1)
  8747. {
  8748. while(index1st < suballocations1st.size())
  8749. {
  8750. const VmaSuballocation& suballoc = suballocations1st[index1st];
  8751. if(VmaBlocksOnSamePage(resultOffset, allocSize, suballoc.offset, bufferImageGranularity))
  8752. {
  8753. if(suballoc.hAllocation != VK_NULL_HANDLE)
  8754. {
  8755. // Not checking actual VmaIsBufferImageGranularityConflict(allocType, suballoc.type).
  8756. if(suballoc.hAllocation->CanBecomeLost() &&
  8757. suballoc.hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
  8758. {
  8759. ++pAllocationRequest->itemsToMakeLostCount;
  8760. pAllocationRequest->sumItemSize += suballoc.size;
  8761. }
  8762. else
  8763. {
  8764. return false;
  8765. }
  8766. }
  8767. }
  8768. else
  8769. {
  8770. // Already on next page.
  8771. break;
  8772. }
  8773. ++index1st;
  8774. }
  8775. }
  8776. // Special case: There is not enough room at the end for this allocation, even after making all from the 1st lost.
  8777. if(index1st == suballocations1st.size() &&
  8778. resultOffset + allocSize + VMA_DEBUG_MARGIN > size)
  8779. {
  8780. // TODO: This is a known bug that it's not yet implemented and the allocation is failing.
  8781. VMA_DEBUG_LOG("Unsupported special case in custom pool with linear allocation algorithm used as ring buffer with allocations that can be lost.");
  8782. }
  8783. }
  8784. // There is enough free space at the end after alignment.
  8785. if((index1st == suballocations1st.size() && resultOffset + allocSize + VMA_DEBUG_MARGIN <= size) ||
  8786. (index1st < suballocations1st.size() && resultOffset + allocSize + VMA_DEBUG_MARGIN <= suballocations1st[index1st].offset))
  8787. {
  8788. // Check next suballocations for BufferImageGranularity conflicts.
  8789. // If conflict exists, allocation cannot be made here.
  8790. if(bufferImageGranularity > 1)
  8791. {
  8792. for(size_t nextSuballocIndex = index1st;
  8793. nextSuballocIndex < suballocations1st.size();
  8794. nextSuballocIndex++)
  8795. {
  8796. const VmaSuballocation& nextSuballoc = suballocations1st[nextSuballocIndex];
  8797. if(VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  8798. {
  8799. if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
  8800. {
  8801. return false;
  8802. }
  8803. }
  8804. else
  8805. {
  8806. // Already on next page.
  8807. break;
  8808. }
  8809. }
  8810. }
  8811. // All tests passed: Success.
  8812. pAllocationRequest->offset = resultOffset;
  8813. pAllocationRequest->sumFreeSize =
  8814. (index1st < suballocations1st.size() ? suballocations1st[index1st].offset : size)
  8815. - resultBaseOffset
  8816. - pAllocationRequest->sumItemSize;
  8817. pAllocationRequest->type = VmaAllocationRequestType::EndOf2nd;
  8818. // pAllocationRequest->item, customData unused.
  8819. return true;
  8820. }
  8821. }
  8822. return false;
  8823. }
  8824. bool VmaBlockMetadata_Linear::MakeRequestedAllocationsLost(
  8825. uint32_t currentFrameIndex,
  8826. uint32_t frameInUseCount,
  8827. VmaAllocationRequest* pAllocationRequest)
  8828. {
  8829. if(pAllocationRequest->itemsToMakeLostCount == 0)
  8830. {
  8831. return true;
  8832. }
  8833. VMA_ASSERT(m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER);
  8834. // We always start from 1st.
  8835. SuballocationVectorType* suballocations = &AccessSuballocations1st();
  8836. size_t index = m_1stNullItemsBeginCount;
  8837. size_t madeLostCount = 0;
  8838. while(madeLostCount < pAllocationRequest->itemsToMakeLostCount)
  8839. {
  8840. if(index == suballocations->size())
  8841. {
  8842. index = 0;
  8843. // If we get to the end of 1st, we wrap around to beginning of 2nd of 1st.
  8844. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  8845. {
  8846. suballocations = &AccessSuballocations2nd();
  8847. }
  8848. // else: m_2ndVectorMode == SECOND_VECTOR_EMPTY:
  8849. // suballocations continues pointing at AccessSuballocations1st().
  8850. VMA_ASSERT(!suballocations->empty());
  8851. }
  8852. VmaSuballocation& suballoc = (*suballocations)[index];
  8853. if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  8854. {
  8855. VMA_ASSERT(suballoc.hAllocation != VK_NULL_HANDLE);
  8856. VMA_ASSERT(suballoc.hAllocation->CanBecomeLost());
  8857. if(suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
  8858. {
  8859. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  8860. suballoc.hAllocation = VK_NULL_HANDLE;
  8861. m_SumFreeSize += suballoc.size;
  8862. if(suballocations == &AccessSuballocations1st())
  8863. {
  8864. ++m_1stNullItemsMiddleCount;
  8865. }
  8866. else
  8867. {
  8868. ++m_2ndNullItemsCount;
  8869. }
  8870. ++madeLostCount;
  8871. }
  8872. else
  8873. {
  8874. return false;
  8875. }
  8876. }
  8877. ++index;
  8878. }
  8879. CleanupAfterFree();
  8880. //VMA_HEAVY_ASSERT(Validate()); // Already called by ClanupAfterFree().
  8881. return true;
  8882. }
  8883. uint32_t VmaBlockMetadata_Linear::MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount)
  8884. {
  8885. uint32_t lostAllocationCount = 0;
  8886. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  8887. for(size_t i = m_1stNullItemsBeginCount, count = suballocations1st.size(); i < count; ++i)
  8888. {
  8889. VmaSuballocation& suballoc = suballocations1st[i];
  8890. if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE &&
  8891. suballoc.hAllocation->CanBecomeLost() &&
  8892. suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
  8893. {
  8894. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  8895. suballoc.hAllocation = VK_NULL_HANDLE;
  8896. ++m_1stNullItemsMiddleCount;
  8897. m_SumFreeSize += suballoc.size;
  8898. ++lostAllocationCount;
  8899. }
  8900. }
  8901. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  8902. for(size_t i = 0, count = suballocations2nd.size(); i < count; ++i)
  8903. {
  8904. VmaSuballocation& suballoc = suballocations2nd[i];
  8905. if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE &&
  8906. suballoc.hAllocation->CanBecomeLost() &&
  8907. suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
  8908. {
  8909. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  8910. suballoc.hAllocation = VK_NULL_HANDLE;
  8911. ++m_2ndNullItemsCount;
  8912. m_SumFreeSize += suballoc.size;
  8913. ++lostAllocationCount;
  8914. }
  8915. }
  8916. if(lostAllocationCount)
  8917. {
  8918. CleanupAfterFree();
  8919. }
  8920. return lostAllocationCount;
  8921. }
  8922. VkResult VmaBlockMetadata_Linear::CheckCorruption(const void* pBlockData)
  8923. {
  8924. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  8925. for(size_t i = m_1stNullItemsBeginCount, count = suballocations1st.size(); i < count; ++i)
  8926. {
  8927. const VmaSuballocation& suballoc = suballocations1st[i];
  8928. if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  8929. {
  8930. if(!VmaValidateMagicValue(pBlockData, suballoc.offset - VMA_DEBUG_MARGIN))
  8931. {
  8932. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE VALIDATED ALLOCATION!");
  8933. return VK_ERROR_VALIDATION_FAILED_EXT;
  8934. }
  8935. if(!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size))
  8936. {
  8937. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
  8938. return VK_ERROR_VALIDATION_FAILED_EXT;
  8939. }
  8940. }
  8941. }
  8942. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  8943. for(size_t i = 0, count = suballocations2nd.size(); i < count; ++i)
  8944. {
  8945. const VmaSuballocation& suballoc = suballocations2nd[i];
  8946. if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  8947. {
  8948. if(!VmaValidateMagicValue(pBlockData, suballoc.offset - VMA_DEBUG_MARGIN))
  8949. {
  8950. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE VALIDATED ALLOCATION!");
  8951. return VK_ERROR_VALIDATION_FAILED_EXT;
  8952. }
  8953. if(!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size))
  8954. {
  8955. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
  8956. return VK_ERROR_VALIDATION_FAILED_EXT;
  8957. }
  8958. }
  8959. }
  8960. return VK_SUCCESS;
  8961. }
  8962. void VmaBlockMetadata_Linear::Alloc(
  8963. const VmaAllocationRequest& request,
  8964. VmaSuballocationType type,
  8965. VkDeviceSize allocSize,
  8966. VmaAllocation hAllocation)
  8967. {
  8968. const VmaSuballocation newSuballoc = { request.offset, allocSize, hAllocation, type };
  8969. switch(request.type)
  8970. {
  8971. case VmaAllocationRequestType::UpperAddress:
  8972. {
  8973. VMA_ASSERT(m_2ndVectorMode != SECOND_VECTOR_RING_BUFFER &&
  8974. "CRITICAL ERROR: Trying to use linear allocator as double stack while it was already used as ring buffer.");
  8975. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  8976. suballocations2nd.push_back(newSuballoc);
  8977. m_2ndVectorMode = SECOND_VECTOR_DOUBLE_STACK;
  8978. }
  8979. break;
  8980. case VmaAllocationRequestType::EndOf1st:
  8981. {
  8982. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  8983. VMA_ASSERT(suballocations1st.empty() ||
  8984. request.offset >= suballocations1st.back().offset + suballocations1st.back().size);
  8985. // Check if it fits before the end of the block.
  8986. VMA_ASSERT(request.offset + allocSize <= GetSize());
  8987. suballocations1st.push_back(newSuballoc);
  8988. }
  8989. break;
  8990. case VmaAllocationRequestType::EndOf2nd:
  8991. {
  8992. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  8993. // New allocation at the end of 2-part ring buffer, so before first allocation from 1st vector.
  8994. VMA_ASSERT(!suballocations1st.empty() &&
  8995. request.offset + allocSize <= suballocations1st[m_1stNullItemsBeginCount].offset);
  8996. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  8997. switch(m_2ndVectorMode)
  8998. {
  8999. case SECOND_VECTOR_EMPTY:
  9000. // First allocation from second part ring buffer.
  9001. VMA_ASSERT(suballocations2nd.empty());
  9002. m_2ndVectorMode = SECOND_VECTOR_RING_BUFFER;
  9003. break;
  9004. case SECOND_VECTOR_RING_BUFFER:
  9005. // 2-part ring buffer is already started.
  9006. VMA_ASSERT(!suballocations2nd.empty());
  9007. break;
  9008. case SECOND_VECTOR_DOUBLE_STACK:
  9009. VMA_ASSERT(0 && "CRITICAL ERROR: Trying to use linear allocator as ring buffer while it was already used as double stack.");
  9010. break;
  9011. default:
  9012. VMA_ASSERT(0);
  9013. }
  9014. suballocations2nd.push_back(newSuballoc);
  9015. }
  9016. break;
  9017. default:
  9018. VMA_ASSERT(0 && "CRITICAL INTERNAL ERROR.");
  9019. }
  9020. m_SumFreeSize -= newSuballoc.size;
  9021. }
  9022. void VmaBlockMetadata_Linear::Free(const VmaAllocation allocation)
  9023. {
  9024. FreeAtOffset(allocation->GetOffset());
  9025. }
  9026. void VmaBlockMetadata_Linear::FreeAtOffset(VkDeviceSize offset)
  9027. {
  9028. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  9029. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  9030. if(!suballocations1st.empty())
  9031. {
  9032. // First allocation: Mark it as next empty at the beginning.
  9033. VmaSuballocation& firstSuballoc = suballocations1st[m_1stNullItemsBeginCount];
  9034. if(firstSuballoc.offset == offset)
  9035. {
  9036. firstSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  9037. firstSuballoc.hAllocation = VK_NULL_HANDLE;
  9038. m_SumFreeSize += firstSuballoc.size;
  9039. ++m_1stNullItemsBeginCount;
  9040. CleanupAfterFree();
  9041. return;
  9042. }
  9043. }
  9044. // Last allocation in 2-part ring buffer or top of upper stack (same logic).
  9045. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ||
  9046. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  9047. {
  9048. VmaSuballocation& lastSuballoc = suballocations2nd.back();
  9049. if(lastSuballoc.offset == offset)
  9050. {
  9051. m_SumFreeSize += lastSuballoc.size;
  9052. suballocations2nd.pop_back();
  9053. CleanupAfterFree();
  9054. return;
  9055. }
  9056. }
  9057. // Last allocation in 1st vector.
  9058. else if(m_2ndVectorMode == SECOND_VECTOR_EMPTY)
  9059. {
  9060. VmaSuballocation& lastSuballoc = suballocations1st.back();
  9061. if(lastSuballoc.offset == offset)
  9062. {
  9063. m_SumFreeSize += lastSuballoc.size;
  9064. suballocations1st.pop_back();
  9065. CleanupAfterFree();
  9066. return;
  9067. }
  9068. }
  9069. // Item from the middle of 1st vector.
  9070. {
  9071. VmaSuballocation refSuballoc;
  9072. refSuballoc.offset = offset;
  9073. // Rest of members stays uninitialized intentionally for better performance.
  9074. SuballocationVectorType::iterator it = VmaBinaryFindSorted(
  9075. suballocations1st.begin() + m_1stNullItemsBeginCount,
  9076. suballocations1st.end(),
  9077. refSuballoc,
  9078. VmaSuballocationOffsetLess());
  9079. if(it != suballocations1st.end())
  9080. {
  9081. it->type = VMA_SUBALLOCATION_TYPE_FREE;
  9082. it->hAllocation = VK_NULL_HANDLE;
  9083. ++m_1stNullItemsMiddleCount;
  9084. m_SumFreeSize += it->size;
  9085. CleanupAfterFree();
  9086. return;
  9087. }
  9088. }
  9089. if(m_2ndVectorMode != SECOND_VECTOR_EMPTY)
  9090. {
  9091. // Item from the middle of 2nd vector.
  9092. VmaSuballocation refSuballoc;
  9093. refSuballoc.offset = offset;
  9094. // Rest of members stays uninitialized intentionally for better performance.
  9095. SuballocationVectorType::iterator it = m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ?
  9096. VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetLess()) :
  9097. VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetGreater());
  9098. if(it != suballocations2nd.end())
  9099. {
  9100. it->type = VMA_SUBALLOCATION_TYPE_FREE;
  9101. it->hAllocation = VK_NULL_HANDLE;
  9102. ++m_2ndNullItemsCount;
  9103. m_SumFreeSize += it->size;
  9104. CleanupAfterFree();
  9105. return;
  9106. }
  9107. }
  9108. VMA_ASSERT(0 && "Allocation to free not found in linear allocator!");
  9109. }
  9110. bool VmaBlockMetadata_Linear::ShouldCompact1st() const
  9111. {
  9112. const size_t nullItemCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount;
  9113. const size_t suballocCount = AccessSuballocations1st().size();
  9114. return suballocCount > 32 && nullItemCount * 2 >= (suballocCount - nullItemCount) * 3;
  9115. }
  9116. void VmaBlockMetadata_Linear::CleanupAfterFree()
  9117. {
  9118. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  9119. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  9120. if(IsEmpty())
  9121. {
  9122. suballocations1st.clear();
  9123. suballocations2nd.clear();
  9124. m_1stNullItemsBeginCount = 0;
  9125. m_1stNullItemsMiddleCount = 0;
  9126. m_2ndNullItemsCount = 0;
  9127. m_2ndVectorMode = SECOND_VECTOR_EMPTY;
  9128. }
  9129. else
  9130. {
  9131. const size_t suballoc1stCount = suballocations1st.size();
  9132. const size_t nullItem1stCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount;
  9133. VMA_ASSERT(nullItem1stCount <= suballoc1stCount);
  9134. // Find more null items at the beginning of 1st vector.
  9135. while(m_1stNullItemsBeginCount < suballoc1stCount &&
  9136. suballocations1st[m_1stNullItemsBeginCount].hAllocation == VK_NULL_HANDLE)
  9137. {
  9138. ++m_1stNullItemsBeginCount;
  9139. --m_1stNullItemsMiddleCount;
  9140. }
  9141. // Find more null items at the end of 1st vector.
  9142. while(m_1stNullItemsMiddleCount > 0 &&
  9143. suballocations1st.back().hAllocation == VK_NULL_HANDLE)
  9144. {
  9145. --m_1stNullItemsMiddleCount;
  9146. suballocations1st.pop_back();
  9147. }
  9148. // Find more null items at the end of 2nd vector.
  9149. while(m_2ndNullItemsCount > 0 &&
  9150. suballocations2nd.back().hAllocation == VK_NULL_HANDLE)
  9151. {
  9152. --m_2ndNullItemsCount;
  9153. suballocations2nd.pop_back();
  9154. }
  9155. // Find more null items at the beginning of 2nd vector.
  9156. while(m_2ndNullItemsCount > 0 &&
  9157. suballocations2nd[0].hAllocation == VK_NULL_HANDLE)
  9158. {
  9159. --m_2ndNullItemsCount;
  9160. VmaVectorRemove(suballocations2nd, 0);
  9161. }
  9162. if(ShouldCompact1st())
  9163. {
  9164. const size_t nonNullItemCount = suballoc1stCount - nullItem1stCount;
  9165. size_t srcIndex = m_1stNullItemsBeginCount;
  9166. for(size_t dstIndex = 0; dstIndex < nonNullItemCount; ++dstIndex)
  9167. {
  9168. while(suballocations1st[srcIndex].hAllocation == VK_NULL_HANDLE)
  9169. {
  9170. ++srcIndex;
  9171. }
  9172. if(dstIndex != srcIndex)
  9173. {
  9174. suballocations1st[dstIndex] = suballocations1st[srcIndex];
  9175. }
  9176. ++srcIndex;
  9177. }
  9178. suballocations1st.resize(nonNullItemCount);
  9179. m_1stNullItemsBeginCount = 0;
  9180. m_1stNullItemsMiddleCount = 0;
  9181. }
  9182. // 2nd vector became empty.
  9183. if(suballocations2nd.empty())
  9184. {
  9185. m_2ndVectorMode = SECOND_VECTOR_EMPTY;
  9186. }
  9187. // 1st vector became empty.
  9188. if(suballocations1st.size() - m_1stNullItemsBeginCount == 0)
  9189. {
  9190. suballocations1st.clear();
  9191. m_1stNullItemsBeginCount = 0;
  9192. if(!suballocations2nd.empty() && m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  9193. {
  9194. // Swap 1st with 2nd. Now 2nd is empty.
  9195. m_2ndVectorMode = SECOND_VECTOR_EMPTY;
  9196. m_1stNullItemsMiddleCount = m_2ndNullItemsCount;
  9197. while(m_1stNullItemsBeginCount < suballocations2nd.size() &&
  9198. suballocations2nd[m_1stNullItemsBeginCount].hAllocation == VK_NULL_HANDLE)
  9199. {
  9200. ++m_1stNullItemsBeginCount;
  9201. --m_1stNullItemsMiddleCount;
  9202. }
  9203. m_2ndNullItemsCount = 0;
  9204. m_1stVectorIndex ^= 1;
  9205. }
  9206. }
  9207. }
  9208. VMA_HEAVY_ASSERT(Validate());
  9209. }
  9210. ////////////////////////////////////////////////////////////////////////////////
  9211. // class VmaBlockMetadata_Buddy
  9212. VmaBlockMetadata_Buddy::VmaBlockMetadata_Buddy(VmaAllocator hAllocator) :
  9213. VmaBlockMetadata(hAllocator),
  9214. m_Root(VMA_NULL),
  9215. m_AllocationCount(0),
  9216. m_FreeCount(1),
  9217. m_SumFreeSize(0)
  9218. {
  9219. memset(m_FreeList, 0, sizeof(m_FreeList));
  9220. }
  9221. VmaBlockMetadata_Buddy::~VmaBlockMetadata_Buddy()
  9222. {
  9223. DeleteNode(m_Root);
  9224. }
  9225. void VmaBlockMetadata_Buddy::Init(VkDeviceSize size)
  9226. {
  9227. VmaBlockMetadata::Init(size);
  9228. m_UsableSize = VmaPrevPow2(size);
  9229. m_SumFreeSize = m_UsableSize;
  9230. // Calculate m_LevelCount.
  9231. m_LevelCount = 1;
  9232. while(m_LevelCount < MAX_LEVELS &&
  9233. LevelToNodeSize(m_LevelCount) >= MIN_NODE_SIZE)
  9234. {
  9235. ++m_LevelCount;
  9236. }
  9237. Node* rootNode = vma_new(GetAllocationCallbacks(), Node)();
  9238. rootNode->offset = 0;
  9239. rootNode->type = Node::TYPE_FREE;
  9240. rootNode->parent = VMA_NULL;
  9241. rootNode->buddy = VMA_NULL;
  9242. m_Root = rootNode;
  9243. AddToFreeListFront(0, rootNode);
  9244. }
  9245. bool VmaBlockMetadata_Buddy::Validate() const
  9246. {
  9247. // Validate tree.
  9248. ValidationContext ctx;
  9249. if(!ValidateNode(ctx, VMA_NULL, m_Root, 0, LevelToNodeSize(0)))
  9250. {
  9251. VMA_VALIDATE(false && "ValidateNode failed.");
  9252. }
  9253. VMA_VALIDATE(m_AllocationCount == ctx.calculatedAllocationCount);
  9254. VMA_VALIDATE(m_SumFreeSize == ctx.calculatedSumFreeSize);
  9255. // Validate free node lists.
  9256. for(uint32_t level = 0; level < m_LevelCount; ++level)
  9257. {
  9258. VMA_VALIDATE(m_FreeList[level].front == VMA_NULL ||
  9259. m_FreeList[level].front->free.prev == VMA_NULL);
  9260. for(Node* node = m_FreeList[level].front;
  9261. node != VMA_NULL;
  9262. node = node->free.next)
  9263. {
  9264. VMA_VALIDATE(node->type == Node::TYPE_FREE);
  9265. if(node->free.next == VMA_NULL)
  9266. {
  9267. VMA_VALIDATE(m_FreeList[level].back == node);
  9268. }
  9269. else
  9270. {
  9271. VMA_VALIDATE(node->free.next->free.prev == node);
  9272. }
  9273. }
  9274. }
  9275. // Validate that free lists ar higher levels are empty.
  9276. for(uint32_t level = m_LevelCount; level < MAX_LEVELS; ++level)
  9277. {
  9278. VMA_VALIDATE(m_FreeList[level].front == VMA_NULL && m_FreeList[level].back == VMA_NULL);
  9279. }
  9280. return true;
  9281. }
  9282. VkDeviceSize VmaBlockMetadata_Buddy::GetUnusedRangeSizeMax() const
  9283. {
  9284. for(uint32_t level = 0; level < m_LevelCount; ++level)
  9285. {
  9286. if(m_FreeList[level].front != VMA_NULL)
  9287. {
  9288. return LevelToNodeSize(level);
  9289. }
  9290. }
  9291. return 0;
  9292. }
  9293. void VmaBlockMetadata_Buddy::CalcAllocationStatInfo(VmaStatInfo& outInfo) const
  9294. {
  9295. const VkDeviceSize unusableSize = GetUnusableSize();
  9296. outInfo.blockCount = 1;
  9297. outInfo.allocationCount = outInfo.unusedRangeCount = 0;
  9298. outInfo.usedBytes = outInfo.unusedBytes = 0;
  9299. outInfo.allocationSizeMax = outInfo.unusedRangeSizeMax = 0;
  9300. outInfo.allocationSizeMin = outInfo.unusedRangeSizeMin = UINT64_MAX;
  9301. outInfo.allocationSizeAvg = outInfo.unusedRangeSizeAvg = 0; // Unused.
  9302. CalcAllocationStatInfoNode(outInfo, m_Root, LevelToNodeSize(0));
  9303. if(unusableSize > 0)
  9304. {
  9305. ++outInfo.unusedRangeCount;
  9306. outInfo.unusedBytes += unusableSize;
  9307. outInfo.unusedRangeSizeMax = VMA_MAX(outInfo.unusedRangeSizeMax, unusableSize);
  9308. outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusableSize);
  9309. }
  9310. }
  9311. void VmaBlockMetadata_Buddy::AddPoolStats(VmaPoolStats& inoutStats) const
  9312. {
  9313. const VkDeviceSize unusableSize = GetUnusableSize();
  9314. inoutStats.size += GetSize();
  9315. inoutStats.unusedSize += m_SumFreeSize + unusableSize;
  9316. inoutStats.allocationCount += m_AllocationCount;
  9317. inoutStats.unusedRangeCount += m_FreeCount;
  9318. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, GetUnusedRangeSizeMax());
  9319. if(unusableSize > 0)
  9320. {
  9321. ++inoutStats.unusedRangeCount;
  9322. // Not updating inoutStats.unusedRangeSizeMax with unusableSize because this space is not available for allocations.
  9323. }
  9324. }
  9325. #if VMA_STATS_STRING_ENABLED
  9326. void VmaBlockMetadata_Buddy::PrintDetailedMap(class VmaJsonWriter& json) const
  9327. {
  9328. // TODO optimize
  9329. VmaStatInfo stat;
  9330. CalcAllocationStatInfo(stat);
  9331. PrintDetailedMap_Begin(
  9332. json,
  9333. stat.unusedBytes,
  9334. stat.allocationCount,
  9335. stat.unusedRangeCount);
  9336. PrintDetailedMapNode(json, m_Root, LevelToNodeSize(0));
  9337. const VkDeviceSize unusableSize = GetUnusableSize();
  9338. if(unusableSize > 0)
  9339. {
  9340. PrintDetailedMap_UnusedRange(json,
  9341. m_UsableSize, // offset
  9342. unusableSize); // size
  9343. }
  9344. PrintDetailedMap_End(json);
  9345. }
  9346. #endif // #if VMA_STATS_STRING_ENABLED
  9347. bool VmaBlockMetadata_Buddy::CreateAllocationRequest(
  9348. uint32_t currentFrameIndex,
  9349. uint32_t frameInUseCount,
  9350. VkDeviceSize bufferImageGranularity,
  9351. VkDeviceSize allocSize,
  9352. VkDeviceSize allocAlignment,
  9353. bool upperAddress,
  9354. VmaSuballocationType allocType,
  9355. bool canMakeOtherLost,
  9356. uint32_t strategy,
  9357. VmaAllocationRequest* pAllocationRequest)
  9358. {
  9359. VMA_ASSERT(!upperAddress && "VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT can be used only with linear algorithm.");
  9360. // Simple way to respect bufferImageGranularity. May be optimized some day.
  9361. // Whenever it might be an OPTIMAL image...
  9362. if(allocType == VMA_SUBALLOCATION_TYPE_UNKNOWN ||
  9363. allocType == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
  9364. allocType == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL)
  9365. {
  9366. allocAlignment = VMA_MAX(allocAlignment, bufferImageGranularity);
  9367. allocSize = VMA_MAX(allocSize, bufferImageGranularity);
  9368. }
  9369. if(allocSize > m_UsableSize)
  9370. {
  9371. return false;
  9372. }
  9373. const uint32_t targetLevel = AllocSizeToLevel(allocSize);
  9374. for(uint32_t level = targetLevel + 1; level--; )
  9375. {
  9376. for(Node* freeNode = m_FreeList[level].front;
  9377. freeNode != VMA_NULL;
  9378. freeNode = freeNode->free.next)
  9379. {
  9380. if(freeNode->offset % allocAlignment == 0)
  9381. {
  9382. pAllocationRequest->type = VmaAllocationRequestType::Normal;
  9383. pAllocationRequest->offset = freeNode->offset;
  9384. pAllocationRequest->sumFreeSize = LevelToNodeSize(level);
  9385. pAllocationRequest->sumItemSize = 0;
  9386. pAllocationRequest->itemsToMakeLostCount = 0;
  9387. pAllocationRequest->customData = (void*)(uintptr_t)level;
  9388. return true;
  9389. }
  9390. }
  9391. }
  9392. return false;
  9393. }
  9394. bool VmaBlockMetadata_Buddy::MakeRequestedAllocationsLost(
  9395. uint32_t currentFrameIndex,
  9396. uint32_t frameInUseCount,
  9397. VmaAllocationRequest* pAllocationRequest)
  9398. {
  9399. /*
  9400. Lost allocations are not supported in buddy allocator at the moment.
  9401. Support might be added in the future.
  9402. */
  9403. return pAllocationRequest->itemsToMakeLostCount == 0;
  9404. }
  9405. uint32_t VmaBlockMetadata_Buddy::MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount)
  9406. {
  9407. /*
  9408. Lost allocations are not supported in buddy allocator at the moment.
  9409. Support might be added in the future.
  9410. */
  9411. return 0;
  9412. }
  9413. void VmaBlockMetadata_Buddy::Alloc(
  9414. const VmaAllocationRequest& request,
  9415. VmaSuballocationType type,
  9416. VkDeviceSize allocSize,
  9417. VmaAllocation hAllocation)
  9418. {
  9419. VMA_ASSERT(request.type == VmaAllocationRequestType::Normal);
  9420. const uint32_t targetLevel = AllocSizeToLevel(allocSize);
  9421. uint32_t currLevel = (uint32_t)(uintptr_t)request.customData;
  9422. Node* currNode = m_FreeList[currLevel].front;
  9423. VMA_ASSERT(currNode != VMA_NULL && currNode->type == Node::TYPE_FREE);
  9424. while(currNode->offset != request.offset)
  9425. {
  9426. currNode = currNode->free.next;
  9427. VMA_ASSERT(currNode != VMA_NULL && currNode->type == Node::TYPE_FREE);
  9428. }
  9429. // Go down, splitting free nodes.
  9430. while(currLevel < targetLevel)
  9431. {
  9432. // currNode is already first free node at currLevel.
  9433. // Remove it from list of free nodes at this currLevel.
  9434. RemoveFromFreeList(currLevel, currNode);
  9435. const uint32_t childrenLevel = currLevel + 1;
  9436. // Create two free sub-nodes.
  9437. Node* leftChild = vma_new(GetAllocationCallbacks(), Node)();
  9438. Node* rightChild = vma_new(GetAllocationCallbacks(), Node)();
  9439. leftChild->offset = currNode->offset;
  9440. leftChild->type = Node::TYPE_FREE;
  9441. leftChild->parent = currNode;
  9442. leftChild->buddy = rightChild;
  9443. rightChild->offset = currNode->offset + LevelToNodeSize(childrenLevel);
  9444. rightChild->type = Node::TYPE_FREE;
  9445. rightChild->parent = currNode;
  9446. rightChild->buddy = leftChild;
  9447. // Convert current currNode to split type.
  9448. currNode->type = Node::TYPE_SPLIT;
  9449. currNode->split.leftChild = leftChild;
  9450. // Add child nodes to free list. Order is important!
  9451. AddToFreeListFront(childrenLevel, rightChild);
  9452. AddToFreeListFront(childrenLevel, leftChild);
  9453. ++m_FreeCount;
  9454. //m_SumFreeSize -= LevelToNodeSize(currLevel) % 2; // Useful only when level node sizes can be non power of 2.
  9455. ++currLevel;
  9456. currNode = m_FreeList[currLevel].front;
  9457. /*
  9458. We can be sure that currNode, as left child of node previously split,
  9459. also fullfills the alignment requirement.
  9460. */
  9461. }
  9462. // Remove from free list.
  9463. VMA_ASSERT(currLevel == targetLevel &&
  9464. currNode != VMA_NULL &&
  9465. currNode->type == Node::TYPE_FREE);
  9466. RemoveFromFreeList(currLevel, currNode);
  9467. // Convert to allocation node.
  9468. currNode->type = Node::TYPE_ALLOCATION;
  9469. currNode->allocation.alloc = hAllocation;
  9470. ++m_AllocationCount;
  9471. --m_FreeCount;
  9472. m_SumFreeSize -= allocSize;
  9473. }
  9474. void VmaBlockMetadata_Buddy::DeleteNode(Node* node)
  9475. {
  9476. if(node->type == Node::TYPE_SPLIT)
  9477. {
  9478. DeleteNode(node->split.leftChild->buddy);
  9479. DeleteNode(node->split.leftChild);
  9480. }
  9481. vma_delete(GetAllocationCallbacks(), node);
  9482. }
  9483. bool VmaBlockMetadata_Buddy::ValidateNode(ValidationContext& ctx, const Node* parent, const Node* curr, uint32_t level, VkDeviceSize levelNodeSize) const
  9484. {
  9485. VMA_VALIDATE(level < m_LevelCount);
  9486. VMA_VALIDATE(curr->parent == parent);
  9487. VMA_VALIDATE((curr->buddy == VMA_NULL) == (parent == VMA_NULL));
  9488. VMA_VALIDATE(curr->buddy == VMA_NULL || curr->buddy->buddy == curr);
  9489. switch(curr->type)
  9490. {
  9491. case Node::TYPE_FREE:
  9492. // curr->free.prev, next are validated separately.
  9493. ctx.calculatedSumFreeSize += levelNodeSize;
  9494. ++ctx.calculatedFreeCount;
  9495. break;
  9496. case Node::TYPE_ALLOCATION:
  9497. ++ctx.calculatedAllocationCount;
  9498. ctx.calculatedSumFreeSize += levelNodeSize - curr->allocation.alloc->GetSize();
  9499. VMA_VALIDATE(curr->allocation.alloc != VK_NULL_HANDLE);
  9500. break;
  9501. case Node::TYPE_SPLIT:
  9502. {
  9503. const uint32_t childrenLevel = level + 1;
  9504. const VkDeviceSize childrenLevelNodeSize = levelNodeSize / 2;
  9505. const Node* const leftChild = curr->split.leftChild;
  9506. VMA_VALIDATE(leftChild != VMA_NULL);
  9507. VMA_VALIDATE(leftChild->offset == curr->offset);
  9508. if(!ValidateNode(ctx, curr, leftChild, childrenLevel, childrenLevelNodeSize))
  9509. {
  9510. VMA_VALIDATE(false && "ValidateNode for left child failed.");
  9511. }
  9512. const Node* const rightChild = leftChild->buddy;
  9513. VMA_VALIDATE(rightChild->offset == curr->offset + childrenLevelNodeSize);
  9514. if(!ValidateNode(ctx, curr, rightChild, childrenLevel, childrenLevelNodeSize))
  9515. {
  9516. VMA_VALIDATE(false && "ValidateNode for right child failed.");
  9517. }
  9518. }
  9519. break;
  9520. default:
  9521. return false;
  9522. }
  9523. return true;
  9524. }
  9525. uint32_t VmaBlockMetadata_Buddy::AllocSizeToLevel(VkDeviceSize allocSize) const
  9526. {
  9527. // I know this could be optimized somehow e.g. by using std::log2p1 from C++20.
  9528. uint32_t level = 0;
  9529. VkDeviceSize currLevelNodeSize = m_UsableSize;
  9530. VkDeviceSize nextLevelNodeSize = currLevelNodeSize >> 1;
  9531. while(allocSize <= nextLevelNodeSize && level + 1 < m_LevelCount)
  9532. {
  9533. ++level;
  9534. currLevelNodeSize = nextLevelNodeSize;
  9535. nextLevelNodeSize = currLevelNodeSize >> 1;
  9536. }
  9537. return level;
  9538. }
  9539. void VmaBlockMetadata_Buddy::FreeAtOffset(VmaAllocation alloc, VkDeviceSize offset)
  9540. {
  9541. // Find node and level.
  9542. Node* node = m_Root;
  9543. VkDeviceSize nodeOffset = 0;
  9544. uint32_t level = 0;
  9545. VkDeviceSize levelNodeSize = LevelToNodeSize(0);
  9546. while(node->type == Node::TYPE_SPLIT)
  9547. {
  9548. const VkDeviceSize nextLevelSize = levelNodeSize >> 1;
  9549. if(offset < nodeOffset + nextLevelSize)
  9550. {
  9551. node = node->split.leftChild;
  9552. }
  9553. else
  9554. {
  9555. node = node->split.leftChild->buddy;
  9556. nodeOffset += nextLevelSize;
  9557. }
  9558. ++level;
  9559. levelNodeSize = nextLevelSize;
  9560. }
  9561. VMA_ASSERT(node != VMA_NULL && node->type == Node::TYPE_ALLOCATION);
  9562. VMA_ASSERT(alloc == VK_NULL_HANDLE || node->allocation.alloc == alloc);
  9563. ++m_FreeCount;
  9564. --m_AllocationCount;
  9565. m_SumFreeSize += alloc->GetSize();
  9566. node->type = Node::TYPE_FREE;
  9567. // Join free nodes if possible.
  9568. while(level > 0 && node->buddy->type == Node::TYPE_FREE)
  9569. {
  9570. RemoveFromFreeList(level, node->buddy);
  9571. Node* const parent = node->parent;
  9572. vma_delete(GetAllocationCallbacks(), node->buddy);
  9573. vma_delete(GetAllocationCallbacks(), node);
  9574. parent->type = Node::TYPE_FREE;
  9575. node = parent;
  9576. --level;
  9577. //m_SumFreeSize += LevelToNodeSize(level) % 2; // Useful only when level node sizes can be non power of 2.
  9578. --m_FreeCount;
  9579. }
  9580. AddToFreeListFront(level, node);
  9581. }
  9582. void VmaBlockMetadata_Buddy::CalcAllocationStatInfoNode(VmaStatInfo& outInfo, const Node* node, VkDeviceSize levelNodeSize) const
  9583. {
  9584. switch(node->type)
  9585. {
  9586. case Node::TYPE_FREE:
  9587. ++outInfo.unusedRangeCount;
  9588. outInfo.unusedBytes += levelNodeSize;
  9589. outInfo.unusedRangeSizeMax = VMA_MAX(outInfo.unusedRangeSizeMax, levelNodeSize);
  9590. outInfo.unusedRangeSizeMin = VMA_MAX(outInfo.unusedRangeSizeMin, levelNodeSize);
  9591. break;
  9592. case Node::TYPE_ALLOCATION:
  9593. {
  9594. const VkDeviceSize allocSize = node->allocation.alloc->GetSize();
  9595. ++outInfo.allocationCount;
  9596. outInfo.usedBytes += allocSize;
  9597. outInfo.allocationSizeMax = VMA_MAX(outInfo.allocationSizeMax, allocSize);
  9598. outInfo.allocationSizeMin = VMA_MAX(outInfo.allocationSizeMin, allocSize);
  9599. const VkDeviceSize unusedRangeSize = levelNodeSize - allocSize;
  9600. if(unusedRangeSize > 0)
  9601. {
  9602. ++outInfo.unusedRangeCount;
  9603. outInfo.unusedBytes += unusedRangeSize;
  9604. outInfo.unusedRangeSizeMax = VMA_MAX(outInfo.unusedRangeSizeMax, unusedRangeSize);
  9605. outInfo.unusedRangeSizeMin = VMA_MAX(outInfo.unusedRangeSizeMin, unusedRangeSize);
  9606. }
  9607. }
  9608. break;
  9609. case Node::TYPE_SPLIT:
  9610. {
  9611. const VkDeviceSize childrenNodeSize = levelNodeSize / 2;
  9612. const Node* const leftChild = node->split.leftChild;
  9613. CalcAllocationStatInfoNode(outInfo, leftChild, childrenNodeSize);
  9614. const Node* const rightChild = leftChild->buddy;
  9615. CalcAllocationStatInfoNode(outInfo, rightChild, childrenNodeSize);
  9616. }
  9617. break;
  9618. default:
  9619. VMA_ASSERT(0);
  9620. }
  9621. }
  9622. void VmaBlockMetadata_Buddy::AddToFreeListFront(uint32_t level, Node* node)
  9623. {
  9624. VMA_ASSERT(node->type == Node::TYPE_FREE);
  9625. // List is empty.
  9626. Node* const frontNode = m_FreeList[level].front;
  9627. if(frontNode == VMA_NULL)
  9628. {
  9629. VMA_ASSERT(m_FreeList[level].back == VMA_NULL);
  9630. node->free.prev = node->free.next = VMA_NULL;
  9631. m_FreeList[level].front = m_FreeList[level].back = node;
  9632. }
  9633. else
  9634. {
  9635. VMA_ASSERT(frontNode->free.prev == VMA_NULL);
  9636. node->free.prev = VMA_NULL;
  9637. node->free.next = frontNode;
  9638. frontNode->free.prev = node;
  9639. m_FreeList[level].front = node;
  9640. }
  9641. }
  9642. void VmaBlockMetadata_Buddy::RemoveFromFreeList(uint32_t level, Node* node)
  9643. {
  9644. VMA_ASSERT(m_FreeList[level].front != VMA_NULL);
  9645. // It is at the front.
  9646. if(node->free.prev == VMA_NULL)
  9647. {
  9648. VMA_ASSERT(m_FreeList[level].front == node);
  9649. m_FreeList[level].front = node->free.next;
  9650. }
  9651. else
  9652. {
  9653. Node* const prevFreeNode = node->free.prev;
  9654. VMA_ASSERT(prevFreeNode->free.next == node);
  9655. prevFreeNode->free.next = node->free.next;
  9656. }
  9657. // It is at the back.
  9658. if(node->free.next == VMA_NULL)
  9659. {
  9660. VMA_ASSERT(m_FreeList[level].back == node);
  9661. m_FreeList[level].back = node->free.prev;
  9662. }
  9663. else
  9664. {
  9665. Node* const nextFreeNode = node->free.next;
  9666. VMA_ASSERT(nextFreeNode->free.prev == node);
  9667. nextFreeNode->free.prev = node->free.prev;
  9668. }
  9669. }
  9670. #if VMA_STATS_STRING_ENABLED
  9671. void VmaBlockMetadata_Buddy::PrintDetailedMapNode(class VmaJsonWriter& json, const Node* node, VkDeviceSize levelNodeSize) const
  9672. {
  9673. switch(node->type)
  9674. {
  9675. case Node::TYPE_FREE:
  9676. PrintDetailedMap_UnusedRange(json, node->offset, levelNodeSize);
  9677. break;
  9678. case Node::TYPE_ALLOCATION:
  9679. {
  9680. PrintDetailedMap_Allocation(json, node->offset, node->allocation.alloc);
  9681. const VkDeviceSize allocSize = node->allocation.alloc->GetSize();
  9682. if(allocSize < levelNodeSize)
  9683. {
  9684. PrintDetailedMap_UnusedRange(json, node->offset + allocSize, levelNodeSize - allocSize);
  9685. }
  9686. }
  9687. break;
  9688. case Node::TYPE_SPLIT:
  9689. {
  9690. const VkDeviceSize childrenNodeSize = levelNodeSize / 2;
  9691. const Node* const leftChild = node->split.leftChild;
  9692. PrintDetailedMapNode(json, leftChild, childrenNodeSize);
  9693. const Node* const rightChild = leftChild->buddy;
  9694. PrintDetailedMapNode(json, rightChild, childrenNodeSize);
  9695. }
  9696. break;
  9697. default:
  9698. VMA_ASSERT(0);
  9699. }
  9700. }
  9701. #endif // #if VMA_STATS_STRING_ENABLED
  9702. ////////////////////////////////////////////////////////////////////////////////
  9703. // class VmaDeviceMemoryBlock
  9704. VmaDeviceMemoryBlock::VmaDeviceMemoryBlock(VmaAllocator hAllocator) :
  9705. m_pMetadata(VMA_NULL),
  9706. m_MemoryTypeIndex(UINT32_MAX),
  9707. m_Id(0),
  9708. m_hMemory(VK_NULL_HANDLE),
  9709. m_MapCount(0),
  9710. m_pMappedData(VMA_NULL)
  9711. {
  9712. }
  9713. void VmaDeviceMemoryBlock::Init(
  9714. VmaAllocator hAllocator,
  9715. VmaPool hParentPool,
  9716. uint32_t newMemoryTypeIndex,
  9717. VkDeviceMemory newMemory,
  9718. VkDeviceSize newSize,
  9719. uint32_t id,
  9720. uint32_t algorithm)
  9721. {
  9722. VMA_ASSERT(m_hMemory == VK_NULL_HANDLE);
  9723. m_hParentPool = hParentPool;
  9724. m_MemoryTypeIndex = newMemoryTypeIndex;
  9725. m_Id = id;
  9726. m_hMemory = newMemory;
  9727. switch(algorithm)
  9728. {
  9729. case VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT:
  9730. m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_Linear)(hAllocator);
  9731. break;
  9732. case VMA_POOL_CREATE_BUDDY_ALGORITHM_BIT:
  9733. m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_Buddy)(hAllocator);
  9734. break;
  9735. default:
  9736. VMA_ASSERT(0);
  9737. // Fall-through.
  9738. case 0:
  9739. m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_Generic)(hAllocator);
  9740. }
  9741. m_pMetadata->Init(newSize);
  9742. }
  9743. void VmaDeviceMemoryBlock::Destroy(VmaAllocator allocator)
  9744. {
  9745. // This is the most important assert in the entire library.
  9746. // Hitting it means you have some memory leak - unreleased VmaAllocation objects.
  9747. VMA_ASSERT(m_pMetadata->IsEmpty() && "Some allocations were not freed before destruction of this memory block!");
  9748. VMA_ASSERT(m_hMemory != VK_NULL_HANDLE);
  9749. allocator->FreeVulkanMemory(m_MemoryTypeIndex, m_pMetadata->GetSize(), m_hMemory);
  9750. m_hMemory = VK_NULL_HANDLE;
  9751. vma_delete(allocator, m_pMetadata);
  9752. m_pMetadata = VMA_NULL;
  9753. }
  9754. bool VmaDeviceMemoryBlock::Validate() const
  9755. {
  9756. VMA_VALIDATE((m_hMemory != VK_NULL_HANDLE) &&
  9757. (m_pMetadata->GetSize() != 0));
  9758. return m_pMetadata->Validate();
  9759. }
  9760. VkResult VmaDeviceMemoryBlock::CheckCorruption(VmaAllocator hAllocator)
  9761. {
  9762. void* pData = nullptr;
  9763. VkResult res = Map(hAllocator, 1, &pData);
  9764. if(res != VK_SUCCESS)
  9765. {
  9766. return res;
  9767. }
  9768. res = m_pMetadata->CheckCorruption(pData);
  9769. Unmap(hAllocator, 1);
  9770. return res;
  9771. }
  9772. VkResult VmaDeviceMemoryBlock::Map(VmaAllocator hAllocator, uint32_t count, void** ppData)
  9773. {
  9774. if(count == 0)
  9775. {
  9776. return VK_SUCCESS;
  9777. }
  9778. VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
  9779. if(m_MapCount != 0)
  9780. {
  9781. m_MapCount += count;
  9782. VMA_ASSERT(m_pMappedData != VMA_NULL);
  9783. if(ppData != VMA_NULL)
  9784. {
  9785. *ppData = m_pMappedData;
  9786. }
  9787. return VK_SUCCESS;
  9788. }
  9789. else
  9790. {
  9791. VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)(
  9792. hAllocator->m_hDevice,
  9793. m_hMemory,
  9794. 0, // offset
  9795. VK_WHOLE_SIZE,
  9796. 0, // flags
  9797. &m_pMappedData);
  9798. if(result == VK_SUCCESS)
  9799. {
  9800. if(ppData != VMA_NULL)
  9801. {
  9802. *ppData = m_pMappedData;
  9803. }
  9804. m_MapCount = count;
  9805. }
  9806. return result;
  9807. }
  9808. }
  9809. void VmaDeviceMemoryBlock::Unmap(VmaAllocator hAllocator, uint32_t count)
  9810. {
  9811. if(count == 0)
  9812. {
  9813. return;
  9814. }
  9815. VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
  9816. if(m_MapCount >= count)
  9817. {
  9818. m_MapCount -= count;
  9819. if(m_MapCount == 0)
  9820. {
  9821. m_pMappedData = VMA_NULL;
  9822. (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(hAllocator->m_hDevice, m_hMemory);
  9823. }
  9824. }
  9825. else
  9826. {
  9827. VMA_ASSERT(0 && "VkDeviceMemory block is being unmapped while it was not previously mapped.");
  9828. }
  9829. }
  9830. VkResult VmaDeviceMemoryBlock::WriteMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize)
  9831. {
  9832. VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION);
  9833. VMA_ASSERT(allocOffset >= VMA_DEBUG_MARGIN);
  9834. void* pData;
  9835. VkResult res = Map(hAllocator, 1, &pData);
  9836. if(res != VK_SUCCESS)
  9837. {
  9838. return res;
  9839. }
  9840. VmaWriteMagicValue(pData, allocOffset - VMA_DEBUG_MARGIN);
  9841. VmaWriteMagicValue(pData, allocOffset + allocSize);
  9842. Unmap(hAllocator, 1);
  9843. return VK_SUCCESS;
  9844. }
  9845. VkResult VmaDeviceMemoryBlock::ValidateMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize)
  9846. {
  9847. VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION);
  9848. VMA_ASSERT(allocOffset >= VMA_DEBUG_MARGIN);
  9849. void* pData;
  9850. VkResult res = Map(hAllocator, 1, &pData);
  9851. if(res != VK_SUCCESS)
  9852. {
  9853. return res;
  9854. }
  9855. if(!VmaValidateMagicValue(pData, allocOffset - VMA_DEBUG_MARGIN))
  9856. {
  9857. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE FREED ALLOCATION!");
  9858. }
  9859. else if(!VmaValidateMagicValue(pData, allocOffset + allocSize))
  9860. {
  9861. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER FREED ALLOCATION!");
  9862. }
  9863. Unmap(hAllocator, 1);
  9864. return VK_SUCCESS;
  9865. }
  9866. VkResult VmaDeviceMemoryBlock::BindBufferMemory(
  9867. const VmaAllocator hAllocator,
  9868. const VmaAllocation hAllocation,
  9869. VkDeviceSize allocationLocalOffset,
  9870. VkBuffer hBuffer,
  9871. const void* pNext)
  9872. {
  9873. VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK &&
  9874. hAllocation->GetBlock() == this);
  9875. VMA_ASSERT(allocationLocalOffset < hAllocation->GetSize() &&
  9876. "Invalid allocationLocalOffset. Did you forget that this offset is relative to the beginning of the allocation, not the whole memory block?");
  9877. const VkDeviceSize memoryOffset = hAllocation->GetOffset() + allocationLocalOffset;
  9878. // This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads.
  9879. VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
  9880. return hAllocator->BindVulkanBuffer(m_hMemory, memoryOffset, hBuffer, pNext);
  9881. }
  9882. VkResult VmaDeviceMemoryBlock::BindImageMemory(
  9883. const VmaAllocator hAllocator,
  9884. const VmaAllocation hAllocation,
  9885. VkDeviceSize allocationLocalOffset,
  9886. VkImage hImage,
  9887. const void* pNext)
  9888. {
  9889. VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK &&
  9890. hAllocation->GetBlock() == this);
  9891. VMA_ASSERT(allocationLocalOffset < hAllocation->GetSize() &&
  9892. "Invalid allocationLocalOffset. Did you forget that this offset is relative to the beginning of the allocation, not the whole memory block?");
  9893. const VkDeviceSize memoryOffset = hAllocation->GetOffset() + allocationLocalOffset;
  9894. // This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads.
  9895. VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
  9896. return hAllocator->BindVulkanImage(m_hMemory, memoryOffset, hImage, pNext);
  9897. }
  9898. static void InitStatInfo(VmaStatInfo& outInfo)
  9899. {
  9900. memset(&outInfo, 0, sizeof(outInfo));
  9901. outInfo.allocationSizeMin = UINT64_MAX;
  9902. outInfo.unusedRangeSizeMin = UINT64_MAX;
  9903. }
  9904. // Adds statistics srcInfo into inoutInfo, like: inoutInfo += srcInfo.
  9905. static void VmaAddStatInfo(VmaStatInfo& inoutInfo, const VmaStatInfo& srcInfo)
  9906. {
  9907. inoutInfo.blockCount += srcInfo.blockCount;
  9908. inoutInfo.allocationCount += srcInfo.allocationCount;
  9909. inoutInfo.unusedRangeCount += srcInfo.unusedRangeCount;
  9910. inoutInfo.usedBytes += srcInfo.usedBytes;
  9911. inoutInfo.unusedBytes += srcInfo.unusedBytes;
  9912. inoutInfo.allocationSizeMin = VMA_MIN(inoutInfo.allocationSizeMin, srcInfo.allocationSizeMin);
  9913. inoutInfo.allocationSizeMax = VMA_MAX(inoutInfo.allocationSizeMax, srcInfo.allocationSizeMax);
  9914. inoutInfo.unusedRangeSizeMin = VMA_MIN(inoutInfo.unusedRangeSizeMin, srcInfo.unusedRangeSizeMin);
  9915. inoutInfo.unusedRangeSizeMax = VMA_MAX(inoutInfo.unusedRangeSizeMax, srcInfo.unusedRangeSizeMax);
  9916. }
  9917. static void VmaPostprocessCalcStatInfo(VmaStatInfo& inoutInfo)
  9918. {
  9919. inoutInfo.allocationSizeAvg = (inoutInfo.allocationCount > 0) ?
  9920. VmaRoundDiv<VkDeviceSize>(inoutInfo.usedBytes, inoutInfo.allocationCount) : 0;
  9921. inoutInfo.unusedRangeSizeAvg = (inoutInfo.unusedRangeCount > 0) ?
  9922. VmaRoundDiv<VkDeviceSize>(inoutInfo.unusedBytes, inoutInfo.unusedRangeCount) : 0;
  9923. }
  9924. VmaPool_T::VmaPool_T(
  9925. VmaAllocator hAllocator,
  9926. const VmaPoolCreateInfo& createInfo,
  9927. VkDeviceSize preferredBlockSize) :
  9928. m_BlockVector(
  9929. hAllocator,
  9930. this, // hParentPool
  9931. createInfo.memoryTypeIndex,
  9932. createInfo.blockSize != 0 ? createInfo.blockSize : preferredBlockSize,
  9933. createInfo.minBlockCount,
  9934. createInfo.maxBlockCount,
  9935. (createInfo.flags & VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT) != 0 ? 1 : hAllocator->GetBufferImageGranularity(),
  9936. createInfo.frameInUseCount,
  9937. createInfo.blockSize != 0, // explicitBlockSize
  9938. createInfo.flags & VMA_POOL_CREATE_ALGORITHM_MASK), // algorithm
  9939. m_Id(0),
  9940. m_Name(VMA_NULL)
  9941. {
  9942. }
  9943. VmaPool_T::~VmaPool_T()
  9944. {
  9945. }
  9946. void VmaPool_T::SetName(const char* pName)
  9947. {
  9948. const VkAllocationCallbacks* allocs = m_BlockVector.GetAllocator()->GetAllocationCallbacks();
  9949. VmaFreeString(allocs, m_Name);
  9950. if(pName != VMA_NULL)
  9951. {
  9952. m_Name = VmaCreateStringCopy(allocs, pName);
  9953. }
  9954. else
  9955. {
  9956. m_Name = VMA_NULL;
  9957. }
  9958. }
  9959. #if VMA_STATS_STRING_ENABLED
  9960. #endif // #if VMA_STATS_STRING_ENABLED
  9961. VmaBlockVector::VmaBlockVector(
  9962. VmaAllocator hAllocator,
  9963. VmaPool hParentPool,
  9964. uint32_t memoryTypeIndex,
  9965. VkDeviceSize preferredBlockSize,
  9966. size_t minBlockCount,
  9967. size_t maxBlockCount,
  9968. VkDeviceSize bufferImageGranularity,
  9969. uint32_t frameInUseCount,
  9970. bool explicitBlockSize,
  9971. uint32_t algorithm) :
  9972. m_hAllocator(hAllocator),
  9973. m_hParentPool(hParentPool),
  9974. m_MemoryTypeIndex(memoryTypeIndex),
  9975. m_PreferredBlockSize(preferredBlockSize),
  9976. m_MinBlockCount(minBlockCount),
  9977. m_MaxBlockCount(maxBlockCount),
  9978. m_BufferImageGranularity(bufferImageGranularity),
  9979. m_FrameInUseCount(frameInUseCount),
  9980. m_ExplicitBlockSize(explicitBlockSize),
  9981. m_Algorithm(algorithm),
  9982. m_HasEmptyBlock(false),
  9983. m_Blocks(VmaStlAllocator<VmaDeviceMemoryBlock*>(hAllocator->GetAllocationCallbacks())),
  9984. m_NextBlockId(0)
  9985. {
  9986. }
  9987. VmaBlockVector::~VmaBlockVector()
  9988. {
  9989. for(size_t i = m_Blocks.size(); i--; )
  9990. {
  9991. m_Blocks[i]->Destroy(m_hAllocator);
  9992. vma_delete(m_hAllocator, m_Blocks[i]);
  9993. }
  9994. }
  9995. VkResult VmaBlockVector::CreateMinBlocks()
  9996. {
  9997. for(size_t i = 0; i < m_MinBlockCount; ++i)
  9998. {
  9999. VkResult res = CreateBlock(m_PreferredBlockSize, VMA_NULL);
  10000. if(res != VK_SUCCESS)
  10001. {
  10002. return res;
  10003. }
  10004. }
  10005. return VK_SUCCESS;
  10006. }
  10007. void VmaBlockVector::GetPoolStats(VmaPoolStats* pStats)
  10008. {
  10009. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  10010. const size_t blockCount = m_Blocks.size();
  10011. pStats->size = 0;
  10012. pStats->unusedSize = 0;
  10013. pStats->allocationCount = 0;
  10014. pStats->unusedRangeCount = 0;
  10015. pStats->unusedRangeSizeMax = 0;
  10016. pStats->blockCount = blockCount;
  10017. for(uint32_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
  10018. {
  10019. const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
  10020. VMA_ASSERT(pBlock);
  10021. VMA_HEAVY_ASSERT(pBlock->Validate());
  10022. pBlock->m_pMetadata->AddPoolStats(*pStats);
  10023. }
  10024. }
  10025. bool VmaBlockVector::IsEmpty()
  10026. {
  10027. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  10028. return m_Blocks.empty();
  10029. }
  10030. bool VmaBlockVector::IsCorruptionDetectionEnabled() const
  10031. {
  10032. const uint32_t requiredMemFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
  10033. return (VMA_DEBUG_DETECT_CORRUPTION != 0) &&
  10034. (VMA_DEBUG_MARGIN > 0) &&
  10035. (m_Algorithm == 0 || m_Algorithm == VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) &&
  10036. (m_hAllocator->m_MemProps.memoryTypes[m_MemoryTypeIndex].propertyFlags & requiredMemFlags) == requiredMemFlags;
  10037. }
  10038. static const uint32_t VMA_ALLOCATION_TRY_COUNT = 32;
  10039. VkResult VmaBlockVector::Allocate(
  10040. uint32_t currentFrameIndex,
  10041. VkDeviceSize size,
  10042. VkDeviceSize alignment,
  10043. const VmaAllocationCreateInfo& createInfo,
  10044. VmaSuballocationType suballocType,
  10045. size_t allocationCount,
  10046. VmaAllocation* pAllocations)
  10047. {
  10048. size_t allocIndex;
  10049. VkResult res = VK_SUCCESS;
  10050. if(IsCorruptionDetectionEnabled())
  10051. {
  10052. size = VmaAlignUp<VkDeviceSize>(size, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE));
  10053. alignment = VmaAlignUp<VkDeviceSize>(alignment, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE));
  10054. }
  10055. {
  10056. VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex);
  10057. for(allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  10058. {
  10059. res = AllocatePage(
  10060. currentFrameIndex,
  10061. size,
  10062. alignment,
  10063. createInfo,
  10064. suballocType,
  10065. pAllocations + allocIndex);
  10066. if(res != VK_SUCCESS)
  10067. {
  10068. break;
  10069. }
  10070. }
  10071. }
  10072. if(res != VK_SUCCESS)
  10073. {
  10074. // Free all already created allocations.
  10075. while(allocIndex--)
  10076. {
  10077. Free(pAllocations[allocIndex]);
  10078. }
  10079. memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount);
  10080. }
  10081. return res;
  10082. }
  10083. VkResult VmaBlockVector::AllocatePage(
  10084. uint32_t currentFrameIndex,
  10085. VkDeviceSize size,
  10086. VkDeviceSize alignment,
  10087. const VmaAllocationCreateInfo& createInfo,
  10088. VmaSuballocationType suballocType,
  10089. VmaAllocation* pAllocation)
  10090. {
  10091. const bool isUpperAddress = (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0;
  10092. bool canMakeOtherLost = (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT) != 0;
  10093. const bool mapped = (createInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0;
  10094. const bool isUserDataString = (createInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0;
  10095. const bool withinBudget = (createInfo.flags & VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT) != 0;
  10096. VkDeviceSize freeMemory;
  10097. {
  10098. const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex);
  10099. VmaBudget heapBudget = {};
  10100. m_hAllocator->GetBudget(&heapBudget, heapIndex, 1);
  10101. freeMemory = (heapBudget.usage < heapBudget.budget) ? (heapBudget.budget - heapBudget.usage) : 0;
  10102. }
  10103. const bool canFallbackToDedicated = !IsCustomPool();
  10104. const bool canCreateNewBlock =
  10105. ((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0) &&
  10106. (m_Blocks.size() < m_MaxBlockCount) &&
  10107. (freeMemory >= size || !canFallbackToDedicated);
  10108. uint32_t strategy = createInfo.flags & VMA_ALLOCATION_CREATE_STRATEGY_MASK;
  10109. // If linearAlgorithm is used, canMakeOtherLost is available only when used as ring buffer.
  10110. // Which in turn is available only when maxBlockCount = 1.
  10111. if(m_Algorithm == VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT && m_MaxBlockCount > 1)
  10112. {
  10113. canMakeOtherLost = false;
  10114. }
  10115. // Upper address can only be used with linear allocator and within single memory block.
  10116. if(isUpperAddress &&
  10117. (m_Algorithm != VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT || m_MaxBlockCount > 1))
  10118. {
  10119. return VK_ERROR_FEATURE_NOT_PRESENT;
  10120. }
  10121. // Validate strategy.
  10122. switch(strategy)
  10123. {
  10124. case 0:
  10125. strategy = VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT;
  10126. break;
  10127. case VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT:
  10128. case VMA_ALLOCATION_CREATE_STRATEGY_WORST_FIT_BIT:
  10129. case VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT:
  10130. break;
  10131. default:
  10132. return VK_ERROR_FEATURE_NOT_PRESENT;
  10133. }
  10134. // Early reject: requested allocation size is larger that maximum block size for this block vector.
  10135. if(size + 2 * VMA_DEBUG_MARGIN > m_PreferredBlockSize)
  10136. {
  10137. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10138. }
  10139. /*
  10140. Under certain condition, this whole section can be skipped for optimization, so
  10141. we move on directly to trying to allocate with canMakeOtherLost. That's the case
  10142. e.g. for custom pools with linear algorithm.
  10143. */
  10144. if(!canMakeOtherLost || canCreateNewBlock)
  10145. {
  10146. // 1. Search existing allocations. Try to allocate without making other allocations lost.
  10147. VmaAllocationCreateFlags allocFlagsCopy = createInfo.flags;
  10148. allocFlagsCopy &= ~VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT;
  10149. if(m_Algorithm == VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT)
  10150. {
  10151. // Use only last block.
  10152. if(!m_Blocks.empty())
  10153. {
  10154. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks.back();
  10155. VMA_ASSERT(pCurrBlock);
  10156. VkResult res = AllocateFromBlock(
  10157. pCurrBlock,
  10158. currentFrameIndex,
  10159. size,
  10160. alignment,
  10161. allocFlagsCopy,
  10162. createInfo.pUserData,
  10163. suballocType,
  10164. strategy,
  10165. pAllocation);
  10166. if(res == VK_SUCCESS)
  10167. {
  10168. VMA_DEBUG_LOG(" Returned from last block #%u", pCurrBlock->GetId());
  10169. return VK_SUCCESS;
  10170. }
  10171. }
  10172. }
  10173. else
  10174. {
  10175. if(strategy == VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT)
  10176. {
  10177. // Forward order in m_Blocks - prefer blocks with smallest amount of free space.
  10178. for(size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex )
  10179. {
  10180. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
  10181. VMA_ASSERT(pCurrBlock);
  10182. VkResult res = AllocateFromBlock(
  10183. pCurrBlock,
  10184. currentFrameIndex,
  10185. size,
  10186. alignment,
  10187. allocFlagsCopy,
  10188. createInfo.pUserData,
  10189. suballocType,
  10190. strategy,
  10191. pAllocation);
  10192. if(res == VK_SUCCESS)
  10193. {
  10194. VMA_DEBUG_LOG(" Returned from existing block #%u", pCurrBlock->GetId());
  10195. return VK_SUCCESS;
  10196. }
  10197. }
  10198. }
  10199. else // WORST_FIT, FIRST_FIT
  10200. {
  10201. // Backward order in m_Blocks - prefer blocks with largest amount of free space.
  10202. for(size_t blockIndex = m_Blocks.size(); blockIndex--; )
  10203. {
  10204. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
  10205. VMA_ASSERT(pCurrBlock);
  10206. VkResult res = AllocateFromBlock(
  10207. pCurrBlock,
  10208. currentFrameIndex,
  10209. size,
  10210. alignment,
  10211. allocFlagsCopy,
  10212. createInfo.pUserData,
  10213. suballocType,
  10214. strategy,
  10215. pAllocation);
  10216. if(res == VK_SUCCESS)
  10217. {
  10218. VMA_DEBUG_LOG(" Returned from existing block #%u", pCurrBlock->GetId());
  10219. return VK_SUCCESS;
  10220. }
  10221. }
  10222. }
  10223. }
  10224. // 2. Try to create new block.
  10225. if(canCreateNewBlock)
  10226. {
  10227. // Calculate optimal size for new block.
  10228. VkDeviceSize newBlockSize = m_PreferredBlockSize;
  10229. uint32_t newBlockSizeShift = 0;
  10230. const uint32_t NEW_BLOCK_SIZE_SHIFT_MAX = 3;
  10231. if(!m_ExplicitBlockSize)
  10232. {
  10233. // Allocate 1/8, 1/4, 1/2 as first blocks.
  10234. const VkDeviceSize maxExistingBlockSize = CalcMaxBlockSize();
  10235. for(uint32_t i = 0; i < NEW_BLOCK_SIZE_SHIFT_MAX; ++i)
  10236. {
  10237. const VkDeviceSize smallerNewBlockSize = newBlockSize / 2;
  10238. if(smallerNewBlockSize > maxExistingBlockSize && smallerNewBlockSize >= size * 2)
  10239. {
  10240. newBlockSize = smallerNewBlockSize;
  10241. ++newBlockSizeShift;
  10242. }
  10243. else
  10244. {
  10245. break;
  10246. }
  10247. }
  10248. }
  10249. size_t newBlockIndex = 0;
  10250. VkResult res = (newBlockSize <= freeMemory || !canFallbackToDedicated) ?
  10251. CreateBlock(newBlockSize, &newBlockIndex) : VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10252. // Allocation of this size failed? Try 1/2, 1/4, 1/8 of m_PreferredBlockSize.
  10253. if(!m_ExplicitBlockSize)
  10254. {
  10255. while(res < 0 && newBlockSizeShift < NEW_BLOCK_SIZE_SHIFT_MAX)
  10256. {
  10257. const VkDeviceSize smallerNewBlockSize = newBlockSize / 2;
  10258. if(smallerNewBlockSize >= size)
  10259. {
  10260. newBlockSize = smallerNewBlockSize;
  10261. ++newBlockSizeShift;
  10262. res = (newBlockSize <= freeMemory || !canFallbackToDedicated) ?
  10263. CreateBlock(newBlockSize, &newBlockIndex) : VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10264. }
  10265. else
  10266. {
  10267. break;
  10268. }
  10269. }
  10270. }
  10271. if(res == VK_SUCCESS)
  10272. {
  10273. VmaDeviceMemoryBlock* const pBlock = m_Blocks[newBlockIndex];
  10274. VMA_ASSERT(pBlock->m_pMetadata->GetSize() >= size);
  10275. res = AllocateFromBlock(
  10276. pBlock,
  10277. currentFrameIndex,
  10278. size,
  10279. alignment,
  10280. allocFlagsCopy,
  10281. createInfo.pUserData,
  10282. suballocType,
  10283. strategy,
  10284. pAllocation);
  10285. if(res == VK_SUCCESS)
  10286. {
  10287. VMA_DEBUG_LOG(" Created new block #%u Size=%llu", pBlock->GetId(), newBlockSize);
  10288. return VK_SUCCESS;
  10289. }
  10290. else
  10291. {
  10292. // Allocation from new block failed, possibly due to VMA_DEBUG_MARGIN or alignment.
  10293. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10294. }
  10295. }
  10296. }
  10297. }
  10298. // 3. Try to allocate from existing blocks with making other allocations lost.
  10299. if(canMakeOtherLost)
  10300. {
  10301. uint32_t tryIndex = 0;
  10302. for(; tryIndex < VMA_ALLOCATION_TRY_COUNT; ++tryIndex)
  10303. {
  10304. VmaDeviceMemoryBlock* pBestRequestBlock = VMA_NULL;
  10305. VmaAllocationRequest bestRequest = {};
  10306. VkDeviceSize bestRequestCost = VK_WHOLE_SIZE;
  10307. // 1. Search existing allocations.
  10308. if(strategy == VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT)
  10309. {
  10310. // Forward order in m_Blocks - prefer blocks with smallest amount of free space.
  10311. for(size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex )
  10312. {
  10313. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
  10314. VMA_ASSERT(pCurrBlock);
  10315. VmaAllocationRequest currRequest = {};
  10316. if(pCurrBlock->m_pMetadata->CreateAllocationRequest(
  10317. currentFrameIndex,
  10318. m_FrameInUseCount,
  10319. m_BufferImageGranularity,
  10320. size,
  10321. alignment,
  10322. (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0,
  10323. suballocType,
  10324. canMakeOtherLost,
  10325. strategy,
  10326. &currRequest))
  10327. {
  10328. const VkDeviceSize currRequestCost = currRequest.CalcCost();
  10329. if(pBestRequestBlock == VMA_NULL ||
  10330. currRequestCost < bestRequestCost)
  10331. {
  10332. pBestRequestBlock = pCurrBlock;
  10333. bestRequest = currRequest;
  10334. bestRequestCost = currRequestCost;
  10335. if(bestRequestCost == 0)
  10336. {
  10337. break;
  10338. }
  10339. }
  10340. }
  10341. }
  10342. }
  10343. else // WORST_FIT, FIRST_FIT
  10344. {
  10345. // Backward order in m_Blocks - prefer blocks with largest amount of free space.
  10346. for(size_t blockIndex = m_Blocks.size(); blockIndex--; )
  10347. {
  10348. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
  10349. VMA_ASSERT(pCurrBlock);
  10350. VmaAllocationRequest currRequest = {};
  10351. if(pCurrBlock->m_pMetadata->CreateAllocationRequest(
  10352. currentFrameIndex,
  10353. m_FrameInUseCount,
  10354. m_BufferImageGranularity,
  10355. size,
  10356. alignment,
  10357. (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0,
  10358. suballocType,
  10359. canMakeOtherLost,
  10360. strategy,
  10361. &currRequest))
  10362. {
  10363. const VkDeviceSize currRequestCost = currRequest.CalcCost();
  10364. if(pBestRequestBlock == VMA_NULL ||
  10365. currRequestCost < bestRequestCost ||
  10366. strategy == VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT)
  10367. {
  10368. pBestRequestBlock = pCurrBlock;
  10369. bestRequest = currRequest;
  10370. bestRequestCost = currRequestCost;
  10371. if(bestRequestCost == 0 ||
  10372. strategy == VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT)
  10373. {
  10374. break;
  10375. }
  10376. }
  10377. }
  10378. }
  10379. }
  10380. if(pBestRequestBlock != VMA_NULL)
  10381. {
  10382. if(mapped)
  10383. {
  10384. VkResult res = pBestRequestBlock->Map(m_hAllocator, 1, VMA_NULL);
  10385. if(res != VK_SUCCESS)
  10386. {
  10387. return res;
  10388. }
  10389. }
  10390. if(pBestRequestBlock->m_pMetadata->MakeRequestedAllocationsLost(
  10391. currentFrameIndex,
  10392. m_FrameInUseCount,
  10393. &bestRequest))
  10394. {
  10395. // Allocate from this pBlock.
  10396. *pAllocation = m_hAllocator->m_AllocationObjectAllocator.Allocate();
  10397. (*pAllocation)->Ctor(currentFrameIndex, isUserDataString);
  10398. pBestRequestBlock->m_pMetadata->Alloc(bestRequest, suballocType, size, *pAllocation);
  10399. UpdateHasEmptyBlock();
  10400. (*pAllocation)->InitBlockAllocation(
  10401. pBestRequestBlock,
  10402. bestRequest.offset,
  10403. alignment,
  10404. size,
  10405. m_MemoryTypeIndex,
  10406. suballocType,
  10407. mapped,
  10408. (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0);
  10409. VMA_HEAVY_ASSERT(pBestRequestBlock->Validate());
  10410. VMA_DEBUG_LOG(" Returned from existing block");
  10411. (*pAllocation)->SetUserData(m_hAllocator, createInfo.pUserData);
  10412. m_hAllocator->m_Budget.AddAllocation(m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex), size);
  10413. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
  10414. {
  10415. m_hAllocator->FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED);
  10416. }
  10417. if(IsCorruptionDetectionEnabled())
  10418. {
  10419. VkResult res = pBestRequestBlock->WriteMagicValueAroundAllocation(m_hAllocator, bestRequest.offset, size);
  10420. VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to write magic value.");
  10421. }
  10422. return VK_SUCCESS;
  10423. }
  10424. // else: Some allocations must have been touched while we are here. Next try.
  10425. }
  10426. else
  10427. {
  10428. // Could not find place in any of the blocks - break outer loop.
  10429. break;
  10430. }
  10431. }
  10432. /* Maximum number of tries exceeded - a very unlike event when many other
  10433. threads are simultaneously touching allocations making it impossible to make
  10434. lost at the same time as we try to allocate. */
  10435. if(tryIndex == VMA_ALLOCATION_TRY_COUNT)
  10436. {
  10437. return VK_ERROR_TOO_MANY_OBJECTS;
  10438. }
  10439. }
  10440. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10441. }
  10442. void VmaBlockVector::Free(
  10443. const VmaAllocation hAllocation)
  10444. {
  10445. VmaDeviceMemoryBlock* pBlockToDelete = VMA_NULL;
  10446. bool budgetExceeded = false;
  10447. {
  10448. const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex);
  10449. VmaBudget heapBudget = {};
  10450. m_hAllocator->GetBudget(&heapBudget, heapIndex, 1);
  10451. budgetExceeded = heapBudget.usage >= heapBudget.budget;
  10452. }
  10453. // Scope for lock.
  10454. {
  10455. VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex);
  10456. VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock();
  10457. if(IsCorruptionDetectionEnabled())
  10458. {
  10459. VkResult res = pBlock->ValidateMagicValueAroundAllocation(m_hAllocator, hAllocation->GetOffset(), hAllocation->GetSize());
  10460. VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to validate magic value.");
  10461. }
  10462. if(hAllocation->IsPersistentMap())
  10463. {
  10464. pBlock->Unmap(m_hAllocator, 1);
  10465. }
  10466. pBlock->m_pMetadata->Free(hAllocation);
  10467. VMA_HEAVY_ASSERT(pBlock->Validate());
  10468. VMA_DEBUG_LOG(" Freed from MemoryTypeIndex=%u", m_MemoryTypeIndex);
  10469. const bool canDeleteBlock = m_Blocks.size() > m_MinBlockCount;
  10470. // pBlock became empty after this deallocation.
  10471. if(pBlock->m_pMetadata->IsEmpty())
  10472. {
  10473. // Already has empty block. We don't want to have two, so delete this one.
  10474. if((m_HasEmptyBlock || budgetExceeded) && canDeleteBlock)
  10475. {
  10476. pBlockToDelete = pBlock;
  10477. Remove(pBlock);
  10478. }
  10479. // else: We now have an empty block - leave it.
  10480. }
  10481. // pBlock didn't become empty, but we have another empty block - find and free that one.
  10482. // (This is optional, heuristics.)
  10483. else if(m_HasEmptyBlock && canDeleteBlock)
  10484. {
  10485. VmaDeviceMemoryBlock* pLastBlock = m_Blocks.back();
  10486. if(pLastBlock->m_pMetadata->IsEmpty())
  10487. {
  10488. pBlockToDelete = pLastBlock;
  10489. m_Blocks.pop_back();
  10490. }
  10491. }
  10492. UpdateHasEmptyBlock();
  10493. IncrementallySortBlocks();
  10494. }
  10495. // Destruction of a free block. Deferred until this point, outside of mutex
  10496. // lock, for performance reason.
  10497. if(pBlockToDelete != VMA_NULL)
  10498. {
  10499. VMA_DEBUG_LOG(" Deleted empty block");
  10500. pBlockToDelete->Destroy(m_hAllocator);
  10501. vma_delete(m_hAllocator, pBlockToDelete);
  10502. }
  10503. }
  10504. VkDeviceSize VmaBlockVector::CalcMaxBlockSize() const
  10505. {
  10506. VkDeviceSize result = 0;
  10507. for(size_t i = m_Blocks.size(); i--; )
  10508. {
  10509. result = VMA_MAX(result, m_Blocks[i]->m_pMetadata->GetSize());
  10510. if(result >= m_PreferredBlockSize)
  10511. {
  10512. break;
  10513. }
  10514. }
  10515. return result;
  10516. }
  10517. void VmaBlockVector::Remove(VmaDeviceMemoryBlock* pBlock)
  10518. {
  10519. for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  10520. {
  10521. if(m_Blocks[blockIndex] == pBlock)
  10522. {
  10523. VmaVectorRemove(m_Blocks, blockIndex);
  10524. return;
  10525. }
  10526. }
  10527. VMA_ASSERT(0);
  10528. }
  10529. void VmaBlockVector::IncrementallySortBlocks()
  10530. {
  10531. if(m_Algorithm != VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT)
  10532. {
  10533. // Bubble sort only until first swap.
  10534. for(size_t i = 1; i < m_Blocks.size(); ++i)
  10535. {
  10536. if(m_Blocks[i - 1]->m_pMetadata->GetSumFreeSize() > m_Blocks[i]->m_pMetadata->GetSumFreeSize())
  10537. {
  10538. VMA_SWAP(m_Blocks[i - 1], m_Blocks[i]);
  10539. return;
  10540. }
  10541. }
  10542. }
  10543. }
  10544. VkResult VmaBlockVector::AllocateFromBlock(
  10545. VmaDeviceMemoryBlock* pBlock,
  10546. uint32_t currentFrameIndex,
  10547. VkDeviceSize size,
  10548. VkDeviceSize alignment,
  10549. VmaAllocationCreateFlags allocFlags,
  10550. void* pUserData,
  10551. VmaSuballocationType suballocType,
  10552. uint32_t strategy,
  10553. VmaAllocation* pAllocation)
  10554. {
  10555. VMA_ASSERT((allocFlags & VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT) == 0);
  10556. const bool isUpperAddress = (allocFlags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0;
  10557. const bool mapped = (allocFlags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0;
  10558. const bool isUserDataString = (allocFlags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0;
  10559. VmaAllocationRequest currRequest = {};
  10560. if(pBlock->m_pMetadata->CreateAllocationRequest(
  10561. currentFrameIndex,
  10562. m_FrameInUseCount,
  10563. m_BufferImageGranularity,
  10564. size,
  10565. alignment,
  10566. isUpperAddress,
  10567. suballocType,
  10568. false, // canMakeOtherLost
  10569. strategy,
  10570. &currRequest))
  10571. {
  10572. // Allocate from pCurrBlock.
  10573. VMA_ASSERT(currRequest.itemsToMakeLostCount == 0);
  10574. if(mapped)
  10575. {
  10576. VkResult res = pBlock->Map(m_hAllocator, 1, VMA_NULL);
  10577. if(res != VK_SUCCESS)
  10578. {
  10579. return res;
  10580. }
  10581. }
  10582. *pAllocation = m_hAllocator->m_AllocationObjectAllocator.Allocate();
  10583. (*pAllocation)->Ctor(currentFrameIndex, isUserDataString);
  10584. pBlock->m_pMetadata->Alloc(currRequest, suballocType, size, *pAllocation);
  10585. UpdateHasEmptyBlock();
  10586. (*pAllocation)->InitBlockAllocation(
  10587. pBlock,
  10588. currRequest.offset,
  10589. alignment,
  10590. size,
  10591. m_MemoryTypeIndex,
  10592. suballocType,
  10593. mapped,
  10594. (allocFlags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0);
  10595. VMA_HEAVY_ASSERT(pBlock->Validate());
  10596. (*pAllocation)->SetUserData(m_hAllocator, pUserData);
  10597. m_hAllocator->m_Budget.AddAllocation(m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex), size);
  10598. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
  10599. {
  10600. m_hAllocator->FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED);
  10601. }
  10602. if(IsCorruptionDetectionEnabled())
  10603. {
  10604. VkResult res = pBlock->WriteMagicValueAroundAllocation(m_hAllocator, currRequest.offset, size);
  10605. VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to write magic value.");
  10606. }
  10607. return VK_SUCCESS;
  10608. }
  10609. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10610. }
  10611. VkResult VmaBlockVector::CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex)
  10612. {
  10613. VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
  10614. allocInfo.memoryTypeIndex = m_MemoryTypeIndex;
  10615. allocInfo.allocationSize = blockSize;
  10616. VkDeviceMemory mem = VK_NULL_HANDLE;
  10617. VkResult res = m_hAllocator->AllocateVulkanMemory(&allocInfo, &mem);
  10618. if(res < 0)
  10619. {
  10620. return res;
  10621. }
  10622. // New VkDeviceMemory successfully created.
  10623. // Create new Allocation for it.
  10624. VmaDeviceMemoryBlock* const pBlock = vma_new(m_hAllocator, VmaDeviceMemoryBlock)(m_hAllocator);
  10625. pBlock->Init(
  10626. m_hAllocator,
  10627. m_hParentPool,
  10628. m_MemoryTypeIndex,
  10629. mem,
  10630. allocInfo.allocationSize,
  10631. m_NextBlockId++,
  10632. m_Algorithm);
  10633. m_Blocks.push_back(pBlock);
  10634. if(pNewBlockIndex != VMA_NULL)
  10635. {
  10636. *pNewBlockIndex = m_Blocks.size() - 1;
  10637. }
  10638. return VK_SUCCESS;
  10639. }
  10640. void VmaBlockVector::ApplyDefragmentationMovesCpu(
  10641. class VmaBlockVectorDefragmentationContext* pDefragCtx,
  10642. const VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves)
  10643. {
  10644. const size_t blockCount = m_Blocks.size();
  10645. const bool isNonCoherent = m_hAllocator->IsMemoryTypeNonCoherent(m_MemoryTypeIndex);
  10646. enum BLOCK_FLAG
  10647. {
  10648. BLOCK_FLAG_USED = 0x00000001,
  10649. BLOCK_FLAG_MAPPED_FOR_DEFRAGMENTATION = 0x00000002,
  10650. };
  10651. struct BlockInfo
  10652. {
  10653. uint32_t flags;
  10654. void* pMappedData;
  10655. };
  10656. VmaVector< BlockInfo, VmaStlAllocator<BlockInfo> >
  10657. blockInfo(blockCount, BlockInfo(), VmaStlAllocator<BlockInfo>(m_hAllocator->GetAllocationCallbacks()));
  10658. memset(blockInfo.data(), 0, blockCount * sizeof(BlockInfo));
  10659. // Go over all moves. Mark blocks that are used with BLOCK_FLAG_USED.
  10660. const size_t moveCount = moves.size();
  10661. for(size_t moveIndex = 0; moveIndex < moveCount; ++moveIndex)
  10662. {
  10663. const VmaDefragmentationMove& move = moves[moveIndex];
  10664. blockInfo[move.srcBlockIndex].flags |= BLOCK_FLAG_USED;
  10665. blockInfo[move.dstBlockIndex].flags |= BLOCK_FLAG_USED;
  10666. }
  10667. VMA_ASSERT(pDefragCtx->res == VK_SUCCESS);
  10668. // Go over all blocks. Get mapped pointer or map if necessary.
  10669. for(size_t blockIndex = 0; pDefragCtx->res == VK_SUCCESS && blockIndex < blockCount; ++blockIndex)
  10670. {
  10671. BlockInfo& currBlockInfo = blockInfo[blockIndex];
  10672. VmaDeviceMemoryBlock* pBlock = m_Blocks[blockIndex];
  10673. if((currBlockInfo.flags & BLOCK_FLAG_USED) != 0)
  10674. {
  10675. currBlockInfo.pMappedData = pBlock->GetMappedData();
  10676. // It is not originally mapped - map it.
  10677. if(currBlockInfo.pMappedData == VMA_NULL)
  10678. {
  10679. pDefragCtx->res = pBlock->Map(m_hAllocator, 1, &currBlockInfo.pMappedData);
  10680. if(pDefragCtx->res == VK_SUCCESS)
  10681. {
  10682. currBlockInfo.flags |= BLOCK_FLAG_MAPPED_FOR_DEFRAGMENTATION;
  10683. }
  10684. }
  10685. }
  10686. }
  10687. // Go over all moves. Do actual data transfer.
  10688. if(pDefragCtx->res == VK_SUCCESS)
  10689. {
  10690. const VkDeviceSize nonCoherentAtomSize = m_hAllocator->m_PhysicalDeviceProperties.limits.nonCoherentAtomSize;
  10691. VkMappedMemoryRange memRange = { VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE };
  10692. for(size_t moveIndex = 0; moveIndex < moveCount; ++moveIndex)
  10693. {
  10694. const VmaDefragmentationMove& move = moves[moveIndex];
  10695. const BlockInfo& srcBlockInfo = blockInfo[move.srcBlockIndex];
  10696. const BlockInfo& dstBlockInfo = blockInfo[move.dstBlockIndex];
  10697. VMA_ASSERT(srcBlockInfo.pMappedData && dstBlockInfo.pMappedData);
  10698. // Invalidate source.
  10699. if(isNonCoherent)
  10700. {
  10701. VmaDeviceMemoryBlock* const pSrcBlock = m_Blocks[move.srcBlockIndex];
  10702. memRange.memory = pSrcBlock->GetDeviceMemory();
  10703. memRange.offset = VmaAlignDown(move.srcOffset, nonCoherentAtomSize);
  10704. memRange.size = VMA_MIN(
  10705. VmaAlignUp(move.size + (move.srcOffset - memRange.offset), nonCoherentAtomSize),
  10706. pSrcBlock->m_pMetadata->GetSize() - memRange.offset);
  10707. (*m_hAllocator->GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hAllocator->m_hDevice, 1, &memRange);
  10708. }
  10709. // THE PLACE WHERE ACTUAL DATA COPY HAPPENS.
  10710. memmove(
  10711. reinterpret_cast<char*>(dstBlockInfo.pMappedData) + move.dstOffset,
  10712. reinterpret_cast<char*>(srcBlockInfo.pMappedData) + move.srcOffset,
  10713. static_cast<size_t>(move.size));
  10714. if(IsCorruptionDetectionEnabled())
  10715. {
  10716. VmaWriteMagicValue(dstBlockInfo.pMappedData, move.dstOffset - VMA_DEBUG_MARGIN);
  10717. VmaWriteMagicValue(dstBlockInfo.pMappedData, move.dstOffset + move.size);
  10718. }
  10719. // Flush destination.
  10720. if(isNonCoherent)
  10721. {
  10722. VmaDeviceMemoryBlock* const pDstBlock = m_Blocks[move.dstBlockIndex];
  10723. memRange.memory = pDstBlock->GetDeviceMemory();
  10724. memRange.offset = VmaAlignDown(move.dstOffset, nonCoherentAtomSize);
  10725. memRange.size = VMA_MIN(
  10726. VmaAlignUp(move.size + (move.dstOffset - memRange.offset), nonCoherentAtomSize),
  10727. pDstBlock->m_pMetadata->GetSize() - memRange.offset);
  10728. (*m_hAllocator->GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hAllocator->m_hDevice, 1, &memRange);
  10729. }
  10730. }
  10731. }
  10732. // Go over all blocks in reverse order. Unmap those that were mapped just for defragmentation.
  10733. // Regardless of pCtx->res == VK_SUCCESS.
  10734. for(size_t blockIndex = blockCount; blockIndex--; )
  10735. {
  10736. const BlockInfo& currBlockInfo = blockInfo[blockIndex];
  10737. if((currBlockInfo.flags & BLOCK_FLAG_MAPPED_FOR_DEFRAGMENTATION) != 0)
  10738. {
  10739. VmaDeviceMemoryBlock* pBlock = m_Blocks[blockIndex];
  10740. pBlock->Unmap(m_hAllocator, 1);
  10741. }
  10742. }
  10743. }
  10744. void VmaBlockVector::ApplyDefragmentationMovesGpu(
  10745. class VmaBlockVectorDefragmentationContext* pDefragCtx,
  10746. const VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  10747. VkCommandBuffer commandBuffer)
  10748. {
  10749. const size_t blockCount = m_Blocks.size();
  10750. pDefragCtx->blockContexts.resize(blockCount);
  10751. memset(pDefragCtx->blockContexts.data(), 0, blockCount * sizeof(VmaBlockDefragmentationContext));
  10752. // Go over all moves. Mark blocks that are used with BLOCK_FLAG_USED.
  10753. const size_t moveCount = moves.size();
  10754. for(size_t moveIndex = 0; moveIndex < moveCount; ++moveIndex)
  10755. {
  10756. const VmaDefragmentationMove& move = moves[moveIndex];
  10757. pDefragCtx->blockContexts[move.srcBlockIndex].flags |= VmaBlockDefragmentationContext::BLOCK_FLAG_USED;
  10758. pDefragCtx->blockContexts[move.dstBlockIndex].flags |= VmaBlockDefragmentationContext::BLOCK_FLAG_USED;
  10759. }
  10760. VMA_ASSERT(pDefragCtx->res == VK_SUCCESS);
  10761. // Go over all blocks. Create and bind buffer for whole block if necessary.
  10762. {
  10763. VkBufferCreateInfo bufCreateInfo;
  10764. VmaFillGpuDefragmentationBufferCreateInfo(bufCreateInfo);
  10765. for(size_t blockIndex = 0; pDefragCtx->res == VK_SUCCESS && blockIndex < blockCount; ++blockIndex)
  10766. {
  10767. VmaBlockDefragmentationContext& currBlockCtx = pDefragCtx->blockContexts[blockIndex];
  10768. VmaDeviceMemoryBlock* pBlock = m_Blocks[blockIndex];
  10769. if((currBlockCtx.flags & VmaBlockDefragmentationContext::BLOCK_FLAG_USED) != 0)
  10770. {
  10771. bufCreateInfo.size = pBlock->m_pMetadata->GetSize();
  10772. pDefragCtx->res = (*m_hAllocator->GetVulkanFunctions().vkCreateBuffer)(
  10773. m_hAllocator->m_hDevice, &bufCreateInfo, m_hAllocator->GetAllocationCallbacks(), &currBlockCtx.hBuffer);
  10774. if(pDefragCtx->res == VK_SUCCESS)
  10775. {
  10776. pDefragCtx->res = (*m_hAllocator->GetVulkanFunctions().vkBindBufferMemory)(
  10777. m_hAllocator->m_hDevice, currBlockCtx.hBuffer, pBlock->GetDeviceMemory(), 0);
  10778. }
  10779. }
  10780. }
  10781. }
  10782. // Go over all moves. Post data transfer commands to command buffer.
  10783. if(pDefragCtx->res == VK_SUCCESS)
  10784. {
  10785. for(size_t moveIndex = 0; moveIndex < moveCount; ++moveIndex)
  10786. {
  10787. const VmaDefragmentationMove& move = moves[moveIndex];
  10788. const VmaBlockDefragmentationContext& srcBlockCtx = pDefragCtx->blockContexts[move.srcBlockIndex];
  10789. const VmaBlockDefragmentationContext& dstBlockCtx = pDefragCtx->blockContexts[move.dstBlockIndex];
  10790. VMA_ASSERT(srcBlockCtx.hBuffer && dstBlockCtx.hBuffer);
  10791. VkBufferCopy region = {
  10792. move.srcOffset,
  10793. move.dstOffset,
  10794. move.size };
  10795. (*m_hAllocator->GetVulkanFunctions().vkCmdCopyBuffer)(
  10796. commandBuffer, srcBlockCtx.hBuffer, dstBlockCtx.hBuffer, 1, &region);
  10797. }
  10798. }
  10799. // Save buffers to defrag context for later destruction.
  10800. if(pDefragCtx->res == VK_SUCCESS && moveCount > 0)
  10801. {
  10802. pDefragCtx->res = VK_NOT_READY;
  10803. }
  10804. }
  10805. void VmaBlockVector::FreeEmptyBlocks(VmaDefragmentationStats* pDefragmentationStats)
  10806. {
  10807. for(size_t blockIndex = m_Blocks.size(); blockIndex--; )
  10808. {
  10809. VmaDeviceMemoryBlock* pBlock = m_Blocks[blockIndex];
  10810. if(pBlock->m_pMetadata->IsEmpty())
  10811. {
  10812. if(m_Blocks.size() > m_MinBlockCount)
  10813. {
  10814. if(pDefragmentationStats != VMA_NULL)
  10815. {
  10816. ++pDefragmentationStats->deviceMemoryBlocksFreed;
  10817. pDefragmentationStats->bytesFreed += pBlock->m_pMetadata->GetSize();
  10818. }
  10819. VmaVectorRemove(m_Blocks, blockIndex);
  10820. pBlock->Destroy(m_hAllocator);
  10821. vma_delete(m_hAllocator, pBlock);
  10822. }
  10823. else
  10824. {
  10825. break;
  10826. }
  10827. }
  10828. }
  10829. UpdateHasEmptyBlock();
  10830. }
  10831. void VmaBlockVector::UpdateHasEmptyBlock()
  10832. {
  10833. m_HasEmptyBlock = false;
  10834. for(size_t index = 0, count = m_Blocks.size(); index < count; ++index)
  10835. {
  10836. VmaDeviceMemoryBlock* const pBlock = m_Blocks[index];
  10837. if(pBlock->m_pMetadata->IsEmpty())
  10838. {
  10839. m_HasEmptyBlock = true;
  10840. break;
  10841. }
  10842. }
  10843. }
  10844. #if VMA_STATS_STRING_ENABLED
  10845. void VmaBlockVector::PrintDetailedMap(class VmaJsonWriter& json)
  10846. {
  10847. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  10848. json.BeginObject();
  10849. if(IsCustomPool())
  10850. {
  10851. const char* poolName = m_hParentPool->GetName();
  10852. if(poolName != VMA_NULL && poolName[0] != '\0')
  10853. {
  10854. json.WriteString("Name");
  10855. json.WriteString(poolName);
  10856. }
  10857. json.WriteString("MemoryTypeIndex");
  10858. json.WriteNumber(m_MemoryTypeIndex);
  10859. json.WriteString("BlockSize");
  10860. json.WriteNumber(m_PreferredBlockSize);
  10861. json.WriteString("BlockCount");
  10862. json.BeginObject(true);
  10863. if(m_MinBlockCount > 0)
  10864. {
  10865. json.WriteString("Min");
  10866. json.WriteNumber((uint64_t)m_MinBlockCount);
  10867. }
  10868. if(m_MaxBlockCount < SIZE_MAX)
  10869. {
  10870. json.WriteString("Max");
  10871. json.WriteNumber((uint64_t)m_MaxBlockCount);
  10872. }
  10873. json.WriteString("Cur");
  10874. json.WriteNumber((uint64_t)m_Blocks.size());
  10875. json.EndObject();
  10876. if(m_FrameInUseCount > 0)
  10877. {
  10878. json.WriteString("FrameInUseCount");
  10879. json.WriteNumber(m_FrameInUseCount);
  10880. }
  10881. if(m_Algorithm != 0)
  10882. {
  10883. json.WriteString("Algorithm");
  10884. json.WriteString(VmaAlgorithmToStr(m_Algorithm));
  10885. }
  10886. }
  10887. else
  10888. {
  10889. json.WriteString("PreferredBlockSize");
  10890. json.WriteNumber(m_PreferredBlockSize);
  10891. }
  10892. json.WriteString("Blocks");
  10893. json.BeginObject();
  10894. for(size_t i = 0; i < m_Blocks.size(); ++i)
  10895. {
  10896. json.BeginString();
  10897. json.ContinueString(m_Blocks[i]->GetId());
  10898. json.EndString();
  10899. m_Blocks[i]->m_pMetadata->PrintDetailedMap(json);
  10900. }
  10901. json.EndObject();
  10902. json.EndObject();
  10903. }
  10904. #endif // #if VMA_STATS_STRING_ENABLED
  10905. void VmaBlockVector::Defragment(
  10906. class VmaBlockVectorDefragmentationContext* pCtx,
  10907. VmaDefragmentationStats* pStats,
  10908. VkDeviceSize& maxCpuBytesToMove, uint32_t& maxCpuAllocationsToMove,
  10909. VkDeviceSize& maxGpuBytesToMove, uint32_t& maxGpuAllocationsToMove,
  10910. VkCommandBuffer commandBuffer)
  10911. {
  10912. pCtx->res = VK_SUCCESS;
  10913. const VkMemoryPropertyFlags memPropFlags =
  10914. m_hAllocator->m_MemProps.memoryTypes[m_MemoryTypeIndex].propertyFlags;
  10915. const bool isHostVisible = (memPropFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0;
  10916. const bool canDefragmentOnCpu = maxCpuBytesToMove > 0 && maxCpuAllocationsToMove > 0 &&
  10917. isHostVisible;
  10918. const bool canDefragmentOnGpu = maxGpuBytesToMove > 0 && maxGpuAllocationsToMove > 0 &&
  10919. !IsCorruptionDetectionEnabled() &&
  10920. ((1u << m_MemoryTypeIndex) & m_hAllocator->GetGpuDefragmentationMemoryTypeBits()) != 0;
  10921. // There are options to defragment this memory type.
  10922. if(canDefragmentOnCpu || canDefragmentOnGpu)
  10923. {
  10924. bool defragmentOnGpu;
  10925. // There is only one option to defragment this memory type.
  10926. if(canDefragmentOnGpu != canDefragmentOnCpu)
  10927. {
  10928. defragmentOnGpu = canDefragmentOnGpu;
  10929. }
  10930. // Both options are available: Heuristics to choose the best one.
  10931. else
  10932. {
  10933. defragmentOnGpu = (memPropFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0 ||
  10934. m_hAllocator->IsIntegratedGpu();
  10935. }
  10936. bool overlappingMoveSupported = !defragmentOnGpu;
  10937. if(m_hAllocator->m_UseMutex)
  10938. {
  10939. m_Mutex.LockWrite();
  10940. pCtx->mutexLocked = true;
  10941. }
  10942. pCtx->Begin(overlappingMoveSupported);
  10943. // Defragment.
  10944. const VkDeviceSize maxBytesToMove = defragmentOnGpu ? maxGpuBytesToMove : maxCpuBytesToMove;
  10945. const uint32_t maxAllocationsToMove = defragmentOnGpu ? maxGpuAllocationsToMove : maxCpuAllocationsToMove;
  10946. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> > moves =
  10947. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >(VmaStlAllocator<VmaDefragmentationMove>(m_hAllocator->GetAllocationCallbacks()));
  10948. pCtx->res = pCtx->GetAlgorithm()->Defragment(moves, maxBytesToMove, maxAllocationsToMove);
  10949. // Accumulate statistics.
  10950. if(pStats != VMA_NULL)
  10951. {
  10952. const VkDeviceSize bytesMoved = pCtx->GetAlgorithm()->GetBytesMoved();
  10953. const uint32_t allocationsMoved = pCtx->GetAlgorithm()->GetAllocationsMoved();
  10954. pStats->bytesMoved += bytesMoved;
  10955. pStats->allocationsMoved += allocationsMoved;
  10956. VMA_ASSERT(bytesMoved <= maxBytesToMove);
  10957. VMA_ASSERT(allocationsMoved <= maxAllocationsToMove);
  10958. if(defragmentOnGpu)
  10959. {
  10960. maxGpuBytesToMove -= bytesMoved;
  10961. maxGpuAllocationsToMove -= allocationsMoved;
  10962. }
  10963. else
  10964. {
  10965. maxCpuBytesToMove -= bytesMoved;
  10966. maxCpuAllocationsToMove -= allocationsMoved;
  10967. }
  10968. }
  10969. if(pCtx->res >= VK_SUCCESS)
  10970. {
  10971. if(defragmentOnGpu)
  10972. {
  10973. ApplyDefragmentationMovesGpu(pCtx, moves, commandBuffer);
  10974. }
  10975. else
  10976. {
  10977. ApplyDefragmentationMovesCpu(pCtx, moves);
  10978. }
  10979. }
  10980. }
  10981. }
  10982. void VmaBlockVector::DefragmentationEnd(
  10983. class VmaBlockVectorDefragmentationContext* pCtx,
  10984. VmaDefragmentationStats* pStats)
  10985. {
  10986. // Destroy buffers.
  10987. for(size_t blockIndex = pCtx->blockContexts.size(); blockIndex--; )
  10988. {
  10989. VmaBlockDefragmentationContext& blockCtx = pCtx->blockContexts[blockIndex];
  10990. if(blockCtx.hBuffer)
  10991. {
  10992. (*m_hAllocator->GetVulkanFunctions().vkDestroyBuffer)(
  10993. m_hAllocator->m_hDevice, blockCtx.hBuffer, m_hAllocator->GetAllocationCallbacks());
  10994. }
  10995. }
  10996. if(pCtx->res >= VK_SUCCESS)
  10997. {
  10998. FreeEmptyBlocks(pStats);
  10999. }
  11000. if(pCtx->mutexLocked)
  11001. {
  11002. VMA_ASSERT(m_hAllocator->m_UseMutex);
  11003. m_Mutex.UnlockWrite();
  11004. }
  11005. }
  11006. size_t VmaBlockVector::CalcAllocationCount() const
  11007. {
  11008. size_t result = 0;
  11009. for(size_t i = 0; i < m_Blocks.size(); ++i)
  11010. {
  11011. result += m_Blocks[i]->m_pMetadata->GetAllocationCount();
  11012. }
  11013. return result;
  11014. }
  11015. bool VmaBlockVector::IsBufferImageGranularityConflictPossible() const
  11016. {
  11017. if(m_BufferImageGranularity == 1)
  11018. {
  11019. return false;
  11020. }
  11021. VmaSuballocationType lastSuballocType = VMA_SUBALLOCATION_TYPE_FREE;
  11022. for(size_t i = 0, count = m_Blocks.size(); i < count; ++i)
  11023. {
  11024. VmaDeviceMemoryBlock* const pBlock = m_Blocks[i];
  11025. VMA_ASSERT(m_Algorithm == 0);
  11026. VmaBlockMetadata_Generic* const pMetadata = (VmaBlockMetadata_Generic*)pBlock->m_pMetadata;
  11027. if(pMetadata->IsBufferImageGranularityConflictPossible(m_BufferImageGranularity, lastSuballocType))
  11028. {
  11029. return true;
  11030. }
  11031. }
  11032. return false;
  11033. }
  11034. void VmaBlockVector::MakePoolAllocationsLost(
  11035. uint32_t currentFrameIndex,
  11036. size_t* pLostAllocationCount)
  11037. {
  11038. VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex);
  11039. size_t lostAllocationCount = 0;
  11040. for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  11041. {
  11042. VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
  11043. VMA_ASSERT(pBlock);
  11044. lostAllocationCount += pBlock->m_pMetadata->MakeAllocationsLost(currentFrameIndex, m_FrameInUseCount);
  11045. }
  11046. if(pLostAllocationCount != VMA_NULL)
  11047. {
  11048. *pLostAllocationCount = lostAllocationCount;
  11049. }
  11050. }
  11051. VkResult VmaBlockVector::CheckCorruption()
  11052. {
  11053. if(!IsCorruptionDetectionEnabled())
  11054. {
  11055. return VK_ERROR_FEATURE_NOT_PRESENT;
  11056. }
  11057. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  11058. for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  11059. {
  11060. VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
  11061. VMA_ASSERT(pBlock);
  11062. VkResult res = pBlock->CheckCorruption(m_hAllocator);
  11063. if(res != VK_SUCCESS)
  11064. {
  11065. return res;
  11066. }
  11067. }
  11068. return VK_SUCCESS;
  11069. }
  11070. void VmaBlockVector::AddStats(VmaStats* pStats)
  11071. {
  11072. const uint32_t memTypeIndex = m_MemoryTypeIndex;
  11073. const uint32_t memHeapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(memTypeIndex);
  11074. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  11075. for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  11076. {
  11077. const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
  11078. VMA_ASSERT(pBlock);
  11079. VMA_HEAVY_ASSERT(pBlock->Validate());
  11080. VmaStatInfo allocationStatInfo;
  11081. pBlock->m_pMetadata->CalcAllocationStatInfo(allocationStatInfo);
  11082. VmaAddStatInfo(pStats->total, allocationStatInfo);
  11083. VmaAddStatInfo(pStats->memoryType[memTypeIndex], allocationStatInfo);
  11084. VmaAddStatInfo(pStats->memoryHeap[memHeapIndex], allocationStatInfo);
  11085. }
  11086. }
  11087. ////////////////////////////////////////////////////////////////////////////////
  11088. // VmaDefragmentationAlgorithm_Generic members definition
  11089. VmaDefragmentationAlgorithm_Generic::VmaDefragmentationAlgorithm_Generic(
  11090. VmaAllocator hAllocator,
  11091. VmaBlockVector* pBlockVector,
  11092. uint32_t currentFrameIndex,
  11093. bool overlappingMoveSupported) :
  11094. VmaDefragmentationAlgorithm(hAllocator, pBlockVector, currentFrameIndex),
  11095. m_AllocationCount(0),
  11096. m_AllAllocations(false),
  11097. m_BytesMoved(0),
  11098. m_AllocationsMoved(0),
  11099. m_Blocks(VmaStlAllocator<BlockInfo*>(hAllocator->GetAllocationCallbacks()))
  11100. {
  11101. // Create block info for each block.
  11102. const size_t blockCount = m_pBlockVector->m_Blocks.size();
  11103. for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
  11104. {
  11105. BlockInfo* pBlockInfo = vma_new(m_hAllocator, BlockInfo)(m_hAllocator->GetAllocationCallbacks());
  11106. pBlockInfo->m_OriginalBlockIndex = blockIndex;
  11107. pBlockInfo->m_pBlock = m_pBlockVector->m_Blocks[blockIndex];
  11108. m_Blocks.push_back(pBlockInfo);
  11109. }
  11110. // Sort them by m_pBlock pointer value.
  11111. VMA_SORT(m_Blocks.begin(), m_Blocks.end(), BlockPointerLess());
  11112. }
  11113. VmaDefragmentationAlgorithm_Generic::~VmaDefragmentationAlgorithm_Generic()
  11114. {
  11115. for(size_t i = m_Blocks.size(); i--; )
  11116. {
  11117. vma_delete(m_hAllocator, m_Blocks[i]);
  11118. }
  11119. }
  11120. void VmaDefragmentationAlgorithm_Generic::AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged)
  11121. {
  11122. // Now as we are inside VmaBlockVector::m_Mutex, we can make final check if this allocation was not lost.
  11123. if(hAlloc->GetLastUseFrameIndex() != VMA_FRAME_INDEX_LOST)
  11124. {
  11125. VmaDeviceMemoryBlock* pBlock = hAlloc->GetBlock();
  11126. BlockInfoVector::iterator it = VmaBinaryFindFirstNotLess(m_Blocks.begin(), m_Blocks.end(), pBlock, BlockPointerLess());
  11127. if(it != m_Blocks.end() && (*it)->m_pBlock == pBlock)
  11128. {
  11129. AllocationInfo allocInfo = AllocationInfo(hAlloc, pChanged);
  11130. (*it)->m_Allocations.push_back(allocInfo);
  11131. }
  11132. else
  11133. {
  11134. VMA_ASSERT(0);
  11135. }
  11136. ++m_AllocationCount;
  11137. }
  11138. }
  11139. VkResult VmaDefragmentationAlgorithm_Generic::DefragmentRound(
  11140. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  11141. VkDeviceSize maxBytesToMove,
  11142. uint32_t maxAllocationsToMove)
  11143. {
  11144. if(m_Blocks.empty())
  11145. {
  11146. return VK_SUCCESS;
  11147. }
  11148. // This is a choice based on research.
  11149. // Option 1:
  11150. uint32_t strategy = VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT;
  11151. // Option 2:
  11152. //uint32_t strategy = VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT;
  11153. // Option 3:
  11154. //uint32_t strategy = VMA_ALLOCATION_CREATE_STRATEGY_MIN_FRAGMENTATION_BIT;
  11155. size_t srcBlockMinIndex = 0;
  11156. // When FAST_ALGORITHM, move allocations from only last out of blocks that contain non-movable allocations.
  11157. /*
  11158. if(m_AlgorithmFlags & VMA_DEFRAGMENTATION_FAST_ALGORITHM_BIT)
  11159. {
  11160. const size_t blocksWithNonMovableCount = CalcBlocksWithNonMovableCount();
  11161. if(blocksWithNonMovableCount > 0)
  11162. {
  11163. srcBlockMinIndex = blocksWithNonMovableCount - 1;
  11164. }
  11165. }
  11166. */
  11167. size_t srcBlockIndex = m_Blocks.size() - 1;
  11168. size_t srcAllocIndex = SIZE_MAX;
  11169. for(;;)
  11170. {
  11171. // 1. Find next allocation to move.
  11172. // 1.1. Start from last to first m_Blocks - they are sorted from most "destination" to most "source".
  11173. // 1.2. Then start from last to first m_Allocations.
  11174. while(srcAllocIndex >= m_Blocks[srcBlockIndex]->m_Allocations.size())
  11175. {
  11176. if(m_Blocks[srcBlockIndex]->m_Allocations.empty())
  11177. {
  11178. // Finished: no more allocations to process.
  11179. if(srcBlockIndex == srcBlockMinIndex)
  11180. {
  11181. return VK_SUCCESS;
  11182. }
  11183. else
  11184. {
  11185. --srcBlockIndex;
  11186. srcAllocIndex = SIZE_MAX;
  11187. }
  11188. }
  11189. else
  11190. {
  11191. srcAllocIndex = m_Blocks[srcBlockIndex]->m_Allocations.size() - 1;
  11192. }
  11193. }
  11194. BlockInfo* pSrcBlockInfo = m_Blocks[srcBlockIndex];
  11195. AllocationInfo& allocInfo = pSrcBlockInfo->m_Allocations[srcAllocIndex];
  11196. const VkDeviceSize size = allocInfo.m_hAllocation->GetSize();
  11197. const VkDeviceSize srcOffset = allocInfo.m_hAllocation->GetOffset();
  11198. const VkDeviceSize alignment = allocInfo.m_hAllocation->GetAlignment();
  11199. const VmaSuballocationType suballocType = allocInfo.m_hAllocation->GetSuballocationType();
  11200. // 2. Try to find new place for this allocation in preceding or current block.
  11201. for(size_t dstBlockIndex = 0; dstBlockIndex <= srcBlockIndex; ++dstBlockIndex)
  11202. {
  11203. BlockInfo* pDstBlockInfo = m_Blocks[dstBlockIndex];
  11204. VmaAllocationRequest dstAllocRequest;
  11205. if(pDstBlockInfo->m_pBlock->m_pMetadata->CreateAllocationRequest(
  11206. m_CurrentFrameIndex,
  11207. m_pBlockVector->GetFrameInUseCount(),
  11208. m_pBlockVector->GetBufferImageGranularity(),
  11209. size,
  11210. alignment,
  11211. false, // upperAddress
  11212. suballocType,
  11213. false, // canMakeOtherLost
  11214. strategy,
  11215. &dstAllocRequest) &&
  11216. MoveMakesSense(
  11217. dstBlockIndex, dstAllocRequest.offset, srcBlockIndex, srcOffset))
  11218. {
  11219. VMA_ASSERT(dstAllocRequest.itemsToMakeLostCount == 0);
  11220. // Reached limit on number of allocations or bytes to move.
  11221. if((m_AllocationsMoved + 1 > maxAllocationsToMove) ||
  11222. (m_BytesMoved + size > maxBytesToMove))
  11223. {
  11224. return VK_SUCCESS;
  11225. }
  11226. VmaDefragmentationMove move;
  11227. move.srcBlockIndex = pSrcBlockInfo->m_OriginalBlockIndex;
  11228. move.dstBlockIndex = pDstBlockInfo->m_OriginalBlockIndex;
  11229. move.srcOffset = srcOffset;
  11230. move.dstOffset = dstAllocRequest.offset;
  11231. move.size = size;
  11232. moves.push_back(move);
  11233. pDstBlockInfo->m_pBlock->m_pMetadata->Alloc(
  11234. dstAllocRequest,
  11235. suballocType,
  11236. size,
  11237. allocInfo.m_hAllocation);
  11238. pSrcBlockInfo->m_pBlock->m_pMetadata->FreeAtOffset(srcOffset);
  11239. allocInfo.m_hAllocation->ChangeBlockAllocation(m_hAllocator, pDstBlockInfo->m_pBlock, dstAllocRequest.offset);
  11240. if(allocInfo.m_pChanged != VMA_NULL)
  11241. {
  11242. *allocInfo.m_pChanged = VK_TRUE;
  11243. }
  11244. ++m_AllocationsMoved;
  11245. m_BytesMoved += size;
  11246. VmaVectorRemove(pSrcBlockInfo->m_Allocations, srcAllocIndex);
  11247. break;
  11248. }
  11249. }
  11250. // If not processed, this allocInfo remains in pBlockInfo->m_Allocations for next round.
  11251. if(srcAllocIndex > 0)
  11252. {
  11253. --srcAllocIndex;
  11254. }
  11255. else
  11256. {
  11257. if(srcBlockIndex > 0)
  11258. {
  11259. --srcBlockIndex;
  11260. srcAllocIndex = SIZE_MAX;
  11261. }
  11262. else
  11263. {
  11264. return VK_SUCCESS;
  11265. }
  11266. }
  11267. }
  11268. }
  11269. size_t VmaDefragmentationAlgorithm_Generic::CalcBlocksWithNonMovableCount() const
  11270. {
  11271. size_t result = 0;
  11272. for(size_t i = 0; i < m_Blocks.size(); ++i)
  11273. {
  11274. if(m_Blocks[i]->m_HasNonMovableAllocations)
  11275. {
  11276. ++result;
  11277. }
  11278. }
  11279. return result;
  11280. }
  11281. VkResult VmaDefragmentationAlgorithm_Generic::Defragment(
  11282. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  11283. VkDeviceSize maxBytesToMove,
  11284. uint32_t maxAllocationsToMove)
  11285. {
  11286. if(!m_AllAllocations && m_AllocationCount == 0)
  11287. {
  11288. return VK_SUCCESS;
  11289. }
  11290. const size_t blockCount = m_Blocks.size();
  11291. for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
  11292. {
  11293. BlockInfo* pBlockInfo = m_Blocks[blockIndex];
  11294. if(m_AllAllocations)
  11295. {
  11296. VmaBlockMetadata_Generic* pMetadata = (VmaBlockMetadata_Generic*)pBlockInfo->m_pBlock->m_pMetadata;
  11297. for(VmaSuballocationList::const_iterator it = pMetadata->m_Suballocations.begin();
  11298. it != pMetadata->m_Suballocations.end();
  11299. ++it)
  11300. {
  11301. if(it->type != VMA_SUBALLOCATION_TYPE_FREE)
  11302. {
  11303. AllocationInfo allocInfo = AllocationInfo(it->hAllocation, VMA_NULL);
  11304. pBlockInfo->m_Allocations.push_back(allocInfo);
  11305. }
  11306. }
  11307. }
  11308. pBlockInfo->CalcHasNonMovableAllocations();
  11309. // This is a choice based on research.
  11310. // Option 1:
  11311. pBlockInfo->SortAllocationsByOffsetDescending();
  11312. // Option 2:
  11313. //pBlockInfo->SortAllocationsBySizeDescending();
  11314. }
  11315. // Sort m_Blocks this time by the main criterium, from most "destination" to most "source" blocks.
  11316. VMA_SORT(m_Blocks.begin(), m_Blocks.end(), BlockInfoCompareMoveDestination());
  11317. // This is a choice based on research.
  11318. const uint32_t roundCount = 2;
  11319. // Execute defragmentation rounds (the main part).
  11320. VkResult result = VK_SUCCESS;
  11321. for(uint32_t round = 0; (round < roundCount) && (result == VK_SUCCESS); ++round)
  11322. {
  11323. result = DefragmentRound(moves, maxBytesToMove, maxAllocationsToMove);
  11324. }
  11325. return result;
  11326. }
  11327. bool VmaDefragmentationAlgorithm_Generic::MoveMakesSense(
  11328. size_t dstBlockIndex, VkDeviceSize dstOffset,
  11329. size_t srcBlockIndex, VkDeviceSize srcOffset)
  11330. {
  11331. if(dstBlockIndex < srcBlockIndex)
  11332. {
  11333. return true;
  11334. }
  11335. if(dstBlockIndex > srcBlockIndex)
  11336. {
  11337. return false;
  11338. }
  11339. if(dstOffset < srcOffset)
  11340. {
  11341. return true;
  11342. }
  11343. return false;
  11344. }
  11345. ////////////////////////////////////////////////////////////////////////////////
  11346. // VmaDefragmentationAlgorithm_Fast
  11347. VmaDefragmentationAlgorithm_Fast::VmaDefragmentationAlgorithm_Fast(
  11348. VmaAllocator hAllocator,
  11349. VmaBlockVector* pBlockVector,
  11350. uint32_t currentFrameIndex,
  11351. bool overlappingMoveSupported) :
  11352. VmaDefragmentationAlgorithm(hAllocator, pBlockVector, currentFrameIndex),
  11353. m_OverlappingMoveSupported(overlappingMoveSupported),
  11354. m_AllocationCount(0),
  11355. m_AllAllocations(false),
  11356. m_BytesMoved(0),
  11357. m_AllocationsMoved(0),
  11358. m_BlockInfos(VmaStlAllocator<BlockInfo>(hAllocator->GetAllocationCallbacks()))
  11359. {
  11360. VMA_ASSERT(VMA_DEBUG_MARGIN == 0);
  11361. }
  11362. VmaDefragmentationAlgorithm_Fast::~VmaDefragmentationAlgorithm_Fast()
  11363. {
  11364. }
  11365. VkResult VmaDefragmentationAlgorithm_Fast::Defragment(
  11366. VmaVector< VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove> >& moves,
  11367. VkDeviceSize maxBytesToMove,
  11368. uint32_t maxAllocationsToMove)
  11369. {
  11370. VMA_ASSERT(m_AllAllocations || m_pBlockVector->CalcAllocationCount() == m_AllocationCount);
  11371. const size_t blockCount = m_pBlockVector->GetBlockCount();
  11372. if(blockCount == 0 || maxBytesToMove == 0 || maxAllocationsToMove == 0)
  11373. {
  11374. return VK_SUCCESS;
  11375. }
  11376. PreprocessMetadata();
  11377. // Sort blocks in order from most destination.
  11378. m_BlockInfos.resize(blockCount);
  11379. for(size_t i = 0; i < blockCount; ++i)
  11380. {
  11381. m_BlockInfos[i].origBlockIndex = i;
  11382. }
  11383. VMA_SORT(m_BlockInfos.begin(), m_BlockInfos.end(), [this](const BlockInfo& lhs, const BlockInfo& rhs) -> bool {
  11384. return m_pBlockVector->GetBlock(lhs.origBlockIndex)->m_pMetadata->GetSumFreeSize() <
  11385. m_pBlockVector->GetBlock(rhs.origBlockIndex)->m_pMetadata->GetSumFreeSize();
  11386. });
  11387. // THE MAIN ALGORITHM
  11388. FreeSpaceDatabase freeSpaceDb;
  11389. size_t dstBlockInfoIndex = 0;
  11390. size_t dstOrigBlockIndex = m_BlockInfos[dstBlockInfoIndex].origBlockIndex;
  11391. VmaDeviceMemoryBlock* pDstBlock = m_pBlockVector->GetBlock(dstOrigBlockIndex);
  11392. VmaBlockMetadata_Generic* pDstMetadata = (VmaBlockMetadata_Generic*)pDstBlock->m_pMetadata;
  11393. VkDeviceSize dstBlockSize = pDstMetadata->GetSize();
  11394. VkDeviceSize dstOffset = 0;
  11395. bool end = false;
  11396. for(size_t srcBlockInfoIndex = 0; !end && srcBlockInfoIndex < blockCount; ++srcBlockInfoIndex)
  11397. {
  11398. const size_t srcOrigBlockIndex = m_BlockInfos[srcBlockInfoIndex].origBlockIndex;
  11399. VmaDeviceMemoryBlock* const pSrcBlock = m_pBlockVector->GetBlock(srcOrigBlockIndex);
  11400. VmaBlockMetadata_Generic* const pSrcMetadata = (VmaBlockMetadata_Generic*)pSrcBlock->m_pMetadata;
  11401. for(VmaSuballocationList::iterator srcSuballocIt = pSrcMetadata->m_Suballocations.begin();
  11402. !end && srcSuballocIt != pSrcMetadata->m_Suballocations.end(); )
  11403. {
  11404. VmaAllocation_T* const pAlloc = srcSuballocIt->hAllocation;
  11405. const VkDeviceSize srcAllocAlignment = pAlloc->GetAlignment();
  11406. const VkDeviceSize srcAllocSize = srcSuballocIt->size;
  11407. if(m_AllocationsMoved == maxAllocationsToMove ||
  11408. m_BytesMoved + srcAllocSize > maxBytesToMove)
  11409. {
  11410. end = true;
  11411. break;
  11412. }
  11413. const VkDeviceSize srcAllocOffset = srcSuballocIt->offset;
  11414. // Try to place it in one of free spaces from the database.
  11415. size_t freeSpaceInfoIndex;
  11416. VkDeviceSize dstAllocOffset;
  11417. if(freeSpaceDb.Fetch(srcAllocAlignment, srcAllocSize,
  11418. freeSpaceInfoIndex, dstAllocOffset))
  11419. {
  11420. size_t freeSpaceOrigBlockIndex = m_BlockInfos[freeSpaceInfoIndex].origBlockIndex;
  11421. VmaDeviceMemoryBlock* pFreeSpaceBlock = m_pBlockVector->GetBlock(freeSpaceOrigBlockIndex);
  11422. VmaBlockMetadata_Generic* pFreeSpaceMetadata = (VmaBlockMetadata_Generic*)pFreeSpaceBlock->m_pMetadata;
  11423. // Same block
  11424. if(freeSpaceInfoIndex == srcBlockInfoIndex)
  11425. {
  11426. VMA_ASSERT(dstAllocOffset <= srcAllocOffset);
  11427. // MOVE OPTION 1: Move the allocation inside the same block by decreasing offset.
  11428. VmaSuballocation suballoc = *srcSuballocIt;
  11429. suballoc.offset = dstAllocOffset;
  11430. suballoc.hAllocation->ChangeOffset(dstAllocOffset);
  11431. m_BytesMoved += srcAllocSize;
  11432. ++m_AllocationsMoved;
  11433. VmaSuballocationList::iterator nextSuballocIt = srcSuballocIt;
  11434. ++nextSuballocIt;
  11435. pSrcMetadata->m_Suballocations.erase(srcSuballocIt);
  11436. srcSuballocIt = nextSuballocIt;
  11437. InsertSuballoc(pFreeSpaceMetadata, suballoc);
  11438. VmaDefragmentationMove move = {
  11439. srcOrigBlockIndex, freeSpaceOrigBlockIndex,
  11440. srcAllocOffset, dstAllocOffset,
  11441. srcAllocSize };
  11442. moves.push_back(move);
  11443. }
  11444. // Different block
  11445. else
  11446. {
  11447. // MOVE OPTION 2: Move the allocation to a different block.
  11448. VMA_ASSERT(freeSpaceInfoIndex < srcBlockInfoIndex);
  11449. VmaSuballocation suballoc = *srcSuballocIt;
  11450. suballoc.offset = dstAllocOffset;
  11451. suballoc.hAllocation->ChangeBlockAllocation(m_hAllocator, pFreeSpaceBlock, dstAllocOffset);
  11452. m_BytesMoved += srcAllocSize;
  11453. ++m_AllocationsMoved;
  11454. VmaSuballocationList::iterator nextSuballocIt = srcSuballocIt;
  11455. ++nextSuballocIt;
  11456. pSrcMetadata->m_Suballocations.erase(srcSuballocIt);
  11457. srcSuballocIt = nextSuballocIt;
  11458. InsertSuballoc(pFreeSpaceMetadata, suballoc);
  11459. VmaDefragmentationMove move = {
  11460. srcOrigBlockIndex, freeSpaceOrigBlockIndex,
  11461. srcAllocOffset, dstAllocOffset,
  11462. srcAllocSize };
  11463. moves.push_back(move);
  11464. }
  11465. }
  11466. else
  11467. {
  11468. dstAllocOffset = VmaAlignUp(dstOffset, srcAllocAlignment);
  11469. // If the allocation doesn't fit before the end of dstBlock, forward to next block.
  11470. while(dstBlockInfoIndex < srcBlockInfoIndex &&
  11471. dstAllocOffset + srcAllocSize > dstBlockSize)
  11472. {
  11473. // But before that, register remaining free space at the end of dst block.
  11474. freeSpaceDb.Register(dstBlockInfoIndex, dstOffset, dstBlockSize - dstOffset);
  11475. ++dstBlockInfoIndex;
  11476. dstOrigBlockIndex = m_BlockInfos[dstBlockInfoIndex].origBlockIndex;
  11477. pDstBlock = m_pBlockVector->GetBlock(dstOrigBlockIndex);
  11478. pDstMetadata = (VmaBlockMetadata_Generic*)pDstBlock->m_pMetadata;
  11479. dstBlockSize = pDstMetadata->GetSize();
  11480. dstOffset = 0;
  11481. dstAllocOffset = 0;
  11482. }
  11483. // Same block
  11484. if(dstBlockInfoIndex == srcBlockInfoIndex)
  11485. {
  11486. VMA_ASSERT(dstAllocOffset <= srcAllocOffset);
  11487. const bool overlap = dstAllocOffset + srcAllocSize > srcAllocOffset;
  11488. bool skipOver = overlap;
  11489. if(overlap && m_OverlappingMoveSupported && dstAllocOffset < srcAllocOffset)
  11490. {
  11491. // If destination and source place overlap, skip if it would move it
  11492. // by only < 1/64 of its size.
  11493. skipOver = (srcAllocOffset - dstAllocOffset) * 64 < srcAllocSize;
  11494. }
  11495. if(skipOver)
  11496. {
  11497. freeSpaceDb.Register(dstBlockInfoIndex, dstOffset, srcAllocOffset - dstOffset);
  11498. dstOffset = srcAllocOffset + srcAllocSize;
  11499. ++srcSuballocIt;
  11500. }
  11501. // MOVE OPTION 1: Move the allocation inside the same block by decreasing offset.
  11502. else
  11503. {
  11504. srcSuballocIt->offset = dstAllocOffset;
  11505. srcSuballocIt->hAllocation->ChangeOffset(dstAllocOffset);
  11506. dstOffset = dstAllocOffset + srcAllocSize;
  11507. m_BytesMoved += srcAllocSize;
  11508. ++m_AllocationsMoved;
  11509. ++srcSuballocIt;
  11510. VmaDefragmentationMove move = {
  11511. srcOrigBlockIndex, dstOrigBlockIndex,
  11512. srcAllocOffset, dstAllocOffset,
  11513. srcAllocSize };
  11514. moves.push_back(move);
  11515. }
  11516. }
  11517. // Different block
  11518. else
  11519. {
  11520. // MOVE OPTION 2: Move the allocation to a different block.
  11521. VMA_ASSERT(dstBlockInfoIndex < srcBlockInfoIndex);
  11522. VMA_ASSERT(dstAllocOffset + srcAllocSize <= dstBlockSize);
  11523. VmaSuballocation suballoc = *srcSuballocIt;
  11524. suballoc.offset = dstAllocOffset;
  11525. suballoc.hAllocation->ChangeBlockAllocation(m_hAllocator, pDstBlock, dstAllocOffset);
  11526. dstOffset = dstAllocOffset + srcAllocSize;
  11527. m_BytesMoved += srcAllocSize;
  11528. ++m_AllocationsMoved;
  11529. VmaSuballocationList::iterator nextSuballocIt = srcSuballocIt;
  11530. ++nextSuballocIt;
  11531. pSrcMetadata->m_Suballocations.erase(srcSuballocIt);
  11532. srcSuballocIt = nextSuballocIt;
  11533. pDstMetadata->m_Suballocations.push_back(suballoc);
  11534. VmaDefragmentationMove move = {
  11535. srcOrigBlockIndex, dstOrigBlockIndex,
  11536. srcAllocOffset, dstAllocOffset,
  11537. srcAllocSize };
  11538. moves.push_back(move);
  11539. }
  11540. }
  11541. }
  11542. }
  11543. m_BlockInfos.clear();
  11544. PostprocessMetadata();
  11545. return VK_SUCCESS;
  11546. }
  11547. void VmaDefragmentationAlgorithm_Fast::PreprocessMetadata()
  11548. {
  11549. const size_t blockCount = m_pBlockVector->GetBlockCount();
  11550. for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
  11551. {
  11552. VmaBlockMetadata_Generic* const pMetadata =
  11553. (VmaBlockMetadata_Generic*)m_pBlockVector->GetBlock(blockIndex)->m_pMetadata;
  11554. pMetadata->m_FreeCount = 0;
  11555. pMetadata->m_SumFreeSize = pMetadata->GetSize();
  11556. pMetadata->m_FreeSuballocationsBySize.clear();
  11557. for(VmaSuballocationList::iterator it = pMetadata->m_Suballocations.begin();
  11558. it != pMetadata->m_Suballocations.end(); )
  11559. {
  11560. if(it->type == VMA_SUBALLOCATION_TYPE_FREE)
  11561. {
  11562. VmaSuballocationList::iterator nextIt = it;
  11563. ++nextIt;
  11564. pMetadata->m_Suballocations.erase(it);
  11565. it = nextIt;
  11566. }
  11567. else
  11568. {
  11569. ++it;
  11570. }
  11571. }
  11572. }
  11573. }
  11574. void VmaDefragmentationAlgorithm_Fast::PostprocessMetadata()
  11575. {
  11576. const size_t blockCount = m_pBlockVector->GetBlockCount();
  11577. for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
  11578. {
  11579. VmaBlockMetadata_Generic* const pMetadata =
  11580. (VmaBlockMetadata_Generic*)m_pBlockVector->GetBlock(blockIndex)->m_pMetadata;
  11581. const VkDeviceSize blockSize = pMetadata->GetSize();
  11582. // No allocations in this block - entire area is free.
  11583. if(pMetadata->m_Suballocations.empty())
  11584. {
  11585. pMetadata->m_FreeCount = 1;
  11586. //pMetadata->m_SumFreeSize is already set to blockSize.
  11587. VmaSuballocation suballoc = {
  11588. 0, // offset
  11589. blockSize, // size
  11590. VMA_NULL, // hAllocation
  11591. VMA_SUBALLOCATION_TYPE_FREE };
  11592. pMetadata->m_Suballocations.push_back(suballoc);
  11593. pMetadata->RegisterFreeSuballocation(pMetadata->m_Suballocations.begin());
  11594. }
  11595. // There are some allocations in this block.
  11596. else
  11597. {
  11598. VkDeviceSize offset = 0;
  11599. VmaSuballocationList::iterator it;
  11600. for(it = pMetadata->m_Suballocations.begin();
  11601. it != pMetadata->m_Suballocations.end();
  11602. ++it)
  11603. {
  11604. VMA_ASSERT(it->type != VMA_SUBALLOCATION_TYPE_FREE);
  11605. VMA_ASSERT(it->offset >= offset);
  11606. // Need to insert preceding free space.
  11607. if(it->offset > offset)
  11608. {
  11609. ++pMetadata->m_FreeCount;
  11610. const VkDeviceSize freeSize = it->offset - offset;
  11611. VmaSuballocation suballoc = {
  11612. offset, // offset
  11613. freeSize, // size
  11614. VMA_NULL, // hAllocation
  11615. VMA_SUBALLOCATION_TYPE_FREE };
  11616. VmaSuballocationList::iterator precedingFreeIt = pMetadata->m_Suballocations.insert(it, suballoc);
  11617. if(freeSize >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
  11618. {
  11619. pMetadata->m_FreeSuballocationsBySize.push_back(precedingFreeIt);
  11620. }
  11621. }
  11622. pMetadata->m_SumFreeSize -= it->size;
  11623. offset = it->offset + it->size;
  11624. }
  11625. // Need to insert trailing free space.
  11626. if(offset < blockSize)
  11627. {
  11628. ++pMetadata->m_FreeCount;
  11629. const VkDeviceSize freeSize = blockSize - offset;
  11630. VmaSuballocation suballoc = {
  11631. offset, // offset
  11632. freeSize, // size
  11633. VMA_NULL, // hAllocation
  11634. VMA_SUBALLOCATION_TYPE_FREE };
  11635. VMA_ASSERT(it == pMetadata->m_Suballocations.end());
  11636. VmaSuballocationList::iterator trailingFreeIt = pMetadata->m_Suballocations.insert(it, suballoc);
  11637. if(freeSize > VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
  11638. {
  11639. pMetadata->m_FreeSuballocationsBySize.push_back(trailingFreeIt);
  11640. }
  11641. }
  11642. VMA_SORT(
  11643. pMetadata->m_FreeSuballocationsBySize.begin(),
  11644. pMetadata->m_FreeSuballocationsBySize.end(),
  11645. VmaSuballocationItemSizeLess());
  11646. }
  11647. VMA_HEAVY_ASSERT(pMetadata->Validate());
  11648. }
  11649. }
  11650. void VmaDefragmentationAlgorithm_Fast::InsertSuballoc(VmaBlockMetadata_Generic* pMetadata, const VmaSuballocation& suballoc)
  11651. {
  11652. // TODO: Optimize somehow. Remember iterator instead of searching for it linearly.
  11653. VmaSuballocationList::iterator it = pMetadata->m_Suballocations.begin();
  11654. while(it != pMetadata->m_Suballocations.end())
  11655. {
  11656. if(it->offset < suballoc.offset)
  11657. {
  11658. ++it;
  11659. }
  11660. }
  11661. pMetadata->m_Suballocations.insert(it, suballoc);
  11662. }
  11663. ////////////////////////////////////////////////////////////////////////////////
  11664. // VmaBlockVectorDefragmentationContext
  11665. VmaBlockVectorDefragmentationContext::VmaBlockVectorDefragmentationContext(
  11666. VmaAllocator hAllocator,
  11667. VmaPool hCustomPool,
  11668. VmaBlockVector* pBlockVector,
  11669. uint32_t currFrameIndex) :
  11670. res(VK_SUCCESS),
  11671. mutexLocked(false),
  11672. blockContexts(VmaStlAllocator<VmaBlockDefragmentationContext>(hAllocator->GetAllocationCallbacks())),
  11673. m_hAllocator(hAllocator),
  11674. m_hCustomPool(hCustomPool),
  11675. m_pBlockVector(pBlockVector),
  11676. m_CurrFrameIndex(currFrameIndex),
  11677. m_pAlgorithm(VMA_NULL),
  11678. m_Allocations(VmaStlAllocator<AllocInfo>(hAllocator->GetAllocationCallbacks())),
  11679. m_AllAllocations(false)
  11680. {
  11681. }
  11682. VmaBlockVectorDefragmentationContext::~VmaBlockVectorDefragmentationContext()
  11683. {
  11684. vma_delete(m_hAllocator, m_pAlgorithm);
  11685. }
  11686. void VmaBlockVectorDefragmentationContext::AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged)
  11687. {
  11688. AllocInfo info = { hAlloc, pChanged };
  11689. m_Allocations.push_back(info);
  11690. }
  11691. void VmaBlockVectorDefragmentationContext::Begin(bool overlappingMoveSupported)
  11692. {
  11693. const bool allAllocations = m_AllAllocations ||
  11694. m_Allocations.size() == m_pBlockVector->CalcAllocationCount();
  11695. /********************************
  11696. HERE IS THE CHOICE OF DEFRAGMENTATION ALGORITHM.
  11697. ********************************/
  11698. /*
  11699. Fast algorithm is supported only when certain criteria are met:
  11700. - VMA_DEBUG_MARGIN is 0.
  11701. - All allocations in this block vector are moveable.
  11702. - There is no possibility of image/buffer granularity conflict.
  11703. */
  11704. if(VMA_DEBUG_MARGIN == 0 &&
  11705. allAllocations &&
  11706. !m_pBlockVector->IsBufferImageGranularityConflictPossible())
  11707. {
  11708. m_pAlgorithm = vma_new(m_hAllocator, VmaDefragmentationAlgorithm_Fast)(
  11709. m_hAllocator, m_pBlockVector, m_CurrFrameIndex, overlappingMoveSupported);
  11710. }
  11711. else
  11712. {
  11713. m_pAlgorithm = vma_new(m_hAllocator, VmaDefragmentationAlgorithm_Generic)(
  11714. m_hAllocator, m_pBlockVector, m_CurrFrameIndex, overlappingMoveSupported);
  11715. }
  11716. if(allAllocations)
  11717. {
  11718. m_pAlgorithm->AddAll();
  11719. }
  11720. else
  11721. {
  11722. for(size_t i = 0, count = m_Allocations.size(); i < count; ++i)
  11723. {
  11724. m_pAlgorithm->AddAllocation(m_Allocations[i].hAlloc, m_Allocations[i].pChanged);
  11725. }
  11726. }
  11727. }
  11728. ////////////////////////////////////////////////////////////////////////////////
  11729. // VmaDefragmentationContext
  11730. VmaDefragmentationContext_T::VmaDefragmentationContext_T(
  11731. VmaAllocator hAllocator,
  11732. uint32_t currFrameIndex,
  11733. uint32_t flags,
  11734. VmaDefragmentationStats* pStats) :
  11735. m_hAllocator(hAllocator),
  11736. m_CurrFrameIndex(currFrameIndex),
  11737. m_Flags(flags),
  11738. m_pStats(pStats),
  11739. m_CustomPoolContexts(VmaStlAllocator<VmaBlockVectorDefragmentationContext*>(hAllocator->GetAllocationCallbacks()))
  11740. {
  11741. memset(m_DefaultPoolContexts, 0, sizeof(m_DefaultPoolContexts));
  11742. }
  11743. VmaDefragmentationContext_T::~VmaDefragmentationContext_T()
  11744. {
  11745. for(size_t i = m_CustomPoolContexts.size(); i--; )
  11746. {
  11747. VmaBlockVectorDefragmentationContext* pBlockVectorCtx = m_CustomPoolContexts[i];
  11748. pBlockVectorCtx->GetBlockVector()->DefragmentationEnd(pBlockVectorCtx, m_pStats);
  11749. vma_delete(m_hAllocator, pBlockVectorCtx);
  11750. }
  11751. for(size_t i = m_hAllocator->m_MemProps.memoryTypeCount; i--; )
  11752. {
  11753. VmaBlockVectorDefragmentationContext* pBlockVectorCtx = m_DefaultPoolContexts[i];
  11754. if(pBlockVectorCtx)
  11755. {
  11756. pBlockVectorCtx->GetBlockVector()->DefragmentationEnd(pBlockVectorCtx, m_pStats);
  11757. vma_delete(m_hAllocator, pBlockVectorCtx);
  11758. }
  11759. }
  11760. }
  11761. void VmaDefragmentationContext_T::AddPools(uint32_t poolCount, VmaPool* pPools)
  11762. {
  11763. for(uint32_t poolIndex = 0; poolIndex < poolCount; ++poolIndex)
  11764. {
  11765. VmaPool pool = pPools[poolIndex];
  11766. VMA_ASSERT(pool);
  11767. // Pools with algorithm other than default are not defragmented.
  11768. if(pool->m_BlockVector.GetAlgorithm() == 0)
  11769. {
  11770. VmaBlockVectorDefragmentationContext* pBlockVectorDefragCtx = VMA_NULL;
  11771. for(size_t i = m_CustomPoolContexts.size(); i--; )
  11772. {
  11773. if(m_CustomPoolContexts[i]->GetCustomPool() == pool)
  11774. {
  11775. pBlockVectorDefragCtx = m_CustomPoolContexts[i];
  11776. break;
  11777. }
  11778. }
  11779. if(!pBlockVectorDefragCtx)
  11780. {
  11781. pBlockVectorDefragCtx = vma_new(m_hAllocator, VmaBlockVectorDefragmentationContext)(
  11782. m_hAllocator,
  11783. pool,
  11784. &pool->m_BlockVector,
  11785. m_CurrFrameIndex);
  11786. m_CustomPoolContexts.push_back(pBlockVectorDefragCtx);
  11787. }
  11788. pBlockVectorDefragCtx->AddAll();
  11789. }
  11790. }
  11791. }
  11792. void VmaDefragmentationContext_T::AddAllocations(
  11793. uint32_t allocationCount,
  11794. VmaAllocation* pAllocations,
  11795. VkBool32* pAllocationsChanged)
  11796. {
  11797. // Dispatch pAllocations among defragmentators. Create them when necessary.
  11798. for(uint32_t allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  11799. {
  11800. const VmaAllocation hAlloc = pAllocations[allocIndex];
  11801. VMA_ASSERT(hAlloc);
  11802. // DedicatedAlloc cannot be defragmented.
  11803. if((hAlloc->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK) &&
  11804. // Lost allocation cannot be defragmented.
  11805. (hAlloc->GetLastUseFrameIndex() != VMA_FRAME_INDEX_LOST))
  11806. {
  11807. VmaBlockVectorDefragmentationContext* pBlockVectorDefragCtx = VMA_NULL;
  11808. const VmaPool hAllocPool = hAlloc->GetBlock()->GetParentPool();
  11809. // This allocation belongs to custom pool.
  11810. if(hAllocPool != VK_NULL_HANDLE)
  11811. {
  11812. // Pools with algorithm other than default are not defragmented.
  11813. if(hAllocPool->m_BlockVector.GetAlgorithm() == 0)
  11814. {
  11815. for(size_t i = m_CustomPoolContexts.size(); i--; )
  11816. {
  11817. if(m_CustomPoolContexts[i]->GetCustomPool() == hAllocPool)
  11818. {
  11819. pBlockVectorDefragCtx = m_CustomPoolContexts[i];
  11820. break;
  11821. }
  11822. }
  11823. if(!pBlockVectorDefragCtx)
  11824. {
  11825. pBlockVectorDefragCtx = vma_new(m_hAllocator, VmaBlockVectorDefragmentationContext)(
  11826. m_hAllocator,
  11827. hAllocPool,
  11828. &hAllocPool->m_BlockVector,
  11829. m_CurrFrameIndex);
  11830. m_CustomPoolContexts.push_back(pBlockVectorDefragCtx);
  11831. }
  11832. }
  11833. }
  11834. // This allocation belongs to default pool.
  11835. else
  11836. {
  11837. const uint32_t memTypeIndex = hAlloc->GetMemoryTypeIndex();
  11838. pBlockVectorDefragCtx = m_DefaultPoolContexts[memTypeIndex];
  11839. if(!pBlockVectorDefragCtx)
  11840. {
  11841. pBlockVectorDefragCtx = vma_new(m_hAllocator, VmaBlockVectorDefragmentationContext)(
  11842. m_hAllocator,
  11843. VMA_NULL, // hCustomPool
  11844. m_hAllocator->m_pBlockVectors[memTypeIndex],
  11845. m_CurrFrameIndex);
  11846. m_DefaultPoolContexts[memTypeIndex] = pBlockVectorDefragCtx;
  11847. }
  11848. }
  11849. if(pBlockVectorDefragCtx)
  11850. {
  11851. VkBool32* const pChanged = (pAllocationsChanged != VMA_NULL) ?
  11852. &pAllocationsChanged[allocIndex] : VMA_NULL;
  11853. pBlockVectorDefragCtx->AddAllocation(hAlloc, pChanged);
  11854. }
  11855. }
  11856. }
  11857. }
  11858. VkResult VmaDefragmentationContext_T::Defragment(
  11859. VkDeviceSize maxCpuBytesToMove, uint32_t maxCpuAllocationsToMove,
  11860. VkDeviceSize maxGpuBytesToMove, uint32_t maxGpuAllocationsToMove,
  11861. VkCommandBuffer commandBuffer, VmaDefragmentationStats* pStats)
  11862. {
  11863. if(pStats)
  11864. {
  11865. memset(pStats, 0, sizeof(VmaDefragmentationStats));
  11866. }
  11867. if(commandBuffer == VK_NULL_HANDLE)
  11868. {
  11869. maxGpuBytesToMove = 0;
  11870. maxGpuAllocationsToMove = 0;
  11871. }
  11872. VkResult res = VK_SUCCESS;
  11873. // Process default pools.
  11874. for(uint32_t memTypeIndex = 0;
  11875. memTypeIndex < m_hAllocator->GetMemoryTypeCount() && res >= VK_SUCCESS;
  11876. ++memTypeIndex)
  11877. {
  11878. VmaBlockVectorDefragmentationContext* pBlockVectorCtx = m_DefaultPoolContexts[memTypeIndex];
  11879. if(pBlockVectorCtx)
  11880. {
  11881. VMA_ASSERT(pBlockVectorCtx->GetBlockVector());
  11882. pBlockVectorCtx->GetBlockVector()->Defragment(
  11883. pBlockVectorCtx,
  11884. pStats,
  11885. maxCpuBytesToMove, maxCpuAllocationsToMove,
  11886. maxGpuBytesToMove, maxGpuAllocationsToMove,
  11887. commandBuffer);
  11888. if(pBlockVectorCtx->res != VK_SUCCESS)
  11889. {
  11890. res = pBlockVectorCtx->res;
  11891. }
  11892. }
  11893. }
  11894. // Process custom pools.
  11895. for(size_t customCtxIndex = 0, customCtxCount = m_CustomPoolContexts.size();
  11896. customCtxIndex < customCtxCount && res >= VK_SUCCESS;
  11897. ++customCtxIndex)
  11898. {
  11899. VmaBlockVectorDefragmentationContext* pBlockVectorCtx = m_CustomPoolContexts[customCtxIndex];
  11900. VMA_ASSERT(pBlockVectorCtx && pBlockVectorCtx->GetBlockVector());
  11901. pBlockVectorCtx->GetBlockVector()->Defragment(
  11902. pBlockVectorCtx,
  11903. pStats,
  11904. maxCpuBytesToMove, maxCpuAllocationsToMove,
  11905. maxGpuBytesToMove, maxGpuAllocationsToMove,
  11906. commandBuffer);
  11907. if(pBlockVectorCtx->res != VK_SUCCESS)
  11908. {
  11909. res = pBlockVectorCtx->res;
  11910. }
  11911. }
  11912. return res;
  11913. }
  11914. ////////////////////////////////////////////////////////////////////////////////
  11915. // VmaRecorder
  11916. #if VMA_RECORDING_ENABLED
  11917. VmaRecorder::VmaRecorder() :
  11918. m_UseMutex(true),
  11919. m_Flags(0),
  11920. m_File(VMA_NULL),
  11921. m_Freq(INT64_MAX),
  11922. m_StartCounter(INT64_MAX)
  11923. {
  11924. }
  11925. VkResult VmaRecorder::Init(const VmaRecordSettings& settings, bool useMutex)
  11926. {
  11927. m_UseMutex = useMutex;
  11928. m_Flags = settings.flags;
  11929. QueryPerformanceFrequency((LARGE_INTEGER*)&m_Freq);
  11930. QueryPerformanceCounter((LARGE_INTEGER*)&m_StartCounter);
  11931. // Open file for writing.
  11932. errno_t err = fopen_s(&m_File, settings.pFilePath, "wb");
  11933. if(err != 0)
  11934. {
  11935. return VK_ERROR_INITIALIZATION_FAILED;
  11936. }
  11937. // Write header.
  11938. fprintf(m_File, "%s\n", "Vulkan Memory Allocator,Calls recording");
  11939. fprintf(m_File, "%s\n", "1,8");
  11940. return VK_SUCCESS;
  11941. }
  11942. VmaRecorder::~VmaRecorder()
  11943. {
  11944. if(m_File != VMA_NULL)
  11945. {
  11946. fclose(m_File);
  11947. }
  11948. }
  11949. void VmaRecorder::RecordCreateAllocator(uint32_t frameIndex)
  11950. {
  11951. CallParams callParams;
  11952. GetBasicParams(callParams);
  11953. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  11954. fprintf(m_File, "%u,%.3f,%u,vmaCreateAllocator\n", callParams.threadId, callParams.time, frameIndex);
  11955. Flush();
  11956. }
  11957. void VmaRecorder::RecordDestroyAllocator(uint32_t frameIndex)
  11958. {
  11959. CallParams callParams;
  11960. GetBasicParams(callParams);
  11961. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  11962. fprintf(m_File, "%u,%.3f,%u,vmaDestroyAllocator\n", callParams.threadId, callParams.time, frameIndex);
  11963. Flush();
  11964. }
  11965. void VmaRecorder::RecordCreatePool(uint32_t frameIndex, const VmaPoolCreateInfo& createInfo, VmaPool pool)
  11966. {
  11967. CallParams callParams;
  11968. GetBasicParams(callParams);
  11969. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  11970. fprintf(m_File, "%u,%.3f,%u,vmaCreatePool,%u,%u,%llu,%llu,%llu,%u,%p\n", callParams.threadId, callParams.time, frameIndex,
  11971. createInfo.memoryTypeIndex,
  11972. createInfo.flags,
  11973. createInfo.blockSize,
  11974. (uint64_t)createInfo.minBlockCount,
  11975. (uint64_t)createInfo.maxBlockCount,
  11976. createInfo.frameInUseCount,
  11977. pool);
  11978. Flush();
  11979. }
  11980. void VmaRecorder::RecordDestroyPool(uint32_t frameIndex, VmaPool pool)
  11981. {
  11982. CallParams callParams;
  11983. GetBasicParams(callParams);
  11984. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  11985. fprintf(m_File, "%u,%.3f,%u,vmaDestroyPool,%p\n", callParams.threadId, callParams.time, frameIndex,
  11986. pool);
  11987. Flush();
  11988. }
  11989. void VmaRecorder::RecordAllocateMemory(uint32_t frameIndex,
  11990. const VkMemoryRequirements& vkMemReq,
  11991. const VmaAllocationCreateInfo& createInfo,
  11992. VmaAllocation allocation)
  11993. {
  11994. CallParams callParams;
  11995. GetBasicParams(callParams);
  11996. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  11997. UserDataString userDataStr(createInfo.flags, createInfo.pUserData);
  11998. fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemory,%llu,%llu,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
  11999. vkMemReq.size,
  12000. vkMemReq.alignment,
  12001. vkMemReq.memoryTypeBits,
  12002. createInfo.flags,
  12003. createInfo.usage,
  12004. createInfo.requiredFlags,
  12005. createInfo.preferredFlags,
  12006. createInfo.memoryTypeBits,
  12007. createInfo.pool,
  12008. allocation,
  12009. userDataStr.GetString());
  12010. Flush();
  12011. }
  12012. void VmaRecorder::RecordAllocateMemoryPages(uint32_t frameIndex,
  12013. const VkMemoryRequirements& vkMemReq,
  12014. const VmaAllocationCreateInfo& createInfo,
  12015. uint64_t allocationCount,
  12016. const VmaAllocation* pAllocations)
  12017. {
  12018. CallParams callParams;
  12019. GetBasicParams(callParams);
  12020. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12021. UserDataString userDataStr(createInfo.flags, createInfo.pUserData);
  12022. fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemoryPages,%llu,%llu,%u,%u,%u,%u,%u,%u,%p,", callParams.threadId, callParams.time, frameIndex,
  12023. vkMemReq.size,
  12024. vkMemReq.alignment,
  12025. vkMemReq.memoryTypeBits,
  12026. createInfo.flags,
  12027. createInfo.usage,
  12028. createInfo.requiredFlags,
  12029. createInfo.preferredFlags,
  12030. createInfo.memoryTypeBits,
  12031. createInfo.pool);
  12032. PrintPointerList(allocationCount, pAllocations);
  12033. fprintf(m_File, ",%s\n", userDataStr.GetString());
  12034. Flush();
  12035. }
  12036. void VmaRecorder::RecordAllocateMemoryForBuffer(uint32_t frameIndex,
  12037. const VkMemoryRequirements& vkMemReq,
  12038. bool requiresDedicatedAllocation,
  12039. bool prefersDedicatedAllocation,
  12040. const VmaAllocationCreateInfo& createInfo,
  12041. VmaAllocation allocation)
  12042. {
  12043. CallParams callParams;
  12044. GetBasicParams(callParams);
  12045. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12046. UserDataString userDataStr(createInfo.flags, createInfo.pUserData);
  12047. fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemoryForBuffer,%llu,%llu,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
  12048. vkMemReq.size,
  12049. vkMemReq.alignment,
  12050. vkMemReq.memoryTypeBits,
  12051. requiresDedicatedAllocation ? 1 : 0,
  12052. prefersDedicatedAllocation ? 1 : 0,
  12053. createInfo.flags,
  12054. createInfo.usage,
  12055. createInfo.requiredFlags,
  12056. createInfo.preferredFlags,
  12057. createInfo.memoryTypeBits,
  12058. createInfo.pool,
  12059. allocation,
  12060. userDataStr.GetString());
  12061. Flush();
  12062. }
  12063. void VmaRecorder::RecordAllocateMemoryForImage(uint32_t frameIndex,
  12064. const VkMemoryRequirements& vkMemReq,
  12065. bool requiresDedicatedAllocation,
  12066. bool prefersDedicatedAllocation,
  12067. const VmaAllocationCreateInfo& createInfo,
  12068. VmaAllocation allocation)
  12069. {
  12070. CallParams callParams;
  12071. GetBasicParams(callParams);
  12072. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12073. UserDataString userDataStr(createInfo.flags, createInfo.pUserData);
  12074. fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemoryForImage,%llu,%llu,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
  12075. vkMemReq.size,
  12076. vkMemReq.alignment,
  12077. vkMemReq.memoryTypeBits,
  12078. requiresDedicatedAllocation ? 1 : 0,
  12079. prefersDedicatedAllocation ? 1 : 0,
  12080. createInfo.flags,
  12081. createInfo.usage,
  12082. createInfo.requiredFlags,
  12083. createInfo.preferredFlags,
  12084. createInfo.memoryTypeBits,
  12085. createInfo.pool,
  12086. allocation,
  12087. userDataStr.GetString());
  12088. Flush();
  12089. }
  12090. void VmaRecorder::RecordFreeMemory(uint32_t frameIndex,
  12091. VmaAllocation allocation)
  12092. {
  12093. CallParams callParams;
  12094. GetBasicParams(callParams);
  12095. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12096. fprintf(m_File, "%u,%.3f,%u,vmaFreeMemory,%p\n", callParams.threadId, callParams.time, frameIndex,
  12097. allocation);
  12098. Flush();
  12099. }
  12100. void VmaRecorder::RecordFreeMemoryPages(uint32_t frameIndex,
  12101. uint64_t allocationCount,
  12102. const VmaAllocation* pAllocations)
  12103. {
  12104. CallParams callParams;
  12105. GetBasicParams(callParams);
  12106. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12107. fprintf(m_File, "%u,%.3f,%u,vmaFreeMemoryPages,", callParams.threadId, callParams.time, frameIndex);
  12108. PrintPointerList(allocationCount, pAllocations);
  12109. fprintf(m_File, "\n");
  12110. Flush();
  12111. }
  12112. void VmaRecorder::RecordSetAllocationUserData(uint32_t frameIndex,
  12113. VmaAllocation allocation,
  12114. const void* pUserData)
  12115. {
  12116. CallParams callParams;
  12117. GetBasicParams(callParams);
  12118. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12119. UserDataString userDataStr(
  12120. allocation->IsUserDataString() ? VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT : 0,
  12121. pUserData);
  12122. fprintf(m_File, "%u,%.3f,%u,vmaSetAllocationUserData,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
  12123. allocation,
  12124. userDataStr.GetString());
  12125. Flush();
  12126. }
  12127. void VmaRecorder::RecordCreateLostAllocation(uint32_t frameIndex,
  12128. VmaAllocation allocation)
  12129. {
  12130. CallParams callParams;
  12131. GetBasicParams(callParams);
  12132. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12133. fprintf(m_File, "%u,%.3f,%u,vmaCreateLostAllocation,%p\n", callParams.threadId, callParams.time, frameIndex,
  12134. allocation);
  12135. Flush();
  12136. }
  12137. void VmaRecorder::RecordMapMemory(uint32_t frameIndex,
  12138. VmaAllocation allocation)
  12139. {
  12140. CallParams callParams;
  12141. GetBasicParams(callParams);
  12142. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12143. fprintf(m_File, "%u,%.3f,%u,vmaMapMemory,%p\n", callParams.threadId, callParams.time, frameIndex,
  12144. allocation);
  12145. Flush();
  12146. }
  12147. void VmaRecorder::RecordUnmapMemory(uint32_t frameIndex,
  12148. VmaAllocation allocation)
  12149. {
  12150. CallParams callParams;
  12151. GetBasicParams(callParams);
  12152. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12153. fprintf(m_File, "%u,%.3f,%u,vmaUnmapMemory,%p\n", callParams.threadId, callParams.time, frameIndex,
  12154. allocation);
  12155. Flush();
  12156. }
  12157. void VmaRecorder::RecordFlushAllocation(uint32_t frameIndex,
  12158. VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size)
  12159. {
  12160. CallParams callParams;
  12161. GetBasicParams(callParams);
  12162. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12163. fprintf(m_File, "%u,%.3f,%u,vmaFlushAllocation,%p,%llu,%llu\n", callParams.threadId, callParams.time, frameIndex,
  12164. allocation,
  12165. offset,
  12166. size);
  12167. Flush();
  12168. }
  12169. void VmaRecorder::RecordInvalidateAllocation(uint32_t frameIndex,
  12170. VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size)
  12171. {
  12172. CallParams callParams;
  12173. GetBasicParams(callParams);
  12174. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12175. fprintf(m_File, "%u,%.3f,%u,vmaInvalidateAllocation,%p,%llu,%llu\n", callParams.threadId, callParams.time, frameIndex,
  12176. allocation,
  12177. offset,
  12178. size);
  12179. Flush();
  12180. }
  12181. void VmaRecorder::RecordCreateBuffer(uint32_t frameIndex,
  12182. const VkBufferCreateInfo& bufCreateInfo,
  12183. const VmaAllocationCreateInfo& allocCreateInfo,
  12184. VmaAllocation allocation)
  12185. {
  12186. CallParams callParams;
  12187. GetBasicParams(callParams);
  12188. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12189. UserDataString userDataStr(allocCreateInfo.flags, allocCreateInfo.pUserData);
  12190. fprintf(m_File, "%u,%.3f,%u,vmaCreateBuffer,%u,%llu,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
  12191. bufCreateInfo.flags,
  12192. bufCreateInfo.size,
  12193. bufCreateInfo.usage,
  12194. bufCreateInfo.sharingMode,
  12195. allocCreateInfo.flags,
  12196. allocCreateInfo.usage,
  12197. allocCreateInfo.requiredFlags,
  12198. allocCreateInfo.preferredFlags,
  12199. allocCreateInfo.memoryTypeBits,
  12200. allocCreateInfo.pool,
  12201. allocation,
  12202. userDataStr.GetString());
  12203. Flush();
  12204. }
  12205. void VmaRecorder::RecordCreateImage(uint32_t frameIndex,
  12206. const VkImageCreateInfo& imageCreateInfo,
  12207. const VmaAllocationCreateInfo& allocCreateInfo,
  12208. VmaAllocation allocation)
  12209. {
  12210. CallParams callParams;
  12211. GetBasicParams(callParams);
  12212. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12213. UserDataString userDataStr(allocCreateInfo.flags, allocCreateInfo.pUserData);
  12214. fprintf(m_File, "%u,%.3f,%u,vmaCreateImage,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
  12215. imageCreateInfo.flags,
  12216. imageCreateInfo.imageType,
  12217. imageCreateInfo.format,
  12218. imageCreateInfo.extent.width,
  12219. imageCreateInfo.extent.height,
  12220. imageCreateInfo.extent.depth,
  12221. imageCreateInfo.mipLevels,
  12222. imageCreateInfo.arrayLayers,
  12223. imageCreateInfo.samples,
  12224. imageCreateInfo.tiling,
  12225. imageCreateInfo.usage,
  12226. imageCreateInfo.sharingMode,
  12227. imageCreateInfo.initialLayout,
  12228. allocCreateInfo.flags,
  12229. allocCreateInfo.usage,
  12230. allocCreateInfo.requiredFlags,
  12231. allocCreateInfo.preferredFlags,
  12232. allocCreateInfo.memoryTypeBits,
  12233. allocCreateInfo.pool,
  12234. allocation,
  12235. userDataStr.GetString());
  12236. Flush();
  12237. }
  12238. void VmaRecorder::RecordDestroyBuffer(uint32_t frameIndex,
  12239. VmaAllocation allocation)
  12240. {
  12241. CallParams callParams;
  12242. GetBasicParams(callParams);
  12243. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12244. fprintf(m_File, "%u,%.3f,%u,vmaDestroyBuffer,%p\n", callParams.threadId, callParams.time, frameIndex,
  12245. allocation);
  12246. Flush();
  12247. }
  12248. void VmaRecorder::RecordDestroyImage(uint32_t frameIndex,
  12249. VmaAllocation allocation)
  12250. {
  12251. CallParams callParams;
  12252. GetBasicParams(callParams);
  12253. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12254. fprintf(m_File, "%u,%.3f,%u,vmaDestroyImage,%p\n", callParams.threadId, callParams.time, frameIndex,
  12255. allocation);
  12256. Flush();
  12257. }
  12258. void VmaRecorder::RecordTouchAllocation(uint32_t frameIndex,
  12259. VmaAllocation allocation)
  12260. {
  12261. CallParams callParams;
  12262. GetBasicParams(callParams);
  12263. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12264. fprintf(m_File, "%u,%.3f,%u,vmaTouchAllocation,%p\n", callParams.threadId, callParams.time, frameIndex,
  12265. allocation);
  12266. Flush();
  12267. }
  12268. void VmaRecorder::RecordGetAllocationInfo(uint32_t frameIndex,
  12269. VmaAllocation allocation)
  12270. {
  12271. CallParams callParams;
  12272. GetBasicParams(callParams);
  12273. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12274. fprintf(m_File, "%u,%.3f,%u,vmaGetAllocationInfo,%p\n", callParams.threadId, callParams.time, frameIndex,
  12275. allocation);
  12276. Flush();
  12277. }
  12278. void VmaRecorder::RecordMakePoolAllocationsLost(uint32_t frameIndex,
  12279. VmaPool pool)
  12280. {
  12281. CallParams callParams;
  12282. GetBasicParams(callParams);
  12283. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12284. fprintf(m_File, "%u,%.3f,%u,vmaMakePoolAllocationsLost,%p\n", callParams.threadId, callParams.time, frameIndex,
  12285. pool);
  12286. Flush();
  12287. }
  12288. void VmaRecorder::RecordDefragmentationBegin(uint32_t frameIndex,
  12289. const VmaDefragmentationInfo2& info,
  12290. VmaDefragmentationContext ctx)
  12291. {
  12292. CallParams callParams;
  12293. GetBasicParams(callParams);
  12294. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12295. fprintf(m_File, "%u,%.3f,%u,vmaDefragmentationBegin,%u,", callParams.threadId, callParams.time, frameIndex,
  12296. info.flags);
  12297. PrintPointerList(info.allocationCount, info.pAllocations);
  12298. fprintf(m_File, ",");
  12299. PrintPointerList(info.poolCount, info.pPools);
  12300. fprintf(m_File, ",%llu,%u,%llu,%u,%p,%p\n",
  12301. info.maxCpuBytesToMove,
  12302. info.maxCpuAllocationsToMove,
  12303. info.maxGpuBytesToMove,
  12304. info.maxGpuAllocationsToMove,
  12305. info.commandBuffer,
  12306. ctx);
  12307. Flush();
  12308. }
  12309. void VmaRecorder::RecordDefragmentationEnd(uint32_t frameIndex,
  12310. VmaDefragmentationContext ctx)
  12311. {
  12312. CallParams callParams;
  12313. GetBasicParams(callParams);
  12314. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12315. fprintf(m_File, "%u,%.3f,%u,vmaDefragmentationEnd,%p\n", callParams.threadId, callParams.time, frameIndex,
  12316. ctx);
  12317. Flush();
  12318. }
  12319. void VmaRecorder::RecordSetPoolName(uint32_t frameIndex,
  12320. VmaPool pool,
  12321. const char* name)
  12322. {
  12323. CallParams callParams;
  12324. GetBasicParams(callParams);
  12325. VmaMutexLock lock(m_FileMutex, m_UseMutex);
  12326. fprintf(m_File, "%u,%.3f,%u,vmaSetPoolName,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
  12327. pool, name != VMA_NULL ? name : "");
  12328. Flush();
  12329. }
  12330. VmaRecorder::UserDataString::UserDataString(VmaAllocationCreateFlags allocFlags, const void* pUserData)
  12331. {
  12332. if(pUserData != VMA_NULL)
  12333. {
  12334. if((allocFlags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0)
  12335. {
  12336. m_Str = (const char*)pUserData;
  12337. }
  12338. else
  12339. {
  12340. sprintf_s(m_PtrStr, "%p", pUserData);
  12341. m_Str = m_PtrStr;
  12342. }
  12343. }
  12344. else
  12345. {
  12346. m_Str = "";
  12347. }
  12348. }
  12349. void VmaRecorder::WriteConfiguration(
  12350. const VkPhysicalDeviceProperties& devProps,
  12351. const VkPhysicalDeviceMemoryProperties& memProps,
  12352. uint32_t vulkanApiVersion,
  12353. bool dedicatedAllocationExtensionEnabled,
  12354. bool bindMemory2ExtensionEnabled,
  12355. bool memoryBudgetExtensionEnabled)
  12356. {
  12357. fprintf(m_File, "Config,Begin\n");
  12358. fprintf(m_File, "VulkanApiVersion,%u,%u\n", VK_VERSION_MAJOR(vulkanApiVersion), VK_VERSION_MINOR(vulkanApiVersion));
  12359. fprintf(m_File, "PhysicalDevice,apiVersion,%u\n", devProps.apiVersion);
  12360. fprintf(m_File, "PhysicalDevice,driverVersion,%u\n", devProps.driverVersion);
  12361. fprintf(m_File, "PhysicalDevice,vendorID,%u\n", devProps.vendorID);
  12362. fprintf(m_File, "PhysicalDevice,deviceID,%u\n", devProps.deviceID);
  12363. fprintf(m_File, "PhysicalDevice,deviceType,%u\n", devProps.deviceType);
  12364. fprintf(m_File, "PhysicalDevice,deviceName,%s\n", devProps.deviceName);
  12365. fprintf(m_File, "PhysicalDeviceLimits,maxMemoryAllocationCount,%u\n", devProps.limits.maxMemoryAllocationCount);
  12366. fprintf(m_File, "PhysicalDeviceLimits,bufferImageGranularity,%llu\n", devProps.limits.bufferImageGranularity);
  12367. fprintf(m_File, "PhysicalDeviceLimits,nonCoherentAtomSize,%llu\n", devProps.limits.nonCoherentAtomSize);
  12368. fprintf(m_File, "PhysicalDeviceMemory,HeapCount,%u\n", memProps.memoryHeapCount);
  12369. for(uint32_t i = 0; i < memProps.memoryHeapCount; ++i)
  12370. {
  12371. fprintf(m_File, "PhysicalDeviceMemory,Heap,%u,size,%llu\n", i, memProps.memoryHeaps[i].size);
  12372. fprintf(m_File, "PhysicalDeviceMemory,Heap,%u,flags,%u\n", i, memProps.memoryHeaps[i].flags);
  12373. }
  12374. fprintf(m_File, "PhysicalDeviceMemory,TypeCount,%u\n", memProps.memoryTypeCount);
  12375. for(uint32_t i = 0; i < memProps.memoryTypeCount; ++i)
  12376. {
  12377. fprintf(m_File, "PhysicalDeviceMemory,Type,%u,heapIndex,%u\n", i, memProps.memoryTypes[i].heapIndex);
  12378. fprintf(m_File, "PhysicalDeviceMemory,Type,%u,propertyFlags,%u\n", i, memProps.memoryTypes[i].propertyFlags);
  12379. }
  12380. fprintf(m_File, "Extension,VK_KHR_dedicated_allocation,%u\n", dedicatedAllocationExtensionEnabled ? 1 : 0);
  12381. fprintf(m_File, "Extension,VK_KHR_bind_memory2,%u\n", bindMemory2ExtensionEnabled ? 1 : 0);
  12382. fprintf(m_File, "Extension,VK_EXT_memory_budget,%u\n", memoryBudgetExtensionEnabled ? 1 : 0);
  12383. fprintf(m_File, "Macro,VMA_DEBUG_ALWAYS_DEDICATED_MEMORY,%u\n", VMA_DEBUG_ALWAYS_DEDICATED_MEMORY ? 1 : 0);
  12384. fprintf(m_File, "Macro,VMA_DEBUG_ALIGNMENT,%llu\n", (VkDeviceSize)VMA_DEBUG_ALIGNMENT);
  12385. fprintf(m_File, "Macro,VMA_DEBUG_MARGIN,%llu\n", (VkDeviceSize)VMA_DEBUG_MARGIN);
  12386. fprintf(m_File, "Macro,VMA_DEBUG_INITIALIZE_ALLOCATIONS,%u\n", VMA_DEBUG_INITIALIZE_ALLOCATIONS ? 1 : 0);
  12387. fprintf(m_File, "Macro,VMA_DEBUG_DETECT_CORRUPTION,%u\n", VMA_DEBUG_DETECT_CORRUPTION ? 1 : 0);
  12388. fprintf(m_File, "Macro,VMA_DEBUG_GLOBAL_MUTEX,%u\n", VMA_DEBUG_GLOBAL_MUTEX ? 1 : 0);
  12389. fprintf(m_File, "Macro,VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY,%llu\n", (VkDeviceSize)VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY);
  12390. fprintf(m_File, "Macro,VMA_SMALL_HEAP_MAX_SIZE,%llu\n", (VkDeviceSize)VMA_SMALL_HEAP_MAX_SIZE);
  12391. fprintf(m_File, "Macro,VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE,%llu\n", (VkDeviceSize)VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE);
  12392. fprintf(m_File, "Config,End\n");
  12393. }
  12394. void VmaRecorder::GetBasicParams(CallParams& outParams)
  12395. {
  12396. outParams.threadId = GetCurrentThreadId();
  12397. LARGE_INTEGER counter;
  12398. QueryPerformanceCounter(&counter);
  12399. outParams.time = (double)(counter.QuadPart - m_StartCounter) / (double)m_Freq;
  12400. }
  12401. void VmaRecorder::PrintPointerList(uint64_t count, const VmaAllocation* pItems)
  12402. {
  12403. if(count)
  12404. {
  12405. fprintf(m_File, "%p", pItems[0]);
  12406. for(uint64_t i = 1; i < count; ++i)
  12407. {
  12408. fprintf(m_File, " %p", pItems[i]);
  12409. }
  12410. }
  12411. }
  12412. void VmaRecorder::Flush()
  12413. {
  12414. if((m_Flags & VMA_RECORD_FLUSH_AFTER_CALL_BIT) != 0)
  12415. {
  12416. fflush(m_File);
  12417. }
  12418. }
  12419. #endif // #if VMA_RECORDING_ENABLED
  12420. ////////////////////////////////////////////////////////////////////////////////
  12421. // VmaAllocationObjectAllocator
  12422. VmaAllocationObjectAllocator::VmaAllocationObjectAllocator(const VkAllocationCallbacks* pAllocationCallbacks) :
  12423. m_Allocator(pAllocationCallbacks, 1024)
  12424. {
  12425. }
  12426. VmaAllocation VmaAllocationObjectAllocator::Allocate()
  12427. {
  12428. VmaMutexLock mutexLock(m_Mutex);
  12429. return m_Allocator.Alloc();
  12430. }
  12431. void VmaAllocationObjectAllocator::Free(VmaAllocation hAlloc)
  12432. {
  12433. VmaMutexLock mutexLock(m_Mutex);
  12434. m_Allocator.Free(hAlloc);
  12435. }
  12436. ////////////////////////////////////////////////////////////////////////////////
  12437. // VmaAllocator_T
  12438. VmaAllocator_T::VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo) :
  12439. m_UseMutex((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT) == 0),
  12440. m_VulkanApiVersion(pCreateInfo->vulkanApiVersion != 0 ? pCreateInfo->vulkanApiVersion : VK_API_VERSION_1_0),
  12441. m_UseKhrDedicatedAllocation((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0),
  12442. m_UseKhrBindMemory2((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT) != 0),
  12443. m_UseExtMemoryBudget((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT) != 0),
  12444. m_hDevice(pCreateInfo->device),
  12445. m_hInstance(pCreateInfo->instance),
  12446. m_AllocationCallbacksSpecified(pCreateInfo->pAllocationCallbacks != VMA_NULL),
  12447. m_AllocationCallbacks(pCreateInfo->pAllocationCallbacks ?
  12448. *pCreateInfo->pAllocationCallbacks : VmaEmptyAllocationCallbacks),
  12449. m_AllocationObjectAllocator(&m_AllocationCallbacks),
  12450. m_HeapSizeLimitMask(0),
  12451. m_PreferredLargeHeapBlockSize(0),
  12452. m_PhysicalDevice(pCreateInfo->physicalDevice),
  12453. m_CurrentFrameIndex(0),
  12454. m_GpuDefragmentationMemoryTypeBits(UINT32_MAX),
  12455. m_Pools(VmaStlAllocator<VmaPool>(GetAllocationCallbacks())),
  12456. m_NextPoolId(0)
  12457. #if VMA_RECORDING_ENABLED
  12458. ,m_pRecorder(VMA_NULL)
  12459. #endif
  12460. {
  12461. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12462. {
  12463. m_UseKhrDedicatedAllocation = false;
  12464. m_UseKhrBindMemory2 = false;
  12465. }
  12466. if(VMA_DEBUG_DETECT_CORRUPTION)
  12467. {
  12468. // Needs to be multiply of uint32_t size because we are going to write VMA_CORRUPTION_DETECTION_MAGIC_VALUE to it.
  12469. VMA_ASSERT(VMA_DEBUG_MARGIN % sizeof(uint32_t) == 0);
  12470. }
  12471. VMA_ASSERT(pCreateInfo->physicalDevice && pCreateInfo->device);
  12472. if(m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0))
  12473. {
  12474. #if !(VMA_DEDICATED_ALLOCATION)
  12475. if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0)
  12476. {
  12477. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT set but required extensions are disabled by preprocessor macros.");
  12478. }
  12479. #endif
  12480. #if !(VMA_BIND_MEMORY2)
  12481. if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT) != 0)
  12482. {
  12483. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT set but required extension is disabled by preprocessor macros.");
  12484. }
  12485. #endif
  12486. }
  12487. #if !(VMA_MEMORY_BUDGET)
  12488. if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT) != 0)
  12489. {
  12490. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT set but required extension is disabled by preprocessor macros.");
  12491. }
  12492. #endif
  12493. #if VMA_VULKAN_VERSION < 1001000
  12494. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12495. {
  12496. VMA_ASSERT(0 && "vulkanApiVersion >= VK_API_VERSION_1_1 but required Vulkan version is disabled by preprocessor macros.");
  12497. }
  12498. #endif
  12499. memset(&m_DeviceMemoryCallbacks, 0 ,sizeof(m_DeviceMemoryCallbacks));
  12500. memset(&m_PhysicalDeviceProperties, 0, sizeof(m_PhysicalDeviceProperties));
  12501. memset(&m_MemProps, 0, sizeof(m_MemProps));
  12502. memset(&m_pBlockVectors, 0, sizeof(m_pBlockVectors));
  12503. memset(&m_pDedicatedAllocations, 0, sizeof(m_pDedicatedAllocations));
  12504. memset(&m_VulkanFunctions, 0, sizeof(m_VulkanFunctions));
  12505. if(pCreateInfo->pDeviceMemoryCallbacks != VMA_NULL)
  12506. {
  12507. m_DeviceMemoryCallbacks.pfnAllocate = pCreateInfo->pDeviceMemoryCallbacks->pfnAllocate;
  12508. m_DeviceMemoryCallbacks.pfnFree = pCreateInfo->pDeviceMemoryCallbacks->pfnFree;
  12509. }
  12510. ImportVulkanFunctions(pCreateInfo->pVulkanFunctions);
  12511. (*m_VulkanFunctions.vkGetPhysicalDeviceProperties)(m_PhysicalDevice, &m_PhysicalDeviceProperties);
  12512. (*m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties)(m_PhysicalDevice, &m_MemProps);
  12513. VMA_ASSERT(VmaIsPow2(VMA_DEBUG_ALIGNMENT));
  12514. VMA_ASSERT(VmaIsPow2(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY));
  12515. VMA_ASSERT(VmaIsPow2(m_PhysicalDeviceProperties.limits.bufferImageGranularity));
  12516. VMA_ASSERT(VmaIsPow2(m_PhysicalDeviceProperties.limits.nonCoherentAtomSize));
  12517. m_PreferredLargeHeapBlockSize = (pCreateInfo->preferredLargeHeapBlockSize != 0) ?
  12518. pCreateInfo->preferredLargeHeapBlockSize : static_cast<VkDeviceSize>(VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE);
  12519. if(pCreateInfo->pHeapSizeLimit != VMA_NULL)
  12520. {
  12521. for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex)
  12522. {
  12523. const VkDeviceSize limit = pCreateInfo->pHeapSizeLimit[heapIndex];
  12524. if(limit != VK_WHOLE_SIZE)
  12525. {
  12526. m_HeapSizeLimitMask |= 1u << heapIndex;
  12527. if(limit < m_MemProps.memoryHeaps[heapIndex].size)
  12528. {
  12529. m_MemProps.memoryHeaps[heapIndex].size = limit;
  12530. }
  12531. }
  12532. }
  12533. }
  12534. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  12535. {
  12536. const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(memTypeIndex);
  12537. m_pBlockVectors[memTypeIndex] = vma_new(this, VmaBlockVector)(
  12538. this,
  12539. VK_NULL_HANDLE, // hParentPool
  12540. memTypeIndex,
  12541. preferredBlockSize,
  12542. 0,
  12543. SIZE_MAX,
  12544. GetBufferImageGranularity(),
  12545. pCreateInfo->frameInUseCount,
  12546. false, // explicitBlockSize
  12547. false); // linearAlgorithm
  12548. // No need to call m_pBlockVectors[memTypeIndex][blockVectorTypeIndex]->CreateMinBlocks here,
  12549. // becase minBlockCount is 0.
  12550. m_pDedicatedAllocations[memTypeIndex] = vma_new(this, AllocationVectorType)(VmaStlAllocator<VmaAllocation>(GetAllocationCallbacks()));
  12551. }
  12552. }
  12553. VkResult VmaAllocator_T::Init(const VmaAllocatorCreateInfo* pCreateInfo)
  12554. {
  12555. VkResult res = VK_SUCCESS;
  12556. if(pCreateInfo->pRecordSettings != VMA_NULL &&
  12557. !VmaStrIsEmpty(pCreateInfo->pRecordSettings->pFilePath))
  12558. {
  12559. #if VMA_RECORDING_ENABLED
  12560. m_pRecorder = vma_new(this, VmaRecorder)();
  12561. res = m_pRecorder->Init(*pCreateInfo->pRecordSettings, m_UseMutex);
  12562. if(res != VK_SUCCESS)
  12563. {
  12564. return res;
  12565. }
  12566. m_pRecorder->WriteConfiguration(
  12567. m_PhysicalDeviceProperties,
  12568. m_MemProps,
  12569. m_VulkanApiVersion,
  12570. m_UseKhrDedicatedAllocation,
  12571. m_UseKhrBindMemory2,
  12572. m_UseExtMemoryBudget);
  12573. m_pRecorder->RecordCreateAllocator(GetCurrentFrameIndex());
  12574. #else
  12575. VMA_ASSERT(0 && "VmaAllocatorCreateInfo::pRecordSettings used, but not supported due to VMA_RECORDING_ENABLED not defined to 1.");
  12576. return VK_ERROR_FEATURE_NOT_PRESENT;
  12577. #endif
  12578. }
  12579. #if VMA_MEMORY_BUDGET
  12580. if(m_UseExtMemoryBudget)
  12581. {
  12582. UpdateVulkanBudget();
  12583. }
  12584. #endif // #if VMA_MEMORY_BUDGET
  12585. return res;
  12586. }
  12587. VmaAllocator_T::~VmaAllocator_T()
  12588. {
  12589. #if VMA_RECORDING_ENABLED
  12590. if(m_pRecorder != VMA_NULL)
  12591. {
  12592. m_pRecorder->RecordDestroyAllocator(GetCurrentFrameIndex());
  12593. vma_delete(this, m_pRecorder);
  12594. }
  12595. #endif
  12596. VMA_ASSERT(m_Pools.empty());
  12597. for(size_t i = GetMemoryTypeCount(); i--; )
  12598. {
  12599. if(m_pDedicatedAllocations[i] != VMA_NULL && !m_pDedicatedAllocations[i]->empty())
  12600. {
  12601. VMA_ASSERT(0 && "Unfreed dedicated allocations found.");
  12602. }
  12603. vma_delete(this, m_pDedicatedAllocations[i]);
  12604. vma_delete(this, m_pBlockVectors[i]);
  12605. }
  12606. }
  12607. void VmaAllocator_T::ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions)
  12608. {
  12609. #if VMA_STATIC_VULKAN_FUNCTIONS == 1
  12610. m_VulkanFunctions.vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)vkGetPhysicalDeviceProperties;
  12611. m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)vkGetPhysicalDeviceMemoryProperties;
  12612. m_VulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkAllocateMemory;
  12613. m_VulkanFunctions.vkFreeMemory = (PFN_vkFreeMemory)vkFreeMemory;
  12614. m_VulkanFunctions.vkMapMemory = (PFN_vkMapMemory)vkMapMemory;
  12615. m_VulkanFunctions.vkUnmapMemory = (PFN_vkUnmapMemory)vkUnmapMemory;
  12616. m_VulkanFunctions.vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)vkFlushMappedMemoryRanges;
  12617. m_VulkanFunctions.vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)vkInvalidateMappedMemoryRanges;
  12618. m_VulkanFunctions.vkBindBufferMemory = (PFN_vkBindBufferMemory)vkBindBufferMemory;
  12619. m_VulkanFunctions.vkBindImageMemory = (PFN_vkBindImageMemory)vkBindImageMemory;
  12620. m_VulkanFunctions.vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)vkGetBufferMemoryRequirements;
  12621. m_VulkanFunctions.vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)vkGetImageMemoryRequirements;
  12622. m_VulkanFunctions.vkCreateBuffer = (PFN_vkCreateBuffer)vkCreateBuffer;
  12623. m_VulkanFunctions.vkDestroyBuffer = (PFN_vkDestroyBuffer)vkDestroyBuffer;
  12624. m_VulkanFunctions.vkCreateImage = (PFN_vkCreateImage)vkCreateImage;
  12625. m_VulkanFunctions.vkDestroyImage = (PFN_vkDestroyImage)vkDestroyImage;
  12626. m_VulkanFunctions.vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)vkCmdCopyBuffer;
  12627. #if VMA_VULKAN_VERSION >= 1001000
  12628. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12629. {
  12630. VMA_ASSERT(m_hInstance != VK_NULL_HANDLE);
  12631. m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR =
  12632. (PFN_vkGetBufferMemoryRequirements2KHR)vkGetDeviceProcAddr(m_hDevice, "vkGetBufferMemoryRequirements2");
  12633. m_VulkanFunctions.vkGetImageMemoryRequirements2KHR =
  12634. (PFN_vkGetImageMemoryRequirements2KHR)vkGetDeviceProcAddr(m_hDevice, "vkGetImageMemoryRequirements2");
  12635. m_VulkanFunctions.vkBindBufferMemory2KHR =
  12636. (PFN_vkBindBufferMemory2KHR)vkGetDeviceProcAddr(m_hDevice, "vkBindBufferMemory2");
  12637. m_VulkanFunctions.vkBindImageMemory2KHR =
  12638. (PFN_vkBindImageMemory2KHR)vkGetDeviceProcAddr(m_hDevice, "vkBindImageMemory2");
  12639. m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR =
  12640. (PFN_vkGetPhysicalDeviceMemoryProperties2KHR)vkGetInstanceProcAddr(m_hInstance, "vkGetPhysicalDeviceMemoryProperties2");
  12641. }
  12642. #endif
  12643. #if VMA_DEDICATED_ALLOCATION
  12644. if(m_UseKhrDedicatedAllocation)
  12645. {
  12646. m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR =
  12647. (PFN_vkGetBufferMemoryRequirements2KHR)vkGetDeviceProcAddr(m_hDevice, "vkGetBufferMemoryRequirements2KHR");
  12648. m_VulkanFunctions.vkGetImageMemoryRequirements2KHR =
  12649. (PFN_vkGetImageMemoryRequirements2KHR)vkGetDeviceProcAddr(m_hDevice, "vkGetImageMemoryRequirements2KHR");
  12650. }
  12651. #endif
  12652. #if VMA_BIND_MEMORY2
  12653. if(m_UseKhrBindMemory2)
  12654. {
  12655. m_VulkanFunctions.vkBindBufferMemory2KHR =
  12656. (PFN_vkBindBufferMemory2KHR)vkGetDeviceProcAddr(m_hDevice, "vkBindBufferMemory2KHR");
  12657. m_VulkanFunctions.vkBindImageMemory2KHR =
  12658. (PFN_vkBindImageMemory2KHR)vkGetDeviceProcAddr(m_hDevice, "vkBindImageMemory2KHR");
  12659. }
  12660. #endif // #if VMA_BIND_MEMORY2
  12661. #if VMA_MEMORY_BUDGET
  12662. if(m_UseExtMemoryBudget && m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0))
  12663. {
  12664. VMA_ASSERT(m_hInstance != VK_NULL_HANDLE);
  12665. m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR =
  12666. (PFN_vkGetPhysicalDeviceMemoryProperties2KHR)vkGetInstanceProcAddr(m_hInstance, "vkGetPhysicalDeviceMemoryProperties2KHR");
  12667. }
  12668. #endif // #if VMA_MEMORY_BUDGET
  12669. #endif // #if VMA_STATIC_VULKAN_FUNCTIONS == 1
  12670. #define VMA_COPY_IF_NOT_NULL(funcName) \
  12671. if(pVulkanFunctions->funcName != VMA_NULL) m_VulkanFunctions.funcName = pVulkanFunctions->funcName;
  12672. if(pVulkanFunctions != VMA_NULL)
  12673. {
  12674. VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceProperties);
  12675. VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties);
  12676. VMA_COPY_IF_NOT_NULL(vkAllocateMemory);
  12677. VMA_COPY_IF_NOT_NULL(vkFreeMemory);
  12678. VMA_COPY_IF_NOT_NULL(vkMapMemory);
  12679. VMA_COPY_IF_NOT_NULL(vkUnmapMemory);
  12680. VMA_COPY_IF_NOT_NULL(vkFlushMappedMemoryRanges);
  12681. VMA_COPY_IF_NOT_NULL(vkInvalidateMappedMemoryRanges);
  12682. VMA_COPY_IF_NOT_NULL(vkBindBufferMemory);
  12683. VMA_COPY_IF_NOT_NULL(vkBindImageMemory);
  12684. VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements);
  12685. VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements);
  12686. VMA_COPY_IF_NOT_NULL(vkCreateBuffer);
  12687. VMA_COPY_IF_NOT_NULL(vkDestroyBuffer);
  12688. VMA_COPY_IF_NOT_NULL(vkCreateImage);
  12689. VMA_COPY_IF_NOT_NULL(vkDestroyImage);
  12690. VMA_COPY_IF_NOT_NULL(vkCmdCopyBuffer);
  12691. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12692. VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements2KHR);
  12693. VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements2KHR);
  12694. #endif
  12695. #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000
  12696. VMA_COPY_IF_NOT_NULL(vkBindBufferMemory2KHR);
  12697. VMA_COPY_IF_NOT_NULL(vkBindImageMemory2KHR);
  12698. #endif
  12699. #if VMA_MEMORY_BUDGET
  12700. VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties2KHR);
  12701. #endif
  12702. }
  12703. #undef VMA_COPY_IF_NOT_NULL
  12704. // If these asserts are hit, you must either #define VMA_STATIC_VULKAN_FUNCTIONS 1
  12705. // or pass valid pointers as VmaAllocatorCreateInfo::pVulkanFunctions.
  12706. VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceProperties != VMA_NULL);
  12707. VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties != VMA_NULL);
  12708. VMA_ASSERT(m_VulkanFunctions.vkAllocateMemory != VMA_NULL);
  12709. VMA_ASSERT(m_VulkanFunctions.vkFreeMemory != VMA_NULL);
  12710. VMA_ASSERT(m_VulkanFunctions.vkMapMemory != VMA_NULL);
  12711. VMA_ASSERT(m_VulkanFunctions.vkUnmapMemory != VMA_NULL);
  12712. VMA_ASSERT(m_VulkanFunctions.vkFlushMappedMemoryRanges != VMA_NULL);
  12713. VMA_ASSERT(m_VulkanFunctions.vkInvalidateMappedMemoryRanges != VMA_NULL);
  12714. VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory != VMA_NULL);
  12715. VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory != VMA_NULL);
  12716. VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements != VMA_NULL);
  12717. VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements != VMA_NULL);
  12718. VMA_ASSERT(m_VulkanFunctions.vkCreateBuffer != VMA_NULL);
  12719. VMA_ASSERT(m_VulkanFunctions.vkDestroyBuffer != VMA_NULL);
  12720. VMA_ASSERT(m_VulkanFunctions.vkCreateImage != VMA_NULL);
  12721. VMA_ASSERT(m_VulkanFunctions.vkDestroyImage != VMA_NULL);
  12722. VMA_ASSERT(m_VulkanFunctions.vkCmdCopyBuffer != VMA_NULL);
  12723. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12724. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0) || m_UseKhrDedicatedAllocation)
  12725. {
  12726. VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR != VMA_NULL);
  12727. VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements2KHR != VMA_NULL);
  12728. }
  12729. #endif
  12730. #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000
  12731. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0) || m_UseKhrBindMemory2)
  12732. {
  12733. VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory2KHR != VMA_NULL);
  12734. VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory2KHR != VMA_NULL);
  12735. }
  12736. #endif
  12737. #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000
  12738. if(m_UseExtMemoryBudget || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12739. {
  12740. VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR != VMA_NULL);
  12741. }
  12742. #endif
  12743. }
  12744. VkDeviceSize VmaAllocator_T::CalcPreferredBlockSize(uint32_t memTypeIndex)
  12745. {
  12746. const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex);
  12747. const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size;
  12748. const bool isSmallHeap = heapSize <= VMA_SMALL_HEAP_MAX_SIZE;
  12749. return VmaAlignUp(isSmallHeap ? (heapSize / 8) : m_PreferredLargeHeapBlockSize, (VkDeviceSize)32);
  12750. }
  12751. VkResult VmaAllocator_T::AllocateMemoryOfType(
  12752. VkDeviceSize size,
  12753. VkDeviceSize alignment,
  12754. bool dedicatedAllocation,
  12755. VkBuffer dedicatedBuffer,
  12756. VkImage dedicatedImage,
  12757. const VmaAllocationCreateInfo& createInfo,
  12758. uint32_t memTypeIndex,
  12759. VmaSuballocationType suballocType,
  12760. size_t allocationCount,
  12761. VmaAllocation* pAllocations)
  12762. {
  12763. VMA_ASSERT(pAllocations != VMA_NULL);
  12764. VMA_DEBUG_LOG(" AllocateMemory: MemoryTypeIndex=%u, AllocationCount=%zu, Size=%llu", memTypeIndex, allocationCount, size);
  12765. VmaAllocationCreateInfo finalCreateInfo = createInfo;
  12766. // If memory type is not HOST_VISIBLE, disable MAPPED.
  12767. if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 &&
  12768. (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  12769. {
  12770. finalCreateInfo.flags &= ~VMA_ALLOCATION_CREATE_MAPPED_BIT;
  12771. }
  12772. // If memory is lazily allocated, it should be always dedicated.
  12773. if(finalCreateInfo.usage == VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED)
  12774. {
  12775. finalCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  12776. }
  12777. VmaBlockVector* const blockVector = m_pBlockVectors[memTypeIndex];
  12778. VMA_ASSERT(blockVector);
  12779. const VkDeviceSize preferredBlockSize = blockVector->GetPreferredBlockSize();
  12780. bool preferDedicatedMemory =
  12781. VMA_DEBUG_ALWAYS_DEDICATED_MEMORY ||
  12782. dedicatedAllocation ||
  12783. // Heuristics: Allocate dedicated memory if requested size if greater than half of preferred block size.
  12784. size > preferredBlockSize / 2;
  12785. if(preferDedicatedMemory &&
  12786. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0 &&
  12787. finalCreateInfo.pool == VK_NULL_HANDLE)
  12788. {
  12789. finalCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  12790. }
  12791. if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0)
  12792. {
  12793. if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
  12794. {
  12795. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  12796. }
  12797. else
  12798. {
  12799. return AllocateDedicatedMemory(
  12800. size,
  12801. suballocType,
  12802. memTypeIndex,
  12803. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT) != 0,
  12804. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0,
  12805. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0,
  12806. finalCreateInfo.pUserData,
  12807. dedicatedBuffer,
  12808. dedicatedImage,
  12809. allocationCount,
  12810. pAllocations);
  12811. }
  12812. }
  12813. else
  12814. {
  12815. VkResult res = blockVector->Allocate(
  12816. m_CurrentFrameIndex.load(),
  12817. size,
  12818. alignment,
  12819. finalCreateInfo,
  12820. suballocType,
  12821. allocationCount,
  12822. pAllocations);
  12823. if(res == VK_SUCCESS)
  12824. {
  12825. return res;
  12826. }
  12827. // 5. Try dedicated memory.
  12828. if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
  12829. {
  12830. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  12831. }
  12832. else
  12833. {
  12834. res = AllocateDedicatedMemory(
  12835. size,
  12836. suballocType,
  12837. memTypeIndex,
  12838. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT) != 0,
  12839. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0,
  12840. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0,
  12841. finalCreateInfo.pUserData,
  12842. dedicatedBuffer,
  12843. dedicatedImage,
  12844. allocationCount,
  12845. pAllocations);
  12846. if(res == VK_SUCCESS)
  12847. {
  12848. // Succeeded: AllocateDedicatedMemory function already filld pMemory, nothing more to do here.
  12849. VMA_DEBUG_LOG(" Allocated as DedicatedMemory");
  12850. return VK_SUCCESS;
  12851. }
  12852. else
  12853. {
  12854. // Everything failed: Return error code.
  12855. VMA_DEBUG_LOG(" vkAllocateMemory FAILED");
  12856. return res;
  12857. }
  12858. }
  12859. }
  12860. }
  12861. VkResult VmaAllocator_T::AllocateDedicatedMemory(
  12862. VkDeviceSize size,
  12863. VmaSuballocationType suballocType,
  12864. uint32_t memTypeIndex,
  12865. bool withinBudget,
  12866. bool map,
  12867. bool isUserDataString,
  12868. void* pUserData,
  12869. VkBuffer dedicatedBuffer,
  12870. VkImage dedicatedImage,
  12871. size_t allocationCount,
  12872. VmaAllocation* pAllocations)
  12873. {
  12874. VMA_ASSERT(allocationCount > 0 && pAllocations);
  12875. if(withinBudget)
  12876. {
  12877. const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex);
  12878. VmaBudget heapBudget = {};
  12879. GetBudget(&heapBudget, heapIndex, 1);
  12880. if(heapBudget.usage + size * allocationCount > heapBudget.budget)
  12881. {
  12882. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  12883. }
  12884. }
  12885. VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
  12886. allocInfo.memoryTypeIndex = memTypeIndex;
  12887. allocInfo.allocationSize = size;
  12888. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12889. VkMemoryDedicatedAllocateInfoKHR dedicatedAllocInfo = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR };
  12890. if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12891. {
  12892. if(dedicatedBuffer != VK_NULL_HANDLE)
  12893. {
  12894. VMA_ASSERT(dedicatedImage == VK_NULL_HANDLE);
  12895. dedicatedAllocInfo.buffer = dedicatedBuffer;
  12896. allocInfo.pNext = &dedicatedAllocInfo;
  12897. }
  12898. else if(dedicatedImage != VK_NULL_HANDLE)
  12899. {
  12900. dedicatedAllocInfo.image = dedicatedImage;
  12901. allocInfo.pNext = &dedicatedAllocInfo;
  12902. }
  12903. }
  12904. #endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12905. size_t allocIndex;
  12906. VkResult res = VK_SUCCESS;
  12907. for(allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  12908. {
  12909. res = AllocateDedicatedMemoryPage(
  12910. size,
  12911. suballocType,
  12912. memTypeIndex,
  12913. allocInfo,
  12914. map,
  12915. isUserDataString,
  12916. pUserData,
  12917. pAllocations + allocIndex);
  12918. if(res != VK_SUCCESS)
  12919. {
  12920. break;
  12921. }
  12922. }
  12923. if(res == VK_SUCCESS)
  12924. {
  12925. // Register them in m_pDedicatedAllocations.
  12926. {
  12927. VmaMutexLockWrite lock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
  12928. AllocationVectorType* pDedicatedAllocations = m_pDedicatedAllocations[memTypeIndex];
  12929. VMA_ASSERT(pDedicatedAllocations);
  12930. for(allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  12931. {
  12932. VmaVectorInsertSorted<VmaPointerLess>(*pDedicatedAllocations, pAllocations[allocIndex]);
  12933. }
  12934. }
  12935. VMA_DEBUG_LOG(" Allocated DedicatedMemory Count=%zu, MemoryTypeIndex=#%u", allocationCount, memTypeIndex);
  12936. }
  12937. else
  12938. {
  12939. // Free all already created allocations.
  12940. while(allocIndex--)
  12941. {
  12942. VmaAllocation currAlloc = pAllocations[allocIndex];
  12943. VkDeviceMemory hMemory = currAlloc->GetMemory();
  12944. /*
  12945. There is no need to call this, because Vulkan spec allows to skip vkUnmapMemory
  12946. before vkFreeMemory.
  12947. if(currAlloc->GetMappedData() != VMA_NULL)
  12948. {
  12949. (*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory);
  12950. }
  12951. */
  12952. FreeVulkanMemory(memTypeIndex, currAlloc->GetSize(), hMemory);
  12953. m_Budget.RemoveAllocation(MemoryTypeIndexToHeapIndex(memTypeIndex), currAlloc->GetSize());
  12954. currAlloc->SetUserData(this, VMA_NULL);
  12955. currAlloc->Dtor();
  12956. m_AllocationObjectAllocator.Free(currAlloc);
  12957. }
  12958. memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount);
  12959. }
  12960. return res;
  12961. }
  12962. VkResult VmaAllocator_T::AllocateDedicatedMemoryPage(
  12963. VkDeviceSize size,
  12964. VmaSuballocationType suballocType,
  12965. uint32_t memTypeIndex,
  12966. const VkMemoryAllocateInfo& allocInfo,
  12967. bool map,
  12968. bool isUserDataString,
  12969. void* pUserData,
  12970. VmaAllocation* pAllocation)
  12971. {
  12972. VkDeviceMemory hMemory = VK_NULL_HANDLE;
  12973. VkResult res = AllocateVulkanMemory(&allocInfo, &hMemory);
  12974. if(res < 0)
  12975. {
  12976. VMA_DEBUG_LOG(" vkAllocateMemory FAILED");
  12977. return res;
  12978. }
  12979. void* pMappedData = VMA_NULL;
  12980. if(map)
  12981. {
  12982. res = (*m_VulkanFunctions.vkMapMemory)(
  12983. m_hDevice,
  12984. hMemory,
  12985. 0,
  12986. VK_WHOLE_SIZE,
  12987. 0,
  12988. &pMappedData);
  12989. if(res < 0)
  12990. {
  12991. VMA_DEBUG_LOG(" vkMapMemory FAILED");
  12992. FreeVulkanMemory(memTypeIndex, size, hMemory);
  12993. return res;
  12994. }
  12995. }
  12996. *pAllocation = m_AllocationObjectAllocator.Allocate();
  12997. (*pAllocation)->Ctor(m_CurrentFrameIndex.load(), isUserDataString);
  12998. (*pAllocation)->InitDedicatedAllocation(memTypeIndex, hMemory, suballocType, pMappedData, size);
  12999. (*pAllocation)->SetUserData(this, pUserData);
  13000. m_Budget.AddAllocation(MemoryTypeIndexToHeapIndex(memTypeIndex), size);
  13001. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
  13002. {
  13003. FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED);
  13004. }
  13005. return VK_SUCCESS;
  13006. }
  13007. void VmaAllocator_T::GetBufferMemoryRequirements(
  13008. VkBuffer hBuffer,
  13009. VkMemoryRequirements& memReq,
  13010. bool& requiresDedicatedAllocation,
  13011. bool& prefersDedicatedAllocation) const
  13012. {
  13013. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  13014. if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  13015. {
  13016. VkBufferMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR };
  13017. memReqInfo.buffer = hBuffer;
  13018. VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR };
  13019. VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR };
  13020. memReq2.pNext = &memDedicatedReq;
  13021. (*m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2);
  13022. memReq = memReq2.memoryRequirements;
  13023. requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE);
  13024. prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE);
  13025. }
  13026. else
  13027. #endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  13028. {
  13029. (*m_VulkanFunctions.vkGetBufferMemoryRequirements)(m_hDevice, hBuffer, &memReq);
  13030. requiresDedicatedAllocation = false;
  13031. prefersDedicatedAllocation = false;
  13032. }
  13033. }
  13034. void VmaAllocator_T::GetImageMemoryRequirements(
  13035. VkImage hImage,
  13036. VkMemoryRequirements& memReq,
  13037. bool& requiresDedicatedAllocation,
  13038. bool& prefersDedicatedAllocation) const
  13039. {
  13040. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  13041. if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  13042. {
  13043. VkImageMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR };
  13044. memReqInfo.image = hImage;
  13045. VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR };
  13046. VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR };
  13047. memReq2.pNext = &memDedicatedReq;
  13048. (*m_VulkanFunctions.vkGetImageMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2);
  13049. memReq = memReq2.memoryRequirements;
  13050. requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE);
  13051. prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE);
  13052. }
  13053. else
  13054. #endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  13055. {
  13056. (*m_VulkanFunctions.vkGetImageMemoryRequirements)(m_hDevice, hImage, &memReq);
  13057. requiresDedicatedAllocation = false;
  13058. prefersDedicatedAllocation = false;
  13059. }
  13060. }
  13061. VkResult VmaAllocator_T::AllocateMemory(
  13062. const VkMemoryRequirements& vkMemReq,
  13063. bool requiresDedicatedAllocation,
  13064. bool prefersDedicatedAllocation,
  13065. VkBuffer dedicatedBuffer,
  13066. VkImage dedicatedImage,
  13067. const VmaAllocationCreateInfo& createInfo,
  13068. VmaSuballocationType suballocType,
  13069. size_t allocationCount,
  13070. VmaAllocation* pAllocations)
  13071. {
  13072. memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount);
  13073. VMA_ASSERT(VmaIsPow2(vkMemReq.alignment));
  13074. if(vkMemReq.size == 0)
  13075. {
  13076. return VK_ERROR_VALIDATION_FAILED_EXT;
  13077. }
  13078. if((createInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0 &&
  13079. (createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
  13080. {
  13081. VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT together with VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT makes no sense.");
  13082. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  13083. }
  13084. if((createInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 &&
  13085. (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0)
  13086. {
  13087. VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_MAPPED_BIT together with VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT is invalid.");
  13088. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  13089. }
  13090. if(requiresDedicatedAllocation)
  13091. {
  13092. if((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
  13093. {
  13094. VMA_ASSERT(0 && "VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT specified while dedicated allocation is required.");
  13095. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  13096. }
  13097. if(createInfo.pool != VK_NULL_HANDLE)
  13098. {
  13099. VMA_ASSERT(0 && "Pool specified while dedicated allocation is required.");
  13100. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  13101. }
  13102. }
  13103. if((createInfo.pool != VK_NULL_HANDLE) &&
  13104. ((createInfo.flags & (VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT)) != 0))
  13105. {
  13106. VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT when pool != null is invalid.");
  13107. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  13108. }
  13109. if(createInfo.pool != VK_NULL_HANDLE)
  13110. {
  13111. const VkDeviceSize alignmentForPool = VMA_MAX(
  13112. vkMemReq.alignment,
  13113. GetMemoryTypeMinAlignment(createInfo.pool->m_BlockVector.GetMemoryTypeIndex()));
  13114. VmaAllocationCreateInfo createInfoForPool = createInfo;
  13115. // If memory type is not HOST_VISIBLE, disable MAPPED.
  13116. if((createInfoForPool.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 &&
  13117. (m_MemProps.memoryTypes[createInfo.pool->m_BlockVector.GetMemoryTypeIndex()].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  13118. {
  13119. createInfoForPool.flags &= ~VMA_ALLOCATION_CREATE_MAPPED_BIT;
  13120. }
  13121. return createInfo.pool->m_BlockVector.Allocate(
  13122. m_CurrentFrameIndex.load(),
  13123. vkMemReq.size,
  13124. alignmentForPool,
  13125. createInfoForPool,
  13126. suballocType,
  13127. allocationCount,
  13128. pAllocations);
  13129. }
  13130. else
  13131. {
  13132. // Bit mask of memory Vulkan types acceptable for this allocation.
  13133. uint32_t memoryTypeBits = vkMemReq.memoryTypeBits;
  13134. uint32_t memTypeIndex = UINT32_MAX;
  13135. VkResult res = vmaFindMemoryTypeIndex(this, memoryTypeBits, &createInfo, &memTypeIndex);
  13136. if(res == VK_SUCCESS)
  13137. {
  13138. VkDeviceSize alignmentForMemType = VMA_MAX(
  13139. vkMemReq.alignment,
  13140. GetMemoryTypeMinAlignment(memTypeIndex));
  13141. res = AllocateMemoryOfType(
  13142. vkMemReq.size,
  13143. alignmentForMemType,
  13144. requiresDedicatedAllocation || prefersDedicatedAllocation,
  13145. dedicatedBuffer,
  13146. dedicatedImage,
  13147. createInfo,
  13148. memTypeIndex,
  13149. suballocType,
  13150. allocationCount,
  13151. pAllocations);
  13152. // Succeeded on first try.
  13153. if(res == VK_SUCCESS)
  13154. {
  13155. return res;
  13156. }
  13157. // Allocation from this memory type failed. Try other compatible memory types.
  13158. else
  13159. {
  13160. for(;;)
  13161. {
  13162. // Remove old memTypeIndex from list of possibilities.
  13163. memoryTypeBits &= ~(1u << memTypeIndex);
  13164. // Find alternative memTypeIndex.
  13165. res = vmaFindMemoryTypeIndex(this, memoryTypeBits, &createInfo, &memTypeIndex);
  13166. if(res == VK_SUCCESS)
  13167. {
  13168. alignmentForMemType = VMA_MAX(
  13169. vkMemReq.alignment,
  13170. GetMemoryTypeMinAlignment(memTypeIndex));
  13171. res = AllocateMemoryOfType(
  13172. vkMemReq.size,
  13173. alignmentForMemType,
  13174. requiresDedicatedAllocation || prefersDedicatedAllocation,
  13175. dedicatedBuffer,
  13176. dedicatedImage,
  13177. createInfo,
  13178. memTypeIndex,
  13179. suballocType,
  13180. allocationCount,
  13181. pAllocations);
  13182. // Allocation from this alternative memory type succeeded.
  13183. if(res == VK_SUCCESS)
  13184. {
  13185. return res;
  13186. }
  13187. // else: Allocation from this memory type failed. Try next one - next loop iteration.
  13188. }
  13189. // No other matching memory type index could be found.
  13190. else
  13191. {
  13192. // Not returning res, which is VK_ERROR_FEATURE_NOT_PRESENT, because we already failed to allocate once.
  13193. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  13194. }
  13195. }
  13196. }
  13197. }
  13198. // Can't find any single memory type maching requirements. res is VK_ERROR_FEATURE_NOT_PRESENT.
  13199. else
  13200. return res;
  13201. }
  13202. }
  13203. void VmaAllocator_T::FreeMemory(
  13204. size_t allocationCount,
  13205. const VmaAllocation* pAllocations)
  13206. {
  13207. VMA_ASSERT(pAllocations);
  13208. for(size_t allocIndex = allocationCount; allocIndex--; )
  13209. {
  13210. VmaAllocation allocation = pAllocations[allocIndex];
  13211. if(allocation != VK_NULL_HANDLE)
  13212. {
  13213. if(TouchAllocation(allocation))
  13214. {
  13215. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
  13216. {
  13217. FillAllocation(allocation, VMA_ALLOCATION_FILL_PATTERN_DESTROYED);
  13218. }
  13219. switch(allocation->GetType())
  13220. {
  13221. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13222. {
  13223. VmaBlockVector* pBlockVector = VMA_NULL;
  13224. VmaPool hPool = allocation->GetBlock()->GetParentPool();
  13225. if(hPool != VK_NULL_HANDLE)
  13226. {
  13227. pBlockVector = &hPool->m_BlockVector;
  13228. }
  13229. else
  13230. {
  13231. const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
  13232. pBlockVector = m_pBlockVectors[memTypeIndex];
  13233. }
  13234. pBlockVector->Free(allocation);
  13235. }
  13236. break;
  13237. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13238. FreeDedicatedMemory(allocation);
  13239. break;
  13240. default:
  13241. VMA_ASSERT(0);
  13242. }
  13243. }
  13244. // Do this regardless of whether the allocation is lost. Lost allocations still account to Budget.AllocationBytes.
  13245. m_Budget.RemoveAllocation(MemoryTypeIndexToHeapIndex(allocation->GetMemoryTypeIndex()), allocation->GetSize());
  13246. allocation->SetUserData(this, VMA_NULL);
  13247. allocation->Dtor();
  13248. m_AllocationObjectAllocator.Free(allocation);
  13249. }
  13250. }
  13251. }
  13252. VkResult VmaAllocator_T::ResizeAllocation(
  13253. const VmaAllocation alloc,
  13254. VkDeviceSize newSize)
  13255. {
  13256. // This function is deprecated and so it does nothing. It's left for backward compatibility.
  13257. if(newSize == 0 || alloc->GetLastUseFrameIndex() == VMA_FRAME_INDEX_LOST)
  13258. {
  13259. return VK_ERROR_VALIDATION_FAILED_EXT;
  13260. }
  13261. if(newSize == alloc->GetSize())
  13262. {
  13263. return VK_SUCCESS;
  13264. }
  13265. return VK_ERROR_OUT_OF_POOL_MEMORY;
  13266. }
  13267. void VmaAllocator_T::CalculateStats(VmaStats* pStats)
  13268. {
  13269. // Initialize.
  13270. InitStatInfo(pStats->total);
  13271. for(size_t i = 0; i < VK_MAX_MEMORY_TYPES; ++i)
  13272. InitStatInfo(pStats->memoryType[i]);
  13273. for(size_t i = 0; i < VK_MAX_MEMORY_HEAPS; ++i)
  13274. InitStatInfo(pStats->memoryHeap[i]);
  13275. // Process default pools.
  13276. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13277. {
  13278. VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex];
  13279. VMA_ASSERT(pBlockVector);
  13280. pBlockVector->AddStats(pStats);
  13281. }
  13282. // Process custom pools.
  13283. {
  13284. VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex);
  13285. for(size_t poolIndex = 0, poolCount = m_Pools.size(); poolIndex < poolCount; ++poolIndex)
  13286. {
  13287. m_Pools[poolIndex]->m_BlockVector.AddStats(pStats);
  13288. }
  13289. }
  13290. // Process dedicated allocations.
  13291. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13292. {
  13293. const uint32_t memHeapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex);
  13294. VmaMutexLockRead dedicatedAllocationsLock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
  13295. AllocationVectorType* const pDedicatedAllocVector = m_pDedicatedAllocations[memTypeIndex];
  13296. VMA_ASSERT(pDedicatedAllocVector);
  13297. for(size_t allocIndex = 0, allocCount = pDedicatedAllocVector->size(); allocIndex < allocCount; ++allocIndex)
  13298. {
  13299. VmaStatInfo allocationStatInfo;
  13300. (*pDedicatedAllocVector)[allocIndex]->DedicatedAllocCalcStatsInfo(allocationStatInfo);
  13301. VmaAddStatInfo(pStats->total, allocationStatInfo);
  13302. VmaAddStatInfo(pStats->memoryType[memTypeIndex], allocationStatInfo);
  13303. VmaAddStatInfo(pStats->memoryHeap[memHeapIndex], allocationStatInfo);
  13304. }
  13305. }
  13306. // Postprocess.
  13307. VmaPostprocessCalcStatInfo(pStats->total);
  13308. for(size_t i = 0; i < GetMemoryTypeCount(); ++i)
  13309. VmaPostprocessCalcStatInfo(pStats->memoryType[i]);
  13310. for(size_t i = 0; i < GetMemoryHeapCount(); ++i)
  13311. VmaPostprocessCalcStatInfo(pStats->memoryHeap[i]);
  13312. }
  13313. void VmaAllocator_T::GetBudget(VmaBudget* outBudget, uint32_t firstHeap, uint32_t heapCount)
  13314. {
  13315. #if VMA_MEMORY_BUDGET
  13316. if(m_UseExtMemoryBudget)
  13317. {
  13318. if(m_Budget.m_OperationsSinceBudgetFetch < 30)
  13319. {
  13320. VmaMutexLockRead lockRead(m_Budget.m_BudgetMutex, m_UseMutex);
  13321. for(uint32_t i = 0; i < heapCount; ++i, ++outBudget)
  13322. {
  13323. const uint32_t heapIndex = firstHeap + i;
  13324. outBudget->blockBytes = m_Budget.m_BlockBytes[heapIndex];
  13325. outBudget->allocationBytes = m_Budget.m_AllocationBytes[heapIndex];
  13326. if(m_Budget.m_VulkanUsage[heapIndex] + outBudget->blockBytes > m_Budget.m_BlockBytesAtBudgetFetch[heapIndex])
  13327. {
  13328. outBudget->usage = m_Budget.m_VulkanUsage[heapIndex] +
  13329. outBudget->blockBytes - m_Budget.m_BlockBytesAtBudgetFetch[heapIndex];
  13330. }
  13331. else
  13332. {
  13333. outBudget->usage = 0;
  13334. }
  13335. // Have to take MIN with heap size because explicit HeapSizeLimit is included in it.
  13336. outBudget->budget = VMA_MIN(
  13337. m_Budget.m_VulkanBudget[heapIndex], m_MemProps.memoryHeaps[heapIndex].size);
  13338. }
  13339. }
  13340. else
  13341. {
  13342. UpdateVulkanBudget(); // Outside of mutex lock
  13343. GetBudget(outBudget, firstHeap, heapCount); // Recursion
  13344. }
  13345. }
  13346. else
  13347. #endif
  13348. {
  13349. for(uint32_t i = 0; i < heapCount; ++i, ++outBudget)
  13350. {
  13351. const uint32_t heapIndex = firstHeap + i;
  13352. outBudget->blockBytes = m_Budget.m_BlockBytes[heapIndex];
  13353. outBudget->allocationBytes = m_Budget.m_AllocationBytes[heapIndex];
  13354. outBudget->usage = outBudget->blockBytes;
  13355. outBudget->budget = m_MemProps.memoryHeaps[heapIndex].size * 8 / 10; // 80% heuristics.
  13356. }
  13357. }
  13358. }
  13359. static const uint32_t VMA_VENDOR_ID_AMD = 4098;
  13360. VkResult VmaAllocator_T::DefragmentationBegin(
  13361. const VmaDefragmentationInfo2& info,
  13362. VmaDefragmentationStats* pStats,
  13363. VmaDefragmentationContext* pContext)
  13364. {
  13365. if(info.pAllocationsChanged != VMA_NULL)
  13366. {
  13367. memset(info.pAllocationsChanged, 0, info.allocationCount * sizeof(VkBool32));
  13368. }
  13369. *pContext = vma_new(this, VmaDefragmentationContext_T)(
  13370. this, m_CurrentFrameIndex.load(), info.flags, pStats);
  13371. (*pContext)->AddPools(info.poolCount, info.pPools);
  13372. (*pContext)->AddAllocations(
  13373. info.allocationCount, info.pAllocations, info.pAllocationsChanged);
  13374. VkResult res = (*pContext)->Defragment(
  13375. info.maxCpuBytesToMove, info.maxCpuAllocationsToMove,
  13376. info.maxGpuBytesToMove, info.maxGpuAllocationsToMove,
  13377. info.commandBuffer, pStats);
  13378. if(res != VK_NOT_READY)
  13379. {
  13380. vma_delete(this, *pContext);
  13381. *pContext = VMA_NULL;
  13382. }
  13383. return res;
  13384. }
  13385. VkResult VmaAllocator_T::DefragmentationEnd(
  13386. VmaDefragmentationContext context)
  13387. {
  13388. vma_delete(this, context);
  13389. return VK_SUCCESS;
  13390. }
  13391. void VmaAllocator_T::GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo)
  13392. {
  13393. if(hAllocation->CanBecomeLost())
  13394. {
  13395. /*
  13396. Warning: This is a carefully designed algorithm.
  13397. Do not modify unless you really know what you're doing :)
  13398. */
  13399. const uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load();
  13400. uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex();
  13401. for(;;)
  13402. {
  13403. if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST)
  13404. {
  13405. pAllocationInfo->memoryType = UINT32_MAX;
  13406. pAllocationInfo->deviceMemory = VK_NULL_HANDLE;
  13407. pAllocationInfo->offset = 0;
  13408. pAllocationInfo->size = hAllocation->GetSize();
  13409. pAllocationInfo->pMappedData = VMA_NULL;
  13410. pAllocationInfo->pUserData = hAllocation->GetUserData();
  13411. return;
  13412. }
  13413. else if(localLastUseFrameIndex == localCurrFrameIndex)
  13414. {
  13415. pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex();
  13416. pAllocationInfo->deviceMemory = hAllocation->GetMemory();
  13417. pAllocationInfo->offset = hAllocation->GetOffset();
  13418. pAllocationInfo->size = hAllocation->GetSize();
  13419. pAllocationInfo->pMappedData = VMA_NULL;
  13420. pAllocationInfo->pUserData = hAllocation->GetUserData();
  13421. return;
  13422. }
  13423. else // Last use time earlier than current time.
  13424. {
  13425. if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex))
  13426. {
  13427. localLastUseFrameIndex = localCurrFrameIndex;
  13428. }
  13429. }
  13430. }
  13431. }
  13432. else
  13433. {
  13434. #if VMA_STATS_STRING_ENABLED
  13435. uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load();
  13436. uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex();
  13437. for(;;)
  13438. {
  13439. VMA_ASSERT(localLastUseFrameIndex != VMA_FRAME_INDEX_LOST);
  13440. if(localLastUseFrameIndex == localCurrFrameIndex)
  13441. {
  13442. break;
  13443. }
  13444. else // Last use time earlier than current time.
  13445. {
  13446. if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex))
  13447. {
  13448. localLastUseFrameIndex = localCurrFrameIndex;
  13449. }
  13450. }
  13451. }
  13452. #endif
  13453. pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex();
  13454. pAllocationInfo->deviceMemory = hAllocation->GetMemory();
  13455. pAllocationInfo->offset = hAllocation->GetOffset();
  13456. pAllocationInfo->size = hAllocation->GetSize();
  13457. pAllocationInfo->pMappedData = hAllocation->GetMappedData();
  13458. pAllocationInfo->pUserData = hAllocation->GetUserData();
  13459. }
  13460. }
  13461. bool VmaAllocator_T::TouchAllocation(VmaAllocation hAllocation)
  13462. {
  13463. // This is a stripped-down version of VmaAllocator_T::GetAllocationInfo.
  13464. if(hAllocation->CanBecomeLost())
  13465. {
  13466. uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load();
  13467. uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex();
  13468. for(;;)
  13469. {
  13470. if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST)
  13471. {
  13472. return false;
  13473. }
  13474. else if(localLastUseFrameIndex == localCurrFrameIndex)
  13475. {
  13476. return true;
  13477. }
  13478. else // Last use time earlier than current time.
  13479. {
  13480. if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex))
  13481. {
  13482. localLastUseFrameIndex = localCurrFrameIndex;
  13483. }
  13484. }
  13485. }
  13486. }
  13487. else
  13488. {
  13489. #if VMA_STATS_STRING_ENABLED
  13490. uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load();
  13491. uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex();
  13492. for(;;)
  13493. {
  13494. VMA_ASSERT(localLastUseFrameIndex != VMA_FRAME_INDEX_LOST);
  13495. if(localLastUseFrameIndex == localCurrFrameIndex)
  13496. {
  13497. break;
  13498. }
  13499. else // Last use time earlier than current time.
  13500. {
  13501. if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex))
  13502. {
  13503. localLastUseFrameIndex = localCurrFrameIndex;
  13504. }
  13505. }
  13506. }
  13507. #endif
  13508. return true;
  13509. }
  13510. }
  13511. VkResult VmaAllocator_T::CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool)
  13512. {
  13513. VMA_DEBUG_LOG(" CreatePool: MemoryTypeIndex=%u, flags=%u", pCreateInfo->memoryTypeIndex, pCreateInfo->flags);
  13514. VmaPoolCreateInfo newCreateInfo = *pCreateInfo;
  13515. if(newCreateInfo.maxBlockCount == 0)
  13516. {
  13517. newCreateInfo.maxBlockCount = SIZE_MAX;
  13518. }
  13519. if(newCreateInfo.minBlockCount > newCreateInfo.maxBlockCount)
  13520. {
  13521. return VK_ERROR_INITIALIZATION_FAILED;
  13522. }
  13523. const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(newCreateInfo.memoryTypeIndex);
  13524. *pPool = vma_new(this, VmaPool_T)(this, newCreateInfo, preferredBlockSize);
  13525. VkResult res = (*pPool)->m_BlockVector.CreateMinBlocks();
  13526. if(res != VK_SUCCESS)
  13527. {
  13528. vma_delete(this, *pPool);
  13529. *pPool = VMA_NULL;
  13530. return res;
  13531. }
  13532. // Add to m_Pools.
  13533. {
  13534. VmaMutexLockWrite lock(m_PoolsMutex, m_UseMutex);
  13535. (*pPool)->SetId(m_NextPoolId++);
  13536. VmaVectorInsertSorted<VmaPointerLess>(m_Pools, *pPool);
  13537. }
  13538. return VK_SUCCESS;
  13539. }
  13540. void VmaAllocator_T::DestroyPool(VmaPool pool)
  13541. {
  13542. // Remove from m_Pools.
  13543. {
  13544. VmaMutexLockWrite lock(m_PoolsMutex, m_UseMutex);
  13545. bool success = VmaVectorRemoveSorted<VmaPointerLess>(m_Pools, pool);
  13546. VMA_ASSERT(success && "Pool not found in Allocator.");
  13547. }
  13548. vma_delete(this, pool);
  13549. }
  13550. void VmaAllocator_T::GetPoolStats(VmaPool pool, VmaPoolStats* pPoolStats)
  13551. {
  13552. pool->m_BlockVector.GetPoolStats(pPoolStats);
  13553. }
  13554. void VmaAllocator_T::SetCurrentFrameIndex(uint32_t frameIndex)
  13555. {
  13556. m_CurrentFrameIndex.store(frameIndex);
  13557. #if VMA_MEMORY_BUDGET
  13558. if(m_UseExtMemoryBudget)
  13559. {
  13560. UpdateVulkanBudget();
  13561. }
  13562. #endif // #if VMA_MEMORY_BUDGET
  13563. }
  13564. void VmaAllocator_T::MakePoolAllocationsLost(
  13565. VmaPool hPool,
  13566. size_t* pLostAllocationCount)
  13567. {
  13568. hPool->m_BlockVector.MakePoolAllocationsLost(
  13569. m_CurrentFrameIndex.load(),
  13570. pLostAllocationCount);
  13571. }
  13572. VkResult VmaAllocator_T::CheckPoolCorruption(VmaPool hPool)
  13573. {
  13574. return hPool->m_BlockVector.CheckCorruption();
  13575. }
  13576. VkResult VmaAllocator_T::CheckCorruption(uint32_t memoryTypeBits)
  13577. {
  13578. VkResult finalRes = VK_ERROR_FEATURE_NOT_PRESENT;
  13579. // Process default pools.
  13580. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13581. {
  13582. if(((1u << memTypeIndex) & memoryTypeBits) != 0)
  13583. {
  13584. VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex];
  13585. VMA_ASSERT(pBlockVector);
  13586. VkResult localRes = pBlockVector->CheckCorruption();
  13587. switch(localRes)
  13588. {
  13589. case VK_ERROR_FEATURE_NOT_PRESENT:
  13590. break;
  13591. case VK_SUCCESS:
  13592. finalRes = VK_SUCCESS;
  13593. break;
  13594. default:
  13595. return localRes;
  13596. }
  13597. }
  13598. }
  13599. // Process custom pools.
  13600. {
  13601. VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex);
  13602. for(size_t poolIndex = 0, poolCount = m_Pools.size(); poolIndex < poolCount; ++poolIndex)
  13603. {
  13604. if(((1u << m_Pools[poolIndex]->m_BlockVector.GetMemoryTypeIndex()) & memoryTypeBits) != 0)
  13605. {
  13606. VkResult localRes = m_Pools[poolIndex]->m_BlockVector.CheckCorruption();
  13607. switch(localRes)
  13608. {
  13609. case VK_ERROR_FEATURE_NOT_PRESENT:
  13610. break;
  13611. case VK_SUCCESS:
  13612. finalRes = VK_SUCCESS;
  13613. break;
  13614. default:
  13615. return localRes;
  13616. }
  13617. }
  13618. }
  13619. }
  13620. return finalRes;
  13621. }
  13622. void VmaAllocator_T::CreateLostAllocation(VmaAllocation* pAllocation)
  13623. {
  13624. *pAllocation = m_AllocationObjectAllocator.Allocate();
  13625. (*pAllocation)->Ctor(VMA_FRAME_INDEX_LOST, false);
  13626. (*pAllocation)->InitLost();
  13627. }
  13628. VkResult VmaAllocator_T::AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory)
  13629. {
  13630. const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(pAllocateInfo->memoryTypeIndex);
  13631. // HeapSizeLimit is in effect for this heap.
  13632. if((m_HeapSizeLimitMask & (1u << heapIndex)) != 0)
  13633. {
  13634. const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size;
  13635. VkDeviceSize blockBytes = m_Budget.m_BlockBytes[heapIndex];
  13636. for(;;)
  13637. {
  13638. const VkDeviceSize blockBytesAfterAllocation = blockBytes + pAllocateInfo->allocationSize;
  13639. if(blockBytesAfterAllocation > heapSize)
  13640. {
  13641. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  13642. }
  13643. if(m_Budget.m_BlockBytes[heapIndex].compare_exchange_strong(blockBytes, blockBytesAfterAllocation))
  13644. {
  13645. break;
  13646. }
  13647. }
  13648. }
  13649. else
  13650. {
  13651. m_Budget.m_BlockBytes[heapIndex] += pAllocateInfo->allocationSize;
  13652. }
  13653. // VULKAN CALL vkAllocateMemory.
  13654. VkResult res = (*m_VulkanFunctions.vkAllocateMemory)(m_hDevice, pAllocateInfo, GetAllocationCallbacks(), pMemory);
  13655. if(res == VK_SUCCESS)
  13656. {
  13657. #if VMA_MEMORY_BUDGET
  13658. ++m_Budget.m_OperationsSinceBudgetFetch;
  13659. #endif
  13660. // Informative callback.
  13661. if(m_DeviceMemoryCallbacks.pfnAllocate != VMA_NULL)
  13662. {
  13663. (*m_DeviceMemoryCallbacks.pfnAllocate)(this, pAllocateInfo->memoryTypeIndex, *pMemory, pAllocateInfo->allocationSize);
  13664. }
  13665. }
  13666. else
  13667. {
  13668. m_Budget.m_BlockBytes[heapIndex] -= pAllocateInfo->allocationSize;
  13669. }
  13670. return res;
  13671. }
  13672. void VmaAllocator_T::FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory)
  13673. {
  13674. // Informative callback.
  13675. if(m_DeviceMemoryCallbacks.pfnFree != VMA_NULL)
  13676. {
  13677. (*m_DeviceMemoryCallbacks.pfnFree)(this, memoryType, hMemory, size);
  13678. }
  13679. // VULKAN CALL vkFreeMemory.
  13680. (*m_VulkanFunctions.vkFreeMemory)(m_hDevice, hMemory, GetAllocationCallbacks());
  13681. m_Budget.m_BlockBytes[MemoryTypeIndexToHeapIndex(memoryType)] -= size;
  13682. }
  13683. VkResult VmaAllocator_T::BindVulkanBuffer(
  13684. VkDeviceMemory memory,
  13685. VkDeviceSize memoryOffset,
  13686. VkBuffer buffer,
  13687. const void* pNext)
  13688. {
  13689. if(pNext != VMA_NULL)
  13690. {
  13691. #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2
  13692. if((m_UseKhrBindMemory2 || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) &&
  13693. m_VulkanFunctions.vkBindBufferMemory2KHR != VMA_NULL)
  13694. {
  13695. VkBindBufferMemoryInfoKHR bindBufferMemoryInfo = { VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR };
  13696. bindBufferMemoryInfo.pNext = pNext;
  13697. bindBufferMemoryInfo.buffer = buffer;
  13698. bindBufferMemoryInfo.memory = memory;
  13699. bindBufferMemoryInfo.memoryOffset = memoryOffset;
  13700. return (*m_VulkanFunctions.vkBindBufferMemory2KHR)(m_hDevice, 1, &bindBufferMemoryInfo);
  13701. }
  13702. else
  13703. #endif // #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2
  13704. {
  13705. return VK_ERROR_EXTENSION_NOT_PRESENT;
  13706. }
  13707. }
  13708. else
  13709. {
  13710. return (*m_VulkanFunctions.vkBindBufferMemory)(m_hDevice, buffer, memory, memoryOffset);
  13711. }
  13712. }
  13713. VkResult VmaAllocator_T::BindVulkanImage(
  13714. VkDeviceMemory memory,
  13715. VkDeviceSize memoryOffset,
  13716. VkImage image,
  13717. const void* pNext)
  13718. {
  13719. if(pNext != VMA_NULL)
  13720. {
  13721. #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2
  13722. if((m_UseKhrBindMemory2 || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) &&
  13723. m_VulkanFunctions.vkBindImageMemory2KHR != VMA_NULL)
  13724. {
  13725. VkBindImageMemoryInfoKHR bindBufferMemoryInfo = { VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO_KHR };
  13726. bindBufferMemoryInfo.pNext = pNext;
  13727. bindBufferMemoryInfo.image = image;
  13728. bindBufferMemoryInfo.memory = memory;
  13729. bindBufferMemoryInfo.memoryOffset = memoryOffset;
  13730. return (*m_VulkanFunctions.vkBindImageMemory2KHR)(m_hDevice, 1, &bindBufferMemoryInfo);
  13731. }
  13732. else
  13733. #endif // #if VMA_BIND_MEMORY2
  13734. {
  13735. return VK_ERROR_EXTENSION_NOT_PRESENT;
  13736. }
  13737. }
  13738. else
  13739. {
  13740. return (*m_VulkanFunctions.vkBindImageMemory)(m_hDevice, image, memory, memoryOffset);
  13741. }
  13742. }
  13743. VkResult VmaAllocator_T::Map(VmaAllocation hAllocation, void** ppData)
  13744. {
  13745. if(hAllocation->CanBecomeLost())
  13746. {
  13747. return VK_ERROR_MEMORY_MAP_FAILED;
  13748. }
  13749. switch(hAllocation->GetType())
  13750. {
  13751. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13752. {
  13753. VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
  13754. char *pBytes = VMA_NULL;
  13755. VkResult res = pBlock->Map(this, 1, (void**)&pBytes);
  13756. if(res == VK_SUCCESS)
  13757. {
  13758. *ppData = pBytes + (ptrdiff_t)hAllocation->GetOffset();
  13759. hAllocation->BlockAllocMap();
  13760. }
  13761. return res;
  13762. }
  13763. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13764. return hAllocation->DedicatedAllocMap(this, ppData);
  13765. default:
  13766. VMA_ASSERT(0);
  13767. return VK_ERROR_MEMORY_MAP_FAILED;
  13768. }
  13769. }
  13770. void VmaAllocator_T::Unmap(VmaAllocation hAllocation)
  13771. {
  13772. switch(hAllocation->GetType())
  13773. {
  13774. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13775. {
  13776. VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
  13777. hAllocation->BlockAllocUnmap();
  13778. pBlock->Unmap(this, 1);
  13779. }
  13780. break;
  13781. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13782. hAllocation->DedicatedAllocUnmap(this);
  13783. break;
  13784. default:
  13785. VMA_ASSERT(0);
  13786. }
  13787. }
  13788. VkResult VmaAllocator_T::BindBufferMemory(
  13789. VmaAllocation hAllocation,
  13790. VkDeviceSize allocationLocalOffset,
  13791. VkBuffer hBuffer,
  13792. const void* pNext)
  13793. {
  13794. VkResult res = VK_SUCCESS;
  13795. switch(hAllocation->GetType())
  13796. {
  13797. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13798. res = BindVulkanBuffer(hAllocation->GetMemory(), allocationLocalOffset, hBuffer, pNext);
  13799. break;
  13800. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13801. {
  13802. VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
  13803. VMA_ASSERT(pBlock && "Binding buffer to allocation that doesn't belong to any block. Is the allocation lost?");
  13804. res = pBlock->BindBufferMemory(this, hAllocation, allocationLocalOffset, hBuffer, pNext);
  13805. break;
  13806. }
  13807. default:
  13808. VMA_ASSERT(0);
  13809. }
  13810. return res;
  13811. }
  13812. VkResult VmaAllocator_T::BindImageMemory(
  13813. VmaAllocation hAllocation,
  13814. VkDeviceSize allocationLocalOffset,
  13815. VkImage hImage,
  13816. const void* pNext)
  13817. {
  13818. VkResult res = VK_SUCCESS;
  13819. switch(hAllocation->GetType())
  13820. {
  13821. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13822. res = BindVulkanImage(hAllocation->GetMemory(), allocationLocalOffset, hImage, pNext);
  13823. break;
  13824. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13825. {
  13826. VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock();
  13827. VMA_ASSERT(pBlock && "Binding image to allocation that doesn't belong to any block. Is the allocation lost?");
  13828. res = pBlock->BindImageMemory(this, hAllocation, allocationLocalOffset, hImage, pNext);
  13829. break;
  13830. }
  13831. default:
  13832. VMA_ASSERT(0);
  13833. }
  13834. return res;
  13835. }
  13836. void VmaAllocator_T::FlushOrInvalidateAllocation(
  13837. VmaAllocation hAllocation,
  13838. VkDeviceSize offset, VkDeviceSize size,
  13839. VMA_CACHE_OPERATION op)
  13840. {
  13841. const uint32_t memTypeIndex = hAllocation->GetMemoryTypeIndex();
  13842. if(size > 0 && IsMemoryTypeNonCoherent(memTypeIndex))
  13843. {
  13844. const VkDeviceSize allocationSize = hAllocation->GetSize();
  13845. VMA_ASSERT(offset <= allocationSize);
  13846. const VkDeviceSize nonCoherentAtomSize = m_PhysicalDeviceProperties.limits.nonCoherentAtomSize;
  13847. VkMappedMemoryRange memRange = { VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE };
  13848. memRange.memory = hAllocation->GetMemory();
  13849. switch(hAllocation->GetType())
  13850. {
  13851. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13852. memRange.offset = VmaAlignDown(offset, nonCoherentAtomSize);
  13853. if(size == VK_WHOLE_SIZE)
  13854. {
  13855. memRange.size = allocationSize - memRange.offset;
  13856. }
  13857. else
  13858. {
  13859. VMA_ASSERT(offset + size <= allocationSize);
  13860. memRange.size = VMA_MIN(
  13861. VmaAlignUp(size + (offset - memRange.offset), nonCoherentAtomSize),
  13862. allocationSize - memRange.offset);
  13863. }
  13864. break;
  13865. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13866. {
  13867. // 1. Still within this allocation.
  13868. memRange.offset = VmaAlignDown(offset, nonCoherentAtomSize);
  13869. if(size == VK_WHOLE_SIZE)
  13870. {
  13871. size = allocationSize - offset;
  13872. }
  13873. else
  13874. {
  13875. VMA_ASSERT(offset + size <= allocationSize);
  13876. }
  13877. memRange.size = VmaAlignUp(size + (offset - memRange.offset), nonCoherentAtomSize);
  13878. // 2. Adjust to whole block.
  13879. const VkDeviceSize allocationOffset = hAllocation->GetOffset();
  13880. VMA_ASSERT(allocationOffset % nonCoherentAtomSize == 0);
  13881. const VkDeviceSize blockSize = hAllocation->GetBlock()->m_pMetadata->GetSize();
  13882. memRange.offset += allocationOffset;
  13883. memRange.size = VMA_MIN(memRange.size, blockSize - memRange.offset);
  13884. break;
  13885. }
  13886. default:
  13887. VMA_ASSERT(0);
  13888. }
  13889. switch(op)
  13890. {
  13891. case VMA_CACHE_FLUSH:
  13892. (*GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hDevice, 1, &memRange);
  13893. break;
  13894. case VMA_CACHE_INVALIDATE:
  13895. (*GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hDevice, 1, &memRange);
  13896. break;
  13897. default:
  13898. VMA_ASSERT(0);
  13899. }
  13900. }
  13901. // else: Just ignore this call.
  13902. }
  13903. void VmaAllocator_T::FreeDedicatedMemory(const VmaAllocation allocation)
  13904. {
  13905. VMA_ASSERT(allocation && allocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  13906. const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
  13907. {
  13908. VmaMutexLockWrite lock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
  13909. AllocationVectorType* const pDedicatedAllocations = m_pDedicatedAllocations[memTypeIndex];
  13910. VMA_ASSERT(pDedicatedAllocations);
  13911. bool success = VmaVectorRemoveSorted<VmaPointerLess>(*pDedicatedAllocations, allocation);
  13912. VMA_ASSERT(success);
  13913. }
  13914. VkDeviceMemory hMemory = allocation->GetMemory();
  13915. /*
  13916. There is no need to call this, because Vulkan spec allows to skip vkUnmapMemory
  13917. before vkFreeMemory.
  13918. if(allocation->GetMappedData() != VMA_NULL)
  13919. {
  13920. (*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory);
  13921. }
  13922. */
  13923. FreeVulkanMemory(memTypeIndex, allocation->GetSize(), hMemory);
  13924. VMA_DEBUG_LOG(" Freed DedicatedMemory MemoryTypeIndex=%u", memTypeIndex);
  13925. }
  13926. uint32_t VmaAllocator_T::CalculateGpuDefragmentationMemoryTypeBits() const
  13927. {
  13928. VkBufferCreateInfo dummyBufCreateInfo;
  13929. VmaFillGpuDefragmentationBufferCreateInfo(dummyBufCreateInfo);
  13930. uint32_t memoryTypeBits = 0;
  13931. // Create buffer.
  13932. VkBuffer buf = VK_NULL_HANDLE;
  13933. VkResult res = (*GetVulkanFunctions().vkCreateBuffer)(
  13934. m_hDevice, &dummyBufCreateInfo, GetAllocationCallbacks(), &buf);
  13935. if(res == VK_SUCCESS)
  13936. {
  13937. // Query for supported memory types.
  13938. VkMemoryRequirements memReq;
  13939. (*GetVulkanFunctions().vkGetBufferMemoryRequirements)(m_hDevice, buf, &memReq);
  13940. memoryTypeBits = memReq.memoryTypeBits;
  13941. // Destroy buffer.
  13942. (*GetVulkanFunctions().vkDestroyBuffer)(m_hDevice, buf, GetAllocationCallbacks());
  13943. }
  13944. return memoryTypeBits;
  13945. }
  13946. #if VMA_MEMORY_BUDGET
  13947. void VmaAllocator_T::UpdateVulkanBudget()
  13948. {
  13949. VMA_ASSERT(m_UseExtMemoryBudget);
  13950. VkPhysicalDeviceMemoryProperties2KHR memProps = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2_KHR };
  13951. VkPhysicalDeviceMemoryBudgetPropertiesEXT budgetProps = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT };
  13952. memProps.pNext = &budgetProps;
  13953. GetVulkanFunctions().vkGetPhysicalDeviceMemoryProperties2KHR(m_PhysicalDevice, &memProps);
  13954. {
  13955. VmaMutexLockWrite lockWrite(m_Budget.m_BudgetMutex, m_UseMutex);
  13956. for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex)
  13957. {
  13958. m_Budget.m_VulkanUsage[heapIndex] = budgetProps.heapUsage[heapIndex];
  13959. m_Budget.m_VulkanBudget[heapIndex] = budgetProps.heapBudget[heapIndex];
  13960. m_Budget.m_BlockBytesAtBudgetFetch[heapIndex] = m_Budget.m_BlockBytes[heapIndex].load();
  13961. }
  13962. m_Budget.m_OperationsSinceBudgetFetch = 0;
  13963. }
  13964. }
  13965. #endif // #if VMA_MEMORY_BUDGET
  13966. void VmaAllocator_T::FillAllocation(const VmaAllocation hAllocation, uint8_t pattern)
  13967. {
  13968. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS &&
  13969. !hAllocation->CanBecomeLost() &&
  13970. (m_MemProps.memoryTypes[hAllocation->GetMemoryTypeIndex()].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
  13971. {
  13972. void* pData = VMA_NULL;
  13973. VkResult res = Map(hAllocation, &pData);
  13974. if(res == VK_SUCCESS)
  13975. {
  13976. memset(pData, (int)pattern, (size_t)hAllocation->GetSize());
  13977. FlushOrInvalidateAllocation(hAllocation, 0, VK_WHOLE_SIZE, VMA_CACHE_FLUSH);
  13978. Unmap(hAllocation);
  13979. }
  13980. else
  13981. {
  13982. VMA_ASSERT(0 && "VMA_DEBUG_INITIALIZE_ALLOCATIONS is enabled, but couldn't map memory to fill allocation.");
  13983. }
  13984. }
  13985. }
  13986. uint32_t VmaAllocator_T::GetGpuDefragmentationMemoryTypeBits()
  13987. {
  13988. uint32_t memoryTypeBits = m_GpuDefragmentationMemoryTypeBits.load();
  13989. if(memoryTypeBits == UINT32_MAX)
  13990. {
  13991. memoryTypeBits = CalculateGpuDefragmentationMemoryTypeBits();
  13992. m_GpuDefragmentationMemoryTypeBits.store(memoryTypeBits);
  13993. }
  13994. return memoryTypeBits;
  13995. }
  13996. #if VMA_STATS_STRING_ENABLED
  13997. void VmaAllocator_T::PrintDetailedMap(VmaJsonWriter& json)
  13998. {
  13999. bool dedicatedAllocationsStarted = false;
  14000. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  14001. {
  14002. VmaMutexLockRead dedicatedAllocationsLock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
  14003. AllocationVectorType* const pDedicatedAllocVector = m_pDedicatedAllocations[memTypeIndex];
  14004. VMA_ASSERT(pDedicatedAllocVector);
  14005. if(pDedicatedAllocVector->empty() == false)
  14006. {
  14007. if(dedicatedAllocationsStarted == false)
  14008. {
  14009. dedicatedAllocationsStarted = true;
  14010. json.WriteString("DedicatedAllocations");
  14011. json.BeginObject();
  14012. }
  14013. json.BeginString("Type ");
  14014. json.ContinueString(memTypeIndex);
  14015. json.EndString();
  14016. json.BeginArray();
  14017. for(size_t i = 0; i < pDedicatedAllocVector->size(); ++i)
  14018. {
  14019. json.BeginObject(true);
  14020. const VmaAllocation hAlloc = (*pDedicatedAllocVector)[i];
  14021. hAlloc->PrintParameters(json);
  14022. json.EndObject();
  14023. }
  14024. json.EndArray();
  14025. }
  14026. }
  14027. if(dedicatedAllocationsStarted)
  14028. {
  14029. json.EndObject();
  14030. }
  14031. {
  14032. bool allocationsStarted = false;
  14033. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  14034. {
  14035. if(m_pBlockVectors[memTypeIndex]->IsEmpty() == false)
  14036. {
  14037. if(allocationsStarted == false)
  14038. {
  14039. allocationsStarted = true;
  14040. json.WriteString("DefaultPools");
  14041. json.BeginObject();
  14042. }
  14043. json.BeginString("Type ");
  14044. json.ContinueString(memTypeIndex);
  14045. json.EndString();
  14046. m_pBlockVectors[memTypeIndex]->PrintDetailedMap(json);
  14047. }
  14048. }
  14049. if(allocationsStarted)
  14050. {
  14051. json.EndObject();
  14052. }
  14053. }
  14054. // Custom pools
  14055. {
  14056. VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex);
  14057. const size_t poolCount = m_Pools.size();
  14058. if(poolCount > 0)
  14059. {
  14060. json.WriteString("Pools");
  14061. json.BeginObject();
  14062. for(size_t poolIndex = 0; poolIndex < poolCount; ++poolIndex)
  14063. {
  14064. json.BeginString();
  14065. json.ContinueString(m_Pools[poolIndex]->GetId());
  14066. json.EndString();
  14067. m_Pools[poolIndex]->m_BlockVector.PrintDetailedMap(json);
  14068. }
  14069. json.EndObject();
  14070. }
  14071. }
  14072. }
  14073. #endif // #if VMA_STATS_STRING_ENABLED
  14074. ////////////////////////////////////////////////////////////////////////////////
  14075. // Public interface
  14076. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAllocator(
  14077. const VmaAllocatorCreateInfo* pCreateInfo,
  14078. VmaAllocator* pAllocator)
  14079. {
  14080. VMA_ASSERT(pCreateInfo && pAllocator);
  14081. VMA_ASSERT(pCreateInfo->vulkanApiVersion == 0 ||
  14082. (VK_VERSION_MAJOR(pCreateInfo->vulkanApiVersion) == 1 && VK_VERSION_MINOR(pCreateInfo->vulkanApiVersion) <= 1));
  14083. VMA_DEBUG_LOG("vmaCreateAllocator");
  14084. *pAllocator = vma_new(pCreateInfo->pAllocationCallbacks, VmaAllocator_T)(pCreateInfo);
  14085. return (*pAllocator)->Init(pCreateInfo);
  14086. }
  14087. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyAllocator(
  14088. VmaAllocator allocator)
  14089. {
  14090. if(allocator != VK_NULL_HANDLE)
  14091. {
  14092. VMA_DEBUG_LOG("vmaDestroyAllocator");
  14093. VkAllocationCallbacks allocationCallbacks = allocator->m_AllocationCallbacks;
  14094. vma_delete(&allocationCallbacks, allocator);
  14095. }
  14096. }
  14097. VMA_CALL_PRE void VMA_CALL_POST vmaGetPhysicalDeviceProperties(
  14098. VmaAllocator allocator,
  14099. const VkPhysicalDeviceProperties **ppPhysicalDeviceProperties)
  14100. {
  14101. VMA_ASSERT(allocator && ppPhysicalDeviceProperties);
  14102. *ppPhysicalDeviceProperties = &allocator->m_PhysicalDeviceProperties;
  14103. }
  14104. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryProperties(
  14105. VmaAllocator allocator,
  14106. const VkPhysicalDeviceMemoryProperties** ppPhysicalDeviceMemoryProperties)
  14107. {
  14108. VMA_ASSERT(allocator && ppPhysicalDeviceMemoryProperties);
  14109. *ppPhysicalDeviceMemoryProperties = &allocator->m_MemProps;
  14110. }
  14111. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties(
  14112. VmaAllocator allocator,
  14113. uint32_t memoryTypeIndex,
  14114. VkMemoryPropertyFlags* pFlags)
  14115. {
  14116. VMA_ASSERT(allocator && pFlags);
  14117. VMA_ASSERT(memoryTypeIndex < allocator->GetMemoryTypeCount());
  14118. *pFlags = allocator->m_MemProps.memoryTypes[memoryTypeIndex].propertyFlags;
  14119. }
  14120. VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex(
  14121. VmaAllocator allocator,
  14122. uint32_t frameIndex)
  14123. {
  14124. VMA_ASSERT(allocator);
  14125. VMA_ASSERT(frameIndex != VMA_FRAME_INDEX_LOST);
  14126. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14127. allocator->SetCurrentFrameIndex(frameIndex);
  14128. }
  14129. VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStats(
  14130. VmaAllocator allocator,
  14131. VmaStats* pStats)
  14132. {
  14133. VMA_ASSERT(allocator && pStats);
  14134. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14135. allocator->CalculateStats(pStats);
  14136. }
  14137. VMA_CALL_PRE void VMA_CALL_POST vmaGetBudget(
  14138. VmaAllocator allocator,
  14139. VmaBudget* pBudget)
  14140. {
  14141. VMA_ASSERT(allocator && pBudget);
  14142. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14143. allocator->GetBudget(pBudget, 0, allocator->GetMemoryHeapCount());
  14144. }
  14145. #if VMA_STATS_STRING_ENABLED
  14146. VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString(
  14147. VmaAllocator allocator,
  14148. char** ppStatsString,
  14149. VkBool32 detailedMap)
  14150. {
  14151. VMA_ASSERT(allocator && ppStatsString);
  14152. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14153. VmaStringBuilder sb(allocator);
  14154. {
  14155. VmaJsonWriter json(allocator->GetAllocationCallbacks(), sb);
  14156. json.BeginObject();
  14157. VmaBudget budget[VK_MAX_MEMORY_HEAPS];
  14158. allocator->GetBudget(budget, 0, allocator->GetMemoryHeapCount());
  14159. VmaStats stats;
  14160. allocator->CalculateStats(&stats);
  14161. json.WriteString("Total");
  14162. VmaPrintStatInfo(json, stats.total);
  14163. for(uint32_t heapIndex = 0; heapIndex < allocator->GetMemoryHeapCount(); ++heapIndex)
  14164. {
  14165. json.BeginString("Heap ");
  14166. json.ContinueString(heapIndex);
  14167. json.EndString();
  14168. json.BeginObject();
  14169. json.WriteString("Size");
  14170. json.WriteNumber(allocator->m_MemProps.memoryHeaps[heapIndex].size);
  14171. json.WriteString("Flags");
  14172. json.BeginArray(true);
  14173. if((allocator->m_MemProps.memoryHeaps[heapIndex].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) != 0)
  14174. {
  14175. json.WriteString("DEVICE_LOCAL");
  14176. }
  14177. json.EndArray();
  14178. json.WriteString("Budget");
  14179. json.BeginObject();
  14180. {
  14181. json.WriteString("BlockBytes");
  14182. json.WriteNumber(budget[heapIndex].blockBytes);
  14183. json.WriteString("AllocationBytes");
  14184. json.WriteNumber(budget[heapIndex].allocationBytes);
  14185. json.WriteString("Usage");
  14186. json.WriteNumber(budget[heapIndex].usage);
  14187. json.WriteString("Budget");
  14188. json.WriteNumber(budget[heapIndex].budget);
  14189. }
  14190. json.EndObject();
  14191. if(stats.memoryHeap[heapIndex].blockCount > 0)
  14192. {
  14193. json.WriteString("Stats");
  14194. VmaPrintStatInfo(json, stats.memoryHeap[heapIndex]);
  14195. }
  14196. for(uint32_t typeIndex = 0; typeIndex < allocator->GetMemoryTypeCount(); ++typeIndex)
  14197. {
  14198. if(allocator->MemoryTypeIndexToHeapIndex(typeIndex) == heapIndex)
  14199. {
  14200. json.BeginString("Type ");
  14201. json.ContinueString(typeIndex);
  14202. json.EndString();
  14203. json.BeginObject();
  14204. json.WriteString("Flags");
  14205. json.BeginArray(true);
  14206. VkMemoryPropertyFlags flags = allocator->m_MemProps.memoryTypes[typeIndex].propertyFlags;
  14207. if((flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0)
  14208. {
  14209. json.WriteString("DEVICE_LOCAL");
  14210. }
  14211. if((flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
  14212. {
  14213. json.WriteString("HOST_VISIBLE");
  14214. }
  14215. if((flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0)
  14216. {
  14217. json.WriteString("HOST_COHERENT");
  14218. }
  14219. if((flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) != 0)
  14220. {
  14221. json.WriteString("HOST_CACHED");
  14222. }
  14223. if((flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) != 0)
  14224. {
  14225. json.WriteString("LAZILY_ALLOCATED");
  14226. }
  14227. json.EndArray();
  14228. if(stats.memoryType[typeIndex].blockCount > 0)
  14229. {
  14230. json.WriteString("Stats");
  14231. VmaPrintStatInfo(json, stats.memoryType[typeIndex]);
  14232. }
  14233. json.EndObject();
  14234. }
  14235. }
  14236. json.EndObject();
  14237. }
  14238. if(detailedMap == VK_TRUE)
  14239. {
  14240. allocator->PrintDetailedMap(json);
  14241. }
  14242. json.EndObject();
  14243. }
  14244. const size_t len = sb.GetLength();
  14245. char* const pChars = vma_new_array(allocator, char, len + 1);
  14246. if(len > 0)
  14247. {
  14248. memcpy(pChars, sb.GetData(), len);
  14249. }
  14250. pChars[len] = '\0';
  14251. *ppStatsString = pChars;
  14252. }
  14253. VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString(
  14254. VmaAllocator allocator,
  14255. char* pStatsString)
  14256. {
  14257. if(pStatsString != VMA_NULL)
  14258. {
  14259. VMA_ASSERT(allocator);
  14260. size_t len = strlen(pStatsString);
  14261. vma_delete_array(allocator, pStatsString, len + 1);
  14262. }
  14263. }
  14264. #endif // #if VMA_STATS_STRING_ENABLED
  14265. /*
  14266. This function is not protected by any mutex because it just reads immutable data.
  14267. */
  14268. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex(
  14269. VmaAllocator allocator,
  14270. uint32_t memoryTypeBits,
  14271. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14272. uint32_t* pMemoryTypeIndex)
  14273. {
  14274. VMA_ASSERT(allocator != VK_NULL_HANDLE);
  14275. VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
  14276. VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
  14277. if(pAllocationCreateInfo->memoryTypeBits != 0)
  14278. {
  14279. memoryTypeBits &= pAllocationCreateInfo->memoryTypeBits;
  14280. }
  14281. uint32_t requiredFlags = pAllocationCreateInfo->requiredFlags;
  14282. uint32_t preferredFlags = pAllocationCreateInfo->preferredFlags;
  14283. uint32_t notPreferredFlags = 0;
  14284. // Convert usage to requiredFlags and preferredFlags.
  14285. switch(pAllocationCreateInfo->usage)
  14286. {
  14287. case VMA_MEMORY_USAGE_UNKNOWN:
  14288. break;
  14289. case VMA_MEMORY_USAGE_GPU_ONLY:
  14290. if(!allocator->IsIntegratedGpu() || (preferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  14291. {
  14292. preferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  14293. }
  14294. break;
  14295. case VMA_MEMORY_USAGE_CPU_ONLY:
  14296. requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
  14297. break;
  14298. case VMA_MEMORY_USAGE_CPU_TO_GPU:
  14299. requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  14300. if(!allocator->IsIntegratedGpu() || (preferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  14301. {
  14302. preferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  14303. }
  14304. break;
  14305. case VMA_MEMORY_USAGE_GPU_TO_CPU:
  14306. requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  14307. preferredFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  14308. break;
  14309. case VMA_MEMORY_USAGE_CPU_COPY:
  14310. notPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  14311. break;
  14312. case VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED:
  14313. requiredFlags |= VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT;
  14314. break;
  14315. default:
  14316. VMA_ASSERT(0);
  14317. break;
  14318. }
  14319. *pMemoryTypeIndex = UINT32_MAX;
  14320. uint32_t minCost = UINT32_MAX;
  14321. for(uint32_t memTypeIndex = 0, memTypeBit = 1;
  14322. memTypeIndex < allocator->GetMemoryTypeCount();
  14323. ++memTypeIndex, memTypeBit <<= 1)
  14324. {
  14325. // This memory type is acceptable according to memoryTypeBits bitmask.
  14326. if((memTypeBit & memoryTypeBits) != 0)
  14327. {
  14328. const VkMemoryPropertyFlags currFlags =
  14329. allocator->m_MemProps.memoryTypes[memTypeIndex].propertyFlags;
  14330. // This memory type contains requiredFlags.
  14331. if((requiredFlags & ~currFlags) == 0)
  14332. {
  14333. // Calculate cost as number of bits from preferredFlags not present in this memory type.
  14334. uint32_t currCost = VmaCountBitsSet(preferredFlags & ~currFlags) +
  14335. VmaCountBitsSet(currFlags & notPreferredFlags);
  14336. // Remember memory type with lowest cost.
  14337. if(currCost < minCost)
  14338. {
  14339. *pMemoryTypeIndex = memTypeIndex;
  14340. if(currCost == 0)
  14341. {
  14342. return VK_SUCCESS;
  14343. }
  14344. minCost = currCost;
  14345. }
  14346. }
  14347. }
  14348. }
  14349. return (*pMemoryTypeIndex != UINT32_MAX) ? VK_SUCCESS : VK_ERROR_FEATURE_NOT_PRESENT;
  14350. }
  14351. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo(
  14352. VmaAllocator allocator,
  14353. const VkBufferCreateInfo* pBufferCreateInfo,
  14354. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14355. uint32_t* pMemoryTypeIndex)
  14356. {
  14357. VMA_ASSERT(allocator != VK_NULL_HANDLE);
  14358. VMA_ASSERT(pBufferCreateInfo != VMA_NULL);
  14359. VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
  14360. VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
  14361. const VkDevice hDev = allocator->m_hDevice;
  14362. VkBuffer hBuffer = VK_NULL_HANDLE;
  14363. VkResult res = allocator->GetVulkanFunctions().vkCreateBuffer(
  14364. hDev, pBufferCreateInfo, allocator->GetAllocationCallbacks(), &hBuffer);
  14365. if(res == VK_SUCCESS)
  14366. {
  14367. VkMemoryRequirements memReq = {};
  14368. allocator->GetVulkanFunctions().vkGetBufferMemoryRequirements(
  14369. hDev, hBuffer, &memReq);
  14370. res = vmaFindMemoryTypeIndex(
  14371. allocator,
  14372. memReq.memoryTypeBits,
  14373. pAllocationCreateInfo,
  14374. pMemoryTypeIndex);
  14375. allocator->GetVulkanFunctions().vkDestroyBuffer(
  14376. hDev, hBuffer, allocator->GetAllocationCallbacks());
  14377. }
  14378. return res;
  14379. }
  14380. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo(
  14381. VmaAllocator allocator,
  14382. const VkImageCreateInfo* pImageCreateInfo,
  14383. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14384. uint32_t* pMemoryTypeIndex)
  14385. {
  14386. VMA_ASSERT(allocator != VK_NULL_HANDLE);
  14387. VMA_ASSERT(pImageCreateInfo != VMA_NULL);
  14388. VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
  14389. VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
  14390. const VkDevice hDev = allocator->m_hDevice;
  14391. VkImage hImage = VK_NULL_HANDLE;
  14392. VkResult res = allocator->GetVulkanFunctions().vkCreateImage(
  14393. hDev, pImageCreateInfo, allocator->GetAllocationCallbacks(), &hImage);
  14394. if(res == VK_SUCCESS)
  14395. {
  14396. VkMemoryRequirements memReq = {};
  14397. allocator->GetVulkanFunctions().vkGetImageMemoryRequirements(
  14398. hDev, hImage, &memReq);
  14399. res = vmaFindMemoryTypeIndex(
  14400. allocator,
  14401. memReq.memoryTypeBits,
  14402. pAllocationCreateInfo,
  14403. pMemoryTypeIndex);
  14404. allocator->GetVulkanFunctions().vkDestroyImage(
  14405. hDev, hImage, allocator->GetAllocationCallbacks());
  14406. }
  14407. return res;
  14408. }
  14409. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool(
  14410. VmaAllocator allocator,
  14411. const VmaPoolCreateInfo* pCreateInfo,
  14412. VmaPool* pPool)
  14413. {
  14414. VMA_ASSERT(allocator && pCreateInfo && pPool);
  14415. VMA_DEBUG_LOG("vmaCreatePool");
  14416. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14417. VkResult res = allocator->CreatePool(pCreateInfo, pPool);
  14418. #if VMA_RECORDING_ENABLED
  14419. if(allocator->GetRecorder() != VMA_NULL)
  14420. {
  14421. allocator->GetRecorder()->RecordCreatePool(allocator->GetCurrentFrameIndex(), *pCreateInfo, *pPool);
  14422. }
  14423. #endif
  14424. return res;
  14425. }
  14426. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool(
  14427. VmaAllocator allocator,
  14428. VmaPool pool)
  14429. {
  14430. VMA_ASSERT(allocator);
  14431. if(pool == VK_NULL_HANDLE)
  14432. {
  14433. return;
  14434. }
  14435. VMA_DEBUG_LOG("vmaDestroyPool");
  14436. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14437. #if VMA_RECORDING_ENABLED
  14438. if(allocator->GetRecorder() != VMA_NULL)
  14439. {
  14440. allocator->GetRecorder()->RecordDestroyPool(allocator->GetCurrentFrameIndex(), pool);
  14441. }
  14442. #endif
  14443. allocator->DestroyPool(pool);
  14444. }
  14445. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStats(
  14446. VmaAllocator allocator,
  14447. VmaPool pool,
  14448. VmaPoolStats* pPoolStats)
  14449. {
  14450. VMA_ASSERT(allocator && pool && pPoolStats);
  14451. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14452. allocator->GetPoolStats(pool, pPoolStats);
  14453. }
  14454. VMA_CALL_PRE void VMA_CALL_POST vmaMakePoolAllocationsLost(
  14455. VmaAllocator allocator,
  14456. VmaPool pool,
  14457. size_t* pLostAllocationCount)
  14458. {
  14459. VMA_ASSERT(allocator && pool);
  14460. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14461. #if VMA_RECORDING_ENABLED
  14462. if(allocator->GetRecorder() != VMA_NULL)
  14463. {
  14464. allocator->GetRecorder()->RecordMakePoolAllocationsLost(allocator->GetCurrentFrameIndex(), pool);
  14465. }
  14466. #endif
  14467. allocator->MakePoolAllocationsLost(pool, pLostAllocationCount);
  14468. }
  14469. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckPoolCorruption(VmaAllocator allocator, VmaPool pool)
  14470. {
  14471. VMA_ASSERT(allocator && pool);
  14472. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14473. VMA_DEBUG_LOG("vmaCheckPoolCorruption");
  14474. return allocator->CheckPoolCorruption(pool);
  14475. }
  14476. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName(
  14477. VmaAllocator allocator,
  14478. VmaPool pool,
  14479. const char** ppName)
  14480. {
  14481. VMA_ASSERT(allocator && pool);
  14482. VMA_DEBUG_LOG("vmaGetPoolName");
  14483. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14484. *ppName = pool->GetName();
  14485. }
  14486. VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName(
  14487. VmaAllocator allocator,
  14488. VmaPool pool,
  14489. const char* pName)
  14490. {
  14491. VMA_ASSERT(allocator && pool);
  14492. VMA_DEBUG_LOG("vmaSetPoolName");
  14493. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14494. pool->SetName(pName);
  14495. #if VMA_RECORDING_ENABLED
  14496. if(allocator->GetRecorder() != VMA_NULL)
  14497. {
  14498. allocator->GetRecorder()->RecordSetPoolName(allocator->GetCurrentFrameIndex(), pool, pName);
  14499. }
  14500. #endif
  14501. }
  14502. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory(
  14503. VmaAllocator allocator,
  14504. const VkMemoryRequirements* pVkMemoryRequirements,
  14505. const VmaAllocationCreateInfo* pCreateInfo,
  14506. VmaAllocation* pAllocation,
  14507. VmaAllocationInfo* pAllocationInfo)
  14508. {
  14509. VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocation);
  14510. VMA_DEBUG_LOG("vmaAllocateMemory");
  14511. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14512. VkResult result = allocator->AllocateMemory(
  14513. *pVkMemoryRequirements,
  14514. false, // requiresDedicatedAllocation
  14515. false, // prefersDedicatedAllocation
  14516. VK_NULL_HANDLE, // dedicatedBuffer
  14517. VK_NULL_HANDLE, // dedicatedImage
  14518. *pCreateInfo,
  14519. VMA_SUBALLOCATION_TYPE_UNKNOWN,
  14520. 1, // allocationCount
  14521. pAllocation);
  14522. #if VMA_RECORDING_ENABLED
  14523. if(allocator->GetRecorder() != VMA_NULL)
  14524. {
  14525. allocator->GetRecorder()->RecordAllocateMemory(
  14526. allocator->GetCurrentFrameIndex(),
  14527. *pVkMemoryRequirements,
  14528. *pCreateInfo,
  14529. *pAllocation);
  14530. }
  14531. #endif
  14532. if(pAllocationInfo != VMA_NULL && result == VK_SUCCESS)
  14533. {
  14534. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  14535. }
  14536. return result;
  14537. }
  14538. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages(
  14539. VmaAllocator allocator,
  14540. const VkMemoryRequirements* pVkMemoryRequirements,
  14541. const VmaAllocationCreateInfo* pCreateInfo,
  14542. size_t allocationCount,
  14543. VmaAllocation* pAllocations,
  14544. VmaAllocationInfo* pAllocationInfo)
  14545. {
  14546. if(allocationCount == 0)
  14547. {
  14548. return VK_SUCCESS;
  14549. }
  14550. VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocations);
  14551. VMA_DEBUG_LOG("vmaAllocateMemoryPages");
  14552. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14553. VkResult result = allocator->AllocateMemory(
  14554. *pVkMemoryRequirements,
  14555. false, // requiresDedicatedAllocation
  14556. false, // prefersDedicatedAllocation
  14557. VK_NULL_HANDLE, // dedicatedBuffer
  14558. VK_NULL_HANDLE, // dedicatedImage
  14559. *pCreateInfo,
  14560. VMA_SUBALLOCATION_TYPE_UNKNOWN,
  14561. allocationCount,
  14562. pAllocations);
  14563. #if VMA_RECORDING_ENABLED
  14564. if(allocator->GetRecorder() != VMA_NULL)
  14565. {
  14566. allocator->GetRecorder()->RecordAllocateMemoryPages(
  14567. allocator->GetCurrentFrameIndex(),
  14568. *pVkMemoryRequirements,
  14569. *pCreateInfo,
  14570. (uint64_t)allocationCount,
  14571. pAllocations);
  14572. }
  14573. #endif
  14574. if(pAllocationInfo != VMA_NULL && result == VK_SUCCESS)
  14575. {
  14576. for(size_t i = 0; i < allocationCount; ++i)
  14577. {
  14578. allocator->GetAllocationInfo(pAllocations[i], pAllocationInfo + i);
  14579. }
  14580. }
  14581. return result;
  14582. }
  14583. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer(
  14584. VmaAllocator allocator,
  14585. VkBuffer buffer,
  14586. const VmaAllocationCreateInfo* pCreateInfo,
  14587. VmaAllocation* pAllocation,
  14588. VmaAllocationInfo* pAllocationInfo)
  14589. {
  14590. VMA_ASSERT(allocator && buffer != VK_NULL_HANDLE && pCreateInfo && pAllocation);
  14591. VMA_DEBUG_LOG("vmaAllocateMemoryForBuffer");
  14592. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14593. VkMemoryRequirements vkMemReq = {};
  14594. bool requiresDedicatedAllocation = false;
  14595. bool prefersDedicatedAllocation = false;
  14596. allocator->GetBufferMemoryRequirements(buffer, vkMemReq,
  14597. requiresDedicatedAllocation,
  14598. prefersDedicatedAllocation);
  14599. VkResult result = allocator->AllocateMemory(
  14600. vkMemReq,
  14601. requiresDedicatedAllocation,
  14602. prefersDedicatedAllocation,
  14603. buffer, // dedicatedBuffer
  14604. VK_NULL_HANDLE, // dedicatedImage
  14605. *pCreateInfo,
  14606. VMA_SUBALLOCATION_TYPE_BUFFER,
  14607. 1, // allocationCount
  14608. pAllocation);
  14609. #if VMA_RECORDING_ENABLED
  14610. if(allocator->GetRecorder() != VMA_NULL)
  14611. {
  14612. allocator->GetRecorder()->RecordAllocateMemoryForBuffer(
  14613. allocator->GetCurrentFrameIndex(),
  14614. vkMemReq,
  14615. requiresDedicatedAllocation,
  14616. prefersDedicatedAllocation,
  14617. *pCreateInfo,
  14618. *pAllocation);
  14619. }
  14620. #endif
  14621. if(pAllocationInfo && result == VK_SUCCESS)
  14622. {
  14623. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  14624. }
  14625. return result;
  14626. }
  14627. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage(
  14628. VmaAllocator allocator,
  14629. VkImage image,
  14630. const VmaAllocationCreateInfo* pCreateInfo,
  14631. VmaAllocation* pAllocation,
  14632. VmaAllocationInfo* pAllocationInfo)
  14633. {
  14634. VMA_ASSERT(allocator && image != VK_NULL_HANDLE && pCreateInfo && pAllocation);
  14635. VMA_DEBUG_LOG("vmaAllocateMemoryForImage");
  14636. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14637. VkMemoryRequirements vkMemReq = {};
  14638. bool requiresDedicatedAllocation = false;
  14639. bool prefersDedicatedAllocation = false;
  14640. allocator->GetImageMemoryRequirements(image, vkMemReq,
  14641. requiresDedicatedAllocation, prefersDedicatedAllocation);
  14642. VkResult result = allocator->AllocateMemory(
  14643. vkMemReq,
  14644. requiresDedicatedAllocation,
  14645. prefersDedicatedAllocation,
  14646. VK_NULL_HANDLE, // dedicatedBuffer
  14647. image, // dedicatedImage
  14648. *pCreateInfo,
  14649. VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN,
  14650. 1, // allocationCount
  14651. pAllocation);
  14652. #if VMA_RECORDING_ENABLED
  14653. if(allocator->GetRecorder() != VMA_NULL)
  14654. {
  14655. allocator->GetRecorder()->RecordAllocateMemoryForImage(
  14656. allocator->GetCurrentFrameIndex(),
  14657. vkMemReq,
  14658. requiresDedicatedAllocation,
  14659. prefersDedicatedAllocation,
  14660. *pCreateInfo,
  14661. *pAllocation);
  14662. }
  14663. #endif
  14664. if(pAllocationInfo && result == VK_SUCCESS)
  14665. {
  14666. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  14667. }
  14668. return result;
  14669. }
  14670. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory(
  14671. VmaAllocator allocator,
  14672. VmaAllocation allocation)
  14673. {
  14674. VMA_ASSERT(allocator);
  14675. if(allocation == VK_NULL_HANDLE)
  14676. {
  14677. return;
  14678. }
  14679. VMA_DEBUG_LOG("vmaFreeMemory");
  14680. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14681. #if VMA_RECORDING_ENABLED
  14682. if(allocator->GetRecorder() != VMA_NULL)
  14683. {
  14684. allocator->GetRecorder()->RecordFreeMemory(
  14685. allocator->GetCurrentFrameIndex(),
  14686. allocation);
  14687. }
  14688. #endif
  14689. allocator->FreeMemory(
  14690. 1, // allocationCount
  14691. &allocation);
  14692. }
  14693. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages(
  14694. VmaAllocator allocator,
  14695. size_t allocationCount,
  14696. VmaAllocation* pAllocations)
  14697. {
  14698. if(allocationCount == 0)
  14699. {
  14700. return;
  14701. }
  14702. VMA_ASSERT(allocator);
  14703. VMA_DEBUG_LOG("vmaFreeMemoryPages");
  14704. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14705. #if VMA_RECORDING_ENABLED
  14706. if(allocator->GetRecorder() != VMA_NULL)
  14707. {
  14708. allocator->GetRecorder()->RecordFreeMemoryPages(
  14709. allocator->GetCurrentFrameIndex(),
  14710. (uint64_t)allocationCount,
  14711. pAllocations);
  14712. }
  14713. #endif
  14714. allocator->FreeMemory(allocationCount, pAllocations);
  14715. }
  14716. VMA_CALL_PRE VkResult VMA_CALL_POST vmaResizeAllocation(
  14717. VmaAllocator allocator,
  14718. VmaAllocation allocation,
  14719. VkDeviceSize newSize)
  14720. {
  14721. VMA_ASSERT(allocator && allocation);
  14722. VMA_DEBUG_LOG("vmaResizeAllocation");
  14723. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14724. return allocator->ResizeAllocation(allocation, newSize);
  14725. }
  14726. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo(
  14727. VmaAllocator allocator,
  14728. VmaAllocation allocation,
  14729. VmaAllocationInfo* pAllocationInfo)
  14730. {
  14731. VMA_ASSERT(allocator && allocation && pAllocationInfo);
  14732. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14733. #if VMA_RECORDING_ENABLED
  14734. if(allocator->GetRecorder() != VMA_NULL)
  14735. {
  14736. allocator->GetRecorder()->RecordGetAllocationInfo(
  14737. allocator->GetCurrentFrameIndex(),
  14738. allocation);
  14739. }
  14740. #endif
  14741. allocator->GetAllocationInfo(allocation, pAllocationInfo);
  14742. }
  14743. VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaTouchAllocation(
  14744. VmaAllocator allocator,
  14745. VmaAllocation allocation)
  14746. {
  14747. VMA_ASSERT(allocator && allocation);
  14748. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14749. #if VMA_RECORDING_ENABLED
  14750. if(allocator->GetRecorder() != VMA_NULL)
  14751. {
  14752. allocator->GetRecorder()->RecordTouchAllocation(
  14753. allocator->GetCurrentFrameIndex(),
  14754. allocation);
  14755. }
  14756. #endif
  14757. return allocator->TouchAllocation(allocation);
  14758. }
  14759. VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData(
  14760. VmaAllocator allocator,
  14761. VmaAllocation allocation,
  14762. void* pUserData)
  14763. {
  14764. VMA_ASSERT(allocator && allocation);
  14765. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14766. allocation->SetUserData(allocator, pUserData);
  14767. #if VMA_RECORDING_ENABLED
  14768. if(allocator->GetRecorder() != VMA_NULL)
  14769. {
  14770. allocator->GetRecorder()->RecordSetAllocationUserData(
  14771. allocator->GetCurrentFrameIndex(),
  14772. allocation,
  14773. pUserData);
  14774. }
  14775. #endif
  14776. }
  14777. VMA_CALL_PRE void VMA_CALL_POST vmaCreateLostAllocation(
  14778. VmaAllocator allocator,
  14779. VmaAllocation* pAllocation)
  14780. {
  14781. VMA_ASSERT(allocator && pAllocation);
  14782. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  14783. allocator->CreateLostAllocation(pAllocation);
  14784. #if VMA_RECORDING_ENABLED
  14785. if(allocator->GetRecorder() != VMA_NULL)
  14786. {
  14787. allocator->GetRecorder()->RecordCreateLostAllocation(
  14788. allocator->GetCurrentFrameIndex(),
  14789. *pAllocation);
  14790. }
  14791. #endif
  14792. }
  14793. VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory(
  14794. VmaAllocator allocator,
  14795. VmaAllocation allocation,
  14796. void** ppData)
  14797. {
  14798. VMA_ASSERT(allocator && allocation && ppData);
  14799. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14800. VkResult res = allocator->Map(allocation, ppData);
  14801. #if VMA_RECORDING_ENABLED
  14802. if(allocator->GetRecorder() != VMA_NULL)
  14803. {
  14804. allocator->GetRecorder()->RecordMapMemory(
  14805. allocator->GetCurrentFrameIndex(),
  14806. allocation);
  14807. }
  14808. #endif
  14809. return res;
  14810. }
  14811. VMA_CALL_PRE void VMA_CALL_POST vmaUnmapMemory(
  14812. VmaAllocator allocator,
  14813. VmaAllocation allocation)
  14814. {
  14815. VMA_ASSERT(allocator && allocation);
  14816. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14817. #if VMA_RECORDING_ENABLED
  14818. if(allocator->GetRecorder() != VMA_NULL)
  14819. {
  14820. allocator->GetRecorder()->RecordUnmapMemory(
  14821. allocator->GetCurrentFrameIndex(),
  14822. allocation);
  14823. }
  14824. #endif
  14825. allocator->Unmap(allocation);
  14826. }
  14827. VMA_CALL_PRE void VMA_CALL_POST vmaFlushAllocation(VmaAllocator allocator, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size)
  14828. {
  14829. VMA_ASSERT(allocator && allocation);
  14830. VMA_DEBUG_LOG("vmaFlushAllocation");
  14831. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14832. allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_FLUSH);
  14833. #if VMA_RECORDING_ENABLED
  14834. if(allocator->GetRecorder() != VMA_NULL)
  14835. {
  14836. allocator->GetRecorder()->RecordFlushAllocation(
  14837. allocator->GetCurrentFrameIndex(),
  14838. allocation, offset, size);
  14839. }
  14840. #endif
  14841. }
  14842. VMA_CALL_PRE void VMA_CALL_POST vmaInvalidateAllocation(VmaAllocator allocator, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size)
  14843. {
  14844. VMA_ASSERT(allocator && allocation);
  14845. VMA_DEBUG_LOG("vmaInvalidateAllocation");
  14846. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14847. allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_INVALIDATE);
  14848. #if VMA_RECORDING_ENABLED
  14849. if(allocator->GetRecorder() != VMA_NULL)
  14850. {
  14851. allocator->GetRecorder()->RecordInvalidateAllocation(
  14852. allocator->GetCurrentFrameIndex(),
  14853. allocation, offset, size);
  14854. }
  14855. #endif
  14856. }
  14857. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckCorruption(VmaAllocator allocator, uint32_t memoryTypeBits)
  14858. {
  14859. VMA_ASSERT(allocator);
  14860. VMA_DEBUG_LOG("vmaCheckCorruption");
  14861. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14862. return allocator->CheckCorruption(memoryTypeBits);
  14863. }
  14864. VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragment(
  14865. VmaAllocator allocator,
  14866. VmaAllocation* pAllocations,
  14867. size_t allocationCount,
  14868. VkBool32* pAllocationsChanged,
  14869. const VmaDefragmentationInfo *pDefragmentationInfo,
  14870. VmaDefragmentationStats* pDefragmentationStats)
  14871. {
  14872. // Deprecated interface, reimplemented using new one.
  14873. VmaDefragmentationInfo2 info2 = {};
  14874. info2.allocationCount = (uint32_t)allocationCount;
  14875. info2.pAllocations = pAllocations;
  14876. info2.pAllocationsChanged = pAllocationsChanged;
  14877. if(pDefragmentationInfo != VMA_NULL)
  14878. {
  14879. info2.maxCpuAllocationsToMove = pDefragmentationInfo->maxAllocationsToMove;
  14880. info2.maxCpuBytesToMove = pDefragmentationInfo->maxBytesToMove;
  14881. }
  14882. else
  14883. {
  14884. info2.maxCpuAllocationsToMove = UINT32_MAX;
  14885. info2.maxCpuBytesToMove = VK_WHOLE_SIZE;
  14886. }
  14887. // info2.flags, maxGpuAllocationsToMove, maxGpuBytesToMove, commandBuffer deliberately left zero.
  14888. VmaDefragmentationContext ctx;
  14889. VkResult res = vmaDefragmentationBegin(allocator, &info2, pDefragmentationStats, &ctx);
  14890. if(res == VK_NOT_READY)
  14891. {
  14892. res = vmaDefragmentationEnd( allocator, ctx);
  14893. }
  14894. return res;
  14895. }
  14896. VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragmentationBegin(
  14897. VmaAllocator allocator,
  14898. const VmaDefragmentationInfo2* pInfo,
  14899. VmaDefragmentationStats* pStats,
  14900. VmaDefragmentationContext *pContext)
  14901. {
  14902. VMA_ASSERT(allocator && pInfo && pContext);
  14903. // Degenerate case: Nothing to defragment.
  14904. if(pInfo->allocationCount == 0 && pInfo->poolCount == 0)
  14905. {
  14906. return VK_SUCCESS;
  14907. }
  14908. VMA_ASSERT(pInfo->allocationCount == 0 || pInfo->pAllocations != VMA_NULL);
  14909. VMA_ASSERT(pInfo->poolCount == 0 || pInfo->pPools != VMA_NULL);
  14910. VMA_HEAVY_ASSERT(VmaValidatePointerArray(pInfo->allocationCount, pInfo->pAllocations));
  14911. VMA_HEAVY_ASSERT(VmaValidatePointerArray(pInfo->poolCount, pInfo->pPools));
  14912. VMA_DEBUG_LOG("vmaDefragmentationBegin");
  14913. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14914. VkResult res = allocator->DefragmentationBegin(*pInfo, pStats, pContext);
  14915. #if VMA_RECORDING_ENABLED
  14916. if(allocator->GetRecorder() != VMA_NULL)
  14917. {
  14918. allocator->GetRecorder()->RecordDefragmentationBegin(
  14919. allocator->GetCurrentFrameIndex(), *pInfo, *pContext);
  14920. }
  14921. #endif
  14922. return res;
  14923. }
  14924. VMA_CALL_PRE VkResult VMA_CALL_POST vmaDefragmentationEnd(
  14925. VmaAllocator allocator,
  14926. VmaDefragmentationContext context)
  14927. {
  14928. VMA_ASSERT(allocator);
  14929. VMA_DEBUG_LOG("vmaDefragmentationEnd");
  14930. if(context != VK_NULL_HANDLE)
  14931. {
  14932. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14933. #if VMA_RECORDING_ENABLED
  14934. if(allocator->GetRecorder() != VMA_NULL)
  14935. {
  14936. allocator->GetRecorder()->RecordDefragmentationEnd(
  14937. allocator->GetCurrentFrameIndex(), context);
  14938. }
  14939. #endif
  14940. return allocator->DefragmentationEnd(context);
  14941. }
  14942. else
  14943. {
  14944. return VK_SUCCESS;
  14945. }
  14946. }
  14947. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory(
  14948. VmaAllocator allocator,
  14949. VmaAllocation allocation,
  14950. VkBuffer buffer)
  14951. {
  14952. VMA_ASSERT(allocator && allocation && buffer);
  14953. VMA_DEBUG_LOG("vmaBindBufferMemory");
  14954. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14955. return allocator->BindBufferMemory(allocation, 0, buffer, VMA_NULL);
  14956. }
  14957. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2(
  14958. VmaAllocator allocator,
  14959. VmaAllocation allocation,
  14960. VkDeviceSize allocationLocalOffset,
  14961. VkBuffer buffer,
  14962. const void* pNext)
  14963. {
  14964. VMA_ASSERT(allocator && allocation && buffer);
  14965. VMA_DEBUG_LOG("vmaBindBufferMemory2");
  14966. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14967. return allocator->BindBufferMemory(allocation, allocationLocalOffset, buffer, pNext);
  14968. }
  14969. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory(
  14970. VmaAllocator allocator,
  14971. VmaAllocation allocation,
  14972. VkImage image)
  14973. {
  14974. VMA_ASSERT(allocator && allocation && image);
  14975. VMA_DEBUG_LOG("vmaBindImageMemory");
  14976. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14977. return allocator->BindImageMemory(allocation, 0, image, VMA_NULL);
  14978. }
  14979. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2(
  14980. VmaAllocator allocator,
  14981. VmaAllocation allocation,
  14982. VkDeviceSize allocationLocalOffset,
  14983. VkImage image,
  14984. const void* pNext)
  14985. {
  14986. VMA_ASSERT(allocator && allocation && image);
  14987. VMA_DEBUG_LOG("vmaBindImageMemory2");
  14988. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14989. return allocator->BindImageMemory(allocation, allocationLocalOffset, image, pNext);
  14990. }
  14991. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer(
  14992. VmaAllocator allocator,
  14993. const VkBufferCreateInfo* pBufferCreateInfo,
  14994. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14995. VkBuffer* pBuffer,
  14996. VmaAllocation* pAllocation,
  14997. VmaAllocationInfo* pAllocationInfo)
  14998. {
  14999. VMA_ASSERT(allocator && pBufferCreateInfo && pAllocationCreateInfo && pBuffer && pAllocation);
  15000. if(pBufferCreateInfo->size == 0)
  15001. {
  15002. return VK_ERROR_VALIDATION_FAILED_EXT;
  15003. }
  15004. VMA_DEBUG_LOG("vmaCreateBuffer");
  15005. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15006. *pBuffer = VK_NULL_HANDLE;
  15007. *pAllocation = VK_NULL_HANDLE;
  15008. // 1. Create VkBuffer.
  15009. VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)(
  15010. allocator->m_hDevice,
  15011. pBufferCreateInfo,
  15012. allocator->GetAllocationCallbacks(),
  15013. pBuffer);
  15014. if(res >= 0)
  15015. {
  15016. // 2. vkGetBufferMemoryRequirements.
  15017. VkMemoryRequirements vkMemReq = {};
  15018. bool requiresDedicatedAllocation = false;
  15019. bool prefersDedicatedAllocation = false;
  15020. allocator->GetBufferMemoryRequirements(*pBuffer, vkMemReq,
  15021. requiresDedicatedAllocation, prefersDedicatedAllocation);
  15022. // 3. Allocate memory using allocator.
  15023. res = allocator->AllocateMemory(
  15024. vkMemReq,
  15025. requiresDedicatedAllocation,
  15026. prefersDedicatedAllocation,
  15027. *pBuffer, // dedicatedBuffer
  15028. VK_NULL_HANDLE, // dedicatedImage
  15029. *pAllocationCreateInfo,
  15030. VMA_SUBALLOCATION_TYPE_BUFFER,
  15031. 1, // allocationCount
  15032. pAllocation);
  15033. #if VMA_RECORDING_ENABLED
  15034. if(allocator->GetRecorder() != VMA_NULL)
  15035. {
  15036. allocator->GetRecorder()->RecordCreateBuffer(
  15037. allocator->GetCurrentFrameIndex(),
  15038. *pBufferCreateInfo,
  15039. *pAllocationCreateInfo,
  15040. *pAllocation);
  15041. }
  15042. #endif
  15043. if(res >= 0)
  15044. {
  15045. // 3. Bind buffer with memory.
  15046. if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0)
  15047. {
  15048. res = allocator->BindBufferMemory(*pAllocation, 0, *pBuffer, VMA_NULL);
  15049. }
  15050. if(res >= 0)
  15051. {
  15052. // All steps succeeded.
  15053. #if VMA_STATS_STRING_ENABLED
  15054. (*pAllocation)->InitBufferImageUsage(pBufferCreateInfo->usage);
  15055. #endif
  15056. if(pAllocationInfo != VMA_NULL)
  15057. {
  15058. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  15059. }
  15060. return VK_SUCCESS;
  15061. }
  15062. allocator->FreeMemory(
  15063. 1, // allocationCount
  15064. pAllocation);
  15065. *pAllocation = VK_NULL_HANDLE;
  15066. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
  15067. *pBuffer = VK_NULL_HANDLE;
  15068. return res;
  15069. }
  15070. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
  15071. *pBuffer = VK_NULL_HANDLE;
  15072. return res;
  15073. }
  15074. return res;
  15075. }
  15076. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer(
  15077. VmaAllocator allocator,
  15078. VkBuffer buffer,
  15079. VmaAllocation allocation)
  15080. {
  15081. VMA_ASSERT(allocator);
  15082. if(buffer == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE)
  15083. {
  15084. return;
  15085. }
  15086. VMA_DEBUG_LOG("vmaDestroyBuffer");
  15087. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15088. #if VMA_RECORDING_ENABLED
  15089. if(allocator->GetRecorder() != VMA_NULL)
  15090. {
  15091. allocator->GetRecorder()->RecordDestroyBuffer(
  15092. allocator->GetCurrentFrameIndex(),
  15093. allocation);
  15094. }
  15095. #endif
  15096. if(buffer != VK_NULL_HANDLE)
  15097. {
  15098. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, buffer, allocator->GetAllocationCallbacks());
  15099. }
  15100. if(allocation != VK_NULL_HANDLE)
  15101. {
  15102. allocator->FreeMemory(
  15103. 1, // allocationCount
  15104. &allocation);
  15105. }
  15106. }
  15107. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage(
  15108. VmaAllocator allocator,
  15109. const VkImageCreateInfo* pImageCreateInfo,
  15110. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  15111. VkImage* pImage,
  15112. VmaAllocation* pAllocation,
  15113. VmaAllocationInfo* pAllocationInfo)
  15114. {
  15115. VMA_ASSERT(allocator && pImageCreateInfo && pAllocationCreateInfo && pImage && pAllocation);
  15116. if(pImageCreateInfo->extent.width == 0 ||
  15117. pImageCreateInfo->extent.height == 0 ||
  15118. pImageCreateInfo->extent.depth == 0 ||
  15119. pImageCreateInfo->mipLevels == 0 ||
  15120. pImageCreateInfo->arrayLayers == 0)
  15121. {
  15122. return VK_ERROR_VALIDATION_FAILED_EXT;
  15123. }
  15124. VMA_DEBUG_LOG("vmaCreateImage");
  15125. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15126. *pImage = VK_NULL_HANDLE;
  15127. *pAllocation = VK_NULL_HANDLE;
  15128. // 1. Create VkImage.
  15129. VkResult res = (*allocator->GetVulkanFunctions().vkCreateImage)(
  15130. allocator->m_hDevice,
  15131. pImageCreateInfo,
  15132. allocator->GetAllocationCallbacks(),
  15133. pImage);
  15134. if(res >= 0)
  15135. {
  15136. VmaSuballocationType suballocType = pImageCreateInfo->tiling == VK_IMAGE_TILING_OPTIMAL ?
  15137. VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL :
  15138. VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR;
  15139. // 2. Allocate memory using allocator.
  15140. VkMemoryRequirements vkMemReq = {};
  15141. bool requiresDedicatedAllocation = false;
  15142. bool prefersDedicatedAllocation = false;
  15143. allocator->GetImageMemoryRequirements(*pImage, vkMemReq,
  15144. requiresDedicatedAllocation, prefersDedicatedAllocation);
  15145. res = allocator->AllocateMemory(
  15146. vkMemReq,
  15147. requiresDedicatedAllocation,
  15148. prefersDedicatedAllocation,
  15149. VK_NULL_HANDLE, // dedicatedBuffer
  15150. *pImage, // dedicatedImage
  15151. *pAllocationCreateInfo,
  15152. suballocType,
  15153. 1, // allocationCount
  15154. pAllocation);
  15155. #if VMA_RECORDING_ENABLED
  15156. if(allocator->GetRecorder() != VMA_NULL)
  15157. {
  15158. allocator->GetRecorder()->RecordCreateImage(
  15159. allocator->GetCurrentFrameIndex(),
  15160. *pImageCreateInfo,
  15161. *pAllocationCreateInfo,
  15162. *pAllocation);
  15163. }
  15164. #endif
  15165. if(res >= 0)
  15166. {
  15167. // 3. Bind image with memory.
  15168. if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0)
  15169. {
  15170. res = allocator->BindImageMemory(*pAllocation, 0, *pImage, VMA_NULL);
  15171. }
  15172. if(res >= 0)
  15173. {
  15174. // All steps succeeded.
  15175. #if VMA_STATS_STRING_ENABLED
  15176. (*pAllocation)->InitBufferImageUsage(pImageCreateInfo->usage);
  15177. #endif
  15178. if(pAllocationInfo != VMA_NULL)
  15179. {
  15180. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  15181. }
  15182. return VK_SUCCESS;
  15183. }
  15184. allocator->FreeMemory(
  15185. 1, // allocationCount
  15186. pAllocation);
  15187. *pAllocation = VK_NULL_HANDLE;
  15188. (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks());
  15189. *pImage = VK_NULL_HANDLE;
  15190. return res;
  15191. }
  15192. (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks());
  15193. *pImage = VK_NULL_HANDLE;
  15194. return res;
  15195. }
  15196. return res;
  15197. }
  15198. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyImage(
  15199. VmaAllocator allocator,
  15200. VkImage image,
  15201. VmaAllocation allocation)
  15202. {
  15203. VMA_ASSERT(allocator);
  15204. if(image == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE)
  15205. {
  15206. return;
  15207. }
  15208. VMA_DEBUG_LOG("vmaDestroyImage");
  15209. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15210. #if VMA_RECORDING_ENABLED
  15211. if(allocator->GetRecorder() != VMA_NULL)
  15212. {
  15213. allocator->GetRecorder()->RecordDestroyImage(
  15214. allocator->GetCurrentFrameIndex(),
  15215. allocation);
  15216. }
  15217. #endif
  15218. if(image != VK_NULL_HANDLE)
  15219. {
  15220. (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, image, allocator->GetAllocationCallbacks());
  15221. }
  15222. if(allocation != VK_NULL_HANDLE)
  15223. {
  15224. allocator->FreeMemory(
  15225. 1, // allocationCount
  15226. &allocation);
  15227. }
  15228. }
  15229. #endif // #ifdef VMA_IMPLEMENTATION