qrhi.h 45.7 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 40 41 42 43 44 45 46 47
/****************************************************************************
**
** 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$
**
****************************************************************************/

#ifndef QRHI_H
#define QRHI_H

#include <QtRhi/qtrhiglobal.h>
#include <QVector4D>
#include <QVector2D>
#include <QSize>
#include <QMatrix4x4>
#include <QVector>
#include <QImage>
#include <QtShaderTools/QBakedShader>
48
#include <functional>
49 50 51 52

QT_BEGIN_NAMESPACE

class QWindow;
Laszlo Agocs's avatar
Laszlo Agocs committed
53 54 55 56 57
class QRhiImplementation;
class QRhiBuffer;
class QRhiRenderBuffer;
class QRhiTexture;
class QRhiSampler;
58 59
class QRhiCommandBuffer;
class QRhiResourceUpdateBatch;
Laszlo Agocs's avatar
Laszlo Agocs committed
60
struct QRhiResourceUpdateBatchPrivate;
61
class QRhiProfiler;
62

63 64 65 66 67 68 69 70
// C++ object ownership rules:
//   1. new*() and create() return value owned by the caller.
//   2. next*() return value not owned by the caller.
//   3. Passing a pointer via set*() or the structs does not transfer ownership.
//   4. release() does not destroy the C++ object. releaseAndDestroy() does, and is equivalent to o->release(); delete o;
//
// Graphics resource ownership rules:
//   1. new*() does not create underlying graphics resources. build() does.
71 72
//   2. Except: new*Descriptor() implicitly "builds". (no build() for QRhiRenderPassDescriptor f.ex.)
//   3. release() schedules graphics resources for destruction. The C++ object is reusable immediately via build(), or can be destroyed.
Laszlo Agocs's avatar
Laszlo Agocs committed
73 74
//   4. build() on an already built object calls release() implicitly. Except swapchains. (buildOrResize() - special semantics)
//   5. Ownership of resources imported (QRhi*InitParams or buildFrom()) or exported (nativeHandles()) is never taken or given away.
75 76 77 78
//
// Other:
//   1. QRhiResourceUpdateBatch manages no graphics resources underneath. beginPass() implicitly calls release() on the batch.

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
struct Q_RHI_EXPORT QRhiColorClearValue
{
    QRhiColorClearValue() : rgba(0, 0, 0, 1) { }
    explicit QRhiColorClearValue(const QVector4D &rgba_) : rgba(rgba_) { }
    QRhiColorClearValue(float r, float g, float b, float a) : rgba(r, g, b, a) { }
    QVector4D rgba;
};

Q_DECLARE_TYPEINFO(QRhiColorClearValue, Q_MOVABLE_TYPE);

struct Q_RHI_EXPORT QRhiDepthStencilClearValue
{
    QRhiDepthStencilClearValue() : d(1), s(0) { }
    QRhiDepthStencilClearValue(float d_, quint32 s_) : d(d_), s(s_) { }
    float d;
    quint32 s;
};

Q_DECLARE_TYPEINFO(QRhiDepthStencilClearValue, Q_MOVABLE_TYPE);

struct Q_RHI_EXPORT QRhiViewport
{
Laszlo Agocs's avatar
Laszlo Agocs committed
101 102 103 104 105
    QRhiViewport()
        : r(0, 0, 1280, 720), minDepth(0), maxDepth(1)
    { }
    // x,y is bottom-left, like in OpenGL, regardless of what isYUpInFramebuffer() says.
    // Depth range defaults to 0..1. See clipSpaceCorrMatrix().
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
    QRhiViewport(float x, float y, float w, float h, float minDepth_ = 0.0f, float maxDepth_ = 1.0f)
        : r(x, y, w, h), minDepth(minDepth_), maxDepth(maxDepth_)
    { }
    QVector4D r;
    float minDepth;
    float maxDepth;
};

Q_DECLARE_TYPEINFO(QRhiViewport, Q_MOVABLE_TYPE);

struct Q_RHI_EXPORT QRhiScissor
{
    QRhiScissor() { }
    // x,y is bottom-left, like in OpenGL, regardless of what isYUpInFramebuffer() says
    QRhiScissor(int x, int y, int w, int h)
        : r(x, y, w, h)
    { }
    QVector4D r;
};

Q_DECLARE_TYPEINFO(QRhiScissor, Q_MOVABLE_TYPE);

struct Q_RHI_EXPORT QRhiVertexInputLayout
{
    struct Q_RHI_EXPORT Binding {
        enum Classification {
            PerVertex,
            PerInstance
        };
        Binding() { }
136 137
        Binding(quint32 stride_, Classification cls = PerVertex, int stepRate = 1)
            : stride(stride_), classification(cls), instanceStepRate(stepRate)
138
        { }
Laszlo Agocs's avatar
Laszlo Agocs committed
139
        quint32 stride; // must be a multiple of 4
140
        Classification classification;
141
        int instanceStepRate;
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
    };

    struct Q_RHI_EXPORT Attribute {
        enum Format {
            Float4,
            Float3,
            Float2,
            Float,
            UNormByte4,
            UNormByte2,
            UNormByte
        };
        Attribute() { }
        Attribute(int binding_, int location_, Format format_, quint32 offset_)
            : binding(binding_), location(location_), format(format_), offset(offset_)
        { }
        int binding;
        // With HLSL we assume the vertex shader uses TEXCOORD<location> as the
        // semantic for each input. Hence no separate semantic name and index.
        int location;
        Format format;
        quint32 offset;
    };

    QVector<Binding> bindings; // slots
    QVector<Attribute> attributes;
};

