qrhi.cpp 88.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt RHI module
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qrhi_p.h"
#include <qmath.h>

Laszlo Agocs's avatar
Laszlo Agocs committed
40
#include "qrhinull_p.h"
41
#ifndef QT_NO_OPENGL
42
#include "qrhigles2_p.h"
43
#endif
44 45 46 47 48 49 50 51 52 53 54 55
#if QT_CONFIG(vulkan)
#include "qrhivulkan_p.h"
#endif
#ifdef Q_OS_WIN
#include "qrhid3d11_p.h"
#endif
#ifdef Q_OS_DARWIN
#include "qrhimetal_p.h"
#endif

QT_BEGIN_NAMESPACE

Laszlo Agocs's avatar
Laszlo Agocs committed
56 57 58
/*!
    \class QRhi
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
59 60

    \brief Accelerated 2D/3D graphics API abstraction.
Laszlo Agocs's avatar
Laszlo Agocs committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152

     QRhi is an abstraction for hardware accelerated graphics APIs, such as,
     \l{https://www.khronos.org/opengl/}{OpenGL},
     \l{https://www.khronos.org/opengles/}{OpenGL ES},
     \l{https://docs.microsoft.com/en-us/windows/desktop/direct3d}{Direct3D},
     \l{https://developer.apple.com/metal/}{Metal}, and
     \l{https://www.khronos.org/vulkan/}{Vulkan}.

    Each QRhi instance is backed by a backend for a specific graphics API. The
    selection of the backend is a run time choice and is up to the application
    or library that creates the QRhi instance. Some backends are available on
    multiple platforms (OpenGL, Vulkan, Null), while APIs specific to a given
    platform are only available when running on the platform in question (Metal
    on macOS/iOS/tvOS, Direct3D on Windows).

    \section2 Design Fundamentals

    A QRhi cannot be instantiated directly. Instead, use the create()
    function. Delete the QRhi instance normally to release the graphics device.

    \section3 Resources

    Instances of classes deriving from QRhiResource, such as, QRhiBuffer,
    QRhiTexture, etc., encapsulate zero, one, or more native graphics
    resources. Instances of such classes are always created via the \c new
    functions of the QRhi, such as, newBuffer(), newTexture(),
    newTextureRenderTarget(), newSwapChain().

    \list

    \li The returned value from both create() and functions like newBuffer() is
    owned by the caller.

    \li Unlike QRhi, subclasses of QRhiResource should not be destroyed
    directly via delete without calling QRhiResource::release(). The typical
    approach is to call QRhiResource::releaseAndDestroy(). This is equivalent
    to QRhiResource::release() followed by \c delete.

    \li Just creating a QRhiResource subclass never allocates or initalizes any
    native resources. That is only done when calling the \c build function of a
    subclass, for example, QRhiBuffer::build() or QRhiTexture::build().

    \li The exception is
    QRhiTextureRenderTarget::newCompatibleRenderPassDescriptor() and
    QRhiSwapChain::newCompatibleRenderPassDescriptor(). There is no \c build
    operation for these and the returned object is immediately active.

    \li The resource objects themselves are treated as immutable: once a
    resource is built, changing any parameters via the setters, such as,
    QRhiTexture::setPixelSize(), has no effect, unless the underlying native
    resource is released and \c build is called again. See more about resource
    reuse in the sections below.

    \li The underlying native resources are scheduled for releasing by calling
    QRhiResource::release(). Backends often queue release requests and defer
    executing them to an unspecified time, this is hidden from the
    applications. This way applications do not have to worry about releasing a
    native resource that may still be in use by an in flight frame.

    \endlist

    \badcode
        vbuf = rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(vertexData));
        if (!vbuf->build()) { error }
        ...
        vbuf->releaseAndDestroy();
    \endcode

    \section3 Resource reuse

    From the user's point of view the QRhiResource is reusable immediately
    after calling QRhiResource::release(). With the exception of swapchains,
    calling \c build on an already built object does an implicit release. This
    provides a handy shortcut to reuse a QRhiResource instance with different
    parameters, with a new native graphics resource underneath.

    The importance of reusing the same object lies in the fact that some
    objects reference other objects: for example, a QRhiShaderResourceBindings
    can reference QRhiBuffer, QRhiTexture, and QRhiSampler instances. If now
    one of these buffers need to be resized or a sampler parameter needs
    changing, destroying and creating a whole new QRhiBuffer or QRhiSampler
    would invalidate all references to the old instance. By just changing the
    appropriate parameters via QRhiBuffer::setSize() or similar and then
    calling QRhiBuffer::build(), everything works as expected and there is no
    need to touch the QRhiShaderResourceBindings at all, even though there is a
    good chance that under the hood the QRhiBuffer is now backed by a whole new
    native buffer.

    \badcode
        ubuf = rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, 256);
        ubuf->build();

153
        srb = rhi->newShaderResourceBindings()
Laszlo Agocs's avatar
Laszlo Agocs committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
        srb->setBindings({
            QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, ubuf)
        });
        srb->build();

        ...

        // now suddenly we need buffer with a different size
        ubuf->setSize(512);
        ubuf->build(); // same as ubuf->release(); ubuf->build();

        // that's it, srb needs no changes whatsoever
    \endcode

    \section3 Pooled objects

    There are pooled objects too, like QRhiResourceUpdateBatch. An instance is
    retrieved via a \c next function, such as, nextResourceUpdateBatch(). The
    caller does not own the returned instance in this case. The only valid way
    of operating here is calling functions on the QRhiResourceUpdateBatch and
    then passing it to QRhiCommandBuffer::beginPass() or
    QRhiCommandBuffer::endPass(). These functions take care of returning the
    batch to the pool. Alternatively, a batch can be "canceled" and returned to
    the pool without processing by calling QRhiResourceUpdateBatch::release().

    A typical pattern is thus:

    \badcode
        QRhiResourceUpdateBatch *resUpdates = rhi->nextResourceUpdateBatch();
        ...
        resUpdates->updateDynamicBuffer(ubuf, 0, 64, mvp.constData());
        if (!image.isNull()) {
            resUpdates->uploadTexture(texture, image);
            image = QImage();
        }
        ...
        QRhiCommandBuffer *cb = m_sc->currentFrameCommandBuffer();
        cb->beginPass(swapchain->currentFrameRenderTarget(), clearCol, clearDs, resUpdates);
    \endcode

    \section3 Swapchain specifics

    QRhiSwapChain features some special semantics due to the peculiar nature of
    swapchains.

    \list

    \li It has no \c build but rather a QRhiSwapChain::buildOrResize().
    Repeatedly calling this function is \b not the same as calling
    QRhiSwapChain::release() followed by QRhiSwapChain::buildOrResize(). This
    is because swapchains often have ways to handle the case where buffers need
    to be resized in a manner that is more efficient than a brute force
    destroying and recreating from scratch.

    \li An active QRhiSwapChain must be released by calling
    QRhiSwapChain::release() whenever the targeted QWindow sends the
    QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed event. It should not be
    postponed since releasing the swapchain may become problematic when the
    native window is not around anymore (e.g. because the QPlatformWindow got
    destroyed already when getting a QWindow::close())

    \endlist

    \section3 Ownership

    The general rule is no ownership transfer. Creating a QRhi with an already
    existing graphics device does not mean the QRhi takes ownership of the
    device object. Similarly, ownership is not given away when a device or
    texture object is "exported" via QRhi::nativeHandles() or
    QRhiTexture::nativeHandles(). Most importantly, passing pointers in structs
    and via setters does not transfer ownership.

    \sa {Qt Shader Tools}
Laszlo Agocs's avatar
Laszlo Agocs committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
 */

/*!
    \enum QRhi::Implementation
    Describes which graphics API-specific backend gets used by a QRhi instance.

    \value Null
    \value Vulkan
    \value OpenGLES2
    \value D3D11
    \value Metal
 */

/*!
    \enum QRhi::Flag
    Describes what special features to enable.

    \value EnableProfiling Enables gathering timing (CPU, GPU) and resource
    (QRhiBuffer, QRhiTexture, etc.) information and additional metadata. See
    QRhiProfiler. Avoid enabling in production builds as it may involve a
    performance penalty.

    \value EnableDebugMarkers Enables debug marker groups. Without this frame
    debugging features like making debug groups and custom resource name
    visible in external GPU debugging tools will not be available and functions
    like QRhiCommandBuffer::debugMarkBegin() will become a no-op. Avoid
    enabling in production builds as it may involve a performance penalty.
 */

/*!
    \enum QRhi::FrameOpResult
    Describes the result of operations that can have a soft failure.

    \value FrameOpSuccess Success

    \value FrameOpError Unspecified error

    \value FrameOpSwapChainOutOfDate The swapchain is in an inconsistent state
    internally. This can be recoverable by attempting to repeat the operation
    (such as, beginFrame()) later.

    \value FrameOpDeviceLost The graphics device was lost. This can be
    recoverable by attempting to repeat the operation (such as, beginFrame())
    and releasing and reinitializing all objects backed by native graphics
    resources.
 */

/*!
    \enum QRhi::Feature
    Flag values to indicate what features are supported by the backend currently in use.

    \value MultisampleTexture Textures with sample count larger than 1 are supported.
    \value MultisampleRenderBuffer Renderbuffers with sample count larger than 1 are supported.
    \value DebugMarkers Debug marker groups (and so QRhiCommandBuffer::debugMarkBegin()) are supported.
    \value Timestamps Command buffer timestamps are supported. Relevant for QRhiProfiler::gpuFrameTimes().
    \value Instancing Instanced drawing is supported.
    \value CustomInstanceStepRate Instance step rate other than 1 is supported.
 */

/*!
    \enum QRhi::ResourceSizeLimit
    Describes the resource limit to query.

    \value TextureSizeMin Minimum texture width and height. This is typically
    1. The minimum texture size is handled gracefully, meaning attempting to
    create a texture with an empty size will instead create a texture with the
    minimum size.

    \value TextureSizeMax Maximum texture width and height. This depends on the
    graphics API and sometimes the platform or implementation as well.
    Typically the value is in the range 4096 - 16384. Attempting to create
    textures larger than this is expected to fail.
Laszlo Agocs's avatar
Laszlo Agocs committed
299 300 301 302 303
 */

