vk_mem_alloc.h 721 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696
  1. //
  2. // Copyright (c) 2017-2022 Advanced Micro Devices, Inc. All rights reserved.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #ifndef AMD_VULKAN_MEMORY_ALLOCATOR_H
  23. #define AMD_VULKAN_MEMORY_ALLOCATOR_H
  24. /** \mainpage Vulkan Memory Allocator
  25. <b>Version 3.1.0-development</b>
  26. Copyright (c) 2017-2022 Advanced Micro Devices, Inc. All rights reserved. \n
  27. License: MIT
  28. <b>API documentation divided into groups:</b> [Modules](modules.html)
  29. \section main_table_of_contents Table of contents
  30. - <b>User guide</b>
  31. - \subpage quick_start
  32. - [Project setup](@ref quick_start_project_setup)
  33. - [Initialization](@ref quick_start_initialization)
  34. - [Resource allocation](@ref quick_start_resource_allocation)
  35. - \subpage choosing_memory_type
  36. - [Usage](@ref choosing_memory_type_usage)
  37. - [Required and preferred flags](@ref choosing_memory_type_required_preferred_flags)
  38. - [Explicit memory types](@ref choosing_memory_type_explicit_memory_types)
  39. - [Custom memory pools](@ref choosing_memory_type_custom_memory_pools)
  40. - [Dedicated allocations](@ref choosing_memory_type_dedicated_allocations)
  41. - \subpage memory_mapping
  42. - [Mapping functions](@ref memory_mapping_mapping_functions)
  43. - [Persistently mapped memory](@ref memory_mapping_persistently_mapped_memory)
  44. - [Cache flush and invalidate](@ref memory_mapping_cache_control)
  45. - \subpage staying_within_budget
  46. - [Querying for budget](@ref staying_within_budget_querying_for_budget)
  47. - [Controlling memory usage](@ref staying_within_budget_controlling_memory_usage)
  48. - \subpage resource_aliasing
  49. - \subpage custom_memory_pools
  50. - [Choosing memory type index](@ref custom_memory_pools_MemTypeIndex)
  51. - [Linear allocation algorithm](@ref linear_algorithm)
  52. - [Free-at-once](@ref linear_algorithm_free_at_once)
  53. - [Stack](@ref linear_algorithm_stack)
  54. - [Double stack](@ref linear_algorithm_double_stack)
  55. - [Ring buffer](@ref linear_algorithm_ring_buffer)
  56. - \subpage defragmentation
  57. - \subpage statistics
  58. - [Numeric statistics](@ref statistics_numeric_statistics)
  59. - [JSON dump](@ref statistics_json_dump)
  60. - \subpage allocation_annotation
  61. - [Allocation user data](@ref allocation_user_data)
  62. - [Allocation names](@ref allocation_names)
  63. - \subpage virtual_allocator
  64. - \subpage debugging_memory_usage
  65. - [Memory initialization](@ref debugging_memory_usage_initialization)
  66. - [Margins](@ref debugging_memory_usage_margins)
  67. - [Corruption detection](@ref debugging_memory_usage_corruption_detection)
  68. - \subpage opengl_interop
  69. - \subpage usage_patterns
  70. - [GPU-only resource](@ref usage_patterns_gpu_only)
  71. - [Staging copy for upload](@ref usage_patterns_staging_copy_upload)
  72. - [Readback](@ref usage_patterns_readback)
  73. - [Advanced data uploading](@ref usage_patterns_advanced_data_uploading)
  74. - [Other use cases](@ref usage_patterns_other_use_cases)
  75. - \subpage configuration
  76. - [Pointers to Vulkan functions](@ref config_Vulkan_functions)
  77. - [Custom host memory allocator](@ref custom_memory_allocator)
  78. - [Device memory allocation callbacks](@ref allocation_callbacks)
  79. - [Device heap memory limit](@ref heap_memory_limit)
  80. - <b>Extension support</b>
  81. - \subpage vk_khr_dedicated_allocation
  82. - \subpage enabling_buffer_device_address
  83. - \subpage vk_ext_memory_priority
  84. - \subpage vk_amd_device_coherent_memory
  85. - \subpage general_considerations
  86. - [Thread safety](@ref general_considerations_thread_safety)
  87. - [Versioning and compatibility](@ref general_considerations_versioning_and_compatibility)
  88. - [Validation layer warnings](@ref general_considerations_validation_layer_warnings)
  89. - [Allocation algorithm](@ref general_considerations_allocation_algorithm)
  90. - [Features not supported](@ref general_considerations_features_not_supported)
  91. \section main_see_also See also
  92. - [**Product page on GPUOpen**](https://gpuopen.com/gaming-product/vulkan-memory-allocator/)
  93. - [**Source repository on GitHub**](https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator)
  94. \defgroup group_init Library initialization
  95. \brief API elements related to the initialization and management of the entire library, especially #VmaAllocator object.
  96. \defgroup group_alloc Memory allocation
  97. \brief API elements related to the allocation, deallocation, and management of Vulkan memory, buffers, images.
  98. Most basic ones being: vmaCreateBuffer(), vmaCreateImage().
  99. \defgroup group_virtual Virtual allocator
  100. \brief API elements related to the mechanism of \ref virtual_allocator - using the core allocation algorithm
  101. for user-defined purpose without allocating any real GPU memory.
  102. \defgroup group_stats Statistics
  103. \brief API elements that query current status of the allocator, from memory usage, budget, to full dump of the internal state in JSON format.
  104. See documentation chapter: \ref statistics.
  105. */
  106. #ifdef __cplusplus
  107. extern "C" {
  108. #endif
  109. #ifdef USE_VOLK
  110. #include <volk.h>
  111. #else
  112. #include <vulkan/vulkan.h>
  113. #endif
  114. #if !defined(VMA_VULKAN_VERSION)
  115. #if defined(VK_VERSION_1_3)
  116. #define VMA_VULKAN_VERSION 1003000
  117. #elif defined(VK_VERSION_1_2)
  118. #define VMA_VULKAN_VERSION 1002000
  119. #elif defined(VK_VERSION_1_1)
  120. #define VMA_VULKAN_VERSION 1001000
  121. #else
  122. #define VMA_VULKAN_VERSION 1000000
  123. #endif
  124. #endif
  125. #if defined(__ANDROID__) && defined(VK_NO_PROTOTYPES) && VMA_STATIC_VULKAN_FUNCTIONS
  126. extern PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr;
  127. extern PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr;
  128. extern PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties;
  129. extern PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties;
  130. extern PFN_vkAllocateMemory vkAllocateMemory;
  131. extern PFN_vkFreeMemory vkFreeMemory;
  132. extern PFN_vkMapMemory vkMapMemory;
  133. extern PFN_vkUnmapMemory vkUnmapMemory;
  134. extern PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges;
  135. extern PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges;
  136. extern PFN_vkBindBufferMemory vkBindBufferMemory;
  137. extern PFN_vkBindImageMemory vkBindImageMemory;
  138. extern PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements;
  139. extern PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements;
  140. extern PFN_vkCreateBuffer vkCreateBuffer;
  141. extern PFN_vkDestroyBuffer vkDestroyBuffer;
  142. extern PFN_vkCreateImage vkCreateImage;
  143. extern PFN_vkDestroyImage vkDestroyImage;
  144. extern PFN_vkCmdCopyBuffer vkCmdCopyBuffer;
  145. #if VMA_VULKAN_VERSION >= 1001000
  146. extern PFN_vkGetBufferMemoryRequirements2 vkGetBufferMemoryRequirements2;
  147. extern PFN_vkGetImageMemoryRequirements2 vkGetImageMemoryRequirements2;
  148. extern PFN_vkBindBufferMemory2 vkBindBufferMemory2;
  149. extern PFN_vkBindImageMemory2 vkBindImageMemory2;
  150. extern PFN_vkGetPhysicalDeviceMemoryProperties2 vkGetPhysicalDeviceMemoryProperties2;
  151. #endif // #if VMA_VULKAN_VERSION >= 1001000
  152. #endif // #if defined(__ANDROID__) && VMA_STATIC_VULKAN_FUNCTIONS && VK_NO_PROTOTYPES
  153. #if !defined(VMA_DEDICATED_ALLOCATION)
  154. #if VK_KHR_get_memory_requirements2 && VK_KHR_dedicated_allocation
  155. #define VMA_DEDICATED_ALLOCATION 1
  156. #else
  157. #define VMA_DEDICATED_ALLOCATION 0
  158. #endif
  159. #endif
  160. #if !defined(VMA_BIND_MEMORY2)
  161. #if VK_KHR_bind_memory2
  162. #define VMA_BIND_MEMORY2 1
  163. #else
  164. #define VMA_BIND_MEMORY2 0
  165. #endif
  166. #endif
  167. #if !defined(VMA_MEMORY_BUDGET)
  168. #if VK_EXT_memory_budget && (VK_KHR_get_physical_device_properties2 || VMA_VULKAN_VERSION >= 1001000)
  169. #define VMA_MEMORY_BUDGET 1
  170. #else
  171. #define VMA_MEMORY_BUDGET 0
  172. #endif
  173. #endif
  174. // Defined to 1 when VK_KHR_buffer_device_address device extension or equivalent core Vulkan 1.2 feature is defined in its headers.
  175. #if !defined(VMA_BUFFER_DEVICE_ADDRESS)
  176. #if VK_KHR_buffer_device_address || VMA_VULKAN_VERSION >= 1002000
  177. #define VMA_BUFFER_DEVICE_ADDRESS 1
  178. #else
  179. #define VMA_BUFFER_DEVICE_ADDRESS 0
  180. #endif
  181. #endif
  182. // Defined to 1 when VK_EXT_memory_priority device extension is defined in Vulkan headers.
  183. #if !defined(VMA_MEMORY_PRIORITY)
  184. #if VK_EXT_memory_priority
  185. #define VMA_MEMORY_PRIORITY 1
  186. #else
  187. #define VMA_MEMORY_PRIORITY 0
  188. #endif
  189. #endif
  190. // Defined to 1 when VK_KHR_external_memory device extension is defined in Vulkan headers.
  191. #if !defined(VMA_EXTERNAL_MEMORY)
  192. #if VK_KHR_external_memory
  193. #define VMA_EXTERNAL_MEMORY 1
  194. #else
  195. #define VMA_EXTERNAL_MEMORY 0
  196. #endif
  197. #endif
  198. // Define these macros to decorate all public functions with additional code,
  199. // before and after returned type, appropriately. This may be useful for
  200. // exporting the functions when compiling VMA as a separate library. Example:
  201. // #define VMA_CALL_PRE __declspec(dllexport)
  202. // #define VMA_CALL_POST __cdecl
  203. #ifndef VMA_CALL_PRE
  204. #define VMA_CALL_PRE
  205. #endif
  206. #ifndef VMA_CALL_POST
  207. #define VMA_CALL_POST
  208. #endif
  209. // Define this macro to decorate pNext pointers with an attribute specifying the Vulkan
  210. // structure that will be extended via the pNext chain.
  211. #ifndef VMA_EXTENDS_VK_STRUCT
  212. #define VMA_EXTENDS_VK_STRUCT(vkStruct)
  213. #endif
  214. // Define this macro to decorate pointers with an attribute specifying the
  215. // length of the array they point to if they are not null.
  216. //
  217. // The length may be one of
  218. // - The name of another parameter in the argument list where the pointer is declared
  219. // - The name of another member in the struct where the pointer is declared
  220. // - The name of a member of a struct type, meaning the value of that member in
  221. // the context of the call. For example
  222. // VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryHeapCount"),
  223. // this means the number of memory heaps available in the device associated
  224. // with the VmaAllocator being dealt with.
  225. #ifndef VMA_LEN_IF_NOT_NULL
  226. #define VMA_LEN_IF_NOT_NULL(len)
  227. #endif
  228. // The VMA_NULLABLE macro is defined to be _Nullable when compiling with Clang.
  229. // see: https://clang.llvm.org/docs/AttributeReference.html#nullable
  230. #ifndef VMA_NULLABLE
  231. #ifdef __clang__
  232. #define VMA_NULLABLE _Nullable
  233. #else
  234. #define VMA_NULLABLE
  235. #endif
  236. #endif
  237. // The VMA_NOT_NULL macro is defined to be _Nonnull when compiling with Clang.
  238. // see: https://clang.llvm.org/docs/AttributeReference.html#nonnull
  239. #ifndef VMA_NOT_NULL
  240. #ifdef __clang__
  241. #define VMA_NOT_NULL _Nonnull
  242. #else
  243. #define VMA_NOT_NULL
  244. #endif
  245. #endif
  246. // If non-dispatchable handles are represented as pointers then we can give
  247. // then nullability annotations
  248. #ifndef VMA_NOT_NULL_NON_DISPATCHABLE
  249. #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
  250. #define VMA_NOT_NULL_NON_DISPATCHABLE VMA_NOT_NULL
  251. #else
  252. #define VMA_NOT_NULL_NON_DISPATCHABLE
  253. #endif
  254. #endif
  255. #ifndef VMA_NULLABLE_NON_DISPATCHABLE
  256. #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
  257. #define VMA_NULLABLE_NON_DISPATCHABLE VMA_NULLABLE
  258. #else
  259. #define VMA_NULLABLE_NON_DISPATCHABLE
  260. #endif
  261. #endif
  262. #ifndef VMA_STATS_STRING_ENABLED
  263. #define VMA_STATS_STRING_ENABLED 1
  264. #endif
  265. ////////////////////////////////////////////////////////////////////////////////
  266. ////////////////////////////////////////////////////////////////////////////////
  267. //
  268. // INTERFACE
  269. //
  270. ////////////////////////////////////////////////////////////////////////////////
  271. ////////////////////////////////////////////////////////////////////////////////
  272. // Sections for managing code placement in file, only for development purposes e.g. for convenient folding inside an IDE.
  273. #ifndef _VMA_ENUM_DECLARATIONS
  274. /**
  275. \addtogroup group_init
  276. @{
  277. */
  278. /// Flags for created #VmaAllocator.
  279. typedef enum VmaAllocatorCreateFlagBits
  280. {
  281. /** \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.
  282. Using this flag may increase performance because internal mutexes are not used.
  283. */
  284. VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT = 0x00000001,
  285. /** \brief Enables usage of VK_KHR_dedicated_allocation extension.
  286. The flag works only if VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_0`.
  287. When it is `VK_API_VERSION_1_1`, the flag is ignored because the extension has been promoted to Vulkan 1.1.
  288. Using this extension will automatically allocate dedicated blocks of memory for
  289. some buffers and images instead of suballocating place for them out of bigger
  290. memory blocks (as if you explicitly used #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT
  291. flag) when it is recommended by the driver. It may improve performance on some
  292. GPUs.
  293. You may set this flag only if you found out that following device extensions are
  294. supported, you enabled them while creating Vulkan device passed as
  295. VmaAllocatorCreateInfo::device, and you want them to be used internally by this
  296. library:
  297. - VK_KHR_get_memory_requirements2 (device extension)
  298. - VK_KHR_dedicated_allocation (device extension)
  299. When this flag is set, you can experience following warnings reported by Vulkan
  300. validation layer. You can ignore them.
  301. > vkBindBufferMemory(): Binding memory to buffer 0x2d but vkGetBufferMemoryRequirements() has not been called on that buffer.
  302. */
  303. VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT = 0x00000002,
  304. /**
  305. Enables usage of VK_KHR_bind_memory2 extension.
  306. The flag works only if VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_0`.
  307. When it is `VK_API_VERSION_1_1`, the flag is ignored because the extension has been promoted to Vulkan 1.1.
  308. You may set this flag only if you found out that this device extension is supported,
  309. you enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device,
  310. and you want it to be used internally by this library.
  311. The extension provides functions `vkBindBufferMemory2KHR` and `vkBindImageMemory2KHR`,
  312. which allow to pass a chain of `pNext` structures while binding.
  313. This flag is required if you use `pNext` parameter in vmaBindBufferMemory2() or vmaBindImageMemory2().
  314. */
  315. VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT = 0x00000004,
  316. /**
  317. Enables usage of VK_EXT_memory_budget extension.
  318. You may set this flag only if you found out that this device extension is supported,
  319. you enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device,
  320. and you want it to be used internally by this library, along with another instance extension
  321. VK_KHR_get_physical_device_properties2, which is required by it (or Vulkan 1.1, where this extension is promoted).
  322. The extension provides query for current memory usage and budget, which will probably
  323. be more accurate than an estimation used by the library otherwise.
  324. */
  325. VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT = 0x00000008,
  326. /**
  327. Enables usage of VK_AMD_device_coherent_memory extension.
  328. You may set this flag only if you:
  329. - found out that this device extension is supported and enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device,
  330. - checked that `VkPhysicalDeviceCoherentMemoryFeaturesAMD::deviceCoherentMemory` is true and set it while creating the Vulkan device,
  331. - want it to be used internally by this library.
  332. The extension and accompanying device feature provide access to memory types with
  333. `VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD` and `VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` flags.
  334. They are useful mostly for writing breadcrumb markers - a common method for debugging GPU crash/hang/TDR.
  335. When the extension is not enabled, such memory types are still enumerated, but their usage is illegal.
  336. To protect from this error, if you don't create the allocator with this flag, it will refuse to allocate any memory or create a custom pool in such memory type,
  337. returning `VK_ERROR_FEATURE_NOT_PRESENT`.
  338. */
  339. VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT = 0x00000010,
  340. /**
  341. Enables usage of "buffer device address" feature, which allows you to use function
  342. `vkGetBufferDeviceAddress*` to get raw GPU pointer to a buffer and pass it for usage inside a shader.
  343. You may set this flag only if you:
  344. 1. (For Vulkan version < 1.2) Found as available and enabled device extension
  345. VK_KHR_buffer_device_address.
  346. This extension is promoted to core Vulkan 1.2.
  347. 2. Found as available and enabled device feature `VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress`.
  348. When this flag is set, you can create buffers with `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT` using VMA.
  349. The library automatically adds `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT` to
  350. allocated memory blocks wherever it might be needed.
  351. For more information, see documentation chapter \ref enabling_buffer_device_address.
  352. */
  353. VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT = 0x00000020,
  354. /**
  355. Enables usage of VK_EXT_memory_priority extension in the library.
  356. You may set this flag only if you found available and enabled this device extension,
  357. along with `VkPhysicalDeviceMemoryPriorityFeaturesEXT::memoryPriority == VK_TRUE`,
  358. while creating Vulkan device passed as VmaAllocatorCreateInfo::device.
  359. When this flag is used, VmaAllocationCreateInfo::priority and VmaPoolCreateInfo::priority
  360. are used to set priorities of allocated Vulkan memory. Without it, these variables are ignored.
  361. A priority must be a floating-point value between 0 and 1, indicating the priority of the allocation relative to other memory allocations.
  362. Larger values are higher priority. The granularity of the priorities is implementation-dependent.
  363. It is automatically passed to every call to `vkAllocateMemory` done by the library using structure `VkMemoryPriorityAllocateInfoEXT`.
  364. The value to be used for default priority is 0.5.
  365. For more details, see the documentation of the VK_EXT_memory_priority extension.
  366. */
  367. VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT = 0x00000040,
  368. VMA_ALLOCATOR_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  369. } VmaAllocatorCreateFlagBits;
  370. /// See #VmaAllocatorCreateFlagBits.
  371. typedef VkFlags VmaAllocatorCreateFlags;
  372. /** @} */
  373. /**
  374. \addtogroup group_alloc
  375. @{
  376. */
  377. /// \brief Intended usage of the allocated memory.
  378. typedef enum VmaMemoryUsage
  379. {
  380. /** No intended memory usage specified.
  381. Use other members of VmaAllocationCreateInfo to specify your requirements.
  382. */
  383. VMA_MEMORY_USAGE_UNKNOWN = 0,
  384. /**
  385. \deprecated Obsolete, preserved for backward compatibility.
  386. Prefers `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`.
  387. */
  388. VMA_MEMORY_USAGE_GPU_ONLY = 1,
  389. /**
  390. \deprecated Obsolete, preserved for backward compatibility.
  391. Guarantees `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` and `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT`.
  392. */
  393. VMA_MEMORY_USAGE_CPU_ONLY = 2,
  394. /**
  395. \deprecated Obsolete, preserved for backward compatibility.
  396. Guarantees `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`, prefers `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`.
  397. */
  398. VMA_MEMORY_USAGE_CPU_TO_GPU = 3,
  399. /**
  400. \deprecated Obsolete, preserved for backward compatibility.
  401. Guarantees `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`, prefers `VK_MEMORY_PROPERTY_HOST_CACHED_BIT`.
  402. */
  403. VMA_MEMORY_USAGE_GPU_TO_CPU = 4,
  404. /**
  405. \deprecated Obsolete, preserved for backward compatibility.
  406. Prefers not `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`.
  407. */
  408. VMA_MEMORY_USAGE_CPU_COPY = 5,
  409. /**
  410. Lazily allocated GPU memory having `VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT`.
  411. Exists mostly on mobile platforms. Using it on desktop PC or other GPUs with no such memory type present will fail the allocation.
  412. Usage: Memory for transient attachment images (color attachments, depth attachments etc.), created with `VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT`.
  413. Allocations with this usage are always created as dedicated - it implies #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  414. */
  415. VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED = 6,
  416. /**
  417. Selects best memory type automatically.
  418. This flag is recommended for most common use cases.
  419. When using this flag, if you want to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT),
  420. you must pass one of the flags: #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT
  421. in VmaAllocationCreateInfo::flags.
  422. It can be used only with functions that let the library know `VkBufferCreateInfo` or `VkImageCreateInfo`, e.g.
  423. vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo()
  424. and not with generic memory allocation functions.
  425. */
  426. VMA_MEMORY_USAGE_AUTO = 7,
  427. /**
  428. Selects best memory type automatically with preference for GPU (device) memory.
  429. When using this flag, if you want to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT),
  430. you must pass one of the flags: #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT
  431. in VmaAllocationCreateInfo::flags.
  432. It can be used only with functions that let the library know `VkBufferCreateInfo` or `VkImageCreateInfo`, e.g.
  433. vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo()
  434. and not with generic memory allocation functions.
  435. */
  436. VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE = 8,
  437. /**
  438. Selects best memory type automatically with preference for CPU (host) memory.
  439. When using this flag, if you want to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT),
  440. you must pass one of the flags: #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT
  441. in VmaAllocationCreateInfo::flags.
  442. It can be used only with functions that let the library know `VkBufferCreateInfo` or `VkImageCreateInfo`, e.g.
  443. vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo()
  444. and not with generic memory allocation functions.
  445. */
  446. VMA_MEMORY_USAGE_AUTO_PREFER_HOST = 9,
  447. VMA_MEMORY_USAGE_MAX_ENUM = 0x7FFFFFFF
  448. } VmaMemoryUsage;
  449. /// Flags to be passed as VmaAllocationCreateInfo::flags.
  450. typedef enum VmaAllocationCreateFlagBits
  451. {
  452. /** \brief Set this flag if the allocation should have its own memory block.
  453. Use it for special, big resources, like fullscreen images used as attachments.
  454. */
  455. VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT = 0x00000001,
  456. /** \brief Set this flag to only try to allocate from existing `VkDeviceMemory` blocks and never create new such block.
  457. If new allocation cannot be placed in any of the existing blocks, allocation
  458. fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY` error.
  459. You should not use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT and
  460. #VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT at the same time. It makes no sense.
  461. */
  462. VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT = 0x00000002,
  463. /** \brief Set this flag to use a memory that will be persistently mapped and retrieve pointer to it.
  464. Pointer to mapped memory will be returned through VmaAllocationInfo::pMappedData.
  465. It is valid to use this flag for allocation made from memory type that is not
  466. `HOST_VISIBLE`. This flag is then ignored and memory is not mapped. This is
  467. useful if you need an allocation that is efficient to use on GPU
  468. (`DEVICE_LOCAL`) and still want to map it directly if possible on platforms that
  469. support it (e.g. Intel GPU).
  470. */
  471. VMA_ALLOCATION_CREATE_MAPPED_BIT = 0x00000004,
  472. /** \deprecated Preserved for backward compatibility. Consider using vmaSetAllocationName() instead.
  473. Set this flag to treat VmaAllocationCreateInfo::pUserData as pointer to a
  474. null-terminated string. Instead of copying pointer value, a local copy of the
  475. string is made and stored in allocation's `pName`. The string is automatically
  476. freed together with the allocation. It is also used in vmaBuildStatsString().
  477. */
  478. VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT = 0x00000020,
  479. /** Allocation will be created from upper stack in a double stack pool.
  480. This flag is only allowed for custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT flag.
  481. */
  482. VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT = 0x00000040,
  483. /** Create both buffer/image and allocation, but don't bind them together.
  484. It is useful when you want to bind yourself to do some more advanced binding, e.g. using some extensions.
  485. The flag is meaningful only with functions that bind by default: vmaCreateBuffer(), vmaCreateImage().
  486. Otherwise it is ignored.
  487. If you want to make sure the new buffer/image is not tied to the new memory allocation
  488. through `VkMemoryDedicatedAllocateInfoKHR` structure in case the allocation ends up in its own memory block,
  489. use also flag #VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT.
  490. */
  491. VMA_ALLOCATION_CREATE_DONT_BIND_BIT = 0x00000080,
  492. /** Create allocation only if additional device memory required for it, if any, won't exceed
  493. memory budget. Otherwise return `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  494. */
  495. VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT = 0x00000100,
  496. /** \brief Set this flag if the allocated memory will have aliasing resources.
  497. Usage of this flag prevents supplying `VkMemoryDedicatedAllocateInfoKHR` when #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT is specified.
  498. Otherwise created dedicated memory will not be suitable for aliasing resources, resulting in Vulkan Validation Layer errors.
  499. */
  500. VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT = 0x00000200,
  501. /**
  502. Requests possibility to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT).
  503. - If you use #VMA_MEMORY_USAGE_AUTO or other `VMA_MEMORY_USAGE_AUTO*` value,
  504. you must use this flag to be able to map the allocation. Otherwise, mapping is incorrect.
  505. - If you use other value of #VmaMemoryUsage, this flag is ignored and mapping is always possible in memory types that are `HOST_VISIBLE`.
  506. This includes allocations created in \ref custom_memory_pools.
  507. Declares that mapped memory will only be written sequentially, e.g. using `memcpy()` or a loop writing number-by-number,
  508. never read or accessed randomly, so a memory type can be selected that is uncached and write-combined.
  509. \warning Violating this declaration may work correctly, but will likely be very slow.
  510. Watch out for implicit reads introduced by doing e.g. `pMappedData[i] += x;`
  511. Better prepare your data in a local variable and `memcpy()` it to the mapped pointer all at once.
  512. */
  513. VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT = 0x00000400,
  514. /**
  515. Requests possibility to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT).
  516. - If you use #VMA_MEMORY_USAGE_AUTO or other `VMA_MEMORY_USAGE_AUTO*` value,
  517. you must use this flag to be able to map the allocation. Otherwise, mapping is incorrect.
  518. - If you use other value of #VmaMemoryUsage, this flag is ignored and mapping is always possible in memory types that are `HOST_VISIBLE`.
  519. This includes allocations created in \ref custom_memory_pools.
  520. Declares that mapped memory can be read, written, and accessed in random order,
  521. so a `HOST_CACHED` memory type is required.
  522. */
  523. VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT = 0x00000800,
  524. /**
  525. Together with #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT,
  526. it says that despite request for host access, a not-`HOST_VISIBLE` memory type can be selected
  527. if it may improve performance.
  528. By using this flag, you declare that you will check if the allocation ended up in a `HOST_VISIBLE` memory type
  529. (e.g. using vmaGetAllocationMemoryProperties()) and if not, you will create some "staging" buffer and
  530. issue an explicit transfer to write/read your data.
  531. To prepare for this possibility, don't forget to add appropriate flags like
  532. `VK_BUFFER_USAGE_TRANSFER_DST_BIT`, `VK_BUFFER_USAGE_TRANSFER_SRC_BIT` to the parameters of created buffer or image.
  533. */
  534. VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT = 0x00001000,
  535. /** Allocation strategy that chooses smallest possible free range for the allocation
  536. to minimize memory usage and fragmentation, possibly at the expense of allocation time.
  537. */
  538. VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT = 0x00010000,
  539. /** Allocation strategy that chooses first suitable free range for the allocation -
  540. not necessarily in terms of the smallest offset but the one that is easiest and fastest to find
  541. to minimize allocation time, possibly at the expense of allocation quality.
  542. */
  543. VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT = 0x00020000,
  544. /** Allocation strategy that chooses always the lowest offset in available space.
  545. This is not the most efficient strategy but achieves highly packed data.
  546. Used internally by defragmentation, not recommended in typical usage.
  547. */
  548. VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT = 0x00040000,
  549. /** Alias to #VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT.
  550. */
  551. VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT,
  552. /** Alias to #VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT.
  553. */
  554. VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT,
  555. /** A bit mask to extract only `STRATEGY` bits from entire set of flags.
  556. */
  557. VMA_ALLOCATION_CREATE_STRATEGY_MASK =
  558. VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT |
  559. VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT |
  560. VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT,
  561. VMA_ALLOCATION_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  562. } VmaAllocationCreateFlagBits;
  563. /// See #VmaAllocationCreateFlagBits.
  564. typedef VkFlags VmaAllocationCreateFlags;
  565. /// Flags to be passed as VmaPoolCreateInfo::flags.
  566. typedef enum VmaPoolCreateFlagBits
  567. {
  568. /** \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.
  569. This is an optional optimization flag.
  570. If you always allocate using vmaCreateBuffer(), vmaCreateImage(),
  571. vmaAllocateMemoryForBuffer(), then you don't need to use it because allocator
  572. knows exact type of your allocations so it can handle Buffer-Image Granularity
  573. in the optimal way.
  574. If you also allocate using vmaAllocateMemoryForImage() or vmaAllocateMemory(),
  575. exact type of such allocations is not known, so allocator must be conservative
  576. in handling Buffer-Image Granularity, which can lead to suboptimal allocation
  577. (wasted memory). In that case, if you can make sure you always allocate only
  578. buffers and linear images or only optimal images out of this pool, use this flag
  579. to make allocator disregard Buffer-Image Granularity and so make allocations
  580. faster and more optimal.
  581. */
  582. VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT = 0x00000002,
  583. /** \brief Enables alternative, linear allocation algorithm in this pool.
  584. Specify this flag to enable linear allocation algorithm, which always creates
  585. new allocations after last one and doesn't reuse space from allocations freed in
  586. between. It trades memory consumption for simplified algorithm and data
  587. structure, which has better performance and uses less memory for metadata.
  588. By using this flag, you can achieve behavior of free-at-once, stack,
  589. ring buffer, and double stack.
  590. For details, see documentation chapter \ref linear_algorithm.
  591. */
  592. VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT = 0x00000004,
  593. /** Bit mask to extract only `ALGORITHM` bits from entire set of flags.
  594. */
  595. VMA_POOL_CREATE_ALGORITHM_MASK =
  596. VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT,
  597. VMA_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  598. } VmaPoolCreateFlagBits;
  599. /// Flags to be passed as VmaPoolCreateInfo::flags. See #VmaPoolCreateFlagBits.
  600. typedef VkFlags VmaPoolCreateFlags;
  601. /// Flags to be passed as VmaDefragmentationInfo::flags.
  602. typedef enum VmaDefragmentationFlagBits
  603. {
  604. /* \brief Use simple but fast algorithm for defragmentation.
  605. May not achieve best results but will require least time to compute and least allocations to copy.
  606. */
  607. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT = 0x1,
  608. /* \brief Default defragmentation algorithm, applied also when no `ALGORITHM` flag is specified.
  609. Offers a balance between defragmentation quality and the amount of allocations and bytes that need to be moved.
  610. */
  611. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT = 0x2,
  612. /* \brief Perform full defragmentation of memory.
  613. Can result in notably more time to compute and allocations to copy, but will achieve best memory packing.
  614. */
  615. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT = 0x4,
  616. /** \brief Use the most roboust algorithm at the cost of time to compute and number of copies to make.
  617. Only available when bufferImageGranularity is greater than 1, since it aims to reduce
  618. alignment issues between different types of resources.
  619. Otherwise falls back to same behavior as #VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT.
  620. */
  621. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT = 0x8,
  622. /// A bit mask to extract only `ALGORITHM` bits from entire set of flags.
  623. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_MASK =
  624. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT |
  625. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT |
  626. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT |
  627. VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT,
  628. VMA_DEFRAGMENTATION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  629. } VmaDefragmentationFlagBits;
  630. /// See #VmaDefragmentationFlagBits.
  631. typedef VkFlags VmaDefragmentationFlags;
  632. /// Operation performed on single defragmentation move. See structure #VmaDefragmentationMove.
  633. typedef enum VmaDefragmentationMoveOperation
  634. {
  635. /// Buffer/image has been recreated at `dstTmpAllocation`, data has been copied, old buffer/image has been destroyed. `srcAllocation` should be changed to point to the new place. This is the default value set by vmaBeginDefragmentationPass().
  636. VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY = 0,
  637. /// Set this value if you cannot move the allocation. New place reserved at `dstTmpAllocation` will be freed. `srcAllocation` will remain unchanged.
  638. VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE = 1,
  639. /// Set this value if you decide to abandon the allocation and you destroyed the buffer/image. New place reserved at `dstTmpAllocation` will be freed, along with `srcAllocation`, which will be destroyed.
  640. VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY = 2,
  641. } VmaDefragmentationMoveOperation;
  642. /** @} */
  643. /**
  644. \addtogroup group_virtual
  645. @{
  646. */
  647. /// Flags to be passed as VmaVirtualBlockCreateInfo::flags.
  648. typedef enum VmaVirtualBlockCreateFlagBits
  649. {
  650. /** \brief Enables alternative, linear allocation algorithm in this virtual block.
  651. Specify this flag to enable linear allocation algorithm, which always creates
  652. new allocations after last one and doesn't reuse space from allocations freed in
  653. between. It trades memory consumption for simplified algorithm and data
  654. structure, which has better performance and uses less memory for metadata.
  655. By using this flag, you can achieve behavior of free-at-once, stack,
  656. ring buffer, and double stack.
  657. For details, see documentation chapter \ref linear_algorithm.
  658. */
  659. VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT = 0x00000001,
  660. /** \brief Bit mask to extract only `ALGORITHM` bits from entire set of flags.
  661. */
  662. VMA_VIRTUAL_BLOCK_CREATE_ALGORITHM_MASK =
  663. VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT,
  664. VMA_VIRTUAL_BLOCK_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  665. } VmaVirtualBlockCreateFlagBits;
  666. /// Flags to be passed as VmaVirtualBlockCreateInfo::flags. See #VmaVirtualBlockCreateFlagBits.
  667. typedef VkFlags VmaVirtualBlockCreateFlags;
  668. /// Flags to be passed as VmaVirtualAllocationCreateInfo::flags.
  669. typedef enum VmaVirtualAllocationCreateFlagBits
  670. {
  671. /** \brief Allocation will be created from upper stack in a double stack pool.
  672. This flag is only allowed for virtual blocks created with #VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT flag.
  673. */
  674. VMA_VIRTUAL_ALLOCATION_CREATE_UPPER_ADDRESS_BIT = VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT,
  675. /** \brief Allocation strategy that tries to minimize memory usage.
  676. */
  677. VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT,
  678. /** \brief Allocation strategy that tries to minimize allocation time.
  679. */
  680. VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT,
  681. /** Allocation strategy that chooses always the lowest offset in available space.
  682. This is not the most efficient strategy but achieves highly packed data.
  683. */
  684. VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT,
  685. /** \brief A bit mask to extract only `STRATEGY` bits from entire set of flags.
  686. These strategy flags are binary compatible with equivalent flags in #VmaAllocationCreateFlagBits.
  687. */
  688. VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MASK = VMA_ALLOCATION_CREATE_STRATEGY_MASK,
  689. VMA_VIRTUAL_ALLOCATION_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
  690. } VmaVirtualAllocationCreateFlagBits;
  691. /// Flags to be passed as VmaVirtualAllocationCreateInfo::flags. See #VmaVirtualAllocationCreateFlagBits.
  692. typedef VkFlags VmaVirtualAllocationCreateFlags;
  693. /** @} */
  694. #endif // _VMA_ENUM_DECLARATIONS
  695. #ifndef _VMA_DATA_TYPES_DECLARATIONS
  696. /**
  697. \addtogroup group_init
  698. @{ */
  699. /** \struct VmaAllocator
  700. \brief Represents main object of this library initialized.
  701. Fill structure #VmaAllocatorCreateInfo and call function vmaCreateAllocator() to create it.
  702. Call function vmaDestroyAllocator() to destroy it.
  703. It is recommended to create just one object of this type per `VkDevice` object,
  704. right after Vulkan is initialized and keep it alive until before Vulkan device is destroyed.
  705. */
  706. VK_DEFINE_HANDLE(VmaAllocator)
  707. /** @} */
  708. /**
  709. \addtogroup group_alloc
  710. @{
  711. */
  712. /** \struct VmaPool
  713. \brief Represents custom memory pool
  714. Fill structure VmaPoolCreateInfo and call function vmaCreatePool() to create it.
  715. Call function vmaDestroyPool() to destroy it.
  716. For more information see [Custom memory pools](@ref choosing_memory_type_custom_memory_pools).
  717. */
  718. VK_DEFINE_HANDLE(VmaPool)
  719. /** \struct VmaAllocation
  720. \brief Represents single memory allocation.
  721. It may be either dedicated block of `VkDeviceMemory` or a specific region of a bigger block of this type
  722. plus unique offset.
  723. There are multiple ways to create such object.
  724. You need to fill structure VmaAllocationCreateInfo.
  725. For more information see [Choosing memory type](@ref choosing_memory_type).
  726. Although the library provides convenience functions that create Vulkan buffer or image,
  727. allocate memory for it and bind them together,
  728. binding of the allocation to a buffer or an image is out of scope of the allocation itself.
  729. Allocation object can exist without buffer/image bound,
  730. binding can be done manually by the user, and destruction of it can be done
  731. independently of destruction of the allocation.
  732. The object also remembers its size and some other information.
  733. To retrieve this information, use function vmaGetAllocationInfo() and inspect
  734. returned structure VmaAllocationInfo.
  735. */
  736. VK_DEFINE_HANDLE(VmaAllocation)
  737. /** \struct VmaDefragmentationContext
  738. \brief An opaque object that represents started defragmentation process.
  739. Fill structure #VmaDefragmentationInfo and call function vmaBeginDefragmentation() to create it.
  740. Call function vmaEndDefragmentation() to destroy it.
  741. */
  742. VK_DEFINE_HANDLE(VmaDefragmentationContext)
  743. /** @} */
  744. /**
  745. \addtogroup group_virtual
  746. @{
  747. */
  748. /** \struct VmaVirtualAllocation
  749. \brief Represents single memory allocation done inside VmaVirtualBlock.
  750. Use it as a unique identifier to virtual allocation within the single block.
  751. Use value `VK_NULL_HANDLE` to represent a null/invalid allocation.
  752. */
  753. VK_DEFINE_NON_DISPATCHABLE_HANDLE(VmaVirtualAllocation)
  754. /** @} */
  755. /**
  756. \addtogroup group_virtual
  757. @{
  758. */
  759. /** \struct VmaVirtualBlock
  760. \brief Handle to a virtual block object that allows to use core allocation algorithm without allocating any real GPU memory.
  761. Fill in #VmaVirtualBlockCreateInfo structure and use vmaCreateVirtualBlock() to create it. Use vmaDestroyVirtualBlock() to destroy it.
  762. For more information, see documentation chapter \ref virtual_allocator.
  763. This object is not thread-safe - should not be used from multiple threads simultaneously, must be synchronized externally.
  764. */
  765. VK_DEFINE_HANDLE(VmaVirtualBlock)
  766. /** @} */
  767. /**
  768. \addtogroup group_init
  769. @{
  770. */
  771. /// Callback function called after successful vkAllocateMemory.
  772. typedef void (VKAPI_PTR* PFN_vmaAllocateDeviceMemoryFunction)(
  773. VmaAllocator VMA_NOT_NULL allocator,
  774. uint32_t memoryType,
  775. VkDeviceMemory VMA_NOT_NULL_NON_DISPATCHABLE memory,
  776. VkDeviceSize size,
  777. void* VMA_NULLABLE pUserData);
  778. /// Callback function called before vkFreeMemory.
  779. typedef void (VKAPI_PTR* PFN_vmaFreeDeviceMemoryFunction)(
  780. VmaAllocator VMA_NOT_NULL allocator,
  781. uint32_t memoryType,
  782. VkDeviceMemory VMA_NOT_NULL_NON_DISPATCHABLE memory,
  783. VkDeviceSize size,
  784. void* VMA_NULLABLE pUserData);
  785. /** \brief Set of callbacks that the library will call for `vkAllocateMemory` and `vkFreeMemory`.
  786. Provided for informative purpose, e.g. to gather statistics about number of
  787. allocations or total amount of memory allocated in Vulkan.
  788. Used in VmaAllocatorCreateInfo::pDeviceMemoryCallbacks.
  789. */
  790. typedef struct VmaDeviceMemoryCallbacks
  791. {
  792. /// Optional, can be null.
  793. PFN_vmaAllocateDeviceMemoryFunction VMA_NULLABLE pfnAllocate;
  794. /// Optional, can be null.
  795. PFN_vmaFreeDeviceMemoryFunction VMA_NULLABLE pfnFree;
  796. /// Optional, can be null.
  797. void* VMA_NULLABLE pUserData;
  798. } VmaDeviceMemoryCallbacks;
  799. /** \brief Pointers to some Vulkan functions - a subset used by the library.
  800. Used in VmaAllocatorCreateInfo::pVulkanFunctions.
  801. */
  802. typedef struct VmaVulkanFunctions
  803. {
  804. /// Required when using VMA_DYNAMIC_VULKAN_FUNCTIONS.
  805. PFN_vkGetInstanceProcAddr VMA_NULLABLE vkGetInstanceProcAddr;
  806. /// Required when using VMA_DYNAMIC_VULKAN_FUNCTIONS.
  807. PFN_vkGetDeviceProcAddr VMA_NULLABLE vkGetDeviceProcAddr;
  808. PFN_vkGetPhysicalDeviceProperties VMA_NULLABLE vkGetPhysicalDeviceProperties;
  809. PFN_vkGetPhysicalDeviceMemoryProperties VMA_NULLABLE vkGetPhysicalDeviceMemoryProperties;
  810. PFN_vkAllocateMemory VMA_NULLABLE vkAllocateMemory;
  811. PFN_vkFreeMemory VMA_NULLABLE vkFreeMemory;
  812. PFN_vkMapMemory VMA_NULLABLE vkMapMemory;
  813. PFN_vkUnmapMemory VMA_NULLABLE vkUnmapMemory;
  814. PFN_vkFlushMappedMemoryRanges VMA_NULLABLE vkFlushMappedMemoryRanges;
  815. PFN_vkInvalidateMappedMemoryRanges VMA_NULLABLE vkInvalidateMappedMemoryRanges;
  816. PFN_vkBindBufferMemory VMA_NULLABLE vkBindBufferMemory;
  817. PFN_vkBindImageMemory VMA_NULLABLE vkBindImageMemory;
  818. PFN_vkGetBufferMemoryRequirements VMA_NULLABLE vkGetBufferMemoryRequirements;
  819. PFN_vkGetImageMemoryRequirements VMA_NULLABLE vkGetImageMemoryRequirements;
  820. PFN_vkCreateBuffer VMA_NULLABLE vkCreateBuffer;
  821. PFN_vkDestroyBuffer VMA_NULLABLE vkDestroyBuffer;
  822. PFN_vkCreateImage VMA_NULLABLE vkCreateImage;
  823. PFN_vkDestroyImage VMA_NULLABLE vkDestroyImage;
  824. PFN_vkCmdCopyBuffer VMA_NULLABLE vkCmdCopyBuffer;
  825. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  826. /// Fetch "vkGetBufferMemoryRequirements2" on Vulkan >= 1.1, fetch "vkGetBufferMemoryRequirements2KHR" when using VK_KHR_dedicated_allocation extension.
  827. PFN_vkGetBufferMemoryRequirements2KHR VMA_NULLABLE vkGetBufferMemoryRequirements2KHR;
  828. /// Fetch "vkGetImageMemoryRequirements2" on Vulkan >= 1.1, fetch "vkGetImageMemoryRequirements2KHR" when using VK_KHR_dedicated_allocation extension.
  829. PFN_vkGetImageMemoryRequirements2KHR VMA_NULLABLE vkGetImageMemoryRequirements2KHR;
  830. #endif
  831. #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000
  832. /// Fetch "vkBindBufferMemory2" on Vulkan >= 1.1, fetch "vkBindBufferMemory2KHR" when using VK_KHR_bind_memory2 extension.
  833. PFN_vkBindBufferMemory2KHR VMA_NULLABLE vkBindBufferMemory2KHR;
  834. /// Fetch "vkBindImageMemory2" on Vulkan >= 1.1, fetch "vkBindImageMemory2KHR" when using VK_KHR_bind_memory2 extension.
  835. PFN_vkBindImageMemory2KHR VMA_NULLABLE vkBindImageMemory2KHR;
  836. #endif
  837. #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000
  838. PFN_vkGetPhysicalDeviceMemoryProperties2KHR VMA_NULLABLE vkGetPhysicalDeviceMemoryProperties2KHR;
  839. #endif
  840. #if VMA_VULKAN_VERSION >= 1003000
  841. /// Fetch from "vkGetDeviceBufferMemoryRequirements" on Vulkan >= 1.3, but you can also fetch it from "vkGetDeviceBufferMemoryRequirementsKHR" if you enabled extension VK_KHR_maintenance4.
  842. PFN_vkGetDeviceBufferMemoryRequirements VMA_NULLABLE vkGetDeviceBufferMemoryRequirements;
  843. /// Fetch from "vkGetDeviceImageMemoryRequirements" on Vulkan >= 1.3, but you can also fetch it from "vkGetDeviceImageMemoryRequirementsKHR" if you enabled extension VK_KHR_maintenance4.
  844. PFN_vkGetDeviceImageMemoryRequirements VMA_NULLABLE vkGetDeviceImageMemoryRequirements;
  845. #endif
  846. } VmaVulkanFunctions;
  847. /// Description of a Allocator to be created.
  848. typedef struct VmaAllocatorCreateInfo
  849. {
  850. /// Flags for created allocator. Use #VmaAllocatorCreateFlagBits enum.
  851. VmaAllocatorCreateFlags flags;
  852. /// Vulkan physical device.
  853. /** It must be valid throughout whole lifetime of created allocator. */
  854. VkPhysicalDevice VMA_NOT_NULL physicalDevice;
  855. /// Vulkan device.
  856. /** It must be valid throughout whole lifetime of created allocator. */
  857. VkDevice VMA_NOT_NULL device;
  858. /// Preferred size of a single `VkDeviceMemory` block to be allocated from large heaps > 1 GiB. Optional.
  859. /** Set to 0 to use default, which is currently 256 MiB. */
  860. VkDeviceSize preferredLargeHeapBlockSize;
  861. /// Custom CPU memory allocation callbacks. Optional.
  862. /** Optional, can be null. When specified, will also be used for all CPU-side memory allocations. */
  863. const VkAllocationCallbacks* VMA_NULLABLE pAllocationCallbacks;
  864. /// Informative callbacks for `vkAllocateMemory`, `vkFreeMemory`. Optional.
  865. /** Optional, can be null. */
  866. const VmaDeviceMemoryCallbacks* VMA_NULLABLE pDeviceMemoryCallbacks;
  867. /** \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.
  868. If not NULL, it must be a pointer to an array of
  869. `VkPhysicalDeviceMemoryProperties::memoryHeapCount` elements, defining limit on
  870. maximum number of bytes that can be allocated out of particular Vulkan memory
  871. heap.
  872. Any of the elements may be equal to `VK_WHOLE_SIZE`, which means no limit on that
  873. heap. This is also the default in case of `pHeapSizeLimit` = NULL.
  874. If there is a limit defined for a heap:
  875. - If user tries to allocate more memory from that heap using this allocator,
  876. the allocation fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  877. - If the limit is smaller than heap size reported in `VkMemoryHeap::size`, the
  878. value of this limit will be reported instead when using vmaGetMemoryProperties().
  879. Warning! Using this feature may not be equivalent to installing a GPU with
  880. smaller amount of memory, because graphics driver doesn't necessary fail new
  881. allocations with `VK_ERROR_OUT_OF_DEVICE_MEMORY` result when memory capacity is
  882. exceeded. It may return success and just silently migrate some device memory
  883. blocks to system RAM. This driver behavior can also be controlled using
  884. VK_AMD_memory_overallocation_behavior extension.
  885. */
  886. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryHeapCount") pHeapSizeLimit;
  887. /** \brief Pointers to Vulkan functions. Can be null.
  888. For details see [Pointers to Vulkan functions](@ref config_Vulkan_functions).
  889. */
  890. const VmaVulkanFunctions* VMA_NULLABLE pVulkanFunctions;
  891. /** \brief Handle to Vulkan instance object.
  892. Starting from version 3.0.0 this member is no longer optional, it must be set!
  893. */
  894. VkInstance VMA_NOT_NULL instance;
  895. /** \brief Optional. The highest version of Vulkan that the application is designed to use.
  896. 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`.
  897. The patch version number specified is ignored. Only the major and minor versions are considered.
  898. It must be less or equal (preferably equal) to value as passed to `vkCreateInstance` as `VkApplicationInfo::apiVersion`.
  899. Only versions 1.0, 1.1, 1.2, 1.3 are supported by the current implementation.
  900. Leaving it initialized to zero is equivalent to `VK_API_VERSION_1_0`.
  901. */
  902. uint32_t vulkanApiVersion;
  903. #if VMA_EXTERNAL_MEMORY
  904. /** \brief Either null or a pointer to an array of external memory handle types for each Vulkan memory type.
  905. If not NULL, it must be a pointer to an array of `VkPhysicalDeviceMemoryProperties::memoryTypeCount`
  906. elements, defining external memory handle types of particular Vulkan memory type,
  907. to be passed using `VkExportMemoryAllocateInfoKHR`.
  908. Any of the elements may be equal to 0, which means not to use `VkExportMemoryAllocateInfoKHR` on this memory type.
  909. This is also the default in case of `pTypeExternalMemoryHandleTypes` = NULL.
  910. */
  911. const VkExternalMemoryHandleTypeFlagsKHR* VMA_NULLABLE VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryTypeCount") pTypeExternalMemoryHandleTypes;
  912. #endif // #if VMA_EXTERNAL_MEMORY
  913. } VmaAllocatorCreateInfo;
  914. /// Information about existing #VmaAllocator object.
  915. typedef struct VmaAllocatorInfo
  916. {
  917. /** \brief Handle to Vulkan instance object.
  918. This is the same value as has been passed through VmaAllocatorCreateInfo::instance.
  919. */
  920. VkInstance VMA_NOT_NULL instance;
  921. /** \brief Handle to Vulkan physical device object.
  922. This is the same value as has been passed through VmaAllocatorCreateInfo::physicalDevice.
  923. */
  924. VkPhysicalDevice VMA_NOT_NULL physicalDevice;
  925. /** \brief Handle to Vulkan device object.
  926. This is the same value as has been passed through VmaAllocatorCreateInfo::device.
  927. */
  928. VkDevice VMA_NOT_NULL device;
  929. } VmaAllocatorInfo;
  930. /** @} */
  931. /**
  932. \addtogroup group_stats
  933. @{
  934. */
  935. /** \brief Calculated statistics of memory usage e.g. in a specific memory type, heap, custom pool, or total.
  936. These are fast to calculate.
  937. See functions: vmaGetHeapBudgets(), vmaGetPoolStatistics().
  938. */
  939. typedef struct VmaStatistics
  940. {
  941. /** \brief Number of `VkDeviceMemory` objects - Vulkan memory blocks allocated.
  942. */
  943. uint32_t blockCount;
  944. /** \brief Number of #VmaAllocation objects allocated.
  945. Dedicated allocations have their own blocks, so each one adds 1 to `allocationCount` as well as `blockCount`.
  946. */
  947. uint32_t allocationCount;
  948. /** \brief Number of bytes allocated in `VkDeviceMemory` blocks.
  949. \note To avoid confusion, please be aware that what Vulkan calls an "allocation" - a whole `VkDeviceMemory` object
  950. (e.g. as in `VkPhysicalDeviceLimits::maxMemoryAllocationCount`) is called a "block" in VMA, while VMA calls
  951. "allocation" a #VmaAllocation object that represents a memory region sub-allocated from such block, usually for a single buffer or image.
  952. */
  953. VkDeviceSize blockBytes;
  954. /** \brief Total number of bytes occupied by all #VmaAllocation objects.
  955. Always less or equal than `blockBytes`.
  956. Difference `(blockBytes - allocationBytes)` is the amount of memory allocated from Vulkan
  957. but unused by any #VmaAllocation.
  958. */
  959. VkDeviceSize allocationBytes;
  960. } VmaStatistics;
  961. /** \brief More detailed statistics than #VmaStatistics.
  962. These are slower to calculate. Use for debugging purposes.
  963. See functions: vmaCalculateStatistics(), vmaCalculatePoolStatistics().
  964. Previous version of the statistics API provided averages, but they have been removed
  965. because they can be easily calculated as:
  966. \code
  967. VkDeviceSize allocationSizeAvg = detailedStats.statistics.allocationBytes / detailedStats.statistics.allocationCount;
  968. VkDeviceSize unusedBytes = detailedStats.statistics.blockBytes - detailedStats.statistics.allocationBytes;
  969. VkDeviceSize unusedRangeSizeAvg = unusedBytes / detailedStats.unusedRangeCount;
  970. \endcode
  971. */
  972. typedef struct VmaDetailedStatistics
  973. {
  974. /// Basic statistics.
  975. VmaStatistics statistics;
  976. /// Number of free ranges of memory between allocations.
  977. uint32_t unusedRangeCount;
  978. /// Smallest allocation size. `VK_WHOLE_SIZE` if there are 0 allocations.
  979. VkDeviceSize allocationSizeMin;
  980. /// Largest allocation size. 0 if there are 0 allocations.
  981. VkDeviceSize allocationSizeMax;
  982. /// Smallest empty range size. `VK_WHOLE_SIZE` if there are 0 empty ranges.
  983. VkDeviceSize unusedRangeSizeMin;
  984. /// Largest empty range size. 0 if there are 0 empty ranges.
  985. VkDeviceSize unusedRangeSizeMax;
  986. } VmaDetailedStatistics;
  987. /** \brief General statistics from current state of the Allocator -
  988. total memory usage across all memory heaps and types.
  989. These are slower to calculate. Use for debugging purposes.
  990. See function vmaCalculateStatistics().
  991. */
  992. typedef struct VmaTotalStatistics
  993. {
  994. VmaDetailedStatistics memoryType[VK_MAX_MEMORY_TYPES];
  995. VmaDetailedStatistics memoryHeap[VK_MAX_MEMORY_HEAPS];
  996. VmaDetailedStatistics total;
  997. } VmaTotalStatistics;
  998. /** \brief Statistics of current memory usage and available budget for a specific memory heap.
  999. These are fast to calculate.
  1000. See function vmaGetHeapBudgets().
  1001. */
  1002. typedef struct VmaBudget
  1003. {
  1004. /** \brief Statistics fetched from the library.
  1005. */
  1006. VmaStatistics statistics;
  1007. /** \brief Estimated current memory usage of the program, in bytes.
  1008. Fetched from system using VK_EXT_memory_budget extension if enabled.
  1009. It might be different than `statistics.blockBytes` (usually higher) due to additional implicit objects
  1010. also occupying the memory, like swapchain, pipelines, descriptor heaps, command buffers, or
  1011. `VkDeviceMemory` blocks allocated outside of this library, if any.
  1012. */
  1013. VkDeviceSize usage;
  1014. /** \brief Estimated amount of memory available to the program, in bytes.
  1015. Fetched from system using VK_EXT_memory_budget extension if enabled.
  1016. It might be different (most probably smaller) than `VkMemoryHeap::size[heapIndex]` due to factors
  1017. external to the program, decided by the operating system.
  1018. Difference `budget - usage` is the amount of additional memory that can probably
  1019. be allocated without problems. Exceeding the budget may result in various problems.
  1020. */
  1021. VkDeviceSize budget;
  1022. } VmaBudget;
  1023. /** @} */
  1024. /**
  1025. \addtogroup group_alloc
  1026. @{
  1027. */
  1028. /** \brief Parameters of new #VmaAllocation.
  1029. To be used with functions like vmaCreateBuffer(), vmaCreateImage(), and many others.
  1030. */
  1031. typedef struct VmaAllocationCreateInfo
  1032. {
  1033. /// Use #VmaAllocationCreateFlagBits enum.
  1034. VmaAllocationCreateFlags flags;
  1035. /** \brief Intended usage of memory.
  1036. You can leave #VMA_MEMORY_USAGE_UNKNOWN if you specify memory requirements in other way. \n
  1037. If `pool` is not null, this member is ignored.
  1038. */
  1039. VmaMemoryUsage usage;
  1040. /** \brief Flags that must be set in a Memory Type chosen for an allocation.
  1041. Leave 0 if you specify memory requirements in other way. \n
  1042. If `pool` is not null, this member is ignored.*/
  1043. VkMemoryPropertyFlags requiredFlags;
  1044. /** \brief Flags that preferably should be set in a memory type chosen for an allocation.
  1045. Set to 0 if no additional flags are preferred. \n
  1046. If `pool` is not null, this member is ignored. */
  1047. VkMemoryPropertyFlags preferredFlags;
  1048. /** \brief Bitmask containing one bit set for every memory type acceptable for this allocation.
  1049. Value 0 is equivalent to `UINT32_MAX` - it means any memory type is accepted if
  1050. it meets other requirements specified by this structure, with no further
  1051. restrictions on memory type index. \n
  1052. If `pool` is not null, this member is ignored.
  1053. */
  1054. uint32_t memoryTypeBits;
  1055. /** \brief Pool that this allocation should be created in.
  1056. Leave `VK_NULL_HANDLE` to allocate from default pool. If not null, members:
  1057. `usage`, `requiredFlags`, `preferredFlags`, `memoryTypeBits` are ignored.
  1058. */
  1059. VmaPool VMA_NULLABLE pool;
  1060. /** \brief Custom general-purpose pointer that will be stored in #VmaAllocation, can be read as VmaAllocationInfo::pUserData and changed using vmaSetAllocationUserData().
  1061. If #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT is used, it must be either
  1062. null or pointer to a null-terminated string. The string will be then copied to
  1063. internal buffer, so it doesn't need to be valid after allocation call.
  1064. */
  1065. void* VMA_NULLABLE pUserData;
  1066. /** \brief A floating-point value between 0 and 1, indicating the priority of the allocation relative to other memory allocations.
  1067. It is used only when #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT flag was used during creation of the #VmaAllocator object
  1068. and this allocation ends up as dedicated or is explicitly forced as dedicated using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  1069. Otherwise, it has the priority of a memory block where it is placed and this variable is ignored.
  1070. */
  1071. float priority;
  1072. } VmaAllocationCreateInfo;
  1073. /// Describes parameter of created #VmaPool.
  1074. typedef struct VmaPoolCreateInfo
  1075. {
  1076. /** \brief Vulkan memory type index to allocate this pool from.
  1077. */
  1078. uint32_t memoryTypeIndex;
  1079. /** \brief Use combination of #VmaPoolCreateFlagBits.
  1080. */
  1081. VmaPoolCreateFlags flags;
  1082. /** \brief Size of a single `VkDeviceMemory` block to be allocated as part of this pool, in bytes. Optional.
  1083. Specify nonzero to set explicit, constant size of memory blocks used by this
  1084. pool.
  1085. Leave 0 to use default and let the library manage block sizes automatically.
  1086. Sizes of particular blocks may vary.
  1087. In this case, the pool will also support dedicated allocations.
  1088. */
  1089. VkDeviceSize blockSize;
  1090. /** \brief Minimum number of blocks to be always allocated in this pool, even if they stay empty.
  1091. Set to 0 to have no preallocated blocks and allow the pool be completely empty.
  1092. */
  1093. size_t minBlockCount;
  1094. /** \brief Maximum number of blocks that can be allocated in this pool. Optional.
  1095. Set to 0 to use default, which is `SIZE_MAX`, which means no limit.
  1096. Set to same value as VmaPoolCreateInfo::minBlockCount to have fixed amount of memory allocated
  1097. throughout whole lifetime of this pool.
  1098. */
  1099. size_t maxBlockCount;
  1100. /** \brief A floating-point value between 0 and 1, indicating the priority of the allocations in this pool relative to other memory allocations.
  1101. It is used only when #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT flag was used during creation of the #VmaAllocator object.
  1102. Otherwise, this variable is ignored.
  1103. */
  1104. float priority;
  1105. /** \brief Additional minimum alignment to be used for all allocations created from this pool. Can be 0.
  1106. Leave 0 (default) not to impose any additional alignment. If not 0, it must be a power of two.
  1107. It can be useful in cases where alignment returned by Vulkan by functions like `vkGetBufferMemoryRequirements` is not enough,
  1108. e.g. when doing interop with OpenGL.
  1109. */
  1110. VkDeviceSize minAllocationAlignment;
  1111. /** \brief Additional `pNext` chain to be attached to `VkMemoryAllocateInfo` used for every allocation made by this pool. Optional.
  1112. Optional, can be null. If not null, it must point to a `pNext` chain of structures that can be attached to `VkMemoryAllocateInfo`.
  1113. It can be useful for special needs such as adding `VkExportMemoryAllocateInfoKHR`.
  1114. Structures pointed by this member must remain alive and unchanged for the whole lifetime of the custom pool.
  1115. Please note that some structures, e.g. `VkMemoryPriorityAllocateInfoEXT`, `VkMemoryDedicatedAllocateInfoKHR`,
  1116. can be attached automatically by this library when using other, more convenient of its features.
  1117. */
  1118. void* VMA_NULLABLE VMA_EXTENDS_VK_STRUCT(VkMemoryAllocateInfo) pMemoryAllocateNext;
  1119. } VmaPoolCreateInfo;
  1120. /** @} */
  1121. /**
  1122. \addtogroup group_alloc
  1123. @{
  1124. */
  1125. /// Parameters of #VmaAllocation objects, that can be retrieved using function vmaGetAllocationInfo().
  1126. typedef struct VmaAllocationInfo
  1127. {
  1128. /** \brief Memory type index that this allocation was allocated from.
  1129. It never changes.
  1130. */
  1131. uint32_t memoryType;
  1132. /** \brief Handle to Vulkan memory object.
  1133. Same memory object can be shared by multiple allocations.
  1134. It can change after the allocation is moved during \ref defragmentation.
  1135. */
  1136. VkDeviceMemory VMA_NULLABLE_NON_DISPATCHABLE deviceMemory;
  1137. /** \brief Offset in `VkDeviceMemory` object to the beginning of this allocation, in bytes. `(deviceMemory, offset)` pair is unique to this allocation.
  1138. You usually don't need to use this offset. If you create a buffer or an image together with the allocation using e.g. function
  1139. vmaCreateBuffer(), vmaCreateImage(), functions that operate on these resources refer to the beginning of the buffer or image,
  1140. not entire device memory block. Functions like vmaMapMemory(), vmaBindBufferMemory() also refer to the beginning of the allocation
  1141. and apply this offset automatically.
  1142. It can change after the allocation is moved during \ref defragmentation.
  1143. */
  1144. VkDeviceSize offset;
  1145. /** \brief Size of this allocation, in bytes.
  1146. It never changes.
  1147. \note Allocation size returned in this variable may be greater than the size
  1148. requested for the resource e.g. as `VkBufferCreateInfo::size`. Whole size of the
  1149. allocation is accessible for operations on memory e.g. using a pointer after
  1150. mapping with vmaMapMemory(), but operations on the resource e.g. using
  1151. `vkCmdCopyBuffer` must be limited to the size of the resource.
  1152. */
  1153. VkDeviceSize size;
  1154. /** \brief Pointer to the beginning of this allocation as mapped data.
  1155. If the allocation hasn't been mapped using vmaMapMemory() and hasn't been
  1156. created with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag, this value is null.
  1157. It can change after call to vmaMapMemory(), vmaUnmapMemory().
  1158. It can also change after the allocation is moved during \ref defragmentation.
  1159. */
  1160. void* VMA_NULLABLE pMappedData;
  1161. /** \brief Custom general-purpose pointer that was passed as VmaAllocationCreateInfo::pUserData or set using vmaSetAllocationUserData().
  1162. It can change after call to vmaSetAllocationUserData() for this allocation.
  1163. */
  1164. void* VMA_NULLABLE pUserData;
  1165. /** \brief Custom allocation name that was set with vmaSetAllocationName().
  1166. It can change after call to vmaSetAllocationName() for this allocation.
  1167. Another way to set custom name is to pass it in VmaAllocationCreateInfo::pUserData with
  1168. additional flag #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT set [DEPRECATED].
  1169. */
  1170. const char* VMA_NULLABLE pName;
  1171. } VmaAllocationInfo;
  1172. /** Callback function called during vmaBeginDefragmentation() to check custom criterion about ending current defragmentation pass.
  1173. Should return true if the defragmentation needs to stop current pass.
  1174. */
  1175. typedef VkBool32 (VKAPI_PTR* PFN_vmaCheckDefragmentationBreakFunction)(void* VMA_NULLABLE pUserData);
  1176. /** \brief Parameters for defragmentation.
  1177. To be used with function vmaBeginDefragmentation().
  1178. */
  1179. typedef struct VmaDefragmentationInfo
  1180. {
  1181. /// \brief Use combination of #VmaDefragmentationFlagBits.
  1182. VmaDefragmentationFlags flags;
  1183. /** \brief Custom pool to be defragmented.
  1184. If null then default pools will undergo defragmentation process.
  1185. */
  1186. VmaPool VMA_NULLABLE pool;
  1187. /** \brief Maximum numbers of bytes that can be copied during single pass, while moving allocations to different places.
  1188. `0` means no limit.
  1189. */
  1190. VkDeviceSize maxBytesPerPass;
  1191. /** \brief Maximum number of allocations that can be moved during single pass to a different place.
  1192. `0` means no limit.
  1193. */
  1194. uint32_t maxAllocationsPerPass;
  1195. /** \brief Optional custom callback for stopping vmaBeginDefragmentation().
  1196. Have to return true for breaking current defragmentation pass.
  1197. */
  1198. PFN_vmaCheckDefragmentationBreakFunction VMA_NULLABLE pfnBreakCallback;
  1199. /// \brief Optional data to pass to custom callback for stopping pass of defragmentation.
  1200. void* VMA_NULLABLE pBreakCallbackUserData;
  1201. } VmaDefragmentationInfo;
  1202. /// Single move of an allocation to be done for defragmentation.
  1203. typedef struct VmaDefragmentationMove
  1204. {
  1205. /// Operation to be performed on the allocation by vmaEndDefragmentationPass(). Default value is #VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY. You can modify it.
  1206. VmaDefragmentationMoveOperation operation;
  1207. /// Allocation that should be moved.
  1208. VmaAllocation VMA_NOT_NULL srcAllocation;
  1209. /** \brief Temporary allocation pointing to destination memory that will replace `srcAllocation`.
  1210. \warning Do not store this allocation in your data structures! It exists only temporarily, for the duration of the defragmentation pass,
  1211. to be used for binding new buffer/image to the destination memory using e.g. vmaBindBufferMemory().
  1212. vmaEndDefragmentationPass() will destroy it and make `srcAllocation` point to this memory.
  1213. */
  1214. VmaAllocation VMA_NOT_NULL dstTmpAllocation;
  1215. } VmaDefragmentationMove;
  1216. /** \brief Parameters for incremental defragmentation steps.
  1217. To be used with function vmaBeginDefragmentationPass().
  1218. */
  1219. typedef struct VmaDefragmentationPassMoveInfo
  1220. {
  1221. /// Number of elements in the `pMoves` array.
  1222. uint32_t moveCount;
  1223. /** \brief Array of moves to be performed by the user in the current defragmentation pass.
  1224. Pointer to an array of `moveCount` elements, owned by VMA, created in vmaBeginDefragmentationPass(), destroyed in vmaEndDefragmentationPass().
  1225. For each element, you should:
  1226. 1. Create a new buffer/image in the place pointed by VmaDefragmentationMove::dstMemory + VmaDefragmentationMove::dstOffset.
  1227. 2. Copy data from the VmaDefragmentationMove::srcAllocation e.g. using `vkCmdCopyBuffer`, `vkCmdCopyImage`.
  1228. 3. Make sure these commands finished executing on the GPU.
  1229. 4. Destroy the old buffer/image.
  1230. Only then you can finish defragmentation pass by calling vmaEndDefragmentationPass().
  1231. After this call, the allocation will point to the new place in memory.
  1232. Alternatively, if you cannot move specific allocation, you can set VmaDefragmentationMove::operation to #VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE.
  1233. Alternatively, if you decide you want to completely remove the allocation:
  1234. 1. Destroy its buffer/image.
  1235. 2. Set VmaDefragmentationMove::operation to #VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY.
  1236. Then, after vmaEndDefragmentationPass() the allocation will be freed.
  1237. */
  1238. VmaDefragmentationMove* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(moveCount) pMoves;
  1239. } VmaDefragmentationPassMoveInfo;
  1240. /// Statistics returned for defragmentation process in function vmaEndDefragmentation().
  1241. typedef struct VmaDefragmentationStats
  1242. {
  1243. /// Total number of bytes that have been copied while moving allocations to different places.
  1244. VkDeviceSize bytesMoved;
  1245. /// Total number of bytes that have been released to the system by freeing empty `VkDeviceMemory` objects.
  1246. VkDeviceSize bytesFreed;
  1247. /// Number of allocations that have been moved to different places.
  1248. uint32_t allocationsMoved;
  1249. /// Number of empty `VkDeviceMemory` objects that have been released to the system.
  1250. uint32_t deviceMemoryBlocksFreed;
  1251. } VmaDefragmentationStats;
  1252. /** @} */
  1253. /**
  1254. \addtogroup group_virtual
  1255. @{
  1256. */
  1257. /// Parameters of created #VmaVirtualBlock object to be passed to vmaCreateVirtualBlock().
  1258. typedef struct VmaVirtualBlockCreateInfo
  1259. {
  1260. /** \brief Total size of the virtual block.
  1261. Sizes can be expressed in bytes or any units you want as long as you are consistent in using them.
  1262. For example, if you allocate from some array of structures, 1 can mean single instance of entire structure.
  1263. */
  1264. VkDeviceSize size;
  1265. /** \brief Use combination of #VmaVirtualBlockCreateFlagBits.
  1266. */
  1267. VmaVirtualBlockCreateFlags flags;
  1268. /** \brief Custom CPU memory allocation callbacks. Optional.
  1269. Optional, can be null. When specified, they will be used for all CPU-side memory allocations.
  1270. */
  1271. const VkAllocationCallbacks* VMA_NULLABLE pAllocationCallbacks;
  1272. } VmaVirtualBlockCreateInfo;
  1273. /// Parameters of created virtual allocation to be passed to vmaVirtualAllocate().
  1274. typedef struct VmaVirtualAllocationCreateInfo
  1275. {
  1276. /** \brief Size of the allocation.
  1277. Cannot be zero.
  1278. */
  1279. VkDeviceSize size;
  1280. /** \brief Required alignment of the allocation. Optional.
  1281. Must be power of two. Special value 0 has the same meaning as 1 - means no special alignment is required, so allocation can start at any offset.
  1282. */
  1283. VkDeviceSize alignment;
  1284. /** \brief Use combination of #VmaVirtualAllocationCreateFlagBits.
  1285. */
  1286. VmaVirtualAllocationCreateFlags flags;
  1287. /** \brief Custom pointer to be associated with the allocation. Optional.
  1288. It can be any value and can be used for user-defined purposes. It can be fetched or changed later.
  1289. */
  1290. void* VMA_NULLABLE pUserData;
  1291. } VmaVirtualAllocationCreateInfo;
  1292. /// Parameters of an existing virtual allocation, returned by vmaGetVirtualAllocationInfo().
  1293. typedef struct VmaVirtualAllocationInfo
  1294. {
  1295. /** \brief Offset of the allocation.
  1296. Offset at which the allocation was made.
  1297. */
  1298. VkDeviceSize offset;
  1299. /** \brief Size of the allocation.
  1300. Same value as passed in VmaVirtualAllocationCreateInfo::size.
  1301. */
  1302. VkDeviceSize size;
  1303. /** \brief Custom pointer associated with the allocation.
  1304. Same value as passed in VmaVirtualAllocationCreateInfo::pUserData or to vmaSetVirtualAllocationUserData().
  1305. */
  1306. void* VMA_NULLABLE pUserData;
  1307. } VmaVirtualAllocationInfo;
  1308. /** @} */
  1309. #endif // _VMA_DATA_TYPES_DECLARATIONS
  1310. #ifndef _VMA_FUNCTION_HEADERS
  1311. /**
  1312. \addtogroup group_init
  1313. @{
  1314. */
  1315. /// Creates #VmaAllocator object.
  1316. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAllocator(
  1317. const VmaAllocatorCreateInfo* VMA_NOT_NULL pCreateInfo,
  1318. VmaAllocator VMA_NULLABLE* VMA_NOT_NULL pAllocator);
  1319. /// Destroys allocator object.
  1320. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyAllocator(
  1321. VmaAllocator VMA_NULLABLE allocator);
  1322. /** \brief Returns information about existing #VmaAllocator object - handle to Vulkan device etc.
  1323. It might be useful if you want to keep just the #VmaAllocator handle and fetch other required handles to
  1324. `VkPhysicalDevice`, `VkDevice` etc. every time using this function.
  1325. */
  1326. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocatorInfo(
  1327. VmaAllocator VMA_NOT_NULL allocator,
  1328. VmaAllocatorInfo* VMA_NOT_NULL pAllocatorInfo);
  1329. /**
  1330. PhysicalDeviceProperties are fetched from physicalDevice by the allocator.
  1331. You can access it here, without fetching it again on your own.
  1332. */
  1333. VMA_CALL_PRE void VMA_CALL_POST vmaGetPhysicalDeviceProperties(
  1334. VmaAllocator VMA_NOT_NULL allocator,
  1335. const VkPhysicalDeviceProperties* VMA_NULLABLE* VMA_NOT_NULL ppPhysicalDeviceProperties);
  1336. /**
  1337. PhysicalDeviceMemoryProperties are fetched from physicalDevice by the allocator.
  1338. You can access it here, without fetching it again on your own.
  1339. */
  1340. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryProperties(
  1341. VmaAllocator VMA_NOT_NULL allocator,
  1342. const VkPhysicalDeviceMemoryProperties* VMA_NULLABLE* VMA_NOT_NULL ppPhysicalDeviceMemoryProperties);
  1343. /**
  1344. \brief Given Memory Type Index, returns Property Flags of this memory type.
  1345. This is just a convenience function. Same information can be obtained using
  1346. vmaGetMemoryProperties().
  1347. */
  1348. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties(
  1349. VmaAllocator VMA_NOT_NULL allocator,
  1350. uint32_t memoryTypeIndex,
  1351. VkMemoryPropertyFlags* VMA_NOT_NULL pFlags);
  1352. /** \brief Sets index of the current frame.
  1353. */
  1354. VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex(
  1355. VmaAllocator VMA_NOT_NULL allocator,
  1356. uint32_t frameIndex);
  1357. /** @} */
  1358. /**
  1359. \addtogroup group_stats
  1360. @{
  1361. */
  1362. /** \brief Retrieves statistics from current state of the Allocator.
  1363. This function is called "calculate" not "get" because it has to traverse all
  1364. internal data structures, so it may be quite slow. Use it for debugging purposes.
  1365. For faster but more brief statistics suitable to be called every frame or every allocation,
  1366. use vmaGetHeapBudgets().
  1367. Note that when using allocator from multiple threads, returned information may immediately
  1368. become outdated.
  1369. */
  1370. VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStatistics(
  1371. VmaAllocator VMA_NOT_NULL allocator,
  1372. VmaTotalStatistics* VMA_NOT_NULL pStats);
  1373. /** \brief Retrieves information about current memory usage and budget for all memory heaps.
  1374. \param allocator
  1375. \param[out] pBudgets Must point to array with number of elements at least equal to number of memory heaps in physical device used.
  1376. This function is called "get" not "calculate" because it is very fast, suitable to be called
  1377. every frame or every allocation. For more detailed statistics use vmaCalculateStatistics().
  1378. Note that when using allocator from multiple threads, returned information may immediately
  1379. become outdated.
  1380. */
  1381. VMA_CALL_PRE void VMA_CALL_POST vmaGetHeapBudgets(
  1382. VmaAllocator VMA_NOT_NULL allocator,
  1383. VmaBudget* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryHeapCount") pBudgets);
  1384. /** @} */
  1385. /**
  1386. \addtogroup group_alloc
  1387. @{
  1388. */
  1389. /**
  1390. \brief Helps to find memoryTypeIndex, given memoryTypeBits and VmaAllocationCreateInfo.
  1391. This algorithm tries to find a memory type that:
  1392. - Is allowed by memoryTypeBits.
  1393. - Contains all the flags from pAllocationCreateInfo->requiredFlags.
  1394. - Matches intended usage.
  1395. - Has as many flags from pAllocationCreateInfo->preferredFlags as possible.
  1396. \return Returns VK_ERROR_FEATURE_NOT_PRESENT if not found. Receiving such result
  1397. from this function or any other allocating function probably means that your
  1398. device doesn't support any memory type with requested features for the specific
  1399. type of resource you want to use it for. Please check parameters of your
  1400. resource, like image layout (OPTIMAL versus LINEAR) or mip level count.
  1401. */
  1402. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex(
  1403. VmaAllocator VMA_NOT_NULL allocator,
  1404. uint32_t memoryTypeBits,
  1405. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  1406. uint32_t* VMA_NOT_NULL pMemoryTypeIndex);
  1407. /**
  1408. \brief Helps to find memoryTypeIndex, given VkBufferCreateInfo and VmaAllocationCreateInfo.
  1409. It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex.
  1410. It internally creates a temporary, dummy buffer that never has memory bound.
  1411. */
  1412. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo(
  1413. VmaAllocator VMA_NOT_NULL allocator,
  1414. const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo,
  1415. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  1416. uint32_t* VMA_NOT_NULL pMemoryTypeIndex);
  1417. /**
  1418. \brief Helps to find memoryTypeIndex, given VkImageCreateInfo and VmaAllocationCreateInfo.
  1419. It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex.
  1420. It internally creates a temporary, dummy image that never has memory bound.
  1421. */
  1422. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo(
  1423. VmaAllocator VMA_NOT_NULL allocator,
  1424. const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo,
  1425. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  1426. uint32_t* VMA_NOT_NULL pMemoryTypeIndex);
  1427. /** \brief Allocates Vulkan device memory and creates #VmaPool object.
  1428. \param allocator Allocator object.
  1429. \param pCreateInfo Parameters of pool to create.
  1430. \param[out] pPool Handle to created pool.
  1431. */
  1432. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool(
  1433. VmaAllocator VMA_NOT_NULL allocator,
  1434. const VmaPoolCreateInfo* VMA_NOT_NULL pCreateInfo,
  1435. VmaPool VMA_NULLABLE* VMA_NOT_NULL pPool);
  1436. /** \brief Destroys #VmaPool object and frees Vulkan device memory.
  1437. */
  1438. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool(
  1439. VmaAllocator VMA_NOT_NULL allocator,
  1440. VmaPool VMA_NULLABLE pool);
  1441. /** @} */
  1442. /**
  1443. \addtogroup group_stats
  1444. @{
  1445. */
  1446. /** \brief Retrieves statistics of existing #VmaPool object.
  1447. \param allocator Allocator object.
  1448. \param pool Pool object.
  1449. \param[out] pPoolStats Statistics of specified pool.
  1450. */
  1451. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStatistics(
  1452. VmaAllocator VMA_NOT_NULL allocator,
  1453. VmaPool VMA_NOT_NULL pool,
  1454. VmaStatistics* VMA_NOT_NULL pPoolStats);
  1455. /** \brief Retrieves detailed statistics of existing #VmaPool object.
  1456. \param allocator Allocator object.
  1457. \param pool Pool object.
  1458. \param[out] pPoolStats Statistics of specified pool.
  1459. */
  1460. VMA_CALL_PRE void VMA_CALL_POST vmaCalculatePoolStatistics(
  1461. VmaAllocator VMA_NOT_NULL allocator,
  1462. VmaPool VMA_NOT_NULL pool,
  1463. VmaDetailedStatistics* VMA_NOT_NULL pPoolStats);
  1464. /** @} */
  1465. /**
  1466. \addtogroup group_alloc
  1467. @{
  1468. */
  1469. /** \brief Checks magic number in margins around all allocations in given memory pool in search for corruptions.
  1470. Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero,
  1471. `VMA_DEBUG_MARGIN` is defined to nonzero and the pool is created in memory type that is
  1472. `HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection).
  1473. Possible return values:
  1474. - `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for specified pool.
  1475. - `VK_SUCCESS` - corruption detection has been performed and succeeded.
  1476. - `VK_ERROR_UNKNOWN` - corruption detection has been performed and found memory corruptions around one of the allocations.
  1477. `VMA_ASSERT` is also fired in that case.
  1478. - Other value: Error returned by Vulkan, e.g. memory mapping failure.
  1479. */
  1480. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckPoolCorruption(
  1481. VmaAllocator VMA_NOT_NULL allocator,
  1482. VmaPool VMA_NOT_NULL pool);
  1483. /** \brief Retrieves name of a custom pool.
  1484. After the call `ppName` is either null or points to an internally-owned null-terminated string
  1485. containing name of the pool that was previously set. The pointer becomes invalid when the pool is
  1486. destroyed or its name is changed using vmaSetPoolName().
  1487. */
  1488. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName(
  1489. VmaAllocator VMA_NOT_NULL allocator,
  1490. VmaPool VMA_NOT_NULL pool,
  1491. const char* VMA_NULLABLE* VMA_NOT_NULL ppName);
  1492. /** \brief Sets name of a custom pool.
  1493. `pName` can be either null or pointer to a null-terminated string with new name for the pool.
  1494. Function makes internal copy of the string, so it can be changed or freed immediately after this call.
  1495. */
  1496. VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName(
  1497. VmaAllocator VMA_NOT_NULL allocator,
  1498. VmaPool VMA_NOT_NULL pool,
  1499. const char* VMA_NULLABLE pName);
  1500. /** \brief General purpose memory allocation.
  1501. \param allocator
  1502. \param pVkMemoryRequirements
  1503. \param pCreateInfo
  1504. \param[out] pAllocation Handle to allocated memory.
  1505. \param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
  1506. You should free the memory using vmaFreeMemory() or vmaFreeMemoryPages().
  1507. It is recommended to use vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage(),
  1508. vmaCreateBuffer(), vmaCreateImage() instead whenever possible.
  1509. */
  1510. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory(
  1511. VmaAllocator VMA_NOT_NULL allocator,
  1512. const VkMemoryRequirements* VMA_NOT_NULL pVkMemoryRequirements,
  1513. const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo,
  1514. VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation,
  1515. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  1516. /** \brief General purpose memory allocation for multiple allocation objects at once.
  1517. \param allocator Allocator object.
  1518. \param pVkMemoryRequirements Memory requirements for each allocation.
  1519. \param pCreateInfo Creation parameters for each allocation.
  1520. \param allocationCount Number of allocations to make.
  1521. \param[out] pAllocations Pointer to array that will be filled with handles to created allocations.
  1522. \param[out] pAllocationInfo Optional. Pointer to array that will be filled with parameters of created allocations.
  1523. You should free the memory using vmaFreeMemory() or vmaFreeMemoryPages().
  1524. Word "pages" is just a suggestion to use this function to allocate pieces of memory needed for sparse binding.
  1525. It is just a general purpose allocation function able to make multiple allocations at once.
  1526. It may be internally optimized to be more efficient than calling vmaAllocateMemory() `allocationCount` times.
  1527. All allocations are made using same parameters. All of them are created out of the same memory pool and type.
  1528. If any allocation fails, all allocations already made within this function call are also freed, so that when
  1529. returned result is not `VK_SUCCESS`, `pAllocation` array is always entirely filled with `VK_NULL_HANDLE`.
  1530. */
  1531. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages(
  1532. VmaAllocator VMA_NOT_NULL allocator,
  1533. const VkMemoryRequirements* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pVkMemoryRequirements,
  1534. const VmaAllocationCreateInfo* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pCreateInfo,
  1535. size_t allocationCount,
  1536. VmaAllocation VMA_NULLABLE* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations,
  1537. VmaAllocationInfo* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) pAllocationInfo);
  1538. /** \brief Allocates memory suitable for given `VkBuffer`.
  1539. \param allocator
  1540. \param buffer
  1541. \param pCreateInfo
  1542. \param[out] pAllocation Handle to allocated memory.
  1543. \param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
  1544. It only creates #VmaAllocation. To bind the memory to the buffer, use vmaBindBufferMemory().
  1545. This is a special-purpose function. In most cases you should use vmaCreateBuffer().
  1546. You must free the allocation using vmaFreeMemory() when no longer needed.
  1547. */
  1548. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer(
  1549. VmaAllocator VMA_NOT_NULL allocator,
  1550. VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer,
  1551. const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo,
  1552. VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation,
  1553. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  1554. /** \brief Allocates memory suitable for given `VkImage`.
  1555. \param allocator
  1556. \param image
  1557. \param pCreateInfo
  1558. \param[out] pAllocation Handle to allocated memory.
  1559. \param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
  1560. It only creates #VmaAllocation. To bind the memory to the buffer, use vmaBindImageMemory().
  1561. This is a special-purpose function. In most cases you should use vmaCreateImage().
  1562. You must free the allocation using vmaFreeMemory() when no longer needed.
  1563. */
  1564. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage(
  1565. VmaAllocator VMA_NOT_NULL allocator,
  1566. VkImage VMA_NOT_NULL_NON_DISPATCHABLE image,
  1567. const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo,
  1568. VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation,
  1569. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  1570. /** \brief Frees memory previously allocated using vmaAllocateMemory(), vmaAllocateMemoryForBuffer(), or vmaAllocateMemoryForImage().
  1571. Passing `VK_NULL_HANDLE` as `allocation` is valid. Such function call is just skipped.
  1572. */
  1573. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory(
  1574. VmaAllocator VMA_NOT_NULL allocator,
  1575. const VmaAllocation VMA_NULLABLE allocation);
  1576. /** \brief Frees memory and destroys multiple allocations.
  1577. Word "pages" is just a suggestion to use this function to free pieces of memory used for sparse binding.
  1578. It is just a general purpose function to free memory and destroy allocations made using e.g. vmaAllocateMemory(),
  1579. vmaAllocateMemoryPages() and other functions.
  1580. It may be internally optimized to be more efficient than calling vmaFreeMemory() `allocationCount` times.
  1581. Allocations in `pAllocations` array can come from any memory pools and types.
  1582. Passing `VK_NULL_HANDLE` as elements of `pAllocations` array is valid. Such entries are just skipped.
  1583. */
  1584. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages(
  1585. VmaAllocator VMA_NOT_NULL allocator,
  1586. size_t allocationCount,
  1587. const VmaAllocation VMA_NULLABLE* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations);
  1588. /** \brief Returns current information about specified allocation.
  1589. Current parameters of given allocation are returned in `pAllocationInfo`.
  1590. Although this function doesn't lock any mutex, so it should be quite efficient,
  1591. you should avoid calling it too often.
  1592. You can retrieve same VmaAllocationInfo structure while creating your resource, from function
  1593. vmaCreateBuffer(), vmaCreateImage(). You can remember it if you are sure parameters don't change
  1594. (e.g. due to defragmentation).
  1595. */
  1596. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo(
  1597. VmaAllocator VMA_NOT_NULL allocator,
  1598. VmaAllocation VMA_NOT_NULL allocation,
  1599. VmaAllocationInfo* VMA_NOT_NULL pAllocationInfo);
  1600. /** \brief Sets pUserData in given allocation to new value.
  1601. The value of pointer `pUserData` is copied to allocation's `pUserData`.
  1602. It is opaque, so you can use it however you want - e.g.
  1603. as a pointer, ordinal number or some handle to you own data.
  1604. */
  1605. VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData(
  1606. VmaAllocator VMA_NOT_NULL allocator,
  1607. VmaAllocation VMA_NOT_NULL allocation,
  1608. void* VMA_NULLABLE pUserData);
  1609. /** \brief Sets pName in given allocation to new value.
  1610. `pName` must be either null, or pointer to a null-terminated string. The function
  1611. makes local copy of the string and sets it as allocation's `pName`. String
  1612. passed as pName doesn't need to be valid for whole lifetime of the allocation -
  1613. you can free it after this call. String previously pointed by allocation's
  1614. `pName` is freed from memory.
  1615. */
  1616. VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationName(
  1617. VmaAllocator VMA_NOT_NULL allocator,
  1618. VmaAllocation VMA_NOT_NULL allocation,
  1619. const char* VMA_NULLABLE pName);
  1620. /**
  1621. \brief Given an allocation, returns Property Flags of its memory type.
  1622. This is just a convenience function. Same information can be obtained using
  1623. vmaGetAllocationInfo() + vmaGetMemoryProperties().
  1624. */
  1625. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationMemoryProperties(
  1626. VmaAllocator VMA_NOT_NULL allocator,
  1627. VmaAllocation VMA_NOT_NULL allocation,
  1628. VkMemoryPropertyFlags* VMA_NOT_NULL pFlags);
  1629. /** \brief Maps memory represented by given allocation and returns pointer to it.
  1630. Maps memory represented by given allocation to make it accessible to CPU code.
  1631. When succeeded, `*ppData` contains pointer to first byte of this memory.
  1632. \warning
  1633. If the allocation is part of a bigger `VkDeviceMemory` block, returned pointer is
  1634. correctly offsetted to the beginning of region assigned to this particular allocation.
  1635. Unlike the result of `vkMapMemory`, it points to the allocation, not to the beginning of the whole block.
  1636. You should not add VmaAllocationInfo::offset to it!
  1637. Mapping is internally reference-counted and synchronized, so despite raw Vulkan
  1638. function `vkMapMemory()` cannot be used to map same block of `VkDeviceMemory`
  1639. multiple times simultaneously, it is safe to call this function on allocations
  1640. assigned to the same memory block. Actual Vulkan memory will be mapped on first
  1641. mapping and unmapped on last unmapping.
  1642. If the function succeeded, you must call vmaUnmapMemory() to unmap the
  1643. allocation when mapping is no longer needed or before freeing the allocation, at
  1644. the latest.
  1645. It also safe to call this function multiple times on the same allocation. You
  1646. must call vmaUnmapMemory() same number of times as you called vmaMapMemory().
  1647. It is also safe to call this function on allocation created with
  1648. #VMA_ALLOCATION_CREATE_MAPPED_BIT flag. Its memory stays mapped all the time.
  1649. You must still call vmaUnmapMemory() same number of times as you called
  1650. vmaMapMemory(). You must not call vmaUnmapMemory() additional time to free the
  1651. "0-th" mapping made automatically due to #VMA_ALLOCATION_CREATE_MAPPED_BIT flag.
  1652. This function fails when used on allocation made in memory type that is not
  1653. `HOST_VISIBLE`.
  1654. This function doesn't automatically flush or invalidate caches.
  1655. If the allocation is made from a memory types that is not `HOST_COHERENT`,
  1656. you also need to use vmaInvalidateAllocation() / vmaFlushAllocation(), as required by Vulkan specification.
  1657. */
  1658. VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory(
  1659. VmaAllocator VMA_NOT_NULL allocator,
  1660. VmaAllocation VMA_NOT_NULL allocation,
  1661. void* VMA_NULLABLE* VMA_NOT_NULL ppData);
  1662. /** \brief Unmaps memory represented by given allocation, mapped previously using vmaMapMemory().
  1663. For details, see description of vmaMapMemory().
  1664. This function doesn't automatically flush or invalidate caches.
  1665. If the allocation is made from a memory types that is not `HOST_COHERENT`,
  1666. you also need to use vmaInvalidateAllocation() / vmaFlushAllocation(), as required by Vulkan specification.
  1667. */
  1668. VMA_CALL_PRE void VMA_CALL_POST vmaUnmapMemory(
  1669. VmaAllocator VMA_NOT_NULL allocator,
  1670. VmaAllocation VMA_NOT_NULL allocation);
  1671. /** \brief Flushes memory of given allocation.
  1672. Calls `vkFlushMappedMemoryRanges()` for memory associated with given range of given allocation.
  1673. It needs to be called after writing to a mapped memory for memory types that are not `HOST_COHERENT`.
  1674. Unmap operation doesn't do that automatically.
  1675. - `offset` must be relative to the beginning of allocation.
  1676. - `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation.
  1677. - `offset` and `size` don't have to be aligned.
  1678. They are internally rounded down/up to multiply of `nonCoherentAtomSize`.
  1679. - If `size` is 0, this call is ignored.
  1680. - If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`,
  1681. this call is ignored.
  1682. Warning! `offset` and `size` are relative to the contents of given `allocation`.
  1683. If you mean whole allocation, you can pass 0 and `VK_WHOLE_SIZE`, respectively.
  1684. Do not pass allocation's offset as `offset`!!!
  1685. This function returns the `VkResult` from `vkFlushMappedMemoryRanges` if it is
  1686. called, otherwise `VK_SUCCESS`.
  1687. */
  1688. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocation(
  1689. VmaAllocator VMA_NOT_NULL allocator,
  1690. VmaAllocation VMA_NOT_NULL allocation,
  1691. VkDeviceSize offset,
  1692. VkDeviceSize size);
  1693. /** \brief Invalidates memory of given allocation.
  1694. Calls `vkInvalidateMappedMemoryRanges()` for memory associated with given range of given allocation.
  1695. It needs to be called before reading from a mapped memory for memory types that are not `HOST_COHERENT`.
  1696. Map operation doesn't do that automatically.
  1697. - `offset` must be relative to the beginning of allocation.
  1698. - `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation.
  1699. - `offset` and `size` don't have to be aligned.
  1700. They are internally rounded down/up to multiply of `nonCoherentAtomSize`.
  1701. - If `size` is 0, this call is ignored.
  1702. - If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`,
  1703. this call is ignored.
  1704. Warning! `offset` and `size` are relative to the contents of given `allocation`.
  1705. If you mean whole allocation, you can pass 0 and `VK_WHOLE_SIZE`, respectively.
  1706. Do not pass allocation's offset as `offset`!!!
  1707. This function returns the `VkResult` from `vkInvalidateMappedMemoryRanges` if
  1708. it is called, otherwise `VK_SUCCESS`.
  1709. */
  1710. VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocation(
  1711. VmaAllocator VMA_NOT_NULL allocator,
  1712. VmaAllocation VMA_NOT_NULL allocation,
  1713. VkDeviceSize offset,
  1714. VkDeviceSize size);
  1715. /** \brief Flushes memory of given set of allocations.
  1716. Calls `vkFlushMappedMemoryRanges()` for memory associated with given ranges of given allocations.
  1717. For more information, see documentation of vmaFlushAllocation().
  1718. \param allocator
  1719. \param allocationCount
  1720. \param allocations
  1721. \param offsets If not null, it must point to an array of offsets of regions to flush, relative to the beginning of respective allocations. Null means all ofsets are zero.
  1722. \param sizes If not null, it must point to an array of sizes of regions to flush in respective allocations. Null means `VK_WHOLE_SIZE` for all allocations.
  1723. This function returns the `VkResult` from `vkFlushMappedMemoryRanges` if it is
  1724. called, otherwise `VK_SUCCESS`.
  1725. */
  1726. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocations(
  1727. VmaAllocator VMA_NOT_NULL allocator,
  1728. uint32_t allocationCount,
  1729. const VmaAllocation VMA_NOT_NULL* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) allocations,
  1730. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) offsets,
  1731. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) sizes);
  1732. /** \brief Invalidates memory of given set of allocations.
  1733. Calls `vkInvalidateMappedMemoryRanges()` for memory associated with given ranges of given allocations.
  1734. For more information, see documentation of vmaInvalidateAllocation().
  1735. \param allocator
  1736. \param allocationCount
  1737. \param allocations
  1738. \param offsets If not null, it must point to an array of offsets of regions to flush, relative to the beginning of respective allocations. Null means all ofsets are zero.
  1739. \param sizes If not null, it must point to an array of sizes of regions to flush in respective allocations. Null means `VK_WHOLE_SIZE` for all allocations.
  1740. This function returns the `VkResult` from `vkInvalidateMappedMemoryRanges` if it is
  1741. called, otherwise `VK_SUCCESS`.
  1742. */
  1743. VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocations(
  1744. VmaAllocator VMA_NOT_NULL allocator,
  1745. uint32_t allocationCount,
  1746. const VmaAllocation VMA_NOT_NULL* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) allocations,
  1747. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) offsets,
  1748. const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) sizes);
  1749. /** \brief Checks magic number in margins around all allocations in given memory types (in both default and custom pools) in search for corruptions.
  1750. \param allocator
  1751. \param memoryTypeBits Bit mask, where each bit set means that a memory type with that index should be checked.
  1752. Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero,
  1753. `VMA_DEBUG_MARGIN` is defined to nonzero and only for memory types that are
  1754. `HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection).
  1755. Possible return values:
  1756. - `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for any of specified memory types.
  1757. - `VK_SUCCESS` - corruption detection has been performed and succeeded.
  1758. - `VK_ERROR_UNKNOWN` - corruption detection has been performed and found memory corruptions around one of the allocations.
  1759. `VMA_ASSERT` is also fired in that case.
  1760. - Other value: Error returned by Vulkan, e.g. memory mapping failure.
  1761. */
  1762. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckCorruption(
  1763. VmaAllocator VMA_NOT_NULL allocator,
  1764. uint32_t memoryTypeBits);
  1765. /** \brief Begins defragmentation process.
  1766. \param allocator Allocator object.
  1767. \param pInfo Structure filled with parameters of defragmentation.
  1768. \param[out] pContext Context object that must be passed to vmaEndDefragmentation() to finish defragmentation.
  1769. \returns
  1770. - `VK_SUCCESS` if defragmentation can begin.
  1771. - `VK_ERROR_FEATURE_NOT_PRESENT` if defragmentation is not supported.
  1772. For more information about defragmentation, see documentation chapter:
  1773. [Defragmentation](@ref defragmentation).
  1774. */
  1775. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentation(
  1776. VmaAllocator VMA_NOT_NULL allocator,
  1777. const VmaDefragmentationInfo* VMA_NOT_NULL pInfo,
  1778. VmaDefragmentationContext VMA_NULLABLE* VMA_NOT_NULL pContext);
  1779. /** \brief Ends defragmentation process.
  1780. \param allocator Allocator object.
  1781. \param context Context object that has been created by vmaBeginDefragmentation().
  1782. \param[out] pStats Optional stats for the defragmentation. Can be null.
  1783. Use this function to finish defragmentation started by vmaBeginDefragmentation().
  1784. */
  1785. VMA_CALL_PRE void VMA_CALL_POST vmaEndDefragmentation(
  1786. VmaAllocator VMA_NOT_NULL allocator,
  1787. VmaDefragmentationContext VMA_NOT_NULL context,
  1788. VmaDefragmentationStats* VMA_NULLABLE pStats);
  1789. /** \brief Starts single defragmentation pass.
  1790. \param allocator Allocator object.
  1791. \param context Context object that has been created by vmaBeginDefragmentation().
  1792. \param[out] pPassInfo Computed information for current pass.
  1793. \returns
  1794. - `VK_SUCCESS` if no more moves are possible. Then you can omit call to vmaEndDefragmentationPass() and simply end whole defragmentation.
  1795. - `VK_INCOMPLETE` if there are pending moves returned in `pPassInfo`. You need to perform them, call vmaEndDefragmentationPass(),
  1796. and then preferably try another pass with vmaBeginDefragmentationPass().
  1797. */
  1798. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentationPass(
  1799. VmaAllocator VMA_NOT_NULL allocator,
  1800. VmaDefragmentationContext VMA_NOT_NULL context,
  1801. VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo);
  1802. /** \brief Ends single defragmentation pass.
  1803. \param allocator Allocator object.
  1804. \param context Context object that has been created by vmaBeginDefragmentation().
  1805. \param pPassInfo Computed information for current pass filled by vmaBeginDefragmentationPass() and possibly modified by you.
  1806. Returns `VK_SUCCESS` if no more moves are possible or `VK_INCOMPLETE` if more defragmentations are possible.
  1807. Ends incremental defragmentation pass and commits all defragmentation moves from `pPassInfo`.
  1808. After this call:
  1809. - Allocations at `pPassInfo[i].srcAllocation` that had `pPassInfo[i].operation ==` #VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY
  1810. (which is the default) will be pointing to the new destination place.
  1811. - Allocation at `pPassInfo[i].srcAllocation` that had `pPassInfo[i].operation ==` #VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY
  1812. will be freed.
  1813. If no more moves are possible you can end whole defragmentation.
  1814. */
  1815. VMA_CALL_PRE VkResult VMA_CALL_POST vmaEndDefragmentationPass(
  1816. VmaAllocator VMA_NOT_NULL allocator,
  1817. VmaDefragmentationContext VMA_NOT_NULL context,
  1818. VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo);
  1819. /** \brief Binds buffer to allocation.
  1820. Binds specified buffer to region of memory represented by specified allocation.
  1821. Gets `VkDeviceMemory` handle and offset from the allocation.
  1822. If you want to create a buffer, allocate memory for it and bind them together separately,
  1823. you should use this function for binding instead of standard `vkBindBufferMemory()`,
  1824. because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple
  1825. allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously
  1826. (which is illegal in Vulkan).
  1827. It is recommended to use function vmaCreateBuffer() instead of this one.
  1828. */
  1829. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory(
  1830. VmaAllocator VMA_NOT_NULL allocator,
  1831. VmaAllocation VMA_NOT_NULL allocation,
  1832. VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer);
  1833. /** \brief Binds buffer to allocation with additional parameters.
  1834. \param allocator
  1835. \param allocation
  1836. \param allocationLocalOffset Additional offset to be added while binding, relative to the beginning of the `allocation`. Normally it should be 0.
  1837. \param buffer
  1838. \param pNext A chain of structures to be attached to `VkBindBufferMemoryInfoKHR` structure used internally. Normally it should be null.
  1839. This function is similar to vmaBindBufferMemory(), but it provides additional parameters.
  1840. If `pNext` is not null, #VmaAllocator object must have been created with #VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT flag
  1841. or with VmaAllocatorCreateInfo::vulkanApiVersion `>= VK_API_VERSION_1_1`. Otherwise the call fails.
  1842. */
  1843. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2(
  1844. VmaAllocator VMA_NOT_NULL allocator,
  1845. VmaAllocation VMA_NOT_NULL allocation,
  1846. VkDeviceSize allocationLocalOffset,
  1847. VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer,
  1848. const void* VMA_NULLABLE VMA_EXTENDS_VK_STRUCT(VkBindBufferMemoryInfoKHR) pNext);
  1849. /** \brief Binds image to allocation.
  1850. Binds specified image to region of memory represented by specified allocation.
  1851. Gets `VkDeviceMemory` handle and offset from the allocation.
  1852. If you want to create an image, allocate memory for it and bind them together separately,
  1853. you should use this function for binding instead of standard `vkBindImageMemory()`,
  1854. because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple
  1855. allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously
  1856. (which is illegal in Vulkan).
  1857. It is recommended to use function vmaCreateImage() instead of this one.
  1858. */
  1859. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory(
  1860. VmaAllocator VMA_NOT_NULL allocator,
  1861. VmaAllocation VMA_NOT_NULL allocation,
  1862. VkImage VMA_NOT_NULL_NON_DISPATCHABLE image);
  1863. /** \brief Binds image to allocation with additional parameters.
  1864. \param allocator
  1865. \param allocation
  1866. \param allocationLocalOffset Additional offset to be added while binding, relative to the beginning of the `allocation`. Normally it should be 0.
  1867. \param image
  1868. \param pNext A chain of structures to be attached to `VkBindImageMemoryInfoKHR` structure used internally. Normally it should be null.
  1869. This function is similar to vmaBindImageMemory(), but it provides additional parameters.
  1870. If `pNext` is not null, #VmaAllocator object must have been created with #VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT flag
  1871. or with VmaAllocatorCreateInfo::vulkanApiVersion `>= VK_API_VERSION_1_1`. Otherwise the call fails.
  1872. */
  1873. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2(
  1874. VmaAllocator VMA_NOT_NULL allocator,
  1875. VmaAllocation VMA_NOT_NULL allocation,
  1876. VkDeviceSize allocationLocalOffset,
  1877. VkImage VMA_NOT_NULL_NON_DISPATCHABLE image,
  1878. const void* VMA_NULLABLE VMA_EXTENDS_VK_STRUCT(VkBindImageMemoryInfoKHR) pNext);
  1879. /** \brief Creates a new `VkBuffer`, allocates and binds memory for it.
  1880. \param allocator
  1881. \param pBufferCreateInfo
  1882. \param pAllocationCreateInfo
  1883. \param[out] pBuffer Buffer that was created.
  1884. \param[out] pAllocation Allocation that was created.
  1885. \param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
  1886. This function automatically:
  1887. -# Creates buffer.
  1888. -# Allocates appropriate memory for it.
  1889. -# Binds the buffer with the memory.
  1890. If any of these operations fail, buffer and allocation are not created,
  1891. returned value is negative error code, `*pBuffer` and `*pAllocation` are null.
  1892. If the function succeeded, you must destroy both buffer and allocation when you
  1893. no longer need them using either convenience function vmaDestroyBuffer() or
  1894. separately, using `vkDestroyBuffer()` and vmaFreeMemory().
  1895. If #VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag was used,
  1896. VK_KHR_dedicated_allocation extension is used internally to query driver whether
  1897. it requires or prefers the new buffer to have dedicated allocation. If yes,
  1898. and if dedicated allocation is possible
  1899. (#VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT is not used), it creates dedicated
  1900. allocation for this buffer, just like when using
  1901. #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  1902. \note This function creates a new `VkBuffer`. Sub-allocation of parts of one large buffer,
  1903. although recommended as a good practice, is out of scope of this library and could be implemented
  1904. by the user as a higher-level logic on top of VMA.
  1905. */
  1906. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer(
  1907. VmaAllocator VMA_NOT_NULL allocator,
  1908. const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo,
  1909. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  1910. VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer,
  1911. VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation,
  1912. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  1913. /** \brief Creates a buffer with additional minimum alignment.
  1914. Similar to vmaCreateBuffer() but provides additional parameter `minAlignment` which allows to specify custom,
  1915. minimum alignment to be used when placing the buffer inside a larger memory block, which may be needed e.g.
  1916. for interop with OpenGL.
  1917. */
  1918. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBufferWithAlignment(
  1919. VmaAllocator VMA_NOT_NULL allocator,
  1920. const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo,
  1921. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  1922. VkDeviceSize minAlignment,
  1923. VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer,
  1924. VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation,
  1925. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  1926. /** \brief Creates a new `VkBuffer`, binds already created memory for it.
  1927. \param allocator
  1928. \param allocation Allocation that provides memory to be used for binding new buffer to it.
  1929. \param pBufferCreateInfo
  1930. \param[out] pBuffer Buffer that was created.
  1931. This function automatically:
  1932. -# Creates buffer.
  1933. -# Binds the buffer with the supplied memory.
  1934. If any of these operations fail, buffer is not created,
  1935. returned value is negative error code and `*pBuffer` is null.
  1936. If the function succeeded, you must destroy the buffer when you
  1937. no longer need it using `vkDestroyBuffer()`. If you want to also destroy the corresponding
  1938. allocation you can use convenience function vmaDestroyBuffer().
  1939. \note There is a new version of this function augmented with parameter `allocationLocalOffset` - see vmaCreateAliasingBuffer2().
  1940. */
  1941. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingBuffer(
  1942. VmaAllocator VMA_NOT_NULL allocator,
  1943. VmaAllocation VMA_NOT_NULL allocation,
  1944. const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo,
  1945. VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer);
  1946. /** \brief Creates a new `VkBuffer`, binds already created memory for it.
  1947. \param allocator
  1948. \param allocation Allocation that provides memory to be used for binding new buffer to it.
  1949. \param allocationLocalOffset Additional offset to be added while binding, relative to the beginning of the allocation. Normally it should be 0.
  1950. \param pBufferCreateInfo
  1951. \param[out] pBuffer Buffer that was created.
  1952. This function automatically:
  1953. -# Creates buffer.
  1954. -# Binds the buffer with the supplied memory.
  1955. If any of these operations fail, buffer is not created,
  1956. returned value is negative error code and `*pBuffer` is null.
  1957. If the function succeeded, you must destroy the buffer when you
  1958. no longer need it using `vkDestroyBuffer()`. If you want to also destroy the corresponding
  1959. allocation you can use convenience function vmaDestroyBuffer().
  1960. \note This is a new version of the function augmented with parameter `allocationLocalOffset`.
  1961. */
  1962. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingBuffer2(
  1963. VmaAllocator VMA_NOT_NULL allocator,
  1964. VmaAllocation VMA_NOT_NULL allocation,
  1965. VkDeviceSize allocationLocalOffset,
  1966. const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo,
  1967. VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer);
  1968. /** \brief Destroys Vulkan buffer and frees allocated memory.
  1969. This is just a convenience function equivalent to:
  1970. \code
  1971. vkDestroyBuffer(device, buffer, allocationCallbacks);
  1972. vmaFreeMemory(allocator, allocation);
  1973. \endcode
  1974. It is safe to pass null as buffer and/or allocation.
  1975. */
  1976. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer(
  1977. VmaAllocator VMA_NOT_NULL allocator,
  1978. VkBuffer VMA_NULLABLE_NON_DISPATCHABLE buffer,
  1979. VmaAllocation VMA_NULLABLE allocation);
  1980. /// Function similar to vmaCreateBuffer().
  1981. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage(
  1982. VmaAllocator VMA_NOT_NULL allocator,
  1983. const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo,
  1984. const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo,
  1985. VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage,
  1986. VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation,
  1987. VmaAllocationInfo* VMA_NULLABLE pAllocationInfo);
  1988. /// Function similar to vmaCreateAliasingBuffer() but for images.
  1989. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingImage(
  1990. VmaAllocator VMA_NOT_NULL allocator,
  1991. VmaAllocation VMA_NOT_NULL allocation,
  1992. const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo,
  1993. VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage);
  1994. /// Function similar to vmaCreateAliasingBuffer2() but for images.
  1995. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingImage2(
  1996. VmaAllocator VMA_NOT_NULL allocator,
  1997. VmaAllocation VMA_NOT_NULL allocation,
  1998. VkDeviceSize allocationLocalOffset,
  1999. const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo,
  2000. VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage);
  2001. /** \brief Destroys Vulkan image and frees allocated memory.
  2002. This is just a convenience function equivalent to:
  2003. \code
  2004. vkDestroyImage(device, image, allocationCallbacks);
  2005. vmaFreeMemory(allocator, allocation);
  2006. \endcode
  2007. It is safe to pass null as image and/or allocation.
  2008. */
  2009. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyImage(
  2010. VmaAllocator VMA_NOT_NULL allocator,
  2011. VkImage VMA_NULLABLE_NON_DISPATCHABLE image,
  2012. VmaAllocation VMA_NULLABLE allocation);
  2013. /** @} */
  2014. /**
  2015. \addtogroup group_virtual
  2016. @{
  2017. */
  2018. /** \brief Creates new #VmaVirtualBlock object.
  2019. \param pCreateInfo Parameters for creation.
  2020. \param[out] pVirtualBlock Returned virtual block object or `VMA_NULL` if creation failed.
  2021. */
  2022. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateVirtualBlock(
  2023. const VmaVirtualBlockCreateInfo* VMA_NOT_NULL pCreateInfo,
  2024. VmaVirtualBlock VMA_NULLABLE* VMA_NOT_NULL pVirtualBlock);
  2025. /** \brief Destroys #VmaVirtualBlock object.
  2026. Please note that you should consciously handle virtual allocations that could remain unfreed in the block.
  2027. You should either free them individually using vmaVirtualFree() or call vmaClearVirtualBlock()
  2028. if you are sure this is what you want. If you do neither, an assert is called.
  2029. If you keep pointers to some additional metadata associated with your virtual allocations in their `pUserData`,
  2030. don't forget to free them.
  2031. */
  2032. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyVirtualBlock(
  2033. VmaVirtualBlock VMA_NULLABLE virtualBlock);
  2034. /** \brief Returns true of the #VmaVirtualBlock is empty - contains 0 virtual allocations and has all its space available for new allocations.
  2035. */
  2036. VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaIsVirtualBlockEmpty(
  2037. VmaVirtualBlock VMA_NOT_NULL virtualBlock);
  2038. /** \brief Returns information about a specific virtual allocation within a virtual block, like its size and `pUserData` pointer.
  2039. */
  2040. VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualAllocationInfo(
  2041. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2042. VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation, VmaVirtualAllocationInfo* VMA_NOT_NULL pVirtualAllocInfo);
  2043. /** \brief Allocates new virtual allocation inside given #VmaVirtualBlock.
  2044. If the allocation fails due to not enough free space available, `VK_ERROR_OUT_OF_DEVICE_MEMORY` is returned
  2045. (despite the function doesn't ever allocate actual GPU memory).
  2046. `pAllocation` is then set to `VK_NULL_HANDLE` and `pOffset`, if not null, it set to `UINT64_MAX`.
  2047. \param virtualBlock Virtual block
  2048. \param pCreateInfo Parameters for the allocation
  2049. \param[out] pAllocation Returned handle of the new allocation
  2050. \param[out] pOffset Returned offset of the new allocation. Optional, can be null.
  2051. */
  2052. VMA_CALL_PRE VkResult VMA_CALL_POST vmaVirtualAllocate(
  2053. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2054. const VmaVirtualAllocationCreateInfo* VMA_NOT_NULL pCreateInfo,
  2055. VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pAllocation,
  2056. VkDeviceSize* VMA_NULLABLE pOffset);
  2057. /** \brief Frees virtual allocation inside given #VmaVirtualBlock.
  2058. It is correct to call this function with `allocation == VK_NULL_HANDLE` - it does nothing.
  2059. */
  2060. VMA_CALL_PRE void VMA_CALL_POST vmaVirtualFree(
  2061. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2062. VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE allocation);
  2063. /** \brief Frees all virtual allocations inside given #VmaVirtualBlock.
  2064. You must either call this function or free each virtual allocation individually with vmaVirtualFree()
  2065. before destroying a virtual block. Otherwise, an assert is called.
  2066. If you keep pointer to some additional metadata associated with your virtual allocation in its `pUserData`,
  2067. don't forget to free it as well.
  2068. */
  2069. VMA_CALL_PRE void VMA_CALL_POST vmaClearVirtualBlock(
  2070. VmaVirtualBlock VMA_NOT_NULL virtualBlock);
  2071. /** \brief Changes custom pointer associated with given virtual allocation.
  2072. */
  2073. VMA_CALL_PRE void VMA_CALL_POST vmaSetVirtualAllocationUserData(
  2074. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2075. VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation,
  2076. void* VMA_NULLABLE pUserData);
  2077. /** \brief Calculates and returns statistics about virtual allocations and memory usage in given #VmaVirtualBlock.
  2078. This function is fast to call. For more detailed statistics, see vmaCalculateVirtualBlockStatistics().
  2079. */
  2080. VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualBlockStatistics(
  2081. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2082. VmaStatistics* VMA_NOT_NULL pStats);
  2083. /** \brief Calculates and returns detailed statistics about virtual allocations and memory usage in given #VmaVirtualBlock.
  2084. This function is slow to call. Use for debugging purposes.
  2085. For less detailed statistics, see vmaGetVirtualBlockStatistics().
  2086. */
  2087. VMA_CALL_PRE void VMA_CALL_POST vmaCalculateVirtualBlockStatistics(
  2088. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2089. VmaDetailedStatistics* VMA_NOT_NULL pStats);
  2090. /** @} */
  2091. #if VMA_STATS_STRING_ENABLED
  2092. /**
  2093. \addtogroup group_stats
  2094. @{
  2095. */
  2096. /** \brief Builds and returns a null-terminated string in JSON format with information about given #VmaVirtualBlock.
  2097. \param virtualBlock Virtual block.
  2098. \param[out] ppStatsString Returned string.
  2099. \param detailedMap Pass `VK_FALSE` to only obtain statistics as returned by vmaCalculateVirtualBlockStatistics(). Pass `VK_TRUE` to also obtain full list of allocations and free spaces.
  2100. Returned string must be freed using vmaFreeVirtualBlockStatsString().
  2101. */
  2102. VMA_CALL_PRE void VMA_CALL_POST vmaBuildVirtualBlockStatsString(
  2103. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2104. char* VMA_NULLABLE* VMA_NOT_NULL ppStatsString,
  2105. VkBool32 detailedMap);
  2106. /// Frees a string returned by vmaBuildVirtualBlockStatsString().
  2107. VMA_CALL_PRE void VMA_CALL_POST vmaFreeVirtualBlockStatsString(
  2108. VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  2109. char* VMA_NULLABLE pStatsString);
  2110. /** \brief Builds and returns statistics as a null-terminated string in JSON format.
  2111. \param allocator
  2112. \param[out] ppStatsString Must be freed using vmaFreeStatsString() function.
  2113. \param detailedMap
  2114. */
  2115. VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString(
  2116. VmaAllocator VMA_NOT_NULL allocator,
  2117. char* VMA_NULLABLE* VMA_NOT_NULL ppStatsString,
  2118. VkBool32 detailedMap);
  2119. VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString(
  2120. VmaAllocator VMA_NOT_NULL allocator,
  2121. char* VMA_NULLABLE pStatsString);
  2122. /** @} */
  2123. #endif // VMA_STATS_STRING_ENABLED
  2124. #endif // _VMA_FUNCTION_HEADERS
  2125. #ifdef __cplusplus
  2126. }
  2127. #endif
  2128. #endif // AMD_VULKAN_MEMORY_ALLOCATOR_H
  2129. ////////////////////////////////////////////////////////////////////////////////
  2130. ////////////////////////////////////////////////////////////////////////////////
  2131. //
  2132. // IMPLEMENTATION
  2133. //
  2134. ////////////////////////////////////////////////////////////////////////////////
  2135. ////////////////////////////////////////////////////////////////////////////////
  2136. // For Visual Studio IntelliSense.
  2137. #if defined(__cplusplus) && defined(__INTELLISENSE__)
  2138. #define VMA_IMPLEMENTATION
  2139. #endif
  2140. #ifdef VMA_IMPLEMENTATION
  2141. #undef VMA_IMPLEMENTATION
  2142. #include <cstdint>
  2143. #include <cstdlib>
  2144. #include <cstring>
  2145. #include <utility>
  2146. #include <type_traits>
  2147. #ifdef _MSC_VER
  2148. #include <intrin.h> // For functions like __popcnt, _BitScanForward etc.
  2149. #endif
  2150. #if __cplusplus >= 202002L || _MSVC_LANG >= 202002L // C++20
  2151. #include <bit> // For std::popcount
  2152. #endif
  2153. #if VMA_STATS_STRING_ENABLED
  2154. #include <cstdio> // For snprintf
  2155. #endif
  2156. /*******************************************************************************
  2157. CONFIGURATION SECTION
  2158. Define some of these macros before each #include of this header or change them
  2159. here if you need other then default behavior depending on your environment.
  2160. */
  2161. #ifndef _VMA_CONFIGURATION
  2162. /*
  2163. Define this macro to 1 to make the library fetch pointers to Vulkan functions
  2164. internally, like:
  2165. vulkanFunctions.vkAllocateMemory = &vkAllocateMemory;
  2166. */
  2167. #if !defined(VMA_STATIC_VULKAN_FUNCTIONS) && !defined(VK_NO_PROTOTYPES)
  2168. #define VMA_STATIC_VULKAN_FUNCTIONS 1
  2169. #endif
  2170. /*
  2171. Define this macro to 1 to make the library fetch pointers to Vulkan functions
  2172. internally, like:
  2173. vulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkGetDeviceProcAddr(device, "vkAllocateMemory");
  2174. To use this feature in new versions of VMA you now have to pass
  2175. VmaVulkanFunctions::vkGetInstanceProcAddr and vkGetDeviceProcAddr as
  2176. VmaAllocatorCreateInfo::pVulkanFunctions. Other members can be null.
  2177. */
  2178. #if !defined(VMA_DYNAMIC_VULKAN_FUNCTIONS)
  2179. #define VMA_DYNAMIC_VULKAN_FUNCTIONS 1
  2180. #endif
  2181. #ifndef VMA_USE_STL_SHARED_MUTEX
  2182. #if __cplusplus >= 201703L || _MSVC_LANG >= 201703L // C++17
  2183. #define VMA_USE_STL_SHARED_MUTEX 1
  2184. // Visual studio defines __cplusplus properly only when passed additional parameter: /Zc:__cplusplus
  2185. // Otherwise it is always 199711L, despite shared_mutex works since Visual Studio 2015 Update 2.
  2186. #elif defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 190023918 && __cplusplus == 199711L && _MSVC_LANG >= 201703L
  2187. #define VMA_USE_STL_SHARED_MUTEX 1
  2188. #else
  2189. #define VMA_USE_STL_SHARED_MUTEX 0
  2190. #endif
  2191. #endif
  2192. /*
  2193. Define this macro to include custom header files without having to edit this file directly, e.g.:
  2194. // Inside of "my_vma_configuration_user_includes.h":
  2195. #include "my_custom_assert.h" // for MY_CUSTOM_ASSERT
  2196. #include "my_custom_min.h" // for my_custom_min
  2197. #include <algorithm>
  2198. #include <mutex>
  2199. // Inside a different file, which includes "vk_mem_alloc.h":
  2200. #define VMA_CONFIGURATION_USER_INCLUDES_H "my_vma_configuration_user_includes.h"
  2201. #define VMA_ASSERT(expr) MY_CUSTOM_ASSERT(expr)
  2202. #define VMA_MIN(v1, v2) (my_custom_min(v1, v2))
  2203. #include "vk_mem_alloc.h"
  2204. ...
  2205. The following headers are used in this CONFIGURATION section only, so feel free to
  2206. remove them if not needed.
  2207. */
  2208. #if !defined(VMA_CONFIGURATION_USER_INCLUDES_H)
  2209. #include <cassert> // for assert
  2210. #include <algorithm> // for min, max
  2211. #include <mutex>
  2212. #else
  2213. #include VMA_CONFIGURATION_USER_INCLUDES_H
  2214. #endif
  2215. #ifndef VMA_NULL
  2216. // Value used as null pointer. Define it to e.g.: nullptr, NULL, 0, (void*)0.
  2217. #define VMA_NULL nullptr
  2218. #endif
  2219. #ifndef VMA_FALLTHROUGH
  2220. #if __cplusplus >= 201703L || _MSVC_LANG >= 201703L // C++17
  2221. #define VMA_FALLTHROUGH [[fallthrough]]
  2222. #else
  2223. #define VMA_FALLTHROUGH
  2224. #endif
  2225. #endif
  2226. // Normal assert to check for programmer's errors, especially in Debug configuration.
  2227. #ifndef VMA_ASSERT
  2228. #ifdef NDEBUG
  2229. #define VMA_ASSERT(expr)
  2230. #else
  2231. #define VMA_ASSERT(expr) assert(expr)
  2232. #endif
  2233. #endif
  2234. // Assert that will be called very often, like inside data structures e.g. operator[].
  2235. // Making it non-empty can make program slow.
  2236. #ifndef VMA_HEAVY_ASSERT
  2237. #ifdef NDEBUG
  2238. #define VMA_HEAVY_ASSERT(expr)
  2239. #else
  2240. #define VMA_HEAVY_ASSERT(expr) //VMA_ASSERT(expr)
  2241. #endif
  2242. #endif
  2243. // If your compiler is not compatible with C++17 and definition of
  2244. // aligned_alloc() function is missing, uncommenting following line may help:
  2245. //#include <malloc.h>
  2246. #if defined(__ANDROID_API__) && (__ANDROID_API__ < 16)
  2247. #include <cstdlib>
  2248. static void* vma_aligned_alloc(size_t alignment, size_t size)
  2249. {
  2250. // alignment must be >= sizeof(void*)
  2251. if(alignment < sizeof(void*))
  2252. {
  2253. alignment = sizeof(void*);
  2254. }
  2255. return memalign(alignment, size);
  2256. }
  2257. #elif defined(__APPLE__) || defined(__ANDROID__) || (defined(__linux__) && defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC))
  2258. #include <cstdlib>
  2259. #if defined(__APPLE__)
  2260. #include <AvailabilityMacros.h>
  2261. #endif
  2262. static void* vma_aligned_alloc(size_t alignment, size_t size)
  2263. {
  2264. // Unfortunately, aligned_alloc causes VMA to crash due to it returning null pointers. (At least under 11.4)
  2265. // Therefore, for now disable this specific exception until a proper solution is found.
  2266. //#if defined(__APPLE__) && (defined(MAC_OS_X_VERSION_10_16) || defined(__IPHONE_14_0))
  2267. //#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_16 || __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0
  2268. // // For C++14, usr/include/malloc/_malloc.h declares aligned_alloc()) only
  2269. // // with the MacOSX11.0 SDK in Xcode 12 (which is what adds
  2270. // // MAC_OS_X_VERSION_10_16), even though the function is marked
  2271. // // available for 10.15. That is why the preprocessor checks for 10.16 but
  2272. // // the __builtin_available checks for 10.15.
  2273. // // People who use C++17 could call aligned_alloc with the 10.15 SDK already.
  2274. // if (__builtin_available(macOS 10.15, iOS 13, *))
  2275. // return aligned_alloc(alignment, size);
  2276. //#endif
  2277. //#endif
  2278. // alignment must be >= sizeof(void*)
  2279. if(alignment < sizeof(void*))
  2280. {
  2281. alignment = sizeof(void*);
  2282. }
  2283. void *pointer;
  2284. if(posix_memalign(&pointer, alignment, size) == 0)
  2285. return pointer;
  2286. return VMA_NULL;
  2287. }
  2288. #elif defined(_WIN32)
  2289. static void* vma_aligned_alloc(size_t alignment, size_t size)
  2290. {
  2291. return _aligned_malloc(size, alignment);
  2292. }
  2293. #elif __cplusplus >= 201703L || _MSVC_LANG >= 201703L // C++17
  2294. static void* vma_aligned_alloc(size_t alignment, size_t size)
  2295. {
  2296. return aligned_alloc(alignment, size);
  2297. }
  2298. #else
  2299. static void* vma_aligned_alloc(size_t alignment, size_t size)
  2300. {
  2301. VMA_ASSERT(0 && "Could not implement aligned_alloc automatically. Please enable C++17 or later in your compiler or provide custom implementation of macro VMA_SYSTEM_ALIGNED_MALLOC (and VMA_SYSTEM_ALIGNED_FREE if needed) using the API of your system.");
  2302. return VMA_NULL;
  2303. }
  2304. #endif
  2305. #if defined(_WIN32)
  2306. static void vma_aligned_free(void* ptr)
  2307. {
  2308. _aligned_free(ptr);
  2309. }
  2310. #else
  2311. static void vma_aligned_free(void* VMA_NULLABLE ptr)
  2312. {
  2313. free(ptr);
  2314. }
  2315. #endif
  2316. #ifndef VMA_ALIGN_OF
  2317. #define VMA_ALIGN_OF(type) (alignof(type))
  2318. #endif
  2319. #ifndef VMA_SYSTEM_ALIGNED_MALLOC
  2320. #define VMA_SYSTEM_ALIGNED_MALLOC(size, alignment) vma_aligned_alloc((alignment), (size))
  2321. #endif
  2322. #ifndef VMA_SYSTEM_ALIGNED_FREE
  2323. // VMA_SYSTEM_FREE is the old name, but might have been defined by the user
  2324. #if defined(VMA_SYSTEM_FREE)
  2325. #define VMA_SYSTEM_ALIGNED_FREE(ptr) VMA_SYSTEM_FREE(ptr)
  2326. #else
  2327. #define VMA_SYSTEM_ALIGNED_FREE(ptr) vma_aligned_free(ptr)
  2328. #endif
  2329. #endif
  2330. #ifndef VMA_COUNT_BITS_SET
  2331. // Returns number of bits set to 1 in (v)
  2332. #define VMA_COUNT_BITS_SET(v) VmaCountBitsSet(v)
  2333. #endif
  2334. #ifndef VMA_BITSCAN_LSB
  2335. // Scans integer for index of first nonzero value from the Least Significant Bit (LSB). If mask is 0 then returns UINT8_MAX
  2336. #define VMA_BITSCAN_LSB(mask) VmaBitScanLSB(mask)
  2337. #endif
  2338. #ifndef VMA_BITSCAN_MSB
  2339. // Scans integer for index of first nonzero value from the Most Significant Bit (MSB). If mask is 0 then returns UINT8_MAX
  2340. #define VMA_BITSCAN_MSB(mask) VmaBitScanMSB(mask)
  2341. #endif
  2342. #ifndef VMA_MIN
  2343. #define VMA_MIN(v1, v2) ((std::min)((v1), (v2)))
  2344. #endif
  2345. #ifndef VMA_MAX
  2346. #define VMA_MAX(v1, v2) ((std::max)((v1), (v2)))
  2347. #endif
  2348. #ifndef VMA_SWAP
  2349. #define VMA_SWAP(v1, v2) std::swap((v1), (v2))
  2350. #endif
  2351. #ifndef VMA_SORT
  2352. #define VMA_SORT(beg, end, cmp) std::sort(beg, end, cmp)
  2353. #endif
  2354. #ifndef VMA_DEBUG_LOG_FORMAT
  2355. #define VMA_DEBUG_LOG_FORMAT(format, ...)
  2356. /*
  2357. #define VMA_DEBUG_LOG_FORMAT(format, ...) do { \
  2358. printf((format), __VA_ARGS__); \
  2359. printf("\n"); \
  2360. } while(false)
  2361. */
  2362. #endif
  2363. #ifndef VMA_DEBUG_LOG
  2364. #define VMA_DEBUG_LOG(str) VMA_DEBUG_LOG_FORMAT("%s", (str))
  2365. #endif
  2366. #ifndef VMA_CLASS_NO_COPY
  2367. #define VMA_CLASS_NO_COPY(className) \
  2368. private: \
  2369. className(const className&) = delete; \
  2370. className& operator=(const className&) = delete;
  2371. #endif
  2372. #ifndef VMA_CLASS_NO_COPY_NO_MOVE
  2373. #define VMA_CLASS_NO_COPY_NO_MOVE(className) \
  2374. private: \
  2375. className(const className&) = delete; \
  2376. className(className&&) = delete; \
  2377. className& operator=(const className&) = delete; \
  2378. className& operator=(className&&) = delete;
  2379. #endif
  2380. // Define this macro to 1 to enable functions: vmaBuildStatsString, vmaFreeStatsString.
  2381. #if VMA_STATS_STRING_ENABLED
  2382. static inline void VmaUint32ToStr(char* VMA_NOT_NULL outStr, size_t strLen, uint32_t num)
  2383. {
  2384. snprintf(outStr, strLen, "%u", static_cast<unsigned int>(num));
  2385. }
  2386. static inline void VmaUint64ToStr(char* VMA_NOT_NULL outStr, size_t strLen, uint64_t num)
  2387. {
  2388. snprintf(outStr, strLen, "%llu", static_cast<unsigned long long>(num));
  2389. }
  2390. static inline void VmaPtrToStr(char* VMA_NOT_NULL outStr, size_t strLen, const void* ptr)
  2391. {
  2392. snprintf(outStr, strLen, "%p", ptr);
  2393. }
  2394. #endif
  2395. #ifndef VMA_MUTEX
  2396. class VmaMutex
  2397. {
  2398. VMA_CLASS_NO_COPY_NO_MOVE(VmaMutex)
  2399. public:
  2400. VmaMutex() { }
  2401. void Lock() { m_Mutex.lock(); }
  2402. void Unlock() { m_Mutex.unlock(); }
  2403. bool TryLock() { return m_Mutex.try_lock(); }
  2404. private:
  2405. std::mutex m_Mutex;
  2406. };
  2407. #define VMA_MUTEX VmaMutex
  2408. #endif
  2409. // Read-write mutex, where "read" is shared access, "write" is exclusive access.
  2410. #ifndef VMA_RW_MUTEX
  2411. #if VMA_USE_STL_SHARED_MUTEX
  2412. // Use std::shared_mutex from C++17.
  2413. #include <shared_mutex>
  2414. class VmaRWMutex
  2415. {
  2416. public:
  2417. void LockRead() { m_Mutex.lock_shared(); }
  2418. void UnlockRead() { m_Mutex.unlock_shared(); }
  2419. bool TryLockRead() { return m_Mutex.try_lock_shared(); }
  2420. void LockWrite() { m_Mutex.lock(); }
  2421. void UnlockWrite() { m_Mutex.unlock(); }
  2422. bool TryLockWrite() { return m_Mutex.try_lock(); }
  2423. private:
  2424. std::shared_mutex m_Mutex;
  2425. };
  2426. #define VMA_RW_MUTEX VmaRWMutex
  2427. #elif defined(_WIN32) && defined(WINVER) && WINVER >= 0x0600
  2428. // Use SRWLOCK from WinAPI.
  2429. // Minimum supported client = Windows Vista, server = Windows Server 2008.
  2430. class VmaRWMutex
  2431. {
  2432. public:
  2433. VmaRWMutex() { InitializeSRWLock(&m_Lock); }
  2434. void LockRead() { AcquireSRWLockShared(&m_Lock); }
  2435. void UnlockRead() { ReleaseSRWLockShared(&m_Lock); }
  2436. bool TryLockRead() { return TryAcquireSRWLockShared(&m_Lock) != FALSE; }
  2437. void LockWrite() { AcquireSRWLockExclusive(&m_Lock); }
  2438. void UnlockWrite() { ReleaseSRWLockExclusive(&m_Lock); }
  2439. bool TryLockWrite() { return TryAcquireSRWLockExclusive(&m_Lock) != FALSE; }
  2440. private:
  2441. SRWLOCK m_Lock;
  2442. };
  2443. #define VMA_RW_MUTEX VmaRWMutex
  2444. #else
  2445. // Less efficient fallback: Use normal mutex.
  2446. class VmaRWMutex
  2447. {
  2448. public:
  2449. void LockRead() { m_Mutex.Lock(); }
  2450. void UnlockRead() { m_Mutex.Unlock(); }
  2451. bool TryLockRead() { return m_Mutex.TryLock(); }
  2452. void LockWrite() { m_Mutex.Lock(); }
  2453. void UnlockWrite() { m_Mutex.Unlock(); }
  2454. bool TryLockWrite() { return m_Mutex.TryLock(); }
  2455. private:
  2456. VMA_MUTEX m_Mutex;
  2457. };
  2458. #define VMA_RW_MUTEX VmaRWMutex
  2459. #endif // #if VMA_USE_STL_SHARED_MUTEX
  2460. #endif // #ifndef VMA_RW_MUTEX
  2461. /*
  2462. If providing your own implementation, you need to implement a subset of std::atomic.
  2463. */
  2464. #ifndef VMA_ATOMIC_UINT32
  2465. #include <atomic>
  2466. #define VMA_ATOMIC_UINT32 std::atomic<uint32_t>
  2467. #endif
  2468. #ifndef VMA_ATOMIC_UINT64
  2469. #include <atomic>
  2470. #define VMA_ATOMIC_UINT64 std::atomic<uint64_t>
  2471. #endif
  2472. #ifndef VMA_DEBUG_ALWAYS_DEDICATED_MEMORY
  2473. /**
  2474. Every allocation will have its own memory block.
  2475. Define to 1 for debugging purposes only.
  2476. */
  2477. #define VMA_DEBUG_ALWAYS_DEDICATED_MEMORY (0)
  2478. #endif
  2479. #ifndef VMA_MIN_ALIGNMENT
  2480. /**
  2481. Minimum alignment of all allocations, in bytes.
  2482. Set to more than 1 for debugging purposes. Must be power of two.
  2483. */
  2484. #ifdef VMA_DEBUG_ALIGNMENT // Old name
  2485. #define VMA_MIN_ALIGNMENT VMA_DEBUG_ALIGNMENT
  2486. #else
  2487. #define VMA_MIN_ALIGNMENT (1)
  2488. #endif
  2489. #endif
  2490. #ifndef VMA_DEBUG_MARGIN
  2491. /**
  2492. Minimum margin after every allocation, in bytes.
  2493. Set nonzero for debugging purposes only.
  2494. */
  2495. #define VMA_DEBUG_MARGIN (0)
  2496. #endif
  2497. #ifndef VMA_DEBUG_INITIALIZE_ALLOCATIONS
  2498. /**
  2499. Define this macro to 1 to automatically fill new allocations and destroyed
  2500. allocations with some bit pattern.
  2501. */
  2502. #define VMA_DEBUG_INITIALIZE_ALLOCATIONS (0)
  2503. #endif
  2504. #ifndef VMA_DEBUG_DETECT_CORRUPTION
  2505. /**
  2506. Define this macro to 1 together with non-zero value of VMA_DEBUG_MARGIN to
  2507. enable writing magic value to the margin after every allocation and
  2508. validating it, so that memory corruptions (out-of-bounds writes) are detected.
  2509. */
  2510. #define VMA_DEBUG_DETECT_CORRUPTION (0)
  2511. #endif
  2512. #ifndef VMA_DEBUG_GLOBAL_MUTEX
  2513. /**
  2514. Set this to 1 for debugging purposes only, to enable single mutex protecting all
  2515. entry calls to the library. Can be useful for debugging multithreading issues.
  2516. */
  2517. #define VMA_DEBUG_GLOBAL_MUTEX (0)
  2518. #endif
  2519. #ifndef VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY
  2520. /**
  2521. Minimum value for VkPhysicalDeviceLimits::bufferImageGranularity.
  2522. Set to more than 1 for debugging purposes only. Must be power of two.
  2523. */
  2524. #define VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY (1)
  2525. #endif
  2526. #ifndef VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT
  2527. /*
  2528. Set this to 1 to make VMA never exceed VkPhysicalDeviceLimits::maxMemoryAllocationCount
  2529. and return error instead of leaving up to Vulkan implementation what to do in such cases.
  2530. */
  2531. #define VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT (0)
  2532. #endif
  2533. #ifndef VMA_SMALL_HEAP_MAX_SIZE
  2534. /// Maximum size of a memory heap in Vulkan to consider it "small".
  2535. #define VMA_SMALL_HEAP_MAX_SIZE (1024ull * 1024 * 1024)
  2536. #endif
  2537. #ifndef VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE
  2538. /// Default size of a block allocated as single VkDeviceMemory from a "large" heap.
  2539. #define VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE (256ull * 1024 * 1024)
  2540. #endif
  2541. /*
  2542. Mapping hysteresis is a logic that launches when vmaMapMemory/vmaUnmapMemory is called
  2543. or a persistently mapped allocation is created and destroyed several times in a row.
  2544. It keeps additional +1 mapping of a device memory block to prevent calling actual
  2545. vkMapMemory/vkUnmapMemory too many times, which may improve performance and help
  2546. tools like RenderDoc.
  2547. */
  2548. #ifndef VMA_MAPPING_HYSTERESIS_ENABLED
  2549. #define VMA_MAPPING_HYSTERESIS_ENABLED 1
  2550. #endif
  2551. #define VMA_VALIDATE(cond) do { if(!(cond)) { \
  2552. VMA_ASSERT(0 && "Validation failed: " #cond); \
  2553. return false; \
  2554. } } while(false)
  2555. /*******************************************************************************
  2556. END OF CONFIGURATION
  2557. */
  2558. #endif // _VMA_CONFIGURATION
  2559. static const uint8_t VMA_ALLOCATION_FILL_PATTERN_CREATED = 0xDC;
  2560. static const uint8_t VMA_ALLOCATION_FILL_PATTERN_DESTROYED = 0xEF;
  2561. // Decimal 2139416166, float NaN, little-endian binary 66 E6 84 7F.
  2562. static const uint32_t VMA_CORRUPTION_DETECTION_MAGIC_VALUE = 0x7F84E666;
  2563. // Copy of some Vulkan definitions so we don't need to check their existence just to handle few constants.
  2564. static const uint32_t VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY = 0x00000040;
  2565. static const uint32_t VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY = 0x00000080;
  2566. static const uint32_t VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY = 0x00020000;
  2567. static const uint32_t VK_IMAGE_CREATE_DISJOINT_BIT_COPY = 0x00000200;
  2568. static const int32_t VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT_COPY = 1000158000;
  2569. static const uint32_t VMA_ALLOCATION_INTERNAL_STRATEGY_MIN_OFFSET = 0x10000000u;
  2570. static const uint32_t VMA_ALLOCATION_TRY_COUNT = 32;
  2571. static const uint32_t VMA_VENDOR_ID_AMD = 4098;
  2572. // This one is tricky. Vulkan specification defines this code as available since
  2573. // Vulkan 1.0, but doesn't actually define it in Vulkan SDK earlier than 1.2.131.
  2574. // See pull request #207.
  2575. #define VK_ERROR_UNKNOWN_COPY ((VkResult)-13)
  2576. #if VMA_STATS_STRING_ENABLED
  2577. // Correspond to values of enum VmaSuballocationType.
  2578. static const char* VMA_SUBALLOCATION_TYPE_NAMES[] =
  2579. {
  2580. "FREE",
  2581. "UNKNOWN",
  2582. "BUFFER",
  2583. "IMAGE_UNKNOWN",
  2584. "IMAGE_LINEAR",
  2585. "IMAGE_OPTIMAL",
  2586. };
  2587. #endif
  2588. static VkAllocationCallbacks VmaEmptyAllocationCallbacks =
  2589. { VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL };
  2590. #ifndef _VMA_ENUM_DECLARATIONS
  2591. enum VmaSuballocationType
  2592. {
  2593. VMA_SUBALLOCATION_TYPE_FREE = 0,
  2594. VMA_SUBALLOCATION_TYPE_UNKNOWN = 1,
  2595. VMA_SUBALLOCATION_TYPE_BUFFER = 2,
  2596. VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN = 3,
  2597. VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR = 4,
  2598. VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL = 5,
  2599. VMA_SUBALLOCATION_TYPE_MAX_ENUM = 0x7FFFFFFF
  2600. };
  2601. enum VMA_CACHE_OPERATION
  2602. {
  2603. VMA_CACHE_FLUSH,
  2604. VMA_CACHE_INVALIDATE
  2605. };
  2606. enum class VmaAllocationRequestType
  2607. {
  2608. Normal,
  2609. TLSF,
  2610. // Used by "Linear" algorithm.
  2611. UpperAddress,
  2612. EndOf1st,
  2613. EndOf2nd,
  2614. };
  2615. #endif // _VMA_ENUM_DECLARATIONS
  2616. #ifndef _VMA_FORWARD_DECLARATIONS
  2617. // Opaque handle used by allocation algorithms to identify single allocation in any conforming way.
  2618. VK_DEFINE_NON_DISPATCHABLE_HANDLE(VmaAllocHandle)
  2619. struct VmaMutexLock;
  2620. struct VmaMutexLockRead;
  2621. struct VmaMutexLockWrite;
  2622. template<typename T>
  2623. struct AtomicTransactionalIncrement;
  2624. template<typename T>
  2625. struct VmaStlAllocator;
  2626. template<typename T, typename AllocatorT>
  2627. class VmaVector;
  2628. template<typename T, typename AllocatorT, size_t N>
  2629. class VmaSmallVector;
  2630. template<typename T>
  2631. class VmaPoolAllocator;
  2632. template<typename T>
  2633. struct VmaListItem;
  2634. template<typename T>
  2635. class VmaRawList;
  2636. template<typename T, typename AllocatorT>
  2637. class VmaList;
  2638. template<typename ItemTypeTraits>
  2639. class VmaIntrusiveLinkedList;
  2640. // Unused in this version
  2641. #if 0
  2642. template<typename T1, typename T2>
  2643. struct VmaPair;
  2644. template<typename FirstT, typename SecondT>
  2645. struct VmaPairFirstLess;
  2646. template<typename KeyT, typename ValueT>
  2647. class VmaMap;
  2648. #endif
  2649. #if VMA_STATS_STRING_ENABLED
  2650. class VmaStringBuilder;
  2651. class VmaJsonWriter;
  2652. #endif
  2653. class VmaDeviceMemoryBlock;
  2654. struct VmaDedicatedAllocationListItemTraits;
  2655. class VmaDedicatedAllocationList;
  2656. struct VmaSuballocation;
  2657. struct VmaSuballocationOffsetLess;
  2658. struct VmaSuballocationOffsetGreater;
  2659. struct VmaSuballocationItemSizeLess;
  2660. typedef VmaList<VmaSuballocation, VmaStlAllocator<VmaSuballocation>> VmaSuballocationList;
  2661. struct VmaAllocationRequest;
  2662. class VmaBlockMetadata;
  2663. class VmaBlockMetadata_Linear;
  2664. class VmaBlockMetadata_TLSF;
  2665. class VmaBlockVector;
  2666. struct VmaPoolListItemTraits;
  2667. struct VmaCurrentBudgetData;
  2668. class VmaAllocationObjectAllocator;
  2669. #endif // _VMA_FORWARD_DECLARATIONS
  2670. #ifndef _VMA_FUNCTIONS
  2671. /*
  2672. Returns number of bits set to 1 in (v).
  2673. On specific platforms and compilers you can use instrinsics like:
  2674. Visual Studio:
  2675. return __popcnt(v);
  2676. GCC, Clang:
  2677. return static_cast<uint32_t>(__builtin_popcount(v));
  2678. Define macro VMA_COUNT_BITS_SET to provide your optimized implementation.
  2679. But you need to check in runtime whether user's CPU supports these, as some old processors don't.
  2680. */
  2681. static inline uint32_t VmaCountBitsSet(uint32_t v)
  2682. {
  2683. #if __cplusplus >= 202002L || _MSVC_LANG >= 202002L // C++20
  2684. return std::popcount(v);
  2685. #else
  2686. uint32_t c = v - ((v >> 1) & 0x55555555);
  2687. c = ((c >> 2) & 0x33333333) + (c & 0x33333333);
  2688. c = ((c >> 4) + c) & 0x0F0F0F0F;
  2689. c = ((c >> 8) + c) & 0x00FF00FF;
  2690. c = ((c >> 16) + c) & 0x0000FFFF;
  2691. return c;
  2692. #endif
  2693. }
  2694. static inline uint8_t VmaBitScanLSB(uint64_t mask)
  2695. {
  2696. #if defined(_MSC_VER) && defined(_WIN64)
  2697. unsigned long pos;
  2698. if (_BitScanForward64(&pos, mask))
  2699. return static_cast<uint8_t>(pos);
  2700. return UINT8_MAX;
  2701. #elif defined __GNUC__ || defined __clang__
  2702. return static_cast<uint8_t>(__builtin_ffsll(mask)) - 1U;
  2703. #else
  2704. uint8_t pos = 0;
  2705. uint64_t bit = 1;
  2706. do
  2707. {
  2708. if (mask & bit)
  2709. return pos;
  2710. bit <<= 1;
  2711. } while (pos++ < 63);
  2712. return UINT8_MAX;
  2713. #endif
  2714. }
  2715. static inline uint8_t VmaBitScanLSB(uint32_t mask)
  2716. {
  2717. #ifdef _MSC_VER
  2718. unsigned long pos;
  2719. if (_BitScanForward(&pos, mask))
  2720. return static_cast<uint8_t>(pos);
  2721. return UINT8_MAX;
  2722. #elif defined __GNUC__ || defined __clang__
  2723. return static_cast<uint8_t>(__builtin_ffs(mask)) - 1U;
  2724. #else
  2725. uint8_t pos = 0;
  2726. uint32_t bit = 1;
  2727. do
  2728. {
  2729. if (mask & bit)
  2730. return pos;
  2731. bit <<= 1;
  2732. } while (pos++ < 31);
  2733. return UINT8_MAX;
  2734. #endif
  2735. }
  2736. static inline uint8_t VmaBitScanMSB(uint64_t mask)
  2737. {
  2738. #if defined(_MSC_VER) && defined(_WIN64)
  2739. unsigned long pos;
  2740. if (_BitScanReverse64(&pos, mask))
  2741. return static_cast<uint8_t>(pos);
  2742. #elif defined __GNUC__ || defined __clang__
  2743. if (mask)
  2744. return 63 - static_cast<uint8_t>(__builtin_clzll(mask));
  2745. #else
  2746. uint8_t pos = 63;
  2747. uint64_t bit = 1ULL << 63;
  2748. do
  2749. {
  2750. if (mask & bit)
  2751. return pos;
  2752. bit >>= 1;
  2753. } while (pos-- > 0);
  2754. #endif
  2755. return UINT8_MAX;
  2756. }
  2757. static inline uint8_t VmaBitScanMSB(uint32_t mask)
  2758. {
  2759. #ifdef _MSC_VER
  2760. unsigned long pos;
  2761. if (_BitScanReverse(&pos, mask))
  2762. return static_cast<uint8_t>(pos);
  2763. #elif defined __GNUC__ || defined __clang__
  2764. if (mask)
  2765. return 31 - static_cast<uint8_t>(__builtin_clz(mask));
  2766. #else
  2767. uint8_t pos = 31;
  2768. uint32_t bit = 1UL << 31;
  2769. do
  2770. {
  2771. if (mask & bit)
  2772. return pos;
  2773. bit >>= 1;
  2774. } while (pos-- > 0);
  2775. #endif
  2776. return UINT8_MAX;
  2777. }
  2778. /*
  2779. Returns true if given number is a power of two.
  2780. T must be unsigned integer number or signed integer but always nonnegative.
  2781. For 0 returns true.
  2782. */
  2783. template <typename T>
  2784. inline bool VmaIsPow2(T x)
  2785. {
  2786. return (x & (x - 1)) == 0;
  2787. }
  2788. // Aligns given value up to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 16.
  2789. // Use types like uint32_t, uint64_t as T.
  2790. template <typename T>
  2791. static inline T VmaAlignUp(T val, T alignment)
  2792. {
  2793. VMA_HEAVY_ASSERT(VmaIsPow2(alignment));
  2794. return (val + alignment - 1) & ~(alignment - 1);
  2795. }
  2796. // Aligns given value down to nearest multiply of align value. For example: VmaAlignDown(11, 8) = 8.
  2797. // Use types like uint32_t, uint64_t as T.
  2798. template <typename T>
  2799. static inline T VmaAlignDown(T val, T alignment)
  2800. {
  2801. VMA_HEAVY_ASSERT(VmaIsPow2(alignment));
  2802. return val & ~(alignment - 1);
  2803. }
  2804. // Division with mathematical rounding to nearest number.
  2805. template <typename T>
  2806. static inline T VmaRoundDiv(T x, T y)
  2807. {
  2808. return (x + (y / (T)2)) / y;
  2809. }
  2810. // Divide by 'y' and round up to nearest integer.
  2811. template <typename T>
  2812. static inline T VmaDivideRoundingUp(T x, T y)
  2813. {
  2814. return (x + y - (T)1) / y;
  2815. }
  2816. // Returns smallest power of 2 greater or equal to v.
  2817. static inline uint32_t VmaNextPow2(uint32_t v)
  2818. {
  2819. v--;
  2820. v |= v >> 1;
  2821. v |= v >> 2;
  2822. v |= v >> 4;
  2823. v |= v >> 8;
  2824. v |= v >> 16;
  2825. v++;
  2826. return v;
  2827. }
  2828. static inline uint64_t VmaNextPow2(uint64_t v)
  2829. {
  2830. v--;
  2831. v |= v >> 1;
  2832. v |= v >> 2;
  2833. v |= v >> 4;
  2834. v |= v >> 8;
  2835. v |= v >> 16;
  2836. v |= v >> 32;
  2837. v++;
  2838. return v;
  2839. }
  2840. // Returns largest power of 2 less or equal to v.
  2841. static inline uint32_t VmaPrevPow2(uint32_t v)
  2842. {
  2843. v |= v >> 1;
  2844. v |= v >> 2;
  2845. v |= v >> 4;
  2846. v |= v >> 8;
  2847. v |= v >> 16;
  2848. v = v ^ (v >> 1);
  2849. return v;
  2850. }
  2851. static inline uint64_t VmaPrevPow2(uint64_t v)
  2852. {
  2853. v |= v >> 1;
  2854. v |= v >> 2;
  2855. v |= v >> 4;
  2856. v |= v >> 8;
  2857. v |= v >> 16;
  2858. v |= v >> 32;
  2859. v = v ^ (v >> 1);
  2860. return v;
  2861. }
  2862. static inline bool VmaStrIsEmpty(const char* pStr)
  2863. {
  2864. return pStr == VMA_NULL || *pStr == '\0';
  2865. }
  2866. /*
  2867. Returns true if two memory blocks occupy overlapping pages.
  2868. ResourceA must be in less memory offset than ResourceB.
  2869. Algorithm is based on "Vulkan 1.0.39 - A Specification (with all registered Vulkan extensions)"
  2870. chapter 11.6 "Resource Memory Association", paragraph "Buffer-Image Granularity".
  2871. */
  2872. static inline bool VmaBlocksOnSamePage(
  2873. VkDeviceSize resourceAOffset,
  2874. VkDeviceSize resourceASize,
  2875. VkDeviceSize resourceBOffset,
  2876. VkDeviceSize pageSize)
  2877. {
  2878. VMA_ASSERT(resourceAOffset + resourceASize <= resourceBOffset && resourceASize > 0 && pageSize > 0);
  2879. VkDeviceSize resourceAEnd = resourceAOffset + resourceASize - 1;
  2880. VkDeviceSize resourceAEndPage = resourceAEnd & ~(pageSize - 1);
  2881. VkDeviceSize resourceBStart = resourceBOffset;
  2882. VkDeviceSize resourceBStartPage = resourceBStart & ~(pageSize - 1);
  2883. return resourceAEndPage == resourceBStartPage;
  2884. }
  2885. /*
  2886. Returns true if given suballocation types could conflict and must respect
  2887. VkPhysicalDeviceLimits::bufferImageGranularity. They conflict if one is buffer
  2888. or linear image and another one is optimal image. If type is unknown, behave
  2889. conservatively.
  2890. */
  2891. static inline bool VmaIsBufferImageGranularityConflict(
  2892. VmaSuballocationType suballocType1,
  2893. VmaSuballocationType suballocType2)
  2894. {
  2895. if (suballocType1 > suballocType2)
  2896. {
  2897. VMA_SWAP(suballocType1, suballocType2);
  2898. }
  2899. switch (suballocType1)
  2900. {
  2901. case VMA_SUBALLOCATION_TYPE_FREE:
  2902. return false;
  2903. case VMA_SUBALLOCATION_TYPE_UNKNOWN:
  2904. return true;
  2905. case VMA_SUBALLOCATION_TYPE_BUFFER:
  2906. return
  2907. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
  2908. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
  2909. case VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN:
  2910. return
  2911. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
  2912. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR ||
  2913. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
  2914. case VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR:
  2915. return
  2916. suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
  2917. case VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL:
  2918. return false;
  2919. default:
  2920. VMA_ASSERT(0);
  2921. return true;
  2922. }
  2923. }
  2924. static void VmaWriteMagicValue(void* pData, VkDeviceSize offset)
  2925. {
  2926. #if VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_DETECT_CORRUPTION
  2927. uint32_t* pDst = (uint32_t*)((char*)pData + offset);
  2928. const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t);
  2929. for (size_t i = 0; i < numberCount; ++i, ++pDst)
  2930. {
  2931. *pDst = VMA_CORRUPTION_DETECTION_MAGIC_VALUE;
  2932. }
  2933. #else
  2934. // no-op
  2935. #endif
  2936. }
  2937. static bool VmaValidateMagicValue(const void* pData, VkDeviceSize offset)
  2938. {
  2939. #if VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_DETECT_CORRUPTION
  2940. const uint32_t* pSrc = (const uint32_t*)((const char*)pData + offset);
  2941. const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t);
  2942. for (size_t i = 0; i < numberCount; ++i, ++pSrc)
  2943. {
  2944. if (*pSrc != VMA_CORRUPTION_DETECTION_MAGIC_VALUE)
  2945. {
  2946. return false;
  2947. }
  2948. }
  2949. #endif
  2950. return true;
  2951. }
  2952. /*
  2953. Fills structure with parameters of an example buffer to be used for transfers
  2954. during GPU memory defragmentation.
  2955. */
  2956. static void VmaFillGpuDefragmentationBufferCreateInfo(VkBufferCreateInfo& outBufCreateInfo)
  2957. {
  2958. memset(&outBufCreateInfo, 0, sizeof(outBufCreateInfo));
  2959. outBufCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  2960. outBufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  2961. outBufCreateInfo.size = (VkDeviceSize)VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE; // Example size.
  2962. }
  2963. /*
  2964. Performs binary search and returns iterator to first element that is greater or
  2965. equal to (key), according to comparison (cmp).
  2966. Cmp should return true if first argument is less than second argument.
  2967. Returned value is the found element, if present in the collection or place where
  2968. new element with value (key) should be inserted.
  2969. */
  2970. template <typename CmpLess, typename IterT, typename KeyT>
  2971. static IterT VmaBinaryFindFirstNotLess(IterT beg, IterT end, const KeyT& key, const CmpLess& cmp)
  2972. {
  2973. size_t down = 0, up = size_t(end - beg);
  2974. while (down < up)
  2975. {
  2976. const size_t mid = down + (up - down) / 2; // Overflow-safe midpoint calculation
  2977. if (cmp(*(beg + mid), key))
  2978. {
  2979. down = mid + 1;
  2980. }
  2981. else
  2982. {
  2983. up = mid;
  2984. }
  2985. }
  2986. return beg + down;
  2987. }
  2988. template<typename CmpLess, typename IterT, typename KeyT>
  2989. IterT VmaBinaryFindSorted(const IterT& beg, const IterT& end, const KeyT& value, const CmpLess& cmp)
  2990. {
  2991. IterT it = VmaBinaryFindFirstNotLess<CmpLess, IterT, KeyT>(
  2992. beg, end, value, cmp);
  2993. if (it == end ||
  2994. (!cmp(*it, value) && !cmp(value, *it)))
  2995. {
  2996. return it;
  2997. }
  2998. return end;
  2999. }
  3000. /*
  3001. Returns true if all pointers in the array are not-null and unique.
  3002. Warning! O(n^2) complexity. Use only inside VMA_HEAVY_ASSERT.
  3003. T must be pointer type, e.g. VmaAllocation, VmaPool.
  3004. */
  3005. template<typename T>
  3006. static bool VmaValidatePointerArray(uint32_t count, const T* arr)
  3007. {
  3008. for (uint32_t i = 0; i < count; ++i)
  3009. {
  3010. const T iPtr = arr[i];
  3011. if (iPtr == VMA_NULL)
  3012. {
  3013. return false;
  3014. }
  3015. for (uint32_t j = i + 1; j < count; ++j)
  3016. {
  3017. if (iPtr == arr[j])
  3018. {
  3019. return false;
  3020. }
  3021. }
  3022. }
  3023. return true;
  3024. }
  3025. template<typename MainT, typename NewT>
  3026. static inline void VmaPnextChainPushFront(MainT* mainStruct, NewT* newStruct)
  3027. {
  3028. newStruct->pNext = mainStruct->pNext;
  3029. mainStruct->pNext = newStruct;
  3030. }
  3031. // This is the main algorithm that guides the selection of a memory type best for an allocation -
  3032. // converts usage to required/preferred/not preferred flags.
  3033. static bool FindMemoryPreferences(
  3034. bool isIntegratedGPU,
  3035. const VmaAllocationCreateInfo& allocCreateInfo,
  3036. VkFlags bufImgUsage, // VkBufferCreateInfo::usage or VkImageCreateInfo::usage. UINT32_MAX if unknown.
  3037. VkMemoryPropertyFlags& outRequiredFlags,
  3038. VkMemoryPropertyFlags& outPreferredFlags,
  3039. VkMemoryPropertyFlags& outNotPreferredFlags)
  3040. {
  3041. outRequiredFlags = allocCreateInfo.requiredFlags;
  3042. outPreferredFlags = allocCreateInfo.preferredFlags;
  3043. outNotPreferredFlags = 0;
  3044. switch(allocCreateInfo.usage)
  3045. {
  3046. case VMA_MEMORY_USAGE_UNKNOWN:
  3047. break;
  3048. case VMA_MEMORY_USAGE_GPU_ONLY:
  3049. if(!isIntegratedGPU || (outPreferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  3050. {
  3051. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3052. }
  3053. break;
  3054. case VMA_MEMORY_USAGE_CPU_ONLY:
  3055. outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
  3056. break;
  3057. case VMA_MEMORY_USAGE_CPU_TO_GPU:
  3058. outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  3059. if(!isIntegratedGPU || (outPreferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  3060. {
  3061. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3062. }
  3063. break;
  3064. case VMA_MEMORY_USAGE_GPU_TO_CPU:
  3065. outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  3066. outPreferredFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  3067. break;
  3068. case VMA_MEMORY_USAGE_CPU_COPY:
  3069. outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3070. break;
  3071. case VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED:
  3072. outRequiredFlags |= VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT;
  3073. break;
  3074. case VMA_MEMORY_USAGE_AUTO:
  3075. case VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE:
  3076. case VMA_MEMORY_USAGE_AUTO_PREFER_HOST:
  3077. {
  3078. if(bufImgUsage == UINT32_MAX)
  3079. {
  3080. VMA_ASSERT(0 && "VMA_MEMORY_USAGE_AUTO* values can only be used with functions like vmaCreateBuffer, vmaCreateImage so that the details of the created resource are known.");
  3081. return false;
  3082. }
  3083. // This relies on values of VK_IMAGE_USAGE_TRANSFER* being the same VK_BUFFER_IMAGE_TRANSFER*.
  3084. const bool deviceAccess = (bufImgUsage & ~(VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT)) != 0;
  3085. const bool hostAccessSequentialWrite = (allocCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT) != 0;
  3086. const bool hostAccessRandom = (allocCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT) != 0;
  3087. const bool hostAccessAllowTransferInstead = (allocCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT) != 0;
  3088. const bool preferDevice = allocCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE;
  3089. const bool preferHost = allocCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_HOST;
  3090. // CPU random access - e.g. a buffer written to or transferred from GPU to read back on CPU.
  3091. if(hostAccessRandom)
  3092. {
  3093. // Prefer cached. Cannot require it, because some platforms don't have it (e.g. Raspberry Pi - see #362)!
  3094. outPreferredFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  3095. if (!isIntegratedGPU && deviceAccess && hostAccessAllowTransferInstead && !preferHost)
  3096. {
  3097. // Nice if it will end up in HOST_VISIBLE, but more importantly prefer DEVICE_LOCAL.
  3098. // Omitting HOST_VISIBLE here is intentional.
  3099. // In case there is DEVICE_LOCAL | HOST_VISIBLE | HOST_CACHED, it will pick that one.
  3100. // Otherwise, this will give same weight to DEVICE_LOCAL as HOST_VISIBLE | HOST_CACHED and select the former if occurs first on the list.
  3101. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3102. }
  3103. else
  3104. {
  3105. // Always CPU memory.
  3106. outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  3107. }
  3108. }
  3109. // CPU sequential write - may be CPU or host-visible GPU memory, uncached and write-combined.
  3110. else if(hostAccessSequentialWrite)
  3111. {
  3112. // Want uncached and write-combined.
  3113. outNotPreferredFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  3114. if(!isIntegratedGPU && deviceAccess && hostAccessAllowTransferInstead && !preferHost)
  3115. {
  3116. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  3117. }
  3118. else
  3119. {
  3120. outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  3121. // Direct GPU access, CPU sequential write (e.g. a dynamic uniform buffer updated every frame)
  3122. if(deviceAccess)
  3123. {
  3124. // Could go to CPU memory or GPU BAR/unified. Up to the user to decide. If no preference, choose GPU memory.
  3125. if(preferHost)
  3126. outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3127. else
  3128. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3129. }
  3130. // GPU no direct access, CPU sequential write (e.g. an upload buffer to be transferred to the GPU)
  3131. else
  3132. {
  3133. // Could go to CPU memory or GPU BAR/unified. Up to the user to decide. If no preference, choose CPU memory.
  3134. if(preferDevice)
  3135. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3136. else
  3137. outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3138. }
  3139. }
  3140. }
  3141. // No CPU access
  3142. else
  3143. {
  3144. // if(deviceAccess)
  3145. //
  3146. // GPU access, no CPU access (e.g. a color attachment image) - prefer GPU memory,
  3147. // unless there is a clear preference from the user not to do so.
  3148. //
  3149. // else:
  3150. //
  3151. // No direct GPU access, no CPU access, just transfers.
  3152. // It may be staging copy intended for e.g. preserving image for next frame (then better GPU memory) or
  3153. // a "swap file" copy to free some GPU memory (then better CPU memory).
  3154. // Up to the user to decide. If no preferece, assume the former and choose GPU memory.
  3155. if(preferHost)
  3156. outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3157. else
  3158. outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  3159. }
  3160. break;
  3161. }
  3162. default:
  3163. VMA_ASSERT(0);
  3164. }
  3165. // Avoid DEVICE_COHERENT unless explicitly requested.
  3166. if(((allocCreateInfo.requiredFlags | allocCreateInfo.preferredFlags) &
  3167. (VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY | VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY)) == 0)
  3168. {
  3169. outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY;
  3170. }
  3171. return true;
  3172. }
  3173. ////////////////////////////////////////////////////////////////////////////////
  3174. // Memory allocation
  3175. static void* VmaMalloc(const VkAllocationCallbacks* pAllocationCallbacks, size_t size, size_t alignment)
  3176. {
  3177. void* result = VMA_NULL;
  3178. if ((pAllocationCallbacks != VMA_NULL) &&
  3179. (pAllocationCallbacks->pfnAllocation != VMA_NULL))
  3180. {
  3181. result = (*pAllocationCallbacks->pfnAllocation)(
  3182. pAllocationCallbacks->pUserData,
  3183. size,
  3184. alignment,
  3185. VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
  3186. }
  3187. else
  3188. {
  3189. result = VMA_SYSTEM_ALIGNED_MALLOC(size, alignment);
  3190. }
  3191. VMA_ASSERT(result != VMA_NULL && "CPU memory allocation failed.");
  3192. return result;
  3193. }
  3194. static void VmaFree(const VkAllocationCallbacks* pAllocationCallbacks, void* ptr)
  3195. {
  3196. if ((pAllocationCallbacks != VMA_NULL) &&
  3197. (pAllocationCallbacks->pfnFree != VMA_NULL))
  3198. {
  3199. (*pAllocationCallbacks->pfnFree)(pAllocationCallbacks->pUserData, ptr);
  3200. }
  3201. else
  3202. {
  3203. VMA_SYSTEM_ALIGNED_FREE(ptr);
  3204. }
  3205. }
  3206. template<typename T>
  3207. static T* VmaAllocate(const VkAllocationCallbacks* pAllocationCallbacks)
  3208. {
  3209. return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T), VMA_ALIGN_OF(T));
  3210. }
  3211. template<typename T>
  3212. static T* VmaAllocateArray(const VkAllocationCallbacks* pAllocationCallbacks, size_t count)
  3213. {
  3214. return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T) * count, VMA_ALIGN_OF(T));
  3215. }
  3216. #define vma_new(allocator, type) new(VmaAllocate<type>(allocator))(type)
  3217. #define vma_new_array(allocator, type, count) new(VmaAllocateArray<type>((allocator), (count)))(type)
  3218. template<typename T>
  3219. static void vma_delete(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr)
  3220. {
  3221. ptr->~T();
  3222. VmaFree(pAllocationCallbacks, ptr);
  3223. }
  3224. template<typename T>
  3225. static void vma_delete_array(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr, size_t count)
  3226. {
  3227. if (ptr != VMA_NULL)
  3228. {
  3229. for (size_t i = count; i--; )
  3230. {
  3231. ptr[i].~T();
  3232. }
  3233. VmaFree(pAllocationCallbacks, ptr);
  3234. }
  3235. }
  3236. static char* VmaCreateStringCopy(const VkAllocationCallbacks* allocs, const char* srcStr)
  3237. {
  3238. if (srcStr != VMA_NULL)
  3239. {
  3240. const size_t len = strlen(srcStr);
  3241. char* const result = vma_new_array(allocs, char, len + 1);
  3242. memcpy(result, srcStr, len + 1);
  3243. return result;
  3244. }
  3245. return VMA_NULL;
  3246. }
  3247. #if VMA_STATS_STRING_ENABLED
  3248. static char* VmaCreateStringCopy(const VkAllocationCallbacks* allocs, const char* srcStr, size_t strLen)
  3249. {
  3250. if (srcStr != VMA_NULL)
  3251. {
  3252. char* const result = vma_new_array(allocs, char, strLen + 1);
  3253. memcpy(result, srcStr, strLen);
  3254. result[strLen] = '\0';
  3255. return result;
  3256. }
  3257. return VMA_NULL;
  3258. }
  3259. #endif // VMA_STATS_STRING_ENABLED
  3260. static void VmaFreeString(const VkAllocationCallbacks* allocs, char* str)
  3261. {
  3262. if (str != VMA_NULL)
  3263. {
  3264. const size_t len = strlen(str);
  3265. vma_delete_array(allocs, str, len + 1);
  3266. }
  3267. }
  3268. template<typename CmpLess, typename VectorT>
  3269. size_t VmaVectorInsertSorted(VectorT& vector, const typename VectorT::value_type& value)
  3270. {
  3271. const size_t indexToInsert = VmaBinaryFindFirstNotLess(
  3272. vector.data(),
  3273. vector.data() + vector.size(),
  3274. value,
  3275. CmpLess()) - vector.data();
  3276. VmaVectorInsert(vector, indexToInsert, value);
  3277. return indexToInsert;
  3278. }
  3279. template<typename CmpLess, typename VectorT>
  3280. bool VmaVectorRemoveSorted(VectorT& vector, const typename VectorT::value_type& value)
  3281. {
  3282. CmpLess comparator;
  3283. typename VectorT::iterator it = VmaBinaryFindFirstNotLess(
  3284. vector.begin(),
  3285. vector.end(),
  3286. value,
  3287. comparator);
  3288. if ((it != vector.end()) && !comparator(*it, value) && !comparator(value, *it))
  3289. {
  3290. size_t indexToRemove = it - vector.begin();
  3291. VmaVectorRemove(vector, indexToRemove);
  3292. return true;
  3293. }
  3294. return false;
  3295. }
  3296. #endif // _VMA_FUNCTIONS
  3297. #ifndef _VMA_STATISTICS_FUNCTIONS
  3298. static void VmaClearStatistics(VmaStatistics& outStats)
  3299. {
  3300. outStats.blockCount = 0;
  3301. outStats.allocationCount = 0;
  3302. outStats.blockBytes = 0;
  3303. outStats.allocationBytes = 0;
  3304. }
  3305. static void VmaAddStatistics(VmaStatistics& inoutStats, const VmaStatistics& src)
  3306. {
  3307. inoutStats.blockCount += src.blockCount;
  3308. inoutStats.allocationCount += src.allocationCount;
  3309. inoutStats.blockBytes += src.blockBytes;
  3310. inoutStats.allocationBytes += src.allocationBytes;
  3311. }
  3312. static void VmaClearDetailedStatistics(VmaDetailedStatistics& outStats)
  3313. {
  3314. VmaClearStatistics(outStats.statistics);
  3315. outStats.unusedRangeCount = 0;
  3316. outStats.allocationSizeMin = VK_WHOLE_SIZE;
  3317. outStats.allocationSizeMax = 0;
  3318. outStats.unusedRangeSizeMin = VK_WHOLE_SIZE;
  3319. outStats.unusedRangeSizeMax = 0;
  3320. }
  3321. static void VmaAddDetailedStatisticsAllocation(VmaDetailedStatistics& inoutStats, VkDeviceSize size)
  3322. {
  3323. inoutStats.statistics.allocationCount++;
  3324. inoutStats.statistics.allocationBytes += size;
  3325. inoutStats.allocationSizeMin = VMA_MIN(inoutStats.allocationSizeMin, size);
  3326. inoutStats.allocationSizeMax = VMA_MAX(inoutStats.allocationSizeMax, size);
  3327. }
  3328. static void VmaAddDetailedStatisticsUnusedRange(VmaDetailedStatistics& inoutStats, VkDeviceSize size)
  3329. {
  3330. inoutStats.unusedRangeCount++;
  3331. inoutStats.unusedRangeSizeMin = VMA_MIN(inoutStats.unusedRangeSizeMin, size);
  3332. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, size);
  3333. }
  3334. static void VmaAddDetailedStatistics(VmaDetailedStatistics& inoutStats, const VmaDetailedStatistics& src)
  3335. {
  3336. VmaAddStatistics(inoutStats.statistics, src.statistics);
  3337. inoutStats.unusedRangeCount += src.unusedRangeCount;
  3338. inoutStats.allocationSizeMin = VMA_MIN(inoutStats.allocationSizeMin, src.allocationSizeMin);
  3339. inoutStats.allocationSizeMax = VMA_MAX(inoutStats.allocationSizeMax, src.allocationSizeMax);
  3340. inoutStats.unusedRangeSizeMin = VMA_MIN(inoutStats.unusedRangeSizeMin, src.unusedRangeSizeMin);
  3341. inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, src.unusedRangeSizeMax);
  3342. }
  3343. #endif // _VMA_STATISTICS_FUNCTIONS
  3344. #ifndef _VMA_MUTEX_LOCK
  3345. // Helper RAII class to lock a mutex in constructor and unlock it in destructor (at the end of scope).
  3346. struct VmaMutexLock
  3347. {
  3348. VMA_CLASS_NO_COPY_NO_MOVE(VmaMutexLock)
  3349. public:
  3350. VmaMutexLock(VMA_MUTEX& mutex, bool useMutex = true) :
  3351. m_pMutex(useMutex ? &mutex : VMA_NULL)
  3352. {
  3353. if (m_pMutex) { m_pMutex->Lock(); }
  3354. }
  3355. ~VmaMutexLock() { if (m_pMutex) { m_pMutex->Unlock(); } }
  3356. private:
  3357. VMA_MUTEX* m_pMutex;
  3358. };
  3359. // Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for reading.
  3360. struct VmaMutexLockRead
  3361. {
  3362. VMA_CLASS_NO_COPY_NO_MOVE(VmaMutexLockRead)
  3363. public:
  3364. VmaMutexLockRead(VMA_RW_MUTEX& mutex, bool useMutex) :
  3365. m_pMutex(useMutex ? &mutex : VMA_NULL)
  3366. {
  3367. if (m_pMutex) { m_pMutex->LockRead(); }
  3368. }
  3369. ~VmaMutexLockRead() { if (m_pMutex) { m_pMutex->UnlockRead(); } }
  3370. private:
  3371. VMA_RW_MUTEX* m_pMutex;
  3372. };
  3373. // Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for writing.
  3374. struct VmaMutexLockWrite
  3375. {
  3376. VMA_CLASS_NO_COPY_NO_MOVE(VmaMutexLockWrite)
  3377. public:
  3378. VmaMutexLockWrite(VMA_RW_MUTEX& mutex, bool useMutex)
  3379. : m_pMutex(useMutex ? &mutex : VMA_NULL)
  3380. {
  3381. if (m_pMutex) { m_pMutex->LockWrite(); }
  3382. }
  3383. ~VmaMutexLockWrite() { if (m_pMutex) { m_pMutex->UnlockWrite(); } }
  3384. private:
  3385. VMA_RW_MUTEX* m_pMutex;
  3386. };
  3387. #if VMA_DEBUG_GLOBAL_MUTEX
  3388. static VMA_MUTEX gDebugGlobalMutex;
  3389. #define VMA_DEBUG_GLOBAL_MUTEX_LOCK VmaMutexLock debugGlobalMutexLock(gDebugGlobalMutex, true);
  3390. #else
  3391. #define VMA_DEBUG_GLOBAL_MUTEX_LOCK
  3392. #endif
  3393. #endif // _VMA_MUTEX_LOCK
  3394. #ifndef _VMA_ATOMIC_TRANSACTIONAL_INCREMENT
  3395. // An object that increments given atomic but decrements it back in the destructor unless Commit() is called.
  3396. template<typename AtomicT>
  3397. struct AtomicTransactionalIncrement
  3398. {
  3399. public:
  3400. using T = decltype(AtomicT().load());
  3401. ~AtomicTransactionalIncrement()
  3402. {
  3403. if(m_Atomic)
  3404. --(*m_Atomic);
  3405. }
  3406. void Commit() { m_Atomic = nullptr; }
  3407. T Increment(AtomicT* atomic)
  3408. {
  3409. m_Atomic = atomic;
  3410. return m_Atomic->fetch_add(1);
  3411. }
  3412. private:
  3413. AtomicT* m_Atomic = nullptr;
  3414. };
  3415. #endif // _VMA_ATOMIC_TRANSACTIONAL_INCREMENT
  3416. #ifndef _VMA_STL_ALLOCATOR
  3417. // STL-compatible allocator.
  3418. template<typename T>
  3419. struct VmaStlAllocator
  3420. {
  3421. const VkAllocationCallbacks* const m_pCallbacks;
  3422. typedef T value_type;
  3423. VmaStlAllocator(const VkAllocationCallbacks* pCallbacks) : m_pCallbacks(pCallbacks) {}
  3424. template<typename U>
  3425. VmaStlAllocator(const VmaStlAllocator<U>& src) : m_pCallbacks(src.m_pCallbacks) {}
  3426. VmaStlAllocator(const VmaStlAllocator&) = default;
  3427. VmaStlAllocator& operator=(const VmaStlAllocator&) = delete;
  3428. T* allocate(size_t n) { return VmaAllocateArray<T>(m_pCallbacks, n); }
  3429. void deallocate(T* p, size_t n) { VmaFree(m_pCallbacks, p); }
  3430. template<typename U>
  3431. bool operator==(const VmaStlAllocator<U>& rhs) const
  3432. {
  3433. return m_pCallbacks == rhs.m_pCallbacks;
  3434. }
  3435. template<typename U>
  3436. bool operator!=(const VmaStlAllocator<U>& rhs) const
  3437. {
  3438. return m_pCallbacks != rhs.m_pCallbacks;
  3439. }
  3440. };
  3441. #endif // _VMA_STL_ALLOCATOR
  3442. #ifndef _VMA_VECTOR
  3443. /* Class with interface compatible with subset of std::vector.
  3444. T must be POD because constructors and destructors are not called and memcpy is
  3445. used for these objects. */
  3446. template<typename T, typename AllocatorT>
  3447. class VmaVector
  3448. {
  3449. public:
  3450. typedef T value_type;
  3451. typedef T* iterator;
  3452. typedef const T* const_iterator;
  3453. VmaVector(const AllocatorT& allocator);
  3454. VmaVector(size_t count, const AllocatorT& allocator);
  3455. // This version of the constructor is here for compatibility with pre-C++14 std::vector.
  3456. // value is unused.
  3457. VmaVector(size_t count, const T& value, const AllocatorT& allocator) : VmaVector(count, allocator) {}
  3458. VmaVector(const VmaVector<T, AllocatorT>& src);
  3459. VmaVector& operator=(const VmaVector& rhs);
  3460. ~VmaVector() { VmaFree(m_Allocator.m_pCallbacks, m_pArray); }
  3461. bool empty() const { return m_Count == 0; }
  3462. size_t size() const { return m_Count; }
  3463. T* data() { return m_pArray; }
  3464. T& front() { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[0]; }
  3465. T& back() { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[m_Count - 1]; }
  3466. const T* data() const { return m_pArray; }
  3467. const T& front() const { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[0]; }
  3468. const T& back() const { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[m_Count - 1]; }
  3469. iterator begin() { return m_pArray; }
  3470. iterator end() { return m_pArray + m_Count; }
  3471. const_iterator cbegin() const { return m_pArray; }
  3472. const_iterator cend() const { return m_pArray + m_Count; }
  3473. const_iterator begin() const { return cbegin(); }
  3474. const_iterator end() const { return cend(); }
  3475. void pop_front() { VMA_HEAVY_ASSERT(m_Count > 0); remove(0); }
  3476. void pop_back() { VMA_HEAVY_ASSERT(m_Count > 0); resize(size() - 1); }
  3477. void push_front(const T& src) { insert(0, src); }
  3478. void push_back(const T& src);
  3479. void reserve(size_t newCapacity, bool freeMemory = false);
  3480. void resize(size_t newCount);
  3481. void clear() { resize(0); }
  3482. void shrink_to_fit();
  3483. void insert(size_t index, const T& src);
  3484. void remove(size_t index);
  3485. T& operator[](size_t index) { VMA_HEAVY_ASSERT(index < m_Count); return m_pArray[index]; }
  3486. const T& operator[](size_t index) const { VMA_HEAVY_ASSERT(index < m_Count); return m_pArray[index]; }
  3487. private:
  3488. AllocatorT m_Allocator;
  3489. T* m_pArray;
  3490. size_t m_Count;
  3491. size_t m_Capacity;
  3492. };
  3493. #ifndef _VMA_VECTOR_FUNCTIONS
  3494. template<typename T, typename AllocatorT>
  3495. VmaVector<T, AllocatorT>::VmaVector(const AllocatorT& allocator)
  3496. : m_Allocator(allocator),
  3497. m_pArray(VMA_NULL),
  3498. m_Count(0),
  3499. m_Capacity(0) {}
  3500. template<typename T, typename AllocatorT>
  3501. VmaVector<T, AllocatorT>::VmaVector(size_t count, const AllocatorT& allocator)
  3502. : m_Allocator(allocator),
  3503. m_pArray(count ? (T*)VmaAllocateArray<T>(allocator.m_pCallbacks, count) : VMA_NULL),
  3504. m_Count(count),
  3505. m_Capacity(count) {}
  3506. template<typename T, typename AllocatorT>
  3507. VmaVector<T, AllocatorT>::VmaVector(const VmaVector& src)
  3508. : m_Allocator(src.m_Allocator),
  3509. m_pArray(src.m_Count ? (T*)VmaAllocateArray<T>(src.m_Allocator.m_pCallbacks, src.m_Count) : VMA_NULL),
  3510. m_Count(src.m_Count),
  3511. m_Capacity(src.m_Count)
  3512. {
  3513. if (m_Count != 0)
  3514. {
  3515. memcpy(m_pArray, src.m_pArray, m_Count * sizeof(T));
  3516. }
  3517. }
  3518. template<typename T, typename AllocatorT>
  3519. VmaVector<T, AllocatorT>& VmaVector<T, AllocatorT>::operator=(const VmaVector& rhs)
  3520. {
  3521. if (&rhs != this)
  3522. {
  3523. resize(rhs.m_Count);
  3524. if (m_Count != 0)
  3525. {
  3526. memcpy(m_pArray, rhs.m_pArray, m_Count * sizeof(T));
  3527. }
  3528. }
  3529. return *this;
  3530. }
  3531. template<typename T, typename AllocatorT>
  3532. void VmaVector<T, AllocatorT>::push_back(const T& src)
  3533. {
  3534. const size_t newIndex = size();
  3535. resize(newIndex + 1);
  3536. m_pArray[newIndex] = src;
  3537. }
  3538. template<typename T, typename AllocatorT>
  3539. void VmaVector<T, AllocatorT>::reserve(size_t newCapacity, bool freeMemory)
  3540. {
  3541. newCapacity = VMA_MAX(newCapacity, m_Count);
  3542. if ((newCapacity < m_Capacity) && !freeMemory)
  3543. {
  3544. newCapacity = m_Capacity;
  3545. }
  3546. if (newCapacity != m_Capacity)
  3547. {
  3548. T* const newArray = newCapacity ? VmaAllocateArray<T>(m_Allocator, newCapacity) : VMA_NULL;
  3549. if (m_Count != 0)
  3550. {
  3551. memcpy(newArray, m_pArray, m_Count * sizeof(T));
  3552. }
  3553. VmaFree(m_Allocator.m_pCallbacks, m_pArray);
  3554. m_Capacity = newCapacity;
  3555. m_pArray = newArray;
  3556. }
  3557. }
  3558. template<typename T, typename AllocatorT>
  3559. void VmaVector<T, AllocatorT>::resize(size_t newCount)
  3560. {
  3561. size_t newCapacity = m_Capacity;
  3562. if (newCount > m_Capacity)
  3563. {
  3564. newCapacity = VMA_MAX(newCount, VMA_MAX(m_Capacity * 3 / 2, (size_t)8));
  3565. }
  3566. if (newCapacity != m_Capacity)
  3567. {
  3568. T* const newArray = newCapacity ? VmaAllocateArray<T>(m_Allocator.m_pCallbacks, newCapacity) : VMA_NULL;
  3569. const size_t elementsToCopy = VMA_MIN(m_Count, newCount);
  3570. if (elementsToCopy != 0)
  3571. {
  3572. memcpy(newArray, m_pArray, elementsToCopy * sizeof(T));
  3573. }
  3574. VmaFree(m_Allocator.m_pCallbacks, m_pArray);
  3575. m_Capacity = newCapacity;
  3576. m_pArray = newArray;
  3577. }
  3578. m_Count = newCount;
  3579. }
  3580. template<typename T, typename AllocatorT>
  3581. void VmaVector<T, AllocatorT>::shrink_to_fit()
  3582. {
  3583. if (m_Capacity > m_Count)
  3584. {
  3585. T* newArray = VMA_NULL;
  3586. if (m_Count > 0)
  3587. {
  3588. newArray = VmaAllocateArray<T>(m_Allocator.m_pCallbacks, m_Count);
  3589. memcpy(newArray, m_pArray, m_Count * sizeof(T));
  3590. }
  3591. VmaFree(m_Allocator.m_pCallbacks, m_pArray);
  3592. m_Capacity = m_Count;
  3593. m_pArray = newArray;
  3594. }
  3595. }
  3596. template<typename T, typename AllocatorT>
  3597. void VmaVector<T, AllocatorT>::insert(size_t index, const T& src)
  3598. {
  3599. VMA_HEAVY_ASSERT(index <= m_Count);
  3600. const size_t oldCount = size();
  3601. resize(oldCount + 1);
  3602. if (index < oldCount)
  3603. {
  3604. memmove(m_pArray + (index + 1), m_pArray + index, (oldCount - index) * sizeof(T));
  3605. }
  3606. m_pArray[index] = src;
  3607. }
  3608. template<typename T, typename AllocatorT>
  3609. void VmaVector<T, AllocatorT>::remove(size_t index)
  3610. {
  3611. VMA_HEAVY_ASSERT(index < m_Count);
  3612. const size_t oldCount = size();
  3613. if (index < oldCount - 1)
  3614. {
  3615. memmove(m_pArray + index, m_pArray + (index + 1), (oldCount - index - 1) * sizeof(T));
  3616. }
  3617. resize(oldCount - 1);
  3618. }
  3619. #endif // _VMA_VECTOR_FUNCTIONS
  3620. template<typename T, typename allocatorT>
  3621. static void VmaVectorInsert(VmaVector<T, allocatorT>& vec, size_t index, const T& item)
  3622. {
  3623. vec.insert(index, item);
  3624. }
  3625. template<typename T, typename allocatorT>
  3626. static void VmaVectorRemove(VmaVector<T, allocatorT>& vec, size_t index)
  3627. {
  3628. vec.remove(index);
  3629. }
  3630. #endif // _VMA_VECTOR
  3631. #ifndef _VMA_SMALL_VECTOR
  3632. /*
  3633. This is a vector (a variable-sized array), optimized for the case when the array is small.
  3634. It contains some number of elements in-place, which allows it to avoid heap allocation
  3635. when the actual number of elements is below that threshold. This allows normal "small"
  3636. cases to be fast without losing generality for large inputs.
  3637. */
  3638. template<typename T, typename AllocatorT, size_t N>
  3639. class VmaSmallVector
  3640. {
  3641. public:
  3642. typedef T value_type;
  3643. typedef T* iterator;
  3644. VmaSmallVector(const AllocatorT& allocator);
  3645. VmaSmallVector(size_t count, const AllocatorT& allocator);
  3646. template<typename SrcT, typename SrcAllocatorT, size_t SrcN>
  3647. VmaSmallVector(const VmaSmallVector<SrcT, SrcAllocatorT, SrcN>&) = delete;
  3648. template<typename SrcT, typename SrcAllocatorT, size_t SrcN>
  3649. VmaSmallVector<T, AllocatorT, N>& operator=(const VmaSmallVector<SrcT, SrcAllocatorT, SrcN>&) = delete;
  3650. ~VmaSmallVector() = default;
  3651. bool empty() const { return m_Count == 0; }
  3652. size_t size() const { return m_Count; }
  3653. T* data() { return m_Count > N ? m_DynamicArray.data() : m_StaticArray; }
  3654. T& front() { VMA_HEAVY_ASSERT(m_Count > 0); return data()[0]; }
  3655. T& back() { VMA_HEAVY_ASSERT(m_Count > 0); return data()[m_Count - 1]; }
  3656. const T* data() const { return m_Count > N ? m_DynamicArray.data() : m_StaticArray; }
  3657. const T& front() const { VMA_HEAVY_ASSERT(m_Count > 0); return data()[0]; }
  3658. const T& back() const { VMA_HEAVY_ASSERT(m_Count > 0); return data()[m_Count - 1]; }
  3659. iterator begin() { return data(); }
  3660. iterator end() { return data() + m_Count; }
  3661. void pop_front() { VMA_HEAVY_ASSERT(m_Count > 0); remove(0); }
  3662. void pop_back() { VMA_HEAVY_ASSERT(m_Count > 0); resize(size() - 1); }
  3663. void push_front(const T& src) { insert(0, src); }
  3664. void push_back(const T& src);
  3665. void resize(size_t newCount, bool freeMemory = false);
  3666. void clear(bool freeMemory = false);
  3667. void insert(size_t index, const T& src);
  3668. void remove(size_t index);
  3669. T& operator[](size_t index) { VMA_HEAVY_ASSERT(index < m_Count); return data()[index]; }
  3670. const T& operator[](size_t index) const { VMA_HEAVY_ASSERT(index < m_Count); return data()[index]; }
  3671. private:
  3672. size_t m_Count;
  3673. T m_StaticArray[N]; // Used when m_Size <= N
  3674. VmaVector<T, AllocatorT> m_DynamicArray; // Used when m_Size > N
  3675. };
  3676. #ifndef _VMA_SMALL_VECTOR_FUNCTIONS
  3677. template<typename T, typename AllocatorT, size_t N>
  3678. VmaSmallVector<T, AllocatorT, N>::VmaSmallVector(const AllocatorT& allocator)
  3679. : m_Count(0),
  3680. m_DynamicArray(allocator) {}
  3681. template<typename T, typename AllocatorT, size_t N>
  3682. VmaSmallVector<T, AllocatorT, N>::VmaSmallVector(size_t count, const AllocatorT& allocator)
  3683. : m_Count(count),
  3684. m_DynamicArray(count > N ? count : 0, allocator) {}
  3685. template<typename T, typename AllocatorT, size_t N>
  3686. void VmaSmallVector<T, AllocatorT, N>::push_back(const T& src)
  3687. {
  3688. const size_t newIndex = size();
  3689. resize(newIndex + 1);
  3690. data()[newIndex] = src;
  3691. }
  3692. template<typename T, typename AllocatorT, size_t N>
  3693. void VmaSmallVector<T, AllocatorT, N>::resize(size_t newCount, bool freeMemory)
  3694. {
  3695. if (newCount > N && m_Count > N)
  3696. {
  3697. // Any direction, staying in m_DynamicArray
  3698. m_DynamicArray.resize(newCount);
  3699. if (freeMemory)
  3700. {
  3701. m_DynamicArray.shrink_to_fit();
  3702. }
  3703. }
  3704. else if (newCount > N && m_Count <= N)
  3705. {
  3706. // Growing, moving from m_StaticArray to m_DynamicArray
  3707. m_DynamicArray.resize(newCount);
  3708. if (m_Count > 0)
  3709. {
  3710. memcpy(m_DynamicArray.data(), m_StaticArray, m_Count * sizeof(T));
  3711. }
  3712. }
  3713. else if (newCount <= N && m_Count > N)
  3714. {
  3715. // Shrinking, moving from m_DynamicArray to m_StaticArray
  3716. if (newCount > 0)
  3717. {
  3718. memcpy(m_StaticArray, m_DynamicArray.data(), newCount * sizeof(T));
  3719. }
  3720. m_DynamicArray.resize(0);
  3721. if (freeMemory)
  3722. {
  3723. m_DynamicArray.shrink_to_fit();
  3724. }
  3725. }
  3726. else
  3727. {
  3728. // Any direction, staying in m_StaticArray - nothing to do here
  3729. }
  3730. m_Count = newCount;
  3731. }
  3732. template<typename T, typename AllocatorT, size_t N>
  3733. void VmaSmallVector<T, AllocatorT, N>::clear(bool freeMemory)
  3734. {
  3735. m_DynamicArray.clear();
  3736. if (freeMemory)
  3737. {
  3738. m_DynamicArray.shrink_to_fit();
  3739. }
  3740. m_Count = 0;
  3741. }
  3742. template<typename T, typename AllocatorT, size_t N>
  3743. void VmaSmallVector<T, AllocatorT, N>::insert(size_t index, const T& src)
  3744. {
  3745. VMA_HEAVY_ASSERT(index <= m_Count);
  3746. const size_t oldCount = size();
  3747. resize(oldCount + 1);
  3748. T* const dataPtr = data();
  3749. if (index < oldCount)
  3750. {
  3751. // I know, this could be more optimal for case where memmove can be memcpy directly from m_StaticArray to m_DynamicArray.
  3752. memmove(dataPtr + (index + 1), dataPtr + index, (oldCount - index) * sizeof(T));
  3753. }
  3754. dataPtr[index] = src;
  3755. }
  3756. template<typename T, typename AllocatorT, size_t N>
  3757. void VmaSmallVector<T, AllocatorT, N>::remove(size_t index)
  3758. {
  3759. VMA_HEAVY_ASSERT(index < m_Count);
  3760. const size_t oldCount = size();
  3761. if (index < oldCount - 1)
  3762. {
  3763. // I know, this could be more optimal for case where memmove can be memcpy directly from m_DynamicArray to m_StaticArray.
  3764. T* const dataPtr = data();
  3765. memmove(dataPtr + index, dataPtr + (index + 1), (oldCount - index - 1) * sizeof(T));
  3766. }
  3767. resize(oldCount - 1);
  3768. }
  3769. #endif // _VMA_SMALL_VECTOR_FUNCTIONS
  3770. #endif // _VMA_SMALL_VECTOR
  3771. #ifndef _VMA_POOL_ALLOCATOR
  3772. /*
  3773. Allocator for objects of type T using a list of arrays (pools) to speed up
  3774. allocation. Number of elements that can be allocated is not bounded because
  3775. allocator can create multiple blocks.
  3776. */
  3777. template<typename T>
  3778. class VmaPoolAllocator
  3779. {
  3780. VMA_CLASS_NO_COPY_NO_MOVE(VmaPoolAllocator)
  3781. public:
  3782. VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, uint32_t firstBlockCapacity);
  3783. ~VmaPoolAllocator();
  3784. template<typename... Types> T* Alloc(Types&&... args);
  3785. void Free(T* ptr);
  3786. private:
  3787. union Item
  3788. {
  3789. uint32_t NextFreeIndex;
  3790. alignas(T) char Value[sizeof(T)];
  3791. };
  3792. struct ItemBlock
  3793. {
  3794. Item* pItems;
  3795. uint32_t Capacity;
  3796. uint32_t FirstFreeIndex;
  3797. };
  3798. const VkAllocationCallbacks* m_pAllocationCallbacks;
  3799. const uint32_t m_FirstBlockCapacity;
  3800. VmaVector<ItemBlock, VmaStlAllocator<ItemBlock>> m_ItemBlocks;
  3801. ItemBlock& CreateNewBlock();
  3802. };
  3803. #ifndef _VMA_POOL_ALLOCATOR_FUNCTIONS
  3804. template<typename T>
  3805. VmaPoolAllocator<T>::VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, uint32_t firstBlockCapacity)
  3806. : m_pAllocationCallbacks(pAllocationCallbacks),
  3807. m_FirstBlockCapacity(firstBlockCapacity),
  3808. m_ItemBlocks(VmaStlAllocator<ItemBlock>(pAllocationCallbacks))
  3809. {
  3810. VMA_ASSERT(m_FirstBlockCapacity > 1);
  3811. }
  3812. template<typename T>
  3813. VmaPoolAllocator<T>::~VmaPoolAllocator()
  3814. {
  3815. for (size_t i = m_ItemBlocks.size(); i--;)
  3816. vma_delete_array(m_pAllocationCallbacks, m_ItemBlocks[i].pItems, m_ItemBlocks[i].Capacity);
  3817. m_ItemBlocks.clear();
  3818. }
  3819. template<typename T>
  3820. template<typename... Types> T* VmaPoolAllocator<T>::Alloc(Types&&... args)
  3821. {
  3822. for (size_t i = m_ItemBlocks.size(); i--; )
  3823. {
  3824. ItemBlock& block = m_ItemBlocks[i];
  3825. // This block has some free items: Use first one.
  3826. if (block.FirstFreeIndex != UINT32_MAX)
  3827. {
  3828. Item* const pItem = &block.pItems[block.FirstFreeIndex];
  3829. block.FirstFreeIndex = pItem->NextFreeIndex;
  3830. T* result = (T*)&pItem->Value;
  3831. new(result)T(std::forward<Types>(args)...); // Explicit constructor call.
  3832. return result;
  3833. }
  3834. }
  3835. // No block has free item: Create new one and use it.
  3836. ItemBlock& newBlock = CreateNewBlock();
  3837. Item* const pItem = &newBlock.pItems[0];
  3838. newBlock.FirstFreeIndex = pItem->NextFreeIndex;
  3839. T* result = (T*)&pItem->Value;
  3840. new(result) T(std::forward<Types>(args)...); // Explicit constructor call.
  3841. return result;
  3842. }
  3843. template<typename T>
  3844. void VmaPoolAllocator<T>::Free(T* ptr)
  3845. {
  3846. // Search all memory blocks to find ptr.
  3847. for (size_t i = m_ItemBlocks.size(); i--; )
  3848. {
  3849. ItemBlock& block = m_ItemBlocks[i];
  3850. // Casting to union.
  3851. Item* pItemPtr;
  3852. memcpy(&pItemPtr, &ptr, sizeof(pItemPtr));
  3853. // Check if pItemPtr is in address range of this block.
  3854. if ((pItemPtr >= block.pItems) && (pItemPtr < block.pItems + block.Capacity))
  3855. {
  3856. ptr->~T(); // Explicit destructor call.
  3857. const uint32_t index = static_cast<uint32_t>(pItemPtr - block.pItems);
  3858. pItemPtr->NextFreeIndex = block.FirstFreeIndex;
  3859. block.FirstFreeIndex = index;
  3860. return;
  3861. }
  3862. }
  3863. VMA_ASSERT(0 && "Pointer doesn't belong to this memory pool.");
  3864. }
  3865. template<typename T>
  3866. typename VmaPoolAllocator<T>::ItemBlock& VmaPoolAllocator<T>::CreateNewBlock()
  3867. {
  3868. const uint32_t newBlockCapacity = m_ItemBlocks.empty() ?
  3869. m_FirstBlockCapacity : m_ItemBlocks.back().Capacity * 3 / 2;
  3870. const ItemBlock newBlock =
  3871. {
  3872. vma_new_array(m_pAllocationCallbacks, Item, newBlockCapacity),
  3873. newBlockCapacity,
  3874. 0
  3875. };
  3876. m_ItemBlocks.push_back(newBlock);
  3877. // Setup singly-linked list of all free items in this block.
  3878. for (uint32_t i = 0; i < newBlockCapacity - 1; ++i)
  3879. newBlock.pItems[i].NextFreeIndex = i + 1;
  3880. newBlock.pItems[newBlockCapacity - 1].NextFreeIndex = UINT32_MAX;
  3881. return m_ItemBlocks.back();
  3882. }
  3883. #endif // _VMA_POOL_ALLOCATOR_FUNCTIONS
  3884. #endif // _VMA_POOL_ALLOCATOR
  3885. #ifndef _VMA_RAW_LIST
  3886. template<typename T>
  3887. struct VmaListItem
  3888. {
  3889. VmaListItem* pPrev;
  3890. VmaListItem* pNext;
  3891. T Value;
  3892. };
  3893. // Doubly linked list.
  3894. template<typename T>
  3895. class VmaRawList
  3896. {
  3897. VMA_CLASS_NO_COPY_NO_MOVE(VmaRawList)
  3898. public:
  3899. typedef VmaListItem<T> ItemType;
  3900. VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks);
  3901. // Intentionally not calling Clear, because that would be unnecessary
  3902. // computations to return all items to m_ItemAllocator as free.
  3903. ~VmaRawList() = default;
  3904. size_t GetCount() const { return m_Count; }
  3905. bool IsEmpty() const { return m_Count == 0; }
  3906. ItemType* Front() { return m_pFront; }
  3907. ItemType* Back() { return m_pBack; }
  3908. const ItemType* Front() const { return m_pFront; }
  3909. const ItemType* Back() const { return m_pBack; }
  3910. ItemType* PushFront();
  3911. ItemType* PushBack();
  3912. ItemType* PushFront(const T& value);
  3913. ItemType* PushBack(const T& value);
  3914. void PopFront();
  3915. void PopBack();
  3916. // Item can be null - it means PushBack.
  3917. ItemType* InsertBefore(ItemType* pItem);
  3918. // Item can be null - it means PushFront.
  3919. ItemType* InsertAfter(ItemType* pItem);
  3920. ItemType* InsertBefore(ItemType* pItem, const T& value);
  3921. ItemType* InsertAfter(ItemType* pItem, const T& value);
  3922. void Clear();
  3923. void Remove(ItemType* pItem);
  3924. private:
  3925. const VkAllocationCallbacks* const m_pAllocationCallbacks;
  3926. VmaPoolAllocator<ItemType> m_ItemAllocator;
  3927. ItemType* m_pFront;
  3928. ItemType* m_pBack;
  3929. size_t m_Count;
  3930. };
  3931. #ifndef _VMA_RAW_LIST_FUNCTIONS
  3932. template<typename T>
  3933. VmaRawList<T>::VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks)
  3934. : m_pAllocationCallbacks(pAllocationCallbacks),
  3935. m_ItemAllocator(pAllocationCallbacks, 128),
  3936. m_pFront(VMA_NULL),
  3937. m_pBack(VMA_NULL),
  3938. m_Count(0) {}
  3939. template<typename T>
  3940. VmaListItem<T>* VmaRawList<T>::PushFront()
  3941. {
  3942. ItemType* const pNewItem = m_ItemAllocator.Alloc();
  3943. pNewItem->pPrev = VMA_NULL;
  3944. if (IsEmpty())
  3945. {
  3946. pNewItem->pNext = VMA_NULL;
  3947. m_pFront = pNewItem;
  3948. m_pBack = pNewItem;
  3949. m_Count = 1;
  3950. }
  3951. else
  3952. {
  3953. pNewItem->pNext = m_pFront;
  3954. m_pFront->pPrev = pNewItem;
  3955. m_pFront = pNewItem;
  3956. ++m_Count;
  3957. }
  3958. return pNewItem;
  3959. }
  3960. template<typename T>
  3961. VmaListItem<T>* VmaRawList<T>::PushBack()
  3962. {
  3963. ItemType* const pNewItem = m_ItemAllocator.Alloc();
  3964. pNewItem->pNext = VMA_NULL;
  3965. if(IsEmpty())
  3966. {
  3967. pNewItem->pPrev = VMA_NULL;
  3968. m_pFront = pNewItem;
  3969. m_pBack = pNewItem;
  3970. m_Count = 1;
  3971. }
  3972. else
  3973. {
  3974. pNewItem->pPrev = m_pBack;
  3975. m_pBack->pNext = pNewItem;
  3976. m_pBack = pNewItem;
  3977. ++m_Count;
  3978. }
  3979. return pNewItem;
  3980. }
  3981. template<typename T>
  3982. VmaListItem<T>* VmaRawList<T>::PushFront(const T& value)
  3983. {
  3984. ItemType* const pNewItem = PushFront();
  3985. pNewItem->Value = value;
  3986. return pNewItem;
  3987. }
  3988. template<typename T>
  3989. VmaListItem<T>* VmaRawList<T>::PushBack(const T& value)
  3990. {
  3991. ItemType* const pNewItem = PushBack();
  3992. pNewItem->Value = value;
  3993. return pNewItem;
  3994. }
  3995. template<typename T>
  3996. void VmaRawList<T>::PopFront()
  3997. {
  3998. VMA_HEAVY_ASSERT(m_Count > 0);
  3999. ItemType* const pFrontItem = m_pFront;
  4000. ItemType* const pNextItem = pFrontItem->pNext;
  4001. if (pNextItem != VMA_NULL)
  4002. {
  4003. pNextItem->pPrev = VMA_NULL;
  4004. }
  4005. m_pFront = pNextItem;
  4006. m_ItemAllocator.Free(pFrontItem);
  4007. --m_Count;
  4008. }
  4009. template<typename T>
  4010. void VmaRawList<T>::PopBack()
  4011. {
  4012. VMA_HEAVY_ASSERT(m_Count > 0);
  4013. ItemType* const pBackItem = m_pBack;
  4014. ItemType* const pPrevItem = pBackItem->pPrev;
  4015. if(pPrevItem != VMA_NULL)
  4016. {
  4017. pPrevItem->pNext = VMA_NULL;
  4018. }
  4019. m_pBack = pPrevItem;
  4020. m_ItemAllocator.Free(pBackItem);
  4021. --m_Count;
  4022. }
  4023. template<typename T>
  4024. void VmaRawList<T>::Clear()
  4025. {
  4026. if (IsEmpty() == false)
  4027. {
  4028. ItemType* pItem = m_pBack;
  4029. while (pItem != VMA_NULL)
  4030. {
  4031. ItemType* const pPrevItem = pItem->pPrev;
  4032. m_ItemAllocator.Free(pItem);
  4033. pItem = pPrevItem;
  4034. }
  4035. m_pFront = VMA_NULL;
  4036. m_pBack = VMA_NULL;
  4037. m_Count = 0;
  4038. }
  4039. }
  4040. template<typename T>
  4041. void VmaRawList<T>::Remove(ItemType* pItem)
  4042. {
  4043. VMA_HEAVY_ASSERT(pItem != VMA_NULL);
  4044. VMA_HEAVY_ASSERT(m_Count > 0);
  4045. if(pItem->pPrev != VMA_NULL)
  4046. {
  4047. pItem->pPrev->pNext = pItem->pNext;
  4048. }
  4049. else
  4050. {
  4051. VMA_HEAVY_ASSERT(m_pFront == pItem);
  4052. m_pFront = pItem->pNext;
  4053. }
  4054. if(pItem->pNext != VMA_NULL)
  4055. {
  4056. pItem->pNext->pPrev = pItem->pPrev;
  4057. }
  4058. else
  4059. {
  4060. VMA_HEAVY_ASSERT(m_pBack == pItem);
  4061. m_pBack = pItem->pPrev;
  4062. }
  4063. m_ItemAllocator.Free(pItem);
  4064. --m_Count;
  4065. }
  4066. template<typename T>
  4067. VmaListItem<T>* VmaRawList<T>::InsertBefore(ItemType* pItem)
  4068. {
  4069. if(pItem != VMA_NULL)
  4070. {
  4071. ItemType* const prevItem = pItem->pPrev;
  4072. ItemType* const newItem = m_ItemAllocator.Alloc();
  4073. newItem->pPrev = prevItem;
  4074. newItem->pNext = pItem;
  4075. pItem->pPrev = newItem;
  4076. if(prevItem != VMA_NULL)
  4077. {
  4078. prevItem->pNext = newItem;
  4079. }
  4080. else
  4081. {
  4082. VMA_HEAVY_ASSERT(m_pFront == pItem);
  4083. m_pFront = newItem;
  4084. }
  4085. ++m_Count;
  4086. return newItem;
  4087. }
  4088. else
  4089. return PushBack();
  4090. }
  4091. template<typename T>
  4092. VmaListItem<T>* VmaRawList<T>::InsertAfter(ItemType* pItem)
  4093. {
  4094. if(pItem != VMA_NULL)
  4095. {
  4096. ItemType* const nextItem = pItem->pNext;
  4097. ItemType* const newItem = m_ItemAllocator.Alloc();
  4098. newItem->pNext = nextItem;
  4099. newItem->pPrev = pItem;
  4100. pItem->pNext = newItem;
  4101. if(nextItem != VMA_NULL)
  4102. {
  4103. nextItem->pPrev = newItem;
  4104. }
  4105. else
  4106. {
  4107. VMA_HEAVY_ASSERT(m_pBack == pItem);
  4108. m_pBack = newItem;
  4109. }
  4110. ++m_Count;
  4111. return newItem;
  4112. }
  4113. else
  4114. return PushFront();
  4115. }
  4116. template<typename T>
  4117. VmaListItem<T>* VmaRawList<T>::InsertBefore(ItemType* pItem, const T& value)
  4118. {
  4119. ItemType* const newItem = InsertBefore(pItem);
  4120. newItem->Value = value;
  4121. return newItem;
  4122. }
  4123. template<typename T>
  4124. VmaListItem<T>* VmaRawList<T>::InsertAfter(ItemType* pItem, const T& value)
  4125. {
  4126. ItemType* const newItem = InsertAfter(pItem);
  4127. newItem->Value = value;
  4128. return newItem;
  4129. }
  4130. #endif // _VMA_RAW_LIST_FUNCTIONS
  4131. #endif // _VMA_RAW_LIST
  4132. #ifndef _VMA_LIST
  4133. template<typename T, typename AllocatorT>
  4134. class VmaList
  4135. {
  4136. VMA_CLASS_NO_COPY_NO_MOVE(VmaList)
  4137. public:
  4138. class reverse_iterator;
  4139. class const_iterator;
  4140. class const_reverse_iterator;
  4141. class iterator
  4142. {
  4143. friend class const_iterator;
  4144. friend class VmaList<T, AllocatorT>;
  4145. public:
  4146. iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {}
  4147. iterator(const reverse_iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {}
  4148. T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; }
  4149. T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; }
  4150. bool operator==(const iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; }
  4151. bool operator!=(const iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; }
  4152. iterator operator++(int) { iterator result = *this; ++*this; return result; }
  4153. iterator operator--(int) { iterator result = *this; --*this; return result; }
  4154. iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pNext; return *this; }
  4155. iterator& operator--();
  4156. private:
  4157. VmaRawList<T>* m_pList;
  4158. VmaListItem<T>* m_pItem;
  4159. iterator(VmaRawList<T>* pList, VmaListItem<T>* pItem) : m_pList(pList), m_pItem(pItem) {}
  4160. };
  4161. class reverse_iterator
  4162. {
  4163. friend class const_reverse_iterator;
  4164. friend class VmaList<T, AllocatorT>;
  4165. public:
  4166. reverse_iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {}
  4167. reverse_iterator(const iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {}
  4168. T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; }
  4169. T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; }
  4170. bool operator==(const reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; }
  4171. bool operator!=(const reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; }
  4172. reverse_iterator operator++(int) { reverse_iterator result = *this; ++* this; return result; }
  4173. reverse_iterator operator--(int) { reverse_iterator result = *this; --* this; return result; }
  4174. reverse_iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pPrev; return *this; }
  4175. reverse_iterator& operator--();
  4176. private:
  4177. VmaRawList<T>* m_pList;
  4178. VmaListItem<T>* m_pItem;
  4179. reverse_iterator(VmaRawList<T>* pList, VmaListItem<T>* pItem) : m_pList(pList), m_pItem(pItem) {}
  4180. };
  4181. class const_iterator
  4182. {
  4183. friend class VmaList<T, AllocatorT>;
  4184. public:
  4185. const_iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {}
  4186. const_iterator(const iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {}
  4187. const_iterator(const reverse_iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {}
  4188. iterator drop_const() { return { const_cast<VmaRawList<T>*>(m_pList), const_cast<VmaListItem<T>*>(m_pItem) }; }
  4189. const T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; }
  4190. const T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; }
  4191. bool operator==(const const_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; }
  4192. bool operator!=(const const_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; }
  4193. const_iterator operator++(int) { const_iterator result = *this; ++* this; return result; }
  4194. const_iterator operator--(int) { const_iterator result = *this; --* this; return result; }
  4195. const_iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pNext; return *this; }
  4196. const_iterator& operator--();
  4197. private:
  4198. const VmaRawList<T>* m_pList;
  4199. const VmaListItem<T>* m_pItem;
  4200. const_iterator(const VmaRawList<T>* pList, const VmaListItem<T>* pItem) : m_pList(pList), m_pItem(pItem) {}
  4201. };
  4202. class const_reverse_iterator
  4203. {
  4204. friend class VmaList<T, AllocatorT>;
  4205. public:
  4206. const_reverse_iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {}
  4207. const_reverse_iterator(const reverse_iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {}
  4208. const_reverse_iterator(const iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {}
  4209. reverse_iterator drop_const() { return { const_cast<VmaRawList<T>*>(m_pList), const_cast<VmaListItem<T>*>(m_pItem) }; }
  4210. const T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; }
  4211. const T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; }
  4212. bool operator==(const const_reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; }
  4213. bool operator!=(const const_reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; }
  4214. const_reverse_iterator operator++(int) { const_reverse_iterator result = *this; ++* this; return result; }
  4215. const_reverse_iterator operator--(int) { const_reverse_iterator result = *this; --* this; return result; }
  4216. const_reverse_iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pPrev; return *this; }
  4217. const_reverse_iterator& operator--();
  4218. private:
  4219. const VmaRawList<T>* m_pList;
  4220. const VmaListItem<T>* m_pItem;
  4221. const_reverse_iterator(const VmaRawList<T>* pList, const VmaListItem<T>* pItem) : m_pList(pList), m_pItem(pItem) {}
  4222. };
  4223. VmaList(const AllocatorT& allocator) : m_RawList(allocator.m_pCallbacks) {}
  4224. bool empty() const { return m_RawList.IsEmpty(); }
  4225. size_t size() const { return m_RawList.GetCount(); }
  4226. iterator begin() { return iterator(&m_RawList, m_RawList.Front()); }
  4227. iterator end() { return iterator(&m_RawList, VMA_NULL); }
  4228. const_iterator cbegin() const { return const_iterator(&m_RawList, m_RawList.Front()); }
  4229. const_iterator cend() const { return const_iterator(&m_RawList, VMA_NULL); }
  4230. const_iterator begin() const { return cbegin(); }
  4231. const_iterator end() const { return cend(); }
  4232. reverse_iterator rbegin() { return reverse_iterator(&m_RawList, m_RawList.Back()); }
  4233. reverse_iterator rend() { return reverse_iterator(&m_RawList, VMA_NULL); }
  4234. const_reverse_iterator crbegin() const { return const_reverse_iterator(&m_RawList, m_RawList.Back()); }
  4235. const_reverse_iterator crend() const { return const_reverse_iterator(&m_RawList, VMA_NULL); }
  4236. const_reverse_iterator rbegin() const { return crbegin(); }
  4237. const_reverse_iterator rend() const { return crend(); }
  4238. void push_back(const T& value) { m_RawList.PushBack(value); }
  4239. iterator insert(iterator it, const T& value) { return iterator(&m_RawList, m_RawList.InsertBefore(it.m_pItem, value)); }
  4240. void clear() { m_RawList.Clear(); }
  4241. void erase(iterator it) { m_RawList.Remove(it.m_pItem); }
  4242. private:
  4243. VmaRawList<T> m_RawList;
  4244. };
  4245. #ifndef _VMA_LIST_FUNCTIONS
  4246. template<typename T, typename AllocatorT>
  4247. typename VmaList<T, AllocatorT>::iterator& VmaList<T, AllocatorT>::iterator::operator--()
  4248. {
  4249. if (m_pItem != VMA_NULL)
  4250. {
  4251. m_pItem = m_pItem->pPrev;
  4252. }
  4253. else
  4254. {
  4255. VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
  4256. m_pItem = m_pList->Back();
  4257. }
  4258. return *this;
  4259. }
  4260. template<typename T, typename AllocatorT>
  4261. typename VmaList<T, AllocatorT>::reverse_iterator& VmaList<T, AllocatorT>::reverse_iterator::operator--()
  4262. {
  4263. if (m_pItem != VMA_NULL)
  4264. {
  4265. m_pItem = m_pItem->pNext;
  4266. }
  4267. else
  4268. {
  4269. VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
  4270. m_pItem = m_pList->Front();
  4271. }
  4272. return *this;
  4273. }
  4274. template<typename T, typename AllocatorT>
  4275. typename VmaList<T, AllocatorT>::const_iterator& VmaList<T, AllocatorT>::const_iterator::operator--()
  4276. {
  4277. if (m_pItem != VMA_NULL)
  4278. {
  4279. m_pItem = m_pItem->pPrev;
  4280. }
  4281. else
  4282. {
  4283. VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
  4284. m_pItem = m_pList->Back();
  4285. }
  4286. return *this;
  4287. }
  4288. template<typename T, typename AllocatorT>
  4289. typename VmaList<T, AllocatorT>::const_reverse_iterator& VmaList<T, AllocatorT>::const_reverse_iterator::operator--()
  4290. {
  4291. if (m_pItem != VMA_NULL)
  4292. {
  4293. m_pItem = m_pItem->pNext;
  4294. }
  4295. else
  4296. {
  4297. VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
  4298. m_pItem = m_pList->Back();
  4299. }
  4300. return *this;
  4301. }
  4302. #endif // _VMA_LIST_FUNCTIONS
  4303. #endif // _VMA_LIST
  4304. #ifndef _VMA_INTRUSIVE_LINKED_LIST
  4305. /*
  4306. Expected interface of ItemTypeTraits:
  4307. struct MyItemTypeTraits
  4308. {
  4309. typedef MyItem ItemType;
  4310. static ItemType* GetPrev(const ItemType* item) { return item->myPrevPtr; }
  4311. static ItemType* GetNext(const ItemType* item) { return item->myNextPtr; }
  4312. static ItemType*& AccessPrev(ItemType* item) { return item->myPrevPtr; }
  4313. static ItemType*& AccessNext(ItemType* item) { return item->myNextPtr; }
  4314. };
  4315. */
  4316. template<typename ItemTypeTraits>
  4317. class VmaIntrusiveLinkedList
  4318. {
  4319. public:
  4320. typedef typename ItemTypeTraits::ItemType ItemType;
  4321. static ItemType* GetPrev(const ItemType* item) { return ItemTypeTraits::GetPrev(item); }
  4322. static ItemType* GetNext(const ItemType* item) { return ItemTypeTraits::GetNext(item); }
  4323. // Movable, not copyable.
  4324. VmaIntrusiveLinkedList() = default;
  4325. VmaIntrusiveLinkedList(VmaIntrusiveLinkedList && src);
  4326. VmaIntrusiveLinkedList(const VmaIntrusiveLinkedList&) = delete;
  4327. VmaIntrusiveLinkedList& operator=(VmaIntrusiveLinkedList&& src);
  4328. VmaIntrusiveLinkedList& operator=(const VmaIntrusiveLinkedList&) = delete;
  4329. ~VmaIntrusiveLinkedList() { VMA_HEAVY_ASSERT(IsEmpty()); }
  4330. size_t GetCount() const { return m_Count; }
  4331. bool IsEmpty() const { return m_Count == 0; }
  4332. ItemType* Front() { return m_Front; }
  4333. ItemType* Back() { return m_Back; }
  4334. const ItemType* Front() const { return m_Front; }
  4335. const ItemType* Back() const { return m_Back; }
  4336. void PushBack(ItemType* item);
  4337. void PushFront(ItemType* item);
  4338. ItemType* PopBack();
  4339. ItemType* PopFront();
  4340. // MyItem can be null - it means PushBack.
  4341. void InsertBefore(ItemType* existingItem, ItemType* newItem);
  4342. // MyItem can be null - it means PushFront.
  4343. void InsertAfter(ItemType* existingItem, ItemType* newItem);
  4344. void Remove(ItemType* item);
  4345. void RemoveAll();
  4346. private:
  4347. ItemType* m_Front = VMA_NULL;
  4348. ItemType* m_Back = VMA_NULL;
  4349. size_t m_Count = 0;
  4350. };
  4351. #ifndef _VMA_INTRUSIVE_LINKED_LIST_FUNCTIONS
  4352. template<typename ItemTypeTraits>
  4353. VmaIntrusiveLinkedList<ItemTypeTraits>::VmaIntrusiveLinkedList(VmaIntrusiveLinkedList&& src)
  4354. : m_Front(src.m_Front), m_Back(src.m_Back), m_Count(src.m_Count)
  4355. {
  4356. src.m_Front = src.m_Back = VMA_NULL;
  4357. src.m_Count = 0;
  4358. }
  4359. template<typename ItemTypeTraits>
  4360. VmaIntrusiveLinkedList<ItemTypeTraits>& VmaIntrusiveLinkedList<ItemTypeTraits>::operator=(VmaIntrusiveLinkedList&& src)
  4361. {
  4362. if (&src != this)
  4363. {
  4364. VMA_HEAVY_ASSERT(IsEmpty());
  4365. m_Front = src.m_Front;
  4366. m_Back = src.m_Back;
  4367. m_Count = src.m_Count;
  4368. src.m_Front = src.m_Back = VMA_NULL;
  4369. src.m_Count = 0;
  4370. }
  4371. return *this;
  4372. }
  4373. template<typename ItemTypeTraits>
  4374. void VmaIntrusiveLinkedList<ItemTypeTraits>::PushBack(ItemType* item)
  4375. {
  4376. VMA_HEAVY_ASSERT(ItemTypeTraits::GetPrev(item) == VMA_NULL && ItemTypeTraits::GetNext(item) == VMA_NULL);
  4377. if (IsEmpty())
  4378. {
  4379. m_Front = item;
  4380. m_Back = item;
  4381. m_Count = 1;
  4382. }
  4383. else
  4384. {
  4385. ItemTypeTraits::AccessPrev(item) = m_Back;
  4386. ItemTypeTraits::AccessNext(m_Back) = item;
  4387. m_Back = item;
  4388. ++m_Count;
  4389. }
  4390. }
  4391. template<typename ItemTypeTraits>
  4392. void VmaIntrusiveLinkedList<ItemTypeTraits>::PushFront(ItemType* item)
  4393. {
  4394. VMA_HEAVY_ASSERT(ItemTypeTraits::GetPrev(item) == VMA_NULL && ItemTypeTraits::GetNext(item) == VMA_NULL);
  4395. if (IsEmpty())
  4396. {
  4397. m_Front = item;
  4398. m_Back = item;
  4399. m_Count = 1;
  4400. }
  4401. else
  4402. {
  4403. ItemTypeTraits::AccessNext(item) = m_Front;
  4404. ItemTypeTraits::AccessPrev(m_Front) = item;
  4405. m_Front = item;
  4406. ++m_Count;
  4407. }
  4408. }
  4409. template<typename ItemTypeTraits>
  4410. typename VmaIntrusiveLinkedList<ItemTypeTraits>::ItemType* VmaIntrusiveLinkedList<ItemTypeTraits>::PopBack()
  4411. {
  4412. VMA_HEAVY_ASSERT(m_Count > 0);
  4413. ItemType* const backItem = m_Back;
  4414. ItemType* const prevItem = ItemTypeTraits::GetPrev(backItem);
  4415. if (prevItem != VMA_NULL)
  4416. {
  4417. ItemTypeTraits::AccessNext(prevItem) = VMA_NULL;
  4418. }
  4419. m_Back = prevItem;
  4420. --m_Count;
  4421. ItemTypeTraits::AccessPrev(backItem) = VMA_NULL;
  4422. ItemTypeTraits::AccessNext(backItem) = VMA_NULL;
  4423. return backItem;
  4424. }
  4425. template<typename ItemTypeTraits>
  4426. typename VmaIntrusiveLinkedList<ItemTypeTraits>::ItemType* VmaIntrusiveLinkedList<ItemTypeTraits>::PopFront()
  4427. {
  4428. VMA_HEAVY_ASSERT(m_Count > 0);
  4429. ItemType* const frontItem = m_Front;
  4430. ItemType* const nextItem = ItemTypeTraits::GetNext(frontItem);
  4431. if (nextItem != VMA_NULL)
  4432. {
  4433. ItemTypeTraits::AccessPrev(nextItem) = VMA_NULL;
  4434. }
  4435. m_Front = nextItem;
  4436. --m_Count;
  4437. ItemTypeTraits::AccessPrev(frontItem) = VMA_NULL;
  4438. ItemTypeTraits::AccessNext(frontItem) = VMA_NULL;
  4439. return frontItem;
  4440. }
  4441. template<typename ItemTypeTraits>
  4442. void VmaIntrusiveLinkedList<ItemTypeTraits>::InsertBefore(ItemType* existingItem, ItemType* newItem)
  4443. {
  4444. VMA_HEAVY_ASSERT(newItem != VMA_NULL && ItemTypeTraits::GetPrev(newItem) == VMA_NULL && ItemTypeTraits::GetNext(newItem) == VMA_NULL);
  4445. if (existingItem != VMA_NULL)
  4446. {
  4447. ItemType* const prevItem = ItemTypeTraits::GetPrev(existingItem);
  4448. ItemTypeTraits::AccessPrev(newItem) = prevItem;
  4449. ItemTypeTraits::AccessNext(newItem) = existingItem;
  4450. ItemTypeTraits::AccessPrev(existingItem) = newItem;
  4451. if (prevItem != VMA_NULL)
  4452. {
  4453. ItemTypeTraits::AccessNext(prevItem) = newItem;
  4454. }
  4455. else
  4456. {
  4457. VMA_HEAVY_ASSERT(m_Front == existingItem);
  4458. m_Front = newItem;
  4459. }
  4460. ++m_Count;
  4461. }
  4462. else
  4463. PushBack(newItem);
  4464. }
  4465. template<typename ItemTypeTraits>
  4466. void VmaIntrusiveLinkedList<ItemTypeTraits>::InsertAfter(ItemType* existingItem, ItemType* newItem)
  4467. {
  4468. VMA_HEAVY_ASSERT(newItem != VMA_NULL && ItemTypeTraits::GetPrev(newItem) == VMA_NULL && ItemTypeTraits::GetNext(newItem) == VMA_NULL);
  4469. if (existingItem != VMA_NULL)
  4470. {
  4471. ItemType* const nextItem = ItemTypeTraits::GetNext(existingItem);
  4472. ItemTypeTraits::AccessNext(newItem) = nextItem;
  4473. ItemTypeTraits::AccessPrev(newItem) = existingItem;
  4474. ItemTypeTraits::AccessNext(existingItem) = newItem;
  4475. if (nextItem != VMA_NULL)
  4476. {
  4477. ItemTypeTraits::AccessPrev(nextItem) = newItem;
  4478. }
  4479. else
  4480. {
  4481. VMA_HEAVY_ASSERT(m_Back == existingItem);
  4482. m_Back = newItem;
  4483. }
  4484. ++m_Count;
  4485. }
  4486. else
  4487. return PushFront(newItem);
  4488. }
  4489. template<typename ItemTypeTraits>
  4490. void VmaIntrusiveLinkedList<ItemTypeTraits>::Remove(ItemType* item)
  4491. {
  4492. VMA_HEAVY_ASSERT(item != VMA_NULL && m_Count > 0);
  4493. if (ItemTypeTraits::GetPrev(item) != VMA_NULL)
  4494. {
  4495. ItemTypeTraits::AccessNext(ItemTypeTraits::AccessPrev(item)) = ItemTypeTraits::GetNext(item);
  4496. }
  4497. else
  4498. {
  4499. VMA_HEAVY_ASSERT(m_Front == item);
  4500. m_Front = ItemTypeTraits::GetNext(item);
  4501. }
  4502. if (ItemTypeTraits::GetNext(item) != VMA_NULL)
  4503. {
  4504. ItemTypeTraits::AccessPrev(ItemTypeTraits::AccessNext(item)) = ItemTypeTraits::GetPrev(item);
  4505. }
  4506. else
  4507. {
  4508. VMA_HEAVY_ASSERT(m_Back == item);
  4509. m_Back = ItemTypeTraits::GetPrev(item);
  4510. }
  4511. ItemTypeTraits::AccessPrev(item) = VMA_NULL;
  4512. ItemTypeTraits::AccessNext(item) = VMA_NULL;
  4513. --m_Count;
  4514. }
  4515. template<typename ItemTypeTraits>
  4516. void VmaIntrusiveLinkedList<ItemTypeTraits>::RemoveAll()
  4517. {
  4518. if (!IsEmpty())
  4519. {
  4520. ItemType* item = m_Back;
  4521. while (item != VMA_NULL)
  4522. {
  4523. ItemType* const prevItem = ItemTypeTraits::AccessPrev(item);
  4524. ItemTypeTraits::AccessPrev(item) = VMA_NULL;
  4525. ItemTypeTraits::AccessNext(item) = VMA_NULL;
  4526. item = prevItem;
  4527. }
  4528. m_Front = VMA_NULL;
  4529. m_Back = VMA_NULL;
  4530. m_Count = 0;
  4531. }
  4532. }
  4533. #endif // _VMA_INTRUSIVE_LINKED_LIST_FUNCTIONS
  4534. #endif // _VMA_INTRUSIVE_LINKED_LIST
  4535. // Unused in this version.
  4536. #if 0
  4537. #ifndef _VMA_PAIR
  4538. template<typename T1, typename T2>
  4539. struct VmaPair
  4540. {
  4541. T1 first;
  4542. T2 second;
  4543. VmaPair() : first(), second() {}
  4544. VmaPair(const T1& firstSrc, const T2& secondSrc) : first(firstSrc), second(secondSrc) {}
  4545. };
  4546. template<typename FirstT, typename SecondT>
  4547. struct VmaPairFirstLess
  4548. {
  4549. bool operator()(const VmaPair<FirstT, SecondT>& lhs, const VmaPair<FirstT, SecondT>& rhs) const
  4550. {
  4551. return lhs.first < rhs.first;
  4552. }
  4553. bool operator()(const VmaPair<FirstT, SecondT>& lhs, const FirstT& rhsFirst) const
  4554. {
  4555. return lhs.first < rhsFirst;
  4556. }
  4557. };
  4558. #endif // _VMA_PAIR
  4559. #ifndef _VMA_MAP
  4560. /* Class compatible with subset of interface of std::unordered_map.
  4561. KeyT, ValueT must be POD because they will be stored in VmaVector.
  4562. */
  4563. template<typename KeyT, typename ValueT>
  4564. class VmaMap
  4565. {
  4566. public:
  4567. typedef VmaPair<KeyT, ValueT> PairType;
  4568. typedef PairType* iterator;
  4569. VmaMap(const VmaStlAllocator<PairType>& allocator) : m_Vector(allocator) {}
  4570. iterator begin() { return m_Vector.begin(); }
  4571. iterator end() { return m_Vector.end(); }
  4572. size_t size() { return m_Vector.size(); }
  4573. void insert(const PairType& pair);
  4574. iterator find(const KeyT& key);
  4575. void erase(iterator it);
  4576. private:
  4577. VmaVector< PairType, VmaStlAllocator<PairType>> m_Vector;
  4578. };
  4579. #ifndef _VMA_MAP_FUNCTIONS
  4580. template<typename KeyT, typename ValueT>
  4581. void VmaMap<KeyT, ValueT>::insert(const PairType& pair)
  4582. {
  4583. const size_t indexToInsert = VmaBinaryFindFirstNotLess(
  4584. m_Vector.data(),
  4585. m_Vector.data() + m_Vector.size(),
  4586. pair,
  4587. VmaPairFirstLess<KeyT, ValueT>()) - m_Vector.data();
  4588. VmaVectorInsert(m_Vector, indexToInsert, pair);
  4589. }
  4590. template<typename KeyT, typename ValueT>
  4591. VmaPair<KeyT, ValueT>* VmaMap<KeyT, ValueT>::find(const KeyT& key)
  4592. {
  4593. PairType* it = VmaBinaryFindFirstNotLess(
  4594. m_Vector.data(),
  4595. m_Vector.data() + m_Vector.size(),
  4596. key,
  4597. VmaPairFirstLess<KeyT, ValueT>());
  4598. if ((it != m_Vector.end()) && (it->first == key))
  4599. {
  4600. return it;
  4601. }
  4602. else
  4603. {
  4604. return m_Vector.end();
  4605. }
  4606. }
  4607. template<typename KeyT, typename ValueT>
  4608. void VmaMap<KeyT, ValueT>::erase(iterator it)
  4609. {
  4610. VmaVectorRemove(m_Vector, it - m_Vector.begin());
  4611. }
  4612. #endif // _VMA_MAP_FUNCTIONS
  4613. #endif // _VMA_MAP
  4614. #endif // #if 0
  4615. #if !defined(_VMA_STRING_BUILDER) && VMA_STATS_STRING_ENABLED
  4616. class VmaStringBuilder
  4617. {
  4618. public:
  4619. VmaStringBuilder(const VkAllocationCallbacks* allocationCallbacks) : m_Data(VmaStlAllocator<char>(allocationCallbacks)) {}
  4620. ~VmaStringBuilder() = default;
  4621. size_t GetLength() const { return m_Data.size(); }
  4622. const char* GetData() const { return m_Data.data(); }
  4623. void AddNewLine() { Add('\n'); }
  4624. void Add(char ch) { m_Data.push_back(ch); }
  4625. void Add(const char* pStr);
  4626. void AddNumber(uint32_t num);
  4627. void AddNumber(uint64_t num);
  4628. void AddPointer(const void* ptr);
  4629. private:
  4630. VmaVector<char, VmaStlAllocator<char>> m_Data;
  4631. };
  4632. #ifndef _VMA_STRING_BUILDER_FUNCTIONS
  4633. void VmaStringBuilder::Add(const char* pStr)
  4634. {
  4635. const size_t strLen = strlen(pStr);
  4636. if (strLen > 0)
  4637. {
  4638. const size_t oldCount = m_Data.size();
  4639. m_Data.resize(oldCount + strLen);
  4640. memcpy(m_Data.data() + oldCount, pStr, strLen);
  4641. }
  4642. }
  4643. void VmaStringBuilder::AddNumber(uint32_t num)
  4644. {
  4645. char buf[11];
  4646. buf[10] = '\0';
  4647. char* p = &buf[10];
  4648. do
  4649. {
  4650. *--p = '0' + (char)(num % 10);
  4651. num /= 10;
  4652. } while (num);
  4653. Add(p);
  4654. }
  4655. void VmaStringBuilder::AddNumber(uint64_t num)
  4656. {
  4657. char buf[21];
  4658. buf[20] = '\0';
  4659. char* p = &buf[20];
  4660. do
  4661. {
  4662. *--p = '0' + (char)(num % 10);
  4663. num /= 10;
  4664. } while (num);
  4665. Add(p);
  4666. }
  4667. void VmaStringBuilder::AddPointer(const void* ptr)
  4668. {
  4669. char buf[21];
  4670. VmaPtrToStr(buf, sizeof(buf), ptr);
  4671. Add(buf);
  4672. }
  4673. #endif //_VMA_STRING_BUILDER_FUNCTIONS
  4674. #endif // _VMA_STRING_BUILDER
  4675. #if !defined(_VMA_JSON_WRITER) && VMA_STATS_STRING_ENABLED
  4676. /*
  4677. Allows to conveniently build a correct JSON document to be written to the
  4678. VmaStringBuilder passed to the constructor.
  4679. */
  4680. class VmaJsonWriter
  4681. {
  4682. VMA_CLASS_NO_COPY_NO_MOVE(VmaJsonWriter)
  4683. public:
  4684. // sb - string builder to write the document to. Must remain alive for the whole lifetime of this object.
  4685. VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb);
  4686. ~VmaJsonWriter();
  4687. // Begins object by writing "{".
  4688. // Inside an object, you must call pairs of WriteString and a value, e.g.:
  4689. // j.BeginObject(true); j.WriteString("A"); j.WriteNumber(1); j.WriteString("B"); j.WriteNumber(2); j.EndObject();
  4690. // Will write: { "A": 1, "B": 2 }
  4691. void BeginObject(bool singleLine = false);
  4692. // Ends object by writing "}".
  4693. void EndObject();
  4694. // Begins array by writing "[".
  4695. // Inside an array, you can write a sequence of any values.
  4696. void BeginArray(bool singleLine = false);
  4697. // Ends array by writing "[".
  4698. void EndArray();
  4699. // Writes a string value inside "".
  4700. // pStr can contain any ANSI characters, including '"', new line etc. - they will be properly escaped.
  4701. void WriteString(const char* pStr);
  4702. // Begins writing a string value.
  4703. // Call BeginString, ContinueString, ContinueString, ..., EndString instead of
  4704. // WriteString to conveniently build the string content incrementally, made of
  4705. // parts including numbers.
  4706. void BeginString(const char* pStr = VMA_NULL);
  4707. // Posts next part of an open string.
  4708. void ContinueString(const char* pStr);
  4709. // Posts next part of an open string. The number is converted to decimal characters.
  4710. void ContinueString(uint32_t n);
  4711. void ContinueString(uint64_t n);
  4712. // Posts next part of an open string. Pointer value is converted to characters
  4713. // using "%p" formatting - shown as hexadecimal number, e.g.: 000000081276Ad00
  4714. void ContinueString_Pointer(const void* ptr);
  4715. // Ends writing a string value by writing '"'.
  4716. void EndString(const char* pStr = VMA_NULL);
  4717. // Writes a number value.
  4718. void WriteNumber(uint32_t n);
  4719. void WriteNumber(uint64_t n);
  4720. // Writes a boolean value - false or true.
  4721. void WriteBool(bool b);
  4722. // Writes a null value.
  4723. void WriteNull();
  4724. private:
  4725. enum COLLECTION_TYPE
  4726. {
  4727. COLLECTION_TYPE_OBJECT,
  4728. COLLECTION_TYPE_ARRAY,
  4729. };
  4730. struct StackItem
  4731. {
  4732. COLLECTION_TYPE type;
  4733. uint32_t valueCount;
  4734. bool singleLineMode;
  4735. };
  4736. static const char* const INDENT;
  4737. VmaStringBuilder& m_SB;
  4738. VmaVector< StackItem, VmaStlAllocator<StackItem> > m_Stack;
  4739. bool m_InsideString;
  4740. void BeginValue(bool isString);
  4741. void WriteIndent(bool oneLess = false);
  4742. };
  4743. const char* const VmaJsonWriter::INDENT = " ";
  4744. #ifndef _VMA_JSON_WRITER_FUNCTIONS
  4745. VmaJsonWriter::VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb)
  4746. : m_SB(sb),
  4747. m_Stack(VmaStlAllocator<StackItem>(pAllocationCallbacks)),
  4748. m_InsideString(false) {}
  4749. VmaJsonWriter::~VmaJsonWriter()
  4750. {
  4751. VMA_ASSERT(!m_InsideString);
  4752. VMA_ASSERT(m_Stack.empty());
  4753. }
  4754. void VmaJsonWriter::BeginObject(bool singleLine)
  4755. {
  4756. VMA_ASSERT(!m_InsideString);
  4757. BeginValue(false);
  4758. m_SB.Add('{');
  4759. StackItem item;
  4760. item.type = COLLECTION_TYPE_OBJECT;
  4761. item.valueCount = 0;
  4762. item.singleLineMode = singleLine;
  4763. m_Stack.push_back(item);
  4764. }
  4765. void VmaJsonWriter::EndObject()
  4766. {
  4767. VMA_ASSERT(!m_InsideString);
  4768. WriteIndent(true);
  4769. m_SB.Add('}');
  4770. VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_OBJECT);
  4771. m_Stack.pop_back();
  4772. }
  4773. void VmaJsonWriter::BeginArray(bool singleLine)
  4774. {
  4775. VMA_ASSERT(!m_InsideString);
  4776. BeginValue(false);
  4777. m_SB.Add('[');
  4778. StackItem item;
  4779. item.type = COLLECTION_TYPE_ARRAY;
  4780. item.valueCount = 0;
  4781. item.singleLineMode = singleLine;
  4782. m_Stack.push_back(item);
  4783. }
  4784. void VmaJsonWriter::EndArray()
  4785. {
  4786. VMA_ASSERT(!m_InsideString);
  4787. WriteIndent(true);
  4788. m_SB.Add(']');
  4789. VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_ARRAY);
  4790. m_Stack.pop_back();
  4791. }
  4792. void VmaJsonWriter::WriteString(const char* pStr)
  4793. {
  4794. BeginString(pStr);
  4795. EndString();
  4796. }
  4797. void VmaJsonWriter::BeginString(const char* pStr)
  4798. {
  4799. VMA_ASSERT(!m_InsideString);
  4800. BeginValue(true);
  4801. m_SB.Add('"');
  4802. m_InsideString = true;
  4803. if (pStr != VMA_NULL && pStr[0] != '\0')
  4804. {
  4805. ContinueString(pStr);
  4806. }
  4807. }
  4808. void VmaJsonWriter::ContinueString(const char* pStr)
  4809. {
  4810. VMA_ASSERT(m_InsideString);
  4811. const size_t strLen = strlen(pStr);
  4812. for (size_t i = 0; i < strLen; ++i)
  4813. {
  4814. char ch = pStr[i];
  4815. if (ch == '\\')
  4816. {
  4817. m_SB.Add("\\\\");
  4818. }
  4819. else if (ch == '"')
  4820. {
  4821. m_SB.Add("\\\"");
  4822. }
  4823. else if (ch >= 32)
  4824. {
  4825. m_SB.Add(ch);
  4826. }
  4827. else switch (ch)
  4828. {
  4829. case '\b':
  4830. m_SB.Add("\\b");
  4831. break;
  4832. case '\f':
  4833. m_SB.Add("\\f");
  4834. break;
  4835. case '\n':
  4836. m_SB.Add("\\n");
  4837. break;
  4838. case '\r':
  4839. m_SB.Add("\\r");
  4840. break;
  4841. case '\t':
  4842. m_SB.Add("\\t");
  4843. break;
  4844. default:
  4845. VMA_ASSERT(0 && "Character not currently supported.");
  4846. }
  4847. }
  4848. }
  4849. void VmaJsonWriter::ContinueString(uint32_t n)
  4850. {
  4851. VMA_ASSERT(m_InsideString);
  4852. m_SB.AddNumber(n);
  4853. }
  4854. void VmaJsonWriter::ContinueString(uint64_t n)
  4855. {
  4856. VMA_ASSERT(m_InsideString);
  4857. m_SB.AddNumber(n);
  4858. }
  4859. void VmaJsonWriter::ContinueString_Pointer(const void* ptr)
  4860. {
  4861. VMA_ASSERT(m_InsideString);
  4862. m_SB.AddPointer(ptr);
  4863. }
  4864. void VmaJsonWriter::EndString(const char* pStr)
  4865. {
  4866. VMA_ASSERT(m_InsideString);
  4867. if (pStr != VMA_NULL && pStr[0] != '\0')
  4868. {
  4869. ContinueString(pStr);
  4870. }
  4871. m_SB.Add('"');
  4872. m_InsideString = false;
  4873. }
  4874. void VmaJsonWriter::WriteNumber(uint32_t n)
  4875. {
  4876. VMA_ASSERT(!m_InsideString);
  4877. BeginValue(false);
  4878. m_SB.AddNumber(n);
  4879. }
  4880. void VmaJsonWriter::WriteNumber(uint64_t n)
  4881. {
  4882. VMA_ASSERT(!m_InsideString);
  4883. BeginValue(false);
  4884. m_SB.AddNumber(n);
  4885. }
  4886. void VmaJsonWriter::WriteBool(bool b)
  4887. {
  4888. VMA_ASSERT(!m_InsideString);
  4889. BeginValue(false);
  4890. m_SB.Add(b ? "true" : "false");
  4891. }
  4892. void VmaJsonWriter::WriteNull()
  4893. {
  4894. VMA_ASSERT(!m_InsideString);
  4895. BeginValue(false);
  4896. m_SB.Add("null");
  4897. }
  4898. void VmaJsonWriter::BeginValue(bool isString)
  4899. {
  4900. if (!m_Stack.empty())
  4901. {
  4902. StackItem& currItem = m_Stack.back();
  4903. if (currItem.type == COLLECTION_TYPE_OBJECT &&
  4904. currItem.valueCount % 2 == 0)
  4905. {
  4906. VMA_ASSERT(isString);
  4907. }
  4908. if (currItem.type == COLLECTION_TYPE_OBJECT &&
  4909. currItem.valueCount % 2 != 0)
  4910. {
  4911. m_SB.Add(": ");
  4912. }
  4913. else if (currItem.valueCount > 0)
  4914. {
  4915. m_SB.Add(", ");
  4916. WriteIndent();
  4917. }
  4918. else
  4919. {
  4920. WriteIndent();
  4921. }
  4922. ++currItem.valueCount;
  4923. }
  4924. }
  4925. void VmaJsonWriter::WriteIndent(bool oneLess)
  4926. {
  4927. if (!m_Stack.empty() && !m_Stack.back().singleLineMode)
  4928. {
  4929. m_SB.AddNewLine();
  4930. size_t count = m_Stack.size();
  4931. if (count > 0 && oneLess)
  4932. {
  4933. --count;
  4934. }
  4935. for (size_t i = 0; i < count; ++i)
  4936. {
  4937. m_SB.Add(INDENT);
  4938. }
  4939. }
  4940. }
  4941. #endif // _VMA_JSON_WRITER_FUNCTIONS
  4942. static void VmaPrintDetailedStatistics(VmaJsonWriter& json, const VmaDetailedStatistics& stat)
  4943. {
  4944. json.BeginObject();
  4945. json.WriteString("BlockCount");
  4946. json.WriteNumber(stat.statistics.blockCount);
  4947. json.WriteString("BlockBytes");
  4948. json.WriteNumber(stat.statistics.blockBytes);
  4949. json.WriteString("AllocationCount");
  4950. json.WriteNumber(stat.statistics.allocationCount);
  4951. json.WriteString("AllocationBytes");
  4952. json.WriteNumber(stat.statistics.allocationBytes);
  4953. json.WriteString("UnusedRangeCount");
  4954. json.WriteNumber(stat.unusedRangeCount);
  4955. if (stat.statistics.allocationCount > 1)
  4956. {
  4957. json.WriteString("AllocationSizeMin");
  4958. json.WriteNumber(stat.allocationSizeMin);
  4959. json.WriteString("AllocationSizeMax");
  4960. json.WriteNumber(stat.allocationSizeMax);
  4961. }
  4962. if (stat.unusedRangeCount > 1)
  4963. {
  4964. json.WriteString("UnusedRangeSizeMin");
  4965. json.WriteNumber(stat.unusedRangeSizeMin);
  4966. json.WriteString("UnusedRangeSizeMax");
  4967. json.WriteNumber(stat.unusedRangeSizeMax);
  4968. }
  4969. json.EndObject();
  4970. }
  4971. #endif // _VMA_JSON_WRITER
  4972. #ifndef _VMA_MAPPING_HYSTERESIS
  4973. class VmaMappingHysteresis
  4974. {
  4975. VMA_CLASS_NO_COPY_NO_MOVE(VmaMappingHysteresis)
  4976. public:
  4977. VmaMappingHysteresis() = default;
  4978. uint32_t GetExtraMapping() const { return m_ExtraMapping; }
  4979. // Call when Map was called.
  4980. // Returns true if switched to extra +1 mapping reference count.
  4981. bool PostMap()
  4982. {
  4983. #if VMA_MAPPING_HYSTERESIS_ENABLED
  4984. if(m_ExtraMapping == 0)
  4985. {
  4986. ++m_MajorCounter;
  4987. if(m_MajorCounter >= COUNTER_MIN_EXTRA_MAPPING)
  4988. {
  4989. m_ExtraMapping = 1;
  4990. m_MajorCounter = 0;
  4991. m_MinorCounter = 0;
  4992. return true;
  4993. }
  4994. }
  4995. else // m_ExtraMapping == 1
  4996. PostMinorCounter();
  4997. #endif // #if VMA_MAPPING_HYSTERESIS_ENABLED
  4998. return false;
  4999. }
  5000. // Call when Unmap was called.
  5001. void PostUnmap()
  5002. {
  5003. #if VMA_MAPPING_HYSTERESIS_ENABLED
  5004. if(m_ExtraMapping == 0)
  5005. ++m_MajorCounter;
  5006. else // m_ExtraMapping == 1
  5007. PostMinorCounter();
  5008. #endif // #if VMA_MAPPING_HYSTERESIS_ENABLED
  5009. }
  5010. // Call when allocation was made from the memory block.
  5011. void PostAlloc()
  5012. {
  5013. #if VMA_MAPPING_HYSTERESIS_ENABLED
  5014. if(m_ExtraMapping == 1)
  5015. ++m_MajorCounter;
  5016. else // m_ExtraMapping == 0
  5017. PostMinorCounter();
  5018. #endif // #if VMA_MAPPING_HYSTERESIS_ENABLED
  5019. }
  5020. // Call when allocation was freed from the memory block.
  5021. // Returns true if switched to extra -1 mapping reference count.
  5022. bool PostFree()
  5023. {
  5024. #if VMA_MAPPING_HYSTERESIS_ENABLED
  5025. if(m_ExtraMapping == 1)
  5026. {
  5027. ++m_MajorCounter;
  5028. if(m_MajorCounter >= COUNTER_MIN_EXTRA_MAPPING &&
  5029. m_MajorCounter > m_MinorCounter + 1)
  5030. {
  5031. m_ExtraMapping = 0;
  5032. m_MajorCounter = 0;
  5033. m_MinorCounter = 0;
  5034. return true;
  5035. }
  5036. }
  5037. else // m_ExtraMapping == 0
  5038. PostMinorCounter();
  5039. #endif // #if VMA_MAPPING_HYSTERESIS_ENABLED
  5040. return false;
  5041. }
  5042. private:
  5043. static const int32_t COUNTER_MIN_EXTRA_MAPPING = 7;
  5044. uint32_t m_MinorCounter = 0;
  5045. uint32_t m_MajorCounter = 0;
  5046. uint32_t m_ExtraMapping = 0; // 0 or 1.
  5047. void PostMinorCounter()
  5048. {
  5049. if(m_MinorCounter < m_MajorCounter)
  5050. {
  5051. ++m_MinorCounter;
  5052. }
  5053. else if(m_MajorCounter > 0)
  5054. {
  5055. --m_MajorCounter;
  5056. --m_MinorCounter;
  5057. }
  5058. }
  5059. };
  5060. #endif // _VMA_MAPPING_HYSTERESIS
  5061. #ifndef _VMA_DEVICE_MEMORY_BLOCK
  5062. /*
  5063. Represents a single block of device memory (`VkDeviceMemory`) with all the
  5064. data about its regions (aka suballocations, #VmaAllocation), assigned and free.
  5065. Thread-safety:
  5066. - Access to m_pMetadata must be externally synchronized.
  5067. - Map, Unmap, Bind* are synchronized internally.
  5068. */
  5069. class VmaDeviceMemoryBlock
  5070. {
  5071. VMA_CLASS_NO_COPY_NO_MOVE(VmaDeviceMemoryBlock)
  5072. public:
  5073. VmaBlockMetadata* m_pMetadata;
  5074. VmaDeviceMemoryBlock(VmaAllocator hAllocator);
  5075. ~VmaDeviceMemoryBlock();
  5076. // Always call after construction.
  5077. void Init(
  5078. VmaAllocator hAllocator,
  5079. VmaPool hParentPool,
  5080. uint32_t newMemoryTypeIndex,
  5081. VkDeviceMemory newMemory,
  5082. VkDeviceSize newSize,
  5083. uint32_t id,
  5084. uint32_t algorithm,
  5085. VkDeviceSize bufferImageGranularity);
  5086. // Always call before destruction.
  5087. void Destroy(VmaAllocator allocator);
  5088. VmaPool GetParentPool() const { return m_hParentPool; }
  5089. VkDeviceMemory GetDeviceMemory() const { return m_hMemory; }
  5090. uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
  5091. uint32_t GetId() const { return m_Id; }
  5092. void* GetMappedData() const { return m_pMappedData; }
  5093. uint32_t GetMapRefCount() const { return m_MapCount; }
  5094. // Call when allocation/free was made from m_pMetadata.
  5095. // Used for m_MappingHysteresis.
  5096. void PostAlloc(VmaAllocator hAllocator);
  5097. void PostFree(VmaAllocator hAllocator);
  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 WriteMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize);
  5105. VkResult ValidateMagicValueAfterAllocation(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 is 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_MapAndBindMutex;
  5129. VmaMappingHysteresis m_MappingHysteresis;
  5130. uint32_t m_MapCount;
  5131. void* m_pMappedData;
  5132. };
  5133. #endif // _VMA_DEVICE_MEMORY_BLOCK
  5134. #ifndef _VMA_ALLOCATION_T
  5135. struct VmaAllocation_T
  5136. {
  5137. friend struct VmaDedicatedAllocationListItemTraits;
  5138. enum FLAGS
  5139. {
  5140. FLAG_PERSISTENT_MAP = 0x01,
  5141. FLAG_MAPPING_ALLOWED = 0x02,
  5142. };
  5143. public:
  5144. enum ALLOCATION_TYPE
  5145. {
  5146. ALLOCATION_TYPE_NONE,
  5147. ALLOCATION_TYPE_BLOCK,
  5148. ALLOCATION_TYPE_DEDICATED,
  5149. };
  5150. // This struct is allocated using VmaPoolAllocator.
  5151. VmaAllocation_T(bool mappingAllowed);
  5152. ~VmaAllocation_T();
  5153. void InitBlockAllocation(
  5154. VmaDeviceMemoryBlock* block,
  5155. VmaAllocHandle allocHandle,
  5156. VkDeviceSize alignment,
  5157. VkDeviceSize size,
  5158. uint32_t memoryTypeIndex,
  5159. VmaSuballocationType suballocationType,
  5160. bool mapped);
  5161. // pMappedData not null means allocation is created with MAPPED flag.
  5162. void InitDedicatedAllocation(
  5163. VmaPool hParentPool,
  5164. uint32_t memoryTypeIndex,
  5165. VkDeviceMemory hMemory,
  5166. VmaSuballocationType suballocationType,
  5167. void* pMappedData,
  5168. VkDeviceSize size);
  5169. ALLOCATION_TYPE GetType() const { return (ALLOCATION_TYPE)m_Type; }
  5170. VkDeviceSize GetAlignment() const { return m_Alignment; }
  5171. VkDeviceSize GetSize() const { return m_Size; }
  5172. void* GetUserData() const { return m_pUserData; }
  5173. const char* GetName() const { return m_pName; }
  5174. VmaSuballocationType GetSuballocationType() const { return (VmaSuballocationType)m_SuballocationType; }
  5175. VmaDeviceMemoryBlock* GetBlock() const { VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK); return m_BlockAllocation.m_Block; }
  5176. uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
  5177. bool IsPersistentMap() const { return (m_Flags & FLAG_PERSISTENT_MAP) != 0; }
  5178. bool IsMappingAllowed() const { return (m_Flags & FLAG_MAPPING_ALLOWED) != 0; }
  5179. void SetUserData(VmaAllocator hAllocator, void* pUserData) { m_pUserData = pUserData; }
  5180. void SetName(VmaAllocator hAllocator, const char* pName);
  5181. void FreeName(VmaAllocator hAllocator);
  5182. uint8_t SwapBlockAllocation(VmaAllocator hAllocator, VmaAllocation allocation);
  5183. VmaAllocHandle GetAllocHandle() const;
  5184. VkDeviceSize GetOffset() const;
  5185. VmaPool GetParentPool() const;
  5186. VkDeviceMemory GetMemory() const;
  5187. void* GetMappedData() const;
  5188. void BlockAllocMap();
  5189. void BlockAllocUnmap();
  5190. VkResult DedicatedAllocMap(VmaAllocator hAllocator, void** ppData);
  5191. void DedicatedAllocUnmap(VmaAllocator hAllocator);
  5192. #if VMA_STATS_STRING_ENABLED
  5193. uint32_t GetBufferImageUsage() const { return m_BufferImageUsage; }
  5194. void InitBufferImageUsage(uint32_t bufferImageUsage);
  5195. void PrintParameters(class VmaJsonWriter& json) const;
  5196. #endif
  5197. private:
  5198. // Allocation out of VmaDeviceMemoryBlock.
  5199. struct BlockAllocation
  5200. {
  5201. VmaDeviceMemoryBlock* m_Block;
  5202. VmaAllocHandle m_AllocHandle;
  5203. };
  5204. // Allocation for an object that has its own private VkDeviceMemory.
  5205. struct DedicatedAllocation
  5206. {
  5207. VmaPool m_hParentPool; // VK_NULL_HANDLE if not belongs to custom pool.
  5208. VkDeviceMemory m_hMemory;
  5209. void* m_pMappedData; // Not null means memory is mapped.
  5210. VmaAllocation_T* m_Prev;
  5211. VmaAllocation_T* m_Next;
  5212. };
  5213. union
  5214. {
  5215. // Allocation out of VmaDeviceMemoryBlock.
  5216. BlockAllocation m_BlockAllocation;
  5217. // Allocation for an object that has its own private VkDeviceMemory.
  5218. DedicatedAllocation m_DedicatedAllocation;
  5219. };
  5220. VkDeviceSize m_Alignment;
  5221. VkDeviceSize m_Size;
  5222. void* m_pUserData;
  5223. char* m_pName;
  5224. uint32_t m_MemoryTypeIndex;
  5225. uint8_t m_Type; // ALLOCATION_TYPE
  5226. uint8_t m_SuballocationType; // VmaSuballocationType
  5227. // Reference counter for vmaMapMemory()/vmaUnmapMemory().
  5228. uint8_t m_MapCount;
  5229. uint8_t m_Flags; // enum FLAGS
  5230. #if VMA_STATS_STRING_ENABLED
  5231. uint32_t m_BufferImageUsage; // 0 if unknown.
  5232. #endif
  5233. };
  5234. #endif // _VMA_ALLOCATION_T
  5235. #ifndef _VMA_DEDICATED_ALLOCATION_LIST_ITEM_TRAITS
  5236. struct VmaDedicatedAllocationListItemTraits
  5237. {
  5238. typedef VmaAllocation_T ItemType;
  5239. static ItemType* GetPrev(const ItemType* item)
  5240. {
  5241. VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  5242. return item->m_DedicatedAllocation.m_Prev;
  5243. }
  5244. static ItemType* GetNext(const ItemType* item)
  5245. {
  5246. VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  5247. return item->m_DedicatedAllocation.m_Next;
  5248. }
  5249. static ItemType*& AccessPrev(ItemType* item)
  5250. {
  5251. VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  5252. return item->m_DedicatedAllocation.m_Prev;
  5253. }
  5254. static ItemType*& AccessNext(ItemType* item)
  5255. {
  5256. VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  5257. return item->m_DedicatedAllocation.m_Next;
  5258. }
  5259. };
  5260. #endif // _VMA_DEDICATED_ALLOCATION_LIST_ITEM_TRAITS
  5261. #ifndef _VMA_DEDICATED_ALLOCATION_LIST
  5262. /*
  5263. Stores linked list of VmaAllocation_T objects.
  5264. Thread-safe, synchronized internally.
  5265. */
  5266. class VmaDedicatedAllocationList
  5267. {
  5268. VMA_CLASS_NO_COPY_NO_MOVE(VmaDedicatedAllocationList)
  5269. public:
  5270. VmaDedicatedAllocationList() {}
  5271. ~VmaDedicatedAllocationList();
  5272. void Init(bool useMutex) { m_UseMutex = useMutex; }
  5273. bool Validate();
  5274. void AddDetailedStatistics(VmaDetailedStatistics& inoutStats);
  5275. void AddStatistics(VmaStatistics& inoutStats);
  5276. #if VMA_STATS_STRING_ENABLED
  5277. // Writes JSON array with the list of allocations.
  5278. void BuildStatsString(VmaJsonWriter& json);
  5279. #endif
  5280. bool IsEmpty();
  5281. void Register(VmaAllocation alloc);
  5282. void Unregister(VmaAllocation alloc);
  5283. private:
  5284. typedef VmaIntrusiveLinkedList<VmaDedicatedAllocationListItemTraits> DedicatedAllocationLinkedList;
  5285. bool m_UseMutex = true;
  5286. VMA_RW_MUTEX m_Mutex;
  5287. DedicatedAllocationLinkedList m_AllocationList;
  5288. };
  5289. #ifndef _VMA_DEDICATED_ALLOCATION_LIST_FUNCTIONS
  5290. VmaDedicatedAllocationList::~VmaDedicatedAllocationList()
  5291. {
  5292. VMA_HEAVY_ASSERT(Validate());
  5293. if (!m_AllocationList.IsEmpty())
  5294. {
  5295. VMA_ASSERT(false && "Unfreed dedicated allocations found!");
  5296. }
  5297. }
  5298. bool VmaDedicatedAllocationList::Validate()
  5299. {
  5300. const size_t declaredCount = m_AllocationList.GetCount();
  5301. size_t actualCount = 0;
  5302. VmaMutexLockRead lock(m_Mutex, m_UseMutex);
  5303. for (VmaAllocation alloc = m_AllocationList.Front();
  5304. alloc != VMA_NULL; alloc = m_AllocationList.GetNext(alloc))
  5305. {
  5306. ++actualCount;
  5307. }
  5308. VMA_VALIDATE(actualCount == declaredCount);
  5309. return true;
  5310. }
  5311. void VmaDedicatedAllocationList::AddDetailedStatistics(VmaDetailedStatistics& inoutStats)
  5312. {
  5313. for(auto* item = m_AllocationList.Front(); item != nullptr; item = DedicatedAllocationLinkedList::GetNext(item))
  5314. {
  5315. const VkDeviceSize size = item->GetSize();
  5316. inoutStats.statistics.blockCount++;
  5317. inoutStats.statistics.blockBytes += size;
  5318. VmaAddDetailedStatisticsAllocation(inoutStats, item->GetSize());
  5319. }
  5320. }
  5321. void VmaDedicatedAllocationList::AddStatistics(VmaStatistics& inoutStats)
  5322. {
  5323. VmaMutexLockRead lock(m_Mutex, m_UseMutex);
  5324. const uint32_t allocCount = (uint32_t)m_AllocationList.GetCount();
  5325. inoutStats.blockCount += allocCount;
  5326. inoutStats.allocationCount += allocCount;
  5327. for(auto* item = m_AllocationList.Front(); item != nullptr; item = DedicatedAllocationLinkedList::GetNext(item))
  5328. {
  5329. const VkDeviceSize size = item->GetSize();
  5330. inoutStats.blockBytes += size;
  5331. inoutStats.allocationBytes += size;
  5332. }
  5333. }
  5334. #if VMA_STATS_STRING_ENABLED
  5335. void VmaDedicatedAllocationList::BuildStatsString(VmaJsonWriter& json)
  5336. {
  5337. VmaMutexLockRead lock(m_Mutex, m_UseMutex);
  5338. json.BeginArray();
  5339. for (VmaAllocation alloc = m_AllocationList.Front();
  5340. alloc != VMA_NULL; alloc = m_AllocationList.GetNext(alloc))
  5341. {
  5342. json.BeginObject(true);
  5343. alloc->PrintParameters(json);
  5344. json.EndObject();
  5345. }
  5346. json.EndArray();
  5347. }
  5348. #endif // VMA_STATS_STRING_ENABLED
  5349. bool VmaDedicatedAllocationList::IsEmpty()
  5350. {
  5351. VmaMutexLockRead lock(m_Mutex, m_UseMutex);
  5352. return m_AllocationList.IsEmpty();
  5353. }
  5354. void VmaDedicatedAllocationList::Register(VmaAllocation alloc)
  5355. {
  5356. VmaMutexLockWrite lock(m_Mutex, m_UseMutex);
  5357. m_AllocationList.PushBack(alloc);
  5358. }
  5359. void VmaDedicatedAllocationList::Unregister(VmaAllocation alloc)
  5360. {
  5361. VmaMutexLockWrite lock(m_Mutex, m_UseMutex);
  5362. m_AllocationList.Remove(alloc);
  5363. }
  5364. #endif // _VMA_DEDICATED_ALLOCATION_LIST_FUNCTIONS
  5365. #endif // _VMA_DEDICATED_ALLOCATION_LIST
  5366. #ifndef _VMA_SUBALLOCATION
  5367. /*
  5368. Represents a region of VmaDeviceMemoryBlock that is either assigned and returned as
  5369. allocated memory block or free.
  5370. */
  5371. struct VmaSuballocation
  5372. {
  5373. VkDeviceSize offset;
  5374. VkDeviceSize size;
  5375. void* userData;
  5376. VmaSuballocationType type;
  5377. };
  5378. // Comparator for offsets.
  5379. struct VmaSuballocationOffsetLess
  5380. {
  5381. bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const
  5382. {
  5383. return lhs.offset < rhs.offset;
  5384. }
  5385. };
  5386. struct VmaSuballocationOffsetGreater
  5387. {
  5388. bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const
  5389. {
  5390. return lhs.offset > rhs.offset;
  5391. }
  5392. };
  5393. struct VmaSuballocationItemSizeLess
  5394. {
  5395. bool operator()(const VmaSuballocationList::iterator lhs,
  5396. const VmaSuballocationList::iterator rhs) const
  5397. {
  5398. return lhs->size < rhs->size;
  5399. }
  5400. bool operator()(const VmaSuballocationList::iterator lhs,
  5401. VkDeviceSize rhsSize) const
  5402. {
  5403. return lhs->size < rhsSize;
  5404. }
  5405. };
  5406. #endif // _VMA_SUBALLOCATION
  5407. #ifndef _VMA_ALLOCATION_REQUEST
  5408. /*
  5409. Parameters of planned allocation inside a VmaDeviceMemoryBlock.
  5410. item points to a FREE suballocation.
  5411. */
  5412. struct VmaAllocationRequest
  5413. {
  5414. VmaAllocHandle allocHandle;
  5415. VkDeviceSize size;
  5416. VmaSuballocationList::iterator item;
  5417. void* customData;
  5418. uint64_t algorithmData;
  5419. VmaAllocationRequestType type;
  5420. };
  5421. #endif // _VMA_ALLOCATION_REQUEST
  5422. #ifndef _VMA_BLOCK_METADATA
  5423. /*
  5424. Data structure used for bookkeeping of allocations and unused ranges of memory
  5425. in a single VkDeviceMemory block.
  5426. */
  5427. class VmaBlockMetadata
  5428. {
  5429. VMA_CLASS_NO_COPY_NO_MOVE(VmaBlockMetadata)
  5430. public:
  5431. // pAllocationCallbacks, if not null, must be owned externally - alive and unchanged for the whole lifetime of this object.
  5432. VmaBlockMetadata(const VkAllocationCallbacks* pAllocationCallbacks,
  5433. VkDeviceSize bufferImageGranularity, bool isVirtual);
  5434. virtual ~VmaBlockMetadata() = default;
  5435. virtual void Init(VkDeviceSize size) { m_Size = size; }
  5436. bool IsVirtual() const { return m_IsVirtual; }
  5437. VkDeviceSize GetSize() const { return m_Size; }
  5438. // Validates all data structures inside this object. If not valid, returns false.
  5439. virtual bool Validate() const = 0;
  5440. virtual size_t GetAllocationCount() const = 0;
  5441. virtual size_t GetFreeRegionsCount() const = 0;
  5442. virtual VkDeviceSize GetSumFreeSize() const = 0;
  5443. // Returns true if this block is empty - contains only single free suballocation.
  5444. virtual bool IsEmpty() const = 0;
  5445. virtual void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) = 0;
  5446. virtual VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const = 0;
  5447. virtual void* GetAllocationUserData(VmaAllocHandle allocHandle) const = 0;
  5448. virtual VmaAllocHandle GetAllocationListBegin() const = 0;
  5449. virtual VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const = 0;
  5450. virtual VkDeviceSize GetNextFreeRegionSize(VmaAllocHandle alloc) const = 0;
  5451. // Shouldn't modify blockCount.
  5452. virtual void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const = 0;
  5453. virtual void AddStatistics(VmaStatistics& inoutStats) const = 0;
  5454. #if VMA_STATS_STRING_ENABLED
  5455. virtual void PrintDetailedMap(class VmaJsonWriter& json) const = 0;
  5456. #endif
  5457. // Tries to find a place for suballocation with given parameters inside this block.
  5458. // If succeeded, fills pAllocationRequest and returns true.
  5459. // If failed, returns false.
  5460. virtual bool CreateAllocationRequest(
  5461. VkDeviceSize allocSize,
  5462. VkDeviceSize allocAlignment,
  5463. bool upperAddress,
  5464. VmaSuballocationType allocType,
  5465. // Always one of VMA_ALLOCATION_CREATE_STRATEGY_* or VMA_ALLOCATION_INTERNAL_STRATEGY_* flags.
  5466. uint32_t strategy,
  5467. VmaAllocationRequest* pAllocationRequest) = 0;
  5468. virtual VkResult CheckCorruption(const void* pBlockData) = 0;
  5469. // Makes actual allocation based on request. Request must already be checked and valid.
  5470. virtual void Alloc(
  5471. const VmaAllocationRequest& request,
  5472. VmaSuballocationType type,
  5473. void* userData) = 0;
  5474. // Frees suballocation assigned to given memory region.
  5475. virtual void Free(VmaAllocHandle allocHandle) = 0;
  5476. // Frees all allocations.
  5477. // Careful! Don't call it if there are VmaAllocation objects owned by userData of cleared allocations!
  5478. virtual void Clear() = 0;
  5479. virtual void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) = 0;
  5480. virtual void DebugLogAllAllocations() const = 0;
  5481. protected:
  5482. const VkAllocationCallbacks* GetAllocationCallbacks() const { return m_pAllocationCallbacks; }
  5483. VkDeviceSize GetBufferImageGranularity() const { return m_BufferImageGranularity; }
  5484. VkDeviceSize GetDebugMargin() const { return VkDeviceSize(IsVirtual() ? 0 : VMA_DEBUG_MARGIN); }
  5485. void DebugLogAllocation(VkDeviceSize offset, VkDeviceSize size, void* userData) const;
  5486. #if VMA_STATS_STRING_ENABLED
  5487. // mapRefCount == UINT32_MAX means unspecified.
  5488. void PrintDetailedMap_Begin(class VmaJsonWriter& json,
  5489. VkDeviceSize unusedBytes,
  5490. size_t allocationCount,
  5491. size_t unusedRangeCount) const;
  5492. void PrintDetailedMap_Allocation(class VmaJsonWriter& json,
  5493. VkDeviceSize offset, VkDeviceSize size, void* userData) const;
  5494. void PrintDetailedMap_UnusedRange(class VmaJsonWriter& json,
  5495. VkDeviceSize offset,
  5496. VkDeviceSize size) const;
  5497. void PrintDetailedMap_End(class VmaJsonWriter& json) const;
  5498. #endif
  5499. private:
  5500. VkDeviceSize m_Size;
  5501. const VkAllocationCallbacks* m_pAllocationCallbacks;
  5502. const VkDeviceSize m_BufferImageGranularity;
  5503. const bool m_IsVirtual;
  5504. };
  5505. #ifndef _VMA_BLOCK_METADATA_FUNCTIONS
  5506. VmaBlockMetadata::VmaBlockMetadata(const VkAllocationCallbacks* pAllocationCallbacks,
  5507. VkDeviceSize bufferImageGranularity, bool isVirtual)
  5508. : m_Size(0),
  5509. m_pAllocationCallbacks(pAllocationCallbacks),
  5510. m_BufferImageGranularity(bufferImageGranularity),
  5511. m_IsVirtual(isVirtual) {}
  5512. void VmaBlockMetadata::DebugLogAllocation(VkDeviceSize offset, VkDeviceSize size, void* userData) const
  5513. {
  5514. if (IsVirtual())
  5515. {
  5516. VMA_DEBUG_LOG_FORMAT("UNFREED VIRTUAL ALLOCATION; Offset: %llu; Size: %llu; UserData: %p", offset, size, userData);
  5517. }
  5518. else
  5519. {
  5520. VMA_ASSERT(userData != VMA_NULL);
  5521. VmaAllocation allocation = reinterpret_cast<VmaAllocation>(userData);
  5522. userData = allocation->GetUserData();
  5523. const char* name = allocation->GetName();
  5524. #if VMA_STATS_STRING_ENABLED
  5525. VMA_DEBUG_LOG_FORMAT("UNFREED ALLOCATION; Offset: %llu; Size: %llu; UserData: %p; Name: %s; Type: %s; Usage: %u",
  5526. offset, size, userData, name ? name : "vma_empty",
  5527. VMA_SUBALLOCATION_TYPE_NAMES[allocation->GetSuballocationType()],
  5528. allocation->GetBufferImageUsage());
  5529. #else
  5530. VMA_DEBUG_LOG_FORMAT("UNFREED ALLOCATION; Offset: %llu; Size: %llu; UserData: %p; Name: %s; Type: %u",
  5531. offset, size, userData, name ? name : "vma_empty",
  5532. (uint32_t)allocation->GetSuballocationType());
  5533. #endif // VMA_STATS_STRING_ENABLED
  5534. }
  5535. }
  5536. #if VMA_STATS_STRING_ENABLED
  5537. void VmaBlockMetadata::PrintDetailedMap_Begin(class VmaJsonWriter& json,
  5538. VkDeviceSize unusedBytes, size_t allocationCount, size_t unusedRangeCount) const
  5539. {
  5540. json.WriteString("TotalBytes");
  5541. json.WriteNumber(GetSize());
  5542. json.WriteString("UnusedBytes");
  5543. json.WriteNumber(unusedBytes);
  5544. json.WriteString("Allocations");
  5545. json.WriteNumber((uint64_t)allocationCount);
  5546. json.WriteString("UnusedRanges");
  5547. json.WriteNumber((uint64_t)unusedRangeCount);
  5548. json.WriteString("Suballocations");
  5549. json.BeginArray();
  5550. }
  5551. void VmaBlockMetadata::PrintDetailedMap_Allocation(class VmaJsonWriter& json,
  5552. VkDeviceSize offset, VkDeviceSize size, void* userData) const
  5553. {
  5554. json.BeginObject(true);
  5555. json.WriteString("Offset");
  5556. json.WriteNumber(offset);
  5557. if (IsVirtual())
  5558. {
  5559. json.WriteString("Size");
  5560. json.WriteNumber(size);
  5561. if (userData)
  5562. {
  5563. json.WriteString("CustomData");
  5564. json.BeginString();
  5565. json.ContinueString_Pointer(userData);
  5566. json.EndString();
  5567. }
  5568. }
  5569. else
  5570. {
  5571. ((VmaAllocation)userData)->PrintParameters(json);
  5572. }
  5573. json.EndObject();
  5574. }
  5575. void VmaBlockMetadata::PrintDetailedMap_UnusedRange(class VmaJsonWriter& json,
  5576. VkDeviceSize offset, VkDeviceSize size) const
  5577. {
  5578. json.BeginObject(true);
  5579. json.WriteString("Offset");
  5580. json.WriteNumber(offset);
  5581. json.WriteString("Type");
  5582. json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[VMA_SUBALLOCATION_TYPE_FREE]);
  5583. json.WriteString("Size");
  5584. json.WriteNumber(size);
  5585. json.EndObject();
  5586. }
  5587. void VmaBlockMetadata::PrintDetailedMap_End(class VmaJsonWriter& json) const
  5588. {
  5589. json.EndArray();
  5590. }
  5591. #endif // VMA_STATS_STRING_ENABLED
  5592. #endif // _VMA_BLOCK_METADATA_FUNCTIONS
  5593. #endif // _VMA_BLOCK_METADATA
  5594. #ifndef _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY
  5595. // Before deleting object of this class remember to call 'Destroy()'
  5596. class VmaBlockBufferImageGranularity final
  5597. {
  5598. public:
  5599. struct ValidationContext
  5600. {
  5601. const VkAllocationCallbacks* allocCallbacks;
  5602. uint16_t* pageAllocs;
  5603. };
  5604. VmaBlockBufferImageGranularity(VkDeviceSize bufferImageGranularity);
  5605. ~VmaBlockBufferImageGranularity();
  5606. bool IsEnabled() const { return m_BufferImageGranularity > MAX_LOW_BUFFER_IMAGE_GRANULARITY; }
  5607. void Init(const VkAllocationCallbacks* pAllocationCallbacks, VkDeviceSize size);
  5608. // Before destroying object you must call free it's memory
  5609. void Destroy(const VkAllocationCallbacks* pAllocationCallbacks);
  5610. void RoundupAllocRequest(VmaSuballocationType allocType,
  5611. VkDeviceSize& inOutAllocSize,
  5612. VkDeviceSize& inOutAllocAlignment) const;
  5613. bool CheckConflictAndAlignUp(VkDeviceSize& inOutAllocOffset,
  5614. VkDeviceSize allocSize,
  5615. VkDeviceSize blockOffset,
  5616. VkDeviceSize blockSize,
  5617. VmaSuballocationType allocType) const;
  5618. void AllocPages(uint8_t allocType, VkDeviceSize offset, VkDeviceSize size);
  5619. void FreePages(VkDeviceSize offset, VkDeviceSize size);
  5620. void Clear();
  5621. ValidationContext StartValidation(const VkAllocationCallbacks* pAllocationCallbacks,
  5622. bool isVirutal) const;
  5623. bool Validate(ValidationContext& ctx, VkDeviceSize offset, VkDeviceSize size) const;
  5624. bool FinishValidation(ValidationContext& ctx) const;
  5625. private:
  5626. static const uint16_t MAX_LOW_BUFFER_IMAGE_GRANULARITY = 256;
  5627. struct RegionInfo
  5628. {
  5629. uint8_t allocType;
  5630. uint16_t allocCount;
  5631. };
  5632. VkDeviceSize m_BufferImageGranularity;
  5633. uint32_t m_RegionCount;
  5634. RegionInfo* m_RegionInfo;
  5635. uint32_t GetStartPage(VkDeviceSize offset) const { return OffsetToPageIndex(offset & ~(m_BufferImageGranularity - 1)); }
  5636. uint32_t GetEndPage(VkDeviceSize offset, VkDeviceSize size) const { return OffsetToPageIndex((offset + size - 1) & ~(m_BufferImageGranularity - 1)); }
  5637. uint32_t OffsetToPageIndex(VkDeviceSize offset) const;
  5638. void AllocPage(RegionInfo& page, uint8_t allocType);
  5639. };
  5640. #ifndef _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY_FUNCTIONS
  5641. VmaBlockBufferImageGranularity::VmaBlockBufferImageGranularity(VkDeviceSize bufferImageGranularity)
  5642. : m_BufferImageGranularity(bufferImageGranularity),
  5643. m_RegionCount(0),
  5644. m_RegionInfo(VMA_NULL) {}
  5645. VmaBlockBufferImageGranularity::~VmaBlockBufferImageGranularity()
  5646. {
  5647. VMA_ASSERT(m_RegionInfo == VMA_NULL && "Free not called before destroying object!");
  5648. }
  5649. void VmaBlockBufferImageGranularity::Init(const VkAllocationCallbacks* pAllocationCallbacks, VkDeviceSize size)
  5650. {
  5651. if (IsEnabled())
  5652. {
  5653. m_RegionCount = static_cast<uint32_t>(VmaDivideRoundingUp(size, m_BufferImageGranularity));
  5654. m_RegionInfo = vma_new_array(pAllocationCallbacks, RegionInfo, m_RegionCount);
  5655. memset(m_RegionInfo, 0, m_RegionCount * sizeof(RegionInfo));
  5656. }
  5657. }
  5658. void VmaBlockBufferImageGranularity::Destroy(const VkAllocationCallbacks* pAllocationCallbacks)
  5659. {
  5660. if (m_RegionInfo)
  5661. {
  5662. vma_delete_array(pAllocationCallbacks, m_RegionInfo, m_RegionCount);
  5663. m_RegionInfo = VMA_NULL;
  5664. }
  5665. }
  5666. void VmaBlockBufferImageGranularity::RoundupAllocRequest(VmaSuballocationType allocType,
  5667. VkDeviceSize& inOutAllocSize,
  5668. VkDeviceSize& inOutAllocAlignment) const
  5669. {
  5670. if (m_BufferImageGranularity > 1 &&
  5671. m_BufferImageGranularity <= MAX_LOW_BUFFER_IMAGE_GRANULARITY)
  5672. {
  5673. if (allocType == VMA_SUBALLOCATION_TYPE_UNKNOWN ||
  5674. allocType == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
  5675. allocType == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL)
  5676. {
  5677. inOutAllocAlignment = VMA_MAX(inOutAllocAlignment, m_BufferImageGranularity);
  5678. inOutAllocSize = VmaAlignUp(inOutAllocSize, m_BufferImageGranularity);
  5679. }
  5680. }
  5681. }
  5682. bool VmaBlockBufferImageGranularity::CheckConflictAndAlignUp(VkDeviceSize& inOutAllocOffset,
  5683. VkDeviceSize allocSize,
  5684. VkDeviceSize blockOffset,
  5685. VkDeviceSize blockSize,
  5686. VmaSuballocationType allocType) const
  5687. {
  5688. if (IsEnabled())
  5689. {
  5690. uint32_t startPage = GetStartPage(inOutAllocOffset);
  5691. if (m_RegionInfo[startPage].allocCount > 0 &&
  5692. VmaIsBufferImageGranularityConflict(static_cast<VmaSuballocationType>(m_RegionInfo[startPage].allocType), allocType))
  5693. {
  5694. inOutAllocOffset = VmaAlignUp(inOutAllocOffset, m_BufferImageGranularity);
  5695. if (blockSize < allocSize + inOutAllocOffset - blockOffset)
  5696. return true;
  5697. ++startPage;
  5698. }
  5699. uint32_t endPage = GetEndPage(inOutAllocOffset, allocSize);
  5700. if (endPage != startPage &&
  5701. m_RegionInfo[endPage].allocCount > 0 &&
  5702. VmaIsBufferImageGranularityConflict(static_cast<VmaSuballocationType>(m_RegionInfo[endPage].allocType), allocType))
  5703. {
  5704. return true;
  5705. }
  5706. }
  5707. return false;
  5708. }
  5709. void VmaBlockBufferImageGranularity::AllocPages(uint8_t allocType, VkDeviceSize offset, VkDeviceSize size)
  5710. {
  5711. if (IsEnabled())
  5712. {
  5713. uint32_t startPage = GetStartPage(offset);
  5714. AllocPage(m_RegionInfo[startPage], allocType);
  5715. uint32_t endPage = GetEndPage(offset, size);
  5716. if (startPage != endPage)
  5717. AllocPage(m_RegionInfo[endPage], allocType);
  5718. }
  5719. }
  5720. void VmaBlockBufferImageGranularity::FreePages(VkDeviceSize offset, VkDeviceSize size)
  5721. {
  5722. if (IsEnabled())
  5723. {
  5724. uint32_t startPage = GetStartPage(offset);
  5725. --m_RegionInfo[startPage].allocCount;
  5726. if (m_RegionInfo[startPage].allocCount == 0)
  5727. m_RegionInfo[startPage].allocType = VMA_SUBALLOCATION_TYPE_FREE;
  5728. uint32_t endPage = GetEndPage(offset, size);
  5729. if (startPage != endPage)
  5730. {
  5731. --m_RegionInfo[endPage].allocCount;
  5732. if (m_RegionInfo[endPage].allocCount == 0)
  5733. m_RegionInfo[endPage].allocType = VMA_SUBALLOCATION_TYPE_FREE;
  5734. }
  5735. }
  5736. }
  5737. void VmaBlockBufferImageGranularity::Clear()
  5738. {
  5739. if (m_RegionInfo)
  5740. memset(m_RegionInfo, 0, m_RegionCount * sizeof(RegionInfo));
  5741. }
  5742. VmaBlockBufferImageGranularity::ValidationContext VmaBlockBufferImageGranularity::StartValidation(
  5743. const VkAllocationCallbacks* pAllocationCallbacks, bool isVirutal) const
  5744. {
  5745. ValidationContext ctx{ pAllocationCallbacks, VMA_NULL };
  5746. if (!isVirutal && IsEnabled())
  5747. {
  5748. ctx.pageAllocs = vma_new_array(pAllocationCallbacks, uint16_t, m_RegionCount);
  5749. memset(ctx.pageAllocs, 0, m_RegionCount * sizeof(uint16_t));
  5750. }
  5751. return ctx;
  5752. }
  5753. bool VmaBlockBufferImageGranularity::Validate(ValidationContext& ctx,
  5754. VkDeviceSize offset, VkDeviceSize size) const
  5755. {
  5756. if (IsEnabled())
  5757. {
  5758. uint32_t start = GetStartPage(offset);
  5759. ++ctx.pageAllocs[start];
  5760. VMA_VALIDATE(m_RegionInfo[start].allocCount > 0);
  5761. uint32_t end = GetEndPage(offset, size);
  5762. if (start != end)
  5763. {
  5764. ++ctx.pageAllocs[end];
  5765. VMA_VALIDATE(m_RegionInfo[end].allocCount > 0);
  5766. }
  5767. }
  5768. return true;
  5769. }
  5770. bool VmaBlockBufferImageGranularity::FinishValidation(ValidationContext& ctx) const
  5771. {
  5772. // Check proper page structure
  5773. if (IsEnabled())
  5774. {
  5775. VMA_ASSERT(ctx.pageAllocs != VMA_NULL && "Validation context not initialized!");
  5776. for (uint32_t page = 0; page < m_RegionCount; ++page)
  5777. {
  5778. VMA_VALIDATE(ctx.pageAllocs[page] == m_RegionInfo[page].allocCount);
  5779. }
  5780. vma_delete_array(ctx.allocCallbacks, ctx.pageAllocs, m_RegionCount);
  5781. ctx.pageAllocs = VMA_NULL;
  5782. }
  5783. return true;
  5784. }
  5785. uint32_t VmaBlockBufferImageGranularity::OffsetToPageIndex(VkDeviceSize offset) const
  5786. {
  5787. return static_cast<uint32_t>(offset >> VMA_BITSCAN_MSB(m_BufferImageGranularity));
  5788. }
  5789. void VmaBlockBufferImageGranularity::AllocPage(RegionInfo& page, uint8_t allocType)
  5790. {
  5791. // When current alloc type is free then it can be overridden by new type
  5792. if (page.allocCount == 0 || (page.allocCount > 0 && page.allocType == VMA_SUBALLOCATION_TYPE_FREE))
  5793. page.allocType = allocType;
  5794. ++page.allocCount;
  5795. }
  5796. #endif // _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY_FUNCTIONS
  5797. #endif // _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY
  5798. #if 0
  5799. #ifndef _VMA_BLOCK_METADATA_GENERIC
  5800. class VmaBlockMetadata_Generic : public VmaBlockMetadata
  5801. {
  5802. friend class VmaDefragmentationAlgorithm_Generic;
  5803. friend class VmaDefragmentationAlgorithm_Fast;
  5804. VMA_CLASS_NO_COPY_NO_MOVE(VmaBlockMetadata_Generic)
  5805. public:
  5806. VmaBlockMetadata_Generic(const VkAllocationCallbacks* pAllocationCallbacks,
  5807. VkDeviceSize bufferImageGranularity, bool isVirtual);
  5808. virtual ~VmaBlockMetadata_Generic() = default;
  5809. size_t GetAllocationCount() const override { return m_Suballocations.size() - m_FreeCount; }
  5810. VkDeviceSize GetSumFreeSize() const override { return m_SumFreeSize; }
  5811. bool IsEmpty() const override { return (m_Suballocations.size() == 1) && (m_FreeCount == 1); }
  5812. void Free(VmaAllocHandle allocHandle) override { FreeSuballocation(FindAtOffset((VkDeviceSize)allocHandle - 1)); }
  5813. VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const override { return (VkDeviceSize)allocHandle - 1; }
  5814. void Init(VkDeviceSize size) override;
  5815. bool Validate() const override;
  5816. void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const override;
  5817. void AddStatistics(VmaStatistics& inoutStats) const override;
  5818. #if VMA_STATS_STRING_ENABLED
  5819. void PrintDetailedMap(class VmaJsonWriter& json, uint32_t mapRefCount) const override;
  5820. #endif
  5821. bool CreateAllocationRequest(
  5822. VkDeviceSize allocSize,
  5823. VkDeviceSize allocAlignment,
  5824. bool upperAddress,
  5825. VmaSuballocationType allocType,
  5826. uint32_t strategy,
  5827. VmaAllocationRequest* pAllocationRequest) override;
  5828. VkResult CheckCorruption(const void* pBlockData) override;
  5829. void Alloc(
  5830. const VmaAllocationRequest& request,
  5831. VmaSuballocationType type,
  5832. void* userData) override;
  5833. void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) override;
  5834. void* GetAllocationUserData(VmaAllocHandle allocHandle) const override;
  5835. VmaAllocHandle GetAllocationListBegin() const override;
  5836. VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const override;
  5837. void Clear() override;
  5838. void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) override;
  5839. void DebugLogAllAllocations() const override;
  5840. private:
  5841. uint32_t m_FreeCount;
  5842. VkDeviceSize m_SumFreeSize;
  5843. VmaSuballocationList m_Suballocations;
  5844. // Suballocations that are free. Sorted by size, ascending.
  5845. VmaVector<VmaSuballocationList::iterator, VmaStlAllocator<VmaSuballocationList::iterator>> m_FreeSuballocationsBySize;
  5846. VkDeviceSize AlignAllocationSize(VkDeviceSize size) const { return IsVirtual() ? size : VmaAlignUp(size, (VkDeviceSize)16); }
  5847. VmaSuballocationList::iterator FindAtOffset(VkDeviceSize offset) const;
  5848. bool ValidateFreeSuballocationList() const;
  5849. // Checks if requested suballocation with given parameters can be placed in given pFreeSuballocItem.
  5850. // If yes, fills pOffset and returns true. If no, returns false.
  5851. bool CheckAllocation(
  5852. VkDeviceSize allocSize,
  5853. VkDeviceSize allocAlignment,
  5854. VmaSuballocationType allocType,
  5855. VmaSuballocationList::const_iterator suballocItem,
  5856. VmaAllocHandle* pAllocHandle) const;
  5857. // Given free suballocation, it merges it with following one, which must also be free.
  5858. void MergeFreeWithNext(VmaSuballocationList::iterator item);
  5859. // Releases given suballocation, making it free.
  5860. // Merges it with adjacent free suballocations if applicable.
  5861. // Returns iterator to new free suballocation at this place.
  5862. VmaSuballocationList::iterator FreeSuballocation(VmaSuballocationList::iterator suballocItem);
  5863. // Given free suballocation, it inserts it into sorted list of
  5864. // m_FreeSuballocationsBySize if it is suitable.
  5865. void RegisterFreeSuballocation(VmaSuballocationList::iterator item);
  5866. // Given free suballocation, it removes it from sorted list of
  5867. // m_FreeSuballocationsBySize if it is suitable.
  5868. void UnregisterFreeSuballocation(VmaSuballocationList::iterator item);
  5869. };
  5870. #ifndef _VMA_BLOCK_METADATA_GENERIC_FUNCTIONS
  5871. VmaBlockMetadata_Generic::VmaBlockMetadata_Generic(const VkAllocationCallbacks* pAllocationCallbacks,
  5872. VkDeviceSize bufferImageGranularity, bool isVirtual)
  5873. : VmaBlockMetadata(pAllocationCallbacks, bufferImageGranularity, isVirtual),
  5874. m_FreeCount(0),
  5875. m_SumFreeSize(0),
  5876. m_Suballocations(VmaStlAllocator<VmaSuballocation>(pAllocationCallbacks)),
  5877. m_FreeSuballocationsBySize(VmaStlAllocator<VmaSuballocationList::iterator>(pAllocationCallbacks)) {}
  5878. void VmaBlockMetadata_Generic::Init(VkDeviceSize size)
  5879. {
  5880. VmaBlockMetadata::Init(size);
  5881. m_FreeCount = 1;
  5882. m_SumFreeSize = size;
  5883. VmaSuballocation suballoc = {};
  5884. suballoc.offset = 0;
  5885. suballoc.size = size;
  5886. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  5887. m_Suballocations.push_back(suballoc);
  5888. m_FreeSuballocationsBySize.push_back(m_Suballocations.begin());
  5889. }
  5890. bool VmaBlockMetadata_Generic::Validate() const
  5891. {
  5892. VMA_VALIDATE(!m_Suballocations.empty());
  5893. // Expected offset of new suballocation as calculated from previous ones.
  5894. VkDeviceSize calculatedOffset = 0;
  5895. // Expected number of free suballocations as calculated from traversing their list.
  5896. uint32_t calculatedFreeCount = 0;
  5897. // Expected sum size of free suballocations as calculated from traversing their list.
  5898. VkDeviceSize calculatedSumFreeSize = 0;
  5899. // Expected number of free suballocations that should be registered in
  5900. // m_FreeSuballocationsBySize calculated from traversing their list.
  5901. size_t freeSuballocationsToRegister = 0;
  5902. // True if previous visited suballocation was free.
  5903. bool prevFree = false;
  5904. const VkDeviceSize debugMargin = GetDebugMargin();
  5905. for (const auto& subAlloc : m_Suballocations)
  5906. {
  5907. // Actual offset of this suballocation doesn't match expected one.
  5908. VMA_VALIDATE(subAlloc.offset == calculatedOffset);
  5909. const bool currFree = (subAlloc.type == VMA_SUBALLOCATION_TYPE_FREE);
  5910. // Two adjacent free suballocations are invalid. They should be merged.
  5911. VMA_VALIDATE(!prevFree || !currFree);
  5912. VmaAllocation alloc = (VmaAllocation)subAlloc.userData;
  5913. if (!IsVirtual())
  5914. {
  5915. VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE));
  5916. }
  5917. if (currFree)
  5918. {
  5919. calculatedSumFreeSize += subAlloc.size;
  5920. ++calculatedFreeCount;
  5921. ++freeSuballocationsToRegister;
  5922. // Margin required between allocations - every free space must be at least that large.
  5923. VMA_VALIDATE(subAlloc.size >= debugMargin);
  5924. }
  5925. else
  5926. {
  5927. if (!IsVirtual())
  5928. {
  5929. VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == subAlloc.offset + 1);
  5930. VMA_VALIDATE(alloc->GetSize() == subAlloc.size);
  5931. }
  5932. // Margin required between allocations - previous allocation must be free.
  5933. VMA_VALIDATE(debugMargin == 0 || prevFree);
  5934. }
  5935. calculatedOffset += subAlloc.size;
  5936. prevFree = currFree;
  5937. }
  5938. // Number of free suballocations registered in m_FreeSuballocationsBySize doesn't
  5939. // match expected one.
  5940. VMA_VALIDATE(m_FreeSuballocationsBySize.size() == freeSuballocationsToRegister);
  5941. VkDeviceSize lastSize = 0;
  5942. for (size_t i = 0; i < m_FreeSuballocationsBySize.size(); ++i)
  5943. {
  5944. VmaSuballocationList::iterator suballocItem = m_FreeSuballocationsBySize[i];
  5945. // Only free suballocations can be registered in m_FreeSuballocationsBySize.
  5946. VMA_VALIDATE(suballocItem->type == VMA_SUBALLOCATION_TYPE_FREE);
  5947. // They must be sorted by size ascending.
  5948. VMA_VALIDATE(suballocItem->size >= lastSize);
  5949. lastSize = suballocItem->size;
  5950. }
  5951. // Check if totals match calculated values.
  5952. VMA_VALIDATE(ValidateFreeSuballocationList());
  5953. VMA_VALIDATE(calculatedOffset == GetSize());
  5954. VMA_VALIDATE(calculatedSumFreeSize == m_SumFreeSize);
  5955. VMA_VALIDATE(calculatedFreeCount == m_FreeCount);
  5956. return true;
  5957. }
  5958. void VmaBlockMetadata_Generic::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const
  5959. {
  5960. const uint32_t rangeCount = (uint32_t)m_Suballocations.size();
  5961. inoutStats.statistics.blockCount++;
  5962. inoutStats.statistics.blockBytes += GetSize();
  5963. for (const auto& suballoc : m_Suballocations)
  5964. {
  5965. if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  5966. VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size);
  5967. else
  5968. VmaAddDetailedStatisticsUnusedRange(inoutStats, suballoc.size);
  5969. }
  5970. }
  5971. void VmaBlockMetadata_Generic::AddStatistics(VmaStatistics& inoutStats) const
  5972. {
  5973. inoutStats.blockCount++;
  5974. inoutStats.allocationCount += (uint32_t)m_Suballocations.size() - m_FreeCount;
  5975. inoutStats.blockBytes += GetSize();
  5976. inoutStats.allocationBytes += GetSize() - m_SumFreeSize;
  5977. }
  5978. #if VMA_STATS_STRING_ENABLED
  5979. void VmaBlockMetadata_Generic::PrintDetailedMap(class VmaJsonWriter& json, uint32_t mapRefCount) const
  5980. {
  5981. PrintDetailedMap_Begin(json,
  5982. m_SumFreeSize, // unusedBytes
  5983. m_Suballocations.size() - (size_t)m_FreeCount, // allocationCount
  5984. m_FreeCount, // unusedRangeCount
  5985. mapRefCount);
  5986. for (const auto& suballoc : m_Suballocations)
  5987. {
  5988. if (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE)
  5989. {
  5990. PrintDetailedMap_UnusedRange(json, suballoc.offset, suballoc.size);
  5991. }
  5992. else
  5993. {
  5994. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData);
  5995. }
  5996. }
  5997. PrintDetailedMap_End(json);
  5998. }
  5999. #endif // VMA_STATS_STRING_ENABLED
  6000. bool VmaBlockMetadata_Generic::CreateAllocationRequest(
  6001. VkDeviceSize allocSize,
  6002. VkDeviceSize allocAlignment,
  6003. bool upperAddress,
  6004. VmaSuballocationType allocType,
  6005. uint32_t strategy,
  6006. VmaAllocationRequest* pAllocationRequest)
  6007. {
  6008. VMA_ASSERT(allocSize > 0);
  6009. VMA_ASSERT(!upperAddress);
  6010. VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
  6011. VMA_ASSERT(pAllocationRequest != VMA_NULL);
  6012. VMA_HEAVY_ASSERT(Validate());
  6013. allocSize = AlignAllocationSize(allocSize);
  6014. pAllocationRequest->type = VmaAllocationRequestType::Normal;
  6015. pAllocationRequest->size = allocSize;
  6016. const VkDeviceSize debugMargin = GetDebugMargin();
  6017. // There is not enough total free space in this block to fulfill the request: Early return.
  6018. if (m_SumFreeSize < allocSize + debugMargin)
  6019. {
  6020. return false;
  6021. }
  6022. // New algorithm, efficiently searching freeSuballocationsBySize.
  6023. const size_t freeSuballocCount = m_FreeSuballocationsBySize.size();
  6024. if (freeSuballocCount > 0)
  6025. {
  6026. if (strategy == 0 ||
  6027. strategy == VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT)
  6028. {
  6029. // Find first free suballocation with size not less than allocSize + debugMargin.
  6030. VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess(
  6031. m_FreeSuballocationsBySize.data(),
  6032. m_FreeSuballocationsBySize.data() + freeSuballocCount,
  6033. allocSize + debugMargin,
  6034. VmaSuballocationItemSizeLess());
  6035. size_t index = it - m_FreeSuballocationsBySize.data();
  6036. for (; index < freeSuballocCount; ++index)
  6037. {
  6038. if (CheckAllocation(
  6039. allocSize,
  6040. allocAlignment,
  6041. allocType,
  6042. m_FreeSuballocationsBySize[index],
  6043. &pAllocationRequest->allocHandle))
  6044. {
  6045. pAllocationRequest->item = m_FreeSuballocationsBySize[index];
  6046. return true;
  6047. }
  6048. }
  6049. }
  6050. else if (strategy == VMA_ALLOCATION_INTERNAL_STRATEGY_MIN_OFFSET)
  6051. {
  6052. for (VmaSuballocationList::iterator it = m_Suballocations.begin();
  6053. it != m_Suballocations.end();
  6054. ++it)
  6055. {
  6056. if (it->type == VMA_SUBALLOCATION_TYPE_FREE && CheckAllocation(
  6057. allocSize,
  6058. allocAlignment,
  6059. allocType,
  6060. it,
  6061. &pAllocationRequest->allocHandle))
  6062. {
  6063. pAllocationRequest->item = it;
  6064. return true;
  6065. }
  6066. }
  6067. }
  6068. else
  6069. {
  6070. VMA_ASSERT(strategy & (VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT | VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT ));
  6071. // Search staring from biggest suballocations.
  6072. for (size_t index = freeSuballocCount; index--; )
  6073. {
  6074. if (CheckAllocation(
  6075. allocSize,
  6076. allocAlignment,
  6077. allocType,
  6078. m_FreeSuballocationsBySize[index],
  6079. &pAllocationRequest->allocHandle))
  6080. {
  6081. pAllocationRequest->item = m_FreeSuballocationsBySize[index];
  6082. return true;
  6083. }
  6084. }
  6085. }
  6086. }
  6087. return false;
  6088. }
  6089. VkResult VmaBlockMetadata_Generic::CheckCorruption(const void* pBlockData)
  6090. {
  6091. for (auto& suballoc : m_Suballocations)
  6092. {
  6093. if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  6094. {
  6095. if (!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size))
  6096. {
  6097. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
  6098. return VK_ERROR_UNKNOWN_COPY;
  6099. }
  6100. }
  6101. }
  6102. return VK_SUCCESS;
  6103. }
  6104. void VmaBlockMetadata_Generic::Alloc(
  6105. const VmaAllocationRequest& request,
  6106. VmaSuballocationType type,
  6107. void* userData)
  6108. {
  6109. VMA_ASSERT(request.type == VmaAllocationRequestType::Normal);
  6110. VMA_ASSERT(request.item != m_Suballocations.end());
  6111. VmaSuballocation& suballoc = *request.item;
  6112. // Given suballocation is a free block.
  6113. VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  6114. // Given offset is inside this suballocation.
  6115. VMA_ASSERT((VkDeviceSize)request.allocHandle - 1 >= suballoc.offset);
  6116. const VkDeviceSize paddingBegin = (VkDeviceSize)request.allocHandle - suballoc.offset - 1;
  6117. VMA_ASSERT(suballoc.size >= paddingBegin + request.size);
  6118. const VkDeviceSize paddingEnd = suballoc.size - paddingBegin - request.size;
  6119. // Unregister this free suballocation from m_FreeSuballocationsBySize and update
  6120. // it to become used.
  6121. UnregisterFreeSuballocation(request.item);
  6122. suballoc.offset = (VkDeviceSize)request.allocHandle - 1;
  6123. suballoc.size = request.size;
  6124. suballoc.type = type;
  6125. suballoc.userData = userData;
  6126. // If there are any free bytes remaining at the end, insert new free suballocation after current one.
  6127. if (paddingEnd)
  6128. {
  6129. VmaSuballocation paddingSuballoc = {};
  6130. paddingSuballoc.offset = suballoc.offset + suballoc.size;
  6131. paddingSuballoc.size = paddingEnd;
  6132. paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  6133. VmaSuballocationList::iterator next = request.item;
  6134. ++next;
  6135. const VmaSuballocationList::iterator paddingEndItem =
  6136. m_Suballocations.insert(next, paddingSuballoc);
  6137. RegisterFreeSuballocation(paddingEndItem);
  6138. }
  6139. // If there are any free bytes remaining at the beginning, insert new free suballocation before current one.
  6140. if (paddingBegin)
  6141. {
  6142. VmaSuballocation paddingSuballoc = {};
  6143. paddingSuballoc.offset = suballoc.offset - paddingBegin;
  6144. paddingSuballoc.size = paddingBegin;
  6145. paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  6146. const VmaSuballocationList::iterator paddingBeginItem =
  6147. m_Suballocations.insert(request.item, paddingSuballoc);
  6148. RegisterFreeSuballocation(paddingBeginItem);
  6149. }
  6150. // Update totals.
  6151. m_FreeCount = m_FreeCount - 1;
  6152. if (paddingBegin > 0)
  6153. {
  6154. ++m_FreeCount;
  6155. }
  6156. if (paddingEnd > 0)
  6157. {
  6158. ++m_FreeCount;
  6159. }
  6160. m_SumFreeSize -= request.size;
  6161. }
  6162. void VmaBlockMetadata_Generic::GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo)
  6163. {
  6164. outInfo.offset = (VkDeviceSize)allocHandle - 1;
  6165. const VmaSuballocation& suballoc = *FindAtOffset(outInfo.offset);
  6166. outInfo.size = suballoc.size;
  6167. outInfo.pUserData = suballoc.userData;
  6168. }
  6169. void* VmaBlockMetadata_Generic::GetAllocationUserData(VmaAllocHandle allocHandle) const
  6170. {
  6171. return FindAtOffset((VkDeviceSize)allocHandle - 1)->userData;
  6172. }
  6173. VmaAllocHandle VmaBlockMetadata_Generic::GetAllocationListBegin() const
  6174. {
  6175. if (IsEmpty())
  6176. return VK_NULL_HANDLE;
  6177. for (const auto& suballoc : m_Suballocations)
  6178. {
  6179. if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  6180. return (VmaAllocHandle)(suballoc.offset + 1);
  6181. }
  6182. VMA_ASSERT(false && "Should contain at least 1 allocation!");
  6183. return VK_NULL_HANDLE;
  6184. }
  6185. VmaAllocHandle VmaBlockMetadata_Generic::GetNextAllocation(VmaAllocHandle prevAlloc) const
  6186. {
  6187. VmaSuballocationList::const_iterator prev = FindAtOffset((VkDeviceSize)prevAlloc - 1);
  6188. for (VmaSuballocationList::const_iterator it = ++prev; it != m_Suballocations.end(); ++it)
  6189. {
  6190. if (it->type != VMA_SUBALLOCATION_TYPE_FREE)
  6191. return (VmaAllocHandle)(it->offset + 1);
  6192. }
  6193. return VK_NULL_HANDLE;
  6194. }
  6195. void VmaBlockMetadata_Generic::Clear()
  6196. {
  6197. const VkDeviceSize size = GetSize();
  6198. VMA_ASSERT(IsVirtual());
  6199. m_FreeCount = 1;
  6200. m_SumFreeSize = size;
  6201. m_Suballocations.clear();
  6202. m_FreeSuballocationsBySize.clear();
  6203. VmaSuballocation suballoc = {};
  6204. suballoc.offset = 0;
  6205. suballoc.size = size;
  6206. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  6207. m_Suballocations.push_back(suballoc);
  6208. m_FreeSuballocationsBySize.push_back(m_Suballocations.begin());
  6209. }
  6210. void VmaBlockMetadata_Generic::SetAllocationUserData(VmaAllocHandle allocHandle, void* userData)
  6211. {
  6212. VmaSuballocation& suballoc = *FindAtOffset((VkDeviceSize)allocHandle - 1);
  6213. suballoc.userData = userData;
  6214. }
  6215. void VmaBlockMetadata_Generic::DebugLogAllAllocations() const
  6216. {
  6217. for (const auto& suballoc : m_Suballocations)
  6218. {
  6219. if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  6220. DebugLogAllocation(suballoc.offset, suballoc.size, suballoc.userData);
  6221. }
  6222. }
  6223. VmaSuballocationList::iterator VmaBlockMetadata_Generic::FindAtOffset(VkDeviceSize offset) const
  6224. {
  6225. VMA_HEAVY_ASSERT(!m_Suballocations.empty());
  6226. const VkDeviceSize last = m_Suballocations.rbegin()->offset;
  6227. if (last == offset)
  6228. return m_Suballocations.rbegin().drop_const();
  6229. const VkDeviceSize first = m_Suballocations.begin()->offset;
  6230. if (first == offset)
  6231. return m_Suballocations.begin().drop_const();
  6232. const size_t suballocCount = m_Suballocations.size();
  6233. const VkDeviceSize step = (last - first + m_Suballocations.begin()->size) / suballocCount;
  6234. auto findSuballocation = [&](auto begin, auto end) -> VmaSuballocationList::iterator
  6235. {
  6236. for (auto suballocItem = begin;
  6237. suballocItem != end;
  6238. ++suballocItem)
  6239. {
  6240. if (suballocItem->offset == offset)
  6241. return suballocItem.drop_const();
  6242. }
  6243. VMA_ASSERT(false && "Not found!");
  6244. return m_Suballocations.end().drop_const();
  6245. };
  6246. // If requested offset is closer to the end of range, search from the end
  6247. if (offset - first > suballocCount * step / 2)
  6248. {
  6249. return findSuballocation(m_Suballocations.rbegin(), m_Suballocations.rend());
  6250. }
  6251. return findSuballocation(m_Suballocations.begin(), m_Suballocations.end());
  6252. }
  6253. bool VmaBlockMetadata_Generic::ValidateFreeSuballocationList() const
  6254. {
  6255. VkDeviceSize lastSize = 0;
  6256. for (size_t i = 0, count = m_FreeSuballocationsBySize.size(); i < count; ++i)
  6257. {
  6258. const VmaSuballocationList::iterator it = m_FreeSuballocationsBySize[i];
  6259. VMA_VALIDATE(it->type == VMA_SUBALLOCATION_TYPE_FREE);
  6260. VMA_VALIDATE(it->size >= lastSize);
  6261. lastSize = it->size;
  6262. }
  6263. return true;
  6264. }
  6265. bool VmaBlockMetadata_Generic::CheckAllocation(
  6266. VkDeviceSize allocSize,
  6267. VkDeviceSize allocAlignment,
  6268. VmaSuballocationType allocType,
  6269. VmaSuballocationList::const_iterator suballocItem,
  6270. VmaAllocHandle* pAllocHandle) const
  6271. {
  6272. VMA_ASSERT(allocSize > 0);
  6273. VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
  6274. VMA_ASSERT(suballocItem != m_Suballocations.cend());
  6275. VMA_ASSERT(pAllocHandle != VMA_NULL);
  6276. const VkDeviceSize debugMargin = GetDebugMargin();
  6277. const VkDeviceSize bufferImageGranularity = GetBufferImageGranularity();
  6278. const VmaSuballocation& suballoc = *suballocItem;
  6279. VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  6280. // Size of this suballocation is too small for this request: Early return.
  6281. if (suballoc.size < allocSize)
  6282. {
  6283. return false;
  6284. }
  6285. // Start from offset equal to beginning of this suballocation.
  6286. VkDeviceSize offset = suballoc.offset + (suballocItem == m_Suballocations.cbegin() ? 0 : GetDebugMargin());
  6287. // Apply debugMargin from the end of previous alloc.
  6288. if (debugMargin > 0)
  6289. {
  6290. offset += debugMargin;
  6291. }
  6292. // Apply alignment.
  6293. offset = VmaAlignUp(offset, allocAlignment);
  6294. // Check previous suballocations for BufferImageGranularity conflicts.
  6295. // Make bigger alignment if necessary.
  6296. if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment)
  6297. {
  6298. bool bufferImageGranularityConflict = false;
  6299. VmaSuballocationList::const_iterator prevSuballocItem = suballocItem;
  6300. while (prevSuballocItem != m_Suballocations.cbegin())
  6301. {
  6302. --prevSuballocItem;
  6303. const VmaSuballocation& prevSuballoc = *prevSuballocItem;
  6304. if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, offset, bufferImageGranularity))
  6305. {
  6306. if (VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
  6307. {
  6308. bufferImageGranularityConflict = true;
  6309. break;
  6310. }
  6311. }
  6312. else
  6313. // Already on previous page.
  6314. break;
  6315. }
  6316. if (bufferImageGranularityConflict)
  6317. {
  6318. offset = VmaAlignUp(offset, bufferImageGranularity);
  6319. }
  6320. }
  6321. // Calculate padding at the beginning based on current offset.
  6322. const VkDeviceSize paddingBegin = offset - suballoc.offset;
  6323. // Fail if requested size plus margin after is bigger than size of this suballocation.
  6324. if (paddingBegin + allocSize + debugMargin > suballoc.size)
  6325. {
  6326. return false;
  6327. }
  6328. // Check next suballocations for BufferImageGranularity conflicts.
  6329. // If conflict exists, allocation cannot be made here.
  6330. if (allocSize % bufferImageGranularity || offset % bufferImageGranularity)
  6331. {
  6332. VmaSuballocationList::const_iterator nextSuballocItem = suballocItem;
  6333. ++nextSuballocItem;
  6334. while (nextSuballocItem != m_Suballocations.cend())
  6335. {
  6336. const VmaSuballocation& nextSuballoc = *nextSuballocItem;
  6337. if (VmaBlocksOnSamePage(offset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  6338. {
  6339. if (VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
  6340. {
  6341. return false;
  6342. }
  6343. }
  6344. else
  6345. {
  6346. // Already on next page.
  6347. break;
  6348. }
  6349. ++nextSuballocItem;
  6350. }
  6351. }
  6352. *pAllocHandle = (VmaAllocHandle)(offset + 1);
  6353. // All tests passed: Success. pAllocHandle is already filled.
  6354. return true;
  6355. }
  6356. void VmaBlockMetadata_Generic::MergeFreeWithNext(VmaSuballocationList::iterator item)
  6357. {
  6358. VMA_ASSERT(item != m_Suballocations.end());
  6359. VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
  6360. VmaSuballocationList::iterator nextItem = item;
  6361. ++nextItem;
  6362. VMA_ASSERT(nextItem != m_Suballocations.end());
  6363. VMA_ASSERT(nextItem->type == VMA_SUBALLOCATION_TYPE_FREE);
  6364. item->size += nextItem->size;
  6365. --m_FreeCount;
  6366. m_Suballocations.erase(nextItem);
  6367. }
  6368. VmaSuballocationList::iterator VmaBlockMetadata_Generic::FreeSuballocation(VmaSuballocationList::iterator suballocItem)
  6369. {
  6370. // Change this suballocation to be marked as free.
  6371. VmaSuballocation& suballoc = *suballocItem;
  6372. suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  6373. suballoc.userData = VMA_NULL;
  6374. // Update totals.
  6375. ++m_FreeCount;
  6376. m_SumFreeSize += suballoc.size;
  6377. // Merge with previous and/or next suballocation if it's also free.
  6378. bool mergeWithNext = false;
  6379. bool mergeWithPrev = false;
  6380. VmaSuballocationList::iterator nextItem = suballocItem;
  6381. ++nextItem;
  6382. if ((nextItem != m_Suballocations.end()) && (nextItem->type == VMA_SUBALLOCATION_TYPE_FREE))
  6383. {
  6384. mergeWithNext = true;
  6385. }
  6386. VmaSuballocationList::iterator prevItem = suballocItem;
  6387. if (suballocItem != m_Suballocations.begin())
  6388. {
  6389. --prevItem;
  6390. if (prevItem->type == VMA_SUBALLOCATION_TYPE_FREE)
  6391. {
  6392. mergeWithPrev = true;
  6393. }
  6394. }
  6395. if (mergeWithNext)
  6396. {
  6397. UnregisterFreeSuballocation(nextItem);
  6398. MergeFreeWithNext(suballocItem);
  6399. }
  6400. if (mergeWithPrev)
  6401. {
  6402. UnregisterFreeSuballocation(prevItem);
  6403. MergeFreeWithNext(prevItem);
  6404. RegisterFreeSuballocation(prevItem);
  6405. return prevItem;
  6406. }
  6407. else
  6408. {
  6409. RegisterFreeSuballocation(suballocItem);
  6410. return suballocItem;
  6411. }
  6412. }
  6413. void VmaBlockMetadata_Generic::RegisterFreeSuballocation(VmaSuballocationList::iterator item)
  6414. {
  6415. VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
  6416. VMA_ASSERT(item->size > 0);
  6417. // You may want to enable this validation at the beginning or at the end of
  6418. // this function, depending on what do you want to check.
  6419. VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  6420. if (m_FreeSuballocationsBySize.empty())
  6421. {
  6422. m_FreeSuballocationsBySize.push_back(item);
  6423. }
  6424. else
  6425. {
  6426. VmaVectorInsertSorted<VmaSuballocationItemSizeLess>(m_FreeSuballocationsBySize, item);
  6427. }
  6428. //VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  6429. }
  6430. void VmaBlockMetadata_Generic::UnregisterFreeSuballocation(VmaSuballocationList::iterator item)
  6431. {
  6432. VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
  6433. VMA_ASSERT(item->size > 0);
  6434. // You may want to enable this validation at the beginning or at the end of
  6435. // this function, depending on what do you want to check.
  6436. VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  6437. VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess(
  6438. m_FreeSuballocationsBySize.data(),
  6439. m_FreeSuballocationsBySize.data() + m_FreeSuballocationsBySize.size(),
  6440. item,
  6441. VmaSuballocationItemSizeLess());
  6442. for (size_t index = it - m_FreeSuballocationsBySize.data();
  6443. index < m_FreeSuballocationsBySize.size();
  6444. ++index)
  6445. {
  6446. if (m_FreeSuballocationsBySize[index] == item)
  6447. {
  6448. VmaVectorRemove(m_FreeSuballocationsBySize, index);
  6449. return;
  6450. }
  6451. VMA_ASSERT((m_FreeSuballocationsBySize[index]->size == item->size) && "Not found.");
  6452. }
  6453. VMA_ASSERT(0 && "Not found.");
  6454. //VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
  6455. }
  6456. #endif // _VMA_BLOCK_METADATA_GENERIC_FUNCTIONS
  6457. #endif // _VMA_BLOCK_METADATA_GENERIC
  6458. #endif // #if 0
  6459. #ifndef _VMA_BLOCK_METADATA_LINEAR
  6460. /*
  6461. Allocations and their references in internal data structure look like this:
  6462. if(m_2ndVectorMode == SECOND_VECTOR_EMPTY):
  6463. 0 +-------+
  6464. | |
  6465. | |
  6466. | |
  6467. +-------+
  6468. | Alloc | 1st[m_1stNullItemsBeginCount]
  6469. +-------+
  6470. | Alloc | 1st[m_1stNullItemsBeginCount + 1]
  6471. +-------+
  6472. | ... |
  6473. +-------+
  6474. | Alloc | 1st[1st.size() - 1]
  6475. +-------+
  6476. | |
  6477. | |
  6478. | |
  6479. GetSize() +-------+
  6480. if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER):
  6481. 0 +-------+
  6482. | Alloc | 2nd[0]
  6483. +-------+
  6484. | Alloc | 2nd[1]
  6485. +-------+
  6486. | ... |
  6487. +-------+
  6488. | Alloc | 2nd[2nd.size() - 1]
  6489. +-------+
  6490. | |
  6491. | |
  6492. | |
  6493. +-------+
  6494. | Alloc | 1st[m_1stNullItemsBeginCount]
  6495. +-------+
  6496. | Alloc | 1st[m_1stNullItemsBeginCount + 1]
  6497. +-------+
  6498. | ... |
  6499. +-------+
  6500. | Alloc | 1st[1st.size() - 1]
  6501. +-------+
  6502. | |
  6503. GetSize() +-------+
  6504. if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK):
  6505. 0 +-------+
  6506. | |
  6507. | |
  6508. | |
  6509. +-------+
  6510. | Alloc | 1st[m_1stNullItemsBeginCount]
  6511. +-------+
  6512. | Alloc | 1st[m_1stNullItemsBeginCount + 1]
  6513. +-------+
  6514. | ... |
  6515. +-------+
  6516. | Alloc | 1st[1st.size() - 1]
  6517. +-------+
  6518. | |
  6519. | |
  6520. | |
  6521. +-------+
  6522. | Alloc | 2nd[2nd.size() - 1]
  6523. +-------+
  6524. | ... |
  6525. +-------+
  6526. | Alloc | 2nd[1]
  6527. +-------+
  6528. | Alloc | 2nd[0]
  6529. GetSize() +-------+
  6530. */
  6531. class VmaBlockMetadata_Linear : public VmaBlockMetadata
  6532. {
  6533. VMA_CLASS_NO_COPY_NO_MOVE(VmaBlockMetadata_Linear)
  6534. public:
  6535. VmaBlockMetadata_Linear(const VkAllocationCallbacks* pAllocationCallbacks,
  6536. VkDeviceSize bufferImageGranularity, bool isVirtual);
  6537. virtual ~VmaBlockMetadata_Linear() = default;
  6538. VkDeviceSize GetSumFreeSize() const override { return m_SumFreeSize; }
  6539. bool IsEmpty() const override { return GetAllocationCount() == 0; }
  6540. VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const override { return (VkDeviceSize)allocHandle - 1; }
  6541. void Init(VkDeviceSize size) override;
  6542. bool Validate() const override;
  6543. size_t GetAllocationCount() const override;
  6544. size_t GetFreeRegionsCount() const override;
  6545. void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const override;
  6546. void AddStatistics(VmaStatistics& inoutStats) const override;
  6547. #if VMA_STATS_STRING_ENABLED
  6548. void PrintDetailedMap(class VmaJsonWriter& json) const override;
  6549. #endif
  6550. bool CreateAllocationRequest(
  6551. VkDeviceSize allocSize,
  6552. VkDeviceSize allocAlignment,
  6553. bool upperAddress,
  6554. VmaSuballocationType allocType,
  6555. uint32_t strategy,
  6556. VmaAllocationRequest* pAllocationRequest) override;
  6557. VkResult CheckCorruption(const void* pBlockData) override;
  6558. void Alloc(
  6559. const VmaAllocationRequest& request,
  6560. VmaSuballocationType type,
  6561. void* userData) override;
  6562. void Free(VmaAllocHandle allocHandle) override;
  6563. void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) override;
  6564. void* GetAllocationUserData(VmaAllocHandle allocHandle) const override;
  6565. VmaAllocHandle GetAllocationListBegin() const override;
  6566. VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const override;
  6567. VkDeviceSize GetNextFreeRegionSize(VmaAllocHandle alloc) const override;
  6568. void Clear() override;
  6569. void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) override;
  6570. void DebugLogAllAllocations() const override;
  6571. private:
  6572. /*
  6573. There are two suballocation vectors, used in ping-pong way.
  6574. The one with index m_1stVectorIndex is called 1st.
  6575. The one with index (m_1stVectorIndex ^ 1) is called 2nd.
  6576. 2nd can be non-empty only when 1st is not empty.
  6577. When 2nd is not empty, m_2ndVectorMode indicates its mode of operation.
  6578. */
  6579. typedef VmaVector<VmaSuballocation, VmaStlAllocator<VmaSuballocation>> SuballocationVectorType;
  6580. enum SECOND_VECTOR_MODE
  6581. {
  6582. SECOND_VECTOR_EMPTY,
  6583. /*
  6584. Suballocations in 2nd vector are created later than the ones in 1st, but they
  6585. all have smaller offset.
  6586. */
  6587. SECOND_VECTOR_RING_BUFFER,
  6588. /*
  6589. Suballocations in 2nd vector are upper side of double stack.
  6590. They all have offsets higher than those in 1st vector.
  6591. Top of this stack means smaller offsets, but higher indices in this vector.
  6592. */
  6593. SECOND_VECTOR_DOUBLE_STACK,
  6594. };
  6595. VkDeviceSize m_SumFreeSize;
  6596. SuballocationVectorType m_Suballocations0, m_Suballocations1;
  6597. uint32_t m_1stVectorIndex;
  6598. SECOND_VECTOR_MODE m_2ndVectorMode;
  6599. // Number of items in 1st vector with hAllocation = null at the beginning.
  6600. size_t m_1stNullItemsBeginCount;
  6601. // Number of other items in 1st vector with hAllocation = null somewhere in the middle.
  6602. size_t m_1stNullItemsMiddleCount;
  6603. // Number of items in 2nd vector with hAllocation = null.
  6604. size_t m_2ndNullItemsCount;
  6605. SuballocationVectorType& AccessSuballocations1st() { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; }
  6606. SuballocationVectorType& AccessSuballocations2nd() { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; }
  6607. const SuballocationVectorType& AccessSuballocations1st() const { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; }
  6608. const SuballocationVectorType& AccessSuballocations2nd() const { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; }
  6609. VmaSuballocation& FindSuballocation(VkDeviceSize offset) const;
  6610. bool ShouldCompact1st() const;
  6611. void CleanupAfterFree();
  6612. bool CreateAllocationRequest_LowerAddress(
  6613. VkDeviceSize allocSize,
  6614. VkDeviceSize allocAlignment,
  6615. VmaSuballocationType allocType,
  6616. uint32_t strategy,
  6617. VmaAllocationRequest* pAllocationRequest);
  6618. bool CreateAllocationRequest_UpperAddress(
  6619. VkDeviceSize allocSize,
  6620. VkDeviceSize allocAlignment,
  6621. VmaSuballocationType allocType,
  6622. uint32_t strategy,
  6623. VmaAllocationRequest* pAllocationRequest);
  6624. };
  6625. #ifndef _VMA_BLOCK_METADATA_LINEAR_FUNCTIONS
  6626. VmaBlockMetadata_Linear::VmaBlockMetadata_Linear(const VkAllocationCallbacks* pAllocationCallbacks,
  6627. VkDeviceSize bufferImageGranularity, bool isVirtual)
  6628. : VmaBlockMetadata(pAllocationCallbacks, bufferImageGranularity, isVirtual),
  6629. m_SumFreeSize(0),
  6630. m_Suballocations0(VmaStlAllocator<VmaSuballocation>(pAllocationCallbacks)),
  6631. m_Suballocations1(VmaStlAllocator<VmaSuballocation>(pAllocationCallbacks)),
  6632. m_1stVectorIndex(0),
  6633. m_2ndVectorMode(SECOND_VECTOR_EMPTY),
  6634. m_1stNullItemsBeginCount(0),
  6635. m_1stNullItemsMiddleCount(0),
  6636. m_2ndNullItemsCount(0) {}
  6637. void VmaBlockMetadata_Linear::Init(VkDeviceSize size)
  6638. {
  6639. VmaBlockMetadata::Init(size);
  6640. m_SumFreeSize = size;
  6641. }
  6642. bool VmaBlockMetadata_Linear::Validate() const
  6643. {
  6644. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  6645. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  6646. VMA_VALIDATE(suballocations2nd.empty() == (m_2ndVectorMode == SECOND_VECTOR_EMPTY));
  6647. VMA_VALIDATE(!suballocations1st.empty() ||
  6648. suballocations2nd.empty() ||
  6649. m_2ndVectorMode != SECOND_VECTOR_RING_BUFFER);
  6650. if (!suballocations1st.empty())
  6651. {
  6652. // Null item at the beginning should be accounted into m_1stNullItemsBeginCount.
  6653. VMA_VALIDATE(suballocations1st[m_1stNullItemsBeginCount].type != VMA_SUBALLOCATION_TYPE_FREE);
  6654. // Null item at the end should be just pop_back().
  6655. VMA_VALIDATE(suballocations1st.back().type != VMA_SUBALLOCATION_TYPE_FREE);
  6656. }
  6657. if (!suballocations2nd.empty())
  6658. {
  6659. // Null item at the end should be just pop_back().
  6660. VMA_VALIDATE(suballocations2nd.back().type != VMA_SUBALLOCATION_TYPE_FREE);
  6661. }
  6662. VMA_VALIDATE(m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount <= suballocations1st.size());
  6663. VMA_VALIDATE(m_2ndNullItemsCount <= suballocations2nd.size());
  6664. VkDeviceSize sumUsedSize = 0;
  6665. const size_t suballoc1stCount = suballocations1st.size();
  6666. const VkDeviceSize debugMargin = GetDebugMargin();
  6667. VkDeviceSize offset = 0;
  6668. if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  6669. {
  6670. const size_t suballoc2ndCount = suballocations2nd.size();
  6671. size_t nullItem2ndCount = 0;
  6672. for (size_t i = 0; i < suballoc2ndCount; ++i)
  6673. {
  6674. const VmaSuballocation& suballoc = suballocations2nd[i];
  6675. const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  6676. VmaAllocation const alloc = (VmaAllocation)suballoc.userData;
  6677. if (!IsVirtual())
  6678. {
  6679. VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE));
  6680. }
  6681. VMA_VALIDATE(suballoc.offset >= offset);
  6682. if (!currFree)
  6683. {
  6684. if (!IsVirtual())
  6685. {
  6686. VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == suballoc.offset + 1);
  6687. VMA_VALIDATE(alloc->GetSize() == suballoc.size);
  6688. }
  6689. sumUsedSize += suballoc.size;
  6690. }
  6691. else
  6692. {
  6693. ++nullItem2ndCount;
  6694. }
  6695. offset = suballoc.offset + suballoc.size + debugMargin;
  6696. }
  6697. VMA_VALIDATE(nullItem2ndCount == m_2ndNullItemsCount);
  6698. }
  6699. for (size_t i = 0; i < m_1stNullItemsBeginCount; ++i)
  6700. {
  6701. const VmaSuballocation& suballoc = suballocations1st[i];
  6702. VMA_VALIDATE(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE &&
  6703. suballoc.userData == VMA_NULL);
  6704. }
  6705. size_t nullItem1stCount = m_1stNullItemsBeginCount;
  6706. for (size_t i = m_1stNullItemsBeginCount; i < suballoc1stCount; ++i)
  6707. {
  6708. const VmaSuballocation& suballoc = suballocations1st[i];
  6709. const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  6710. VmaAllocation const alloc = (VmaAllocation)suballoc.userData;
  6711. if (!IsVirtual())
  6712. {
  6713. VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE));
  6714. }
  6715. VMA_VALIDATE(suballoc.offset >= offset);
  6716. VMA_VALIDATE(i >= m_1stNullItemsBeginCount || currFree);
  6717. if (!currFree)
  6718. {
  6719. if (!IsVirtual())
  6720. {
  6721. VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == suballoc.offset + 1);
  6722. VMA_VALIDATE(alloc->GetSize() == suballoc.size);
  6723. }
  6724. sumUsedSize += suballoc.size;
  6725. }
  6726. else
  6727. {
  6728. ++nullItem1stCount;
  6729. }
  6730. offset = suballoc.offset + suballoc.size + debugMargin;
  6731. }
  6732. VMA_VALIDATE(nullItem1stCount == m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount);
  6733. if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  6734. {
  6735. const size_t suballoc2ndCount = suballocations2nd.size();
  6736. size_t nullItem2ndCount = 0;
  6737. for (size_t i = suballoc2ndCount; i--; )
  6738. {
  6739. const VmaSuballocation& suballoc = suballocations2nd[i];
  6740. const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
  6741. VmaAllocation const alloc = (VmaAllocation)suballoc.userData;
  6742. if (!IsVirtual())
  6743. {
  6744. VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE));
  6745. }
  6746. VMA_VALIDATE(suballoc.offset >= offset);
  6747. if (!currFree)
  6748. {
  6749. if (!IsVirtual())
  6750. {
  6751. VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == suballoc.offset + 1);
  6752. VMA_VALIDATE(alloc->GetSize() == suballoc.size);
  6753. }
  6754. sumUsedSize += suballoc.size;
  6755. }
  6756. else
  6757. {
  6758. ++nullItem2ndCount;
  6759. }
  6760. offset = suballoc.offset + suballoc.size + debugMargin;
  6761. }
  6762. VMA_VALIDATE(nullItem2ndCount == m_2ndNullItemsCount);
  6763. }
  6764. VMA_VALIDATE(offset <= GetSize());
  6765. VMA_VALIDATE(m_SumFreeSize == GetSize() - sumUsedSize);
  6766. return true;
  6767. }
  6768. size_t VmaBlockMetadata_Linear::GetAllocationCount() const
  6769. {
  6770. return AccessSuballocations1st().size() - m_1stNullItemsBeginCount - m_1stNullItemsMiddleCount +
  6771. AccessSuballocations2nd().size() - m_2ndNullItemsCount;
  6772. }
  6773. size_t VmaBlockMetadata_Linear::GetFreeRegionsCount() const
  6774. {
  6775. // Function only used for defragmentation, which is disabled for this algorithm
  6776. VMA_ASSERT(0);
  6777. return SIZE_MAX;
  6778. }
  6779. void VmaBlockMetadata_Linear::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const
  6780. {
  6781. const VkDeviceSize size = GetSize();
  6782. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  6783. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  6784. const size_t suballoc1stCount = suballocations1st.size();
  6785. const size_t suballoc2ndCount = suballocations2nd.size();
  6786. inoutStats.statistics.blockCount++;
  6787. inoutStats.statistics.blockBytes += size;
  6788. VkDeviceSize lastOffset = 0;
  6789. if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  6790. {
  6791. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  6792. size_t nextAlloc2ndIndex = 0;
  6793. while (lastOffset < freeSpace2ndTo1stEnd)
  6794. {
  6795. // Find next non-null allocation or move nextAllocIndex to the end.
  6796. while (nextAlloc2ndIndex < suballoc2ndCount &&
  6797. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  6798. {
  6799. ++nextAlloc2ndIndex;
  6800. }
  6801. // Found non-null allocation.
  6802. if (nextAlloc2ndIndex < suballoc2ndCount)
  6803. {
  6804. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  6805. // 1. Process free space before this allocation.
  6806. if (lastOffset < suballoc.offset)
  6807. {
  6808. // There is free space from lastOffset to suballoc.offset.
  6809. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  6810. VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize);
  6811. }
  6812. // 2. Process this allocation.
  6813. // There is allocation with suballoc.offset, suballoc.size.
  6814. VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size);
  6815. // 3. Prepare for next iteration.
  6816. lastOffset = suballoc.offset + suballoc.size;
  6817. ++nextAlloc2ndIndex;
  6818. }
  6819. // We are at the end.
  6820. else
  6821. {
  6822. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  6823. if (lastOffset < freeSpace2ndTo1stEnd)
  6824. {
  6825. const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset;
  6826. VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize);
  6827. }
  6828. // End of loop.
  6829. lastOffset = freeSpace2ndTo1stEnd;
  6830. }
  6831. }
  6832. }
  6833. size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
  6834. const VkDeviceSize freeSpace1stTo2ndEnd =
  6835. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
  6836. while (lastOffset < freeSpace1stTo2ndEnd)
  6837. {
  6838. // Find next non-null allocation or move nextAllocIndex to the end.
  6839. while (nextAlloc1stIndex < suballoc1stCount &&
  6840. suballocations1st[nextAlloc1stIndex].userData == VMA_NULL)
  6841. {
  6842. ++nextAlloc1stIndex;
  6843. }
  6844. // Found non-null allocation.
  6845. if (nextAlloc1stIndex < suballoc1stCount)
  6846. {
  6847. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  6848. // 1. Process free space before this allocation.
  6849. if (lastOffset < suballoc.offset)
  6850. {
  6851. // There is free space from lastOffset to suballoc.offset.
  6852. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  6853. VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize);
  6854. }
  6855. // 2. Process this allocation.
  6856. // There is allocation with suballoc.offset, suballoc.size.
  6857. VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size);
  6858. // 3. Prepare for next iteration.
  6859. lastOffset = suballoc.offset + suballoc.size;
  6860. ++nextAlloc1stIndex;
  6861. }
  6862. // We are at the end.
  6863. else
  6864. {
  6865. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  6866. if (lastOffset < freeSpace1stTo2ndEnd)
  6867. {
  6868. const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset;
  6869. VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize);
  6870. }
  6871. // End of loop.
  6872. lastOffset = freeSpace1stTo2ndEnd;
  6873. }
  6874. }
  6875. if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  6876. {
  6877. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  6878. while (lastOffset < size)
  6879. {
  6880. // Find next non-null allocation or move nextAllocIndex to the end.
  6881. while (nextAlloc2ndIndex != SIZE_MAX &&
  6882. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  6883. {
  6884. --nextAlloc2ndIndex;
  6885. }
  6886. // Found non-null allocation.
  6887. if (nextAlloc2ndIndex != SIZE_MAX)
  6888. {
  6889. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  6890. // 1. Process free space before this allocation.
  6891. if (lastOffset < suballoc.offset)
  6892. {
  6893. // There is free space from lastOffset to suballoc.offset.
  6894. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  6895. VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize);
  6896. }
  6897. // 2. Process this allocation.
  6898. // There is allocation with suballoc.offset, suballoc.size.
  6899. VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size);
  6900. // 3. Prepare for next iteration.
  6901. lastOffset = suballoc.offset + suballoc.size;
  6902. --nextAlloc2ndIndex;
  6903. }
  6904. // We are at the end.
  6905. else
  6906. {
  6907. // There is free space from lastOffset to size.
  6908. if (lastOffset < size)
  6909. {
  6910. const VkDeviceSize unusedRangeSize = size - lastOffset;
  6911. VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize);
  6912. }
  6913. // End of loop.
  6914. lastOffset = size;
  6915. }
  6916. }
  6917. }
  6918. }
  6919. void VmaBlockMetadata_Linear::AddStatistics(VmaStatistics& inoutStats) const
  6920. {
  6921. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  6922. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  6923. const VkDeviceSize size = GetSize();
  6924. const size_t suballoc1stCount = suballocations1st.size();
  6925. const size_t suballoc2ndCount = suballocations2nd.size();
  6926. inoutStats.blockCount++;
  6927. inoutStats.blockBytes += size;
  6928. inoutStats.allocationBytes += size - m_SumFreeSize;
  6929. VkDeviceSize lastOffset = 0;
  6930. if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  6931. {
  6932. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  6933. size_t nextAlloc2ndIndex = m_1stNullItemsBeginCount;
  6934. while (lastOffset < freeSpace2ndTo1stEnd)
  6935. {
  6936. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  6937. while (nextAlloc2ndIndex < suballoc2ndCount &&
  6938. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  6939. {
  6940. ++nextAlloc2ndIndex;
  6941. }
  6942. // Found non-null allocation.
  6943. if (nextAlloc2ndIndex < suballoc2ndCount)
  6944. {
  6945. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  6946. // Process this allocation.
  6947. // There is allocation with suballoc.offset, suballoc.size.
  6948. ++inoutStats.allocationCount;
  6949. // Prepare for next iteration.
  6950. lastOffset = suballoc.offset + suballoc.size;
  6951. ++nextAlloc2ndIndex;
  6952. }
  6953. // We are at the end.
  6954. else
  6955. {
  6956. // End of loop.
  6957. lastOffset = freeSpace2ndTo1stEnd;
  6958. }
  6959. }
  6960. }
  6961. size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
  6962. const VkDeviceSize freeSpace1stTo2ndEnd =
  6963. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
  6964. while (lastOffset < freeSpace1stTo2ndEnd)
  6965. {
  6966. // Find next non-null allocation or move nextAllocIndex to the end.
  6967. while (nextAlloc1stIndex < suballoc1stCount &&
  6968. suballocations1st[nextAlloc1stIndex].userData == VMA_NULL)
  6969. {
  6970. ++nextAlloc1stIndex;
  6971. }
  6972. // Found non-null allocation.
  6973. if (nextAlloc1stIndex < suballoc1stCount)
  6974. {
  6975. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  6976. // Process this allocation.
  6977. // There is allocation with suballoc.offset, suballoc.size.
  6978. ++inoutStats.allocationCount;
  6979. // Prepare for next iteration.
  6980. lastOffset = suballoc.offset + suballoc.size;
  6981. ++nextAlloc1stIndex;
  6982. }
  6983. // We are at the end.
  6984. else
  6985. {
  6986. // End of loop.
  6987. lastOffset = freeSpace1stTo2ndEnd;
  6988. }
  6989. }
  6990. if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  6991. {
  6992. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  6993. while (lastOffset < size)
  6994. {
  6995. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  6996. while (nextAlloc2ndIndex != SIZE_MAX &&
  6997. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  6998. {
  6999. --nextAlloc2ndIndex;
  7000. }
  7001. // Found non-null allocation.
  7002. if (nextAlloc2ndIndex != SIZE_MAX)
  7003. {
  7004. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  7005. // Process this allocation.
  7006. // There is allocation with suballoc.offset, suballoc.size.
  7007. ++inoutStats.allocationCount;
  7008. // Prepare for next iteration.
  7009. lastOffset = suballoc.offset + suballoc.size;
  7010. --nextAlloc2ndIndex;
  7011. }
  7012. // We are at the end.
  7013. else
  7014. {
  7015. // End of loop.
  7016. lastOffset = size;
  7017. }
  7018. }
  7019. }
  7020. }
  7021. #if VMA_STATS_STRING_ENABLED
  7022. void VmaBlockMetadata_Linear::PrintDetailedMap(class VmaJsonWriter& json) const
  7023. {
  7024. const VkDeviceSize size = GetSize();
  7025. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7026. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7027. const size_t suballoc1stCount = suballocations1st.size();
  7028. const size_t suballoc2ndCount = suballocations2nd.size();
  7029. // FIRST PASS
  7030. size_t unusedRangeCount = 0;
  7031. VkDeviceSize usedBytes = 0;
  7032. VkDeviceSize lastOffset = 0;
  7033. size_t alloc2ndCount = 0;
  7034. if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  7035. {
  7036. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  7037. size_t nextAlloc2ndIndex = 0;
  7038. while (lastOffset < freeSpace2ndTo1stEnd)
  7039. {
  7040. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  7041. while (nextAlloc2ndIndex < suballoc2ndCount &&
  7042. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  7043. {
  7044. ++nextAlloc2ndIndex;
  7045. }
  7046. // Found non-null allocation.
  7047. if (nextAlloc2ndIndex < suballoc2ndCount)
  7048. {
  7049. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  7050. // 1. Process free space before this allocation.
  7051. if (lastOffset < suballoc.offset)
  7052. {
  7053. // There is free space from lastOffset to suballoc.offset.
  7054. ++unusedRangeCount;
  7055. }
  7056. // 2. Process this allocation.
  7057. // There is allocation with suballoc.offset, suballoc.size.
  7058. ++alloc2ndCount;
  7059. usedBytes += suballoc.size;
  7060. // 3. Prepare for next iteration.
  7061. lastOffset = suballoc.offset + suballoc.size;
  7062. ++nextAlloc2ndIndex;
  7063. }
  7064. // We are at the end.
  7065. else
  7066. {
  7067. if (lastOffset < freeSpace2ndTo1stEnd)
  7068. {
  7069. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  7070. ++unusedRangeCount;
  7071. }
  7072. // End of loop.
  7073. lastOffset = freeSpace2ndTo1stEnd;
  7074. }
  7075. }
  7076. }
  7077. size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
  7078. size_t alloc1stCount = 0;
  7079. const VkDeviceSize freeSpace1stTo2ndEnd =
  7080. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
  7081. while (lastOffset < freeSpace1stTo2ndEnd)
  7082. {
  7083. // Find next non-null allocation or move nextAllocIndex to the end.
  7084. while (nextAlloc1stIndex < suballoc1stCount &&
  7085. suballocations1st[nextAlloc1stIndex].userData == VMA_NULL)
  7086. {
  7087. ++nextAlloc1stIndex;
  7088. }
  7089. // Found non-null allocation.
  7090. if (nextAlloc1stIndex < suballoc1stCount)
  7091. {
  7092. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  7093. // 1. Process free space before this allocation.
  7094. if (lastOffset < suballoc.offset)
  7095. {
  7096. // There is free space from lastOffset to suballoc.offset.
  7097. ++unusedRangeCount;
  7098. }
  7099. // 2. Process this allocation.
  7100. // There is allocation with suballoc.offset, suballoc.size.
  7101. ++alloc1stCount;
  7102. usedBytes += suballoc.size;
  7103. // 3. Prepare for next iteration.
  7104. lastOffset = suballoc.offset + suballoc.size;
  7105. ++nextAlloc1stIndex;
  7106. }
  7107. // We are at the end.
  7108. else
  7109. {
  7110. if (lastOffset < size)
  7111. {
  7112. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  7113. ++unusedRangeCount;
  7114. }
  7115. // End of loop.
  7116. lastOffset = freeSpace1stTo2ndEnd;
  7117. }
  7118. }
  7119. if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  7120. {
  7121. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  7122. while (lastOffset < size)
  7123. {
  7124. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  7125. while (nextAlloc2ndIndex != SIZE_MAX &&
  7126. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  7127. {
  7128. --nextAlloc2ndIndex;
  7129. }
  7130. // Found non-null allocation.
  7131. if (nextAlloc2ndIndex != SIZE_MAX)
  7132. {
  7133. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  7134. // 1. Process free space before this allocation.
  7135. if (lastOffset < suballoc.offset)
  7136. {
  7137. // There is free space from lastOffset to suballoc.offset.
  7138. ++unusedRangeCount;
  7139. }
  7140. // 2. Process this allocation.
  7141. // There is allocation with suballoc.offset, suballoc.size.
  7142. ++alloc2ndCount;
  7143. usedBytes += suballoc.size;
  7144. // 3. Prepare for next iteration.
  7145. lastOffset = suballoc.offset + suballoc.size;
  7146. --nextAlloc2ndIndex;
  7147. }
  7148. // We are at the end.
  7149. else
  7150. {
  7151. if (lastOffset < size)
  7152. {
  7153. // There is free space from lastOffset to size.
  7154. ++unusedRangeCount;
  7155. }
  7156. // End of loop.
  7157. lastOffset = size;
  7158. }
  7159. }
  7160. }
  7161. const VkDeviceSize unusedBytes = size - usedBytes;
  7162. PrintDetailedMap_Begin(json, unusedBytes, alloc1stCount + alloc2ndCount, unusedRangeCount);
  7163. // SECOND PASS
  7164. lastOffset = 0;
  7165. if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  7166. {
  7167. const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
  7168. size_t nextAlloc2ndIndex = 0;
  7169. while (lastOffset < freeSpace2ndTo1stEnd)
  7170. {
  7171. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  7172. while (nextAlloc2ndIndex < suballoc2ndCount &&
  7173. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  7174. {
  7175. ++nextAlloc2ndIndex;
  7176. }
  7177. // Found non-null allocation.
  7178. if (nextAlloc2ndIndex < suballoc2ndCount)
  7179. {
  7180. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  7181. // 1. Process free space before this allocation.
  7182. if (lastOffset < suballoc.offset)
  7183. {
  7184. // There is free space from lastOffset to suballoc.offset.
  7185. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  7186. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  7187. }
  7188. // 2. Process this allocation.
  7189. // There is allocation with suballoc.offset, suballoc.size.
  7190. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData);
  7191. // 3. Prepare for next iteration.
  7192. lastOffset = suballoc.offset + suballoc.size;
  7193. ++nextAlloc2ndIndex;
  7194. }
  7195. // We are at the end.
  7196. else
  7197. {
  7198. if (lastOffset < freeSpace2ndTo1stEnd)
  7199. {
  7200. // There is free space from lastOffset to freeSpace2ndTo1stEnd.
  7201. const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset;
  7202. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  7203. }
  7204. // End of loop.
  7205. lastOffset = freeSpace2ndTo1stEnd;
  7206. }
  7207. }
  7208. }
  7209. nextAlloc1stIndex = m_1stNullItemsBeginCount;
  7210. while (lastOffset < freeSpace1stTo2ndEnd)
  7211. {
  7212. // Find next non-null allocation or move nextAllocIndex to the end.
  7213. while (nextAlloc1stIndex < suballoc1stCount &&
  7214. suballocations1st[nextAlloc1stIndex].userData == VMA_NULL)
  7215. {
  7216. ++nextAlloc1stIndex;
  7217. }
  7218. // Found non-null allocation.
  7219. if (nextAlloc1stIndex < suballoc1stCount)
  7220. {
  7221. const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
  7222. // 1. Process free space before this allocation.
  7223. if (lastOffset < suballoc.offset)
  7224. {
  7225. // There is free space from lastOffset to suballoc.offset.
  7226. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  7227. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  7228. }
  7229. // 2. Process this allocation.
  7230. // There is allocation with suballoc.offset, suballoc.size.
  7231. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData);
  7232. // 3. Prepare for next iteration.
  7233. lastOffset = suballoc.offset + suballoc.size;
  7234. ++nextAlloc1stIndex;
  7235. }
  7236. // We are at the end.
  7237. else
  7238. {
  7239. if (lastOffset < freeSpace1stTo2ndEnd)
  7240. {
  7241. // There is free space from lastOffset to freeSpace1stTo2ndEnd.
  7242. const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset;
  7243. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  7244. }
  7245. // End of loop.
  7246. lastOffset = freeSpace1stTo2ndEnd;
  7247. }
  7248. }
  7249. if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  7250. {
  7251. size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
  7252. while (lastOffset < size)
  7253. {
  7254. // Find next non-null allocation or move nextAlloc2ndIndex to the end.
  7255. while (nextAlloc2ndIndex != SIZE_MAX &&
  7256. suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL)
  7257. {
  7258. --nextAlloc2ndIndex;
  7259. }
  7260. // Found non-null allocation.
  7261. if (nextAlloc2ndIndex != SIZE_MAX)
  7262. {
  7263. const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
  7264. // 1. Process free space before this allocation.
  7265. if (lastOffset < suballoc.offset)
  7266. {
  7267. // There is free space from lastOffset to suballoc.offset.
  7268. const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
  7269. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  7270. }
  7271. // 2. Process this allocation.
  7272. // There is allocation with suballoc.offset, suballoc.size.
  7273. PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData);
  7274. // 3. Prepare for next iteration.
  7275. lastOffset = suballoc.offset + suballoc.size;
  7276. --nextAlloc2ndIndex;
  7277. }
  7278. // We are at the end.
  7279. else
  7280. {
  7281. if (lastOffset < size)
  7282. {
  7283. // There is free space from lastOffset to size.
  7284. const VkDeviceSize unusedRangeSize = size - lastOffset;
  7285. PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
  7286. }
  7287. // End of loop.
  7288. lastOffset = size;
  7289. }
  7290. }
  7291. }
  7292. PrintDetailedMap_End(json);
  7293. }
  7294. #endif // VMA_STATS_STRING_ENABLED
  7295. bool VmaBlockMetadata_Linear::CreateAllocationRequest(
  7296. VkDeviceSize allocSize,
  7297. VkDeviceSize allocAlignment,
  7298. bool upperAddress,
  7299. VmaSuballocationType allocType,
  7300. uint32_t strategy,
  7301. VmaAllocationRequest* pAllocationRequest)
  7302. {
  7303. VMA_ASSERT(allocSize > 0);
  7304. VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
  7305. VMA_ASSERT(pAllocationRequest != VMA_NULL);
  7306. VMA_HEAVY_ASSERT(Validate());
  7307. pAllocationRequest->size = allocSize;
  7308. return upperAddress ?
  7309. CreateAllocationRequest_UpperAddress(
  7310. allocSize, allocAlignment, allocType, strategy, pAllocationRequest) :
  7311. CreateAllocationRequest_LowerAddress(
  7312. allocSize, allocAlignment, allocType, strategy, pAllocationRequest);
  7313. }
  7314. VkResult VmaBlockMetadata_Linear::CheckCorruption(const void* pBlockData)
  7315. {
  7316. VMA_ASSERT(!IsVirtual());
  7317. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7318. for (size_t i = m_1stNullItemsBeginCount, count = suballocations1st.size(); i < count; ++i)
  7319. {
  7320. const VmaSuballocation& suballoc = suballocations1st[i];
  7321. if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  7322. {
  7323. if (!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size))
  7324. {
  7325. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
  7326. return VK_ERROR_UNKNOWN_COPY;
  7327. }
  7328. }
  7329. }
  7330. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7331. for (size_t i = 0, count = suballocations2nd.size(); i < count; ++i)
  7332. {
  7333. const VmaSuballocation& suballoc = suballocations2nd[i];
  7334. if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
  7335. {
  7336. if (!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size))
  7337. {
  7338. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
  7339. return VK_ERROR_UNKNOWN_COPY;
  7340. }
  7341. }
  7342. }
  7343. return VK_SUCCESS;
  7344. }
  7345. void VmaBlockMetadata_Linear::Alloc(
  7346. const VmaAllocationRequest& request,
  7347. VmaSuballocationType type,
  7348. void* userData)
  7349. {
  7350. const VkDeviceSize offset = (VkDeviceSize)request.allocHandle - 1;
  7351. const VmaSuballocation newSuballoc = { offset, request.size, userData, type };
  7352. switch (request.type)
  7353. {
  7354. case VmaAllocationRequestType::UpperAddress:
  7355. {
  7356. VMA_ASSERT(m_2ndVectorMode != SECOND_VECTOR_RING_BUFFER &&
  7357. "CRITICAL ERROR: Trying to use linear allocator as double stack while it was already used as ring buffer.");
  7358. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7359. suballocations2nd.push_back(newSuballoc);
  7360. m_2ndVectorMode = SECOND_VECTOR_DOUBLE_STACK;
  7361. }
  7362. break;
  7363. case VmaAllocationRequestType::EndOf1st:
  7364. {
  7365. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7366. VMA_ASSERT(suballocations1st.empty() ||
  7367. offset >= suballocations1st.back().offset + suballocations1st.back().size);
  7368. // Check if it fits before the end of the block.
  7369. VMA_ASSERT(offset + request.size <= GetSize());
  7370. suballocations1st.push_back(newSuballoc);
  7371. }
  7372. break;
  7373. case VmaAllocationRequestType::EndOf2nd:
  7374. {
  7375. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7376. // New allocation at the end of 2-part ring buffer, so before first allocation from 1st vector.
  7377. VMA_ASSERT(!suballocations1st.empty() &&
  7378. offset + request.size <= suballocations1st[m_1stNullItemsBeginCount].offset);
  7379. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7380. switch (m_2ndVectorMode)
  7381. {
  7382. case SECOND_VECTOR_EMPTY:
  7383. // First allocation from second part ring buffer.
  7384. VMA_ASSERT(suballocations2nd.empty());
  7385. m_2ndVectorMode = SECOND_VECTOR_RING_BUFFER;
  7386. break;
  7387. case SECOND_VECTOR_RING_BUFFER:
  7388. // 2-part ring buffer is already started.
  7389. VMA_ASSERT(!suballocations2nd.empty());
  7390. break;
  7391. case SECOND_VECTOR_DOUBLE_STACK:
  7392. VMA_ASSERT(0 && "CRITICAL ERROR: Trying to use linear allocator as ring buffer while it was already used as double stack.");
  7393. break;
  7394. default:
  7395. VMA_ASSERT(0);
  7396. }
  7397. suballocations2nd.push_back(newSuballoc);
  7398. }
  7399. break;
  7400. default:
  7401. VMA_ASSERT(0 && "CRITICAL INTERNAL ERROR.");
  7402. }
  7403. m_SumFreeSize -= newSuballoc.size;
  7404. }
  7405. void VmaBlockMetadata_Linear::Free(VmaAllocHandle allocHandle)
  7406. {
  7407. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7408. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7409. VkDeviceSize offset = (VkDeviceSize)allocHandle - 1;
  7410. if (!suballocations1st.empty())
  7411. {
  7412. // First allocation: Mark it as next empty at the beginning.
  7413. VmaSuballocation& firstSuballoc = suballocations1st[m_1stNullItemsBeginCount];
  7414. if (firstSuballoc.offset == offset)
  7415. {
  7416. firstSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
  7417. firstSuballoc.userData = VMA_NULL;
  7418. m_SumFreeSize += firstSuballoc.size;
  7419. ++m_1stNullItemsBeginCount;
  7420. CleanupAfterFree();
  7421. return;
  7422. }
  7423. }
  7424. // Last allocation in 2-part ring buffer or top of upper stack (same logic).
  7425. if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ||
  7426. m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  7427. {
  7428. VmaSuballocation& lastSuballoc = suballocations2nd.back();
  7429. if (lastSuballoc.offset == offset)
  7430. {
  7431. m_SumFreeSize += lastSuballoc.size;
  7432. suballocations2nd.pop_back();
  7433. CleanupAfterFree();
  7434. return;
  7435. }
  7436. }
  7437. // Last allocation in 1st vector.
  7438. else if (m_2ndVectorMode == SECOND_VECTOR_EMPTY)
  7439. {
  7440. VmaSuballocation& lastSuballoc = suballocations1st.back();
  7441. if (lastSuballoc.offset == offset)
  7442. {
  7443. m_SumFreeSize += lastSuballoc.size;
  7444. suballocations1st.pop_back();
  7445. CleanupAfterFree();
  7446. return;
  7447. }
  7448. }
  7449. VmaSuballocation refSuballoc;
  7450. refSuballoc.offset = offset;
  7451. // Rest of members stays uninitialized intentionally for better performance.
  7452. // Item from the middle of 1st vector.
  7453. {
  7454. const SuballocationVectorType::iterator it = VmaBinaryFindSorted(
  7455. suballocations1st.begin() + m_1stNullItemsBeginCount,
  7456. suballocations1st.end(),
  7457. refSuballoc,
  7458. VmaSuballocationOffsetLess());
  7459. if (it != suballocations1st.end())
  7460. {
  7461. it->type = VMA_SUBALLOCATION_TYPE_FREE;
  7462. it->userData = VMA_NULL;
  7463. ++m_1stNullItemsMiddleCount;
  7464. m_SumFreeSize += it->size;
  7465. CleanupAfterFree();
  7466. return;
  7467. }
  7468. }
  7469. if (m_2ndVectorMode != SECOND_VECTOR_EMPTY)
  7470. {
  7471. // Item from the middle of 2nd vector.
  7472. const SuballocationVectorType::iterator it = m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ?
  7473. VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetLess()) :
  7474. VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetGreater());
  7475. if (it != suballocations2nd.end())
  7476. {
  7477. it->type = VMA_SUBALLOCATION_TYPE_FREE;
  7478. it->userData = VMA_NULL;
  7479. ++m_2ndNullItemsCount;
  7480. m_SumFreeSize += it->size;
  7481. CleanupAfterFree();
  7482. return;
  7483. }
  7484. }
  7485. VMA_ASSERT(0 && "Allocation to free not found in linear allocator!");
  7486. }
  7487. void VmaBlockMetadata_Linear::GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo)
  7488. {
  7489. outInfo.offset = (VkDeviceSize)allocHandle - 1;
  7490. VmaSuballocation& suballoc = FindSuballocation(outInfo.offset);
  7491. outInfo.size = suballoc.size;
  7492. outInfo.pUserData = suballoc.userData;
  7493. }
  7494. void* VmaBlockMetadata_Linear::GetAllocationUserData(VmaAllocHandle allocHandle) const
  7495. {
  7496. return FindSuballocation((VkDeviceSize)allocHandle - 1).userData;
  7497. }
  7498. VmaAllocHandle VmaBlockMetadata_Linear::GetAllocationListBegin() const
  7499. {
  7500. // Function only used for defragmentation, which is disabled for this algorithm
  7501. VMA_ASSERT(0);
  7502. return VK_NULL_HANDLE;
  7503. }
  7504. VmaAllocHandle VmaBlockMetadata_Linear::GetNextAllocation(VmaAllocHandle prevAlloc) const
  7505. {
  7506. // Function only used for defragmentation, which is disabled for this algorithm
  7507. VMA_ASSERT(0);
  7508. return VK_NULL_HANDLE;
  7509. }
  7510. VkDeviceSize VmaBlockMetadata_Linear::GetNextFreeRegionSize(VmaAllocHandle alloc) const
  7511. {
  7512. // Function only used for defragmentation, which is disabled for this algorithm
  7513. VMA_ASSERT(0);
  7514. return 0;
  7515. }
  7516. void VmaBlockMetadata_Linear::Clear()
  7517. {
  7518. m_SumFreeSize = GetSize();
  7519. m_Suballocations0.clear();
  7520. m_Suballocations1.clear();
  7521. // Leaving m_1stVectorIndex unchanged - it doesn't matter.
  7522. m_2ndVectorMode = SECOND_VECTOR_EMPTY;
  7523. m_1stNullItemsBeginCount = 0;
  7524. m_1stNullItemsMiddleCount = 0;
  7525. m_2ndNullItemsCount = 0;
  7526. }
  7527. void VmaBlockMetadata_Linear::SetAllocationUserData(VmaAllocHandle allocHandle, void* userData)
  7528. {
  7529. VmaSuballocation& suballoc = FindSuballocation((VkDeviceSize)allocHandle - 1);
  7530. suballoc.userData = userData;
  7531. }
  7532. void VmaBlockMetadata_Linear::DebugLogAllAllocations() const
  7533. {
  7534. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7535. for (auto it = suballocations1st.begin() + m_1stNullItemsBeginCount; it != suballocations1st.end(); ++it)
  7536. if (it->type != VMA_SUBALLOCATION_TYPE_FREE)
  7537. DebugLogAllocation(it->offset, it->size, it->userData);
  7538. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7539. for (auto it = suballocations2nd.begin(); it != suballocations2nd.end(); ++it)
  7540. if (it->type != VMA_SUBALLOCATION_TYPE_FREE)
  7541. DebugLogAllocation(it->offset, it->size, it->userData);
  7542. }
  7543. VmaSuballocation& VmaBlockMetadata_Linear::FindSuballocation(VkDeviceSize offset) const
  7544. {
  7545. const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7546. const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7547. VmaSuballocation refSuballoc;
  7548. refSuballoc.offset = offset;
  7549. // Rest of members stays uninitialized intentionally for better performance.
  7550. // Item from the 1st vector.
  7551. {
  7552. SuballocationVectorType::const_iterator it = VmaBinaryFindSorted(
  7553. suballocations1st.begin() + m_1stNullItemsBeginCount,
  7554. suballocations1st.end(),
  7555. refSuballoc,
  7556. VmaSuballocationOffsetLess());
  7557. if (it != suballocations1st.end())
  7558. {
  7559. return const_cast<VmaSuballocation&>(*it);
  7560. }
  7561. }
  7562. if (m_2ndVectorMode != SECOND_VECTOR_EMPTY)
  7563. {
  7564. // Rest of members stays uninitialized intentionally for better performance.
  7565. SuballocationVectorType::const_iterator it = m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ?
  7566. VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetLess()) :
  7567. VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetGreater());
  7568. if (it != suballocations2nd.end())
  7569. {
  7570. return const_cast<VmaSuballocation&>(*it);
  7571. }
  7572. }
  7573. VMA_ASSERT(0 && "Allocation not found in linear allocator!");
  7574. return const_cast<VmaSuballocation&>(suballocations1st.back()); // Should never occur.
  7575. }
  7576. bool VmaBlockMetadata_Linear::ShouldCompact1st() const
  7577. {
  7578. const size_t nullItemCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount;
  7579. const size_t suballocCount = AccessSuballocations1st().size();
  7580. return suballocCount > 32 && nullItemCount * 2 >= (suballocCount - nullItemCount) * 3;
  7581. }
  7582. void VmaBlockMetadata_Linear::CleanupAfterFree()
  7583. {
  7584. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7585. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7586. if (IsEmpty())
  7587. {
  7588. suballocations1st.clear();
  7589. suballocations2nd.clear();
  7590. m_1stNullItemsBeginCount = 0;
  7591. m_1stNullItemsMiddleCount = 0;
  7592. m_2ndNullItemsCount = 0;
  7593. m_2ndVectorMode = SECOND_VECTOR_EMPTY;
  7594. }
  7595. else
  7596. {
  7597. const size_t suballoc1stCount = suballocations1st.size();
  7598. const size_t nullItem1stCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount;
  7599. VMA_ASSERT(nullItem1stCount <= suballoc1stCount);
  7600. // Find more null items at the beginning of 1st vector.
  7601. while (m_1stNullItemsBeginCount < suballoc1stCount &&
  7602. suballocations1st[m_1stNullItemsBeginCount].type == VMA_SUBALLOCATION_TYPE_FREE)
  7603. {
  7604. ++m_1stNullItemsBeginCount;
  7605. --m_1stNullItemsMiddleCount;
  7606. }
  7607. // Find more null items at the end of 1st vector.
  7608. while (m_1stNullItemsMiddleCount > 0 &&
  7609. suballocations1st.back().type == VMA_SUBALLOCATION_TYPE_FREE)
  7610. {
  7611. --m_1stNullItemsMiddleCount;
  7612. suballocations1st.pop_back();
  7613. }
  7614. // Find more null items at the end of 2nd vector.
  7615. while (m_2ndNullItemsCount > 0 &&
  7616. suballocations2nd.back().type == VMA_SUBALLOCATION_TYPE_FREE)
  7617. {
  7618. --m_2ndNullItemsCount;
  7619. suballocations2nd.pop_back();
  7620. }
  7621. // Find more null items at the beginning of 2nd vector.
  7622. while (m_2ndNullItemsCount > 0 &&
  7623. suballocations2nd[0].type == VMA_SUBALLOCATION_TYPE_FREE)
  7624. {
  7625. --m_2ndNullItemsCount;
  7626. VmaVectorRemove(suballocations2nd, 0);
  7627. }
  7628. if (ShouldCompact1st())
  7629. {
  7630. const size_t nonNullItemCount = suballoc1stCount - nullItem1stCount;
  7631. size_t srcIndex = m_1stNullItemsBeginCount;
  7632. for (size_t dstIndex = 0; dstIndex < nonNullItemCount; ++dstIndex)
  7633. {
  7634. while (suballocations1st[srcIndex].type == VMA_SUBALLOCATION_TYPE_FREE)
  7635. {
  7636. ++srcIndex;
  7637. }
  7638. if (dstIndex != srcIndex)
  7639. {
  7640. suballocations1st[dstIndex] = suballocations1st[srcIndex];
  7641. }
  7642. ++srcIndex;
  7643. }
  7644. suballocations1st.resize(nonNullItemCount);
  7645. m_1stNullItemsBeginCount = 0;
  7646. m_1stNullItemsMiddleCount = 0;
  7647. }
  7648. // 2nd vector became empty.
  7649. if (suballocations2nd.empty())
  7650. {
  7651. m_2ndVectorMode = SECOND_VECTOR_EMPTY;
  7652. }
  7653. // 1st vector became empty.
  7654. if (suballocations1st.size() - m_1stNullItemsBeginCount == 0)
  7655. {
  7656. suballocations1st.clear();
  7657. m_1stNullItemsBeginCount = 0;
  7658. if (!suballocations2nd.empty() && m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  7659. {
  7660. // Swap 1st with 2nd. Now 2nd is empty.
  7661. m_2ndVectorMode = SECOND_VECTOR_EMPTY;
  7662. m_1stNullItemsMiddleCount = m_2ndNullItemsCount;
  7663. while (m_1stNullItemsBeginCount < suballocations2nd.size() &&
  7664. suballocations2nd[m_1stNullItemsBeginCount].type == VMA_SUBALLOCATION_TYPE_FREE)
  7665. {
  7666. ++m_1stNullItemsBeginCount;
  7667. --m_1stNullItemsMiddleCount;
  7668. }
  7669. m_2ndNullItemsCount = 0;
  7670. m_1stVectorIndex ^= 1;
  7671. }
  7672. }
  7673. }
  7674. VMA_HEAVY_ASSERT(Validate());
  7675. }
  7676. bool VmaBlockMetadata_Linear::CreateAllocationRequest_LowerAddress(
  7677. VkDeviceSize allocSize,
  7678. VkDeviceSize allocAlignment,
  7679. VmaSuballocationType allocType,
  7680. uint32_t strategy,
  7681. VmaAllocationRequest* pAllocationRequest)
  7682. {
  7683. const VkDeviceSize blockSize = GetSize();
  7684. const VkDeviceSize debugMargin = GetDebugMargin();
  7685. const VkDeviceSize bufferImageGranularity = GetBufferImageGranularity();
  7686. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7687. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7688. if (m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  7689. {
  7690. // Try to allocate at the end of 1st vector.
  7691. VkDeviceSize resultBaseOffset = 0;
  7692. if (!suballocations1st.empty())
  7693. {
  7694. const VmaSuballocation& lastSuballoc = suballocations1st.back();
  7695. resultBaseOffset = lastSuballoc.offset + lastSuballoc.size + debugMargin;
  7696. }
  7697. // Start from offset equal to beginning of free space.
  7698. VkDeviceSize resultOffset = resultBaseOffset;
  7699. // Apply alignment.
  7700. resultOffset = VmaAlignUp(resultOffset, allocAlignment);
  7701. // Check previous suballocations for BufferImageGranularity conflicts.
  7702. // Make bigger alignment if necessary.
  7703. if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations1st.empty())
  7704. {
  7705. bool bufferImageGranularityConflict = false;
  7706. for (size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; )
  7707. {
  7708. const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex];
  7709. if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
  7710. {
  7711. if (VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
  7712. {
  7713. bufferImageGranularityConflict = true;
  7714. break;
  7715. }
  7716. }
  7717. else
  7718. // Already on previous page.
  7719. break;
  7720. }
  7721. if (bufferImageGranularityConflict)
  7722. {
  7723. resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity);
  7724. }
  7725. }
  7726. const VkDeviceSize freeSpaceEnd = m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ?
  7727. suballocations2nd.back().offset : blockSize;
  7728. // There is enough free space at the end after alignment.
  7729. if (resultOffset + allocSize + debugMargin <= freeSpaceEnd)
  7730. {
  7731. // Check next suballocations for BufferImageGranularity conflicts.
  7732. // If conflict exists, allocation cannot be made here.
  7733. if ((allocSize % bufferImageGranularity || resultOffset % bufferImageGranularity) && m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
  7734. {
  7735. for (size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; )
  7736. {
  7737. const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex];
  7738. if (VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  7739. {
  7740. if (VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
  7741. {
  7742. return false;
  7743. }
  7744. }
  7745. else
  7746. {
  7747. // Already on previous page.
  7748. break;
  7749. }
  7750. }
  7751. }
  7752. // All tests passed: Success.
  7753. pAllocationRequest->allocHandle = (VmaAllocHandle)(resultOffset + 1);
  7754. // pAllocationRequest->item, customData unused.
  7755. pAllocationRequest->type = VmaAllocationRequestType::EndOf1st;
  7756. return true;
  7757. }
  7758. }
  7759. // Wrap-around to end of 2nd vector. Try to allocate there, watching for the
  7760. // beginning of 1st vector as the end of free space.
  7761. if (m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  7762. {
  7763. VMA_ASSERT(!suballocations1st.empty());
  7764. VkDeviceSize resultBaseOffset = 0;
  7765. if (!suballocations2nd.empty())
  7766. {
  7767. const VmaSuballocation& lastSuballoc = suballocations2nd.back();
  7768. resultBaseOffset = lastSuballoc.offset + lastSuballoc.size + debugMargin;
  7769. }
  7770. // Start from offset equal to beginning of free space.
  7771. VkDeviceSize resultOffset = resultBaseOffset;
  7772. // Apply alignment.
  7773. resultOffset = VmaAlignUp(resultOffset, allocAlignment);
  7774. // Check previous suballocations for BufferImageGranularity conflicts.
  7775. // Make bigger alignment if necessary.
  7776. if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations2nd.empty())
  7777. {
  7778. bool bufferImageGranularityConflict = false;
  7779. for (size_t prevSuballocIndex = suballocations2nd.size(); prevSuballocIndex--; )
  7780. {
  7781. const VmaSuballocation& prevSuballoc = suballocations2nd[prevSuballocIndex];
  7782. if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
  7783. {
  7784. if (VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
  7785. {
  7786. bufferImageGranularityConflict = true;
  7787. break;
  7788. }
  7789. }
  7790. else
  7791. // Already on previous page.
  7792. break;
  7793. }
  7794. if (bufferImageGranularityConflict)
  7795. {
  7796. resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity);
  7797. }
  7798. }
  7799. size_t index1st = m_1stNullItemsBeginCount;
  7800. // There is enough free space at the end after alignment.
  7801. if ((index1st == suballocations1st.size() && resultOffset + allocSize + debugMargin <= blockSize) ||
  7802. (index1st < suballocations1st.size() && resultOffset + allocSize + debugMargin <= suballocations1st[index1st].offset))
  7803. {
  7804. // Check next suballocations for BufferImageGranularity conflicts.
  7805. // If conflict exists, allocation cannot be made here.
  7806. if (allocSize % bufferImageGranularity || resultOffset % bufferImageGranularity)
  7807. {
  7808. for (size_t nextSuballocIndex = index1st;
  7809. nextSuballocIndex < suballocations1st.size();
  7810. nextSuballocIndex++)
  7811. {
  7812. const VmaSuballocation& nextSuballoc = suballocations1st[nextSuballocIndex];
  7813. if (VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  7814. {
  7815. if (VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
  7816. {
  7817. return false;
  7818. }
  7819. }
  7820. else
  7821. {
  7822. // Already on next page.
  7823. break;
  7824. }
  7825. }
  7826. }
  7827. // All tests passed: Success.
  7828. pAllocationRequest->allocHandle = (VmaAllocHandle)(resultOffset + 1);
  7829. pAllocationRequest->type = VmaAllocationRequestType::EndOf2nd;
  7830. // pAllocationRequest->item, customData unused.
  7831. return true;
  7832. }
  7833. }
  7834. return false;
  7835. }
  7836. bool VmaBlockMetadata_Linear::CreateAllocationRequest_UpperAddress(
  7837. VkDeviceSize allocSize,
  7838. VkDeviceSize allocAlignment,
  7839. VmaSuballocationType allocType,
  7840. uint32_t strategy,
  7841. VmaAllocationRequest* pAllocationRequest)
  7842. {
  7843. const VkDeviceSize blockSize = GetSize();
  7844. const VkDeviceSize bufferImageGranularity = GetBufferImageGranularity();
  7845. SuballocationVectorType& suballocations1st = AccessSuballocations1st();
  7846. SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
  7847. if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
  7848. {
  7849. VMA_ASSERT(0 && "Trying to use pool with linear algorithm as double stack, while it is already being used as ring buffer.");
  7850. return false;
  7851. }
  7852. // Try to allocate before 2nd.back(), or end of block if 2nd.empty().
  7853. if (allocSize > blockSize)
  7854. {
  7855. return false;
  7856. }
  7857. VkDeviceSize resultBaseOffset = blockSize - allocSize;
  7858. if (!suballocations2nd.empty())
  7859. {
  7860. const VmaSuballocation& lastSuballoc = suballocations2nd.back();
  7861. resultBaseOffset = lastSuballoc.offset - allocSize;
  7862. if (allocSize > lastSuballoc.offset)
  7863. {
  7864. return false;
  7865. }
  7866. }
  7867. // Start from offset equal to end of free space.
  7868. VkDeviceSize resultOffset = resultBaseOffset;
  7869. const VkDeviceSize debugMargin = GetDebugMargin();
  7870. // Apply debugMargin at the end.
  7871. if (debugMargin > 0)
  7872. {
  7873. if (resultOffset < debugMargin)
  7874. {
  7875. return false;
  7876. }
  7877. resultOffset -= debugMargin;
  7878. }
  7879. // Apply alignment.
  7880. resultOffset = VmaAlignDown(resultOffset, allocAlignment);
  7881. // Check next suballocations from 2nd for BufferImageGranularity conflicts.
  7882. // Make bigger alignment if necessary.
  7883. if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations2nd.empty())
  7884. {
  7885. bool bufferImageGranularityConflict = false;
  7886. for (size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; )
  7887. {
  7888. const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex];
  7889. if (VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
  7890. {
  7891. if (VmaIsBufferImageGranularityConflict(nextSuballoc.type, allocType))
  7892. {
  7893. bufferImageGranularityConflict = true;
  7894. break;
  7895. }
  7896. }
  7897. else
  7898. // Already on previous page.
  7899. break;
  7900. }
  7901. if (bufferImageGranularityConflict)
  7902. {
  7903. resultOffset = VmaAlignDown(resultOffset, bufferImageGranularity);
  7904. }
  7905. }
  7906. // There is enough free space.
  7907. const VkDeviceSize endOf1st = !suballocations1st.empty() ?
  7908. suballocations1st.back().offset + suballocations1st.back().size :
  7909. 0;
  7910. if (endOf1st + debugMargin <= resultOffset)
  7911. {
  7912. // Check previous suballocations for BufferImageGranularity conflicts.
  7913. // If conflict exists, allocation cannot be made here.
  7914. if (bufferImageGranularity > 1)
  7915. {
  7916. for (size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; )
  7917. {
  7918. const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex];
  7919. if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
  7920. {
  7921. if (VmaIsBufferImageGranularityConflict(allocType, prevSuballoc.type))
  7922. {
  7923. return false;
  7924. }
  7925. }
  7926. else
  7927. {
  7928. // Already on next page.
  7929. break;
  7930. }
  7931. }
  7932. }
  7933. // All tests passed: Success.
  7934. pAllocationRequest->allocHandle = (VmaAllocHandle)(resultOffset + 1);
  7935. // pAllocationRequest->item unused.
  7936. pAllocationRequest->type = VmaAllocationRequestType::UpperAddress;
  7937. return true;
  7938. }
  7939. return false;
  7940. }
  7941. #endif // _VMA_BLOCK_METADATA_LINEAR_FUNCTIONS
  7942. #endif // _VMA_BLOCK_METADATA_LINEAR
  7943. #if 0
  7944. #ifndef _VMA_BLOCK_METADATA_BUDDY
  7945. /*
  7946. - GetSize() is the original size of allocated memory block.
  7947. - m_UsableSize is this size aligned down to a power of two.
  7948. All allocations and calculations happen relative to m_UsableSize.
  7949. - GetUnusableSize() is the difference between them.
  7950. It is reported as separate, unused range, not available for allocations.
  7951. Node at level 0 has size = m_UsableSize.
  7952. Each next level contains nodes with size 2 times smaller than current level.
  7953. m_LevelCount is the maximum number of levels to use in the current object.
  7954. */
  7955. class VmaBlockMetadata_Buddy : public VmaBlockMetadata
  7956. {
  7957. VMA_CLASS_NO_COPY_NO_MOVE(VmaBlockMetadata_Buddy)
  7958. public:
  7959. VmaBlockMetadata_Buddy(const VkAllocationCallbacks* pAllocationCallbacks,
  7960. VkDeviceSize bufferImageGranularity, bool isVirtual);
  7961. virtual ~VmaBlockMetadata_Buddy();
  7962. size_t GetAllocationCount() const override { return m_AllocationCount; }
  7963. VkDeviceSize GetSumFreeSize() const override { return m_SumFreeSize + GetUnusableSize(); }
  7964. bool IsEmpty() const override { return m_Root->type == Node::TYPE_FREE; }
  7965. VkResult CheckCorruption(const void* pBlockData) override { return VK_ERROR_FEATURE_NOT_PRESENT; }
  7966. VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const override { return (VkDeviceSize)allocHandle - 1; }
  7967. void DebugLogAllAllocations() const override { DebugLogAllAllocationNode(m_Root, 0); }
  7968. void Init(VkDeviceSize size) override;
  7969. bool Validate() const override;
  7970. void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const override;
  7971. void AddStatistics(VmaStatistics& inoutStats) const override;
  7972. #if VMA_STATS_STRING_ENABLED
  7973. void PrintDetailedMap(class VmaJsonWriter& json, uint32_t mapRefCount) const override;
  7974. #endif
  7975. bool CreateAllocationRequest(
  7976. VkDeviceSize allocSize,
  7977. VkDeviceSize allocAlignment,
  7978. bool upperAddress,
  7979. VmaSuballocationType allocType,
  7980. uint32_t strategy,
  7981. VmaAllocationRequest* pAllocationRequest) override;
  7982. void Alloc(
  7983. const VmaAllocationRequest& request,
  7984. VmaSuballocationType type,
  7985. void* userData) override;
  7986. void Free(VmaAllocHandle allocHandle) override;
  7987. void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) override;
  7988. void* GetAllocationUserData(VmaAllocHandle allocHandle) const override;
  7989. VmaAllocHandle GetAllocationListBegin() const override;
  7990. VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const override;
  7991. void Clear() override;
  7992. void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) override;
  7993. private:
  7994. static const size_t MAX_LEVELS = 48;
  7995. struct ValidationContext
  7996. {
  7997. size_t calculatedAllocationCount = 0;
  7998. size_t calculatedFreeCount = 0;
  7999. VkDeviceSize calculatedSumFreeSize = 0;
  8000. };
  8001. struct Node
  8002. {
  8003. VkDeviceSize offset;
  8004. enum TYPE
  8005. {
  8006. TYPE_FREE,
  8007. TYPE_ALLOCATION,
  8008. TYPE_SPLIT,
  8009. TYPE_COUNT
  8010. } type;
  8011. Node* parent;
  8012. Node* buddy;
  8013. union
  8014. {
  8015. struct
  8016. {
  8017. Node* prev;
  8018. Node* next;
  8019. } free;
  8020. struct
  8021. {
  8022. void* userData;
  8023. } allocation;
  8024. struct
  8025. {
  8026. Node* leftChild;
  8027. } split;
  8028. };
  8029. };
  8030. // Size of the memory block aligned down to a power of two.
  8031. VkDeviceSize m_UsableSize;
  8032. uint32_t m_LevelCount;
  8033. VmaPoolAllocator<Node> m_NodeAllocator;
  8034. Node* m_Root;
  8035. struct
  8036. {
  8037. Node* front;
  8038. Node* back;
  8039. } m_FreeList[MAX_LEVELS];
  8040. // Number of nodes in the tree with type == TYPE_ALLOCATION.
  8041. size_t m_AllocationCount;
  8042. // Number of nodes in the tree with type == TYPE_FREE.
  8043. size_t m_FreeCount;
  8044. // Doesn't include space wasted due to internal fragmentation - allocation sizes are just aligned up to node sizes.
  8045. // Doesn't include unusable size.
  8046. VkDeviceSize m_SumFreeSize;
  8047. VkDeviceSize GetUnusableSize() const { return GetSize() - m_UsableSize; }
  8048. VkDeviceSize LevelToNodeSize(uint32_t level) const { return m_UsableSize >> level; }
  8049. VkDeviceSize AlignAllocationSize(VkDeviceSize size) const
  8050. {
  8051. if (!IsVirtual())
  8052. {
  8053. size = VmaAlignUp(size, (VkDeviceSize)16);
  8054. }
  8055. return VmaNextPow2(size);
  8056. }
  8057. Node* FindAllocationNode(VkDeviceSize offset, uint32_t& outLevel) const;
  8058. void DeleteNodeChildren(Node* node);
  8059. bool ValidateNode(ValidationContext& ctx, const Node* parent, const Node* curr, uint32_t level, VkDeviceSize levelNodeSize) const;
  8060. uint32_t AllocSizeToLevel(VkDeviceSize allocSize) const;
  8061. void AddNodeToDetailedStatistics(VmaDetailedStatistics& inoutStats, const Node* node, VkDeviceSize levelNodeSize) const;
  8062. // Adds node to the front of FreeList at given level.
  8063. // node->type must be FREE.
  8064. // node->free.prev, next can be undefined.
  8065. void AddToFreeListFront(uint32_t level, Node* node);
  8066. // Removes node from FreeList at given level.
  8067. // node->type must be FREE.
  8068. // node->free.prev, next stay untouched.
  8069. void RemoveFromFreeList(uint32_t level, Node* node);
  8070. void DebugLogAllAllocationNode(Node* node, uint32_t level) const;
  8071. #if VMA_STATS_STRING_ENABLED
  8072. void PrintDetailedMapNode(class VmaJsonWriter& json, const Node* node, VkDeviceSize levelNodeSize) const;
  8073. #endif
  8074. };
  8075. #ifndef _VMA_BLOCK_METADATA_BUDDY_FUNCTIONS
  8076. VmaBlockMetadata_Buddy::VmaBlockMetadata_Buddy(const VkAllocationCallbacks* pAllocationCallbacks,
  8077. VkDeviceSize bufferImageGranularity, bool isVirtual)
  8078. : VmaBlockMetadata(pAllocationCallbacks, bufferImageGranularity, isVirtual),
  8079. m_NodeAllocator(pAllocationCallbacks, 32), // firstBlockCapacity
  8080. m_Root(VMA_NULL),
  8081. m_AllocationCount(0),
  8082. m_FreeCount(1),
  8083. m_SumFreeSize(0)
  8084. {
  8085. memset(m_FreeList, 0, sizeof(m_FreeList));
  8086. }
  8087. VmaBlockMetadata_Buddy::~VmaBlockMetadata_Buddy()
  8088. {
  8089. DeleteNodeChildren(m_Root);
  8090. m_NodeAllocator.Free(m_Root);
  8091. }
  8092. void VmaBlockMetadata_Buddy::Init(VkDeviceSize size)
  8093. {
  8094. VmaBlockMetadata::Init(size);
  8095. m_UsableSize = VmaPrevPow2(size);
  8096. m_SumFreeSize = m_UsableSize;
  8097. // Calculate m_LevelCount.
  8098. const VkDeviceSize minNodeSize = IsVirtual() ? 1 : 16;
  8099. m_LevelCount = 1;
  8100. while (m_LevelCount < MAX_LEVELS &&
  8101. LevelToNodeSize(m_LevelCount) >= minNodeSize)
  8102. {
  8103. ++m_LevelCount;
  8104. }
  8105. Node* rootNode = m_NodeAllocator.Alloc();
  8106. rootNode->offset = 0;
  8107. rootNode->type = Node::TYPE_FREE;
  8108. rootNode->parent = VMA_NULL;
  8109. rootNode->buddy = VMA_NULL;
  8110. m_Root = rootNode;
  8111. AddToFreeListFront(0, rootNode);
  8112. }
  8113. bool VmaBlockMetadata_Buddy::Validate() const
  8114. {
  8115. // Validate tree.
  8116. ValidationContext ctx;
  8117. if (!ValidateNode(ctx, VMA_NULL, m_Root, 0, LevelToNodeSize(0)))
  8118. {
  8119. VMA_VALIDATE(false && "ValidateNode failed.");
  8120. }
  8121. VMA_VALIDATE(m_AllocationCount == ctx.calculatedAllocationCount);
  8122. VMA_VALIDATE(m_SumFreeSize == ctx.calculatedSumFreeSize);
  8123. // Validate free node lists.
  8124. for (uint32_t level = 0; level < m_LevelCount; ++level)
  8125. {
  8126. VMA_VALIDATE(m_FreeList[level].front == VMA_NULL ||
  8127. m_FreeList[level].front->free.prev == VMA_NULL);
  8128. for (Node* node = m_FreeList[level].front;
  8129. node != VMA_NULL;
  8130. node = node->free.next)
  8131. {
  8132. VMA_VALIDATE(node->type == Node::TYPE_FREE);
  8133. if (node->free.next == VMA_NULL)
  8134. {
  8135. VMA_VALIDATE(m_FreeList[level].back == node);
  8136. }
  8137. else
  8138. {
  8139. VMA_VALIDATE(node->free.next->free.prev == node);
  8140. }
  8141. }
  8142. }
  8143. // Validate that free lists ar higher levels are empty.
  8144. for (uint32_t level = m_LevelCount; level < MAX_LEVELS; ++level)
  8145. {
  8146. VMA_VALIDATE(m_FreeList[level].front == VMA_NULL && m_FreeList[level].back == VMA_NULL);
  8147. }
  8148. return true;
  8149. }
  8150. void VmaBlockMetadata_Buddy::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const
  8151. {
  8152. inoutStats.statistics.blockCount++;
  8153. inoutStats.statistics.blockBytes += GetSize();
  8154. AddNodeToDetailedStatistics(inoutStats, m_Root, LevelToNodeSize(0));
  8155. const VkDeviceSize unusableSize = GetUnusableSize();
  8156. if (unusableSize > 0)
  8157. VmaAddDetailedStatisticsUnusedRange(inoutStats, unusableSize);
  8158. }
  8159. void VmaBlockMetadata_Buddy::AddStatistics(VmaStatistics& inoutStats) const
  8160. {
  8161. inoutStats.blockCount++;
  8162. inoutStats.allocationCount += (uint32_t)m_AllocationCount;
  8163. inoutStats.blockBytes += GetSize();
  8164. inoutStats.allocationBytes += GetSize() - m_SumFreeSize;
  8165. }
  8166. #if VMA_STATS_STRING_ENABLED
  8167. void VmaBlockMetadata_Buddy::PrintDetailedMap(class VmaJsonWriter& json, uint32_t mapRefCount) const
  8168. {
  8169. VmaDetailedStatistics stats;
  8170. VmaClearDetailedStatistics(stats);
  8171. AddDetailedStatistics(stats);
  8172. PrintDetailedMap_Begin(
  8173. json,
  8174. stats.statistics.blockBytes - stats.statistics.allocationBytes,
  8175. stats.statistics.allocationCount,
  8176. stats.unusedRangeCount,
  8177. mapRefCount);
  8178. PrintDetailedMapNode(json, m_Root, LevelToNodeSize(0));
  8179. const VkDeviceSize unusableSize = GetUnusableSize();
  8180. if (unusableSize > 0)
  8181. {
  8182. PrintDetailedMap_UnusedRange(json,
  8183. m_UsableSize, // offset
  8184. unusableSize); // size
  8185. }
  8186. PrintDetailedMap_End(json);
  8187. }
  8188. #endif // VMA_STATS_STRING_ENABLED
  8189. bool VmaBlockMetadata_Buddy::CreateAllocationRequest(
  8190. VkDeviceSize allocSize,
  8191. VkDeviceSize allocAlignment,
  8192. bool upperAddress,
  8193. VmaSuballocationType allocType,
  8194. uint32_t strategy,
  8195. VmaAllocationRequest* pAllocationRequest)
  8196. {
  8197. VMA_ASSERT(!upperAddress && "VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT can be used only with linear algorithm.");
  8198. allocSize = AlignAllocationSize(allocSize);
  8199. // Simple way to respect bufferImageGranularity. May be optimized some day.
  8200. // Whenever it might be an OPTIMAL image...
  8201. if (allocType == VMA_SUBALLOCATION_TYPE_UNKNOWN ||
  8202. allocType == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
  8203. allocType == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL)
  8204. {
  8205. allocAlignment = VMA_MAX(allocAlignment, GetBufferImageGranularity());
  8206. allocSize = VmaAlignUp(allocSize, GetBufferImageGranularity());
  8207. }
  8208. if (allocSize > m_UsableSize)
  8209. {
  8210. return false;
  8211. }
  8212. const uint32_t targetLevel = AllocSizeToLevel(allocSize);
  8213. for (uint32_t level = targetLevel; level--; )
  8214. {
  8215. for (Node* freeNode = m_FreeList[level].front;
  8216. freeNode != VMA_NULL;
  8217. freeNode = freeNode->free.next)
  8218. {
  8219. if (freeNode->offset % allocAlignment == 0)
  8220. {
  8221. pAllocationRequest->type = VmaAllocationRequestType::Normal;
  8222. pAllocationRequest->allocHandle = (VmaAllocHandle)(freeNode->offset + 1);
  8223. pAllocationRequest->size = allocSize;
  8224. pAllocationRequest->customData = (void*)(uintptr_t)level;
  8225. return true;
  8226. }
  8227. }
  8228. }
  8229. return false;
  8230. }
  8231. void VmaBlockMetadata_Buddy::Alloc(
  8232. const VmaAllocationRequest& request,
  8233. VmaSuballocationType type,
  8234. void* userData)
  8235. {
  8236. VMA_ASSERT(request.type == VmaAllocationRequestType::Normal);
  8237. const uint32_t targetLevel = AllocSizeToLevel(request.size);
  8238. uint32_t currLevel = (uint32_t)(uintptr_t)request.customData;
  8239. Node* currNode = m_FreeList[currLevel].front;
  8240. VMA_ASSERT(currNode != VMA_NULL && currNode->type == Node::TYPE_FREE);
  8241. const VkDeviceSize offset = (VkDeviceSize)request.allocHandle - 1;
  8242. while (currNode->offset != offset)
  8243. {
  8244. currNode = currNode->free.next;
  8245. VMA_ASSERT(currNode != VMA_NULL && currNode->type == Node::TYPE_FREE);
  8246. }
  8247. // Go down, splitting free nodes.
  8248. while (currLevel < targetLevel)
  8249. {
  8250. // currNode is already first free node at currLevel.
  8251. // Remove it from list of free nodes at this currLevel.
  8252. RemoveFromFreeList(currLevel, currNode);
  8253. const uint32_t childrenLevel = currLevel + 1;
  8254. // Create two free sub-nodes.
  8255. Node* leftChild = m_NodeAllocator.Alloc();
  8256. Node* rightChild = m_NodeAllocator.Alloc();
  8257. leftChild->offset = currNode->offset;
  8258. leftChild->type = Node::TYPE_FREE;
  8259. leftChild->parent = currNode;
  8260. leftChild->buddy = rightChild;
  8261. rightChild->offset = currNode->offset + LevelToNodeSize(childrenLevel);
  8262. rightChild->type = Node::TYPE_FREE;
  8263. rightChild->parent = currNode;
  8264. rightChild->buddy = leftChild;
  8265. // Convert current currNode to split type.
  8266. currNode->type = Node::TYPE_SPLIT;
  8267. currNode->split.leftChild = leftChild;
  8268. // Add child nodes to free list. Order is important!
  8269. AddToFreeListFront(childrenLevel, rightChild);
  8270. AddToFreeListFront(childrenLevel, leftChild);
  8271. ++m_FreeCount;
  8272. ++currLevel;
  8273. currNode = m_FreeList[currLevel].front;
  8274. /*
  8275. We can be sure that currNode, as left child of node previously split,
  8276. also fulfills the alignment requirement.
  8277. */
  8278. }
  8279. // Remove from free list.
  8280. VMA_ASSERT(currLevel == targetLevel &&
  8281. currNode != VMA_NULL &&
  8282. currNode->type == Node::TYPE_FREE);
  8283. RemoveFromFreeList(currLevel, currNode);
  8284. // Convert to allocation node.
  8285. currNode->type = Node::TYPE_ALLOCATION;
  8286. currNode->allocation.userData = userData;
  8287. ++m_AllocationCount;
  8288. --m_FreeCount;
  8289. m_SumFreeSize -= request.size;
  8290. }
  8291. void VmaBlockMetadata_Buddy::GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo)
  8292. {
  8293. uint32_t level = 0;
  8294. outInfo.offset = (VkDeviceSize)allocHandle - 1;
  8295. const Node* const node = FindAllocationNode(outInfo.offset, level);
  8296. outInfo.size = LevelToNodeSize(level);
  8297. outInfo.pUserData = node->allocation.userData;
  8298. }
  8299. void* VmaBlockMetadata_Buddy::GetAllocationUserData(VmaAllocHandle allocHandle) const
  8300. {
  8301. uint32_t level = 0;
  8302. const Node* const node = FindAllocationNode((VkDeviceSize)allocHandle - 1, level);
  8303. return node->allocation.userData;
  8304. }
  8305. VmaAllocHandle VmaBlockMetadata_Buddy::GetAllocationListBegin() const
  8306. {
  8307. // Function only used for defragmentation, which is disabled for this algorithm
  8308. return VK_NULL_HANDLE;
  8309. }
  8310. VmaAllocHandle VmaBlockMetadata_Buddy::GetNextAllocation(VmaAllocHandle prevAlloc) const
  8311. {
  8312. // Function only used for defragmentation, which is disabled for this algorithm
  8313. return VK_NULL_HANDLE;
  8314. }
  8315. void VmaBlockMetadata_Buddy::DeleteNodeChildren(Node* node)
  8316. {
  8317. if (node->type == Node::TYPE_SPLIT)
  8318. {
  8319. DeleteNodeChildren(node->split.leftChild->buddy);
  8320. DeleteNodeChildren(node->split.leftChild);
  8321. const VkAllocationCallbacks* allocationCallbacks = GetAllocationCallbacks();
  8322. m_NodeAllocator.Free(node->split.leftChild->buddy);
  8323. m_NodeAllocator.Free(node->split.leftChild);
  8324. }
  8325. }
  8326. void VmaBlockMetadata_Buddy::Clear()
  8327. {
  8328. DeleteNodeChildren(m_Root);
  8329. m_Root->type = Node::TYPE_FREE;
  8330. m_AllocationCount = 0;
  8331. m_FreeCount = 1;
  8332. m_SumFreeSize = m_UsableSize;
  8333. }
  8334. void VmaBlockMetadata_Buddy::SetAllocationUserData(VmaAllocHandle allocHandle, void* userData)
  8335. {
  8336. uint32_t level = 0;
  8337. Node* const node = FindAllocationNode((VkDeviceSize)allocHandle - 1, level);
  8338. node->allocation.userData = userData;
  8339. }
  8340. VmaBlockMetadata_Buddy::Node* VmaBlockMetadata_Buddy::FindAllocationNode(VkDeviceSize offset, uint32_t& outLevel) const
  8341. {
  8342. Node* node = m_Root;
  8343. VkDeviceSize nodeOffset = 0;
  8344. outLevel = 0;
  8345. VkDeviceSize levelNodeSize = LevelToNodeSize(0);
  8346. while (node->type == Node::TYPE_SPLIT)
  8347. {
  8348. const VkDeviceSize nextLevelNodeSize = levelNodeSize >> 1;
  8349. if (offset < nodeOffset + nextLevelNodeSize)
  8350. {
  8351. node = node->split.leftChild;
  8352. }
  8353. else
  8354. {
  8355. node = node->split.leftChild->buddy;
  8356. nodeOffset += nextLevelNodeSize;
  8357. }
  8358. ++outLevel;
  8359. levelNodeSize = nextLevelNodeSize;
  8360. }
  8361. VMA_ASSERT(node != VMA_NULL && node->type == Node::TYPE_ALLOCATION);
  8362. return node;
  8363. }
  8364. bool VmaBlockMetadata_Buddy::ValidateNode(ValidationContext& ctx, const Node* parent, const Node* curr, uint32_t level, VkDeviceSize levelNodeSize) const
  8365. {
  8366. VMA_VALIDATE(level < m_LevelCount);
  8367. VMA_VALIDATE(curr->parent == parent);
  8368. VMA_VALIDATE((curr->buddy == VMA_NULL) == (parent == VMA_NULL));
  8369. VMA_VALIDATE(curr->buddy == VMA_NULL || curr->buddy->buddy == curr);
  8370. switch (curr->type)
  8371. {
  8372. case Node::TYPE_FREE:
  8373. // curr->free.prev, next are validated separately.
  8374. ctx.calculatedSumFreeSize += levelNodeSize;
  8375. ++ctx.calculatedFreeCount;
  8376. break;
  8377. case Node::TYPE_ALLOCATION:
  8378. ++ctx.calculatedAllocationCount;
  8379. if (!IsVirtual())
  8380. {
  8381. VMA_VALIDATE(curr->allocation.userData != VMA_NULL);
  8382. }
  8383. break;
  8384. case Node::TYPE_SPLIT:
  8385. {
  8386. const uint32_t childrenLevel = level + 1;
  8387. const VkDeviceSize childrenLevelNodeSize = levelNodeSize >> 1;
  8388. const Node* const leftChild = curr->split.leftChild;
  8389. VMA_VALIDATE(leftChild != VMA_NULL);
  8390. VMA_VALIDATE(leftChild->offset == curr->offset);
  8391. if (!ValidateNode(ctx, curr, leftChild, childrenLevel, childrenLevelNodeSize))
  8392. {
  8393. VMA_VALIDATE(false && "ValidateNode for left child failed.");
  8394. }
  8395. const Node* const rightChild = leftChild->buddy;
  8396. VMA_VALIDATE(rightChild->offset == curr->offset + childrenLevelNodeSize);
  8397. if (!ValidateNode(ctx, curr, rightChild, childrenLevel, childrenLevelNodeSize))
  8398. {
  8399. VMA_VALIDATE(false && "ValidateNode for right child failed.");
  8400. }
  8401. }
  8402. break;
  8403. default:
  8404. return false;
  8405. }
  8406. return true;
  8407. }
  8408. uint32_t VmaBlockMetadata_Buddy::AllocSizeToLevel(VkDeviceSize allocSize) const
  8409. {
  8410. // I know this could be optimized somehow e.g. by using std::log2p1 from C++20.
  8411. uint32_t level = 0;
  8412. VkDeviceSize currLevelNodeSize = m_UsableSize;
  8413. VkDeviceSize nextLevelNodeSize = currLevelNodeSize >> 1;
  8414. while (allocSize <= nextLevelNodeSize && level + 1 < m_LevelCount)
  8415. {
  8416. ++level;
  8417. currLevelNodeSize >>= 1;
  8418. nextLevelNodeSize >>= 1;
  8419. }
  8420. return level;
  8421. }
  8422. void VmaBlockMetadata_Buddy::Free(VmaAllocHandle allocHandle)
  8423. {
  8424. uint32_t level = 0;
  8425. Node* node = FindAllocationNode((VkDeviceSize)allocHandle - 1, level);
  8426. ++m_FreeCount;
  8427. --m_AllocationCount;
  8428. m_SumFreeSize += LevelToNodeSize(level);
  8429. node->type = Node::TYPE_FREE;
  8430. // Join free nodes if possible.
  8431. while (level > 0 && node->buddy->type == Node::TYPE_FREE)
  8432. {
  8433. RemoveFromFreeList(level, node->buddy);
  8434. Node* const parent = node->parent;
  8435. m_NodeAllocator.Free(node->buddy);
  8436. m_NodeAllocator.Free(node);
  8437. parent->type = Node::TYPE_FREE;
  8438. node = parent;
  8439. --level;
  8440. --m_FreeCount;
  8441. }
  8442. AddToFreeListFront(level, node);
  8443. }
  8444. void VmaBlockMetadata_Buddy::AddNodeToDetailedStatistics(VmaDetailedStatistics& inoutStats, const Node* node, VkDeviceSize levelNodeSize) const
  8445. {
  8446. switch (node->type)
  8447. {
  8448. case Node::TYPE_FREE:
  8449. VmaAddDetailedStatisticsUnusedRange(inoutStats, levelNodeSize);
  8450. break;
  8451. case Node::TYPE_ALLOCATION:
  8452. VmaAddDetailedStatisticsAllocation(inoutStats, levelNodeSize);
  8453. break;
  8454. case Node::TYPE_SPLIT:
  8455. {
  8456. const VkDeviceSize childrenNodeSize = levelNodeSize / 2;
  8457. const Node* const leftChild = node->split.leftChild;
  8458. AddNodeToDetailedStatistics(inoutStats, leftChild, childrenNodeSize);
  8459. const Node* const rightChild = leftChild->buddy;
  8460. AddNodeToDetailedStatistics(inoutStats, rightChild, childrenNodeSize);
  8461. }
  8462. break;
  8463. default:
  8464. VMA_ASSERT(0);
  8465. }
  8466. }
  8467. void VmaBlockMetadata_Buddy::AddToFreeListFront(uint32_t level, Node* node)
  8468. {
  8469. VMA_ASSERT(node->type == Node::TYPE_FREE);
  8470. // List is empty.
  8471. Node* const frontNode = m_FreeList[level].front;
  8472. if (frontNode == VMA_NULL)
  8473. {
  8474. VMA_ASSERT(m_FreeList[level].back == VMA_NULL);
  8475. node->free.prev = node->free.next = VMA_NULL;
  8476. m_FreeList[level].front = m_FreeList[level].back = node;
  8477. }
  8478. else
  8479. {
  8480. VMA_ASSERT(frontNode->free.prev == VMA_NULL);
  8481. node->free.prev = VMA_NULL;
  8482. node->free.next = frontNode;
  8483. frontNode->free.prev = node;
  8484. m_FreeList[level].front = node;
  8485. }
  8486. }
  8487. void VmaBlockMetadata_Buddy::RemoveFromFreeList(uint32_t level, Node* node)
  8488. {
  8489. VMA_ASSERT(m_FreeList[level].front != VMA_NULL);
  8490. // It is at the front.
  8491. if (node->free.prev == VMA_NULL)
  8492. {
  8493. VMA_ASSERT(m_FreeList[level].front == node);
  8494. m_FreeList[level].front = node->free.next;
  8495. }
  8496. else
  8497. {
  8498. Node* const prevFreeNode = node->free.prev;
  8499. VMA_ASSERT(prevFreeNode->free.next == node);
  8500. prevFreeNode->free.next = node->free.next;
  8501. }
  8502. // It is at the back.
  8503. if (node->free.next == VMA_NULL)
  8504. {
  8505. VMA_ASSERT(m_FreeList[level].back == node);
  8506. m_FreeList[level].back = node->free.prev;
  8507. }
  8508. else
  8509. {
  8510. Node* const nextFreeNode = node->free.next;
  8511. VMA_ASSERT(nextFreeNode->free.prev == node);
  8512. nextFreeNode->free.prev = node->free.prev;
  8513. }
  8514. }
  8515. void VmaBlockMetadata_Buddy::DebugLogAllAllocationNode(Node* node, uint32_t level) const
  8516. {
  8517. switch (node->type)
  8518. {
  8519. case Node::TYPE_FREE:
  8520. break;
  8521. case Node::TYPE_ALLOCATION:
  8522. DebugLogAllocation(node->offset, LevelToNodeSize(level), node->allocation.userData);
  8523. break;
  8524. case Node::TYPE_SPLIT:
  8525. {
  8526. ++level;
  8527. DebugLogAllAllocationNode(node->split.leftChild, level);
  8528. DebugLogAllAllocationNode(node->split.leftChild->buddy, level);
  8529. }
  8530. break;
  8531. default:
  8532. VMA_ASSERT(0);
  8533. }
  8534. }
  8535. #if VMA_STATS_STRING_ENABLED
  8536. void VmaBlockMetadata_Buddy::PrintDetailedMapNode(class VmaJsonWriter& json, const Node* node, VkDeviceSize levelNodeSize) const
  8537. {
  8538. switch (node->type)
  8539. {
  8540. case Node::TYPE_FREE:
  8541. PrintDetailedMap_UnusedRange(json, node->offset, levelNodeSize);
  8542. break;
  8543. case Node::TYPE_ALLOCATION:
  8544. PrintDetailedMap_Allocation(json, node->offset, levelNodeSize, node->allocation.userData);
  8545. break;
  8546. case Node::TYPE_SPLIT:
  8547. {
  8548. const VkDeviceSize childrenNodeSize = levelNodeSize / 2;
  8549. const Node* const leftChild = node->split.leftChild;
  8550. PrintDetailedMapNode(json, leftChild, childrenNodeSize);
  8551. const Node* const rightChild = leftChild->buddy;
  8552. PrintDetailedMapNode(json, rightChild, childrenNodeSize);
  8553. }
  8554. break;
  8555. default:
  8556. VMA_ASSERT(0);
  8557. }
  8558. }
  8559. #endif // VMA_STATS_STRING_ENABLED
  8560. #endif // _VMA_BLOCK_METADATA_BUDDY_FUNCTIONS
  8561. #endif // _VMA_BLOCK_METADATA_BUDDY
  8562. #endif // #if 0
  8563. #ifndef _VMA_BLOCK_METADATA_TLSF
  8564. // To not search current larger region if first allocation won't succeed and skip to smaller range
  8565. // use with VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT as strategy in CreateAllocationRequest().
  8566. // When fragmentation and reusal of previous blocks doesn't matter then use with
  8567. // VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT for fastest alloc time possible.
  8568. class VmaBlockMetadata_TLSF : public VmaBlockMetadata
  8569. {
  8570. VMA_CLASS_NO_COPY_NO_MOVE(VmaBlockMetadata_TLSF)
  8571. public:
  8572. VmaBlockMetadata_TLSF(const VkAllocationCallbacks* pAllocationCallbacks,
  8573. VkDeviceSize bufferImageGranularity, bool isVirtual);
  8574. virtual ~VmaBlockMetadata_TLSF();
  8575. size_t GetAllocationCount() const override { return m_AllocCount; }
  8576. size_t GetFreeRegionsCount() const override { return m_BlocksFreeCount + 1; }
  8577. VkDeviceSize GetSumFreeSize() const override { return m_BlocksFreeSize + m_NullBlock->size; }
  8578. bool IsEmpty() const override { return m_NullBlock->offset == 0; }
  8579. VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const override { return ((Block*)allocHandle)->offset; }
  8580. void Init(VkDeviceSize size) override;
  8581. bool Validate() const override;
  8582. void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const override;
  8583. void AddStatistics(VmaStatistics& inoutStats) const override;
  8584. #if VMA_STATS_STRING_ENABLED
  8585. void PrintDetailedMap(class VmaJsonWriter& json) const override;
  8586. #endif
  8587. bool CreateAllocationRequest(
  8588. VkDeviceSize allocSize,
  8589. VkDeviceSize allocAlignment,
  8590. bool upperAddress,
  8591. VmaSuballocationType allocType,
  8592. uint32_t strategy,
  8593. VmaAllocationRequest* pAllocationRequest) override;
  8594. VkResult CheckCorruption(const void* pBlockData) override;
  8595. void Alloc(
  8596. const VmaAllocationRequest& request,
  8597. VmaSuballocationType type,
  8598. void* userData) override;
  8599. void Free(VmaAllocHandle allocHandle) override;
  8600. void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) override;
  8601. void* GetAllocationUserData(VmaAllocHandle allocHandle) const override;
  8602. VmaAllocHandle GetAllocationListBegin() const override;
  8603. VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const override;
  8604. VkDeviceSize GetNextFreeRegionSize(VmaAllocHandle alloc) const override;
  8605. void Clear() override;
  8606. void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) override;
  8607. void DebugLogAllAllocations() const override;
  8608. private:
  8609. // According to original paper it should be preferable 4 or 5:
  8610. // M. Masmano, I. Ripoll, A. Crespo, and J. Real "TLSF: a New Dynamic Memory Allocator for Real-Time Systems"
  8611. // http://www.gii.upv.es/tlsf/files/ecrts04_tlsf.pdf
  8612. static const uint8_t SECOND_LEVEL_INDEX = 5;
  8613. static const uint16_t SMALL_BUFFER_SIZE = 256;
  8614. static const uint32_t INITIAL_BLOCK_ALLOC_COUNT = 16;
  8615. static const uint8_t MEMORY_CLASS_SHIFT = 7;
  8616. static const uint8_t MAX_MEMORY_CLASSES = 65 - MEMORY_CLASS_SHIFT;
  8617. class Block
  8618. {
  8619. public:
  8620. VkDeviceSize offset;
  8621. VkDeviceSize size;
  8622. Block* prevPhysical;
  8623. Block* nextPhysical;
  8624. void MarkFree() { prevFree = VMA_NULL; }
  8625. void MarkTaken() { prevFree = this; }
  8626. bool IsFree() const { return prevFree != this; }
  8627. void*& UserData() { VMA_HEAVY_ASSERT(!IsFree()); return userData; }
  8628. Block*& PrevFree() { return prevFree; }
  8629. Block*& NextFree() { VMA_HEAVY_ASSERT(IsFree()); return nextFree; }
  8630. private:
  8631. Block* prevFree; // Address of the same block here indicates that block is taken
  8632. union
  8633. {
  8634. Block* nextFree;
  8635. void* userData;
  8636. };
  8637. };
  8638. size_t m_AllocCount;
  8639. // Total number of free blocks besides null block
  8640. size_t m_BlocksFreeCount;
  8641. // Total size of free blocks excluding null block
  8642. VkDeviceSize m_BlocksFreeSize;
  8643. uint32_t m_IsFreeBitmap;
  8644. uint8_t m_MemoryClasses;
  8645. uint32_t m_InnerIsFreeBitmap[MAX_MEMORY_CLASSES];
  8646. uint32_t m_ListsCount;
  8647. /*
  8648. * 0: 0-3 lists for small buffers
  8649. * 1+: 0-(2^SLI-1) lists for normal buffers
  8650. */
  8651. Block** m_FreeList;
  8652. VmaPoolAllocator<Block> m_BlockAllocator;
  8653. Block* m_NullBlock;
  8654. VmaBlockBufferImageGranularity m_GranularityHandler;
  8655. uint8_t SizeToMemoryClass(VkDeviceSize size) const;
  8656. uint16_t SizeToSecondIndex(VkDeviceSize size, uint8_t memoryClass) const;
  8657. uint32_t GetListIndex(uint8_t memoryClass, uint16_t secondIndex) const;
  8658. uint32_t GetListIndex(VkDeviceSize size) const;
  8659. void RemoveFreeBlock(Block* block);
  8660. void InsertFreeBlock(Block* block);
  8661. void MergeBlock(Block* block, Block* prev);
  8662. Block* FindFreeBlock(VkDeviceSize size, uint32_t& listIndex) const;
  8663. bool CheckBlock(
  8664. Block& block,
  8665. uint32_t listIndex,
  8666. VkDeviceSize allocSize,
  8667. VkDeviceSize allocAlignment,
  8668. VmaSuballocationType allocType,
  8669. VmaAllocationRequest* pAllocationRequest);
  8670. };
  8671. #ifndef _VMA_BLOCK_METADATA_TLSF_FUNCTIONS
  8672. VmaBlockMetadata_TLSF::VmaBlockMetadata_TLSF(const VkAllocationCallbacks* pAllocationCallbacks,
  8673. VkDeviceSize bufferImageGranularity, bool isVirtual)
  8674. : VmaBlockMetadata(pAllocationCallbacks, bufferImageGranularity, isVirtual),
  8675. m_AllocCount(0),
  8676. m_BlocksFreeCount(0),
  8677. m_BlocksFreeSize(0),
  8678. m_IsFreeBitmap(0),
  8679. m_MemoryClasses(0),
  8680. m_ListsCount(0),
  8681. m_FreeList(VMA_NULL),
  8682. m_BlockAllocator(pAllocationCallbacks, INITIAL_BLOCK_ALLOC_COUNT),
  8683. m_NullBlock(VMA_NULL),
  8684. m_GranularityHandler(bufferImageGranularity) {}
  8685. VmaBlockMetadata_TLSF::~VmaBlockMetadata_TLSF()
  8686. {
  8687. if (m_FreeList)
  8688. vma_delete_array(GetAllocationCallbacks(), m_FreeList, m_ListsCount);
  8689. m_GranularityHandler.Destroy(GetAllocationCallbacks());
  8690. }
  8691. void VmaBlockMetadata_TLSF::Init(VkDeviceSize size)
  8692. {
  8693. VmaBlockMetadata::Init(size);
  8694. if (!IsVirtual())
  8695. m_GranularityHandler.Init(GetAllocationCallbacks(), size);
  8696. m_NullBlock = m_BlockAllocator.Alloc();
  8697. m_NullBlock->size = size;
  8698. m_NullBlock->offset = 0;
  8699. m_NullBlock->prevPhysical = VMA_NULL;
  8700. m_NullBlock->nextPhysical = VMA_NULL;
  8701. m_NullBlock->MarkFree();
  8702. m_NullBlock->NextFree() = VMA_NULL;
  8703. m_NullBlock->PrevFree() = VMA_NULL;
  8704. uint8_t memoryClass = SizeToMemoryClass(size);
  8705. uint16_t sli = SizeToSecondIndex(size, memoryClass);
  8706. m_ListsCount = (memoryClass == 0 ? 0 : (memoryClass - 1) * (1UL << SECOND_LEVEL_INDEX) + sli) + 1;
  8707. if (IsVirtual())
  8708. m_ListsCount += 1UL << SECOND_LEVEL_INDEX;
  8709. else
  8710. m_ListsCount += 4;
  8711. m_MemoryClasses = memoryClass + uint8_t(2);
  8712. memset(m_InnerIsFreeBitmap, 0, MAX_MEMORY_CLASSES * sizeof(uint32_t));
  8713. m_FreeList = vma_new_array(GetAllocationCallbacks(), Block*, m_ListsCount);
  8714. memset(m_FreeList, 0, m_ListsCount * sizeof(Block*));
  8715. }
  8716. bool VmaBlockMetadata_TLSF::Validate() const
  8717. {
  8718. VMA_VALIDATE(GetSumFreeSize() <= GetSize());
  8719. VkDeviceSize calculatedSize = m_NullBlock->size;
  8720. VkDeviceSize calculatedFreeSize = m_NullBlock->size;
  8721. size_t allocCount = 0;
  8722. size_t freeCount = 0;
  8723. // Check integrity of free lists
  8724. for (uint32_t list = 0; list < m_ListsCount; ++list)
  8725. {
  8726. Block* block = m_FreeList[list];
  8727. if (block != VMA_NULL)
  8728. {
  8729. VMA_VALIDATE(block->IsFree());
  8730. VMA_VALIDATE(block->PrevFree() == VMA_NULL);
  8731. while (block->NextFree())
  8732. {
  8733. VMA_VALIDATE(block->NextFree()->IsFree());
  8734. VMA_VALIDATE(block->NextFree()->PrevFree() == block);
  8735. block = block->NextFree();
  8736. }
  8737. }
  8738. }
  8739. VkDeviceSize nextOffset = m_NullBlock->offset;
  8740. auto validateCtx = m_GranularityHandler.StartValidation(GetAllocationCallbacks(), IsVirtual());
  8741. VMA_VALIDATE(m_NullBlock->nextPhysical == VMA_NULL);
  8742. if (m_NullBlock->prevPhysical)
  8743. {
  8744. VMA_VALIDATE(m_NullBlock->prevPhysical->nextPhysical == m_NullBlock);
  8745. }
  8746. // Check all blocks
  8747. for (Block* prev = m_NullBlock->prevPhysical; prev != VMA_NULL; prev = prev->prevPhysical)
  8748. {
  8749. VMA_VALIDATE(prev->offset + prev->size == nextOffset);
  8750. nextOffset = prev->offset;
  8751. calculatedSize += prev->size;
  8752. uint32_t listIndex = GetListIndex(prev->size);
  8753. if (prev->IsFree())
  8754. {
  8755. ++freeCount;
  8756. // Check if free block belongs to free list
  8757. Block* freeBlock = m_FreeList[listIndex];
  8758. VMA_VALIDATE(freeBlock != VMA_NULL);
  8759. bool found = false;
  8760. do
  8761. {
  8762. if (freeBlock == prev)
  8763. found = true;
  8764. freeBlock = freeBlock->NextFree();
  8765. } while (!found && freeBlock != VMA_NULL);
  8766. VMA_VALIDATE(found);
  8767. calculatedFreeSize += prev->size;
  8768. }
  8769. else
  8770. {
  8771. ++allocCount;
  8772. // Check if taken block is not on a free list
  8773. Block* freeBlock = m_FreeList[listIndex];
  8774. while (freeBlock)
  8775. {
  8776. VMA_VALIDATE(freeBlock != prev);
  8777. freeBlock = freeBlock->NextFree();
  8778. }
  8779. if (!IsVirtual())
  8780. {
  8781. VMA_VALIDATE(m_GranularityHandler.Validate(validateCtx, prev->offset, prev->size));
  8782. }
  8783. }
  8784. if (prev->prevPhysical)
  8785. {
  8786. VMA_VALIDATE(prev->prevPhysical->nextPhysical == prev);
  8787. }
  8788. }
  8789. if (!IsVirtual())
  8790. {
  8791. VMA_VALIDATE(m_GranularityHandler.FinishValidation(validateCtx));
  8792. }
  8793. VMA_VALIDATE(nextOffset == 0);
  8794. VMA_VALIDATE(calculatedSize == GetSize());
  8795. VMA_VALIDATE(calculatedFreeSize == GetSumFreeSize());
  8796. VMA_VALIDATE(allocCount == m_AllocCount);
  8797. VMA_VALIDATE(freeCount == m_BlocksFreeCount);
  8798. return true;
  8799. }
  8800. void VmaBlockMetadata_TLSF::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const
  8801. {
  8802. inoutStats.statistics.blockCount++;
  8803. inoutStats.statistics.blockBytes += GetSize();
  8804. if (m_NullBlock->size > 0)
  8805. VmaAddDetailedStatisticsUnusedRange(inoutStats, m_NullBlock->size);
  8806. for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical)
  8807. {
  8808. if (block->IsFree())
  8809. VmaAddDetailedStatisticsUnusedRange(inoutStats, block->size);
  8810. else
  8811. VmaAddDetailedStatisticsAllocation(inoutStats, block->size);
  8812. }
  8813. }
  8814. void VmaBlockMetadata_TLSF::AddStatistics(VmaStatistics& inoutStats) const
  8815. {
  8816. inoutStats.blockCount++;
  8817. inoutStats.allocationCount += (uint32_t)m_AllocCount;
  8818. inoutStats.blockBytes += GetSize();
  8819. inoutStats.allocationBytes += GetSize() - GetSumFreeSize();
  8820. }
  8821. #if VMA_STATS_STRING_ENABLED
  8822. void VmaBlockMetadata_TLSF::PrintDetailedMap(class VmaJsonWriter& json) const
  8823. {
  8824. size_t blockCount = m_AllocCount + m_BlocksFreeCount;
  8825. VmaStlAllocator<Block*> allocator(GetAllocationCallbacks());
  8826. VmaVector<Block*, VmaStlAllocator<Block*>> blockList(blockCount, allocator);
  8827. size_t i = blockCount;
  8828. for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical)
  8829. {
  8830. blockList[--i] = block;
  8831. }
  8832. VMA_ASSERT(i == 0);
  8833. VmaDetailedStatistics stats;
  8834. VmaClearDetailedStatistics(stats);
  8835. AddDetailedStatistics(stats);
  8836. PrintDetailedMap_Begin(json,
  8837. stats.statistics.blockBytes - stats.statistics.allocationBytes,
  8838. stats.statistics.allocationCount,
  8839. stats.unusedRangeCount);
  8840. for (; i < blockCount; ++i)
  8841. {
  8842. Block* block = blockList[i];
  8843. if (block->IsFree())
  8844. PrintDetailedMap_UnusedRange(json, block->offset, block->size);
  8845. else
  8846. PrintDetailedMap_Allocation(json, block->offset, block->size, block->UserData());
  8847. }
  8848. if (m_NullBlock->size > 0)
  8849. PrintDetailedMap_UnusedRange(json, m_NullBlock->offset, m_NullBlock->size);
  8850. PrintDetailedMap_End(json);
  8851. }
  8852. #endif
  8853. bool VmaBlockMetadata_TLSF::CreateAllocationRequest(
  8854. VkDeviceSize allocSize,
  8855. VkDeviceSize allocAlignment,
  8856. bool upperAddress,
  8857. VmaSuballocationType allocType,
  8858. uint32_t strategy,
  8859. VmaAllocationRequest* pAllocationRequest)
  8860. {
  8861. VMA_ASSERT(allocSize > 0 && "Cannot allocate empty block!");
  8862. VMA_ASSERT(!upperAddress && "VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT can be used only with linear algorithm.");
  8863. // For small granularity round up
  8864. if (!IsVirtual())
  8865. m_GranularityHandler.RoundupAllocRequest(allocType, allocSize, allocAlignment);
  8866. allocSize += GetDebugMargin();
  8867. // Quick check for too small pool
  8868. if (allocSize > GetSumFreeSize())
  8869. return false;
  8870. // If no free blocks in pool then check only null block
  8871. if (m_BlocksFreeCount == 0)
  8872. return CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest);
  8873. // Round up to the next block
  8874. VkDeviceSize sizeForNextList = allocSize;
  8875. VkDeviceSize smallSizeStep = VkDeviceSize(SMALL_BUFFER_SIZE / (IsVirtual() ? 1 << SECOND_LEVEL_INDEX : 4));
  8876. if (allocSize > SMALL_BUFFER_SIZE)
  8877. {
  8878. sizeForNextList += (1ULL << (VMA_BITSCAN_MSB(allocSize) - SECOND_LEVEL_INDEX));
  8879. }
  8880. else if (allocSize > SMALL_BUFFER_SIZE - smallSizeStep)
  8881. sizeForNextList = SMALL_BUFFER_SIZE + 1;
  8882. else
  8883. sizeForNextList += smallSizeStep;
  8884. uint32_t nextListIndex = m_ListsCount;
  8885. uint32_t prevListIndex = m_ListsCount;
  8886. Block* nextListBlock = VMA_NULL;
  8887. Block* prevListBlock = VMA_NULL;
  8888. // Check blocks according to strategies
  8889. if (strategy & VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT)
  8890. {
  8891. // Quick check for larger block first
  8892. nextListBlock = FindFreeBlock(sizeForNextList, nextListIndex);
  8893. if (nextListBlock != VMA_NULL && CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8894. return true;
  8895. // If not fitted then null block
  8896. if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest))
  8897. return true;
  8898. // Null block failed, search larger bucket
  8899. while (nextListBlock)
  8900. {
  8901. if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8902. return true;
  8903. nextListBlock = nextListBlock->NextFree();
  8904. }
  8905. // Failed again, check best fit bucket
  8906. prevListBlock = FindFreeBlock(allocSize, prevListIndex);
  8907. while (prevListBlock)
  8908. {
  8909. if (CheckBlock(*prevListBlock, prevListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8910. return true;
  8911. prevListBlock = prevListBlock->NextFree();
  8912. }
  8913. }
  8914. else if (strategy & VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT)
  8915. {
  8916. // Check best fit bucket
  8917. prevListBlock = FindFreeBlock(allocSize, prevListIndex);
  8918. while (prevListBlock)
  8919. {
  8920. if (CheckBlock(*prevListBlock, prevListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8921. return true;
  8922. prevListBlock = prevListBlock->NextFree();
  8923. }
  8924. // If failed check null block
  8925. if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest))
  8926. return true;
  8927. // Check larger bucket
  8928. nextListBlock = FindFreeBlock(sizeForNextList, nextListIndex);
  8929. while (nextListBlock)
  8930. {
  8931. if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8932. return true;
  8933. nextListBlock = nextListBlock->NextFree();
  8934. }
  8935. }
  8936. else if (strategy & VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT )
  8937. {
  8938. // Perform search from the start
  8939. VmaStlAllocator<Block*> allocator(GetAllocationCallbacks());
  8940. VmaVector<Block*, VmaStlAllocator<Block*>> blockList(m_BlocksFreeCount, allocator);
  8941. size_t i = m_BlocksFreeCount;
  8942. for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical)
  8943. {
  8944. if (block->IsFree() && block->size >= allocSize)
  8945. blockList[--i] = block;
  8946. }
  8947. for (; i < m_BlocksFreeCount; ++i)
  8948. {
  8949. Block& block = *blockList[i];
  8950. if (CheckBlock(block, GetListIndex(block.size), allocSize, allocAlignment, allocType, pAllocationRequest))
  8951. return true;
  8952. }
  8953. // If failed check null block
  8954. if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest))
  8955. return true;
  8956. // Whole range searched, no more memory
  8957. return false;
  8958. }
  8959. else
  8960. {
  8961. // Check larger bucket
  8962. nextListBlock = FindFreeBlock(sizeForNextList, nextListIndex);
  8963. while (nextListBlock)
  8964. {
  8965. if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8966. return true;
  8967. nextListBlock = nextListBlock->NextFree();
  8968. }
  8969. // If failed check null block
  8970. if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest))
  8971. return true;
  8972. // Check best fit bucket
  8973. prevListBlock = FindFreeBlock(allocSize, prevListIndex);
  8974. while (prevListBlock)
  8975. {
  8976. if (CheckBlock(*prevListBlock, prevListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8977. return true;
  8978. prevListBlock = prevListBlock->NextFree();
  8979. }
  8980. }
  8981. // Worst case, full search has to be done
  8982. while (++nextListIndex < m_ListsCount)
  8983. {
  8984. nextListBlock = m_FreeList[nextListIndex];
  8985. while (nextListBlock)
  8986. {
  8987. if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest))
  8988. return true;
  8989. nextListBlock = nextListBlock->NextFree();
  8990. }
  8991. }
  8992. // No more memory sadly
  8993. return false;
  8994. }
  8995. VkResult VmaBlockMetadata_TLSF::CheckCorruption(const void* pBlockData)
  8996. {
  8997. for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical)
  8998. {
  8999. if (!block->IsFree())
  9000. {
  9001. if (!VmaValidateMagicValue(pBlockData, block->offset + block->size))
  9002. {
  9003. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
  9004. return VK_ERROR_UNKNOWN_COPY;
  9005. }
  9006. }
  9007. }
  9008. return VK_SUCCESS;
  9009. }
  9010. void VmaBlockMetadata_TLSF::Alloc(
  9011. const VmaAllocationRequest& request,
  9012. VmaSuballocationType type,
  9013. void* userData)
  9014. {
  9015. VMA_ASSERT(request.type == VmaAllocationRequestType::TLSF);
  9016. // Get block and pop it from the free list
  9017. Block* currentBlock = (Block*)request.allocHandle;
  9018. VkDeviceSize offset = request.algorithmData;
  9019. VMA_ASSERT(currentBlock != VMA_NULL);
  9020. VMA_ASSERT(currentBlock->offset <= offset);
  9021. if (currentBlock != m_NullBlock)
  9022. RemoveFreeBlock(currentBlock);
  9023. VkDeviceSize debugMargin = GetDebugMargin();
  9024. VkDeviceSize misssingAlignment = offset - currentBlock->offset;
  9025. // Append missing alignment to prev block or create new one
  9026. if (misssingAlignment)
  9027. {
  9028. Block* prevBlock = currentBlock->prevPhysical;
  9029. VMA_ASSERT(prevBlock != VMA_NULL && "There should be no missing alignment at offset 0!");
  9030. if (prevBlock->IsFree() && prevBlock->size != debugMargin)
  9031. {
  9032. uint32_t oldList = GetListIndex(prevBlock->size);
  9033. prevBlock->size += misssingAlignment;
  9034. // Check if new size crosses list bucket
  9035. if (oldList != GetListIndex(prevBlock->size))
  9036. {
  9037. prevBlock->size -= misssingAlignment;
  9038. RemoveFreeBlock(prevBlock);
  9039. prevBlock->size += misssingAlignment;
  9040. InsertFreeBlock(prevBlock);
  9041. }
  9042. else
  9043. m_BlocksFreeSize += misssingAlignment;
  9044. }
  9045. else
  9046. {
  9047. Block* newBlock = m_BlockAllocator.Alloc();
  9048. currentBlock->prevPhysical = newBlock;
  9049. prevBlock->nextPhysical = newBlock;
  9050. newBlock->prevPhysical = prevBlock;
  9051. newBlock->nextPhysical = currentBlock;
  9052. newBlock->size = misssingAlignment;
  9053. newBlock->offset = currentBlock->offset;
  9054. newBlock->MarkTaken();
  9055. InsertFreeBlock(newBlock);
  9056. }
  9057. currentBlock->size -= misssingAlignment;
  9058. currentBlock->offset += misssingAlignment;
  9059. }
  9060. VkDeviceSize size = request.size + debugMargin;
  9061. if (currentBlock->size == size)
  9062. {
  9063. if (currentBlock == m_NullBlock)
  9064. {
  9065. // Setup new null block
  9066. m_NullBlock = m_BlockAllocator.Alloc();
  9067. m_NullBlock->size = 0;
  9068. m_NullBlock->offset = currentBlock->offset + size;
  9069. m_NullBlock->prevPhysical = currentBlock;
  9070. m_NullBlock->nextPhysical = VMA_NULL;
  9071. m_NullBlock->MarkFree();
  9072. m_NullBlock->PrevFree() = VMA_NULL;
  9073. m_NullBlock->NextFree() = VMA_NULL;
  9074. currentBlock->nextPhysical = m_NullBlock;
  9075. currentBlock->MarkTaken();
  9076. }
  9077. }
  9078. else
  9079. {
  9080. VMA_ASSERT(currentBlock->size > size && "Proper block already found, shouldn't find smaller one!");
  9081. // Create new free block
  9082. Block* newBlock = m_BlockAllocator.Alloc();
  9083. newBlock->size = currentBlock->size - size;
  9084. newBlock->offset = currentBlock->offset + size;
  9085. newBlock->prevPhysical = currentBlock;
  9086. newBlock->nextPhysical = currentBlock->nextPhysical;
  9087. currentBlock->nextPhysical = newBlock;
  9088. currentBlock->size = size;
  9089. if (currentBlock == m_NullBlock)
  9090. {
  9091. m_NullBlock = newBlock;
  9092. m_NullBlock->MarkFree();
  9093. m_NullBlock->NextFree() = VMA_NULL;
  9094. m_NullBlock->PrevFree() = VMA_NULL;
  9095. currentBlock->MarkTaken();
  9096. }
  9097. else
  9098. {
  9099. newBlock->nextPhysical->prevPhysical = newBlock;
  9100. newBlock->MarkTaken();
  9101. InsertFreeBlock(newBlock);
  9102. }
  9103. }
  9104. currentBlock->UserData() = userData;
  9105. if (debugMargin > 0)
  9106. {
  9107. currentBlock->size -= debugMargin;
  9108. Block* newBlock = m_BlockAllocator.Alloc();
  9109. newBlock->size = debugMargin;
  9110. newBlock->offset = currentBlock->offset + currentBlock->size;
  9111. newBlock->prevPhysical = currentBlock;
  9112. newBlock->nextPhysical = currentBlock->nextPhysical;
  9113. newBlock->MarkTaken();
  9114. currentBlock->nextPhysical->prevPhysical = newBlock;
  9115. currentBlock->nextPhysical = newBlock;
  9116. InsertFreeBlock(newBlock);
  9117. }
  9118. if (!IsVirtual())
  9119. m_GranularityHandler.AllocPages((uint8_t)(uintptr_t)request.customData,
  9120. currentBlock->offset, currentBlock->size);
  9121. ++m_AllocCount;
  9122. }
  9123. void VmaBlockMetadata_TLSF::Free(VmaAllocHandle allocHandle)
  9124. {
  9125. Block* block = (Block*)allocHandle;
  9126. Block* next = block->nextPhysical;
  9127. VMA_ASSERT(!block->IsFree() && "Block is already free!");
  9128. if (!IsVirtual())
  9129. m_GranularityHandler.FreePages(block->offset, block->size);
  9130. --m_AllocCount;
  9131. VkDeviceSize debugMargin = GetDebugMargin();
  9132. if (debugMargin > 0)
  9133. {
  9134. RemoveFreeBlock(next);
  9135. MergeBlock(next, block);
  9136. block = next;
  9137. next = next->nextPhysical;
  9138. }
  9139. // Try merging
  9140. Block* prev = block->prevPhysical;
  9141. if (prev != VMA_NULL && prev->IsFree() && prev->size != debugMargin)
  9142. {
  9143. RemoveFreeBlock(prev);
  9144. MergeBlock(block, prev);
  9145. }
  9146. if (!next->IsFree())
  9147. InsertFreeBlock(block);
  9148. else if (next == m_NullBlock)
  9149. MergeBlock(m_NullBlock, block);
  9150. else
  9151. {
  9152. RemoveFreeBlock(next);
  9153. MergeBlock(next, block);
  9154. InsertFreeBlock(next);
  9155. }
  9156. }
  9157. void VmaBlockMetadata_TLSF::GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo)
  9158. {
  9159. Block* block = (Block*)allocHandle;
  9160. VMA_ASSERT(!block->IsFree() && "Cannot get allocation info for free block!");
  9161. outInfo.offset = block->offset;
  9162. outInfo.size = block->size;
  9163. outInfo.pUserData = block->UserData();
  9164. }
  9165. void* VmaBlockMetadata_TLSF::GetAllocationUserData(VmaAllocHandle allocHandle) const
  9166. {
  9167. Block* block = (Block*)allocHandle;
  9168. VMA_ASSERT(!block->IsFree() && "Cannot get user data for free block!");
  9169. return block->UserData();
  9170. }
  9171. VmaAllocHandle VmaBlockMetadata_TLSF::GetAllocationListBegin() const
  9172. {
  9173. if (m_AllocCount == 0)
  9174. return VK_NULL_HANDLE;
  9175. for (Block* block = m_NullBlock->prevPhysical; block; block = block->prevPhysical)
  9176. {
  9177. if (!block->IsFree())
  9178. return (VmaAllocHandle)block;
  9179. }
  9180. VMA_ASSERT(false && "If m_AllocCount > 0 then should find any allocation!");
  9181. return VK_NULL_HANDLE;
  9182. }
  9183. VmaAllocHandle VmaBlockMetadata_TLSF::GetNextAllocation(VmaAllocHandle prevAlloc) const
  9184. {
  9185. Block* startBlock = (Block*)prevAlloc;
  9186. VMA_ASSERT(!startBlock->IsFree() && "Incorrect block!");
  9187. for (Block* block = startBlock->prevPhysical; block; block = block->prevPhysical)
  9188. {
  9189. if (!block->IsFree())
  9190. return (VmaAllocHandle)block;
  9191. }
  9192. return VK_NULL_HANDLE;
  9193. }
  9194. VkDeviceSize VmaBlockMetadata_TLSF::GetNextFreeRegionSize(VmaAllocHandle alloc) const
  9195. {
  9196. Block* block = (Block*)alloc;
  9197. VMA_ASSERT(!block->IsFree() && "Incorrect block!");
  9198. if (block->prevPhysical)
  9199. return block->prevPhysical->IsFree() ? block->prevPhysical->size : 0;
  9200. return 0;
  9201. }
  9202. void VmaBlockMetadata_TLSF::Clear()
  9203. {
  9204. m_AllocCount = 0;
  9205. m_BlocksFreeCount = 0;
  9206. m_BlocksFreeSize = 0;
  9207. m_IsFreeBitmap = 0;
  9208. m_NullBlock->offset = 0;
  9209. m_NullBlock->size = GetSize();
  9210. Block* block = m_NullBlock->prevPhysical;
  9211. m_NullBlock->prevPhysical = VMA_NULL;
  9212. while (block)
  9213. {
  9214. Block* prev = block->prevPhysical;
  9215. m_BlockAllocator.Free(block);
  9216. block = prev;
  9217. }
  9218. memset(m_FreeList, 0, m_ListsCount * sizeof(Block*));
  9219. memset(m_InnerIsFreeBitmap, 0, m_MemoryClasses * sizeof(uint32_t));
  9220. m_GranularityHandler.Clear();
  9221. }
  9222. void VmaBlockMetadata_TLSF::SetAllocationUserData(VmaAllocHandle allocHandle, void* userData)
  9223. {
  9224. Block* block = (Block*)allocHandle;
  9225. VMA_ASSERT(!block->IsFree() && "Trying to set user data for not allocated block!");
  9226. block->UserData() = userData;
  9227. }
  9228. void VmaBlockMetadata_TLSF::DebugLogAllAllocations() const
  9229. {
  9230. for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical)
  9231. if (!block->IsFree())
  9232. DebugLogAllocation(block->offset, block->size, block->UserData());
  9233. }
  9234. uint8_t VmaBlockMetadata_TLSF::SizeToMemoryClass(VkDeviceSize size) const
  9235. {
  9236. if (size > SMALL_BUFFER_SIZE)
  9237. return uint8_t(VMA_BITSCAN_MSB(size) - MEMORY_CLASS_SHIFT);
  9238. return 0;
  9239. }
  9240. uint16_t VmaBlockMetadata_TLSF::SizeToSecondIndex(VkDeviceSize size, uint8_t memoryClass) const
  9241. {
  9242. if (memoryClass == 0)
  9243. {
  9244. if (IsVirtual())
  9245. return static_cast<uint16_t>((size - 1) / 8);
  9246. else
  9247. return static_cast<uint16_t>((size - 1) / 64);
  9248. }
  9249. return static_cast<uint16_t>((size >> (memoryClass + MEMORY_CLASS_SHIFT - SECOND_LEVEL_INDEX)) ^ (1U << SECOND_LEVEL_INDEX));
  9250. }
  9251. uint32_t VmaBlockMetadata_TLSF::GetListIndex(uint8_t memoryClass, uint16_t secondIndex) const
  9252. {
  9253. if (memoryClass == 0)
  9254. return secondIndex;
  9255. const uint32_t index = static_cast<uint32_t>(memoryClass - 1) * (1 << SECOND_LEVEL_INDEX) + secondIndex;
  9256. if (IsVirtual())
  9257. return index + (1 << SECOND_LEVEL_INDEX);
  9258. else
  9259. return index + 4;
  9260. }
  9261. uint32_t VmaBlockMetadata_TLSF::GetListIndex(VkDeviceSize size) const
  9262. {
  9263. uint8_t memoryClass = SizeToMemoryClass(size);
  9264. return GetListIndex(memoryClass, SizeToSecondIndex(size, memoryClass));
  9265. }
  9266. void VmaBlockMetadata_TLSF::RemoveFreeBlock(Block* block)
  9267. {
  9268. VMA_ASSERT(block != m_NullBlock);
  9269. VMA_ASSERT(block->IsFree());
  9270. if (block->NextFree() != VMA_NULL)
  9271. block->NextFree()->PrevFree() = block->PrevFree();
  9272. if (block->PrevFree() != VMA_NULL)
  9273. block->PrevFree()->NextFree() = block->NextFree();
  9274. else
  9275. {
  9276. uint8_t memClass = SizeToMemoryClass(block->size);
  9277. uint16_t secondIndex = SizeToSecondIndex(block->size, memClass);
  9278. uint32_t index = GetListIndex(memClass, secondIndex);
  9279. VMA_ASSERT(m_FreeList[index] == block);
  9280. m_FreeList[index] = block->NextFree();
  9281. if (block->NextFree() == VMA_NULL)
  9282. {
  9283. m_InnerIsFreeBitmap[memClass] &= ~(1U << secondIndex);
  9284. if (m_InnerIsFreeBitmap[memClass] == 0)
  9285. m_IsFreeBitmap &= ~(1UL << memClass);
  9286. }
  9287. }
  9288. block->MarkTaken();
  9289. block->UserData() = VMA_NULL;
  9290. --m_BlocksFreeCount;
  9291. m_BlocksFreeSize -= block->size;
  9292. }
  9293. void VmaBlockMetadata_TLSF::InsertFreeBlock(Block* block)
  9294. {
  9295. VMA_ASSERT(block != m_NullBlock);
  9296. VMA_ASSERT(!block->IsFree() && "Cannot insert block twice!");
  9297. uint8_t memClass = SizeToMemoryClass(block->size);
  9298. uint16_t secondIndex = SizeToSecondIndex(block->size, memClass);
  9299. uint32_t index = GetListIndex(memClass, secondIndex);
  9300. VMA_ASSERT(index < m_ListsCount);
  9301. block->PrevFree() = VMA_NULL;
  9302. block->NextFree() = m_FreeList[index];
  9303. m_FreeList[index] = block;
  9304. if (block->NextFree() != VMA_NULL)
  9305. block->NextFree()->PrevFree() = block;
  9306. else
  9307. {
  9308. m_InnerIsFreeBitmap[memClass] |= 1U << secondIndex;
  9309. m_IsFreeBitmap |= 1UL << memClass;
  9310. }
  9311. ++m_BlocksFreeCount;
  9312. m_BlocksFreeSize += block->size;
  9313. }
  9314. void VmaBlockMetadata_TLSF::MergeBlock(Block* block, Block* prev)
  9315. {
  9316. VMA_ASSERT(block->prevPhysical == prev && "Cannot merge separate physical regions!");
  9317. VMA_ASSERT(!prev->IsFree() && "Cannot merge block that belongs to free list!");
  9318. block->offset = prev->offset;
  9319. block->size += prev->size;
  9320. block->prevPhysical = prev->prevPhysical;
  9321. if (block->prevPhysical)
  9322. block->prevPhysical->nextPhysical = block;
  9323. m_BlockAllocator.Free(prev);
  9324. }
  9325. VmaBlockMetadata_TLSF::Block* VmaBlockMetadata_TLSF::FindFreeBlock(VkDeviceSize size, uint32_t& listIndex) const
  9326. {
  9327. uint8_t memoryClass = SizeToMemoryClass(size);
  9328. uint32_t innerFreeMap = m_InnerIsFreeBitmap[memoryClass] & (~0U << SizeToSecondIndex(size, memoryClass));
  9329. if (!innerFreeMap)
  9330. {
  9331. // Check higher levels for available blocks
  9332. uint32_t freeMap = m_IsFreeBitmap & (~0UL << (memoryClass + 1));
  9333. if (!freeMap)
  9334. return VMA_NULL; // No more memory available
  9335. // Find lowest free region
  9336. memoryClass = VMA_BITSCAN_LSB(freeMap);
  9337. innerFreeMap = m_InnerIsFreeBitmap[memoryClass];
  9338. VMA_ASSERT(innerFreeMap != 0);
  9339. }
  9340. // Find lowest free subregion
  9341. listIndex = GetListIndex(memoryClass, VMA_BITSCAN_LSB(innerFreeMap));
  9342. VMA_ASSERT(m_FreeList[listIndex]);
  9343. return m_FreeList[listIndex];
  9344. }
  9345. bool VmaBlockMetadata_TLSF::CheckBlock(
  9346. Block& block,
  9347. uint32_t listIndex,
  9348. VkDeviceSize allocSize,
  9349. VkDeviceSize allocAlignment,
  9350. VmaSuballocationType allocType,
  9351. VmaAllocationRequest* pAllocationRequest)
  9352. {
  9353. VMA_ASSERT(block.IsFree() && "Block is already taken!");
  9354. VkDeviceSize alignedOffset = VmaAlignUp(block.offset, allocAlignment);
  9355. if (block.size < allocSize + alignedOffset - block.offset)
  9356. return false;
  9357. // Check for granularity conflicts
  9358. if (!IsVirtual() &&
  9359. m_GranularityHandler.CheckConflictAndAlignUp(alignedOffset, allocSize, block.offset, block.size, allocType))
  9360. return false;
  9361. // Alloc successful
  9362. pAllocationRequest->type = VmaAllocationRequestType::TLSF;
  9363. pAllocationRequest->allocHandle = (VmaAllocHandle)&block;
  9364. pAllocationRequest->size = allocSize - GetDebugMargin();
  9365. pAllocationRequest->customData = (void*)allocType;
  9366. pAllocationRequest->algorithmData = alignedOffset;
  9367. // Place block at the start of list if it's normal block
  9368. if (listIndex != m_ListsCount && block.PrevFree())
  9369. {
  9370. block.PrevFree()->NextFree() = block.NextFree();
  9371. if (block.NextFree())
  9372. block.NextFree()->PrevFree() = block.PrevFree();
  9373. block.PrevFree() = VMA_NULL;
  9374. block.NextFree() = m_FreeList[listIndex];
  9375. m_FreeList[listIndex] = &block;
  9376. if (block.NextFree())
  9377. block.NextFree()->PrevFree() = &block;
  9378. }
  9379. return true;
  9380. }
  9381. #endif // _VMA_BLOCK_METADATA_TLSF_FUNCTIONS
  9382. #endif // _VMA_BLOCK_METADATA_TLSF
  9383. #ifndef _VMA_BLOCK_VECTOR
  9384. /*
  9385. Sequence of VmaDeviceMemoryBlock. Represents memory blocks allocated for a specific
  9386. Vulkan memory type.
  9387. Synchronized internally with a mutex.
  9388. */
  9389. class VmaBlockVector
  9390. {
  9391. friend struct VmaDefragmentationContext_T;
  9392. VMA_CLASS_NO_COPY_NO_MOVE(VmaBlockVector)
  9393. public:
  9394. VmaBlockVector(
  9395. VmaAllocator hAllocator,
  9396. VmaPool hParentPool,
  9397. uint32_t memoryTypeIndex,
  9398. VkDeviceSize preferredBlockSize,
  9399. size_t minBlockCount,
  9400. size_t maxBlockCount,
  9401. VkDeviceSize bufferImageGranularity,
  9402. bool explicitBlockSize,
  9403. uint32_t algorithm,
  9404. float priority,
  9405. VkDeviceSize minAllocationAlignment,
  9406. void* pMemoryAllocateNext);
  9407. ~VmaBlockVector();
  9408. VmaAllocator GetAllocator() const { return m_hAllocator; }
  9409. VmaPool GetParentPool() const { return m_hParentPool; }
  9410. bool IsCustomPool() const { return m_hParentPool != VMA_NULL; }
  9411. uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
  9412. VkDeviceSize GetPreferredBlockSize() const { return m_PreferredBlockSize; }
  9413. VkDeviceSize GetBufferImageGranularity() const { return m_BufferImageGranularity; }
  9414. uint32_t GetAlgorithm() const { return m_Algorithm; }
  9415. bool HasExplicitBlockSize() const { return m_ExplicitBlockSize; }
  9416. float GetPriority() const { return m_Priority; }
  9417. const void* GetAllocationNextPtr() const { return m_pMemoryAllocateNext; }
  9418. // To be used only while the m_Mutex is locked. Used during defragmentation.
  9419. size_t GetBlockCount() const { return m_Blocks.size(); }
  9420. // To be used only while the m_Mutex is locked. Used during defragmentation.
  9421. VmaDeviceMemoryBlock* GetBlock(size_t index) const { return m_Blocks[index]; }
  9422. VMA_RW_MUTEX &GetMutex() { return m_Mutex; }
  9423. VkResult CreateMinBlocks();
  9424. void AddStatistics(VmaStatistics& inoutStats);
  9425. void AddDetailedStatistics(VmaDetailedStatistics& inoutStats);
  9426. bool IsEmpty();
  9427. bool IsCorruptionDetectionEnabled() const;
  9428. VkResult Allocate(
  9429. VkDeviceSize size,
  9430. VkDeviceSize alignment,
  9431. const VmaAllocationCreateInfo& createInfo,
  9432. VmaSuballocationType suballocType,
  9433. size_t allocationCount,
  9434. VmaAllocation* pAllocations);
  9435. void Free(const VmaAllocation hAllocation);
  9436. #if VMA_STATS_STRING_ENABLED
  9437. void PrintDetailedMap(class VmaJsonWriter& json);
  9438. #endif
  9439. VkResult CheckCorruption();
  9440. private:
  9441. const VmaAllocator m_hAllocator;
  9442. const VmaPool m_hParentPool;
  9443. const uint32_t m_MemoryTypeIndex;
  9444. const VkDeviceSize m_PreferredBlockSize;
  9445. const size_t m_MinBlockCount;
  9446. const size_t m_MaxBlockCount;
  9447. const VkDeviceSize m_BufferImageGranularity;
  9448. const bool m_ExplicitBlockSize;
  9449. const uint32_t m_Algorithm;
  9450. const float m_Priority;
  9451. const VkDeviceSize m_MinAllocationAlignment;
  9452. void* const m_pMemoryAllocateNext;
  9453. VMA_RW_MUTEX m_Mutex;
  9454. // Incrementally sorted by sumFreeSize, ascending.
  9455. VmaVector<VmaDeviceMemoryBlock*, VmaStlAllocator<VmaDeviceMemoryBlock*>> m_Blocks;
  9456. uint32_t m_NextBlockId;
  9457. bool m_IncrementalSort = true;
  9458. void SetIncrementalSort(bool val) { m_IncrementalSort = val; }
  9459. VkDeviceSize CalcMaxBlockSize() const;
  9460. // Finds and removes given block from vector.
  9461. void Remove(VmaDeviceMemoryBlock* pBlock);
  9462. // Performs single step in sorting m_Blocks. They may not be fully sorted
  9463. // after this call.
  9464. void IncrementallySortBlocks();
  9465. void SortByFreeSize();
  9466. VkResult AllocatePage(
  9467. VkDeviceSize size,
  9468. VkDeviceSize alignment,
  9469. const VmaAllocationCreateInfo& createInfo,
  9470. VmaSuballocationType suballocType,
  9471. VmaAllocation* pAllocation);
  9472. VkResult AllocateFromBlock(
  9473. VmaDeviceMemoryBlock* pBlock,
  9474. VkDeviceSize size,
  9475. VkDeviceSize alignment,
  9476. VmaAllocationCreateFlags allocFlags,
  9477. void* pUserData,
  9478. VmaSuballocationType suballocType,
  9479. uint32_t strategy,
  9480. VmaAllocation* pAllocation);
  9481. VkResult CommitAllocationRequest(
  9482. VmaAllocationRequest& allocRequest,
  9483. VmaDeviceMemoryBlock* pBlock,
  9484. VkDeviceSize alignment,
  9485. VmaAllocationCreateFlags allocFlags,
  9486. void* pUserData,
  9487. VmaSuballocationType suballocType,
  9488. VmaAllocation* pAllocation);
  9489. VkResult CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex);
  9490. bool HasEmptyBlock();
  9491. };
  9492. #endif // _VMA_BLOCK_VECTOR
  9493. #ifndef _VMA_DEFRAGMENTATION_CONTEXT
  9494. struct VmaDefragmentationContext_T
  9495. {
  9496. VMA_CLASS_NO_COPY_NO_MOVE(VmaDefragmentationContext_T)
  9497. public:
  9498. VmaDefragmentationContext_T(
  9499. VmaAllocator hAllocator,
  9500. const VmaDefragmentationInfo& info);
  9501. ~VmaDefragmentationContext_T();
  9502. void GetStats(VmaDefragmentationStats& outStats) { outStats = m_GlobalStats; }
  9503. VkResult DefragmentPassBegin(VmaDefragmentationPassMoveInfo& moveInfo);
  9504. VkResult DefragmentPassEnd(VmaDefragmentationPassMoveInfo& moveInfo);
  9505. private:
  9506. // Max number of allocations to ignore due to size constraints before ending single pass
  9507. static const uint8_t MAX_ALLOCS_TO_IGNORE = 16;
  9508. enum class CounterStatus { Pass, Ignore, End };
  9509. struct FragmentedBlock
  9510. {
  9511. uint32_t data;
  9512. VmaDeviceMemoryBlock* block;
  9513. };
  9514. struct StateBalanced
  9515. {
  9516. VkDeviceSize avgFreeSize = 0;
  9517. VkDeviceSize avgAllocSize = UINT64_MAX;
  9518. };
  9519. struct StateExtensive
  9520. {
  9521. enum class Operation : uint8_t
  9522. {
  9523. FindFreeBlockBuffer, FindFreeBlockTexture, FindFreeBlockAll,
  9524. MoveBuffers, MoveTextures, MoveAll,
  9525. Cleanup, Done
  9526. };
  9527. Operation operation = Operation::FindFreeBlockTexture;
  9528. size_t firstFreeBlock = SIZE_MAX;
  9529. };
  9530. struct MoveAllocationData
  9531. {
  9532. VkDeviceSize size;
  9533. VkDeviceSize alignment;
  9534. VmaSuballocationType type;
  9535. VmaAllocationCreateFlags flags;
  9536. VmaDefragmentationMove move = {};
  9537. };
  9538. const VkDeviceSize m_MaxPassBytes;
  9539. const uint32_t m_MaxPassAllocations;
  9540. const PFN_vmaCheckDefragmentationBreakFunction m_BreakCallback;
  9541. void* m_BreakCallbackUserData;
  9542. VmaStlAllocator<VmaDefragmentationMove> m_MoveAllocator;
  9543. VmaVector<VmaDefragmentationMove, VmaStlAllocator<VmaDefragmentationMove>> m_Moves;
  9544. uint8_t m_IgnoredAllocs = 0;
  9545. uint32_t m_Algorithm;
  9546. uint32_t m_BlockVectorCount;
  9547. VmaBlockVector* m_PoolBlockVector;
  9548. VmaBlockVector** m_pBlockVectors;
  9549. size_t m_ImmovableBlockCount = 0;
  9550. VmaDefragmentationStats m_GlobalStats = { 0 };
  9551. VmaDefragmentationStats m_PassStats = { 0 };
  9552. void* m_AlgorithmState = VMA_NULL;
  9553. static MoveAllocationData GetMoveData(VmaAllocHandle handle, VmaBlockMetadata* metadata);
  9554. CounterStatus CheckCounters(VkDeviceSize bytes);
  9555. bool IncrementCounters(VkDeviceSize bytes);
  9556. bool ReallocWithinBlock(VmaBlockVector& vector, VmaDeviceMemoryBlock* block);
  9557. bool AllocInOtherBlock(size_t start, size_t end, MoveAllocationData& data, VmaBlockVector& vector);
  9558. bool ComputeDefragmentation(VmaBlockVector& vector, size_t index);
  9559. bool ComputeDefragmentation_Fast(VmaBlockVector& vector);
  9560. bool ComputeDefragmentation_Balanced(VmaBlockVector& vector, size_t index, bool update);
  9561. bool ComputeDefragmentation_Full(VmaBlockVector& vector);
  9562. bool ComputeDefragmentation_Extensive(VmaBlockVector& vector, size_t index);
  9563. void UpdateVectorStatistics(VmaBlockVector& vector, StateBalanced& state);
  9564. bool MoveDataToFreeBlocks(VmaSuballocationType currentType,
  9565. VmaBlockVector& vector, size_t firstFreeBlock,
  9566. bool& texturePresent, bool& bufferPresent, bool& otherPresent);
  9567. };
  9568. #endif // _VMA_DEFRAGMENTATION_CONTEXT
  9569. #ifndef _VMA_POOL_T
  9570. struct VmaPool_T
  9571. {
  9572. friend struct VmaPoolListItemTraits;
  9573. VMA_CLASS_NO_COPY_NO_MOVE(VmaPool_T)
  9574. public:
  9575. VmaBlockVector m_BlockVector;
  9576. VmaDedicatedAllocationList m_DedicatedAllocations;
  9577. VmaPool_T(
  9578. VmaAllocator hAllocator,
  9579. const VmaPoolCreateInfo& createInfo,
  9580. VkDeviceSize preferredBlockSize);
  9581. ~VmaPool_T();
  9582. uint32_t GetId() const { return m_Id; }
  9583. void SetId(uint32_t id) { VMA_ASSERT(m_Id == 0); m_Id = id; }
  9584. const char* GetName() const { return m_Name; }
  9585. void SetName(const char* pName);
  9586. #if VMA_STATS_STRING_ENABLED
  9587. //void PrintDetailedMap(class VmaStringBuilder& sb);
  9588. #endif
  9589. private:
  9590. uint32_t m_Id;
  9591. char* m_Name;
  9592. VmaPool_T* m_PrevPool = VMA_NULL;
  9593. VmaPool_T* m_NextPool = VMA_NULL;
  9594. };
  9595. struct VmaPoolListItemTraits
  9596. {
  9597. typedef VmaPool_T ItemType;
  9598. static ItemType* GetPrev(const ItemType* item) { return item->m_PrevPool; }
  9599. static ItemType* GetNext(const ItemType* item) { return item->m_NextPool; }
  9600. static ItemType*& AccessPrev(ItemType* item) { return item->m_PrevPool; }
  9601. static ItemType*& AccessNext(ItemType* item) { return item->m_NextPool; }
  9602. };
  9603. #endif // _VMA_POOL_T
  9604. #ifndef _VMA_CURRENT_BUDGET_DATA
  9605. struct VmaCurrentBudgetData
  9606. {
  9607. VMA_CLASS_NO_COPY_NO_MOVE(VmaCurrentBudgetData)
  9608. public:
  9609. VMA_ATOMIC_UINT32 m_BlockCount[VK_MAX_MEMORY_HEAPS];
  9610. VMA_ATOMIC_UINT32 m_AllocationCount[VK_MAX_MEMORY_HEAPS];
  9611. VMA_ATOMIC_UINT64 m_BlockBytes[VK_MAX_MEMORY_HEAPS];
  9612. VMA_ATOMIC_UINT64 m_AllocationBytes[VK_MAX_MEMORY_HEAPS];
  9613. #if VMA_MEMORY_BUDGET
  9614. VMA_ATOMIC_UINT32 m_OperationsSinceBudgetFetch;
  9615. VMA_RW_MUTEX m_BudgetMutex;
  9616. uint64_t m_VulkanUsage[VK_MAX_MEMORY_HEAPS];
  9617. uint64_t m_VulkanBudget[VK_MAX_MEMORY_HEAPS];
  9618. uint64_t m_BlockBytesAtBudgetFetch[VK_MAX_MEMORY_HEAPS];
  9619. #endif // VMA_MEMORY_BUDGET
  9620. VmaCurrentBudgetData();
  9621. void AddAllocation(uint32_t heapIndex, VkDeviceSize allocationSize);
  9622. void RemoveAllocation(uint32_t heapIndex, VkDeviceSize allocationSize);
  9623. };
  9624. #ifndef _VMA_CURRENT_BUDGET_DATA_FUNCTIONS
  9625. VmaCurrentBudgetData::VmaCurrentBudgetData()
  9626. {
  9627. for (uint32_t heapIndex = 0; heapIndex < VK_MAX_MEMORY_HEAPS; ++heapIndex)
  9628. {
  9629. m_BlockCount[heapIndex] = 0;
  9630. m_AllocationCount[heapIndex] = 0;
  9631. m_BlockBytes[heapIndex] = 0;
  9632. m_AllocationBytes[heapIndex] = 0;
  9633. #if VMA_MEMORY_BUDGET
  9634. m_VulkanUsage[heapIndex] = 0;
  9635. m_VulkanBudget[heapIndex] = 0;
  9636. m_BlockBytesAtBudgetFetch[heapIndex] = 0;
  9637. #endif
  9638. }
  9639. #if VMA_MEMORY_BUDGET
  9640. m_OperationsSinceBudgetFetch = 0;
  9641. #endif
  9642. }
  9643. void VmaCurrentBudgetData::AddAllocation(uint32_t heapIndex, VkDeviceSize allocationSize)
  9644. {
  9645. m_AllocationBytes[heapIndex] += allocationSize;
  9646. ++m_AllocationCount[heapIndex];
  9647. #if VMA_MEMORY_BUDGET
  9648. ++m_OperationsSinceBudgetFetch;
  9649. #endif
  9650. }
  9651. void VmaCurrentBudgetData::RemoveAllocation(uint32_t heapIndex, VkDeviceSize allocationSize)
  9652. {
  9653. VMA_ASSERT(m_AllocationBytes[heapIndex] >= allocationSize);
  9654. m_AllocationBytes[heapIndex] -= allocationSize;
  9655. VMA_ASSERT(m_AllocationCount[heapIndex] > 0);
  9656. --m_AllocationCount[heapIndex];
  9657. #if VMA_MEMORY_BUDGET
  9658. ++m_OperationsSinceBudgetFetch;
  9659. #endif
  9660. }
  9661. #endif // _VMA_CURRENT_BUDGET_DATA_FUNCTIONS
  9662. #endif // _VMA_CURRENT_BUDGET_DATA
  9663. #ifndef _VMA_ALLOCATION_OBJECT_ALLOCATOR
  9664. /*
  9665. Thread-safe wrapper over VmaPoolAllocator free list, for allocation of VmaAllocation_T objects.
  9666. */
  9667. class VmaAllocationObjectAllocator
  9668. {
  9669. VMA_CLASS_NO_COPY_NO_MOVE(VmaAllocationObjectAllocator)
  9670. public:
  9671. VmaAllocationObjectAllocator(const VkAllocationCallbacks* pAllocationCallbacks)
  9672. : m_Allocator(pAllocationCallbacks, 1024) {}
  9673. template<typename... Types> VmaAllocation Allocate(Types&&... args);
  9674. void Free(VmaAllocation hAlloc);
  9675. private:
  9676. VMA_MUTEX m_Mutex;
  9677. VmaPoolAllocator<VmaAllocation_T> m_Allocator;
  9678. };
  9679. template<typename... Types>
  9680. VmaAllocation VmaAllocationObjectAllocator::Allocate(Types&&... args)
  9681. {
  9682. VmaMutexLock mutexLock(m_Mutex);
  9683. return m_Allocator.Alloc<Types...>(std::forward<Types>(args)...);
  9684. }
  9685. void VmaAllocationObjectAllocator::Free(VmaAllocation hAlloc)
  9686. {
  9687. VmaMutexLock mutexLock(m_Mutex);
  9688. m_Allocator.Free(hAlloc);
  9689. }
  9690. #endif // _VMA_ALLOCATION_OBJECT_ALLOCATOR
  9691. #ifndef _VMA_VIRTUAL_BLOCK_T
  9692. struct VmaVirtualBlock_T
  9693. {
  9694. VMA_CLASS_NO_COPY_NO_MOVE(VmaVirtualBlock_T)
  9695. public:
  9696. const bool m_AllocationCallbacksSpecified;
  9697. const VkAllocationCallbacks m_AllocationCallbacks;
  9698. VmaVirtualBlock_T(const VmaVirtualBlockCreateInfo& createInfo);
  9699. ~VmaVirtualBlock_T();
  9700. VkResult Init() { return VK_SUCCESS; }
  9701. bool IsEmpty() const { return m_Metadata->IsEmpty(); }
  9702. void Free(VmaVirtualAllocation allocation) { m_Metadata->Free((VmaAllocHandle)allocation); }
  9703. void SetAllocationUserData(VmaVirtualAllocation allocation, void* userData) { m_Metadata->SetAllocationUserData((VmaAllocHandle)allocation, userData); }
  9704. void Clear() { m_Metadata->Clear(); }
  9705. const VkAllocationCallbacks* GetAllocationCallbacks() const;
  9706. void GetAllocationInfo(VmaVirtualAllocation allocation, VmaVirtualAllocationInfo& outInfo);
  9707. VkResult Allocate(const VmaVirtualAllocationCreateInfo& createInfo, VmaVirtualAllocation& outAllocation,
  9708. VkDeviceSize* outOffset);
  9709. void GetStatistics(VmaStatistics& outStats) const;
  9710. void CalculateDetailedStatistics(VmaDetailedStatistics& outStats) const;
  9711. #if VMA_STATS_STRING_ENABLED
  9712. void BuildStatsString(bool detailedMap, VmaStringBuilder& sb) const;
  9713. #endif
  9714. private:
  9715. VmaBlockMetadata* m_Metadata;
  9716. };
  9717. #ifndef _VMA_VIRTUAL_BLOCK_T_FUNCTIONS
  9718. VmaVirtualBlock_T::VmaVirtualBlock_T(const VmaVirtualBlockCreateInfo& createInfo)
  9719. : m_AllocationCallbacksSpecified(createInfo.pAllocationCallbacks != VMA_NULL),
  9720. m_AllocationCallbacks(createInfo.pAllocationCallbacks != VMA_NULL ? *createInfo.pAllocationCallbacks : VmaEmptyAllocationCallbacks)
  9721. {
  9722. const uint32_t algorithm = createInfo.flags & VMA_VIRTUAL_BLOCK_CREATE_ALGORITHM_MASK;
  9723. switch (algorithm)
  9724. {
  9725. case 0:
  9726. m_Metadata = vma_new(GetAllocationCallbacks(), VmaBlockMetadata_TLSF)(VK_NULL_HANDLE, 1, true);
  9727. break;
  9728. case VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT:
  9729. m_Metadata = vma_new(GetAllocationCallbacks(), VmaBlockMetadata_Linear)(VK_NULL_HANDLE, 1, true);
  9730. break;
  9731. default:
  9732. VMA_ASSERT(0);
  9733. m_Metadata = vma_new(GetAllocationCallbacks(), VmaBlockMetadata_TLSF)(VK_NULL_HANDLE, 1, true);
  9734. }
  9735. m_Metadata->Init(createInfo.size);
  9736. }
  9737. VmaVirtualBlock_T::~VmaVirtualBlock_T()
  9738. {
  9739. // Define macro VMA_DEBUG_LOG_FORMAT to receive the list of the unfreed allocations
  9740. if (!m_Metadata->IsEmpty())
  9741. m_Metadata->DebugLogAllAllocations();
  9742. // This is the most important assert in the entire library.
  9743. // Hitting it means you have some memory leak - unreleased virtual allocations.
  9744. VMA_ASSERT(m_Metadata->IsEmpty() && "Some virtual allocations were not freed before destruction of this virtual block!");
  9745. vma_delete(GetAllocationCallbacks(), m_Metadata);
  9746. }
  9747. const VkAllocationCallbacks* VmaVirtualBlock_T::GetAllocationCallbacks() const
  9748. {
  9749. return m_AllocationCallbacksSpecified ? &m_AllocationCallbacks : VMA_NULL;
  9750. }
  9751. void VmaVirtualBlock_T::GetAllocationInfo(VmaVirtualAllocation allocation, VmaVirtualAllocationInfo& outInfo)
  9752. {
  9753. m_Metadata->GetAllocationInfo((VmaAllocHandle)allocation, outInfo);
  9754. }
  9755. VkResult VmaVirtualBlock_T::Allocate(const VmaVirtualAllocationCreateInfo& createInfo, VmaVirtualAllocation& outAllocation,
  9756. VkDeviceSize* outOffset)
  9757. {
  9758. VmaAllocationRequest request = {};
  9759. if (m_Metadata->CreateAllocationRequest(
  9760. createInfo.size, // allocSize
  9761. VMA_MAX(createInfo.alignment, (VkDeviceSize)1), // allocAlignment
  9762. (createInfo.flags & VMA_VIRTUAL_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0, // upperAddress
  9763. VMA_SUBALLOCATION_TYPE_UNKNOWN, // allocType - unimportant
  9764. createInfo.flags & VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MASK, // strategy
  9765. &request))
  9766. {
  9767. m_Metadata->Alloc(request,
  9768. VMA_SUBALLOCATION_TYPE_UNKNOWN, // type - unimportant
  9769. createInfo.pUserData);
  9770. outAllocation = (VmaVirtualAllocation)request.allocHandle;
  9771. if(outOffset)
  9772. *outOffset = m_Metadata->GetAllocationOffset(request.allocHandle);
  9773. return VK_SUCCESS;
  9774. }
  9775. outAllocation = (VmaVirtualAllocation)VK_NULL_HANDLE;
  9776. if (outOffset)
  9777. *outOffset = UINT64_MAX;
  9778. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  9779. }
  9780. void VmaVirtualBlock_T::GetStatistics(VmaStatistics& outStats) const
  9781. {
  9782. VmaClearStatistics(outStats);
  9783. m_Metadata->AddStatistics(outStats);
  9784. }
  9785. void VmaVirtualBlock_T::CalculateDetailedStatistics(VmaDetailedStatistics& outStats) const
  9786. {
  9787. VmaClearDetailedStatistics(outStats);
  9788. m_Metadata->AddDetailedStatistics(outStats);
  9789. }
  9790. #if VMA_STATS_STRING_ENABLED
  9791. void VmaVirtualBlock_T::BuildStatsString(bool detailedMap, VmaStringBuilder& sb) const
  9792. {
  9793. VmaJsonWriter json(GetAllocationCallbacks(), sb);
  9794. json.BeginObject();
  9795. VmaDetailedStatistics stats;
  9796. CalculateDetailedStatistics(stats);
  9797. json.WriteString("Stats");
  9798. VmaPrintDetailedStatistics(json, stats);
  9799. if (detailedMap)
  9800. {
  9801. json.WriteString("Details");
  9802. json.BeginObject();
  9803. m_Metadata->PrintDetailedMap(json);
  9804. json.EndObject();
  9805. }
  9806. json.EndObject();
  9807. }
  9808. #endif // VMA_STATS_STRING_ENABLED
  9809. #endif // _VMA_VIRTUAL_BLOCK_T_FUNCTIONS
  9810. #endif // _VMA_VIRTUAL_BLOCK_T
  9811. // Main allocator object.
  9812. struct VmaAllocator_T
  9813. {
  9814. VMA_CLASS_NO_COPY_NO_MOVE(VmaAllocator_T)
  9815. public:
  9816. bool m_UseMutex;
  9817. uint32_t m_VulkanApiVersion;
  9818. bool m_UseKhrDedicatedAllocation; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0).
  9819. bool m_UseKhrBindMemory2; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0).
  9820. bool m_UseExtMemoryBudget;
  9821. bool m_UseAmdDeviceCoherentMemory;
  9822. bool m_UseKhrBufferDeviceAddress;
  9823. bool m_UseExtMemoryPriority;
  9824. VkDevice m_hDevice;
  9825. VkInstance m_hInstance;
  9826. bool m_AllocationCallbacksSpecified;
  9827. VkAllocationCallbacks m_AllocationCallbacks;
  9828. VmaDeviceMemoryCallbacks m_DeviceMemoryCallbacks;
  9829. VmaAllocationObjectAllocator m_AllocationObjectAllocator;
  9830. // Each bit (1 << i) is set if HeapSizeLimit is enabled for that heap, so cannot allocate more than the heap size.
  9831. uint32_t m_HeapSizeLimitMask;
  9832. VkPhysicalDeviceProperties m_PhysicalDeviceProperties;
  9833. VkPhysicalDeviceMemoryProperties m_MemProps;
  9834. // Default pools.
  9835. VmaBlockVector* m_pBlockVectors[VK_MAX_MEMORY_TYPES];
  9836. VmaDedicatedAllocationList m_DedicatedAllocations[VK_MAX_MEMORY_TYPES];
  9837. VmaCurrentBudgetData m_Budget;
  9838. VMA_ATOMIC_UINT32 m_DeviceMemoryCount; // Total number of VkDeviceMemory objects.
  9839. VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo);
  9840. VkResult Init(const VmaAllocatorCreateInfo* pCreateInfo);
  9841. ~VmaAllocator_T();
  9842. const VkAllocationCallbacks* GetAllocationCallbacks() const
  9843. {
  9844. return m_AllocationCallbacksSpecified ? &m_AllocationCallbacks : VMA_NULL;
  9845. }
  9846. const VmaVulkanFunctions& GetVulkanFunctions() const
  9847. {
  9848. return m_VulkanFunctions;
  9849. }
  9850. VkPhysicalDevice GetPhysicalDevice() const { return m_PhysicalDevice; }
  9851. VkDeviceSize GetBufferImageGranularity() const
  9852. {
  9853. return VMA_MAX(
  9854. static_cast<VkDeviceSize>(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY),
  9855. m_PhysicalDeviceProperties.limits.bufferImageGranularity);
  9856. }
  9857. uint32_t GetMemoryHeapCount() const { return m_MemProps.memoryHeapCount; }
  9858. uint32_t GetMemoryTypeCount() const { return m_MemProps.memoryTypeCount; }
  9859. uint32_t MemoryTypeIndexToHeapIndex(uint32_t memTypeIndex) const
  9860. {
  9861. VMA_ASSERT(memTypeIndex < m_MemProps.memoryTypeCount);
  9862. return m_MemProps.memoryTypes[memTypeIndex].heapIndex;
  9863. }
  9864. // True when specific memory type is HOST_VISIBLE but not HOST_COHERENT.
  9865. bool IsMemoryTypeNonCoherent(uint32_t memTypeIndex) const
  9866. {
  9867. return (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) ==
  9868. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  9869. }
  9870. // Minimum alignment for all allocations in specific memory type.
  9871. VkDeviceSize GetMemoryTypeMinAlignment(uint32_t memTypeIndex) const
  9872. {
  9873. return IsMemoryTypeNonCoherent(memTypeIndex) ?
  9874. VMA_MAX((VkDeviceSize)VMA_MIN_ALIGNMENT, m_PhysicalDeviceProperties.limits.nonCoherentAtomSize) :
  9875. (VkDeviceSize)VMA_MIN_ALIGNMENT;
  9876. }
  9877. bool IsIntegratedGpu() const
  9878. {
  9879. return m_PhysicalDeviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
  9880. }
  9881. uint32_t GetGlobalMemoryTypeBits() const { return m_GlobalMemoryTypeBits; }
  9882. void GetBufferMemoryRequirements(
  9883. VkBuffer hBuffer,
  9884. VkMemoryRequirements& memReq,
  9885. bool& requiresDedicatedAllocation,
  9886. bool& prefersDedicatedAllocation) const;
  9887. void GetImageMemoryRequirements(
  9888. VkImage hImage,
  9889. VkMemoryRequirements& memReq,
  9890. bool& requiresDedicatedAllocation,
  9891. bool& prefersDedicatedAllocation) const;
  9892. VkResult FindMemoryTypeIndex(
  9893. uint32_t memoryTypeBits,
  9894. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  9895. VkFlags bufImgUsage, // VkBufferCreateInfo::usage or VkImageCreateInfo::usage. UINT32_MAX if unknown.
  9896. uint32_t* pMemoryTypeIndex) const;
  9897. // Main allocation function.
  9898. VkResult AllocateMemory(
  9899. const VkMemoryRequirements& vkMemReq,
  9900. bool requiresDedicatedAllocation,
  9901. bool prefersDedicatedAllocation,
  9902. VkBuffer dedicatedBuffer,
  9903. VkImage dedicatedImage,
  9904. VkFlags dedicatedBufferImageUsage, // UINT32_MAX if unknown.
  9905. const VmaAllocationCreateInfo& createInfo,
  9906. VmaSuballocationType suballocType,
  9907. size_t allocationCount,
  9908. VmaAllocation* pAllocations);
  9909. // Main deallocation function.
  9910. void FreeMemory(
  9911. size_t allocationCount,
  9912. const VmaAllocation* pAllocations);
  9913. void CalculateStatistics(VmaTotalStatistics* pStats);
  9914. void GetHeapBudgets(
  9915. VmaBudget* outBudgets, uint32_t firstHeap, uint32_t heapCount);
  9916. #if VMA_STATS_STRING_ENABLED
  9917. void PrintDetailedMap(class VmaJsonWriter& json);
  9918. #endif
  9919. void GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo);
  9920. VkResult CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool);
  9921. void DestroyPool(VmaPool pool);
  9922. void GetPoolStatistics(VmaPool pool, VmaStatistics* pPoolStats);
  9923. void CalculatePoolStatistics(VmaPool pool, VmaDetailedStatistics* pPoolStats);
  9924. void SetCurrentFrameIndex(uint32_t frameIndex);
  9925. uint32_t GetCurrentFrameIndex() const { return m_CurrentFrameIndex.load(); }
  9926. VkResult CheckPoolCorruption(VmaPool hPool);
  9927. VkResult CheckCorruption(uint32_t memoryTypeBits);
  9928. // Call to Vulkan function vkAllocateMemory with accompanying bookkeeping.
  9929. VkResult AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory);
  9930. // Call to Vulkan function vkFreeMemory with accompanying bookkeeping.
  9931. void FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory);
  9932. // Call to Vulkan function vkBindBufferMemory or vkBindBufferMemory2KHR.
  9933. VkResult BindVulkanBuffer(
  9934. VkDeviceMemory memory,
  9935. VkDeviceSize memoryOffset,
  9936. VkBuffer buffer,
  9937. const void* pNext);
  9938. // Call to Vulkan function vkBindImageMemory or vkBindImageMemory2KHR.
  9939. VkResult BindVulkanImage(
  9940. VkDeviceMemory memory,
  9941. VkDeviceSize memoryOffset,
  9942. VkImage image,
  9943. const void* pNext);
  9944. VkResult Map(VmaAllocation hAllocation, void** ppData);
  9945. void Unmap(VmaAllocation hAllocation);
  9946. VkResult BindBufferMemory(
  9947. VmaAllocation hAllocation,
  9948. VkDeviceSize allocationLocalOffset,
  9949. VkBuffer hBuffer,
  9950. const void* pNext);
  9951. VkResult BindImageMemory(
  9952. VmaAllocation hAllocation,
  9953. VkDeviceSize allocationLocalOffset,
  9954. VkImage hImage,
  9955. const void* pNext);
  9956. VkResult FlushOrInvalidateAllocation(
  9957. VmaAllocation hAllocation,
  9958. VkDeviceSize offset, VkDeviceSize size,
  9959. VMA_CACHE_OPERATION op);
  9960. VkResult FlushOrInvalidateAllocations(
  9961. uint32_t allocationCount,
  9962. const VmaAllocation* allocations,
  9963. const VkDeviceSize* offsets, const VkDeviceSize* sizes,
  9964. VMA_CACHE_OPERATION op);
  9965. void FillAllocation(const VmaAllocation hAllocation, uint8_t pattern);
  9966. /*
  9967. Returns bit mask of memory types that can support defragmentation on GPU as
  9968. they support creation of required buffer for copy operations.
  9969. */
  9970. uint32_t GetGpuDefragmentationMemoryTypeBits();
  9971. #if VMA_EXTERNAL_MEMORY
  9972. VkExternalMemoryHandleTypeFlagsKHR GetExternalMemoryHandleTypeFlags(uint32_t memTypeIndex) const
  9973. {
  9974. return m_TypeExternalMemoryHandleTypes[memTypeIndex];
  9975. }
  9976. #endif // #if VMA_EXTERNAL_MEMORY
  9977. private:
  9978. VkDeviceSize m_PreferredLargeHeapBlockSize;
  9979. VkPhysicalDevice m_PhysicalDevice;
  9980. VMA_ATOMIC_UINT32 m_CurrentFrameIndex;
  9981. VMA_ATOMIC_UINT32 m_GpuDefragmentationMemoryTypeBits; // UINT32_MAX means uninitialized.
  9982. #if VMA_EXTERNAL_MEMORY
  9983. VkExternalMemoryHandleTypeFlagsKHR m_TypeExternalMemoryHandleTypes[VK_MAX_MEMORY_TYPES];
  9984. #endif // #if VMA_EXTERNAL_MEMORY
  9985. VMA_RW_MUTEX m_PoolsMutex;
  9986. typedef VmaIntrusiveLinkedList<VmaPoolListItemTraits> PoolList;
  9987. // Protected by m_PoolsMutex.
  9988. PoolList m_Pools;
  9989. uint32_t m_NextPoolId;
  9990. VmaVulkanFunctions m_VulkanFunctions;
  9991. // Global bit mask AND-ed with any memoryTypeBits to disallow certain memory types.
  9992. uint32_t m_GlobalMemoryTypeBits;
  9993. void ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions);
  9994. #if VMA_STATIC_VULKAN_FUNCTIONS == 1
  9995. void ImportVulkanFunctions_Static();
  9996. #endif
  9997. void ImportVulkanFunctions_Custom(const VmaVulkanFunctions* pVulkanFunctions);
  9998. #if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1
  9999. void ImportVulkanFunctions_Dynamic();
  10000. #endif
  10001. void ValidateVulkanFunctions();
  10002. VkDeviceSize CalcPreferredBlockSize(uint32_t memTypeIndex);
  10003. VkResult AllocateMemoryOfType(
  10004. VmaPool pool,
  10005. VkDeviceSize size,
  10006. VkDeviceSize alignment,
  10007. bool dedicatedPreferred,
  10008. VkBuffer dedicatedBuffer,
  10009. VkImage dedicatedImage,
  10010. VkFlags dedicatedBufferImageUsage,
  10011. const VmaAllocationCreateInfo& createInfo,
  10012. uint32_t memTypeIndex,
  10013. VmaSuballocationType suballocType,
  10014. VmaDedicatedAllocationList& dedicatedAllocations,
  10015. VmaBlockVector& blockVector,
  10016. size_t allocationCount,
  10017. VmaAllocation* pAllocations);
  10018. // Helper function only to be used inside AllocateDedicatedMemory.
  10019. VkResult AllocateDedicatedMemoryPage(
  10020. VmaPool pool,
  10021. VkDeviceSize size,
  10022. VmaSuballocationType suballocType,
  10023. uint32_t memTypeIndex,
  10024. const VkMemoryAllocateInfo& allocInfo,
  10025. bool map,
  10026. bool isUserDataString,
  10027. bool isMappingAllowed,
  10028. void* pUserData,
  10029. VmaAllocation* pAllocation);
  10030. // Allocates and registers new VkDeviceMemory specifically for dedicated allocations.
  10031. VkResult AllocateDedicatedMemory(
  10032. VmaPool pool,
  10033. VkDeviceSize size,
  10034. VmaSuballocationType suballocType,
  10035. VmaDedicatedAllocationList& dedicatedAllocations,
  10036. uint32_t memTypeIndex,
  10037. bool map,
  10038. bool isUserDataString,
  10039. bool isMappingAllowed,
  10040. bool canAliasMemory,
  10041. void* pUserData,
  10042. float priority,
  10043. VkBuffer dedicatedBuffer,
  10044. VkImage dedicatedImage,
  10045. VkFlags dedicatedBufferImageUsage,
  10046. size_t allocationCount,
  10047. VmaAllocation* pAllocations,
  10048. const void* pNextChain = nullptr);
  10049. void FreeDedicatedMemory(const VmaAllocation allocation);
  10050. VkResult CalcMemTypeParams(
  10051. VmaAllocationCreateInfo& outCreateInfo,
  10052. uint32_t memTypeIndex,
  10053. VkDeviceSize size,
  10054. size_t allocationCount);
  10055. VkResult CalcAllocationParams(
  10056. VmaAllocationCreateInfo& outCreateInfo,
  10057. bool dedicatedRequired,
  10058. bool dedicatedPreferred);
  10059. /*
  10060. Calculates and returns bit mask of memory types that can support defragmentation
  10061. on GPU as they support creation of required buffer for copy operations.
  10062. */
  10063. uint32_t CalculateGpuDefragmentationMemoryTypeBits() const;
  10064. uint32_t CalculateGlobalMemoryTypeBits() const;
  10065. bool GetFlushOrInvalidateRange(
  10066. VmaAllocation allocation,
  10067. VkDeviceSize offset, VkDeviceSize size,
  10068. VkMappedMemoryRange& outRange) const;
  10069. #if VMA_MEMORY_BUDGET
  10070. void UpdateVulkanBudget();
  10071. #endif // #if VMA_MEMORY_BUDGET
  10072. };
  10073. #ifndef _VMA_MEMORY_FUNCTIONS
  10074. static void* VmaMalloc(VmaAllocator hAllocator, size_t size, size_t alignment)
  10075. {
  10076. return VmaMalloc(&hAllocator->m_AllocationCallbacks, size, alignment);
  10077. }
  10078. static void VmaFree(VmaAllocator hAllocator, void* ptr)
  10079. {
  10080. VmaFree(&hAllocator->m_AllocationCallbacks, ptr);
  10081. }
  10082. template<typename T>
  10083. static T* VmaAllocate(VmaAllocator hAllocator)
  10084. {
  10085. return (T*)VmaMalloc(hAllocator, sizeof(T), VMA_ALIGN_OF(T));
  10086. }
  10087. template<typename T>
  10088. static T* VmaAllocateArray(VmaAllocator hAllocator, size_t count)
  10089. {
  10090. return (T*)VmaMalloc(hAllocator, sizeof(T) * count, VMA_ALIGN_OF(T));
  10091. }
  10092. template<typename T>
  10093. static void vma_delete(VmaAllocator hAllocator, T* ptr)
  10094. {
  10095. if(ptr != VMA_NULL)
  10096. {
  10097. ptr->~T();
  10098. VmaFree(hAllocator, ptr);
  10099. }
  10100. }
  10101. template<typename T>
  10102. static void vma_delete_array(VmaAllocator hAllocator, T* ptr, size_t count)
  10103. {
  10104. if(ptr != VMA_NULL)
  10105. {
  10106. for(size_t i = count; i--; )
  10107. ptr[i].~T();
  10108. VmaFree(hAllocator, ptr);
  10109. }
  10110. }
  10111. #endif // _VMA_MEMORY_FUNCTIONS
  10112. #ifndef _VMA_DEVICE_MEMORY_BLOCK_FUNCTIONS
  10113. VmaDeviceMemoryBlock::VmaDeviceMemoryBlock(VmaAllocator hAllocator)
  10114. : m_pMetadata(VMA_NULL),
  10115. m_MemoryTypeIndex(UINT32_MAX),
  10116. m_Id(0),
  10117. m_hMemory(VK_NULL_HANDLE),
  10118. m_MapCount(0),
  10119. m_pMappedData(VMA_NULL) {}
  10120. VmaDeviceMemoryBlock::~VmaDeviceMemoryBlock()
  10121. {
  10122. VMA_ASSERT(m_MapCount == 0 && "VkDeviceMemory block is being destroyed while it is still mapped.");
  10123. VMA_ASSERT(m_hMemory == VK_NULL_HANDLE);
  10124. }
  10125. void VmaDeviceMemoryBlock::Init(
  10126. VmaAllocator hAllocator,
  10127. VmaPool hParentPool,
  10128. uint32_t newMemoryTypeIndex,
  10129. VkDeviceMemory newMemory,
  10130. VkDeviceSize newSize,
  10131. uint32_t id,
  10132. uint32_t algorithm,
  10133. VkDeviceSize bufferImageGranularity)
  10134. {
  10135. VMA_ASSERT(m_hMemory == VK_NULL_HANDLE);
  10136. m_hParentPool = hParentPool;
  10137. m_MemoryTypeIndex = newMemoryTypeIndex;
  10138. m_Id = id;
  10139. m_hMemory = newMemory;
  10140. switch (algorithm)
  10141. {
  10142. case 0:
  10143. m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_TLSF)(hAllocator->GetAllocationCallbacks(),
  10144. bufferImageGranularity, false); // isVirtual
  10145. break;
  10146. case VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT:
  10147. m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_Linear)(hAllocator->GetAllocationCallbacks(),
  10148. bufferImageGranularity, false); // isVirtual
  10149. break;
  10150. default:
  10151. VMA_ASSERT(0);
  10152. m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_TLSF)(hAllocator->GetAllocationCallbacks(),
  10153. bufferImageGranularity, false); // isVirtual
  10154. }
  10155. m_pMetadata->Init(newSize);
  10156. }
  10157. void VmaDeviceMemoryBlock::Destroy(VmaAllocator allocator)
  10158. {
  10159. // Define macro VMA_DEBUG_LOG_FORMAT to receive the list of the unfreed allocations
  10160. if (!m_pMetadata->IsEmpty())
  10161. m_pMetadata->DebugLogAllAllocations();
  10162. // This is the most important assert in the entire library.
  10163. // Hitting it means you have some memory leak - unreleased VmaAllocation objects.
  10164. VMA_ASSERT(m_pMetadata->IsEmpty() && "Some allocations were not freed before destruction of this memory block!");
  10165. VMA_ASSERT(m_hMemory != VK_NULL_HANDLE);
  10166. allocator->FreeVulkanMemory(m_MemoryTypeIndex, m_pMetadata->GetSize(), m_hMemory);
  10167. m_hMemory = VK_NULL_HANDLE;
  10168. vma_delete(allocator, m_pMetadata);
  10169. m_pMetadata = VMA_NULL;
  10170. }
  10171. void VmaDeviceMemoryBlock::PostAlloc(VmaAllocator hAllocator)
  10172. {
  10173. VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex);
  10174. m_MappingHysteresis.PostAlloc();
  10175. }
  10176. void VmaDeviceMemoryBlock::PostFree(VmaAllocator hAllocator)
  10177. {
  10178. VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex);
  10179. if(m_MappingHysteresis.PostFree())
  10180. {
  10181. VMA_ASSERT(m_MappingHysteresis.GetExtraMapping() == 0);
  10182. if (m_MapCount == 0)
  10183. {
  10184. m_pMappedData = VMA_NULL;
  10185. (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(hAllocator->m_hDevice, m_hMemory);
  10186. }
  10187. }
  10188. }
  10189. bool VmaDeviceMemoryBlock::Validate() const
  10190. {
  10191. VMA_VALIDATE((m_hMemory != VK_NULL_HANDLE) &&
  10192. (m_pMetadata->GetSize() != 0));
  10193. return m_pMetadata->Validate();
  10194. }
  10195. VkResult VmaDeviceMemoryBlock::CheckCorruption(VmaAllocator hAllocator)
  10196. {
  10197. void* pData = nullptr;
  10198. VkResult res = Map(hAllocator, 1, &pData);
  10199. if (res != VK_SUCCESS)
  10200. {
  10201. return res;
  10202. }
  10203. res = m_pMetadata->CheckCorruption(pData);
  10204. Unmap(hAllocator, 1);
  10205. return res;
  10206. }
  10207. VkResult VmaDeviceMemoryBlock::Map(VmaAllocator hAllocator, uint32_t count, void** ppData)
  10208. {
  10209. if (count == 0)
  10210. {
  10211. return VK_SUCCESS;
  10212. }
  10213. VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex);
  10214. const uint32_t oldTotalMapCount = m_MapCount + m_MappingHysteresis.GetExtraMapping();
  10215. m_MappingHysteresis.PostMap();
  10216. if (oldTotalMapCount != 0)
  10217. {
  10218. m_MapCount += count;
  10219. VMA_ASSERT(m_pMappedData != VMA_NULL);
  10220. if (ppData != VMA_NULL)
  10221. {
  10222. *ppData = m_pMappedData;
  10223. }
  10224. return VK_SUCCESS;
  10225. }
  10226. else
  10227. {
  10228. VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)(
  10229. hAllocator->m_hDevice,
  10230. m_hMemory,
  10231. 0, // offset
  10232. VK_WHOLE_SIZE,
  10233. 0, // flags
  10234. &m_pMappedData);
  10235. if (result == VK_SUCCESS)
  10236. {
  10237. if (ppData != VMA_NULL)
  10238. {
  10239. *ppData = m_pMappedData;
  10240. }
  10241. m_MapCount = count;
  10242. }
  10243. return result;
  10244. }
  10245. }
  10246. void VmaDeviceMemoryBlock::Unmap(VmaAllocator hAllocator, uint32_t count)
  10247. {
  10248. if (count == 0)
  10249. {
  10250. return;
  10251. }
  10252. VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex);
  10253. if (m_MapCount >= count)
  10254. {
  10255. m_MapCount -= count;
  10256. const uint32_t totalMapCount = m_MapCount + m_MappingHysteresis.GetExtraMapping();
  10257. if (totalMapCount == 0)
  10258. {
  10259. m_pMappedData = VMA_NULL;
  10260. (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(hAllocator->m_hDevice, m_hMemory);
  10261. }
  10262. m_MappingHysteresis.PostUnmap();
  10263. }
  10264. else
  10265. {
  10266. VMA_ASSERT(0 && "VkDeviceMemory block is being unmapped while it was not previously mapped.");
  10267. }
  10268. }
  10269. VkResult VmaDeviceMemoryBlock::WriteMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize)
  10270. {
  10271. VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION);
  10272. void* pData;
  10273. VkResult res = Map(hAllocator, 1, &pData);
  10274. if (res != VK_SUCCESS)
  10275. {
  10276. return res;
  10277. }
  10278. VmaWriteMagicValue(pData, allocOffset + allocSize);
  10279. Unmap(hAllocator, 1);
  10280. return VK_SUCCESS;
  10281. }
  10282. VkResult VmaDeviceMemoryBlock::ValidateMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize)
  10283. {
  10284. VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION);
  10285. void* pData;
  10286. VkResult res = Map(hAllocator, 1, &pData);
  10287. if (res != VK_SUCCESS)
  10288. {
  10289. return res;
  10290. }
  10291. if (!VmaValidateMagicValue(pData, allocOffset + allocSize))
  10292. {
  10293. VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER FREED ALLOCATION!");
  10294. }
  10295. Unmap(hAllocator, 1);
  10296. return VK_SUCCESS;
  10297. }
  10298. VkResult VmaDeviceMemoryBlock::BindBufferMemory(
  10299. const VmaAllocator hAllocator,
  10300. const VmaAllocation hAllocation,
  10301. VkDeviceSize allocationLocalOffset,
  10302. VkBuffer hBuffer,
  10303. const void* pNext)
  10304. {
  10305. VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK &&
  10306. hAllocation->GetBlock() == this);
  10307. VMA_ASSERT(allocationLocalOffset < hAllocation->GetSize() &&
  10308. "Invalid allocationLocalOffset. Did you forget that this offset is relative to the beginning of the allocation, not the whole memory block?");
  10309. const VkDeviceSize memoryOffset = hAllocation->GetOffset() + allocationLocalOffset;
  10310. // This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads.
  10311. VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex);
  10312. return hAllocator->BindVulkanBuffer(m_hMemory, memoryOffset, hBuffer, pNext);
  10313. }
  10314. VkResult VmaDeviceMemoryBlock::BindImageMemory(
  10315. const VmaAllocator hAllocator,
  10316. const VmaAllocation hAllocation,
  10317. VkDeviceSize allocationLocalOffset,
  10318. VkImage hImage,
  10319. const void* pNext)
  10320. {
  10321. VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK &&
  10322. hAllocation->GetBlock() == this);
  10323. VMA_ASSERT(allocationLocalOffset < hAllocation->GetSize() &&
  10324. "Invalid allocationLocalOffset. Did you forget that this offset is relative to the beginning of the allocation, not the whole memory block?");
  10325. const VkDeviceSize memoryOffset = hAllocation->GetOffset() + allocationLocalOffset;
  10326. // This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads.
  10327. VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex);
  10328. return hAllocator->BindVulkanImage(m_hMemory, memoryOffset, hImage, pNext);
  10329. }
  10330. #endif // _VMA_DEVICE_MEMORY_BLOCK_FUNCTIONS
  10331. #ifndef _VMA_ALLOCATION_T_FUNCTIONS
  10332. VmaAllocation_T::VmaAllocation_T(bool mappingAllowed)
  10333. : m_Alignment{ 1 },
  10334. m_Size{ 0 },
  10335. m_pUserData{ VMA_NULL },
  10336. m_pName{ VMA_NULL },
  10337. m_MemoryTypeIndex{ 0 },
  10338. m_Type{ (uint8_t)ALLOCATION_TYPE_NONE },
  10339. m_SuballocationType{ (uint8_t)VMA_SUBALLOCATION_TYPE_UNKNOWN },
  10340. m_MapCount{ 0 },
  10341. m_Flags{ 0 }
  10342. {
  10343. if(mappingAllowed)
  10344. m_Flags |= (uint8_t)FLAG_MAPPING_ALLOWED;
  10345. #if VMA_STATS_STRING_ENABLED
  10346. m_BufferImageUsage = 0;
  10347. #endif
  10348. }
  10349. VmaAllocation_T::~VmaAllocation_T()
  10350. {
  10351. VMA_ASSERT(m_MapCount == 0 && "Allocation was not unmapped before destruction.");
  10352. // Check if owned string was freed.
  10353. VMA_ASSERT(m_pName == VMA_NULL);
  10354. }
  10355. void VmaAllocation_T::InitBlockAllocation(
  10356. VmaDeviceMemoryBlock* block,
  10357. VmaAllocHandle allocHandle,
  10358. VkDeviceSize alignment,
  10359. VkDeviceSize size,
  10360. uint32_t memoryTypeIndex,
  10361. VmaSuballocationType suballocationType,
  10362. bool mapped)
  10363. {
  10364. VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
  10365. VMA_ASSERT(block != VMA_NULL);
  10366. m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK;
  10367. m_Alignment = alignment;
  10368. m_Size = size;
  10369. m_MemoryTypeIndex = memoryTypeIndex;
  10370. if(mapped)
  10371. {
  10372. VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it.");
  10373. m_Flags |= (uint8_t)FLAG_PERSISTENT_MAP;
  10374. }
  10375. m_SuballocationType = (uint8_t)suballocationType;
  10376. m_BlockAllocation.m_Block = block;
  10377. m_BlockAllocation.m_AllocHandle = allocHandle;
  10378. }
  10379. void VmaAllocation_T::InitDedicatedAllocation(
  10380. VmaPool hParentPool,
  10381. uint32_t memoryTypeIndex,
  10382. VkDeviceMemory hMemory,
  10383. VmaSuballocationType suballocationType,
  10384. void* pMappedData,
  10385. VkDeviceSize size)
  10386. {
  10387. VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
  10388. VMA_ASSERT(hMemory != VK_NULL_HANDLE);
  10389. m_Type = (uint8_t)ALLOCATION_TYPE_DEDICATED;
  10390. m_Alignment = 0;
  10391. m_Size = size;
  10392. m_MemoryTypeIndex = memoryTypeIndex;
  10393. m_SuballocationType = (uint8_t)suballocationType;
  10394. if(pMappedData != VMA_NULL)
  10395. {
  10396. VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it.");
  10397. m_Flags |= (uint8_t)FLAG_PERSISTENT_MAP;
  10398. }
  10399. m_DedicatedAllocation.m_hParentPool = hParentPool;
  10400. m_DedicatedAllocation.m_hMemory = hMemory;
  10401. m_DedicatedAllocation.m_pMappedData = pMappedData;
  10402. m_DedicatedAllocation.m_Prev = VMA_NULL;
  10403. m_DedicatedAllocation.m_Next = VMA_NULL;
  10404. }
  10405. void VmaAllocation_T::SetName(VmaAllocator hAllocator, const char* pName)
  10406. {
  10407. VMA_ASSERT(pName == VMA_NULL || pName != m_pName);
  10408. FreeName(hAllocator);
  10409. if (pName != VMA_NULL)
  10410. m_pName = VmaCreateStringCopy(hAllocator->GetAllocationCallbacks(), pName);
  10411. }
  10412. uint8_t VmaAllocation_T::SwapBlockAllocation(VmaAllocator hAllocator, VmaAllocation allocation)
  10413. {
  10414. VMA_ASSERT(allocation != VMA_NULL);
  10415. VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK);
  10416. VMA_ASSERT(allocation->m_Type == ALLOCATION_TYPE_BLOCK);
  10417. if (m_MapCount != 0)
  10418. m_BlockAllocation.m_Block->Unmap(hAllocator, m_MapCount);
  10419. m_BlockAllocation.m_Block->m_pMetadata->SetAllocationUserData(m_BlockAllocation.m_AllocHandle, allocation);
  10420. VMA_SWAP(m_BlockAllocation, allocation->m_BlockAllocation);
  10421. m_BlockAllocation.m_Block->m_pMetadata->SetAllocationUserData(m_BlockAllocation.m_AllocHandle, this);
  10422. #if VMA_STATS_STRING_ENABLED
  10423. VMA_SWAP(m_BufferImageUsage, allocation->m_BufferImageUsage);
  10424. #endif
  10425. return m_MapCount;
  10426. }
  10427. VmaAllocHandle VmaAllocation_T::GetAllocHandle() const
  10428. {
  10429. switch (m_Type)
  10430. {
  10431. case ALLOCATION_TYPE_BLOCK:
  10432. return m_BlockAllocation.m_AllocHandle;
  10433. case ALLOCATION_TYPE_DEDICATED:
  10434. return VK_NULL_HANDLE;
  10435. default:
  10436. VMA_ASSERT(0);
  10437. return VK_NULL_HANDLE;
  10438. }
  10439. }
  10440. VkDeviceSize VmaAllocation_T::GetOffset() const
  10441. {
  10442. switch (m_Type)
  10443. {
  10444. case ALLOCATION_TYPE_BLOCK:
  10445. return m_BlockAllocation.m_Block->m_pMetadata->GetAllocationOffset(m_BlockAllocation.m_AllocHandle);
  10446. case ALLOCATION_TYPE_DEDICATED:
  10447. return 0;
  10448. default:
  10449. VMA_ASSERT(0);
  10450. return 0;
  10451. }
  10452. }
  10453. VmaPool VmaAllocation_T::GetParentPool() const
  10454. {
  10455. switch (m_Type)
  10456. {
  10457. case ALLOCATION_TYPE_BLOCK:
  10458. return m_BlockAllocation.m_Block->GetParentPool();
  10459. case ALLOCATION_TYPE_DEDICATED:
  10460. return m_DedicatedAllocation.m_hParentPool;
  10461. default:
  10462. VMA_ASSERT(0);
  10463. return VK_NULL_HANDLE;
  10464. }
  10465. }
  10466. VkDeviceMemory VmaAllocation_T::GetMemory() const
  10467. {
  10468. switch (m_Type)
  10469. {
  10470. case ALLOCATION_TYPE_BLOCK:
  10471. return m_BlockAllocation.m_Block->GetDeviceMemory();
  10472. case ALLOCATION_TYPE_DEDICATED:
  10473. return m_DedicatedAllocation.m_hMemory;
  10474. default:
  10475. VMA_ASSERT(0);
  10476. return VK_NULL_HANDLE;
  10477. }
  10478. }
  10479. void* VmaAllocation_T::GetMappedData() const
  10480. {
  10481. switch (m_Type)
  10482. {
  10483. case ALLOCATION_TYPE_BLOCK:
  10484. if (m_MapCount != 0 || IsPersistentMap())
  10485. {
  10486. void* pBlockData = m_BlockAllocation.m_Block->GetMappedData();
  10487. VMA_ASSERT(pBlockData != VMA_NULL);
  10488. return (char*)pBlockData + GetOffset();
  10489. }
  10490. else
  10491. {
  10492. return VMA_NULL;
  10493. }
  10494. break;
  10495. case ALLOCATION_TYPE_DEDICATED:
  10496. VMA_ASSERT((m_DedicatedAllocation.m_pMappedData != VMA_NULL) == (m_MapCount != 0 || IsPersistentMap()));
  10497. return m_DedicatedAllocation.m_pMappedData;
  10498. default:
  10499. VMA_ASSERT(0);
  10500. return VMA_NULL;
  10501. }
  10502. }
  10503. void VmaAllocation_T::BlockAllocMap()
  10504. {
  10505. VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK);
  10506. VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it.");
  10507. if (m_MapCount < 0xFF)
  10508. {
  10509. ++m_MapCount;
  10510. }
  10511. else
  10512. {
  10513. VMA_ASSERT(0 && "Allocation mapped too many times simultaneously.");
  10514. }
  10515. }
  10516. void VmaAllocation_T::BlockAllocUnmap()
  10517. {
  10518. VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK);
  10519. if (m_MapCount > 0)
  10520. {
  10521. --m_MapCount;
  10522. }
  10523. else
  10524. {
  10525. VMA_ASSERT(0 && "Unmapping allocation not previously mapped.");
  10526. }
  10527. }
  10528. VkResult VmaAllocation_T::DedicatedAllocMap(VmaAllocator hAllocator, void** ppData)
  10529. {
  10530. VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED);
  10531. VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it.");
  10532. if (m_MapCount != 0 || IsPersistentMap())
  10533. {
  10534. if (m_MapCount < 0xFF)
  10535. {
  10536. VMA_ASSERT(m_DedicatedAllocation.m_pMappedData != VMA_NULL);
  10537. *ppData = m_DedicatedAllocation.m_pMappedData;
  10538. ++m_MapCount;
  10539. return VK_SUCCESS;
  10540. }
  10541. else
  10542. {
  10543. VMA_ASSERT(0 && "Dedicated allocation mapped too many times simultaneously.");
  10544. return VK_ERROR_MEMORY_MAP_FAILED;
  10545. }
  10546. }
  10547. else
  10548. {
  10549. VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)(
  10550. hAllocator->m_hDevice,
  10551. m_DedicatedAllocation.m_hMemory,
  10552. 0, // offset
  10553. VK_WHOLE_SIZE,
  10554. 0, // flags
  10555. ppData);
  10556. if (result == VK_SUCCESS)
  10557. {
  10558. m_DedicatedAllocation.m_pMappedData = *ppData;
  10559. m_MapCount = 1;
  10560. }
  10561. return result;
  10562. }
  10563. }
  10564. void VmaAllocation_T::DedicatedAllocUnmap(VmaAllocator hAllocator)
  10565. {
  10566. VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED);
  10567. if (m_MapCount > 0)
  10568. {
  10569. --m_MapCount;
  10570. if (m_MapCount == 0 && !IsPersistentMap())
  10571. {
  10572. m_DedicatedAllocation.m_pMappedData = VMA_NULL;
  10573. (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(
  10574. hAllocator->m_hDevice,
  10575. m_DedicatedAllocation.m_hMemory);
  10576. }
  10577. }
  10578. else
  10579. {
  10580. VMA_ASSERT(0 && "Unmapping dedicated allocation not previously mapped.");
  10581. }
  10582. }
  10583. #if VMA_STATS_STRING_ENABLED
  10584. void VmaAllocation_T::InitBufferImageUsage(uint32_t bufferImageUsage)
  10585. {
  10586. VMA_ASSERT(m_BufferImageUsage == 0);
  10587. m_BufferImageUsage = bufferImageUsage;
  10588. }
  10589. void VmaAllocation_T::PrintParameters(class VmaJsonWriter& json) const
  10590. {
  10591. json.WriteString("Type");
  10592. json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[m_SuballocationType]);
  10593. json.WriteString("Size");
  10594. json.WriteNumber(m_Size);
  10595. json.WriteString("Usage");
  10596. json.WriteNumber(m_BufferImageUsage);
  10597. if (m_pUserData != VMA_NULL)
  10598. {
  10599. json.WriteString("CustomData");
  10600. json.BeginString();
  10601. json.ContinueString_Pointer(m_pUserData);
  10602. json.EndString();
  10603. }
  10604. if (m_pName != VMA_NULL)
  10605. {
  10606. json.WriteString("Name");
  10607. json.WriteString(m_pName);
  10608. }
  10609. }
  10610. #endif // VMA_STATS_STRING_ENABLED
  10611. void VmaAllocation_T::FreeName(VmaAllocator hAllocator)
  10612. {
  10613. if(m_pName)
  10614. {
  10615. VmaFreeString(hAllocator->GetAllocationCallbacks(), m_pName);
  10616. m_pName = VMA_NULL;
  10617. }
  10618. }
  10619. #endif // _VMA_ALLOCATION_T_FUNCTIONS
  10620. #ifndef _VMA_BLOCK_VECTOR_FUNCTIONS
  10621. VmaBlockVector::VmaBlockVector(
  10622. VmaAllocator hAllocator,
  10623. VmaPool hParentPool,
  10624. uint32_t memoryTypeIndex,
  10625. VkDeviceSize preferredBlockSize,
  10626. size_t minBlockCount,
  10627. size_t maxBlockCount,
  10628. VkDeviceSize bufferImageGranularity,
  10629. bool explicitBlockSize,
  10630. uint32_t algorithm,
  10631. float priority,
  10632. VkDeviceSize minAllocationAlignment,
  10633. void* pMemoryAllocateNext)
  10634. : m_hAllocator(hAllocator),
  10635. m_hParentPool(hParentPool),
  10636. m_MemoryTypeIndex(memoryTypeIndex),
  10637. m_PreferredBlockSize(preferredBlockSize),
  10638. m_MinBlockCount(minBlockCount),
  10639. m_MaxBlockCount(maxBlockCount),
  10640. m_BufferImageGranularity(bufferImageGranularity),
  10641. m_ExplicitBlockSize(explicitBlockSize),
  10642. m_Algorithm(algorithm),
  10643. m_Priority(priority),
  10644. m_MinAllocationAlignment(minAllocationAlignment),
  10645. m_pMemoryAllocateNext(pMemoryAllocateNext),
  10646. m_Blocks(VmaStlAllocator<VmaDeviceMemoryBlock*>(hAllocator->GetAllocationCallbacks())),
  10647. m_NextBlockId(0) {}
  10648. VmaBlockVector::~VmaBlockVector()
  10649. {
  10650. for (size_t i = m_Blocks.size(); i--; )
  10651. {
  10652. m_Blocks[i]->Destroy(m_hAllocator);
  10653. vma_delete(m_hAllocator, m_Blocks[i]);
  10654. }
  10655. }
  10656. VkResult VmaBlockVector::CreateMinBlocks()
  10657. {
  10658. for (size_t i = 0; i < m_MinBlockCount; ++i)
  10659. {
  10660. VkResult res = CreateBlock(m_PreferredBlockSize, VMA_NULL);
  10661. if (res != VK_SUCCESS)
  10662. {
  10663. return res;
  10664. }
  10665. }
  10666. return VK_SUCCESS;
  10667. }
  10668. void VmaBlockVector::AddStatistics(VmaStatistics& inoutStats)
  10669. {
  10670. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  10671. const size_t blockCount = m_Blocks.size();
  10672. for (uint32_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
  10673. {
  10674. const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
  10675. VMA_ASSERT(pBlock);
  10676. VMA_HEAVY_ASSERT(pBlock->Validate());
  10677. pBlock->m_pMetadata->AddStatistics(inoutStats);
  10678. }
  10679. }
  10680. void VmaBlockVector::AddDetailedStatistics(VmaDetailedStatistics& inoutStats)
  10681. {
  10682. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  10683. const size_t blockCount = m_Blocks.size();
  10684. for (uint32_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
  10685. {
  10686. const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
  10687. VMA_ASSERT(pBlock);
  10688. VMA_HEAVY_ASSERT(pBlock->Validate());
  10689. pBlock->m_pMetadata->AddDetailedStatistics(inoutStats);
  10690. }
  10691. }
  10692. bool VmaBlockVector::IsEmpty()
  10693. {
  10694. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  10695. return m_Blocks.empty();
  10696. }
  10697. bool VmaBlockVector::IsCorruptionDetectionEnabled() const
  10698. {
  10699. const uint32_t requiredMemFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
  10700. return (VMA_DEBUG_DETECT_CORRUPTION != 0) &&
  10701. (VMA_DEBUG_MARGIN > 0) &&
  10702. (m_Algorithm == 0 || m_Algorithm == VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) &&
  10703. (m_hAllocator->m_MemProps.memoryTypes[m_MemoryTypeIndex].propertyFlags & requiredMemFlags) == requiredMemFlags;
  10704. }
  10705. VkResult VmaBlockVector::Allocate(
  10706. VkDeviceSize size,
  10707. VkDeviceSize alignment,
  10708. const VmaAllocationCreateInfo& createInfo,
  10709. VmaSuballocationType suballocType,
  10710. size_t allocationCount,
  10711. VmaAllocation* pAllocations)
  10712. {
  10713. size_t allocIndex;
  10714. VkResult res = VK_SUCCESS;
  10715. alignment = VMA_MAX(alignment, m_MinAllocationAlignment);
  10716. if (IsCorruptionDetectionEnabled())
  10717. {
  10718. size = VmaAlignUp<VkDeviceSize>(size, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE));
  10719. alignment = VmaAlignUp<VkDeviceSize>(alignment, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE));
  10720. }
  10721. {
  10722. VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex);
  10723. for (allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  10724. {
  10725. res = AllocatePage(
  10726. size,
  10727. alignment,
  10728. createInfo,
  10729. suballocType,
  10730. pAllocations + allocIndex);
  10731. if (res != VK_SUCCESS)
  10732. {
  10733. break;
  10734. }
  10735. }
  10736. }
  10737. if (res != VK_SUCCESS)
  10738. {
  10739. // Free all already created allocations.
  10740. while (allocIndex--)
  10741. Free(pAllocations[allocIndex]);
  10742. memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount);
  10743. }
  10744. return res;
  10745. }
  10746. VkResult VmaBlockVector::AllocatePage(
  10747. VkDeviceSize size,
  10748. VkDeviceSize alignment,
  10749. const VmaAllocationCreateInfo& createInfo,
  10750. VmaSuballocationType suballocType,
  10751. VmaAllocation* pAllocation)
  10752. {
  10753. const bool isUpperAddress = (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0;
  10754. VkDeviceSize freeMemory;
  10755. {
  10756. const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex);
  10757. VmaBudget heapBudget = {};
  10758. m_hAllocator->GetHeapBudgets(&heapBudget, heapIndex, 1);
  10759. freeMemory = (heapBudget.usage < heapBudget.budget) ? (heapBudget.budget - heapBudget.usage) : 0;
  10760. }
  10761. const bool canFallbackToDedicated = !HasExplicitBlockSize() &&
  10762. (createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0;
  10763. const bool canCreateNewBlock =
  10764. ((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0) &&
  10765. (m_Blocks.size() < m_MaxBlockCount) &&
  10766. (freeMemory >= size || !canFallbackToDedicated);
  10767. uint32_t strategy = createInfo.flags & VMA_ALLOCATION_CREATE_STRATEGY_MASK;
  10768. // Upper address can only be used with linear allocator and within single memory block.
  10769. if (isUpperAddress &&
  10770. (m_Algorithm != VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT || m_MaxBlockCount > 1))
  10771. {
  10772. return VK_ERROR_FEATURE_NOT_PRESENT;
  10773. }
  10774. // Early reject: requested allocation size is larger that maximum block size for this block vector.
  10775. if (size + VMA_DEBUG_MARGIN > m_PreferredBlockSize)
  10776. {
  10777. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10778. }
  10779. // 1. Search existing allocations. Try to allocate.
  10780. if (m_Algorithm == VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT)
  10781. {
  10782. // Use only last block.
  10783. if (!m_Blocks.empty())
  10784. {
  10785. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks.back();
  10786. VMA_ASSERT(pCurrBlock);
  10787. VkResult res = AllocateFromBlock(
  10788. pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation);
  10789. if (res == VK_SUCCESS)
  10790. {
  10791. VMA_DEBUG_LOG_FORMAT(" Returned from last block #%u", pCurrBlock->GetId());
  10792. IncrementallySortBlocks();
  10793. return VK_SUCCESS;
  10794. }
  10795. }
  10796. }
  10797. else
  10798. {
  10799. if (strategy != VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT) // MIN_MEMORY or default
  10800. {
  10801. const bool isHostVisible =
  10802. (m_hAllocator->m_MemProps.memoryTypes[m_MemoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0;
  10803. if(isHostVisible)
  10804. {
  10805. const bool isMappingAllowed = (createInfo.flags &
  10806. (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0;
  10807. /*
  10808. For non-mappable allocations, check blocks that are not mapped first.
  10809. For mappable allocations, check blocks that are already mapped first.
  10810. This way, having many blocks, we will separate mappable and non-mappable allocations,
  10811. hopefully limiting the number of blocks that are mapped, which will help tools like RenderDoc.
  10812. */
  10813. for(size_t mappingI = 0; mappingI < 2; ++mappingI)
  10814. {
  10815. // Forward order in m_Blocks - prefer blocks with smallest amount of free space.
  10816. for (size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  10817. {
  10818. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
  10819. VMA_ASSERT(pCurrBlock);
  10820. const bool isBlockMapped = pCurrBlock->GetMappedData() != VMA_NULL;
  10821. if((mappingI == 0) == (isMappingAllowed == isBlockMapped))
  10822. {
  10823. VkResult res = AllocateFromBlock(
  10824. pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation);
  10825. if (res == VK_SUCCESS)
  10826. {
  10827. VMA_DEBUG_LOG_FORMAT(" Returned from existing block #%u", pCurrBlock->GetId());
  10828. IncrementallySortBlocks();
  10829. return VK_SUCCESS;
  10830. }
  10831. }
  10832. }
  10833. }
  10834. }
  10835. else
  10836. {
  10837. // Forward order in m_Blocks - prefer blocks with smallest amount of free space.
  10838. for (size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  10839. {
  10840. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
  10841. VMA_ASSERT(pCurrBlock);
  10842. VkResult res = AllocateFromBlock(
  10843. pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation);
  10844. if (res == VK_SUCCESS)
  10845. {
  10846. VMA_DEBUG_LOG_FORMAT(" Returned from existing block #%u", pCurrBlock->GetId());
  10847. IncrementallySortBlocks();
  10848. return VK_SUCCESS;
  10849. }
  10850. }
  10851. }
  10852. }
  10853. else // VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT
  10854. {
  10855. // Backward order in m_Blocks - prefer blocks with largest amount of free space.
  10856. for (size_t blockIndex = m_Blocks.size(); blockIndex--; )
  10857. {
  10858. VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
  10859. VMA_ASSERT(pCurrBlock);
  10860. VkResult res = AllocateFromBlock(pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation);
  10861. if (res == VK_SUCCESS)
  10862. {
  10863. VMA_DEBUG_LOG_FORMAT(" Returned from existing block #%u", pCurrBlock->GetId());
  10864. IncrementallySortBlocks();
  10865. return VK_SUCCESS;
  10866. }
  10867. }
  10868. }
  10869. }
  10870. // 2. Try to create new block.
  10871. if (canCreateNewBlock)
  10872. {
  10873. // Calculate optimal size for new block.
  10874. VkDeviceSize newBlockSize = m_PreferredBlockSize;
  10875. uint32_t newBlockSizeShift = 0;
  10876. const uint32_t NEW_BLOCK_SIZE_SHIFT_MAX = 3;
  10877. if (!m_ExplicitBlockSize)
  10878. {
  10879. // Allocate 1/8, 1/4, 1/2 as first blocks.
  10880. const VkDeviceSize maxExistingBlockSize = CalcMaxBlockSize();
  10881. for (uint32_t i = 0; i < NEW_BLOCK_SIZE_SHIFT_MAX; ++i)
  10882. {
  10883. const VkDeviceSize smallerNewBlockSize = newBlockSize / 2;
  10884. if (smallerNewBlockSize > maxExistingBlockSize && smallerNewBlockSize >= size * 2)
  10885. {
  10886. newBlockSize = smallerNewBlockSize;
  10887. ++newBlockSizeShift;
  10888. }
  10889. else
  10890. {
  10891. break;
  10892. }
  10893. }
  10894. }
  10895. size_t newBlockIndex = 0;
  10896. VkResult res = (newBlockSize <= freeMemory || !canFallbackToDedicated) ?
  10897. CreateBlock(newBlockSize, &newBlockIndex) : VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10898. // Allocation of this size failed? Try 1/2, 1/4, 1/8 of m_PreferredBlockSize.
  10899. if (!m_ExplicitBlockSize)
  10900. {
  10901. while (res < 0 && newBlockSizeShift < NEW_BLOCK_SIZE_SHIFT_MAX)
  10902. {
  10903. const VkDeviceSize smallerNewBlockSize = newBlockSize / 2;
  10904. if (smallerNewBlockSize >= size)
  10905. {
  10906. newBlockSize = smallerNewBlockSize;
  10907. ++newBlockSizeShift;
  10908. res = (newBlockSize <= freeMemory || !canFallbackToDedicated) ?
  10909. CreateBlock(newBlockSize, &newBlockIndex) : VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10910. }
  10911. else
  10912. {
  10913. break;
  10914. }
  10915. }
  10916. }
  10917. if (res == VK_SUCCESS)
  10918. {
  10919. VmaDeviceMemoryBlock* const pBlock = m_Blocks[newBlockIndex];
  10920. VMA_ASSERT(pBlock->m_pMetadata->GetSize() >= size);
  10921. res = AllocateFromBlock(
  10922. pBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation);
  10923. if (res == VK_SUCCESS)
  10924. {
  10925. VMA_DEBUG_LOG_FORMAT(" Created new block #%u Size=%llu", pBlock->GetId(), newBlockSize);
  10926. IncrementallySortBlocks();
  10927. return VK_SUCCESS;
  10928. }
  10929. else
  10930. {
  10931. // Allocation from new block failed, possibly due to VMA_DEBUG_MARGIN or alignment.
  10932. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10933. }
  10934. }
  10935. }
  10936. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  10937. }
  10938. void VmaBlockVector::Free(const VmaAllocation hAllocation)
  10939. {
  10940. VmaDeviceMemoryBlock* pBlockToDelete = VMA_NULL;
  10941. bool budgetExceeded = false;
  10942. {
  10943. const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex);
  10944. VmaBudget heapBudget = {};
  10945. m_hAllocator->GetHeapBudgets(&heapBudget, heapIndex, 1);
  10946. budgetExceeded = heapBudget.usage >= heapBudget.budget;
  10947. }
  10948. // Scope for lock.
  10949. {
  10950. VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex);
  10951. VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock();
  10952. if (IsCorruptionDetectionEnabled())
  10953. {
  10954. VkResult res = pBlock->ValidateMagicValueAfterAllocation(m_hAllocator, hAllocation->GetOffset(), hAllocation->GetSize());
  10955. VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to validate magic value.");
  10956. }
  10957. if (hAllocation->IsPersistentMap())
  10958. {
  10959. pBlock->Unmap(m_hAllocator, 1);
  10960. }
  10961. const bool hadEmptyBlockBeforeFree = HasEmptyBlock();
  10962. pBlock->m_pMetadata->Free(hAllocation->GetAllocHandle());
  10963. pBlock->PostFree(m_hAllocator);
  10964. VMA_HEAVY_ASSERT(pBlock->Validate());
  10965. VMA_DEBUG_LOG_FORMAT(" Freed from MemoryTypeIndex=%u", m_MemoryTypeIndex);
  10966. const bool canDeleteBlock = m_Blocks.size() > m_MinBlockCount;
  10967. // pBlock became empty after this deallocation.
  10968. if (pBlock->m_pMetadata->IsEmpty())
  10969. {
  10970. // Already had empty block. We don't want to have two, so delete this one.
  10971. if ((hadEmptyBlockBeforeFree || budgetExceeded) && canDeleteBlock)
  10972. {
  10973. pBlockToDelete = pBlock;
  10974. Remove(pBlock);
  10975. }
  10976. // else: We now have one empty block - leave it. A hysteresis to avoid allocating whole block back and forth.
  10977. }
  10978. // pBlock didn't become empty, but we have another empty block - find and free that one.
  10979. // (This is optional, heuristics.)
  10980. else if (hadEmptyBlockBeforeFree && canDeleteBlock)
  10981. {
  10982. VmaDeviceMemoryBlock* pLastBlock = m_Blocks.back();
  10983. if (pLastBlock->m_pMetadata->IsEmpty())
  10984. {
  10985. pBlockToDelete = pLastBlock;
  10986. m_Blocks.pop_back();
  10987. }
  10988. }
  10989. IncrementallySortBlocks();
  10990. }
  10991. // Destruction of a free block. Deferred until this point, outside of mutex
  10992. // lock, for performance reason.
  10993. if (pBlockToDelete != VMA_NULL)
  10994. {
  10995. VMA_DEBUG_LOG_FORMAT(" Deleted empty block #%u", pBlockToDelete->GetId());
  10996. pBlockToDelete->Destroy(m_hAllocator);
  10997. vma_delete(m_hAllocator, pBlockToDelete);
  10998. }
  10999. m_hAllocator->m_Budget.RemoveAllocation(m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex), hAllocation->GetSize());
  11000. m_hAllocator->m_AllocationObjectAllocator.Free(hAllocation);
  11001. }
  11002. VkDeviceSize VmaBlockVector::CalcMaxBlockSize() const
  11003. {
  11004. VkDeviceSize result = 0;
  11005. for (size_t i = m_Blocks.size(); i--; )
  11006. {
  11007. result = VMA_MAX(result, m_Blocks[i]->m_pMetadata->GetSize());
  11008. if (result >= m_PreferredBlockSize)
  11009. {
  11010. break;
  11011. }
  11012. }
  11013. return result;
  11014. }
  11015. void VmaBlockVector::Remove(VmaDeviceMemoryBlock* pBlock)
  11016. {
  11017. for (uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  11018. {
  11019. if (m_Blocks[blockIndex] == pBlock)
  11020. {
  11021. VmaVectorRemove(m_Blocks, blockIndex);
  11022. return;
  11023. }
  11024. }
  11025. VMA_ASSERT(0);
  11026. }
  11027. void VmaBlockVector::IncrementallySortBlocks()
  11028. {
  11029. if (!m_IncrementalSort)
  11030. return;
  11031. if (m_Algorithm != VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT)
  11032. {
  11033. // Bubble sort only until first swap.
  11034. for (size_t i = 1; i < m_Blocks.size(); ++i)
  11035. {
  11036. if (m_Blocks[i - 1]->m_pMetadata->GetSumFreeSize() > m_Blocks[i]->m_pMetadata->GetSumFreeSize())
  11037. {
  11038. VMA_SWAP(m_Blocks[i - 1], m_Blocks[i]);
  11039. return;
  11040. }
  11041. }
  11042. }
  11043. }
  11044. void VmaBlockVector::SortByFreeSize()
  11045. {
  11046. VMA_SORT(m_Blocks.begin(), m_Blocks.end(),
  11047. [](VmaDeviceMemoryBlock* b1, VmaDeviceMemoryBlock* b2) -> bool
  11048. {
  11049. return b1->m_pMetadata->GetSumFreeSize() < b2->m_pMetadata->GetSumFreeSize();
  11050. });
  11051. }
  11052. VkResult VmaBlockVector::AllocateFromBlock(
  11053. VmaDeviceMemoryBlock* pBlock,
  11054. VkDeviceSize size,
  11055. VkDeviceSize alignment,
  11056. VmaAllocationCreateFlags allocFlags,
  11057. void* pUserData,
  11058. VmaSuballocationType suballocType,
  11059. uint32_t strategy,
  11060. VmaAllocation* pAllocation)
  11061. {
  11062. const bool isUpperAddress = (allocFlags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0;
  11063. VmaAllocationRequest currRequest = {};
  11064. if (pBlock->m_pMetadata->CreateAllocationRequest(
  11065. size,
  11066. alignment,
  11067. isUpperAddress,
  11068. suballocType,
  11069. strategy,
  11070. &currRequest))
  11071. {
  11072. return CommitAllocationRequest(currRequest, pBlock, alignment, allocFlags, pUserData, suballocType, pAllocation);
  11073. }
  11074. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  11075. }
  11076. VkResult VmaBlockVector::CommitAllocationRequest(
  11077. VmaAllocationRequest& allocRequest,
  11078. VmaDeviceMemoryBlock* pBlock,
  11079. VkDeviceSize alignment,
  11080. VmaAllocationCreateFlags allocFlags,
  11081. void* pUserData,
  11082. VmaSuballocationType suballocType,
  11083. VmaAllocation* pAllocation)
  11084. {
  11085. const bool mapped = (allocFlags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0;
  11086. const bool isUserDataString = (allocFlags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0;
  11087. const bool isMappingAllowed = (allocFlags &
  11088. (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0;
  11089. pBlock->PostAlloc(m_hAllocator);
  11090. // Allocate from pCurrBlock.
  11091. if (mapped)
  11092. {
  11093. VkResult res = pBlock->Map(m_hAllocator, 1, VMA_NULL);
  11094. if (res != VK_SUCCESS)
  11095. {
  11096. return res;
  11097. }
  11098. }
  11099. *pAllocation = m_hAllocator->m_AllocationObjectAllocator.Allocate(isMappingAllowed);
  11100. pBlock->m_pMetadata->Alloc(allocRequest, suballocType, *pAllocation);
  11101. (*pAllocation)->InitBlockAllocation(
  11102. pBlock,
  11103. allocRequest.allocHandle,
  11104. alignment,
  11105. allocRequest.size, // Not size, as actual allocation size may be larger than requested!
  11106. m_MemoryTypeIndex,
  11107. suballocType,
  11108. mapped);
  11109. VMA_HEAVY_ASSERT(pBlock->Validate());
  11110. if (isUserDataString)
  11111. (*pAllocation)->SetName(m_hAllocator, (const char*)pUserData);
  11112. else
  11113. (*pAllocation)->SetUserData(m_hAllocator, pUserData);
  11114. m_hAllocator->m_Budget.AddAllocation(m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex), allocRequest.size);
  11115. if (VMA_DEBUG_INITIALIZE_ALLOCATIONS)
  11116. {
  11117. m_hAllocator->FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED);
  11118. }
  11119. if (IsCorruptionDetectionEnabled())
  11120. {
  11121. VkResult res = pBlock->WriteMagicValueAfterAllocation(m_hAllocator, (*pAllocation)->GetOffset(), allocRequest.size);
  11122. VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to write magic value.");
  11123. }
  11124. return VK_SUCCESS;
  11125. }
  11126. VkResult VmaBlockVector::CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex)
  11127. {
  11128. VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
  11129. allocInfo.pNext = m_pMemoryAllocateNext;
  11130. allocInfo.memoryTypeIndex = m_MemoryTypeIndex;
  11131. allocInfo.allocationSize = blockSize;
  11132. #if VMA_BUFFER_DEVICE_ADDRESS
  11133. // Every standalone block can potentially contain a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT - always enable the feature.
  11134. VkMemoryAllocateFlagsInfoKHR allocFlagsInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR };
  11135. if (m_hAllocator->m_UseKhrBufferDeviceAddress)
  11136. {
  11137. allocFlagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR;
  11138. VmaPnextChainPushFront(&allocInfo, &allocFlagsInfo);
  11139. }
  11140. #endif // VMA_BUFFER_DEVICE_ADDRESS
  11141. #if VMA_MEMORY_PRIORITY
  11142. VkMemoryPriorityAllocateInfoEXT priorityInfo = { VK_STRUCTURE_TYPE_MEMORY_PRIORITY_ALLOCATE_INFO_EXT };
  11143. if (m_hAllocator->m_UseExtMemoryPriority)
  11144. {
  11145. VMA_ASSERT(m_Priority >= 0.f && m_Priority <= 1.f);
  11146. priorityInfo.priority = m_Priority;
  11147. VmaPnextChainPushFront(&allocInfo, &priorityInfo);
  11148. }
  11149. #endif // VMA_MEMORY_PRIORITY
  11150. #if VMA_EXTERNAL_MEMORY
  11151. // Attach VkExportMemoryAllocateInfoKHR if necessary.
  11152. VkExportMemoryAllocateInfoKHR exportMemoryAllocInfo = { VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR };
  11153. exportMemoryAllocInfo.handleTypes = m_hAllocator->GetExternalMemoryHandleTypeFlags(m_MemoryTypeIndex);
  11154. if (exportMemoryAllocInfo.handleTypes != 0)
  11155. {
  11156. VmaPnextChainPushFront(&allocInfo, &exportMemoryAllocInfo);
  11157. }
  11158. #endif // VMA_EXTERNAL_MEMORY
  11159. VkDeviceMemory mem = VK_NULL_HANDLE;
  11160. VkResult res = m_hAllocator->AllocateVulkanMemory(&allocInfo, &mem);
  11161. if (res < 0)
  11162. {
  11163. return res;
  11164. }
  11165. // New VkDeviceMemory successfully created.
  11166. // Create new Allocation for it.
  11167. VmaDeviceMemoryBlock* const pBlock = vma_new(m_hAllocator, VmaDeviceMemoryBlock)(m_hAllocator);
  11168. pBlock->Init(
  11169. m_hAllocator,
  11170. m_hParentPool,
  11171. m_MemoryTypeIndex,
  11172. mem,
  11173. allocInfo.allocationSize,
  11174. m_NextBlockId++,
  11175. m_Algorithm,
  11176. m_BufferImageGranularity);
  11177. m_Blocks.push_back(pBlock);
  11178. if (pNewBlockIndex != VMA_NULL)
  11179. {
  11180. *pNewBlockIndex = m_Blocks.size() - 1;
  11181. }
  11182. return VK_SUCCESS;
  11183. }
  11184. bool VmaBlockVector::HasEmptyBlock()
  11185. {
  11186. for (size_t index = 0, count = m_Blocks.size(); index < count; ++index)
  11187. {
  11188. VmaDeviceMemoryBlock* const pBlock = m_Blocks[index];
  11189. if (pBlock->m_pMetadata->IsEmpty())
  11190. {
  11191. return true;
  11192. }
  11193. }
  11194. return false;
  11195. }
  11196. #if VMA_STATS_STRING_ENABLED
  11197. void VmaBlockVector::PrintDetailedMap(class VmaJsonWriter& json)
  11198. {
  11199. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  11200. json.BeginObject();
  11201. for (size_t i = 0; i < m_Blocks.size(); ++i)
  11202. {
  11203. json.BeginString();
  11204. json.ContinueString(m_Blocks[i]->GetId());
  11205. json.EndString();
  11206. json.BeginObject();
  11207. json.WriteString("MapRefCount");
  11208. json.WriteNumber(m_Blocks[i]->GetMapRefCount());
  11209. m_Blocks[i]->m_pMetadata->PrintDetailedMap(json);
  11210. json.EndObject();
  11211. }
  11212. json.EndObject();
  11213. }
  11214. #endif // VMA_STATS_STRING_ENABLED
  11215. VkResult VmaBlockVector::CheckCorruption()
  11216. {
  11217. if (!IsCorruptionDetectionEnabled())
  11218. {
  11219. return VK_ERROR_FEATURE_NOT_PRESENT;
  11220. }
  11221. VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex);
  11222. for (uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
  11223. {
  11224. VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
  11225. VMA_ASSERT(pBlock);
  11226. VkResult res = pBlock->CheckCorruption(m_hAllocator);
  11227. if (res != VK_SUCCESS)
  11228. {
  11229. return res;
  11230. }
  11231. }
  11232. return VK_SUCCESS;
  11233. }
  11234. #endif // _VMA_BLOCK_VECTOR_FUNCTIONS
  11235. #ifndef _VMA_DEFRAGMENTATION_CONTEXT_FUNCTIONS
  11236. VmaDefragmentationContext_T::VmaDefragmentationContext_T(
  11237. VmaAllocator hAllocator,
  11238. const VmaDefragmentationInfo& info)
  11239. : m_MaxPassBytes(info.maxBytesPerPass == 0 ? VK_WHOLE_SIZE : info.maxBytesPerPass),
  11240. m_MaxPassAllocations(info.maxAllocationsPerPass == 0 ? UINT32_MAX : info.maxAllocationsPerPass),
  11241. m_BreakCallback(info.pfnBreakCallback),
  11242. m_BreakCallbackUserData(info.pBreakCallbackUserData),
  11243. m_MoveAllocator(hAllocator->GetAllocationCallbacks()),
  11244. m_Moves(m_MoveAllocator)
  11245. {
  11246. m_Algorithm = info.flags & VMA_DEFRAGMENTATION_FLAG_ALGORITHM_MASK;
  11247. if (info.pool != VMA_NULL)
  11248. {
  11249. m_BlockVectorCount = 1;
  11250. m_PoolBlockVector = &info.pool->m_BlockVector;
  11251. m_pBlockVectors = &m_PoolBlockVector;
  11252. m_PoolBlockVector->SetIncrementalSort(false);
  11253. m_PoolBlockVector->SortByFreeSize();
  11254. }
  11255. else
  11256. {
  11257. m_BlockVectorCount = hAllocator->GetMemoryTypeCount();
  11258. m_PoolBlockVector = VMA_NULL;
  11259. m_pBlockVectors = hAllocator->m_pBlockVectors;
  11260. for (uint32_t i = 0; i < m_BlockVectorCount; ++i)
  11261. {
  11262. VmaBlockVector* vector = m_pBlockVectors[i];
  11263. if (vector != VMA_NULL)
  11264. {
  11265. vector->SetIncrementalSort(false);
  11266. vector->SortByFreeSize();
  11267. }
  11268. }
  11269. }
  11270. switch (m_Algorithm)
  11271. {
  11272. case 0: // Default algorithm
  11273. m_Algorithm = VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT;
  11274. m_AlgorithmState = vma_new_array(hAllocator, StateBalanced, m_BlockVectorCount);
  11275. break;
  11276. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT:
  11277. m_AlgorithmState = vma_new_array(hAllocator, StateBalanced, m_BlockVectorCount);
  11278. break;
  11279. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT:
  11280. if (hAllocator->GetBufferImageGranularity() > 1)
  11281. {
  11282. m_AlgorithmState = vma_new_array(hAllocator, StateExtensive, m_BlockVectorCount);
  11283. }
  11284. break;
  11285. }
  11286. }
  11287. VmaDefragmentationContext_T::~VmaDefragmentationContext_T()
  11288. {
  11289. if (m_PoolBlockVector != VMA_NULL)
  11290. {
  11291. m_PoolBlockVector->SetIncrementalSort(true);
  11292. }
  11293. else
  11294. {
  11295. for (uint32_t i = 0; i < m_BlockVectorCount; ++i)
  11296. {
  11297. VmaBlockVector* vector = m_pBlockVectors[i];
  11298. if (vector != VMA_NULL)
  11299. vector->SetIncrementalSort(true);
  11300. }
  11301. }
  11302. if (m_AlgorithmState)
  11303. {
  11304. switch (m_Algorithm)
  11305. {
  11306. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT:
  11307. vma_delete_array(m_MoveAllocator.m_pCallbacks, reinterpret_cast<StateBalanced*>(m_AlgorithmState), m_BlockVectorCount);
  11308. break;
  11309. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT:
  11310. vma_delete_array(m_MoveAllocator.m_pCallbacks, reinterpret_cast<StateExtensive*>(m_AlgorithmState), m_BlockVectorCount);
  11311. break;
  11312. default:
  11313. VMA_ASSERT(0);
  11314. }
  11315. }
  11316. }
  11317. VkResult VmaDefragmentationContext_T::DefragmentPassBegin(VmaDefragmentationPassMoveInfo& moveInfo)
  11318. {
  11319. if (m_PoolBlockVector != VMA_NULL)
  11320. {
  11321. VmaMutexLockWrite lock(m_PoolBlockVector->GetMutex(), m_PoolBlockVector->GetAllocator()->m_UseMutex);
  11322. if (m_PoolBlockVector->GetBlockCount() > 1)
  11323. ComputeDefragmentation(*m_PoolBlockVector, 0);
  11324. else if (m_PoolBlockVector->GetBlockCount() == 1)
  11325. ReallocWithinBlock(*m_PoolBlockVector, m_PoolBlockVector->GetBlock(0));
  11326. }
  11327. else
  11328. {
  11329. for (uint32_t i = 0; i < m_BlockVectorCount; ++i)
  11330. {
  11331. if (m_pBlockVectors[i] != VMA_NULL)
  11332. {
  11333. VmaMutexLockWrite lock(m_pBlockVectors[i]->GetMutex(), m_pBlockVectors[i]->GetAllocator()->m_UseMutex);
  11334. if (m_pBlockVectors[i]->GetBlockCount() > 1)
  11335. {
  11336. if (ComputeDefragmentation(*m_pBlockVectors[i], i))
  11337. break;
  11338. }
  11339. else if (m_pBlockVectors[i]->GetBlockCount() == 1)
  11340. {
  11341. if (ReallocWithinBlock(*m_pBlockVectors[i], m_pBlockVectors[i]->GetBlock(0)))
  11342. break;
  11343. }
  11344. }
  11345. }
  11346. }
  11347. moveInfo.moveCount = static_cast<uint32_t>(m_Moves.size());
  11348. if (moveInfo.moveCount > 0)
  11349. {
  11350. moveInfo.pMoves = m_Moves.data();
  11351. return VK_INCOMPLETE;
  11352. }
  11353. moveInfo.pMoves = VMA_NULL;
  11354. return VK_SUCCESS;
  11355. }
  11356. VkResult VmaDefragmentationContext_T::DefragmentPassEnd(VmaDefragmentationPassMoveInfo& moveInfo)
  11357. {
  11358. VMA_ASSERT(moveInfo.moveCount > 0 ? moveInfo.pMoves != VMA_NULL : true);
  11359. VkResult result = VK_SUCCESS;
  11360. VmaStlAllocator<FragmentedBlock> blockAllocator(m_MoveAllocator.m_pCallbacks);
  11361. VmaVector<FragmentedBlock, VmaStlAllocator<FragmentedBlock>> immovableBlocks(blockAllocator);
  11362. VmaVector<FragmentedBlock, VmaStlAllocator<FragmentedBlock>> mappedBlocks(blockAllocator);
  11363. VmaAllocator allocator = VMA_NULL;
  11364. for (uint32_t i = 0; i < moveInfo.moveCount; ++i)
  11365. {
  11366. VmaDefragmentationMove& move = moveInfo.pMoves[i];
  11367. size_t prevCount = 0, currentCount = 0;
  11368. VkDeviceSize freedBlockSize = 0;
  11369. uint32_t vectorIndex;
  11370. VmaBlockVector* vector;
  11371. if (m_PoolBlockVector != VMA_NULL)
  11372. {
  11373. vectorIndex = 0;
  11374. vector = m_PoolBlockVector;
  11375. }
  11376. else
  11377. {
  11378. vectorIndex = move.srcAllocation->GetMemoryTypeIndex();
  11379. vector = m_pBlockVectors[vectorIndex];
  11380. VMA_ASSERT(vector != VMA_NULL);
  11381. }
  11382. switch (move.operation)
  11383. {
  11384. case VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY:
  11385. {
  11386. uint8_t mapCount = move.srcAllocation->SwapBlockAllocation(vector->m_hAllocator, move.dstTmpAllocation);
  11387. if (mapCount > 0)
  11388. {
  11389. allocator = vector->m_hAllocator;
  11390. VmaDeviceMemoryBlock* newMapBlock = move.srcAllocation->GetBlock();
  11391. bool notPresent = true;
  11392. for (FragmentedBlock& block : mappedBlocks)
  11393. {
  11394. if (block.block == newMapBlock)
  11395. {
  11396. notPresent = false;
  11397. block.data += mapCount;
  11398. break;
  11399. }
  11400. }
  11401. if (notPresent)
  11402. mappedBlocks.push_back({ mapCount, newMapBlock });
  11403. }
  11404. // Scope for locks, Free have it's own lock
  11405. {
  11406. VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11407. prevCount = vector->GetBlockCount();
  11408. freedBlockSize = move.dstTmpAllocation->GetBlock()->m_pMetadata->GetSize();
  11409. }
  11410. vector->Free(move.dstTmpAllocation);
  11411. {
  11412. VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11413. currentCount = vector->GetBlockCount();
  11414. }
  11415. result = VK_INCOMPLETE;
  11416. break;
  11417. }
  11418. case VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE:
  11419. {
  11420. m_PassStats.bytesMoved -= move.srcAllocation->GetSize();
  11421. --m_PassStats.allocationsMoved;
  11422. vector->Free(move.dstTmpAllocation);
  11423. VmaDeviceMemoryBlock* newBlock = move.srcAllocation->GetBlock();
  11424. bool notPresent = true;
  11425. for (const FragmentedBlock& block : immovableBlocks)
  11426. {
  11427. if (block.block == newBlock)
  11428. {
  11429. notPresent = false;
  11430. break;
  11431. }
  11432. }
  11433. if (notPresent)
  11434. immovableBlocks.push_back({ vectorIndex, newBlock });
  11435. break;
  11436. }
  11437. case VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY:
  11438. {
  11439. m_PassStats.bytesMoved -= move.srcAllocation->GetSize();
  11440. --m_PassStats.allocationsMoved;
  11441. // Scope for locks, Free have it's own lock
  11442. {
  11443. VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11444. prevCount = vector->GetBlockCount();
  11445. freedBlockSize = move.srcAllocation->GetBlock()->m_pMetadata->GetSize();
  11446. }
  11447. vector->Free(move.srcAllocation);
  11448. {
  11449. VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11450. currentCount = vector->GetBlockCount();
  11451. }
  11452. freedBlockSize *= prevCount - currentCount;
  11453. VkDeviceSize dstBlockSize;
  11454. {
  11455. VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11456. dstBlockSize = move.dstTmpAllocation->GetBlock()->m_pMetadata->GetSize();
  11457. }
  11458. vector->Free(move.dstTmpAllocation);
  11459. {
  11460. VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11461. freedBlockSize += dstBlockSize * (currentCount - vector->GetBlockCount());
  11462. currentCount = vector->GetBlockCount();
  11463. }
  11464. result = VK_INCOMPLETE;
  11465. break;
  11466. }
  11467. default:
  11468. VMA_ASSERT(0);
  11469. }
  11470. if (prevCount > currentCount)
  11471. {
  11472. size_t freedBlocks = prevCount - currentCount;
  11473. m_PassStats.deviceMemoryBlocksFreed += static_cast<uint32_t>(freedBlocks);
  11474. m_PassStats.bytesFreed += freedBlockSize;
  11475. }
  11476. if(m_Algorithm == VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT &&
  11477. m_AlgorithmState != VMA_NULL)
  11478. {
  11479. // Avoid unnecessary tries to allocate when new free block is available
  11480. StateExtensive& state = reinterpret_cast<StateExtensive*>(m_AlgorithmState)[vectorIndex];
  11481. if (state.firstFreeBlock != SIZE_MAX)
  11482. {
  11483. const size_t diff = prevCount - currentCount;
  11484. if (state.firstFreeBlock >= diff)
  11485. {
  11486. state.firstFreeBlock -= diff;
  11487. if (state.firstFreeBlock != 0)
  11488. state.firstFreeBlock -= vector->GetBlock(state.firstFreeBlock - 1)->m_pMetadata->IsEmpty();
  11489. }
  11490. else
  11491. state.firstFreeBlock = 0;
  11492. }
  11493. }
  11494. }
  11495. moveInfo.moveCount = 0;
  11496. moveInfo.pMoves = VMA_NULL;
  11497. m_Moves.clear();
  11498. // Update stats
  11499. m_GlobalStats.allocationsMoved += m_PassStats.allocationsMoved;
  11500. m_GlobalStats.bytesFreed += m_PassStats.bytesFreed;
  11501. m_GlobalStats.bytesMoved += m_PassStats.bytesMoved;
  11502. m_GlobalStats.deviceMemoryBlocksFreed += m_PassStats.deviceMemoryBlocksFreed;
  11503. m_PassStats = { 0 };
  11504. // Move blocks with immovable allocations according to algorithm
  11505. if (immovableBlocks.size() > 0)
  11506. {
  11507. do
  11508. {
  11509. if(m_Algorithm == VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT)
  11510. {
  11511. if (m_AlgorithmState != VMA_NULL)
  11512. {
  11513. bool swapped = false;
  11514. // Move to the start of free blocks range
  11515. for (const FragmentedBlock& block : immovableBlocks)
  11516. {
  11517. StateExtensive& state = reinterpret_cast<StateExtensive*>(m_AlgorithmState)[block.data];
  11518. if (state.operation != StateExtensive::Operation::Cleanup)
  11519. {
  11520. VmaBlockVector* vector = m_pBlockVectors[block.data];
  11521. VmaMutexLockWrite lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11522. for (size_t i = 0, count = vector->GetBlockCount() - m_ImmovableBlockCount; i < count; ++i)
  11523. {
  11524. if (vector->GetBlock(i) == block.block)
  11525. {
  11526. VMA_SWAP(vector->m_Blocks[i], vector->m_Blocks[vector->GetBlockCount() - ++m_ImmovableBlockCount]);
  11527. if (state.firstFreeBlock != SIZE_MAX)
  11528. {
  11529. if (i + 1 < state.firstFreeBlock)
  11530. {
  11531. if (state.firstFreeBlock > 1)
  11532. VMA_SWAP(vector->m_Blocks[i], vector->m_Blocks[--state.firstFreeBlock]);
  11533. else
  11534. --state.firstFreeBlock;
  11535. }
  11536. }
  11537. swapped = true;
  11538. break;
  11539. }
  11540. }
  11541. }
  11542. }
  11543. if (swapped)
  11544. result = VK_INCOMPLETE;
  11545. break;
  11546. }
  11547. }
  11548. // Move to the beginning
  11549. for (const FragmentedBlock& block : immovableBlocks)
  11550. {
  11551. VmaBlockVector* vector = m_pBlockVectors[block.data];
  11552. VmaMutexLockWrite lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex);
  11553. for (size_t i = m_ImmovableBlockCount; i < vector->GetBlockCount(); ++i)
  11554. {
  11555. if (vector->GetBlock(i) == block.block)
  11556. {
  11557. VMA_SWAP(vector->m_Blocks[i], vector->m_Blocks[m_ImmovableBlockCount++]);
  11558. break;
  11559. }
  11560. }
  11561. }
  11562. } while (false);
  11563. }
  11564. // Bulk-map destination blocks
  11565. for (const FragmentedBlock& block : mappedBlocks)
  11566. {
  11567. VkResult res = block.block->Map(allocator, block.data, VMA_NULL);
  11568. VMA_ASSERT(res == VK_SUCCESS);
  11569. }
  11570. return result;
  11571. }
  11572. bool VmaDefragmentationContext_T::ComputeDefragmentation(VmaBlockVector& vector, size_t index)
  11573. {
  11574. switch (m_Algorithm)
  11575. {
  11576. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT:
  11577. return ComputeDefragmentation_Fast(vector);
  11578. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT:
  11579. return ComputeDefragmentation_Balanced(vector, index, true);
  11580. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT:
  11581. return ComputeDefragmentation_Full(vector);
  11582. case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT:
  11583. return ComputeDefragmentation_Extensive(vector, index);
  11584. default:
  11585. VMA_ASSERT(0);
  11586. return ComputeDefragmentation_Balanced(vector, index, true);
  11587. }
  11588. }
  11589. VmaDefragmentationContext_T::MoveAllocationData VmaDefragmentationContext_T::GetMoveData(
  11590. VmaAllocHandle handle, VmaBlockMetadata* metadata)
  11591. {
  11592. MoveAllocationData moveData;
  11593. moveData.move.srcAllocation = (VmaAllocation)metadata->GetAllocationUserData(handle);
  11594. moveData.size = moveData.move.srcAllocation->GetSize();
  11595. moveData.alignment = moveData.move.srcAllocation->GetAlignment();
  11596. moveData.type = moveData.move.srcAllocation->GetSuballocationType();
  11597. moveData.flags = 0;
  11598. if (moveData.move.srcAllocation->IsPersistentMap())
  11599. moveData.flags |= VMA_ALLOCATION_CREATE_MAPPED_BIT;
  11600. if (moveData.move.srcAllocation->IsMappingAllowed())
  11601. moveData.flags |= VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT;
  11602. return moveData;
  11603. }
  11604. VmaDefragmentationContext_T::CounterStatus VmaDefragmentationContext_T::CheckCounters(VkDeviceSize bytes)
  11605. {
  11606. // Check custom criteria if exists
  11607. if (m_BreakCallback && m_BreakCallback(m_BreakCallbackUserData))
  11608. return CounterStatus::End;
  11609. // Ignore allocation if will exceed max size for copy
  11610. if (m_PassStats.bytesMoved + bytes > m_MaxPassBytes)
  11611. {
  11612. if (++m_IgnoredAllocs < MAX_ALLOCS_TO_IGNORE)
  11613. return CounterStatus::Ignore;
  11614. else
  11615. return CounterStatus::End;
  11616. }
  11617. else
  11618. m_IgnoredAllocs = 0;
  11619. return CounterStatus::Pass;
  11620. }
  11621. bool VmaDefragmentationContext_T::IncrementCounters(VkDeviceSize bytes)
  11622. {
  11623. m_PassStats.bytesMoved += bytes;
  11624. // Early return when max found
  11625. if (++m_PassStats.allocationsMoved >= m_MaxPassAllocations || m_PassStats.bytesMoved >= m_MaxPassBytes)
  11626. {
  11627. VMA_ASSERT((m_PassStats.allocationsMoved == m_MaxPassAllocations ||
  11628. m_PassStats.bytesMoved == m_MaxPassBytes) && "Exceeded maximal pass threshold!");
  11629. return true;
  11630. }
  11631. return false;
  11632. }
  11633. bool VmaDefragmentationContext_T::ReallocWithinBlock(VmaBlockVector& vector, VmaDeviceMemoryBlock* block)
  11634. {
  11635. VmaBlockMetadata* metadata = block->m_pMetadata;
  11636. for (VmaAllocHandle handle = metadata->GetAllocationListBegin();
  11637. handle != VK_NULL_HANDLE;
  11638. handle = metadata->GetNextAllocation(handle))
  11639. {
  11640. MoveAllocationData moveData = GetMoveData(handle, metadata);
  11641. // Ignore newly created allocations by defragmentation algorithm
  11642. if (moveData.move.srcAllocation->GetUserData() == this)
  11643. continue;
  11644. switch (CheckCounters(moveData.move.srcAllocation->GetSize()))
  11645. {
  11646. case CounterStatus::Ignore:
  11647. continue;
  11648. case CounterStatus::End:
  11649. return true;
  11650. case CounterStatus::Pass:
  11651. break;
  11652. default:
  11653. VMA_ASSERT(0);
  11654. }
  11655. VkDeviceSize offset = moveData.move.srcAllocation->GetOffset();
  11656. if (offset != 0 && metadata->GetSumFreeSize() >= moveData.size)
  11657. {
  11658. VmaAllocationRequest request = {};
  11659. if (metadata->CreateAllocationRequest(
  11660. moveData.size,
  11661. moveData.alignment,
  11662. false,
  11663. moveData.type,
  11664. VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT,
  11665. &request))
  11666. {
  11667. if (metadata->GetAllocationOffset(request.allocHandle) < offset)
  11668. {
  11669. if (vector.CommitAllocationRequest(
  11670. request,
  11671. block,
  11672. moveData.alignment,
  11673. moveData.flags,
  11674. this,
  11675. moveData.type,
  11676. &moveData.move.dstTmpAllocation) == VK_SUCCESS)
  11677. {
  11678. m_Moves.push_back(moveData.move);
  11679. if (IncrementCounters(moveData.size))
  11680. return true;
  11681. }
  11682. }
  11683. }
  11684. }
  11685. }
  11686. return false;
  11687. }
  11688. bool VmaDefragmentationContext_T::AllocInOtherBlock(size_t start, size_t end, MoveAllocationData& data, VmaBlockVector& vector)
  11689. {
  11690. for (; start < end; ++start)
  11691. {
  11692. VmaDeviceMemoryBlock* dstBlock = vector.GetBlock(start);
  11693. if (dstBlock->m_pMetadata->GetSumFreeSize() >= data.size)
  11694. {
  11695. if (vector.AllocateFromBlock(dstBlock,
  11696. data.size,
  11697. data.alignment,
  11698. data.flags,
  11699. this,
  11700. data.type,
  11701. 0,
  11702. &data.move.dstTmpAllocation) == VK_SUCCESS)
  11703. {
  11704. m_Moves.push_back(data.move);
  11705. if (IncrementCounters(data.size))
  11706. return true;
  11707. break;
  11708. }
  11709. }
  11710. }
  11711. return false;
  11712. }
  11713. bool VmaDefragmentationContext_T::ComputeDefragmentation_Fast(VmaBlockVector& vector)
  11714. {
  11715. // Move only between blocks
  11716. // Go through allocations in last blocks and try to fit them inside first ones
  11717. for (size_t i = vector.GetBlockCount() - 1; i > m_ImmovableBlockCount; --i)
  11718. {
  11719. VmaBlockMetadata* metadata = vector.GetBlock(i)->m_pMetadata;
  11720. for (VmaAllocHandle handle = metadata->GetAllocationListBegin();
  11721. handle != VK_NULL_HANDLE;
  11722. handle = metadata->GetNextAllocation(handle))
  11723. {
  11724. MoveAllocationData moveData = GetMoveData(handle, metadata);
  11725. // Ignore newly created allocations by defragmentation algorithm
  11726. if (moveData.move.srcAllocation->GetUserData() == this)
  11727. continue;
  11728. switch (CheckCounters(moveData.move.srcAllocation->GetSize()))
  11729. {
  11730. case CounterStatus::Ignore:
  11731. continue;
  11732. case CounterStatus::End:
  11733. return true;
  11734. case CounterStatus::Pass:
  11735. break;
  11736. default:
  11737. VMA_ASSERT(0);
  11738. }
  11739. // Check all previous blocks for free space
  11740. if (AllocInOtherBlock(0, i, moveData, vector))
  11741. return true;
  11742. }
  11743. }
  11744. return false;
  11745. }
  11746. bool VmaDefragmentationContext_T::ComputeDefragmentation_Balanced(VmaBlockVector& vector, size_t index, bool update)
  11747. {
  11748. // Go over every allocation and try to fit it in previous blocks at lowest offsets,
  11749. // if not possible: realloc within single block to minimize offset (exclude offset == 0),
  11750. // but only if there are noticeable gaps between them (some heuristic, ex. average size of allocation in block)
  11751. VMA_ASSERT(m_AlgorithmState != VMA_NULL);
  11752. StateBalanced& vectorState = reinterpret_cast<StateBalanced*>(m_AlgorithmState)[index];
  11753. if (update && vectorState.avgAllocSize == UINT64_MAX)
  11754. UpdateVectorStatistics(vector, vectorState);
  11755. const size_t startMoveCount = m_Moves.size();
  11756. VkDeviceSize minimalFreeRegion = vectorState.avgFreeSize / 2;
  11757. for (size_t i = vector.GetBlockCount() - 1; i > m_ImmovableBlockCount; --i)
  11758. {
  11759. VmaDeviceMemoryBlock* block = vector.GetBlock(i);
  11760. VmaBlockMetadata* metadata = block->m_pMetadata;
  11761. VkDeviceSize prevFreeRegionSize = 0;
  11762. for (VmaAllocHandle handle = metadata->GetAllocationListBegin();
  11763. handle != VK_NULL_HANDLE;
  11764. handle = metadata->GetNextAllocation(handle))
  11765. {
  11766. MoveAllocationData moveData = GetMoveData(handle, metadata);
  11767. // Ignore newly created allocations by defragmentation algorithm
  11768. if (moveData.move.srcAllocation->GetUserData() == this)
  11769. continue;
  11770. switch (CheckCounters(moveData.move.srcAllocation->GetSize()))
  11771. {
  11772. case CounterStatus::Ignore:
  11773. continue;
  11774. case CounterStatus::End:
  11775. return true;
  11776. case CounterStatus::Pass:
  11777. break;
  11778. default:
  11779. VMA_ASSERT(0);
  11780. }
  11781. // Check all previous blocks for free space
  11782. const size_t prevMoveCount = m_Moves.size();
  11783. if (AllocInOtherBlock(0, i, moveData, vector))
  11784. return true;
  11785. VkDeviceSize nextFreeRegionSize = metadata->GetNextFreeRegionSize(handle);
  11786. // If no room found then realloc within block for lower offset
  11787. VkDeviceSize offset = moveData.move.srcAllocation->GetOffset();
  11788. if (prevMoveCount == m_Moves.size() && offset != 0 && metadata->GetSumFreeSize() >= moveData.size)
  11789. {
  11790. // Check if realloc will make sense
  11791. if (prevFreeRegionSize >= minimalFreeRegion ||
  11792. nextFreeRegionSize >= minimalFreeRegion ||
  11793. moveData.size <= vectorState.avgFreeSize ||
  11794. moveData.size <= vectorState.avgAllocSize)
  11795. {
  11796. VmaAllocationRequest request = {};
  11797. if (metadata->CreateAllocationRequest(
  11798. moveData.size,
  11799. moveData.alignment,
  11800. false,
  11801. moveData.type,
  11802. VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT,
  11803. &request))
  11804. {
  11805. if (metadata->GetAllocationOffset(request.allocHandle) < offset)
  11806. {
  11807. if (vector.CommitAllocationRequest(
  11808. request,
  11809. block,
  11810. moveData.alignment,
  11811. moveData.flags,
  11812. this,
  11813. moveData.type,
  11814. &moveData.move.dstTmpAllocation) == VK_SUCCESS)
  11815. {
  11816. m_Moves.push_back(moveData.move);
  11817. if (IncrementCounters(moveData.size))
  11818. return true;
  11819. }
  11820. }
  11821. }
  11822. }
  11823. }
  11824. prevFreeRegionSize = nextFreeRegionSize;
  11825. }
  11826. }
  11827. // No moves performed, update statistics to current vector state
  11828. if (startMoveCount == m_Moves.size() && !update)
  11829. {
  11830. vectorState.avgAllocSize = UINT64_MAX;
  11831. return ComputeDefragmentation_Balanced(vector, index, false);
  11832. }
  11833. return false;
  11834. }
  11835. bool VmaDefragmentationContext_T::ComputeDefragmentation_Full(VmaBlockVector& vector)
  11836. {
  11837. // Go over every allocation and try to fit it in previous blocks at lowest offsets,
  11838. // if not possible: realloc within single block to minimize offset (exclude offset == 0)
  11839. for (size_t i = vector.GetBlockCount() - 1; i > m_ImmovableBlockCount; --i)
  11840. {
  11841. VmaDeviceMemoryBlock* block = vector.GetBlock(i);
  11842. VmaBlockMetadata* metadata = block->m_pMetadata;
  11843. for (VmaAllocHandle handle = metadata->GetAllocationListBegin();
  11844. handle != VK_NULL_HANDLE;
  11845. handle = metadata->GetNextAllocation(handle))
  11846. {
  11847. MoveAllocationData moveData = GetMoveData(handle, metadata);
  11848. // Ignore newly created allocations by defragmentation algorithm
  11849. if (moveData.move.srcAllocation->GetUserData() == this)
  11850. continue;
  11851. switch (CheckCounters(moveData.move.srcAllocation->GetSize()))
  11852. {
  11853. case CounterStatus::Ignore:
  11854. continue;
  11855. case CounterStatus::End:
  11856. return true;
  11857. case CounterStatus::Pass:
  11858. break;
  11859. default:
  11860. VMA_ASSERT(0);
  11861. }
  11862. // Check all previous blocks for free space
  11863. const size_t prevMoveCount = m_Moves.size();
  11864. if (AllocInOtherBlock(0, i, moveData, vector))
  11865. return true;
  11866. // If no room found then realloc within block for lower offset
  11867. VkDeviceSize offset = moveData.move.srcAllocation->GetOffset();
  11868. if (prevMoveCount == m_Moves.size() && offset != 0 && metadata->GetSumFreeSize() >= moveData.size)
  11869. {
  11870. VmaAllocationRequest request = {};
  11871. if (metadata->CreateAllocationRequest(
  11872. moveData.size,
  11873. moveData.alignment,
  11874. false,
  11875. moveData.type,
  11876. VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT,
  11877. &request))
  11878. {
  11879. if (metadata->GetAllocationOffset(request.allocHandle) < offset)
  11880. {
  11881. if (vector.CommitAllocationRequest(
  11882. request,
  11883. block,
  11884. moveData.alignment,
  11885. moveData.flags,
  11886. this,
  11887. moveData.type,
  11888. &moveData.move.dstTmpAllocation) == VK_SUCCESS)
  11889. {
  11890. m_Moves.push_back(moveData.move);
  11891. if (IncrementCounters(moveData.size))
  11892. return true;
  11893. }
  11894. }
  11895. }
  11896. }
  11897. }
  11898. }
  11899. return false;
  11900. }
  11901. bool VmaDefragmentationContext_T::ComputeDefragmentation_Extensive(VmaBlockVector& vector, size_t index)
  11902. {
  11903. // First free single block, then populate it to the brim, then free another block, and so on
  11904. // Fallback to previous algorithm since without granularity conflicts it can achieve max packing
  11905. if (vector.m_BufferImageGranularity == 1)
  11906. return ComputeDefragmentation_Full(vector);
  11907. VMA_ASSERT(m_AlgorithmState != VMA_NULL);
  11908. StateExtensive& vectorState = reinterpret_cast<StateExtensive*>(m_AlgorithmState)[index];
  11909. bool texturePresent = false, bufferPresent = false, otherPresent = false;
  11910. switch (vectorState.operation)
  11911. {
  11912. case StateExtensive::Operation::Done: // Vector defragmented
  11913. return false;
  11914. case StateExtensive::Operation::FindFreeBlockBuffer:
  11915. case StateExtensive::Operation::FindFreeBlockTexture:
  11916. case StateExtensive::Operation::FindFreeBlockAll:
  11917. {
  11918. // No more blocks to free, just perform fast realloc and move to cleanup
  11919. if (vectorState.firstFreeBlock == 0)
  11920. {
  11921. vectorState.operation = StateExtensive::Operation::Cleanup;
  11922. return ComputeDefragmentation_Fast(vector);
  11923. }
  11924. // No free blocks, have to clear last one
  11925. size_t last = (vectorState.firstFreeBlock == SIZE_MAX ? vector.GetBlockCount() : vectorState.firstFreeBlock) - 1;
  11926. VmaBlockMetadata* freeMetadata = vector.GetBlock(last)->m_pMetadata;
  11927. const size_t prevMoveCount = m_Moves.size();
  11928. for (VmaAllocHandle handle = freeMetadata->GetAllocationListBegin();
  11929. handle != VK_NULL_HANDLE;
  11930. handle = freeMetadata->GetNextAllocation(handle))
  11931. {
  11932. MoveAllocationData moveData = GetMoveData(handle, freeMetadata);
  11933. switch (CheckCounters(moveData.move.srcAllocation->GetSize()))
  11934. {
  11935. case CounterStatus::Ignore:
  11936. continue;
  11937. case CounterStatus::End:
  11938. return true;
  11939. case CounterStatus::Pass:
  11940. break;
  11941. default:
  11942. VMA_ASSERT(0);
  11943. }
  11944. // Check all previous blocks for free space
  11945. if (AllocInOtherBlock(0, last, moveData, vector))
  11946. {
  11947. // Full clear performed already
  11948. if (prevMoveCount != m_Moves.size() && freeMetadata->GetNextAllocation(handle) == VK_NULL_HANDLE)
  11949. vectorState.firstFreeBlock = last;
  11950. return true;
  11951. }
  11952. }
  11953. if (prevMoveCount == m_Moves.size())
  11954. {
  11955. // Cannot perform full clear, have to move data in other blocks around
  11956. if (last != 0)
  11957. {
  11958. for (size_t i = last - 1; i; --i)
  11959. {
  11960. if (ReallocWithinBlock(vector, vector.GetBlock(i)))
  11961. return true;
  11962. }
  11963. }
  11964. if (prevMoveCount == m_Moves.size())
  11965. {
  11966. // No possible reallocs within blocks, try to move them around fast
  11967. return ComputeDefragmentation_Fast(vector);
  11968. }
  11969. }
  11970. else
  11971. {
  11972. switch (vectorState.operation)
  11973. {
  11974. case StateExtensive::Operation::FindFreeBlockBuffer:
  11975. vectorState.operation = StateExtensive::Operation::MoveBuffers;
  11976. break;
  11977. case StateExtensive::Operation::FindFreeBlockTexture:
  11978. vectorState.operation = StateExtensive::Operation::MoveTextures;
  11979. break;
  11980. case StateExtensive::Operation::FindFreeBlockAll:
  11981. vectorState.operation = StateExtensive::Operation::MoveAll;
  11982. break;
  11983. default:
  11984. VMA_ASSERT(0);
  11985. vectorState.operation = StateExtensive::Operation::MoveTextures;
  11986. }
  11987. vectorState.firstFreeBlock = last;
  11988. // Nothing done, block found without reallocations, can perform another reallocs in same pass
  11989. return ComputeDefragmentation_Extensive(vector, index);
  11990. }
  11991. break;
  11992. }
  11993. case StateExtensive::Operation::MoveTextures:
  11994. {
  11995. if (MoveDataToFreeBlocks(VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL, vector,
  11996. vectorState.firstFreeBlock, texturePresent, bufferPresent, otherPresent))
  11997. {
  11998. if (texturePresent)
  11999. {
  12000. vectorState.operation = StateExtensive::Operation::FindFreeBlockTexture;
  12001. return ComputeDefragmentation_Extensive(vector, index);
  12002. }
  12003. if (!bufferPresent && !otherPresent)
  12004. {
  12005. vectorState.operation = StateExtensive::Operation::Cleanup;
  12006. break;
  12007. }
  12008. // No more textures to move, check buffers
  12009. vectorState.operation = StateExtensive::Operation::MoveBuffers;
  12010. bufferPresent = false;
  12011. otherPresent = false;
  12012. }
  12013. else
  12014. break;
  12015. VMA_FALLTHROUGH; // Fallthrough
  12016. }
  12017. case StateExtensive::Operation::MoveBuffers:
  12018. {
  12019. if (MoveDataToFreeBlocks(VMA_SUBALLOCATION_TYPE_BUFFER, vector,
  12020. vectorState.firstFreeBlock, texturePresent, bufferPresent, otherPresent))
  12021. {
  12022. if (bufferPresent)
  12023. {
  12024. vectorState.operation = StateExtensive::Operation::FindFreeBlockBuffer;
  12025. return ComputeDefragmentation_Extensive(vector, index);
  12026. }
  12027. if (!otherPresent)
  12028. {
  12029. vectorState.operation = StateExtensive::Operation::Cleanup;
  12030. break;
  12031. }
  12032. // No more buffers to move, check all others
  12033. vectorState.operation = StateExtensive::Operation::MoveAll;
  12034. otherPresent = false;
  12035. }
  12036. else
  12037. break;
  12038. VMA_FALLTHROUGH; // Fallthrough
  12039. }
  12040. case StateExtensive::Operation::MoveAll:
  12041. {
  12042. if (MoveDataToFreeBlocks(VMA_SUBALLOCATION_TYPE_FREE, vector,
  12043. vectorState.firstFreeBlock, texturePresent, bufferPresent, otherPresent))
  12044. {
  12045. if (otherPresent)
  12046. {
  12047. vectorState.operation = StateExtensive::Operation::FindFreeBlockBuffer;
  12048. return ComputeDefragmentation_Extensive(vector, index);
  12049. }
  12050. // Everything moved
  12051. vectorState.operation = StateExtensive::Operation::Cleanup;
  12052. }
  12053. break;
  12054. }
  12055. case StateExtensive::Operation::Cleanup:
  12056. // Cleanup is handled below so that other operations may reuse the cleanup code. This case is here to prevent the unhandled enum value warning (C4062).
  12057. break;
  12058. }
  12059. if (vectorState.operation == StateExtensive::Operation::Cleanup)
  12060. {
  12061. // All other work done, pack data in blocks even tighter if possible
  12062. const size_t prevMoveCount = m_Moves.size();
  12063. for (size_t i = 0; i < vector.GetBlockCount(); ++i)
  12064. {
  12065. if (ReallocWithinBlock(vector, vector.GetBlock(i)))
  12066. return true;
  12067. }
  12068. if (prevMoveCount == m_Moves.size())
  12069. vectorState.operation = StateExtensive::Operation::Done;
  12070. }
  12071. return false;
  12072. }
  12073. void VmaDefragmentationContext_T::UpdateVectorStatistics(VmaBlockVector& vector, StateBalanced& state)
  12074. {
  12075. size_t allocCount = 0;
  12076. size_t freeCount = 0;
  12077. state.avgFreeSize = 0;
  12078. state.avgAllocSize = 0;
  12079. for (size_t i = 0; i < vector.GetBlockCount(); ++i)
  12080. {
  12081. VmaBlockMetadata* metadata = vector.GetBlock(i)->m_pMetadata;
  12082. allocCount += metadata->GetAllocationCount();
  12083. freeCount += metadata->GetFreeRegionsCount();
  12084. state.avgFreeSize += metadata->GetSumFreeSize();
  12085. state.avgAllocSize += metadata->GetSize();
  12086. }
  12087. state.avgAllocSize = (state.avgAllocSize - state.avgFreeSize) / allocCount;
  12088. state.avgFreeSize /= freeCount;
  12089. }
  12090. bool VmaDefragmentationContext_T::MoveDataToFreeBlocks(VmaSuballocationType currentType,
  12091. VmaBlockVector& vector, size_t firstFreeBlock,
  12092. bool& texturePresent, bool& bufferPresent, bool& otherPresent)
  12093. {
  12094. const size_t prevMoveCount = m_Moves.size();
  12095. for (size_t i = firstFreeBlock ; i;)
  12096. {
  12097. VmaDeviceMemoryBlock* block = vector.GetBlock(--i);
  12098. VmaBlockMetadata* metadata = block->m_pMetadata;
  12099. for (VmaAllocHandle handle = metadata->GetAllocationListBegin();
  12100. handle != VK_NULL_HANDLE;
  12101. handle = metadata->GetNextAllocation(handle))
  12102. {
  12103. MoveAllocationData moveData = GetMoveData(handle, metadata);
  12104. // Ignore newly created allocations by defragmentation algorithm
  12105. if (moveData.move.srcAllocation->GetUserData() == this)
  12106. continue;
  12107. switch (CheckCounters(moveData.move.srcAllocation->GetSize()))
  12108. {
  12109. case CounterStatus::Ignore:
  12110. continue;
  12111. case CounterStatus::End:
  12112. return true;
  12113. case CounterStatus::Pass:
  12114. break;
  12115. default:
  12116. VMA_ASSERT(0);
  12117. }
  12118. // Move only single type of resources at once
  12119. if (!VmaIsBufferImageGranularityConflict(moveData.type, currentType))
  12120. {
  12121. // Try to fit allocation into free blocks
  12122. if (AllocInOtherBlock(firstFreeBlock, vector.GetBlockCount(), moveData, vector))
  12123. return false;
  12124. }
  12125. if (!VmaIsBufferImageGranularityConflict(moveData.type, VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL))
  12126. texturePresent = true;
  12127. else if (!VmaIsBufferImageGranularityConflict(moveData.type, VMA_SUBALLOCATION_TYPE_BUFFER))
  12128. bufferPresent = true;
  12129. else
  12130. otherPresent = true;
  12131. }
  12132. }
  12133. return prevMoveCount == m_Moves.size();
  12134. }
  12135. #endif // _VMA_DEFRAGMENTATION_CONTEXT_FUNCTIONS
  12136. #ifndef _VMA_POOL_T_FUNCTIONS
  12137. VmaPool_T::VmaPool_T(
  12138. VmaAllocator hAllocator,
  12139. const VmaPoolCreateInfo& createInfo,
  12140. VkDeviceSize preferredBlockSize)
  12141. : m_BlockVector(
  12142. hAllocator,
  12143. this, // hParentPool
  12144. createInfo.memoryTypeIndex,
  12145. createInfo.blockSize != 0 ? createInfo.blockSize : preferredBlockSize,
  12146. createInfo.minBlockCount,
  12147. createInfo.maxBlockCount,
  12148. (createInfo.flags& VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT) != 0 ? 1 : hAllocator->GetBufferImageGranularity(),
  12149. createInfo.blockSize != 0, // explicitBlockSize
  12150. createInfo.flags & VMA_POOL_CREATE_ALGORITHM_MASK, // algorithm
  12151. createInfo.priority,
  12152. VMA_MAX(hAllocator->GetMemoryTypeMinAlignment(createInfo.memoryTypeIndex), createInfo.minAllocationAlignment),
  12153. createInfo.pMemoryAllocateNext),
  12154. m_Id(0),
  12155. m_Name(VMA_NULL) {}
  12156. VmaPool_T::~VmaPool_T()
  12157. {
  12158. VMA_ASSERT(m_PrevPool == VMA_NULL && m_NextPool == VMA_NULL);
  12159. }
  12160. void VmaPool_T::SetName(const char* pName)
  12161. {
  12162. const VkAllocationCallbacks* allocs = m_BlockVector.GetAllocator()->GetAllocationCallbacks();
  12163. VmaFreeString(allocs, m_Name);
  12164. if (pName != VMA_NULL)
  12165. {
  12166. m_Name = VmaCreateStringCopy(allocs, pName);
  12167. }
  12168. else
  12169. {
  12170. m_Name = VMA_NULL;
  12171. }
  12172. }
  12173. #endif // _VMA_POOL_T_FUNCTIONS
  12174. #ifndef _VMA_ALLOCATOR_T_FUNCTIONS
  12175. VmaAllocator_T::VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo) :
  12176. m_UseMutex((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT) == 0),
  12177. m_VulkanApiVersion(pCreateInfo->vulkanApiVersion != 0 ? pCreateInfo->vulkanApiVersion : VK_API_VERSION_1_0),
  12178. m_UseKhrDedicatedAllocation((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0),
  12179. m_UseKhrBindMemory2((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT) != 0),
  12180. m_UseExtMemoryBudget((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT) != 0),
  12181. m_UseAmdDeviceCoherentMemory((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT) != 0),
  12182. m_UseKhrBufferDeviceAddress((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT) != 0),
  12183. m_UseExtMemoryPriority((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT) != 0),
  12184. m_hDevice(pCreateInfo->device),
  12185. m_hInstance(pCreateInfo->instance),
  12186. m_AllocationCallbacksSpecified(pCreateInfo->pAllocationCallbacks != VMA_NULL),
  12187. m_AllocationCallbacks(pCreateInfo->pAllocationCallbacks ?
  12188. *pCreateInfo->pAllocationCallbacks : VmaEmptyAllocationCallbacks),
  12189. m_AllocationObjectAllocator(&m_AllocationCallbacks),
  12190. m_HeapSizeLimitMask(0),
  12191. m_DeviceMemoryCount(0),
  12192. m_PreferredLargeHeapBlockSize(0),
  12193. m_PhysicalDevice(pCreateInfo->physicalDevice),
  12194. m_GpuDefragmentationMemoryTypeBits(UINT32_MAX),
  12195. m_NextPoolId(0),
  12196. m_GlobalMemoryTypeBits(UINT32_MAX)
  12197. {
  12198. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12199. {
  12200. m_UseKhrDedicatedAllocation = false;
  12201. m_UseKhrBindMemory2 = false;
  12202. }
  12203. if(VMA_DEBUG_DETECT_CORRUPTION)
  12204. {
  12205. // Needs to be multiply of uint32_t size because we are going to write VMA_CORRUPTION_DETECTION_MAGIC_VALUE to it.
  12206. VMA_ASSERT(VMA_DEBUG_MARGIN % sizeof(uint32_t) == 0);
  12207. }
  12208. VMA_ASSERT(pCreateInfo->physicalDevice && pCreateInfo->device && pCreateInfo->instance);
  12209. if(m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0))
  12210. {
  12211. #if !(VMA_DEDICATED_ALLOCATION)
  12212. if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0)
  12213. {
  12214. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT set but required extensions are disabled by preprocessor macros.");
  12215. }
  12216. #endif
  12217. #if !(VMA_BIND_MEMORY2)
  12218. if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT) != 0)
  12219. {
  12220. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT set but required extension is disabled by preprocessor macros.");
  12221. }
  12222. #endif
  12223. }
  12224. #if !(VMA_MEMORY_BUDGET)
  12225. if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT) != 0)
  12226. {
  12227. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT set but required extension is disabled by preprocessor macros.");
  12228. }
  12229. #endif
  12230. #if !(VMA_BUFFER_DEVICE_ADDRESS)
  12231. if(m_UseKhrBufferDeviceAddress)
  12232. {
  12233. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT is set but required extension or Vulkan 1.2 is not available in your Vulkan header or its support in VMA has been disabled by a preprocessor macro.");
  12234. }
  12235. #endif
  12236. #if VMA_VULKAN_VERSION < 1003000
  12237. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 3, 0))
  12238. {
  12239. VMA_ASSERT(0 && "vulkanApiVersion >= VK_API_VERSION_1_3 but required Vulkan version is disabled by preprocessor macros.");
  12240. }
  12241. #endif
  12242. #if VMA_VULKAN_VERSION < 1002000
  12243. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 2, 0))
  12244. {
  12245. VMA_ASSERT(0 && "vulkanApiVersion >= VK_API_VERSION_1_2 but required Vulkan version is disabled by preprocessor macros.");
  12246. }
  12247. #endif
  12248. #if VMA_VULKAN_VERSION < 1001000
  12249. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12250. {
  12251. VMA_ASSERT(0 && "vulkanApiVersion >= VK_API_VERSION_1_1 but required Vulkan version is disabled by preprocessor macros.");
  12252. }
  12253. #endif
  12254. #if !(VMA_MEMORY_PRIORITY)
  12255. if(m_UseExtMemoryPriority)
  12256. {
  12257. VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT is set but required extension is not available in your Vulkan header or its support in VMA has been disabled by a preprocessor macro.");
  12258. }
  12259. #endif
  12260. memset(&m_DeviceMemoryCallbacks, 0 ,sizeof(m_DeviceMemoryCallbacks));
  12261. memset(&m_PhysicalDeviceProperties, 0, sizeof(m_PhysicalDeviceProperties));
  12262. memset(&m_MemProps, 0, sizeof(m_MemProps));
  12263. memset(&m_pBlockVectors, 0, sizeof(m_pBlockVectors));
  12264. memset(&m_VulkanFunctions, 0, sizeof(m_VulkanFunctions));
  12265. #if VMA_EXTERNAL_MEMORY
  12266. memset(&m_TypeExternalMemoryHandleTypes, 0, sizeof(m_TypeExternalMemoryHandleTypes));
  12267. #endif // #if VMA_EXTERNAL_MEMORY
  12268. if(pCreateInfo->pDeviceMemoryCallbacks != VMA_NULL)
  12269. {
  12270. m_DeviceMemoryCallbacks.pUserData = pCreateInfo->pDeviceMemoryCallbacks->pUserData;
  12271. m_DeviceMemoryCallbacks.pfnAllocate = pCreateInfo->pDeviceMemoryCallbacks->pfnAllocate;
  12272. m_DeviceMemoryCallbacks.pfnFree = pCreateInfo->pDeviceMemoryCallbacks->pfnFree;
  12273. }
  12274. ImportVulkanFunctions(pCreateInfo->pVulkanFunctions);
  12275. (*m_VulkanFunctions.vkGetPhysicalDeviceProperties)(m_PhysicalDevice, &m_PhysicalDeviceProperties);
  12276. (*m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties)(m_PhysicalDevice, &m_MemProps);
  12277. VMA_ASSERT(VmaIsPow2(VMA_MIN_ALIGNMENT));
  12278. VMA_ASSERT(VmaIsPow2(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY));
  12279. VMA_ASSERT(VmaIsPow2(m_PhysicalDeviceProperties.limits.bufferImageGranularity));
  12280. VMA_ASSERT(VmaIsPow2(m_PhysicalDeviceProperties.limits.nonCoherentAtomSize));
  12281. m_PreferredLargeHeapBlockSize = (pCreateInfo->preferredLargeHeapBlockSize != 0) ?
  12282. pCreateInfo->preferredLargeHeapBlockSize : static_cast<VkDeviceSize>(VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE);
  12283. m_GlobalMemoryTypeBits = CalculateGlobalMemoryTypeBits();
  12284. #if VMA_EXTERNAL_MEMORY
  12285. if(pCreateInfo->pTypeExternalMemoryHandleTypes != VMA_NULL)
  12286. {
  12287. memcpy(m_TypeExternalMemoryHandleTypes, pCreateInfo->pTypeExternalMemoryHandleTypes,
  12288. sizeof(VkExternalMemoryHandleTypeFlagsKHR) * GetMemoryTypeCount());
  12289. }
  12290. #endif // #if VMA_EXTERNAL_MEMORY
  12291. if(pCreateInfo->pHeapSizeLimit != VMA_NULL)
  12292. {
  12293. for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex)
  12294. {
  12295. const VkDeviceSize limit = pCreateInfo->pHeapSizeLimit[heapIndex];
  12296. if(limit != VK_WHOLE_SIZE)
  12297. {
  12298. m_HeapSizeLimitMask |= 1u << heapIndex;
  12299. if(limit < m_MemProps.memoryHeaps[heapIndex].size)
  12300. {
  12301. m_MemProps.memoryHeaps[heapIndex].size = limit;
  12302. }
  12303. }
  12304. }
  12305. }
  12306. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  12307. {
  12308. // Create only supported types
  12309. if((m_GlobalMemoryTypeBits & (1u << memTypeIndex)) != 0)
  12310. {
  12311. const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(memTypeIndex);
  12312. m_pBlockVectors[memTypeIndex] = vma_new(this, VmaBlockVector)(
  12313. this,
  12314. VK_NULL_HANDLE, // hParentPool
  12315. memTypeIndex,
  12316. preferredBlockSize,
  12317. 0,
  12318. SIZE_MAX,
  12319. GetBufferImageGranularity(),
  12320. false, // explicitBlockSize
  12321. 0, // algorithm
  12322. 0.5f, // priority (0.5 is the default per Vulkan spec)
  12323. GetMemoryTypeMinAlignment(memTypeIndex), // minAllocationAlignment
  12324. VMA_NULL); // // pMemoryAllocateNext
  12325. // No need to call m_pBlockVectors[memTypeIndex][blockVectorTypeIndex]->CreateMinBlocks here,
  12326. // becase minBlockCount is 0.
  12327. }
  12328. }
  12329. }
  12330. VkResult VmaAllocator_T::Init(const VmaAllocatorCreateInfo* pCreateInfo)
  12331. {
  12332. VkResult res = VK_SUCCESS;
  12333. #if VMA_MEMORY_BUDGET
  12334. if(m_UseExtMemoryBudget)
  12335. {
  12336. UpdateVulkanBudget();
  12337. }
  12338. #endif // #if VMA_MEMORY_BUDGET
  12339. return res;
  12340. }
  12341. VmaAllocator_T::~VmaAllocator_T()
  12342. {
  12343. VMA_ASSERT(m_Pools.IsEmpty());
  12344. for(size_t memTypeIndex = GetMemoryTypeCount(); memTypeIndex--; )
  12345. {
  12346. vma_delete(this, m_pBlockVectors[memTypeIndex]);
  12347. }
  12348. }
  12349. void VmaAllocator_T::ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions)
  12350. {
  12351. #if VMA_STATIC_VULKAN_FUNCTIONS == 1
  12352. ImportVulkanFunctions_Static();
  12353. #endif
  12354. if(pVulkanFunctions != VMA_NULL)
  12355. {
  12356. ImportVulkanFunctions_Custom(pVulkanFunctions);
  12357. }
  12358. #if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1
  12359. ImportVulkanFunctions_Dynamic();
  12360. #endif
  12361. ValidateVulkanFunctions();
  12362. }
  12363. #if VMA_STATIC_VULKAN_FUNCTIONS == 1
  12364. void VmaAllocator_T::ImportVulkanFunctions_Static()
  12365. {
  12366. // Vulkan 1.0
  12367. m_VulkanFunctions.vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)vkGetInstanceProcAddr;
  12368. m_VulkanFunctions.vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr)vkGetDeviceProcAddr;
  12369. m_VulkanFunctions.vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)vkGetPhysicalDeviceProperties;
  12370. m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)vkGetPhysicalDeviceMemoryProperties;
  12371. m_VulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkAllocateMemory;
  12372. m_VulkanFunctions.vkFreeMemory = (PFN_vkFreeMemory)vkFreeMemory;
  12373. m_VulkanFunctions.vkMapMemory = (PFN_vkMapMemory)vkMapMemory;
  12374. m_VulkanFunctions.vkUnmapMemory = (PFN_vkUnmapMemory)vkUnmapMemory;
  12375. m_VulkanFunctions.vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)vkFlushMappedMemoryRanges;
  12376. m_VulkanFunctions.vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)vkInvalidateMappedMemoryRanges;
  12377. m_VulkanFunctions.vkBindBufferMemory = (PFN_vkBindBufferMemory)vkBindBufferMemory;
  12378. m_VulkanFunctions.vkBindImageMemory = (PFN_vkBindImageMemory)vkBindImageMemory;
  12379. m_VulkanFunctions.vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)vkGetBufferMemoryRequirements;
  12380. m_VulkanFunctions.vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)vkGetImageMemoryRequirements;
  12381. m_VulkanFunctions.vkCreateBuffer = (PFN_vkCreateBuffer)vkCreateBuffer;
  12382. m_VulkanFunctions.vkDestroyBuffer = (PFN_vkDestroyBuffer)vkDestroyBuffer;
  12383. m_VulkanFunctions.vkCreateImage = (PFN_vkCreateImage)vkCreateImage;
  12384. m_VulkanFunctions.vkDestroyImage = (PFN_vkDestroyImage)vkDestroyImage;
  12385. m_VulkanFunctions.vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)vkCmdCopyBuffer;
  12386. // Vulkan 1.1
  12387. #if VMA_VULKAN_VERSION >= 1001000
  12388. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12389. {
  12390. m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR = (PFN_vkGetBufferMemoryRequirements2)vkGetBufferMemoryRequirements2;
  12391. m_VulkanFunctions.vkGetImageMemoryRequirements2KHR = (PFN_vkGetImageMemoryRequirements2)vkGetImageMemoryRequirements2;
  12392. m_VulkanFunctions.vkBindBufferMemory2KHR = (PFN_vkBindBufferMemory2)vkBindBufferMemory2;
  12393. m_VulkanFunctions.vkBindImageMemory2KHR = (PFN_vkBindImageMemory2)vkBindImageMemory2;
  12394. }
  12395. #endif
  12396. #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000
  12397. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12398. {
  12399. m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR = (PFN_vkGetPhysicalDeviceMemoryProperties2)vkGetPhysicalDeviceMemoryProperties2;
  12400. }
  12401. #endif
  12402. #if VMA_VULKAN_VERSION >= 1003000
  12403. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 3, 0))
  12404. {
  12405. m_VulkanFunctions.vkGetDeviceBufferMemoryRequirements = (PFN_vkGetDeviceBufferMemoryRequirements)vkGetDeviceBufferMemoryRequirements;
  12406. m_VulkanFunctions.vkGetDeviceImageMemoryRequirements = (PFN_vkGetDeviceImageMemoryRequirements)vkGetDeviceImageMemoryRequirements;
  12407. }
  12408. #endif
  12409. }
  12410. #endif // VMA_STATIC_VULKAN_FUNCTIONS == 1
  12411. void VmaAllocator_T::ImportVulkanFunctions_Custom(const VmaVulkanFunctions* pVulkanFunctions)
  12412. {
  12413. VMA_ASSERT(pVulkanFunctions != VMA_NULL);
  12414. #define VMA_COPY_IF_NOT_NULL(funcName) \
  12415. if(pVulkanFunctions->funcName != VMA_NULL) m_VulkanFunctions.funcName = pVulkanFunctions->funcName;
  12416. VMA_COPY_IF_NOT_NULL(vkGetInstanceProcAddr);
  12417. VMA_COPY_IF_NOT_NULL(vkGetDeviceProcAddr);
  12418. VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceProperties);
  12419. VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties);
  12420. VMA_COPY_IF_NOT_NULL(vkAllocateMemory);
  12421. VMA_COPY_IF_NOT_NULL(vkFreeMemory);
  12422. VMA_COPY_IF_NOT_NULL(vkMapMemory);
  12423. VMA_COPY_IF_NOT_NULL(vkUnmapMemory);
  12424. VMA_COPY_IF_NOT_NULL(vkFlushMappedMemoryRanges);
  12425. VMA_COPY_IF_NOT_NULL(vkInvalidateMappedMemoryRanges);
  12426. VMA_COPY_IF_NOT_NULL(vkBindBufferMemory);
  12427. VMA_COPY_IF_NOT_NULL(vkBindImageMemory);
  12428. VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements);
  12429. VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements);
  12430. VMA_COPY_IF_NOT_NULL(vkCreateBuffer);
  12431. VMA_COPY_IF_NOT_NULL(vkDestroyBuffer);
  12432. VMA_COPY_IF_NOT_NULL(vkCreateImage);
  12433. VMA_COPY_IF_NOT_NULL(vkDestroyImage);
  12434. VMA_COPY_IF_NOT_NULL(vkCmdCopyBuffer);
  12435. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12436. VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements2KHR);
  12437. VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements2KHR);
  12438. #endif
  12439. #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000
  12440. VMA_COPY_IF_NOT_NULL(vkBindBufferMemory2KHR);
  12441. VMA_COPY_IF_NOT_NULL(vkBindImageMemory2KHR);
  12442. #endif
  12443. #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000
  12444. VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties2KHR);
  12445. #endif
  12446. #if VMA_VULKAN_VERSION >= 1003000
  12447. VMA_COPY_IF_NOT_NULL(vkGetDeviceBufferMemoryRequirements);
  12448. VMA_COPY_IF_NOT_NULL(vkGetDeviceImageMemoryRequirements);
  12449. #endif
  12450. #undef VMA_COPY_IF_NOT_NULL
  12451. }
  12452. #if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1
  12453. void VmaAllocator_T::ImportVulkanFunctions_Dynamic()
  12454. {
  12455. VMA_ASSERT(m_VulkanFunctions.vkGetInstanceProcAddr && m_VulkanFunctions.vkGetDeviceProcAddr &&
  12456. "To use VMA_DYNAMIC_VULKAN_FUNCTIONS in new versions of VMA you now have to pass "
  12457. "VmaVulkanFunctions::vkGetInstanceProcAddr and vkGetDeviceProcAddr as VmaAllocatorCreateInfo::pVulkanFunctions. "
  12458. "Other members can be null.");
  12459. #define VMA_FETCH_INSTANCE_FUNC(memberName, functionPointerType, functionNameString) \
  12460. if(m_VulkanFunctions.memberName == VMA_NULL) \
  12461. m_VulkanFunctions.memberName = \
  12462. (functionPointerType)m_VulkanFunctions.vkGetInstanceProcAddr(m_hInstance, functionNameString);
  12463. #define VMA_FETCH_DEVICE_FUNC(memberName, functionPointerType, functionNameString) \
  12464. if(m_VulkanFunctions.memberName == VMA_NULL) \
  12465. m_VulkanFunctions.memberName = \
  12466. (functionPointerType)m_VulkanFunctions.vkGetDeviceProcAddr(m_hDevice, functionNameString);
  12467. VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceProperties, PFN_vkGetPhysicalDeviceProperties, "vkGetPhysicalDeviceProperties");
  12468. VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties, PFN_vkGetPhysicalDeviceMemoryProperties, "vkGetPhysicalDeviceMemoryProperties");
  12469. VMA_FETCH_DEVICE_FUNC(vkAllocateMemory, PFN_vkAllocateMemory, "vkAllocateMemory");
  12470. VMA_FETCH_DEVICE_FUNC(vkFreeMemory, PFN_vkFreeMemory, "vkFreeMemory");
  12471. VMA_FETCH_DEVICE_FUNC(vkMapMemory, PFN_vkMapMemory, "vkMapMemory");
  12472. VMA_FETCH_DEVICE_FUNC(vkUnmapMemory, PFN_vkUnmapMemory, "vkUnmapMemory");
  12473. VMA_FETCH_DEVICE_FUNC(vkFlushMappedMemoryRanges, PFN_vkFlushMappedMemoryRanges, "vkFlushMappedMemoryRanges");
  12474. VMA_FETCH_DEVICE_FUNC(vkInvalidateMappedMemoryRanges, PFN_vkInvalidateMappedMemoryRanges, "vkInvalidateMappedMemoryRanges");
  12475. VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory, PFN_vkBindBufferMemory, "vkBindBufferMemory");
  12476. VMA_FETCH_DEVICE_FUNC(vkBindImageMemory, PFN_vkBindImageMemory, "vkBindImageMemory");
  12477. VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements, PFN_vkGetBufferMemoryRequirements, "vkGetBufferMemoryRequirements");
  12478. VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements, PFN_vkGetImageMemoryRequirements, "vkGetImageMemoryRequirements");
  12479. VMA_FETCH_DEVICE_FUNC(vkCreateBuffer, PFN_vkCreateBuffer, "vkCreateBuffer");
  12480. VMA_FETCH_DEVICE_FUNC(vkDestroyBuffer, PFN_vkDestroyBuffer, "vkDestroyBuffer");
  12481. VMA_FETCH_DEVICE_FUNC(vkCreateImage, PFN_vkCreateImage, "vkCreateImage");
  12482. VMA_FETCH_DEVICE_FUNC(vkDestroyImage, PFN_vkDestroyImage, "vkDestroyImage");
  12483. VMA_FETCH_DEVICE_FUNC(vkCmdCopyBuffer, PFN_vkCmdCopyBuffer, "vkCmdCopyBuffer");
  12484. #if VMA_VULKAN_VERSION >= 1001000
  12485. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12486. {
  12487. VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements2KHR, PFN_vkGetBufferMemoryRequirements2, "vkGetBufferMemoryRequirements2");
  12488. VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements2KHR, PFN_vkGetImageMemoryRequirements2, "vkGetImageMemoryRequirements2");
  12489. VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory2KHR, PFN_vkBindBufferMemory2, "vkBindBufferMemory2");
  12490. VMA_FETCH_DEVICE_FUNC(vkBindImageMemory2KHR, PFN_vkBindImageMemory2, "vkBindImageMemory2");
  12491. }
  12492. #endif
  12493. #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000
  12494. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12495. {
  12496. VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties2KHR, PFN_vkGetPhysicalDeviceMemoryProperties2, "vkGetPhysicalDeviceMemoryProperties2");
  12497. }
  12498. else if(m_UseExtMemoryBudget)
  12499. {
  12500. VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties2KHR, PFN_vkGetPhysicalDeviceMemoryProperties2, "vkGetPhysicalDeviceMemoryProperties2KHR");
  12501. }
  12502. #endif
  12503. #if VMA_DEDICATED_ALLOCATION
  12504. if(m_UseKhrDedicatedAllocation)
  12505. {
  12506. VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements2KHR, PFN_vkGetBufferMemoryRequirements2KHR, "vkGetBufferMemoryRequirements2KHR");
  12507. VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements2KHR, PFN_vkGetImageMemoryRequirements2KHR, "vkGetImageMemoryRequirements2KHR");
  12508. }
  12509. #endif
  12510. #if VMA_BIND_MEMORY2
  12511. if(m_UseKhrBindMemory2)
  12512. {
  12513. VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory2KHR, PFN_vkBindBufferMemory2KHR, "vkBindBufferMemory2KHR");
  12514. VMA_FETCH_DEVICE_FUNC(vkBindImageMemory2KHR, PFN_vkBindImageMemory2KHR, "vkBindImageMemory2KHR");
  12515. }
  12516. #endif // #if VMA_BIND_MEMORY2
  12517. #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000
  12518. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12519. {
  12520. VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties2KHR, PFN_vkGetPhysicalDeviceMemoryProperties2KHR, "vkGetPhysicalDeviceMemoryProperties2");
  12521. }
  12522. else if(m_UseExtMemoryBudget)
  12523. {
  12524. VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties2KHR, PFN_vkGetPhysicalDeviceMemoryProperties2KHR, "vkGetPhysicalDeviceMemoryProperties2KHR");
  12525. }
  12526. #endif // #if VMA_MEMORY_BUDGET
  12527. #if VMA_VULKAN_VERSION >= 1003000
  12528. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 3, 0))
  12529. {
  12530. VMA_FETCH_DEVICE_FUNC(vkGetDeviceBufferMemoryRequirements, PFN_vkGetDeviceBufferMemoryRequirements, "vkGetDeviceBufferMemoryRequirements");
  12531. VMA_FETCH_DEVICE_FUNC(vkGetDeviceImageMemoryRequirements, PFN_vkGetDeviceImageMemoryRequirements, "vkGetDeviceImageMemoryRequirements");
  12532. }
  12533. #endif
  12534. #undef VMA_FETCH_DEVICE_FUNC
  12535. #undef VMA_FETCH_INSTANCE_FUNC
  12536. }
  12537. #endif // VMA_DYNAMIC_VULKAN_FUNCTIONS == 1
  12538. void VmaAllocator_T::ValidateVulkanFunctions()
  12539. {
  12540. VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceProperties != VMA_NULL);
  12541. VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties != VMA_NULL);
  12542. VMA_ASSERT(m_VulkanFunctions.vkAllocateMemory != VMA_NULL);
  12543. VMA_ASSERT(m_VulkanFunctions.vkFreeMemory != VMA_NULL);
  12544. VMA_ASSERT(m_VulkanFunctions.vkMapMemory != VMA_NULL);
  12545. VMA_ASSERT(m_VulkanFunctions.vkUnmapMemory != VMA_NULL);
  12546. VMA_ASSERT(m_VulkanFunctions.vkFlushMappedMemoryRanges != VMA_NULL);
  12547. VMA_ASSERT(m_VulkanFunctions.vkInvalidateMappedMemoryRanges != VMA_NULL);
  12548. VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory != VMA_NULL);
  12549. VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory != VMA_NULL);
  12550. VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements != VMA_NULL);
  12551. VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements != VMA_NULL);
  12552. VMA_ASSERT(m_VulkanFunctions.vkCreateBuffer != VMA_NULL);
  12553. VMA_ASSERT(m_VulkanFunctions.vkDestroyBuffer != VMA_NULL);
  12554. VMA_ASSERT(m_VulkanFunctions.vkCreateImage != VMA_NULL);
  12555. VMA_ASSERT(m_VulkanFunctions.vkDestroyImage != VMA_NULL);
  12556. VMA_ASSERT(m_VulkanFunctions.vkCmdCopyBuffer != VMA_NULL);
  12557. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12558. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0) || m_UseKhrDedicatedAllocation)
  12559. {
  12560. VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR != VMA_NULL);
  12561. VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements2KHR != VMA_NULL);
  12562. }
  12563. #endif
  12564. #if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000
  12565. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0) || m_UseKhrBindMemory2)
  12566. {
  12567. VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory2KHR != VMA_NULL);
  12568. VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory2KHR != VMA_NULL);
  12569. }
  12570. #endif
  12571. #if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000
  12572. if(m_UseExtMemoryBudget || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12573. {
  12574. VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR != VMA_NULL);
  12575. }
  12576. #endif
  12577. #if VMA_VULKAN_VERSION >= 1003000
  12578. if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 3, 0))
  12579. {
  12580. VMA_ASSERT(m_VulkanFunctions.vkGetDeviceBufferMemoryRequirements != VMA_NULL);
  12581. VMA_ASSERT(m_VulkanFunctions.vkGetDeviceImageMemoryRequirements != VMA_NULL);
  12582. }
  12583. #endif
  12584. }
  12585. VkDeviceSize VmaAllocator_T::CalcPreferredBlockSize(uint32_t memTypeIndex)
  12586. {
  12587. const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex);
  12588. const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size;
  12589. const bool isSmallHeap = heapSize <= VMA_SMALL_HEAP_MAX_SIZE;
  12590. return VmaAlignUp(isSmallHeap ? (heapSize / 8) : m_PreferredLargeHeapBlockSize, (VkDeviceSize)32);
  12591. }
  12592. VkResult VmaAllocator_T::AllocateMemoryOfType(
  12593. VmaPool pool,
  12594. VkDeviceSize size,
  12595. VkDeviceSize alignment,
  12596. bool dedicatedPreferred,
  12597. VkBuffer dedicatedBuffer,
  12598. VkImage dedicatedImage,
  12599. VkFlags dedicatedBufferImageUsage,
  12600. const VmaAllocationCreateInfo& createInfo,
  12601. uint32_t memTypeIndex,
  12602. VmaSuballocationType suballocType,
  12603. VmaDedicatedAllocationList& dedicatedAllocations,
  12604. VmaBlockVector& blockVector,
  12605. size_t allocationCount,
  12606. VmaAllocation* pAllocations)
  12607. {
  12608. VMA_ASSERT(pAllocations != VMA_NULL);
  12609. VMA_DEBUG_LOG_FORMAT(" AllocateMemory: MemoryTypeIndex=%u, AllocationCount=%zu, Size=%llu", memTypeIndex, allocationCount, size);
  12610. VmaAllocationCreateInfo finalCreateInfo = createInfo;
  12611. VkResult res = CalcMemTypeParams(
  12612. finalCreateInfo,
  12613. memTypeIndex,
  12614. size,
  12615. allocationCount);
  12616. if(res != VK_SUCCESS)
  12617. return res;
  12618. if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0)
  12619. {
  12620. return AllocateDedicatedMemory(
  12621. pool,
  12622. size,
  12623. suballocType,
  12624. dedicatedAllocations,
  12625. memTypeIndex,
  12626. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0,
  12627. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0,
  12628. (finalCreateInfo.flags &
  12629. (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0,
  12630. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT) != 0,
  12631. finalCreateInfo.pUserData,
  12632. finalCreateInfo.priority,
  12633. dedicatedBuffer,
  12634. dedicatedImage,
  12635. dedicatedBufferImageUsage,
  12636. allocationCount,
  12637. pAllocations,
  12638. blockVector.GetAllocationNextPtr());
  12639. }
  12640. else
  12641. {
  12642. const bool canAllocateDedicated =
  12643. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0 &&
  12644. (pool == VK_NULL_HANDLE || !blockVector.HasExplicitBlockSize());
  12645. if(canAllocateDedicated)
  12646. {
  12647. // Heuristics: Allocate dedicated memory if requested size if greater than half of preferred block size.
  12648. if(size > blockVector.GetPreferredBlockSize() / 2)
  12649. {
  12650. dedicatedPreferred = true;
  12651. }
  12652. // Protection against creating each allocation as dedicated when we reach or exceed heap size/budget,
  12653. // which can quickly deplete maxMemoryAllocationCount: Don't prefer dedicated allocations when above
  12654. // 3/4 of the maximum allocation count.
  12655. if(m_PhysicalDeviceProperties.limits.maxMemoryAllocationCount < UINT32_MAX / 4 &&
  12656. m_DeviceMemoryCount.load() > m_PhysicalDeviceProperties.limits.maxMemoryAllocationCount * 3 / 4)
  12657. {
  12658. dedicatedPreferred = false;
  12659. }
  12660. if(dedicatedPreferred)
  12661. {
  12662. res = AllocateDedicatedMemory(
  12663. pool,
  12664. size,
  12665. suballocType,
  12666. dedicatedAllocations,
  12667. memTypeIndex,
  12668. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0,
  12669. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0,
  12670. (finalCreateInfo.flags &
  12671. (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0,
  12672. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT) != 0,
  12673. finalCreateInfo.pUserData,
  12674. finalCreateInfo.priority,
  12675. dedicatedBuffer,
  12676. dedicatedImage,
  12677. dedicatedBufferImageUsage,
  12678. allocationCount,
  12679. pAllocations,
  12680. blockVector.GetAllocationNextPtr());
  12681. if(res == VK_SUCCESS)
  12682. {
  12683. // Succeeded: AllocateDedicatedMemory function already filled pMemory, nothing more to do here.
  12684. VMA_DEBUG_LOG(" Allocated as DedicatedMemory");
  12685. return VK_SUCCESS;
  12686. }
  12687. }
  12688. }
  12689. res = blockVector.Allocate(
  12690. size,
  12691. alignment,
  12692. finalCreateInfo,
  12693. suballocType,
  12694. allocationCount,
  12695. pAllocations);
  12696. if(res == VK_SUCCESS)
  12697. return VK_SUCCESS;
  12698. // Try dedicated memory.
  12699. if(canAllocateDedicated && !dedicatedPreferred)
  12700. {
  12701. res = AllocateDedicatedMemory(
  12702. pool,
  12703. size,
  12704. suballocType,
  12705. dedicatedAllocations,
  12706. memTypeIndex,
  12707. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0,
  12708. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0,
  12709. (finalCreateInfo.flags &
  12710. (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0,
  12711. (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT) != 0,
  12712. finalCreateInfo.pUserData,
  12713. finalCreateInfo.priority,
  12714. dedicatedBuffer,
  12715. dedicatedImage,
  12716. dedicatedBufferImageUsage,
  12717. allocationCount,
  12718. pAllocations,
  12719. blockVector.GetAllocationNextPtr());
  12720. if(res == VK_SUCCESS)
  12721. {
  12722. // Succeeded: AllocateDedicatedMemory function already filled pMemory, nothing more to do here.
  12723. VMA_DEBUG_LOG(" Allocated as DedicatedMemory");
  12724. return VK_SUCCESS;
  12725. }
  12726. }
  12727. // Everything failed: Return error code.
  12728. VMA_DEBUG_LOG(" vkAllocateMemory FAILED");
  12729. return res;
  12730. }
  12731. }
  12732. VkResult VmaAllocator_T::AllocateDedicatedMemory(
  12733. VmaPool pool,
  12734. VkDeviceSize size,
  12735. VmaSuballocationType suballocType,
  12736. VmaDedicatedAllocationList& dedicatedAllocations,
  12737. uint32_t memTypeIndex,
  12738. bool map,
  12739. bool isUserDataString,
  12740. bool isMappingAllowed,
  12741. bool canAliasMemory,
  12742. void* pUserData,
  12743. float priority,
  12744. VkBuffer dedicatedBuffer,
  12745. VkImage dedicatedImage,
  12746. VkFlags dedicatedBufferImageUsage,
  12747. size_t allocationCount,
  12748. VmaAllocation* pAllocations,
  12749. const void* pNextChain)
  12750. {
  12751. VMA_ASSERT(allocationCount > 0 && pAllocations);
  12752. VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
  12753. allocInfo.memoryTypeIndex = memTypeIndex;
  12754. allocInfo.allocationSize = size;
  12755. allocInfo.pNext = pNextChain;
  12756. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12757. VkMemoryDedicatedAllocateInfoKHR dedicatedAllocInfo = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR };
  12758. if(!canAliasMemory)
  12759. {
  12760. if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12761. {
  12762. if(dedicatedBuffer != VK_NULL_HANDLE)
  12763. {
  12764. VMA_ASSERT(dedicatedImage == VK_NULL_HANDLE);
  12765. dedicatedAllocInfo.buffer = dedicatedBuffer;
  12766. VmaPnextChainPushFront(&allocInfo, &dedicatedAllocInfo);
  12767. }
  12768. else if(dedicatedImage != VK_NULL_HANDLE)
  12769. {
  12770. dedicatedAllocInfo.image = dedicatedImage;
  12771. VmaPnextChainPushFront(&allocInfo, &dedicatedAllocInfo);
  12772. }
  12773. }
  12774. }
  12775. #endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12776. #if VMA_BUFFER_DEVICE_ADDRESS
  12777. VkMemoryAllocateFlagsInfoKHR allocFlagsInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR };
  12778. if(m_UseKhrBufferDeviceAddress)
  12779. {
  12780. bool canContainBufferWithDeviceAddress = true;
  12781. if(dedicatedBuffer != VK_NULL_HANDLE)
  12782. {
  12783. canContainBufferWithDeviceAddress = dedicatedBufferImageUsage == UINT32_MAX || // Usage flags unknown
  12784. (dedicatedBufferImageUsage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT) != 0;
  12785. }
  12786. else if(dedicatedImage != VK_NULL_HANDLE)
  12787. {
  12788. canContainBufferWithDeviceAddress = false;
  12789. }
  12790. if(canContainBufferWithDeviceAddress)
  12791. {
  12792. allocFlagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR;
  12793. VmaPnextChainPushFront(&allocInfo, &allocFlagsInfo);
  12794. }
  12795. }
  12796. #endif // #if VMA_BUFFER_DEVICE_ADDRESS
  12797. #if VMA_MEMORY_PRIORITY
  12798. VkMemoryPriorityAllocateInfoEXT priorityInfo = { VK_STRUCTURE_TYPE_MEMORY_PRIORITY_ALLOCATE_INFO_EXT };
  12799. if(m_UseExtMemoryPriority)
  12800. {
  12801. VMA_ASSERT(priority >= 0.f && priority <= 1.f);
  12802. priorityInfo.priority = priority;
  12803. VmaPnextChainPushFront(&allocInfo, &priorityInfo);
  12804. }
  12805. #endif // #if VMA_MEMORY_PRIORITY
  12806. #if VMA_EXTERNAL_MEMORY
  12807. // Attach VkExportMemoryAllocateInfoKHR if necessary.
  12808. VkExportMemoryAllocateInfoKHR exportMemoryAllocInfo = { VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR };
  12809. exportMemoryAllocInfo.handleTypes = GetExternalMemoryHandleTypeFlags(memTypeIndex);
  12810. if(exportMemoryAllocInfo.handleTypes != 0)
  12811. {
  12812. VmaPnextChainPushFront(&allocInfo, &exportMemoryAllocInfo);
  12813. }
  12814. #endif // #if VMA_EXTERNAL_MEMORY
  12815. size_t allocIndex;
  12816. VkResult res = VK_SUCCESS;
  12817. for(allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  12818. {
  12819. res = AllocateDedicatedMemoryPage(
  12820. pool,
  12821. size,
  12822. suballocType,
  12823. memTypeIndex,
  12824. allocInfo,
  12825. map,
  12826. isUserDataString,
  12827. isMappingAllowed,
  12828. pUserData,
  12829. pAllocations + allocIndex);
  12830. if(res != VK_SUCCESS)
  12831. {
  12832. break;
  12833. }
  12834. }
  12835. if(res == VK_SUCCESS)
  12836. {
  12837. for (allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  12838. {
  12839. dedicatedAllocations.Register(pAllocations[allocIndex]);
  12840. }
  12841. VMA_DEBUG_LOG_FORMAT(" Allocated DedicatedMemory Count=%zu, MemoryTypeIndex=#%u", allocationCount, memTypeIndex);
  12842. }
  12843. else
  12844. {
  12845. // Free all already created allocations.
  12846. while(allocIndex--)
  12847. {
  12848. VmaAllocation currAlloc = pAllocations[allocIndex];
  12849. VkDeviceMemory hMemory = currAlloc->GetMemory();
  12850. /*
  12851. There is no need to call this, because Vulkan spec allows to skip vkUnmapMemory
  12852. before vkFreeMemory.
  12853. if(currAlloc->GetMappedData() != VMA_NULL)
  12854. {
  12855. (*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory);
  12856. }
  12857. */
  12858. FreeVulkanMemory(memTypeIndex, currAlloc->GetSize(), hMemory);
  12859. m_Budget.RemoveAllocation(MemoryTypeIndexToHeapIndex(memTypeIndex), currAlloc->GetSize());
  12860. m_AllocationObjectAllocator.Free(currAlloc);
  12861. }
  12862. memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount);
  12863. }
  12864. return res;
  12865. }
  12866. VkResult VmaAllocator_T::AllocateDedicatedMemoryPage(
  12867. VmaPool pool,
  12868. VkDeviceSize size,
  12869. VmaSuballocationType suballocType,
  12870. uint32_t memTypeIndex,
  12871. const VkMemoryAllocateInfo& allocInfo,
  12872. bool map,
  12873. bool isUserDataString,
  12874. bool isMappingAllowed,
  12875. void* pUserData,
  12876. VmaAllocation* pAllocation)
  12877. {
  12878. VkDeviceMemory hMemory = VK_NULL_HANDLE;
  12879. VkResult res = AllocateVulkanMemory(&allocInfo, &hMemory);
  12880. if(res < 0)
  12881. {
  12882. VMA_DEBUG_LOG(" vkAllocateMemory FAILED");
  12883. return res;
  12884. }
  12885. void* pMappedData = VMA_NULL;
  12886. if(map)
  12887. {
  12888. res = (*m_VulkanFunctions.vkMapMemory)(
  12889. m_hDevice,
  12890. hMemory,
  12891. 0,
  12892. VK_WHOLE_SIZE,
  12893. 0,
  12894. &pMappedData);
  12895. if(res < 0)
  12896. {
  12897. VMA_DEBUG_LOG(" vkMapMemory FAILED");
  12898. FreeVulkanMemory(memTypeIndex, size, hMemory);
  12899. return res;
  12900. }
  12901. }
  12902. *pAllocation = m_AllocationObjectAllocator.Allocate(isMappingAllowed);
  12903. (*pAllocation)->InitDedicatedAllocation(pool, memTypeIndex, hMemory, suballocType, pMappedData, size);
  12904. if (isUserDataString)
  12905. (*pAllocation)->SetName(this, (const char*)pUserData);
  12906. else
  12907. (*pAllocation)->SetUserData(this, pUserData);
  12908. m_Budget.AddAllocation(MemoryTypeIndexToHeapIndex(memTypeIndex), size);
  12909. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
  12910. {
  12911. FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED);
  12912. }
  12913. return VK_SUCCESS;
  12914. }
  12915. void VmaAllocator_T::GetBufferMemoryRequirements(
  12916. VkBuffer hBuffer,
  12917. VkMemoryRequirements& memReq,
  12918. bool& requiresDedicatedAllocation,
  12919. bool& prefersDedicatedAllocation) const
  12920. {
  12921. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12922. if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12923. {
  12924. VkBufferMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR };
  12925. memReqInfo.buffer = hBuffer;
  12926. VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR };
  12927. VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR };
  12928. VmaPnextChainPushFront(&memReq2, &memDedicatedReq);
  12929. (*m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2);
  12930. memReq = memReq2.memoryRequirements;
  12931. requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE);
  12932. prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE);
  12933. }
  12934. else
  12935. #endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12936. {
  12937. (*m_VulkanFunctions.vkGetBufferMemoryRequirements)(m_hDevice, hBuffer, &memReq);
  12938. requiresDedicatedAllocation = false;
  12939. prefersDedicatedAllocation = false;
  12940. }
  12941. }
  12942. void VmaAllocator_T::GetImageMemoryRequirements(
  12943. VkImage hImage,
  12944. VkMemoryRequirements& memReq,
  12945. bool& requiresDedicatedAllocation,
  12946. bool& prefersDedicatedAllocation) const
  12947. {
  12948. #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12949. if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0))
  12950. {
  12951. VkImageMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR };
  12952. memReqInfo.image = hImage;
  12953. VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR };
  12954. VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR };
  12955. VmaPnextChainPushFront(&memReq2, &memDedicatedReq);
  12956. (*m_VulkanFunctions.vkGetImageMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2);
  12957. memReq = memReq2.memoryRequirements;
  12958. requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE);
  12959. prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE);
  12960. }
  12961. else
  12962. #endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000
  12963. {
  12964. (*m_VulkanFunctions.vkGetImageMemoryRequirements)(m_hDevice, hImage, &memReq);
  12965. requiresDedicatedAllocation = false;
  12966. prefersDedicatedAllocation = false;
  12967. }
  12968. }
  12969. VkResult VmaAllocator_T::FindMemoryTypeIndex(
  12970. uint32_t memoryTypeBits,
  12971. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  12972. VkFlags bufImgUsage,
  12973. uint32_t* pMemoryTypeIndex) const
  12974. {
  12975. memoryTypeBits &= GetGlobalMemoryTypeBits();
  12976. if(pAllocationCreateInfo->memoryTypeBits != 0)
  12977. {
  12978. memoryTypeBits &= pAllocationCreateInfo->memoryTypeBits;
  12979. }
  12980. VkMemoryPropertyFlags requiredFlags = 0, preferredFlags = 0, notPreferredFlags = 0;
  12981. if(!FindMemoryPreferences(
  12982. IsIntegratedGpu(),
  12983. *pAllocationCreateInfo,
  12984. bufImgUsage,
  12985. requiredFlags, preferredFlags, notPreferredFlags))
  12986. {
  12987. return VK_ERROR_FEATURE_NOT_PRESENT;
  12988. }
  12989. *pMemoryTypeIndex = UINT32_MAX;
  12990. uint32_t minCost = UINT32_MAX;
  12991. for(uint32_t memTypeIndex = 0, memTypeBit = 1;
  12992. memTypeIndex < GetMemoryTypeCount();
  12993. ++memTypeIndex, memTypeBit <<= 1)
  12994. {
  12995. // This memory type is acceptable according to memoryTypeBits bitmask.
  12996. if((memTypeBit & memoryTypeBits) != 0)
  12997. {
  12998. const VkMemoryPropertyFlags currFlags =
  12999. m_MemProps.memoryTypes[memTypeIndex].propertyFlags;
  13000. // This memory type contains requiredFlags.
  13001. if((requiredFlags & ~currFlags) == 0)
  13002. {
  13003. // Calculate cost as number of bits from preferredFlags not present in this memory type.
  13004. uint32_t currCost = VMA_COUNT_BITS_SET(preferredFlags & ~currFlags) +
  13005. VMA_COUNT_BITS_SET(currFlags & notPreferredFlags);
  13006. // Remember memory type with lowest cost.
  13007. if(currCost < minCost)
  13008. {
  13009. *pMemoryTypeIndex = memTypeIndex;
  13010. if(currCost == 0)
  13011. {
  13012. return VK_SUCCESS;
  13013. }
  13014. minCost = currCost;
  13015. }
  13016. }
  13017. }
  13018. }
  13019. return (*pMemoryTypeIndex != UINT32_MAX) ? VK_SUCCESS : VK_ERROR_FEATURE_NOT_PRESENT;
  13020. }
  13021. VkResult VmaAllocator_T::CalcMemTypeParams(
  13022. VmaAllocationCreateInfo& inoutCreateInfo,
  13023. uint32_t memTypeIndex,
  13024. VkDeviceSize size,
  13025. size_t allocationCount)
  13026. {
  13027. // If memory type is not HOST_VISIBLE, disable MAPPED.
  13028. if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 &&
  13029. (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
  13030. {
  13031. inoutCreateInfo.flags &= ~VMA_ALLOCATION_CREATE_MAPPED_BIT;
  13032. }
  13033. if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0 &&
  13034. (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT) != 0)
  13035. {
  13036. const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex);
  13037. VmaBudget heapBudget = {};
  13038. GetHeapBudgets(&heapBudget, heapIndex, 1);
  13039. if(heapBudget.usage + size * allocationCount > heapBudget.budget)
  13040. {
  13041. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  13042. }
  13043. }
  13044. return VK_SUCCESS;
  13045. }
  13046. VkResult VmaAllocator_T::CalcAllocationParams(
  13047. VmaAllocationCreateInfo& inoutCreateInfo,
  13048. bool dedicatedRequired,
  13049. bool dedicatedPreferred)
  13050. {
  13051. VMA_ASSERT((inoutCreateInfo.flags &
  13052. (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) !=
  13053. (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT) &&
  13054. "Specifying both flags VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT and VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT is incorrect.");
  13055. VMA_ASSERT((((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT) == 0 ||
  13056. (inoutCreateInfo.flags & (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0)) &&
  13057. "Specifying VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT requires also VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT.");
  13058. if(inoutCreateInfo.usage == VMA_MEMORY_USAGE_AUTO || inoutCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE || inoutCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_HOST)
  13059. {
  13060. if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0)
  13061. {
  13062. VMA_ASSERT((inoutCreateInfo.flags & (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0 &&
  13063. "When using VMA_ALLOCATION_CREATE_MAPPED_BIT and usage = VMA_MEMORY_USAGE_AUTO*, you must also specify VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT.");
  13064. }
  13065. }
  13066. // If memory is lazily allocated, it should be always dedicated.
  13067. if(dedicatedRequired ||
  13068. inoutCreateInfo.usage == VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED)
  13069. {
  13070. inoutCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  13071. }
  13072. if(inoutCreateInfo.pool != VK_NULL_HANDLE)
  13073. {
  13074. if(inoutCreateInfo.pool->m_BlockVector.HasExplicitBlockSize() &&
  13075. (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0)
  13076. {
  13077. VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT while current custom pool doesn't support dedicated allocations.");
  13078. return VK_ERROR_FEATURE_NOT_PRESENT;
  13079. }
  13080. inoutCreateInfo.priority = inoutCreateInfo.pool->m_BlockVector.GetPriority();
  13081. }
  13082. if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0 &&
  13083. (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
  13084. {
  13085. VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT together with VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT makes no sense.");
  13086. return VK_ERROR_FEATURE_NOT_PRESENT;
  13087. }
  13088. if(VMA_DEBUG_ALWAYS_DEDICATED_MEMORY &&
  13089. (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
  13090. {
  13091. inoutCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  13092. }
  13093. // Non-auto USAGE values imply HOST_ACCESS flags.
  13094. // And so does VMA_MEMORY_USAGE_UNKNOWN because it is used with custom pools.
  13095. // Which specific flag is used doesn't matter. They change things only when used with VMA_MEMORY_USAGE_AUTO*.
  13096. // Otherwise they just protect from assert on mapping.
  13097. if(inoutCreateInfo.usage != VMA_MEMORY_USAGE_AUTO &&
  13098. inoutCreateInfo.usage != VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE &&
  13099. inoutCreateInfo.usage != VMA_MEMORY_USAGE_AUTO_PREFER_HOST)
  13100. {
  13101. if((inoutCreateInfo.flags & (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) == 0)
  13102. {
  13103. inoutCreateInfo.flags |= VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT;
  13104. }
  13105. }
  13106. return VK_SUCCESS;
  13107. }
  13108. VkResult VmaAllocator_T::AllocateMemory(
  13109. const VkMemoryRequirements& vkMemReq,
  13110. bool requiresDedicatedAllocation,
  13111. bool prefersDedicatedAllocation,
  13112. VkBuffer dedicatedBuffer,
  13113. VkImage dedicatedImage,
  13114. VkFlags dedicatedBufferImageUsage,
  13115. const VmaAllocationCreateInfo& createInfo,
  13116. VmaSuballocationType suballocType,
  13117. size_t allocationCount,
  13118. VmaAllocation* pAllocations)
  13119. {
  13120. memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount);
  13121. VMA_ASSERT(VmaIsPow2(vkMemReq.alignment));
  13122. if(vkMemReq.size == 0)
  13123. {
  13124. return VK_ERROR_INITIALIZATION_FAILED;
  13125. }
  13126. VmaAllocationCreateInfo createInfoFinal = createInfo;
  13127. VkResult res = CalcAllocationParams(createInfoFinal, requiresDedicatedAllocation, prefersDedicatedAllocation);
  13128. if(res != VK_SUCCESS)
  13129. return res;
  13130. if(createInfoFinal.pool != VK_NULL_HANDLE)
  13131. {
  13132. VmaBlockVector& blockVector = createInfoFinal.pool->m_BlockVector;
  13133. return AllocateMemoryOfType(
  13134. createInfoFinal.pool,
  13135. vkMemReq.size,
  13136. vkMemReq.alignment,
  13137. prefersDedicatedAllocation,
  13138. dedicatedBuffer,
  13139. dedicatedImage,
  13140. dedicatedBufferImageUsage,
  13141. createInfoFinal,
  13142. blockVector.GetMemoryTypeIndex(),
  13143. suballocType,
  13144. createInfoFinal.pool->m_DedicatedAllocations,
  13145. blockVector,
  13146. allocationCount,
  13147. pAllocations);
  13148. }
  13149. else
  13150. {
  13151. // Bit mask of memory Vulkan types acceptable for this allocation.
  13152. uint32_t memoryTypeBits = vkMemReq.memoryTypeBits;
  13153. uint32_t memTypeIndex = UINT32_MAX;
  13154. res = FindMemoryTypeIndex(memoryTypeBits, &createInfoFinal, dedicatedBufferImageUsage, &memTypeIndex);
  13155. // Can't find any single memory type matching requirements. res is VK_ERROR_FEATURE_NOT_PRESENT.
  13156. if(res != VK_SUCCESS)
  13157. return res;
  13158. do
  13159. {
  13160. VmaBlockVector* blockVector = m_pBlockVectors[memTypeIndex];
  13161. VMA_ASSERT(blockVector && "Trying to use unsupported memory type!");
  13162. res = AllocateMemoryOfType(
  13163. VK_NULL_HANDLE,
  13164. vkMemReq.size,
  13165. vkMemReq.alignment,
  13166. requiresDedicatedAllocation || prefersDedicatedAllocation,
  13167. dedicatedBuffer,
  13168. dedicatedImage,
  13169. dedicatedBufferImageUsage,
  13170. createInfoFinal,
  13171. memTypeIndex,
  13172. suballocType,
  13173. m_DedicatedAllocations[memTypeIndex],
  13174. *blockVector,
  13175. allocationCount,
  13176. pAllocations);
  13177. // Allocation succeeded
  13178. if(res == VK_SUCCESS)
  13179. return VK_SUCCESS;
  13180. // Remove old memTypeIndex from list of possibilities.
  13181. memoryTypeBits &= ~(1u << memTypeIndex);
  13182. // Find alternative memTypeIndex.
  13183. res = FindMemoryTypeIndex(memoryTypeBits, &createInfoFinal, dedicatedBufferImageUsage, &memTypeIndex);
  13184. } while(res == VK_SUCCESS);
  13185. // No other matching memory type index could be found.
  13186. // Not returning res, which is VK_ERROR_FEATURE_NOT_PRESENT, because we already failed to allocate once.
  13187. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  13188. }
  13189. }
  13190. void VmaAllocator_T::FreeMemory(
  13191. size_t allocationCount,
  13192. const VmaAllocation* pAllocations)
  13193. {
  13194. VMA_ASSERT(pAllocations);
  13195. for(size_t allocIndex = allocationCount; allocIndex--; )
  13196. {
  13197. VmaAllocation allocation = pAllocations[allocIndex];
  13198. if(allocation != VK_NULL_HANDLE)
  13199. {
  13200. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
  13201. {
  13202. FillAllocation(allocation, VMA_ALLOCATION_FILL_PATTERN_DESTROYED);
  13203. }
  13204. allocation->FreeName(this);
  13205. switch(allocation->GetType())
  13206. {
  13207. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13208. {
  13209. VmaBlockVector* pBlockVector = VMA_NULL;
  13210. VmaPool hPool = allocation->GetParentPool();
  13211. if(hPool != VK_NULL_HANDLE)
  13212. {
  13213. pBlockVector = &hPool->m_BlockVector;
  13214. }
  13215. else
  13216. {
  13217. const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
  13218. pBlockVector = m_pBlockVectors[memTypeIndex];
  13219. VMA_ASSERT(pBlockVector && "Trying to free memory of unsupported type!");
  13220. }
  13221. pBlockVector->Free(allocation);
  13222. }
  13223. break;
  13224. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13225. FreeDedicatedMemory(allocation);
  13226. break;
  13227. default:
  13228. VMA_ASSERT(0);
  13229. }
  13230. }
  13231. }
  13232. }
  13233. void VmaAllocator_T::CalculateStatistics(VmaTotalStatistics* pStats)
  13234. {
  13235. // Initialize.
  13236. VmaClearDetailedStatistics(pStats->total);
  13237. for(uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; ++i)
  13238. VmaClearDetailedStatistics(pStats->memoryType[i]);
  13239. for(uint32_t i = 0; i < VK_MAX_MEMORY_HEAPS; ++i)
  13240. VmaClearDetailedStatistics(pStats->memoryHeap[i]);
  13241. // Process default pools.
  13242. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13243. {
  13244. VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex];
  13245. if (pBlockVector != VMA_NULL)
  13246. pBlockVector->AddDetailedStatistics(pStats->memoryType[memTypeIndex]);
  13247. }
  13248. // Process custom pools.
  13249. {
  13250. VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex);
  13251. for(VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool))
  13252. {
  13253. VmaBlockVector& blockVector = pool->m_BlockVector;
  13254. const uint32_t memTypeIndex = blockVector.GetMemoryTypeIndex();
  13255. blockVector.AddDetailedStatistics(pStats->memoryType[memTypeIndex]);
  13256. pool->m_DedicatedAllocations.AddDetailedStatistics(pStats->memoryType[memTypeIndex]);
  13257. }
  13258. }
  13259. // Process dedicated allocations.
  13260. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13261. {
  13262. m_DedicatedAllocations[memTypeIndex].AddDetailedStatistics(pStats->memoryType[memTypeIndex]);
  13263. }
  13264. // Sum from memory types to memory heaps.
  13265. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13266. {
  13267. const uint32_t memHeapIndex = m_MemProps.memoryTypes[memTypeIndex].heapIndex;
  13268. VmaAddDetailedStatistics(pStats->memoryHeap[memHeapIndex], pStats->memoryType[memTypeIndex]);
  13269. }
  13270. // Sum from memory heaps to total.
  13271. for(uint32_t memHeapIndex = 0; memHeapIndex < GetMemoryHeapCount(); ++memHeapIndex)
  13272. VmaAddDetailedStatistics(pStats->total, pStats->memoryHeap[memHeapIndex]);
  13273. VMA_ASSERT(pStats->total.statistics.allocationCount == 0 ||
  13274. pStats->total.allocationSizeMax >= pStats->total.allocationSizeMin);
  13275. VMA_ASSERT(pStats->total.unusedRangeCount == 0 ||
  13276. pStats->total.unusedRangeSizeMax >= pStats->total.unusedRangeSizeMin);
  13277. }
  13278. void VmaAllocator_T::GetHeapBudgets(VmaBudget* outBudgets, uint32_t firstHeap, uint32_t heapCount)
  13279. {
  13280. #if VMA_MEMORY_BUDGET
  13281. if(m_UseExtMemoryBudget)
  13282. {
  13283. if(m_Budget.m_OperationsSinceBudgetFetch < 30)
  13284. {
  13285. VmaMutexLockRead lockRead(m_Budget.m_BudgetMutex, m_UseMutex);
  13286. for(uint32_t i = 0; i < heapCount; ++i, ++outBudgets)
  13287. {
  13288. const uint32_t heapIndex = firstHeap + i;
  13289. outBudgets->statistics.blockCount = m_Budget.m_BlockCount[heapIndex];
  13290. outBudgets->statistics.allocationCount = m_Budget.m_AllocationCount[heapIndex];
  13291. outBudgets->statistics.blockBytes = m_Budget.m_BlockBytes[heapIndex];
  13292. outBudgets->statistics.allocationBytes = m_Budget.m_AllocationBytes[heapIndex];
  13293. if(m_Budget.m_VulkanUsage[heapIndex] + outBudgets->statistics.blockBytes > m_Budget.m_BlockBytesAtBudgetFetch[heapIndex])
  13294. {
  13295. outBudgets->usage = m_Budget.m_VulkanUsage[heapIndex] +
  13296. outBudgets->statistics.blockBytes - m_Budget.m_BlockBytesAtBudgetFetch[heapIndex];
  13297. }
  13298. else
  13299. {
  13300. outBudgets->usage = 0;
  13301. }
  13302. // Have to take MIN with heap size because explicit HeapSizeLimit is included in it.
  13303. outBudgets->budget = VMA_MIN(
  13304. m_Budget.m_VulkanBudget[heapIndex], m_MemProps.memoryHeaps[heapIndex].size);
  13305. }
  13306. }
  13307. else
  13308. {
  13309. UpdateVulkanBudget(); // Outside of mutex lock
  13310. GetHeapBudgets(outBudgets, firstHeap, heapCount); // Recursion
  13311. }
  13312. }
  13313. else
  13314. #endif
  13315. {
  13316. for(uint32_t i = 0; i < heapCount; ++i, ++outBudgets)
  13317. {
  13318. const uint32_t heapIndex = firstHeap + i;
  13319. outBudgets->statistics.blockCount = m_Budget.m_BlockCount[heapIndex];
  13320. outBudgets->statistics.allocationCount = m_Budget.m_AllocationCount[heapIndex];
  13321. outBudgets->statistics.blockBytes = m_Budget.m_BlockBytes[heapIndex];
  13322. outBudgets->statistics.allocationBytes = m_Budget.m_AllocationBytes[heapIndex];
  13323. outBudgets->usage = outBudgets->statistics.blockBytes;
  13324. outBudgets->budget = m_MemProps.memoryHeaps[heapIndex].size * 8 / 10; // 80% heuristics.
  13325. }
  13326. }
  13327. }
  13328. void VmaAllocator_T::GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo)
  13329. {
  13330. pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex();
  13331. pAllocationInfo->deviceMemory = hAllocation->GetMemory();
  13332. pAllocationInfo->offset = hAllocation->GetOffset();
  13333. pAllocationInfo->size = hAllocation->GetSize();
  13334. pAllocationInfo->pMappedData = hAllocation->GetMappedData();
  13335. pAllocationInfo->pUserData = hAllocation->GetUserData();
  13336. pAllocationInfo->pName = hAllocation->GetName();
  13337. }
  13338. VkResult VmaAllocator_T::CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool)
  13339. {
  13340. VMA_DEBUG_LOG_FORMAT(" CreatePool: MemoryTypeIndex=%u, flags=%u", pCreateInfo->memoryTypeIndex, pCreateInfo->flags);
  13341. VmaPoolCreateInfo newCreateInfo = *pCreateInfo;
  13342. // Protection against uninitialized new structure member. If garbage data are left there, this pointer dereference would crash.
  13343. if(pCreateInfo->pMemoryAllocateNext)
  13344. {
  13345. VMA_ASSERT(((const VkBaseInStructure*)pCreateInfo->pMemoryAllocateNext)->sType != 0);
  13346. }
  13347. if(newCreateInfo.maxBlockCount == 0)
  13348. {
  13349. newCreateInfo.maxBlockCount = SIZE_MAX;
  13350. }
  13351. if(newCreateInfo.minBlockCount > newCreateInfo.maxBlockCount)
  13352. {
  13353. return VK_ERROR_INITIALIZATION_FAILED;
  13354. }
  13355. // Memory type index out of range or forbidden.
  13356. if(pCreateInfo->memoryTypeIndex >= GetMemoryTypeCount() ||
  13357. ((1u << pCreateInfo->memoryTypeIndex) & m_GlobalMemoryTypeBits) == 0)
  13358. {
  13359. return VK_ERROR_FEATURE_NOT_PRESENT;
  13360. }
  13361. if(newCreateInfo.minAllocationAlignment > 0)
  13362. {
  13363. VMA_ASSERT(VmaIsPow2(newCreateInfo.minAllocationAlignment));
  13364. }
  13365. const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(newCreateInfo.memoryTypeIndex);
  13366. *pPool = vma_new(this, VmaPool_T)(this, newCreateInfo, preferredBlockSize);
  13367. VkResult res = (*pPool)->m_BlockVector.CreateMinBlocks();
  13368. if(res != VK_SUCCESS)
  13369. {
  13370. vma_delete(this, *pPool);
  13371. *pPool = VMA_NULL;
  13372. return res;
  13373. }
  13374. // Add to m_Pools.
  13375. {
  13376. VmaMutexLockWrite lock(m_PoolsMutex, m_UseMutex);
  13377. (*pPool)->SetId(m_NextPoolId++);
  13378. m_Pools.PushBack(*pPool);
  13379. }
  13380. return VK_SUCCESS;
  13381. }
  13382. void VmaAllocator_T::DestroyPool(VmaPool pool)
  13383. {
  13384. // Remove from m_Pools.
  13385. {
  13386. VmaMutexLockWrite lock(m_PoolsMutex, m_UseMutex);
  13387. m_Pools.Remove(pool);
  13388. }
  13389. vma_delete(this, pool);
  13390. }
  13391. void VmaAllocator_T::GetPoolStatistics(VmaPool pool, VmaStatistics* pPoolStats)
  13392. {
  13393. VmaClearStatistics(*pPoolStats);
  13394. pool->m_BlockVector.AddStatistics(*pPoolStats);
  13395. pool->m_DedicatedAllocations.AddStatistics(*pPoolStats);
  13396. }
  13397. void VmaAllocator_T::CalculatePoolStatistics(VmaPool pool, VmaDetailedStatistics* pPoolStats)
  13398. {
  13399. VmaClearDetailedStatistics(*pPoolStats);
  13400. pool->m_BlockVector.AddDetailedStatistics(*pPoolStats);
  13401. pool->m_DedicatedAllocations.AddDetailedStatistics(*pPoolStats);
  13402. }
  13403. void VmaAllocator_T::SetCurrentFrameIndex(uint32_t frameIndex)
  13404. {
  13405. m_CurrentFrameIndex.store(frameIndex);
  13406. #if VMA_MEMORY_BUDGET
  13407. if(m_UseExtMemoryBudget)
  13408. {
  13409. UpdateVulkanBudget();
  13410. }
  13411. #endif // #if VMA_MEMORY_BUDGET
  13412. }
  13413. VkResult VmaAllocator_T::CheckPoolCorruption(VmaPool hPool)
  13414. {
  13415. return hPool->m_BlockVector.CheckCorruption();
  13416. }
  13417. VkResult VmaAllocator_T::CheckCorruption(uint32_t memoryTypeBits)
  13418. {
  13419. VkResult finalRes = VK_ERROR_FEATURE_NOT_PRESENT;
  13420. // Process default pools.
  13421. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13422. {
  13423. VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex];
  13424. if(pBlockVector != VMA_NULL)
  13425. {
  13426. VkResult localRes = pBlockVector->CheckCorruption();
  13427. switch(localRes)
  13428. {
  13429. case VK_ERROR_FEATURE_NOT_PRESENT:
  13430. break;
  13431. case VK_SUCCESS:
  13432. finalRes = VK_SUCCESS;
  13433. break;
  13434. default:
  13435. return localRes;
  13436. }
  13437. }
  13438. }
  13439. // Process custom pools.
  13440. {
  13441. VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex);
  13442. for(VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool))
  13443. {
  13444. if(((1u << pool->m_BlockVector.GetMemoryTypeIndex()) & memoryTypeBits) != 0)
  13445. {
  13446. VkResult localRes = pool->m_BlockVector.CheckCorruption();
  13447. switch(localRes)
  13448. {
  13449. case VK_ERROR_FEATURE_NOT_PRESENT:
  13450. break;
  13451. case VK_SUCCESS:
  13452. finalRes = VK_SUCCESS;
  13453. break;
  13454. default:
  13455. return localRes;
  13456. }
  13457. }
  13458. }
  13459. }
  13460. return finalRes;
  13461. }
  13462. VkResult VmaAllocator_T::AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory)
  13463. {
  13464. AtomicTransactionalIncrement<VMA_ATOMIC_UINT32> deviceMemoryCountIncrement;
  13465. const uint64_t prevDeviceMemoryCount = deviceMemoryCountIncrement.Increment(&m_DeviceMemoryCount);
  13466. #if VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT
  13467. if(prevDeviceMemoryCount >= m_PhysicalDeviceProperties.limits.maxMemoryAllocationCount)
  13468. {
  13469. return VK_ERROR_TOO_MANY_OBJECTS;
  13470. }
  13471. #endif
  13472. const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(pAllocateInfo->memoryTypeIndex);
  13473. // HeapSizeLimit is in effect for this heap.
  13474. if((m_HeapSizeLimitMask & (1u << heapIndex)) != 0)
  13475. {
  13476. const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size;
  13477. VkDeviceSize blockBytes = m_Budget.m_BlockBytes[heapIndex];
  13478. for(;;)
  13479. {
  13480. const VkDeviceSize blockBytesAfterAllocation = blockBytes + pAllocateInfo->allocationSize;
  13481. if(blockBytesAfterAllocation > heapSize)
  13482. {
  13483. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  13484. }
  13485. if(m_Budget.m_BlockBytes[heapIndex].compare_exchange_strong(blockBytes, blockBytesAfterAllocation))
  13486. {
  13487. break;
  13488. }
  13489. }
  13490. }
  13491. else
  13492. {
  13493. m_Budget.m_BlockBytes[heapIndex] += pAllocateInfo->allocationSize;
  13494. }
  13495. ++m_Budget.m_BlockCount[heapIndex];
  13496. // VULKAN CALL vkAllocateMemory.
  13497. VkResult res = (*m_VulkanFunctions.vkAllocateMemory)(m_hDevice, pAllocateInfo, GetAllocationCallbacks(), pMemory);
  13498. if(res == VK_SUCCESS)
  13499. {
  13500. #if VMA_MEMORY_BUDGET
  13501. ++m_Budget.m_OperationsSinceBudgetFetch;
  13502. #endif
  13503. // Informative callback.
  13504. if(m_DeviceMemoryCallbacks.pfnAllocate != VMA_NULL)
  13505. {
  13506. (*m_DeviceMemoryCallbacks.pfnAllocate)(this, pAllocateInfo->memoryTypeIndex, *pMemory, pAllocateInfo->allocationSize, m_DeviceMemoryCallbacks.pUserData);
  13507. }
  13508. deviceMemoryCountIncrement.Commit();
  13509. }
  13510. else
  13511. {
  13512. --m_Budget.m_BlockCount[heapIndex];
  13513. m_Budget.m_BlockBytes[heapIndex] -= pAllocateInfo->allocationSize;
  13514. }
  13515. return res;
  13516. }
  13517. void VmaAllocator_T::FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory)
  13518. {
  13519. // Informative callback.
  13520. if(m_DeviceMemoryCallbacks.pfnFree != VMA_NULL)
  13521. {
  13522. (*m_DeviceMemoryCallbacks.pfnFree)(this, memoryType, hMemory, size, m_DeviceMemoryCallbacks.pUserData);
  13523. }
  13524. // VULKAN CALL vkFreeMemory.
  13525. (*m_VulkanFunctions.vkFreeMemory)(m_hDevice, hMemory, GetAllocationCallbacks());
  13526. const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memoryType);
  13527. --m_Budget.m_BlockCount[heapIndex];
  13528. m_Budget.m_BlockBytes[heapIndex] -= size;
  13529. --m_DeviceMemoryCount;
  13530. }
  13531. VkResult VmaAllocator_T::BindVulkanBuffer(
  13532. VkDeviceMemory memory,
  13533. VkDeviceSize memoryOffset,
  13534. VkBuffer buffer,
  13535. const void* pNext)
  13536. {
  13537. if(pNext != VMA_NULL)
  13538. {
  13539. #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2
  13540. if((m_UseKhrBindMemory2 || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) &&
  13541. m_VulkanFunctions.vkBindBufferMemory2KHR != VMA_NULL)
  13542. {
  13543. VkBindBufferMemoryInfoKHR bindBufferMemoryInfo = { VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR };
  13544. bindBufferMemoryInfo.pNext = pNext;
  13545. bindBufferMemoryInfo.buffer = buffer;
  13546. bindBufferMemoryInfo.memory = memory;
  13547. bindBufferMemoryInfo.memoryOffset = memoryOffset;
  13548. return (*m_VulkanFunctions.vkBindBufferMemory2KHR)(m_hDevice, 1, &bindBufferMemoryInfo);
  13549. }
  13550. else
  13551. #endif // #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2
  13552. {
  13553. return VK_ERROR_EXTENSION_NOT_PRESENT;
  13554. }
  13555. }
  13556. else
  13557. {
  13558. return (*m_VulkanFunctions.vkBindBufferMemory)(m_hDevice, buffer, memory, memoryOffset);
  13559. }
  13560. }
  13561. VkResult VmaAllocator_T::BindVulkanImage(
  13562. VkDeviceMemory memory,
  13563. VkDeviceSize memoryOffset,
  13564. VkImage image,
  13565. const void* pNext)
  13566. {
  13567. if(pNext != VMA_NULL)
  13568. {
  13569. #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2
  13570. if((m_UseKhrBindMemory2 || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) &&
  13571. m_VulkanFunctions.vkBindImageMemory2KHR != VMA_NULL)
  13572. {
  13573. VkBindImageMemoryInfoKHR bindBufferMemoryInfo = { VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO_KHR };
  13574. bindBufferMemoryInfo.pNext = pNext;
  13575. bindBufferMemoryInfo.image = image;
  13576. bindBufferMemoryInfo.memory = memory;
  13577. bindBufferMemoryInfo.memoryOffset = memoryOffset;
  13578. return (*m_VulkanFunctions.vkBindImageMemory2KHR)(m_hDevice, 1, &bindBufferMemoryInfo);
  13579. }
  13580. else
  13581. #endif // #if VMA_BIND_MEMORY2
  13582. {
  13583. return VK_ERROR_EXTENSION_NOT_PRESENT;
  13584. }
  13585. }
  13586. else
  13587. {
  13588. return (*m_VulkanFunctions.vkBindImageMemory)(m_hDevice, image, memory, memoryOffset);
  13589. }
  13590. }
  13591. VkResult VmaAllocator_T::Map(VmaAllocation hAllocation, void** ppData)
  13592. {
  13593. switch(hAllocation->GetType())
  13594. {
  13595. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13596. {
  13597. VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
  13598. char *pBytes = VMA_NULL;
  13599. VkResult res = pBlock->Map(this, 1, (void**)&pBytes);
  13600. if(res == VK_SUCCESS)
  13601. {
  13602. *ppData = pBytes + (ptrdiff_t)hAllocation->GetOffset();
  13603. hAllocation->BlockAllocMap();
  13604. }
  13605. return res;
  13606. }
  13607. VMA_FALLTHROUGH; // Fallthrough
  13608. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13609. return hAllocation->DedicatedAllocMap(this, ppData);
  13610. default:
  13611. VMA_ASSERT(0);
  13612. return VK_ERROR_MEMORY_MAP_FAILED;
  13613. }
  13614. }
  13615. void VmaAllocator_T::Unmap(VmaAllocation hAllocation)
  13616. {
  13617. switch(hAllocation->GetType())
  13618. {
  13619. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13620. {
  13621. VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
  13622. hAllocation->BlockAllocUnmap();
  13623. pBlock->Unmap(this, 1);
  13624. }
  13625. break;
  13626. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13627. hAllocation->DedicatedAllocUnmap(this);
  13628. break;
  13629. default:
  13630. VMA_ASSERT(0);
  13631. }
  13632. }
  13633. VkResult VmaAllocator_T::BindBufferMemory(
  13634. VmaAllocation hAllocation,
  13635. VkDeviceSize allocationLocalOffset,
  13636. VkBuffer hBuffer,
  13637. const void* pNext)
  13638. {
  13639. VkResult res = VK_ERROR_UNKNOWN;
  13640. switch(hAllocation->GetType())
  13641. {
  13642. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13643. res = BindVulkanBuffer(hAllocation->GetMemory(), allocationLocalOffset, hBuffer, pNext);
  13644. break;
  13645. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13646. {
  13647. VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
  13648. VMA_ASSERT(pBlock && "Binding buffer to allocation that doesn't belong to any block.");
  13649. res = pBlock->BindBufferMemory(this, hAllocation, allocationLocalOffset, hBuffer, pNext);
  13650. break;
  13651. }
  13652. default:
  13653. VMA_ASSERT(0);
  13654. }
  13655. return res;
  13656. }
  13657. VkResult VmaAllocator_T::BindImageMemory(
  13658. VmaAllocation hAllocation,
  13659. VkDeviceSize allocationLocalOffset,
  13660. VkImage hImage,
  13661. const void* pNext)
  13662. {
  13663. VkResult res = VK_ERROR_UNKNOWN;
  13664. switch(hAllocation->GetType())
  13665. {
  13666. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13667. res = BindVulkanImage(hAllocation->GetMemory(), allocationLocalOffset, hImage, pNext);
  13668. break;
  13669. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13670. {
  13671. VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock();
  13672. VMA_ASSERT(pBlock && "Binding image to allocation that doesn't belong to any block.");
  13673. res = pBlock->BindImageMemory(this, hAllocation, allocationLocalOffset, hImage, pNext);
  13674. break;
  13675. }
  13676. default:
  13677. VMA_ASSERT(0);
  13678. }
  13679. return res;
  13680. }
  13681. VkResult VmaAllocator_T::FlushOrInvalidateAllocation(
  13682. VmaAllocation hAllocation,
  13683. VkDeviceSize offset, VkDeviceSize size,
  13684. VMA_CACHE_OPERATION op)
  13685. {
  13686. VkResult res = VK_SUCCESS;
  13687. VkMappedMemoryRange memRange = {};
  13688. if(GetFlushOrInvalidateRange(hAllocation, offset, size, memRange))
  13689. {
  13690. switch(op)
  13691. {
  13692. case VMA_CACHE_FLUSH:
  13693. res = (*GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hDevice, 1, &memRange);
  13694. break;
  13695. case VMA_CACHE_INVALIDATE:
  13696. res = (*GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hDevice, 1, &memRange);
  13697. break;
  13698. default:
  13699. VMA_ASSERT(0);
  13700. }
  13701. }
  13702. // else: Just ignore this call.
  13703. return res;
  13704. }
  13705. VkResult VmaAllocator_T::FlushOrInvalidateAllocations(
  13706. uint32_t allocationCount,
  13707. const VmaAllocation* allocations,
  13708. const VkDeviceSize* offsets, const VkDeviceSize* sizes,
  13709. VMA_CACHE_OPERATION op)
  13710. {
  13711. typedef VmaStlAllocator<VkMappedMemoryRange> RangeAllocator;
  13712. typedef VmaSmallVector<VkMappedMemoryRange, RangeAllocator, 16> RangeVector;
  13713. RangeVector ranges = RangeVector(RangeAllocator(GetAllocationCallbacks()));
  13714. for(uint32_t allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
  13715. {
  13716. const VmaAllocation alloc = allocations[allocIndex];
  13717. const VkDeviceSize offset = offsets != VMA_NULL ? offsets[allocIndex] : 0;
  13718. const VkDeviceSize size = sizes != VMA_NULL ? sizes[allocIndex] : VK_WHOLE_SIZE;
  13719. VkMappedMemoryRange newRange;
  13720. if(GetFlushOrInvalidateRange(alloc, offset, size, newRange))
  13721. {
  13722. ranges.push_back(newRange);
  13723. }
  13724. }
  13725. VkResult res = VK_SUCCESS;
  13726. if(!ranges.empty())
  13727. {
  13728. switch(op)
  13729. {
  13730. case VMA_CACHE_FLUSH:
  13731. res = (*GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hDevice, (uint32_t)ranges.size(), ranges.data());
  13732. break;
  13733. case VMA_CACHE_INVALIDATE:
  13734. res = (*GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hDevice, (uint32_t)ranges.size(), ranges.data());
  13735. break;
  13736. default:
  13737. VMA_ASSERT(0);
  13738. }
  13739. }
  13740. // else: Just ignore this call.
  13741. return res;
  13742. }
  13743. void VmaAllocator_T::FreeDedicatedMemory(const VmaAllocation allocation)
  13744. {
  13745. VMA_ASSERT(allocation && allocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
  13746. const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
  13747. VmaPool parentPool = allocation->GetParentPool();
  13748. if(parentPool == VK_NULL_HANDLE)
  13749. {
  13750. // Default pool
  13751. m_DedicatedAllocations[memTypeIndex].Unregister(allocation);
  13752. }
  13753. else
  13754. {
  13755. // Custom pool
  13756. parentPool->m_DedicatedAllocations.Unregister(allocation);
  13757. }
  13758. VkDeviceMemory hMemory = allocation->GetMemory();
  13759. /*
  13760. There is no need to call this, because Vulkan spec allows to skip vkUnmapMemory
  13761. before vkFreeMemory.
  13762. if(allocation->GetMappedData() != VMA_NULL)
  13763. {
  13764. (*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory);
  13765. }
  13766. */
  13767. FreeVulkanMemory(memTypeIndex, allocation->GetSize(), hMemory);
  13768. m_Budget.RemoveAllocation(MemoryTypeIndexToHeapIndex(allocation->GetMemoryTypeIndex()), allocation->GetSize());
  13769. m_AllocationObjectAllocator.Free(allocation);
  13770. VMA_DEBUG_LOG_FORMAT(" Freed DedicatedMemory MemoryTypeIndex=%u", memTypeIndex);
  13771. }
  13772. uint32_t VmaAllocator_T::CalculateGpuDefragmentationMemoryTypeBits() const
  13773. {
  13774. VkBufferCreateInfo dummyBufCreateInfo;
  13775. VmaFillGpuDefragmentationBufferCreateInfo(dummyBufCreateInfo);
  13776. uint32_t memoryTypeBits = 0;
  13777. // Create buffer.
  13778. VkBuffer buf = VK_NULL_HANDLE;
  13779. VkResult res = (*GetVulkanFunctions().vkCreateBuffer)(
  13780. m_hDevice, &dummyBufCreateInfo, GetAllocationCallbacks(), &buf);
  13781. if(res == VK_SUCCESS)
  13782. {
  13783. // Query for supported memory types.
  13784. VkMemoryRequirements memReq;
  13785. (*GetVulkanFunctions().vkGetBufferMemoryRequirements)(m_hDevice, buf, &memReq);
  13786. memoryTypeBits = memReq.memoryTypeBits;
  13787. // Destroy buffer.
  13788. (*GetVulkanFunctions().vkDestroyBuffer)(m_hDevice, buf, GetAllocationCallbacks());
  13789. }
  13790. return memoryTypeBits;
  13791. }
  13792. uint32_t VmaAllocator_T::CalculateGlobalMemoryTypeBits() const
  13793. {
  13794. // Make sure memory information is already fetched.
  13795. VMA_ASSERT(GetMemoryTypeCount() > 0);
  13796. uint32_t memoryTypeBits = UINT32_MAX;
  13797. if(!m_UseAmdDeviceCoherentMemory)
  13798. {
  13799. // Exclude memory types that have VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD.
  13800. for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13801. {
  13802. if((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY) != 0)
  13803. {
  13804. memoryTypeBits &= ~(1u << memTypeIndex);
  13805. }
  13806. }
  13807. }
  13808. return memoryTypeBits;
  13809. }
  13810. bool VmaAllocator_T::GetFlushOrInvalidateRange(
  13811. VmaAllocation allocation,
  13812. VkDeviceSize offset, VkDeviceSize size,
  13813. VkMappedMemoryRange& outRange) const
  13814. {
  13815. const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
  13816. if(size > 0 && IsMemoryTypeNonCoherent(memTypeIndex))
  13817. {
  13818. const VkDeviceSize nonCoherentAtomSize = m_PhysicalDeviceProperties.limits.nonCoherentAtomSize;
  13819. const VkDeviceSize allocationSize = allocation->GetSize();
  13820. VMA_ASSERT(offset <= allocationSize);
  13821. outRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
  13822. outRange.pNext = VMA_NULL;
  13823. outRange.memory = allocation->GetMemory();
  13824. switch(allocation->GetType())
  13825. {
  13826. case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
  13827. outRange.offset = VmaAlignDown(offset, nonCoherentAtomSize);
  13828. if(size == VK_WHOLE_SIZE)
  13829. {
  13830. outRange.size = allocationSize - outRange.offset;
  13831. }
  13832. else
  13833. {
  13834. VMA_ASSERT(offset + size <= allocationSize);
  13835. outRange.size = VMA_MIN(
  13836. VmaAlignUp(size + (offset - outRange.offset), nonCoherentAtomSize),
  13837. allocationSize - outRange.offset);
  13838. }
  13839. break;
  13840. case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
  13841. {
  13842. // 1. Still within this allocation.
  13843. outRange.offset = VmaAlignDown(offset, nonCoherentAtomSize);
  13844. if(size == VK_WHOLE_SIZE)
  13845. {
  13846. size = allocationSize - offset;
  13847. }
  13848. else
  13849. {
  13850. VMA_ASSERT(offset + size <= allocationSize);
  13851. }
  13852. outRange.size = VmaAlignUp(size + (offset - outRange.offset), nonCoherentAtomSize);
  13853. // 2. Adjust to whole block.
  13854. const VkDeviceSize allocationOffset = allocation->GetOffset();
  13855. VMA_ASSERT(allocationOffset % nonCoherentAtomSize == 0);
  13856. const VkDeviceSize blockSize = allocation->GetBlock()->m_pMetadata->GetSize();
  13857. outRange.offset += allocationOffset;
  13858. outRange.size = VMA_MIN(outRange.size, blockSize - outRange.offset);
  13859. break;
  13860. }
  13861. default:
  13862. VMA_ASSERT(0);
  13863. }
  13864. return true;
  13865. }
  13866. return false;
  13867. }
  13868. #if VMA_MEMORY_BUDGET
  13869. void VmaAllocator_T::UpdateVulkanBudget()
  13870. {
  13871. VMA_ASSERT(m_UseExtMemoryBudget);
  13872. VkPhysicalDeviceMemoryProperties2KHR memProps = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2_KHR };
  13873. VkPhysicalDeviceMemoryBudgetPropertiesEXT budgetProps = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT };
  13874. VmaPnextChainPushFront(&memProps, &budgetProps);
  13875. GetVulkanFunctions().vkGetPhysicalDeviceMemoryProperties2KHR(m_PhysicalDevice, &memProps);
  13876. {
  13877. VmaMutexLockWrite lockWrite(m_Budget.m_BudgetMutex, m_UseMutex);
  13878. for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex)
  13879. {
  13880. m_Budget.m_VulkanUsage[heapIndex] = budgetProps.heapUsage[heapIndex];
  13881. m_Budget.m_VulkanBudget[heapIndex] = budgetProps.heapBudget[heapIndex];
  13882. m_Budget.m_BlockBytesAtBudgetFetch[heapIndex] = m_Budget.m_BlockBytes[heapIndex].load();
  13883. // Some bugged drivers return the budget incorrectly, e.g. 0 or much bigger than heap size.
  13884. if(m_Budget.m_VulkanBudget[heapIndex] == 0)
  13885. {
  13886. m_Budget.m_VulkanBudget[heapIndex] = m_MemProps.memoryHeaps[heapIndex].size * 8 / 10; // 80% heuristics.
  13887. }
  13888. else if(m_Budget.m_VulkanBudget[heapIndex] > m_MemProps.memoryHeaps[heapIndex].size)
  13889. {
  13890. m_Budget.m_VulkanBudget[heapIndex] = m_MemProps.memoryHeaps[heapIndex].size;
  13891. }
  13892. if(m_Budget.m_VulkanUsage[heapIndex] == 0 && m_Budget.m_BlockBytesAtBudgetFetch[heapIndex] > 0)
  13893. {
  13894. m_Budget.m_VulkanUsage[heapIndex] = m_Budget.m_BlockBytesAtBudgetFetch[heapIndex];
  13895. }
  13896. }
  13897. m_Budget.m_OperationsSinceBudgetFetch = 0;
  13898. }
  13899. }
  13900. #endif // VMA_MEMORY_BUDGET
  13901. void VmaAllocator_T::FillAllocation(const VmaAllocation hAllocation, uint8_t pattern)
  13902. {
  13903. if(VMA_DEBUG_INITIALIZE_ALLOCATIONS &&
  13904. hAllocation->IsMappingAllowed() &&
  13905. (m_MemProps.memoryTypes[hAllocation->GetMemoryTypeIndex()].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
  13906. {
  13907. void* pData = VMA_NULL;
  13908. VkResult res = Map(hAllocation, &pData);
  13909. if(res == VK_SUCCESS)
  13910. {
  13911. memset(pData, (int)pattern, (size_t)hAllocation->GetSize());
  13912. FlushOrInvalidateAllocation(hAllocation, 0, VK_WHOLE_SIZE, VMA_CACHE_FLUSH);
  13913. Unmap(hAllocation);
  13914. }
  13915. else
  13916. {
  13917. VMA_ASSERT(0 && "VMA_DEBUG_INITIALIZE_ALLOCATIONS is enabled, but couldn't map memory to fill allocation.");
  13918. }
  13919. }
  13920. }
  13921. uint32_t VmaAllocator_T::GetGpuDefragmentationMemoryTypeBits()
  13922. {
  13923. uint32_t memoryTypeBits = m_GpuDefragmentationMemoryTypeBits.load();
  13924. if(memoryTypeBits == UINT32_MAX)
  13925. {
  13926. memoryTypeBits = CalculateGpuDefragmentationMemoryTypeBits();
  13927. m_GpuDefragmentationMemoryTypeBits.store(memoryTypeBits);
  13928. }
  13929. return memoryTypeBits;
  13930. }
  13931. #if VMA_STATS_STRING_ENABLED
  13932. void VmaAllocator_T::PrintDetailedMap(VmaJsonWriter& json)
  13933. {
  13934. json.WriteString("DefaultPools");
  13935. json.BeginObject();
  13936. {
  13937. for (uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13938. {
  13939. VmaBlockVector* pBlockVector = m_pBlockVectors[memTypeIndex];
  13940. VmaDedicatedAllocationList& dedicatedAllocList = m_DedicatedAllocations[memTypeIndex];
  13941. if (pBlockVector != VMA_NULL)
  13942. {
  13943. json.BeginString("Type ");
  13944. json.ContinueString(memTypeIndex);
  13945. json.EndString();
  13946. json.BeginObject();
  13947. {
  13948. json.WriteString("PreferredBlockSize");
  13949. json.WriteNumber(pBlockVector->GetPreferredBlockSize());
  13950. json.WriteString("Blocks");
  13951. pBlockVector->PrintDetailedMap(json);
  13952. json.WriteString("DedicatedAllocations");
  13953. dedicatedAllocList.BuildStatsString(json);
  13954. }
  13955. json.EndObject();
  13956. }
  13957. }
  13958. }
  13959. json.EndObject();
  13960. json.WriteString("CustomPools");
  13961. json.BeginObject();
  13962. {
  13963. VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex);
  13964. if (!m_Pools.IsEmpty())
  13965. {
  13966. for (uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
  13967. {
  13968. bool displayType = true;
  13969. size_t index = 0;
  13970. for (VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool))
  13971. {
  13972. VmaBlockVector& blockVector = pool->m_BlockVector;
  13973. if (blockVector.GetMemoryTypeIndex() == memTypeIndex)
  13974. {
  13975. if (displayType)
  13976. {
  13977. json.BeginString("Type ");
  13978. json.ContinueString(memTypeIndex);
  13979. json.EndString();
  13980. json.BeginArray();
  13981. displayType = false;
  13982. }
  13983. json.BeginObject();
  13984. {
  13985. json.WriteString("Name");
  13986. json.BeginString();
  13987. json.ContinueString((uint64_t)index++);
  13988. if (pool->GetName())
  13989. {
  13990. json.ContinueString(" - ");
  13991. json.ContinueString(pool->GetName());
  13992. }
  13993. json.EndString();
  13994. json.WriteString("PreferredBlockSize");
  13995. json.WriteNumber(blockVector.GetPreferredBlockSize());
  13996. json.WriteString("Blocks");
  13997. blockVector.PrintDetailedMap(json);
  13998. json.WriteString("DedicatedAllocations");
  13999. pool->m_DedicatedAllocations.BuildStatsString(json);
  14000. }
  14001. json.EndObject();
  14002. }
  14003. }
  14004. if (!displayType)
  14005. json.EndArray();
  14006. }
  14007. }
  14008. }
  14009. json.EndObject();
  14010. }
  14011. #endif // VMA_STATS_STRING_ENABLED
  14012. #endif // _VMA_ALLOCATOR_T_FUNCTIONS
  14013. #ifndef _VMA_PUBLIC_INTERFACE
  14014. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAllocator(
  14015. const VmaAllocatorCreateInfo* pCreateInfo,
  14016. VmaAllocator* pAllocator)
  14017. {
  14018. VMA_ASSERT(pCreateInfo && pAllocator);
  14019. VMA_ASSERT(pCreateInfo->vulkanApiVersion == 0 ||
  14020. (VK_VERSION_MAJOR(pCreateInfo->vulkanApiVersion) == 1 && VK_VERSION_MINOR(pCreateInfo->vulkanApiVersion) <= 3));
  14021. VMA_DEBUG_LOG("vmaCreateAllocator");
  14022. *pAllocator = vma_new(pCreateInfo->pAllocationCallbacks, VmaAllocator_T)(pCreateInfo);
  14023. VkResult result = (*pAllocator)->Init(pCreateInfo);
  14024. if(result < 0)
  14025. {
  14026. vma_delete(pCreateInfo->pAllocationCallbacks, *pAllocator);
  14027. *pAllocator = VK_NULL_HANDLE;
  14028. }
  14029. return result;
  14030. }
  14031. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyAllocator(
  14032. VmaAllocator allocator)
  14033. {
  14034. if(allocator != VK_NULL_HANDLE)
  14035. {
  14036. VMA_DEBUG_LOG("vmaDestroyAllocator");
  14037. VkAllocationCallbacks allocationCallbacks = allocator->m_AllocationCallbacks; // Have to copy the callbacks when destroying.
  14038. vma_delete(&allocationCallbacks, allocator);
  14039. }
  14040. }
  14041. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocatorInfo(VmaAllocator allocator, VmaAllocatorInfo* pAllocatorInfo)
  14042. {
  14043. VMA_ASSERT(allocator && pAllocatorInfo);
  14044. pAllocatorInfo->instance = allocator->m_hInstance;
  14045. pAllocatorInfo->physicalDevice = allocator->GetPhysicalDevice();
  14046. pAllocatorInfo->device = allocator->m_hDevice;
  14047. }
  14048. VMA_CALL_PRE void VMA_CALL_POST vmaGetPhysicalDeviceProperties(
  14049. VmaAllocator allocator,
  14050. const VkPhysicalDeviceProperties **ppPhysicalDeviceProperties)
  14051. {
  14052. VMA_ASSERT(allocator && ppPhysicalDeviceProperties);
  14053. *ppPhysicalDeviceProperties = &allocator->m_PhysicalDeviceProperties;
  14054. }
  14055. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryProperties(
  14056. VmaAllocator allocator,
  14057. const VkPhysicalDeviceMemoryProperties** ppPhysicalDeviceMemoryProperties)
  14058. {
  14059. VMA_ASSERT(allocator && ppPhysicalDeviceMemoryProperties);
  14060. *ppPhysicalDeviceMemoryProperties = &allocator->m_MemProps;
  14061. }
  14062. VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties(
  14063. VmaAllocator allocator,
  14064. uint32_t memoryTypeIndex,
  14065. VkMemoryPropertyFlags* pFlags)
  14066. {
  14067. VMA_ASSERT(allocator && pFlags);
  14068. VMA_ASSERT(memoryTypeIndex < allocator->GetMemoryTypeCount());
  14069. *pFlags = allocator->m_MemProps.memoryTypes[memoryTypeIndex].propertyFlags;
  14070. }
  14071. VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex(
  14072. VmaAllocator allocator,
  14073. uint32_t frameIndex)
  14074. {
  14075. VMA_ASSERT(allocator);
  14076. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14077. allocator->SetCurrentFrameIndex(frameIndex);
  14078. }
  14079. VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStatistics(
  14080. VmaAllocator allocator,
  14081. VmaTotalStatistics* pStats)
  14082. {
  14083. VMA_ASSERT(allocator && pStats);
  14084. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14085. allocator->CalculateStatistics(pStats);
  14086. }
  14087. VMA_CALL_PRE void VMA_CALL_POST vmaGetHeapBudgets(
  14088. VmaAllocator allocator,
  14089. VmaBudget* pBudgets)
  14090. {
  14091. VMA_ASSERT(allocator && pBudgets);
  14092. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14093. allocator->GetHeapBudgets(pBudgets, 0, allocator->GetMemoryHeapCount());
  14094. }
  14095. #if VMA_STATS_STRING_ENABLED
  14096. VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString(
  14097. VmaAllocator allocator,
  14098. char** ppStatsString,
  14099. VkBool32 detailedMap)
  14100. {
  14101. VMA_ASSERT(allocator && ppStatsString);
  14102. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14103. VmaStringBuilder sb(allocator->GetAllocationCallbacks());
  14104. {
  14105. VmaBudget budgets[VK_MAX_MEMORY_HEAPS];
  14106. allocator->GetHeapBudgets(budgets, 0, allocator->GetMemoryHeapCount());
  14107. VmaTotalStatistics stats;
  14108. allocator->CalculateStatistics(&stats);
  14109. VmaJsonWriter json(allocator->GetAllocationCallbacks(), sb);
  14110. json.BeginObject();
  14111. {
  14112. json.WriteString("General");
  14113. json.BeginObject();
  14114. {
  14115. const VkPhysicalDeviceProperties& deviceProperties = allocator->m_PhysicalDeviceProperties;
  14116. const VkPhysicalDeviceMemoryProperties& memoryProperties = allocator->m_MemProps;
  14117. json.WriteString("API");
  14118. json.WriteString("Vulkan");
  14119. json.WriteString("apiVersion");
  14120. json.BeginString();
  14121. json.ContinueString(VK_VERSION_MAJOR(deviceProperties.apiVersion));
  14122. json.ContinueString(".");
  14123. json.ContinueString(VK_VERSION_MINOR(deviceProperties.apiVersion));
  14124. json.ContinueString(".");
  14125. json.ContinueString(VK_VERSION_PATCH(deviceProperties.apiVersion));
  14126. json.EndString();
  14127. json.WriteString("GPU");
  14128. json.WriteString(deviceProperties.deviceName);
  14129. json.WriteString("deviceType");
  14130. json.WriteNumber(static_cast<uint32_t>(deviceProperties.deviceType));
  14131. json.WriteString("maxMemoryAllocationCount");
  14132. json.WriteNumber(deviceProperties.limits.maxMemoryAllocationCount);
  14133. json.WriteString("bufferImageGranularity");
  14134. json.WriteNumber(deviceProperties.limits.bufferImageGranularity);
  14135. json.WriteString("nonCoherentAtomSize");
  14136. json.WriteNumber(deviceProperties.limits.nonCoherentAtomSize);
  14137. json.WriteString("memoryHeapCount");
  14138. json.WriteNumber(memoryProperties.memoryHeapCount);
  14139. json.WriteString("memoryTypeCount");
  14140. json.WriteNumber(memoryProperties.memoryTypeCount);
  14141. }
  14142. json.EndObject();
  14143. }
  14144. {
  14145. json.WriteString("Total");
  14146. VmaPrintDetailedStatistics(json, stats.total);
  14147. }
  14148. {
  14149. json.WriteString("MemoryInfo");
  14150. json.BeginObject();
  14151. {
  14152. for (uint32_t heapIndex = 0; heapIndex < allocator->GetMemoryHeapCount(); ++heapIndex)
  14153. {
  14154. json.BeginString("Heap ");
  14155. json.ContinueString(heapIndex);
  14156. json.EndString();
  14157. json.BeginObject();
  14158. {
  14159. const VkMemoryHeap& heapInfo = allocator->m_MemProps.memoryHeaps[heapIndex];
  14160. json.WriteString("Flags");
  14161. json.BeginArray(true);
  14162. {
  14163. if (heapInfo.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT)
  14164. json.WriteString("DEVICE_LOCAL");
  14165. #if VMA_VULKAN_VERSION >= 1001000
  14166. if (heapInfo.flags & VK_MEMORY_HEAP_MULTI_INSTANCE_BIT)
  14167. json.WriteString("MULTI_INSTANCE");
  14168. #endif
  14169. VkMemoryHeapFlags flags = heapInfo.flags &
  14170. ~(VK_MEMORY_HEAP_DEVICE_LOCAL_BIT
  14171. #if VMA_VULKAN_VERSION >= 1001000
  14172. | VK_MEMORY_HEAP_MULTI_INSTANCE_BIT
  14173. #endif
  14174. );
  14175. if (flags != 0)
  14176. json.WriteNumber(flags);
  14177. }
  14178. json.EndArray();
  14179. json.WriteString("Size");
  14180. json.WriteNumber(heapInfo.size);
  14181. json.WriteString("Budget");
  14182. json.BeginObject();
  14183. {
  14184. json.WriteString("BudgetBytes");
  14185. json.WriteNumber(budgets[heapIndex].budget);
  14186. json.WriteString("UsageBytes");
  14187. json.WriteNumber(budgets[heapIndex].usage);
  14188. }
  14189. json.EndObject();
  14190. json.WriteString("Stats");
  14191. VmaPrintDetailedStatistics(json, stats.memoryHeap[heapIndex]);
  14192. json.WriteString("MemoryPools");
  14193. json.BeginObject();
  14194. {
  14195. for (uint32_t typeIndex = 0; typeIndex < allocator->GetMemoryTypeCount(); ++typeIndex)
  14196. {
  14197. if (allocator->MemoryTypeIndexToHeapIndex(typeIndex) == heapIndex)
  14198. {
  14199. json.BeginString("Type ");
  14200. json.ContinueString(typeIndex);
  14201. json.EndString();
  14202. json.BeginObject();
  14203. {
  14204. json.WriteString("Flags");
  14205. json.BeginArray(true);
  14206. {
  14207. VkMemoryPropertyFlags flags = allocator->m_MemProps.memoryTypes[typeIndex].propertyFlags;
  14208. if (flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)
  14209. json.WriteString("DEVICE_LOCAL");
  14210. if (flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
  14211. json.WriteString("HOST_VISIBLE");
  14212. if (flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
  14213. json.WriteString("HOST_COHERENT");
  14214. if (flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT)
  14215. json.WriteString("HOST_CACHED");
  14216. if (flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT)
  14217. json.WriteString("LAZILY_ALLOCATED");
  14218. #if VMA_VULKAN_VERSION >= 1001000
  14219. if (flags & VK_MEMORY_PROPERTY_PROTECTED_BIT)
  14220. json.WriteString("PROTECTED");
  14221. #endif
  14222. #if VK_AMD_device_coherent_memory
  14223. if (flags & VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY)
  14224. json.WriteString("DEVICE_COHERENT_AMD");
  14225. if (flags & VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY)
  14226. json.WriteString("DEVICE_UNCACHED_AMD");
  14227. #endif
  14228. flags &= ~(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT
  14229. #if VMA_VULKAN_VERSION >= 1001000
  14230. | VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT
  14231. #endif
  14232. #if VK_AMD_device_coherent_memory
  14233. | VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY
  14234. | VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY
  14235. #endif
  14236. | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT
  14237. | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT
  14238. | VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
  14239. if (flags != 0)
  14240. json.WriteNumber(flags);
  14241. }
  14242. json.EndArray();
  14243. json.WriteString("Stats");
  14244. VmaPrintDetailedStatistics(json, stats.memoryType[typeIndex]);
  14245. }
  14246. json.EndObject();
  14247. }
  14248. }
  14249. }
  14250. json.EndObject();
  14251. }
  14252. json.EndObject();
  14253. }
  14254. }
  14255. json.EndObject();
  14256. }
  14257. if (detailedMap == VK_TRUE)
  14258. allocator->PrintDetailedMap(json);
  14259. json.EndObject();
  14260. }
  14261. *ppStatsString = VmaCreateStringCopy(allocator->GetAllocationCallbacks(), sb.GetData(), sb.GetLength());
  14262. }
  14263. VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString(
  14264. VmaAllocator allocator,
  14265. char* pStatsString)
  14266. {
  14267. if(pStatsString != VMA_NULL)
  14268. {
  14269. VMA_ASSERT(allocator);
  14270. VmaFreeString(allocator->GetAllocationCallbacks(), pStatsString);
  14271. }
  14272. }
  14273. #endif // VMA_STATS_STRING_ENABLED
  14274. /*
  14275. This function is not protected by any mutex because it just reads immutable data.
  14276. */
  14277. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex(
  14278. VmaAllocator allocator,
  14279. uint32_t memoryTypeBits,
  14280. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14281. uint32_t* pMemoryTypeIndex)
  14282. {
  14283. VMA_ASSERT(allocator != VK_NULL_HANDLE);
  14284. VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
  14285. VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
  14286. return allocator->FindMemoryTypeIndex(memoryTypeBits, pAllocationCreateInfo, UINT32_MAX, pMemoryTypeIndex);
  14287. }
  14288. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo(
  14289. VmaAllocator allocator,
  14290. const VkBufferCreateInfo* pBufferCreateInfo,
  14291. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14292. uint32_t* pMemoryTypeIndex)
  14293. {
  14294. VMA_ASSERT(allocator != VK_NULL_HANDLE);
  14295. VMA_ASSERT(pBufferCreateInfo != VMA_NULL);
  14296. VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
  14297. VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
  14298. const VkDevice hDev = allocator->m_hDevice;
  14299. const VmaVulkanFunctions* funcs = &allocator->GetVulkanFunctions();
  14300. VkResult res;
  14301. #if VMA_VULKAN_VERSION >= 1003000
  14302. if(funcs->vkGetDeviceBufferMemoryRequirements)
  14303. {
  14304. // Can query straight from VkBufferCreateInfo :)
  14305. VkDeviceBufferMemoryRequirements devBufMemReq = {VK_STRUCTURE_TYPE_DEVICE_BUFFER_MEMORY_REQUIREMENTS};
  14306. devBufMemReq.pCreateInfo = pBufferCreateInfo;
  14307. VkMemoryRequirements2 memReq = {VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2};
  14308. (*funcs->vkGetDeviceBufferMemoryRequirements)(hDev, &devBufMemReq, &memReq);
  14309. res = allocator->FindMemoryTypeIndex(
  14310. memReq.memoryRequirements.memoryTypeBits, pAllocationCreateInfo, pBufferCreateInfo->usage, pMemoryTypeIndex);
  14311. }
  14312. else
  14313. #endif // #if VMA_VULKAN_VERSION >= 1003000
  14314. {
  14315. // Must create a dummy buffer to query :(
  14316. VkBuffer hBuffer = VK_NULL_HANDLE;
  14317. res = funcs->vkCreateBuffer(
  14318. hDev, pBufferCreateInfo, allocator->GetAllocationCallbacks(), &hBuffer);
  14319. if(res == VK_SUCCESS)
  14320. {
  14321. VkMemoryRequirements memReq = {};
  14322. funcs->vkGetBufferMemoryRequirements(hDev, hBuffer, &memReq);
  14323. res = allocator->FindMemoryTypeIndex(
  14324. memReq.memoryTypeBits, pAllocationCreateInfo, pBufferCreateInfo->usage, pMemoryTypeIndex);
  14325. funcs->vkDestroyBuffer(
  14326. hDev, hBuffer, allocator->GetAllocationCallbacks());
  14327. }
  14328. }
  14329. return res;
  14330. }
  14331. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo(
  14332. VmaAllocator allocator,
  14333. const VkImageCreateInfo* pImageCreateInfo,
  14334. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14335. uint32_t* pMemoryTypeIndex)
  14336. {
  14337. VMA_ASSERT(allocator != VK_NULL_HANDLE);
  14338. VMA_ASSERT(pImageCreateInfo != VMA_NULL);
  14339. VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
  14340. VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
  14341. const VkDevice hDev = allocator->m_hDevice;
  14342. const VmaVulkanFunctions* funcs = &allocator->GetVulkanFunctions();
  14343. VkResult res;
  14344. #if VMA_VULKAN_VERSION >= 1003000
  14345. if(funcs->vkGetDeviceImageMemoryRequirements)
  14346. {
  14347. // Can query straight from VkImageCreateInfo :)
  14348. VkDeviceImageMemoryRequirements devImgMemReq = {VK_STRUCTURE_TYPE_DEVICE_IMAGE_MEMORY_REQUIREMENTS};
  14349. devImgMemReq.pCreateInfo = pImageCreateInfo;
  14350. VMA_ASSERT(pImageCreateInfo->tiling != VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT_COPY && (pImageCreateInfo->flags & VK_IMAGE_CREATE_DISJOINT_BIT_COPY) == 0 &&
  14351. "Cannot use this VkImageCreateInfo with vmaFindMemoryTypeIndexForImageInfo as I don't know what to pass as VkDeviceImageMemoryRequirements::planeAspect.");
  14352. VkMemoryRequirements2 memReq = {VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2};
  14353. (*funcs->vkGetDeviceImageMemoryRequirements)(hDev, &devImgMemReq, &memReq);
  14354. res = allocator->FindMemoryTypeIndex(
  14355. memReq.memoryRequirements.memoryTypeBits, pAllocationCreateInfo, pImageCreateInfo->usage, pMemoryTypeIndex);
  14356. }
  14357. else
  14358. #endif // #if VMA_VULKAN_VERSION >= 1003000
  14359. {
  14360. // Must create a dummy image to query :(
  14361. VkImage hImage = VK_NULL_HANDLE;
  14362. res = funcs->vkCreateImage(
  14363. hDev, pImageCreateInfo, allocator->GetAllocationCallbacks(), &hImage);
  14364. if(res == VK_SUCCESS)
  14365. {
  14366. VkMemoryRequirements memReq = {};
  14367. funcs->vkGetImageMemoryRequirements(hDev, hImage, &memReq);
  14368. res = allocator->FindMemoryTypeIndex(
  14369. memReq.memoryTypeBits, pAllocationCreateInfo, pImageCreateInfo->usage, pMemoryTypeIndex);
  14370. funcs->vkDestroyImage(
  14371. hDev, hImage, allocator->GetAllocationCallbacks());
  14372. }
  14373. }
  14374. return res;
  14375. }
  14376. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool(
  14377. VmaAllocator allocator,
  14378. const VmaPoolCreateInfo* pCreateInfo,
  14379. VmaPool* pPool)
  14380. {
  14381. VMA_ASSERT(allocator && pCreateInfo && pPool);
  14382. VMA_DEBUG_LOG("vmaCreatePool");
  14383. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14384. return allocator->CreatePool(pCreateInfo, pPool);
  14385. }
  14386. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool(
  14387. VmaAllocator allocator,
  14388. VmaPool pool)
  14389. {
  14390. VMA_ASSERT(allocator);
  14391. if(pool == VK_NULL_HANDLE)
  14392. {
  14393. return;
  14394. }
  14395. VMA_DEBUG_LOG("vmaDestroyPool");
  14396. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14397. allocator->DestroyPool(pool);
  14398. }
  14399. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStatistics(
  14400. VmaAllocator allocator,
  14401. VmaPool pool,
  14402. VmaStatistics* pPoolStats)
  14403. {
  14404. VMA_ASSERT(allocator && pool && pPoolStats);
  14405. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14406. allocator->GetPoolStatistics(pool, pPoolStats);
  14407. }
  14408. VMA_CALL_PRE void VMA_CALL_POST vmaCalculatePoolStatistics(
  14409. VmaAllocator allocator,
  14410. VmaPool pool,
  14411. VmaDetailedStatistics* pPoolStats)
  14412. {
  14413. VMA_ASSERT(allocator && pool && pPoolStats);
  14414. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14415. allocator->CalculatePoolStatistics(pool, pPoolStats);
  14416. }
  14417. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckPoolCorruption(VmaAllocator allocator, VmaPool pool)
  14418. {
  14419. VMA_ASSERT(allocator && pool);
  14420. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14421. VMA_DEBUG_LOG("vmaCheckPoolCorruption");
  14422. return allocator->CheckPoolCorruption(pool);
  14423. }
  14424. VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName(
  14425. VmaAllocator allocator,
  14426. VmaPool pool,
  14427. const char** ppName)
  14428. {
  14429. VMA_ASSERT(allocator && pool && ppName);
  14430. VMA_DEBUG_LOG("vmaGetPoolName");
  14431. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14432. *ppName = pool->GetName();
  14433. }
  14434. VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName(
  14435. VmaAllocator allocator,
  14436. VmaPool pool,
  14437. const char* pName)
  14438. {
  14439. VMA_ASSERT(allocator && pool);
  14440. VMA_DEBUG_LOG("vmaSetPoolName");
  14441. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14442. pool->SetName(pName);
  14443. }
  14444. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory(
  14445. VmaAllocator allocator,
  14446. const VkMemoryRequirements* pVkMemoryRequirements,
  14447. const VmaAllocationCreateInfo* pCreateInfo,
  14448. VmaAllocation* pAllocation,
  14449. VmaAllocationInfo* pAllocationInfo)
  14450. {
  14451. VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocation);
  14452. VMA_DEBUG_LOG("vmaAllocateMemory");
  14453. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14454. VkResult result = allocator->AllocateMemory(
  14455. *pVkMemoryRequirements,
  14456. false, // requiresDedicatedAllocation
  14457. false, // prefersDedicatedAllocation
  14458. VK_NULL_HANDLE, // dedicatedBuffer
  14459. VK_NULL_HANDLE, // dedicatedImage
  14460. UINT32_MAX, // dedicatedBufferImageUsage
  14461. *pCreateInfo,
  14462. VMA_SUBALLOCATION_TYPE_UNKNOWN,
  14463. 1, // allocationCount
  14464. pAllocation);
  14465. if(pAllocationInfo != VMA_NULL && result == VK_SUCCESS)
  14466. {
  14467. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  14468. }
  14469. return result;
  14470. }
  14471. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages(
  14472. VmaAllocator allocator,
  14473. const VkMemoryRequirements* pVkMemoryRequirements,
  14474. const VmaAllocationCreateInfo* pCreateInfo,
  14475. size_t allocationCount,
  14476. VmaAllocation* pAllocations,
  14477. VmaAllocationInfo* pAllocationInfo)
  14478. {
  14479. if(allocationCount == 0)
  14480. {
  14481. return VK_SUCCESS;
  14482. }
  14483. VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocations);
  14484. VMA_DEBUG_LOG("vmaAllocateMemoryPages");
  14485. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14486. VkResult result = allocator->AllocateMemory(
  14487. *pVkMemoryRequirements,
  14488. false, // requiresDedicatedAllocation
  14489. false, // prefersDedicatedAllocation
  14490. VK_NULL_HANDLE, // dedicatedBuffer
  14491. VK_NULL_HANDLE, // dedicatedImage
  14492. UINT32_MAX, // dedicatedBufferImageUsage
  14493. *pCreateInfo,
  14494. VMA_SUBALLOCATION_TYPE_UNKNOWN,
  14495. allocationCount,
  14496. pAllocations);
  14497. if(pAllocationInfo != VMA_NULL && result == VK_SUCCESS)
  14498. {
  14499. for(size_t i = 0; i < allocationCount; ++i)
  14500. {
  14501. allocator->GetAllocationInfo(pAllocations[i], pAllocationInfo + i);
  14502. }
  14503. }
  14504. return result;
  14505. }
  14506. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer(
  14507. VmaAllocator allocator,
  14508. VkBuffer buffer,
  14509. const VmaAllocationCreateInfo* pCreateInfo,
  14510. VmaAllocation* pAllocation,
  14511. VmaAllocationInfo* pAllocationInfo)
  14512. {
  14513. VMA_ASSERT(allocator && buffer != VK_NULL_HANDLE && pCreateInfo && pAllocation);
  14514. VMA_DEBUG_LOG("vmaAllocateMemoryForBuffer");
  14515. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14516. VkMemoryRequirements vkMemReq = {};
  14517. bool requiresDedicatedAllocation = false;
  14518. bool prefersDedicatedAllocation = false;
  14519. allocator->GetBufferMemoryRequirements(buffer, vkMemReq,
  14520. requiresDedicatedAllocation,
  14521. prefersDedicatedAllocation);
  14522. VkResult result = allocator->AllocateMemory(
  14523. vkMemReq,
  14524. requiresDedicatedAllocation,
  14525. prefersDedicatedAllocation,
  14526. buffer, // dedicatedBuffer
  14527. VK_NULL_HANDLE, // dedicatedImage
  14528. UINT32_MAX, // dedicatedBufferImageUsage
  14529. *pCreateInfo,
  14530. VMA_SUBALLOCATION_TYPE_BUFFER,
  14531. 1, // allocationCount
  14532. pAllocation);
  14533. if(pAllocationInfo && result == VK_SUCCESS)
  14534. {
  14535. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  14536. }
  14537. return result;
  14538. }
  14539. VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage(
  14540. VmaAllocator allocator,
  14541. VkImage image,
  14542. const VmaAllocationCreateInfo* pCreateInfo,
  14543. VmaAllocation* pAllocation,
  14544. VmaAllocationInfo* pAllocationInfo)
  14545. {
  14546. VMA_ASSERT(allocator && image != VK_NULL_HANDLE && pCreateInfo && pAllocation);
  14547. VMA_DEBUG_LOG("vmaAllocateMemoryForImage");
  14548. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14549. VkMemoryRequirements vkMemReq = {};
  14550. bool requiresDedicatedAllocation = false;
  14551. bool prefersDedicatedAllocation = false;
  14552. allocator->GetImageMemoryRequirements(image, vkMemReq,
  14553. requiresDedicatedAllocation, prefersDedicatedAllocation);
  14554. VkResult result = allocator->AllocateMemory(
  14555. vkMemReq,
  14556. requiresDedicatedAllocation,
  14557. prefersDedicatedAllocation,
  14558. VK_NULL_HANDLE, // dedicatedBuffer
  14559. image, // dedicatedImage
  14560. UINT32_MAX, // dedicatedBufferImageUsage
  14561. *pCreateInfo,
  14562. VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN,
  14563. 1, // allocationCount
  14564. pAllocation);
  14565. if(pAllocationInfo && result == VK_SUCCESS)
  14566. {
  14567. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  14568. }
  14569. return result;
  14570. }
  14571. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory(
  14572. VmaAllocator allocator,
  14573. VmaAllocation allocation)
  14574. {
  14575. VMA_ASSERT(allocator);
  14576. if(allocation == VK_NULL_HANDLE)
  14577. {
  14578. return;
  14579. }
  14580. VMA_DEBUG_LOG("vmaFreeMemory");
  14581. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14582. allocator->FreeMemory(
  14583. 1, // allocationCount
  14584. &allocation);
  14585. }
  14586. VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages(
  14587. VmaAllocator allocator,
  14588. size_t allocationCount,
  14589. const VmaAllocation* pAllocations)
  14590. {
  14591. if(allocationCount == 0)
  14592. {
  14593. return;
  14594. }
  14595. VMA_ASSERT(allocator);
  14596. VMA_DEBUG_LOG("vmaFreeMemoryPages");
  14597. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14598. allocator->FreeMemory(allocationCount, pAllocations);
  14599. }
  14600. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo(
  14601. VmaAllocator allocator,
  14602. VmaAllocation allocation,
  14603. VmaAllocationInfo* pAllocationInfo)
  14604. {
  14605. VMA_ASSERT(allocator && allocation && pAllocationInfo);
  14606. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14607. allocator->GetAllocationInfo(allocation, pAllocationInfo);
  14608. }
  14609. VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData(
  14610. VmaAllocator allocator,
  14611. VmaAllocation allocation,
  14612. void* pUserData)
  14613. {
  14614. VMA_ASSERT(allocator && allocation);
  14615. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14616. allocation->SetUserData(allocator, pUserData);
  14617. }
  14618. VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationName(
  14619. VmaAllocator VMA_NOT_NULL allocator,
  14620. VmaAllocation VMA_NOT_NULL allocation,
  14621. const char* VMA_NULLABLE pName)
  14622. {
  14623. allocation->SetName(allocator, pName);
  14624. }
  14625. VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationMemoryProperties(
  14626. VmaAllocator VMA_NOT_NULL allocator,
  14627. VmaAllocation VMA_NOT_NULL allocation,
  14628. VkMemoryPropertyFlags* VMA_NOT_NULL pFlags)
  14629. {
  14630. VMA_ASSERT(allocator && allocation && pFlags);
  14631. const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
  14632. *pFlags = allocator->m_MemProps.memoryTypes[memTypeIndex].propertyFlags;
  14633. }
  14634. VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory(
  14635. VmaAllocator allocator,
  14636. VmaAllocation allocation,
  14637. void** ppData)
  14638. {
  14639. VMA_ASSERT(allocator && allocation && ppData);
  14640. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14641. return allocator->Map(allocation, ppData);
  14642. }
  14643. VMA_CALL_PRE void VMA_CALL_POST vmaUnmapMemory(
  14644. VmaAllocator allocator,
  14645. VmaAllocation allocation)
  14646. {
  14647. VMA_ASSERT(allocator && allocation);
  14648. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14649. allocator->Unmap(allocation);
  14650. }
  14651. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocation(
  14652. VmaAllocator allocator,
  14653. VmaAllocation allocation,
  14654. VkDeviceSize offset,
  14655. VkDeviceSize size)
  14656. {
  14657. VMA_ASSERT(allocator && allocation);
  14658. VMA_DEBUG_LOG("vmaFlushAllocation");
  14659. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14660. const VkResult res = allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_FLUSH);
  14661. return res;
  14662. }
  14663. VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocation(
  14664. VmaAllocator allocator,
  14665. VmaAllocation allocation,
  14666. VkDeviceSize offset,
  14667. VkDeviceSize size)
  14668. {
  14669. VMA_ASSERT(allocator && allocation);
  14670. VMA_DEBUG_LOG("vmaInvalidateAllocation");
  14671. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14672. const VkResult res = allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_INVALIDATE);
  14673. return res;
  14674. }
  14675. VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocations(
  14676. VmaAllocator allocator,
  14677. uint32_t allocationCount,
  14678. const VmaAllocation* allocations,
  14679. const VkDeviceSize* offsets,
  14680. const VkDeviceSize* sizes)
  14681. {
  14682. VMA_ASSERT(allocator);
  14683. if(allocationCount == 0)
  14684. {
  14685. return VK_SUCCESS;
  14686. }
  14687. VMA_ASSERT(allocations);
  14688. VMA_DEBUG_LOG("vmaFlushAllocations");
  14689. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14690. const VkResult res = allocator->FlushOrInvalidateAllocations(allocationCount, allocations, offsets, sizes, VMA_CACHE_FLUSH);
  14691. return res;
  14692. }
  14693. VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocations(
  14694. VmaAllocator allocator,
  14695. uint32_t allocationCount,
  14696. const VmaAllocation* allocations,
  14697. const VkDeviceSize* offsets,
  14698. const VkDeviceSize* sizes)
  14699. {
  14700. VMA_ASSERT(allocator);
  14701. if(allocationCount == 0)
  14702. {
  14703. return VK_SUCCESS;
  14704. }
  14705. VMA_ASSERT(allocations);
  14706. VMA_DEBUG_LOG("vmaInvalidateAllocations");
  14707. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14708. const VkResult res = allocator->FlushOrInvalidateAllocations(allocationCount, allocations, offsets, sizes, VMA_CACHE_INVALIDATE);
  14709. return res;
  14710. }
  14711. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckCorruption(
  14712. VmaAllocator allocator,
  14713. uint32_t memoryTypeBits)
  14714. {
  14715. VMA_ASSERT(allocator);
  14716. VMA_DEBUG_LOG("vmaCheckCorruption");
  14717. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14718. return allocator->CheckCorruption(memoryTypeBits);
  14719. }
  14720. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentation(
  14721. VmaAllocator allocator,
  14722. const VmaDefragmentationInfo* pInfo,
  14723. VmaDefragmentationContext* pContext)
  14724. {
  14725. VMA_ASSERT(allocator && pInfo && pContext);
  14726. VMA_DEBUG_LOG("vmaBeginDefragmentation");
  14727. if (pInfo->pool != VMA_NULL)
  14728. {
  14729. // Check if run on supported algorithms
  14730. if (pInfo->pool->m_BlockVector.GetAlgorithm() & VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT)
  14731. return VK_ERROR_FEATURE_NOT_PRESENT;
  14732. }
  14733. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14734. *pContext = vma_new(allocator, VmaDefragmentationContext_T)(allocator, *pInfo);
  14735. return VK_SUCCESS;
  14736. }
  14737. VMA_CALL_PRE void VMA_CALL_POST vmaEndDefragmentation(
  14738. VmaAllocator allocator,
  14739. VmaDefragmentationContext context,
  14740. VmaDefragmentationStats* pStats)
  14741. {
  14742. VMA_ASSERT(allocator && context);
  14743. VMA_DEBUG_LOG("vmaEndDefragmentation");
  14744. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14745. if (pStats)
  14746. context->GetStats(*pStats);
  14747. vma_delete(allocator, context);
  14748. }
  14749. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentationPass(
  14750. VmaAllocator VMA_NOT_NULL allocator,
  14751. VmaDefragmentationContext VMA_NOT_NULL context,
  14752. VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo)
  14753. {
  14754. VMA_ASSERT(context && pPassInfo);
  14755. VMA_DEBUG_LOG("vmaBeginDefragmentationPass");
  14756. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14757. return context->DefragmentPassBegin(*pPassInfo);
  14758. }
  14759. VMA_CALL_PRE VkResult VMA_CALL_POST vmaEndDefragmentationPass(
  14760. VmaAllocator VMA_NOT_NULL allocator,
  14761. VmaDefragmentationContext VMA_NOT_NULL context,
  14762. VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo)
  14763. {
  14764. VMA_ASSERT(context && pPassInfo);
  14765. VMA_DEBUG_LOG("vmaEndDefragmentationPass");
  14766. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14767. return context->DefragmentPassEnd(*pPassInfo);
  14768. }
  14769. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory(
  14770. VmaAllocator allocator,
  14771. VmaAllocation allocation,
  14772. VkBuffer buffer)
  14773. {
  14774. VMA_ASSERT(allocator && allocation && buffer);
  14775. VMA_DEBUG_LOG("vmaBindBufferMemory");
  14776. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14777. return allocator->BindBufferMemory(allocation, 0, buffer, VMA_NULL);
  14778. }
  14779. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2(
  14780. VmaAllocator allocator,
  14781. VmaAllocation allocation,
  14782. VkDeviceSize allocationLocalOffset,
  14783. VkBuffer buffer,
  14784. const void* pNext)
  14785. {
  14786. VMA_ASSERT(allocator && allocation && buffer);
  14787. VMA_DEBUG_LOG("vmaBindBufferMemory2");
  14788. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14789. return allocator->BindBufferMemory(allocation, allocationLocalOffset, buffer, pNext);
  14790. }
  14791. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory(
  14792. VmaAllocator allocator,
  14793. VmaAllocation allocation,
  14794. VkImage image)
  14795. {
  14796. VMA_ASSERT(allocator && allocation && image);
  14797. VMA_DEBUG_LOG("vmaBindImageMemory");
  14798. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14799. return allocator->BindImageMemory(allocation, 0, image, VMA_NULL);
  14800. }
  14801. VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2(
  14802. VmaAllocator allocator,
  14803. VmaAllocation allocation,
  14804. VkDeviceSize allocationLocalOffset,
  14805. VkImage image,
  14806. const void* pNext)
  14807. {
  14808. VMA_ASSERT(allocator && allocation && image);
  14809. VMA_DEBUG_LOG("vmaBindImageMemory2");
  14810. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14811. return allocator->BindImageMemory(allocation, allocationLocalOffset, image, pNext);
  14812. }
  14813. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer(
  14814. VmaAllocator allocator,
  14815. const VkBufferCreateInfo* pBufferCreateInfo,
  14816. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14817. VkBuffer* pBuffer,
  14818. VmaAllocation* pAllocation,
  14819. VmaAllocationInfo* pAllocationInfo)
  14820. {
  14821. VMA_ASSERT(allocator && pBufferCreateInfo && pAllocationCreateInfo && pBuffer && pAllocation);
  14822. if(pBufferCreateInfo->size == 0)
  14823. {
  14824. return VK_ERROR_INITIALIZATION_FAILED;
  14825. }
  14826. if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY) != 0 &&
  14827. !allocator->m_UseKhrBufferDeviceAddress)
  14828. {
  14829. VMA_ASSERT(0 && "Creating a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT is not valid if VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT was not used.");
  14830. return VK_ERROR_INITIALIZATION_FAILED;
  14831. }
  14832. VMA_DEBUG_LOG("vmaCreateBuffer");
  14833. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14834. *pBuffer = VK_NULL_HANDLE;
  14835. *pAllocation = VK_NULL_HANDLE;
  14836. // 1. Create VkBuffer.
  14837. VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)(
  14838. allocator->m_hDevice,
  14839. pBufferCreateInfo,
  14840. allocator->GetAllocationCallbacks(),
  14841. pBuffer);
  14842. if(res >= 0)
  14843. {
  14844. // 2. vkGetBufferMemoryRequirements.
  14845. VkMemoryRequirements vkMemReq = {};
  14846. bool requiresDedicatedAllocation = false;
  14847. bool prefersDedicatedAllocation = false;
  14848. allocator->GetBufferMemoryRequirements(*pBuffer, vkMemReq,
  14849. requiresDedicatedAllocation, prefersDedicatedAllocation);
  14850. // 3. Allocate memory using allocator.
  14851. res = allocator->AllocateMemory(
  14852. vkMemReq,
  14853. requiresDedicatedAllocation,
  14854. prefersDedicatedAllocation,
  14855. *pBuffer, // dedicatedBuffer
  14856. VK_NULL_HANDLE, // dedicatedImage
  14857. pBufferCreateInfo->usage, // dedicatedBufferImageUsage
  14858. *pAllocationCreateInfo,
  14859. VMA_SUBALLOCATION_TYPE_BUFFER,
  14860. 1, // allocationCount
  14861. pAllocation);
  14862. if(res >= 0)
  14863. {
  14864. // 3. Bind buffer with memory.
  14865. if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0)
  14866. {
  14867. res = allocator->BindBufferMemory(*pAllocation, 0, *pBuffer, VMA_NULL);
  14868. }
  14869. if(res >= 0)
  14870. {
  14871. // All steps succeeded.
  14872. #if VMA_STATS_STRING_ENABLED
  14873. (*pAllocation)->InitBufferImageUsage(pBufferCreateInfo->usage);
  14874. #endif
  14875. if(pAllocationInfo != VMA_NULL)
  14876. {
  14877. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  14878. }
  14879. return VK_SUCCESS;
  14880. }
  14881. allocator->FreeMemory(
  14882. 1, // allocationCount
  14883. pAllocation);
  14884. *pAllocation = VK_NULL_HANDLE;
  14885. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
  14886. *pBuffer = VK_NULL_HANDLE;
  14887. return res;
  14888. }
  14889. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
  14890. *pBuffer = VK_NULL_HANDLE;
  14891. return res;
  14892. }
  14893. return res;
  14894. }
  14895. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBufferWithAlignment(
  14896. VmaAllocator allocator,
  14897. const VkBufferCreateInfo* pBufferCreateInfo,
  14898. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  14899. VkDeviceSize minAlignment,
  14900. VkBuffer* pBuffer,
  14901. VmaAllocation* pAllocation,
  14902. VmaAllocationInfo* pAllocationInfo)
  14903. {
  14904. VMA_ASSERT(allocator && pBufferCreateInfo && pAllocationCreateInfo && VmaIsPow2(minAlignment) && pBuffer && pAllocation);
  14905. if(pBufferCreateInfo->size == 0)
  14906. {
  14907. return VK_ERROR_INITIALIZATION_FAILED;
  14908. }
  14909. if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY) != 0 &&
  14910. !allocator->m_UseKhrBufferDeviceAddress)
  14911. {
  14912. VMA_ASSERT(0 && "Creating a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT is not valid if VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT was not used.");
  14913. return VK_ERROR_INITIALIZATION_FAILED;
  14914. }
  14915. VMA_DEBUG_LOG("vmaCreateBufferWithAlignment");
  14916. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  14917. *pBuffer = VK_NULL_HANDLE;
  14918. *pAllocation = VK_NULL_HANDLE;
  14919. // 1. Create VkBuffer.
  14920. VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)(
  14921. allocator->m_hDevice,
  14922. pBufferCreateInfo,
  14923. allocator->GetAllocationCallbacks(),
  14924. pBuffer);
  14925. if(res >= 0)
  14926. {
  14927. // 2. vkGetBufferMemoryRequirements.
  14928. VkMemoryRequirements vkMemReq = {};
  14929. bool requiresDedicatedAllocation = false;
  14930. bool prefersDedicatedAllocation = false;
  14931. allocator->GetBufferMemoryRequirements(*pBuffer, vkMemReq,
  14932. requiresDedicatedAllocation, prefersDedicatedAllocation);
  14933. // 2a. Include minAlignment
  14934. vkMemReq.alignment = VMA_MAX(vkMemReq.alignment, minAlignment);
  14935. // 3. Allocate memory using allocator.
  14936. res = allocator->AllocateMemory(
  14937. vkMemReq,
  14938. requiresDedicatedAllocation,
  14939. prefersDedicatedAllocation,
  14940. *pBuffer, // dedicatedBuffer
  14941. VK_NULL_HANDLE, // dedicatedImage
  14942. pBufferCreateInfo->usage, // dedicatedBufferImageUsage
  14943. *pAllocationCreateInfo,
  14944. VMA_SUBALLOCATION_TYPE_BUFFER,
  14945. 1, // allocationCount
  14946. pAllocation);
  14947. if(res >= 0)
  14948. {
  14949. // 3. Bind buffer with memory.
  14950. if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0)
  14951. {
  14952. res = allocator->BindBufferMemory(*pAllocation, 0, *pBuffer, VMA_NULL);
  14953. }
  14954. if(res >= 0)
  14955. {
  14956. // All steps succeeded.
  14957. #if VMA_STATS_STRING_ENABLED
  14958. (*pAllocation)->InitBufferImageUsage(pBufferCreateInfo->usage);
  14959. #endif
  14960. if(pAllocationInfo != VMA_NULL)
  14961. {
  14962. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  14963. }
  14964. return VK_SUCCESS;
  14965. }
  14966. allocator->FreeMemory(
  14967. 1, // allocationCount
  14968. pAllocation);
  14969. *pAllocation = VK_NULL_HANDLE;
  14970. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
  14971. *pBuffer = VK_NULL_HANDLE;
  14972. return res;
  14973. }
  14974. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
  14975. *pBuffer = VK_NULL_HANDLE;
  14976. return res;
  14977. }
  14978. return res;
  14979. }
  14980. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingBuffer(
  14981. VmaAllocator VMA_NOT_NULL allocator,
  14982. VmaAllocation VMA_NOT_NULL allocation,
  14983. const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo,
  14984. VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer)
  14985. {
  14986. return vmaCreateAliasingBuffer2(allocator, allocation, 0, pBufferCreateInfo, pBuffer);
  14987. }
  14988. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingBuffer2(
  14989. VmaAllocator VMA_NOT_NULL allocator,
  14990. VmaAllocation VMA_NOT_NULL allocation,
  14991. VkDeviceSize allocationLocalOffset,
  14992. const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo,
  14993. VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer)
  14994. {
  14995. VMA_ASSERT(allocator && pBufferCreateInfo && pBuffer && allocation);
  14996. VMA_ASSERT(allocationLocalOffset + pBufferCreateInfo->size <= allocation->GetSize());
  14997. VMA_DEBUG_LOG("vmaCreateAliasingBuffer2");
  14998. *pBuffer = VK_NULL_HANDLE;
  14999. if (pBufferCreateInfo->size == 0)
  15000. {
  15001. return VK_ERROR_INITIALIZATION_FAILED;
  15002. }
  15003. if ((pBufferCreateInfo->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY) != 0 &&
  15004. !allocator->m_UseKhrBufferDeviceAddress)
  15005. {
  15006. VMA_ASSERT(0 && "Creating a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT is not valid if VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT was not used.");
  15007. return VK_ERROR_INITIALIZATION_FAILED;
  15008. }
  15009. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15010. // 1. Create VkBuffer.
  15011. VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)(
  15012. allocator->m_hDevice,
  15013. pBufferCreateInfo,
  15014. allocator->GetAllocationCallbacks(),
  15015. pBuffer);
  15016. if (res >= 0)
  15017. {
  15018. // 2. Bind buffer with memory.
  15019. res = allocator->BindBufferMemory(allocation, allocationLocalOffset, *pBuffer, VMA_NULL);
  15020. if (res >= 0)
  15021. {
  15022. return VK_SUCCESS;
  15023. }
  15024. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
  15025. }
  15026. return res;
  15027. }
  15028. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer(
  15029. VmaAllocator allocator,
  15030. VkBuffer buffer,
  15031. VmaAllocation allocation)
  15032. {
  15033. VMA_ASSERT(allocator);
  15034. if(buffer == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE)
  15035. {
  15036. return;
  15037. }
  15038. VMA_DEBUG_LOG("vmaDestroyBuffer");
  15039. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15040. if(buffer != VK_NULL_HANDLE)
  15041. {
  15042. (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, buffer, allocator->GetAllocationCallbacks());
  15043. }
  15044. if(allocation != VK_NULL_HANDLE)
  15045. {
  15046. allocator->FreeMemory(
  15047. 1, // allocationCount
  15048. &allocation);
  15049. }
  15050. }
  15051. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage(
  15052. VmaAllocator allocator,
  15053. const VkImageCreateInfo* pImageCreateInfo,
  15054. const VmaAllocationCreateInfo* pAllocationCreateInfo,
  15055. VkImage* pImage,
  15056. VmaAllocation* pAllocation,
  15057. VmaAllocationInfo* pAllocationInfo)
  15058. {
  15059. VMA_ASSERT(allocator && pImageCreateInfo && pAllocationCreateInfo && pImage && pAllocation);
  15060. if(pImageCreateInfo->extent.width == 0 ||
  15061. pImageCreateInfo->extent.height == 0 ||
  15062. pImageCreateInfo->extent.depth == 0 ||
  15063. pImageCreateInfo->mipLevels == 0 ||
  15064. pImageCreateInfo->arrayLayers == 0)
  15065. {
  15066. return VK_ERROR_INITIALIZATION_FAILED;
  15067. }
  15068. VMA_DEBUG_LOG("vmaCreateImage");
  15069. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15070. *pImage = VK_NULL_HANDLE;
  15071. *pAllocation = VK_NULL_HANDLE;
  15072. // 1. Create VkImage.
  15073. VkResult res = (*allocator->GetVulkanFunctions().vkCreateImage)(
  15074. allocator->m_hDevice,
  15075. pImageCreateInfo,
  15076. allocator->GetAllocationCallbacks(),
  15077. pImage);
  15078. if(res >= 0)
  15079. {
  15080. VmaSuballocationType suballocType = pImageCreateInfo->tiling == VK_IMAGE_TILING_OPTIMAL ?
  15081. VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL :
  15082. VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR;
  15083. // 2. Allocate memory using allocator.
  15084. VkMemoryRequirements vkMemReq = {};
  15085. bool requiresDedicatedAllocation = false;
  15086. bool prefersDedicatedAllocation = false;
  15087. allocator->GetImageMemoryRequirements(*pImage, vkMemReq,
  15088. requiresDedicatedAllocation, prefersDedicatedAllocation);
  15089. res = allocator->AllocateMemory(
  15090. vkMemReq,
  15091. requiresDedicatedAllocation,
  15092. prefersDedicatedAllocation,
  15093. VK_NULL_HANDLE, // dedicatedBuffer
  15094. *pImage, // dedicatedImage
  15095. pImageCreateInfo->usage, // dedicatedBufferImageUsage
  15096. *pAllocationCreateInfo,
  15097. suballocType,
  15098. 1, // allocationCount
  15099. pAllocation);
  15100. if(res >= 0)
  15101. {
  15102. // 3. Bind image with memory.
  15103. if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0)
  15104. {
  15105. res = allocator->BindImageMemory(*pAllocation, 0, *pImage, VMA_NULL);
  15106. }
  15107. if(res >= 0)
  15108. {
  15109. // All steps succeeded.
  15110. #if VMA_STATS_STRING_ENABLED
  15111. (*pAllocation)->InitBufferImageUsage(pImageCreateInfo->usage);
  15112. #endif
  15113. if(pAllocationInfo != VMA_NULL)
  15114. {
  15115. allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
  15116. }
  15117. return VK_SUCCESS;
  15118. }
  15119. allocator->FreeMemory(
  15120. 1, // allocationCount
  15121. pAllocation);
  15122. *pAllocation = VK_NULL_HANDLE;
  15123. (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks());
  15124. *pImage = VK_NULL_HANDLE;
  15125. return res;
  15126. }
  15127. (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks());
  15128. *pImage = VK_NULL_HANDLE;
  15129. return res;
  15130. }
  15131. return res;
  15132. }
  15133. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingImage(
  15134. VmaAllocator VMA_NOT_NULL allocator,
  15135. VmaAllocation VMA_NOT_NULL allocation,
  15136. const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo,
  15137. VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage)
  15138. {
  15139. return vmaCreateAliasingImage2(allocator, allocation, 0, pImageCreateInfo, pImage);
  15140. }
  15141. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingImage2(
  15142. VmaAllocator VMA_NOT_NULL allocator,
  15143. VmaAllocation VMA_NOT_NULL allocation,
  15144. VkDeviceSize allocationLocalOffset,
  15145. const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo,
  15146. VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage)
  15147. {
  15148. VMA_ASSERT(allocator && pImageCreateInfo && pImage && allocation);
  15149. *pImage = VK_NULL_HANDLE;
  15150. VMA_DEBUG_LOG("vmaCreateImage2");
  15151. if (pImageCreateInfo->extent.width == 0 ||
  15152. pImageCreateInfo->extent.height == 0 ||
  15153. pImageCreateInfo->extent.depth == 0 ||
  15154. pImageCreateInfo->mipLevels == 0 ||
  15155. pImageCreateInfo->arrayLayers == 0)
  15156. {
  15157. return VK_ERROR_INITIALIZATION_FAILED;
  15158. }
  15159. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15160. // 1. Create VkImage.
  15161. VkResult res = (*allocator->GetVulkanFunctions().vkCreateImage)(
  15162. allocator->m_hDevice,
  15163. pImageCreateInfo,
  15164. allocator->GetAllocationCallbacks(),
  15165. pImage);
  15166. if (res >= 0)
  15167. {
  15168. // 2. Bind image with memory.
  15169. res = allocator->BindImageMemory(allocation, allocationLocalOffset, *pImage, VMA_NULL);
  15170. if (res >= 0)
  15171. {
  15172. return VK_SUCCESS;
  15173. }
  15174. (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks());
  15175. }
  15176. return res;
  15177. }
  15178. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyImage(
  15179. VmaAllocator VMA_NOT_NULL allocator,
  15180. VkImage VMA_NULLABLE_NON_DISPATCHABLE image,
  15181. VmaAllocation VMA_NULLABLE allocation)
  15182. {
  15183. VMA_ASSERT(allocator);
  15184. if(image == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE)
  15185. {
  15186. return;
  15187. }
  15188. VMA_DEBUG_LOG("vmaDestroyImage");
  15189. VMA_DEBUG_GLOBAL_MUTEX_LOCK
  15190. if(image != VK_NULL_HANDLE)
  15191. {
  15192. (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, image, allocator->GetAllocationCallbacks());
  15193. }
  15194. if(allocation != VK_NULL_HANDLE)
  15195. {
  15196. allocator->FreeMemory(
  15197. 1, // allocationCount
  15198. &allocation);
  15199. }
  15200. }
  15201. VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateVirtualBlock(
  15202. const VmaVirtualBlockCreateInfo* VMA_NOT_NULL pCreateInfo,
  15203. VmaVirtualBlock VMA_NULLABLE * VMA_NOT_NULL pVirtualBlock)
  15204. {
  15205. VMA_ASSERT(pCreateInfo && pVirtualBlock);
  15206. VMA_ASSERT(pCreateInfo->size > 0);
  15207. VMA_DEBUG_LOG("vmaCreateVirtualBlock");
  15208. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15209. *pVirtualBlock = vma_new(pCreateInfo->pAllocationCallbacks, VmaVirtualBlock_T)(*pCreateInfo);
  15210. VkResult res = (*pVirtualBlock)->Init();
  15211. if(res < 0)
  15212. {
  15213. vma_delete(pCreateInfo->pAllocationCallbacks, *pVirtualBlock);
  15214. *pVirtualBlock = VK_NULL_HANDLE;
  15215. }
  15216. return res;
  15217. }
  15218. VMA_CALL_PRE void VMA_CALL_POST vmaDestroyVirtualBlock(VmaVirtualBlock VMA_NULLABLE virtualBlock)
  15219. {
  15220. if(virtualBlock != VK_NULL_HANDLE)
  15221. {
  15222. VMA_DEBUG_LOG("vmaDestroyVirtualBlock");
  15223. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15224. VkAllocationCallbacks allocationCallbacks = virtualBlock->m_AllocationCallbacks; // Have to copy the callbacks when destroying.
  15225. vma_delete(&allocationCallbacks, virtualBlock);
  15226. }
  15227. }
  15228. VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaIsVirtualBlockEmpty(VmaVirtualBlock VMA_NOT_NULL virtualBlock)
  15229. {
  15230. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE);
  15231. VMA_DEBUG_LOG("vmaIsVirtualBlockEmpty");
  15232. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15233. return virtualBlock->IsEmpty() ? VK_TRUE : VK_FALSE;
  15234. }
  15235. VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualAllocationInfo(VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  15236. VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation, VmaVirtualAllocationInfo* VMA_NOT_NULL pVirtualAllocInfo)
  15237. {
  15238. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pVirtualAllocInfo != VMA_NULL);
  15239. VMA_DEBUG_LOG("vmaGetVirtualAllocationInfo");
  15240. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15241. virtualBlock->GetAllocationInfo(allocation, *pVirtualAllocInfo);
  15242. }
  15243. VMA_CALL_PRE VkResult VMA_CALL_POST vmaVirtualAllocate(VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  15244. const VmaVirtualAllocationCreateInfo* VMA_NOT_NULL pCreateInfo, VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pAllocation,
  15245. VkDeviceSize* VMA_NULLABLE pOffset)
  15246. {
  15247. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pCreateInfo != VMA_NULL && pAllocation != VMA_NULL);
  15248. VMA_DEBUG_LOG("vmaVirtualAllocate");
  15249. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15250. return virtualBlock->Allocate(*pCreateInfo, *pAllocation, pOffset);
  15251. }
  15252. VMA_CALL_PRE void VMA_CALL_POST vmaVirtualFree(VmaVirtualBlock VMA_NOT_NULL virtualBlock, VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE allocation)
  15253. {
  15254. if(allocation != VK_NULL_HANDLE)
  15255. {
  15256. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE);
  15257. VMA_DEBUG_LOG("vmaVirtualFree");
  15258. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15259. virtualBlock->Free(allocation);
  15260. }
  15261. }
  15262. VMA_CALL_PRE void VMA_CALL_POST vmaClearVirtualBlock(VmaVirtualBlock VMA_NOT_NULL virtualBlock)
  15263. {
  15264. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE);
  15265. VMA_DEBUG_LOG("vmaClearVirtualBlock");
  15266. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15267. virtualBlock->Clear();
  15268. }
  15269. VMA_CALL_PRE void VMA_CALL_POST vmaSetVirtualAllocationUserData(VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  15270. VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation, void* VMA_NULLABLE pUserData)
  15271. {
  15272. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE);
  15273. VMA_DEBUG_LOG("vmaSetVirtualAllocationUserData");
  15274. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15275. virtualBlock->SetAllocationUserData(allocation, pUserData);
  15276. }
  15277. VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualBlockStatistics(VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  15278. VmaStatistics* VMA_NOT_NULL pStats)
  15279. {
  15280. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pStats != VMA_NULL);
  15281. VMA_DEBUG_LOG("vmaGetVirtualBlockStatistics");
  15282. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15283. virtualBlock->GetStatistics(*pStats);
  15284. }
  15285. VMA_CALL_PRE void VMA_CALL_POST vmaCalculateVirtualBlockStatistics(VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  15286. VmaDetailedStatistics* VMA_NOT_NULL pStats)
  15287. {
  15288. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pStats != VMA_NULL);
  15289. VMA_DEBUG_LOG("vmaCalculateVirtualBlockStatistics");
  15290. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15291. virtualBlock->CalculateDetailedStatistics(*pStats);
  15292. }
  15293. #if VMA_STATS_STRING_ENABLED
  15294. VMA_CALL_PRE void VMA_CALL_POST vmaBuildVirtualBlockStatsString(VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  15295. char* VMA_NULLABLE * VMA_NOT_NULL ppStatsString, VkBool32 detailedMap)
  15296. {
  15297. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && ppStatsString != VMA_NULL);
  15298. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15299. const VkAllocationCallbacks* allocationCallbacks = virtualBlock->GetAllocationCallbacks();
  15300. VmaStringBuilder sb(allocationCallbacks);
  15301. virtualBlock->BuildStatsString(detailedMap != VK_FALSE, sb);
  15302. *ppStatsString = VmaCreateStringCopy(allocationCallbacks, sb.GetData(), sb.GetLength());
  15303. }
  15304. VMA_CALL_PRE void VMA_CALL_POST vmaFreeVirtualBlockStatsString(VmaVirtualBlock VMA_NOT_NULL virtualBlock,
  15305. char* VMA_NULLABLE pStatsString)
  15306. {
  15307. if(pStatsString != VMA_NULL)
  15308. {
  15309. VMA_ASSERT(virtualBlock != VK_NULL_HANDLE);
  15310. VMA_DEBUG_GLOBAL_MUTEX_LOCK;
  15311. VmaFreeString(virtualBlock->GetAllocationCallbacks(), pStatsString);
  15312. }
  15313. }
  15314. #endif // VMA_STATS_STRING_ENABLED
  15315. #endif // _VMA_PUBLIC_INTERFACE
  15316. #endif // VMA_IMPLEMENTATION
  15317. /**
  15318. \page quick_start Quick start
  15319. \section quick_start_project_setup Project setup
  15320. Vulkan Memory Allocator comes in form of a "stb-style" single header file.
  15321. You don't need to build it as a separate library project.
  15322. You can add this file directly to your project and submit it to code repository next to your other source files.
  15323. "Single header" doesn't mean that everything is contained in C/C++ declarations,
  15324. like it tends to be in case of inline functions or C++ templates.
  15325. It means that implementation is bundled with interface in a single file and needs to be extracted using preprocessor macro.
  15326. If you don't do it properly, you will get linker errors.
  15327. To do it properly:
  15328. -# Include "vk_mem_alloc.h" file in each CPP file where you want to use the library.
  15329. This includes declarations of all members of the library.
  15330. -# In exactly one CPP file define following macro before this include.
  15331. It enables also internal definitions.
  15332. \code
  15333. #define VMA_IMPLEMENTATION
  15334. #include "vk_mem_alloc.h"
  15335. \endcode
  15336. It may be a good idea to create dedicated CPP file just for this purpose.
  15337. This library includes header `<vulkan/vulkan.h>`, which in turn
  15338. includes `<windows.h>` on Windows. If you need some specific macros defined
  15339. before including these headers (like `WIN32_LEAN_AND_MEAN` or
  15340. `WINVER` for Windows, `VK_USE_PLATFORM_WIN32_KHR` for Vulkan), you must define
  15341. them before every `#include` of this library.
  15342. This library is written in C++, but has C-compatible interface.
  15343. Thus you can include and use vk_mem_alloc.h in C or C++ code, but full
  15344. implementation with `VMA_IMPLEMENTATION` macro must be compiled as C++, NOT as C.
  15345. Some features of C++14 are used. STL containers, RTTI, or C++ exceptions are not used.
  15346. \section quick_start_initialization Initialization
  15347. At program startup:
  15348. -# Initialize Vulkan to have `VkPhysicalDevice`, `VkDevice` and `VkInstance` object.
  15349. -# Fill VmaAllocatorCreateInfo structure and create #VmaAllocator object by
  15350. calling vmaCreateAllocator().
  15351. Only members `physicalDevice`, `device`, `instance` are required.
  15352. However, you should inform the library which Vulkan version do you use by setting
  15353. VmaAllocatorCreateInfo::vulkanApiVersion and which extensions did you enable
  15354. by setting VmaAllocatorCreateInfo::flags (like #VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT for VK_KHR_buffer_device_address).
  15355. Otherwise, VMA would use only features of Vulkan 1.0 core with no extensions.
  15356. \subsection quick_start_initialization_selecting_vulkan_version Selecting Vulkan version
  15357. VMA supports Vulkan version down to 1.0, for backward compatibility.
  15358. If you want to use higher version, you need to inform the library about it.
  15359. This is a two-step process.
  15360. <b>Step 1: Compile time.</b> By default, VMA compiles with code supporting the highest
  15361. Vulkan version found in the included `<vulkan/vulkan.h>` that is also supported by the library.
  15362. If this is OK, you don't need to do anything.
  15363. However, if you want to compile VMA as if only some lower Vulkan version was available,
  15364. define macro `VMA_VULKAN_VERSION` before every `#include "vk_mem_alloc.h"`.
  15365. It should have decimal numeric value in form of ABBBCCC, where A = major, BBB = minor, CCC = patch Vulkan version.
  15366. For example, to compile against Vulkan 1.2:
  15367. \code
  15368. #define VMA_VULKAN_VERSION 1002000 // Vulkan 1.2
  15369. #include "vk_mem_alloc.h"
  15370. \endcode
  15371. <b>Step 2: Runtime.</b> Even when compiled with higher Vulkan version available,
  15372. VMA can use only features of a lower version, which is configurable during creation of the #VmaAllocator object.
  15373. By default, only Vulkan 1.0 is used.
  15374. To initialize the allocator with support for higher Vulkan version, you need to set member
  15375. VmaAllocatorCreateInfo::vulkanApiVersion to an appropriate value, e.g. using constants like `VK_API_VERSION_1_2`.
  15376. See code sample below.
  15377. \subsection quick_start_initialization_importing_vulkan_functions Importing Vulkan functions
  15378. You may need to configure importing Vulkan functions. There are 3 ways to do this:
  15379. -# **If you link with Vulkan static library** (e.g. "vulkan-1.lib" on Windows):
  15380. - You don't need to do anything.
  15381. - VMA will use these, as macro `VMA_STATIC_VULKAN_FUNCTIONS` is defined to 1 by default.
  15382. -# **If you want VMA to fetch pointers to Vulkan functions dynamically** using `vkGetInstanceProcAddr`,
  15383. `vkGetDeviceProcAddr` (this is the option presented in the example below):
  15384. - Define `VMA_STATIC_VULKAN_FUNCTIONS` to 0, `VMA_DYNAMIC_VULKAN_FUNCTIONS` to 1.
  15385. - Provide pointers to these two functions via VmaVulkanFunctions::vkGetInstanceProcAddr,
  15386. VmaVulkanFunctions::vkGetDeviceProcAddr.
  15387. - The library will fetch pointers to all other functions it needs internally.
  15388. -# **If you fetch pointers to all Vulkan functions in a custom way**, e.g. using some loader like
  15389. [Volk](https://github.com/zeux/volk):
  15390. - Define `VMA_STATIC_VULKAN_FUNCTIONS` and `VMA_DYNAMIC_VULKAN_FUNCTIONS` to 0.
  15391. - Pass these pointers via structure #VmaVulkanFunctions.
  15392. Example for case 2:
  15393. \code
  15394. #define VMA_STATIC_VULKAN_FUNCTIONS 0
  15395. #define VMA_DYNAMIC_VULKAN_FUNCTIONS 1
  15396. #include "vk_mem_alloc.h"
  15397. ...
  15398. VmaVulkanFunctions vulkanFunctions = {};
  15399. vulkanFunctions.vkGetInstanceProcAddr = &vkGetInstanceProcAddr;
  15400. vulkanFunctions.vkGetDeviceProcAddr = &vkGetDeviceProcAddr;
  15401. VmaAllocatorCreateInfo allocatorCreateInfo = {};
  15402. allocatorCreateInfo.vulkanApiVersion = VK_API_VERSION_1_2;
  15403. allocatorCreateInfo.physicalDevice = physicalDevice;
  15404. allocatorCreateInfo.device = device;
  15405. allocatorCreateInfo.instance = instance;
  15406. allocatorCreateInfo.pVulkanFunctions = &vulkanFunctions;
  15407. VmaAllocator allocator;
  15408. vmaCreateAllocator(&allocatorCreateInfo, &allocator);
  15409. \endcode
  15410. \section quick_start_resource_allocation Resource allocation
  15411. When you want to create a buffer or image:
  15412. -# Fill `VkBufferCreateInfo` / `VkImageCreateInfo` structure.
  15413. -# Fill VmaAllocationCreateInfo structure.
  15414. -# Call vmaCreateBuffer() / vmaCreateImage() to get `VkBuffer`/`VkImage` with memory
  15415. already allocated and bound to it, plus #VmaAllocation objects that represents its underlying memory.
  15416. \code
  15417. VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  15418. bufferInfo.size = 65536;
  15419. bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  15420. VmaAllocationCreateInfo allocInfo = {};
  15421. allocInfo.usage = VMA_MEMORY_USAGE_AUTO;
  15422. VkBuffer buffer;
  15423. VmaAllocation allocation;
  15424. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  15425. \endcode
  15426. Don't forget to destroy your objects when no longer needed:
  15427. \code
  15428. vmaDestroyBuffer(allocator, buffer, allocation);
  15429. vmaDestroyAllocator(allocator);
  15430. \endcode
  15431. \page choosing_memory_type Choosing memory type
  15432. Physical devices in Vulkan support various combinations of memory heaps and
  15433. types. Help with choosing correct and optimal memory type for your specific
  15434. resource is one of the key features of this library. You can use it by filling
  15435. appropriate members of VmaAllocationCreateInfo structure, as described below.
  15436. You can also combine multiple methods.
  15437. -# If you just want to find memory type index that meets your requirements, you
  15438. can use function: vmaFindMemoryTypeIndexForBufferInfo(),
  15439. vmaFindMemoryTypeIndexForImageInfo(), vmaFindMemoryTypeIndex().
  15440. -# If you want to allocate a region of device memory without association with any
  15441. specific image or buffer, you can use function vmaAllocateMemory(). Usage of
  15442. this function is not recommended and usually not needed.
  15443. vmaAllocateMemoryPages() function is also provided for creating multiple allocations at once,
  15444. which may be useful for sparse binding.
  15445. -# If you already have a buffer or an image created, you want to allocate memory
  15446. for it and then you will bind it yourself, you can use function
  15447. vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage().
  15448. For binding you should use functions: vmaBindBufferMemory(), vmaBindImageMemory()
  15449. or their extended versions: vmaBindBufferMemory2(), vmaBindImageMemory2().
  15450. -# **This is the easiest and recommended way to use this library:**
  15451. If you want to create a buffer or an image, allocate memory for it and bind
  15452. them together, all in one call, you can use function vmaCreateBuffer(),
  15453. vmaCreateImage().
  15454. When using 3. or 4., the library internally queries Vulkan for memory types
  15455. supported for that buffer or image (function `vkGetBufferMemoryRequirements()`)
  15456. and uses only one of these types.
  15457. If no memory type can be found that meets all the requirements, these functions
  15458. return `VK_ERROR_FEATURE_NOT_PRESENT`.
  15459. You can leave VmaAllocationCreateInfo structure completely filled with zeros.
  15460. It means no requirements are specified for memory type.
  15461. It is valid, although not very useful.
  15462. \section choosing_memory_type_usage Usage
  15463. The easiest way to specify memory requirements is to fill member
  15464. VmaAllocationCreateInfo::usage using one of the values of enum #VmaMemoryUsage.
  15465. It defines high level, common usage types.
  15466. Since version 3 of the library, it is recommended to use #VMA_MEMORY_USAGE_AUTO to let it select best memory type for your resource automatically.
  15467. For example, if you want to create a uniform buffer that will be filled using
  15468. transfer only once or infrequently and then used for rendering every frame as a uniform buffer, you can
  15469. do it using following code. The buffer will most likely end up in a memory type with
  15470. `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT` to be fast to access by the GPU device.
  15471. \code
  15472. VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  15473. bufferInfo.size = 65536;
  15474. bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  15475. VmaAllocationCreateInfo allocInfo = {};
  15476. allocInfo.usage = VMA_MEMORY_USAGE_AUTO;
  15477. VkBuffer buffer;
  15478. VmaAllocation allocation;
  15479. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  15480. \endcode
  15481. If you have a preference for putting the resource in GPU (device) memory or CPU (host) memory
  15482. on systems with discrete graphics card that have the memories separate, you can use
  15483. #VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE or #VMA_MEMORY_USAGE_AUTO_PREFER_HOST.
  15484. When using `VMA_MEMORY_USAGE_AUTO*` while you want to map the allocated memory,
  15485. you also need to specify one of the host access flags:
  15486. #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT.
  15487. This will help the library decide about preferred memory type to ensure it has `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`
  15488. so you can map it.
  15489. For example, a staging buffer that will be filled via mapped pointer and then
  15490. used as a source of transfer to the buffer described previously can be created like this.
  15491. It will likely end up in a memory type that is `HOST_VISIBLE` and `HOST_COHERENT`
  15492. but not `HOST_CACHED` (meaning uncached, write-combined) and not `DEVICE_LOCAL` (meaning system RAM).
  15493. \code
  15494. VkBufferCreateInfo stagingBufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  15495. stagingBufferInfo.size = 65536;
  15496. stagingBufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  15497. VmaAllocationCreateInfo stagingAllocInfo = {};
  15498. stagingAllocInfo.usage = VMA_MEMORY_USAGE_AUTO;
  15499. stagingAllocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
  15500. VkBuffer stagingBuffer;
  15501. VmaAllocation stagingAllocation;
  15502. vmaCreateBuffer(allocator, &stagingBufferInfo, &stagingAllocInfo, &stagingBuffer, &stagingAllocation, nullptr);
  15503. \endcode
  15504. For more examples of creating different kinds of resources, see chapter \ref usage_patterns.
  15505. Usage values `VMA_MEMORY_USAGE_AUTO*` are legal to use only when the library knows
  15506. about the resource being created by having `VkBufferCreateInfo` / `VkImageCreateInfo` passed,
  15507. so they work with functions like: vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo() etc.
  15508. If you allocate raw memory using function vmaAllocateMemory(), you have to use other means of selecting
  15509. memory type, as described below.
  15510. \note
  15511. Old usage values (`VMA_MEMORY_USAGE_GPU_ONLY`, `VMA_MEMORY_USAGE_CPU_ONLY`,
  15512. `VMA_MEMORY_USAGE_CPU_TO_GPU`, `VMA_MEMORY_USAGE_GPU_TO_CPU`, `VMA_MEMORY_USAGE_CPU_COPY`)
  15513. are still available and work same way as in previous versions of the library
  15514. for backward compatibility, but they are not recommended.
  15515. \section choosing_memory_type_required_preferred_flags Required and preferred flags
  15516. You can specify more detailed requirements by filling members
  15517. VmaAllocationCreateInfo::requiredFlags and VmaAllocationCreateInfo::preferredFlags
  15518. with a combination of bits from enum `VkMemoryPropertyFlags`. For example,
  15519. if you want to create a buffer that will be persistently mapped on host (so it
  15520. must be `HOST_VISIBLE`) and preferably will also be `HOST_COHERENT` and `HOST_CACHED`,
  15521. use following code:
  15522. \code
  15523. VmaAllocationCreateInfo allocInfo = {};
  15524. allocInfo.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
  15525. allocInfo.preferredFlags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
  15526. allocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT;
  15527. VkBuffer buffer;
  15528. VmaAllocation allocation;
  15529. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  15530. \endcode
  15531. A memory type is chosen that has all the required flags and as many preferred
  15532. flags set as possible.
  15533. Value passed in VmaAllocationCreateInfo::usage is internally converted to a set of required and preferred flags,
  15534. plus some extra "magic" (heuristics).
  15535. \section choosing_memory_type_explicit_memory_types Explicit memory types
  15536. If you inspected memory types available on the physical device and you have
  15537. a preference for memory types that you want to use, you can fill member
  15538. VmaAllocationCreateInfo::memoryTypeBits. It is a bit mask, where each bit set
  15539. means that a memory type with that index is allowed to be used for the
  15540. allocation. Special value 0, just like `UINT32_MAX`, means there are no
  15541. restrictions to memory type index.
  15542. Please note that this member is NOT just a memory type index.
  15543. Still you can use it to choose just one, specific memory type.
  15544. For example, if you already determined that your buffer should be created in
  15545. memory type 2, use following code:
  15546. \code
  15547. uint32_t memoryTypeIndex = 2;
  15548. VmaAllocationCreateInfo allocInfo = {};
  15549. allocInfo.memoryTypeBits = 1u << memoryTypeIndex;
  15550. VkBuffer buffer;
  15551. VmaAllocation allocation;
  15552. vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
  15553. \endcode
  15554. \section choosing_memory_type_custom_memory_pools Custom memory pools
  15555. If you allocate from custom memory pool, all the ways of specifying memory
  15556. requirements described above are not applicable and the aforementioned members
  15557. of VmaAllocationCreateInfo structure are ignored. Memory type is selected
  15558. explicitly when creating the pool and then used to make all the allocations from
  15559. that pool. For further details, see \ref custom_memory_pools.
  15560. \section choosing_memory_type_dedicated_allocations Dedicated allocations
  15561. Memory for allocations is reserved out of larger block of `VkDeviceMemory`
  15562. allocated from Vulkan internally. That is the main feature of this whole library.
  15563. You can still request a separate memory block to be created for an allocation,
  15564. just like you would do in a trivial solution without using any allocator.
  15565. In that case, a buffer or image is always bound to that memory at offset 0.
  15566. This is called a "dedicated allocation".
  15567. You can explicitly request it by using flag #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  15568. The library can also internally decide to use dedicated allocation in some cases, e.g.:
  15569. - When the size of the allocation is large.
  15570. - When [VK_KHR_dedicated_allocation](@ref vk_khr_dedicated_allocation) extension is enabled
  15571. and it reports that dedicated allocation is required or recommended for the resource.
  15572. - When allocation of next big memory block fails due to not enough device memory,
  15573. but allocation with the exact requested size succeeds.
  15574. \page memory_mapping Memory mapping
  15575. To "map memory" in Vulkan means to obtain a CPU pointer to `VkDeviceMemory`,
  15576. to be able to read from it or write to it in CPU code.
  15577. Mapping is possible only of memory allocated from a memory type that has
  15578. `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag.
  15579. Functions `vkMapMemory()`, `vkUnmapMemory()` are designed for this purpose.
  15580. You can use them directly with memory allocated by this library,
  15581. but it is not recommended because of following issue:
  15582. Mapping the same `VkDeviceMemory` block multiple times is illegal - only one mapping at a time is allowed.
  15583. This includes mapping disjoint regions. Mapping is not reference-counted internally by Vulkan.
  15584. Because of this, Vulkan Memory Allocator provides following facilities:
  15585. \note If you want to be able to map an allocation, you need to specify one of the flags
  15586. #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT
  15587. in VmaAllocationCreateInfo::flags. These flags are required for an allocation to be mappable
  15588. when using #VMA_MEMORY_USAGE_AUTO or other `VMA_MEMORY_USAGE_AUTO*` enum values.
  15589. For other usage values they are ignored and every such allocation made in `HOST_VISIBLE` memory type is mappable,
  15590. but they can still be used for consistency.
  15591. \section memory_mapping_mapping_functions Mapping functions
  15592. The library provides following functions for mapping of a specific #VmaAllocation: vmaMapMemory(), vmaUnmapMemory().
  15593. They are safer and more convenient to use than standard Vulkan functions.
  15594. You can map an allocation multiple times simultaneously - mapping is reference-counted internally.
  15595. You can also map different allocations simultaneously regardless of whether they use the same `VkDeviceMemory` block.
  15596. The way it is implemented is that the library always maps entire memory block, not just region of the allocation.
  15597. For further details, see description of vmaMapMemory() function.
  15598. Example:
  15599. \code
  15600. // Having these objects initialized:
  15601. struct ConstantBuffer
  15602. {
  15603. ...
  15604. };
  15605. ConstantBuffer constantBufferData = ...
  15606. VmaAllocator allocator = ...
  15607. VkBuffer constantBuffer = ...
  15608. VmaAllocation constantBufferAllocation = ...
  15609. // You can map and fill your buffer using following code:
  15610. void* mappedData;
  15611. vmaMapMemory(allocator, constantBufferAllocation, &mappedData);
  15612. memcpy(mappedData, &constantBufferData, sizeof(constantBufferData));
  15613. vmaUnmapMemory(allocator, constantBufferAllocation);
  15614. \endcode
  15615. When mapping, you may see a warning from Vulkan validation layer similar to this one:
  15616. <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>
  15617. It happens because the library maps entire `VkDeviceMemory` block, where different
  15618. types of images and buffers may end up together, especially on GPUs with unified memory like Intel.
  15619. You can safely ignore it if you are sure you access only memory of the intended
  15620. object that you wanted to map.
  15621. \section memory_mapping_persistently_mapped_memory Persistently mapped memory
  15622. Keeping your memory persistently mapped is generally OK in Vulkan.
  15623. You don't need to unmap it before using its data on the GPU.
  15624. The library provides a special feature designed for that:
  15625. Allocations made with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag set in
  15626. VmaAllocationCreateInfo::flags stay mapped all the time,
  15627. so you can just access CPU pointer to it any time
  15628. without a need to call any "map" or "unmap" function.
  15629. Example:
  15630. \code
  15631. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  15632. bufCreateInfo.size = sizeof(ConstantBuffer);
  15633. bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  15634. VmaAllocationCreateInfo allocCreateInfo = {};
  15635. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  15636. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT |
  15637. VMA_ALLOCATION_CREATE_MAPPED_BIT;
  15638. VkBuffer buf;
  15639. VmaAllocation alloc;
  15640. VmaAllocationInfo allocInfo;
  15641. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  15642. // Buffer is already mapped. You can access its memory.
  15643. memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData));
  15644. \endcode
  15645. \note #VMA_ALLOCATION_CREATE_MAPPED_BIT by itself doesn't guarantee that the allocation will end up
  15646. in a mappable memory type.
  15647. For this, you need to also specify #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or
  15648. #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT.
  15649. #VMA_ALLOCATION_CREATE_MAPPED_BIT only guarantees that if the memory is `HOST_VISIBLE`, the allocation will be mapped on creation.
  15650. For an example of how to make use of this fact, see section \ref usage_patterns_advanced_data_uploading.
  15651. \section memory_mapping_cache_control Cache flush and invalidate
  15652. Memory in Vulkan doesn't need to be unmapped before using it on GPU,
  15653. but unless a memory types has `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT` flag set,
  15654. you need to manually **invalidate** cache before reading of mapped pointer
  15655. and **flush** cache after writing to mapped pointer.
  15656. Map/unmap operations don't do that automatically.
  15657. Vulkan provides following functions for this purpose `vkFlushMappedMemoryRanges()`,
  15658. `vkInvalidateMappedMemoryRanges()`, but this library provides more convenient
  15659. functions that refer to given allocation object: vmaFlushAllocation(),
  15660. vmaInvalidateAllocation(),
  15661. or multiple objects at once: vmaFlushAllocations(), vmaInvalidateAllocations().
  15662. Regions of memory specified for flush/invalidate must be aligned to
  15663. `VkPhysicalDeviceLimits::nonCoherentAtomSize`. This is automatically ensured by the library.
  15664. In any memory type that is `HOST_VISIBLE` but not `HOST_COHERENT`, all allocations
  15665. within blocks are aligned to this value, so their offsets are always multiply of
  15666. `nonCoherentAtomSize` and two different allocations never share same "line" of this size.
  15667. Also, Windows drivers from all 3 PC GPU vendors (AMD, Intel, NVIDIA)
  15668. currently provide `HOST_COHERENT` flag on all memory types that are
  15669. `HOST_VISIBLE`, so on PC you may not need to bother.
  15670. \page staying_within_budget Staying within budget
  15671. When developing a graphics-intensive game or program, it is important to avoid allocating
  15672. more GPU memory than it is physically available. When the memory is over-committed,
  15673. various bad things can happen, depending on the specific GPU, graphics driver, and
  15674. operating system:
  15675. - It may just work without any problems.
  15676. - The application may slow down because some memory blocks are moved to system RAM
  15677. and the GPU has to access them through PCI Express bus.
  15678. - A new allocation may take very long time to complete, even few seconds, and possibly
  15679. freeze entire system.
  15680. - The new allocation may fail with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  15681. - It may even result in GPU crash (TDR), observed as `VK_ERROR_DEVICE_LOST`
  15682. returned somewhere later.
  15683. \section staying_within_budget_querying_for_budget Querying for budget
  15684. To query for current memory usage and available budget, use function vmaGetHeapBudgets().
  15685. Returned structure #VmaBudget contains quantities expressed in bytes, per Vulkan memory heap.
  15686. Please note that this function returns different information and works faster than
  15687. vmaCalculateStatistics(). vmaGetHeapBudgets() can be called every frame or even before every
  15688. allocation, while vmaCalculateStatistics() is intended to be used rarely,
  15689. only to obtain statistical information, e.g. for debugging purposes.
  15690. It is recommended to use <b>VK_EXT_memory_budget</b> device extension to obtain information
  15691. about the budget from Vulkan device. VMA is able to use this extension automatically.
  15692. When not enabled, the allocator behaves same way, but then it estimates current usage
  15693. and available budget based on its internal information and Vulkan memory heap sizes,
  15694. which may be less precise. In order to use this extension:
  15695. 1. Make sure extensions VK_EXT_memory_budget and VK_KHR_get_physical_device_properties2
  15696. required by it are available and enable them. Please note that the first is a device
  15697. extension and the second is instance extension!
  15698. 2. Use flag #VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT when creating #VmaAllocator object.
  15699. 3. Make sure to call vmaSetCurrentFrameIndex() every frame. Budget is queried from
  15700. Vulkan inside of it to avoid overhead of querying it with every allocation.
  15701. \section staying_within_budget_controlling_memory_usage Controlling memory usage
  15702. There are many ways in which you can try to stay within the budget.
  15703. First, when making new allocation requires allocating a new memory block, the library
  15704. tries not to exceed the budget automatically. If a block with default recommended size
  15705. (e.g. 256 MB) would go over budget, a smaller block is allocated, possibly even
  15706. dedicated memory for just this resource.
  15707. If the size of the requested resource plus current memory usage is more than the
  15708. budget, by default the library still tries to create it, leaving it to the Vulkan
  15709. implementation whether the allocation succeeds or fails. You can change this behavior
  15710. by using #VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT flag. With it, the allocation is
  15711. not made if it would exceed the budget or if the budget is already exceeded.
  15712. VMA then tries to make the allocation from the next eligible Vulkan memory type.
  15713. The all of them fail, the call then fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  15714. Example usage pattern may be to pass the #VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT flag
  15715. when creating resources that are not essential for the application (e.g. the texture
  15716. of a specific object) and not to pass it when creating critically important resources
  15717. (e.g. render targets).
  15718. On AMD graphics cards there is a custom vendor extension available: <b>VK_AMD_memory_overallocation_behavior</b>
  15719. that allows to control the behavior of the Vulkan implementation in out-of-memory cases -
  15720. whether it should fail with an error code or still allow the allocation.
  15721. Usage of this extension involves only passing extra structure on Vulkan device creation,
  15722. so it is out of scope of this library.
  15723. Finally, you can also use #VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT flag to make sure
  15724. a new allocation is created only when it fits inside one of the existing memory blocks.
  15725. If it would require to allocate a new block, if fails instead with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  15726. This also ensures that the function call is very fast because it never goes to Vulkan
  15727. to obtain a new block.
  15728. \note Creating \ref custom_memory_pools with VmaPoolCreateInfo::minBlockCount
  15729. set to more than 0 will currently try to allocate memory blocks without checking whether they
  15730. fit within budget.
  15731. \page resource_aliasing Resource aliasing (overlap)
  15732. New explicit graphics APIs (Vulkan and Direct3D 12), thanks to manual memory
  15733. management, give an opportunity to alias (overlap) multiple resources in the
  15734. same region of memory - a feature not available in the old APIs (Direct3D 11, OpenGL).
  15735. It can be useful to save video memory, but it must be used with caution.
  15736. For example, if you know the flow of your whole render frame in advance, you
  15737. are going to use some intermediate textures or buffers only during a small range of render passes,
  15738. and you know these ranges don't overlap in time, you can bind these resources to
  15739. the same place in memory, even if they have completely different parameters (width, height, format etc.).
  15740. ![Resource aliasing (overlap)](../gfx/Aliasing.png)
  15741. Such scenario is possible using VMA, but you need to create your images manually.
  15742. Then you need to calculate parameters of an allocation to be made using formula:
  15743. - allocation size = max(size of each image)
  15744. - allocation alignment = max(alignment of each image)
  15745. - allocation memoryTypeBits = bitwise AND(memoryTypeBits of each image)
  15746. Following example shows two different images bound to the same place in memory,
  15747. allocated to fit largest of them.
  15748. \code
  15749. // A 512x512 texture to be sampled.
  15750. VkImageCreateInfo img1CreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
  15751. img1CreateInfo.imageType = VK_IMAGE_TYPE_2D;
  15752. img1CreateInfo.extent.width = 512;
  15753. img1CreateInfo.extent.height = 512;
  15754. img1CreateInfo.extent.depth = 1;
  15755. img1CreateInfo.mipLevels = 10;
  15756. img1CreateInfo.arrayLayers = 1;
  15757. img1CreateInfo.format = VK_FORMAT_R8G8B8A8_SRGB;
  15758. img1CreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  15759. img1CreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  15760. img1CreateInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
  15761. img1CreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
  15762. // A full screen texture to be used as color attachment.
  15763. VkImageCreateInfo img2CreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
  15764. img2CreateInfo.imageType = VK_IMAGE_TYPE_2D;
  15765. img2CreateInfo.extent.width = 1920;
  15766. img2CreateInfo.extent.height = 1080;
  15767. img2CreateInfo.extent.depth = 1;
  15768. img2CreateInfo.mipLevels = 1;
  15769. img2CreateInfo.arrayLayers = 1;
  15770. img2CreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
  15771. img2CreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  15772. img2CreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  15773. img2CreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  15774. img2CreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
  15775. VkImage img1;
  15776. res = vkCreateImage(device, &img1CreateInfo, nullptr, &img1);
  15777. VkImage img2;
  15778. res = vkCreateImage(device, &img2CreateInfo, nullptr, &img2);
  15779. VkMemoryRequirements img1MemReq;
  15780. vkGetImageMemoryRequirements(device, img1, &img1MemReq);
  15781. VkMemoryRequirements img2MemReq;
  15782. vkGetImageMemoryRequirements(device, img2, &img2MemReq);
  15783. VkMemoryRequirements finalMemReq = {};
  15784. finalMemReq.size = std::max(img1MemReq.size, img2MemReq.size);
  15785. finalMemReq.alignment = std::max(img1MemReq.alignment, img2MemReq.alignment);
  15786. finalMemReq.memoryTypeBits = img1MemReq.memoryTypeBits & img2MemReq.memoryTypeBits;
  15787. // Validate if(finalMemReq.memoryTypeBits != 0)
  15788. VmaAllocationCreateInfo allocCreateInfo = {};
  15789. allocCreateInfo.preferredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
  15790. VmaAllocation alloc;
  15791. res = vmaAllocateMemory(allocator, &finalMemReq, &allocCreateInfo, &alloc, nullptr);
  15792. res = vmaBindImageMemory(allocator, alloc, img1);
  15793. res = vmaBindImageMemory(allocator, alloc, img2);
  15794. // You can use img1, img2 here, but not at the same time!
  15795. vmaFreeMemory(allocator, alloc);
  15796. vkDestroyImage(allocator, img2, nullptr);
  15797. vkDestroyImage(allocator, img1, nullptr);
  15798. \endcode
  15799. VMA also provides convenience functions that create a buffer or image and bind it to memory
  15800. represented by an existing #VmaAllocation:
  15801. vmaCreateAliasingBuffer(), vmaCreateAliasingBuffer2(),
  15802. vmaCreateAliasingImage(), vmaCreateAliasingImage2().
  15803. Versions with "2" offer additional parameter `allocationLocalOffset`.
  15804. Remember that using resources that alias in memory requires proper synchronization.
  15805. You need to issue a memory barrier to make sure commands that use `img1` and `img2`
  15806. don't overlap on GPU timeline.
  15807. You also need to treat a resource after aliasing as uninitialized - containing garbage data.
  15808. For example, if you use `img1` and then want to use `img2`, you need to issue
  15809. an image memory barrier for `img2` with `oldLayout` = `VK_IMAGE_LAYOUT_UNDEFINED`.
  15810. Additional considerations:
  15811. - Vulkan also allows to interpret contents of memory between aliasing resources consistently in some cases.
  15812. See chapter 11.8. "Memory Aliasing" of Vulkan specification or `VK_IMAGE_CREATE_ALIAS_BIT` flag.
  15813. - You can create more complex layout where different images and buffers are bound
  15814. at different offsets inside one large allocation. For example, one can imagine
  15815. a big texture used in some render passes, aliasing with a set of many small buffers
  15816. used between in some further passes. To bind a resource at non-zero offset in an allocation,
  15817. use vmaBindBufferMemory2() / vmaBindImageMemory2().
  15818. - Before allocating memory for the resources you want to alias, check `memoryTypeBits`
  15819. returned in memory requirements of each resource to make sure the bits overlap.
  15820. Some GPUs may expose multiple memory types suitable e.g. only for buffers or
  15821. images with `COLOR_ATTACHMENT` usage, so the sets of memory types supported by your
  15822. resources may be disjoint. Aliasing them is not possible in that case.
  15823. \page custom_memory_pools Custom memory pools
  15824. A memory pool contains a number of `VkDeviceMemory` blocks.
  15825. The library automatically creates and manages default pool for each memory type available on the device.
  15826. Default memory pool automatically grows in size.
  15827. Size of allocated blocks is also variable and managed automatically.
  15828. You can create custom pool and allocate memory out of it.
  15829. It can be useful if you want to:
  15830. - Keep certain kind of allocations separate from others.
  15831. - Enforce particular, fixed size of Vulkan memory blocks.
  15832. - Limit maximum amount of Vulkan memory allocated for that pool.
  15833. - Reserve minimum or fixed amount of Vulkan memory always preallocated for that pool.
  15834. - Use extra parameters for a set of your allocations that are available in #VmaPoolCreateInfo but not in
  15835. #VmaAllocationCreateInfo - e.g., custom minimum alignment, custom `pNext` chain.
  15836. - Perform defragmentation on a specific subset of your allocations.
  15837. To use custom memory pools:
  15838. -# Fill VmaPoolCreateInfo structure.
  15839. -# Call vmaCreatePool() to obtain #VmaPool handle.
  15840. -# When making an allocation, set VmaAllocationCreateInfo::pool to this handle.
  15841. You don't need to specify any other parameters of this structure, like `usage`.
  15842. Example:
  15843. \code
  15844. // Find memoryTypeIndex for the pool.
  15845. VkBufferCreateInfo sampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  15846. sampleBufCreateInfo.size = 0x10000; // Doesn't matter.
  15847. sampleBufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  15848. VmaAllocationCreateInfo sampleAllocCreateInfo = {};
  15849. sampleAllocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  15850. uint32_t memTypeIndex;
  15851. VkResult res = vmaFindMemoryTypeIndexForBufferInfo(allocator,
  15852. &sampleBufCreateInfo, &sampleAllocCreateInfo, &memTypeIndex);
  15853. // Check res...
  15854. // Create a pool that can have at most 2 blocks, 128 MiB each.
  15855. VmaPoolCreateInfo poolCreateInfo = {};
  15856. poolCreateInfo.memoryTypeIndex = memTypeIndex;
  15857. poolCreateInfo.blockSize = 128ull * 1024 * 1024;
  15858. poolCreateInfo.maxBlockCount = 2;
  15859. VmaPool pool;
  15860. res = vmaCreatePool(allocator, &poolCreateInfo, &pool);
  15861. // Check res...
  15862. // Allocate a buffer out of it.
  15863. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  15864. bufCreateInfo.size = 1024;
  15865. bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  15866. VmaAllocationCreateInfo allocCreateInfo = {};
  15867. allocCreateInfo.pool = pool;
  15868. VkBuffer buf;
  15869. VmaAllocation alloc;
  15870. res = vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, nullptr);
  15871. // Check res...
  15872. \endcode
  15873. You have to free all allocations made from this pool before destroying it.
  15874. \code
  15875. vmaDestroyBuffer(allocator, buf, alloc);
  15876. vmaDestroyPool(allocator, pool);
  15877. \endcode
  15878. New versions of this library support creating dedicated allocations in custom pools.
  15879. It is supported only when VmaPoolCreateInfo::blockSize = 0.
  15880. To use this feature, set VmaAllocationCreateInfo::pool to the pointer to your custom pool and
  15881. VmaAllocationCreateInfo::flags to #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  15882. \note Excessive use of custom pools is a common mistake when using this library.
  15883. Custom pools may be useful for special purposes - when you want to
  15884. keep certain type of resources separate e.g. to reserve minimum amount of memory
  15885. for them or limit maximum amount of memory they can occupy. For most
  15886. resources this is not needed and so it is not recommended to create #VmaPool
  15887. objects and allocations out of them. Allocating from the default pool is sufficient.
  15888. \section custom_memory_pools_MemTypeIndex Choosing memory type index
  15889. When creating a pool, you must explicitly specify memory type index.
  15890. To find the one suitable for your buffers or images, you can use helper functions
  15891. vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo().
  15892. You need to provide structures with example parameters of buffers or images
  15893. that you are going to create in that pool.
  15894. \code
  15895. VkBufferCreateInfo exampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  15896. exampleBufCreateInfo.size = 1024; // Doesn't matter
  15897. exampleBufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  15898. VmaAllocationCreateInfo allocCreateInfo = {};
  15899. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  15900. uint32_t memTypeIndex;
  15901. vmaFindMemoryTypeIndexForBufferInfo(allocator, &exampleBufCreateInfo, &allocCreateInfo, &memTypeIndex);
  15902. VmaPoolCreateInfo poolCreateInfo = {};
  15903. poolCreateInfo.memoryTypeIndex = memTypeIndex;
  15904. // ...
  15905. \endcode
  15906. When creating buffers/images allocated in that pool, provide following parameters:
  15907. - `VkBufferCreateInfo`: Prefer to pass same parameters as above.
  15908. Otherwise you risk creating resources in a memory type that is not suitable for them, which may result in undefined behavior.
  15909. Using different `VK_BUFFER_USAGE_` flags may work, but you shouldn't create images in a pool intended for buffers
  15910. or the other way around.
  15911. - VmaAllocationCreateInfo: You don't need to pass same parameters. Fill only `pool` member.
  15912. Other members are ignored anyway.
  15913. \section linear_algorithm Linear allocation algorithm
  15914. Each Vulkan memory block managed by this library has accompanying metadata that
  15915. keeps track of used and unused regions. By default, the metadata structure and
  15916. algorithm tries to find best place for new allocations among free regions to
  15917. optimize memory usage. This way you can allocate and free objects in any order.
  15918. ![Default allocation algorithm](../gfx/Linear_allocator_1_algo_default.png)
  15919. Sometimes there is a need to use simpler, linear allocation algorithm. You can
  15920. create custom pool that uses such algorithm by adding flag
  15921. #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT to VmaPoolCreateInfo::flags while creating
  15922. #VmaPool object. Then an alternative metadata management is used. It always
  15923. creates new allocations after last one and doesn't reuse free regions after
  15924. allocations freed in the middle. It results in better allocation performance and
  15925. less memory consumed by metadata.
  15926. ![Linear allocation algorithm](../gfx/Linear_allocator_2_algo_linear.png)
  15927. With this one flag, you can create a custom pool that can be used in many ways:
  15928. free-at-once, stack, double stack, and ring buffer. See below for details.
  15929. You don't need to specify explicitly which of these options you are going to use - it is detected automatically.
  15930. \subsection linear_algorithm_free_at_once Free-at-once
  15931. In a pool that uses linear algorithm, you still need to free all the allocations
  15932. individually, e.g. by using vmaFreeMemory() or vmaDestroyBuffer(). You can free
  15933. them in any order. New allocations are always made after last one - free space
  15934. in the middle is not reused. However, when you release all the allocation and
  15935. the pool becomes empty, allocation starts from the beginning again. This way you
  15936. can use linear algorithm to speed up creation of allocations that you are going
  15937. to release all at once.
  15938. ![Free-at-once](../gfx/Linear_allocator_3_free_at_once.png)
  15939. This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount
  15940. value that allows multiple memory blocks.
  15941. \subsection linear_algorithm_stack Stack
  15942. When you free an allocation that was created last, its space can be reused.
  15943. Thanks to this, if you always release allocations in the order opposite to their
  15944. creation (LIFO - Last In First Out), you can achieve behavior of a stack.
  15945. ![Stack](../gfx/Linear_allocator_4_stack.png)
  15946. This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount
  15947. value that allows multiple memory blocks.
  15948. \subsection linear_algorithm_double_stack Double stack
  15949. The space reserved by a custom pool with linear algorithm may be used by two
  15950. stacks:
  15951. - First, default one, growing up from offset 0.
  15952. - Second, "upper" one, growing down from the end towards lower offsets.
  15953. To make allocation from the upper stack, add flag #VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT
  15954. to VmaAllocationCreateInfo::flags.
  15955. ![Double stack](../gfx/Linear_allocator_7_double_stack.png)
  15956. Double stack is available only in pools with one memory block -
  15957. VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined.
  15958. When the two stacks' ends meet so there is not enough space between them for a
  15959. new allocation, such allocation fails with usual
  15960. `VK_ERROR_OUT_OF_DEVICE_MEMORY` error.
  15961. \subsection linear_algorithm_ring_buffer Ring buffer
  15962. When you free some allocations from the beginning and there is not enough free space
  15963. for a new one at the end of a pool, allocator's "cursor" wraps around to the
  15964. beginning and starts allocation there. Thanks to this, if you always release
  15965. allocations in the same order as you created them (FIFO - First In First Out),
  15966. you can achieve behavior of a ring buffer / queue.
  15967. ![Ring buffer](../gfx/Linear_allocator_5_ring_buffer.png)
  15968. Ring buffer is available only in pools with one memory block -
  15969. VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined.
  15970. \note \ref defragmentation is not supported in custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT.
  15971. \page defragmentation Defragmentation
  15972. Interleaved allocations and deallocations of many objects of varying size can
  15973. cause fragmentation over time, which can lead to a situation where the library is unable
  15974. to find a continuous range of free memory for a new allocation despite there is
  15975. enough free space, just scattered across many small free ranges between existing
  15976. allocations.
  15977. To mitigate this problem, you can use defragmentation feature.
  15978. It doesn't happen automatically though and needs your cooperation,
  15979. because VMA is a low level library that only allocates memory.
  15980. It cannot recreate buffers and images in a new place as it doesn't remember the contents of `VkBufferCreateInfo` / `VkImageCreateInfo` structures.
  15981. It cannot copy their contents as it doesn't record any commands to a command buffer.
  15982. Example:
  15983. \code
  15984. VmaDefragmentationInfo defragInfo = {};
  15985. defragInfo.pool = myPool;
  15986. defragInfo.flags = VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT;
  15987. VmaDefragmentationContext defragCtx;
  15988. VkResult res = vmaBeginDefragmentation(allocator, &defragInfo, &defragCtx);
  15989. // Check res...
  15990. for(;;)
  15991. {
  15992. VmaDefragmentationPassMoveInfo pass;
  15993. res = vmaBeginDefragmentationPass(allocator, defragCtx, &pass);
  15994. if(res == VK_SUCCESS)
  15995. break;
  15996. else if(res != VK_INCOMPLETE)
  15997. // Handle error...
  15998. for(uint32_t i = 0; i < pass.moveCount; ++i)
  15999. {
  16000. // Inspect pass.pMoves[i].srcAllocation, identify what buffer/image it represents.
  16001. VmaAllocationInfo allocInfo;
  16002. vmaGetAllocationInfo(allocator, pass.pMoves[i].srcAllocation, &allocInfo);
  16003. MyEngineResourceData* resData = (MyEngineResourceData*)allocInfo.pUserData;
  16004. // Recreate and bind this buffer/image at: pass.pMoves[i].dstMemory, pass.pMoves[i].dstOffset.
  16005. VkImageCreateInfo imgCreateInfo = ...
  16006. VkImage newImg;
  16007. res = vkCreateImage(device, &imgCreateInfo, nullptr, &newImg);
  16008. // Check res...
  16009. res = vmaBindImageMemory(allocator, pass.pMoves[i].dstTmpAllocation, newImg);
  16010. // Check res...
  16011. // Issue a vkCmdCopyBuffer/vkCmdCopyImage to copy its content to the new place.
  16012. vkCmdCopyImage(cmdBuf, resData->img, ..., newImg, ...);
  16013. }
  16014. // Make sure the copy commands finished executing.
  16015. vkWaitForFences(...);
  16016. // Destroy old buffers/images bound with pass.pMoves[i].srcAllocation.
  16017. for(uint32_t i = 0; i < pass.moveCount; ++i)
  16018. {
  16019. // ...
  16020. vkDestroyImage(device, resData->img, nullptr);
  16021. }
  16022. // Update appropriate descriptors to point to the new places...
  16023. res = vmaEndDefragmentationPass(allocator, defragCtx, &pass);
  16024. if(res == VK_SUCCESS)
  16025. break;
  16026. else if(res != VK_INCOMPLETE)
  16027. // Handle error...
  16028. }
  16029. vmaEndDefragmentation(allocator, defragCtx, nullptr);
  16030. \endcode
  16031. Although functions like vmaCreateBuffer(), vmaCreateImage(), vmaDestroyBuffer(), vmaDestroyImage()
  16032. create/destroy an allocation and a buffer/image at once, these are just a shortcut for
  16033. creating the resource, allocating memory, and binding them together.
  16034. Defragmentation works on memory allocations only. You must handle the rest manually.
  16035. Defragmentation is an iterative process that should repreat "passes" as long as related functions
  16036. return `VK_INCOMPLETE` not `VK_SUCCESS`.
  16037. In each pass:
  16038. 1. vmaBeginDefragmentationPass() function call:
  16039. - Calculates and returns the list of allocations to be moved in this pass.
  16040. Note this can be a time-consuming process.
  16041. - Reserves destination memory for them by creating temporary destination allocations
  16042. that you can query for their `VkDeviceMemory` + offset using vmaGetAllocationInfo().
  16043. 2. Inside the pass, **you should**:
  16044. - Inspect the returned list of allocations to be moved.
  16045. - Create new buffers/images and bind them at the returned destination temporary allocations.
  16046. - Copy data from source to destination resources if necessary.
  16047. - Destroy the source buffers/images, but NOT their allocations.
  16048. 3. vmaEndDefragmentationPass() function call:
  16049. - Frees the source memory reserved for the allocations that are moved.
  16050. - Modifies source #VmaAllocation objects that are moved to point to the destination reserved memory.
  16051. - Frees `VkDeviceMemory` blocks that became empty.
  16052. Unlike in previous iterations of the defragmentation API, there is no list of "movable" allocations passed as a parameter.
  16053. Defragmentation algorithm tries to move all suitable allocations.
  16054. You can, however, refuse to move some of them inside a defragmentation pass, by setting
  16055. `pass.pMoves[i].operation` to #VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE.
  16056. This is not recommended and may result in suboptimal packing of the allocations after defragmentation.
  16057. If you cannot ensure any allocation can be moved, it is better to keep movable allocations separate in a custom pool.
  16058. Inside a pass, for each allocation that should be moved:
  16059. - You should copy its data from the source to the destination place by calling e.g. `vkCmdCopyBuffer()`, `vkCmdCopyImage()`.
  16060. - You need to make sure these commands finished executing before destroying the source buffers/images and before calling vmaEndDefragmentationPass().
  16061. - If a resource doesn't contain any meaningful data, e.g. it is a transient color attachment image to be cleared,
  16062. filled, and used temporarily in each rendering frame, you can just recreate this image
  16063. without copying its data.
  16064. - If the resource is in `HOST_VISIBLE` and `HOST_CACHED` memory, you can copy its data on the CPU
  16065. using `memcpy()`.
  16066. - If you cannot move the allocation, you can set `pass.pMoves[i].operation` to #VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE.
  16067. This will cancel the move.
  16068. - vmaEndDefragmentationPass() will then free the destination memory
  16069. not the source memory of the allocation, leaving it unchanged.
  16070. - If you decide the allocation is unimportant and can be destroyed instead of moved (e.g. it wasn't used for long time),
  16071. you can set `pass.pMoves[i].operation` to #VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY.
  16072. - vmaEndDefragmentationPass() will then free both source and destination memory, and will destroy the source #VmaAllocation object.
  16073. You can defragment a specific custom pool by setting VmaDefragmentationInfo::pool
  16074. (like in the example above) or all the default pools by setting this member to null.
  16075. Defragmentation is always performed in each pool separately.
  16076. Allocations are never moved between different Vulkan memory types.
  16077. The size of the destination memory reserved for a moved allocation is the same as the original one.
  16078. Alignment of an allocation as it was determined using `vkGetBufferMemoryRequirements()` etc. is also respected after defragmentation.
  16079. Buffers/images should be recreated with the same `VkBufferCreateInfo` / `VkImageCreateInfo` parameters as the original ones.
  16080. You can perform the defragmentation incrementally to limit the number of allocations and bytes to be moved
  16081. in each pass, e.g. to call it in sync with render frames and not to experience too big hitches.
  16082. See members: VmaDefragmentationInfo::maxBytesPerPass, VmaDefragmentationInfo::maxAllocationsPerPass.
  16083. It is also safe to perform the defragmentation asynchronously to render frames and other Vulkan and VMA
  16084. usage, possibly from multiple threads, with the exception that allocations
  16085. returned in VmaDefragmentationPassMoveInfo::pMoves shouldn't be destroyed until the defragmentation pass is ended.
  16086. <b>Mapping</b> is preserved on allocations that are moved during defragmentation.
  16087. Whether through #VMA_ALLOCATION_CREATE_MAPPED_BIT or vmaMapMemory(), the allocations
  16088. are mapped at their new place. Of course, pointer to the mapped data changes, so it needs to be queried
  16089. using VmaAllocationInfo::pMappedData.
  16090. \note Defragmentation is not supported in custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT.
  16091. \page statistics Statistics
  16092. This library contains several functions that return information about its internal state,
  16093. especially the amount of memory allocated from Vulkan.
  16094. \section statistics_numeric_statistics Numeric statistics
  16095. If you need to obtain basic statistics about memory usage per heap, together with current budget,
  16096. you can call function vmaGetHeapBudgets() and inspect structure #VmaBudget.
  16097. This is useful to keep track of memory usage and stay within budget
  16098. (see also \ref staying_within_budget).
  16099. Example:
  16100. \code
  16101. uint32_t heapIndex = ...
  16102. VmaBudget budgets[VK_MAX_MEMORY_HEAPS];
  16103. vmaGetHeapBudgets(allocator, budgets);
  16104. printf("My heap currently has %u allocations taking %llu B,\n",
  16105. budgets[heapIndex].statistics.allocationCount,
  16106. budgets[heapIndex].statistics.allocationBytes);
  16107. printf("allocated out of %u Vulkan device memory blocks taking %llu B,\n",
  16108. budgets[heapIndex].statistics.blockCount,
  16109. budgets[heapIndex].statistics.blockBytes);
  16110. printf("Vulkan reports total usage %llu B with budget %llu B.\n",
  16111. budgets[heapIndex].usage,
  16112. budgets[heapIndex].budget);
  16113. \endcode
  16114. You can query for more detailed statistics per memory heap, type, and totals,
  16115. including minimum and maximum allocation size and unused range size,
  16116. by calling function vmaCalculateStatistics() and inspecting structure #VmaTotalStatistics.
  16117. This function is slower though, as it has to traverse all the internal data structures,
  16118. so it should be used only for debugging purposes.
  16119. You can query for statistics of a custom pool using function vmaGetPoolStatistics()
  16120. or vmaCalculatePoolStatistics().
  16121. You can query for information about a specific allocation using function vmaGetAllocationInfo().
  16122. It fill structure #VmaAllocationInfo.
  16123. \section statistics_json_dump JSON dump
  16124. You can dump internal state of the allocator to a string in JSON format using function vmaBuildStatsString().
  16125. The result is guaranteed to be correct JSON.
  16126. It uses ANSI encoding.
  16127. Any strings provided by user (see [Allocation names](@ref allocation_names))
  16128. are copied as-is and properly escaped for JSON, so if they use UTF-8, ISO-8859-2 or any other encoding,
  16129. this JSON string can be treated as using this encoding.
  16130. It must be freed using function vmaFreeStatsString().
  16131. The format of this JSON string is not part of official documentation of the library,
  16132. but it will not change in backward-incompatible way without increasing library major version number
  16133. and appropriate mention in changelog.
  16134. The JSON string contains all the data that can be obtained using vmaCalculateStatistics().
  16135. It can also contain detailed map of allocated memory blocks and their regions -
  16136. free and occupied by allocations.
  16137. This allows e.g. to visualize the memory or assess fragmentation.
  16138. \page allocation_annotation Allocation names and user data
  16139. \section allocation_user_data Allocation user data
  16140. You can annotate allocations with your own information, e.g. for debugging purposes.
  16141. To do that, fill VmaAllocationCreateInfo::pUserData field when creating
  16142. an allocation. It is an opaque `void*` pointer. You can use it e.g. as a pointer,
  16143. some handle, index, key, ordinal number or any other value that would associate
  16144. the allocation with your custom metadata.
  16145. It is useful to identify appropriate data structures in your engine given #VmaAllocation,
  16146. e.g. when doing \ref defragmentation.
  16147. \code
  16148. VkBufferCreateInfo bufCreateInfo = ...
  16149. MyBufferMetadata* pMetadata = CreateBufferMetadata();
  16150. VmaAllocationCreateInfo allocCreateInfo = {};
  16151. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  16152. allocCreateInfo.pUserData = pMetadata;
  16153. VkBuffer buffer;
  16154. VmaAllocation allocation;
  16155. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buffer, &allocation, nullptr);
  16156. \endcode
  16157. The pointer may be later retrieved as VmaAllocationInfo::pUserData:
  16158. \code
  16159. VmaAllocationInfo allocInfo;
  16160. vmaGetAllocationInfo(allocator, allocation, &allocInfo);
  16161. MyBufferMetadata* pMetadata = (MyBufferMetadata*)allocInfo.pUserData;
  16162. \endcode
  16163. It can also be changed using function vmaSetAllocationUserData().
  16164. Values of (non-zero) allocations' `pUserData` are printed in JSON report created by
  16165. vmaBuildStatsString() in hexadecimal form.
  16166. \section allocation_names Allocation names
  16167. An allocation can also carry a null-terminated string, giving a name to the allocation.
  16168. To set it, call vmaSetAllocationName().
  16169. The library creates internal copy of the string, so the pointer you pass doesn't need
  16170. to be valid for whole lifetime of the allocation. You can free it after the call.
  16171. \code
  16172. std::string imageName = "Texture: ";
  16173. imageName += fileName;
  16174. vmaSetAllocationName(allocator, allocation, imageName.c_str());
  16175. \endcode
  16176. The string can be later retrieved by inspecting VmaAllocationInfo::pName.
  16177. It is also printed in JSON report created by vmaBuildStatsString().
  16178. \note Setting string name to VMA allocation doesn't automatically set it to the Vulkan buffer or image created with it.
  16179. You must do it manually using an extension like VK_EXT_debug_utils, which is independent of this library.
  16180. \page virtual_allocator Virtual allocator
  16181. As an extra feature, the core allocation algorithm of the library is exposed through a simple and convenient API of "virtual allocator".
  16182. It doesn't allocate any real GPU memory. It just keeps track of used and free regions of a "virtual block".
  16183. You can use it to allocate your own memory or other objects, even completely unrelated to Vulkan.
  16184. A common use case is sub-allocation of pieces of one large GPU buffer.
  16185. \section virtual_allocator_creating_virtual_block Creating virtual block
  16186. To use this functionality, there is no main "allocator" object.
  16187. You don't need to have #VmaAllocator object created.
  16188. All you need to do is to create a separate #VmaVirtualBlock object for each block of memory you want to be managed by the allocator:
  16189. -# Fill in #VmaVirtualBlockCreateInfo structure.
  16190. -# Call vmaCreateVirtualBlock(). Get new #VmaVirtualBlock object.
  16191. Example:
  16192. \code
  16193. VmaVirtualBlockCreateInfo blockCreateInfo = {};
  16194. blockCreateInfo.size = 1048576; // 1 MB
  16195. VmaVirtualBlock block;
  16196. VkResult res = vmaCreateVirtualBlock(&blockCreateInfo, &block);
  16197. \endcode
  16198. \section virtual_allocator_making_virtual_allocations Making virtual allocations
  16199. #VmaVirtualBlock object contains internal data structure that keeps track of free and occupied regions
  16200. using the same code as the main Vulkan memory allocator.
  16201. Similarly to #VmaAllocation for standard GPU allocations, there is #VmaVirtualAllocation type
  16202. that represents an opaque handle to an allocation within the virtual block.
  16203. In order to make such allocation:
  16204. -# Fill in #VmaVirtualAllocationCreateInfo structure.
  16205. -# Call vmaVirtualAllocate(). Get new #VmaVirtualAllocation object that represents the allocation.
  16206. You can also receive `VkDeviceSize offset` that was assigned to the allocation.
  16207. Example:
  16208. \code
  16209. VmaVirtualAllocationCreateInfo allocCreateInfo = {};
  16210. allocCreateInfo.size = 4096; // 4 KB
  16211. VmaVirtualAllocation alloc;
  16212. VkDeviceSize offset;
  16213. res = vmaVirtualAllocate(block, &allocCreateInfo, &alloc, &offset);
  16214. if(res == VK_SUCCESS)
  16215. {
  16216. // Use the 4 KB of your memory starting at offset.
  16217. }
  16218. else
  16219. {
  16220. // Allocation failed - no space for it could be found. Handle this error!
  16221. }
  16222. \endcode
  16223. \section virtual_allocator_deallocation Deallocation
  16224. When no longer needed, an allocation can be freed by calling vmaVirtualFree().
  16225. You can only pass to this function an allocation that was previously returned by vmaVirtualAllocate()
  16226. called for the same #VmaVirtualBlock.
  16227. When whole block is no longer needed, the block object can be released by calling vmaDestroyVirtualBlock().
  16228. All allocations must be freed before the block is destroyed, which is checked internally by an assert.
  16229. However, if you don't want to call vmaVirtualFree() for each allocation, you can use vmaClearVirtualBlock() to free them all at once -
  16230. a feature not available in normal Vulkan memory allocator. Example:
  16231. \code
  16232. vmaVirtualFree(block, alloc);
  16233. vmaDestroyVirtualBlock(block);
  16234. \endcode
  16235. \section virtual_allocator_allocation_parameters Allocation parameters
  16236. You can attach a custom pointer to each allocation by using vmaSetVirtualAllocationUserData().
  16237. Its default value is null.
  16238. It can be used to store any data that needs to be associated with that allocation - e.g. an index, a handle, or a pointer to some
  16239. larger data structure containing more information. Example:
  16240. \code
  16241. struct CustomAllocData
  16242. {
  16243. std::string m_AllocName;
  16244. };
  16245. CustomAllocData* allocData = new CustomAllocData();
  16246. allocData->m_AllocName = "My allocation 1";
  16247. vmaSetVirtualAllocationUserData(block, alloc, allocData);
  16248. \endcode
  16249. The pointer can later be fetched, along with allocation offset and size, by passing the allocation handle to function
  16250. vmaGetVirtualAllocationInfo() and inspecting returned structure #VmaVirtualAllocationInfo.
  16251. If you allocated a new object to be used as the custom pointer, don't forget to delete that object before freeing the allocation!
  16252. Example:
  16253. \code
  16254. VmaVirtualAllocationInfo allocInfo;
  16255. vmaGetVirtualAllocationInfo(block, alloc, &allocInfo);
  16256. delete (CustomAllocData*)allocInfo.pUserData;
  16257. vmaVirtualFree(block, alloc);
  16258. \endcode
  16259. \section virtual_allocator_alignment_and_units Alignment and units
  16260. It feels natural to express sizes and offsets in bytes.
  16261. If an offset of an allocation needs to be aligned to a multiply of some number (e.g. 4 bytes), you can fill optional member
  16262. VmaVirtualAllocationCreateInfo::alignment to request it. Example:
  16263. \code
  16264. VmaVirtualAllocationCreateInfo allocCreateInfo = {};
  16265. allocCreateInfo.size = 4096; // 4 KB
  16266. allocCreateInfo.alignment = 4; // Returned offset must be a multiply of 4 B
  16267. VmaVirtualAllocation alloc;
  16268. res = vmaVirtualAllocate(block, &allocCreateInfo, &alloc, nullptr);
  16269. \endcode
  16270. Alignments of different allocations made from one block may vary.
  16271. However, if all alignments and sizes are always multiply of some size e.g. 4 B or `sizeof(MyDataStruct)`,
  16272. you can express all sizes, alignments, and offsets in multiples of that size instead of individual bytes.
  16273. It might be more convenient, but you need to make sure to use this new unit consistently in all the places:
  16274. - VmaVirtualBlockCreateInfo::size
  16275. - VmaVirtualAllocationCreateInfo::size and VmaVirtualAllocationCreateInfo::alignment
  16276. - Using offset returned by vmaVirtualAllocate() or in VmaVirtualAllocationInfo::offset
  16277. \section virtual_allocator_statistics Statistics
  16278. You can obtain statistics of a virtual block using vmaGetVirtualBlockStatistics()
  16279. (to get brief statistics that are fast to calculate)
  16280. or vmaCalculateVirtualBlockStatistics() (to get more detailed statistics, slower to calculate).
  16281. The functions fill structures #VmaStatistics, #VmaDetailedStatistics respectively - same as used by the normal Vulkan memory allocator.
  16282. Example:
  16283. \code
  16284. VmaStatistics stats;
  16285. vmaGetVirtualBlockStatistics(block, &stats);
  16286. printf("My virtual block has %llu bytes used by %u virtual allocations\n",
  16287. stats.allocationBytes, stats.allocationCount);
  16288. \endcode
  16289. You can also request a full list of allocations and free regions as a string in JSON format by calling
  16290. vmaBuildVirtualBlockStatsString().
  16291. Returned string must be later freed using vmaFreeVirtualBlockStatsString().
  16292. The format of this string differs from the one returned by the main Vulkan allocator, but it is similar.
  16293. \section virtual_allocator_additional_considerations Additional considerations
  16294. The "virtual allocator" functionality is implemented on a level of individual memory blocks.
  16295. Keeping track of a whole collection of blocks, allocating new ones when out of free space,
  16296. deleting empty ones, and deciding which one to try first for a new allocation must be implemented by the user.
  16297. Alternative allocation algorithms are supported, just like in custom pools of the real GPU memory.
  16298. See enum #VmaVirtualBlockCreateFlagBits to learn how to specify them (e.g. #VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT).
  16299. You can find their description in chapter \ref custom_memory_pools.
  16300. Allocation strategies are also supported.
  16301. See enum #VmaVirtualAllocationCreateFlagBits to learn how to specify them (e.g. #VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT).
  16302. Following features are supported only by the allocator of the real GPU memory and not by virtual allocations:
  16303. buffer-image granularity, `VMA_DEBUG_MARGIN`, `VMA_MIN_ALIGNMENT`.
  16304. \page debugging_memory_usage Debugging incorrect memory usage
  16305. If you suspect a bug with memory usage, like usage of uninitialized memory or
  16306. memory being overwritten out of bounds of an allocation,
  16307. you can use debug features of this library to verify this.
  16308. \section debugging_memory_usage_initialization Memory initialization
  16309. If you experience a bug with incorrect and nondeterministic data in your program and you suspect uninitialized memory to be used,
  16310. you can enable automatic memory initialization to verify this.
  16311. To do it, define macro `VMA_DEBUG_INITIALIZE_ALLOCATIONS` to 1.
  16312. \code
  16313. #define VMA_DEBUG_INITIALIZE_ALLOCATIONS 1
  16314. #include "vk_mem_alloc.h"
  16315. \endcode
  16316. It makes memory of new allocations initialized to bit pattern `0xDCDCDCDC`.
  16317. Before an allocation is destroyed, its memory is filled with bit pattern `0xEFEFEFEF`.
  16318. Memory is automatically mapped and unmapped if necessary.
  16319. If you find these values while debugging your program, good chances are that you incorrectly
  16320. read Vulkan memory that is allocated but not initialized, or already freed, respectively.
  16321. Memory initialization works only with memory types that are `HOST_VISIBLE` and with allocations that can be mapped.
  16322. It works also with dedicated allocations.
  16323. \section debugging_memory_usage_margins Margins
  16324. By default, allocations are laid out in memory blocks next to each other if possible
  16325. (considering required alignment, `bufferImageGranularity`, and `nonCoherentAtomSize`).
  16326. ![Allocations without margin](../gfx/Margins_1.png)
  16327. Define macro `VMA_DEBUG_MARGIN` to some non-zero value (e.g. 16) to enforce specified
  16328. number of bytes as a margin after every allocation.
  16329. \code
  16330. #define VMA_DEBUG_MARGIN 16
  16331. #include "vk_mem_alloc.h"
  16332. \endcode
  16333. ![Allocations with margin](../gfx/Margins_2.png)
  16334. If your bug goes away after enabling margins, it means it may be caused by memory
  16335. being overwritten outside of allocation boundaries. It is not 100% certain though.
  16336. Change in application behavior may also be caused by different order and distribution
  16337. of allocations across memory blocks after margins are applied.
  16338. Margins work with all types of memory.
  16339. Margin is applied only to allocations made out of memory blocks and not to dedicated
  16340. allocations, which have their own memory block of specific size.
  16341. It is thus not applied to allocations made using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT flag
  16342. or those automatically decided to put into dedicated allocations, e.g. due to its
  16343. large size or recommended by VK_KHR_dedicated_allocation extension.
  16344. Margins appear in [JSON dump](@ref statistics_json_dump) as part of free space.
  16345. Note that enabling margins increases memory usage and fragmentation.
  16346. Margins do not apply to \ref virtual_allocator.
  16347. \section debugging_memory_usage_corruption_detection Corruption detection
  16348. You can additionally define macro `VMA_DEBUG_DETECT_CORRUPTION` to 1 to enable validation
  16349. of contents of the margins.
  16350. \code
  16351. #define VMA_DEBUG_MARGIN 16
  16352. #define VMA_DEBUG_DETECT_CORRUPTION 1
  16353. #include "vk_mem_alloc.h"
  16354. \endcode
  16355. When this feature is enabled, number of bytes specified as `VMA_DEBUG_MARGIN`
  16356. (it must be multiply of 4) after every allocation is filled with a magic number.
  16357. This idea is also know as "canary".
  16358. Memory is automatically mapped and unmapped if necessary.
  16359. This number is validated automatically when the allocation is destroyed.
  16360. If it is not equal to the expected value, `VMA_ASSERT()` is executed.
  16361. It clearly means that either CPU or GPU overwritten the memory outside of boundaries of the allocation,
  16362. which indicates a serious bug.
  16363. You can also explicitly request checking margins of all allocations in all memory blocks
  16364. that belong to specified memory types by using function vmaCheckCorruption(),
  16365. or in memory blocks that belong to specified custom pool, by using function
  16366. vmaCheckPoolCorruption().
  16367. Margin validation (corruption detection) works only for memory types that are
  16368. `HOST_VISIBLE` and `HOST_COHERENT`.
  16369. \page opengl_interop OpenGL Interop
  16370. VMA provides some features that help with interoperability with OpenGL.
  16371. \section opengl_interop_exporting_memory Exporting memory
  16372. If you want to attach `VkExportMemoryAllocateInfoKHR` structure to `pNext` chain of memory allocations made by the library:
  16373. It is recommended to create \ref custom_memory_pools for such allocations.
  16374. Define and fill in your `VkExportMemoryAllocateInfoKHR` structure and attach it to VmaPoolCreateInfo::pMemoryAllocateNext
  16375. while creating the custom pool.
  16376. Please note that the structure must remain alive and unchanged for the whole lifetime of the #VmaPool,
  16377. not only while creating it, as no copy of the structure is made,
  16378. but its original pointer is used for each allocation instead.
  16379. If you want to export all memory allocated by the library from certain memory types,
  16380. also dedicated allocations or other allocations made from default pools,
  16381. an alternative solution is to fill in VmaAllocatorCreateInfo::pTypeExternalMemoryHandleTypes.
  16382. It should point to an array with `VkExternalMemoryHandleTypeFlagsKHR` to be automatically passed by the library
  16383. through `VkExportMemoryAllocateInfoKHR` on each allocation made from a specific memory type.
  16384. Please note that new versions of the library also support dedicated allocations created in custom pools.
  16385. You should not mix these two methods in a way that allows to apply both to the same memory type.
  16386. Otherwise, `VkExportMemoryAllocateInfoKHR` structure would be attached twice to the `pNext` chain of `VkMemoryAllocateInfo`.
  16387. \section opengl_interop_custom_alignment Custom alignment
  16388. Buffers or images exported to a different API like OpenGL may require a different alignment,
  16389. higher than the one used by the library automatically, queried from functions like `vkGetBufferMemoryRequirements`.
  16390. To impose such alignment:
  16391. It is recommended to create \ref custom_memory_pools for such allocations.
  16392. Set VmaPoolCreateInfo::minAllocationAlignment member to the minimum alignment required for each allocation
  16393. to be made out of this pool.
  16394. The alignment actually used will be the maximum of this member and the alignment returned for the specific buffer or image
  16395. from a function like `vkGetBufferMemoryRequirements`, which is called by VMA automatically.
  16396. If you want to create a buffer with a specific minimum alignment out of default pools,
  16397. use special function vmaCreateBufferWithAlignment(), which takes additional parameter `minAlignment`.
  16398. Note the problem of alignment affects only resources placed inside bigger `VkDeviceMemory` blocks and not dedicated
  16399. allocations, as these, by definition, always have alignment = 0 because the resource is bound to the beginning of its dedicated block.
  16400. Contrary to Direct3D 12, Vulkan doesn't have a concept of alignment of the entire memory block passed on its allocation.
  16401. \page usage_patterns Recommended usage patterns
  16402. Vulkan gives great flexibility in memory allocation.
  16403. This chapter shows the most common patterns.
  16404. See also slides from talk:
  16405. [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)
  16406. \section usage_patterns_gpu_only GPU-only resource
  16407. <b>When:</b>
  16408. Any resources that you frequently write and read on GPU,
  16409. e.g. images used as color attachments (aka "render targets"), depth-stencil attachments,
  16410. images/buffers used as storage image/buffer (aka "Unordered Access View (UAV)").
  16411. <b>What to do:</b>
  16412. Let the library select the optimal memory type, which will likely have `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`.
  16413. \code
  16414. VkImageCreateInfo imgCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
  16415. imgCreateInfo.imageType = VK_IMAGE_TYPE_2D;
  16416. imgCreateInfo.extent.width = 3840;
  16417. imgCreateInfo.extent.height = 2160;
  16418. imgCreateInfo.extent.depth = 1;
  16419. imgCreateInfo.mipLevels = 1;
  16420. imgCreateInfo.arrayLayers = 1;
  16421. imgCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
  16422. imgCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  16423. imgCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  16424. imgCreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  16425. imgCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
  16426. VmaAllocationCreateInfo allocCreateInfo = {};
  16427. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  16428. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  16429. allocCreateInfo.priority = 1.0f;
  16430. VkImage img;
  16431. VmaAllocation alloc;
  16432. vmaCreateImage(allocator, &imgCreateInfo, &allocCreateInfo, &img, &alloc, nullptr);
  16433. \endcode
  16434. <b>Also consider:</b>
  16435. Consider creating them as dedicated allocations using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
  16436. especially if they are large or if you plan to destroy and recreate them with different sizes
  16437. e.g. when display resolution changes.
  16438. Prefer to create such resources first and all other GPU resources (like textures and vertex buffers) later.
  16439. When VK_EXT_memory_priority extension is enabled, it is also worth setting high priority to such allocation
  16440. to decrease chances to be evicted to system memory by the operating system.
  16441. \section usage_patterns_staging_copy_upload Staging copy for upload
  16442. <b>When:</b>
  16443. A "staging" buffer than you want to map and fill from CPU code, then use as a source of transfer
  16444. to some GPU resource.
  16445. <b>What to do:</b>
  16446. Use flag #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT.
  16447. Let the library select the optimal memory type, which will always have `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`.
  16448. \code
  16449. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  16450. bufCreateInfo.size = 65536;
  16451. bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  16452. VmaAllocationCreateInfo allocCreateInfo = {};
  16453. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  16454. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT |
  16455. VMA_ALLOCATION_CREATE_MAPPED_BIT;
  16456. VkBuffer buf;
  16457. VmaAllocation alloc;
  16458. VmaAllocationInfo allocInfo;
  16459. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  16460. ...
  16461. memcpy(allocInfo.pMappedData, myData, myDataSize);
  16462. \endcode
  16463. <b>Also consider:</b>
  16464. You can map the allocation using vmaMapMemory() or you can create it as persistenly mapped
  16465. using #VMA_ALLOCATION_CREATE_MAPPED_BIT, as in the example above.
  16466. \section usage_patterns_readback Readback
  16467. <b>When:</b>
  16468. Buffers for data written by or transferred from the GPU that you want to read back on the CPU,
  16469. e.g. results of some computations.
  16470. <b>What to do:</b>
  16471. Use flag #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT.
  16472. Let the library select the optimal memory type, which will always have `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`
  16473. and `VK_MEMORY_PROPERTY_HOST_CACHED_BIT`.
  16474. \code
  16475. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  16476. bufCreateInfo.size = 65536;
  16477. bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  16478. VmaAllocationCreateInfo allocCreateInfo = {};
  16479. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  16480. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT |
  16481. VMA_ALLOCATION_CREATE_MAPPED_BIT;
  16482. VkBuffer buf;
  16483. VmaAllocation alloc;
  16484. VmaAllocationInfo allocInfo;
  16485. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  16486. ...
  16487. const float* downloadedData = (const float*)allocInfo.pMappedData;
  16488. \endcode
  16489. \section usage_patterns_advanced_data_uploading Advanced data uploading
  16490. For resources that you frequently write on CPU via mapped pointer and
  16491. frequently read on GPU e.g. as a uniform buffer (also called "dynamic"), multiple options are possible:
  16492. -# Easiest solution is to have one copy of the resource in `HOST_VISIBLE` memory,
  16493. even if it means system RAM (not `DEVICE_LOCAL`) on systems with a discrete graphics card,
  16494. and make the device reach out to that resource directly.
  16495. - Reads performed by the device will then go through PCI Express bus.
  16496. The performance of this access may be limited, but it may be fine depending on the size
  16497. of this resource (whether it is small enough to quickly end up in GPU cache) and the sparsity
  16498. of access.
  16499. -# On systems with unified memory (e.g. AMD APU or Intel integrated graphics, mobile chips),
  16500. a memory type may be available that is both `HOST_VISIBLE` (available for mapping) and `DEVICE_LOCAL`
  16501. (fast to access from the GPU). Then, it is likely the best choice for such type of resource.
  16502. -# Systems with a discrete graphics card and separate video memory may or may not expose
  16503. a memory type that is both `HOST_VISIBLE` and `DEVICE_LOCAL`, also known as Base Address Register (BAR).
  16504. If they do, it represents a piece of VRAM (or entire VRAM, if ReBAR is enabled in the motherboard BIOS)
  16505. that is available to CPU for mapping.
  16506. - Writes performed by the host to that memory go through PCI Express bus.
  16507. The performance of these writes may be limited, but it may be fine, especially on PCIe 4.0,
  16508. as long as rules of using uncached and write-combined memory are followed - only sequential writes and no reads.
  16509. -# Finally, you may need or prefer to create a separate copy of the resource in `DEVICE_LOCAL` memory,
  16510. a separate "staging" copy in `HOST_VISIBLE` memory and perform an explicit transfer command between them.
  16511. Thankfully, VMA offers an aid to create and use such resources in the the way optimal
  16512. for the current Vulkan device. To help the library make the best choice,
  16513. use flag #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT together with
  16514. #VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT.
  16515. It will then prefer a memory type that is both `DEVICE_LOCAL` and `HOST_VISIBLE` (integrated memory or BAR),
  16516. but if no such memory type is available or allocation from it fails
  16517. (PC graphics cards have only 256 MB of BAR by default, unless ReBAR is supported and enabled in BIOS),
  16518. it will fall back to `DEVICE_LOCAL` memory for fast GPU access.
  16519. It is then up to you to detect that the allocation ended up in a memory type that is not `HOST_VISIBLE`,
  16520. so you need to create another "staging" allocation and perform explicit transfers.
  16521. \code
  16522. VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  16523. bufCreateInfo.size = 65536;
  16524. bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  16525. VmaAllocationCreateInfo allocCreateInfo = {};
  16526. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  16527. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT |
  16528. VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT |
  16529. VMA_ALLOCATION_CREATE_MAPPED_BIT;
  16530. VkBuffer buf;
  16531. VmaAllocation alloc;
  16532. VmaAllocationInfo allocInfo;
  16533. vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
  16534. VkMemoryPropertyFlags memPropFlags;
  16535. vmaGetAllocationMemoryProperties(allocator, alloc, &memPropFlags);
  16536. if(memPropFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
  16537. {
  16538. // Allocation ended up in a mappable memory and is already mapped - write to it directly.
  16539. // [Executed in runtime]:
  16540. memcpy(allocInfo.pMappedData, myData, myDataSize);
  16541. }
  16542. else
  16543. {
  16544. // Allocation ended up in a non-mappable memory - need to transfer.
  16545. VkBufferCreateInfo stagingBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
  16546. stagingBufCreateInfo.size = 65536;
  16547. stagingBufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
  16548. VmaAllocationCreateInfo stagingAllocCreateInfo = {};
  16549. stagingAllocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  16550. stagingAllocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT |
  16551. VMA_ALLOCATION_CREATE_MAPPED_BIT;
  16552. VkBuffer stagingBuf;
  16553. VmaAllocation stagingAlloc;
  16554. VmaAllocationInfo stagingAllocInfo;
  16555. vmaCreateBuffer(allocator, &stagingBufCreateInfo, &stagingAllocCreateInfo,
  16556. &stagingBuf, &stagingAlloc, stagingAllocInfo);
  16557. // [Executed in runtime]:
  16558. memcpy(stagingAllocInfo.pMappedData, myData, myDataSize);
  16559. vmaFlushAllocation(allocator, stagingAlloc, 0, VK_WHOLE_SIZE);
  16560. //vkCmdPipelineBarrier: VK_ACCESS_HOST_WRITE_BIT --> VK_ACCESS_TRANSFER_READ_BIT
  16561. VkBufferCopy bufCopy = {
  16562. 0, // srcOffset
  16563. 0, // dstOffset,
  16564. myDataSize); // size
  16565. vkCmdCopyBuffer(cmdBuf, stagingBuf, buf, 1, &bufCopy);
  16566. }
  16567. \endcode
  16568. \section usage_patterns_other_use_cases Other use cases
  16569. Here are some other, less obvious use cases and their recommended settings:
  16570. - An image that is used only as transfer source and destination, but it should stay on the device,
  16571. as it is used to temporarily store a copy of some texture, e.g. from the current to the next frame,
  16572. for temporal antialiasing or other temporal effects.
  16573. - Use `VkImageCreateInfo::usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT`
  16574. - Use VmaAllocationCreateInfo::usage = #VMA_MEMORY_USAGE_AUTO
  16575. - An image that is used only as transfer source and destination, but it should be placed
  16576. in the system RAM despite it doesn't need to be mapped, because it serves as a "swap" copy to evict
  16577. least recently used textures from VRAM.
  16578. - Use `VkImageCreateInfo::usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT`
  16579. - Use VmaAllocationCreateInfo::usage = #VMA_MEMORY_USAGE_AUTO_PREFER_HOST,
  16580. as VMA needs a hint here to differentiate from the previous case.
  16581. - A buffer that you want to map and write from the CPU, directly read from the GPU
  16582. (e.g. as a uniform or vertex buffer), but you have a clear preference to place it in device or
  16583. host memory due to its large size.
  16584. - Use `VkBufferCreateInfo::usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT`
  16585. - Use VmaAllocationCreateInfo::usage = #VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE or #VMA_MEMORY_USAGE_AUTO_PREFER_HOST
  16586. - Use VmaAllocationCreateInfo::flags = #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT
  16587. \page configuration Configuration
  16588. Please check "CONFIGURATION SECTION" in the code to find macros that you can define
  16589. before each include of this file or change directly in this file to provide
  16590. your own implementation of basic facilities like assert, `min()` and `max()` functions,
  16591. mutex, atomic etc.
  16592. The library uses its own implementation of containers by default, but you can switch to using
  16593. STL containers instead.
  16594. For example, define `VMA_ASSERT(expr)` before including the library to provide
  16595. custom implementation of the assertion, compatible with your project.
  16596. By default it is defined to standard C `assert(expr)` in `_DEBUG` configuration
  16597. and empty otherwise.
  16598. \section config_Vulkan_functions Pointers to Vulkan functions
  16599. There are multiple ways to import pointers to Vulkan functions in the library.
  16600. In the simplest case you don't need to do anything.
  16601. If the compilation or linking of your program or the initialization of the #VmaAllocator
  16602. doesn't work for you, you can try to reconfigure it.
  16603. First, the allocator tries to fetch pointers to Vulkan functions linked statically,
  16604. like this:
  16605. \code
  16606. m_VulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkAllocateMemory;
  16607. \endcode
  16608. If you want to disable this feature, set configuration macro: `#define VMA_STATIC_VULKAN_FUNCTIONS 0`.
  16609. Second, you can provide the pointers yourself by setting member VmaAllocatorCreateInfo::pVulkanFunctions.
  16610. You can fetch them e.g. using functions `vkGetInstanceProcAddr` and `vkGetDeviceProcAddr` or
  16611. by using a helper library like [volk](https://github.com/zeux/volk).
  16612. Third, VMA tries to fetch remaining pointers that are still null by calling
  16613. `vkGetInstanceProcAddr` and `vkGetDeviceProcAddr` on its own.
  16614. You need to only fill in VmaVulkanFunctions::vkGetInstanceProcAddr and VmaVulkanFunctions::vkGetDeviceProcAddr.
  16615. Other pointers will be fetched automatically.
  16616. If you want to disable this feature, set configuration macro: `#define VMA_DYNAMIC_VULKAN_FUNCTIONS 0`.
  16617. Finally, all the function pointers required by the library (considering selected
  16618. Vulkan version and enabled extensions) are checked with `VMA_ASSERT` if they are not null.
  16619. \section custom_memory_allocator Custom host memory allocator
  16620. If you use custom allocator for CPU memory rather than default operator `new`
  16621. and `delete` from C++, you can make this library using your allocator as well
  16622. by filling optional member VmaAllocatorCreateInfo::pAllocationCallbacks. These
  16623. functions will be passed to Vulkan, as well as used by the library itself to
  16624. make any CPU-side allocations.
  16625. \section allocation_callbacks Device memory allocation callbacks
  16626. The library makes calls to `vkAllocateMemory()` and `vkFreeMemory()` internally.
  16627. You can setup callbacks to be informed about these calls, e.g. for the purpose
  16628. of gathering some statistics. To do it, fill optional member
  16629. VmaAllocatorCreateInfo::pDeviceMemoryCallbacks.
  16630. \section heap_memory_limit Device heap memory limit
  16631. When device memory of certain heap runs out of free space, new allocations may
  16632. fail (returning error code) or they may succeed, silently pushing some existing_
  16633. memory blocks from GPU VRAM to system RAM (which degrades performance). This
  16634. behavior is implementation-dependent - it depends on GPU vendor and graphics
  16635. driver.
  16636. On AMD cards it can be controlled while creating Vulkan device object by using
  16637. VK_AMD_memory_overallocation_behavior extension, if available.
  16638. Alternatively, if you want to test how your program behaves with limited amount of Vulkan device
  16639. memory available without switching your graphics card to one that really has
  16640. smaller VRAM, you can use a feature of this library intended for this purpose.
  16641. To do it, fill optional member VmaAllocatorCreateInfo::pHeapSizeLimit.
  16642. \page vk_khr_dedicated_allocation VK_KHR_dedicated_allocation
  16643. VK_KHR_dedicated_allocation is a Vulkan extension which can be used to improve
  16644. performance on some GPUs. It augments Vulkan API with possibility to query
  16645. driver whether it prefers particular buffer or image to have its own, dedicated
  16646. allocation (separate `VkDeviceMemory` block) for better efficiency - to be able
  16647. to do some internal optimizations. The extension is supported by this library.
  16648. It will be used automatically when enabled.
  16649. It has been promoted to core Vulkan 1.1, so if you use eligible Vulkan version
  16650. and inform VMA about it by setting VmaAllocatorCreateInfo::vulkanApiVersion,
  16651. you are all set.
  16652. Otherwise, if you want to use it as an extension:
  16653. 1 . When creating Vulkan device, check if following 2 device extensions are
  16654. supported (call `vkEnumerateDeviceExtensionProperties()`).
  16655. If yes, enable them (fill `VkDeviceCreateInfo::ppEnabledExtensionNames`).
  16656. - VK_KHR_get_memory_requirements2
  16657. - VK_KHR_dedicated_allocation
  16658. If you enabled these extensions:
  16659. 2 . Use #VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag when creating
  16660. your #VmaAllocator to inform the library that you enabled required extensions
  16661. and you want the library to use them.
  16662. \code
  16663. allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT;
  16664. vmaCreateAllocator(&allocatorInfo, &allocator);
  16665. \endcode
  16666. That is all. The extension will be automatically used whenever you create a
  16667. buffer using vmaCreateBuffer() or image using vmaCreateImage().
  16668. When using the extension together with Vulkan Validation Layer, you will receive
  16669. warnings like this:
  16670. _vkBindBufferMemory(): Binding memory to buffer 0x33 but vkGetBufferMemoryRequirements() has not been called on that buffer._
  16671. It is OK, you should just ignore it. It happens because you use function
  16672. `vkGetBufferMemoryRequirements2KHR()` instead of standard
  16673. `vkGetBufferMemoryRequirements()`, while the validation layer seems to be
  16674. unaware of it.
  16675. To learn more about this extension, see:
  16676. - [VK_KHR_dedicated_allocation in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/chap50.html#VK_KHR_dedicated_allocation)
  16677. - [VK_KHR_dedicated_allocation unofficial manual](http://asawicki.info/articles/VK_KHR_dedicated_allocation.php5)
  16678. \page vk_ext_memory_priority VK_EXT_memory_priority
  16679. VK_EXT_memory_priority is a device extension that allows to pass additional "priority"
  16680. value to Vulkan memory allocations that the implementation may use prefer certain
  16681. buffers and images that are critical for performance to stay in device-local memory
  16682. in cases when the memory is over-subscribed, while some others may be moved to the system memory.
  16683. VMA offers convenient usage of this extension.
  16684. If you enable it, you can pass "priority" parameter when creating allocations or custom pools
  16685. and the library automatically passes the value to Vulkan using this extension.
  16686. If you want to use this extension in connection with VMA, follow these steps:
  16687. \section vk_ext_memory_priority_initialization Initialization
  16688. 1) Call `vkEnumerateDeviceExtensionProperties` for the physical device.
  16689. Check if the extension is supported - if returned array of `VkExtensionProperties` contains "VK_EXT_memory_priority".
  16690. 2) Call `vkGetPhysicalDeviceFeatures2` for the physical device instead of old `vkGetPhysicalDeviceFeatures`.
  16691. Attach additional structure `VkPhysicalDeviceMemoryPriorityFeaturesEXT` to `VkPhysicalDeviceFeatures2::pNext` to be returned.
  16692. Check if the device feature is really supported - check if `VkPhysicalDeviceMemoryPriorityFeaturesEXT::memoryPriority` is true.
  16693. 3) While creating device with `vkCreateDevice`, enable this extension - add "VK_EXT_memory_priority"
  16694. to the list passed as `VkDeviceCreateInfo::ppEnabledExtensionNames`.
  16695. 4) While creating the device, also don't set `VkDeviceCreateInfo::pEnabledFeatures`.
  16696. Fill in `VkPhysicalDeviceFeatures2` structure instead and pass it as `VkDeviceCreateInfo::pNext`.
  16697. Enable this device feature - attach additional structure `VkPhysicalDeviceMemoryPriorityFeaturesEXT` to
  16698. `VkPhysicalDeviceFeatures2::pNext` chain and set its member `memoryPriority` to `VK_TRUE`.
  16699. 5) While creating #VmaAllocator with vmaCreateAllocator() inform VMA that you
  16700. have enabled this extension and feature - add #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT
  16701. to VmaAllocatorCreateInfo::flags.
  16702. \section vk_ext_memory_priority_usage Usage
  16703. When using this extension, you should initialize following member:
  16704. - VmaAllocationCreateInfo::priority when creating a dedicated allocation with #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  16705. - VmaPoolCreateInfo::priority when creating a custom pool.
  16706. It should be a floating-point value between `0.0f` and `1.0f`, where recommended default is `0.5f`.
  16707. Memory allocated with higher value can be treated by the Vulkan implementation as higher priority
  16708. and so it can have lower chances of being pushed out to system memory, experiencing degraded performance.
  16709. It might be a good idea to create performance-critical resources like color-attachment or depth-stencil images
  16710. as dedicated and set high priority to them. For example:
  16711. \code
  16712. VkImageCreateInfo imgCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
  16713. imgCreateInfo.imageType = VK_IMAGE_TYPE_2D;
  16714. imgCreateInfo.extent.width = 3840;
  16715. imgCreateInfo.extent.height = 2160;
  16716. imgCreateInfo.extent.depth = 1;
  16717. imgCreateInfo.mipLevels = 1;
  16718. imgCreateInfo.arrayLayers = 1;
  16719. imgCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
  16720. imgCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  16721. imgCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  16722. imgCreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  16723. imgCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
  16724. VmaAllocationCreateInfo allocCreateInfo = {};
  16725. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  16726. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  16727. allocCreateInfo.priority = 1.0f;
  16728. VkImage img;
  16729. VmaAllocation alloc;
  16730. vmaCreateImage(allocator, &imgCreateInfo, &allocCreateInfo, &img, &alloc, nullptr);
  16731. \endcode
  16732. `priority` member is ignored in the following situations:
  16733. - Allocations created in custom pools: They inherit the priority, along with all other allocation parameters
  16734. from the parametrs passed in #VmaPoolCreateInfo when the pool was created.
  16735. - Allocations created in default pools: They inherit the priority from the parameters
  16736. VMA used when creating default pools, which means `priority == 0.5f`.
  16737. \page vk_amd_device_coherent_memory VK_AMD_device_coherent_memory
  16738. VK_AMD_device_coherent_memory is a device extension that enables access to
  16739. additional memory types with `VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD` and
  16740. `VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` flag. It is useful mostly for
  16741. allocation of buffers intended for writing "breadcrumb markers" in between passes
  16742. or draw calls, which in turn are useful for debugging GPU crash/hang/TDR cases.
  16743. When the extension is available but has not been enabled, Vulkan physical device
  16744. still exposes those memory types, but their usage is forbidden. VMA automatically
  16745. takes care of that - it returns `VK_ERROR_FEATURE_NOT_PRESENT` when an attempt
  16746. to allocate memory of such type is made.
  16747. If you want to use this extension in connection with VMA, follow these steps:
  16748. \section vk_amd_device_coherent_memory_initialization Initialization
  16749. 1) Call `vkEnumerateDeviceExtensionProperties` for the physical device.
  16750. Check if the extension is supported - if returned array of `VkExtensionProperties` contains "VK_AMD_device_coherent_memory".
  16751. 2) Call `vkGetPhysicalDeviceFeatures2` for the physical device instead of old `vkGetPhysicalDeviceFeatures`.
  16752. Attach additional structure `VkPhysicalDeviceCoherentMemoryFeaturesAMD` to `VkPhysicalDeviceFeatures2::pNext` to be returned.
  16753. Check if the device feature is really supported - check if `VkPhysicalDeviceCoherentMemoryFeaturesAMD::deviceCoherentMemory` is true.
  16754. 3) While creating device with `vkCreateDevice`, enable this extension - add "VK_AMD_device_coherent_memory"
  16755. to the list passed as `VkDeviceCreateInfo::ppEnabledExtensionNames`.
  16756. 4) While creating the device, also don't set `VkDeviceCreateInfo::pEnabledFeatures`.
  16757. Fill in `VkPhysicalDeviceFeatures2` structure instead and pass it as `VkDeviceCreateInfo::pNext`.
  16758. Enable this device feature - attach additional structure `VkPhysicalDeviceCoherentMemoryFeaturesAMD` to
  16759. `VkPhysicalDeviceFeatures2::pNext` and set its member `deviceCoherentMemory` to `VK_TRUE`.
  16760. 5) While creating #VmaAllocator with vmaCreateAllocator() inform VMA that you
  16761. have enabled this extension and feature - add #VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT
  16762. to VmaAllocatorCreateInfo::flags.
  16763. \section vk_amd_device_coherent_memory_usage Usage
  16764. After following steps described above, you can create VMA allocations and custom pools
  16765. out of the special `DEVICE_COHERENT` and `DEVICE_UNCACHED` memory types on eligible
  16766. devices. There are multiple ways to do it, for example:
  16767. - You can request or prefer to allocate out of such memory types by adding
  16768. `VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` to VmaAllocationCreateInfo::requiredFlags
  16769. or VmaAllocationCreateInfo::preferredFlags. Those flags can be freely mixed with
  16770. other ways of \ref choosing_memory_type, like setting VmaAllocationCreateInfo::usage.
  16771. - If you manually found memory type index to use for this purpose, force allocation
  16772. from this specific index by setting VmaAllocationCreateInfo::memoryTypeBits `= 1u << index`.
  16773. \section vk_amd_device_coherent_memory_more_information More information
  16774. To learn more about this extension, see [VK_AMD_device_coherent_memory in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VK_AMD_device_coherent_memory.html)
  16775. Example use of this extension can be found in the code of the sample and test suite
  16776. accompanying this library.
  16777. \page enabling_buffer_device_address Enabling buffer device address
  16778. Device extension VK_KHR_buffer_device_address
  16779. allow to fetch raw GPU pointer to a buffer and pass it for usage in a shader code.
  16780. It has been promoted to core Vulkan 1.2.
  16781. If you want to use this feature in connection with VMA, follow these steps:
  16782. \section enabling_buffer_device_address_initialization Initialization
  16783. 1) (For Vulkan version < 1.2) Call `vkEnumerateDeviceExtensionProperties` for the physical device.
  16784. Check if the extension is supported - if returned array of `VkExtensionProperties` contains
  16785. "VK_KHR_buffer_device_address".
  16786. 2) Call `vkGetPhysicalDeviceFeatures2` for the physical device instead of old `vkGetPhysicalDeviceFeatures`.
  16787. Attach additional structure `VkPhysicalDeviceBufferDeviceAddressFeatures*` to `VkPhysicalDeviceFeatures2::pNext` to be returned.
  16788. Check if the device feature is really supported - check if `VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress` is true.
  16789. 3) (For Vulkan version < 1.2) While creating device with `vkCreateDevice`, enable this extension - add
  16790. "VK_KHR_buffer_device_address" to the list passed as `VkDeviceCreateInfo::ppEnabledExtensionNames`.
  16791. 4) While creating the device, also don't set `VkDeviceCreateInfo::pEnabledFeatures`.
  16792. Fill in `VkPhysicalDeviceFeatures2` structure instead and pass it as `VkDeviceCreateInfo::pNext`.
  16793. Enable this device feature - attach additional structure `VkPhysicalDeviceBufferDeviceAddressFeatures*` to
  16794. `VkPhysicalDeviceFeatures2::pNext` and set its member `bufferDeviceAddress` to `VK_TRUE`.
  16795. 5) While creating #VmaAllocator with vmaCreateAllocator() inform VMA that you
  16796. have enabled this feature - add #VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT
  16797. to VmaAllocatorCreateInfo::flags.
  16798. \section enabling_buffer_device_address_usage Usage
  16799. After following steps described above, you can create buffers with `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT*` using VMA.
  16800. The library automatically adds `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT*` to
  16801. allocated memory blocks wherever it might be needed.
  16802. Please note that the library supports only `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT*`.
  16803. The second part of this functionality related to "capture and replay" is not supported,
  16804. as it is intended for usage in debugging tools like RenderDoc, not in everyday Vulkan usage.
  16805. \section enabling_buffer_device_address_more_information More information
  16806. To learn more about this extension, see [VK_KHR_buffer_device_address in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/chap46.html#VK_KHR_buffer_device_address)
  16807. Example use of this extension can be found in the code of the sample and test suite
  16808. accompanying this library.
  16809. \page general_considerations General considerations
  16810. \section general_considerations_thread_safety Thread safety
  16811. - The library has no global state, so separate #VmaAllocator objects can be used
  16812. independently.
  16813. There should be no need to create multiple such objects though - one per `VkDevice` is enough.
  16814. - By default, all calls to functions that take #VmaAllocator as first parameter
  16815. are safe to call from multiple threads simultaneously because they are
  16816. synchronized internally when needed.
  16817. This includes allocation and deallocation from default memory pool, as well as custom #VmaPool.
  16818. - When the allocator is created with #VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT
  16819. flag, calls to functions that take such #VmaAllocator object must be
  16820. synchronized externally.
  16821. - Access to a #VmaAllocation object must be externally synchronized. For example,
  16822. you must not call vmaGetAllocationInfo() and vmaMapMemory() from different
  16823. threads at the same time if you pass the same #VmaAllocation object to these
  16824. functions.
  16825. - #VmaVirtualBlock is not safe to be used from multiple threads simultaneously.
  16826. \section general_considerations_versioning_and_compatibility Versioning and compatibility
  16827. The library uses [**Semantic Versioning**](https://semver.org/),
  16828. which means version numbers follow convention: Major.Minor.Patch (e.g. 2.3.0), where:
  16829. - Incremented Patch version means a release is backward- and forward-compatible,
  16830. introducing only some internal improvements, bug fixes, optimizations etc.
  16831. or changes that are out of scope of the official API described in this documentation.
  16832. - Incremented Minor version means a release is backward-compatible,
  16833. so existing code that uses the library should continue to work, while some new
  16834. symbols could have been added: new structures, functions, new values in existing
  16835. enums and bit flags, new structure members, but not new function parameters.
  16836. - Incrementing Major version means a release could break some backward compatibility.
  16837. All changes between official releases are documented in file "CHANGELOG.md".
  16838. \warning Backward compatibility is considered on the level of C++ source code, not binary linkage.
  16839. Adding new members to existing structures is treated as backward compatible if initializing
  16840. the new members to binary zero results in the old behavior.
  16841. You should always fully initialize all library structures to zeros and not rely on their
  16842. exact binary size.
  16843. \section general_considerations_validation_layer_warnings Validation layer warnings
  16844. When using this library, you can meet following types of warnings issued by
  16845. Vulkan validation layer. They don't necessarily indicate a bug, so you may need
  16846. to just ignore them.
  16847. - *vkBindBufferMemory(): Binding memory to buffer 0xeb8e4 but vkGetBufferMemoryRequirements() has not been called on that buffer.*
  16848. - It happens when VK_KHR_dedicated_allocation extension is enabled.
  16849. `vkGetBufferMemoryRequirements2KHR` function is used instead, while validation layer seems to be unaware of it.
  16850. - *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.*
  16851. - It happens when you map a buffer or image, because the library maps entire
  16852. `VkDeviceMemory` block, where different types of images and buffers may end
  16853. up together, especially on GPUs with unified memory like Intel.
  16854. - *Non-linear image 0xebc91 is aliased with linear buffer 0xeb8e4 which may indicate a bug.*
  16855. - It may happen when you use [defragmentation](@ref defragmentation).
  16856. \section general_considerations_allocation_algorithm Allocation algorithm
  16857. The library uses following algorithm for allocation, in order:
  16858. -# Try to find free range of memory in existing blocks.
  16859. -# If failed, try to create a new block of `VkDeviceMemory`, with preferred block size.
  16860. -# If failed, try to create such block with size / 2, size / 4, size / 8.
  16861. -# If failed, try to allocate separate `VkDeviceMemory` for this allocation,
  16862. just like when you use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
  16863. -# If failed, choose other memory type that meets the requirements specified in
  16864. VmaAllocationCreateInfo and go to point 1.
  16865. -# If failed, return `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
  16866. \section general_considerations_features_not_supported Features not supported
  16867. Features deliberately excluded from the scope of this library:
  16868. -# **Data transfer.** Uploading (streaming) and downloading data of buffers and images
  16869. between CPU and GPU memory and related synchronization is responsibility of the user.
  16870. Defining some "texture" object that would automatically stream its data from a
  16871. staging copy in CPU memory to GPU memory would rather be a feature of another,
  16872. higher-level library implemented on top of VMA.
  16873. VMA doesn't record any commands to a `VkCommandBuffer`. It just allocates memory.
  16874. -# **Recreation of buffers and images.** Although the library has functions for
  16875. buffer and image creation: vmaCreateBuffer(), vmaCreateImage(), you need to
  16876. recreate these objects yourself after defragmentation. That is because the big
  16877. structures `VkBufferCreateInfo`, `VkImageCreateInfo` are not stored in
  16878. #VmaAllocation object.
  16879. -# **Handling CPU memory allocation failures.** When dynamically creating small C++
  16880. objects in CPU memory (not Vulkan memory), allocation failures are not checked
  16881. and handled gracefully, because that would complicate code significantly and
  16882. is usually not needed in desktop PC applications anyway.
  16883. Success of an allocation is just checked with an assert.
  16884. -# **Code free of any compiler warnings.** Maintaining the library to compile and
  16885. work correctly on so many different platforms is hard enough. Being free of
  16886. any warnings, on any version of any compiler, is simply not feasible.
  16887. There are many preprocessor macros that make some variables unused, function parameters unreferenced,
  16888. or conditional expressions constant in some configurations.
  16889. The code of this library should not be bigger or more complicated just to silence these warnings.
  16890. It is recommended to disable such warnings instead.
  16891. -# This is a C++ library with C interface. **Bindings or ports to any other programming languages** are welcome as external projects but
  16892. are not going to be included into this repository.
  16893. */