qrhi.cpp 51.2 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 153 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

     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();

        srb = m_r->newShaderResourceBindings()
        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
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
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
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
322
    \brief Specifies a viewport rectangle.
Laszlo Agocs's avatar
Laszlo Agocs committed
323 324 325 326 327
 */

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

/*!
    \class QRhiVertexInputLayout
    \inmodule QtRhi
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
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
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
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
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
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
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
425
    \brief Describes a texture upload operation.
Laszlo Agocs's avatar
Laszlo Agocs committed
426 427 428 429 430
 */

/*!
    \class QRhiTextureUploadDescription::Layer
    \inmodule QtRhi
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
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
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
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
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
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
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
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
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
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
622
    \brief Renderbuffer resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
623 624
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
/*!
    \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
646 647 648
/*!
    \class QRhiRenderPassDescriptor
    \inmodule QtRhi
649
    \brief Render pass resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
650 651 652 653 654
 */

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

Laszlo Agocs's avatar
Laszlo Agocs committed
658 659 660 661 662 663 664 665 666 667
/*!
    \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
668 669 670
/*!
    \class QRhiTextureRenderTarget
    \inmodule QtRhi
671
    \brief Texture render target resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
672 673
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
/*!
    \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
691 692 693
/*!
    \class QRhiShaderResourceBindings
    \inmodule QtRhi
694
    \brief Encapsulates resources for making buffer, texture, sampler resources visible to shaders.
Laszlo Agocs's avatar
Laszlo Agocs committed
695 696 697 698 699
 */

/*!
    \class QRhiGraphicsPipeline
    \inmodule QtRhi
700
    \brief Graphics pipeline state resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
701 702
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 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 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
/*!
    \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
820 821 822
/*!
    \class QRhiGraphicsPipeline::TargetBlend
    \inmodule QtRhi
823
    \brief Describes the blend state for one color attachment.
Laszlo Agocs's avatar
Laszlo Agocs committed
824 825 826 827 828 829 830 831 832

    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
833 834 835 836 837
 */

/*!
    \class QRhiGraphicsPipeline::StencilOpState
    \inmodule QtRhi
838
    \brief Describes the stencil operation state.
Laszlo Agocs's avatar
Laszlo Agocs committed
839 840 841 842 843
 */

/*!
    \class QRhiSwapChain
    \inmodule QtRhi
844
    \brief Swapchain resource.
Laszlo Agocs's avatar
Laszlo Agocs committed
845 846
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
/*!
    \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
868 869 870
/*!
    \class QRhiCommandBuffer
    \inmodule QtRhi
871 872 873 874 875
    \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
Laszlo Agocs's avatar
Laszlo Agocs committed
876 877 878 879 880 881 882 883 884
    compeletely offscreen, initializing one via QRhi::beginOffscreenFrame().
 */

/*!
    \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
885 886 887 888 889
 */

/*!
    \class QRhiResourceUpdateBatch
    \inmodule QtRhi
890
    \brief Records upload and copy type of operations.
Laszlo Agocs's avatar
Laszlo Agocs committed
891 892
 */

Laszlo Agocs's avatar
Laszlo Agocs committed
893 894 895 896 897
/*!
    \enum QRhiResourceUpdateBatch::TexturePrepareFlag
    \internal
 */

898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
QRhiResource::QRhiResource(QRhiImplementation *rhi_)
    : rhi(rhi_)
{
}

QRhiResource::~QRhiResource()
{
}

void QRhiResource::releaseAndDestroy()
{
    release();
    delete this;
}

913 914 915 916 917 918 919 920 921 922
QByteArray QRhiResource::name() const
{
    return objectName;
}

void QRhiResource::setName(const QByteArray &name)
{
    objectName = name;
}

923 924
QRhiBuffer::QRhiBuffer(QRhiImplementation *rhi, Type type_, UsageFlags usage_, int size_)
    : QRhiResource(rhi),
Laszlo Agocs's avatar
Laszlo Agocs committed
925
      m_type(type_), m_usage(usage_), m_size(size_)
926 927 928 929
{
}

QRhiRenderBuffer::QRhiRenderBuffer(QRhiImplementation *rhi, Type type_, const QSize &pixelSize_,
Laszlo Agocs's avatar
Laszlo Agocs committed
930
                                   int sampleCount_, Flags flags_)