/*!
    \class QRhiInitParams
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
304
    \brief Base class for backend-specific initialization parameters.
Laszlo Agocs's avatar
Laszlo Agocs committed
305 306 307 308 309
 */

/*!
    \class QRhiColorClearValue
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
310
    \brief Specifies a clear color for a color buffer.
Laszlo Agocs's avatar
Laszlo Agocs committed
311 312 313 314 315
 */

/*!
    \class QRhiDepthStencilClearValue
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
316
    \brief Specifies clear values for a depth or stencil buffer.
Laszlo Agocs's avatar
Laszlo Agocs committed
317 318 319 320 321
 */

/*!
    \class QRhiViewport
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
322
    \brief Specifies a viewport rectangle.
Laszlo Agocs's avatar
Laszlo Agocs committed
323 324 325 326 327
 */

/*!
    \class QRhiScissor
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
328
    \brief Specifies a scissor rectangle.
Laszlo Agocs's avatar
Laszlo Agocs committed
329 330 331 332 333
 */

/*!
    \class QRhiVertexInputLayout
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
334
    \brief Describes the layout of vertex inputs consumed by a vertex shader.
Laszlo Agocs's avatar
Laszlo Agocs committed
335 336 337 338 339
 */

/*!
    \class QRhiVertexInputLayout::Binding
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
340
    \brief Describes a vertex input binding.
Laszlo Agocs's avatar
Laszlo Agocs committed
341 342
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
343 344 345 346 347 348 349 350
/*!
    \enum QRhiVertexInputLayout::Binding::Classification
    Describes the input data classification.

    \value PerVertex Data is per-vertex
    \value PerInstance Data is per-instance
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
351 352 353
/*!
    \class QRhiVertexInputLayout::Attribute
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
354
    \brief Describes a single vertex input element.
Laszlo Agocs's avatar
Laszlo Agocs committed
355 356
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
357 358 359 360 361 362 363 364 365 366 367 368 369
/*!
    \enum QRhiVertexInputLayout::Attribute::Format
    Specifies the type of the element data.

    \value Float4 Four component float vector
    \value Float3 Three component float vector
    \value Float2 Two component float vector
    \value Float Float
    \value UNormByte4 Four component normalized unsigned byte vector
    \value UNormByte2 Two component normalized unsigned byte vector
    \value UNormByte Normalized unsigned byte
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
370 371 372
/*!
    \class QRhiGraphicsShaderStage
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
373
    \brief Specifies the type and the shader code for a shader stage in the graphics pipeline.
Laszlo Agocs's avatar
Laszlo Agocs committed
374 375
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
376 377 378 379 380 381 382 383 384 385
/*!
    \enum QRhiGraphicsShaderStage::Type
    Specifies the type of the shader stage.

    \value Vertex Vertex stage
    \value Fragment Fragment (pixel) stage
    \value TessellationControl Tessellation control (hull) stage
    \value TessellationEvaluation Tessellation evaluation (domain) stage
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
386 387 388
/*!
    \class QRhiShaderResourceBinding
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
389
    \brief Specifies the shader resources that are made visible to one or more shader stages.
Laszlo Agocs's avatar
Laszlo Agocs committed
390 391
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
/*!
    \enum QRhiShaderResourceBinding::Type
    Specifies type of the shader resource bound to a binding point

    \value UniformBuffer Uniform buffer
    \value SampledTexture Combined image sampler
 */

/*!
    \enum QRhiShaderResourceBinding::StageFlag
    Flag values to indicate which stages the shader resource is visible in

    \value VertexStage Vertex stage
    \value FragmentStage Fragment (pixel) stage
    \value TessellationControlStage Tessellation control (hull) stage
    \value TessellationEvaluationStage Tessellation evaluation (domain) stage
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
410 411 412
/*!
    \class QRhiTextureRenderTargetDescription
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
413
    \brief Describes the color and depth or depth/stencil attachments of a render target.
Laszlo Agocs's avatar
Laszlo Agocs committed
414 415 416 417 418
 */

/*!
    \class QRhiTextureRenderTargetDescription::ColorAttachment
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
419
    \brief Describes the color attachments of a render target.
Laszlo Agocs's avatar
Laszlo Agocs committed
420 421 422 423 424
 */

/*!
    \class QRhiTextureUploadDescription
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
425
    \brief Describes a texture upload operation.
Laszlo Agocs's avatar
Laszlo Agocs committed
426 427 428 429 430
 */

/*!
    \class QRhiTextureUploadDescription::Layer
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
431
    \brief Describes one layer (face for cubemaps) in a texture upload operation.
Laszlo Agocs's avatar
Laszlo Agocs committed
432 433 434 435 436
 */

/*!
    \class QRhiTextureUploadDescription::Layer::MipLevel
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
437
    \brief Describes one mip level in a layer in a texture upload operation.
Laszlo Agocs's avatar
Laszlo Agocs committed
438 439 440 441 442
 */

/*!
    \class QRhiTextureCopyDescription
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
443
    \brief Describes a texture-to-texture copy operation.
Laszlo Agocs's avatar
Laszlo Agocs committed
444 445 446 447 448
 */

/*!
    \class QRhiReadbackDescription
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
449
    \brief Describes a readback (reading back texture contents from possibly GPU-only memory) operation.
Laszlo Agocs's avatar
Laszlo Agocs committed
450 451 452 453 454
 */

/*!
    \class QRhiReadbackResult
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
455
    \brief Describes the results of a potentially asynchronous readback operation.
Laszlo Agocs's avatar
Laszlo Agocs committed
456 457 458 459 460
 */

/*!
    \class QRhiNativeHandles
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
461
    \brief Base class for classes exposing backend-specific collections of native resource objects.
Laszlo Agocs's avatar
Laszlo Agocs committed
462 463 464 465 466
 */

/*!
    \class QRhiResource
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
467
    \brief Base class for classes encapsulating native resource objects.
Laszlo Agocs's avatar
Laszlo Agocs committed
468 469 470 471 472
 */

/*!
    \class QRhiBuffer
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
473
    \brief Vertex, index, or uniform (constant) buffer resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
474 475
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
/*!
    \enum QRhiBuffer::Type
    Specifies type of buffer resource.

    \value Immutable Indicates that the data is not expected to change ever
    after the initial upload. Under the hood such buffer resources are
    typically placed in device local (GPU) memory (on systems where
    applicable). Uploading new data is possible, but frequent changes can be
    expensive. Upload typically happens by copying to a separate, host visible
    staging buffer from which a GPU buffer-to-buffer copy is issued into the
    actual GPU-only buffer.

    \value Static Indicates that the data is expected to change only
    infrequently. Typically placed in device local (GPU) memory, where
    applicable. On backends where host visible staging buffers are used for
    uploading, the staging buffers are kept around for this type, unlike with
    Immutable, so subsequent uploads do not suffer in performance. Frequent
    updates should be avoided.

    \value Dynamic Indicates that the data is expected to change frequently.
    Not recommended for large buffers. Typically backed by host visible memory
    in 2 copies in order to allow for changing without stalling the graphics
    pipeline. The double buffering is managed transparently to the applications
    and is not exposed in the API here in any form.
 */

/*!
    \enum QRhiBuffer::UsageFlag
    Flag values to specify how the buffer is going to be used.

    \value VertexBuffer Vertex buffer
    \value IndexBuffer Index buffer
    \value UniformBuffer Uniform (constant) buffer
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
511 512 513
/*!
    \class QRhiTexture
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
514
    \brief Texture resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
515 516
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
/*!
    \enum QRhiTexture::Flag

    Flag values to specify how the texture is going to be used. Not honoring
    the flags set before build() and attempting to use the texture in ways that
    was not declared upfront can lead to unspecified behavior or decreased
    performance depending on the backend and the underlying graphics API.

    \value RenderTarget The texture going to be used in combination with
    QRhiTextureRenderTarget

    \value ChangesFrequently Performance hint to indicate that the texture
    contents will change frequently and so staging buffers, if any, are to be
    kept alive to avoid performance hits

    \value CubeMap The texture is a cubemap. Such textures have 6 layers, one
    for each face in the order of +X, -X, +Y, -Y, +Z, -Z. Cubemap textures
    cannot be multisample.

     \value MipMapped The texture has mipmaps. The appropriate mip count is
     calculated automatically and can also be retrieved via
     QRhi::mipLevelsForSize(). The images for the mip levels have to be
     provided in the texture uploaded or generated via
     QRhiResourceUpdateBatch::generateMips(). Multisample textures cannot have
     mipmaps.

    \value sRGB Use an sRGB format

    \value UsedAsTransferSource The texture is used as the source of a texture
    copy or readback, meaning the texture is given as the source in
    QRhiResourceUpdateBatch::copyTexture() or
    QRhiResourceUpdateBatch::readBackTexture().

     \value UsedWithGenerateMips The texture is going to be used with
     QRhiResourceUpdateBatch::generateMips().
 */

/*!
    \enum QRhiTexture::Format

    Specifies the texture format. See also QRhi::isTextureFormatSupported() and
    note that flags() can modify the format when QRhiTexture::sRGB is set.

    \value UnknownFormat Not a valid format. This cannot be passed to setFormat().
    \value RGBA8
    \value BGRA8
    \value R8
    \value R16
    \value D16
    \value D32
    \value BC1
    \value BC2
    \value BC3
    \value BC4
    \value BC5
    \value BC6H
    \value BC7
    \value ETC2_RGB8
    \value ETC2_RGB8A1
    \value ETC2_RGBA8
    \value ASTC_4x4
    \value ASTC_5x4
    \value ASTC_5x5
    \value ASTC_6x5
    \value ASTC_6x6
    \value ASTC_8x5
    \value ASTC_8x6
    \value ASTC_8x8
    \value ASTC_10x5
    \value ASTC_10x6
    \value ASTC_10x8
    \value ASTC_10x10
    \value ASTC_12x10
    \value ASTC_12x12
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
593 594 595
/*!
    \class QRhiSampler
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
596
    \brief Sampler resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
597 598
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
/*!
    \enum QRhiSampler::Filter
    Specifies the minification, magnification, or mipmap filtering

    \value None Applicable only for mipmapMode(), indicates no mipmaps to be used
    \value Nearest
    \value Linear
 */

