-
Notifications
You must be signed in to change notification settings - Fork 89
/
D3D12MemAlloc.h
2644 lines (2085 loc) · 114 KB
/
D3D12MemAlloc.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2019-2022 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#pragma once
/** \mainpage D3D12 Memory Allocator
<b>Version 2.1.0-development</b> (2024-07-05)
Copyright (c) 2019-2024 Advanced Micro Devices, Inc. All rights reserved. \n
License: MIT
Documentation of all members: D3D12MemAlloc.h
\section main_table_of_contents Table of contents
- \subpage quick_start
- [Project setup](@ref quick_start_project_setup)
- [Creating resources](@ref quick_start_creating_resources)
- [Resource reference counting](@ref quick_start_resource_reference_counting)
- [Mapping memory](@ref quick_start_mapping_memory)
- \subpage custom_pools
- \subpage defragmentation
- \subpage statistics
- \subpage resource_aliasing
- \subpage linear_algorithm
- \subpage virtual_allocator
- \subpage configuration
- [Custom CPU memory allocator](@ref custom_memory_allocator)
- [Debug margins](@ref debug_margins)
- \subpage general_considerations
- [Thread safety](@ref general_considerations_thread_safety)
- [Versioning and compatibility](@ref general_considerations_versioning_and_compatibility)
- [Features not supported](@ref general_considerations_features_not_supported)
\section main_see_also See also
- [Product page on GPUOpen](https://gpuopen.com/gaming-product/d3d12-memory-allocator/)
- [Source repository on GitHub](https://github.com/GPUOpen-LibrariesAndSDKs/D3D12MemoryAllocator)
*/
// If using this library on a platform different than Windows PC or want to use different version of DXGI,
// you should include D3D12-compatible headers before this library on your own and define
// D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED.
// Alternatively, if you are targeting the open sourced DirectX headers, defining D3D12MA_USING_DIRECTX_HEADERS
// will include them rather the ones provided by the Windows SDK.
#ifndef D3D12MA_D3D12_HEADERS_ALREADY_INCLUDED
#if defined(D3D12MA_USING_DIRECTX_HEADERS)
#include <directx/d3d12.h>
#include <dxguids/dxguids.h>
#else
#include <d3d12.h>
#endif
#include <dxgi1_4.h>
#endif
// Define this macro to 0 to disable usage of DXGI 1.4 (needed for IDXGIAdapter3 and query for memory budget).
#ifndef D3D12MA_DXGI_1_4
#ifdef __IDXGIAdapter3_INTERFACE_DEFINED__
#define D3D12MA_DXGI_1_4 1
#else
#define D3D12MA_DXGI_1_4 0
#endif
#endif
/*
When defined to value other than 0, the library will try to use
D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT or D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT
for created textures when possible, which can save memory because some small textures
may get their alignment 4K and their size a multiply of 4K instead of 64K.
#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 0
Disables small texture alignment.
#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 1
Enables conservative algorithm that will use small alignment only for some textures
that are surely known to support it.
#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 2
Enables query for small alignment to D3D12 (based on Microsoft sample) which will
enable small alignment for more textures, but will also generate D3D Debug Layer
error #721 on call to ID3D12Device::GetResourceAllocationInfo, which you should just
ignore.
*/
#ifndef D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT
#define D3D12MA_USE_SMALL_RESOURCE_PLACEMENT_ALIGNMENT 1
#endif
/// \cond INTERNAL
#define D3D12MA_CLASS_NO_COPY(className) \
private: \
className(const className&) = delete; \
className(className&&) = delete; \
className& operator=(const className&) = delete; \
className& operator=(className&&) = delete;
// To be used with MAKE_HRESULT to define custom error codes.
#define FACILITY_D3D12MA 3542
/*
If providing your own implementation, you need to implement a subset of std::atomic.
*/
#if !defined(D3D12MA_ATOMIC_UINT32) || !defined(D3D12MA_ATOMIC_UINT64)
#include <atomic>
#endif
#ifndef D3D12MA_ATOMIC_UINT32
#define D3D12MA_ATOMIC_UINT32 std::atomic<UINT>
#endif
#ifndef D3D12MA_ATOMIC_UINT64
#define D3D12MA_ATOMIC_UINT64 std::atomic<UINT64>
#endif
#ifdef D3D12MA_EXPORTS
#define D3D12MA_API __declspec(dllexport)
#elif defined(D3D12MA_IMPORTS)
#define D3D12MA_API __declspec(dllimport)
#else
#define D3D12MA_API
#endif
// Forward declaration if ID3D12ProtectedResourceSession is not defined inside the headers (older SDK, pre ID3D12Device4)
struct ID3D12ProtectedResourceSession;
// Define this enum even if SDK doesn't provide it, to simplify the API.
#ifndef __ID3D12Device1_INTERFACE_DEFINED__
typedef enum D3D12_RESIDENCY_PRIORITY
{
D3D12_RESIDENCY_PRIORITY_MINIMUM = 0x28000000,
D3D12_RESIDENCY_PRIORITY_LOW = 0x50000000,
D3D12_RESIDENCY_PRIORITY_NORMAL = 0x78000000,
D3D12_RESIDENCY_PRIORITY_HIGH = 0xa0010000,
D3D12_RESIDENCY_PRIORITY_MAXIMUM = 0xc8000000
} D3D12_RESIDENCY_PRIORITY;
#endif
namespace D3D12MA
{
class D3D12MA_API IUnknownImpl : public IUnknown
{
public:
virtual ~IUnknownImpl() = default;
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObject) override;
ULONG STDMETHODCALLTYPE AddRef() override;
ULONG STDMETHODCALLTYPE Release() override;
protected:
virtual void ReleaseThis() { delete this; }
private:
D3D12MA_ATOMIC_UINT32 m_RefCount = {1};
};
} // namespace D3D12MA
/// \endcond
namespace D3D12MA
{
/// \cond INTERNAL
class DefragmentationContextPimpl;
class AllocatorPimpl;
class PoolPimpl;
class NormalBlock;
class BlockVector;
class CommittedAllocationList;
class JsonWriter;
class VirtualBlockPimpl;
/// \endcond
class Pool;
class Allocator;
struct Statistics;
struct DetailedStatistics;
struct TotalStatistics;
/// \brief Unique identifier of single allocation done inside the memory heap.
typedef UINT64 AllocHandle;
/// Pointer to custom callback function that allocates CPU memory.
using ALLOCATE_FUNC_PTR = void* (*)(size_t Size, size_t Alignment, void* pPrivateData);
/**
\brief Pointer to custom callback function that deallocates CPU memory.
`pMemory = null` should be accepted and ignored.
*/
using FREE_FUNC_PTR = void (*)(void* pMemory, void* pPrivateData);
/// Custom callbacks to CPU memory allocation functions.
struct ALLOCATION_CALLBACKS
{
/// %Allocation function.
ALLOCATE_FUNC_PTR pAllocate;
/// Dellocation function.
FREE_FUNC_PTR pFree;
/// Custom data that will be passed to allocation and deallocation functions as `pUserData` parameter.
void* pPrivateData;
};
/// \brief Bit flags to be used with ALLOCATION_DESC::Flags.
enum ALLOCATION_FLAGS
{
/// Zero
ALLOCATION_FLAG_NONE = 0,
/**
Set this flag if the allocation should have its own dedicated memory allocation (committed resource with implicit heap).
Use it for special, big resources, like fullscreen textures used as render targets.
- When used with functions like D3D12MA::Allocator::CreateResource, it will use `ID3D12Device::CreateCommittedResource`,
so the created allocation will contain a resource (D3D12MA::Allocation::GetResource() `!= NULL`) but will not have
a heap (D3D12MA::Allocation::GetHeap() `== NULL`), as the heap is implicit.
- When used with raw memory allocation like D3D12MA::Allocator::AllocateMemory, it will use `ID3D12Device::CreateHeap`,
so the created allocation will contain a heap (D3D12MA::Allocation::GetHeap() `!= NULL`) and its offset will always be 0.
*/
ALLOCATION_FLAG_COMMITTED = 0x1,
/**
Set this flag to only try to allocate from existing memory heaps and never create new such heap.
If new allocation cannot be placed in any of the existing heaps, allocation
fails with `E_OUTOFMEMORY` error.
You should not use D3D12MA::ALLOCATION_FLAG_COMMITTED and
D3D12MA::ALLOCATION_FLAG_NEVER_ALLOCATE at the same time. It makes no sense.
*/
ALLOCATION_FLAG_NEVER_ALLOCATE = 0x2,
/** Create allocation only if additional memory required for it, if any, won't exceed
memory budget. Otherwise return `E_OUTOFMEMORY`.
*/
ALLOCATION_FLAG_WITHIN_BUDGET = 0x4,
/** Allocation will be created from upper stack in a double stack pool.
This flag is only allowed for custom pools created with #POOL_FLAG_ALGORITHM_LINEAR flag.
*/
ALLOCATION_FLAG_UPPER_ADDRESS = 0x8,
/** Set this flag if the allocated memory will have aliasing resources.
Use this when calling D3D12MA::Allocator::CreateResource() and similar to
guarantee creation of explicit heap for desired allocation and prevent it from using `CreateCommittedResource`,
so that new allocation object will always have `allocation->GetHeap() != NULL`.
*/
ALLOCATION_FLAG_CAN_ALIAS = 0x10,
/** %Allocation strategy that chooses smallest possible free range for the allocation
to minimize memory usage and fragmentation, possibly at the expense of allocation time.
*/
ALLOCATION_FLAG_STRATEGY_MIN_MEMORY = 0x00010000,
/** %Allocation strategy that chooses first suitable free range for the allocation -
not necessarily in terms of the smallest offset but the one that is easiest and fastest to find
to minimize allocation time, possibly at the expense of allocation quality.
*/
ALLOCATION_FLAG_STRATEGY_MIN_TIME = 0x00020000,
/** %Allocation strategy that chooses always the lowest offset in available space.
This is not the most efficient strategy but achieves highly packed data.
Used internally by defragmentation, not recomended in typical usage.
*/
ALLOCATION_FLAG_STRATEGY_MIN_OFFSET = 0x0004000,
/// Alias to #ALLOCATION_FLAG_STRATEGY_MIN_MEMORY.
ALLOCATION_FLAG_STRATEGY_BEST_FIT = ALLOCATION_FLAG_STRATEGY_MIN_MEMORY,
/// Alias to #ALLOCATION_FLAG_STRATEGY_MIN_TIME.
ALLOCATION_FLAG_STRATEGY_FIRST_FIT = ALLOCATION_FLAG_STRATEGY_MIN_TIME,
/// A bit mask to extract only `STRATEGY` bits from entire set of flags.
ALLOCATION_FLAG_STRATEGY_MASK =
ALLOCATION_FLAG_STRATEGY_MIN_MEMORY |
ALLOCATION_FLAG_STRATEGY_MIN_TIME |
ALLOCATION_FLAG_STRATEGY_MIN_OFFSET,
};
/// \brief Parameters of created D3D12MA::Allocation object. To be used with Allocator::CreateResource.
struct ALLOCATION_DESC
{
/// Flags.
ALLOCATION_FLAGS Flags;
/** \brief The type of memory heap where the new allocation should be placed.
It must be one of: `D3D12_HEAP_TYPE_DEFAULT`, `D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`.
When D3D12MA::ALLOCATION_DESC::CustomPool != NULL this member is ignored.
*/
D3D12_HEAP_TYPE HeapType;
/** \brief Additional heap flags to be used when allocating memory.
In most cases it can be 0.
- If you use D3D12MA::Allocator::CreateResource(), you don't need to care.
Necessary flag `D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS`, `D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES`,
or `D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES` is added automatically.
- If you use D3D12MA::Allocator::AllocateMemory(), you should specify one of those `ALLOW_ONLY` flags.
Except when you validate that D3D12MA::Allocator::GetD3D12Options()`.ResourceHeapTier == D3D12_RESOURCE_HEAP_TIER_1` -
then you can leave it 0.
- You can specify additional flags if needed. Then the memory will always be allocated as
separate block using `D3D12Device::CreateCommittedResource` or `CreateHeap`, not as part of an existing larget block.
When D3D12MA::ALLOCATION_DESC::CustomPool != NULL this member is ignored.
*/
D3D12_HEAP_FLAGS ExtraHeapFlags;
/** \brief Custom pool to place the new resource in. Optional.
When not NULL, the resource will be created inside specified custom pool.
*/
Pool* CustomPool;
/// Custom general-purpose pointer that will be stored in D3D12MA::Allocation.
void* pPrivateData;
};
/** \brief Calculated statistics of memory usage e.g. in a specific memory heap type,
memory segment group, custom pool, or total.
These are fast to calculate.
See functions: D3D12MA::Allocator::GetBudget(), D3D12MA::Pool::GetStatistics().
*/
struct Statistics
{
/** \brief Number of D3D12 memory blocks allocated - `ID3D12Heap` objects and committed resources.
*/
UINT BlockCount;
/** \brief Number of D3D12MA::Allocation objects allocated.
Committed allocations have their own blocks, so each one adds 1 to `AllocationCount` as well as `BlockCount`.
*/
UINT AllocationCount;
/** \brief Number of bytes allocated in memory blocks.
*/
UINT64 BlockBytes;
/** \brief Total number of bytes occupied by all D3D12MA::Allocation objects.
Always less or equal than `BlockBytes`.
Difference `(BlockBytes - AllocationBytes)` is the amount of memory allocated from D3D12
but unused by any D3D12MA::Allocation.
*/
UINT64 AllocationBytes;
};
/** \brief More detailed statistics than D3D12MA::Statistics.
These are slower to calculate. Use for debugging purposes.
See functions: D3D12MA::Allocator::CalculateStatistics(), D3D12MA::Pool::CalculateStatistics().
Averages are not provided because they can be easily calculated as:
\code
UINT64 AllocationSizeAvg = DetailedStats.Statistics.AllocationBytes / detailedStats.Statistics.AllocationCount;
UINT64 UnusedBytes = DetailedStats.Statistics.BlockBytes - DetailedStats.Statistics.AllocationBytes;
UINT64 UnusedRangeSizeAvg = UnusedBytes / DetailedStats.UnusedRangeCount;
\endcode
*/
struct DetailedStatistics
{
/// Basic statistics.
Statistics Stats;
/// Number of free ranges of memory between allocations.
UINT UnusedRangeCount;
/// Smallest allocation size. `UINT64_MAX` if there are 0 allocations.
UINT64 AllocationSizeMin;
/// Largest allocation size. 0 if there are 0 allocations.
UINT64 AllocationSizeMax;
/// Smallest empty range size. `UINT64_MAX` if there are 0 empty ranges.
UINT64 UnusedRangeSizeMin;
/// Largest empty range size. 0 if there are 0 empty ranges.
UINT64 UnusedRangeSizeMax;
};
/** \brief General statistics from current state of the allocator -
total memory usage across all memory heaps and segments.
These are slower to calculate. Use for debugging purposes.
See function D3D12MA::Allocator::CalculateStatistics().
*/
struct TotalStatistics
{
/** \brief One element for each type of heap located at the following indices:
- 0 = `D3D12_HEAP_TYPE_DEFAULT`
- 1 = `D3D12_HEAP_TYPE_UPLOAD`
- 2 = `D3D12_HEAP_TYPE_READBACK`
- 3 = `D3D12_HEAP_TYPE_CUSTOM`
- 4 = `D3D12_HEAP_TYPE_GPU_UPLOAD`
*/
DetailedStatistics HeapType[5];
/** \brief One element for each memory segment group located at the following indices:
- 0 = `DXGI_MEMORY_SEGMENT_GROUP_LOCAL`
- 1 = `DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL`
Meaning of these segment groups is:
- When `IsUMA() == FALSE` (discrete graphics card):
- `DXGI_MEMORY_SEGMENT_GROUP_LOCAL` (index 0) represents GPU memory
(resources allocated in `D3D12_HEAP_TYPE_DEFAULT`, `D3D12_HEAP_TYPE_GPU_UPLOAD` or `D3D12_MEMORY_POOL_L1`).
- `DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL` (index 1) represents system memory
(resources allocated in `D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`, or `D3D12_MEMORY_POOL_L0`).
- When `IsUMA() == TRUE` (integrated graphics chip):
- `DXGI_MEMORY_SEGMENT_GROUP_LOCAL` = (index 0) represents memory shared for all the resources.
- `DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL` = (index 1) is unused and always 0.
*/
DetailedStatistics MemorySegmentGroup[2];
/// Total statistics from all memory allocated from D3D12.
DetailedStatistics Total;
};
/** \brief %Statistics of current memory usage and available budget for a specific memory segment group.
These are fast to calculate. See function D3D12MA::Allocator::GetBudget().
*/
struct Budget
{
/** \brief %Statistics fetched from the library.
*/
Statistics Stats;
/** \brief Estimated current memory usage of the program.
Fetched from system using `IDXGIAdapter3::QueryVideoMemoryInfo` if possible.
It might be different than `BlockBytes` (usually higher) due to additional implicit objects
also occupying the memory, like swapchain, pipeline state objects, descriptor heaps, command lists, or
heaps and resources allocated outside of this library, if any.
*/
UINT64 UsageBytes;
/** \brief Estimated amount of memory available to the program.
Fetched from system using `IDXGIAdapter3::QueryVideoMemoryInfo` if possible.
It might be different (most probably smaller) than memory capacity returned
by D3D12MA::Allocator::GetMemoryCapacity() due to factors
external to the program, decided by the operating system.
Difference `BudgetBytes - UsageBytes` is the amount of additional memory that can probably
be allocated without problems. Exceeding the budget may result in various problems.
*/
UINT64 BudgetBytes;
};
/// \brief Represents single memory allocation done inside VirtualBlock.
struct D3D12MA_API VirtualAllocation
{
/// \brief Unique idenitfier of current allocation. 0 means null/invalid.
AllocHandle AllocHandle;
};
/** \brief Represents single memory allocation.
It may be either implicit memory heap dedicated to a single resource or a
specific region of a bigger heap plus unique offset.
To create such object, fill structure D3D12MA::ALLOCATION_DESC and call function
Allocator::CreateResource.
The object remembers size and some other information.
To retrieve this information, use methods of this class.
The object also remembers `ID3D12Resource` and "owns" a reference to it,
so it calls `%Release()` on the resource when destroyed.
*/
class D3D12MA_API Allocation : public IUnknownImpl
{
public:
/** \brief Returns offset in bytes from the start of memory heap.
You usually don't need to use this offset. If you create a buffer or a texture together with the allocation using function
D3D12MA::Allocator::CreateResource, functions that operate on that resource refer to the beginning of the resource,
not entire memory heap.
If the Allocation represents committed resource with implicit heap, returns 0.
*/
UINT64 GetOffset() const;
/// Returns alignment that resource was created with.
UINT64 GetAlignment() const { return m_Alignment; }
/** \brief Returns size in bytes of the allocation.
- If you created a buffer or a texture together with the allocation using function D3D12MA::Allocator::CreateResource,
this is the size of the resource returned by `ID3D12Device::GetResourceAllocationInfo`.
- For allocations made out of bigger memory blocks, this also is the size of the memory region assigned exclusively to this allocation.
- For resources created as committed, this value may not be accurate. DirectX implementation may optimize memory usage internally
so that you may even observe regions of `ID3D12Resource::GetGPUVirtualAddress()` + Allocation::GetSize() to overlap in memory and still work correctly.
*/
UINT64 GetSize() const { return m_Size; }
/** \brief Returns D3D12 resource associated with this object.
Calling this method doesn't increment resource's reference counter.
*/
ID3D12Resource* GetResource() const { return m_Resource; }
/// Releases the resource currently pointed by the allocation (if any), sets it to new one, incrementing its reference counter (if not null).
void SetResource(ID3D12Resource* pResource);
/** \brief Returns memory heap that the resource is created in.
If the Allocation represents committed resource with implicit heap, returns NULL.
*/
ID3D12Heap* GetHeap() const;
/// Changes custom pointer for an allocation to a new value.
void SetPrivateData(void* pPrivateData) { m_pPrivateData = pPrivateData; }
/// Get custom pointer associated with the allocation.
void* GetPrivateData() const { return m_pPrivateData; }
/** \brief Associates a name with the allocation object. This name is for use in debug diagnostics and tools.
Internal copy of the string is made, so the memory pointed by the argument can be
changed of freed immediately after this call.
`Name` can be null.
*/
void SetName(LPCWSTR Name);
/** \brief Returns the name associated with the allocation object.
Returned string points to an internal copy.
If no name was associated with the allocation, returns null.
*/
LPCWSTR GetName() const { return m_Name; }
protected:
void ReleaseThis() override;
private:
friend class AllocatorPimpl;
friend class BlockVector;
friend class CommittedAllocationList;
friend class JsonWriter;
friend class BlockMetadata_Linear;
friend class DefragmentationContextPimpl;
friend struct CommittedAllocationListItemTraits;
template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);
template<typename T> friend class PoolAllocator;
enum Type
{
TYPE_COMMITTED,
TYPE_PLACED,
TYPE_HEAP,
TYPE_COUNT
};
AllocatorPimpl* m_Allocator;
UINT64 m_Size;
UINT64 m_Alignment;
ID3D12Resource* m_Resource;
void* m_pPrivateData;
wchar_t* m_Name;
union
{
struct
{
CommittedAllocationList* list;
Allocation* prev;
Allocation* next;
} m_Committed;
struct
{
AllocHandle allocHandle;
NormalBlock* block;
} m_Placed;
struct
{
// Beginning must be compatible with m_Committed.
CommittedAllocationList* list;
Allocation* prev;
Allocation* next;
ID3D12Heap* heap;
} m_Heap;
};
struct PackedData
{
public:
PackedData() :
m_Type(0), m_ResourceDimension(0), m_ResourceFlags(0), m_TextureLayout(0) { }
Type GetType() const { return (Type)m_Type; }
D3D12_RESOURCE_DIMENSION GetResourceDimension() const { return (D3D12_RESOURCE_DIMENSION)m_ResourceDimension; }
D3D12_RESOURCE_FLAGS GetResourceFlags() const { return (D3D12_RESOURCE_FLAGS)m_ResourceFlags; }
D3D12_TEXTURE_LAYOUT GetTextureLayout() const { return (D3D12_TEXTURE_LAYOUT)m_TextureLayout; }
void SetType(Type type);
void SetResourceDimension(D3D12_RESOURCE_DIMENSION resourceDimension);
void SetResourceFlags(D3D12_RESOURCE_FLAGS resourceFlags);
void SetTextureLayout(D3D12_TEXTURE_LAYOUT textureLayout);
private:
UINT m_Type : 2; // enum Type
UINT m_ResourceDimension : 3; // enum D3D12_RESOURCE_DIMENSION
UINT m_ResourceFlags : 24; // flags D3D12_RESOURCE_FLAGS
UINT m_TextureLayout : 9; // enum D3D12_TEXTURE_LAYOUT
} m_PackedData;
Allocation(AllocatorPimpl* allocator, UINT64 size, UINT64 alignment);
// Nothing here, everything already done in Release.
virtual ~Allocation() = default;
void InitCommitted(CommittedAllocationList* list);
void InitPlaced(AllocHandle allocHandle, NormalBlock* block);
void InitHeap(CommittedAllocationList* list, ID3D12Heap* heap);
void SwapBlockAllocation(Allocation* allocation);
// If the Allocation represents committed resource with implicit heap, returns UINT64_MAX.
AllocHandle GetAllocHandle() const;
NormalBlock* GetBlock();
template<typename D3D12_RESOURCE_DESC_T>
void SetResourcePointer(ID3D12Resource* resource, const D3D12_RESOURCE_DESC_T* pResourceDesc);
void FreeName();
D3D12MA_CLASS_NO_COPY(Allocation)
};
/// Flags to be passed as DEFRAGMENTATION_DESC::Flags.
enum DEFRAGMENTATION_FLAGS
{
/** Use simple but fast algorithm for defragmentation.
May not achieve best results but will require least time to compute and least allocations to copy.
*/
DEFRAGMENTATION_FLAG_ALGORITHM_FAST = 0x1,
/** Default defragmentation algorithm, applied also when no `ALGORITHM` flag is specified.
Offers a balance between defragmentation quality and the amount of allocations and bytes that need to be moved.
*/
DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED = 0x2,
/** Perform full defragmentation of memory.
Can result in notably more time to compute and allocations to copy, but will achieve best memory packing.
*/
DEFRAGMENTATION_FLAG_ALGORITHM_FULL = 0x4,
/// A bit mask to extract only `ALGORITHM` bits from entire set of flags.
DEFRAGMENTATION_FLAG_ALGORITHM_MASK =
DEFRAGMENTATION_FLAG_ALGORITHM_FAST |
DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED |
DEFRAGMENTATION_FLAG_ALGORITHM_FULL
};
/** \brief Parameters for defragmentation.
To be used with functions Allocator::BeginDefragmentation() and Pool::BeginDefragmentation().
*/
struct DEFRAGMENTATION_DESC
{
/// Flags.
DEFRAGMENTATION_FLAGS Flags;
/** \brief Maximum numbers of bytes that can be copied during single pass, while moving allocations to different places.
0 means no limit.
*/
UINT64 MaxBytesPerPass;
/** \brief Maximum number of allocations that can be moved during single pass to a different place.
0 means no limit.
*/
UINT32 MaxAllocationsPerPass;
};
/// Operation performed on single defragmentation move.
enum DEFRAGMENTATION_MOVE_OPERATION
{
/** Resource has been recreated at `pDstTmpAllocation`, data has been copied, old resource has been destroyed.
`pSrcAllocation` will be changed to point to the new place. This is the default value set by DefragmentationContext::BeginPass().
*/
DEFRAGMENTATION_MOVE_OPERATION_COPY = 0,
/// Set this value if you cannot move the allocation. New place reserved at `pDstTmpAllocation` will be freed. `pSrcAllocation` will remain unchanged.
DEFRAGMENTATION_MOVE_OPERATION_IGNORE = 1,
/// 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`.
DEFRAGMENTATION_MOVE_OPERATION_DESTROY = 2,
};
/// Single move of an allocation to be done for defragmentation.
struct DEFRAGMENTATION_MOVE
{
/** \brief Operation to be performed on the allocation by DefragmentationContext::EndPass().
Default value is #DEFRAGMENTATION_MOVE_OPERATION_COPY. You can modify it.
*/
DEFRAGMENTATION_MOVE_OPERATION Operation;
/// %Allocation that should be moved.
Allocation* pSrcAllocation;
/** \brief Temporary allocation pointing to destination memory that will replace `pSrcAllocation`.
Use it to retrieve new `ID3D12Heap` and offset to create new `ID3D12Resource` and then store it here via Allocation::SetResource().
\warning Do not store this allocation in your data structures! It exists only temporarily, for the duration of the defragmentation pass,
to be used for storing newly created resource. DefragmentationContext::EndPass() will destroy it and make `pSrcAllocation` point to this memory.
*/
Allocation* pDstTmpAllocation;
};
/** \brief Parameters for incremental defragmentation steps.
To be used with function DefragmentationContext::BeginPass().
*/
struct DEFRAGMENTATION_PASS_MOVE_INFO
{
/// Number of elements in the `pMoves` array.
UINT32 MoveCount;
/** \brief Array of moves to be performed by the user in the current defragmentation pass.
Pointer to an array of `MoveCount` elements, owned by %D3D12MA, created in DefragmentationContext::BeginPass(), destroyed in DefragmentationContext::EndPass().
For each element, you should:
1. Create a new resource in the place pointed by `pMoves[i].pDstTmpAllocation->GetHeap()` + `pMoves[i].pDstTmpAllocation->GetOffset()`.
2. Store new resource in `pMoves[i].pDstTmpAllocation` by using Allocation::SetResource(). It will later replace old resource from `pMoves[i].pSrcAllocation`.
3. Copy data from the `pMoves[i].pSrcAllocation` e.g. using `D3D12GraphicsCommandList::CopyResource`.
4. Make sure these commands finished executing on the GPU.
Only then you can finish defragmentation pass by calling DefragmentationContext::EndPass().
After this call, the allocation will point to the new place in memory.
Alternatively, if you cannot move specific allocation,
you can set DEFRAGMENTATION_MOVE::Operation to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_IGNORE.
Alternatively, if you decide you want to completely remove the allocation,
set DEFRAGMENTATION_MOVE::Operation to D3D12MA::DEFRAGMENTATION_MOVE_OPERATION_DESTROY.
Then, after DefragmentationContext::EndPass() the allocation will be released.
*/
DEFRAGMENTATION_MOVE* pMoves;
};
/// %Statistics returned for defragmentation process by function DefragmentationContext::GetStats().
struct DEFRAGMENTATION_STATS
{
/// Total number of bytes that have been copied while moving allocations to different places.
UINT64 BytesMoved;
/// Total number of bytes that have been released to the system by freeing empty heaps.
UINT64 BytesFreed;
/// Number of allocations that have been moved to different places.
UINT32 AllocationsMoved;
/// Number of empty `ID3D12Heap` objects that have been released to the system.
UINT32 HeapsFreed;
};
/** \brief Represents defragmentation process in progress.
You can create this object using Allocator::BeginDefragmentation (for default pools) or
Pool::BeginDefragmentation (for a custom pool).
*/
class D3D12MA_API DefragmentationContext : public IUnknownImpl
{
public:
/** \brief Starts single defragmentation pass.
\param[out] pPassInfo Computed informations for current pass.
\returns
- `S_OK` if no more moves are possible. Then you can omit call to DefragmentationContext::EndPass() and simply end whole defragmentation.
- `S_FALSE` if there are pending moves returned in `pPassInfo`. You need to perform them, call DefragmentationContext::EndPass(),
and then preferably try another pass with DefragmentationContext::BeginPass().
*/
HRESULT BeginPass(DEFRAGMENTATION_PASS_MOVE_INFO* pPassInfo);
/** \brief Ends single defragmentation pass.
\param pPassInfo Computed informations for current pass filled by DefragmentationContext::BeginPass() and possibly modified by you.
\return Returns `S_OK` if no more moves are possible or `S_FALSE` if more defragmentations are possible.
Ends incremental defragmentation pass and commits all defragmentation moves from `pPassInfo`.
After this call:
- %Allocation at `pPassInfo[i].pSrcAllocation` that had `pPassInfo[i].Operation ==` #DEFRAGMENTATION_MOVE_OPERATION_COPY
(which is the default) will be pointing to the new destination place.
- %Allocation at `pPassInfo[i].pSrcAllocation` that had `pPassInfo[i].operation ==` #DEFRAGMENTATION_MOVE_OPERATION_DESTROY
will be released.
If no more moves are possible you can end whole defragmentation.
*/
HRESULT EndPass(DEFRAGMENTATION_PASS_MOVE_INFO* pPassInfo);
/** \brief Returns statistics of the defragmentation performed so far.
*/
void GetStats(DEFRAGMENTATION_STATS* pStats);
protected:
void ReleaseThis() override;
private:
friend class Pool;
friend class Allocator;
template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);
DefragmentationContextPimpl* m_Pimpl;
DefragmentationContext(AllocatorPimpl* allocator,
const DEFRAGMENTATION_DESC& desc,
BlockVector* poolVector);
~DefragmentationContext();
D3D12MA_CLASS_NO_COPY(DefragmentationContext)
};
/// \brief Bit flags to be used with POOL_DESC::Flags.
enum POOL_FLAGS
{
/// Zero
POOL_FLAG_NONE = 0,
/** \brief Enables alternative, linear allocation algorithm in this pool.
Specify this flag to enable linear allocation algorithm, which always creates
new allocations after last one and doesn't reuse space from allocations freed in
between. It trades memory consumption for simplified algorithm and data
structure, which has better performance and uses less memory for metadata.
By using this flag, you can achieve behavior of free-at-once, stack,
ring buffer, and double stack.
For details, see documentation chapter \ref linear_algorithm.
*/
POOL_FLAG_ALGORITHM_LINEAR = 0x1,
/** \brief Optimization, allocate MSAA textures as committed resources always.
Specify this flag to create MSAA textures with implicit heaps, as if they were created
with flag D3D12MA::ALLOCATION_FLAG_COMMITTED. Usage of this flags enables pool to create its heaps
on smaller alignment not suitable for MSAA textures.
*/
POOL_FLAG_MSAA_TEXTURES_ALWAYS_COMMITTED = 0x2,
// Bit mask to extract only `ALGORITHM` bits from entire set of flags.
POOL_FLAG_ALGORITHM_MASK = POOL_FLAG_ALGORITHM_LINEAR
};
/// \brief Parameters of created D3D12MA::Pool object. To be used with D3D12MA::Allocator::CreatePool.
struct POOL_DESC
{
/// Flags.
POOL_FLAGS Flags;
/** \brief The parameters of memory heap where allocations of this pool should be placed.
In the simplest case, just fill it with zeros and set `Type` to one of: `D3D12_HEAP_TYPE_DEFAULT`,
`D3D12_HEAP_TYPE_UPLOAD`, `D3D12_HEAP_TYPE_READBACK`. Additional parameters can be used e.g. to utilize UMA.
*/
D3D12_HEAP_PROPERTIES HeapProperties;
/** \brief Heap flags to be used when allocating heaps of this pool.
It should contain one of these values, depending on type of resources you are going to create in this heap:
`D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS`,
`D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES`,
`D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES`.
Except if ResourceHeapTier = 2, then it may be `D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES` = 0.
You can specify additional flags if needed.
*/
D3D12_HEAP_FLAGS HeapFlags;
/** \brief Size of a single heap (memory block) to be allocated as part of this pool, in bytes. Optional.
Specify nonzero to set explicit, constant size of memory blocks used by this pool.
Leave 0 to use default and let the library manage block sizes automatically.
Then sizes of particular blocks may vary.
*/
UINT64 BlockSize;
/** \brief Minimum number of heaps (memory blocks) to be always allocated in this pool, even if they stay empty. Optional.
Set to 0 to have no preallocated blocks and allow the pool be completely empty.
*/
UINT MinBlockCount;
/** \brief Maximum number of heaps (memory blocks) that can be allocated in this pool. Optional.
Set to 0 to use default, which is `UINT64_MAX`, which means no limit.
Set to same value as D3D12MA::POOL_DESC::MinBlockCount to have fixed amount of memory allocated
throughout whole lifetime of this pool.
*/
UINT MaxBlockCount;
/** \brief Additional minimum alignment to be used for all allocations created from this pool. Can be 0.
Leave 0 (default) not to impose any additional alignment. If not 0, it must be a power of two.
*/
UINT64 MinAllocationAlignment;
/** \brief Additional parameter allowing pool to create resources with passed protected session.
If not null then all the heaps and committed resources will be created with this parameter.
Valid only if ID3D12Device4 interface is present in current Windows SDK!
*/
ID3D12ProtectedResourceSession* pProtectedSession;
/** \brief Residency priority to be set for all allocations made in this pool. Optional.
Set this parameter to one of the possible enum values e.g. `D3D12_RESIDENCY_PRIORITY_HIGH`
to apply specific residency priority to all allocations made in this pool:
`ID3D12Heap` memory blocks used to sub-allocate for placed resources, as well as
committed resources or heaps created when D3D12MA::ALLOCATION_FLAG_COMMITTED is used.
This can increase/decrease chance that the memory will be pushed out from VRAM
to system RAM when the system runs out of memory, which is invisible to the developer
using D3D12 API while it can degrade performance.
Priority is set using function `ID3D12Device1::SetResidencyPriority`.
It is performed only when `ID3D12Device1` interface is defined and successfully obtained.
Otherwise, this parameter is ignored.
This parameter is optional. If you set it to `D3D12_RESIDENCY_PRIORITY(0)`,
residency priority will not be set for allocations made in this pool.
There is no equivalent parameter for allocations made in default pools.
If you want to set residency priority for such allocation, you need to do it manually:
allocate with D3D12MA::ALLOCATION_FLAG_COMMITTED and call
`ID3D12Device1::SetResidencyPriority`, passing `allocation->GetResource()`.
*/
D3D12_RESIDENCY_PRIORITY ResidencyPriority;
};
/** \brief Custom memory pool
Represents a separate set of heaps (memory blocks) that can be used to create
D3D12MA::Allocation-s and resources in it. Usually there is no need to create custom
pools - creating resources in default pool is sufficient.
To create custom pool, fill D3D12MA::POOL_DESC and call D3D12MA::Allocator::CreatePool.
*/
class D3D12MA_API Pool : public IUnknownImpl
{
public:
/** \brief Returns copy of parameters of the pool.
These are the same parameters as passed to D3D12MA::Allocator::CreatePool.
*/
POOL_DESC GetDesc() const;
/** \brief Retrieves basic statistics of the custom pool that are fast to calculate.
\param[out] pStats %Statistics of the current pool.
*/
void GetStatistics(Statistics* pStats);
/** \brief Retrieves detailed statistics of the custom pool that are slower to calculate.
\param[out] pStats %Statistics of the current pool.
*/
void CalculateStatistics(DetailedStatistics* pStats);
/** \brief Associates a name with the pool. This name is for use in debug diagnostics and tools.
Internal copy of the string is made, so the memory pointed by the argument can be
changed of freed immediately after this call.
`Name` can be NULL.
*/
void SetName(LPCWSTR Name);
/** \brief Returns the name associated with the pool object.
Returned string points to an internal copy.
If no name was associated with the allocation, returns NULL.
*/
LPCWSTR GetName() const;
/** \brief Begins defragmentation process of the current pool.
\param pDesc Structure filled with parameters of defragmentation.
\param[out] ppContext Context object that will manage defragmentation.
\returns
- `S_OK` if defragmentation can begin.
- `E_NOINTERFACE` if defragmentation is not supported.
For more information about defragmentation, see documentation chapter:
[Defragmentation](@ref defragmentation).
*/
HRESULT BeginDefragmentation(const DEFRAGMENTATION_DESC* pDesc, DefragmentationContext** ppContext);
protected:
void ReleaseThis() override;
private:
friend class Allocator;
friend class AllocatorPimpl;
template<typename T> friend void D3D12MA_DELETE(const ALLOCATION_CALLBACKS&, T*);
PoolPimpl* m_Pimpl;
Pool(Allocator* allocator, const POOL_DESC &desc);
~Pool();
D3D12MA_CLASS_NO_COPY(Pool)
};