D3D12MemAlloc.h 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632
  1. //
  2. // Copyright (c) 2019-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. #pragma once
  23. /** \mainpage D3D12 Memory Allocator
  24. <b>Version 2.1.0-development</b> (2022-12-15)
  25. Copyright (c) 2019-2022 Advanced Micro Devices, Inc. All rights reserved. \n
  26. License: MIT
  27. Documentation of all members: D3D12MemAlloc.h
  28. \section main_table_of_contents Table of contents
  29. - \subpage quick_start
  30. - [Project setup](@ref quick_start_project_setup)
  31. - [Creating resources](@ref quick_start_creating_resources)
  32. - [Resource reference counting](@ref quick_start_resource_reference_counting)
  33. - [Mapping memory](@ref quick_start_mapping_memory)
  34. - \subpage custom_pools
  35. - \subpage defragmentation
  36. - \subpage statistics
  37. - \subpage resource_aliasing
  38. - \subpage linear_algorithm
  39. - \subpage virtual_allocator
  40. - \subpage configuration
  41. - [Custom CPU memory allocator](@ref custom_memory_allocator)
  42. - [Debug margins](@ref debug_margins)
  43. - \subpage general_considerations
  44. - [Thread safety](@ref general_considerations_thread_safety)
  45. - [Versioning and compatibility](@ref general_considerations_versioning_and_compatibility)
  46. - [Features not supported](@ref general_considerations_features_not_supported)
  47. \section main_see_also See also
  48. - [Product page on GPUOpen](https://gpuopen.com/gaming-product/d3d12-memory-allocator/)
  49. - [Source repository on GitHub](https://github.com/GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator)
  50. */
  51. // If using this library on a platform different than Windows PC or want to use different version of DXGI,
  52. // you should include D3D12-compatible headers before this library on your own and define this macro.
  53. #ifndef D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED
  54. #include <d3d12.h>
  55. #include <dxgi1_4.h>
  56. #endif
  57. // Define this macro to 0 to disable usage of DXGI 1.4 (needed for IDXGIAdapter3 and query for memory budget).
  58. #ifndef D3D12MA_DXGI_1_4
  59. #ifdef __IDXGIAdapter3_INTERFACE_DEFINED__
  60. #define D3D12MA_DXGI_1_4 1
  61. #else
  62. #define D3D12MA_DXGI_1_4 0
  63. #endif
  64. #endif
  65. /*
  66. When defined to value other than 0, the library will try to use
  67. D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT or D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT
  68. for created textures when possible, which can save memory because some small textures
  69. may get their alignment 4K and their size a multiply of 4K instead of 64K.
  70. #define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 0
  71. Disables small texture alignment.
  72. #define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 1
  73. Enables conservative algorithm that will use small alignment only for some textures
  74. that are surely known to support it.
  75. #define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 2
  76. Enables query for small alignment to D3D12 (based on Microsoft sample) which will
  77. enable small alignment for more textures, but will also generate D3D Debug Layer
  78. error #721 on call to ID3D12Device::GetResourceAllocationInfo, which you should just
  79. ignore.
  80. */
  81. #ifndef D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT
  82. #define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 1
  83. #endif
  84. /// \cond INTERNAL
  85. #define D3D12MA_CLASS_NO_COPY(className) \
  86. private: \
  87. className(const className&) = delete; \
  88. className(className&&) = delete; \
  89. className& operator=(const className&) = delete; \
  90. className& operator=(className&&) = delete;
  91. // To be used with MAKE_HRESULT to define custom error codes.
  92. #define FACILITY_D3D12MA 3542
  93. /*
  94. If providing your own implementation, you need to implement a subset of std::atomic.
  95. */
  96. #if !defined(D3D12MA_ATOMIC_UINT32) || !defined(D3D12MA_ATOMIC_UINT64)
  97. #include <atomic>
  98. #endif
  99. #ifndef D3D12MA_ATOMIC_UINT32
  100. #define D3D12MA_ATOMIC_UINT32 std::atomic<UINT>
  101. #endif
  102. #ifndef D3D12MA_ATOMIC_UINT64
  103. #define D3D12MA_ATOMIC_UINT64 std::atomic<UINT64>
  104. #endif
  105. #ifdef D3D12MA_EXPORTS
  106. #define D3D12MA_API __declspec(dllexport)
  107. #elif defined(D3D12MA_IMPORTS)
  108. #define D3D12MA_API __declspec(dllimport)
  109. #else
  110. #define D3D12MA_API
  111. #endif
  112. // Forward declaration if ID3D12ProtectedResourceSession is not defined inside the headers (older SDK, pre ID3D12Device4)
  113. struct ID3D12ProtectedResourceSession;
  114. // Define this enum even if SDK doesn't provide it, to simplify the API.
  115. #ifndef __ID3D12Device1_INTERFACE_DEFINED__
  116. typedef enum D3D12_RESIDENCY_PRIORITY
  117. {
  118. D3D12_RESIDENCY_PRIORITY_MINIMUM = 0x28000000,
  119. D3D12_RESIDENCY_PRIORITY_LOW = 0x50000000,
  120. D3D12_RESIDENCY_PRIORITY_NORMAL = 0x78000000,
  121. D3D12_RESIDENCY_PRIORITY_HIGH = 0xa0010000,
  122. D3D12_RESIDENCY_PRIORITY_MAXIMUM = 0xc8000000
  123. } D3D12_RESIDENCY_PRIORITY;
  124. #endif
  125. namespace D3D12MA
  126. {
  127. class D3D12MA_API IUnknownImpl : public IUnknown
  128. {
  129. public:
  130. virtual ~IUnknownImpl() = default;
  131. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObject);
  132. virtual ULONG STDMETHODCALLTYPE AddRef();
  133. virtual ULONG STDMETHODCALLTYPE Release();
  134. protected:
  135. virtual void ReleaseThis() { delete this; }
  136. private:
  137. D3D12MA_ATOMIC_UINT32 m_RefCount = {1};
  138. };
  139. } // namespace D3D12MA
  140. /// \endcond
  141. namespace D3D12MA
  142. {
  143. /// \cond INTERNAL
  144. class DefragmentationContextPimpl;
  145. class AllocatorPimpl;
  146. class PoolPimpl;
  147. class NormalBlock;
  148. class BlockVector;
  149. class CommittedAllocationList;
  150. class JsonWriter;
  151. class VirtualBlockPimpl;
  152. /// \endcond
  153. class Pool;
  154. class Allocator;
  155. struct Statistics;
  156. struct DetailedStatistics;
  157. struct TotalStatistics;
  158. /// \brief Unique identifier of single allocation done inside the memory heap.
  159. typedef UINT64 AllocHandle;
  160. /// Pointer to custom callback function that allocates CPU memory.
  161. using ALLOCATE_FUNC_PTR = void* (*)(size_t Size, size_t Alignment, void* pPrivateData);
  162. /**
  163. \brief Pointer to custom callback function that deallocates CPU memory.
  164. `pMemory = null` should be accepted and ignored.
  165. */
  166. using FREE_FUNC_PTR = void (*)(void* pMemory, void* pPrivateData);
  167. /// Custom callbacks to CPU memory allocation functions.
  168. struct ALLOCATION_CALLBACKS
  169. {
  170. /// %Allocation function.
  171. ALLOCATE_FUNC_PTR pAllocate;
  172. /// Dellocation function.
  173. FREE_FUNC_PTR pFree;
  174. /// Custom data that will be passed to allocation and deallocation functions as `pUserData` parameter.
  175. void* pPrivateData;
  176. };
  177. /// \brief Bit flags to be used with ALLOCATION_DESC::Flags.
  178. enum ALLOCATION_FLAGS
  179. {
  180. /// Zero
  181. ALLOCATION_FLAG_NONE = 0,
  182. /**
  183. Set this flag if the allocation should have its own dedicated memory allocation (committed resource with implicit heap).
  184. Use it for special, big resources, like fullscreen textures used as render targets.
  185. - When used with functions like D3D12MA::Allocator::CreateResource, it will use `ID3D12Device::CreateCommittedResource`,
  186. so the created allocation will contain a resource (D3D12MA::Allocation::GetResource() `!= NULL`) but will not have
  187. a heap (D3D12MA::Allocation::GetHeap() `== NULL`), as the heap is implicit.
  188. - When used with raw memory allocation like D3D12MA::Allocator::AllocateMemory, it will use `ID3D12Device::CreateHeap`,
  189. so the created allocation will contain a heap (D3D12MA::Allocation::GetHeap() `!= NULL`) and its offset will always be 0.
  190. */
  191. ALLOCATION_FLAG_COMMITTED = 0x1,
  192. /**
  193. Set this flag to only try to allocate from existing memory heaps and never create new such heap.
  194. If new allocation cannot be placed in any of the existing heaps, allocation
  195. fails with `E_OUTOFMEMORY` error.
  196. You should not use D3D12MA::ALLOCATION_FLAG_COMMITTED and
  197. D3D12MA::ALLOCATION_FLAG_NEVER_ALLOCATE at the same time. It makes no sense.
  198. */
  199. ALLOCATION_FLAG_NEVER_ALLOCATE = 0x2,
  200. /** Create allocation only if additional memory required for it, if any, won't exceed
  201. memory budget. Otherwise return `E_OUTOFMEMORY`.
  202. */
  203. ALLOCATION_FLAG_WITHIN_BUDGET = 0x4,
  204. /** Allocation will be created from upper stack in a double stack pool.
  205. This flag is only allowed for custom pools created with #POOL_FLAG_ALGORITHM_LINEAR flag.
  206. */
  207. ALLOCATION_FLAG_UPPER_ADDRESS = 0x8,
  208. /** Set this flag if the allocated memory will have aliasing resources.
  209. Use this when calling D3D12MA::Allocator::CreateResource() and similar to
  210. guarantee creation of explicit heap for desired allocation and prevent it from using `CreateCommittedResource`,
  211. so that new allocation object will always have `allocation->GetHeap() != NULL`.
  212. */
  213. ALLOCATION_FLAG_CAN_ALIAS = 0x10,
  214. /** Allocation strategy that chooses smallest possible free range for the allocation
  215. to minimize memory usage and fragmentation, possibly at the expense of allocation time.
  216. */
  217. ALLOCATION_FLAG_STRATEGY_MIN_MEMORY = 0x00010000,
  218. /** Allocation strategy that chooses first suitable free range for the allocation -
  219. not necessarily in terms of the smallest offset but the one that is easiest and fastest to find
  220. to minimize allocation time, possibly at the expense of allocation quality.
  221. */
  222. ALLOCATION_FLAG_STRATEGY_MIN_TIME = 0x00020000,
  223. /** Allocation strategy that chooses always the lowest offset in available space.
  224. This is not the most efficient strategy but achieves highly packed data.
  225. Used internally by defragmentation, not recomended in typical usage.
  226. */
  227. ALLOCATION_FLAG_STRATEGY_MIN_OFFSET = 0x0004000,
  228. /// Alias to #ALLOCATION_FLAG_STRATEGY_MIN_MEMORY.
  229. ALLOCATION_FLAG_STRATEGY_BEST_FIT = ALLOCATION_FLAG_STRATEGY_MIN_MEMORY,
  230. /// Alias to #ALLOCATION_FLAG_STRATEGY_MIN_TIME.
  231. ALLOCATION_FLAG_STRATEGY_FIRST_FIT = ALLOCATION_FLAG_STRATEGY_MIN_TIME,
  232. /// A bit mask to extract only `STRATEGY` bits from entire set of flags.
  233. ALLOCATION_FLAG_STRATEGY_MASK =
  234. ALLOCATION_FLAG_STRATEGY_MIN_MEMORY |
  235. ALLOCATION_FLAG_STRATEGY_MIN_TIME |
  236. ALLOCATION_FLAG_STRATEGY_MIN_OFFSET,
  237. };
  238. /// \brief Parameters of created D3D12MA::Allocation object. To be used with Allocator::CreateResource.
  239. struct ALLOCATION_DESC
  240. {
  241. /// Flags.
  242. ALLOCATION_FLAGS Flags;
  243. /** \brief The type of memory heap where the new allocation should be placed.
  244. It must be one of: `D3D12_HEAP_TYPE_DEFAULT`, `D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`.
  245. When D3D12MA::ALLOCATION_DESC::CustomPool != NULL this member is ignored.
  246. */
  247. D3D12_HEAP_TYPE HeapType;
  248. /** \brief Additional heap flags to be used when allocating memory.
  249. In most cases it can be 0.
  250. - If you use D3D12MA::Allocator::CreateResource(), you don't need to care.
  251. Necessary flag `D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS`, `D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES`,
  252. or `D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES` is added automatically.
  253. - If you use D3D12MA::Allocator::AllocateMemory(), you should specify one of those `ALLOW_ONLY` flags.
  254. Except when you validate that D3D12MA::Allocator::GetD3D12Options()`.ResourceHeapTier == D3D12_RESOURCE_HEAP_TIER_1` -
  255. then you can leave it 0.
  256. - You can specify additional flags if needed. Then the memory will always be allocated as
  257. separate block using `D3D12Device::CreateCommittedResource` or `CreateHeap`, not as part of an existing larget block.
  258. When D3D12MA::ALLOCATION_DESC::CustomPool != NULL this member is ignored.
  259. */
  260. D3D12_HEAP_FLAGS ExtraHeapFlags;
  261. /** \brief Custom pool to place the new resource in. Optional.
  262. When not NULL, the resource will be created inside specified custom pool.
  263. */
  264. Pool* CustomPool;
  265. /// Custom general-purpose pointer that will be stored in D3D12MA::Allocation.
  266. void* pPrivateData;
  267. };
  268. /** \brief Calculated statistics of memory usage e.g. in a specific memory heap type,
  269. memory segment group, custom pool, or total.
  270. These are fast to calculate.
  271. See functions: D3D12MA::Allocator::GetBudget(), D3D12MA::Pool::GetStatistics().
  272. */
  273. struct Statistics
  274. {
  275. /** \brief Number of D3D12 memory blocks allocated - `ID3D12Heap` objects and committed resources.
  276. */
  277. UINT BlockCount;
  278. /** \brief Number of D3D12MA::Allocation objects allocated.
  279. Committed allocations have their own blocks, so each one adds 1 to `AllocationCount` as well as `BlockCount`.
  280. */
  281. UINT AllocationCount;
  282. /** \brief Number of bytes allocated in memory blocks.
  283. */
  284. UINT64 BlockBytes;
  285. /** \brief Total number of bytes occupied by all D3D12MA::Allocation objects.
  286. Always less or equal than `BlockBytes`.
  287. Difference `(BlockBytes - AllocationBytes)` is the amount of memory allocated from D3D12
  288. but unused by any D3D12MA::Allocation.
  289. */
  290. UINT64 AllocationBytes;
  291. };
  292. /** \brief More detailed statistics than D3D12MA::Statistics.
  293. These are slower to calculate. Use for debugging purposes.
  294. See functions: D3D12MA::Allocator::CalculateStatistics(), D3D12MA::Pool::CalculateStatistics().
  295. Averages are not provided because they can be easily calculated as:
  296. \code
  297. UINT64 AllocationSizeAvg = DetailedStats.Statistics.AllocationBytes / detailedStats.Statistics.AllocationCount;
  298. UINT64 UnusedBytes = DetailedStats.Statistics.BlockBytes - DetailedStats.Statistics.AllocationBytes;
  299. UINT64 UnusedRangeSizeAvg = UnusedBytes / DetailedStats.UnusedRangeCount;
  300. \endcode
  301. */
  302. struct DetailedStatistics
  303. {
  304. /// Basic statistics.
  305. Statistics Stats;
  306. /// Number of free ranges of memory between allocations.
  307. UINT UnusedRangeCount;
  308. /// Smallest allocation size. `UINT64_MAX` if there are 0 allocations.
  309. UINT64 AllocationSizeMin;
  310. /// Largest allocation size. 0 if there are 0 allocations.
  311. UINT64 AllocationSizeMax;
  312. /// Smallest empty range size. `UINT64_MAX` if there are 0 empty ranges.
  313. UINT64 UnusedRangeSizeMin;
  314. /// Largest empty range size. 0 if there are 0 empty ranges.
  315. UINT64 UnusedRangeSizeMax;
  316. };
  317. /** \brief General statistics from current state of the allocator -
  318. total memory usage across all memory heaps and segments.
  319. These are slower to calculate. Use for debugging purposes.
  320. See function D3D12MA::Allocator::CalculateStatistics().
  321. */
  322. struct TotalStatistics
  323. {
  324. /** \brief One element for each type of heap located at the following indices:
  325. - 0 = `D3D12_HEAP_TYPE_DEFAULT`
  326. - 1 = `D3D12_HEAP_TYPE_UPLOAD`
  327. - 2 = `D3D12_HEAP_TYPE_READBACK`
  328. - 3 = `D3D12_HEAP_TYPE_CUSTOM`
  329. */
  330. DetailedStatistics HeapType[4];
  331. /** \brief One element for each memory segment group located at the following indices:
  332. - 0 = `DXGI_MEMORY_SEGMENT_GROUP_LOCAL`
  333. - 1 = `DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL`
  334. Meaning of these segment groups is:
  335. - When `IsUMA() == FALSE` (discrete graphics card):
  336. - `DXGI_MEMORY_SEGMENT_GROUP_LOCAL` (index 0) represents GPU memory
  337. (resources allocated in `D3D12_HEAP_TYPE_DEFAULT` or `D3D12_MEMORY_POOL_L1`).
  338. - `DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL` (index 1) represents system memory
  339. (resources allocated in `D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`, or `D3D12_MEMORY_POOL_L0`).
  340. - When `IsUMA() == TRUE` (integrated graphics chip):
  341. - `DXGI_MEMORY_SEGMENT_GROUP_LOCAL` = (index 0) represents memory shared for all the resources.
  342. - `DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL` = (index 1) is unused and always 0.
  343. */
  344. DetailedStatistics MemorySegmentGroup[2];
  345. /// Total statistics from all memory allocated from D3D12.
  346. DetailedStatistics Total;
  347. };
  348. /** \brief %Statistics of current memory usage and available budget for a specific memory segment group.
  349. These are fast to calculate. See function D3D12MA::Allocator::GetBudget().
  350. */
  351. struct Budget
  352. {
  353. /** \brief %Statistics fetched from the library.
  354. */
  355. Statistics Stats;
  356. /** \brief Estimated current memory usage of the program.
  357. Fetched from system using `IDXGIAdapter3::QueryVideoMemoryInfo` if possible.
  358. It might be different than `BlockBytes` (usually higher) due to additional implicit objects
  359. also occupying the memory, like swapchain, pipeline state objects, descriptor heaps, command lists, or
  360. heaps and resources allocated outside of this library, if any.
  361. */
  362. UINT64 UsageBytes;
  363. /** \brief Estimated amount of memory available to the program.
  364. Fetched from system using `IDXGIAdapter3::QueryVideoMemoryInfo` if possible.
  365. It might be different (most probably smaller) than memory capacity returned
  366. by D3D12MA::Allocator::GetMemoryCapacity() due to factors
  367. external to the program, decided by the operating system.
  368. Difference `BudgetBytes - UsageBytes` is the amount of additional memory that can probably
  369. be allocated without problems. Exceeding the budget may result in various problems.
  370. */
  371. UINT64 BudgetBytes;
  372. };
  373. /// \brief Represents single memory allocation done inside VirtualBlock.
  374. struct D3D12MA_API VirtualAllocation
  375. {
  376. /// \brief Unique idenitfier of current allocation. 0 means null/invalid.
  377. AllocHandle AllocHandle;
  378. };
  379. /** \brief Represents single memory allocation.
  380. It may be either implicit memory heap dedicated to a single resource or a
  381. specific region of a bigger heap plus unique offset.
  382. To create such object, fill structure D3D12MA::ALLOCATION_DESC and call function
  383. Allocator::CreateResource.
  384. The object remembers size and some other information.
  385. To retrieve this information, use methods of this class.
  386. The object also remembers `ID3D12Resource` and "owns" a reference to it,
  387. so it calls `%Release()` on the resource when destroyed.
  388. */
  389. class D3D12MA_API Allocation : public IUnknownImpl
  390. {
  391. public:
  392. /** \brief Returns offset in bytes from the start of memory heap.
  393. You usually don't need to use this offset. If you create a buffer or a texture together with the allocation using function
  394. D3D12MA::Allocator::CreateResource, functions that operate on that resource refer to the beginning of the resource,
  395. not entire memory heap.
  396. If the Allocation represents committed resource with implicit heap, returns 0.
  397. */
  398. UINT64 GetOffset() const;
  399. /// Returns alignment that resource was created with.
  400. UINT64 GetAlignment() const { return m_Alignment; }
  401. /** \brief Returns size in bytes of the allocation.
  402. - If you created a buffer or a texture together with the allocation using function D3D12MA::Allocator::CreateResource,
  403. this is the size of the resource returned by `ID3D12Device::GetResourceAllocationInfo`.
  404. - For allocations made out of bigger memory blocks, this also is the size of the memory region assigned exclusively to this allocation.
  405. - For resources created as committed, this value may not be accurate. DirectX implementation may optimize memory usage internally
  406. so that you may even observe regions of `ID3D12Resource::GetGPUVirtualAddress()` + Allocation::GetSize() to overlap in memory and still work correctly.
  407. */
  408. UINT64 GetSize() const { return m_Size; }
  409. /** \brief Returns D3D12 resource associated with this object.
  410. Calling this method doesn't increment resource's reference counter.
  411. */
  412. ID3D12Resource* GetResource() const { return m_Resource; }
  413. /// Releases the resource currently pointed by the allocation (if any), sets it to new one, incrementing its reference counter (if not null).
  414. void SetResource(ID3D12Resource* pResource);
  415. /** \brief Returns memory heap that the resource is created in.
  416. If the Allocation represents committed resource with implicit heap, returns NULL.
  417. */
  418. ID3D12Heap* GetHeap() const;
  419. /// Changes custom pointer for an allocation to a new value.
  420. void SetPrivateData(void* pPrivateData) { m_pPrivateData = pPrivateData; }
  421. /// Get custom pointer associated with the allocation.
  422. void* GetPrivateData() const { return m_pPrivateData; }
  423. /** \brief Associates a name with the allocation object. This name is for use in debug diagnostics and tools.
  424. Internal copy of the string is made, so the memory pointed by the argument can be
  425. changed of freed immediately after this call.
  426. `Name` can be null.
  427. */
  428. void SetName(LPCWSTR Name);
  429. /** \brief Returns the name associated with the allocation object.
  430. Returned string points to an internal copy.
  431. If no name was associated with the allocation, returns null.
  432. */
  433. LPCWSTR GetName() const { return m_Name; }
  434. /** \brief Returns `TRUE` if the memory of the allocation was filled with zeros when the allocation was created.
  435. Returns `TRUE` only if the allocator is sure that the entire memory where the
  436. allocation was created was filled with zeros at the moment the allocation was made.
  437. Returns `FALSE` if the memory could potentially contain garbage data.
  438. If it's a render-target or depth-stencil texture, it then needs proper
  439. initialization with `ClearRenderTargetView`, `ClearDepthStencilView`, `DiscardResource`,
  440. or a copy operation, as described on page
  441. "ID3D12Device::CreatePlacedResource method - Notes on the required resource initialization" in Microsoft documentation.
  442. Please note that rendering a fullscreen triangle or quad to the texture as
  443. a render target is not a proper way of initialization!
  444. See also articles:
  445. - "Coming to DirectX 12: More control over memory allocation" on DirectX Developer Blog
  446. - ["Initializing DX12 Textures After Allocation and Aliasing"](https://asawicki.info/news_1724_initializing_dx12_textures_after_allocation_and_aliasing).
  447. */
  448. BOOL WasZeroInitialized() const { return m_PackedData.WasZeroInitialized(); }
  449. protected:
  450. void ReleaseThis() override;
  451. private:
  452. friend class AllocatorPimpl;
  453. friend class BlockVector;
  454. friend class CommittedAllocationList;
  455. friend class JsonWriter;
  456. friend class BlockMetadata_Linear;
  457. friend class DefragmentationContextPimpl;
  458. friend struct CommittedAllocationListItemTraits;
  459. template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);
  460. template<typename T> friend class PoolAllocator;
  461. enum Type
  462. {
  463. TYPE_COMMITTED,
  464. TYPE_PLACED,
  465. TYPE_HEAP,
  466. TYPE_COUNT
  467. };
  468. AllocatorPimpl* m_Allocator;
  469. UINT64 m_Size;
  470. UINT64 m_Alignment;
  471. ID3D12Resource* m_Resource;
  472. void* m_pPrivateData;
  473. wchar_t* m_Name;
  474. union
  475. {
  476. struct
  477. {
  478. CommittedAllocationList* list;
  479. Allocation* prev;
  480. Allocation* next;
  481. } m_Committed;
  482. struct
  483. {
  484. AllocHandle allocHandle;
  485. NormalBlock* block;
  486. } m_Placed;
  487. struct
  488. {
  489. // Beginning must be compatible with m_Committed.
  490. CommittedAllocationList* list;
  491. Allocation* prev;
  492. Allocation* next;
  493. ID3D12Heap* heap;
  494. } m_Heap;
  495. };
  496. struct PackedData
  497. {
  498. public:
  499. PackedData() :
  500. m_Type(0), m_ResourceDimension(0), m_ResourceFlags(0), m_TextureLayout(0), m_WasZeroInitialized(0) { }
  501. Type GetType() const { return (Type)m_Type; }
  502. D3D12_RESOURCE_DIMENSION GetResourceDimension() const { return (D3D12_RESOURCE_DIMENSION)m_ResourceDimension; }
  503. D3D12_RESOURCE_FLAGS GetResourceFlags() const { return (D3D12_RESOURCE_FLAGS)m_ResourceFlags; }
  504. D3D12_TEXTURE_LAYOUT GetTextureLayout() const { return (D3D12_TEXTURE_LAYOUT)m_TextureLayout; }
  505. BOOL WasZeroInitialized() const { return (BOOL)m_WasZeroInitialized; }
  506. void SetType(Type type);
  507. void SetResourceDimension(D3D12_RESOURCE_DIMENSION resourceDimension);
  508. void SetResourceFlags(D3D12_RESOURCE_FLAGS resourceFlags);
  509. void SetTextureLayout(D3D12_TEXTURE_LAYOUT textureLayout);
  510. void SetWasZeroInitialized(BOOL wasZeroInitialized) { m_WasZeroInitialized = wasZeroInitialized ? 1 : 0; }
  511. private:
  512. UINT m_Type : 2; // enum Type
  513. UINT m_ResourceDimension : 3; // enum D3D12_RESOURCE_DIMENSION
  514. UINT m_ResourceFlags : 24; // flags D3D12_RESOURCE_FLAGS
  515. UINT m_TextureLayout : 9; // enum D3D12_TEXTURE_LAYOUT
  516. UINT m_WasZeroInitialized : 1; // BOOL
  517. } m_PackedData;
  518. Allocation(AllocatorPimpl* allocator, UINT64 size, UINT64 alignment, BOOL wasZeroInitialized);
  519. // Nothing here, everything already done in Release.
  520. virtual ~Allocation() = default;
  521. void InitCommitted(CommittedAllocationList* list);
  522. void InitPlaced(AllocHandle allocHandle, NormalBlock* block);
  523. void InitHeap(CommittedAllocationList* list, ID3D12Heap* heap);
  524. void SwapBlockAllocation(Allocation* allocation);
  525. // If the Allocation represents committed resource with implicit heap, returns UINT64_MAX.
  526. AllocHandle GetAllocHandle() const;
  527. NormalBlock* GetBlock();
  528. template<typename D3D12_RESOURCE_DESC_T>
  529. void SetResourcePointer(ID3D12Resource* resource, const D3D12_RESOURCE_DESC_T* pResourceDesc);
  530. void FreeName();
  531. D3D12MA_CLASS_NO_COPY(Allocation)
  532. };
  533. /// Flags to be passed as DEFRAGMENTATION_DESC::Flags.
  534. enum DEFRAGMENTATION_FLAGS
  535. {
  536. /** Use simple but fast algorithm for defragmentation.
  537. May not achieve best results but will require least time to compute and least allocations to copy.
  538. */
  539. DEFRAGMENTATION_FLAG_ALGORITHM_FAST = 0x1,
  540. /** Default defragmentation algorithm, applied also when no `ALGORITHM` flag is specified.
  541. Offers a balance between defragmentation quality and the amount of allocations and bytes that need to be moved.
  542. */
  543. DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED = 0x2,
  544. /** Perform full defragmentation of memory.
  545. Can result in notably more time to compute and allocations to copy, but will achieve best memory packing.
  546. */
  547. DEFRAGMENTATION_FLAG_ALGORITHM_FULL = 0x4,
  548. /// A bit mask to extract only `ALGORITHM` bits from entire set of flags.
  549. DEFRAGMENTATION_FLAG_ALGORITHM_MASK =
  550. DEFRAGMENTATION_FLAG_ALGORITHM_FAST |
  551. DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED |
  552. DEFRAGMENTATION_FLAG_ALGORITHM_FULL
  553. };
  554. /** \brief Parameters for defragmentation.
  555. To be used with functions Allocator::BeginDefragmentation() and Pool::BeginDefragmentation().
  556. */
  557. struct DEFRAGMENTATION_DESC
  558. {
  559. /// Flags.
  560. DEFRAGMENTATION_FLAGS Flags;
  561. /** \brief Maximum numbers of bytes that can be copied during single pass, while moving allocations to different places.
  562. 0 means no limit.
  563. */
  564. UINT64 MaxBytesPerPass;
  565. /** \brief Maximum number of allocations that can be moved during single pass to a different place.
  566. 0 means no limit.
  567. */
  568. UINT32 MaxAllocationsPerPass;
  569. };
  570. /// Operation performed on single defragmentation move.
  571. enum DEFRAGMENTATION_MOVE_OPERATION
  572. {
  573. /** Resource has been recreated at `pDstTmpAllocation`, data has been copied, old resource has been destroyed.
  574. `pSrcAllocation` will be changed to point to the new place. This is the default value set by DefragmentationContext::BeginPass().
  575. */
  576. DEFRAGMENTATION_MOVE_OPERATION_COPY = 0,
  577. /// Set this value if you cannot move the allocation. New place reserved at `pDstTmpAllocation` will be freed. `pSrcAllocation` will remain unchanged.
  578. DEFRAGMENTATION_MOVE_OPERATION_IGNORE = 1,
  579. /// Set this value if you decide to abandon the allocation and you destroyed the resource. New place reserved `pDstTmpAllocation` will be freed, along with `pSrcAllocation`.
  580. DEFRAGMENTATION_MOVE_OPERATION_DESTROY = 2,
  581. };
  582. /// Single move of an allocation to be done for defragmentation.
  583. struct DEFRAGMENTATION_MOVE
  584. {
  585. /** \brief Operation to be performed on the allocation by DefragmentationContext::EndPass().
  586. Default value is #DEFRAGMENTATION_MOVE_OPERATION_COPY. You can modify it.
  587. */
  588. DEFRAGMENTATION_MOVE_OPERATION Operation;
  589. /// %Allocation that should be moved.
  590. Allocation* pSrcAllocation;
  591. /** \brief Temporary allocation pointing to destination memory that will replace `pSrcAllocation`.
  592. Use it to retrieve new `ID3D12Heap` and offset to create new `ID3D12Resource` and then store it here via Allocation::SetResource().
  593. \warning Do not store this allocation in your data structures! It exists only temporarily, for the duration of the defragmentation pass,
  594. to be used for storing newly created resource. DefragmentationContext::EndPass() will destroy it and make `pSrcAllocation` point to this memory.
  595. */
  596. Allocation* pDstTmpAllocation;
  597. };
  598. /** \brief Parameters for incremental defragmentation steps.
  599. To be used with function DefragmentationContext::BeginPass().
  600. */
  601. struct DEFRAGMENTATION_PASS_MOVE_INFO
  602. {
  603. /// Number of elements in the `pMoves` array.
  604. UINT32 MoveCount;
  605. /** \brief Array of moves to be performed by the user in the current defragmentation pass.
  606. Pointer to an array of `MoveCount` elements, owned by %D3D12MA, created in DefragmentationContext::BeginPass(), destroyed in DefragmentationContext::EndPass().
  607. For each element, you should:
  608. 1. Create a new resource in the place pointed by `pMoves[i].pDstTmpAllocation->GetHeap()` + `pMoves[i].pDstTmpAllocation->GetOffset()`.
  609. 2. Store new resource in `pMoves[i].pDstTmpAllocation` by using Allocation::SetResource(). It will later replace old resource from `pMoves[i].pSrcAllocation`.
  610. 3. Copy data from the `pMoves[i].pSrcAllocation` e.g. using `D3D12GraphicsCommandList::CopyResource`.
  611. 4. Make sure these commands finished executing on the GPU.
  612. Only then you can finish defragmentation pass by calling DefragmentationContext::EndPass().
  613. After this call, the allocation will point to the new place in memory.
  614. Alternatively, if you cannot move specific allocation,
  615. you can set DEFRAGMENTATION_MOVE::Operation to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_IGNORE.
  616. Alternatively, if you decide you want to completely remove the allocation,
  617. set DEFRAGMENTATION_MOVE::Operation to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_DESTROY.
  618. Then, after DefragmentationContext::EndPass() the allocation will be released.
  619. */
  620. DEFRAGMENTATION_MOVE* pMoves;
  621. };
  622. /// %Statistics returned for defragmentation process by function DefragmentationContext::GetStats().
  623. struct DEFRAGMENTATION_STATS
  624. {
  625. /// Total number of bytes that have been copied while moving allocations to different places.
  626. UINT64 BytesMoved;
  627. /// Total number of bytes that have been released to the system by freeing empty heaps.
  628. UINT64 BytesFreed;
  629. /// Number of allocations that have been moved to different places.
  630. UINT32 AllocationsMoved;
  631. /// Number of empty `ID3D12Heap` objects that have been released to the system.
  632. UINT32 HeapsFreed;
  633. };
  634. /** \brief Represents defragmentation process in progress.
  635. You can create this object using Allocator::BeginDefragmentation (for default pools) or
  636. Pool::BeginDefragmentation (for a custom pool).
  637. */
  638. class D3D12MA_API DefragmentationContext : public IUnknownImpl
  639. {
  640. public:
  641. /** \brief Starts single defragmentation pass.
  642. \param[out] pPassInfo Computed informations for current pass.
  643. \returns
  644. - `S_OK` if no more moves are possible. Then you can omit call to DefragmentationContext::EndPass() and simply end whole defragmentation.
  645. - `S_FALSE` if there are pending moves returned in `pPassInfo`. You need to perform them, call DefragmentationContext::EndPass(),
  646. and then preferably try another pass with DefragmentationContext::BeginPass().
  647. */
  648. HRESULT BeginPass(DEFRAGMENTATION_PASS_MOVE_INFO* pPassInfo);
  649. /** \brief Ends single defragmentation pass.
  650. \param pPassInfo Computed informations for current pass filled by DefragmentationContext::BeginPass() and possibly modified by you.
  651. \return Returns `S_OK` if no more moves are possible or `S_FALSE` if more defragmentations are possible.
  652. Ends incremental defragmentation pass and commits all defragmentation moves from `pPassInfo`.
  653. After this call:
  654. - %Allocation at `pPassInfo[i].pSrcAllocation` that had `pPassInfo[i].Operation ==` #DEFRAGMENTATION_MOVE_OPERATION_COPY
  655. (which is the default) will be pointing to the new destination place.
  656. - %Allocation at `pPassInfo[i].pSrcAllocation` that had `pPassInfo[i].operation ==` #DEFRAGMENTATION_MOVE_OPERATION_DESTROY
  657. will be released.
  658. If no more moves are possible you can end whole defragmentation.
  659. */
  660. HRESULT EndPass(DEFRAGMENTATION_PASS_MOVE_INFO* pPassInfo);
  661. /** \brief Returns statistics of the defragmentation performed so far.
  662. */
  663. void GetStats(DEFRAGMENTATION_STATS* pStats);
  664. protected:
  665. void ReleaseThis() override;
  666. private:
  667. friend class Pool;
  668. friend class Allocator;
  669. template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);
  670. DefragmentationContextPimpl* m_Pimpl;
  671. DefragmentationContext(AllocatorPimpl* allocator,
  672. const DEFRAGMENTATION_DESC& desc,
  673. BlockVector* poolVector);
  674. ~DefragmentationContext();
  675. D3D12MA_CLASS_NO_COPY(DefragmentationContext)
  676. };
  677. /// \brief Bit flags to be used with POOL_DESC::Flags.
  678. enum POOL_FLAGS
  679. {
  680. /// Zero
  681. POOL_FLAG_NONE = 0,
  682. /** \brief Enables alternative, linear allocation algorithm in this pool.
  683. Specify this flag to enable linear allocation algorithm, which always creates
  684. new allocations after last one and doesn't reuse space from allocations freed in
  685. between. It trades memory consumption for simplified algorithm and data
  686. structure, which has better performance and uses less memory for metadata.
  687. By using this flag, you can achieve behavior of free-at-once, stack,
  688. ring buffer, and double stack.
  689. For details, see documentation chapter \ref linear_algorithm.
  690. */
  691. POOL_FLAG_ALGORITHM_LINEAR = 0x1,
  692. /** \brief Optimization, allocate MSAA textures as committed resources always.
  693. Specify this flag to create MSAA textures with implicit heaps, as if they were created
  694. with flag D3D12MA::ALLOCATION_FLAG_COMMITTED. Usage of this flags enables pool to create its heaps
  695. on smaller alignment not suitable for MSAA textures.
  696. */
  697. POOL_FLAG_MSAA_TEXTURES_ALWAYS_COMMITTED = 0x2,
  698. // Bit mask to extract only `ALGORITHM` bits from entire set of flags.
  699. POOL_FLAG_ALGORITHM_MASK = POOL_FLAG_ALGORITHM_LINEAR
  700. };
  701. /// \brief Parameters of created D3D12MA::Pool object. To be used with D3D12MA::Allocator::CreatePool.
  702. struct POOL_DESC
  703. {
  704. /// Flags.
  705. POOL_FLAGS Flags;
  706. /** \brief The parameters of memory heap where allocations of this pool should be placed.
  707. In the simplest case, just fill it with zeros and set `Type` to one of: `D3D12_HEAP_TYPE_DEFAULT`,
  708. `D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`. Additional parameters can be used e.g. to utilize UMA.
  709. */
  710. D3D12_HEAP_PROPERTIES HeapProperties;
  711. /** \brief Heap flags to be used when allocating heaps of this pool.
  712. It should contain one of these values, depending on type of resources you are going to create in this heap:
  713. `D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS`,
  714. `D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES`,
  715. `D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES`.
  716. Except if ResourceHeapTier = 2, then it may be `D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES` = 0.
  717. You can specify additional flags if needed.
  718. */
  719. D3D12_HEAP_FLAGS HeapFlags;
  720. /** \brief Size of a single heap (memory block) to be allocated as part of this pool, in bytes. Optional.
  721. Specify nonzero to set explicit, constant size of memory blocks used by this pool.
  722. Leave 0 to use default and let the library manage block sizes automatically.
  723. Then sizes of particular blocks may vary.
  724. */
  725. UINT64 BlockSize;
  726. /** \brief Minimum number of heaps (memory blocks) to be always allocated in this pool, even if they stay empty. Optional.
  727. Set to 0 to have no preallocated blocks and allow the pool be completely empty.
  728. */
  729. UINT MinBlockCount;
  730. /** \brief Maximum number of heaps (memory blocks) that can be allocated in this pool. Optional.
  731. Set to 0 to use default, which is `UINT64_MAX`, which means no limit.
  732. Set to same value as D3D12MA::POOL_DESC::MinBlockCount to have fixed amount of memory allocated
  733. throughout whole lifetime of this pool.
  734. */
  735. UINT MaxBlockCount;
  736. /** \brief Additional minimum alignment to be used for all allocations created from this pool. Can be 0.
  737. Leave 0 (default) not to impose any additional alignment. If not 0, it must be a power of two.
  738. */
  739. UINT64 MinAllocationAlignment;
  740. /** \brief Additional parameter allowing pool to create resources with passed protected session.
  741. If not null then all the heaps and committed resources will be created with this parameter.
  742. Valid only if ID3D12Device4 interface is present in current Windows SDK!
  743. */
  744. ID3D12ProtectedResourceSession* pProtectedSession;
  745. /** \brief Residency priority to be set for all allocations made in this pool. Optional.
  746. Set this parameter to one of the possible enum values e.g. `D3D12_RESIDENCY_PRIORITY_HIGH`
  747. to apply specific residency priority to all allocations made in this pool:
  748. `ID3D12Heap` memory blocks used to sub-allocate for placed resources, as well as
  749. committed resources or heaps created when D3D12MA::ALLOCATION_FLAG_COMMITTED is used.
  750. This can increase/decrease chance that the memory will be pushed out from VRAM
  751. to system RAM when the system runs out of memory, which is invisible to the developer
  752. using D3D12 API while it can degrade performance.
  753. Priority is set using function `ID3D12Device1::SetResidencyPriority`.
  754. It is performed only when `ID3D12Device1` interface is defined and successfully obtained.
  755. Otherwise, this parameter is ignored.
  756. This parameter is optional. If you set it to `D3D12_RESIDENCY_PRIORITY(0)`,
  757. residency priority will not be set for allocations made in this pool.
  758. There is no equivalent parameter for allocations made in default pools.
  759. If you want to set residency priority for such allocation, you need to do it manually:
  760. allocate with D3D12MA::ALLOCATION_FLAG_COMMITTED and call
  761. `ID3D12Device1::SetResidencyPriority`, passing `allocation->GetResource()`.
  762. */
  763. D3D12_RESIDENCY_PRIORITY ResidencyPriority;
  764. };
  765. /** \brief Custom memory pool
  766. Represents a separate set of heaps (memory blocks) that can be used to create
  767. D3D12MA::Allocation-s and resources in it. Usually there is no need to create custom
  768. pools - creating resources in default pool is sufficient.
  769. To create custom pool, fill D3D12MA::POOL_DESC and call D3D12MA::Allocator::CreatePool.
  770. */
  771. class D3D12MA_API Pool : public IUnknownImpl
  772. {
  773. public:
  774. /** \brief Returns copy of parameters of the pool.
  775. These are the same parameters as passed to D3D12MA::Allocator::CreatePool.
  776. */
  777. POOL_DESC GetDesc() const;
  778. /** \brief Retrieves basic statistics of the custom pool that are fast to calculate.
  779. \param[out] pStats %Statistics of the current pool.
  780. */
  781. void GetStatistics(Statistics* pStats);
  782. /** \brief Retrieves detailed statistics of the custom pool that are slower to calculate.
  783. \param[out] pStats %Statistics of the current pool.
  784. */
  785. void CalculateStatistics(DetailedStatistics* pStats);
  786. /** \brief Associates a name with the pool. This name is for use in debug diagnostics and tools.
  787. Internal copy of the string is made, so the memory pointed by the argument can be
  788. changed of freed immediately after this call.
  789. `Name` can be NULL.
  790. */
  791. void SetName(LPCWSTR Name);
  792. /** \brief Returns the name associated with the pool object.
  793. Returned string points to an internal copy.
  794. If no name was associated with the allocation, returns NULL.
  795. */
  796. LPCWSTR GetName() const;
  797. /** \brief Begins defragmentation process of the current pool.
  798. \param pDesc Structure filled with parameters of defragmentation.
  799. \param[out] ppContext Context object that will manage defragmentation.
  800. \returns
  801. - `S_OK` if defragmentation can begin.
  802. - `E_NOINTERFACE` if defragmentation is not supported.
  803. For more information about defragmentation, see documentation chapter:
  804. [Defragmentation](@ref defragmentation).
  805. */
  806. HRESULT BeginDefragmentation(const DEFRAGMENTATION_DESC* pDesc, DefragmentationContext** ppContext);
  807. protected:
  808. void ReleaseThis() override;
  809. private:
  810. friend class Allocator;
  811. friend class AllocatorPimpl;
  812. template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);
  813. PoolPimpl* m_Pimpl;
  814. Pool(Allocator* allocator, const POOL_DESC &desc);
  815. ~Pool();
  816. D3D12MA_CLASS_NO_COPY(Pool)
  817. };
  818. /// \brief Bit flags to be used with ALLOCATOR_DESC::Flags.
  819. enum ALLOCATOR_FLAGS
  820. {
  821. /// Zero
  822. ALLOCATOR_FLAG_NONE = 0,
  823. /**
  824. Allocator and all objects created from it will not be synchronized internally,
  825. so you must guarantee they are used from only one thread at a time or
  826. synchronized by you.
  827. Using this flag may increase performance because internal mutexes are not used.
  828. */
  829. ALLOCATOR_FLAG_SINGLETHREADED = 0x1,
  830. /**
  831. Every allocation will have its own memory block.
  832. To be used for debugging purposes.
  833. */
  834. ALLOCATOR_FLAG_ALWAYS_COMMITTED = 0x2,
  835. /**
  836. Heaps created for the default pools will be created with flag `D3D12_HEAP_FLAG_CREATE_NOT_ZEROED`,
  837. allowing for their memory to be not zeroed by the system if possible,
  838. which can speed up allocation.
  839. Only affects default pools.
  840. To use the flag with @ref custom_pools, you need to add it manually:
  841. \code
  842. poolDesc.heapFlags |= D3D12_HEAP_FLAG_CREATE_NOT_ZEROED;
  843. \endcode
  844. Only avaiable if `ID3D12Device8` is present. Otherwise, the flag is ignored.
  845. */
  846. ALLOCATOR_FLAG_DEFAULT_POOLS_NOT_ZEROED = 0x4,
  847. /** \brief Optimization, allocate MSAA textures as committed resources always.
  848. Specify this flag to create MSAA textures with implicit heaps, as if they were created
  849. with flag D3D12MA::ALLOCATION_FLAG_COMMITTED. Usage of this flags enables all default pools
  850. to create its heaps on smaller alignment not suitable for MSAA textures.
  851. */
  852. ALLOCATOR_FLAG_MSAA_TEXTURES_ALWAYS_COMMITTED = 0x8,
  853. };
  854. /// \brief Parameters of created Allocator object. To be used with CreateAllocator().
  855. struct ALLOCATOR_DESC
  856. {
  857. /// Flags.
  858. ALLOCATOR_FLAGS Flags;
  859. /** Direct3D device object that the allocator should be attached to.
  860. Allocator is doing `AddRef`/`Release` on this object.
  861. */
  862. ID3D12Device* pDevice;
  863. /** \brief Preferred size of a single `ID3D12Heap` block to be allocated.
  864. Set to 0 to use default, which is currently 64 MiB.
  865. */
  866. UINT64 PreferredBlockSize;
  867. /** \brief Custom CPU memory allocation callbacks. Optional.
  868. Optional, can be null. When specified, will be used for all CPU-side memory allocations.
  869. */
  870. const ALLOCATION_CALLBACKS* pAllocationCallbacks;
  871. /** DXGI Adapter object that you use for D3D12 and this allocator.
  872. Allocator is doing `AddRef`/`Release` on this object.
  873. */
  874. IDXGIAdapter* pAdapter;
  875. };
  876. /**
  877. \brief Represents main object of this library initialized for particular `ID3D12Device`.
  878. Fill structure D3D12MA::ALLOCATOR_DESC and call function CreateAllocator() to create it.
  879. Call method `Release()` to destroy it.
  880. It is recommended to create just one object of this type per `ID3D12Device` object,
  881. right after Direct3D 12 is initialized and keep it alive until before Direct3D device is destroyed.
  882. */
  883. class D3D12MA_API Allocator : public IUnknownImpl
  884. {
  885. public:
  886. /// Returns cached options retrieved from D3D12 device.
  887. const D3D12_FEATURE_DATA_D3D12_OPTIONS& GetD3D12Options() const;
  888. /** \brief Returns true if `D3D12_FEATURE_DATA_ARCHITECTURE1::UMA` was found to be true.
  889. For more information about how to use it, see articles in Microsoft Docs articles:
  890. - "UMA Optimizations: CPU Accessible Textures and Standard Swizzle"
  891. - "D3D12_FEATURE_DATA_ARCHITECTURE structure (d3d12.h)"
  892. - "ID3D12Device::GetCustomHeapProperties method (d3d12.h)"
  893. */
  894. BOOL IsUMA() const;
  895. /** \brief Returns true if `D3D12_FEATURE_DATA_ARCHITECTURE1::CacheCoherentUMA` was found to be true.
  896. For more information about how to use it, see articles in Microsoft Docs articles:
  897. - "UMA Optimizations: CPU Accessible Textures and Standard Swizzle"
  898. - "D3D12_FEATURE_DATA_ARCHITECTURE structure (d3d12.h)"
  899. - "ID3D12Device::GetCustomHeapProperties method (d3d12.h)"
  900. */
  901. BOOL IsCacheCoherentUMA() const;
  902. /** \brief Returns total amount of memory of specific segment group, in bytes.
  903. \param memorySegmentGroup use `DXGI_MEMORY_SEGMENT_GROUP_LOCAL` or DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL`.
  904. This information is taken from `DXGI_ADAPTER_DESC`.
  905. It is not recommended to use this number.
  906. You should preferably call GetBudget() and limit memory usage to D3D12MA::Budget::BudgetBytes instead.
  907. - When IsUMA() `== FALSE` (discrete graphics card):
  908. - `GetMemoryCapacity(DXGI_MEMORY_SEGMENT_GROUP_LOCAL)` returns the size of the video memory.
  909. - `GetMemoryCapacity(DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)` returns the size of the system memory available for D3D12 resources.
  910. - When IsUMA() `== TRUE` (integrated graphics chip):
  911. - `GetMemoryCapacity(DXGI_MEMORY_SEGMENT_GROUP_LOCAL)` returns the size of the shared memory available for all D3D12 resources.
  912. All memory is considered "local".
  913. - `GetMemoryCapacity(DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)` is not applicable and returns 0.
  914. */
  915. UINT64 GetMemoryCapacity(UINT memorySegmentGroup) const;
  916. /** \brief Allocates memory and creates a D3D12 resource (buffer or texture). This is the main allocation function.
  917. The function is similar to `ID3D12Device::CreateCommittedResource`, but it may
  918. really call `ID3D12Device::CreatePlacedResource` to assign part of a larger,
  919. existing memory heap to the new resource, which is the main purpose of this
  920. whole library.
  921. If `ppvResource` is null, you receive only `ppAllocation` object from this function.
  922. It holds pointer to `ID3D12Resource` that can be queried using function D3D12MA::Allocation::GetResource().
  923. Reference count of the resource object is 1.
  924. It is automatically destroyed when you destroy the allocation object.
  925. If `ppvResource` is not null, you receive pointer to the resource next to allocation object.
  926. Reference count of the resource object is then increased by calling `QueryInterface`, so you need to manually `Release` it
  927. along with the allocation.
  928. \param pAllocDesc Parameters of the allocation.
  929. \param pResourceDesc Description of created resource.
  930. \param InitialResourceState Initial resource state.
  931. \param pOptimizedClearValue Optional. Either null or optimized clear value.
  932. \param[out] ppAllocation Filled with pointer to new allocation object created.
  933. \param riidResource IID of a resource to be returned via `ppvResource`.
  934. \param[out] ppvResource Optional. If not null, filled with pointer to new resouce created.
  935. \note This function creates a new resource. Sub-allocation of parts of one large buffer,
  936. although recommended as a good practice, is out of scope of this library and could be implemented
  937. by the user as a higher-level logic on top of it, e.g. using the \ref virtual_allocator feature.
  938. */
  939. HRESULT CreateResource(
  940. const ALLOCATION_DESC* pAllocDesc,
  941. const D3D12_RESOURCE_DESC* pResourceDesc,
  942. D3D12_RESOURCE_STATES InitialResourceState,
  943. const D3D12_CLEAR_VALUE *pOptimizedClearValue,
  944. Allocation** ppAllocation,
  945. REFIID riidResource,
  946. void** ppvResource);
  947. #ifdef __ID3D12Device8_INTERFACE_DEFINED__
  948. /** \brief Similar to Allocator::CreateResource, but supports new structure `D3D12_RESOURCE_DESC1`.
  949. It internally uses `ID3D12Device8::CreateCommittedResource2` or `ID3D12Device8::CreatePlacedResource1`.
  950. To work correctly, `ID3D12Device8` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.
  951. */
  952. HRESULT CreateResource2(
  953. const ALLOCATION_DESC* pAllocDesc,
  954. const D3D12_RESOURCE_DESC1* pResourceDesc,
  955. D3D12_RESOURCE_STATES InitialResourceState,
  956. const D3D12_CLEAR_VALUE *pOptimizedClearValue,
  957. Allocation** ppAllocation,
  958. REFIID riidResource,
  959. void** ppvResource);
  960. #endif // #ifdef __ID3D12Device8_INTERFACE_DEFINED__
  961. #ifdef __ID3D12Device10_INTERFACE_DEFINED__
  962. /** \brief Similar to Allocator::CreateResource2, but there are initial layout instead of state and
  963. castable formats list
  964. It internally uses `ID3D12Device10::CreateCommittedResource3` or `ID3D12Device10::CreatePlacedResource2`.
  965. To work correctly, `ID3D12Device10` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.
  966. */
  967. HRESULT CreateResource3(const ALLOCATION_DESC* pAllocDesc,
  968. const D3D12_RESOURCE_DESC1* pResourceDesc,
  969. D3D12_BARRIER_LAYOUT InitialLayout,
  970. const D3D12_CLEAR_VALUE* pOptimizedClearValue,
  971. UINT32 NumCastableFormats,
  972. DXGI_FORMAT* pCastableFormats,
  973. Allocation** ppAllocation,
  974. REFIID riidResource,
  975. void** ppvResource);
  976. #endif // #ifdef __ID3D12Device10_INTERFACE_DEFINED__
  977. /** \brief Allocates memory without creating any resource placed in it.
  978. This function is similar to `ID3D12Device::CreateHeap`, but it may really assign
  979. part of a larger, existing heap to the allocation.
  980. `pAllocDesc->heapFlags` should contain one of these values, depending on type of resources you are going to create in this memory:
  981. `D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS`,
  982. `D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES`,
  983. `D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES`.
  984. Except if you validate that ResourceHeapTier = 2 - then `heapFlags`
  985. may be `D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES` = 0.
  986. Additional flags in `heapFlags` are allowed as well.
  987. `pAllocInfo->SizeInBytes` must be multiply of 64KB.
  988. `pAllocInfo->Alignment` must be one of the legal values as described in documentation of `D3D12_HEAP_DESC`.
  989. If you use D3D12MA::ALLOCATION_FLAG_COMMITTED you will get a separate memory block -
  990. a heap that always has offset 0.
  991. */
  992. HRESULT AllocateMemory(
  993. const ALLOCATION_DESC* pAllocDesc,
  994. const D3D12_RESOURCE_ALLOCATION_INFO* pAllocInfo,
  995. Allocation** ppAllocation);
  996. /** \brief Creates a new resource in place of an existing allocation. This is useful for memory aliasing.
  997. \param pAllocation Existing allocation indicating the memory where the new resource should be created.
  998. It can be created using D3D12MA::Allocator::CreateResource and already have a resource bound to it,
  999. or can be a raw memory allocated with D3D12MA::Allocator::AllocateMemory.
  1000. It must not be created as committed so that `ID3D12Heap` is available and not implicit.
  1001. \param AllocationLocalOffset Additional offset in bytes to be applied when allocating the resource.
  1002. Local from the start of `pAllocation`, not the beginning of the whole `ID3D12Heap`!
  1003. If the new resource should start from the beginning of the `pAllocation` it should be 0.
  1004. \param pResourceDesc Description of the new resource to be created.
  1005. \param InitialResourceState
  1006. \param pOptimizedClearValue
  1007. \param riidResource
  1008. \param[out] ppvResource Returns pointer to the new resource.
  1009. The resource is not bound with `pAllocation`.
  1010. This pointer must not be null - you must get the resource pointer and `Release` it when no longer needed.
  1011. Memory requirements of the new resource are checked for validation.
  1012. If its size exceeds the end of `pAllocation` or required alignment is not fulfilled
  1013. considering `pAllocation->GetOffset() + AllocationLocalOffset`, the function
  1014. returns `E_INVALIDARG`.
  1015. */
  1016. HRESULT CreateAliasingResource(
  1017. Allocation* pAllocation,
  1018. UINT64 AllocationLocalOffset,
  1019. const D3D12_RESOURCE_DESC* pResourceDesc,
  1020. D3D12_RESOURCE_STATES InitialResourceState,
  1021. const D3D12_CLEAR_VALUE *pOptimizedClearValue,
  1022. REFIID riidResource,
  1023. void** ppvResource);
  1024. #ifdef __ID3D12Device8_INTERFACE_DEFINED__
  1025. /** \brief Similar to Allocator::CreateAliasingResource, but supports new structure `D3D12_RESOURCE_DESC1`.
  1026. It internally uses `ID3D12Device8::CreatePlacedResource1`.
  1027. To work correctly, `ID3D12Device8` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.
  1028. */
  1029. HRESULT CreateAliasingResource1(Allocation* pAllocation,
  1030. UINT64 AllocationLocalOffset,
  1031. const D3D12_RESOURCE_DESC1* pResourceDesc,
  1032. D3D12_RESOURCE_STATES InitialResourceState,
  1033. const D3D12_CLEAR_VALUE* pOptimizedClearValue,
  1034. REFIID riidResource,
  1035. void** ppvResource);
  1036. #endif // #ifdef __ID3D12Device8_INTERFACE_DEFINED__
  1037. #ifdef __ID3D12Device10_INTERFACE_DEFINED__
  1038. /** \brief Similar to Allocator::CreateAliasingResource1, but there are initial layout instead of state and
  1039. castable formats list
  1040. It internally uses `ID3D12Device10::CreatePlacedResource2`.
  1041. To work correctly, `ID3D12Device10` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.
  1042. */
  1043. HRESULT CreateAliasingResource2(Allocation* pAllocation,
  1044. UINT64 AllocationLocalOffset,
  1045. const D3D12_RESOURCE_DESC1* pResourceDesc,
  1046. D3D12_BARRIER_LAYOUT InitialLayout,
  1047. const D3D12_CLEAR_VALUE* pOptimizedClearValue,
  1048. UINT32 NumCastableFormats,
  1049. DXGI_FORMAT* pCastableFormats,
  1050. REFIID riidResource,
  1051. void** ppvResource);
  1052. #endif // #ifdef __ID3D12Device10_INTERFACE_DEFINED__
  1053. /** \brief Creates custom pool.
  1054. */
  1055. HRESULT CreatePool(
  1056. const POOL_DESC* pPoolDesc,
  1057. Pool** ppPool);
  1058. /** \brief Sets the index of the current frame.
  1059. This function is used to set the frame index in the allocator when a new game frame begins.
  1060. */
  1061. void SetCurrentFrameIndex(UINT frameIndex);
  1062. /** \brief Retrieves information about current memory usage and budget.
  1063. \param[out] pLocalBudget Optional, can be null.
  1064. \param[out] pNonLocalBudget Optional, can be null.
  1065. - When IsUMA() `== FALSE` (discrete graphics card):
  1066. - `pLocalBudget` returns the budget of the video memory.
  1067. - `pNonLocalBudget` returns the budget of the system memory available for D3D12 resources.
  1068. - When IsUMA() `== TRUE` (integrated graphics chip):
  1069. - `pLocalBudget` returns the budget of the shared memory available for all D3D12 resources.
  1070. All memory is considered "local".
  1071. - `pNonLocalBudget` is not applicable and returns zeros.
  1072. This function is called "get" not "calculate" because it is very fast, suitable to be called
  1073. every frame or every allocation. For more detailed statistics use CalculateStatistics().
  1074. Note that when using allocator from multiple threads, returned information may immediately
  1075. become outdated.
  1076. */
  1077. void GetBudget(Budget* pLocalBudget, Budget* pNonLocalBudget);
  1078. /** \brief Retrieves statistics from current state of the allocator.
  1079. This function is called "calculate" not "get" because it has to traverse all
  1080. internal data structures, so it may be quite slow. Use it for debugging purposes.
  1081. For faster but more brief statistics suitable to be called every frame or every allocation,
  1082. use GetBudget().
  1083. Note that when using allocator from multiple threads, returned information may immediately
  1084. become outdated.
  1085. */
  1086. void CalculateStatistics(TotalStatistics* pStats);
  1087. /** \brief Builds and returns statistics as a string in JSON format.
  1088. *
  1089. @param[out] ppStatsString Must be freed using Allocator::FreeStatsString.
  1090. @param DetailedMap `TRUE` to include full list of allocations (can make the string quite long), `FALSE` to only return statistics.
  1091. */
  1092. void BuildStatsString(WCHAR** ppStatsString, BOOL DetailedMap) const;
  1093. /// Frees memory of a string returned from Allocator::BuildStatsString.
  1094. void FreeStatsString(WCHAR* pStatsString) const;
  1095. /** \brief Begins defragmentation process of the default pools.
  1096. \param pDesc Structure filled with parameters of defragmentation.
  1097. \param[out] ppContext Context object that will manage defragmentation.
  1098. For more information about defragmentation, see documentation chapter:
  1099. [Defragmentation](@ref defragmentation).
  1100. */
  1101. void BeginDefragmentation(const DEFRAGMENTATION_DESC* pDesc, DefragmentationContext** ppContext);
  1102. protected:
  1103. void ReleaseThis() override;
  1104. private:
  1105. friend D3D12MA_API HRESULT CreateAllocator(const ALLOCATOR_DESC*, Allocator**);
  1106. template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);
  1107. friend class DefragmentationContext;
  1108. friend class Pool;
  1109. Allocator(const ALLOCATION_CALLBACKS& allocationCallbacks, const ALLOCATOR_DESC& desc);
  1110. ~Allocator();
  1111. AllocatorPimpl* m_Pimpl;
  1112. D3D12MA_CLASS_NO_COPY(Allocator)
  1113. };
  1114. /// \brief Bit flags to be used with VIRTUAL_BLOCK_DESC::Flags.
  1115. enum VIRTUAL_BLOCK_FLAGS
  1116. {
  1117. /// Zero
  1118. VIRTUAL_BLOCK_FLAG_NONE = 0,
  1119. /** \brief Enables alternative, linear allocation algorithm in this virtual block.
  1120. Specify this flag to enable linear allocation algorithm, which always creates
  1121. new allocations after last one and doesn't reuse space from allocations freed in
  1122. between. It trades memory consumption for simplified algorithm and data
  1123. structure, which has better performance and uses less memory for metadata.
  1124. By using this flag, you can achieve behavior of free-at-once, stack,
  1125. ring buffer, and double stack.
  1126. For details, see documentation chapter \ref linear_algorithm.
  1127. */
  1128. VIRTUAL_BLOCK_FLAG_ALGORITHM_LINEAR = POOL_FLAG_ALGORITHM_LINEAR,
  1129. // Bit mask to extract only `ALGORITHM` bits from entire set of flags.
  1130. VIRTUAL_BLOCK_FLAG_ALGORITHM_MASK = POOL_FLAG_ALGORITHM_MASK
  1131. };
  1132. /// Parameters of created D3D12MA::VirtualBlock object to be passed to CreateVirtualBlock().
  1133. struct VIRTUAL_BLOCK_DESC
  1134. {
  1135. /// Flags.
  1136. VIRTUAL_BLOCK_FLAGS Flags;
  1137. /** \brief Total size of the block.
  1138. Sizes can be expressed in bytes or any units you want as long as you are consistent in using them.
  1139. For example, if you allocate from some array of structures, 1 can mean single instance of entire structure.
  1140. */
  1141. UINT64 Size;
  1142. /** \brief Custom CPU memory allocation callbacks. Optional.
  1143. Optional, can be null. When specified, will be used for all CPU-side memory allocations.
  1144. */
  1145. const ALLOCATION_CALLBACKS* pAllocationCallbacks;
  1146. };
  1147. /// \brief Bit flags to be used with VIRTUAL_ALLOCATION_DESC::Flags.
  1148. enum VIRTUAL_ALLOCATION_FLAGS
  1149. {
  1150. /// Zero
  1151. VIRTUAL_ALLOCATION_FLAG_NONE = 0,
  1152. /** \brief Allocation will be created from upper stack in a double stack pool.
  1153. This flag is only allowed for virtual blocks created with #VIRTUAL_BLOCK_FLAG_ALGORITHM_LINEAR flag.
  1154. */
  1155. VIRTUAL_ALLOCATION_FLAG_UPPER_ADDRESS = ALLOCATION_FLAG_UPPER_ADDRESS,
  1156. /// Allocation strategy that tries to minimize memory usage.
  1157. VIRTUAL_ALLOCATION_FLAG_STRATEGY_MIN_MEMORY = ALLOCATION_FLAG_STRATEGY_MIN_MEMORY,
  1158. /// Allocation strategy that tries to minimize allocation time.
  1159. VIRTUAL_ALLOCATION_FLAG_STRATEGY_MIN_TIME = ALLOCATION_FLAG_STRATEGY_MIN_TIME,
  1160. /** \brief Allocation strategy that chooses always the lowest offset in available space.
  1161. This is not the most efficient strategy but achieves highly packed data.
  1162. */
  1163. VIRTUAL_ALLOCATION_FLAG_STRATEGY_MIN_OFFSET = ALLOCATION_FLAG_STRATEGY_MIN_OFFSET,
  1164. /** \brief A bit mask to extract only `STRATEGY` bits from entire set of flags.
  1165. These strategy flags are binary compatible with equivalent flags in #ALLOCATION_FLAGS.
  1166. */
  1167. VIRTUAL_ALLOCATION_FLAG_STRATEGY_MASK = ALLOCATION_FLAG_STRATEGY_MASK,
  1168. };
  1169. /// Parameters of created virtual allocation to be passed to VirtualBlock::Allocate().
  1170. struct VIRTUAL_ALLOCATION_DESC
  1171. {
  1172. /// Flags.
  1173. VIRTUAL_ALLOCATION_FLAGS Flags;
  1174. /** \brief Size of the allocation.
  1175. Cannot be zero.
  1176. */
  1177. UINT64 Size;
  1178. /** \brief Required alignment of the allocation.
  1179. 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.
  1180. */
  1181. UINT64 Alignment;
  1182. /** \brief Custom pointer to be associated with the allocation.
  1183. It can be fetched or changed later.
  1184. */
  1185. void* pPrivateData;
  1186. };
  1187. /// Parameters of an existing virtual allocation, returned by VirtualBlock::GetAllocationInfo().
  1188. struct VIRTUAL_ALLOCATION_INFO
  1189. {
  1190. /// \brief Offset of the allocation.
  1191. UINT64 Offset;
  1192. /** \brief Size of the allocation.
  1193. Same value as passed in VIRTUAL_ALLOCATION_DESC::Size.
  1194. */
  1195. UINT64 Size;
  1196. /** \brief Custom pointer associated with the allocation.
  1197. Same value as passed in VIRTUAL_ALLOCATION_DESC::pPrivateData or VirtualBlock::SetAllocationPrivateData().
  1198. */
  1199. void* pPrivateData;
  1200. };
  1201. /** \brief Represents pure allocation algorithm and a data structure with allocations in some memory block, without actually allocating any GPU memory.
  1202. This class allows to use the core algorithm of the library custom allocations e.g. CPU memory or
  1203. sub-allocation regions inside a single GPU buffer.
  1204. To create this object, fill in D3D12MA::VIRTUAL_BLOCK_DESC and call CreateVirtualBlock().
  1205. To destroy it, call its method `VirtualBlock::Release()`.
  1206. You need to free all the allocations within this block or call Clear() before destroying it.
  1207. This object is not thread-safe - should not be used from multiple threads simultaneously, must be synchronized externally.
  1208. */
  1209. class D3D12MA_API VirtualBlock : public IUnknownImpl
  1210. {
  1211. public:
  1212. /** \brief Returns true if the block is empty - contains 0 allocations.
  1213. */
  1214. BOOL IsEmpty() const;
  1215. /** \brief Returns information about an allocation - its offset, size and custom pointer.
  1216. */
  1217. void GetAllocationInfo(VirtualAllocation allocation, VIRTUAL_ALLOCATION_INFO* pInfo) const;
  1218. /** \brief Creates new allocation.
  1219. \param pDesc
  1220. \param[out] pAllocation Unique indentifier of the new allocation within single block.
  1221. \param[out] pOffset Returned offset of the new allocation. Optional, can be null.
  1222. \return `S_OK` if allocation succeeded, `E_OUTOFMEMORY` if it failed.
  1223. If the allocation failed, `pAllocation->AllocHandle` is set to 0 and `pOffset`, if not null, is set to `UINT64_MAX`.
  1224. */
  1225. HRESULT Allocate(const VIRTUAL_ALLOCATION_DESC* pDesc, VirtualAllocation* pAllocation, UINT64* pOffset);
  1226. /** \brief Frees the allocation.
  1227. Calling this function with `allocation.AllocHandle == 0` is correct and does nothing.
  1228. */
  1229. void FreeAllocation(VirtualAllocation allocation);
  1230. /** \brief Frees all the allocations.
  1231. */
  1232. void Clear();
  1233. /** \brief Changes custom pointer for an allocation to a new value.
  1234. */
  1235. void SetAllocationPrivateData(VirtualAllocation allocation, void* pPrivateData);
  1236. /** \brief Retrieves basic statistics of the virtual block that are fast to calculate.
  1237. \param[out] pStats %Statistics of the virtual block.
  1238. */
  1239. void GetStatistics(Statistics* pStats) const;
  1240. /** \brief Retrieves detailed statistics of the virtual block that are slower to calculate.
  1241. \param[out] pStats %Statistics of the virtual block.
  1242. */
  1243. void CalculateStatistics(DetailedStatistics* pStats) const;
  1244. /** \brief Builds and returns statistics as a string in JSON format, including the list of allocations with their parameters.
  1245. @param[out] ppStatsString Must be freed using VirtualBlock::FreeStatsString.
  1246. */
  1247. void BuildStatsString(WCHAR** ppStatsString) const;
  1248. /** \brief Frees memory of a string returned from VirtualBlock::BuildStatsString.
  1249. */
  1250. void FreeStatsString(WCHAR* pStatsString) const;
  1251. protected:
  1252. void ReleaseThis() override;
  1253. private:
  1254. friend D3D12MA_API HRESULT CreateVirtualBlock(const VIRTUAL_BLOCK_DESC*, VirtualBlock**);
  1255. template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);
  1256. VirtualBlockPimpl* m_Pimpl;
  1257. VirtualBlock(const ALLOCATION_CALLBACKS& allocationCallbacks, const VIRTUAL_BLOCK_DESC& desc);
  1258. ~VirtualBlock();
  1259. D3D12MA_CLASS_NO_COPY(VirtualBlock)
  1260. };
  1261. /** \brief Creates new main D3D12MA::Allocator object and returns it through `ppAllocator`.
  1262. You normally only need to call it once and keep a single Allocator object for your `ID3D12Device`.
  1263. */
  1264. D3D12MA_API HRESULT CreateAllocator(const ALLOCATOR_DESC* pDesc, Allocator** ppAllocator);
  1265. /** \brief Creates new D3D12MA::VirtualBlock object and returns it through `ppVirtualBlock`.
  1266. Note you don't need to create D3D12MA::Allocator to use virtual blocks.
  1267. */
  1268. D3D12MA_API HRESULT CreateVirtualBlock(const VIRTUAL_BLOCK_DESC* pDesc, VirtualBlock** ppVirtualBlock);
  1269. } // namespace D3D12MA
  1270. /// \cond INTERNAL
  1271. DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::ALLOCATION_FLAGS);
  1272. DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::DEFRAGMENTATION_FLAGS);
  1273. DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::ALLOCATOR_FLAGS);
  1274. DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::POOL_FLAGS);
  1275. DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::VIRTUAL_BLOCK_FLAGS);
  1276. DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::VIRTUAL_ALLOCATION_FLAGS);
  1277. /// \endcond
  1278. /**
  1279. \page quick_start Quick start
  1280. \section quick_start_project_setup Project setup and initialization
  1281. This is a small, standalone C++ library. It consists of a pair of 2 files:
  1282. "D3D12MemAlloc.h" header file with public interface and "D3D12MemAlloc.cpp" with
  1283. internal implementation. The only external dependencies are WinAPI, Direct3D 12,
  1284. and parts of C/C++ standard library (but STL containers, exceptions, or RTTI are
  1285. not used).
  1286. The library is developed and tested using Microsoft Visual Studio 2019, but it
  1287. should work with other compilers as well. It is designed for 64-bit code.
  1288. To use the library in your project:
  1289. (1.) Copy files `D3D12MemAlloc.cpp`, `%D3D12MemAlloc.h` to your project.
  1290. (2.) Make `D3D12MemAlloc.cpp` compiling as part of the project, as C++ code.
  1291. (3.) Include library header in each CPP file that needs to use the library.
  1292. \code
  1293. #include "D3D12MemAlloc.h"
  1294. \endcode
  1295. (4.) Right after you created `ID3D12Device`, fill D3D12MA::ALLOCATOR_DESC
  1296. structure and call function D3D12MA::CreateAllocator to create the main
  1297. D3D12MA::Allocator object.
  1298. Please note that all symbols of the library are declared inside #D3D12MA namespace.
  1299. \code
  1300. IDXGIAdapter* adapter = (...)
  1301. ID3D12Device* device = (...)
  1302. D3D12MA::ALLOCATOR_DESC allocatorDesc = {};
  1303. allocatorDesc.pDevice = device;
  1304. allocatorDesc.pAdapter = adapter;
  1305. D3D12MA::Allocator* allocator;
  1306. HRESULT hr = D3D12MA::CreateAllocator(&allocatorDesc, &allocator);
  1307. \endcode
  1308. (5.) Right before destroying the D3D12 device, destroy the allocator object.
  1309. Objects of this library must be destroyed by calling `Release` method.
  1310. They are somewhat compatible with COM: they implement `IUnknown` interface with its virtual methods: `AddRef`, `Release`, `QueryInterface`,
  1311. and they are reference-counted internally.
  1312. You can use smart pointers designed for COM with objects of this library - e.g. `CComPtr` or `Microsoft::WRL::ComPtr`.
  1313. The reference counter is thread-safe.
  1314. `QueryInterface` method supports only `IUnknown`, as classes of this library don't define their own GUIDs.
  1315. \code
  1316. allocator->Release();
  1317. \endcode
  1318. \section quick_start_creating_resources Creating resources
  1319. To use the library for creating resources (textures and buffers), call method
  1320. D3D12MA::Allocator::CreateResource in the place where you would previously call
  1321. `ID3D12Device::CreateCommittedResource`.
  1322. The function has similar syntax, but it expects structure D3D12MA::ALLOCATION_DESC
  1323. to be passed along with `D3D12_RESOURCE_DESC` and other parameters for created
  1324. resource. This structure describes parameters of the desired memory allocation,
  1325. including choice of `D3D12_HEAP_TYPE`.
  1326. The function returns a new object of type D3D12MA::Allocation.
  1327. It represents allocated memory and can be queried for size, offset, `ID3D12Heap`.
  1328. It also holds a reference to the `ID3D12Resource`, which can be accessed by calling D3D12MA::Allocation::GetResource().
  1329. \code
  1330. D3D12_RESOURCE_DESC resourceDesc = {};
  1331. resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  1332. resourceDesc.Alignment = 0;
  1333. resourceDesc.Width = 1024;
  1334. resourceDesc.Height = 1024;
  1335. resourceDesc.DepthOrArraySize = 1;
  1336. resourceDesc.MipLevels = 1;
  1337. resourceDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  1338. resourceDesc.SampleDesc.Count = 1;
  1339. resourceDesc.SampleDesc.Quality = 0;
  1340. resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  1341. resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
  1342. D3D12MA::ALLOCATION_DESC allocationDesc = {};
  1343. allocationDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;
  1344. D3D12MA::Allocation* allocation;
  1345. HRESULT hr = allocator->CreateResource(
  1346. &allocationDesc,
  1347. &resourceDesc,
  1348. D3D12_RESOURCE_STATE_COPY_DEST,
  1349. NULL,
  1350. &allocation,
  1351. IID_NULL, NULL);
  1352. // Use allocation->GetResource()...
  1353. \endcode
  1354. You need to release the allocation object when no longer needed.
  1355. This will also release the D3D12 resource.
  1356. \code
  1357. allocation->Release();
  1358. \endcode
  1359. The advantage of using the allocator instead of creating committed resource, and
  1360. the main purpose of this library, is that it can decide to allocate bigger memory
  1361. heap internally using `ID3D12Device::CreateHeap` and place multiple resources in
  1362. it, at different offsets, using `ID3D12Device::CreatePlacedResource`. The library
  1363. manages its own collection of allocated memory blocks (heaps) and remembers which
  1364. parts of them are occupied and which parts are free to be used for new resources.
  1365. It is important to remember that resources created as placed don't have their memory
  1366. initialized to zeros, but may contain garbage data, so they need to be fully initialized
  1367. before usage, e.g. using Clear (`ClearRenderTargetView`), Discard (`DiscardResource`),
  1368. or copy (`CopyResource`).
  1369. The library also automatically handles resource heap tier.
  1370. When `D3D12_FEATURE_DATA_D3D12_OPTIONS::ResourceHeapTier` equals `D3D12_RESOURCE_HEAP_TIER_1`,
  1371. resources of 3 types: buffers, textures that are render targets or depth-stencil,
  1372. and other textures must be kept in separate heaps. When `D3D12_RESOURCE_HEAP_TIER_2`,
  1373. they can be kept together. By using this library, you don't need to handle this
  1374. manually.
  1375. \section quick_start_resource_reference_counting Resource reference counting
  1376. `ID3D12Resource` and other interfaces of Direct3D 12 use COM, so they are reference-counted.
  1377. Objects of this library are reference-counted as well.
  1378. An object of type D3D12MA::Allocation remembers the resource (buffer or texture)
  1379. that was created together with this memory allocation
  1380. and holds a reference to the `ID3D12Resource` object.
  1381. (Note this is a difference to Vulkan Memory Allocator, where a `VmaAllocation` object has no connection
  1382. with the buffer or image that was created with it.)
  1383. Thus, it is important to manage the resource reference counter properly.
  1384. <b>The simplest use case</b> is shown in the code snippet above.
  1385. When only D3D12MA::Allocation object is obtained from a function call like D3D12MA::Allocator::CreateResource,
  1386. it remembers the `ID3D12Resource` that was created with it and holds a reference to it.
  1387. The resource can be obtained by calling `allocation->GetResource()`, which doesn't increment the resource
  1388. reference counter.
  1389. Calling `allocation->Release()` will decrease the resource reference counter, which is = 1 in this case,
  1390. so the resource will be released.
  1391. <b>Second option</b> is to retrieve a pointer to the resource along with D3D12MA::Allocation.
  1392. Last parameters of the resource creation function can be used for this purpose.
  1393. \code
  1394. D3D12MA::Allocation* allocation;
  1395. ID3D12Resource* resource;
  1396. HRESULT hr = allocator->CreateResource(
  1397. &allocationDesc,
  1398. &resourceDesc,
  1399. D3D12_RESOURCE_STATE_COPY_DEST,
  1400. NULL,
  1401. &allocation,
  1402. IID_PPV_ARGS(&resource));
  1403. // Use resource...
  1404. \endcode
  1405. In this case, returned pointer `resource` is equal to `allocation->GetResource()`,
  1406. but the creation function additionally increases resource reference counter for the purpose of returning it from this call
  1407. (it actually calls `QueryInterface` internally), so the resource will have the counter = 2.
  1408. The resource then need to be released along with the allocation, in this particular order,
  1409. to make sure the resource is destroyed before its memory heap can potentially be freed.
  1410. \code
  1411. resource->Release();
  1412. allocation->Release();
  1413. \endcode
  1414. <b>More advanced use cases</b> are possible when we consider that an D3D12MA::Allocation object can just hold
  1415. a reference to any resource.
  1416. It can be changed by calling D3D12MA::Allocation::SetResource. This function
  1417. releases the old resource and calls `AddRef` on the new one.
  1418. Special care must be taken when performing <b>defragmentation</b>.
  1419. The new resource created at the destination place should be set as `pass.pMoves[i].pDstTmpAllocation->SetResource(newRes)`,
  1420. but it is moved to the source allocation at end of the defragmentation pass,
  1421. while the old resource accessible through `pass.pMoves[i].pSrcAllocation->GetResource()` is then released.
  1422. For more information, see documentation chapter \ref defragmentation.
  1423. \section quick_start_mapping_memory Mapping memory
  1424. The process of getting regular CPU-side pointer to the memory of a resource in
  1425. Direct3D is called "mapping". There are rules and restrictions to this process,
  1426. as described in D3D12 documentation of `ID3D12Resource::Map` method.
  1427. Mapping happens on the level of particular resources, not entire memory heaps,
  1428. and so it is out of scope of this library. Just as the documentation of the `Map` function says:
  1429. - Returned pointer refers to data of particular subresource, not entire memory heap.
  1430. - You can map same resource multiple times. It is ref-counted internally.
  1431. - Mapping is thread-safe.
  1432. - Unmapping is not required before resource destruction.
  1433. - Unmapping may not be required before using written data - some heap types on
  1434. some platforms support resources persistently mapped.
  1435. When using this library, you can map and use your resources normally without
  1436. considering whether they are created as committed resources or placed resources in one large heap.
  1437. Example for buffer created and filled in `UPLOAD` heap type:
  1438. \code
  1439. const UINT64 bufSize = 65536;
  1440. const float* bufData = (...);
  1441. D3D12_RESOURCE_DESC resourceDesc = {};
  1442. resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
  1443. resourceDesc.Alignment = 0;
  1444. resourceDesc.Width = bufSize;
  1445. resourceDesc.Height = 1;
  1446. resourceDesc.DepthOrArraySize = 1;
  1447. resourceDesc.MipLevels = 1;
  1448. resourceDesc.Format = DXGI_FORMAT_UNKNOWN;
  1449. resourceDesc.SampleDesc.Count = 1;
  1450. resourceDesc.SampleDesc.Quality = 0;
  1451. resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
  1452. resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
  1453. D3D12MA::ALLOCATION_DESC allocationDesc = {};
  1454. allocationDesc.HeapType = D3D12_HEAP_TYPE_UPLOAD;
  1455. D3D12Resource* resource;
  1456. D3D12MA::Allocation* allocation;
  1457. HRESULT hr = allocator->CreateResource(
  1458. &allocationDesc,
  1459. &resourceDesc,
  1460. D3D12_RESOURCE_STATE_GENERIC_READ,
  1461. NULL,
  1462. &allocation,
  1463. IID_PPV_ARGS(&resource));
  1464. void* mappedPtr;
  1465. hr = resource->Map(0, NULL, &mappedPtr);
  1466. memcpy(mappedPtr, bufData, bufSize);
  1467. resource->Unmap(0, NULL);
  1468. \endcode
  1469. \page custom_pools Custom memory pools
  1470. A "pool" is a collection of memory blocks that share certain properties.
  1471. Allocator creates 3 default pools: for `D3D12_HEAP_TYPE_DEFAULT`, `UPLOAD`, `READBACK`.
  1472. A default pool automatically grows in size. Size of allocated blocks is also variable and managed automatically.
  1473. Typical allocations are created in these pools. You can also create custom pools.
  1474. \section custom_pools_usage Usage
  1475. To create a custom pool, fill in structure D3D12MA::POOL_DESC and call function D3D12MA::Allocator::CreatePool
  1476. to obtain object D3D12MA::Pool. Example:
  1477. \code
  1478. POOL_DESC poolDesc = {};
  1479. poolDesc.HeapProperties.Type = D3D12_HEAP_TYPE_DEFAULT;
  1480. Pool* pool;
  1481. HRESULT hr = allocator->CreatePool(&poolDesc, &pool);
  1482. \endcode
  1483. To allocate resources out of a custom pool, only set member D3D12MA::ALLOCATION_DESC::CustomPool.
  1484. Example:
  1485. \code
  1486. ALLOCATION_DESC allocDesc = {};
  1487. allocDesc.CustomPool = pool;
  1488. D3D12_RESOURCE_DESC resDesc = ...
  1489. Allocation* alloc;
  1490. hr = allocator->CreateResource(&allocDesc, &resDesc,
  1491. D3D12_RESOURCE_STATE_GENERIC_READ, NULL, &alloc, IID_NULL, NULL);
  1492. \endcode
  1493. All allocations must be released before releasing the pool.
  1494. The pool must be released before relasing the allocator.
  1495. \code
  1496. alloc->Release();
  1497. pool->Release();
  1498. \endcode
  1499. \section custom_pools_features_and_benefits Features and benefits
  1500. While it is recommended to use default pools whenever possible for simplicity and to give the allocator
  1501. more opportunities for internal optimizations, custom pools may be useful in following cases:
  1502. - To keep some resources separate from others in memory.
  1503. - To keep track of memory usage of just a specific group of resources. %Statistics can be queried using
  1504. D3D12MA::Pool::CalculateStatistics.
  1505. - To use specific size of a memory block (`ID3D12Heap`). To set it, use member D3D12MA::POOL_DESC::BlockSize.
  1506. When set to 0, the library uses automatically determined, variable block sizes.
  1507. - To reserve some minimum amount of memory allocated. To use it, set member D3D12MA::POOL_DESC::MinBlockCount.
  1508. - To limit maximum amount of memory allocated. To use it, set member D3D12MA::POOL_DESC::MaxBlockCount.
  1509. - To use extended parameters of the D3D12 memory allocation. While resources created from default pools
  1510. can only specify `D3D12_HEAP_TYPE_DEFAULT`, `UPLOAD`, `READBACK`, a custom pool may use non-standard
  1511. `D3D12_HEAP_PROPERTIES` (member D3D12MA::POOL_DESC::HeapProperties) and `D3D12_HEAP_FLAGS`
  1512. (D3D12MA::POOL_DESC::HeapFlags), which is useful e.g. for cross-adapter sharing or UMA
  1513. (see also D3D12MA::Allocator::IsUMA).
  1514. New versions of this library support creating **committed allocations in custom pools**.
  1515. It is supported only when D3D12MA::POOL_DESC::BlockSize = 0.
  1516. To use this feature, set D3D12MA::ALLOCATION_DESC::CustomPool to the pointer to your custom pool and
  1517. D3D12MA::ALLOCATION_DESC::Flags to D3D12MA::ALLOCATION_FLAG_COMMITTED. Example:
  1518. \code
  1519. ALLOCATION_DESC allocDesc = {};
  1520. allocDesc.CustomPool = pool;
  1521. allocDesc.Flags = ALLOCATION_FLAG_COMMITTED;
  1522. D3D12_RESOURCE_DESC resDesc = ...
  1523. Allocation* alloc;
  1524. ID3D12Resource* res;
  1525. hr = allocator->CreateResource(&allocDesc, &resDesc,
  1526. D3D12_RESOURCE_STATE_GENERIC_READ, NULL, &alloc, IID_PPV_ARGS(&res));
  1527. \endcode
  1528. This feature may seem unnecessary, but creating committed allocations from custom pools may be useful
  1529. in some cases, e.g. to have separate memory usage statistics for some group of resources or to use
  1530. extended allocation parameters, like custom `D3D12_HEAP_PROPERTIES`, which are available only in custom pools.
  1531. \page defragmentation Defragmentation
  1532. Interleaved allocations and deallocations of many objects of varying size can
  1533. cause fragmentation over time, which can lead to a situation where the library is unable
  1534. to find a continuous range of free memory for a new allocation despite there is
  1535. enough free space, just scattered across many small free ranges between existing
  1536. allocations.
  1537. To mitigate this problem, you can use defragmentation feature.
  1538. It doesn't happen automatically though and needs your cooperation,
  1539. because %D3D12MA is a low level library that only allocates memory.
  1540. It cannot recreate buffers and textures in a new place as it doesn't remember the contents of `D3D12_RESOURCE_DESC` structure.
  1541. It cannot copy their contents as it doesn't record any commands to a command list.
  1542. Example:
  1543. \code
  1544. D3D12MA::DEFRAGMENTATION_DESC defragDesc = {};
  1545. defragDesc.Flags = D3D12MA::DEFRAGMENTATION_FLAG_ALGORITHM_FAST;
  1546. D3D12MA::DefragmentationContext* defragCtx;
  1547. allocator->BeginDefragmentation(&defragDesc, &defragCtx);
  1548. for(;;)
  1549. {
  1550. D3D12MA::DEFRAGMENTATION_PASS_MOVE_INFO pass;
  1551. HRESULT hr = defragCtx->BeginPass(&pass);
  1552. if(hr == S_OK)
  1553. break;
  1554. else if(hr != S_FALSE)
  1555. // Handle error...
  1556. for(UINT i = 0; i < pass.MoveCount; ++i)
  1557. {
  1558. // Inspect pass.pMoves[i].pSrcAllocation, identify what buffer/texture it represents.
  1559. MyEngineResourceData* resData = (MyEngineResourceData*)pMoves[i].pSrcAllocation->GetPrivateData();
  1560. // Recreate this buffer/texture as placed at pass.pMoves[i].pDstTmpAllocation.
  1561. D3D12_RESOURCE_DESC resDesc = ...
  1562. ID3D12Resource* newRes;
  1563. hr = device->CreatePlacedResource(
  1564. pass.pMoves[i].pDstTmpAllocation->GetHeap(),
  1565. pass.pMoves[i].pDstTmpAllocation->GetOffset(), &resDesc,
  1566. D3D12_RESOURCE_STATE_COPY_DEST, NULL, IID_PPV_ARGS(&newRes));
  1567. // Check hr...
  1568. // Store new resource in the pDstTmpAllocation.
  1569. pass.pMoves[i].pDstTmpAllocation->SetResource(newRes);
  1570. // Copy its content to the new place.
  1571. cmdList->CopyResource(
  1572. pass.pMoves[i].pDstTmpAllocation->GetResource(),
  1573. pass.pMoves[i].pSrcAllocation->GetResource());
  1574. }
  1575. // Make sure the copy commands finished executing.
  1576. cmdQueue->ExecuteCommandLists(...);
  1577. // ...
  1578. WaitForSingleObject(fenceEvent, INFINITE);
  1579. // Update appropriate descriptors to point to the new places...
  1580. hr = defragCtx->EndPass(&pass);
  1581. if(hr == S_OK)
  1582. break;
  1583. else if(hr != S_FALSE)
  1584. // Handle error...
  1585. }
  1586. defragCtx->Release();
  1587. \endcode
  1588. Although functions like D3D12MA::Allocator::CreateResource()
  1589. create an allocation and a buffer/texture at once, these are just a shortcut for
  1590. allocating memory and creating a placed resource.
  1591. Defragmentation works on memory allocations only. You must handle the rest manually.
  1592. Defragmentation is an iterative process that should repreat "passes" as long as related functions
  1593. return `S_FALSE` not `S_OK`.
  1594. In each pass:
  1595. 1. D3D12MA::DefragmentationContext::BeginPass() function call:
  1596. - Calculates and returns the list of allocations to be moved in this pass.
  1597. Note this can be a time-consuming process.
  1598. - Reserves destination memory for them by creating temporary destination allocations
  1599. that you can query for their `ID3D12Heap` + offset using methods like D3D12MA::Allocation::GetHeap().
  1600. 2. Inside the pass, **you should**:
  1601. - Inspect the returned list of allocations to be moved.
  1602. - Create new buffers/textures as placed at the returned destination temporary allocations.
  1603. - Copy data from source to destination resources if necessary.
  1604. - Store the pointer to the new resource in the temporary destination allocation.
  1605. 3. D3D12MA::DefragmentationContext::EndPass() function call:
  1606. - Frees the source memory reserved for the allocations that are moved.
  1607. - Modifies source D3D12MA::Allocation objects that are moved to point to the destination reserved memory
  1608. and destination resource, while source resource is released.
  1609. - Frees `ID3D12Heap` blocks that became empty.
  1610. Defragmentation algorithm tries to move all suitable allocations.
  1611. You can, however, refuse to move some of them inside a defragmentation pass, by setting
  1612. `pass.pMoves[i].Operation` to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_IGNORE.
  1613. This is not recommended and may result in suboptimal packing of the allocations after defragmentation.
  1614. If you cannot ensure any allocation can be moved, it is better to keep movable allocations separate in a custom pool.
  1615. Inside a pass, for each allocation that should be moved:
  1616. - You should copy its data from the source to the destination place by calling e.g. `CopyResource()`.
  1617. - You need to make sure these commands finished executing before the source buffers/textures are released by D3D12MA::DefragmentationContext::EndPass().
  1618. - If a resource doesn't contain any meaningful data, e.g. it is a transient render-target texture to be cleared,
  1619. filled, and used temporarily in each rendering frame, you can just recreate this texture
  1620. without copying its data.
  1621. - If the resource is in `D3D12_HEAP_TYPE_READBACK` memory, you can copy its data on the CPU
  1622. using `memcpy()`.
  1623. - If you cannot move the allocation, you can set `pass.pMoves[i].Operation` to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_IGNORE.
  1624. This will cancel the move.
  1625. - D3D12MA::DefragmentationContext::EndPass() will then free the destination memory
  1626. not the source memory of the allocation, leaving it unchanged.
  1627. - If you decide the allocation is unimportant and can be destroyed instead of moved (e.g. it wasn't used for long time),
  1628. you can set `pass.pMoves[i].Operation` to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_DESTROY.
  1629. - D3D12MA::DefragmentationContext::EndPass() will then free both source and destination memory, and will destroy the source D3D12MA::Allocation object.
  1630. You can defragment a specific custom pool by calling D3D12MA::Pool::BeginDefragmentation
  1631. or all the default pools by calling D3D12MA::Allocator::BeginDefragmentation (like in the example above).
  1632. Defragmentation is always performed in each pool separately.
  1633. Allocations are never moved between different heap types.
  1634. The size of the destination memory reserved for a moved allocation is the same as the original one.
  1635. Alignment of an allocation as it was determined using `GetResourceAllocationInfo()` is also respected after defragmentation.
  1636. Buffers/textures should be recreated with the same `D3D12_RESOURCE_DESC` parameters as the original ones.
  1637. You can perform the defragmentation incrementally to limit the number of allocations and bytes to be moved
  1638. in each pass, e.g. to call it in sync with render frames and not to experience too big hitches.
  1639. See members: D3D12MA::DEFRAGMENTATION_DESC::MaxBytesPerPass, D3D12MA::DEFRAGMENTATION_DESC::MaxAllocationsPerPass.
  1640. <b>Thread safety:</b>
  1641. It is safe to perform the defragmentation asynchronously to render frames and other Direct3D 12 and %D3D12MA
  1642. usage, possibly from multiple threads, with the exception that allocations
  1643. returned in D3D12MA::DEFRAGMENTATION_PASS_MOVE_INFO::pMoves shouldn't be released until the defragmentation pass is ended.
  1644. During the call to D3D12MA::DefragmentationContext::BeginPass(), any operations on the memory pool
  1645. affected by the defragmentation are blocked by a mutex.
  1646. What it means in practice is that you shouldn't free any allocations from the defragmented pool
  1647. since the moment a call to `BeginPass` begins. Otherwise, a thread performing the `allocation->Release()`
  1648. would block for the time `BeginPass` executes and then free the allocation when it finishes, while the allocation
  1649. could have ended up on the list of allocations to move.
  1650. A solution to freeing allocations during defragmentation is to find such allocation on the list
  1651. `pass.pMoves[i]` and set its operation to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_DESTROY instead of
  1652. calling `allocation->Release()`, or simply deferring the release to the time after defragmentation finished.
  1653. <b>Mapping</b> is out of scope of this library and so it is not preserved after an allocation is moved during defragmentation.
  1654. You need to map the new resource yourself if needed.
  1655. \note Defragmentation is not supported in custom pools created with D3D12MA::POOL_FLAG_ALGORITHM_LINEAR.
  1656. \page statistics Statistics
  1657. This library contains several functions that return information about its internal state,
  1658. especially the amount of memory allocated from D3D12.
  1659. \section statistics_numeric_statistics Numeric statistics
  1660. If you need to obtain basic statistics about memory usage per memory segment group, together with current budget,
  1661. you can call function D3D12MA::Allocator::GetBudget() and inspect structure D3D12MA::Budget.
  1662. This is useful to keep track of memory usage and stay withing budget.
  1663. Example:
  1664. \code
  1665. D3D12MA::Budget localBudget;
  1666. allocator->GetBudget(&localBudget, NULL);
  1667. printf("My GPU memory currently has %u allocations taking %llu B,\n",
  1668. localBudget.Statistics.AllocationCount,
  1669. localBudget.Statistics.AllocationBytes);
  1670. printf("allocated out of %u D3D12 memory heaps taking %llu B,\n",
  1671. localBudget.Statistics.BlockCount,
  1672. localBudget.Statistics.BlockBytes);
  1673. printf("D3D12 reports total usage %llu B with budget %llu B.\n",
  1674. localBudget.UsageBytes,
  1675. localBudget.BudgetBytes);
  1676. \endcode
  1677. You can query for more detailed statistics per heap type, memory segment group, and totals,
  1678. including minimum and maximum allocation size and unused range size,
  1679. by calling function D3D12MA::Allocator::CalculateStatistics() and inspecting structure D3D12MA::TotalStatistics.
  1680. This function is slower though, as it has to traverse all the internal data structures,
  1681. so it should be used only for debugging purposes.
  1682. You can query for statistics of a custom pool using function D3D12MA::Pool::GetStatistics()
  1683. or D3D12MA::Pool::CalculateStatistics().
  1684. You can query for information about a specific allocation using functions of the D3D12MA::Allocation class,
  1685. e.g. `GetSize()`, `GetOffset()`, `GetHeap()`.
  1686. \section statistics_json_dump JSON dump
  1687. You can dump internal state of the allocator to a string in JSON format using function D3D12MA::Allocator::BuildStatsString().
  1688. The result is guaranteed to be correct JSON.
  1689. It uses Windows Unicode (UTF-16) encoding.
  1690. Any strings provided by user (see D3D12MA::Allocation::SetName())
  1691. are copied as-is and properly escaped for JSON.
  1692. It must be freed using function D3D12MA::Allocator::FreeStatsString().
  1693. The format of this JSON string is not part of official documentation of the library,
  1694. but it will not change in backward-incompatible way without increasing library major version number
  1695. and appropriate mention in changelog.
  1696. The JSON string contains all the data that can be obtained using D3D12MA::Allocator::CalculateStatistics().
  1697. It can also contain detailed map of allocated memory blocks and their regions -
  1698. free and occupied by allocations.
  1699. This allows e.g. to visualize the memory or assess fragmentation.
  1700. \page resource_aliasing Resource aliasing (overlap)
  1701. New explicit graphics APIs (Vulkan and Direct3D 12), thanks to manual memory
  1702. management, give an opportunity to alias (overlap) multiple resources in the
  1703. same region of memory - a feature not available in the old APIs (Direct3D 11, OpenGL).
  1704. It can be useful to save video memory, but it must be used with caution.
  1705. For example, if you know the flow of your whole render frame in advance, you
  1706. are going to use some intermediate textures or buffers only during a small range of render passes,
  1707. and you know these ranges don't overlap in time, you can create these resources in
  1708. the same place in memory, even if they have completely different parameters (width, height, format etc.).
  1709. ![Resource aliasing (overlap)](../gfx/Aliasing.png)
  1710. Such scenario is possible using D3D12MA, but you need to create your resources
  1711. using special function D3D12MA::Allocator::CreateAliasingResource.
  1712. Before that, you need to allocate memory with parameters calculated using formula:
  1713. - allocation size = max(size of each resource)
  1714. - allocation alignment = max(alignment of each resource)
  1715. Following example shows two different textures created in the same place in memory,
  1716. allocated to fit largest of them.
  1717. \code
  1718. D3D12_RESOURCE_DESC resDesc1 = {};
  1719. resDesc1.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  1720. resDesc1.Alignment = 0;
  1721. resDesc1.Width = 1920;
  1722. resDesc1.Height = 1080;
  1723. resDesc1.DepthOrArraySize = 1;
  1724. resDesc1.MipLevels = 1;
  1725. resDesc1.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  1726. resDesc1.SampleDesc.Count = 1;
  1727. resDesc1.SampleDesc.Quality = 0;
  1728. resDesc1.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  1729. resDesc1.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
  1730. D3D12_RESOURCE_DESC resDesc2 = {};
  1731. resDesc2.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
  1732. resDesc2.Alignment = 0;
  1733. resDesc2.Width = 1024;
  1734. resDesc2.Height = 1024;
  1735. resDesc2.DepthOrArraySize = 1;
  1736. resDesc2.MipLevels = 0;
  1737. resDesc2.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  1738. resDesc2.SampleDesc.Count = 1;
  1739. resDesc2.SampleDesc.Quality = 0;
  1740. resDesc2.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
  1741. resDesc2.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
  1742. const D3D12_RESOURCE_ALLOCATION_INFO allocInfo1 =
  1743. device->GetResourceAllocationInfo(0, 1, &resDesc1);
  1744. const D3D12_RESOURCE_ALLOCATION_INFO allocInfo2 =
  1745. device->GetResourceAllocationInfo(0, 1, &resDesc2);
  1746. D3D12_RESOURCE_ALLOCATION_INFO finalAllocInfo = {};
  1747. finalAllocInfo.Alignment = std::max(allocInfo1.Alignment, allocInfo2.Alignment);
  1748. finalAllocInfo.SizeInBytes = std::max(allocInfo1.SizeInBytes, allocInfo2.SizeInBytes);
  1749. D3D12MA::ALLOCATION_DESC allocDesc = {};
  1750. allocDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;
  1751. allocDesc.ExtraHeapFlags = D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES;
  1752. D3D12MA::Allocation* alloc;
  1753. hr = allocator->AllocateMemory(&allocDesc, &finalAllocInfo, &alloc);
  1754. assert(alloc != NULL && alloc->GetHeap() != NULL);
  1755. ID3D12Resource* res1;
  1756. hr = allocator->CreateAliasingResource(
  1757. alloc,
  1758. 0, // AllocationLocalOffset
  1759. &resDesc1,
  1760. D3D12_RESOURCE_STATE_COMMON,
  1761. NULL, // pOptimizedClearValue
  1762. IID_PPV_ARGS(&res1));
  1763. ID3D12Resource* res2;
  1764. hr = allocator->CreateAliasingResource(
  1765. alloc,
  1766. 0, // AllocationLocalOffset
  1767. &resDesc2,
  1768. D3D12_RESOURCE_STATE_COMMON,
  1769. NULL, // pOptimizedClearValue
  1770. IID_PPV_ARGS(&res2));
  1771. // You can use res1 and res2, but not at the same time!
  1772. res2->Release();
  1773. res1->Release();
  1774. alloc->Release();
  1775. \endcode
  1776. Remember that using resouces that alias in memory requires proper synchronization.
  1777. You need to issue a special barrier of type `D3D12_RESOURCE_BARRIER_TYPE_ALIASING`.
  1778. You also need to treat a resource after aliasing as uninitialized - containing garbage data.
  1779. For example, if you use `res1` and then want to use `res2`, you need to first initialize `res2`
  1780. using either Clear, Discard, or Copy to the entire resource.
  1781. Additional considerations:
  1782. - D3D12 also allows to interpret contents of memory between aliasing resources consistently in some cases,
  1783. which is called "data inheritance". For details, see
  1784. Microsoft documentation chapter "Memory Aliasing and Data Inheritance".
  1785. - You can create more complex layout where different textures and buffers are bound
  1786. at different offsets inside one large allocation. For example, one can imagine
  1787. a big texture used in some render passes, aliasing with a set of many small buffers
  1788. used in some further passes. To bind a resource at non-zero offset of an allocation,
  1789. call D3D12MA::Allocator::CreateAliasingResource with appropriate value of `AllocationLocalOffset` parameter.
  1790. - Resources of the three categories: buffers, textures with `RENDER_TARGET` or `DEPTH_STENCIL` flags, and all other textures,
  1791. can be placed in the same memory only when `allocator->GetD3D12Options().ResourceHeapTier >= D3D12_RESOURCE_HEAP_TIER_2`.
  1792. Otherwise they must be placed in different memory heap types, and thus aliasing them is not possible.
  1793. \page linear_algorithm Linear allocation algorithm
  1794. Each D3D12 memory block managed by this library has accompanying metadata that
  1795. keeps track of used and unused regions. By default, the metadata structure and
  1796. algorithm tries to find best place for new allocations among free regions to
  1797. optimize memory usage. This way you can allocate and free objects in any order.
  1798. ![Default allocation algorithm](../gfx/Linear_allocator_1_algo_default.png)
  1799. Sometimes there is a need to use simpler, linear allocation algorithm. You can
  1800. create custom pool that uses such algorithm by adding flag
  1801. D3D12MA::POOL_FLAG_ALGORITHM_LINEAR to D3D12MA::POOL_DESC::Flags while creating
  1802. D3D12MA::Pool object. Then an alternative metadata management is used. It always
  1803. creates new allocations after last one and doesn't reuse free regions after
  1804. allocations freed in the middle. It results in better allocation performance and
  1805. less memory consumed by metadata.
  1806. ![Linear allocation algorithm](../gfx/Linear_allocator_2_algo_linear.png)
  1807. With this one flag, you can create a custom pool that can be used in many ways:
  1808. free-at-once, stack, double stack, and ring buffer. See below for details.
  1809. You don't need to specify explicitly which of these options you are going to use - it is detected automatically.
  1810. \section linear_algorithm_free_at_once Free-at-once
  1811. In a pool that uses linear algorithm, you still need to free all the allocations
  1812. individually by calling `allocation->Release()`. You can free
  1813. them in any order. New allocations are always made after last one - free space
  1814. in the middle is not reused. However, when you release all the allocation and
  1815. the pool becomes empty, allocation starts from the beginning again. This way you
  1816. can use linear algorithm to speed up creation of allocations that you are going
  1817. to release all at once.
  1818. ![Free-at-once](../gfx/Linear_allocator_3_free_at_once.png)
  1819. This mode is also available for pools created with D3D12MA::POOL_DESC::MaxBlockCount
  1820. value that allows multiple memory blocks.
  1821. \section linear_algorithm_stack Stack
  1822. When you free an allocation that was created last, its space can be reused.
  1823. Thanks to this, if you always release allocations in the order opposite to their
  1824. creation (LIFO - Last In First Out), you can achieve behavior of a stack.
  1825. ![Stack](../gfx/Linear_allocator_4_stack.png)
  1826. This mode is also available for pools created with D3D12MA::POOL_DESC::MaxBlockCount
  1827. value that allows multiple memory blocks.
  1828. \section linear_algorithm_double_stack Double stack
  1829. The space reserved by a custom pool with linear algorithm may be used by two
  1830. stacks:
  1831. - First, default one, growing up from offset 0.
  1832. - Second, "upper" one, growing down from the end towards lower offsets.
  1833. To make allocation from the upper stack, add flag D3D12MA::ALLOCATION_FLAG_UPPER_ADDRESS
  1834. to D3D12MA::ALLOCATION_DESC::Flags.
  1835. ![Double stack](../gfx/Linear_allocator_7_double_stack.png)
  1836. Double stack is available only in pools with one memory block -
  1837. D3D12MA::POOL_DESC::MaxBlockCount must be 1. Otherwise behavior is undefined.
  1838. When the two stacks' ends meet so there is not enough space between them for a
  1839. new allocation, such allocation fails with usual `E_OUTOFMEMORY` error.
  1840. \section linear_algorithm_ring_buffer Ring buffer
  1841. When you free some allocations from the beginning and there is not enough free space
  1842. for a new one at the end of a pool, allocator's "cursor" wraps around to the
  1843. beginning and starts allocation there. Thanks to this, if you always release
  1844. allocations in the same order as you created them (FIFO - First In First Out),
  1845. you can achieve behavior of a ring buffer / queue.
  1846. ![Ring buffer](../gfx/Linear_allocator_5_ring_buffer.png)
  1847. Ring buffer is available only in pools with one memory block -
  1848. D3D12MA::POOL_DESC::MaxBlockCount must be 1. Otherwise behavior is undefined.
  1849. \section linear_algorithm_additional_considerations Additional considerations
  1850. Linear algorithm can also be used with \ref virtual_allocator.
  1851. See flag D3D12MA::VIRTUAL_BLOCK_FLAG_ALGORITHM_LINEAR.
  1852. \page virtual_allocator Virtual allocator
  1853. As an extra feature, the core allocation algorithm of the library is exposed through a simple and convenient API of "virtual allocator".
  1854. It doesn't allocate any real GPU memory. It just keeps track of used and free regions of a "virtual block".
  1855. You can use it to allocate your own memory or other objects, even completely unrelated to D3D12.
  1856. A common use case is sub-allocation of pieces of one large GPU buffer.
  1857. \section virtual_allocator_creating_virtual_block Creating virtual block
  1858. To use this functionality, there is no main "allocator" object.
  1859. You don't need to have D3D12MA::Allocator object created.
  1860. All you need to do is to create a separate D3D12MA::VirtualBlock object for each block of memory you want to be managed by the allocator:
  1861. -# Fill in D3D12MA::ALLOCATOR_DESC structure.
  1862. -# Call D3D12MA::CreateVirtualBlock. Get new D3D12MA::VirtualBlock object.
  1863. Example:
  1864. \code
  1865. D3D12MA::VIRTUAL_BLOCK_DESC blockDesc = {};
  1866. blockDesc.Size = 1048576; // 1 MB
  1867. D3D12MA::VirtualBlock *block;
  1868. HRESULT hr = CreateVirtualBlock(&blockDesc, &block);
  1869. \endcode
  1870. \section virtual_allocator_making_virtual_allocations Making virtual allocations
  1871. D3D12MA::VirtualBlock object contains internal data structure that keeps track of free and occupied regions
  1872. using the same code as the main D3D12 memory allocator.
  1873. A single allocation is identified by a lightweight structure D3D12MA::VirtualAllocation.
  1874. You will also likely want to know the offset at which the allocation was made in the block.
  1875. In order to make an allocation:
  1876. -# Fill in D3D12MA::VIRTUAL_ALLOCATION_DESC structure.
  1877. -# Call D3D12MA::VirtualBlock::Allocate. Get new D3D12MA::VirtualAllocation value that identifies the allocation.
  1878. Example:
  1879. \code
  1880. D3D12MA::VIRTUAL_ALLOCATION_DESC allocDesc = {};
  1881. allocDesc.Size = 4096; // 4 KB
  1882. D3D12MA::VirtualAllocation alloc;
  1883. UINT64 allocOffset;
  1884. hr = block->Allocate(&allocDesc, &alloc, &allocOffset);
  1885. if(SUCCEEDED(hr))
  1886. {
  1887. // Use the 4 KB of your memory starting at allocOffset.
  1888. }
  1889. else
  1890. {
  1891. // Allocation failed - no space for it could be found. Handle this error!
  1892. }
  1893. \endcode
  1894. \section virtual_allocator_deallocation Deallocation
  1895. When no longer needed, an allocation can be freed by calling D3D12MA::VirtualBlock::FreeAllocation.
  1896. When whole block is no longer needed, the block object can be released by calling `block->Release()`.
  1897. All allocations must be freed before the block is destroyed, which is checked internally by an assert.
  1898. However, if you don't want to call `block->FreeAllocation` for each allocation, you can use D3D12MA::VirtualBlock::Clear to free them all at once -
  1899. a feature not available in normal D3D12 memory allocator.
  1900. Example:
  1901. \code
  1902. block->FreeAllocation(alloc);
  1903. block->Release();
  1904. \endcode
  1905. \section virtual_allocator_allocation_parameters Allocation parameters
  1906. You can attach a custom pointer to each allocation by using D3D12MA::VirtualBlock::SetAllocationPrivateData.
  1907. Its default value is `NULL`.
  1908. 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
  1909. larger data structure containing more information. Example:
  1910. \code
  1911. struct CustomAllocData
  1912. {
  1913. std::string m_AllocName;
  1914. };
  1915. CustomAllocData* allocData = new CustomAllocData();
  1916. allocData->m_AllocName = "My allocation 1";
  1917. block->SetAllocationPrivateData(alloc, allocData);
  1918. \endcode
  1919. The pointer can later be fetched, along with allocation offset and size, by passing the allocation handle to function
  1920. D3D12MA::VirtualBlock::GetAllocationInfo and inspecting returned structure D3D12MA::VIRTUAL_ALLOCATION_INFO.
  1921. If you allocated a new object to be used as the custom pointer, don't forget to delete that object before freeing the allocation!
  1922. Example:
  1923. \code
  1924. VIRTUAL_ALLOCATION_INFO allocInfo;
  1925. block->GetAllocationInfo(alloc, &allocInfo);
  1926. delete (CustomAllocData*)allocInfo.pPrivateData;
  1927. block->FreeAllocation(alloc);
  1928. \endcode
  1929. \section virtual_allocator_alignment_and_units Alignment and units
  1930. It feels natural to express sizes and offsets in bytes.
  1931. 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
  1932. D3D12MA::VIRTUAL_ALLOCATION_DESC::Alignment to request it. Example:
  1933. \code
  1934. D3D12MA::VIRTUAL_ALLOCATION_DESC allocDesc = {};
  1935. allocDesc.Size = 4096; // 4 KB
  1936. allocDesc.Alignment = 4; // Returned offset must be a multiply of 4 B
  1937. D3D12MA::VirtualAllocation alloc;
  1938. UINT64 allocOffset;
  1939. hr = block->Allocate(&allocDesc, &alloc, &allocOffset);
  1940. \endcode
  1941. Alignments of different allocations made from one block may vary.
  1942. However, if all alignments and sizes are always multiply of some size e.g. 4 B or `sizeof(MyDataStruct)`,
  1943. you can express all sizes, alignments, and offsets in multiples of that size instead of individual bytes.
  1944. It might be more convenient, but you need to make sure to use this new unit consistently in all the places:
  1945. - D3D12MA::VIRTUAL_BLOCK_DESC::Size
  1946. - D3D12MA::VIRTUAL_ALLOCATION_DESC::Size and D3D12MA::VIRTUAL_ALLOCATION_DESC::Alignment
  1947. - Using offset returned by D3D12MA::VirtualBlock::Allocate and D3D12MA::VIRTUAL_ALLOCATION_INFO::Offset
  1948. \section virtual_allocator_statistics Statistics
  1949. You can obtain brief statistics of a virtual block using D3D12MA::VirtualBlock::GetStatistics().
  1950. The function fills structure D3D12MA::Statistics - same as used by the normal D3D12 memory allocator.
  1951. Example:
  1952. \code
  1953. D3D12MA::Statistics stats;
  1954. block->GetStatistics(&stats);
  1955. printf("My virtual block has %llu bytes used by %u virtual allocations\n",
  1956. stats.AllocationBytes, stats.AllocationCount);
  1957. \endcode
  1958. More detailed statistics can be obtained using function D3D12MA::VirtualBlock::CalculateStatistics(),
  1959. but they are slower to calculate.
  1960. You can also request a full list of allocations and free regions as a string in JSON format by calling
  1961. D3D12MA::VirtualBlock::BuildStatsString.
  1962. Returned string must be later freed using D3D12MA::VirtualBlock::FreeStatsString.
  1963. The format of this string may differ from the one returned by the main D3D12 allocator, but it is similar.
  1964. \section virtual_allocator_additional_considerations Additional considerations
  1965. Alternative, linear algorithm can be used with virtual allocator - see flag
  1966. D3D12MA::VIRTUAL_BLOCK_FLAG_ALGORITHM_LINEAR and documentation: \ref linear_algorithm.
  1967. Note that the "virtual allocator" functionality is implemented on a level of individual memory blocks.
  1968. Keeping track of a whole collection of blocks, allocating new ones when out of free space,
  1969. deleting empty ones, and deciding which one to try first for a new allocation must be implemented by the user.
  1970. \page configuration Configuration
  1971. Please check file `D3D12MemAlloc.cpp` lines between "Configuration Begin" and
  1972. "Configuration End" to find macros that you can define to change the behavior of
  1973. the library, primarily for debugging purposes.
  1974. \section custom_memory_allocator Custom CPU memory allocator
  1975. If you use custom allocator for CPU memory rather than default C++ operator `new`
  1976. and `delete` or `malloc` and `free` functions, you can make this library using
  1977. your allocator as well by filling structure D3D12MA::ALLOCATION_CALLBACKS and
  1978. passing it as optional member D3D12MA::ALLOCATOR_DESC::pAllocationCallbacks.
  1979. Functions pointed there will be used by the library to make any CPU-side
  1980. allocations. Example:
  1981. \code
  1982. #include <malloc.h>
  1983. void* CustomAllocate(size_t Size, size_t Alignment, void* pPrivateData)
  1984. {
  1985. void* memory = _aligned_malloc(Size, Alignment);
  1986. // Your extra bookkeeping here...
  1987. return memory;
  1988. }
  1989. void CustomFree(void* pMemory, void* pPrivateData)
  1990. {
  1991. // Your extra bookkeeping here...
  1992. _aligned_free(pMemory);
  1993. }
  1994. (...)
  1995. D3D12MA::ALLOCATION_CALLBACKS allocationCallbacks = {};
  1996. allocationCallbacks.pAllocate = &CustomAllocate;
  1997. allocationCallbacks.pFree = &CustomFree;
  1998. D3D12MA::ALLOCATOR_DESC allocatorDesc = {};
  1999. allocatorDesc.pDevice = device;
  2000. allocatorDesc.pAdapter = adapter;
  2001. allocatorDesc.pAllocationCallbacks = &allocationCallbacks;
  2002. D3D12MA::Allocator* allocator;
  2003. HRESULT hr = D3D12MA::CreateAllocator(&allocatorDesc, &allocator);
  2004. \endcode
  2005. \section debug_margins Debug margins
  2006. By default, allocations are laid out in memory blocks next to each other if possible
  2007. (considering required alignment returned by `ID3D12Device::GetResourceAllocationInfo`).
  2008. ![Allocations without margin](../gfx/Margins_1.png)
  2009. Define macro `D3D12MA_DEBUG_MARGIN` to some non-zero value (e.g. 16) inside "D3D12MemAlloc.cpp"
  2010. to enforce specified number of bytes as a margin after every allocation.
  2011. ![Allocations with margin](../gfx/Margins_2.png)
  2012. If your bug goes away after enabling margins, it means it may be caused by memory
  2013. being overwritten outside of allocation boundaries. It is not 100% certain though.
  2014. Change in application behavior may also be caused by different order and distribution
  2015. of allocations across memory blocks after margins are applied.
  2016. Margins work with all memory heap types.
  2017. Margin is applied only to placed allocations made out of memory heaps and not to committed
  2018. allocations, which have their own, implicit memory heap of specific size.
  2019. It is thus not applied to allocations made using D3D12MA::ALLOCATION_FLAG_COMMITTED flag
  2020. or those automatically decided to put into committed allocations, e.g. due to its large size.
  2021. Margins appear in [JSON dump](@ref statistics_json_dump) as part of free space.
  2022. Note that enabling margins increases memory usage and fragmentation.
  2023. Margins do not apply to \ref virtual_allocator.
  2024. \page general_considerations General considerations
  2025. \section general_considerations_thread_safety Thread safety
  2026. - The library has no global state, so separate D3D12MA::Allocator objects can be used independently.
  2027. In typical applications there should be no need to create multiple such objects though - one per `ID3D12Device` is enough.
  2028. - All calls to methods of D3D12MA::Allocator class are safe to be made from multiple
  2029. threads simultaneously because they are synchronized internally when needed.
  2030. - When the allocator is created with D3D12MA::ALLOCATOR_FLAG_SINGLETHREADED,
  2031. calls to methods of D3D12MA::Allocator class must be made from a single thread or synchronized by the user.
  2032. Using this flag may improve performance.
  2033. - D3D12MA::VirtualBlock is not safe to be used from multiple threads simultaneously.
  2034. \section general_considerations_versioning_and_compatibility Versioning and compatibility
  2035. The library uses [**Semantic Versioning**](https://semver.org/),
  2036. which means version numbers follow convention: Major.Minor.Patch (e.g. 2.3.0), where:
  2037. - Incremented Patch version means a release is backward- and forward-compatible,
  2038. introducing only some internal improvements, bug fixes, optimizations etc.
  2039. or changes that are out of scope of the official API described in this documentation.
  2040. - Incremented Minor version means a release is backward-compatible,
  2041. so existing code that uses the library should continue to work, while some new
  2042. symbols could have been added: new structures, functions, new values in existing
  2043. enums and bit flags, new structure members, but not new function parameters.
  2044. - Incrementing Major version means a release could break some backward compatibility.
  2045. All changes between official releases are documented in file "CHANGELOG.md".
  2046. \warning Backward compatiblity is considered on the level of C++ source code, not binary linkage.
  2047. Adding new members to existing structures is treated as backward compatible if initializing
  2048. the new members to binary zero results in the old behavior.
  2049. You should always fully initialize all library structures to zeros and not rely on their
  2050. exact binary size.
  2051. \section general_considerations_features_not_supported Features not supported
  2052. Features deliberately excluded from the scope of this library:
  2053. - **Descriptor allocation.** Although also called "heaps", objects that represent
  2054. descriptors are separate part of the D3D12 API from buffers and textures.
  2055. You can still use \ref virtual_allocator to manage descriptors and their ranges inside a descriptor heap.
  2056. - **Support for reserved (tiled) resources.** We don't recommend using them.
  2057. - Support for `ID3D12Device::Evict` and `MakeResident`. We don't recommend using them.
  2058. You can call them on the D3D12 objects manually.
  2059. Plese keep in mind, however, that eviction happens on the level of entire `ID3D12Heap` memory blocks
  2060. and not individual buffers or textures which may be placed inside them.
  2061. - **Handling CPU memory allocation failures.** When dynamically creating small C++
  2062. objects in CPU memory (not the GPU memory), allocation failures are not
  2063. handled gracefully, because that would complicate code significantly and
  2064. is usually not needed in desktop PC applications anyway.
  2065. Success of an allocation is just checked with an assert.
  2066. - **Code free of any compiler warnings.**
  2067. There are many preprocessor macros that make some variables unused, function parameters unreferenced,
  2068. or conditional expressions constant in some configurations.
  2069. The code of this library should not be bigger or more complicated just to silence these warnings.
  2070. It is recommended to disable such warnings instead.
  2071. - This is a C++ library. **Bindings or ports to any other programming languages** are welcome as external projects but
  2072. are not going to be included into this repository.
  2073. */