/*!
    \enum QRhiSampler::AddressMode
    Specifies the addressing mode

    \value Repeat
    \value ClampToEdge
    \value Border
    \value Mirror
    \value MirrorOnce
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
619 620 621
/*!
    \class QRhiRenderBuffer
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
622
    \brief Renderbuffer resource.
623 624 625 626 627 628 629 630 631 632 633 634 635 636

    Renderbuffers cannot be sampled or read but have some benefits over
    textures in some cases:

    A DepthStencil renderbuffer may be lazily allocated and be backed by
    transient memory with some APIs. On some platforms this may mean the
    depth/stencil buffer uses no physical backing at all.

    Color renderbuffers are useful since QRhi::MultisampleRenderBuffer may be
    supported even when QRhi::MultisampleTexture is not.

    How the renderbuffer is implemented by a backend is not exposed to the
    applications. In some cases it may be backed by ordinary textures, while in
    others there may be a different kind of native resource used.
Laszlo Agocs's avatar
Laszlo Agocs committed
637 638
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
/*!
    \enum QRhiRenderBuffer::Type
    Specifies the type of the renderbuffer

    \value DepthStencil Combined depth/stencil
    \value Color Color
 */

/*!
    \enum QRhiRenderBuffer::Flag
    Flag values for flags() and setFlags()

    \value UsedWithSwapChainOnly For DepthStencil renderbuffers this indicates
    that the renderbuffer is only used in combination with a QRhiSwapChain and
    never in other ways. Relevant with some backends, while others ignore it.
    With OpenGL where a separate windowing system interface API is in use (EGL,
    GLX, etc.), the flag is important since it avoids creating any actual
    resource as there is already a windowing system provided depth/stencil
    buffer as requested by QSurfaceFormat.
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
660 661 662
/*!
    \class QRhiRenderPassDescriptor
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
663
    \brief Render pass resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
664 665 666 667 668
 */

/*!
    \class QRhiRenderTarget
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
669
    \brief Represents an onscreen (swapchain) or offscreen (texture) render target.
Laszlo Agocs's avatar
Laszlo Agocs committed
670 671
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
672 673 674 675 676 677 678 679 680 681
/*!
    \enum QRhiRenderTarget::Type
    Specifies the type of the render target

    \value RtRef This is a reference to another resource's buffer(s). Used by
    targets returned from QRhiSwapChain::currentFrameRenderTarget().

    \value RtTexture This is a QRhiTextureRenderTarget.
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
682 683 684
/*!
    \class QRhiTextureRenderTarget
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
685
    \brief Texture render target resource.
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704

    A texture render target allows rendering into one or more textures,
    optionally with a depth texture or depth/stencil renderbuffer.

    \note Textures used in combination with QRhiTextureRenderTarget must be
    created with the QRhiTexture::RenderTarget flag.

    The simplest example of creating a render target with a texture as its
    single color attachment:

    \badcode
        texture = rhi->newTexture(QRhiTexture::RGBA8, size, 1, QRhiTexture::RenderTarget);
        texture->build();
        rt = rhi->newTextureRenderTarget({ texture });
        rp = rt->newCompatibleRenderPassDescriptor();
        rt->setRenderPassDescriptor(rt);
        rt->build();
        // rt can now be used with beginPass()
    \endcode
Laszlo Agocs's avatar
Laszlo Agocs committed
705 706
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
/*!
    \enum QRhiTextureRenderTarget::Flag
    Flag values describing the load/store behavior for the render target

    \value PreserveColorContents Indicates that the contents of the color
    attachments is to be loaded when starting a render pass, instead of
    clearing. This is potentially more expensive, especially on mobile (tiled)
    GPUs, but allows preserving the existing contents between passes.

    \value PreserveDepthStencilContents Indicates that the contents of the
    depth texture is to be loaded when starting a render pass, instead
    clearing. Only applicable when a texture is used as the depth buffer
    (QRhiTextureRenderTargetDescription::depthTexture is set) because
    depth/stencil renderbuffers may not have any physical backing and data may
    not be written out in the first place.
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
724 725 726
/*!
    \class QRhiShaderResourceBindings
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
727
    \brief Encapsulates resources for making buffer, texture, sampler resources visible to shaders.
Laszlo Agocs's avatar
Laszlo Agocs committed
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791

    A QRhiShaderResourceBindings is a collection of QRhiShaderResourceBinding
    instances, each of which describe a single binding.

    Take a fragment shader with the following interface:

    \badcode
        layout(std140, binding = 0) uniform buf {
            mat4 mvp;
            int flip;
        } ubuf;

        layout(binding = 1) uniform sampler2D tex;
    \endcode

    To make resources visible to the shader, the following
    QRhiShaderResourceBindings could be created and then passed to
    QRhiGraphicsPipeline::setShaderResourceBindings():

    \badcode
        srb = rhi->newShaderResourceBindings();
        srb->setBindings({
            QRhiShaderResourceBinding::uniformBuffer(0, QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage, ubuf),
            QRhiShaderResourceBinding::sampledTexture(1, QRhiShaderResourceBinding::FragmentStage, texture, sampler)
        });
        srb->build();
        ...
        ps = rhi->newGraphicsPipeline();
        ...
        ps->setShaderResourceBindings(srb);
        ps->build();
        ...
        cb->setGraphicsPipeline(ps);
    \endcode

    This assumes that \c ubuf is a QRhiBuffer, \c texture is a QRhiTexture,
    while \a sampler is a QRhiSampler. The example also assumes that the
    uniform block is present in the vertex shader as well so the same buffer is
    made visible to the vertex stage too.

    \section3 Advanced usage

    Building on the above example, let's assume that a pass now needs to use
    the exact same pipeline and shaders with a different texture. Creating a
    whole separate QRhiGraphicsPipeline just for this would be an overkill.
    This is why QRhiCommandBuffer::setGraphicsPipeline() allows specifying an
    optional \a srb argument. As long as the layouts (so the number of bindings
    and the binding points) match between two QRhiShaderResourceBindings, they
    can both be used with the same pipeline, assuming the pipeline was built
    with one of them in the first place.

    Creating and then using a new \c srb2 that is very similar to \c srb with
    the exception of referencing another texture could be implemented like the
    following:

    \badcode
        srb2 = rhi->newShaderResourceBindings();
        QVector<QRhiShaderResourceBinding> bindings = srb->bindings();
        bindings[1].stex.tex = anotherTexture;
        srb2->setBindings(bindings);
        srb2->build();
        ...
        cb->setGraphicsPipeline(ps, srb2);
    \endcode
Laszlo Agocs's avatar
Laszlo Agocs committed
792 793 794 795 796
 */

/*!
    \class QRhiGraphicsPipeline
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
797
    \brief Graphics pipeline state resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
798 799
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
/*!
    \enum QRhiGraphicsPipeline::Flag

    Flag values for describing the dynamic state of the pipeline. The viewport is always dynamic.

    \value UsesBlendConstants Indicates that a blend color constant will be set
    via QRhiCommandBuffer::setBlendConstants()

    \value UsesStencilRef Indicates that a stencil reference value will be set
    via QRhiCommandBuffer::setStencilRef()

    \value UsesScissor Indicates that a scissor rectangle will be set via
    QRhiCommandBuffer::setScissor()
 */

/*!
    \enum QRhiGraphicsPipeline::Topology
    Specifies the primitive topology

    \value Triangles (default)
    \value TriangleStrip
    \value Lines
    \value LineStrip
    \value Points
 */

/*!
    \enum QRhiGraphicsPipeline::CullMode
    Specifies the culling mode

    \value None No culling (default)
    \value Front Cull front faces
    \value Back Cull back faces
 */

/*!
    \enum QRhiGraphicsPipeline::FrontFace
    Specifies the front face winding order

    \value CCW Counter clockwise (default)
    \value CW Clockwise
 */

/*!
    \enum QRhiGraphicsPipeline::ColorMaskComponent
    Flag values for specifying the color write mask

    \value R
    \value G
    \value B
    \value A
 */

/*!
    \enum QRhiGraphicsPipeline::BlendFactor
    Specifies the blend factor

    \value Zero
    \value One
    \value SrcColor
    \value OneMinusSrcColor
    \value DstColor
    \value OneMinusDstColor
    \value SrcAlpha
    \value OneMinusSrcAlpha
    \value DstAlpha
    \value OneMinusDstAlpha
    \value ConstantColor
    \value OneMinusConstantColor
    \value ConstantAlpha
    \value OneMinusConstantAlpha
    \value SrcAlphaSaturate
    \value Src1Color
    \value OneMinusSrc1Color
    \value Src1Alpha
    \value OneMinusSrc1Alpha
 */

/*!
    \enum QRhiGraphicsPipeline::BlendOp
    Specifies the blend operation

    \value Add
    \value Subtract
    \value ReverseSubtract
    \value Min
    \value Max
 */

/*!
    \enum QRhiGraphicsPipeline::CompareOp
    Specifies the depth or stencil comparison function

    \value Never
    \value Less (default for depth)
    \value Equal
    \value LessOrEqual
    \value Greater
    \value NotEqual
    \value GreaterOrEqual
    \value Always (default for stencil)
 */

