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.cpp
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#include "qrhid3d12_p.h"
6#include "qshader_p.h"
7#include <qmath.h>
8#include <QtCore/private/qsystemerror_p.h>
9#include <QtCore/qcryptographichash.h>
10#include <QtCore/qendian.h>
11#include <comdef.h>
13#include "cs_mipmap_p.h"
14#include "cs_mipmap_3d_p.h"
15
16#include <utility>
17
18#if __has_include(<pix.h>)
19#include <pix.h>
20#define QRHI_D3D12_HAS_OLD_PIX
21#endif
22
23#ifdef __ID3D12Device2_INTERFACE_DEFINED__
24
25QT_BEGIN_NAMESPACE
26
27/*
28 Direct 3D 12 backend.
29*/
30
31/*!
32 \class QRhiD3D12InitParams
33 \inmodule QtGuiPrivate
34 \inheaderfile rhi/qrhi.h
35 \brief Direct3D 12 specific initialization parameters.
36
37 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
38 for details.
39
40 A D3D12-based QRhi needs no special parameters for initialization. If
41 desired, enableDebugLayer can be set to \c true to enable the Direct3D
42 debug layer. This can be useful during development, but should be avoided
43 in production builds.
44
45 \badcode
46 QRhiD3D12InitParams params;
47 params.enableDebugLayer = true;
48 rhi = QRhi::create(QRhi::D3D12, &params);
49 \endcode
50
51 \note QRhiSwapChain should only be used in combination with QWindow
52 instances that have their surface type set to QSurface::Direct3DSurface.
53
54 \section2 Working with existing Direct3D 12 devices
55
56 When interoperating with another graphics engine, it may be necessary to
57 get a QRhi instance that uses the same Direct3D device. This can be
58 achieved by passing a pointer to a QRhiD3D12NativeHandles to
59 QRhi::create(). QRhi does not take ownership of any of the external
60 objects.
61
62 Sometimes, for example when using QRhi in combination with OpenXR, one will
63 want to specify which adapter to use, and optionally, which feature level
64 to request on the device, while leaving the device creation to QRhi. This
65 is achieved by leaving the device pointer set to null, while specifying the
66 adapter LUID and feature level.
67
68 Optionally the ID3D12CommandQueue can be specified as well, by setting \c
69 commandQueue to a non-null value.
70 */
71
72/*!
73 \variable QRhiD3D12InitParams::enableDebugLayer
74
75 When set to true, the debug layer is enabled, if installed and available.
76 The default value is false.
77
78 The messages from the debug layer are printed via qDebug, unless the debug
79 layer is too old to support message callbacks, in which case the messages
80 are only sent to the debug output.
81*/
82
83/*!
84 \variable QRhiD3D12InitParams::enableGpuBasedValidation
85 \since 6.13
86
87 When set to true, and enableDebugLayer is true as well, GPU-based
88 validation is enabled in the debug layer. This validates what can only be
89 checked while the GPU executes the commands, such as the state of the
90 resources accessed through descriptors, at a significant performance cost.
91 The default value is false.
92
93 \note With Vulkan the similar feature, GPU-assisted validation in the
94 validation layer, is enabled by setting the environment variable
95 \c{VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1}.
96*/
97
98/*!
99 \class QRhiD3D12NativeHandles
100 \inmodule QtGuiPrivate
101 \inheaderfile rhi/qrhi.h
102 \brief Holds the D3D12 device used by the QRhi.
103
104 \note The class uses \c{void *} as the type since including the COM-based
105 \c{d3d12.h} headers is not acceptable here. The actual types are
106 \c{ID3D12Device *} and \c{ID3D12CommandQueue *}.
107
108 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
109 for details.
110 */
111
112/*!
113 \variable QRhiD3D12NativeHandles::dev
114
115 Points to a
116 \l{https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nn-d3d12-id3d12device}{ID3D12Device}
117 or left set to \nullptr if no existing device is to be imported.
118*/
119
120/*!
121 \variable QRhiD3D12NativeHandles::minimumFeatureLevel
122
123 Specifies the \b minimum feature level passed to
124 \l{https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-d3d12createdevice}{D3D12CreateDevice()}.
125 When not set, \c{D3D_FEATURE_LEVEL_11_0} is used. See
126 \l{https://learn.microsoft.com/en-us/windows/win32/direct3d12/hardware-feature-levels}{this
127 page} for details.
128
129 Relevant only when QRhi creates the device, ignored when importing a device
130 and device context.
131*/
132
133/*!
134 \variable QRhiD3D12NativeHandles::adapterLuidLow
135
136 The low part of the local identifier (LUID) of the DXGI adapter to use.
137 Relevant only when QRhi creates the device, ignored when importing a device
138 and device context.
139*/
140
141/*!
142 \variable QRhiD3D12NativeHandles::adapterLuidHigh
143
144 The high part of the local identifier (LUID) of the DXGI adapter to use.
145 Relevant only when QRhi creates the device, ignored when importing a device
146 and device context.
147*/
148
149/*!
150 \variable QRhiD3D12NativeHandles::commandQueue
151
152 When set, must point to a
153 \l{https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nn-d3d12-id3d12commandqueue}{ID3D12CommandQueue}.
154 It allows to optionally import a command queue as well, in addition to a
155 device.
156*/
157
158/*!
159 \class QRhiD3D12CommandBufferNativeHandles
160 \inmodule QtGuiPrivate
161 \inheaderfile rhi/qrhi.h
162 \brief Holds the ID3D12GraphicsCommandList1 object that is backing a QRhiCommandBuffer.
163
164 \note The command list object is only guaranteed to be valid, and
165 in recording state, while recording a frame. That is, between a
166 \l{QRhi::beginFrame()}{beginFrame()} - \l{QRhi::endFrame()}{endFrame()} or
167 \l{QRhi::beginOffscreenFrame()}{beginOffscreenFrame()} -
168 \l{QRhi::endOffscreenFrame()}{endOffscreenFrame()} pair.
169
170 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
171 for details.
172 */
173
174/*!
175 \variable QRhiD3D12CommandBufferNativeHandles::commandList
176*/
177
178// https://learn.microsoft.com/en-us/windows/win32/direct3d12/hardware-feature-levels
179static const D3D_FEATURE_LEVEL MIN_FEATURE_LEVEL = D3D_FEATURE_LEVEL_11_0;
180
181QRhiD3D12::QRhiD3D12(QRhiD3D12InitParams *params, QRhiD3D12NativeHandles *importParams)
182{
183 debugLayer = params->enableDebugLayer;
184 gpuBasedValidation = params->enableGpuBasedValidation;
185 if (importParams) {
186 if (importParams->dev) {
187 ID3D12Device *d3d12Device = reinterpret_cast<ID3D12Device *>(importParams->dev);
188 if (SUCCEEDED(d3d12Device->QueryInterface(__uuidof(ID3D12Device2), reinterpret_cast<void **>(&dev)))) {
189 // get rid of the ref added by QueryInterface
190 d3d12Device->Release();
191 importedDevice = true;
192 } else {
193 qWarning("ID3D12Device2 not supported, cannot import device");
194 }
195 }
196 if (importParams->commandQueue) {
197 cmdQueue = reinterpret_cast<ID3D12CommandQueue *>(importParams->commandQueue);
198 importedCommandQueue = true;
199 }
200 minimumFeatureLevel = D3D_FEATURE_LEVEL(importParams->minimumFeatureLevel);
201 adapterLuid.LowPart = importParams->adapterLuidLow;
202 adapterLuid.HighPart = importParams->adapterLuidHigh;
203 }
204}
205
206template <class Int>
207inline Int aligned(Int v, Int byteAlign)
208{
209 return (v + byteAlign - 1) & ~(byteAlign - 1);
210}
211
212static inline UINT calcSubresource(UINT mipSlice, UINT arraySlice, UINT mipLevels)
213{
214 return mipSlice + arraySlice * mipLevels;
215}
216
217static inline QD3D12RenderTargetData *rtData(QRhiRenderTarget *rt)
218{
219 switch (rt->resourceType()) {
220 case QRhiResource::SwapChainRenderTarget:
221 return &QRHI_RES(QD3D12SwapChainRenderTarget, rt)->d;
222 case QRhiResource::TextureRenderTarget:
223 return &QRHI_RES(QD3D12TextureRenderTarget, rt)->d;
224 break;
225 default:
226 break;
227 }
228 Q_UNREACHABLE_RETURN(nullptr);
229}
230
231static D3D12_MESSAGE_ID qd3d12_suppressed_messages[] = {
232 // there is no way of knowing the clear color upfront
233 D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE,
234 // same for the depth-stencil clear values
235 D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_MISMATCHINGCLEARVALUE,
236 // we have no control over viewport and scissor rects
237 D3D12_MESSAGE_ID_DRAW_EMPTY_SCISSOR_RECTANGLE,
238 // a miss in the pipeline library is perfectly normal, it just means the
239 // pipeline state has to be built now
240 D3D12_MESSAGE_ID_LOADPIPELINE_NAMENOTFOUND
241};
242
243#ifdef QRHI_D3D12_INFOQUEUE1_AVAILABLE
244static void __stdcall qd3d12_message_callback(D3D12_MESSAGE_CATEGORY category,
245 D3D12_MESSAGE_SEVERITY severity,
246 D3D12_MESSAGE_ID id,
247 LPCSTR description,
248 void *context)
249{
250 Q_UNUSED(category);
251 Q_UNUSED(context);
252
253 // The callback is registered with IGNORE_FILTERS, so apply the same
254 // filtering the storage filter does.
255 if (severity == D3D12_MESSAGE_SEVERITY_INFO)
256 return;
257 for (D3D12_MESSAGE_ID suppressedId : qd3d12_suppressed_messages) {
258 if (id == suppressedId)
259 return;
260 }
261
262 // Called on the thread that made the offending call, from within the D3D12
263 // call itself; must not call back into D3D12 from here.
264 qDebug("D3D12: %s", description);
265}
266#endif
267
268bool QRhiD3D12::create(QRhi::Flags flags)
269{
270 rhiFlags = flags;
271
272 UINT factoryFlags = 0;
273 if (debugLayer)
274 factoryFlags |= DXGI_CREATE_FACTORY_DEBUG;
275 HRESULT hr = CreateDXGIFactory2(factoryFlags, __uuidof(IDXGIFactory2), reinterpret_cast<void **>(&dxgiFactory));
276 if (FAILED(hr)) {
277 // retry without debug, if it was requested (to match D3D11 backend behavior)
278 if (debugLayer) {
279 qCDebug(QRHI_LOG_INFO, "Debug layer was requested but is not available. "
280 "Attempting to create DXGIFactory2 without it.");
281 factoryFlags &= ~DXGI_CREATE_FACTORY_DEBUG;
282 hr = CreateDXGIFactory2(factoryFlags, __uuidof(IDXGIFactory2), reinterpret_cast<void **>(&dxgiFactory));
283 }
284 if (SUCCEEDED(hr)) {
285 debugLayer = false;
286 } else {
287 qWarning("CreateDXGIFactory2() failed to create DXGI factory: %s",
288 qPrintable(QSystemError::windowsComString(hr)));
289 return false;
290 }
291 }
292
293 if (qEnvironmentVariableIsSet("QT_D3D_MAX_FRAME_LATENCY"))
294 maxFrameLatency = UINT(qMax(0, qEnvironmentVariableIntValue("QT_D3D_MAX_FRAME_LATENCY")));
295 if (maxFrameLatency != 0)
296 qCDebug(QRHI_LOG_INFO, "Using frame latency waitable object with max frame latency %u", maxFrameLatency);
297
298 supportsAllowTearing = false;
299 IDXGIFactory5 *factory5 = nullptr;
300 if (SUCCEEDED(dxgiFactory->QueryInterface(__uuidof(IDXGIFactory5), reinterpret_cast<void **>(&factory5)))) {
301 BOOL allowTearing = false;
302 if (SUCCEEDED(factory5->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allowTearing, sizeof(allowTearing))))
303 supportsAllowTearing = allowTearing;
304 factory5->Release();
305 }
306
307 if (debugLayer) {
308 ID3D12Debug1 *debug = nullptr;
309 if (SUCCEEDED(D3D12GetDebugInterface(__uuidof(ID3D12Debug1), reinterpret_cast<void **>(&debug)))) {
310 qCDebug(QRHI_LOG_INFO, "Enabling D3D12 debug layer");
311 debug->EnableDebugLayer();
312 if (gpuBasedValidation) {
313 qCDebug(QRHI_LOG_INFO, "Enabling D3D12 GPU-based validation");
314 debug->SetEnableGPUBasedValidation(TRUE);
315 }
316 debug->Release();
317 }
318 }
319
320 activeAdapter = nullptr;
321
322 if (!importedDevice) {
323 IDXGIAdapter1 *adapter;
324 int requestedAdapterIndex = -1;
325 if (qEnvironmentVariableIsSet("QT_D3D_ADAPTER_INDEX"))
326 requestedAdapterIndex = qEnvironmentVariableIntValue("QT_D3D_ADAPTER_INDEX");
327
328 if (requestedRhiAdapter)
329 adapterLuid = static_cast<QD3D12Adapter *>(requestedRhiAdapter)->luid;
330
331 // importParams or requestedRhiAdapter may specify an adapter by the luid, use that in the absence of an env.var. override.
332 if (requestedAdapterIndex < 0 && (adapterLuid.LowPart || adapterLuid.HighPart)) {
333 for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
334 DXGI_ADAPTER_DESC1 desc;
335 adapter->GetDesc1(&desc);
336 adapter->Release();
337 if (desc.AdapterLuid.LowPart == adapterLuid.LowPart
338 && desc.AdapterLuid.HighPart == adapterLuid.HighPart)
339 {
340 requestedAdapterIndex = adapterIndex;
341 break;
342 }
343 }
344 }
345
346 if (requestedAdapterIndex < 0 && flags.testFlag(QRhi::PreferSoftwareRenderer)) {
347 for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
348 DXGI_ADAPTER_DESC1 desc;
349 adapter->GetDesc1(&desc);
350 adapter->Release();
351 if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) {
352 requestedAdapterIndex = adapterIndex;
353 break;
354 }
355 }
356 }
357
358 for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
359 DXGI_ADAPTER_DESC1 desc;
360 adapter->GetDesc1(&desc);
361 const QString name = QString::fromUtf16(reinterpret_cast<char16_t *>(desc.Description));
362 qCDebug(QRHI_LOG_INFO, "Adapter %d: '%s' (vendor 0x%X device 0x%X flags 0x%X)",
363 adapterIndex,
364 qPrintable(name),
365 desc.VendorId,
366 desc.DeviceId,
367 desc.Flags);
368 if (!activeAdapter && (requestedAdapterIndex < 0 || requestedAdapterIndex == adapterIndex)) {
369 activeAdapter = adapter;
370 adapterLuid = desc.AdapterLuid;
371 QRhiD3D::fillDriverInfo(&driverInfoStruct, desc);
372 qCDebug(QRHI_LOG_INFO, " using this adapter");
373 } else {
374 adapter->Release();
375 }
376 }
377 if (!activeAdapter) {
378 qWarning("No adapter");
379 return false;
380 }
381
382 if (minimumFeatureLevel == 0)
383 minimumFeatureLevel = MIN_FEATURE_LEVEL;
384
385 hr = D3D12CreateDevice(activeAdapter,
386 minimumFeatureLevel,
387 __uuidof(ID3D12Device2),
388 reinterpret_cast<void **>(&dev));
389 if (FAILED(hr)) {
390 qWarning("Failed to create D3D12 device: %s", qPrintable(QSystemError::windowsComString(hr)));
391 return false;
392 }
393 } else {
394 Q_ASSERT(dev);
395 // cannot just get a IDXGIDevice from the ID3D12Device anymore, look up the adapter instead
396 adapterLuid = dev->GetAdapterLuid();
397 IDXGIAdapter1 *adapter;
398 for (int adapterIndex = 0; dxgiFactory->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
399 DXGI_ADAPTER_DESC1 desc;
400 adapter->GetDesc1(&desc);
401 if (desc.AdapterLuid.LowPart == adapterLuid.LowPart
402 && desc.AdapterLuid.HighPart == adapterLuid.HighPart)
403 {
404 activeAdapter = adapter;
405 QRhiD3D::fillDriverInfo(&driverInfoStruct, desc);
406 break;
407 } else {
408 adapter->Release();
409 }
410 }
411 if (!activeAdapter) {
412 qWarning("No adapter");
413 return false;
414 }
415 qCDebug(QRHI_LOG_INFO, "Using imported device %p", dev);
416 }
417
418 QDxgiVSyncService::instance()->refAdapter(adapterLuid);
419
420 if (debugLayer) {
421 ID3D12InfoQueue *infoQueue;
422 if (SUCCEEDED(dev->QueryInterface(__uuidof(ID3D12InfoQueue), reinterpret_cast<void **>(&infoQueue)))) {
423 if (qEnvironmentVariableIntValue("QT_D3D_DEBUG_BREAK")) {
424 infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, true);
425 infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true);
426 infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, true);
427 }
428 D3D12_INFO_QUEUE_FILTER filter = {};
429 filter.DenyList.NumIDs = UINT(std::size(qd3d12_suppressed_messages));
430 filter.DenyList.pIDList = qd3d12_suppressed_messages;
431 // Setting the filter would enable Info messages (e.g. about
432 // resource creation) which we don't need.
433 D3D12_MESSAGE_SEVERITY infoSev = D3D12_MESSAGE_SEVERITY_INFO;
434 filter.DenyList.NumSeverities = 1;
435 filter.DenyList.pSeverityList = &infoSev;
436 infoQueue->PushStorageFilter(&filter);
437#ifdef QRHI_D3D12_INFOQUEUE1_AVAILABLE
438 // Route the messages to qDebug, like QVulkanInstance does with the
439 // Vulkan validation layer messages. Needs a recent enough debug
440 // layer, otherwise this is not possible and the messages will only
441 // show up on the debug output.
442 if (SUCCEEDED(infoQueue->QueryInterface(__uuidof(ID3D12InfoQueue1), reinterpret_cast<void **>(&infoQueue1)))) {
443 // Registering with IGNORE_FILTERS, and so filtering in the
444 // callback instead, is not optional: with FLAG_NONE the
445 // callback stops getting invoked once the debug output is muted
446 // below.
447 if (SUCCEEDED(infoQueue1->RegisterMessageCallback(qd3d12_message_callback,
448 D3D12_MESSAGE_CALLBACK_IGNORE_FILTERS,
449 nullptr,
450 &infoQueueCallbackCookie)))
451 {
452 // Do not want the messages twice, so stop them from going
453 // to the debug output now that we print them ourselves.
454 infoQueue1->SetMuteDebugOutput(true);
455 } else {
456 infoQueue1->Release();
457 infoQueue1 = nullptr;
458 }
459 }
460#endif
461 infoQueue->Release();
462 }
463 }
464
465 if (!importedCommandQueue) {
466 D3D12_COMMAND_QUEUE_DESC queueDesc = {};
467 queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
468 queueDesc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
469 hr = dev->CreateCommandQueue(&queueDesc, __uuidof(ID3D12CommandQueue), reinterpret_cast<void **>(&cmdQueue));
470 if (FAILED(hr)) {
471 qWarning("Failed to create command queue: %s", qPrintable(QSystemError::windowsComString(hr)));
472 return false;
473 }
474 }
475
476 hr = dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void **>(&fullFence));
477 if (FAILED(hr)) {
478 qWarning("Failed to create fence: %s", qPrintable(QSystemError::windowsComString(hr)));
479 return false;
480 }
481 fullFenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
482 fullFenceCounter = 0;
483
484 for (int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
485 hr = dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
486 __uuidof(ID3D12CommandAllocator),
487 reinterpret_cast<void **>(&cmdAllocators[i]));
488 if (FAILED(hr)) {
489 qWarning("Failed to create command allocator: %s", qPrintable(QSystemError::windowsComString(hr)));
490 return false;
491 }
492 }
493
494 if (!vma.create(dev, activeAdapter)) {
495 qWarning("Failed to initialize graphics memory suballocator");
496 return false;
497 }
498
499 if (!rtvPool.create(dev, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, "main RTV pool")) {
500 qWarning("Could not create RTV pool");
501 return false;
502 }
503
504 if (!dsvPool.create(dev, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, "main DSV pool")) {
505 qWarning("Could not create DSV pool");
506 return false;
507 }
508
509 if (!cbvSrvUavPool.create(dev, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, "main CBV-SRV-UAV pool")) {
510 qWarning("Could not create CBV-SRV-UAV pool");
511 return false;
512 }
513
514 resourcePool.create("main resource pool");
515 pipelinePool.create("main pipeline pool");
516 rootSignaturePool.create("main root signature pool");
517 releaseQueue.create(&resourcePool, &pipelinePool, &rootSignaturePool);
518 barrierGen.create(&resourcePool);
519
520 if (!samplerMgr.create(dev)) {
521 qWarning("Could not create sampler pool and shader-visible sampler heap");
522 return false;
523 }
524
525 mipmapGen.create(this);
526 mipmapGen3D.create(this);
527
528 const qint32 smallStagingSize = aligned(SMALL_STAGING_AREA_BYTES_PER_FRAME_START, QD3D12StagingArea::ALIGNMENT);
529 for (int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
530 if (!smallStagingAreas[i].create(this, smallStagingSize, D3D12_HEAP_TYPE_UPLOAD)) {
531 qWarning("Could not create host-visible staging area");
532 return false;
533 }
534 QString decoratedName = QLatin1String("Small staging area buffer/");
535 decoratedName += QString::number(i);
536 smallStagingAreas[i].mem.buffer->SetName(reinterpret_cast<LPCWSTR>(decoratedName.utf16()));
537 }
538
539 if (!shaderVisibleCbvSrvUavHeap.create(dev,
540 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
541 SHADER_VISIBLE_CBV_SRV_UAV_HEAP_PER_FRAME_START_SIZE))
542 {
543 qWarning("Could not create first shader-visible CBV/SRV/UAV heap");
544 return false;
545 }
546
547 if (flags.testFlag(QRhi::EnableTimestamps)) {
548 static bool wantsStablePowerState = qEnvironmentVariableIntValue("QT_D3D_STABLE_POWER_STATE");
549 //
550 // https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-setstablepowerstate
551 //
552 // NB! This is a _global_ setting, affecting other processes (and 3D
553 // APIs such as Vulkan), as long as this application is running. Hence
554 // making it an env.var. for now. Never enable it in production. But
555 // extremely useful for the GPU timings with NVIDIA at least; the
556 // timestamps become stable and smooth, making the number readable and
557 // actually useful e.g. in Quick 3D's DebugView when this is enabled.
558 // (otherwise the number's all over the place)
559 //
560 // See also
561 // https://developer.nvidia.com/blog/advanced-api-performance-setstablepowerstate/
562 // for possible other approaches.
563 //
564 if (wantsStablePowerState)
565 dev->SetStablePowerState(TRUE);
566
567 hr = cmdQueue->GetTimestampFrequency(&timestampTicksPerSecond);
568 if (FAILED(hr)) {
569 qWarning("Failed to query timestamp frequency: %s",
570 qPrintable(QSystemError::windowsComString(hr)));
571 return false;
572 }
573 if (!timestampQueryHeap.create(dev, QD3D12_FRAMES_IN_FLIGHT * 2, D3D12_QUERY_HEAP_TYPE_TIMESTAMP)) {
574 qWarning("Failed to create timestamp query pool");
575 return false;
576 }
577 const quint32 readbackBufSize = QD3D12_FRAMES_IN_FLIGHT * 2 * sizeof(quint64);
578 if (!timestampReadbackArea.create(this, readbackBufSize, D3D12_HEAP_TYPE_READBACK)) {
579 qWarning("Failed to create timestamp readback buffer");
580 return false;
581 }
582 timestampReadbackArea.mem.buffer->SetName(L"Timestamp readback buffer");
583 memset(timestampReadbackArea.mem.p, 0, readbackBufSize);
584 }
585
586 caps = {};
587 D3D12_FEATURE_DATA_D3D12_OPTIONS3 options3 = {};
588 if (SUCCEEDED(dev->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS3, &options3, sizeof(options3)))) {
589 caps.multiView = options3.ViewInstancingTier != D3D12_VIEW_INSTANCING_TIER_NOT_SUPPORTED;
590 // https://microsoft.github.io/DirectX-Specs/d3d/RelaxedCasting.html
591 caps.textureViewFormat = options3.CastingFullyTypedFormatSupported;
592 }
593
594#ifdef QRHI_D3D12_CL5_AVAILABLE
595 D3D12_FEATURE_DATA_D3D12_OPTIONS6 options6 = {};
596 if (SUCCEEDED(dev->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS6, &options6, sizeof(options6)))) {
597 caps.vrs = options6.VariableShadingRateTier != D3D12_VARIABLE_SHADING_RATE_TIER_NOT_SUPPORTED;
598 caps.vrsMap = options6.VariableShadingRateTier == D3D12_VARIABLE_SHADING_RATE_TIER_2;
599 caps.vrsAdditionalRates = options6.AdditionalShadingRatesSupported;
600 shadingRateImageTileSize = options6.ShadingRateImageTileSize;
601 }
602#else
603 caps.vrs = false;
604 caps.vrsMap = false;
605 caps.vrsAdditionalRates = false;
606#endif
607
608 {
609 D3D12_INDIRECT_ARGUMENT_DESC arg = {};
610 arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW;
611
612 D3D12_COMMAND_SIGNATURE_DESC sigDesc = {};
613 sigDesc.ByteStride = sizeof(D3D12_DRAW_ARGUMENTS);
614 sigDesc.NumArgumentDescs = 1;
615 sigDesc.pArgumentDescs = &arg;
616
617 hr = dev->CreateCommandSignature(&sigDesc, nullptr, IID_PPV_ARGS(&drawCommandSignature));
618 if (FAILED(hr)) {
619 qWarning("Failed to create draw command signature: %s", qPrintable(QSystemError::windowsComString(hr)));
620 return false;
621 }
622 }
623
624 {
625 D3D12_INDIRECT_ARGUMENT_DESC arg = {};
626 arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED;
627
628 D3D12_COMMAND_SIGNATURE_DESC sigDesc = {};
629 sigDesc.ByteStride = sizeof(D3D12_DRAW_INDEXED_ARGUMENTS);
630 sigDesc.NumArgumentDescs = 1;
631 sigDesc.pArgumentDescs = &arg;
632
633 hr = dev->CreateCommandSignature(&sigDesc, nullptr, IID_PPV_ARGS(&drawIndexedCommandSignature));
634 if (FAILED(hr)) {
635 qWarning("Failed to create draw indexed command signature: %s", qPrintable(QSystemError::windowsComString(hr)));
636 return false;
637 }
638 }
639
640 {
641 D3D12_INDIRECT_ARGUMENT_DESC arg = {};
642 arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
643
644 D3D12_COMMAND_SIGNATURE_DESC sigDesc = {};
645 sigDesc.ByteStride = sizeof(D3D12_DISPATCH_ARGUMENTS);
646 sigDesc.NumArgumentDescs = 1;
647 sigDesc.pArgumentDescs = &arg;
648
649 hr = dev->CreateCommandSignature(&sigDesc, nullptr, IID_PPV_ARGS(&dispatchCommandSignature));
650 if (FAILED(hr)) {
651 qWarning("Failed to create dispatch command signature: %s", qPrintable(QSystemError::windowsComString(hr)));
652 return false;
653 }
654 }
655
656 deviceLost = false;
657 offscreenActive = false;
658
659 nativeHandlesStruct.dev = dev;
660 nativeHandlesStruct.minimumFeatureLevel = minimumFeatureLevel;
661 nativeHandlesStruct.adapterLuidLow = adapterLuid.LowPart;
662 nativeHandlesStruct.adapterLuidHigh = adapterLuid.HighPart;
663 nativeHandlesStruct.commandQueue = cmdQueue;
664
665 return true;
666}
667
668void QRhiD3D12::destroy()
669{
670 if (!deviceLost && fullFence && fullFenceEvent)
671 waitGpu();
672
673 releaseQueue.releaseAll();
674
675 for (int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
676 if (offscreenCb[i]) {
677 if (offscreenCb[i]->cmdList)
678 offscreenCb[i]->cmdList->Release();
679 delete offscreenCb[i];
680 offscreenCb[i] = nullptr;
681 }
682 }
683
684 timestampQueryHeap.destroy();
685 timestampReadbackArea.destroy();
686
687 shaderVisibleCbvSrvUavHeap.destroy();
688
689 for (int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i)
690 smallStagingAreas[i].destroy();
691
692 mipmapGen.destroy();
693 mipmapGen3D.destroy();
694 samplerMgr.destroy();
695 resourcePool.destroy();
696 pipelinePool.destroy();
697 rootSignaturePool.destroy();
698 rtvPool.destroy();
699 dsvPool.destroy();
700 cbvSrvUavPool.destroy();
701
702 for (int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
703 if (cmdAllocators[i]) {
704 cmdAllocators[i]->Release();
705 cmdAllocators[i] = nullptr;
706 }
707 }
708
709 if (fullFenceEvent) {
710 CloseHandle(fullFenceEvent);
711 fullFenceEvent = nullptr;
712 }
713
714 if (fullFence) {
715 fullFence->Release();
716 fullFence = nullptr;
717 }
718
719 if (!importedCommandQueue) {
720 if (cmdQueue) {
721 cmdQueue->Release();
722 cmdQueue = nullptr;
723 }
724 }
725
726 vma.destroy();
727
728#ifdef QRHI_D3D12_INFOQUEUE1_AVAILABLE
729 if (infoQueue1) {
730 infoQueue1->UnregisterMessageCallback(infoQueueCallbackCookie);
731 infoQueue1->Release();
732 infoQueue1 = nullptr;
733 infoQueueCallbackCookie = 0;
734 }
735#endif
736
737 if (!importedDevice) {
738 if (dev) {
739 dev->Release();
740 dev = nullptr;
741 }
742 }
743
744 if (dcompDevice) {
745 dcompDevice->Release();
746 dcompDevice = nullptr;
747 }
748
749 if (activeAdapter) {
750 activeAdapter->Release();
751 activeAdapter = nullptr;
752 }
753
754 if (dxgiFactory) {
755 dxgiFactory->Release();
756 dxgiFactory = nullptr;
757 }
758
759 QDxgiVSyncService::instance()->derefAdapter(adapterLuid);
760
761 adapterLuid = {};
762 importedDevice = false;
763 importedCommandQueue = false;
764
765 if (drawCommandSignature) {
766 drawCommandSignature->Release();
767 drawCommandSignature = nullptr;
768 }
769
770 if (drawIndexedCommandSignature) {
771 drawIndexedCommandSignature->Release();
772 drawIndexedCommandSignature = nullptr;
773 }
774
775 if (dispatchCommandSignature) {
776 dispatchCommandSignature->Release();
777 dispatchCommandSignature = nullptr;
778 }
779
780 for (ID3D12CommandSignature *sig : std::as_const(drawCommandSignaturesByStride))
781 sig->Release();
782 drawCommandSignaturesByStride.clear();
783
784 for (ID3D12CommandSignature *sig : std::as_const(drawIndexedCommandSignaturesByStride))
785 sig->Release();
786 drawIndexedCommandSignaturesByStride.clear();
787
788 destroyPipelineLibrary();
789}
790
791QRhi::AdapterList QRhiD3D12::enumerateAdaptersBeforeCreate(QRhiNativeHandles *nativeHandles) const
792{
793 LUID requestedLuid = {};
794 if (nativeHandles) {
795 QRhiD3D12NativeHandles *h = static_cast<QRhiD3D12NativeHandles *>(nativeHandles);
796 const LUID adapterLuid = { h->adapterLuidLow, h->adapterLuidHigh };
797 if (adapterLuid.LowPart || adapterLuid.HighPart)
798 requestedLuid = adapterLuid;
799 }
800
801 IDXGIFactory2 *dxgi = nullptr;
802 if (FAILED(CreateDXGIFactory2(0, __uuidof(IDXGIFactory2), reinterpret_cast<void **>(&dxgi))))
803 return {};
804
805 QRhi::AdapterList list;
806 IDXGIAdapter1 *adapter;
807 for (int adapterIndex = 0; dxgi->EnumAdapters1(UINT(adapterIndex), &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
808 DXGI_ADAPTER_DESC1 desc;
809 adapter->GetDesc1(&desc);
810 adapter->Release();
811 if (requestedLuid.LowPart || requestedLuid.HighPart) {
812 if (desc.AdapterLuid.LowPart != requestedLuid.LowPart
813 || desc.AdapterLuid.HighPart != requestedLuid.HighPart)
814 {
815 continue;
816 }
817 }
818 QD3D12Adapter *a = new QD3D12Adapter;
819 a->luid = desc.AdapterLuid;
820 QRhiD3D::fillDriverInfo(&a->adapterInfo, desc);
821 list.append(a);
822 }
823
824 dxgi->Release();
825 return list;
826}
827
828QRhiDriverInfo QD3D12Adapter::info() const
829{
830 return adapterInfo;
831}
832
833QList<int> QRhiD3D12::supportedSampleCounts() const
834{
835 return { 1, 2, 4, 8 };
836}
837
838QList<QSize> QRhiD3D12::supportedShadingRates(int sampleCount) const
839{
840 QList<QSize> sizes;
841 switch (sampleCount) {
842 case 0:
843 case 1:
844 if (caps.vrsAdditionalRates) {
845 sizes.append(QSize(4, 4));
846 sizes.append(QSize(4, 2));
847 sizes.append(QSize(2, 4));
848 }
849 sizes.append(QSize(2, 2));
850 sizes.append(QSize(2, 1));
851 sizes.append(QSize(1, 2));
852 break;
853 case 2:
854 if (caps.vrsAdditionalRates)
855 sizes.append(QSize(2, 4));
856 sizes.append(QSize(2, 2));
857 sizes.append(QSize(2, 1));
858 sizes.append(QSize(1, 2));
859 break;
860 case 4:
861 sizes.append(QSize(2, 2));
862 sizes.append(QSize(2, 1));
863 sizes.append(QSize(1, 2));
864 break;
865 default:
866 break;
867 }
868 sizes.append(QSize(1, 1));
869 return sizes;
870}
871
872QRhiSwapChain *QRhiD3D12::createSwapChain()
873{
874 return new QD3D12SwapChain(this);
875}
876
877QRhiBuffer *QRhiD3D12::createBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, quint32 size)
878{
879 return new QD3D12Buffer(this, type, usage, size);
880}
881
882int QRhiD3D12::ubufAlignment() const
883{
884 return D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT; // 256
885}
886
887bool QRhiD3D12::isYUpInFramebuffer() const
888{
889 return false;
890}
891
892bool QRhiD3D12::isYUpInNDC() const
893{
894 return true;
895}
896
897bool QRhiD3D12::isClipDepthZeroToOne() const
898{
899 return true;
900}
901
902QMatrix4x4 QRhiD3D12::clipSpaceCorrMatrix() const
903{
904 // Like with Vulkan, but Y is already good.
905
906 // NB the ctor takes row-major
907 static constexpr QMatrix4x4 m(1.0f, 0.0f, 0.0f, 0.0f,
908 0.0f, 1.0f, 0.0f, 0.0f,
909 0.0f, 0.0f, 0.5f, 0.5f,
910 0.0f, 0.0f, 0.0f, 1.0f);
911 return m;
912}
913
914bool QRhiD3D12::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const
915{
916 Q_UNUSED(flags);
917
918 if (format >= QRhiTexture::ETC2_RGB8 && format <= QRhiTexture::ASTC_12x12)
919 return false;
920
921 return true;
922}
923
924bool QRhiD3D12::isFeatureSupported(QRhi::Feature feature) const
925{
926 switch (feature) {
927 case QRhi::MultisampleTexture:
928 return true;
929 case QRhi::MultisampleRenderBuffer:
930 return true;
931 case QRhi::DebugMarkers:
932#ifdef QRHI_D3D12_HAS_OLD_PIX
933 return true;
934#else
935 return false;
936#endif
937 case QRhi::Timestamps:
938 return true;
939 case QRhi::Instancing:
940 return true;
941 case QRhi::CustomInstanceStepRate:
942 return true;
943 case QRhi::PrimitiveRestart:
944 return true;
945 case QRhi::NonDynamicUniformBuffers:
946 return false;
947 case QRhi::NonFourAlignedEffectiveIndexBufferOffset:
948 return true;
949 case QRhi::NPOTTextureRepeat:
950 return true;
951 case QRhi::RedOrAlpha8IsRed:
952 return true;
953 case QRhi::ElementIndexUint:
954 return true;
955 case QRhi::Compute:
956 return true;
957 case QRhi::FragmentStoresAndAtomics:
958 return true;
959 case QRhi::WideLines:
960 return false;
961 case QRhi::VertexShaderPointSize:
962 return false;
963 case QRhi::BaseVertex:
964 return true;
965 case QRhi::BaseInstance:
966 return true;
967 case QRhi::TriangleFanTopology:
968 return false;
969 case QRhi::ReadBackNonUniformBuffer:
970 return true;
971 case QRhi::ReadBackNonBaseMipLevel:
972 return true;
973 case QRhi::TexelFetch:
974 return true;
975 case QRhi::RenderToNonBaseMipLevel:
976 return true;
977 case QRhi::IntAttributes:
978 return true;
979 case QRhi::ScreenSpaceDerivatives:
980 return true;
981 case QRhi::ReadBackAnyTextureFormat:
982 return true;
983 case QRhi::PipelineCacheDataLoadSave:
984#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
985 return true;
986#else
987 return false;
988#endif
989 case QRhi::ImageDataStride:
990 return true;
991 case QRhi::RenderBufferImport:
992 return false;
993 case QRhi::ThreeDimensionalTextures:
994 return true;
995 case QRhi::RenderTo3DTextureSlice:
996 return true;
997 case QRhi::TextureArrays:
998 return true;
999 case QRhi::Tessellation:
1000 return true;
1001 case QRhi::GeometryShader:
1002 return true;
1003 case QRhi::TextureArrayRange:
1004 return true;
1005 case QRhi::NonFillPolygonMode:
1006 return true;
1007 case QRhi::OneDimensionalTextures:
1008 return true;
1009 case QRhi::OneDimensionalTextureMipmaps:
1010 return false; // we generate mipmaps ourselves with compute and this is not implemented
1011 case QRhi::HalfAttributes:
1012 return true;
1013 case QRhi::RenderToOneDimensionalTexture:
1014 return true;
1015 case QRhi::ThreeDimensionalTextureMipmaps:
1016 return true;
1017 case QRhi::MultiView:
1018 return caps.multiView;
1019 case QRhi::TextureViewFormat:
1020 return caps.textureViewFormat;
1021 case QRhi::ResolveDepthStencil:
1022 // there is no Multisample Resolve support for depth/stencil formats
1023 // https://learn.microsoft.com/en-us/windows/win32/direct3ddxgi/hardware-support-for-direct3d-12-1-formats
1024 return false;
1025 case QRhi::VariableRateShading:
1026 return caps.vrs;
1027 case QRhi::VariableRateShadingMap:
1028 case QRhi::VariableRateShadingMapWithTexture:
1029 return caps.vrsMap;
1030 case QRhi::DualSourceBlend:
1031 case QRhi::PerRenderTargetBlending:
1032 case QRhi::SampleVariables:
1033 return true;
1034 case QRhi::InstanceIndexIncludesBaseInstance:
1035 return false;
1036 case QRhi::DepthClamp:
1037 return true;
1038 case QRhi::DrawIndirect:
1039 case QRhi::BaseInstanceIndirect:
1040 return drawCommandSignature != nullptr && drawIndexedCommandSignature != nullptr;
1041 case QRhi::DrawIndirectMulti:
1042 return drawCommandSignature != nullptr && drawIndexedCommandSignature != nullptr;
1043 case QRhi::ShaderDrawParameters:
1044 return false;
1045 case QRhi::DispatchIndirect:
1046 return dispatchCommandSignature != nullptr;
1047 case QRhi::PushConstants:
1048 return true;
1049 case QRhi::DrawIndirectCount:
1050 // ExecuteIndirect natively supports a GPU-supplied count buffer.
1051 return drawCommandSignature != nullptr && drawIndexedCommandSignature != nullptr;
1052 case QRhi::BufferToBufferCopy:
1053 return true;
1054 case QRhi::StaticBuffersOnGpuTimeline:
1055 return true;
1056 }
1057 return false;
1058}
1059
1060int QRhiD3D12::resourceLimit(QRhi::ResourceLimit limit) const
1061{
1062 switch (limit) {
1063 case QRhi::TextureSizeMin:
1064 return 1;
1065 case QRhi::TextureSizeMax:
1066 return 16384;
1067 case QRhi::MaxColorAttachments:
1068 return 8;
1069 case QRhi::FramesInFlight:
1070 return QD3D12_FRAMES_IN_FLIGHT;
1071 case QRhi::MaxAsyncReadbackFrames:
1072 return QD3D12_FRAMES_IN_FLIGHT;
1073 case QRhi::MaxThreadGroupsPerDimension:
1074 return 65535;
1075 case QRhi::MaxThreadsPerThreadGroup:
1076 return 1024;
1077 case QRhi::MaxThreadGroupX:
1078 return 1024;
1079 case QRhi::MaxThreadGroupY:
1080 return 1024;
1081 case QRhi::MaxThreadGroupZ:
1082 return 1024;
1083 case QRhi::TextureArraySizeMax:
1084 return 2048;
1085 case QRhi::MaxUniformBufferRange:
1086 return 65536;
1087 case QRhi::MaxVertexInputs:
1088 return 32;
1089 case QRhi::MaxVertexOutputs:
1090 return 32;
1091 case QRhi::MaxPushConstantsSize:
1092 return 128; // root constants share the root signature budget
1093 case QRhi::MaxVertexStorageBuffers:
1094 case QRhi::MaxFragmentStorageBuffers:
1095 return 128;
1096 case QRhi::MaxStorageBufferBindings:
1097 case QRhi::MaxStorageImageBindings:
1098 return INT_MAX; // binding numbers are mapped to native slots
1099 case QRhi::ShadingRateImageTileSize:
1100 return shadingRateImageTileSize;
1101 }
1102 return 0;
1103}
1104
1105const QRhiNativeHandles *QRhiD3D12::nativeHandles()
1106{
1107 return &nativeHandlesStruct;
1108}
1109
1110QRhiDriverInfo QRhiD3D12::driverInfo() const
1111{
1112 return driverInfoStruct;
1113}
1114
1115QRhiStats QRhiD3D12::statistics()
1116{
1117 QRhiStats result;
1118 result.totalPipelineCreationTime = totalPipelineCreationTime();
1119
1120 D3D12MA::Budget budgets[2]; // [gpu, system] with discreet GPU or [shared, nothing] with UMA
1121 vma.getBudget(&budgets[0], &budgets[1]);
1122 for (int i = 0; i < 2; ++i) {
1123 const D3D12MA::Statistics &stats(budgets[i].Stats);
1124 result.blockCount += stats.BlockCount;
1125 result.allocCount += stats.AllocationCount;
1126 result.usedBytes += stats.AllocationBytes;
1127 result.unusedBytes += stats.BlockBytes - stats.AllocationBytes;
1128 result.totalUsageBytes += budgets[i].UsageBytes;
1129 }
1130
1131 return result;
1132}
1133
1134bool QRhiD3D12::makeThreadLocalNativeContextCurrent()
1135{
1136 // not applicable
1137 return false;
1138}
1139
1140void QRhiD3D12::setQueueSubmitParams(QRhiNativeHandles *)
1141{
1142 // not applicable
1143}
1144
1145void QRhiD3D12::releaseCachedResources()
1146{
1147 shaderBytecodeCache.clear();
1148}
1149
1150// The pipeline library identifies pipelines by name, so we need a key that
1151// covers everything the PSO is built from. Note that the plain-data subobjects
1152// of the pipeline state stream can be hashed as they are: they are all
1153// value-initialized before their fields get set, so the padding is
1154// deterministic. The ones holding pointers cannot, and are fed in separately.
1155
1156static inline void addToKey(QCryptographicHash *h, const void *p, size_t size)
1157{
1158 h->addData(QByteArrayView(static_cast<const char *>(p), qsizetype(size)));
1159}
1160
1161template<typename T>
1162static inline void addToKey(QCryptographicHash *h, const T &v)
1163{
1164 addToKey(h, &v, sizeof(T));
1165}
1166
1167static inline void addToKey(QCryptographicHash *h, const QByteArray &b)
1168{
1169 const quint32 size = quint32(b.size());
1170 addToKey(h, size);
1171 h->addData(b);
1172}
1173
1174static inline void addToKey(QCryptographicHash *h, const QVector<quint32> &v)
1175{
1176 const quint32 count = quint32(v.count());
1177 addToKey(h, count);
1178 addToKey(h, v.constData(), v.count() * sizeof(quint32));
1179}
1180
1181bool QRhiD3D12::createPipelineLibrary(const QByteArray &blob)
1182{
1183#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1184 destroyPipelineLibrary();
1185
1186 pipelineLibraryBlob = blob;
1187 HRESULT hr = dev->CreatePipelineLibrary(pipelineLibraryBlob.isEmpty() ? nullptr
1188 : pipelineLibraryBlob.constData(),
1189 SIZE_T(pipelineLibraryBlob.size()),
1190 __uuidof(ID3D12PipelineLibrary1),
1191 reinterpret_cast<void **>(&pipelineLibrary));
1192 if (FAILED(hr)) {
1193 // E_NOTIMPL with drivers that have no pipeline library support,
1194 // D3D12_ERROR_DRIVER_VERSION_MISMATCH and
1195 // D3D12_ERROR_ADAPTER_NOT_FOUND for a stale blob. None of these are
1196 // fatal, they just mean no pipeline cache.
1197 qCDebug(QRHI_LOG_INFO, "Failed to create pipeline library: %s",
1198 qPrintable(QSystemError::windowsComString(hr)));
1199 pipelineLibrary = nullptr;
1200 pipelineLibraryBlob.clear();
1201 return false;
1202 }
1203 return true;
1204#else
1205 Q_UNUSED(blob);
1206 return false;
1207#endif
1208}
1209
1210bool QRhiD3D12::ensurePipelineLibrary()
1211{
1212#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1213 if (pipelineLibrary)
1214 return true;
1215 if (!rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
1216 return false;
1217 return createPipelineLibrary(QByteArray());
1218#else
1219 return false;
1220#endif
1221}
1222
1223void QRhiD3D12::destroyPipelineLibrary()
1224{
1225#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1226 if (pipelineLibrary) {
1227 pipelineLibrary->Release();
1228 pipelineLibrary = nullptr;
1229 }
1230 pipelineLibraryBlob.clear();
1231 pipelineLibraryNames.clear();
1232#endif
1233}
1234
1235ID3D12PipelineState *QRhiD3D12::loadOrCreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC *streamDesc,
1236 const QByteArray &cacheKey,
1237 const char *what)
1238{
1239 ID3D12PipelineState *pso = nullptr;
1240
1241#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1242 QVarLengthArray<wchar_t, 64> name;
1243 if (ensurePipelineLibrary() && !cacheKey.isEmpty()) {
1244 name.resize(cacheKey.size() + 1);
1245 for (qsizetype i = 0; i < cacheKey.size(); ++i)
1246 name[i] = wchar_t(cacheKey.at(i));
1247 name[cacheKey.size()] = 0;
1248 HRESULT hr = pipelineLibrary->LoadPipeline(name.constData(),
1249 streamDesc,
1250 __uuidof(ID3D12PipelineState),
1251 reinterpret_cast<void **>(&pso));
1252 if (SUCCEEDED(hr))
1253 return pso;
1254 }
1255#endif
1256
1257 HRESULT hr = dev->CreatePipelineState(streamDesc,
1258 __uuidof(ID3D12PipelineState),
1259 reinterpret_cast<void **>(&pso));
1260 if (FAILED(hr)) {
1261 qWarning("Failed to create %s pipeline state: %s",
1262 what, qPrintable(QSystemError::windowsComString(hr)));
1263 return nullptr;
1264 }
1265
1266#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1267 if (pipelineLibrary && !name.isEmpty() && !pipelineLibraryNames.contains(cacheKey)) {
1268 if (SUCCEEDED(pipelineLibrary->StorePipeline(name.constData(), pso)))
1269 pipelineLibraryNames.insert(cacheKey);
1270 }
1271#endif
1272
1273 return pso;
1274}
1275
1276struct QD3D12PipelineCacheDataHeader
1277{
1278 quint32 rhiId;
1279 quint32 arch;
1280 quint32 dataSize;
1281 quint32 vendorId;
1282 quint32 deviceId;
1283 quint32 reserved;
1284 quint64 adapterLuid;
1285};
1286
1287QByteArray QRhiD3D12::pipelineCacheData()
1288{
1289 static_assert(sizeof(QD3D12PipelineCacheDataHeader) == 32);
1290
1291 QByteArray data;
1292#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1293 if (!pipelineLibrary || !rhiFlags.testFlag(QRhi::EnablePipelineCacheDataSave))
1294 return data;
1295
1296 const SIZE_T dataSize = pipelineLibrary->GetSerializedSize();
1297 if (!dataSize)
1298 return data;
1299
1300 const size_t headerSize = sizeof(QD3D12PipelineCacheDataHeader);
1301 data.resize(qsizetype(headerSize + dataSize));
1302 HRESULT hr = pipelineLibrary->Serialize(data.data() + headerSize, dataSize);
1303 if (FAILED(hr)) {
1304 qCDebug(QRHI_LOG_INFO, "Failed to serialize pipeline library: %s",
1305 qPrintable(QSystemError::windowsComString(hr)));
1306 return QByteArray();
1307 }
1308
1309 QD3D12PipelineCacheDataHeader header = {};
1310 header.rhiId = pipelineCacheRhiId();
1311 header.arch = quint32(sizeof(void *));
1312 header.dataSize = quint32(dataSize);
1313 header.vendorId = quint32(driverInfoStruct.vendorId);
1314 header.deviceId = quint32(driverInfoStruct.deviceId);
1315 header.adapterLuid = (quint64(quint32(adapterLuid.HighPart)) << 32) | quint64(adapterLuid.LowPart);
1316 memcpy(data.data(), &header, headerSize);
1317#endif
1318 return data;
1319}
1320
1321void QRhiD3D12::setPipelineCacheData(const QByteArray &data)
1322{
1323#ifdef QRHI_D3D12_PIPELINE_LIBRARY_AVAILABLE
1324 if (data.isEmpty())
1325 return;
1326
1327 const size_t headerSize = sizeof(QD3D12PipelineCacheDataHeader);
1328 if (data.size() < qsizetype(headerSize)) {
1329 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Invalid blob size");
1330 return;
1331 }
1332 QD3D12PipelineCacheDataHeader header;
1333 memcpy(&header, data.constData(), headerSize);
1334
1335 const quint32 rhiId = pipelineCacheRhiId();
1336 if (header.rhiId != rhiId) {
1337 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: The data is for a different QRhi version or backend (%u, %u)",
1338 rhiId, header.rhiId);
1339 return;
1340 }
1341 const quint32 arch = quint32(sizeof(void *));
1342 if (header.arch != arch) {
1343 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Architecture does not match (%u, %u)",
1344 arch, header.arch);
1345 return;
1346 }
1347 if (header.vendorId != quint32(driverInfoStruct.vendorId)) {
1348 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: vendorId does not match (%u, %u)",
1349 quint32(driverInfoStruct.vendorId), header.vendorId);
1350 return;
1351 }
1352 if (header.deviceId != quint32(driverInfoStruct.deviceId)) {
1353 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: deviceId does not match (%u, %u)",
1354 quint32(driverInfoStruct.deviceId), header.deviceId);
1355 return;
1356 }
1357 const quint64 luid = (quint64(quint32(adapterLuid.HighPart)) << 32) | quint64(adapterLuid.LowPart);
1358 if (header.adapterLuid != luid) {
1359 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: adapter LUID does not match");
1360 return;
1361 }
1362 if (quint64(data.size()) < quint64(headerSize) + header.dataSize) {
1363 qCDebug(QRHI_LOG_INFO, "setPipelineCacheData: Invalid blob, data missing");
1364 return;
1365 }
1366
1367 // The driver version is not in the header: CreatePipelineLibrary() checks
1368 // the blob against the current driver and adapter itself and fails with
1369 // D3D12_ERROR_DRIVER_VERSION_MISMATCH or _ADAPTER_NOT_FOUND when stale.
1370 if (createPipelineLibrary(data.mid(qsizetype(headerSize)))) {
1371 qCDebug(QRHI_LOG_INFO, "Created pipeline library with initial data of %u bytes",
1372 header.dataSize);
1373 }
1374#else
1375 Q_UNUSED(data);
1376#endif
1377}
1378
1379bool QRhiD3D12::isDeviceLost() const
1380{
1381 return deviceLost;
1382}
1383
1384QRhiRenderBuffer *QRhiD3D12::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize,
1385 int sampleCount, QRhiRenderBuffer::Flags flags,
1386 QRhiTexture::Format backingFormatHint)
1387{
1388 return new QD3D12RenderBuffer(this, type, pixelSize, sampleCount, flags, backingFormatHint);
1389}
1390
1391QRhiTexture *QRhiD3D12::createTexture(QRhiTexture::Format format,
1392 const QSize &pixelSize, int depth, int arraySize,
1393 int sampleCount, QRhiTexture::Flags flags)
1394{
1395 return new QD3D12Texture(this, format, pixelSize, depth, arraySize, sampleCount, flags);
1396}
1397
1398QRhiSampler *QRhiD3D12::createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter,
1399 QRhiSampler::Filter mipmapMode,
1400 QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
1401{
1402 return new QD3D12Sampler(this, magFilter, minFilter, mipmapMode, u, v, w);
1403}
1404
1405QRhiTextureRenderTarget *QRhiD3D12::createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc,
1406 QRhiTextureRenderTarget::Flags flags)
1407{
1408 return new QD3D12TextureRenderTarget(this, desc, flags);
1409}
1410
1411QRhiShadingRateMap *QRhiD3D12::createShadingRateMap()
1412{
1413 return new QD3D12ShadingRateMap(this);
1414}
1415
1416QRhiGraphicsPipeline *QRhiD3D12::createGraphicsPipeline()
1417{
1418 return new QD3D12GraphicsPipeline(this);
1419}
1420
1421QRhiComputePipeline *QRhiD3D12::createComputePipeline()
1422{
1423 return new QD3D12ComputePipeline(this);
1424}
1425
1426QRhiShaderResourceBindings *QRhiD3D12::createShaderResourceBindings()
1427{
1428 return new QD3D12ShaderResourceBindings(this);
1429}
1430
1431void QRhiD3D12::setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps)
1432{
1433 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
1434 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
1435 QD3D12GraphicsPipeline *psD = QRHI_RES(QD3D12GraphicsPipeline, ps);
1436 const bool pipelineChanged = cbD->currentGraphicsPipeline != psD || cbD->currentPipelineGeneration != psD->generation;
1437
1438 if (pipelineChanged) {
1439 cbD->currentGraphicsPipeline = psD;
1440 cbD->currentComputePipeline = nullptr;
1441 cbD->currentPipelineGeneration = psD->generation;
1442
1443 if (QD3D12Pipeline *pipeline = pipelinePool.lookupRef(psD->handle)) {
1444 Q_ASSERT(pipeline->type == QD3D12Pipeline::Graphics);
1445 cbD->cmdList->SetPipelineState(pipeline->pso);
1446 if (QD3D12RootSignature *rs = rootSignaturePool.lookupRef(psD->rootSigHandle))
1447 cbD->cmdList->SetGraphicsRootSignature(rs->rootSig);
1448 }
1449
1450 cbD->cmdList->IASetPrimitiveTopology(psD->topology);
1451
1452 if (psD->viewInstanceMask)
1453 cbD->cmdList->SetViewInstanceMask(psD->viewInstanceMask);
1454
1455 if (cbD->hasCustomScissorSet && !psD->m_flags.testFlag(QRhiGraphicsPipeline::UsesScissor))
1456 setDefaultScissor(cbD);
1457
1458 if (psD->m_stencilTest) {
1459 const quint32 ref = psD->m_flags.testFlag(QRhiGraphicsPipeline::UsesStencilRef)
1460 ? cbD->currentStencilRef : 0;
1461 if (cbD->appliedStencilRef != ref) {
1462 cbD->cmdList->OMSetStencilRef(ref);
1463 cbD->appliedStencilRef = ref;
1464 }
1465 }
1466 }
1467}
1468
1469void QD3D12ShaderResourceBindings::cacheUniformBuffer(QD3D12Stage s,
1470 const QRhiShaderResourceBinding::Data::UniformBufferData &d,
1471 int,
1472 int binding)
1473{
1474 // Which of the buffer's per-frame-slot resources to use, and what dynamic
1475 // offset to add, is only known when binding. Keep the QRhiBuffer so that
1476 // the cache stays valid regardless of the frame slot and the offsets.
1477 bindingCache.cbufs[s].append({ QRHI_RES(QD3D12Buffer, d.buf), d.offset, binding });
1478}
1479
1480void QD3D12ShaderResourceBindings::cacheTextures(QD3D12Stage s,
1481 const QRhiShaderResourceBinding::TextureAndSampler *d,
1482 int count,
1483 int)
1484{
1485 for (int i = 0; i < count; ++i) {
1486 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, d[i].tex);
1487 bindingCache.srvs[s].append(texD->srv.cpuHandle);
1488 }
1489}
1490
1491void QD3D12ShaderResourceBindings::cacheSamplers(QD3D12Stage s,
1492 const QRhiShaderResourceBinding::TextureAndSampler *d,
1493 int count,
1494 int)
1495{
1496 if (count == 1) {
1497 QD3D12Sampler *samplerD = QRHI_RES(QD3D12Sampler, d[0].sampler);
1498 bindingCache.samplers[s].append(samplerD->lookupOrCreateShaderVisibleDescriptor().gpuHandle);
1499 return;
1500 }
1501
1502 // An array of samplers must be backed by consecutive descriptors. The
1503 // per-sampler descriptors are scattered in the shader-visible sampler
1504 // heap, so get a dedicated run for this combination of samplers instead.
1505 // (deduplicated by sampler description, so this is not per srb)
1506 QRHI_RES_RHI(QRhiD3D12);
1507 QVarLengthArray<Q_D3D12_SAMPLER_DESC, 8> descs;
1508 for (int i = 0; i < count; ++i)
1509 descs.append({ QRHI_RES(QD3D12Sampler, d[i].sampler)->desc });
1510 bindingCache.samplers[s].append(rhiD->samplerMgr.getShaderVisibleDescriptors(descs).gpuHandle);
1511}
1512
1513void QD3D12ShaderResourceBindings::cacheStorageBuffer(QD3D12Stage s,
1514 const QRhiShaderResourceBinding::Data::StorageBufferData &d,
1515 QD3D12ShaderResourceVisitor::StorageOp,
1516 int)
1517{
1518 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, d.buf);
1519 // SPIRV-Cross generated HLSL uses RWByteAddressBuffer
1520 D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
1521 uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
1522 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
1523 uavDesc.Buffer.FirstElement = d.offset / 4;
1524 uavDesc.Buffer.NumElements = aligned(bufD->m_size - d.offset, 4u) / 4;
1525 uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
1526 bindingCache.uavs[s].append({ bufD->handles[0], uavDesc });
1527}
1528
1529void QD3D12ShaderResourceBindings::cacheStorageImage(QD3D12Stage s,
1530 const QRhiShaderResourceBinding::Data::StorageImageData &d,
1531 QD3D12ShaderResourceVisitor::StorageOp,
1532 int)
1533{
1534 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, d.tex);
1535 const bool isCube = texD->m_flags.testFlag(QRhiTexture::CubeMap);
1536 const bool isArray = texD->m_flags.testFlag(QRhiTexture::TextureArray);
1537 const bool is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
1538 const bool is1D = texD->m_flags.testFlag(QRhiTexture::OneDimensional);
1539 D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
1540 uavDesc.Format = texD->rtFormat;
1541 if (isCube) {
1542 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
1543 uavDesc.Texture2DArray.MipSlice = UINT(d.level);
1544 uavDesc.Texture2DArray.FirstArraySlice = 0;
1545 uavDesc.Texture2DArray.ArraySize = 6;
1546 } else if (isArray && is1D) {
1547 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY;
1548 uavDesc.Texture1DArray.MipSlice = UINT(d.level);
1549 uavDesc.Texture1DArray.FirstArraySlice = 0;
1550 uavDesc.Texture1DArray.ArraySize = UINT(qMax(0, texD->m_arraySize));
1551 } else if (is1D) {
1552 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D;
1553 uavDesc.Texture1D.MipSlice = UINT(d.level);
1554 } else if (isArray) {
1555 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
1556 uavDesc.Texture2DArray.MipSlice = UINT(d.level);
1557 uavDesc.Texture2DArray.FirstArraySlice = 0;
1558 uavDesc.Texture2DArray.ArraySize = UINT(qMax(0, texD->m_arraySize));
1559 } else if (is3D) {
1560 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
1561 uavDesc.Texture3D.MipSlice = UINT(d.level);
1562 uavDesc.Texture3D.WSize = UINT(-1);
1563 } else {
1564 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
1565 uavDesc.Texture2D.MipSlice = UINT(d.level);
1566 }
1567 bindingCache.uavs[s].append({ texD->handle, uavDesc });
1568}
1569
1570void QD3D12ShaderResourceBindings::rebuildBindingCache(const QD3D12ShaderStageData *stageData,
1571 int stageCount)
1572{
1573 bindingCache.reset();
1574
1575 QD3D12ShaderResourceVisitor visitor(this, stageData, stageCount);
1576
1577 using namespace std::placeholders;
1578 visitor.uniformBuffer = std::bind(&QD3D12ShaderResourceBindings::cacheUniformBuffer, this, _1, _2, _3, _4);
1579 visitor.textures = std::bind(&QD3D12ShaderResourceBindings::cacheTextures, this, _1, _2, _3, _4);
1580 visitor.samplers = std::bind(&QD3D12ShaderResourceBindings::cacheSamplers, this, _1, _2, _3, _4);
1581 visitor.storageBuffer = std::bind(&QD3D12ShaderResourceBindings::cacheStorageBuffer, this, _1, _2, _3, _4);
1582 visitor.storageImage = std::bind(&QD3D12ShaderResourceBindings::cacheStorageImage, this, _1, _2, _3, _4);
1583
1584 visitor.visit();
1585
1586 // CBs use root constant buffer views, no need to count them here.
1587 for (int s = 0; s < 6; ++s) {
1588 bindingCache.srvUavCount += bindingCache.srvs[s].count();
1589 bindingCache.srvUavCount += bindingCache.uavs[s].count();
1590 }
1591
1592 bindingCacheValid = true;
1593 bindingCacheGeneration = generation;
1594}
1595
1596void QRhiD3D12::setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBindings *srb,
1597 int dynamicOffsetCount,
1598 const QRhiCommandBuffer::DynamicOffset *dynamicOffsets)
1599{
1600 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
1601 Q_ASSERT(cbD->recordingPass != QD3D12CommandBuffer::NoPass);
1602 QD3D12GraphicsPipeline *gfxPsD = QRHI_RES(QD3D12GraphicsPipeline, cbD->currentGraphicsPipeline);
1603 QD3D12ComputePipeline *compPsD = QRHI_RES(QD3D12ComputePipeline, cbD->currentComputePipeline);
1604
1605 if (!srb) {
1606 if (gfxPsD)
1607 srb = gfxPsD->m_shaderResourceBindings;
1608 else
1609 srb = compPsD->m_shaderResourceBindings;
1610 }
1611
1612 QD3D12ShaderResourceBindings *srbD = QRHI_RES(QD3D12ShaderResourceBindings, srb);
1613
1614 bool pipelineChanged = false;
1615 if (gfxPsD) {
1616 pipelineChanged = srbD->lastUsedGraphicsPipeline != gfxPsD
1617 || srbD->lastUsedPipelineGeneration != gfxPsD->generation;
1618 srbD->lastUsedGraphicsPipeline = gfxPsD;
1619 srbD->lastUsedComputePipeline = nullptr;
1620 srbD->lastUsedPipelineGeneration = gfxPsD->generation;
1621 } else {
1622 pipelineChanged = srbD->lastUsedComputePipeline != compPsD
1623 || srbD->lastUsedPipelineGeneration != compPsD->generation;
1624 srbD->lastUsedGraphicsPipeline = nullptr;
1625 srbD->lastUsedComputePipeline = compPsD;
1626 srbD->lastUsedPipelineGeneration = compPsD->generation;
1627 }
1628
1629 bool srbUpdate = false;
1630
1631 for (int i = 0, ie = srbD->m_bindings.size(); i != ie; ++i) {
1632 const QRhiShaderResourceBinding::Data *b = shaderResourceBindingData(srbD->m_bindings[i]);
1633 QD3D12ShaderResourceBindings::BoundResourceData &bd(srbD->boundResourceData[i]);
1634 switch (b->type()) {
1635 case QRhiShaderResourceBinding::UniformBuffer:
1636 {
1637 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, b->ubuf().buf);
1638 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer));
1639 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
1640 sanityCheckResourceOwnership(bufD);
1641 bufD->executeHostWritesForFrameSlot(currentFrameSlot);
1642 if (bufD->generation != bd.ubuf.generation || bufD->m_id != bd.ubuf.id) {
1643 srbUpdate = true;
1644 bd.ubuf.id = bufD->m_id;
1645 bd.ubuf.generation = bufD->generation;
1646 }
1647 }
1648 break;
1649 case QRhiShaderResourceBinding::SampledTexture:
1650 case QRhiShaderResourceBinding::Texture:
1651 case QRhiShaderResourceBinding::Sampler:
1652 {
1653 const QRhiShaderResourceBinding::Data::TextureAndOrSamplerData *data = &b->stex();
1654 if (bd.stex.d.size() != data->count()) {
1655 bd.stex.d.resize(data->count());
1656 srbUpdate = true;
1657 }
1658 for (int elem = 0; elem < data->count(); ++elem) {
1659 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, data->texSamplers[elem].tex);
1660 QD3D12Sampler *samplerD = QRHI_RES(QD3D12Sampler, data->texSamplers[elem].sampler);
1661 // We use the same code path for both combined and separate
1662 // images and samplers, so tex or sampler (but not both) can be
1663 // null here.
1664 Q_ASSERT(texD || samplerD);
1665 sanityCheckResourceOwnership(texD);
1666 sanityCheckResourceOwnership(samplerD);
1667 const quint64 texId = texD ? texD->m_id : 0;
1668 const uint texGen = texD ? texD->generation : 0;
1669 const quint64 samplerId = samplerD ? samplerD->m_id : 0;
1670 const uint samplerGen = samplerD ? samplerD->generation : 0;
1671 if (texId != bd.stex.d[elem].texId || texGen != bd.stex.d[elem].texGeneration
1672 || samplerId != bd.stex.d[elem].samplerId
1673 || samplerGen != bd.stex.d[elem].samplerGeneration)
1674 {
1675 srbUpdate = true;
1676 bd.stex.d[elem].texId = texId;
1677 bd.stex.d[elem].texGeneration = texGen;
1678 bd.stex.d[elem].samplerId = samplerId;
1679 bd.stex.d[elem].samplerGeneration = samplerGen;
1680 }
1681 if (texD) {
1682 UINT state = 0;
1683 if (b->stage == QRhiShaderResourceBinding::FragmentStage) {
1684 state = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
1685 } else if (b->stage.testFlag(QRhiShaderResourceBinding::FragmentStage)) {
1686 state = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1687 } else {
1688 state = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
1689 }
1690 barrierGen.addTransitionBarrier(texD->handle, D3D12_RESOURCE_STATES(state));
1691 }
1692 }
1693 }
1694 break;
1695 case QRhiShaderResourceBinding::ImageLoad:
1696 case QRhiShaderResourceBinding::ImageStore:
1697 case QRhiShaderResourceBinding::ImageLoadStore:
1698 {
1699 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, b->simage().tex);
1700 sanityCheckResourceOwnership(texD);
1701 if (texD->generation != bd.simage.generation || texD->m_id != bd.simage.id) {
1702 srbUpdate = true;
1703 bd.simage.id = texD->m_id;
1704 bd.simage.generation = texD->generation;
1705 }
1706 if (QD3D12Resource *res = resourcePool.lookupRef(texD->handle)) {
1707 if (res->uavUsage) {
1708 if (res->uavUsage & QD3D12Resource::UavUsageWrite) {
1709 // RaW or WaW
1710 barrierGen.enqueueUavBarrier(cbD, texD->handle);
1711 } else {
1712 if (b->type() == QRhiShaderResourceBinding::ImageStore
1713 || b->type() == QRhiShaderResourceBinding::ImageLoadStore)
1714 {
1715 // WaR or WaW
1716 barrierGen.enqueueUavBarrier(cbD, texD->handle);
1717 }
1718 }
1719 }
1720 res->uavUsage = 0;
1721 if (b->type() == QRhiShaderResourceBinding::ImageLoad || b->type() == QRhiShaderResourceBinding::ImageLoadStore)
1722 res->uavUsage |= QD3D12Resource::UavUsageRead;
1723 if (b->type() == QRhiShaderResourceBinding::ImageStore || b->type() == QRhiShaderResourceBinding::ImageLoadStore)
1724 res->uavUsage |= QD3D12Resource::UavUsageWrite;
1725 barrierGen.addTransitionBarrier(texD->handle, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
1726 }
1727 }
1728 break;
1729 case QRhiShaderResourceBinding::BufferLoad:
1730 case QRhiShaderResourceBinding::BufferStore:
1731 case QRhiShaderResourceBinding::BufferLoadStore:
1732 {
1733 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, b->sbuf().buf);
1734 sanityCheckResourceOwnership(bufD);
1735 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::StorageBuffer));
1736 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
1737 if (bufD->generation != bd.sbuf.generation || bufD->m_id != bd.sbuf.id) {
1738 srbUpdate = true;
1739 bd.sbuf.id = bufD->m_id;
1740 bd.sbuf.generation = bufD->generation;
1741 }
1742 if (QD3D12Resource *res = resourcePool.lookupRef(bufD->handles[0])) {
1743 if (res->uavUsage) {
1744 if (res->uavUsage & QD3D12Resource::UavUsageWrite) {
1745 // RaW or WaW
1746 barrierGen.enqueueUavBarrier(cbD, bufD->handles[0]);
1747 } else {
1748 if (b->type() == QRhiShaderResourceBinding::BufferStore
1749 || b->type() == QRhiShaderResourceBinding::BufferLoadStore)
1750 {
1751 // WaR or WaW
1752 barrierGen.enqueueUavBarrier(cbD, bufD->handles[0]);
1753 }
1754 }
1755 }
1756 res->uavUsage = 0;
1757 if (b->type() == QRhiShaderResourceBinding::BufferLoad || b->type() == QRhiShaderResourceBinding::BufferLoadStore)
1758 res->uavUsage |= QD3D12Resource::UavUsageRead;
1759 if (b->type() == QRhiShaderResourceBinding::BufferStore || b->type() == QRhiShaderResourceBinding::BufferLoadStore)
1760 res->uavUsage |= QD3D12Resource::UavUsageWrite;
1761 barrierGen.addTransitionBarrier(bufD->handles[0], D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
1762 }
1763 }
1764 break;
1765 }
1766 }
1767
1768 const bool srbChanged = gfxPsD ? (cbD->currentGraphicsSrb != srb) : (cbD->currentComputeSrb != srb);
1769 const bool srbRebuilt = cbD->currentSrbGeneration != srbD->generation;
1770
1771 // One ResourceBarrier() for all the transitions, instead of one per
1772 // binding. While the enqueueUavBarrier() calls in the loop above may make
1773 // deferring this to here seem incorrect, that is not a problem: no draw or
1774 // dispatch is recorded in-between, so the whole set takes effect before the
1775 // next one either way, and for a given resource the relative order is still
1776 // preserved.
1777 barrierGen.enqueueBufferedTransitionBarriers(cbD);
1778
1779 // Rebuilding the cache is the expensive part (it runs the visitor over all
1780 // bindings for all stages), so only do it when something it depends on
1781 // actually changed. Note that srbChanged is deliberately not part of this:
1782 // binding a different srb does not invalidate this srb's cache.
1783 if (pipelineChanged || srbUpdate || !srbD->bindingCacheValid
1784 || srbD->bindingCacheGeneration != srbD->generation)
1785 {
1786 const QD3D12ShaderStageData *stageData = gfxPsD ? gfxPsD->stageData.data() : &compPsD->stageData;
1787 srbD->rebuildBindingCache(stageData, gfxPsD ? 5 : 1);
1788 }
1789
1790 if (pipelineChanged || srbChanged || srbRebuilt || srbUpdate || srbD->hasDynamicOffset) {
1791 // The order of root parameters must match
1792 // QD3D12ShaderResourceBindings::createRootSignature(), meaning the
1793 // logic below must mirror that function (uniform buffers first etc.)
1794
1795 const QD3D12ShaderResourceBindings::BindingCache &cache(srbD->bindingCache);
1796
1797 bool gotNewHeap = false;
1798 if (!ensureShaderVisibleDescriptorHeapCapacity(&shaderVisibleCbvSrvUavHeap,
1799 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
1800 currentFrameSlot,
1801 cache.srvUavCount,
1802 &gotNewHeap))
1803 {
1804 return;
1805 }
1806 if (gotNewHeap) {
1807 qCDebug(QRHI_LOG_INFO, "Created new shader-visible CBV/SRV/UAV descriptor heap,"
1808 " per-frame slice size is now %u,"
1809 " if this happens frequently then that's not great.",
1810 shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[0].capacity);
1811 bindShaderVisibleHeaps(cbD);
1812 }
1813
1814 int rootParamIndex = 0;
1815 for (int s = 0; s < 6; ++s) {
1816 for (const QD3D12ShaderResourceBindings::BindingCache::CBuf &cbuf : cache.cbufs[s]) {
1817 if (QD3D12Resource *res = resourcePool.lookupRef(cbuf.buf->handles[currentFrameSlot])) {
1818 quint32 offset = cbuf.offset;
1819 if (srbD->hasDynamicOffset) {
1820 for (int i = 0; i < dynamicOffsetCount; ++i) {
1821 const QRhiCommandBuffer::DynamicOffset &dynOfs(dynamicOffsets[i]);
1822 if (dynOfs.first == cbuf.binding) {
1823 Q_ASSERT(aligned(dynOfs.second, 256u) == dynOfs.second);
1824 offset += dynOfs.second;
1825 }
1826 }
1827 }
1828 const D3D12_GPU_VIRTUAL_ADDRESS gpuAddr = res->resource->GetGPUVirtualAddress() + offset;
1829 if (gfxPsD)
1830 cbD->cmdList->SetGraphicsRootConstantBufferView(rootParamIndex, gpuAddr);
1831 else
1832 cbD->cmdList->SetComputeRootConstantBufferView(rootParamIndex, gpuAddr);
1833 }
1834 rootParamIndex += 1;
1835 }
1836 }
1837 for (int s = 0; s < 6; ++s) {
1838 if (!cache.srvs[s].isEmpty()) {
1839 QD3D12DescriptorHeap &gpuSrvHeap(shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[currentFrameSlot]);
1840 const UINT count = UINT(cache.srvs[s].count());
1841 const QD3D12Descriptor startDesc = gpuSrvHeap.get(count);
1842 // One destination range of count descriptors, count source
1843 // ranges of one descriptor each (nullptr sizes means all 1).
1844 dev->CopyDescriptors(1, &startDesc.cpuHandle, &count,
1845 count, cache.srvs[s].constData(), nullptr,
1846 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
1847
1848 if (gfxPsD)
1849 cbD->cmdList->SetGraphicsRootDescriptorTable(rootParamIndex, startDesc.gpuHandle);
1850 else
1851 cbD->cmdList->SetComputeRootDescriptorTable(rootParamIndex, startDesc.gpuHandle);
1852
1853 rootParamIndex += 1;
1854 }
1855 }
1856 for (int s = 0; s < 6; ++s) {
1857 // Samplers are one parameter / descriptor table each, and the
1858 // descriptor is from the shader visible sampler heap already.
1859 for (D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor : cache.samplers[s]) {
1860 if (gfxPsD)
1861 cbD->cmdList->SetGraphicsRootDescriptorTable(rootParamIndex, samplerDescriptor);
1862 else
1863 cbD->cmdList->SetComputeRootDescriptorTable(rootParamIndex, samplerDescriptor);
1864
1865 rootParamIndex += 1;
1866 }
1867 }
1868 for (int s = 0; s < 6; ++s) {
1869 if (!cache.uavs[s].isEmpty()) {
1870 QD3D12DescriptorHeap &gpuUavHeap(shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[currentFrameSlot]);
1871 const int count = cache.uavs[s].count();
1872 const QD3D12Descriptor startDesc = gpuUavHeap.get(count);
1873 for (int i = 0; i < count; ++i) {
1874 const QD3D12ShaderResourceBindings::BindingCache::Uav &uav(cache.uavs[s][i]);
1875 if (QD3D12Resource *res = resourcePool.lookupRef(uav.handle)) {
1876 dev->CreateUnorderedAccessView(res->resource, nullptr, &uav.desc,
1877 gpuUavHeap.incremented(startDesc, i).cpuHandle);
1878 } else {
1879 dev->CreateUnorderedAccessView(nullptr, nullptr, nullptr,
1880 gpuUavHeap.incremented(startDesc, i).cpuHandle);
1881 }
1882 }
1883
1884 if (gfxPsD)
1885 cbD->cmdList->SetGraphicsRootDescriptorTable(rootParamIndex, startDesc.gpuHandle);
1886 else
1887 cbD->cmdList->SetComputeRootDescriptorTable(rootParamIndex, startDesc.gpuHandle);
1888
1889 rootParamIndex += 1;
1890 }
1891 }
1892
1893 if (gfxPsD) {
1894 cbD->currentGraphicsSrb = srb;
1895 cbD->currentComputeSrb = nullptr;
1896 } else {
1897 cbD->currentGraphicsSrb = nullptr;
1898 cbD->currentComputeSrb = srb;
1899 }
1900 cbD->currentSrbGeneration = srbD->generation;
1901 }
1902}
1903
1904void QRhiD3D12::setVertexInput(QRhiCommandBuffer *cb,
1905 int startBinding, int bindingCount, const QRhiCommandBuffer::VertexInput *bindings,
1906 QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
1907{
1908 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
1909 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
1910
1911 const QRhiVertexInputLayout *inputLayout = cbD->currentGraphicsPipeline
1912 ? &cbD->currentGraphicsPipeline->m_vertexInputLayout : nullptr;
1913 const int inputBindingCount = inputLayout
1914 ? inputLayout->cendBindings() - inputLayout->cbeginBindings() : 0;
1915 const int vertexBindingCount = qMin(bindingCount, inputBindingCount - startBinding);
1916
1917 // The vertex buffer view includes the pipeline's stride. Switching
1918 // pipelines can change the view even when the buffer and offset match.
1919 bool needsBindVBuf = false;
1920 for (int i = 0; i < vertexBindingCount; ++i) {
1921 const int inputSlot = startBinding + i;
1922 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, bindings[i].first);
1923 Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::VertexBuffer));
1924 const bool isDynamic = bufD->m_type == QRhiBuffer::Dynamic;
1925 if (isDynamic)
1926 bufD->executeHostWritesForFrameSlot(currentFrameSlot);
1927
1928 const QD3D12ObjectHandle handle = bufD->handles[isDynamic ? currentFrameSlot : 0];
1929 const quint32 offset = bindings[i].second;
1930 const quint32 stride = inputLayout->bindingAt(inputSlot)->stride();
1931 if (cbD->currentVertexBuffers[inputSlot] != handle
1932 || cbD->currentVertexOffsets[inputSlot] != offset
1933 || cbD->currentVertexStrides[inputSlot] != stride)
1934 {
1935 needsBindVBuf = true;
1936 cbD->currentVertexBuffers[inputSlot] = handle;
1937 cbD->currentVertexOffsets[inputSlot] = offset;
1938 cbD->currentVertexStrides[inputSlot] = stride;
1939 }
1940 }
1941
1942 if (needsBindVBuf) {
1943 QVarLengthArray<D3D12_VERTEX_BUFFER_VIEW, 4> vbv;
1944 vbv.reserve(vertexBindingCount);
1945
1946 for (int i = 0; i < vertexBindingCount; ++i) {
1947 const int inputSlot = startBinding + i;
1948 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, bindings[i].first);
1949 const QD3D12ObjectHandle handle = cbD->currentVertexBuffers[inputSlot];
1950 const quint32 offset = cbD->currentVertexOffsets[inputSlot];
1951 const quint32 stride = cbD->currentVertexStrides[inputSlot];
1952
1953 if (bufD->m_type != QRhiBuffer::Dynamic) {
1954 barrierGen.addTransitionBarrier(handle, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
1955 barrierGen.enqueueBufferedTransitionBarriers(cbD);
1956 }
1957
1958 if (QD3D12Resource *res = resourcePool.lookupRef(handle)) {
1959 vbv.append({
1960 res->resource->GetGPUVirtualAddress() + offset,
1961 UINT(res->desc.Width - offset),
1962 stride
1963 });
1964 }
1965 }
1966
1967 cbD->cmdList->IASetVertexBuffers(UINT(startBinding), vbv.count(), vbv.constData());
1968 }
1969
1970 if (indexBuf) {
1971 QD3D12Buffer *ibufD = QRHI_RES(QD3D12Buffer, indexBuf);
1972 Q_ASSERT(ibufD->m_usage.testFlag(QRhiBuffer::IndexBuffer));
1973 const bool isDynamic = ibufD->m_type == QRhiBuffer::Dynamic;
1974 if (isDynamic)
1975 ibufD->executeHostWritesForFrameSlot(currentFrameSlot);
1976
1977 const DXGI_FORMAT dxgiFormat = indexFormat == QRhiCommandBuffer::IndexUInt16 ? DXGI_FORMAT_R16_UINT
1978 : DXGI_FORMAT_R32_UINT;
1979 if (cbD->currentIndexBuffer != ibufD->handles[isDynamic ? currentFrameSlot : 0]
1980 || cbD->currentIndexOffset != indexOffset
1981 || cbD->currentIndexFormat != dxgiFormat)
1982 {
1983 cbD->currentIndexBuffer = ibufD->handles[isDynamic ? currentFrameSlot : 0];
1984 cbD->currentIndexOffset = indexOffset;
1985 cbD->currentIndexFormat = dxgiFormat;
1986
1987 if (ibufD->m_type != QRhiBuffer::Dynamic) {
1988 barrierGen.addTransitionBarrier(cbD->currentIndexBuffer, D3D12_RESOURCE_STATE_INDEX_BUFFER);
1989 barrierGen.enqueueBufferedTransitionBarriers(cbD);
1990 }
1991
1992 if (QD3D12Resource *res = resourcePool.lookupRef(cbD->currentIndexBuffer)) {
1993 const D3D12_INDEX_BUFFER_VIEW ibv = {
1994 res->resource->GetGPUVirtualAddress() + indexOffset,
1995 UINT(res->desc.Width - indexOffset),
1996 dxgiFormat
1997 };
1998 cbD->cmdList->IASetIndexBuffer(&ibv);
1999 }
2000 }
2001 }
2002}
2003
2004void QRhiD3D12::setDefaultScissor(QD3D12CommandBuffer *cbD)
2005{
2006 cbD->hasCustomScissorSet = false;
2007
2008 const QSize outputSize = cbD->currentTarget->pixelSize();
2009 std::array<float, 4> vp = cbD->currentViewport.viewport();
2010 float x = 0, y = 0, w = 0, h = 0;
2011
2012 if (qFuzzyIsNull(vp[2]) && qFuzzyIsNull(vp[3])) {
2013 x = 0;
2014 y = 0;
2015 w = outputSize.width();
2016 h = outputSize.height();
2017 } else {
2018 // x,y is top-left in D3D12_RECT but bottom-left in QRhiScissor
2019 qrhi_toTopLeftRenderTargetRect<Bounded>(outputSize, vp, &x, &y, &w, &h);
2020 }
2021
2022 D3D12_RECT r;
2023 r.left = x;
2024 r.top = y;
2025 // right and bottom are exclusive
2026 r.right = x + w;
2027 r.bottom = y + h;
2028 cbD->cmdList->RSSetScissorRects(1, &r);
2029}
2030
2031void QRhiD3D12::setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport)
2032{
2033 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2034 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2035 Q_ASSERT(cbD->currentTarget);
2036 const QSize outputSize = cbD->currentTarget->pixelSize();
2037
2038 // D3D expects top-left, QRhiViewport is bottom-left
2039 float x, y, w, h;
2040 if (!qrhi_toTopLeftRenderTargetRect<UnBounded>(outputSize, viewport.viewport(), &x, &y, &w, &h))
2041 return;
2042
2043 D3D12_VIEWPORT v;
2044 v.TopLeftX = x;
2045 v.TopLeftY = y;
2046 v.Width = w;
2047 v.Height = h;
2048 v.MinDepth = viewport.minDepth();
2049 v.MaxDepth = viewport.maxDepth();
2050 cbD->cmdList->RSSetViewports(1, &v);
2051
2052 cbD->currentViewport = viewport;
2053 if (cbD->currentGraphicsPipeline
2054 && !cbD->currentGraphicsPipeline->flags().testFlag(QRhiGraphicsPipeline::UsesScissor))
2055 {
2056 setDefaultScissor(cbD);
2057 }
2058}
2059
2060void QRhiD3D12::setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor)
2061{
2062 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2063 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2064 Q_ASSERT(cbD->currentTarget);
2065 const QSize outputSize = cbD->currentTarget->pixelSize();
2066
2067 // D3D expects top-left, QRhiScissor is bottom-left
2068 int x, y, w, h;
2069 if (!qrhi_toTopLeftRenderTargetRect<Bounded>(outputSize, scissor.scissor(), &x, &y, &w, &h))
2070 return;
2071
2072 D3D12_RECT r;
2073 r.left = x;
2074 r.top = y;
2075 // right and bottom are exclusive
2076 r.right = x + w;
2077 r.bottom = y + h;
2078 cbD->cmdList->RSSetScissorRects(1, &r);
2079
2080 cbD->hasCustomScissorSet = true;
2081}
2082
2083void QRhiD3D12::setBlendConstants(QRhiCommandBuffer *cb, const QColor &c)
2084{
2085 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2086 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2087 float v[4] = { c.redF(), c.greenF(), c.blueF(), c.alphaF() };
2088 cbD->cmdList->OMSetBlendFactor(v);
2089}
2090
2091void QRhiD3D12::setStencilRef(QRhiCommandBuffer *cb, quint32 refValue)
2092{
2093 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2094 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2095 cbD->cmdList->OMSetStencilRef(refValue);
2096 cbD->currentStencilRef = refValue;
2097 cbD->appliedStencilRef = refValue;
2098}
2099
2100void QRhiD3D12::setPushConstants(QRhiCommandBuffer *cb, quint32 offset, quint32 size, const void *data)
2101{
2102 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2103 Q_ASSERT(cbD->recordingPass != QD3D12CommandBuffer::NoPass);
2104
2105 const bool compute = cbD->recordingPass == QD3D12CommandBuffer::ComputePass;
2106 const int index = compute ? (cbD->currentComputePipeline ? cbD->currentComputePipeline->pushConstantRootParamIndex : -1)
2107 : (cbD->currentGraphicsPipeline ? cbD->currentGraphicsPipeline->pushConstantRootParamIndex : -1);
2108 if (index < 0) {
2109 qWarning("No pipeline with a push constant block is active; setPushConstants ignored");
2110 return;
2111 }
2112
2113 if (compute)
2114 cbD->cmdList->SetComputeRoot32BitConstants(UINT(index), size / 4, data, offset / 4);
2115 else
2116 cbD->cmdList->SetGraphicsRoot32BitConstants(UINT(index), size / 4, data, offset / 4);
2117}
2118
2119static inline D3D12_SHADING_RATE toD3DShadingRate(const QSize &coarsePixelSize)
2120{
2121 if (coarsePixelSize == QSize(1, 2))
2122 return D3D12_SHADING_RATE_1X2;
2123 if (coarsePixelSize == QSize(2, 1))
2124 return D3D12_SHADING_RATE_2X1;
2125 if (coarsePixelSize == QSize(2, 2))
2126 return D3D12_SHADING_RATE_2X2;
2127 if (coarsePixelSize == QSize(2, 4))
2128 return D3D12_SHADING_RATE_2X4;
2129 if (coarsePixelSize == QSize(4, 2))
2130 return D3D12_SHADING_RATE_4X2;
2131 if (coarsePixelSize == QSize(4, 4))
2132 return D3D12_SHADING_RATE_4X4;
2133 return D3D12_SHADING_RATE_1X1;
2134}
2135
2136void QRhiD3D12::setShadingRate(QRhiCommandBuffer *cb, const QSize &coarsePixelSize)
2137{
2138 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2139 cbD->hasShadingRateSet = false;
2140
2141#ifdef QRHI_D3D12_CL5_AVAILABLE
2142 if (!caps.vrs)
2143 return;
2144
2145 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2146 const D3D12_SHADING_RATE_COMBINER combiners[] = { D3D12_SHADING_RATE_COMBINER_MAX, D3D12_SHADING_RATE_COMBINER_MAX };
2147 cbD->cmdList->RSSetShadingRate(toD3DShadingRate(coarsePixelSize), combiners);
2148 if (coarsePixelSize.width() != 1 || coarsePixelSize.height() != 1)
2149 cbD->hasShadingRateSet = true;
2150#else
2151 Q_UNUSED(cb);
2152 Q_UNUSED(coarsePixelSize);
2153 qWarning("Attempted to set ShadingRate without building Qt against a sufficiently new Windows SDK and d3d12.h. This cannot work.");
2154#endif
2155}
2156
2157void QRhiD3D12::draw(QRhiCommandBuffer *cb, quint32 vertexCount,
2158 quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
2159{
2160 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2161 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2162 cbD->cmdList->DrawInstanced(vertexCount, instanceCount, firstVertex, firstInstance);
2163}
2164
2165void QRhiD3D12::drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount,
2166 quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance)
2167{
2168 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2169 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2170 cbD->cmdList->DrawIndexedInstanced(indexCount, instanceCount,
2171 firstIndex, vertexOffset,
2172 firstInstance);
2173}
2174
2175void QRhiD3D12::drawIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
2176 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
2177{
2178 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2179 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2180
2181 QD3D12Buffer *indirectBufferD = QRHI_RES(QD3D12Buffer, indirectBuffer);
2182 const bool isDynamic = indirectBufferD->m_type == QRhiBuffer::Dynamic;
2183 const QD3D12ObjectHandle indirectBufferHandle = indirectBufferD->handles[isDynamic ? currentFrameSlot : 0];
2184 if (isDynamic) {
2185 indirectBufferD->executeHostWritesForFrameSlot(currentFrameSlot);
2186 } else {
2187 barrierGen.addTransitionBarrier(indirectBufferHandle, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
2188 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2189 }
2190 QD3D12Resource *indirectRes = resourcePool.lookupRef(indirectBufferHandle);
2191 if (!indirectRes)
2192 return;
2193 ID3D12Resource *indirectBufferRes = indirectRes->resource;
2194
2195 const bool canUseMulti = (stride == sizeof(QRhiIndirectDrawCommand) && drawCommandSignature);
2196
2197 if (canUseMulti && drawCount > 1) {
2198 cbD->cmdList->ExecuteIndirect(drawCommandSignature, drawCount,
2199 indirectBufferRes, indirectBufferOffset,
2200 nullptr, 0);
2201 } else {
2202 UINT offset = indirectBufferOffset;
2203 for (quint32 i = 0; i < drawCount; ++i) {
2204 cbD->cmdList->ExecuteIndirect(drawCommandSignature, 1,
2205 indirectBufferRes, offset,
2206 nullptr, 0);
2207 offset += stride;
2208 }
2209 }
2210}
2211
2212void QRhiD3D12::drawIndexedIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
2213 quint32 indirectBufferOffset, quint32 drawCount, quint32 stride)
2214{
2215 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2216 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2217
2218 QD3D12Buffer *indirectBufferD = QRHI_RES(QD3D12Buffer, indirectBuffer);
2219 const bool isDynamic = indirectBufferD->m_type == QRhiBuffer::Dynamic;
2220 const QD3D12ObjectHandle indirectBufferHandle = indirectBufferD->handles[isDynamic ? currentFrameSlot : 0];
2221 if (isDynamic) {
2222 indirectBufferD->executeHostWritesForFrameSlot(currentFrameSlot);
2223 } else {
2224 barrierGen.addTransitionBarrier(indirectBufferHandle, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
2225 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2226 }
2227 QD3D12Resource *indirectRes = resourcePool.lookupRef(indirectBufferHandle);
2228 if (!indirectRes)
2229 return;
2230 ID3D12Resource *indirectBufferRes = indirectRes->resource;
2231
2232 const bool canUseMulti = (stride == sizeof(QRhiIndexedIndirectDrawCommand) && drawIndexedCommandSignature);
2233
2234 if (canUseMulti && drawCount > 1) {
2235 cbD->cmdList->ExecuteIndirect(drawIndexedCommandSignature, drawCount,
2236 indirectBufferRes, indirectBufferOffset,
2237 nullptr, 0);
2238 } else {
2239 UINT offset = indirectBufferOffset;
2240 for (quint32 i = 0; i < drawCount; ++i) {
2241 cbD->cmdList->ExecuteIndirect(drawIndexedCommandSignature, 1,
2242 indirectBufferRes, offset,
2243 nullptr, 0);
2244 offset += stride;
2245 }
2246 }
2247}
2248
2249void QRhiD3D12::debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name)
2250{
2251 if (!debugMarkers)
2252 return;
2253
2254 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2255#ifdef QRHI_D3D12_HAS_OLD_PIX
2256 PIXBeginEvent(cbD->cmdList, PIX_COLOR_DEFAULT, reinterpret_cast<LPCWSTR>(QString::fromLatin1(name).utf16()));
2257#else
2258 Q_UNUSED(cbD);
2259 Q_UNUSED(name);
2260#endif
2261}
2262
2263void QRhiD3D12::debugMarkEnd(QRhiCommandBuffer *cb)
2264{
2265 if (!debugMarkers)
2266 return;
2267
2268 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2269#ifdef QRHI_D3D12_HAS_OLD_PIX
2270 PIXEndEvent(cbD->cmdList);
2271#else
2272 Q_UNUSED(cbD);
2273#endif
2274}
2275
2276void QRhiD3D12::debugMarkMsg(QRhiCommandBuffer *cb, const QByteArray &msg)
2277{
2278 if (!debugMarkers)
2279 return;
2280
2281 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2282#ifdef QRHI_D3D12_HAS_OLD_PIX
2283 PIXSetMarker(cbD->cmdList, PIX_COLOR_DEFAULT, reinterpret_cast<LPCWSTR>(QString::fromLatin1(msg).utf16()));
2284#else
2285 Q_UNUSED(cbD);
2286 Q_UNUSED(msg);
2287#endif
2288}
2289
2290const QRhiNativeHandles *QRhiD3D12::nativeHandles(QRhiCommandBuffer *cb)
2291{
2292 return QRHI_RES(QD3D12CommandBuffer, cb)->nativeHandles();
2293}
2294
2295void QRhiD3D12::beginExternal(QRhiCommandBuffer *cb)
2296{
2297 Q_UNUSED(cb);
2298}
2299
2300void QRhiD3D12::endExternal(QRhiCommandBuffer *cb)
2301{
2302 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2303 cbD->resetPerPassState();
2304 bindShaderVisibleHeaps(cbD);
2305 if (cbD->currentTarget) { // could be compute, no rendertarget then
2306 QD3D12RenderTargetData *rtD = rtData(cbD->currentTarget);
2307 cbD->cmdList->OMSetRenderTargets(UINT(rtD->colorAttCount),
2308 rtD->rtv,
2309 FALSE,
2310 rtD->dsAttCount ? &rtD->dsv : nullptr);
2311 }
2312}
2313
2314double QRhiD3D12::lastCompletedGpuTime(QRhiCommandBuffer *cb)
2315{
2316 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2317 return cbD->lastGpuTime;
2318}
2319
2320static void calculateGpuTime(QD3D12CommandBuffer *cbD,
2321 int timestampPairStartIndex,
2322 const quint8 *readbackBufPtr,
2323 quint64 timestampTicksPerSecond)
2324{
2325 const size_t byteOffset = timestampPairStartIndex * sizeof(quint64);
2326 const quint64 *p = reinterpret_cast<const quint64 *>(readbackBufPtr + byteOffset);
2327 const quint64 startTime = *p++;
2328 const quint64 endTime = *p;
2329 if (startTime < endTime) {
2330 const quint64 ticks = endTime - startTime;
2331 const double timeSec = ticks / double(timestampTicksPerSecond);
2332 cbD->lastGpuTime = timeSec;
2333 }
2334}
2335
2336QRhi::FrameOpResult QRhiD3D12::beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags)
2337{
2338 Q_UNUSED(flags);
2339
2340 // Report a device loss that was detected earlier (in createOrResize()'s
2341 // ResizeBuffers(), during swapchain creation, or by the previous frame's
2342 // Present()). Without this the caller has no way to find out - it would
2343 // carry on and render into resources that could not be recreated. The
2344 // Vulkan and OpenGL backends already report the loss from beginFrame().
2345 if (deviceLost)
2346 return QRhi::FrameOpDeviceLost;
2347
2348 QD3D12SwapChain *swapChainD = QRHI_RES(QD3D12SwapChain, swapChain);
2349 currentSwapChain = swapChainD;
2350 currentFrameSlot = swapChainD->currentFrameSlot;
2351 QD3D12SwapChain::FrameResources &fr(swapChainD->frameRes[currentFrameSlot]);
2352
2353 // We could do smarter things but mirror the Vulkan backend for now: Make
2354 // sure the previous commands for this same frame slot have finished. Do
2355 // this also for any other swapchain's commands with the same frame slot.
2356 // While this reduces concurrency in render-to-swapchain-A,
2357 // render-to-swapchain-B, repeat kind of scenarios, it keeps resource usage
2358 // safe: swapchain A starting its frame 0, followed by swapchain B starting
2359 // its own frame 0 will make B wait for A's frame 0 commands. If a resource
2360 // is written in B's frame or when B checks for pending resource releases,
2361 // that won't mess up A's in-flight commands (as they are guaranteed not to
2362 // be in flight anymore). With Qt Quick this situation cannot happen anyway
2363 // by design (one QRhi per window).
2364 for (QD3D12SwapChain *sc : std::as_const(swapchains))
2365 sc->waitCommandCompletionForFrameSlot(currentFrameSlot); // note: swapChainD->currentFrameSlot, not sc's
2366
2367 if (swapChainD->frameLatencyWaitableObject) {
2368 // only wait when endFrame() called Present(), otherwise this would become a 1 sec timeout
2369 if (swapChainD->lastFrameLatencyWaitSlot != currentFrameSlot) {
2370 WaitForSingleObjectEx(swapChainD->frameLatencyWaitableObject, 1000, true);
2371 swapChainD->lastFrameLatencyWaitSlot = currentFrameSlot;
2372 }
2373 }
2374
2375 HRESULT hr = cmdAllocators[currentFrameSlot]->Reset();
2376 if (FAILED(hr)) {
2377 qWarning("Failed to reset command allocator: %s",
2378 qPrintable(QSystemError::windowsComString(hr)));
2379 return QRhi::FrameOpError;
2380 }
2381
2382 if (!startCommandListForCurrentFrameSlot(&fr.cmdList))
2383 return QRhi::FrameOpError;
2384
2385 QD3D12CommandBuffer *cbD = &swapChainD->cbWrapper;
2386 cbD->cmdList = fr.cmdList;
2387
2388 swapChainD->rtWrapper.d.rtv[0] = swapChainD->sampleDesc.Count > 1
2389 ? swapChainD->msaaRtvs[currentFrameSlot].cpuHandle
2390 : swapChainD->rtvs[swapChainD->currentBackBufferIndex].cpuHandle;
2391
2392 swapChainD->rtWrapper.d.dsv = swapChainD->ds ? swapChainD->ds->dsv.cpuHandle
2393 : D3D12_CPU_DESCRIPTOR_HANDLE { 0 };
2394
2395 if (swapChainD->stereo) {
2396 swapChainD->rtWrapperRight.d.rtv[0] = swapChainD->sampleDesc.Count > 1
2397 ? swapChainD->msaaRtvs[currentFrameSlot].cpuHandle
2398 : swapChainD->rtvsRight[swapChainD->currentBackBufferIndex].cpuHandle;
2399
2400 swapChainD->rtWrapperRight.d.dsv =
2401 swapChainD->ds ? swapChainD->ds->dsv.cpuHandle : D3D12_CPU_DESCRIPTOR_HANDLE{ 0 };
2402 }
2403
2404
2405 // Time to release things that are marked for currentFrameSlot since due to
2406 // the wait above we know that the previous commands on the GPU for this
2407 // slot must have finished already.
2408 releaseQueue.executeDeferredReleases(currentFrameSlot);
2409
2410 // Full reset of the command buffer data.
2411 cbD->resetState();
2412
2413 // Move the head back to zero for the per-frame shader-visible descriptor heap work areas.
2414 shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[currentFrameSlot].head = 0;
2415 // Same for the small staging area, resizing it first if what this slot was
2416 // asked for the last time round says it should be bigger or smaller.
2417 resetAndResizeSmallStagingArea(currentFrameSlot);
2418
2419 bindShaderVisibleHeaps(cbD);
2420
2421 finishActiveReadbacks(); // last, in case the readback-completed callback issues rhi calls
2422
2423 if (timestampQueryHeap.isValid() && timestampTicksPerSecond) {
2424 // Read the timestamps for the previous frame for this slot. (the
2425 // ResolveQuery() should have completed by now due to the wait above)
2426 const int timestampPairStartIndex = currentFrameSlot * QD3D12_FRAMES_IN_FLIGHT;
2427 calculateGpuTime(cbD,
2428 timestampPairStartIndex,
2429 timestampReadbackArea.mem.p,
2430 timestampTicksPerSecond);
2431 // Write the start timestamp for this frame for this slot.
2432 cbD->cmdList->EndQuery(timestampQueryHeap.heap,
2433 D3D12_QUERY_TYPE_TIMESTAMP,
2434 timestampPairStartIndex);
2435 }
2436
2437 QDxgiVSyncService::instance()->beginFrame(adapterLuid);
2438
2439 return QRhi::FrameOpSuccess;
2440}
2441
2442QRhi::FrameOpResult QRhiD3D12::endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags)
2443{
2444 QD3D12SwapChain *swapChainD = QRHI_RES(QD3D12SwapChain, swapChain);
2445 Q_ASSERT(currentSwapChain == swapChainD);
2446 QD3D12CommandBuffer *cbD = &swapChainD->cbWrapper;
2447
2448 QD3D12ObjectHandle backBufferResourceHandle = swapChainD->colorBuffers[swapChainD->currentBackBufferIndex];
2449 if (swapChainD->sampleDesc.Count > 1) {
2450 QD3D12ObjectHandle msaaBackBufferResourceHandle = swapChainD->msaaBuffers[currentFrameSlot];
2451 barrierGen.addTransitionBarrier(msaaBackBufferResourceHandle, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
2452 barrierGen.addTransitionBarrier(backBufferResourceHandle, D3D12_RESOURCE_STATE_RESOLVE_DEST);
2453 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2454 const QD3D12Resource *src = resourcePool.lookupRef(msaaBackBufferResourceHandle);
2455 const QD3D12Resource *dst = resourcePool.lookupRef(backBufferResourceHandle);
2456 if (src && dst)
2457 cbD->cmdList->ResolveSubresource(dst->resource, 0, src->resource, 0, swapChainD->colorFormat);
2458 }
2459
2460 barrierGen.addTransitionBarrier(backBufferResourceHandle, D3D12_RESOURCE_STATE_PRESENT);
2461 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2462
2463 if (timestampQueryHeap.isValid()) {
2464 const int timestampPairStartIndex = currentFrameSlot * QD3D12_FRAMES_IN_FLIGHT;
2465 cbD->cmdList->EndQuery(timestampQueryHeap.heap,
2466 D3D12_QUERY_TYPE_TIMESTAMP,
2467 timestampPairStartIndex + 1);
2468 cbD->cmdList->ResolveQueryData(timestampQueryHeap.heap,
2469 D3D12_QUERY_TYPE_TIMESTAMP,
2470 timestampPairStartIndex,
2471 2,
2472 timestampReadbackArea.mem.buffer,
2473 timestampPairStartIndex * sizeof(quint64));
2474 }
2475
2476 D3D12GraphicsCommandList *cmdList = cbD->cmdList;
2477 HRESULT hr = cmdList->Close();
2478 if (FAILED(hr)) {
2479 qWarning("Failed to close command list: %s",
2480 qPrintable(QSystemError::windowsComString(hr)));
2481 return QRhi::FrameOpError;
2482 }
2483
2484 ID3D12CommandList *execList[] = { cmdList };
2485 cmdQueue->ExecuteCommandLists(1, execList);
2486
2487 if (!flags.testFlag(QRhi::SkipPresent)) {
2488 UINT presentFlags = 0;
2489 if (swapChainD->swapInterval == 0
2490 && (swapChainD->swapChainFlags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING))
2491 {
2492 presentFlags |= DXGI_PRESENT_ALLOW_TEARING;
2493 }
2494 if (!swapChainD->swapChain) {
2495 qWarning("Failed to present, no swapchain");
2496 return QRhi::FrameOpError;
2497 }
2498 HRESULT hr = swapChainD->swapChain->Present(swapChainD->swapInterval, presentFlags);
2499 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
2500 qWarning("Device loss detected in Present()");
2501 deviceLost = true;
2502 return QRhi::FrameOpDeviceLost;
2503 } else if (FAILED(hr)) {
2504 qWarning("Failed to present: %s", qPrintable(QSystemError::windowsComString(hr)));
2505 return QRhi::FrameOpError;
2506 }
2507
2508 if (dcompDevice && swapChainD->dcompTarget && swapChainD->dcompVisual)
2509 dcompDevice->Commit();
2510 }
2511
2512 swapChainD->addCommandCompletionSignalForCurrentFrameSlot();
2513
2514 // NB! The deferred-release mechanism here differs from the older QRhi
2515 // backends. There is no lastActiveFrameSlot tracking. Instead,
2516 // currentFrameSlot is written to the registered entries now, and so the
2517 // resources will get released in the frames_in_flight'th beginFrame()
2518 // counting starting from now.
2519 releaseQueue.activatePendingDeferredReleaseRequests(currentFrameSlot);
2520
2521 if (!flags.testFlag(QRhi::SkipPresent)) {
2522 // Only move to the next slot if we presented. Otherwise will block and
2523 // wait for completion in the next beginFrame already, but SkipPresent
2524 // should be infrequent anyway.
2525 swapChainD->currentFrameSlot = (swapChainD->currentFrameSlot + 1) % QD3D12_FRAMES_IN_FLIGHT;
2526 swapChainD->currentBackBufferIndex = swapChainD->swapChain->GetCurrentBackBufferIndex();
2527 }
2528
2529 currentSwapChain = nullptr;
2530 return QRhi::FrameOpSuccess;
2531}
2532
2533QRhi::FrameOpResult QRhiD3D12::beginOffscreenFrame(QRhiCommandBuffer **cb, QRhi::BeginFrameFlags flags)
2534{
2535 Q_UNUSED(flags);
2536
2537 // Switch to the next slot manually. Swapchains do not know about this
2538 // which is good. So for example an onscreen, onscreen, offscreen,
2539 // onscreen, onscreen, onscreen sequence of frames leads to 0, 1, 0, 0, 1,
2540 // 0. (no strict alternation anymore) But this is not different from what
2541 // happens when multiple swapchains are involved. Offscreen frames are
2542 // synchronous anyway in the sense that they wait for execution to complete
2543 // in endOffscreenFrame, so no resources used in that frame are busy
2544 // anymore in the next frame.
2545
2546 currentFrameSlot = (currentFrameSlot + 1) % QD3D12_FRAMES_IN_FLIGHT;
2547
2548 for (QD3D12SwapChain *sc : std::as_const(swapchains))
2549 sc->waitCommandCompletionForFrameSlot(currentFrameSlot); // note: not sc's currentFrameSlot
2550
2551 HRESULT hr = cmdAllocators[currentFrameSlot]->Reset();
2552 if (FAILED(hr)) {
2553 qWarning("Failed to reset command allocator: %s",
2554 qPrintable(QSystemError::windowsComString(hr)));
2555 return QRhi::FrameOpError;
2556 }
2557
2558 if (!offscreenCb[currentFrameSlot])
2559 offscreenCb[currentFrameSlot] = new QD3D12CommandBuffer(this);
2560 QD3D12CommandBuffer *cbD = offscreenCb[currentFrameSlot];
2561 if (!startCommandListForCurrentFrameSlot(&cbD->cmdList))
2562 return QRhi::FrameOpError;
2563
2564 releaseQueue.executeDeferredReleases(currentFrameSlot);
2565 cbD->resetState();
2566 shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[currentFrameSlot].head = 0;
2567 resetAndResizeSmallStagingArea(currentFrameSlot);
2568
2569 bindShaderVisibleHeaps(cbD);
2570
2571 if (timestampQueryHeap.isValid() && timestampTicksPerSecond) {
2572 cbD->cmdList->EndQuery(timestampQueryHeap.heap,
2573 D3D12_QUERY_TYPE_TIMESTAMP,
2574 currentFrameSlot * QD3D12_FRAMES_IN_FLIGHT);
2575 }
2576
2577 offscreenActive = true;
2578 *cb = cbD;
2579
2580 return QRhi::FrameOpSuccess;
2581}
2582
2583QRhi::FrameOpResult QRhiD3D12::endOffscreenFrame(QRhi::EndFrameFlags flags)
2584{
2585 Q_UNUSED(flags);
2586 Q_ASSERT(offscreenActive);
2587 offscreenActive = false;
2588
2589 QD3D12CommandBuffer *cbD = offscreenCb[currentFrameSlot];
2590 if (timestampQueryHeap.isValid()) {
2591 const int timestampPairStartIndex = currentFrameSlot * QD3D12_FRAMES_IN_FLIGHT;
2592 cbD->cmdList->EndQuery(timestampQueryHeap.heap,
2593 D3D12_QUERY_TYPE_TIMESTAMP,
2594 timestampPairStartIndex + 1);
2595 cbD->cmdList->ResolveQueryData(timestampQueryHeap.heap,
2596 D3D12_QUERY_TYPE_TIMESTAMP,
2597 timestampPairStartIndex,
2598 2,
2599 timestampReadbackArea.mem.buffer,
2600 timestampPairStartIndex * sizeof(quint64));
2601 }
2602
2603 D3D12GraphicsCommandList *cmdList = cbD->cmdList;
2604 HRESULT hr = cmdList->Close();
2605 if (FAILED(hr)) {
2606 qWarning("Failed to close command list: %s",
2607 qPrintable(QSystemError::windowsComString(hr)));
2608 return QRhi::FrameOpError;
2609 }
2610
2611 ID3D12CommandList *execList[] = { cmdList };
2612 cmdQueue->ExecuteCommandLists(1, execList);
2613
2614 releaseQueue.activatePendingDeferredReleaseRequests(currentFrameSlot);
2615
2616 // wait for completion
2617 waitGpu();
2618
2619 // Here we know that executing the host-side reads for this (or any
2620 // previous) frame is safe since we waited for completion above.
2621 finishActiveReadbacks(true);
2622
2623 // the timestamp query results should be available too, given the wait
2624 if (timestampQueryHeap.isValid()) {
2625 calculateGpuTime(cbD,
2626 currentFrameSlot * QD3D12_FRAMES_IN_FLIGHT,
2627 timestampReadbackArea.mem.p,
2628 timestampTicksPerSecond);
2629 }
2630
2631 return QRhi::FrameOpSuccess;
2632}
2633
2634QRhi::FrameOpResult QRhiD3D12::finish()
2635{
2636 QD3D12CommandBuffer *cbD = nullptr;
2637 if (inFrame) {
2638 if (offscreenActive) {
2639 Q_ASSERT(!currentSwapChain);
2640 cbD = offscreenCb[currentFrameSlot];
2641 } else {
2642 Q_ASSERT(currentSwapChain);
2643 cbD = &currentSwapChain->cbWrapper;
2644 }
2645 if (!cbD)
2646 return QRhi::FrameOpError;
2647
2648 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::NoPass);
2649
2650 D3D12GraphicsCommandList *cmdList = cbD->cmdList;
2651 HRESULT hr = cmdList->Close();
2652 if (FAILED(hr)) {
2653 qWarning("Failed to close command list: %s",
2654 qPrintable(QSystemError::windowsComString(hr)));
2655 return QRhi::FrameOpError;
2656 }
2657
2658 ID3D12CommandList *execList[] = { cmdList };
2659 cmdQueue->ExecuteCommandLists(1, execList);
2660
2661 releaseQueue.activatePendingDeferredReleaseRequests(currentFrameSlot);
2662 }
2663
2664 // full blocking wait for everything, frame slots do not matter now
2665 waitGpu();
2666
2667 if (inFrame) {
2668 HRESULT hr = cmdAllocators[currentFrameSlot]->Reset();
2669 if (FAILED(hr)) {
2670 qWarning("Failed to reset command allocator: %s",
2671 qPrintable(QSystemError::windowsComString(hr)));
2672 return QRhi::FrameOpError;
2673 }
2674
2675 if (!startCommandListForCurrentFrameSlot(&cbD->cmdList))
2676 return QRhi::FrameOpError;
2677
2678 cbD->resetState();
2679
2680 shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[currentFrameSlot].head = 0;
2681 smallStagingAreas[currentFrameSlot].head = 0;
2682
2683 bindShaderVisibleHeaps(cbD);
2684 }
2685
2686 releaseQueue.releaseAll();
2687 finishActiveReadbacks(true);
2688
2689 return QRhi::FrameOpSuccess;
2690}
2691
2692void QRhiD3D12::resourceUpdate(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
2693{
2694 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2695 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::NoPass);
2696 enqueueResourceUpdates(cbD, resourceUpdates);
2697}
2698
2699void QRhiD3D12::beginPass(QRhiCommandBuffer *cb,
2700 QRhiRenderTarget *rt,
2701 const QColor &colorClearValue,
2702 const QRhiDepthStencilClearValue &depthStencilClearValue,
2703 QRhiResourceUpdateBatch *resourceUpdates,
2704 QRhiCommandBuffer::BeginPassFlags)
2705{
2706 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2707 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::NoPass);
2708
2709 if (resourceUpdates)
2710 enqueueResourceUpdates(cbD, resourceUpdates);
2711
2712 QD3D12RenderTargetData *rtD = rtData(rt);
2713 bool wantsColorClear = true;
2714 bool wantsDsClear = true;
2715 if (rt->resourceType() == QRhiRenderTarget::TextureRenderTarget) {
2716 QD3D12TextureRenderTarget *rtTex = QRHI_RES(QD3D12TextureRenderTarget, rt);
2717 wantsColorClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveColorContents);
2718 wantsDsClear = !rtTex->m_flags.testFlag(QRhiTextureRenderTarget::PreserveDepthStencilContents);
2719 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QD3D12Texture, QD3D12RenderBuffer>(rtTex->description(), rtD->currentResIdList))
2720 rtTex->create();
2721
2722 for (auto it = rtTex->m_desc.cbeginColorAttachments(), itEnd = rtTex->m_desc.cendColorAttachments(); it != itEnd; ++it) {
2723 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, it->texture());
2724 QD3D12Texture *resolveTexD = QRHI_RES(QD3D12Texture, it->resolveTexture());
2725 QD3D12RenderBuffer *rbD = QRHI_RES(QD3D12RenderBuffer, it->renderBuffer());
2726 if (texD)
2727 barrierGen.addTransitionBarrier(texD->handle, D3D12_RESOURCE_STATE_RENDER_TARGET);
2728 else if (rbD)
2729 barrierGen.addTransitionBarrier(rbD->handle, D3D12_RESOURCE_STATE_RENDER_TARGET);
2730 if (resolveTexD)
2731 barrierGen.addTransitionBarrier(resolveTexD->handle, D3D12_RESOURCE_STATE_RENDER_TARGET);
2732 }
2733 if (rtTex->m_desc.depthStencilBuffer()) {
2734 QD3D12RenderBuffer *rbD = QRHI_RES(QD3D12RenderBuffer, rtTex->m_desc.depthStencilBuffer());
2735 Q_ASSERT(rbD->m_type == QRhiRenderBuffer::DepthStencil);
2736 barrierGen.addTransitionBarrier(rbD->handle, D3D12_RESOURCE_STATE_DEPTH_WRITE);
2737 } else if (rtTex->m_desc.depthTexture()) {
2738 QD3D12Texture *depthTexD = QRHI_RES(QD3D12Texture, rtTex->m_desc.depthTexture());
2739 barrierGen.addTransitionBarrier(depthTexD->handle, D3D12_RESOURCE_STATE_DEPTH_WRITE);
2740 }
2741 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2742 } else {
2743 Q_ASSERT(currentSwapChain);
2744 barrierGen.addTransitionBarrier(currentSwapChain->sampleDesc.Count > 1
2745 ? currentSwapChain->msaaBuffers[currentFrameSlot]
2746 : currentSwapChain->colorBuffers[currentSwapChain->currentBackBufferIndex],
2747 D3D12_RESOURCE_STATE_RENDER_TARGET);
2748 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2749 }
2750
2751 cbD->cmdList->OMSetRenderTargets(UINT(rtD->colorAttCount),
2752 rtD->rtv,
2753 FALSE,
2754 rtD->dsAttCount ? &rtD->dsv : nullptr);
2755
2756 if (rtD->colorAttCount && wantsColorClear) {
2757 float clearColor[4] = {
2758 colorClearValue.redF(),
2759 colorClearValue.greenF(),
2760 colorClearValue.blueF(),
2761 colorClearValue.alphaF()
2762 };
2763 for (int i = 0; i < rtD->colorAttCount; ++i)
2764 cbD->cmdList->ClearRenderTargetView(rtD->rtv[i], clearColor, 0, nullptr);
2765 }
2766 if (rtD->dsAttCount && wantsDsClear) {
2767 cbD->cmdList->ClearDepthStencilView(rtD->dsv,
2768 D3D12_CLEAR_FLAGS(D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL),
2769 depthStencilClearValue.depthClearValue(),
2770 UINT8(depthStencilClearValue.stencilClearValue()),
2771 0,
2772 nullptr);
2773 }
2774
2775 cbD->recordingPass = QD3D12CommandBuffer::RenderPass;
2776 cbD->currentTarget = rt;
2777
2778 bool hasShadingRateMapSet = false;
2779#ifdef QRHI_D3D12_CL5_AVAILABLE
2780 if (rtD->rp->hasShadingRateMap) {
2781 cbD->setShadingRate(QSize(1, 1));
2782 QD3D12ShadingRateMap *rateMapD = rt->resourceType() == QRhiRenderTarget::TextureRenderTarget
2783 ? QRHI_RES(QD3D12ShadingRateMap, QRHI_RES(QD3D12TextureRenderTarget, rt)->m_desc.shadingRateMap())
2784 : QRHI_RES(QD3D12ShadingRateMap, QRHI_RES(QD3D12SwapChainRenderTarget, rt)->swapChain()->shadingRateMap());
2785 if (QD3D12Resource *res = resourcePool.lookupRef(rateMapD->handle)) {
2786 barrierGen.addTransitionBarrier(rateMapD->handle, D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE);
2787 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2788 cbD->cmdList->RSSetShadingRateImage(res->resource);
2789 hasShadingRateMapSet = true;
2790 }
2791 } else if (cbD->hasShadingRateMapSet) {
2792 cbD->cmdList->RSSetShadingRateImage(nullptr);
2793 cbD->setShadingRate(QSize(1, 1));
2794 } else if (cbD->hasShadingRateSet) {
2795 cbD->setShadingRate(QSize(1, 1));
2796 }
2797#endif
2798
2799 cbD->resetPerPassState();
2800
2801 // shading rate tracking is reset in resetPerPassState(), sync what we did just above
2802 cbD->hasShadingRateMapSet = hasShadingRateMapSet;
2803}
2804
2805void QRhiD3D12::endPass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
2806{
2807 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2808 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
2809
2810 if (cbD->currentTarget->resourceType() == QRhiResource::TextureRenderTarget) {
2811 QD3D12TextureRenderTarget *rtTex = QRHI_RES(QD3D12TextureRenderTarget, cbD->currentTarget);
2812 for (auto it = rtTex->m_desc.cbeginColorAttachments(), itEnd = rtTex->m_desc.cendColorAttachments();
2813 it != itEnd; ++it)
2814 {
2815 const QRhiColorAttachment &colorAtt(*it);
2816 if (!colorAtt.resolveTexture())
2817 continue;
2818
2819 QD3D12Texture *dstTexD = QRHI_RES(QD3D12Texture, colorAtt.resolveTexture());
2820 QD3D12Resource *dstRes = resourcePool.lookupRef(dstTexD->handle);
2821 if (!dstRes)
2822 continue;
2823
2824 QD3D12Texture *srcTexD = QRHI_RES(QD3D12Texture, colorAtt.texture());
2825 QD3D12RenderBuffer *srcRbD = QRHI_RES(QD3D12RenderBuffer, colorAtt.renderBuffer());
2826 Q_ASSERT(srcTexD || srcRbD);
2827 QD3D12Resource *srcRes = resourcePool.lookupRef(srcTexD ? srcTexD->handle : srcRbD->handle);
2828 if (!srcRes)
2829 continue;
2830
2831 if (srcTexD) {
2832 if (srcTexD->dxgiFormat != dstTexD->dxgiFormat) {
2833 qWarning("Resolve source (%d) and destination (%d) formats do not match",
2834 int(srcTexD->dxgiFormat), int(dstTexD->dxgiFormat));
2835 continue;
2836 }
2837 if (srcTexD->sampleDesc.Count <= 1) {
2838 qWarning("Cannot resolve a non-multisample texture");
2839 continue;
2840 }
2841 if (srcTexD->m_pixelSize != dstTexD->m_pixelSize) {
2842 qWarning("Resolve source and destination sizes do not match");
2843 continue;
2844 }
2845 } else {
2846 if (srcRbD->dxgiFormat != dstTexD->dxgiFormat) {
2847 qWarning("Resolve source (%d) and destination (%d) formats do not match",
2848 int(srcRbD->dxgiFormat), int(dstTexD->dxgiFormat));
2849 continue;
2850 }
2851 if (srcRbD->m_pixelSize != dstTexD->m_pixelSize) {
2852 qWarning("Resolve source and destination sizes do not match");
2853 continue;
2854 }
2855 }
2856
2857 // The subresources of a placed resource must be initialized with a
2858 // Discard, Clear, or Copy before they can be used for anything else.
2859 // ResolveSubresource is not one of those, so discard the destination
2860 // subresources that were never written to, otherwise the debug layer
2861 // complains. Only the subresources that are about to be overwritten
2862 // by the resolve are discarded, and only once each.
2863 const UINT resolveCount = colorAtt.multiViewCount() >= 2 ? colorAtt.multiViewCount() : 1;
2864 QBitArray &initialized(dstTexD->subresourceInitialized);
2865 QVarLengthArray<UINT, 4> dstSubresources;
2866 QVarLengthArray<UINT, 4> subresourcesToDiscard;
2867 for (UINT resolveIdx = 0; resolveIdx < resolveCount; ++resolveIdx) {
2868 const UINT dstSubresource = calcSubresource(UINT(colorAtt.resolveLevel()),
2869 UINT(colorAtt.resolveLayer()) + resolveIdx,
2870 dstTexD->mipLevelCount);
2871 dstSubresources.append(dstSubresource);
2872 if (int(dstSubresource) >= initialized.size())
2873 initialized.resize(int(dstSubresource) + 1);
2874 if (!initialized.testBit(int(dstSubresource))) {
2875 initialized.setBit(int(dstSubresource));
2876 subresourcesToDiscard.append(dstSubresource);
2877 }
2878 }
2879
2880 barrierGen.addTransitionBarrier(srcTexD ? srcTexD->handle : srcRbD->handle, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
2881
2882 // Discarding needs the RENDER_TARGET state, unlike the resolve itself.
2883 if (!subresourcesToDiscard.isEmpty()) {
2884 barrierGen.addTransitionBarrier(dstTexD->handle, D3D12_RESOURCE_STATE_RENDER_TARGET);
2885 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2886 for (UINT dstSubresource : subresourcesToDiscard) {
2887 D3D12_DISCARD_REGION region = {};
2888 region.FirstSubresource = dstSubresource;
2889 region.NumSubresources = 1;
2890 cbD->cmdList->DiscardResource(dstRes->resource, &region);
2891 }
2892 }
2893
2894 barrierGen.addTransitionBarrier(dstTexD->handle, D3D12_RESOURCE_STATE_RESOLVE_DEST);
2895 barrierGen.enqueueBufferedTransitionBarriers(cbD);
2896
2897 for (UINT resolveIdx = 0; resolveIdx < resolveCount; ++resolveIdx) {
2898 const UINT srcSubresource = calcSubresource(0, UINT(colorAtt.layer()) + resolveIdx, 1);
2899 cbD->cmdList->ResolveSubresource(dstRes->resource, dstSubresources[resolveIdx],
2900 srcRes->resource, srcSubresource,
2901 dstTexD->dxgiFormat);
2902 }
2903 }
2904 if (rtTex->m_desc.depthResolveTexture())
2905 qWarning("Resolving multisample depth-stencil buffers is not supported with D3D");
2906 }
2907
2908 cbD->recordingPass = QD3D12CommandBuffer::NoPass;
2909 cbD->currentTarget = nullptr;
2910
2911 if (resourceUpdates)
2912 enqueueResourceUpdates(cbD, resourceUpdates);
2913}
2914
2915void QRhiD3D12::beginComputePass(QRhiCommandBuffer *cb,
2916 QRhiResourceUpdateBatch *resourceUpdates,
2917 QRhiCommandBuffer::BeginPassFlags)
2918{
2919 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2920 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::NoPass);
2921
2922 if (resourceUpdates)
2923 enqueueResourceUpdates(cbD, resourceUpdates);
2924
2925 cbD->recordingPass = QD3D12CommandBuffer::ComputePass;
2926
2927 cbD->resetPerPassState();
2928}
2929
2930void QRhiD3D12::endComputePass(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
2931{
2932 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2933 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::ComputePass);
2934
2935 cbD->recordingPass = QD3D12CommandBuffer::NoPass;
2936
2937 if (resourceUpdates)
2938 enqueueResourceUpdates(cbD, resourceUpdates);
2939}
2940
2941void QRhiD3D12::setComputePipeline(QRhiCommandBuffer *cb, QRhiComputePipeline *ps)
2942{
2943 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2944 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::ComputePass);
2945 QD3D12ComputePipeline *psD = QRHI_RES(QD3D12ComputePipeline, ps);
2946 const bool pipelineChanged = cbD->currentComputePipeline != psD || cbD->currentPipelineGeneration != psD->generation;
2947
2948 if (pipelineChanged) {
2949 cbD->currentGraphicsPipeline = nullptr;
2950 cbD->currentComputePipeline = psD;
2951 cbD->currentPipelineGeneration = psD->generation;
2952
2953 if (QD3D12Pipeline *pipeline = pipelinePool.lookupRef(psD->handle)) {
2954 Q_ASSERT(pipeline->type == QD3D12Pipeline::Compute);
2955 cbD->cmdList->SetPipelineState(pipeline->pso);
2956 if (QD3D12RootSignature *rs = rootSignaturePool.lookupRef(psD->rootSigHandle))
2957 cbD->cmdList->SetComputeRootSignature(rs->rootSig);
2958 }
2959 }
2960}
2961
2962void QRhiD3D12::dispatch(QRhiCommandBuffer *cb, int x, int y, int z)
2963{
2964 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
2965 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::ComputePass);
2966 cbD->cmdList->Dispatch(UINT(x), UINT(y), UINT(z));
2967}
2968
2969// ByteStride is a property of the command signature, so a non-canonical stride
2970// needs its own. Cannot loop with MaxCommandCount 1 like drawIndirect() does,
2971// because ExecuteIndirect executes min(MaxCommandCount, *countBuffer) commands.
2972ID3D12CommandSignature *QRhiD3D12::indirectDrawCommandSignature(bool indexed, quint32 stride)
2973{
2974 const quint32 canonicalStride = indexed ? sizeof(QRhiIndexedIndirectDrawCommand)
2975 : sizeof(QRhiIndirectDrawCommand);
2976 if (stride == canonicalStride)
2977 return indexed ? drawIndexedCommandSignature : drawCommandSignature;
2978
2979 QHash<quint32, ID3D12CommandSignature *> &cache(indexed ? drawIndexedCommandSignaturesByStride
2980 : drawCommandSignaturesByStride);
2981 auto it = cache.constFind(stride);
2982 if (it != cache.constEnd())
2983 return *it;
2984
2985 D3D12_INDIRECT_ARGUMENT_DESC arg = {};
2986 arg.Type = indexed ? D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED : D3D12_INDIRECT_ARGUMENT_TYPE_DRAW;
2987
2988 D3D12_COMMAND_SIGNATURE_DESC sigDesc = {};
2989 sigDesc.ByteStride = stride;
2990 sigDesc.NumArgumentDescs = 1;
2991 sigDesc.pArgumentDescs = &arg;
2992
2993 ID3D12CommandSignature *sig = nullptr;
2994 HRESULT hr = dev->CreateCommandSignature(&sigDesc, nullptr, IID_PPV_ARGS(&sig));
2995 if (FAILED(hr)) {
2996 qWarning("Failed to create indirect draw command signature with stride %u: %s",
2997 stride, qPrintable(QSystemError::windowsComString(hr)));
2998 return nullptr;
2999 }
3000
3001 cache.insert(stride, sig);
3002 return sig;
3003}
3004
3005void QRhiD3D12::drawIndirectCount(QRhiCommandBuffer *cb,
3006 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
3007 QRhiBuffer *countBuffer, quint32 countBufferOffset,
3008 quint32 maxDrawCount, quint32 stride)
3009{
3010 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
3011 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
3012
3013 ID3D12CommandSignature *sig = indirectDrawCommandSignature(false, stride);
3014 if (!sig)
3015 return;
3016
3017 QD3D12Buffer *indirectBufferD = QRHI_RES(QD3D12Buffer, indirectBuffer);
3018 const bool indirectIsDynamic = indirectBufferD->m_type == QRhiBuffer::Dynamic;
3019 const QD3D12ObjectHandle indirectHandle = indirectBufferD->handles[indirectIsDynamic ? currentFrameSlot : 0];
3020 if (indirectIsDynamic)
3021 indirectBufferD->executeHostWritesForFrameSlot(currentFrameSlot);
3022 else
3023 barrierGen.addTransitionBarrier(indirectHandle, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
3024
3025 QD3D12Buffer *countBufferD = QRHI_RES(QD3D12Buffer, countBuffer);
3026 const bool countIsDynamic = countBufferD->m_type == QRhiBuffer::Dynamic;
3027 const QD3D12ObjectHandle countHandle = countBufferD->handles[countIsDynamic ? currentFrameSlot : 0];
3028 if (countIsDynamic)
3029 countBufferD->executeHostWritesForFrameSlot(currentFrameSlot);
3030 else
3031 barrierGen.addTransitionBarrier(countHandle, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
3032
3033 if (!indirectIsDynamic || !countIsDynamic)
3034 barrierGen.enqueueBufferedTransitionBarriers(cbD);
3035
3036 QD3D12Resource *indirectRes = resourcePool.lookupRef(indirectHandle);
3037 QD3D12Resource *countRes = resourcePool.lookupRef(countHandle);
3038 if (!indirectRes || !countRes)
3039 return;
3040
3041 cbD->cmdList->ExecuteIndirect(sig, maxDrawCount,
3042 indirectRes->resource, indirectBufferOffset,
3043 countRes->resource, countBufferOffset);
3044}
3045
3046void QRhiD3D12::drawIndexedIndirectCount(QRhiCommandBuffer *cb,
3047 QRhiBuffer *indirectBuffer, quint32 indirectBufferOffset,
3048 QRhiBuffer *countBuffer, quint32 countBufferOffset,
3049 quint32 maxDrawCount, quint32 stride)
3050{
3051 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
3052 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::RenderPass);
3053
3054 ID3D12CommandSignature *sig = indirectDrawCommandSignature(true, stride);
3055 if (!sig)
3056 return;
3057
3058 QD3D12Buffer *indirectBufferD = QRHI_RES(QD3D12Buffer, indirectBuffer);
3059 const bool indirectIsDynamic = indirectBufferD->m_type == QRhiBuffer::Dynamic;
3060 const QD3D12ObjectHandle indirectHandle = indirectBufferD->handles[indirectIsDynamic ? currentFrameSlot : 0];
3061 if (indirectIsDynamic)
3062 indirectBufferD->executeHostWritesForFrameSlot(currentFrameSlot);
3063 else
3064 barrierGen.addTransitionBarrier(indirectHandle, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
3065
3066 QD3D12Buffer *countBufferD = QRHI_RES(QD3D12Buffer, countBuffer);
3067 const bool countIsDynamic = countBufferD->m_type == QRhiBuffer::Dynamic;
3068 const QD3D12ObjectHandle countHandle = countBufferD->handles[countIsDynamic ? currentFrameSlot : 0];
3069 if (countIsDynamic)
3070 countBufferD->executeHostWritesForFrameSlot(currentFrameSlot);
3071 else
3072 barrierGen.addTransitionBarrier(countHandle, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
3073
3074 if (!indirectIsDynamic || !countIsDynamic)
3075 barrierGen.enqueueBufferedTransitionBarriers(cbD);
3076
3077 QD3D12Resource *indirectRes = resourcePool.lookupRef(indirectHandle);
3078 QD3D12Resource *countRes = resourcePool.lookupRef(countHandle);
3079 if (!indirectRes || !countRes)
3080 return;
3081
3082 cbD->cmdList->ExecuteIndirect(sig, maxDrawCount,
3083 indirectRes->resource, indirectBufferOffset,
3084 countRes->resource, countBufferOffset);
3085}
3086
3087void QRhiD3D12::dispatchIndirect(QRhiCommandBuffer *cb, QRhiBuffer *indirectBuffer,
3088 quint32 indirectBufferOffset)
3089{
3090 QD3D12CommandBuffer *cbD = QRHI_RES(QD3D12CommandBuffer, cb);
3091 Q_ASSERT(cbD->recordingPass == QD3D12CommandBuffer::ComputePass);
3092
3093 QD3D12Buffer *indirectBufferD = QRHI_RES(QD3D12Buffer, indirectBuffer);
3094 const bool isDynamic = indirectBufferD->m_type == QRhiBuffer::Dynamic;
3095 const QD3D12ObjectHandle indirectBufferHandle = indirectBufferD->handles[isDynamic ? currentFrameSlot : 0];
3096 if (isDynamic) {
3097 indirectBufferD->executeHostWritesForFrameSlot(currentFrameSlot);
3098 } else {
3099 // For Static/Immutable buffers, transition to INDIRECT_ARGUMENT state
3100 // so any earlier UAV writes (e.g. by a compute shader that produced
3101 // the dispatch arguments) are flushed before ExecuteIndirect reads.
3102 barrierGen.addTransitionBarrier(indirectBufferHandle, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT);
3103 barrierGen.enqueueBufferedTransitionBarriers(cbD);
3104 }
3105 QD3D12Resource *indirectRes = resourcePool.lookupRef(indirectBufferHandle);
3106 if (!indirectRes)
3107 return;
3108
3109 cbD->cmdList->ExecuteIndirect(dispatchCommandSignature, 1,
3110 indirectRes->resource, indirectBufferOffset,
3111 nullptr, 0);
3112}
3113
3114bool QD3D12DescriptorHeap::create(ID3D12Device *device,
3115 quint32 descriptorCount,
3116 D3D12_DESCRIPTOR_HEAP_TYPE heapType,
3117 D3D12_DESCRIPTOR_HEAP_FLAGS heapFlags)
3118{
3119 head = 0;
3120 capacity = descriptorCount;
3121 this->heapType = heapType;
3122 this->heapFlags = heapFlags;
3123
3124 D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
3125 heapDesc.Type = heapType;
3126 heapDesc.NumDescriptors = capacity;
3127 heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAGS(heapFlags);
3128
3129 HRESULT hr = device->CreateDescriptorHeap(&heapDesc, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void **>(&heap));
3130 if (FAILED(hr)) {
3131 qWarning("Failed to create descriptor heap: %s", qPrintable(QSystemError::windowsComString(hr)));
3132 heap = nullptr;
3133 capacity = descriptorByteSize = 0;
3134 return false;
3135 }
3136
3137 descriptorByteSize = device->GetDescriptorHandleIncrementSize(heapType);
3138 heapStart.cpuHandle = heap->GetCPUDescriptorHandleForHeapStart();
3139 if (heapFlags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)
3140 heapStart.gpuHandle = heap->GetGPUDescriptorHandleForHeapStart();
3141
3142 return true;
3143}
3144
3145void QD3D12DescriptorHeap::createWithExisting(const QD3D12DescriptorHeap &other,
3146 quint32 offsetInDescriptors,
3147 quint32 descriptorCount)
3148{
3149 heap = nullptr;
3150 head = 0;
3151 capacity = descriptorCount;
3152 heapType = other.heapType;
3153 heapFlags = other.heapFlags;
3154 descriptorByteSize = other.descriptorByteSize;
3155 heapStart = incremented(other.heapStart, offsetInDescriptors);
3156}
3157
3158void QD3D12DescriptorHeap::destroy()
3159{
3160 if (heap) {
3161 heap->Release();
3162 heap = nullptr;
3163 }
3164 capacity = 0;
3165}
3166
3167void QD3D12DescriptorHeap::destroyWithDeferredRelease(QD3D12ReleaseQueue *releaseQueue)
3168{
3169 if (heap) {
3170 releaseQueue->deferredReleaseDescriptorHeap(heap);
3171 heap = nullptr;
3172 }
3173 capacity = 0;
3174}
3175
3176QD3D12Descriptor QD3D12DescriptorHeap::get(quint32 count)
3177{
3178 Q_ASSERT(count > 0);
3179 if (head + count > capacity) {
3180 qWarning("Cannot get %u descriptors as that would exceed capacity %u", count, capacity);
3181 return {};
3182 }
3183 head += count;
3184 return at(head - count);
3185}
3186
3187QD3D12Descriptor QD3D12DescriptorHeap::at(quint32 index) const
3188{
3189 const quint32 startOffset = index * descriptorByteSize;
3190 QD3D12Descriptor result;
3191 result.cpuHandle.ptr = heapStart.cpuHandle.ptr + startOffset;
3192 if (heapStart.gpuHandle.ptr != 0)
3193 result.gpuHandle.ptr = heapStart.gpuHandle.ptr + startOffset;
3194 return result;
3195}
3196
3197bool QD3D12CpuDescriptorPool::create(ID3D12Device *device, D3D12_DESCRIPTOR_HEAP_TYPE heapType, const char *debugName)
3198{
3199 QD3D12DescriptorHeap firstHeap;
3200 if (!firstHeap.create(device, DESCRIPTORS_PER_HEAP, heapType, D3D12_DESCRIPTOR_HEAP_FLAG_NONE))
3201 return false;
3202 heaps.append(HeapWithMap::init(firstHeap, DESCRIPTORS_PER_HEAP));
3203 descriptorByteSize = heaps[0].heap.descriptorByteSize;
3204 this->device = device;
3205 this->debugName = debugName;
3206 return true;
3207}
3208
3209void QD3D12CpuDescriptorPool::destroy()
3210{
3211#ifndef QT_NO_DEBUG
3212 // debug builds: just do it always
3213 static bool leakCheck = true;
3214#else
3215 // release builds: opt-in
3216 static bool leakCheck = qEnvironmentVariableIntValue("QT_RHI_LEAK_CHECK");
3217#endif
3218 if (leakCheck) {
3219 for (const HeapWithMap &heap : std::as_const(heaps)) {
3220 const int leakedDescriptorCount = heap.map.count(true);
3221 if (leakedDescriptorCount > 0) {
3222 qWarning("QD3D12CpuDescriptorPool::destroy(): "
3223 "Heap %p for descriptor pool %p '%s' has %d unreleased descriptors",
3224 &heap.heap, this, debugName, leakedDescriptorCount);
3225 }
3226 }
3227 }
3228 for (HeapWithMap &heap : heaps)
3229 heap.heap.destroy();
3230 heaps.clear();
3231}
3232
3233QD3D12Descriptor QD3D12CpuDescriptorPool::allocate(quint32 count)
3234{
3235 Q_ASSERT(count > 0 && count <= DESCRIPTORS_PER_HEAP);
3236
3237 HeapWithMap &last(heaps.last());
3238 if (last.heap.head + count <= last.heap.capacity) {
3239 quint32 firstIndex = last.heap.head;
3240 for (quint32 i = 0; i < count; ++i)
3241 last.map.setBit(firstIndex + i);
3242 return last.heap.get(count);
3243 }
3244
3245 for (HeapWithMap &heap : heaps) {
3246 quint32 freeCount = 0;
3247 for (quint32 i = 0; i < DESCRIPTORS_PER_HEAP; ++i) {
3248 if (heap.map.testBit(i)) {
3249 freeCount = 0;
3250 } else {
3251 freeCount += 1;
3252 if (freeCount == count) {
3253 const quint32 firstIndex = i - (freeCount - 1);
3254 for (quint32 j = 0; j < count; ++j)
3255 heap.map.setBit(firstIndex + j);
3256 // May need to bump heap.head to ensure the heap.get() on
3257 // the other code path above does not accidentally alias the
3258 // same entries when count > 1.
3259 if (firstIndex + count > heap.heap.head)
3260 heap.heap.head = firstIndex + count;
3261 return heap.heap.at(firstIndex);
3262 }
3263 }
3264 }
3265 }
3266
3267 QD3D12DescriptorHeap newHeap;
3268 if (!newHeap.create(device, DESCRIPTORS_PER_HEAP, last.heap.heapType, last.heap.heapFlags))
3269 return {};
3270
3271 heaps.append(HeapWithMap::init(newHeap, DESCRIPTORS_PER_HEAP));
3272
3273 for (quint32 i = 0; i < count; ++i)
3274 heaps.last().map.setBit(i);
3275
3276 return heaps.last().heap.get(count);
3277}
3278
3279void QD3D12CpuDescriptorPool::release(const QD3D12Descriptor &descriptor, quint32 count)
3280{
3281 Q_ASSERT(count > 0 && count <= DESCRIPTORS_PER_HEAP);
3282 if (!descriptor.isValid())
3283 return;
3284
3285 const SIZE_T addr = descriptor.cpuHandle.ptr;
3286 for (HeapWithMap &heap : heaps) {
3287 const SIZE_T begin = heap.heap.heapStart.cpuHandle.ptr;
3288 const SIZE_T end = begin + heap.heap.descriptorByteSize * heap.heap.capacity;
3289 if (addr >= begin && addr < end) {
3290 quint32 firstIndex = (addr - begin) / heap.heap.descriptorByteSize;
3291 for (quint32 i = 0; i < count; ++i)
3292 heap.map.setBit(firstIndex + i, false);
3293 return;
3294 }
3295 }
3296
3297 qWarning("QD3D12CpuDescriptorPool::release: Descriptor with address %llu is not in any heap",
3298 quint64(descriptor.cpuHandle.ptr));
3299}
3300
3301bool QD3D12QueryHeap::create(ID3D12Device *device,
3302 quint32 queryCount,
3303 D3D12_QUERY_HEAP_TYPE heapType)
3304{
3305 capacity = queryCount;
3306
3307 D3D12_QUERY_HEAP_DESC heapDesc = {};
3308 heapDesc.Type = heapType;
3309 heapDesc.Count = capacity;
3310
3311 HRESULT hr = device->CreateQueryHeap(&heapDesc, __uuidof(ID3D12QueryHeap), reinterpret_cast<void **>(&heap));
3312 if (FAILED(hr)) {
3313 qWarning("Failed to create query heap: %s", qPrintable(QSystemError::windowsComString(hr)));
3314 heap = nullptr;
3315 capacity = 0;
3316 return false;
3317 }
3318
3319 return true;
3320}
3321
3322void QD3D12QueryHeap::destroy()
3323{
3324 if (heap) {
3325 heap->Release();
3326 heap = nullptr;
3327 }
3328 capacity = 0;
3329}
3330
3331bool QD3D12StagingArea::create(QRhiD3D12 *rhi, quint32 capacity, D3D12_HEAP_TYPE heapType)
3332{
3333 Q_ASSERT(heapType == D3D12_HEAP_TYPE_UPLOAD || heapType == D3D12_HEAP_TYPE_READBACK);
3334 D3D12_RESOURCE_DESC resourceDesc = {};
3335 resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
3336 resourceDesc.Width = capacity;
3337 resourceDesc.Height = 1;
3338 resourceDesc.DepthOrArraySize = 1;
3339 resourceDesc.MipLevels = 1;
3340 resourceDesc.Format = DXGI_FORMAT_UNKNOWN;
3341 resourceDesc.SampleDesc = { 1, 0 };
3342 resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
3343 resourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
3344 UINT state = heapType == D3D12_HEAP_TYPE_UPLOAD ? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_COPY_DEST;
3345 HRESULT hr = rhi->vma.createResource(heapType,
3346 &resourceDesc,
3347 D3D12_RESOURCE_STATES(state),
3348 nullptr,
3349 &allocation,
3350 __uuidof(ID3D12Resource),
3351 reinterpret_cast<void **>(&resource));
3352 if (FAILED(hr)) {
3353 qWarning("Failed to create buffer for staging area: %s",
3354 qPrintable(QSystemError::windowsComString(hr)));
3355 return false;
3356 }
3357 void *p = nullptr;
3358 hr = resource->Map(0, nullptr, &p);
3359 if (FAILED(hr)) {
3360 qWarning("Failed to map buffer for staging area: %s",
3361 qPrintable(QSystemError::windowsComString(hr)));
3362 destroy();
3363 return false;
3364 }
3365
3366 mem.p = static_cast<quint8 *>(p);
3367 mem.gpuAddr = resource->GetGPUVirtualAddress();
3368 mem.buffer = resource;
3369 mem.bufferOffset = 0;
3370
3371 this->capacity = capacity;
3372 head = 0;
3373
3374 return true;
3375}
3376
3377void QD3D12StagingArea::destroy()
3378{
3379 if (resource) {
3380 resource->Release();
3381 resource = nullptr;
3382 }
3383 if (allocation) {
3384 allocation->Release();
3385 allocation = nullptr;
3386 }
3387 mem = {};
3388}
3389
3390void QD3D12StagingArea::destroyWithDeferredRelease(QD3D12ReleaseQueue *releaseQueue)
3391{
3392 if (resource)
3393 releaseQueue->deferredReleaseResourceAndAllocation(resource, allocation);
3394 mem = {};
3395}
3396
3397QD3D12StagingArea::Allocation QD3D12StagingArea::get(quint32 byteSize)
3398{
3399 const quint32 allocSize = aligned(byteSize, ALIGNMENT);
3400 if (head + allocSize > capacity) {
3401 qWarning("Failed to allocate %u (%u) bytes from staging area of size %u with %u bytes left",
3402 allocSize, byteSize, capacity, remainingCapacity());
3403 return {};
3404 }
3405 const quint32 offset = head;
3406 head += allocSize;
3407 return {
3408 mem.p + offset,
3409 mem.gpuAddr + offset,
3410 mem.buffer,
3411 offset
3412 };
3413}
3414
3415// Can be called inside and outside of begin-endFrame. Removes from the pool
3416// and releases the underlying native resource only in the frames_in_flight'th
3417// beginFrame() counted starting from the next endFrame().
3418void QD3D12ReleaseQueue::deferredReleaseResource(const QD3D12ObjectHandle &handle)
3419{
3420 DeferredReleaseEntry e;
3421 e.handle = handle;
3422 queue.append(e);
3423}
3424
3425void QD3D12ReleaseQueue::deferredReleaseResourceWithViews(const QD3D12ObjectHandle &handle,
3426 QD3D12CpuDescriptorPool *pool,
3427 const QD3D12Descriptor &viewsStart,
3428 int viewCount)
3429{
3430 DeferredReleaseEntry e;
3431 e.type = DeferredReleaseEntry::Resource;
3432 e.handle = handle;
3433 e.poolForViews = pool;
3434 e.viewsStart = viewsStart;
3435 e.viewCount = viewCount;
3436 queue.append(e);
3437}
3438
3439void QD3D12ReleaseQueue::deferredReleasePipeline(const QD3D12ObjectHandle &handle)
3440{
3441 DeferredReleaseEntry e;
3442 e.type = DeferredReleaseEntry::Pipeline;
3443 e.handle = handle;
3444 queue.append(e);
3445}
3446
3447void QD3D12ReleaseQueue::deferredReleaseRootSignature(const QD3D12ObjectHandle &handle)
3448{
3449 DeferredReleaseEntry e;
3450 e.type = DeferredReleaseEntry::RootSignature;
3451 e.handle = handle;
3452 queue.append(e);
3453}
3454
3455void QD3D12ReleaseQueue::deferredReleaseCallback(std::function<void(void*)> callback, void *userData)
3456{
3457 DeferredReleaseEntry e;
3458 e.type = DeferredReleaseEntry::Callback;
3459 e.callback = callback;
3460 e.callbackUserData = userData;
3461 queue.append(e);
3462}
3463
3464void QD3D12ReleaseQueue::deferredReleaseResourceAndAllocation(ID3D12Resource *resource,
3465 D3D12MA::Allocation *allocation)
3466{
3467 DeferredReleaseEntry e;
3468 e.type = DeferredReleaseEntry::ResourceAndAllocation;
3469 e.resourceAndAllocation = { resource, allocation };
3470 queue.append(e);
3471}
3472
3473void QD3D12ReleaseQueue::deferredReleaseDescriptorHeap(ID3D12DescriptorHeap *heap)
3474{
3475 DeferredReleaseEntry e;
3476 e.type = DeferredReleaseEntry::DescriptorHeap;
3477 e.descriptorHeap = heap;
3478 queue.append(e);
3479}
3480
3481void QD3D12ReleaseQueue::deferredReleaseViews(QD3D12CpuDescriptorPool *pool,
3482 const QD3D12Descriptor &viewsStart,
3483 int viewCount)
3484{
3485 DeferredReleaseEntry e;
3486 e.type = DeferredReleaseEntry::Views;
3487 e.poolForViews = pool;
3488 e.viewsStart = viewsStart;
3489 e.viewCount = viewCount;
3490 queue.append(e);
3491}
3492
3493void QD3D12ReleaseQueue::activatePendingDeferredReleaseRequests(int frameSlot)
3494{
3495 for (DeferredReleaseEntry &e : queue) {
3496 if (!e.frameSlotToBeReleasedIn.has_value())
3497 e.frameSlotToBeReleasedIn = frameSlot;
3498 }
3499}
3500
3501void QD3D12ReleaseQueue::executeDeferredReleases(int frameSlot, bool forced)
3502{
3503 qsizetype keepBegin = queue.size();
3504 for (qsizetype i = keepBegin - 1; i >= 0; --i) {
3505 const DeferredReleaseEntry &e(queue[i]);
3506 if (forced || (e.frameSlotToBeReleasedIn.has_value() && e.frameSlotToBeReleasedIn.value() == frameSlot)) {
3507 switch (e.type) {
3508 case DeferredReleaseEntry::Resource:
3509 resourcePool->remove(e.handle);
3510 if (e.poolForViews && e.viewsStart.isValid() && e.viewCount > 0)
3511 e.poolForViews->release(e.viewsStart, e.viewCount);
3512 break;
3513 case DeferredReleaseEntry::Pipeline:
3514 pipelinePool->remove(e.handle);
3515 break;
3516 case DeferredReleaseEntry::RootSignature:
3517 rootSignaturePool->remove(e.handle);
3518 break;
3519 case DeferredReleaseEntry::Callback:
3520 e.callback(e.callbackUserData);
3521 break;
3522 case DeferredReleaseEntry::ResourceAndAllocation:
3523 // order matters: resource first, then the allocation (which
3524 // may be null)
3525 e.resourceAndAllocation.first->Release();
3526 if (e.resourceAndAllocation.second)
3527 e.resourceAndAllocation.second->Release();
3528 break;
3529 case DeferredReleaseEntry::DescriptorHeap:
3530 e.descriptorHeap->Release();
3531 break;
3532 case DeferredReleaseEntry::Views:
3533 e.poolForViews->release(e.viewsStart, e.viewCount);
3534 break;
3535 }
3536 } else if (--keepBegin != i) {
3537 queue[keepBegin] = std::move(queue[i]);
3538 }
3539 }
3540 if (keepBegin)
3541 queue.remove(0, keepBegin);
3542}
3543
3544void QD3D12ReleaseQueue::releaseAll()
3545{
3546 executeDeferredReleases(0, true);
3547}
3548
3549void QD3D12ResourceBarrierGenerator::addTransitionBarrier(const QD3D12ObjectHandle &resourceHandle,
3550 D3D12_RESOURCE_STATES stateAfter)
3551{
3552 if (QD3D12Resource *res = resourcePool->lookupRef(resourceHandle)) {
3553 if (stateAfter != res->state) {
3554 transitionResourceBarriers.append({ resourceHandle, res->state, stateAfter });
3555 res->state = stateAfter;
3556 }
3557 }
3558}
3559
3560void QD3D12ResourceBarrierGenerator::enqueueBufferedTransitionBarriers(QD3D12CommandBuffer *cbD)
3561{
3562 QVarLengthArray<D3D12_RESOURCE_BARRIER, PREALLOC> barriers;
3563 for (const TransitionResourceBarrier &trb : transitionResourceBarriers) {
3564 if (QD3D12Resource *res = resourcePool->lookupRef(trb.resourceHandle)) {
3565 D3D12_RESOURCE_BARRIER barrier = {};
3566 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
3567 barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
3568 barrier.Transition.pResource = res->resource;
3569 barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
3570 barrier.Transition.StateBefore = trb.stateBefore;
3571 barrier.Transition.StateAfter = trb.stateAfter;
3572 barriers.append(barrier);
3573 }
3574 }
3575 transitionResourceBarriers.clear();
3576 if (!barriers.isEmpty())
3577 cbD->cmdList->ResourceBarrier(barriers.count(), barriers.constData());
3578}
3579
3580void QD3D12ResourceBarrierGenerator::enqueueSubresourceTransitionBarrier(QD3D12CommandBuffer *cbD,
3581 const QD3D12ObjectHandle &resourceHandle,
3582 UINT subresource,
3583 D3D12_RESOURCE_STATES stateBefore,
3584 D3D12_RESOURCE_STATES stateAfter)
3585{
3586 if (QD3D12Resource *res = resourcePool->lookupRef(resourceHandle)) {
3587 D3D12_RESOURCE_BARRIER barrier = {};
3588 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
3589 barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
3590 barrier.Transition.pResource = res->resource;
3591 barrier.Transition.Subresource = subresource;
3592 barrier.Transition.StateBefore = stateBefore;
3593 barrier.Transition.StateAfter = stateAfter;
3594 cbD->cmdList->ResourceBarrier(1, &barrier);
3595 }
3596}
3597
3598void QD3D12ResourceBarrierGenerator::enqueueUavBarrier(QD3D12CommandBuffer *cbD,
3599 const QD3D12ObjectHandle &resourceHandle)
3600{
3601 if (QD3D12Resource *res = resourcePool->lookupRef(resourceHandle)) {
3602 D3D12_RESOURCE_BARRIER barrier = {};
3603 barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
3604 barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
3605 barrier.UAV.pResource = res->resource;
3606 cbD->cmdList->ResourceBarrier(1, &barrier);
3607 }
3608}
3609
3610bool QD3D12ShaderVisibleDescriptorHeap::create(ID3D12Device *device,
3611 D3D12_DESCRIPTOR_HEAP_TYPE type,
3612 quint32 perFrameDescriptorCount)
3613{
3614 Q_ASSERT(type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
3615
3616 quint32 size = perFrameDescriptorCount * QD3D12_FRAMES_IN_FLIGHT;
3617
3618 // https://learn.microsoft.com/en-us/windows/win32/direct3d12/hardware-support
3619 const quint32 CBV_SRV_UAV_MAX = 1000000;
3620 const quint32 SAMPLER_MAX = 2048;
3621 if (type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)
3622 size = qMin(size, CBV_SRV_UAV_MAX);
3623 else if (type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)
3624 size = qMin(size, SAMPLER_MAX);
3625
3626 if (!heap.create(device, size, type, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) {
3627 qWarning("Failed to create shader-visible descriptor heap of size %u", size);
3628 return false;
3629 }
3630
3631 perFrameDescriptorCount = size / QD3D12_FRAMES_IN_FLIGHT;
3632 quint32 currentOffsetInDescriptors = 0;
3633 for (int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
3634 perFrameHeapSlice[i].createWithExisting(heap, currentOffsetInDescriptors, perFrameDescriptorCount);
3635 currentOffsetInDescriptors += perFrameDescriptorCount;
3636 }
3637
3638 return true;
3639}
3640
3641void QD3D12ShaderVisibleDescriptorHeap::destroy()
3642{
3643 heap.destroy();
3644}
3645
3646void QD3D12ShaderVisibleDescriptorHeap::destroyWithDeferredRelease(QD3D12ReleaseQueue *releaseQueue)
3647{
3648 heap.destroyWithDeferredRelease(releaseQueue);
3649}
3650
3651static inline std::pair<int, int> mapBinding(int binding, const QD3D12ShaderStageData *sd)
3652{
3653 const QShader::NativeResourceBindingMap &map(sd->nativeResourceBindingMap);
3654 if (map.isEmpty()) {
3655 // An empty map normally means an old qsb that did not generate one,
3656 // hence the 1:1 fallback. But the push constant register is only
3657 // known from qsb versions that always generate the map, so for a
3658 // stage with a push constant block an empty map really means the
3659 // shader has no other resources. Falling back would put a uniform
3660 // buffer at binding 0 on the register reserved for the push constant
3661 // block, and the root signature would fail to build.
3662 if (sd->pushConstantRegister >= 0)
3663 return { -1, -1 };
3664 return { binding, binding }; // assume 1:1 mapping
3665 }
3666
3667 auto it = map.constFind(binding);
3668 if (it != map.cend())
3669 return *it;
3670
3671 // Hitting this path is normal too. It is not given that the resource is
3672 // present in the shaders for all the stages specified by the visibility
3673 // mask in the QRhiShaderResourceBinding.
3674 return { -1, -1 };
3675}
3676
3677void QD3D12ShaderResourceVisitor::visit()
3678{
3679 for (int bindingIdx = 0, bindingCount = srb->m_bindings.count(); bindingIdx != bindingCount; ++bindingIdx) {
3680 const QRhiShaderResourceBinding &b(srb->m_bindings[bindingIdx]);
3681 const QRhiShaderResourceBinding::Data *bd = QRhiImplementation::shaderResourceBindingData(b);
3682
3683 for (int stageIdx = 0; stageIdx < stageCount; ++stageIdx) {
3684 const QD3D12ShaderStageData *sd = &stageData[stageIdx];
3685 if (!sd->valid)
3686 continue;
3687
3688 if (!bd->stage.testFlag(qd3d12_stageToSrb(sd->stage)))
3689 continue;
3690
3691 switch (bd->type()) {
3692 case QRhiShaderResourceBinding::UniformBuffer:
3693 {
3694 const int shaderRegister = mapBinding(bd->binding, sd).first;
3695 if (shaderRegister >= 0 && uniformBuffer)
3696 uniformBuffer(sd->stage, bd->ubuf(), shaderRegister, bd->binding);
3697 }
3698 break;
3699 case QRhiShaderResourceBinding::SampledTexture:
3700 {
3701 Q_ASSERT(bd->stex().count() > 0);
3702 const int textureBaseShaderRegister = mapBinding(bd->binding, sd).first;
3703 const int samplerBaseShaderRegister = mapBinding(bd->binding, sd).second;
3704 if (textureBaseShaderRegister >= 0 && textures)
3705 textures(sd->stage, bd->stex().texSamplers.constData(), bd->stex().count(), textureBaseShaderRegister);
3706 if (samplerBaseShaderRegister >= 0 && samplers)
3707 samplers(sd->stage, bd->stex().texSamplers.constData(), bd->stex().count(), samplerBaseShaderRegister);
3708 }
3709 break;
3710 case QRhiShaderResourceBinding::Texture:
3711 {
3712 Q_ASSERT(bd->stex().count() > 0);
3713 const int baseShaderRegister = mapBinding(bd->binding, sd).first;
3714 if (baseShaderRegister >= 0 && textures)
3715 textures(sd->stage, bd->stex().texSamplers.constData(), bd->stex().count(), baseShaderRegister);
3716 }
3717 break;
3718 case QRhiShaderResourceBinding::Sampler:
3719 {
3720 Q_ASSERT(bd->stex().count() > 0);
3721 const int baseShaderRegister = mapBinding(bd->binding, sd).first;
3722 if (baseShaderRegister >= 0 && samplers)
3723 samplers(sd->stage, bd->stex().texSamplers.constData(), bd->stex().count(), baseShaderRegister);
3724 }
3725 break;
3726 case QRhiShaderResourceBinding::ImageLoad:
3727 {
3728 const int shaderRegister = mapBinding(bd->binding, sd).first;
3729 if (shaderRegister >= 0 && storageImage)
3730 storageImage(sd->stage, bd->simage(), Load, shaderRegister);
3731 }
3732 break;
3733 case QRhiShaderResourceBinding::ImageStore:
3734 {
3735 const int shaderRegister = mapBinding(bd->binding, sd).first;
3736 if (shaderRegister >= 0 && storageImage)
3737 storageImage(sd->stage, bd->simage(), Store, shaderRegister);
3738 }
3739 break;
3740 case QRhiShaderResourceBinding::ImageLoadStore:
3741 {
3742 const int shaderRegister = mapBinding(bd->binding, sd).first;
3743 if (shaderRegister >= 0 && storageImage)
3744 storageImage(sd->stage, bd->simage(), LoadStore, shaderRegister);
3745 }
3746 break;
3747 case QRhiShaderResourceBinding::BufferLoad:
3748 {
3749 const int shaderRegister = mapBinding(bd->binding, sd).first;
3750 if (shaderRegister >= 0 && storageBuffer)
3751 storageBuffer(sd->stage, bd->sbuf(), Load, shaderRegister);
3752 }
3753 break;
3754 case QRhiShaderResourceBinding::BufferStore:
3755 {
3756 const int shaderRegister = mapBinding(bd->binding, sd).first;
3757 if (shaderRegister >= 0 && storageBuffer)
3758 storageBuffer(sd->stage, bd->sbuf(), Store, shaderRegister);
3759 }
3760 break;
3761 case QRhiShaderResourceBinding::BufferLoadStore:
3762 {
3763 const int shaderRegister = mapBinding(bd->binding, sd).first;
3764 if (shaderRegister >= 0 && storageBuffer)
3765 storageBuffer(sd->stage, bd->sbuf(), LoadStore, shaderRegister);
3766 }
3767 break;
3768 }
3769 }
3770 }
3771}
3772
3773bool QD3D12SamplerManager::create(ID3D12Device *device)
3774{
3775 // This does not need to be per-frame slot, just grab space for MAX_SAMPLERS samplers.
3776 if (!shaderVisibleSamplerHeap.create(device,
3777 D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
3778 MAX_SAMPLERS / QD3D12_FRAMES_IN_FLIGHT))
3779 {
3780 qWarning("Could not create shader-visible SAMPLER heap");
3781 return false;
3782 }
3783
3784 this->device = device;
3785 return true;
3786}
3787
3788void QD3D12SamplerManager::destroy()
3789{
3790 if (device) {
3791 shaderVisibleSamplerHeap.destroy();
3792 device = nullptr;
3793 }
3794}
3795
3796QD3D12Descriptor QD3D12SamplerManager::getShaderVisibleDescriptor(const D3D12_SAMPLER_DESC &desc)
3797{
3798 auto it = gpuMap.constFind({desc});
3799 if (it != gpuMap.cend())
3800 return *it;
3801
3802 QD3D12Descriptor descriptor = shaderVisibleSamplerHeap.heap.get(1);
3803 if (descriptor.isValid()) {
3804 device->CreateSampler(&desc, descriptor.cpuHandle);
3805 gpuMap.insert({desc}, descriptor);
3806 } else {
3807 qWarning("Out of shader-visible SAMPLER descriptor heap space,"
3808 " this should not happen, maximum number of unique samplers is %u",
3809 shaderVisibleSamplerHeap.heap.capacity);
3810 }
3811
3812 return descriptor;
3813}
3814
3815QD3D12Descriptor QD3D12SamplerManager::getShaderVisibleDescriptors(const QVarLengthArray<Q_D3D12_SAMPLER_DESC, 8> &descs)
3816{
3817 // Deliberately keyed on the sampler descriptions, not on the QRhiSampler
3818 // objects: an array of samplers with the same combination of filtering and
3819 // addressing modes can share one descriptor run, however many
3820 // QRhiShaderResourceBindings reference it.
3821 auto it = gpuArrayMap.constFind({ descs });
3822 if (it != gpuArrayMap.cend())
3823 return *it;
3824
3825 const quint32 count = quint32(descs.count());
3826 QD3D12Descriptor startDescriptor = shaderVisibleSamplerHeap.heap.get(count);
3827 if (startDescriptor.isValid()) {
3828 for (quint32 i = 0; i < count; ++i) {
3829 device->CreateSampler(&descs[int(i)].desc,
3830 shaderVisibleSamplerHeap.heap.incremented(startDescriptor, i).cpuHandle);
3831 }
3832 gpuArrayMap.insert({ descs }, startDescriptor);
3833 } else {
3834 // Not inserting anything into the map on failure, so this is retried
3835 // (and warns again) on every setShaderResources() with this binding.
3836 // Same as the single sampler case above, and preferable to caching the
3837 // invalid descriptor, which would keep binding a null descriptor table
3838 // without saying anything about it.
3839 qWarning("Out of shader-visible SAMPLER descriptor heap space when reserving"
3840 " %u consecutive descriptors for a sampler array, maximum number of"
3841 " sampler descriptors is %u",
3842 count, shaderVisibleSamplerHeap.heap.capacity);
3843 }
3844
3845 return startDescriptor;
3846}
3847
3848void QD3D12MipmapGenerator::create(QRhiD3D12 *rhiD)
3849{
3850 this->rhiD = rhiD;
3851}
3852
3853bool QD3D12MipmapGenerator::ensureCreated()
3854{
3855 if (!pipelineHandle.isNull())
3856 return true;
3857
3858 if (createFailed)
3859 return false;
3860
3861 if (!buildPipeline()) {
3862 createFailed = true;
3863 return false;
3864 }
3865
3866 return true;
3867}
3868
3869bool QD3D12MipmapGenerator::buildPipeline()
3870{
3871 qCDebug(QRHI_LOG_INFO, "Building mipmap generator compute pipeline on first use");
3872
3873 D3D12_ROOT_PARAMETER1 rootParams[3] = {};
3874 D3D12_DESCRIPTOR_RANGE1 descriptorRanges[2] = {};
3875
3876 // b0
3877 rootParams[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
3878 rootParams[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
3879 rootParams[0].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC;
3880
3881 // t0
3882 descriptorRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
3883 descriptorRanges[0].NumDescriptors = 1;
3884 descriptorRanges[0].Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;
3885 rootParams[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
3886 rootParams[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
3887 rootParams[1].DescriptorTable.NumDescriptorRanges = 1;
3888 rootParams[1].DescriptorTable.pDescriptorRanges = &descriptorRanges[0];
3889
3890 // u0..3
3891 descriptorRanges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
3892 descriptorRanges[1].NumDescriptors = 4;
3893 rootParams[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
3894 rootParams[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
3895 rootParams[2].DescriptorTable.NumDescriptorRanges = 1;
3896 rootParams[2].DescriptorTable.pDescriptorRanges = &descriptorRanges[1];
3897
3898 // s0
3899 D3D12_STATIC_SAMPLER_DESC samplerDesc = {};
3900 samplerDesc.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT;
3901 samplerDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
3902 samplerDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
3903 samplerDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
3904 samplerDesc.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
3905
3906 D3D12_VERSIONED_ROOT_SIGNATURE_DESC rsDesc = {};
3907 rsDesc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
3908 rsDesc.Desc_1_1.NumParameters = 3;
3909 rsDesc.Desc_1_1.pParameters = rootParams;
3910 rsDesc.Desc_1_1.NumStaticSamplers = 1;
3911 rsDesc.Desc_1_1.pStaticSamplers = &samplerDesc;
3912
3913 ID3DBlob *signature = nullptr;
3914 HRESULT hr = D3D12SerializeVersionedRootSignature(&rsDesc, &signature, nullptr);
3915 if (FAILED(hr)) {
3916 qWarning("Failed to serialize root signature: %s", qPrintable(QSystemError::windowsComString(hr)));
3917 return false;
3918 }
3919 ID3D12RootSignature *rootSig = nullptr;
3920 hr = rhiD->dev->CreateRootSignature(0,
3921 signature->GetBufferPointer(),
3922 signature->GetBufferSize(),
3923 __uuidof(ID3D12RootSignature),
3924 reinterpret_cast<void **>(&rootSig));
3925 signature->Release();
3926 if (FAILED(hr)) {
3927 qWarning("Failed to create root signature: %s",
3928 qPrintable(QSystemError::windowsComString(hr)));
3929 return false;
3930 }
3931
3932 rootSigHandle = QD3D12RootSignature::addToPool(&rhiD->rootSignaturePool, rootSig);
3933
3934 D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = {};
3935 psoDesc.pRootSignature = rootSig;
3936 psoDesc.CS.pShaderBytecode = g_csMipmap;
3937 psoDesc.CS.BytecodeLength = sizeof(g_csMipmap);
3938 ID3D12PipelineState *pso = nullptr;
3939 hr = rhiD->dev->CreateComputePipelineState(&psoDesc,
3940 __uuidof(ID3D12PipelineState),
3941 reinterpret_cast<void **>(&pso));
3942 if (FAILED(hr)) {
3943 qWarning("Failed to create compute pipeline state: %s",
3944 qPrintable(QSystemError::windowsComString(hr)));
3945 rhiD->rootSignaturePool.remove(rootSigHandle);
3946 rootSigHandle = {};
3947 return false;
3948 }
3949
3950 pipelineHandle = QD3D12Pipeline::addToPool(&rhiD->pipelinePool, QD3D12Pipeline::Compute, pso);
3951
3952 return true;
3953}
3954
3955void QD3D12MipmapGenerator::destroy()
3956{
3957 // Be safe even if create() was never called due to other failures in the
3958 // init sequence.
3959 if (!rhiD)
3960 return;
3961
3962 rhiD->pipelinePool.remove(pipelineHandle);
3963 pipelineHandle = {};
3964 rhiD->rootSignaturePool.remove(rootSigHandle);
3965 rootSigHandle = {};
3966 createFailed = false;
3967}
3968
3969void QD3D12MipmapGenerator::generate(QD3D12CommandBuffer *cbD, const QD3D12ObjectHandle &textureHandle)
3970{
3971 if (!ensureCreated())
3972 return;
3973
3974 QD3D12Pipeline *pipeline = rhiD->pipelinePool.lookupRef(pipelineHandle);
3975 if (!pipeline)
3976 return;
3977 QD3D12RootSignature *rootSig = rhiD->rootSignaturePool.lookupRef(rootSigHandle);
3978 if (!rootSig)
3979 return;
3980 QD3D12Resource *res = rhiD->resourcePool.lookupRef(textureHandle);
3981 if (!res)
3982 return;
3983
3984 const quint32 mipLevelCount = res->desc.MipLevels;
3985 if (mipLevelCount < 2)
3986 return;
3987
3988 if (res->desc.SampleDesc.Count > 1) {
3989 qWarning("Cannot generate mipmaps for MSAA texture");
3990 return;
3991 }
3992
3993 const bool is1D = res->desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D;
3994 if (is1D) {
3995 qWarning("Cannot generate mipmaps for 1D texture");
3996 return;
3997 }
3998
3999 const bool is3D = res->desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D;
4000 const bool isCubeOrArray = res->desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D
4001 && res->desc.DepthOrArraySize > 1;
4002 const quint32 layerCount = isCubeOrArray ? res->desc.DepthOrArraySize : 1;
4003
4004 if (is3D) {
4005 qWarning("2D mipmap generator invoked for 3D texture, this should not happen");
4006 return;
4007 }
4008
4009 rhiD->barrierGen.addTransitionBarrier(textureHandle, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
4010 rhiD->barrierGen.enqueueBufferedTransitionBarriers(cbD);
4011
4012 cbD->cmdList->SetPipelineState(pipeline->pso);
4013 cbD->cmdList->SetComputeRootSignature(rootSig->rootSig);
4014
4015 const quint32 descriptorByteSize = rhiD->shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[rhiD->currentFrameSlot].descriptorByteSize;
4016
4017 struct CBufData {
4018 quint32 srcMipLevel;
4019 quint32 numMipLevels;
4020 float texelWidth;
4021 float texelHeight;
4022 };
4023
4024 const quint32 allocSize = QD3D12StagingArea::allocSizeForArray(sizeof(CBufData), mipLevelCount * layerCount);
4025 std::optional<QD3D12StagingArea> ownStagingArea;
4026 rhiD->recordSmallStagingAreaDemand(allocSize);
4027 if (rhiD->smallStagingAreas[rhiD->currentFrameSlot].remainingCapacity() < allocSize) {
4028 ownStagingArea = QD3D12StagingArea();
4029 if (!ownStagingArea->create(rhiD, allocSize, D3D12_HEAP_TYPE_UPLOAD)) {
4030 qWarning("Could not create staging area for mipmap generation");
4031 return;
4032 }
4033 }
4034 QD3D12StagingArea *workArea = ownStagingArea.has_value()
4035 ? &ownStagingArea.value()
4036 : &rhiD->smallStagingAreas[rhiD->currentFrameSlot];
4037
4038 bool gotNewHeap = false;
4039 if (!rhiD->ensureShaderVisibleDescriptorHeapCapacity(&rhiD->shaderVisibleCbvSrvUavHeap,
4040 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
4041 rhiD->currentFrameSlot,
4042 (1 + 4) * mipLevelCount * layerCount,
4043 &gotNewHeap))
4044 {
4045 qWarning("Could not ensure enough space in descriptor heap for mipmap generation");
4046 return;
4047 }
4048 if (gotNewHeap)
4049 rhiD->bindShaderVisibleHeaps(cbD);
4050
4051 for (quint32 layer = 0; layer < layerCount; ++layer) {
4052 // the last level is only written, never a source
4053 for (quint32 level = 0; level + 1 < mipLevelCount ;) {
4054 UINT subresource = calcSubresource(level, layer, res->desc.MipLevels);
4055 rhiD->barrierGen.enqueueSubresourceTransitionBarrier(cbD, textureHandle, subresource,
4056 D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
4057 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
4058
4059 quint32 levelPlusOneMipWidth = res->desc.Width >> (level + 1);
4060 quint32 levelPlusOneMipHeight = res->desc.Height >> (level + 1);
4061 const quint32 dw = levelPlusOneMipWidth == 1 ? levelPlusOneMipHeight : levelPlusOneMipWidth;
4062 const quint32 dh = levelPlusOneMipHeight == 1 ? levelPlusOneMipWidth : levelPlusOneMipHeight;
4063 // number of times the size can be halved while still resulting in an even dimension
4064 const quint32 additionalMips = qCountTrailingZeroBits(dw | dh);
4065 const quint32 numGenMips = qMin(1u + qMin(3u, additionalMips), res->desc.MipLevels - 1u - level);
4066 levelPlusOneMipWidth = qMax(1u, levelPlusOneMipWidth);
4067 levelPlusOneMipHeight = qMax(1u, levelPlusOneMipHeight);
4068
4069 // The view exposes only the source level, as the other levels
4070 // are in the unordered access state, so the source is at LOD 0.
4071 CBufData cbufData = {
4072 0,
4073 numGenMips,
4074 1.0f / float(levelPlusOneMipWidth),
4075 1.0f / float(levelPlusOneMipHeight)
4076 };
4077
4078 QD3D12StagingArea::Allocation cbuf = workArea->get(sizeof(cbufData));
4079 memcpy(cbuf.p, &cbufData, sizeof(cbufData));
4080 cbD->cmdList->SetComputeRootConstantBufferView(0, cbuf.gpuAddr);
4081
4082 QD3D12Descriptor srv = rhiD->shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[rhiD->currentFrameSlot].get(1);
4083 D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
4084 srvDesc.Format = res->desc.Format;
4085 srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
4086 if (isCubeOrArray) {
4087 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
4088 srvDesc.Texture2DArray.MostDetailedMip = level;
4089 srvDesc.Texture2DArray.MipLevels = 1;
4090 srvDesc.Texture2DArray.FirstArraySlice = layer;
4091 srvDesc.Texture2DArray.ArraySize = 1;
4092 } else {
4093 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
4094 srvDesc.Texture2D.MostDetailedMip = level;
4095 srvDesc.Texture2D.MipLevels = 1;
4096 }
4097 rhiD->dev->CreateShaderResourceView(res->resource, &srvDesc, srv.cpuHandle);
4098 cbD->cmdList->SetComputeRootDescriptorTable(1, srv.gpuHandle);
4099
4100 QD3D12Descriptor uavStart = rhiD->shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[rhiD->currentFrameSlot].get(4);
4101 D3D12_CPU_DESCRIPTOR_HANDLE uavCpuHandle = uavStart.cpuHandle;
4102 // if level is N, then need UAVs for levels N+1, ..., N+4
4103 for (quint32 uavIdx = 0; uavIdx < 4; ++uavIdx) {
4104 const quint32 uavMipLevel = qMin(level + 1u + uavIdx, res->desc.MipLevels - 1u);
4105 D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
4106 uavDesc.Format = res->desc.Format;
4107 if (isCubeOrArray) {
4108 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
4109 uavDesc.Texture2DArray.MipSlice = uavMipLevel;
4110 uavDesc.Texture2DArray.FirstArraySlice = layer;
4111 uavDesc.Texture2DArray.ArraySize = 1;
4112 } else {
4113 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
4114 uavDesc.Texture2D.MipSlice = uavMipLevel;
4115 }
4116 rhiD->dev->CreateUnorderedAccessView(res->resource, nullptr, &uavDesc, uavCpuHandle);
4117 uavCpuHandle.ptr += descriptorByteSize;
4118 }
4119 cbD->cmdList->SetComputeRootDescriptorTable(2, uavStart.gpuHandle);
4120
4121 cbD->cmdList->Dispatch(levelPlusOneMipWidth, levelPlusOneMipHeight, 1);
4122
4123 rhiD->barrierGen.enqueueUavBarrier(cbD, textureHandle);
4124 rhiD->barrierGen.enqueueSubresourceTransitionBarrier(cbD, textureHandle, subresource,
4125 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
4126 D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
4127
4128 level += numGenMips;
4129 }
4130 }
4131
4132 if (ownStagingArea.has_value())
4133 ownStagingArea->destroyWithDeferredRelease(&rhiD->releaseQueue);
4134}
4135
4136void QD3D12MipmapGenerator3D::create(QRhiD3D12 *rhiD)
4137{
4138 this->rhiD = rhiD;
4139}
4140
4141bool QD3D12MipmapGenerator3D::ensureCreated()
4142{
4143 if (!pipelineHandle.isNull())
4144 return true;
4145
4146 if (createFailed)
4147 return false;
4148
4149 if (!buildPipeline()) {
4150 createFailed = true;
4151 return false;
4152 }
4153
4154 return true;
4155}
4156
4157bool QD3D12MipmapGenerator3D::buildPipeline()
4158{
4159 qCDebug(QRHI_LOG_INFO, "Building 3D texture mipmap generator compute pipeline on first use");
4160
4161 D3D12_ROOT_PARAMETER1 rootParams[3] = {};
4162 D3D12_DESCRIPTOR_RANGE1 descriptorRanges[2] = {};
4163
4164 // b0
4165 rootParams[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
4166 rootParams[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
4167 rootParams[0].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC;
4168
4169 // t0
4170 descriptorRanges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
4171 descriptorRanges[0].NumDescriptors = 1;
4172 descriptorRanges[0].Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;
4173 rootParams[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
4174 rootParams[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
4175 rootParams[1].DescriptorTable.NumDescriptorRanges = 1;
4176 rootParams[1].DescriptorTable.pDescriptorRanges = &descriptorRanges[0];
4177
4178 // u0
4179 descriptorRanges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
4180 descriptorRanges[1].NumDescriptors = 1;
4181 rootParams[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
4182 rootParams[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
4183 rootParams[2].DescriptorTable.NumDescriptorRanges = 1;
4184 rootParams[2].DescriptorTable.pDescriptorRanges = &descriptorRanges[1];
4185
4186 // s0
4187 D3D12_STATIC_SAMPLER_DESC samplerDesc = {};
4188 samplerDesc.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT;
4189 samplerDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
4190 samplerDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
4191 samplerDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
4192 samplerDesc.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
4193
4194 D3D12_VERSIONED_ROOT_SIGNATURE_DESC rsDesc = {};
4195 rsDesc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
4196 rsDesc.Desc_1_1.NumParameters = 3;
4197 rsDesc.Desc_1_1.pParameters = rootParams;
4198 rsDesc.Desc_1_1.NumStaticSamplers = 1;
4199 rsDesc.Desc_1_1.pStaticSamplers = &samplerDesc;
4200
4201 ID3DBlob *signature = nullptr;
4202 HRESULT hr = D3D12SerializeVersionedRootSignature(&rsDesc, &signature, nullptr);
4203 if (FAILED(hr)) {
4204 qWarning("Failed to serialize root signature: %s", qPrintable(QSystemError::windowsComString(hr)));
4205 return false;
4206 }
4207 ID3D12RootSignature *rootSig = nullptr;
4208 hr = rhiD->dev->CreateRootSignature(0,
4209 signature->GetBufferPointer(),
4210 signature->GetBufferSize(),
4211 __uuidof(ID3D12RootSignature),
4212 reinterpret_cast<void **>(&rootSig));
4213 signature->Release();
4214 if (FAILED(hr)) {
4215 qWarning("Failed to create root signature: %s",
4216 qPrintable(QSystemError::windowsComString(hr)));
4217 return false;
4218 }
4219
4220 rootSigHandle = QD3D12RootSignature::addToPool(&rhiD->rootSignaturePool, rootSig);
4221
4222 D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = {};
4223 psoDesc.pRootSignature = rootSig;
4224 psoDesc.CS.pShaderBytecode = g_csMipmap3D;
4225 psoDesc.CS.BytecodeLength = sizeof(g_csMipmap3D);
4226 ID3D12PipelineState *pso = nullptr;
4227 hr = rhiD->dev->CreateComputePipelineState(&psoDesc,
4228 __uuidof(ID3D12PipelineState),
4229 reinterpret_cast<void **>(&pso));
4230 if (FAILED(hr)) {
4231 qWarning("Failed to create compute pipeline state: %s",
4232 qPrintable(QSystemError::windowsComString(hr)));
4233 rhiD->rootSignaturePool.remove(rootSigHandle);
4234 rootSigHandle = {};
4235 return false;
4236 }
4237
4238 pipelineHandle = QD3D12Pipeline::addToPool(&rhiD->pipelinePool, QD3D12Pipeline::Compute, pso);
4239
4240 return true;
4241}
4242
4243void QD3D12MipmapGenerator3D::destroy()
4244{
4245 if (!rhiD)
4246 return;
4247
4248 rhiD->pipelinePool.remove(pipelineHandle);
4249 pipelineHandle = {};
4250 rhiD->rootSignaturePool.remove(rootSigHandle);
4251 rootSigHandle = {};
4252 createFailed = false;
4253}
4254
4255void QD3D12MipmapGenerator3D::generate(QD3D12CommandBuffer *cbD, const QD3D12ObjectHandle &textureHandle)
4256{
4257 if (!ensureCreated())
4258 return;
4259
4260 QD3D12Pipeline *pipeline = rhiD->pipelinePool.lookupRef(pipelineHandle);
4261 if (!pipeline)
4262 return;
4263 QD3D12RootSignature *rootSig = rhiD->rootSignaturePool.lookupRef(rootSigHandle);
4264 if (!rootSig)
4265 return;
4266 QD3D12Resource *res = rhiD->resourcePool.lookupRef(textureHandle);
4267 if (!res)
4268 return;
4269
4270 const quint32 mipLevelCount = res->desc.MipLevels;
4271 if (mipLevelCount < 2)
4272 return;
4273
4274 const bool is3D = res->desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D;
4275 if (!is3D) {
4276 qWarning("3D mipmap generator invoked for non-3D texture, this should not happen");
4277 return;
4278 }
4279
4280 rhiD->barrierGen.addTransitionBarrier(textureHandle, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
4281 rhiD->barrierGen.enqueueBufferedTransitionBarriers(cbD);
4282
4283 cbD->cmdList->SetPipelineState(pipeline->pso);
4284 cbD->cmdList->SetComputeRootSignature(rootSig->rootSig);
4285
4286 const quint32 descriptorByteSize = rhiD->shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[rhiD->currentFrameSlot].descriptorByteSize;
4287
4288 struct CBufData {
4289 float texelWidth;
4290 float texelHeight;
4291 float texelDepth;
4292 quint32 srcMipLevel;
4293 };
4294
4295 const quint32 allocSize = QD3D12StagingArea::allocSizeForArray(sizeof(CBufData), mipLevelCount);
4296 std::optional<QD3D12StagingArea> ownStagingArea;
4297 rhiD->recordSmallStagingAreaDemand(allocSize);
4298 if (rhiD->smallStagingAreas[rhiD->currentFrameSlot].remainingCapacity() < allocSize) {
4299 ownStagingArea = QD3D12StagingArea();
4300 if (!ownStagingArea->create(rhiD, allocSize, D3D12_HEAP_TYPE_UPLOAD)) {
4301 qWarning("Could not create staging area for mipmap generation");
4302 return;
4303 }
4304 }
4305 QD3D12StagingArea *workArea = ownStagingArea.has_value()
4306 ? &ownStagingArea.value()
4307 : &rhiD->smallStagingAreas[rhiD->currentFrameSlot];
4308
4309 bool gotNewHeap = false;
4310 if (!rhiD->ensureShaderVisibleDescriptorHeapCapacity(&rhiD->shaderVisibleCbvSrvUavHeap,
4311 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
4312 rhiD->currentFrameSlot,
4313 (1 + 1) * mipLevelCount, // 1 SRV + 1 UAV
4314 &gotNewHeap))
4315 {
4316 qWarning("Could not ensure enough space in descriptor heap for mipmap generation");
4317 return;
4318 }
4319 if (gotNewHeap)
4320 rhiD->bindShaderVisibleHeaps(cbD);
4321
4322 // the last level is only written, never a source
4323 for (quint32 level = 0; level + 1 < mipLevelCount; ++level) {
4324 UINT subresource = calcSubresource(level, 0u, res->desc.MipLevels);
4325 rhiD->barrierGen.enqueueSubresourceTransitionBarrier(cbD, textureHandle, subresource,
4326 D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
4327 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
4328
4329 quint32 levelPlusOneMipWidth = qMax<quint32>(1, res->desc.Width >> (level + 1));
4330 quint32 levelPlusOneMipHeight = qMax<quint32>(1, res->desc.Height >> (level + 1));
4331 quint32 levelPlusOneMipDepth = qMax<quint32>(1, res->desc.DepthOrArraySize >> (level + 1));
4332
4333 // The view exposes only the source level, as the other levels are in
4334 // the unordered access state, so the source is at LOD 0.
4335 CBufData cbufData = {
4336 1.0f / float(levelPlusOneMipWidth),
4337 1.0f / float(levelPlusOneMipHeight),
4338 1.0f / float(levelPlusOneMipDepth),
4339 0
4340 };
4341
4342 QD3D12StagingArea::Allocation cbuf = workArea->get(sizeof(cbufData));
4343 memcpy(cbuf.p, &cbufData, sizeof(cbufData));
4344 cbD->cmdList->SetComputeRootConstantBufferView(0, cbuf.gpuAddr);
4345
4346 QD3D12Descriptor srv = rhiD->shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[rhiD->currentFrameSlot].get(1);
4347 D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
4348 srvDesc.Format = res->desc.Format;
4349 srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
4350 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D;
4351 srvDesc.Texture3D.MostDetailedMip = level;
4352 srvDesc.Texture3D.MipLevels = 1;
4353
4354 rhiD->dev->CreateShaderResourceView(res->resource, &srvDesc, srv.cpuHandle);
4355 cbD->cmdList->SetComputeRootDescriptorTable(1, srv.gpuHandle);
4356
4357 QD3D12Descriptor uavStart = rhiD->shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[rhiD->currentFrameSlot].get(1);
4358 D3D12_CPU_DESCRIPTOR_HANDLE uavCpuHandle = uavStart.cpuHandle;
4359 const quint32 uavMipLevel = qMin(level + 1u, res->desc.MipLevels - 1u);
4360 D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
4361 uavDesc.Format = res->desc.Format;
4362 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
4363 uavDesc.Texture3D.MipSlice = uavMipLevel;
4364 uavDesc.Texture3D.WSize = UINT(-1);
4365 rhiD->dev->CreateUnorderedAccessView(res->resource, nullptr, &uavDesc, uavCpuHandle);
4366 uavCpuHandle.ptr += descriptorByteSize;
4367 cbD->cmdList->SetComputeRootDescriptorTable(2, uavStart.gpuHandle);
4368
4369 cbD->cmdList->Dispatch(levelPlusOneMipWidth, levelPlusOneMipHeight, levelPlusOneMipDepth);
4370
4371 rhiD->barrierGen.enqueueUavBarrier(cbD, textureHandle);
4372 rhiD->barrierGen.enqueueSubresourceTransitionBarrier(cbD, textureHandle, subresource,
4373 D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
4374 D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
4375 }
4376
4377 if (ownStagingArea.has_value())
4378 ownStagingArea->destroyWithDeferredRelease(&rhiD->releaseQueue);
4379}
4380
4381bool QD3D12MemoryAllocator::create(ID3D12Device *device, IDXGIAdapter1 *adapter)
4382{
4383 this->device = device;
4384
4385 // We can function with and without D3D12MA: CreateCommittedResource is
4386 // just fine for our purposes and not any complicated API-wise; the memory
4387 // allocator is interesting for efficiency mainly since it can suballocate
4388 // instead of making everything a committed resource allocation.
4389
4390 static bool disableMA = qEnvironmentVariableIntValue("QT_D3D_NO_SUBALLOC");
4391 if (disableMA)
4392 return true;
4393
4394 DXGI_ADAPTER_DESC1 desc;
4395 adapter->GetDesc1(&desc);
4396 if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
4397 return true;
4398
4399 D3D12MA::ALLOCATOR_DESC allocatorDesc = {};
4400 allocatorDesc.pDevice = device;
4401 allocatorDesc.pAdapter = adapter;
4402 // A QRhi is supposed to be used from one single thread only. Disable
4403 // the allocator's own mutexes. This may give a performance boost.
4404 allocatorDesc.Flags = D3D12MA::ALLOCATOR_FLAG_SINGLETHREADED;
4405 HRESULT hr = D3D12MA::CreateAllocator(&allocatorDesc, &allocator);
4406 if (FAILED(hr)) {
4407 qWarning("Failed to initialize D3D12 Memory Allocator: %s",
4408 qPrintable(QSystemError::windowsComString(hr)));
4409 return false;
4410 }
4411 return true;
4412}
4413
4414void QD3D12MemoryAllocator::destroy()
4415{
4416 if (allocator) {
4417 allocator->Release();
4418 allocator = nullptr;
4419 }
4420}
4421
4422HRESULT QD3D12MemoryAllocator::createResource(D3D12_HEAP_TYPE heapType,
4423 const D3D12_RESOURCE_DESC *resourceDesc,
4424 D3D12_RESOURCE_STATES initialState,
4425 const D3D12_CLEAR_VALUE *optimizedClearValue,
4426 D3D12MA::Allocation **maybeAllocation,
4427 REFIID riidResource,
4428 void **ppvResource)
4429{
4430 if (allocator) {
4431 D3D12MA::ALLOCATION_DESC allocDesc = {};
4432 allocDesc.HeapType = heapType;
4433 return allocator->CreateResource(&allocDesc,
4434 resourceDesc,
4435 initialState,
4436 optimizedClearValue,
4437 maybeAllocation,
4438 riidResource,
4439 ppvResource);
4440 } else {
4441 *maybeAllocation = nullptr;
4442 D3D12_HEAP_PROPERTIES heapProps = {};
4443 heapProps.Type = heapType;
4444 return device->CreateCommittedResource(&heapProps,
4445 D3D12_HEAP_FLAG_NONE,
4446 resourceDesc,
4447 initialState,
4448 optimizedClearValue,
4449 riidResource,
4450 ppvResource);
4451 }
4452}
4453
4454void QD3D12MemoryAllocator::getBudget(D3D12MA::Budget *localBudget, D3D12MA::Budget *nonLocalBudget)
4455{
4456 if (allocator) {
4457 allocator->GetBudget(localBudget, nonLocalBudget);
4458 } else {
4459 *localBudget = {};
4460 *nonLocalBudget = {};
4461 }
4462}
4463
4464void QRhiD3D12::waitGpu()
4465{
4466 fullFenceCounter += 1u;
4467 if (SUCCEEDED(cmdQueue->Signal(fullFence, fullFenceCounter))) {
4468 if (SUCCEEDED(fullFence->SetEventOnCompletion(fullFenceCounter, fullFenceEvent)))
4469 WaitForSingleObject(fullFenceEvent, INFINITE);
4470 }
4471}
4472
4473DXGI_SAMPLE_DESC QRhiD3D12::effectiveSampleDesc(int sampleCount, DXGI_FORMAT format) const
4474{
4475 DXGI_SAMPLE_DESC desc;
4476 desc.Count = 1;
4477 desc.Quality = 0;
4478
4479 const int s = effectiveSampleCount(sampleCount);
4480
4481 if (s > 1) {
4482 D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS msaaInfo = {};
4483 msaaInfo.Format = format;
4484 msaaInfo.SampleCount = UINT(s);
4485 if (SUCCEEDED(dev->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &msaaInfo, sizeof(msaaInfo)))) {
4486 if (msaaInfo.NumQualityLevels > 0) {
4487 desc.Count = UINT(s);
4488 desc.Quality = msaaInfo.NumQualityLevels - 1;
4489 } else {
4490 qWarning("No quality levels for multisampling with sample count %d", s);
4491 }
4492 }
4493 }
4494
4495 return desc;
4496}
4497
4498bool QRhiD3D12::startCommandListForCurrentFrameSlot(D3D12GraphicsCommandList **cmdList)
4499{
4500 ID3D12CommandAllocator *cmdAlloc = cmdAllocators[currentFrameSlot];
4501 if (!*cmdList) {
4502 HRESULT hr = dev->CreateCommandList(0,
4503 D3D12_COMMAND_LIST_TYPE_DIRECT,
4504 cmdAlloc,
4505 nullptr,
4506 __uuidof(D3D12GraphicsCommandList),
4507 reinterpret_cast<void **>(cmdList));
4508 if (FAILED(hr)) {
4509 qWarning("Failed to create command list: %s", qPrintable(QSystemError::windowsComString(hr)));
4510 return false;
4511 }
4512 } else {
4513 HRESULT hr = (*cmdList)->Reset(cmdAlloc, nullptr);
4514 if (FAILED(hr)) {
4515 qWarning("Failed to reset command list: %s", qPrintable(QSystemError::windowsComString(hr)));
4516 return false;
4517 }
4518 }
4519 return true;
4520}
4521
4522static inline QRhiTexture::Format swapchainReadbackTextureFormat(DXGI_FORMAT format, QRhiTexture::Flags *flags)
4523{
4524 switch (format) {
4525 case DXGI_FORMAT_R8G8B8A8_UNORM:
4526 return QRhiTexture::RGBA8;
4527 case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
4528 if (flags)
4529 (*flags) |= QRhiTexture::sRGB;
4530 return QRhiTexture::RGBA8;
4531 case DXGI_FORMAT_B8G8R8A8_UNORM:
4532 return QRhiTexture::BGRA8;
4533 case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
4534 if (flags)
4535 (*flags) |= QRhiTexture::sRGB;
4536 return QRhiTexture::BGRA8;
4537 case DXGI_FORMAT_R16G16B16A16_FLOAT:
4538 return QRhiTexture::RGBA16F;
4539 case DXGI_FORMAT_R32G32B32A32_FLOAT:
4540 return QRhiTexture::RGBA32F;
4541 case DXGI_FORMAT_R10G10B10A2_UNORM:
4542 return QRhiTexture::RGB10A2;
4543 default:
4544 qWarning("DXGI_FORMAT %d cannot be read back", format);
4545 break;
4546 }
4547 return QRhiTexture::UnknownFormat;
4548}
4549
4550static inline bool isDepthTextureFormat(QRhiTexture::Format format)
4551{
4552 switch (format) {
4553 case QRhiTexture::Format::D16:
4554 case QRhiTexture::Format::D24:
4555 case QRhiTexture::Format::D24S8:
4556 case QRhiTexture::Format::D32F:
4557 case QRhiTexture::Format::D32FS8:
4558 return true;
4559 default:
4560 return false;
4561 }
4562}
4563
4564void QRhiD3D12::enqueueResourceUpdates(QD3D12CommandBuffer *cbD, QRhiResourceUpdateBatch *resourceUpdates)
4565{
4566 QRhiResourceUpdateBatchPrivate *ud = QRhiResourceUpdateBatchPrivate::get(resourceUpdates);
4567
4568 for (int opIdx = 0; opIdx < ud->activeBufferOpCount; ++opIdx) {
4569 const QRhiResourceUpdateBatchPrivate::BufferOp &u(ud->bufferOps[opIdx]);
4570 if (u.type == QRhiResourceUpdateBatchPrivate::BufferOp::DynamicUpdate) {
4571 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, u.buf);
4572 Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
4573 for (int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
4574 if (u.offset == 0 && u.data.size() == bufD->m_size)
4575 bufD->pendingHostWrites[i].clear();
4576 bufD->pendingHostWrites[i].append({ u.offset, u.data });
4577 }
4578 } else if (u.type == QRhiResourceUpdateBatchPrivate::BufferOp::StaticUpload) {
4579 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, u.buf);
4580 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
4581 Q_ASSERT(u.offset + u.data.size() <= bufD->m_size);
4582
4583 // The general approach to staging upload data is to first try
4584 // using the per-frame "small" staging area, which is a very simple
4585 // linear allocator; if that's not big enough then create a
4586 // dedicated StagingArea and then deferred-release it to make sure
4587 // if stays alive while the frame is possibly still in flight.
4588
4589 QD3D12StagingArea::Allocation stagingAlloc;
4590 const quint32 allocSize = QD3D12StagingArea::allocSizeForArray(bufD->m_size, 1);
4591 recordSmallStagingAreaDemand(allocSize);
4592 if (smallStagingAreas[currentFrameSlot].remainingCapacity() >= allocSize)
4593 stagingAlloc = smallStagingAreas[currentFrameSlot].get(bufD->m_size);
4594
4595 std::optional<QD3D12StagingArea> ownStagingArea;
4596 if (!stagingAlloc.isValid()) {
4597 ownStagingArea = QD3D12StagingArea();
4598 if (!ownStagingArea->create(this, allocSize, D3D12_HEAP_TYPE_UPLOAD))
4599 continue;
4600 stagingAlloc = ownStagingArea->get(allocSize);
4601 if (!stagingAlloc.isValid()) {
4602 ownStagingArea->destroy();
4603 continue;
4604 }
4605 }
4606
4607 memcpy(stagingAlloc.p + u.offset, u.data.constData(), u.data.size());
4608
4609 barrierGen.addTransitionBarrier(bufD->handles[0], D3D12_RESOURCE_STATE_COPY_DEST);
4610 barrierGen.enqueueBufferedTransitionBarriers(cbD);
4611
4612 if (QD3D12Resource *res = resourcePool.lookupRef(bufD->handles[0])) {
4613 cbD->cmdList->CopyBufferRegion(res->resource,
4614 u.offset,
4615 stagingAlloc.buffer,
4616 stagingAlloc.bufferOffset + u.offset,
4617 u.data.size());
4618 }
4619
4620 if (ownStagingArea.has_value())
4621 ownStagingArea->destroyWithDeferredRelease(&releaseQueue);
4622 } else if (u.type == QRhiResourceUpdateBatchPrivate::BufferOp::Read) {
4623 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, u.buf);
4624 if (bufD->m_type == QRhiBuffer::Dynamic) {
4625 bufD->executeHostWritesForFrameSlot(currentFrameSlot);
4626 if (QD3D12Resource *res = resourcePool.lookupRef(bufD->handles[currentFrameSlot])) {
4627 Q_ASSERT(res->cpuMapPtr);
4628 u.result->data.resize(u.readSize);
4629 memcpy(u.result->data.data(), reinterpret_cast<char *>(res->cpuMapPtr) + u.offset, u.readSize);
4630 }
4631 if (u.result->completed)
4632 u.result->completed();
4633 } else {
4634 QD3D12Readback readback;
4635 readback.frameSlot = currentFrameSlot;
4636 readback.result = u.result;
4637 readback.byteSize = u.readSize;
4638 const quint32 allocSize = aligned(u.readSize, QD3D12StagingArea::ALIGNMENT);
4639 if (!readback.staging.create(this, allocSize, D3D12_HEAP_TYPE_READBACK)) {
4640 if (u.result->completed)
4641 u.result->completed();
4642 continue;
4643 }
4644 QD3D12StagingArea::Allocation stagingAlloc = readback.staging.get(u.readSize);
4645 if (!stagingAlloc.isValid()) {
4646 readback.staging.destroy();
4647 if (u.result->completed)
4648 u.result->completed();
4649 continue;
4650 }
4651 Q_ASSERT(stagingAlloc.bufferOffset == 0);
4652 barrierGen.addTransitionBarrier(bufD->handles[0], D3D12_RESOURCE_STATE_COPY_SOURCE);
4653 barrierGen.enqueueBufferedTransitionBarriers(cbD);
4654 if (QD3D12Resource *res = resourcePool.lookupRef(bufD->handles[0])) {
4655 cbD->cmdList->CopyBufferRegion(stagingAlloc.buffer, 0, res->resource, u.offset, u.readSize);
4656 activeReadbacks.append(readback);
4657 } else {
4658 readback.staging.destroy();
4659 if (u.result->completed)
4660 u.result->completed();
4661 }
4662 }
4663 } else if (u.type == QRhiResourceUpdateBatchPrivate::BufferOp::Copy) {
4664 QD3D12Buffer *dstD = QRHI_RES(QD3D12Buffer, u.buf);
4665 QD3D12Buffer *srcD = QRHI_RES(QD3D12Buffer, u.src);
4666 Q_ASSERT(dstD->m_type != QRhiBuffer::Dynamic && srcD->m_type != QRhiBuffer::Dynamic);
4667
4668 QD3D12Resource *dstRes = resourcePool.lookupRef(dstD->handles[0]);
4669 QD3D12Resource *srcRes = resourcePool.lookupRef(srcD->handles[0]);
4670 if (!dstRes || !srcRes)
4671 continue;
4672
4673 barrierGen.addTransitionBarrier(srcD->handles[0], D3D12_RESOURCE_STATE_COPY_SOURCE);
4674 barrierGen.addTransitionBarrier(dstD->handles[0], D3D12_RESOURCE_STATE_COPY_DEST);
4675 barrierGen.enqueueBufferedTransitionBarriers(cbD);
4676
4677 cbD->cmdList->CopyBufferRegion(dstRes->resource, u.offset,
4678 srcRes->resource, u.srcOffset,
4679 u.readSize);
4680 } else if (u.type == QRhiResourceUpdateBatchPrivate::BufferOp::Clear) {
4681 QD3D12Buffer *bufD = QRHI_RES(QD3D12Buffer, u.buf);
4682 Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
4683
4684 QD3D12Resource *res = resourcePool.lookupRef(bufD->handles[0]);
4685 if (!res)
4686 continue;
4687
4688 bool gotNewHeap = false;
4689 if (!ensureShaderVisibleDescriptorHeapCapacity(&shaderVisibleCbvSrvUavHeap,
4690 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
4691 currentFrameSlot, 1, &gotNewHeap))
4692 {
4693 continue;
4694 }
4695 if (gotNewHeap)
4696 bindShaderVisibleHeaps(cbD);
4697
4698 const QD3D12Descriptor cpuDesc = cbvSrvUavPool.allocate(1);
4699 if (!cpuDesc.isValid())
4700 continue;
4701 const QD3D12Descriptor gpuDesc = shaderVisibleCbvSrvUavHeap.perFrameHeapSlice[currentFrameSlot].get(1);
4702
4703 // Typed, because a raw view would need a 16 byte aligned offset.
4704 D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
4705 uavDesc.Format = DXGI_FORMAT_R32_UINT;
4706 uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
4707 uavDesc.Buffer.FirstElement = u.offset / 4u;
4708 uavDesc.Buffer.NumElements = u.readSize / 4u;
4709 dev->CreateUnorderedAccessView(res->resource, nullptr, &uavDesc, cpuDesc.cpuHandle);
4710 dev->CopyDescriptorsSimple(1, gpuDesc.cpuHandle, cpuDesc.cpuHandle,
4711 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
4712
4713 if (res->state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS && res->uavUsage)
4714 barrierGen.enqueueUavBarrier(cbD, bufD->handles[0]);
4715 barrierGen.addTransitionBarrier(bufD->handles[0], D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
4716 barrierGen.enqueueBufferedTransitionBarriers(cbD);
4717
4718 const UINT values[4] = { u.fillValue32(), u.fillValue32(), u.fillValue32(), u.fillValue32() };
4719 cbD->cmdList->ClearUnorderedAccessViewUint(gpuDesc.gpuHandle, cpuDesc.cpuHandle,
4720 res->resource, values, 0, nullptr);
4721
4722 res->uavUsage = QD3D12Resource::UavUsageWrite;
4723
4724 releaseQueue.deferredReleaseViews(&cbvSrvUavPool, cpuDesc, 1);
4725 }
4726 }
4727
4728 for (int opIdx = 0; opIdx < ud->activeTextureOpCount; ++opIdx) {
4729 const QRhiResourceUpdateBatchPrivate::TextureOp &u(ud->textureOps[opIdx]);
4730 if (u.type == QRhiResourceUpdateBatchPrivate::TextureOp::Upload) {
4731 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, u.dst);
4732 const bool is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4733 QD3D12Resource *res = resourcePool.lookupRef(texD->handle);
4734 if (!res)
4735 continue;
4736 barrierGen.addTransitionBarrier(texD->handle, D3D12_RESOURCE_STATE_COPY_DEST);
4737 barrierGen.enqueueBufferedTransitionBarriers(cbD);
4738 for (const auto &subres : u.subresDesc) {
4739 const int layer = subres.layer;
4740 const int level = subres.level;
4741 const QRhiTextureSubresourceUploadDescription &subresDesc(subres.desc);
4742 D3D12_SUBRESOURCE_FOOTPRINT footprint = {};
4743 footprint.Format = res->desc.Format;
4744 footprint.Depth = 1;
4745 quint32 totalBytes = 0;
4746
4747 QSize subresSize = subresDesc.sourceSize().isEmpty() ? q->sizeForMipLevel(level, texD->m_pixelSize)
4748 : subresDesc.sourceSize();
4749 const QPoint srcPos = subresDesc.sourceTopLeft();
4750 QPoint dstPos = subresDesc.destinationTopLeft();
4751
4752 if (subresDesc.image().isNull() && !subresDesc.data().isEmpty()) {
4753 if (isCompressedFormat(texD->m_format)) {
4754 subresSize = clampedCompressedSubResourceUploadSizeForSourceData(
4755 texD->m_format, subresSize, subresDesc.data().size());
4756 } else {
4757 subresSize = clampedSubResourceUploadSize(subresSize, dstPos, level, texD->m_pixelSize);
4758 quint32 bytesPerPixel = 0;
4759 textureFormatInfo(texD->m_format, subresSize, nullptr, nullptr, &bytesPerPixel);
4760 subresSize = clampedSubResourceUploadSizeForSourceData(subresSize,
4761 subresDesc.dataStride(),
4762 bytesPerPixel,
4763 subresDesc.data().size());
4764 }
4765 if (subresSize.isEmpty())
4766 continue;
4767 }
4768
4769 if (!subresDesc.image().isNull()) {
4770 const QImage img = subresDesc.image();
4771 const int bpl = img.bytesPerLine();
4772 footprint.RowPitch = aligned<UINT>(bpl, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
4773 totalBytes = footprint.RowPitch * img.height();
4774 } else if (!subresDesc.data().isEmpty() && isCompressedFormat(texD->m_format)) {
4775 QSize blockDim;
4776 quint32 bpl = 0;
4777 compressedFormatInfo(texD->m_format, subresSize, &bpl, nullptr, &blockDim);
4778 footprint.RowPitch = aligned<UINT>(bpl, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
4779 const int rowCount = aligned(subresSize.height(), blockDim.height()) / blockDim.height();
4780 totalBytes = footprint.RowPitch * rowCount;
4781 } else if (!subresDesc.data().isEmpty()) {
4782 quint32 bpl = 0;
4783 if (subresDesc.dataStride())
4784 bpl = subresDesc.dataStride();
4785 else
4786 textureFormatInfo(texD->m_format, subresSize, &bpl, nullptr, nullptr);
4787 footprint.RowPitch = aligned<UINT>(bpl, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
4788 totalBytes = footprint.RowPitch * subresSize.height();
4789 } else {
4790 qWarning("Invalid texture upload for %p layer=%d mip=%d", texD, layer, level);
4791 continue;
4792 }
4793
4794 const quint32 allocSize = QD3D12StagingArea::allocSizeForArray(totalBytes, 1);
4795 QD3D12StagingArea::Allocation stagingAlloc;
4796 recordSmallStagingAreaDemand(allocSize);
4797 if (smallStagingAreas[currentFrameSlot].remainingCapacity() >= allocSize)
4798 stagingAlloc = smallStagingAreas[currentFrameSlot].get(allocSize);
4799
4800 std::optional<QD3D12StagingArea> ownStagingArea;
4801 if (!stagingAlloc.isValid()) {
4802 ownStagingArea = QD3D12StagingArea();
4803 if (!ownStagingArea->create(this, allocSize, D3D12_HEAP_TYPE_UPLOAD))
4804 continue;
4805 stagingAlloc = ownStagingArea->get(allocSize);
4806 if (!stagingAlloc.isValid()) {
4807 ownStagingArea->destroy();
4808 continue;
4809 }
4810 }
4811
4812 D3D12_TEXTURE_COPY_LOCATION dst;
4813 dst.pResource = res->resource;
4814 dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
4815 dst.SubresourceIndex = calcSubresource(UINT(level), is3D ? 0u : UINT(layer), texD->mipLevelCount);
4816 D3D12_TEXTURE_COPY_LOCATION src;
4817 src.pResource = stagingAlloc.buffer;
4818 src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
4819 src.PlacedFootprint.Offset = stagingAlloc.bufferOffset;
4820
4821 D3D12_BOX srcBox; // back, right, bottom are exclusive
4822
4823 if (!subresDesc.image().isNull()) {
4824 const QImage img = subresDesc.image();
4825 const int bpc = qMax(1, img.depth() / 8);
4826 const int bpl = img.bytesPerLine();
4827
4828 QSize size = subresDesc.sourceSize().isEmpty() ? img.size() : subresDesc.sourceSize();
4829 size.setWidth(qMin(size.width(), img.width() - srcPos.x()));
4830 size.setHeight(qMin(size.height(), img.height() - srcPos.y()));
4831 size = clampedSubResourceUploadSize(size, dstPos, level, texD->m_pixelSize);
4832
4833 footprint.Width = size.width();
4834 footprint.Height = size.height();
4835
4836 srcBox.left = 0;
4837 srcBox.top = 0;
4838 srcBox.right = UINT(size.width());
4839 srcBox.bottom = UINT(size.height());
4840 srcBox.front = 0;
4841 srcBox.back = 1;
4842
4843 const uchar *imgPtr = img.constBits();
4844 const quint32 lineBytes = size.width() * bpc;
4845 for (int y = 0, h = size.height(); y < h; ++y) {
4846 memcpy(stagingAlloc.p + y * footprint.RowPitch,
4847 imgPtr + srcPos.x() * bpc + (y + srcPos.y()) * bpl,
4848 lineBytes);
4849 }
4850 } else if (!subresDesc.data().isEmpty() && isCompressedFormat(texD->m_format)) {
4851 QSize blockDim;
4852 quint32 bpl = 0;
4853 compressedFormatInfo(texD->m_format, subresSize, &bpl, nullptr, &blockDim);
4854 // x and y must be multiples of the block width and height
4855 dstPos.setX(aligned(dstPos.x(), blockDim.width()));
4856 dstPos.setY(aligned(dstPos.y(), blockDim.height()));
4857
4858 srcBox.left = 0;
4859 srcBox.top = 0;
4860 // width and height must be multiples of the block width and height
4861 srcBox.right = aligned(subresSize.width(), blockDim.width());
4862 srcBox.bottom = aligned(subresSize.height(), blockDim.height());
4863
4864 srcBox.front = 0;
4865 srcBox.back = 1;
4866
4867 footprint.Width = aligned(subresSize.width(), blockDim.width());
4868 footprint.Height = aligned(subresSize.height(), blockDim.height());
4869
4870 const quint32 copyBytes = qMin(bpl, footprint.RowPitch);
4871 const QByteArray imgData = subresDesc.data();
4872 const char *imgPtr = imgData.constData();
4873 const int rowCount = aligned(subresSize.height(), blockDim.height()) / blockDim.height();
4874 for (int y = 0; y < rowCount; ++y) {
4875 const quint64 srcOffset = quint64(y) * bpl;
4876 if (srcOffset >= quint64(imgData.size()))
4877 break;
4878 const quint32 n = quint32(qMin(quint64(copyBytes),
4879 quint64(imgData.size()) - srcOffset));
4880 memcpy(stagingAlloc.p + y * footprint.RowPitch, imgPtr + srcOffset, n);
4881 }
4882 } else if (!subresDesc.data().isEmpty()) {
4883 srcBox.left = 0;
4884 srcBox.top = 0;
4885 srcBox.right = subresSize.width();
4886 srcBox.bottom = subresSize.height();
4887 srcBox.front = 0;
4888 srcBox.back = 1;
4889
4890 footprint.Width = subresSize.width();
4891 footprint.Height = subresSize.height();
4892
4893 quint32 bpl = 0;
4894 if (subresDesc.dataStride())
4895 bpl = subresDesc.dataStride();
4896 else
4897 textureFormatInfo(texD->m_format, subresSize, &bpl, nullptr, nullptr);
4898
4899 const quint32 copyBytes = qMin(bpl, footprint.RowPitch);
4900 const QByteArray data = subresDesc.data();
4901 const char *imgPtr = data.constData();
4902 for (int y = 0, h = subresSize.height(); y < h; ++y) {
4903 // subresSize is bounded above, but copyBytes is the full bpl
4904 // for a padded dataStride(), so the last row would still read
4905 // past the data: a stride pads only *between* rows, and the
4906 // caller is not required to supply trailing padding.
4907 const quint64 srcOffset = quint64(y) * bpl;
4908 if (srcOffset >= quint64(data.size()))
4909 break;
4910 const quint32 n = quint32(qMin(quint64(copyBytes),
4911 quint64(data.size()) - srcOffset));
4912 memcpy(stagingAlloc.p + y * footprint.RowPitch, imgPtr + srcOffset, n);
4913 }
4914 }
4915
4916 src.PlacedFootprint.Footprint = footprint;
4917
4918 cbD->cmdList->CopyTextureRegion(&dst,
4919 UINT(dstPos.x()),
4920 UINT(dstPos.y()),
4921 is3D ? UINT(layer) : 0u,
4922 &src,
4923 &srcBox);
4924
4925 if (ownStagingArea.has_value())
4926 ownStagingArea->destroyWithDeferredRelease(&releaseQueue);
4927 }
4928 } else if (u.type == QRhiResourceUpdateBatchPrivate::TextureOp::Copy) {
4929 Q_ASSERT(u.src && u.dst);
4930 QD3D12Texture *srcD = QRHI_RES(QD3D12Texture, u.src);
4931 QD3D12Texture *dstD = QRHI_RES(QD3D12Texture, u.dst);
4932 const bool srcIs3D = srcD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4933 const bool dstIs3D = dstD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4934 QD3D12Resource *srcRes = resourcePool.lookupRef(srcD->handle);
4935 QD3D12Resource *dstRes = resourcePool.lookupRef(dstD->handle);
4936 if (!srcRes || !dstRes)
4937 continue;
4938
4939 barrierGen.addTransitionBarrier(srcD->handle, D3D12_RESOURCE_STATE_COPY_SOURCE);
4940 barrierGen.addTransitionBarrier(dstD->handle, D3D12_RESOURCE_STATE_COPY_DEST);
4941 barrierGen.enqueueBufferedTransitionBarriers(cbD);
4942
4943 const UINT srcSubresource = calcSubresource(UINT(u.desc.sourceLevel()),
4944 srcIs3D ? 0u : UINT(u.desc.sourceLayer()),
4945 srcD->mipLevelCount);
4946 const UINT dstSubresource = calcSubresource(UINT(u.desc.destinationLevel()),
4947 dstIs3D ? 0u : UINT(u.desc.destinationLayer()),
4948 dstD->mipLevelCount);
4949 const QPoint dp = u.desc.destinationTopLeft();
4950 const QSize mipSize = q->sizeForMipLevel(u.desc.sourceLevel(), srcD->m_pixelSize);
4951 const QSize copySize = u.desc.pixelSize().isEmpty() ? mipSize : u.desc.pixelSize();
4952 const QPoint sp = u.desc.sourceTopLeft();
4953
4954 D3D12_BOX srcBox;
4955 srcBox.left = UINT(sp.x());
4956 srcBox.top = UINT(sp.y());
4957 srcBox.front = srcIs3D ? UINT(u.desc.sourceLayer()) : 0u;
4958 // back, right, bottom are exclusive
4959 srcBox.right = srcBox.left + UINT(copySize.width());
4960 srcBox.bottom = srcBox.top + UINT(copySize.height());
4961 srcBox.back = srcBox.front + 1;
4962
4963 D3D12_TEXTURE_COPY_LOCATION src;
4964 src.pResource = srcRes->resource;
4965 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
4966 src.SubresourceIndex = srcSubresource;
4967 D3D12_TEXTURE_COPY_LOCATION dst;
4968 dst.pResource = dstRes->resource;
4969 dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
4970 dst.SubresourceIndex = dstSubresource;
4971
4972 cbD->cmdList->CopyTextureRegion(&dst,
4973 UINT(dp.x()),
4974 UINT(dp.y()),
4975 dstIs3D ? UINT(u.desc.destinationLayer()) : 0u,
4976 &src,
4977 &srcBox);
4978 } else if (u.type == QRhiResourceUpdateBatchPrivate::TextureOp::Read) {
4979 QD3D12Readback readback;
4980 readback.frameSlot = currentFrameSlot;
4981 readback.result = u.result;
4982
4983 QD3D12ObjectHandle srcHandle;
4984 QRect rect;
4985 bool is3D = false;
4986 if (u.rb.texture()) {
4987 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, u.rb.texture());
4988 if (texD->sampleDesc.Count > 1) {
4989 qWarning("Multisample texture cannot be read back");
4990 continue;
4991 }
4992 is3D = texD->m_flags.testFlag(QRhiTexture::ThreeDimensional);
4993 const QRect levelRect({0, 0}, q->sizeForMipLevel(u.rb.level(), texD->m_pixelSize));
4994 readback.format = texD->m_format;
4995 rect = u.rb.rect().isValid() ? u.rb.rect() : levelRect;
4996 if (isDepthTextureFormat(readback.format)) {
4997 // CopyTextureRegion() requires pSrcBox to be null when
4998 // copying from a depth-stencil resource, i.e. the whole
4999 // subresource is copied. The requested rectangle is cropped
5000 // out of it in finishActiveReadbacks().
5001 rect = rect.intersected(levelRect);
5002 readback.cropOrigin = rect.topLeft();
5003 }
5004 srcHandle = texD->handle;
5005 } else {
5006 Q_ASSERT(currentSwapChain);
5007 if (u.rb.rect().isValid())
5008 rect = u.rb.rect();
5009 else
5010 rect = QRect({0, 0}, currentSwapChain->pixelSize);
5011 readback.format = swapchainReadbackTextureFormat(currentSwapChain->colorFormat, nullptr);
5012 if (readback.format == QRhiTexture::UnknownFormat)
5013 continue;
5014 srcHandle = currentSwapChain->colorBuffers[currentSwapChain->currentBackBufferIndex];
5015 }
5016 readback.pixelSize = rect.size();
5017
5018 textureFormatInfo(readback.format,
5019 readback.pixelSize,
5020 &readback.bytesPerLine,
5021 &readback.byteSize,
5022 &readback.bytesPerPixel);
5023
5024 QD3D12Resource *srcRes = resourcePool.lookupRef(srcHandle);
5025 if (!srcRes)
5026 continue;
5027
5028 // D3D12 exposes a combined depth-stencil resource as two
5029 // separately addressable planes (Plane 0 = depth, Plane 1 =
5030 // stencil) for copying purposes; CopyTextureRegion cannot copy
5031 // both planes in one go. Read them out as two separate copies,
5032 // each into its own placed footprint within the same staging
5033 // buffer. finishActiveReadbacks() then interleaves the two
5034 // planes into the result.
5035 const bool combinedDepthStencil = u.rb.texture() && isStencilSupportingFormat(readback.format);
5036 const bool depthTexture = u.rb.texture() && isDepthTextureFormat(readback.format);
5037
5038 const UINT subresource = calcSubresource(UINT(u.rb.level()),
5039 is3D ? 0u : UINT(u.rb.layer()),
5040 srcRes->desc.MipLevels);
5041 D3D12_PLACED_SUBRESOURCE_FOOTPRINT layout;
5042 // totalBytes is what we get from D3D, with the 256 aligned stride,
5043 // readback.byteSize is the final result that's not relevant here yet
5044 UINT64 totalBytes = 0;
5045 dev->GetCopyableFootprints(&srcRes->desc, subresource, 1, 0,
5046 &layout, nullptr, nullptr, &totalBytes);
5047 readback.stagingRowPitch = layout.Footprint.RowPitch;
5048
5049 UINT stencilSubresource = 0;
5050 D3D12_PLACED_SUBRESOURCE_FOOTPRINT stencilLayout;
5051 UINT64 stencilTotalBytes = 0;
5052 if (combinedDepthStencil) {
5053 stencilSubresource = subresource
5054 + srcRes->desc.MipLevels * UINT(srcRes->desc.DepthOrArraySize);
5055 dev->GetCopyableFootprints(&srcRes->desc, stencilSubresource, 1, 0,
5056 &stencilLayout, nullptr, nullptr, &stencilTotalBytes);
5057 readback.stencilStagingRowPitch = stencilLayout.Footprint.RowPitch;
5058 }
5059
5060 const quint32 allocSize = aligned<quint32>(totalBytes, QD3D12StagingArea::ALIGNMENT)
5061 + (combinedDepthStencil ? aligned<quint32>(stencilTotalBytes, QD3D12StagingArea::ALIGNMENT) : 0);
5062 if (!readback.staging.create(this, allocSize, D3D12_HEAP_TYPE_READBACK)) {
5063 if (u.result->completed)
5064 u.result->completed();
5065 continue;
5066 }
5067 QD3D12StagingArea::Allocation stagingAlloc = readback.staging.get(totalBytes);
5068 QD3D12StagingArea::Allocation stencilStagingAlloc;
5069 if (combinedDepthStencil)
5070 stencilStagingAlloc = readback.staging.get(stencilTotalBytes);
5071 if (!stagingAlloc.isValid() || (combinedDepthStencil && !stencilStagingAlloc.isValid())) {
5072 readback.staging.destroy();
5073 if (u.result->completed)
5074 u.result->completed();
5075 continue;
5076 }
5077 Q_ASSERT(stagingAlloc.bufferOffset == 0);
5078 readback.stencilStagingOffset = stencilStagingAlloc.bufferOffset;
5079
5080 barrierGen.addTransitionBarrier(srcHandle, D3D12_RESOURCE_STATE_COPY_SOURCE);
5081 barrierGen.enqueueBufferedTransitionBarriers(cbD);
5082
5083 D3D12_TEXTURE_COPY_LOCATION dst;
5084 dst.pResource = stagingAlloc.buffer;
5085 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
5086 dst.PlacedFootprint.Offset = 0;
5087 dst.PlacedFootprint.Footprint = layout.Footprint;
5088
5089 D3D12_TEXTURE_COPY_LOCATION src;
5090 src.pResource = srcRes->resource;
5091 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
5092 src.SubresourceIndex = subresource;
5093
5094 D3D12_BOX srcBox = {};
5095 srcBox.left = UINT(rect.left());
5096 srcBox.top = UINT(rect.top());
5097 srcBox.front = is3D ? UINT(u.rb.layer()) : 0u;
5098 // back, right, bottom are exclusive
5099 srcBox.right = srcBox.left + UINT(rect.width());
5100 srcBox.bottom = srcBox.top + UINT(rect.height());
5101 srcBox.back = srcBox.front + 1;
5102
5103 // see the comment above: a depth-stencil source requires a null box
5104 const D3D12_BOX *srcBoxPtr = depthTexture ? nullptr : &srcBox;
5105
5106 cbD->cmdList->CopyTextureRegion(&dst, 0, 0, 0, &src, srcBoxPtr);
5107
5108 if (combinedDepthStencil) {
5109 D3D12_TEXTURE_COPY_LOCATION stencilDst;
5110 stencilDst.pResource = stencilStagingAlloc.buffer;
5111 stencilDst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
5112 stencilDst.PlacedFootprint.Offset = stencilStagingAlloc.bufferOffset;
5113 stencilDst.PlacedFootprint.Footprint = stencilLayout.Footprint;
5114
5115 D3D12_TEXTURE_COPY_LOCATION stencilSrc;
5116 stencilSrc.pResource = srcRes->resource;
5117 stencilSrc.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
5118 stencilSrc.SubresourceIndex = stencilSubresource;
5119
5120 cbD->cmdList->CopyTextureRegion(&stencilDst, 0, 0, 0, &stencilSrc, srcBoxPtr);
5121 }
5122
5123 activeReadbacks.append(readback);
5124 } else if (u.type == QRhiResourceUpdateBatchPrivate::TextureOp::GenMips) {
5125 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, u.dst);
5126 Q_ASSERT(texD->flags().testFlag(QRhiTexture::UsedWithGenerateMips));
5127
5128 // Writing the levels above 0 with unordered access views does not
5129 // initialize the subresources of a placed resource, so discard
5130 // those levels upfront, otherwise the debug layer complains once
5131 // they get sampled. Level 0 must be left alone, it has content.
5132 QD3D12Resource *res = resourcePool.lookupRef(texD->handle);
5133 if (res && texD->mipLevelCount >= 2
5134 && (res->desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET))
5135 {
5136 const bool is3D = res->desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D;
5137 const UINT layerCount = is3D ? 1u : UINT(res->desc.DepthOrArraySize);
5138 QBitArray &initialized(texD->subresourceInitialized);
5139 QVarLengthArray<UINT, 16> subresourcesToDiscard;
5140 for (UINT layer = 0; layer < layerCount; ++layer) {
5141 for (UINT level = 1; level < texD->mipLevelCount; ++level) {
5142 const UINT subresource = calcSubresource(level, layer, texD->mipLevelCount);
5143 if (int(subresource) >= initialized.size())
5144 initialized.resize(int(subresource) + 1);
5145 if (!initialized.testBit(int(subresource))) {
5146 initialized.setBit(int(subresource));
5147 subresourcesToDiscard.append(subresource);
5148 }
5149 }
5150 }
5151 if (!subresourcesToDiscard.isEmpty()) {
5152 // Discarding needs the RENDER_TARGET state.
5153 barrierGen.addTransitionBarrier(texD->handle, D3D12_RESOURCE_STATE_RENDER_TARGET);
5154 barrierGen.enqueueBufferedTransitionBarriers(cbD);
5155 for (UINT subresource : subresourcesToDiscard) {
5156 D3D12_DISCARD_REGION region = {};
5157 region.FirstSubresource = subresource;
5158 region.NumSubresources = 1;
5159 cbD->cmdList->DiscardResource(res->resource, &region);
5160 }
5161 }
5162 }
5163
5164 if (texD->flags().testFlag(QRhiTexture::ThreeDimensional))
5165 mipmapGen3D.generate(cbD, texD->handle);
5166 else
5167 mipmapGen.generate(cbD, texD->handle);
5168 }
5169 }
5170
5171 ud->free();
5172}
5173
5174void QRhiD3D12::finishActiveReadbacks(bool forced)
5175{
5176 QVarLengthArray<std::function<void()>, 4> completedCallbacks;
5177
5178 for (int i = activeReadbacks.size() - 1; i >= 0; --i) {
5179 QD3D12Readback &readback(activeReadbacks[i]);
5180 if (forced || currentFrameSlot == readback.frameSlot || readback.frameSlot < 0) {
5181 readback.result->format = readback.format;
5182 readback.result->pixelSize = readback.pixelSize;
5183 readback.result->data.resize(int(readback.byteSize));
5184
5185 if (readback.format != QRhiTexture::UnknownFormat) {
5186 if (isStencilSupportingFormat(readback.format)) {
5187 // The staging buffer holds two separate planes (see
5188 // enqueueResourceUpdates()): the 32-bit depth plane at
5189 // offset 0 and the 8-bit stencil plane at
5190 // readback.stencilStagingOffset, each with its own row
5191 // pitch. Interleave them into one packed value per
5192 // pixel, in the same layout OpenGL's native
5193 // GL_UNSIGNED_INT_24_8 (D24S8) and
5194 // GL_FLOAT_32_UNSIGNED_INT_24_8_REV (D32FS8) readbacks
5195 // produce. The Vulkan and Metal backends do the same.
5196 // A depth-stencil texture is always copied in its entirety,
5197 // so skip to where the requested rectangle starts in each plane.
5198 const quint8 *depthBase = readback.staging.mem.p
5199 + readback.cropOrigin.y() * readback.stagingRowPitch
5200 + readback.cropOrigin.x() * 4;
5201 const quint8 *stencilBase = readback.staging.mem.p + readback.stencilStagingOffset
5202 + readback.cropOrigin.y() * readback.stencilStagingRowPitch
5203 + readback.cropOrigin.x();
5204 char *dst = readback.result->data.data();
5205 const int w = readback.pixelSize.width();
5206 const int h = readback.pixelSize.height();
5207 if (readback.format == QRhiTexture::D32FS8) {
5208 // 8 bytes per pixel: the float depth, then a 32-bit
5209 // word with the stencil in its low 8 bits.
5210 for (int y = 0; y < h; ++y) {
5211 const quint8 *depthRow = depthBase + y * readback.stagingRowPitch;
5212 const quint8 *stencilRow = stencilBase + y * readback.stencilStagingRowPitch;
5213 for (int x = 0; x < w; ++x) {
5214 const quint32 stencilWord = stencilRow[x];
5215 char *dstPixel = dst + (y * w + x) * 8;
5216 memcpy(dstPixel, depthRow + x * 4, sizeof(quint32));
5217 memcpy(dstPixel + 4, &stencilWord, sizeof(quint32));
5218 }
5219 }
5220 } else { // D24S8
5221 // 4 bytes per pixel: depth in the upper 24 bits,
5222 // stencil in the low 8 bits.
5223 for (int y = 0; y < h; ++y) {
5224 const quint8 *depthRow = depthBase + y * readback.stagingRowPitch;
5225 const quint8 *stencilRow = stencilBase + y * readback.stencilStagingRowPitch;
5226 for (int x = 0; x < w; ++x) {
5227 // depthRow's texel is a 32-bit value with the
5228 // 24-bit depth in the low bits, like the
5229 // Vulkan/Metal depth plane.
5230 quint32 depthWord;
5231 memcpy(&depthWord, depthRow + x * 4, sizeof(quint32));
5232 const quint32 combined = ((depthWord & 0x00FFFFFFu) << 8) | stencilRow[x];
5233 memcpy(dst + (y * w + x) * 4, &combined, sizeof(quint32));
5234 }
5235 }
5236 }
5237 } else {
5238 quint8 *dstPtr = reinterpret_cast<quint8 *>(readback.result->data.data());
5239 const quint8 *srcPtr = readback.staging.mem.p
5240 + readback.cropOrigin.y() * readback.stagingRowPitch
5241 + readback.cropOrigin.x() * readback.bytesPerPixel;
5242 const quint32 lineSize = qMin(readback.bytesPerLine, readback.stagingRowPitch);
5243 for (int y = 0, h = readback.pixelSize.height(); y < h; ++y)
5244 memcpy(dstPtr + y * readback.bytesPerLine, srcPtr + y * readback.stagingRowPitch, lineSize);
5245 if (readback.format == QRhiTexture::D24) {
5246 // The depth is in the low 24 bits and the upper 8 bits
5247 // are unused. Use the same layout as for D24S8: depth in
5248 // the upper 24 bits, the low 8 bits zero.
5249 char *p = readback.result->data.data();
5250 for (qsizetype px = 0, count = readback.result->data.size() / 4; px < count; ++px)
5251 qToUnaligned((qFromUnaligned<quint32>(p + px * 4) & 0x00FFFFFFu) << 8, p + px * 4);
5252 }
5253 }
5254 } else {
5255 memcpy(readback.result->data.data(), readback.staging.mem.p, readback.byteSize);
5256 }
5257
5258 readback.staging.destroy();
5259
5260 if (readback.result->completed)
5261 completedCallbacks.append(readback.result->completed);
5262
5263 activeReadbacks.remove(i);
5264 }
5265 }
5266
5267 for (auto f : completedCallbacks)
5268 f();
5269}
5270
5271bool QRhiD3D12::ensureShaderVisibleDescriptorHeapCapacity(QD3D12ShaderVisibleDescriptorHeap *h,
5272 D3D12_DESCRIPTOR_HEAP_TYPE type,
5273 int frameSlot,
5274 quint32 neededDescriptorCount,
5275 bool *gotNew)
5276{
5277 // Gets a new heap if needed. Note that the capacity we get is clamped
5278 // automatically (e.g. to 1 million, or 2048 for samplers), so * 2 does not
5279 // mean we can grow indefinitely, then again even using the same size would
5280 // work (because we what we are after here is a new heap for the rest of
5281 // the commands, not affecting what's already recorded).
5282 if (h->perFrameHeapSlice[frameSlot].remainingCapacity() < neededDescriptorCount) {
5283 const quint32 newPerFrameSize = qMax(h->perFrameHeapSlice[frameSlot].capacity * 2,
5284 neededDescriptorCount);
5285 QD3D12ShaderVisibleDescriptorHeap newHeap;
5286 if (!newHeap.create(dev, type, newPerFrameSize)) {
5287 qWarning("Could not create new shader-visible descriptor heap");
5288 return false;
5289 }
5290 h->destroyWithDeferredRelease(&releaseQueue);
5291 *h = newHeap;
5292 *gotNew = true;
5293 }
5294 return true;
5295}
5296
5297void QRhiD3D12::resetAndResizeSmallStagingArea(int frameSlot)
5298{
5299 QD3D12StagingArea &area(smallStagingAreas[frameSlot]);
5300
5301 // What this slot was asked for the last time it was used. Note that a
5302 // finish() in the middle of a frame rewinds the area without clearing the
5303 // counter, so with that this is an overestimate - which only means the
5304 // area may end up somewhat larger than strictly necessary.
5305 const quint32 needed = smallStagingAreaBytesNeeded[frameSlot];
5306 smallStagingAreaBytesNeeded[frameSlot] = 0;
5307
5308 quint32 newCapacity = 0;
5309 if (needed > area.capacity) {
5310 // Fell back to dedicated staging areas last time. Grow so that it
5311 // does not have to happen again.
5312 smallStagingAreaLowDemandFrames[frameSlot] = 0;
5313 newCapacity = qMin(qNextPowerOfTwo(needed), SMALL_STAGING_AREA_BYTES_PER_FRAME_MAX);
5314 } else if (needed <= area.capacity / 4 && area.capacity > SMALL_STAGING_AREA_BYTES_PER_FRAME_START) {
5315 if (++smallStagingAreaLowDemandFrames[frameSlot] >= SMALL_STAGING_AREA_LOW_DEMAND_FRAMES) {
5316 smallStagingAreaLowDemandFrames[frameSlot] = 0;
5317 newCapacity = qMax(area.capacity / 2, SMALL_STAGING_AREA_BYTES_PER_FRAME_START);
5318 }
5319 } else {
5320 smallStagingAreaLowDemandFrames[frameSlot] = 0;
5321 }
5322
5323 if (newCapacity && newCapacity != area.capacity) {
5324 QD3D12StagingArea newArea;
5325 if (newArea.create(this, aligned(newCapacity, QD3D12StagingArea::ALIGNMENT), D3D12_HEAP_TYPE_UPLOAD)) {
5326 area.destroyWithDeferredRelease(&releaseQueue);
5327 area = newArea;
5328 QString decoratedName = QLatin1String("Small staging area buffer/");
5329 decoratedName += QString::number(frameSlot);
5330 area.mem.buffer->SetName(reinterpret_cast<LPCWSTR>(decoratedName.utf16()));
5331 }
5332 // If it failed, just carry on with the existing area; the dedicated
5333 // staging area fallback keeps things working.
5334 }
5335
5336 area.head = 0;
5337}
5338
5339void QRhiD3D12::bindShaderVisibleHeaps(QD3D12CommandBuffer *cbD)
5340{
5341 ID3D12DescriptorHeap *heaps[] = {
5342 shaderVisibleCbvSrvUavHeap.heap.heap,
5343 samplerMgr.shaderVisibleSamplerHeap.heap.heap
5344 };
5345 cbD->cmdList->SetDescriptorHeaps(2, heaps);
5346}
5347
5348QD3D12Buffer::QD3D12Buffer(QRhiImplementation *rhi, Type type, UsageFlags usage, quint32 size)
5349 : QRhiBuffer(rhi, type, usage, size)
5350{
5351}
5352
5353QD3D12Buffer::~QD3D12Buffer()
5354{
5355 destroy();
5356}
5357
5358void QD3D12Buffer::destroy()
5359{
5360 if (handles[0].isNull())
5361 return;
5362
5363 QRHI_RES_RHI(QRhiD3D12);
5364
5365 // destroy() implementations, unlike other functions, are expected to test
5366 // for m_rhi (rhiD) being null, to allow surviving in case one attempts to
5367 // destroy a (leaked) resource after the QRhi.
5368 //
5369 // If there is no QRhi anymore, we do not deferred-release but that's fine
5370 // since the QRhi already released everything that was in the resourcePool.
5371
5372 for (int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
5373 if (rhiD)
5374 rhiD->releaseQueue.deferredReleaseResource(handles[i]);
5375 handles[i] = {};
5376 pendingHostWrites[i].clear();
5377 }
5378
5379 if (rhiD)
5380 rhiD->unregisterResource(this);
5381}
5382
5383bool QD3D12Buffer::create()
5384{
5385 if (!handles[0].isNull())
5386 destroy();
5387
5388 if (m_usage.testFlag(QRhiBuffer::UniformBuffer) && m_type != Dynamic) {
5389 qWarning("UniformBuffer must always be Dynamic");
5390 return false;
5391 }
5392
5393 if (m_usage.testFlag(QRhiBuffer::StorageBuffer) && m_type == Dynamic) {
5394 qWarning("StorageBuffer cannot be combined with Dynamic");
5395 return false;
5396 }
5397
5398 const quint32 nonZeroSize = m_size <= 0 ? 256 : m_size;
5399 const quint32 roundedSize = aligned(nonZeroSize, m_usage.testFlag(QRhiBuffer::UniformBuffer) ? 256u : 4u);
5400
5401 UINT resourceFlags = D3D12_RESOURCE_FLAG_NONE;
5402 if (m_usage.testFlag(QRhiBuffer::StorageBuffer))
5403 resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
5404
5405 QRHI_RES_RHI(QRhiD3D12);
5406 HRESULT hr = 0;
5407 for (int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
5408 if (i == 0 || m_type == Dynamic) {
5409 D3D12_RESOURCE_DESC resourceDesc = {};
5410 resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
5411 resourceDesc.Width = roundedSize;
5412 resourceDesc.Height = 1;
5413 resourceDesc.DepthOrArraySize = 1;
5414 resourceDesc.MipLevels = 1;
5415 resourceDesc.Format = DXGI_FORMAT_UNKNOWN;
5416 resourceDesc.SampleDesc = { 1, 0 };
5417 resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
5418 resourceDesc.Flags = D3D12_RESOURCE_FLAGS(resourceFlags);
5419 ID3D12Resource *resource = nullptr;
5420 D3D12MA::Allocation *allocation = nullptr;
5421 // Dynamic == host (CPU) visible
5422 D3D12_HEAP_TYPE heapType = m_type == Dynamic
5423 ? D3D12_HEAP_TYPE_UPLOAD
5424 : D3D12_HEAP_TYPE_DEFAULT;
5425 D3D12_RESOURCE_STATES resourceState = m_type == Dynamic
5426 ? D3D12_RESOURCE_STATE_GENERIC_READ
5427 : D3D12_RESOURCE_STATE_COMMON;
5428 hr = rhiD->vma.createResource(heapType,
5429 &resourceDesc,
5430 resourceState,
5431 nullptr,
5432 &allocation,
5433 __uuidof(resource),
5434 reinterpret_cast<void **>(&resource));
5435 if (FAILED(hr))
5436 break;
5437 if (!m_objectName.isEmpty()) {
5438 QString decoratedName = QString::fromUtf8(m_objectName);
5439 if (m_type == Dynamic) {
5440 decoratedName += QLatin1Char('/');
5441 decoratedName += QString::number(i);
5442 }
5443 resource->SetName(reinterpret_cast<LPCWSTR>(decoratedName.utf16()));
5444 }
5445 void *cpuMemPtr = nullptr;
5446 if (m_type == Dynamic) {
5447 // will be mapped for ever on the CPU, this makes future host write operations very simple
5448 hr = resource->Map(0, nullptr, &cpuMemPtr);
5449 if (FAILED(hr)) {
5450 qWarning("Map() failed to dynamic buffer");
5451 resource->Release();
5452 if (allocation)
5453 allocation->Release();
5454 break;
5455 }
5456 }
5457 handles[i] = QD3D12Resource::addToPool(&rhiD->resourcePool,
5458 resource,
5459 resourceState,
5460 allocation,
5461 cpuMemPtr);
5462 }
5463 }
5464 if (FAILED(hr)) {
5465 qWarning("Failed to create buffer: '%s' Type was %d, size was %u, using D3D12MA was %d.",
5466 qPrintable(QSystemError::windowsComString(hr)),
5467 int(m_type),
5468 roundedSize,
5469 int(rhiD->vma.isUsingD3D12MA()));
5470 return false;
5471 }
5472
5473 generation += 1;
5474 rhiD->registerResource(this);
5475 return true;
5476}
5477
5478QRhiBuffer::NativeBuffer QD3D12Buffer::nativeBuffer()
5479{
5480 NativeBuffer b;
5481 Q_ASSERT(sizeof(b.objects) / sizeof(b.objects[0]) >= size_t(QD3D12_FRAMES_IN_FLIGHT));
5482 QRHI_RES_RHI(QRhiD3D12);
5483 if (m_type == Dynamic) {
5484 for (int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
5485 executeHostWritesForFrameSlot(i);
5486 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handles[i]))
5487 b.objects[i] = res->resource;
5488 else
5489 b.objects[i] = nullptr;
5490 }
5491 b.slotCount = QD3D12_FRAMES_IN_FLIGHT;
5492 return b;
5493 }
5494 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handles[0]))
5495 b.objects[0] = res->resource;
5496 else
5497 b.objects[0] = nullptr;
5498 b.slotCount = 1;
5499 return b;
5500}
5501
5502char *QD3D12Buffer::beginFullDynamicBufferUpdateForCurrentFrame()
5503{
5504 // Shortcut the entire buffer update mechanism and allow the client to do
5505 // the host writes directly to the buffer. This will lead to unexpected
5506 // results when combined with QRhiResourceUpdateBatch-based updates for the
5507 // buffer, but provides a fast path for dynamic buffers that have all their
5508 // content changed in every frame.
5509
5510 Q_ASSERT(m_type == Dynamic);
5511 QRHI_RES_RHI(QRhiD3D12);
5512 Q_ASSERT(rhiD->inFrame);
5513 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handles[rhiD->currentFrameSlot]))
5514 return static_cast<char *>(res->cpuMapPtr);
5515
5516 return nullptr;
5517}
5518
5519void QD3D12Buffer::endFullDynamicBufferUpdateForCurrentFrame()
5520{
5521 // nothing to do here
5522}
5523
5524void QD3D12Buffer::executeHostWritesForFrameSlot(int frameSlot)
5525{
5526 if (pendingHostWrites[frameSlot].isEmpty())
5527 return;
5528
5529 Q_ASSERT(m_type == QRhiBuffer::Dynamic);
5530 QRHI_RES_RHI(QRhiD3D12);
5531 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handles[frameSlot])) {
5532 Q_ASSERT(res->cpuMapPtr);
5533 for (const QD3D12Buffer::HostWrite &u : std::as_const(pendingHostWrites[frameSlot]))
5534 memcpy(static_cast<char *>(res->cpuMapPtr) + u.offset, u.data.constData(), u.data.size());
5535 }
5536 pendingHostWrites[frameSlot].clear();
5537}
5538
5539static inline DXGI_FORMAT toD3DTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags)
5540{
5541 const bool srgb = flags.testFlag(QRhiTexture::sRGB);
5542 switch (format) {
5543 case QRhiTexture::RGBA8:
5544 return srgb ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM;
5545 case QRhiTexture::BGRA8:
5546 return srgb ? DXGI_FORMAT_B8G8R8A8_UNORM_SRGB : DXGI_FORMAT_B8G8R8A8_UNORM;
5547 case QRhiTexture::R8:
5548 return DXGI_FORMAT_R8_UNORM;
5549 case QRhiTexture::R8SI:
5550 return DXGI_FORMAT_R8_SINT;
5551 case QRhiTexture::R8UI:
5552 return DXGI_FORMAT_R8_UINT;
5553 case QRhiTexture::RG8:
5554 return DXGI_FORMAT_R8G8_UNORM;
5555 case QRhiTexture::R16:
5556 return DXGI_FORMAT_R16_UNORM;
5557 case QRhiTexture::RG16:
5558 return DXGI_FORMAT_R16G16_UNORM;
5559 case QRhiTexture::RED_OR_ALPHA8:
5560 return DXGI_FORMAT_R8_UNORM;
5561
5562 case QRhiTexture::RGBA16F:
5563 return DXGI_FORMAT_R16G16B16A16_FLOAT;
5564 case QRhiTexture::RGBA32F:
5565 return DXGI_FORMAT_R32G32B32A32_FLOAT;
5566 case QRhiTexture::R16F:
5567 return DXGI_FORMAT_R16_FLOAT;
5568 case QRhiTexture::R32F:
5569 return DXGI_FORMAT_R32_FLOAT;
5570
5571 case QRhiTexture::RGB10A2:
5572 return DXGI_FORMAT_R10G10B10A2_UNORM;
5573
5574 case QRhiTexture::R32SI:
5575 return DXGI_FORMAT_R32_SINT;
5576 case QRhiTexture::R32UI:
5577 return DXGI_FORMAT_R32_UINT;
5578 case QRhiTexture::RG32SI:
5579 return DXGI_FORMAT_R32G32_SINT;
5580 case QRhiTexture::RG32UI:
5581 return DXGI_FORMAT_R32G32_UINT;
5582 case QRhiTexture::RGBA32SI:
5583 return DXGI_FORMAT_R32G32B32A32_SINT;
5584 case QRhiTexture::RGBA32UI:
5585 return DXGI_FORMAT_R32G32B32A32_UINT;
5586
5587 case QRhiTexture::D16:
5588 return DXGI_FORMAT_R16_TYPELESS;
5589 case QRhiTexture::D24:
5590 return DXGI_FORMAT_R24G8_TYPELESS;
5591 case QRhiTexture::D24S8:
5592 return DXGI_FORMAT_R24G8_TYPELESS;
5593 case QRhiTexture::D32F:
5594 return DXGI_FORMAT_R32_TYPELESS;
5595 case QRhiTexture::Format::D32FS8:
5596 return DXGI_FORMAT_R32G8X24_TYPELESS;
5597
5598 case QRhiTexture::BC1:
5599 return srgb ? DXGI_FORMAT_BC1_UNORM_SRGB : DXGI_FORMAT_BC1_UNORM;
5600 case QRhiTexture::BC2:
5601 return srgb ? DXGI_FORMAT_BC2_UNORM_SRGB : DXGI_FORMAT_BC2_UNORM;
5602 case QRhiTexture::BC3:
5603 return srgb ? DXGI_FORMAT_BC3_UNORM_SRGB : DXGI_FORMAT_BC3_UNORM;
5604 case QRhiTexture::BC4:
5605 return DXGI_FORMAT_BC4_UNORM;
5606 case QRhiTexture::BC5:
5607 return DXGI_FORMAT_BC5_UNORM;
5608 case QRhiTexture::BC6H:
5609 return DXGI_FORMAT_BC6H_UF16;
5610 case QRhiTexture::BC7:
5611 return srgb ? DXGI_FORMAT_BC7_UNORM_SRGB : DXGI_FORMAT_BC7_UNORM;
5612
5613 case QRhiTexture::ETC2_RGB8:
5614 case QRhiTexture::ETC2_RGB8A1:
5615 case QRhiTexture::ETC2_RGBA8:
5616 qWarning("QRhiD3D12 does not support ETC2 textures");
5617 return DXGI_FORMAT_R8G8B8A8_UNORM;
5618
5619 case QRhiTexture::ASTC_4x4:
5620 case QRhiTexture::ASTC_5x4:
5621 case QRhiTexture::ASTC_5x5:
5622 case QRhiTexture::ASTC_6x5:
5623 case QRhiTexture::ASTC_6x6:
5624 case QRhiTexture::ASTC_8x5:
5625 case QRhiTexture::ASTC_8x6:
5626 case QRhiTexture::ASTC_8x8:
5627 case QRhiTexture::ASTC_10x5:
5628 case QRhiTexture::ASTC_10x6:
5629 case QRhiTexture::ASTC_10x8:
5630 case QRhiTexture::ASTC_10x10:
5631 case QRhiTexture::ASTC_12x10:
5632 case QRhiTexture::ASTC_12x12:
5633 qWarning("QRhiD3D12 does not support ASTC textures");
5634 return DXGI_FORMAT_R8G8B8A8_UNORM;
5635
5636 default:
5637 break;
5638 }
5639 return DXGI_FORMAT_R8G8B8A8_UNORM;
5640}
5641
5642QD3D12RenderBuffer::QD3D12RenderBuffer(QRhiImplementation *rhi,
5643 Type type,
5644 const QSize &pixelSize,
5645 int sampleCount,
5646 Flags flags,
5647 QRhiTexture::Format backingFormatHint)
5648 : QRhiRenderBuffer(rhi, type, pixelSize, sampleCount, flags, backingFormatHint)
5649{
5650}
5651
5652QD3D12RenderBuffer::~QD3D12RenderBuffer()
5653{
5654 destroy();
5655}
5656
5657void QD3D12RenderBuffer::destroy()
5658{
5659 if (handle.isNull())
5660 return;
5661
5662 QRHI_RES_RHI(QRhiD3D12);
5663 if (rhiD) {
5664 if (rtv.isValid())
5665 rhiD->releaseQueue.deferredReleaseResourceWithViews(handle, &rhiD->rtvPool, rtv, 1);
5666 else if (dsv.isValid())
5667 rhiD->releaseQueue.deferredReleaseResourceWithViews(handle, &rhiD->dsvPool, dsv, 1);
5668 }
5669
5670 handle = {};
5671 rtv = {};
5672 dsv = {};
5673
5674 if (rhiD)
5675 rhiD->unregisterResource(this);
5676}
5677
5678bool QD3D12RenderBuffer::create()
5679{
5680 if (!handle.isNull())
5681 destroy();
5682
5683 if (m_pixelSize.isEmpty())
5684 return false;
5685
5686 QRHI_RES_RHI(QRhiD3D12);
5687
5688 switch (m_type) {
5689 case QRhiRenderBuffer::Color:
5690 {
5691 dxgiFormat = toD3DTextureFormat(backingFormat(), {});
5692 sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount, dxgiFormat);
5693 D3D12_RESOURCE_DESC resourceDesc = {};
5694 resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
5695 resourceDesc.Width = UINT64(m_pixelSize.width());
5696 resourceDesc.Height = UINT(m_pixelSize.height());
5697 resourceDesc.DepthOrArraySize = 1;
5698 resourceDesc.MipLevels = 1;
5699 resourceDesc.Format = dxgiFormat;
5700 resourceDesc.SampleDesc = sampleDesc;
5701 resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
5702 resourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
5703 D3D12_CLEAR_VALUE clearValue = {};
5704 clearValue.Format = dxgiFormat;
5705 // have a separate allocation and resource object (meaning both will need its own Release())
5706 ID3D12Resource *resource = nullptr;
5707 D3D12MA::Allocation *allocation = nullptr;
5708 HRESULT hr = rhiD->vma.createResource(D3D12_HEAP_TYPE_DEFAULT,
5709 &resourceDesc,
5710 D3D12_RESOURCE_STATE_RENDER_TARGET,
5711 &clearValue,
5712 &allocation,
5713 __uuidof(ID3D12Resource),
5714 reinterpret_cast<void **>(&resource));
5715 if (FAILED(hr)) {
5716 qWarning("Failed to create color buffer: %s", qPrintable(QSystemError::windowsComString(hr)));
5717 return false;
5718 }
5719 handle = QD3D12Resource::addToPool(&rhiD->resourcePool, resource, D3D12_RESOURCE_STATE_RENDER_TARGET, allocation);
5720 rtv = rhiD->rtvPool.allocate(1);
5721 if (!rtv.isValid())
5722 return false;
5723 D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
5724 rtvDesc.Format = dxgiFormat;
5725 rtvDesc.ViewDimension = sampleDesc.Count > 1 ? D3D12_RTV_DIMENSION_TEXTURE2DMS
5726 : D3D12_RTV_DIMENSION_TEXTURE2D;
5727 rhiD->dev->CreateRenderTargetView(resource, &rtvDesc, rtv.cpuHandle);
5728 }
5729 break;
5730 case QRhiRenderBuffer::DepthStencil:
5731 {
5732 dxgiFormat = DS_FORMAT;
5733 sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount, dxgiFormat);
5734 D3D12_RESOURCE_DESC resourceDesc = {};
5735 resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
5736 resourceDesc.Width = UINT64(m_pixelSize.width());
5737 resourceDesc.Height = UINT(m_pixelSize.height());
5738 resourceDesc.DepthOrArraySize = 1;
5739 resourceDesc.MipLevels = 1;
5740 resourceDesc.Format = dxgiFormat;
5741 resourceDesc.SampleDesc = sampleDesc;
5742 resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
5743 resourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
5744 if (m_flags.testFlag(UsedWithSwapChainOnly))
5745 resourceDesc.Flags |= D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE;
5746 D3D12_CLEAR_VALUE clearValue = {};
5747 clearValue.Format = dxgiFormat;
5748 clearValue.DepthStencil.Depth = 1.0f;
5749 clearValue.DepthStencil.Stencil = 0;
5750 ID3D12Resource *resource = nullptr;
5751 D3D12MA::Allocation *allocation = nullptr;
5752 HRESULT hr = rhiD->vma.createResource(D3D12_HEAP_TYPE_DEFAULT,
5753 &resourceDesc,
5754 D3D12_RESOURCE_STATE_DEPTH_WRITE,
5755 &clearValue,
5756 &allocation,
5757 __uuidof(ID3D12Resource),
5758 reinterpret_cast<void **>(&resource));
5759 if (FAILED(hr)) {
5760 qWarning("Failed to create depth-stencil buffer: %s", qPrintable(QSystemError::windowsComString(hr)));
5761 return false;
5762 }
5763 handle = QD3D12Resource::addToPool(&rhiD->resourcePool, resource, D3D12_RESOURCE_STATE_DEPTH_WRITE, allocation);
5764 dsv = rhiD->dsvPool.allocate(1);
5765 if (!dsv.isValid())
5766 return false;
5767 D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
5768 dsvDesc.Format = dxgiFormat;
5769 dsvDesc.ViewDimension = sampleDesc.Count > 1 ? D3D12_DSV_DIMENSION_TEXTURE2DMS
5770 : D3D12_DSV_DIMENSION_TEXTURE2D;
5771 rhiD->dev->CreateDepthStencilView(resource, &dsvDesc, dsv.cpuHandle);
5772 }
5773 break;
5774 }
5775
5776 if (!m_objectName.isEmpty()) {
5777 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handle)) {
5778 const QString name = QString::fromUtf8(m_objectName);
5779 res->resource->SetName(reinterpret_cast<LPCWSTR>(name.utf16()));
5780 }
5781 }
5782
5783 generation += 1;
5784 rhiD->registerResource(this);
5785 return true;
5786}
5787
5788QRhiTexture::Format QD3D12RenderBuffer::backingFormat() const
5789{
5790 if (m_backingFormatHint != QRhiTexture::UnknownFormat)
5791 return m_backingFormatHint;
5792 else
5793 return m_type == Color ? QRhiTexture::RGBA8 : QRhiTexture::UnknownFormat;
5794}
5795
5796QD3D12Texture::QD3D12Texture(QRhiImplementation *rhi, Format format, const QSize &pixelSize, int depth,
5797 int arraySize, int sampleCount, Flags flags)
5798 : QRhiTexture(rhi, format, pixelSize, depth, arraySize, sampleCount, flags)
5799{
5800}
5801
5802QD3D12Texture::~QD3D12Texture()
5803{
5804 destroy();
5805}
5806
5807void QD3D12Texture::destroy()
5808{
5809 if (handle.isNull())
5810 return;
5811
5812 QRHI_RES_RHI(QRhiD3D12);
5813 if (rhiD)
5814 rhiD->releaseQueue.deferredReleaseResourceWithViews(handle, &rhiD->cbvSrvUavPool, srv, 1);
5815
5816 handle = {};
5817 srv = {};
5818 subresourceInitialized.clear();
5819
5820 if (rhiD)
5821 rhiD->unregisterResource(this);
5822}
5823
5824static inline DXGI_FORMAT toD3DDepthTextureSRVFormat(QRhiTexture::Format format)
5825{
5826 switch (format) {
5827 case QRhiTexture::Format::D16:
5828 return DXGI_FORMAT_R16_UNORM;
5829 case QRhiTexture::Format::D24:
5830 return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
5831 case QRhiTexture::Format::D24S8:
5832 return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
5833 case QRhiTexture::Format::D32F:
5834 return DXGI_FORMAT_R32_FLOAT;
5835 case QRhiTexture::Format::D32FS8:
5836 return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
5837 default:
5838 break;
5839 }
5840 Q_UNREACHABLE_RETURN(DXGI_FORMAT_R32_FLOAT);
5841}
5842
5843static inline DXGI_FORMAT toD3DDepthTextureDSVFormat(QRhiTexture::Format format)
5844{
5845 // here the result cannot be typeless
5846 switch (format) {
5847 case QRhiTexture::Format::D16:
5848 return DXGI_FORMAT_D16_UNORM;
5849 case QRhiTexture::Format::D24:
5850 return DXGI_FORMAT_D24_UNORM_S8_UINT;
5851 case QRhiTexture::Format::D24S8:
5852 return DXGI_FORMAT_D24_UNORM_S8_UINT;
5853 case QRhiTexture::Format::D32F:
5854 return DXGI_FORMAT_D32_FLOAT;
5855 case QRhiTexture::Format::D32FS8:
5856 return DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
5857 default:
5858 break;
5859 }
5860 Q_UNREACHABLE_RETURN(DXGI_FORMAT_D32_FLOAT);
5861}
5862
5863bool QD3D12Texture::prepareCreate(QSize *adjustedSize)
5864{
5865 if (!handle.isNull())
5866 destroy();
5867
5868 QRHI_RES_RHI(QRhiD3D12);
5869 if (!rhiD->isTextureFormatSupported(m_format, m_flags))
5870 return false;
5871
5872 const bool isDepth = isDepthTextureFormat(m_format);
5873 const bool isCube = m_flags.testFlag(CubeMap);
5874 const bool is3D = m_flags.testFlag(ThreeDimensional);
5875 const bool isArray = m_flags.testFlag(TextureArray);
5876 const bool hasMipMaps = m_flags.testFlag(MipMapped);
5877 const bool is1D = m_flags.testFlag(OneDimensional);
5878
5879 const QSize size = is1D ? QSize(qMax(1, m_pixelSize.width()), 1)
5880 : (m_pixelSize.isEmpty() ? QSize(1, 1) : m_pixelSize);
5881
5882 dxgiFormat = toD3DTextureFormat(m_format, m_flags);
5883 if (isDepth) {
5884 srvFormat = toD3DDepthTextureSRVFormat(m_format);
5885 rtFormat = toD3DDepthTextureDSVFormat(m_format);
5886 } else {
5887 srvFormat = dxgiFormat;
5888 rtFormat = dxgiFormat;
5889 }
5890 if (m_writeViewFormat.format != UnknownFormat) {
5891 if (isDepth)
5892 rtFormat = toD3DDepthTextureDSVFormat(m_writeViewFormat.format);
5893 else
5894 rtFormat = toD3DTextureFormat(m_writeViewFormat.format, m_writeViewFormat.srgb ? sRGB : Flags());
5895 }
5896 if (m_readViewFormat.format != UnknownFormat) {
5897 if (isDepth)
5898 srvFormat = toD3DDepthTextureSRVFormat(m_readViewFormat.format);
5899 else
5900 srvFormat = toD3DTextureFormat(m_readViewFormat.format, m_readViewFormat.srgb ? sRGB : Flags());
5901 }
5902
5903 mipLevelCount = uint(hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1);
5904 sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount, dxgiFormat);
5905 if (sampleDesc.Count > 1) {
5906 if (isCube) {
5907 qWarning("Cubemap texture cannot be multisample");
5908 return false;
5909 }
5910 if (is3D) {
5911 qWarning("3D texture cannot be multisample");
5912 return false;
5913 }
5914 if (hasMipMaps) {
5915 qWarning("Multisample texture cannot have mipmaps");
5916 return false;
5917 }
5918 }
5919 if (isDepth && hasMipMaps) {
5920 qWarning("Depth texture cannot have mipmaps");
5921 return false;
5922 }
5923 if (isCube && is3D) {
5924 qWarning("Texture cannot be both cube and 3D");
5925 return false;
5926 }
5927 if (isArray && is3D) {
5928 qWarning("Texture cannot be both array and 3D");
5929 return false;
5930 }
5931 if (isCube && is1D) {
5932 qWarning("Texture cannot be both cube and 1D");
5933 return false;
5934 }
5935 if (is1D && is3D) {
5936 qWarning("Texture cannot be both 1D and 3D");
5937 return false;
5938 }
5939 if (m_depth > 1 && !is3D) {
5940 qWarning("Texture cannot have a depth of %d when it is not 3D", m_depth);
5941 return false;
5942 }
5943 if (m_arraySize > 0 && !isArray) {
5944 qWarning("Texture cannot have an array size of %d when it is not an array", m_arraySize);
5945 return false;
5946 }
5947 if (m_arraySize < 1 && isArray) {
5948 qWarning("Texture is an array but array size is %d", m_arraySize);
5949 return false;
5950 }
5951
5952 if (!rhiD->textureFormatInfo(m_format, size, nullptr, nullptr, nullptr))
5953 return false;
5954
5955 if (adjustedSize)
5956 *adjustedSize = size;
5957
5958 return true;
5959}
5960
5961bool QD3D12Texture::finishCreate()
5962{
5963 QRHI_RES_RHI(QRhiD3D12);
5964 const bool isCube = m_flags.testFlag(CubeMap);
5965 const bool is3D = m_flags.testFlag(ThreeDimensional);
5966 const bool isArray = m_flags.testFlag(TextureArray);
5967 const bool is1D = m_flags.testFlag(OneDimensional);
5968
5969 D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
5970 srvDesc.Format = srvFormat;
5971 srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
5972
5973 if (isCube) {
5974 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE;
5975 srvDesc.TextureCube.MipLevels = mipLevelCount;
5976 } else {
5977 if (is1D) {
5978 if (isArray) {
5979 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1DARRAY;
5980 srvDesc.Texture1DArray.MipLevels = mipLevelCount;
5981 if (m_arrayRangeStart >= 0 && m_arrayRangeLength >= 0) {
5982 srvDesc.Texture1DArray.FirstArraySlice = UINT(m_arrayRangeStart);
5983 srvDesc.Texture1DArray.ArraySize = UINT(m_arrayRangeLength);
5984 } else {
5985 srvDesc.Texture1DArray.FirstArraySlice = 0;
5986 srvDesc.Texture1DArray.ArraySize = UINT(qMax(0, m_arraySize));
5987 }
5988 } else {
5989 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D;
5990 srvDesc.Texture1D.MipLevels = mipLevelCount;
5991 }
5992 } else if (isArray) {
5993 if (sampleDesc.Count > 1) {
5994 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY;
5995 if (m_arrayRangeStart >= 0 && m_arrayRangeLength >= 0) {
5996 srvDesc.Texture2DMSArray.FirstArraySlice = UINT(m_arrayRangeStart);
5997 srvDesc.Texture2DMSArray.ArraySize = UINT(m_arrayRangeLength);
5998 } else {
5999 srvDesc.Texture2DMSArray.FirstArraySlice = 0;
6000 srvDesc.Texture2DMSArray.ArraySize = UINT(qMax(0, m_arraySize));
6001 }
6002 } else {
6003 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
6004 srvDesc.Texture2DArray.MipLevels = mipLevelCount;
6005 if (m_arrayRangeStart >= 0 && m_arrayRangeLength >= 0) {
6006 srvDesc.Texture2DArray.FirstArraySlice = UINT(m_arrayRangeStart);
6007 srvDesc.Texture2DArray.ArraySize = UINT(m_arrayRangeLength);
6008 } else {
6009 srvDesc.Texture2DArray.FirstArraySlice = 0;
6010 srvDesc.Texture2DArray.ArraySize = UINT(qMax(0, m_arraySize));
6011 }
6012 }
6013 } else {
6014 if (sampleDesc.Count > 1) {
6015 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMS;
6016 } else if (is3D) {
6017 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D;
6018 srvDesc.Texture3D.MipLevels = mipLevelCount;
6019 } else {
6020 srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
6021 srvDesc.Texture2D.MipLevels = mipLevelCount;
6022 }
6023 }
6024 }
6025
6026 srv = rhiD->cbvSrvUavPool.allocate(1);
6027 if (!srv.isValid())
6028 return false;
6029
6030 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handle)) {
6031 rhiD->dev->CreateShaderResourceView(res->resource, &srvDesc, srv.cpuHandle);
6032 if (!m_objectName.isEmpty()) {
6033 const QString name = QString::fromUtf8(m_objectName);
6034 res->resource->SetName(reinterpret_cast<LPCWSTR>(name.utf16()));
6035 }
6036 } else {
6037 return false;
6038 }
6039
6040 generation += 1;
6041 return true;
6042}
6043
6044bool QD3D12Texture::create()
6045{
6046 QSize size;
6047 if (!prepareCreate(&size))
6048 return false;
6049
6050 const bool isDepth = isDepthTextureFormat(m_format);
6051 const bool isCube = m_flags.testFlag(CubeMap);
6052 const bool is3D = m_flags.testFlag(ThreeDimensional);
6053 const bool isArray = m_flags.testFlag(TextureArray);
6054 const bool is1D = m_flags.testFlag(OneDimensional);
6055
6056 QRHI_RES_RHI(QRhiD3D12);
6057
6058 bool needsOptimizedClearValueSpecified = false;
6059 UINT resourceFlags = 0;
6060 if (m_flags.testFlag(RenderTarget) || sampleDesc.Count > 1) {
6061 if (isDepth)
6062 resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
6063 else
6064 resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
6065 needsOptimizedClearValueSpecified = true;
6066 }
6067 if (m_flags.testFlag(UsedWithGenerateMips)) {
6068 if (isDepth) {
6069 qWarning("Depth texture cannot have mipmaps generated");
6070 return false;
6071 }
6072 resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
6073 }
6074 if (m_flags.testFlag(UsedWithLoadStore))
6075 resourceFlags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
6076
6077 D3D12_RESOURCE_DESC resourceDesc = {};
6078 resourceDesc.Dimension = is1D ? D3D12_RESOURCE_DIMENSION_TEXTURE1D
6079 : (is3D ? D3D12_RESOURCE_DIMENSION_TEXTURE3D
6080 : D3D12_RESOURCE_DIMENSION_TEXTURE2D);
6081 resourceDesc.Width = UINT64(size.width());
6082 resourceDesc.Height = UINT(size.height());
6083 resourceDesc.DepthOrArraySize = isCube ? 6
6084 : (isArray ? UINT(qMax(0, m_arraySize))
6085 : (is3D ? qMax(1, m_depth)
6086 : 1));
6087 resourceDesc.MipLevels = mipLevelCount;
6088 resourceDesc.Format = dxgiFormat;
6089 resourceDesc.SampleDesc = sampleDesc;
6090 resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
6091 resourceDesc.Flags = D3D12_RESOURCE_FLAGS(resourceFlags);
6092 D3D12_CLEAR_VALUE clearValue = {};
6093 clearValue.Format = dxgiFormat;
6094 if (isDepth) {
6095 clearValue.Format = toD3DDepthTextureDSVFormat(m_format);
6096 clearValue.DepthStencil.Depth = 1.0f;
6097 clearValue.DepthStencil.Stencil = 0;
6098 }
6099 ID3D12Resource *resource = nullptr;
6100 D3D12MA::Allocation *allocation = nullptr;
6101 HRESULT hr = rhiD->vma.createResource(D3D12_HEAP_TYPE_DEFAULT,
6102 &resourceDesc,
6103 D3D12_RESOURCE_STATE_COMMON,
6104 needsOptimizedClearValueSpecified ? &clearValue : nullptr,
6105 &allocation,
6106 __uuidof(ID3D12Resource),
6107 reinterpret_cast<void **>(&resource));
6108 if (FAILED(hr)) {
6109 qWarning("Failed to create texture: '%s'"
6110 " Dim was %d Size was %ux%u Depth/ArraySize was %u MipLevels was %u Format was %d Sample count was %d",
6111 qPrintable(QSystemError::windowsComString(hr)),
6112 int(resourceDesc.Dimension),
6113 uint(resourceDesc.Width),
6114 uint(resourceDesc.Height),
6115 uint(resourceDesc.DepthOrArraySize),
6116 uint(resourceDesc.MipLevels),
6117 int(resourceDesc.Format),
6118 int(resourceDesc.SampleDesc.Count));
6119 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
6120 rhiD->deviceLost = true;
6121 return false;
6122 }
6123
6124 handle = QD3D12Resource::addToPool(&rhiD->resourcePool, resource, D3D12_RESOURCE_STATE_COMMON, allocation);
6125
6126 if (!finishCreate())
6127 return false;
6128
6129 rhiD->registerResource(this);
6130 return true;
6131}
6132
6133bool QD3D12Texture::createFrom(QRhiTexture::NativeTexture src)
6134{
6135 if (!src.object)
6136 return false;
6137
6138 if (!prepareCreate())
6139 return false;
6140
6141 ID3D12Resource *resource = reinterpret_cast<ID3D12Resource *>(src.object);
6142 D3D12_RESOURCE_STATES state = D3D12_RESOURCE_STATES(src.layout);
6143
6144 QRHI_RES_RHI(QRhiD3D12);
6145 handle = QD3D12Resource::addNonOwningToPool(&rhiD->resourcePool, resource, state);
6146
6147 if (!finishCreate())
6148 return false;
6149
6150 rhiD->registerResource(this);
6151 return true;
6152}
6153
6154QRhiTexture::NativeTexture QD3D12Texture::nativeTexture()
6155{
6156 QRHI_RES_RHI(QRhiD3D12);
6157 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handle))
6158 return { quint64(res->resource), int(res->state) };
6159
6160 return {};
6161}
6162
6163void QD3D12Texture::setNativeLayout(int layout)
6164{
6165 QRHI_RES_RHI(QRhiD3D12);
6166 if (QD3D12Resource *res = rhiD->resourcePool.lookupRef(handle))
6167 res->state = D3D12_RESOURCE_STATES(layout);
6168}
6169
6170QD3D12Sampler::QD3D12Sampler(QRhiImplementation *rhi, Filter magFilter, Filter minFilter, Filter mipmapMode,
6171 AddressMode u, AddressMode v, AddressMode w)
6172 : QRhiSampler(rhi, magFilter, minFilter, mipmapMode, u, v, w)
6173{
6174}
6175
6176QD3D12Sampler::~QD3D12Sampler()
6177{
6178 destroy();
6179}
6180
6181void QD3D12Sampler::destroy()
6182{
6183 shaderVisibleDescriptor = {};
6184
6185 QRHI_RES_RHI(QRhiD3D12);
6186 if (rhiD)
6187 rhiD->unregisterResource(this);
6188}
6189
6190static inline D3D12_FILTER toD3DFilter(QRhiSampler::Filter minFilter, QRhiSampler::Filter magFilter, QRhiSampler::Filter mipFilter)
6191{
6192 if (minFilter == QRhiSampler::Nearest) {
6193 if (magFilter == QRhiSampler::Nearest) {
6194 if (mipFilter == QRhiSampler::Linear)
6195 return D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR;
6196 else
6197 return D3D12_FILTER_MIN_MAG_MIP_POINT;
6198 } else {
6199 if (mipFilter == QRhiSampler::Linear)
6200 return D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR;
6201 else
6202 return D3D12_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT;
6203 }
6204 } else {
6205 if (magFilter == QRhiSampler::Nearest) {
6206 if (mipFilter == QRhiSampler::Linear)
6207 return D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR;
6208 else
6209 return D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT;
6210 } else {
6211 if (mipFilter == QRhiSampler::Linear)
6212 return D3D12_FILTER_MIN_MAG_MIP_LINEAR;
6213 else
6214 return D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT;
6215 }
6216 }
6217 Q_UNREACHABLE_RETURN(D3D12_FILTER_MIN_MAG_MIP_LINEAR);
6218}
6219
6220static inline D3D12_TEXTURE_ADDRESS_MODE toD3DAddressMode(QRhiSampler::AddressMode m)
6221{
6222 switch (m) {
6223 case QRhiSampler::Repeat:
6224 return D3D12_TEXTURE_ADDRESS_MODE_WRAP;
6225 case QRhiSampler::ClampToEdge:
6226 return D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
6227 case QRhiSampler::Mirror:
6228 return D3D12_TEXTURE_ADDRESS_MODE_MIRROR;
6229 }
6230 Q_UNREACHABLE_RETURN(D3D12_TEXTURE_ADDRESS_MODE_CLAMP);
6231}
6232
6233static inline D3D12_COMPARISON_FUNC toD3DTextureComparisonFunc(QRhiSampler::CompareOp op)
6234{
6235 switch (op) {
6236 case QRhiSampler::Never:
6237 return D3D12_COMPARISON_FUNC_NEVER;
6238 case QRhiSampler::Less:
6239 return D3D12_COMPARISON_FUNC_LESS;
6240 case QRhiSampler::Equal:
6241 return D3D12_COMPARISON_FUNC_EQUAL;
6242 case QRhiSampler::LessOrEqual:
6243 return D3D12_COMPARISON_FUNC_LESS_EQUAL;
6244 case QRhiSampler::Greater:
6245 return D3D12_COMPARISON_FUNC_GREATER;
6246 case QRhiSampler::NotEqual:
6247 return D3D12_COMPARISON_FUNC_NOT_EQUAL;
6248 case QRhiSampler::GreaterOrEqual:
6249 return D3D12_COMPARISON_FUNC_GREATER_EQUAL;
6250 case QRhiSampler::Always:
6251 return D3D12_COMPARISON_FUNC_ALWAYS;
6252 }
6253 Q_UNREACHABLE_RETURN(D3D12_COMPARISON_FUNC_NEVER);
6254}
6255
6256bool QD3D12Sampler::create()
6257{
6258 desc = {};
6259 desc.Filter = toD3DFilter(m_minFilter, m_magFilter, m_mipmapMode);
6260 if (m_compareOp != Never)
6261 desc.Filter = D3D12_FILTER(desc.Filter | 0x80);
6262 desc.AddressU = toD3DAddressMode(m_addressU);
6263 desc.AddressV = toD3DAddressMode(m_addressV);
6264 desc.AddressW = toD3DAddressMode(m_addressW);
6265 desc.MaxAnisotropy = 1.0f;
6266 desc.ComparisonFunc = toD3DTextureComparisonFunc(m_compareOp);
6267 desc.MaxLOD = m_mipmapMode == None ? 0.0f : 10000.0f;
6268
6269 // The shader-visible descriptor is looked up lazily and depends on desc, so
6270 // drop the old one.
6271 shaderVisibleDescriptor = {};
6272
6273 generation += 1;
6274
6275 QRHI_RES_RHI(QRhiD3D12);
6276 rhiD->registerResource(this, false);
6277 return true;
6278}
6279
6280QD3D12Descriptor QD3D12Sampler::lookupOrCreateShaderVisibleDescriptor()
6281{
6282 if (!shaderVisibleDescriptor.isValid()) {
6283 QRHI_RES_RHI(QRhiD3D12);
6284 shaderVisibleDescriptor = rhiD->samplerMgr.getShaderVisibleDescriptor(desc);
6285 }
6286 return shaderVisibleDescriptor;
6287}
6288
6289QD3D12ShadingRateMap::QD3D12ShadingRateMap(QRhiImplementation *rhi)
6290 : QRhiShadingRateMap(rhi)
6291{
6292}
6293
6294QD3D12ShadingRateMap::~QD3D12ShadingRateMap()
6295{
6296 destroy();
6297}
6298
6299void QD3D12ShadingRateMap::destroy()
6300{
6301 if (handle.isNull())
6302 return;
6303
6304 handle = {};
6305}
6306
6307bool QD3D12ShadingRateMap::createFrom(QRhiTexture *src)
6308{
6309 if (!handle.isNull())
6310 destroy();
6311
6312 handle = QRHI_RES(QD3D12Texture, src)->handle;
6313
6314 return true;
6315}
6316
6317QD3D12TextureRenderTarget::QD3D12TextureRenderTarget(QRhiImplementation *rhi,
6318 const QRhiTextureRenderTargetDescription &desc,
6319 Flags flags)
6320 : QRhiTextureRenderTarget(rhi, desc, flags),
6321 d(rhi)
6322{
6323}
6324
6325QD3D12TextureRenderTarget::~QD3D12TextureRenderTarget()
6326{
6327 destroy();
6328}
6329
6330void QD3D12TextureRenderTarget::destroy()
6331{
6332 if (!rtv[0].isValid() && !dsv.isValid())
6333 return;
6334
6335 QRHI_RES_RHI(QRhiD3D12);
6336 if (dsv.isValid()) {
6337 if (ownsDsv && rhiD)
6338 rhiD->releaseQueue.deferredReleaseViews(&rhiD->dsvPool, dsv, 1);
6339 dsv = {};
6340 }
6341
6342 for (int i = 0; i < QD3D12RenderTargetData::MAX_COLOR_ATTACHMENTS; ++i) {
6343 if (rtv[i].isValid()) {
6344 if (ownsRtv[i] && rhiD)
6345 rhiD->releaseQueue.deferredReleaseViews(&rhiD->rtvPool, rtv[i], 1);
6346 rtv[i] = {};
6347 }
6348 }
6349
6350 if (rhiD)
6351 rhiD->unregisterResource(this);
6352}
6353
6354QRhiRenderPassDescriptor *QD3D12TextureRenderTarget::newCompatibleRenderPassDescriptor()
6355{
6356 // not yet built so cannot rely on data computed in create()
6357
6358 QD3D12RenderPassDescriptor *rpD = new QD3D12RenderPassDescriptor(m_rhi);
6359
6360 rpD->colorAttachmentCount = 0;
6361 for (auto it = m_desc.cbeginColorAttachments(), itEnd = m_desc.cendColorAttachments(); it != itEnd; ++it) {
6362 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, it->texture());
6363 QD3D12RenderBuffer *rbD = QRHI_RES(QD3D12RenderBuffer, it->renderBuffer());
6364 if (texD)
6365 rpD->colorFormat[rpD->colorAttachmentCount] = texD->rtFormat;
6366 else if (rbD)
6367 rpD->colorFormat[rpD->colorAttachmentCount] = rbD->dxgiFormat;
6368 rpD->colorAttachmentCount += 1;
6369 }
6370
6371 rpD->hasDepthStencil = false;
6372 if (m_desc.depthStencilBuffer()) {
6373 rpD->hasDepthStencil = true;
6374 rpD->dsFormat = QD3D12RenderBuffer::DS_FORMAT;
6375 } else if (m_desc.depthTexture()) {
6376 QD3D12Texture *depthTexD = QRHI_RES(QD3D12Texture, m_desc.depthTexture());
6377 rpD->hasDepthStencil = true;
6378 rpD->dsFormat = toD3DDepthTextureDSVFormat(depthTexD->format()); // cannot be a typeless format
6379 }
6380
6381 rpD->hasShadingRateMap = m_desc.shadingRateMap() != nullptr;
6382
6383 rpD->updateSerializedFormat();
6384
6385 QRHI_RES_RHI(QRhiD3D12);
6386 rhiD->registerResource(rpD);
6387 return rpD;
6388}
6389
6390bool QD3D12TextureRenderTarget::create()
6391{
6392 if (rtv[0].isValid() || dsv.isValid())
6393 destroy();
6394
6395 QRHI_RES_RHI(QRhiD3D12);
6396 Q_ASSERT(m_desc.colorAttachmentCount() > 0 || m_desc.depthTexture());
6397 Q_ASSERT(!m_desc.depthStencilBuffer() || !m_desc.depthTexture());
6398 const bool hasDepthStencil = m_desc.depthStencilBuffer() || m_desc.depthTexture();
6399 d.colorAttCount = 0;
6400 int attIndex = 0;
6401
6402 for (auto it = m_desc.cbeginColorAttachments(), itEnd = m_desc.cendColorAttachments(); it != itEnd; ++it, ++attIndex) {
6403 d.colorAttCount += 1;
6404 const QRhiColorAttachment &colorAtt(*it);
6405 QRhiTexture *texture = colorAtt.texture();
6406 QRhiRenderBuffer *rb = colorAtt.renderBuffer();
6407 Q_ASSERT(texture || rb);
6408 if (texture) {
6409 QD3D12Texture *texD = QRHI_RES(QD3D12Texture, texture);
6410 QD3D12Resource *res = rhiD->resourcePool.lookupRef(texD->handle);
6411 if (!res) {
6412 qWarning("Could not look up texture handle for render target");
6413 return false;
6414 }
6415 const bool isMultiView = it->multiViewCount() >= 2;
6416 UINT layerCount = isMultiView ? UINT(it->multiViewCount()) : 1;
6417 D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
6418 rtvDesc.Format = texD->rtFormat;
6419 if (texD->flags().testFlag(QRhiTexture::CubeMap)) {
6420 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
6421 rtvDesc.Texture2DArray.MipSlice = UINT(colorAtt.level());
6422 rtvDesc.Texture2DArray.FirstArraySlice = UINT(colorAtt.layer());
6423 rtvDesc.Texture2DArray.ArraySize = layerCount;
6424 } else if (texD->flags().testFlag(QRhiTexture::OneDimensional)) {
6425 if (texD->flags().testFlag(QRhiTexture::TextureArray)) {
6426 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1DARRAY;
6427 rtvDesc.Texture1DArray.MipSlice = UINT(colorAtt.level());
6428 rtvDesc.Texture1DArray.FirstArraySlice = UINT(colorAtt.layer());
6429 rtvDesc.Texture1DArray.ArraySize = layerCount;
6430 } else {
6431 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE1D;
6432 rtvDesc.Texture1D.MipSlice = UINT(colorAtt.level());
6433 }
6434 } else if (texD->flags().testFlag(QRhiTexture::TextureArray)) {
6435 if (texD->sampleDesc.Count > 1) {
6436 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY;
6437 rtvDesc.Texture2DMSArray.FirstArraySlice = UINT(colorAtt.layer());
6438 rtvDesc.Texture2DMSArray.ArraySize = layerCount;
6439 } else {
6440 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
6441 rtvDesc.Texture2DArray.MipSlice = UINT(colorAtt.level());
6442 rtvDesc.Texture2DArray.FirstArraySlice = UINT(colorAtt.layer());
6443 rtvDesc.Texture2DArray.ArraySize = layerCount;
6444 }
6445 } else if (texD->flags().testFlag(QRhiTexture::ThreeDimensional)) {
6446 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D;
6447 rtvDesc.Texture3D.MipSlice = UINT(colorAtt.level());
6448 rtvDesc.Texture3D.FirstWSlice = UINT(colorAtt.layer());
6449 rtvDesc.Texture3D.WSize = layerCount;
6450 } else {
6451 if (texD->sampleDesc.Count > 1) {
6452 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMS;
6453 } else {
6454 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
6455 rtvDesc.Texture2D.MipSlice = UINT(colorAtt.level());
6456 }
6457 }
6458 rtv[attIndex] = rhiD->rtvPool.allocate(1);
6459 if (!rtv[attIndex].isValid()) {
6460 qWarning("Failed to allocate RTV for texture render target");
6461 return false;
6462 }
6463 rhiD->dev->CreateRenderTargetView(res->resource, &rtvDesc, rtv[attIndex].cpuHandle);
6464 ownsRtv[attIndex] = true;
6465 if (attIndex == 0) {
6466 d.pixelSize = rhiD->q->sizeForMipLevel(colorAtt.level(), texD->pixelSize());
6467 d.sampleCount = int(texD->sampleDesc.Count);
6468 }
6469 } else if (rb) {
6470 QD3D12RenderBuffer *rbD = QRHI_RES(QD3D12RenderBuffer, rb);
6471 ownsRtv[attIndex] = false;
6472 rtv[attIndex] = rbD->rtv;
6473 if (attIndex == 0) {
6474 d.pixelSize = rbD->pixelSize();
6475 d.sampleCount = int(rbD->sampleDesc.Count);
6476 }
6477 }
6478 }
6479
6480 d.dpr = 1;
6481
6482 if (hasDepthStencil) {
6483 if (m_desc.depthTexture()) {
6484 ownsDsv = true;
6485 QD3D12Texture *depthTexD = QRHI_RES(QD3D12Texture, m_desc.depthTexture());
6486 QD3D12Resource *res = rhiD->resourcePool.lookupRef(depthTexD->handle);
6487 if (!res) {
6488 qWarning("Could not look up depth texture handle");
6489 return false;
6490 }
6491 D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};
6492 dsvDesc.Format = depthTexD->rtFormat;
6493 const bool isMultisample = depthTexD->sampleDesc.Count > 1;
6494 if (depthTexD->flags().testFlag(QRhiTexture::TextureArray)) {
6495 if (isMultisample) {
6496 dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY;
6497 if (m_desc.depthLayer() >= 0) {
6498 dsvDesc.Texture2DMSArray.FirstArraySlice = UINT(m_desc.depthLayer());
6499 dsvDesc.Texture2DMSArray.ArraySize = 1;
6500 } else if (depthTexD->arrayRangeStart() >= 0 && depthTexD->arrayRangeLength() >= 0) {
6501 dsvDesc.Texture2DMSArray.FirstArraySlice = UINT(depthTexD->arrayRangeStart());
6502 dsvDesc.Texture2DMSArray.ArraySize = UINT(depthTexD->arrayRangeLength());
6503 } else {
6504 dsvDesc.Texture2DMSArray.FirstArraySlice = 0;
6505 dsvDesc.Texture2DMSArray.ArraySize = UINT(qMax(0, depthTexD->arraySize()));
6506 }
6507 } else {
6508 dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY;
6509 if (m_desc.depthLayer() >= 0) {
6510 dsvDesc.Texture2DArray.FirstArraySlice = UINT(m_desc.depthLayer());
6511 dsvDesc.Texture2DArray.ArraySize = 1;
6512 } else if (depthTexD->arrayRangeStart() >= 0 && depthTexD->arrayRangeLength() >= 0) {
6513 dsvDesc.Texture2DArray.FirstArraySlice = UINT(depthTexD->arrayRangeStart());
6514 dsvDesc.Texture2DArray.ArraySize = UINT(depthTexD->arrayRangeLength());
6515 } else {
6516 dsvDesc.Texture2DArray.FirstArraySlice = 0;
6517 dsvDesc.Texture2DArray.ArraySize = UINT(qMax(0, depthTexD->arraySize()));
6518 }
6519 }
6520 }
6521 else {
6522 dsvDesc.ViewDimension = isMultisample ? D3D12_DSV_DIMENSION_TEXTURE2DMS
6523 : D3D12_DSV_DIMENSION_TEXTURE2D;
6524 }
6525 dsv = rhiD->dsvPool.allocate(1);
6526 if (!dsv.isValid()) {
6527 qWarning("Failed to allocate DSV for texture render target");
6528 return false;
6529 }
6530 rhiD->dev->CreateDepthStencilView(res->resource, &dsvDesc, dsv.cpuHandle);
6531 if (d.colorAttCount == 0) {
6532 d.pixelSize = depthTexD->pixelSize();
6533 d.sampleCount = int(depthTexD->sampleDesc.Count);
6534 }
6535 } else {
6536 ownsDsv = false;
6537 QD3D12RenderBuffer *depthRbD = QRHI_RES(QD3D12RenderBuffer, m_desc.depthStencilBuffer());
6538 dsv = depthRbD->dsv;
6539 if (d.colorAttCount == 0) {
6540 d.pixelSize = m_desc.depthStencilBuffer()->pixelSize();
6541 d.sampleCount = int(depthRbD->sampleDesc.Count);
6542 }
6543 }
6544 d.dsAttCount = 1;
6545 } else {
6546 d.dsAttCount = 0;
6547 }
6548
6549 D3D12_CPU_DESCRIPTOR_HANDLE nullDescHandle = { 0 };
6550 for (int i = 0; i < QD3D12RenderTargetData::MAX_COLOR_ATTACHMENTS; ++i)
6551 d.rtv[i] = i < d.colorAttCount ? rtv[i].cpuHandle : nullDescHandle;
6552 d.dsv = dsv.cpuHandle;
6553 d.rp = QRHI_RES(QD3D12RenderPassDescriptor, m_renderPassDesc);
6554
6555 QRhiRenderTargetAttachmentTracker::updateResIdList<QD3D12Texture, QD3D12RenderBuffer>(m_desc, &d.currentResIdList);
6556
6557 rhiD->registerResource(this);
6558 return true;
6559}
6560
6561QSize QD3D12TextureRenderTarget::pixelSize() const
6562{
6563 if (!QRhiRenderTargetAttachmentTracker::isUpToDate<QD3D12Texture, QD3D12RenderBuffer>(m_desc, d.currentResIdList))
6564 const_cast<QD3D12TextureRenderTarget *>(this)->create();
6565
6566 return d.pixelSize;
6567}
6568
6569float QD3D12TextureRenderTarget::devicePixelRatio() const
6570{
6571 return d.dpr;
6572}
6573
6574int QD3D12TextureRenderTarget::sampleCount() const
6575{
6576 return d.sampleCount;
6577}
6578
6579QD3D12ShaderResourceBindings::QD3D12ShaderResourceBindings(QRhiImplementation *rhi)
6580 : QRhiShaderResourceBindings(rhi)
6581{
6582}
6583
6584QD3D12ShaderResourceBindings::~QD3D12ShaderResourceBindings()
6585{
6586 destroy();
6587}
6588
6589void QD3D12ShaderResourceBindings::destroy()
6590{
6591 bindingCache.reset();
6592 bindingCacheValid = false;
6593 boundResourceData.clear();
6594
6595 QRHI_RES_RHI(QRhiD3D12);
6596 if (rhiD)
6597 rhiD->unregisterResource(this);
6598}
6599
6600bool QD3D12ShaderResourceBindings::create()
6601{
6602 QRHI_RES_RHI(QRhiD3D12);
6603 if (!rhiD->sanityCheckShaderResourceBindings(this))
6604 return false;
6605
6606 rhiD->updateLayoutDesc(this);
6607
6608 boundResourceData.resize(m_bindings.count());
6609 for (BoundResourceData &bd : boundResourceData)
6610 bd = {};
6611
6612 bindingCache.reset();
6613 bindingCacheValid = false;
6614
6615 hasDynamicOffset = false;
6616 for (const QRhiShaderResourceBinding &b : std::as_const(m_bindings)) {
6617 const QRhiShaderResourceBinding::Data *bd = QRhiImplementation::shaderResourceBindingData(b);
6618 if (bd->type() == QRhiShaderResourceBinding::UniformBuffer && bd->ubuf().hasDynamicOffset) {
6619 hasDynamicOffset = true;
6620 break;
6621 }
6622 }
6623
6624 // The root signature is not part of the srb. Unintuitive, but the shader
6625 // translation pipeline ties our hands: as long as the per-shader (so per
6626 // stage!) nativeResourceBindingMap exist, meaning f.ex. that a SPIR-V
6627 // combined image sampler binding X passed in here may map to the tY and sY
6628 // HLSL registers, where Y is known only once the mapping table from the
6629 // shader is looked up. Creating a root parameters at this stage is
6630 // therefore impossible.
6631
6632 generation += 1;
6633 rhiD->registerResource(this, false);
6634 return true;
6635}
6636
6637void QD3D12ShaderResourceBindings::updateResources(UpdateFlags flags)
6638{
6639 Q_UNUSED(flags);
6640
6641 Q_ASSERT(boundResourceData.count() == m_bindings.count());
6642 for (BoundResourceData &bd : boundResourceData)
6643 bd = {};
6644
6645 bindingCache.reset();
6646 bindingCacheValid = false;
6647
6648 generation += 1;
6649}
6650
6651// Accessing the QRhiBuffer/Texture/Sampler resources must be avoided in the
6652// callbacks; that would only be possible if the srb had those specified, and
6653// that's not required at the time of srb and pipeline create() time, and
6654// createRootSignature is called from the pipeline create().
6655
6656void QD3D12ShaderResourceBindings::visitUniformBuffer(QD3D12Stage s,
6657 const QRhiShaderResourceBinding::Data::UniformBufferData &,
6658 int shaderRegister,
6659 int)
6660{
6661 D3D12_ROOT_PARAMETER1 rootParam = {};
6662 rootParam.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
6663 rootParam.ShaderVisibility = qd3d12_stageToVisibility(s);
6664 rootParam.Descriptor.ShaderRegister = shaderRegister;
6665 rootParam.Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC;
6666 visitorData.cbParams[s].append(rootParam);
6667}
6668
6669void QD3D12ShaderResourceBindings::visitTextures(QD3D12Stage s,
6670 const QRhiShaderResourceBinding::TextureAndSampler *,
6671 int count,
6672 int baseShaderRegister)
6673{
6674 // An array of textures is one range of count descriptors, not count ranges
6675 // of one: the shader declares the array as a single range and D3D12
6676 // rejects the pipeline unless the range is bound in full.
6677 D3D12_DESCRIPTOR_RANGE1 range = {};
6678 range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
6679 range.NumDescriptors = UINT(count);
6680 range.BaseShaderRegister = baseShaderRegister;
6681 range.OffsetInDescriptorsFromTableStart = visitorData.currentSrvRangeOffset[s];
6682 visitorData.currentSrvRangeOffset[s] += UINT(count);
6683 visitorData.srvRanges[s].append(range);
6684 if (visitorData.srvRanges[s].count() == 1) {
6685 visitorData.srvTables[s].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
6686 visitorData.srvTables[s].ShaderVisibility = qd3d12_stageToVisibility(s);
6687 }
6688}
6689
6690void QD3D12ShaderResourceBindings::visitSamplers(QD3D12Stage s,
6691 const QRhiShaderResourceBinding::TextureAndSampler *,
6692 int count,
6693 int baseShaderRegister)
6694{
6695 // Unlike SRVs and UAVs, samplers are handled so that each binding becomes
6696 // a root parameter with its own descriptor table. An array of samplers is
6697 // one range of count descriptors within that table: shaders declare such
6698 // an array as a single range and D3D12 rejects the pipeline unless the
6699 // range is bound in full.
6700
6701 int &rangeStoreIdx(visitorData.samplerRangeHeads[s]);
6702 if (rangeStoreIdx == 16) {
6703 qWarning("Sampler binding count in QD3D12Stage %d exceeds the limit of 16, this is disallowed by QRhi", s);
6704 return;
6705 }
6706 D3D12_DESCRIPTOR_RANGE1 range = {};
6707 range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER;
6708 range.NumDescriptors = UINT(count);
6709 range.BaseShaderRegister = baseShaderRegister;
6710 visitorData.samplerRanges[s][rangeStoreIdx] = range;
6711 D3D12_ROOT_PARAMETER1 param = {};
6712 param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
6713 param.ShaderVisibility = qd3d12_stageToVisibility(s);
6714 param.DescriptorTable.NumDescriptorRanges = 1;
6715 param.DescriptorTable.pDescriptorRanges = &visitorData.samplerRanges[s][rangeStoreIdx];
6716 rangeStoreIdx += 1;
6717 visitorData.samplerTables[s].append(param);
6718}
6719
6720void QD3D12ShaderResourceBindings::visitStorageBuffer(QD3D12Stage s,
6721 const QRhiShaderResourceBinding::Data::StorageBufferData &,
6722 QD3D12ShaderResourceVisitor::StorageOp,
6723 int shaderRegister)
6724{
6725 D3D12_DESCRIPTOR_RANGE1 range = {};
6726 range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
6727 range.NumDescriptors = 1;
6728 range.BaseShaderRegister = shaderRegister;
6729 range.OffsetInDescriptorsFromTableStart = visitorData.currentUavRangeOffset[s];
6730 visitorData.currentUavRangeOffset[s] += 1;
6731 visitorData.uavRanges[s].append(range);
6732 if (visitorData.uavRanges[s].count() == 1) {
6733 visitorData.uavTables[s].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
6734 visitorData.uavTables[s].ShaderVisibility = qd3d12_stageToVisibility(s);
6735 }
6736}
6737
6738void QD3D12ShaderResourceBindings::visitStorageImage(QD3D12Stage s,
6739 const QRhiShaderResourceBinding::Data::StorageImageData &,
6740 QD3D12ShaderResourceVisitor::StorageOp,
6741 int shaderRegister)
6742{
6743 D3D12_DESCRIPTOR_RANGE1 range = {};
6744 range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
6745 range.NumDescriptors = 1;
6746 range.BaseShaderRegister = shaderRegister;
6747 range.OffsetInDescriptorsFromTableStart = visitorData.currentUavRangeOffset[s];
6748 visitorData.currentUavRangeOffset[s] += 1;
6749 visitorData.uavRanges[s].append(range);
6750 if (visitorData.uavRanges[s].count() == 1) {
6751 visitorData.uavTables[s].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
6752 visitorData.uavTables[s].ShaderVisibility = qd3d12_stageToVisibility(s);
6753 }
6754}
6755
6756static void qd3d12_setPushConstantInfo(QD3D12ShaderStageData *sd, const QShader &shader, const QShaderKey &key)
6757{
6758 const QList<QShaderDescription::PushConstantBlock> blocks = shader.description().pushConstantBlocks();
6759 if (blocks.isEmpty())
6760 return;
6761 sd->pushConstantRegister = shader.nativeShaderInfo(key).extraBufferBindings.value(
6762 QShaderPrivate::HlslPushConstantBufferBinding, -1);
6763 sd->pushConstantSize = quint32((blocks.first().size + 3) & ~3);
6764}
6765
6766QD3D12ObjectHandle QD3D12ShaderResourceBindings::createRootSignature(const QD3D12ShaderStageData *stageData,
6767 int stageCount)
6768{
6769 QRHI_RES_RHI(QRhiD3D12);
6770
6771 // It's not just that the root signature has to be tied to the pipeline
6772 // (cannot just freely create it like e.g. with Vulkan where one just
6773 // creates a descriptor layout 1:1 with the QRhiShaderResourceBindings'
6774 // data), due to not knowing the shader-specific resource binding mapping
6775 // tables at the point of srb creation, but each shader stage may have a
6776 // different mapping table. (ugh!)
6777 //
6778 // Hence we set up everything per-stage, even if it means the root
6779 // signature gets unnecessarily big. (note that the magic is in the
6780 // ShaderVisibility: even though the register range is the same in the
6781 // descriptor tables, the visibility is different)
6782
6783 QD3D12ShaderResourceVisitor visitor(this, stageData, stageCount);
6784
6785 visitorData = {};
6786
6787 using namespace std::placeholders;
6788 visitor.uniformBuffer = std::bind(&QD3D12ShaderResourceBindings::visitUniformBuffer, this, _1, _2, _3, _4);
6789 visitor.textures = std::bind(&QD3D12ShaderResourceBindings::visitTextures, this, _1, _2, _3, _4);
6790 visitor.samplers = std::bind(&QD3D12ShaderResourceBindings::visitSamplers, this, _1, _2, _3, _4);
6791 visitor.storageBuffer = std::bind(&QD3D12ShaderResourceBindings::visitStorageBuffer, this, _1, _2, _3, _4);
6792 visitor.storageImage = std::bind(&QD3D12ShaderResourceBindings::visitStorageImage, this, _1, _2, _3, _4);
6793
6794 visitor.visit();
6795
6796 // The maximum size of a root signature is 256 bytes, where a descriptor
6797 // table is 4, a root descriptor (e.g. CBV) is 8. We have 5 stages at most
6798 // (or 1 with compute) and a separate descriptor table for SRVs (->
6799 // textures) and UAVs (-> storage buffers and images) per stage, plus each
6800 // uniform buffer counts as a CBV in the stages it is visible.
6801 //
6802 // Due to the limited maximum size of a shader-visible sampler heap (2048)
6803 // and the potential costly switching of descriptor heaps, each sampler is
6804 // declared as a separate root parameter / descriptor table (meaning that
6805 // two samplers in the same stage are two parameters and two tables, not
6806 // just one). QRhi documents a hard limit of 16 on texture/sampler bindings
6807 // in a shader (matching D3D11), so we can hopefully get away with this.
6808 //
6809 // This means that e.g. a vertex+fragment shader with a uniform buffer
6810 // visible in both and one texture+sampler in the fragment shader would
6811 // consume 2*8 + 4 + 4 = 24 bytes. This also implies that clients
6812 // specifying the minimal stage bit mask for each entry in
6813 // QRhiShaderResourceBindings are ideal for this backend since it helps
6814 // reducing the chance of hitting the size limit.
6815
6816 QVarLengthArray<D3D12_ROOT_PARAMETER1, 4> rootParams;
6817 for (int s = 0; s < 6; ++s) {
6818 if (!visitorData.cbParams[s].isEmpty())
6819 rootParams.append(visitorData.cbParams[s].constData(), visitorData.cbParams[s].count());
6820 }
6821 for (int s = 0; s < 6; ++s) {
6822 if (!visitorData.srvRanges[s].isEmpty()) {
6823 visitorData.srvTables[s].DescriptorTable.NumDescriptorRanges = visitorData.srvRanges[s].count();
6824 visitorData.srvTables[s].DescriptorTable.pDescriptorRanges = visitorData.srvRanges[s].constData();
6825 rootParams.append(visitorData.srvTables[s]);
6826 }
6827 }
6828 for (int s = 0; s < 6; ++s) {
6829 if (!visitorData.samplerTables[s].isEmpty())
6830 rootParams.append(visitorData.samplerTables[s].constData(), visitorData.samplerTables[s].count());
6831 }
6832 for (int s = 0; s < 6; ++s) {
6833 if (!visitorData.uavRanges[s].isEmpty()) {
6834 visitorData.uavTables[s].DescriptorTable.NumDescriptorRanges = visitorData.uavRanges[s].count();
6835 visitorData.uavTables[s].DescriptorTable.pDescriptorRanges = visitorData.uavRanges[s].constData();
6836 rootParams.append(visitorData.uavTables[s]);
6837 }
6838 }
6839
6840 // Root constants go last so that the indices of everything above, which
6841 // the draw time code recomputes by walking the same order, are unaffected.
6842 pushConstantRootParamIndex = -1;
6843 UINT pushConstantReg = 0;
6844 quint32 pushConstantSize = 0;
6845 int pushConstantStages = 0;
6846 D3D12_SHADER_VISIBILITY pushConstantVis = D3D12_SHADER_VISIBILITY_ALL;
6847 for (int stageIdx = 0; stageIdx < stageCount; ++stageIdx) {
6848 const QD3D12ShaderStageData &sd(stageData[stageIdx]);
6849 if (!sd.valid || !sd.pushConstantSize || sd.pushConstantRegister < 0)
6850 continue;
6851 pushConstantReg = UINT(sd.pushConstantRegister);
6852 pushConstantSize = qMax(pushConstantSize, sd.pushConstantSize);
6853 pushConstantVis = qd3d12_stageToVisibility(sd.stage);
6854 ++pushConstantStages;
6855 }
6856 if (pushConstantSize) {
6857 // Assumes nothing else uses the push constant register (b0 as
6858 // reserved by qsb); a stage without a block would get its uniform
6859 // block there and root signature creation would fail.
6860 D3D12_ROOT_PARAMETER1 param = {};
6861 param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
6862 param.ShaderVisibility = pushConstantStages > 1 ? D3D12_SHADER_VISIBILITY_ALL : pushConstantVis;
6863 param.Constants.ShaderRegister = pushConstantReg;
6864 param.Constants.Num32BitValues = pushConstantSize / 4;
6865 pushConstantRootParamIndex = rootParams.count();
6866 rootParams.append(param);
6867 }
6868
6869 D3D12_VERSIONED_ROOT_SIGNATURE_DESC rsDesc = {};
6870 rsDesc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
6871 if (!rootParams.isEmpty()) {
6872 rsDesc.Desc_1_1.NumParameters = rootParams.count();
6873 rsDesc.Desc_1_1.pParameters = rootParams.constData();
6874 }
6875
6876 UINT rsFlags = 0;
6877 for (int stageIdx = 0; stageIdx < stageCount; ++stageIdx) {
6878 if (stageData[stageIdx].valid && stageData[stageIdx].stage == VS)
6879 rsFlags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
6880 }
6881 rsDesc.Desc_1_1.Flags = D3D12_ROOT_SIGNATURE_FLAGS(rsFlags);
6882
6883 ID3DBlob *signature = nullptr;
6884 HRESULT hr = D3D12SerializeVersionedRootSignature(&rsDesc, &signature, nullptr);
6885 if (FAILED(hr)) {
6886 qWarning("Failed to serialize root signature: %s", qPrintable(QSystemError::windowsComString(hr)));
6887 return {};
6888 }
6889 ID3D12RootSignature *rootSig = nullptr;
6890 hr = rhiD->dev->CreateRootSignature(0,
6891 signature->GetBufferPointer(),
6892 signature->GetBufferSize(),
6893 __uuidof(ID3D12RootSignature),
6894 reinterpret_cast<void **>(&rootSig));
6895 signature->Release();
6896 if (FAILED(hr)) {
6897 qWarning("Failed to create root signature: %s", qPrintable(QSystemError::windowsComString(hr)));
6898 return {};
6899 }
6900
6901 return QD3D12RootSignature::addToPool(&rhiD->rootSignaturePool, rootSig);
6902}
6903
6904// For shader model < 6.0 we do the same as the D3D11 backend: use the old
6905// compiler (D3DCompile) to generate DXBC, just as qsb does (when -c is passed)
6906// by invoking fxc, not dxc. For SM >= 6.0 we have to use the new compiler and
6907// work with DXIL. And that involves IDxcCompiler and needs the presence of
6908// dxcompiler.dll and dxil.dll at runtime. Plus there's a chance we have
6909// ancient SDK headers when not using MSVC. So this is heavily optional,
6910// meaning support for dxc can be disabled both at build time (no dxcapi.h) and
6911// at run time (no DLLs).
6912
6913static inline void makeHlslTargetString(char target[7], const char stage[3], int version)
6914{
6915 const int smMajor = version / 10;
6916 const int smMinor = version % 10;
6917 target[0] = stage[0];
6918 target[1] = stage[1];
6919 target[2] = '_';
6920 target[3] = '0' + smMajor;
6921 target[4] = '_';
6922 target[5] = '0' + smMinor;
6923 target[6] = '\0';
6924}
6925
6926enum class HlslCompileFlag
6927{
6928 WithDebugInfo = 0x01
6929};
6930
6931static QByteArray legacyCompile(const QShaderCode &hlslSource, const char *target, int flags, QString *error)
6932{
6933 static const pD3DCompile d3dCompile = QRhiD3D::resolveD3DCompile();
6934 if (!d3dCompile) {
6935 qWarning("Unable to resolve function D3DCompile()");
6936 return QByteArray();
6937 }
6938
6939 ID3DBlob *bytecode = nullptr;
6940 ID3DBlob *errors = nullptr;
6941 UINT d3dCompileFlags = 0;
6942 if (flags & int(HlslCompileFlag::WithDebugInfo))
6943 d3dCompileFlags |= D3DCOMPILE_DEBUG;
6944
6945 HRESULT hr = d3dCompile(hlslSource.shader().constData(), SIZE_T(hlslSource.shader().size()),
6946 nullptr, nullptr, nullptr,
6947 hlslSource.entryPoint().constData(), target, d3dCompileFlags, 0, &bytecode, &errors);
6948 if (FAILED(hr) || !bytecode) {
6949 qWarning("HLSL shader compilation failed: 0x%x", uint(hr));
6950 if (errors) {
6951 *error = QString::fromUtf8(static_cast<const char *>(errors->GetBufferPointer()),
6952 int(errors->GetBufferSize()));
6953 errors->Release();
6954 }
6955 return QByteArray();
6956 }
6957
6958 QByteArray result;
6959 result.resize(int(bytecode->GetBufferSize()));
6960 memcpy(result.data(), bytecode->GetBufferPointer(), size_t(result.size()));
6961 bytecode->Release();
6962 return result;
6963}
6964
6965#ifdef QRHI_D3D12_HAS_DXC
6966
6967#ifndef DXC_CP_UTF8
6968#define DXC_CP_UTF8 65001
6969#endif
6970
6971#ifndef DXC_ARG_DEBUG
6972#define DXC_ARG_DEBUG L"-Zi"
6973#endif
6974
6975static QByteArray dxcCompile(const QShaderCode &hlslSource, const char *target, int flags, QString *error)
6976{
6977 static std::pair<IDxcCompiler *, IDxcLibrary *> dxc = QRhiD3D::createDxcCompiler();
6978 IDxcCompiler *compiler = dxc.first;
6979 if (!compiler) {
6980 qWarning("Unable to instantiate IDxcCompiler. Likely no dxcompiler.dll and dxil.dll present. "
6981 "Use windeployqt or try https://github.com/microsoft/DirectXShaderCompiler/releases");
6982 return QByteArray();
6983 }
6984 IDxcLibrary *library = dxc.second;
6985 if (!library)
6986 return QByteArray();
6987
6988 IDxcBlobEncoding *sourceBlob = nullptr;
6989 HRESULT hr = library->CreateBlobWithEncodingOnHeapCopy(hlslSource.shader().constData(),
6990 UINT32(hlslSource.shader().size()),
6991 DXC_CP_UTF8,
6992 &sourceBlob);
6993 if (FAILED(hr)) {
6994 qWarning("Failed to create source blob for dxc: 0x%x (%s)",
6995 uint(hr),
6996 qPrintable(QSystemError::windowsComString(hr)));
6997 return QByteArray();
6998 }
6999
7000 const QString entryPointStr = QString::fromLatin1(hlslSource.entryPoint());
7001 const QString targetStr = QString::fromLatin1(target);
7002
7003 QVarLengthArray<LPCWSTR, 4> argPtrs;
7004 QString debugArg;
7005 if (flags & int(HlslCompileFlag::WithDebugInfo)) {
7006 debugArg = QString::fromUtf16(reinterpret_cast<const char16_t *>(DXC_ARG_DEBUG));
7007 argPtrs.append(reinterpret_cast<LPCWSTR>(debugArg.utf16()));
7008 }
7009
7010 IDxcOperationResult *result = nullptr;
7011 hr = compiler->Compile(sourceBlob,
7012 nullptr,
7013 reinterpret_cast<LPCWSTR>(entryPointStr.utf16()),
7014 reinterpret_cast<LPCWSTR>(targetStr.utf16()),
7015 argPtrs.data(), argPtrs.count(),
7016 nullptr, 0,
7017 nullptr,
7018 &result);
7019 sourceBlob->Release();
7020 if (SUCCEEDED(hr))
7021 result->GetStatus(&hr);
7022 if (FAILED(hr)) {
7023 qWarning("HLSL shader compilation failed: 0x%x (%s)",
7024 uint(hr),
7025 qPrintable(QSystemError::windowsComString(hr)));
7026 if (result) {
7027 IDxcBlobEncoding *errorsBlob = nullptr;
7028 if (SUCCEEDED(result->GetErrorBuffer(&errorsBlob))) {
7029 if (errorsBlob) {
7030 *error = QString::fromUtf8(static_cast<const char *>(errorsBlob->GetBufferPointer()),
7031 int(errorsBlob->GetBufferSize()));
7032 errorsBlob->Release();
7033 }
7034 }
7035 }
7036 return QByteArray();
7037 }
7038
7039 IDxcBlob *bytecode = nullptr;
7040 if FAILED(result->GetResult(&bytecode)) {
7041 qWarning("No result from IDxcCompiler: 0x%x (%s)",
7042 uint(hr),
7043 qPrintable(QSystemError::windowsComString(hr)));
7044 return QByteArray();
7045 }
7046
7047 QByteArray ba;
7048 ba.resize(int(bytecode->GetBufferSize()));
7049 memcpy(ba.data(), bytecode->GetBufferPointer(), size_t(ba.size()));
7050 bytecode->Release();
7051 return ba;
7052}
7053
7054#endif // QRHI_D3D12_HAS_DXC
7055
7056static QByteArray compileHlslShaderSource(const QShader &shader,
7057 QShader::Variant shaderVariant,
7058 int flags,
7059 QString *error,
7060 QShaderKey *usedShaderKey)
7061{
7062 // look for SM 6.7, 6.6, .., 5.0
7063 const int shaderModelMax = 67;
7064 for (int sm = shaderModelMax; sm >= 50; --sm) {
7065 for (QShader::Source type : { QShader::DxilShader, QShader::DxbcShader }) {
7066 QShaderKey key = { type, sm, shaderVariant };
7067 QShaderCode intermediateBytecodeShader = shader.shader(key);
7068 if (!intermediateBytecodeShader.shader().isEmpty()) {
7069 if (usedShaderKey)
7070 *usedShaderKey = key;
7071 return intermediateBytecodeShader.shader();
7072 }
7073 }
7074 }
7075
7076 QShaderCode hlslSource;
7077 QShaderKey key;
7078 for (int sm = shaderModelMax; sm >= 50; --sm) {
7079 key = { QShader::HlslShader, sm, shaderVariant };
7080 hlslSource = shader.shader(key);
7081 if (!hlslSource.shader().isEmpty())
7082 break;
7083 }
7084
7085 if (hlslSource.shader().isEmpty()) {
7086 qWarning() << "No HLSL (shader model 6.7..5.0) code found in baked shader" << shader;
7087 return QByteArray();
7088 }
7089
7090 if (usedShaderKey)
7091 *usedShaderKey = key;
7092
7093 char target[7];
7094 switch (shader.stage()) {
7095 case QShader::VertexStage:
7096 makeHlslTargetString(target, "vs", key.sourceVersion().version());
7097 break;
7098 case QShader::TessellationControlStage:
7099 makeHlslTargetString(target, "hs", key.sourceVersion().version());
7100 break;
7101 case QShader::TessellationEvaluationStage:
7102 makeHlslTargetString(target, "ds", key.sourceVersion().version());
7103 break;
7104 case QShader::GeometryStage:
7105 makeHlslTargetString(target, "gs", key.sourceVersion().version());
7106 break;
7107 case QShader::FragmentStage:
7108 makeHlslTargetString(target, "ps", key.sourceVersion().version());
7109 break;
7110 case QShader::ComputeStage:
7111 makeHlslTargetString(target, "cs", key.sourceVersion().version());
7112 break;
7113 default:
7114 qWarning("compileHlslShaderSource: Unknown stage (%d)", int(shader.stage()));
7115 return QByteArray();
7116 }
7117
7118 if (key.sourceVersion().version() >= 60) {
7119#ifdef QRHI_D3D12_HAS_DXC
7120 return dxcCompile(hlslSource, target, flags, error);
7121#else
7122 qWarning("Attempted to runtime-compile HLSL source code for shader model >= 6.0 "
7123 "but the Qt build has no support for DXC. "
7124 "Rebuild Qt with a recent Windows SDK or switch to an MSVC build.");
7125#endif
7126 }
7127
7128 return legacyCompile(hlslSource, target, flags, error);
7129}
7130
7131static inline UINT8 toD3DColorWriteMask(QRhiGraphicsPipeline::ColorMask c)
7132{
7133 UINT8 f = 0;
7134 if (c.testFlag(QRhiGraphicsPipeline::R))
7135 f |= D3D12_COLOR_WRITE_ENABLE_RED;
7136 if (c.testFlag(QRhiGraphicsPipeline::G))
7137 f |= D3D12_COLOR_WRITE_ENABLE_GREEN;
7138 if (c.testFlag(QRhiGraphicsPipeline::B))
7139 f |= D3D12_COLOR_WRITE_ENABLE_BLUE;
7140 if (c.testFlag(QRhiGraphicsPipeline::A))
7141 f |= D3D12_COLOR_WRITE_ENABLE_ALPHA;
7142 return f;
7143}
7144
7145static inline D3D12_BLEND toD3DBlendFactor(QRhiGraphicsPipeline::BlendFactor f, bool rgb)
7146{
7147 // SrcBlendAlpha and DstBlendAlpha do not accept *_COLOR. With other APIs
7148 // this is handled internally (so that e.g. VK_BLEND_FACTOR_SRC_COLOR is
7149 // accepted and is in effect equivalent to VK_BLEND_FACTOR_SRC_ALPHA when
7150 // set as an alpha src/dest factor), but for D3D we have to take care of it
7151 // ourselves. Hence the rgb argument.
7152
7153 switch (f) {
7154 case QRhiGraphicsPipeline::Zero:
7155 return D3D12_BLEND_ZERO;
7156 case QRhiGraphicsPipeline::One:
7157 return D3D12_BLEND_ONE;
7158 case QRhiGraphicsPipeline::SrcColor:
7159 return rgb ? D3D12_BLEND_SRC_COLOR : D3D12_BLEND_SRC_ALPHA;
7160 case QRhiGraphicsPipeline::OneMinusSrcColor:
7161 return rgb ? D3D12_BLEND_INV_SRC_COLOR : D3D12_BLEND_INV_SRC_ALPHA;
7162 case QRhiGraphicsPipeline::DstColor:
7163 return rgb ? D3D12_BLEND_DEST_COLOR : D3D12_BLEND_DEST_ALPHA;
7164 case QRhiGraphicsPipeline::OneMinusDstColor:
7165 return rgb ? D3D12_BLEND_INV_DEST_COLOR : D3D12_BLEND_INV_DEST_ALPHA;
7166 case QRhiGraphicsPipeline::SrcAlpha:
7167 return D3D12_BLEND_SRC_ALPHA;
7168 case QRhiGraphicsPipeline::OneMinusSrcAlpha:
7169 return D3D12_BLEND_INV_SRC_ALPHA;
7170 case QRhiGraphicsPipeline::DstAlpha:
7171 return D3D12_BLEND_DEST_ALPHA;
7172 case QRhiGraphicsPipeline::OneMinusDstAlpha:
7173 return D3D12_BLEND_INV_DEST_ALPHA;
7174 case QRhiGraphicsPipeline::ConstantColor:
7175 case QRhiGraphicsPipeline::ConstantAlpha:
7176 return D3D12_BLEND_BLEND_FACTOR;
7177 case QRhiGraphicsPipeline::OneMinusConstantColor:
7178 case QRhiGraphicsPipeline::OneMinusConstantAlpha:
7179 return D3D12_BLEND_INV_BLEND_FACTOR;
7180 case QRhiGraphicsPipeline::SrcAlphaSaturate:
7181 return D3D12_BLEND_SRC_ALPHA_SAT;
7182 case QRhiGraphicsPipeline::Src1Color:
7183 return rgb ? D3D12_BLEND_SRC1_COLOR : D3D12_BLEND_SRC1_ALPHA;
7184 case QRhiGraphicsPipeline::OneMinusSrc1Color:
7185 return rgb ? D3D12_BLEND_INV_SRC1_COLOR : D3D12_BLEND_INV_SRC1_ALPHA;
7186 case QRhiGraphicsPipeline::Src1Alpha:
7187 return D3D12_BLEND_SRC1_ALPHA;
7188 case QRhiGraphicsPipeline::OneMinusSrc1Alpha:
7189 return D3D12_BLEND_INV_SRC1_ALPHA;
7190 }
7191 Q_UNREACHABLE_RETURN(D3D12_BLEND_ZERO);
7192}
7193
7194static inline D3D12_BLEND_OP toD3DBlendOp(QRhiGraphicsPipeline::BlendOp op)
7195{
7196 switch (op) {
7197 case QRhiGraphicsPipeline::Add:
7198 return D3D12_BLEND_OP_ADD;
7199 case QRhiGraphicsPipeline::Subtract:
7200 return D3D12_BLEND_OP_SUBTRACT;
7201 case QRhiGraphicsPipeline::ReverseSubtract:
7202 return D3D12_BLEND_OP_REV_SUBTRACT;
7203 case QRhiGraphicsPipeline::Min:
7204 return D3D12_BLEND_OP_MIN;
7205 case QRhiGraphicsPipeline::Max:
7206 return D3D12_BLEND_OP_MAX;
7207 }
7208 Q_UNREACHABLE_RETURN(D3D12_BLEND_OP_ADD);
7209}
7210
7211static inline D3D12_CULL_MODE toD3DCullMode(QRhiGraphicsPipeline::CullMode c)
7212{
7213 switch (c) {
7214 case QRhiGraphicsPipeline::None:
7215 return D3D12_CULL_MODE_NONE;
7216 case QRhiGraphicsPipeline::Front:
7217 return D3D12_CULL_MODE_FRONT;
7218 case QRhiGraphicsPipeline::Back:
7219 return D3D12_CULL_MODE_BACK;
7220 }
7221 Q_UNREACHABLE_RETURN(D3D12_CULL_MODE_NONE);
7222}
7223
7224static inline D3D12_FILL_MODE toD3DFillMode(QRhiGraphicsPipeline::PolygonMode mode)
7225{
7226 switch (mode) {
7227 case QRhiGraphicsPipeline::Fill:
7228 return D3D12_FILL_MODE_SOLID;
7229 case QRhiGraphicsPipeline::Line:
7230 return D3D12_FILL_MODE_WIREFRAME;
7231 }
7232 Q_UNREACHABLE_RETURN(D3D12_FILL_MODE_SOLID);
7233}
7234
7235static inline D3D12_COMPARISON_FUNC toD3DCompareOp(QRhiGraphicsPipeline::CompareOp op)
7236{
7237 switch (op) {
7238 case QRhiGraphicsPipeline::Never:
7239 return D3D12_COMPARISON_FUNC_NEVER;
7240 case QRhiGraphicsPipeline::Less:
7241 return D3D12_COMPARISON_FUNC_LESS;
7242 case QRhiGraphicsPipeline::Equal:
7243 return D3D12_COMPARISON_FUNC_EQUAL;
7244 case QRhiGraphicsPipeline::LessOrEqual:
7245 return D3D12_COMPARISON_FUNC_LESS_EQUAL;
7246 case QRhiGraphicsPipeline::Greater:
7247 return D3D12_COMPARISON_FUNC_GREATER;
7248 case QRhiGraphicsPipeline::NotEqual:
7249 return D3D12_COMPARISON_FUNC_NOT_EQUAL;
7250 case QRhiGraphicsPipeline::GreaterOrEqual:
7251 return D3D12_COMPARISON_FUNC_GREATER_EQUAL;
7252 case QRhiGraphicsPipeline::Always:
7253 return D3D12_COMPARISON_FUNC_ALWAYS;
7254 }
7255 Q_UNREACHABLE_RETURN(D3D12_COMPARISON_FUNC_ALWAYS);
7256}
7257
7258static inline D3D12_STENCIL_OP toD3DStencilOp(QRhiGraphicsPipeline::StencilOp op)
7259{
7260 switch (op) {
7261 case QRhiGraphicsPipeline::StencilZero:
7262 return D3D12_STENCIL_OP_ZERO;
7263 case QRhiGraphicsPipeline::Keep:
7264 return D3D12_STENCIL_OP_KEEP;
7265 case QRhiGraphicsPipeline::Replace:
7266 return D3D12_STENCIL_OP_REPLACE;
7267 case QRhiGraphicsPipeline::IncrementAndClamp:
7268 return D3D12_STENCIL_OP_INCR_SAT;
7269 case QRhiGraphicsPipeline::DecrementAndClamp:
7270 return D3D12_STENCIL_OP_DECR_SAT;
7271 case QRhiGraphicsPipeline::Invert:
7272 return D3D12_STENCIL_OP_INVERT;
7273 case QRhiGraphicsPipeline::IncrementAndWrap:
7274 return D3D12_STENCIL_OP_INCR;
7275 case QRhiGraphicsPipeline::DecrementAndWrap:
7276 return D3D12_STENCIL_OP_DECR;
7277 }
7278 Q_UNREACHABLE_RETURN(D3D12_STENCIL_OP_KEEP);
7279}
7280
7281static inline D3D12_PRIMITIVE_TOPOLOGY toD3DTopology(QRhiGraphicsPipeline::Topology t, int patchControlPointCount)
7282{
7283 switch (t) {
7284 case QRhiGraphicsPipeline::Triangles:
7285 return D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
7286 case QRhiGraphicsPipeline::TriangleStrip:
7287 return D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
7288 case QRhiGraphicsPipeline::TriangleFan:
7289 qWarning("Triangle fans are not supported with D3D");
7290 return D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
7291 case QRhiGraphicsPipeline::Lines:
7292 return D3D_PRIMITIVE_TOPOLOGY_LINELIST;
7293 case QRhiGraphicsPipeline::LineStrip:
7294 return D3D_PRIMITIVE_TOPOLOGY_LINESTRIP;
7295 case QRhiGraphicsPipeline::Points:
7296 return D3D_PRIMITIVE_TOPOLOGY_POINTLIST;
7297 case QRhiGraphicsPipeline::Patches:
7298 Q_ASSERT(patchControlPointCount >= 1 && patchControlPointCount <= 32);
7299 return D3D_PRIMITIVE_TOPOLOGY(D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST + (patchControlPointCount - 1));
7300 }
7301 Q_UNREACHABLE_RETURN(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
7302}
7303
7304static inline D3D12_PRIMITIVE_TOPOLOGY_TYPE toD3DTopologyType(QRhiGraphicsPipeline::Topology t)
7305{
7306 switch (t) {
7307 case QRhiGraphicsPipeline::Triangles:
7308 case QRhiGraphicsPipeline::TriangleStrip:
7309 case QRhiGraphicsPipeline::TriangleFan:
7310 return D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
7311 case QRhiGraphicsPipeline::Lines:
7312 case QRhiGraphicsPipeline::LineStrip:
7313 return D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE;
7314 case QRhiGraphicsPipeline::Points:
7315 return D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT;
7316 case QRhiGraphicsPipeline::Patches:
7317 return D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH;
7318 }
7319 Q_UNREACHABLE_RETURN(D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE);
7320}
7321
7322static inline DXGI_FORMAT toD3DAttributeFormat(QRhiVertexInputAttribute::Format format)
7323{
7324 switch (format) {
7325 case QRhiVertexInputAttribute::Float4:
7326 return DXGI_FORMAT_R32G32B32A32_FLOAT;
7327 case QRhiVertexInputAttribute::Float3:
7328 return DXGI_FORMAT_R32G32B32_FLOAT;
7329 case QRhiVertexInputAttribute::Float2:
7330 return DXGI_FORMAT_R32G32_FLOAT;
7331 case QRhiVertexInputAttribute::Float:
7332 return DXGI_FORMAT_R32_FLOAT;
7333 case QRhiVertexInputAttribute::UNormByte4:
7334 return DXGI_FORMAT_R8G8B8A8_UNORM;
7335 case QRhiVertexInputAttribute::UNormByte2:
7336 return DXGI_FORMAT_R8G8_UNORM;
7337 case QRhiVertexInputAttribute::UNormByte:
7338 return DXGI_FORMAT_R8_UNORM;
7339 case QRhiVertexInputAttribute::UInt4:
7340 return DXGI_FORMAT_R32G32B32A32_UINT;
7341 case QRhiVertexInputAttribute::UInt3:
7342 return DXGI_FORMAT_R32G32B32_UINT;
7343 case QRhiVertexInputAttribute::UInt2:
7344 return DXGI_FORMAT_R32G32_UINT;
7345 case QRhiVertexInputAttribute::UInt:
7346 return DXGI_FORMAT_R32_UINT;
7347 case QRhiVertexInputAttribute::SInt4:
7348 return DXGI_FORMAT_R32G32B32A32_SINT;
7349 case QRhiVertexInputAttribute::SInt3:
7350 return DXGI_FORMAT_R32G32B32_SINT;
7351 case QRhiVertexInputAttribute::SInt2:
7352 return DXGI_FORMAT_R32G32_SINT;
7353 case QRhiVertexInputAttribute::SInt:
7354 return DXGI_FORMAT_R32_SINT;
7355 case QRhiVertexInputAttribute::Half4:
7356 // Note: D3D does not support half3. Pass through half3 as half4.
7357 case QRhiVertexInputAttribute::Half3:
7358 return DXGI_FORMAT_R16G16B16A16_FLOAT;
7359 case QRhiVertexInputAttribute::Half2:
7360 return DXGI_FORMAT_R16G16_FLOAT;
7361 case QRhiVertexInputAttribute::Half:
7362 return DXGI_FORMAT_R16_FLOAT;
7363 case QRhiVertexInputAttribute::UShort4:
7364 // Note: D3D does not support UShort3. Pass through UShort3 as UShort4.
7365 case QRhiVertexInputAttribute::UShort3:
7366 return DXGI_FORMAT_R16G16B16A16_UINT;
7367 case QRhiVertexInputAttribute::UShort2:
7368 return DXGI_FORMAT_R16G16_UINT;
7369 case QRhiVertexInputAttribute::UShort:
7370 return DXGI_FORMAT_R16_UINT;
7371 case QRhiVertexInputAttribute::SShort4:
7372 // Note: D3D does not support SShort3. Pass through SShort3 as SShort4.
7373 case QRhiVertexInputAttribute::SShort3:
7374 return DXGI_FORMAT_R16G16B16A16_SINT;
7375 case QRhiVertexInputAttribute::SShort2:
7376 return DXGI_FORMAT_R16G16_SINT;
7377 case QRhiVertexInputAttribute::SShort:
7378 return DXGI_FORMAT_R16_SINT;
7379 }
7380 Q_UNREACHABLE_RETURN(DXGI_FORMAT_R32G32B32A32_FLOAT);
7381}
7382
7383QD3D12GraphicsPipeline::QD3D12GraphicsPipeline(QRhiImplementation *rhi)
7384 : QRhiGraphicsPipeline(rhi)
7385{
7386}
7387
7388QD3D12GraphicsPipeline::~QD3D12GraphicsPipeline()
7389{
7390 destroy();
7391}
7392
7393void QD3D12GraphicsPipeline::destroy()
7394{
7395 if (handle.isNull())
7396 return;
7397
7398 QRHI_RES_RHI(QRhiD3D12);
7399 if (rhiD) {
7400 rhiD->releaseQueue.deferredReleasePipeline(handle);
7401 rhiD->releaseQueue.deferredReleaseRootSignature(rootSigHandle);
7402 }
7403
7404 handle = {};
7405 stageData = {};
7406
7407 if (rhiD)
7408 rhiD->unregisterResource(this);
7409}
7410
7411bool QD3D12GraphicsPipeline::create()
7412{
7413 if (!handle.isNull())
7414 destroy();
7415
7416 QRHI_RES_RHI(QRhiD3D12);
7417 if (!rhiD->sanityCheckGraphicsPipeline(this))
7418 return false;
7419
7420 rhiD->pipelineCreationStart();
7421
7422 QByteArray shaderBytecode[5];
7423 for (const QRhiShaderStage &shaderStage : std::as_const(m_shaderStages)) {
7424 const QD3D12Stage d3dStage = qd3d12_stage(shaderStage.type());
7425 stageData[d3dStage].valid = true;
7426 stageData[d3dStage].stage = d3dStage;
7427 auto cacheIt = rhiD->shaderBytecodeCache.data.constFind(shaderStage);
7428 if (cacheIt != rhiD->shaderBytecodeCache.data.constEnd()) {
7429 shaderBytecode[d3dStage] = cacheIt->bytecode;
7430 stageData[d3dStage].nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
7431 stageData[d3dStage].pushConstantRegister = cacheIt->pushConstantRegister;
7432 stageData[d3dStage].pushConstantSize = cacheIt->pushConstantSize;
7433 } else {
7434 QString error;
7435 QShaderKey shaderKey;
7436 int compileFlags = 0;
7437 if (m_flags.testFlag(CompileShadersWithDebugInfo))
7438 compileFlags |= int(HlslCompileFlag::WithDebugInfo);
7439 const QByteArray bytecode = compileHlslShaderSource(shaderStage.shader(),
7440 shaderStage.shaderVariant(),
7441 compileFlags,
7442 &error,
7443 &shaderKey);
7444 if (bytecode.isEmpty()) {
7445 qWarning("HLSL graphics shader compilation failed: %s", qPrintable(error));
7446 return false;
7447 }
7448
7449 shaderBytecode[d3dStage] = bytecode;
7450 stageData[d3dStage].nativeResourceBindingMap = shaderStage.shader().nativeResourceBindingMap(shaderKey);
7451 qd3d12_setPushConstantInfo(&stageData[d3dStage], shaderStage.shader(), shaderKey);
7452 rhiD->shaderBytecodeCache.insertWithCapacityLimit(shaderStage,
7453 { bytecode, stageData[d3dStage].nativeResourceBindingMap,
7454 stageData[d3dStage].pushConstantRegister,
7455 stageData[d3dStage].pushConstantSize });
7456 }
7457 }
7458
7459 QD3D12ShaderResourceBindings *srbD = QRHI_RES(QD3D12ShaderResourceBindings, m_shaderResourceBindings);
7460 if (srbD) {
7461 rootSigHandle = srbD->createRootSignature(stageData.data(), 5);
7462 pushConstantRootParamIndex = srbD->pushConstantRootParamIndex;
7463 if (rootSigHandle.isNull()) {
7464 qWarning("Failed to create root signature");
7465 return false;
7466 }
7467 }
7468 ID3D12RootSignature *rootSig = nullptr;
7469 if (QD3D12RootSignature *rs = rhiD->rootSignaturePool.lookupRef(rootSigHandle))
7470 rootSig = rs->rootSig;
7471 if (!rootSig) {
7472 qWarning("Cannot create graphics pipeline state without root signature");
7473 return false;
7474 }
7475
7476 QD3D12RenderPassDescriptor *rpD = QRHI_RES(QD3D12RenderPassDescriptor, m_renderPassDesc);
7477 DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
7478 if (rpD->colorAttachmentCount > 0) {
7479 format = DXGI_FORMAT(rpD->colorFormat[0]);
7480 } else if (rpD->hasDepthStencil) {
7481 format = DXGI_FORMAT(rpD->dsFormat);
7482 } else {
7483 qWarning("Cannot create graphics pipeline state without color or depthStencil format");
7484 return false;
7485 }
7486 const DXGI_SAMPLE_DESC sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount, format);
7487
7488 struct {
7489 QD3D12PipelineStateSubObject<ID3D12RootSignature *, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE> rootSig;
7490 QD3D12PipelineStateSubObject<D3D12_INPUT_LAYOUT_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT> inputLayout;
7491 QD3D12PipelineStateSubObject<D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE> primitiveRestartValue;
7492 QD3D12PipelineStateSubObject<D3D12_PRIMITIVE_TOPOLOGY_TYPE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY> primitiveTopology;
7493 QD3D12PipelineStateSubObject<D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS> VS;
7494 QD3D12PipelineStateSubObject<D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS> HS;
7495 QD3D12PipelineStateSubObject<D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS> DS;
7496 QD3D12PipelineStateSubObject<D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS> GS;
7497 QD3D12PipelineStateSubObject<D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS> PS;
7498 QD3D12PipelineStateSubObject<D3D12_RASTERIZER_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER> rasterizerState;
7499 QD3D12PipelineStateSubObject<D3D12_DEPTH_STENCIL_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL> depthStencilState;
7500 QD3D12PipelineStateSubObject<D3D12_BLEND_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND> blendState;
7501 QD3D12PipelineStateSubObject<D3D12_RT_FORMAT_ARRAY, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS> rtFormats;
7502 QD3D12PipelineStateSubObject<DXGI_FORMAT, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT> dsFormat;
7503 QD3D12PipelineStateSubObject<DXGI_SAMPLE_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC> sampleDesc;
7504 QD3D12PipelineStateSubObject<UINT, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK> sampleMask;
7505 QD3D12PipelineStateSubObject<D3D12_VIEW_INSTANCING_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING> viewInstancingDesc;
7506 } stream;
7507
7508 stream.rootSig.object = rootSig;
7509
7510 QVarLengthArray<D3D12_INPUT_ELEMENT_DESC, 4> inputDescs;
7511 QByteArrayList matrixSliceSemantics;
7512 if (!shaderBytecode[VS].isEmpty()) {
7513 for (auto it = m_vertexInputLayout.cbeginAttributes(), itEnd = m_vertexInputLayout.cendAttributes();
7514 it != itEnd; ++it)
7515 {
7516 D3D12_INPUT_ELEMENT_DESC desc = {};
7517 // The output from SPIRV-Cross uses TEXCOORD<location> as the
7518 // semantic, except for matrices that are unrolled into consecutive
7519 // vec2/3/4s attributes and need TEXCOORD<location>_ as
7520 // SemanticName and row/column index as SemanticIndex.
7521 const int matrixSlice = it->matrixSlice();
7522 if (matrixSlice < 0) {
7523 desc.SemanticName = "TEXCOORD";
7524 desc.SemanticIndex = UINT(it->location());
7525 } else {
7526 QByteArray sem;
7527 sem.resize(16);
7528 std::snprintf(sem.data(), sem.size(), "TEXCOORD%d_", it->location() - matrixSlice);
7529 matrixSliceSemantics.append(sem);
7530 desc.SemanticName = matrixSliceSemantics.last().constData();
7531 desc.SemanticIndex = UINT(matrixSlice);
7532 }
7533 desc.Format = toD3DAttributeFormat(it->format());
7534 desc.InputSlot = UINT(it->binding());
7535 desc.AlignedByteOffset = it->offset();
7536 const QRhiVertexInputBinding *inputBinding = m_vertexInputLayout.bindingAt(it->binding());
7537 if (inputBinding->classification() == QRhiVertexInputBinding::PerInstance) {
7538 desc.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA;
7539 desc.InstanceDataStepRate = inputBinding->instanceStepRate();
7540 } else {
7541 desc.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
7542 }
7543 inputDescs.append(desc);
7544 }
7545 }
7546
7547 stream.inputLayout.object.NumElements = inputDescs.count();
7548 stream.inputLayout.object.pInputElementDescs = inputDescs.isEmpty() ? nullptr : inputDescs.constData();
7549
7550 stream.primitiveRestartValue.object = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF;
7551
7552 stream.primitiveTopology.object = toD3DTopologyType(m_topology);
7553 topology = toD3DTopology(m_topology, m_patchControlPointCount);
7554
7555 for (const QRhiShaderStage &shaderStage : std::as_const(m_shaderStages)) {
7556 const int d3dStage = qd3d12_stage(shaderStage.type());
7557 switch (d3dStage) {
7558 case VS:
7559 stream.VS.object.pShaderBytecode = shaderBytecode[d3dStage].constData();
7560 stream.VS.object.BytecodeLength = shaderBytecode[d3dStage].size();
7561 break;
7562 case HS:
7563 stream.HS.object.pShaderBytecode = shaderBytecode[d3dStage].constData();
7564 stream.HS.object.BytecodeLength = shaderBytecode[d3dStage].size();
7565 break;
7566 case DS:
7567 stream.DS.object.pShaderBytecode = shaderBytecode[d3dStage].constData();
7568 stream.DS.object.BytecodeLength = shaderBytecode[d3dStage].size();
7569 break;
7570 case GS:
7571 stream.GS.object.pShaderBytecode = shaderBytecode[d3dStage].constData();
7572 stream.GS.object.BytecodeLength = shaderBytecode[d3dStage].size();
7573 break;
7574 case PS:
7575 stream.PS.object.pShaderBytecode = shaderBytecode[d3dStage].constData();
7576 stream.PS.object.BytecodeLength = shaderBytecode[d3dStage].size();
7577 break;
7578 default:
7579 Q_UNREACHABLE();
7580 break;
7581 }
7582 }
7583
7584 stream.rasterizerState.object.FillMode = toD3DFillMode(m_polygonMode);
7585 stream.rasterizerState.object.CullMode = toD3DCullMode(m_cullMode);
7586 stream.rasterizerState.object.FrontCounterClockwise = m_frontFace == CCW;
7587 stream.rasterizerState.object.DepthBias = m_depthBias;
7588 stream.rasterizerState.object.SlopeScaledDepthBias = m_slopeScaledDepthBias;
7589 stream.rasterizerState.object.DepthClipEnable = m_depthClamp ? FALSE : TRUE;
7590 stream.rasterizerState.object.MultisampleEnable = sampleDesc.Count > 1;
7591
7592 stream.depthStencilState.object.DepthEnable = m_depthTest;
7593 stream.depthStencilState.object.DepthWriteMask = m_depthWrite ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO;
7594 stream.depthStencilState.object.DepthFunc = toD3DCompareOp(m_depthOp);
7595 stream.depthStencilState.object.StencilEnable = m_stencilTest;
7596 if (m_stencilTest) {
7597 stream.depthStencilState.object.StencilReadMask = UINT8(m_stencilReadMask);
7598 stream.depthStencilState.object.StencilWriteMask = UINT8(m_stencilWriteMask);
7599 stream.depthStencilState.object.FrontFace.StencilFailOp = toD3DStencilOp(m_stencilFront.failOp);
7600 stream.depthStencilState.object.FrontFace.StencilDepthFailOp = toD3DStencilOp(m_stencilFront.depthFailOp);
7601 stream.depthStencilState.object.FrontFace.StencilPassOp = toD3DStencilOp(m_stencilFront.passOp);
7602 stream.depthStencilState.object.FrontFace.StencilFunc = toD3DCompareOp(m_stencilFront.compareOp);
7603 stream.depthStencilState.object.BackFace.StencilFailOp = toD3DStencilOp(m_stencilBack.failOp);
7604 stream.depthStencilState.object.BackFace.StencilDepthFailOp = toD3DStencilOp(m_stencilBack.depthFailOp);
7605 stream.depthStencilState.object.BackFace.StencilPassOp = toD3DStencilOp(m_stencilBack.passOp);
7606 stream.depthStencilState.object.BackFace.StencilFunc = toD3DCompareOp(m_stencilBack.compareOp);
7607 }
7608
7609 stream.blendState.object.IndependentBlendEnable = m_targetBlends.count() > 1;
7610 for (int i = 0, ie = m_targetBlends.count(); i != ie; ++i) {
7611 const QRhiGraphicsPipeline::TargetBlend &b(m_targetBlends[i]);
7612 D3D12_RENDER_TARGET_BLEND_DESC blend = {};
7613 blend.BlendEnable = b.enable;
7614 blend.SrcBlend = toD3DBlendFactor(b.srcColor, true);
7615 blend.DestBlend = toD3DBlendFactor(b.dstColor, true);
7616 blend.BlendOp = toD3DBlendOp(b.opColor);
7617 blend.SrcBlendAlpha = toD3DBlendFactor(b.srcAlpha, false);
7618 blend.DestBlendAlpha = toD3DBlendFactor(b.dstAlpha, false);
7619 blend.BlendOpAlpha = toD3DBlendOp(b.opAlpha);
7620 blend.RenderTargetWriteMask = toD3DColorWriteMask(b.colorWrite);
7621 stream.blendState.object.RenderTarget[i] = blend;
7622 }
7623 if (m_targetBlends.isEmpty()) {
7624 D3D12_RENDER_TARGET_BLEND_DESC blend = {};
7625 blend.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
7626 stream.blendState.object.RenderTarget[0] = blend;
7627 }
7628
7629 stream.rtFormats.object.NumRenderTargets = rpD->colorAttachmentCount;
7630 for (int i = 0; i < rpD->colorAttachmentCount; ++i)
7631 stream.rtFormats.object.RTFormats[i] = DXGI_FORMAT(rpD->colorFormat[i]);
7632
7633 stream.dsFormat.object = rpD->hasDepthStencil ? DXGI_FORMAT(rpD->dsFormat) : DXGI_FORMAT_UNKNOWN;
7634
7635 stream.sampleDesc.object = sampleDesc;
7636
7637 stream.sampleMask.object = 0xFFFFFFFF;
7638
7639 viewInstanceMask = 0;
7640 const bool isMultiView = m_multiViewCount >= 2;
7641 stream.viewInstancingDesc.object.ViewInstanceCount = isMultiView ? m_multiViewCount : 0;
7642 QVarLengthArray<D3D12_VIEW_INSTANCE_LOCATION, 4> viewInstanceLocations;
7643 if (isMultiView) {
7644 for (int i = 0; i < m_multiViewCount; ++i) {
7645 viewInstanceMask |= (1 << i);
7646 viewInstanceLocations.append({ 0, UINT(i) });
7647 }
7648 stream.viewInstancingDesc.object.pViewInstanceLocations = viewInstanceLocations.constData();
7649 }
7650
7651 const D3D12_PIPELINE_STATE_STREAM_DESC streamDesc = { sizeof(stream), &stream };
7652
7653 QCryptographicHash keyHash(QCryptographicHash::Sha1);
7654 for (const QByteArray &bytecode : shaderBytecode)
7655 addToKey(&keyHash, bytecode);
7656 for (const D3D12_INPUT_ELEMENT_DESC &desc : inputDescs) {
7657 keyHash.addData(QByteArrayView(desc.SemanticName));
7658 addToKey(&keyHash, desc.SemanticIndex);
7659 addToKey(&keyHash, desc.Format);
7660 addToKey(&keyHash, desc.InputSlot);
7661 addToKey(&keyHash, desc.AlignedByteOffset);
7662 addToKey(&keyHash, desc.InputSlotClass);
7663 addToKey(&keyHash, desc.InstanceDataStepRate);
7664 }
7665 addToKey(&keyHash, stream.primitiveRestartValue.object);
7666 addToKey(&keyHash, stream.primitiveTopology.object);
7667 addToKey(&keyHash, stream.rasterizerState.object);
7668 addToKey(&keyHash, stream.depthStencilState.object);
7669 addToKey(&keyHash, stream.blendState.object);
7670 addToKey(&keyHash, stream.rtFormats.object);
7671 addToKey(&keyHash, stream.dsFormat.object);
7672 addToKey(&keyHash, stream.sampleDesc.object);
7673 addToKey(&keyHash, stream.sampleMask.object);
7674 addToKey(&keyHash, stream.viewInstancingDesc.object.ViewInstanceCount);
7675 addToKey(&keyHash, stream.viewInstancingDesc.object.Flags);
7676 addToKey(&keyHash, viewInstanceLocations.constData(),
7677 viewInstanceLocations.count() * sizeof(D3D12_VIEW_INSTANCE_LOCATION));
7678 // Stands in for the root signature, which is built from this plus the
7679 // shaders' native resource binding maps.
7680 addToKey(&keyHash, srbD->serializedLayoutDescription());
7681
7682 ID3D12PipelineState *pso = rhiD->loadOrCreatePipelineState(&streamDesc, keyHash.result().toHex(), "graphics");
7683 if (!pso) {
7684 rhiD->rootSignaturePool.remove(rootSigHandle);
7685 rootSigHandle = {};
7686 return false;
7687 }
7688
7689 handle = QD3D12Pipeline::addToPool(&rhiD->pipelinePool, QD3D12Pipeline::Graphics, pso);
7690
7691 rhiD->pipelineCreationEnd();
7692 generation += 1;
7693 rhiD->registerResource(this);
7694 return true;
7695}
7696
7697QD3D12ComputePipeline::QD3D12ComputePipeline(QRhiImplementation *rhi)
7698 : QRhiComputePipeline(rhi)
7699{
7700}
7701
7702QD3D12ComputePipeline::~QD3D12ComputePipeline()
7703{
7704 destroy();
7705}
7706
7707void QD3D12ComputePipeline::destroy()
7708{
7709 if (handle.isNull())
7710 return;
7711
7712 QRHI_RES_RHI(QRhiD3D12);
7713 if (rhiD) {
7714 rhiD->releaseQueue.deferredReleasePipeline(handle);
7715 rhiD->releaseQueue.deferredReleaseRootSignature(rootSigHandle);
7716 }
7717
7718 handle = {};
7719 stageData = {};
7720
7721 if (rhiD)
7722 rhiD->unregisterResource(this);
7723}
7724
7725bool QD3D12ComputePipeline::create()
7726{
7727 if (!handle.isNull())
7728 destroy();
7729
7730 QRHI_RES_RHI(QRhiD3D12);
7731 rhiD->pipelineCreationStart();
7732
7733 stageData.valid = true;
7734 stageData.stage = CS;
7735
7736 QByteArray shaderBytecode;
7737 auto cacheIt = rhiD->shaderBytecodeCache.data.constFind(m_shaderStage);
7738 if (cacheIt != rhiD->shaderBytecodeCache.data.constEnd()) {
7739 shaderBytecode = cacheIt->bytecode;
7740 stageData.nativeResourceBindingMap = cacheIt->nativeResourceBindingMap;
7741 stageData.pushConstantRegister = cacheIt->pushConstantRegister;
7742 stageData.pushConstantSize = cacheIt->pushConstantSize;
7743 } else {
7744 QString error;
7745 QShaderKey shaderKey;
7746 int compileFlags = 0;
7747 if (m_flags.testFlag(CompileShadersWithDebugInfo))
7748 compileFlags |= int(HlslCompileFlag::WithDebugInfo);
7749 const QByteArray bytecode = compileHlslShaderSource(m_shaderStage.shader(),
7750 m_shaderStage.shaderVariant(),
7751 compileFlags,
7752 &error,
7753 &shaderKey);
7754 if (bytecode.isEmpty()) {
7755 qWarning("HLSL compute shader compilation failed: %s", qPrintable(error));
7756 return false;
7757 }
7758
7759 shaderBytecode = bytecode;
7760 stageData.nativeResourceBindingMap = m_shaderStage.shader().nativeResourceBindingMap(shaderKey);
7761 qd3d12_setPushConstantInfo(&stageData, m_shaderStage.shader(), shaderKey);
7762 rhiD->shaderBytecodeCache.insertWithCapacityLimit(m_shaderStage, { bytecode,
7763 stageData.nativeResourceBindingMap,
7764 stageData.pushConstantRegister,
7765 stageData.pushConstantSize });
7766 }
7767
7768 QD3D12ShaderResourceBindings *srbD = QRHI_RES(QD3D12ShaderResourceBindings, m_shaderResourceBindings);
7769 if (srbD) {
7770 rootSigHandle = srbD->createRootSignature(&stageData, 1);
7771 pushConstantRootParamIndex = srbD->pushConstantRootParamIndex;
7772 if (rootSigHandle.isNull()) {
7773 qWarning("Failed to create root signature");
7774 return false;
7775 }
7776 }
7777 ID3D12RootSignature *rootSig = nullptr;
7778 if (QD3D12RootSignature *rs = rhiD->rootSignaturePool.lookupRef(rootSigHandle))
7779 rootSig = rs->rootSig;
7780 if (!rootSig) {
7781 qWarning("Cannot create compute pipeline state without root signature");
7782 return false;
7783 }
7784
7785 struct {
7786 QD3D12PipelineStateSubObject<ID3D12RootSignature *, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE> rootSig;
7787 QD3D12PipelineStateSubObject<D3D12_SHADER_BYTECODE, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS> CS;
7788 } stream;
7789 stream.rootSig.object = rootSig;
7790 stream.CS.object.pShaderBytecode = shaderBytecode.constData();
7791 stream.CS.object.BytecodeLength = shaderBytecode.size();
7792 const D3D12_PIPELINE_STATE_STREAM_DESC streamDesc = { sizeof(stream), &stream };
7793
7794 QCryptographicHash keyHash(QCryptographicHash::Sha1);
7795 addToKey(&keyHash, shaderBytecode);
7796 addToKey(&keyHash, srbD->serializedLayoutDescription());
7797
7798 ID3D12PipelineState *pso = rhiD->loadOrCreatePipelineState(&streamDesc, keyHash.result().toHex(), "compute");
7799 if (!pso) {
7800 rhiD->rootSignaturePool.remove(rootSigHandle);
7801 rootSigHandle = {};
7802 return false;
7803 }
7804
7805 handle = QD3D12Pipeline::addToPool(&rhiD->pipelinePool, QD3D12Pipeline::Compute, pso);
7806
7807 rhiD->pipelineCreationEnd();
7808 generation += 1;
7809 rhiD->registerResource(this);
7810 return true;
7811}
7812
7813// This is a lot like in the Metal backend: we need to now the rtv and dsv
7814// formats to create a graphics pipeline, and that's exactly what our
7815// "renderpass descriptor" is going to hold.
7816QD3D12RenderPassDescriptor::QD3D12RenderPassDescriptor(QRhiImplementation *rhi)
7817 : QRhiRenderPassDescriptor(rhi)
7818{
7819 serializedFormatData.reserve(16);
7820}
7821
7822QD3D12RenderPassDescriptor::~QD3D12RenderPassDescriptor()
7823{
7824 destroy();
7825}
7826
7827void QD3D12RenderPassDescriptor::destroy()
7828{
7829 QRHI_RES_RHI(QRhiD3D12);
7830 if (rhiD)
7831 rhiD->unregisterResource(this);
7832}
7833
7834bool QD3D12RenderPassDescriptor::isCompatible(const QRhiRenderPassDescriptor *other) const
7835{
7836 if (!other)
7837 return false;
7838
7839 const QD3D12RenderPassDescriptor *o = QRHI_RES(const QD3D12RenderPassDescriptor, other);
7840
7841 if (colorAttachmentCount != o->colorAttachmentCount)
7842 return false;
7843
7844 if (hasDepthStencil != o->hasDepthStencil)
7845 return false;
7846
7847 for (int i = 0; i < colorAttachmentCount; ++i) {
7848 if (colorFormat[i] != o->colorFormat[i])
7849 return false;
7850 }
7851
7852 if (hasDepthStencil) {
7853 if (dsFormat != o->dsFormat)
7854 return false;
7855 }
7856
7857 if (hasShadingRateMap != o->hasShadingRateMap)
7858 return false;
7859
7860 return true;
7861}
7862
7863void QD3D12RenderPassDescriptor::updateSerializedFormat()
7864{
7865 serializedFormatData.clear();
7866 auto p = std::back_inserter(serializedFormatData);
7867
7868 *p++ = colorAttachmentCount;
7869 *p++ = hasDepthStencil;
7870 for (int i = 0; i < colorAttachmentCount; ++i)
7871 *p++ = colorFormat[i];
7872 *p++ = hasDepthStencil ? dsFormat : 0;
7873}
7874
7875QRhiRenderPassDescriptor *QD3D12RenderPassDescriptor::newCompatibleRenderPassDescriptor() const
7876{
7877 QD3D12RenderPassDescriptor *rpD = new QD3D12RenderPassDescriptor(m_rhi);
7878 rpD->colorAttachmentCount = colorAttachmentCount;
7879 rpD->hasDepthStencil = hasDepthStencil;
7880 memcpy(rpD->colorFormat, colorFormat, sizeof(colorFormat));
7881 rpD->dsFormat = dsFormat;
7882 rpD->hasShadingRateMap = hasShadingRateMap;
7883
7884 rpD->updateSerializedFormat();
7885
7886 QRHI_RES_RHI(QRhiD3D12);
7887 rhiD->registerResource(rpD);
7888 return rpD;
7889}
7890
7891QVector<quint32> QD3D12RenderPassDescriptor::serializedFormat() const
7892{
7893 return serializedFormatData;
7894}
7895
7896QD3D12CommandBuffer::QD3D12CommandBuffer(QRhiImplementation *rhi)
7897 : QRhiCommandBuffer(rhi)
7898{
7899 resetState();
7900}
7901
7902QD3D12CommandBuffer::~QD3D12CommandBuffer()
7903{
7904 destroy();
7905}
7906
7907void QD3D12CommandBuffer::destroy()
7908{
7909 // nothing to do here, the command list is not owned by us
7910}
7911
7912const QRhiNativeHandles *QD3D12CommandBuffer::nativeHandles()
7913{
7914 nativeHandlesStruct.commandList = cmdList;
7915 return &nativeHandlesStruct;
7916}
7917
7918QD3D12SwapChainRenderTarget::QD3D12SwapChainRenderTarget(QRhiImplementation *rhi, QRhiSwapChain *swapchain)
7919 : QRhiSwapChainRenderTarget(rhi, swapchain),
7920 d(rhi)
7921{
7922}
7923
7924QD3D12SwapChainRenderTarget::~QD3D12SwapChainRenderTarget()
7925{
7926 destroy();
7927}
7928
7929void QD3D12SwapChainRenderTarget::destroy()
7930{
7931 // nothing to do here
7932}
7933
7934QSize QD3D12SwapChainRenderTarget::pixelSize() const
7935{
7936 return d.pixelSize;
7937}
7938
7939float QD3D12SwapChainRenderTarget::devicePixelRatio() const
7940{
7941 return d.dpr;
7942}
7943
7944int QD3D12SwapChainRenderTarget::sampleCount() const
7945{
7946 return d.sampleCount;
7947}
7948
7949QD3D12SwapChain::QD3D12SwapChain(QRhiImplementation *rhi)
7950 : QRhiSwapChain(rhi),
7951 rtWrapper(rhi, this),
7952 rtWrapperRight(rhi, this),
7953 cbWrapper(rhi)
7954{
7955}
7956
7957QD3D12SwapChain::~QD3D12SwapChain()
7958{
7959 destroy();
7960}
7961
7962void QD3D12SwapChain::destroy()
7963{
7964 if (dcompVisual) {
7965 dcompVisual->Release();
7966 dcompVisual = nullptr;
7967 }
7968
7969 if (dcompTarget) {
7970 dcompTarget->Release();
7971 dcompTarget = nullptr;
7972 }
7973
7974 if (!swapChain)
7975 return;
7976
7977 releaseBuffers();
7978
7979 swapChain->Release();
7980 swapChain = nullptr;
7981 sourceSwapChain1->Release();
7982 sourceSwapChain1 = nullptr;
7983
7984 for (int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
7985 FrameResources &fr(frameRes[i]);
7986 if (fr.fence)
7987 fr.fence->Release();
7988 if (fr.fenceEvent)
7989 CloseHandle(fr.fenceEvent);
7990 if (fr.cmdList)
7991 fr.cmdList->Release();
7992 fr = {};
7993 }
7994
7995 if (frameLatencyWaitableObject) {
7996 CloseHandle(frameLatencyWaitableObject);
7997 frameLatencyWaitableObject = nullptr;
7998 }
7999
8000 QDxgiVSyncService::instance()->unregisterWindow(window);
8001
8002 QRHI_RES_RHI(QRhiD3D12);
8003 if (rhiD) {
8004 rhiD->swapchains.remove(this);
8005 rhiD->unregisterResource(this);
8006 }
8007}
8008
8009void QD3D12SwapChain::releaseBuffers()
8010{
8011 QRHI_RES_RHI(QRhiD3D12);
8012 rhiD->waitGpu();
8013 for (UINT i = 0; i < BUFFER_COUNT; ++i) {
8014 rhiD->resourcePool.remove(colorBuffers[i]);
8015 rhiD->rtvPool.release(rtvs[i], 1);
8016 if (stereo)
8017 rhiD->rtvPool.release(rtvsRight[i], 1);
8018 }
8019 for (int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
8020 if (!msaaBuffers[i].isNull())
8021 rhiD->resourcePool.remove(msaaBuffers[i]);
8022 if (msaaRtvs[i].isValid())
8023 rhiD->rtvPool.release(msaaRtvs[i], 1);
8024 }
8025}
8026
8027void QD3D12SwapChain::waitCommandCompletionForFrameSlot(int frameSlot)
8028{
8029 FrameResources &fr(frameRes[frameSlot]);
8030 if (fr.fence->GetCompletedValue() < fr.fenceCounter) {
8031 fr.fence->SetEventOnCompletion(fr.fenceCounter, fr.fenceEvent);
8032 WaitForSingleObject(fr.fenceEvent, INFINITE);
8033 }
8034}
8035
8036void QD3D12SwapChain::addCommandCompletionSignalForCurrentFrameSlot()
8037{
8038 QRHI_RES_RHI(QRhiD3D12);
8039 FrameResources &fr(frameRes[currentFrameSlot]);
8040 fr.fenceCounter += 1u;
8041 rhiD->cmdQueue->Signal(fr.fence, fr.fenceCounter);
8042}
8043
8044QRhiCommandBuffer *QD3D12SwapChain::currentFrameCommandBuffer()
8045{
8046 return &cbWrapper;
8047}
8048
8049QRhiRenderTarget *QD3D12SwapChain::currentFrameRenderTarget()
8050{
8051 return &rtWrapper;
8052}
8053
8054QRhiRenderTarget *QD3D12SwapChain::currentFrameRenderTarget(StereoTargetBuffer targetBuffer)
8055{
8056 return !stereo || targetBuffer == StereoTargetBuffer::LeftBuffer ? &rtWrapper : &rtWrapperRight;
8057}
8058
8059QSize QD3D12SwapChain::surfacePixelSize()
8060{
8061 Q_ASSERT(m_window);
8062 return m_window->size() * m_window->devicePixelRatio();
8063}
8064
8065bool QD3D12SwapChain::isFormatSupported(Format f)
8066{
8067 if (f == SDR)
8068 return true;
8069
8070 if (!m_window) {
8071 qWarning("Attempted to call isFormatSupported() without a window set");
8072 return false;
8073 }
8074
8075 QRHI_RES_RHI(QRhiD3D12);
8076 if (QDxgiHdrInfo(rhiD->activeAdapter).isHdrCapable(m_window))
8077 return f == QRhiSwapChain::HDRExtendedSrgbLinear || f == QRhiSwapChain::HDR10;
8078
8079 return false;
8080}
8081
8082QRhiSwapChainHdrInfo QD3D12SwapChain::hdrInfo()
8083{
8084 QRhiSwapChainHdrInfo info = QRhiSwapChain::hdrInfo();
8085 // Must use m_window, not window, given this may be called before createOrResize().
8086 if (m_window) {
8087 QRHI_RES_RHI(QRhiD3D12);
8088 info = QDxgiHdrInfo(rhiD->activeAdapter).queryHdrInfo(m_window);
8089 }
8090 return info;
8091}
8092
8093QRhiRenderPassDescriptor *QD3D12SwapChain::newCompatibleRenderPassDescriptor()
8094{
8095 // not yet built so cannot rely on data computed in createOrResize()
8096 chooseFormats();
8097
8098 QD3D12RenderPassDescriptor *rpD = new QD3D12RenderPassDescriptor(m_rhi);
8099 rpD->colorAttachmentCount = 1;
8100 rpD->hasDepthStencil = m_depthStencil != nullptr;
8101 rpD->colorFormat[0] = int(srgbAdjustedColorFormat);
8102 rpD->dsFormat = QD3D12RenderBuffer::DS_FORMAT;
8103
8104 rpD->hasShadingRateMap = m_shadingRateMap != nullptr;
8105
8106 rpD->updateSerializedFormat();
8107
8108 QRHI_RES_RHI(QRhiD3D12);
8109 rhiD->registerResource(rpD);
8110 return rpD;
8111}
8112
8113bool QRhiD3D12::ensureDirectCompositionDevice()
8114{
8115 if (dcompDevice)
8116 return true;
8117
8118 qCDebug(QRHI_LOG_INFO, "Creating Direct Composition device (needed for semi-transparent windows)");
8119 dcompDevice = QRhiD3D::createDirectCompositionDevice();
8120 return dcompDevice ? true : false;
8121}
8122
8123static const DXGI_FORMAT DEFAULT_FORMAT = DXGI_FORMAT_R8G8B8A8_UNORM;
8124static const DXGI_FORMAT DEFAULT_SRGB_FORMAT = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
8125
8126void QD3D12SwapChain::chooseFormats()
8127{
8128 colorFormat = DEFAULT_FORMAT;
8129 srgbAdjustedColorFormat = m_flags.testFlag(sRGB) ? DEFAULT_SRGB_FORMAT : DEFAULT_FORMAT;
8130 hdrColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; // SDR
8131 QRHI_RES_RHI(QRhiD3D12);
8132 if (m_format != SDR) {
8133 if (QDxgiHdrInfo(rhiD->activeAdapter).isHdrCapable(m_window)) {
8134 // https://docs.microsoft.com/en-us/windows/win32/direct3darticles/high-dynamic-range
8135 switch (m_format) {
8136 case HDRExtendedSrgbLinear:
8137 colorFormat = DXGI_FORMAT_R16G16B16A16_FLOAT;
8138 hdrColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709;
8139 srgbAdjustedColorFormat = colorFormat;
8140 break;
8141 case HDR10:
8142 colorFormat = DXGI_FORMAT_R10G10B10A2_UNORM;
8143 hdrColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020;
8144 srgbAdjustedColorFormat = colorFormat;
8145 break;
8146 default:
8147 break;
8148 }
8149 } else {
8150 // This happens also when Use HDR is set to Off in the Windows
8151 // Display settings. Show a helpful warning, but continue with the
8152 // default non-HDR format.
8153 qWarning("The output associated with the window is not HDR capable "
8154 "(or Use HDR is Off in the Display Settings), ignoring HDR format request");
8155 }
8156 }
8157 sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount, colorFormat);
8158}
8159
8160bool QD3D12SwapChain::createOrResize()
8161{
8162 // Can be called multiple times due to window resizes - that is not the
8163 // same as a simple destroy+create (as with other resources). Just need to
8164 // resize the buffers then.
8165
8166 const bool needsRegistration = !window || window != m_window;
8167
8168 // except if the window actually changes
8169 if (window && window != m_window)
8170 destroy();
8171
8172 window = m_window;
8173 pixelSize = surfacePixelSize();
8174
8175 if (pixelSize.isEmpty())
8176 return false;
8177
8178 HWND hwnd = reinterpret_cast<HWND>(window->winId());
8179 HRESULT hr;
8180 QRHI_RES_RHI(QRhiD3D12);
8181 stereo = m_window->format().stereo() && rhiD->dxgiFactory->IsWindowedStereoEnabled();
8182
8183 if (m_flags.testFlag(SurfaceHasPreMulAlpha) || m_flags.testFlag(SurfaceHasNonPreMulAlpha)) {
8184 if (rhiD->ensureDirectCompositionDevice()) {
8185 if (!dcompTarget) {
8186 hr = rhiD->dcompDevice->CreateTargetForHwnd(hwnd, false, &dcompTarget);
8187 if (FAILED(hr)) {
8188 qWarning("Failed to create Direct Composition target for the window: %s",
8189 qPrintable(QSystemError::windowsComString(hr)));
8190 }
8191 }
8192 if (dcompTarget && !dcompVisual) {
8193 hr = rhiD->dcompDevice->CreateVisual(&dcompVisual);
8194 if (FAILED(hr)) {
8195 qWarning("Failed to create DirectComposition visual: %s",
8196 qPrintable(QSystemError::windowsComString(hr)));
8197 }
8198 }
8199 }
8200 // simple consistency check
8201 if (window->requestedFormat().alphaBufferSize() <= 0)
8202 qWarning("Swapchain says surface has alpha but the window has no alphaBufferSize set. "
8203 "This may lead to problems.");
8204 }
8205
8206 swapInterval = m_flags.testFlag(QRhiSwapChain::NoVSync) ? 0 : 1;
8207 swapChainFlags = 0;
8208 if (swapInterval == 0 && rhiD->supportsAllowTearing)
8209 swapChainFlags |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
8210
8211 // maxFrameLatency 0 means no waitable object usage.
8212 // Ignore it also when NoVSync is on, and when using WARP.
8213 const bool useFrameLatencyWaitableObject = rhiD->maxFrameLatency != 0
8214 && swapInterval != 0
8215 && rhiD->driverInfoStruct.deviceType != QRhiDriverInfo::CpuDevice;
8216 if (useFrameLatencyWaitableObject)
8217 swapChainFlags |= DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
8218
8219 if (!swapChain) {
8220 chooseFormats();
8221
8222 DXGI_SWAP_CHAIN_DESC1 desc = {};
8223 desc.Width = UINT(pixelSize.width());
8224 desc.Height = UINT(pixelSize.height());
8225 desc.Format = colorFormat;
8226 desc.SampleDesc.Count = 1;
8227 desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
8228 desc.BufferCount = BUFFER_COUNT;
8229 desc.Flags = swapChainFlags;
8230 desc.Scaling = DXGI_SCALING_NONE;
8231 desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
8232 desc.Stereo = stereo;
8233
8234 if (dcompVisual) {
8235 // With DirectComposition setting AlphaMode to STRAIGHT fails the
8236 // swapchain creation, whereas the result seems to be identical
8237 // with any of the other values, including IGNORE. (?)
8238 desc.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED;
8239
8240 // DirectComposition has its own limitations, cannot use
8241 // SCALING_NONE. So with semi-transparency requested we are forced
8242 // to SCALING_STRETCH.
8243 desc.Scaling = DXGI_SCALING_STRETCH;
8244 }
8245
8246 if (dcompVisual)
8247 hr = rhiD->dxgiFactory->CreateSwapChainForComposition(rhiD->cmdQueue, &desc, nullptr, &sourceSwapChain1);
8248 else
8249 hr = rhiD->dxgiFactory->CreateSwapChainForHwnd(rhiD->cmdQueue, hwnd, &desc, nullptr, nullptr, &sourceSwapChain1);
8250
8251 // If failed and we tried a HDR format, then try with SDR. This
8252 // matches other backends, such as Vulkan where if the format is
8253 // not supported, the default one is used instead.
8254 if (FAILED(hr) && m_format != SDR) {
8255 colorFormat = DEFAULT_FORMAT;
8256 desc.Format = DEFAULT_FORMAT;
8257 if (dcompVisual)
8258 hr = rhiD->dxgiFactory->CreateSwapChainForComposition(rhiD->cmdQueue, &desc, nullptr, &sourceSwapChain1);
8259 else
8260 hr = rhiD->dxgiFactory->CreateSwapChainForHwnd(rhiD->cmdQueue, hwnd, &desc, nullptr, nullptr, &sourceSwapChain1);
8261 }
8262
8263 if (SUCCEEDED(hr)) {
8264 if (FAILED(sourceSwapChain1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void **>(&swapChain)))) {
8265 qWarning("IDXGISwapChain3 not available");
8266 return false;
8267 }
8268 if (m_format != SDR) {
8269 hr = swapChain->SetColorSpace1(hdrColorSpace);
8270 if (FAILED(hr)) {
8271 qWarning("Failed to set color space on swapchain: %s",
8272 qPrintable(QSystemError::windowsComString(hr)));
8273 }
8274 }
8275 if (useFrameLatencyWaitableObject) {
8276 swapChain->SetMaximumFrameLatency(rhiD->maxFrameLatency);
8277 frameLatencyWaitableObject = swapChain->GetFrameLatencyWaitableObject();
8278 }
8279 if (dcompVisual) {
8280 hr = dcompVisual->SetContent(swapChain);
8281 if (SUCCEEDED(hr)) {
8282 hr = dcompTarget->SetRoot(dcompVisual);
8283 if (FAILED(hr)) {
8284 qWarning("Failed to associate Direct Composition visual with the target: %s",
8285 qPrintable(QSystemError::windowsComString(hr)));
8286 }
8287 } else {
8288 qWarning("Failed to set content for Direct Composition visual: %s",
8289 qPrintable(QSystemError::windowsComString(hr)));
8290 }
8291 } else {
8292 // disable Alt+Enter; not relevant when using DirectComposition
8293 rhiD->dxgiFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_WINDOW_CHANGES);
8294 }
8295 }
8296 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
8297 qWarning("Device loss detected during swapchain creation");
8298 rhiD->deviceLost = true;
8299 return false;
8300 } else if (FAILED(hr)) {
8301 qWarning("Failed to create D3D12 swapchain: %s"
8302 " (Width=%u Height=%u Format=%u SampleCount=%u BufferCount=%u Scaling=%u SwapEffect=%u Stereo=%u)",
8303 qPrintable(QSystemError::windowsComString(hr)),
8304 desc.Width, desc.Height, UINT(desc.Format), desc.SampleDesc.Count,
8305 desc.BufferCount, UINT(desc.Scaling), UINT(desc.SwapEffect), UINT(desc.Stereo));
8306 return false;
8307 }
8308
8309 for (int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
8310 hr = rhiD->dev->CreateFence(0,
8311 D3D12_FENCE_FLAG_NONE,
8312 __uuidof(ID3D12Fence),
8313 reinterpret_cast<void **>(&frameRes[i].fence));
8314 if (FAILED(hr)) {
8315 qWarning("Failed to create fence for swapchain: %s",
8316 qPrintable(QSystemError::windowsComString(hr)));
8317 return false;
8318 }
8319 frameRes[i].fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
8320
8321 frameRes[i].fenceCounter = 0;
8322 }
8323 } else {
8324 releaseBuffers();
8325 hr = swapChain->ResizeBuffers(BUFFER_COUNT,
8326 UINT(pixelSize.width()),
8327 UINT(pixelSize.height()),
8328 colorFormat,
8329 swapChainFlags);
8330 if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
8331 qWarning("Device loss detected in ResizeBuffers()");
8332 rhiD->deviceLost = true;
8333 return false;
8334 } else if (FAILED(hr)) {
8335 qWarning("Failed to resize D3D12 swapchain: %s", qPrintable(QSystemError::windowsComString(hr)));
8336 return false;
8337 }
8338 }
8339
8340 for (UINT i = 0; i < BUFFER_COUNT; ++i) {
8341 ID3D12Resource *colorBuffer;
8342 hr = swapChain->GetBuffer(i, __uuidof(ID3D12Resource), reinterpret_cast<void **>(&colorBuffer));
8343 if (FAILED(hr)) {
8344 qWarning("Failed to get buffer %u for D3D12 swapchain: %s",
8345 i, qPrintable(QSystemError::windowsComString(hr)));
8346 return false;
8347 }
8348 colorBuffers[i] = QD3D12Resource::addToPool(&rhiD->resourcePool, colorBuffer, D3D12_RESOURCE_STATE_PRESENT);
8349 rtvs[i] = rhiD->rtvPool.allocate(1);
8350 D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
8351 rtvDesc.Format = srgbAdjustedColorFormat;
8352 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
8353 rhiD->dev->CreateRenderTargetView(colorBuffer, &rtvDesc, rtvs[i].cpuHandle);
8354
8355 if (stereo) {
8356 rtvsRight[i] = rhiD->rtvPool.allocate(1);
8357 D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
8358 rtvDesc.Format = srgbAdjustedColorFormat;
8359 rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
8360 rtvDesc.Texture2DArray.ArraySize = 1;
8361 rtvDesc.Texture2DArray.FirstArraySlice = 1;
8362 rhiD->dev->CreateRenderTargetView(colorBuffer, &rtvDesc, rtvsRight[i].cpuHandle);
8363 }
8364 }
8365
8366 if (m_depthStencil && m_depthStencil->sampleCount() != m_sampleCount) {
8367 qWarning("Depth-stencil buffer's sampleCount (%d) does not match color buffers' sample count (%d). Expect problems.",
8368 m_depthStencil->sampleCount(), m_sampleCount);
8369 }
8370 if (m_depthStencil && m_depthStencil->pixelSize() != pixelSize) {
8371 if (m_depthStencil->flags().testFlag(QRhiRenderBuffer::UsedWithSwapChainOnly)) {
8372 m_depthStencil->setPixelSize(pixelSize);
8373 if (!m_depthStencil->create())
8374 qWarning("Failed to rebuild swapchain's associated depth-stencil buffer for size %dx%d",
8375 pixelSize.width(), pixelSize.height());
8376 } else {
8377 qWarning("Depth-stencil buffer's size (%dx%d) does not match the surface size (%dx%d). Expect problems.",
8378 m_depthStencil->pixelSize().width(), m_depthStencil->pixelSize().height(),
8379 pixelSize.width(), pixelSize.height());
8380 }
8381 }
8382
8383 ds = m_depthStencil ? QRHI_RES(QD3D12RenderBuffer, m_depthStencil) : nullptr;
8384
8385 if (sampleDesc.Count > 1) {
8386 for (int i = 0; i < QD3D12_FRAMES_IN_FLIGHT; ++i) {
8387 D3D12_RESOURCE_DESC resourceDesc = {};
8388 resourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
8389 resourceDesc.Width = UINT64(pixelSize.width());
8390 resourceDesc.Height = UINT(pixelSize.height());
8391 resourceDesc.DepthOrArraySize = 1;
8392 resourceDesc.MipLevels = 1;
8393 resourceDesc.Format = srgbAdjustedColorFormat;
8394 resourceDesc.SampleDesc = sampleDesc;
8395 resourceDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
8396 resourceDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
8397 D3D12_CLEAR_VALUE clearValue = {};
8398 clearValue.Format = colorFormat;
8399 ID3D12Resource *resource = nullptr;
8400 D3D12MA::Allocation *allocation = nullptr;
8401 HRESULT hr = rhiD->vma.createResource(D3D12_HEAP_TYPE_DEFAULT,
8402 &resourceDesc,
8403 D3D12_RESOURCE_STATE_RENDER_TARGET,
8404 &clearValue,
8405 &allocation,
8406 __uuidof(ID3D12Resource),
8407 reinterpret_cast<void **>(&resource));
8408 if (FAILED(hr)) {
8409 qWarning("Failed to create MSAA color buffer: %s", qPrintable(QSystemError::windowsComString(hr)));
8410 return false;
8411 }
8412 msaaBuffers[i] = QD3D12Resource::addToPool(&rhiD->resourcePool, resource, D3D12_RESOURCE_STATE_RENDER_TARGET, allocation);
8413 msaaRtvs[i] = rhiD->rtvPool.allocate(1);
8414 if (!msaaRtvs[i].isValid())
8415 return false;
8416 D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
8417 rtvDesc.Format = srgbAdjustedColorFormat;
8418 rtvDesc.ViewDimension = sampleDesc.Count > 1 ? D3D12_RTV_DIMENSION_TEXTURE2DMS
8419 : D3D12_RTV_DIMENSION_TEXTURE2D;
8420 rhiD->dev->CreateRenderTargetView(resource, &rtvDesc, msaaRtvs[i].cpuHandle);
8421 }
8422 }
8423
8424 currentBackBufferIndex = swapChain->GetCurrentBackBufferIndex();
8425 currentFrameSlot = 0;
8426 lastFrameLatencyWaitSlot = -1; // wait already in the first frame, as instructed in the dxgi docs
8427
8428 rtWrapper.setRenderPassDescriptor(m_renderPassDesc); // for the public getter in QRhiRenderTarget
8429 QD3D12SwapChainRenderTarget *rtD = QRHI_RES(QD3D12SwapChainRenderTarget, &rtWrapper);
8430 rtD->d.rp = QRHI_RES(QD3D12RenderPassDescriptor, m_renderPassDesc);
8431 rtD->d.pixelSize = pixelSize;
8432 rtD->d.dpr = float(window->devicePixelRatio());
8433 rtD->d.sampleCount = int(sampleDesc.Count);
8434 rtD->d.colorAttCount = 1;
8435 rtD->d.dsAttCount = m_depthStencil ? 1 : 0;
8436
8437 rtWrapperRight.setRenderPassDescriptor(m_renderPassDesc);
8438 QD3D12SwapChainRenderTarget *rtDr = QRHI_RES(QD3D12SwapChainRenderTarget, &rtWrapperRight);
8439 rtDr->d.rp = QRHI_RES(QD3D12RenderPassDescriptor, m_renderPassDesc);
8440 rtDr->d.pixelSize = pixelSize;
8441 rtDr->d.dpr = float(window->devicePixelRatio());
8442 rtDr->d.sampleCount = int(sampleDesc.Count);
8443 rtDr->d.colorAttCount = 1;
8444 rtDr->d.dsAttCount = m_depthStencil ? 1 : 0;
8445
8446 QDxgiVSyncService::instance()->registerWindow(window);
8447
8448 if (needsRegistration || !rhiD->swapchains.contains(this))
8449 rhiD->swapchains.insert(this);
8450
8451 rhiD->registerResource(this);
8452
8453 m_currentPixelSize = pixelSize;
8454 return true;
8455}
8456
8457QT_END_NAMESPACE
8458
8459#endif // __ID3D12Device2_INTERFACE_DEFINED__
#define __has_include(x)