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
qrhi.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 "qrhi_p.h"
6#include <qmath.h>
7#include <QLoggingCategory>
8#include "private/qloggingregistry_p.h"
9
10#include "qrhinull_p.h"
11#ifndef QT_NO_OPENGL
12#include "qrhigles2_p.h"
13#endif
14#if QT_CONFIG(vulkan)
15#include "qrhivulkan_p.h"
16#endif
17#ifdef Q_OS_WIN
18#include "qrhid3d11_p.h"
19#include "qrhid3d12_p.h"
20#endif
21#if QT_CONFIG(metal)
22#include "qrhimetal_p.h"
23#endif
24
25#include <limits>
26#include <memory>
27
28QT_BEGIN_NAMESPACE
29
30// Play nice with QSG_INFO since that is still the most commonly used
31// way to get graphics info printed from Qt Quick apps, and the Quick
32// scenegraph is our primary user.
33Q_LOGGING_CATEGORY_WITH_ENV_OVERRIDE(QRHI_LOG_INFO, "QSG_INFO", "qt.rhi.general")
34
35Q_LOGGING_CATEGORY(QRHI_LOG_RUB, "qt.rhi.rub")
36
37Q_CONSTINIT QRhiDebugHooks qrhiDebugHooks;
38
39/*!
40 \class QRhi
41 \ingroup painting-3D
42 \inmodule QtGuiPrivate
43 \inheaderfile rhi/qrhi.h
44 \since 6.6
45
46 \brief Accelerated 2D/3D graphics API abstraction.
47
48 The Qt Rendering Hardware Interface is an abstraction for hardware accelerated
49 graphics APIs, such as, \l{https://www.khronos.org/opengl/}{OpenGL},
50 \l{https://www.khronos.org/opengles/}{OpenGL ES},
51 \l{https://docs.microsoft.com/en-us/windows/desktop/direct3d}{Direct3D},
52 \l{https://developer.apple.com/metal/}{Metal}, and
53 \l{https://www.khronos.org/vulkan/}{Vulkan}.
54
55 \warning The QRhi family of classes in the Qt Gui module, including QShader
56 and QShaderDescription, offer limited compatibility guarantees. There are
57 no source or binary compatibility guarantees for these classes, meaning the
58 API is only guaranteed to work with the Qt version the application was
59 developed against. Source incompatible changes are however aimed to be kept
60 at a minimum and will only be made in minor releases (6.7, 6.8, and so on).
61 To use these classes in an application, link to
62 \c{Qt::GuiPrivate} (if using CMake), and include the headers with the \c
63 rhi prefix, for example \c{#include <rhi/qrhi.h>}.
64
65 Each QRhi instance is backed by a backend for a specific graphics API. The
66 selection of the backend is a run time choice and is up to the application
67 or library that creates the QRhi instance. Some backends are available on
68 multiple platforms (OpenGL, Vulkan, Null), while APIs specific to a given
69 platform are only available when running on the platform in question (Metal
70 on macOS/iOS, Direct3D on Windows).
71
72 The available backends currently are:
73
74 \list
75
76 \li OpenGL 2.1 / OpenGL ES 2.0 or newer. Some extensions and newer core
77 specification features are utilized when present, for example to enable
78 multisample framebuffers or compute shaders. Operating in core profile
79 contexts is supported as well. If necessary, applications can query the
80 \l{QRhi::Feature}{feature flags} at runtime to check for features that are
81 not supported in the OpenGL context backing the QRhi. The OpenGL backend
82 builds on QOpenGLContext, QOpenGLFunctions, and the related cross-platform
83 infrastructure of the Qt GUI module.
84
85 \li Direct3D 11.2 and newer (with DXGI 1.3 and newer), using Shader Model
86 5.0 or newer. When the D3D runtime has no support for 11.2 features or
87 Shader Model 5.0, initialization using an accelerated graphics device will
88 fail, but using the
89 \l{https://learn.microsoft.com/en-us/windows/win32/direct3darticles/directx-warp}{software
90 adapter} is still an option.
91
92 \li Direct3D 12 on Windows 10 version 1703 and newer, with Shader Model 5.0
93 or newer. Qt requires ID3D12Device2 to be present, hence the requirement
94 for at least version 1703 of Windows 10. The D3D12 device is by default
95 created with specifying a minimum feature level of
96 \c{D3D_FEATURE_LEVEL_11_0}.
97
98 \li Metal 1.2 or newer.
99
100 \li Vulkan 1.0 or newer, optionally utilizing some Vulkan 1.1 level
101 features.
102
103 \li Null, a "dummy" backend that issues no graphics calls at all.
104
105 \endlist
106
107 In order to allow shader code to be written once in Qt applications and
108 libraries, all shaders are expected to be written in a single language
109 which is then compiled into SPIR-V. Versions for various shading language
110 are then generated from that, together with reflection information (inputs,
111 outputs, shader resources). This is then packed into easily and efficiently
112 serializable QShader instances. The compilers and tools to generate such
113 shaders are not part of QRhi and the Qt GUI module, but the core classes
114 for using such shaders, QShader and QShaderDescription, are. The APIs and
115 tools for performing compilation and translation are part of the Qt Shader
116 Tools module.
117
118 See the \l{RHI Window Example} for an introductory example of creating a
119 portable, cross-platform application that performs accelerated 3D rendering
120 onto a QWindow using QRhi.
121
122 \section1 An Impression of the API
123
124 To provide a quick look at the API with a short yet complete example that
125 does not involve window-related setup, the following is a complete,
126 runnable cross-platform application that renders 20 frames off-screen, and
127 then saves the generated images to files after reading back the texture
128 contents from the GPU. For an example that renders on-screen, which then
129 involves setting up a QWindow and a swapchain, refer to the
130 \l{RHI Window Example}.
131
132 For brevity, the initialization of the QRhi is done based on the platform:
133 the sample code here chooses Direct 3D 12 on Windows, Metal on macOS and
134 iOS, and Vulkan otherwise. OpenGL and Direct 3D 11 are never used by this
135 application, but support for those could be introduced with a few
136 additional lines.
137
138 \snippet rhioffscreen/main.cpp 0
139
140 The result of the application is 20 \c PNG images (frame0.png -
141 frame19.png). These contain a rotating triangle with varying opacity over a
142 green background.
143
144 The vertex and fragment shaders are expected to be processed and packaged
145 into \c{.qsb} files. The Vulkan-compatible GLSL source code is the
146 following:
147
148 \e color.vert
149 \snippet rhioffscreen/color.vert 0
150
151 \e color.frag
152 \snippet rhioffscreen/color.frag 0
153
154 To manually compile and transpile these shaders to a number of targets
155 (SPIR-V, HLSL, MSL, GLSL) and generate the \c{.qsb} files the application
156 loads at run time, run \c{qsb --qt6 color.vert -o color.vert.qsb} and
157 \c{qsb --qt6 color.frag -o color.frag.qsb}. Alternatively, the Qt Shader
158 Tools module offers build system integration for CMake, the
159 \c qt_add_shaders() CMake function, that can achieve the same at build time.
160
161 \section1 Security Considerations
162
163 All data consumed by QRhi and related classes such as QShader are considered
164 trusted content.
165
166 \warning Application developers are advised to carefully consider the
167 potential implications before allowing the feeding of user-provided content
168 that is not part of the application and is not under the developers'
169 control. (this includes all vertex/index data, shaders, pipeline and draw
170 call parameters, etc.)
171
172 \section1 Design Fundamentals
173
174 A QRhi cannot be instantiated directly. Instead, use the create()
175 function. Delete the QRhi instance normally to release the graphics device.
176
177 \section2 Resources
178
179 Instances of classes deriving from QRhiResource, such as, QRhiBuffer,
180 QRhiTexture, etc., encapsulate zero, one, or more native graphics
181 resources. Instances of such classes are always created via the \c new
182 functions of the QRhi, such as, newBuffer(), newTexture(),
183 newTextureRenderTarget(), newSwapChain().
184
185 \code
186 QRhiBuffer *vbuf = rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertexData));
187 if (!vbuf->create()) { error(); }
188 // ...
189 delete vbuf;
190 \endcode
191
192 \list
193
194 \li The returned value from functions like newBuffer() is always owned by
195 the caller.
196
197 \li Just creating an instance of a QRhiResource subclass never allocates or
198 initializes any native resources. That is only done when calling the
199 \c create() function of a subclass, for example, QRhiBuffer::create() or
200 QRhiTexture::create().
201
202 \li The exceptions are
203 QRhiTextureRenderTarget::newCompatibleRenderPassDescriptor(),
204 QRhiSwapChain::newCompatibleRenderPassDescriptor(), and
205 QRhiRenderPassDescriptor::newCompatibleRenderPassDescriptor(). There is no
206 \c create() operation for these and the returned object is immediately
207 active.
208
209 \li The resource objects themselves are treated as immutable: once a
210 resource has create() called, changing any parameters via the setters, such as,
211 QRhiTexture::setPixelSize(), has no effect, unless the underlying native
212 resource is released and \c create() is called again. See more about resource
213 reuse in the sections below.
214
215 \li The underlying native resources are scheduled for releasing by the
216 QRhiResource destructor, or by calling QRhiResource::destroy(). Backends
217 often queue release requests and defer executing them to an unspecified
218 time, this is hidden from the applications. This way applications do not
219 have to worry about releasing native resources that may still be in use by
220 an in-flight frame.
221
222 \li Note that this does not mean that a QRhiResource can freely be
223 destroy()'ed or deleted within a frame (that is, in a
224 \l{QRhi::beginFrame()}{beginFrame()} - \l{QRhi::endFrame()}{endFrame()}
225 section). As a general rule, all referenced QRhiResource objects must stay
226 unchanged until the frame is submitted by calling
227 \l{QRhi::endFrame()}{endFrame()}. To ease this,
228 QRhiResource::deleteLater() is provided as a convenience.
229
230 \endlist
231
232 \section2 Command buffers and deferred command execution
233
234 Regardless of the design and capabilities of the underlying graphics API,
235 all QRhi backends implement some level of command buffers. No
236 QRhiCommandBuffer function issues any native bind or draw command (such as,
237 \c glDrawElements) directly. Commands are always recorded in a queue,
238 either native or provided by the QRhi backend. The command buffer is
239 submitted, and so execution starts only upon QRhi::endFrame() or
240 QRhi::finish().
241
242 The deferred nature has consequences for some types of objects. For example,
243 writing to a dynamic buffer multiple times within a frame, in case such
244 buffers are backed by host-visible memory, will result in making the
245 results of all writes are visible to all draw calls in the command buffer
246 of the frame, regardless of when the dynamic buffer update was recorded
247 relative to a draw call.
248
249 Furthermore, instances of QRhiResource subclasses must be treated immutable
250 within a frame in which they are referenced in any way. Create
251 all resources upfront, before starting to record commands for the next
252 frame. Reusing a QRhiResource instance within a frame (by calling \c create()
253 then referencing it again in the same \c{beginFrame - endFrame} section)
254 should be avoided as it may lead to unexpected results, depending on the
255 backend.
256
257 As a general rule, all referenced QRhiResource objects must stay valid and
258 unmodified until the frame is submitted by calling
259 \l{QRhi::endFrame()}{endFrame()}. On the other hand, calling
260 \l{QRhiResource::destroy()}{destroy()} or deleting the QRhiResource are
261 always safe once the frame is submitted, regardless of the status of the
262 underlying native resources (which may still be in use by the GPU - but
263 that is taken care of internally).
264
265 Unlike APIs like OpenGL, upload and copy type of commands cannot be mixed
266 with draw commands. The typical renderer will involve a sequence similar to
267 the following:
268
269 \list
270 \li (re)create resources
271 \li begin frame
272 \li record/issue uploads and copies
273 \li start recording a render pass
274 \li record draw calls
275 \li end render pass
276 \li end frame
277 \endlist
278
279 Recording copy type of operations happens via QRhiResourceUpdateBatch. Such
280 operations are committed typically on
281 \l{QRhiCommandBuffer::beginPass()}{beginPass()}.
282
283 When working with legacy rendering engines designed for OpenGL, the
284 migration to QRhi often involves redesigning from having a single \c render
285 step (that performs copies and uploads, clears buffers, and issues draw
286 calls, all mixed together) to a clearly separated, two phase \c prepare -
287 \c render setup where the \c render step only starts a renderpass and
288 records draw calls, while all resource creation and queuing of updates,
289 uploads and copies happens beforehand, in the \c prepare step.
290
291 QRhi does not at the moment allow freely creating and submitting command
292 buffers. This may be lifted in the future to some extent, in particular if
293 compute support is introduced, but the model of well defined
294 \c{frame-start} and \c{frame-end} points, combined with a dedicated,
295 "frame" command buffer, where \c{frame-end} implies presenting, is going to
296 remain the primary way of operating since this is what fits Qt's various UI
297 technologies best.
298
299 \section2 Threading
300
301 A QRhi instance and the associated resources can be created and used on any
302 thread but all usage must be limited to that one single thread. When
303 rendering to multiple QWindows in an application, having a dedicated thread
304 and QRhi instance for each window is often advisable, as this can eliminate
305 issues with unexpected throttling caused by presenting to multiple windows.
306 Conceptually that is then the same as how Qt Quick scene graph's threaded
307 render loop operates when working directly with OpenGL: one thread for each
308 window, one QOpenGLContext for each thread. When moving onto QRhi,
309 QOpenGLContext is replaced by QRhi, making the migration straightforward.
310
311 When it comes to externally created native objects, such as OpenGL contexts
312 passed in via QRhiGles2NativeHandles, it is up to the application to ensure
313 they are not misused by other threads.
314
315 Resources are not shareable between QRhi instances. This is an intentional
316 choice since QRhi hides most queue, command buffer, and resource
317 synchronization related tasks, and provides no API for them. Safe and
318 efficient concurrent use of graphics resources from multiple threads is
319 tied to those concepts, however, and is thus a topic that is currently out
320 of scope, but may be introduced in the future.
321
322 \note The Metal backend requires that an autorelease pool is available on
323 the rendering thread, ideally wrapping each iteration of the render loop.
324 This needs no action from the users of QRhi when rendering on the main
325 (gui) thread, but becomes important when a separate, dedicated render
326 thread is used.
327
328 \section2 Resource synchronization
329
330 QRhi does not expose APIs for resource barriers or image layout
331 transitions. Such synchronization is done implicitly by the backends, where
332 applicable (for example, Vulkan), by tracking resource usage as necessary.
333 Buffer and image barriers are inserted before render or compute passes
334 transparently to the application.
335
336 \note Resources within a render or compute pass are expected to be bound to
337 a single usage during that pass. For example, a buffer can be used as
338 vertex, index, uniform, or storage buffer, but not a combination of them
339 within a single pass. However, it is perfectly fine to use a buffer as a
340 storage buffer in a compute pass, and then as a vertex buffer in a render
341 pass, for example, assuming the buffer declared both usages upon creation.
342
343 \note Textures have this rule relaxed in certain cases, because using two
344 subresources (typically two different mip levels) of the same texture for
345 different access (one for load, one for store) is supported even within the
346 same pass.
347
348 \section2 Resource reuse
349
350 From the user's point of view a QRhiResource is reusable immediately after
351 calling QRhiResource::destroy(). With the exception of swapchains, calling
352 \c create() on an already created object does an implicit \c destroy(). This
353 provides a handy shortcut to reuse a QRhiResource instance with different
354 parameters, with a new native graphics object underneath.
355
356 The importance of reusing the same object lies in the fact that some
357 objects reference other objects: for example, a QRhiShaderResourceBindings
358 can reference QRhiBuffer, QRhiTexture, and QRhiSampler instances. If in a
359 later frame one of these buffers need to be resized or a sampler parameter
360 needs changing, destroying and creating a whole new QRhiBuffer or
361 QRhiSampler would invalidate all references to the old instance. By just
362 changing the appropriate parameters via QRhiBuffer::setSize() or similar
363 and then calling QRhiBuffer::create(), everything works as expected and
364 there is no need to touch the QRhiShaderResourceBindings at all, even
365 though there is a good chance that under the hood the QRhiBuffer is now
366 backed by a whole new native buffer.
367
368 \code
369 QRhiBuffer *ubuf = rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 256);
370 ubuf->create();
371
372 QRhiShaderResourceBindings *srb = rhi->newShaderResourceBindings()
373 srb->setBindings({
374 QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, ubuf)
375 });
376 srb->create();
377
378 // ...
379
380 // now in a later frame we need to grow the buffer to a larger size
381 ubuf->setSize(512);
382 ubuf->create(); // same as ubuf->destroy(); ubuf->create();
383
384 // srb needs no changes whatsoever, any references in it to ubuf
385 // stay valid. When it comes to internal details, such as that
386 // ubuf may now be backed by a completely different native buffer
387 // resource, that is is recognized and handled automatically by the
388 // next setShaderResources().
389 \endcode
390
391 QRhiTextureRenderTarget offers the same contract: calling
392 QRhiCommandBuffer::beginPass() is safe even when one of the render target's
393 associated textures or renderbuffers has been rebuilt (by calling \c
394 create() on it) since the creation of the render target object. This allows
395 the application to resize a texture by setting a new pixel size on the
396 QRhiTexture and calling create(), thus creating a whole new native texture
397 resource underneath, without having to update the QRhiTextureRenderTarget
398 as that will be done implicitly in beginPass().
399
400 \section2 Pooled objects
401
402 In addition to resources, there are pooled objects as well, such as,
403 QRhiResourceUpdateBatch. An instance is retrieved via a \c next function,
404 such as, nextResourceUpdateBatch(). The caller does not own the returned
405 instance in this case. The only valid way of operating here is calling
406 functions on the QRhiResourceUpdateBatch and then passing it to
407 QRhiCommandBuffer::beginPass() or QRhiCommandBuffer::endPass(). These
408 functions take care of returning the batch to the pool. Alternatively, a
409 batch can be "canceled" and returned to the pool without processing by
410 calling QRhiResourceUpdateBatch::release().
411
412 A typical pattern is thus:
413
414 \code
415 QRhiResourceUpdateBatch *resUpdates = rhi->nextResourceUpdateBatch();
416 // ...
417 resUpdates->updateDynamicBuffer(ubuf, 0, 64, mvp.constData());
418 if (!image.isNull()) {
419 resUpdates->uploadTexture(texture, image);
420 image = QImage();
421 }
422 // ...
423 QRhiCommandBuffer *cb = m_sc->currentFrameCommandBuffer();
424 // note the last argument
425 cb->beginPass(swapchain->currentFrameRenderTarget(), clearCol, clearDs, resUpdates);
426 \endcode
427
428 \section2 Swapchain specifics
429
430 QRhiSwapChain features some special semantics due to the peculiar nature of
431 swapchains.
432
433 \list
434
435 \li It has no \c create() but rather a QRhiSwapChain::createOrResize().
436 Repeatedly calling this function is \b not the same as calling
437 QRhiSwapChain::destroy() followed by QRhiSwapChain::createOrResize(). This
438 is because swapchains often have ways to handle the case where buffers need
439 to be resized in a manner that is more efficient than a brute force
440 destroying and recreating from scratch.
441
442 \li An active QRhiSwapChain must be released by calling
443 \l{QRhiSwapChain::destroy()}{destroy()}, or by destroying the object, before
444 the QWindow's underlying QPlatformWindow, and so the associated native
445 window object, is destroyed. It should not be postponed because releasing
446 the swapchain may become problematic (and with some APIs, like Vulkan, is
447 explicitly disallowed) when the native window is not around anymore, for
448 example because the QPlatformWindow got destroyed upon getting a
449 QWindow::close(). Therefore, releasing the swapchain must happen whenever
450 the targeted QWindow sends the
451 QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed event. If the event does
452 not arrive before the destruction of the QWindow - this can happen when
453 using QCoreApplication::quit() -, then check QWindow::handle() after the
454 event loop exits and invoke the swapchain release when non-null (meaning
455 the underlying native window is still around).
456
457 \endlist
458
459 \section2 Coordinate system differences between graphics APIs
460
461 The graphics APIs that QRhi supports do not use the same coordinate systems.
462 They differ in the direction of the Y axis in normalized device coordinates
463 (NDC), in the origin of framebuffers and images, and in the depth range of
464 clip space:
465
466 \table
467 \header
468 \li Graphics API
469 \li Y axis in NDC
470 \li Origin of framebuffers and images
471 \li Depth range in clip space
472 \row
473 \li OpenGL and OpenGL ES
474 \li Up
475 \li Bottom-left
476 \li [-1, 1]
477 \row
478 \li Vulkan
479 \li Down
480 \li Top-left
481 \li [0, 1]
482 \row
483 \li Direct3D 11, Direct3D 12, and Metal
484 \li Up
485 \li Top-left
486 \li [0, 1]
487 \endtable
488
489 To query these values at runtime, call \l QRhi::isYUpInNDC(),
490 \l QRhi::isYUpInFramebuffer(), and \l QRhi::isClipDepthZeroToOne().
491
492 Most renderers do not need these queries. A renderer that uses a projection
493 matrix, such as a matrix from \l QMatrix4x4::perspective(), can multiply the
494 projection matrix with \l QRhi::clipSpaceCorrMatrix(). The correction matrix
495 flips the Y axis for Vulkan, and maps the depth range [-1, 1] to [0, 1] for
496 every graphics API except OpenGL. The renderer can then use OpenGL-style
497 vertex data, with the Y axis pointing up, with every graphics API.
498
499 The correction matrix is not enough in these cases:
500
501 \list
502 \li The vertex shader uses no projection matrix, for example, because
503 the vertex data is already in NDC.
504 \li The shader logic depends on the direction of the Y axis, for
505 example, when the shader calculates colors or texture coordinates
506 from vertex positions.
507 \li The shaders read or write depth values, for example, in some types
508 of shadow mapping.
509 \endlist
510
511 In these cases, query the values and adjust the vertex positions, texture
512 coordinates, or depth values in the application code or in the shaders.
513
514 \section2 Ownership
515
516 The general rule is no ownership transfer. Creating a QRhi with an already
517 existing graphics device does not mean the QRhi takes ownership of the
518 device object. Similarly, ownership is not given away when a device or
519 texture object is "exported" via QRhi::nativeHandles() or
520 QRhiTexture::nativeTexture(). Most importantly, passing pointers in structs
521 and via setters does not transfer ownership.
522
523 \section1 Troubleshooting and Profiling
524
525 \section2 Error reporting
526
527 Functions such as \l QRhi::create() and the resource classes' \c create()
528 member functions (e.g., \l QRhiBuffer::create()) indicate failure with the
529 return value (\nullptr or
530 \c false, respectively). When working with QShader, \l QShader::fromSerialized()
531 returns an invalid QShader (for which \l{QShader::isValid()}{isValid()} returns
532 \c false) when the data passed to the function cannot be successfully deserialized.
533 Some functions, beginFrame() in particular, may also sometimes report "soft failures",
534 such as \l FrameOpSwapChainOutOfDate, which do not indicate an unrecoverable error,
535 but rather should be seen as a "try again later" response.
536
537 Warnings and errors may get printed at any time to the debug output via
538 qWarning(). It is therefore always advisable to inspect the output of the
539 application.
540
541 Additional debug messages can be enabled via the following logging
542 categories. Messages from these categories are not printed by default
543 unless explicitly enabled via QLoggingCategory or the \c QT_LOGGING_RULES
544 environment variable. For better interoperation with Qt Quick, the
545 environment variable \c{QSG_INFO} also enables these debug prints.
546
547 \list
548 \li \c{qt.rhi.general}
549 \endlist
550
551 Additionally, applications can query the \l{QRhi::backendName()}{QRhi
552 backend name} and
553 \l{QRhi::driverInfo()}{graphics device information} from a successfully
554 initialized QRhi. This can then be printed to the user or stored in the
555 application logs even in production builds, if desired.
556
557 \section2 Investigating rendering problems
558
559 When the rendering results are not as expected, or the application is
560 experiencing problems, always consider checking with the native 3D
561 APIs' debug and validation facilities. QRhi itself features limited error
562 checking since replicating the already existing, vast amount of
563 functionality in the underlying layers is not reasonable.
564
565 \list
566
567 \li For Vulkan, controlling the
568 \l{https://github.com/KhronosGroup/Vulkan-ValidationLayers}{Vulkan
569 Validation Layers} is not in the scope of the QRhi, but rather can be
570 achieved by configuring the \l QVulkanInstance with the appropriate layers.
571 For example, call \c{instance.setLayers({ "VK_LAYER_KHRONOS_validation" });}
572 before invoking \l{QVulkanInstance::create()}{create()} on the QVulkanInstance.
573 (note that this assumes that the validation layers are actually installed
574 and available, e.g. from the Vulkan SDK) By default, QVulkanInstance conveniently
575 redirects the Vulkan debug messages to qDebug, meaning the validation messages get
576 printed just like other Qt warnings.
577
578 \li With Direct 3D 11 and 12, a graphics device with the debug layer
579 enabled can be requested by toggling the \c enableDebugLayer flag in the
580 appropriate \l{QRhiD3D11InitParams}{init params struct}. With Direct 3D 12 the
581 messages are then printed via qDebug, just like the Vulkan validation
582 messages, as long as the debug layer supports message callbacks. Otherwise,
583 and always with Direct 3D 11, the messages appear on the debug output, which
584 is visible in Qt Creator's messages panel or via a tool such as
585 \l{https://learn.microsoft.com/en-us/sysinternals/downloads/debugview}{DebugView}.
586
587 \li For Metal, controlling Metal Validation is outside of QRhi's scope.
588 Rather, to enable validation, run the application with the environment
589 variable \c{METAL_DEVICE_WRAPPER_TYPE=1} set, or run the application within
590 XCode. There may also be further settings and environment variable in modern
591 XCode and macOS versions. See for instance
592 \l{https://developer.apple.com/documentation/metal/diagnosing_metal_programming_issues_early}{this
593 page}.
594
595 \endlist
596
597 \section2 Frame captures and performance profiling
598
599 A Qt application rendering with QRhi to a window while relying on a 3D API
600 under the hood, is, from the windowing and graphics pipeline perspective at
601 least, no different from any other (non-Qt) applications using the same 3D
602 API. This means that tools and practices for debugging and profiling
603 applications involving 3D graphics, such as games, all apply to such a Qt
604 application as well.
605
606 A few examples of tools that can provide insights into the rendering
607 internals of Qt applications that use QRhi, which includes Qt Quick and Qt
608 Quick 3D based projects as well:
609
610 \list
611
612 \li \l{https://renderdoc.org/}{RenderDoc} allows taking frame captures and
613 introspecting the recorded commands and pipeline state on Windows and Linux
614 for applications using OpenGL, Vulkan, D3D11, or D3D12. When trying to
615 figure out why some parts of the 3D scene do not show up as expected,
616 RenderDoc is often a fast and efficient way to check the pipeline stages
617 and the related state and discover the missing or incorrect value. It is
618 also a tool that is actively used when developing Qt itself.
619
620 \li For NVIDIA-based systems,
621 \l{https://developer.nvidia.com/nsight-graphics}{Nsight Graphics} provides
622 a graphics debugger tool on Windows and Linux. In addition to investigating the commands
623 in the frame and the pipeline, the vendor-specific tools allow looking at timings and
624 hardware performance information, which is not something simple frame captures can provide.
625
626 \li For AMD-based systems, the \l{https://gpuopen.com/rgp/}{Radeon GPU
627 Profiler} can be used to gain deeper insights into the application's
628 rendering and its performance.
629
630 \li Overlays showing live performance information can be highly useful as well, and
631 are often preferable to implementing simple frames-per-second counters within the
632 application itself, since they are more reliable and show more information. An example
633 is \l{https://game.intel.com/us/intel-presentmon/}{PresentMon}, which supports
634 graphics hardware from multiple vendors.
635
636 \li As QRhi supports Direct 3D 12, using
637 \l{https://devblogs.microsoft.com/pix/download/}{PIX}, a performance tuning
638 and debugging tool for DirectX 12 games on Windows is an option as well.
639
640 \li On macOS,
641 \l{https://developer.apple.com/documentation/metal/debugging_tools/viewing_your_gpu_workload_with_the_metal_debugger}{the
642 XCode Metal debugger} can be used to take and introspect frame
643 captures, to investigate performance details, and debug shaders. In macOS 13 it is also possible
644 to enable an overlay that displays frame rate and other information for any Metal-based window by
645 setting the environment variable \c{MTL_HUD_ENABLED=1}.
646
647 \endlist
648
649 On mobile and embedded platforms, there may be vendor and platform-specific
650 tools, provided by the GPU or SoC vendor, available to perform performance
651 profiling of application using OpenGL ES or Vulkan.
652
653 When capturing frames, remember that objects and groups of commands can be
654 named via debug markers, as long as \l{QRhi::EnableDebugMarkers}{debug
655 markers were enabled} for the QRhi, and the graphics API in use supports
656 this. To annotate the command stream, call
657 \l{QRhiCommandBuffer::debugMarkBegin()}{debugMarkBegin()},
658 \l{QRhiCommandBuffer::debugMarkEnd()}{debugMarkEnd()} and/or
659 \l{QRhiCommandBuffer::debugMarkMsg()}{debugMarkMsg()}.
660 This can be particularly useful in larger frames with multiple render passes.
661 Resources are named by calling \l{QRhiResource::setName()}{setName()} before create().
662
663 To perform basic timing measurements on the CPU and GPU side within the
664 application, \l QElapsedTimer and
665 \l QRhiCommandBuffer::lastCompletedGpuTime() can be used. The latter is
666 only available with select graphics APIs at the moment and requires opting
667 in via the \l QRhi::EnableTimestamps flag.
668
669 \section2 Resource leak checking
670
671 When destroying a QRhi object without properly destroying all buffers,
672 textures, and other resources created from it, warnings about this are
673 printed to the debug output whenever the application is a debug build, or
674 when the \c QT_RHI_LEAK_CHECK environment variable is set to a non-zero
675 value. This is a simple way to discover design issues around resource
676 handling within the application rendering logic. Note however that some
677 platforms and underlying graphics APIs may perform their own allocation and
678 resource leak detection as well, over which Qt will have no direct control.
679 For example, when using Vulkan, the memory allocator may raise failing
680 assertions in debug builds when resources that own graphics memory
681 allocations are not destroyed before the QRhi. In addition, the Vulkan
682 validation layer, when enabled, will issue warnings about native graphics
683 resources that were not released. Similarly, with Direct 3D warnings may
684 get printed about unreleased COM objects when the application does not
685 destroy the QRhi and its resources in the correct order.
686
687 \sa {RHI Window Example}, QRhiCommandBuffer, QRhiResourceUpdateBatch,
688 QRhiShaderResourceBindings, QShader, QRhiBuffer, QRhiTexture,
689 QRhiRenderBuffer, QRhiSampler, QRhiTextureRenderTarget,
690 QRhiGraphicsPipeline, QRhiComputePipeline, QRhiSwapChain
691 */
692
693/*!
694 \enum QRhi::Implementation
695 Describes which graphics API-specific backend gets used by a QRhi instance.
696
697 \value Null
698 \value Vulkan
699 \value OpenGLES2
700 \value D3D11
701 \value D3D12
702 \value Metal
703 */
704
705/*!
706 \enum QRhi::Flag
707 Describes what special features to enable.
708
709 \value EnableDebugMarkers Enables debug marker groups. Without this frame
710 debugging features like making debug groups and custom resource name
711 visible in external GPU debugging tools will not be available and functions
712 like QRhiCommandBuffer::debugMarkBegin() will become no-ops. Avoid enabling
713 in production builds as it may involve a small performance impact. Has no
714 effect when the QRhi::DebugMarkers feature is not reported as supported.
715
716 \value EnableTimestamps Enables GPU timestamp collection. When not set,
717 QRhiCommandBuffer::lastCompletedGpuTime() always returns 0. Enable this
718 only when needed since there may be a small amount of extra work involved
719 (e.g. timestamp queries), depending on the underlying graphics API. Has no
720 effect when the QRhi::Timestamps feature is not reported as supported.
721
722 \value PreferSoftwareRenderer Indicates that backends should prefer
723 choosing an adapter or physical device that renders in software on the CPU.
724 For example, with Direct3D there is typically a "Basic Render Driver"
725 adapter available with \c{DXGI_ADAPTER_FLAG_SOFTWARE}. Setting this flag
726 requests the backend to choose that adapter over any other, as long as no
727 specific adapter was forced by other backend-specific means. With Vulkan
728 this maps to preferring physical devices with
729 \c{VK_PHYSICAL_DEVICE_TYPE_CPU}. When not available, or when it is not
730 possible to decide if an adapter/device is software-based, this flag is
731 ignored. It may also be ignored with graphics APIs that have no concept and
732 means of enumerating adapters/devices.
733
734 \value EnablePipelineCacheDataSave Enables retrieving the pipeline cache
735 contents, where applicable. When not set, pipelineCacheData() will return an
736 empty blob always. With backends where retrieving and restoring the pipeline
737 cache contents is not supported, the flag has no effect and the serialized
738 cache data is always empty. The flag provides an opt-in mechanism because
739 the cost of maintaining the related data structures is not insignificant
740 with some backends. With Vulkan this feature maps directly to
741 VkPipelineCache, vkGetPipelineCacheData and
742 VkPipelineCacheCreateInfo::pInitialData. With Direct3D 12
743 ID3D12PipelineLibrary is used. With Direct3D 11 there is no real pipline
744 cache, but the results of HLSL->DXBC compilations are stored and can be
745 serialized/deserialized via this mechanism. This allows skipping the time
746 consuming D3DCompile() in future runs of the applications for shaders that
747 come with HLSL source instead of offline pre-compiled bytecode. This can
748 provide a huge boost in startup and load times, if there is a lot of HLSL
749 source compilation happening. With OpenGL the "pipeline cache" is simulated
750 by retrieving and loading shader program binaries (if supported by the
751 driver). With OpenGL there are additional, disk-based caching mechanisms for
752 shader/program binaries provided by Qt. Writing to those may get disabled
753 whenever this flag is set since storing program binaries to multiple caches
754 is not sensible.
755
756 \value SuppressSmokeTestWarnings Indicates that, with backends where this
757 is relevant, certain, non-fatal QRhi::create() failures should not
758 produce qWarning() calls. For example, with D3D11, passing this flag
759 makes a number of warning messages (that appear due to QRhi::create()
760 failing) to become categorized debug prints instead under the commonly used
761 \c{qt.rhi.general} logging category. This can be used by engines, such as
762 Qt Quick, that feature fallback logic, i.e. they retry calling create()
763 with a different set of flags (such as, \l PreferSoftwareRenderer), in order
764 to hide the unconditional warnings from the output that would be printed
765 when the first create() attempt had failed.
766 */
767
768/*!
769 \enum QRhi::FrameOpResult
770 Describes the result of operations that can have a soft failure.
771
772 \value FrameOpSuccess Success
773
774 \value FrameOpError Unspecified error
775
776 \value FrameOpSwapChainOutOfDate The swapchain is in an inconsistent state
777 internally. This can be recoverable by attempting to repeat the operation
778 (such as, beginFrame()) later.
779
780 \value FrameOpDeviceLost The graphics device was lost. This can be
781 recoverable by attempting to repeat the operation (such as, beginFrame())
782 after releasing and reinitializing all objects backed by native graphics
783 resources. See isDeviceLost().
784 */
785
786/*!
787 \enum QRhi::Feature
788 Flag values to indicate what features are supported by the backend currently in use.
789
790 \value MultisampleTexture Indicates that textures with a sample count larger
791 than 1 are supported. In practice this feature will be unsupported with
792 OpenGL ES versions older than 3.1, and OpenGL older than 3.0.
793
794 \value MultisampleRenderBuffer Indicates that renderbuffers with a sample
795 count larger than 1 are supported. In practice this feature will be
796 unsupported with OpenGL ES 2.0, and may also be unsupported with OpenGL 2.x
797 unless the relevant extensions are present.
798
799 \value DebugMarkers Indicates that debug marker groups (and so
800 QRhiCommandBuffer::debugMarkBegin()) are supported.
801
802 \value Timestamps Indicates that command buffer timestamps are supported.
803 Relevant for QRhiCommandBuffer::lastCompletedGpuTime(). This can be
804 expected to be supported on Metal, Vulkan, Direct 3D 11 and 12, and OpenGL
805 contexts of version 3.3 or newer. However, with some of these APIs support
806 for timestamp queries is technically optional, and therefore it cannot be
807 guaranteed that this feature is always supported with every implementation
808 of them.
809
810 \value Instancing Indicates that instanced drawing is supported. In
811 practice this feature will be unsupported with OpenGL ES 2.0 and OpenGL
812 3.2 or older.
813
814 \value CustomInstanceStepRate Indicates that instance step rates other
815 than 1 are supported. In practice this feature will always be unsupported
816 with OpenGL. In addition, running with Vulkan 1.0 without
817 VK_EXT_vertex_attribute_divisor will also lead to reporting false for this
818 feature.
819
820 \value PrimitiveRestart Indicates that restarting the assembly of
821 primitives when encountering an index value of 0xFFFF
822 (\l{QRhiCommandBuffer::IndexUInt16}{IndexUInt16}) or 0xFFFFFFFF
823 (\l{QRhiCommandBuffer::IndexUInt32}{IndexUInt32}) is enabled, for certain
824 primitive topologies at least. QRhi will try to enable this with all
825 backends, but in some cases it will not be supported. Dynamically
826 controlling primitive restart is not possible since with some APIs
827 primitive restart with a fixed index is always on. Applications must assume
828 that whenever this feature is reported as supported, the above mentioned
829 index values \c may be treated specially, depending on the topology. The
830 only two topologies where primitive restart is guaranteed to behave
831 identically across backends, as long as this feature is reported as
832 supported, are \l{QRhiGraphicsPipeline::LineStrip}{LineStrip} and
833 \l{QRhiGraphicsPipeline::TriangleStrip}{TriangleStrip}.
834
835 \value NonDynamicUniformBuffers Indicates that creating buffers with the
836 usage \l{QRhiBuffer::UniformBuffer}{UniformBuffer} and the types
837 \l{QRhiBuffer::Immutable}{Immutable} or \l{QRhiBuffer::Static}{Static} is
838 supported. When reported as unsupported, uniform (constant) buffers must be
839 created as \l{QRhiBuffer::Dynamic}{Dynamic}. (which is recommended
840 regardless)
841
842 \value NonFourAlignedEffectiveIndexBufferOffset Indicates that effective
843 index buffer offsets (\c{indexOffset + firstIndex * indexComponentSize})
844 that are not 4 byte aligned are supported. When not supported, attempting
845 to issue a \l{QRhiCommandBuffer::drawIndexed()}{drawIndexed()} with a
846 non-aligned effective offset may lead to unspecified behavior. Relevant in
847 particular for Metal, where this will be reported as unsupported.
848
849 \value NPOTTextureRepeat Indicates that the
850 \l{QRhiSampler::Repeat}{Repeat} wrap mode and mipmap filtering modes are
851 supported for textures with a non-power-of-two size. In practice this can
852 only be false with OpenGL ES 2.0 implementations without
853 \c{GL_OES_texture_npot}.
854
855 \value RedOrAlpha8IsRed Indicates that the
856 \l{QRhiTexture::RED_OR_ALPHA8}{RED_OR_ALPHA8} format maps to a one
857 component 8-bit \c red format. This is the case for all backends except
858 OpenGL when using either OpenGL ES or a non-core profile context. There
859 \c{GL_ALPHA}, a one component 8-bit \c alpha format, is used
860 instead. Using the special texture format allows having a single code
861 path for creating textures, leaving it up to the backend to decide the
862 actual format, while the feature flag can be used to pick the
863 appropriate shader variant for sampling the texture.
864
865 \value ElementIndexUint Indicates that 32-bit unsigned integer elements are
866 supported in the index buffer. In practice this is true everywhere except
867 when running on plain OpenGL ES 2.0 implementations without the necessary
868 extension. When false, only 16-bit unsigned elements are supported in the
869 index buffer.
870
871 \value Compute Indicates that compute shaders, image load/store, and
872 storage buffers are supported. OpenGL older than 4.3 and OpenGL ES older
873 than 3.1 have no compute support. This does not imply support for writing
874 storage buffers in fragment shaders; see FragmentStoresAndAtomics.
875
876 \value [since 6.13] FragmentStoresAndAtomics Indicates that fragment
877 shaders support storage buffer writes and 32-bit integer atomic operations
878 on storage buffers. This does not imply support for texture atomics,
879 floating-point atomics, or 64-bit atomics. Applications must also respect
880 the MaxFragmentStorageBuffers resource limit and any resource binding
881 limits imposed by the graphics API. In particular, Direct3D 11 shares
882 unordered access view slots with render target outputs.
883
884 \value WideLines Indicates that lines with a width other than 1 are
885 supported. When reported as not supported, the line width set on the
886 graphics pipeline state is ignored. This can always be false with some
887 backends (D3D11, D3D12, Metal). With Vulkan, the value depends on the
888 implementation. With OpenGL, wide lines are not supported in core profile
889 contexts.
890
891 \value VertexShaderPointSize Indicates that the size of rasterized points
892 set via \c{gl_PointSize} in the vertex shader is taken into account. When
893 reported as not supported, drawing points with a size other than 1 is not
894 supported. Setting \c{gl_PointSize} in the shader is still valid then, but
895 is ignored. (for example, when generating HLSL, the assignment is silently
896 dropped from the generated code) Note that some APIs (Metal, Vulkan)
897 require the point size to be set in the shader explicitly whenever drawing
898 points, even when the size is 1, as they do not automatically default to 1.
899
900 \value BaseVertex Indicates that
901 \l{QRhiCommandBuffer::drawIndexed()}{drawIndexed()} supports the \c
902 vertexOffset argument. When reported as not supported, the vertexOffset
903 value in an indexed draw is ignored. In practice this feature will be
904 unsupported with OpenGL and OpenGL ES versions lower than 3.2, and with
905 Metal on older iOS devices, including the iOS Simulator.
906
907 \value BaseInstance Indicates that instanced draw commands support the \c
908 firstInstance argument. When reported as not supported, the firstInstance
909 value is ignored and the instance ID starts from 0. In practice this feature
910 will be unsupported with Metal on older iOS devices, including the iOS
911 Simulator, and with OpenGL ES, which has no support for draw calls with a
912 base instance at all. With OpenGL it needs version 4.2 or newer, or
913 \c GL_ARB_base_instance. Applications relying on a non-zero base instance
914 should be aware of the InstanceIndexIncludesBaseInstance feature as well.
915
916 \value TriangleFanTopology Indicates that QRhiGraphicsPipeline::setTopology()
917 supports QRhiGraphicsPipeline::TriangleFan. In practice this feature will be
918 unsupported with Metal and Direct 3D 11/12.
919
920 \value ReadBackNonUniformBuffer Indicates that
921 \l{QRhiResourceUpdateBatch::readBackBuffer()}{reading buffer contents} is
922 supported for QRhiBuffer instances with a usage different than
923 UniformBuffer. In practice this feature will be unsupported with OpenGL ES
924 2.0.
925
926 \value ReadBackNonBaseMipLevel Indicates that specifying a mip level other
927 than 0 is supported when reading back texture contents. When not supported,
928 specifying a non-zero level in QRhiReadbackDescription leads to returning
929 an all-zero image. In practice this feature will be unsupported with OpenGL
930 ES 2.0.
931
932 \value TexelFetch Indicates that texelFetch() and textureLod() are available
933 in shaders. In practice this will be reported as unsupported with OpenGL ES
934 2.0 and OpenGL 2.x contexts, because GLSL 100 es and versions before 130 do
935 not support these functions.
936
937 \value RenderToNonBaseMipLevel Indicates that specifying a mip level other
938 than 0 is supported when creating a QRhiTextureRenderTarget with a
939 QRhiTexture as its color attachment. When not supported, create() will fail
940 whenever the target mip level is not zero. In practice this feature will be
941 unsupported with OpenGL ES 2.0.
942
943 \value IntAttributes Indicates that specifying input attributes with
944 signed and unsigned integer types for a shader pipeline is supported. When
945 not supported,
946 \l{QRhiGraphicsPipeline::create()}{QRhiGraphicsPipeline::create()} will
947 succeed but show a warning message and the values of the target attributes
948 will be broken. In practice this feature will be unsupported with OpenGL ES
949 2.0 and OpenGL 2.x.
950
951 \value ScreenSpaceDerivatives Indicates that functions such as dFdx(),
952 dFdy(), and fwidth() are supported in shaders. In practice this feature will
953 be unsupported with OpenGL ES 2.0 without the GL_OES_standard_derivatives
954 extension.
955
956 \value ReadBackAnyTextureFormat Indicates that reading back texture
957 contents can be expected to work for any QRhiTexture::Format. Backends
958 other than OpenGL can be expected to return true for this feature. When
959 reported as false, which will typically happen with OpenGL, only the
960 formats QRhiTexture::RGBA8 and QRhiTexture::BGRA8 are guaranteed to be
961 supported for readbacks. In addition, with OpenGL, but not OpenGL ES,
962 reading back the 1 byte per component formats QRhiTexture::R8 and
963 QRhiTexture::RED_OR_ALPHA8 are supported as well, and so are the depth and
964 depth-stencil formats QRhiTexture::D16, D24, D24S8, D32F and D32FS8, as long
965 as the format is supported in the first place. Reading back floating
966 point formats QRhiTexture::RGBA16F and RGBA32F may work too with OpenGL, as
967 long as the implementation provides support for these, but QRhi can give no
968 guarantees, as indicated by this flag.
969
970 \value PipelineCacheDataLoadSave Indicates that the pipelineCacheData() and
971 setPipelineCacheData() functions are functional. When not supported, the
972 functions will not perform any action, the retrieved blob is always empty,
973 and thus no benefits can be expected from retrieving and, during a
974 subsequent run of the application, reloading the pipeline cache content.
975
976 \value ImageDataStride Indicates that specifying a custom stride (row
977 length) for raw image data in texture uploads is supported. When not
978 supported (which can happen when the underlying API is OpenGL ES 2.0 without
979 support for GL_UNPACK_ROW_LENGTH),
980 QRhiTextureSubresourceUploadDescription::setDataStride() must not be used.
981
982 \value RenderBufferImport Indicates that QRhiRenderBuffer::createFrom() is
983 supported. For most graphics APIs this is not sensible because
984 QRhiRenderBuffer encapsulates texture objects internally, just like
985 QRhiTexture. With OpenGL however, renderbuffer object exist as a separate
986 object type in the API, and in certain environments (for example, where one
987 may want to associated a renderbuffer object with an EGLImage object) it is
988 important to allow wrapping an existing OpenGL renderbuffer object with a
989 QRhiRenderBuffer.
990
991 \value ThreeDimensionalTextures Indicates that 3D textures are supported.
992 In practice this feature will be unsupported with OpenGL and OpenGL ES
993 versions lower than 3.0.
994
995 \value RenderTo3DTextureSlice Indicates that rendering to a slice in a 3D
996 texture is supported. This can be unsupported with Vulkan 1.0 due to
997 relying on VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT which is a Vulkan 1.1
998 feature.
999
1000 \value TextureArrays Indicates that texture arrays are supported and
1001 QRhi::newTextureArray() is functional. Note that even when texture arrays
1002 are not supported, arrays of textures are still available as those are two
1003 independent features.
1004
1005 \value Tessellation Indicates that the tessellation control and evaluation
1006 stages are supported. When reported as supported, the topology of a
1007 QRhiGraphicsPipeline can be set to
1008 \l{QRhiGraphicsPipeline::Patches}{Patches}, the number of control points
1009 can be set via
1010 \l{QRhiGraphicsPipeline::setPatchControlPointCount()}{setPatchControlPointCount()},
1011 and shaders for tessellation control and evaluation can be specified in the
1012 QRhiShaderStage list. Tessellation shaders have portability issues between
1013 APIs (for example, translating GLSL/SPIR-V to HLSL is problematic due to
1014 the way hull shaders are structured, whereas Metal uses a somewhat
1015 different tessellation pipeline than others), and therefore unexpected
1016 issues may still arise, even though basic functionality is implemented
1017 across all the underlying APIs. For Direct 3D in particular, handwritten
1018 HLSL hull and domain shaders must be injected into each QShader for the
1019 tessellation control and evaluation stages, respectively, since qsb cannot
1020 generate these from SPIR-V. Note that isoline tessellation should be
1021 avoided as it will not be supported by all backends. The maximum patch
1022 control point count portable between backends is 32.
1023
1024 \value GeometryShader Indicates that the geometry shader stage is supported.
1025 When supported, a geometry shader can be specified in the QRhiShaderStage
1026 list. Geometry Shaders are considered an experimental feature in QRhi and
1027 can only be expected to be supported with Vulkan, Direct 3D 11 and 12,
1028 OpenGL (3.2+) and OpenGL ES (3.2+), assuming the implementation reports it
1029 as supported at run time. Starting with Qt 6.11 geometry shaders are
1030 automatically translated to HLSL, and therefore no injection of handwritten
1031 HLSL geometry shaders is necessary anymore (but note that gl_in and
1032 expressions such as gl_in[0].gl_Position are not supported; rather, pass the
1033 position as an output variable from the vertex shader). Geometry shaders are
1034 not supported with Metal.
1035
1036 \value TextureArrayRange Indicates that for
1037 \l{QRhi::newTextureArray()}{texture arrays} it is possible to specify a
1038 range that is exposed to the shaders. Normally all array layers are exposed
1039 and it is up to the shader to select the layer (via the third coordinate
1040 passed to texture() when sampling the \c sampler2DArray). When supported,
1041 calling QRhiTexture::setArrayRangeStart() and
1042 QRhiTexture::setArrayRangeLength() before
1043 \l{QRhiTexture::create()}{building} or
1044 \l{QRhiTexture::createFrom()}{importing} the native texture has an effect,
1045 and leads to selecting only the specified range from the array. This will
1046 be necessary in special cases, such as when working with accelerated video
1047 decoding and Direct 3D 11, because a texture array with both
1048 \c{D3D11_BIND_DECODER} and \c{D3D11_BIND_SHADER_RESOURCE} on it is only
1049 usable as a shader resource if a single array layer is selected. Note that
1050 all this is applicable only when the texture is used as a
1051 QRhiShaderResourceBinding::SampledTexture or
1052 QRhiShaderResourceBinding::Texture shader resource, and is not compatible
1053 with image load/store. This feature is only available with some backends as
1054 it does not map well to all graphics APIs, and it is only meant to provide
1055 support for special cases anyhow. In practice the feature can be expected to
1056 be supported with Direct3D 11/12, Vulkan and Metal.
1057
1058 \value NonFillPolygonMode Indicates that setting a PolygonMode other than
1059 the default Fill is supported for QRhiGraphicsPipeline. A common use case
1060 for changing the mode to Line is to get wireframe rendering. This however
1061 is not available as a core OpenGL ES feature, and is optional with Vulkan
1062 as well as some mobile GPUs may not offer the feature.
1063
1064 \value OneDimensionalTextures Indicates that 1D textures are supported.
1065 In practice this feature will be unsupported on OpenGL ES.
1066
1067 \value OneDimensionalTextureMipmaps Indicates that generating 1D texture
1068 mipmaps is supported. In practice this feature will be unsupported on
1069 backends that do not report support for
1070 \l{OneDimensionalTextures}, Metal, and Direct 3D 12.
1071
1072 \value HalfAttributes Indicates that specifying input attributes with half
1073 precision (16bit) floating point types for a shader pipeline is supported.
1074 When not supported,
1075 \l{QRhiGraphicsPipeline::create()}{QRhiGraphicsPipeline::create()} will
1076 succeed but show a warning message and the values of the target attributes
1077 will be broken. In practice this feature will be unsupported in some OpenGL
1078 ES 2.0 and OpenGL 2.x
1079 implementations. Note that while Direct3D 11/12 does support half precision
1080 input attributes, it does not support the half3 type. The D3D backends pass
1081 half3 attributes as half4. To ensure cross platform compatibility, half3
1082 inputs should be padded to 8 bytes.
1083
1084 \value RenderToOneDimensionalTexture Indicates that 1D texture render
1085 targets are supported. In practice this feature will be unsupported on
1086 backends that do not report support for
1087 \l{OneDimensionalTextures}, and Metal.
1088
1089 \value ThreeDimensionalTextureMipmaps Indicates that generating 3D texture
1090 mipmaps is supported. This is typically supported with all backends starting
1091 with Qt 6.10.
1092
1093 \value MultiView Indicates that multiview, see e.g.
1094 \l{https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_multiview.html}{VK_KHR_multiview}
1095 is supported. With OpenGL ES 2.0, Direct 3D 11, and OpenGL (ES)
1096 implementations without \c{GL_OVR_multiview2} this feature will not be
1097 supported. With Vulkan 1.1 and newer, and Direct 3D 12 multiview is
1098 typically supported. When reported as supported, creating a
1099 QRhiTextureRenderTarget with a QRhiColorAttachment that references a texture
1100 array and has \l{QRhiColorAttachment::setMultiViewCount()}{multiViewCount}
1101 set enables recording a render pass that uses multiview rendering. In addition,
1102 any QRhiGraphicsPipeline used in that render pass must have
1103 \l{QRhiGraphicsPipeline::setMultiViewCount()}{the same view count set}. Note that
1104 multiview is only available in combination with 2D texture arrays. It cannot
1105 be used to optimize the rendering into individual textures (e.g. two, for
1106 the left and right eyes). Rather, the target of a multiview render pass is
1107 always a texture array, automatically rendering to the layer (array element)
1108 corresponding to each view. Therefore this feature implies \l TextureArrays
1109 as well. Multiview rendering is not supported in combination with
1110 tessellation or geometry shaders. See QRhiColorAttachment::setMultiViewCount()
1111 for further details on multiview rendering. This enum value has been introduced in Qt 6.7.
1112
1113 \value TextureViewFormat Indicates that setting a
1114 \l{QRhiTexture::setWriteViewFormat()}{view format} on a QRhiTexture is
1115 effective. When reported as supported, setting the read (sampling) or write
1116 (render target / image load-store) view mode changes the texture's viewing
1117 format. When unsupported, setting a view format has no effect. Note that Qt
1118 has no knowledge or control over format compatibility or resource view rules
1119 in the underlying 3D API and its implementation. Passing in unsuitable,
1120 incompatible formats may lead to errors and unspecified behavior. This is
1121 provided mainly to allow "casting" rendering into a texture created with an
1122 sRGB format to non-sRGB to avoid the unwanted linear->sRGB conversion on
1123 shader writes. Other types of casting may or may not be functional,
1124 depending on the underlying API. Currently implemented for Vulkan and Direct
1125 3D 12 and Metal. With D3D12 the feature is available only if
1126 \c CastingFullyTypedFormatSupported is supported, see
1127 \l{https://microsoft.github.io/DirectX-Specs/d3d/RelaxedCasting.html} (and
1128 note that QRhi always uses fully typed formats for textures.) This enum
1129 value has been introduced in Qt 6.8.
1130
1131 \value ResolveDepthStencil Indicates that resolving a multisample depth or
1132 depth-stencil texture is supported. Otherwise,
1133 \l{QRhiTextureRenderTargetDescription::setDepthResolveTexture()}{setting a
1134 depth resolve texture} is not functional and must be avoided. Direct 3D 11
1135 and 12 have no support for resolving depth/depth-stencil formats, and
1136 therefore this feature will never be supported with those. Vulkan 1.0 has no
1137 API to request resolving a depth-stencil attachment. Therefore, with Vulkan
1138 this feature will only be supported with Vulkan 1.2 and up, and on 1.1
1139 implementations with the appropriate extensions present. This feature is
1140 provided for the rare case when resolving into a non-multisample depth
1141 texture becomes necessary, for example when rendering into an
1142 OpenXR-provided depth texture (XR_KHR_composition_layer_depth). This enum
1143 value has been introduced in Qt 6.8.
1144
1145 \value VariableRateShading Indicates that per-draw (per-pipeline) variable
1146 rate shading is supported. When reported as supported, \l
1147 QRhiCommandBuffer::setShadingRate() is functional and has an effect for
1148 QRhiGraphicsPipeline objects that declared \l
1149 QRhiGraphicsPipeline::UsesShadingRate in their flags. Call \l
1150 QRhi::supportedShadingRates() to check which rates are supported. (1x1 is
1151 always supported, other typical values are 2x2, 1x2, 2x1, 2x4, 4x2, 4x4).
1152 This feature can be expected to be supported with Direct 3D 12 and Vulkan,
1153 assuming the implementation and GPU used at run time supports VRS. This enum
1154 value has been introduced in Qt 6.9.
1155
1156 \value VariableRateShadingMap Indicates that image-based specification of
1157 the shading rate is possible. The "image" is not necessarily a texture, it
1158 may be a native 3D API object, depending on the underlying backend and
1159 graphics API at run time. In practice this feature can be expected to be
1160 supported with Direct 3D 12, Vulkan, and Metal, assuming the GPU is modern
1161 enough to support VRS. To check if D3D12/Vulkan-style image-based VRS is
1162 supported, use VariableRateShadingMapWithTexture instead. When this feature
1163 is reported as supported, there are two possibilities: when
1164 VariableRateShadingMapWithTexture is also true, then QRhiShadingRateMap
1165 consumes QRhiTexture objects via the createFrom() overload taking a
1166 QRhiTexture argument. When VariableRateShadingMapWithTexture is false, then
1167 QRhiShadingRateMap consumes some other type of native objects, for example
1168 an MTLRasterizationRateMap in case of Metal. Use the createFrom() overload
1169 taking a NativeShadingRateMap in this case. This enum value has been
1170 introduced in Qt 6.9.
1171
1172 \value VariableRateShadingMapWithTexture Indicates that image-based
1173 specification of the shading rate is supported via regular textures. In
1174 practice this may be supported with Direct 3D 12 and Vulkan. This enum value
1175 has been introduced in Qt 6.9.
1176
1177 \value PerRenderTargetBlending Indicates that per rendertarget blending is
1178 supported i.e. different render targets in MRT framebuffer can have different
1179 blending modes. In practice this can be expected to be supported everywhere
1180 except OpenGL ES, where it is only available with GLES 3.2 implementations.
1181 This enum value has been introduced in Qt 6.9.
1182
1183 \value SampleVariables Indicates that gl_SampleID, gl_SamplePosition,
1184 gl_SampleMaskIn and gl_SampleMask variables are available in fragment shaders.
1185 In practice this can be expected to be supported everywhere except OpenGL ES,
1186 where it is only available with GLES 3.2 implementations.
1187 This enum value has been introduced in Qt 6.9.
1188
1189 \value InstanceIndexIncludesBaseInstance Indicates that \c gl_InstanceIndex
1190 includes the base instance (the \c firstInstance argument in draw calls) in
1191 its value. When this feature is unsupported, but BaseInstance is, it
1192 indicates that \c gl_InstanceIndex always starts at 0, not the base value.
1193 In practice this will be the case for Direct 3D 11 and 12 at the moment.
1194 With Vulkan and Metal this feature is expected to be reported as supported
1195 always. This enum value has been introduced in Qt 6.11.
1196
1197 \value [since 6.11] DepthClamp Indicates that enabling depth clamping is
1198 supported. When reported as unsupported, which will be the case with OpenGL
1199 ES, OpenGL versions before 3.2 without the relevant extension present, and
1200 Metal on the iOS Simulator, calling \l{QRhiGraphicsPipeline::setDepthClamp()}
1201 with an argument of \c true has no effect.
1202
1203 \value [since 6.12] DrawIndirect Indicates that the
1204 \l{QRhiCommandBuffer::drawIndirect()}{drawIndirect()}
1205 and \l{QRhiCommandBuffer::drawIndexedIndirect()}{drawIndexedIndirect()}
1206 functions are available.
1207 In practice this can be expected to be supported everywhere except on
1208 OpenGL ES < 3.1.
1209
1210 \value [since 6.12] DrawIndirectMulti Indicates that a drawCount > 1 is natively
1211 supported by the backend in \l{QRhiCommandBuffer::drawIndirect()}{drawIndirect()}
1212 and \l{QRhiCommandBuffer::drawIndexedIndirect()}{drawIndexedIndirect()}.
1213 Otherwise, multiple draw calls are issued on the CPU by the RHI.
1214 In practice this can be expected to be supported on Vulkan 1.1+, OpenGL
1215 4.3+, D3D12, and Metal.
1216
1217 \value [since 6.12] ShaderDrawParameters Indicates that the \c{gl_BaseInstance},
1218 \c{gl_BaseVertex} and \c{gl_DrawID} built-in variables are available in shaders.
1219 In practice this can be expected to be supported on Vulkan 1.1+ and with desktop OpenGL
1220 4.6 or \c{GL_ARB_shader_draw_parameters}.
1221
1222 \value [since 6.13] DispatchIndirect Indicates that the
1223 \l{QRhiCommandBuffer::dispatchIndirect()}{dispatchIndirect()} function is
1224 available, allowing compute work group counts to be sourced from a
1225 \l QRhiBuffer at execution time. In practice this can be expected to be
1226 supported wherever the \l Compute feature is reported as supported, that is,
1227 on Vulkan, OpenGL 4.3+ / OpenGL ES 3.1+, Direct3D 11/12, and Metal.
1228
1229 \value [since 6.13] DrawIndirectCount Indicates that the
1230 \l{QRhiCommandBuffer::drawIndirectCount()}{drawIndirectCount()} and
1231 \l{QRhiCommandBuffer::drawIndexedIndirectCount()}{drawIndexedIndirectCount()}
1232 functions are available. These are GPU-driven multi-draw variants where the
1233 actual draw count is read from a buffer at execution time, capped to a
1234 CPU-supplied \c maxDrawCount. In practice this can be expected to be
1235 supported with Vulkan 1.2 and newer, when both the \c drawIndirectCount and
1236 \c multiDrawIndirect device features are present, with OpenGL 4.6 or when
1237 \c GL_ARB_indirect_parameters is available, with Direct3D 12, and with Metal
1238 on devices supporting Metal 3 and indirect command buffers. Direct3D 11 does
1239 not expose an equivalent entry point. Note that with Vulkan the two device
1240 features are queried from the physical device. When importing an existing
1241 VkDevice, the application must make sure the features were enabled when that
1242 device was created, because this cannot be queried afterwards. With Metal
1243 there is a further requirement that this feature flag cannot reflect: the
1244 graphics pipeline must have
1245 \l{QRhiGraphicsPipeline::UsesIndirectDraws}{UsesIndirectDraws} set, without
1246 which the draw is skipped with a warning.
1247
1248 \value [since 6.13] BufferToBufferCopy Indicates that the
1249 \l{QRhiResourceUpdateBatch::copyBuffer()}{copyBuffer()} function is
1250 available, allowing the contents of a QRhiBuffer to be copied into another
1251 QRhiBuffer on the GPU, without a readback to the CPU. In practice this can
1252 be expected to be supported everywhere except with OpenGL ES 2.0 and
1253 desktop OpenGL versions before 3.1 without \c GL_ARB_copy_buffer, which
1254 have no \c glCopyBufferSubData. There is no fallback on such systems
1255 because OpenGL ES 2.0 provides no way of reading back the contents of a
1256 buffer either.
1257
1258 \value [since 6.13] PushConstants Indicates that
1259 \l{QRhiCommandBuffer::setPushConstants()}{setPushConstants()} is
1260 functional, meaning shaders can declare a \c{layout(push_constant)} block
1261 and the data for it can be updated between draw calls without involving a
1262 QRhiShaderResourceBindings. The maximum size of the block is reported by
1263 the \l{QRhi::MaxPushConstantsSize}{MaxPushConstantsSize} resource limit.
1264 Vulkan, Metal and Direct3D 12 have a native equivalent. OpenGL and
1265 Direct3D 11 emulate it, with plain uniforms and with a small dynamic
1266 constant buffer, respectively, so there an update costs about as much as
1267 updating a small uniform buffer; what is gained is not having to have a
1268 QRhiShaderResourceBindings per draw call. There is one case where the
1269 feature is reported as supported but does not apply: with Metal, push
1270 constants are not supported with a graphics pipeline that uses
1271 tessellation.
1272
1273 \value [since 6.13] StaticBuffersOnGpuTimeline Indicates that updates of
1274 QRhiBuffer objects with a type of QRhiBuffer::Immutable or
1275 QRhiBuffer::Static are recorded into the command stream, and so are
1276 executed on the GPU timeline, in the order they were recorded in. In
1277 particular this means that
1278 \l{QRhiResourceUpdateBatch::uploadStaticBuffer()}{uploadStaticBuffer()} and
1279 \l{QRhiResourceUpdateBatch::copyBuffer()}{copyBuffer()} targeting the same
1280 buffer within one \l QRhiResourceUpdateBatch take effect in the recorded
1281 order. When this is reported as not supported, uploads are implemented by
1282 writing to host visible memory on an unrelated timeline, and the ordering
1283 between the two kinds of updates is undefined. In practice this is only
1284 relevant with Metal: the feature is not supported there when the Metal
1285 device does not report an Apple GPU, which is the case on Intel-based Macs,
1286 and also in virtual machines where the paravirtualized device does not
1287 advertise an Apple GPU family. Note that this says nothing about when the
1288 contents become visible to the CPU or to subsequent draw calls, which is
1289 always taken care of by QRhi.
1290
1291 \value [since 6.13] DualSourceBlend Indicates that a graphics pipeline can
1292 use the Src1Color, OneMinusSrc1Color, Src1Alpha, and OneMinusSrc1Alpha blend
1293 factors from QRhiGraphicsPipeline::BlendFactor. For portable use, configure
1294 the render target with a single color attachment in slot 0. The fragment
1295 shader must provide two blend sources for that attachment, e.g. \c{location
1296 = 0}, with \c{index = 0} for the primary source and \c{index = 1} for the
1297 secondary source. In practice, this feature can be expected to be supported
1298 with desktop OpenGL 3.3 or newer, Direct3D 11/12, Vulkan, and Metal. Vulkan
1299 support is also optional and depends on the device's \c{dualSrcBlend}
1300 feature. OpenGL ES will always report this as unsupported.
1301
1302 \value [since 6.13] BaseInstanceIndirect Indicates that the \c
1303 firstInstance member of QRhiIndirectDrawCommand and
1304 QRhiIndexedIndirectDrawCommand is supported in indirect draws. When reported
1305 as not supported, the value must be 0, otherwise the behavior is undefined.
1306 This is separate from \l BaseInstance, which applies to the direct draw
1307 commands, because some 3D APIs support a non-zero first instance in direct
1308 draws but not in indirect ones. In practice this can be expected to be
1309 supported wherever both \l DrawIndirect and \l BaseInstance are reported as
1310 supported, except with Vulkan implementations that do not support the \c
1311 drawIndirectFirstInstance device feature. Note that with Vulkan the feature
1312 is queried from the physical device. When importing an existing VkDevice,
1313 the application must make sure the feature was enabled when that device was
1314 created, because this cannot be queried afterwards.
1315 */
1316
1317/*!
1318 \enum QRhi::BeginFrameFlag
1319 Flag values for QRhi::beginFrame()
1320 */
1321
1322/*!
1323 \enum QRhi::EndFrameFlag
1324 Flag values for QRhi::endFrame()
1325
1326 \value SkipPresent Specifies that no present command is to be queued or no
1327 swapBuffers call is to be made. This way no image is presented. Generating
1328 multiple frames with all having this flag set is not recommended (except,
1329 for example, for benchmarking purposes - but keep in mind that backends may
1330 behave differently when it comes to waiting for command completion without
1331 presenting so the results are not comparable between them)
1332 */
1333
1334/*!
1335 \enum QRhi::ResourceLimit
1336 Describes the resource limit to query.
1337
1338 \value TextureSizeMin Minimum texture width and height. This is typically
1339 1. The minimum texture size is handled gracefully, meaning attempting to
1340 create a texture with an empty size will instead create a texture with the
1341 minimum size.
1342
1343 \value TextureSizeMax Maximum texture width and height. This depends on the
1344 graphics API and sometimes the platform or implementation as well.
1345 Typically the value is in the range 4096 - 16384. Attempting to create
1346 textures larger than this is expected to fail.
1347
1348 \value MaxColorAttachments The maximum number of color attachments for a
1349 QRhiTextureRenderTarget, in case multiple render targets are supported. When
1350 MRT is not supported, the value is 1. Otherwise this is typically 8, but
1351 watch out for the fact that OpenGL only mandates 4 as the minimum, and that
1352 is what some OpenGL ES implementations provide.
1353
1354 \value FramesInFlight The number of frames the backend may keep "in
1355 flight": with backends like Vulkan or Metal, it is the responsibility of
1356 QRhi to block whenever starting a new frame and finding the CPU is already
1357 \c{N - 1} frames ahead of the GPU (because the command buffer submitted in
1358 frame no. \c{current} - \c{N} has not yet completed). The value N is what
1359 is returned from here, and is typically 2. This can be relevant to
1360 applications that integrate rendering done directly with the graphics API,
1361 as such rendering code may want to perform double (if the value is 2)
1362 buffering for resources, such as, buffers, similarly to the QRhi backends
1363 themselves. The current frame slot index (a value running 0, 1, .., N-1,
1364 then wrapping around) is retrievable from QRhi::currentFrameSlot(). The
1365 value is 1 for backends where the graphics API offers no such low level
1366 control over the command submission process. Note that pipelining may still
1367 happen even when this value is 1 (some backends, such as D3D11, are
1368 designed to attempt to enable this, for instance, by using an update
1369 strategy for uniform buffers that does not stall the pipeline), but that is
1370 then not controlled by QRhi and so not reflected here in the API.
1371
1372 \value MaxAsyncReadbackFrames The number of \l{QRhi::endFrame()}{submitted}
1373 frames (including the one that contains the readback) after which an
1374 asynchronous texture or buffer readback is guaranteed to complete upon
1375 \l{QRhi::beginFrame()}{starting a new frame}.
1376
1377 \value MaxThreadGroupsPerDimension The maximum number of compute
1378 work/thread groups that can be dispatched. Effectively the maximum value
1379 for the arguments of QRhiCommandBuffer::dispatch(). Typically 65535.
1380
1381 \value MaxThreadsPerThreadGroup The maximum number of invocations in a
1382 single local work group, or in other terminology, the maximum number of
1383 threads in a thread group. Effectively the maximum value for the product of
1384 \c local_size_x, \c local_size_y, and \c local_size_z in the compute
1385 shader. Typical values are 128, 256, 512, 1024, or 1536. Watch out that
1386 both OpenGL ES and Vulkan specify only 128 as the minimum required limit
1387 for implementations. While uncommon for Vulkan, some OpenGL ES 3.1
1388 implementations for mobile/embedded devices only support the spec-mandated
1389 minimum value.
1390
1391 \value MaxThreadGroupX The maximum size of a work/thread group in the X
1392 dimension. Effectively the maximum value of \c local_size_x in the compute
1393 shader. Typically 256 or 1024.
1394
1395 \value MaxThreadGroupY The maximum size of a work/thread group in the Y
1396 dimension. Effectively the maximum value of \c local_size_y in the compute
1397 shader. Typically 256 or 1024.
1398
1399 \value MaxThreadGroupZ The maximum size of a work/thread group in the Z
1400 dimension. Effectively the maximum value of \c local_size_z in the compute
1401 shader. Typically 64 or 256.
1402
1403 \value TextureArraySizeMax Maximum texture array size. Typically in range
1404 256 - 2048. Attempting to \l{QRhi::newTextureArray()}{create a texture
1405 array} with more elements will likely fail.
1406
1407 \value MaxUniformBufferRange The number of bytes that can be exposed from a
1408 uniform buffer to the shaders at once. On OpenGL ES 2.0 and 3.0
1409 implementations this may be as low as 3584 bytes (224 four component, 32
1410 bits per component vectors). Elsewhere the value is typically 16384 (1024
1411 vec4s) or 65536 (4096 vec4s).
1412
1413 \value MaxVertexInputs The number of input attributes to the vertex shader.
1414 The location in a QRhiVertexInputAttribute must be in range \c{[0,
1415 MaxVertexInputs-1]}. The value may be as low as 8 with OpenGL ES 2.0.
1416 Elsewhere, typical values are 16, 31, or 32.
1417
1418 \value MaxVertexOutputs The maximum number of outputs (4 component vector
1419 \c out variables) from the vertex shader. The value may be as low as 8 with
1420 OpenGL ES 2.0, and 15 with OpenGL ES 3.0 and some Metal devices. Elsewhere,
1421 a typical value is 32.
1422
1423 \value ShadingRateImageTileSize The tile size for shading rate textures. 0
1424 if the QRhi::VariableRateShadingMapWithTexture feature is not supported.
1425 Otherwise a value such as 16, indicating, for example, a tile size of 16x16.
1426 Each byte in the (R8UI) shading rate texture defines then the shading rate
1427 for a tile of 16x16 pixels. See \l QRhiShadingRateMap for details.
1428
1429 \value [since 6.13] MaxVertexStorageBuffers The maximum number of
1430 storage buffers that can be bound for reading (bufferLoad) in the
1431 vertex stage. Can legitimately be 0: OpenGL ES makes vertex-stage
1432 storage blocks optional even on 3.1 and newer, and many mobile
1433 drivers report 0 while supporting them via Vulkan on the same GPU;
1434 Direct 3D 11 has no vertex-stage storage buffer support at all.
1435 Clients reading storage buffers in the vertex shader must therefore
1436 check this even when QRhi::Compute is supported. Write access can be
1437 more restricted than this value suggests: with Vulkan it additionally
1438 requires the vertexPipelineStoresAndAtomics device feature, and with
1439 Direct 3D 12 unordered access has lower, resource-binding-tier
1440 dependent limits. With Metal the value is the size of the buffer
1441 argument table, which is shared with vertex inputs and uniform
1442 buffers, so the full count is not available in combination with them.
1443
1444 \value [since 6.13] MaxFragmentStorageBuffers The maximum number of
1445 storage buffers that can be bound for reading (bufferLoad) in the
1446 fragment stage. Like the vertex stage, this is optional in OpenGL ES
1447 (only compute-stage storage blocks are mandatory), so 0 is a
1448 legitimate value. The write access and Metal argument table notes
1449 from MaxVertexStorageBuffers apply here as well; with Direct 3D 11
1450 the value reflects the unordered access view slots, which are shared
1451 with render target outputs. Writing storage buffers in fragment shaders
1452 additionally requires the FragmentStoresAndAtomics feature.
1453
1454 \value [since 6.13] MaxPushConstantsSize The maximum size in bytes of the
1455 push constant block a shader can declare. 0 when the
1456 \l{QRhi::PushConstants}{PushConstants} feature is not supported.
1457 Portable code should stay within 128 bytes: that is what Direct3D 11 and
1458 12 and OpenGL report and what Vulkan guarantees, whereas Metal reports
1459 4096. Note that with Direct3D 12 even 128 is optimistic, because a block
1460 that size takes 32 of the 64 root signature DWORDs, so with a
1461 sufficiently large QRhiShaderResourceBindings the root signature can
1462 still fail to build. With OpenGL the block competes for the uniform
1463 budget with everything else in the shader.
1464
1465 \value [since 6.13] MaxStorageBufferBindings The number of binding
1466 points for storage buffers. The binding number of a
1467 \l{QRhiShaderResourceBinding::bufferLoad()}{bufferLoad},
1468 \l{QRhiShaderResourceBinding::bufferStore()}{bufferStore}, or
1469 \l{QRhiShaderResourceBinding::bufferLoadStore()}{bufferLoadStore}
1470 binding, and so the \c binding in the shader, must be in range
1471 \c{[0, MaxStorageBufferBindings-1]}. This limits the binding number,
1472 not how many storage buffers a stage can use; for that see
1473 MaxVertexStorageBuffers and MaxFragmentStorageBuffers. Only OpenGL and
1474 OpenGL ES have such a limit, because there the binding number is used
1475 as is for the buffer binding point, of which there can be as few as 4
1476 (OpenGL ES 3.1) or 8 (OpenGL 4.3). Other backends map binding numbers
1477 to native slots or do not limit them, and report \c INT_MAX. With
1478 OpenGL the value is 0 when QRhi::Compute is not supported.
1479
1480 \value [since 6.13] MaxStorageImageBindings The number of binding
1481 points for storage images. The binding number of an
1482 \l{QRhiShaderResourceBinding::imageLoad()}{imageLoad},
1483 \l{QRhiShaderResourceBinding::imageStore()}{imageStore}, or
1484 \l{QRhiShaderResourceBinding::imageLoadStore()}{imageLoadStore}
1485 binding, and so the \c binding in the shader, must be in range
1486 \c{[0, MaxStorageImageBindings-1]}. Only OpenGL and OpenGL ES have such
1487 a limit, because there the binding number is used as is for the image
1488 unit, of which there can be as few as 4 (OpenGL ES 3.1) or 8 (OpenGL
1489 4.3). Other backends map binding numbers to native slots or do not
1490 limit them, and report \c INT_MAX. With OpenGL the value is 0 when
1491 QRhi::Compute is not supported.
1492 */
1493
1494/*!
1495 \class QRhiInitParams
1496 \inmodule QtGuiPrivate
1497 \inheaderfile rhi/qrhi.h
1498 \since 6.6
1499 \brief Base class for backend-specific initialization parameters.
1500
1501 Contains fields that are relevant to all backends.
1502
1503 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
1504 for details.
1505 */
1506
1507/*!
1508 \class QRhiDepthStencilClearValue
1509 \inmodule QtGuiPrivate
1510 \inheaderfile rhi/qrhi.h
1511 \since 6.6
1512 \brief Specifies clear values for a depth or stencil buffer.
1513
1514 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
1515 for details.
1516 */
1517
1518/*!
1519 \fn QRhiDepthStencilClearValue::QRhiDepthStencilClearValue() = default
1520
1521 Constructs a depth/stencil clear value with depth clear value 1.0f and
1522 stencil clear value 0.
1523 */
1524
1525/*!
1526 Constructs a depth/stencil clear value with depth clear value \a d and
1527 stencil clear value \a s.
1528 */
1529QRhiDepthStencilClearValue::QRhiDepthStencilClearValue(float d, quint32 s)
1530 : m_d(d),
1531 m_s(s)
1532{
1533}
1534
1535/*!
1536 \fn float QRhiDepthStencilClearValue::depthClearValue() const
1537 \return the depth clear value. In most cases this is 1.0f.
1538 */
1539
1540/*!
1541 \fn void QRhiDepthStencilClearValue::setDepthClearValue(float d)
1542 Sets the depth clear value to \a d.
1543 */
1544
1545/*!
1546 \fn quint32 QRhiDepthStencilClearValue::stencilClearValue() const
1547 \return the stencil clear value. In most cases this is 0.
1548 */
1549
1550/*!
1551 \fn void QRhiDepthStencilClearValue::setStencilClearValue(quint32 s)
1552 Sets the stencil clear value to \a s.
1553 */
1554
1555/*!
1556 \fn bool QRhiDepthStencilClearValue::operator==(const QRhiDepthStencilClearValue &a, const QRhiDepthStencilClearValue &b) noexcept
1557
1558 \return \c true if the values in the two QRhiDepthStencilClearValue objects
1559 \a a and \a b are equal.
1560 */
1561
1562/*!
1563 \fn bool QRhiDepthStencilClearValue::operator!=(const QRhiDepthStencilClearValue &a, const QRhiDepthStencilClearValue &b) noexcept
1564
1565 \return \c false if the values in the two QRhiDepthStencilClearValue
1566 objects \a a and \a b are equal; otherwise returns \c true.
1567
1568*/
1569
1570/*!
1571 \fn size_t QRhiDepthStencilClearValue::qHash(const QRhiDepthStencilClearValue &key, size_t seed)
1572 \qhash{QRhiDepthStencilClearValue}
1573 */
1574
1575#ifndef QT_NO_DEBUG_STREAM
1576QDebug operator<<(QDebug dbg, const QRhiDepthStencilClearValue &v)
1577{
1578 QDebugStateSaver saver(dbg);
1579 dbg.nospace() << "QRhiDepthStencilClearValue(depth-clear=" << v.depthClearValue()
1580 << " stencil-clear=" << v.stencilClearValue()
1581 << ')';
1582 return dbg;
1583}
1584#endif
1585
1586/*!
1587 \class QRhiViewport
1588 \inmodule QtGuiPrivate
1589 \inheaderfile rhi/qrhi.h
1590 \since 6.6
1591 \brief Specifies a viewport rectangle.
1592
1593 Used with QRhiCommandBuffer::setViewport().
1594
1595 QRhi assumes OpenGL-style viewport coordinates, meaning x and y are
1596 bottom-left. Negative width or height are not allowed.
1597
1598 Typical usage is like the following:
1599
1600 \code
1601 const QSize outputSizeInPixels = swapchain->currentPixelSize();
1602 const QRhiViewport viewport(0, 0, outputSizeInPixels.width(), outputSizeInPixels.height());
1603 cb->beginPass(swapchain->currentFrameRenderTarget(), Qt::black, { 1.0f, 0 });
1604 cb->setGraphicsPipeline(ps);
1605 cb->setViewport(viewport);
1606 // ...
1607 \endcode
1608
1609 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
1610 for details.
1611
1612 \sa QRhiCommandBuffer::setViewport(), QRhi::clipSpaceCorrMatrix(), QRhiScissor
1613 */
1614
1615/*!
1616 \fn QRhiViewport::QRhiViewport() = default
1617
1618 Constructs a viewport description with an empty rectangle and a depth range
1619 of 0.0f - 1.0f.
1620
1621 \sa QRhi::clipSpaceCorrMatrix()
1622 */
1623
1624/*!
1625 Constructs a viewport description with the rectangle specified by \a x, \a
1626 y, \a w, \a h and the depth range \a minDepth and \a maxDepth.
1627
1628 \note \a x and \a y are assumed to be the bottom-left position. \a w and \a
1629 h should not be negative, the viewport will be ignored by
1630 QRhiCommandBuffer::setViewport() otherwise.
1631
1632 \sa QRhi::clipSpaceCorrMatrix()
1633 */
1634QRhiViewport::QRhiViewport(float x, float y, float w, float h, float minDepth, float maxDepth)
1635 : m_rect { { x, y, w, h } },
1636 m_minDepth(minDepth),
1637 m_maxDepth(maxDepth)
1638{
1639}
1640
1641/*!
1642 \fn std::array<float, 4> QRhiViewport::viewport() const
1643 \return the viewport x, y, width, and height.
1644 */
1645
1646/*!
1647 \fn void QRhiViewport::setViewport(float x, float y, float w, float h)
1648 Sets the viewport's position and size to \a x, \a y, \a w, and \a h.
1649
1650 \note Viewports are specified in a coordinate system that has its origin in
1651 the bottom-left.
1652 */
1653
1654/*!
1655 \fn float QRhiViewport::minDepth() const
1656 \return the minDepth value of the depth range of the viewport.
1657 */
1658
1659/*!
1660 \fn void QRhiViewport::setMinDepth(float minDepth)
1661 Sets the \a minDepth of the depth range of the viewport.
1662 By default this is set to 0.0f.
1663 */
1664
1665/*!
1666 \fn float QRhiViewport::maxDepth() const
1667 \return the maxDepth value of the depth range of the viewport.
1668 */
1669
1670/*!
1671 \fn void QRhiViewport::setMaxDepth(float maxDepth)
1672 Sets the \a maxDepth of the depth range of the viewport.
1673 By default this is set to 1.0f.
1674 */
1675
1676/*!
1677 \fn bool QRhiViewport::operator==(const QRhiViewport &a, const QRhiViewport &b) noexcept
1678
1679 \return \c true if the values in the two QRhiViewport objects
1680 \a a and \a b are equal.
1681 */
1682
1683/*!
1684 \fn bool QRhiViewport::operator!=(const QRhiViewport &a, const QRhiViewport &b) noexcept
1685
1686 \return \c false if the values in the two QRhiViewport
1687 objects \a a and \a b are equal; otherwise returns \c true.
1688*/
1689
1690/*!
1691 \fn size_t QRhiViewport::qHash(const QRhiViewport &key, size_t seed)
1692 \qhash{QRhiViewport}
1693 */
1694
1695#ifndef QT_NO_DEBUG_STREAM
1696QDebug operator<<(QDebug dbg, const QRhiViewport &v)
1697{
1698 QDebugStateSaver saver(dbg);
1699 const std::array<float, 4> r = v.viewport();
1700 dbg.nospace() << "QRhiViewport(bottom-left-x=" << r[0]
1701 << " bottom-left-y=" << r[1]
1702 << " width=" << r[2]
1703 << " height=" << r[3]
1704 << " minDepth=" << v.minDepth()
1705 << " maxDepth=" << v.maxDepth()
1706 << ')';
1707 return dbg;
1708}
1709#endif
1710
1711/*!
1712 \class QRhiScissor
1713 \inmodule QtGuiPrivate
1714 \inheaderfile rhi/qrhi.h
1715 \since 6.6
1716 \brief Specifies a scissor rectangle.
1717
1718 Used with QRhiCommandBuffer::setScissor(). Setting a scissor rectangle is
1719 only possible with a QRhiGraphicsPipeline that has
1720 QRhiGraphicsPipeline::UsesScissor set.
1721
1722 QRhi assumes OpenGL-style scissor coordinates, meaning x and y are
1723 bottom-left. Negative width or height are not allowed. However, apart from
1724 that, the flexible OpenGL semantics apply: negative x and y, partially out
1725 of bounds rectangles, etc. will be handled gracefully, clamping as
1726 appropriate. Therefore, any rendering logic targeting OpenGL can feed
1727 scissor rectangles into QRhiScissor as-is, without any adaptation.
1728
1729 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
1730 for details.
1731
1732 \sa QRhiCommandBuffer::setScissor(), QRhiViewport
1733 */
1734
1735/*!
1736 \fn QRhiScissor::QRhiScissor() = default
1737
1738 Constructs an empty scissor.
1739 */
1740
1741/*!
1742 Constructs a scissor with the rectangle specified by \a x, \a y, \a w, and
1743 \a h.
1744
1745 \note \a x and \a y are assumed to be the bottom-left position. Negative \a w
1746 or \a h are not allowed, such scissor rectangles will be ignored by
1747 QRhiCommandBuffer. Other than that, the flexible OpenGL semantics apply:
1748 negative x and y, partially out of bounds rectangles, etc. will be handled
1749 gracefully, clamping as appropriate.
1750 */
1751QRhiScissor::QRhiScissor(int x, int y, int w, int h)
1752 : m_rect { { x, y, w, h } }
1753{
1754}
1755
1756/*!
1757 \fn std::array<int, 4> QRhiScissor::scissor() const
1758 \return the scissor position and size.
1759 */
1760
1761/*!
1762 \fn void QRhiScissor::setScissor(int x, int y, int w, int h)
1763 Sets the scissor position and size to \a x, \a y, \a w, \a h.
1764
1765 \note The position is always expected to be specified in a coordinate
1766 system that has its origin in the bottom-left corner, like OpenGL.
1767 */
1768
1769/*!
1770 \fn bool QRhiScissor::operator==(const QRhiScissor &a, const QRhiScissor &b) noexcept
1771
1772 \return \c true if the values in the two QRhiScissor objects
1773 \a a and \a b are equal.
1774 */
1775
1776/*!
1777 \fn bool QRhiScissor::operator!=(const QRhiScissor &a, const QRhiScissor &b) noexcept
1778
1779 \return \c false if the values in the two QRhiScissor
1780 objects \a a and \a b are equal; otherwise returns \c true.
1781*/
1782
1783/*!
1784 \fn size_t QRhiScissor::qHash(const QRhiScissor &key, size_t seed)
1785 \qhash{QRhiScissor}
1786 */
1787
1788#ifndef QT_NO_DEBUG_STREAM
1789QDebug operator<<(QDebug dbg, const QRhiScissor &s)
1790{
1791 QDebugStateSaver saver(dbg);
1792 const std::array<int, 4> r = s.scissor();
1793 dbg.nospace() << "QRhiScissor(bottom-left-x=" << r[0]
1794 << " bottom-left-y=" << r[1]
1795 << " width=" << r[2]
1796 << " height=" << r[3]
1797 << ')';
1798 return dbg;
1799}
1800#endif
1801
1802/*!
1803 \class QRhiVertexInputBinding
1804 \inmodule QtGuiPrivate
1805 \inheaderfile rhi/qrhi.h
1806 \since 6.6
1807 \brief Describes a vertex input binding.
1808
1809 Specifies the stride (in bytes, must be a multiple of 4), the
1810 classification and optionally the instance step rate.
1811
1812 As an example, assume a vertex shader with the following inputs:
1813
1814 \badcode
1815 layout(location = 0) in vec4 position;
1816 layout(location = 1) in vec2 texcoord;
1817 \endcode
1818
1819 Now let's assume also that 3 component vertex positions \c{(x, y, z)} and 2
1820 component texture coordinates \c{(u, v)} are provided in a non-interleaved
1821 format in a buffer (or separate buffers even). Defining two bindings
1822 could then be done like this:
1823
1824 \code
1825 QRhiVertexInputLayout inputLayout;
1826 inputLayout.setBindings({
1827 { 3 * sizeof(float) },
1828 { 2 * sizeof(float) }
1829 });
1830 \endcode
1831
1832 Only the stride is interesting here since instancing is not used. The
1833 binding number is given by the index of the QRhiVertexInputBinding
1834 element in the bindings vector of the QRhiVertexInputLayout.
1835
1836 Once a graphics pipeline with this vertex input layout is bound, the vertex
1837 inputs could be set up like the following for drawing a cube with 36
1838 vertices, assuming we have a single buffer with first the positions and
1839 then the texture coordinates:
1840
1841 \code
1842 const QRhiCommandBuffer::VertexInput vbufBindings[] = {
1843 { cubeBuf, 0 },
1844 { cubeBuf, 36 * 3 * sizeof(float) }
1845 };
1846 cb->setVertexInput(0, 2, vbufBindings);
1847 \endcode
1848
1849 Note how the index defined by \c {startBinding + i}, where \c i is the
1850 index in the second argument of
1851 \l{QRhiCommandBuffer::setVertexInput()}{setVertexInput()}, matches the
1852 index of the corresponding entry in the \c bindings vector of the
1853 QRhiVertexInputLayout.
1854
1855 \note the stride must always be a multiple of 4.
1856
1857 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
1858 for details.
1859
1860 \sa QRhiCommandBuffer::setVertexInput()
1861 */
1862
1863/*!
1864 \enum QRhiVertexInputBinding::Classification
1865 Describes the input data classification.
1866
1867 \value PerVertex Data is per-vertex
1868 \value PerInstance Data is per-instance
1869 */
1870
1871/*!
1872 \fn QRhiVertexInputBinding::QRhiVertexInputBinding() = default
1873
1874 Constructs a default vertex input binding description.
1875 */
1876
1877/*!
1878 Constructs a vertex input binding description with the specified \a stride,
1879 classification \a cls, and instance step rate \a stepRate.
1880
1881 \note \a stepRate other than 1 is only supported when
1882 QRhi::CustomInstanceStepRate is reported to be supported.
1883 */
1884QRhiVertexInputBinding::QRhiVertexInputBinding(quint32 stride, Classification cls, quint32 stepRate)
1885 : m_stride(stride),
1886 m_classification(cls),
1887 m_instanceStepRate(stepRate)
1888{
1889}
1890
1891/*!
1892 \fn quint32 QRhiVertexInputBinding::stride() const
1893 \return the stride in bytes.
1894 */
1895
1896/*!
1897 \fn void QRhiVertexInputBinding::setStride(quint32 s)
1898 Sets the stride to \a s.
1899 */
1900
1901/*!
1902 \fn QRhiVertexInputBinding::Classification QRhiVertexInputBinding::classification() const
1903 \return the input data classification.
1904 */
1905
1906/*!
1907 \fn void QRhiVertexInputBinding::setClassification(Classification c)
1908 Sets the input data classification \a c. By default this is set to PerVertex.
1909 */
1910
1911/*!
1912 \fn quint32 QRhiVertexInputBinding::instanceStepRate() const
1913 \return the instance step rate.
1914 */
1915
1916/*!
1917 \fn void QRhiVertexInputBinding::setInstanceStepRate(quint32 rate)
1918 Sets the instance step \a rate. By default this is set to 1.
1919 */
1920
1921/*!
1922 \fn bool QRhiVertexInputBinding::operator==(const QRhiVertexInputBinding &a, const QRhiVertexInputBinding &b) noexcept
1923
1924 \return \c true if the values in the two QRhiVertexInputBinding objects
1925 \a a and \a b are equal.
1926 */
1927
1928/*!
1929 \fn bool QRhiVertexInputBinding::operator!=(const QRhiVertexInputBinding &a, const QRhiVertexInputBinding &b) noexcept
1930
1931 \return \c false if the values in the two QRhiVertexInputBinding
1932 objects \a a and \a b are equal; otherwise returns \c true.
1933*/
1934
1935/*!
1936 \fn size_t QRhiVertexInputBinding::qHash(const QRhiVertexInputBinding &key, size_t seed)
1937 \qhash{QRhiVertexInputBinding}
1938 */
1939
1940#ifndef QT_NO_DEBUG_STREAM
1941QDebug operator<<(QDebug dbg, const QRhiVertexInputBinding &b)
1942{
1943 QDebugStateSaver saver(dbg);
1944 dbg.nospace() << "QRhiVertexInputBinding(stride=" << b.stride()
1945 << " cls=" << b.classification()
1946 << " step-rate=" << b.instanceStepRate()
1947 << ')';
1948 return dbg;
1949}
1950#endif
1951
1952/*!
1953 \class QRhiVertexInputAttribute
1954 \inmodule QtGuiPrivate
1955 \inheaderfile rhi/qrhi.h
1956 \since 6.6
1957 \brief Describes a single vertex input element.
1958
1959 The members specify the binding number, location, format, and offset for a
1960 single vertex input element.
1961
1962 \note For HLSL it is assumed that the vertex shader translated from SPIR-V
1963 uses
1964 \c{TEXCOORD<location>} as the semantic for each input. Hence no separate
1965 semantic name and index.
1966
1967 As an example, assume a vertex shader with the following inputs:
1968
1969 \badcode
1970 layout(location = 0) in vec4 position;
1971 layout(location = 1) in vec2 texcoord;
1972 \endcode
1973
1974 Now let's assume that we have 3 component vertex positions \c{(x, y, z)}
1975 and 2 component texture coordinates \c{(u, v)} are provided in a
1976 non-interleaved format in a buffer (or separate buffers even). Once two
1977 bindings are defined, the attributes could be specified as:
1978
1979 \code
1980 QRhiVertexInputLayout inputLayout;
1981 inputLayout.setBindings({
1982 { 3 * sizeof(float) },
1983 { 2 * sizeof(float) }
1984 });
1985 inputLayout.setAttributes({
1986 { 0, 0, QRhiVertexInputAttribute::Float3, 0 },
1987 { 1, 1, QRhiVertexInputAttribute::Float2, 0 }
1988 });
1989 \endcode
1990
1991 Once a graphics pipeline with this vertex input layout is bound, the vertex
1992 inputs could be set up like the following for drawing a cube with 36
1993 vertices, assuming we have a single buffer with first the positions and
1994 then the texture coordinates:
1995
1996 \code
1997 const QRhiCommandBuffer::VertexInput vbufBindings[] = {
1998 { cubeBuf, 0 },
1999 { cubeBuf, 36 * 3 * sizeof(float) }
2000 };
2001 cb->setVertexInput(0, 2, vbufBindings);
2002 \endcode
2003
2004 When working with interleaved data, there will typically be just one
2005 binding, with multiple attributes referring to that same buffer binding
2006 point:
2007
2008 \code
2009 QRhiVertexInputLayout inputLayout;
2010 inputLayout.setBindings({
2011 { 5 * sizeof(float) }
2012 });
2013 inputLayout.setAttributes({
2014 { 0, 0, QRhiVertexInputAttribute::Float3, 0 },
2015 { 0, 1, QRhiVertexInputAttribute::Float2, 3 * sizeof(float) }
2016 });
2017 \endcode
2018
2019 and then:
2020
2021 \code
2022 const QRhiCommandBuffer::VertexInput vbufBinding(interleavedCubeBuf, 0);
2023 cb->setVertexInput(0, 1, &vbufBinding);
2024 \endcode
2025
2026 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
2027 for details.
2028
2029 \sa QRhiCommandBuffer::setVertexInput()
2030 */
2031
2032/*!
2033 \enum QRhiVertexInputAttribute::Format
2034 Specifies the type of the element data.
2035
2036 \value Float4 Four component float vector
2037 \value Float3 Three component float vector
2038 \value Float2 Two component float vector
2039 \value Float Float
2040 \value UNormByte4 Four component normalized unsigned byte vector
2041 \value UNormByte2 Two component normalized unsigned byte vector
2042 \value UNormByte Normalized unsigned byte
2043 \value UInt4 Four component unsigned integer vector
2044 \value UInt3 Three component unsigned integer vector
2045 \value UInt2 Two component unsigned integer vector
2046 \value UInt Unsigned integer
2047 \value SInt4 Four component signed integer vector
2048 \value SInt3 Three component signed integer vector
2049 \value SInt2 Two component signed integer vector
2050 \value SInt Signed integer
2051 \value Half4 Four component half precision (16 bit) float vector
2052 \value Half3 Three component half precision (16 bit) float vector
2053 \value Half2 Two component half precision (16 bit) float vector
2054 \value Half Half precision (16 bit) float
2055 \value UShort4 Four component unsigned short (16 bit) integer vector
2056 \value UShort3 Three component unsigned short (16 bit) integer vector
2057 \value UShort2 Two component unsigned short (16 bit) integer vector
2058 \value UShort Unsigned short (16 bit) integer
2059 \value SShort4 Four component signed short (16 bit) integer vector
2060 \value SShort3 Three component signed short (16 bit) integer vector
2061 \value SShort2 Two component signed short (16 bit) integer vector
2062 \value SShort Signed short (16 bit) integer
2063
2064 \note Support for half precision floating point attributes is indicated at
2065 run time by the QRhi::Feature::HalfAttributes feature flag.
2066
2067 \note Direct3D 11/12 supports 16 bit input attributes, but does not support
2068 the Half3, UShort3 or SShort3 types. The D3D backends pass through Half3 as
2069 Half4, UShort3 as UShort4, and SShort3 as SShort4. To ensure cross platform
2070 compatibility, 16 bit inputs should be padded to 8 bytes.
2071 */
2072
2073/*!
2074 \fn QRhiVertexInputAttribute::QRhiVertexInputAttribute() = default
2075
2076 Constructs a default vertex input attribute description.
2077 */
2078
2079/*!
2080 Constructs a vertex input attribute description with the specified \a
2081 binding number, \a location, \a format, and \a offset.
2082
2083 \a matrixSlice should be -1 except when this attribute corresponds to a row
2084 or column of a matrix (for example, a 4x4 matrix becomes 4 vec4s, consuming
2085 4 consecutive vertex input locations), in which case it is the index of the
2086 row or column. \c{location - matrixSlice} must always be equal to the \c
2087 location for the first row or column of the unrolled matrix.
2088 */
2089QRhiVertexInputAttribute::QRhiVertexInputAttribute(int binding, int location, Format format, quint32 offset, int matrixSlice)
2090 : m_binding(binding),
2091 m_location(location),
2092 m_format(format),
2093 m_offset(offset),
2094 m_matrixSlice(matrixSlice)
2095{
2096}
2097
2098/*!
2099 \fn int QRhiVertexInputAttribute::binding() const
2100 \return the binding point index.
2101 */
2102
2103/*!
2104 \fn void QRhiVertexInputAttribute::setBinding(int b)
2105 Sets the binding point index to \a b.
2106 By default this is set to 0.
2107 */
2108
2109/*!
2110 \fn int QRhiVertexInputAttribute::location() const
2111 \return the location of the vertex input element.
2112 */
2113
2114/*!
2115 \fn void QRhiVertexInputAttribute::setLocation(int loc)
2116 Sets the location of the vertex input element to \a loc.
2117 By default this is set to 0.
2118 */
2119
2120/*!
2121 \fn QRhiVertexInputAttribute::Format QRhiVertexInputAttribute::format() const
2122 \return the format of the vertex input element.
2123 */
2124
2125/*!
2126 \fn void QRhiVertexInputAttribute::setFormat(Format f)
2127 Sets the format of the vertex input element to \a f.
2128 By default this is set to Float4.
2129 */
2130
2131/*!
2132 \fn quint32 QRhiVertexInputAttribute::offset() const
2133 \return the byte offset for the input element.
2134 */
2135
2136/*!
2137 \fn void QRhiVertexInputAttribute::setOffset(quint32 ofs)
2138 Sets the byte offset for the input element to \a ofs.
2139 */
2140
2141/*!
2142 \fn int QRhiVertexInputAttribute::matrixSlice() const
2143
2144 \return the matrix slice if the input element corresponds to a row or
2145 column of a matrix, or -1 if not relevant.
2146 */
2147
2148/*!
2149 \fn void QRhiVertexInputAttribute::setMatrixSlice(int slice)
2150
2151 Sets the matrix \a slice. By default this is set to -1, and should be set
2152 to a >= 0 value only when this attribute corresponds to a row or column of
2153 a matrix (for example, a 4x4 matrix becomes 4 vec4s, consuming 4
2154 consecutive vertex input locations), in which case it is the index of the
2155 row or column. \c{location - matrixSlice} must always be equal to the \c
2156 location for the first row or column of the unrolled matrix.
2157 */
2158
2159/*!
2160 \fn bool QRhiVertexInputAttribute::operator==(const QRhiVertexInputAttribute &a, const QRhiVertexInputAttribute &b) noexcept
2161
2162 \return \c true if the values in the two QRhiVertexInputAttribute objects
2163 \a a and \a b are equal.
2164 */
2165
2166/*!
2167 \fn bool QRhiVertexInputAttribute::operator!=(const QRhiVertexInputAttribute &a, const QRhiVertexInputAttribute &b) noexcept
2168
2169 \return \c false if the values in the two QRhiVertexInputAttribute
2170 objects \a a and \a b are equal; otherwise returns \c true.
2171*/
2172
2173/*!
2174 \fn size_t QRhiVertexInputAttribute::qHash(const QRhiVertexInputAttribute &key, size_t seed)
2175 \qhash{QRhiVertexInputAttribute}
2176 */
2177
2178#ifndef QT_NO_DEBUG_STREAM
2179QDebug operator<<(QDebug dbg, const QRhiVertexInputAttribute &a)
2180{
2181 QDebugStateSaver saver(dbg);
2182 dbg.nospace() << "QRhiVertexInputAttribute(binding=" << a.binding()
2183 << " location=" << a.location()
2184 << " format=" << a.format()
2185 << " offset=" << a.offset()
2186 << ')';
2187 return dbg;
2188}
2189#endif
2190
2191QRhiVertexInputAttribute::Format QRhiImplementation::shaderDescVariableFormatToVertexInputFormat(QShaderDescription::VariableType type) const
2192{
2193 switch (type) {
2194 case QShaderDescription::Vec4:
2195 return QRhiVertexInputAttribute::Float4;
2196 case QShaderDescription::Vec3:
2197 return QRhiVertexInputAttribute::Float3;
2198 case QShaderDescription::Vec2:
2199 return QRhiVertexInputAttribute::Float2;
2200 case QShaderDescription::Float:
2201 return QRhiVertexInputAttribute::Float;
2202
2203 case QShaderDescription::Int4:
2204 return QRhiVertexInputAttribute::SInt4;
2205 case QShaderDescription::Int3:
2206 return QRhiVertexInputAttribute::SInt3;
2207 case QShaderDescription::Int2:
2208 return QRhiVertexInputAttribute::SInt2;
2209 case QShaderDescription::Int:
2210 return QRhiVertexInputAttribute::SInt;
2211
2212 case QShaderDescription::Uint4:
2213 return QRhiVertexInputAttribute::UInt4;
2214 case QShaderDescription::Uint3:
2215 return QRhiVertexInputAttribute::UInt3;
2216 case QShaderDescription::Uint2:
2217 return QRhiVertexInputAttribute::UInt2;
2218 case QShaderDescription::Uint:
2219 return QRhiVertexInputAttribute::UInt;
2220
2221 case QShaderDescription::Half4:
2222 return QRhiVertexInputAttribute::Half4;
2223 case QShaderDescription::Half3:
2224 return QRhiVertexInputAttribute::Half3;
2225 case QShaderDescription::Half2:
2226 return QRhiVertexInputAttribute::Half2;
2227 case QShaderDescription::Half:
2228 return QRhiVertexInputAttribute::Half;
2229
2230 default:
2231 Q_UNREACHABLE_RETURN(QRhiVertexInputAttribute::Float);
2232 }
2233}
2234
2235quint32 QRhiImplementation::byteSizePerVertexForVertexInputFormat(QRhiVertexInputAttribute::Format format) const
2236{
2237 switch (format) {
2238 case QRhiVertexInputAttribute::Float4:
2239 return 4 * sizeof(float);
2240 case QRhiVertexInputAttribute::Float3:
2241 return 4 * sizeof(float); // vec3 still takes 16 bytes
2242 case QRhiVertexInputAttribute::Float2:
2243 return 2 * sizeof(float);
2244 case QRhiVertexInputAttribute::Float:
2245 return sizeof(float);
2246
2247 case QRhiVertexInputAttribute::UNormByte4:
2248 return 4 * sizeof(quint8);
2249 case QRhiVertexInputAttribute::UNormByte2:
2250 return 2 * sizeof(quint8);
2251 case QRhiVertexInputAttribute::UNormByte:
2252 return sizeof(quint8);
2253
2254 case QRhiVertexInputAttribute::UInt4:
2255 return 4 * sizeof(quint32);
2256 case QRhiVertexInputAttribute::UInt3:
2257 return 4 * sizeof(quint32); // ivec3 still takes 16 bytes
2258 case QRhiVertexInputAttribute::UInt2:
2259 return 2 * sizeof(quint32);
2260 case QRhiVertexInputAttribute::UInt:
2261 return sizeof(quint32);
2262
2263 case QRhiVertexInputAttribute::SInt4:
2264 return 4 * sizeof(qint32);
2265 case QRhiVertexInputAttribute::SInt3:
2266 return 4 * sizeof(qint32); // uvec3 still takes 16 bytes
2267 case QRhiVertexInputAttribute::SInt2:
2268 return 2 * sizeof(qint32);
2269 case QRhiVertexInputAttribute::SInt:
2270 return sizeof(qint32);
2271
2272 case QRhiVertexInputAttribute::Half4:
2273 return 4 * sizeof(qfloat16);
2274 case QRhiVertexInputAttribute::Half3:
2275 return 4 * sizeof(qfloat16); // half3 still takes 8 bytes
2276 case QRhiVertexInputAttribute::Half2:
2277 return 2 * sizeof(qfloat16);
2278 case QRhiVertexInputAttribute::Half:
2279 return sizeof(qfloat16);
2280
2281 case QRhiVertexInputAttribute::UShort4:
2282 return 4 * sizeof(quint16);
2283 case QRhiVertexInputAttribute::UShort3:
2284 return 4 * sizeof(quint16); // ivec3 still takes 8 bytes
2285 case QRhiVertexInputAttribute::UShort2:
2286 return 2 * sizeof(quint16);
2287 case QRhiVertexInputAttribute::UShort:
2288 return sizeof(quint16);
2289
2290 case QRhiVertexInputAttribute::SShort4:
2291 return 4 * sizeof(qint16);
2292 case QRhiVertexInputAttribute::SShort3:
2293 return 4 * sizeof(qint16); // uvec3 still takes 8 bytes
2294 case QRhiVertexInputAttribute::SShort2:
2295 return 2 * sizeof(qint16);
2296 case QRhiVertexInputAttribute::SShort:
2297 return sizeof(qint16);
2298
2299 default:
2300 Q_UNREACHABLE_RETURN(1);
2301 }
2302}
2303
2304/*!
2305 \class QRhiVertexInputLayout
2306 \inmodule QtGuiPrivate
2307 \inheaderfile rhi/qrhi.h
2308 \since 6.6
2309 \brief Describes the layout of vertex inputs consumed by a vertex shader.
2310
2311 The vertex input layout is defined by the collections of
2312 QRhiVertexInputBinding and QRhiVertexInputAttribute.
2313
2314 As an example, let's assume that we have a single buffer with 3 component
2315 vertex positions and 2 component UV coordinates interleaved (\c x, \c y, \c
2316 z, \c u, \c v), that the position and UV are expected at input locations 0
2317 and 1 by the vertex shader, and that the vertex buffer will be bound at
2318 binding point 0 using
2319 \l{QRhiCommandBuffer::setVertexInput()}{setVertexInput()} later on:
2320
2321 \code
2322 QRhiVertexInputLayout inputLayout;
2323 inputLayout.setBindings({
2324 { 5 * sizeof(float) }
2325 });
2326 inputLayout.setAttributes({
2327 { 0, 0, QRhiVertexInputAttribute::Float3, 0 },
2328 { 0, 1, QRhiVertexInputAttribute::Float2, 3 * sizeof(float) }
2329 });
2330 \endcode
2331
2332 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
2333 for details.
2334 */
2335
2336/*!
2337 \fn QRhiVertexInputLayout::QRhiVertexInputLayout() = default
2338
2339 Constructs an empty vertex input layout description.
2340 */
2341
2342/*!
2343 \fn void QRhiVertexInputLayout::setBindings(std::initializer_list<QRhiVertexInputBinding> list)
2344 Sets the bindings from the specified \a list.
2345 */
2346
2347/*!
2348 \fn template<typename InputIterator> void QRhiVertexInputLayout::setBindings(InputIterator first, InputIterator last)
2349 Sets the bindings using the iterators \a first and \a last.
2350 */
2351
2352/*!
2353 \fn const QRhiVertexInputBinding *QRhiVertexInputLayout::cbeginBindings() const
2354 \return a const iterator pointing to the first item in the binding list.
2355 */
2356
2357/*!
2358 \fn const QRhiVertexInputBinding *QRhiVertexInputLayout::cendBindings() const
2359 \return a const iterator pointing just after the last item in the binding list.
2360 */
2361
2362/*!
2363 \fn const QRhiVertexInputBinding *QRhiVertexInputLayout::bindingAt(qsizetype index) const
2364 \return the binding at the given \a index.
2365 */
2366
2367/*!
2368 \fn qsizetype QRhiVertexInputLayout::bindingCount() const
2369 \return the number of bindings.
2370 */
2371
2372/*!
2373 \fn void QRhiVertexInputLayout::setAttributes(std::initializer_list<QRhiVertexInputAttribute> list)
2374 Sets the attributes from the specified \a list.
2375 */
2376
2377/*!
2378 \fn template<typename InputIterator> void QRhiVertexInputLayout::setAttributes(InputIterator first, InputIterator last)
2379 Sets the attributes using the iterators \a first and \a last.
2380 */
2381
2382/*!
2383 \fn const QRhiVertexInputAttribute *QRhiVertexInputLayout::cbeginAttributes() const
2384 \return a const iterator pointing to the first item in the attribute list.
2385 */
2386
2387/*!
2388 \fn const QRhiVertexInputAttribute *QRhiVertexInputLayout::cendAttributes() const
2389 \return a const iterator pointing just after the last item in the attribute list.
2390 */
2391
2392/*!
2393 \fn const QRhiVertexInputAttribute *QRhiVertexInputLayout::attributeAt(qsizetype index) const
2394 \return the attribute at the given \a index.
2395 */
2396
2397/*!
2398 \fn qsizetype QRhiVertexInputLayout::attributeCount() const
2399 \return the number of attributes.
2400 */
2401
2402/*!
2403 \fn bool QRhiVertexInputLayout::operator==(const QRhiVertexInputLayout &a, const QRhiVertexInputLayout &b) noexcept
2404
2405 \return \c true if the values in the two QRhiVertexInputLayout objects
2406 \a a and \a b are equal.
2407 */
2408
2409/*!
2410 \fn bool QRhiVertexInputLayout::operator!=(const QRhiVertexInputLayout &a, const QRhiVertexInputLayout &b) noexcept
2411
2412 \return \c false if the values in the two QRhiVertexInputLayout
2413 objects \a a and \a b are equal; otherwise returns \c true.
2414*/
2415
2416/*!
2417 \fn size_t QRhiVertexInputLayout::qHash(const QRhiVertexInputLayout &key, size_t seed)
2418 \qhash{QRhiVertexInputLayout}
2419 */
2420
2421#ifndef QT_NO_DEBUG_STREAM
2422QDebug operator<<(QDebug dbg, const QRhiVertexInputLayout &v)
2423{
2424 QDebugStateSaver saver(dbg);
2425 dbg.nospace() << "QRhiVertexInputLayout(bindings=" << v.m_bindings
2426 << " attributes=" << v.m_attributes
2427 << ')';
2428 return dbg;
2429}
2430#endif
2431
2432/*!
2433 \class QRhiShaderStage
2434 \inmodule QtGuiPrivate
2435 \inheaderfile rhi/qrhi.h
2436 \since 6.6
2437 \brief Specifies the type and the shader code for a shader stage in the pipeline.
2438
2439 When setting up a QRhiGraphicsPipeline, a collection of shader stages are
2440 specified. The QRhiShaderStage contains a QShader and some associated
2441 metadata, such as the graphics pipeline stage, and the
2442 \l{QShader::Variant}{shader variant} to select. There is no need to specify
2443 the shader language or version because the QRhi backend in use at runtime
2444 will take care of choosing the appropriate shader version from the
2445 collection within the QShader.
2446
2447 The typical usage is in combination with
2448 QRhiGraphicsPipeline::setShaderStages(), shown here with a simple approach
2449 to load the QShader from \c{.qsb} files generated offline or at build time:
2450
2451 \code
2452 QShader getShader(const QString &name)
2453 {
2454 QFile f(name);
2455 return f.open(QIODevice::ReadOnly) ? QShader::fromSerialized(f.readAll()) : QShader();
2456 }
2457
2458 QShader vs = getShader("material.vert.qsb");
2459 QShader fs = getShader("material.frag.qsb");
2460 pipeline->setShaderStages({
2461 { QRhiShaderStage::Vertex, vs },
2462 { QRhiShaderStage::Fragment, fs }
2463 });
2464 \endcode
2465
2466 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
2467 for details.
2468 */
2469
2470/*!
2471 \enum QRhiShaderStage::Type
2472 Specifies the type of the shader stage.
2473
2474 \value Vertex Vertex stage
2475
2476 \value TessellationControl Tessellation control (hull shader) stage. Must
2477 be used only when the QRhi::Tessellation feature is supported.
2478
2479 \value TessellationEvaluation Tessellation evaluation (domain shader)
2480 stage. Must be used only when the QRhi::Tessellation feature is supported.
2481
2482 \value Fragment Fragment (pixel shader) stage
2483
2484 \value Compute Compute stage. Must be used only when the QRhi::Compute
2485 feature is supported.
2486
2487 \value Geometry Geometry stage. Must be used only when the
2488 QRhi::GeometryShader feature is supported.
2489 */
2490
2491/*!
2492 \fn QRhiShaderStage::QRhiShaderStage() = default
2493
2494 Constructs a shader stage description for the vertex stage with an empty
2495 QShader.
2496 */
2497
2498/*!
2499 \fn QRhiShaderStage::Type QRhiShaderStage::type() const
2500 \return the type of the stage.
2501 */
2502
2503/*!
2504 \fn void QRhiShaderStage::setType(Type t)
2505
2506 Sets the type of the stage to \a t. Setters should rarely be needed in
2507 pratice. Most applications will likely use the QRhiShaderStage constructor
2508 in most cases.
2509 */
2510
2511/*!
2512 \fn QShader QRhiShaderStage::shader() const
2513 \return the QShader to be used for this stage in the graphics pipeline.
2514 */
2515
2516/*!
2517 \fn void QRhiShaderStage::setShader(const QShader &s)
2518 Sets the shader collection \a s.
2519 */
2520
2521/*!
2522 \fn QShader::Variant QRhiShaderStage::shaderVariant() const
2523 \return the requested shader variant.
2524 */
2525
2526/*!
2527 \fn void QRhiShaderStage::setShaderVariant(QShader::Variant v)
2528 Sets the requested shader variant \a v.
2529 */
2530
2531/*!
2532 Constructs a shader stage description with the \a type of the stage and the
2533 \a shader.
2534
2535 The shader variant \a v defaults to QShader::StandardShader. A
2536 QShader contains multiple source and binary versions of a shader.
2537 In addition, it can also contain variants of the shader with slightly
2538 modified code. \a v can then be used to select the desired variant.
2539 */
2540QRhiShaderStage::QRhiShaderStage(Type type, const QShader &shader, QShader::Variant v)
2541 : m_type(type),
2542 m_shader(shader),
2543 m_shaderVariant(v)
2544{
2545}
2546
2547/*!
2548 \fn bool QRhiShaderStage::operator==(const QRhiShaderStage &a, const QRhiShaderStage &b) noexcept
2549
2550 \return \c true if the values in the two QRhiShaderStage objects
2551 \a a and \a b are equal.
2552 */
2553
2554/*!
2555 \fn bool QRhiShaderStage::operator!=(const QRhiShaderStage &a, const QRhiShaderStage &b) noexcept
2556
2557 \return \c false if the values in the two QRhiShaderStage
2558 objects \a a and \a b are equal; otherwise returns \c true.
2559*/
2560
2561/*!
2562 \fn size_t QRhiShaderStage::qHash(const QRhiShaderStage &key, size_t seed)
2563 \qhash{QRhiShaderStage}
2564 */
2565
2566#ifndef QT_NO_DEBUG_STREAM
2567QDebug operator<<(QDebug dbg, const QRhiShaderStage &s)
2568{
2569 QDebugStateSaver saver(dbg);
2570 dbg.nospace() << "QRhiShaderStage(type=" << s.type()
2571 << " shader=" << s.shader()
2572 << " variant=" << s.shaderVariant()
2573 << ')';
2574 return dbg;
2575}
2576#endif
2577
2578/*!
2579 \class QRhiColorAttachment
2580 \inmodule QtGuiPrivate
2581 \inheaderfile rhi/qrhi.h
2582 \since 6.6
2583 \brief Describes the a single color attachment of a render target.
2584
2585 A color attachment is either a QRhiTexture or a QRhiRenderBuffer. The
2586 former, i.e. when texture() is set, is used in most cases.
2587 QRhiColorAttachment is commonly used in combination with
2588 QRhiTextureRenderTargetDescription.
2589
2590 \note texture() and renderBuffer() cannot be both set (be non-null at the
2591 same time).
2592
2593 Setting renderBuffer instead is recommended only when multisampling is
2594 needed. Relying on QRhi::MultisampleRenderBuffer is a better choice than
2595 QRhi::MultisampleTexture in practice since the former is available in more
2596 run time configurations (e.g. when running on OpenGL ES 3.0 which has no
2597 support for multisample textures, but does support multisample
2598 renderbuffers).
2599
2600 When targeting a non-multisample texture, the layer() and level() indicate
2601 the targeted layer (face index \c{0-5} for cubemaps) and mip level. For 3D
2602 textures layer() specifies the slice (one 2D image within the 3D texture)
2603 to render to. For texture arrays layer() is the array index.
2604
2605 When texture() or renderBuffer() is multisample, resolveTexture() can be
2606 set optionally. When set, samples are resolved automatically into that
2607 (non-multisample) texture at the end of the render pass. When rendering
2608 into a multisample renderbuffers, this is the only way to get resolved,
2609 non-multisample content out of them. Multisample textures allow sampling in
2610 shaders so for them this is just one option.
2611
2612 \note when resolving is enabled, the multisample data may not be written
2613 out at all. This means that the multisample texture() must not be used
2614 afterwards with shaders for sampling when resolveTexture() is set.
2615
2616 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
2617 for details.
2618
2619 \sa QRhiTextureRenderTargetDescription
2620 */
2621
2622/*!
2623 \fn QRhiColorAttachment::QRhiColorAttachment() = default
2624
2625 Constructs an empty color attachment description.
2626 */
2627
2628/*!
2629 Constructs a color attachment description that specifies \a texture as the
2630 associated color buffer.
2631 */
2632QRhiColorAttachment::QRhiColorAttachment(QRhiTexture *texture)
2633 : m_texture(texture)
2634{
2635}
2636
2637/*!
2638 Constructs a color attachment description that specifies \a renderBuffer as
2639 the associated color buffer.
2640 */
2641QRhiColorAttachment::QRhiColorAttachment(QRhiRenderBuffer *renderBuffer)
2642 : m_renderBuffer(renderBuffer)
2643{
2644}
2645
2646/*!
2647 \fn QRhiTexture *QRhiColorAttachment::texture() const
2648
2649 \return the texture this attachment description references, or \nullptr if
2650 there is none.
2651 */
2652
2653/*!
2654 \fn void QRhiColorAttachment::setTexture(QRhiTexture *tex)
2655
2656 Sets the texture \a tex.
2657
2658 \note texture() and renderBuffer() cannot be both set (be non-null at the
2659 same time).
2660 */
2661
2662/*!
2663 \fn QRhiRenderBuffer *QRhiColorAttachment::renderBuffer() const
2664
2665 \return the renderbuffer this attachment description references, or
2666 \nullptr if there is none.
2667
2668 In practice associating a QRhiRenderBuffer with a QRhiColorAttachment makes
2669 the most sense when setting up multisample rendering via a multisample
2670 \l{QRhiRenderBuffer::Type}{color} renderbuffer that is then resolved into a
2671 non-multisample texture at the end of the render pass.
2672 */
2673
2674/*!
2675 \fn void QRhiColorAttachment::setRenderBuffer(QRhiRenderBuffer *rb)
2676
2677 Sets the renderbuffer \a rb.
2678
2679 \note texture() and renderBuffer() cannot be both set (be non-null at the
2680 same time).
2681 */
2682
2683/*!
2684 \fn int QRhiColorAttachment::layer() const
2685 \return the layer index (cubemap face or array layer). 0 by default.
2686 */
2687
2688/*!
2689 \fn void QRhiColorAttachment::setLayer(int layer)
2690 Sets the \a layer index.
2691 */
2692
2693/*!
2694 \fn int QRhiColorAttachment::level() const
2695 \return the mip level. 0 by default.
2696 */
2697
2698/*!
2699 \fn void QRhiColorAttachment::setLevel(int level)
2700 Sets the mip \a level.
2701 */
2702
2703/*!
2704 \fn QRhiTexture *QRhiColorAttachment::resolveTexture() const
2705
2706 \return the resolve texture this attachment description references, or
2707 \nullptr if there is none.
2708
2709 Setting a non-null resolve texture is applicable when the attachment
2710 references a multisample texture or renderbuffer. The QRhiTexture in the
2711 resolveTexture() is then a non-multisample 2D texture (or texture array)
2712 with the same size (but a sample count of 1). The multisample content is
2713 automatically resolved into this texture at the end of each render pass.
2714 */
2715
2716/*!
2717 \fn void QRhiColorAttachment::setResolveTexture(QRhiTexture *tex)
2718
2719 Sets the resolve texture \a tex.
2720
2721 \a tex is expected to be a 2D texture or a 2D texture array. In either
2722 case, resolving targets a single mip level of a single layer (array
2723 element) of \a tex. The mip level and array layer are specified by
2724 resolveLevel() and resolveLayer().
2725
2726 An exception is \l{setMultiViewCount()}{multiview}: when the color
2727 attachment is associated with a texture array and multiview is enabled, the
2728 resolve texture must also be a texture array with sufficient elements for
2729 all views. In this case all elements that correspond to views are resolved
2730 automatically; the behavior is similar to the following pseudo-code:
2731 \badcode
2732 for (i = 0; i < multiViewCount(); ++i)
2733 resolve texture's layer() + i into resolveTexture's resolveLayer() + i
2734 \endcode
2735
2736 Setting a non-multisample texture to resolve a multisample texture or
2737 renderbuffer automatically at the end of the render pass is often
2738 preferable to working with multisample textures (and not setting a resolve
2739 texture), because it avoids the need for writing dedicated fragment shaders
2740 that work exclusively with multisample textures (\c sampler2DMS, \c
2741 texelFetch, etc.), and rather allows using the same shader as one would if
2742 the attachment's texture was not multisampled to begin with. This comes at
2743 the expense of an additional resource (the non-multisample \a tex).
2744 */
2745
2746/*!
2747 \fn int QRhiColorAttachment::resolveLayer() const
2748 \return the currently set resolve texture layer. Defaults to 0.
2749 */
2750
2751/*!
2752 \fn void QRhiColorAttachment::setResolveLayer(int layer)
2753 Sets the resolve texture \a layer to use.
2754 */
2755
2756/*!
2757 \fn int QRhiColorAttachment::resolveLevel() const
2758 \return the currently set resolve texture mip level. Defaults to 0.
2759 */
2760
2761/*!
2762 \fn void QRhiColorAttachment::setResolveLevel(int level)
2763 Sets the resolve texture mip \a level to use.
2764 */
2765
2766/*!
2767 \fn int QRhiColorAttachment::multiViewCount() const
2768
2769 \return the currently set number of views. Defaults to 0 which indicates
2770 the render target with this color attachment is not going to be used with
2771 multiview rendering.
2772
2773 \since 6.7
2774 */
2775
2776/*!
2777 \fn void QRhiColorAttachment::setMultiViewCount(int count)
2778
2779 Sets the view \a count. Setting a value larger than 1 indicates that the
2780 render target with this color attachment is going to be used with multiview
2781 rendering. The default value is 0. Values smaller than 2 indicate no
2782 multiview rendering.
2783
2784 When \a count is set to \c 2 or greater, the color attachment must be
2785 associated with a 2D texture array. layer() and multiViewCount() together
2786 define the range of texture array elements that are targeted during
2787 multiview rendering.
2788
2789 For example, if \c layer is \c 0 and \c multiViewCount is \c 2, the texture
2790 array must have 2 (or more) elements, and the multiview rendering will
2791 target elements 0 and 1. The \c{gl_ViewIndex} variable in the shaders has a
2792 value of \c 0 or \c 1 then, where view \c 0 corresponds to the texture array
2793 element \c 0, and view \c 1 to the array element \c 1.
2794
2795 \note Setting a \a count larger than 1, using a texture array as texture(),
2796 and calling \l{QRhiCommandBuffer::beginPass()}{beginPass()} on a
2797 QRhiTextureRenderTarget with this color attachment implies multiview
2798 rendering for the entire render pass. multiViewCount() should not be set
2799 unless multiview rendering is wanted. Multiview cannot be used with texture
2800 types other than 2D texture arrays. (although 3D textures may work,
2801 depending on the graphics API and backend; applications are nonetheless
2802 advised not to rely on that and only use 2D texture arrays as the render
2803 targets of multiview rendering)
2804
2805 See
2806 \l{https://registry.khronos.org/OpenGL/extensions/OVR/OVR_multiview.txt}{GL_OVR_multiview}
2807 for more details regarding multiview rendering. Do note that Qt requires
2808 \l{https://registry.khronos.org/OpenGL/extensions/OVR/OVR_multiview2.txt}{GL_OVR_multiview2}
2809 as well, when running on OpenGL (ES).
2810
2811 Multiview rendering is available only when the
2812 \l{QRhi::MultiView}{MultiView} feature is reported as supported from
2813 \l{QRhi::isFeatureSupported()}{isFeatureSupported()}.
2814
2815 \note For portability, be aware of limitations that exist for multiview
2816 rendering with some of the graphics APIs. It is recommended that multiview
2817 render passes do not rely on any of the features that
2818 \l{https://registry.khronos.org/OpenGL/extensions/OVR/OVR_multiview.txt}{GL_OVR_multiview}
2819 declares as unsupported. The one exception is shader stage outputs other
2820 than \c{gl_Position} depending on \c{gl_ViewIndex}: that can be relied on
2821 (even with OpenGL) because QRhi never reports multiview as supported without
2822 \c{GL_OVR_multiview2} also being present.
2823
2824 \note Multiview rendering is not supported in combination with tessellation
2825 or geometry shaders, even though some implementations of some graphics APIs
2826 may allow this.
2827
2828 \since 6.7
2829 */
2830
2831/*!
2832 \class QRhiTextureRenderTargetDescription
2833 \inmodule QtGuiPrivate
2834 \inheaderfile rhi/qrhi.h
2835 \since 6.6
2836 \brief Describes the color and depth or depth/stencil attachments of a render target.
2837
2838 A texture render target has zero or more textures as color attachments,
2839 zero or one renderbuffer as combined depth/stencil buffer or zero or one
2840 texture as depth buffer.
2841
2842 \note depthStencilBuffer() and depthTexture() cannot be both set (cannot be
2843 non-null at the same time).
2844
2845 Let's look at some example usages in combination with
2846 QRhiTextureRenderTarget.
2847
2848 Due to the constructors, the targeting a texture (and no depth/stencil
2849 buffer) is simple:
2850
2851 \code
2852 QRhiTexture *texture = rhi->newTexture(QRhiTexture::RGBA8, QSize(256, 256), 1, QRhiTexture::RenderTarget);
2853 texture->create();
2854 QRhiTextureRenderTarget *rt = rhi->newTextureRenderTarget({ texture }));
2855 \endcode
2856
2857 The following creates a texture render target that is set up to target mip
2858 level #2 of a texture:
2859
2860 \code
2861 QRhiTexture *texture = rhi->newTexture(QRhiTexture::RGBA8, QSize(512, 512), 1, QRhiTexture::RenderTarget | QRhiTexture::MipMapped);
2862 texture->create();
2863 QRhiColorAttachment colorAtt(texture);
2864 colorAtt.setLevel(2);
2865 QRhiTextureRenderTarget *rt = rhi->newTextureRenderTarget({ colorAtt });
2866 \endcode
2867
2868 Another example, this time to render into a depth texture:
2869
2870 \code
2871 QRhiTexture *shadowMap = rhi->newTexture(QRhiTexture::D32F, QSize(1024, 1024), 1, QRhiTexture::RenderTarget);
2872 shadowMap->create();
2873 QRhiTextureRenderTargetDescription rtDesc;
2874 rtDesc.setDepthTexture(shadowMap);
2875 QRhiTextureRenderTarget *rt = rhi->newTextureRenderTarget(rtDesc);
2876 \endcode
2877
2878 A very common case, having a texture as the color attachment and a
2879 renderbuffer as depth/stencil to enable depth testing:
2880
2881 \code
2882 QRhiTexture *texture = rhi->newTexture(QRhiTexture::RGBA8, QSize(512, 512), 1, QRhiTexture::RenderTarget);
2883 texture->create();
2884 QRhiRenderBuffer *depthStencil = rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil, QSize(512, 512));
2885 depthStencil->create();
2886 QRhiTextureRenderTargetDescription rtDesc({ texture }, depthStencil);
2887 QRhiTextureRenderTarget *rt = rhi->newTextureRenderTarget(rtDesc);
2888 \endcode
2889
2890 Finally, to enable multisample rendering in a portable manner (so also
2891 supporting OpenGL ES 3.0), using a QRhiRenderBuffer as the (multisample)
2892 color buffer and then resolving into a regular (non-multisample) 2D
2893 texture. To enable depth testing, a depth-stencil buffer, which also must
2894 use the same sample count, is used as well:
2895
2896 \code
2897 QRhiRenderBuffer *colorBuffer = rhi->newRenderBuffer(QRhiRenderBuffer::Color, QSize(512, 512), 4); // 4x MSAA
2898 colorBuffer->create();
2899 QRhiRenderBuffer *depthStencil = rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil, QSize(512, 512), 4);
2900 depthStencil->create();
2901 QRhiTexture *texture = rhi->newTexture(QRhiTexture::RGBA8, QSize(512, 512), 1, QRhiTexture::RenderTarget);
2902 texture->create();
2903 QRhiColorAttachment colorAtt(colorBuffer);
2904 colorAtt.setResolveTexture(texture);
2905 QRhiTextureRenderTarget *rt = rhi->newTextureRenderTarget({ colorAtt, depthStencil });
2906 \endcode
2907
2908 \note when multisample resolving is enabled, the multisample data may not be
2909 written out at all. This means that the multisample texture in a color
2910 attachment must not be used afterwards with shaders for sampling (or other
2911 purposes) whenever a resolve texture is set, since the multisample color
2912 buffer is merely an intermediate storage then that gets no data written back
2913 on some GPU architectures at all. See
2914 \l{QRhiTextureRenderTarget::Flag}{PreserveColorContents} for more details.
2915
2916 \note When using setDepthTexture(), not setDepthStencilBuffer(), and the
2917 depth (stencil) data is not of interest afterwards, set the
2918 DoNotStoreDepthStencilContents flag on the QRhiTextureRenderTarget. This
2919 allows indicating to the underlying 3D API that the depth/stencil data can
2920 be discarded, leading potentially to better performance with tiled GPU
2921 architectures. When the depth-stencil buffer is a QRhiRenderBuffer (and also
2922 for the multisample color texture, see previous note) this is implicit, but
2923 with a depth (stencil) QRhiTexture the intention needs to be declared
2924 explicitly. By default QRhi assumes that the data is of interest (e.g., the
2925 depth texture is sampled in a shader afterwards).
2926
2927 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
2928 for details.
2929
2930 \sa QRhiColorAttachment, QRhiTextureRenderTarget
2931 */
2932
2933/*!
2934 \fn QRhiTextureRenderTargetDescription::QRhiTextureRenderTargetDescription() = default
2935
2936 Constructs an empty texture render target description.
2937 */
2938
2939/*!
2940 Constructs a texture render target description with one attachment
2941 described by \a colorAttachment.
2942 */
2943QRhiTextureRenderTargetDescription::QRhiTextureRenderTargetDescription(const QRhiColorAttachment &colorAttachment)
2944{
2945 m_colorAttachments.append(colorAttachment);
2946}
2947
2948/*!
2949 Constructs a texture render target description with two attachments, a
2950 color attachment described by \a colorAttachment, and a depth/stencil
2951 attachment with \a depthStencilBuffer.
2952 */
2953QRhiTextureRenderTargetDescription::QRhiTextureRenderTargetDescription(const QRhiColorAttachment &colorAttachment,
2954 QRhiRenderBuffer *depthStencilBuffer)
2955 : m_depthStencilBuffer(depthStencilBuffer)
2956{
2957 m_colorAttachments.append(colorAttachment);
2958}
2959
2960/*!
2961 Constructs a texture render target description with two attachments, a
2962 color attachment described by \a colorAttachment, and a depth attachment
2963 with \a depthTexture.
2964
2965 \note \a depthTexture must have a suitable format, such as QRhiTexture::D16
2966 or QRhiTexture::D32F.
2967 */
2968QRhiTextureRenderTargetDescription::QRhiTextureRenderTargetDescription(const QRhiColorAttachment &colorAttachment,
2969 QRhiTexture *depthTexture)
2970 : m_depthTexture(depthTexture)
2971{
2972 m_colorAttachments.append(colorAttachment);
2973}
2974
2975/*!
2976 \fn void QRhiTextureRenderTargetDescription::setColorAttachments(std::initializer_list<QRhiColorAttachment> list)
2977 Sets the \a list of color attachments.
2978 */
2979
2980/*!
2981 \fn template<typename InputIterator> void QRhiTextureRenderTargetDescription::setColorAttachments(InputIterator first, InputIterator last)
2982 Sets the list of color attachments via the iterators \a first and \a last.
2983 */
2984
2985/*!
2986 \fn const QRhiColorAttachment *QRhiTextureRenderTargetDescription::cbeginColorAttachments() const
2987 \return a const iterator pointing to the first item in the attachment list.
2988 */
2989
2990/*!
2991 \fn const QRhiColorAttachment *QRhiTextureRenderTargetDescription::cendColorAttachments() const
2992 \return a const iterator pointing just after the last item in the attachment list.
2993 */
2994
2995/*!
2996 \fn const QRhiColorAttachment *QRhiTextureRenderTargetDescription::colorAttachmentAt(qsizetype index) const
2997 \return the color attachment at the specified \a index.
2998 */
2999
3000/*!
3001 \fn qsizetype QRhiTextureRenderTargetDescription::colorAttachmentCount() const
3002 \return the number of currently set color attachments.
3003 */
3004
3005/*!
3006 \fn QRhiRenderBuffer *QRhiTextureRenderTargetDescription::depthStencilBuffer() const
3007 \return the renderbuffer used as depth-stencil buffer, or \nullptr if none was set.
3008 */
3009
3010/*!
3011 \fn void QRhiTextureRenderTargetDescription::setDepthStencilBuffer(QRhiRenderBuffer *renderBuffer)
3012
3013 Sets the \a renderBuffer for depth-stencil. Not mandatory, e.g. when no
3014 depth test/write or stencil-related features are used within any graphics
3015 pipelines in any of the render passes for this render target, it can be
3016 left set to \nullptr.
3017
3018 \note depthStencilBuffer() and depthTexture() cannot be both set (cannot be
3019 non-null at the same time).
3020
3021 Using a QRhiRenderBuffer over a 2D QRhiTexture as the depth or
3022 depth/stencil buffer is very common, and is the recommended approach for
3023 applications. Using a QRhiTexture, and so setDepthTexture() becomes
3024 relevant if the depth data is meant to be accessed (e.g. sampled in a
3025 shader) afterwards, or when
3026 \l{QRhiColorAttachment::setMultiViewCount()}{multiview rendering} is
3027 involved (because then the depth texture must be a texture array).
3028
3029 \sa setDepthTexture()
3030 */
3031
3032/*!
3033 \fn QRhiTexture *QRhiTextureRenderTargetDescription::depthTexture() const
3034 \return the currently referenced depth texture, or \nullptr if none was set.
3035 */
3036
3037/*!
3038 \fn void QRhiTextureRenderTargetDescription::setDepthTexture(QRhiTexture *texture)
3039
3040 Sets the \a texture for depth-stencil. This is an alternative to
3041 setDepthStencilBuffer(), where instead of a QRhiRenderBuffer a QRhiTexture
3042 with a suitable type (e.g., QRhiTexture::D32F) is provided.
3043
3044 \note depthStencilBuffer() and depthTexture() cannot be both set (cannot be
3045 non-null at the same time).
3046
3047 \a texture can either be a 2D texture or a 2D texture array (when texture
3048 arrays are supported). Specifying a texture array is relevant in particular
3049 with
3050 \l{QRhiColorAttachment::setMultiViewCount()}{multiview rendering}.
3051
3052 \note If \a texture is a format with a stencil component, such as
3053 \l QRhiTexture::D24S8, it will serve as the stencil buffer as well.
3054
3055 \sa setDepthStencilBuffer()
3056 */
3057
3058/*!
3059 \fn int QRhiTextureRenderTargetDescription::depthLayer() const
3060 \return the array slice index to be used for the depth/stencil attachment,
3061 or -1 by default.
3062
3063 \since 6.12
3064 \sa setDepthLayer(), setDepthTexture()
3065 */
3066
3067/*!
3068 \fn void QRhiTextureRenderTargetDescription::setDepthLayer(int depthLayer)
3069
3070 Sets the array slice index to be used for the depth/stencil attachment.
3071
3072 Pass -1 (the default) to not target a particular layer. When set to a
3073 non-negative value, the render target attaches a view that targets exactly
3074 that layer (slice) of the depth texture. This is only effective when a 2D
3075 array depth texture is provided via setDepthTexture(); otherwise the value
3076 is ignored.
3077
3078 The value must be within the array size of the depth texture; passing an
3079 out-of-range index leads to undefined behavior. The index is absolute
3080 with respect to the underlying texture, regardless of any array range
3081 that may have been specified when creating the texture.
3082
3083 Specifying a \a depthLayer disables layered/multiview rendering for the
3084 depth attachment.
3085
3086 \since 6.12
3087 \sa depthLayer(), setDepthTexture()
3088 */
3089
3090/*!
3091 \fn QRhiTexture *QRhiTextureRenderTargetDescription::depthResolveTexture() const
3092
3093 \return the texture to which a multisample depth (or depth-stencil) texture
3094 (or texture array) is resolved to. \nullptr if there is none, which is the
3095 most common case.
3096
3097 \since 6.8
3098 \sa QRhiColorAttachment::resolveTexture(), depthTexture()
3099 */
3100
3101/*!
3102 \fn void QRhiTextureRenderTargetDescription::setDepthResolveTexture(QRhiTexture *tex)
3103
3104 Sets the depth (or depth-stencil) resolve texture \a tex.
3105
3106 \a tex is expected to be a 2D texture or a 2D texture array with a format
3107 matching the texture set via setDepthTexture().
3108
3109 \note Resolving depth (or depth-stencil) data is only functional when the
3110 \l QRhi::ResolveDepthStencil feature is reported as supported at run time.
3111 Support for depth-stencil resolve is not universally available among the
3112 graphics APIs. Designs assuming unconditional availability of depth-stencil
3113 resolve are therefore non-portable, and should be avoided.
3114
3115 \note As an additional limitation for OpenGL ES in particular, setting a
3116 depth resolve texture may only be functional in combination with
3117 setDepthTexture(), not with setDepthStencilBuffer().
3118
3119 \since 6.8
3120 \sa QRhiColorAttachment::setResolveTexture(), setDepthTexture()
3121 */
3122
3123/*!
3124 \fn QRhiShadingRateMap *QRhiTextureRenderTargetDescription::shadingRateMap() const
3125 \return the currently set QRhiShadingRateMap. By default this is \nullptr.
3126 \since 6.9
3127 */
3128
3129/*!
3130 \fn void QRhiTextureRenderTargetDescription::setShadingRateMap(QRhiShadingRateMap *map)
3131
3132 Associates with the specified QRhiShadingRateMap \a map. This is functional
3133 only when the \l QRhi::VariableRateShadingMap feature is reported as
3134 supported.
3135
3136 When QRhiCommandBuffer::setShadingRate() is also called, the higher of the
3137 two shading rates is used for each tile. There is currently no control
3138 offered over the combiner behavior.
3139
3140 \note When the render target had already been built (create() was called
3141 successfully), setting a shading rate map implies that a different, new
3142 QRhiRenderPassDescriptor is needed and thus a rebuild is needed. Call
3143 setRenderPassDescriptor() again (outside of a render pass) and then rebuild
3144 by calling create(). This has other rolling consequences as well, for
3145 example for graphics pipelines: those also need to be associated with the
3146 new QRhiRenderPassDescriptor and then rebuilt. See \l
3147 QRhiRenderPassDescriptor::serializedFormat() for some suggestions on how to
3148 deal with this. Remember to set the QRhiGraphicsPipeline::UsesShadingRate
3149 flag as well.
3150
3151 \since 6.9
3152 */
3153
3154/*!
3155 \class QRhiTextureSubresourceUploadDescription
3156 \inmodule QtGuiPrivate
3157 \inheaderfile rhi/qrhi.h
3158 \since 6.6
3159 \brief Describes the source for one mip level in a layer in a texture upload operation.
3160
3161 The source content is specified either as a QImage or as a raw blob. The
3162 former is only allowed for uncompressed textures with a format that can be
3163 mapped to QImage, while the latter is supported for all formats, including
3164 floating point and compressed.
3165
3166 \note image() and data() cannot be both set at the same time.
3167
3168 destinationTopLeft() specifies the top-left corner of the target
3169 rectangle. Defaults to (0, 0).
3170
3171 An empty sourceSize() (the default) indicates that size is assumed to be
3172 the size of the subresource. With QImage-based uploads this implies that
3173 the size of the source image() must match the subresource. When providing
3174 raw data instead, sufficient number of bytes must be provided in data().
3175
3176 sourceTopLeft() is supported only for QImage-based uploads, and specifies
3177 the top-left corner of the source rectangle.
3178
3179 \note Setting sourceSize() or sourceTopLeft() may trigger a QImage copy
3180 internally, depending on the format and the backend.
3181
3182 When providing raw data, and the stride is not specified via
3183 setDataStride(), the stride (row pitch, row length in bytes) of the
3184 provided data must be equal to \c{width * pixelSize} where \c pixelSize is
3185 the number of bytes used for one pixel, and there must be no additional
3186 padding between rows. There is no row start alignment requirement.
3187
3188 When there is unused data at the end of each row in the input raw data,
3189 call setDataStride() with the total number of bytes per row. The stride
3190 must always be a multiple of the number of bytes for one pixel. The row
3191 stride is only applicable to image data for textures with an uncompressed
3192 format.
3193
3194 \note The format of the source data must be compatible with the texture
3195 format. With many graphics APIs the data is copied as-is into a staging
3196 buffer, there is no intermediate format conversion provided by QRhi. This
3197 applies to floating point formats as well, with, for example, RGBA16F
3198 requiring half floats in the source data.
3199
3200 \note Setting the stride via setDataStride() is only functional when
3201 QRhi::ImageDataStride is reported as
3202 \l{QRhi::isFeatureSupported()}{supported}. In practice this can be expected
3203 to be supported everywhere except for OpenGL ES 2.0.
3204
3205 \note When a QImage is given, the stride returned from
3206 QImage::bytesPerLine() is taken into account automatically.
3207
3208 \warning When a QImage is given and the QImage does not own the underlying
3209 pixel data, it is up to the caller to ensure that the associated data stays
3210 valid until the end of the frame. (just submitting the resource update batch
3211 is not sufficient, the data must stay valid until QRhi::endFrame() is called
3212 in order to be portable across all backends) If this cannot be ensured, the
3213 caller is strongly encouraged to call QImage::detach() on the image before
3214 passing it to uploadTexture().
3215
3216 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
3217 for details.
3218
3219 \sa QRhiTextureUploadDescription
3220 */
3221
3222/*!
3223 \fn QRhiTextureSubresourceUploadDescription::QRhiTextureSubresourceUploadDescription() = default
3224
3225 Constructs an empty subresource description.
3226
3227 \note an empty QRhiTextureSubresourceUploadDescription is not useful on its
3228 own and should not be submitted to a QRhiTextureUploadEntry. At minimum
3229 image or data must be set first.
3230 */
3231
3232/*!
3233 Constructs a mip level description with a \a image.
3234
3235 The \l{QImage::size()}{size} of \a image must match the size of the mip
3236 level. For level 0 that is the \l{QRhiTexture::pixelSize()}{texture size}.
3237
3238 The bit depth of \a image must be compatible with the
3239 \l{QRhiTexture::Format}{texture format}.
3240
3241 To describe a partial upload, call setSourceSize(), setSourceTopLeft(), or
3242 setDestinationTopLeft() afterwards.
3243 */
3244QRhiTextureSubresourceUploadDescription::QRhiTextureSubresourceUploadDescription(const QImage &image)
3245 : m_image(image)
3246{
3247}
3248
3249/*!
3250 Constructs a mip level description with the image data is specified by \a
3251 data and \a size. This is suitable for floating point and compressed
3252 formats as well.
3253
3254 \a data can safely be destroyed or changed once this function returns.
3255 */
3256QRhiTextureSubresourceUploadDescription::QRhiTextureSubresourceUploadDescription(const void *data, quint32 size)
3257 : m_data(reinterpret_cast<const char *>(data), size)
3258{
3259}
3260
3261/*!
3262 Constructs a mip level description with the image data specified by \a
3263 data. This is suitable for floating point and compressed formats as well.
3264 */
3265QRhiTextureSubresourceUploadDescription::QRhiTextureSubresourceUploadDescription(const QByteArray &data)
3266 : m_data(data)
3267{
3268}
3269
3270/*!
3271 \fn QImage QRhiTextureSubresourceUploadDescription::image() const
3272 \return the currently set QImage.
3273 */
3274
3275/*!
3276 \fn void QRhiTextureSubresourceUploadDescription::setImage(const QImage &image)
3277
3278 Sets \a image.
3279 Upon textures loading, the image data will be read as is, with no formats conversions.
3280
3281 \note image() and data() cannot be both set at the same time.
3282 */
3283
3284/*!
3285 \fn QByteArray QRhiTextureSubresourceUploadDescription::data() const
3286 \return the currently set raw pixel data.
3287 */
3288
3289/*!
3290 \fn void QRhiTextureSubresourceUploadDescription::setData(const QByteArray &data)
3291
3292 Sets \a data.
3293
3294 \note image() and data() cannot be both set at the same time.
3295 */
3296
3297/*!
3298 \fn quint32 QRhiTextureSubresourceUploadDescription::dataStride() const
3299 \return the currently set data stride.
3300 */
3301
3302/*!
3303 \fn void QRhiTextureSubresourceUploadDescription::setDataStride(quint32 stride)
3304
3305 Sets the data \a stride in bytes. By default this is 0 and not always
3306 relevant. When providing raw data(), and the stride is not specified via
3307 setDataStride(), the stride (row pitch, row length in bytes) of the
3308 provided data must be equal to \c{width * pixelSize} where \c pixelSize is
3309 the number of bytes used for one pixel, and there must be no additional
3310 padding between rows. Otherwise, if there is additional space between the
3311 lines, set a non-zero \a stride. All this is applicable only when raw image
3312 data is provided, and is not necessary when working QImage since that has
3313 its own \l{QImage::bytesPerLine()}{stride} value.
3314
3315 \note When a non-zero \a stride is set, make sure the data contains the
3316 trailing padding for the last row as well, i.e. at least \c{stride * height}
3317 bytes in total. While providing the data without the last row's padding
3318 (i.e., interpreting stride as not applicable to the last row) could be safe,
3319 and is in fact safe with Vulkan, OpenGL, and D3D12, this cannot be
3320 guaranteed for all backends, so the safe approach is to avoid this and treat
3321 the last line like all others.
3322
3323 \note Setting the stride via setDataStride() is only functional when
3324 QRhi::ImageDataStride is reported as
3325 \l{QRhi::isFeatureSupported()}{supported}.
3326
3327 \note When a QImage is given, the stride returned from
3328 QImage::bytesPerLine() is taken into account automatically and therefore
3329 there is no need to set the data stride manually.
3330 */
3331
3332/*!
3333 \fn QPoint QRhiTextureSubresourceUploadDescription::destinationTopLeft() const
3334 \return the currently set destination top-left position. Defaults to (0, 0).
3335 */
3336
3337/*!
3338 \fn void QRhiTextureSubresourceUploadDescription::setDestinationTopLeft(const QPoint &p)
3339 Sets the destination top-left position \a p.
3340
3341 \note In the most common case of sourcing the image data from a QImage, Qt
3342 performs clamping of invalid texture upload sizes when the destination
3343 position + the source size exceeds the size of the targeted texture
3344 subresource (i.e, the size at the given mip level). There is also a
3345 qWarning() message printed on the debug output in this case. This is done in
3346 order to avoid confusion when the underlying 3D APIs crash and lead to GPU
3347 device removals at a later point when submitting the commands. Regardless,
3348 developers are encouraged to always validate applications by running with the
3349 Vulkan, D3D12, or Metal validation/debug layers enabled, since those offer a
3350 much wider range of checks on API usage.
3351 */
3352
3353/*!
3354 \fn QSize QRhiTextureSubresourceUploadDescription::sourceSize() const
3355
3356 \return the source size in pixels. Defaults to a default-constructed QSize,
3357 which indicates the entire subresource.
3358 */
3359
3360/*!
3361 \fn void QRhiTextureSubresourceUploadDescription::setSourceSize(const QSize &size)
3362
3363 Sets the source \a size in pixels.
3364
3365 \note Setting sourceSize() or sourceTopLeft() may trigger a QImage copy
3366 internally, depending on the format and the backend.
3367 */
3368
3369/*!
3370 \fn QPoint QRhiTextureSubresourceUploadDescription::sourceTopLeft() const
3371 \return the currently set source top-left position. Defaults to (0, 0).
3372 */
3373
3374/*!
3375 \fn void QRhiTextureSubresourceUploadDescription::setSourceTopLeft(const QPoint &p)
3376
3377 Sets the source top-left position \a p.
3378
3379 \note Setting sourceSize() or sourceTopLeft() may trigger a QImage copy
3380 internally, depending on the format and the backend.
3381 */
3382
3383/*!
3384 \class QRhiTextureUploadEntry
3385 \inmodule QtGuiPrivate
3386 \inheaderfile rhi/qrhi.h
3387 \since 6.6
3388
3389 \brief Describes one layer (face for cubemaps, slice for 3D textures,
3390 element for texture arrays) in a texture upload operation.
3391
3392 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
3393 for details.
3394 */
3395
3396/*!
3397 \fn QRhiTextureUploadEntry::QRhiTextureUploadEntry()
3398
3399 Constructs an empty QRhiTextureUploadEntry targeting layer 0 and level 0.
3400
3401 \note an empty QRhiTextureUploadEntry should not be submitted without
3402 setting a QRhiTextureSubresourceUploadDescription via setDescription()
3403 first.
3404 */
3405
3406/*!
3407 Constructs a QRhiTextureUploadEntry targeting the given \a layer and mip
3408 \a level, with the subresource contents described by \a desc.
3409 */
3410QRhiTextureUploadEntry::QRhiTextureUploadEntry(int layer, int level,
3411 const QRhiTextureSubresourceUploadDescription &desc)
3412 : m_layer(layer),
3413 m_level(level),
3414 m_desc(desc)
3415{
3416}
3417
3418/*!
3419 \fn int QRhiTextureUploadEntry::layer() const
3420 \return the currently set layer index (cubemap face, array layer). Defaults to 0.
3421 */
3422
3423/*!
3424 \fn void QRhiTextureUploadEntry::setLayer(int layer)
3425 Sets the \a layer.
3426 */
3427
3428/*!
3429 \fn int QRhiTextureUploadEntry::level() const
3430 \return the currently set mip level. Defaults to 0.
3431 */
3432
3433/*!
3434 \fn void QRhiTextureUploadEntry::setLevel(int level)
3435 Sets the mip \a level.
3436 */
3437
3438/*!
3439 \fn QRhiTextureSubresourceUploadDescription QRhiTextureUploadEntry::description() const
3440 \return the currently set subresource description.
3441 */
3442
3443/*!
3444 \fn void QRhiTextureUploadEntry::setDescription(const QRhiTextureSubresourceUploadDescription &desc)
3445 Sets the subresource description \a desc.
3446 */
3447
3448/*!
3449 \class QRhiTextureUploadDescription
3450 \inmodule QtGuiPrivate
3451 \inheaderfile rhi/qrhi.h
3452 \since 6.6
3453 \brief Describes a texture upload operation.
3454
3455 Used with QRhiResourceUpdateBatch::uploadTexture(). That function has two
3456 variants: one taking a QImage and one taking a
3457 QRhiTextureUploadDescription. The former is a convenience version,
3458 internally creating a QRhiTextureUploadDescription with a single image
3459 targeting level 0 for layer 0.
3460
3461 An example of the common, simple case of wanting to upload the contents
3462 of a QImage to a QRhiTexture with a matching pixel size:
3463
3464 \code
3465 QImage image(256, 256, QImage::Format_RGBA8888);
3466 image.fill(Qt::green); // or could use a QPainter targeting image
3467 QRhiTexture *texture = rhi->newTexture(QRhiTexture::RGBA8, QSize(256, 256));
3468 texture->create();
3469 QRhiResourceUpdateBatch *u = rhi->nextResourceUpdateBatch();
3470 u->uploadTexture(texture, image);
3471 \endcode
3472
3473 When cubemaps, pre-generated mip images, compressed textures, or partial
3474 uploads are involved, applications will have to use this class instead.
3475
3476 QRhiTextureUploadDescription also enables specifying batched uploads, which
3477 are useful for example when generating an atlas or glyph cache texture:
3478 multiple, partial uploads for the same subresource (meaning the same layer
3479 and level) are supported, and can be, depending on the backend and the
3480 underlying graphics API, more efficient when batched into the same
3481 QRhiTextureUploadDescription as opposed to issuing individual
3482 \l{QRhiResourceUpdateBatch::uploadTexture()}{uploadTexture()} commands for
3483 each of them.
3484
3485 \note Cubemaps have one layer for each of the six faces in the order +X,
3486 -X, +Y, -Y, +Z, -Z.
3487
3488 For example, specifying the faces of a cubemap could look like the following:
3489
3490 \code
3491 QImage faces[6];
3492 // ...
3493 QVarLengthArray<QRhiTextureUploadEntry, 6> entries;
3494 for (int i = 0; i < 6; ++i)
3495 entries.append(QRhiTextureUploadEntry(i, 0, faces[i]));
3496 QRhiTextureUploadDescription desc;
3497 desc.setEntries(entries.cbegin(), entries.cend());
3498 resourceUpdates->uploadTexture(texture, desc);
3499 \endcode
3500
3501 Another example that specifies mip images for a compressed texture:
3502
3503 \code
3504 QList<QRhiTextureUploadEntry> entries;
3505 const int mipCount = rhi->mipLevelsForSize(compressedTexture->pixelSize());
3506 for (int level = 0; level < mipCount; ++level) {
3507 const QByteArray compressedDataForLevel = ..
3508 entries.append(QRhiTextureUploadEntry(0, level, compressedDataForLevel));
3509 }
3510 QRhiTextureUploadDescription desc;
3511 desc.setEntries(entries.cbegin(), entries.cend());
3512 resourceUpdates->uploadTexture(compressedTexture, desc);
3513 \endcode
3514
3515 With partial uploads targeting the same subresource, it is recommended to
3516 batch them into a single upload request, whenever possible:
3517
3518 \code
3519 QRhiTextureSubresourceUploadDescription subresDesc(image);
3520 subresDesc.setSourceSize(QSize(10, 10));
3521 subResDesc.setDestinationTopLeft(QPoint(50, 40));
3522 QRhiTextureUploadEntry entry(0, 0, subresDesc); // layer 0, level 0
3523
3524 QRhiTextureSubresourceUploadDescription subresDesc2(image);
3525 subresDesc2.setSourceSize(QSize(30, 40));
3526 subResDesc2.setDestinationTopLeft(QPoint(100, 200));
3527 QRhiTextureUploadEntry entry2(0, 0, subresDesc2); // layer 0, level 0, i.e. same subresource
3528
3529 QRhiTextureUploadDescription desc({ entry, entry2});
3530 resourceUpdates->uploadTexture(texture, desc);
3531 \endcode
3532
3533 Batching is a recommendation, not a requirement. The subresources of a
3534 texture, including the mip levels of a compressed texture, can also be
3535 uploaded via separate
3536 \l{QRhiResourceUpdateBatch::uploadTexture()}{uploadTexture()} calls, in any
3537 order, and spread over multiple frames. This is what streaming a mip chain
3538 under a per-frame upload budget needs.
3539
3540 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
3541 for details.
3542
3543 \sa QRhiResourceUpdateBatch
3544 */
3545
3546/*!
3547 \fn QRhiTextureUploadDescription::QRhiTextureUploadDescription()
3548
3549 Constructs an empty texture upload description.
3550 */
3551
3552/*!
3553 Constructs a texture upload description with a single subresource upload
3554 described by \a entry.
3555 */
3556QRhiTextureUploadDescription::QRhiTextureUploadDescription(const QRhiTextureUploadEntry &entry)
3557{
3558 m_entries.append(entry);
3559}
3560
3561/*!
3562 Constructs a texture upload description with the specified \a list of entries.
3563
3564 \note \a list can also contain multiple QRhiTextureUploadEntry elements
3565 with the same layer and level. This makes sense when those uploads are
3566 partial, meaning their subresource description has a source size or image
3567 smaller than the subresource dimensions, and can be more efficient than
3568 issuing separate uploadTexture()'s.
3569 */
3570QRhiTextureUploadDescription::QRhiTextureUploadDescription(std::initializer_list<QRhiTextureUploadEntry> list)
3571 : m_entries(list)
3572{
3573}
3574
3575/*!
3576 \fn void QRhiTextureUploadDescription::setEntries(std::initializer_list<QRhiTextureUploadEntry> list)
3577 Sets the \a list of entries.
3578 */
3579
3580/*!
3581 \fn template<typename InputIterator> void QRhiTextureUploadDescription::setEntries(InputIterator first, InputIterator last)
3582 Sets the list of entries using the iterators \a first and \a last.
3583 */
3584
3585/*!
3586 \fn const QRhiTextureUploadEntry *QRhiTextureUploadDescription::cbeginEntries() const
3587 \return a const iterator pointing to the first item in the entry list.
3588 */
3589
3590/*!
3591 \fn const QRhiTextureUploadEntry *QRhiTextureUploadDescription::cendEntries() const
3592 \return a const iterator pointing just after the last item in the entry list.
3593 */
3594
3595/*!
3596 \fn const QRhiTextureUploadEntry *QRhiTextureUploadDescription::entryAt(qsizetype index) const
3597 \return the entry at \a index.
3598 */
3599
3600/*!
3601 \fn qsizetype QRhiTextureUploadDescription::entryCount() const
3602 \return the number of entries.
3603 */
3604
3605/*!
3606 \class QRhiBufferCopyDescription
3607 \inmodule QtGuiPrivate
3608 \inheaderfile rhi/qrhi.h
3609 \since 6.13
3610 \brief Describes a buffer-to-buffer copy operation.
3611
3612 A size() of 0 indicates that the entire source buffer is to be copied. A
3613 default constructed copy description therefore leads to copying the whole
3614 of the source buffer to the beginning of the destination buffer.
3615
3616 \note The copied region must fit both the source and the destination
3617 buffer. When it does not, QRhiResourceUpdateBatch::copyBuffer() prints a
3618 warning and drops the operation.
3619
3620 \note size(), sourceOffset(), and destinationOffset() should all be
3621 multiples of 4. This is a requirement of the blit encoder in Metal, and it
3622 applies on macOS on Intel-based devices. Other platforms and 3D APIs,
3623 including Metal on Apple Silicon and on iOS, have no such restriction, but
3624 portable code has to assume the strictest of these. Note that a size() of 0
3625 implies the full size of the source buffer, which is not necessarily a
3626 multiple of 4 either.
3627
3628 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
3629 for details.
3630
3631 \sa QRhiResourceUpdateBatch::copyBuffer()
3632 */
3633
3634/*!
3635 \fn QRhiBufferCopyDescription::QRhiBufferCopyDescription()
3636
3637 Constructs an empty buffer copy description.
3638 */
3639
3640/*!
3641 \fn quint32 QRhiBufferCopyDescription::size() const
3642 \return the number of bytes to copy.
3643
3644 \note A size() of 0 indicates that the entire source buffer is to be
3645 copied.
3646 */
3647
3648/*!
3649 \fn void QRhiBufferCopyDescription::setSize(quint32 sz)
3650 Sets the number of bytes to copy to \a sz.
3651 */
3652
3653/*!
3654 \fn quint32 QRhiBufferCopyDescription::sourceOffset() const
3655 \return the offset in bytes into the source buffer. Defaults to 0.
3656 */
3657
3658/*!
3659 \fn void QRhiBufferCopyDescription::setSourceOffset(quint32 offset)
3660 Sets the source \a offset in bytes.
3661 */
3662
3663/*!
3664 \fn quint32 QRhiBufferCopyDescription::destinationOffset() const
3665 \return the offset in bytes into the destination buffer. Defaults to 0.
3666 */
3667
3668/*!
3669 \fn void QRhiBufferCopyDescription::setDestinationOffset(quint32 offset)
3670 Sets the destination \a offset in bytes.
3671 */
3672
3673/*!
3674 \class QRhiTextureCopyDescription
3675 \inmodule QtGuiPrivate
3676 \inheaderfile rhi/qrhi.h
3677 \since 6.6
3678 \brief Describes a texture-to-texture copy operation.
3679
3680 An empty pixelSize() indicates that the entire subresource is to be copied.
3681 A default constructed copy description therefore leads to copying the
3682 entire subresource at level 0 of layer 0.
3683
3684 \note The source texture must be created with
3685 QRhiTexture::UsedAsTransferSource.
3686
3687 \note The source and destination rectangles defined by pixelSize(),
3688 sourceTopLeft(), and destinationTopLeft() must fit the source and
3689 destination textures, respectively. The behavior is undefined otherwise.
3690
3691 With cubemaps, 3D textures, and texture arrays one face or slice can be
3692 copied at a time. The face or slice is specified by the source and
3693 destination layer indices. With mipmapped textures one mip level can be
3694 copied at a time. The source and destination layer and mip level indices can
3695 differ, but the size and position must be carefully controlled to avoid out
3696 of bounds copies, in which case the behavior is undefined.
3697
3698 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
3699 for details.
3700 */
3701
3702/*!
3703 \fn QRhiTextureCopyDescription::QRhiTextureCopyDescription()
3704
3705 Constructs an empty texture copy description.
3706 */
3707
3708/*!
3709 \fn QSize QRhiTextureCopyDescription::pixelSize() const
3710 \return the size of the region to copy.
3711
3712 \note An empty pixelSize() indicates that the entire subresource is to be
3713 copied. A default constructed copy description therefore leads to copying
3714 the entire subresource at level 0 of layer 0.
3715 */
3716
3717/*!
3718 \fn void QRhiTextureCopyDescription::setPixelSize(const QSize &sz)
3719 Sets the size of the region to copy to \a sz.
3720 */
3721
3722/*!
3723 \fn int QRhiTextureCopyDescription::sourceLayer() const
3724 \return the source array layer (cubemap face or array layer index). Defaults to 0.
3725 */
3726
3727/*!
3728 \fn void QRhiTextureCopyDescription::setSourceLayer(int layer)
3729 Sets the source array \a layer.
3730 */
3731
3732/*!
3733 \fn int QRhiTextureCopyDescription::sourceLevel() const
3734 \return the source mip level. Defaults to 0.
3735 */
3736
3737/*!
3738 \fn void QRhiTextureCopyDescription::setSourceLevel(int level)
3739 Sets the source mip \a level.
3740 */
3741
3742/*!
3743 \fn QPoint QRhiTextureCopyDescription::sourceTopLeft() const
3744 \return the source top-left position (in pixels). Defaults to (0, 0).
3745 */
3746
3747/*!
3748 \fn void QRhiTextureCopyDescription::setSourceTopLeft(const QPoint &p)
3749 Sets the source top-left position to \a p.
3750 */
3751
3752/*!
3753 \fn int QRhiTextureCopyDescription::destinationLayer() const
3754 \return the destination array layer (cubemap face or array layer index). Default to 0.
3755 */
3756
3757/*!
3758 \fn void QRhiTextureCopyDescription::setDestinationLayer(int layer)
3759 Sets the destination array \a layer.
3760 */
3761
3762/*!
3763 \fn int QRhiTextureCopyDescription::destinationLevel() const
3764 \return the destionation mip level. Defaults to 0.
3765 */
3766
3767/*!
3768 \fn void QRhiTextureCopyDescription::setDestinationLevel(int level)
3769 Sets the destination mip \a level.
3770 */
3771
3772/*!
3773 \fn QPoint QRhiTextureCopyDescription::destinationTopLeft() const
3774 \return the destionation top-left position in pixels. Defaults to (0, 0).
3775 */
3776
3777/*!
3778 \fn void QRhiTextureCopyDescription::setDestinationTopLeft(const QPoint &p)
3779 Sets the destination top-left position \a p.
3780 */
3781
3782/*!
3783 \class QRhiReadbackDescription
3784 \inmodule QtGuiPrivate
3785 \inheaderfile rhi/qrhi.h
3786 \since 6.6
3787 \brief Describes a readback (reading back texture contents from possibly GPU-only memory) operation.
3788
3789 The source of the readback operation is either a QRhiTexture or the
3790 current backbuffer of the currently targeted QRhiSwapChain. When
3791 texture() is not set, the swapchain is used. Otherwise the specified
3792 QRhiTexture is treated as the source.
3793
3794 \note Textures used in readbacks must be created with
3795 QRhiTexture::UsedAsTransferSource.
3796
3797 \note Swapchains used in readbacks must be created with
3798 QRhiSwapChain::UsedAsTransferSource.
3799
3800 layer() and level() are only applicable when the source is a QRhiTexture.
3801
3802 \note Multisample textures cannot be read back. Readbacks are supported for
3803 multisample swapchain buffers however.
3804
3805 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
3806 for details.
3807 */
3808
3809/*!
3810 \fn QRhiReadbackDescription::QRhiReadbackDescription() = default
3811
3812 Constructs an empty texture readback description.
3813
3814 \note The source texture is set to null by default, which is still a valid
3815 readback: it specifies that the backbuffer of the current swapchain is to
3816 be read back. (current meaning the frame's target swapchain at the time of
3817 committing the QRhiResourceUpdateBatch with the
3818 \l{QRhiResourceUpdateBatch::readBackTexture()}{texture readback} on it)
3819 */
3820
3821/*!
3822 Constructs an texture readback description that specifies that level 0 of
3823 layer 0 of \a texture is to be read back.
3824
3825 \note \a texture can also be null in which case this constructor is
3826 identical to the argumentless variant.
3827 */
3828QRhiReadbackDescription::QRhiReadbackDescription(QRhiTexture *texture)
3829 : m_texture(texture)
3830{
3831}
3832
3833/*!
3834 \fn QRhiTexture *QRhiReadbackDescription::texture() const
3835
3836 \return the QRhiTexture that is read back. Can be left set to \nullptr
3837 which indicates that the backbuffer of the current swapchain is to be used
3838 instead.
3839 */
3840
3841/*!
3842 \fn void QRhiReadbackDescription::setTexture(QRhiTexture *tex)
3843
3844 Sets the texture \a tex as the source of the readback operation.
3845
3846 Setting \nullptr is valid too, in which case the current swapchain's
3847 current backbuffer is used. (but then the readback cannot be issued in a
3848 non-swapchain-based frame)
3849
3850 \note Multisample textures cannot be read back. Readbacks are supported for
3851 multisample swapchain buffers however.
3852
3853 \note Textures used in readbacks must be created with
3854 QRhiTexture::UsedAsTransferSource.
3855
3856 \note Swapchains used in readbacks must be created with
3857 QRhiSwapChain::UsedAsTransferSource.
3858 */
3859
3860/*!
3861 \fn int QRhiReadbackDescription::layer() const
3862
3863 \return the currently set array layer (cubemap face, array index). Defaults to 0.
3864
3865 Applicable only when the source of the readback is a QRhiTexture.
3866 */
3867
3868/*!
3869 \fn void QRhiReadbackDescription::setLayer(int layer)
3870 Sets the array \a layer to read back.
3871 */
3872
3873/*!
3874 \fn int QRhiReadbackDescription::level() const
3875
3876 \return the currently set mip level. Defaults to 0.
3877
3878 Applicable only when the source of the readback is a QRhiTexture.
3879 */
3880
3881/*!
3882 \fn void QRhiReadbackDescription::setLevel(int level)
3883 Sets the mip \a level to read back.
3884 */
3885
3886/*!
3887 \fn const QRect &QRhiReadbackDescription::rect() const
3888 \since 6.10
3889
3890 \return the rectangle to read back. Defaults to an invalid rectangle.
3891
3892 If invalid, the entire texture or swapchain backbuffer is read back.
3893 */
3894
3895/*!
3896 \fn void QRhiReadbackDescription::setRect(const QRect &rectangle)
3897 \since 6.10
3898
3899 Sets the \a rectangle to read back.
3900 */
3901
3902/*!
3903 \class QRhiReadbackResult
3904 \inmodule QtGuiPrivate
3905 \inheaderfile rhi/qrhi.h
3906 \since 6.6
3907 \brief Describes the results of a potentially asynchronous buffer or texture readback operation.
3908
3909 When \l completed is set, the function is invoked when the \l data is
3910 available. \l format and \l pixelSize are set upon completion together with
3911 \l data.
3912
3913 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
3914 for details.
3915 */
3916
3917/*!
3918 \variable QRhiReadbackResult::completed
3919
3920 Callback that is invoked upon completion, on the thread the QRhi operates
3921 on. Can be left set to \nullptr, in which case no callback is invoked.
3922 */
3923
3924/*!
3925 \variable QRhiReadbackResult::format
3926
3927 Valid only for textures, the texture format.
3928 */
3929
3930/*!
3931 \variable QRhiReadbackResult::pixelSize
3932
3933 Valid only for textures, the size in pixels.
3934 */
3935
3936/*!
3937 \variable QRhiReadbackResult::data
3938
3939 The buffer or image data.
3940
3941 \sa QRhiResourceUpdateBatch::readBackTexture(), QRhiResourceUpdateBatch::readBackBuffer()
3942 */
3943
3944
3945/*!
3946 \class QRhiNativeHandles
3947 \inmodule QtGuiPrivate
3948 \inheaderfile rhi/qrhi.h
3949 \since 6.6
3950 \brief Base class for classes exposing backend-specific collections of native resource objects.
3951
3952 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
3953 for details.
3954 */
3955
3956/*!
3957 \class QRhiResource
3958 \inmodule QtGuiPrivate
3959 \inheaderfile rhi/qrhi.h
3960 \since 6.6
3961 \brief Base class for classes encapsulating native resource objects.
3962
3963 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
3964 for details.
3965 */
3966
3967/*!
3968 \enum QRhiResource::Type
3969 Specifies type of the resource.
3970
3971 \value Buffer
3972 \value Texture
3973 \value Sampler
3974 \value RenderBuffer
3975 \value RenderPassDescriptor
3976 \value SwapChainRenderTarget
3977 \value TextureRenderTarget
3978 \value ShaderResourceBindings
3979 \value GraphicsPipeline
3980 \value SwapChain
3981 \value ComputePipeline
3982 \value CommandBuffer
3983 \value ShadingRateMap
3984 \value [since 6.13] IndirectCommandBuffer
3985 */
3986
3987/*!
3988 \fn virtual QRhiResource::Type QRhiResource::resourceType() const = 0
3989
3990 \return the type of the resource.
3991 */
3992
3993/*!
3994 \internal
3995 */
3996QRhiResource::QRhiResource(QRhiImplementation *rhi)
3997 : m_rhi(rhi)
3998{
3999 m_id = QRhiGlobalObjectIdGenerator::newId();
4000}
4001
4002/*!
4003 Destructor.
4004
4005 Releases (or requests deferred releasing of) the underlying native graphics
4006 resources, if there are any.
4007
4008 \note Resources referenced by commands for the current frame should not be
4009 released until the frame is submitted by QRhi::endFrame().
4010
4011 \sa destroy()
4012 */
4013QRhiResource::~QRhiResource()
4014{
4015 // destroy() cannot be called here, due to virtuals; it is up to the
4016 // subclasses to do that.
4017}
4018
4019/*!
4020 \fn virtual void QRhiResource::destroy() = 0
4021
4022 Releases (or requests deferred releasing of) the underlying native graphics
4023 resources. Safe to call multiple times, subsequent invocations will be a
4024 no-op then.
4025
4026 Once destroy() is called, the QRhiResource instance can be reused, by
4027 calling \c create() again. That will then result in creating new native
4028 graphics resources underneath.
4029
4030 \note Resources referenced by commands for the current frame should not be
4031 released until the frame is submitted by QRhi::endFrame().
4032
4033 The QRhiResource destructor also performs the same task, so calling this
4034 function is not necessary before deleting a QRhiResource.
4035
4036 \sa deleteLater()
4037 */
4038
4039/*!
4040 When called without a frame being recorded, this function is equivalent to
4041 deleting the object. Between a QRhi::beginFrame() and QRhi::endFrame()
4042 however the behavior is different: the QRhiResource will not be destroyed
4043 until the frame is submitted via QRhi::endFrame(), thus satisfying the QRhi
4044 requirement of not altering QRhiResource objects that are referenced by the
4045 frame being recorded.
4046
4047 If the QRhi that created this object is already destroyed, the object is
4048 deleted immediately.
4049
4050 Using deleteLater() can be a useful convenience in many cases, and it
4051 complements the low-level guarantee (that the underlying native graphics
4052 objects are never destroyed until it is safe to do so and it is known for
4053 sure that they are not used by the GPU in an still in-flight frame), by
4054 offering a way to make sure the C++ object instances (of QRhiBuffer,
4055 QRhiTexture, etc.) themselves also stay valid until the end of the current
4056 frame.
4057
4058 The following example shows a convenient way of creating a throwaway buffer
4059 that is only used in one frame and gets automatically released in
4060 endFrame(). (when it comes to the underlying native buffer(s), the usual
4061 guarantee applies: the QRhi backend defers the releasing of those until it
4062 is guaranteed that the frame in which the buffer is accessed by the GPU has
4063 completed)
4064
4065 \code
4066 rhi->beginFrame(swapchain);
4067 QRhiBuffer *buf = rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, 256);
4068 buf->deleteLater(); // !
4069 u = rhi->nextResourceUpdateBatch();
4070 u->uploadStaticBuffer(buf, data);
4071 // ... draw with buf
4072 rhi->endFrame();
4073 \endcode
4074
4075 \sa destroy()
4076 */
4077void QRhiResource::deleteLater()
4078{
4079 if (m_rhi)
4080 m_rhi->addDeleteLater(this);
4081 else
4082 delete this;
4083}
4084
4085/*!
4086 \return the currently set object name. By default the name is empty.
4087 */
4088QByteArray QRhiResource::name() const
4089{
4090 return m_objectName;
4091}
4092
4093/*!
4094 Sets a \a name for the object.
4095
4096 This allows getting descriptive names for the native graphics
4097 resources visible in graphics debugging tools, such as
4098 \l{https://renderdoc.org/}{RenderDoc} and
4099 \l{https://developer.apple.com/xcode/}{XCode}.
4100
4101 When it comes to naming native objects by relaying the name via the
4102 appropriate graphics API, note that the name is ignored when
4103 QRhi::DebugMarkers are not supported, and may, depending on the backend,
4104 also be ignored when QRhi::EnableDebugMarkers is not set.
4105
4106 \note The name may be ignored for objects other than buffers,
4107 renderbuffers, and textures, depending on the backend.
4108
4109 \note The name may be modified. For slotted resources, such as a QRhiBuffer
4110 backed by multiple native buffers, QRhi will append a suffix to make the
4111 underlying native buffers easily distinguishable from each other.
4112 */
4113void QRhiResource::setName(const QByteArray &name)
4114{
4115 m_objectName = name;
4116}
4117
4118/*!
4119 \return the global, unique identifier of this QRhiResource.
4120
4121 User code rarely needs to deal with the value directly. It is used
4122 internally for tracking and bookkeeping purposes.
4123 */
4124quint64 QRhiResource::globalResourceId() const
4125{
4126 return m_id;
4127}
4128
4129/*!
4130 \return the QRhi that created this resource.
4131
4132 If the QRhi that created this object is already destroyed, the result is
4133 \nullptr.
4134 */
4135QRhi *QRhiResource::rhi() const
4136{
4137 return m_rhi ? m_rhi->q : nullptr;
4138}
4139
4140/*!
4141 \class QRhiBuffer
4142 \inmodule QtGuiPrivate
4143 \inheaderfile rhi/qrhi.h
4144 \since 6.6
4145 \brief Vertex, index, or uniform (constant) buffer resource.
4146
4147 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
4148 for details.
4149
4150 A QRhiBuffer encapsulates zero, one, or more native buffer objects (such as
4151 a \c VkBuffer or \c MTLBuffer). With some graphics APIs and backends
4152 certain types of buffers may not use a native buffer object at all (e.g.
4153 OpenGL if uniform buffer objects are not used), but this is transparent to
4154 the user of the QRhiBuffer API. Similarly, the fact that some types of
4155 buffers may use two or three native buffers underneath, in order to allow
4156 efficient per-frame content update without stalling the GPU pipeline, is
4157 mostly invisible to the applications and libraries.
4158
4159 A QRhiBuffer instance is always created by calling
4160 \l{QRhi::newBuffer()}{the QRhi's newBuffer() function}. This creates no
4161 native graphics resources. To do that, call create() after setting the
4162 appropriate options, such as the type, usage flags, size, although in most cases these
4163 are already set based on the arguments passed to
4164 \l{QRhi::newBuffer()}{newBuffer()}.
4165
4166 \section1 Example usage
4167
4168 To create a uniform buffer for a shader where the GLSL uniform block
4169 contains a single \c mat4 member, and update the contents:
4170
4171 \code
4172 QRhiBuffer *ubuf = rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 64);
4173 if (!ubuf->create()) { error(); }
4174 QRhiResourceUpdateBatch *batch = rhi->nextResourceUpdateBatch();
4175 QMatrix4x4 mvp;
4176 // ... set up the modelview-projection matrix
4177 batch->updateDynamicBuffer(ubuf, 0, 64, mvp.constData());
4178 // ...
4179 commandBuffer->resourceUpdate(batch); // or, alternatively, pass 'batch' to a beginPass() call
4180 \endcode
4181
4182 An example of creating a buffer with vertex data:
4183
4184 \code
4185 const float vertices[] = { -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 1.0f };
4186 QRhiBuffer *vbuf = rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertices));
4187 if (!vbuf->create()) { error(); }
4188 QRhiResourceUpdateBatch *batch = rhi->nextResourceUpdateBatch();
4189 batch->uploadStaticBuffer(vbuf, vertices);
4190 // ...
4191 commandBuffer->resourceUpdate(batch); // or, alternatively, pass 'batch' to a beginPass() call
4192 \endcode
4193
4194 An index buffer:
4195
4196 \code
4197 static const quint16 indices[] = { 0, 1, 2 };
4198 QRhiBuffer *ibuf = rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::IndexBuffer, sizeof(indices));
4199 if (!ibuf->create()) { error(); }
4200 QRhiResourceUpdateBatch *batch = rhi->nextResourceUpdateBatch();
4201 batch->uploadStaticBuffer(ibuf, indices);
4202 // ...
4203 commandBuffer->resourceUpdate(batch); // or, alternatively, pass 'batch' to a beginPass() call
4204 \endcode
4205
4206 \section1 Common patterns
4207
4208 A call to create() destroys any existing native resources if create() was
4209 successfully called before. If those native resources are still in use by
4210 an in-flight frame (i.e., there's a chance they are still read by the GPU),
4211 the destroying of those resources is deferred automatically. Thus a very
4212 common and convenient pattern to safely increase the size of an already
4213 initialized buffer is the following. In practice this drops and creates a
4214 whole new set of native resources underneath, so it is not necessarily a
4215 cheap operation, but is more convenient and still faster than the
4216 alternatives, because by not destroying the \c buf object itself, all
4217 references to it stay valid in other data structures (e.g., in any
4218 QRhiShaderResourceBinding the QRhiBuffer is referenced from).
4219
4220 \code
4221 if (buf->size() < newSize) {
4222 buf->setSize(newSize);
4223 if (!buf->create()) { error(); }
4224 }
4225 // continue using buf, fill it with new data
4226 \endcode
4227
4228 When working with uniform buffers, it will sometimes be necessary to
4229 combine data for multiple draw calls into a single buffer for efficiency
4230 reasons. Be aware of the aligment requirements: with some graphics APIs
4231 offsets for a uniform buffer must be aligned to 256 bytes. This applies
4232 both to QRhiShaderResourceBinding and to the dynamic offsets passed to
4233 \l{QRhiCommandBuffer::setShaderResources()}{setShaderResources()}. Use the
4234 \l{QRhi::ubufAlignment()}{ubufAlignment()} and
4235 \l{QRhi::ubufAligned()}{ubufAligned()} functions to create portable code.
4236 As an example, the following is an outline for issuing multiple (\c N) draw
4237 calls with the same pipeline and geometry, but with a different data in the
4238 uniform buffers exposed at binding point 0. This assumes the buffer is
4239 exposed via
4240 \l{QRhiShaderResourceBinding::uniformBufferWithDynamicOffset()}{uniformBufferWithDynamicOffset()}
4241 which allows passing a QRhiCommandBuffer::DynamicOffset list to
4242 \l{QRhiCommandBuffer::setShaderResources()}{setShaderResources()}.
4243
4244 \code
4245 const int N = 2;
4246 const int UB_SIZE = 64 + 4; // assuming a uniform block with { mat4 matrix; float opacity; }
4247 const int ONE_UBUF_SIZE = rhi->ubufAligned(UB_SIZE);
4248 const int TOTAL_UBUF_SIZE = N * ONE_UBUF_SIZE;
4249 QRhiBuffer *ubuf = rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, TOTAL_UBUF_SIZE);
4250 if (!ubuf->create()) { error(); }
4251 QRhiResourceUpdateBatch *batch = rhi->nextResourceUpdateBatch();
4252 for (int i = 0; i < N; ++i) {
4253 batch->updateDynamicBuffer(ubuf, i * ONE_UBUF_SIZE, 64, matrix.constData());
4254 batch->updateDynamicBuffer(ubuf, i * ONE_UBUF_SIZE + 64, 4, &opacity);
4255 }
4256 // ...
4257 // beginPass(), set pipeline, etc., and then:
4258 for (int i = 0; i < N; ++i) {
4259 QRhiCommandBuffer::DynamicOffset dynOfs[] = { { 0, i * ONE_UBUF_SIZE } };
4260 cb->setShaderResources(srb, 1, dynOfs);
4261 cb->draw(36);
4262 }
4263 \endcode
4264
4265 \sa QRhiResourceUpdateBatch, QRhi, QRhiCommandBuffer
4266 */
4267
4268/*!
4269 \enum QRhiBuffer::Type
4270 Specifies storage type of buffer resource.
4271
4272 \value Immutable Indicates that the data is not expected to change ever
4273 after the initial upload. Under the hood such buffer resources are
4274 typically placed in device local (GPU) memory (on systems where
4275 applicable). Uploading new data is possible, but may be expensive. The
4276 upload typically happens by copying to a separate, host visible staging
4277 buffer from which a GPU buffer-to-buffer copy is issued into the actual
4278 GPU-only buffer.
4279
4280 \value Static Indicates that the data is expected to change only
4281 infrequently. Typically placed in device local (GPU) memory, where
4282 applicable. On backends where host visible staging buffers are used for
4283 uploading, the staging buffers are kept around for this type, unlike with
4284 Immutable, so subsequent uploads do not suffer in performance. Frequent
4285 updates, especially updates in consecutive frames, should be avoided.
4286
4287 \value Dynamic Indicates that the data is expected to change frequently.
4288 Not recommended for large buffers. Typically backed by host visible memory
4289 in 2 copies in order to allow for changing without stalling the graphics
4290 pipeline. The double buffering is managed transparently to the applications
4291 and is not exposed in the API here in any form. This is the recommended,
4292 and, with some backends, the only possible, type for buffers with
4293 UniformBuffer usage.
4294 */
4295
4296/*!
4297 \enum QRhiBuffer::UsageFlag
4298 Flag values to specify how the buffer is going to be used.
4299
4300 \value VertexBuffer Vertex buffer. This allows the QRhiBuffer to be used in
4301 \l{QRhiCommandBuffer::setVertexInput()}{setVertexInput()}.
4302
4303 \value IndexBuffer Index buffer. This allows the QRhiBuffer to be used in
4304 \l{QRhiCommandBuffer::setVertexInput()}{setVertexInput()}.
4305
4306 \value UniformBuffer Uniform buffer (also called constant buffer). This
4307 allows the QRhiBuffer to be used in combination with
4308 \l{QRhiShaderResourceBinding::UniformBuffer}{UniformBuffer}. When
4309 \l{QRhi::NonDynamicUniformBuffers}{NonDynamicUniformBuffers} is reported as
4310 not supported, this usage can only be combined with the type Dynamic.
4311
4312 \value StorageBuffer Storage buffer. This allows the QRhiBuffer to be used
4313 in combination with \l{QRhiShaderResourceBinding::BufferLoad}{BufferLoad},
4314 \l{QRhiShaderResourceBinding::BufferStore}{BufferStore}, or
4315 \l{QRhiShaderResourceBinding::BufferLoadStore}{BufferLoadStore}. This usage
4316 can only be combined with the types Immutable or Static, and is only
4317 available when the \l{QRhi::Compute}{Compute feature} is reported as
4318 supported.
4319
4320 \value [since 6.12] IndirectBuffer Indirect draw or dispatch buffer. This
4321 allows the QRhiBuffer to be used in
4322 \l{QRhiCommandBuffer::drawIndirect()}{drawIndirect()},
4323 \l{QRhiCommandBuffer::drawIndexedIndirect()}{drawIndexedIndirect()}, and
4324 \l{QRhiCommandBuffer::dispatchIndirect()}{dispatchIndirect()}.
4325 This usage can be combined with types Immutable or Static. Combining it with
4326 Dynamic is unsupported with D3D11, where create() will fail. This usage may
4327 also be combined with StorageBuffer on backends that support
4328 \l{QRhi::Compute}{compute shaders}, allowing indirect draw or dispatch
4329 commands to be generated by compute shaders and consumed by indirect
4330 draw/dispatch calls.
4331 */
4332
4333/*!
4334 \class QRhiBuffer::NativeBuffer
4335 \inmodule QtGuiPrivate
4336 \inheaderfile rhi/qrhi.h
4337 \brief Contains information about the underlying native resources of a buffer.
4338 */
4339
4340/*!
4341 \variable QRhiBuffer::NativeBuffer::objects
4342 \brief an array with pointers to the native object handles.
4343
4344 With OpenGL, the native handle is a GLuint value, so the elements in the \c
4345 objects array are pointers to a GLuint. With Vulkan, the native handle is a
4346 VkBuffer, so the elements of the array are pointers to a VkBuffer. With
4347 Direct3D 11 and Metal the elements are pointers to a ID3D11Buffer or
4348 MTLBuffer pointer, respectively. With Direct3D 12, the elements are
4349 pointers to a ID3D12Resource.
4350
4351 \note Pay attention to the fact that the elements are always pointers to
4352 the native buffer handle type, even if the native type itself is a pointer.
4353 (so the elements are \c{VkBuffer *} on Vulkan, even though VkBuffer itself
4354 is a pointer on 64-bit architectures).
4355 */
4356
4357/*!
4358 \variable QRhiBuffer::NativeBuffer::slotCount
4359 \brief Specifies the number of valid elements in the objects array.
4360
4361 The value can be 0, 1, 2, or 3 in practice. 0 indicates that the QRhiBuffer
4362 is not backed by any native buffer objects. This can happen with
4363 QRhiBuffers with the usage UniformBuffer when the underlying API does not
4364 support (or the backend chooses not to use) native uniform buffers. 1 is
4365 commonly used for Immutable and Static types (but some backends may
4366 differ). 2 or 3 is typical when the type is Dynamic (but some backends may
4367 differ).
4368
4369 \sa QRhi::currentFrameSlot(), QRhi::FramesInFlight
4370 */
4371
4372/*!
4373 \internal
4374 */
4375QRhiBuffer::QRhiBuffer(QRhiImplementation *rhi, Type type_, UsageFlags usage_, quint32 size_)
4376 : QRhiResource(rhi),
4377 m_type(type_), m_usage(usage_), m_size(size_)
4378{
4379}
4380
4381/*!
4382 \return the resource type.
4383 */
4384QRhiResource::Type QRhiBuffer::resourceType() const
4385{
4386 return Buffer;
4387}
4388
4389/*!
4390 \fn virtual bool QRhiBuffer::create() = 0
4391
4392 Creates the corresponding native graphics resources. If there are already
4393 resources present due to an earlier create() with no corresponding
4394 destroy(), then destroy() is called implicitly first.
4395
4396 \return \c true when successful, \c false when a graphics operation failed.
4397 Regardless of the return value, calling destroy() is always safe.
4398 */
4399
4400/*!
4401 \fn QRhiBuffer::Type QRhiBuffer::type() const
4402 \return the buffer type.
4403 */
4404
4405/*!
4406 \fn void QRhiBuffer::setType(Type t)
4407 Sets the buffer's type to \a t.
4408 */
4409
4410/*!
4411 \fn QRhiBuffer::UsageFlags QRhiBuffer::usage() const
4412 \return the buffer's usage flags.
4413 */
4414
4415/*!
4416 \fn void QRhiBuffer::setUsage(UsageFlags u)
4417 Sets the buffer's usage flags to \a u.
4418 */
4419
4420/*!
4421 \fn quint32 QRhiBuffer::size() const
4422
4423 \return the buffer's size in bytes.
4424
4425 This is always the value that was passed to setSize() or QRhi::newBuffer().
4426 Internally, the native buffers may be bigger if that is required by the
4427 underlying graphics API.
4428 */
4429
4430/*!
4431 \fn void QRhiBuffer::setSize(quint32 sz)
4432
4433 Sets the size of the buffer in bytes. The size is normally specified in
4434 QRhi::newBuffer() so this function is only used when the size has to be
4435 changed. As with other setters, the size only takes effect when calling
4436 create(), and for already created buffers this involves releasing the previous
4437 native resource and creating new ones under the hood.
4438
4439 Backends may choose to allocate buffers bigger than \a sz in order to
4440 fulfill alignment requirements. This is hidden from the applications and
4441 size() will always report the size requested in \a sz.
4442 */
4443
4444/*!
4445 \return the underlying native resources for this buffer. The returned value
4446 will be empty if exposing the underlying native resources is not supported by
4447 the backend.
4448
4449 A QRhiBuffer may be backed by multiple native buffer objects, depending on
4450 the type() and the QRhi backend in use. When this is the case, all of them
4451 are returned in the objects array in the returned struct, with slotCount
4452 specifying the number of native buffer objects. While
4453 \l{QRhi::beginFrame()}{recording a frame}, QRhi::currentFrameSlot() can be
4454 used to determine which of the native buffers QRhi is using for operations
4455 that read or write from this QRhiBuffer within the frame being recorded.
4456
4457 In some cases a QRhiBuffer will not be backed by a native buffer object at
4458 all. In this case slotCount will be set to 0 and no valid native objects
4459 are returned. This is not an error, and is perfectly valid when a given
4460 backend does not use native buffers for QRhiBuffers with certain types or
4461 usages.
4462
4463 \note Be aware that QRhi backends may employ various buffer update
4464 strategies. Unlike textures, where uploading image data always means
4465 recording a buffer-to-image (or similar) copy command on the command
4466 buffer, buffers, in particular Dynamic and UniformBuffer ones, can operate
4467 in many different ways. For example, a QRhiBuffer with usage type
4468 UniformBuffer may not even be backed by a native buffer object at all if
4469 uniform buffers are not used or supported by a given backend and graphics
4470 API. There are also differences to how data is written to the buffer and
4471 the type of backing memory used. For buffers backed by host visible memory,
4472 calling this function guarantees that pending host writes are executed for
4473 all the returned native buffers.
4474
4475 \sa QRhi::currentFrameSlot(), QRhi::FramesInFlight
4476 */
4477QRhiBuffer::NativeBuffer QRhiBuffer::nativeBuffer()
4478{
4479 return { {}, 0 };
4480}
4481
4482/*!
4483 \return a pointer to a memory block with the host visible buffer data.
4484
4485 This is a shortcut for medium-to-large dynamic uniform buffers that have
4486 their \b entire contents (or at least all regions that are read by the
4487 shaders in the current frame) changed \b{in every frame} and the
4488 QRhiResourceUpdateBatch-based update mechanism is seen too heavy due to the
4489 amount of data copying involved.
4490
4491 The call to this function must be eventually followed by a call to
4492 endFullDynamicUniformBufferUpdateForCurrentFrame(), before recording any
4493 render or compute pass that relies on this buffer.
4494
4495 \warning Updating data via this method is not compatible with
4496 QRhiResourceUpdateBatch-based updates and readbacks. Unexpected behavior
4497 may occur when attempting to combine the two update models for the same
4498 buffer. Similarly, the data updated this direct way may not be visible to
4499 \l{QRhiResourceUpdateBatch::readBackBuffer()}{readBackBuffer operations},
4500 depending on the backend.
4501
4502 \warning When updating buffer data via this method, the update must be done
4503 in every frame, otherwise backends that perform double or triple buffering
4504 of resources may end up in unexpected behavior.
4505
4506 \warning Partial updates are not possible with this approach since some
4507 backends may choose a strategy where the previous contents of the buffer is
4508 lost upon calling this function. Data must be written to all regions that
4509 are read by shaders in the frame currently being prepared.
4510
4511 \warning This function can only be called when recording a frame, so
4512 between QRhi::beginFrame() and QRhi::endFrame().
4513
4514 \warning This function can only be called on Dynamic buffers.
4515 */
4516char *QRhiBuffer::beginFullDynamicBufferUpdateForCurrentFrame()
4517{
4518 return nullptr;
4519}
4520
4521/*!
4522 To be called when the entire contents of the buffer data has been updated
4523 in the memory block returned from
4524 beginFullDynamicBufferUpdateForCurrentFrame().
4525 */
4526void QRhiBuffer::endFullDynamicBufferUpdateForCurrentFrame()
4527{
4528}
4529
4530/*!
4531 \internal
4532 */
4533void QRhiBuffer::fullDynamicBufferUpdateForCurrentFrame(const void *data, quint32 size)
4534{
4535 char *p = beginFullDynamicBufferUpdateForCurrentFrame();
4536 if (p) {
4537 memcpy(p, data, size > 0 ? size : m_size);
4538 endFullDynamicBufferUpdateForCurrentFrame();
4539 }
4540}
4541
4542/*!
4543 \class QRhiRenderBuffer
4544 \inmodule QtGuiPrivate
4545 \inheaderfile rhi/qrhi.h
4546 \since 6.6
4547 \brief Renderbuffer resource.
4548
4549 Renderbuffers cannot be sampled or read but have some benefits over
4550 textures in some cases:
4551
4552 A \l DepthStencil renderbuffer may be lazily allocated and be backed by
4553 transient memory with some APIs. On some platforms this may mean the
4554 depth/stencil buffer uses no physical backing at all.
4555
4556 That transient nature has a consequence: the contents of a \l DepthStencil
4557 renderbuffer are not guaranteed to survive if a backend has to interrupt and
4558 restart a render pass internally. With Metal this happens when a draw call
4559 is implemented via indirect command buffers, which is the case for
4560 \l{QRhiCommandBuffer::drawIndirectCount()}{drawIndirectCount()} and its
4561 indexed variant, for a high draw count
4562 \l{QRhiCommandBuffer::drawIndirect()}{drawIndirect()} or
4563 \l{QRhiCommandBuffer::drawIndexedIndirect()}{drawIndexedIndirect()}, and
4564 also when tessellation is used. Draws recorded after such a call then
4565 depth-test against a depth buffer that lost its contents. When this matters,
4566 set the \l NoTransientBacking flag, which makes the contents preservable at
4567 the cost of the memory and bandwidth that the transient backing was saving.
4568 Alternatively, where a QRhiTextureRenderTarget is used anyway, attach a depth
4569 or depth-stencil QRhiTexture with
4570 \l{QRhiTextureRenderTargetDescription::setDepthTexture()}{setDepthTexture()}
4571 instead of a renderbuffer: that is preserved across an interruption, unless
4572 QRhiTextureRenderTarget::DoNotStoreDepthStencilContents is set.
4573
4574 Note that the indirect drawing cases above are avoidable. A
4575 QRhiIndirectCommandBuffer executed with
4576 \l{QRhiCommandBuffer::executeIndirect()}{executeIndirect()} is prepared
4577 before the render pass begins, so it never interrupts the pass however many
4578 commands it holds, and none of this applies to it. Only tessellation then
4579 remains as a reason to consider \l NoTransientBacking.
4580
4581 \l Color renderbuffers are useful since QRhi::MultisampleRenderBuffer may be
4582 supported even when QRhi::MultisampleTexture is not.
4583
4584 How the renderbuffer is implemented by a backend is not exposed to the
4585 applications. In some cases it may be backed by ordinary textures, while in
4586 others there may be a different kind of native resource used.
4587
4588 Renderbuffers that are used as (and are only used as) depth-stencil buffers
4589 in combination with a QRhiSwapChain's color buffers should have the
4590 UsedWithSwapChainOnly flag set. This serves a double purpose: such buffers,
4591 depending on the backend and the underlying APIs, be more efficient, and
4592 QRhi provides automatic sizing behavior to match the color buffers, which
4593 means calling setPixelSize() and create() are not necessary for such
4594 renderbuffers.
4595
4596 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
4597 for details.
4598 */
4599
4600/*!
4601 \enum QRhiRenderBuffer::Type
4602 Specifies the type of the renderbuffer
4603
4604 \value DepthStencil Combined depth/stencil
4605 \value Color Color
4606 */
4607
4608/*!
4609 \struct QRhiRenderBuffer::NativeRenderBuffer
4610 \inmodule QtGuiPrivate
4611 \inheaderfile rhi/qrhi.h
4612 \brief Wraps a native renderbuffer object.
4613 */
4614
4615/*!
4616 \variable QRhiRenderBuffer::NativeRenderBuffer::object
4617 \brief 64-bit integer containing the native object handle.
4618
4619 Used with QRhiRenderBuffer::createFrom().
4620
4621 With OpenGL the native handle is a GLuint value. \c object is expected to
4622 be a valid OpenGL renderbuffer object ID.
4623 */
4624
4625/*!
4626 \enum QRhiRenderBuffer::Flag
4627 Flag values for flags() and setFlags()
4628
4629 \value UsedWithSwapChainOnly For DepthStencil renderbuffers this indicates
4630 that the renderbuffer is only used in combination with a QRhiSwapChain, and
4631 never in any other way. This provides automatic sizing and resource
4632 rebuilding, so calling setPixelSize() or create() is not needed whenever
4633 this flag is set. This flag value may also trigger backend-specific
4634 behavior, for example with OpenGL, where a separate windowing system
4635 interface API is in use (EGL, GLX, etc.), the flag is especially important
4636 as it avoids creating any actual renderbuffer resource as there is already
4637 a windowing system provided depth/stencil buffer as requested by
4638 QSurfaceFormat.
4639
4640 \value [since 6.13] NoTransientBacking Requests that the renderbuffer is not
4641 backed by transient, lazily allocated memory. Only relevant for
4642 \l DepthStencil renderbuffers, and only with backends that would otherwise
4643 choose such storage, which in practice means Metal on Apple GPUs. Set this
4644 when the contents have to survive a render pass being interrupted and
4645 continued internally by a backend, as described in the
4646 \l{QRhiRenderBuffer}{class documentation}. It costs actual memory and
4647 bandwidth for the depth/stencil buffer, so do not set it when not needed.
4648 In particular it is not needed on account of
4649 \l{QRhiCommandBuffer::executeIndirect()}{executeIndirect()}, which never
4650 interrupts the pass.
4651 */
4652
4653/*!
4654 \internal
4655 */
4656QRhiRenderBuffer::QRhiRenderBuffer(QRhiImplementation *rhi, Type type_, const QSize &pixelSize_,
4657 int sampleCount_, Flags flags_,
4658 QRhiTexture::Format backingFormatHint_)
4659 : QRhiResource(rhi),
4660 m_type(type_), m_pixelSize(pixelSize_), m_sampleCount(sampleCount_), m_flags(flags_),
4661 m_backingFormatHint(backingFormatHint_)
4662{
4663}
4664
4665/*!
4666 \return the resource type.
4667 */
4668QRhiResource::Type QRhiRenderBuffer::resourceType() const
4669{
4670 return RenderBuffer;
4671}
4672
4673/*!
4674 \fn virtual bool QRhiRenderBuffer::create() = 0
4675
4676 Creates the corresponding native graphics resources. If there are already
4677 resources present due to an earlier create() with no corresponding
4678 destroy(), then destroy() is called implicitly first.
4679
4680 \return \c true when successful, \c false when a graphics operation failed.
4681 Regardless of the return value, calling destroy() is always safe.
4682 */
4683
4684/*!
4685 Similar to create() except that no new native renderbuffer objects are
4686 created. Instead, the native renderbuffer object specified by \a src is
4687 used.
4688
4689 This allows importing an existing renderbuffer object (which must belong to
4690 the same device or sharing context, depending on the graphics API) from an
4691 external graphics engine.
4692
4693 \note This is currently applicable to OpenGL only. This function exists
4694 solely to allow importing a renderbuffer object that is bound to some
4695 special, external object, such as an EGLImageKHR. Once the application
4696 performed the glEGLImageTargetRenderbufferStorageOES call, the renderbuffer
4697 object can be passed to this function to create a wrapping
4698 QRhiRenderBuffer, which in turn can be passed in as a color attachment to
4699 a QRhiTextureRenderTarget to enable rendering to the EGLImage.
4700
4701 \note pixelSize(), sampleCount(), and flags() must still be set correctly.
4702 Passing incorrect sizes and other values to QRhi::newRenderBuffer() and
4703 then following it with a createFrom() expecting that the native
4704 renderbuffer object alone is sufficient to deduce such values is \b wrong
4705 and will lead to problems.
4706
4707 \note QRhiRenderBuffer does not take ownership of the native object, and
4708 destroy() will not release that object.
4709
4710 \note This function is only implemented when the QRhi::RenderBufferImport
4711 feature is reported as \l{QRhi::isFeatureSupported()}{supported}. Otherwise,
4712 the function does nothing and the return value is \c false.
4713
4714 \return \c true when successful, \c false when not supported.
4715 */
4716bool QRhiRenderBuffer::createFrom(NativeRenderBuffer src)
4717{
4718 Q_UNUSED(src);
4719 return false;
4720}
4721
4722/*!
4723 \fn QRhiRenderBuffer::Type QRhiRenderBuffer::type() const
4724 \return the renderbuffer type.
4725 */
4726
4727/*!
4728 \fn void QRhiRenderBuffer::setType(Type t)
4729 Sets the type to \a t.
4730 */
4731
4732/*!
4733 \fn QSize QRhiRenderBuffer::pixelSize() const
4734 \return the pixel size.
4735 */
4736
4737/*!
4738 \fn void QRhiRenderBuffer::setPixelSize(const QSize &sz)
4739 Sets the size (in pixels) to \a sz.
4740 */
4741
4742/*!
4743 \fn int QRhiRenderBuffer::sampleCount() const
4744 \return the sample count. 1 means no multisample antialiasing.
4745 */
4746
4747/*!
4748 \fn void QRhiRenderBuffer::setSampleCount(int s)
4749 Sets the sample count to \a s.
4750 */
4751
4752/*!
4753 \fn QRhiRenderBuffer::Flags QRhiRenderBuffer::flags() const
4754 \return the flags.
4755 */
4756
4757/*!
4758 \fn void QRhiRenderBuffer::setFlags(Flags f)
4759 Sets the flags to \a f.
4760 */
4761
4762/*!
4763 \fn virtual QRhiTexture::Format QRhiRenderBuffer::backingFormat() const = 0
4764
4765 \internal
4766 */
4767
4768/*!
4769 \class QRhiTexture
4770 \inmodule QtGuiPrivate
4771 \inheaderfile rhi/qrhi.h
4772 \since 6.6
4773 \brief Texture resource.
4774
4775 A QRhiTexture encapsulates a native texture object, such as a \c VkImage or
4776 \c MTLTexture.
4777
4778 A QRhiTexture instance is always created by calling
4779 \l{QRhi::newTexture()}{the QRhi's newTexture() function}. This creates no
4780 native graphics resources. To do that, call create() after setting the
4781 appropriate options, such as the format and size, although in most cases
4782 these are already set based on the arguments passed to
4783 \l{QRhi::newTexture()}{newTexture()}.
4784
4785 Setting the \l{QRhiTexture::Flags}{flags} correctly is essential, otherwise
4786 various errors can occur depending on the underlying QRhi backend and
4787 graphics API. For example, when a texture will be rendered into from a
4788 render pass via QRhiTextureRenderTarget, the texture must be created with
4789 the \l RenderTarget flag set. Similarly, when the texture is going to be
4790 \l{QRhiResourceUpdateBatch::readBackTexture()}{read back}, the \l
4791 UsedAsTransferSource flag must be set upfront. Mipmapped textures must have
4792 the MipMapped flag set. And so on. It is not possible to change the flags
4793 once create() has succeeded. To release the existing and create a new
4794 native texture object with the changed settings, call the setters and call
4795 create() again. This then might be a potentially expensive operation.
4796
4797 \section1 Example usage
4798
4799 To create a 2D texture with a size of 512x512 pixels and set its contents to all green:
4800
4801 \code
4802 QRhiTexture *texture = rhi->newTexture(QRhiTexture::RGBA8, QSize(512, 512));
4803 if (!texture->create()) { error(); }
4804 QRhiResourceUpdateBatch *batch = rhi->nextResourceUpdateBatch();
4805 QImage image(512, 512, QImage::Format_RGBA8888);
4806 image.fill(Qt::green);
4807 batch->uploadTexture(texture, image);
4808 // ...
4809 commandBuffer->resourceUpdate(batch); // or, alternatively, pass 'batch' to a beginPass() call
4810 \endcode
4811
4812 \section1 Common patterns
4813
4814 A call to create() destroys any existing native resources if create() was
4815 successfully called before. If those native resources are still in use by
4816 an in-flight frame (i.e., there's a chance they are still read by the GPU),
4817 the destroying of those resources is deferred automatically. Thus a very
4818 common and convenient pattern to safely change the size of an already
4819 existing texture is the following. In practice this drops and creates a
4820 whole new native texture resource underneath, so it is not necessarily a
4821 cheap operation, but is more convenient and still faster than the
4822 alternatives, because by not destroying the \c texture object itself, all
4823 references to it stay valid in other data structures (e.g., in any
4824 QShaderResourceBinding the QRhiTexture is referenced from).
4825
4826 \code
4827 // determine newSize, e.g. based on the swapchain's output size or other factors
4828 if (texture->pixelSize() != newSize) {
4829 texture->setPixelSize(newSize);
4830 if (!texture->create()) { error(); }
4831 }
4832 // continue using texture, fill it with new data
4833 \endcode
4834
4835 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
4836 for details.
4837
4838 \sa QRhiResourceUpdateBatch, QRhi, QRhiTextureRenderTarget
4839 */
4840
4841/*!
4842 \enum QRhiTexture::Flag
4843
4844 Flag values to specify how the texture is going to be used. Not honoring
4845 the flags set before create() and attempting to use the texture in ways that
4846 was not declared upfront can lead to unspecified behavior or decreased
4847 performance depending on the backend and the underlying graphics API.
4848
4849 \value RenderTarget The texture going to be used in combination with
4850 QRhiTextureRenderTarget.
4851
4852 \value CubeMap The texture is a cubemap. Such textures have 6 layers, one
4853 for each face in the order of +X, -X, +Y, -Y, +Z, -Z. Cubemap textures
4854 cannot be multisample.
4855
4856 \value MipMapped The texture has mipmaps. The appropriate mip count is
4857 calculated automatically and can also be retrieved via
4858 QRhi::mipLevelsForSize(). The images for the mip levels have to be
4859 provided in the texture uploaded or generated via
4860 QRhiResourceUpdateBatch::generateMips(). Multisample textures cannot have
4861 mipmaps.
4862
4863 \value sRGB Use an sRGB format.
4864
4865 \value UsedAsTransferSource The texture is used as the source of a texture
4866 copy or readback, meaning the texture is given as the source in
4867 QRhiResourceUpdateBatch::copyTexture() or
4868 QRhiResourceUpdateBatch::readBackTexture().
4869
4870 \value UsedWithGenerateMips The texture is going to be used with
4871 QRhiResourceUpdateBatch::generateMips().
4872
4873 \value UsedWithLoadStore The texture is going to be used with image
4874 load/store operations, for example, in a compute shader.
4875
4876 \value UsedAsCompressedAtlas This value has no effect since Qt 6.13.
4877 Textures that have a compressed format and the dimensions of subresource
4878 uploads do not match the texture size are handled automatically now.
4879
4880 \value ExternalOES The texture should use the GL_TEXTURE_EXTERNAL_OES
4881 target with OpenGL. This flag is ignored with other graphics APIs.
4882
4883 \value ThreeDimensional The texture is a 3D texture. Such textures should
4884 be created with the QRhi::newTexture() overload taking a depth in addition
4885 to width and height. A 3D texture can have mipmaps but cannot be
4886 multisample. When rendering into, or uploading data to a 3D texture, the \c
4887 layer specified in the render target's color attachment or the upload
4888 description refers to a single slice in range [0..depth-1]. The underlying
4889 graphics API may not support 3D textures at run time. Support is indicated
4890 by the QRhi::ThreeDimensionalTextures feature.
4891
4892 \value TextureRectangleGL The texture should use the GL_TEXTURE_RECTANGLE
4893 target with OpenGL. This flag is ignored with other graphics APIs. Just
4894 like ExternalOES, this flag is useful when working with platform APIs where
4895 native OpenGL texture objects received from the platform are wrapped in a
4896 QRhiTexture, and the platform can only provide textures for a non-2D
4897 texture target.
4898
4899 \value TextureArray The texture is a texture array, i.e. a single texture
4900 object that is a homogeneous array of 2D textures. Texture arrays are
4901 created with QRhi::newTextureArray(). The underlying graphics API may not
4902 support texture array objects at run time. Support is indicated by the
4903 QRhi::TextureArrays feature. When rendering into, or uploading data to a
4904 texture array, the \c layer specified in the render target's color
4905 attachment or the upload description selects a single element in the array.
4906
4907 \value OneDimensional The texture is a 1D texture. Such textures can be
4908 created by passing a 0 height and depth to QRhi::newTexture(). Note that
4909 there can be limitations on one dimensional textures depending on the
4910 underlying graphics API. For example, rendering to them or using them with
4911 mipmap-based filtering may be unsupported. This is indicated by the
4912 QRhi::OneDimensionalTextures and QRhi::OneDimensionalTextureMipmaps
4913 feature flags.
4914
4915 \value UsedAsShadingRateMap
4916 */
4917
4918/*!
4919 \enum QRhiTexture::Format
4920
4921 Specifies the texture format. See also QRhi::isTextureFormatSupported() and
4922 note that flags() can modify the format when QRhiTexture::sRGB is set.
4923
4924 \value UnknownFormat Not a valid format. This cannot be passed to setFormat().
4925
4926 \value RGBA8 Four components, unsigned normalized 8-bit per component. Always supported. (32 bits total)
4927
4928 \value BGRA8 Four components, unsigned normalized 8-bit per component. (32 bits total)
4929
4930 \value R8 One component, unsigned normalized 8-bit. (8 bits total)
4931
4932 \value RG8 Two components, unsigned normalized 8-bit. (16 bits total)
4933
4934 \value R16 One component, unsigned normalized 16-bit. (16 bits total)
4935
4936 \value RG16 Two components, unsigned normalized 16-bit. (32 bits total)
4937
4938 \value RED_OR_ALPHA8 Either same as R8, or is a similar format with the component swizzled to alpha,
4939 depending on \l{QRhi::RedOrAlpha8IsRed}{RedOrAlpha8IsRed}. (8 bits total)
4940
4941 \value RGBA16F Four components, 16-bit float. (64 bits total)
4942
4943 \value RGBA32F Four components, 32-bit float. (128 bits total)
4944
4945 \value R16F One component, 16-bit float. (16 bits total)
4946
4947 \value R32F One component, 32-bit float. (32 bits total)
4948
4949 \value RGB10A2 Four components, unsigned normalized 10 bit R, G, and B,
4950 2-bit alpha. This is a packed format so native endianness applies. Note
4951 that there is no BGR10A2. This is because RGB10A2 maps to
4952 DXGI_FORMAT_R10G10B10A2_UNORM with D3D, MTLPixelFormatRGB10A2Unorm with
4953 Metal, VK_FORMAT_A2B10G10R10_UNORM_PACK32 with Vulkan, and
4954 GL_RGB10_A2/GL_RGB/GL_UNSIGNED_INT_2_10_10_10_REV on OpenGL (ES). This is
4955 the only universally supported RGB30 option. The corresponding QImage
4956 formats are QImage::Format_BGR30 and QImage::Format_A2BGR30_Premultiplied.
4957 (32 bits total)
4958
4959 \value D16 16-bit depth (normalized unsigned integer)
4960
4961 \value D24 24-bit depth (normalized unsigned integer)
4962
4963 \value D24S8 24-bit depth (normalized unsigned integer), 8 bit stencil
4964
4965 \value D32F 32-bit depth (32-bit float)
4966
4967 \value [since 6.9] D32FS8 32-bit depth (32-bit float), 8 bits of stencil, 24 bits unused
4968 (64 bits total)
4969
4970 \value BC1
4971 \value BC2
4972 \value BC3
4973 \value BC4
4974 \value BC5
4975 \value BC6H
4976 \value BC7
4977
4978 \value ETC2_RGB8
4979 \value ETC2_RGB8A1
4980 \value ETC2_RGBA8
4981
4982 \value ASTC_4x4
4983 \value ASTC_5x4
4984 \value ASTC_5x5
4985 \value ASTC_6x5
4986 \value ASTC_6x6
4987 \value ASTC_8x5
4988 \value ASTC_8x6
4989 \value ASTC_8x8
4990 \value ASTC_10x5
4991 \value ASTC_10x6
4992 \value ASTC_10x8
4993 \value ASTC_10x10
4994 \value ASTC_12x10
4995 \value ASTC_12x12
4996
4997 \value [since 6.9] R8UI One component, unsigned 8-bit. (8 bits total)
4998 \value [since 6.9] R32UI One component, unsigned 32-bit. (32 bits total)
4999 \value [since 6.9] RG32UI Two components, unsigned 32-bit. (64 bits total)
5000 \value [since 6.9] RGBA32UI Four components, unsigned 32-bit. (128 bits total)
5001
5002 \value [since 6.10] R8SI One component, signed 8-bit. (8 bits total)
5003 \value [since 6.10] R32SI One component, signed 32-bit. (32 bits total)
5004 \value [since 6.10] RG32SI Two components, signed 32-bit. (64 bits total)
5005 \value [since 6.10] RGBA32SI Four components, signed 32-bit. (128 bits total)
5006 */
5007
5008// When adding new texture formats, update void tst_QRhi::textureFormats_data().
5009
5010/*!
5011 \struct QRhiTexture::NativeTexture
5012 \inmodule QtGuiPrivate
5013 \inheaderfile rhi/qrhi.h
5014 \brief Contains information about the underlying native resources of a texture.
5015 */
5016
5017/*!
5018 \variable QRhiTexture::NativeTexture::object
5019 \brief 64-bit integer containing the native object handle.
5020
5021 With OpenGL, the native handle is a GLuint value, so \c object can then be
5022 cast to a GLuint. With Vulkan, the native handle is a VkImage, so \c object
5023 can be cast to a VkImage. With Direct3D 11 and Metal \c object contains a
5024 ID3D11Texture2D or MTLTexture pointer, respectively. With Direct3D 12
5025 \c object contains a ID3D12Resource pointer.
5026 */
5027
5028/*!
5029 \variable QRhiTexture::NativeTexture::layout
5030 \brief Specifies the current image layout for APIs like Vulkan.
5031
5032 For Vulkan, \c layout contains a \c VkImageLayout value. For Direct3D 12, a
5033 \c D3D12_RESOURCE_STATES value. For other APIs, this is undefined and should be
5034 ignored.
5035 */
5036
5037/*!
5038 \internal
5039 */
5040QRhiTexture::QRhiTexture(QRhiImplementation *rhi, Format format_, const QSize &pixelSize_, int depth_,
5041 int arraySize_, int sampleCount_, Flags flags_)
5042 : QRhiResource(rhi),
5043 m_format(format_), m_pixelSize(pixelSize_), m_depth(depth_),
5044 m_arraySize(arraySize_), m_sampleCount(sampleCount_), m_flags(flags_)
5045{
5046}
5047
5048/*!
5049 \return the resource type.
5050 */
5051QRhiResource::Type QRhiTexture::resourceType() const
5052{
5053 return Texture;
5054}
5055
5056/*!
5057 \fn virtual bool QRhiTexture::create() = 0
5058
5059 Creates the corresponding native graphics resources. If there are already
5060 resources present due to an earlier create() with no corresponding
5061 destroy(), then destroy() is called implicitly first.
5062
5063 \return \c true when successful, \c false when a graphics operation failed.
5064 Regardless of the return value, calling destroy() is always safe.
5065 */
5066
5067/*!
5068 \return the underlying native resources for this texture. The returned value
5069 will be empty if exposing the underlying native resources is not supported by
5070 the backend.
5071
5072 \sa createFrom()
5073 */
5074QRhiTexture::NativeTexture QRhiTexture::nativeTexture()
5075{
5076 return {};
5077}
5078
5079/*!
5080 Similar to create(), except that no new native textures are created.
5081 Instead, the native texture resources specified by \a src is used.
5082
5083 This allows importing an existing native texture object (which must belong
5084 to the same device or sharing context, depending on the graphics API) from
5085 an external graphics engine.
5086
5087 \return true if the specified existing native texture object has been
5088 successfully wrapped as a non-owning QRhiTexture.
5089
5090 \note format(), pixelSize(), sampleCount(), and flags() must still be set
5091 correctly. Passing incorrect sizes and other values to QRhi::newTexture()
5092 and then following it with a createFrom() expecting that the native texture
5093 object alone is sufficient to deduce such values is \b wrong and will lead
5094 to problems.
5095
5096 \note QRhiTexture does not take ownership of the texture object. destroy()
5097 does not free the object or any associated memory.
5098
5099 The opposite of this operation, exposing a QRhiTexture-created native
5100 texture object to a foreign engine, is possible via nativeTexture().
5101
5102 \note When importing a 3D texture, or a texture array object, or, with
5103 OpenGL ES, an external texture, it is then especially important to set the
5104 corresponding flags (ThreeDimensional, TextureArray, ExternalOES) via
5105 setFlags() before calling this function.
5106*/
5107bool QRhiTexture::createFrom(QRhiTexture::NativeTexture src)
5108{
5109 Q_UNUSED(src);
5110 return false;
5111}
5112
5113/*!
5114 With some graphics APIs, such as Vulkan, integrating custom rendering code
5115 that uses the graphics API directly needs special care when it comes to
5116 image layouts. This function allows communicating the expected \a layout the
5117 image backing the QRhiTexture is in after the native rendering commands.
5118
5119 For example, consider rendering into a QRhiTexture's VkImage directly with
5120 Vulkan in a code block enclosed by QRhiCommandBuffer::beginExternal() and
5121 QRhiCommandBuffer::endExternal(), followed by using the image for texture
5122 sampling in a QRhi-based render pass. To avoid potentially incorrect image
5123 layout transitions, this function can be used to indicate what the image
5124 layout will be once the commands recorded in said code block complete.
5125
5126 Calling this function makes sense only after
5127 QRhiCommandBuffer::endExternal() and before a subsequent
5128 QRhiCommandBuffer::beginPass().
5129
5130 This function has no effect with QRhi backends where the underlying
5131 graphics API does not expose a concept of image layouts.
5132
5133 \note With Vulkan \a layout is a \c VkImageLayout. With Direct 3D 12 \a
5134 layout is a value composed of the bits from \c D3D12_RESOURCE_STATES.
5135 */
5136void QRhiTexture::setNativeLayout(int layout)
5137{
5138 Q_UNUSED(layout);
5139}
5140
5141/*!
5142 \fn QRhiTexture::Format QRhiTexture::format() const
5143 \return the texture format.
5144 */
5145
5146/*!
5147 \fn void QRhiTexture::setFormat(QRhiTexture::Format fmt)
5148
5149 Sets the requested texture format to \a fmt.
5150
5151 \note The value set is only taken into account upon the next call to
5152 create(), i.e. when the underlying graphics resource are (re)created.
5153 Setting a new value is futile otherwise and must be avoided since it can
5154 lead to inconsistent state.
5155 */
5156
5157/*!
5158 \fn QSize QRhiTexture::pixelSize() const
5159 \return the size in pixels.
5160 */
5161
5162/*!
5163 \fn void QRhiTexture::setPixelSize(const QSize &sz)
5164
5165 Sets the texture size, specified in pixels, to \a sz.
5166
5167 \note The value set is only taken into account upon the next call to
5168 create(), i.e. when the underlying graphics resource are (re)created.
5169 Setting a new value is futile otherwise and must be avoided since it can
5170 lead to inconsistent state. The same applies to all other setters as well.
5171 */
5172
5173/*!
5174 \fn int QRhiTexture::depth() const
5175 \return the depth for 3D textures.
5176 */
5177
5178/*!
5179 \fn void QRhiTexture::setDepth(int depth)
5180 Sets the \a depth for a 3D texture.
5181 */
5182
5183/*!
5184 \fn int QRhiTexture::arraySize() const
5185 \return the texture array size.
5186 */
5187
5188/*!
5189 \fn void QRhiTexture::setArraySize(int arraySize)
5190 Sets the texture \a arraySize.
5191 */
5192
5193/*!
5194 \fn int QRhiTexture::arrayRangeStart() const
5195
5196 \return the first array layer when setArrayRange() was called.
5197
5198 \sa setArrayRange()
5199 */
5200
5201/*!
5202 \fn int QRhiTexture::arrayRangeLength() const
5203
5204 \return the exposed array range size when setArrayRange() was called.
5205
5206 \sa setArrayRange()
5207*/
5208
5209/*!
5210 \fn void QRhiTexture::setArrayRange(int startIndex, int count)
5211
5212 Normally all array layers are exposed and it is up to the shader to select
5213 the layer via the third coordinate passed to the \c{texture()} GLSL
5214 function when sampling the \c sampler2DArray. When QRhi::TextureArrayRange
5215 is reported as supported, calling setArrayRange() before create() or
5216 createFrom() requests selecting only the specified range, \a count elements
5217 starting from \a startIndex. The shader logic can then be written with this
5218 in mind.
5219
5220 \sa QRhi::TextureArrayRange
5221 */
5222
5223/*!
5224 \fn Flags QRhiTexture::flags() const
5225 \return the texture flags.
5226 */
5227
5228/*!
5229 \fn void QRhiTexture::setFlags(Flags f)
5230 Sets the texture flags to \a f.
5231 */
5232
5233/*!
5234 \fn int QRhiTexture::sampleCount() const
5235 \return the sample count. 1 means no multisample antialiasing.
5236 */
5237
5238/*!
5239 \fn void QRhiTexture::setSampleCount(int s)
5240 Sets the sample count to \a s.
5241 */
5242
5243/*!
5244 \struct QRhiTexture::ViewFormat
5245 \inmodule QtGuiPrivate
5246 \inheaderfile rhi/qrhi.h
5247 \since 6.8
5248 \brief Specifies the view format for reading or writing from or to the texture.
5249
5250 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
5251 for details.
5252 */
5253
5254/*!
5255 \variable QRhiTexture::ViewFormat::format
5256 */
5257
5258/*!
5259 \variable QRhiTexture::ViewFormat::srgb
5260 */
5261
5262/*!
5263 \fn QRhiTexture::ViewFormat QRhiTexture::readViewFormat() const
5264 \since 6.8
5265 \return the view format used when sampling the texture. When not called, the view
5266 format is assumed to be the same as format().
5267 */
5268
5269/*!
5270 \fn void QRhiTexture::setReadViewFormat(const ViewFormat &fmt)
5271 \since 6.8
5272
5273 Sets the shader resource view format (or the format of the view used for
5274 sampling the texture) to \a fmt. By default the same format (and sRGB-ness)
5275 is used as the texture itself, and in most cases this function does not need
5276 to be called.
5277
5278 This setting is only taken into account when the \l QRhi::TextureViewFormat
5279 feature is reported as supported.
5280
5281 \note This functionality is provided to allow "casting" between
5282 non-sRGB and sRGB in order to get the shader reads perform, or not perform,
5283 the implicit sRGB conversions. Other types of casting may or may not be
5284 functional.
5285 */
5286
5287/*!
5288 \fn QRhiTexture::ViewFormat QRhiTexture::writeViewFormat() const
5289 \since 6.8
5290 \return the view format used when writing to the texture and when using it
5291 with image load/store. When not called, the view format is assumed to be the
5292 same as format().
5293 */
5294
5295/*!
5296 \fn void QRhiTexture::setWriteViewFormat(const ViewFormat &fmt)
5297 \since 6.8
5298
5299 Sets the render target view format to \a fmt. By default the same format
5300 (and sRGB-ness) is used as the texture itself, and in most cases this
5301 function does not need to be called.
5302
5303 One common use case for providing a write view format is working with
5304 externally provided textures that, outside of our control, use an sRGB
5305 format with 3D APIs such as Vulkan or Direct 3D, but the rendering engine is
5306 already prepared to handle linearization and conversion to sRGB at the end
5307 of its shading pipeline. In this case what is wanted when rendering into
5308 such a texture is a render target view (e.g. VkImageView) that has the same,
5309 but non-sRGB format. (if e.g. from an OpenXR implementation one gets a
5310 VK_FORMAT_R8G8B8A8_SRGB texture, it is likely that rendering into it should
5311 be done using a VK_FORMAT_R8G8B8A8_UNORM view, if that is what the rendering
5312 engine's pipeline requires; in this example one would call this function
5313 with a ViewFormat that has a format of QRhiTexture::RGBA8 and \c srgb set to
5314 \c false).
5315
5316 This setting is only taken into account when the \l QRhi::TextureViewFormat
5317 feature is reported as supported.
5318
5319 \note This functionality is provided to allow "casting" between
5320 non-sRGB and sRGB in order to get the shader write not perform, or perform,
5321 the implicit sRGB conversions. Other types of casting may or may not be
5322 functional.
5323 */
5324
5325/*!
5326 \class QRhiSampler
5327 \inmodule QtGuiPrivate
5328 \inheaderfile rhi/qrhi.h
5329 \since 6.6
5330 \brief Sampler resource.
5331
5332 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
5333 for details.
5334 */
5335
5336/*!
5337 \enum QRhiSampler::Filter
5338 Specifies the minification, magnification, or mipmap filtering
5339
5340 \value None Applicable only for mipmapMode(), indicates no mipmaps to be used
5341 \value Nearest
5342 \value Linear
5343 */
5344
5345/*!
5346 \enum QRhiSampler::AddressMode
5347 Specifies the addressing mode
5348
5349 \value Repeat
5350 \value ClampToEdge
5351 \value Mirror
5352 */
5353
5354/*!
5355 \enum QRhiSampler::CompareOp
5356 Specifies the texture comparison function.
5357
5358 \value Never (default)
5359 \value Less
5360 \value Equal
5361 \value LessOrEqual
5362 \value Greater
5363 \value NotEqual
5364 \value GreaterOrEqual
5365 \value Always
5366 */
5367
5368/*!
5369 \internal
5370 */
5371QRhiSampler::QRhiSampler(QRhiImplementation *rhi,
5372 Filter magFilter_, Filter minFilter_, Filter mipmapMode_,
5373 AddressMode u_, AddressMode v_, AddressMode w_)
5374 : QRhiResource(rhi),
5375 m_magFilter(magFilter_), m_minFilter(minFilter_), m_mipmapMode(mipmapMode_),
5376 m_addressU(u_), m_addressV(v_), m_addressW(w_),
5377 m_compareOp(QRhiSampler::Never)
5378{
5379}
5380
5381/*!
5382 \return the resource type.
5383 */
5384QRhiResource::Type QRhiSampler::resourceType() const
5385{
5386 return Sampler;
5387}
5388
5389/*!
5390 \fn QRhiSampler::Filter QRhiSampler::magFilter() const
5391 \return the magnification filter mode.
5392 */
5393
5394/*!
5395 \fn void QRhiSampler::setMagFilter(Filter f)
5396 Sets the magnification filter mode to \a f.
5397 */
5398
5399/*!
5400 \fn QRhiSampler::Filter QRhiSampler::minFilter() const
5401 \return the minification filter mode.
5402 */
5403
5404/*!
5405 \fn void QRhiSampler::setMinFilter(Filter f)
5406 Sets the minification filter mode to \a f.
5407 */
5408
5409/*!
5410 \fn QRhiSampler::Filter QRhiSampler::mipmapMode() const
5411 \return the mipmap filter mode.
5412 */
5413
5414/*!
5415 \fn void QRhiSampler::setMipmapMode(Filter f)
5416
5417 Sets the mipmap filter mode to \a f.
5418
5419 Leave this set to None when the texture has no mip levels, or when the mip
5420 levels are not to be taken into account.
5421 */
5422
5423/*!
5424 \fn QRhiSampler::AddressMode QRhiSampler::addressU() const
5425 \return the horizontal wrap mode.
5426 */
5427
5428/*!
5429 \fn void QRhiSampler::setAddressU(AddressMode mode)
5430 Sets the horizontal wrap \a mode.
5431 */
5432
5433/*!
5434 \fn QRhiSampler::AddressMode QRhiSampler::addressV() const
5435 \return the vertical wrap mode.
5436 */
5437
5438/*!
5439 \fn void QRhiSampler::setAddressV(AddressMode mode)
5440 Sets the vertical wrap \a mode.
5441 */
5442
5443/*!
5444 \fn QRhiSampler::AddressMode QRhiSampler::addressW() const
5445 \return the depth wrap mode.
5446 */
5447
5448/*!
5449 \fn void QRhiSampler::setAddressW(AddressMode mode)
5450 Sets the depth wrap \a mode.
5451 */
5452
5453/*!
5454 \fn QRhiSampler::CompareOp QRhiSampler::textureCompareOp() const
5455 \return the texture comparison function.
5456 */
5457
5458/*!
5459 \fn void QRhiSampler::setTextureCompareOp(CompareOp op)
5460 Sets the texture comparison function \a op.
5461 */
5462
5463/*!
5464 \class QRhiShadingRateMap
5465 \inmodule QtGuiPrivate
5466 \inheaderfile rhi/qrhi.h
5467 \since 6.9
5468 \brief An object that wraps a texture or another kind of native 3D API object.
5469
5470 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
5471 for details.
5472
5473 For an introduction to Variable Rate Shading (VRS), see
5474 \l{https://learn.microsoft.com/en-us/windows/win32/direct3d12/vrs}. Qt
5475 supports a subset of the VRS features offered by Direct 3D 12 and Vulkan. In
5476 addition, Metal's somewhat different mechanism is supported by making it
5477 possible to set up a QRhiShadingRateMap with an existing
5478 MTLRasterizationRateMap object.
5479 */
5480
5481/*!
5482 \struct QRhiShadingRateMap::NativeShadingRateMap
5483 \inmodule QtGuiPrivate
5484 \inheaderfile rhi/qrhi.h
5485 \since 6.9
5486 \brief Wraps a native shading rate map.
5487
5488 An example is MTLRasterizationRateMap with Metal. Other 3D APIs that use
5489 textures for image-based VRS do not use this struct since those can function
5490 via the QRhiTexture-based overload of QRhiShadingRateMap::createFrom().
5491 */
5492
5493/*!
5494 \variable QRhiShadingRateMap::NativeShadingRateMap::object
5495 \brief 64-bit integer containing the native object handle.
5496
5497 Used with QRhiShadingRateMap::createFrom(). For example, with Metal,
5498 \c object is expected to be an id<MTLRasterizationRateMap>.
5499 */
5500
5501/*!
5502 \internal
5503 */
5504QRhiShadingRateMap::QRhiShadingRateMap(QRhiImplementation *rhi)
5505 : QRhiResource(rhi)
5506{
5507}
5508
5509/*!
5510 \return the resource type.
5511 */
5512QRhiResource::Type QRhiShadingRateMap::resourceType() const
5513{
5514 return ShadingRateMap;
5515}
5516
5517/*!
5518 Sets up the shading rate map to use a native 3D API shading rate object
5519 \a src.
5520
5521 \return \c true when successful, \c false when not supported.
5522
5523 \note This is functional only when the QRhi::VariableRateShadingMap feature
5524 is reported as supported, while QRhi::VariableRateShadingMapWithTexture
5525 feature is not. Currently this is true for Metal, assuming variable rate
5526 shading is supported by the GPU.
5527
5528 \note With Metal, the \c object field of \a src is expected to contain an
5529 id<MTLRasterizationRateMap>. Qt passes the MTLRasterizationRateMap on to the
5530 MTLRenderPassDescriptor, and, because Metal then interprets viewports and
5531 scissor rectangles in the map's screen space coordinate system, sizes the
5532 default scissor and converts viewports and scissors specified via
5533 QRhiCommandBuffer accordingly. The size of that coordinate system is
5534 reported by logicalSize(). Anything else, such as scaling when sampling
5535 the rendered result, is up to the application (or the XR compositor).
5536 */
5537bool QRhiShadingRateMap::createFrom(NativeShadingRateMap src)
5538{
5539 Q_UNUSED(src);
5540 return false;
5541}
5542
5543/*!
5544 Sets up the shading rate map to use the texture \a src as the
5545 image containing the per-tile shading rates.
5546
5547 \return \c true when successful, \c false when not supported.
5548
5549 The QRhiShadingRateMap does not take ownership of \a src.
5550
5551 \note This is functional only when the
5552 QRhi::VariableRateShadingMapWithTexture feature is reported as supported. In
5553 practice may be supported on Vulkan and Direct 3D 12 when using modern
5554 graphics cards. It will never be supported on OpenGL or Metal, for example.
5555
5556 \note \a src must have a format of QRhiTexture::R8UI.
5557
5558 \note \a src must have a width of \c{ceil(render_target_pixel_width /
5559 (float)tile_width)} and a height of \c{ceil(render_target_pixel_height /
5560 (float)tile_height)}. It is up to the application to ensure the size of the
5561 texture is as expected, using the above formula, at all times. The tile size
5562 can be queried via \l QRhi::resourceLimit() and
5563 QRhi::ShadingRateImageTileSize.
5564
5565 Each byte (texel) in the texture corresponds to the shading rate value for
5566 one tile. 0 indicates 1x1, while a value of 10 indicates 4x4. See
5567 \l{https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_shading_rate}{D3D12_SHADING_RATE}
5568 for other possible values.
5569 */
5570bool QRhiShadingRateMap::createFrom(QRhiTexture *src)
5571{
5572 Q_UNUSED(src);
5573 return false;
5574}
5575
5576/*!
5577 \since 6.13
5578
5579 \return the size of the logical coordinate space the shading rate map
5580 defines, or an invalid QSize when the map does not define one.
5581
5582 Some implementations, Metal in particular, describe a shading rate map in
5583 terms of a logical (screen space) size that is mapped onto the physical
5584 pixels of the render target. When such a map is attached to a render
5585 target, viewports and scissor rectangles are interpreted in the logical
5586 coordinate system, and the logical size is typically larger than
5587 QRhiRenderTarget::pixelSize(). Applications that derive viewports,
5588 scissors, or projection setup from the render target size should use this
5589 size instead whenever it is valid.
5590
5591 For implementations where the shading rate map is a tile image covering
5592 the render target, such as Vulkan and Direct 3D 12, there is no separate
5593 logical coordinate space, and an invalid QSize is returned. The render
5594 target's pixel size applies as usual in that case.
5595
5596 \sa QRhiRenderTarget::pixelSize()
5597 */
5598QSize QRhiShadingRateMap::logicalSize() const
5599{
5600 return QSize();
5601}
5602
5603/*!
5604 \class QRhiRenderPassDescriptor
5605 \inmodule QtGuiPrivate
5606 \inheaderfile rhi/qrhi.h
5607 \since 6.6
5608 \brief Render pass resource.
5609
5610 A render pass, if such a concept exists in the underlying graphics API, is
5611 a collection of attachments (color, depth, stencil) and describes how those
5612 attachments are used.
5613
5614 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
5615 for details.
5616 */
5617
5618/*!
5619 \internal
5620 */
5621QRhiRenderPassDescriptor::QRhiRenderPassDescriptor(QRhiImplementation *rhi)
5622 : QRhiResource(rhi)
5623{
5624}
5625
5626/*!
5627 \return the resource type.
5628 */
5629QRhiResource::Type QRhiRenderPassDescriptor::resourceType() const
5630{
5631 return RenderPassDescriptor;
5632}
5633
5634/*!
5635 \fn virtual bool QRhiRenderPassDescriptor::isCompatible(const QRhiRenderPassDescriptor *other) const = 0
5636
5637 \return true if the \a other QRhiRenderPassDescriptor is compatible with
5638 this one, meaning \c this and \a other can be used interchangeably in
5639 QRhiGraphicsPipeline::setRenderPassDescriptor().
5640
5641 The concept of the compatibility of renderpass descriptors is similar to
5642 the \l{QRhiShaderResourceBindings::isLayoutCompatible}{layout
5643 compatibility} of QRhiShaderResourceBindings instances. They allow better
5644 reuse of QRhiGraphicsPipeline instances: for example, a
5645 QRhiGraphicsPipeline instance cache is expected to use these functions to
5646 look for a matching pipeline, instead of just comparing pointers, thus
5647 allowing a different QRhiRenderPassDescriptor and
5648 QRhiShaderResourceBindings to be used in combination with the pipeline, as
5649 long as they are compatible.
5650
5651 The exact details of compatibility depend on the underlying graphics API.
5652 Two renderpass descriptors
5653 \l{QRhiTextureRenderTarget::newCompatibleRenderPassDescriptor()}{created}
5654 from the same QRhiTextureRenderTarget are always compatible.
5655
5656 Similarly to QRhiShaderResourceBindings, compatibility can also be tested
5657 without having two existing objects available. Extracting the opaque blob by
5658 calling serializedFormat() allows testing for compatibility by comparing the
5659 returned vector to another QRhiRenderPassDescriptor's
5660 serializedFormat(). This has benefits in certain situations, because it
5661 allows testing the compatibility of a QRhiRenderPassDescriptor with a
5662 QRhiGraphicsPipeline even when the QRhiRenderPassDescriptor the pipeline was
5663 originally built with is no longer available (but the data returned from its
5664 serializedFormat() still is).
5665
5666 \sa newCompatibleRenderPassDescriptor(), serializedFormat()
5667 */
5668
5669/*!
5670 \fn virtual QRhiRenderPassDescriptor *QRhiRenderPassDescriptor::newCompatibleRenderPassDescriptor() const = 0
5671
5672 \return a new QRhiRenderPassDescriptor that is
5673 \l{isCompatible()}{compatible} with this one.
5674
5675 This function allows cloning a QRhiRenderPassDescriptor. The returned
5676 object is ready to be used, and the ownership is transferred to the caller.
5677 Cloning a QRhiRenderPassDescriptor object can become useful in situations
5678 where the object is stored in data structures related to graphics pipelines
5679 (in order to allow creating new pipelines which in turn requires a
5680 renderpass descriptor object), and the lifetime of the renderpass
5681 descriptor created from a render target may be shorter than the pipelines.
5682 (for example, because the engine manages and destroys renderpasses together
5683 with the textures and render targets it was created from) In such a
5684 situation, it can be beneficial to store a cloned version in the data
5685 structures, and thus transferring ownership as well.
5686
5687 \sa isCompatible()
5688 */
5689
5690/*!
5691 \fn virtual QVector<quint32> QRhiRenderPassDescriptor::serializedFormat() const = 0
5692
5693 \return a vector of integers containing an opaque blob describing the data
5694 relevant for \l{isCompatible()}{compatibility}.
5695
5696 Given two QRhiRenderPassDescriptor objects \c rp1 and \c rp2, if the data
5697 returned from this function is identical, then \c{rp1->isCompatible(rp2)},
5698 and vice versa hold true as well.
5699
5700 \note The returned data is meant to be used for storing in memory and
5701 comparisons during the lifetime of the QRhi the object belongs to. It is not
5702 meant for storing on disk, reusing between processes, or using with multiple
5703 QRhi instances with potentially different backends.
5704
5705 \note Calling this function is expected to be a cheap operation since the
5706 backends are not supposed to calculate the data in this function, but rather
5707 return an already calculated series of data.
5708
5709 When creating reusable components as part of a library, where graphics
5710 pipelines are created and maintained while targeting a QRhiRenderTarget (be
5711 it a swapchain or a texture) managed by the client of the library, the
5712 components must be able to deal with a changing QRhiRenderPassDescriptor.
5713 For example, because the render target changes and so invalidates the
5714 previously QRhiRenderPassDescriptor (with regards to the new render target
5715 at least) due to having a potentially different color format and attachments
5716 now. Or because \l{QRhiShadingRateMap}{variable rate shading} is taken into
5717 use dynamically. A simple pattern that helps dealing with this is performing
5718 the following check on every frame, to recognize the case when the pipeline
5719 needs to be associated with a new QRhiRenderPassDescriptor, because
5720 something is different about the render target now, compared to earlier
5721 frames:
5722
5723 \code
5724 QRhiRenderPassDescriptor *rp = m_renderTarget->renderPassDescriptor();
5725 if (m_pipeline && rp->serializedFormat() != m_renderPassFormat) {
5726 m_pipeline->setRenderPassDescriptor(rp);
5727 m_renderPassFormat = rp->serializedFormat();
5728 m_pipeline->create();
5729 }
5730 // remember to store m_renderPassFormat also when creating m_pipeline the first time
5731 \endcode
5732
5733 \sa isCompatible()
5734 */
5735
5736/*!
5737 \return a pointer to a backend-specific QRhiNativeHandles subclass, such as
5738 QRhiVulkanRenderPassNativeHandles. The returned value is \nullptr when exposing
5739 the underlying native resources is not supported by the backend.
5740
5741 \sa QRhiVulkanRenderPassNativeHandles
5742 */
5743const QRhiNativeHandles *QRhiRenderPassDescriptor::nativeHandles()
5744{
5745 return nullptr;
5746}
5747
5748/*!
5749 \class QRhiRenderTarget
5750 \inmodule QtGuiPrivate
5751 \inheaderfile rhi/qrhi.h
5752 \since 6.6
5753 \brief Represents an onscreen (swapchain) or offscreen (texture) render target.
5754
5755 Applications do not create an instance of this class directly. Rather, it
5756 is the subclass QRhiTextureRenderTarget that is instantiable by clients of
5757 the API via \l{QRhi::newTextureRenderTarget()}{newTextureRenderTarget()}.
5758 The other subclass is QRhiSwapChainRenderTarget, which is the type
5759 QRhiSwapChain returns when calling
5760 \l{QRhiSwapChain::currentFrameRenderTarget()}{currentFrameRenderTarget()}.
5761
5762 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
5763 for details.
5764
5765 \sa QRhiSwapChainRenderTarget, QRhiTextureRenderTarget
5766 */
5767
5768/*!
5769 \internal
5770 */
5771QRhiRenderTarget::QRhiRenderTarget(QRhiImplementation *rhi)
5772 : QRhiResource(rhi)
5773{
5774}
5775
5776/*!
5777 \fn virtual QSize QRhiRenderTarget::pixelSize() const = 0
5778
5779 \return the size in pixels.
5780
5781 Valid only after create() has been called successfully. Until then the
5782 result is a default-constructed QSize.
5783
5784 With QRhiTextureRenderTarget the returned size is the size of the
5785 associated attachments at the time of create(), in practice the size of the
5786 first color attachment, or the depth/stencil buffer if there are no color
5787 attachments. If the associated textures or renderbuffers are resized and
5788 rebuilt afterwards, then pixelSize() performs an implicit call to create()
5789 in order to rebuild the underlying data structures. This implicit check is
5790 similar to what QRhiCommandBuffer::beginPass() does, and ensures that the
5791 returned size is always up-to-date.
5792 */
5793
5794/*!
5795 \fn virtual float QRhiRenderTarget::devicePixelRatio() const = 0
5796
5797 \return the device pixel ratio. For QRhiTextureRenderTarget this is always
5798 1. For targets retrieved from a QRhiSwapChain the value reflects the
5799 \l{QWindow::devicePixelRatio()}{device pixel ratio} of the targeted
5800 QWindow.
5801 */
5802
5803/*!
5804 \fn virtual int QRhiRenderTarget::sampleCount() const = 0
5805
5806 \return the sample count or 1 if multisample antialiasing is not relevant for
5807 this render target.
5808 */
5809
5810/*!
5811 \fn QRhiRenderPassDescriptor *QRhiRenderTarget::renderPassDescriptor() const
5812
5813 \return the associated QRhiRenderPassDescriptor.
5814 */
5815
5816/*!
5817 \fn void QRhiRenderTarget::setRenderPassDescriptor(QRhiRenderPassDescriptor *desc)
5818
5819 Sets the QRhiRenderPassDescriptor \a desc for use with this render target.
5820 */
5821
5822/*!
5823 \internal
5824 */
5825QRhiSwapChainRenderTarget::QRhiSwapChainRenderTarget(QRhiImplementation *rhi, QRhiSwapChain *swapchain_)
5826 : QRhiRenderTarget(rhi),
5827 m_swapchain(swapchain_)
5828{
5829}
5830
5831/*!
5832 \class QRhiSwapChainRenderTarget
5833 \inmodule QtGuiPrivate
5834 \inheaderfile rhi/qrhi.h
5835 \since 6.6
5836 \brief Swapchain render target resource.
5837
5838 When targeting the color buffers of a swapchain, active render target is a
5839 QRhiSwapChainRenderTarget. This is what
5840 QRhiSwapChain::currentFrameRenderTarget() returns.
5841
5842 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
5843 for details.
5844
5845 \sa QRhiSwapChain
5846 */
5847
5848/*!
5849 \return the resource type.
5850 */
5851QRhiResource::Type QRhiSwapChainRenderTarget::resourceType() const
5852{
5853 return SwapChainRenderTarget;
5854}
5855
5856/*!
5857 \fn QRhiSwapChain *QRhiSwapChainRenderTarget::swapChain() const
5858
5859 \return the swapchain object.
5860 */
5861
5862/*!
5863 \class QRhiTextureRenderTarget
5864 \inmodule QtGuiPrivate
5865 \inheaderfile rhi/qrhi.h
5866 \since 6.6
5867 \brief Texture render target resource.
5868
5869 A texture render target allows rendering into one or more textures,
5870 optionally with a depth texture or depth/stencil renderbuffer.
5871
5872 For multisample rendering the common approach is to use a renderbuffer as
5873 the color attachment and set the non-multisample destination texture as the
5874 \c{resolve texture}. For more information, read the detailed description of
5875 the \l QRhiColorAttachment class.
5876
5877 \note Textures used in combination with QRhiTextureRenderTarget must be
5878 created with the QRhiTexture::RenderTarget flag.
5879
5880 The simplest example of creating a render target with a texture as its
5881 single color attachment:
5882
5883 \code
5884 QRhiTexture *texture = rhi->newTexture(QRhiTexture::RGBA8, size, 1, QRhiTexture::RenderTarget);
5885 texture->create();
5886 QRhiTextureRenderTarget *rt = rhi->newTextureRenderTarget({ texture });
5887 rp = rt->newCompatibleRenderPassDescriptor();
5888 rt->setRenderPassDescriptor(rp);
5889 rt->create();
5890 // rt can now be used with beginPass()
5891 \endcode
5892
5893 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
5894 for details.
5895 */
5896
5897/*!
5898 \enum QRhiTextureRenderTarget::Flag
5899
5900 Flag values describing the load/store behavior for the render target. The
5901 load/store behavior may be baked into native resources under the hood,
5902 depending on the backend, and therefore it needs to be known upfront and
5903 cannot be changed without rebuilding (and so releasing and creating new
5904 native resources).
5905
5906 \value PreserveColorContents Indicates that the contents of the color
5907 attachments is to be loaded when starting a render pass, instead of
5908 clearing. This is potentially more expensive, especially on mobile (tiled)
5909 GPUs, but allows preserving the existing contents between passes. When doing
5910 multisample rendering with a resolve texture set, setting this flag also
5911 requests the multisample color data to be stored (written out) to the
5912 multisample texture or render buffer. (for non-multisample rendering the
5913 color data is always stored, but for MSAA storing the multisample data
5914 decreases efficiency for certain GPU architectures, hence defaulting to not
5915 writing it out) Note however that this is non-portable: in some cases there
5916 is no intermediate multisample texture on the graphics API level, e.g. when
5917 using OpenGL ES's \c{GL_EXT_multisampled_render_to_texture} as it is all
5918 implicit, handled by the OpenGL ES implementation. In that case,
5919 PreserveColorContents will likely have no effect. Therefore, avoid relying
5920 on this flag when using multisample rendering and the color attachment is
5921 using a multisample QRhiTexture (not QRhiRenderBuffer).
5922
5923 \value PreserveDepthStencilContents Indicates that the contents of the
5924 depth texture is to be loaded when starting a render pass, instead
5925 clearing. Only applicable when a texture is used as the depth buffer
5926 (QRhiTextureRenderTargetDescription::depthTexture() is set) because
5927 depth/stencil renderbuffers may not have any physical backing and data may
5928 not be written out in the first place.
5929
5930 \value DoNotStoreDepthStencilContents Indicates that the contents of the
5931 depth texture does not need to be written out. Relevant only when a
5932 QRhiTexture, not QRhiRenderBuffer, is used as the depth-stencil buffer,
5933 because for QRhiRenderBuffer this is implicit. When a depthResolveTexture is
5934 set, the flag is not relevant, because the behavior is then as if the flag
5935 was set. This enum value is introduced in Qt 6.8.
5936 */
5937
5938/*!
5939 \internal
5940 */
5941QRhiTextureRenderTarget::QRhiTextureRenderTarget(QRhiImplementation *rhi,
5942 const QRhiTextureRenderTargetDescription &desc_,
5943 Flags flags_)
5944 : QRhiRenderTarget(rhi),
5945 m_desc(desc_),
5946 m_flags(flags_)
5947{
5948}
5949
5950/*!
5951 \return the resource type.
5952 */
5953QRhiResource::Type QRhiTextureRenderTarget::resourceType() const
5954{
5955 return TextureRenderTarget;
5956}
5957
5958/*!
5959 \fn virtual QRhiRenderPassDescriptor *QRhiTextureRenderTarget::newCompatibleRenderPassDescriptor() = 0
5960
5961 \return a new QRhiRenderPassDescriptor that is compatible with this render
5962 target.
5963
5964 The returned value is used in two ways: it can be passed to
5965 setRenderPassDescriptor() and
5966 QRhiGraphicsPipeline::setRenderPassDescriptor(). A render pass descriptor
5967 describes the attachments (color, depth/stencil) and the load/store
5968 behavior that can be affected by flags(). A QRhiGraphicsPipeline can only
5969 be used in combination with a render target that has a
5970 \l{QRhiRenderPassDescriptor::isCompatible()}{compatible}
5971 QRhiRenderPassDescriptor set.
5972
5973 Two QRhiTextureRenderTarget instances can share the same render pass
5974 descriptor as long as they have the same number and type of attachments.
5975 The associated QRhiTexture or QRhiRenderBuffer instances are not part of
5976 the render pass descriptor so those can differ in the two
5977 QRhiTextureRenderTarget instances.
5978
5979 \note resources, such as QRhiTexture instances, referenced in description()
5980 must already have create() called on them.
5981
5982 \sa create()
5983 */
5984
5985/*!
5986 \fn virtual bool QRhiTextureRenderTarget::create() = 0
5987
5988 Creates the corresponding native graphics resources. If there are already
5989 resources present due to an earlier create() with no corresponding
5990 destroy(), then destroy() is called implicitly first.
5991
5992 \note renderPassDescriptor() must be set before calling create(). To obtain
5993 a QRhiRenderPassDescriptor compatible with the render target, call
5994 newCompatibleRenderPassDescriptor() before create() but after setting all
5995 other parameters, such as description() and flags(). To save resources,
5996 reuse the same QRhiRenderPassDescriptor with multiple
5997 QRhiTextureRenderTarget instances, whenever possible. Sharing the same
5998 render pass descriptor is only possible when the render targets have the
5999 same number and type of attachments (the actual textures can differ) and
6000 the same flags.
6001
6002 \note resources, such as QRhiTexture instances, referenced in description()
6003 must already have create() called on them.
6004
6005 \return \c true when successful, \c false when a graphics operation failed.
6006 Regardless of the return value, calling destroy() is always safe.
6007 */
6008
6009/*!
6010 \fn QRhiTextureRenderTargetDescription QRhiTextureRenderTarget::description() const
6011 \return the render target description.
6012 */
6013
6014/*!
6015 \fn void QRhiTextureRenderTarget::setDescription(const QRhiTextureRenderTargetDescription &desc)
6016 Sets the render target description \a desc.
6017 */
6018
6019/*!
6020 \fn QRhiTextureRenderTarget::Flags QRhiTextureRenderTarget::flags() const
6021 \return the currently set flags.
6022 */
6023
6024/*!
6025 \fn void QRhiTextureRenderTarget::setFlags(Flags f)
6026 Sets the flags to \a f.
6027 */
6028
6029/*!
6030 \class QRhiShaderResourceBindings
6031 \inmodule QtGuiPrivate
6032 \inheaderfile rhi/qrhi.h
6033 \since 6.6
6034 \brief Encapsulates resources for making buffer, texture, sampler resources visible to shaders.
6035
6036 A QRhiShaderResourceBindings is a collection of QRhiShaderResourceBinding
6037 objects, each of which describe a single binding.
6038
6039 Take a fragment shader with the following interface:
6040
6041 \badcode
6042 layout(std140, binding = 0) uniform buf {
6043 mat4 mvp;
6044 int flip;
6045 } ubuf;
6046
6047 layout(binding = 1) uniform sampler2D tex;
6048 \endcode
6049
6050 To make resources visible to the shader, the following
6051 QRhiShaderResourceBindings could be created and then passed to
6052 QRhiGraphicsPipeline::setShaderResourceBindings():
6053
6054 \code
6055 QRhiShaderResourceBindings *srb = rhi->newShaderResourceBindings();
6056 srb->setBindings({
6057 QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, ubuf),
6058 QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, texture, sampler)
6059 });
6060 srb->create();
6061 // ...
6062 QRhiGraphicsPipeline *ps = rhi->newGraphicsPipeline();
6063 // ...
6064 ps->setShaderResourceBindings(srb);
6065 ps->create();
6066 // ...
6067 cb->setGraphicsPipeline(ps);
6068 cb->setShaderResources(); // binds srb
6069 \endcode
6070
6071 This assumes that \c ubuf is a QRhiBuffer, \c texture is a QRhiTexture,
6072 while \a sampler is a QRhiSampler. The example also assumes that the
6073 uniform block is present in the vertex shader as well so the same buffer is
6074 made visible to the vertex stage too.
6075
6076 \section1 Advanced usage
6077
6078 Building on the above example, let's assume that a pass now needs to use
6079 the exact same pipeline and shaders with a different texture. Creating a
6080 whole separate QRhiGraphicsPipeline just for this would be an overkill.
6081 This is why QRhiCommandBuffer::setShaderResources() allows specifying a \a
6082 srb argument. As long as the layouts (so the number of bindings and the
6083 binding points) match between two QRhiShaderResourceBindings, they can both
6084 be used with the same pipeline, assuming the pipeline was created with one of
6085 them in the first place. See isLayoutCompatible() for more details.
6086
6087 \code
6088 QRhiShaderResourceBindings *srb2 = rhi->newShaderResourceBindings();
6089 // ...
6090 cb->setGraphicsPipeline(ps);
6091 cb->setShaderResources(srb2); // binds srb2
6092 \endcode
6093
6094 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
6095 for details.
6096 */
6097
6098/*!
6099 \typedef QRhiShaderResourceBindingSet
6100 \relates QRhi
6101 \since 6.7
6102
6103 Synonym for QRhiShaderResourceBindings.
6104*/
6105
6106/*!
6107 \internal
6108 */
6109QRhiShaderResourceBindings::QRhiShaderResourceBindings(QRhiImplementation *rhi)
6110 : QRhiResource(rhi)
6111{
6112 m_layoutDesc.reserve(BINDING_PREALLOC * QRhiShaderResourceBinding::LAYOUT_DESC_ENTRIES_PER_BINDING);
6113}
6114
6115/*!
6116 \return the resource type.
6117 */
6118QRhiResource::Type QRhiShaderResourceBindings::resourceType() const
6119{
6120 return ShaderResourceBindings;
6121}
6122
6123/*!
6124 \return \c true if the layout is compatible with \a other. The layout does
6125 not include the actual resource (such as, buffer or texture) and related
6126 parameters (such as, offset or size). It does include the binding point,
6127 pipeline stage, and resource type, however. The number and order of the
6128 bindings must also match in order to be compatible.
6129
6130 When there is a QRhiGraphicsPipeline created with this
6131 QRhiShaderResourceBindings, and the function returns \c true, \a other can
6132 then safely be passed to QRhiCommandBuffer::setShaderResources(), and so
6133 be used with the pipeline in place of this QRhiShaderResourceBindings.
6134
6135 \note This function must only be called after a successful create(), because
6136 it relies on data generated during the baking of the underlying data
6137 structures. This way the function can implement a comparison approach that
6138 is more efficient than iterating through two binding lists and calling
6139 QRhiShaderResourceBinding::isLayoutCompatible() on each pair. This becomes
6140 relevant especially when this function is called at a high frequency.
6141
6142 \sa serializedLayoutDescription()
6143 */
6144bool QRhiShaderResourceBindings::isLayoutCompatible(const QRhiShaderResourceBindings *other) const
6145{
6146 if (other == this)
6147 return true;
6148
6149 if (!other)
6150 return false;
6151
6152 // This can become a hot code path. Therefore we do not iterate and call
6153 // isLayoutCompatible() on m_bindings, but rather check a pre-calculated
6154 // hash code and then, if the hash matched, do a uint array comparison
6155 // (that's still more cache friendly).
6156
6157 return m_layoutDescHash == other->m_layoutDescHash
6158 && m_layoutDesc == other->m_layoutDesc;
6159}
6160
6161/*!
6162 \fn QVector<quint32> QRhiShaderResourceBindings::serializedLayoutDescription() const
6163
6164 \return a vector of integers containing an opaque blob describing the layout
6165 of the binding list, i.e. the data relevant for
6166 \l{isLayoutCompatible()}{layout compatibility tests}.
6167
6168 Given two objects \c srb1 and \c srb2, if the data returned from this
6169 function is identical, then \c{srb1->isLayoutCompatible(srb2)}, and vice
6170 versa hold true as well.
6171
6172 \note The returned data is meant to be used for storing in memory and
6173 comparisons during the lifetime of the QRhi the object belongs to. It is not
6174 meant for storing on disk, reusing between processes, or using with multiple
6175 QRhi instances with potentially different backends.
6176
6177 \sa isLayoutCompatible()
6178 */
6179
6180void QRhiImplementation::updateLayoutDesc(QRhiShaderResourceBindings *srb)
6181{
6182 srb->m_layoutDescHash = 0;
6183 srb->m_layoutDesc.clear();
6184 auto layoutDescAppender = std::back_inserter(srb->m_layoutDesc);
6185 for (const QRhiShaderResourceBinding &b : std::as_const(srb->m_bindings)) {
6186 const QRhiShaderResourceBinding::Data *d = &b.d;
6187 srb->m_layoutDescHash ^= uint(d->binding) ^ uint(d->stage) ^ uint(d->type())
6188 ^ uint(d->arraySize());
6189 layoutDescAppender = d->serialize(layoutDescAppender);
6190 }
6191}
6192
6193/*!
6194 \fn virtual bool QRhiShaderResourceBindings::create() = 0
6195
6196 Creates the corresponding resource binding set. Depending on the underlying
6197 graphics API, this may involve creating native graphics resources, and
6198 therefore it should not be assumed that this is a cheap operation.
6199
6200 If create() has been called before with no corresponding destroy(), then
6201 destroy() is called implicitly first.
6202
6203 \return \c true when successful, \c false when failed.
6204 Regardless of the return value, calling destroy() is always safe.
6205 */
6206
6207/*!
6208 \fn void QRhiShaderResourceBindings::setBindings(std::initializer_list<QRhiShaderResourceBinding> list)
6209 Sets the \a list of bindings.
6210 */
6211
6212/*!
6213 \fn template<typename InputIterator> void QRhiShaderResourceBindings::setBindings(InputIterator first, InputIterator last)
6214 Sets the list of bindings from the iterators \a first and \a last.
6215 */
6216
6217/*!
6218 \fn const QRhiShaderResourceBinding *QRhiShaderResourceBindings::cbeginBindings() const
6219 \return a const iterator pointing to the first item in the binding list.
6220 */
6221
6222/*!
6223 \fn const QRhiShaderResourceBinding *QRhiShaderResourceBindings::cendBindings() const
6224 \return a const iterator pointing just after the last item in the binding list.
6225 */
6226
6227/*!
6228 \fn const QRhiShaderResourceBinding *QRhiShaderResourceBindings::bindingAt(qsizetype index) const
6229 \return the binding at the specified \a index.
6230 */
6231
6232/*!
6233 \fn qsizetype QRhiShaderResourceBindings::bindingCount() const
6234 \return the number of bindings.
6235 */
6236
6237/*!
6238 \class QRhiShaderResourceBinding
6239 \inmodule QtGuiPrivate
6240 \inheaderfile rhi/qrhi.h
6241 \since 6.6
6242 \brief Describes the shader resource for a single binding point.
6243
6244 A QRhiShaderResourceBinding cannot be constructed directly. Instead, use the
6245 static functions such as uniformBuffer() or sampledTexture() to get an
6246 instance.
6247
6248 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
6249 for details.
6250 */
6251
6252/*!
6253 \enum QRhiShaderResourceBinding::Type
6254 Specifies type of the shader resource bound to a binding point
6255
6256 \value UniformBuffer Uniform buffer
6257
6258 \value SampledTexture Combined image sampler (a texture and sampler pair).
6259 Even when the shading language associated with the underlying 3D API has no
6260 support for this concept (e.g. D3D and HLSL), this is still supported
6261 because the shader translation layer takes care of the appropriate
6262 translation and remapping of binding points or shader registers.
6263
6264 \value Texture Texture (separate)
6265
6266 \value Sampler Sampler (separate)
6267
6268 \value ImageLoad Image load (with GLSL this maps to doing imageLoad() on a
6269 single level - and either one or all layers - of a texture exposed to the
6270 shader as an image object)
6271
6272 \value ImageStore Image store (with GLSL this maps to doing imageStore() or
6273 imageAtomic*() on a single level - and either one or all layers - of a
6274 texture exposed to the shader as an image object)
6275
6276 \value ImageLoadStore Image load and store
6277
6278 \value BufferLoad Storage buffer load (with GLSL this maps to reading from
6279 a shader storage buffer)
6280
6281 \value BufferStore Storage buffer store (with GLSL this maps to writing to
6282 a shader storage buffer)
6283
6284 \value BufferLoadStore Storage buffer load and store
6285 */
6286
6287/*!
6288 \enum QRhiShaderResourceBinding::StageFlag
6289 Flag values to indicate which stages the shader resource is visible in
6290
6291 \value VertexStage Vertex stage
6292 \value TessellationControlStage Tessellation control (hull shader) stage
6293 \value TessellationEvaluationStage Tessellation evaluation (domain shader) stage
6294 \value FragmentStage Fragment (pixel shader) stage
6295 \value ComputeStage Compute stage
6296 \value GeometryStage Geometry stage
6297 */
6298
6299/*!
6300 \return \c true if the layout is compatible with \a other. The layout does not
6301 include the actual resource (such as, buffer or texture) and related
6302 parameters (such as, offset or size).
6303
6304 For example, \c a and \c b below are not equal, but are compatible layout-wise:
6305
6306 \code
6307 auto a = QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage, buffer);
6308 auto b = QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage, someOtherBuffer, 256);
6309 \endcode
6310 */
6311bool QRhiShaderResourceBinding::isLayoutCompatible(const QRhiShaderResourceBinding &other) const
6312{
6313 // everything that goes into a VkDescriptorSetLayoutBinding must match
6314 return d.binding == other.d.binding
6315 && d.stage == other.d.stage
6316 && d.type() == other.d.type()
6317 && d.arraySize() == other.d.arraySize();
6318}
6319
6320template<QRhiShaderResourceBinding::Type T>
6321static auto &emplaceData(QRhiShaderResourceBinding::Data &d)
6322{
6323 // Not using the return value of emplace() because the standard library on
6324 // VxWorks lacks the LWG 2857 resolution, so emplace() returns void there.
6325 d.u.emplace<T>();
6326 return *std::get_if<T>(&d.u);
6327}
6328
6329/*!
6330 \return a shader resource binding for the given binding number, pipeline
6331 stages, and buffer specified by \a binding, \a stage, and \a buf.
6332
6333 \note When \a buf is not null, it must have been created with
6334 QRhiBuffer::UniformBuffer.
6335
6336 \note \a buf can be null. It is valid to create a
6337 QRhiShaderResourceBindings with unspecified resources, but such an object
6338 cannot be used with QRhiCommandBuffer::setShaderResources(). It is however
6339 suitable for creating pipelines. Such a pipeline must then always be used
6340 together with another, layout compatible QRhiShaderResourceBindings with
6341 resources present passed to QRhiCommandBuffer::setShaderResources().
6342
6343 \note If the size of \a buf exceeds the limit reported for
6344 QRhi::MaxUniformBufferRange, unexpected errors may occur.
6345 */
6346QRhiShaderResourceBinding QRhiShaderResourceBinding::uniformBuffer(
6347 int binding, StageFlags stage, QRhiBuffer *buf)
6348{
6349 QRhiShaderResourceBinding b;
6350 b.d.binding = binding;
6351 b.d.stage = stage;
6352 b.d.u.emplace<UniformBuffer>(Data::UniformBufferData{ buf, 0, 0, false });
6353 return b;
6354}
6355
6356/*!
6357 \return a shader resource binding for the given binding number, pipeline
6358 stages, and buffer specified by \a binding, \a stage, and \a buf. This
6359 overload binds a region only, as specified by \a offset and \a size.
6360
6361 \note It is up to the user to ensure the offset is aligned to
6362 QRhi::ubufAlignment().
6363
6364 \note \a size must be greater than 0.
6365
6366 \note When \a buf is not null, it must have been created with
6367 QRhiBuffer::UniformBuffer.
6368
6369 \note \a buf can be null. It is valid to create a
6370 QRhiShaderResourceBindings with unspecified resources, but such an object
6371 cannot be used with QRhiCommandBuffer::setShaderResources(). It is however
6372 suitable for creating pipelines. Such a pipeline must then always be used
6373 together with another, layout compatible QRhiShaderResourceBindings with
6374 resources present passed to QRhiCommandBuffer::setShaderResources().
6375
6376 \note If \a size exceeds the limit reported for QRhi::MaxUniformBufferRange,
6377 unexpected errors may occur.
6378 */
6379QRhiShaderResourceBinding QRhiShaderResourceBinding::uniformBuffer(
6380 int binding, StageFlags stage, QRhiBuffer *buf, quint32 offset, quint32 size)
6381{
6382 Q_ASSERT(size > 0);
6383 QRhiShaderResourceBinding b;
6384 b.d.binding = binding;
6385 b.d.stage = stage;
6386 b.d.u.emplace<UniformBuffer>(Data::UniformBufferData{ buf, offset, size, false });
6387 return b;
6388}
6389
6390/*!
6391 \return a shader resource binding for the given binding number, pipeline
6392 stages, and buffer specified by \a binding, \a stage, and \a buf. The
6393 uniform buffer is assumed to have dynamic offset. The dynamic offset can be
6394 specified in QRhiCommandBuffer::setShaderResources(), thus allowing using
6395 varying offset values without creating new bindings for the buffer. The
6396 size of the bound region is specified by \a size. Like with non-dynamic
6397 offsets, \c{offset + size} cannot exceed the size of \a buf.
6398
6399 \note When \a buf is not null, it must have been created with
6400 QRhiBuffer::UniformBuffer.
6401
6402 \note \a buf can be null. It is valid to create a
6403 QRhiShaderResourceBindings with unspecified resources, but such an object
6404 cannot be used with QRhiCommandBuffer::setShaderResources(). It is however
6405 suitable for creating pipelines. Such a pipeline must then always be used
6406 together with another, layout compatible QRhiShaderResourceBindings with
6407 resources present passed to QRhiCommandBuffer::setShaderResources().
6408
6409 \note If \a size exceeds the limit reported for QRhi::MaxUniformBufferRange,
6410 unexpected errors may occur.
6411 */
6412QRhiShaderResourceBinding QRhiShaderResourceBinding::uniformBufferWithDynamicOffset(
6413 int binding, StageFlags stage, QRhiBuffer *buf, quint32 size)
6414{
6415 Q_ASSERT(size > 0);
6416 QRhiShaderResourceBinding b;
6417 b.d.binding = binding;
6418 b.d.stage = stage;
6419 b.d.u.emplace<UniformBuffer>(Data::UniformBufferData{ buf, 0, size, true });
6420 return b;
6421}
6422
6423/*!
6424 \return a shader resource binding for the given binding number, pipeline
6425 stages, texture, and sampler specified by \a binding, \a stage, \a tex,
6426 \a sampler.
6427
6428 \note This function is equivalent to calling sampledTextures() with a
6429 \c count of 1.
6430
6431 \note \a tex and \a sampler can be null. It is valid to create a
6432 QRhiShaderResourceBindings with unspecified resources, but such an object
6433 cannot be used with QRhiCommandBuffer::setShaderResources(). It is however
6434 suitable for creating pipelines. Such a pipeline must then always be used
6435 together with another, layout compatible QRhiShaderResourceBindings with
6436 resources present passed to QRhiCommandBuffer::setShaderResources().
6437
6438 \note A shader may not be able to consume more than 16 textures/samplers,
6439 depending on the underlying graphics API. This hard limit must be kept in
6440 mind in renderer design. This does not apply to texture arrays which
6441 consume a single binding point (shader register) and can contain 256-2048
6442 textures, depending on the underlying graphics API. Arrays of textures (see
6443 sampledTextures()) are however no different in this regard than using the
6444 same number of individual textures.
6445
6446 \sa sampledTextures()
6447 */
6448QRhiShaderResourceBinding QRhiShaderResourceBinding::sampledTexture(
6449 int binding, StageFlags stage, QRhiTexture *tex, QRhiSampler *sampler)
6450{
6451 QRhiShaderResourceBinding b;
6452 b.d.binding = binding;
6453 b.d.stage = stage;
6454 emplaceData<SampledTexture>(b.d).texSamplers = { { tex, sampler } };
6455 return b;
6456}
6457
6458/*!
6459 \return a shader resource binding for the given binding number, pipeline
6460 stages, and the array of texture-sampler pairs specified by \a binding, \a
6461 stage, \a count, and \a texSamplers.
6462
6463 \note \a count must be at least 1. There is no fixed upper limit, but each
6464 element counts towards the per-stage texture and sampler limits of the
6465 underlying graphics API, summed over all bindings visible to a given
6466 stage. Portable applications should not use more than 16 samplers per
6467 stage in total.
6468
6469 \note When \a count is 1, this function is equivalent to sampledTexture().
6470
6471 This function is relevant when arrays of combined image samplers are
6472 involved. For example, in GLSL \c{layout(binding = 5) uniform sampler2D
6473 shadowMaps[8];} declares an array of combined image samplers. The
6474 application is then expected provide a QRhiShaderResourceBinding for
6475 binding point 5, set up by calling this function with \a count set to 8 and
6476 a valid texture and sampler for each element of the array.
6477
6478 \warning All elements of the array must be specified. With the above
6479 example, the only valid, portable approach is calling this function with a
6480 \a count of 8. Additionally, all QRhiTexture and QRhiSampler instances must
6481 be valid, meaning nullptr is not an accepted value. This is due to some of
6482 the underlying APIs, such as, Vulkan, that require a valid image and
6483 sampler object for each element in descriptor arrays. Applications are
6484 advised to provide "dummy" samplers and textures if some array elements are
6485 not relevant (due to not being accessed in the shader).
6486
6487 \note \a texSamplers can be null. It is valid to create a
6488 QRhiShaderResourceBindings with unspecified resources, but such an object
6489 cannot be used with QRhiCommandBuffer::setShaderResources(). It is however
6490 suitable for creating pipelines. Such a pipeline must then always be used
6491 together with another, layout compatible QRhiShaderResourceBindings with
6492 resources present passed to QRhiCommandBuffer::setShaderResources().
6493
6494 \sa sampledTexture()
6495 */
6496QRhiShaderResourceBinding QRhiShaderResourceBinding::sampledTextures(
6497 int binding, StageFlags stage, int count, const TextureAndSampler *texSamplers)
6498{
6499 Q_ASSERT(count >= 1);
6500 QRhiShaderResourceBinding b;
6501 b.d.binding = binding;
6502 b.d.stage = stage;
6503 auto &stex = emplaceData<SampledTexture>(b.d);
6504 stex.texSamplers.resize(count);
6505 for (int i = 0; i < count; ++i) {
6506 if (texSamplers)
6507 stex.texSamplers[i] = texSamplers[i];
6508 else
6509 stex.texSamplers[i] = { nullptr, nullptr };
6510 }
6511 return b;
6512}
6513
6514/*!
6515 \return a shader resource binding for the given binding number, pipeline
6516 stages, and texture specified by \a binding, \a stage, \a tex.
6517
6518 \note This function is equivalent to calling textures() with a
6519 \c count of 1.
6520
6521 \note \a tex can be null. It is valid to create a
6522 QRhiShaderResourceBindings with unspecified resources, but such an object
6523 cannot be used with QRhiCommandBuffer::setShaderResources(). It is however
6524 suitable for creating pipelines. Such a pipeline must then always be used
6525 together with another, layout compatible QRhiShaderResourceBindings with
6526 resources present passed to QRhiCommandBuffer::setShaderResources().
6527
6528 This creates a binding for a separate texture (image) object, whereas
6529 sampledTexture() is suitable for combined image samplers. In
6530 Vulkan-compatible GLSL code separate textures are declared as \c texture2D
6531 as opposed to \c sampler2D: \c{layout(binding = 1) uniform texture2D tex;}
6532
6533 \note A shader may not be able to consume more than 16 textures, depending
6534 on the underlying graphics API. This hard limit must be kept in mind in
6535 renderer design. This does not apply to texture arrays which consume a
6536 single binding point (shader register) and can contain 256-2048 textures,
6537 depending on the underlying graphics API. Arrays of textures (see
6538 sampledTextures()) are however no different in this regard than using the
6539 same number of individual textures.
6540
6541 \sa textures(), sampler()
6542 */
6543QRhiShaderResourceBinding QRhiShaderResourceBinding::texture(int binding, StageFlags stage, QRhiTexture *tex)
6544{
6545 QRhiShaderResourceBinding b;
6546 b.d.binding = binding;
6547 b.d.stage = stage;
6548 emplaceData<Texture>(b.d).texSamplers = { { tex, nullptr } };
6549 return b;
6550}
6551
6552/*!
6553 \return a shader resource binding for the given binding number, pipeline
6554 stages, and the array of (separate) textures specified by \a binding, \a
6555 stage, \a count, and \a tex.
6556
6557 \note \a count must be at least 1. There is no fixed upper limit, but each
6558 element counts towards the per-stage texture limit of the underlying
6559 graphics API, summed over all bindings visible to a given stage. Portable
6560 applications should not use more than 16 textures per stage in total.
6561
6562 \note When \a count is 1, this function is equivalent to texture().
6563
6564 \warning All elements of the array must be specified.
6565
6566 \note \a tex can be null. It is valid to create a
6567 QRhiShaderResourceBindings with unspecified resources, but such an object
6568 cannot be used with QRhiCommandBuffer::setShaderResources(). It is however
6569 suitable for creating pipelines. Such a pipeline must then always be used
6570 together with another, layout compatible QRhiShaderResourceBindings with
6571 resources present passed to QRhiCommandBuffer::setShaderResources().
6572
6573 \sa texture(), sampler()
6574 */
6575QRhiShaderResourceBinding QRhiShaderResourceBinding::textures(int binding, StageFlags stage, int count, QRhiTexture **tex)
6576{
6577 Q_ASSERT(count >= 1);
6578 QRhiShaderResourceBinding b;
6579 b.d.binding = binding;
6580 b.d.stage = stage;
6581 auto &stex = emplaceData<Texture>(b.d);
6582 stex.texSamplers.resize(count);
6583 for (int i = 0; i < count; ++i) {
6584 if (tex)
6585 stex.texSamplers[i] = { tex[i], nullptr };
6586 else
6587 stex.texSamplers[i] = { nullptr, nullptr };
6588 }
6589 return b;
6590}
6591
6592/*!
6593 \return a shader resource binding for the given binding number, pipeline
6594 stages, and sampler specified by \a binding, \a stage, \a sampler.
6595
6596 \note \a sampler can be null. It is valid to create a
6597 QRhiShaderResourceBindings with unspecified resources, but such an object
6598 cannot be used with QRhiCommandBuffer::setShaderResources(). It is however
6599 suitable for creating pipelines. Such a pipeline must then always be used
6600 together with another, layout compatible QRhiShaderResourceBindings with
6601 resources present passed to QRhiCommandBuffer::setShaderResources().
6602
6603 Arrays of separate samplers are not supported.
6604
6605 This creates a binding for a separate sampler object, whereas
6606 sampledTexture() is suitable for combined image samplers. In
6607 Vulkan-compatible GLSL code separate samplers are declared as \c sampler
6608 as opposed to \c sampler2D: \c{layout(binding = 2) uniform sampler samp;}
6609
6610 With both a \c texture2D and \c sampler present, they can be used together
6611 to sample the texture: \c{fragColor = texture(sampler2D(tex, samp),
6612 texcoord);}.
6613
6614 \note A shader may not be able to consume more than 16 samplers, depending
6615 on the underlying graphics API. This hard limit must be kept in mind in
6616 renderer design.
6617
6618 \sa texture()
6619 */
6620QRhiShaderResourceBinding QRhiShaderResourceBinding::sampler(int binding, StageFlags stage, QRhiSampler *sampler)
6621{
6622 QRhiShaderResourceBinding b;
6623 b.d.binding = binding;
6624 b.d.stage = stage;
6625 emplaceData<Sampler>(b.d).texSamplers = { { nullptr, sampler } };
6626 return b;
6627}
6628
6629/*!
6630 \return a shader resource binding for a read-only storage image with the
6631 given \a binding number and pipeline \a stage. The image load operations
6632 will have access to all layers of the specified \a level. (so if the texture
6633 is a cubemap, the shader must use imageCube instead of image2D)
6634
6635 \note When \a tex is not null, it must have been created with
6636 QRhiTexture::UsedWithLoadStore.
6637
6638 \note \a tex can be null. It is valid to create a QRhiShaderResourceBindings
6639 with unspecified resources, but such an object cannot be used with
6640 QRhiCommandBuffer::setShaderResources(). It is however suitable for creating
6641 pipelines. Such a pipeline must then always be used together with another,
6642 layout compatible QRhiShaderResourceBindings with resources present passed
6643 to QRhiCommandBuffer::setShaderResources().
6644
6645 \note Image load/store is only available within the compute and fragment stages.
6646 */
6647QRhiShaderResourceBinding QRhiShaderResourceBinding::imageLoad(
6648 int binding, StageFlags stage, QRhiTexture *tex, int level)
6649{
6650 QRhiShaderResourceBinding b;
6651 b.d.binding = binding;
6652 b.d.stage = stage;
6653 b.d.u.emplace<ImageLoad>(Data::StorageImageData{ tex, level });
6654 return b;
6655}
6656
6657/*!
6658 \return a shader resource binding for a write-only storage image with the
6659 given \a binding number and pipeline \a stage. The image store operations
6660 will have access to all layers of the specified \a level. (so if the texture
6661 is a cubemap, the shader must use imageCube instead of image2D)
6662
6663 \note When \a tex is not null, it must have been created with
6664 QRhiTexture::UsedWithLoadStore.
6665
6666 \note \a tex can be null. It is valid to create a QRhiShaderResourceBindings
6667 with unspecified resources, but such an object cannot be used with
6668 QRhiCommandBuffer::setShaderResources(). It is however suitable for creating
6669 pipelines. Such a pipeline must then always be used together with another,
6670 layout compatible QRhiShaderResourceBindings with resources present passed
6671 to QRhiCommandBuffer::setShaderResources().
6672
6673 \note Image load/store is only available within the compute and fragment stages.
6674 */
6675QRhiShaderResourceBinding QRhiShaderResourceBinding::imageStore(
6676 int binding, StageFlags stage, QRhiTexture *tex, int level)
6677{
6678 QRhiShaderResourceBinding b;
6679 b.d.binding = binding;
6680 b.d.stage = stage;
6681 b.d.u.emplace<ImageStore>(Data::StorageImageData{ tex, level });
6682 return b;
6683}
6684
6685/*!
6686 \return a shader resource binding for a read/write storage image with the
6687 given \a binding number and pipeline \a stage. The image load/store operations
6688 will have access to all layers of the specified \a level. (so if the texture
6689 is a cubemap, the shader must use imageCube instead of image2D)
6690
6691 \note When \a tex is not null, it must have been created with
6692 QRhiTexture::UsedWithLoadStore.
6693
6694 \note \a tex can be null. It is valid to create a QRhiShaderResourceBindings
6695 with unspecified resources, but such an object cannot be used with
6696 QRhiCommandBuffer::setShaderResources(). It is however suitable for creating
6697 pipelines. Such a pipeline must then always be used together with another,
6698 layout compatible QRhiShaderResourceBindings with resources present passed
6699 to QRhiCommandBuffer::setShaderResources().
6700
6701 \note Image load/store is only available within the compute and fragment stages.
6702 */
6703QRhiShaderResourceBinding QRhiShaderResourceBinding::imageLoadStore(
6704 int binding, StageFlags stage, QRhiTexture *tex, int level)
6705{
6706 QRhiShaderResourceBinding b;
6707 b.d.binding = binding;
6708 b.d.stage = stage;
6709 b.d.u.emplace<ImageLoadStore>(Data::StorageImageData{ tex, level });
6710 return b;
6711}
6712
6713/*!
6714 \return a shader resource binding for a read-only storage buffer with the
6715 given \a binding number and pipeline \a stage.
6716
6717 \note When \a buf is not null, must have been created with
6718 QRhiBuffer::StorageBuffer.
6719
6720 \note \a buf can be null. It is valid to create a
6721 QRhiShaderResourceBindings with unspecified resources, but such an object
6722 cannot be used with QRhiCommandBuffer::setShaderResources(). It is however
6723 suitable for creating pipelines. Such a pipeline must then always be used
6724 together with another, layout compatible QRhiShaderResourceBindings with
6725 resources present passed to QRhiCommandBuffer::setShaderResources().
6726
6727 \note Buffer load/store is only guaranteed to be available within a compute
6728 pipeline. While some backends may support using these resources in a
6729 graphics pipeline as well, this is not universally supported, and even when
6730 it is, unexpected problems may arise when it comes to barriers and
6731 synchronization. Therefore, avoid using such resources with shaders other
6732 than compute.
6733 */
6734QRhiShaderResourceBinding QRhiShaderResourceBinding::bufferLoad(
6735 int binding, StageFlags stage, QRhiBuffer *buf)
6736{
6737 QRhiShaderResourceBinding b;
6738 b.d.binding = binding;
6739 b.d.stage = stage;
6740 b.d.u.emplace<BufferLoad>(Data::StorageBufferData{ buf, 0, 0 });
6741 return b;
6742}
6743
6744/*!
6745 \return a shader resource binding for a read-only storage buffer with the
6746 given \a binding number and pipeline \a stage. This overload binds a region
6747 only, as specified by \a offset and \a size.
6748
6749 \note When \a buf is not null, must have been created with
6750 QRhiBuffer::StorageBuffer.
6751
6752 \note \a buf can be null. It is valid to create a
6753 QRhiShaderResourceBindings with unspecified resources, but such an object
6754 cannot be used with QRhiCommandBuffer::setShaderResources(). It is however
6755 suitable for creating pipelines. Such a pipeline must then always be used
6756 together with another, layout compatible QRhiShaderResourceBindings with
6757 resources present passed to QRhiCommandBuffer::setShaderResources().
6758
6759 \note Buffer load/store is only guaranteed to be available within a compute
6760 pipeline. While some backends may support using these resources in a
6761 graphics pipeline as well, this is not universally supported, and even when
6762 it is, unexpected problems may arise when it comes to barriers and
6763 synchronization. Therefore, avoid using such resources with shaders other
6764 than compute.
6765 */
6766QRhiShaderResourceBinding QRhiShaderResourceBinding::bufferLoad(
6767 int binding, StageFlags stage, QRhiBuffer *buf, quint32 offset, quint32 size)
6768{
6769 Q_ASSERT(size > 0);
6770 QRhiShaderResourceBinding b;
6771 b.d.binding = binding;
6772 b.d.stage = stage;
6773 b.d.u.emplace<BufferLoad>(Data::StorageBufferData{ buf, offset, size });
6774 return b;
6775}
6776
6777/*!
6778 \return a shader resource binding for a write-only storage buffer with the
6779 given \a binding number and pipeline \a stage.
6780
6781 \note When \a buf is not null, must have been created with
6782 QRhiBuffer::StorageBuffer.
6783
6784 \note \a buf can be null. It is valid to create a
6785 QRhiShaderResourceBindings with unspecified resources, but such an object
6786 cannot be used with QRhiCommandBuffer::setShaderResources(). It is however
6787 suitable for creating pipelines. Such a pipeline must then always be used
6788 together with another, layout compatible QRhiShaderResourceBindings with
6789 resources present passed to QRhiCommandBuffer::setShaderResources().
6790
6791 \note Buffer load/store is only guaranteed to be available within a compute
6792 pipeline. While some backends may support using these resources in a
6793 graphics pipeline as well, this is not universally supported, and even when
6794 it is, unexpected problems may arise when it comes to barriers and
6795 synchronization. Therefore, avoid using such resources with shaders other
6796 than compute.
6797 */
6798QRhiShaderResourceBinding QRhiShaderResourceBinding::bufferStore(
6799 int binding, StageFlags stage, QRhiBuffer *buf)
6800{
6801 QRhiShaderResourceBinding b;
6802 b.d.binding = binding;
6803 b.d.stage = stage;
6804 b.d.u.emplace<BufferStore>(Data::StorageBufferData{ buf, 0, 0 });
6805 return b;
6806}
6807
6808/*!
6809 \return a shader resource binding for a write-only storage buffer with the
6810 given \a binding number and pipeline \a stage. This overload binds a region
6811 only, as specified by \a offset and \a size.
6812
6813 \note When \a buf is not null, must have been created with
6814 QRhiBuffer::StorageBuffer.
6815
6816 \note \a buf can be null. It is valid to create a
6817 QRhiShaderResourceBindings with unspecified resources, but such an object
6818 cannot be used with QRhiCommandBuffer::setShaderResources(). It is however
6819 suitable for creating pipelines. Such a pipeline must then always be used
6820 together with another, layout compatible QRhiShaderResourceBindings with
6821 resources present passed to QRhiCommandBuffer::setShaderResources().
6822
6823 \note Buffer load/store is only guaranteed to be available within a compute
6824 pipeline. While some backends may support using these resources in a
6825 graphics pipeline as well, this is not universally supported, and even when
6826 it is, unexpected problems may arise when it comes to barriers and
6827 synchronization. Therefore, avoid using such resources with shaders other
6828 than compute.
6829 */
6830QRhiShaderResourceBinding QRhiShaderResourceBinding::bufferStore(
6831 int binding, StageFlags stage, QRhiBuffer *buf, quint32 offset, quint32 size)
6832{
6833 Q_ASSERT(size > 0);
6834 QRhiShaderResourceBinding b;
6835 b.d.binding = binding;
6836 b.d.stage = stage;
6837 b.d.u.emplace<BufferStore>(Data::StorageBufferData{ buf, offset, size });
6838 return b;
6839}
6840
6841/*!
6842 \return a shader resource binding for a read-write storage buffer with the
6843 given \a binding number and pipeline \a stage.
6844
6845 \note When \a buf is not null, must have been created with
6846 QRhiBuffer::StorageBuffer.
6847
6848 \note \a buf can be null. It is valid to create a
6849 QRhiShaderResourceBindings with unspecified resources, but such an object
6850 cannot be used with QRhiCommandBuffer::setShaderResources(). It is however
6851 suitable for creating pipelines. Such a pipeline must then always be used
6852 together with another, layout compatible QRhiShaderResourceBindings with
6853 resources present passed to QRhiCommandBuffer::setShaderResources().
6854
6855 \note Buffer load/store is only guaranteed to be available within a compute
6856 pipeline. While some backends may support using these resources in a
6857 graphics pipeline as well, this is not universally supported, and even when
6858 it is, unexpected problems may arise when it comes to barriers and
6859 synchronization. Therefore, avoid using such resources with shaders other
6860 than compute.
6861 */
6862QRhiShaderResourceBinding QRhiShaderResourceBinding::bufferLoadStore(
6863 int binding, StageFlags stage, QRhiBuffer *buf)
6864{
6865 QRhiShaderResourceBinding b;
6866 b.d.binding = binding;
6867 b.d.stage = stage;
6868 b.d.u.emplace<BufferLoadStore>(Data::StorageBufferData{ buf, 0, 0 });
6869 return b;
6870}
6871
6872/*!
6873 \return a shader resource binding for a read-write storage buffer with the
6874 given \a binding number and pipeline \a stage. This overload binds a region
6875 only, as specified by \a offset and \a size.
6876
6877 \note When \a buf is not null, must have been created with
6878 QRhiBuffer::StorageBuffer.
6879
6880 \note \a buf can be null. It is valid to create a
6881 QRhiShaderResourceBindings with unspecified resources, but such an object
6882 cannot be used with QRhiCommandBuffer::setShaderResources(). It is however
6883 suitable for creating pipelines. Such a pipeline must then always be used
6884 together with another, layout compatible QRhiShaderResourceBindings with
6885 resources present passed to QRhiCommandBuffer::setShaderResources().
6886
6887 \note Buffer load/store is only guaranteed to be available within a compute
6888 pipeline. While some backends may support using these resources in a
6889 graphics pipeline as well, this is not universally supported, and even when
6890 it is, unexpected problems may arise when it comes to barriers and
6891 synchronization. Therefore, avoid using such resources with shaders other
6892 than compute.
6893 */
6894QRhiShaderResourceBinding QRhiShaderResourceBinding::bufferLoadStore(
6895 int binding, StageFlags stage, QRhiBuffer *buf, quint32 offset, quint32 size)
6896{
6897 Q_ASSERT(size > 0);
6898 QRhiShaderResourceBinding b;
6899 b.d.binding = binding;
6900 b.d.stage = stage;
6901 b.d.u.emplace<BufferLoadStore>(Data::StorageBufferData{ buf, offset, size });
6902 return b;
6903}
6904
6905/*!
6906 \return \c true if the contents of the two QRhiShaderResourceBinding
6907 objects \a a and \a b are equal. This includes the resources (buffer,
6908 texture) and related parameters (offset, size) as well. To only compare
6909 layouts (binding point, pipeline stage, resource type), use
6910 \l{QRhiShaderResourceBinding::isLayoutCompatible()}{isLayoutCompatible()}
6911 instead.
6912
6913 \relates QRhiShaderResourceBinding
6914 */
6915bool operator==(const QRhiShaderResourceBinding &a, const QRhiShaderResourceBinding &b) noexcept
6916{
6917 const QRhiShaderResourceBinding::Data *da = QRhiImplementation::shaderResourceBindingData(a);
6918 const QRhiShaderResourceBinding::Data *db = QRhiImplementation::shaderResourceBindingData(b);
6919
6920 if (da == db)
6921 return true;
6922
6923
6924 if (da->binding != db->binding
6925 || da->stage != db->stage
6926 || da->type() != db->type())
6927 {
6928 return false;
6929 }
6930
6931 switch (da->type()) {
6932 case QRhiShaderResourceBinding::UniformBuffer:
6933 if (da->ubuf().buf != db->ubuf().buf
6934 || da->ubuf().offset != db->ubuf().offset
6935 || da->ubuf().maybeSize != db->ubuf().maybeSize)
6936 {
6937 return false;
6938 }
6939 break;
6940 case QRhiShaderResourceBinding::SampledTexture:
6941 if (da->stex().count() != db->stex().count())
6942 return false;
6943 for (int i = 0; i < da->stex().count(); ++i) {
6944 if (da->stex().texSamplers[i].tex != db->stex().texSamplers[i].tex
6945 || da->stex().texSamplers[i].sampler != db->stex().texSamplers[i].sampler)
6946 {
6947 return false;
6948 }
6949 }
6950 break;
6951 case QRhiShaderResourceBinding::Texture:
6952 if (da->stex().count() != db->stex().count())
6953 return false;
6954 for (int i = 0; i < da->stex().count(); ++i) {
6955 if (da->stex().texSamplers[i].tex != db->stex().texSamplers[i].tex)
6956 return false;
6957 }
6958 break;
6959 case QRhiShaderResourceBinding::Sampler:
6960 if (da->stex().texSamplers[0].sampler != db->stex().texSamplers[0].sampler)
6961 return false;
6962 break;
6963 case QRhiShaderResourceBinding::ImageLoad:
6964 case QRhiShaderResourceBinding::ImageStore:
6965 case QRhiShaderResourceBinding::ImageLoadStore:
6966 if (da->simage().tex != db->simage().tex
6967 || da->simage().level != db->simage().level)
6968 {
6969 return false;
6970 }
6971 break;
6972 case QRhiShaderResourceBinding::BufferLoad:
6973 case QRhiShaderResourceBinding::BufferStore:
6974 case QRhiShaderResourceBinding::BufferLoadStore:
6975 if (da->sbuf().buf != db->sbuf().buf
6976 || da->sbuf().offset != db->sbuf().offset
6977 || da->sbuf().maybeSize != db->sbuf().maybeSize)
6978 {
6979 return false;
6980 }
6981 break;
6982 default:
6983 Q_UNREACHABLE_RETURN(false);
6984 }
6985
6986 return true;
6987}
6988
6989/*!
6990 \return \c false if all the bindings in the two QRhiShaderResourceBinding
6991 objects \a a and \a b are equal; otherwise returns \c true.
6992
6993 \relates QRhiShaderResourceBinding
6994 */
6995bool operator!=(const QRhiShaderResourceBinding &a, const QRhiShaderResourceBinding &b) noexcept
6996{
6997 return !(a == b);
6998}
6999
7000/*!
7001 \fn size_t qHash(const QRhiShaderResourceBinding &key, size_t seed)
7002 \qhashold{QRhiShaderResourceBinding}
7003 */
7004size_t qHash(const QRhiShaderResourceBinding &b, size_t seed) noexcept
7005{
7006 const QRhiShaderResourceBinding::Data *d = QRhiImplementation::shaderResourceBindingData(b);
7007 QtPrivate::QHashCombineWithSeed hash(seed);
7008 seed = hash(seed, d->binding);
7009 seed = hash(seed, d->stage);
7010 seed = hash(seed, d->type());
7011 switch (d->type()) {
7012 case QRhiShaderResourceBinding::UniformBuffer:
7013 seed = hash(seed, reinterpret_cast<quintptr>(d->ubuf().buf));
7014 break;
7015 case QRhiShaderResourceBinding::SampledTexture:
7016 seed = hash(seed, reinterpret_cast<quintptr>(d->stex().texSamplers[0].tex));
7017 seed = hash(seed, reinterpret_cast<quintptr>(d->stex().texSamplers[0].sampler));
7018 break;
7019 case QRhiShaderResourceBinding::Texture:
7020 seed = hash(seed, reinterpret_cast<quintptr>(d->stex().texSamplers[0].tex));
7021 break;
7022 case QRhiShaderResourceBinding::Sampler:
7023 seed = hash(seed, reinterpret_cast<quintptr>(d->stex().texSamplers[0].sampler));
7024 break;
7025 case QRhiShaderResourceBinding::ImageLoad:
7026 case QRhiShaderResourceBinding::ImageStore:
7027 case QRhiShaderResourceBinding::ImageLoadStore:
7028 seed = hash(seed, reinterpret_cast<quintptr>(d->simage().tex));
7029 break;
7030 case QRhiShaderResourceBinding::BufferLoad:
7031 case QRhiShaderResourceBinding::BufferStore:
7032 case QRhiShaderResourceBinding::BufferLoadStore:
7033 seed = hash(seed, reinterpret_cast<quintptr>(d->sbuf().buf));
7034 break;
7035 }
7036 return seed;
7037}
7038
7039#ifndef QT_NO_DEBUG_STREAM
7040QDebug operator<<(QDebug dbg, const QRhiShaderResourceBinding &b)
7041{
7042 QDebugStateSaver saver(dbg);
7043 const QRhiShaderResourceBinding::Data *d = QRhiImplementation::shaderResourceBindingData(b);
7044 dbg.nospace() << "QRhiShaderResourceBinding("
7045 << "binding=" << d->binding
7046 << " stage=" << d->stage
7047 << " type=" << d->type();
7048 switch (d->type()) {
7049 case QRhiShaderResourceBinding::UniformBuffer:
7050 dbg.nospace() << " UniformBuffer("
7051 << "buffer=" << d->ubuf().buf
7052 << " offset=" << d->ubuf().offset
7053 << " maybeSize=" << d->ubuf().maybeSize
7054 << ')';
7055 break;
7056 case QRhiShaderResourceBinding::SampledTexture:
7057 dbg.nospace() << " SampledTextures("
7058 << "count=" << d->stex().count();
7059 for (int i = 0; i < d->stex().count(); ++i) {
7060 dbg.nospace() << " texture=" << d->stex().texSamplers[i].tex
7061 << " sampler=" << d->stex().texSamplers[i].sampler;
7062 }
7063 dbg.nospace() << ')';
7064 break;
7065 case QRhiShaderResourceBinding::Texture:
7066 dbg.nospace() << " Textures("
7067 << "count=" << d->stex().count();
7068 for (int i = 0; i < d->stex().count(); ++i)
7069 dbg.nospace() << " texture=" << d->stex().texSamplers[i].tex;
7070 dbg.nospace() << ')';
7071 break;
7072 case QRhiShaderResourceBinding::Sampler:
7073 dbg.nospace() << " Sampler("
7074 << " sampler=" << d->stex().texSamplers[0].sampler
7075 << ')';
7076 break;
7077 case QRhiShaderResourceBinding::ImageLoad:
7078 dbg.nospace() << " ImageLoad("
7079 << "texture=" << d->simage().tex
7080 << " level=" << d->simage().level
7081 << ')';
7082 break;
7083 case QRhiShaderResourceBinding::ImageStore:
7084 dbg.nospace() << " ImageStore("
7085 << "texture=" << d->simage().tex
7086 << " level=" << d->simage().level
7087 << ')';
7088 break;
7089 case QRhiShaderResourceBinding::ImageLoadStore:
7090 dbg.nospace() << " ImageLoadStore("
7091 << "texture=" << d->simage().tex
7092 << " level=" << d->simage().level
7093 << ')';
7094 break;
7095 case QRhiShaderResourceBinding::BufferLoad:
7096 dbg.nospace() << " BufferLoad("
7097 << "buffer=" << d->sbuf().buf
7098 << " offset=" << d->sbuf().offset
7099 << " maybeSize=" << d->sbuf().maybeSize
7100 << ')';
7101 break;
7102 case QRhiShaderResourceBinding::BufferStore:
7103 dbg.nospace() << " BufferStore("
7104 << "buffer=" << d->sbuf().buf
7105 << " offset=" << d->sbuf().offset
7106 << " maybeSize=" << d->sbuf().maybeSize
7107 << ')';
7108 break;
7109 case QRhiShaderResourceBinding::BufferLoadStore:
7110 dbg.nospace() << " BufferLoadStore("
7111 << "buffer=" << d->sbuf().buf
7112 << " offset=" << d->sbuf().offset
7113 << " maybeSize=" << d->sbuf().maybeSize
7114 << ')';
7115 break;
7116 default:
7117 dbg.nospace() << " UNKNOWN()";
7118 break;
7119 }
7120 dbg.nospace() << ')';
7121 return dbg;
7122}
7123#endif
7124
7125#ifndef QT_NO_DEBUG_STREAM
7126QDebug operator<<(QDebug dbg, const QRhiShaderResourceBindings &srb)
7127{
7128 QDebugStateSaver saver(dbg);
7129 dbg.nospace() << "QRhiShaderResourceBindings("
7130 << srb.m_bindings
7131 << ')';
7132 return dbg;
7133}
7134#endif
7135
7136/*!
7137 \class QRhiGraphicsPipeline
7138 \inmodule QtGuiPrivate
7139 \inheaderfile rhi/qrhi.h
7140 \since 6.6
7141 \brief Graphics pipeline state resource.
7142
7143 Represents a graphics pipeline. What exactly this map to in the underlying
7144 native graphics API, varies. Where there is a concept of pipeline objects,
7145 for example with Vulkan, the QRhi backend will create such an object upon
7146 calling create(). Elsewhere, for example with OpenGL, the
7147 QRhiGraphicsPipeline may merely collect the various state, and create()'s
7148 main task is to set up the corresponding shader program, but deferring
7149 looking at any of the requested state to a later point.
7150
7151 As with all QRhiResource subclasses, the two-phased initialization pattern
7152 applies: setting any values via the setters, for example setDepthTest(), is
7153 only effective after calling create(). Avoid changing any values once the
7154 QRhiGraphicsPipeline has been initialized via create(). To change some
7155 state, set the new value and call create() again. However, that will
7156 effectively release all underlying native resources and create new ones. As
7157 a result, it may be a heavy, expensive operation. Rather, prefer creating
7158 multiple pipelines with the different states, and
7159 \l{QRhiCommandBuffer::setGraphicsPipeline()}{switch between them} when
7160 recording the render pass.
7161
7162 \note Setting the shader stages is mandatory. There must be at least one
7163 stage, and there must be a vertex stage.
7164
7165 \note Setting the shader resource bindings is mandatory. The referenced
7166 QRhiShaderResourceBindings must already have create() called on it by the
7167 time create() is called. Associating with a QRhiShaderResourceBindings that
7168 has no bindings is also valid, as long as no shader in any stage expects any
7169 resources. Using a QRhiShaderResourceBindings object that does not specify
7170 any actual resources (i.e., the buffers, textures, etc. for the binding
7171 points are set to \nullptr) is valid as well, as long as a
7172 \l{QRhiShaderResourceBindings::isLayoutCompatible()}{layout-compatible}
7173 QRhiShaderResourceBindings, that specifies resources for all the bindings,
7174 is going to be set via
7175 \l{QRhiCommandBuffer::setShaderResources()}{setShaderResources()} when
7176 recording the render pass.
7177
7178 \note Setting the render pass descriptor is mandatory. To obtain a
7179 QRhiRenderPassDescriptor that can be passed to setRenderPassDescriptor(),
7180 use either QRhiTextureRenderTarget::newCompatibleRenderPassDescriptor() or
7181 QRhiSwapChain::newCompatibleRenderPassDescriptor().
7182
7183 \note Setting the vertex input layout is mandatory.
7184
7185 \note sampleCount() defaults to 1 and must match the sample count of the
7186 render target's color and depth stencil attachments.
7187
7188 \note The depth test, depth write, and stencil test are disabled by
7189 default. The face culling mode defaults to no culling.
7190
7191 \note stencilReadMask() and stencilWriteMask() apply to both faces. They
7192 both default to 0xFF.
7193
7194 \section1 Example usage
7195
7196 All settings of a graphics pipeline have defaults which might be suitable
7197 to many applications. Therefore a minimal example of creating a graphics
7198 pipeline could be the following. This assumes that the vertex shader takes
7199 a single \c{vec3 position} input at the input location 0. With the
7200 QRhiShaderResourceBindings and QRhiRenderPassDescriptor objects, plus the
7201 QShader collections for the vertex and fragment stages, a pipeline could be
7202 created like this:
7203
7204 \code
7205 QRhiShaderResourceBindings *srb;
7206 QRhiRenderPassDescriptor *rpDesc;
7207 QShader vs, fs;
7208 // ...
7209
7210 QRhiVertexInputLayout inputLayout;
7211 inputLayout.setBindings({ { 3 * sizeof(float) } });
7212 inputLayout.setAttributes({ { 0, 0, QRhiVertexInputAttribute::Float3, 0 } });
7213
7214 QRhiGraphicsPipeline *ps = rhi->newGraphicsPipeline();
7215 ps->setShaderStages({ { QRhiShaderStage::Vertex, vs }, { QRhiShaderStage::Fragment, fs } });
7216 ps->setVertexInputLayout(inputLayout);
7217 ps->setShaderResourceBindings(srb);
7218 ps->setRenderPassDescriptor(rpDesc);
7219 if (!ps->create()) { error(); }
7220 \endcode
7221
7222 The above code creates a pipeline object that uses the defaults for many
7223 settings and states. For example, it will use a \l Triangles topology, no
7224 backface culling, blending is disabled but color write is enabled for all
7225 four channels, depth test/write are disabled, stencil operations are
7226 disabled.
7227
7228 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
7229 for details.
7230
7231 \sa QRhiCommandBuffer, QRhi
7232 */
7233
7234/*!
7235 \enum QRhiGraphicsPipeline::Flag
7236
7237 Flag values for describing the dynamic state of the pipeline, and other
7238 options. The viewport is always dynamic.
7239
7240 \value UsesBlendConstants Indicates that a blend color constant will be set
7241 via QRhiCommandBuffer::setBlendConstants()
7242
7243 \value UsesStencilRef Indicates that a stencil reference value will be set
7244 via QRhiCommandBuffer::setStencilRef(). Pipelines without this flag use a
7245 stencil reference value of 0.
7246
7247 \value UsesScissor Indicates that a scissor rectangle will be set via
7248 QRhiCommandBuffer::setScissor()
7249
7250 \value CompileShadersWithDebugInfo Requests compiling shaders with debug
7251 information enabled. This is relevant only when runtime shader compilation
7252 from source code is involved, and only when the underlying infrastructure
7253 supports this. With concrete examples, this is not relevant with Vulkan and
7254 SPIR-V, because the GLSL-to-SPIR-V compilation does not happen at run
7255 time. On the other hand, consider Direct3D and HLSL, where there are
7256 multiple options: when the QShader packages ship with pre-compiled bytecode
7257 (\c DXBC), debug information is to be requested through the tool that
7258 generates the \c{.qsb} file, similarly to the case of Vulkan and
7259 SPIR-V. However, when having HLSL source code in the pre- or
7260 runtime-generated QShader packages, the first phase of compilation (HLSL
7261 source to intermediate format) happens at run time too, with this flag taken
7262 into account. Debug information is relevant in particular with tools like
7263 RenderDoc since it allows seeing the original source code when investigating
7264 the pipeline and when performing vertex or fragment shader debugging.
7265
7266 \value UsesShadingRate Indicates that a per-draw (per-pipeline) shading rate
7267 value will be set via QRhiCommandBuffer::setShadingRate(). Not specifying
7268 this flag and still calling setShadingRate() may lead to varying, unexpected
7269 results depending on the underlying graphics API.
7270
7271 \value [since 6.12] UsesIndirectDraws Indicates that this pipeline will be used with
7272 indirect draw calls (QRhiCommandBuffer::drawIndirect() or
7273 QRhiCommandBuffer::drawIndexedIndirect()). Setting this flag allows the
7274 Metal backend to use Indirect Command Buffers (ICB) for GPU-driven
7275 rendering, which significantly reduces CPU overhead for large draw counts.
7276 Not setting this flag when using indirect draws is still functional but may
7277 result in less optimal performance on Metal: QRhi::DrawIndirectMulti reports
7278 what the device can do, without knowing about individual pipelines, so a
7279 pipeline without this flag falls back to CPU-side looping even when that
7280 feature is reported as supported. The exception is
7281 QRhiCommandBuffer::drawIndirectCount() and
7282 QRhiCommandBuffer::drawIndexedIndirectCount(), for which the flag is
7283 mandatory on Metal because there is no non-ICB implementation of those. This
7284 flag has no effect on other backends.
7285 */
7286
7287/*!
7288 \enum QRhiGraphicsPipeline::Topology
7289 Specifies the primitive topology
7290
7291 \value Triangles (default)
7292 \value TriangleStrip
7293 \value TriangleFan (only available if QRhi::TriangleFanTopology is supported)
7294 \value Lines
7295 \value LineStrip
7296 \value Points
7297
7298 \value Patches (only available if QRhi::Tessellation is supported, and
7299 requires the tessellation stages to be present in the pipeline)
7300 */
7301
7302/*!
7303 \enum QRhiGraphicsPipeline::CullMode
7304 Specifies the culling mode
7305
7306 \value None No culling (default)
7307 \value Front Cull front faces
7308 \value Back Cull back faces
7309 */
7310
7311/*!
7312 \enum QRhiGraphicsPipeline::FrontFace
7313 Specifies the front face winding order
7314
7315 \value CCW Counter clockwise (default)
7316 \value CW Clockwise
7317 */
7318
7319/*!
7320 \enum QRhiGraphicsPipeline::ColorMaskComponent
7321 Flag values for specifying the color write mask
7322
7323 \value R
7324 \value G
7325 \value B
7326 \value A
7327 */
7328
7329/*!
7330 \enum QRhiGraphicsPipeline::BlendFactor
7331 Specifies the blend factor
7332
7333 \value Zero
7334 \value One
7335 \value SrcColor
7336 \value OneMinusSrcColor
7337 \value DstColor
7338 \value OneMinusDstColor
7339 \value SrcAlpha
7340 \value OneMinusSrcAlpha
7341 \value DstAlpha
7342 \value OneMinusDstAlpha
7343 \value ConstantColor
7344 \value OneMinusConstantColor
7345 \value ConstantAlpha
7346 \value OneMinusConstantAlpha
7347 \value SrcAlphaSaturate
7348 \value Src1Color
7349 \value OneMinusSrc1Color
7350 \value Src1Alpha
7351 \value OneMinusSrc1Alpha
7352 */
7353
7354/*!
7355 \enum QRhiGraphicsPipeline::BlendOp
7356 Specifies the blend operation
7357
7358 \value Add
7359 \value Subtract
7360 \value ReverseSubtract
7361 \value Min
7362 \value Max
7363 */
7364
7365/*!
7366 \enum QRhiGraphicsPipeline::CompareOp
7367 Specifies the depth or stencil comparison function
7368
7369 \value Never
7370 \value Less (default for depth)
7371 \value Equal
7372 \value LessOrEqual
7373 \value Greater
7374 \value NotEqual
7375 \value GreaterOrEqual
7376 \value Always (default for stencil)
7377 */
7378
7379/*!
7380 \enum QRhiGraphicsPipeline::StencilOp
7381 Specifies the stencil operation
7382
7383 \value StencilZero
7384 \value Keep (default)
7385 \value Replace
7386 \value IncrementAndClamp
7387 \value DecrementAndClamp
7388 \value Invert
7389 \value IncrementAndWrap
7390 \value DecrementAndWrap
7391 */
7392
7393/*!
7394 \enum QRhiGraphicsPipeline::PolygonMode
7395 \brief Specifies the polygon rasterization mode
7396
7397 Polygon Mode (Triangle Fill Mode in Metal, Fill Mode in D3D) specifies
7398 the fill mode used when rasterizing polygons. Polygons may be drawn as
7399 solids (Fill), or as a wire mesh (Line).
7400
7401 Support for non-fill polygon modes is optional and is indicated by the
7402 QRhi::NonFillPolygonMode feature. With OpenGL ES and some Vulkan
7403 implementations the feature will likely be reported as unsupported, which
7404 then means values other than Fill cannot be used.
7405
7406 \value Fill The interior of the polygon is filled (default)
7407 \value Line Boundary edges of the polygon are drawn as line segments.
7408 */
7409
7410/*!
7411 \struct QRhiGraphicsPipeline::TargetBlend
7412 \inmodule QtGuiPrivate
7413 \inheaderfile rhi/qrhi.h
7414 \since 6.6
7415 \brief Describes the blend state for one color attachment.
7416
7417 Defaults to color write enabled, blending disabled. The blend values are
7418 set up for pre-multiplied alpha (One, OneMinusSrcAlpha, One,
7419 OneMinusSrcAlpha) by default. This means that to get the alpha blending
7420 mode Qt Quick uses, it is enough to set the \c enable flag to true while
7421 leaving other values at their defaults.
7422
7423 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
7424 for details.
7425 */
7426
7427/*!
7428 \variable QRhiGraphicsPipeline::TargetBlend::colorWrite
7429 */
7430
7431/*!
7432 \variable QRhiGraphicsPipeline::TargetBlend::enable
7433 */
7434
7435/*!
7436 \variable QRhiGraphicsPipeline::TargetBlend::srcColor
7437 */
7438
7439/*!
7440 \variable QRhiGraphicsPipeline::TargetBlend::dstColor
7441 */
7442
7443/*!
7444 \variable QRhiGraphicsPipeline::TargetBlend::opColor
7445 */
7446
7447/*!
7448 \variable QRhiGraphicsPipeline::TargetBlend::srcAlpha
7449 */
7450
7451/*!
7452 \variable QRhiGraphicsPipeline::TargetBlend::dstAlpha
7453 */
7454
7455/*!
7456 \variable QRhiGraphicsPipeline::TargetBlend::opAlpha
7457 */
7458
7459/*!
7460 \struct QRhiGraphicsPipeline::StencilOpState
7461 \inmodule QtGuiPrivate
7462 \inheaderfile rhi/qrhi.h
7463 \since 6.6
7464 \brief Describes the stencil operation state.
7465
7466 The default-constructed StencilOpState has the following set:
7467 \list
7468 \li failOp - \l Keep
7469 \li depthFailOp - \l Keep
7470 \li passOp - \l Keep
7471 \li compareOp \l Always
7472 \endlist
7473
7474 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
7475 for details.
7476 */
7477
7478/*!
7479 \variable QRhiGraphicsPipeline::StencilOpState::failOp
7480 */
7481
7482/*!
7483 \variable QRhiGraphicsPipeline::StencilOpState::depthFailOp
7484 */
7485
7486/*!
7487 \variable QRhiGraphicsPipeline::StencilOpState::passOp
7488 */
7489
7490/*!
7491 \variable QRhiGraphicsPipeline::StencilOpState::compareOp
7492 */
7493
7494/*!
7495 \internal
7496 */
7497QRhiGraphicsPipeline::QRhiGraphicsPipeline(QRhiImplementation *rhi)
7498 : QRhiResource(rhi)
7499{
7500}
7501
7502/*!
7503 \return the resource type.
7504 */
7505QRhiResource::Type QRhiGraphicsPipeline::resourceType() const
7506{
7507 return GraphicsPipeline;
7508}
7509
7510/*!
7511 \fn virtual bool QRhiGraphicsPipeline::create() = 0
7512
7513 Creates the corresponding native graphics resources. If there are already
7514 resources present due to an earlier create() with no corresponding
7515 destroy(), then destroy() is called implicitly first.
7516
7517 \return \c true when successful, \c false when a graphics operation failed.
7518 Regardless of the return value, calling destroy() is always safe.
7519
7520 \note This may be, depending on the underlying graphics API, an expensive
7521 operation, especially when shaders get compiled/optimized from source or
7522 from an intermediate bytecode format to the GPU's own instruction set.
7523 Where applicable, the QRhi backend automatically sets up the relevant
7524 non-persistent facilities to accelerate this, for example the Vulkan
7525 backend automatically creates a \c VkPipelineCache to improve data reuse
7526 during the lifetime of the application.
7527
7528 \note Drivers may also employ various persistent (disk-based) caching
7529 strategies for shader and pipeline data, which is hidden to and is outside
7530 of Qt's control. In some cases, depending on the graphics API and the QRhi
7531 backend, there are facilities within QRhi for manually managing such a
7532 cache, allowing the retrieval of a serializable blob that can then be
7533 reloaded in the future runs of the application to ensure faster pipeline
7534 creation times. See QRhi::pipelineCacheData() and
7535 QRhi::setPipelineCacheData() for details. Note also that when working with
7536 a QRhi instance managed by a higher level Qt framework, such as Qt Quick,
7537 it is possible that such disk-based caching is taken care of automatically,
7538 for example QQuickWindow uses a disk-based pipeline cache by default (which
7539 comes in addition to any driver-level caching).
7540 */
7541
7542/*!
7543 \fn QRhiGraphicsPipeline::Flags QRhiGraphicsPipeline::flags() const
7544 \return the currently set flags.
7545 */
7546
7547/*!
7548 \fn void QRhiGraphicsPipeline::setFlags(Flags f)
7549 Sets the flags \a f.
7550 */
7551
7552/*!
7553 \fn QRhiGraphicsPipeline::Topology QRhiGraphicsPipeline::topology() const
7554 \return the currently set primitive topology.
7555 */
7556
7557/*!
7558 \fn void QRhiGraphicsPipeline::setTopology(Topology t)
7559 Sets the primitive topology \a t.
7560 */
7561
7562/*!
7563 \fn QRhiGraphicsPipeline::CullMode QRhiGraphicsPipeline::cullMode() const
7564 \return the currently set face culling mode.
7565 */
7566
7567/*!
7568 \fn void QRhiGraphicsPipeline::setCullMode(CullMode mode)
7569 Sets the specified face culling \a mode.
7570 */
7571
7572/*!
7573 \fn QRhiGraphicsPipeline::FrontFace QRhiGraphicsPipeline::frontFace() const
7574 \return the currently set front face mode.
7575 */
7576
7577/*!
7578 \fn void QRhiGraphicsPipeline::setFrontFace(FrontFace f)
7579 Sets the front face mode \a f.
7580 */
7581
7582/*!
7583 \fn void QRhiGraphicsPipeline::setTargetBlends(std::initializer_list<TargetBlend> list)
7584
7585 Sets the \a list of render target blend settings. This is a list because
7586 when multiple render targets are used (i.e., a QRhiTextureRenderTarget with
7587 more than one QRhiColorAttachment), there needs to be a TargetBlend
7588 structure per render target (color attachment).
7589
7590 By default there is one default-constructed TargetBlend set.
7591
7592 \sa QRhi::MaxColorAttachments
7593 */
7594
7595/*!
7596 \fn template<typename InputIterator> void QRhiGraphicsPipeline::setTargetBlends(InputIterator first, InputIterator last)
7597 Sets the list of render target blend settings from the iterators \a first and \a last.
7598 */
7599
7600/*!
7601 \fn const QRhiGraphicsPipeline::TargetBlend *QRhiGraphicsPipeline::cbeginTargetBlends() const
7602 \return a const iterator pointing to the first item in the render target blend setting list.
7603 */
7604
7605/*!
7606 \fn const QRhiGraphicsPipeline::TargetBlend *QRhiGraphicsPipeline::cendTargetBlends() const
7607 \return a const iterator pointing just after the last item in the render target blend setting list.
7608 */
7609
7610/*!
7611 \fn const QRhiGraphicsPipeline::TargetBlend *QRhiGraphicsPipeline::targetBlendAt(qsizetype index) const
7612 \return the render target blend setting at the specified \a index.
7613 */
7614
7615/*!
7616 \fn qsizetype QRhiGraphicsPipeline::targetBlendCount() const
7617 \return the number of render target blend settings.
7618 */
7619
7620/*!
7621 \fn bool QRhiGraphicsPipeline::hasDepthTest() const
7622 \return true if depth testing is enabled.
7623 */
7624
7625/*!
7626 \fn void QRhiGraphicsPipeline::setDepthTest(bool enable)
7627
7628 Enables or disables depth testing based on \a enable. Both depth test and
7629 the writing out of depth data are disabled by default.
7630
7631 \sa setDepthWrite()
7632 */
7633
7634/*!
7635 \fn bool QRhiGraphicsPipeline::hasDepthWrite() const
7636 \return true if depth write is enabled.
7637 */
7638
7639/*!
7640 \fn void QRhiGraphicsPipeline::setDepthWrite(bool enable)
7641
7642 Controls the writing out of depth data into the depth buffer based on
7643 \a enable. By default this is disabled. Depth write is typically enabled
7644 together with the depth test.
7645
7646 \note Enabling depth write without having depth testing enabled may not
7647 lead to the desired result, and should be avoided.
7648
7649 \sa setDepthTest()
7650 */
7651
7652/*!
7653 \fn bool QRhiGraphicsPipeline::hasDepthClamp() const
7654 \return true if depth clamp is enabled.
7655
7656 \since 6.11
7657 */
7658
7659/*!
7660 \fn void QRhiGraphicsPipeline::setDepthClamp(bool enable)
7661
7662 Enables depth clamping when \a enable is true. When depth clamping is
7663 enabled, primitives that would otherwise be clipped by the near or far
7664 clip plane are rasterized and their depth values are clamped to the
7665 depth range. When disabled (the default), such primitives are clipped.
7666
7667 \note This setting is ignored when the QRhi::DepthClamp feature is
7668 reported as unsupported.
7669
7670 \since 6.11
7671 */
7672
7673/*!
7674 \fn QRhiGraphicsPipeline::CompareOp QRhiGraphicsPipeline::depthOp() const
7675 \return the depth comparison function.
7676 */
7677
7678/*!
7679 \fn void QRhiGraphicsPipeline::setDepthOp(CompareOp op)
7680 Sets the depth comparison function \a op.
7681 */
7682
7683/*!
7684 \fn bool QRhiGraphicsPipeline::hasStencilTest() const
7685 \return true if stencil testing is enabled.
7686 */
7687
7688/*!
7689 \fn void QRhiGraphicsPipeline::setStencilTest(bool enable)
7690 Enables or disables stencil tests based on \a enable.
7691 By default this is disabled.
7692 */
7693
7694/*!
7695 \fn QRhiGraphicsPipeline::StencilOpState QRhiGraphicsPipeline::stencilFront() const
7696 \return the current stencil test state for front faces.
7697 */
7698
7699/*!
7700 \fn void QRhiGraphicsPipeline::setStencilFront(const StencilOpState &state)
7701 Sets the stencil test \a state for front faces.
7702 */
7703
7704/*!
7705 \fn QRhiGraphicsPipeline::StencilOpState QRhiGraphicsPipeline::stencilBack() const
7706 \return the current stencil test state for back faces.
7707 */
7708
7709/*!
7710 \fn void QRhiGraphicsPipeline::setStencilBack(const StencilOpState &state)
7711 Sets the stencil test \a state for back faces.
7712 */
7713
7714/*!
7715 \fn quint32 QRhiGraphicsPipeline::stencilReadMask() const
7716 \return the currrent stencil read mask.
7717 */
7718
7719/*!
7720 \fn void QRhiGraphicsPipeline::setStencilReadMask(quint32 mask)
7721 Sets the stencil read \a mask. The default value is 0xFF.
7722 */
7723
7724/*!
7725 \fn quint32 QRhiGraphicsPipeline::stencilWriteMask() const
7726 \return the current stencil write mask.
7727 */
7728
7729/*!
7730 \fn void QRhiGraphicsPipeline::setStencilWriteMask(quint32 mask)
7731 Sets the stencil write \a mask. The default value is 0xFF.
7732 */
7733
7734/*!
7735 \fn int QRhiGraphicsPipeline::sampleCount() const
7736 \return the currently set sample count. 1 means no multisample antialiasing.
7737 */
7738
7739/*!
7740 \fn void QRhiGraphicsPipeline::setSampleCount(int s)
7741
7742 Sets the sample count. Typical values for \a s are 1, 4, or 8. The pipeline
7743 must always be compatible with the render target, i.e. the sample counts
7744 must match.
7745
7746 \sa QRhi::supportedSampleCounts()
7747 */
7748
7749/*!
7750 \fn float QRhiGraphicsPipeline::lineWidth() const
7751 \return the currently set line width. The default is 1.0f.
7752 */
7753
7754/*!
7755 \fn void QRhiGraphicsPipeline::setLineWidth(float width)
7756
7757 Sets the line \a width. If the QRhi::WideLines feature is reported as
7758 unsupported at runtime, values other than 1.0f are ignored.
7759 */
7760
7761/*!
7762 \fn int QRhiGraphicsPipeline::depthBias() const
7763 \return the currently set depth bias.
7764 */
7765
7766/*!
7767 \fn void QRhiGraphicsPipeline::setDepthBias(int bias)
7768 Sets the depth \a bias. The default value is 0.
7769 */
7770
7771/*!
7772 \fn float QRhiGraphicsPipeline::slopeScaledDepthBias() const
7773 \return the currently set slope scaled depth bias.
7774 */
7775
7776/*!
7777 \fn void QRhiGraphicsPipeline::setSlopeScaledDepthBias(float bias)
7778 Sets the slope scaled depth \a bias. The default value is 0.
7779 */
7780
7781/*!
7782 \fn void QRhiGraphicsPipeline::setShaderStages(std::initializer_list<QRhiShaderStage> list)
7783 Sets the \a list of shader stages.
7784 */
7785
7786/*!
7787 \fn template<typename InputIterator> void QRhiGraphicsPipeline::setShaderStages(InputIterator first, InputIterator last)
7788 Sets the list of shader stages from the iterators \a first and \a last.
7789 */
7790
7791/*!
7792 \fn const QRhiShaderStage *QRhiGraphicsPipeline::cbeginShaderStages() const
7793 \return a const iterator pointing to the first item in the shader stage list.
7794 */
7795
7796/*!
7797 \fn const QRhiShaderStage *QRhiGraphicsPipeline::cendShaderStages() const
7798 \return a const iterator pointing just after the last item in the shader stage list.
7799 */
7800
7801/*!
7802 \fn const QRhiShaderStage *QRhiGraphicsPipeline::shaderStageAt(qsizetype index) const
7803 \return the shader stage at the specified \a index.
7804 */
7805
7806/*!
7807 \fn qsizetype QRhiGraphicsPipeline::shaderStageCount() const
7808 \return the number of shader stages in this pipeline.
7809 */
7810
7811/*!
7812 \fn QRhiVertexInputLayout QRhiGraphicsPipeline::vertexInputLayout() const
7813 \return the currently set vertex input layout specification.
7814 */
7815
7816/*!
7817 \fn void QRhiGraphicsPipeline::setVertexInputLayout(const QRhiVertexInputLayout &layout)
7818 Specifies the vertex input \a layout.
7819 */
7820
7821/*!
7822 \fn QRhiShaderResourceBindings *QRhiGraphicsPipeline::shaderResourceBindings() const
7823 \return the currently associated QRhiShaderResourceBindings object.
7824 */
7825
7826/*!
7827 \fn void QRhiGraphicsPipeline::setShaderResourceBindings(QRhiShaderResourceBindings *srb)
7828
7829 Associates with \a srb describing the resource binding layout and the
7830 resources (QRhiBuffer, QRhiTexture) themselves. The latter is optional,
7831 because only the layout matters during pipeline creation. Therefore, the \a
7832 srb passed in here can leave the actual buffer or texture objects
7833 unspecified (\nullptr) as long as there is another,
7834 \l{QRhiShaderResourceBindings::isLayoutCompatible()}{layout-compatible}
7835 QRhiShaderResourceBindings bound via
7836 \l{QRhiCommandBuffer::setShaderResources()}{setShaderResources()} before
7837 recording the draw calls.
7838 */
7839
7840/*!
7841 \fn QRhiRenderPassDescriptor *QRhiGraphicsPipeline::renderPassDescriptor() const
7842 \return the currently set QRhiRenderPassDescriptor.
7843 */
7844
7845/*!
7846 \fn void QRhiGraphicsPipeline::setRenderPassDescriptor(QRhiRenderPassDescriptor *desc)
7847 Associates with the specified QRhiRenderPassDescriptor \a desc.
7848 */
7849
7850/*!
7851 \fn int QRhiGraphicsPipeline::patchControlPointCount() const
7852 \return the currently set patch control point count.
7853 */
7854
7855/*!
7856 \fn void QRhiGraphicsPipeline::setPatchControlPointCount(int count)
7857
7858 Sets the number of patch control points to \a count. The default value is
7859 3. This is used only when the topology is set to \l Patches.
7860 */
7861
7862/*!
7863 \fn QRhiGraphicsPipeline::PolygonMode QRhiGraphicsPipeline::polygonMode() const
7864 \return the polygon mode.
7865 */
7866
7867/*!
7868 \fn void QRhiGraphicsPipeline::setPolygonMode(PolygonMode mode)
7869 Sets the polygon \a mode. The default is Fill.
7870
7871 \sa QRhi::NonFillPolygonMode
7872 */
7873
7874/*!
7875 \fn int QRhiGraphicsPipeline::multiViewCount() const
7876 \return the view count. The default is 0, indicating no multiview rendering.
7877 \since 6.7
7878 */
7879
7880/*!
7881 \fn void QRhiGraphicsPipeline::setMultiViewCount(int count)
7882 Sets the view \a count for multiview rendering. The default is 0,
7883 indicating no multiview rendering.
7884 \a count must be 2 or larger to trigger multiview rendering.
7885
7886 Multiview is only available when the \l{QRhi::MultiView}{MultiView feature}
7887 is reported as supported. The render target must be a 2D texture array, and
7888 the color attachment for the render target must have the same \a count set.
7889
7890 See QRhiColorAttachment::setMultiViewCount() for further details on
7891 multiview rendering.
7892
7893 \since 6.7
7894 \sa QRhi::MultiView, QRhiColorAttachment::setMultiViewCount()
7895 */
7896
7897/*!
7898 \class QRhiSwapChain
7899 \inmodule QtGuiPrivate
7900 \inheaderfile rhi/qrhi.h
7901 \since 6.6
7902 \brief Swapchain resource.
7903
7904 A swapchain enables presenting rendering results to a surface. A swapchain
7905 is typically backed by a set of color buffers. Of these, one is displayed
7906 at a time.
7907
7908 Below is a typical pattern for creating and managing a swapchain and some
7909 associated resources in order to render onto a QWindow:
7910
7911 \code
7912 void init()
7913 {
7914 sc = rhi->newSwapChain();
7915 ds = rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil,
7916 QSize(), // no need to set the size here due to UsedWithSwapChainOnly
7917 1,
7918 QRhiRenderBuffer::UsedWithSwapChainOnly);
7919 sc->setWindow(window);
7920 sc->setDepthStencil(ds);
7921 rp = sc->newCompatibleRenderPassDescriptor();
7922 sc->setRenderPassDescriptor(rp);
7923 resizeSwapChain();
7924 }
7925
7926 void resizeSwapChain()
7927 {
7928 hasSwapChain = sc->createOrResize();
7929 }
7930
7931 void render()
7932 {
7933 if (!hasSwapChain || notExposed)
7934 return;
7935
7936 if (sc->currentPixelSize() != sc->surfacePixelSize() || newlyExposed) {
7937 resizeSwapChain();
7938 if (!hasSwapChain)
7939 return;
7940 newlyExposed = false;
7941 }
7942
7943 rhi->beginFrame(sc);
7944 // ...
7945 rhi->endFrame(sc);
7946 }
7947 \endcode
7948
7949 Avoid relying on QWindow resize events to resize swapchains, especially
7950 considering that surface sizes may not always fully match the QWindow
7951 reported dimensions. The safe, cross-platform approach is to do the check
7952 via surfacePixelSize() whenever starting a new frame.
7953
7954 Releasing the swapchain must happen while the QWindow and the underlying
7955 native window is fully up and running. Building on the previous example:
7956
7957 \code
7958 void releaseSwapChain()
7959 {
7960 if (hasSwapChain) {
7961 sc->destroy();
7962 hasSwapChain = false;
7963 }
7964 }
7965
7966 // assuming Window is our QWindow subclass
7967 bool Window::event(QEvent *e)
7968 {
7969 switch (e->type()) {
7970 case QEvent::UpdateRequest: // for QWindow::requestUpdate()
7971 render();
7972 break;
7973 case QEvent::PlatformSurface:
7974 if (static_cast<QPlatformSurfaceEvent *>(e)->surfaceEventType() == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed)
7975 releaseSwapChain();
7976 break;
7977 default:
7978 break;
7979 }
7980 return QWindow::event(e);
7981 }
7982 \endcode
7983
7984 Initializing the swapchain and starting to render the first frame cannot
7985 start at any time. The safe, cross-platform approach is to rely on expose
7986 events. QExposeEvent is a loosely specified event that is sent whenever a
7987 window gets mapped, obscured, and resized, depending on the platform.
7988
7989 \code
7990 void Window::exposeEvent(QExposeEvent *)
7991 {
7992 // initialize and start rendering when the window becomes usable for graphics purposes
7993 if (isExposed() && !running) {
7994 running = true;
7995 init();
7996 }
7997
7998 // stop pushing frames when not exposed or size becomes 0
7999 if ((!isExposed() || (hasSwapChain && sc->surfacePixelSize().isEmpty())) && running)
8000 notExposed = true;
8001
8002 // continue when exposed again and the surface has a valid size
8003 if (isExposed() && running && notExposed && !sc->surfacePixelSize().isEmpty()) {
8004 notExposed = false;
8005 newlyExposed = true;
8006 }
8007
8008 if (isExposed() && !sc->surfacePixelSize().isEmpty())
8009 render();
8010 }
8011 \endcode
8012
8013 Once the rendering has started, a simple way to request a new frame is
8014 QWindow::requestUpdate(). While on some platforms this is merely a small
8015 timer, on others it has a specific implementation: for instance on macOS or
8016 iOS it may be backed by
8017 \l{https://developer.apple.com/documentation/corevideo/cvdisplaylink?language=objc}{CVDisplayLink}.
8018 The example above is already prepared for update requests by handling
8019 QEvent::UpdateRequest.
8020
8021 While acting as a QRhiRenderTarget, QRhiSwapChain also manages a
8022 QRhiCommandBuffer. Calling QRhi::endFrame() submits the recorded commands
8023 and also enqueues a \c present request. The default behavior is to do this
8024 with a swap interval of 1, meaning synchronizing to the display's vertical
8025 refresh is enabled. Thus the rendering thread calling beginFrame() and
8026 endFrame() will get throttled to vsync. On some backends this can be
8027 disabled by passing QRhiSwapChain:NoVSync in flags().
8028
8029 Multisampling (MSAA) is handled transparently to the applications when
8030 requested via setSampleCount(). Where applicable, QRhiSwapChain will take
8031 care of creating additional color buffers and issuing a multisample resolve
8032 command at the end of a frame. For OpenGL, it is necessary to request the
8033 appropriate sample count also via QSurfaceFormat, by calling
8034 QSurfaceFormat::setDefaultFormat() before initializing the QRhi.
8035
8036 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
8037 for details.
8038 */
8039
8040/*!
8041 \enum QRhiSwapChain::Flag
8042 Flag values to describe swapchain properties
8043
8044 \value SurfaceHasPreMulAlpha Indicates that the target surface has
8045 transparency with premultiplied alpha. For example, this is what Qt Quick
8046 uses when the alpha channel is enabled on the target QWindow, because the
8047 scenegraph rendrerer always outputs fragments with alpha multiplied into
8048 the red, green, and blue values. To ensure identical behavior across
8049 platforms, always set QSurfaceFormat::alphaBufferSize() to a non-zero value
8050 on the target QWindow whenever this flag is set on the swapchain.
8051
8052 \value SurfaceHasNonPreMulAlpha Indicates the target surface has
8053 transparency with non-premultiplied alpha. Be aware that this may not be
8054 supported on some systems, if the system compositor always expects content
8055 with premultiplied alpha. In that case the behavior with this flag set is
8056 expected to be equivalent to SurfaceHasPreMulAlpha.
8057
8058 \value sRGB Requests to pick an sRGB format for the swapchain's color
8059 buffers and/or render target views, where applicable. Note that this
8060 implies that sRGB framebuffer update and blending will get enabled for all
8061 content targeting this swapchain, and opting out is not possible. For
8062 OpenGL, set \l{QSurfaceFormat::sRGBColorSpace}{sRGBColorSpace} on the
8063 QSurfaceFormat of the QWindow in addition. Applicable only when the
8064 swapchain format is set to QRhiSwapChain::SDR.
8065
8066 \value UsedAsTransferSource Indicates the swapchain will be used as the
8067 source of a readback in QRhiResourceUpdateBatch::readBackTexture().
8068
8069 \value NoVSync Requests disabling waiting for vertical sync, also avoiding
8070 throttling the rendering thread. The behavior is backend specific and
8071 applicable only where it is possible to control this. Some may ignore the
8072 request altogether. For OpenGL, try instead setting the swap interval to 0
8073 on the QWindow via QSurfaceFormat::setSwapInterval().
8074
8075 \value MinimalBufferCount Requests creating the swapchain with the minimum
8076 number of buffers, which is in practice 2, unless the graphics
8077 implementation has a higher minimum number than that. Only applicable with
8078 backends where such control is available via the graphics API, for example,
8079 Vulkan. By default it is up to the backend to decide what number of buffers
8080 it requests (in practice this is almost always either 2 or 3), and it is
8081 not the applications' concern. However, on Vulkan for instance the backend
8082 will likely prefer the higher number (3), for example to avoid odd
8083 performance issues with some Vulkan implementations on mobile devices. It
8084 could be that on some platforms it can prove to be beneficial to force the
8085 lower buffer count (2), so this flag allows forcing that. Note that all
8086 this has no effect on the number of frames kept in flight, so the CPU
8087 (QRhi) will still prepare frames at most \c{N - 1} frames ahead of the GPU,
8088 even when the swapchain image buffer count larger than \c N. (\c{N} =
8089 QRhi::FramesInFlight and typically 2).
8090 */
8091
8092/*!
8093 \enum QRhiSwapChain::Format
8094 Describes the swapchain format. The default format is SDR.
8095
8096 This enum is used with
8097 \l{QRhiSwapChain::isFormatSupported()}{isFormatSupported()} to check
8098 upfront if creating the swapchain with the given format is supported by the
8099 platform and the window's associated screen, and with
8100 \l{QRhiSwapChain::setFormat()}{setFormat()}
8101 to set the requested format in the swapchain before calling
8102 \l{QRhiSwapChain::createOrResize()}{createOrResize()} for the first time.
8103
8104 \value SDR 8-bit RGBA or BGRA, depending on the backend and platform. With
8105 OpenGL ES in particular, it could happen that the platform provides less
8106 than 8 bits (e.g. due to EGL and the QSurfaceFormat choosing a 565 or 444
8107 format - this is outside the control of QRhi). Standard dynamic range. May
8108 be combined with setting the QRhiSwapChain::sRGB flag.
8109
8110 \value HDRExtendedSrgbLinear 16-bit float RGBA, high dynamic range,
8111 extended linear sRGB (scRGB) color space. This involves Rec. 709 primaries
8112 (same as SDR/sRGB) and linear colors. Conversion to the display's native
8113 color space (such as, HDR10) is performed by the windowing system. On
8114 Windows this is the canonical color space of the system compositor, and is
8115 the recommended format for HDR swapchains in general on desktop platforms.
8116
8117 \value HDR10 10-bit unsigned int RGB or BGR with 2 bit alpha, high dynamic
8118 range, HDR10 (Rec. 2020) color space with an ST2084 PQ transfer function.
8119
8120 \value HDRExtendedDisplayP3Linear 16-bit float RGBA, high dynamic range,
8121 extended linear Display P3 color space. The primary choice for HDR on
8122 platforms such as iOS and VisionOS.
8123 */
8124
8125/*!
8126 \internal
8127 */
8128QRhiSwapChain::QRhiSwapChain(QRhiImplementation *rhi)
8129 : QRhiResource(rhi)
8130{
8131}
8132
8133/*!
8134 \return the resource type.
8135 */
8136QRhiResource::Type QRhiSwapChain::resourceType() const
8137{
8138 return SwapChain;
8139}
8140
8141/*!
8142 \fn QSize QRhiSwapChain::currentPixelSize() const
8143
8144 \return the size with which the swapchain was last successfully built. Use
8145 this to decide if createOrResize() needs to be called again: if
8146 \c{currentPixelSize() != surfacePixelSize()} then the swapchain needs to be
8147 resized.
8148
8149 \note Typical rendering logic will call this function to get the output
8150 size when starting to prepare a new frame, and base dependent calculations
8151 (such as, the viewport) on the size returned from this function.
8152
8153 While in many cases the value is the same as \c{QWindow::size() *
8154 QWindow::devicePixelRatio()}, relying on the QWindow-reported size is not
8155 guaranteed to be correct on all platforms and graphics API implementations.
8156 Using this function is therefore strongly recommended whenever there is a
8157 need to identify the dimensions, in pixels, of the output layer or surface.
8158
8159 This also has the added benefit of avoiding potential data races when QRhi
8160 is used on a dedicated rendering thread, because the need to call QWindow
8161 functions, that may then access data updated on the main thread, is
8162 avoided.
8163
8164 \sa surfacePixelSize()
8165 */
8166
8167/*!
8168 \fn virtual QSize QRhiSwapChain::surfacePixelSize() = 0
8169
8170 \return The size of the window's associated surface or layer.
8171
8172 \warning Do not assume this is the same as \c{QWindow::size() *
8173 QWindow::devicePixelRatio()}. With some graphics APIs and windowing system
8174 interfaces (for example, Vulkan) there is a theoretical possibility for a
8175 surface to assume a size different from the associated window. To support
8176 these cases, \b{rendering logic must always base size-derived calculations
8177 (such as, viewports) on the size reported from QRhiSwapChain, and never on
8178 the size queried from QWindow}.
8179
8180 \note \b{Can also be called before createOrResize(), if at least window() is
8181 already set. This in combination with currentPixelSize() allows to detect
8182 when a swapchain needs to be resized.} However, watch out for the fact that
8183 the size of the underlying native object (surface, layer, or similar) is
8184 "live", so whenever this function is called, it returns the latest value
8185 reported by the underlying implementation, without any atomicity guarantee.
8186 Therefore, using this function to determine pixel sizes for graphics
8187 resources that are used in a frame is strongly discouraged. Rely on
8188 currentPixelSize() instead which returns a size that is atomic and will not
8189 change between createOrResize() invocations.
8190
8191 \note For depth-stencil buffers used in combination with the swapchain's
8192 color buffers, it is strongly recommended to rely on the automatic sizing
8193 and rebuilding behavior provided by the
8194 QRhiRenderBuffer:UsedWithSwapChainOnly flag. Avoid querying the surface
8195 size via this function just to get a size that can be passed to
8196 QRhiRenderBuffer::setPixelSize() as that would suffer from the lack of
8197 atomicity as described above.
8198
8199 \sa currentPixelSize()
8200 */
8201
8202/*!
8203 \fn virtual bool QRhiSwapChain::isFormatSupported(Format f) = 0
8204
8205 \return true if the given swapchain format \a f is supported. SDR is always
8206 supported.
8207
8208 \note Can be called independently of createOrResize(), but window() must
8209 already be set. Calling without the window set may lead to unexpected
8210 results depending on the backend and platform (most likely false for any
8211 HDR format), because HDR format support is usually tied to the output
8212 (screen) to which the swapchain's associated window belongs at any given
8213 time. If the result is true for a HDR format, then creating the swapchain
8214 with that format is expected to succeed as long as the window is not moved
8215 to another screen in the meantime.
8216
8217 The main use of this function is to call it before the first
8218 createOrResize() after the window is already set. This allow the QRhi
8219 backends to perform platform or windowing system specific queries to
8220 determine if the window (and the screen it is on) is capable of true HDR
8221 output with the specified format.
8222
8223 When the format is reported as supported, call setFormat() to set the
8224 requested format and call createOrResize(). Be aware of the consequences
8225 however: successfully requesting a HDR format will involve having to deal
8226 with a different color space, possibly doing white level correction for
8227 non-HDR-aware content, adjusting tonemapping methods, adjusting offscreen
8228 render target settings, etc.
8229
8230 \sa setFormat()
8231 */
8232
8233/*!
8234 \fn virtual QRhiCommandBuffer *QRhiSwapChain::currentFrameCommandBuffer() = 0
8235
8236 \return a command buffer on which rendering commands and resource updates
8237 can be recorded within a \l{QRhi::beginFrame()}{beginFrame} -
8238 \l{QRhi::endFrame()}{endFrame} block, assuming beginFrame() was called with
8239 this swapchain.
8240
8241 \note The returned object is valid also after endFrame(), up until the next
8242 beginFrame(), but the returned command buffer should not be used to record
8243 any commands then. Rather, it can be used to query data collected during
8244 the frame (or previous frames), for example by calling
8245 \l{QRhiCommandBuffer::lastCompletedGpuTime()}{lastCompletedGpuTime()}.
8246
8247 \note The value must not be cached and reused between frames. The caller
8248 should not hold on to the returned object once
8249 \l{QRhi::beginFrame()}{beginFrame()} is called again. Instead, the command
8250 buffer object should be queried again by calling this function.
8251*/
8252
8253/*!
8254 \fn virtual QRhiRenderTarget *QRhiSwapChain::currentFrameRenderTarget() = 0
8255
8256 \return a render target that can used with beginPass() in order to render
8257 the swapchain's current backbuffer. Only valid within a
8258 QRhi::beginFrame() - QRhi::endFrame() block where beginFrame() was called
8259 with this swapchain.
8260
8261 \note the value must not be cached and reused between frames
8262 */
8263
8264/*!
8265 \enum QRhiSwapChain::StereoTargetBuffer
8266 Selects the backbuffer to use with a stereoscopic swapchain.
8267
8268 \value LeftBuffer
8269 \value RightBuffer
8270 */
8271
8272/*!
8273 \return a render target that can be used with beginPass() in order to
8274 render to the swapchain's left or right backbuffer. This overload should be
8275 used only with stereoscopic rendering, that is, when the associated QWindow
8276 is backed by two color buffers, one for each eye, instead of just one.
8277
8278 When stereoscopic rendering is not supported, the return value will be
8279 the default target. It is supported by all hardware backends except for Metal, in
8280 combination with \l QSurfaceFormat::StereoBuffers, assuming it is supported
8281 by the graphics and display driver stack at run time. Metal and Null backends
8282 are going to return the default render target from this overload.
8283
8284 \note the value must not be cached and reused between frames
8285 */
8286QRhiRenderTarget *QRhiSwapChain::currentFrameRenderTarget(StereoTargetBuffer targetBuffer)
8287{
8288 Q_UNUSED(targetBuffer);
8289 return currentFrameRenderTarget();
8290}
8291
8292/*!
8293 \fn virtual bool QRhiSwapChain::createOrResize() = 0
8294
8295 Creates the swapchain if not already done and resizes the swapchain buffers
8296 to match the current size of the targeted surface. Call this whenever the
8297 size of the target surface is different than before.
8298
8299 \note call destroy() only when the swapchain needs to be released
8300 completely, typically upon
8301 QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed. To perform resizing, just
8302 call createOrResize().
8303
8304 \return \c true when successful, \c false when a graphics operation failed.
8305 Regardless of the return value, calling destroy() is always safe.
8306 */
8307
8308/*!
8309 \fn QWindow *QRhiSwapChain::window() const
8310 \return the currently set window.
8311 */
8312
8313/*!
8314 \fn void QRhiSwapChain::setWindow(QWindow *window)
8315 Sets the \a window.
8316 */
8317
8318/*!
8319 \fn QRhiSwapChainProxyData QRhiSwapChain::proxyData() const
8320 \return the currently set proxy data.
8321 */
8322
8323/*!
8324 \fn void QRhiSwapChain::setProxyData(const QRhiSwapChainProxyData &d)
8325 Sets the proxy data \a d.
8326
8327 \sa QRhi::updateSwapChainProxyData()
8328 */
8329
8330/*!
8331 \fn QRhiSwapChain::Flags QRhiSwapChain::flags() const
8332 \return the currently set flags.
8333 */
8334
8335/*!
8336 \fn void QRhiSwapChain::setFlags(Flags f)
8337 Sets the flags \a f.
8338 */
8339
8340/*!
8341 \fn QRhiSwapChain::Format QRhiSwapChain::format() const
8342 \return the currently set format.
8343 */
8344
8345/*!
8346 \fn void QRhiSwapChain::setFormat(Format f)
8347 Sets the format \a f.
8348
8349 Avoid setting formats that are reported as unsupported from
8350 isFormatSupported(). Note that support for a given format may depend on the
8351 screen the swapchain's associated window is opened on. On some platforms,
8352 such as Windows and macOS, for HDR output to work it is necessary to have
8353 HDR output enabled in the display settings.
8354
8355 See isFormatSupported(), \l QRhiSwapChainHdrInfo, and \l Format for more
8356 information on high dynamic range output.
8357 */
8358
8359/*!
8360 \fn QRhiRenderBuffer *QRhiSwapChain::depthStencil() const
8361 \return the currently associated renderbuffer for depth-stencil.
8362 */
8363
8364/*!
8365 \fn void QRhiSwapChain::setDepthStencil(QRhiRenderBuffer *ds)
8366 Sets the renderbuffer \a ds for use as a depth-stencil buffer.
8367 */
8368
8369/*!
8370 \fn int QRhiSwapChain::sampleCount() const
8371 \return the currently set sample count. 1 means no multisample antialiasing.
8372 */
8373
8374/*!
8375 \fn void QRhiSwapChain::setSampleCount(int samples)
8376
8377 Sets the sample count. Common values for \a samples are 1 (no MSAA), 4 (4x
8378 MSAA), or 8 (8x MSAA).
8379
8380 \sa QRhi::supportedSampleCounts()
8381 */
8382
8383/*!
8384 \fn QRhiRenderPassDescriptor *QRhiSwapChain::renderPassDescriptor() const
8385 \return the currently associated QRhiRenderPassDescriptor object.
8386 */
8387
8388/*!
8389 \fn void QRhiSwapChain::setRenderPassDescriptor(QRhiRenderPassDescriptor *desc)
8390 Associates with the QRhiRenderPassDescriptor \a desc.
8391 */
8392
8393/*!
8394 \fn virtual QRhiRenderPassDescriptor *QRhiSwapChain::newCompatibleRenderPassDescriptor() = 0;
8395
8396 \return a new QRhiRenderPassDescriptor that is compatible with this swapchain.
8397
8398 The returned value is used in two ways: it can be passed to
8399 setRenderPassDescriptor() and
8400 QRhiGraphicsPipeline::setRenderPassDescriptor(). A render pass descriptor
8401 describes the attachments (color, depth/stencil) and the load/store
8402 behavior that can be affected by flags(). A QRhiGraphicsPipeline can only
8403 be used in combination with a swapchain that has a
8404 \l{QRhiRenderPassDescriptor::isCompatible()}{compatible}
8405 QRhiRenderPassDescriptor set.
8406
8407 \sa createOrResize()
8408 */
8409
8410/*!
8411 \fn QRhiShadingRateMap *QRhiSwapChain::shadingRateMap() const
8412 \return the currently set QRhiShadingRateMap. By default this is \nullptr.
8413 \since 6.9
8414 */
8415
8416/*!
8417 \fn void QRhiSwapChain::setShadingRateMap(QRhiShadingRateMap *map)
8418
8419 Associates with the specified QRhiShadingRateMap \a map. This is functional
8420 only when the \l QRhi::VariableRateShadingMap feature is reported as
8421 supported.
8422
8423 When QRhiCommandBuffer::setShadingRate() is also called, the higher of the
8424 two shading rates is used for each tile. There is currently no control
8425 offered over the combiner behavior.
8426
8427 \note Setting a shading rate map implies that a different, new
8428 QRhiRenderPassDescriptor is needed and some of the native swapchain objects
8429 must be rebuilt. Therefore, if the swapchain is already set up, call
8430 newCompatibleRenderPassDescriptor() and setRenderPassDescriptor() right
8431 after setShadingRateMap(). Then, createOrResize() must also be called again.
8432 This has rolling consequences, for example for graphics pipelines: those
8433 also need to be associated with the new QRhiRenderPassDescriptor and then
8434 rebuilt. See \l QRhiRenderPassDescriptor::serializedFormat() for some
8435 suggestions on how to deal with this. Remember to set the
8436 QRhiGraphicsPipeline::UsesShadingRate flag for them as well.
8437
8438 \since 6.9
8439 */
8440
8441/*!
8442 \struct QRhiSwapChainHdrInfo
8443 \inmodule QtGuiPrivate
8444 \inheaderfile rhi/qrhi.h
8445 \since 6.6
8446
8447 \brief Describes the high dynamic range related information of the
8448 swapchain's associated output.
8449
8450 To perform HDR-compatible tonemapping, where the target range is not [0,1],
8451 one often needs to know the maximum luminance of the display the
8452 swapchain's window is associated with. While this is often made
8453 user-configurable (think brightness, gamma and similar settings in games),
8454 it can be highly useful to set defaults based on the values reported by the
8455 display itself, thus providing a decent starting point.
8456
8457 There are some problems however: the information is exposed in different
8458 forms on different platforms, whereas with cross-platform graphics APIs
8459 there is often no associated solution at all, because managing such
8460 information is not in the scope of the API (and may rather be retrievable
8461 via other platform-specific means, if any).
8462
8463 With Metal on macOS/iOS, there is no luminance values exposed in the
8464 platform APIs. Instead, the maximum color component value, that would be
8465 1.0 in a non-HDR setup, is provided. The \c limitsType field indicates what
8466 kind of information is available. It is then up to the clients of QRhi to
8467 access the correct data from the \c limits union and use it as they see
8468 fit.
8469
8470 With an API like Vulkan, where there is no way to get such information, the
8471 values are always the built-in defaults.
8472
8473 Therefore, the struct returned from QRhiSwapChain::hdrInfo() contains
8474 either some hard-coded defaults or real values received from an API such as
8475 DXGI (IDXGIOutput6) or Cocoa (NSScreen). When no platform queries are
8476 available (or needs using platform facilities out of scope for QRhi), the
8477 hard-coded defaults are a maximum luminance of 1000 nits and an SDR white
8478 level of 200.
8479
8480 The struct also exposes the presumed luminance behavior of the platform and
8481 its compositor, to indicate what a color component value of 1.0 is treated
8482 as in a HDR color buffer. In some cases it will be necessary to perform
8483 color correction of non-HDR content composited with HDR content. To enable
8484 this, the SDR white level is queried from the system on some platforms
8485 (Windows) and exposed here.
8486
8487 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
8488 for details.
8489
8490 \sa QRhiSwapChain::hdrInfo()
8491 */
8492
8493/*!
8494 \enum QRhiSwapChainHdrInfo::LimitsType
8495
8496 \value LuminanceInNits Indicates that the \l limits union has its
8497 \c luminanceInNits struct set
8498
8499 \value ColorComponentValue Indicates that the \l limits union has its
8500 \c colorComponentValue struct set
8501*/
8502
8503/*!
8504 \enum QRhiSwapChainHdrInfo::LuminanceBehavior
8505
8506 \value SceneReferred Indicates that the color value of 1.0 is interpreted
8507 as 80 nits. This is the behavior of HDR-enabled windows with the Windows
8508 compositor. See
8509 \l{https://learn.microsoft.com/en-us/windows/win32/direct3darticles/high-dynamic-range}{this
8510 page} for more information on HDR on Windows.
8511
8512 \value DisplayReferred Indicates that the color value of 1.0 is interpreted
8513 as the value of the SDR white. (which can be e.g. 200 nits, but will vary
8514 depending on screen brightness) This is the behavior of HDR-enabled windows
8515 on Apple platforms. See
8516 \l{https://developer.apple.com/documentation/metal/hdr_content/displaying_hdr_content_in_a_metal_layer}{this
8517 page} for more information on Apple's EDR system.
8518*/
8519
8520/*!
8521 \variable QRhiSwapChainHdrInfo::limitsType
8522
8523 With Metal on macOS/iOS, there is no luminance values exposed in the
8524 platform APIs. Instead, the maximum color component value, that would be
8525 1.0 in a non-HDR setup, is provided. This value indicates what kind of
8526 information is available in \l limits.
8527
8528 \sa QRhiSwapChain::hdrInfo()
8529*/
8530
8531/*!
8532 \variable QRhiSwapChainHdrInfo::limits
8533
8534 Contains the actual values queried from the graphics API or the platform.
8535 The type of data is indicated by \l limitsType. This is therefore a union.
8536 There are currently two options:
8537
8538 Luminance values in nits:
8539
8540 \code
8541 struct {
8542 float minLuminance;
8543 float maxLuminance;
8544 } luminanceInNits;
8545 \endcode
8546
8547 On Windows the minimum and maximum luminance depends on the screen
8548 brightness. While not relevant for desktops, on laptops the screen
8549 brightness may change at any time. Increasing brightness implies decreased
8550 maximum luminance. In addition, the results may also be dependent on the
8551 HDR Content Brightness set in Windows Settings' System/Display/HDR view,
8552 if there is such a setting.
8553
8554 Note however that the changes made to the laptop screen's brightness or in
8555 the system settings while the application is running are not necessarily
8556 reflected in the returned values, meaning calling hdrInfo() again may still
8557 return the same luminance range as before for the rest of the process'
8558 lifetime. The exact behavior is up to DXGI and Qt has no control over it.
8559
8560 \note The Windows compositor works in scene-referred mode for HDR content.
8561 A color component value of 1.0 corresponds to a luminance of 80 nits. When
8562 rendering non-HDR content (e.g. 2D UI elements), the correction of the
8563 white level is often necessary. (e.g., outputting the fragment color (1, 1,
8564 1) will likely lead to showing a shade of white that is too dim on-screen)
8565 See \l sdrWhiteLevel.
8566
8567 For macOS/iOS, the current maximum and potential maximum color
8568 component values are provided:
8569
8570 \code
8571 struct {
8572 float maxColorComponentValue;
8573 float maxPotentialColorComponentValue;
8574 } colorComponentValue;
8575 \endcode
8576
8577 The value may depend on the screen brightness, which on laptops means that
8578 the result may change in the next call to hdrInfo() if the brightness was
8579 changed in the meantime. The maximum screen brightness implies a maximum
8580 color value of 1.0.
8581
8582 \note Apple's EDR is display-referred. 1.0 corresponds to a luminance level
8583 of SDR white (e.g. 200 nits), the value of which varies based on the screen
8584 brightness and possibly other settings. The exact luminance value for that,
8585 or the maximum luminance of the display, are not exposed to the
8586 applications.
8587
8588 \note It has been observed that the color component values are not set to
8589 the correct larger-than-1 value right away on startup on some macOS
8590 systems, but the values tend to change during or after the first frame.
8591
8592 \sa QRhiSwapChain::hdrInfo()
8593*/
8594
8595/*!
8596 \variable QRhiSwapChainHdrInfo::luminanceBehavior
8597
8598 Describes the platform's presumed behavior with regards to color values.
8599
8600 \sa sdrWhiteLevel
8601 */
8602
8603/*!
8604 \variable QRhiSwapChainHdrInfo::sdrWhiteLevel
8605
8606 On Windows this is the dynamic SDR white level in nits. The value is
8607 dependent on the screen brightness (on laptops), and the SDR or HDR Content
8608 Brightness settings in the Windows settings' System/Display/HDR view.
8609
8610 To perform white level correction for non-HDR (SDR) content, such as 2D UI
8611 elemenents, multiply the final color with sdrWhiteLevel / 80.0 whenever
8612 \l luminanceBehavior is SceneReferred. (assuming Windows and a linear
8613 extended sRGB (scRGB) color space)
8614
8615 On other platforms the value is always a pre-defined value, 200. This may
8616 not match the system's actual SDR white level, but the value of this
8617 variable is not relevant in practice when the \l luminanceBehavior is
8618 DisplayReferred, because then the color component value of 1.0 refers to
8619 the SDR white by default.
8620
8621 \sa luminanceBehavior
8622*/
8623
8624/*!
8625 \return the HDR information for the associated display.
8626
8627 Do not assume that this is a cheap operation. Depending on the platform,
8628 this function makes various platform queries which may have a performance
8629 impact.
8630
8631 \note Can be called before createOrResize() as long as the window is
8632 \l{setWindow()}{set}.
8633
8634 \note What happens when moving a window with an initialized swapchain
8635 between displays (HDR to HDR with different characteristics, HDR to SDR,
8636 etc.) is not currently well-defined and depends heavily on the windowing
8637 system and compositor, with potentially varying behavior between platforms.
8638 Currently QRhi only guarantees that hdrInfo() returns valid data, if
8639 available, for the display to which the swapchain's associated window
8640 belonged at the time of createOrResize().
8641
8642 \sa QRhiSwapChainHdrInfo
8643 */
8644QRhiSwapChainHdrInfo QRhiSwapChain::hdrInfo()
8645{
8646 QRhiSwapChainHdrInfo info;
8647 info.limitsType = QRhiSwapChainHdrInfo::LuminanceInNits;
8648 info.limits.luminanceInNits.minLuminance = 0.0f;
8649 info.limits.luminanceInNits.maxLuminance = 1000.0f;
8650 info.luminanceBehavior = QRhiSwapChainHdrInfo::SceneReferred;
8651 info.sdrWhiteLevel = 200.0f;
8652 return info;
8653}
8654
8655#ifndef QT_NO_DEBUG_STREAM
8656QDebug operator<<(QDebug dbg, const QRhiSwapChainHdrInfo &info)
8657{
8658 QDebugStateSaver saver(dbg);
8659 dbg.nospace() << "QRhiSwapChainHdrInfo(";
8660 switch (info.limitsType) {
8662 dbg.nospace() << " minLuminance=" << info.limits.luminanceInNits.minLuminance
8663 << " maxLuminance=" << info.limits.luminanceInNits.maxLuminance;
8664 break;
8666 dbg.nospace() << " maxColorComponentValue=" << info.limits.colorComponentValue.maxColorComponentValue;
8667 dbg.nospace() << " maxPotentialColorComponentValue=" << info.limits.colorComponentValue.maxPotentialColorComponentValue;
8668 break;
8669 }
8670 switch (info.luminanceBehavior) {
8672 dbg.nospace() << " scene-referred, SDR white level=" << info.sdrWhiteLevel;
8673 break;
8675 dbg.nospace() << " display-referred";
8676 break;
8677 }
8678 dbg.nospace() << ')';
8679 return dbg;
8680}
8681#endif
8682
8683/*!
8684 \class QRhiComputePipeline
8685 \inmodule QtGuiPrivate
8686 \inheaderfile rhi/qrhi.h
8687 \since 6.6
8688 \brief Compute pipeline state resource.
8689
8690 \note Setting the shader resource bindings is mandatory. The referenced
8691 QRhiShaderResourceBindings must already have created() called on it by the
8692 time create() is called.
8693
8694 \note Setting the shader is mandatory.
8695
8696 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
8697 for details.
8698 */
8699
8700/*!
8701 \enum QRhiComputePipeline::Flag
8702
8703 Flag values for describing pipeline options.
8704
8705 \value CompileShadersWithDebugInfo Requests compiling shaders with debug
8706 information enabled, when applicable. See
8707 QRhiGraphicsPipeline::CompileShadersWithDebugInfo for more information.
8708 */
8709
8710/*!
8711 \return the resource type.
8712 */
8713QRhiResource::Type QRhiComputePipeline::resourceType() const
8714{
8715 return ComputePipeline;
8716}
8717
8718/*!
8719 \internal
8720 */
8721QRhiComputePipeline::QRhiComputePipeline(QRhiImplementation *rhi)
8722 : QRhiResource(rhi)
8723{
8724}
8725
8726/*!
8727 \fn QRhiComputePipeline::Flags QRhiComputePipeline::flags() const
8728 \return the currently set flags.
8729 */
8730
8731/*!
8732 \fn void QRhiComputePipeline::setFlags(Flags f)
8733 Sets the flags \a f.
8734 */
8735
8736/*!
8737 \fn QRhiShaderStage QRhiComputePipeline::shaderStage() const
8738 \return the currently set shader.
8739 */
8740
8741/*!
8742 \fn void QRhiComputePipeline::setShaderStage(const QRhiShaderStage &stage)
8743
8744 Sets the shader to use. \a stage can only refer to the
8745 \l{QRhiShaderStage::Compute}{compute stage}.
8746 */
8747
8748/*!
8749 \fn QRhiShaderResourceBindings *QRhiComputePipeline::shaderResourceBindings() const
8750 \return the currently associated QRhiShaderResourceBindings object.
8751 */
8752
8753/*!
8754 \fn void QRhiComputePipeline::setShaderResourceBindings(QRhiShaderResourceBindings *srb)
8755
8756 Associates with \a srb describing the resource binding layout and the
8757 resources (QRhiBuffer, QRhiTexture) themselves. The latter is optional. As
8758 with graphics pipelines, the \a srb passed in here can leave the actual
8759 buffer or texture objects unspecified (\nullptr) as long as there is
8760 another,
8761 \l{QRhiShaderResourceBindings::isLayoutCompatible()}{layout-compatible}
8762 QRhiShaderResourceBindings bound via
8763 \l{QRhiCommandBuffer::setShaderResources()}{setShaderResources()} before
8764 recording the dispatch call.
8765 */
8766
8767/*!
8768 \struct QRhiIndirectDrawCommand
8769 \inmodule QtGuiPrivate
8770 \inheaderfile rhi/qrhi.h
8771 \since 6.12
8772 \brief Draw command.
8773
8774 A draw command that can be uploaded to a QRhiBuffer of usage
8775 QRhiBuffer::UsageFlag::IndirectBuffer.
8776
8777 \sa QRhiCommandBuffer::drawIndirect()
8778
8779 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
8780 for details.
8781 */
8782
8783/*!
8784 \variable QRhiIndirectDrawCommand::vertexCount
8785*/
8786
8787/*!
8788 \variable QRhiIndirectDrawCommand::instanceCount
8789*/
8790
8791/*!
8792 \variable QRhiIndirectDrawCommand::firstVertex
8793*/
8794
8795/*!
8796 \variable QRhiIndirectDrawCommand::firstInstance
8797
8798 \note A non-zero value is only valid when the
8799 QRhi::BaseInstanceIndirect feature is reported as supported.
8800*/
8801
8802/*!
8803 \struct QRhiIndexedIndirectDrawCommand
8804 \inmodule QtGuiPrivate
8805 \inheaderfile rhi/qrhi.h
8806 \since 6.12
8807 \brief Indexed draw command.
8808
8809 An indexed draw command that can be uploaded to a QRhiBuffer of usage
8810 QRhiBuffer::UsageFlag::IndirectBuffer.
8811
8812 \sa QRhiCommandBuffer::drawIndexedIndirect()
8813
8814 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
8815 for details.
8816 */
8817
8818/*!
8819 \variable QRhiIndexedIndirectDrawCommand::indexCount
8820*/
8821
8822/*!
8823 \variable QRhiIndexedIndirectDrawCommand::instanceCount
8824*/
8825
8826/*!
8827 \variable QRhiIndexedIndirectDrawCommand::firstIndex
8828*/
8829
8830/*!
8831 \variable QRhiIndexedIndirectDrawCommand::vertexOffset
8832*/
8833
8834/*!
8835 \variable QRhiIndexedIndirectDrawCommand::firstInstance
8836
8837 \note A non-zero value is only valid when the
8838 QRhi::BaseInstanceIndirect feature is reported as supported.
8839*/
8840
8841/*!
8842 \struct QRhiDispatchIndirectCommand
8843 \inmodule QtGuiPrivate
8844 \inheaderfile rhi/qrhi.h
8845 \since 6.13
8846 \brief Compute dispatch command.
8847
8848 A compute dispatch command that can be uploaded to a QRhiBuffer of usage
8849 QRhiBuffer::UsageFlag::IndirectBuffer. The fields specify the number of
8850 local work groups along each dimension and have the same meaning as the
8851 \c x, \c y, \c z parameters of QRhiCommandBuffer::dispatch().
8852
8853 \c y and \c z default to 1, so a one dimensional dispatch only needs \c x
8854 to be set. Note that a count of 0 in any dimension is valid and results in
8855 no work groups being launched at all.
8856
8857 \sa QRhiCommandBuffer::dispatchIndirect()
8858
8859 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
8860 for details.
8861 */
8862
8863/*!
8864 \variable QRhiDispatchIndirectCommand::x
8865*/
8866
8867/*!
8868 \variable QRhiDispatchIndirectCommand::y
8869*/
8870
8871/*!
8872 \variable QRhiDispatchIndirectCommand::z
8873*/
8874
8875/*!
8876 \class QRhiIndirectCommandBuffer
8877 \inmodule QtGuiPrivate
8878 \inheaderfile rhi/qrhi.h
8879 \since 6.13
8880 \brief A prerecorded batch of indirect draw commands.
8881
8882 A QRhiIndirectCommandBuffer holds a number of draw commands that are
8883 recorded once and can then be replayed any number of times with a single
8884 QRhiCommandBuffer::executeIndirect() call. It is an alternative to the
8885 buffer-based QRhiCommandBuffer::drawIndirect() family of functions. Under
8886 the hood, it may do exactly the same as does (typical with Vulkan, Direct
8887 3D, and OpenGL), or may be implemented differently (Metal).
8888
8889 Create one with QRhi::newIndirectCommandBuffer(), passing in the type and
8890 the maximum number of commands, and call create(). The (maximum) command
8891 count is mandatory, whichever way the commands are going to be provided: it
8892 is the capacity of the object, and create() fails when it is 0.
8893
8894 \badcode
8895 icb = rhi->newIndirectCommandBuffer(QRhiIndirectCommandBuffer::IndexedDraws, 1024);
8896 if (!icb->create()) { error(); }
8897 \endcode
8898
8899 Record commands with draw() or drawIndexed(), then hand the object to a
8900 resource update batch so that the recorded contents reach the GPU.
8901 commitIndirectCommandBuffer() has to be called after recording and before
8902 the pass that executes the commands. It is a no-op when nothing changed
8903 since the last time, so calling it every frame is cheap.
8904
8905 Executing happens inside a render pass:
8906
8907 \badcode
8908 icb->clear();
8909 for (const Item &item : items)
8910 icb->drawIndexed(item.indexCount, 1, item.firstIndex, item.vertexOffset);
8911
8912 QRhiResourceUpdateBatch *u = rhi->nextResourceUpdateBatch();
8913 u->commitIndirectCommandBuffer(icb);
8914
8915 cb->beginPass(rt, Qt::black, { 1.0f, 0 }, u);
8916 cb->setGraphicsPipeline(ps);
8917 cb->setVertexInput(0, 1, &vbufBinding, ibuf, 0, QRhiCommandBuffer::IndexUInt16);
8918 cb->setShaderResources();
8919 cb->executeIndirect(icb);
8920 cb->endPass();
8921 \endcode
8922
8923 The commands can also be generated on the GPU instead of being recorded on
8924 the CPU. In that case fill a buffer with QRhiIndirectDrawCommand or
8925 QRhiIndexedIndirectDrawCommand entries from a compute shader, and call
8926 QRhiCommandBuffer::buildIndirect() with that buffer. That call must happen
8927 outside of any pass. The CPU-side recording functions of
8928 QRhiIndirectCommandBuffer are not used in this case.
8929
8930 \badcode
8931 cb->beginComputePass();
8932 ... // a cb->dispatch() to invoke a compute shader that writes to indirectBuf
8933 cb->endComputePass();
8934
8935 QRhiIndirectCommandBufferBuildInfo buildInfo;
8936 buildInfo.topology = ps->topology();
8937 buildInfo.sourceBuffer = indirectBuf;
8938 buildInfo.commandCount = itemCount; // as many as the compute shader wrote
8939 buildInfo.indexBuffer = indexBuffer;
8940 buildInfo.indexFormat = QRhiCommandBuffer::IndexUInt16;
8941 cb->buildIndirect(icb, buildInfo);
8942
8943 cb->beginPass(rt, Qt::black, { 1.0f, 0 });
8944 cb->setGraphicsPipeline(ps);
8945 cb->setVertexInput(0, 1, &vbufBinding, ibuf, 0, QRhiCommandBuffer::IndexUInt16);
8946 cb->setShaderResources();
8947 cb->executeIndirect(icb);
8948 cb->endPass();
8949 \endcode
8950
8951 When the number of commands is itself decided on the device, set
8952 QRhiIndirectCommandBufferBuildInfo::countBuffer instead of working out
8953 \c itemCount on the CPU. See \l{Command counts} below.
8954
8955 \section2 Command counts
8956
8957 Three counts are involved, and they are not the same thing:
8958
8959 \list
8960
8961 \li maxCommandCount() is the capacity. It is fixed at create() time and
8962 sizes whatever native object the backend needs. Neither of the two ways of
8963 providing commands can exceed it; attempting to does not grow the object.
8964
8965 \li recordedCommandCount() is how many draw() or drawIndexed() calls were
8966 made since the last clear(). It only concerns the CPU-recorded case.
8967
8968 \li commandCount() is how many commands QRhiCommandBuffer::executeIndirect()
8969 issues by default. For a CPU-recorded indirect command buffer that is
8970 recordedCommandCount(). Once QRhiCommandBuffer::buildIndirect() has been
8971 called, isGpuBuilt() returns true and commandCount() is the count resolved
8972 from QRhiIndirectCommandBufferBuildInfo::commandCount instead (but note that
8973 that value is the actual command count only when no
8974 \l{QRhiIndirectCommandBufferBuildInfo::}countBuffer is set, is just a
8975 maximum with a counter buffer present).
8976
8977 \endlist
8978
8979 The size of QRhiIndirectCommandBufferBuildInfo::sourceBuffer plays no part
8980 in any of this: no count is ever derived from it. The buffer is written by
8981 the GPU and is free to be larger than the number of commands actually in
8982 it, so leaving QRhiIndirectCommandBufferBuildInfo::commandCount at 0 does
8983 not mean "as many as fit", it means maxCommandCount().
8984
8985 A device-side count, via QRhiIndirectCommandBufferBuildInfo::countBuffer,
8986 narrows the count further when the commands are executed, and can only
8987 reduce it: the value in the count buffer is clamped to what
8988 commandCount() returns.
8989
8990 Either way, the indirect command buffer is fully prepared before the render
8991 pass begins. That is what separates it from the buffer-based
8992 QRhiCommandBuffer::drawIndirect() family, where some backends (Metal above a
8993 certain draw count, and always for the count variants) have to interrupt and
8994 restart the render pass in order to encode the commands. Such an
8995 interruption costs a QRhiRenderBuffer depth-stencil buffer its contents
8996 unless QRhiRenderBuffer::NoTransientBacking was set, and may also be degrading
8997 performance due to having to reload the color buffer values. With
8998 executeIndirect() the question does not arise.
8999
9000 For Metal, the buffer-based API implies (ahove a certain draw count, or
9001 whhen using the count variants) having to run a compute kernel to create an
9002 MTLIndirectCommandBuffer from the Vulkan/Direct 3D/OpenGL style indirect
9003 buffer. With QRhiIndirectCommandBuffer this is not always necessary, because
9004 now, at least when the commands are generated on the CPU side, an
9005 MTLIndirectCommandBuffer can be created and set up normally, by calling
9006 MTLIndirectCommandBuffer's Objective-C API, instead of having to inject a
9007 compute pass. When generating the commands on the GPU, the extra compute
9008 pass is still necessary, but at least it will not interrupt the render pass,
9009 by design, unlike with the direct buffer-based API. Note however that using
9010 MTLIndirectCommandBuffer natively from C++/Objective-C to perform repeated
9011 CPU-side draw call generation can prove to be quite expensive (when
9012 frequently re-recording a larger set of draw commands), compared to the
9013 GPU-side draw command generation, even though that involves an extra encoding
9014 compute pass to "convert" the Vulkan/Direct 3D/OpenGL style indirect buffer
9015 to what Metal prefers. See the next section.
9016
9017 \section2 Recording on the CPU or building on the GPU
9018
9019 The two ways of populating an indirect command buffer are not equivalent in
9020 cost, and the difference grows with the number of commands.
9021
9022 Recording with draw() or drawIndexed() is work proportional to the number of
9023 commands, and it is repeated whenever the contents change. Where that work
9024 lands depends on the backend: those that keep the commands in a buffer
9025 upload it from QRhiResourceUpdateBatch::commitIndirectCommandBuffer(),
9026 whereas Metal encodes each command individually into a native
9027 \c MTLIndirectCommandBuffer, one native call per command, and does so from
9028 QRhiCommandBuffer::executeIndirect().
9029
9030 Either way the result is cached and keyed on the recorded contents, so an
9031 indirect command buffer that is recorded once and then executed unchanged
9032 frame after frame costs nothing beyond the first few frames. That is the
9033 case CPU recording is meant for: a command set that is stable, or changes
9034 rarely, relative to how often it is executed.
9035
9036 The opposite case - many commands, cleared and re-recorded every frame - is
9037 the one to avoid. Regenerating tens of thousands of commands per frame that
9038 way can be an order of magnitude more expensive on Apple platforms than
9039 filling a QRhiBuffer and calling QRhiCommandBuffer::drawIndexedIndirect() on
9040 it, because of the per-command native encoding. When the command set is both
9041 large and regenerated every frame, generate it on the GPU and use
9042 QRhiCommandBuffer::buildIndirect(); the alternative is to stay with the
9043 buffer-based drawIndirect() family and accept the render pass interruption
9044 it may cause (which is still not recommended, even if it would perform
9045 better).
9046
9047 A given QRhiIndirectCommandBuffer holds one kind of command: either
9048 non-indexed draws (\c Draws) or indexed draws (\c IndexedDraws), never a
9049 mix of the two. This mirrors what the underlying APIs can express: a single
9050 indirect draw call always has one command type and one stride.
9051
9052 The requirements are the same as for the indirect draws this stands in for:
9053 QRhi::DrawIndirect has to be supported, the graphics pipeline should be
9054 created with \l{QRhiGraphicsPipeline::UsesIndirectDraws}{UsesIndirectDraws},
9055 and a count buffer additionally needs QRhi::DrawIndirectCount to be
9056 supported.
9057
9058 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
9059 for details.
9060
9061 \sa QRhiCommandBuffer::executeIndirect(), QRhiCommandBuffer::drawIndirect()
9062 */
9063
9064/*!
9065 \enum QRhiIndirectCommandBuffer::Type
9066 Specifies the kind of commands an indirect command buffer holds.
9067
9068 \value Draws Non-indexed draw commands, recorded with draw().
9069 \value IndexedDraws Indexed draw commands, recorded with drawIndexed().
9070 */
9071
9072/*!
9073 \fn QRhiIndirectCommandBuffer::Type QRhiIndirectCommandBuffer::type() const
9074 \return the type of commands this indirect command buffer holds.
9075 */
9076
9077/*!
9078 \fn void QRhiIndirectCommandBuffer::setType(Type t)
9079
9080 Sets the command type \a t. The type is normally specified in
9081 QRhi::newIndirectCommandBuffer(), so this function is only used when it has
9082 to be changed. As with other setters, it only takes effect when calling
9083 create().
9084 */
9085
9086/*!
9087 \fn quint32 QRhiIndirectCommandBuffer::maxCommandCount() const
9088 \return the capacity, i.e. the maximum number of commands.
9089 */
9090
9091/*!
9092 \fn void QRhiIndirectCommandBuffer::setMaxCommandCount(quint32 count)
9093
9094 Sets the capacity, the maximum number of commands, to \a count. The
9095 capacity is normally specified in QRhi::newIndirectCommandBuffer(), so this
9096 function is only used when it has to be changed. As with other setters, it
9097 only takes effect when calling create(), which fails when \a count is 0.
9098
9099 The capacity applies regardless of how the commands are going to be
9100 provided: recording them with draw() and drawIndexed() and building them
9101 with QRhiCommandBuffer::buildIndirect() are both bounded by it.
9102
9103 draw() and drawIndexed() ignore, with a warning, any command past the first
9104 \a count ones. QRhiCommandBuffer::buildIndirect() clamps, also with a
9105 warning, when QRhiIndirectCommandBufferBuildInfo::commandCount is larger.
9106
9107 \sa commandCount(), recordedCommandCount()
9108 */
9109
9110/*!
9111 \fn quint32 QRhiIndirectCommandBuffer::recordedCommandCount() const
9112
9113 \return the number of commands recorded with draw() or drawIndexed() since
9114 the last clear().
9115
9116 This is unaffected by QRhiCommandBuffer::buildIndirect(): once the commands
9117 come from the GPU, whatever was recorded on the CPU is ignored. Use
9118 commandCount() to get the number of commands that will actually be
9119 executed.
9120 */
9121
9122/*!
9123 \fn bool QRhiIndirectCommandBuffer::isGpuBuilt() const
9124
9125 \return \c true when QRhiCommandBuffer::buildIndirect() has been called on
9126 this indirect command buffer, meaning its contents come from a QRhiBuffer
9127 instead of from draw() and drawIndexed().
9128
9129 Once true, this stays true until the next create().
9130 */
9131
9132/*!
9133 \fn quint32 QRhiIndirectCommandBuffer::commandCount() const
9134
9135 \return the number of commands QRhiCommandBuffer::executeIndirect() issues
9136 by default.
9137
9138 This is recordedCommandCount() for a CPU-recorded indirect command buffer,
9139 and the count resolved from
9140 QRhiIndirectCommandBufferBuildInfo::commandCount once
9141 QRhiCommandBuffer::buildIndirect() has been called.
9142
9143 A count buffer, if there is one, can reduce the number of draws further at
9144 execution time. This function does not, and cannot, account for that.
9145 */
9146
9147/*!
9148 \fn virtual bool QRhiIndirectCommandBuffer::create() = 0
9149
9150 Creates the corresponding native objects.
9151
9152 Fails when maxCommandCount() is 0.
9153
9154 A given QRhiIndirectCommandBuffer takes its commands either from draw() and
9155 drawIndexed() followed by
9156 QRhiResourceUpdateBatch::commitIndirectCommandBuffer(), or from
9157 QRhiCommandBuffer::buildIndirect(), but not from both. Moving to the latter
9158 is one-way: clear() does not undo it, and neither does a subsequent
9159 commitIndirectCommandBuffer(); isGpuBuilt() stays true and the commands keep
9160 coming from the buffer. Call create() again to get an indirect command
9161 buffer that is populated from the CPU once more.
9162
9163 \note Like with every other QRhi resource, destroy() gives up the contents,
9164 and so create() starts from an empty indirect command buffer:
9165 recordedCommandCount() is 0 afterwards. Setting a different type() or
9166 maxCommandCount() and calling create() again therefore needs the commands
9167 to be recorded again as well.
9168
9169 \return \c true when successful, \c false when a graphics operation failed.
9170 */
9171
9172/*!
9173 \internal
9174 */
9175QRhiIndirectCommandBuffer::QRhiIndirectCommandBuffer(QRhiImplementation *rhi, Type type_,
9176 quint32 maxCommandCount_)
9177 : QRhiResource(rhi),
9178 m_type(type_), m_maxCommandCount(maxCommandCount_)
9179{
9180}
9181
9182/*!
9183 \return the resource type.
9184 */
9185QRhiResource::Type QRhiIndirectCommandBuffer::resourceType() const
9186{
9187 return IndirectCommandBuffer;
9188}
9189
9190/*!
9191 Discards all commands recorded so far.
9192
9193 Can be called at any time, also before create(). The recorded contents only
9194 become visible to the GPU once the object is passed to
9195 QRhiResourceUpdateBatch::commitIndirectCommandBuffer().
9196
9197 This resets recordedCommandCount() to 0. It does not undo a
9198 QRhiCommandBuffer::buildIndirect(): an indirect command buffer that gets
9199 its commands from the GPU keeps doing so, and commandCount() is unchanged.
9200
9201 \note Clearing and re-recording invalidates whatever the backend cached for
9202 the previous contents, so the per-command cost of recording is paid again.
9203 Call this only when the commands actually have to change. See
9204 \l{Recording on the CPU or building on the GPU} for why that matters at high
9205 command counts.
9206 */
9207void QRhiIndirectCommandBuffer::clear()
9208{
9209 m_data.clear();
9210 m_commandCount = 0;
9211 m_generation += 1;
9212}
9213
9214/*!
9215 Records a non-indexed draw command with \a vertexCount, \a instanceCount,
9216 \a firstVertex, and \a firstInstance.
9217
9218 The semantics are the same as QRhiCommandBuffer::draw().
9219
9220 \note Only valid on an indirect command buffer of type Draws.
9221 */
9222void QRhiIndirectCommandBuffer::draw(quint32 vertexCount, quint32 instanceCount,
9223 quint32 firstVertex, quint32 firstInstance)
9224{
9225 if (m_type != Draws) {
9226 qWarning("QRhiIndirectCommandBuffer: draw() on an IndexedDraws indirect command buffer; ignored");
9227 return;
9228 }
9229 if (m_commandCount == m_maxCommandCount) {
9230 qWarning("QRhiIndirectCommandBuffer: maxCommandCount (%u) reached; command ignored",
9231 m_maxCommandCount);
9232 return;
9233 }
9234 const QRhiIndirectDrawCommand cmd = { vertexCount, instanceCount, firstVertex, firstInstance };
9235 m_data.append(reinterpret_cast<const char *>(&cmd), sizeof(cmd));
9236 m_commandCount += 1;
9237 m_generation += 1;
9238}
9239
9240/*!
9241 Records an indexed draw command with \a indexCount, \a instanceCount, \a
9242 firstIndex, \a vertexOffset, and \a firstInstance.
9243
9244 The semantics are the same as QRhiCommandBuffer::drawIndexed().
9245
9246 \note Only valid on an indirect command buffer of type IndexedDraws.
9247 */
9248void QRhiIndirectCommandBuffer::drawIndexed(quint32 indexCount, quint32 instanceCount,
9249 quint32 firstIndex, qint32 vertexOffset,
9250 quint32 firstInstance)
9251{
9252 if (m_type != IndexedDraws) {
9253 qWarning("QRhiIndirectCommandBuffer: drawIndexed() on a Draws indirect command buffer; ignored");
9254 return;
9255 }
9256 if (m_commandCount == m_maxCommandCount) {
9257 qWarning("QRhiIndirectCommandBuffer: maxCommandCount (%u) reached; command ignored",
9258 m_maxCommandCount);
9259 return;
9260 }
9261 const QRhiIndexedIndirectDrawCommand cmd = { indexCount, instanceCount, firstIndex,
9262 vertexOffset, firstInstance };
9263 m_data.append(reinterpret_cast<const char *>(&cmd), sizeof(cmd));
9264 m_commandCount += 1;
9265 m_generation += 1;
9266}
9267
9268/*!
9269 \struct QRhiIndirectCommandBufferBuildInfo
9270 \inmodule QtGuiPrivate
9271 \inheaderfile rhi/qrhi.h
9272 \since 6.13
9273 \brief Describes how to build an indirect command buffer from a QRhiBuffer.
9274
9275 \sa QRhiCommandBuffer::buildIndirect()
9276
9277 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
9278 for details.
9279 */
9280
9281/*!
9282 \variable QRhiIndirectCommandBufferBuildInfo::topology
9283
9284 The topology the commands will be drawn with. Must match the topology of the
9285 graphics pipeline that is set when QRhiCommandBuffer::executeIndirect() is
9286 called. Some backends need it in order to build their native indirect
9287 command buffer, and it is not available to them outside of a render pass.
9288*/
9289
9290/*!
9291 \variable QRhiIndirectCommandBufferBuildInfo::sourceBuffer
9292
9293 The buffer holding the QRhiIndirectDrawCommand or
9294 QRhiIndexedIndirectDrawCommand entries. Must have IndirectBuffer usage.
9295
9296 Its size is not used to work out how many commands there are, see
9297 commandCount.
9298*/
9299
9300/*!
9301 \variable QRhiIndirectCommandBufferBuildInfo::sourceBufferOffset
9302*/
9303
9304/*!
9305 \variable QRhiIndirectCommandBufferBuildInfo::commandCount
9306
9307 The number of commands to take from sourceBuffer. This is what
9308 QRhiIndirectCommandBuffer::commandCount() reports afterwards, and so how
9309 many draws QRhiCommandBuffer::executeIndirect() issues by default.
9310
9311 0 means QRhiIndirectCommandBuffer::maxCommandCount(). It does not mean "as
9312 many as fit in sourceBuffer": a buffer written by the GPU can be larger
9313 than the number of commands in it, so no count is ever derived from its
9314 size. A value above QRhiIndirectCommandBuffer::maxCommandCount() is clamped
9315 to it, with a warning.
9316
9317 \note Specifying countBuffer changes what this value means: it stops being
9318 the number of commands and becomes the \e maximum number of commands, with
9319 the device-side count in countBuffer deciding the actual number. Without a
9320 countBuffer, exactly this many commands are executed.
9321*/
9322
9323/*!
9324 \variable QRhiIndirectCommandBufferBuildInfo::stride
9325
9326 The byte distance between two commands in sourceBuffer. 0 means the size of
9327 the corresponding command struct.
9328*/
9329
9330/*!
9331 \variable QRhiIndirectCommandBufferBuildInfo::countBuffer
9332
9333 An optional buffer whose first quint32 holds the number of commands to
9334 execute. Requires QRhi::DrawIndirectCount.
9335
9336 \note Setting this turns commandCount into an upper bound. The device-side
9337 value is clamped to it, so a count buffer can only ever reduce the number
9338 of draws, never raise it.
9339*/
9340
9341/*!
9342 \variable QRhiIndirectCommandBufferBuildInfo::countBufferOffset
9343*/
9344
9345/*!
9346 \variable QRhiIndirectCommandBufferBuildInfo::indexBuffer
9347
9348 The index buffer the commands index into. Required for IndexedDraws.
9349*/
9350
9351/*!
9352 \variable QRhiIndirectCommandBufferBuildInfo::indexBufferOffset
9353*/
9354
9355/*!
9356 \variable QRhiIndirectCommandBufferBuildInfo::indexFormat
9357*/
9358
9360 Type type,
9361 quint32 maxCommandCount)
9363{
9364}
9365
9370
9372{
9373 // Unconditionally, also when there is nothing else to do: like with every
9374 // other resource, destroy() gives up the contents. Carrying a recording
9375 // over into the next create() would not survive a changed maxCommandCount
9376 // or type.
9377 clear();
9378
9379 if (!valid)
9380 return;
9381
9382 delete buffer;
9383 buffer = nullptr;
9384 uploadedGeneration = 0;
9385 buildInfo = {};
9386 m_gpuBuilt = false;
9387 m_gpuBuiltCommandCount = 0;
9388 valid = false;
9389
9390 if (m_rhi)
9391 m_rhi->unregisterResource(this);
9392}
9393
9395{
9396 // Either way the recorded commands go: they may not fit maxCommandCount()
9397 // or match type() anymore.
9398 if (valid)
9399 destroy();
9400 else
9401 clear();
9402
9403 if (!m_maxCommandCount) {
9404 qWarning("QRhiIndirectCommandBuffer: maxCommandCount is 0");
9405 return false;
9406 }
9407
9408 valid = true;
9409 m_rhi->registerResource(this);
9410 return true;
9411}
9412
9414{
9415 // m_gpuBuilt: the commands come from the source buffer from now on, so
9416 // there is nothing to upload, as documented for commitIndirectCommandBuffer().
9417 if (!valid || m_gpuBuilt || m_data.isEmpty() || uploadedGeneration == m_generation)
9418 return;
9419
9420 if (!buffer) {
9421 const quint32 commandSize = m_type == IndexedDraws ? sizeof(QRhiIndexedIndirectDrawCommand)
9422 : sizeof(QRhiIndirectDrawCommand);
9423 buffer = m_rhi->createBuffer(QRhiBuffer::Static, QRhiBuffer::IndirectBuffer,
9424 m_maxCommandCount * commandSize);
9425 if (!buffer || !buffer->create()) {
9426 delete buffer;
9427 buffer = nullptr;
9428 return;
9429 }
9430 }
9431
9432 u->uploadStaticBuffer(buffer, 0, quint32(m_data.size()), m_data.constData());
9433 uploadedGeneration = m_generation;
9434}
9435
9436void QRhiBufferBackedIndirectCommandBuffer::build(const QRhiIndirectCommandBufferBuildInfo &info)
9437{
9438 buildInfo = info;
9439 quint32 count = info.commandCount ? info.commandCount : m_maxCommandCount;
9440 if (count > m_maxCommandCount) {
9441 qWarning("QRhiIndirectCommandBuffer: buildIndirect() with commandCount %u exceeds "
9442 "maxCommandCount %u; clamping", count, m_maxCommandCount);
9443 count = m_maxCommandCount;
9444 }
9445 m_gpuBuilt = true;
9446 m_gpuBuiltCommandCount = count;
9447}
9448
9450 quint32 firstCommand,
9451 quint32 commandCount)
9452{
9453 const bool indexed = m_type == IndexedDraws;
9454 const quint32 canonicalStride = m_type == IndexedDraws ? sizeof(QRhiIndexedIndirectDrawCommand)
9455 : sizeof(QRhiIndirectDrawCommand);
9456
9457 if (m_gpuBuilt) {
9458 const quint32 stride = buildInfo.stride ? buildInfo.stride : canonicalStride;
9459 const quint32 available = m_gpuBuiltCommandCount > firstCommand
9460 ? m_gpuBuiltCommandCount - firstCommand : 0;
9461 const quint32 count = qMin(commandCount, available);
9462 if (!count)
9463 return;
9464 const quint32 offset = buildInfo.sourceBufferOffset + firstCommand * stride;
9465 if (buildInfo.countBuffer) {
9466 // Note that a non-zero firstCommand shifts the window, but the
9467 // device-side count is still relative to the start of that window.
9468 if (indexed) {
9469 cb->drawIndexedIndirectCount(buildInfo.sourceBuffer, offset,
9470 buildInfo.countBuffer, buildInfo.countBufferOffset,
9471 count, stride);
9472 } else {
9473 cb->drawIndirectCount(buildInfo.sourceBuffer, offset,
9474 buildInfo.countBuffer, buildInfo.countBufferOffset,
9475 count, stride);
9476 }
9477 } else {
9478 if (indexed)
9479 cb->drawIndexedIndirect(buildInfo.sourceBuffer, offset, count, stride);
9480 else
9481 cb->drawIndirect(buildInfo.sourceBuffer, offset, count, stride);
9482 }
9483 return;
9484 }
9485
9486 if (!buffer) {
9487 // Metal encodes on the spot in executeIndirect() and so needs no
9488 // commit. Everywhere else a missing one means drawing nothing.
9489 if (m_commandCount) {
9490 qWarning("QRhiIndirectCommandBuffer: %u command(s) recorded but never flushed with "
9491 "QRhiResourceUpdateBatch::commitIndirectCommandBuffer(); nothing to draw",
9492 m_commandCount);
9493 }
9494 return;
9495 }
9496 if (!m_commandCount)
9497 return;
9498
9499 const quint32 available = m_commandCount > firstCommand ? m_commandCount - firstCommand : 0;
9500 const quint32 count = qMin(commandCount, available);
9501 if (!count)
9502 return;
9503
9504 const quint32 offset = firstCommand * canonicalStride;
9505 if (indexed)
9506 cb->drawIndexedIndirect(buffer, offset, count, canonicalStride);
9507 else
9508 cb->drawIndirect(buffer, offset, count, canonicalStride);
9509}
9510
9511QRhiIndirectCommandBuffer *QRhiImplementation::createIndirectCommandBuffer(QRhiIndirectCommandBuffer::Type type,
9512 quint32 maxCommandCount)
9513{
9514 return new QRhiBufferBackedIndirectCommandBuffer(this, type, maxCommandCount);
9515}
9516
9517void QRhiImplementation::buildIndirect(QRhiCommandBuffer *cb, QRhiIndirectCommandBuffer *icb,
9518 const QRhiIndirectCommandBufferBuildInfo &info)
9519{
9520 Q_UNUSED(cb);
9521 static_cast<QRhiBufferBackedIndirectCommandBuffer *>(icb)->build(info);
9522}
9523
9524void QRhiImplementation::executeIndirect(QRhiCommandBuffer *cb, QRhiIndirectCommandBuffer *icb,
9525 quint32 firstCommand, quint32 commandCount)
9526{
9527 static_cast<QRhiBufferBackedIndirectCommandBuffer *>(icb)->execute(cb, firstCommand, commandCount);
9528}
9529
9530void QRhiImplementation::commitIndirectCommandBuffer(QRhiResourceUpdateBatch *u,
9531 QRhiIndirectCommandBuffer *icb)
9532{
9533 static_cast<QRhiBufferBackedIndirectCommandBuffer *>(icb)->enqueueUpload(u);
9534}
9535
9536/*!
9537 \class QRhiCommandBuffer
9538 \inmodule QtGuiPrivate
9539 \inheaderfile rhi/qrhi.h
9540 \since 6.6
9541 \brief Command buffer resource.
9542
9543 Not creatable by applications at the moment. The only ways to obtain a
9544 valid QRhiCommandBuffer are to get it from the targeted swapchain via
9545 QRhiSwapChain::currentFrameCommandBuffer(), or, in case of rendering
9546 completely offscreen, initializing one via QRhi::beginOffscreenFrame().
9547
9548 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
9549 for details.
9550 */
9551
9552/*!
9553 \enum QRhiCommandBuffer::IndexFormat
9554 Specifies the index data type
9555
9556 \value IndexUInt16 Unsigned 16-bit (quint16)
9557 \value IndexUInt32 Unsigned 32-bit (quint32)
9558 */
9559
9560/*!
9561 \enum QRhiCommandBuffer::BeginPassFlag
9562 Flag values for QRhi::beginPass()
9563
9564 \value ExternalContent Specifies that there will be a call to
9565 QRhiCommandBuffer::beginExternal() in this pass. Some backends, Vulkan in
9566 particular, will fail if this flag is not set and beginExternal() is still
9567 called.
9568
9569 \value DoNotTrackResourcesForCompute Specifies that there is no need to
9570 track resources used in this pass if the only purpose of such tracking is
9571 to generate barriers for compute. Implies that there are no compute passes
9572 in the frame. This is an optimization hint that may be taken into account
9573 by certain backends, OpenGL in particular, allowing them to skip certain
9574 operations. When this flag is set for a render pass in a frame, calling
9575 \l{QRhiCommandBuffer::beginComputePass()}{beginComputePass()} in that frame
9576 may lead to unexpected behavior, depending on the resource dependencies
9577 between the render and compute passes.
9578 */
9579
9580/*!
9581 \typedef QRhiCommandBuffer::DynamicOffset
9582
9583 Synonym for std::pair<int, quint32>. The first entry is the binding, the second
9584 is the offset in the buffer.
9585*/
9586
9587/*!
9588 \typedef QRhiCommandBuffer::VertexInput
9589
9590 Synonym for std::pair<QRhiBuffer *, quint32>. The second entry is an offset in
9591 the buffer specified by the first.
9592*/
9593
9594/*!
9595 \internal
9596 */
9597QRhiCommandBuffer::QRhiCommandBuffer(QRhiImplementation *rhi)
9598 : QRhiResource(rhi)
9599{
9600}
9601
9602/*!
9603 \return the resource type.
9604 */
9605QRhiResource::Type QRhiCommandBuffer::resourceType() const
9606{
9607 return CommandBuffer;
9608}
9609
9610static const char *resourceTypeStr(const QRhiResource *res)
9611{
9612 switch (res->resourceType()) {
9613 case QRhiResource::Buffer:
9614 return "Buffer";
9615 case QRhiResource::Texture:
9616 return "Texture";
9617 case QRhiResource::Sampler:
9618 return "Sampler";
9619 case QRhiResource::RenderBuffer:
9620 return "RenderBuffer";
9621 case QRhiResource::RenderPassDescriptor:
9622 return "RenderPassDescriptor";
9623 case QRhiResource::SwapChainRenderTarget:
9624 return "SwapChainRenderTarget";
9625 case QRhiResource::TextureRenderTarget:
9626 return "TextureRenderTarget";
9627 case QRhiResource::ShaderResourceBindings:
9628 return "ShaderResourceBindings";
9629 case QRhiResource::GraphicsPipeline:
9630 return "GraphicsPipeline";
9631 case QRhiResource::SwapChain:
9632 return "SwapChain";
9633 case QRhiResource::ComputePipeline:
9634 return "ComputePipeline";
9635 case QRhiResource::CommandBuffer:
9636 return "CommandBuffer";
9637 case QRhiResource::ShadingRateMap:
9638 return "ShadingRateMap";
9639 case QRhiResource::IndirectCommandBuffer:
9640 return "IndirectCommandBuffer";
9641 }
9642
9643 Q_UNREACHABLE_RETURN("");
9644}
9645
9646QRhiImplementation::~QRhiImplementation()
9647{
9648 qDeleteAll(resUpdPool);
9649
9650 // Be nice and show something about leaked stuff. Though we may not get
9651 // this far with some backends where the allocator or the api may check
9652 // and freak out for unfreed graphics objects in the derived dtor already.
9653#ifndef QT_NO_DEBUG
9654 // debug builds: just do it always
9655 static bool leakCheck = true;
9656#else
9657 // release builds: opt-in
9658 static bool leakCheck = qEnvironmentVariableIntValue("QT_RHI_LEAK_CHECK");
9659#endif
9660 if (!resources.isEmpty()) {
9661 if (leakCheck) {
9662 qWarning("QRhi %p going down with %d unreleased resources that own native graphics objects. This is not nice.",
9663 q, int(resources.size()));
9664 }
9665 for (auto it = resources.cbegin(), end = resources.cend(); it != end; ++it) {
9666 QRhiResource *res = it.key();
9667 const bool ownsNativeResources = it.value();
9668 if (leakCheck && ownsNativeResources)
9669 qWarning(" %s resource %p (%s)", resourceTypeStr(res), res, res->m_objectName.constData());
9670
9671 // Null out the resource's rhi pointer. This is why it makes sense to do null
9672 // checks in the destroy() implementations of the various resource types. It
9673 // allows to survive in bad applications that somehow manage to destroy a
9674 // resource of a QRhi after the QRhi itself.
9675 res->m_rhi = nullptr;
9676 }
9677 }
9678}
9679
9680bool QRhiImplementation::isCompressedFormat(QRhiTexture::Format format) const
9681{
9682 return (format >= QRhiTexture::BC1 && format <= QRhiTexture::BC7)
9683 || (format >= QRhiTexture::ETC2_RGB8 && format <= QRhiTexture::ETC2_RGBA8)
9684 || (format >= QRhiTexture::ASTC_4x4 && format <= QRhiTexture::ASTC_12x12);
9685}
9686
9687bool QRhiImplementation::compressedFormatInfo(QRhiTexture::Format format, const QSize &size,
9688 quint32 *bpl, quint32 *byteSize,
9689 QSize *blockDim) const
9690{
9691 int xdim = 4;
9692 int ydim = 4;
9693 quint32 blockSize = 0;
9694
9695 switch (format) {
9696 case QRhiTexture::BC1:
9697 blockSize = 8;
9698 break;
9699 case QRhiTexture::BC2:
9700 blockSize = 16;
9701 break;
9702 case QRhiTexture::BC3:
9703 blockSize = 16;
9704 break;
9705 case QRhiTexture::BC4:
9706 blockSize = 8;
9707 break;
9708 case QRhiTexture::BC5:
9709 blockSize = 16;
9710 break;
9711 case QRhiTexture::BC6H:
9712 blockSize = 16;
9713 break;
9714 case QRhiTexture::BC7:
9715 blockSize = 16;
9716 break;
9717
9718 case QRhiTexture::ETC2_RGB8:
9719 blockSize = 8;
9720 break;
9721 case QRhiTexture::ETC2_RGB8A1:
9722 blockSize = 8;
9723 break;
9724 case QRhiTexture::ETC2_RGBA8:
9725 blockSize = 16;
9726 break;
9727
9728 case QRhiTexture::ASTC_4x4:
9729 blockSize = 16;
9730 break;
9731 case QRhiTexture::ASTC_5x4:
9732 blockSize = 16;
9733 xdim = 5;
9734 break;
9735 case QRhiTexture::ASTC_5x5:
9736 blockSize = 16;
9737 xdim = ydim = 5;
9738 break;
9739 case QRhiTexture::ASTC_6x5:
9740 blockSize = 16;
9741 xdim = 6;
9742 ydim = 5;
9743 break;
9744 case QRhiTexture::ASTC_6x6:
9745 blockSize = 16;
9746 xdim = ydim = 6;
9747 break;
9748 case QRhiTexture::ASTC_8x5:
9749 blockSize = 16;
9750 xdim = 8;
9751 ydim = 5;
9752 break;
9753 case QRhiTexture::ASTC_8x6:
9754 blockSize = 16;
9755 xdim = 8;
9756 ydim = 6;
9757 break;
9758 case QRhiTexture::ASTC_8x8:
9759 blockSize = 16;
9760 xdim = ydim = 8;
9761 break;
9762 case QRhiTexture::ASTC_10x5:
9763 blockSize = 16;
9764 xdim = 10;
9765 ydim = 5;
9766 break;
9767 case QRhiTexture::ASTC_10x6:
9768 blockSize = 16;
9769 xdim = 10;
9770 ydim = 6;
9771 break;
9772 case QRhiTexture::ASTC_10x8:
9773 blockSize = 16;
9774 xdim = 10;
9775 ydim = 8;
9776 break;
9777 case QRhiTexture::ASTC_10x10:
9778 blockSize = 16;
9779 xdim = ydim = 10;
9780 break;
9781 case QRhiTexture::ASTC_12x10:
9782 blockSize = 16;
9783 xdim = 12;
9784 ydim = 10;
9785 break;
9786 case QRhiTexture::ASTC_12x12:
9787 blockSize = 16;
9788 xdim = ydim = 12;
9789 break;
9790
9791 default:
9792 Q_UNREACHABLE();
9793 break;
9794 }
9795
9796 const quint32 wblocks = quint32((qint64(qMax(0, size.width())) + xdim - 1) / xdim);
9797 const quint32 hblocks = quint32((qint64(qMax(0, size.height())) + ydim - 1) / ydim);
9798
9799 if (blockDim)
9800 *blockDim = QSize(xdim, ydim);
9801
9802 // Compute in 64-bit, as safety for extreme geometry that would not fit.
9803 // wblocks and hblocks are at most 2^29 and blockSize at most 16.
9804 const quint64 bytesPerLine = quint64(wblocks) * quint64(blockSize);
9805 const quint64 totalSize = quint64(wblocks) * quint64(hblocks) * quint64(blockSize);
9806 if (bytesPerLine > std::numeric_limits<quint32>::max()
9807 || totalSize > std::numeric_limits<quint32>::max())
9808 {
9809 qWarning("Compressed texture of size %dx%d with format %d has a byte size of %llu "
9810 "which is too large to be handled",
9811 size.width(), size.height(), int(format), totalSize);
9812 if (bpl)
9813 *bpl = 0;
9814 if (byteSize)
9815 *byteSize = 0;
9816 return false;
9817 }
9818
9819 if (bpl)
9820 *bpl = quint32(bytesPerLine);
9821 if (byteSize)
9822 *byteSize = quint32(totalSize);
9823
9824 return true;
9825}
9826
9827bool QRhiImplementation::textureFormatInfo(QRhiTexture::Format format, const QSize &size,
9828 quint32 *bpl, quint32 *byteSize, quint32 *bytesPerPixel) const
9829{
9830 if (isCompressedFormat(format))
9831 return compressedFormatInfo(format, size, bpl, byteSize, nullptr);
9832
9833 quint32 bpc = 0;
9834 switch (format) {
9835 case QRhiTexture::RGBA8:
9836 bpc = 4;
9837 break;
9838 case QRhiTexture::BGRA8:
9839 bpc = 4;
9840 break;
9841 case QRhiTexture::R8:
9842 bpc = 1;
9843 break;
9844 case QRhiTexture::RG8:
9845 bpc = 2;
9846 break;
9847 case QRhiTexture::R16:
9848 bpc = 2;
9849 break;
9850 case QRhiTexture::RG16:
9851 bpc = 4;
9852 break;
9853 case QRhiTexture::RED_OR_ALPHA8:
9854 bpc = 1;
9855 break;
9856
9857 case QRhiTexture::RGBA16F:
9858 bpc = 8;
9859 break;
9860 case QRhiTexture::RGBA32F:
9861 bpc = 16;
9862 break;
9863 case QRhiTexture::R16F:
9864 bpc = 2;
9865 break;
9866 case QRhiTexture::R32F:
9867 bpc = 4;
9868 break;
9869
9870 case QRhiTexture::RGB10A2:
9871 bpc = 4;
9872 break;
9873
9874 case QRhiTexture::D16:
9875 bpc = 2;
9876 break;
9877 case QRhiTexture::D24:
9878 case QRhiTexture::D24S8:
9879 case QRhiTexture::D32F:
9880 bpc = 4;
9881 break;
9882
9883 case QRhiTexture::D32FS8:
9884 bpc = 8;
9885 break;
9886
9887 case QRhiTexture::R8SI:
9888 case QRhiTexture::R8UI:
9889 bpc = 1;
9890 break;
9891 case QRhiTexture::R32SI:
9892 case QRhiTexture::R32UI:
9893 bpc = 4;
9894 break;
9895 case QRhiTexture::RG32SI:
9896 case QRhiTexture::RG32UI:
9897 bpc = 8;
9898 break;
9899 case QRhiTexture::RGBA32SI:
9900 case QRhiTexture::RGBA32UI:
9901 bpc = 16;
9902 break;
9903
9904 default:
9905 Q_UNREACHABLE();
9906 break;
9907 }
9908
9909 const quint32 width = uint(qMax(0, size.width()));
9910 const quint32 height = uint(qMax(0, size.height()));
9911
9912 if (bytesPerPixel)
9913 *bytesPerPixel = bpc;
9914
9915 // Compute in 64-bit, as safety for extreme geometry that would not fit.
9916 const quint64 bytesPerLine = quint64(width) * quint64(bpc);
9917 const quint64 pixelCount = quint64(width) * quint64(height);
9918 if (bytesPerLine > std::numeric_limits<quint32>::max()
9919 || pixelCount > std::numeric_limits<quint32>::max() / bpc)
9920 {
9921 qWarning("Texture of size %dx%d with format %d has a byte size "
9922 "which is too large to be handled",
9923 size.width(), size.height(), int(format));
9924 if (bpl)
9925 *bpl = 0;
9926 if (byteSize)
9927 *byteSize = 0;
9928 return false;
9929 }
9930
9931 if (bpl)
9932 *bpl = quint32(bytesPerLine);
9933 if (byteSize)
9934 *byteSize = quint32(pixelCount * quint64(bpc));
9935
9936 return true;
9937}
9938
9939bool QRhiImplementation::isStencilSupportingFormat(QRhiTexture::Format format) const
9940{
9941 switch (format) {
9942 case QRhiTexture::D24S8:
9943 case QRhiTexture::D32FS8:
9944 return true;
9945 default:
9946 break;
9947 }
9948 return false;
9949}
9950
9951bool QRhiImplementation::sanityCheckGraphicsPipeline(QRhiGraphicsPipeline *ps)
9952{
9953 if (ps->cbeginShaderStages() == ps->cendShaderStages()) {
9954 qWarning("Cannot build a graphics pipeline without any stages");
9955 return false;
9956 }
9957
9958 bool hasVertexStage = false;
9959 for (auto it = ps->cbeginShaderStages(), itEnd = ps->cendShaderStages(); it != itEnd; ++it) {
9960 if (!it->shader().isValid()) {
9961 qWarning("Empty shader passed to graphics pipeline");
9962 return false;
9963 }
9964 if (it->type() == QRhiShaderStage::Vertex)
9965 hasVertexStage = true;
9966 }
9967 if (!hasVertexStage) {
9968 qWarning("Cannot build a graphics pipeline without a vertex stage");
9969 return false;
9970 }
9971
9972 if (!ps->renderPassDescriptor()) {
9973 qWarning("Cannot build a graphics pipeline without a QRhiRenderPassDescriptor");
9974 return false;
9975 }
9976
9977 if (!ps->shaderResourceBindings()) {
9978 qWarning("Cannot build a graphics pipeline without QRhiShaderResourceBindings");
9979 return false;
9980 }
9981
9982 if (!isFeatureSupported(QRhi::DualSourceBlend)) {
9983 const auto usesDualSourceBlendFactor = [](QRhiGraphicsPipeline::BlendFactor factor) {
9984 return factor == QRhiGraphicsPipeline::Src1Color
9985 || factor == QRhiGraphicsPipeline::OneMinusSrc1Color
9986 || factor == QRhiGraphicsPipeline::Src1Alpha
9987 || factor == QRhiGraphicsPipeline::OneMinusSrc1Alpha;
9988 };
9989 for (auto it = ps->cbeginTargetBlends(), end = ps->cendTargetBlends(); it != end; ++it) {
9990 const auto &blend = *it;
9991 if (blend.enable
9992 && (usesDualSourceBlendFactor(blend.srcColor)
9993 || usesDualSourceBlendFactor(blend.dstColor)
9994 || usesDualSourceBlendFactor(blend.srcAlpha)
9995 || usesDualSourceBlendFactor(blend.dstAlpha))) {
9996 qWarning("Dual-source blending is not supported by this backend");
9997 return false;
9998 }
9999 }
10000 }
10001
10002 return true;
10003}
10004
10005bool QRhiImplementation::sanityCheckShaderResourceBindings(QRhiShaderResourceBindings *srb)
10006{
10007#ifndef QT_NO_DEBUG
10008 bool bindingsOk = true;
10009 const int CHECKED_BINDINGS_COUNT = 64;
10010 bool bindingSeen[CHECKED_BINDINGS_COUNT] = {};
10011 for (auto it = srb->cbeginBindings(), end = srb->cendBindings(); it != end; ++it) {
10012 const int binding = shaderResourceBindingData(*it)->binding;
10013 if (binding >= CHECKED_BINDINGS_COUNT)
10014 continue;
10015 if (binding < 0) {
10016 qWarning("Invalid binding number %d", binding);
10017 bindingsOk = false;
10018 continue;
10019 }
10020 switch (shaderResourceBindingData(*it)->type()) {
10021 case QRhiShaderResourceBinding::UniformBuffer:
10022 if (!bindingSeen[binding]) {
10023 bindingSeen[binding] = true;
10024 } else {
10025 qWarning("Uniform buffer duplicates an existing binding number %d", binding);
10026 bindingsOk = false;
10027 }
10028 break;
10029 case QRhiShaderResourceBinding::SampledTexture:
10030 if (!bindingSeen[binding]) {
10031 bindingSeen[binding] = true;
10032 } else {
10033 qWarning("Combined image sampler duplicates an existing binding number %d", binding);
10034 bindingsOk = false;
10035 }
10036 break;
10037 case QRhiShaderResourceBinding::Texture:
10038 if (!bindingSeen[binding]) {
10039 bindingSeen[binding] = true;
10040 } else {
10041 qWarning("Texture duplicates an existing binding number %d", binding);
10042 bindingsOk = false;
10043 }
10044 break;
10045 case QRhiShaderResourceBinding::Sampler:
10046 if (!bindingSeen[binding]) {
10047 bindingSeen[binding] = true;
10048 } else {
10049 qWarning("Sampler duplicates an existing binding number %d", binding);
10050 bindingsOk = false;
10051 }
10052 break;
10053 case QRhiShaderResourceBinding::ImageLoad:
10054 case QRhiShaderResourceBinding::ImageStore:
10055 case QRhiShaderResourceBinding::ImageLoadStore:
10056 if (!bindingSeen[binding]) {
10057 bindingSeen[binding] = true;
10058 } else {
10059 qWarning("Image duplicates an existing binding number %d", binding);
10060 bindingsOk = false;
10061 }
10062 break;
10063 case QRhiShaderResourceBinding::BufferLoad:
10064 case QRhiShaderResourceBinding::BufferStore:
10065 case QRhiShaderResourceBinding::BufferLoadStore:
10066 if (!bindingSeen[binding]) {
10067 bindingSeen[binding] = true;
10068 } else {
10069 qWarning("Buffer duplicates an existing binding number %d", binding);
10070 bindingsOk = false;
10071 }
10072 break;
10073 default:
10074 qWarning("Unknown binding type %d", int(shaderResourceBindingData(*it)->type()));
10075 bindingsOk = false;
10076 break;
10077 }
10078 }
10079
10080 if (!bindingsOk) {
10081 qWarning() << *srb;
10082 return false;
10083 }
10084#else
10085 Q_UNUSED(srb);
10086#endif
10087 return true;
10088}
10089
10090bool QRhiImplementation::sanityCheckResourceOwnership(QRhiResource *maybeResource)
10091{
10092 if (maybeResource == nullptr || maybeResource->m_rhi == nullptr)
10093 return true;
10094
10095 if (maybeResource->m_rhi->q != q) {
10096 qWarning("%s %p (%s) belongs to QRhi %p, but client code attempted to use it with QRhi %p. This is wrong.",
10097 resourceTypeStr(maybeResource),
10098 maybeResource,
10099 maybeResource->m_objectName.constData(),
10100 maybeResource->m_rhi->q,
10101 q);
10102 return false;
10103 }
10104
10105 return true;
10106}
10107
10108int QRhiImplementation::effectiveSampleCount(int sampleCount) const
10109{
10110 // Stay compatible with QSurfaceFormat and friends where samples == 0 means the same as 1.
10111 const int s = qBound(1, sampleCount, 64);
10112 const QList<int> supported = supportedSampleCounts();
10113 int result = 1;
10114
10115 // Stay compatible with Qt 5 in that requesting an unsupported sample count
10116 // is not an error (although we still do a categorized debug print about
10117 // this), and rather a supported value, preferably a close one, not just 1,
10118 // is used instead. This is actually deviating from Qt 5 as that performs a
10119 // clamping only and does not handle cases such as when sample count 2 is
10120 // not supported but 4 is. (OpenGL handles things like that gracefully,
10121 // other APIs may not, so improve this by picking the next largest, or in
10122 // absence of that, the largest value; this with the goal to not reduce
10123 // quality by rather picking a larger-than-requested value than a smaller one)
10124
10125 for (int i = 0, ie = supported.count(); i != ie; ++i) {
10126 // assumes the 'supported' list is sorted
10127 if (supported[i] >= s) {
10128 result = supported[i];
10129 break;
10130 }
10131 }
10132
10133 if (result != s) {
10134 if (result == 1 && !supported.isEmpty())
10135 result = supported.last();
10136 qCDebug(QRHI_LOG_INFO, "Attempted to set unsupported sample count %d, using %d instead",
10137 sampleCount, result);
10138 }
10139
10140 return result;
10141}
10142
10143/*!
10144 \internal
10145 */
10146QRhi::QRhi()
10147{
10148}
10149
10150/*!
10151 Destructor. Destroys the backend and releases resources.
10152 */
10153QRhi::~QRhi()
10154{
10155 if (!d)
10156 return;
10157
10158 if (qrhiDebugHooks.rhiAboutToBeDestroyed)
10159 qrhiDebugHooks.rhiAboutToBeDestroyed(d);
10160
10161 d->runCleanup();
10162
10163 qDeleteAll(d->pendingDeleteResources);
10164 d->pendingDeleteResources.clear();
10165
10166 d->destroy();
10167 delete d;
10168}
10169
10170QRhiImplementation *QRhiImplementation::newInstance(QRhi::Implementation impl, QRhiInitParams *params, QRhiNativeHandles *importDevice)
10171{
10172 QRhiImplementation *d = nullptr;
10173
10174 switch (impl) {
10175 case QRhi::Null:
10176 d = new QRhiNull(static_cast<QRhiNullInitParams *>(params));
10177 break;
10178 case QRhi::Vulkan:
10179#if QT_CONFIG(vulkan)
10180 d = new QRhiVulkan(static_cast<QRhiVulkanInitParams *>(params),
10181 static_cast<QRhiVulkanNativeHandles *>(importDevice));
10182 break;
10183#else
10184 Q_UNUSED(importDevice);
10185 qWarning("This build of Qt has no Vulkan support");
10186 break;
10187#endif
10188 case QRhi::OpenGLES2:
10189#ifndef QT_NO_OPENGL
10190 d = new QRhiGles2(static_cast<QRhiGles2InitParams *>(params),
10191 static_cast<QRhiGles2NativeHandles *>(importDevice));
10192 break;
10193#else
10194 qWarning("This build of Qt has no OpenGL support");
10195 break;
10196#endif
10197 case QRhi::D3D11:
10198#ifdef Q_OS_WIN
10199 d = new QRhiD3D11(static_cast<QRhiD3D11InitParams *>(params),
10200 static_cast<QRhiD3D11NativeHandles *>(importDevice));
10201 break;
10202#else
10203 qWarning("This platform has no Direct3D 11 support");
10204 break;
10205#endif
10206 case QRhi::Metal:
10207#if QT_CONFIG(metal)
10208 d = new QRhiMetal(static_cast<QRhiMetalInitParams *>(params),
10209 static_cast<QRhiMetalNativeHandles *>(importDevice));
10210 break;
10211#else
10212 qWarning("This platform has no Metal support");
10213 break;
10214#endif
10215 case QRhi::D3D12:
10216#ifdef Q_OS_WIN
10217#ifdef QRHI_D3D12_AVAILABLE
10218 d = new QRhiD3D12(static_cast<QRhiD3D12InitParams *>(params),
10219 static_cast<QRhiD3D12NativeHandles *>(importDevice));
10220 break;
10221#else
10222 qWarning("Qt was built without Direct3D 12 support. "
10223 "This is likely due to having ancient SDK headers (such as d3d12.h) in the Qt build environment. "
10224 "Rebuild Qt with an SDK supporting D3D12 features introduced in Windows 10 version 1703, "
10225 "or use an MSVC build as those typically are built with more up-to-date SDKs.");
10226 break;
10227#endif
10228#else
10229 qWarning("This platform has no Direct3D 12 support");
10230 break;
10231#endif
10232 }
10233
10234 return d;
10235}
10236
10237void QRhiImplementation::prepareForCreate(QRhi *rhi, QRhi::Implementation impl, QRhi::Flags flags, QRhiAdapter *adapter)
10238{
10239 q = rhi;
10240
10241 debugMarkers = flags.testFlag(QRhi::EnableDebugMarkers);
10242 timestamps = flags.testFlag(QRhi::EnableTimestamps);
10243
10244 implType = impl;
10245 implThread = QThread::currentThread();
10246
10247 requestedRhiAdapter = adapter;
10248}
10249
10250QRhi::AdapterList QRhiImplementation::enumerateAdaptersBeforeCreate(QRhiNativeHandles *) const
10251{
10252 return {};
10253}
10254
10255/*!
10256 \overload
10257
10258 Equivalent to create(\a impl, \a params, \a flags, \a importDevice, \c nullptr).
10259 */
10260QRhi *QRhi::create(Implementation impl, QRhiInitParams *params, Flags flags, QRhiNativeHandles *importDevice)
10261{
10262 return create(impl, params, flags, importDevice, nullptr);
10263}
10264
10265/*!
10266 \return a new QRhi instance with a backend for the graphics API specified
10267 by \a impl with the specified \a flags. \return \c nullptr if the
10268 function fails.
10269
10270 \a params must point to an instance of one of the backend-specific
10271 subclasses of QRhiInitParams, such as, QRhiVulkanInitParams,
10272 QRhiMetalInitParams, QRhiD3D11InitParams, QRhiD3D12InitParams,
10273 QRhiGles2InitParams. See these classes for examples on creating a QRhi.
10274
10275 QRhi by design does not implement any fallback logic: if the specified API
10276 cannot be initialized, create() will fail, with warnings printed on the
10277 debug output by the backends. The clients of QRhi, for example Qt Quick,
10278 may however provide additional logic that allow falling back to an API
10279 different than what was requested, depending on the platform. If the
10280 intention is just to test if initialization would succeed when calling
10281 create() at later point, it is preferable to use probe() instead of
10282 create(), because with some backends probing can be implemented in a more
10283 lightweight manner as opposed to create(), which performs full
10284 initialization of the infrastructure and is wasteful if that QRhi instance
10285 is then thrown immediately away.
10286
10287 \a importDevice allows using an already existing graphics device, without
10288 QRhi creating its own. When not null, this parameter must point to an
10289 instance of one of the subclasses of QRhiNativeHandles:
10290 QRhiVulkanNativeHandles, QRhiD3D11NativeHandles, QRhiD3D12NativeHandles,
10291 QRhiMetalNativeHandles, QRhiGles2NativeHandles. The exact details and
10292 semantics depend on the backand and the underlying graphics API.
10293
10294 Specifying a QRhiAdapter in \a adapter offers a transparent, cross-API
10295 alternative to passing in a \c VkPhysicalDevice via QRhiVulkanNativeHandles,
10296 or an adapter LUID via QRhiD3D12NativeHandles. The ownership of \a adapter
10297 is not taken. See enumerateAdapters() for more information on this approach.
10298
10299 \note \a importDevice and \a adapter cannot be both specified.
10300
10301 \sa probe()
10302 */
10303QRhi *QRhi::create(Implementation impl, QRhiInitParams *params, Flags flags, QRhiNativeHandles *importDevice, QRhiAdapter *adapter)
10304{
10305 if (adapter && importDevice)
10306 qWarning("adapter and importDevice should not both be non-null in QRhi::create()");
10307
10308 std::unique_ptr<QRhiImplementation> rd(QRhiImplementation::newInstance(impl, params, importDevice));
10309 if (!rd)
10310 return nullptr;
10311
10312 std::unique_ptr<QRhi> r(new QRhi);
10313 r->d = rd.release();
10314 r->d->prepareForCreate(r.get(), impl, flags, adapter);
10315 if (!r->d->create(flags))
10316 return nullptr;
10317
10318 return r.release();
10319}
10320
10321/*!
10322 \return true if create() can be expected to succeed when called the given
10323 \a impl and \a params.
10324
10325 For some backends this is equivalent to calling create(), checking its
10326 return value, and then destroying the resulting QRhi.
10327
10328 For others, in particular with Metal, there may be a specific probing
10329 implementation, which allows testing in a more lightweight manner without
10330 polluting the debug output with warnings upon failures.
10331
10332 \sa create()
10333 */
10334bool QRhi::probe(QRhi::Implementation impl, QRhiInitParams *params)
10335{
10336 bool ok = false;
10337
10338 // The only place currently where this makes sense is Metal, where the API
10339 // is simple enough so that a special probing function - doing nothing but
10340 // a MTLCreateSystemDefaultDevice - is reasonable. Elsewhere, just call
10341 // create() and then drop the result.
10342
10343 if (impl == Metal) {
10344#if QT_CONFIG(metal)
10345 ok = QRhiMetal::probe(static_cast<QRhiMetalInitParams *>(params));
10346#endif
10347 } else {
10348 QRhi *rhi = create(impl, params);
10349 ok = rhi != nullptr;
10350 delete rhi;
10351 }
10352 return ok;
10353}
10354
10355/*!
10356 \typedef QRhi::AdapterList
10357 \relates QRhi
10358 \since 6.10
10359
10360 Synonym for QVector<QRhiAdapter *>.
10361*/
10362
10363/*!
10364 \return the list of adapters (physical devices) present, or an empty list
10365 when such control is not available with a given graphics API.
10366
10367 Backends where such level of control is not available, the returned list is
10368 always empty. Thus an empty list does not indicate there are no graphics
10369 devices in the system, but that fine-grained control over selecting which
10370 one to use is not available.
10371
10372 Backends for Direct 3D 11, Direct 3D 12, and Vulkan can be expected to fully
10373 support enumerating adapters. Others may not. The backend is specified by \a
10374 impl. A QRhiAdapter returned from this function must only be used in a
10375 create() call with the same \a impl. Some underlying APIs may present
10376 further limitations, with Vulkan in particular the QRhiAdapter is specified
10377 to the QVulkanInstance (\c VkInstance).
10378
10379 The caller is expected to destroy the QRhiAdapter objects in the list. Apart
10380 from querying \l{QRhiAdapter::}{info()}, the only purpose of these objects is
10381 to be passed on to create(), or the corresponding functions in higher layers
10382 such as Qt Quick.
10383
10384 The following snippet, written specifically for Vulkan, shows how to
10385 enumerate the available physical devices and request to create a QRhi for
10386 the chosen one. This in practice is equivalent to passing in a \c
10387 VkPhysicalDevice via a QRhiVulkanNativeHandles to create(), but it involves
10388 less API-specific code on the application side:
10389
10390 \code
10391 QRhiVulkanInitParams initParams;
10392 initParams.inst = &vulkanInstance;
10393 QRhi::AdapterList adapters = QRhi::enumerateAdapters(QRhi::Vulkan, &initParams);
10394 QRhiAdapter *chosenAdapter = nullptr;
10395 for (QRhiAdapter *adapter : adapters) {
10396 if (looksGood(adapter->info())) {
10397 chosenAdapter = adapter;
10398 break;
10399 }
10400 }
10401 QRhi *rhi = QRhi::create(QRhi::Vulkan, &initParams, {}, nullptr, chosenAdapter);
10402 qDeleteAll(adapters);
10403 \endcode
10404
10405 Passing in \a params is required due to some of the underlying graphics
10406 APIs' design. With Vulkan in particular, the QVulkanInstance must be
10407 provided, since enumerating is not possible without it. Other fields in the
10408 backend-specific \a params will not actually be used by this function.
10409
10410 \a nativeHandles is optional. When specified, it must be a valid
10411 QRhiD3D11NativeHandles, QRhiD3D12NativeHandles, or QRhiVulkanNativeHandles,
10412 similarly to create(). However, unlike create(), only the physical device
10413 (in case of Vulkan) or the adapter LUID (in case of D3D) fields are used,
10414 all other fields are ignored. This can be used the restrict the results to a
10415 given adapter. The returned list will contain 1 or 0 elements in this case.
10416
10417 Note how in the previous code snippet the looksGood() function
10418 implementation cannot perform any platform-specific filtering based on the
10419 true adapter / physical device identity, such as the adapter LUID on Windows
10420 or the VkPhysicalDevice with Vulkan. This is because QRhiDriverInfo does not
10421 contain platform-specific data. Instead, use \a nativeHandles to get the
10422 results filtered already inside enumerateAdapters().
10423
10424 The following two snippets, using Direct 3D 12 as an example, are equivalent
10425 in practice:
10426
10427 \code
10428 // enumerateAdapters-based approach from Qt 6.10 on
10429 QRhiD3D12InitParams initParams;
10430 QRhiD3D12NativeHandles nativeHandles;
10431 nativeHandles.adapterLuidLow = luid.LowPart; // retrieved a LUID from somewhere, now pass it on to Qt
10432 nativeHandles.adapterLuidHigh = luid.HighPart;
10433 QRhi::AdapterList adapters = QRhi::enumerateAdapters(QRhi::D3D12, &initParams, &nativeHandles);
10434 if (adapters.isEmpty()) { qWarning("Requested adapter was not found"); }
10435 QRhi *rhi = QRhi::create(QRhi::D3D12, &initParams, {}, nullptr, adapters[0]);
10436 qDeleteAll(adapters);
10437 \endcode
10438
10439 \code
10440 // traditional approach, more lightweight
10441 QRhiD3D12InitParams initParams;
10442 QRhiD3D12NativeHandles nativeHandles;
10443 nativeHandles.adapterLuidLow = luid.LowPart; // retrieved a LUID from somewhere, now pass it on to Qt
10444 nativeHandles.adapterLuidHigh = luid.HighPart;
10445 QRhi *rhi = QRhi::create(QRhi::D3D12, &initParams, {}, &nativeHandles, nullptr);
10446 \endcode
10447
10448 \since 6.10
10449 \sa create()
10450 */
10451QRhi::AdapterList QRhi::enumerateAdapters(Implementation impl, QRhiInitParams *params, QRhiNativeHandles *nativeHandles)
10452{
10453 std::unique_ptr<QRhiImplementation> rd(QRhiImplementation::newInstance(impl, params, nullptr));
10454 if (!rd)
10455 return {};
10456
10457 return rd->enumerateAdaptersBeforeCreate(nativeHandles);
10458}
10459
10460/*!
10461 \struct QRhiSwapChainProxyData
10462 \inmodule QtGuiPrivate
10463 \inheaderfile rhi/qrhi.h
10464 \since 6.6
10465
10466 \brief Opaque data describing native objects needed to set up a swapchain.
10467
10468 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
10469 for details.
10470
10471 \sa QRhi::updateSwapChainProxyData()
10472 */
10473
10474/*!
10475 Generates and returns a QRhiSwapChainProxyData struct containing opaque
10476 data specific to the backend and graphics API specified by \a impl. \a
10477 window is the QWindow a swapchain is targeting.
10478
10479 The returned struct can be passed to QRhiSwapChain::setProxyData(). This
10480 makes sense in threaded rendering systems: this static function is expected
10481 to be called on the \b{main (gui) thread}, unlike all QRhi operations, then
10482 transferred to the thread working with the QRhi and QRhiSwapChain and passed
10483 on to the swapchain. This allows doing native platform queries that are
10484 only safe to be called on the main thread, for example to query the
10485 CAMetalLayer from a NSView, and then passing on the data to the
10486 QRhiSwapChain living on the rendering thread. With the Metal example, doing
10487 the view.layer access on a dedicated rendering thread causes a warning in
10488 the Xcode Thread Checker. With the data proxy mechanism, this is avoided.
10489
10490 When threads are not involved, generating and passing on the
10491 QRhiSwapChainProxyData is not required: backends are guaranteed to be able
10492 to query whatever is needed on their own, and if everything lives on the
10493 main (gui) thread, that should be sufficient.
10494
10495 \note \a impl should match what the QRhi is created with. For example,
10496 calling with QRhi::Metal on a non-Apple platform will not generate any
10497 useful data.
10498 */
10499QRhiSwapChainProxyData QRhi::updateSwapChainProxyData(QRhi::Implementation impl, QWindow *window)
10500{
10501#if QT_CONFIG(metal)
10502 if (impl == Metal)
10503 return QRhiMetal::updateSwapChainProxyData(window);
10504#else
10505 Q_UNUSED(impl);
10506 Q_UNUSED(window);
10507#endif
10508 return {};
10509}
10510
10511/*!
10512 \return the backend type for this QRhi.
10513 */
10514QRhi::Implementation QRhi::backend() const
10515{
10516 return d->implType;
10517}
10518
10519/*!
10520 \return a friendly name for the backend \a impl, usually the name of the 3D
10521 API in use.
10522 */
10523const char *QRhi::backendName(Implementation impl)
10524{
10525 switch (impl) {
10526 case QRhi::Null:
10527 return "Null";
10528 case QRhi::Vulkan:
10529 return "Vulkan";
10530 case QRhi::OpenGLES2:
10531 return "OpenGL";
10532 case QRhi::D3D11:
10533 return "D3D11";
10534 case QRhi::Metal:
10535 return "Metal";
10536 case QRhi::D3D12:
10537 return "D3D12";
10538 }
10539
10540 Q_UNREACHABLE_RETURN("Unknown");
10541}
10542
10543/*!
10544 \return the backend type as string for this QRhi.
10545 */
10546const char *QRhi::backendName() const
10547{
10548 return backendName(d->implType);
10549}
10550
10551/*!
10552 \enum QRhiDriverInfo::DeviceType
10553 Specifies the graphics device's type, when the information is available.
10554
10555 In practice this is only applicable with Vulkan and Metal. With Direct 3D
10556 11 and 12, using an adapter with the software flag set leads to the value
10557 \c CpuDevice. Otherwise, and with OpenGL, the value is always UnknownDevice.
10558
10559 \value UnknownDevice
10560 \value IntegratedDevice
10561 \value DiscreteDevice
10562 \value ExternalDevice
10563 \value VirtualDevice
10564 \value CpuDevice
10565*/
10566
10567/*!
10568 \struct QRhiDriverInfo
10569 \inmodule QtGuiPrivate
10570 \inheaderfile rhi/qrhi.h
10571 \since 6.6
10572
10573 \brief Describes the physical device, adapter, or graphics API
10574 implementation that is used by an initialized QRhi.
10575
10576 Graphics APIs offer different levels and kinds of information. The only
10577 value that is available across all APIs is the deviceName, which is a
10578 freetext description of the physical device, adapter, or is a combination
10579 of the strings reported for \c{GL_VENDOR} + \c{GL_RENDERER} +
10580 \c{GL_VERSION}. The deviceId is always 0 for OpenGL. vendorId is always 0
10581 for OpenGL and Metal. deviceType is always UnknownDevice for OpenGL and
10582 Direct 3D.
10583
10584 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
10585 for details.
10586 */
10587
10588/*!
10589 \variable QRhiDriverInfo::deviceName
10590
10591 \sa QRhi::driverInfo()
10592*/
10593
10594/*!
10595 \variable QRhiDriverInfo::deviceId
10596
10597 \sa QRhi::driverInfo()
10598*/
10599
10600/*!
10601 \variable QRhiDriverInfo::vendorId
10602
10603 \sa QRhi::driverInfo()
10604*/
10605
10606/*!
10607 \variable QRhiDriverInfo::deviceType
10608
10609 \sa QRhi::driverInfo(), QRhiDriverInfo::DeviceType
10610*/
10611
10612#ifndef QT_NO_DEBUG_STREAM
10613static inline const char *deviceTypeStr(QRhiDriverInfo::DeviceType type)
10614{
10615 switch (type) {
10616 case QRhiDriverInfo::UnknownDevice:
10617 return "Unknown";
10618 case QRhiDriverInfo::IntegratedDevice:
10619 return "Integrated";
10620 case QRhiDriverInfo::DiscreteDevice:
10621 return "Discrete";
10622 case QRhiDriverInfo::ExternalDevice:
10623 return "External";
10624 case QRhiDriverInfo::VirtualDevice:
10625 return "Virtual";
10626 case QRhiDriverInfo::CpuDevice:
10627 return "Cpu";
10628 }
10629
10630 Q_UNREACHABLE_RETURN(nullptr);
10631}
10632QDebug operator<<(QDebug dbg, const QRhiDriverInfo &info)
10633{
10634 QDebugStateSaver saver(dbg);
10635 dbg.nospace() << "QRhiDriverInfo(deviceName=" << info.deviceName
10636 << " deviceId=0x" << Qt::hex << info.deviceId
10637 << " vendorId=0x" << info.vendorId
10638 << " deviceType=" << deviceTypeStr(info.deviceType)
10639 << ')';
10640 return dbg;
10641}
10642#endif
10643
10644/*!
10645 \return metadata for the graphics device used by this successfully
10646 initialized QRhi instance.
10647 */
10648QRhiDriverInfo QRhi::driverInfo() const
10649{
10650 return d->driverInfo();
10651}
10652
10653/*!
10654 \class QRhiAdapter
10655 \inmodule QtGuiPrivate
10656 \inheaderfile rhi/qrhi.h
10657 \since 6.10
10658
10659 \brief Represents a physical graphics device.
10660
10661 Some QRhi backends target graphics APIs that expose the concept of \c
10662 adapters or \c{physical devices}. Call the static \l
10663 {QRhi::}{enumerateAdapters()} function to retrieve a list of the adapters
10664 present in the system. Pass one of the returned QRhiAdapter objects to \l
10665 {QRhi::}{create()} in order to request using the adapter or physical device
10666 the QRhiAdapter corresponds to. Other than exposing the QRhiDriverInfo,
10667 QRhiAdapter is to be treated as an opaque handle.
10668
10669 \note With Vulkan, the QRhiAdapter is valid only as long as the
10670 QVulkanInstance that was used for \l{QRhi::}{enumerateAdapters()} is valid.
10671 This also means that a QRhiAdapter is tied to the Vulkan instance
10672 (QVulkanInstance, \c VkInstance) and cannot be used in the context of
10673 another Vulkan instance.
10674
10675 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
10676 for details.
10677 */
10678
10679/*!
10680 \fn virtual QRhiDriverInfo QRhiAdapter::info() const = 0
10681
10682 \return the corresponding QRhiDriverInfo.
10683 */
10684
10685/*!
10686 \internal
10687 */
10688QRhiAdapter::~QRhiAdapter()
10689{
10690}
10691
10692/*!
10693 \return the thread on which the QRhi was \l{QRhi::create()}{initialized}.
10694 */
10695QThread *QRhi::thread() const
10696{
10697 return d->implThread;
10698}
10699
10700/*!
10701 Registers a \a callback that is invoked when the QRhi is destroyed.
10702
10703 The callback will run with the graphics resource still available, so this
10704 provides an opportunity for the application to cleanly release QRhiResource
10705 instances belonging to the QRhi. This is particularly useful for managing
10706 the lifetime of resources stored in \c cache type of objects, where the
10707 cache holds QRhiResources or objects containing QRhiResources.
10708
10709 \sa ~QRhi()
10710 */
10711void QRhi::addCleanupCallback(const CleanupCallback &callback)
10712{
10713 d->addCleanupCallback(callback);
10714}
10715
10716/*!
10717 \overload
10718
10719 Registers \a callback to be invoked when the QRhi is destroyed. This
10720 overload takes an opaque pointer, \a key, that is used to ensure that a
10721 given callback is registered (and so called) only once.
10722
10723 \sa removeCleanupCallback()
10724 */
10725void QRhi::addCleanupCallback(const void *key, const CleanupCallback &callback)
10726{
10727 d->addCleanupCallback(key, callback);
10728}
10729
10730/*!
10731 Deregisters the callback with \a key. If no cleanup callback was registered
10732 with \a key, the function does nothing. Callbacks registered without a key
10733 cannot be removed.
10734
10735 \sa addCleanupCallback()
10736 */
10737void QRhi::removeCleanupCallback(const void *key)
10738{
10739 d->removeCleanupCallback(key);
10740}
10741
10742void QRhiImplementation::runCleanup()
10743{
10744 for (const QRhi::CleanupCallback &f : std::as_const(cleanupCallbacks))
10745 f(q);
10746
10747 cleanupCallbacks.clear();
10748
10749 for (auto it = keyedCleanupCallbacks.cbegin(), end = keyedCleanupCallbacks.cend(); it != end; ++it)
10750 it.value()(q);
10751
10752 keyedCleanupCallbacks.clear();
10753}
10754
10755/*!
10756 \class QRhiResourceUpdateBatch
10757 \inmodule QtGuiPrivate
10758 \inheaderfile rhi/qrhi.h
10759 \since 6.6
10760 \brief Records upload and copy type of operations.
10761
10762 With QRhi it is no longer possible to perform copy type of operations at
10763 arbitrary times. Instead, all such operations are recorded into batches
10764 that are then passed, most commonly, to QRhiCommandBuffer::beginPass().
10765 What then happens under the hood is hidden from the application: the
10766 underlying implementations can defer and implement these operations in
10767 various different ways.
10768
10769 A resource update batch owns no graphics resources and does not perform any
10770 actual operations on its own. It should rather be viewed as a command
10771 buffer for update, upload, and copy type of commands.
10772
10773 To get an available, empty batch from the pool, call
10774 QRhi::nextResourceUpdateBatch().
10775
10776 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
10777 for details.
10778 */
10779
10780/*!
10781 \internal
10782 */
10783QRhiResourceUpdateBatch::QRhiResourceUpdateBatch(QRhiImplementation *rhi)
10784 : d(new QRhiResourceUpdateBatchPrivate)
10785{
10786 d->q = this;
10787 d->rhi = rhi;
10788}
10789
10790QRhiResourceUpdateBatch::~QRhiResourceUpdateBatch()
10791{
10792 delete d;
10793}
10794
10795/*!
10796 \return the batch to the pool. This should only be used when the batch is
10797 not passed to one of QRhiCommandBuffer::beginPass(),
10798 QRhiCommandBuffer::endPass(), or QRhiCommandBuffer::resourceUpdate()
10799 because these implicitly call destroy().
10800
10801 \note QRhiResourceUpdateBatch instances must never by \c deleted by
10802 applications.
10803 */
10804void QRhiResourceUpdateBatch::release()
10805{
10806 d->free();
10807}
10808
10809/*!
10810 Copies all queued operations from the \a other batch into this one.
10811
10812 \note \a other may no longer contain valid data after the merge operation,
10813 and must not be submitted, but it will still need to be released by calling
10814 release().
10815
10816 This allows for a convenient pattern where resource updates that are
10817 already known during the initialization step are collected into a batch
10818 that is then merged into another when starting to first render pass later
10819 on:
10820
10821 \code
10822 void init()
10823 {
10824 initialUpdates = rhi->nextResourceUpdateBatch();
10825 initialUpdates->uploadStaticBuffer(vbuf, vertexData);
10826 initialUpdates->uploadStaticBuffer(ibuf, indexData);
10827 // ...
10828 }
10829
10830 void render()
10831 {
10832 QRhiResourceUpdateBatch *resUpdates = rhi->nextResourceUpdateBatch();
10833 if (initialUpdates) {
10834 resUpdates->merge(initialUpdates);
10835 initialUpdates->release();
10836 initialUpdates = nullptr;
10837 }
10838 // resUpdates->updateDynamicBuffer(...);
10839 cb->beginPass(rt, clearCol, clearDs, resUpdates);
10840 }
10841 \endcode
10842 */
10843void QRhiResourceUpdateBatch::merge(QRhiResourceUpdateBatch *other)
10844{
10845 d->merge(other->d);
10846}
10847
10848/*!
10849 \return true until the number of buffer and texture operations enqueued
10850 onto this batch is below a reasonable limit.
10851
10852 The return value is false when the number of buffer and/or texture
10853 operations added to this batch have reached, or are about to reach, a
10854 certain limit. The batch is fully functional afterwards as well, but may
10855 need to allocate additional memory. Therefore, a renderer that collects
10856 lots of buffer and texture updates in a single batch when preparing a frame
10857 may want to consider \l{QRhiCommandBuffer::resourceUpdate()}{submitting the
10858 batch} and \l{QRhi::nextResourceUpdateBatch()}{starting a new one} when
10859 this function returns false.
10860 */
10861bool QRhiResourceUpdateBatch::hasOptimalCapacity() const
10862{
10863 return d->hasOptimalCapacity();
10864}
10865
10866/*!
10867 Enqueues updating a region of a QRhiBuffer \a buf created with the type
10868 QRhiBuffer::Dynamic.
10869
10870 The region is specified \a offset and \a size. The actual bytes to write
10871 are specified by \a data which must have at least \a size bytes available.
10872
10873 \a data is copied and can safely be destroyed or changed once this function
10874 returns.
10875
10876 \note If host writes are involved, which is the case with
10877 updateDynamicBuffer() typically as such buffers are backed by host visible
10878 memory with most backends, they may accumulate within a frame. Thus pass 1
10879 reading a region changed by a batch passed to pass 2 may see the changes
10880 specified in pass 2's update batch.
10881
10882 \note QRhi transparently manages double buffering in order to prevent
10883 stalling the graphics pipeline. The fact that a QRhiBuffer may have
10884 multiple native buffer objects underneath can be safely ignored when using
10885 the QRhi and QRhiResourceUpdateBatch.
10886 */
10887void QRhiResourceUpdateBatch::updateDynamicBuffer(QRhiBuffer *buf, quint32 offset, quint32 size, const void *data)
10888{
10889 if (size > 0) {
10890 const int idx = d->activeBufferOpCount++;
10891 const int opListSize = d->bufferOps.size();
10892 if (idx < opListSize)
10893 QRhiResourceUpdateBatchPrivate::BufferOp::changeToDynamicUpdate(&d->bufferOps[idx], buf, offset, size, data);
10894 else
10895 d->bufferOps.append(QRhiResourceUpdateBatchPrivate::BufferOp::dynamicUpdate(buf, offset, size, data));
10896 }
10897}
10898
10899/*!
10900 \overload
10901 \since 6.10
10902
10903 Enqueues updating a region of a QRhiBuffer \a buf created with the type
10904 QRhiBuffer::Dynamic.
10905
10906 \a data is moved into the batch instead of copied with this overload.
10907 */
10908void QRhiResourceUpdateBatch::updateDynamicBuffer(QRhiBuffer *buf, quint32 offset, QByteArray data)
10909{
10910 if (!data.isEmpty()) {
10911 const int idx = d->activeBufferOpCount++;
10912 const int opListSize = d->bufferOps.size();
10913 if (idx < opListSize)
10914 QRhiResourceUpdateBatchPrivate::BufferOp::changeToDynamicUpdate(&d->bufferOps[idx], buf, offset, std::move(data));
10915 else
10916 d->bufferOps.append(QRhiResourceUpdateBatchPrivate::BufferOp::dynamicUpdate(buf, offset, std::move(data)));
10917 }
10918}
10919
10920/*!
10921 Enqueues updating a region of a QRhiBuffer \a buf created with the type
10922 QRhiBuffer::Immutable or QRhiBuffer::Static.
10923
10924 The region is specified \a offset and \a size. The actual bytes to write
10925 are specified by \a data which must have at least \a size bytes available.
10926
10927 \a data is copied and can safely be destroyed or changed once this function
10928 returns.
10929
10930 \note Whether the upload is performed on the GPU timeline, and so is ordered
10931 against the other operations recorded in the same batch, is indicated by the
10932 \l QRhi::StaticBuffersOnGpuTimeline feature. This only matters when
10933 combining uploads with
10934 \l{QRhiResourceUpdateBatch::copyBuffer()}{copyBuffer()} on the same buffer.
10935
10936 \sa copyBuffer()
10937 */
10938void QRhiResourceUpdateBatch::uploadStaticBuffer(QRhiBuffer *buf, quint32 offset, quint32 size, const void *data)
10939{
10940 if (size > 0) {
10941 const int idx = d->activeBufferOpCount++;
10942 if (idx < d->bufferOps.size())
10943 QRhiResourceUpdateBatchPrivate::BufferOp::changeToStaticUpload(&d->bufferOps[idx], buf, offset, size, data);
10944 else
10945 d->bufferOps.append(QRhiResourceUpdateBatchPrivate::BufferOp::staticUpload(buf, offset, size, data));
10946 }
10947}
10948
10949/*!
10950 \overload
10951 \since 6.10
10952
10953 Enqueues updating a region of a QRhiBuffer \a buf created with the type
10954 QRhiBuffer::Immutable or QRhiBuffer::Static.
10955
10956 \a data is moved into the batch instead of copied with this overload.
10957 */
10958void QRhiResourceUpdateBatch::uploadStaticBuffer(QRhiBuffer *buf, quint32 offset, QByteArray data)
10959{
10960 if (!data.isEmpty()) {
10961 const int idx = d->activeBufferOpCount++;
10962 if (idx < d->bufferOps.size())
10963 QRhiResourceUpdateBatchPrivate::BufferOp::changeToStaticUpload(&d->bufferOps[idx], buf, offset, std::move(data));
10964 else
10965 d->bufferOps.append(QRhiResourceUpdateBatchPrivate::BufferOp::staticUpload(buf, offset, std::move(data)));
10966 }
10967}
10968
10969/*!
10970 \overload
10971
10972 Enqueues updating the entire QRhiBuffer \a buf created with the type
10973 QRhiBuffer::Immutable or QRhiBuffer::Static.
10974 */
10975void QRhiResourceUpdateBatch::uploadStaticBuffer(QRhiBuffer *buf, const void *data)
10976{
10977 if (buf->size() > 0) {
10978 const int idx = d->activeBufferOpCount++;
10979 if (idx < d->bufferOps.size())
10980 QRhiResourceUpdateBatchPrivate::BufferOp::changeToStaticUpload(&d->bufferOps[idx], buf, 0, 0, data);
10981 else
10982 d->bufferOps.append(QRhiResourceUpdateBatchPrivate::BufferOp::staticUpload(buf, 0, 0, data));
10983 }
10984}
10985
10986/*!
10987 \overload
10988 \since 6.10
10989
10990 Enqueues updating the entire QRhiBuffer \a buf created with the type
10991 QRhiBuffer::Immutable or QRhiBuffer::Static.
10992
10993 \a data is moved into the batch instead of copied with this overload.
10994
10995 \a data size must equal the size of \a buf.
10996 */
10997void QRhiResourceUpdateBatch::uploadStaticBuffer(QRhiBuffer *buf, QByteArray data)
10998{
10999 if (buf->size() > 0 && quint32(data.size()) == buf->size()) {
11000 const int idx = d->activeBufferOpCount++;
11001 if (idx < d->bufferOps.size())
11002 QRhiResourceUpdateBatchPrivate::BufferOp::changeToStaticUpload(&d->bufferOps[idx], buf, 0, std::move(data));
11003 else
11004 d->bufferOps.append(QRhiResourceUpdateBatchPrivate::BufferOp::staticUpload(buf, 0, std::move(data)));
11005 }
11006}
11007
11008/*!
11009 Enqueues reading back a region of the QRhiBuffer \a buf. The size of the
11010 region is specified by \a size in bytes, \a offset is the offset in bytes
11011 to start reading from.
11012
11013 A readback is asynchronous. \a result contains a callback that is invoked
11014 when the operation has completed. The data is provided in
11015 QRhiReadbackResult::data. Upon successful completion that QByteArray
11016 will have a size equal to \a size. On failure the QByteArray will be empty.
11017
11018 \note Reading buffers with a usage different than QRhiBuffer::UniformBuffer
11019 is supported only when the QRhi::ReadBackNonUniformBuffer feature is
11020 reported as supported.
11021
11022 \note The asynchronous readback is guaranteed to have completed when one of
11023 the following conditions is met: \l{QRhi::finish()}{finish()} has been
11024 called; or, at least \c N frames have been \l{QRhi::endFrame()}{submitted},
11025 including the frame that issued the readback operation, and the
11026 \l{QRhi::beginFrame()}{recording of a new frame} has been started, where \c
11027 N is the \l{QRhi::resourceLimit()}{resource limit value} returned for
11028 QRhi::MaxAsyncReadbackFrames.
11029
11030 \sa readBackTexture(), QRhi::isFeatureSupported(), QRhi::resourceLimit()
11031 */
11032void QRhiResourceUpdateBatch::readBackBuffer(QRhiBuffer *buf, quint32 offset, quint32 size, QRhiReadbackResult *result)
11033{
11034 const int idx = d->activeBufferOpCount++;
11035 if (idx < d->bufferOps.size())
11036 d->bufferOps[idx] = QRhiResourceUpdateBatchPrivate::BufferOp::read(buf, offset, size, result);
11037 else
11038 d->bufferOps.append(QRhiResourceUpdateBatchPrivate::BufferOp::read(buf, offset, size, result));
11039}
11040
11041/*!
11042 Enqueues a buffer-to-buffer copy operation from \a src into \a dst as
11043 described by \a desc.
11044
11045 The copy is performed on the GPU, without involving the CPU. This is the
11046 preferred way of moving data between two non-Dynamic QRhiBuffer objects.
11047
11048 Availability is indicated by the \l QRhi::BufferToBufferCopy feature. When
11049 that is reported as not supported, which in practice means OpenGL ES 2.0 and
11050 old desktop OpenGL versions, calling this function has no effect.
11051
11052 A \l{QRhiBufferCopyDescription::size()}{size} of 0 in \a desc, which is what
11053 a default constructed description has, means the entire \a src buffer. Watch
11054 out for this when \a dst is smaller than \a src, because the copy then does
11055 not fit and gets dropped, as described below.
11056
11057 \note Neither buffer can be of the type QRhiBuffer::Dynamic, and neither can
11058 have QRhiBuffer::UniformBuffer usage. With some of the underlying 3D APIs
11059 such buffers are backed by host visible memory, or are not real GPU buffers
11060 at all, and so cannot take part in a GPU-side copy.
11061
11062 \note The size and offsets in \a desc should all be multiples of 4. This is a
11063 requirement of the blit encoder in Metal, and it applies on macOS on
11064 Intel-based devices. Other platforms and 3D APIs, including Metal on Apple
11065 Silicon and on iOS, have no such restriction, but portable code has to assume
11066 the strictest of these. Keep in mind that a
11067 \l{QRhiBufferCopyDescription::size()}{size} of 0 leads to using the full size
11068 of \a src, which is not necessarily a multiple of 4 either.
11069
11070 \note Mixing GPU-side copies with host-side updates
11071 (\l{QRhiResourceUpdateBatch::uploadStaticBuffer()}{uploadStaticBuffer()}) on
11072 the same buffer within the same frame follows the order in which the
11073 operations were recorded in the batch, but only when the
11074 \l QRhi::StaticBuffersOnGpuTimeline feature is reported as supported. Where
11075 it is not, which in practice means Metal on macOS on devices without an
11076 Apple GPU, buffer uploads are implemented by writing to host visible memory,
11077 and so the ordering between the two kinds of updates is not defined.
11078 Portable applications need to either avoid the pattern or check the feature
11079 flag.
11080
11081 \since 6.13
11082 \sa copyTexture(), QRhi::isFeatureSupported()
11083 */
11084void QRhiResourceUpdateBatch::copyBuffer(QRhiBuffer *dst, QRhiBuffer *src, const QRhiBufferCopyDescription &desc)
11085{
11086 if (!dst || !src) {
11087 qWarning("Buffer copy with a null source or destination is not supported");
11088 return;
11089 }
11090 if (dst == src) {
11091 qWarning("Buffer copy with matching source and destination is not supported");
11092 return;
11093 }
11094 // Dynamic buffers are host visible, or shadowed on the CPU, with some of
11095 // the backends, and so cannot be the source or the destination of a
11096 // GPU-side copy. UniformBuffer is not necessarily backed by a real GPU
11097 // buffer either.
11098 if (dst->usage().testFlag(QRhiBuffer::UniformBuffer) || src->usage().testFlag(QRhiBuffer::UniformBuffer)) {
11099 qWarning("Buffer copy is not supported for buffers with UniformBuffer usage");
11100 return;
11101 }
11102 if (dst->type() == QRhiBuffer::Dynamic || src->type() == QRhiBuffer::Dynamic) {
11103 qWarning("Buffer copy is not supported for Dynamic buffers");
11104 return;
11105 }
11106
11107 const quint32 size = desc.size() ? desc.size() : src->size();
11108 if (!size)
11109 return;
11110 if (quint64(desc.sourceOffset()) + size > src->size() || quint64(desc.destinationOffset()) + size > dst->size()) {
11111 qWarning("Buffer copy of %u bytes (source offset %u, destination offset %u) "
11112 "does not fit the source (%u bytes) or destination (%u bytes) buffer",
11113 size, desc.sourceOffset(), desc.destinationOffset(),
11114 src->size(), dst->size());
11115 return;
11116 }
11117
11118 const int idx = d->activeBufferOpCount++;
11119 const QRhiResourceUpdateBatchPrivate::BufferOp op = QRhiResourceUpdateBatchPrivate::BufferOp::copy(dst, src,
11120 desc.destinationOffset(), desc.sourceOffset(), size);
11121
11122 if (idx < d->bufferOps.size())
11123 d->bufferOps[idx] = op;
11124 else
11125 d->bufferOps.append(op);
11126}
11127
11128/*!
11129 Enqueues filling \a size bytes of the buffer \a buf, starting at \a offset,
11130 with the byte \a value.
11131
11132 The buffer must have been created with the QRhiBuffer::StorageBuffer usage.
11133 Such buffers are only available when the \l QRhi::Compute feature is
11134 reported as supported, and are never of the type QRhiBuffer::Dynamic. The
11135 clear is performed on the GPU, and it takes effect in the order it was
11136 recorded in, relative to the compute and render passes, and to the other
11137 buffer operations in the batch that are performed on the GPU, such as
11138 copyBuffer(). This makes it suitable for resetting storage buffers
11139 (counters, accumulators) between compute dispatches.
11140
11141 \note \a offset must be a multiple of 4, otherwise the clear is ignored,
11142 with a warning. When \a size is not a multiple of 4, it is rounded down to
11143 the previous multiple of 4, again with a warning, which means the
11144 remaining one to three bytes are left untouched. These are restrictions of
11145 some of the underlying 3D APIs.
11146
11147 \note The clear maps to the native buffer fill or clear operation of the
11148 underlying 3D API, such as \c vkCmdFillBuffer or
11149 \c ClearUnorderedAccessViewUint, without transferring data from the CPU.
11150 OpenGL ES has no such operation; there the clear is performed by a
11151 dedicated compute shader dispatch.
11152
11153 \note Mixing clears with host-side updates
11154 (\l{QRhiResourceUpdateBatch::uploadStaticBuffer()}{uploadStaticBuffer()}) on
11155 the same buffer within the same frame follows the order in which the
11156 operations were recorded in the batch only when the
11157 \l QRhi::StaticBuffersOnGpuTimeline feature is reported as supported. See
11158 copyBuffer() for details.
11159
11160 \since 6.13
11161 \sa copyBuffer()
11162 */
11163void QRhiResourceUpdateBatch::clearStorageBuffer(QRhiBuffer *buf, quint32 offset, quint32 size, quint8 value)
11164{
11165 if (!buf) {
11166 qWarning("Buffer clear with a null buffer is not supported");
11167 return;
11168 }
11169 if (!buf->usage().testFlag(QRhiBuffer::StorageBuffer)) {
11170 qWarning("Buffer clear is only supported for buffers with StorageBuffer usage");
11171 return;
11172 }
11173 // StorageBuffer is not supposed to be combined with Dynamic, but not all
11174 // backends reject it
11175 if (buf->type() == QRhiBuffer::Dynamic) {
11176 qWarning("Buffer clear is not supported for Dynamic buffers");
11177 return;
11178 }
11179 if (offset % 4u) {
11180 qWarning("Buffer clear offset %u is not a multiple of 4", offset);
11181 return;
11182 }
11183 if (quint64(offset) + size > buf->size()) {
11184 qWarning("Buffer clear of %u bytes at offset %u does not fit the buffer (%u bytes)",
11185 size, offset, buf->size());
11186 return;
11187 }
11188 if (size % 4u) {
11189 qWarning("Buffer clear size %u is not a multiple of 4, rounding down", size);
11190 size &= ~3u;
11191 }
11192 if (!size)
11193 return;
11194
11195 const int idx = d->activeBufferOpCount++;
11196 const QRhiResourceUpdateBatchPrivate::BufferOp op = QRhiResourceUpdateBatchPrivate::BufferOp::clear(buf,
11197 offset, size, value);
11198
11199 if (idx < d->bufferOps.size())
11200 d->bufferOps[idx] = op;
11201 else
11202 d->bufferOps.append(op);
11203}
11204
11205/*!
11206 \overload
11207
11208 Enqueues filling the entire buffer \a buf with the byte \a value. When the
11209 size of \a buf is not a multiple of 4, the last one to three bytes are left
11210 untouched, and a warning is printed.
11211
11212 \since 6.13
11213 */
11214void QRhiResourceUpdateBatch::clearStorageBuffer(QRhiBuffer *buf, quint8 value)
11215{
11216 clearStorageBuffer(buf, 0, buf ? buf->size() : 0, value);
11217}
11218
11219/*!
11220 Enqueues uploading the image data for one or more mip levels in one or more
11221 layers of the texture \a tex.
11222
11223 The details of the copy (source QImage or compressed texture data, regions,
11224 target layers and levels) are described in \a desc.
11225 */
11226void QRhiResourceUpdateBatch::uploadTexture(QRhiTexture *tex, const QRhiTextureUploadDescription &desc)
11227{
11228 if (desc.cbeginEntries() != desc.cendEntries()) {
11229 const int idx = d->activeTextureOpCount++;
11230 if (idx < d->textureOps.size())
11231 d->textureOps[idx] = QRhiResourceUpdateBatchPrivate::TextureOp::upload(tex, desc);
11232 else
11233 d->textureOps.append(QRhiResourceUpdateBatchPrivate::TextureOp::upload(tex, desc));
11234 }
11235}
11236
11237/*!
11238 Enqueues uploading the image data for mip level 0 of layer 0 of the texture
11239 \a tex.
11240
11241 \a tex must have an uncompressed format. Its format must also be compatible
11242 with the QImage::format() of \a image. The source data is given in \a
11243 image.
11244 */
11245void QRhiResourceUpdateBatch::uploadTexture(QRhiTexture *tex, const QImage &image)
11246{
11247 uploadTexture(tex,
11248 QRhiTextureUploadEntry(0, 0, QRhiTextureSubresourceUploadDescription(image)));
11249}
11250
11251/*!
11252 Enqueues a texture-to-texture copy operation from \a src into \a dst as
11253 described by \a desc.
11254
11255 \note The source texture \a src must be created with
11256 QRhiTexture::UsedAsTransferSource.
11257
11258 \note The format of the textures must match. With most graphics
11259 APIs the data is copied as-is without any format conversions. If
11260 \a dst and \a src are created with different formats, unspecified
11261 issues may arise.
11262 */
11263void QRhiResourceUpdateBatch::copyTexture(QRhiTexture *dst, QRhiTexture *src, const QRhiTextureCopyDescription &desc)
11264{
11265 const int idx = d->activeTextureOpCount++;
11266 if (idx < d->textureOps.size())
11267 d->textureOps[idx] = QRhiResourceUpdateBatchPrivate::TextureOp::copy(dst, src, desc);
11268 else
11269 d->textureOps.append(QRhiResourceUpdateBatchPrivate::TextureOp::copy(dst, src, desc));
11270}
11271
11272/*!
11273 Enqueues a texture-to-host copy operation as described by \a rb.
11274
11275 Normally \a rb will specify a QRhiTexture as the source. However, when the
11276 swapchain in the current frame was created with
11277 QRhiSwapChain::UsedAsTransferSource, it can also be the source of the
11278 readback. For this, leave the texture set to null in \a rb.
11279
11280 Unlike other operations, the results here need to be processed by the
11281 application. Therefore, \a result provides not just the data but also a
11282 callback as operations on the batch are asynchronous by nature:
11283
11284 \code
11285 rhi->beginFrame(swapchain);
11286 cb->beginPass(swapchain->currentFrameRenderTarget(), colorClear, dsClear);
11287 // ...
11288 QRhiReadbackResult *rbResult = new QRhiReadbackResult;
11289 rbResult->completed = [rbResult] {
11290 {
11291 const QImage::Format fmt = QImage::Format_RGBA8888_Premultiplied; // fits QRhiTexture::RGBA8
11292 const uchar *p = reinterpret_cast<const uchar *>(rbResult->data.constData());
11293 QImage image(p, rbResult->pixelSize.width(), rbResult->pixelSize.height(), fmt);
11294 image.save("result.png");
11295 }
11296 delete rbResult;
11297 };
11298 QRhiResourceUpdateBatch *u = nextResourceUpdateBatch();
11299 QRhiReadbackDescription rb; // no texture -> uses the current backbuffer of sc
11300 u->readBackTexture(rb, rbResult);
11301 cb->endPass(u);
11302 rhi->endFrame(swapchain);
11303 \endcode
11304
11305 \note The texture must be created with QRhiTexture::UsedAsTransferSource.
11306
11307 \note Multisample textures cannot be read back.
11308
11309 \note The readback returns raw byte data, in order to allow the applications
11310 to interpret it in any way they see fit. Be aware of the blending settings
11311 of rendering code: if the blending is set up to rely on premultiplied alpha,
11312 the results of the readback must also be interpreted as Premultiplied.
11313
11314 \note When interpreting the resulting raw data, be aware that the readback
11315 happens with a byte ordered format. A \l{QRhiTexture::RGBA8}{RGBA8} texture
11316 maps therefore to byte ordered QImage formats, such as,
11317 QImage::Format_RGBA8888.
11318
11319 The data of a depth or depth-stencil texture is returned in the following
11320 layout, in native byte order, regardless of the backend. Any bits not
11321 mentioned are zero.
11322
11323 \list
11324 \li \l{QRhiTexture::D16}{D16}: 2 bytes per pixel, a 16-bit normalized unsigned integer.
11325 \li \l{QRhiTexture::D24}{D24}: 4 bytes per pixel, the 24-bit normalized
11326 unsigned integer depth in the upper 24 bits.
11327 \li \l{QRhiTexture::D24S8}{D24S8}: 4 bytes per pixel, the 24-bit
11328 normalized unsigned integer depth in the upper 24 bits and the stencil in
11329 the lower 8 bits.
11330 \li \l{QRhiTexture::D32F}{D32F}: 4 bytes per pixel, a 32-bit float.
11331 \li \l{QRhiTexture::D32FS8}{D32FS8}: 8 bytes per pixel, a 32-bit float
11332 depth, followed by a 32-bit unsigned integer with the stencil in the lower 8
11333 bits.
11334 \endlist
11335
11336 \note With OpenGL ES, reading back a depth or depth-stencil texture is not
11337 supported, see QRhi::ReadBackAnyTextureFormat.
11338
11339 \note The asynchronous readback is guaranteed to have completed when one of
11340 the following conditions is met: \l{QRhi::finish()}{finish()} has been
11341 called; or, at least \c N frames have been \l{QRhi::endFrame()}{submitted},
11342 including the frame that issued the readback operation, and the
11343 \l{QRhi::beginFrame()}{recording of a new frame} has been started, where \c
11344 N is the \l{QRhi::resourceLimit()}{resource limit value} returned for
11345 QRhi::MaxAsyncReadbackFrames.
11346
11347 A single readback operation copies one mip level of one layer (cubemap face
11348 or 3D slice or texture array element) at a time. The level and layer are
11349 specified by the respective fields in \a rb.
11350
11351 \sa readBackBuffer(), QRhi::resourceLimit()
11352 */
11353void QRhiResourceUpdateBatch::readBackTexture(const QRhiReadbackDescription &rb, QRhiReadbackResult *result)
11354{
11355 const int idx = d->activeTextureOpCount++;
11356 if (idx < d->textureOps.size())
11357 d->textureOps[idx] = QRhiResourceUpdateBatchPrivate::TextureOp::read(rb, result);
11358 else
11359 d->textureOps.append(QRhiResourceUpdateBatchPrivate::TextureOp::read(rb, result));
11360}
11361
11362/*!
11363 Enqueues a mipmap generation operation for the specified texture \a tex.
11364
11365 2D and cube textures are supported. 1D and 3D textures are supported when
11366 the QRhi::OneDimensionalTextureMipmaps or QRhi::ThreeDimensionalTextureMipmaps
11367 feature is reported as supported, respectively.
11368
11369 \note The texture must be created with QRhiTexture::MipMapped and
11370 QRhiTexture::UsedWithGenerateMips.
11371
11372 \warning QRhi cannot guarantee that mipmaps can be generated for all
11373 supported texture formats. For example, QRhiTexture::RGBA32F is not a \c
11374 filterable format in OpenGL ES 3.0 and Metal on iOS, and therefore the
11375 mipmap generation request may fail. RGBA8 and RGBA16F are typically
11376 filterable, so it is recommended to use these formats when mipmap generation
11377 is desired.
11378 */
11379void QRhiResourceUpdateBatch::generateMips(QRhiTexture *tex)
11380{
11381 const int idx = d->activeTextureOpCount++;
11382 if (idx < d->textureOps.size())
11383 d->textureOps[idx] = QRhiResourceUpdateBatchPrivate::TextureOp::genMips(tex);
11384 else
11385 d->textureOps.append(QRhiResourceUpdateBatchPrivate::TextureOp::genMips(tex));
11386}
11387
11388/*!
11389 Enqueues updating the contents of the indirect command buffer \a icb from
11390 the commands recorded on it with QRhiIndirectCommandBuffer::draw() or
11391 QRhiIndirectCommandBuffer::drawIndexed().
11392
11393 Has to be called after recording and before the render pass that executes
11394 the commands. Does nothing when nothing changed since the last time, so
11395 calling it once per frame is inexpensive.
11396
11397 Has no effect on an indirect command buffer that was populated with
11398 QRhiCommandBuffer::buildIndirect() instead.
11399
11400 \note This is where backends that keep the commands in a buffer perform the
11401 upload, but it is not necessarily where the cost of a CPU-recorded indirect
11402 command buffer is: Metal has nothing to upload here and does its per-command
11403 encoding in QRhiCommandBuffer::executeIndirect() instead. An inexpensive
11404 commitIndirectCommandBuffer() therefore does not by itself mean that
11405 recording the commands was inexpensive. See \l QRhiIndirectCommandBuffer for
11406 how the cost of CPU recording scales.
11407
11408 \since 6.13
11409 */
11410void QRhiResourceUpdateBatch::commitIndirectCommandBuffer(QRhiIndirectCommandBuffer *icb)
11411{
11412 Q_ASSERT(icb);
11413 d->rhi->commitIndirectCommandBuffer(this, icb);
11414}
11415
11416/*!
11417 \return an available, empty batch to which copy type of operations can be
11418 recorded.
11419
11420 \note the return value is not owned by the caller and must never be
11421 destroyed. Instead, the batch is returned the pool for reuse by passing
11422 it to QRhiCommandBuffer::beginPass(), QRhiCommandBuffer::endPass(), or
11423 QRhiCommandBuffer::resourceUpdate(), or by calling
11424 QRhiResourceUpdateBatch::release() on it.
11425
11426 \note Can be called outside beginFrame() - endFrame() as well since a batch
11427 instance just collects data on its own, it does not perform any operations.
11428
11429 Due to not being tied to a frame being recorded, the following sequence is
11430 valid for example:
11431
11432 \code
11433 rhi->beginFrame(swapchain);
11434 QRhiResourceUpdateBatch *u = rhi->nextResourceUpdateBatch();
11435 u->uploadStaticBuffer(buf, data);
11436 // ... do not commit the batch
11437 rhi->endFrame();
11438 // u stays valid (assuming buf stays valid as well)
11439 rhi->beginFrame(swapchain);
11440 swapchain->currentFrameCommandBuffer()->resourceUpdate(u);
11441 // ... draw with buf
11442 rhi->endFrame();
11443 \endcode
11444
11445 \warning The maximum number of batches per QRhi is 64. When this limit is
11446 reached, the function will return null until a batch is returned to the
11447 pool.
11448 */
11449QRhiResourceUpdateBatch *QRhi::nextResourceUpdateBatch()
11450{
11451 // By default we prefer spreading out the utilization of the worst case 64
11452 // (but typically 4) batches as much as possible, meaning we won't pick the
11453 // first one even if it's free, but prefer picking one after the last picked
11454 // one. Relevant due to implicit sharing (the backend may hold on to the
11455 // QRhiBufferData until frame no. current+FramesInFlight-1, but
11456 // implementations may vary), combined with the desire to reuse container
11457 // and QRhiBufferData allocations in bufferOps instead of flooding every
11458 // frame with allocs. See free(). In typical Qt Quick scenes this leads to
11459 // eventually seeding all 4 (or more) resource batches with buffer operation
11460 // data allocations which may (*) then be reused in subsequent frames. This
11461 // comes at the expense of using more memory, but has proven good results
11462 // when (CPU) profiling typical Quick/Quick3D apps.
11463 //
11464 // (*) Due to implicit sharing(ish), the exact behavior is unpredictable. If
11465 // a backend holds on to the QRhiBufferData for, e.g., a dynamic buffer
11466 // update, and then there is a new assign() for that same QRhiBufferData
11467 // while the refcount is still 2, it will "detach" (without contents) and
11468 // there is no reuse of the alloc. This is mitigated by the 'choose the one
11469 // afer the last picked one' logic when handing out batches.
11470
11471 auto nextFreeBatch = [this]() -> QRhiResourceUpdateBatch * {
11472 auto isFree = [this](int i) -> QRhiResourceUpdateBatch * {
11473 const quint64 mask = 1ULL << quint64(i);
11474 if (!(d->resUpdPoolMap & mask)) {
11475 d->resUpdPoolMap |= mask;
11476 QRhiResourceUpdateBatch *u = d->resUpdPool[i];
11477 QRhiResourceUpdateBatchPrivate::get(u)->poolIndex = i;
11478 d->lastResUpdIdx = i;
11479 return u;
11480 }
11481 return nullptr;
11482 };
11483 const int poolSize = d->resUpdPool.size();
11484 for (int i = d->lastResUpdIdx + 1; i < poolSize; ++i) {
11485 if (QRhiResourceUpdateBatch *u = isFree(i))
11486 return u;
11487 }
11488 for (int i = 0; i <= d->lastResUpdIdx; ++i) {
11489 if (QRhiResourceUpdateBatch *u = isFree(i))
11490 return u;
11491 }
11492 return nullptr;
11493 };
11494
11495 QRhiResourceUpdateBatch *u = nextFreeBatch();
11496 if (!u) {
11497 const int oldSize = d->resUpdPool.size();
11498 // 4, 8, 12, ..., up to 64
11499 const int newSize = oldSize + qMin(4, qMax(0, 64 - oldSize));
11500 d->resUpdPool.resize(newSize);
11501 for (int i = oldSize; i < newSize; ++i)
11502 d->resUpdPool[i] = new QRhiResourceUpdateBatch(d);
11503 u = nextFreeBatch();
11504 if (!u)
11505 qWarning("Resource update batch pool exhausted (max is 64)");
11506 }
11507
11508 return u;
11509}
11510
11512{
11513 Q_ASSERT(poolIndex >= 0 && rhi->resUpdPool[poolIndex] == q);
11514
11515 quint32 bufferDataTotal = 0;
11516 quint32 bufferLargeAllocTotal = 0;
11517 for (const BufferOp &op : std::as_const(bufferOps)) {
11518 bufferDataTotal += op.data.size();
11519 bufferLargeAllocTotal += op.data.largeAlloc(); // alloc when > 1 KB
11520 }
11521
11522 if (QRHI_LOG_RUB().isDebugEnabled()) {
11523 qDebug() << "[rub] release to pool upd.batch #" << poolIndex
11524 << "/ bufferOps active" << activeBufferOpCount
11525 << "of" << bufferOps.count()
11526 << "data" << bufferDataTotal
11527 << "largeAlloc" << bufferLargeAllocTotal
11528 << "textureOps active" << activeTextureOpCount
11529 << "of" << textureOps.count();
11530 }
11531
11534
11535 const quint64 mask = 1ULL << quint64(poolIndex);
11536 rhi->resUpdPoolMap &= ~mask;
11537 poolIndex = -1;
11538
11539 // textureOps is cleared, to not keep the potentially large image pixel
11540 // data alive, but it is expected that the container keeps the list alloc
11541 // at least. Only trimOpList() goes for the more aggressive route with squeeze.
11542 textureOps.clear();
11543
11544 // bufferOps is not touched in many cases, to allow reusing allocations
11545 // (incl. in the elements' QRhiBufferData) as much as possible when this
11546 // batch is used again in the future, which is important for performance, in
11547 // particular with Qt Quick where it is easy for scenes to produce lots of,
11548 // typically small buffer changes on every frame.
11549 //
11550 // However, ensure that even in the unlikely case of having the max number
11551 // of batches (64) created in resUpdPool, no more than 64 MB in total is
11552 // used up by buffer data just to help future reuse. For simplicity, if
11553 // there is more than 1 MB data -> clear. Applications with frequent, huge
11554 // buffer updates probably have other bottlenecks anyway.
11555 if (bufferLargeAllocTotal > 1024 * 1024)
11556 bufferOps.clear();
11557}
11558
11560{
11561 int combinedSize = activeBufferOpCount + other->activeBufferOpCount;
11562 if (bufferOps.size() < combinedSize)
11563 bufferOps.resize(combinedSize);
11564 for (int i = activeBufferOpCount; i < combinedSize; ++i)
11565 bufferOps[i] = std::move(other->bufferOps[i - activeBufferOpCount]);
11567
11568 combinedSize = activeTextureOpCount + other->activeTextureOpCount;
11569 if (textureOps.size() < combinedSize)
11570 textureOps.resize(combinedSize);
11571 for (int i = activeTextureOpCount; i < combinedSize; ++i)
11572 textureOps[i] = std::move(other->textureOps[i - activeTextureOpCount]);
11574}
11575
11581
11583{
11584 // Unlike free(), this is expected to aggressively deallocate all memory
11585 // used by both the buffer and texture operation lists. (i.e. using
11586 // squeeze() to only keep the stack prealloc of the QVLAs)
11587 //
11588 // This (e.g. just the destruction of bufferOps elements) may have a
11589 // non-negligible performance impact e.g. with Qt Quick with scenes where
11590 // there are lots of buffer operations per frame.
11591
11593 bufferOps.clear();
11594 bufferOps.squeeze();
11595
11597 textureOps.clear();
11598 textureOps.squeeze();
11599}
11600
11601/*!
11602 Sometimes committing resource updates is necessary or just more convenient
11603 without starting a render pass. Calling this function with \a
11604 resourceUpdates is an alternative to passing \a resourceUpdates to a
11605 beginPass() call (or endPass(), which would be typical in case of readbacks).
11606
11607 \note Cannot be called inside a pass.
11608 */
11609void QRhiCommandBuffer::resourceUpdate(QRhiResourceUpdateBatch *resourceUpdates)
11610{
11611 if (resourceUpdates)
11612 m_rhi->resourceUpdate(this, resourceUpdates);
11613}
11614
11615/*!
11616 Records starting a new render pass targeting the render target \a rt.
11617
11618 \a resourceUpdates, when not null, specifies a resource update batch that
11619 is to be committed and then released.
11620
11621 The color and depth/stencil buffers of the render target are normally
11622 cleared. The clear values are specified in \a colorClearValue and \a
11623 depthStencilClearValue. The exception is when the render target was created
11624 with QRhiTextureRenderTarget::PreserveColorContents and/or
11625 QRhiTextureRenderTarget::PreserveDepthStencilContents. The clear values are
11626 ignored then.
11627
11628 \note Enabling preserved color or depth contents leads to decreased
11629 performance depending on the underlying hardware. Mobile GPUs with tiled
11630 architecture benefit from not having to reload the previous contents into
11631 the tile buffer. Similarly, a QRhiTextureRenderTarget with a QRhiTexture as
11632 the depth buffer is less efficient than a QRhiRenderBuffer since using a
11633 depth texture triggers requiring writing the data out to it, while with
11634 renderbuffers this is not needed (as the API does not allow sampling or
11635 reading from a renderbuffer).
11636
11637 \note Do not assume that any state or resource bindings persist between
11638 passes.
11639
11640 \note The QRhiCommandBuffer's \c set and \c draw functions can only be
11641 called inside a pass. Also, with the exception of setGraphicsPipeline(),
11642 they expect to have a pipeline set already on the command buffer.
11643 Unspecified issues may arise otherwise, depending on the backend.
11644
11645 If \a rt is a QRhiTextureRenderTarget, beginPass() performs a check to see
11646 if the texture and renderbuffer objects referenced from the render target
11647 are up-to-date. This is similar to what setShaderResources() does for
11648 QRhiShaderResourceBindings. If any of the attachments had been rebuilt
11649 since QRhiTextureRenderTarget::create(), an implicit call to create() is
11650 made on \a rt. Therefore, if \a rt has a QRhiTexture color attachment \c
11651 texture, and one needs to make the texture a different size, the following
11652 is then valid:
11653 \code
11654 QRhiTextureRenderTarget *rt = rhi->newTextureRenderTarget({ { texture } });
11655 rt->create();
11656 // ...
11657 texture->setPixelSize(new_size);
11658 texture->create();
11659 cb->beginPass(rt, colorClear, dsClear); // this is ok, no explicit rt->create() is required before
11660 \endcode
11661
11662 \a flags allow controlling certain advanced functionality. One commonly used
11663 flag is \c ExternalContents. This should be specified whenever
11664 beginExternal() will be called within the pass started by this function.
11665
11666 \sa endPass(), BeginPassFlags
11667 */
11668void QRhiCommandBuffer::beginPass(QRhiRenderTarget *rt,
11669 const QColor &colorClearValue,
11670 const QRhiDepthStencilClearValue &depthStencilClearValue,
11671 QRhiResourceUpdateBatch *resourceUpdates,
11672 BeginPassFlags flags)
11673{
11674 m_rhi->beginPass(this, rt, colorClearValue, depthStencilClearValue, resourceUpdates, flags);
11675}
11676
11677/*!
11678 Records ending the current render pass.
11679
11680 \a resourceUpdates, when not null, specifies a resource update batch that
11681 is to be committed and then released.
11682
11683 \sa beginPass()
11684 */
11685void QRhiCommandBuffer::endPass(QRhiResourceUpdateBatch *resourceUpdates)
11686{
11687 m_rhi->endPass(this, resourceUpdates);
11688}
11689
11690/*!
11691 Records setting a new graphics pipeline \a ps.
11692
11693 \note This function must be called before recording other \c set or \c draw
11694 commands on the command buffer.
11695
11696 \note QRhi will optimize out unnecessary invocations within a pass, so
11697 therefore overoptimizing to avoid calls to this function is not necessary
11698 on the applications' side.
11699
11700 \note This function can only be called inside a render pass, meaning
11701 between a beginPass() and endPass() call.
11702
11703 \note The new graphics pipeline \a ps must be a valid pointer.
11704
11705 Setting a graphics pipeline that does not have the
11706 \l{QRhiGraphicsPipeline::}{UsesScissor} flag will either disable scissoring,
11707 with graphics APIs where that is applicable, or set the scissor rectangle to
11708 match the viewport that was last set (with graphics APIs where scissoring is
11709 effectively always active), in order to ensure a uniform behavior across QRhi
11710 backends.
11711 */
11712void QRhiCommandBuffer::setGraphicsPipeline(QRhiGraphicsPipeline *ps)
11713{
11714 Q_ASSERT(ps != nullptr);
11715 m_rhi->setGraphicsPipeline(this, ps);
11716}
11717
11718/*!
11719 Records binding a set of shader resources, such as, uniform buffers or
11720 textures, that are made visible to one or more shader stages.
11721
11722 \a srb can be null in which case the current graphics or compute pipeline's
11723 associated QRhiShaderResourceBindings is used. When \a srb is non-null, it
11724 must be
11725 \l{QRhiShaderResourceBindings::isLayoutCompatible()}{layout-compatible},
11726 meaning the layout (number of bindings, the type and binding number of each
11727 binding) must fully match the QRhiShaderResourceBindings that was
11728 associated with the pipeline at the time of calling the pipeline's create().
11729
11730 There are cases when a seemingly unnecessary setShaderResources() call is
11731 mandatory: when rebuilding a resource referenced from \a srb, for example
11732 changing the size of a QRhiBuffer followed by a QRhiBuffer::create(), this
11733 is the place where associated native objects (such as descriptor sets in
11734 case of Vulkan) are updated to refer to the current native resources that
11735 back the QRhiBuffer, QRhiTexture, QRhiSampler objects referenced from \a
11736 srb. In this case setShaderResources() must be called even if \a srb is
11737 the same as in the last call.
11738
11739 When \a srb is not null, the QRhiShaderResourceBindings object the pipeline
11740 was built with in create() is guaranteed to be not accessed in any form. In
11741 fact, it does not need to be valid even at this point: destroying the
11742 pipeline's associated srb after create() and instead explicitly specifying
11743 another, \l{QRhiShaderResourceBindings::isLayoutCompatible()}{layout
11744 compatible} one in every setShaderResources() call is valid.
11745
11746 \a dynamicOffsets allows specifying buffer offsets for uniform buffers that
11747 were associated with \a srb via
11748 QRhiShaderResourceBinding::uniformBufferWithDynamicOffset(). This is
11749 different from providing the offset in the \a srb itself: dynamic offsets
11750 do not require building a new QRhiShaderResourceBindings for every
11751 different offset, can avoid writing the underlying descriptors (with
11752 backends where applicable), and so they may be more efficient. Each element
11753 of \a dynamicOffsets is a \c binding - \c offset pair.
11754 \a dynamicOffsetCount specifies the number of elements in \a dynamicOffsets.
11755
11756 \note All offsets in \a dynamicOffsets must be byte aligned to the value
11757 returned from QRhi::ubufAlignment().
11758
11759 \note Some backends may limit the number of supported dynamic offsets.
11760 Avoid using a \a dynamicOffsetCount larger than 8.
11761
11762 \note QRhi will optimize out unnecessary invocations within a pass (taking
11763 the conditions described above into account), so therefore overoptimizing
11764 to avoid calls to this function is not necessary on the applications' side.
11765
11766 \note This function can only be called inside a render or compute pass,
11767 meaning between a beginPass() and endPass(), or beginComputePass() and
11768 endComputePass().
11769 */
11770void QRhiCommandBuffer::setShaderResources(QRhiShaderResourceBindings *srb,
11771 int dynamicOffsetCount,
11772 const DynamicOffset *dynamicOffsets)
11773{
11774 m_rhi->setShaderResources(this, srb, dynamicOffsetCount, dynamicOffsets);
11775}
11776
11777/*!
11778 Records vertex input bindings.
11779
11780 The index buffer used by subsequent drawIndexed() commands is specified by
11781 \a indexBuf, \a indexOffset, and \a indexFormat. \a indexBuf can be set to
11782 null when indexed drawing is not needed.
11783
11784 Vertex buffer bindings are batched. \a startBinding specifies the first
11785 binding number. The recorded command then binds each buffer from \a
11786 bindings to the binding point \c{startBinding + i} where \c i is the index
11787 in \a bindings. Each element in \a bindings specifies a QRhiBuffer and an
11788 offset.
11789
11790 \note Some backends may limit the number of vertex buffer bindings. Avoid
11791 using a \a bindingCount larger than 8.
11792
11793 Superfluous vertex input and index changes in the same pass are ignored
11794 automatically with most backends and therefore applications do not need to
11795 overoptimize to avoid calls to this function.
11796
11797 \note With some backends, parts of the active QRhiGraphicsPipeline's vertex
11798 input layout, most importantly the stride of each binding, are applied by
11799 setVertexInput() and not by setGraphicsPipeline(). Therefore, after
11800 switching to a pipeline with a different vertex input layout, for example
11801 one that specifies different strides, call setVertexInput() again, even if
11802 the vertex buffers and offsets stay the same. When the vertex input layout
11803 is the same, there is no need to call setVertexInput() again.
11804
11805 \note This function can only be called inside a render pass, meaning
11806 between a beginPass() and endPass() call.
11807
11808 As a simple example, take a vertex shader with two inputs:
11809
11810 \badcode
11811 layout(location = 0) in vec4 position;
11812 layout(location = 1) in vec3 color;
11813 \endcode
11814
11815 and assume we have the data available in interleaved format, using only 2
11816 floats for position (so 5 floats per vertex: x, y, r, g, b). A QRhiGraphicsPipeline for
11817 this shader can then be created using the input layout:
11818
11819 \code
11820 QRhiVertexInputLayout inputLayout;
11821 inputLayout.setBindings({
11822 { 5 * sizeof(float) }
11823 });
11824 inputLayout.setAttributes({
11825 { 0, 0, QRhiVertexInputAttribute::Float2, 0 },
11826 { 0, 1, QRhiVertexInputAttribute::Float3, 2 * sizeof(float) }
11827 });
11828 \endcode
11829
11830 Here there is one buffer binding (binding number 0), with two inputs
11831 referencing it. When recording the pass, once the pipeline is set, the
11832 vertex bindings can be specified simply like the following, assuming vbuf
11833 is the QRhiBuffer with all the interleaved position+color data:
11834
11835 \code
11836 const QRhiCommandBuffer::VertexInput vbufBinding(vbuf, 0);
11837 cb->setVertexInput(0, 1, &vbufBinding);
11838 \endcode
11839 */
11840void QRhiCommandBuffer::setVertexInput(int startBinding, int bindingCount, const VertexInput *bindings,
11841 QRhiBuffer *indexBuf, quint32 indexOffset,
11842 IndexFormat indexFormat)
11843{
11844 m_rhi->setVertexInput(this, startBinding, bindingCount, bindings, indexBuf, indexOffset, indexFormat);
11845}
11846
11847/*!
11848 Records setting the active viewport rectangle specified in \a viewport.
11849
11850 With backends where the underlying graphics API has scissoring always
11851 enabled, this function also sets the scissor to match the viewport whenever
11852 the active QRhiGraphicsPipeline does not have
11853 \l{QRhiGraphicsPipeline::UsesScissor}{UsesScissor} set.
11854
11855 \note QRhi assumes OpenGL-style viewport coordinates, meaning x and y are
11856 bottom-left.
11857
11858 \note This function can only be called inside a render pass, meaning
11859 between a beginPass() and endPass() call.
11860 */
11861void QRhiCommandBuffer::setViewport(const QRhiViewport &viewport)
11862{
11863 m_rhi->setViewport(this, viewport);
11864}
11865
11866/*!
11867 Records setting the active scissor rectangle specified in \a scissor.
11868
11869 This can only be called when the bound pipeline has
11870 \l{QRhiGraphicsPipeline::UsesScissor}{UsesScissor} set. When the flag is
11871 set on the active pipeline, this function must be called because scissor
11872 testing will get enabled and so a scissor rectangle must be provided.
11873
11874 \note QRhi assumes OpenGL-style viewport coordinates, meaning x and y are
11875 bottom-left.
11876
11877 \note This function can only be called inside a render pass, meaning
11878 between a beginPass() and endPass() call.
11879 */
11880void QRhiCommandBuffer::setScissor(const QRhiScissor &scissor)
11881{
11882 m_rhi->setScissor(this, scissor);
11883}
11884
11885/*!
11886 Records setting the active blend constants to \a c.
11887
11888 This can only be called when the bound pipeline has
11889 QRhiGraphicsPipeline::UsesBlendConstants set.
11890
11891 \note This function can only be called inside a render pass, meaning
11892 between a beginPass() and endPass() call.
11893 */
11894void QRhiCommandBuffer::setBlendConstants(const QColor &c)
11895{
11896 m_rhi->setBlendConstants(this, c);
11897}
11898
11899/*!
11900 Records setting the active stencil reference value to \a refValue.
11901
11902 This can only be called when the bound pipeline has
11903 QRhiGraphicsPipeline::UsesStencilRef set.
11904
11905 The value stays in effect for the rest of the render pass, also when other
11906 pipelines are bound, but it is only used by pipelines with
11907 QRhiGraphicsPipeline::UsesStencilRef set. Pipelines without the flag always
11908 use a stencil reference value of 0. Each render pass starts with a stencil
11909 reference value of 0, regardless of what was set in earlier passes.
11910
11911 \note This function can only be called inside a render pass, meaning between
11912 a beginPass() and endPass() call.
11913 */
11914void QRhiCommandBuffer::setStencilRef(quint32 refValue)
11915{
11916 m_rhi->setStencilRef(this, refValue);
11917}
11918
11919/*!
11920 Records setting the push constant data for the currently bound graphics or
11921 compute pipeline. \a size bytes are taken from \a data and placed at byte
11922 offset \a offset within the push constant block. Both \a offset and \a
11923 size must be a multiple of 4.
11924
11925 Push constants are a small, pipeline-layout-resident block of data that can
11926 be updated between draw calls without touching any
11927 QRhiShaderResourceBindings. This makes them suitable for per-draw values
11928 such as an index into a storage buffer, avoiding a setShaderResources()
11929 call per draw.
11930
11931 The shaders declare the block in the usual way, for example:
11932
11933 \badcode
11934 layout(push_constant) uniform PC { uint objectIndex; } pc;
11935 \endcode
11936
11937 \note A push constant block defaults to the std430 layout, unlike a
11938 uniform block. There an array of scalars or of \c vec2 is tightly packed,
11939 and so are the columns of a matrix with two rows (\c mat2, \c mat3x2,
11940 \c mat4x2). Neither can be expressed in a Direct3D constant buffer, so a
11941 block that has such a member has to be declared with
11942 \c{layout(push_constant, std140)} in order to be usable with the D3D
11943 backends. (qsb reports an error when baking such a shader for HLSL) Blocks
11944 with only scalars, vectors, and \c mat3 or \c mat4 matrices, which is what
11945 push constants are mostly used for, are unaffected.
11946
11947 QRhi derives the push constant range from the shader reflection data of the
11948 pipeline's shader stages, so no extra declaration is needed on the
11949 QRhiGraphicsPipeline or QRhiComputePipeline.
11950
11951 \note This is only functional when the PushConstants feature is reported as
11952 supported. The maximum size of the block is reported by the
11953 MaxPushConstantsSize resource limit.
11954
11955 \note With Metal, push constants are not supported with a graphics pipeline
11956 that uses tessellation. Calling this function while such a pipeline is
11957 bound has no effect, apart from a warning.
11958
11959 \note Must be called inside a pass, after setGraphicsPipeline() or
11960 setComputePipeline().
11961
11962 \note The data does not persist. It has to be set again in every pass and
11963 after every change of pipeline. The backends differ in how much they would
11964 otherwise retain, so relying on anything else is not portable.
11965
11966 \since 6.13
11967 */
11968void QRhiCommandBuffer::setPushConstants(quint32 offset, quint32 size, const void *data)
11969{
11970 m_rhi->setPushConstants(this, offset, size, data);
11971}
11972
11973/*!
11974 Sets the shading rate for the following draw calls to \a coarsePixelSize.
11975
11976 The default is 1x1.
11977
11978 Functional only when the \l QRhi::VariableRateShading feature is reported as
11979 supported and the QRhiGraphicsPipeline(s) bound on the command buffer were
11980 declaring \l QRhiGraphicsPipeline::UsesShadingRate when creating them.
11981
11982 Call \l QRhi::supportedShadingRates() to check what shading rates are
11983 supported for a given sample count.
11984
11985 When both a QRhiShadingRateMap and this function are in use, the higher of
11986 the two shading rates is used for each tile. There is currently no control
11987 offered over the combiner behavior.
11988
11989 \since 6.9
11990 */
11991void QRhiCommandBuffer::setShadingRate(const QSize &coarsePixelSize)
11992{
11993 m_rhi->setShadingRate(this, coarsePixelSize);
11994}
11995
11996/*!
11997 Records a non-indexed draw.
11998
11999 The number of vertices is specified in \a vertexCount. For instanced
12000 drawing set \a instanceCount to a value other than 1. \a firstVertex is the
12001 index of the first vertex to draw. When drawing multiple instances, the
12002 first instance ID is specified by \a firstInstance.
12003
12004 \note \a firstInstance may not be supported, and is ignored when the
12005 QRhi::BaseInstance feature is reported as not supported. The first instance
12006 ID is always 0 in that case. QRhi::BaseInstance is never supported with
12007 OpenGL ES, and therefore portable applications should not be designed to
12008 rely on this argument.
12009
12010 \note Shaders that need to access the index of the current vertex or
12011 instance must use \c gl_VertexIndex and \c gl_InstanceIndex, i.e., the
12012 Vulkan-compatible built-in variables, instead of \c gl_VertexID and \c
12013 gl_InstanceID.
12014
12015 \note When \a firstInstance is non-zero, \c gl_InstanceIndex will not
12016 include the base value with some of the underlying 3D APIs. This is
12017 indicated by the QRhi::InstanceIndexIncludesBaseInstance feature. If relying
12018 on a base instance value cannot be avoided, applications are advised to pass
12019 in the value as a uniform conditionally based on what that feature reports,
12020 and add it to \c gl_InstanceIndex in the shader.
12021
12022 \note This function can only be called inside a render pass, meaning
12023 between a beginPass() and endPass() call.
12024 */
12025void QRhiCommandBuffer::draw(quint32 vertexCount,
12026 quint32 instanceCount,
12027 quint32 firstVertex,
12028 quint32 firstInstance)
12029{
12030 m_rhi->draw(this, vertexCount, instanceCount, firstVertex, firstInstance);
12031}
12032
12033/*!
12034 Records an indexed draw.
12035
12036 The number of vertices is specified in \a indexCount. \a firstIndex is the
12037 base index. The effective offset in the index buffer is given by
12038 \c{indexOffset + firstIndex * n} where \c n is 2 or 4 depending on the
12039 index element type. \c indexOffset is specified in setVertexInput().
12040
12041 \note The effective offset in the index buffer must be 4 byte aligned with
12042 some backends (for example, Metal). With these backends the
12043 \l{QRhi::NonFourAlignedEffectiveIndexBufferOffset}{NonFourAlignedEffectiveIndexBufferOffset}
12044 feature will be reported as not-supported.
12045
12046 \a vertexOffset (also called \c{base vertex}) is a signed value that is
12047 added to the element index before indexing into the vertex buffer. Support
12048 for this is not always available, and the value is ignored when the feature
12049 QRhi::BaseVertex is reported as unsupported.
12050
12051 For instanced drawing set \a instanceCount to a value other than 1. When
12052 drawing multiple instances, the first instance ID is specified by \a
12053 firstInstance.
12054
12055 \note \a firstInstance may not be supported, and is ignored when the
12056 QRhi::BaseInstance feature is reported as not supported. The first instance
12057 ID is always 0 in that case. QRhi::BaseInstance is never supported with
12058 OpenGL ES, and therefore portable applications should not be designed to
12059 rely on this argument.
12060
12061 \note Shaders that need to access the index of the current vertex or
12062 instance must use \c gl_VertexIndex and \c gl_InstanceIndex, i.e., the
12063 Vulkan-compatible built-in variables, instead of \c gl_VertexID and \c
12064 gl_InstanceID.
12065
12066 \note When \a firstInstance is non-zero, \c gl_InstanceIndex will not
12067 include the base value with some of the underlying 3D APIs. This is
12068 indicated by the QRhi::InstanceIndexIncludesBaseInstance feature. If relying
12069 on a base instance value cannot be avoided, applications are advised to pass
12070 in the value as a uniform conditionally based on what that feature reports,
12071 and add it to \c gl_InstanceIndex in the shader.
12072
12073 \note This function can only be called inside a render pass, meaning
12074 between a beginPass() and endPass() call.
12075 */
12076void QRhiCommandBuffer::drawIndexed(quint32 indexCount,
12077 quint32 instanceCount,
12078 quint32 firstIndex,
12079 qint32 vertexOffset,
12080 quint32 firstInstance)
12081{
12082 m_rhi->drawIndexed(this, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
12083}
12084
12085/*!
12086 Records a non-indexed, indirect draw.
12087
12088 The draw parameters are provided by the buffer specified in \a indirectBuffer,
12089 which must contain an array of elements of type QRhiIndirectDrawCommand.
12090 The parameters in QRhiIndirectDrawCommand have the same meaning as in draw().
12091
12092 The offset, in bytes, from which the parameters are read in the buffer is specified
12093 by \a indirectBufferOffset.
12094
12095 \a drawCount specifies the number of such draw commands to issue.
12096
12097 \a stride indicates the byte size of each individual draw command structure
12098 in the buffer. This allows interleaving custom data between commands if needed.
12099 The value must be a multiple of 4 and greater than or equal to sizeof(QRhiIndirectDrawCommand).
12100
12101 \note A \a drawCount value greater than 1 is only natively supported if the
12102 QRhi::DrawIndirectMulti feature is reported as supported.
12103 Otherwise, this function emulates multi-draw by recording multiple draw calls,
12104 offering no performance benefit over repeated draw() calls.
12105
12106 \note Leaving \a stride at its default is recommended whenever performance
12107 matters. With Direct 3D 12 a non-default stride prevents issuing a single
12108 native multi-draw, forcing the backend to record one command per draw
12109 instead. For a large \a drawCount this can be an order of magnitude slower,
12110 which defeats the purpose of the indirect draw. Vulkan, OpenGL, and Metal
12111 pass the stride on to their native multi-draw entry points and are not
12112 affected. Rather than interleaving custom data between the commands, keep
12113 that data in a separate buffer and index into it.
12114
12115 \note The render pass interruption and the render target consequences and
12116 limitations described for drawIndexedIndirect() apply here as well.
12117
12118 \note Therefore, portable applications should consider always using
12119 QRhiIndirectCommandBuffer and executeIndirect() instead of the
12120 draw*Indirect*() family of functions.
12121
12122 \note This function can only be called inside a render pass, meaning
12123 between a beginPass() and endPass() call.
12124
12125 \since 6.12
12126
12127 \sa drawIndexedIndirect(), drawIndirectCount(), drawIndexedIndirectCount()
12128 */
12129void QRhiCommandBuffer::drawIndirect(QRhiBuffer *indirectBuffer,
12130 quint32 indirectBufferOffset,
12131 quint32 drawCount,
12132 quint32 stride)
12133{
12134 Q_ASSERT(indirectBuffer);
12135 Q_ASSERT(indirectBuffer->usage().testFlag(QRhiBuffer::IndirectBuffer));
12136 Q_ASSERT_X((indirectBufferOffset & 3u) == 0u, Q_FUNC_INFO, "indirectBufferOffset must be a multiple of 4");
12137 Q_ASSERT(stride >= sizeof(QRhiIndirectDrawCommand));
12138 Q_ASSERT_X((stride & 3u) == 0u, Q_FUNC_INFO, "stride must be a multiple of 4");
12139 m_rhi->drawIndirect(this, indirectBuffer, indirectBufferOffset, drawCount, stride);
12140}
12141
12142/*!
12143 Records an indexed, indirect draw.
12144
12145 The draw parameters are provided by the buffer specified in \a indirectBuffer,
12146 which must contain an array of elements of type QRhiIndexedIndirectDrawCommand.
12147 The parameters in QRhiIndexedIndirectDrawCommand have the same meaning as in drawIndexed().
12148
12149 The offset, in bytes, from which the parameters are read in the buffer is specified
12150 by \a indirectBufferOffset.
12151
12152 \a drawCount specifies the number of such draw commands to issue.
12153
12154 \a stride indicates the byte size of each individual draw command structure
12155 in the buffer. This allows interleaving custom data between commands if needed.
12156 The value must be a multiple of 4 and greater than or equal to sizeof(QRhiIndexedIndirectDrawCommand).
12157
12158 \note A \a drawCount value greater than 1 is only natively supported if the
12159 QRhi::DrawIndirectMulti feature is reported as supported.
12160 Otherwise, this function emulates multi-draw by recording multiple draw calls,
12161 offering no performance benefit over repeated drawIndexed() calls.
12162
12163 \note Leaving \a stride at its default is recommended whenever performance
12164 matters. With Direct 3D 12 a non-default stride prevents issuing a single
12165 native multi-draw, forcing the backend to record one command per draw
12166 instead. For a large \a drawCount this can be an order of magnitude slower,
12167 which defeats the purpose of the indirect draw. Vulkan, OpenGL, and Metal
12168 pass the stride on to their native multi-draw entry points and are not
12169 affected. Rather than interleaving custom data between the commands, keep
12170 that data in a separate buffer and index into it.
12171
12172 \note With some backends a large \a drawCount is implemented by interrupting
12173 and then restarting the render pass internally due to launching a compute
12174 kernel to encode commands into an indirect command buffer. With Metal this
12175 happens above a certain \a drawCount (e.g., 128). This has consequences for
12176 the render targets: color attachment contents are preserved automatically,
12177 but a QRhiRenderBuffer serving as the depth-stencil buffer only keeps its
12178 contents if it was created with QRhiRenderBuffer::NoTransientBacking, which
12179 means that, with Metal, rendering errors may occur if the depth-stencil
12180 buffer is a QRhiRenderBuffer without the NoTransientBacking flag and the \a
12181 drawCount is above the threshold. Recording the same commands into a
12182 QRhiIndirectCommandBuffer and issuing them with executeIndirect() avoids
12183 this altogether: that never interrupts the pass.
12184
12185 \note Therefore, portable applications should consider always using
12186 QRhiIndirectCommandBuffer and executeIndirect() instead of the
12187 draw*Indirect*() family of functions.
12188
12189 \note This function can only be called inside a render pass, meaning
12190 between a beginPass() and endPass() call.
12191
12192 \since 6.12
12193
12194 \sa drawIndirect(), drawIndirectCount(), drawIndexedIndirectCount()
12195 */
12196void QRhiCommandBuffer::drawIndexedIndirect(QRhiBuffer *indirectBuffer,
12197 quint32 indirectBufferOffset,
12198 quint32 drawCount,
12199 quint32 stride)
12200{
12201 Q_ASSERT(indirectBuffer);
12202 Q_ASSERT(indirectBuffer->usage().testFlag(QRhiBuffer::IndirectBuffer));
12203 Q_ASSERT_X((indirectBufferOffset & 3u) == 0u, Q_FUNC_INFO, "indirectBufferOffset must be a multiple of 4");
12204 Q_ASSERT(stride >= sizeof(QRhiIndexedIndirectDrawCommand));
12205 Q_ASSERT_X((stride & 3u) == 0u, Q_FUNC_INFO, "stride must be a multiple of 4");
12206 m_rhi->drawIndexedIndirect(this, indirectBuffer, indirectBufferOffset, drawCount, stride);
12207}
12208
12209/*!
12210 Records a non-indexed, indirect draw, with the draw count itself read
12211 from a buffer at execution time.
12212
12213 Draw parameters are read from \a indirectBuffer at byte offset
12214 \a indirectBufferOffset as an array of QRhiIndirectDrawCommand entries
12215 spaced \a stride bytes apart. The number of draws issued is the 32-bit
12216 unsigned integer stored at \a countBufferOffset in \a countBuffer, clamped
12217 to \a maxDrawCount.
12218
12219 Both buffers must have QRhiBuffer::IndirectBuffer usage. Offsets must be
12220 4-byte aligned; \a stride must be 4-byte aligned and at least
12221 sizeof(QRhiIndirectDrawCommand).
12222
12223 Only available when \l QRhi::DrawIndirectCount is reported as supported.
12224 On other backends this is a no-op and a warning is logged. With Metal there
12225 are additional requirements, see QRhi::DrawIndirectCount.
12226
12227 \note Unlike with drawIndirect(), a non-default \a stride does not prevent
12228 the use of a single native multi-draw here. With Direct 3D 12 it does mean
12229 that an additional command signature is created and cached for each
12230 distinct stride value, so sticking to one stride is still preferable.
12231
12232 \note The value in \a countBuffer is read as a \e signed 32-bit integer by
12233 OpenGL, unlike the other backends. Counts above \c INT_MAX are therefore
12234 not portable, and neither is relying on any particular behavior for a count
12235 that exceeds \a maxDrawCount, beyond the clamping described above.
12236
12237 \note With some backends, Metal in particular, the render pass is always
12238 interrupted and restarted internally because the draw commands have to be
12239 encoded on the GPU. Color attachment contents are preserved automatically,
12240 but a QRhiRenderBuffer serving as the depth-stencil buffer only keeps its
12241 contents if it was created with QRhiRenderBuffer::NoTransientBacking.
12242 Building a QRhiIndirectCommandBuffer with buildIndirect(),
12243 which happens before the pass begins, and issuing it with
12244 executeIndirect() avoids this: that never interrupts the pass, and supports
12245 a device-side count just the same.
12246
12247 \note Therefore, portable applications should consider always using
12248 QRhiIndirectCommandBuffer and executeIndirect() instead of the
12249 draw*Indirect*() family of functions.
12250
12251 \note \a maxDrawCount is not a free upper bound. With Metal it sizes the
12252 indirect command buffer that the draw commands are encoded into, and that
12253 buffer is shared, grows on demand, and is never shrunk again for the
12254 lifetime of the QRhi. It also determines how many encoding threads are
12255 dispatched every time. Passing the capacity of \a indirectBuffer instead of
12256 a realistic upper bound therefore has a real cost.
12257
12258 \note Only valid inside a render pass.
12259
12260 \since 6.13
12261
12262 \sa drawIndirect(), drawIndexedIndirect(), drawIndexedIndirectCount()
12263 */
12264void QRhiCommandBuffer::drawIndirectCount(QRhiBuffer *indirectBuffer,
12265 quint32 indirectBufferOffset,
12266 QRhiBuffer *countBuffer,
12267 quint32 countBufferOffset,
12268 quint32 maxDrawCount,
12269 quint32 stride)
12270{
12271 Q_ASSERT(indirectBuffer);
12272 Q_ASSERT(countBuffer);
12273 Q_ASSERT(indirectBuffer->usage().testFlag(QRhiBuffer::IndirectBuffer));
12274 Q_ASSERT(countBuffer->usage().testFlag(QRhiBuffer::IndirectBuffer));
12275 Q_ASSERT_X((indirectBufferOffset & 3u) == 0u, Q_FUNC_INFO, "indirectBufferOffset must be a multiple of 4");
12276 Q_ASSERT_X((countBufferOffset & 3u) == 0u, Q_FUNC_INFO, "countBufferOffset must be a multiple of 4");
12277 Q_ASSERT(stride >= sizeof(QRhiIndirectDrawCommand));
12278 Q_ASSERT_X((stride & 3u) == 0u, Q_FUNC_INFO, "stride must be a multiple of 4");
12279 m_rhi->drawIndirectCount(this, indirectBuffer, indirectBufferOffset,
12280 countBuffer, countBufferOffset, maxDrawCount, stride);
12281}
12282
12283/*!
12284 Indexed variant of drawIndirectCount(). \a indirectBuffer contains, at byte
12285 offset \a indirectBufferOffset, QRhiIndexedIndirectDrawCommand entries,
12286 spaced \a stride bytes apart, and \a stride must be at least
12287 sizeof(QRhiIndexedIndirectDrawCommand). All other requirements, including
12288 how \a countBuffer, \a countBufferOffset and \a maxDrawCount are
12289 interpreted, are as described for drawIndirectCount().
12290
12291 \note The render pass interruption described for drawIndirectCount() applies
12292 here as well.
12293
12294 \note Therefore, portable applications should consider always using
12295 QRhiIndirectCommandBuffer and executeIndirect() instead of the
12296 draw*Indirect*() family of functions.
12297
12298 \note Only valid inside a render pass.
12299
12300 \since 6.13
12301
12302 \sa drawIndirect(), drawIndexedIndirect(), drawIndirectCount()
12303 */
12304void QRhiCommandBuffer::drawIndexedIndirectCount(QRhiBuffer *indirectBuffer,
12305 quint32 indirectBufferOffset,
12306 QRhiBuffer *countBuffer,
12307 quint32 countBufferOffset,
12308 quint32 maxDrawCount,
12309 quint32 stride)
12310{
12311 Q_ASSERT(indirectBuffer);
12312 Q_ASSERT(countBuffer);
12313 Q_ASSERT(indirectBuffer->usage().testFlag(QRhiBuffer::IndirectBuffer));
12314 Q_ASSERT(countBuffer->usage().testFlag(QRhiBuffer::IndirectBuffer));
12315 Q_ASSERT_X((indirectBufferOffset & 3u) == 0u, Q_FUNC_INFO, "indirectBufferOffset must be a multiple of 4");
12316 Q_ASSERT_X((countBufferOffset & 3u) == 0u, Q_FUNC_INFO, "countBufferOffset must be a multiple of 4");
12317 Q_ASSERT(stride >= sizeof(QRhiIndexedIndirectDrawCommand));
12318 Q_ASSERT_X((stride & 3u) == 0u, Q_FUNC_INFO, "stride must be a multiple of 4");
12319 m_rhi->drawIndexedIndirectCount(this, indirectBuffer, indirectBufferOffset,
12320 countBuffer, countBufferOffset, maxDrawCount, stride);
12321}
12322
12323/*!
12324 Records populating the indirect command buffer \a icb from the buffer and
12325 parameters described by \a info.
12326
12327 This is the GPU-driven counterpart of recording draw() or drawIndexed()
12328 calls on the QRhiIndirectCommandBuffer: the commands come from
12329 \c{info.sourceBuffer}, which is typically written by a compute shader
12330 earlier in the frame. Any commands recorded on the CPU side are ignored
12331 from this point on.
12332
12333 \c{info.topology} and, for an indirect command buffer of type
12334 QRhiIndirectCommandBuffer::IndexedDraws, \c{info.indexBuffer} have to be
12335 specified because some backends need them in order to build their native
12336 indirect command buffer object, and neither is available outside of a
12337 render pass. They must match what is set on the command buffer when
12338 executeIndirect() is called.
12339
12340 \c{info.commandCount} is the number of commands to take from
12341 \c{info.sourceBuffer}, and becomes what
12342 QRhiIndirectCommandBuffer::commandCount() reports from here on. Leaving it
12343 at 0 means \a{icb}'s QRhiIndirectCommandBuffer::maxCommandCount(); a larger
12344 value is clamped to that, with a warning. The size of
12345 \c{info.sourceBuffer} is not consulted. When \c{info.countBuffer} is set,
12346 \c{info.commandCount} becomes an upper bound instead, with the device-side
12347 count deciding how many commands are executed.
12348
12349 \note This function must be called outside of any pass. That is the entire
12350 point: it gives backends that need to run a compute shader in order to
12351 build their native indirect command buffer a place to do so without having
12352 to interrupt and restart the render pass.
12353
12354 \sa executeIndirect(), QRhiIndirectCommandBuffer
12355 */
12356void QRhiCommandBuffer::buildIndirect(QRhiIndirectCommandBuffer *icb,
12357 const QRhiIndirectCommandBufferBuildInfo &info)
12358{
12359 Q_ASSERT(icb);
12360 Q_ASSERT(info.sourceBuffer);
12361 Q_ASSERT(info.sourceBuffer->usage().testFlag(QRhiBuffer::IndirectBuffer));
12362 Q_ASSERT_X((info.sourceBufferOffset & 3u) == 0u, Q_FUNC_INFO,
12363 "sourceBufferOffset must be a multiple of 4");
12364 Q_ASSERT_X((info.stride & 3u) == 0u, Q_FUNC_INFO, "stride must be a multiple of 4");
12365 Q_ASSERT(!info.countBuffer || info.countBuffer->usage().testFlag(QRhiBuffer::IndirectBuffer));
12366 Q_ASSERT_X((info.countBufferOffset & 3u) == 0u, Q_FUNC_INFO,
12367 "countBufferOffset must be a multiple of 4");
12368 m_rhi->buildIndirect(this, icb, info);
12369}
12370
12371/*!
12372 Records executing the commands held by the indirect command buffer \a icb,
12373 starting at \a firstCommand and executing at most \a commandCount of them.
12374 By default all commands are executed.
12375
12376 Everything else - the graphics pipeline, the vertex and index buffers, the
12377 shader resources, the viewport, the scissor - is taken from the current
12378 state of the command buffer, exactly like with drawIndirect().
12379
12380 The number of draws issued is \c{qMin(commandCount, icb->commandCount() -
12381 firstCommand)}, so leaving \a commandCount at its default executes
12382 everything from \a firstCommand onwards. What
12383 QRhiIndirectCommandBuffer::commandCount() means depends on how \a icb was
12384 populated: it is the number of draw() and drawIndexed() calls recorded on
12385 it, or, after a buildIndirect(), the count resolved from
12386 QRhiIndirectCommandBufferBuildInfo::commandCount. Nothing is drawn when \a
12387 firstCommand is at or past that count.
12388
12389 When \a icb was populated by recording draw() or drawIndexed() calls on it,
12390 the recorded contents must have been flushed with
12391 QRhiResourceUpdateBatch::commitIndirectCommandBuffer() beforehand. When it
12392 was populated with buildIndirect(), and a count buffer was specified there,
12393 the device-side count reduces the number of draws further: the number
12394 actually executed is the smallest of that, \a commandCount, and what is
12395 left in \a icb after \a firstCommand.
12396
12397 \warning With a count buffer some backends, Metal in particular, cannot combine
12398 the device-side count with a subrange. \a firstCommand and \a commandCount
12399 are then ignored, printing a warning, and all commands up to the device-side
12400 count are executed.
12401
12402 \note An indirect command buffer that was populated by recording draw() or
12403 drawIndexed() calls on it can be executed any number of times, but within
12404 one frame all those executions must use the same topology, index buffer,
12405 index buffer offset and index format: some backends bake these into their
12406 native indirect command buffer at the first executeIndirect() of the frame.
12407 A mismatch is reported with a warning, and handled by falling back to
12408 ordinary draw calls.
12409
12410 \note Unlike drawIndirect(), drawIndexedIndirect(), drawIndirectCount() and
12411 drawIndexedIndirectCount(), this never causes the render pass to be
12412 interrupted and restarted internally, whatever the number of commands.
12413 Commands built with buildIndirect() were prepared before the pass began, and
12414 CPU-recorded ones need no compute work to encode. The consequences described
12415 for those functions therefore do not apply here. Color attachment contents
12416 are not at risk, and a QRhiRenderBuffer serving as the depth-stencil buffer
12417 keeps its contents without needing QRhiRenderBuffer::NoTransientBacking.
12418
12419 \note The CPU cost of this call is not constant for a CPU-recorded indirect
12420 command buffer. When the recorded contents changed since the last execution,
12421 some backends do their per-command native encoding here rather than in
12422 QRhiResourceUpdateBatch::commitIndirectCommandBuffer(), which for a large
12423 command set re-recorded every frame can dominate the time spent between
12424 beginPass() and endPass(). See \l QRhiIndirectCommandBuffer for how the cost
12425 of CPU recording scales.
12426
12427 \note This function can only be called inside a render pass.
12428
12429 \sa buildIndirect(), drawIndirect(), QRhiIndirectCommandBuffer
12430 */
12431void QRhiCommandBuffer::executeIndirect(QRhiIndirectCommandBuffer *icb,
12432 quint32 firstCommand,
12433 quint32 commandCount)
12434{
12435 Q_ASSERT(icb);
12436 m_rhi->executeIndirect(this, icb, firstCommand, commandCount);
12437}
12438
12439/*!
12440 Records a named debug group on the command buffer with the specified \a
12441 name. This is shown in graphics debugging tools such as
12442 \l{https://renderdoc.org/}{RenderDoc} and
12443 \l{https://developer.apple.com/xcode/}{XCode}. The end of the grouping is
12444 indicated by debugMarkEnd().
12445
12446 \note Ignored when QRhi::DebugMarkers are not supported or
12447 QRhi::EnableDebugMarkers is not set.
12448
12449 \note Can be called anywhere within the frame, both inside and outside of passes.
12450 */
12451void QRhiCommandBuffer::debugMarkBegin(const QByteArray &name)
12452{
12453 m_rhi->debugMarkBegin(this, name);
12454}
12455
12456/*!
12457 Records the end of a debug group.
12458
12459 \note Ignored when QRhi::DebugMarkers are not supported or
12460 QRhi::EnableDebugMarkers is not set.
12461
12462 \note Can be called anywhere within the frame, both inside and outside of passes.
12463 */
12464void QRhiCommandBuffer::debugMarkEnd()
12465{
12466 m_rhi->debugMarkEnd(this);
12467}
12468
12469/*!
12470 Inserts a debug message \a msg into the command stream.
12471
12472 \note Ignored when QRhi::DebugMarkers are not supported or
12473 QRhi::EnableDebugMarkers is not set.
12474
12475 \note With some backends debugMarkMsg() is only supported inside a pass and
12476 is ignored when called outside a pass. With others it is recorded anywhere
12477 within the frame.
12478 */
12479void QRhiCommandBuffer::debugMarkMsg(const QByteArray &msg)
12480{
12481 m_rhi->debugMarkMsg(this, msg);
12482}
12483
12484/*!
12485 Records starting a new compute pass.
12486
12487 \a resourceUpdates, when not null, specifies a resource update batch that
12488 is to be committed and then released.
12489
12490 \note Do not assume that any state or resource bindings persist between
12491 passes.
12492
12493 \note A compute pass can record setComputePipeline(), setShaderResources(),
12494 and dispatch() calls, not graphics ones. General functionality, such as,
12495 debug markers and beginExternal() is available both in render and compute
12496 passes.
12497
12498 \note Compute is only available when the \l{QRhi::Compute}{Compute} feature
12499 is reported as supported.
12500
12501 \a flags is not currently used.
12502 */
12503void QRhiCommandBuffer::beginComputePass(QRhiResourceUpdateBatch *resourceUpdates, BeginPassFlags flags)
12504{
12505 m_rhi->beginComputePass(this, resourceUpdates, flags);
12506}
12507
12508/*!
12509 Records ending the current compute pass.
12510
12511 \a resourceUpdates, when not null, specifies a resource update batch that
12512 is to be committed and then released.
12513 */
12514void QRhiCommandBuffer::endComputePass(QRhiResourceUpdateBatch *resourceUpdates)
12515{
12516 m_rhi->endComputePass(this, resourceUpdates);
12517}
12518
12519/*!
12520 Records setting a new compute pipeline \a ps.
12521
12522 \note This function must be called before recording setShaderResources() or
12523 dispatch() commands on the command buffer.
12524
12525 \note QRhi will optimize out unnecessary invocations within a pass, so
12526 therefore overoptimizing to avoid calls to this function is not necessary
12527 on the applications' side.
12528
12529 \note This function can only be called inside a compute pass, meaning
12530 between a beginComputePass() and endComputePass() call.
12531 */
12532void QRhiCommandBuffer::setComputePipeline(QRhiComputePipeline *ps)
12533{
12534 m_rhi->setComputePipeline(this, ps);
12535}
12536
12537/*!
12538 Records dispatching compute work items, with \a x, \a y, and \a z
12539 specifying the number of local workgroups in the corresponding dimension.
12540
12541 \note This function can only be called inside a compute pass, meaning
12542 between a beginComputePass() and endComputePass() call.
12543
12544 \note \a x, \a y, and \a z must fit the limits from the underlying graphics
12545 API implementation at run time. The maximum values are typically 65535.
12546
12547 \note Watch out for possible limits on the local workgroup size as well.
12548 This is specified in the shader, for example: \c{layout(local_size_x = 16,
12549 local_size_y = 16) in;}. For example, with OpenGL the minimum value mandated
12550 by the specification for the number of invocations in a single local work
12551 group (the product of \c local_size_x, \c local_size_y, and \c local_size_z)
12552 is 1024, while with OpenGL ES (3.1) the value may be as low as 128. This
12553 means that the example given above may be rejected by some OpenGL ES
12554 implementations as the number of invocations is 256.
12555 */
12556void QRhiCommandBuffer::dispatch(int x, int y, int z)
12557{
12558 m_rhi->dispatch(this, x, y, z);
12559}
12560
12561/*!
12562 Records an indirect compute dispatch.
12563
12564 The work group counts are read by the device from \a indirectBuffer at
12565 \a indirectBufferOffset, as a single QRhiDispatchIndirectCommand.
12566 \a indirectBuffer must have QRhiBuffer::IndirectBuffer usage and
12567 \a indirectBufferOffset must be 4-byte aligned.
12568
12569 Only one dispatch per call; no native multi-dispatch variant exists.
12570 Requires \l QRhi::DispatchIndirect.
12571
12572 \note Only valid inside a compute pass.
12573
12574 \since 6.13
12575 */
12576void QRhiCommandBuffer::dispatchIndirect(QRhiBuffer *indirectBuffer,
12577 quint32 indirectBufferOffset)
12578{
12579 Q_ASSERT(indirectBuffer);
12580 Q_ASSERT(indirectBuffer->usage().testFlag(QRhiBuffer::IndirectBuffer));
12581 Q_ASSERT_X((indirectBufferOffset & 3u) == 0u, Q_FUNC_INFO, "indirectBufferOffset must be a multiple of 4");
12582 m_rhi->dispatchIndirect(this, indirectBuffer, indirectBufferOffset);
12583}
12584
12585/*!
12586 \return a pointer to a backend-specific QRhiNativeHandles subclass, such as
12587 QRhiVulkanCommandBufferNativeHandles. The returned value is \nullptr when
12588 exposing the underlying native resources is not supported by, or not
12589 applicable to, the backend.
12590
12591 \sa QRhiVulkanCommandBufferNativeHandles,
12592 QRhiMetalCommandBufferNativeHandles, beginExternal(), endExternal()
12593 */
12594const QRhiNativeHandles *QRhiCommandBuffer::nativeHandles()
12595{
12596 return m_rhi->nativeHandles(this);
12597}
12598
12599/*!
12600 To be called when the application before the application is about to
12601 enqueue commands to the current pass' command buffer by calling graphics
12602 API functions directly.
12603
12604 \note This is only available when the intent was declared upfront in
12605 beginPass() or beginComputePass(). Therefore this function must only be
12606 called when the pass recording was started with specifying
12607 QRhiCommandBuffer::ExternalContent.
12608
12609 With Vulkan, Metal, or Direct3D 12 one can query the native command buffer
12610 or encoder objects via nativeHandles() and enqueue commands to them. With
12611 OpenGL or Direct3D 11 the (device) context can be retrieved from
12612 QRhi::nativeHandles(). However, this must never be done without ensuring
12613 the QRhiCommandBuffer's state stays up-to-date. Hence the requirement for
12614 wrapping any externally added command recording between beginExternal() and
12615 endExternal(). Conceptually this is the same as QPainter's
12616 \l{QPainter::beginNativePainting()}{beginNativePainting()} and
12617 \l{QPainter::endNativePainting()}{endNativePainting()} functions.
12618
12619 For OpenGL in particular, this function has an additional task: it makes
12620 sure the context is made current on the current thread.
12621
12622 \note Once beginExternal() is called, no other render pass specific
12623 functions (\c set* or \c draw*) must be called on the
12624 QRhiCommandBuffer until endExternal().
12625
12626 \warning Some backends may return a native command buffer object from
12627 QRhiCommandBuffer::nativeHandles() that is different from the primary one
12628 when inside a beginExternal() - endExternal() block. Therefore it is
12629 important to (re)query the native command buffer object after calling
12630 beginExternal(). In practical terms this means that with Vulkan for example
12631 the externally recorded Vulkan commands are placed onto a secondary command
12632 buffer (with VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT).
12633 nativeHandles() returns this secondary command buffer when called between
12634 begin/endExternal.
12635
12636 \sa endExternal(), nativeHandles()
12637 */
12638void QRhiCommandBuffer::beginExternal()
12639{
12640 m_rhi->beginExternal(this);
12641}
12642
12643/*!
12644 To be called once the externally added commands are recorded to the command
12645 buffer or context.
12646
12647 \note All QRhiCommandBuffer state must be assumed as invalid after calling
12648 this function. Pipelines, vertex and index buffers, and other state must be
12649 set again if more draw calls are recorded after the external commands.
12650
12651 \sa beginExternal(), nativeHandles()
12652 */
12653void QRhiCommandBuffer::endExternal()
12654{
12655 m_rhi->endExternal(this);
12656}
12657
12658/*!
12659 \return the last available timestamp, in seconds, when
12660 \l QRhi::EnableTimestamps was enabled when creating the QRhi. The value
12661 indicates the elapsed time on the GPU during the last completed frame.
12662
12663 \note Do not expect results other than 0 when the QRhi::Timestamps feature
12664 is not reported as supported, or when QRhi::EnableTimestamps was not passed
12665 to QRhi::create(). There are exceptions to this, because with some graphics
12666 APIs (Metal) timings are available without having to perform extra
12667 operations (timestamp queries), but portable applications should always
12668 consciously opt-in to timestamp collection when they know it is needed, and
12669 call this function accordingly.
12670
12671 Care must be exercised with the interpretation of the value, as its
12672 precision and granularity is often not controlled by Qt, and depends on the
12673 underlying graphics API and its implementation. In particular, comparing
12674 the values between different graphics APIs and hardware is discouraged and
12675 may be meaningless.
12676
12677 The timing values will likely become available asynchronously. The returned
12678 value may therefore be 0 (e.g., for the first 1-2 frames) or the last known
12679 value referring to some previous frame. The value my also become 0 again
12680 under certain conditions, such as when resizing the window. It can be
12681 expected that the most up-to-date available value is retrieved in
12682 beginFrame() and becomes queriable via this function once beginFrame()
12683 returns.
12684
12685 \note Do not assume that the value refers to the previous
12686 (\c{currently_recorded - 1}) frame. It may refer to \c{currently_recorded -
12687 2} or \c{currently_recorded - 3} as well. The exact behavior may depend on
12688 the graphics API and its implementation.
12689
12690 Watch out for the consequences of GPU frequency scaling and GPU clock
12691 changes, depending on the platform. For example, on Windows the returned
12692 timing may vary in a quite wide range between frames with modern graphics
12693 cards, even when submitting frames with a similar, or the same workload.
12694 This is out of scope for Qt to control and solve, generally speaking.
12695 However, the D3D12 backend automatically calls
12696 \l{https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-setstablepowerstate}{ID3D12Device::SetStablePowerState()}
12697 whenever the environment variable \c QT_D3D_STABLE_POWER_STATE is set to a
12698 non-zero value. This can greatly stabilize the result. It can also have a
12699 non-insignificant effect on the CPU-side timings measured via QElapsedTimer
12700 for example, especially when offscreen frames are involved.
12701
12702 \note Do not and never ship applications to production with
12703 \c QT_D3D_STABLE_POWER_STATE set. See the Windows API documentation for details.
12704
12705 \sa QRhi::Timestamps, QRhi::EnableTimestamps
12706 */
12707double QRhiCommandBuffer::lastCompletedGpuTime()
12708{
12709 return m_rhi->lastCompletedGpuTime(this);
12710}
12711
12712/*!
12713 \return the value (typically an offset) \a v aligned to the uniform buffer
12714 alignment given by ubufAlignment().
12715 */
12716int QRhi::ubufAligned(int v) const
12717{
12718 const int byteAlign = ubufAlignment();
12719 return (v + byteAlign - 1) & ~(byteAlign - 1);
12720}
12721
12722/*!
12723 \return the number of mip levels for a given \a size.
12724 */
12725int QRhi::mipLevelsForSize(const QSize &size)
12726{
12727 return qFloor(std::log2(qMax(size.width(), size.height()))) + 1;
12728}
12729
12730/*!
12731 \return the texture image size for a given \a mipLevel, calculated based on
12732 the level 0 size given in \a baseLevelSize.
12733 */
12734QSize QRhi::sizeForMipLevel(int mipLevel, const QSize &baseLevelSize)
12735{
12736 const int w = qMax(1, baseLevelSize.width() >> mipLevel);
12737 const int h = qMax(1, baseLevelSize.height() >> mipLevel);
12738 return QSize(w, h);
12739}
12740
12741/*!
12742 \return \c true if the underlying graphics API has the Y axis pointing up
12743 in framebuffers and images.
12744
12745 In practice this is \c true for OpenGL only.
12746
12747 \sa {Coordinate system differences between graphics APIs}
12748 */
12749bool QRhi::isYUpInFramebuffer() const
12750{
12751 return d->isYUpInFramebuffer();
12752}
12753
12754/*!
12755 \return \c true if the underlying graphics API has the Y axis pointing up
12756 in its normalized device coordinate system.
12757
12758 In practice this is \c false for Vulkan only.
12759
12760 \note clipSpaceCorrMatrix() includes the corresponding adjustment (to make
12761 Y point up) in its returned matrix.
12762
12763 \sa {Coordinate system differences between graphics APIs}
12764 */
12765bool QRhi::isYUpInNDC() const
12766{
12767 return d->isYUpInNDC();
12768}
12769
12770/*!
12771 \return \c true if the underlying graphics API uses depth range [0, 1] in
12772 clip space.
12773
12774 In practice this is \c false for OpenGL only, because OpenGL uses a
12775 post-projection depth range of [-1, 1]. (not to be confused with the
12776 NDC-to-window mapping controlled by glDepthRange(), which uses a range of
12777 [0, 1], unless overridden by the QRhiViewport) In some OpenGL versions
12778 glClipControl() could be used to change this, but the OpenGL backend of
12779 QRhi does not use that function as it is not available in OpenGL ES or
12780 OpenGL versions lower than 4.5.
12781
12782 \note clipSpaceCorrMatrix() includes the corresponding adjustment in its
12783 returned matrix. Therefore, many users of QRhi do not need to take any
12784 further measures apart from pre-multiplying their projection matrices with
12785 clipSpaceCorrMatrix(). However, some graphics techniques, such as, some
12786 types of shadow mapping, involve working with and outputting depth values
12787 in the shaders. These will need to query and take the value of this
12788 function into account as appropriate.
12789
12790 \sa {Coordinate system differences between graphics APIs}
12791 */
12792bool QRhi::isClipDepthZeroToOne() const
12793{
12794 return d->isClipDepthZeroToOne();
12795}
12796
12797/*!
12798 \return a matrix that can be used to allow applications keep using
12799 OpenGL-targeted vertex data and perspective projection matrices (such as,
12800 the ones generated by QMatrix4x4::perspective()), regardless of the active
12801 QRhi backend.
12802
12803 In a typical renderer, once \c{this_matrix * mvp} is used instead of just
12804 \c mvp, vertex data with Y up and viewports with depth range 0 - 1 can be
12805 used without considering what backend (and so graphics API) is going to be
12806 used at run time. This way branching based on isYUpInNDC() and
12807 isClipDepthZeroToOne() can be avoided (although such logic may still become
12808 required when implementing certain advanced graphics techniques).
12809
12810 See
12811 \l{https://matthewwellings.com/blog/the-new-vulkan-coordinate-system/}{this
12812 page} for a discussion of the topic from Vulkan perspective.
12813
12814 \sa {Coordinate system differences between graphics APIs}
12815 */
12816QMatrix4x4 QRhi::clipSpaceCorrMatrix() const
12817{
12818 return d->clipSpaceCorrMatrix();
12819}
12820
12821/*!
12822 \return \c true if the specified texture \a format modified by \a flags is
12823 supported.
12824
12825 The query is supported both for uncompressed and compressed formats.
12826 */
12827bool QRhi::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const
12828{
12829 return d->isTextureFormatSupported(format, flags);
12830}
12831
12832/*!
12833 \return \c true if the specified \a feature is supported
12834 */
12835bool QRhi::isFeatureSupported(QRhi::Feature feature) const
12836{
12837 return d->isFeatureSupported(feature);
12838}
12839
12840/*!
12841 \return the value for the specified resource \a limit.
12842
12843 The values are expected to be queried by the backends upon initialization,
12844 meaning calling this function is a light operation.
12845 */
12846int QRhi::resourceLimit(ResourceLimit limit) const
12847{
12848 return d->resourceLimit(limit);
12849}
12850
12851/*!
12852 \return a pointer to the backend-specific collection of native objects
12853 for the device, context, and similar concepts used by the backend.
12854
12855 Cast to QRhiVulkanNativeHandles, QRhiD3D11NativeHandles,
12856 QRhiD3D12NativeHandles, QRhiGles2NativeHandles, or QRhiMetalNativeHandles
12857 as appropriate.
12858
12859 \note No ownership is transferred, neither for the returned pointer nor for
12860 any native objects.
12861 */
12862const QRhiNativeHandles *QRhi::nativeHandles()
12863{
12864 return d->nativeHandles();
12865}
12866
12867/*!
12868 With OpenGL this makes the OpenGL context current on the current thread.
12869 The function has no effect with other backends.
12870
12871 Calling this function is relevant typically in Qt framework code, when one
12872 has to ensure external OpenGL code provided by the application can still
12873 run like it did before with direct usage of OpenGL, as long as the QRhi is
12874 using the OpenGL backend.
12875
12876 \return false when failed, similarly to QOpenGLContext::makeCurrent(). When
12877 the operation failed, isDeviceLost() can be called to determine if there
12878 was a loss of context situation. Such a check is equivalent to checking via
12879 QOpenGLContext::isValid().
12880
12881 \sa QOpenGLContext::makeCurrent(), QOpenGLContext::isValid()
12882 */
12883bool QRhi::makeThreadLocalNativeContextCurrent()
12884{
12885 return d->makeThreadLocalNativeContextCurrent();
12886}
12887
12888/*!
12889 With backends and graphics APIs where applicable, this function allows to
12890 provide additional arguments to the \b next submission of commands to the
12891 graphics command queue.
12892
12893 In particular, with Vulkan this allows passing in a list of Vulkan semaphore
12894 objects for \c vkQueueSubmit() to signal and wait on. \a params must then be
12895 a \l QRhiVulkanQueueSubmitParams. This becomes essential in certain advanced
12896 use cases, such as when performing native Vulkan calls that involve having
12897 to wait on and signal VkSemaphores that the application's custom Vulkan
12898 rendering or compute code manages. In addition, this also allows specifying
12899 additional semaphores to wait on in the next \c vkQueuePresentKHR().
12900
12901 \note This function affects the next queue submission only, which will
12902 happen in endFrame(), endOffscreenFrame(), or finish(). The enqueuing of
12903 present happens in endFrame().
12904
12905 With many other backends the implementation of this function is a no-op.
12906
12907 \since 6.9
12908 */
12909void QRhi::setQueueSubmitParams(QRhiNativeHandles *params)
12910{
12911 d->setQueueSubmitParams(params);
12912}
12913
12914/*!
12915 Attempts to release resources in the backend's caches. This can include both
12916 CPU and GPU resources. Only memory and resources that can be recreated
12917 automatically are in scope. As an example, if the backend's
12918 QRhiGraphicsPipeline implementation maintains a cache of shader compilation
12919 results, calling this function leads to emptying that cache, thus
12920 potentially freeing up memory and graphics resources.
12921
12922 Calling this function makes sense in resource constrained environments,
12923 where at a certain point there is a need to ensure minimal resource usage,
12924 at the expense of performance.
12925 */
12926void QRhi::releaseCachedResources()
12927{
12928 d->releaseCachedResources();
12929
12930 for (QRhiResourceUpdateBatch *u : d->resUpdPool) {
12931 if (u->d->poolIndex < 0)
12932 u->d->trimOpLists();
12933 }
12934}
12935
12936/*!
12937 \return true if the graphics device was lost.
12938
12939 The loss of the device is typically detected in beginFrame(), endFrame() or
12940 QRhiSwapChain::createOrResize(), depending on the backend and the underlying
12941 native APIs. The most common is endFrame() because that is where presenting
12942 happens. With some backends QRhiSwapChain::createOrResize() can also fail
12943 due to a device loss. Therefore this function is provided as a generic way
12944 to check if a device loss was detected by a previous operation.
12945
12946 When the device is lost, no further operations should be done via the QRhi.
12947 Rather, all QRhi resources should be released, followed by destroying the
12948 QRhi. A new QRhi can then be attempted to be created. If successful, all
12949 graphics resources must be reinitialized. If not, try again later,
12950 repeatedly.
12951
12952 While simple applications may decide to not care about device loss,
12953 on the commonly used desktop platforms a device loss can happen
12954 due to a variety of reasons, including physically disconnecting the
12955 graphics adapter, disabling the device or driver, uninstalling or upgrading
12956 the graphics driver, or due to errors that lead to a graphics device reset.
12957 Some of these can happen under perfectly normal circumstances as well, for
12958 example the upgrade of the graphics driver to a newer version is a common
12959 task that can happen at any time while a Qt application is running. Users
12960 may very well expect applications to be able to survive this, even when the
12961 application is actively using an API like OpenGL or Direct3D.
12962
12963 Qt's own frameworks built on top of QRhi, such as, Qt Quick, can be
12964 expected to handle and take appropriate measures when a device loss occurs.
12965 If the data for graphics resources, such as textures and buffers, are still
12966 available on the CPU side, such an event may not be noticeable on the
12967 application level at all since graphics resources can seamlessly be
12968 reinitialized then. However, applications and libraries working directly
12969 with QRhi are expected to be prepared to check and handle device loss
12970 situations themselves.
12971
12972 \note With OpenGL, applications may need to opt-in to context reset
12973 notifications by setting QSurfaceFormat::ResetNotification on the
12974 QOpenGLContext. This is typically done by enabling the flag in
12975 QRhiGles2InitParams::format. Keep in mind however that some systems may
12976 generate context resets situations even when this flag is not set.
12977 */
12978bool QRhi::isDeviceLost() const
12979{
12980 return d->isDeviceLost();
12981}
12982
12983/*!
12984 \return a binary data blob with data collected from the
12985 QRhiGraphicsPipeline and QRhiComputePipeline successfully created during
12986 the lifetime of this QRhi.
12987
12988 By saving and then, in subsequent runs of the same application, reloading
12989 the cache data, pipeline and shader creation times can potentially be
12990 reduced. What exactly the cache and its serialized version includes is not
12991 specified, is always specific to the backend used, and in some cases also
12992 dependent on the particular implementation of the graphics API.
12993
12994 When the PipelineCacheDataLoadSave is reported as unsupported, the returned
12995 QByteArray is empty.
12996
12997 When the EnablePipelineCacheDataSave flag was not specified when calling
12998 create(), the returned QByteArray may be empty, even when the
12999 PipelineCacheDataLoadSave feature is supported.
13000
13001 When the returned data is non-empty, it is always specific to the Qt
13002 version and QRhi backend. In addition, in some cases there is a strong
13003 dependency to the graphics device and the exact driver version used. QRhi
13004 takes care of adding the appropriate header and safeguards that ensure that
13005 the data can always be passed safely to setPipelineCacheData(), therefore
13006 attempting to load data from a run on another version of a driver will be
13007 handled safely and gracefully.
13008
13009 \note Calling releaseCachedResources() may, depending on the backend, clear
13010 the pipeline data collected. A subsequent call to this function may then
13011 not return any data.
13012
13013 See EnablePipelineCacheDataSave for further details about this feature.
13014
13015 \note Minimize the number of calls to this function. Retrieving the blob is
13016 not always a cheap operation, and therefore this function should only be
13017 called at a low frequency, ideally only once e.g. when closing the
13018 application.
13019
13020 \sa setPipelineCacheData(), create(), isFeatureSupported()
13021 */
13022QByteArray QRhi::pipelineCacheData()
13023{
13024 return d->pipelineCacheData();
13025}
13026
13027/*!
13028 Loads \a data into the pipeline cache, when applicable.
13029
13030 When the PipelineCacheDataLoadSave is reported as unsupported, the function
13031 is safe to call, but has no effect.
13032
13033 The blob returned by pipelineCacheData() is always specific to the Qt
13034 version, the QRhi backend, and, in some cases, also to the graphics device,
13035 and a given version of the graphics driver. QRhi takes care of adding the
13036 appropriate header and safeguards that ensure that the data can always be
13037 passed safely to this function. If there is a mismatch, e.g. because the
13038 driver has been upgraded to a newer version, or because the data was
13039 generated from a different QRhi backend, a warning is printed and \a data
13040 is safely ignored.
13041
13042 With Vulkan, this maps directly to VkPipelineCache. Calling this function
13043 creates a new Vulkan pipeline cache object, with its initial data sourced
13044 from \a data. The pipeline cache object is then used by all subsequently
13045 created QRhiGraphicsPipeline and QRhiComputePipeline objects, thus
13046 accelerating, potentially, the pipeline creation.
13047
13048 With Direct 3D 12, this maps to ID3D12PipelineLibrary. Calling this
13049 function creates a new pipeline library object, with its initial data
13050 sourced from \a data. Subsequently created QRhiGraphicsPipeline and
13051 QRhiComputePipeline objects first attempt to load their pipeline state
13052 object from the library. Pipeline state objects that are not found in the
13053 library are created normally and then added to it.
13054
13055 With other APIs there is no real pipeline cache, but they may provide a
13056 cache with bytecode from shader compilations (D3D11) or simulate it with
13057 program binaries (OpenGL). In applications that perform a lot of shader
13058 compilation from source at run time this can provide a significant boost in
13059 subsequent runs if the "pipeline cache" is pre-seeded from an earlier run
13060 using this function.
13061
13062 \note QRhi cannot give any guarantees that \a data has an effect on the
13063 pipeline and shader creation performance. With APIs like Vulkan, it is up
13064 to the driver to decide if \a data is used for some purpose, or if it is
13065 ignored.
13066
13067 See EnablePipelineCacheDataSave for further details about this feature.
13068
13069 \note This mechanism offered by QRhi is independent of the drivers' own
13070 internal persistent caching mechanism, which is not uncommon on platforms
13071 such as Windows or macOS. This means that, depending on the graphics API and
13072 its implementation, the exact effects of retrieving and then reloading
13073 \a data are not predictable. Improved performance may not be visible at all
13074 in case other caching mechanisms outside of Qt's control are already active.
13075
13076 \note Some backends, Metal in particular, may choose to rely on the platform's
13077 own persistent shader caching instead of exposing control via this function
13078 and pipelineCacheData(). In case of Metal, this is indicated by reporting
13079 \c false for the PipelineCacheDataLoadSave feature, but it does not mean
13080 shaders created at run time are not cached persistently by the system.
13081
13082 \note Minimize the number of calls to this function. Loading the blob is
13083 not always a cheap operation, and therefore this function should only be
13084 called at a low frequency, ideally only once e.g. when starting the
13085 application.
13086
13087 \warning Serialized pipeline cache data is assumed to be trusted content. Qt
13088 performs robust parsing of the header and metadata included in \a data,
13089 application developers are however advised to never pass in data from
13090 untrusted sources.
13091
13092 \sa pipelineCacheData(), isFeatureSupported()
13093 */
13094void QRhi::setPipelineCacheData(const QByteArray &data)
13095{
13096 d->setPipelineCacheData(data);
13097}
13098
13099/*!
13100 \struct QRhiStats
13101 \inmodule QtGuiPrivate
13102 \inheaderfile rhi/qrhi.h
13103 \since 6.6
13104
13105 \brief Statistics provided from the underlying memory allocator.
13106
13107 \note This is a RHI API with limited compatibility guarantees, see \l QRhi
13108 for details.
13109 */
13110
13111/*!
13112 \variable QRhiStats::totalPipelineCreationTime
13113
13114 The total time in milliseconds spent in graphics and compute pipeline
13115 creation, which usually involves shader compilation or cache lookups, and
13116 potentially expensive processing.
13117
13118 \note The value should not be compared between different backends since the
13119 concept of "pipelines" and what exactly happens under the hood during, for
13120 instance, a call to QRhiGraphicsPipeline::create(), differ greatly between
13121 graphics APIs and their implementations.
13122
13123 \sa QRhi::statistics()
13124*/
13125
13126/*!
13127 \variable QRhiStats::blockCount
13128
13129 Statistic reported from the Vulkan or D3D12 memory allocator.
13130
13131 \sa QRhi::statistics()
13132*/
13133
13134/*!
13135 \variable QRhiStats::allocCount
13136
13137 Statistic reported from the Vulkan or D3D12 memory allocator.
13138
13139 \sa QRhi::statistics()
13140*/
13141
13142/*!
13143 \variable QRhiStats::usedBytes
13144
13145 Statistic reported from the Vulkan or D3D12 memory allocator.
13146
13147 \sa QRhi::statistics()
13148*/
13149
13150/*!
13151 \variable QRhiStats::unusedBytes
13152
13153 Statistic reported from the Vulkan or D3D12 memory allocator.
13154
13155 \sa QRhi::statistics()
13156*/
13157
13158/*!
13159 \variable QRhiStats::totalUsageBytes
13160
13161 Valid only with D3D12 currently. Matches IDXGIAdapter3::QueryVideoMemoryInfo().
13162
13163 \sa QRhi::statistics()
13164*/
13165
13166#ifndef QT_NO_DEBUG_STREAM
13167QDebug operator<<(QDebug dbg, const QRhiStats &info)
13168{
13169 QDebugStateSaver saver(dbg);
13170 dbg.nospace() << "QRhiStats("
13171 << "totalPipelineCreationTime=" << info.totalPipelineCreationTime
13172 << " blockCount=" << info.blockCount
13173 << " allocCount=" << info.allocCount
13174 << " usedBytes=" << info.usedBytes
13175 << " unusedBytes=" << info.unusedBytes
13176 << " totalUsageBytes=" << info.totalUsageBytes
13177 << ')';
13178 return dbg;
13179}
13180#endif
13181
13182/*!
13183 Gathers and returns statistics about the timings and allocations of
13184 graphics resources.
13185
13186 Data about memory allocations is only available with some backends, where
13187 such operations are under Qt's control. With graphics APIs where there is
13188 no lower level control over resource memory allocations, this will never be
13189 supported and all relevant fields in the results are 0.
13190
13191 With Vulkan in particular, the values are valid always, and are queried
13192 from the underlying memory allocator library. This gives an insight into
13193 the memory requirements of the active buffers and textures.
13194
13195 The same is true for Direct 3D 12. In addition to the memory allocator
13196 library's statistics, here the result also includes a \c totalUsageBytes
13197 field which reports the total size including additional resources that are
13198 not under the memory allocator library's control (swapchain buffers,
13199 descriptor heaps, etc.), as reported by DXGI.
13200
13201 The values correspond to all types of memory used, combined. (i.e. video +
13202 system in case of a discreet GPU)
13203
13204 Additional data, such as the total time in milliseconds spent in graphics
13205 and compute pipeline creation (which usually involves shader compilation or
13206 cache lookups, and potentially expensive processing) is available with most
13207 backends.
13208
13209 \note The elapsed times for operations such as pipeline creation may be
13210 affected by various factors. The results should not be compared between
13211 different backends since the concept of "pipelines" and what exactly
13212 happens under the hood during, for instance, a call to
13213 QRhiGraphicsPipeline::create(), differ greatly between graphics APIs and
13214 their implementations.
13215
13216 \note Additionally, many drivers will likely employ various caching
13217 strategies for shaders, programs, pipelines. (independently of Qt's own
13218 similar facilities, such as setPipelineCacheData() or the OpenGL-specific
13219 program binary disk cache). Because such internal behavior is transparent
13220 to the API client, Qt and QRhi have no knowledge or control over the exact
13221 caching strategy, persistency, invalidation of the cached data, etc. When
13222 reading timings, such as the time spent on pipeline creation, the potential
13223 presence and unspecified behavior of driver-level caching mechanisms should
13224 be kept in mind.
13225 */
13226QRhiStats QRhi::statistics() const
13227{
13228 return d->statistics();
13229}
13230
13231/*!
13232 \return a new graphics pipeline resource.
13233
13234 \sa QRhiResource::destroy()
13235 */
13236QRhiGraphicsPipeline *QRhi::newGraphicsPipeline()
13237{
13238 return d->createGraphicsPipeline();
13239}
13240
13241/*!
13242 \return a new compute pipeline resource.
13243
13244 \note Compute is only available when the \l{QRhi::Compute}{Compute} feature
13245 is reported as supported.
13246
13247 \sa QRhiResource::destroy()
13248 */
13249QRhiComputePipeline *QRhi::newComputePipeline()
13250{
13251 return d->createComputePipeline();
13252}
13253
13254/*!
13255 \return a new shader resource binding collection resource.
13256
13257 \sa QRhiResource::destroy()
13258 */
13259QRhiShaderResourceBindings *QRhi::newShaderResourceBindings()
13260{
13261 return d->createShaderResourceBindings();
13262}
13263
13264/*!
13265 \return a new buffer with the specified \a type, \a usage, and \a size.
13266
13267 \note Some \a usage and \a type combinations may not be supported by all
13268 backends. See \l{QRhiBuffer::UsageFlag}{UsageFlags} and
13269 \l{QRhi::NonDynamicUniformBuffers}{the feature flags}.
13270
13271 \note Backends may choose to allocate buffers bigger than \a size. This is
13272 done transparently to applications, so there are no special restrictions on
13273 the value of \a size. QRhiBuffer::size() will always report back the value
13274 that was requested in \a size.
13275
13276 \sa QRhiResource::destroy()
13277 */
13278QRhiBuffer *QRhi::newBuffer(QRhiBuffer::Type type,
13279 QRhiBuffer::UsageFlags usage,
13280 quint32 size)
13281{
13282 return d->createBuffer(type, usage, size);
13283}
13284
13285/*!
13286 \return a new renderbuffer with the specified \a type, \a pixelSize, \a
13287 sampleCount, and \a flags.
13288
13289 When \a backingFormatHint is set to a texture format other than
13290 QRhiTexture::UnknownFormat, it may be used by the backend to decide what
13291 format to use for the storage backing the renderbuffer.
13292
13293 \note \a backingFormatHint becomes relevant typically when multisampling
13294 and floating point texture formats are involved: rendering into a
13295 multisample QRhiRenderBuffer and then resolving into a non-RGBA8
13296 QRhiTexture implies (with some graphics APIs) that the storage backing the
13297 QRhiRenderBuffer uses the matching non-RGBA8 format. That means that
13298 passing a format like QRhiTexture::RGBA32F is important, because backends
13299 will typically opt for QRhiTexture::RGBA8 by default, which would then
13300 break later on due to attempting to set up RGBA8->RGBA32F multisample
13301 resolve in the color attachment(s) of the QRhiTextureRenderTarget.
13302
13303 \sa QRhiResource::destroy()
13304 */
13305QRhiRenderBuffer *QRhi::newRenderBuffer(QRhiRenderBuffer::Type type,
13306 const QSize &pixelSize,
13307 int sampleCount,
13308 QRhiRenderBuffer::Flags flags,
13309 QRhiTexture::Format backingFormatHint)
13310{
13311 return d->createRenderBuffer(type, pixelSize, sampleCount, flags, backingFormatHint);
13312}
13313
13314/*!
13315 \return a new 1D or 2D texture with the specified \a format, \a pixelSize, \a
13316 sampleCount, and \a flags.
13317
13318 A 1D texture must have QRhiTexture::OneDimensional set in \a flags. This
13319 function will implicitly set this flag if the \a pixelSize height is 0.
13320
13321 \note \a format specifies the requested internal and external format,
13322 meaning the data to be uploaded to the texture will need to be in a
13323 compatible format, while the native texture may (but is not guaranteed to,
13324 in case of OpenGL at least) use this format internally.
13325
13326 \note 1D textures are only functional when the OneDimensionalTextures feature is
13327 reported as supported at run time. Further, mipmaps on 1D textures are only
13328 functional when the OneDimensionalTextureMipmaps feature is reported at run time.
13329
13330 \sa QRhiResource::destroy()
13331 */
13332QRhiTexture *QRhi::newTexture(QRhiTexture::Format format,
13333 const QSize &pixelSize,
13334 int sampleCount,
13335 QRhiTexture::Flags flags)
13336{
13337 if (pixelSize.height() == 0)
13338 flags |= QRhiTexture::OneDimensional;
13339
13340 return d->createTexture(format, pixelSize, 1, 0, sampleCount, flags);
13341}
13342
13343/*!
13344 \return a new 1D, 2D or 3D texture with the specified \a format, \a width, \a
13345 height, \a depth, \a sampleCount, and \a flags.
13346
13347 This overload is suitable for 3D textures because it allows specifying \a
13348 depth. A 3D texture must have QRhiTexture::ThreeDimensional set in \a
13349 flags, but using this overload that can be omitted because the flag is set
13350 implicitly whenever \a depth is greater than 0. For 1D, 2D and cube textures \a
13351 depth should be set to 0.
13352
13353 A 1D texture must have QRhiTexture::OneDimensional set in \a flags. This overload
13354 will implicitly set this flag if both \a height and \a depth are 0.
13355
13356 \note 3D textures are only functional when the ThreeDimensionalTextures
13357 feature is reported as supported at run time.
13358
13359 \note 1D textures are only functional when the OneDimensionalTextures feature is
13360 reported as supported at run time. Further, mipmaps on 1D textures are only
13361 functional when the OneDimensionalTextureMipmaps feature is reported at run time.
13362
13363 \overload
13364 */
13365QRhiTexture *QRhi::newTexture(QRhiTexture::Format format,
13366 int width, int height, int depth,
13367 int sampleCount,
13368 QRhiTexture::Flags flags)
13369{
13370 if (depth > 0)
13371 flags |= QRhiTexture::ThreeDimensional;
13372
13373 if (height == 0 && depth == 0)
13374 flags |= QRhiTexture::OneDimensional;
13375
13376 return d->createTexture(format, QSize(width, height), depth, 0, sampleCount, flags);
13377}
13378
13379/*!
13380 \return a new 1D or 2D texture array with the specified \a format, \a arraySize,
13381 \a pixelSize, \a sampleCount, and \a flags.
13382
13383 This function implicitly sets QRhiTexture::TextureArray in \a flags.
13384
13385 A 1D texture array must have QRhiTexture::OneDimensional set in \a flags. This
13386 function will implicitly set this flag if the \a pixelSize height is 0.
13387
13388 \note Do not confuse texture arrays with arrays of textures. A QRhiTexture
13389 created by this function is usable with 1D or 2D array samplers in the shader, for
13390 example: \c{layout(binding = 1) uniform sampler2DArray texArr;}. Arrays of
13391 textures refers to a list of textures that are exposed to the shader via
13392 QRhiShaderResourceBinding::sampledTextures() and a count > 1, and declared
13393 in the shader for example like this: \c{layout(binding = 1) uniform
13394 sampler2D textures[4];}
13395
13396 \note This is only functional when the TextureArrays feature is reported as
13397 supported at run time.
13398
13399 \note 1D textures are only functional when the OneDimensionalTextures feature is
13400 reported as supported at run time. Further, mipmaps on 1D textures are only
13401 functional when the OneDimensionalTextureMipmaps feature is reported at run time.
13402
13403
13404 \sa newTexture()
13405 */
13406QRhiTexture *QRhi::newTextureArray(QRhiTexture::Format format,
13407 int arraySize,
13408 const QSize &pixelSize,
13409 int sampleCount,
13410 QRhiTexture::Flags flags)
13411{
13412 flags |= QRhiTexture::TextureArray;
13413
13414 if (pixelSize.height() == 0)
13415 flags |= QRhiTexture::OneDimensional;
13416
13417 return d->createTexture(format, pixelSize, 1, arraySize, sampleCount, flags);
13418}
13419
13420/*!
13421 \return a new sampler with the specified magnification filter \a magFilter,
13422 minification filter \a minFilter, mipmapping mode \a mipmapMode, and the
13423 addressing (wrap) modes \a addressU, \a addressV, and \a addressW.
13424
13425 \note Setting \a mipmapMode to a value other than \c None implies that
13426 images for all relevant mip levels will be provided either via
13427 \l{QRhiResourceUpdateBatch::uploadTexture()}{texture uploads} or by calling
13428 \l{QRhiResourceUpdateBatch::generateMips()}{generateMips()} on the texture
13429 that is used with this sampler. Attempting to use the sampler with a
13430 texture that has no data for all relevant mip levels will lead to rendering
13431 errors, with the exact behavior dependent on the underlying graphics API.
13432
13433 \sa QRhiResource::destroy()
13434 */
13435QRhiSampler *QRhi::newSampler(QRhiSampler::Filter magFilter,
13436 QRhiSampler::Filter minFilter,
13437 QRhiSampler::Filter mipmapMode,
13438 QRhiSampler::AddressMode addressU,
13439 QRhiSampler::AddressMode addressV,
13440 QRhiSampler::AddressMode addressW)
13441{
13442 return d->createSampler(magFilter, minFilter, mipmapMode, addressU, addressV, addressW);
13443}
13444
13445/*!
13446 \return a new shading rate map object.
13447
13448 \since 6.9
13449 */
13450QRhiShadingRateMap *QRhi::newShadingRateMap()
13451{
13452 return d->createShadingRateMap();
13453}
13454
13455/*!
13456 \return a new indirect command buffer that holds commands of the specified
13457 \a type, with room for \a maxCommandCount of them.
13458
13459 \a maxCommandCount cannot be 0, otherwise create() fails. It is the upper
13460 bound for both ways of providing commands: recording them with
13461 QRhiIndirectCommandBuffer::draw() or
13462 QRhiIndirectCommandBuffer::drawIndexed(), and generating them on the GPU
13463 and calling QRhiCommandBuffer::buildIndirect(). Backends allocate their
13464 native objects, and the QRhiBuffer holding the recorded commands, based on
13465 it, which is why it is fixed up front instead of growing on demand.
13466
13467 \sa QRhiIndirectCommandBuffer::setMaxCommandCount(), QRhiIndirectCommandBuffer
13468
13469 \since 6.13
13470 */
13471QRhiIndirectCommandBuffer *QRhi::newIndirectCommandBuffer(QRhiIndirectCommandBuffer::Type type,
13472 quint32 maxCommandCount)
13473{
13474 return d->createIndirectCommandBuffer(type, maxCommandCount);
13475}
13476
13477/*!
13478 \return a new texture render target with color and depth/stencil
13479 attachments given in \a desc, and with the specified \a flags.
13480
13481 \sa QRhiResource::destroy()
13482 */
13483
13484QRhiTextureRenderTarget *QRhi::newTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc,
13485 QRhiTextureRenderTarget::Flags flags)
13486{
13487 return d->createTextureRenderTarget(desc, flags);
13488}
13489
13490/*!
13491 \return a new swapchain.
13492
13493 \sa QRhiResource::destroy(), QRhiSwapChain::createOrResize()
13494 */
13495QRhiSwapChain *QRhi::newSwapChain()
13496{
13497 return d->createSwapChain();
13498}
13499
13500/*!
13501 Starts a new frame targeting the next available buffer of \a swapChain.
13502
13503 A frame consists of resource updates and one or more render and compute
13504 passes.
13505
13506 \a flags can indicate certain special cases.
13507
13508 The high level pattern of rendering into a QWindow using a swapchain:
13509
13510 \list
13511
13512 \li Create a swapchain.
13513
13514 \li Call QRhiSwapChain::createOrResize() whenever the surface size is
13515 different than before.
13516
13517 \li Call QRhiSwapChain::destroy() on
13518 QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed.
13519
13520 \li Then on every frame:
13521 \badcode
13522 beginFrame(sc);
13523 updates = nextResourceUpdateBatch();
13524 updates->...
13525 QRhiCommandBuffer *cb = sc->currentFrameCommandBuffer();
13526 cb->beginPass(sc->currentFrameRenderTarget(), colorClear, dsClear, updates);
13527 ...
13528 cb->endPass();
13529 ... // more passes as necessary
13530 endFrame(sc);
13531 \endcode
13532
13533 \endlist
13534
13535 \return QRhi::FrameOpSuccess on success, or another QRhi::FrameOpResult
13536 value on failure. Some of these should be treated as soft, "try again
13537 later" type of errors: When QRhi::FrameOpSwapChainOutOfDate is returned,
13538 the swapchain is to be resized or updated by calling
13539 QRhiSwapChain::createOrResize(). The application should then attempt to
13540 generate a new frame. QRhi::FrameOpDeviceLost means the graphics device is
13541 lost but this may also be recoverable by releasing all resources, including
13542 the QRhi itself, and then recreating all resources. See isDeviceLost() for
13543 further discussion.
13544
13545 \sa endFrame(), beginOffscreenFrame(), isDeviceLost()
13546 */
13547QRhi::FrameOpResult QRhi::beginFrame(QRhiSwapChain *swapChain, BeginFrameFlags flags)
13548{
13549 if (d->inFrame)
13550 qWarning("Attempted to call beginFrame() within a still active frame; ignored");
13551
13552 qCDebug(QRHI_LOG_RUB) << "[rub] new frame";
13553
13554 QRhi::FrameOpResult r = !d->inFrame ? d->beginFrame(swapChain, flags) : FrameOpSuccess;
13555 if (r == FrameOpSuccess)
13556 d->inFrame = true;
13557
13558 return r;
13559}
13560
13561/*!
13562 Ends, commits, and presents a frame that was started in the last
13563 beginFrame() on \a swapChain.
13564
13565 Double (or triple) buffering is managed internally by the QRhiSwapChain and
13566 QRhi.
13567
13568 \a flags can optionally be used to change the behavior in certain ways.
13569 Passing QRhi::SkipPresent skips queuing the Present command or calling
13570 swapBuffers.
13571
13572 \return QRhi::FrameOpSuccess on success, or another QRhi::FrameOpResult
13573 value on failure. Some of these should be treated as soft, "try again
13574 later" type of errors: When QRhi::FrameOpSwapChainOutOfDate is returned,
13575 the swapchain is to be resized or updated by calling
13576 QRhiSwapChain::createOrResize(). The application should then attempt to
13577 generate a new frame. QRhi::FrameOpDeviceLost means the graphics device is
13578 lost but this may also be recoverable by releasing all resources, including
13579 the QRhi itself, and then recreating all resources. See isDeviceLost() for
13580 further discussion.
13581
13582 \sa beginFrame(), isDeviceLost()
13583 */
13584QRhi::FrameOpResult QRhi::endFrame(QRhiSwapChain *swapChain, EndFrameFlags flags)
13585{
13586 const bool wasInFrame = d->inFrame;
13587 if (!wasInFrame)
13588 qWarning("Attempted to call endFrame() without an active frame; ignored");
13589
13590 QRhi::FrameOpResult r = wasInFrame ? d->endFrame(swapChain, flags) : FrameOpSuccess;
13591 d->inFrame = false;
13592 // deleteLater is a high level QRhi concept the backends know
13593 // nothing about - handle it here.
13594 qDeleteAll(d->pendingDeleteResources);
13595 d->pendingDeleteResources.clear();
13596
13597 if (wasInFrame && qrhiDebugHooks.frameEnd) {
13598 QRhiCommandBuffer *cb = (r == FrameOpSuccess && swapChain)
13599 ? swapChain->currentFrameCommandBuffer() : nullptr;
13600 qrhiDebugHooks.frameEnd(d, swapChain, cb);
13601 }
13602
13603 return r;
13604}
13605
13606/*!
13607 \return true when there is an active frame, meaning there was a
13608 beginFrame() (or beginOffscreenFrame()) with no corresponding endFrame()
13609 (or endOffscreenFrame()) yet.
13610
13611 \sa currentFrameSlot(), beginFrame(), endFrame()
13612 */
13613bool QRhi::isRecordingFrame() const
13614{
13615 return d->inFrame;
13616}
13617
13618/*!
13619 \return the current frame slot index while recording a frame. Unspecified
13620 when called outside an active frame (that is, when isRecordingFrame() is \c
13621 false).
13622
13623 With backends like Vulkan or Metal, it is the responsibility of the QRhi
13624 backend to block whenever starting a new frame and finding the CPU is
13625 already \c{FramesInFlight - 1} frames ahead of the GPU (because the command
13626 buffer submitted in frame no. \c{current} - \c{FramesInFlight} has not yet
13627 completed).
13628
13629 Resources that tend to change between frames (such as, the native buffer
13630 object backing a QRhiBuffer with type QRhiBuffer::Dynamic) exist in
13631 multiple versions, so that each frame, that can be submitted while a
13632 previous one is still being processed, works with its own copy, thus
13633 avoiding the need to stall the pipeline when preparing the frame. (The
13634 contents of a resource that may still be in use in the GPU should not be
13635 touched, but simply always waiting for the previous frame to finish would
13636 reduce GPU utilization and ultimately, performance and efficiency.)
13637
13638 Conceptually this is somewhat similar to copy-on-write schemes used by some
13639 C++ containers and other types. It may also be similar to what an OpenGL or
13640 Direct 3D 11 implementation performs internally for certain type of objects.
13641
13642 In practice, such double (or triple) buffering resources is realized in
13643 the Vulkan, Metal, and similar QRhi backends by having a fixed number of
13644 native resource (such as, VkBuffer) \c slots behind a QRhiResource. That
13645 can then be indexed by a frame slot index running 0, 1, ..,
13646 FramesInFlight-1, and then wrapping around.
13647
13648 All this is managed transparently to the users of QRhi. However,
13649 applications that integrate rendering done directly with the graphics API
13650 may want to perform a similar double or triple buffering of their own
13651 graphics resources. That is then most easily achieved by knowing the values
13652 of the maximum number of in-flight frames (retrievable via resourceLimit())
13653 and the current frame (slot) index (returned by this function).
13654
13655 \sa isRecordingFrame(), beginFrame(), endFrame()
13656 */
13657int QRhi::currentFrameSlot() const
13658{
13659 return d->currentFrameSlot;
13660}
13661
13662/*!
13663 Starts a new offscreen frame. Provides a command buffer suitable for
13664 recording rendering commands in \a cb. \a flags is used to indicate
13665 certain special cases, just like with beginFrame().
13666
13667 \note The QRhiCommandBuffer stored to *cb is not owned by the caller.
13668
13669 Rendering without a swapchain is possible as well. The typical use case is
13670 to use it in completely offscreen applications, e.g. to generate image
13671 sequences by rendering and reading back without ever showing a window.
13672
13673 Usage in on-screen applications (so beginFrame, endFrame,
13674 beginOffscreenFrame, endOffscreenFrame, beginFrame, ...) is possible too.
13675
13676 When a \l{QRhiResourceUpdateBatch::readBackTexture()}{texture} or
13677 \l{QRhiResourceUpdateBatch::readBackBuffer()}{buffer} readback was
13678 scheduled, offscreen frames do not let the CPU potentially generate another
13679 frame while the GPU is still processing the previous one. This has the side
13680 effect that if readbacks are scheduled, the results are guaranteed to be
13681 available once endOffscreenFrame() returns. That is not the case with frames
13682 targeting a swapchain: there the GPU is potentially better utilized, but
13683 working with readback operations needs more care from the application
13684 because endFrame(), unlike endOffscreenFrame(), does not guarantee that the
13685 results from the readback are available at that point.
13686
13687 The skeleton of rendering a frame without a swapchain and then reading the
13688 frame contents back could look like the following:
13689
13690 \code
13691 QRhiReadbackResult rbResult;
13692 QRhiCommandBuffer *cb;
13693 rhi->beginOffscreenFrame(&cb);
13694 cb->beginPass(rt, colorClear, dsClear);
13695 // ...
13696 u = nextResourceUpdateBatch();
13697 u->readBackTexture(rb, &rbResult);
13698 cb->endPass(u);
13699 rhi->endOffscreenFrame();
13700 // image data available in rbResult
13701 \endcode
13702
13703 \sa endOffscreenFrame(), beginFrame()
13704 */
13705QRhi::FrameOpResult QRhi::beginOffscreenFrame(QRhiCommandBuffer **cb, BeginFrameFlags flags)
13706{
13707 const bool wasInFrame = d->inFrame;
13708 if (wasInFrame)
13709 qWarning("Attempted to call beginOffscreenFrame() within a still active frame; ignored");
13710
13711 qCDebug(QRHI_LOG_RUB) << "[rub] new offscreen frame";
13712
13713 QRhi::FrameOpResult r = !wasInFrame ? d->beginOffscreenFrame(cb, flags) : FrameOpSuccess;
13714 if (r == FrameOpSuccess) {
13715 d->inFrame = true;
13716 if (!wasInFrame)
13717 d->currentOffscreenCb = *cb;
13718 }
13719
13720 return r;
13721}
13722
13723/*!
13724 Ends, submits, and potentially waits for the offscreen frame.
13725
13726 Unlike endFrame(), this function will block and wait for completion of the
13727 GPU-side work when there are active buffer or texture readbacks.
13728
13729 \a flags is not currently used.
13730
13731 \sa beginOffscreenFrame()
13732 */
13733QRhi::FrameOpResult QRhi::endOffscreenFrame(EndFrameFlags flags)
13734{
13735 const bool wasInFrame = d->inFrame;
13736 if (!wasInFrame)
13737 qWarning("Attempted to call endOffscreenFrame() without an active frame; ignored");
13738
13739 QRhi::FrameOpResult r = wasInFrame ? d->endOffscreenFrame(flags) : FrameOpSuccess;
13740 d->inFrame = false;
13741 qDeleteAll(d->pendingDeleteResources);
13742 d->pendingDeleteResources.clear();
13743
13744 if (wasInFrame && qrhiDebugHooks.frameEnd) {
13745 QRhiCommandBuffer *cb = r == FrameOpSuccess ? d->currentOffscreenCb : nullptr;
13746 qrhiDebugHooks.frameEnd(d, nullptr, cb);
13747 }
13748 d->currentOffscreenCb = nullptr;
13749
13750 return r;
13751}
13752
13753/*!
13754 Waits for any work on the graphics queue (where applicable) to complete,
13755 then executes all deferred operations, like completing readbacks and
13756 resource releases. Can be called inside and outside of a frame, but not
13757 inside a pass. Inside a frame it implies submitting any work on the
13758 command buffer.
13759
13760 \note Avoid this function. One case where it may be needed is when the
13761 results of an enqueued readback in a swapchain-based frame are needed at a
13762 fixed given point and so waiting for the results is desired.
13763 */
13764QRhi::FrameOpResult QRhi::finish()
13765{
13766 return d->finish();
13767}
13768
13769/*!
13770 \return the list of supported sample counts.
13771
13772 A typical example would be (1, 2, 4, 8).
13773
13774 With some backend this list of supported values is fixed in advance, while
13775 with some others the (physical) device properties indicate what is
13776 supported at run time.
13777
13778 \sa QRhiRenderBuffer::setSampleCount(), QRhiTexture::setSampleCount(),
13779 QRhiGraphicsPipeline::setSampleCount(), QRhiSwapChain::setSampleCount()
13780 */
13781QList<int> QRhi::supportedSampleCounts() const
13782{
13783 return d->supportedSampleCounts();
13784}
13785
13786/*!
13787 \return the minimum uniform buffer offset alignment in bytes. This is
13788 typically 256.
13789
13790 Attempting to bind a uniform buffer region with an offset not aligned to
13791 this value will lead to failures depending on the backend and the
13792 underlying graphics API.
13793
13794 \sa ubufAligned()
13795 */
13796int QRhi::ubufAlignment() const
13797{
13798 return d->ubufAlignment();
13799}
13800
13801/*!
13802 \return The list of supported variable shading rates for the specified \a sampleCount.
13803
13804 1x1 is always supported.
13805
13806 \since 6.9
13807 */
13808QList<QSize> QRhi::supportedShadingRates(int sampleCount) const
13809{
13810 return d->supportedShadingRates(sampleCount);
13811}
13812
13813Q_CONSTINIT static QBasicAtomicInteger<QRhiGlobalObjectIdGenerator::Type> counter = Q_BASIC_ATOMIC_INITIALIZER(0);
13814
13815QRhiGlobalObjectIdGenerator::Type QRhiGlobalObjectIdGenerator::newId()
13816{
13817 return counter.fetchAndAddRelaxed(1) + 1;
13818}
13819
13821{
13822 return m_buffers.isEmpty() && m_textures.isEmpty();
13823}
13824
13826{
13827 m_buffers.clear();
13828 m_textures.clear();
13829}
13830
13836
13837void QRhiPassResourceTracker::registerBuffer(QRhiBuffer *buf, int slot, BufferAccess *access, BufferStage *stage,
13838 const UsageState &state)
13839{
13840 auto it = m_buffers.find(buf);
13841 if (it != m_buffers.end()) {
13842 Buffer &b = it->second;
13843 if (Q_UNLIKELY(b.access != *access)) {
13844 const QByteArray name = buf->name();
13845 qWarning("Buffer %p (%s) used with different accesses within the same pass, this is not allowed.",
13846 buf, name.constData());
13847 return;
13848 }
13849 if (b.stage != *stage) {
13850 b.stage = earlierStage(b.stage, *stage);
13851 *stage = b.stage;
13852 }
13853 return;
13854 }
13855
13856 Buffer b;
13857 b.slot = slot;
13858 b.access = *access;
13859 b.stage = *stage;
13860 b.stateAtPassBegin = state; // first use -> initial state
13861 m_buffers.append(buf, b);
13862}
13863
13869
13876
13878 const UsageState &state)
13879{
13880 auto it = m_textures.find(tex);
13881 if (it != m_textures.end()) {
13882 Texture &t = it->second;
13883 if (t.access != *access) {
13884 // Different subresources of a texture may be used for both load
13885 // and store in the same pass. (think reading from one mip level
13886 // and writing to another one in a compute shader) This we can
13887 // handle by treating the entire resource as read-write.
13888 if (Q_LIKELY(isImageLoadStore(t.access) && isImageLoadStore(*access))) {
13890 *access = t.access;
13891 } else {
13892 const QByteArray name = tex->name();
13893 qWarning("Texture %p (%s) used with different accesses within the same pass, this is not allowed.",
13894 tex, name.constData());
13895 }
13896 }
13897 if (t.stage != *stage) {
13898 t.stage = earlierStage(t.stage, *stage);
13899 *stage = t.stage;
13900 }
13901 return;
13902 }
13903
13904 Texture t;
13905 t.access = *access;
13906 t.stage = *stage;
13907 t.stateAtPassBegin = state; // first use -> initial state
13908 m_textures.append(tex, t);
13909}
13910
13911QRhiPassResourceTracker::BufferStage QRhiPassResourceTracker::toPassTrackerBufferStage(QRhiShaderResourceBinding::StageFlags stages)
13912{
13913 // pick the earlier stage (as this is going to be dstAccessMask)
13914 if (stages.testFlag(QRhiShaderResourceBinding::VertexStage))
13916 if (stages.testFlag(QRhiShaderResourceBinding::TessellationControlStage))
13918 if (stages.testFlag(QRhiShaderResourceBinding::TessellationEvaluationStage))
13920 if (stages.testFlag(QRhiShaderResourceBinding::FragmentStage))
13922 if (stages.testFlag(QRhiShaderResourceBinding::ComputeStage))
13924 if (stages.testFlag(QRhiShaderResourceBinding::GeometryStage))
13926
13927 Q_UNREACHABLE_RETURN(QRhiPassResourceTracker::BufVertexStage);
13928}
13929
13930QRhiPassResourceTracker::TextureStage QRhiPassResourceTracker::toPassTrackerTextureStage(QRhiShaderResourceBinding::StageFlags stages)
13931{
13932 // pick the earlier stage (as this is going to be dstAccessMask)
13933 if (stages.testFlag(QRhiShaderResourceBinding::VertexStage))
13935 if (stages.testFlag(QRhiShaderResourceBinding::TessellationControlStage))
13937 if (stages.testFlag(QRhiShaderResourceBinding::TessellationEvaluationStage))
13939 if (stages.testFlag(QRhiShaderResourceBinding::FragmentStage))
13941 if (stages.testFlag(QRhiShaderResourceBinding::ComputeStage))
13943 if (stages.testFlag(QRhiShaderResourceBinding::GeometryStage))
13945
13946 Q_UNREACHABLE_RETURN(QRhiPassResourceTracker::TexVertexStage);
13947}
13948
13949QSize QRhiImplementation::clampedSubResourceUploadSize(QSize size, QPoint dstPos, int level, QSize textureSizeAtLevelZero, bool warn)
13950{
13951 const QSize subResSize = q->sizeForMipLevel(level, textureSizeAtLevelZero);
13952 const bool outOfBoundsHoriz = dstPos.x() + size.width() > subResSize.width();
13953 const bool outOfBoundsVert = dstPos.y() + size.height() > subResSize.height();
13954 if (Q_UNLIKELY(outOfBoundsHoriz || outOfBoundsVert)) {
13955 if (warn) {
13956 qWarning("Invalid texture upload issued; size %dx%d dst.position %d,%d dst.subresource size %dx%d; size will be clamped",
13957 size.width(), size.height(), dstPos.x(), dstPos.y(), subResSize.width(), subResSize.height());
13958 }
13959 if (outOfBoundsHoriz)
13960 size.setWidth(subResSize.width() - dstPos.x());
13961 if (outOfBoundsVert)
13962 size.setHeight(subResSize.height() - dstPos.y());
13963 }
13964 return size;
13965}
13966
13967// Clamps size so that reading the image with a source row stride of bpl does
13968// not go past dataSize bytes. bpl may be 0, meaning the data is tightly packed.
13969// Returns a size with a height of 0 when not even a single row can be
13970// satisfied, in which case the caller is expected to skip the copy.
13971QSize QRhiImplementation::clampedSubResourceUploadSizeForSourceData(QSize size, quint32 bpl,
13972 quint32 bytesPerPixel,
13973 qsizetype dataSize, bool warn)
13974{
13975 if (size.isEmpty() || !bytesPerPixel)
13976 return size;
13977
13978 const quint64 rowBytes = quint64(bytesPerPixel) * quint64(size.width());
13979 if (!bpl)
13980 bpl = quint32(qMin(rowBytes, quint64(std::numeric_limits<quint32>::max())));
13981
13982 if (quint64(bpl) < rowBytes) {
13983 if (warn) {
13984 qWarning("Invalid texture upload issued; source row stride %u is smaller than the %llu "
13985 "bytes a row of %d pixels needs; upload will be skipped",
13986 bpl, rowBytes, size.width());
13987 }
13988 return QSize(size.width(), 0);
13989 }
13990
13991 // Row y is read from y * bpl and needs rowBytes bytes, so the last row ends
13992 // at (height - 1) * bpl + rowBytes.
13993 const quint64 needed = quint64(bpl) * quint64(size.height() - 1) + rowBytes;
13994 if (quint64(dataSize) >= needed)
13995 return size;
13996
13997 int rows = 0;
13998 if (quint64(dataSize) >= rowBytes)
13999 rows = int((quint64(dataSize) - rowBytes) / quint64(bpl)) + 1;
14000
14001 if (warn) {
14002 qWarning("Invalid texture upload issued; %lld bytes of data cannot back a %dx%d upload with "
14003 "source row stride %u (needs %llu bytes); height will be clamped to %d",
14004 qint64(dataSize), size.width(), size.height(), bpl, needed, rows);
14005 }
14006
14007 return QSize(size.width(), rows);
14008}
14009
14010// The compressed counterpart of clampedSubResourceUploadSizeForSourceData().
14011// Clamps to whole rows of blocks; a height of 0 means not even one row can be
14012// satisfied and the caller is expected to skip the copy.
14013QSize QRhiImplementation::clampedCompressedSubResourceUploadSizeForSourceData(QRhiTexture::Format format,
14014 QSize size,
14015 qsizetype dataSize,
14016 bool warn)
14017{
14018 if (size.isEmpty())
14019 return size;
14020
14021 quint32 bpl = 0;
14022 quint32 byteSize = 0;
14023 QSize blockDim;
14024 if (!compressedFormatInfo(format, size, &bpl, &byteSize, &blockDim) || !bpl)
14025 return size;
14026
14027 if (quint64(dataSize) >= byteSize)
14028 return size;
14029
14030 // Each row of blocks needs bpl bytes and covers blockDim.height() pixels.
14031 const quint32 blockRows = quint32(quint64(dataSize) / quint64(bpl));
14032 const int height = qMin(size.height(), int(blockRows * quint32(blockDim.height())));
14033
14034 if (warn) {
14035 qWarning("Invalid compressed texture upload issued; %lld bytes of data cannot back a "
14036 "%dx%d upload (needs %u bytes); height will be clamped to %d",
14037 qint64(dataSize), size.width(), size.height(), byteSize, height);
14038 }
14039
14040 return QSize(size.width(), height);
14041}
14042
14043QT_END_NAMESPACE
friend bool operator==(const QByteArray::FromBase64Result &lhs, const QByteArray::FromBase64Result &rhs) noexcept
Returns true if lhs and rhs are equal, otherwise returns false.
Definition qbytearray.h:834
friend bool operator!=(const QByteArray::FromBase64Result &lhs, const QByteArray::FromBase64Result &rhs) noexcept
Returns true if lhs and rhs are different, otherwise returns false.
Definition qbytearray.h:845
void execute(QRhiCommandBuffer *cb, quint32 firstCommand, quint32 commandCount)
Definition qrhi.cpp:9449
QRhiBufferBackedIndirectCommandBuffer(QRhiImplementation *rhi, Type type, quint32 maxCommandCount)
\variable QRhiIndirectCommandBufferBuildInfo::topology
Definition qrhi.cpp:9359
void enqueueUpload(QRhiResourceUpdateBatch *u)
Definition qrhi.cpp:9413
void build(const QRhiIndirectCommandBufferBuildInfo &info)
Definition qrhi.cpp:9436
void destroy() override
Releases (or requests deferred releasing of) the underlying native graphics resources.
Definition qrhi.cpp:9371
bool create() override
Creates the corresponding native objects.
Definition qrhi.cpp:9394
bool isEmpty() const
Definition qrhi.cpp:13820
void registerBuffer(QRhiBuffer *buf, int slot, BufferAccess *access, BufferStage *stage, const UsageState &state)
Definition qrhi.cpp:13837
void registerTexture(QRhiTexture *tex, TextureAccess *access, TextureStage *stage, const UsageState &state)
Definition qrhi.cpp:13877
QRhiImplementation * rhi
Definition qrhi_p.h:748
static const int BUFFER_OPS_STATIC_ALLOC
Definition qrhi_p.h:740
void merge(QRhiResourceUpdateBatchPrivate *other)
Definition qrhi.cpp:11559
QRhiResourceUpdateBatch * q
Definition qrhi_p.h:747
static const int TEXTURE_OPS_STATIC_ALLOC
Definition qrhi_p.h:744
QDebug operator<<(QDebug dbg, const QFileInfo &fi)
static const char * resourceTypeStr(const QRhiResource *res)
Definition qrhi.cpp:9610
static QRhiPassResourceTracker::BufferStage earlierStage(QRhiPassResourceTracker::BufferStage a, QRhiPassResourceTracker::BufferStage b)
Definition qrhi.cpp:13831
QDebug operator<<(QDebug dbg, const QRhiSwapChainHdrInfo &info)
Definition qrhi.cpp:8656
static bool isImageLoadStore(QRhiPassResourceTracker::TextureAccess access)
Definition qrhi.cpp:13870
static const char * deviceTypeStr(QRhiDriverInfo::DeviceType type)
\variable QRhiDriverInfo::deviceName
Definition qrhi.cpp:10613
static auto & emplaceData(QRhiShaderResourceBinding::Data &d)
Definition qrhi.cpp:6321
static QRhiPassResourceTracker::TextureStage earlierStage(QRhiPassResourceTracker::TextureStage a, QRhiPassResourceTracker::TextureStage b)
Definition qrhi.cpp:13864
constexpr size_t qHash(const QSize &s, size_t seed=0) noexcept
Definition qsize.h:192
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:1616
LimitsType limitsType
Definition qrhi.h:1627
LuminanceBehavior luminanceBehavior
Definition qrhi.h:1638