/*!
    \enum QRhiGraphicsPipeline::StencilOp
    Specifies the stencil operation

    \value StencilZero
    \value Keep (default)
    \value Replace
    \value IncrementAndClamp
    \value DecrementAndClamp
    \value Invert
    \value IncrementAndWrap
    \value DecrementAndWrap
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
917 918 919
/*!
    \class QRhiGraphicsPipeline::TargetBlend
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
920
    \brief Describes the blend state for one color attachment.
Laszlo Agocs's avatar
Laszlo Agocs committed
921 922 923 924 925 926 927 928 929

    Defaults to color write enabled, blending disabled. The blend values are
    set up for pre-multiplied alpha (One, OneMinusSrcAlpha, One,
    OneMinusSrcAlpha) by default.

    Not having any TargetBlend specified in
    QRhiGraphicsPipeline::setTargetBlends() disables blending and is a
    convenient shortcut when having only one color attachment and no blending
    is desired. Otherwise a TargetBlend for each color attachment is expected.
Laszlo Agocs's avatar
Laszlo Agocs committed
930 931 932 933 934
 */

/*!
    \class QRhiGraphicsPipeline::StencilOpState
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
935
    \brief Describes the stencil operation state.
Laszlo Agocs's avatar
Laszlo Agocs committed
936 937 938 939 940
 */

/*!
    \class QRhiSwapChain
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
941
    \brief Swapchain resource.
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066

    A swapchain enables presenting rendering results to a surface. A swapchain
    is typically backed by a set of color buffers. Of these, one is displayed
    at a time.

    Below is a typical pattern for creating and managing a swapchain and some
    associated resources in order to render onto a QWindow:

    \badcode
      void init()
      {
          sc = rhi->newSwapChain();
          ds = rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil,
                                    QSize(), // no need to set the size yet
                                    1,
                                    QRhiRenderBuffer::UsedWithSwapChainOnly);
          sc->setWindow(window);
          sc->setDepthStencil(ds);
          rp = sc->newCompatibleRenderPassDescriptor();
          sc->setRenderPassDescriptor(rp);
          resizeSwapChain();
      }

      void resizeSwapChain()
      {
          const QSize outputSize = sc->surfacePixelSize();
          ds->setPixelSize(outputSize);
          ds->build();
          hasSwapChain = sc->buildOrResize();
      }

      void render()
      {
          if (!hasSwapChain || notExposed)
              return;

          if (sc->currentPixelSize() != sc->surfacePixelSize() || newlyExposed) {
              resizeSwapChain();
              if (!hasSwapChain)
                  return;
              newlyExposed = false;
          }

          rhi->beginFrame(sc);
          // ...
          rhi->endFrame(sc);
      }
    \endcode

    Avoid relying on QWindow resize events to resize swapchains, especially
    considering that surface sizes may not always fully match the QWindow
    reported dimensions. The safe, cross-platform approach is to do the check
    via surfacePixelSize() whenever starting a new frame.

    Releasing the swapchain must happen while the QWindow and the underlying
    native window is fully up and running. Building on the previous example:

    \badcode
        void releaseSwapChain()
        {
            sc->release();
            hasSwapChain = false;
        }

        // assuming Window is our QWindow subclass
        bool Window::event(QEvent *e)
        {
            switch (e->type()) {
            case QEvent::UpdateRequest: // for QWindow::requestUpdate()
                render();
                break;
            case QEvent::PlatformSurface:
                if (static_cast<QPlatformSurfaceEvent *>(e)->surfaceEventType() == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed)
                    releaseSwapChain();
                break;
            default:
                break;
            }
            return QWindow::event(e);
        }
    \endcode

    Initializing the swapchain and starting to render the first frame cannot
    start at any time. The safe, cross-platform approach is to rely on expose
    events. QExposeEvent is a loosely specified event that is sent whenever a
    window gets mapped, obscured, and resized, depending on the platform.

    \badcode
        void Window::exposeEvent(QExposeEvent *)
        {
            // initialize and start rendering when the window becomes usable for graphics purposes
            if (isExposed() && !running) {
                running = true;
                init();
                render();
            }

            // stop pushing frames when not exposed or size becomes 0
            if ((!isExposed() || (hasSwapChain && sc->surfacePixelSize().isEmpty())) && running)
                notExposed = true;

            // continue when exposed again and the surface has a valid size
            if (isExposed() && running && notExposed && !sc->surfacePixelSize().isEmpty()) {
                notExposed = false;
                newlyExposed = true;
                render();
            }
        }
    \endcode

    Once the rendering has started, a simple way to request a new frame is
    QWindow::requestUpdate(). While on some platforms this is merely a small
    timer, on others it has a specific implementation: for instance on macOS or
    iOS it may be backed by
    \l{https://developer.apple.com/documentation/corevideo/cvdisplaylink?language=objc}{CVDisplayLink}.
    The example above is already prepared for update requests by handling
    QEvent::UpdateRequest.

    While acting as a QRhiRenderTarget, QRhiSwapChain also manages a
    QRhiCommandBuffer. Calling QRhi::endFrame() submits the recorded commands
    and also enqueues a \c present request. The default behavior is to do this
    with a swap interval of 1, meaning synchronizing to the display's vertical
    refresh is enabled. Thus the rendering thread calling beginFrame() and
    endFrame() will get throttled to vsync. On some backends this can be
    disabled by passing QRhiSwapChain:NoVSync in flags().
Laszlo Agocs's avatar
Laszlo Agocs committed
1067 1068
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
/*!
    \enum QRhiSwapChain::Flag
    Flag values to describe swapchain properties

    \value SurfaceHasPreMulAlpha Indicates that the target surface has
    transparency with premultiplied alpha.

    \value SurfaceHasNonPreMulAlpha Indicates the target surface has
    transparencyt with non-premultiplied alpha.

    \value sRGB Requests to pick an sRGB format.

    \value UsedAsTransferSource Indicates the the swapchain will be used as the
    source of a readback in QRhiResourceUpdateBatch::readBackTexture().

    \value NoVSync Requests disabling waiting for vertical sync, also avoiding
    throttling the rendering thread. The behavior is backend specific and
    applicable only where it is possible to control this. Some may ignore the
    request altogether. For OpenGL, use QSurfaceFormat::setSwapInterval().
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1090 1091 1092
/*!
    \class QRhiCommandBuffer
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
1093 1094 1095 1096 1097
    \brief Command buffer resource.

    Not creatable by applications at the moment. The only ways to obtain a
    valid QRhiCommandBuffer are to get it from the targeted swapchain via
    QRhiSwapChain::currentFrameCommandBuffer(), or, in case of rendering
1098
    completely offscreen, initializing one via QRhi::beginOffscreenFrame().
Laszlo Agocs's avatar
Laszlo Agocs committed
1099 1100 1101 1102 1103 1104 1105 1106
 */

/*!
    \enum QRhiCommandBuffer::IndexFormat
    Specifies the index data type

    \value IndexUInt16 Unsigned 16-bit (quint16)
    \value IndexUInt32 Unsigned 32-bit (quint32)
Laszlo Agocs's avatar
Laszlo Agocs committed
1107 1108
 */

1109 1110 1111 1112 1113 1114 1115
/*!
    \typedef QRhiCommandBuffer::VertexInput

    Synonym for QPair<QRhiBuffer *, quint32>. The second entry is an offset in
    the buffer specified by the first.
*/

Laszlo Agocs's avatar
Laszlo Agocs committed
1116 1117 1118
/*!
    \class QRhiResourceUpdateBatch
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
1119
    \brief Records upload and copy type of operations.
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133

    With QRhi it is no longer possible to perform copy type of operations at
    arbitrary times. Instead, all such operations are recorded into batches
    that are then passed, most commonly, to QRhiCommandBuffer::beginPass().
    What then happens under the hood is hidden from the application: the
    underlying implementations can defer and implement these operations in
    various different ways.

    A resource update batch owns no graphics resources and does not perform any
    actual operations on its own. It should rather be viewed as a command
    buffer for update, upload, and copy type of commands.

    To get an available, empty batch from the pool, call
    QRhi::nextResourceUpdateBatch().
Laszlo Agocs's avatar
Laszlo Agocs committed
1134 1135
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
1136 1137 1138 1139 1140
/*!
    \enum QRhiResourceUpdateBatch::TexturePrepareFlag
    \internal
 */

1141 1142 1143
/*!
    \internal
 */
1144 1145 1146 1147 1148
QRhiResource::QRhiResource(QRhiImplementation *rhi_)
    : rhi(rhi_)
{
}

1149 1150 1151
/*!
   Destructor.
 */
1152 1153 1154 1155
QRhiResource::~QRhiResource()
{
}

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
/*!
    \fn void QRhiResource::release()

    Releases the underlying native graphics resources. Safe to call multiple
    times, subsequent invocations will be a no-op then.

    Once release() is called, the QRhiResource instance can be reused, by
    calling the appropriate \c build() function again, or destroyed.
 */

/*!
    Releases native graphics resources, if there is any, and destroys the
    QRhiResource. Equivalent to \c{r->release(); delete r; }.
 */
1170 1171 1172 1173 1174 1175
void QRhiResource::releaseAndDestroy()
{
    release();
    delete this;
}

1176 1177 1178
/*!
    Returns the currently set object name. By default the name is empty.
 */
1179 1180 1181 1182 1183
QByteArray QRhiResource::name() const
{
    return objectName;
}

1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
/*!
    Sets a \a name for the object.

    This has two uses: to get descriptive names for the native graphics
    resources visible in graphics debugging tools, such as
    \l{https://renderdoc.org/}{RenderDoc} and
    \l{https://developer.apple.com/xcode/}{XCode}, and in the output stream of
    QRhiProfiler.

    When it comes to naming native objects by relaying the name via the
    appropriate graphics API, note that the name is ignored when
    QRhi::DebugMarkers are not supported, and may, depending on the backend,
    also be ignored when QRhi::EnableDebugMarkers is not set.

    \note The name may be ignored for objects other than buffers,
    renderbuffers, and textures, depending on the backend.

    \note The name may be modified. For slotted resources, such as a QRhiBuffer
    backed by multiple native buffers, QRhi will append a suffix to make the
    underlying native buffers easily distinguishable from each other.
 */
1205 1206 1207
void QRhiResource::setName(const QByteArray &name)
{
    objectName = name;
1208
    objectName.replace(',', '_'); // cannot contain comma for QRhiProfiler
1209 1210
}

