Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qrhid3d12_p.h
Go to the documentation of this file.
1// Copyright (C) 2023 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#ifndef QRHID3D12_P_H
6#define QRHID3D12_P_H
7
8//
9// W A R N I N G
10// -------------
11//
12// This file is not part of the Qt API. It exists purely as an
13// implementation detail. This header file may change from version to
14// version without notice, or even be removed.
15//
16// We mean it.
17//
18
19#include "qrhi_p.h"
20#include <QWindow>
21#include <QBitArray>
22
23#include <optional>
24#include <array>
25
26#include <d3d12.h>
27#include <d3d12sdklayers.h>
28#include <dxgi1_6.h>
29#include <dcomp.h>
30
31#include "D3D12MemAlloc.h"
32
33// ID3D12Device2 and ID3D12GraphicsCommandList1 and types and enums introduced
34// with those are hard requirements now. These should be declared in any
35// moderately recent d3d12.h, but if it is an SDK from before Windows 10
36// version 1703 then these types could be missing. In the absence of other
37// options, handle this by skipping all the code and making QRhi::create() fail
38// in such builds.
39#ifdef __ID3D12Device2_INTERFACE_DEFINED__
40#define QRHI_D3D12_AVAILABLE
41
42// Will use ID3D12GraphicsCommandList5 as long as the d3d12.h is new enough.
43// Otherwise, some features (VRS) will not be available.
44#ifdef __ID3D12GraphicsCommandList5_INTERFACE_DEFINED__
45#define QRHI_D3D12_CL5_AVAILABLE
46using D3D12GraphicsCommandList = ID3D12GraphicsCommandList5;
47#else
48using D3D12GraphicsCommandList = ID3D12GraphicsCommandList1;
49#endif
50
51#ifdef __ID3D12InfoQueue1_INTERFACE_DEFINED__
52#define QRHI_D3D12_INFOQUEUE1_AVAILABLE
53#endif
54
55#ifdef __ID3D12PipelineLibrary1_INTERFACE_DEFINED__
56#define QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
57#endif
58
59QT_BEGIN_NAMESPACE
60
61static const int QD3D12_FRAMES_IN_FLIGHT = 2;
62
63class QRhiD3D12;
64
65struct QD3D12Descriptor
66{
67 D3D12_CPU_DESCRIPTOR_HANDLE cpuHandle = {};
68 D3D12_GPU_DESCRIPTOR_HANDLE gpuHandle = {};
69
70 bool isValid() const { return cpuHandle.ptr != 0; }
71};
72
73struct QD3D12ReleaseQueue;
74
75struct QD3D12DescriptorHeap
76{
77 bool isValid() const { return heap && capacity; }
78 bool create(ID3D12Device *device,
79 quint32 descriptorCount,
80 D3D12_DESCRIPTOR_HEAP_TYPE heapType,
81 D3D12_DESCRIPTOR_HEAP_FLAGS heapFlags);
82 void createWithExisting(const QD3D12DescriptorHeap &other,
83 quint32 offsetInDescriptors,
84 quint32 descriptorCount);
85 void destroy();
86 void destroyWithDeferredRelease(QD3D12ReleaseQueue *releaseQueue);
87
88 QD3D12Descriptor get(quint32 count);
89 QD3D12Descriptor at(quint32 index) const;
90 quint32 remainingCapacity() const { return capacity - head; }
91
92 QD3D12Descriptor incremented(const QD3D12Descriptor &descriptor, quint32 offsetInDescriptors) const
93 {
94 D3D12_CPU_DESCRIPTOR_HANDLE cpuHandle = descriptor.cpuHandle;
95 cpuHandle.ptr += offsetInDescriptors * descriptorByteSize;
96 D3D12_GPU_DESCRIPTOR_HANDLE gpuHandle = descriptor.gpuHandle;
97 if (gpuHandle.ptr)
98 gpuHandle.ptr += offsetInDescriptors * descriptorByteSize;
99 return { cpuHandle, gpuHandle };
100 }
101
102 ID3D12DescriptorHeap *heap = nullptr;
103 quint32 capacity = 0;
104 QD3D12Descriptor heapStart;
105 quint32 head = 0;
106 quint32 descriptorByteSize = 0;
107 D3D12_DESCRIPTOR_HEAP_TYPE heapType;
108 D3D12_DESCRIPTOR_HEAP_FLAGS heapFlags;
109};
110
111struct QD3D12CpuDescriptorPool
112{
113 bool isValid() const { return !heaps.isEmpty(); }
114 bool create(ID3D12Device *device, D3D12_DESCRIPTOR_HEAP_TYPE heapType, const char *debugName = "");
115 void destroy();
116
117 QD3D12Descriptor allocate(quint32 count);
118 void release(const QD3D12Descriptor &descriptor, quint32 count);
119
120 static const int DESCRIPTORS_PER_HEAP = 256;
121
122 struct HeapWithMap {
123 QD3D12DescriptorHeap heap;
124 QBitArray map;
125 static HeapWithMap init(const QD3D12DescriptorHeap &heap, quint32 descriptorCount) {
126 HeapWithMap result;
127 result.heap = heap;
128 result.map.resize(descriptorCount);
129 return result;
130 }
131 };
132
133 ID3D12Device *device;
134 quint32 descriptorByteSize;
135 QVector<HeapWithMap> heaps;
136 const char *debugName;
137};
138
139struct QD3D12QueryHeap
140{
141 bool isValid() const { return heap && capacity; }
142 bool create(ID3D12Device *device,
143 quint32 queryCount,
144 D3D12_QUERY_HEAP_TYPE heapType);
145 void destroy();
146
147 ID3D12QueryHeap *heap = nullptr;
148 quint32 capacity = 0;
149};
150
151struct QD3D12StagingArea
152{
153 static const quint32 ALIGNMENT = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT; // 512 so good enough both for cb and texdata
154
155 struct Allocation {
156 quint8 *p = nullptr;
157 D3D12_GPU_VIRTUAL_ADDRESS gpuAddr = 0;
158 ID3D12Resource *buffer = nullptr;
159 quint32 bufferOffset = 0;
160 bool isValid() const { return p != nullptr; }
161 };
162
163 bool isValid() const { return allocation && mem.isValid(); }
164 bool create(QRhiD3D12 *rhi, quint32 capacity, D3D12_HEAP_TYPE heapType);
165 void destroy();
166 void destroyWithDeferredRelease(QD3D12ReleaseQueue *releaseQueue);
167
168 Allocation get(quint32 byteSize);
169
170 quint32 remainingCapacity() const
171 {
172 return capacity - head;
173 }
174
175 static quint32 allocSizeForArray(quint32 size, int count = 1)
176 {
177 return count * ((size + ALIGNMENT - 1) & ~(ALIGNMENT - 1));
178 }
179
180 Allocation mem;
181 ID3D12Resource *resource = nullptr;
182 D3D12MA::Allocation *allocation = nullptr;
183 quint32 head;
184 quint32 capacity;
185};
186
187struct QD3D12ObjectHandle
188{
189 quint32 index = 0;
190 quint32 generation = 0;
191
192 // the default, null handle is guaranteed to give ObjectPool::isValid() == false
193 bool isNull() const { return index == 0 && generation == 0; }
194};
195
196inline bool operator==(const QD3D12ObjectHandle &a, const QD3D12ObjectHandle &b) noexcept
197{
198 return a.index == b.index && a.generation == b.generation;
199}
200
201inline bool operator!=(const QD3D12ObjectHandle &a, const QD3D12ObjectHandle &b) noexcept
202{
203 return !(a == b);
204}
205
206template<typename T>
207struct QD3D12ObjectPool
208{
209 void create(const char *debugName = "")
210 {
211 this->debugName = debugName;
212 Q_ASSERT(data.isEmpty());
213 data.append(Data()); // index 0 is always invalid
214 }
215
216 void destroy() {
217 int leakCount = 0; // will nicely destroy everything here, but warn about it if enabled
218 for (Data &d : data) {
219 if (d.object.has_value()) {
220 leakCount += 1;
221 d.object->releaseResources();
222 }
223 }
224 data.clear();
225#ifndef QT_NO_DEBUG
226 // debug builds: just do it always
227 static bool leakCheck = true;
228#else
229 // release builds: opt-in
230 static bool leakCheck = qEnvironmentVariableIntValue("QT_RHI_LEAK_CHECK");
231#endif
232 if (leakCheck) {
233 if (leakCount > 0) {
234 qWarning("QD3D12ObjectPool::destroy(): Pool %p '%s' had %d unreleased objects",
235 this, debugName, leakCount);
236 }
237 }
238 }
239
240 bool isValid(const QD3D12ObjectHandle &handle) const
241 {
242 return handle.index > 0
243 && handle.index < quint32(data.count())
244 && handle.generation > 0
245 && handle.generation == data[handle.index].generation
246 && data[handle.index].object.has_value();
247 }
248
249 T lookup(const QD3D12ObjectHandle &handle) const
250 {
251 return isValid(handle) ? *data[handle.index].object : T();
252 }
253
254 const T *lookupRef(const QD3D12ObjectHandle &handle) const
255 {
256 return isValid(handle) ? &*data[handle.index].object : nullptr;
257 }
258
259 T *lookupRef(const QD3D12ObjectHandle &handle)
260 {
261 return isValid(handle) ? &*data[handle.index].object : nullptr;
262 }
263
264 QD3D12ObjectHandle add(const T &object)
265 {
266 Q_ASSERT(!data.isEmpty());
267 const quint32 count = quint32(data.count());
268 quint32 index = 1; // index 0 is always invalid
269 for (; index < count; ++index) {
270 if (!data[index].object.has_value())
271 break;
272 }
273 if (index < count) {
274 data[index].object = object;
275 quint32 &generation = data[index].generation;
276 generation += 1u;
277 return { index, generation };
278 } else {
279 data.append({ object, 1 });
280 return { count, 1 };
281 }
282 }
283
284 void remove(const QD3D12ObjectHandle &handle)
285 {
286 if (T *object = lookupRef(handle)) {
287 object->releaseResources();
288 data[handle.index].object.reset();
289 }
290 }
291
292 const char *debugName;
293 struct Data {
294 std::optional<T> object;
295 quint32 generation = 0;
296 };
297 QVector<Data> data;
298};
299
300struct QD3D12Resource
301{
302 ID3D12Resource *resource;
303 D3D12_RESOURCE_STATES state;
304 D3D12_RESOURCE_DESC desc;
305 D3D12MA::Allocation *allocation;
306 void *cpuMapPtr;
307 enum { UavUsageRead = 0x01, UavUsageWrite = 0x02 };
308 int uavUsage;
309 bool owns;
310
311 // note that this assumes the allocation (if there is one) and the resource
312 // are separately releaseable, see D3D12MemAlloc docs
313 static QD3D12ObjectHandle addToPool(QD3D12ObjectPool<QD3D12Resource> *pool,
314 ID3D12Resource *resource,
315 D3D12_RESOURCE_STATES state,
316 D3D12MA::Allocation *allocation = nullptr,
317 void *cpuMapPtr = nullptr)
318 {
319 Q_ASSERT(resource);
320 return pool->add({ resource, state, resource->GetDesc(), allocation, cpuMapPtr, 0, true });
321 }
322
323 // for QRhiTexture::createFrom() where the ID3D12Resource is not owned by us
324 static QD3D12ObjectHandle addNonOwningToPool(QD3D12ObjectPool<QD3D12Resource> *pool,
325 ID3D12Resource *resource,
326 D3D12_RESOURCE_STATES state)
327 {
328 Q_ASSERT(resource);
329 return pool->add({ resource, state, resource->GetDesc(), nullptr, nullptr, 0, false });
330 }
331
332 void releaseResources()
333 {
334 if (owns) {
335 // order matters: resource first, then the allocation
336 resource->Release();
337 if (allocation)
338 allocation->Release();
339 }
340 }
341};
342
343struct QD3D12Pipeline
344{
345 enum Type {
346 Graphics,
347 Compute
348 };
349 Type type;
350 ID3D12PipelineState *pso;
351
352 static QD3D12ObjectHandle addToPool(QD3D12ObjectPool<QD3D12Pipeline> *pool,
353 Type type,
354 ID3D12PipelineState *pso)
355 {
356 return pool->add({ type, pso });
357 }
358
359 void releaseResources()
360 {
361 pso->Release();
362 }
363};
364
365struct QD3D12RootSignature
366{
367 ID3D12RootSignature *rootSig;
368
369 static QD3D12ObjectHandle addToPool(QD3D12ObjectPool<QD3D12RootSignature> *pool,
370 ID3D12RootSignature *rootSig)
371 {
372 return pool->add({ rootSig });
373 }
374
375 void releaseResources()
376 {
377 rootSig->Release();
378 }
379};
380
381struct QD3D12ReleaseQueue
382{
383 void create(QD3D12ObjectPool<QD3D12Resource> *resourcePool,
384 QD3D12ObjectPool<QD3D12Pipeline> *pipelinePool,
385 QD3D12ObjectPool<QD3D12RootSignature> *rootSignaturePool)
386 {
387 this->resourcePool = resourcePool;
388 this->pipelinePool = pipelinePool;
389 this->rootSignaturePool = rootSignaturePool;
390 }
391
392 void deferredReleaseResource(const QD3D12ObjectHandle &handle);
393 void deferredReleaseResourceWithViews(const QD3D12ObjectHandle &handle,
394 QD3D12CpuDescriptorPool *pool,
395 const QD3D12Descriptor &viewsStart,
396 int viewCount);
397 void deferredReleasePipeline(const QD3D12ObjectHandle &handle);
398 void deferredReleaseRootSignature(const QD3D12ObjectHandle &handle);
399 void deferredReleaseCallback(std::function<void(void*)> callback, void *userData);
400 void deferredReleaseResourceAndAllocation(ID3D12Resource *resource,
401 D3D12MA::Allocation *allocation);
402 void deferredReleaseDescriptorHeap(ID3D12DescriptorHeap *heap);
403 void deferredReleaseViews(QD3D12CpuDescriptorPool *pool,
404 const QD3D12Descriptor &viewsStart,
405 int viewCount);
406
407 void activatePendingDeferredReleaseRequests(int frameSlot);
408 void executeDeferredReleases(int frameSlot, bool forced = false);
409 void releaseAll();
410
411 struct DeferredReleaseEntry {
412 enum Type {
413 Resource,
414 Pipeline,
415 RootSignature,
416 Callback,
417 ResourceAndAllocation,
418 DescriptorHeap,
419 Views
420 };
421 Type type = Resource;
422 std::optional<int> frameSlotToBeReleasedIn;
423 QD3D12ObjectHandle handle;
424 QD3D12CpuDescriptorPool *poolForViews = nullptr;
425 QD3D12Descriptor viewsStart;
426 int viewCount = 0;
427 std::function<void(void*)> callback = nullptr;
428 void *callbackUserData = nullptr;
429 std::pair<ID3D12Resource *, D3D12MA::Allocation *> resourceAndAllocation = {};
430 ID3D12DescriptorHeap *descriptorHeap = nullptr;
431 };
432 QVector<DeferredReleaseEntry> queue;
433 QD3D12ObjectPool<QD3D12Resource> *resourcePool = nullptr;
434 QD3D12ObjectPool<QD3D12Pipeline> *pipelinePool = nullptr;
435 QD3D12ObjectPool<QD3D12RootSignature> *rootSignaturePool = nullptr;
436};
437
438struct QD3D12CommandBuffer;
439
440struct QD3D12ResourceBarrierGenerator
441{
442 static const int PREALLOC = 16;
443
444 void create(QD3D12ObjectPool<QD3D12Resource> *resourcePool)
445 {
446 this->resourcePool = resourcePool;
447 }
448
449 void addTransitionBarrier(const QD3D12ObjectHandle &resourceHandle, D3D12_RESOURCE_STATES stateAfter);
450 void enqueueBufferedTransitionBarriers(QD3D12CommandBuffer *cbD);
451 void enqueueSubresourceTransitionBarrier(QD3D12CommandBuffer *cbD,
452 const QD3D12ObjectHandle &resourceHandle,
453 UINT subresource,
454 D3D12_RESOURCE_STATES stateBefore,
455 D3D12_RESOURCE_STATES stateAfter);
456 void enqueueUavBarrier(QD3D12CommandBuffer *cbD, const QD3D12ObjectHandle &resourceHandle);
457
458 struct TransitionResourceBarrier {
459 QD3D12ObjectHandle resourceHandle;
460 D3D12_RESOURCE_STATES stateBefore;
461 D3D12_RESOURCE_STATES stateAfter;
462 };
463 QVarLengthArray<TransitionResourceBarrier, PREALLOC> transitionResourceBarriers;
464 QD3D12ObjectPool<QD3D12Resource> *resourcePool = nullptr;
465};
466
467struct QD3D12ShaderBytecodeCache
468{
469 struct Shader {
470 Shader() = default;
471 Shader(const QByteArray &bytecode, const QShader::NativeResourceBindingMap &rbm)
472 : bytecode(bytecode), nativeResourceBindingMap(rbm)
473 { }
474 QByteArray bytecode;
475 QShader::NativeResourceBindingMap nativeResourceBindingMap;
476 };
477
478 QHash<QRhiShaderStage, Shader> data;
479
480 void insertWithCapacityLimit(const QRhiShaderStage &key, const Shader &s);
481};
482
483struct QD3D12ShaderVisibleDescriptorHeap
484{
485 bool create(ID3D12Device *device, D3D12_DESCRIPTOR_HEAP_TYPE type, quint32 perFrameDescriptorCount);
486 void destroy();
487 void destroyWithDeferredRelease(QD3D12ReleaseQueue *releaseQueue);
488
489 QD3D12DescriptorHeap heap;
490 QD3D12DescriptorHeap perFrameHeapSlice[QD3D12_FRAMES_IN_FLIGHT];
491};
492
493// wrap foreign struct so we can legally supply equality operators and qHash:
494struct Q_D3D12_SAMPLER_DESC
495{
496 D3D12_SAMPLER_DESC desc;
497
498 friend bool operator==(const Q_D3D12_SAMPLER_DESC &lhs, const Q_D3D12_SAMPLER_DESC &rhs) noexcept
499 {
500 return lhs.desc.Filter == rhs.desc.Filter
501 && lhs.desc.AddressU == rhs.desc.AddressU
502 && lhs.desc.AddressV == rhs.desc.AddressV
503 && lhs.desc.AddressW == rhs.desc.AddressW
504 && lhs.desc.MipLODBias == rhs.desc.MipLODBias
505 && lhs.desc.MaxAnisotropy == rhs.desc.MaxAnisotropy
506 && lhs.desc.ComparisonFunc == rhs.desc.ComparisonFunc
507 // BorderColor is never used, skip it
508 && lhs.desc.MinLOD == rhs.desc.MinLOD
509 && lhs.desc.MaxLOD == rhs.desc.MaxLOD;
510 }
511
512 friend bool operator!=(const Q_D3D12_SAMPLER_DESC &lhs, const Q_D3D12_SAMPLER_DESC &rhs) noexcept
513 {
514 return !(lhs == rhs);
515 }
516
517 friend size_t qHash(const Q_D3D12_SAMPLER_DESC &key, size_t seed = 0) noexcept
518 {
519 QtPrivate::QHashCombine hash(seed);
520 seed = hash(seed, key.desc.Filter);
521 seed = hash(seed, key.desc.AddressU);
522 seed = hash(seed, key.desc.AddressV);
523 seed = hash(seed, key.desc.AddressW);
524 seed = hash(seed, key.desc.MipLODBias);
525 seed = hash(seed, key.desc.MaxAnisotropy);
526 seed = hash(seed, key.desc.ComparisonFunc);
527 // BorderColor is never used, skip it
528 seed = hash(seed, key.desc.MinLOD);
529 seed = hash(seed, key.desc.MaxLOD);
530 return seed;
531 }
532};
533
534// A list of sampler descriptions, used as the key for looking up the
535// contiguous descriptor run that backs an array of samplers.
536struct Q_D3D12_SAMPLER_DESC_LIST
537{
538 QVarLengthArray<Q_D3D12_SAMPLER_DESC, 8> descs;
539
540 friend bool operator==(const Q_D3D12_SAMPLER_DESC_LIST &lhs, const Q_D3D12_SAMPLER_DESC_LIST &rhs) noexcept
541 {
542 return lhs.descs == rhs.descs;
543 }
544
545 friend bool operator!=(const Q_D3D12_SAMPLER_DESC_LIST &lhs, const Q_D3D12_SAMPLER_DESC_LIST &rhs) noexcept
546 {
547 return !(lhs == rhs);
548 }
549
550 friend size_t qHash(const Q_D3D12_SAMPLER_DESC_LIST &key, size_t seed = 0) noexcept
551 {
552 return qHashRange(key.descs.cbegin(), key.descs.cend(), seed);
553 }
554};
555
556struct QD3D12SamplerManager
557{
558 const quint32 MAX_SAMPLERS = 512;
559
560 bool create(ID3D12Device *device);
561 void destroy();
562
563 QD3D12Descriptor getShaderVisibleDescriptor(const D3D12_SAMPLER_DESC &desc);
564 // For an array of samplers: returns the start of a run of count
565 // consecutive descriptors, so that the array can be bound as one
566 // descriptor range.
567 QD3D12Descriptor getShaderVisibleDescriptors(const QVarLengthArray<Q_D3D12_SAMPLER_DESC, 8> &descs);
568
569 ID3D12Device *device = nullptr;
570 QD3D12ShaderVisibleDescriptorHeap shaderVisibleSamplerHeap;
571 // Nothing is ever pruned from these: the heap is allocated from linearly
572 // and a descriptor (run) is kept until the QRhi goes away. This relies on
573 // the number of distinct sampler descriptions an application uses being
574 // small, which holds in practice because the descriptions are generated
575 // from the handful of filtering and addressing modes QRhiSampler exposes.
576 // The assumption is weaker for gpuArrayMap, where the key is a list, so
577 // combinations of even a few distinct samplers can multiply, and each
578 // entry takes count descriptors out of MAX_SAMPLERS. Should that ever
579 // become a problem in practice, the runs would need reference counting and
580 // deferred release, not just a bump allocator.
581 QHash<Q_D3D12_SAMPLER_DESC, QD3D12Descriptor> gpuMap;
582 QHash<Q_D3D12_SAMPLER_DESC_LIST, QD3D12Descriptor> gpuArrayMap;
583};
584
585enum QD3D12Stage { VS = 0, HS, DS, GS, PS, CS };
586
587static inline QD3D12Stage qd3d12_stage(QRhiShaderStage::Type type)
588{
589 switch (type) {
590 case QRhiShaderStage::Vertex:
591 return VS;
592 case QRhiShaderStage::TessellationControl:
593 return HS;
594 case QRhiShaderStage::TessellationEvaluation:
595 return DS;
596 case QRhiShaderStage::Geometry:
597 return GS;
598 case QRhiShaderStage::Fragment:
599 return PS;
600 case QRhiShaderStage::Compute:
601 return CS;
602 }
603 Q_UNREACHABLE_RETURN(VS);
604}
605
606static inline D3D12_SHADER_VISIBILITY qd3d12_stageToVisibility(QD3D12Stage s)
607{
608 switch (s) {
609 case VS:
610 return D3D12_SHADER_VISIBILITY_VERTEX;
611 case HS:
612 return D3D12_SHADER_VISIBILITY_HULL;
613 case DS:
614 return D3D12_SHADER_VISIBILITY_DOMAIN;
615 case GS:
616 return D3D12_SHADER_VISIBILITY_GEOMETRY;
617 case PS:
618 return D3D12_SHADER_VISIBILITY_PIXEL;
619 case CS:
620 return D3D12_SHADER_VISIBILITY_ALL;
621 }
622 Q_UNREACHABLE_RETURN(D3D12_SHADER_VISIBILITY_ALL);
623}
624
625static inline QRhiShaderResourceBinding::StageFlag qd3d12_stageToSrb(QD3D12Stage s)
626{
627 switch (s) {
628 case VS:
629 return QRhiShaderResourceBinding::VertexStage;
630 case HS:
631 return QRhiShaderResourceBinding::TessellationControlStage;
632 case DS:
633 return QRhiShaderResourceBinding::TessellationEvaluationStage;
634 case GS:
635 return QRhiShaderResourceBinding::GeometryStage;
636 case PS:
637 return QRhiShaderResourceBinding::FragmentStage;
638 case CS:
639 return QRhiShaderResourceBinding::ComputeStage;
640 }
641 Q_UNREACHABLE_RETURN(QRhiShaderResourceBinding::VertexStage);
642}
643
644struct QD3D12ShaderStageData
645{
646 bool valid = false; // to allow simple arrays where unused stages are indicated by !valid
647 QD3D12Stage stage = VS;
648 QShader::NativeResourceBindingMap nativeResourceBindingMap;
649};
650
651struct QD3D12ShaderResourceBindings;
652
653struct QD3D12ShaderResourceVisitor
654{
655 enum StorageOp { Load = 0, Store, LoadStore };
656
657 QD3D12ShaderResourceVisitor(const QD3D12ShaderResourceBindings *srb,
658 const QD3D12ShaderStageData *stageData,
659 int stageCount)
660 : srb(srb),
661 stageData(stageData),
662 stageCount(stageCount)
663 {
664 }
665
666 std::function<void(QD3D12Stage, const QRhiShaderResourceBinding::Data::UniformBufferData &, int, int)> uniformBuffer = nullptr;
667 // Textures and samplers are visited per binding, not per array element: a
668 // shader declares an array of textures or samplers as a single descriptor
669 // range, and D3D12 will not accept a pipeline where such a range is only
670 // partially bound (a series of one-descriptor ranges does not qualify), so
671 // the whole array has to be seen at once. (arguments: stage, elements,
672 // element count, base shader register)
673 std::function<void(QD3D12Stage, const QRhiShaderResourceBinding::TextureAndSampler *, int, int)> textures = nullptr;
674 std::function<void(QD3D12Stage, const QRhiShaderResourceBinding::TextureAndSampler *, int, int)> samplers = nullptr;
675 std::function<void(QD3D12Stage, const QRhiShaderResourceBinding::Data::StorageImageData &, StorageOp, int)> storageImage = nullptr;
676 std::function<void(QD3D12Stage, const QRhiShaderResourceBinding::Data::StorageBufferData &, StorageOp, int)> storageBuffer = nullptr;
677
678 void visit();
679
680 const QD3D12ShaderResourceBindings *srb;
681 const QD3D12ShaderStageData *stageData;
682 int stageCount;
683};
684
685struct QD3D12Readback
686{
687 // common
688 int frameSlot = -1;
689 QRhiReadbackResult *result = nullptr;
690 QD3D12StagingArea staging;
691 quint32 byteSize = 0;
692 // textures
693 quint32 bytesPerLine = 0;
694 QSize pixelSize;
695 QRhiTexture::Format format = QRhiTexture::UnknownFormat;
696 quint32 stagingRowPitch = 0;
697};
698
699struct QD3D12MipmapGenerator
700{
701 void create(QRhiD3D12 *rhiD);
702 void destroy();
703 void generate(QD3D12CommandBuffer *cbD, const QD3D12ObjectHandle &textureHandle);
704
705 bool ensureCreated();
706 bool buildPipeline();
707
708 QRhiD3D12 *rhiD = nullptr;
709 QD3D12ObjectHandle rootSigHandle;
710 QD3D12ObjectHandle pipelineHandle;
711 bool createFailed = false;
712};
713
714struct QD3D12MipmapGenerator3D
715{
716 void create(QRhiD3D12 *rhiD);
717 void destroy();
718 void generate(QD3D12CommandBuffer *cbD, const QD3D12ObjectHandle &textureHandle);
719
720 bool ensureCreated();
721 bool buildPipeline();
722
723 QRhiD3D12 *rhiD = nullptr;
724 QD3D12ObjectHandle rootSigHandle;
725 QD3D12ObjectHandle pipelineHandle;
726 bool createFailed = false;
727};
728
729struct QD3D12MemoryAllocator
730{
731 bool create(ID3D12Device *device, IDXGIAdapter1 *adapter);
732 void destroy();
733
734 HRESULT createResource(D3D12_HEAP_TYPE heapType,
735 const D3D12_RESOURCE_DESC *resourceDesc,
736 D3D12_RESOURCE_STATES initialState,
737 const D3D12_CLEAR_VALUE *optimizedClearValue,
738 D3D12MA::Allocation **maybeAllocation,
739 REFIID riidResource,
740 void **ppvResource);
741
742 void getBudget(D3D12MA::Budget *localBudget, D3D12MA::Budget *nonLocalBudget);
743
744 bool isUsingD3D12MA() const { return allocator != nullptr; }
745
746 ID3D12Device *device = nullptr;
747 D3D12MA::Allocator *allocator = nullptr;
748};
749
750struct QD3D12Buffer : public QRhiBuffer
751{
752 QD3D12Buffer(QRhiImplementation *rhi, Type type, UsageFlags usage, quint32 size);
753 ~QD3D12Buffer();
754
755 void destroy() override;
756 bool create() override;
757 QRhiBuffer::NativeBuffer nativeBuffer() override;
758 char *beginFullDynamicBufferUpdateForCurrentFrame() override;
759 void endFullDynamicBufferUpdateForCurrentFrame() override;
760
761 void executeHostWritesForFrameSlot(int frameSlot);
762
763 QD3D12ObjectHandle handles[QD3D12_FRAMES_IN_FLIGHT] = {};
764 struct HostWrite {
765 quint32 offset;
766 QRhiBufferData data;
767 };
768 QVarLengthArray<HostWrite, 16> pendingHostWrites[QD3D12_FRAMES_IN_FLIGHT];
769 uint generation = 0;
770 friend class QRhiD3D12;
771 friend struct QD3D12ShaderResourceBindings;
772};
773
774struct QD3D12RenderBuffer : public QRhiRenderBuffer
775{
776 QD3D12RenderBuffer(QRhiImplementation *rhi,
777 Type type,
778 const QSize &pixelSize,
779 int sampleCount,
780 Flags flags,
781 QRhiTexture::Format backingFormatHint);
782 ~QD3D12RenderBuffer();
783 void destroy() override;
784 bool create() override;
785 QRhiTexture::Format backingFormat() const override;
786
787 static const DXGI_FORMAT DS_FORMAT = DXGI_FORMAT_D24_UNORM_S8_UINT;
788
789 QD3D12ObjectHandle handle;
790 QD3D12Descriptor rtv;
791 QD3D12Descriptor dsv;
792 DXGI_FORMAT dxgiFormat;
793 DXGI_SAMPLE_DESC sampleDesc;
794 uint generation = 0;
795 friend class QRhiD3D12;
796};
797
798struct QD3D12Texture : public QRhiTexture
799{
800 QD3D12Texture(QRhiImplementation *rhi, Format format, const QSize &pixelSize, int depth,
801 int arraySize, int sampleCount, Flags flags);
802 ~QD3D12Texture();
803 void destroy() override;
804 bool create() override;
805 bool createFrom(NativeTexture src) override;
806 NativeTexture nativeTexture() override;
807 void setNativeLayout(int layout) override;
808
809 bool prepareCreate(QSize *adjustedSize = nullptr);
810 bool finishCreate();
811
812 QD3D12ObjectHandle handle;
813 QD3D12Descriptor srv;
814 DXGI_FORMAT dxgiFormat;
815 DXGI_FORMAT srvFormat;
816 DXGI_FORMAT rtFormat; // RTV/DSV/UAV
817 uint mipLevelCount;
818 DXGI_SAMPLE_DESC sampleDesc;
819 QBitArray resolveDestInitialized;
820 uint generation = 0;
821 friend class QRhiD3D12;
822 friend struct QD3D12ShaderResourceBindings;
823};
824
825struct QD3D12Sampler : public QRhiSampler
826{
827 QD3D12Sampler(QRhiImplementation *rhi, Filter magFilter, Filter minFilter, Filter mipmapMode,
828 AddressMode u, AddressMode v, AddressMode w);
829 ~QD3D12Sampler();
830 void destroy() override;
831 bool create() override;
832
833 QD3D12Descriptor lookupOrCreateShaderVisibleDescriptor();
834
835 D3D12_SAMPLER_DESC desc = {};
836 QD3D12Descriptor shaderVisibleDescriptor;
837 uint generation = 0;
838 friend class QRhiD3D12;
839};
840
841struct QD3D12ShadingRateMap : public QRhiShadingRateMap
842{
843 QD3D12ShadingRateMap(QRhiImplementation *rhi);
844 ~QD3D12ShadingRateMap();
845 void destroy() override;
846 bool createFrom(QRhiTexture *src) override;
847
848 QD3D12ObjectHandle handle; // just copied from the texture
849 friend class QRhiD3D12;
850};
851
852struct QD3D12RenderPassDescriptor : public QRhiRenderPassDescriptor
853{
854 QD3D12RenderPassDescriptor(QRhiImplementation *rhi);
855 ~QD3D12RenderPassDescriptor();
856 void destroy() override;
857 bool isCompatible(const QRhiRenderPassDescriptor *other) const override;
858 QRhiRenderPassDescriptor *newCompatibleRenderPassDescriptor() const override;
859 QVector<quint32> serializedFormat() const override;
860
861 void updateSerializedFormat();
862
863 static const int MAX_COLOR_ATTACHMENTS = 8;
864 int colorAttachmentCount = 0;
865 bool hasDepthStencil = false;
866 int colorFormat[MAX_COLOR_ATTACHMENTS];
867 int dsFormat;
868 bool hasShadingRateMap = false;
869 QVector<quint32> serializedFormatData;
870};
871
872struct QD3D12RenderTargetData
873{
874 QD3D12RenderTargetData(QRhiImplementation *) { }
875
876 QD3D12RenderPassDescriptor *rp = nullptr;
877 QSize pixelSize;
878 float dpr = 1;
879 int sampleCount = 1;
880 int colorAttCount = 0;
881 int dsAttCount = 0;
882 QRhiRenderTargetAttachmentTracker::ResIdList currentResIdList;
883 static const int MAX_COLOR_ATTACHMENTS = QD3D12RenderPassDescriptor::MAX_COLOR_ATTACHMENTS;
884 D3D12_CPU_DESCRIPTOR_HANDLE rtv[MAX_COLOR_ATTACHMENTS];
885 D3D12_CPU_DESCRIPTOR_HANDLE dsv;
886};
887
888struct QD3D12SwapChainRenderTarget : public QRhiSwapChainRenderTarget
889{
890 QD3D12SwapChainRenderTarget(QRhiImplementation *rhi, QRhiSwapChain *swapchain);
891 ~QD3D12SwapChainRenderTarget();
892 void destroy() override;
893
894 QSize pixelSize() const override;
895 float devicePixelRatio() const override;
896 int sampleCount() const override;
897
898 QD3D12RenderTargetData d;
899};
900
901struct QD3D12TextureRenderTarget : public QRhiTextureRenderTarget
902{
903 QD3D12TextureRenderTarget(QRhiImplementation *rhi,
904 const QRhiTextureRenderTargetDescription &desc,
905 Flags flags);
906 ~QD3D12TextureRenderTarget();
907 void destroy() override;
908
909 QSize pixelSize() const override;
910 float devicePixelRatio() const override;
911 int sampleCount() const override;
912
913 QRhiRenderPassDescriptor *newCompatibleRenderPassDescriptor() override;
914 bool create() override;
915
916 QD3D12RenderTargetData d;
917 bool ownsRtv[QD3D12RenderTargetData::MAX_COLOR_ATTACHMENTS];
918 QD3D12Descriptor rtv[QD3D12RenderTargetData::MAX_COLOR_ATTACHMENTS];
919 bool ownsDsv = false;
920 QD3D12Descriptor dsv;
921 friend class QRhiD3D12;
922};
923
924struct QD3D12GraphicsPipeline;
925struct QD3D12ComputePipeline;
926
927struct QD3D12ShaderResourceBindings : public QRhiShaderResourceBindings
928{
929 QD3D12ShaderResourceBindings(QRhiImplementation *rhi);
930 ~QD3D12ShaderResourceBindings();
931 void destroy() override;
932 bool create() override;
933 void updateResources(UpdateFlags flags) override;
934
935 QD3D12ObjectHandle createRootSignature(const QD3D12ShaderStageData *stageData, int stageCount);
936
937 struct VisitorData {
938 QVarLengthArray<D3D12_ROOT_PARAMETER1, 2> cbParams[6];
939
940 D3D12_ROOT_PARAMETER1 srvTables[6] = {};
941 QVarLengthArray<D3D12_DESCRIPTOR_RANGE1, 4> srvRanges[6];
942 quint32 currentSrvRangeOffset[6] = {};
943
944 QVarLengthArray<D3D12_ROOT_PARAMETER1, 4> samplerTables[6];
945 std::array<D3D12_DESCRIPTOR_RANGE1, 16> samplerRanges[6] = {};
946 int samplerRangeHeads[6] = {};
947
948 D3D12_ROOT_PARAMETER1 uavTables[6] = {};
949 QVarLengthArray<D3D12_DESCRIPTOR_RANGE1, 4> uavRanges[6];
950 quint32 currentUavRangeOffset[6] = {};
951 } visitorData;
952
953
954 void visitUniformBuffer(QD3D12Stage s,
955 const QRhiShaderResourceBinding::Data::UniformBufferData &d,
956 int shaderRegister,
957 int binding);
958 void visitTextures(QD3D12Stage s,
959 const QRhiShaderResourceBinding::TextureAndSampler *d,
960 int count,
961 int baseShaderRegister);
962 void visitSamplers(QD3D12Stage s,
963 const QRhiShaderResourceBinding::TextureAndSampler *d,
964 int count,
965 int baseShaderRegister);
966 void visitStorageBuffer(QD3D12Stage s,
967 const QRhiShaderResourceBinding::Data::StorageBufferData &d,
968 QD3D12ShaderResourceVisitor::StorageOp op,
969 int shaderRegister);
970 void visitStorageImage(QD3D12Stage s,
971 const QRhiShaderResourceBinding::Data::StorageImageData &d,
972 QD3D12ShaderResourceVisitor::StorageOp op,
973 int shaderRegister);
974
975 // The translation of the QRhi-level bindings into what has to be handed to
976 // the command list. This depends both on the srb's own contents and on the
977 // per-stage native resource binding maps of the pipeline, and is rebuilt
978 // whenever either changes - but not on every setShaderResources().
979 struct BindingCache {
980 // The frame slot's resource and any dynamic offset are only known when
981 // binding, so keep the QRhiBuffer and resolve there.
982 struct CBuf {
983 QD3D12Buffer *buf;
984 quint32 offset;
985 int binding;
986 };
987 QVarLengthArray<CBuf, 2> cbufs[6];
988 QVarLengthArray<D3D12_CPU_DESCRIPTOR_HANDLE, 8> srvs[6];
989 QVarLengthArray<D3D12_GPU_DESCRIPTOR_HANDLE, 8> samplers[6];
990 struct Uav {
991 QD3D12ObjectHandle handle;
992 D3D12_UNORDERED_ACCESS_VIEW_DESC desc;
993 };
994 QVarLengthArray<Uav, 4> uavs[6];
995 quint32 srvUavCount = 0;
996
997 void reset() {
998 for (int s = 0; s < 6; ++s) {
999 cbufs[s].clear();
1000 srvs[s].clear();
1001 samplers[s].clear();
1002 uavs[s].clear();
1003 }
1004 srvUavCount = 0;
1005 }
1006 } bindingCache;
1007
1008 bool bindingCacheValid = false;
1009 uint bindingCacheGeneration = 0;
1010
1011 void rebuildBindingCache(const QD3D12ShaderStageData *stageData, int stageCount);
1012
1013 // Unlike the visit* functions above, these run at setShaderResources() time
1014 // and so are free to look at the bound QRhiBuffer/Texture/Sampler objects.
1015 void cacheUniformBuffer(QD3D12Stage s,
1016 const QRhiShaderResourceBinding::Data::UniformBufferData &d,
1017 int shaderRegister,
1018 int binding);
1019 void cacheTextures(QD3D12Stage s,
1020 const QRhiShaderResourceBinding::TextureAndSampler *d,
1021 int count,
1022 int baseShaderRegister);
1023 void cacheSamplers(QD3D12Stage s,
1024 const QRhiShaderResourceBinding::TextureAndSampler *d,
1025 int count,
1026 int baseShaderRegister);
1027 void cacheStorageBuffer(QD3D12Stage s,
1028 const QRhiShaderResourceBinding::Data::StorageBufferData &d,
1029 QD3D12ShaderResourceVisitor::StorageOp op,
1030 int shaderRegister);
1031 void cacheStorageImage(QD3D12Stage s,
1032 const QRhiShaderResourceBinding::Data::StorageImageData &d,
1033 QD3D12ShaderResourceVisitor::StorageOp op,
1034 int shaderRegister);
1035
1036 struct BoundUniformBufferData {
1037 quint64 id;
1038 uint generation;
1039 };
1040 struct BoundSampledTextureData {
1041 int count;
1042 struct {
1043 quint64 texId;
1044 uint texGeneration;
1045 quint64 samplerId;
1046 uint samplerGeneration;
1047 } d[QRhiShaderResourceBinding::Data::MAX_TEX_SAMPLER_ARRAY_SIZE];
1048 };
1049 struct BoundStorageImageData {
1050 quint64 id;
1051 uint generation;
1052 };
1053 struct BoundStorageBufferData {
1054 quint64 id;
1055 uint generation;
1056 };
1057 struct BoundResourceData {
1058 union {
1059 BoundUniformBufferData ubuf;
1060 BoundSampledTextureData stex;
1061 BoundStorageImageData simage;
1062 BoundStorageBufferData sbuf;
1063 };
1064 };
1065 QVarLengthArray<BoundResourceData, 8> boundResourceData;
1066
1067 bool hasDynamicOffset = false;
1068 uint generation = 0;
1069 QD3D12GraphicsPipeline *lastUsedGraphicsPipeline = nullptr;
1070 QD3D12ComputePipeline *lastUsedComputePipeline = nullptr;
1071 uint lastUsedPipelineGeneration = 0;
1072
1073 friend class QRhiD3D12;
1074 friend struct QD3D12ShaderResourceVisitor;
1075};
1076
1077struct QD3D12GraphicsPipeline : public QRhiGraphicsPipeline
1078{
1079 QD3D12GraphicsPipeline(QRhiImplementation *rhi);
1080 ~QD3D12GraphicsPipeline();
1081 void destroy() override;
1082 bool create() override;
1083
1084 QD3D12ObjectHandle handle;
1085 QD3D12ObjectHandle rootSigHandle;
1086 std::array<QD3D12ShaderStageData, 5> stageData;
1087 D3D12_PRIMITIVE_TOPOLOGY topology;
1088 UINT viewInstanceMask = 0;
1089 uint generation = 0;
1090 friend class QRhiD3D12;
1091};
1092
1093struct QD3D12ComputePipeline : public QRhiComputePipeline
1094{
1095 QD3D12ComputePipeline(QRhiImplementation *rhi);
1096 ~QD3D12ComputePipeline();
1097 void destroy() override;
1098 bool create() override;
1099
1100 QD3D12ObjectHandle handle;
1101 QD3D12ObjectHandle rootSigHandle;
1102 QD3D12ShaderStageData stageData;
1103 uint generation = 0;
1104 friend class QRhiD3D12;
1105};
1106
1107struct QD3D12CommandBuffer : public QRhiCommandBuffer
1108{
1109 QD3D12CommandBuffer(QRhiImplementation *rhi);
1110 ~QD3D12CommandBuffer();
1111 void destroy() override;
1112
1113 const QRhiNativeHandles *nativeHandles();
1114
1115 D3D12GraphicsCommandList *cmdList = nullptr; // not owned
1116 QRhiD3D12CommandBufferNativeHandles nativeHandlesStruct;
1117
1118 enum PassType {
1119 NoPass,
1120 RenderPass,
1121 ComputePass
1122 };
1123
1124 void resetState()
1125 {
1126 recordingPass = NoPass;
1127 currentTarget = nullptr;
1128
1129 resetPerPassState();
1130 }
1131
1132 void resetPerPassState()
1133 {
1134 currentGraphicsPipeline = nullptr;
1135 currentComputePipeline = nullptr;
1136 currentPipelineGeneration = 0;
1137 currentGraphicsSrb = nullptr;
1138 currentComputeSrb = nullptr;
1139 currentSrbGeneration = 0;
1140 currentIndexBuffer = {};
1141 currentIndexOffset = 0;
1142 currentIndexFormat = DXGI_FORMAT_R16_UINT;
1143 currentVertexBuffers = {};
1144 currentVertexOffsets = {};
1145 hasShadingRateSet = false;
1146 hasShadingRateMapSet = false;
1147 hasCustomScissorSet = false;
1148 currentViewport = {};
1149 }
1150
1151 // per-frame
1152 PassType recordingPass;
1153 QRhiRenderTarget *currentTarget;
1154
1155 // per-pass
1156 QD3D12GraphicsPipeline *currentGraphicsPipeline;
1157 QD3D12ComputePipeline *currentComputePipeline;
1158 uint currentPipelineGeneration;
1159 QRhiShaderResourceBindings *currentGraphicsSrb;
1160 QRhiShaderResourceBindings *currentComputeSrb;
1161 uint currentSrbGeneration;
1162 QD3D12ObjectHandle currentIndexBuffer;
1163 quint32 currentIndexOffset;
1164 DXGI_FORMAT currentIndexFormat;
1165 std::array<QD3D12ObjectHandle, D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> currentVertexBuffers;
1166 std::array<quint32, D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> currentVertexOffsets;
1167 bool hasShadingRateSet;
1168 bool hasShadingRateMapSet;
1169 bool hasCustomScissorSet;
1170 QRhiViewport currentViewport;
1171
1172 // global
1173 double lastGpuTime = 0;
1174};
1175
1176struct QD3D12SwapChain : public QRhiSwapChain
1177{
1178 QD3D12SwapChain(QRhiImplementation *rhi);
1179 ~QD3D12SwapChain();
1180 void destroy() override;
1181
1182 QRhiCommandBuffer *currentFrameCommandBuffer() override;
1183 QRhiRenderTarget *currentFrameRenderTarget() override;
1184 QRhiRenderTarget *currentFrameRenderTarget(StereoTargetBuffer targetBuffer) override;
1185
1186 QSize surfacePixelSize() override;
1187 bool isFormatSupported(Format f) override;
1188 QRhiSwapChainHdrInfo hdrInfo() override;
1189
1190 QRhiRenderPassDescriptor *newCompatibleRenderPassDescriptor() override;
1191 bool createOrResize() override;
1192
1193 void releaseBuffers();
1194 void waitCommandCompletionForFrameSlot(int frameSlot);
1195 void addCommandCompletionSignalForCurrentFrameSlot();
1196 void chooseFormats();
1197
1198 QWindow *window = nullptr;
1199 IDXGISwapChain1 *sourceSwapChain1 = nullptr;
1200 IDXGISwapChain3 *swapChain = nullptr;
1201 QSize pixelSize;
1202 UINT swapInterval = 1;
1203 UINT swapChainFlags = 0;
1204 BOOL stereo = false;
1205 DXGI_FORMAT colorFormat;
1206 DXGI_FORMAT srgbAdjustedColorFormat;
1207 DXGI_COLOR_SPACE_TYPE hdrColorSpace;
1208 IDCompositionTarget *dcompTarget = nullptr;
1209 IDCompositionVisual *dcompVisual = nullptr;
1210 static const UINT BUFFER_COUNT = 3;
1211 QD3D12ObjectHandle colorBuffers[BUFFER_COUNT];
1212 QD3D12Descriptor rtvs[BUFFER_COUNT];
1213 QD3D12Descriptor rtvsRight[BUFFER_COUNT];
1214 DXGI_SAMPLE_DESC sampleDesc;
1215 QD3D12ObjectHandle msaaBuffers[QD3D12_FRAMES_IN_FLIGHT]; // one per frame slot, not swapchain buffer, is enough
1216 QD3D12Descriptor msaaRtvs[QD3D12_FRAMES_IN_FLIGHT];
1217 QD3D12RenderBuffer *ds = nullptr;
1218 UINT currentBackBufferIndex = 0;
1219 QD3D12SwapChainRenderTarget rtWrapper;
1220 QD3D12SwapChainRenderTarget rtWrapperRight;
1221 QD3D12CommandBuffer cbWrapper;
1222 HANDLE frameLatencyWaitableObject = nullptr;
1223
1224 struct FrameResources {
1225 ID3D12Fence *fence = nullptr;
1226 HANDLE fenceEvent = nullptr;
1227 UINT64 fenceCounter = 0;
1228 D3D12GraphicsCommandList *cmdList = nullptr;
1229 } frameRes[QD3D12_FRAMES_IN_FLIGHT];
1230
1231 int currentFrameSlot = 0; // index in frameRes
1232 int lastFrameLatencyWaitSlot = -1;
1233};
1234
1235template<typename T, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE Type>
1236struct alignas(void*) QD3D12PipelineStateSubObject
1237{
1238 D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = Type;
1239 T object = {};
1240};
1241
1242class QD3D12Adapter : public QRhiAdapter
1243{
1244public:
1245 QRhiDriverInfo info() const override;
1246
1247 LUID luid;
1248 QRhiDriverInfo adapterInfo;
1249};
1250
1251class QRhiD3D12 : public QRhiImplementation
1252{
1253public:
1254 // The shared, per-slot staging area starts at 512 KB and grows up to 16 MB.
1255 static constexpr quint32 SMALL_STAGING_AREA_BYTES_PER_FRAME_START = 512 * 1024;
1256 static constexpr quint32 SMALL_STAGING_AREA_BYTES_PER_FRAME_MAX = 16 * 1024 * 1024;
1257 // Only give the memory back once the demand has stayed low for a while,
1258 // so that an alternating pattern does not recreate the area every frame.
1259 static constexpr int SMALL_STAGING_AREA_LOW_DEMAND_FRAMES = 60;
1260
1261 static constexpr quint32 SHADER_VISIBLE_CBV_SRV_UAV_HEAP_PER_FRAME_START_SIZE = 16384;
1262
1263 QRhiD3D12(QRhiD3D12InitParams *params, QRhiD3D12NativeHandles *importDevice = nullptr);
1264
1265 bool create(QRhi::Flags flags) override;
1266 void destroy() override;
1267 QRhi::AdapterList enumerateAdaptersBeforeCreate(QRhiNativeHandles *nativeHandles) const override;
1268
1269 QRhiGraphicsPipeline *createGraphicsPipeline() override;
1270 QRhiComputePipeline *createComputePipeline() override;
1271 QRhiShaderResourceBindings *createShaderResourceBindings() override;
1272 QRhiBuffer *createBuffer(QRhiBuffer::Type type,
1273 QRhiBuffer::UsageFlags usage,
1274 quint32 size) override;
1275 QRhiRenderBuffer *createRenderBuffer(QRhiRenderBuffer::Type type,
1276 const QSize &pixelSize,
1277 int sampleCount,
1278 QRhiRenderBuffer::Flags flags,
1279 QRhiTexture::Format backingFormatHint) override;
1280 QRhiTexture *createTexture(QRhiTexture::Format format,
1281 const QSize &pixelSize,
1282 int depth,
1283 int arraySize,
1284 int sampleCount,
1285 QRhiTexture::Flags flags) override;
1286 QRhiSampler *createSampler(QRhiSampler::Filter magFilter,
1287 QRhiSampler::Filter minFilter,
1288 QRhiSampler::Filter mipmapMode,
1289 QRhiSampler:: AddressMode u,
1290 QRhiSampler::AddressMode v,
1291 QRhiSampler::AddressMode w) override;
1292
1293 QRhiTextureRenderTarget *createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc,
1294 QRhiTextureRenderTarget::Flags flags) override;
1295
1296 QRhiShadingRateMap *createShadingRateMap() override;
1297
1298 QRhiSwapChain *createSwapChain() override;
1299 QRhi::FrameOpResult beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags) override;
1300 QRhi::FrameOpResult endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags) override;
1301 QRhi::FrameOpResult beginOffscreenFrame(QRhiCommandBuffer **cb, QRhi::BeginFrameFlags flags) override;
1302 QRhi::FrameOpResult endOffscreenFrame(QRhi::EndFrameFlags flags) override;
1303 QRhi::FrameOpResult finish() override;
1304
1305 void resourceUpdate(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override;
1306
1307 void beginPass(QRhiCommandBuffer *cb,
1308 QRhiRenderTarget *rt,
1309 const QColor &colorClearValue,
1310 const QRhiDepthStencilClearValue &depthStencilClearValue,
1311 QRhiResourceUpdateBatch *resourceUpdates,
1312 QRhiCommandBuffer::BeginPassFlags flags) override;
1313 void endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override;
1314
1315 void setGraphicsPipeline(QRhiCommandBuffer *cb,
1316 QRhiGraphicsPipeline *ps) override;
1317
1318 void setShaderResources(QRhiCommandBuffer *cb,
1319 QRhiShaderResourceBindings *srb,
1320 int dynamicOffsetCount,
1321 const QRhiCommandBuffer::DynamicOffset *dynamicOffsets) override;
1322
1323 void setVertexInput(QRhiCommandBuffer *cb,
1324 int startBinding, int bindingCount, const QRhiCommandBuffer::VertexInput *bindings,
1325 QRhiBuffer *indexBuf, quint32 indexOffset,
1326 QRhiCommandBuffer::IndexFormat indexFormat) override;
1327
1328 void setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport) override;
1329 void setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor) override;
1330 void setBlendConstants(QRhiCommandBuffer *cb, const QColor &c) override;
1331 void setStencilRef(QRhiCommandBuffer *cb, quint32 refValue) override;
1332 void setShadingRate(QRhiCommandBuffer *cb, const QSize &coarsePixelSize) override;
1333
1334 void draw(QRhiCommandBuffer *cb, quint32 vertexCount,
1335 quint32 instanceCount, quint32 firstVertex, quint32 firstInstance) override;
1336
1337 void drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount,
1338 quint32 instanceCount, quint32 firstIndex,
1339 qint32 vertexOffset, quint32 firstInstance) override;
1340
1341 void drawIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
1342 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride) override;
1343
1344 void drawIndexedIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
1345 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride) override;
1346
1347 void debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name) override;
1348 void debugMarkEnd(QRhiCommandBuffer *cb) override;
1349 void debugMarkMsg(QRhiCommandBuffer *cb, const QByteArray &msg) override;
1350
1351 void beginComputePass(QRhiCommandBuffer *cb,
1352 QRhiResourceUpdateBatch *resourceUpdates,
1353 QRhiCommandBuffer::BeginPassFlags flags) override;
1354 void endComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates) override;
1355 void setComputePipeline(QRhiCommandBuffer *cb, QRhiComputePipeline *ps) override;
1356 void dispatch(QRhiCommandBuffer *cb, int x, int y, int z) override;
1357
1358 const QRhiNativeHandles *nativeHandles(QRhiCommandBuffer *cb) override;
1359 void beginExternal(QRhiCommandBuffer *cb) override;
1360 void endExternal(QRhiCommandBuffer *cb) override;
1361 double lastCompletedGpuTime(QRhiCommandBuffer *cb) override;
1362
1363 QList<int> supportedSampleCounts() const override;
1364 QList<QSize> supportedShadingRates(int sampleCount) const override;
1365 int ubufAlignment() const override;
1366 bool isYUpInFramebuffer() const override;
1367 bool isYUpInNDC() const override;
1368 bool isClipDepthZeroToOne() const override;
1369 QMatrix4x4 clipSpaceCorrMatrix() const override;
1370 bool isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const override;
1371 bool isFeatureSupported(QRhi::Feature feature) const override;
1372 int resourceLimit(QRhi::ResourceLimit limit) const override;
1373 const QRhiNativeHandles *nativeHandles() override;
1374 QRhiDriverInfo driverInfo() const override;
1375 QRhiStats statistics() override;
1376 bool makeThreadLocalNativeContextCurrent() override;
1377 void setQueueSubmitParams(QRhiNativeHandles *params) override;
1378 void releaseCachedResources() override;
1379 bool isDeviceLost() const override;
1380
1381 QByteArray pipelineCacheData() override;
1382 void setPipelineCacheData(const QByteArray &data) override;
1383
1384 // Must be called for every request made of the per-frame staging area,
1385 // whether or not it ends up fitting: what does not fit is exactly what the
1386 // area should have been big enough for. The point being that if the common
1387 // area is too small, we record the demand for the next frame, and fall back
1388 // to using a temporary, dedicated staging area instead, but in the next
1389 // frame the common one will be big enough, if still needed.
1390 void recordSmallStagingAreaDemand(quint32 byteSize)
1391 {
1392 smallStagingAreaBytesNeeded[currentFrameSlot] += byteSize;
1393 }
1394 void resetAndResizeSmallStagingArea(int frameSlot);
1395
1396 ID3D12PipelineState *loadOrCreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC *streamDesc,
1397 const QByteArray &cacheKey,
1398 const char *what);
1399 bool ensurePipelineLibrary();
1400 bool createPipelineLibrary(const QByteArray &blob);
1401 void destroyPipelineLibrary();
1402
1403 void waitGpu();
1404 DXGI_SAMPLE_DESC effectiveSampleDesc(int sampleCount, DXGI_FORMAT format) const;
1405 bool ensureDirectCompositionDevice();
1406 bool startCommandListForCurrentFrameSlot(D3D12GraphicsCommandList **cmdList);
1407 void enqueueResourceUpdates(QD3D12CommandBuffer *cbD, QRhiResourceUpdateBatch *resourceUpdates);
1408 void finishActiveReadbacks(bool forced = false);
1409 bool ensureShaderVisibleDescriptorHeapCapacity(QD3D12ShaderVisibleDescriptorHeap *h,
1410 D3D12_DESCRIPTOR_HEAP_TYPE type,
1411 int frameSlot,
1412 quint32 neededDescriptorCount,
1413 bool *gotNew);
1414 void bindShaderVisibleHeaps(QD3D12CommandBuffer *cbD);
1415 void setDefaultScissor(QD3D12CommandBuffer *cbD);
1416
1417 bool debugLayer = false;
1418#ifdef QRHI_D3D12_INFOQUEUE1_AVAILABLE
1419 ID3D12InfoQueue1 *infoQueue1 = nullptr;
1420 DWORD infoQueueCallbackCookie = 0;
1421#endif
1422 UINT maxFrameLatency = 2; // 1-3, use 2 to keep CPU-GPU parallelism while reducing lag compared to tripple buffering
1423 ID3D12Device2 *dev = nullptr;
1424 D3D_FEATURE_LEVEL minimumFeatureLevel = D3D_FEATURE_LEVEL(0);
1425 LUID adapterLuid = {};
1426 bool importedDevice = false;
1427 bool importedCommandQueue = false;
1428 QRhi::Flags rhiFlags;
1429 IDXGIFactory2 *dxgiFactory = nullptr;
1430 bool supportsAllowTearing = false;
1431 IDXGIAdapter1 *activeAdapter = nullptr;
1432 QRhiDriverInfo driverInfoStruct;
1433 QRhiD3D12NativeHandles nativeHandlesStruct;
1434 bool deviceLost = false;
1435 ID3D12CommandQueue *cmdQueue = nullptr;
1436 ID3D12Fence *fullFence = nullptr;
1437 HANDLE fullFenceEvent = nullptr;
1438 UINT64 fullFenceCounter = 0;
1439 ID3D12CommandAllocator *cmdAllocators[QD3D12_FRAMES_IN_FLIGHT] = {};
1440 QD3D12MemoryAllocator vma;
1441 QD3D12CpuDescriptorPool rtvPool;
1442 QD3D12CpuDescriptorPool dsvPool;
1443 QD3D12CpuDescriptorPool cbvSrvUavPool;
1444 QD3D12ObjectPool<QD3D12Resource> resourcePool;
1445 QD3D12ObjectPool<QD3D12Pipeline> pipelinePool;
1446 QD3D12ObjectPool<QD3D12RootSignature> rootSignaturePool;
1447 QD3D12ReleaseQueue releaseQueue;
1448 QD3D12ResourceBarrierGenerator barrierGen;
1449 QD3D12SamplerManager samplerMgr;
1450 QD3D12MipmapGenerator mipmapGen;
1451 QD3D12MipmapGenerator3D mipmapGen3D;
1452 QD3D12StagingArea smallStagingAreas[QD3D12_FRAMES_IN_FLIGHT];
1453 quint32 smallStagingAreaBytesNeeded[QD3D12_FRAMES_IN_FLIGHT] = {};
1454 int smallStagingAreaLowDemandFrames[QD3D12_FRAMES_IN_FLIGHT] = {};
1455 QD3D12ShaderVisibleDescriptorHeap shaderVisibleCbvSrvUavHeap;
1456 UINT64 timestampTicksPerSecond = 0;
1457 QD3D12QueryHeap timestampQueryHeap;
1458 QD3D12StagingArea timestampReadbackArea;
1459 IDCompositionDevice *dcompDevice = nullptr;
1460 QD3D12SwapChain *currentSwapChain = nullptr;
1461 QSet<QD3D12SwapChain *> swapchains;
1462 QD3D12ShaderBytecodeCache shaderBytecodeCache;
1463 QVarLengthArray<QD3D12Readback, 4> activeReadbacks;
1464 bool offscreenActive = false;
1465 QD3D12CommandBuffer *offscreenCb[QD3D12_FRAMES_IN_FLIGHT] = {};
1466 UINT shadingRateImageTileSize = 0;
1467 ID3D12CommandSignature *drawCommandSignature = nullptr;
1468 ID3D12CommandSignature *drawIndexedCommandSignature = nullptr;
1469#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1470 ID3D12PipelineLibrary1 *pipelineLibrary = nullptr;
1471 // CreatePipelineLibrary() does not copy: the blob must stay alive and
1472 // unmodified for as long as the library does.
1473 QByteArray pipelineLibraryBlob;
1474 // StorePipeline() fails if the name is taken already.
1475 QSet<QByteArray> pipelineLibraryNames;
1476#endif
1477
1478 struct {
1479 bool multiView = false;
1480 bool textureViewFormat = false;
1481 bool vrs = false;
1482 bool vrsMap = false;
1483 bool vrsAdditionalRates = false;
1484 } caps;
1485};
1486
1487QT_END_NAMESPACE
1488
1489#endif // __ID3D12Device2_INTERFACE_DEFINED__
1490
1491#endif
#define __has_include(x)