Q_DECLARE_TYPEINFO(QRhiVertexInputLayout::Binding, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(QRhiVertexInputLayout::Attribute, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(QRhiVertexInputLayout, Q_MOVABLE_TYPE);

struct Q_RHI_EXPORT QRhiGraphicsShaderStage
{
    enum Type {
        Vertex,
        Fragment,
        TessellationControl, // Hull
        TessellationEvaluation // Domain
181
        // yes, no geometry shaders (Metal does not have them)
182 183 184 185 186 187 188 189 190 191 192 193 194
    };

    QRhiGraphicsShaderStage() { }
    QRhiGraphicsShaderStage(Type type_, const QBakedShader &shader_)
        : type(type_), shader(shader_)
    { }

    Type type;
    QBakedShader shader;
};

Q_DECLARE_TYPEINFO(QRhiGraphicsShaderStage, Q_MOVABLE_TYPE);

Laszlo Agocs's avatar
Laszlo Agocs committed
195 196 197 198 199 200 201 202 203 204
struct Q_RHI_EXPORT QRhiShaderResourceBinding
{
    enum Type {
        UniformBuffer,
        SampledTexture
    };

    enum StageFlag {
        VertexStage = 1 << 0,
        FragmentStage = 1 << 1,
205 206
        TessellationControlStage = 1 << 2,
        TessellationEvaluationStage = 1 << 3
Laszlo Agocs's avatar
Laszlo Agocs committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    };
    Q_DECLARE_FLAGS(StageFlags, StageFlag)

    static QRhiShaderResourceBinding uniformBuffer(int binding_, StageFlags stage_, QRhiBuffer *buf_);

    // Bind a region only. Up to the user to ensure offset is aligned to ubufAlignment.
    static QRhiShaderResourceBinding uniformBuffer(int binding_, StageFlags stage_, QRhiBuffer *buf_, int offset_, int size_);

    static QRhiShaderResourceBinding sampledTexture(int binding_, StageFlags stage_, QRhiTexture *tex_, QRhiSampler *sampler_);

    int binding;
    StageFlags stage;
    Type type;
    struct UniformBufferData {
        QRhiBuffer *buf;
        int offset;
        int maybeSize;
    };
    struct SampledTextureData {
        QRhiTexture *tex;
        QRhiSampler *sampler;
    };
    union {
        UniformBufferData ubuf;
        SampledTextureData stex;
    };
};

Q_DECLARE_OPERATORS_FOR_FLAGS(QRhiShaderResourceBinding::StageFlags)
Q_DECLARE_TYPEINFO(QRhiShaderResourceBinding, Q_MOVABLE_TYPE);

struct Q_RHI_EXPORT QRhiTextureRenderTargetDescription
{
    struct Q_RHI_EXPORT ColorAttachment {
        ColorAttachment() { }
242
        // either a texture or a renderbuffer
Laszlo Agocs's avatar
Laszlo Agocs committed
243
        ColorAttachment(QRhiTexture *texture_) : texture(texture_) { }
244 245
        ColorAttachment(QRhiRenderBuffer *renderBuffer_) : renderBuffer(renderBuffer_) { }

Laszlo Agocs's avatar
Laszlo Agocs committed
246
        QRhiTexture *texture = nullptr;
247
        QRhiRenderBuffer *renderBuffer = nullptr;
248 249

        // for texture
Laszlo Agocs's avatar
Laszlo Agocs committed
250
        int layer = 0; // face (0..5) for cubemaps
251 252 253 254 255 256 257 258 259 260 261
        int level = 0; // only when non-multisample

        // When texture or renderBuffer is multisample. Optional. When set,
        // samples are resolved into this non-multisample texture. Note that
        // the msaa data may not be written out at all in this case. This is
        // the only way to get a non-msaa texture from an msaa render target as
        // we do not have an explicit resolve operation because it does not
        // exist in some APIs and would not be efficient with tiled GPUs anyways.
        QRhiTexture *resolveTexture = nullptr;
        int resolveLayer = 0; // unused for now since cubemaps cannot be multisample
        int resolveLevel = 0;
Laszlo Agocs's avatar
Laszlo Agocs committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275
    };

    QRhiTextureRenderTargetDescription()
    { }
    QRhiTextureRenderTargetDescription(const ColorAttachment &colorAttachment)
    { colorAttachments.append(colorAttachment); }
    QRhiTextureRenderTargetDescription(const ColorAttachment &colorAttachment, QRhiRenderBuffer *depthStencilBuffer_)
        : depthStencilBuffer(depthStencilBuffer_)
    { colorAttachments.append(colorAttachment); }
    QRhiTextureRenderTargetDescription(const ColorAttachment &colorAttachment, QRhiTexture *depthTexture_)
        : depthTexture(depthTexture_)
    { colorAttachments.append(colorAttachment); }

    QVector<ColorAttachment> colorAttachments;
276
    // depth-stencil is is a renderbuffer, a texture, or none
Laszlo Agocs's avatar
Laszlo Agocs committed
277 278 279 280 281 282 283 284 285 286 287 288
    QRhiRenderBuffer *depthStencilBuffer = nullptr;
    QRhiTexture *depthTexture = nullptr;
};

Q_DECLARE_TYPEINFO(QRhiTextureRenderTargetDescription::ColorAttachment, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(QRhiTextureRenderTargetDescription, Q_MOVABLE_TYPE);

struct Q_RHI_EXPORT QRhiTextureUploadDescription
{
    struct Q_RHI_EXPORT Layer {
        struct Q_RHI_EXPORT MipLevel {
            MipLevel() { }
289
            // either a QImage or compressed data (not both)
Laszlo Agocs's avatar
Laszlo Agocs committed
290
            MipLevel(const QImage &image_) : image(image_) { }
291
            MipLevel(const QByteArray &compressedData_) : compressedData(compressedData_) { }
292

Laszlo Agocs's avatar
Laszlo Agocs committed
293
            QImage image;
294
            QByteArray compressedData;
295

296
            QPoint destinationTopLeft;
297 298 299 300 301 302 303 304 305 306 307 308 309 310

            // Empty = entire subresource. For uncompressed this then means the
            // size of the source image must match the subresource. When
            // non-empty, this size is used.
            //
            // Works for compressed as well, but the first compressed upload
            // must always match the subresource size (and sourceSize can be
            // left unset) due to gfx api limitations with some backends.
            QSize sourceSize;

            // This is only supported for uncompressed. Setting sourceSize or
            // sourceTopLeft may trigger a QImage copy internally (depending on
            // the format and the gfx api).
            QPoint sourceTopLeft;
Laszlo Agocs's avatar
Laszlo Agocs committed
311
        };
312

Laszlo Agocs's avatar
Laszlo Agocs committed
313 314 315 316
        Layer() { }
        Layer(const QVector<MipLevel> &mipImages_) : mipImages(mipImages_) { }
        QVector<MipLevel> mipImages;
    };
317

Laszlo Agocs's avatar
Laszlo Agocs committed
318 319 320 321 322 323 324 325 326
    QRhiTextureUploadDescription() { }
    QRhiTextureUploadDescription(const QVector<Layer> &layers_) : layers(layers_) { }
    QVector<Layer> layers; // 6 layers for cubemaps, 1 otherwise
};

Q_DECLARE_TYPEINFO(QRhiTextureUploadDescription::Layer::MipLevel, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(QRhiTextureUploadDescription::Layer, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(QRhiTextureUploadDescription, Q_MOVABLE_TYPE);

327 328
struct Q_RHI_EXPORT QRhiTextureCopyDescription
{
329
    QSize pixelSize; // empty = entire subresource
330 331 332

    int sourceLayer = 0;
    int sourceLevel = 0;
Laszlo Agocs's avatar
Laszlo Agocs committed
333
    QPoint sourceTopLeft;
334 335 336

    int destinationLayer = 0;
    int destinationLevel = 0;
Laszlo Agocs's avatar
Laszlo Agocs committed
337
    QPoint destinationTopLeft;
338 339 340 341
};

Q_DECLARE_TYPEINFO(QRhiTextureCopyDescription, Q_MOVABLE_TYPE);

342
struct Q_RHI_EXPORT QRhiReadbackDescription
Laszlo Agocs's avatar
Laszlo Agocs committed
343
{
344
    QRhiReadbackDescription() { } // source is the back buffer of the swapchain of the current frame (if the swapchain supports readback)
345
    QRhiReadbackDescription(QRhiTexture *texture_) : texture(texture_) { } // source is the specified texture
346 347
    // Note that reading back an msaa image is only supported for swapchains.
    // Multisample textures cannot be read back.
348

349 350 351
    QRhiTexture *texture = nullptr;
    int layer = 0;
    int level = 0;
Laszlo Agocs's avatar
Laszlo Agocs committed
352 353
};

354 355
Q_DECLARE_TYPEINFO(QRhiReadbackDescription, Q_MOVABLE_TYPE);

356 357 358 359
struct Q_RHI_EXPORT QRhiNativeHandles
{
};

360 361 362 363
class Q_RHI_EXPORT QRhiResource
{
public:
    virtual ~QRhiResource();
364

365 366 367
    virtual void release() = 0;
    void releaseAndDestroy();

368 369
    // This has two uses: to get names visible in graphics debugging tools and
    // in the profiling output. Regarding the former, the name is ignored when
370 371 372
    // DebugMarkers are not supported, and may be ignored when
    // EnableDebugMarkers is not set. May also be ignored for objects other
    // than buffers, renderbuffers, and textures, depending on the backend.
373 374 375
    QByteArray name() const;
    void setName(const QByteArray &name);

376 377 378
protected:
    QRhiResource(QRhiImplementation *rhi_);
    Q_DISABLE_COPY(QRhiResource)
379 380
    QRhiImplementation *rhi = nullptr;
    QByteArray objectName;
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
};

class Q_RHI_EXPORT QRhiBuffer : public QRhiResource
{
public:
    enum Type {
        Immutable, // data never changes after initial upload - under the hood typically in device local (GPU) memory
        Static,    // data changes infrequently - under the hood typically device local and updated via a separate, host visible staging buffer
        Dynamic    // data changes frequently - under the hood typically host visible
    };

    enum UsageFlag {
        VertexBuffer = 1 << 0,
        IndexBuffer = 1 << 1,
        UniformBuffer = 1 << 2
    };
    Q_DECLARE_FLAGS(UsageFlags, UsageFlag)

Laszlo Agocs's avatar
Laszlo Agocs committed
399 400 401 402 403 404
    Type type() const { return m_type; }
    void setType(Type t) { m_type = t; }

    UsageFlags usage() const { return m_usage; }
    void setUsage(UsageFlags u) { m_usage = u; }

405 406
    // no restrictions here, up to the backend to round up if needed (that
    // won't be visible in the user-provided size reported here)
Laszlo Agocs's avatar
Laszlo Agocs committed
407 408
    int size() const { return m_size; }
    void setSize(int sz) { m_size = sz; }
409 410 411 412 413

    virtual bool build() = 0;

protected:
    QRhiBuffer(QRhiImplementation *rhi, Type type_, UsageFlags usage_, int size_);
Laszlo Agocs's avatar
Laszlo Agocs committed
414 415
    Type m_type;
    UsageFlags m_usage;
416
    int m_size;
Laszlo Agocs's avatar
Laszlo Agocs committed
417
    void *m_reserved;
418 419 420 421 422 423 424 425 426
};

Q_DECLARE_OPERATORS_FOR_FLAGS(QRhiBuffer::UsageFlags)

class Q_RHI_EXPORT QRhiTexture : public QRhiResource
{
public:
    enum Flag {
        RenderTarget = 1 << 0,
427
        ChangesFrequently = 1 << 1, // hint for backend to keep staging resources around
428
        CubeMap = 1 << 2,
429
        MipMapped = 1 << 3,
430
        sRGB = 1 << 4,
431
        UsedAsTransferSource = 1 << 5, // will (also) be used as the source of a copy or readback
432
        UsedWithGenerateMips = 1 << 6
433 434 435 436
    };
    Q_DECLARE_FLAGS(Flags, Flag)

    enum Format {
437 438
        UnknownFormat,

439 440 441 442 443 444
        RGBA8,
        BGRA8,
        R8,
        R16,

        D16,
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
        D32,

        BC1,
        BC2,
        BC3,
        BC4,
        BC5,
        BC6H,
        BC7,

        ETC2_RGB8,
        ETC2_RGB8A1,
        ETC2_RGBA8,

        ASTC_4x4,
        ASTC_5x4,
        ASTC_5x5,
        ASTC_6x5,
        ASTC_6x6,
        ASTC_8x5,
        ASTC_8x6,
        ASTC_8x8,
        ASTC_10x5,
        ASTC_10x6,
        ASTC_10x8,
        ASTC_10x10,
        ASTC_12x10,
        ASTC_12x12
473 474
    };

Laszlo Agocs's avatar
Laszlo Agocs committed
475 476 477 478 479 480 481 482
    Format format() const { return m_format; }
    void setFormat(Format fmt) { m_format = fmt; }

    QSize pixelSize() const { return m_pixelSize; }
    void setPixelSize(const QSize &sz) { m_pixelSize = sz; }

    Flags flags() const { return m_flags; }
    void setFlags(Flags f) { m_flags = f; }
483

Laszlo Agocs's avatar
Laszlo Agocs committed
484 485 486
    int sampleCount() const { return m_sampleCount; }
    void setSampleCount(int s) { m_sampleCount = s; }

487 488
    virtual bool build() = 0;

489 490
    // Returns a ptr to a QRhi<backend>TextureNativeHandles struct.
    // Ownership of the native objects is not transfered.
491
    virtual const QRhiNativeHandles *nativeHandles();
492 493 494 495 496

    // 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.
497
    virtual bool buildFrom(const QRhiNativeHandles *src);
498

499
protected:
Laszlo Agocs's avatar
Laszlo Agocs committed
500 501
    QRhiTexture(QRhiImplementation *rhi, Format format_, const QSize &pixelSize_,
                int sampleCount_, Flags flags_);
Laszlo Agocs's avatar
Laszlo Agocs committed
502 503
    Format m_format;
    QSize m_pixelSize;
Laszlo Agocs's avatar
Laszlo Agocs committed
504
    int m_sampleCount;
Laszlo Agocs's avatar
Laszlo Agocs committed
505
    Flags m_flags;
Laszlo Agocs's avatar
Laszlo Agocs committed
506
    void *m_reserved;
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
};

Q_DECLARE_OPERATORS_FOR_FLAGS(QRhiTexture::Flags)

class Q_RHI_EXPORT QRhiSampler : public QRhiResource
{
public:
    enum Filter {
        None, // for mipmapMode only
        Nearest,
        Linear
    };

    enum AddressMode {
        Repeat,
        ClampToEdge,
        Border,
        Mirror,
        MirrorOnce
    };

Laszlo Agocs's avatar
Laszlo Agocs committed
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
    Filter magFilter() const { return m_magFilter; }
    void setMagFilter(Filter f) { m_magFilter = f; }

    Filter minFilter() const { return m_minFilter; }
    void setMinFilter(Filter f) { m_minFilter = f; }

    Filter mipmapMode() const { return m_mipmapMode; }
    void setMipmapMode(Filter f) { m_mipmapMode = f; }

    AddressMode addressU() const { return m_addressU; }
    void setAddressU(AddressMode mode) { m_addressU = mode; }

    AddressMode addressV() const { return m_addressV; }
    void setAddressV(AddressMode mode) { m_addressV = mode; }

    AddressMode addressW() const { return m_addressW; }
    void setAddressW(AddressMode mode) { m_addressW = mode; }
545 546 547 548 549 550 551

    virtual bool build() = 0;

protected:
    QRhiSampler(QRhiImplementation *rhi,
                Filter magFilter_, Filter minFilter_, Filter mipmapMode_,
                AddressMode u_, AddressMode v_, AddressMode w_);
Laszlo Agocs's avatar
Laszlo Agocs committed
552 553 554 555 556 557 558
    Filter m_magFilter;
    Filter m_minFilter;
    Filter m_mipmapMode;
    AddressMode m_addressU;
    AddressMode m_addressV;
    AddressMode m_addressW;
    void *m_reserved;
559 560
};

Laszlo Agocs's avatar
Laszlo Agocs committed
561 562 563 564 565 566 567 568 569
class Q_RHI_EXPORT QRhiRenderBuffer : public QRhiResource
{
public:
    enum Type {
        DepthStencil,
        Color
    };

    enum Flag {
570
        UsedWithSwapChainOnly = 1 << 0 // use implicit winsys buffers, don't create anything (GL)
Laszlo Agocs's avatar
Laszlo Agocs committed
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
    };
    Q_DECLARE_FLAGS(Flags, Flag)

    Type type() const { return m_type; }
    void setType(Type t) { m_type = t; }

    QSize pixelSize() const { return m_pixelSize; }
    void setPixelSize(const QSize &sz) { m_pixelSize = sz; }

    int sampleCount() const { return m_sampleCount; }
    void setSampleCount(int s) { m_sampleCount = s; }

    Flags flags() const { return m_flags; }
    void setFlags(Flags h) { m_flags = h; }

    virtual bool build() = 0;

    virtual QRhiTexture::Format backingFormat() const = 0;

protected:
    QRhiRenderBuffer(QRhiImplementation *rhi, Type type_, const QSize &pixelSize_,
                     int sampleCount_, Flags flags_);
    Type m_type;
    QSize m_pixelSize;
    int m_sampleCount;
    Flags m_flags;
    void *m_reserved;
};

Q_DECLARE_OPERATORS_FOR_FLAGS(QRhiRenderBuffer::Flags)

602
class Q_RHI_EXPORT QRhiRenderPassDescriptor : public QRhiResource
603 604
{
protected:
605
    QRhiRenderPassDescriptor(QRhiImplementation *rhi);
Laszlo Agocs's avatar
Laszlo Agocs committed
606
    void *m_reserved;
607 608 609 610 611 612 613 614 615 616 617 618
};

class Q_RHI_EXPORT QRhiRenderTarget : public QRhiResource
{
public:
    enum Type {
        RtRef,
        RtTexture
    };

    virtual Type type() const = 0;
    virtual QSize sizeInPixels() const = 0;
Laszlo Agocs's avatar
Laszlo Agocs committed
619
    virtual float devicePixelRatio() const = 0;
Laszlo Agocs's avatar
Laszlo Agocs committed
620

621 622
    QRhiRenderPassDescriptor *renderPassDescriptor() const { return m_renderPassDesc; }
    void setRenderPassDescriptor(QRhiRenderPassDescriptor *desc) { m_renderPassDesc = desc; }
623 624 625

protected:
    QRhiRenderTarget(QRhiImplementation *rhi);
626
    QRhiRenderPassDescriptor *m_renderPassDesc = nullptr;
Laszlo Agocs's avatar
Laszlo Agocs committed
627
    void *m_reserved;
628 629 630 631 632 633
};

class Q_RHI_EXPORT QRhiTextureRenderTarget : public QRhiRenderTarget
{
public:
    enum Flag {
634 635
        // the load-not-clear request is baked into the resources under the rpd
        // with some backends so it cannot be more dynamic than this
636 637
        PreserveColorContents = 1 << 0,
        PreserveDepthStencilContents = 1 << 1
638 639 640
    };
    Q_DECLARE_FLAGS(Flags, Flag)

Laszlo Agocs's avatar
Laszlo Agocs committed
641 642
    QRhiTextureRenderTargetDescription description() const { return m_desc; }
    void setDescription(const QRhiTextureRenderTargetDescription &desc) { m_desc = desc; }
643

Laszlo Agocs's avatar
Laszlo Agocs committed
644 645 646
    Flags flags() const { return m_flags; }
    void setFlags(Flags f) { m_flags = f; }

Laszlo Agocs's avatar
Laszlo Agocs committed
647
    // To be called before build() with description and flags set.
648 649
    // Textures in desc must already be built.
    // Note setRenderPassDescriptor() in the base class, that must still be called afterwards (but before build()).
650
    virtual QRhiRenderPassDescriptor *newCompatibleRenderPassDescriptor() = 0;
Laszlo Agocs's avatar
Laszlo Agocs committed
651

Laszlo Agocs's avatar
Laszlo Agocs committed
652
    // as usual, textures in desc must be built before calling build() on the rt
653 654 655 656
    virtual bool build() = 0;

protected:
    QRhiTextureRenderTarget(QRhiImplementation *rhi, const QRhiTextureRenderTargetDescription &desc_, Flags flags_);
Laszlo Agocs's avatar
Laszlo Agocs committed
657 658
    QRhiTextureRenderTargetDescription m_desc;
    Flags m_flags;
659 660 661 662 663 664 665
};

Q_DECLARE_OPERATORS_FOR_FLAGS(QRhiTextureRenderTarget::Flags)

class Q_RHI_EXPORT QRhiShaderResourceBindings : public QRhiResource
{
public:
Laszlo Agocs's avatar
Laszlo Agocs committed
666 667
    QVector<QRhiShaderResourceBinding> bindings() const { return m_bindings; }
    void setBindings(const QVector<QRhiShaderResourceBinding> &b) { m_bindings = b; }
668 669 670 671 672

    virtual bool build() = 0;

protected:
    QRhiShaderResourceBindings(QRhiImplementation *rhi);
Laszlo Agocs's avatar
Laszlo Agocs committed
673 674
    QVector<QRhiShaderResourceBinding> m_bindings;
    void *m_reserved;
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 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
};

class Q_RHI_EXPORT QRhiGraphicsPipeline : public QRhiResource
{
public:
    enum Flag {
        UsesBlendConstants = 1 << 0,
        UsesStencilRef = 1 << 1,
        UsesScissor = 1 << 2
    };
    Q_DECLARE_FLAGS(Flags, Flag)

    enum Topology {
        Triangles,
        TriangleStrip,
        Lines,
        LineStrip,
        Points
    };

    enum CullMode { // not a bitmask since some apis use a mask, some don't
        None,
        Front,
        Back
    };

    enum FrontFace {
        CCW,
        CW
    };

    enum ColorMaskComponent {
        R = 1 << 0,
        G = 1 << 1,
        B = 1 << 2,
        A = 1 << 3
    };
    Q_DECLARE_FLAGS(ColorMask, ColorMaskComponent)

    enum BlendFactor {
        Zero,
        One,
        SrcColor,
        OneMinusSrcColor,
        DstColor,
        OneMinusDstColor,
        SrcAlpha,
        OneMinusSrcAlpha,
        DstAlpha,
        OneMinusDstAlpha,
        ConstantColor,
        OneMinusConstantColor,
        ConstantAlpha,
        OneMinusConstantAlpha,
        SrcAlphaSaturate,
        Src1Color,
        OneMinusSrc1Color,
        Src1Alpha,
        OneMinusSrc1Alpha
    };

    enum BlendOp {
        Add,
        Subtract,
        ReverseSubtract,
        Min,
        Max
    };

    struct TargetBlend {
        ColorMask colorWrite = ColorMask(0xF); // R | G | B | A
        bool enable = false;
        BlendFactor srcColor = One;
        BlendFactor dstColor = OneMinusSrcAlpha;
        BlendOp opColor = Add;
        BlendFactor srcAlpha = One;
        BlendFactor dstAlpha = OneMinusSrcAlpha;
        BlendOp opAlpha = Add;
    };

    enum CompareOp {
        Never,
        Less,
        Equal,
        LessOrEqual,
        Greater,
        NotEqual,
        GreaterOrEqual,
        Always
    };

    enum StencilOp {
        StencilZero,
        Keep,
        Replace,
        IncrementAndClamp,
        DecrementAndClamp,
        Invert,
        IncrementAndWrap,
        DecrementAndWrap
    };

    struct StencilOpState {
        StencilOp failOp = Keep;
        StencilOp depthFailOp = Keep;
        StencilOp passOp = Keep;
        CompareOp compareOp = Always;
    };

Laszlo Agocs's avatar
Laszlo Agocs committed
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 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
    Flags flags() const { return m_flags; }
    void setFlags(Flags f) { m_flags = f; }

    Topology topology() const { return m_topology; }
    void setTopology(Topology t) { m_topology = t; }

    CullMode cullMode() const { return m_cullMode; }
    void setCullMode(CullMode mode) { m_cullMode = mode; }

    FrontFace frontFace() const { return m_frontFace; }
    void setFrontFace(FrontFace f) { m_frontFace = f; }

    QVector<TargetBlend> targetBlends() const { return m_targetBlends; }
    void setTargetBlends(const QVector<TargetBlend> &blends) { m_targetBlends = blends; }

    bool hasDepthTest() const { return m_depthTest; }
    void setDepthTest(bool enable) { m_depthTest = enable; }

    bool hasDepthWrite() const { return m_depthWrite; }
    void setDepthWrite(bool enable) { m_depthWrite = enable; }

    CompareOp depthOp() const { return m_depthOp; }
    void setDepthOp(CompareOp op) { m_depthOp = op; }

    bool hasStencilTest() const { return m_stencilTest; }
    void setStencilTest(bool enable) { m_stencilTest = enable; }

    StencilOpState stencilFront() const { return m_stencilFront; }
    void setStencilFront(const StencilOpState &state) { m_stencilFront = state; }

    StencilOpState stencilBack() const { return m_stencilBack; }
    void setStencilBack(const StencilOpState &state) { m_stencilBack = state; }

    quint32 stencilReadMask() const { return m_stencilReadMask; }
    void setStencilReadMask(quint32 mask) { m_stencilReadMask = mask; }

    quint32 stencilWriteMask() const { return m_stencilWriteMask; }
    void setStencilWriteMask(quint32 mask) { m_stencilWriteMask = mask; }

    int sampleCount() const { return m_sampleCount; }
    void setSampleCount(int s) { m_sampleCount = s; }

    QVector<QRhiGraphicsShaderStage> shaderStages() const { return m_shaderStages; }
    void setShaderStages(const QVector<QRhiGraphicsShaderStage> &stages) { m_shaderStages = stages; }

    QRhiVertexInputLayout vertexInputLayout() const { return m_vertexInputLayout; }
    void setVertexInputLayout(const QRhiVertexInputLayout &layout) { m_vertexInputLayout = layout; }

    QRhiShaderResourceBindings *shaderResourceBindings() const { return m_shaderResourceBindings; }
    void setShaderResourceBindings(QRhiShaderResourceBindings *srb) { m_shaderResourceBindings = srb; }

835 836
    QRhiRenderPassDescriptor *renderPassDescriptor() const { return m_renderPassDesc; }
    void setRenderPassDescriptor(QRhiRenderPassDescriptor *desc) { m_renderPassDesc = desc; }
837 838 839 840 841

    virtual bool build() = 0;

protected:
    QRhiGraphicsPipeline(QRhiImplementation *rhi);
Laszlo Agocs's avatar
Laszlo Agocs committed
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
    Flags m_flags;
    Topology m_topology = Triangles;
    CullMode m_cullMode = None;
    FrontFace m_frontFace = CCW;
    QVector<TargetBlend> m_targetBlends; // no blend when empty
    bool m_depthTest = false;
    bool m_depthWrite = false;
    CompareOp m_depthOp = Less;
    bool m_stencilTest = false;
    StencilOpState m_stencilFront;
    StencilOpState m_stencilBack;
    quint32 m_stencilReadMask = 0xFF; // applies to both faces
    quint32 m_stencilWriteMask = 0xFF; // applies to both faces
    int m_sampleCount = 1; // MSAA, swapchain+depthstencil must match
    QVector<QRhiGraphicsShaderStage> m_shaderStages;
    QRhiVertexInputLayout m_vertexInputLayout;
    QRhiShaderResourceBindings *m_shaderResourceBindings = nullptr; // must be built by the time ps' build() is called
859
    QRhiRenderPassDescriptor *m_renderPassDesc = nullptr;
Laszlo Agocs's avatar
Laszlo Agocs committed
860
    void *m_reserved;
861 862 863 864 865 866 867 868 869
};

Q_DECLARE_OPERATORS_FOR_FLAGS(QRhiGraphicsPipeline::Flags)
Q_DECLARE_OPERATORS_FOR_FLAGS(QRhiGraphicsPipeline::ColorMask)
Q_DECLARE_TYPEINFO(QRhiGraphicsPipeline::TargetBlend, Q_MOVABLE_TYPE);

class Q_RHI_EXPORT QRhiSwapChain : public QRhiResource
{
public:
870
    enum Flag {
871
        SurfaceHasPreMulAlpha = 1 << 0,
872
        SurfaceHasNonPreMulAlpha = 1 << 1,
873
        sRGB = 1 << 2,
874
        UsedAsTransferSource = 1 << 3, // will be read back
Laszlo Agocs's avatar
Laszlo Agocs committed
875
        NoVSync = 1 << 4 // may be implementation specific what this results in
876
    };
877
    Q_DECLARE_FLAGS(Flags, Flag)
878

Laszlo Agocs's avatar
Laszlo Agocs committed
879 880 881
    QWindow *window() const { return m_window; }
    void setWindow(QWindow *window) { m_window = window; }

882 883
    Flags flags() const { return m_flags; }
    void setFlags(Flags f) { m_flags = f; }
Laszlo Agocs's avatar
Laszlo Agocs committed
884 885 886 887 888 889 890

    QRhiRenderBuffer *depthStencil() const { return m_depthStencil; }
    void setDepthStencil(QRhiRenderBuffer *ds) { m_depthStencil = ds; }

    int sampleCount() const { return m_sampleCount; }
    void setSampleCount(int samples) { m_sampleCount = samples; }

891 892
    QRhiRenderPassDescriptor *renderPassDescriptor() const { return m_renderPassDesc; }
    void setRenderPassDescriptor(QRhiRenderPassDescriptor *desc) { m_renderPassDesc = desc; }
Laszlo Agocs's avatar
Laszlo Agocs committed
893

Laszlo Agocs's avatar
Laszlo Agocs committed
894 895 896 897 898
    // Alternatively, integrate with an existing swapchain, f.ex.
    // QVulkanWindow. Other settings have no effect when this is set.
    QObject *target() const { return m_target; }
    void setTarget(QObject *obj) { m_target = obj; }

899
    // Returns the size with which the swapchain was last successfully built.
900
    // Use this to decide if buildOrResize() needs to be called again: if
901 902 903 904
    // currentPixelSize() != surfacePixelSize() then the swapchain needs to
    // be resized.
    QSize currentPixelSize() const { return m_currentPixelSize; }

905 906 907
    virtual QRhiCommandBuffer *currentFrameCommandBuffer() = 0;
    virtual QRhiRenderTarget *currentFrameRenderTarget() = 0;

908 909 910 911 912 913 914 915 916 917 918 919
    // The size of the window's associated surface or layer. Do not assume this
    // is the same as size() * devicePixelRatio()! Can be called before
    // buildOrResize() (with window 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.
    virtual QSize surfacePixelSize() = 0;

    // To be called before build() with relevant parameters like depthStencil
    // and sampleCount set. As an exception to the common rules, m_depthStencil
    // is not required to be built yet. Note setRenderPassDescriptor(), that
    // must still be called afterwards (but before buildOrResize()).
920 921 922 923 924 925 926 927
    virtual QRhiRenderPassDescriptor *newCompatibleRenderPassDescriptor() = 0;

    // As the name suggests, this is slightly different from the typical
    // build+release pattern: buildOrResize - buildOrResize is not the same as
    // buildOrResize - release - buildOrResize. A swapchain is often able to,
    // depending on the underlying APIs, accomodate changed output sizes in a
    // manner that is more efficient than a full destroy - create. So use the
    // former when a window is resized.
Laszlo Agocs's avatar
Laszlo Agocs committed
928
    virtual bool buildOrResize() = 0;
929 930 931

protected:
    QRhiSwapChain(QRhiImplementation *rhi);
Laszlo Agocs's avatar
Laszlo Agocs committed
932
    QWindow *m_window = nullptr;
933
    Flags m_flags;
Laszlo Agocs's avatar
Laszlo Agocs committed
934 935
    QRhiRenderBuffer *m_depthStencil = nullptr;
    int m_sampleCount = 1;
936
    QRhiRenderPassDescriptor *m_renderPassDesc = nullptr;
Laszlo Agocs's avatar
Laszlo Agocs committed
937
    QObject *m_target = nullptr;
938
    QSize m_currentPixelSize;
Laszlo Agocs's avatar
Laszlo Agocs committed
939
    void *m_reserved;
940 941
};

942
Q_DECLARE_OPERATORS_FOR_FLAGS(QRhiSwapChain::Flags)
943

944 945 946 947 948 949 950 951
class Q_RHI_EXPORT QRhiCommandBuffer : public QRhiResource
{
public:
    enum IndexFormat {
        IndexUInt16,
        IndexUInt32
    };

952 953
    // Sometimes committing the updates is necessary without starting a render
    // pass. Not often needed, updates should typically be passed to beginPass
954
    // (or endPass, in case of readbacks) instead. Cannot be called inside a pass.
955 956
    void resourceUpdate(QRhiResourceUpdateBatch *resourceUpdates);

957 958 959 960
    void beginPass(QRhiRenderTarget *rt,
                   const QRhiColorClearValue &colorClearValue, // ignored when rt has PreserveColorContents
                   const QRhiDepthStencilClearValue &depthStencilClearValue, // ignored when no ds attachment
                   QRhiResourceUpdateBatch *resourceUpdates = nullptr);
961
    void endPass(QRhiResourceUpdateBatch *resourceUpdates = nullptr);
962

963 964 965 966 967 968 969
    // The set* and 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. Otherwise, unspecified
    // issues may arise, depending on the backend.
    //
    // Do not assume that any bindings or states persist between passes.

970 971
    // When specified, srb can be different from ps' srb but the layouts must
    // match. Basic tracking is included: no command is added to the cb when
972 973 974 975 976 977
    // the pipeline or srb are the same as in the last call in the same frame;
    // resource bindings are updated automatically at this point if a
    // referenced buffer, texture, etc. has a new underlying native resource
    // (due to rebuilding since the creation of the srb) - hence no need to
    // rebuild the srb in case, for example, a QRhiBuffer is "resized" via
    // setSize()+build().
978 979 980
    void setGraphicsPipeline(QRhiGraphicsPipeline *ps,
                             QRhiShaderResourceBindings *srb = nullptr);

981
    // Some level of smartness can be expected from most backends: superfluous
982
    // vertex input and index changes in the same pass are ignored automatically.
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
    using VertexInput = QPair<QRhiBuffer *, quint32>; // buffer, offset
    void setVertexInput(int startBinding, const QVector<VertexInput> &bindings,
                        QRhiBuffer *indexBuf = nullptr, quint32 indexOffset = 0,
                        IndexFormat indexFormat = IndexUInt16);

    void setViewport(const QRhiViewport &viewport);
    void setScissor(const QRhiScissor &scissor);
    void setBlendConstants(const QVector4D &c);
    void setStencilRef(quint32 refValue);

    void draw(quint32 vertexCount,
              quint32 instanceCount = 1,
              quint32 firstVertex = 0,
              quint32 firstInstance = 0);

    // final offset (indexOffset + firstIndex * n) must be 4 byte aligned with some backends
    void drawIndexed(quint32 indexCount,
                     quint32 instanceCount = 1,
                     quint32 firstIndex = 0,
                     qint32 vertexOffset = 0,
                     quint32 firstInstance = 0);

1005
    // Ignored when DebugMarkers are not supported or EnableDebugMarkers is not set.
1006
    // debugMarkBegin/End can be called both inside and outside a pass.
1007 1008 1009 1010 1011 1012
    void debugMarkBegin(const QByteArray &name);
    void debugMarkEnd();
    // With some backends debugMarkMsg is only supported inside a pass and is
    // ignored when called outside a begin/endPass.
    void debugMarkMsg(const QByteArray &msg);

1013 1014 1015 1016 1017 1018 1019
protected:
    QRhiCommandBuffer(QRhiImplementation *rhi);
    void *m_reserved;
};

struct Q_RHI_EXPORT QRhiReadbackResult
{
1020
    /*
1021 1022 1023
      When doing a readback after a pass inside a begin-endFrame (not
      offscreen), the data may only be available in a future frame. Hence the
      completed callback:
1024
          beginFrame(sc);
1025
          beginPass
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
          ...
          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);
                    ...
              }
              delete rbResult;
          };
1038
          u = nextResourceUpdateBatch();
1039
          QRhiReadbackDescription rb; // no texture -> backbuffer
1040
          u->readBackTexture(rb, rbResult);
1041
          endPass(u);
1042 1043
          endFrame(sc);
     */
1044 1045 1046 1047 1048
    std::function<void()> completed = nullptr;
    QRhiTexture::Format format;
    QSize pixelSize;
    QByteArray data;
}; // non-movable due to the std::function
1049

1050 1051 1052
class Q_RHI_EXPORT QRhiResourceUpdateBatch // sort of a command buffer for copy type of operations
{
public:
1053 1054 1055 1056 1057 1058
    enum TexturePrepareFlag {
        TextureRead = 1 << 0,
        TextureWrite = 1 << 1
    };
    Q_DECLARE_FLAGS(TexturePrepareFlags, TexturePrepareFlag)

1059 1060 1061 1062
    ~QRhiResourceUpdateBatch();
    // Puts the batch back to the pool without any processing.
    void release();

1063 1064 1065 1066 1067 1068
    // Applications do not have to defer all upload preparation to the first
    // frame: an update batch can be prepared in advance during initialization,
    // and afterwards, if needed, merged into another that is then submitted to
    // beginPass(). (nb the one we merged from must be release()'d manually)
    void merge(QRhiResourceUpdateBatch *other);

1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
    // None of these execute anything, processing is deferred. What exactly
    // then happens underneath is hidden from the applications. The caller is
    // free to destroy or reuse the data or image right after returning from
    // the functions.
    //
    // Note: Updates involving host writes - typically the dynamic buffer
    // updates - 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.
    //
1079
    void updateDynamicBuffer(QRhiBuffer *buf, int offset, int size, const void *data);
1080
    void uploadStaticBuffer(QRhiBuffer *buf, int offset, int size, const void *data);
1081
    void uploadStaticBuffer(QRhiBuffer *buf, const void *data);
Laszlo Agocs's avatar
Laszlo Agocs committed
1082
    void uploadTexture(QRhiTexture *tex, const QRhiTextureUploadDescription &desc);
1083
    void uploadTexture(QRhiTexture *tex, const QImage &image); // shortcut
1084
    void copyTexture(QRhiTexture *dst, QRhiTexture *src, const QRhiTextureCopyDescription &desc = QRhiTextureCopyDescription());
1085
    void readBackTexture(const QRhiReadbackDescription &rb, QRhiReadbackResult *result);
1086
    void generateMips(QRhiTexture *tex);
1087

1088 1089 1090 1091
    // This is not normally needed, textures that have an upload or are used
    // with a TextureRenderTarget will be fine without it. May be more relevant later.
    void prepareTextureForUse(QRhiTexture *tex, TexturePrepareFlags flags);

1092 1093 1094 1095 1096 1097 1098 1099
private:
    QRhiResourceUpdateBatch(QRhiImplementation *rhi);
    Q_DISABLE_COPY(QRhiResourceUpdateBatch)
    QRhiResourceUpdateBatchPrivate *d;
    friend struct QRhiResourceUpdateBatchPrivate;
    friend class QRhi;
};

1100 1101
Q_DECLARE_OPERATORS_FOR_FLAGS(QRhiResourceUpdateBatch::TexturePrepareFlags)

1102 1103 1104 1105
struct Q_RHI_EXPORT QRhiInitParams
{
};

1106 1107
// A QRhi instance can be created and used on any thread but all usage must be
// limited to that one single thread.
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
class Q_RHI_EXPORT QRhi
{
public:
    enum Implementation {
        Vulkan,
        OpenGLES2,
        D3D11,
        Metal
    };

1118
    enum Flag {
1119 1120
        EnableProfiling = 1 << 0,
        EnableDebugMarkers = 1 << 1
1121 1122 1123
    };
    Q_DECLARE_FLAGS(Flags, Flag)

1124 1125 1126 1127 1128 1129 1130
    enum FrameOpResult {
        FrameOpSuccess = 0,
        FrameOpError,
        FrameOpSwapChainOutOfDate,
        FrameOpDeviceLost
    };

1131 1132
    enum Feature {
        MultisampleTexture = 1,
1133
        MultisampleRenderBuffer,
1134
        DebugMarkers,
1135 1136 1137
        Timestamps,
        Instancing,
        CustomInstanceStepRate
1138 1139
    };

1140 1141 1142 1143 1144
    enum ResourceSizeLimit {
        TextureSizeMin = 1,
        TextureSizeMax
    };

1145 1146
    ~QRhi();

1147
    static QRhi *create(Implementation impl, QRhiInitParams *params, Flags flags = Flags());
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168

    /*
       The underlying graphics resources are created when calling build() and
       put on the release queue by release() (so this is safe even when the
       resource is used by the still executing/pending frame(s)).

       The QRhi* instance itself is not destroyed by the release and it is safe
       to destroy it right away after calling release().

       Changing any value needs explicit release and rebuilding of the
       underlying resource before it can take effect.

       res->build(); <change something>; res->release(); res->build(); ...
       is therefore perfectly valid and can be used to recreate things (when
       buffer or texture size changes f.ex.)

       In addition, just doing res->build(); ...; res->build() is valid too and
       has the same effect due to an implicit release() call made by build()
       when invoked on an object with valid resources underneath.
     */

1169 1170
    QRhiGraphicsPipeline *newGraphicsPipeline();
    QRhiShaderResourceBindings *newShaderResourceBindings();
1171 1172 1173 1174 1175 1176 1177 1178

    // Buffers are immutable like other resources but the underlying data can
    // change. (its size cannot) Having multiple frames in flight is handled
    // transparently, with multiple allocations, recording updates, etc.
    // internally. The underlying memory type may differ for static and dynamic
    // buffers. For best performance, static buffers may be copied to device
    // local (not necessarily host visible) memory via a staging (host visible)
    // buffer. Hence separate update-dynamic and upload-static operations.
1179 1180 1181
    QRhiBuffer *newBuffer(QRhiBuffer::Type type,
                          QRhiBuffer::UsageFlags usage,
                          int size);
1182 1183

    // To be used for depth-stencil when no access is needed afterwards.
Laszlo Agocs's avatar
Laszlo Agocs committed
1184 1185
    // Transient image, backed by lazily allocated memory (on Vulkan at least,
    // ideal for tiled GPUs). May also be a dummy internally depending on the
Laszlo Agocs's avatar
Laszlo Agocs committed
1186
    // backend and the flags (OpenGL, where the winsys interface provides the
Laszlo Agocs's avatar
Laszlo Agocs committed
1187
    // depth-stencil buffer via the window surface).
1188 1189
    //
    // Color is also supported. With some gfx apis (GL) this is different from
1190 1191 1192
    // textures. (cannot be sampled, but can be rendered to) This becomes
    // important when doing msaa offscreen and the gfx api has no multisample
    // textures.
1193 1194 1195
    QRhiRenderBuffer *newRenderBuffer(QRhiRenderBuffer::Type type,
                                      const QSize &pixelSize,
                                      int sampleCount = 1,
Laszlo Agocs's avatar
Laszlo Agocs committed
1196
                                      QRhiRenderBuffer::Flags flags = QRhiRenderBuffer::Flags());
1197

1198 1199
    QRhiTexture *newTexture(QRhiTexture::Format format,
                            const QSize &pixelSize,
Laszlo Agocs's avatar
Laszlo Agocs committed
1200
                            int sampleCount = 1,
1201
                            QRhiTexture::Flags flags = QRhiTexture::Flags());
1202

1203 1204 1205
    QRhiSampler *newSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter,
                            QRhiSampler::Filter mipmapMode,
                            QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w = QRhiSampler::ClampToEdge);
1206

1207 1208
    QRhiTextureRenderTarget *newTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc,
                                                    QRhiTextureRenderTarget::Flags flags = QRhiTextureRenderTarget::Flags());
1209 1210

    /*
1211
      Rendering to a QWindow (must be Vulkan/Metal/OpenGLSurface as appropriate):
1212
        Create a swapchain.
1213 1214
        Call buildOrResize() on the swapchain whenever the size is different than before.
        Call release() on the swapchain on QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed.
1215 1216
        Then on every frame:
           beginFrame(sc);
Laszlo Agocs's avatar
Laszlo Agocs committed
1217 1218
           updates = nextResourceUpdateBatch();
           updates->...
1219 1220
           QRhiCommandBuffer *cb = sc->currentFrameCommandBuffer();
           cb->beginPass(sc->currentFrameRenderTarget(), clearValues, updates);
1221
           ...
1222
           cb->endPass();
1223 1224
           endFrame(sc); // this queues the Present, begin/endFrame manages double buffering internally
     */
1225
    QRhiSwapChain *newSwapChain();
1226 1227 1228
    FrameOpResult beginFrame(QRhiSwapChain *swapChain);
    FrameOpResult endFrame(QRhiSwapChain *swapChain);

1229
    /*
1230 1231 1232 1233
      Rendering without a swapchain is possible as well. The typical use case
      is to use it in completely offscreen applications, e.g. to generate image
      sequences by rendering and reading back without ever showing a window.
      Usage in on-screen applications (so beginFrame, endFrame,
1234 1235 1236 1237
      beginOffscreenFrame, endOffscreenFrame, beginFrame, ...) is possible too
      but it does reduce parallelism (offscreen frames do not let the CPU -
      potentially - generate another frame while the GPU is still processing
      the previous one) so should be done only infrequently.
1238
          QRhiReadbackResult rbResult;
1239 1240
          QRhiCommandBuffer *cb; // not owned
          beginOffscreenFrame(&cb);
1241 1242 1243
          beginPass
          ...
          u = nextResourceUpdateBatch();
1244
          u->readBackTexture(rb, &rbResult);
1245
          endPass(u);
1246
          endOffscreenFrame();
1247
          // image data available in rbResult
1248 1249
     */
    FrameOpResult beginOffscreenFrame(QRhiCommandBuffer **cb);
1250 1251 1252
    FrameOpResult endOffscreenFrame();

    // Waits for any work on the graphics queue (where applicable) to complete,
1253 1254 1255 1256
    // then executes all deferred operations, like completing readbacks and
    // resource releases. Can be called inside and outside of a frame, but not
    // inside a pass. Inside a frame it implies submitting any work on the
    // command buffer.
1257
    QRhi::FrameOpResult finish();
1258

1259 1260 1261
    // Returns an instance to which updates can be queued. Batch instances are
    // pooled and never owned by the application. An instance is returned to
    // the pool after a beginPass() processes it or when it is "canceled" by
Laszlo Agocs's avatar
Laszlo Agocs committed
1262 1263
    // calling release(). Can be called outside begin-endFrame as well since
    // a batch instance just collects data on its own.
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    QRhiResourceUpdateBatch *nextResourceUpdateBatch();

    QVector<int> supportedSampleCounts() const;

    int ubufAlignment() const;
    int ubufAligned(int v) const;

    int mipLevelsForSize(const QSize &size) const;
    QSize sizeForMipLevel(int mipLevel, const QSize &baseLevelSize) const;

    bool isYUpInFramebuffer() const;

    // Make Y up and allow using 0..1 as the depth range. This lets
    // applications keep using OpenGL-targeted vertex data and perspective
    // matrices regardless of the backend. (by passing this_matrix * mvp,
    // instead of just mvp, to their vertex shaders)
    QMatrix4x4 clipSpaceCorrMatrix() const;

1282
    bool isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags = QRhiTexture::Flags()) const;
1283
    bool isFeatureSupported(QRhi::Feature feature) const;
1284
    int resourceSizeLimit(ResourceSizeLimit limit) const;
1285

1286 1287
    // Returns a ptr to a QRhi<backend>NativeHandles struct.
    // Ownership of the native objects is not transfered.
1288 1289
    const QRhiNativeHandles *nativeHandles();

1290
    QRhiProfiler *profiler();
1291

1292 1293 1294 1295 1296 1297 1298 1299
protected:
    QRhi();

private:
    Q_DISABLE_COPY(QRhi)
    QRhiImplementation *d = nullptr;
};

1300 1301
Q_DECLARE_OPERATORS_FOR_FLAGS(QRhi::Flags)

1302 1303 1304
QT_END_NAMESPACE

#endif