1211 1212 1213
/*!
    \internal
 */
1214 1215
QRhiBuffer::QRhiBuffer(QRhiImplementation *rhi, Type type_, UsageFlags usage_, int size_)
    : QRhiResource(rhi),
Laszlo Agocs's avatar
Laszlo Agocs committed
1216
      m_type(type_), m_usage(usage_), m_size(size_)
1217 1218 1219
{
}

1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
/*!
    \fn bool QRhiBuffer::build()

    Creates the corresponding native graphics resources. If there are already
    resources present due to an earlier build() with no corresponding
    release(), then release() is called implicitly first.

    \return \c true when successful, \c false when a graphics operation failed.
    Regardless of the return value, calling release() is always safe.
 */

/*!
    \internal
 */
1234
QRhiRenderBuffer::QRhiRenderBuffer(QRhiImplementation *rhi, Type type_, const QSize &pixelSize_,
Laszlo Agocs's avatar
Laszlo Agocs committed
1235
                                   int sampleCount_, Flags flags_)
1236
    : QRhiResource(rhi),
Laszlo Agocs's avatar
Laszlo Agocs committed
1237
      m_type(type_), m_pixelSize(pixelSize_), m_sampleCount(sampleCount_), m_flags(flags_)
1238 1239 1240
{
}

1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
/*!
    \fn bool QRhiRenderBuffer::build()

    Creates the corresponding native graphics resources. If there are already
    resources present due to an earlier build() with no corresponding
    release(), then release() is called implicitly first.

    \return \c true when successful, \c false when a graphics operation failed.
    Regardless of the return value, calling release() is always safe.
 */

/*!
    \internal
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1255 1256
QRhiTexture::QRhiTexture(QRhiImplementation *rhi, Format format_, const QSize &pixelSize_,
                         int sampleCount_, Flags flags_)
1257
    : QRhiResource(rhi),
Laszlo Agocs's avatar
Laszlo Agocs committed
1258
      m_format(format_), m_pixelSize(pixelSize_), m_sampleCount(sampleCount_), m_flags(flags_)
1259 1260 1261
{
}

1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
/*!
    \fn bool QRhiTexture::build()

    Creates the corresponding native graphics resources. If there are already
    resources present due to an earlier build() with no corresponding
    release(), then release() is called implicitly first.

    \return \c true when successful, \c false when a graphics operation failed.
    Regardless of the return value, calling release() is always safe.
 */

/*!
    \return a pointer to a backend-specific QRhiNativeHandles subclass, such as
    QRhiVulkanTextureNativeHandles. The returned value is null when exposing
    the underlying native resources is not supported by the backend.
 */
1278
const QRhiNativeHandles *QRhiTexture::nativeHandles()
1279 1280 1281 1282
{
    return nullptr;
}

1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
/*!
    Similar to build() except that no new native textures are created. Instead,
    the texture from \a src is used.

    // Calling this instead of build() allows importing an existing native
    // texture object (must belong to the same device or a sharing context).
    // Note that format, pixelSize, etc. must still be set correctly (typically
    // via QRhi::newTexture()). Ownership of the native resource is not taken.

    \note QRhiTexture does not take ownership of the texture object. release()
    does not free the object or any associated memory.

    \sa QRhiVulkanTextureNativeHandles
 */
1297
bool QRhiTexture::buildFrom(const QRhiNativeHandles *src)
1298 1299 1300 1301 1302
{
    Q_UNUSED(src);
    return false;
}

1303 1304 1305
/*!
    \internal
 */
1306 1307 1308 1309
QRhiSampler::QRhiSampler(QRhiImplementation *rhi,
                         Filter magFilter_, Filter minFilter_, Filter mipmapMode_,
                         AddressMode u_, AddressMode v_, AddressMode w_)
    : QRhiResource(rhi),
Laszlo Agocs's avatar
Laszlo Agocs committed
1310 1311
      m_magFilter(magFilter_), m_minFilter(minFilter_), m_mipmapMode(mipmapMode_),
      m_addressU(u_), m_addressV(v_), m_addressW(w_)
1312 1313 1314
{
}

1315 1316 1317
/*!
    \internal
 */
1318
QRhiRenderPassDescriptor::QRhiRenderPassDescriptor(QRhiImplementation *rhi)
1319 1320 1321 1322
    : QRhiResource(rhi)
{
}

1323 1324 1325
/*!
    \internal
 */
