Path: blob/master/dep/d3d12ma/include/D3D12MemAlloc.h
4253 views
//1// Copyright (c) 2019-2022 Advanced Micro Devices, Inc. All rights reserved.2//3// Permission is hereby granted, free of charge, to any person obtaining a copy4// of this software and associated documentation files (the "Software"), to deal5// in the Software without restriction, including without limitation the rights6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell7// copies of the Software, and to permit persons to whom the Software is8// furnished to do so, subject to the following conditions:9//10// The above copyright notice and this permission notice shall be included in11// all copies or substantial portions of the Software.12//13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN19// THE SOFTWARE.20//2122#pragma once2324/** \mainpage D3D12 Memory Allocator2526<b>Version 2.1.0-development</b> (2023-07-05)2728Copyright (c) 2019-2023 Advanced Micro Devices, Inc. All rights reserved. \n29License: MIT3031Documentation of all members: D3D12MemAlloc.h3233\section main_table_of_contents Table of contents3435- \subpage quick_start36- [Project setup](@ref quick_start_project_setup)37- [Creating resources](@ref quick_start_creating_resources)38- [Resource reference counting](@ref quick_start_resource_reference_counting)39- [Mapping memory](@ref quick_start_mapping_memory)40- \subpage custom_pools41- \subpage defragmentation42- \subpage statistics43- \subpage resource_aliasing44- \subpage linear_algorithm45- \subpage virtual_allocator46- \subpage configuration47- [Custom CPU memory allocator](@ref custom_memory_allocator)48- [Debug margins](@ref debug_margins)49- \subpage general_considerations50- [Thread safety](@ref general_considerations_thread_safety)51- [Versioning and compatibility](@ref general_considerations_versioning_and_compatibility)52- [Features not supported](@ref general_considerations_features_not_supported)5354\section main_see_also See also5556- [Product page on GPUOpen](https://gpuopen.com/gaming-product/d3d12-memory-allocator/)57- [Source repository on GitHub](https://github.com/GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator)58*/5960// If using this library on a platform different than Windows PC or want to use different version of DXGI,61// you should include D3D12-compatible headers before this library on your own and define62// D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED.63// Alternatively, if you are targeting the open sourced DirectX headers, defining D3D12MA_USING_DIRECTX_HEADERS64// will include them rather the ones provided by the Windows SDK.65#ifndef D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED66#if defined(D3D12MA_USING_DIRECTX_HEADERS)67#include <directx/d3d12.h>68#include <dxguids/dxguids.h>69#else70#include <d3d12.h>71#endif7273#include <dxgi1_4.h>74#endif7576// Define this macro to 0 to disable usage of DXGI 1.4 (needed for IDXGIAdapter3 and query for memory budget).77#ifndef D3D12MA_DXGI_1_478#ifdef __IDXGIAdapter3_INTERFACE_DEFINED__79#define D3D12MA_DXGI_1_4 180#else81#define D3D12MA_DXGI_1_4 082#endif83#endif8485/*86When defined to value other than 0, the library will try to use87D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT or D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT88for created textures when possible, which can save memory because some small textures89may get their alignment 4K and their size a multiply of 4K instead of 64K.9091#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 092Disables small texture alignment.93#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 194Enables conservative algorithm that will use small alignment only for some textures95that are surely known to support it.96#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 297Enables query for small alignment to D3D12 (based on Microsoft sample) which will98enable small alignment for more textures, but will also generate D3D Debug Layer99error #721 on call to ID3D12Device::GetResourceAllocationInfo, which you should just100ignore.101*/102#ifndef D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT103#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 1104#endif105106/// \cond INTERNAL107108#define D3D12MA_CLASS_NO_COPY(className) \109private: \110className(const className&) = delete; \111className(className&&) = delete; \112className& operator=(const className&) = delete; \113className& operator=(className&&) = delete;114115// To be used with MAKE_HRESULT to define custom error codes.116#define FACILITY_D3D12MA 3542117118/*119If providing your own implementation, you need to implement a subset of std::atomic.120*/121#if !defined(D3D12MA_ATOMIC_UINT32) || !defined(D3D12MA_ATOMIC_UINT64)122#include <atomic>123#endif124125#ifndef D3D12MA_ATOMIC_UINT32126#define D3D12MA_ATOMIC_UINT32 std::atomic<UINT>127#endif128129#ifndef D3D12MA_ATOMIC_UINT64130#define D3D12MA_ATOMIC_UINT64 std::atomic<UINT64>131#endif132133#ifdef D3D12MA_EXPORTS134#define D3D12MA_API __declspec(dllexport)135#elif defined(D3D12MA_IMPORTS)136#define D3D12MA_API __declspec(dllimport)137#else138#define D3D12MA_API139#endif140141// Forward declaration if ID3D12ProtectedResourceSession is not defined inside the headers (older SDK, pre ID3D12Device4)142struct ID3D12ProtectedResourceSession;143144// Define this enum even if SDK doesn't provide it, to simplify the API.145#ifndef __ID3D12Device1_INTERFACE_DEFINED__146typedef enum D3D12_RESIDENCY_PRIORITY147{148D3D12_RESIDENCY_PRIORITY_MINIMUM = 0x28000000,149D3D12_RESIDENCY_PRIORITY_LOW = 0x50000000,150D3D12_RESIDENCY_PRIORITY_NORMAL = 0x78000000,151D3D12_RESIDENCY_PRIORITY_HIGH = 0xa0010000,152D3D12_RESIDENCY_PRIORITY_MAXIMUM = 0xc8000000153} D3D12_RESIDENCY_PRIORITY;154#endif155156namespace D3D12MA157{158class D3D12MA_API IUnknownImpl : public IUnknown159{160public:161virtual ~IUnknownImpl() = default;162virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObject);163virtual ULONG STDMETHODCALLTYPE AddRef();164virtual ULONG STDMETHODCALLTYPE Release();165protected:166virtual void ReleaseThis() { delete this; }167private:168D3D12MA_ATOMIC_UINT32 m_RefCount = {1};169};170} // namespace D3D12MA171172/// \endcond173174namespace D3D12MA175{176177/// \cond INTERNAL178class DefragmentationContextPimpl;179class AllocatorPimpl;180class PoolPimpl;181class NormalBlock;182class BlockVector;183class CommittedAllocationList;184class JsonWriter;185class VirtualBlockPimpl;186/// \endcond187188class Pool;189class Allocator;190struct Statistics;191struct DetailedStatistics;192struct TotalStatistics;193194/// \brief Unique identifier of single allocation done inside the memory heap.195typedef UINT64 AllocHandle;196197/// Pointer to custom callback function that allocates CPU memory.198using ALLOCATE_FUNC_PTR = void* (*)(size_t Size, size_t Alignment, void* pPrivateData);199/**200\brief Pointer to custom callback function that deallocates CPU memory.201202`pMemory = null` should be accepted and ignored.203*/204using FREE_FUNC_PTR = void (*)(void* pMemory, void* pPrivateData);205206/// Custom callbacks to CPU memory allocation functions.207struct ALLOCATION_CALLBACKS208{209/// %Allocation function.210ALLOCATE_FUNC_PTR pAllocate;211/// Dellocation function.212FREE_FUNC_PTR pFree;213/// Custom data that will be passed to allocation and deallocation functions as `pUserData` parameter.214void* pPrivateData;215};216217218/// \brief Bit flags to be used with ALLOCATION_DESC::Flags.219enum ALLOCATION_FLAGS220{221/// Zero222ALLOCATION_FLAG_NONE = 0,223224/**225Set this flag if the allocation should have its own dedicated memory allocation (committed resource with implicit heap).226227Use it for special, big resources, like fullscreen textures used as render targets.228229- When used with functions like D3D12MA::Allocator::CreateResource, it will use `ID3D12Device::CreateCommittedResource`,230so the created allocation will contain a resource (D3D12MA::Allocation::GetResource() `!= NULL`) but will not have231a heap (D3D12MA::Allocation::GetHeap() `== NULL`), as the heap is implicit.232- When used with raw memory allocation like D3D12MA::Allocator::AllocateMemory, it will use `ID3D12Device::CreateHeap`,233so the created allocation will contain a heap (D3D12MA::Allocation::GetHeap() `!= NULL`) and its offset will always be 0.234*/235ALLOCATION_FLAG_COMMITTED = 0x1,236237/**238Set this flag to only try to allocate from existing memory heaps and never create new such heap.239240If new allocation cannot be placed in any of the existing heaps, allocation241fails with `E_OUTOFMEMORY` error.242243You should not use D3D12MA::ALLOCATION_FLAG_COMMITTED and244D3D12MA::ALLOCATION_FLAG_NEVER_ALLOCATE at the same time. It makes no sense.245*/246ALLOCATION_FLAG_NEVER_ALLOCATE = 0x2,247248/** Create allocation only if additional memory required for it, if any, won't exceed249memory budget. Otherwise return `E_OUTOFMEMORY`.250*/251ALLOCATION_FLAG_WITHIN_BUDGET = 0x4,252253/** Allocation will be created from upper stack in a double stack pool.254255This flag is only allowed for custom pools created with #POOL_FLAG_ALGORITHM_LINEAR flag.256*/257ALLOCATION_FLAG_UPPER_ADDRESS = 0x8,258259/** Set this flag if the allocated memory will have aliasing resources.260261Use this when calling D3D12MA::Allocator::CreateResource() and similar to262guarantee creation of explicit heap for desired allocation and prevent it from using `CreateCommittedResource`,263so that new allocation object will always have `allocation->GetHeap() != NULL`.264*/265ALLOCATION_FLAG_CAN_ALIAS = 0x10,266267/** Allocation strategy that chooses smallest possible free range for the allocation268to minimize memory usage and fragmentation, possibly at the expense of allocation time.269*/270ALLOCATION_FLAG_STRATEGY_MIN_MEMORY = 0x00010000,271272/** Allocation strategy that chooses first suitable free range for the allocation -273not necessarily in terms of the smallest offset but the one that is easiest and fastest to find274to minimize allocation time, possibly at the expense of allocation quality.275*/276ALLOCATION_FLAG_STRATEGY_MIN_TIME = 0x00020000,277278/** Allocation strategy that chooses always the lowest offset in available space.279This is not the most efficient strategy but achieves highly packed data.280Used internally by defragmentation, not recomended in typical usage.281*/282ALLOCATION_FLAG_STRATEGY_MIN_OFFSET = 0x0004000,283284/// Alias to #ALLOCATION_FLAG_STRATEGY_MIN_MEMORY.285ALLOCATION_FLAG_STRATEGY_BEST_FIT = ALLOCATION_FLAG_STRATEGY_MIN_MEMORY,286/// Alias to #ALLOCATION_FLAG_STRATEGY_MIN_TIME.287ALLOCATION_FLAG_STRATEGY_FIRST_FIT = ALLOCATION_FLAG_STRATEGY_MIN_TIME,288289/// A bit mask to extract only `STRATEGY` bits from entire set of flags.290ALLOCATION_FLAG_STRATEGY_MASK =291ALLOCATION_FLAG_STRATEGY_MIN_MEMORY |292ALLOCATION_FLAG_STRATEGY_MIN_TIME |293ALLOCATION_FLAG_STRATEGY_MIN_OFFSET,294};295296/// \brief Parameters of created D3D12MA::Allocation object. To be used with Allocator::CreateResource.297struct ALLOCATION_DESC298{299/// Flags.300ALLOCATION_FLAGS Flags;301/** \brief The type of memory heap where the new allocation should be placed.302303It must be one of: `D3D12_HEAP_TYPE_DEFAULT`, `D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`.304305When D3D12MA::ALLOCATION_DESC::CustomPool != NULL this member is ignored.306*/307D3D12_HEAP_TYPE HeapType;308/** \brief Additional heap flags to be used when allocating memory.309310In most cases it can be 0.311312- If you use D3D12MA::Allocator::CreateResource(), you don't need to care.313Necessary flag `D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS`, `D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES`,314or `D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES` is added automatically.315- If you use D3D12MA::Allocator::AllocateMemory(), you should specify one of those `ALLOW_ONLY` flags.316Except when you validate that D3D12MA::Allocator::GetD3D12Options()`.ResourceHeapTier == D3D12_RESOURCE_HEAP_TIER_1` -317then you can leave it 0.318- You can specify additional flags if needed. Then the memory will always be allocated as319separate block using `D3D12Device::CreateCommittedResource` or `CreateHeap`, not as part of an existing larget block.320321When D3D12MA::ALLOCATION_DESC::CustomPool != NULL this member is ignored.322*/323D3D12_HEAP_FLAGS ExtraHeapFlags;324/** \brief Custom pool to place the new resource in. Optional.325326When not NULL, the resource will be created inside specified custom pool.327*/328Pool* CustomPool;329/// Custom general-purpose pointer that will be stored in D3D12MA::Allocation.330void* pPrivateData;331};332333/** \brief Calculated statistics of memory usage e.g. in a specific memory heap type,334memory segment group, custom pool, or total.335336These are fast to calculate.337See functions: D3D12MA::Allocator::GetBudget(), D3D12MA::Pool::GetStatistics().338*/339struct Statistics340{341/** \brief Number of D3D12 memory blocks allocated - `ID3D12Heap` objects and committed resources.342*/343UINT BlockCount;344/** \brief Number of D3D12MA::Allocation objects allocated.345346Committed allocations have their own blocks, so each one adds 1 to `AllocationCount` as well as `BlockCount`.347*/348UINT AllocationCount;349/** \brief Number of bytes allocated in memory blocks.350*/351UINT64 BlockBytes;352/** \brief Total number of bytes occupied by all D3D12MA::Allocation objects.353354Always less or equal than `BlockBytes`.355Difference `(BlockBytes - AllocationBytes)` is the amount of memory allocated from D3D12356but unused by any D3D12MA::Allocation.357*/358UINT64 AllocationBytes;359};360361/** \brief More detailed statistics than D3D12MA::Statistics.362363These are slower to calculate. Use for debugging purposes.364See functions: D3D12MA::Allocator::CalculateStatistics(), D3D12MA::Pool::CalculateStatistics().365366Averages are not provided because they can be easily calculated as:367368\code369UINT64 AllocationSizeAvg = DetailedStats.Statistics.AllocationBytes / detailedStats.Statistics.AllocationCount;370UINT64 UnusedBytes = DetailedStats.Statistics.BlockBytes - DetailedStats.Statistics.AllocationBytes;371UINT64 UnusedRangeSizeAvg = UnusedBytes / DetailedStats.UnusedRangeCount;372\endcode373*/374struct DetailedStatistics375{376/// Basic statistics.377Statistics Stats;378/// Number of free ranges of memory between allocations.379UINT UnusedRangeCount;380/// Smallest allocation size. `UINT64_MAX` if there are 0 allocations.381UINT64 AllocationSizeMin;382/// Largest allocation size. 0 if there are 0 allocations.383UINT64 AllocationSizeMax;384/// Smallest empty range size. `UINT64_MAX` if there are 0 empty ranges.385UINT64 UnusedRangeSizeMin;386/// Largest empty range size. 0 if there are 0 empty ranges.387UINT64 UnusedRangeSizeMax;388};389390/** \brief General statistics from current state of the allocator -391total memory usage across all memory heaps and segments.392393These are slower to calculate. Use for debugging purposes.394See function D3D12MA::Allocator::CalculateStatistics().395*/396struct TotalStatistics397{398/** \brief One element for each type of heap located at the following indices:399400- 0 = `D3D12_HEAP_TYPE_DEFAULT`401- 1 = `D3D12_HEAP_TYPE_UPLOAD`402- 2 = `D3D12_HEAP_TYPE_READBACK`403- 3 = `D3D12_HEAP_TYPE_CUSTOM`404*/405DetailedStatistics HeapType[4];406/** \brief One element for each memory segment group located at the following indices:407408- 0 = `DXGI_MEMORY_SEGMENT_GROUP_LOCAL`409- 1 = `DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL`410411Meaning of these segment groups is:412413- When `IsUMA() == FALSE` (discrete graphics card):414- `DXGI_MEMORY_SEGMENT_GROUP_LOCAL` (index 0) represents GPU memory415(resources allocated in `D3D12_HEAP_TYPE_DEFAULT` or `D3D12_MEMORY_POOL_L1`).416- `DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL` (index 1) represents system memory417(resources allocated in `D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`, or `D3D12_MEMORY_POOL_L0`).418- When `IsUMA() == TRUE` (integrated graphics chip):419- `DXGI_MEMORY_SEGMENT_GROUP_LOCAL` = (index 0) represents memory shared for all the resources.420- `DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL` = (index 1) is unused and always 0.421*/422DetailedStatistics MemorySegmentGroup[2];423/// Total statistics from all memory allocated from D3D12.424DetailedStatistics Total;425};426427/** \brief %Statistics of current memory usage and available budget for a specific memory segment group.428429These are fast to calculate. See function D3D12MA::Allocator::GetBudget().430*/431struct Budget432{433/** \brief %Statistics fetched from the library.434*/435Statistics Stats;436/** \brief Estimated current memory usage of the program.437438Fetched from system using `IDXGIAdapter3::QueryVideoMemoryInfo` if possible.439440It might be different than `BlockBytes` (usually higher) due to additional implicit objects441also occupying the memory, like swapchain, pipeline state objects, descriptor heaps, command lists, or442heaps and resources allocated outside of this library, if any.443*/444UINT64 UsageBytes;445/** \brief Estimated amount of memory available to the program.446447Fetched from system using `IDXGIAdapter3::QueryVideoMemoryInfo` if possible.448449It might be different (most probably smaller) than memory capacity returned450by D3D12MA::Allocator::GetMemoryCapacity() due to factors451external to the program, decided by the operating system.452Difference `BudgetBytes - UsageBytes` is the amount of additional memory that can probably453be allocated without problems. Exceeding the budget may result in various problems.454*/455UINT64 BudgetBytes;456};457458459/// \brief Represents single memory allocation done inside VirtualBlock.460struct D3D12MA_API VirtualAllocation461{462/// \brief Unique idenitfier of current allocation. 0 means null/invalid.463AllocHandle AllocHandle;464};465466/** \brief Represents single memory allocation.467468It may be either implicit memory heap dedicated to a single resource or a469specific region of a bigger heap plus unique offset.470471To create such object, fill structure D3D12MA::ALLOCATION_DESC and call function472Allocator::CreateResource.473474The object remembers size and some other information.475To retrieve this information, use methods of this class.476477The object also remembers `ID3D12Resource` and "owns" a reference to it,478so it calls `%Release()` on the resource when destroyed.479*/480class D3D12MA_API Allocation : public IUnknownImpl481{482public:483/** \brief Returns offset in bytes from the start of memory heap.484485You usually don't need to use this offset. If you create a buffer or a texture together with the allocation using function486D3D12MA::Allocator::CreateResource, functions that operate on that resource refer to the beginning of the resource,487not entire memory heap.488489If the Allocation represents committed resource with implicit heap, returns 0.490*/491UINT64 GetOffset() const;492493/// Returns alignment that resource was created with.494UINT64 GetAlignment() const { return m_Alignment; }495496/** \brief Returns size in bytes of the allocation.497498- If you created a buffer or a texture together with the allocation using function D3D12MA::Allocator::CreateResource,499this is the size of the resource returned by `ID3D12Device::GetResourceAllocationInfo`.500- For allocations made out of bigger memory blocks, this also is the size of the memory region assigned exclusively to this allocation.501- For resources created as committed, this value may not be accurate. DirectX implementation may optimize memory usage internally502so that you may even observe regions of `ID3D12Resource::GetGPUVirtualAddress()` + Allocation::GetSize() to overlap in memory and still work correctly.503*/504UINT64 GetSize() const { return m_Size; }505506/** \brief Returns D3D12 resource associated with this object.507508Calling this method doesn't increment resource's reference counter.509*/510ID3D12Resource* GetResource() const { return m_Resource; }511512/// Releases the resource currently pointed by the allocation (if any), sets it to new one, incrementing its reference counter (if not null).513void SetResource(ID3D12Resource* pResource);514515/** \brief Returns memory heap that the resource is created in.516517If the Allocation represents committed resource with implicit heap, returns NULL.518*/519ID3D12Heap* GetHeap() const;520521/// Changes custom pointer for an allocation to a new value.522void SetPrivateData(void* pPrivateData) { m_pPrivateData = pPrivateData; }523524/// Get custom pointer associated with the allocation.525void* GetPrivateData() const { return m_pPrivateData; }526527/** \brief Associates a name with the allocation object. This name is for use in debug diagnostics and tools.528529Internal copy of the string is made, so the memory pointed by the argument can be530changed of freed immediately after this call.531532`Name` can be null.533*/534void SetName(LPCWSTR Name);535536/** \brief Returns the name associated with the allocation object.537538Returned string points to an internal copy.539540If no name was associated with the allocation, returns null.541*/542LPCWSTR GetName() const { return m_Name; }543544/** \brief Returns `TRUE` if the memory of the allocation was filled with zeros when the allocation was created.545546Returns `TRUE` only if the allocator is sure that the entire memory where the547allocation was created was filled with zeros at the moment the allocation was made.548549Returns `FALSE` if the memory could potentially contain garbage data.550If it's a render-target or depth-stencil texture, it then needs proper551initialization with `ClearRenderTargetView`, `ClearDepthStencilView`, `DiscardResource`,552or a copy operation, as described on page553"ID3D12Device::CreatePlacedResource method - Notes on the required resource initialization" in Microsoft documentation.554Please note that rendering a fullscreen triangle or quad to the texture as555a render target is not a proper way of initialization!556557See also articles:558559- "Coming to DirectX 12: More control over memory allocation" on DirectX Developer Blog560- ["Initializing DX12 Textures After Allocation and Aliasing"](https://asawicki.info/news_1724_initializing_dx12_textures_after_allocation_and_aliasing).561*/562BOOL WasZeroInitialized() const { return m_PackedData.WasZeroInitialized(); }563564protected:565void ReleaseThis() override;566567private:568friend class AllocatorPimpl;569friend class BlockVector;570friend class CommittedAllocationList;571friend class JsonWriter;572friend class BlockMetadata_Linear;573friend class DefragmentationContextPimpl;574friend struct CommittedAllocationListItemTraits;575template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);576template<typename T> friend class PoolAllocator;577578enum Type579{580TYPE_COMMITTED,581TYPE_PLACED,582TYPE_HEAP,583TYPE_COUNT584};585586AllocatorPimpl* m_Allocator;587UINT64 m_Size;588UINT64 m_Alignment;589ID3D12Resource* m_Resource;590void* m_pPrivateData;591wchar_t* m_Name;592593union594{595struct596{597CommittedAllocationList* list;598Allocation* prev;599Allocation* next;600} m_Committed;601602struct603{604AllocHandle allocHandle;605NormalBlock* block;606} m_Placed;607608struct609{610// Beginning must be compatible with m_Committed.611CommittedAllocationList* list;612Allocation* prev;613Allocation* next;614ID3D12Heap* heap;615} m_Heap;616};617618struct PackedData619{620public:621PackedData() :622m_Type(0), m_ResourceDimension(0), m_ResourceFlags(0), m_TextureLayout(0), m_WasZeroInitialized(0) { }623624Type GetType() const { return (Type)m_Type; }625D3D12_RESOURCE_DIMENSION GetResourceDimension() const { return (D3D12_RESOURCE_DIMENSION)m_ResourceDimension; }626D3D12_RESOURCE_FLAGS GetResourceFlags() const { return (D3D12_RESOURCE_FLAGS)m_ResourceFlags; }627D3D12_TEXTURE_LAYOUT GetTextureLayout() const { return (D3D12_TEXTURE_LAYOUT)m_TextureLayout; }628BOOL WasZeroInitialized() const { return (BOOL)m_WasZeroInitialized; }629630void SetType(Type type);631void SetResourceDimension(D3D12_RESOURCE_DIMENSION resourceDimension);632void SetResourceFlags(D3D12_RESOURCE_FLAGS resourceFlags);633void SetTextureLayout(D3D12_TEXTURE_LAYOUT textureLayout);634void SetWasZeroInitialized(BOOL wasZeroInitialized) { m_WasZeroInitialized = wasZeroInitialized ? 1 : 0; }635636private:637UINT m_Type : 2; // enum Type638UINT m_ResourceDimension : 3; // enum D3D12_RESOURCE_DIMENSION639UINT m_ResourceFlags : 24; // flags D3D12_RESOURCE_FLAGS640UINT m_TextureLayout : 9; // enum D3D12_TEXTURE_LAYOUT641UINT m_WasZeroInitialized : 1; // BOOL642} m_PackedData;643644Allocation(AllocatorPimpl* allocator, UINT64 size, UINT64 alignment, BOOL wasZeroInitialized);645// Nothing here, everything already done in Release.646virtual ~Allocation() = default;647648void InitCommitted(CommittedAllocationList* list);649void InitPlaced(AllocHandle allocHandle, NormalBlock* block);650void InitHeap(CommittedAllocationList* list, ID3D12Heap* heap);651void SwapBlockAllocation(Allocation* allocation);652// If the Allocation represents committed resource with implicit heap, returns UINT64_MAX.653AllocHandle GetAllocHandle() const;654NormalBlock* GetBlock();655template<typename D3D12_RESOURCE_DESC_T>656void SetResourcePointer(ID3D12Resource* resource, const D3D12_RESOURCE_DESC_T* pResourceDesc);657void FreeName();658659D3D12MA_CLASS_NO_COPY(Allocation)660};661662663/// Flags to be passed as DEFRAGMENTATION_DESC::Flags.664enum DEFRAGMENTATION_FLAGS665{666/** Use simple but fast algorithm for defragmentation.667May not achieve best results but will require least time to compute and least allocations to copy.668*/669DEFRAGMENTATION_FLAG_ALGORITHM_FAST = 0x1,670/** Default defragmentation algorithm, applied also when no `ALGORITHM` flag is specified.671Offers a balance between defragmentation quality and the amount of allocations and bytes that need to be moved.672*/673DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED = 0x2,674/** Perform full defragmentation of memory.675Can result in notably more time to compute and allocations to copy, but will achieve best memory packing.676*/677DEFRAGMENTATION_FLAG_ALGORITHM_FULL = 0x4,678679/// A bit mask to extract only `ALGORITHM` bits from entire set of flags.680DEFRAGMENTATION_FLAG_ALGORITHM_MASK =681DEFRAGMENTATION_FLAG_ALGORITHM_FAST |682DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED |683DEFRAGMENTATION_FLAG_ALGORITHM_FULL684};685686/** \brief Parameters for defragmentation.687688To be used with functions Allocator::BeginDefragmentation() and Pool::BeginDefragmentation().689*/690struct DEFRAGMENTATION_DESC691{692/// Flags.693DEFRAGMENTATION_FLAGS Flags;694/** \brief Maximum numbers of bytes that can be copied during single pass, while moving allocations to different places.6956960 means no limit.697*/698UINT64 MaxBytesPerPass;699/** \brief Maximum number of allocations that can be moved during single pass to a different place.7007010 means no limit.702*/703UINT32 MaxAllocationsPerPass;704};705706/// Operation performed on single defragmentation move.707enum DEFRAGMENTATION_MOVE_OPERATION708{709/** Resource has been recreated at `pDstTmpAllocation`, data has been copied, old resource has been destroyed.710`pSrcAllocation` will be changed to point to the new place. This is the default value set by DefragmentationContext::BeginPass().711*/712DEFRAGMENTATION_MOVE_OPERATION_COPY = 0,713/// Set this value if you cannot move the allocation. New place reserved at `pDstTmpAllocation` will be freed. `pSrcAllocation` will remain unchanged.714DEFRAGMENTATION_MOVE_OPERATION_IGNORE = 1,715/// 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`.716DEFRAGMENTATION_MOVE_OPERATION_DESTROY = 2,717};718719/// Single move of an allocation to be done for defragmentation.720struct DEFRAGMENTATION_MOVE721{722/** \brief Operation to be performed on the allocation by DefragmentationContext::EndPass().723Default value is #DEFRAGMENTATION_MOVE_OPERATION_COPY. You can modify it.724*/725DEFRAGMENTATION_MOVE_OPERATION Operation;726/// %Allocation that should be moved.727Allocation* pSrcAllocation;728/** \brief Temporary allocation pointing to destination memory that will replace `pSrcAllocation`.729730Use it to retrieve new `ID3D12Heap` and offset to create new `ID3D12Resource` and then store it here via Allocation::SetResource().731732\warning Do not store this allocation in your data structures! It exists only temporarily, for the duration of the defragmentation pass,733to be used for storing newly created resource. DefragmentationContext::EndPass() will destroy it and make `pSrcAllocation` point to this memory.734*/735Allocation* pDstTmpAllocation;736};737738/** \brief Parameters for incremental defragmentation steps.739740To be used with function DefragmentationContext::BeginPass().741*/742struct DEFRAGMENTATION_PASS_MOVE_INFO743{744/// Number of elements in the `pMoves` array.745UINT32 MoveCount;746/** \brief Array of moves to be performed by the user in the current defragmentation pass.747748Pointer to an array of `MoveCount` elements, owned by %D3D12MA, created in DefragmentationContext::BeginPass(), destroyed in DefragmentationContext::EndPass().749750For each element, you should:7517521. Create a new resource in the place pointed by `pMoves[i].pDstTmpAllocation->GetHeap()` + `pMoves[i].pDstTmpAllocation->GetOffset()`.7532. Store new resource in `pMoves[i].pDstTmpAllocation` by using Allocation::SetResource(). It will later replace old resource from `pMoves[i].pSrcAllocation`.7543. Copy data from the `pMoves[i].pSrcAllocation` e.g. using `D3D12GraphicsCommandList::CopyResource`.7554. Make sure these commands finished executing on the GPU.756757Only then you can finish defragmentation pass by calling DefragmentationContext::EndPass().758After this call, the allocation will point to the new place in memory.759760Alternatively, if you cannot move specific allocation,761you can set DEFRAGMENTATION_MOVE::Operation to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_IGNORE.762763Alternatively, if you decide you want to completely remove the allocation,764set DEFRAGMENTATION_MOVE::Operation to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_DESTROY.765Then, after DefragmentationContext::EndPass() the allocation will be released.766*/767DEFRAGMENTATION_MOVE* pMoves;768};769770/// %Statistics returned for defragmentation process by function DefragmentationContext::GetStats().771struct DEFRAGMENTATION_STATS772{773/// Total number of bytes that have been copied while moving allocations to different places.774UINT64 BytesMoved;775/// Total number of bytes that have been released to the system by freeing empty heaps.776UINT64 BytesFreed;777/// Number of allocations that have been moved to different places.778UINT32 AllocationsMoved;779/// Number of empty `ID3D12Heap` objects that have been released to the system.780UINT32 HeapsFreed;781};782783/** \brief Represents defragmentation process in progress.784785You can create this object using Allocator::BeginDefragmentation (for default pools) or786Pool::BeginDefragmentation (for a custom pool).787*/788class D3D12MA_API DefragmentationContext : public IUnknownImpl789{790public:791/** \brief Starts single defragmentation pass.792793\param[out] pPassInfo Computed informations for current pass.794\returns795- `S_OK` if no more moves are possible. Then you can omit call to DefragmentationContext::EndPass() and simply end whole defragmentation.796- `S_FALSE` if there are pending moves returned in `pPassInfo`. You need to perform them, call DefragmentationContext::EndPass(),797and then preferably try another pass with DefragmentationContext::BeginPass().798*/799HRESULT BeginPass(DEFRAGMENTATION_PASS_MOVE_INFO* pPassInfo);800/** \brief Ends single defragmentation pass.801802\param pPassInfo Computed informations for current pass filled by DefragmentationContext::BeginPass() and possibly modified by you.803\return Returns `S_OK` if no more moves are possible or `S_FALSE` if more defragmentations are possible.804805Ends incremental defragmentation pass and commits all defragmentation moves from `pPassInfo`.806After this call:807808- %Allocation at `pPassInfo[i].pSrcAllocation` that had `pPassInfo[i].Operation ==` #DEFRAGMENTATION_MOVE_OPERATION_COPY809(which is the default) will be pointing to the new destination place.810- %Allocation at `pPassInfo[i].pSrcAllocation` that had `pPassInfo[i].operation ==` #DEFRAGMENTATION_MOVE_OPERATION_DESTROY811will be released.812813If no more moves are possible you can end whole defragmentation.814*/815HRESULT EndPass(DEFRAGMENTATION_PASS_MOVE_INFO* pPassInfo);816/** \brief Returns statistics of the defragmentation performed so far.817*/818void GetStats(DEFRAGMENTATION_STATS* pStats);819820protected:821void ReleaseThis() override;822823private:824friend class Pool;825friend class Allocator;826template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);827828DefragmentationContextPimpl* m_Pimpl;829830DefragmentationContext(AllocatorPimpl* allocator,831const DEFRAGMENTATION_DESC& desc,832BlockVector* poolVector);833~DefragmentationContext();834835D3D12MA_CLASS_NO_COPY(DefragmentationContext)836};837838/// \brief Bit flags to be used with POOL_DESC::Flags.839enum POOL_FLAGS840{841/// Zero842POOL_FLAG_NONE = 0,843844/** \brief Enables alternative, linear allocation algorithm in this pool.845846Specify this flag to enable linear allocation algorithm, which always creates847new allocations after last one and doesn't reuse space from allocations freed in848between. It trades memory consumption for simplified algorithm and data849structure, which has better performance and uses less memory for metadata.850851By using this flag, you can achieve behavior of free-at-once, stack,852ring buffer, and double stack.853For details, see documentation chapter \ref linear_algorithm.854*/855POOL_FLAG_ALGORITHM_LINEAR = 0x1,856857/** \brief Optimization, allocate MSAA textures as committed resources always.858859Specify this flag to create MSAA textures with implicit heaps, as if they were created860with flag D3D12MA::ALLOCATION_FLAG_COMMITTED. Usage of this flags enables pool to create its heaps861on smaller alignment not suitable for MSAA textures.862*/863POOL_FLAG_MSAA_TEXTURES_ALWAYS_COMMITTED = 0x2,864865// Bit mask to extract only `ALGORITHM` bits from entire set of flags.866POOL_FLAG_ALGORITHM_MASK = POOL_FLAG_ALGORITHM_LINEAR867};868869/// \brief Parameters of created D3D12MA::Pool object. To be used with D3D12MA::Allocator::CreatePool.870struct POOL_DESC871{872/// Flags.873POOL_FLAGS Flags;874/** \brief The parameters of memory heap where allocations of this pool should be placed.875876In the simplest case, just fill it with zeros and set `Type` to one of: `D3D12_HEAP_TYPE_DEFAULT`,877`D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`. Additional parameters can be used e.g. to utilize UMA.878*/879D3D12_HEAP_PROPERTIES HeapProperties;880/** \brief Heap flags to be used when allocating heaps of this pool.881882It should contain one of these values, depending on type of resources you are going to create in this heap:883`D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS`,884`D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES`,885`D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES`.886Except if ResourceHeapTier = 2, then it may be `D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES` = 0.887888You can specify additional flags if needed.889*/890D3D12_HEAP_FLAGS HeapFlags;891/** \brief Size of a single heap (memory block) to be allocated as part of this pool, in bytes. Optional.892893Specify nonzero to set explicit, constant size of memory blocks used by this pool.894Leave 0 to use default and let the library manage block sizes automatically.895Then sizes of particular blocks may vary.896*/897UINT64 BlockSize;898/** \brief Minimum number of heaps (memory blocks) to be always allocated in this pool, even if they stay empty. Optional.899900Set to 0 to have no preallocated blocks and allow the pool be completely empty.901*/902UINT MinBlockCount;903/** \brief Maximum number of heaps (memory blocks) that can be allocated in this pool. Optional.904905Set to 0 to use default, which is `UINT64_MAX`, which means no limit.906907Set to same value as D3D12MA::POOL_DESC::MinBlockCount to have fixed amount of memory allocated908throughout whole lifetime of this pool.909*/910UINT MaxBlockCount;911/** \brief Additional minimum alignment to be used for all allocations created from this pool. Can be 0.912913Leave 0 (default) not to impose any additional alignment. If not 0, it must be a power of two.914*/915UINT64 MinAllocationAlignment;916/** \brief Additional parameter allowing pool to create resources with passed protected session.917918If not null then all the heaps and committed resources will be created with this parameter.919Valid only if ID3D12Device4 interface is present in current Windows SDK!920*/921ID3D12ProtectedResourceSession* pProtectedSession;922/** \brief Residency priority to be set for all allocations made in this pool. Optional.923924Set this parameter to one of the possible enum values e.g. `D3D12_RESIDENCY_PRIORITY_HIGH`925to apply specific residency priority to all allocations made in this pool:926`ID3D12Heap` memory blocks used to sub-allocate for placed resources, as well as927committed resources or heaps created when D3D12MA::ALLOCATION_FLAG_COMMITTED is used.928This can increase/decrease chance that the memory will be pushed out from VRAM929to system RAM when the system runs out of memory, which is invisible to the developer930using D3D12 API while it can degrade performance.931932Priority is set using function `ID3D12Device1::SetResidencyPriority`.933It is performed only when `ID3D12Device1` interface is defined and successfully obtained.934Otherwise, this parameter is ignored.935936This parameter is optional. If you set it to `D3D12_RESIDENCY_PRIORITY(0)`,937residency priority will not be set for allocations made in this pool.938939There is no equivalent parameter for allocations made in default pools.940If you want to set residency priority for such allocation, you need to do it manually:941allocate with D3D12MA::ALLOCATION_FLAG_COMMITTED and call942`ID3D12Device1::SetResidencyPriority`, passing `allocation->GetResource()`.943*/944D3D12_RESIDENCY_PRIORITY ResidencyPriority;945};946947/** \brief Custom memory pool948949Represents a separate set of heaps (memory blocks) that can be used to create950D3D12MA::Allocation-s and resources in it. Usually there is no need to create custom951pools - creating resources in default pool is sufficient.952953To create custom pool, fill D3D12MA::POOL_DESC and call D3D12MA::Allocator::CreatePool.954*/955class D3D12MA_API Pool : public IUnknownImpl956{957public:958/** \brief Returns copy of parameters of the pool.959960These are the same parameters as passed to D3D12MA::Allocator::CreatePool.961*/962POOL_DESC GetDesc() const;963964/** \brief Retrieves basic statistics of the custom pool that are fast to calculate.965966\param[out] pStats %Statistics of the current pool.967*/968void GetStatistics(Statistics* pStats);969970/** \brief Retrieves detailed statistics of the custom pool that are slower to calculate.971972\param[out] pStats %Statistics of the current pool.973*/974void CalculateStatistics(DetailedStatistics* pStats);975976/** \brief Associates a name with the pool. This name is for use in debug diagnostics and tools.977978Internal copy of the string is made, so the memory pointed by the argument can be979changed of freed immediately after this call.980981`Name` can be NULL.982*/983void SetName(LPCWSTR Name);984985/** \brief Returns the name associated with the pool object.986987Returned string points to an internal copy.988989If no name was associated with the allocation, returns NULL.990*/991LPCWSTR GetName() const;992993/** \brief Begins defragmentation process of the current pool.994995\param pDesc Structure filled with parameters of defragmentation.996\param[out] ppContext Context object that will manage defragmentation.997\returns998- `S_OK` if defragmentation can begin.999- `E_NOINTERFACE` if defragmentation is not supported.10001001For more information about defragmentation, see documentation chapter:1002[Defragmentation](@ref defragmentation).1003*/1004HRESULT BeginDefragmentation(const DEFRAGMENTATION_DESC* pDesc, DefragmentationContext** ppContext);10051006protected:1007void ReleaseThis() override;10081009private:1010friend class Allocator;1011friend class AllocatorPimpl;1012template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);10131014PoolPimpl* m_Pimpl;10151016Pool(Allocator* allocator, const POOL_DESC &desc);1017~Pool();10181019D3D12MA_CLASS_NO_COPY(Pool)1020};102110221023/// \brief Bit flags to be used with ALLOCATOR_DESC::Flags.1024enum ALLOCATOR_FLAGS1025{1026/// Zero1027ALLOCATOR_FLAG_NONE = 0,10281029/**1030Allocator and all objects created from it will not be synchronized internally,1031so you must guarantee they are used from only one thread at a time or1032synchronized by you.10331034Using this flag may increase performance because internal mutexes are not used.1035*/1036ALLOCATOR_FLAG_SINGLETHREADED = 0x1,10371038/**1039Every allocation will have its own memory block.1040To be used for debugging purposes.1041*/1042ALLOCATOR_FLAG_ALWAYS_COMMITTED = 0x2,10431044/**1045Heaps created for the default pools will be created with flag `D3D12_HEAP_FLAG_CREATE_NOT_ZEROED`,1046allowing for their memory to be not zeroed by the system if possible,1047which can speed up allocation.10481049Only affects default pools.1050To use the flag with @ref custom_pools, you need to add it manually:10511052\code1053poolDesc.heapFlags |= D3D12_HEAP_FLAG_CREATE_NOT_ZEROED;1054\endcode10551056Only avaiable if `ID3D12Device8` is present. Otherwise, the flag is ignored.1057*/1058ALLOCATOR_FLAG_DEFAULT_POOLS_NOT_ZEROED = 0x4,10591060/** \brief Optimization, allocate MSAA textures as committed resources always.10611062Specify this flag to create MSAA textures with implicit heaps, as if they were created1063with flag D3D12MA::ALLOCATION_FLAG_COMMITTED. Usage of this flags enables all default pools1064to create its heaps on smaller alignment not suitable for MSAA textures.1065*/1066ALLOCATOR_FLAG_MSAA_TEXTURES_ALWAYS_COMMITTED = 0x8,1067};10681069/// \brief Parameters of created Allocator object. To be used with CreateAllocator().1070struct ALLOCATOR_DESC1071{1072/// Flags.1073ALLOCATOR_FLAGS Flags;10741075/** Direct3D device object that the allocator should be attached to.10761077Allocator is doing `AddRef`/`Release` on this object.1078*/1079ID3D12Device* pDevice;10801081/** \brief Preferred size of a single `ID3D12Heap` block to be allocated.10821083Set to 0 to use default, which is currently 64 MiB.1084*/1085UINT64 PreferredBlockSize;10861087/** \brief Custom CPU memory allocation callbacks. Optional.10881089Optional, can be null. When specified, will be used for all CPU-side memory allocations.1090*/1091const ALLOCATION_CALLBACKS* pAllocationCallbacks;10921093/** DXGI Adapter object that you use for D3D12 and this allocator.10941095Allocator is doing `AddRef`/`Release` on this object.1096*/1097IDXGIAdapter* pAdapter;1098};10991100/**1101\brief Represents main object of this library initialized for particular `ID3D12Device`.11021103Fill structure D3D12MA::ALLOCATOR_DESC and call function CreateAllocator() to create it.1104Call method `Release()` to destroy it.11051106It is recommended to create just one object of this type per `ID3D12Device` object,1107right after Direct3D 12 is initialized and keep it alive until before Direct3D device is destroyed.1108*/1109class D3D12MA_API Allocator : public IUnknownImpl1110{1111public:1112/// Returns cached options retrieved from D3D12 device.1113const D3D12_FEATURE_DATA_D3D12_OPTIONS& GetD3D12Options() const;1114/** \brief Returns true if `D3D12_FEATURE_DATA_ARCHITECTURE1::UMA` was found to be true.11151116For more information about how to use it, see articles in Microsoft Docs articles:11171118- "UMA Optimizations: CPU Accessible Textures and Standard Swizzle"1119- "D3D12_FEATURE_DATA_ARCHITECTURE structure (d3d12.h)"1120- "ID3D12Device::GetCustomHeapProperties method (d3d12.h)"1121*/1122BOOL IsUMA() const;1123/** \brief Returns true if `D3D12_FEATURE_DATA_ARCHITECTURE1::CacheCoherentUMA` was found to be true.11241125For more information about how to use it, see articles in Microsoft Docs articles:11261127- "UMA Optimizations: CPU Accessible Textures and Standard Swizzle"1128- "D3D12_FEATURE_DATA_ARCHITECTURE structure (d3d12.h)"1129- "ID3D12Device::GetCustomHeapProperties method (d3d12.h)"1130*/1131BOOL IsCacheCoherentUMA() const;1132/** \brief Returns total amount of memory of specific segment group, in bytes.11331134\param memorySegmentGroup use `DXGI_MEMORY_SEGMENT_GROUP_LOCAL` or DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL`.11351136This information is taken from `DXGI_ADAPTER_DESC`.1137It is not recommended to use this number.1138You should preferably call GetBudget() and limit memory usage to D3D12MA::Budget::BudgetBytes instead.11391140- When IsUMA() `== FALSE` (discrete graphics card):1141- `GetMemoryCapacity(DXGI_MEMORY_SEGMENT_GROUP_LOCAL)` returns the size of the video memory.1142- `GetMemoryCapacity(DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)` returns the size of the system memory available for D3D12 resources.1143- When IsUMA() `== TRUE` (integrated graphics chip):1144- `GetMemoryCapacity(DXGI_MEMORY_SEGMENT_GROUP_LOCAL)` returns the size of the shared memory available for all D3D12 resources.1145All memory is considered "local".1146- `GetMemoryCapacity(DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)` is not applicable and returns 0.1147*/1148UINT64 GetMemoryCapacity(UINT memorySegmentGroup) const;11491150/** \brief Allocates memory and creates a D3D12 resource (buffer or texture). This is the main allocation function.11511152The function is similar to `ID3D12Device::CreateCommittedResource`, but it may1153really call `ID3D12Device::CreatePlacedResource` to assign part of a larger,1154existing memory heap to the new resource, which is the main purpose of this1155whole library.11561157If `ppvResource` is null, you receive only `ppAllocation` object from this function.1158It holds pointer to `ID3D12Resource` that can be queried using function D3D12MA::Allocation::GetResource().1159Reference count of the resource object is 1.1160It is automatically destroyed when you destroy the allocation object.11611162If `ppvResource` is not null, you receive pointer to the resource next to allocation object.1163Reference count of the resource object is then increased by calling `QueryInterface`, so you need to manually `Release` it1164along with the allocation.11651166\param pAllocDesc Parameters of the allocation.1167\param pResourceDesc Description of created resource.1168\param InitialResourceState Initial resource state.1169\param pOptimizedClearValue Optional. Either null or optimized clear value.1170\param[out] ppAllocation Filled with pointer to new allocation object created.1171\param riidResource IID of a resource to be returned via `ppvResource`.1172\param[out] ppvResource Optional. If not null, filled with pointer to new resouce created.11731174\note This function creates a new resource. Sub-allocation of parts of one large buffer,1175although recommended as a good practice, is out of scope of this library and could be implemented1176by the user as a higher-level logic on top of it, e.g. using the \ref virtual_allocator feature.1177*/1178HRESULT CreateResource(1179const ALLOCATION_DESC* pAllocDesc,1180const D3D12_RESOURCE_DESC* pResourceDesc,1181D3D12_RESOURCE_STATES InitialResourceState,1182const D3D12_CLEAR_VALUE *pOptimizedClearValue,1183Allocation** ppAllocation,1184REFIID riidResource,1185void** ppvResource);11861187#ifdef __ID3D12Device8_INTERFACE_DEFINED__1188/** \brief Similar to Allocator::CreateResource, but supports new structure `D3D12_RESOURCE_DESC1`.11891190It internally uses `ID3D12Device8::CreateCommittedResource2` or `ID3D12Device8::CreatePlacedResource1`.11911192To work correctly, `ID3D12Device8` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.1193*/1194HRESULT CreateResource2(1195const ALLOCATION_DESC* pAllocDesc,1196const D3D12_RESOURCE_DESC1* pResourceDesc,1197D3D12_RESOURCE_STATES InitialResourceState,1198const D3D12_CLEAR_VALUE *pOptimizedClearValue,1199Allocation** ppAllocation,1200REFIID riidResource,1201void** ppvResource);1202#endif // #ifdef __ID3D12Device8_INTERFACE_DEFINED__12031204#ifdef __ID3D12Device10_INTERFACE_DEFINED__1205/** \brief Similar to Allocator::CreateResource2, but there are initial layout instead of state and1206castable formats list12071208It internally uses `ID3D12Device10::CreateCommittedResource3` or `ID3D12Device10::CreatePlacedResource2`.12091210To work correctly, `ID3D12Device10` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.1211*/1212HRESULT CreateResource3(const ALLOCATION_DESC* pAllocDesc,1213const D3D12_RESOURCE_DESC1* pResourceDesc,1214D3D12_BARRIER_LAYOUT InitialLayout,1215const D3D12_CLEAR_VALUE* pOptimizedClearValue,1216UINT32 NumCastableFormats,1217DXGI_FORMAT* pCastableFormats,1218Allocation** ppAllocation,1219REFIID riidResource,1220void** ppvResource);1221#endif // #ifdef __ID3D12Device10_INTERFACE_DEFINED__12221223/** \brief Allocates memory without creating any resource placed in it.12241225This function is similar to `ID3D12Device::CreateHeap`, but it may really assign1226part of a larger, existing heap to the allocation.12271228`pAllocDesc->heapFlags` should contain one of these values, depending on type of resources you are going to create in this memory:1229`D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS`,1230`D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES`,1231`D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES`.1232Except if you validate that ResourceHeapTier = 2 - then `heapFlags`1233may be `D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES` = 0.1234Additional flags in `heapFlags` are allowed as well.12351236`pAllocInfo->SizeInBytes` must be multiply of 64KB.1237`pAllocInfo->Alignment` must be one of the legal values as described in documentation of `D3D12_HEAP_DESC`.12381239If you use D3D12MA::ALLOCATION_FLAG_COMMITTED you will get a separate memory block -1240a heap that always has offset 0.1241*/1242HRESULT AllocateMemory(1243const ALLOCATION_DESC* pAllocDesc,1244const D3D12_RESOURCE_ALLOCATION_INFO* pAllocInfo,1245Allocation** ppAllocation);12461247/** \brief Creates a new resource in place of an existing allocation. This is useful for memory aliasing.12481249\param pAllocation Existing allocation indicating the memory where the new resource should be created.1250It can be created using D3D12MA::Allocator::CreateResource and already have a resource bound to it,1251or can be a raw memory allocated with D3D12MA::Allocator::AllocateMemory.1252It must not be created as committed so that `ID3D12Heap` is available and not implicit.1253\param AllocationLocalOffset Additional offset in bytes to be applied when allocating the resource.1254Local from the start of `pAllocation`, not the beginning of the whole `ID3D12Heap`!1255If the new resource should start from the beginning of the `pAllocation` it should be 0.1256\param pResourceDesc Description of the new resource to be created.1257\param InitialResourceState1258\param pOptimizedClearValue1259\param riidResource1260\param[out] ppvResource Returns pointer to the new resource.1261The resource is not bound with `pAllocation`.1262This pointer must not be null - you must get the resource pointer and `Release` it when no longer needed.12631264Memory requirements of the new resource are checked for validation.1265If its size exceeds the end of `pAllocation` or required alignment is not fulfilled1266considering `pAllocation->GetOffset() + AllocationLocalOffset`, the function1267returns `E_INVALIDARG`.1268*/1269HRESULT CreateAliasingResource(1270Allocation* pAllocation,1271UINT64 AllocationLocalOffset,1272const D3D12_RESOURCE_DESC* pResourceDesc,1273D3D12_RESOURCE_STATES InitialResourceState,1274const D3D12_CLEAR_VALUE *pOptimizedClearValue,1275REFIID riidResource,1276void** ppvResource);12771278#ifdef __ID3D12Device8_INTERFACE_DEFINED__1279/** \brief Similar to Allocator::CreateAliasingResource, but supports new structure `D3D12_RESOURCE_DESC1`.12801281It internally uses `ID3D12Device8::CreatePlacedResource1`.12821283To work correctly, `ID3D12Device8` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.1284*/1285HRESULT CreateAliasingResource1(Allocation* pAllocation,1286UINT64 AllocationLocalOffset,1287const D3D12_RESOURCE_DESC1* pResourceDesc,1288D3D12_RESOURCE_STATES InitialResourceState,1289const D3D12_CLEAR_VALUE* pOptimizedClearValue,1290REFIID riidResource,1291void** ppvResource);1292#endif // #ifdef __ID3D12Device8_INTERFACE_DEFINED__12931294#ifdef __ID3D12Device10_INTERFACE_DEFINED__1295/** \brief Similar to Allocator::CreateAliasingResource1, but there are initial layout instead of state and1296castable formats list12971298It internally uses `ID3D12Device10::CreatePlacedResource2`.12991300To work correctly, `ID3D12Device10` interface must be available in the current system. Otherwise, `E_NOINTERFACE` is returned.1301*/1302HRESULT CreateAliasingResource2(Allocation* pAllocation,1303UINT64 AllocationLocalOffset,1304const D3D12_RESOURCE_DESC1* pResourceDesc,1305D3D12_BARRIER_LAYOUT InitialLayout,1306const D3D12_CLEAR_VALUE* pOptimizedClearValue,1307UINT32 NumCastableFormats,1308DXGI_FORMAT* pCastableFormats,1309REFIID riidResource,1310void** ppvResource);1311#endif // #ifdef __ID3D12Device10_INTERFACE_DEFINED__13121313/** \brief Creates custom pool.1314*/1315HRESULT CreatePool(1316const POOL_DESC* pPoolDesc,1317Pool** ppPool);13181319/** \brief Sets the index of the current frame.13201321This function is used to set the frame index in the allocator when a new game frame begins.1322*/1323void SetCurrentFrameIndex(UINT frameIndex);13241325/** \brief Retrieves information about current memory usage and budget.13261327\param[out] pLocalBudget Optional, can be null.1328\param[out] pNonLocalBudget Optional, can be null.13291330- When IsUMA() `== FALSE` (discrete graphics card):1331- `pLocalBudget` returns the budget of the video memory.1332- `pNonLocalBudget` returns the budget of the system memory available for D3D12 resources.1333- When IsUMA() `== TRUE` (integrated graphics chip):1334- `pLocalBudget` returns the budget of the shared memory available for all D3D12 resources.1335All memory is considered "local".1336- `pNonLocalBudget` is not applicable and returns zeros.13371338This function is called "get" not "calculate" because it is very fast, suitable to be called1339every frame or every allocation. For more detailed statistics use CalculateStatistics().13401341Note that when using allocator from multiple threads, returned information may immediately1342become outdated.1343*/1344void GetBudget(Budget* pLocalBudget, Budget* pNonLocalBudget);13451346/** \brief Retrieves statistics from current state of the allocator.13471348This function is called "calculate" not "get" because it has to traverse all1349internal data structures, so it may be quite slow. Use it for debugging purposes.1350For faster but more brief statistics suitable to be called every frame or every allocation,1351use GetBudget().13521353Note that when using allocator from multiple threads, returned information may immediately1354become outdated.1355*/1356void CalculateStatistics(TotalStatistics* pStats);13571358/** \brief Builds and returns statistics as a string in JSON format.1359*1360@param[out] ppStatsString Must be freed using Allocator::FreeStatsString.1361@param DetailedMap `TRUE` to include full list of allocations (can make the string quite long), `FALSE` to only return statistics.1362*/1363void BuildStatsString(WCHAR** ppStatsString, BOOL DetailedMap) const;13641365/// Frees memory of a string returned from Allocator::BuildStatsString.1366void FreeStatsString(WCHAR* pStatsString) const;13671368/** \brief Begins defragmentation process of the default pools.13691370\param pDesc Structure filled with parameters of defragmentation.1371\param[out] ppContext Context object that will manage defragmentation.13721373For more information about defragmentation, see documentation chapter:1374[Defragmentation](@ref defragmentation).1375*/1376void BeginDefragmentation(const DEFRAGMENTATION_DESC* pDesc, DefragmentationContext** ppContext);13771378protected:1379void ReleaseThis() override;13801381private:1382friend D3D12MA_API HRESULT CreateAllocator(const ALLOCATOR_DESC*, Allocator**);1383template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);1384friend class DefragmentationContext;1385friend class Pool;13861387Allocator(const ALLOCATION_CALLBACKS& allocationCallbacks, const ALLOCATOR_DESC& desc);1388~Allocator();13891390AllocatorPimpl* m_Pimpl;13911392D3D12MA_CLASS_NO_COPY(Allocator)1393};139413951396/// \brief Bit flags to be used with VIRTUAL_BLOCK_DESC::Flags.1397enum VIRTUAL_BLOCK_FLAGS1398{1399/// Zero1400VIRTUAL_BLOCK_FLAG_NONE = 0,14011402/** \brief Enables alternative, linear allocation algorithm in this virtual block.14031404Specify this flag to enable linear allocation algorithm, which always creates1405new allocations after last one and doesn't reuse space from allocations freed in1406between. It trades memory consumption for simplified algorithm and data1407structure, which has better performance and uses less memory for metadata.14081409By using this flag, you can achieve behavior of free-at-once, stack,1410ring buffer, and double stack.1411For details, see documentation chapter \ref linear_algorithm.1412*/1413VIRTUAL_BLOCK_FLAG_ALGORITHM_LINEAR = POOL_FLAG_ALGORITHM_LINEAR,14141415// Bit mask to extract only `ALGORITHM` bits from entire set of flags.1416VIRTUAL_BLOCK_FLAG_ALGORITHM_MASK = POOL_FLAG_ALGORITHM_MASK1417};14181419/// Parameters of created D3D12MA::VirtualBlock object to be passed to CreateVirtualBlock().1420struct VIRTUAL_BLOCK_DESC1421{1422/// Flags.1423VIRTUAL_BLOCK_FLAGS Flags;1424/** \brief Total size of the block.14251426Sizes can be expressed in bytes or any units you want as long as you are consistent in using them.1427For example, if you allocate from some array of structures, 1 can mean single instance of entire structure.1428*/1429UINT64 Size;1430/** \brief Custom CPU memory allocation callbacks. Optional.14311432Optional, can be null. When specified, will be used for all CPU-side memory allocations.1433*/1434const ALLOCATION_CALLBACKS* pAllocationCallbacks;1435};14361437/// \brief Bit flags to be used with VIRTUAL_ALLOCATION_DESC::Flags.1438enum VIRTUAL_ALLOCATION_FLAGS1439{1440/// Zero1441VIRTUAL_ALLOCATION_FLAG_NONE = 0,14421443/** \brief Allocation will be created from upper stack in a double stack pool.14441445This flag is only allowed for virtual blocks created with #VIRTUAL_BLOCK_FLAG_ALGORITHM_LINEAR flag.1446*/1447VIRTUAL_ALLOCATION_FLAG_UPPER_ADDRESS = ALLOCATION_FLAG_UPPER_ADDRESS,14481449/// Allocation strategy that tries to minimize memory usage.1450VIRTUAL_ALLOCATION_FLAG_STRATEGY_MIN_MEMORY = ALLOCATION_FLAG_STRATEGY_MIN_MEMORY,1451/// Allocation strategy that tries to minimize allocation time.1452VIRTUAL_ALLOCATION_FLAG_STRATEGY_MIN_TIME = ALLOCATION_FLAG_STRATEGY_MIN_TIME,1453/** \brief Allocation strategy that chooses always the lowest offset in available space.1454This is not the most efficient strategy but achieves highly packed data.1455*/1456VIRTUAL_ALLOCATION_FLAG_STRATEGY_MIN_OFFSET = ALLOCATION_FLAG_STRATEGY_MIN_OFFSET,1457/** \brief A bit mask to extract only `STRATEGY` bits from entire set of flags.14581459These strategy flags are binary compatible with equivalent flags in #ALLOCATION_FLAGS.1460*/1461VIRTUAL_ALLOCATION_FLAG_STRATEGY_MASK = ALLOCATION_FLAG_STRATEGY_MASK,1462};14631464/// Parameters of created virtual allocation to be passed to VirtualBlock::Allocate().1465struct VIRTUAL_ALLOCATION_DESC1466{1467/// Flags.1468VIRTUAL_ALLOCATION_FLAGS Flags;1469/** \brief Size of the allocation.14701471Cannot be zero.1472*/1473UINT64 Size;1474/** \brief Required alignment of the allocation.14751476Must 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.1477*/1478UINT64 Alignment;1479/** \brief Custom pointer to be associated with the allocation.14801481It can be fetched or changed later.1482*/1483void* pPrivateData;1484};14851486/// Parameters of an existing virtual allocation, returned by VirtualBlock::GetAllocationInfo().1487struct VIRTUAL_ALLOCATION_INFO1488{1489/// \brief Offset of the allocation.1490UINT64 Offset;1491/** \brief Size of the allocation.14921493Same value as passed in VIRTUAL_ALLOCATION_DESC::Size.1494*/1495UINT64 Size;1496/** \brief Custom pointer associated with the allocation.14971498Same value as passed in VIRTUAL_ALLOCATION_DESC::pPrivateData or VirtualBlock::SetAllocationPrivateData().1499*/1500void* pPrivateData;1501};15021503/** \brief Represents pure allocation algorithm and a data structure with allocations in some memory block, without actually allocating any GPU memory.15041505This class allows to use the core algorithm of the library custom allocations e.g. CPU memory or1506sub-allocation regions inside a single GPU buffer.15071508To create this object, fill in D3D12MA::VIRTUAL_BLOCK_DESC and call CreateVirtualBlock().1509To destroy it, call its method `VirtualBlock::Release()`.1510You need to free all the allocations within this block or call Clear() before destroying it.15111512This object is not thread-safe - should not be used from multiple threads simultaneously, must be synchronized externally.1513*/1514class D3D12MA_API VirtualBlock : public IUnknownImpl1515{1516public:1517/** \brief Returns true if the block is empty - contains 0 allocations.1518*/1519BOOL IsEmpty() const;1520/** \brief Returns information about an allocation - its offset, size and custom pointer.1521*/1522void GetAllocationInfo(VirtualAllocation allocation, VIRTUAL_ALLOCATION_INFO* pInfo) const;15231524/** \brief Creates new allocation.1525\param pDesc1526\param[out] pAllocation Unique indentifier of the new allocation within single block.1527\param[out] pOffset Returned offset of the new allocation. Optional, can be null.1528\return `S_OK` if allocation succeeded, `E_OUTOFMEMORY` if it failed.15291530If the allocation failed, `pAllocation->AllocHandle` is set to 0 and `pOffset`, if not null, is set to `UINT64_MAX`.1531*/1532HRESULT Allocate(const VIRTUAL_ALLOCATION_DESC* pDesc, VirtualAllocation* pAllocation, UINT64* pOffset);1533/** \brief Frees the allocation.15341535Calling this function with `allocation.AllocHandle == 0` is correct and does nothing.1536*/1537void FreeAllocation(VirtualAllocation allocation);1538/** \brief Frees all the allocations.1539*/1540void Clear();1541/** \brief Changes custom pointer for an allocation to a new value.1542*/1543void SetAllocationPrivateData(VirtualAllocation allocation, void* pPrivateData);1544/** \brief Retrieves basic statistics of the virtual block that are fast to calculate.15451546\param[out] pStats %Statistics of the virtual block.1547*/1548void GetStatistics(Statistics* pStats) const;1549/** \brief Retrieves detailed statistics of the virtual block that are slower to calculate.15501551\param[out] pStats %Statistics of the virtual block.1552*/1553void CalculateStatistics(DetailedStatistics* pStats) const;15541555/** \brief Builds and returns statistics as a string in JSON format, including the list of allocations with their parameters.1556@param[out] ppStatsString Must be freed using VirtualBlock::FreeStatsString.1557*/1558void BuildStatsString(WCHAR** ppStatsString) const;15591560/** \brief Frees memory of a string returned from VirtualBlock::BuildStatsString.1561*/1562void FreeStatsString(WCHAR* pStatsString) const;15631564protected:1565void ReleaseThis() override;15661567private:1568friend D3D12MA_API HRESULT CreateVirtualBlock(const VIRTUAL_BLOCK_DESC*, VirtualBlock**);1569template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);15701571VirtualBlockPimpl* m_Pimpl;15721573VirtualBlock(const ALLOCATION_CALLBACKS& allocationCallbacks, const VIRTUAL_BLOCK_DESC& desc);1574~VirtualBlock();15751576D3D12MA_CLASS_NO_COPY(VirtualBlock)1577};157815791580/** \brief Creates new main D3D12MA::Allocator object and returns it through `ppAllocator`.15811582You normally only need to call it once and keep a single Allocator object for your `ID3D12Device`.1583*/1584D3D12MA_API HRESULT CreateAllocator(const ALLOCATOR_DESC* pDesc, Allocator** ppAllocator);15851586/** \brief Creates new D3D12MA::VirtualBlock object and returns it through `ppVirtualBlock`.15871588Note you don't need to create D3D12MA::Allocator to use virtual blocks.1589*/1590D3D12MA_API HRESULT CreateVirtualBlock(const VIRTUAL_BLOCK_DESC* pDesc, VirtualBlock** ppVirtualBlock);15911592} // namespace D3D12MA15931594/// \cond INTERNAL1595DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::ALLOCATION_FLAGS);1596DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::DEFRAGMENTATION_FLAGS);1597DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::ALLOCATOR_FLAGS);1598DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::POOL_FLAGS);1599DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::VIRTUAL_BLOCK_FLAGS);1600DEFINE_ENUM_FLAG_OPERATORS(D3D12MA::VIRTUAL_ALLOCATION_FLAGS);1601/// \endcond16021603/**1604\page quick_start Quick start16051606\section quick_start_project_setup Project setup and initialization16071608This is a small, standalone C++ library. It consists of a pair of 2 files:1609"D3D12MemAlloc.h" header file with public interface and "D3D12MemAlloc.cpp" with1610internal implementation. The only external dependencies are WinAPI, Direct3D 12,1611and parts of C/C++ standard library (but STL containers, exceptions, or RTTI are1612not used).16131614The library is developed and tested using Microsoft Visual Studio 2019, but it1615should work with other compilers as well. It is designed for 64-bit code.16161617To use the library in your project:16181619(1.) Copy files `D3D12MemAlloc.cpp`, `%D3D12MemAlloc.h` to your project.16201621(2.) Make `D3D12MemAlloc.cpp` compiling as part of the project, as C++ code.16221623(3.) Include library header in each CPP file that needs to use the library.16241625\code1626#include "D3D12MemAlloc.h"1627\endcode16281629(4.) Right after you created `ID3D12Device`, fill D3D12MA::ALLOCATOR_DESC1630structure and call function D3D12MA::CreateAllocator to create the main1631D3D12MA::Allocator object.16321633Please note that all symbols of the library are declared inside #D3D12MA namespace.16341635\code1636IDXGIAdapter* adapter = (...)1637ID3D12Device* device = (...)16381639D3D12MA::ALLOCATOR_DESC allocatorDesc = {};1640allocatorDesc.pDevice = device;1641allocatorDesc.pAdapter = adapter;16421643D3D12MA::Allocator* allocator;1644HRESULT hr = D3D12MA::CreateAllocator(&allocatorDesc, &allocator);1645\endcode16461647(5.) Right before destroying the D3D12 device, destroy the allocator object.16481649Objects of this library must be destroyed by calling `Release` method.1650They are somewhat compatible with COM: they implement `IUnknown` interface with its virtual methods: `AddRef`, `Release`, `QueryInterface`,1651and they are reference-counted internally.1652You can use smart pointers designed for COM with objects of this library - e.g. `CComPtr` or `Microsoft::WRL::ComPtr`.1653The reference counter is thread-safe.1654`QueryInterface` method supports only `IUnknown`, as classes of this library don't define their own GUIDs.16551656\code1657allocator->Release();1658\endcode165916601661\section quick_start_creating_resources Creating resources16621663To use the library for creating resources (textures and buffers), call method1664D3D12MA::Allocator::CreateResource in the place where you would previously call1665`ID3D12Device::CreateCommittedResource`.16661667The function has similar syntax, but it expects structure D3D12MA::ALLOCATION_DESC1668to be passed along with `D3D12_RESOURCE_DESC` and other parameters for created1669resource. This structure describes parameters of the desired memory allocation,1670including choice of `D3D12_HEAP_TYPE`.16711672The function returns a new object of type D3D12MA::Allocation.1673It represents allocated memory and can be queried for size, offset, `ID3D12Heap`.1674It also holds a reference to the `ID3D12Resource`, which can be accessed by calling D3D12MA::Allocation::GetResource().16751676\code1677D3D12_RESOURCE_DESC resourceDesc = {};1678resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;1679resourceDesc.Alignment = 0;1680resourceDesc.Width = 1024;1681resourceDesc.Height = 1024;1682resourceDesc.DepthOrArraySize = 1;1683resourceDesc.MipLevels = 1;1684resourceDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;1685resourceDesc.SampleDesc.Count = 1;1686resourceDesc.SampleDesc.Quality = 0;1687resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;1688resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;16891690D3D12MA::ALLOCATION_DESC allocationDesc = {};1691allocationDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;16921693D3D12MA::Allocation* allocation;1694HRESULT hr = allocator->CreateResource(1695&allocationDesc,1696&resourceDesc,1697D3D12_RESOURCE_STATE_COPY_DEST,1698NULL,1699&allocation,1700IID_NULL, NULL);17011702// Use allocation->GetResource()...1703\endcode17041705You need to release the allocation object when no longer needed.1706This will also release the D3D12 resource.17071708\code1709allocation->Release();1710\endcode17111712The advantage of using the allocator instead of creating committed resource, and1713the main purpose of this library, is that it can decide to allocate bigger memory1714heap internally using `ID3D12Device::CreateHeap` and place multiple resources in1715it, at different offsets, using `ID3D12Device::CreatePlacedResource`. The library1716manages its own collection of allocated memory blocks (heaps) and remembers which1717parts of them are occupied and which parts are free to be used for new resources.17181719It is important to remember that resources created as placed don't have their memory1720initialized to zeros, but may contain garbage data, so they need to be fully initialized1721before usage, e.g. using Clear (`ClearRenderTargetView`), Discard (`DiscardResource`),1722or copy (`CopyResource`).17231724The library also automatically handles resource heap tier.1725When `D3D12_FEATURE_DATA_D3D12_OPTIONS::ResourceHeapTier` equals `D3D12_RESOURCE_HEAP_TIER_1`,1726resources of 3 types: buffers, textures that are render targets or depth-stencil,1727and other textures must be kept in separate heaps. When `D3D12_RESOURCE_HEAP_TIER_2`,1728they can be kept together. By using this library, you don't need to handle this1729manually.173017311732\section quick_start_resource_reference_counting Resource reference counting17331734`ID3D12Resource` and other interfaces of Direct3D 12 use COM, so they are reference-counted.1735Objects of this library are reference-counted as well.1736An object of type D3D12MA::Allocation remembers the resource (buffer or texture)1737that was created together with this memory allocation1738and holds a reference to the `ID3D12Resource` object.1739(Note this is a difference to Vulkan Memory Allocator, where a `VmaAllocation` object has no connection1740with the buffer or image that was created with it.)1741Thus, it is important to manage the resource reference counter properly.17421743<b>The simplest use case</b> is shown in the code snippet above.1744When only D3D12MA::Allocation object is obtained from a function call like D3D12MA::Allocator::CreateResource,1745it remembers the `ID3D12Resource` that was created with it and holds a reference to it.1746The resource can be obtained by calling `allocation->GetResource()`, which doesn't increment the resource1747reference counter.1748Calling `allocation->Release()` will decrease the resource reference counter, which is = 1 in this case,1749so the resource will be released.17501751<b>Second option</b> is to retrieve a pointer to the resource along with D3D12MA::Allocation.1752Last parameters of the resource creation function can be used for this purpose.17531754\code1755D3D12MA::Allocation* allocation;1756ID3D12Resource* resource;1757HRESULT hr = allocator->CreateResource(1758&allocationDesc,1759&resourceDesc,1760D3D12_RESOURCE_STATE_COPY_DEST,1761NULL,1762&allocation,1763IID_PPV_ARGS(&resource));17641765// Use resource...1766\endcode17671768In this case, returned pointer `resource` is equal to `allocation->GetResource()`,1769but the creation function additionally increases resource reference counter for the purpose of returning it from this call1770(it actually calls `QueryInterface` internally), so the resource will have the counter = 2.1771The resource then need to be released along with the allocation, in this particular order,1772to make sure the resource is destroyed before its memory heap can potentially be freed.17731774\code1775resource->Release();1776allocation->Release();1777\endcode17781779<b>More advanced use cases</b> are possible when we consider that an D3D12MA::Allocation object can just hold1780a reference to any resource.1781It can be changed by calling D3D12MA::Allocation::SetResource. This function1782releases the old resource and calls `AddRef` on the new one.17831784Special care must be taken when performing <b>defragmentation</b>.1785The new resource created at the destination place should be set as `pass.pMoves[i].pDstTmpAllocation->SetResource(newRes)`,1786but it is moved to the source allocation at end of the defragmentation pass,1787while the old resource accessible through `pass.pMoves[i].pSrcAllocation->GetResource()` is then released.1788For more information, see documentation chapter \ref defragmentation.178917901791\section quick_start_mapping_memory Mapping memory17921793The process of getting regular CPU-side pointer to the memory of a resource in1794Direct3D is called "mapping". There are rules and restrictions to this process,1795as described in D3D12 documentation of `ID3D12Resource::Map` method.17961797Mapping happens on the level of particular resources, not entire memory heaps,1798and so it is out of scope of this library. Just as the documentation of the `Map` function says:17991800- Returned pointer refers to data of particular subresource, not entire memory heap.1801- You can map same resource multiple times. It is ref-counted internally.1802- Mapping is thread-safe.1803- Unmapping is not required before resource destruction.1804- Unmapping may not be required before using written data - some heap types on1805some platforms support resources persistently mapped.18061807When using this library, you can map and use your resources normally without1808considering whether they are created as committed resources or placed resources in one large heap.18091810Example for buffer created and filled in `UPLOAD` heap type:18111812\code1813const UINT64 bufSize = 65536;1814const float* bufData = (...);18151816D3D12_RESOURCE_DESC resourceDesc = {};1817resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;1818resourceDesc.Alignment = 0;1819resourceDesc.Width = bufSize;1820resourceDesc.Height = 1;1821resourceDesc.DepthOrArraySize = 1;1822resourceDesc.MipLevels = 1;1823resourceDesc.Format = DXGI_FORMAT_UNKNOWN;1824resourceDesc.SampleDesc.Count = 1;1825resourceDesc.SampleDesc.Quality = 0;1826resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;1827resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;18281829D3D12MA::ALLOCATION_DESC allocationDesc = {};1830allocationDesc.HeapType = D3D12_HEAP_TYPE_UPLOAD;18311832D3D12Resource* resource;1833D3D12MA::Allocation* allocation;1834HRESULT hr = allocator->CreateResource(1835&allocationDesc,1836&resourceDesc,1837D3D12_RESOURCE_STATE_GENERIC_READ,1838NULL,1839&allocation,1840IID_PPV_ARGS(&resource));18411842void* mappedPtr;1843hr = resource->Map(0, NULL, &mappedPtr);18441845memcpy(mappedPtr, bufData, bufSize);18461847resource->Unmap(0, NULL);1848\endcode184918501851\page custom_pools Custom memory pools18521853A "pool" is a collection of memory blocks that share certain properties.1854Allocator creates 3 default pools: for `D3D12_HEAP_TYPE_DEFAULT`, `UPLOAD`, `READBACK`.1855A default pool automatically grows in size. Size of allocated blocks is also variable and managed automatically.1856Typical allocations are created in these pools. You can also create custom pools.18571858\section custom_pools_usage Usage18591860To create a custom pool, fill in structure D3D12MA::POOL_DESC and call function D3D12MA::Allocator::CreatePool1861to obtain object D3D12MA::Pool. Example:18621863\code1864POOL_DESC poolDesc = {};1865poolDesc.HeapProperties.Type = D3D12_HEAP_TYPE_DEFAULT;18661867Pool* pool;1868HRESULT hr = allocator->CreatePool(&poolDesc, &pool);1869\endcode18701871To allocate resources out of a custom pool, only set member D3D12MA::ALLOCATION_DESC::CustomPool.1872Example:18731874\code1875ALLOCATION_DESC allocDesc = {};1876allocDesc.CustomPool = pool;18771878D3D12_RESOURCE_DESC resDesc = ...1879Allocation* alloc;1880hr = allocator->CreateResource(&allocDesc, &resDesc,1881D3D12_RESOURCE_STATE_GENERIC_READ, NULL, &alloc, IID_NULL, NULL);1882\endcode18831884All allocations must be released before releasing the pool.1885The pool must be released before relasing the allocator.18861887\code1888alloc->Release();1889pool->Release();1890\endcode18911892\section custom_pools_features_and_benefits Features and benefits18931894While it is recommended to use default pools whenever possible for simplicity and to give the allocator1895more opportunities for internal optimizations, custom pools may be useful in following cases:18961897- To keep some resources separate from others in memory.1898- To keep track of memory usage of just a specific group of resources. %Statistics can be queried using1899D3D12MA::Pool::CalculateStatistics.1900- To use specific size of a memory block (`ID3D12Heap`). To set it, use member D3D12MA::POOL_DESC::BlockSize.1901When set to 0, the library uses automatically determined, variable block sizes.1902- To reserve some minimum amount of memory allocated. To use it, set member D3D12MA::POOL_DESC::MinBlockCount.1903- To limit maximum amount of memory allocated. To use it, set member D3D12MA::POOL_DESC::MaxBlockCount.1904- To use extended parameters of the D3D12 memory allocation. While resources created from default pools1905can only specify `D3D12_HEAP_TYPE_DEFAULT`, `UPLOAD`, `READBACK`, a custom pool may use non-standard1906`D3D12_HEAP_PROPERTIES` (member D3D12MA::POOL_DESC::HeapProperties) and `D3D12_HEAP_FLAGS`1907(D3D12MA::POOL_DESC::HeapFlags), which is useful e.g. for cross-adapter sharing or UMA1908(see also D3D12MA::Allocator::IsUMA).19091910New versions of this library support creating **committed allocations in custom pools**.1911It is supported only when D3D12MA::POOL_DESC::BlockSize = 0.1912To use this feature, set D3D12MA::ALLOCATION_DESC::CustomPool to the pointer to your custom pool and1913D3D12MA::ALLOCATION_DESC::Flags to D3D12MA::ALLOCATION_FLAG_COMMITTED. Example:19141915\code1916ALLOCATION_DESC allocDesc = {};1917allocDesc.CustomPool = pool;1918allocDesc.Flags = ALLOCATION_FLAG_COMMITTED;19191920D3D12_RESOURCE_DESC resDesc = ...1921Allocation* alloc;1922ID3D12Resource* res;1923hr = allocator->CreateResource(&allocDesc, &resDesc,1924D3D12_RESOURCE_STATE_GENERIC_READ, NULL, &alloc, IID_PPV_ARGS(&res));1925\endcode19261927This feature may seem unnecessary, but creating committed allocations from custom pools may be useful1928in some cases, e.g. to have separate memory usage statistics for some group of resources or to use1929extended allocation parameters, like custom `D3D12_HEAP_PROPERTIES`, which are available only in custom pools.193019311932\page defragmentation Defragmentation19331934Interleaved allocations and deallocations of many objects of varying size can1935cause fragmentation over time, which can lead to a situation where the library is unable1936to find a continuous range of free memory for a new allocation despite there is1937enough free space, just scattered across many small free ranges between existing1938allocations.19391940To mitigate this problem, you can use defragmentation feature.1941It doesn't happen automatically though and needs your cooperation,1942because %D3D12MA is a low level library that only allocates memory.1943It cannot recreate buffers and textures in a new place as it doesn't remember the contents of `D3D12_RESOURCE_DESC` structure.1944It cannot copy their contents as it doesn't record any commands to a command list.19451946Example:19471948\code1949D3D12MA::DEFRAGMENTATION_DESC defragDesc = {};1950defragDesc.Flags = D3D12MA::DEFRAGMENTATION_FLAG_ALGORITHM_FAST;19511952D3D12MA::DefragmentationContext* defragCtx;1953allocator->BeginDefragmentation(&defragDesc, &defragCtx);19541955for(;;)1956{1957D3D12MA::DEFRAGMENTATION_PASS_MOVE_INFO pass;1958HRESULT hr = defragCtx->BeginPass(&pass);1959if(hr == S_OK)1960break;1961else if(hr != S_FALSE)1962// Handle error...19631964for(UINT i = 0; i < pass.MoveCount; ++i)1965{1966// Inspect pass.pMoves[i].pSrcAllocation, identify what buffer/texture it represents.1967MyEngineResourceData* resData = (MyEngineResourceData*)pMoves[i].pSrcAllocation->GetPrivateData();19681969// Recreate this buffer/texture as placed at pass.pMoves[i].pDstTmpAllocation.1970D3D12_RESOURCE_DESC resDesc = ...1971ID3D12Resource* newRes;1972hr = device->CreatePlacedResource(1973pass.pMoves[i].pDstTmpAllocation->GetHeap(),1974pass.pMoves[i].pDstTmpAllocation->GetOffset(), &resDesc,1975D3D12_RESOURCE_STATE_COPY_DEST, NULL, IID_PPV_ARGS(&newRes));1976// Check hr...19771978// Store new resource in the pDstTmpAllocation.1979pass.pMoves[i].pDstTmpAllocation->SetResource(newRes);19801981// Copy its content to the new place.1982cmdList->CopyResource(1983pass.pMoves[i].pDstTmpAllocation->GetResource(),1984pass.pMoves[i].pSrcAllocation->GetResource());1985}19861987// Make sure the copy commands finished executing.1988cmdQueue->ExecuteCommandLists(...);1989// ...1990WaitForSingleObject(fenceEvent, INFINITE);19911992// Update appropriate descriptors to point to the new places...19931994hr = defragCtx->EndPass(&pass);1995if(hr == S_OK)1996break;1997else if(hr != S_FALSE)1998// Handle error...1999}20002001defragCtx->Release();2002\endcode20032004Although functions like D3D12MA::Allocator::CreateResource()2005create an allocation and a buffer/texture at once, these are just a shortcut for2006allocating memory and creating a placed resource.2007Defragmentation works on memory allocations only. You must handle the rest manually.2008Defragmentation is an iterative process that should repreat "passes" as long as related functions2009return `S_FALSE` not `S_OK`.2010In each pass:201120121. D3D12MA::DefragmentationContext::BeginPass() function call:2013- Calculates and returns the list of allocations to be moved in this pass.2014Note this can be a time-consuming process.2015- Reserves destination memory for them by creating temporary destination allocations2016that you can query for their `ID3D12Heap` + offset using methods like D3D12MA::Allocation::GetHeap().20172. Inside the pass, **you should**:2018- Inspect the returned list of allocations to be moved.2019- Create new buffers/textures as placed at the returned destination temporary allocations.2020- Copy data from source to destination resources if necessary.2021- Store the pointer to the new resource in the temporary destination allocation.20223. D3D12MA::DefragmentationContext::EndPass() function call:2023- Frees the source memory reserved for the allocations that are moved.2024- Modifies source D3D12MA::Allocation objects that are moved to point to the destination reserved memory2025and destination resource, while source resource is released.2026- Frees `ID3D12Heap` blocks that became empty.20272028Defragmentation algorithm tries to move all suitable allocations.2029You can, however, refuse to move some of them inside a defragmentation pass, by setting2030`pass.pMoves[i].Operation` to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_IGNORE.2031This is not recommended and may result in suboptimal packing of the allocations after defragmentation.2032If you cannot ensure any allocation can be moved, it is better to keep movable allocations separate in a custom pool.20332034Inside a pass, for each allocation that should be moved:20352036- You should copy its data from the source to the destination place by calling e.g. `CopyResource()`.2037- You need to make sure these commands finished executing before the source buffers/textures are released by D3D12MA::DefragmentationContext::EndPass().2038- If a resource doesn't contain any meaningful data, e.g. it is a transient render-target texture to be cleared,2039filled, and used temporarily in each rendering frame, you can just recreate this texture2040without copying its data.2041- If the resource is in `D3D12_HEAP_TYPE_READBACK` memory, you can copy its data on the CPU2042using `memcpy()`.2043- If you cannot move the allocation, you can set `pass.pMoves[i].Operation` to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_IGNORE.2044This will cancel the move.2045- D3D12MA::DefragmentationContext::EndPass() will then free the destination memory2046not the source memory of the allocation, leaving it unchanged.2047- If you decide the allocation is unimportant and can be destroyed instead of moved (e.g. it wasn't used for long time),2048you can set `pass.pMoves[i].Operation` to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_DESTROY.2049- D3D12MA::DefragmentationContext::EndPass() will then free both source and destination memory, and will destroy the source D3D12MA::Allocation object.20502051You can defragment a specific custom pool by calling D3D12MA::Pool::BeginDefragmentation2052or all the default pools by calling D3D12MA::Allocator::BeginDefragmentation (like in the example above).20532054Defragmentation is always performed in each pool separately.2055Allocations are never moved between different heap types.2056The size of the destination memory reserved for a moved allocation is the same as the original one.2057Alignment of an allocation as it was determined using `GetResourceAllocationInfo()` is also respected after defragmentation.2058Buffers/textures should be recreated with the same `D3D12_RESOURCE_DESC` parameters as the original ones.20592060You can perform the defragmentation incrementally to limit the number of allocations and bytes to be moved2061in each pass, e.g. to call it in sync with render frames and not to experience too big hitches.2062See members: D3D12MA::DEFRAGMENTATION_DESC::MaxBytesPerPass, D3D12MA::DEFRAGMENTATION_DESC::MaxAllocationsPerPass.20632064<b>Thread safety:</b>2065It is safe to perform the defragmentation asynchronously to render frames and other Direct3D 12 and %D3D12MA2066usage, possibly from multiple threads, with the exception that allocations2067returned in D3D12MA::DEFRAGMENTATION_PASS_MOVE_INFO::pMoves shouldn't be released until the defragmentation pass is ended.2068During the call to D3D12MA::DefragmentationContext::BeginPass(), any operations on the memory pool2069affected by the defragmentation are blocked by a mutex.20702071What it means in practice is that you shouldn't free any allocations from the defragmented pool2072since the moment a call to `BeginPass` begins. Otherwise, a thread performing the `allocation->Release()`2073would block for the time `BeginPass` executes and then free the allocation when it finishes, while the allocation2074could have ended up on the list of allocations to move.2075A solution to freeing allocations during defragmentation is to find such allocation on the list2076`pass.pMoves[i]` and set its operation to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_DESTROY instead of2077calling `allocation->Release()`, or simply deferring the release to the time after defragmentation finished.20782079<b>Mapping</b> is out of scope of this library and so it is not preserved after an allocation is moved during defragmentation.2080You need to map the new resource yourself if needed.20812082\note Defragmentation is not supported in custom pools created with D3D12MA::POOL_FLAG_ALGORITHM_LINEAR.208320842085\page statistics Statistics20862087This library contains several functions that return information about its internal state,2088especially the amount of memory allocated from D3D12.20892090\section statistics_numeric_statistics Numeric statistics20912092If you need to obtain basic statistics about memory usage per memory segment group, together with current budget,2093you can call function D3D12MA::Allocator::GetBudget() and inspect structure D3D12MA::Budget.2094This is useful to keep track of memory usage and stay withing budget.2095Example:20962097\code2098D3D12MA::Budget localBudget;2099allocator->GetBudget(&localBudget, NULL);21002101printf("My GPU memory currently has %u allocations taking %llu B,\n",2102localBudget.Statistics.AllocationCount,2103localBudget.Statistics.AllocationBytes);2104printf("allocated out of %u D3D12 memory heaps taking %llu B,\n",2105localBudget.Statistics.BlockCount,2106localBudget.Statistics.BlockBytes);2107printf("D3D12 reports total usage %llu B with budget %llu B.\n",2108localBudget.UsageBytes,2109localBudget.BudgetBytes);2110\endcode21112112You can query for more detailed statistics per heap type, memory segment group, and totals,2113including minimum and maximum allocation size and unused range size,2114by calling function D3D12MA::Allocator::CalculateStatistics() and inspecting structure D3D12MA::TotalStatistics.2115This function is slower though, as it has to traverse all the internal data structures,2116so it should be used only for debugging purposes.21172118You can query for statistics of a custom pool using function D3D12MA::Pool::GetStatistics()2119or D3D12MA::Pool::CalculateStatistics().21202121You can query for information about a specific allocation using functions of the D3D12MA::Allocation class,2122e.g. `GetSize()`, `GetOffset()`, `GetHeap()`.21232124\section statistics_json_dump JSON dump21252126You can dump internal state of the allocator to a string in JSON format using function D3D12MA::Allocator::BuildStatsString().2127The result is guaranteed to be correct JSON.2128It uses Windows Unicode (UTF-16) encoding.2129Any strings provided by user (see D3D12MA::Allocation::SetName())2130are copied as-is and properly escaped for JSON.2131It must be freed using function D3D12MA::Allocator::FreeStatsString().21322133The format of this JSON string is not part of official documentation of the library,2134but it will not change in backward-incompatible way without increasing library major version number2135and appropriate mention in changelog.21362137The JSON string contains all the data that can be obtained using D3D12MA::Allocator::CalculateStatistics().2138It can also contain detailed map of allocated memory blocks and their regions -2139free and occupied by allocations.2140This allows e.g. to visualize the memory or assess fragmentation.214121422143\page resource_aliasing Resource aliasing (overlap)21442145New explicit graphics APIs (Vulkan and Direct3D 12), thanks to manual memory2146management, give an opportunity to alias (overlap) multiple resources in the2147same region of memory - a feature not available in the old APIs (Direct3D 11, OpenGL).2148It can be useful to save video memory, but it must be used with caution.21492150For example, if you know the flow of your whole render frame in advance, you2151are going to use some intermediate textures or buffers only during a small range of render passes,2152and you know these ranges don't overlap in time, you can create these resources in2153the same place in memory, even if they have completely different parameters (width, height, format etc.).2154215521562157Such scenario is possible using D3D12MA, but you need to create your resources2158using special function D3D12MA::Allocator::CreateAliasingResource.2159Before that, you need to allocate memory with parameters calculated using formula:21602161- allocation size = max(size of each resource)2162- allocation alignment = max(alignment of each resource)21632164Following example shows two different textures created in the same place in memory,2165allocated to fit largest of them.21662167\code2168D3D12_RESOURCE_DESC resDesc1 = {};2169resDesc1.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;2170resDesc1.Alignment = 0;2171resDesc1.Width = 1920;2172resDesc1.Height = 1080;2173resDesc1.DepthOrArraySize = 1;2174resDesc1.MipLevels = 1;2175resDesc1.Format = DXGI_FORMAT_R8G8B8A8_UNORM;2176resDesc1.SampleDesc.Count = 1;2177resDesc1.SampleDesc.Quality = 0;2178resDesc1.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;2179resDesc1.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;21802181D3D12_RESOURCE_DESC resDesc2 = {};2182resDesc2.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;2183resDesc2.Alignment = 0;2184resDesc2.Width = 1024;2185resDesc2.Height = 1024;2186resDesc2.DepthOrArraySize = 1;2187resDesc2.MipLevels = 0;2188resDesc2.Format = DXGI_FORMAT_R8G8B8A8_UNORM;2189resDesc2.SampleDesc.Count = 1;2190resDesc2.SampleDesc.Quality = 0;2191resDesc2.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;2192resDesc2.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;21932194const D3D12_RESOURCE_ALLOCATION_INFO allocInfo1 =2195device->GetResourceAllocationInfo(0, 1, &resDesc1);2196const D3D12_RESOURCE_ALLOCATION_INFO allocInfo2 =2197device->GetResourceAllocationInfo(0, 1, &resDesc2);21982199D3D12_RESOURCE_ALLOCATION_INFO finalAllocInfo = {};2200finalAllocInfo.Alignment = std::max(allocInfo1.Alignment, allocInfo2.Alignment);2201finalAllocInfo.SizeInBytes = std::max(allocInfo1.SizeInBytes, allocInfo2.SizeInBytes);22022203D3D12MA::ALLOCATION_DESC allocDesc = {};2204allocDesc.HeapType = D3D12_HEAP_TYPE_DEFAULT;2205allocDesc.ExtraHeapFlags = D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES;22062207D3D12MA::Allocation* alloc;2208hr = allocator->AllocateMemory(&allocDesc, &finalAllocInfo, &alloc);2209assert(alloc != NULL && alloc->GetHeap() != NULL);22102211ID3D12Resource* res1;2212hr = allocator->CreateAliasingResource(2213alloc,22140, // AllocationLocalOffset2215&resDesc1,2216D3D12_RESOURCE_STATE_COMMON,2217NULL, // pOptimizedClearValue2218IID_PPV_ARGS(&res1));22192220ID3D12Resource* res2;2221hr = allocator->CreateAliasingResource(2222alloc,22230, // AllocationLocalOffset2224&resDesc2,2225D3D12_RESOURCE_STATE_COMMON,2226NULL, // pOptimizedClearValue2227IID_PPV_ARGS(&res2));22282229// You can use res1 and res2, but not at the same time!22302231res2->Release();2232res1->Release();2233alloc->Release();2234\endcode22352236Remember that using resouces that alias in memory requires proper synchronization.2237You need to issue a special barrier of type `D3D12_RESOURCE_BARRIER_TYPE_ALIASING`.2238You also need to treat a resource after aliasing as uninitialized - containing garbage data.2239For example, if you use `res1` and then want to use `res2`, you need to first initialize `res2`2240using either Clear, Discard, or Copy to the entire resource.22412242Additional considerations:22432244- D3D12 also allows to interpret contents of memory between aliasing resources consistently in some cases,2245which is called "data inheritance". For details, see2246Microsoft documentation chapter "Memory Aliasing and Data Inheritance".2247- You can create more complex layout where different textures and buffers are bound2248at different offsets inside one large allocation. For example, one can imagine2249a big texture used in some render passes, aliasing with a set of many small buffers2250used in some further passes. To bind a resource at non-zero offset of an allocation,2251call D3D12MA::Allocator::CreateAliasingResource with appropriate value of `AllocationLocalOffset` parameter.2252- Resources of the three categories: buffers, textures with `RENDER_TARGET` or `DEPTH_STENCIL` flags, and all other textures,2253can be placed in the same memory only when `allocator->GetD3D12Options().ResourceHeapTier >= D3D12_RESOURCE_HEAP_TIER_2`.2254Otherwise they must be placed in different memory heap types, and thus aliasing them is not possible.225522562257\page linear_algorithm Linear allocation algorithm22582259Each D3D12 memory block managed by this library has accompanying metadata that2260keeps track of used and unused regions. By default, the metadata structure and2261algorithm tries to find best place for new allocations among free regions to2262optimize memory usage. This way you can allocate and free objects in any order.2263226422652266Sometimes there is a need to use simpler, linear allocation algorithm. You can2267create custom pool that uses such algorithm by adding flag2268D3D12MA::POOL_FLAG_ALGORITHM_LINEAR to D3D12MA::POOL_DESC::Flags while creating2269D3D12MA::Pool object. Then an alternative metadata management is used. It always2270creates new allocations after last one and doesn't reuse free regions after2271allocations freed in the middle. It results in better allocation performance and2272less memory consumed by metadata.2273227422752276With this one flag, you can create a custom pool that can be used in many ways:2277free-at-once, stack, double stack, and ring buffer. See below for details.2278You don't need to specify explicitly which of these options you are going to use - it is detected automatically.22792280\section linear_algorithm_free_at_once Free-at-once22812282In a pool that uses linear algorithm, you still need to free all the allocations2283individually by calling `allocation->Release()`. You can free2284them in any order. New allocations are always made after last one - free space2285in the middle is not reused. However, when you release all the allocation and2286the pool becomes empty, allocation starts from the beginning again. This way you2287can use linear algorithm to speed up creation of allocations that you are going2288to release all at once.2289229022912292This mode is also available for pools created with D3D12MA::POOL_DESC::MaxBlockCount2293value that allows multiple memory blocks.22942295\section linear_algorithm_stack Stack22962297When you free an allocation that was created last, its space can be reused.2298Thanks to this, if you always release allocations in the order opposite to their2299creation (LIFO - Last In First Out), you can achieve behavior of a stack.2300230123022303This mode is also available for pools created with D3D12MA::POOL_DESC::MaxBlockCount2304value that allows multiple memory blocks.23052306\section linear_algorithm_double_stack Double stack23072308The space reserved by a custom pool with linear algorithm may be used by two2309stacks:23102311- First, default one, growing up from offset 0.2312- Second, "upper" one, growing down from the end towards lower offsets.23132314To make allocation from the upper stack, add flag D3D12MA::ALLOCATION_FLAG_UPPER_ADDRESS2315to D3D12MA::ALLOCATION_DESC::Flags.2316231723182319Double stack is available only in pools with one memory block -2320D3D12MA::POOL_DESC::MaxBlockCount must be 1. Otherwise behavior is undefined.23212322When the two stacks' ends meet so there is not enough space between them for a2323new allocation, such allocation fails with usual `E_OUTOFMEMORY` error.23242325\section linear_algorithm_ring_buffer Ring buffer23262327When you free some allocations from the beginning and there is not enough free space2328for a new one at the end of a pool, allocator's "cursor" wraps around to the2329beginning and starts allocation there. Thanks to this, if you always release2330allocations in the same order as you created them (FIFO - First In First Out),2331you can achieve behavior of a ring buffer / queue.2332233323342335Ring buffer is available only in pools with one memory block -2336D3D12MA::POOL_DESC::MaxBlockCount must be 1. Otherwise behavior is undefined.23372338\section linear_algorithm_additional_considerations Additional considerations23392340Linear algorithm can also be used with \ref virtual_allocator.2341See flag D3D12MA::VIRTUAL_BLOCK_FLAG_ALGORITHM_LINEAR.234223432344\page virtual_allocator Virtual allocator23452346As an extra feature, the core allocation algorithm of the library is exposed through a simple and convenient API of "virtual allocator".2347It doesn't allocate any real GPU memory. It just keeps track of used and free regions of a "virtual block".2348You can use it to allocate your own memory or other objects, even completely unrelated to D3D12.2349A common use case is sub-allocation of pieces of one large GPU buffer.23502351\section virtual_allocator_creating_virtual_block Creating virtual block23522353To use this functionality, there is no main "allocator" object.2354You don't need to have D3D12MA::Allocator object created.2355All 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:23562357-# Fill in D3D12MA::ALLOCATOR_DESC structure.2358-# Call D3D12MA::CreateVirtualBlock. Get new D3D12MA::VirtualBlock object.23592360Example:23612362\code2363D3D12MA::VIRTUAL_BLOCK_DESC blockDesc = {};2364blockDesc.Size = 1048576; // 1 MB23652366D3D12MA::VirtualBlock *block;2367HRESULT hr = CreateVirtualBlock(&blockDesc, &block);2368\endcode23692370\section virtual_allocator_making_virtual_allocations Making virtual allocations23712372D3D12MA::VirtualBlock object contains internal data structure that keeps track of free and occupied regions2373using the same code as the main D3D12 memory allocator.2374A single allocation is identified by a lightweight structure D3D12MA::VirtualAllocation.2375You will also likely want to know the offset at which the allocation was made in the block.23762377In order to make an allocation:23782379-# Fill in D3D12MA::VIRTUAL_ALLOCATION_DESC structure.2380-# Call D3D12MA::VirtualBlock::Allocate. Get new D3D12MA::VirtualAllocation value that identifies the allocation.23812382Example:23832384\code2385D3D12MA::VIRTUAL_ALLOCATION_DESC allocDesc = {};2386allocDesc.Size = 4096; // 4 KB23872388D3D12MA::VirtualAllocation alloc;2389UINT64 allocOffset;2390hr = block->Allocate(&allocDesc, &alloc, &allocOffset);2391if(SUCCEEDED(hr))2392{2393// Use the 4 KB of your memory starting at allocOffset.2394}2395else2396{2397// Allocation failed - no space for it could be found. Handle this error!2398}2399\endcode24002401\section virtual_allocator_deallocation Deallocation24022403When no longer needed, an allocation can be freed by calling D3D12MA::VirtualBlock::FreeAllocation.24042405When whole block is no longer needed, the block object can be released by calling `block->Release()`.2406All allocations must be freed before the block is destroyed, which is checked internally by an assert.2407However, if you don't want to call `block->FreeAllocation` for each allocation, you can use D3D12MA::VirtualBlock::Clear to free them all at once -2408a feature not available in normal D3D12 memory allocator.24092410Example:24112412\code2413block->FreeAllocation(alloc);2414block->Release();2415\endcode24162417\section virtual_allocator_allocation_parameters Allocation parameters24182419You can attach a custom pointer to each allocation by using D3D12MA::VirtualBlock::SetAllocationPrivateData.2420Its default value is `NULL`.2421It 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 some2422larger data structure containing more information. Example:24232424\code2425struct CustomAllocData2426{2427std::string m_AllocName;2428};2429CustomAllocData* allocData = new CustomAllocData();2430allocData->m_AllocName = "My allocation 1";2431block->SetAllocationPrivateData(alloc, allocData);2432\endcode24332434The pointer can later be fetched, along with allocation offset and size, by passing the allocation handle to function2435D3D12MA::VirtualBlock::GetAllocationInfo and inspecting returned structure D3D12MA::VIRTUAL_ALLOCATION_INFO.2436If you allocated a new object to be used as the custom pointer, don't forget to delete that object before freeing the allocation!2437Example:24382439\code2440VIRTUAL_ALLOCATION_INFO allocInfo;2441block->GetAllocationInfo(alloc, &allocInfo);2442delete (CustomAllocData*)allocInfo.pPrivateData;24432444block->FreeAllocation(alloc);2445\endcode24462447\section virtual_allocator_alignment_and_units Alignment and units24482449It feels natural to express sizes and offsets in bytes.2450If an offset of an allocation needs to be aligned to a multiply of some number (e.g. 4 bytes), you can fill optional member2451D3D12MA::VIRTUAL_ALLOCATION_DESC::Alignment to request it. Example:24522453\code2454D3D12MA::VIRTUAL_ALLOCATION_DESC allocDesc = {};2455allocDesc.Size = 4096; // 4 KB2456allocDesc.Alignment = 4; // Returned offset must be a multiply of 4 B24572458D3D12MA::VirtualAllocation alloc;2459UINT64 allocOffset;2460hr = block->Allocate(&allocDesc, &alloc, &allocOffset);2461\endcode24622463Alignments of different allocations made from one block may vary.2464However, if all alignments and sizes are always multiply of some size e.g. 4 B or `sizeof(MyDataStruct)`,2465you can express all sizes, alignments, and offsets in multiples of that size instead of individual bytes.2466It might be more convenient, but you need to make sure to use this new unit consistently in all the places:24672468- D3D12MA::VIRTUAL_BLOCK_DESC::Size2469- D3D12MA::VIRTUAL_ALLOCATION_DESC::Size and D3D12MA::VIRTUAL_ALLOCATION_DESC::Alignment2470- Using offset returned by D3D12MA::VirtualBlock::Allocate and D3D12MA::VIRTUAL_ALLOCATION_INFO::Offset24712472\section virtual_allocator_statistics Statistics24732474You can obtain brief statistics of a virtual block using D3D12MA::VirtualBlock::GetStatistics().2475The function fills structure D3D12MA::Statistics - same as used by the normal D3D12 memory allocator.2476Example:24772478\code2479D3D12MA::Statistics stats;2480block->GetStatistics(&stats);2481printf("My virtual block has %llu bytes used by %u virtual allocations\n",2482stats.AllocationBytes, stats.AllocationCount);2483\endcode24842485More detailed statistics can be obtained using function D3D12MA::VirtualBlock::CalculateStatistics(),2486but they are slower to calculate.24872488You can also request a full list of allocations and free regions as a string in JSON format by calling2489D3D12MA::VirtualBlock::BuildStatsString.2490Returned string must be later freed using D3D12MA::VirtualBlock::FreeStatsString.2491The format of this string may differ from the one returned by the main D3D12 allocator, but it is similar.24922493\section virtual_allocator_additional_considerations Additional considerations24942495Alternative, linear algorithm can be used with virtual allocator - see flag2496D3D12MA::VIRTUAL_BLOCK_FLAG_ALGORITHM_LINEAR and documentation: \ref linear_algorithm.24972498Note that the "virtual allocator" functionality is implemented on a level of individual memory blocks.2499Keeping track of a whole collection of blocks, allocating new ones when out of free space,2500deleting empty ones, and deciding which one to try first for a new allocation must be implemented by the user.250125022503\page configuration Configuration25042505Please check file `D3D12MemAlloc.cpp` lines between "Configuration Begin" and2506"Configuration End" to find macros that you can define to change the behavior of2507the library, primarily for debugging purposes.25082509\section custom_memory_allocator Custom CPU memory allocator25102511If you use custom allocator for CPU memory rather than default C++ operator `new`2512and `delete` or `malloc` and `free` functions, you can make this library using2513your allocator as well by filling structure D3D12MA::ALLOCATION_CALLBACKS and2514passing it as optional member D3D12MA::ALLOCATOR_DESC::pAllocationCallbacks.2515Functions pointed there will be used by the library to make any CPU-side2516allocations. Example:25172518\code2519#include <malloc.h>25202521void* CustomAllocate(size_t Size, size_t Alignment, void* pPrivateData)2522{2523void* memory = _aligned_malloc(Size, Alignment);2524// Your extra bookkeeping here...2525return memory;2526}25272528void CustomFree(void* pMemory, void* pPrivateData)2529{2530// Your extra bookkeeping here...2531_aligned_free(pMemory);2532}25332534(...)25352536D3D12MA::ALLOCATION_CALLBACKS allocationCallbacks = {};2537allocationCallbacks.pAllocate = &CustomAllocate;2538allocationCallbacks.pFree = &CustomFree;25392540D3D12MA::ALLOCATOR_DESC allocatorDesc = {};2541allocatorDesc.pDevice = device;2542allocatorDesc.pAdapter = adapter;2543allocatorDesc.pAllocationCallbacks = &allocationCallbacks;25442545D3D12MA::Allocator* allocator;2546HRESULT hr = D3D12MA::CreateAllocator(&allocatorDesc, &allocator);2547\endcode254825492550\section debug_margins Debug margins25512552By default, allocations are laid out in memory blocks next to each other if possible2553(considering required alignment returned by `ID3D12Device::GetResourceAllocationInfo`).2554255525562557Define macro `D3D12MA_DEBUG_MARGIN` to some non-zero value (e.g. 16) inside "D3D12MemAlloc.cpp"2558to enforce specified number of bytes as a margin after every allocation.2559256025612562If your bug goes away after enabling margins, it means it may be caused by memory2563being overwritten outside of allocation boundaries. It is not 100% certain though.2564Change in application behavior may also be caused by different order and distribution2565of allocations across memory blocks after margins are applied.25662567Margins work with all memory heap types.25682569Margin is applied only to placed allocations made out of memory heaps and not to committed2570allocations, which have their own, implicit memory heap of specific size.2571It is thus not applied to allocations made using D3D12MA::ALLOCATION_FLAG_COMMITTED flag2572or those automatically decided to put into committed allocations, e.g. due to its large size.25732574Margins appear in [JSON dump](@ref statistics_json_dump) as part of free space.25752576Note that enabling margins increases memory usage and fragmentation.25772578Margins do not apply to \ref virtual_allocator.257925802581\page general_considerations General considerations25822583\section general_considerations_thread_safety Thread safety25842585- The library has no global state, so separate D3D12MA::Allocator objects can be used independently.2586In typical applications there should be no need to create multiple such objects though - one per `ID3D12Device` is enough.2587- All calls to methods of D3D12MA::Allocator class are safe to be made from multiple2588threads simultaneously because they are synchronized internally when needed.2589- When the allocator is created with D3D12MA::ALLOCATOR_FLAG_SINGLETHREADED,2590calls to methods of D3D12MA::Allocator class must be made from a single thread or synchronized by the user.2591Using this flag may improve performance.2592- D3D12MA::VirtualBlock is not safe to be used from multiple threads simultaneously.25932594\section general_considerations_versioning_and_compatibility Versioning and compatibility25952596The library uses [**Semantic Versioning**](https://semver.org/),2597which means version numbers follow convention: Major.Minor.Patch (e.g. 2.3.0), where:25982599- Incremented Patch version means a release is backward- and forward-compatible,2600introducing only some internal improvements, bug fixes, optimizations etc.2601or changes that are out of scope of the official API described in this documentation.2602- Incremented Minor version means a release is backward-compatible,2603so existing code that uses the library should continue to work, while some new2604symbols could have been added: new structures, functions, new values in existing2605enums and bit flags, new structure members, but not new function parameters.2606- Incrementing Major version means a release could break some backward compatibility.26072608All changes between official releases are documented in file "CHANGELOG.md".26092610\warning Backward compatiblity is considered on the level of C++ source code, not binary linkage.2611Adding new members to existing structures is treated as backward compatible if initializing2612the new members to binary zero results in the old behavior.2613You should always fully initialize all library structures to zeros and not rely on their2614exact binary size.26152616\section general_considerations_features_not_supported Features not supported26172618Features deliberately excluded from the scope of this library:26192620- **Descriptor allocation.** Although also called "heaps", objects that represent2621descriptors are separate part of the D3D12 API from buffers and textures.2622You can still use \ref virtual_allocator to manage descriptors and their ranges inside a descriptor heap.2623- **Support for reserved (tiled) resources.** We don't recommend using them.2624- Support for `ID3D12Device::Evict` and `MakeResident`. We don't recommend using them.2625You can call them on the D3D12 objects manually.2626Plese keep in mind, however, that eviction happens on the level of entire `ID3D12Heap` memory blocks2627and not individual buffers or textures which may be placed inside them.2628- **Handling CPU memory allocation failures.** When dynamically creating small C++2629objects in CPU memory (not the GPU memory), allocation failures are not2630handled gracefully, because that would complicate code significantly and2631is usually not needed in desktop PC applications anyway.2632Success of an allocation is just checked with an assert.2633- **Code free of any compiler warnings.**2634There are many preprocessor macros that make some variables unused, function parameters unreferenced,2635or conditional expressions constant in some configurations.2636The code of this library should not be bigger or more complicated just to silence these warnings.2637It is recommended to disable such warnings instead.2638- This is a C++ library. **Bindings or ports to any other programming languages** are welcome as external projects but2639are not going to be included into this repository.2640*/264126422643