TachyonUI 1.1.0
High-performance UI for building tools.
Loading...
Searching...
No Matches
d3d12_device.h
Go to the documentation of this file.
1#pragma once
2
3// Inside the Direct3D 12 backend: the device and what its graphics context and window contexts
4// share. The queue's one fence counts every submit, the way the Vulkan backend's timeline does:
5// a frame slot waits on it, and what's let go waits for it before it's freed.
6
11
12#include <D3D12MemAlloc.h>
13
14#include <array>
15#include <atomic>
16#include <functional>
17#include <memory>
18#include <mutex>
19#include <optional>
20#include <span>
21#include <string>
22#include <unordered_map>
23#include <unordered_set>
24#include <vector>
25
26namespace tachyon
27{
28 class StyleManager;
29 class GradientManager;
30}
31
32namespace tachyon::d3d12
33{
35 struct Buffer
36 {
37 ComPtr<D3D12MA::Allocation> allocation;
38 void* mapped = nullptr;
39 D3D12_GPU_VIRTUAL_ADDRESS address = 0;
40 UINT64 size = 0;
41
42 ID3D12Resource* Resource() const { return allocation ? allocation->GetResource() : nullptr; }
43 explicit operator bool() const { return allocation != nullptr; }
44 };
45
48 class D3D12Image final : public Image
49 {
50 public:
51 ComPtr<D3D12MA::Allocation> allocation;
52 ID3D12Resource* external = nullptr;
53 DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
57 std::optional<ImageFormat> sourceFormat;
58
59 ID3D12Resource* Resource() const { return allocation ? allocation->GetResource() : external; }
60 };
61
64 uint32_t SamplerSlot(Sampler sampler);
65
70 class D3D12ImageSet final : public ImageSet
71 {
72 public:
73 bool Create(ID3D12Device* device, uint32_t capacity);
74
75 void Clear() override;
76 ImageIndex Add(Image* image) override;
77 void Remove(ImageIndex index) override;
81 void SetImage(ImageIndex index, D3D12Image* image);
83 uint64_t Writes() const { return m_writes; }
84
85 uint32_t Capacity() const { return m_capacity; }
87 uint32_t SlotsInUse() const { return uint32_t(m_images.size()); }
88 D3D12_CPU_DESCRIPTOR_HANDLE CpuStart() const { return m_heap->GetCPUDescriptorHandleForHeapStart(); }
90 const std::vector<uint32_t>& SamplerSlots() const { return m_samplers; }
91
92 private:
93 ImageIndex Allocate();
94 void WriteSlot(uint32_t slot);
95
96 ID3D12Device* m_device = nullptr;
97 ComPtr<ID3D12DescriptorHeap> m_heap;
98 UINT m_descriptorSize = 0;
99 uint32_t m_capacity = 0;
100 std::vector<D3D12Image*> m_images;
101 std::vector<uint32_t> m_samplers;
102 std::vector<uint32_t> m_free;
103 uint64_t m_writes = 0;
104 };
105
107 {
110 std::string gpuPreference;
111 std::string deviceName;
112 bool debugLayer = false;
113 uint32_t imageSlots = 4096;
114
115 ComPtr<IDXGIFactory6> factory;
116 ComPtr<IDXGIAdapter1> adapter;
117 ComPtr<ID3D12Device> device;
118 ComPtr<ID3D12CommandQueue> queue;
119 ComPtr<D3D12MA::Allocator> allocator;
120 ComPtr<ID3D12InfoQueue1> infoQueue;
122
124 ComPtr<ID3D12Fence> submitFence;
126 std::atomic<UINT64> submitted = 0;
129 std::atomic<bool> removed = false;
131 void NoteFailure(HRESULT hr, const char* what);
132 HANDLE waitEvent = nullptr;
133
135 std::vector<std::pair<ComPtr<ID3D12Fence>, UINT64>> frameWaits;
137 UINT64 Submit(ID3D12CommandList* list);
139 void Wait(UINT64 value);
141 void WaitIdle();
142 UINT64 Completed() const { return submitFence ? submitFence->GetCompletedValue() : 0; }
143
144 // ---- Memory -------------------------------------------------------------------
149
153 void DestroyAfterGpu(ComPtr<D3D12MA::Allocation> allocation, UINT64 afterValue);
154 void DestroyAfterGpu(std::unique_ptr<D3D12Image> image, UINT64 afterValue);
155 void DestroyAfterGpu(ComPtr<ID3D12Resource> resource, UINT64 afterValue);
158
159 struct Garbage
160 {
161 UINT64 afterValue = 0;
162 ComPtr<D3D12MA::Allocation> allocation;
163 std::unique_ptr<D3D12Image> image;
164 ComPtr<ID3D12Resource> resource;
165 };
166 std::mutex garbageMutex;
167 std::vector<Garbage> garbage;
168
169 // ---- Uploads, recorded at the start of the next window frame -----------------
173 {
174 D3D12Image* image = nullptr;
176 D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint {};
177 uint32_t firstRow = 0;
178 bool partial = false;
179 };
180 std::mutex uploadMutex;
181 std::vector<ImageUpload> imageUploads;
184 {
185 std::vector<ImageUpload> images;
186 std::vector<D3D12_RESOURCE_BARRIER> barriers;
187 std::vector<const D3D12Image*> copying;
189
191 void RecordPendingUploads(ID3D12GraphicsCommandList* list);
192
193 // ---- Resident buffers (RHI::UploadResidentBuffers) ----------------------------
194 struct Resident
195 {
198 bool ready = false;
199 };
200 std::unordered_map<RHI::ResidentBufferId, Resident> residents;
203 std::vector<RHI::ResidentBufferId> pendingResidents;
205
206 RHI::ResidentBufferId CreateResidentBuffer(std::span<const RHI::UploadRequest> requests,
207 std::span<DeviceAddress> addresses);
210
211 // ---- Images ------------------------------------------------------------------------
214 std::unordered_set<D3D12Image*> liveImages;
215
216 // ---- What every frame draws with ------------------------------------------------
222 std::vector<ImageIndex> gradientPages;
225 float lastTime = 0.0f;
226 ComPtr<ID3D12RootSignature> rootSignature;
227 std::vector<ComPtr<ID3D12PipelineState>> pipelineStates;
228 std::array<RHI::GpuPipeline, kPrimitiveKindCount> pipelines {};
231 uint32_t quadCapacity = 0;
233
236 bool EnsureQuadIndices(ID3D12GraphicsCommandList* list, uint32_t quads);
237
238 // ---- Scenes the app draws (RenderScene) ----------------------------------------
239 static constexpr DXGI_FORMAT kSceneColorFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
240 static constexpr uint64_t kSceneKeepFrames = 4;
241
244 struct Scene
245 {
246 D3D12Image* color = nullptr;
247 D3D12Image* depth = nullptr;
248 ComPtr<ID3D12DescriptorHeap> rtv;
249 ComPtr<ID3D12DescriptorHeap> dsv;
253 uint64_t lastFrame = 0;
254 };
256 {
260 std::function<void(const ScenePayload& scene)> record;
261 };
262 std::unordered_map<ID, Scene> scenes;
263
264 // ---- A host's textures (RegisterExternalImage, SetWindowImageTarget) -----------
266 std::unordered_map<uint32_t, std::unique_ptr<D3D12Image>> externalImages;
268 std::unordered_map<ID, ID3D12Resource*> imageTargets;
269 std::vector<SceneRequest> sceneRequests;
270 uint64_t sceneFrame = 0;
271
273 void RecordScenes(ID3D12GraphicsCommandList* list, ID window);
274
278 D3D12Image* CreateTargetImage(uint2 size, DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state,
279 const D3D12_CLEAR_VALUE* clear, Sampler sampler);
280 };
281}
The atlas that the colors of color styles are baked into: pages of 2D textures, one row per gradient,...
Definition gui_gradient_manager.h:65
The images the shaders can sample, each at an ImageIndex. Implemented by the backend.
Definition gui_image.h:106
An image made by GraphicsContext::CreateImage; the backend defines its contents.
Definition gui_image.h:102
What GraphicsContext::RenderScene's record gets: the backend's recording state, as the struct of the ...
Definition gui_graphics_api.h:41
Bakes serializable Styles into deduplicated runtime layout/visual styles; a StyleRef holds indices in...
Definition gui_style_manager.h:39
The images the shaders sample, by ImageIndex (1-based; the shaders' slot is one less).
Definition d3d12_device.h:71
ImageIndex Add(Image *image) override
Adds an image (not owned) and returns its index.
D3D12_CPU_DESCRIPTOR_HANDLE CpuStart() const
Definition d3d12_device.h:88
ImageIndex ReserveIndex()
A slot with no image yet, for one that comes later (a text atlas page).
void Remove(ImageIndex index) override
Frees the index for reuse; the image itself stays.
void Clear() override
Removes every image, freeing all indices.
uint64_t Writes() const
How many views were written into the heap.
Definition d3d12_device.h:83
void SetImage(ImageIndex index, D3D12Image *image)
Points the slot at another image; the image it holds is no change.
uint32_t SlotsInUse() const
One past the highest slot handed out: what a frame copies.
Definition d3d12_device.h:87
const std::vector< uint32_t > & SamplerSlots() const
Each slot's static sampler, as t7 holds them.
Definition d3d12_device.h:90
uint32_t Capacity() const
Definition d3d12_device.h:85
bool Create(ID3D12Device *device, uint32_t capacity)
An image (GraphicsContext::CreateImage): a texture sampled by the shaders.
Definition d3d12_device.h:49
ComPtr< D3D12MA::Allocation > allocation
Definition d3d12_device.h:51
uint2 size
Definition d3d12_device.h:55
std::optional< ImageFormat > sourceFormat
Made by CreateImage from pixels of this format: UpdateImageRows can write into it.
Definition d3d12_device.h:57
DXGI_FORMAT format
Definition d3d12_device.h:53
ID3D12Resource * Resource() const
Definition d3d12_device.h:59
ID3D12Resource * external
Definition d3d12_device.h:52
Sampler sampler
Definition d3d12_device.h:54
uint64_t ResidentBufferId
GPU storage kept across frames (UploadResidentBuffers); 0 is none.
Definition gui_rhi.h:36
Sampler
How an image is filtered and addressed when sampled.
Definition gui_image.h:89
ImageIndex
Index of an image in the graphics context's image set, as the shaders sample it.
Definition gui_image.h:99
ResidentState
Where a resident buffer is.
Definition gui_rhi.h:40
@ NearestRepeat
Definition gui_image.h:92
@ Invalid
Definition gui_image.h:99
Definition d3d12_common.h:22
uint32_t SamplerSlot(Sampler sampler)
The static sampler (s0, s1, s2) the shaders sample an image with: its row in the per-image table at t...
Definition gui_logging.h:24
Definition gui_render_primitives.h:257
A 64-bit element ID whose bit layout depends on its IDMode.
Definition gui_id.h:23
Definition gui_base_types.h:394
A buffer in one of D3D12MA's heaps. An upload-heap buffer stays mapped (mapped).
Definition d3d12_device.h:36
void * mapped
Definition d3d12_device.h:38
UINT64 size
Definition d3d12_device.h:40
D3D12_GPU_VIRTUAL_ADDRESS address
Definition d3d12_device.h:39
ID3D12Resource * Resource() const
Definition d3d12_device.h:42
ComPtr< D3D12MA::Allocation > allocation
Definition d3d12_device.h:37
ComPtr< D3D12MA::Allocation > allocation
Definition d3d12_device.h:162
UINT64 afterValue
Definition d3d12_device.h:161
ComPtr< ID3D12Resource > resource
Definition d3d12_device.h:164
std::unique_ptr< D3D12Image > image
Definition d3d12_device.h:163
A whole image's pixels, or with partial a band of rows from firstRow written into an image already up...
Definition d3d12_device.h:173
D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint
Definition d3d12_device.h:176
Buffer staging
Definition d3d12_device.h:175
uint32_t firstRow
Definition d3d12_device.h:177
D3D12Image * image
Definition d3d12_device.h:174
Buffer gpu
Definition d3d12_device.h:196
Buffer staging
filled at once; copied into gpu by RecordPendingUploads
Definition d3d12_device.h:197
std::function< void(const ScenePayload &scene)> record
Definition d3d12_device.h:260
color4f clear
Definition d3d12_device.h:259
What RenderScene keeps for a key: its color texture (in the image set) and depth, both in liveImages,...
Definition d3d12_device.h:245
uint2 extent
Definition d3d12_device.h:251
ComPtr< ID3D12DescriptorHeap > rtv
Definition d3d12_device.h:248
color4f clear
the color texture's optimized clear
Definition d3d12_device.h:252
ImageIndex index
Definition d3d12_device.h:250
D3D12Image * color
Definition d3d12_device.h:246
D3D12Image * depth
Definition d3d12_device.h:247
ComPtr< ID3D12DescriptorHeap > dsv
Definition d3d12_device.h:249
uint64_t lastFrame
the frame it was last asked for
Definition d3d12_device.h:253
RecordPendingUploads' working lists, kept between frames for their storage.
Definition d3d12_device.h:184
std::vector< ImageUpload > images
Definition d3d12_device.h:185
std::vector< const D3D12Image * > copying
Definition d3d12_device.h:187
std::vector< D3D12_RESOURCE_BARRIER > barriers
Definition d3d12_device.h:186
Definition d3d12_device.h:107
std::vector< SceneRequest > sceneRequests
Definition d3d12_device.h:269
std::atomic< UINT64 > submitted
Atomic: DestroyImageAtEnd, on any thread, reads it.
Definition d3d12_device.h:126
uint64_t sceneFrame
Definition d3d12_device.h:270
void DestroyAfterGpu(ComPtr< D3D12MA::Allocation > allocation, UINT64 afterValue)
What's let go is freed once the GPU is past afterValue: the next submit (submitted + 1) for anything ...
HANDLE waitEvent
Definition d3d12_device.h:132
std::unordered_map< ID, ID3D12Resource * > imageTargets
The texture a render-to-image window is copied into, by window.
Definition d3d12_device.h:268
ComPtr< ID3D12RootSignature > rootSignature
Definition d3d12_device.h:226
bool EnsureQuadIndices(ID3D12GraphicsCommandList *list, uint32_t quads)
Grows the quads' index buffer to hold quads, its copy recorded into list before the draw that needs i...
void NoteFailure(HRESULT hr, const char *what)
Notes a failed call: logged, and when it says the device is gone, removed is set.
void RecordPendingUploads(ID3D12GraphicsCommandList *list)
Records the queued image and resident-buffer copies into list.
ComPtr< IDXGIAdapter1 > adapter
Definition d3d12_device.h:116
D3D12Image * CreateTargetImage(uint2 size, DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE *clear, Sampler sampler)
A texture the GPU draws into (a scene's), in liveImages so DestroyImageAtEnd frees it; null on failur...
GPUDrawPushConstants pushConstants
the styles' addresses and the time, from PrepareFrame
Definition d3d12_device.h:232
ComPtr< ID3D12Device > device
Definition d3d12_device.h:117
ExternalDevice external
the host's device and queue, when it gave them
Definition d3d12_device.h:109
std::vector< ComPtr< ID3D12PipelineState > > pipelineStates
by PrimitiveKind
Definition d3d12_device.h:227
void FlushDeletions()
Frees what the GPU is done with.
static constexpr uint64_t kSceneKeepFrames
a scene not asked for this long goes
Definition d3d12_device.h:240
ComPtr< D3D12MA::Allocator > allocator
GPU memory: buffers and textures in its heaps.
Definition d3d12_device.h:119
std::vector< Garbage > garbage
Definition d3d12_device.h:167
void Wait(UINT64 value)
Waits on the CPU until the fence reaches value.
Buffer CreateGpuBuffer(UINT64 size)
A buffer in GPU memory, made ready for a copy into it.
UINT64 Completed() const
Definition d3d12_device.h:142
Buffer quadIndices
p * 4 + { 0, 1, 3, 0, 3, 2 } for each quad p, in GPU memory.
Definition d3d12_device.h:230
std::vector< RHI::ResidentBufferId > pendingResidents
Made and not copied yet, oldest first; one let go of meanwhile is no longer in residents and is passe...
Definition d3d12_device.h:203
std::string deviceName
Definition d3d12_device.h:111
std::unordered_map< uint32_t, std::unique_ptr< D3D12Image > > externalImages
By image index: what the image set points at for a host's texture.
Definition d3d12_device.h:266
ComPtr< ID3D12CommandQueue > queue
Definition d3d12_device.h:118
static constexpr DXGI_FORMAT kSceneColorFormat
Definition d3d12_device.h:239
struct tachyon::d3d12::D3D12GraphicsContext::Impl::UploadScratch uploadScratch
RHI::ResidentBufferId CreateResidentBuffer(std::span< const RHI::UploadRequest > requests, std::span< DeviceAddress > addresses)
std::mutex uploadMutex
images are made on any thread
Definition d3d12_device.h:180
std::unordered_set< D3D12Image * > liveImages
Every image made and not let go for a frame (DeviceScope::Frame): those handed over for the applicati...
Definition d3d12_device.h:214
void DestroyAfterGpu(ComPtr< ID3D12Resource > resource, UINT64 afterValue)
ComPtr< ID3D12InfoQueue1 > infoQueue
Definition d3d12_device.h:120
StyleManager * lastStyles
PrepareFrame's, for a live resize's redraw.
Definition d3d12_device.h:223
std::vector< ImageUpload > imageUploads
Definition d3d12_device.h:181
ComPtr< ID3D12Fence > submitFence
Every submit signals the next value: submitted is the last one signalled.
Definition d3d12_device.h:124
std::vector< std::pair< ComPtr< ID3D12Fence >, UINT64 > > frameWaits
What the next submit waits for on the queue (AddFrameWait), a fence once each.
Definition d3d12_device.h:135
std::unordered_map< RHI::ResidentBufferId, Resident > residents
Definition d3d12_device.h:200
RHI::ResidentBufferId nextResident
Definition d3d12_device.h:204
RHI::ResidentBufferId boxStyles
The box styles in GPU memory (a resident buffer), made again when they change; 0: none.
Definition d3d12_device.h:219
std::array< RHI::GpuPipeline, kPrimitiveKindCount > pipelines
Definition d3d12_device.h:228
void DestroyAfterGpu(std::unique_ptr< D3D12Image > image, UINT64 afterValue)
std::string gpuPreference
Definition d3d12_device.h:110
void ReleaseResident(RHI::ResidentBufferId id)
GradientManager * lastGradients
Definition d3d12_device.h:224
std::vector< ImageIndex > gradientPages
each gradient page's index in the image set
Definition d3d12_device.h:222
DWORD messageCallback
Definition d3d12_device.h:121
uint32_t imageSlots
asked for with SetImageSlotCount
Definition d3d12_device.h:113
float lastTime
Definition d3d12_device.h:225
void RecordScenes(ID3D12GraphicsCommandList *list, ID window)
Records the scenes asked for in window this frame, before its UI.
ComPtr< IDXGIFactory6 > factory
Definition d3d12_device.h:115
std::unordered_map< ID, Scene > scenes
Definition d3d12_device.h:262
DebugConfig debug
Definition d3d12_device.h:108
RHI::ResidentBufferId colorStyles
The color styles, with their gradient pages' slots, likewise.
Definition d3d12_device.h:221
std::mutex garbageMutex
images are let go on any thread
Definition d3d12_device.h:166
Buffer CreateUploadBuffer(UINT64 size)
A buffer the CPU writes and the GPU reads, mapped. Empty on failure.
void WaitIdle()
Waits until everything submitted so far is done, presents included.
std::atomic< bool > removed
The device was removed (a Present, a resize or the debug layer said so): told once,...
Definition d3d12_device.h:129
UINT64 Submit(ID3D12CommandList *list)
Runs list, after the frame waits, and signals the fence's next value, which it returns.
RHI::ResidentState ResidentState(RHI::ResidentBufferId id) const
uint32_t quadCapacity
Definition d3d12_device.h:231
D3D12ImageSet imageSet
Definition d3d12_device.h:217
bool debugLayer
the debug layer is on: its messages go to debug
Definition d3d12_device.h:112
Where the debug layer's messages go.
Definition d3d12_graphics_context.h:50
A host's device and queue, for the GUI to render on (SetExternalDevice) instead of making its own.
Definition d3d12_graphics_context.h:58
Definition gui_base_types.h:74