1326 1327 1328 1329 1330
QRhiRenderTarget::QRhiRenderTarget(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
/*!
    \fn QRhiRenderTarget::Type QRhiRenderTarget::type() const

    \return the type of the render target.
 */

/*!
    \fn QSize QRhiRenderTarget::sizeInPixels() const

    \return the size in pixels.
 */

/*!
    \fn float QRhiRenderTarget::devicePixelRatio() const

    \return the device pixel ratio. For QRhiTextureRenderTarget this is always
    1. For targets retrieved from a QRhiSwapChain the value reflects the
    \l{QWindow::devicePixelRatio()}{device pixel ratio} of the targeted
    QWindow.
 */

/*!
    \internal
 */
1355 1356 1357 1358 1359
QRhiReferenceRenderTarget::QRhiReferenceRenderTarget(QRhiImplementation *rhi)
    : QRhiRenderTarget(rhi)
{
}

1360 1361 1362
/*!
    \internal
 */
1363 1364 1365 1366
QRhiTextureRenderTarget::QRhiTextureRenderTarget(QRhiImplementation *rhi,
                                                 const QRhiTextureRenderTargetDescription &desc_,
                                                 Flags flags_)
    : QRhiRenderTarget(rhi),
Laszlo Agocs's avatar
Laszlo Agocs committed
1367 1368
      m_desc(desc_),
      m_flags(flags_)
1369 1370 1371
{
}

1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
/*!
    \fn QRhiRenderPassDescriptor *QRhiTextureRenderTarget::newCompatibleRenderPassDescriptor()

    \return a new QRhiRenderPassDescriptor that is compatible with this render
    target.

    The returned value is used in two ways: it can be passed to
    setRenderPassDescriptor() and
    QRhiGraphicsPipeline::setRenderPassDescriptor(). A render pass descriptor
    describes the attachments (color, depth/stencil) and the load/store
    behavior that can be affected by flags(). A QRhiGraphicsPipeline can only
    be used in combination with a render target that has the same
    QRhiRenderPassDescriptor set.

    Two QRhiTextureRenderTarget instances can share the same render pass
    descriptor as long as they have the same number and type of attachments.
    The associated QRhiTexture or QRhiRenderBuffer instances are not part of
    the render pass descriptor so those can differ in the two
    QRhiTextureRenderTarget intances.

    \sa build()
 */

/*!
    \fn bool QRhiTextureRenderTarget::build()

    Creates the corresponding native graphics resources. If there are already
    resources present due to an earlier build() with no corresponding
    release(), then release() is called implicitly first.

    \note renderPassDescriptor() must be set before calling build(). To obtain
    a QRhiRenderPassDescriptor compatible with the render target, call
    newCompatibleRenderPassDescriptor() before build() but after setting all
    other parameters, such as description() and flags(). To save resources,
    reuse the same QRhiRenderPassDescriptor with multiple
    QRhiTextureRenderTarget instances, whenever possible. Sharing the same
    render pass descriptor is only possible when the render targets have the
    same number and type of attachments (the actual textures can differ) and
    the same flags.

    \return \c true when successful, \c false when a graphics operation failed.
    Regardless of the return value, calling release() is always safe.
 */

/*!
    \internal
 */
1419 1420 1421 1422 1423
QRhiShaderResourceBindings::QRhiShaderResourceBindings(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1424 1425 1426 1427
/*!
    Returns a shader resource binding for the given binding number, pipeline
    stage, and buffer specified by \a binding_, \a stage_, and \a buf_.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1428
QRhiShaderResourceBinding QRhiShaderResourceBinding::uniformBuffer(
1429 1430
        int binding_, StageFlags stage_, QRhiBuffer *buf_)
{
Laszlo Agocs's avatar
Laszlo Agocs committed
1431
    QRhiShaderResourceBinding b;
1432 1433 1434 1435 1436 1437 1438 1439 1440
    b.binding = binding_;
    b.stage = stage_;
    b.type = UniformBuffer;
    b.ubuf.buf = buf_;
    b.ubuf.offset = 0;
    b.ubuf.maybeSize = 0; // entire buffer
    return b;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1441 1442 1443 1444 1445 1446 1447 1448
/*!
    Returns a shader resource binding for the given binding number, pipeline
    stage, and buffer specified by \a binding_, \a stage_, and \a buf_. This
    overload binds a region only, as specified by \a offset_ and \a size_.

    \note It is up to the user to ensure the offset is aligned to
    QRhi::ubufAlignment().
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1449
QRhiShaderResourceBinding QRhiShaderResourceBinding::uniformBuffer(
1450 1451 1452
        int binding_, StageFlags stage_, QRhiBuffer *buf_, int offset_, int size_)
{
    Q_ASSERT(size_ > 0);
Laszlo Agocs's avatar
Laszlo Agocs committed
1453
    QRhiShaderResourceBinding b;
1454 1455 1456 1457 1458 1459 1460 1461 1462
    b.binding = binding_;
    b.stage = stage_;
    b.type = UniformBuffer;
    b.ubuf.buf = buf_;
    b.ubuf.offset = offset_;
    b.ubuf.maybeSize = size_;
    return b;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1463 1464 1465 1466 1467
/*!
    Returns a shader resource binding for the given binding number, pipeline
    stage, texture, and sampler specified by \a binding_, \a stage_, \a tex_,
    \a sampler_.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1468
QRhiShaderResourceBinding QRhiShaderResourceBinding::sampledTexture(
1469 1470
        int binding_, StageFlags stage_, QRhiTexture *tex_, QRhiSampler *sampler_)
{
Laszlo Agocs's avatar
Laszlo Agocs committed
1471
    QRhiShaderResourceBinding b;
1472 1473 1474 1475 1476 1477 1478 1479
    b.binding = binding_;
    b.stage = stage_;
    b.type = SampledTexture;
    b.stex.tex = tex_;
    b.stex.sampler = sampler_;
    return b;
}

1480 1481 1482
/*!
    \internal
 */
1483 1484 1485 1486 1487
QRhiGraphicsPipeline::QRhiGraphicsPipeline(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
/*!
    \fn bool QRhiGraphicsPipeline::build()

    Creates the corresponding native graphics resources. If there are already
    resources present due to an earlier build() with no corresponding
    release(), then release() is called implicitly first.

    \return \c true when successful, \c false when a graphics operation failed.
    Regardless of the return value, calling release() is always safe.
 */

/*!
    \internal
 */
1502 1503 1504 1505 1506
QRhiSwapChain::QRhiSwapChain(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
/*!
    \fn QObject *QRhiSwapChain::target() const
    \internal
 */

/*!
    \fn void QRhiSwapChain::setTarget(QObject *obj)
    \internal
 */

/*!
    \fn QSize QRhiSwapChain::currentPixelSize() const

    \return the size with which the swapchain was last successfully built. Use
    this to decide if buildOrResize() needs to be called again: if
    \c{currentPixelSize() != surfacePixelSize()} then the swapchain needs to be
    resized.

    \sa surfacePixelSize()
  */

/*!
    \fn QSize QRhiSwapChain::surfacePixelSize()

    \return The size of the window's associated surface or layer. Do not assume
    this is the same as QWindow::size() * QWindow::devicePixelRatio().

    Can be called before buildOrResize() (but with window() already set), which
    allows setting the correct size for the depth-stencil buffer that is then
    used together with the swapchain's color buffers. Also used in combination
    with currentPixelSize() to detect size changes.

    \sa currentPixelSize()
  */

/*!
    \fn QRhiCommandBuffer *QRhiSwapChain::currentFrameCommandBuffer()

    \return a command buffer on which rendering commands can be recorded. Only
    valid within a Rhi::beginFrame() - QRhi::endFrame() block where
    beginFrame() was called with this swapchain.

    \note the value must not be cached and reused between frames
*/

/*!
    \fn QRhiRenderTarget *QRhiSwapChain::currentFrameRenderTarget()

    \return a render target that can used with beginPass() in order to render
    the the swapchain's current backbuffer. Only valid within a
    QRhi::beginFrame() - QRhi::endFrame() block where beginFrame() was called
    with this swapchain.

    \note the value must not be cached and reused between frames
 */

/*!
    \fn bool QRhiSwapChain::buildOrResize()

    Creates the swapchain if not already done and resizes the swapchain buffers
    to match the current size of the targeted surface. Call this whenever the
    size of the target surface is different than before.

    \note call release() only when the swapchain needs to be released
    completely, typically upon
    QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed. To perform resizing, just
    call buildOrResize().

    \return \c true when successful, \c false when a graphics operation failed.
    Regardless of the return value, calling release() is always safe.
 */

/*!
    \internal
 */
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
QRhiCommandBuffer::QRhiCommandBuffer(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

QRhiImplementation::~QRhiImplementation()
{
    qDeleteAll(resUpdPool);
}

1592 1593 1594 1595 1596
void QRhiImplementation::sendVMemStatsToProfiler()
{
    // nothing to do in the default implementation
}

1597
bool QRhiImplementation::isCompressedFormat(QRhiTexture::Format format) const
1598 1599 1600 1601 1602 1603 1604
{
    return (format >= QRhiTexture::BC1 && format <= QRhiTexture::BC7)
            || (format >= QRhiTexture::ETC2_RGB8 && format <= QRhiTexture::ETC2_RGBA8)
            || (format >= QRhiTexture::ASTC_4x4 && format <= QRhiTexture::ASTC_12x12);
}

void QRhiImplementation::compressedFormatInfo(QRhiTexture::Format format, const QSize &size,
1605 1606
                                              quint32 *bpl, quint32 *byteSize,
                                              QSize *blockDim) const
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
{
    int xdim = 4;
    int ydim = 4;
    quint32 blockSize = 0;

    switch (format) {
    case QRhiTexture::BC1:
        blockSize = 8;
        break;
    case QRhiTexture::BC2:
        blockSize = 16;
        break;
    case QRhiTexture::BC3:
        blockSize = 16;
        break;
    case QRhiTexture::BC4:
        blockSize = 8;
        break;
    case QRhiTexture::BC5:
        blockSize = 16;
        break;
    case QRhiTexture::BC6H:
        blockSize = 16;
        break;
    case QRhiTexture::BC7:
        blockSize = 16;
        break;

    case QRhiTexture::ETC2_RGB8:
        blockSize = 8;
        break;
    case QRhiTexture::ETC2_RGB8A1:
        blockSize = 8;
        break;
    case QRhiTexture::ETC2_RGBA8:
        blockSize = 16;
        break;

    case QRhiTexture::ASTC_4x4:
        blockSize = 16;
        break;
    case QRhiTexture::ASTC_5x4:
        blockSize = 16;
        xdim = 5;
        break;
    case QRhiTexture::ASTC_5x5:
        blockSize = 16;
        xdim = ydim = 5;
        break;
    case QRhiTexture::ASTC_6x5:
        blockSize = 16;
        xdim = 6;
        ydim = 5;
        break;
    case QRhiTexture::ASTC_6x6:
        blockSize = 16;
        xdim = ydim = 6;
        break;
    case QRhiTexture::ASTC_8x5:
        blockSize = 16;
        xdim = 8;
        ydim = 5;
        break;
    case QRhiTexture::ASTC_8x6:
        blockSize = 16;
        xdim = 8;
        ydim = 6;
        break;
    case QRhiTexture::ASTC_8x8:
        blockSize = 16;
        xdim = ydim = 8;
        break;
    case QRhiTexture::ASTC_10x5:
        blockSize = 16;
        xdim = 10;
        ydim = 5;
        break;
    case QRhiTexture::ASTC_10x6:
        blockSize = 16;
        xdim = 10;
        ydim = 6;
        break;
    case QRhiTexture::ASTC_10x8:
        blockSize = 16;
        xdim = 10;
        ydim = 8;
        break;
    case QRhiTexture::ASTC_10x10:
        blockSize = 16;
        xdim = ydim = 10;
        break;
    case QRhiTexture::ASTC_12x10:
        blockSize = 16;
        xdim = 12;
        ydim = 10;
        break;
    case QRhiTexture::ASTC_12x12:
        blockSize = 16;
        xdim = ydim = 12;
        break;

    default:
        Q_UNREACHABLE();
        break;
    }

    const quint32 wblocks = (size.width() + xdim - 1) / xdim;
    const quint32 hblocks = (size.height() + ydim - 1) / ydim;

    if (bpl)
        *bpl = wblocks * blockSize;
    if (byteSize)
        *byteSize = wblocks * hblocks * blockSize;
1720 1721
    if (blockDim)
        *blockDim = QSize(xdim, ydim);
1722 1723 1724
}

void QRhiImplementation::textureFormatInfo(QRhiTexture::Format format, const QSize &size,
1725
                                           quint32 *bpl, quint32 *byteSize) const
1726 1727
{
    if (isCompressedFormat(format)) {
1728
        compressedFormatInfo(format, size, bpl, byteSize, nullptr);
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
        return;
    }

    quint32 bpc = 0;
    switch (format) {
    case QRhiTexture::RGBA8:
        bpc = 4;
        break;
    case QRhiTexture::BGRA8:
        bpc = 4;
        break;
    case QRhiTexture::R8:
        bpc = 1;
        break;
    case QRhiTexture::R16:
        bpc = 2;
        break;

    case QRhiTexture::D16:
        bpc = 2;
        break;
    case QRhiTexture::D32:
        bpc = 4;
        break;

    default:
        Q_UNREACHABLE();
        break;
    }

    if (bpl)
        *bpl = size.width() * bpc;
    if (byteSize)
        *byteSize = size.width() * size.height() * bpc;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1765
// Approximate because it excludes subresource alignment or multisampling.
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
quint32 QRhiImplementation::approxByteSizeForTexture(QRhiTexture::Format format, const QSize &baseSize,
                                                     int mipCount, int layerCount)
{
    quint32 approxSize = 0;
    for (int level = 0; level < mipCount; ++level) {
        quint32 byteSize = 0;
        const QSize size(qFloor(float(qMax(1, baseSize.width() >> level))),
                         qFloor(float(qMax(1, baseSize.height() >> level))));
        textureFormatInfo(format, size, nullptr, &byteSize);
        approxSize += byteSize;
    }
    approxSize *= layerCount;
    return approxSize;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1781 1782 1783
/*!
    \internal
 */
1784 1785 1786 1787
QRhi::QRhi()
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1788 1789 1790
/*!
    Destructor. Destroys the backend and releases resources.
 */
1791 1792
QRhi::~QRhi()
{
1793 1794 1795 1796
    if (d) {
        d->destroy();
        delete d;
    }
1797 1798
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
/*!
    \return a new QRhi instance with a backend for the graphics API specified by \a impl.

    \a params must point to an instance of one of the backend-specific
    subclasses of QRhiInitParams, such as, QRhiVulkanInitParams,
    QRhiMetalInitParams, QRhiD3D11InitParams, QRhiGles2InitParams. See these
    classes for examples on creating a QRhi.

    \a flags is optional. It is used to enable profile and debug related
    features that are potentially expensive and should only be used during
    development.
 */
1811
QRhi *QRhi::create(Implementation impl, QRhiInitParams *params, Flags flags)
1812
{
1813 1814
    QScopedPointer<QRhi> r(new QRhi);

1815
    switch (impl) {
Laszlo Agocs's avatar
Laszlo Agocs committed
1816 1817 1818
    case Null:
        r->d = new QRhiNull(params);
        break;
1819 1820 1821
    case Vulkan:
#if QT_CONFIG(vulkan)
        r->d = new QRhiVulkan(params);
1822
        break;
1823 1824 1825 1826 1827
#else
        qWarning("This build of Qt has no Vulkan support");
        break;
#endif
    case OpenGLES2:
1828
#ifndef QT_NO_OPENGL
1829
        r->d = new QRhiGles2(params);
1830
        break;
1831 1832 1833 1834
#else
        qWarning("This build of Qt has no OpenGL support");
        break;
#endif
1835 1836 1837
    case D3D11:
#ifdef Q_OS_WIN
        r->d = new QRhiD3D11(params);
1838
        break;
1839 1840 1841 1842 1843 1844 1845
#else
        qWarning("This platform has no Direct3D 11 support");
        break;
#endif
    case Metal:
#ifdef Q_OS_DARWIN
        r->d = new QRhiMetal(params);
1846
        break;
1847 1848 1849 1850 1851 1852 1853
#else
        qWarning("This platform has no Metal support");
        break;
#endif
    default:
        break;
    }
1854

1855 1856 1857 1858 1859 1860
    if (r->d) {
        if (flags.testFlag(EnableProfiling)) {
            QRhiProfilerPrivate *profD = QRhiProfilerPrivate::get(&r->d->profiler);
            profD->rhi = r.data();
            profD->rhiD = r->d;
        }
1861
        r->d->debugMarkers = flags.testFlag(EnableDebugMarkers);
1862 1863 1864
        if (r->d->create(flags))
            return r.take();
    }
1865

1866 1867 1868
    return nullptr;
}

1869 1870 1871
/*!
    \internal
 */
1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
QRhiResourceUpdateBatch::QRhiResourceUpdateBatch(QRhiImplementation *rhi)
    : d(new QRhiResourceUpdateBatchPrivate)
{
    d->q = this;
    d->rhi = rhi;
}

QRhiResourceUpdateBatch::~QRhiResourceUpdateBatch()
{
    delete d;
}

1884 1885 1886 1887 1888 1889 1890 1891 1892
/*!
    Returns the batch to the pool. This should only be used when the batch is
    not passed to one of QRhiCommandBuffer::beginPass(),
    QRhiCommandBuffer::endPass(), or QRhiCommandBuffer::resourceUpdate()
    because these implicitly call release().

    \note QRhiResourceUpdateBatch instances must never by \c deleted by
    applications.
 */
1893 1894 1895 1896 1897
void QRhiResourceUpdateBatch::release()
{
    d->free();
}

1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
/*!
    Copies all queued operations from the \a other batch into this one.

    \note \a other is not changed in any way, typically it will still need a
    release()

    This allows for a convenient pattern where resource updates that are
    already known during the initialization step are collected into a batch
    that is then merged into another when starting to first render pass later
    on:

    \badcode
    void init()
    {
        ...
        initialUpdates = rhi->nextResourceUpdateBatch();
        initialUpdates->uploadStaticBuffer(vbuf, vertexData);
        initialUpdates->uploadStaticBuffer(ibuf, indexData);
        ...
    }

    void render()
    {
        ...
        QRhiResourceUpdateBatch *resUpdates = rhi->nextResourceUpdateBatch();
        if (initialUpdates) {
            resUpdates->merge(initialUpdates);
            initialUpdates->release();
            initialUpdates = nullptr;
        }
        resUpdates->updateDynamicBuffer(...);
        ...
        cb->beginPass(rt, clearCol, clearDs, resUpdates);
    }
    \endcode
 */
1934 1935 1936 1937 1938
void QRhiResourceUpdateBatch::merge(QRhiResourceUpdateBatch *other)
{
    d->merge(other->d);
}

1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
/*!
    Enqueues updating a region of a QRhiBuffer \a buf created with the type
    QRhiBuffer::Dynamic.

    The region is specified \a offset and \a size. The actual bytes to write
    are specified by \a data which must have at least \a size bytes available.
    \a data can safely be destroyed or changed once this function returns since
    it takes a copy internally as necessary.

    \note If host writes are involved, which in case of updateDynamicBuffer()
    typically are as such buffers are backed by host visible memory with most
    backend, they may accumulate within a frame. Thus pass 1 reading a region
    changed by a batch passed to pass 2 may see the changes specified in pass
    2's update batch.

    \note QRhi transparently manages double buffering in order to prevent
    stalling the graphics pipeline. The fact that a QRhiBuffer may have
    multiple native underneath can be safely ignored when using the QRhi and
    QRhiResourceUpdateBatch.
 */
1959 1960 1961 1962 1963
void QRhiResourceUpdateBatch::updateDynamicBuffer(QRhiBuffer *buf, int offset, int size, const void *data)
{
    d->dynamicBufferUpdates.append({ buf, offset, size, data });
}

1964 1965 1966 1967 1968 1969 1970 1971 1972
/*!
    Enqueues updating a region of a QRhiBuffer \a buf created with the type
    QRhiBuffer::Immutable or QRhiBuffer::Static.

    The region is specified \a offset and \a size. The actual bytes to write
    are specified by \a data which must have at least \a size bytes available.
    \a data can safely be destroyed or changed once this function returns since
    it takes a copy internally as necessary.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1973 1974 1975 1976 1977
void QRhiResourceUpdateBatch::uploadStaticBuffer(QRhiBuffer *buf, int offset, int size, const void *data)
{
    d->staticBufferUploads.append({ buf, offset, size, data });
}

1978 1979 1980 1981
/*!
    Enqueues updating the entire QRhiBuffer \a buf created with the type
    QRhiBuffer::Immutable or QRhiBuffer::Static.
 */
1982 1983
void QRhiResourceUpdateBatch::uploadStaticBuffer(QRhiBuffer *buf, const void *data)
{
Laszlo Agocs's avatar
Laszlo Agocs committed
1984
    d->staticBufferUploads.append({ buf, 0, 0, data });
1985 1986
}

1987 1988 1989 1990 1991 1992 1993
/*!
    Enqueues uploading the image data for one or more mip levels in one or more
    layers of the texture \a tex.

    The details of the copy (source QImage or compressed texture data, regions,
    target layers and levels) are described in \a desc.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
1994
void QRhiResourceUpdateBatch::uploadTexture(QRhiTexture *tex, const QRhiTextureUploadDescription &desc)
1995 1996 1997 1998
{
    d->textureUploads.append({ tex, desc });
}

1999 2000 2001 2002 2003 2004 2005 2006
/*!
    Enqueues uploading the image data for mip level 0 of layer 0 of the texture
    \a tex.

    \a tex must have an uncompressed format. Its format must also be compatible
    with the QImage::format() of \a image. The source data is given in \a
    image.
 */
2007 2008 2009 2010 2011
void QRhiResourceUpdateBatch::uploadTexture(QRhiTexture *tex, const QImage &image)
{
    uploadTexture(tex, {{{{{ image }}}}});
}

2012 2013 2014 2015 2016 2017 2018
/*!
   Enqueues a texture-to-texture copy operation from \a src into \a dst as
   described by \a desc.

   \note The source texture \a src must be created with
   QRhiTexture::UsedAsTransferSource.
 */
2019 2020 2021 2022 2023
void QRhiResourceUpdateBatch::copyTexture(QRhiTexture *dst, QRhiTexture *src, const QRhiTextureCopyDescription &desc)
{
    d->textureCopies.append({ dst, src, desc });
}

2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
/*!
   Enqueues a texture-to-host copy operation as described by \a rb.

   Normally \a rb will specify a QRhiTexture as the source. However, when the
   swapchain in the current frame was created with
   QRhiSwapChain::UsedAsTransferSource, it can also be the source of the
   readback. For this, leave the texture set to null in \a rb.

   Unlike other operations, the results here need to be processed by the
   application. Therefore, \a result provides not just the data but also a
   callback as operations on the batch are asynchronous by nature:

   \badcode
      beginFrame(sc);
      beginPass
      ...
      QRhiReadbackResult *rbResult = new QRhiReadbackResult;
      rbResult->completed = [rbResult] {
          {
              QImage::Format fmt = rbResult->format == QRhiTexture::BGRA8 ? QImage::Format_ARGB32_Premultiplied
                                                                          : QImage::Format_RGBA8888_Premultiplied;
              const uchar *p = reinterpret_cast<const uchar *>(rbResult->data.constData());
              QImage image(p, rbResult->pixelSize.width(), rbResult->pixelSize.height(), fmt);
              image.save("result.png");
          }
          delete rbResult;
      };
      u = nextResourceUpdateBatch();
      QRhiReadbackDescription rb; // no texture -> uses the current backbuffer of sc
      u->readBackTexture(rb, rbResult);
      endPass(u);
      endFrame(sc);
   \endcode

   \note The texture must be created with QRhiTexture::UsedAsTransferSource.

   \note Multisample textures cannot be read back.
 */
2062 2063 2064 2065 2066
void QRhiResourceUpdateBatch::readBackTexture(const QRhiReadbackDescription &rb, QRhiReadbackResult *result)
{
    d->textureReadbacks.append({ rb, result });
}

2067 2068 2069 2070 2071 2072
/*!
   Enqueues a mipmap generation operation for the texture \a tex.

   \note The texture must be created with QRhiTexture::MipMapped and
   QRhiTexture::UsedWithGenerateMips.
 */
Laszlo Agocs's avatar
Laszlo Agocs committed
2073 2074
void QRhiResourceUpdateBatch::generateMips(QRhiTexture *tex)
{
Laszlo Agocs's avatar
Laszlo Agocs committed
2075
    d->textureMipGens.append(QRhiResourceUpdateBatchPrivate::TextureMipGen(tex));
Laszlo Agocs's avatar
Laszlo Agocs committed
2076 2077
}

Laszlo Agocs's avatar
Laszlo Agocs committed
2078 2079 2080
/*!
    \internal
 */
2081 2082 2083 2084 2085
void QRhiResourceUpdateBatch::prepareTextureForUse(QRhiTexture *tex, TexturePrepareFlags flags)
{
    d->texturePrepares.append({ tex, flags });
}

2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
/*!
   \return an available, empty batch to which copy type of operations can be
   recorded.

   \note the return value is not owned by the caller and must never be
   destroyed. Instead, the batch is returned the the pool for reuse by passing
   it to QRhiCommandBuffer::beginPass(), QRhiCommandBuffer::endPass(), or
   QRhiCommandBuffer::resourceUpdate(), or by calling
   QRhiResourceUpdateBatch::release() on it.

   \note Can be called outside beginFrame() - endFrame() as well since a batch
   instance just collects data on its own, it does not perform any operations.
 */
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
QRhiResourceUpdateBatch *QRhi::nextResourceUpdateBatch()
{
    auto nextFreeBatch = [this]() -> QRhiResourceUpdateBatch * {
        for (int i = 0, ie = d->resUpdPoolMap.count(); i != ie; ++i) {
            if (!d->resUpdPoolMap.testBit(i)) {
                d->resUpdPoolMap.setBit(i);
                QRhiResourceUpdateBatch *u = d->resUpdPool[i];
                QRhiResourceUpdateBatchPrivate::get(u)->poolIndex = i;
                return u;
            }
        }
        return nullptr;
    };

    QRhiResourceUpdateBatch *u = nextFreeBatch();
    if (!u) {
        const int oldSize = d->resUpdPool.count();
        const int newSize = oldSize + 4;
        d->resUpdPool.resize(newSize);
        d->resUpdPoolMap.resize(newSize);
        for (int i = oldSize; i < newSize; ++i)
            d->resUpdPool[i] = new QRhiResourceUpdateBatch(d);
        u = nextFreeBatch();
        Q_ASSERT(u);
    }

    return u;
}

void QRhiResourceUpdateBatchPrivate::free()
{
    Q_ASSERT(poolIndex >= 0 && rhi->resUpdPool[poolIndex] == q);

    dynamicBufferUpdates.clear();
    staticBufferUploads.clear();
    textureUploads.clear();
2135
    textureCopies.clear();
2136
    textureReadbacks.clear();
Laszlo Agocs's avatar
Laszlo Agocs committed
2137
    textureMipGens.clear();
2138
    texturePrepares.clear();
2139 2140 2141 2142 2143

    rhi->resUpdPoolMap.clearBit(poolIndex);
    poolIndex = -1;
}

2144 2145 2146 2147 2148
void QRhiResourceUpdateBatchPrivate::merge(QRhiResourceUpdateBatchPrivate *other)
{
    dynamicBufferUpdates += other->dynamicBufferUpdates;
    staticBufferUploads += other->staticBufferUploads;
    textureUploads += other->textureUploads;
2149
    textureCopies += other->textureCopies;
2150
    textureReadbacks += other->textureReadbacks;
Laszlo Agocs's avatar
Laszlo Agocs committed
2151
    textureMipGens += other->textureMipGens;
2152 2153 2154
    texturePrepares += other->texturePrepares;
}

2155 2156 2157 2158 2159 2160 2161
/*!
    Sometimes committing resource updates is necessary without starting a
    render pass. Not often needed, updates should typically be passed to
    beginPass (or endPass, in case of readbacks) instead.

    \note Cannot be called inside a pass.
 */
2162 2163 2164 2165 2166
void QRhiCommandBuffer::resourceUpdate(QRhiResourceUpdateBatch *resourceUpdates)
{
    rhi->resourceUpdate(this, resourceUpdates);
}

2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
/*!
    Records starting a new render pass targeting the render target \a rt.

    \a resourceUpdates, when not null, specifies a resource update batch that
    is to be committed and then released.

    The color and depth/stencil buffers of the render target are normally
    cleared. The clear values are specified in \a colorClearValue and \a
    depthStencilClearValue. The exception is when the render target was created
    with QRhiTextureRenderTarget::PreserveColorContents and/or
    QRhiTextureRenderTarget::PreserveDepthStencilContents. The clear values are
    ignored then.

    \note Enabling preserved color or depth contents leads to decreased
    performance depending on the underlying hardware. Mobile GPUs with tiled
    architecture benefit from not having to reload the previous contents into
    the tile buffer. Similarly, a QRhiTextureRenderTarget with a QRhiTexture as
    the depth buffer is less efficient than a QRhiRenderBuffer since using a
    depth texture triggers requiring writing the data out to it, while with
    renderbuffers this is not needed (as the API does not allow sampling or
    reading from a renderbuffer).

    \note Do not assume that any state or resource bindings persist between
    passes.

    \note The QRhiCommandBuffer's \c set and \c draw functions can only be
    called inside a pass. Also, with the exception of setGraphicsPipeline(),
    they expect to have a pipeline set already on the command buffer.
    Unspecified issues may arise otherwise, depending on the backend.
 */
2197 2198 2199 2200 2201
void QRhiCommandBuffer::beginPass(QRhiRenderTarget *rt,
                                  const QRhiColorClearValue &colorClearValue,
                                  const QRhiDepthStencilClearValue &depthStencilClearValue,
                                  QRhiResourceUpdateBatch *resourceUpdates)
{
2202
    rhi->beginPass(this, rt, colorClearValue, depthStencilClearValue, resourceUpdates);
2203 2204
}

2205 2206 2207 2208 2209 2210
/*!
    Records ending the current render pass.

    \a resourceUpdates, when not null, specifies a resource update batch that
    is to be committed and then released.
 */
2211
void QRhiCommandBuffer::endPass(QRhiResourceUpdateBatch *resourceUpdates)
2212
{
2213
    rhi->endPass(this, resourceUpdates);
2214 2215
}

2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
/*!
    Records setting a new graphics pipeline and shader resource binding
    collection.

    The pipeline is specified by \a ps. \a srb can be null in which case the
    pipeline's associated QRhiGraphicsPipeline::shaderResourceBindings() is
    used. When \a srb is specified, the layout (number of bindings, the type
    and binding number of each binding) must fully match the
    QRhiShaderResourceBindings that was associated with the pipeline upon
    calling QRhiGraphicsPipeline::build().

    There are cases when a seemingly unnecessary setGraphicsPipeline() call is
    mandatory: when rebuilding a resource referenced from \a srb, for example
    changing the size of a QRhiBuffer followed by a QRhiBuffer::build(), this
    is the place where associated native objects (such as descriptor sets in
    case of Vulkan) are updated to refer to the current native resources that
    back the QRhiBuffer, QRhiTexture, QRhiSampler objects referenced from \a
    srb. In this case setGraphicsPipeline() must be called even if \a ps and \a
    srb are the same as in the last call.

    QRhi will optimize out unneccessary invocations within a pass (taking the
    conditions described above into account), so therefore overoptimizing to
    avoid calls to this function is not necessary on the applications' side.

    \note This function can only be called inside a pass, meaning between a
    beginPass() end endPass() call.
 */
2243 2244 2245 2246 2247 2248
void QRhiCommandBuffer::setGraphicsPipeline(QRhiGraphicsPipeline *ps,
                                            QRhiShaderResourceBindings *srb)
{
    rhi->setGraphicsPipeline(this, ps, srb);
}

2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
/*!
    Records vertex input bindings.

    The index buffer used by subsequent drawIndexed() commands is specified by
    \a indexBuf, \a indexOffset, and \a indexFormat. \a indexBuf can be set to
    null when indexed drawing is not needed.

    Vertex buffer bindings are batched. \a startBinding specifies the first
    binding number. The recorded command then binds each buffer from \a
    bindings to the binding point \c{startBinding + i} where \c i is the index
    in \a bindings. Each element in \a bindings specifies a QRhiBuffer and an
    offset.

    Superfluous vertex input and index changes in the same pass are ignored
    automatically with most backends and therefore applications do not need to
    overoptimize to avoid calls to this function.

    \note This function can only be called inside a pass, meaning between a
    beginPass() end endPass() call.

    As a simple example, take a vertex shader with two inputs:

    \badcode
        layout(location = 0) in vec4 position;
        layout(location = 1) in vec3 color;
    \endcode

    and assume we have the data available in interleaved format, using only 2
    floats for position (so 5 floats per vertex: x, y, r, g, b). A QRhiGraphicsPipeline for
    this shader can then be created using the input layout:

    \badcode
        QRhiVertexInputLayout inputLayout;
        inputLayout.bindings = {
            { 5 * sizeof(float) }
        };
        inputLayout.attributes = {
            { 0, 0, QRhiVertexInputLayout::Attribute::Float2, 0 },
            { 0, 1, QRhiVertexInputLayout::Attribute::Float3, 2 * sizeof(float) }
        };
    \endcode

    Here there is one buffer binding (binding number 0), with two inputs
    referencing it. When recording the pass, once the pipeline is set, the
    vertex bindings can be specified simply like the following (using C++11
    initializer syntax), assuming vbuf is the QRhiBuffer with all the
    interleaved position+color data:

    \badcode
        cb->setVertexInput(0, { { vbuf, 0 } });
    \endcode
 */
2301 2302 2303 2304 2305 2306 2307
void QRhiCommandBuffer::setVertexInput(int startBinding, const QVector<VertexInput> &bindings,
                                       QRhiBuffer *indexBuf, quint32 indexOffset,
                                       IndexFormat indexFormat)
{
    rhi->setVertexInput(this, startBinding, bindings, indexBuf, indexOffset, indexFormat);
}

2308 2309 2310 2311 2312 2313 2314 2315 2316
/*!
    Records setting the active viewport rectangle specified in \a viewport.

    \note QRhi assumes OpenGL-style viewport coordinates, meaning x and y are
    bottom-left.

    \note This function can only be called inside a pass, meaning between a
    beginPass() end endPass() call.
 */
2317 2318 2319 2320 2321
void QRhiCommandBuffer::setViewport(const QRhiViewport &viewport)
{
    rhi->setViewport(this, viewport);
}

2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333
/*!
    Records setting the active scissor rectangle specified in \a scissor.

    This can only be called when the bound pipeline has
    QRhiGraphicsPipeline::UsesScissor set.

    \note QRhi assumes OpenGL-style viewport coordinates, meaning x and y are
    bottom-left.

    \note This function can only be called inside a pass, meaning between a
    beginPass() end endPass() call.
 */