931
    : QRhiResource(rhi),
Laszlo Agocs's avatar
Laszlo Agocs committed
932
      m_type(type_), m_pixelSize(pixelSize_), m_sampleCount(sampleCount_), m_flags(flags_)
933 934 935
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
936 937
QRhiTexture::QRhiTexture(QRhiImplementation *rhi, Format format_, const QSize &pixelSize_,
                         int sampleCount_, Flags flags_)
938
    : QRhiResource(rhi),
Laszlo Agocs's avatar
Laszlo Agocs committed
939
      m_format(format_), m_pixelSize(pixelSize_), m_sampleCount(sampleCount_), m_flags(flags_)
940 941 942
{
}

943
const QRhiNativeHandles *QRhiTexture::nativeHandles()
944 945 946 947
{
    return nullptr;
}

948
bool QRhiTexture::buildFrom(const QRhiNativeHandles *src)
949 950 951 952 953
{
    Q_UNUSED(src);
    return false;
}

954 955 956 957
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
958 959
      m_magFilter(magFilter_), m_minFilter(minFilter_), m_mipmapMode(mipmapMode_),
      m_addressU(u_), m_addressV(v_), m_addressW(w_)
960 961 962
{
}

963
QRhiRenderPassDescriptor::QRhiRenderPassDescriptor(QRhiImplementation *rhi)
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
    : QRhiResource(rhi)
{
}

QRhiRenderTarget::QRhiRenderTarget(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

QRhiReferenceRenderTarget::QRhiReferenceRenderTarget(QRhiImplementation *rhi)
    : QRhiRenderTarget(rhi)
{
}

QRhiTextureRenderTarget::QRhiTextureRenderTarget(QRhiImplementation *rhi,
                                                 const QRhiTextureRenderTargetDescription &desc_,
                                                 Flags flags_)
    : QRhiRenderTarget(rhi),
Laszlo Agocs's avatar
Laszlo Agocs committed
982 983
      m_desc(desc_),
      m_flags(flags_)
984 985 986 987 988 989 990 991
{
}

QRhiShaderResourceBindings::QRhiShaderResourceBindings(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
992 993 994 995
/*!
    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
996
QRhiShaderResourceBinding QRhiShaderResourceBinding::uniformBuffer(
997 998
        int binding_, StageFlags stage_, QRhiBuffer *buf_)
{
Laszlo Agocs's avatar
Laszlo Agocs committed
999
    QRhiShaderResourceBinding b;
1000 1001 1002 1003 1004 1005 1006 1007 1008
    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
1009 1010 1011 1012 1013 1014 1015 1016
/*!
    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
1017
QRhiShaderResourceBinding QRhiShaderResourceBinding::uniformBuffer(
1018 1019 1020
        int binding_, StageFlags stage_, QRhiBuffer *buf_, int offset_, int size_)
{
    Q_ASSERT(size_ > 0);
Laszlo Agocs's avatar
Laszlo Agocs committed
1021
    QRhiShaderResourceBinding b;
1022 1023 1024 1025 1026 1027 1028 1029 1030
    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
1031 1032 1033 1034 1035
/*!
    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
1036
QRhiShaderResourceBinding QRhiShaderResourceBinding::sampledTexture(
1037 1038
        int binding_, StageFlags stage_, QRhiTexture *tex_, QRhiSampler *sampler_)
{
Laszlo Agocs's avatar
Laszlo Agocs committed
1039
    QRhiShaderResourceBinding b;
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 1067
    b.binding = binding_;
    b.stage = stage_;
    b.type = SampledTexture;
    b.stex.tex = tex_;
    b.stex.sampler = sampler_;
    return b;
}

QRhiGraphicsPipeline::QRhiGraphicsPipeline(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

QRhiSwapChain::QRhiSwapChain(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

QRhiCommandBuffer::QRhiCommandBuffer(QRhiImplementation *rhi)
    : QRhiResource(rhi)
{
}

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

1068 1069 1070 1071 1072
void QRhiImplementation::sendVMemStatsToProfiler()
{
    // nothing to do in the default implementation
}

1073
bool QRhiImplementation::isCompressedFormat(QRhiTexture::Format format) const
1074 1075 1076 1077 1078 1079 1080
{
    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,
1081 1082
                                              quint32 *bpl, quint32 *byteSize,
                                              QSize *blockDim) const
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
{
    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;
1196 1197
    if (blockDim)
        *blockDim = QSize(xdim, ydim);
1198 1199 1200
}

void QRhiImplementation::textureFormatInfo(QRhiTexture::Format format, const QSize &size,
1201
                                           quint32 *bpl, quint32 *byteSize) const
1202 1203
{
    if (isCompressedFormat(format)) {
1204
        compressedFormatInfo(format, size, bpl, byteSize, nullptr);
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
        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;
}

1241
// Approximate because it excludes subresource alignment or multisampling.
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
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
1257 1258 1259
/*!
    \internal
 */
1260 1261 1262 1263
QRhi::QRhi()
{
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1264 1265 1266
/*!
    Destructor. Destroys the backend and releases resources.
 */
1267 1268
QRhi::~QRhi()
{
1269 1270 1271 1272
    if (d) {
        d->destroy();
        delete d;
    }
1273 1274
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
/*!
    \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.
 */
1287
QRhi *QRhi::create(Implementation impl, QRhiInitParams *params, Flags flags)
1288
{
1289 1290
    QScopedPointer<QRhi> r(new QRhi);

1291
    switch (impl) {
Laszlo Agocs's avatar
Laszlo Agocs committed
1292 1293 1294
    case Null:
        r->d = new QRhiNull(params);
        break;
1295 1296 1297
    case Vulkan:
#if QT_CONFIG(vulkan)
        r->d = new QRhiVulkan(params);
1298
        break;
1299 1300 1301 1302 1303
#else
        qWarning("This build of Qt has no Vulkan support");
        break;
#endif
    case OpenGLES2:
1304
#ifndef QT_NO_OPENGL
1305
        r->d = new QRhiGles2(params);
1306
        break;
1307 1308 1309 1310
#else
        qWarning("This build of Qt has no OpenGL support");
        break;
#endif
1311 1312 1313
    case D3D11:
#ifdef Q_OS_WIN
        r->d = new QRhiD3D11(params);
1314
        break;
1315 1316 1317 1318 1319 1320 1321
#else
        qWarning("This platform has no Direct3D 11 support");
        break;
#endif
    case Metal:
#ifdef Q_OS_DARWIN
        r->d = new QRhiMetal(params);
1322
        break;
1323 1324 1325 1326 1327 1328 1329
#else
        qWarning("This platform has no Metal support");
        break;
#endif
    default:
        break;
    }
1330

1331 1332 1333 1334 1335 1336
    if (r->d) {
        if (flags.testFlag(EnableProfiling)) {
            QRhiProfilerPrivate *profD = QRhiProfilerPrivate::get(&r->d->profiler);
            profD->rhi = r.data();
            profD->rhiD = r->d;
        }
1337
        r->d->debugMarkers = flags.testFlag(EnableDebugMarkers);
1338 1339 1340
        if (r->d->create(flags))
            return r.take();
    }
1341

1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
    return nullptr;
}

QRhiResourceUpdateBatch::QRhiResourceUpdateBatch(QRhiImplementation *rhi)
    : d(new QRhiResourceUpdateBatchPrivate)
{
    d->q = this;
    d->rhi = rhi;
}

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

void QRhiResourceUpdateBatch::release()
{
    d->free();
}

1362 1363 1364 1365 1366
void QRhiResourceUpdateBatch::merge(QRhiResourceUpdateBatch *other)
{
    d->merge(other->d);
}

1367 1368 1369 1370 1371
void QRhiResourceUpdateBatch::updateDynamicBuffer(QRhiBuffer *buf, int offset, int size, const void *data)
{
    d->dynamicBufferUpdates.append({ buf, offset, size, data });
}

1372 1373 1374 1375 1376
void QRhiResourceUpdateBatch::uploadStaticBuffer(QRhiBuffer *buf, int offset, int size, const void *data)
{
    d->staticBufferUploads.append({ buf, offset, size, data });
}

1377 1378
void QRhiResourceUpdateBatch::uploadStaticBuffer(QRhiBuffer *buf, const void *data)
{
1379
    d->staticBufferUploads.append({ buf, 0, 0, data });
1380 1381
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1382
void QRhiResourceUpdateBatch::uploadTexture(QRhiTexture *tex, const QRhiTextureUploadDescription &desc)
1383 1384 1385 1386 1387 1388 1389 1390 1391
{
    d->textureUploads.append({ tex, desc });
}

void QRhiResourceUpdateBatch::uploadTexture(QRhiTexture *tex, const QImage &image)
{
    uploadTexture(tex, {{{{{ image }}}}});
}

1392 1393 1394 1395 1396
void QRhiResourceUpdateBatch::copyTexture(QRhiTexture *dst, QRhiTexture *src, const QRhiTextureCopyDescription &desc)
{
    d->textureCopies.append({ dst, src, desc });
}

1397 1398 1399 1400 1401
void QRhiResourceUpdateBatch::readBackTexture(const QRhiReadbackDescription &rb, QRhiReadbackResult *result)
{
    d->textureReadbacks.append({ rb, result });
}

1402 1403
void QRhiResourceUpdateBatch::generateMips(QRhiTexture *tex)
{
Laszlo Agocs's avatar
Laszlo Agocs committed
1404
    d->textureMipGens.append(QRhiResourceUpdateBatchPrivate::TextureMipGen(tex));
1405 1406
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1407 1408 1409
/*!
    \internal
 */
1410 1411 1412 1413 1414
void QRhiResourceUpdateBatch::prepareTextureForUse(QRhiTexture *tex, TexturePrepareFlags flags)
{
    d->texturePrepares.append({ tex, flags });
}

1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
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();
1451
    textureCopies.clear();
1452
    textureReadbacks.clear();
1453
    textureMipGens.clear();
1454
    texturePrepares.clear();
1455 1456 1457 1458 1459

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

1460 1461 1462 1463 1464
void QRhiResourceUpdateBatchPrivate::merge(QRhiResourceUpdateBatchPrivate *other)
{
    dynamicBufferUpdates += other->dynamicBufferUpdates;
    staticBufferUploads += other->staticBufferUploads;
    textureUploads += other->textureUploads;
1465
    textureCopies += other->textureCopies;
1466
    textureReadbacks += other->textureReadbacks;
1467
    textureMipGens += other->textureMipGens;
1468 1469 1470
    texturePrepares += other->texturePrepares;
}

1471 1472 1473 1474 1475
void QRhiCommandBuffer::resourceUpdate(QRhiResourceUpdateBatch *resourceUpdates)
{
    rhi->resourceUpdate(this, resourceUpdates);
}

1476 1477 1478 1479 1480
void QRhiCommandBuffer::beginPass(QRhiRenderTarget *rt,
                                  const QRhiColorClearValue &colorClearValue,
                                  const QRhiDepthStencilClearValue &depthStencilClearValue,
                                  QRhiResourceUpdateBatch *resourceUpdates)
{
1481
    rhi->beginPass(this, rt, colorClearValue, depthStencilClearValue, resourceUpdates);
1482 1483
}

1484
void QRhiCommandBuffer::endPass(QRhiResourceUpdateBatch *resourceUpdates)
1485
{
1486
    rhi->endPass(this, resourceUpdates);
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 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
}

void QRhiCommandBuffer::setGraphicsPipeline(QRhiGraphicsPipeline *ps,
                                            QRhiShaderResourceBindings *srb)
{
    rhi->setGraphicsPipeline(this, ps, srb);
}

void QRhiCommandBuffer::setVertexInput(int startBinding, const QVector<VertexInput> &bindings,
                                       QRhiBuffer *indexBuf, quint32 indexOffset,
                                       IndexFormat indexFormat)
{
    rhi->setVertexInput(this, startBinding, bindings, indexBuf, indexOffset, indexFormat);
}

void QRhiCommandBuffer::setViewport(const QRhiViewport &viewport)
{
    rhi->setViewport(this, viewport);
}

void QRhiCommandBuffer::setScissor(const QRhiScissor &scissor)
{
    rhi->setScissor(this, scissor);
}

void QRhiCommandBuffer::setBlendConstants(const QVector4D &c)
{
    rhi->setBlendConstants(this, c);
}

void QRhiCommandBuffer::setStencilRef(quint32 refValue)
{
    rhi->setStencilRef(this, refValue);
}

void QRhiCommandBuffer::draw(quint32 vertexCount,
                             quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
{
    rhi->draw(this, vertexCount, instanceCount, firstVertex, firstInstance);
}

void QRhiCommandBuffer::drawIndexed(quint32 indexCount,
                                    quint32 instanceCount, quint32 firstIndex,
                                    qint32 vertexOffset, quint32 firstInstance)
{
    rhi->drawIndexed(this, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
}

1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
void QRhiCommandBuffer::debugMarkBegin(const QByteArray &name)
{
    rhi->debugMarkBegin(this, name);
}

void QRhiCommandBuffer::debugMarkEnd()
{
    rhi->debugMarkEnd(this);
}

void QRhiCommandBuffer::debugMarkMsg(const QByteArray &msg)
{
    rhi->debugMarkMsg(this, msg);
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1550 1551 1552 1553
/*!
    \return the value (typically an offset) \a v aligned to the uniform buffer
    alignment given by by ubufAlignment().
 */
1554 1555 1556 1557 1558 1559
int QRhi::ubufAligned(int v) const
{
    const int byteAlign = ubufAlignment();
    return (v + byteAlign - 1) & ~(byteAlign - 1);
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1560 1561 1562
/*!
    \return the number of mip levels for a given \a size.
 */
1563 1564 1565 1566 1567
int QRhi::mipLevelsForSize(const QSize &size) const
{
    return qCeil(std::log2(qMax(size.width(), size.height()))) + 1;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1568 1569 1570 1571
/*!
    \return the texture image size for a given \a mipLevel, calculated based on
    the level 0 size given in \a baseLevelSize.
 */
1572 1573
QSize QRhi::sizeForMipLevel(int mipLevel, const QSize &baseLevelSize) const
{
1574 1575
    const int w = qFloor(float(qMax(1, baseLevelSize.width() >> mipLevel)));
    const int h = qFloor(float(qMax(1, baseLevelSize.height() >> mipLevel)));
1576 1577 1578
    return QSize(w, h);
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1579 1580 1581 1582 1583
/*!
    \return \c true if the underlying graphics API has Y up in the framebuffer.

    In practice this is \c true for OpenGL only.
 */
1584 1585 1586 1587 1588
bool QRhi::isYUpInFramebuffer() const
{
    return d->isYUpInFramebuffer();
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
/*!
    Returns a matrix that can be used allow applications keep using
    OpenGL-targeted vertex data and projection matrices (for example, the ones
    generated by QMatrix4x4::perspective()) regardless of the backed. Once
    \c{this_matrix * mvp} is used instead of just \c mvp, vertex data with Y up
    and viewports with depth range 0 - 1 can be used without considering what
    backend and so graphics API is going to be used at run time.

    See
    \l{https://matthewwellings.com/blog/the-new-vulkan-coordinate-system/}{this
    page} for a discussion of the topic from Vulkan perspective.
 */
1601 1602 1603 1604 1605
QMatrix4x4 QRhi::clipSpaceCorrMatrix() const
{
    return d->clipSpaceCorrMatrix();
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1606 1607 1608 1609 1610 1611
/*!
    \return \c true if the specified texture \a format modified by \a flags is
    supported.

    The query is supported both for uncompressed and compressed formats.
 */
1612
bool QRhi::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const
1613
{
1614
    return d->isTextureFormatSupported(format, flags);
1615 1616
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1617 1618 1619
/*!
    \return \c true if the specified \a feature is supported
 */
1620 1621 1622 1623 1624
bool QRhi::isFeatureSupported(QRhi::Feature feature) const
{
    return d->isFeatureSupported(feature);
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1625 1626 1627 1628 1629 1630
/*!
    \return the value for the specified resource \a limit.

    The values are expected to be queried by the backends upon initialization,
    meaning calling this function is a light operation.
 */
1631 1632 1633 1634 1635
int QRhi::resourceSizeLimit(ResourceSizeLimit limit) const
{
    return d->resourceSizeLimit(limit);
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
/*!
    \return a pointer to the backend-specific collection of native objects
    for the device, context, and similar concepts used by the backend.

    Cast to QRhiVulkanNativeHandles, QRhiD3D11NativeHandles,
    QRhiGles2NativeHandles, QRhiMetalNativeHandles as appropriate.

    \note No ownership is transfered, neither for the returned pointer nor for
    any native objects.
 */
1646
const QRhiNativeHandles *QRhi::nativeHandles()
1647 1648 1649 1650
{
    return d->nativeHandles();
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1651 1652 1653 1654 1655 1656 1657
/*!
    \return the associated QRhiProfiler instance.

    An instance is always available for each QRhi, but it is not very useful
    without EnableProfiling because no data is collected without setting the
    flag upon creation.
  */
1658
QRhiProfiler *QRhi::profiler()
1659 1660 1661 1662
{
    return &d->profiler;
}

1663
QRhiGraphicsPipeline *QRhi::newGraphicsPipeline()
1664 1665 1666 1667
{
    return d->createGraphicsPipeline();
}

1668
QRhiShaderResourceBindings *QRhi::newShaderResourceBindings()
1669 1670 1671 1672
{
    return d->createShaderResourceBindings();
}

1673 1674 1675
QRhiBuffer *QRhi::newBuffer(QRhiBuffer::Type type,
                            QRhiBuffer::UsageFlags usage,
                            int size)
1676 1677 1678 1679
{
    return d->createBuffer(type, usage, size);
}

1680 1681 1682
QRhiRenderBuffer *QRhi::newRenderBuffer(QRhiRenderBuffer::Type type,
                                        const QSize &pixelSize,
                                        int sampleCount,
Laszlo Agocs's avatar
Laszlo Agocs committed
1683
                                        QRhiRenderBuffer::Flags flags)
1684
{
Laszlo Agocs's avatar
Laszlo Agocs committed
1685
    return d->createRenderBuffer(type, pixelSize, sampleCount, flags);
1686 1687
}

1688 1689
QRhiTexture *QRhi::newTexture(QRhiTexture::Format format,
                              const QSize &pixelSize,
Laszlo Agocs's avatar
Laszlo Agocs committed
1690
                              int sampleCount,
1691
                              QRhiTexture::Flags flags)
1692
{
Laszlo Agocs's avatar
Laszlo Agocs committed
1693
    return d->createTexture(format, pixelSize, sampleCount, flags);
1694 1695
}

1696 1697 1698
QRhiSampler *QRhi::newSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter,
                              QRhiSampler::Filter mipmapMode,
                              QRhiSampler:: AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
1699 1700 1701 1702
{
    return d->createSampler(magFilter, minFilter, mipmapMode, u, v, w);
}

1703 1704
QRhiTextureRenderTarget *QRhi::newTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc,
                                                      QRhiTextureRenderTarget::Flags flags)
1705 1706 1707 1708
{
    return d->createTextureRenderTarget(desc, flags);
}

1709
QRhiSwapChain *QRhi::newSwapChain()
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
{
    return d->createSwapChain();
}

QRhi::FrameOpResult QRhi::beginFrame(QRhiSwapChain *swapChain)
{
    return d->beginFrame(swapChain);
}

QRhi::FrameOpResult QRhi::endFrame(QRhiSwapChain *swapChain)
{
    return d->endFrame(swapChain);
}

1724 1725 1726 1727 1728
QRhi::FrameOpResult QRhi::beginOffscreenFrame(QRhiCommandBuffer **cb)
{
    return d->beginOffscreenFrame(cb);
}

1729
QRhi::FrameOpResult QRhi::endOffscreenFrame()
1730
{
1731 1732 1733 1734 1735 1736
    return d->endOffscreenFrame();
}

QRhi::FrameOpResult QRhi::finish()
{
    return d->finish();
1737 1738
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1739 1740 1741 1742 1743 1744 1745 1746 1747
/*!
    \return the list of supported sample counts.

    A typical example would be (1, 2, 4, 8).

    With some backend this list of supported values is fixed in advance, while
    with some others the (physical) device properties indicate what is
    supported at run time.
 */
1748 1749 1750 1751 1752
QVector<int> QRhi::supportedSampleCounts() const
{
    return d->supportedSampleCounts();
}

Laszlo Agocs's avatar
Laszlo Agocs committed
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
/*!
    \return the minimum uniform buffer offset alignment in bytes. This is
    typically 256.

    Attempting to bind a uniform buffer region with an offset not aligned to
    this value will lead to failures depending on the backend and the
    underlying graphics API.

    \sa ubufAligned()
 */
1763 1764 1765 1766 1767 1768
int QRhi::ubufAlignment() const
{
    return d->ubufAlignment();
}

QT_END_NAMESPACE